monoban 1.3.0 → 1.5.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 +39 -0
  2. package/dist/index.mjs +2605 -133
  3. package/package.json +4 -4
package/dist/index.mjs CHANGED
@@ -1,15 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  import { homedir, hostname, tmpdir } from "node:os";
3
- import path, { dirname, join } from "node:path";
4
- import { mkdir, mkdtemp, open, readFile, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
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";
5
5
  import childProcess, { execFile, spawn, spawnSync } from "node:child_process";
6
6
  import { EventEmitter } from "node:events";
7
- import fs, { realpathSync } from "node:fs";
7
+ import fs, { existsSync, 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
12
  import { createServer } from "node:http";
13
+ import { createInterface as createInterface$1 } from "node:readline";
13
14
  /** Where the CLI keeps its files: $MONOBAN_CONFIG_DIR, else $XDG_CONFIG_HOME/monoban, else ~/.config/monoban. */
14
15
  function configDir(env = process.env) {
15
16
  if (env.MONOBAN_CONFIG_DIR) return env.MONOBAN_CONFIG_DIR;
@@ -46,6 +47,63 @@ function canOpenBrowser(env = process.env, platform = process.platform) {
46
47
  }
47
48
  const trimSlash = (url) => url.replace(/\/+$/, "");
48
49
  //#endregion
50
+ //#region ../../packages/contract/src/agents.ts
51
+ /**
52
+ * The coding agents a run can use (docs/PLAN-ORCHESTRATOR.md §9), for the web's dialog, the API's checks and
53
+ * the CLI. A runner says which of them it has; one this list doesn't know (from a newer runner) still runs,
54
+ * with only the options every agent takes. Adding one: an entry here and its file in apps/cli/src/runner/agents.
55
+ */
56
+ /** The run options an agent may take besides `pr` (every agent takes that). */
57
+ const AGENT_OPTIONS = [
58
+ "budgetUsd",
59
+ "autonomous",
60
+ "model",
61
+ "access"
62
+ ];
63
+ const AGENTS$1 = {
64
+ agentpipe: {
65
+ label: "agentpipe",
66
+ description: "Plans, implements and verifies in steps; moves and comments on the task itself.",
67
+ options: ["budgetUsd", "autonomous"]
68
+ },
69
+ claude: {
70
+ label: "Claude Code",
71
+ description: "claude -p in auto mode: a classifier reviews what it does, and nothing waits for you.",
72
+ options: ["budgetUsd", "model"]
73
+ },
74
+ codex: {
75
+ label: "Codex",
76
+ description: "codex exec in its sandbox: it writes in the folder, with the network off unless you say.",
77
+ options: ["model", "access"]
78
+ }
79
+ };
80
+ /** How Codex may reach outside the folder: its sandbox, the sandbox with the network, or no sandbox. */
81
+ const AGENT_ACCESS = [
82
+ "sandbox",
83
+ "network",
84
+ "full"
85
+ ];
86
+ /** "Claude Code"; an agent this list doesn't know is called by its name. */
87
+ function agentLabel(name) {
88
+ return AGENTS$1[name]?.label ?? name;
89
+ }
90
+ /** The options `name` takes besides `pr`. */
91
+ function agentOptions(name) {
92
+ return AGENTS$1[name]?.options ?? [];
93
+ }
94
+ /**
95
+ * The first option set that `agent` doesn't take, or null. `autonomous` always has a value (true by default),
96
+ * so only turning it off counts.
97
+ */
98
+ function unsupportedOption(agent, options) {
99
+ const takes = agentOptions(agent);
100
+ for (const option of AGENT_OPTIONS) {
101
+ const value = options[option];
102
+ if ((option === "autonomous" ? value === false : value !== void 0) && !takes.includes(option)) return option;
103
+ }
104
+ return null;
105
+ }
106
+ //#endregion
49
107
  //#region ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/core/util.js
50
108
  function getEnumValues(entries) {
51
109
  const numericValues = Object.values(entries).filter((v) => typeof v === "number");
@@ -1060,8 +1118,10 @@ function datetime$1(args) {
1060
1118
  return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
1061
1119
  }
1062
1120
  const anyString = /^[\s\S]{0,}$/;
1121
+ const integer = /^-?\d+$/;
1063
1122
  const number$2 = /^-?\d+(?:\.\d+)?$/;
1064
1123
  const boolean$1 = /^(?:true|false)$/i;
1124
+ const _null$2 = /^null$/i;
1065
1125
  const lowercase = /^[^A-Z]*$/;
1066
1126
  const uppercase = /^[^a-z]*$/;
1067
1127
  //#endregion
@@ -1883,6 +1943,22 @@ const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => {
1883
1943
  return payload;
1884
1944
  };
1885
1945
  });
1946
+ const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => {
1947
+ $ZodType.init(inst, def);
1948
+ inst._zod.pattern = _null$2;
1949
+ inst._zod.values = /* @__PURE__ */ new Set([null]);
1950
+ inst._zod.parse = (payload, _ctx) => {
1951
+ const input = payload.value;
1952
+ if (input === null) return payload;
1953
+ payload.issues.push({
1954
+ expected: "null",
1955
+ code: "invalid_type",
1956
+ input,
1957
+ inst
1958
+ });
1959
+ return payload;
1960
+ };
1961
+ });
1886
1962
  const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => {
1887
1963
  $ZodType.init(inst, def);
1888
1964
  inst._zod.parse = (payload) => payload;
@@ -2441,6 +2517,138 @@ function handleIntersectionResults(result, left, right) {
2441
2517
  result.value = merged.data;
2442
2518
  return result;
2443
2519
  }
2520
+ const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => {
2521
+ $ZodType.init(inst, def);
2522
+ const memo = globalConfig.memoizer;
2523
+ memo?.attach(inst);
2524
+ inst._zod.parse = (payload, ctx) => {
2525
+ const input = payload.value;
2526
+ if (!isPlainObject(input)) {
2527
+ payload.issues.push({
2528
+ expected: "record",
2529
+ code: "invalid_type",
2530
+ input,
2531
+ inst
2532
+ });
2533
+ return payload;
2534
+ }
2535
+ const proms = [];
2536
+ const values = def.keyType._zod.values;
2537
+ if (values && !def.partial) {
2538
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
2539
+ const recordKeys = /* @__PURE__ */ new Set();
2540
+ for (const key of values) if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
2541
+ recordKeys.add(typeof key === "number" ? key.toString() : key);
2542
+ if (key === "__proto__") continue;
2543
+ const keyResult = def.keyType._zod.run({
2544
+ value: key,
2545
+ issues: []
2546
+ }, ctx);
2547
+ if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
2548
+ if (keyResult.issues.length) {
2549
+ payload.issues.push({
2550
+ code: "invalid_key",
2551
+ origin: "record",
2552
+ issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
2553
+ input: key,
2554
+ path: [key],
2555
+ inst
2556
+ });
2557
+ continue;
2558
+ }
2559
+ const outKey = keyResult.value;
2560
+ if (outKey === "__proto__") continue;
2561
+ const result = def.valueType._zod.run({
2562
+ value: input[key],
2563
+ issues: []
2564
+ }, ctx);
2565
+ if (result instanceof Promise) proms.push(result.then((result) => {
2566
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
2567
+ payload.value[outKey] = result.value;
2568
+ }));
2569
+ else {
2570
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
2571
+ payload.value[outKey] = result.value;
2572
+ }
2573
+ }
2574
+ let unrecognized;
2575
+ for (const key in input) if (!recordKeys.has(key)) {
2576
+ if (def.mode === "loose") {
2577
+ if (key === "__proto__") continue;
2578
+ payload.value[key] = input[key];
2579
+ } else {
2580
+ unrecognized = unrecognized ?? [];
2581
+ unrecognized.push(key);
2582
+ }
2583
+ }
2584
+ if (unrecognized && unrecognized.length > 0) payload.issues.push({
2585
+ code: "unrecognized_keys",
2586
+ input,
2587
+ inst,
2588
+ keys: unrecognized,
2589
+ continue: true
2590
+ });
2591
+ } else {
2592
+ payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {};
2593
+ let unrecognized;
2594
+ for (const key of Reflect.ownKeys(input)) {
2595
+ if (key === "__proto__") continue;
2596
+ if (!Object.prototype.propertyIsEnumerable.call(input, key)) continue;
2597
+ let keyResult = def.keyType._zod.run({
2598
+ value: key,
2599
+ issues: []
2600
+ }, ctx);
2601
+ if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
2602
+ if (typeof key === "string" && number$2.test(key) && keyResult.issues.length) {
2603
+ const retryResult = def.keyType._zod.run({
2604
+ value: Number(key),
2605
+ issues: []
2606
+ }, ctx);
2607
+ if (retryResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently");
2608
+ if (retryResult.issues.length === 0) keyResult = retryResult;
2609
+ }
2610
+ if (keyResult.issues.length) {
2611
+ if (def.mode === "loose") payload.value[key] = input[key];
2612
+ else if (values) {
2613
+ unrecognized = unrecognized ?? [];
2614
+ unrecognized.push(key);
2615
+ } else payload.issues.push({
2616
+ code: "invalid_key",
2617
+ origin: "record",
2618
+ issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
2619
+ input: key,
2620
+ path: [key],
2621
+ inst
2622
+ });
2623
+ continue;
2624
+ }
2625
+ const outKey = keyResult.value;
2626
+ if (outKey === "__proto__") continue;
2627
+ const result = def.valueType._zod.run({
2628
+ value: input[key],
2629
+ issues: []
2630
+ }, ctx);
2631
+ if (result instanceof Promise) proms.push(result.then((result) => {
2632
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
2633
+ payload.value[outKey] = result.value;
2634
+ }));
2635
+ else {
2636
+ if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues));
2637
+ payload.value[outKey] = result.value;
2638
+ }
2639
+ }
2640
+ if (unrecognized && unrecognized.length > 0) payload.issues.push({
2641
+ code: "unrecognized_keys",
2642
+ input,
2643
+ inst,
2644
+ keys: unrecognized,
2645
+ continue: true
2646
+ });
2647
+ }
2648
+ if (proms.length) return Promise.all(proms).then(() => payload);
2649
+ return payload;
2650
+ };
2651
+ });
2444
2652
  const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => {
2445
2653
  $ZodType.init(inst, def);
2446
2654
  const values = getEnumValues(def.entries);
@@ -3427,6 +3635,13 @@ function _boolean(Class, params) {
3427
3635
  });
3428
3636
  }
3429
3637
  // @__NO_SIDE_EFFECTS__
3638
+ function _null$1(Class, params) {
3639
+ return new Class({
3640
+ type: "null",
3641
+ ...normalizeParams(params)
3642
+ });
3643
+ }
3644
+ // @__NO_SIDE_EFFECTS__
3430
3645
  function _unknown(Class) {
3431
3646
  return new Class({ type: "unknown" });
3432
3647
  }
@@ -4208,6 +4423,13 @@ const numberProcessor = (schema, ctx, _json, params) => {
4208
4423
  const booleanProcessor = (_schema, _ctx, json, _params) => {
4209
4424
  json.type = "boolean";
4210
4425
  };
4426
+ const nullProcessor = (_schema, ctx, json, _params) => {
4427
+ if (ctx.target === "openapi-3.0") {
4428
+ json.type = "string";
4429
+ json.nullable = true;
4430
+ json.enum = [null];
4431
+ } else json.type = "null";
4432
+ };
4211
4433
  const neverProcessor = (_schema, _ctx, json, _params) => {
4212
4434
  json.not = {};
4213
4435
  };
@@ -4338,6 +4560,107 @@ const intersectionProcessor = (schema, ctx, json, params) => {
4338
4560
  json.allOf = allOf;
4339
4561
  ctx.intersections.push(allOf);
4340
4562
  };
4563
+ /** JSON object keys are always strings, so a numeric record key schema is re-expressed over the
4564
+ * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key
4565
+ * behind a wrapper only carries its own `type` before then, and a union key only has its branches.
4566
+ *
4567
+ * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather
4568
+ * than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this
4569
+ * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)`
4570
+ * accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema
4571
+ * outright. */
4572
+ function stringifyKeyNames(bySchema, json, visited) {
4573
+ if (json.$ref) {
4574
+ if (visited.has(json)) return json;
4575
+ visited.add(json);
4576
+ const def = bySchema.get(json)?.def;
4577
+ if (!def) return json;
4578
+ const inlined = stringifyKeyNames(bySchema, def, visited);
4579
+ return inlined === def ? json : inlined;
4580
+ }
4581
+ for (const keyword of ["anyOf", "oneOf"]) {
4582
+ const branches = json[keyword];
4583
+ if (!Array.isArray(branches)) continue;
4584
+ const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited));
4585
+ if (mapped.some((branch, i) => branch !== branches[i])) json = {
4586
+ ...json,
4587
+ [keyword]: mapped
4588
+ };
4589
+ }
4590
+ const types = Array.isArray(json.type) ? json.type : [json.type];
4591
+ const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer");
4592
+ const values = json.enum ?? (json.const !== void 0 ? [json.const] : void 0);
4593
+ if (!numericType && !values?.some((v) => typeof v === "number")) return json;
4594
+ const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json;
4595
+ if (rest.enum) rest.enum = rest.enum.map((v) => typeof v === "number" ? String(v) : v);
4596
+ else if (typeof rest.const === "number") rest.const = String(rest.const);
4597
+ if (!numericType) return rest;
4598
+ rest.type = "string";
4599
+ if (!values) rest.pattern = (types.includes("number") ? number$2 : integer).source;
4600
+ return rest;
4601
+ }
4602
+ /** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */
4603
+ const pendingRecords = /* @__PURE__ */ new WeakMap();
4604
+ function rewriteKeyNames(ctx) {
4605
+ const bySchema = /* @__PURE__ */ new Map();
4606
+ for (const entry of ctx.seen.values()) if (entry.def && !bySchema.has(entry.schema)) bySchema.set(entry.schema, entry);
4607
+ const rewrites = /* @__PURE__ */ new Map();
4608
+ for (const record of pendingRecords.get(ctx) ?? []) {
4609
+ const seen = ctx.seen.get(record);
4610
+ const names = (seen?.def ?? seen?.schema)?.propertyNames;
4611
+ if (!names || names === true || rewrites.has(names)) continue;
4612
+ const rewritten = stringifyKeyNames(bySchema, names, /* @__PURE__ */ new Set());
4613
+ if (rewritten !== names) rewrites.set(names, rewritten);
4614
+ }
4615
+ if (!rewrites.size) return;
4616
+ for (const entry of ctx.seen.values()) for (const carrier of [entry.schema, entry.def]) {
4617
+ const rewritten = carrier && rewrites.get(carrier.propertyNames);
4618
+ if (rewritten) carrier.propertyNames = rewritten;
4619
+ }
4620
+ }
4621
+ const recordProcessor = (schema, ctx, _json, params) => {
4622
+ const json = _json;
4623
+ const def = schema._zod.def;
4624
+ json.type = "object";
4625
+ const keyType = def.keyType;
4626
+ const patterns = aggregateChecks(keyType).patterns;
4627
+ if (def.mode === "loose" && patterns && patterns.size > 0) {
4628
+ const valueSchema = processSchema(def.valueType, ctx, {
4629
+ ...params,
4630
+ path: [
4631
+ ...params.path,
4632
+ "patternProperties",
4633
+ "*"
4634
+ ]
4635
+ });
4636
+ json.patternProperties = {};
4637
+ for (const pattern of patterns) assignProp(json.patternProperties, exactPattern(pattern).source, valueSchema);
4638
+ } else {
4639
+ if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
4640
+ json.propertyNames = processSchema(def.keyType, ctx, {
4641
+ ...params,
4642
+ path: [...params.path, "propertyNames"]
4643
+ });
4644
+ let pending = pendingRecords.get(ctx);
4645
+ if (!pending) {
4646
+ pending = [];
4647
+ pendingRecords.set(ctx, pending);
4648
+ ctx.deferred.push(() => rewriteKeyNames(ctx));
4649
+ }
4650
+ pending.push(schema);
4651
+ }
4652
+ json.additionalProperties = processSchema(def.valueType, ctx, {
4653
+ ...params,
4654
+ path: [...params.path, "additionalProperties"]
4655
+ });
4656
+ }
4657
+ const keyValues = keyType._zod.values;
4658
+ const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== void 0;
4659
+ if (keyValues && !def.partial && !omittableOnInput) {
4660
+ const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
4661
+ if (validKeyValues.length > 0) json.required = validKeyValues.map(String);
4662
+ }
4663
+ };
4341
4664
  const nullableProcessor = (schema, ctx, json, params) => {
4342
4665
  const def = schema._zod.def;
4343
4666
  const inner = processSchema(def.innerType, ctx, params);
@@ -4845,6 +5168,9 @@ const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => {
4845
5168
  $ZodURL.init(inst, def);
4846
5169
  ZodStringFormat.init(inst, def);
4847
5170
  });
5171
+ function url(params) {
5172
+ return /* @__PURE__ */ _url(ZodURL, params);
5173
+ }
4848
5174
  const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => {
4849
5175
  $ZodEmoji.init(inst, def);
4850
5176
  ZodStringFormat.init(inst, def);
@@ -4994,6 +5320,14 @@ const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => {
4994
5320
  function boolean(params) {
4995
5321
  return /* @__PURE__ */ _boolean(ZodBoolean, params);
4996
5322
  }
5323
+ const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => {
5324
+ $ZodNull.init(inst, def);
5325
+ ZodType.init(inst, def);
5326
+ inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params);
5327
+ });
5328
+ function _null(params) {
5329
+ return /* @__PURE__ */ _null$1(ZodNull, params);
5330
+ }
4997
5331
  const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => {
4998
5332
  $ZodUnknown.init(inst, def);
4999
5333
  ZodType.init(inst, def);
@@ -5139,6 +5473,28 @@ function intersection(left, right) {
5139
5473
  right
5140
5474
  });
5141
5475
  }
5476
+ const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => {
5477
+ _ensureDefaultMemoizer();
5478
+ $ZodRecord.init(inst, def);
5479
+ ZodType.init(inst, def);
5480
+ inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params);
5481
+ inst.keyType = def.keyType;
5482
+ inst.valueType = def.valueType;
5483
+ });
5484
+ function record(keyType, valueType, params) {
5485
+ if (!valueType || !valueType._zod) return new ZodRecord({
5486
+ type: "record",
5487
+ keyType: string(),
5488
+ valueType: keyType,
5489
+ ...normalizeParams(valueType)
5490
+ });
5491
+ return new ZodRecord({
5492
+ type: "record",
5493
+ keyType,
5494
+ valueType,
5495
+ ...normalizeParams(params)
5496
+ });
5497
+ }
5142
5498
  const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => {
5143
5499
  $ZodEnum.init(inst, def);
5144
5500
  ZodType.init(inst, def);
@@ -5988,6 +6344,104 @@ function parseTaskRef(ref) {
5988
6344
  };
5989
6345
  }
5990
6346
  //#endregion
6347
+ //#region ../../packages/contract/src/runs.ts
6348
+ /**
6349
+ * Runs: a coding agent working on a task on the user's machine (docs/PLAN-ORCHESTRATOR.md). `monoban runner`
6350
+ * starts it and reports what it does as events; these turn the events into what a person reads.
6351
+ */
6352
+ /** How a run is going. `lost` isn't stored: a running run whose runner stopped answering. */
6353
+ const RUN_STATUSES = [
6354
+ "queued",
6355
+ "running",
6356
+ "succeeded",
6357
+ "failed",
6358
+ "needs_human",
6359
+ "cancelled",
6360
+ "lost"
6361
+ ];
6362
+ /** How a run can end (what a runner sends). */
6363
+ const RUN_ENDINGS$1 = [
6364
+ "succeeded",
6365
+ "failed",
6366
+ "needs_human",
6367
+ "cancelled"
6368
+ ];
6369
+ /** A step's status. Keep in sync with the check on task_run_events.status. */
6370
+ const STEP_STATUSES = [
6371
+ "running",
6372
+ "ok",
6373
+ "failed",
6374
+ "skipped",
6375
+ "cancelled",
6376
+ "needs_human"
6377
+ ];
6378
+ /** What a run reports. Keep in sync with the check on task_run_events.kind. */
6379
+ const RUN_EVENT_KINDS = [
6380
+ "step_started",
6381
+ "step_finished",
6382
+ "pr_opened",
6383
+ "board",
6384
+ "question",
6385
+ "warning",
6386
+ "error",
6387
+ "activity"
6388
+ ];
6389
+ /** Where a run works. Only on the runner's machine for now; remote (a fresh clone) comes later. */
6390
+ const RUN_MODES = ["local"];
6391
+ const RUN_LIMITS = {
6392
+ /** Events per run (the check in guard_task_run_event). */
6393
+ eventsPerRun: 2e3,
6394
+ /** Events in one POST. */
6395
+ eventsPerBatch: 200,
6396
+ eventMessage: 2e3,
6397
+ reason: 1e3,
6398
+ workdir: 1024,
6399
+ runnerName: 64,
6400
+ runnersPerUser: 20
6401
+ };
6402
+ /** A run that won't change any more (a lost one may: its runner can come back). */
6403
+ function isFinished(status) {
6404
+ return status !== "queued" && status !== "running" && status !== "lost";
6405
+ }
6406
+ /** "1m02", "45s", "1h05": how long a step or a run took. */
6407
+ function formatDuration(ms) {
6408
+ const seconds = Math.max(0, Math.round(ms / 1e3));
6409
+ if (seconds < 60) return `${seconds}s`;
6410
+ const minutes = Math.floor(seconds / 60);
6411
+ if (minutes < 60) return `${minutes}m${String(seconds % 60).padStart(2, "0")}`;
6412
+ return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}`;
6413
+ }
6414
+ /** "$0.31", "$0.004": what a run or step cost, to a cent once it's a cent or more. */
6415
+ function formatCost(usd) {
6416
+ if (usd >= .01 || usd === 0) return `$${usd.toFixed(2)}`;
6417
+ return `$${usd.toFixed(3)}`;
6418
+ }
6419
+ /** A run's status in a few words. */
6420
+ function describeRunStatus(run) {
6421
+ switch (run.status) {
6422
+ case "queued": return "waiting for the runner";
6423
+ case "running": return run.cancelRequested ? "cancelling" : "running";
6424
+ case "succeeded": return "done";
6425
+ case "failed": return "failed";
6426
+ case "needs_human": return "needs you";
6427
+ case "cancelled": return "cancelled";
6428
+ case "lost": return "lost (the runner stopped answering)";
6429
+ }
6430
+ }
6431
+ /** A step's mark in a list: ✓ ok, ● running, ✗ failed, – skipped, ■ cancelled, ? needs you. */
6432
+ const STEP_MARKS = {
6433
+ running: "●",
6434
+ ok: "✓",
6435
+ failed: "✗",
6436
+ skipped: "–",
6437
+ cancelled: "■",
6438
+ needs_human: "?"
6439
+ };
6440
+ /** Whether `workdir` is an absolute path a run can be given (macOS and Linux for now). */
6441
+ function isAbsolutePath(workdir) {
6442
+ return workdir.startsWith("/") && workdir.length <= RUN_LIMITS.workdir && !/[\u0000-\u001f\u007f]/.test(workdir);
6443
+ }
6444
+ //#endregion
5991
6445
  //#region ../../packages/contract/src/tags.ts
5992
6446
  /** One word, not starting with - or # (the CLI and the board filter read those). Same as the check on tags.name. */
5993
6447
  const TAG_NAME_PATTERN = /^[^\s#-]\S*$/;
@@ -6341,6 +6795,11 @@ const EventLink = object({
6341
6795
  title: string(),
6342
6796
  state: _enum(LINK_STATES).nullable()
6343
6797
  }).meta({ id: "EventLink" });
6798
+ const EventRun = object({
6799
+ id: IdSchema,
6800
+ adapter: string(),
6801
+ runner: string()
6802
+ }).meta({ id: "EventRun" });
6344
6803
  const event = (kind, shape) => object({
6345
6804
  /** Newer events have larger ids. */
6346
6805
  id: string().regex(/^[1-9][0-9]*$/),
@@ -6400,7 +6859,13 @@ discriminatedUnion("kind", [
6400
6859
  event("commented", { comment: object({
6401
6860
  id: IdSchema,
6402
6861
  excerpt: string()
6403
- }).meta({ id: "EventComment" }) })
6862
+ }).meta({ id: "EventComment" }) }),
6863
+ event("run_started", { run: EventRun }),
6864
+ event("run_finished", { run: EventRun.extend({
6865
+ status: _enum(RUN_ENDINGS$1),
6866
+ reason: string().nullable(),
6867
+ prUrl: string().nullable()
6868
+ }).meta({ id: "EventRunEnding" }) })
6404
6869
  ]).meta({ id: "TaskEvent" });
6405
6870
  /**
6406
6871
  * Every list takes `?limit=` and `?cursor=` and answers `{ <items>: [...], nextCursor }` (keyset
@@ -6415,6 +6880,184 @@ const PageQuerySchema = strictObject({
6415
6880
  limit: number().int().min(1).max(PAGE_LIMIT.max).default(PAGE_LIMIT.default).describe("Items per page"),
6416
6881
  cursor: string().min(1).max(1024).optional().describe("`nextCursor` from the previous page")
6417
6882
  });
6883
+ /** An agent a runner can run, by name: "agentpipe". */
6884
+ const AdapterSchema = string().regex(/^[a-z][a-z0-9-]{0,31}$/, "A lowercase name, like agentpipe");
6885
+ /** One line of text, no control characters. */
6886
+ const oneLine$1 = (max) => string().trim().min(1, "Required").max(max).regex(/^[^\u0000-\u001f\u007f]*$/, "One line");
6887
+ /** A machine that runs agents for you: `monoban runner`, running in a terminal there. */
6888
+ const RunnerSchema = object({
6889
+ id: IdSchema,
6890
+ /** The machine's name (its hostname, unless the runner was given another). */
6891
+ name: string(),
6892
+ /** The agents it can run. */
6893
+ adapters: array(string()),
6894
+ /** The CLI's version. */
6895
+ version: string().nullable(),
6896
+ /** How often it asks for work, in seconds. */
6897
+ pollSeconds: number$1().int(),
6898
+ /** It asked for work recently (within 30 seconds, or three of its intervals). */
6899
+ online: boolean(),
6900
+ lastSeenAt: Timestamp,
6901
+ createdAt: Timestamp
6902
+ }).meta({ id: "Runner" });
6903
+ strictObject({
6904
+ name: oneLine$1(RUN_LIMITS.runnerName),
6905
+ adapters: array(AdapterSchema).max(8),
6906
+ version: string().regex(/^[0-9A-Za-z.+-]{1,32}$/).optional(),
6907
+ /** How often it will ask for work (default 3). */
6908
+ pollSeconds: number$1().int().min(1).max(60).optional()
6909
+ }).meta({ id: "RunnerRegister" });
6910
+ /** What the agent may do. */
6911
+ const RunOptionsSchema = strictObject({
6912
+ /** Open a pull request as a draft, ready for review, or none (finish on a branch). */
6913
+ pr: _enum([
6914
+ "draft",
6915
+ "ready",
6916
+ "none"
6917
+ ]).default("draft"),
6918
+ /** The most the run may spend, in US dollars; the agent's own default when left out. */
6919
+ budgetUsd: number$1().min(.1).max(1e3).optional(),
6920
+ /** Decide on its own instead of waiting for answers (agentpipe). */
6921
+ autonomous: boolean().default(true),
6922
+ /** The model, as the agent names it ("opus", "gpt-5.5-codex"); the agent's own default when left out. */
6923
+ model: string().regex(/^[A-Za-z0-9][A-Za-z0-9._:/@[\]-]{0,63}$/, "A model name, like opus or gpt-5.5-codex").optional(),
6924
+ /** How far Codex may reach outside the folder: its sandbox (the default), with the network, or none. */
6925
+ access: _enum(AGENT_ACCESS).optional()
6926
+ }).meta({ id: "RunOptions" });
6927
+ /** A step of a run, worked out from its events. */
6928
+ const RunStepSchema = object({
6929
+ /** The agent's name for it: plan, implement, verify… */
6930
+ name: string(),
6931
+ attempt: number$1().int().positive(),
6932
+ status: _enum(STEP_STATUSES),
6933
+ startedAt: Timestamp,
6934
+ finishedAt: Timestamp.nullable(),
6935
+ durationMs: number$1().nullable(),
6936
+ costUsd: number$1().nullable(),
6937
+ /** What it used, from an agent that counts tokens instead of cost (Codex). */
6938
+ tokens: number$1().nullable(),
6939
+ /** Why it was skipped or failed. */
6940
+ message: string().nullable()
6941
+ }).meta({ id: "RunStep" });
6942
+ /** A coding agent working on a task, on one of your runners. */
6943
+ const TaskRunSchema = object({
6944
+ id: IdSchema,
6945
+ /** The task ("MON-12"); null once it's deleted. */
6946
+ ref: string().nullable(),
6947
+ runner: object({
6948
+ /** Null once the runner is gone. */
6949
+ id: IdSchema.nullable(),
6950
+ name: string(),
6951
+ online: boolean()
6952
+ }).meta({ id: "RunRunner" }),
6953
+ adapter: string(),
6954
+ mode: _enum(RUN_MODES),
6955
+ /** The checkout it works in, on the runner's machine. */
6956
+ workdir: string(),
6957
+ options: object({
6958
+ pr: _enum([
6959
+ "draft",
6960
+ "ready",
6961
+ "none"
6962
+ ]),
6963
+ budgetUsd: number$1().optional(),
6964
+ autonomous: boolean(),
6965
+ model: string().optional(),
6966
+ access: _enum(AGENT_ACCESS).optional()
6967
+ }).meta({ id: "RunOptionsSet" }),
6968
+ status: _enum(RUN_STATUSES),
6969
+ /** Why it ended the way it did, or what it's waiting for. */
6970
+ reason: string().nullable(),
6971
+ /** The agent's own id for the run (agentpipe's r-20261015-…). */
6972
+ externalId: string().nullable(),
6973
+ prUrl: string().nullable(),
6974
+ costUsd: number$1().nullable(),
6975
+ /** Someone asked it to stop; it will at its next checkpoint. */
6976
+ cancelRequested: boolean(),
6977
+ version: Version,
6978
+ createdAt: Timestamp,
6979
+ startedAt: Timestamp.nullable(),
6980
+ finishedAt: Timestamp.nullable(),
6981
+ updatedAt: Timestamp
6982
+ }).meta({ id: "TaskRun" });
6983
+ TaskRunSchema.extend({ steps: array(RunStepSchema) }).meta({ id: "TaskRunDetail" });
6984
+ /** A run for a runner to start: with what it needs to check the folder (the project's key and repo). */
6985
+ const RunToStartSchema = TaskRunSchema.extend({ project: object({
6986
+ key: string(),
6987
+ repo: string().nullable()
6988
+ }).meta({ id: "RunProject" }) }).meta({ id: "RunToStart" });
6989
+ strictObject({
6990
+ runnerId: IdSchema,
6991
+ /** An absolute path on the runner's machine: a checkout of the project's linked repository. */
6992
+ workdir: string().trim().min(1, "Required").max(RUN_LIMITS.workdir).refine(isAbsolutePath, "An absolute path, like /Users/you/code/project").meta({ pattern: "^/" }),
6993
+ /** The agent (agents.ts); the runner must have it, and it must take the options (default agentpipe). */
6994
+ adapter: AdapterSchema.optional(),
6995
+ mode: _enum(RUN_MODES).default("local"),
6996
+ options: RunOptionsSchema.default({
6997
+ pr: "draft",
6998
+ autonomous: true
6999
+ })
7000
+ }).superRefine((run, ctx) => {
7001
+ const agent = run.adapter ?? "agentpipe";
7002
+ const option = unsupportedOption(agent, run.options);
7003
+ if (option) {
7004
+ const what = option === "autonomous" ? "waiting for answers" : option;
7005
+ ctx.addIssue({
7006
+ code: "custom",
7007
+ path: ["options", option],
7008
+ message: `${agentLabel(agent)} doesn't take ${what}.`
7009
+ });
7010
+ }
7011
+ }).meta({
7012
+ id: "TaskRunCreate",
7013
+ description: "The options must be ones the agent takes (packages/contract/src/agents.ts)."
7014
+ });
7015
+ strictObject({
7016
+ cancel: literal(true).optional(),
7017
+ status: _enum(["running", ...RUN_ENDINGS$1]).optional(),
7018
+ reason: string().max(RUN_LIMITS.reason).nullable().optional(),
7019
+ externalId: string().regex(/^[\x21-\x7e]{1,128}$/).optional(),
7020
+ prUrl: url({ protocol: /^https$/ }).max(2e3).optional(),
7021
+ costUsd: number$1().min(0).max(99999999).optional()
7022
+ }).refine((p) => Object.keys(p).length > 0, "Send something to change").meta({
7023
+ id: "TaskRunPatch",
7024
+ minProperties: 1
7025
+ });
7026
+ object({
7027
+ /** The runner numbers them from 1, in order. */
7028
+ seq: number$1().int().positive(),
7029
+ kind: _enum(RUN_EVENT_KINDS),
7030
+ step: string().nullable(),
7031
+ attempt: number$1().int().nullable(),
7032
+ status: _enum(STEP_STATUSES).nullable(),
7033
+ message: string().nullable(),
7034
+ /** step_finished: durationMs, costUsd, tokens; pr_opened: url, number. */
7035
+ data: record(string(), unknown()),
7036
+ /** When it happened, by the runner's clock. */
7037
+ at: Timestamp
7038
+ }).meta({ id: "RunEvent" });
7039
+ strictObject({ events: array(strictObject({
7040
+ seq: number$1().int().positive().max(1e6),
7041
+ kind: _enum(RUN_EVENT_KINDS),
7042
+ step: string().regex(/^[a-z][a-z0-9_.-]{0,39}$/).optional(),
7043
+ attempt: number$1().int().min(1).max(1e3).optional(),
7044
+ status: _enum(STEP_STATUSES).optional(),
7045
+ message: string().max(RUN_LIMITS.eventMessage).regex(/^[^\u0000]*$/, "Can't contain NUL characters").optional(),
7046
+ data: record(string(), union([
7047
+ string().max(2e3),
7048
+ number$1(),
7049
+ boolean(),
7050
+ _null()
7051
+ ])).optional(),
7052
+ at: Timestamp
7053
+ })).min(1).max(RUN_LIMITS.eventsPerBatch) }).meta({ id: "RunEventsCreate" });
7054
+ object({
7055
+ runner: RunnerSchema,
7056
+ /** Queued for it, oldest first (at most 5). */
7057
+ queued: array(RunToStartSchema),
7058
+ /** Running on it: one it doesn't know of was left behind; `cancelRequested` asks it to stop. */
7059
+ running: array(TaskRunSchema)
7060
+ }).meta({ id: "RunnerWork" });
6418
7061
  PageQuerySchema.extend({
6419
7062
  from: DaySchema.describe("The first day (the client's today, for Today)"),
6420
7063
  to: DaySchema.optional().describe("The last day (`from` when left out); at most 62 days after `from`"),
@@ -7221,6 +7864,25 @@ function describeEvent(event, now = today()) {
7221
7864
  verb: "commented",
7222
7865
  detail: event.comment.excerpt
7223
7866
  };
7867
+ case "run_started": return {
7868
+ verb: "run started",
7869
+ detail: `${event.run.adapter} on ${event.run.runner}`
7870
+ };
7871
+ case "run_finished": {
7872
+ const { status, reason, prUrl } = event.run;
7873
+ return {
7874
+ verb: {
7875
+ succeeded: "run done",
7876
+ failed: "run failed",
7877
+ needs_human: "run needs you",
7878
+ cancelled: "run cancelled"
7879
+ }[status],
7880
+ detail: [prUrl && eventLinkName({
7881
+ url: prUrl,
7882
+ kind: "pr"
7883
+ }), status !== "succeeded" && reason].filter(Boolean).join(" · ")
7884
+ };
7885
+ }
7224
7886
  }
7225
7887
  }
7226
7888
  const MINUTE = 6e4;
@@ -7327,7 +7989,7 @@ strictObject({ email: email().max(254).meta({ example: "ada@example.com" }) }).m
7327
7989
  //#endregion
7328
7990
  //#region src/version.ts
7329
7991
  /** This CLI's version, from package.json (set at build time by tsdown, and by vitest in tests). */
7330
- const VERSION = "1.3.0";
7992
+ const VERSION = "1.5.0";
7331
7993
  /** Sent as X-Monoban-Client, and shown in Devices & tokens. */
7332
7994
  const CLIENT = `cli/${VERSION}`;
7333
7995
  //#endregion
@@ -11773,6 +12435,7 @@ async function tags(ctx, options) {
11773
12435
  async function move(ctx, ref, columnQuery, options) {
11774
12436
  const api = apis(ctx).signedIn;
11775
12437
  const task = await taskByRef(api, ref, ctx);
12438
+ if (options.ifColumnSince !== void 0) unmovedSince(task, options.ifColumnSince);
11776
12439
  const { key } = taskRefOf(task.ref);
11777
12440
  const to = options.to?.trim().toUpperCase();
11778
12441
  if (to && to !== key) return transfer(ctx, api, task, to, columnQuery, options);
@@ -11783,6 +12446,15 @@ async function move(ctx, ref, columnQuery, options) {
11783
12446
  const columns = await columnsOf(api, key);
11784
12447
  await moveTo(ctx, api, task, columns, findColumn(columns, columnQuery), options);
11785
12448
  }
12449
+ /**
12450
+ * --if-column-since: only a task still in the column it arrived in at `since` (its columnSince then). The
12451
+ * write that follows carries the version this read saw, so a move in between is a 412 too.
12452
+ */
12453
+ function unmovedSince(task, since) {
12454
+ const at = Date.parse(since);
12455
+ if (Number.isNaN(at)) throw new CliError(`--if-column-since takes a time like 2026-10-14T10:00:00Z (a task's columnSince).`, EXIT.usage);
12456
+ if (Date.parse(task.columnSince) !== at) throw new CliError(`${task.ref} changed elsewhere in the meantime: it has been in its column since ${task.columnSince}, not ${since}.`);
12457
+ }
11786
12458
  /** Moves a task to project `to` (its column `columnQuery`, if given). */
11787
12459
  async function transfer(ctx, api, task, to, columnQuery, options) {
11788
12460
  const columns = await columnsOf(api, to);
@@ -12137,51 +12809,1916 @@ async function notesEdit(ctx, options) {
12137
12809
  ctx.out(`Updated the notes of ${key}.`);
12138
12810
  }
12139
12811
  //#endregion
12140
- //#region src/commands/search.ts
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;
12141
12830
  /**
12142
- * `monoban search login page`: the tasks with all of these words (in the title or description, as a tag, or
12143
- * as the reference), in every project, the last changed first, archived ones too. `-n` of them, 30 unless
12144
- * you say.
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).
12145
12835
  */
12146
- async function search(ctx, words, options) {
12147
- const q = words.join(" ").trim();
12148
- if (!q) throw new CliError("Say what to look for: monoban search login page", EXIT.usage);
12149
- const count = options.number === void 0 ? 30 : Number(options.number);
12150
- if (!Number.isInteger(count) || count < 1) throw new CliError("-n is how many tasks to show: 1 or more.", EXIT.usage);
12151
- const api = apis(ctx).signedIn;
12152
- const tasks = [];
12153
- let cursor;
12154
- do {
12155
- const limit = Math.min(count - tasks.length, PAGE_LIMIT.max);
12156
- const page = await unwrap(api.GET("/v1/search", { params: { query: {
12157
- q,
12158
- limit,
12159
- cursor
12160
- } } }));
12161
- tasks.push(...page.tasks);
12162
- cursor = page.nextCursor ?? void 0;
12163
- } while (cursor && tasks.length < count);
12164
- if (options.json) return ctx.out(JSON.stringify(tasks, null, 2));
12165
- if (tasks.length === 0) {
12166
- ctx.err(`No task has "${q}".`);
12167
- return;
12168
- }
12169
- const { dim, color } = ctx.style;
12170
- const refWidth = Math.max(...tasks.map((t) => t.ref.length));
12171
- const columnWidth = Math.max(...tasks.map((t) => [...t.column.name].length));
12172
- for (const t of tasks) {
12173
- const mark = t.done ? color("green", "✓") : " ";
12174
- const column = `${t.column.name}${" ".repeat(columnWidth - [...t.column.name].length)}`;
12175
- const title = t.done ? dim(oneLine(t.title)) : oneLine(t.title);
12176
- ctx.out(`${mark} ${t.ref.padEnd(refWidth)} ${dim(column)} ${title}${t.archived ? ` ${dim("archived")}` : ""}`);
12177
- }
12178
- if (cursor) ctx.err(`More tasks have it: -n ${count * 5} shows more.`);
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, " ")
12867
+ };
12868
+ };
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 }
12894
+ });
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 }
12943
+ });
12944
+ return;
12945
+ }
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;
12954
+ }
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)
12996
+ });
12997
+ return;
12998
+ }
12999
+ }
13000
+ };
13001
+ return {
13002
+ take,
13003
+ /** How agentpipe said the run ended (null: it didn't). */
13004
+ ending: () => ending,
13005
+ flush: () => flush()
13006
+ };
13007
+ }
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;
13017
+ }
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
+ ];
13030
+ }
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
+ };
13104
+ }
13105
+ };
12179
13106
  }
12180
13107
  //#endregion
12181
- //#region src/skill.ts
12182
- /** The coding agents `monoban setup` teaches monoban to. */
12183
- const AGENTS = ["claude", "codex"];
12184
- const AGENT_NAMES = {
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)"
13366
+ ];
13367
+ if (comments.length) {
13368
+ lines.push("", "## Its latest comments, oldest first", "");
13369
+ for (const c of comments) lines.push(`- ${c.via ? `(${c.via}) ` : ""}${c.body.trim().replace(/\n+/g, "\n ")}`);
13370
+ }
13371
+ lines.push("", "## How to work", "", `- You're in a git checkout of the project, on the branch ${branch}, made for this task. Stay on it.`, "- Do what the task asks, and only that. Follow the repository's own instructions (CLAUDE.md, AGENTS.md, CONTRIBUTING, the README) and run its checks (tests, lint, typecheck) before you finish.", "- Commit your work on this branch with clear messages (if git won't let you, leave the changes: they're committed for you). Don't push, don't open a pull request and don't change the monoban board: that's done for you when you finish.", "- Nobody is watching to answer questions. When something is unclear, make a reasonable choice and say so in your summary. Stop as blocked only when you can't go on without an answer.", "", "End with a JSON object, and nothing after it: {\"status\": \"done\" or \"blocked\", \"summary\": what you changed and how you checked it, \"prTitle\": a pull request title, \"question\": what you need to know when blocked, else \"\"}.");
13372
+ return lines.join("\n");
13373
+ }
13374
+ //#endregion
13375
+ //#region src/runner/workspace.ts
13376
+ var WorkspaceError = class extends Error {};
13377
+ /** Runs a command in `cwd`: its stdout, or a WorkspaceError with what it said on stderr. */
13378
+ function runIn(cwd, env) {
13379
+ return (command, args, timeoutMs = 3e4) => new Promise((resolve, reject) => {
13380
+ execFile(command, args, {
13381
+ cwd,
13382
+ env,
13383
+ timeout: timeoutMs,
13384
+ maxBuffer: 8388608
13385
+ }, (err, stdout, stderr) => {
13386
+ if (!err) return resolve(String(stdout).trim());
13387
+ if (err.code === "ENOENT") {
13388
+ if (!existsSync(cwd)) return reject(new WorkspaceError(`${cwd} isn't there any more.`));
13389
+ return reject(new WorkspaceError(command === "gh" ? "The GitHub CLI (gh) isn't installed here: https://cli.github.com" : `${command} isn't installed here.`));
13390
+ }
13391
+ const said = String(stderr).trim().split("\n").filter(Boolean).slice(-3).join(" ");
13392
+ reject(new WorkspaceError(`${command} ${args[0]}: ${said || err.message}`));
13393
+ });
13394
+ });
13395
+ }
13396
+ function workspace(cwd, env = process.env) {
13397
+ const run = runIn(cwd, env);
13398
+ const git = (...args) => run("git", args);
13399
+ const quiet = (...args) => git(...args).catch(() => null);
13400
+ return {
13401
+ dirty: async () => (await git("status", "--porcelain")).length > 0,
13402
+ baseBranch: async () => {
13403
+ const remote = await quiet("symbolic-ref", "--short", "refs/remotes/origin/HEAD");
13404
+ if (remote?.startsWith("origin/")) return remote.slice(7);
13405
+ return await quiet("symbolic-ref", "--short", "HEAD") || "main";
13406
+ },
13407
+ fetch: async (base) => await run("git", [
13408
+ "fetch",
13409
+ "origin",
13410
+ base
13411
+ ], 12e4).catch(() => null) !== null,
13412
+ checkout: async (branch, base) => {
13413
+ if (await quiet("rev-parse", "--verify", "--quiet", `refs/heads/${branch}`) !== null) {
13414
+ await git("switch", branch);
13415
+ return "existing";
13416
+ }
13417
+ const from = await quiet("rev-parse", "--verify", "--quiet", `refs/remotes/origin/${base}`) ? `origin/${base}` : base;
13418
+ await git("switch", "--no-track", "-c", branch, from);
13419
+ return "new";
13420
+ },
13421
+ head: () => git("rev-parse", "HEAD"),
13422
+ commitAll: async (message) => {
13423
+ await git("add", "-A");
13424
+ if ((await git("diff", "--cached", "--name-only")).length === 0) return false;
13425
+ await git("commit", "-m", message);
13426
+ return true;
13427
+ },
13428
+ commitsSince: async (sha) => Number(await git("rev-list", "--count", `${sha}..HEAD`)) || 0,
13429
+ push: async (branch) => {
13430
+ await run("git", [
13431
+ "push",
13432
+ "--set-upstream",
13433
+ "origin",
13434
+ branch
13435
+ ], 3e5);
13436
+ },
13437
+ pullRequestOf: async (branch) => {
13438
+ const out = await run("gh", [
13439
+ "pr",
13440
+ "list",
13441
+ "--head",
13442
+ branch,
13443
+ "--state",
13444
+ "open",
13445
+ "--json",
13446
+ "url",
13447
+ "--limit",
13448
+ "1"
13449
+ ]);
13450
+ const [first] = JSON.parse(out || "[]");
13451
+ return first?.url ?? null;
13452
+ },
13453
+ openPullRequest: async ({ base, branch, title, body, draft }) => {
13454
+ const out = await run("gh", [
13455
+ "pr",
13456
+ "create",
13457
+ "--base",
13458
+ base,
13459
+ "--head",
13460
+ branch,
13461
+ "--title",
13462
+ title,
13463
+ "--body",
13464
+ body,
13465
+ ...draft ? ["--draft"] : []
13466
+ ], 12e4);
13467
+ const url = out.split("\n").find((l) => /^https:\/\/\S+\/pull\/\d+/.test(l.trim()));
13468
+ if (!url) throw new WorkspaceError(`gh pr create didn't say where the pull request is: ${out.slice(0, 200)}`);
13469
+ return url.trim();
13470
+ }
13471
+ };
13472
+ }
13473
+ //#endregion
13474
+ //#region src/runner/agents/coding.ts
13475
+ /** Secrets a command line or an error might carry, kept out of what the board shows. */
13476
+ const SECRETS = [
13477
+ [/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/g, "…"],
13478
+ [/\bsk-[A-Za-z0-9_-]{16,}/g, "…"],
13479
+ [/\bmbn_[A-Za-z0-9_]{8,}/g, "…"],
13480
+ [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, "…"],
13481
+ [/\bAKIA[0-9A-Z]{16}\b/g, "…"],
13482
+ [/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1…"],
13483
+ [/((?:token|secret|passw(?:or)?d|api[_-]?key|auth)[A-Za-z_]*["']?\s*[=:]\s*["']?)(?!Bearer\b|Basic\b)[^\s"']+/gi, "$1…"]
13484
+ ];
13485
+ function redact(text) {
13486
+ return SECRETS.reduce((t, [pattern, by]) => t.replace(pattern, by), text);
13487
+ }
13488
+ /** A message the API takes (and the board shows), secrets out. */
13489
+ function clip(text, max = 2e3) {
13490
+ const clean = redact(text).trim();
13491
+ return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;
13492
+ }
13493
+ /** A command's first line ("pnpm test"), for "$ pnpm test". */
13494
+ function firstLine(command) {
13495
+ const text = typeof command === "string" ? command.trim() : "";
13496
+ const [line = ""] = text.split("\n");
13497
+ return text.includes("\n") ? `${line} …` : line;
13498
+ }
13499
+ /**
13500
+ * A path inside the run's folder, from it ("src/a.ts"); others as they are. `roots` are the folder as given
13501
+ * and as it really is (an agent reports /private/var/… for /var/… on macOS).
13502
+ */
13503
+ function relativeTo(roots, path) {
13504
+ const p = typeof path === "string" ? path : "";
13505
+ for (const r of roots) {
13506
+ const root = r.endsWith("/") ? r : `${r}/`;
13507
+ if (p.startsWith(root)) return p.slice(root.length);
13508
+ }
13509
+ return p;
13510
+ }
13511
+ /** "plan: 2/5 done", from a to-do list. */
13512
+ function planLine(items) {
13513
+ return `plan: ${items.filter((i) => i.done).length}/${items.length} done`;
13514
+ }
13515
+ /**
13516
+ * Activity reaches the board a few seconds apart at most: the first at once, then the latest one at the end
13517
+ * of each wait (what it's doing now, not everything it did).
13518
+ */
13519
+ function throttled(send, ms) {
13520
+ let last = Number.NEGATIVE_INFINITY;
13521
+ let pending = null;
13522
+ let timer;
13523
+ const fire = (message) => {
13524
+ last = Date.now();
13525
+ send(message);
13526
+ };
13527
+ return {
13528
+ push(message) {
13529
+ const wait = last + ms - Date.now();
13530
+ if (wait <= 0 && !timer) return fire(message);
13531
+ pending = message;
13532
+ timer ??= setTimeout(() => {
13533
+ timer = void 0;
13534
+ if (pending !== null) fire(pending);
13535
+ pending = null;
13536
+ }, Math.max(0, wait));
13537
+ },
13538
+ stop() {
13539
+ clearTimeout(timer);
13540
+ timer = void 0;
13541
+ pending = null;
13542
+ }
13543
+ };
13544
+ }
13545
+ function codingAgent({ spec, command, args: extra = [], board, env = process.env, open = workspace, spawn, activityMs = 3e3, graceMs }) {
13546
+ const label = agentLabel(spec.name);
13547
+ return {
13548
+ name: spec.name,
13549
+ start(run, report) {
13550
+ let cancelled = false;
13551
+ let agent = null;
13552
+ const begin = (step) => {
13553
+ const started = Date.now();
13554
+ report.event({
13555
+ kind: "step_started",
13556
+ step,
13557
+ attempt: 1,
13558
+ status: "running"
13559
+ });
13560
+ return (status, message, data = {}) => report.event({
13561
+ kind: "step_finished",
13562
+ step,
13563
+ attempt: 1,
13564
+ status,
13565
+ ...message && { message: clip(message) },
13566
+ data: {
13567
+ durationMs: Date.now() - started,
13568
+ ...data
13569
+ }
13570
+ });
13571
+ };
13572
+ const warn = (message) => report.event({
13573
+ kind: "warning",
13574
+ message: clip(message)
13575
+ });
13576
+ /** Says on the task how it went; a failure to is a warning, not the run's ending. */
13577
+ let ref = run.ref;
13578
+ const tell = (body) => board.comment(ref, body).catch((err) => warn(`Couldn't comment on ${ref}: ${err.message}`));
13579
+ const flow = async () => {
13580
+ const ws = open(run.workdir, env);
13581
+ let end = begin("prepare");
13582
+ let branch;
13583
+ let base;
13584
+ let startSha;
13585
+ let prompt;
13586
+ let title;
13587
+ try {
13588
+ if (await ws.dirty()) {
13589
+ const reason = `${run.workdir} has uncommitted changes: commit or stash them, then run it again.`;
13590
+ end("failed", reason);
13591
+ return {
13592
+ status: "failed",
13593
+ reason
13594
+ };
13595
+ }
13596
+ const { task, comments } = await board.task(run.ref);
13597
+ ref = task.ref;
13598
+ title = task.title;
13599
+ base = await ws.baseBranch();
13600
+ if (!await ws.fetch(base)) warn(`Couldn't fetch ${base} from origin: it starts from the copy here.`);
13601
+ branch = branchName(task.ref, task.title);
13602
+ await ws.checkout(branch, base);
13603
+ startSha = await ws.head();
13604
+ const moved = await board.startWork(ref).catch((err) => {
13605
+ warn(`Couldn't move ${ref}: ${err.message}`);
13606
+ return null;
13607
+ });
13608
+ if (moved) report.event({
13609
+ kind: "board",
13610
+ message: clip(moved)
13611
+ });
13612
+ prompt = buildPrompt({
13613
+ task,
13614
+ comments,
13615
+ branch
13616
+ });
13617
+ end("ok");
13618
+ } catch (err) {
13619
+ const reason = clip(`Couldn't get the folder ready: ${err.message}`, 1e3);
13620
+ end("failed", reason);
13621
+ return {
13622
+ status: "failed",
13623
+ reason
13624
+ };
13625
+ }
13626
+ if (cancelled) return {
13627
+ status: "cancelled",
13628
+ reason: "Cancelled before the agent started."
13629
+ };
13630
+ end = begin("code");
13631
+ const limited = spec.limit?.(run.options);
13632
+ if (limited) report.event({
13633
+ kind: "warning",
13634
+ step: "code",
13635
+ message: clip(limited.warning)
13636
+ });
13637
+ const asked = limited ? {
13638
+ ...run,
13639
+ options: limited.options
13640
+ } : run;
13641
+ const dir = await mkdtemp(join(tmpdir(), "monoban-run-"));
13642
+ const schemaFile = join(dir, "outcome.schema.json");
13643
+ const schema = JSON.stringify(OUTCOME_SCHEMA);
13644
+ await writeFile(schemaFile, schema);
13645
+ const reader = spec.reader([run.workdir, await realpath(run.workdir).catch(() => run.workdir)]);
13646
+ const activity = throttled((message) => report.event({
13647
+ kind: "activity",
13648
+ step: "code",
13649
+ message: clip(message, 200)
13650
+ }), activityMs);
13651
+ const out = {
13652
+ activity: (m) => m.trim() && activity.push(m),
13653
+ warning: (m) => report.event({
13654
+ kind: "warning",
13655
+ step: "code",
13656
+ message: clip(m)
13657
+ }),
13658
+ externalId: (id) => report.update({ externalId: id.slice(0, 128) })
13659
+ };
13660
+ agent = startProcess({
13661
+ command,
13662
+ args: spec.args(asked, {
13663
+ schema,
13664
+ schemaFile
13665
+ }, extra),
13666
+ cwd: run.workdir,
13667
+ env,
13668
+ stdin: prompt,
13669
+ onLine: (line) => {
13670
+ try {
13671
+ reader.line(line, out);
13672
+ } catch {}
13673
+ },
13674
+ ...spawn && { spawn },
13675
+ ...graceMs !== void 0 && { graceMs }
13676
+ });
13677
+ if (cancelled) agent.stop();
13678
+ const exit = await agent.done;
13679
+ agent = null;
13680
+ activity.stop();
13681
+ await rm(dir, {
13682
+ recursive: true,
13683
+ force: true
13684
+ });
13685
+ const result = reader.result();
13686
+ const data = {};
13687
+ if (result.costUsd !== null) {
13688
+ data.costUsd = result.costUsd;
13689
+ report.update({ costUsd: Math.round(result.costUsd * 1e4) / 1e4 });
13690
+ }
13691
+ if (result.tokens !== null) data.tokens = result.tokens;
13692
+ const outcome = parseOutcome(result.answer);
13693
+ let failure = null;
13694
+ if (cancelled) end("cancelled", null, data);
13695
+ else {
13696
+ failure = exit.spawnError ?? result.failure ?? (exit.code === 0 ? null : `${label} stopped (exit code ${exit.code ?? "none"})${exit.lastError ? `: ${exit.lastError}` : "."}`);
13697
+ if (failure) end("failed", failure, data);
13698
+ else if (outcome?.status === "blocked") end("needs_human", outcome.question || outcome.summary, data);
13699
+ else end("ok", null, data);
13700
+ }
13701
+ if (exit.spawnError) return {
13702
+ status: "failed",
13703
+ reason: clip(exit.spawnError, 1e3)
13704
+ };
13705
+ end = begin("commit");
13706
+ const unfinished = cancelled || failure !== null;
13707
+ let commits = 0;
13708
+ try {
13709
+ const message = unfinished ? `${ref}: work in progress (the ${label} run ${cancelled ? "was cancelled" : "failed"})` : `${ref}: ${outcome?.prTitle || title}`;
13710
+ const left = await ws.commitAll(message);
13711
+ commits = await ws.commitsSince(startSha);
13712
+ end(commits ? "ok" : "skipped", commits ? null : "nothing changed", { commits });
13713
+ if (left && unfinished) report.event({
13714
+ kind: "board",
13715
+ message: `kept its unfinished work on ${branch}`
13716
+ });
13717
+ } catch (err) {
13718
+ end("failed", err.message);
13719
+ failure ??= `Couldn't commit its work: ${err.message}`;
13720
+ }
13721
+ const kept = commits ? `\n\nIts work so far is on the branch \`${branch}\`.` : "";
13722
+ if (cancelled) return {
13723
+ status: "cancelled",
13724
+ reason: commits ? `Cancelled; its work so far is on ${branch}.` : null
13725
+ };
13726
+ if (failure) {
13727
+ await tell(`${label} couldn't finish: ${clip(failure, 1e3)}${kept}`);
13728
+ return {
13729
+ status: "failed",
13730
+ reason: clip(failure, 1e3)
13731
+ };
13732
+ }
13733
+ if (outcome?.status === "blocked") {
13734
+ const question = outcome.question || outcome.summary || "It got stuck without saying why.";
13735
+ report.event({
13736
+ kind: "question",
13737
+ message: clip(question)
13738
+ });
13739
+ await tell(`${label} needs an answer: ${clip(question, 1500)}${kept}`);
13740
+ return {
13741
+ status: "needs_human",
13742
+ reason: clip(question, 1e3)
13743
+ };
13744
+ }
13745
+ const summary = outcome?.summary || (typeof result.answer === "string" ? result.answer : "");
13746
+ if (!commits) {
13747
+ const reason = `${label} changed nothing${summary ? `: ${summary}` : "."}`;
13748
+ await tell(`${label} made no changes.${summary ? `\n\n${clip(summary, 1500)}` : ""}`);
13749
+ return {
13750
+ status: "needs_human",
13751
+ reason: clip(reason, 1e3)
13752
+ };
13753
+ }
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
+ };
13786
+ }
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"
13795
+ });
13796
+ end("ok");
13797
+ } catch (err) {
13798
+ end("failed", err.message);
13799
+ }
13800
+ return {
13801
+ status: "succeeded",
13802
+ reason: null
13803
+ };
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
+ };
13815
+ }
13816
+ };
13817
+ }
13818
+ //#endregion
13819
+ //#region src/runner/agents/claude.ts
13820
+ /**
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.
13825
+ */
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}` : "."}`;
13855
+ }
13856
+ function claudeReader(roots) {
13857
+ let answer = null;
13858
+ let lastText = null;
13859
+ let costUsd = null;
13860
+ let failure = null;
13861
+ let ended = false;
13862
+ 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;
13886
+ }
13887
+ }
13888
+ },
13889
+ result: () => ({
13890
+ answer: ended ? answer : lastText,
13891
+ costUsd,
13892
+ tokens: null,
13893
+ failure
13894
+ })
13895
+ };
13896
+ }
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
+ //#endregion
13917
+ //#region src/runner/agents/codex.ts
13918
+ /** `bash -lc 'pnpm test'` → `pnpm test`: the command inside the shell Codex runs it with. */
13919
+ function shellCommand(command) {
13920
+ const text = typeof command === "string" ? command.trim() : "";
13921
+ const inner = /^(?:\S*\/)?(?:ba|z)?sh\s+-l?c\s+(['"])([\s\S]*)\1$/.exec(text);
13922
+ if (!inner?.[2]) return firstLine(text);
13923
+ return firstLine(inner[1] === "\"" ? inner[2].replace(/\\(["\\$`])/g, "$1") : inner[2].replace(/'\\''/g, "'"));
13924
+ }
13925
+ function codexReader(roots) {
13926
+ let answer = null;
13927
+ let tokens = 0;
13928
+ let failure = null;
13929
+ return {
13930
+ line(text, out) {
13931
+ if (!text.trim().startsWith("{")) return;
13932
+ const line = JSON.parse(text);
13933
+ const item = line.item ?? {};
13934
+ switch (line.type) {
13935
+ case "thread.started":
13936
+ if (line.thread_id) out.externalId(line.thread_id);
13937
+ out.activity("started");
13938
+ return;
13939
+ case "item.started":
13940
+ if (item.type === "command_execution") out.activity(`$ ${shellCommand(item.command)}`);
13941
+ return;
13942
+ case "item.updated":
13943
+ if (item.type === "todo_list" && item.items) out.activity(planLine(item.items.map((i) => ({ done: Boolean(i.completed) }))));
13944
+ return;
13945
+ case "item.completed":
13946
+ switch (item.type) {
13947
+ case "agent_message":
13948
+ if (item.text?.trim()) answer = item.text;
13949
+ return;
13950
+ case "file_change": {
13951
+ const paths = (item.changes ?? []).map((c) => relativeTo(roots, c.path)).filter(Boolean);
13952
+ const more = paths.length > 3 ? ` and ${paths.length - 3} more` : "";
13953
+ if (paths.length) out.activity(`edit ${paths.slice(0, 3).join(", ")}${more}`);
13954
+ return;
13955
+ }
13956
+ case "mcp_tool_call":
13957
+ out.activity(`${item.server ?? "mcp"}: ${item.tool ?? "a tool"}`);
13958
+ return;
13959
+ case "web_search":
13960
+ out.activity(`search the web: ${item.query ?? ""}`);
13961
+ return;
13962
+ case "todo_list":
13963
+ out.activity(planLine((item.items ?? []).map((i) => ({ done: Boolean(i.completed) }))));
13964
+ return;
13965
+ case "error":
13966
+ if (item.message) out.warning(item.message);
13967
+ return;
13968
+ }
13969
+ return;
13970
+ case "turn.completed":
13971
+ tokens += (line.usage?.input_tokens ?? 0) + (line.usage?.output_tokens ?? 0);
13972
+ return;
13973
+ case "turn.failed":
13974
+ failure = line.error?.message?.trim() || "Its turn failed.";
13975
+ return;
13976
+ }
13977
+ },
13978
+ result: () => ({
13979
+ answer,
13980
+ costUsd: null,
13981
+ tokens: tokens || null,
13982
+ failure
13983
+ })
13984
+ };
13985
+ }
13986
+ /**
13987
+ * Codex as this machine runs it: without its sandbox (a run's `access: full`) only when the runner allows it
13988
+ * (runner.json's adapters.codex.allowFullAccess, or --allow-full-access); otherwise in the sandbox, saying so.
13989
+ * A run is queued from the web or with a token, so the machine's owner decides how far it may reach.
13990
+ */
13991
+ const codexSpec = ({ allowFullAccess = false } = {}) => ({
13992
+ name: "codex",
13993
+ limit: (options) => options.access === "full" && !allowFullAccess ? {
13994
+ options: {
13995
+ ...options,
13996
+ access: "sandbox"
13997
+ },
13998
+ warning: "Full access isn't allowed on this runner, so it runs in the sandbox (no network). Allow it with adapters.codex.allowFullAccess in runner.json, or monoban runner --allow-full-access."
13999
+ } : null,
14000
+ args: (run, { schemaFile }, extra) => [
14001
+ "exec",
14002
+ "--json",
14003
+ "--color",
14004
+ "never",
14005
+ "--sandbox",
14006
+ run.options.access === "full" ? "danger-full-access" : "workspace-write",
14007
+ ...run.options.access === "network" ? ["-c", "sandbox_workspace_write.network_access=true"] : [],
14008
+ "--output-schema",
14009
+ schemaFile,
14010
+ ...run.options.model ? ["--model", run.options.model] : [],
14011
+ ...extra,
14012
+ "-"
14013
+ ],
14014
+ reader: codexReader
14015
+ });
14016
+ codexSpec();
14017
+ //#endregion
14018
+ //#region src/runner/agents/index.ts
14019
+ const DEFINITIONS = {
14020
+ agentpipe: { create: (d) => agentpipe({
14021
+ command: d.command,
14022
+ args: d.args,
14023
+ env: d.env
14024
+ }) },
14025
+ claude: {
14026
+ minimum: CLAUDE_MINIMUM,
14027
+ update: "claude update",
14028
+ create: ({ allowFullAccess: _, ...d }) => codingAgent({
14029
+ spec: claude,
14030
+ ...d
14031
+ })
14032
+ },
14033
+ codex: { create: ({ allowFullAccess, ...d }) => codingAgent({
14034
+ spec: codexSpec({ allowFullAccess }),
14035
+ ...d
14036
+ }) }
14037
+ };
14038
+ /**
14039
+ * The agents installed here (their command answers --version), as many as `settings.agents` allows, and why
14040
+ * each of the others isn't offered.
14041
+ */
14042
+ async function detectAgents(settings, env, version = versionOf) {
14043
+ const names = settings.agents ?? Object.keys(AGENTS$1);
14044
+ const checked = await Promise.all(names.map(async (name) => ({
14045
+ name,
14046
+ version: await version(settings.commands[name], env)
14047
+ })));
14048
+ const found = [];
14049
+ const missing = [];
14050
+ for (const { name, version: v } of checked) {
14051
+ const { minimum, update } = DEFINITIONS[name];
14052
+ const label = agentLabel(name);
14053
+ if (!v) missing.push(`${label} isn't installed (${settings.commands[name]} --version didn't answer)`);
14054
+ else if (minimum && !atLeast(v, minimum)) missing.push(`${label} ${v} is too old: it needs ${minimum} or later${update ? ` (${update})` : ""}`);
14055
+ else found.push({
14056
+ name,
14057
+ version: v
14058
+ });
14059
+ }
14060
+ return {
14061
+ found,
14062
+ missing
14063
+ };
14064
+ }
14065
+ /** The adapters for what was found. */
14066
+ function adaptersFor(found, settings, board, env) {
14067
+ return Object.fromEntries(found.map(({ name }) => [name, DEFINITIONS[name].create({
14068
+ command: settings.commands[name],
14069
+ args: settings.args[name],
14070
+ board,
14071
+ env,
14072
+ allowFullAccess: settings.allowFullAccess
14073
+ })]));
14074
+ }
14075
+ //#endregion
14076
+ //#region src/runner/board.ts
14077
+ function runBoard(api) {
14078
+ return {
14079
+ task: async (ref) => {
14080
+ const task = await taskByRef(api, ref);
14081
+ return {
14082
+ task,
14083
+ comments: (await commentsOf(api, task.ref)).slice(-5)
14084
+ };
14085
+ },
14086
+ startWork: async (ref) => {
14087
+ const task = await taskByRef(api, ref);
14088
+ const moved = await moveToWork(api, task, await columnsOf(api, taskRefOf(task.ref).key));
14089
+ return moved.moved ? moved.line.replace(/\.$/, "") : null;
14090
+ },
14091
+ comment: async (ref, body) => {
14092
+ const { key, number } = taskRefOf(ref);
14093
+ await unwrap(api.POST("/v1/projects/{key}/tasks/{number}/comments", {
14094
+ params: { path: {
14095
+ key,
14096
+ number
14097
+ } },
14098
+ body: { body }
14099
+ }));
14100
+ },
14101
+ attach: async (ref, url, title, draft) => {
14102
+ const { key, number } = taskRefOf(ref);
14103
+ await unwrap(api.POST("/v1/projects/{key}/tasks/{number}/links", {
14104
+ params: { path: {
14105
+ key,
14106
+ number
14107
+ } },
14108
+ body: {
14109
+ url,
14110
+ title,
14111
+ state: draft ? "draft" : "open"
14112
+ }
14113
+ }));
14114
+ }
14115
+ };
14116
+ }
14117
+ //#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
+ //#region src/runner/loop.ts
14216
+ const sleepFor = (ms, signal) => new Promise((resolve) => {
14217
+ if (signal.aborted) return resolve();
14218
+ const timer = setTimeout(resolve, ms);
14219
+ signal.addEventListener("abort", () => {
14220
+ clearTimeout(timer);
14221
+ resolve();
14222
+ });
14223
+ });
14224
+ const defaultSleep = sleepFor;
14225
+ /** How a run that didn't succeed reads in the terminal. */
14226
+ const ENDINGS = {
14227
+ succeeded: "✓ done",
14228
+ failed: "✗ failed",
14229
+ needs_human: "? needs you",
14230
+ cancelled: "■ cancelled"
14231
+ };
14232
+ async function runRunner(ctx, settings, deps, options = {}) {
14233
+ const api = apis(ctx).signedIn;
14234
+ const now = deps.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
14235
+ const adapters = Object.keys(deps.adapters);
14236
+ const register = () => unwrap(api.POST("/v1/runners", { body: {
14237
+ name: settings.name,
14238
+ adapters,
14239
+ version: VERSION,
14240
+ pollSeconds: settings.pollSeconds
14241
+ } }));
14242
+ let runner = await register();
14243
+ ctx.err(`Runner ${runner.name} is online with ${adapters.join(", ")}: waiting for runs (checking every ${settings.pollSeconds}s; Ctrl-C to stop).`);
14244
+ let active = null;
14245
+ let stopping = false;
14246
+ let leave = false;
14247
+ let wake = new AbortController();
14248
+ let first = true;
14249
+ let unreachable = false;
14250
+ let took = false;
14251
+ const stopListening = deps.onInterrupt(() => {
14252
+ if (stopping && active) {
14253
+ leave = true;
14254
+ ctx.err(`Leaving ${active.ref} running: it will show as lost once this runner is gone.`);
14255
+ } else if (active) {
14256
+ ctx.err(`Cancelling ${active.ref}, then stopping (Ctrl-C again to leave it running)…`);
14257
+ active.cancelling = true;
14258
+ active.cancel();
14259
+ } else ctx.err("Stopping.");
14260
+ stopping = true;
14261
+ wake.abort();
14262
+ });
14263
+ try {
14264
+ while (!leave && (!stopping || active)) {
14265
+ let work = null;
14266
+ try {
14267
+ work = await heartbeat(api, runner.id);
14268
+ if (unreachable) ctx.err("Reached the API again.");
14269
+ unreachable = false;
14270
+ } catch (err) {
14271
+ if (err instanceof NotSignedIn || err instanceof ApiProblem && err.status === 401) throw err;
14272
+ if (err instanceof ApiProblem && err.status === 404) runner = await register();
14273
+ else if (!unreachable) {
14274
+ unreachable = true;
14275
+ ctx.err(`Can't reach the API (${err.message}); trying again every ${settings.pollSeconds}s.`);
14276
+ }
14277
+ }
14278
+ if (work) {
14279
+ for (const run of work.running) if (active?.id === run.id) {
14280
+ if (run.cancelRequested && !active.cancelling) {
14281
+ active.cancelling = true;
14282
+ ctx.err(`Cancelling ${active.ref}: asked from the board.`);
14283
+ active.cancel();
14284
+ }
14285
+ } else if (first) await patch(api, run.id, {
14286
+ status: "failed",
14287
+ reason: "The runner stopped while it ran."
14288
+ }).catch(() => {});
14289
+ first = false;
14290
+ const next = work.queued[0];
14291
+ if (!active && !stopping && next && !(options.once && took)) {
14292
+ took = true;
14293
+ const started = execute(next);
14294
+ if (started) {
14295
+ active = started.active;
14296
+ started.finished.then(() => {
14297
+ active = null;
14298
+ if (options.once) stopping = true;
14299
+ wake.abort();
14300
+ });
14301
+ }
14302
+ }
14303
+ }
14304
+ await active?.flush();
14305
+ if (options.once && !active && (took || !work?.queued.length)) break;
14306
+ if (!leave && (!stopping || active)) {
14307
+ await deps.sleep(settings.pollSeconds * 1e3, wake.signal);
14308
+ wake = new AbortController();
14309
+ }
14310
+ }
14311
+ } finally {
14312
+ stopListening();
14313
+ }
14314
+ /** Starts a queued run, unless it can't (its folder, a declined confirm, another runner took it). */
14315
+ function execute(run) {
14316
+ const ref = run.ref;
14317
+ const outbox = new Outbox(api, run.id, now);
14318
+ let cancel = async () => {};
14319
+ let cancelled = false;
14320
+ const self = {
14321
+ id: run.id,
14322
+ ref: ref ?? "a deleted task",
14323
+ cancelling: false,
14324
+ cancel: async () => {
14325
+ cancelled = true;
14326
+ await cancel();
14327
+ },
14328
+ flush: () => outbox.flush()
14329
+ };
14330
+ return {
14331
+ active: self,
14332
+ finished: (async () => {
14333
+ const refuse = async (status, reason) => {
14334
+ ctx.err(`✗ ${self.ref}: ${reason}`);
14335
+ await patch(api, run.id, {
14336
+ status,
14337
+ reason
14338
+ }, run.version).catch(() => {});
14339
+ };
14340
+ if (!ref) return refuse("failed", "Its task was deleted.");
14341
+ const adapter = deps.adapters[run.adapter];
14342
+ if (!adapter) return refuse("failed", `${runner.name} can't run ${run.adapter}.`);
14343
+ const problem = await deps.workdirProblem(run.workdir, run.project);
14344
+ if (problem) return refuse("failed", problem);
14345
+ if (settings.confirm && !await ctx.confirm(`Run ${ref} with ${run.adapter} in ${run.workdir}?`)) return refuse("cancelled", `Declined on ${runner.name}.`);
14346
+ if (cancelled) return refuse("cancelled", "Cancelled before it started.");
14347
+ try {
14348
+ await patch(api, run.id, { status: "running" }, run.version);
14349
+ } catch (err) {
14350
+ if (err instanceof ApiProblem && (err.status === 412 || err.status === 409)) return;
14351
+ throw err;
14352
+ }
14353
+ ctx.err(`▶ ${ref} in ${run.workdir} (${run.adapter})`);
14354
+ const started = adapter.start({
14355
+ ref,
14356
+ workdir: run.workdir,
14357
+ options: run.options
14358
+ }, {
14359
+ event: (e) => {
14360
+ outbox.push(e);
14361
+ const line = describe(e);
14362
+ if (line) ctx.err(` ${line}`);
14363
+ },
14364
+ update: (u) => outbox.update(u)
14365
+ });
14366
+ cancel = started.cancel;
14367
+ if (cancelled) started.cancel();
14368
+ const ending = await started.done;
14369
+ await outbox.flush();
14370
+ await patch(api, run.id, {
14371
+ ...outbox.updates(),
14372
+ status: ending.status,
14373
+ reason: ending.reason
14374
+ }).catch((err) => ctx.err(`Couldn't record how ${ref} ended: ${err.message}`));
14375
+ const pr = outbox.updates().prUrl;
14376
+ ctx.err(`${ENDINGS[ending.status]}: ${ref}${ending.reason ? ` (${ending.reason})` : ""}${pr ? ` ${pr}` : ""}`);
14377
+ })().catch((err) => ctx.err(`✗ ${self.ref}: ${err.message}`))
14378
+ };
14379
+ }
14380
+ }
14381
+ function heartbeat(api, runnerId) {
14382
+ return unwrap(api.POST("/v1/runners/{runnerId}/heartbeat", { params: { path: { runnerId } } }));
14383
+ }
14384
+ function patch(api, runId, body, version) {
14385
+ return unwrap(api.PATCH("/v1/runs/{runId}", {
14386
+ params: {
14387
+ path: { runId },
14388
+ header: version ? { "if-match": `"${version}"` } : {}
14389
+ },
14390
+ body
14391
+ }));
14392
+ }
14393
+ /** A line for the terminal, for the events a person follows. */
14394
+ function describe(e) {
14395
+ const data = e.data ?? {};
14396
+ switch (e.kind) {
14397
+ case "step_finished": {
14398
+ const took = data.durationMs ? ` ${formatDuration(data.durationMs)}` : "";
14399
+ const cost = data.costUsd ? ` ${formatCost(data.costUsd)}` : "";
14400
+ const why = e.status !== "ok" && e.message ? ` (${e.message})` : "";
14401
+ return `${STEP_MARKS[e.status ?? "ok"]} ${e.step}${took}${cost}${why}`;
14402
+ }
14403
+ case "pr_opened": return `pull request ${e.message}`;
14404
+ case "question": return `? ${e.message}`;
14405
+ case "error": return `✗ ${e.message}`;
14406
+ default: return null;
14407
+ }
14408
+ }
14409
+ /**
14410
+ * What a run reported, until it's sent: numbered from 1, sent at each check-in (and when the run ends) in
14411
+ * batches the API takes, and kept when sending fails, to try again. A run that stopped running (cancelled
14412
+ * from the web after its runner went quiet) takes no more, so they're dropped.
14413
+ */
14414
+ var Outbox = class {
14415
+ api;
14416
+ runId;
14417
+ now;
14418
+ seq = 0;
14419
+ queue = [];
14420
+ changed = {};
14421
+ sentUpdates = {};
14422
+ closed = false;
14423
+ sending = null;
14424
+ constructor(api, runId, now) {
14425
+ this.api = api;
14426
+ this.runId = runId;
14427
+ this.now = now;
14428
+ }
14429
+ push(e) {
14430
+ if (this.closed || this.seq >= RUN_LIMITS.eventsPerRun) return;
14431
+ if (!(e.kind === "step_started" || e.kind === "step_finished") && this.seq >= RUN_LIMITS.eventsPerRun - 100) return;
14432
+ this.queue.push({
14433
+ ...e,
14434
+ seq: ++this.seq,
14435
+ at: e.at ?? this.now()
14436
+ });
14437
+ }
14438
+ update(u) {
14439
+ Object.assign(this.changed, u);
14440
+ }
14441
+ /** Everything the run has said about itself (for its ending). */
14442
+ updates() {
14443
+ return {
14444
+ ...this.sentUpdates,
14445
+ ...this.changed
14446
+ };
14447
+ }
14448
+ flush() {
14449
+ this.sending ??= this.send().finally(() => {
14450
+ this.sending = null;
14451
+ });
14452
+ return this.sending;
14453
+ }
14454
+ async send() {
14455
+ while (this.queue.length && !this.closed) {
14456
+ const batch = this.queue.slice(0, RUN_LIMITS.eventsPerBatch);
14457
+ try {
14458
+ await unwrap(this.api.POST("/v1/runs/{runId}/events", {
14459
+ params: { path: { runId: this.runId } },
14460
+ body: { events: batch }
14461
+ }));
14462
+ this.queue.splice(0, batch.length);
14463
+ } catch (err) {
14464
+ if (err instanceof ApiProblem && (err.status === 409 || err.status === 404)) this.closed = true;
14465
+ else return;
14466
+ }
14467
+ }
14468
+ if (Object.keys(this.changed).length && !this.closed) {
14469
+ const body = this.changed;
14470
+ this.changed = {};
14471
+ try {
14472
+ await patch(this.api, this.runId, body);
14473
+ Object.assign(this.sentUpdates, body);
14474
+ } catch {
14475
+ this.changed = {
14476
+ ...body,
14477
+ ...this.changed
14478
+ };
14479
+ }
14480
+ }
14481
+ }
14482
+ };
14483
+ //#endregion
14484
+ //#region src/runner/workdir.ts
14485
+ /**
14486
+ * Whether a run may work in `workdir` (docs/PLAN-ORCHESTRATOR.md §0): a folder on this machine, a git checkout
14487
+ * of the task's project (its origin is the project's linked repository, or `monoban link` remembered the
14488
+ * project there), and inside one of the `allow` folders when there are any. The web only sends a path; this is
14489
+ * what makes sure it's the project's code and nothing else. Answers why not, or null.
14490
+ */
14491
+ async function workdirProblem(workdir, project, allow, open = clone) {
14492
+ if (!isAbsolutePath(workdir)) return `${workdir} isn't an absolute path.`;
14493
+ let real;
14494
+ try {
14495
+ real = await realpath(workdir);
14496
+ if (!(await stat(real)).isDirectory()) return `${workdir} isn't a folder.`;
14497
+ } catch {
14498
+ return `${workdir} doesn't exist on this machine.`;
14499
+ }
14500
+ if (allow.length) {
14501
+ if (!(await Promise.all(allow.map((a) => realpath(a).catch(() => a)))).some((root) => real === root || real.startsWith(root.endsWith(sep) ? root : root + sep))) return `${workdir} isn't in a folder this runner allows (${allow.join(", ")}).`;
14502
+ }
14503
+ const repo = open(real);
14504
+ if (!await repo.inClone()) return `${workdir} isn't a git checkout.`;
14505
+ const [origin, linked] = await Promise.all([repo.origin(), repo.project()]);
14506
+ if (linked?.toUpperCase() === project.key) return null;
14507
+ if (project.repo && origin?.repo === project.repo) return null;
14508
+ if (!project.repo) return `${project.key} isn't linked to a repository: run \`monoban link ${project.key}\` in ${workdir} first.`;
14509
+ return `${workdir} isn't a checkout of ${project.repo} (its origin is ${origin?.repo ?? origin?.url ?? "not set"}).`;
14510
+ }
14511
+ //#endregion
14512
+ //#region src/commands/runs.ts
14513
+ /** "agentpipe 0.1.0, Claude Code 2.1.300". */
14514
+ const agentList = (found) => found.map((a) => `${agentLabel(a.name)}${a.version ? ` ${a.version}` : ""}`).join(", ");
14515
+ /**
14516
+ * `monoban runner`: run agents on this machine for the runs queued from the board, until Ctrl-C. It offers the
14517
+ * agents installed here (or the ones --agents names), and says why it doesn't offer the others.
14518
+ */
14519
+ async function runner(ctx, options, overrides = {}) {
14520
+ const settings = await runnerSettings(configDir(ctx.env), options, ctx.env, deviceName());
14521
+ const { detect = detectAgents, ...deps } = overrides;
14522
+ let adapters = deps.adapters;
14523
+ if (!adapters) {
14524
+ const env = ctx.env;
14525
+ const { found, missing } = await detect(settings, env);
14526
+ 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
+ ctx.err(`Agents: ${agentList(found)}.${missing.length ? ` Not offered: ${missing.join("; ")}.` : ""}`);
14528
+ 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);
14530
+ }
14531
+ await runRunner(ctx, settings, {
14532
+ workdirProblem: (workdir, project) => workdirProblem(workdir, project, settings.allow),
14533
+ sleep: defaultSleep,
14534
+ onInterrupt: (handler) => {
14535
+ process.on("SIGINT", handler);
14536
+ return () => process.off("SIGINT", handler);
14537
+ },
14538
+ ...deps,
14539
+ adapters
14540
+ }, { once: options.once });
14541
+ }
14542
+ const PR_CHOICES = [
14543
+ "draft",
14544
+ "ready",
14545
+ "none"
14546
+ ];
14547
+ /** Which runner: the one named, else the only online one, else a usage error naming them. */
14548
+ async function chooseRunner(api, name) {
14549
+ const { runners } = await unwrap(api.GET("/v1/runners"));
14550
+ if (name) {
14551
+ const found = runners.find((r) => r.name.toLowerCase() === name.trim().toLowerCase());
14552
+ if (!found) {
14553
+ const names = runners.map((r) => r.name).join(", ");
14554
+ throw new CliError(`No runner named ${name}${names ? ` (yours: ${names})` : ""}.`, EXIT.notFound);
14555
+ }
14556
+ return found;
14557
+ }
14558
+ const online = runners.filter((r) => r.online);
14559
+ if (online.length === 1) return online[0];
14560
+ if (!online.length) throw new CliError("No runner is online. Start one with `monoban runner` on the machine with the code.");
14561
+ throw new CliError(`Which runner? Pass --runner (${online.map((r) => r.name).join(", ")}).`, EXIT.usage);
14562
+ }
14563
+ /**
14564
+ * `monoban run MON-12`: queue an agent run on a runner (the only online one, or --runner), in --path (this
14565
+ * clone's top folder unless told). --follow prints its steps until it ends, and exits 0 only if it succeeded.
14566
+ */
14567
+ async function run(ctx, ref, options) {
14568
+ if (options.pr !== void 0 && !PR_CHOICES.includes(options.pr)) throw new CliError(`--pr is draft, ready or none (not ${options.pr}).`, EXIT.usage);
14569
+ const budget = options.budget === void 0 ? void 0 : Number(options.budget);
14570
+ if (budget !== void 0 && !(Number.isFinite(budget) && budget >= .1 && budget <= 1e3)) throw new CliError("--budget is the most it may spend, in US dollars: 0.1 to 1000.", EXIT.usage);
14571
+ if (options.access !== void 0 && !AGENT_ACCESS.includes(options.access)) throw new CliError(`--access is ${AGENT_ACCESS.join(", ")} (not ${options.access}).`, EXIT.usage);
14572
+ const api = apis(ctx).signedIn;
14573
+ const task = await taskByRef(api, ref, ctx);
14574
+ const { key, number } = taskRefOf(task.ref);
14575
+ const chosen = await chooseRunner(api, options.runner);
14576
+ const agent = options.agent?.trim().toLowerCase() ?? (chosen.adapters.includes("agentpipe") ? "agentpipe" : chosen.adapters[0] ?? "agentpipe");
14577
+ if (!chosen.adapters.includes(agent)) {
14578
+ const has = chosen.adapters.map(agentLabel).join(", ");
14579
+ throw new CliError(`${chosen.name} can't run ${agentLabel(agent)}${has ? ` (it has ${has})` : ""}.`, EXIT.usage);
14580
+ }
14581
+ const workdir = options.path ? resolve(options.path) : await ctx.clone.root();
14582
+ const queued = await unwrap(api.POST("/v1/projects/{key}/tasks/{number}/runs", {
14583
+ params: { path: {
14584
+ key,
14585
+ number
14586
+ } },
14587
+ body: {
14588
+ runnerId: chosen.id,
14589
+ adapter: agent,
14590
+ mode: "local",
14591
+ workdir,
14592
+ options: {
14593
+ pr: options.pr ?? "draft",
14594
+ ...budget !== void 0 && { budgetUsd: budget },
14595
+ autonomous: !options.ask,
14596
+ ...options.model && { model: options.model.trim() },
14597
+ ...options.access && { access: options.access }
14598
+ }
14599
+ }
14600
+ }));
14601
+ if (!options.follow) {
14602
+ if (options.json) return ctx.out(JSON.stringify(queued, null, 2));
14603
+ ctx.out(`Queued ${task.ref} on ${chosen.name}, in ${workdir}, with ${agentLabel(agent)}.`);
14604
+ if (!chosen.online) ctx.err(`${chosen.name} is offline: it starts once \`monoban runner\` runs there.`);
14605
+ return;
14606
+ }
14607
+ ctx.err(`Queued ${task.ref} on ${chosen.name}, in ${workdir}, with ${agentLabel(agent)}. Following it (Ctrl-C stops following, not the run).`);
14608
+ const ended = await follow(ctx, api, queued.id);
14609
+ if (options.json) ctx.out(JSON.stringify(ended, null, 2));
14610
+ if (ended.status !== "succeeded") throw new CliError(`${task.ref}: ${describeRunStatus(ended)}.`);
14611
+ }
14612
+ /** Prints a run's steps as they change, until it ends; answers it as it ended. */
14613
+ async function follow(ctx, api, runId, sleep = (ms) => new Promise((r) => setTimeout(r, ms))) {
14614
+ const said = /* @__PURE__ */ new Map();
14615
+ let status = "";
14616
+ for (;;) {
14617
+ const current = await unwrap(api.GET("/v1/runs/{runId}", { params: { path: { runId } } }));
14618
+ if (current.status !== status) {
14619
+ status = current.status;
14620
+ ctx.err(`[${describeRunStatus(current)}]`);
14621
+ }
14622
+ for (const step of current.steps) {
14623
+ const key = `${step.name}@${step.attempt}`;
14624
+ const line = stepLine(step);
14625
+ if (said.get(key) !== line) {
14626
+ said.set(key, line);
14627
+ ctx.err(` ${line}`);
14628
+ }
14629
+ }
14630
+ if (isFinished(current.status)) {
14631
+ if (current.prUrl) ctx.err(`pull request ${current.prUrl}`);
14632
+ if (current.reason && current.status !== "succeeded") ctx.err(current.reason);
14633
+ return current;
14634
+ }
14635
+ await sleep(2e3);
14636
+ }
14637
+ }
14638
+ /** "✓ plan 1m02 $0.31", "● implement". */
14639
+ function stepLine(step) {
14640
+ const took = step.durationMs !== null && step.status !== "running" ? ` ${formatDuration(step.durationMs)}` : "";
14641
+ const cost = step.costUsd ? ` ${formatCost(step.costUsd)}` : "";
14642
+ const attempt = step.attempt > 1 ? ` (attempt ${step.attempt})` : "";
14643
+ const why = step.message && step.status !== "ok" ? ` — ${step.message}` : "";
14644
+ return `${STEP_MARKS[step.status]} ${step.name}${attempt}${took}${cost}${why}`;
14645
+ }
14646
+ /** `monoban runs MON-12`: a task's runs, newest first. */
14647
+ async function runs(ctx, ref, options) {
14648
+ const api = apis(ctx).signedIn;
14649
+ const task = await taskByRef(api, ref, ctx);
14650
+ const { key, number } = taskRefOf(task.ref);
14651
+ const page = await unwrap(api.GET("/v1/projects/{key}/tasks/{number}/runs", { params: { path: {
14652
+ key,
14653
+ number
14654
+ } } }));
14655
+ if (options.json) return ctx.out(JSON.stringify(page.runs, null, 2));
14656
+ if (!page.runs.length) {
14657
+ ctx.err(`${task.ref} has no runs yet. Start one with \`monoban run ${task.ref}\`, or from the board.`);
14658
+ return;
14659
+ }
14660
+ for (const r of page.runs) ctx.out(runLine(r));
14661
+ }
14662
+ /** "succeeded mbp 12m04 $0.29 /Users/me/monoban https://github.com/…/pull/7". */
14663
+ function runLine(r) {
14664
+ const end = r.finishedAt ?? (/* @__PURE__ */ new Date()).toISOString();
14665
+ const took = r.startedAt ? formatDuration(Date.parse(end) - Date.parse(r.startedAt)) : "-";
14666
+ const cost = r.costUsd === null ? "-" : formatCost(r.costUsd);
14667
+ return [
14668
+ r.status.padEnd(11),
14669
+ r.runner.name,
14670
+ took,
14671
+ cost,
14672
+ r.workdir,
14673
+ r.prUrl ?? r.reason ?? ""
14674
+ ].join(" ").trimEnd();
14675
+ }
14676
+ //#endregion
14677
+ //#region src/commands/search.ts
14678
+ /**
14679
+ * `monoban search login page`: the tasks with all of these words (in the title or description, as a tag, or
14680
+ * as the reference), in every project, the last changed first, archived ones too. `-n` of them, 30 unless
14681
+ * you say.
14682
+ */
14683
+ async function search(ctx, words, options) {
14684
+ const q = words.join(" ").trim();
14685
+ if (!q) throw new CliError("Say what to look for: monoban search login page", EXIT.usage);
14686
+ const count = options.number === void 0 ? 30 : Number(options.number);
14687
+ if (!Number.isInteger(count) || count < 1) throw new CliError("-n is how many tasks to show: 1 or more.", EXIT.usage);
14688
+ const api = apis(ctx).signedIn;
14689
+ const tasks = [];
14690
+ let cursor;
14691
+ do {
14692
+ const limit = Math.min(count - tasks.length, PAGE_LIMIT.max);
14693
+ const page = await unwrap(api.GET("/v1/search", { params: { query: {
14694
+ q,
14695
+ limit,
14696
+ cursor
14697
+ } } }));
14698
+ tasks.push(...page.tasks);
14699
+ cursor = page.nextCursor ?? void 0;
14700
+ } while (cursor && tasks.length < count);
14701
+ if (options.json) return ctx.out(JSON.stringify(tasks, null, 2));
14702
+ if (tasks.length === 0) {
14703
+ ctx.err(`No task has "${q}".`);
14704
+ return;
14705
+ }
14706
+ const { dim, color } = ctx.style;
14707
+ const refWidth = Math.max(...tasks.map((t) => t.ref.length));
14708
+ const columnWidth = Math.max(...tasks.map((t) => [...t.column.name].length));
14709
+ for (const t of tasks) {
14710
+ const mark = t.done ? color("green", "✓") : " ";
14711
+ const column = `${t.column.name}${" ".repeat(columnWidth - [...t.column.name].length)}`;
14712
+ const title = t.done ? dim(oneLine(t.title)) : oneLine(t.title);
14713
+ ctx.out(`${mark} ${t.ref.padEnd(refWidth)} ${dim(column)} ${title}${t.archived ? ` ${dim("archived")}` : ""}`);
14714
+ }
14715
+ if (cursor) ctx.err(`More tasks have it: -n ${count * 5} shows more.`);
14716
+ }
14717
+ //#endregion
14718
+ //#region src/skill.ts
14719
+ /** The coding agents `monoban setup` teaches monoban to. */
14720
+ const AGENTS = ["claude", "codex"];
14721
+ const AGENT_NAMES = {
12185
14722
  claude: "Claude Code",
12186
14723
  codex: "Codex"
12187
14724
  };
@@ -12200,6 +14737,7 @@ const READ_ONLY = [
12200
14737
  "monoban show",
12201
14738
  "monoban log",
12202
14739
  "monoban comments",
14740
+ "monoban runs",
12203
14741
  "monoban today",
12204
14742
  "monoban search",
12205
14743
  "monoban tags",
@@ -12407,91 +14945,6 @@ async function setup(ctx, agent, options) {
12407
14945
  ctx.err(options.project ? `Commit it so everyone working in this repository gets it. New ${name} sessions use it.` : `New ${name} sessions use it, in any repository. Ask one to plan something, or say "put it on monoban".`);
12408
14946
  }
12409
14947
  //#endregion
12410
- //#region src/commands/start.ts
12411
- /** How long a branch name's words may be, after `mon-12-`. */
12412
- const SLUG_LENGTH = 40;
12413
- /** The branch for a task: `mon-12-import-boards-from-trello` (its ref, then its title's first words). */
12414
- function branchName(ref, title) {
12415
- const words = title.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
12416
- const cut = words.length > SLUG_LENGTH ? words.slice(0, 41).replace(/-[^-]*$/, "") : words;
12417
- return [ref.toLowerCase(), cut].filter(Boolean).join("-");
12418
- }
12419
- /**
12420
- * The column where work happens: the one named In progress (or Doing, WIP…), else the one after the
12421
- * first, unless that's Done. undefined when the board has none (Backlog and Done only).
12422
- */
12423
- function workColumn(columns) {
12424
- const names = [
12425
- "in progress",
12426
- "in-progress",
12427
- "doing",
12428
- "wip",
12429
- "started",
12430
- "working",
12431
- "active"
12432
- ];
12433
- const named = columns.find((c) => names.includes(c.name.trim().toLowerCase()));
12434
- if (named) return named;
12435
- const second = columns[1];
12436
- return second && second !== doneColumn(columns) ? second : void 0;
12437
- }
12438
- /**
12439
- * `monoban start MON-12`: work on a task. Checks out its branch (`mon-12-title`: made from the commit
12440
- * you're on, or the one already there) and moves it to In progress, unless it's there or further on.
12441
- * --no-branch and --no-move do half of it.
12442
- */
12443
- async function start(ctx, ref, options) {
12444
- const api = apis(ctx).signedIn;
12445
- let task = await taskByRef(api, ref, ctx);
12446
- const { key, number } = taskRefOf(task.ref);
12447
- const columns = await columnsOf(api, key);
12448
- const lines = [];
12449
- let branch = null;
12450
- if (options.branch !== false) {
12451
- 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);
12452
- const current = await ctx.clone.branch();
12453
- const own = (name) => taskOfBranch(name) === task.ref;
12454
- if (own(current)) {
12455
- branch = current;
12456
- lines.push(`Already on ${branch}.`);
12457
- } else {
12458
- const existing = (await ctx.clone.branches()).find(own);
12459
- branch = existing ?? branchName(task.ref, task.title);
12460
- const why = await ctx.clone.switchTo(branch, !existing);
12461
- if (why) throw new CliError(`git couldn't switch to ${branch}: ${why}`);
12462
- lines.push(existing ? `Switched to ${branch}.` : `Switched to a new branch ${branch}.`);
12463
- }
12464
- }
12465
- if (options.move !== false) {
12466
- const target = workColumn(columns);
12467
- const at = (t) => columns.findIndex((c) => c.id === t.columnId);
12468
- const here = columns[at(task)];
12469
- if (!target) lines.push(`${task.ref} stays in ${here?.name ?? "its column"}: the board has no In progress column.`);
12470
- else if (at(task) >= columns.indexOf(target)) lines.push(`${task.ref} is in ${here?.name ?? "its column"} already.`);
12471
- else {
12472
- task = await unwrap(api.PATCH("/v1/projects/{key}/tasks/{number}", {
12473
- params: {
12474
- path: {
12475
- key,
12476
- number
12477
- },
12478
- header: ifMatch(task.version)
12479
- },
12480
- body: { columnId: target.id }
12481
- })).catch((err) => changedElsewhere(err, task.ref));
12482
- lines.push(`Moved ${task.ref}${here ? ` from ${here.name}` : ""} to ${target.name}.`);
12483
- }
12484
- }
12485
- if (options.json) {
12486
- const json = {
12487
- ...taskJson(task, columns, await tagsFor(api, key, task)),
12488
- branch
12489
- };
12490
- return ctx.out(JSON.stringify(json, null, 2));
12491
- }
12492
- for (const line of lines) ctx.out(line);
12493
- }
12494
- //#endregion
12495
14948
  //#region src/complete.ts
12496
14949
  /**
12497
14950
  * Shell completion (`monoban completion bash|zsh|fish`). The scripts are thin: on Tab they run
@@ -12749,7 +15202,7 @@ async function latestVersion(ctx) {
12749
15202
  async function upgrade(ctx, options, kind = thisInstall()) {
12750
15203
  const latest = await latestVersion(ctx);
12751
15204
  const { how, command } = UPGRADE[kind];
12752
- const outdated = latest !== null && newer(latest, "1.3.0");
15205
+ const outdated = latest !== null && newer(latest, "1.5.0");
12753
15206
  if (options.json) {
12754
15207
  ctx.out(JSON.stringify({
12755
15208
  version: VERSION,
@@ -12787,7 +15240,7 @@ function program(ctx) {
12787
15240
  cli.command("today").argument("[day]", "another day: tomorrow, fri, oct 12, 2026-10-12…").description("Show what's planned for today in every project (overdue first), or for another day").option("-w, --week", "the 7 days from it").addOption(json()).action(async (day, options) => todayView(await ctx(), day, options));
12788
15241
  cli.command("search").argument("<words...>", "all of them: in the title or description, a tag, or a reference like MON-12").description("Find tasks in every project, the last changed first").option("-n, --number <count>", "how many tasks (default 30)").addOption(json()).action(async (words, options) => search(await ctx(), words, options));
12789
15242
  cli.command("schedule").argument("<task>", "like MON-12").argument("[day]", "today, tomorrow, fri, next week, +3, oct 12, 2026-10-12…").description("Plan a task for a day (it shows in `monoban today` then), or take its date off with --clear").option("--clear", "take the date off").addOption(json()).action(async (ref, day, options) => schedule(await ctx(), ref, day, options));
12790
- cli.command("move").argument("<task>", "like MON-12").argument("[column]", "where to (any case; a prefix works)").description("Move a task to the end of another column, or (--to) to another project").option("--to <project>", "another project's key: the task gets a number there (MON-12 becomes WEB-7)").addOption(json()).action(async (ref, column, options) => move(await ctx(), ref, column, options));
15243
+ cli.command("move").argument("<task>", "like MON-12").argument("[column]", "where to (any case; a prefix works)").description("Move a task to the end of another column, or (--to) to another project").option("--to <project>", "another project's key: the task gets a number there (MON-12 becomes WEB-7)").option("--if-column-since <time>", "only if it's been in its column since then (its columnSince): nobody moved it").addOption(json()).action(async (ref, column, options) => move(await ctx(), ref, column, options));
12791
15244
  cli.command("done").argument("<task>", "like MON-12").description("Move a task to Done (or the last column)").addOption(json()).action(async (ref, options) => done(await ctx(), ref, options));
12792
15245
  cli.command("start").argument("<task>", "like MON-12").description("Start a task: check out its branch (mon-12-title, made from the commit you're on) and move it to In progress").option("--no-branch", "only move it").option("--no-move", "only check out its branch").addOption(json()).action(async (ref, options) => start(await ctx(), ref, options));
12793
15246
  cli.command("edit").argument("<task>", "like MON-12").description("Edit a task's title (the first line) and description in $EDITOR, or set them with --title and -d").option("--title <text>", "a new title (no editor)").option("-d, --description <text>", "a new description, replacing it (- reads it from stdin; no editor)").addOption(json()).action(async (ref, options) => edit(await ctx(), ref, options));
@@ -12802,6 +15255,25 @@ function program(ctx) {
12802
15255
  notes.command("add").argument("<text...>", "the line to add (- reads it from stdin)").description("Add a line at the end of the notes").addOption(project()).addOption(json()).action(async (words, options) => notesAdd(await ctx(), words, options));
12803
15256
  notes.command("edit").description("Edit the notes in $EDITOR").addOption(project()).addOption(json()).action(async (options) => notesEdit(await ctx(), options));
12804
15257
  cli.command("open").argument("[task]", "like MON-12").description("Open the board, or a task, in the browser").addOption(project()).action(async (ref, options) => open$1(await ctx(), ref, options));
15258
+ cli.command("runner").description("Run coding agents here for the runs you start from the board (Run with orchestrator), until Ctrl-C").option("--name <name>", "what the board calls this machine (default: its hostname)").option("--interval <seconds>", "how often to ask for work (default 3)").option("--allow <folder>", "only run in this folder or below (repeat for more)", collect).option("--confirm", "ask here before starting each run").option("--agents <names>", "offer only these agents: agentpipe, claude, codex (comma-separated)").option("--allow-full-access", "let a run turn Codex's sandbox off (access: full); otherwise it stays on").option("--once", "take one run (if one is waiting), then stop").addHelpText("after", `
15259
+ A run works in the folder it was given, which must be a checkout of the task's project: its origin is the
15260
+ project's linked repository, or \`monoban link\` was run there. The runner offers the agents installed here:
15261
+ agentpipe (it narrates onto the task itself), Claude Code (claude -p, in auto mode) and Codex (codex exec,
15262
+ in its sandbox). For Claude Code and Codex the runner makes the task's branch, commits what they leave,
15263
+ pushes, opens the pull request with gh and comments on the task. Codex keeps its sandbox unless this
15264
+ machine allows a run to turn it off. Settings can also go in runner.json in the config folder:
15265
+ {"pollSeconds": 3, "allow": ["/Users/me/code"], "confirm": false, "agents": ["claude"],
15266
+ "adapters": {"claude": {"command": "claude", "args": []}, "codex": {"allowFullAccess": false}}}.`).action(async (options) => runner(await ctx(), options));
15267
+ cli.command("run").argument("<task>", "like MON-12").description("Queue a coding agent on a task, on your runner (`monoban runner`), in this clone or --path").option("--path <folder>", "the checkout to work in, on the runner's machine (default: this clone's top folder)").option("--runner <name>", "which runner (default: your only online one)").option("--agent <name>", "agentpipe, claude or codex (default: agentpipe when the runner has it)").addOption(new Option("--pr <kind>", "the pull request: draft (default), ready, or none").choices([
15268
+ "draft",
15269
+ "ready",
15270
+ "none"
15271
+ ])).option("--budget <usd>", "the most it may spend, in US dollars (agentpipe, claude)").option("--model <name>", "the model, as the agent names it: opus, gpt-5.5-codex… (claude, codex)").addOption(new Option("--access <kind>", "how far Codex reaches: sandbox (default), network, full").choices([
15272
+ "sandbox",
15273
+ "network",
15274
+ "full"
15275
+ ])).option("--ask", "wait for answers to its questions instead of deciding on its own (agentpipe)").option("-f, --follow", "print its steps until it ends (exit 0 only if it succeeded)").addOption(json()).action(async (ref, options) => run(await ctx(), ref, options));
15276
+ cli.command("runs").argument("<task>", "like MON-12").description("List a task's agent runs, newest first").addOption(json()).action(async (ref, options) => runs(await ctx(), ref, options));
12805
15277
  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", `
12806
15278
  It goes in ~/.claude/skills/monoban (Claude Code) or ~/.agents/skills/monoban (Codex); with --project,
12807
15279
  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));