monoban 1.5.1 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +4 -2
  2. package/dist/index.mjs +1632 -988
  3. package/package.json +7 -7
package/dist/index.mjs CHANGED
@@ -1,14 +1,15 @@
1
1
  #!/usr/bin/env node
2
2
  import { homedir, hostname, tmpdir } from "node:os";
3
- import path, { dirname, join, resolve, sep } from "node:path";
4
- import { mkdir, mkdtemp, open, readFile, realpath, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
3
+ import path, { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path";
4
+ import { access, constants, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
5
5
  import childProcess, { execFile, spawn, spawnSync } from "node:child_process";
6
6
  import { EventEmitter } from "node:events";
7
- import fs, { existsSync, realpathSync } from "node:fs";
7
+ import fs, { existsSync, readdirSync, realpathSync } from "node:fs";
8
8
  import process$1 from "node:process";
9
9
  import { stripVTControlCharacters } from "node:util";
10
10
  import { createInterface } from "node:readline/promises";
11
11
  import { createHash, randomBytes } from "node:crypto";
12
+ import { pathToFileURL } from "node:url";
12
13
  import { createServer } from "node:http";
13
14
  import { createInterface as createInterface$1 } from "node:readline";
14
15
  /** Where the CLI keeps its files: $MONOBAN_CONFIG_DIR, else $XDG_CONFIG_HOME/monoban, else ~/.config/monoban. */
@@ -64,17 +65,20 @@ const AGENTS$1 = {
64
65
  agentpipe: {
65
66
  label: "agentpipe",
66
67
  description: "Plans, implements and verifies in steps; moves and comments on the task itself.",
67
- options: ["budgetUsd", "autonomous"]
68
+ options: ["budgetUsd", "autonomous"],
69
+ install: "monoban agentpipe install"
68
70
  },
69
71
  claude: {
70
72
  label: "Claude Code",
71
73
  description: "claude -p in auto mode: a classifier reviews what it does, and nothing waits for you.",
72
- options: ["budgetUsd", "model"]
74
+ options: ["budgetUsd", "model"],
75
+ install: "npm install -g @anthropic-ai/claude-code"
73
76
  },
74
77
  codex: {
75
78
  label: "Codex",
76
79
  description: "codex exec in its sandbox: it writes in the folder, with the network off unless you say.",
77
- options: ["model", "access"]
80
+ options: ["model", "access"],
81
+ install: "npm install -g @openai/codex"
78
82
  }
79
83
  };
80
84
  /** How Codex may reach outside the folder: its sandbox, the sandbox with the network, or no sandbox. */
@@ -104,7 +108,7 @@ function unsupportedOption(agent, options) {
104
108
  return null;
105
109
  }
106
110
  //#endregion
107
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/util.js
111
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/util.js
108
112
  function getEnumValues(entries) {
109
113
  const numericValues = Object.values(entries).filter((v) => typeof v === "number");
110
114
  return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
@@ -411,6 +415,17 @@ function prefixIssues(path, issues) {
411
415
  function unwrapMessage(message) {
412
416
  return typeof message === "string" ? message : message?.message;
413
417
  }
418
+ /** The leading size checks of `defChecks` that set an upper bound, each paired with it. */
419
+ function sizeCaps(defChecks) {
420
+ const caps = [];
421
+ for (const ch of defChecks ?? []) {
422
+ const d = ch._zod.def;
423
+ if (!/_(length|size)$|_equals$/.test(d.check)) break;
424
+ const max = d.maximum ?? d.length ?? d.size;
425
+ if (max >= 0) caps.push([max, ch]);
426
+ }
427
+ return caps;
428
+ }
414
429
  function attachSchema(issues, start, inst) {
415
430
  var _a;
416
431
  for (let i = start; i < issues.length; i++) (_a = issues[i]).schema ?? (_a.schema = inst);
@@ -627,7 +642,7 @@ function constantCatch(value) {
627
642
  return fn;
628
643
  }
629
644
  //#endregion
630
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/core.js
645
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/core.js
631
646
  var _a$1;
632
647
  const _zodDesc = {
633
648
  value: void 0,
@@ -733,7 +748,7 @@ function config(newConfig) {
733
748
  return globalConfig;
734
749
  }
735
750
  //#endregion
736
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/errors.js
751
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/errors.js
737
752
  function _getMessage() {
738
753
  const internals = this._zod;
739
754
  internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2));
@@ -849,7 +864,7 @@ function formatError(error, mapper = (issue) => issue.message) {
849
864
  return fieldErrors;
850
865
  }
851
866
  //#endregion
852
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/parse.js
867
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/parse.js
853
868
  function finalizeParams(callee, params) {
854
869
  return {
855
870
  callee: params?.callee ?? callee,
@@ -1052,7 +1067,7 @@ const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
1052
1067
  return _safeParseAsync(_Err)(schema, value, _ctx);
1053
1068
  };
1054
1069
  //#endregion
1055
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/regexes.js
1070
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/regexes.js
1056
1071
  /**
1057
1072
  * @deprecated CUID v1 is deprecated by its authors due to information leakage
1058
1073
  * (timestamps embedded in the id). Use {@link cuid2} instead.
@@ -1125,7 +1140,7 @@ const _null$2 = /^null$/i;
1125
1140
  const lowercase = /^[^A-Z]*$/;
1126
1141
  const uppercase = /^[^a-z]*$/;
1127
1142
  //#endregion
1128
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/checks.js
1143
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/checks.js
1129
1144
  const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => {
1130
1145
  var _a;
1131
1146
  inst._zod ?? (inst._zod = {});
@@ -1421,7 +1436,7 @@ const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (ins
1421
1436
  };
1422
1437
  });
1423
1438
  //#endregion
1424
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/doc.js
1439
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/doc.js
1425
1440
  var Doc = class {
1426
1441
  constructor(args = [], closed = {}) {
1427
1442
  this.content = [];
@@ -1455,14 +1470,14 @@ var Doc = class {
1455
1470
  }
1456
1471
  };
1457
1472
  //#endregion
1458
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/versions.js
1473
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/versions.js
1459
1474
  const version = {
1460
1475
  major: 4,
1461
1476
  minor: 6,
1462
- patch: 5
1477
+ patch: 7
1463
1478
  };
1464
1479
  //#endregion
1465
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/schemas.js
1480
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/schemas.js
1466
1481
  const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => {
1467
1482
  var _a;
1468
1483
  inst ?? (inst = {});
@@ -1975,6 +1990,26 @@ const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => {
1975
1990
  return payload;
1976
1991
  };
1977
1992
  });
1993
+ function capSize(inst, size) {
1994
+ const caps = sizeCaps(inst._zod.def.checks);
1995
+ if (!caps.length) return;
1996
+ const cap = Math.min(...caps.map((c) => c[0]));
1997
+ const parse = inst._zod.parse;
1998
+ inst._zod.parse = (payload, ctx) => {
1999
+ const n = size(payload.value);
2000
+ if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") {
2001
+ for (const [max, ch] of sizeCaps(inst._zod.def.checks)) if (n > max && ch._zod.def.when(payload)) {
2002
+ const start = payload.issues.length;
2003
+ ch._zod.check(payload);
2004
+ payload.issues[start].continue = false;
2005
+ attachSchema(payload.issues, start, inst);
2006
+ return payload;
2007
+ }
2008
+ }
2009
+ return parse(payload, ctx);
2010
+ };
2011
+ }
2012
+ const arraySize = (input) => Array.isArray(input) ? input.length : -1;
1978
2013
  function handleArrayResult(result, final, index) {
1979
2014
  if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues));
1980
2015
  final.value[index] = result.value;
@@ -2012,6 +2047,7 @@ const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => {
2012
2047
  if (proms.length) return Promise.all(proms).then(() => payload);
2013
2048
  return payload;
2014
2049
  };
2050
+ capSize(inst, arraySize);
2015
2051
  });
2016
2052
  function handlePropertyResult(result, final, key, input, optin, optout) {
2017
2053
  const isPresent = key in input;
@@ -2120,7 +2156,7 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
2120
2156
  }
2121
2157
  return propValues;
2122
2158
  });
2123
- const isObject$2 = isObject;
2159
+ const isObject$1 = isObject;
2124
2160
  const catchall = def.catchall;
2125
2161
  let value;
2126
2162
  const memo = globalConfig.memoizer;
@@ -2128,7 +2164,7 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
2128
2164
  inst._zod.parse = (payload, ctx) => {
2129
2165
  value ?? (value = _normalized.value);
2130
2166
  const input = payload.value;
2131
- if (!isObject$2(input)) {
2167
+ if (!isObject$1(input)) {
2132
2168
  payload.issues.push({
2133
2169
  expected: "object",
2134
2170
  code: "invalid_type",
@@ -2258,7 +2294,7 @@ const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) =>
2258
2294
  return doc.compile();
2259
2295
  };
2260
2296
  let fastpass;
2261
- const isObject$1 = isObject;
2297
+ const isObject$2 = isObject;
2262
2298
  const jit = !globalConfig.jitless;
2263
2299
  const fastEnabled = jit && allowsEval.value;
2264
2300
  const catchall = def.catchall;
@@ -2266,7 +2302,7 @@ const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) =>
2266
2302
  inst._zod.parse = (payload, ctx) => {
2267
2303
  value ?? (value = _normalized.value);
2268
2304
  const input = payload.value;
2269
- if (!isObject$1(input)) {
2305
+ if (!isObject$2(input)) {
2270
2306
  payload.issues.push({
2271
2307
  expected: "object",
2272
2308
  code: "invalid_type",
@@ -2912,7 +2948,7 @@ function handleRefineResult(result, payload, input, inst) {
2912
2948
  }
2913
2949
  }
2914
2950
  //#endregion
2915
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/memoizer.js
2951
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/memoizer.js
2916
2952
  var $ZodCyclicError = class extends Error {
2917
2953
  constructor() {
2918
2954
  super(`Cannot parse a reference cycle that closes through a transform`);
@@ -3165,7 +3201,7 @@ function isBackEdge(ctx, value) {
3165
3201
  return backEdges !== void 0 && isRef(value) && backEdges.has(value);
3166
3202
  }
3167
3203
  //#endregion
3168
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/locales/en.js
3204
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/locales/en.js
3169
3205
  const error = () => {
3170
3206
  const Sizable = {
3171
3207
  string: {
@@ -3273,7 +3309,7 @@ function en_default() {
3273
3309
  return { localeError: error() };
3274
3310
  }
3275
3311
  //#endregion
3276
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/registries.js
3312
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/registries.js
3277
3313
  var _a;
3278
3314
  var $ZodRegistry = class {
3279
3315
  constructor() {
@@ -3320,7 +3356,7 @@ function registry() {
3320
3356
  (_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry());
3321
3357
  const globalRegistry = globalThis.__zod_globalRegistry;
3322
3358
  //#endregion
3323
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/api.js
3359
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/api.js
3324
3360
  function snapshotChecks(def) {
3325
3361
  if (def.checks) def.checks = [...def.checks];
3326
3362
  return def;
@@ -3845,7 +3881,7 @@ function _check(fn, params) {
3845
3881
  return ch;
3846
3882
  }
3847
3883
  //#endregion
3848
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/to-json-schema.js
3884
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/to-json-schema.js
3849
3885
  function assignProps(target, ...sources) {
3850
3886
  for (const source of sources) for (const key of Reflect.ownKeys(source)) if (Object.prototype.propertyIsEnumerable.call(source, key)) assignProp(target, key, source[key]);
3851
3887
  return target;
@@ -4289,7 +4325,7 @@ const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params)
4289
4325
  return finalize(ctx, schema);
4290
4326
  };
4291
4327
  //#endregion
4292
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/json-schema-processors.js
4328
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/core/json-schema-processors.js
4293
4329
  const narrowMin = (agg, key, value) => {
4294
4330
  if (agg[key] === void 0 || value > agg[key]) agg[key] = value;
4295
4331
  };
@@ -4744,7 +4780,7 @@ const optionalProcessor = (schema, ctx, _json, params) => {
4744
4780
  seen.ref = def.innerType;
4745
4781
  };
4746
4782
  //#endregion
4747
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/errors.js
4783
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/errors.js
4748
4784
  const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]);
4749
4785
  function _lazyMethod(proto, key, make) {
4750
4786
  Object.defineProperty(proto, key, {
@@ -4794,7 +4830,7 @@ const initializer = (inst, issues) => {
4794
4830
  };
4795
4831
  const ZodRealError = /*@__PURE__*/ $constructor("ZodError", initializer, void 0, { Parent: Error });
4796
4832
  //#endregion
4797
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/parse.js
4833
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/parse.js
4798
4834
  const parse$1 = /* @__PURE__ */ _parse(ZodRealError);
4799
4835
  const parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError);
4800
4836
  const safeParse = /* @__PURE__ */ _safeParse(ZodRealError);
@@ -4808,7 +4844,7 @@ const safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError);
4808
4844
  const safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
4809
4845
  const safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);
4810
4846
  //#endregion
4811
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/schemas.js
4847
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/schemas.js
4812
4848
  function _ensureDefaultLocale() {
4813
4849
  if (!globalConfig.localeError) config(en_default());
4814
4850
  }
@@ -5715,12 +5751,12 @@ function superRefine(fn, params) {
5715
5751
  return /* @__PURE__ */ _superRefine(fn, params);
5716
5752
  }
5717
5753
  //#endregion
5718
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/iso.js
5754
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/iso.js
5719
5755
  function datetime(params) {
5720
5756
  return /* @__PURE__ */ _isoDateTime(ZodISODateTime, params);
5721
5757
  }
5722
5758
  //#endregion
5723
- //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/coerce.js
5759
+ //#region ../../node_modules/.pnpm/zod@4.6.7/node_modules/zod/v4/classic/coerce.js
5724
5760
  function number(params) {
5725
5761
  return /* @__PURE__ */ _coercedNumber(ZodNumber, params);
5726
5762
  }
@@ -7989,7 +8025,7 @@ strictObject({ email: email().max(254).meta({ example: "ada@example.com" }) }).m
7989
8025
  //#endregion
7990
8026
  //#region src/version.ts
7991
8027
  /** This CLI's version, from package.json (set at build time by tsdown, and by vitest in tests). */
7992
- const VERSION = "1.5.1";
8028
+ const VERSION = "1.6.0";
7993
8029
  /** Sent as X-Monoban-Client, and shown in Devices & tokens. */
7994
8030
  const CLIENT = `cli/${VERSION}`;
7995
8031
  //#endregion
@@ -11123,7 +11159,7 @@ new Command();
11123
11159
  * token works once, and using it twice signs the CLI out). A lock older than `staleMs` is from a
11124
11160
  * process that died, and is taken over.
11125
11161
  */
11126
- async function withLock(path, fn, { staleMs = 3e4, timeoutMs = 45e3, sleep = wait$1 } = {}) {
11162
+ async function withLock(path, fn, { staleMs = 3e4, timeoutMs = 45e3, sleep = wait$1, busy = `Another monoban is still refreshing the sign-in (${path}). Try again.` } = {}) {
11127
11163
  await mkdir(dirname(path), {
11128
11164
  recursive: true,
11129
11165
  mode: 448
@@ -11137,7 +11173,7 @@ async function withLock(path, fn, { staleMs = 3e4, timeoutMs = 45e3, sleep = wai
11137
11173
  if (err.code !== "EEXIST") throw err;
11138
11174
  }
11139
11175
  if (await stat(path).then((s) => Date.now() - s.mtimeMs, () => 0) > staleMs) await rm(path, { force: true });
11140
- else if (Date.now() > deadline) throw new Error(`Another monoban is still refreshing the sign-in (${path}). Try again.`);
11176
+ else if (Date.now() > deadline) throw new Error(busy);
11141
11177
  else await sleep(100);
11142
11178
  }
11143
11179
  try {
@@ -11255,7 +11291,7 @@ function report(err, print, apiUrl) {
11255
11291
  return err.status === 404 ? EXIT.notFound : EXIT.error;
11256
11292
  }
11257
11293
  if (err instanceof CliError) {
11258
- print(err.message);
11294
+ if (err.message) print(err.message);
11259
11295
  return err.exitCode;
11260
11296
  }
11261
11297
  const cause = err instanceof TypeError ? err.cause : void 0;
@@ -11544,6 +11580,452 @@ const apis = (ctx) => ({
11544
11580
  public: publicApi(ctx.apiUrl, ctx.fetch),
11545
11581
  signedIn: signedInApi(ctx.apiUrl, ctx.session, ctx.fetch)
11546
11582
  });
11583
+ const RELEASES = `https://github.com/thiagodmont/homebrew-tap/releases`;
11584
+ //#endregion
11585
+ //#region src/agentpipe/pin.ts
11586
+ /**
11587
+ * The agentpipe this monoban release installs (`monoban agentpipe install`): its wheel and its dependencies, each
11588
+ * pinned with a hash, from agentpipe's release on the tap (thiagodmont/homebrew-tap, `agentpipe-vX.Y.Z`). A new
11589
+ * agentpipe comes with a new monoban: change these three lines (from the release's checksums.txt) and release.
11590
+ */
11591
+ const AGENTPIPE = {
11592
+ version: "0.2.0",
11593
+ wheelSha256: "3ae6d9a2d8d9c5fe5b866a447a78bd4888c0e658b5bab16e0dc26ff68e63364c",
11594
+ requirementsSha256: "5a5de7c5a55e2e0eff86a56661244b888a91551d36d69fbc01ee8ec5020f85b5"
11595
+ };
11596
+ const agentpipeWheel = (version) => `agentpipe-${version}-py3-none-any.whl`;
11597
+ const agentpipeRequirements = (version) => `agentpipe-${version}-requirements.txt`;
11598
+ const agentpipeAsset = (version, name) => `${RELEASES}/download/agentpipe-v${version}/${name}`;
11599
+ /**
11600
+ * The uv that installs it, when the machine has none: uv's own release archives, with the SHA-256s GitHub and
11601
+ * uv publish for them.
11602
+ */
11603
+ const UV = {
11604
+ version: "0.12.21",
11605
+ sha256: {
11606
+ "aarch64-apple-darwin": "b88bda573e566ef9bced66b155fe0408626fbbc053aee1c30ba686f0728c9447",
11607
+ "x86_64-apple-darwin": "2b336763b396ec6afa20c5a8b083538ca7402445b868311979d740a4344c17d8",
11608
+ "aarch64-unknown-linux-gnu": "030b69227b40af8c1981b7301793dc66e71ed3c796ea8688209dd268bd91ec51",
11609
+ "x86_64-unknown-linux-gnu": "23f02075b652bb1df64178cfae41b5caf160822e720e2663568f3f5d63bc52c0"
11610
+ }
11611
+ };
11612
+ const uvArchive = (target, version = UV.version) => `https://github.com/astral-sh/uv/releases/download/${version}/uv-${target}.tar.gz`;
11613
+ const UPGRADE = {
11614
+ brew: {
11615
+ how: "Homebrew",
11616
+ command: "brew upgrade monoban"
11617
+ },
11618
+ binary: {
11619
+ how: "a downloaded binary",
11620
+ command: `download it again: ${RELEASES}/latest`
11621
+ },
11622
+ npx: {
11623
+ how: "npx",
11624
+ command: "npx monoban@latest"
11625
+ },
11626
+ npm: {
11627
+ how: "npm",
11628
+ command: "npm install -g monoban@latest"
11629
+ },
11630
+ pnpm: {
11631
+ how: "pnpm",
11632
+ command: "pnpm add -g monoban@latest"
11633
+ },
11634
+ yarn: {
11635
+ how: "yarn",
11636
+ command: "yarn global add monoban@latest"
11637
+ },
11638
+ bun: {
11639
+ how: "bun",
11640
+ command: "bun add -g monoban@latest"
11641
+ }
11642
+ };
11643
+ /**
11644
+ * Told apart by where it runs from: a binary in a Homebrew Cellar, or the npm package under npx's
11645
+ * cache or a package manager's global folder (npm when it's none of those).
11646
+ */
11647
+ function installKind(where) {
11648
+ if (where.binary) return where.executable.includes("/Cellar/") ? "brew" : "binary";
11649
+ const script = where.script.replaceAll("\\", "/");
11650
+ if (script.includes("/_npx/")) return "npx";
11651
+ if (/\/\.?pnpm\//.test(script)) return "pnpm";
11652
+ if (script.includes("/.bun/")) return "bun";
11653
+ if (/\/(\.yarn|yarn\/global)\//.test(script)) return "yarn";
11654
+ return "npm";
11655
+ }
11656
+ const real = (path) => {
11657
+ try {
11658
+ return path ? realpathSync(path) : "";
11659
+ } catch {
11660
+ return path ?? "";
11661
+ }
11662
+ };
11663
+ /**
11664
+ * The command that runs this monoban, for a program it starts to call it back (MONOBAN_BIN): the binary itself,
11665
+ * or the npm package's script, which runs with the node on the PATH.
11666
+ */
11667
+ const selfCommand = () => {
11668
+ const command = process.argv[1];
11669
+ return command && isAbsolute(command) ? command : null;
11670
+ };
11671
+ /** This process's install. */
11672
+ const thisInstall = () => installKind({
11673
+ binary: false,
11674
+ executable: real(process.execPath),
11675
+ script: real(process.argv[1])
11676
+ });
11677
+ /** 1.2.10 > 1.2.9; a pre-release counts as its version. */
11678
+ function newer(a, b) {
11679
+ const parts = (v) => v.split(/[-+]/)[0]?.split(".").map(Number) ?? [];
11680
+ const [x, y] = [parts(a), parts(b)];
11681
+ for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0);
11682
+ return false;
11683
+ }
11684
+ /** The latest version on npm (Homebrew and the binaries ship the same releases), or null offline. */
11685
+ async function latestVersion(ctx) {
11686
+ try {
11687
+ const res = await ctx.fetch(new Request("https://registry.npmjs.org/monoban/latest", { signal: AbortSignal.timeout(3e3) }));
11688
+ if (!res.ok) return null;
11689
+ const { version } = await res.json();
11690
+ return typeof version === "string" ? version : null;
11691
+ } catch {
11692
+ return null;
11693
+ }
11694
+ }
11695
+ /** `monoban upgrade`: whether there's a newer version, and the command that installs it here. */
11696
+ async function upgrade(ctx, options, kind = thisInstall()) {
11697
+ const latest = await latestVersion(ctx);
11698
+ const { how, command } = UPGRADE[kind];
11699
+ const outdated = latest !== null && newer(latest, "1.6.0");
11700
+ if (options.json) {
11701
+ ctx.out(JSON.stringify({
11702
+ version: VERSION,
11703
+ latest,
11704
+ outdated,
11705
+ installedWith: kind,
11706
+ command
11707
+ }, null, 2));
11708
+ return;
11709
+ }
11710
+ if (latest === null) ctx.out(`You have monoban ${VERSION} (installed with ${how}). To get the latest: ${command}`);
11711
+ else if (outdated) ctx.out(`monoban ${latest} is out (you have ${VERSION}). To upgrade: ${command}`);
11712
+ else ctx.out(`monoban ${VERSION} is the latest.`);
11713
+ }
11714
+ //#endregion
11715
+ //#region src/agentpipe/install.ts
11716
+ /**
11717
+ * `monoban agentpipe install`: agentpipe, CLI only, in a folder of monoban's own, for `monoban runner` to run.
11718
+ *
11719
+ * <data dir>/agentpipe/versions/X.Y.Z a Python environment with agentpipe X.Y.Z (a venv can't be moved, so
11720
+ * each version is made where it stays)
11721
+ * <data dir>/agentpipe/current → versions/X.Y.Z, switched in one step once a version works
11722
+ * <data dir>/agentpipe/python, uv the Python 3.12 and the uv that made it, when the machine had no uv
11723
+ *
11724
+ * Every file is checked against a SHA-256 this monoban pins (agentpipe/pin.ts) before it's used: the wheel, its
11725
+ * requirements, and each dependency they name (`uv pip install --require-hashes`; `uv tool install` reads a
11726
+ * constraints file's versions but not its hashes).
11727
+ */
11728
+ /** Where monoban keeps what it installs: $MONOBAN_DATA_DIR, else $XDG_DATA_HOME/monoban, else ~/.local/share/monoban. */
11729
+ function dataDir(env = process.env) {
11730
+ if (env.MONOBAN_DATA_DIR) return env.MONOBAN_DATA_DIR;
11731
+ if (env.XDG_DATA_HOME) return join(env.XDG_DATA_HOME, "monoban");
11732
+ return join(homedir(), ".local", "share", "monoban");
11733
+ }
11734
+ const agentpipeHome = (env = process.env) => join(dataDir(env), "agentpipe");
11735
+ /** The agentpipe monoban installed, whether or not it's there. */
11736
+ const agentpipeBin = (env = process.env) => join(agentpipeHome(env), "current", "bin", "agentpipe");
11737
+ /** The file agentpipe looks for to refer its `self-update` to monoban. */
11738
+ const MANAGED = "monoban-managed";
11739
+ /** The uv release this machine runs, or why agentpipe can't be installed here. */
11740
+ function installTarget(platform = process.platform, arch = process.arch, musl = isMusl) {
11741
+ const cpu = arch === "arm64" ? "aarch64" : arch === "x64" ? "x86_64" : null;
11742
+ if (!cpu) return { problem: `agentpipe runs on 64-bit Intel or ARM machines, not ${arch}.` };
11743
+ if (platform === "darwin") return { target: `${cpu}-apple-darwin` };
11744
+ if (platform === "linux") {
11745
+ if (musl()) return { problem: "agentpipe needs a Linux with glibc (Debian, Ubuntu, Fedora…), not musl (Alpine)." };
11746
+ return { target: `${cpu}-unknown-linux-gnu` };
11747
+ }
11748
+ return { problem: `agentpipe runs on macOS and Linux, not ${platform}.` };
11749
+ }
11750
+ function isMusl() {
11751
+ try {
11752
+ return readdirSync("/lib").some((name) => name.startsWith("ld-musl-"));
11753
+ } catch {
11754
+ return false;
11755
+ }
11756
+ }
11757
+ const exec$1 = (command, args, { env, cwd }) => new Promise((resolve) => {
11758
+ execFile(command, args, {
11759
+ env,
11760
+ cwd,
11761
+ maxBuffer: 33554432,
11762
+ timeout: 12e5
11763
+ }, (err, stdout, stderr) => {
11764
+ const code = err?.code;
11765
+ resolve({
11766
+ code: !err ? 0 : typeof code === "number" ? code : 127,
11767
+ stdout: String(stdout),
11768
+ stderr: String(stderr) || (err?.message ?? "")
11769
+ });
11770
+ });
11771
+ });
11772
+ /** The version `current` points to, when its agentpipe is there. */
11773
+ async function installedVersion(env = process.env) {
11774
+ const home = agentpipeHome(env);
11775
+ try {
11776
+ const version = basename(await readlink(join(home, "current")));
11777
+ await access(agentpipeBin(env), constants.X_OK);
11778
+ return version;
11779
+ } catch {
11780
+ return null;
11781
+ }
11782
+ }
11783
+ /** What uv gets of the environment: the network's settings and uv's own, and the folders it works in. */
11784
+ function uvEnv(env, home) {
11785
+ const keep = (name) => [
11786
+ "PATH",
11787
+ "HOME",
11788
+ "TMPDIR",
11789
+ "SSL_CERT_FILE",
11790
+ "SSL_CERT_DIR"
11791
+ ].includes(name) || /^(https?|no|all)_proxy$/i.test(name) || name.startsWith("UV_");
11792
+ return {
11793
+ ...Object.fromEntries(Object.entries(env).filter(([name, value]) => value !== void 0 && keep(name))),
11794
+ UV_PYTHON_INSTALL_DIR: join(home, "python"),
11795
+ UV_PYTHON_PREFERENCE: "only-managed",
11796
+ UV_CACHE_DIR: join(home, "cache"),
11797
+ UV_NO_PROGRESS: "1"
11798
+ };
11799
+ }
11800
+ /** An executable named `name` on PATH. */
11801
+ async function onPath(name, env) {
11802
+ for (const dir of (env.PATH ?? "").split(delimiter).filter(Boolean)) {
11803
+ const path = join(dir, name);
11804
+ try {
11805
+ await access(path, constants.X_OK);
11806
+ return path;
11807
+ } catch {}
11808
+ }
11809
+ return null;
11810
+ }
11811
+ /** The first version a command prints for `--version`, or null. */
11812
+ async function versionOf$1(run, command, env, cwd) {
11813
+ const { code, stdout } = await run(command, ["--version"], {
11814
+ env,
11815
+ cwd
11816
+ });
11817
+ return code === 0 ? /\d+\.\d+\.\d+/.exec(stdout)?.[0] ?? null : null;
11818
+ }
11819
+ const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
11820
+ /** A download, kept only when it's the file this monoban pins. */
11821
+ async function download(ctx, url, expected) {
11822
+ let res;
11823
+ try {
11824
+ res = await ctx.fetch(new Request(url, { signal: AbortSignal.timeout(3e5) }));
11825
+ } catch (err) {
11826
+ throw new CliError(`Couldn't download ${url}: ${err.message}.`);
11827
+ }
11828
+ if (!res.ok) throw new CliError(`Couldn't download ${url}: HTTP ${res.status}.`);
11829
+ const bytes = new Uint8Array(await res.arrayBuffer());
11830
+ const actual = sha256(bytes);
11831
+ if (actual !== expected) throw new CliError(`${url} isn't the file this monoban pins (SHA-256 ${actual}, expected ${expected}). Nothing was installed.`);
11832
+ return bytes;
11833
+ }
11834
+ /** The uv to install with: monoban's own, else a recent one on PATH, else monoban downloads its own. */
11835
+ async function findUv(ctx, run, home, target, uvPin) {
11836
+ const ours = join(home, "uv", "uv");
11837
+ if (existsSync(ours)) return ours;
11838
+ const theirs = await onPath("uv", ctx.env);
11839
+ const version = theirs && await versionOf$1(run, theirs, uvEnv(ctx.env, home), home);
11840
+ if (theirs && version && !newer("0.8.0", version)) return theirs;
11841
+ ctx.err(`Downloading uv ${uvPin.version}…`);
11842
+ const archive = join(home, "downloads", `uv-${target}.tar.gz`);
11843
+ await writeFile(archive, await download(ctx, uvArchive(target, uvPin.version), uvPin.sha256[target]));
11844
+ const unpacked = join(home, "downloads", "uv");
11845
+ await rm(unpacked, {
11846
+ recursive: true,
11847
+ force: true
11848
+ });
11849
+ await mkdir(unpacked, { recursive: true });
11850
+ const untar = await run("tar", [
11851
+ "-xzf",
11852
+ archive,
11853
+ "-C",
11854
+ unpacked
11855
+ ], {
11856
+ env: ctx.env,
11857
+ cwd: home
11858
+ });
11859
+ if (untar.code !== 0) throw new CliError(`Couldn't unpack uv: ${untar.stderr.trim()}`);
11860
+ await mkdir(join(home, "uv"), { recursive: true });
11861
+ await rename(join(unpacked, `uv-${target}`, "uv"), ours);
11862
+ return ours;
11863
+ }
11864
+ /** Runs uv, and turns its failure into what it said. */
11865
+ async function uv(run, command, args, env, cwd, doing) {
11866
+ const { code, stderr } = await run(command, args, {
11867
+ env,
11868
+ cwd
11869
+ });
11870
+ if (code !== 0) throw new CliError(`Couldn't ${doing} (uv exited ${code}):\n${stderr.trim().split("\n").slice(-12).join("\n")}`);
11871
+ }
11872
+ /** `monoban agentpipe install` (and `update`): installs this monoban's agentpipe, unless it's there. */
11873
+ async function installAgentpipe(ctx, options = {}, deps = {}) {
11874
+ const run = deps.exec ?? exec$1;
11875
+ const where = deps.target ?? installTarget();
11876
+ const pins = deps.pins ?? {
11877
+ agentpipe: AGENTPIPE,
11878
+ uv: UV
11879
+ };
11880
+ const pin = pins.agentpipe;
11881
+ if ("problem" in where) throw new CliError(where.problem);
11882
+ const home = agentpipeHome(ctx.env);
11883
+ const { version } = pin;
11884
+ await mkdir(join(home, "downloads"), {
11885
+ recursive: true,
11886
+ mode: 448
11887
+ });
11888
+ await withLock(join(home, "install.lock"), async () => {
11889
+ const before = await installedVersion(ctx.env);
11890
+ if (before === version && !options.force) {
11891
+ ctx.out(`agentpipe ${version} is installed: ${agentpipeBin(ctx.env)}`);
11892
+ return;
11893
+ }
11894
+ const uvBin = await findUv(ctx, run, home, where.target, pins.uv);
11895
+ const env = uvEnv(ctx.env, home);
11896
+ ctx.err(`Downloading agentpipe ${version}…`);
11897
+ const wheel = join(home, "downloads", agentpipeWheel(version));
11898
+ await writeFile(wheel, await download(ctx, agentpipeAsset(version, agentpipeWheel(version)), pin.wheelSha256));
11899
+ const requirements = await download(ctx, agentpipeAsset(version, agentpipeRequirements(version)), pin.requirementsSha256);
11900
+ const lock = join(home, "downloads", "lock.txt");
11901
+ await writeFile(lock, `${new TextDecoder().decode(requirements).trimEnd()}\nagentpipe @ ${pathToFileURL(wheel).href} --hash=sha256:${pin.wheelSha256}\n`);
11902
+ ctx.err("Installing Python 3.12 and agentpipe's dependencies (a minute or two the first time)…");
11903
+ const dir = join(home, "versions", version);
11904
+ await rm(dir, {
11905
+ recursive: true,
11906
+ force: true
11907
+ });
11908
+ await uv(run, uvBin, [
11909
+ "venv",
11910
+ "--quiet",
11911
+ "--python",
11912
+ "3.12",
11913
+ dir
11914
+ ], env, home, "make agentpipe's Python environment");
11915
+ await uv(run, uvBin, [
11916
+ "pip",
11917
+ "install",
11918
+ "--quiet",
11919
+ "--require-hashes",
11920
+ "--python",
11921
+ join(dir, "bin", "python"),
11922
+ "-r",
11923
+ lock
11924
+ ], env, home, "install agentpipe");
11925
+ await writeFile(join(dir, MANAGED), "agentpipe is installed by monoban: update it with `monoban agentpipe update`.\n");
11926
+ const said = await run(join(dir, "bin", "agentpipe"), ["--version"], {
11927
+ env,
11928
+ cwd: home
11929
+ });
11930
+ if (said.code !== 0 || !said.stdout.includes(`agentpipe ${version}`)) throw new CliError(`agentpipe ${version} was installed but doesn't run: ${(said.stderr || said.stdout).trim()}`);
11931
+ const link = join(home, "current.new");
11932
+ await rm(link, { force: true });
11933
+ await symlink(join("versions", version), link);
11934
+ await rename(link, join(home, "current"));
11935
+ for (const old of await readdir(join(home, "versions"))) if (old !== version && old !== before) await rm(join(home, "versions", old), {
11936
+ recursive: true,
11937
+ force: true
11938
+ });
11939
+ await rm(join(home, "cache"), {
11940
+ recursive: true,
11941
+ force: true
11942
+ });
11943
+ await rm(join(home, "downloads"), {
11944
+ recursive: true,
11945
+ force: true
11946
+ });
11947
+ ctx.out(`Installed agentpipe ${version}: ${agentpipeBin(ctx.env)}`);
11948
+ }, {
11949
+ staleMs: 18e5,
11950
+ timeoutMs: 0,
11951
+ busy: `Another monoban is installing agentpipe (${home}). Try again.`
11952
+ });
11953
+ }
11954
+ async function agentpipeStatus(env, target = installTarget()) {
11955
+ const installed = await installedVersion(env);
11956
+ return {
11957
+ installed,
11958
+ pinned: AGENTPIPE.version,
11959
+ command: installed ? agentpipeBin(env) : null,
11960
+ updateAvailable: installed !== null && newer(AGENTPIPE.version, installed),
11961
+ unsupported: "problem" in target ? target.problem : null
11962
+ };
11963
+ }
11964
+ /** The status in a sentence, and the command that fixes it. */
11965
+ function describeStatus(s) {
11966
+ if (s.unsupported && !s.installed) return {
11967
+ ok: false,
11968
+ text: s.unsupported
11969
+ };
11970
+ if (!s.installed) return {
11971
+ ok: false,
11972
+ text: "agentpipe isn't installed",
11973
+ fix: "monoban agentpipe install"
11974
+ };
11975
+ if (s.updateAvailable) return {
11976
+ ok: false,
11977
+ text: `agentpipe ${s.installed}; this monoban comes with ${s.pinned}`,
11978
+ fix: "monoban agentpipe update"
11979
+ };
11980
+ return {
11981
+ ok: true,
11982
+ text: `agentpipe ${s.installed} (${s.command})`
11983
+ };
11984
+ }
11985
+ /** `monoban agentpipe status`. */
11986
+ async function status(ctx, options) {
11987
+ const s = await agentpipeStatus(ctx.env);
11988
+ if (options.json) return ctx.out(JSON.stringify(s, null, 2));
11989
+ const { text, fix } = describeStatus(s);
11990
+ ctx.out(fix ? `${text}: ${fix}` : text);
11991
+ }
11992
+ /** `monoban agentpipe update`: this monoban's agentpipe, over an older one. */
11993
+ async function update(ctx, deps = {}) {
11994
+ const installed = await installedVersion(ctx.env);
11995
+ const pinned = (deps.pins?.agentpipe ?? AGENTPIPE).version;
11996
+ if (!installed) throw new CliError("agentpipe isn't installed by monoban: monoban agentpipe install", EXIT.notFound);
11997
+ if (installed === pinned) {
11998
+ ctx.out(`agentpipe ${installed} is the version this monoban comes with. A newer one comes with a newer monoban (monoban upgrade).`);
11999
+ return;
12000
+ }
12001
+ await installAgentpipe(ctx, {}, deps);
12002
+ }
12003
+ /** `monoban agentpipe uninstall`: removes what monoban installed; agentpipe's runs and settings stay. */
12004
+ async function uninstall(ctx, options) {
12005
+ const home = agentpipeHome(ctx.env);
12006
+ if (!existsSync(home)) return ctx.out("agentpipe isn't installed by monoban: nothing to remove.");
12007
+ if (!options.yes && !await ctx.confirm(`Remove agentpipe (${home})?`)) throw new CliError("Left as it is (--yes removes it without asking).", EXIT.usage);
12008
+ await rm(home, {
12009
+ recursive: true,
12010
+ force: true
12011
+ });
12012
+ ctx.out(`Removed agentpipe (${home}). Its runs and settings in ~/.agentpipe are kept.`);
12013
+ }
12014
+ /** Runs monoban's agentpipe on this terminal (`monoban agentpipe login`, `monoban agentpipe -- …`): its exit code. */
12015
+ async function runAgentpipe(ctx, args) {
12016
+ if (!await installedVersion(ctx.env)) throw new CliError("agentpipe isn't installed by monoban: monoban agentpipe install", EXIT.notFound);
12017
+ return new Promise((resolve) => {
12018
+ const child = spawn(agentpipeBin(ctx.env), args, {
12019
+ stdio: "inherit",
12020
+ env: ctx.env
12021
+ });
12022
+ child.on("error", (err) => {
12023
+ ctx.err(`Couldn't start agentpipe: ${err.message}`);
12024
+ resolve(EXIT.error);
12025
+ });
12026
+ child.on("close", (code) => resolve(code ?? EXIT.error));
12027
+ });
12028
+ }
11547
12029
  //#endregion
11548
12030
  //#region src/login/browser.ts
11549
12031
  /**
@@ -12750,619 +13232,264 @@ async function detach(ctx, ref, which, options) {
12750
13232
  ctx.out(`Removed ${linkLabel(link)} from ${task.ref}.`);
12751
13233
  }
12752
13234
  //#endregion
12753
- //#region src/commands/notes.ts
12754
- const printNotes = (ctx, key, notes) => ctx.out(JSON.stringify({
12755
- project: key,
12756
- ...notes
12757
- }, null, 2));
12758
- /** `monoban notes`: the project's notes as they are, for reading, a pager or a pipe. */
12759
- async function notesShow(ctx, options) {
12760
- const api = apis(ctx).signedIn;
12761
- const key = await resolveProject(ctx, api, options.project);
12762
- const notes = await unwrap(api.GET("/v1/projects/{key}/notes", { params: { path: { key } } }));
12763
- if (options.json) return printNotes(ctx, key, notes);
12764
- if (!notes.text) {
12765
- ctx.err(`${key} has no notes yet. Add a line with \`monoban notes add …\`, or write them with \`monoban notes edit\`.`);
12766
- return;
12767
- }
12768
- ctx.out(notes.text.replace(/\n$/, ""));
13235
+ //#region src/commands/start.ts
13236
+ /** How long a branch name's words may be, after `mon-12-`. */
13237
+ const SLUG_LENGTH = 40;
13238
+ /** The branch for a task: `mon-12-import-boards-from-trello` (its ref, then its title's first words). */
13239
+ function branchName(ref, title) {
13240
+ const words = title.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
13241
+ const cut = words.length > SLUG_LENGTH ? words.slice(0, 41).replace(/-[^-]*$/, "") : words;
13242
+ return [ref.toLowerCase(), cut].filter(Boolean).join("-");
12769
13243
  }
12770
- /** `monoban notes add TEXT…`: a line at the end of the notes (`-` reads it from stdin). */
12771
- async function notesAdd(ctx, words, options) {
12772
- const text = words.length === 1 && words[0] === "-" ? (await ctx.readStdin()).replace(/\n$/, "") : words.join(" ");
12773
- if (!text.trim()) throw new CliError("Nothing to add: give the text, or - to read it from stdin.", EXIT.usage);
12774
- const api = apis(ctx).signedIn;
12775
- const key = await resolveProject(ctx, api, options.project);
12776
- const notes = await unwrap(api.PATCH("/v1/projects/{key}/notes", {
12777
- params: { path: { key } },
12778
- body: { append: text }
12779
- }));
12780
- if (options.json) return printNotes(ctx, key, notes);
12781
- ctx.out(`Added to the notes of ${key}.`);
13244
+ /**
13245
+ * The column where work happens: the one named In progress (or Doing, WIP…), else the one after the
13246
+ * first, unless that's Done. undefined when the board has none (Backlog and Done only).
13247
+ */
13248
+ function workColumn(columns) {
13249
+ const names = [
13250
+ "in progress",
13251
+ "in-progress",
13252
+ "doing",
13253
+ "wip",
13254
+ "started",
13255
+ "working",
13256
+ "active"
13257
+ ];
13258
+ const named = columns.find((c) => names.includes(c.name.trim().toLowerCase()));
13259
+ if (named) return named;
13260
+ const second = columns[1];
13261
+ return second && second !== doneColumn(columns) ? second : void 0;
12782
13262
  }
12783
- /** `monoban notes edit`: the notes in $EDITOR, saved only if nobody changed them in the meantime. */
12784
- async function notesEdit(ctx, options) {
12785
- const api = apis(ctx).signedIn;
12786
- const key = await resolveProject(ctx, api, options.project);
12787
- const notes = await unwrap(api.GET("/v1/projects/{key}/notes", { params: { path: { key } } }));
12788
- const text = await ctx.edit(notes.text, `${key}-notes`);
12789
- if (text === notes.text) {
12790
- ctx.err(`No changes to the notes of ${key}.`);
12791
- return;
12792
- }
12793
- let saved;
12794
- try {
12795
- saved = await unwrap(api.PATCH("/v1/projects/{key}/notes", {
13263
+ /**
13264
+ * Moves a task to the column where work happens, unless it's there or further on. Answers it, and what
13265
+ * happened in words ("Moved MON-12 from Backlog to In progress.").
13266
+ */
13267
+ async function moveToWork(api, task, columns) {
13268
+ const target = workColumn(columns);
13269
+ const at = (t) => columns.findIndex((c) => c.id === t.columnId);
13270
+ const here = columns[at(task)];
13271
+ if (!target) return {
13272
+ task,
13273
+ moved: false,
13274
+ line: `${task.ref} stays in ${here?.name ?? "its column"}: the board has no In progress column.`
13275
+ };
13276
+ if (at(task) >= columns.indexOf(target)) return {
13277
+ task,
13278
+ moved: false,
13279
+ line: `${task.ref} is in ${here?.name ?? "its column"} already.`
13280
+ };
13281
+ const { key, number } = taskRefOf(task.ref);
13282
+ return {
13283
+ task: await unwrap(api.PATCH("/v1/projects/{key}/tasks/{number}", {
12796
13284
  params: {
12797
- path: { key },
12798
- header: ifMatch(notes.version)
13285
+ path: {
13286
+ key,
13287
+ number
13288
+ },
13289
+ header: ifMatch(task.version)
12799
13290
  },
12800
- body: { text }
12801
- }));
12802
- } catch (err) {
12803
- const draft = await keepDraft(text, `${key}-notes`);
12804
- ctx.err(`Your text is saved in ${draft}.`);
12805
- if (err instanceof ApiProblem && err.status === 412) throw new CliError(`The notes of ${key} changed elsewhere in the meantime. Run \`monoban notes edit\` again.`);
12806
- throw err;
12807
- }
12808
- if (options.json) return printNotes(ctx, key, saved);
12809
- ctx.out(`Updated the notes of ${key}.`);
13291
+ body: { columnId: target.id }
13292
+ })).catch((err) => changedElsewhere(err, task.ref)),
13293
+ moved: true,
13294
+ line: `Moved ${task.ref}${here ? ` from ${here.name}` : ""} to ${target.name}.`
13295
+ };
12810
13296
  }
12811
- //#endregion
12812
- //#region src/runner/agents/agentpipe.ts
12813
- /** agentpipe's step statuses that monoban has too; the others (budget_exceeded, max_turns…) are failures. */
12814
- const SAME = [
12815
- "ok",
12816
- "failed",
12817
- "skipped",
12818
- "cancelled",
12819
- "needs_human"
12820
- ];
12821
- const RUN_ENDINGS = {
12822
- ok: "succeeded",
12823
- needs_human: "needs_human",
12824
- cancelled: "cancelled"
12825
- };
12826
- const str = (v) => typeof v === "string" && v.trim() ? v.trim() : null;
12827
- const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
12828
- /** A message the API takes: one line or more, at most 2000 characters. */
12829
- const clip$1 = (text) => text.length > 2e3 ? `${text.slice(0, 1999)}…` : text;
12830
13297
  /**
12831
- * Turns agentpipe's events into monoban's, one at a time, remembering what it needs across them. agentpipe ends
12832
- * each step twice: first with what the step decided (a skip says `skipped`, with its reason), then with what it
12833
- * cost (`turns`, `cost_usd`). They become one step_finished, sent when the second arrives (or the next step
12834
- * starts, or the run ends, if it never does).
13298
+ * `monoban start MON-12`: work on a task. Checks out its branch (`mon-12-title`: made from the commit
13299
+ * you're on, or the one already there) and moves it to In progress, unless it's there or further on.
13300
+ * --no-branch and --no-move do half of it.
12835
13301
  */
12836
- function agentpipeMapper(report) {
12837
- const started = /* @__PURE__ */ new Set();
12838
- const attempts = /* @__PURE__ */ new Map();
12839
- let pending = null;
12840
- let total = 0;
12841
- let ending = null;
12842
- const flush = (cost) => {
12843
- if (!pending) return;
12844
- const { step, attempt, status, message, at } = pending;
12845
- pending = null;
12846
- const data = {};
12847
- if (cost?.durationMs != null) data.durationMs = cost.durationMs;
12848
- if (cost?.costUsd != null) data.costUsd = cost.costUsd;
12849
- report.event({
12850
- kind: "step_finished",
12851
- step,
12852
- attempt,
12853
- status,
12854
- ...message && { message: clip$1(message) },
12855
- ...Object.keys(data).length && { data },
12856
- ...at && { at }
12857
- });
12858
- };
12859
- const stepStatus = (raw) => {
12860
- const s = str(raw) ?? "ok";
12861
- return SAME.includes(s) ? {
12862
- status: s,
12863
- note: null
12864
- } : {
12865
- status: "failed",
12866
- note: s.replace(/_/g, " ")
13302
+ async function start(ctx, ref, options) {
13303
+ const api = apis(ctx).signedIn;
13304
+ let task = await taskByRef(api, ref, ctx);
13305
+ const { key } = taskRefOf(task.ref);
13306
+ const columns = await columnsOf(api, key);
13307
+ const lines = [];
13308
+ let branch = null;
13309
+ if (options.branch !== false) {
13310
+ if (!await ctx.clone.inClone()) throw new CliError("Not in a git clone, so there's no branch to make. Run it in the repository, or with --no-branch.", EXIT.usage);
13311
+ const current = await ctx.clone.branch();
13312
+ const own = (name) => taskOfBranch(name) === task.ref;
13313
+ if (own(current)) {
13314
+ branch = current;
13315
+ lines.push(`Already on ${branch}.`);
13316
+ } else {
13317
+ const existing = (await ctx.clone.branches()).find(own);
13318
+ branch = existing ?? branchName(task.ref, task.title);
13319
+ const why = await ctx.clone.switchTo(branch, !existing);
13320
+ if (why) throw new CliError(`git couldn't switch to ${branch}: ${why}`);
13321
+ lines.push(existing ? `Switched to ${branch}.` : `Switched to a new branch ${branch}.`);
13322
+ }
13323
+ }
13324
+ if (options.move !== false) {
13325
+ const moved = await moveToWork(api, task, columns);
13326
+ task = moved.task;
13327
+ lines.push(moved.line);
13328
+ }
13329
+ if (options.json) {
13330
+ const json = {
13331
+ ...taskJson(task, columns, await tagsFor(api, key, task)),
13332
+ branch
12867
13333
  };
13334
+ return ctx.out(JSON.stringify(json, null, 2));
13335
+ }
13336
+ for (const line of lines) ctx.out(line);
13337
+ }
13338
+ //#endregion
13339
+ //#region src/runner/process.ts
13340
+ const defaultSpawn = spawn;
13341
+ const TAIL$1 = 20;
13342
+ function startProcess({ command, args, cwd, env, stdin, onLine, spawn = defaultSpawn, graceMs = 1e4 }) {
13343
+ let child;
13344
+ let exited = false;
13345
+ const timers = [];
13346
+ const signal = (sig) => {
13347
+ if (!child || exited) return;
13348
+ try {
13349
+ if (child.pid) process.kill(-child.pid, sig);
13350
+ else child.kill(sig);
13351
+ } catch {
13352
+ child.kill(sig);
13353
+ }
12868
13354
  };
12869
- /** Feed it one event; answers how the run ended once agentpipe said so. */
12870
- const take = (e) => {
12871
- const d = e.data ?? {};
12872
- const at = str(e.ts) ?? void 0;
12873
- const step = str(e.step);
12874
- switch (e.kind) {
12875
- case "run.start": {
12876
- const id = str(d.run_id) ?? str(e.run_id);
12877
- if (id) report.update({ externalId: id });
12878
- return;
12879
- }
12880
- case "step.start": {
12881
- if (!step) return;
12882
- const attempt = num(d.attempt) ?? attempts.get(step) ?? 1;
12883
- const key = `${step}@${attempt}`;
12884
- if (started.has(key)) return;
12885
- if (pending && pending.step !== step) flush();
12886
- started.add(key);
12887
- attempts.set(step, attempt);
12888
- report.event({
12889
- kind: "step_started",
12890
- step,
12891
- attempt,
12892
- status: "running",
12893
- ...at && { at }
13355
+ return {
13356
+ done: new Promise((resolve) => {
13357
+ try {
13358
+ child = spawn(command, args, {
13359
+ cwd,
13360
+ env,
13361
+ detached: true
12894
13362
  });
12895
- return;
12896
- }
12897
- case "step.end": {
12898
- if (!step) return;
12899
- const attempt = num(d.attempt) ?? attempts.get(step) ?? 1;
12900
- const { status, note } = stepStatus(d.status);
12901
- const reason = str(d.reason) ?? str(d.error) ?? note;
12902
- const costShaped = "turns" in d || "cost_usd" in d;
12903
- if (!pending || pending.step !== step) {
12904
- flush();
12905
- pending = {
12906
- step,
12907
- attempt,
12908
- status,
12909
- message: reason,
12910
- ...at && { at }
12911
- };
12912
- } else {
12913
- if (pending.status === "ok" && status !== "ok") pending.status = status;
12914
- pending.message = pending.message ?? reason;
12915
- if (at) pending.at = at;
12916
- }
12917
- if (costShaped) {
12918
- const costUsd = num(d.cost_usd);
12919
- if (costUsd) {
12920
- total += costUsd;
12921
- report.update({ costUsd: Math.round(total * 1e4) / 1e4 });
12922
- }
12923
- flush({
12924
- durationMs: num(d.duration_ms),
12925
- costUsd
12926
- });
12927
- }
12928
- return;
12929
- }
12930
- case "pr.created": {
12931
- const url = str(d.url);
12932
- if (!url) return;
12933
- report.update({ prUrl: url });
12934
- report.event({
12935
- kind: "pr_opened",
12936
- ...step && { step },
12937
- message: url,
12938
- data: {
12939
- url,
12940
- ...num(d.number) !== null && { number: num(d.number) }
12941
- },
12942
- ...at && { at }
13363
+ } catch (err) {
13364
+ resolve({
13365
+ code: null,
13366
+ spawnError: `Couldn't start ${command}: ${err.message}`,
13367
+ lastError: null
12943
13368
  });
12944
13369
  return;
12945
13370
  }
12946
- case "issue.updated": {
12947
- const change = str(d.change);
12948
- if (change) report.event({
12949
- kind: "board",
12950
- message: clip$1(change),
12951
- ...at && { at }
12952
- });
12953
- return;
13371
+ let spawnError = null;
13372
+ const tail = [];
13373
+ child.on("error", (err) => {
13374
+ spawnError = err.code === "ENOENT" ? `${command} isn't installed here (or isn't on the runner's PATH).` : `${command} failed: ${err.message}`;
13375
+ });
13376
+ if (child.stdin) {
13377
+ child.stdin.on("error", () => {});
13378
+ child.stdin.end(stdin ?? "");
12954
13379
  }
12955
- case "issue.comment": {
12956
- const milestone = str(d.milestone);
12957
- report.event({
12958
- kind: "board",
12959
- message: milestone ? `commented: ${milestone}` : "commented",
12960
- ...at && { at }
12961
- });
12962
- return;
12963
- }
12964
- case "question.asked":
12965
- case "escalation": {
12966
- const text = str(d.question) ?? str(d.text) ?? str(d.message) ?? str(d.reason) ?? "It needs an answer.";
12967
- report.event({
12968
- kind: "question",
12969
- ...step && { step },
12970
- message: clip$1(text),
12971
- ...at && { at }
12972
- });
12973
- return;
12974
- }
12975
- case "error": {
12976
- const text = str(d.message) ?? str(d.kind) ?? "Something went wrong.";
12977
- report.event({
12978
- kind: "warning",
12979
- ...step && { step },
12980
- message: clip$1(text),
12981
- ...at && { at }
12982
- });
12983
- return;
12984
- }
12985
- case "run.end": {
12986
- flush();
12987
- const status = str(d.status) ?? "failed";
12988
- const reason = str(d.reason);
12989
- ending = {
12990
- status: RUN_ENDINGS[status] ?? "failed",
12991
- reason: reason ?? (RUN_ENDINGS[status] ? null : `It ended ${status.replace(/_/g, " ")}.`)
12992
- };
12993
- if (ending.status === "failed" && ending.reason) report.event({
12994
- kind: "error",
12995
- message: clip$1(ending.reason)
13380
+ if (child.stdout) createInterface$1({ input: child.stdout }).on("line", onLine);
13381
+ if (child.stderr) createInterface$1({ input: child.stderr }).on("line", (line) => {
13382
+ if (!line.trim()) return;
13383
+ tail.push(line.trim());
13384
+ if (tail.length > TAIL$1) tail.shift();
13385
+ });
13386
+ child.on("close", (code) => {
13387
+ exited = true;
13388
+ for (const t of timers) clearTimeout(t);
13389
+ resolve({
13390
+ code,
13391
+ spawnError,
13392
+ lastError: tail.at(-1) ?? null
12996
13393
  });
12997
- return;
12998
- }
13394
+ });
13395
+ }),
13396
+ stop: () => {
13397
+ signal("SIGINT");
13398
+ timers.push(setTimeout(() => signal("SIGTERM"), graceMs));
13399
+ timers.push(setTimeout(() => signal("SIGKILL"), graceMs * 2));
12999
13400
  }
13000
13401
  };
13001
- return {
13002
- take,
13003
- /** How agentpipe said the run ended (null: it didn't). */
13004
- ending: () => ending,
13005
- flush: () => flush()
13006
- };
13007
13402
  }
13008
- /** One stdout line as an event, or null for agentpipe's plain lines ("profile: cached", the step table). */
13009
- function parseLine(line) {
13010
- const text = line.trim();
13011
- if (!text.startsWith("{")) return null;
13012
- try {
13013
- const value = JSON.parse(text);
13014
- if (value && typeof value === "object" && typeof value.kind === "string") return value;
13015
- } catch {}
13016
- return null;
13403
+ /** The first version number a command prints for `--version` ("2.1.300 (Claude Code)" → 2.1.300), or null. */
13404
+ function versionOf(command, env = process.env) {
13405
+ return new Promise((resolve) => {
13406
+ execFile(command, ["--version"], {
13407
+ timeout: 15e3,
13408
+ env
13409
+ }, (err, stdout, stderr) => {
13410
+ if (err) return resolve(null);
13411
+ resolve(/\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?/.exec(`${stdout} ${stderr}`)?.[0] ?? null);
13412
+ });
13413
+ });
13017
13414
  }
13018
- /** agentpipe's arguments for a run: the folder, the task, and what it may do. */
13019
- function agentpipeArgs({ ref, workdir, options }) {
13020
- return [
13021
- "run",
13022
- workdir,
13023
- "--from-issue",
13024
- ref,
13025
- "--json",
13026
- ...options.pr === "none" ? ["--local"] : options.pr === "ready" ? ["--no-draft"] : ["--draft"],
13027
- ...options.budgetUsd !== void 0 ? ["--budget", String(options.budgetUsd)] : [],
13028
- ...options.autonomous ? ["--autonomous"] : []
13029
- ];
13415
+ /** Whether version `a` is at least `b` (numbers only: 2.1.259). */
13416
+ function atLeast(a, b) {
13417
+ const parts = (v) => v.split(/[-+]/)[0]?.split(".").map(Number) ?? [];
13418
+ const [x, y] = [parts(a), parts(b)];
13419
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
13420
+ const d = (x[i] ?? 0) - (y[i] ?? 0);
13421
+ if (d) return d > 0;
13422
+ }
13423
+ return true;
13030
13424
  }
13031
- const exec = (command, args, env) => new Promise((resolve) => execFile(command, args, {
13032
- timeout: 3e4,
13033
- env
13034
- }, () => resolve()));
13035
- /** Stderr's last lines, to say why agentpipe stopped without saying so itself. */
13036
- const TAIL$1 = 20;
13037
- function agentpipe({ command = "agentpipe", args = [], spawn: spawn$1 = spawn, execCommand = exec, env = process.env } = {}) {
13038
- return {
13039
- name: "agentpipe",
13040
- start(run, report) {
13041
- let externalId = null;
13042
- const feed = agentpipeMapper({
13043
- event: report.event,
13044
- update: (u) => {
13045
- if (u.externalId) externalId = u.externalId;
13046
- report.update(u);
13047
- }
13048
- });
13049
- const tail = [];
13050
- let child;
13051
- return {
13052
- done: new Promise((resolve) => {
13053
- try {
13054
- child = spawn$1(command, [...agentpipeArgs(run), ...args], {
13055
- cwd: run.workdir,
13056
- env,
13057
- detached: true
13058
- });
13059
- } catch (err) {
13060
- resolve({
13061
- status: "failed",
13062
- reason: `Couldn't start ${command}: ${err.message}`
13063
- });
13064
- return;
13065
- }
13066
- let spawnError = null;
13067
- child.on("error", (err) => {
13068
- spawnError = err.code === "ENOENT" ? `${command} isn't installed here (or isn't on the runner's PATH).` : `${command} failed: ${err.message}`;
13069
- });
13070
- if (child.stdout) createInterface$1({ input: child.stdout }).on("line", (line) => {
13071
- const event = parseLine(line);
13072
- if (event) feed.take(event);
13073
- });
13074
- if (child.stderr) createInterface$1({ input: child.stderr }).on("line", (line) => {
13075
- if (!line.trim()) return;
13076
- tail.push(line.trim());
13077
- if (tail.length > TAIL$1) tail.shift();
13078
- });
13079
- child.on("close", (code) => {
13080
- feed.flush();
13081
- const said = feed.ending();
13082
- if (said) return resolve(said);
13083
- if (spawnError) return resolve({
13084
- status: "failed",
13085
- reason: spawnError
13086
- });
13087
- const last = tail.at(-1);
13088
- resolve({
13089
- status: "failed",
13090
- reason: `${command} stopped (exit code ${code ?? "none"}) without saying how it ended${last ? `: ${last}` : "."}`
13091
- });
13092
- });
13093
- }),
13094
- cancel: async () => {
13095
- if (externalId) await execCommand(command, [
13096
- "cancel",
13097
- externalId,
13098
- "--reason",
13099
- "Cancelled from monoban"
13100
- ], env);
13101
- else child?.kill("SIGINT");
13102
- }
13103
- };
13425
+ //#endregion
13426
+ //#region src/runner/prompt.ts
13427
+ /** The JSON Schema the agent's last message follows (strict, as Codex's --output-schema needs). */
13428
+ const OUTCOME_SCHEMA = {
13429
+ type: "object",
13430
+ additionalProperties: false,
13431
+ required: [
13432
+ "status",
13433
+ "summary",
13434
+ "prTitle",
13435
+ "question"
13436
+ ],
13437
+ properties: {
13438
+ status: {
13439
+ type: "string",
13440
+ enum: ["done", "blocked"],
13441
+ description: "done: the task is done; blocked: it can't go on without an answer"
13442
+ },
13443
+ summary: {
13444
+ type: "string",
13445
+ description: "What you changed and how you checked it, in a few sentences of Markdown"
13446
+ },
13447
+ prTitle: {
13448
+ type: "string",
13449
+ description: "A pull request title, under 70 characters"
13450
+ },
13451
+ question: {
13452
+ type: "string",
13453
+ description: "When blocked, what you need to know; otherwise empty"
13104
13454
  }
13455
+ }
13456
+ };
13457
+ /** The outcome in an agent's answer: the JSON itself, or the last JSON object in its text. */
13458
+ function parseOutcome(value) {
13459
+ let v = value;
13460
+ if (typeof v === "string") {
13461
+ const text = v.trim();
13462
+ const candidates = [text, ...[...text.matchAll(/```(?:json)?\s*([\s\S]*?)```/g)].map((m) => m[1] ?? "")];
13463
+ const open = text.lastIndexOf("{", text.lastIndexOf("\"status\""));
13464
+ if (open >= 0) candidates.push(text.slice(open, text.lastIndexOf("}") + 1));
13465
+ v = null;
13466
+ for (const c of candidates.reverse()) try {
13467
+ const parsed = JSON.parse(c);
13468
+ if (parsed && typeof parsed === "object") {
13469
+ v = parsed;
13470
+ break;
13471
+ }
13472
+ } catch {}
13473
+ }
13474
+ if (!v || typeof v !== "object") return null;
13475
+ const o = v;
13476
+ if (o.status !== "done" && o.status !== "blocked") return null;
13477
+ const str = (x) => typeof x === "string" ? x.trim() : "";
13478
+ return {
13479
+ status: o.status,
13480
+ summary: str(o.summary),
13481
+ prTitle: str(o.prTitle),
13482
+ question: str(o.question)
13105
13483
  };
13106
13484
  }
13107
- //#endregion
13108
- //#region src/commands/start.ts
13109
- /** How long a branch name's words may be, after `mon-12-`. */
13110
- const SLUG_LENGTH = 40;
13111
- /** The branch for a task: `mon-12-import-boards-from-trello` (its ref, then its title's first words). */
13112
- function branchName(ref, title) {
13113
- const words = title.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
13114
- const cut = words.length > SLUG_LENGTH ? words.slice(0, 41).replace(/-[^-]*$/, "") : words;
13115
- return [ref.toLowerCase(), cut].filter(Boolean).join("-");
13116
- }
13117
- /**
13118
- * The column where work happens: the one named In progress (or Doing, WIP…), else the one after the
13119
- * first, unless that's Done. undefined when the board has none (Backlog and Done only).
13120
- */
13121
- function workColumn(columns) {
13122
- const names = [
13123
- "in progress",
13124
- "in-progress",
13125
- "doing",
13126
- "wip",
13127
- "started",
13128
- "working",
13129
- "active"
13130
- ];
13131
- const named = columns.find((c) => names.includes(c.name.trim().toLowerCase()));
13132
- if (named) return named;
13133
- const second = columns[1];
13134
- return second && second !== doneColumn(columns) ? second : void 0;
13135
- }
13136
- /**
13137
- * Moves a task to the column where work happens, unless it's there or further on. Answers it, and what
13138
- * happened in words ("Moved MON-12 from Backlog to In progress.").
13139
- */
13140
- async function moveToWork(api, task, columns) {
13141
- const target = workColumn(columns);
13142
- const at = (t) => columns.findIndex((c) => c.id === t.columnId);
13143
- const here = columns[at(task)];
13144
- if (!target) return {
13145
- task,
13146
- moved: false,
13147
- line: `${task.ref} stays in ${here?.name ?? "its column"}: the board has no In progress column.`
13148
- };
13149
- if (at(task) >= columns.indexOf(target)) return {
13150
- task,
13151
- moved: false,
13152
- line: `${task.ref} is in ${here?.name ?? "its column"} already.`
13153
- };
13154
- const { key, number } = taskRefOf(task.ref);
13155
- return {
13156
- task: await unwrap(api.PATCH("/v1/projects/{key}/tasks/{number}", {
13157
- params: {
13158
- path: {
13159
- key,
13160
- number
13161
- },
13162
- header: ifMatch(task.version)
13163
- },
13164
- body: { columnId: target.id }
13165
- })).catch((err) => changedElsewhere(err, task.ref)),
13166
- moved: true,
13167
- line: `Moved ${task.ref}${here ? ` from ${here.name}` : ""} to ${target.name}.`
13168
- };
13169
- }
13170
- /**
13171
- * `monoban start MON-12`: work on a task. Checks out its branch (`mon-12-title`: made from the commit
13172
- * you're on, or the one already there) and moves it to In progress, unless it's there or further on.
13173
- * --no-branch and --no-move do half of it.
13174
- */
13175
- async function start(ctx, ref, options) {
13176
- const api = apis(ctx).signedIn;
13177
- let task = await taskByRef(api, ref, ctx);
13178
- const { key } = taskRefOf(task.ref);
13179
- const columns = await columnsOf(api, key);
13180
- const lines = [];
13181
- let branch = null;
13182
- if (options.branch !== false) {
13183
- if (!await ctx.clone.inClone()) throw new CliError("Not in a git clone, so there's no branch to make. Run it in the repository, or with --no-branch.", EXIT.usage);
13184
- const current = await ctx.clone.branch();
13185
- const own = (name) => taskOfBranch(name) === task.ref;
13186
- if (own(current)) {
13187
- branch = current;
13188
- lines.push(`Already on ${branch}.`);
13189
- } else {
13190
- const existing = (await ctx.clone.branches()).find(own);
13191
- branch = existing ?? branchName(task.ref, task.title);
13192
- const why = await ctx.clone.switchTo(branch, !existing);
13193
- if (why) throw new CliError(`git couldn't switch to ${branch}: ${why}`);
13194
- lines.push(existing ? `Switched to ${branch}.` : `Switched to a new branch ${branch}.`);
13195
- }
13196
- }
13197
- if (options.move !== false) {
13198
- const moved = await moveToWork(api, task, columns);
13199
- task = moved.task;
13200
- lines.push(moved.line);
13201
- }
13202
- if (options.json) {
13203
- const json = {
13204
- ...taskJson(task, columns, await tagsFor(api, key, task)),
13205
- branch
13206
- };
13207
- return ctx.out(JSON.stringify(json, null, 2));
13208
- }
13209
- for (const line of lines) ctx.out(line);
13210
- }
13211
- //#endregion
13212
- //#region src/runner/process.ts
13213
- const defaultSpawn = spawn;
13214
- const TAIL = 20;
13215
- function startProcess({ command, args, cwd, env, stdin, onLine, spawn = defaultSpawn, graceMs = 1e4 }) {
13216
- let child;
13217
- let exited = false;
13218
- const timers = [];
13219
- const signal = (sig) => {
13220
- if (!child || exited) return;
13221
- try {
13222
- if (child.pid) process.kill(-child.pid, sig);
13223
- else child.kill(sig);
13224
- } catch {
13225
- child.kill(sig);
13226
- }
13227
- };
13228
- return {
13229
- done: new Promise((resolve) => {
13230
- try {
13231
- child = spawn(command, args, {
13232
- cwd,
13233
- env,
13234
- detached: true
13235
- });
13236
- } catch (err) {
13237
- resolve({
13238
- code: null,
13239
- spawnError: `Couldn't start ${command}: ${err.message}`,
13240
- lastError: null
13241
- });
13242
- return;
13243
- }
13244
- let spawnError = null;
13245
- const tail = [];
13246
- child.on("error", (err) => {
13247
- spawnError = err.code === "ENOENT" ? `${command} isn't installed here (or isn't on the runner's PATH).` : `${command} failed: ${err.message}`;
13248
- });
13249
- if (child.stdin) {
13250
- child.stdin.on("error", () => {});
13251
- child.stdin.end(stdin ?? "");
13252
- }
13253
- if (child.stdout) createInterface$1({ input: child.stdout }).on("line", onLine);
13254
- if (child.stderr) createInterface$1({ input: child.stderr }).on("line", (line) => {
13255
- if (!line.trim()) return;
13256
- tail.push(line.trim());
13257
- if (tail.length > TAIL) tail.shift();
13258
- });
13259
- child.on("close", (code) => {
13260
- exited = true;
13261
- for (const t of timers) clearTimeout(t);
13262
- resolve({
13263
- code,
13264
- spawnError,
13265
- lastError: tail.at(-1) ?? null
13266
- });
13267
- });
13268
- }),
13269
- stop: () => {
13270
- signal("SIGINT");
13271
- timers.push(setTimeout(() => signal("SIGTERM"), graceMs));
13272
- timers.push(setTimeout(() => signal("SIGKILL"), graceMs * 2));
13273
- }
13274
- };
13275
- }
13276
- /** The first version number a command prints for `--version` ("2.1.300 (Claude Code)" → 2.1.300), or null. */
13277
- function versionOf(command, env = process.env) {
13278
- return new Promise((resolve) => {
13279
- execFile(command, ["--version"], {
13280
- timeout: 15e3,
13281
- env
13282
- }, (err, stdout, stderr) => {
13283
- if (err) return resolve(null);
13284
- resolve(/\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?/.exec(`${stdout} ${stderr}`)?.[0] ?? null);
13285
- });
13286
- });
13287
- }
13288
- /** Whether version `a` is at least `b` (numbers only: 2.1.259). */
13289
- function atLeast(a, b) {
13290
- const parts = (v) => v.split(/[-+]/)[0]?.split(".").map(Number) ?? [];
13291
- const [x, y] = [parts(a), parts(b)];
13292
- for (let i = 0; i < Math.max(x.length, y.length); i++) {
13293
- const d = (x[i] ?? 0) - (y[i] ?? 0);
13294
- if (d) return d > 0;
13295
- }
13296
- return true;
13297
- }
13298
- //#endregion
13299
- //#region src/runner/prompt.ts
13300
- /** The JSON Schema the agent's last message follows (strict, as Codex's --output-schema needs). */
13301
- const OUTCOME_SCHEMA = {
13302
- type: "object",
13303
- additionalProperties: false,
13304
- required: [
13305
- "status",
13306
- "summary",
13307
- "prTitle",
13308
- "question"
13309
- ],
13310
- properties: {
13311
- status: {
13312
- type: "string",
13313
- enum: ["done", "blocked"],
13314
- description: "done: the task is done; blocked: it can't go on without an answer"
13315
- },
13316
- summary: {
13317
- type: "string",
13318
- description: "What you changed and how you checked it, in a few sentences of Markdown"
13319
- },
13320
- prTitle: {
13321
- type: "string",
13322
- description: "A pull request title, under 70 characters"
13323
- },
13324
- question: {
13325
- type: "string",
13326
- description: "When blocked, what you need to know; otherwise empty"
13327
- }
13328
- }
13329
- };
13330
- /** The outcome in an agent's answer: the JSON itself, or the last JSON object in its text. */
13331
- function parseOutcome(value) {
13332
- let v = value;
13333
- if (typeof v === "string") {
13334
- const text = v.trim();
13335
- const candidates = [text, ...[...text.matchAll(/```(?:json)?\s*([\s\S]*?)```/g)].map((m) => m[1] ?? "")];
13336
- const open = text.lastIndexOf("{", text.lastIndexOf("\"status\""));
13337
- if (open >= 0) candidates.push(text.slice(open, text.lastIndexOf("}") + 1));
13338
- v = null;
13339
- for (const c of candidates.reverse()) try {
13340
- const parsed = JSON.parse(c);
13341
- if (parsed && typeof parsed === "object") {
13342
- v = parsed;
13343
- break;
13344
- }
13345
- } catch {}
13346
- }
13347
- if (!v || typeof v !== "object") return null;
13348
- const o = v;
13349
- if (o.status !== "done" && o.status !== "blocked") return null;
13350
- const str = (x) => typeof x === "string" ? x.trim() : "";
13351
- return {
13352
- status: o.status,
13353
- summary: str(o.summary),
13354
- prTitle: str(o.prTitle),
13355
- question: str(o.question)
13356
- };
13357
- }
13358
- /** The prompt for `task`, on `branch`. */
13359
- function buildPrompt({ task, comments, branch }) {
13360
- const lines = [
13361
- `You're working on ${task.ref}, "${task.title}", a task from the team's monoban board.`,
13362
- "",
13363
- "## The task",
13364
- "",
13365
- task.description.trim() || "(no description: the title is all there is)"
13485
+ /** The prompt for `task`, on `branch`. */
13486
+ function buildPrompt({ task, comments, branch }) {
13487
+ const lines = [
13488
+ `You're working on ${task.ref}, "${task.title}", a task from the team's monoban board.`,
13489
+ "",
13490
+ "## The task",
13491
+ "",
13492
+ task.description.trim() || "(no description: the title is all there is)"
13366
13493
  ];
13367
13494
  if (comments.length) {
13368
13495
  lines.push("", "## Its latest comments, oldest first", "");
@@ -13486,7 +13613,7 @@ function redact(text) {
13486
13613
  return SECRETS.reduce((t, [pattern, by]) => t.replace(pattern, by), text);
13487
13614
  }
13488
13615
  /** A message the API takes (and the board shows), secrets out. */
13489
- function clip(text, max = 2e3) {
13616
+ function clip$1(text, max = 2e3) {
13490
13617
  const clean = redact(text).trim();
13491
13618
  return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;
13492
13619
  }
@@ -13562,7 +13689,7 @@ function codingAgent({ spec, command, args: extra = [], board, env = process.env
13562
13689
  step,
13563
13690
  attempt: 1,
13564
13691
  status,
13565
- ...message && { message: clip(message) },
13692
+ ...message && { message: clip$1(message) },
13566
13693
  data: {
13567
13694
  durationMs: Date.now() - started,
13568
13695
  ...data
@@ -13571,7 +13698,7 @@ function codingAgent({ spec, command, args: extra = [], board, env = process.env
13571
13698
  };
13572
13699
  const warn = (message) => report.event({
13573
13700
  kind: "warning",
13574
- message: clip(message)
13701
+ message: clip$1(message)
13575
13702
  });
13576
13703
  /** Says on the task how it went; a failure to is a warning, not the run's ending. */
13577
13704
  let ref = run.ref;
@@ -13607,7 +13734,7 @@ function codingAgent({ spec, command, args: extra = [], board, env = process.env
13607
13734
  });
13608
13735
  if (moved) report.event({
13609
13736
  kind: "board",
13610
- message: clip(moved)
13737
+ message: clip$1(moved)
13611
13738
  });
13612
13739
  prompt = buildPrompt({
13613
13740
  task,
@@ -13616,7 +13743,7 @@ function codingAgent({ spec, command, args: extra = [], board, env = process.env
13616
13743
  });
13617
13744
  end("ok");
13618
13745
  } catch (err) {
13619
- const reason = clip(`Couldn't get the folder ready: ${err.message}`, 1e3);
13746
+ const reason = clip$1(`Couldn't get the folder ready: ${err.message}`, 1e3);
13620
13747
  end("failed", reason);
13621
13748
  return {
13622
13749
  status: "failed",
@@ -13632,7 +13759,7 @@ function codingAgent({ spec, command, args: extra = [], board, env = process.env
13632
13759
  if (limited) report.event({
13633
13760
  kind: "warning",
13634
13761
  step: "code",
13635
- message: clip(limited.warning)
13762
+ message: clip$1(limited.warning)
13636
13763
  });
13637
13764
  const asked = limited ? {
13638
13765
  ...run,
@@ -13646,14 +13773,14 @@ function codingAgent({ spec, command, args: extra = [], board, env = process.env
13646
13773
  const activity = throttled((message) => report.event({
13647
13774
  kind: "activity",
13648
13775
  step: "code",
13649
- message: clip(message, 200)
13776
+ message: clip$1(message, 200)
13650
13777
  }), activityMs);
13651
13778
  const out = {
13652
13779
  activity: (m) => m.trim() && activity.push(m),
13653
13780
  warning: (m) => report.event({
13654
13781
  kind: "warning",
13655
13782
  step: "code",
13656
- message: clip(m)
13783
+ message: clip$1(m)
13657
13784
  }),
13658
13785
  externalId: (id) => report.update({ externalId: id.slice(0, 128) })
13659
13786
  };
@@ -13700,7 +13827,7 @@ function codingAgent({ spec, command, args: extra = [], board, env = process.env
13700
13827
  }
13701
13828
  if (exit.spawnError) return {
13702
13829
  status: "failed",
13703
- reason: clip(exit.spawnError, 1e3)
13830
+ reason: clip$1(exit.spawnError, 1e3)
13704
13831
  };
13705
13832
  end = begin("commit");
13706
13833
  const unfinished = cancelled || failure !== null;
@@ -13724,195 +13851,859 @@ function codingAgent({ spec, command, args: extra = [], board, env = process.env
13724
13851
  reason: commits ? `Cancelled; its work so far is on ${branch}.` : null
13725
13852
  };
13726
13853
  if (failure) {
13727
- await tell(`${label} couldn't finish: ${clip(failure, 1e3)}${kept}`);
13854
+ await tell(`${label} couldn't finish: ${clip$1(failure, 1e3)}${kept}`);
13728
13855
  return {
13729
13856
  status: "failed",
13730
- reason: clip(failure, 1e3)
13857
+ reason: clip$1(failure, 1e3)
13731
13858
  };
13732
13859
  }
13733
13860
  if (outcome?.status === "blocked") {
13734
13861
  const question = outcome.question || outcome.summary || "It got stuck without saying why.";
13735
13862
  report.event({
13736
13863
  kind: "question",
13737
- message: clip(question)
13864
+ message: clip$1(question)
13738
13865
  });
13739
- await tell(`${label} needs an answer: ${clip(question, 1500)}${kept}`);
13866
+ await tell(`${label} needs an answer: ${clip$1(question, 1500)}${kept}`);
13740
13867
  return {
13741
13868
  status: "needs_human",
13742
- reason: clip(question, 1e3)
13869
+ reason: clip$1(question, 1e3)
13743
13870
  };
13744
13871
  }
13745
13872
  const summary = outcome?.summary || (typeof result.answer === "string" ? result.answer : "");
13746
13873
  if (!commits) {
13747
13874
  const reason = `${label} changed nothing${summary ? `: ${summary}` : "."}`;
13748
- await tell(`${label} made no changes.${summary ? `\n\n${clip(summary, 1500)}` : ""}`);
13875
+ await tell(`${label} made no changes.${summary ? `\n\n${clip$1(summary, 1500)}` : ""}`);
13749
13876
  return {
13750
13877
  status: "needs_human",
13751
- reason: clip(reason, 1e3)
13878
+ reason: clip$1(reason, 1e3)
13879
+ };
13880
+ }
13881
+ let url = null;
13882
+ const prTitle = clip$1(outcome?.prTitle || `${ref}: ${title}`, 200);
13883
+ if (run.options.pr === "none") begin("pr")("skipped", `none asked for: the work is on ${branch}`);
13884
+ else {
13885
+ end = begin("push");
13886
+ try {
13887
+ await ws.push(branch);
13888
+ end("ok");
13889
+ end = begin("pr");
13890
+ url = await ws.pullRequestOf(branch) ?? await ws.openPullRequest({
13891
+ base,
13892
+ branch,
13893
+ title: prTitle,
13894
+ body: `${clip$1(summary || prTitle, 6e3)}\n\n---\n${ref} · by ${label}, through \`monoban runner\``,
13895
+ draft: run.options.pr === "draft"
13896
+ });
13897
+ report.update({ prUrl: url });
13898
+ report.event({
13899
+ kind: "pr_opened",
13900
+ step: "pr",
13901
+ message: url,
13902
+ data: { url }
13903
+ });
13904
+ end("ok");
13905
+ } catch (err) {
13906
+ const reason = clip$1(err.message, 1e3);
13907
+ end("failed", reason);
13908
+ await tell(`${label} finished, but couldn't put it up for review: ${reason}${kept}`);
13909
+ return {
13910
+ status: "failed",
13911
+ reason
13912
+ };
13913
+ }
13914
+ }
13915
+ end = begin("report");
13916
+ try {
13917
+ if (url) await board.attach(ref, url, prTitle, run.options.pr === "draft");
13918
+ await board.comment(ref, `${label} finished${url ? `: ${url}` : `, on the branch \`${branch}\``}.${summary ? `\n\n${clip$1(summary, 6e3)}` : ""}`);
13919
+ report.event({
13920
+ kind: "board",
13921
+ message: url ? "attached the pull request, and commented" : "commented"
13922
+ });
13923
+ end("ok");
13924
+ } catch (err) {
13925
+ end("failed", err.message);
13926
+ }
13927
+ return {
13928
+ status: "succeeded",
13929
+ reason: null
13930
+ };
13931
+ };
13932
+ return {
13933
+ done: flow().catch((err) => ({
13934
+ status: "failed",
13935
+ reason: clip$1(`The run stopped: ${err.message}`, 1e3)
13936
+ })),
13937
+ cancel: async () => {
13938
+ cancelled = true;
13939
+ agent?.stop();
13940
+ }
13941
+ };
13942
+ }
13943
+ };
13944
+ }
13945
+ //#endregion
13946
+ //#region src/runner/agents/claude.ts
13947
+ /**
13948
+ * Claude Code, unattended: `claude -p --output-format stream-json --verbose` with the prompt on stdin. Auto
13949
+ * mode has a classifier review each action instead of a person, and `--permission-prompts none` denies what
13950
+ * would still need one (so nothing waits). It ends with a `result` line: the cost, and the outcome shaped by
13951
+ * --json-schema. It loads the folder's CLAUDE.md, settings and MCP servers, as a session there would.
13952
+ */
13953
+ /** The oldest Claude Code with --permission-prompts. */
13954
+ const CLAUDE_MINIMUM = "2.1.259";
13955
+ /** "edit src/a.ts", "$ pnpm test", "subagent: review the diff": a tool call in a few words. */
13956
+ function describeTool(name, input = {}, roots = []) {
13957
+ const path = (key) => relativeTo(roots, input[key]);
13958
+ switch (name) {
13959
+ case "Edit":
13960
+ case "MultiEdit": return `edit ${path("file_path")}`;
13961
+ case "NotebookEdit": return `edit ${path("notebook_path")}`;
13962
+ case "Write": return `write ${path("file_path")}`;
13963
+ case "Read": return `read ${path("file_path")}`;
13964
+ case "Bash": return `$ ${firstLine(input.command)}`;
13965
+ case "Grep": return `search ${JSON.stringify(input.pattern ?? "")}`;
13966
+ case "Glob": return `find ${String(input.pattern ?? "")}`;
13967
+ case "Agent":
13968
+ case "Task": return `subagent: ${String(input.description ?? input.subagent_type ?? "")}`;
13969
+ case "TodoWrite": return planLine((Array.isArray(input.todos) ? input.todos : []).map((t) => ({ done: t.status === "completed" })));
13970
+ case "WebFetch": return `fetch ${String(input.url ?? "")}`;
13971
+ case "WebSearch": return `search the web: ${String(input.query ?? "")}`;
13972
+ default: return name.startsWith("mcp__") ? name.split("__").slice(1).join(": ") : name;
13973
+ }
13974
+ }
13975
+ /** Why a `result` line says it didn't succeed. */
13976
+ function failureOf(line) {
13977
+ const subtype = line.subtype ?? "";
13978
+ if (subtype.includes("budget")) return "It reached its budget.";
13979
+ if (subtype.includes("max_turns")) return "It reached its turn limit.";
13980
+ const said = typeof line.result === "string" && line.result.trim() ? line.result.trim().split("\n")[0] : null;
13981
+ return `It stopped${subtype && subtype !== "success" ? ` (${subtype.replace(/_/g, " ")})` : ""}${said ? `: ${said}` : "."}`;
13982
+ }
13983
+ function claudeReader(roots) {
13984
+ let answer = null;
13985
+ let lastText = null;
13986
+ let costUsd = null;
13987
+ let failure = null;
13988
+ let ended = false;
13989
+ return {
13990
+ line(text, out) {
13991
+ if (!text.trim().startsWith("{")) return;
13992
+ const line = JSON.parse(text);
13993
+ switch (line.type) {
13994
+ case "system":
13995
+ if (line.subtype === "init") {
13996
+ if (line.session_id) out.externalId(line.session_id);
13997
+ out.activity(line.model ? `started (${line.model})` : "started");
13998
+ } else if (line.subtype === "api_retry") out.activity(`retrying: ${line.error ?? "the API"}${line.attempt ? ` (attempt ${line.attempt})` : ""}`);
13999
+ return;
14000
+ case "assistant":
14001
+ for (const c of line.message?.content ?? []) if (c.type === "tool_use" && c.name) {
14002
+ if (c.name !== "StructuredOutput") out.activity(describeTool(c.name, c.input, roots));
14003
+ } else if (c.type === "text" && c.text?.trim()) lastText = c.text;
14004
+ return;
14005
+ case "result": {
14006
+ ended = true;
14007
+ if (typeof line.total_cost_usd === "number") costUsd = line.total_cost_usd;
14008
+ answer = line.structured_output ?? line.result ?? lastText;
14009
+ if (line.is_error || line.subtype && line.subtype !== "success") failure = failureOf(line);
14010
+ const denied = new Set((line.permission_denials ?? []).map((d) => describeTool(d.tool_name ?? "a tool", d.tool_input, roots)));
14011
+ for (const what of [...denied].slice(0, 3)) out.warning(`Not allowed: ${what}`);
14012
+ return;
14013
+ }
14014
+ }
14015
+ },
14016
+ result: () => ({
14017
+ answer: ended ? answer : lastText,
14018
+ costUsd,
14019
+ tokens: null,
14020
+ failure
14021
+ })
14022
+ };
14023
+ }
14024
+ const claude = {
14025
+ name: "claude",
14026
+ args: (run, { schema }, extra) => [
14027
+ "-p",
14028
+ "--output-format",
14029
+ "stream-json",
14030
+ "--verbose",
14031
+ "--permission-mode",
14032
+ "auto",
14033
+ "--permission-prompts",
14034
+ "none",
14035
+ "--json-schema",
14036
+ schema,
14037
+ ...run.options.budgetUsd !== void 0 ? ["--max-budget-usd", String(run.options.budgetUsd)] : [],
14038
+ ...run.options.model ? ["--model", run.options.model] : [],
14039
+ ...extra
14040
+ ],
14041
+ reader: claudeReader
14042
+ };
14043
+ const AGENT_NAMES$1 = Object.keys(AGENTS$1);
14044
+ const isAgent = (name) => AGENT_NAMES$1.includes(name);
14045
+ /** What's wrong with runner.json's contents, or null. */
14046
+ function fileProblem(v) {
14047
+ if (!v || typeof v !== "object" || Array.isArray(v)) return "it should be an object";
14048
+ const f = v;
14049
+ const known = [
14050
+ "name",
14051
+ "pollSeconds",
14052
+ "allow",
14053
+ "confirm",
14054
+ "agents",
14055
+ "adapters"
14056
+ ];
14057
+ const unknown = Object.keys(f).find((k) => !known.includes(k));
14058
+ if (unknown) return `${unknown} isn't a setting (${known.join(", ")})`;
14059
+ if (f.name !== void 0 && (typeof f.name !== "string" || !f.name.trim() || f.name.length > 64)) return "name: 1 to 64 characters";
14060
+ if (f.pollSeconds !== void 0 && !(Number.isInteger(f.pollSeconds) && f.pollSeconds >= 1 && f.pollSeconds <= 60)) return "pollSeconds: a whole number of seconds, 1 to 60";
14061
+ if (f.allow !== void 0 && !(Array.isArray(f.allow) && f.allow.every((p) => typeof p === "string" && p.startsWith("/")))) return "allow: a list of absolute paths";
14062
+ if (f.confirm !== void 0 && typeof f.confirm !== "boolean") return "confirm: true or false";
14063
+ if (f.agents !== void 0) {
14064
+ if (!Array.isArray(f.agents) || !f.agents.every((a) => typeof a === "string" && isAgent(a))) return `agents: a list of ${AGENT_NAMES$1.join(", ")}`;
14065
+ }
14066
+ if (f.adapters !== void 0) {
14067
+ if (!f.adapters || typeof f.adapters !== "object" || Array.isArray(f.adapters)) return "adapters: an object";
14068
+ for (const [name, value] of Object.entries(f.adapters)) {
14069
+ if (!isAgent(name)) return `adapters.${name}: monoban doesn't run ${name} (${AGENT_NAMES$1.join(", ")})`;
14070
+ const agent = value ?? {};
14071
+ const settings = [
14072
+ "command",
14073
+ "args",
14074
+ ...name === "codex" ? ["allowFullAccess"] : name === "agentpipe" ? ["budgetUsd"] : []
14075
+ ];
14076
+ const extra = Object.keys(agent).find((k) => !settings.includes(k));
14077
+ if (extra) return `adapters.${name}.${extra} isn't a setting (${settings.join(", ")})`;
14078
+ if (agent.allowFullAccess !== void 0 && typeof agent.allowFullAccess !== "boolean") return `adapters.${name}.allowFullAccess: true or false`;
14079
+ if (agent.budgetUsd !== void 0 && !(typeof agent.budgetUsd === "number" && agent.budgetUsd >= .1 && agent.budgetUsd <= 1e3)) return `adapters.${name}.budgetUsd: US dollars, 0.1 to 1000`;
14080
+ if (agent.command !== void 0 && (typeof agent.command !== "string" || !agent.command)) return `adapters.${name}.command: a command`;
14081
+ if (agent.args !== void 0 && !(Array.isArray(agent.args) && agent.args.every((a) => typeof a === "string"))) return `adapters.${name}.args: a list of arguments`;
14082
+ }
14083
+ }
14084
+ return null;
14085
+ }
14086
+ const RUNNER_FILE = "runner.json";
14087
+ async function readSettingsFile(dir) {
14088
+ const path = join(dir, RUNNER_FILE);
14089
+ let text;
14090
+ try {
14091
+ text = await readFile(path, "utf8");
14092
+ } catch {
14093
+ return {};
14094
+ }
14095
+ let parsed;
14096
+ try {
14097
+ parsed = JSON.parse(text);
14098
+ } catch {
14099
+ throw new CliError(`${path} isn't JSON.`, EXIT.usage);
14100
+ }
14101
+ const problem = fileProblem(parsed);
14102
+ if (problem) throw new CliError(`${path}: ${problem}.`, EXIT.usage);
14103
+ return parsed;
14104
+ }
14105
+ /** --agents claude,codex. */
14106
+ function agentsFlag(value) {
14107
+ const names = value.split(",").map((a) => a.trim().toLowerCase()).filter(Boolean);
14108
+ const unknown = names.find((a) => !isAgent(a));
14109
+ if (unknown || !names.length) throw new CliError(`--agents takes ${AGENT_NAMES$1.join(", ")} (comma-separated)${unknown ? `, not ${unknown}` : ""}.`, EXIT.usage);
14110
+ return names;
14111
+ }
14112
+ async function runnerSettings(dir, flags, env, hostname) {
14113
+ const file = await readSettingsFile(dir);
14114
+ let pollSeconds = file.pollSeconds ?? 3;
14115
+ if (flags.interval !== void 0) {
14116
+ pollSeconds = Number(flags.interval);
14117
+ if (!Number.isInteger(pollSeconds) || pollSeconds < 1 || pollSeconds > 60) throw new CliError("--interval is how often to ask for work, in seconds: 1 to 60.", EXIT.usage);
14118
+ }
14119
+ const allow = [...file.allow ?? [], ...flags.allow ?? []];
14120
+ const relative = allow.find((p) => !p.startsWith("/"));
14121
+ if (relative) throw new CliError(`--allow takes absolute paths (${relative} isn't one).`, EXIT.usage);
14122
+ const commands = {};
14123
+ const args = {};
14124
+ for (const name of AGENT_NAMES$1) {
14125
+ commands[name] = env[`MONOBAN_${name.toUpperCase()}`] || file.adapters?.[name]?.command || (name === "agentpipe" && existsSync(agentpipeBin(env)) ? agentpipeBin(env) : name);
14126
+ args[name] = file.adapters?.[name]?.args ?? [];
14127
+ }
14128
+ return {
14129
+ name: flags.name?.trim() || file.name || hostname,
14130
+ pollSeconds,
14131
+ allow,
14132
+ confirm: flags.confirm ?? file.confirm ?? false,
14133
+ agents: flags.agents !== void 0 ? agentsFlag(flags.agents) : file.agents ?? null,
14134
+ commands,
14135
+ args,
14136
+ allowFullAccess: flags.allowFullAccess ?? file.adapters?.codex?.allowFullAccess ?? false,
14137
+ agentpipeBudgetUsd: file.adapters?.agentpipe?.budgetUsd ?? 10
14138
+ };
14139
+ }
14140
+ //#endregion
14141
+ //#region src/commands/doctor.ts
14142
+ const MARKS = {
14143
+ ok: "✓",
14144
+ warn: "!",
14145
+ fail: "✗"
14146
+ };
14147
+ async function checks(ctx, deps = {}) {
14148
+ const version = deps.version ?? versionOf;
14149
+ const env = ctx.env;
14150
+ const found = [];
14151
+ const latest = await (deps.latest ?? latestVersion)(ctx);
14152
+ const upgrade = UPGRADE[thisInstall()].command;
14153
+ found.push(latest && newer(latest, "1.6.0") ? {
14154
+ name: "monoban",
14155
+ status: "warn",
14156
+ detail: `${VERSION}; ${latest} is out`,
14157
+ fix: upgrade
14158
+ } : {
14159
+ name: "monoban",
14160
+ status: "ok",
14161
+ detail: latest ? `${VERSION} (the latest)` : VERSION
14162
+ });
14163
+ try {
14164
+ const me = await unwrap(apis(ctx).signedIn.GET("/v1/me"));
14165
+ found.push({
14166
+ name: "sign-in",
14167
+ status: "ok",
14168
+ detail: me.email ?? me.id
14169
+ });
14170
+ } catch (err) {
14171
+ if (err instanceof NotSignedIn || err instanceof ApiProblem && err.status === 401) found.push({
14172
+ name: "sign-in",
14173
+ status: "fail",
14174
+ detail: "not signed in",
14175
+ fix: "monoban login"
14176
+ });
14177
+ else found.push({
14178
+ name: "sign-in",
14179
+ status: "warn",
14180
+ detail: `can't reach ${ctx.apiUrl} (${err.message})`
14181
+ });
14182
+ }
14183
+ let settings = null;
14184
+ try {
14185
+ settings = await runnerSettings(configDir(ctx.env), {}, ctx.env, deviceName());
14186
+ } catch (err) {
14187
+ found.push({
14188
+ name: "runner.json",
14189
+ status: "fail",
14190
+ detail: err.message
14191
+ });
14192
+ }
14193
+ const pipe = await (deps.agentpipe ?? agentpipeStatus)(ctx.env);
14194
+ const command = settings?.commands.agentpipe ?? "agentpipe";
14195
+ if (command !== "agentpipe" && command !== agentpipeBin(ctx.env)) {
14196
+ const v = await version(command, env);
14197
+ found.push(v ? {
14198
+ name: "agentpipe",
14199
+ status: "ok",
14200
+ detail: `${v} (${command}, the runner's)`
14201
+ } : {
14202
+ name: "agentpipe",
14203
+ status: "warn",
14204
+ detail: `${command} doesn't answer --version`
14205
+ });
14206
+ } else {
14207
+ const onPath = pipe.installed ? null : await version("agentpipe", env);
14208
+ const said = describeStatus(pipe);
14209
+ if (onPath && !newer(pipe.pinned, onPath)) found.push({
14210
+ name: "agentpipe",
14211
+ status: "ok",
14212
+ detail: `${onPath} (on PATH)`
14213
+ });
14214
+ else if (onPath) {
14215
+ const detail = `${onPath} (on PATH); this monoban comes with ${pipe.pinned}`;
14216
+ found.push({
14217
+ name: "agentpipe",
14218
+ status: "warn",
14219
+ detail,
14220
+ fix: "monoban agentpipe install"
14221
+ });
14222
+ } else found.push({
14223
+ name: "agentpipe",
14224
+ status: said.ok ? "ok" : "warn",
14225
+ detail: said.text,
14226
+ ...said.fix && { fix: said.fix }
14227
+ });
14228
+ }
14229
+ const agents = [{
14230
+ name: "claude",
14231
+ minimum: CLAUDE_MINIMUM,
14232
+ update: "claude update"
14233
+ }, {
14234
+ name: "codex",
14235
+ minimum: null,
14236
+ update: null
14237
+ }];
14238
+ for (const agent of agents) {
14239
+ const v = await version(settings?.commands[agent.name] ?? agent.name, env);
14240
+ const label = agentLabel(agent.name);
14241
+ if (!v) found.push({
14242
+ name: label,
14243
+ status: "warn",
14244
+ detail: "not installed (the runner offers it once it is)"
14245
+ });
14246
+ else if (agent.minimum && !atLeast(v, agent.minimum)) found.push({
14247
+ name: label,
14248
+ status: "warn",
14249
+ detail: `${v}; the runner needs ${agent.minimum}`,
14250
+ fix: agent.update ?? ""
14251
+ });
14252
+ else found.push({
14253
+ name: label,
14254
+ status: "ok",
14255
+ detail: v
14256
+ });
14257
+ }
14258
+ const git = await version("git", env);
14259
+ found.push(git ? {
14260
+ name: "git",
14261
+ status: "ok",
14262
+ detail: git
14263
+ } : {
14264
+ name: "git",
14265
+ status: "fail",
14266
+ detail: "not installed"
14267
+ });
14268
+ const gh = await version("gh", env);
14269
+ found.push(gh ? {
14270
+ name: "gh",
14271
+ status: "ok",
14272
+ detail: gh
14273
+ } : {
14274
+ name: "gh",
14275
+ status: "warn",
14276
+ detail: "not installed: runs can't open pull requests",
14277
+ fix: "https://cli.github.com"
14278
+ });
14279
+ return found;
14280
+ }
14281
+ /** `monoban doctor`. */
14282
+ async function doctor(ctx, options, deps = {}) {
14283
+ const found = await checks(ctx, deps);
14284
+ if (options.json) ctx.out(JSON.stringify({ checks: found }, null, 2));
14285
+ else {
14286
+ const width = Math.max(...found.map((c) => c.name.length));
14287
+ for (const c of found) ctx.out(`${MARKS[c.status]} ${c.name.padEnd(width)} ${c.detail}${c.fix ? `: ${c.fix}` : ""}`);
14288
+ }
14289
+ if (found.some((c) => c.status === "fail")) throw new CliError("", EXIT.error);
14290
+ }
14291
+ //#endregion
14292
+ //#region src/commands/notes.ts
14293
+ const printNotes = (ctx, key, notes) => ctx.out(JSON.stringify({
14294
+ project: key,
14295
+ ...notes
14296
+ }, null, 2));
14297
+ /** `monoban notes`: the project's notes as they are, for reading, a pager or a pipe. */
14298
+ async function notesShow(ctx, options) {
14299
+ const api = apis(ctx).signedIn;
14300
+ const key = await resolveProject(ctx, api, options.project);
14301
+ const notes = await unwrap(api.GET("/v1/projects/{key}/notes", { params: { path: { key } } }));
14302
+ if (options.json) return printNotes(ctx, key, notes);
14303
+ if (!notes.text) {
14304
+ ctx.err(`${key} has no notes yet. Add a line with \`monoban notes add …\`, or write them with \`monoban notes edit\`.`);
14305
+ return;
14306
+ }
14307
+ ctx.out(notes.text.replace(/\n$/, ""));
14308
+ }
14309
+ /** `monoban notes add TEXT…`: a line at the end of the notes (`-` reads it from stdin). */
14310
+ async function notesAdd(ctx, words, options) {
14311
+ const text = words.length === 1 && words[0] === "-" ? (await ctx.readStdin()).replace(/\n$/, "") : words.join(" ");
14312
+ if (!text.trim()) throw new CliError("Nothing to add: give the text, or - to read it from stdin.", EXIT.usage);
14313
+ const api = apis(ctx).signedIn;
14314
+ const key = await resolveProject(ctx, api, options.project);
14315
+ const notes = await unwrap(api.PATCH("/v1/projects/{key}/notes", {
14316
+ params: { path: { key } },
14317
+ body: { append: text }
14318
+ }));
14319
+ if (options.json) return printNotes(ctx, key, notes);
14320
+ ctx.out(`Added to the notes of ${key}.`);
14321
+ }
14322
+ /** `monoban notes edit`: the notes in $EDITOR, saved only if nobody changed them in the meantime. */
14323
+ async function notesEdit(ctx, options) {
14324
+ const api = apis(ctx).signedIn;
14325
+ const key = await resolveProject(ctx, api, options.project);
14326
+ const notes = await unwrap(api.GET("/v1/projects/{key}/notes", { params: { path: { key } } }));
14327
+ const text = await ctx.edit(notes.text, `${key}-notes`);
14328
+ if (text === notes.text) {
14329
+ ctx.err(`No changes to the notes of ${key}.`);
14330
+ return;
14331
+ }
14332
+ let saved;
14333
+ try {
14334
+ saved = await unwrap(api.PATCH("/v1/projects/{key}/notes", {
14335
+ params: {
14336
+ path: { key },
14337
+ header: ifMatch(notes.version)
14338
+ },
14339
+ body: { text }
14340
+ }));
14341
+ } catch (err) {
14342
+ const draft = await keepDraft(text, `${key}-notes`);
14343
+ ctx.err(`Your text is saved in ${draft}.`);
14344
+ if (err instanceof ApiProblem && err.status === 412) throw new CliError(`The notes of ${key} changed elsewhere in the meantime. Run \`monoban notes edit\` again.`);
14345
+ throw err;
14346
+ }
14347
+ if (options.json) return printNotes(ctx, key, saved);
14348
+ ctx.out(`Updated the notes of ${key}.`);
14349
+ }
14350
+ //#endregion
14351
+ //#region src/runner/agents/agentpipe.ts
14352
+ /** agentpipe's step statuses that monoban has too; the others (budget_exceeded, max_turns…) are failures. */
14353
+ const SAME = [
14354
+ "ok",
14355
+ "failed",
14356
+ "skipped",
14357
+ "cancelled",
14358
+ "needs_human"
14359
+ ];
14360
+ const RUN_ENDINGS = {
14361
+ ok: "succeeded",
14362
+ needs_human: "needs_human",
14363
+ cancelled: "cancelled",
14364
+ nothing_to_do: "succeeded"
14365
+ };
14366
+ /** How agentpipe's own endings read, before its reason. */
14367
+ const SAYS = {
14368
+ refused: "It couldn't start",
14369
+ nothing_to_do: "There was nothing to do"
14370
+ };
14371
+ const str = (v) => typeof v === "string" && v.trim() ? v.trim() : null;
14372
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
14373
+ /** A message the API takes: one line or more, at most 2000 characters. */
14374
+ const clip = (text) => text.length > 2e3 ? `${text.slice(0, 1999)}…` : text;
14375
+ /**
14376
+ * Turns agentpipe's events into monoban's, one at a time, remembering what it needs across them. agentpipe ends
14377
+ * each step twice: first with what the step decided (a skip says `skipped`, with its reason), then with what it
14378
+ * cost (`turns`, `cost_usd`). They become one step_finished, sent when the second arrives (or the next step
14379
+ * starts, or the run ends, if it never does).
14380
+ */
14381
+ function agentpipeMapper(report) {
14382
+ const started = /* @__PURE__ */ new Set();
14383
+ const attempts = /* @__PURE__ */ new Map();
14384
+ let pending = null;
14385
+ let total = 0;
14386
+ let ending = null;
14387
+ const flush = (cost) => {
14388
+ if (!pending) return;
14389
+ const { step, attempt, status, message, at } = pending;
14390
+ pending = null;
14391
+ const data = {};
14392
+ if (cost?.durationMs != null) data.durationMs = cost.durationMs;
14393
+ if (cost?.costUsd != null) data.costUsd = cost.costUsd;
14394
+ report.event({
14395
+ kind: "step_finished",
14396
+ step,
14397
+ attempt,
14398
+ status,
14399
+ ...message && { message: clip(message) },
14400
+ ...Object.keys(data).length && { data },
14401
+ ...at && { at }
14402
+ });
14403
+ };
14404
+ const stepStatus = (raw) => {
14405
+ const s = str(raw) ?? "ok";
14406
+ return SAME.includes(s) ? {
14407
+ status: s,
14408
+ note: null
14409
+ } : {
14410
+ status: "failed",
14411
+ note: s.replace(/_/g, " ")
14412
+ };
14413
+ };
14414
+ /** Feed it one event; answers how the run ended once agentpipe said so. */
14415
+ const take = (e) => {
14416
+ const d = e.data ?? {};
14417
+ const at = str(e.ts) ?? void 0;
14418
+ const step = str(e.step);
14419
+ switch (e.kind) {
14420
+ case "run.start": {
14421
+ const id = str(d.run_id) ?? str(e.run_id);
14422
+ if (id) report.update({ externalId: id });
14423
+ return;
14424
+ }
14425
+ case "step.start": {
14426
+ if (!step) return;
14427
+ const attempt = num(d.attempt) ?? attempts.get(step) ?? 1;
14428
+ const key = `${step}@${attempt}`;
14429
+ if (started.has(key)) return;
14430
+ if (pending && pending.step !== step) flush();
14431
+ started.add(key);
14432
+ attempts.set(step, attempt);
14433
+ report.event({
14434
+ kind: "step_started",
14435
+ step,
14436
+ attempt,
14437
+ status: "running",
14438
+ ...at && { at }
14439
+ });
14440
+ return;
14441
+ }
14442
+ case "step.end": {
14443
+ if (!step) return;
14444
+ const attempt = num(d.attempt) ?? attempts.get(step) ?? 1;
14445
+ const { status, note } = stepStatus(d.status);
14446
+ const reason = str(d.reason) ?? str(d.error) ?? note;
14447
+ const costShaped = "turns" in d || "cost_usd" in d;
14448
+ if (!pending || pending.step !== step) {
14449
+ flush();
14450
+ pending = {
14451
+ step,
14452
+ attempt,
14453
+ status,
14454
+ message: reason,
14455
+ ...at && { at }
13752
14456
  };
14457
+ } else {
14458
+ if (pending.status === "ok" && status !== "ok") pending.status = status;
14459
+ pending.message = pending.message ?? reason;
14460
+ if (at) pending.at = at;
13753
14461
  }
13754
- let url = null;
13755
- const prTitle = clip(outcome?.prTitle || `${ref}: ${title}`, 200);
13756
- if (run.options.pr === "none") begin("pr")("skipped", `none asked for: the work is on ${branch}`);
13757
- else {
13758
- end = begin("push");
13759
- try {
13760
- await ws.push(branch);
13761
- end("ok");
13762
- end = begin("pr");
13763
- url = await ws.pullRequestOf(branch) ?? await ws.openPullRequest({
13764
- base,
13765
- branch,
13766
- title: prTitle,
13767
- body: `${clip(summary || prTitle, 6e3)}\n\n---\n${ref} · by ${label}, through \`monoban runner\``,
13768
- draft: run.options.pr === "draft"
13769
- });
13770
- report.update({ prUrl: url });
13771
- report.event({
13772
- kind: "pr_opened",
13773
- step: "pr",
13774
- message: url,
13775
- data: { url }
13776
- });
13777
- end("ok");
13778
- } catch (err) {
13779
- const reason = clip(err.message, 1e3);
13780
- end("failed", reason);
13781
- await tell(`${label} finished, but couldn't put it up for review: ${reason}${kept}`);
13782
- return {
13783
- status: "failed",
13784
- reason
13785
- };
14462
+ if (costShaped) {
14463
+ const costUsd = num(d.cost_usd);
14464
+ if (costUsd) {
14465
+ total += costUsd;
14466
+ report.update({ costUsd: Math.round(total * 1e4) / 1e4 });
13786
14467
  }
13787
- }
13788
- end = begin("report");
13789
- try {
13790
- if (url) await board.attach(ref, url, prTitle, run.options.pr === "draft");
13791
- await board.comment(ref, `${label} finished${url ? `: ${url}` : `, on the branch \`${branch}\``}.${summary ? `\n\n${clip(summary, 6e3)}` : ""}`);
13792
- report.event({
13793
- kind: "board",
13794
- message: url ? "attached the pull request, and commented" : "commented"
14468
+ flush({
14469
+ durationMs: num(d.duration_ms),
14470
+ costUsd
13795
14471
  });
13796
- end("ok");
13797
- } catch (err) {
13798
- end("failed", err.message);
13799
14472
  }
13800
- return {
13801
- status: "succeeded",
13802
- reason: null
14473
+ return;
14474
+ }
14475
+ case "pr.created": {
14476
+ const url = str(d.url);
14477
+ if (!url) return;
14478
+ report.update({ prUrl: url });
14479
+ report.event({
14480
+ kind: "pr_opened",
14481
+ ...step && { step },
14482
+ message: url,
14483
+ data: {
14484
+ url,
14485
+ ...num(d.number) !== null && { number: num(d.number) }
14486
+ },
14487
+ ...at && { at }
14488
+ });
14489
+ return;
14490
+ }
14491
+ case "issue.updated": {
14492
+ const change = str(d.change);
14493
+ if (change) report.event({
14494
+ kind: "board",
14495
+ message: clip(change),
14496
+ ...at && { at }
14497
+ });
14498
+ return;
14499
+ }
14500
+ case "issue.comment": {
14501
+ const milestone = str(d.milestone);
14502
+ report.event({
14503
+ kind: "board",
14504
+ message: milestone ? `commented: ${milestone}` : "commented",
14505
+ ...at && { at }
14506
+ });
14507
+ return;
14508
+ }
14509
+ case "question.asked":
14510
+ case "escalation": {
14511
+ const text = str(d.question) ?? str(d.text) ?? str(d.message) ?? str(d.reason) ?? "It needs an answer.";
14512
+ report.event({
14513
+ kind: "question",
14514
+ ...step && { step },
14515
+ message: clip(text),
14516
+ ...at && { at }
14517
+ });
14518
+ return;
14519
+ }
14520
+ case "error": {
14521
+ const text = str(d.message) ?? str(d.kind) ?? "Something went wrong.";
14522
+ report.event({
14523
+ kind: "warning",
14524
+ ...step && { step },
14525
+ message: clip(text),
14526
+ ...at && { at }
14527
+ });
14528
+ return;
14529
+ }
14530
+ case "run.end": {
14531
+ flush();
14532
+ const status = str(d.status) ?? "failed";
14533
+ const reason = str(d.reason);
14534
+ const says = SAYS[status];
14535
+ ending = {
14536
+ status: RUN_ENDINGS[status] ?? "failed",
14537
+ reason: clip(says ? `${says}${reason ? `: ${reason}` : "."}` : reason ?? (RUN_ENDINGS[status] ? "" : `It ended ${status.replace(/_/g, " ")}.`)) || null
13803
14538
  };
13804
- };
13805
- return {
13806
- done: flow().catch((err) => ({
13807
- status: "failed",
13808
- reason: clip(`The run stopped: ${err.message}`, 1e3)
13809
- })),
13810
- cancel: async () => {
13811
- cancelled = true;
13812
- agent?.stop();
13813
- }
13814
- };
14539
+ if (ending.status === "failed" && ending.reason) report.event({
14540
+ kind: "error",
14541
+ message: clip(ending.reason)
14542
+ });
14543
+ return;
14544
+ }
13815
14545
  }
13816
14546
  };
14547
+ return {
14548
+ take,
14549
+ /** How agentpipe said the run ended (null: it didn't). */
14550
+ ending: () => ending,
14551
+ flush: () => flush()
14552
+ };
13817
14553
  }
13818
- //#endregion
13819
- //#region src/runner/agents/claude.ts
14554
+ /** One stdout line as an event, or null for agentpipe's plain lines ("profile: cached", the step table). */
14555
+ function parseLine(line) {
14556
+ const text = line.trim();
14557
+ if (!text.startsWith("{")) return null;
14558
+ try {
14559
+ const value = JSON.parse(text);
14560
+ if (value && typeof value === "object" && typeof value.kind === "string") return value;
14561
+ } catch {}
14562
+ return null;
14563
+ }
14564
+ /** agentpipe's arguments for a run: the folder, the task, and what it may do (and spend, by default `budgetUsd`). */
14565
+ function agentpipeArgs({ ref, workdir, options }, budgetUsd = 10) {
14566
+ return [
14567
+ "run",
14568
+ workdir,
14569
+ "--from-issue",
14570
+ ref,
14571
+ "--json",
14572
+ ...options.pr === "none" ? ["--local"] : options.pr === "ready" ? ["--no-draft"] : ["--draft"],
14573
+ "--budget",
14574
+ String(options.budgetUsd ?? budgetUsd),
14575
+ ...options.autonomous ? ["--autonomous"] : []
14576
+ ];
14577
+ }
14578
+ /** What agentpipe keeps of the runner's environment, by name. */
14579
+ const KEEP = /* @__PURE__ */ new Set([
14580
+ "PATH",
14581
+ "HOME",
14582
+ "USER",
14583
+ "LOGNAME",
14584
+ "SHELL",
14585
+ "TMPDIR",
14586
+ "LANG",
14587
+ "LANGUAGE",
14588
+ "TZ",
14589
+ "DBUS_SESSION_BUS_ADDRESS",
14590
+ "SSH_AUTH_SOCK",
14591
+ "GIT_SSH_COMMAND",
14592
+ "GITHUB_TOKEN",
14593
+ "HTTPS_PROXY",
14594
+ "HTTP_PROXY",
14595
+ "NO_PROXY",
14596
+ "ALL_PROXY",
14597
+ "https_proxy",
14598
+ "http_proxy",
14599
+ "no_proxy",
14600
+ "all_proxy",
14601
+ "SSL_CERT_FILE",
14602
+ "SSL_CERT_DIR",
14603
+ "NODE_EXTRA_CA_CERTS"
14604
+ ]);
13820
14605
  /**
13821
- * Claude Code, unattended: `claude -p --output-format stream-json --verbose` with the prompt on stdin. Auto
13822
- * mode has a classifier review each action instead of a person, and `--permission-prompts none` denies what
13823
- * would still need one (so nothing waits). It ends with a `result` line: the cost, and the outcome shaped by
13824
- * --json-schema. It loads the folder's CLAUDE.md, settings and MCP servers, as a session there would.
14606
+ * And by prefix: the locale, the XDG folders, Claude's sign-in (ANTHROPIC_API_KEY, CLAUDE_CODE_OAUTH_TOKEN), gh's
14607
+ * (GH_TOKEN, GH_HOST), agentpipe's own settings, and monoban's sign-in for the commands agentpipe runs.
13825
14608
  */
13826
- /** The oldest Claude Code with --permission-prompts. */
13827
- const CLAUDE_MINIMUM = "2.1.259";
13828
- /** "edit src/a.ts", "$ pnpm test", "subagent: review the diff": a tool call in a few words. */
13829
- function describeTool(name, input = {}, roots = []) {
13830
- const path = (key) => relativeTo(roots, input[key]);
13831
- switch (name) {
13832
- case "Edit":
13833
- case "MultiEdit": return `edit ${path("file_path")}`;
13834
- case "NotebookEdit": return `edit ${path("notebook_path")}`;
13835
- case "Write": return `write ${path("file_path")}`;
13836
- case "Read": return `read ${path("file_path")}`;
13837
- case "Bash": return `$ ${firstLine(input.command)}`;
13838
- case "Grep": return `search ${JSON.stringify(input.pattern ?? "")}`;
13839
- case "Glob": return `find ${String(input.pattern ?? "")}`;
13840
- case "Agent":
13841
- case "Task": return `subagent: ${String(input.description ?? input.subagent_type ?? "")}`;
13842
- case "TodoWrite": return planLine((Array.isArray(input.todos) ? input.todos : []).map((t) => ({ done: t.status === "completed" })));
13843
- case "WebFetch": return `fetch ${String(input.url ?? "")}`;
13844
- case "WebSearch": return `search the web: ${String(input.query ?? "")}`;
13845
- default: return name.startsWith("mcp__") ? name.split("__").slice(1).join(": ") : name;
13846
- }
13847
- }
13848
- /** Why a `result` line says it didn't succeed. */
13849
- function failureOf(line) {
13850
- const subtype = line.subtype ?? "";
13851
- if (subtype.includes("budget")) return "It reached its budget.";
13852
- if (subtype.includes("max_turns")) return "It reached its turn limit.";
13853
- const said = typeof line.result === "string" && line.result.trim() ? line.result.trim().split("\n")[0] : null;
13854
- return `It stopped${subtype && subtype !== "success" ? ` (${subtype.replace(/_/g, " ")})` : ""}${said ? `: ${said}` : "."}`;
14609
+ const KEEP_PREFIXES = [
14610
+ "LC_",
14611
+ "XDG_",
14612
+ "ANTHROPIC_",
14613
+ "CLAUDE_CODE_",
14614
+ "GH_",
14615
+ "AGENTPIPE_",
14616
+ "MONOBAN_"
14617
+ ];
14618
+ /**
14619
+ * agentpipe's environment: only what it needs, so the runner's other secrets (a database password, cloud keys, an
14620
+ * npm token) never reach it, nor the commands it runs. MONOBAN_BIN names this monoban, so agentpipe calls back the
14621
+ * one that started it.
14622
+ */
14623
+ function agentpipeEnv(env, monobanBin) {
14624
+ const kept = {};
14625
+ for (const [name, value] of Object.entries(env)) if (value !== void 0 && (KEEP.has(name) || KEEP_PREFIXES.some((p) => name.startsWith(p)))) kept[name] = value;
14626
+ delete kept.MONOBAN_BIN;
14627
+ if (monobanBin) kept.MONOBAN_BIN = monobanBin;
14628
+ return kept;
13855
14629
  }
13856
- function claudeReader(roots) {
13857
- let answer = null;
13858
- let lastText = null;
13859
- let costUsd = null;
13860
- let failure = null;
13861
- let ended = false;
14630
+ const exec = (command, args, env) => new Promise((resolve) => execFile(command, args, {
14631
+ timeout: 3e4,
14632
+ env
14633
+ }, () => resolve()));
14634
+ /** Stderr's last lines, to say why agentpipe stopped without saying so itself. */
14635
+ const TAIL = 20;
14636
+ function agentpipe({ command = "agentpipe", args = [], spawn: spawn$1 = spawn, execCommand = exec, env: runnerEnv = process.env, monobanBin = null, budgetUsd = 10 } = {}) {
14637
+ const env = agentpipeEnv(runnerEnv, monobanBin);
13862
14638
  return {
13863
- line(text, out) {
13864
- if (!text.trim().startsWith("{")) return;
13865
- const line = JSON.parse(text);
13866
- switch (line.type) {
13867
- case "system":
13868
- if (line.subtype === "init") {
13869
- if (line.session_id) out.externalId(line.session_id);
13870
- out.activity(line.model ? `started (${line.model})` : "started");
13871
- } else if (line.subtype === "api_retry") out.activity(`retrying: ${line.error ?? "the API"}${line.attempt ? ` (attempt ${line.attempt})` : ""}`);
13872
- return;
13873
- case "assistant":
13874
- for (const c of line.message?.content ?? []) if (c.type === "tool_use" && c.name) {
13875
- if (c.name !== "StructuredOutput") out.activity(describeTool(c.name, c.input, roots));
13876
- } else if (c.type === "text" && c.text?.trim()) lastText = c.text;
13877
- return;
13878
- case "result": {
13879
- ended = true;
13880
- if (typeof line.total_cost_usd === "number") costUsd = line.total_cost_usd;
13881
- answer = line.structured_output ?? line.result ?? lastText;
13882
- if (line.is_error || line.subtype && line.subtype !== "success") failure = failureOf(line);
13883
- const denied = new Set((line.permission_denials ?? []).map((d) => describeTool(d.tool_name ?? "a tool", d.tool_input, roots)));
13884
- for (const what of [...denied].slice(0, 3)) out.warning(`Not allowed: ${what}`);
13885
- return;
14639
+ name: "agentpipe",
14640
+ start(run, report) {
14641
+ let externalId = null;
14642
+ const feed = agentpipeMapper({
14643
+ event: report.event,
14644
+ update: (u) => {
14645
+ if (u.externalId) externalId = u.externalId;
14646
+ report.update(u);
14647
+ }
14648
+ });
14649
+ const tail = [];
14650
+ let child;
14651
+ return {
14652
+ done: new Promise((resolve) => {
14653
+ try {
14654
+ child = spawn$1(command, [...agentpipeArgs(run, budgetUsd), ...args], {
14655
+ cwd: run.workdir,
14656
+ env,
14657
+ detached: true
14658
+ });
14659
+ } catch (err) {
14660
+ resolve({
14661
+ status: "failed",
14662
+ reason: `Couldn't start ${command}: ${err.message}`
14663
+ });
14664
+ return;
14665
+ }
14666
+ let spawnError = null;
14667
+ child.on("error", (err) => {
14668
+ spawnError = err.code === "ENOENT" ? `${command} isn't installed here (or isn't on the runner's PATH).` : `${command} failed: ${err.message}`;
14669
+ });
14670
+ if (child.stdout) createInterface$1({ input: child.stdout }).on("line", (line) => {
14671
+ const event = parseLine(line);
14672
+ if (event) feed.take(event);
14673
+ });
14674
+ if (child.stderr) createInterface$1({ input: child.stderr }).on("line", (line) => {
14675
+ if (!line.trim()) return;
14676
+ tail.push(line.trim());
14677
+ if (tail.length > TAIL) tail.shift();
14678
+ });
14679
+ child.on("close", (code) => {
14680
+ feed.flush();
14681
+ const said = feed.ending();
14682
+ if (said) return resolve(said);
14683
+ if (spawnError) return resolve({
14684
+ status: "failed",
14685
+ reason: spawnError
14686
+ });
14687
+ const last = tail.at(-1);
14688
+ resolve({
14689
+ status: "failed",
14690
+ reason: `${command} stopped (exit code ${code ?? "none"}) without saying how it ended${last ? `: ${last}` : "."}`
14691
+ });
14692
+ });
14693
+ }),
14694
+ cancel: async () => {
14695
+ if (externalId) await execCommand(command, [
14696
+ "cancel",
14697
+ externalId,
14698
+ "--reason",
14699
+ "Cancelled from monoban"
14700
+ ], env);
14701
+ else child?.kill("SIGINT");
13886
14702
  }
13887
- }
13888
- },
13889
- result: () => ({
13890
- answer: ended ? answer : lastText,
13891
- costUsd,
13892
- tokens: null,
13893
- failure
13894
- })
14703
+ };
14704
+ }
13895
14705
  };
13896
14706
  }
13897
- const claude = {
13898
- name: "claude",
13899
- args: (run, { schema }, extra) => [
13900
- "-p",
13901
- "--output-format",
13902
- "stream-json",
13903
- "--verbose",
13904
- "--permission-mode",
13905
- "auto",
13906
- "--permission-prompts",
13907
- "none",
13908
- "--json-schema",
13909
- schema,
13910
- ...run.options.budgetUsd !== void 0 ? ["--max-budget-usd", String(run.options.budgetUsd)] : [],
13911
- ...run.options.model ? ["--model", run.options.model] : [],
13912
- ...extra
13913
- ],
13914
- reader: claudeReader
13915
- };
13916
14707
  //#endregion
13917
14708
  //#region src/runner/agents/codex.ts
13918
14709
  /** `bash -lc 'pnpm test'` → `pnpm test`: the command inside the shell Codex runs it with. */
@@ -14020,17 +14811,19 @@ const DEFINITIONS = {
14020
14811
  agentpipe: { create: (d) => agentpipe({
14021
14812
  command: d.command,
14022
14813
  args: d.args,
14023
- env: d.env
14814
+ env: d.env,
14815
+ monobanBin: d.monobanBin,
14816
+ budgetUsd: d.agentpipeBudgetUsd
14024
14817
  }) },
14025
14818
  claude: {
14026
14819
  minimum: CLAUDE_MINIMUM,
14027
14820
  update: "claude update",
14028
- create: ({ allowFullAccess: _, ...d }) => codingAgent({
14821
+ create: ({ allowFullAccess: _, agentpipeBudgetUsd: __, monobanBin: ___, ...d }) => codingAgent({
14029
14822
  spec: claude,
14030
14823
  ...d
14031
14824
  })
14032
14825
  },
14033
- codex: { create: ({ allowFullAccess, ...d }) => codingAgent({
14826
+ codex: { create: ({ allowFullAccess, agentpipeBudgetUsd: _, monobanBin: __, ...d }) => codingAgent({
14034
14827
  spec: codexSpec({ allowFullAccess }),
14035
14828
  ...d
14036
14829
  }) }
@@ -14063,13 +14856,15 @@ async function detectAgents(settings, env, version = versionOf) {
14063
14856
  };
14064
14857
  }
14065
14858
  /** The adapters for what was found. */
14066
- function adaptersFor(found, settings, board, env) {
14859
+ function adaptersFor(found, settings, board, env, monobanBin = null) {
14067
14860
  return Object.fromEntries(found.map(({ name }) => [name, DEFINITIONS[name].create({
14068
14861
  command: settings.commands[name],
14069
14862
  args: settings.args[name],
14070
14863
  board,
14071
14864
  env,
14072
- allowFullAccess: settings.allowFullAccess
14865
+ allowFullAccess: settings.allowFullAccess,
14866
+ agentpipeBudgetUsd: settings.agentpipeBudgetUsd,
14867
+ monobanBin
14073
14868
  })]));
14074
14869
  }
14075
14870
  //#endregion
@@ -14115,103 +14910,6 @@ function runBoard(api) {
14115
14910
  };
14116
14911
  }
14117
14912
  //#endregion
14118
- //#region src/runner/config.ts
14119
- const AGENT_NAMES$1 = Object.keys(AGENTS$1);
14120
- const isAgent = (name) => AGENT_NAMES$1.includes(name);
14121
- /** What's wrong with runner.json's contents, or null. */
14122
- function fileProblem(v) {
14123
- if (!v || typeof v !== "object" || Array.isArray(v)) return "it should be an object";
14124
- const f = v;
14125
- const known = [
14126
- "name",
14127
- "pollSeconds",
14128
- "allow",
14129
- "confirm",
14130
- "agents",
14131
- "adapters"
14132
- ];
14133
- const unknown = Object.keys(f).find((k) => !known.includes(k));
14134
- if (unknown) return `${unknown} isn't a setting (${known.join(", ")})`;
14135
- if (f.name !== void 0 && (typeof f.name !== "string" || !f.name.trim() || f.name.length > 64)) return "name: 1 to 64 characters";
14136
- if (f.pollSeconds !== void 0 && !(Number.isInteger(f.pollSeconds) && f.pollSeconds >= 1 && f.pollSeconds <= 60)) return "pollSeconds: a whole number of seconds, 1 to 60";
14137
- if (f.allow !== void 0 && !(Array.isArray(f.allow) && f.allow.every((p) => typeof p === "string" && p.startsWith("/")))) return "allow: a list of absolute paths";
14138
- if (f.confirm !== void 0 && typeof f.confirm !== "boolean") return "confirm: true or false";
14139
- if (f.agents !== void 0) {
14140
- if (!Array.isArray(f.agents) || !f.agents.every((a) => typeof a === "string" && isAgent(a))) return `agents: a list of ${AGENT_NAMES$1.join(", ")}`;
14141
- }
14142
- if (f.adapters !== void 0) {
14143
- if (!f.adapters || typeof f.adapters !== "object" || Array.isArray(f.adapters)) return "adapters: an object";
14144
- for (const [name, value] of Object.entries(f.adapters)) {
14145
- if (!isAgent(name)) return `adapters.${name}: monoban doesn't run ${name} (${AGENT_NAMES$1.join(", ")})`;
14146
- const agent = value ?? {};
14147
- const settings = name === "codex" ? [
14148
- "command",
14149
- "args",
14150
- "allowFullAccess"
14151
- ] : ["command", "args"];
14152
- const extra = Object.keys(agent).find((k) => !settings.includes(k));
14153
- if (extra) return `adapters.${name}.${extra} isn't a setting (${settings.join(", ")})`;
14154
- if (agent.allowFullAccess !== void 0 && typeof agent.allowFullAccess !== "boolean") return `adapters.${name}.allowFullAccess: true or false`;
14155
- if (agent.command !== void 0 && (typeof agent.command !== "string" || !agent.command)) return `adapters.${name}.command: a command`;
14156
- if (agent.args !== void 0 && !(Array.isArray(agent.args) && agent.args.every((a) => typeof a === "string"))) return `adapters.${name}.args: a list of arguments`;
14157
- }
14158
- }
14159
- return null;
14160
- }
14161
- const RUNNER_FILE = "runner.json";
14162
- async function readSettingsFile(dir) {
14163
- const path = join(dir, RUNNER_FILE);
14164
- let text;
14165
- try {
14166
- text = await readFile(path, "utf8");
14167
- } catch {
14168
- return {};
14169
- }
14170
- let parsed;
14171
- try {
14172
- parsed = JSON.parse(text);
14173
- } catch {
14174
- throw new CliError(`${path} isn't JSON.`, EXIT.usage);
14175
- }
14176
- const problem = fileProblem(parsed);
14177
- if (problem) throw new CliError(`${path}: ${problem}.`, EXIT.usage);
14178
- return parsed;
14179
- }
14180
- /** --agents claude,codex. */
14181
- function agentsFlag(value) {
14182
- const names = value.split(",").map((a) => a.trim().toLowerCase()).filter(Boolean);
14183
- const unknown = names.find((a) => !isAgent(a));
14184
- if (unknown || !names.length) throw new CliError(`--agents takes ${AGENT_NAMES$1.join(", ")} (comma-separated)${unknown ? `, not ${unknown}` : ""}.`, EXIT.usage);
14185
- return names;
14186
- }
14187
- async function runnerSettings(dir, flags, env, hostname) {
14188
- const file = await readSettingsFile(dir);
14189
- let pollSeconds = file.pollSeconds ?? 3;
14190
- if (flags.interval !== void 0) {
14191
- pollSeconds = Number(flags.interval);
14192
- if (!Number.isInteger(pollSeconds) || pollSeconds < 1 || pollSeconds > 60) throw new CliError("--interval is how often to ask for work, in seconds: 1 to 60.", EXIT.usage);
14193
- }
14194
- const allow = [...file.allow ?? [], ...flags.allow ?? []];
14195
- const relative = allow.find((p) => !p.startsWith("/"));
14196
- if (relative) throw new CliError(`--allow takes absolute paths (${relative} isn't one).`, EXIT.usage);
14197
- const commands = {};
14198
- const args = {};
14199
- for (const name of AGENT_NAMES$1) {
14200
- commands[name] = env[`MONOBAN_${name.toUpperCase()}`] || file.adapters?.[name]?.command || name;
14201
- args[name] = file.adapters?.[name]?.args ?? [];
14202
- }
14203
- return {
14204
- name: flags.name?.trim() || file.name || hostname,
14205
- pollSeconds,
14206
- allow,
14207
- confirm: flags.confirm ?? file.confirm ?? false,
14208
- agents: flags.agents !== void 0 ? agentsFlag(flags.agents) : file.agents ?? null,
14209
- commands,
14210
- args,
14211
- allowFullAccess: flags.allowFullAccess ?? file.adapters?.codex?.allowFullAccess ?? false
14212
- };
14213
- }
14214
- //#endregion
14215
14913
  //#region src/runner/loop.ts
14216
14914
  const sleepFor = (ms, signal) => new Promise((resolve) => {
14217
14915
  if (signal.aborted) return resolve();
@@ -14232,13 +14930,31 @@ const ENDINGS = {
14232
14930
  async function runRunner(ctx, settings, deps, options = {}) {
14233
14931
  const api = apis(ctx).signedIn;
14234
14932
  const now = deps.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
14235
- const adapters = Object.keys(deps.adapters);
14933
+ let installed = deps.adapters;
14934
+ let adapters = Object.keys(installed);
14236
14935
  const register = () => unwrap(api.POST("/v1/runners", { body: {
14237
14936
  name: settings.name,
14238
14937
  adapters,
14239
14938
  version: VERSION,
14240
14939
  pollSeconds: settings.pollSeconds
14241
14940
  } }));
14941
+ const redetectMs = deps.redetectMs ?? 6e4;
14942
+ let detectedAt = Date.now();
14943
+ /** Offers the agents installed now, when they changed (registering again tells the board). */
14944
+ const redetect = async () => {
14945
+ if (!deps.redetect || Date.now() - detectedAt < redetectMs) return;
14946
+ detectedAt = Date.now();
14947
+ const next = await deps.redetect().catch(() => installed);
14948
+ const names = Object.keys(next);
14949
+ if (!names.length || names.join() === adapters.join()) return;
14950
+ const added = names.filter((n) => !adapters.includes(n));
14951
+ const gone = adapters.filter((n) => !names.includes(n));
14952
+ installed = next;
14953
+ adapters = names;
14954
+ runner = await register();
14955
+ const said = [added.length && `now offers ${added.join(", ")}`, gone.length && `no longer offers ${gone.join(", ")}`];
14956
+ ctx.err(`Runner ${runner.name} ${said.filter(Boolean).join(" and ")}.`);
14957
+ };
14242
14958
  let runner = await register();
14243
14959
  ctx.err(`Runner ${runner.name} is online with ${adapters.join(", ")}: waiting for runs (checking every ${settings.pollSeconds}s; Ctrl-C to stop).`);
14244
14960
  let active = null;
@@ -14303,6 +15019,7 @@ async function runRunner(ctx, settings, deps, options = {}) {
14303
15019
  }
14304
15020
  await active?.flush();
14305
15021
  if (options.once && !active && (took || !work?.queued.length)) break;
15022
+ if (!active && !stopping) await redetect().catch(() => {});
14306
15023
  if (!leave && (!stopping || active)) {
14307
15024
  await deps.sleep(settings.pollSeconds * 1e3, wake.signal);
14308
15025
  wake = new AbortController();
@@ -14338,7 +15055,7 @@ async function runRunner(ctx, settings, deps, options = {}) {
14338
15055
  }, run.version).catch(() => {});
14339
15056
  };
14340
15057
  if (!ref) return refuse("failed", "Its task was deleted.");
14341
- const adapter = deps.adapters[run.adapter];
15058
+ const adapter = installed[run.adapter];
14342
15059
  if (!adapter) return refuse("failed", `${runner.name} can't run ${run.adapter}.`);
14343
15060
  const problem = await deps.workdirProblem(run.workdir, run.project);
14344
15061
  if (problem) return refuse("failed", problem);
@@ -14520,13 +15237,17 @@ async function runner(ctx, options, overrides = {}) {
14520
15237
  const settings = await runnerSettings(configDir(ctx.env), options, ctx.env, deviceName());
14521
15238
  const { detect = detectAgents, ...deps } = overrides;
14522
15239
  let adapters = deps.adapters;
15240
+ let redetect = deps.redetect;
14523
15241
  if (!adapters) {
14524
15242
  const env = ctx.env;
15243
+ const board = runBoard(apis(ctx).signedIn);
15244
+ const monobanBin = selfCommand();
14525
15245
  const { found, missing } = await detect(settings, env);
14526
15246
  if (!found.length) throw new CliError(`No coding agent to run here: ${missing.join("; ")}. Install one (agentpipe, Claude Code or Codex), or set its command in ${configDir(ctx.env)}/runner.json.`, EXIT.usage);
14527
15247
  ctx.err(`Agents: ${agentList(found)}.${missing.length ? ` Not offered: ${missing.join("; ")}.` : ""}`);
14528
15248
  if (settings.allowFullAccess && found.some((a) => a.name === "codex")) ctx.err("Codex may run without its sandbox here, when a run asks for full access.");
14529
- adapters = adaptersFor(found, settings, runBoard(apis(ctx).signedIn), env);
15249
+ adapters = adaptersFor(found, settings, board, env, monobanBin);
15250
+ redetect ??= async () => adaptersFor((await detect(settings, env)).found, settings, board, env, monobanBin);
14530
15251
  }
14531
15252
  await runRunner(ctx, settings, {
14532
15253
  workdirProblem: (workdir, project) => workdirProblem(workdir, project, settings.allow),
@@ -14536,7 +15257,8 @@ async function runner(ctx, options, overrides = {}) {
14536
15257
  return () => process.off("SIGINT", handler);
14537
15258
  },
14538
15259
  ...deps,
14539
- adapters
15260
+ adapters,
15261
+ redetect
14540
15262
  }, { once: options.once });
14541
15263
  }
14542
15264
  const PR_CHOICES = [
@@ -15124,99 +15846,6 @@ end
15124
15846
  complete -c monoban -f -a '(__monoban_complete)'
15125
15847
  `
15126
15848
  };
15127
- const UPGRADE = {
15128
- brew: {
15129
- how: "Homebrew",
15130
- command: "brew upgrade monoban"
15131
- },
15132
- binary: {
15133
- how: "a downloaded binary",
15134
- command: `download it again: https://github.com/thiagodmont/homebrew-tap/releases/latest`
15135
- },
15136
- npx: {
15137
- how: "npx",
15138
- command: "npx monoban@latest"
15139
- },
15140
- npm: {
15141
- how: "npm",
15142
- command: "npm install -g monoban@latest"
15143
- },
15144
- pnpm: {
15145
- how: "pnpm",
15146
- command: "pnpm add -g monoban@latest"
15147
- },
15148
- yarn: {
15149
- how: "yarn",
15150
- command: "yarn global add monoban@latest"
15151
- },
15152
- bun: {
15153
- how: "bun",
15154
- command: "bun add -g monoban@latest"
15155
- }
15156
- };
15157
- /**
15158
- * Told apart by where it runs from: a binary in a Homebrew Cellar, or the npm package under npx's
15159
- * cache or a package manager's global folder (npm when it's none of those).
15160
- */
15161
- function installKind(where) {
15162
- if (where.binary) return where.executable.includes("/Cellar/") ? "brew" : "binary";
15163
- const script = where.script.replaceAll("\\", "/");
15164
- if (script.includes("/_npx/")) return "npx";
15165
- if (/\/\.?pnpm\//.test(script)) return "pnpm";
15166
- if (script.includes("/.bun/")) return "bun";
15167
- if (/\/(\.yarn|yarn\/global)\//.test(script)) return "yarn";
15168
- return "npm";
15169
- }
15170
- const real = (path) => {
15171
- try {
15172
- return path ? realpathSync(path) : "";
15173
- } catch {
15174
- return path ?? "";
15175
- }
15176
- };
15177
- /** This process's install. */
15178
- const thisInstall = () => installKind({
15179
- binary: false,
15180
- executable: real(process.execPath),
15181
- script: real(process.argv[1])
15182
- });
15183
- /** 1.2.10 > 1.2.9; a pre-release counts as its version. */
15184
- function newer(a, b) {
15185
- const parts = (v) => v.split(/[-+]/)[0]?.split(".").map(Number) ?? [];
15186
- const [x, y] = [parts(a), parts(b)];
15187
- for (let i = 0; i < 3; i++) if ((x[i] ?? 0) !== (y[i] ?? 0)) return (x[i] ?? 0) > (y[i] ?? 0);
15188
- return false;
15189
- }
15190
- /** The latest version on npm (Homebrew and the binaries ship the same releases), or null offline. */
15191
- async function latestVersion(ctx) {
15192
- try {
15193
- const res = await ctx.fetch(new Request("https://registry.npmjs.org/monoban/latest", { signal: AbortSignal.timeout(3e3) }));
15194
- if (!res.ok) return null;
15195
- const { version } = await res.json();
15196
- return typeof version === "string" ? version : null;
15197
- } catch {
15198
- return null;
15199
- }
15200
- }
15201
- /** `monoban upgrade`: whether there's a newer version, and the command that installs it here. */
15202
- async function upgrade(ctx, options, kind = thisInstall()) {
15203
- const latest = await latestVersion(ctx);
15204
- const { how, command } = UPGRADE[kind];
15205
- const outdated = latest !== null && newer(latest, "1.5.1");
15206
- if (options.json) {
15207
- ctx.out(JSON.stringify({
15208
- version: VERSION,
15209
- latest,
15210
- outdated,
15211
- installedWith: kind,
15212
- command
15213
- }, null, 2));
15214
- return;
15215
- }
15216
- if (latest === null) ctx.out(`You have monoban ${VERSION} (installed with ${how}). To get the latest: ${command}`);
15217
- else if (outdated) ctx.out(`monoban ${latest} is out (you have ${VERSION}). To upgrade: ${command}`);
15218
- else ctx.out(`monoban ${VERSION} is the latest.`);
15219
- }
15220
15849
  //#endregion
15221
15850
  //#region src/program.ts
15222
15851
  /** The command tree. Each action gets the run's Context. */
@@ -15277,6 +15906,21 @@ machine allows a run to turn it off. Settings can also go in runner.json in the
15277
15906
  cli.command("setup").addArgument(new Argument("<agent>", "which agent: claude (Claude Code) or codex").choices(AGENTS)).description("Teach a coding agent monoban: a skill to plan work as tasks (phases as tags) and keep them current").option("--project", "install it in this repository (to commit), not for you in every one").option("--print", "print the skill instead of installing it").option("--remove", "remove the skill").option("-f, --force", "replace (or remove) a skill monoban didn't write").addOption(json()).addHelpText("after", `
15278
15907
  It goes in ~/.claude/skills/monoban (Claude Code) or ~/.agents/skills/monoban (Codex); with --project,
15279
15908
  in .claude/skills or .agents/skills at the top of this repository. Run it again after upgrading monoban.`).action(async (agent, options) => setup(await ctx(), agent, options));
15909
+ const pipe = cli.command("agentpipe").description("Install agentpipe for the runner, and run it: install, status, update, login, uninstall").argument("[args...]", "after --: arguments for agentpipe itself (monoban agentpipe -- doctor .)").addHelpText("after", `
15910
+ agentpipe is installed, CLI only, in monoban's own folder ($XDG_DATA_HOME/monoban, or ~/.local/share/monoban),
15911
+ at the version this monoban comes with: every file it downloads is checked against a SHA-256 monoban pins.
15912
+ \`monoban runner\` offers it within a minute of installing. It needs macOS, or Linux with glibc.`).action(async (args) => {
15913
+ if (!args.length) return pipe.help();
15914
+ process.exitCode = await runAgentpipe(await ctx(), args);
15915
+ });
15916
+ pipe.command("install").description("Install the agentpipe this monoban comes with (downloads Python 3.12, and uv if needed)").option("--force", "install it again, over the same version").action(async (options) => installAgentpipe(await ctx(), options));
15917
+ pipe.command("status").description("Whether agentpipe is installed, and whether this monoban comes with a newer one").addOption(json()).action(async (options) => status(await ctx(), options));
15918
+ pipe.command("update").description("Install the agentpipe this monoban comes with, over an older one").action(async () => update(await ctx()));
15919
+ pipe.command("login").description("Sign agentpipe in to Claude (your Claude account), on this terminal").action(async () => {
15920
+ process.exitCode = await runAgentpipe(await ctx(), ["login"]);
15921
+ });
15922
+ pipe.command("uninstall").description("Remove the agentpipe monoban installed (its runs and settings in ~/.agentpipe stay)").option("-y, --yes", "don't ask").action(async (options) => uninstall(await ctx(), options));
15923
+ cli.command("doctor").description("Check what monoban and its runner need here (sign-in, agents, git, gh), and how to fix what's missing").addOption(json()).action(async (options) => doctor(await ctx(), options));
15280
15924
  cli.command("upgrade").description("Check for a newer version, and say how to install it (Homebrew, npm…)").addOption(json()).action(async (options) => upgrade(await ctx(), options));
15281
15925
  cli.command("completion").addArgument(new Argument("<shell>", "bash, zsh or fish").choices(SHELLS)).description("Print the script that makes Tab complete commands, projects, columns, tasks and tags").addHelpText("after", `
15282
15926
  Load it in your shell: