monoban 1.8.0 → 1.10.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 +1 -1
  2. package/dist/index.mjs +2349 -431
  3. package/package.json +3 -3
package/dist/index.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import { homedir, hostname, tmpdir } from "node:os";
3
3
  import path, { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "node:path";
4
- import { access, constants, mkdir, mkdtemp, open, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, symlink, writeFile } from "node:fs/promises";
4
+ import { access, constants, mkdir, mkdtemp, open as open$3, readFile, readdir, readlink, realpath, rename, rm as rm$1, rmdir, stat, symlink, writeFile } from "node:fs/promises";
5
5
  import childProcess, { execFile, spawn, spawnSync } from "node:child_process";
6
6
  import { EventEmitter } from "node:events";
7
- import fs, { closeSync, existsSync, openSync, readdirSync, realpathSync } from "node:fs";
7
+ import fs, { closeSync, existsSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync } 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";
@@ -3031,7 +3031,7 @@ function bucketFor(state, inst) {
3031
3031
  return bucket;
3032
3032
  }
3033
3033
  let handoff;
3034
- const open$3 = [];
3034
+ const open$2 = [];
3035
3035
  const memo = {
3036
3036
  alloc(_inst, payload, empty) {
3037
3037
  const bucket = handoff;
@@ -3042,7 +3042,7 @@ const memo = {
3042
3042
  issues: null
3043
3043
  };
3044
3044
  bucket.set(payload.value, entry);
3045
- open$3.push(entry);
3045
+ open$2.push(entry);
3046
3046
  return empty;
3047
3047
  },
3048
3048
  guard(inst) {
@@ -3108,10 +3108,10 @@ const memo = {
3108
3108
  return payload;
3109
3109
  }
3110
3110
  handoff = bucket;
3111
- const depth = open$3.length;
3111
+ const depth = open$2.length;
3112
3112
  const result = base(payload, ctx);
3113
3113
  handoff = void 0;
3114
- const entry = open$3.length > depth ? open$3.pop() : void 0;
3114
+ const entry = open$2.length > depth ? open$2.pop() : void 0;
3115
3115
  if (result instanceof Promise) return result.then((r) => {
3116
3116
  if (entry) entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES;
3117
3117
  return r;
@@ -5782,7 +5782,7 @@ const LIMITS = {
5782
5782
  * Days, as tasks are scheduled: "2026-10-02", no time and no time zone. "Today" is the user's own: clients
5783
5783
  * work it out from their clock (today()) and send it, so the API never guesses a time zone.
5784
5784
  */
5785
- const DAY_MS$1 = 864e5;
5785
+ const DAY_MS$2 = 864e5;
5786
5786
  const DAY_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
5787
5787
  const pad$1 = (n) => String(n).padStart(2, "0");
5788
5788
  const fromUtc = (ms) => {
@@ -5803,11 +5803,11 @@ function today$1(now = /* @__PURE__ */ new Date()) {
5803
5803
  return `${now.getFullYear()}-${pad$1(now.getMonth() + 1)}-${pad$1(now.getDate())}`;
5804
5804
  }
5805
5805
  function addDays(day, days) {
5806
- return fromUtc(utc$1(day) + days * DAY_MS$1);
5806
+ return fromUtc(utc$1(day) + days * DAY_MS$2);
5807
5807
  }
5808
5808
  /** How many days from `from` to `to` (negative when `to` is earlier). */
5809
5809
  function daysBetween(from, to) {
5810
- return Math.round((utc$1(to) - utc$1(from)) / DAY_MS$1);
5810
+ return Math.round((utc$1(to) - utc$1(from)) / DAY_MS$2);
5811
5811
  }
5812
5812
  /**
5813
5813
  * A project's Done column, as `monoban done` and the Today view read it: the one named Done (any case),
@@ -5892,6 +5892,119 @@ function linkLabel(link) {
5892
5892
  return link.url;
5893
5893
  }
5894
5894
  }
5895
+ // ../../packages/contract/src/loops.ts
5896
+ /**
5897
+ * Agent loops (docs/PLAN-AGENT-LOOPS.md): looping agents a user creates per project, which `monoban runner` runs
5898
+ * through agentpipe. A loop's type is its recipe: a fixed, ordered list of steps, each one agentpipe command. One
5899
+ * pass of a loop is an ordinary run. Their shapes (options, a loop, its create and patch) are in schemas.ts; the
5900
+ * words for a loop's state are @monoban/i18n's `describeLoopState`.
5901
+ */
5902
+ /**
5903
+ * The recipes and their steps, in order. `deliver` takes a task from a column and delivers it as a merged pull
5904
+ * request; its `review` step is `agentpipe review --fix` (kept by the owner, plan §1.9 S1).
5905
+ * `scavenge` finds problems and files tasks.
5906
+ */
5907
+ const RECIPES$1 = {
5908
+ deliver: { steps: [
5909
+ "implement",
5910
+ "review",
5911
+ "checks",
5912
+ "feedback",
5913
+ "merge"
5914
+ ] },
5915
+ scavenge: { steps: ["scout"] }
5916
+ };
5917
+ const RECIPE_NAMES = Object.keys(RECIPES$1);
5918
+ const range = (min, max) => ({
5919
+ min,
5920
+ max
5921
+ });
5922
+ /** How much a loop may be and take (plan §1.4). The owner confirms them at the mockup (MON-193). */
5923
+ const LOOP_LIMITS = {
5924
+ /** Loops per project. */
5925
+ perProject: 10,
5926
+ name: 64,
5927
+ /** Between the starts of its runs: 5 minutes to a week. */
5928
+ intervalSeconds: range(300, 604800),
5929
+ /** Its options, as stored (bytes of JSON). */
5930
+ optionsBytes: 2048,
5931
+ /** Runs started per 24 hours. */
5932
+ perDay: range(1, 100),
5933
+ /** Per run, in US dollars. */
5934
+ budgetUsd: range(1, 100),
5935
+ /** Per 24 hours, in US dollars. */
5936
+ budgetUsdPerDay: range(1, 1e3),
5937
+ /** Runs in a row that failed or need you before the loop pauses itself. */
5938
+ pauseAfter: range(1, 10),
5939
+ /** deliver: its pull requests that may wait for you before it stops taking tasks. */
5940
+ deliverMaxOpen: range(1, 10),
5941
+ /** deliver: how long its `checks` step may wait for CI, in minutes. */
5942
+ checksMinutes: range(10, 240),
5943
+ /** scavenge: its open tasks before it stops filing. */
5944
+ scavengeMaxOpen: range(1, 20),
5945
+ /** scavenge: what to look for, on one line. */
5946
+ focus: 500
5947
+ };
5948
+ /** What a loop's options are when left out. Merge is on unless the loop says otherwise (plan §1.10.3). */
5949
+ const LOOP_DEFAULTS = {
5950
+ perDay: 5,
5951
+ budgetUsd: 10,
5952
+ budgetUsdPerDay: 50,
5953
+ pauseAfter: 2,
5954
+ merge: true,
5955
+ deliverMaxOpen: 1,
5956
+ checksMinutes: 60,
5957
+ /** deliver: agentpipe's own tier for its review step. */
5958
+ reviewTier: null,
5959
+ scavengeMaxOpen: 5
5960
+ };
5961
+ /** A tier's name, as agentpipe takes it (`--tier NAME`). */
5962
+ const TIER_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
5963
+ /**
5964
+ * The steps a deliver run can continue a pull request from (`POST /v1/loops/{id}/runs {task, from}`): the ones
5965
+ * after it was opened and reviewed. `merge` only when the loop merges.
5966
+ */
5967
+ const CONTINUE_STEPS = [
5968
+ "checks",
5969
+ "feedback",
5970
+ "merge"
5971
+ ];
5972
+ /**
5973
+ * Why a deliver run stops before `merge` (plan §1.12): the loop doesn't merge (`mergeOff`); nobody queued its task
5974
+ * from a browser (`queuedOutside`); or its title or description was written outside a browser after it was queued
5975
+ * (`textChanged`). A loop merges on its own only what a person queued from a browser, and nothing has rewritten since.
5976
+ */
5977
+ const MERGE_HOLDS = [
5978
+ "mergeOff",
5979
+ "queuedOutside",
5980
+ "textChanged"
5981
+ ];
5982
+ /**
5983
+ * Why a loop is paused: you paused it; `pauseAfter` runs in a row failed or needed you; or a run couldn't start
5984
+ * (the folder, agentpipe missing, a refusing precondition: the run says which).
5985
+ */
5986
+ const PAUSE_REASONS = [
5987
+ "you",
5988
+ "failures",
5989
+ "unstartable"
5990
+ ];
5991
+ /**
5992
+ * What a loop is doing, as `loopState()` works it out, in the order it checks them: the first that holds is the
5993
+ * state. `due` means it starts at its runner's next check-in.
5994
+ */
5995
+ const LOOP_STATES = [
5996
+ "paused",
5997
+ "noRunner",
5998
+ "runnerOffline",
5999
+ "runnerOutdated",
6000
+ "running",
6001
+ "waitingForYou",
6002
+ "dailyLimit",
6003
+ "budget",
6004
+ "waitingForTask",
6005
+ "due",
6006
+ "next"
6007
+ ];
5895
6008
  // ../../node_modules/.pnpm/fractional-indexing@4.0.0/node_modules/fractional-indexing/src/index.js
5896
6009
  const BASE_62_DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
5897
6010
  const BASE_52_DIGITS = BASE_62_DIGITS.slice(10);
@@ -6254,7 +6367,10 @@ const PROBLEM_CODES = [
6254
6367
  "session_ended",
6255
6368
  "email_not_confirmed",
6256
6369
  "unsupported_email",
6257
- "email_not_sent"
6370
+ "email_not_sent",
6371
+ "loops_off",
6372
+ "nothing_to_do",
6373
+ "pr_open"
6258
6374
  ];
6259
6375
  const CODES = new Set(PROBLEM_CODES);
6260
6376
  const isString = (v) => typeof v === "string";
@@ -6861,6 +6977,8 @@ const PageQuerySchema = strictObject({
6861
6977
  });
6862
6978
  /** An agent a runner can run, by name: "agentpipe". */
6863
6979
  const AdapterSchema = string().regex(/^[a-z][a-z0-9-]{0,31}$/, "A lowercase name, like agentpipe");
6980
+ /** A loop's recipe a runner can run, by name: "deliver". The server may not know it yet (a newer runner). */
6981
+ const RecipeNameSchema = string().regex(/^[a-z][a-z0-9-]{0,31}$/, "A lowercase name, like deliver");
6864
6982
  /** One line of text, no control characters. */
6865
6983
  const oneLine$1 = (max) => string().trim().min(1, "Required").max(max).regex(/^[^\u0000-\u001f\u007f]*$/, "One line");
6866
6984
  /** A machine that runs agents for you: `monoban runner`, running there (in the background, or in a terminal). */
@@ -6884,8 +7002,89 @@ strictObject({
6884
7002
  adapters: array(AdapterSchema).max(8),
6885
7003
  version: string().regex(/^[0-9A-Za-z.+-]{1,32}$/).optional(),
6886
7004
  /** How often it will ask for work (default 3). */
6887
- pollSeconds: number$1().int().min(1).max(60).optional()
7005
+ pollSeconds: number$1().int().min(1).max(60).optional(),
7006
+ /** The loops' recipes it can run (docs/PLAN-AGENT-LOOPS.md); none when left out (a runner before loops). */
7007
+ recipes: array(RecipeNameSchema).max(8).optional()
6888
7008
  }).meta({ id: "RunnerRegister" });
7009
+ strictObject({
7010
+ recipes: array(RecipeNameSchema).max(8),
7011
+ free: boolean()
7012
+ }).meta({ id: "RunnerHeartbeat" });
7013
+ /**
7014
+ * Agent loops (loops.ts, docs/PLAN-AGENT-LOOPS.md §1.4). A loop's options say how much it takes; each recipe has
7015
+ * its own, and a run of the loop carries a copy of them. The patch shapes have no defaults: the API merges a
7016
+ * patch into the loop's options and checks the result with the full shape.
7017
+ */
7018
+ const between = ({ min, max }) => number$1().min(min).max(max);
7019
+ const wholeBetween = (limits) => between(limits).int();
7020
+ const loopCommon = {
7021
+ /** Runs it starts per 24 hours. */
7022
+ perDay: wholeBetween(LOOP_LIMITS.perDay),
7023
+ /** What one run may spend, in US dollars. */
7024
+ budgetUsd: between(LOOP_LIMITS.budgetUsd),
7025
+ /** What its runs may spend per 24 hours, in US dollars. */
7026
+ budgetUsdPerDay: between(LOOP_LIMITS.budgetUsdPerDay),
7027
+ /** Runs in a row that failed or need you before it pauses itself. */
7028
+ pauseAfter: wholeBetween(LOOP_LIMITS.pauseAfter)
7029
+ };
7030
+ const deliverFields = {
7031
+ ...loopCommon,
7032
+ /** The column it takes tasks from. */
7033
+ column: IdSchema,
7034
+ /** Only tasks with this tag, which it takes off when it takes the task; null: every task in the column. */
7035
+ tag: IdSchema.nullable(),
7036
+ /** Merge each pull request when its checks pass (only a task queued from the browser, plan §1.12). */
7037
+ merge: boolean(),
7038
+ /** Its pull requests that may wait for you before it stops taking tasks. */
7039
+ maxOpen: wholeBetween(LOOP_LIMITS.deliverMaxOpen),
7040
+ /** How long `checks` waits for CI, in minutes. */
7041
+ checksMinutes: wholeBetween(LOOP_LIMITS.checksMinutes),
7042
+ /** The agentpipe tier its review step runs on (`--tier`); null: agentpipe's own. */
7043
+ reviewTier: string().regex(TIER_NAME, "A tier's name, like light").nullable()
7044
+ };
7045
+ const scavengeFields = {
7046
+ ...loopCommon,
7047
+ /** What to look for, on one line. */
7048
+ focus: text().min(1, "Required").max(LOOP_LIMITS.focus).regex(/^[^\r\n]*$/, "One line"),
7049
+ /** The column it files tasks in. */
7050
+ column: IdSchema,
7051
+ /** The tag it puts on what it files (and counts its open tasks by). */
7052
+ tag: IdSchema,
7053
+ /** Its open tasks before it stops filing. */
7054
+ maxOpen: wholeBetween(LOOP_LIMITS.scavengeMaxOpen)
7055
+ };
7056
+ /** A run's budget can't be more than the day's, or the loop would never start one. */
7057
+ const budgetFits = (o) => o.budgetUsd === void 0 || o.budgetUsdPerDay === void 0 || o.budgetUsd <= o.budgetUsdPerDay;
7058
+ const BUDGET_FITS = "A run's budget can't be more than the day's";
7059
+ const DeliverOptionsSchema = strictObject({
7060
+ ...deliverFields,
7061
+ perDay: deliverFields.perDay.default(LOOP_DEFAULTS.perDay),
7062
+ budgetUsd: deliverFields.budgetUsd.default(LOOP_DEFAULTS.budgetUsd),
7063
+ budgetUsdPerDay: deliverFields.budgetUsdPerDay.default(LOOP_DEFAULTS.budgetUsdPerDay),
7064
+ pauseAfter: deliverFields.pauseAfter.default(LOOP_DEFAULTS.pauseAfter),
7065
+ tag: deliverFields.tag.default(null),
7066
+ merge: deliverFields.merge.default(LOOP_DEFAULTS.merge),
7067
+ maxOpen: deliverFields.maxOpen.default(LOOP_DEFAULTS.deliverMaxOpen),
7068
+ checksMinutes: deliverFields.checksMinutes.default(LOOP_DEFAULTS.checksMinutes),
7069
+ reviewTier: deliverFields.reviewTier.default(LOOP_DEFAULTS.reviewTier)
7070
+ }).refine(budgetFits, {
7071
+ message: BUDGET_FITS,
7072
+ path: ["budgetUsd"]
7073
+ }).meta({ id: "DeliverOptions" });
7074
+ const ScavengeOptionsSchema = strictObject({
7075
+ ...scavengeFields,
7076
+ perDay: scavengeFields.perDay.default(LOOP_DEFAULTS.perDay),
7077
+ budgetUsd: scavengeFields.budgetUsd.default(LOOP_DEFAULTS.budgetUsd),
7078
+ budgetUsdPerDay: scavengeFields.budgetUsdPerDay.default(LOOP_DEFAULTS.budgetUsdPerDay),
7079
+ pauseAfter: scavengeFields.pauseAfter.default(LOOP_DEFAULTS.pauseAfter),
7080
+ maxOpen: scavengeFields.maxOpen.default(LOOP_DEFAULTS.scavengeMaxOpen)
7081
+ }).refine(budgetFits, {
7082
+ message: BUDGET_FITS,
7083
+ path: ["budgetUsd"]
7084
+ }).meta({ id: "ScavengeOptions" });
7085
+ /** A loop's options as the API returns them: every one set. */
7086
+ const DeliverOptionsSetSchema = object(deliverFields).meta({ id: "DeliverOptionsSet" });
7087
+ const ScavengeOptionsSetSchema = object(scavengeFields).meta({ id: "ScavengeOptionsSet" });
6889
7088
  /** What the agent may do. */
6890
7089
  const RunOptionsSchema = strictObject({
6891
7090
  /** Open a pull request as a draft, ready for review, or none (finish on a branch). */
@@ -6918,11 +7117,51 @@ const RunStepSchema = object({
6918
7117
  /** Why it was skipped or failed. */
6919
7118
  message: string().nullable()
6920
7119
  }).meta({ id: "RunStep" });
7120
+ /**
7121
+ * What a loop's run was started with (docs/PLAN-AGENT-LOOPS.md §1.4): a copy of the loop's options then, the names
7122
+ * its column and tag had, and for a run that continues a pull request, the step it starts at, the pull request and
7123
+ * the run that opened it. Only the server writes it.
7124
+ */
7125
+ const LoopRunPlanSchema = object({
7126
+ /** The loop's options when the run was made (its recipe's: DeliverOptionsSet or ScavengeOptionsSet). */
7127
+ options: union([DeliverOptionsSetSchema, ScavengeOptionsSetSchema]),
7128
+ /** deliver: the column it took the task from; scavenge: the column it files in. */
7129
+ columnName: string().nullable(),
7130
+ /** deliver: the tag it took off the task (null: none); scavenge: the tag it puts on what it files. */
7131
+ tagName: string().nullable(),
7132
+ /** The step a continued run starts at; null: from the first. */
7133
+ from: _enum(CONTINUE_STEPS).nullable(),
7134
+ /** The pull request a continued run works on. */
7135
+ prUrl: string().nullable(),
7136
+ /** The run that opened that pull request. */
7137
+ continues: IdSchema.nullable(),
7138
+ /**
7139
+ * That run's external id: agentpipe's run that opened the pull request (its branch is `agentpipe/<id>`), which
7140
+ * `agentpipe merge --expect-run` checks. Null when that run never said it.
7141
+ */
7142
+ externalId: string().nullable(),
7143
+ /** scavenge: how many tasks it may file (its `maxOpen` less its open tasks); null for deliver. */
7144
+ limit: number$1().int().nonnegative().nullable()
7145
+ }).meta({ id: "LoopRunPlan" });
6921
7146
  /** A coding agent working on a task, on one of your runners. */
6922
7147
  const TaskRunSchema = object({
6923
7148
  id: IdSchema,
6924
- /** The task ("MON-12"); null once it's deleted. */
7149
+ /** The task ("MON-12"); null once it's deleted, and for a loop's run that has none (a scavenger's). */
6925
7150
  ref: string().nullable(),
7151
+ /** The loop it is a pass of (docs/PLAN-AGENT-LOOPS.md); null for a run started on a task, or its loop deleted. */
7152
+ loopId: IdSchema.nullable(),
7153
+ /** The loop's type, which stays after the loop is deleted; null for a run started on a task. */
7154
+ recipe: string().nullable(),
7155
+ /** What a loop's run was started with; null for a run started on a task. */
7156
+ loopRun: LoopRunPlanSchema.nullable(),
7157
+ /**
7158
+ * A deliver loop's run: whether it may merge its pull request on its own (its loop merges, a browser queued its
7159
+ * task, and nothing but a browser has written the task's text since; docs/PLAN-AGENT-LOOPS.md §1.12), read now.
7160
+ * Null for a run that isn't a deliver loop's.
7161
+ */
7162
+ mayMerge: boolean().nullable(),
7163
+ /** Why it may not (`mergeOff`, `queuedOutside`, `textChanged`); null when it may, or isn't a deliver loop's. */
7164
+ mergeHold: _enum(MERGE_HOLDS).nullable(),
6926
7165
  runner: object({
6927
7166
  /** Null once the runner is gone. */
6928
7167
  id: IdSchema.nullable(),
@@ -6961,14 +7200,19 @@ const TaskRunSchema = object({
6961
7200
  }).meta({ id: "TaskRun" });
6962
7201
  TaskRunSchema.extend({ steps: array(RunStepSchema) }).meta({ id: "TaskRunDetail" });
6963
7202
  /** A run for a runner to start: with what it needs to check the folder (the project's key and repo). */
6964
- const RunToStartSchema = TaskRunSchema.extend({ project: object({
7203
+ /** A run's project, for the runner to check the folder against (its key, and the repository it's linked to). */
7204
+ const RunProjectSchema = object({
6965
7205
  key: string(),
6966
7206
  repo: string().nullable()
6967
- }).meta({ id: "RunProject" }) }).meta({ id: "RunToStart" });
7207
+ }).meta({ id: "RunProject" });
7208
+ const RunToStartSchema = TaskRunSchema.extend({ project: RunProjectSchema }).meta({ id: "RunToStart" });
7209
+ /** Run an agent on a task, on one of your runners. */
7210
+ /** An absolute path on a runner's machine. */
7211
+ const Workdir = string().trim().min(1, "Required").max(RUN_LIMITS.workdir).refine(isAbsolutePath, "An absolute path, like /Users/you/code/project").meta({ pattern: "^/" });
6968
7212
  strictObject({
6969
7213
  runnerId: IdSchema,
6970
7214
  /** An absolute path on the runner's machine: a checkout of the project's linked repository. */
6971
- workdir: string().trim().min(1, "Required").max(RUN_LIMITS.workdir).refine(isAbsolutePath, "An absolute path, like /Users/you/code/project").meta({ pattern: "^/" }),
7215
+ workdir: Workdir,
6972
7216
  /** The agent (agents.ts); the runner must have it, and it must take the options (default agentpipe). */
6973
7217
  adapter: AdapterSchema.optional(),
6974
7218
  mode: _enum(RUN_MODES).default("local"),
@@ -7035,8 +7279,121 @@ object({
7035
7279
  /** Queued for it, oldest first (at most 5). */
7036
7280
  queued: array(RunToStartSchema),
7037
7281
  /** Running on it: one it doesn't know of was left behind; `cancelRequested` asks it to stop. */
7038
- running: array(TaskRunSchema)
7282
+ running: array(TaskRunSchema),
7283
+ /**
7284
+ * To a runner that runs loops: its deliver loops with pull requests waiting for you, and their folders, where an
7285
+ * idle runner runs `agentpipe ledger sync` (a pull request merged by hand moves its task to Done), once the folder
7286
+ * is a checkout of the project's, as for a run.
7287
+ */
7288
+ waiting: array(object({
7289
+ loopId: IdSchema,
7290
+ workdir: string(),
7291
+ project: RunProjectSchema
7292
+ }).meta({ id: "LoopWaiting" })).optional()
7039
7293
  }).meta({ id: "RunnerWork" });
7294
+ /** At least one option, or the patch would change nothing (the refine, for JSON Schema: minProperties). */
7295
+ const someOption = (o) => Object.keys(o).length > 0;
7296
+ const SOME_OPTION = "Send at least one option to change";
7297
+ const DeliverOptionsPatchSchema = strictObject(deliverFields).partial().refine(someOption, SOME_OPTION).meta({
7298
+ id: "DeliverOptionsPatch",
7299
+ minProperties: 1
7300
+ });
7301
+ const ScavengeOptionsPatchSchema = strictObject(scavengeFields).partial().refine(someOption, SOME_OPTION).meta({
7302
+ id: "ScavengeOptionsPatch",
7303
+ minProperties: 1
7304
+ });
7305
+ /** What a loop is doing (loops.ts `loopState`); the words are @monoban/i18n's `describeLoopState`. */
7306
+ const LoopStateSchema = object({
7307
+ state: _enum(LOOP_STATES),
7308
+ /** When it would start next if nothing else stood in the way. */
7309
+ nextAt: Timestamp.nullable(),
7310
+ why: object({
7311
+ reason: _enum(PAUSE_REASONS).optional(),
7312
+ runner: string().optional(),
7313
+ count: number$1().int().nonnegative().optional(),
7314
+ of: _enum(["pullRequests", "tasks"]).optional(),
7315
+ spent: number$1().nonnegative().optional(),
7316
+ limit: number$1().nonnegative().optional()
7317
+ }).meta({ id: "LoopWhy" })
7318
+ }).meta({ id: "LoopState" });
7319
+ const loopName = text().min(1, "Required").max(LOOP_LIMITS.name);
7320
+ const loopInterval = wholeBetween(LOOP_LIMITS.intervalSeconds);
7321
+ const LoopBase = object({
7322
+ id: IdSchema,
7323
+ name: string(),
7324
+ runner: object({
7325
+ /** Null once the runner is gone (choose another). */
7326
+ id: IdSchema.nullable(),
7327
+ name: string(),
7328
+ online: boolean()
7329
+ }).meta({ id: "LoopRunner" }),
7330
+ workdir: string(),
7331
+ /** Between the starts of its runs. */
7332
+ intervalSeconds: number$1().int(),
7333
+ /** Null: on. Else why it's paused. */
7334
+ paused: _enum(PAUSE_REASONS).nullable(),
7335
+ state: LoopStateSchema,
7336
+ /** Its run going now (queued or running): the step it's in (null before the first) and its task, if it has one. */
7337
+ going: object({
7338
+ runId: IdSchema,
7339
+ step: string().nullable(),
7340
+ ref: string().nullable()
7341
+ }).nullable().meta({ id: "LoopGoing" }),
7342
+ /** Its runs started in the last 24 hours, and what they cost. */
7343
+ last24h: object({
7344
+ runs: number$1().int().nonnegative(),
7345
+ costUsd: number$1().nonnegative()
7346
+ }).meta({ id: "LoopDay" }),
7347
+ version: Version,
7348
+ createdAt: Timestamp,
7349
+ updatedAt: Timestamp
7350
+ });
7351
+ discriminatedUnion("recipe", [LoopBase.extend({
7352
+ recipe: literal("deliver"),
7353
+ options: DeliverOptionsSetSchema
7354
+ }).meta({ id: "DeliverLoop" }), LoopBase.extend({
7355
+ recipe: literal("scavenge"),
7356
+ options: ScavengeOptionsSetSchema
7357
+ }).meta({ id: "ScavengeLoop" })]).meta({ id: "Loop" });
7358
+ const LoopCreateBase = {
7359
+ name: loopName,
7360
+ runnerId: IdSchema,
7361
+ /** A checkout of the project's linked repository on the runner's machine. */
7362
+ workdir: Workdir,
7363
+ intervalSeconds: loopInterval
7364
+ };
7365
+ discriminatedUnion("recipe", [strictObject({
7366
+ ...LoopCreateBase,
7367
+ recipe: literal("deliver"),
7368
+ options: DeliverOptionsSchema
7369
+ }), strictObject({
7370
+ ...LoopCreateBase,
7371
+ recipe: literal("scavenge"),
7372
+ options: ScavengeOptionsSchema
7373
+ })]).meta({ id: "LoopCreate" });
7374
+ strictObject({
7375
+ name: loopName.optional(),
7376
+ runnerId: IdSchema.optional(),
7377
+ workdir: Workdir.optional(),
7378
+ intervalSeconds: loopInterval.optional(),
7379
+ options: union([DeliverOptionsPatchSchema, ScavengeOptionsPatchSchema]).optional(),
7380
+ paused: boolean().optional()
7381
+ }).refine((patch) => Object.keys(patch).length > 0, "Send at least one field to change").meta({
7382
+ id: "LoopPatch",
7383
+ minProperties: 1
7384
+ });
7385
+ strictObject({
7386
+ /** The task's number in the loop's project (12 for MON-12). */
7387
+ task: number$1().int().min(1).max(2147483647).optional(),
7388
+ /** Continue the task's pull request from this step (`merge` only when the loop merges); needs `task`. */
7389
+ from: _enum(CONTINUE_STEPS).optional()
7390
+ }).refine((body) => body.from === void 0 || body.task !== void 0, {
7391
+ message: "Name the task whose pull request to continue",
7392
+ path: ["from"]
7393
+ }).meta({
7394
+ id: "LoopRunCreate",
7395
+ dependentRequired: { from: ["task"] }
7396
+ });
7040
7397
  PageQuerySchema.extend({
7041
7398
  from: DaySchema.describe("The first day (the client's today, for Today)"),
7042
7399
  to: DaySchema.optional().describe("The last day (`from` when left out); at most 62 days after `from`"),
@@ -7753,7 +8110,7 @@ function matchColumn(columns, query) {
7753
8110
  choices: [...columns]
7754
8111
  };
7755
8112
  }
7756
- const DAY_MS = 864e5;
8113
+ const DAY_MS$1 = 864e5;
7757
8114
  /**
7758
8115
  * Whether a task is archived: archived by hand (in any column: in Done it's done, elsewhere it won't be), or
7759
8116
  * in its project's Done column (`doneColumnId`: doneColumn()) for longer than the project's
@@ -7766,11 +8123,11 @@ function isArchived(task, doneColumnId, archiveAfterDays, now = Date.now()) {
7766
8123
  }
7767
8124
  /** Whether a task has been in its column for longer than `archiveAfterDays` (in Done, that archives it). */
7768
8125
  function archivedByTime(task, archiveAfterDays, now = Date.now()) {
7769
- return archiveAfterDays !== null && Date.parse(task.columnSince) < now - archiveAfterDays * DAY_MS;
8126
+ return archiveAfterDays !== null && Date.parse(task.columnSince) < now - archiveAfterDays * DAY_MS$1;
7770
8127
  }
7771
8128
  // src/version.ts
7772
8129
  /** This CLI's version, from package.json (set at build time by tsdown, and by vitest in tests). */
7773
- const VERSION = "1.8.0";
8130
+ const VERSION = "1.10.0";
7774
8131
  /** Sent as X-Monoban-Client, and shown in Settings › CLI sessions. */
7775
8132
  const CLIENT = `cli/${VERSION}`;
7776
8133
  // src/api.ts
@@ -7856,7 +8213,7 @@ var FileStore = class {
7856
8213
  }
7857
8214
  async write(all) {
7858
8215
  if (Object.keys(all).length === 0) {
7859
- await rm(this.path, { force: true });
8216
+ await rm$1(this.path, { force: true });
7860
8217
  return;
7861
8218
  }
7862
8219
  await mkdir(this.dir, {
@@ -7940,7 +8297,7 @@ async function openStore(options) {
7940
8297
  return file;
7941
8298
  }
7942
8299
  }
7943
- // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
8300
+ // ../../node_modules/.pnpm/commander@15.1.0/node_modules/commander/lib/error.js
7944
8301
  /**
7945
8302
  * CommanderError class
7946
8303
  */
@@ -7974,7 +8331,7 @@ var InvalidArgumentError = class extends CommanderError {
7974
8331
  this.name = this.constructor.name;
7975
8332
  }
7976
8333
  };
7977
- // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/argument.js
8334
+ // ../../node_modules/.pnpm/commander@15.1.0/node_modules/commander/lib/argument.js
7978
8335
  var Argument = class {
7979
8336
  /**
7980
8337
  * Initialize a new command argument with the given name and description.
@@ -8092,7 +8449,7 @@ function humanReadableArgName(arg) {
8092
8449
  const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
8093
8450
  return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
8094
8451
  }
8095
- // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/help.js
8452
+ // ../../node_modules/.pnpm/commander@15.1.0/node_modules/commander/lib/help.js
8096
8453
  /**
8097
8454
  * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
8098
8455
  * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
@@ -8160,8 +8517,8 @@ var Help = class {
8160
8517
  const removeShort = helpOption.short && cmd._findOption(helpOption.short);
8161
8518
  const removeLong = helpOption.long && cmd._findOption(helpOption.long);
8162
8519
  if (!removeShort && !removeLong) visibleOptions.push(helpOption);
8163
- else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description));
8164
- else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description));
8520
+ else if (helpOption.long && !removeLong) visibleOptions.push(cmd.createOption(helpOption.long, helpOption.description).helpGroup(helpOption.helpGroupHeading));
8521
+ else if (helpOption.short && !removeShort) visibleOptions.push(cmd.createOption(helpOption.short, helpOption.description).helpGroup(helpOption.helpGroupHeading));
8165
8522
  }
8166
8523
  if (this.sortOptions) visibleOptions.sort(this.compareOptions);
8167
8524
  return visibleOptions;
@@ -8566,7 +8923,7 @@ var Help = class {
8566
8923
  return wrappedLines.join("\n");
8567
8924
  }
8568
8925
  };
8569
- // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/option.js
8926
+ // ../../node_modules/.pnpm/commander@15.1.0/node_modules/commander/lib/option.js
8570
8927
  var Option = class {
8571
8928
  /**
8572
8929
  * Initialize a new `Option` with the given `flags` and `description`.
@@ -8579,7 +8936,7 @@ var Option = class {
8579
8936
  this.description = description || "";
8580
8937
  this.required = flags.includes("<");
8581
8938
  this.optional = flags.includes("[");
8582
- this.variadic = /\w\.\.\.[>\]]$/.test(flags);
8939
+ this.variadic = /\p{ID_Continue}\.\.\.[>\]]$/u.test(flags);
8583
8940
  this.mandatory = false;
8584
8941
  const optionFlags = splitOptionFlags(flags);
8585
8942
  this.short = optionFlags.shortFlag;
@@ -8863,7 +9220,7 @@ function splitOptionFlags(flags) {
8863
9220
  longFlag
8864
9221
  };
8865
9222
  }
8866
- // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/suggestSimilar.js
9223
+ // ../../node_modules/.pnpm/commander@15.1.0/node_modules/commander/lib/suggestSimilar.js
8867
9224
  const maxDistance = 3;
8868
9225
  function editDistance(a, b) {
8869
9226
  if (Math.abs(a.length - b.length) > maxDistance) return Math.max(a.length, b.length);
@@ -8914,7 +9271,7 @@ function suggestSimilar(word, candidates) {
8914
9271
  if (similar.length === 1) return `\n(Did you mean ${similar[0]}?)`;
8915
9272
  return "";
8916
9273
  }
8917
- // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/command.js
9274
+ // ../../node_modules/.pnpm/commander@15.1.0/node_modules/commander/lib/command.js
8918
9275
  var Command = class Command extends EventEmitter {
8919
9276
  /**
8920
9277
  * Initialize a new `Command`.
@@ -9664,7 +10021,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
9664
10021
  getOptionValueSourceWithGlobals(key) {
9665
10022
  let source;
9666
10023
  this._getCommandAndAncestors().forEach((cmd) => {
9667
- if (cmd.getOptionValueSource(key) !== void 0) source = cmd.getOptionValueSource(key);
10024
+ if (Object.hasOwn(cmd._optionValueSources, key)) source = cmd.getOptionValueSource(key);
9668
10025
  });
9669
10026
  return source;
9670
10027
  }
@@ -10173,7 +10530,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
10173
10530
  return arg.length > 1 && arg[0] === "-";
10174
10531
  }
10175
10532
  const negativeNumberArg = (arg) => {
10176
- if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
10533
+ if (!/^-(\d+|\d*\.\d+)([eE][+-]?\d+)?$/.test(arg)) return false;
10177
10534
  return !this._getCommandAndAncestors().some((cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short)));
10178
10535
  };
10179
10536
  let activeVariadicOption = null;
@@ -10573,7 +10930,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
10573
10930
  * (This does not override a group set directly on the subcommand using .helpGroup().)
10574
10931
  *
10575
10932
  * @example
10576
- * program.commandsGroup('Development Commands:);
10933
+ * program.commandsGroup('Development Commands:');
10577
10934
  * program.command('watch')...
10578
10935
  * program.command('lint')...
10579
10936
  * ...
@@ -10742,7 +11099,7 @@ Expecting one of '${allowedValues.join("', '")}'`);
10742
11099
  * Pass in false to disable the built-in help option.
10743
11100
  *
10744
11101
  * @example
10745
- * program.helpOption('-?, --help' 'show help'); // customise
11102
+ * program.helpOption('-?, --help', 'show help'); // customise
10746
11103
  * program.helpOption(false); // disable
10747
11104
  *
10748
11105
  * @param {(string | boolean)} flags
@@ -10864,12 +11221,12 @@ function incrementNodeInspectorPort(args) {
10864
11221
  let debugHost = "127.0.0.1";
10865
11222
  let debugPort = "9229";
10866
11223
  let match;
10867
- if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) debugOption = match[1];
10868
- else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
11224
+ if ((match = arg.match(/^(--inspect(-brk|-wait)?)$/)) !== null) debugOption = match[1];
11225
+ else if ((match = arg.match(/^(--inspect(-brk|-port|-wait)?)=(\[[^\]]+\]|[^:]+)$/)) !== null) {
10869
11226
  debugOption = match[1];
10870
11227
  if (/^\d+$/.test(match[3])) debugPort = match[3];
10871
11228
  else debugHost = match[3];
10872
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
11229
+ } else if ((match = arg.match(/^(--inspect(-brk|-port|-wait)?)=(\[[^\]]+\]|[^:]+):(\d+)$/)) !== null) {
10873
11230
  debugOption = match[1];
10874
11231
  debugHost = match[3];
10875
11232
  debugPort = match[4];
@@ -10903,19 +11260,19 @@ async function withLock(path, fn, { staleMs = 3e4, timeoutMs = 45e3, sleep = wai
10903
11260
  const deadline = Date.now() + timeoutMs;
10904
11261
  for (;;) {
10905
11262
  try {
10906
- await (await open(path, "wx", 384)).close();
11263
+ await (await open$3(path, "wx", 384)).close();
10907
11264
  break;
10908
11265
  } catch (err) {
10909
11266
  if (err.code !== "EEXIST") throw err;
10910
11267
  }
10911
- if (await stat(path).then((s) => Date.now() - s.mtimeMs, () => 0) > staleMs) await rm(path, { force: true });
11268
+ if (await stat(path).then((s) => Date.now() - s.mtimeMs, () => 0) > staleMs) await rm$1(path, { force: true });
10912
11269
  else if (Date.now() > deadline) throw new Error(busy);
10913
11270
  else await sleep(100);
10914
11271
  }
10915
11272
  try {
10916
11273
  return await fn();
10917
11274
  } finally {
10918
- await rm(path, { force: true });
11275
+ await rm$1(path, { force: true });
10919
11276
  }
10920
11277
  }
10921
11278
  const wait$1 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
@@ -11055,7 +11412,7 @@ async function editInEditor(text, name, env = process.env) {
11055
11412
  if (result.error || result.status !== 0) throw new CliError(`The editor (${editor}) didn't exit cleanly, so nothing changed.`);
11056
11413
  return await readFile(file, "utf8");
11057
11414
  } finally {
11058
- await rm(dir, {
11415
+ await rm$1(dir, {
11059
11416
  recursive: true,
11060
11417
  force: true
11061
11418
  });
@@ -11222,10 +11579,10 @@ function style(enabled) {
11222
11579
  color: (color, s) => sgr(ANSI[color], 39)(s)
11223
11580
  };
11224
11581
  }
11225
- const DAY = 864e5;
11582
+ const DAY$1 = 864e5;
11226
11583
  /** How long ago, in a few characters: "today", "3d", "5mo", "2y". */
11227
11584
  function age$1(iso, now = Date.now()) {
11228
- const days = Math.floor((now - new Date(iso).getTime()) / DAY);
11585
+ const days = Math.floor((now - new Date(iso).getTime()) / DAY$1);
11229
11586
  if (days < 1) return "today";
11230
11587
  if (days < 60) return `${days}d`;
11231
11588
  if (days < 730) return `${Math.floor(days / 30)}mo`;
@@ -11315,8 +11672,8 @@ const RELEASES = `https://github.com/thiagodmont/homebrew-tap/releases`;
11315
11672
  * agentpipe comes with a new monoban: change these three lines (from the release's checksums.txt) and release.
11316
11673
  */
11317
11674
  const AGENTPIPE = {
11318
- version: "0.5.0",
11319
- wheelSha256: "e69545311cfc99f09df165facf7fb74540d3b0903400ed5311f8245cfba00a89",
11675
+ version: "0.8.0",
11676
+ wheelSha256: "e1e92ec985827359abd4fbb71c54ebcbdaf5636e810695b2ef321c64a7e20c26",
11320
11677
  requirementsSha256: "41a8d073b0087efb80efafeb6a2b4750340d0f64920159cd4c723ed9167d0a98"
11321
11678
  };
11322
11679
  const agentpipeWheel = (version) => `agentpipe-${version}-py3-none-any.whl`;
@@ -11430,7 +11787,7 @@ async function latestVersion(ctx) {
11430
11787
  async function upgrade(ctx, options, kind = thisInstall()) {
11431
11788
  const latest = await latestVersion(ctx);
11432
11789
  const { how, command } = UPGRADE[kind];
11433
- const outdated = latest !== null && newer(latest, "1.8.0");
11790
+ const outdated = latest !== null && newer(latest, "1.10.0");
11434
11791
  if (options.json) {
11435
11792
  ctx.out(JSON.stringify({
11436
11793
  version: VERSION,
@@ -11575,7 +11932,7 @@ async function findUv(ctx, run, home, target, uvPin) {
11575
11932
  const archive = join(home, "downloads", `uv-${target}.tar.gz`);
11576
11933
  await writeFile(archive, await download(ctx, uvArchive(target, uvPin.version), uvPin.sha256[target]));
11577
11934
  const unpacked = join(home, "downloads", "uv");
11578
- await rm(unpacked, {
11935
+ await rm$1(unpacked, {
11579
11936
  recursive: true,
11580
11937
  force: true
11581
11938
  });
@@ -11634,7 +11991,7 @@ async function installAgentpipe(ctx, options = {}, deps = {}) {
11634
11991
  await writeFile(lock, `${new TextDecoder().decode(requirements).trimEnd()}\nagentpipe @ ${pathToFileURL(wheel).href} --hash=sha256:${pin.wheelSha256}\n`);
11635
11992
  ctx.err("Installing Python 3.12 and agentpipe's dependencies (a minute or two the first time)…");
11636
11993
  const dir = join(home, "versions", version);
11637
- await rm(dir, {
11994
+ await rm$1(dir, {
11638
11995
  recursive: true,
11639
11996
  force: true
11640
11997
  });
@@ -11662,18 +12019,18 @@ async function installAgentpipe(ctx, options = {}, deps = {}) {
11662
12019
  });
11663
12020
  if (said.code !== 0 || !said.stdout.includes(`agentpipe ${version}`)) throw new CliError(`agentpipe ${version} was installed but doesn't run: ${(said.stderr || said.stdout).trim()}`);
11664
12021
  const link = join(home, "current.new");
11665
- await rm(link, { force: true });
12022
+ await rm$1(link, { force: true });
11666
12023
  await symlink(join("versions", version), link);
11667
12024
  await rename(link, join(home, "current"));
11668
- for (const old of await readdir(join(home, "versions"))) if (old !== version && old !== before) await rm(join(home, "versions", old), {
12025
+ for (const old of await readdir(join(home, "versions"))) if (old !== version && old !== before) await rm$1(join(home, "versions", old), {
11669
12026
  recursive: true,
11670
12027
  force: true
11671
12028
  });
11672
- await rm(join(home, "cache"), {
12029
+ await rm$1(join(home, "cache"), {
11673
12030
  recursive: true,
11674
12031
  force: true
11675
12032
  });
11676
- await rm(join(home, "downloads"), {
12033
+ await rm$1(join(home, "downloads"), {
11677
12034
  recursive: true,
11678
12035
  force: true
11679
12036
  });
@@ -11738,7 +12095,7 @@ async function uninstall(ctx, options) {
11738
12095
  const home = agentpipeHome(ctx.env);
11739
12096
  if (!existsSync(home)) return ctx.out("agentpipe isn't installed by monoban: nothing to remove.");
11740
12097
  if (!options.yes && !await ctx.confirm(`Remove agentpipe (${home})?`)) throw new CliError("Left as it is (--yes removes it without asking).", EXIT.usage);
11741
- await rm(home, {
12098
+ await rm$1(home, {
11742
12099
  recursive: true,
11743
12100
  force: true
11744
12101
  });
@@ -11771,7 +12128,8 @@ function fileProblem(v) {
11771
12128
  "allow",
11772
12129
  "confirm",
11773
12130
  "agents",
11774
- "adapters"
12131
+ "adapters",
12132
+ "loops"
11775
12133
  ];
11776
12134
  const unknown = Object.keys(f).find((k) => !known.includes(k));
11777
12135
  if (unknown) return `${unknown} isn't a setting (${known.join(", ")})`;
@@ -11800,6 +12158,20 @@ function fileProblem(v) {
11800
12158
  if (agent.args !== void 0 && !(Array.isArray(agent.args) && agent.args.every((a) => typeof a === "string"))) return `adapters.${name}.args: a list of arguments`;
11801
12159
  }
11802
12160
  }
12161
+ if (f.loops !== void 0) {
12162
+ if (!f.loops || typeof f.loops !== "object" || Array.isArray(f.loops)) return "loops: an object";
12163
+ const loops = f.loops;
12164
+ const settings = [
12165
+ "enabled",
12166
+ "merge",
12167
+ "maxUsdPerDay"
12168
+ ];
12169
+ const extra = Object.keys(loops).find((k) => !settings.includes(k));
12170
+ if (extra) return `loops.${extra} isn't a setting (${settings.join(", ")})`;
12171
+ for (const key of ["enabled", "merge"]) if (loops[key] !== void 0 && typeof loops[key] !== "boolean") return `loops.${key}: true or false`;
12172
+ const max = loops.maxUsdPerDay;
12173
+ if (max !== void 0 && !(typeof max === "number" && max >= 1 && max <= 1e4)) return "loops.maxUsdPerDay: US dollars, 1 to 10000";
12174
+ }
11803
12175
  return null;
11804
12176
  }
11805
12177
  const RUNNER_FILE = "runner.json";
@@ -11853,9 +12225,109 @@ async function runnerSettings(dir, flags, env, hostname) {
11853
12225
  commands,
11854
12226
  args,
11855
12227
  allowFullAccess: flags.allowFullAccess ?? file.adapters?.codex?.allowFullAccess ?? false,
11856
- agentpipeBudgetUsd: file.adapters?.agentpipe?.budgetUsd ?? 10
12228
+ agentpipeBudgetUsd: file.adapters?.agentpipe?.budgetUsd ?? 10,
12229
+ loops: {
12230
+ enabled: flags.loops !== false && (file.loops?.enabled ?? true),
12231
+ merge: file.loops?.merge ?? true,
12232
+ maxUsdPerDay: file.loops?.maxUsdPerDay ?? 100
12233
+ }
12234
+ };
12235
+ }
12236
+ // src/runner/process.ts
12237
+ const defaultSpawn = spawn;
12238
+ const TAIL = 20;
12239
+ function startProcess({ command, args, cwd, env, stdin, onLine, spawn = defaultSpawn, graceMs = 1e4 }) {
12240
+ let child;
12241
+ let exited = false;
12242
+ const timers = [];
12243
+ const signal = (sig) => {
12244
+ if (!child || exited) return;
12245
+ try {
12246
+ if (child.pid) process.kill(-child.pid, sig);
12247
+ else child.kill(sig);
12248
+ } catch {
12249
+ child.kill(sig);
12250
+ }
12251
+ };
12252
+ return {
12253
+ done: new Promise((resolve) => {
12254
+ try {
12255
+ child = spawn(command, args, {
12256
+ cwd,
12257
+ env,
12258
+ detached: true
12259
+ });
12260
+ } catch (err) {
12261
+ resolve({
12262
+ code: null,
12263
+ spawnError: `Couldn't start ${command}: ${err.message}`,
12264
+ lastError: null
12265
+ });
12266
+ return;
12267
+ }
12268
+ let spawnError = null;
12269
+ const tail = [];
12270
+ child.on("error", (err) => {
12271
+ spawnError = err.code === "ENOENT" ? `${command} isn't installed here (or isn't on the runner's PATH).` : `${command} failed: ${err.message}`;
12272
+ });
12273
+ if (child.stdin) {
12274
+ child.stdin.on("error", () => {});
12275
+ child.stdin.end(stdin ?? "");
12276
+ }
12277
+ if (child.stdout) createInterface$1({ input: child.stdout }).on("line", onLine);
12278
+ if (child.stderr) createInterface$1({ input: child.stderr }).on("line", (line) => {
12279
+ if (!line.trim()) return;
12280
+ tail.push(line.trim());
12281
+ if (tail.length > TAIL) tail.shift();
12282
+ });
12283
+ child.on("close", (code) => {
12284
+ exited = true;
12285
+ for (const t of timers) clearTimeout(t);
12286
+ resolve({
12287
+ code,
12288
+ spawnError,
12289
+ lastError: tail.at(-1) ?? null
12290
+ });
12291
+ });
12292
+ }),
12293
+ stop: () => {
12294
+ signal("SIGINT");
12295
+ timers.push(setTimeout(() => signal("SIGTERM"), graceMs));
12296
+ timers.push(setTimeout(() => signal("SIGKILL"), graceMs * 2));
12297
+ },
12298
+ interrupt: () => {
12299
+ if (child && !exited) child.kill("SIGINT");
12300
+ },
12301
+ terminate: () => {
12302
+ if (!child || exited) return;
12303
+ child.kill("SIGTERM");
12304
+ timers.push(setTimeout(() => signal("SIGKILL"), graceMs * 3));
12305
+ },
12306
+ pid: () => child?.pid ?? null
11857
12307
  };
11858
12308
  }
12309
+ /** The first version number a command prints for `--version` ("2.1.300 (Claude Code)" → 2.1.300), or null. */
12310
+ function versionOf(command, env = process.env) {
12311
+ return new Promise((resolve) => {
12312
+ execFile(command, ["--version"], {
12313
+ timeout: 15e3,
12314
+ env
12315
+ }, (err, stdout, stderr) => {
12316
+ if (err) return resolve(null);
12317
+ resolve(/\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?/.exec(`${stdout} ${stderr}`)?.[0] ?? null);
12318
+ });
12319
+ });
12320
+ }
12321
+ /** Whether version `a` is at least `b` (numbers only: 2.1.259). */
12322
+ function atLeast(a, b) {
12323
+ const parts = (v) => v.split(/[-+]/)[0]?.split(".").map(Number) ?? [];
12324
+ const [x, y] = [parts(a), parts(b)];
12325
+ for (let i = 0; i < Math.max(x.length, y.length); i++) {
12326
+ const d = (x[i] ?? 0) - (y[i] ?? 0);
12327
+ if (d) return d > 0;
12328
+ }
12329
+ return true;
12330
+ }
11859
12331
  // src/runner/agents/agentpipe.ts
11860
12332
  /** agentpipe's step statuses that monoban has too; the others (budget_exceeded, max_turns…) are failures. */
11861
12333
  const SAME = [
@@ -11876,6 +12348,26 @@ const SAYS = {
11876
12348
  refused: "It couldn't start",
11877
12349
  nothing_to_do: "There was nothing to do"
11878
12350
  };
12351
+ /**
12352
+ * What `ship.end`'s state means for the step (`ship --no-merge`, and `address --ship`): it hands back a green pull
12353
+ * request (`ready_to_merge`), or parks it for a person, or was stopped. `merged` only without `--no-merge`.
12354
+ */
12355
+ const SHIP_ENDINGS = {
12356
+ merged: "succeeded",
12357
+ ready_to_merge: "succeeded",
12358
+ needs_human: "needs_human",
12359
+ cancelled: "cancelled"
12360
+ };
12361
+ /** What CI's state reads as, by `ci.check`'s trigger; another trigger reads as its words. */
12362
+ const CI_SAYS = {
12363
+ checks_green: "CI is green",
12364
+ checks_red: "CI failed",
12365
+ checks_pending: "CI is running",
12366
+ no_checks: "The pull request has no CI checks",
12367
+ blocked: "CI is green; GitHub reports the pull request blocked (a required review, or another rule)",
12368
+ behind_base: "The pull request is behind its base",
12369
+ conflicted: "The pull request conflicts with its base"
12370
+ };
11879
12371
  const str = (v) => typeof v === "string" && v.trim() ? v.trim() : null;
11880
12372
  const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;
11881
12373
  /** A message the API takes: one line or more, at most 2000 characters. */
@@ -11890,8 +12382,20 @@ function agentpipeMapper(report) {
11890
12382
  const started = /* @__PURE__ */ new Set();
11891
12383
  const attempts = /* @__PURE__ */ new Map();
11892
12384
  let pending = null;
12385
+ /** What the model steps cost (their `step.end`s), and what the ship loop after them spent (its own count). */
11893
12386
  let total = 0;
12387
+ let shipped = 0;
11894
12388
  let ending = null;
12389
+ /** agentpipe's own word for how it ended: `run.end`'s status, then `ship.end`'s state. */
12390
+ let said = null;
12391
+ /** `run.end` came: what follows is `address --ship`'s ship loop, which `agentpipe cancel` can't reach. */
12392
+ let runEnded = false;
12393
+ /** CI's state as last said (`ci.check`), so only a change is reported: the loop polls every few seconds. */
12394
+ let ci = null;
12395
+ /** `scout --track`: the tasks its `file` step filed (their refs, else their URLs), and `run.end`'s counts. */
12396
+ const filed = [];
12397
+ let counts = null;
12398
+ const spent = () => report.update({ costUsd: Math.round((total + shipped) * 1e4) / 1e4 });
11895
12399
  const flush = (cost) => {
11896
12400
  if (!pending) return;
11897
12401
  const { step, attempt, status, message, at } = pending;
@@ -11969,9 +12473,9 @@ function agentpipeMapper(report) {
11969
12473
  }
11970
12474
  if (costShaped) {
11971
12475
  const costUsd = num(d.cost_usd);
11972
- if (costUsd) {
12476
+ if (costUsd && !runEnded && ci === null) {
11973
12477
  total += costUsd;
11974
- report.update({ costUsd: Math.round(total * 1e4) / 1e4 });
12478
+ spent();
11975
12479
  }
11976
12480
  flush({
11977
12481
  durationMs: num(d.duration_ms),
@@ -11980,6 +12484,72 @@ function agentpipeMapper(report) {
11980
12484
  }
11981
12485
  return;
11982
12486
  }
12487
+ case "ci.check": {
12488
+ const trigger = str(d.trigger);
12489
+ if (!trigger) return;
12490
+ const failing = Array.isArray(d.failing) ? d.failing.filter((f) => typeof f === "string") : [];
12491
+ const words = CI_SAYS[trigger] ?? trigger.replace(/_/g, " ");
12492
+ const now = trigger === "checks_red" && failing.length ? `${words}: ${failing.join(", ")}` : words;
12493
+ const blocked = trigger === "blocked";
12494
+ if (ci?.said !== now) report.event({
12495
+ kind: "activity",
12496
+ ...step && { step },
12497
+ message: clip$1(now),
12498
+ ...at && { at }
12499
+ });
12500
+ ci = {
12501
+ said: now,
12502
+ blocked
12503
+ };
12504
+ return;
12505
+ }
12506
+ case "ci.repair_attempt": {
12507
+ const sofar = num(d.spent_usd);
12508
+ if (sofar !== null && sofar > shipped) {
12509
+ shipped = sofar;
12510
+ spent();
12511
+ }
12512
+ const attempt = num(d.attempt);
12513
+ const message = `${d.succeeded === true ? "Pushed a repair" : "A repair didn't work"}${attempt ? ` (attempt ${attempt})` : ""}`;
12514
+ report.event({
12515
+ kind: "activity",
12516
+ ...step && { step },
12517
+ message,
12518
+ ...at && { at }
12519
+ });
12520
+ return;
12521
+ }
12522
+ case "review.findings": {
12523
+ const found = Array.isArray(d.candidates) ? d.candidates.length : 0;
12524
+ const message = found === 1 ? "Found 1 thing to look at" : `Found ${found} things to look at`;
12525
+ report.event({
12526
+ kind: "activity",
12527
+ ...step && { step },
12528
+ message,
12529
+ ...at && { at }
12530
+ });
12531
+ return;
12532
+ }
12533
+ case "review.posted":
12534
+ report.event({
12535
+ kind: "activity",
12536
+ ...step && { step },
12537
+ message: "Posted its review",
12538
+ ...at && { at }
12539
+ });
12540
+ return;
12541
+ case "review.answered":
12542
+ case "feedback.intake": {
12543
+ const n = Array.isArray(d.answers) ? d.answers.length : Array.isArray(d.comments) ? d.comments.length : 0;
12544
+ const what = e.kind === "review.answered" ? "Answered" : "Comments to answer:";
12545
+ report.event({
12546
+ kind: "activity",
12547
+ ...step && { step },
12548
+ message: `${what} ${n}`,
12549
+ ...at && { at }
12550
+ });
12551
+ return;
12552
+ }
11983
12553
  case "pr.created": {
11984
12554
  const url = str(d.url);
11985
12555
  if (!url) return;
@@ -12005,6 +12575,20 @@ function agentpipeMapper(report) {
12005
12575
  });
12006
12576
  return;
12007
12577
  }
12578
+ case "issue.created": {
12579
+ const url = str(d.url);
12580
+ if (step !== "file" || d.reused === true || !url) return;
12581
+ const what = str(d.display) ?? (num(d.number) !== null ? `#${num(d.number)}` : url);
12582
+ filed.push(what);
12583
+ report.event({
12584
+ kind: "board",
12585
+ ...step && { step },
12586
+ message: clip$1(`filed ${what}`),
12587
+ data: { url: clip$1(url) },
12588
+ ...at && { at }
12589
+ });
12590
+ return;
12591
+ }
12008
12592
  case "issue.comment": {
12009
12593
  const milestone = str(d.milestone);
12010
12594
  report.event({
@@ -12016,6 +12600,15 @@ function agentpipeMapper(report) {
12016
12600
  }
12017
12601
  case "question.asked":
12018
12602
  case "escalation": {
12603
+ if (e.kind === "escalation" && ci?.blocked) {
12604
+ report.event({
12605
+ kind: "activity",
12606
+ ...step && { step },
12607
+ message: "Waiting for a required review",
12608
+ ...at && { at }
12609
+ });
12610
+ return;
12611
+ }
12019
12612
  const text = str(d.question) ?? str(d.text) ?? str(d.message) ?? str(d.reason) ?? "It needs an answer.";
12020
12613
  report.event({
12021
12614
  kind: "question",
@@ -12037,7 +12630,10 @@ function agentpipeMapper(report) {
12037
12630
  }
12038
12631
  case "run.end": {
12039
12632
  flush();
12633
+ runEnded = true;
12040
12634
  const status = str(d.status) ?? "failed";
12635
+ said = status;
12636
+ if (d.counts && typeof d.counts === "object") counts = Object.fromEntries(Object.entries(d.counts).flatMap(([k, v]) => num(v) === null ? [] : [[k, v]]));
12041
12637
  const reason = str(d.reason);
12042
12638
  const says = SAYS[status];
12043
12639
  ending = {
@@ -12050,12 +12646,75 @@ function agentpipeMapper(report) {
12050
12646
  });
12051
12647
  return;
12052
12648
  }
12649
+ case "merge.completed": {
12650
+ said = "merged";
12651
+ const sha = str(d.sha);
12652
+ ending = {
12653
+ status: "succeeded",
12654
+ reason: sha ? `Merged (${sha.slice(0, 7)}).` : "Merged."
12655
+ };
12656
+ return;
12657
+ }
12658
+ case "merge.blocked": {
12659
+ said = "blocked";
12660
+ const reason = str(d.reason);
12661
+ ending = {
12662
+ status: "needs_human",
12663
+ reason: clip$1(reason ?? "agentpipe didn't merge it.")
12664
+ };
12665
+ report.event({
12666
+ kind: "question",
12667
+ ...step && { step },
12668
+ message: ending.reason ?? "",
12669
+ ...at && { at }
12670
+ });
12671
+ return;
12672
+ }
12673
+ case "ship.end": {
12674
+ flush();
12675
+ const state = str(d.state) ?? "failed";
12676
+ const reason = str(d.reason);
12677
+ said = state;
12678
+ const cost = num(d.cost_usd);
12679
+ if (cost !== null && cost > shipped) {
12680
+ shipped = cost;
12681
+ spent();
12682
+ }
12683
+ if (state === "needs_human" && ci?.blocked) ending = {
12684
+ status: "succeeded",
12685
+ reason: "CI is green; GitHub is waiting for a required review."
12686
+ };
12687
+ else if (state === "ready_to_merge") ending = {
12688
+ status: "succeeded",
12689
+ reason: "CI is green: ready for you to merge."
12690
+ };
12691
+ else if (state === "refused") ending = {
12692
+ status: "failed",
12693
+ reason: clip$1(`${SAYS.refused}${reason ? `: ${reason}` : "."}`)
12694
+ };
12695
+ else ending = {
12696
+ status: SHIP_ENDINGS[state] ?? "failed",
12697
+ reason: reason ? clip$1(reason) : SHIP_ENDINGS[state] ? null : `It ended ${state.replace(/_/g, " ")}.`
12698
+ };
12699
+ if (ending.status === "failed" && ending.reason) report.event({
12700
+ kind: "error",
12701
+ message: clip$1(ending.reason)
12702
+ });
12703
+ return;
12704
+ }
12053
12705
  }
12054
12706
  };
12055
12707
  return {
12056
12708
  take,
12057
12709
  /** How agentpipe said the run ended (null: it didn't). */
12058
12710
  ending: () => ending,
12711
+ /** agentpipe's own word for it (`nothing_to_do`, `ready_to_merge`…; null: it didn't say). */
12712
+ said: () => said,
12713
+ /** Its `run.end` came: anything after is a ship loop's (`address --ship`). */
12714
+ runEnded: () => runEnded,
12715
+ /** What `scout --track` filed (refs, in order), and the numbers behind how it ended (`run.end`'s counts). */
12716
+ filed: () => [...filed],
12717
+ counts: () => counts,
12059
12718
  flush: () => flush()
12060
12719
  };
12061
12720
  }
@@ -12135,13 +12794,43 @@ function agentpipeEnv(env, monobanBin) {
12135
12794
  if (monobanBin) kept.MONOBAN_BIN = monobanBin;
12136
12795
  return kept;
12137
12796
  }
12797
+ /**
12798
+ * One agentpipe command (`run`, and the loops' recipes' `review`, `ship`, `address`, `merge`, `scout`…): in its own
12799
+ * process group, with only the environment it needs (agentpipeEnv), each `--json` event line it prints given to
12800
+ * `map` (its plain lines skipped), its stderr's last line kept to say why it stopped. `stop()` and `interrupt()`
12801
+ * end it from outside; `agentpipe cancel <run id>` is the polite way, once there is one.
12802
+ */
12803
+ function agentpipeCommand({ command = "agentpipe", args, cwd, env, monobanBin = null, map, spawn = defaultSpawn, graceMs }) {
12804
+ return startProcess({
12805
+ command,
12806
+ args,
12807
+ cwd,
12808
+ env: agentpipeEnv(env, monobanBin),
12809
+ spawn,
12810
+ ...graceMs !== void 0 && { graceMs },
12811
+ onLine: (line) => {
12812
+ const event = parseLine(line);
12813
+ if (event) map(event);
12814
+ }
12815
+ });
12816
+ }
12817
+ /** Runs a short agentpipe command (`cancel`) to its end, whatever it says. */
12138
12818
  const exec = (command, args, env) => new Promise((resolve) => execFile(command, args, {
12139
12819
  timeout: 3e4,
12140
12820
  env
12141
12821
  }, () => resolve()));
12142
- /** Stderr's last lines, to say why agentpipe stopped without saying so itself. */
12143
- const TAIL$1 = 20;
12144
- function agentpipe({ command = "agentpipe", args = [], spawn: spawn$1 = spawn, execCommand = exec, env: runnerEnv = process.env, monobanBin = null, budgetUsd = 10 } = {}) {
12822
+ /**
12823
+ * `agentpipe ledger sync <folder>`: asks GitHub what became of the pull requests its runs opened there (read-only),
12824
+ * and a merged one's task goes to Done (agentpipe calls this monoban back). No model, no cost; whatever it says.
12825
+ */
12826
+ function ledgerSync(deps, workdir) {
12827
+ return (deps.execCommand ?? exec)(deps.command, [
12828
+ "ledger",
12829
+ "sync",
12830
+ workdir
12831
+ ], agentpipeEnv(deps.env, deps.monobanBin));
12832
+ }
12833
+ function agentpipe({ command = "agentpipe", args = [], spawn = defaultSpawn, execCommand = exec, env: runnerEnv = process.env, monobanBin = null, budgetUsd = 10 } = {}) {
12145
12834
  const env = agentpipeEnv(runnerEnv, monobanBin);
12146
12835
  return {
12147
12836
  name: "agentpipe",
@@ -12154,50 +12843,28 @@ function agentpipe({ command = "agentpipe", args = [], spawn: spawn$1 = spawn, e
12154
12843
  report.update(u);
12155
12844
  }
12156
12845
  });
12157
- const tail = [];
12158
- let child;
12846
+ const started = agentpipeCommand({
12847
+ command,
12848
+ args: [...agentpipeArgs(run, budgetUsd), ...args],
12849
+ cwd: run.workdir,
12850
+ env: runnerEnv,
12851
+ monobanBin,
12852
+ map: feed.take,
12853
+ spawn
12854
+ });
12159
12855
  return {
12160
- done: new Promise((resolve) => {
12161
- try {
12162
- child = spawn$1(command, [...agentpipeArgs(run, budgetUsd), ...args], {
12163
- cwd: run.workdir,
12164
- env,
12165
- detached: true
12166
- });
12167
- } catch (err) {
12168
- resolve({
12169
- status: "failed",
12170
- reason: `Couldn't start ${command}: ${err.message}`
12171
- });
12172
- return;
12173
- }
12174
- let spawnError = null;
12175
- child.on("error", (err) => {
12176
- spawnError = err.code === "ENOENT" ? `${command} isn't installed here (or isn't on the runner's PATH).` : `${command} failed: ${err.message}`;
12177
- });
12178
- if (child.stdout) createInterface$1({ input: child.stdout }).on("line", (line) => {
12179
- const event = parseLine(line);
12180
- if (event) feed.take(event);
12181
- });
12182
- if (child.stderr) createInterface$1({ input: child.stderr }).on("line", (line) => {
12183
- if (!line.trim()) return;
12184
- tail.push(line.trim());
12185
- if (tail.length > TAIL$1) tail.shift();
12186
- });
12187
- child.on("close", (code) => {
12188
- feed.flush();
12189
- const said = feed.ending();
12190
- if (said) return resolve(said);
12191
- if (spawnError) return resolve({
12192
- status: "failed",
12193
- reason: spawnError
12194
- });
12195
- const last = tail.at(-1);
12196
- resolve({
12197
- status: "failed",
12198
- reason: `${command} stopped (exit code ${code ?? "none"}) without saying how it ended${last ? `: ${last}` : "."}`
12199
- });
12200
- });
12856
+ done: started.done.then(({ code, spawnError, lastError }) => {
12857
+ feed.flush();
12858
+ const said = feed.ending();
12859
+ if (said) return said;
12860
+ if (spawnError) return {
12861
+ status: "failed",
12862
+ reason: spawnError
12863
+ };
12864
+ return {
12865
+ status: "failed",
12866
+ reason: `${command} stopped (exit code ${code ?? "none"}) without saying how it ended${lastError ? `: ${lastError}` : "."}`
12867
+ };
12201
12868
  }),
12202
12869
  cancel: async () => {
12203
12870
  if (externalId) await execCommand(command, [
@@ -12206,12 +12873,65 @@ function agentpipe({ command = "agentpipe", args = [], spawn: spawn$1 = spawn, e
12206
12873
  "--reason",
12207
12874
  "Cancelled from monoban"
12208
12875
  ], env);
12209
- else child?.kill("SIGINT");
12876
+ else started.interrupt();
12210
12877
  }
12211
12878
  };
12212
12879
  }
12213
12880
  };
12214
12881
  }
12882
+ /** What each loop's recipe needs of agentpipe: its commands and their flags (docs/PLAN-AGENT-LOOPS.md §1.6). */
12883
+ const RECIPE_NEEDS = {
12884
+ deliver: [
12885
+ "run.json",
12886
+ "run.dry_run_json",
12887
+ "run.fresh_base",
12888
+ "review.json",
12889
+ "ship.json",
12890
+ "address.json",
12891
+ "address.no_merge",
12892
+ "merge.json",
12893
+ "merge.expect_run"
12894
+ ],
12895
+ scavenge: [
12896
+ "scout.json",
12897
+ "scout.track",
12898
+ "run.dry_run_json"
12899
+ ]
12900
+ };
12901
+ /** The recipes an agentpipe can run, from what it says it has. */
12902
+ function recipesOf(capabilities) {
12903
+ const has = (need) => {
12904
+ const [command = "", flag = ""] = need.split(".");
12905
+ return capabilities?.commands?.[command]?.[flag] === true;
12906
+ };
12907
+ return RECIPE_NAMES.filter((recipe) => RECIPE_NEEDS[recipe].every(has));
12908
+ }
12909
+ /**
12910
+ * Asks agentpipe what it can do (`capabilities --json`: it spends nothing and needs no repository; given a folder,
12911
+ * its tiers are that repository's too). Null when it can't say: an agentpipe before the command (AGE-127), or one
12912
+ * that doesn't answer.
12913
+ */
12914
+ function agentpipeCapabilities(command, env, folder) {
12915
+ return new Promise((resolve) => {
12916
+ execFile(command, [
12917
+ "capabilities",
12918
+ ...folder ? [folder] : [],
12919
+ "--json"
12920
+ ], {
12921
+ timeout: 15e3,
12922
+ env: agentpipeEnv(env, null),
12923
+ maxBuffer: 1048576
12924
+ }, (err, stdout) => {
12925
+ if (err) return resolve(null);
12926
+ try {
12927
+ const parsed = JSON.parse(stdout);
12928
+ resolve(parsed && typeof parsed === "object" ? parsed : null);
12929
+ } catch {
12930
+ resolve(null);
12931
+ }
12932
+ });
12933
+ });
12934
+ }
12215
12935
  // src/board.ts
12216
12936
  /** Every project you have, in sidebar order. */
12217
12937
  async function allProjects$1(api) {
@@ -12424,7 +13144,7 @@ const strategies = {
12424
13144
  variadic: strategyVariadic,
12425
13145
  monadic: strategyMonadic
12426
13146
  };
12427
- // ../../node_modules/.pnpm/use-intl@4.14.9_@types+react@19.3.0_react@19.3.1/node_modules/use-intl/dist/esm/production/formatters-CJcico0N.js
13147
+ // ../../node_modules/.pnpm/use-intl@4.14.10_@types+react@19.3.0_react@19.3.1/node_modules/use-intl/dist/esm/production/formatters-CJcico0N.js
12428
13148
  var a = class extends Error {
12429
13149
  constructor(e, t) {
12430
13150
  let a = e;
@@ -16360,7 +17080,7 @@ var IntlMessageFormat = class IntlMessageFormat {
16360
17080
  };
16361
17081
  }
16362
17082
  };
16363
- // ../../node_modules/.pnpm/use-intl@4.14.9_@types+react@19.3.0_react@19.3.1/node_modules/use-intl/dist/esm/production/format-message/index.js
17083
+ // ../../node_modules/.pnpm/use-intl@4.14.10_@types+react@19.3.0_react@19.3.1/node_modules/use-intl/dist/esm/production/format-message/index.js
16364
17084
  var import_react = require_react();
16365
17085
  function m$1(...[m, s, i, n]) {
16366
17086
  if (Array.isArray(s)) throw new a(r.INVALID_MESSAGE, void 0);
@@ -16419,7 +17139,7 @@ function m$1(...[m, s, i, n]) {
16419
17139
  return (0, import_react.isValidElement)(w) || Array.isArray(w) || "string" == typeof w ? w : String(w);
16420
17140
  }
16421
17141
  m$1.raw = !0;
16422
- // ../../node_modules/.pnpm/use-intl@4.14.9_@types+react@19.3.0_react@19.3.1/node_modules/use-intl/dist/esm/production/initializeConfig-CHgjheii.js
17142
+ // ../../node_modules/.pnpm/use-intl@4.14.10_@types+react@19.3.0_react@19.3.1/node_modules/use-intl/dist/esm/production/initializeConfig-CHgjheii.js
16423
17143
  function c(...e) {
16424
17144
  return e.filter(Boolean).join(".");
16425
17145
  }
@@ -16536,7 +17256,7 @@ function f(a$1) {
16536
17256
  function l(e, t) {
16537
17257
  return e === t ? void 0 : e.slice((t + ".").length);
16538
17258
  }
16539
- // ../../node_modules/.pnpm/use-intl@4.14.9_@types+react@19.3.0_react@19.3.1/node_modules/use-intl/dist/esm/production/core.js
17259
+ // ../../node_modules/.pnpm/use-intl@4.14.10_@types+react@19.3.0_react@19.3.1/node_modules/use-intl/dist/esm/production/core.js
16540
17260
  function n({ _cache: a = s(), _formatters: i$2 = l$1(a), getMessageFallback: n = i, messages: c, namespace: f$1, onError: g = u, ...l$2 }) {
16541
17261
  return function({ messages: e, namespace: a, ...r }, o) {
16542
17262
  return e = e[o], a = l(a, o), f({
@@ -16787,10 +17507,12 @@ var en_US_default = {
16787
17507
  "label": "Project views",
16788
17508
  "board": "board",
16789
17509
  "notes": "notes.md",
17510
+ "loops": "loops",
16790
17511
  "archive": "archive"
16791
17512
  },
16792
17513
  status: {
16793
17514
  "notes": "notes.md",
17515
+ "loops": "loops · {count}",
16794
17516
  "archiveTask": "{ref} · archive",
16795
17517
  "archive": "archive · {count}",
16796
17518
  "task": "{ref} · {column}",
@@ -16945,7 +17667,8 @@ var en_US_default = {
16945
17667
  "view": "view",
16946
17668
  "account": "account",
16947
17669
  "goTo": "go to",
16948
- "projectList": "project list"
17670
+ "projectList": "project list",
17671
+ "loop": "loop"
16949
17672
  },
16950
17673
  unavailable: "{command}: {needs}.",
16951
17674
  palette: {
@@ -17233,6 +17956,10 @@ var en_US_default = {
17233
17956
  "label": "Notes of {project}",
17234
17957
  "keywords": "notes scratch memo text"
17235
17958
  },
17959
+ "loops": {
17960
+ "label": "Loops of {project}",
17961
+ "keywords": "loops agents automation schedule deliver scavenge runner"
17962
+ },
17236
17963
  "archive": {
17237
17964
  "label": "Archive of {project}: done and won't-do tasks",
17238
17965
  "keywords": "archive archived old done wont history unarchive"
@@ -17278,6 +18005,46 @@ var en_US_default = {
17278
18005
  "showWeek": { "label": "Show the next 7 days" },
17279
18006
  "pickDay": { "label": "Show another day…" }
17280
18007
  },
18008
+ loops: {
18009
+ "down": { "label": "Next loop" },
18010
+ "up": { "label": "Previous loop" },
18011
+ "open": {
18012
+ "label": "Open {name}",
18013
+ "help": "Open loop"
18014
+ },
18015
+ "back": { "label": "Back to the loops" },
18016
+ "runDown": { "label": "Next run" },
18017
+ "runUp": { "label": "Previous run" },
18018
+ "new": {
18019
+ "label": "New loop in {project}",
18020
+ "keywords": "loop create add agent schedule"
18021
+ },
18022
+ "edit": {
18023
+ "label": "Edit {name}",
18024
+ "help": "Edit loop"
18025
+ },
18026
+ "pause": {
18027
+ "label": "Pause {name}",
18028
+ "help": "Pause loop"
18029
+ },
18030
+ "resume": {
18031
+ "label": "Resume {name}",
18032
+ "help": "Resume loop"
18033
+ },
18034
+ "runNow": {
18035
+ "label": "Run {name} now",
18036
+ "help": "Run loop now"
18037
+ },
18038
+ "continue": {
18039
+ "label": "Continue {ref}'s pull request from {step}",
18040
+ "help": "Continue a run's pull request",
18041
+ "keywords": "continue resume retry pull request merge checks feedback"
18042
+ },
18043
+ "delete": {
18044
+ "label": "Delete {name}",
18045
+ "help": "Delete loop"
18046
+ }
18047
+ },
17281
18048
  archive: {
17282
18049
  "down": { "label": "Next archived task" },
17283
18050
  "up": { "label": "Previous archived task" },
@@ -17327,6 +18094,153 @@ var en_US_default = {
17327
18094
  "attach": "Attach"
17328
18095
  }
17329
18096
  },
18097
+ loops: {
18098
+ label: "Loops",
18099
+ recipe: {
18100
+ "deliver": "deliver",
18101
+ "scavenge": "scavenge"
18102
+ },
18103
+ empty: "No loops in {project} yet. A loop runs an agent on your runner, on a schedule: it takes tasks and delivers them as merged pull requests, or finds problems and files them as tasks.",
18104
+ loading: "loading loops…",
18105
+ loadFailed: "Couldn't load the loops.",
18106
+ tryAgain: "Try again",
18107
+ heading: {
18108
+ "name": "loop",
18109
+ "type": "type",
18110
+ "state": "state",
18111
+ "now": "now",
18112
+ "day": "24 h"
18113
+ },
18114
+ now: "{step} · {ref}",
18115
+ starting: "starting",
18116
+ day: "{runs, plural, one {# run} other {# runs}} · {cost}",
18117
+ row: "{name}, {type}: {state}",
18118
+ detail: {
18119
+ "label": "{name}: its steps and runs",
18120
+ "back": "All loops",
18121
+ "on": "{type} on {runner}",
18122
+ "steps": "Steps",
18123
+ "stepState": {
18124
+ "done": "done",
18125
+ "current": "now",
18126
+ "next": "to come",
18127
+ "skipped": "skipped"
18128
+ },
18129
+ "now": "now",
18130
+ "task": "task",
18131
+ "pr": "PR",
18132
+ "hold": "{going, select, yes {Stops before merge} other {Stopped before merge}}: {why, select, mergeOff {merge is off for this loop} queuedOutside {its task was queued outside the browser} other {its text was changed outside the browser after you queued it}}.",
18133
+ "waiting": "Waiting for you",
18134
+ "waits": "<pr>{ref}'s pull request</pr> is ready for you to merge: {why, select, mergeOff {merge is off for this loop} queuedOutside {its task was queued outside the browser} other {its text was changed outside the browser after you queued it}}.",
18135
+ "waitsOpen": "<pr>{ref}'s pull request</pr> waits for you.",
18136
+ "continue": "Continue {ref}'s pull request",
18137
+ "continueHint": "A run picks it up from the step you choose, at the runner's next check-in.{merges, select, yes { Continued from here, it may merge on its own.} other {}}"
18138
+ },
18139
+ runs: {
18140
+ "heading": "Runs",
18141
+ "label": "Runs of {name}",
18142
+ "when": "started",
18143
+ "task": "task",
18144
+ "result": "result",
18145
+ "took": "took",
18146
+ "cost": "cost",
18147
+ "noTask": "no task",
18148
+ "row": "{date}, {task}: {result}",
18149
+ "none": "No runs yet.",
18150
+ "loading": "loading its runs…"
18151
+ },
18152
+ dialog: {
18153
+ "newTitle": "New loop in {project}",
18154
+ "editTitle": "Edit {name}",
18155
+ "description": "A loop runs an agent on your runner, through agentpipe, again and again. It starts at its runner's next check-in.",
18156
+ "name": "Name",
18157
+ "namePlaceholder": "Ship the To do column",
18158
+ "type": "Type",
18159
+ "recipeHint": {
18160
+ "deliver": "Takes tasks from a column, one at a time, and delivers each as a pull request.",
18161
+ "scavenge": "Looks for problems in the code and files them as tasks."
18162
+ },
18163
+ "typeFixed": "A loop's type can't change.",
18164
+ "runner": "Runner",
18165
+ "folder": "Folder",
18166
+ "folderHint": "A checkout of the project's repository, on the runner's machine.",
18167
+ "every": "Every",
18168
+ "interval": "{unit, select, seconds {{n, plural, one {# second} other {# seconds}}} minutes {{n, plural, one {# minute} other {# minutes}}} hours {{n, plural, one {# hour} other {# hours}}} days {{n, plural, one {# day} other {# days}}} other {{n, plural, one {# week} other {# weeks}}}}",
18169
+ "takesFrom": "Takes tasks from",
18170
+ "onlyTagged": "Only tasks tagged",
18171
+ "anyTag": "any tag: every task in the column",
18172
+ "merge": "Merge each pull request when its checks pass",
18173
+ "mergeHint": "Only the tasks you queued from the browser. The others wait for you to merge.",
18174
+ "deliverMaxOpen": "Pull requests that may wait for you",
18175
+ "checksMinutes": "Wait for checks (minutes)",
18176
+ "reviewTier": "Review on",
18177
+ "reviewTierHint": "The models agentpipe reviews the pull request with: its tier (--tier).",
18178
+ "reviewTierDefault": "agentpipe's own tier",
18179
+ "focus": "What to look for",
18180
+ "focusPlaceholder": "Tests that fail now and then, and why",
18181
+ "filesIn": "Files tasks in",
18182
+ "tagsWith": "Tags them",
18183
+ "pickTag": "pick a tag",
18184
+ "scavengeMaxOpen": "Its open tasks, at most",
18185
+ "limits": "How much it may do",
18186
+ "perDay": "Runs a day",
18187
+ "budgetUsd": "Budget per run (US$)",
18188
+ "budgetUsdPerDay": "Budget per day (US$)",
18189
+ "pauseAfter": "Pause after runs in a row",
18190
+ "summary": {
18191
+ "deliver": "Every {interval}, on {runner}, it takes {tagged, select, yes {the tasks tagged #{tag} in {column}} other {every task in {column}}}, one at a time, up to {perDay} a day, and opens a pull request for each. {merge, select, yes {It merges each one when its checks pass, for the tasks you queued from the browser; the others wait for you to merge.} other {It leaves each one for you to merge.}} It stops taking tasks while {maxOpen, plural, one {# pull request waits} other {# pull requests wait}} for you, spends at most {budget} a run and {budgetDay} a day, and pauses after {pauseAfter, plural, one {a run that fails or needs you} other {# runs in a row that fail or need you}}.",
18192
+ "scavenge": "Every {interval}, on {runner}, it looks for: {focus}. It files what it finds in {column}, tagged #{tag}, and stops filing while {maxOpen, plural, one {# of those tasks is} other {# of those tasks are}} open. It spends at most {budget} a run and {budgetDay} a day, and pauses after {pauseAfter, plural, one {a run that fails or needs you} other {# runs in a row that fail or need you}}.",
18193
+ "incomplete": "Fill in the fields above to see what the loop will do."
18194
+ },
18195
+ "create": "Create loop",
18196
+ "creating": "Creating…",
18197
+ "save": "Save",
18198
+ "saving": "Saving…",
18199
+ "cancel": "Cancel",
18200
+ "couldntSave": "Couldn't save the loop.",
18201
+ "problem": {
18202
+ "required": "Required.",
18203
+ "tooLong": "At most {max} characters.",
18204
+ "runner": "Pick a runner.",
18205
+ "absolute": "An absolute path, like /Users/you/code/project.",
18206
+ "number": "A number.",
18207
+ "whole": "A whole number.",
18208
+ "between": "From {min} to {max}.",
18209
+ "overDay": "No more than the budget per day.",
18210
+ "oneLine": "One line.",
18211
+ "tag": "Pick the tag it puts on what it files.",
18212
+ "nul": "Can't contain NUL characters."
18213
+ },
18214
+ "pauseAfterHint": "That fail or need you."
18215
+ },
18216
+ "delete": {
18217
+ "title": "Delete {name}?",
18218
+ "about": "Its runs stay on their tasks. A run that's queued is cancelled; a run that's going has to end first.",
18219
+ "confirm": "Delete",
18220
+ "deleting": "Deleting…",
18221
+ "cancel": "Cancel",
18222
+ "couldnt": "Couldn't delete the loop."
18223
+ },
18224
+ controls: {
18225
+ "new": "New loop",
18226
+ "runNow": "Run now",
18227
+ "pause": "Pause",
18228
+ "resume": "Resume",
18229
+ "edit": "Edit",
18230
+ "delete": "Delete",
18231
+ "continueFrom": "From {step}"
18232
+ },
18233
+ toast: {
18234
+ "created": "Created {name}.",
18235
+ "saved": "Saved {name}.",
18236
+ "paused": "Paused {name}.",
18237
+ "resumed": "Resumed {name}.",
18238
+ "queued": "{name} runs at its runner's next check-in.",
18239
+ "deleted": "Deleted {name}.",
18240
+ "failed": "That didn't work: try again.",
18241
+ "continued": "{ref} continues from {step} at its runner's next check-in."
18242
+ }
18243
+ },
17330
18244
  notes: {
17331
18245
  find: {
17332
18246
  "label": "Find in notes",
@@ -17511,7 +18425,10 @@ var en_US_default = {
17511
18425
  "startingRun": "Starting a run",
17512
18426
  "loadingRuns": "Loading the runs",
17513
18427
  "deletingAccount": "Deleting your account",
17514
- "changingLanguage": "Changing the language"
18428
+ "changingLanguage": "Changing the language",
18429
+ "loadingLoops": "Loading the loops",
18430
+ "savingLoop": "Saving the loop",
18431
+ "deletingLoop": "Deleting the loop"
17515
18432
  },
17516
18433
  keptNotRemoved: "Could not remove what's kept. Try again.",
17517
18434
  saveState: {
@@ -17545,6 +18462,9 @@ var en_US_default = {
17545
18462
  email_not_confirmed: "Confirm your email first: open the link we sent you, or ask for a new one on the sign-in page.",
17546
18463
  unsupported_email: "monoban doesn't send this kind of email.",
17547
18464
  email_not_sent: "The email couldn't be sent. Try again in a moment.",
18465
+ loops_off: "Agent loops aren't on for your account yet.",
18466
+ nothing_to_do: "No task is waiting for this loop: its column has none it can take.",
18467
+ pr_open: "This task's pull request may still be open: continue it from a step, or close it first.",
17548
18468
  unreachable: "Couldn't reach monoban. Try again.",
17549
18469
  unreachableShort: "Couldn't reach monoban.",
17550
18470
  cantDeleteAccount: "Couldn't delete your account. Try again."
@@ -17752,6 +18672,7 @@ var en_US_default = {
17752
18672
  "queuedOffline": "{runner} is offline: it starts once <code>monoban runner</code> runs there.",
17753
18673
  "steps": "Steps",
17754
18674
  "stepsHeading": "steps",
18675
+ "innerSteps": "{step}'s steps",
17755
18676
  "noneYet": "none yet",
17756
18677
  "none": "none",
17757
18678
  "now": "now",
@@ -17909,6 +18830,33 @@ var en_US_default = {
17909
18830
  "thousandTokens": "{n}k tokens",
17910
18831
  "millionTokens": "{n}M tokens"
17911
18832
  },
18833
+ loop: {
18834
+ "state": {
18835
+ "paused": {
18836
+ "you": "paused",
18837
+ "failures": "paused: its last runs failed or needed you",
18838
+ "unstartable": "paused: a run couldn't start"
18839
+ },
18840
+ "noRunner": "no runner: choose one",
18841
+ "runnerOffline": "{runner} is offline",
18842
+ "runnerOutdated": "{runner} can't run it: update agentpipe there",
18843
+ "running": "running",
18844
+ "waitingForYou": {
18845
+ "pullRequests": "{count, plural, one {a pull request waits for you} other {# pull requests wait for you}}",
18846
+ "tasks": "{count, plural, one {a task it filed waits for you} other {# tasks it filed wait for you}}"
18847
+ },
18848
+ "dailyLimit": "{count, plural, one {# run} other {# runs}} in 24 hours: its daily limit",
18849
+ "budget": "{spent} of {limit} spent in 24 hours: its daily budget",
18850
+ "waitingForTask": "waiting for a task",
18851
+ "due": "starting",
18852
+ "next": "next at {time}"
18853
+ },
18854
+ "hold": {
18855
+ "mergeOff": "merge is off for this loop",
18856
+ "queuedOutside": "its task was queued outside the browser",
18857
+ "textChanged": "its text was changed outside the browser after you queued it"
18858
+ }
18859
+ },
17912
18860
  history: {
17913
18861
  "verb": {
17914
18862
  "created": "created",
@@ -18002,7 +18950,9 @@ var en_US_default = {
18002
18950
  "wide": "wide",
18003
18951
  "tags": "tags",
18004
18952
  "link": "link",
18005
- "move": "move"
18953
+ "move": "move",
18954
+ "nextRun": "next run",
18955
+ "back": "back"
18006
18956
  },
18007
18957
  "backOnline": "online again"
18008
18958
  },
@@ -18039,6 +18989,7 @@ var en_US_default = {
18039
18989
  "switchProject": "switch project",
18040
18990
  "open": "open",
18041
18991
  "views": "notes · archive · board",
18992
+ "viewsWithLoops": "notes · loops · archive · board",
18042
18993
  "commands": "commands",
18043
18994
  "everything": "everything"
18044
18995
  }
@@ -18049,6 +19000,7 @@ var en_US_default = {
18049
19000
  "location": "Location",
18050
19001
  "today": "today",
18051
19002
  "notes": "notes.md",
19003
+ "loops": "loops",
18052
19004
  "board": "board",
18053
19005
  "search": "› search tasks or run a command…",
18054
19006
  "account": "Account and settings",
@@ -18746,6 +19698,48 @@ function formatCost(usd, { locale }) {
18746
19698
  maximumFractionDigits: digits
18747
19699
  }).format(usd);
18748
19700
  }
19701
+ // ../../packages/i18n/src/loops.ts
19702
+ const DAY_MS = 864e5;
19703
+ /**
19704
+ * A loop's state in a few words (contract's `loopState`): "paused", "mbp is offline", "a pull request waits for
19705
+ * you", "next at 14:05". A start more than a day away says its day too ("next at Fri 09:00"). `now`: the
19706
+ * clock it's said against, for that. The time is in the reader's own time zone (the browser's, the terminal's),
19707
+ * so this is for the web and the CLI, never an email (those say UTC: `momentFormat`).
19708
+ */
19709
+ function describeLoopState({ state, nextAt, why }, words, now = Date.now()) {
19710
+ const { t, locale } = words;
19711
+ const count = why.count ?? 0;
19712
+ switch (state) {
19713
+ case "paused": return t(`loop.state.paused.${why.reason ?? "you"}`);
19714
+ case "noRunner":
19715
+ case "running":
19716
+ case "waitingForTask":
19717
+ case "due": return t(`loop.state.${state}`);
19718
+ case "runnerOffline":
19719
+ case "runnerOutdated": return t(`loop.state.${state}`, { runner: why.runner ?? "" });
19720
+ case "waitingForYou": return t(`loop.state.waitingForYou.${why.of ?? "pullRequests"}`, { count });
19721
+ case "dailyLimit": return t("loop.state.dailyLimit", { count });
19722
+ case "budget": return t("loop.state.budget", {
19723
+ spent: formatCost(why.spent ?? 0, words),
19724
+ limit: formatCost(why.limit ?? 0, words)
19725
+ });
19726
+ case "next": {
19727
+ const at = nextAt ? Date.parse(nextAt) : now;
19728
+ return t("loop.state.next", { time: new Intl.DateTimeFormat(locale, {
19729
+ ...at - now >= DAY_MS && { weekday: "short" },
19730
+ hour: "2-digit",
19731
+ minute: "2-digit"
19732
+ }).format(at) });
19733
+ }
19734
+ }
19735
+ }
19736
+ /**
19737
+ * Why a deliver run won't merge on its own (contract's `mergeHoldOf`, plan §1.12), in a few words: "its task was
19738
+ * queued outside the browser". The loops tab says the same in its own sentences (loops.json `detail.waits`).
19739
+ */
19740
+ function describeMergeHold(hold, { t }) {
19741
+ return t(`loop.hold.${hold}`);
19742
+ }
18749
19743
  // src/commands/comments.ts
18750
19744
  /** `monoban comment MON-12 TEXT…`: a comment on the task (`-` reads it from stdin, Markdown and all). */
18751
19745
  async function comment(ctx, ref, words, options) {
@@ -18974,15 +19968,15 @@ async function projects(ctx, options) {
18974
19968
  const { bold, dim } = ctx.style;
18975
19969
  const keyWidth = Math.max(...all.map((p) => p.key.length));
18976
19970
  const nameWidth = Math.max(...all.map((p) => [...p.name].length));
18977
- const countWidth = Math.max(...all.map((p) => tasks(p).length));
19971
+ const countWidth = Math.max(...all.map((p) => tasks$1(p).length));
18978
19972
  for (const p of all) {
18979
19973
  const mark = here ? p.key === here ? "* " : " " : "";
18980
19974
  const name = `${p.name}${" ".repeat(nameWidth - [...p.name].length)}`;
18981
- const line = `${mark}${bold(p.key.padEnd(keyWidth))} ${name} ${dim(tasks(p).padEnd(countWidth))} ${dim(p.repo ?? "")}`;
19975
+ const line = `${mark}${bold(p.key.padEnd(keyWidth))} ${name} ${dim(tasks$1(p).padEnd(countWidth))} ${dim(p.repo ?? "")}`;
18982
19976
  ctx.out(line.trimEnd());
18983
19977
  }
18984
19978
  }
18985
- const tasks = (p) => `${p.taskCount} ${p.taskCount === 1 ? "task" : "tasks"}`;
19979
+ const tasks$1 = (p) => `${p.taskCount} ${p.taskCount === 1 ? "task" : "tasks"}`;
18986
19980
  /**
18987
19981
  * `monoban list [COLUMN…]`: the board, by column (every column, or the ones named); `--tag` keeps a tag's
18988
19982
  * tasks. `--archived`: the archived ones instead (done a while ago, or won't do: with why).
@@ -19398,7 +20392,7 @@ async function edit(ctx, ref, options) {
19398
20392
  ctx.out(`Updated ${task.ref}.`);
19399
20393
  }
19400
20394
  /** `monoban rm MON-12`: asks first, unless -y. */
19401
- async function rm$1(ctx, ref, options) {
20395
+ async function rm(ctx, ref, options) {
19402
20396
  const api = apis(ctx).signedIn;
19403
20397
  const task = await taskByRef(api, ref, ctx);
19404
20398
  if (!options.yes) {
@@ -19420,7 +20414,7 @@ async function rm$1(ctx, ref, options) {
19420
20414
  ctx.out(`Deleted ${task.ref}.`);
19421
20415
  }
19422
20416
  /** `monoban open [MON-12]`: the task, or the board, in the browser (and the link on stdout). */
19423
- async function open$1(ctx, ref, options) {
20417
+ async function open(ctx, ref, options) {
19424
20418
  let url;
19425
20419
  if (ref) {
19426
20420
  const { key, number } = taskRefOf(ref);
@@ -19686,92 +20680,6 @@ async function start(ctx, ref, options) {
19686
20680
  }
19687
20681
  for (const line of lines) ctx.out(line);
19688
20682
  }
19689
- // src/runner/process.ts
19690
- const defaultSpawn = spawn;
19691
- const TAIL = 20;
19692
- function startProcess({ command, args, cwd, env, stdin, onLine, spawn = defaultSpawn, graceMs = 1e4 }) {
19693
- let child;
19694
- let exited = false;
19695
- const timers = [];
19696
- const signal = (sig) => {
19697
- if (!child || exited) return;
19698
- try {
19699
- if (child.pid) process.kill(-child.pid, sig);
19700
- else child.kill(sig);
19701
- } catch {
19702
- child.kill(sig);
19703
- }
19704
- };
19705
- return {
19706
- done: new Promise((resolve) => {
19707
- try {
19708
- child = spawn(command, args, {
19709
- cwd,
19710
- env,
19711
- detached: true
19712
- });
19713
- } catch (err) {
19714
- resolve({
19715
- code: null,
19716
- spawnError: `Couldn't start ${command}: ${err.message}`,
19717
- lastError: null
19718
- });
19719
- return;
19720
- }
19721
- let spawnError = null;
19722
- const tail = [];
19723
- child.on("error", (err) => {
19724
- spawnError = err.code === "ENOENT" ? `${command} isn't installed here (or isn't on the runner's PATH).` : `${command} failed: ${err.message}`;
19725
- });
19726
- if (child.stdin) {
19727
- child.stdin.on("error", () => {});
19728
- child.stdin.end(stdin ?? "");
19729
- }
19730
- if (child.stdout) createInterface$1({ input: child.stdout }).on("line", onLine);
19731
- if (child.stderr) createInterface$1({ input: child.stderr }).on("line", (line) => {
19732
- if (!line.trim()) return;
19733
- tail.push(line.trim());
19734
- if (tail.length > TAIL) tail.shift();
19735
- });
19736
- child.on("close", (code) => {
19737
- exited = true;
19738
- for (const t of timers) clearTimeout(t);
19739
- resolve({
19740
- code,
19741
- spawnError,
19742
- lastError: tail.at(-1) ?? null
19743
- });
19744
- });
19745
- }),
19746
- stop: () => {
19747
- signal("SIGINT");
19748
- timers.push(setTimeout(() => signal("SIGTERM"), graceMs));
19749
- timers.push(setTimeout(() => signal("SIGKILL"), graceMs * 2));
19750
- }
19751
- };
19752
- }
19753
- /** The first version number a command prints for `--version` ("2.1.300 (Claude Code)" → 2.1.300), or null. */
19754
- function versionOf(command, env = process.env) {
19755
- return new Promise((resolve) => {
19756
- execFile(command, ["--version"], {
19757
- timeout: 15e3,
19758
- env
19759
- }, (err, stdout, stderr) => {
19760
- if (err) return resolve(null);
19761
- resolve(/\d+\.\d+(?:\.\d+)?(?:[-+][0-9A-Za-z.-]+)?/.exec(`${stdout} ${stderr}`)?.[0] ?? null);
19762
- });
19763
- });
19764
- }
19765
- /** Whether version `a` is at least `b` (numbers only: 2.1.259). */
19766
- function atLeast(a, b) {
19767
- const parts = (v) => v.split(/[-+]/)[0]?.split(".").map(Number) ?? [];
19768
- const [x, y] = [parts(a), parts(b)];
19769
- for (let i = 0; i < Math.max(x.length, y.length); i++) {
19770
- const d = (x[i] ?? 0) - (y[i] ?? 0);
19771
- if (d) return d > 0;
19772
- }
19773
- return true;
19774
- }
19775
20683
  // src/runner/prompt.ts
19776
20684
  /** The JSON Schema the agent's last message follows (strict, as Codex's --output-schema needs). */
19777
20685
  const OUTCOME_SCHEMA = {
@@ -19847,6 +20755,109 @@ function buildPrompt({ task, comments, branch }) {
19847
20755
  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 \"\"}.");
19848
20756
  return lines.join("\n");
19849
20757
  }
20758
+ // src/runner/redact.ts
20759
+ /**
20760
+ * What the runner sends the board from an agent's output, secrets out: a command line, an error, a step's message.
20761
+ * Every message a run reports goes through `clip()` (docs/PLAN-AGENT-LOOPS.md §1.6: agentpipe's too).
20762
+ */
20763
+ /** Secrets a command line or an error might carry, kept out of what the board shows. */
20764
+ const SECRETS = [
20765
+ [/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/g, "…"],
20766
+ [/\bsk-[A-Za-z0-9_-]{16,}/g, "…"],
20767
+ [/\bmbn_[A-Za-z0-9_]{8,}/g, "…"],
20768
+ [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, "…"],
20769
+ [/\bAKIA[0-9A-Z]{16}\b/g, "…"],
20770
+ [/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1…"],
20771
+ [/((?:token|secret|passw(?:or)?d|api[_-]?key|auth)[A-Za-z_]*["']?\s*[=:]\s*["']?)(?!Bearer\b|Basic\b)[^\s"']+/gi, "$1…"]
20772
+ ];
20773
+ function redact(text) {
20774
+ return SECRETS.reduce((t, [pattern, by]) => t.replace(pattern, by), text);
20775
+ }
20776
+ /** A message the API takes (and the board shows), secrets out. */
20777
+ function clip(text, max = 2e3) {
20778
+ const clean = redact(text).trim();
20779
+ return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;
20780
+ }
20781
+ // src/runner/steps.ts
20782
+ const ok = (value, data) => ({
20783
+ status: "ok",
20784
+ ...value !== void 0 && { value },
20785
+ ...data && { data }
20786
+ });
20787
+ const skipped = (message, data) => ({
20788
+ status: "skipped",
20789
+ message,
20790
+ ...data && { data }
20791
+ });
20792
+ const failed = (message, value, data) => ({
20793
+ status: "failed",
20794
+ message,
20795
+ ...value !== void 0 && { value },
20796
+ ...data && { data }
20797
+ });
20798
+ function steps(report, isCancelled = () => false) {
20799
+ const attempts = /* @__PURE__ */ new Map();
20800
+ let stoppedBy = null;
20801
+ /**
20802
+ * Runs step `name`: unless the run was cancelled or an earlier step stopped it (`always` runs it anyway). A step
20803
+ * that throws finishes `failed`, saying why, and the error goes on to the caller.
20804
+ */
20805
+ async function step(name, fn, { always = false } = {}) {
20806
+ if (!always && isCancelled()) return {
20807
+ ran: false,
20808
+ why: "cancelled"
20809
+ };
20810
+ if (!always && stoppedBy) return {
20811
+ ran: false,
20812
+ why: "stopped"
20813
+ };
20814
+ const attempt = (attempts.get(name) ?? 0) + 1;
20815
+ attempts.set(name, attempt);
20816
+ const started = Date.now();
20817
+ report.event({
20818
+ kind: "step_started",
20819
+ step: name,
20820
+ attempt,
20821
+ status: "running"
20822
+ });
20823
+ const finish = ({ status, message, data }) => {
20824
+ if (status !== "ok" && status !== "skipped") stoppedBy ??= name;
20825
+ report.event({
20826
+ kind: "step_finished",
20827
+ step: name,
20828
+ attempt,
20829
+ status,
20830
+ ...message && { message: clip(message) },
20831
+ data: {
20832
+ durationMs: Date.now() - started,
20833
+ ...data
20834
+ }
20835
+ });
20836
+ };
20837
+ let end;
20838
+ try {
20839
+ end = await fn();
20840
+ } catch (err) {
20841
+ finish({
20842
+ status: "failed",
20843
+ message: err.message
20844
+ });
20845
+ throw err;
20846
+ }
20847
+ finish(end);
20848
+ return {
20849
+ ran: true,
20850
+ status: end.status,
20851
+ message: end.message ?? null,
20852
+ value: end.value
20853
+ };
20854
+ }
20855
+ return {
20856
+ step,
20857
+ /** The step that stopped the run, if one did. */
20858
+ stoppedBy: () => stoppedBy
20859
+ };
20860
+ }
19850
20861
  // src/runner/workspace.ts
19851
20862
  var WorkspaceError = class extends Error {};
19852
20863
  /** Runs a command in `cwd`: its stdout, or a WorkspaceError with what it said on stderr. */
@@ -19946,24 +20957,6 @@ function workspace(cwd, env = process.env) {
19946
20957
  };
19947
20958
  }
19948
20959
  // src/runner/agents/coding.ts
19949
- /** Secrets a command line or an error might carry, kept out of what the board shows. */
19950
- const SECRETS = [
19951
- [/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})/g, "…"],
19952
- [/\bsk-[A-Za-z0-9_-]{16,}/g, "…"],
19953
- [/\bmbn_[A-Za-z0-9_]{8,}/g, "…"],
19954
- [/\bxox[abprs]-[A-Za-z0-9-]{10,}/g, "…"],
19955
- [/\bAKIA[0-9A-Z]{16}\b/g, "…"],
19956
- [/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi, "$1…"],
19957
- [/((?:token|secret|passw(?:or)?d|api[_-]?key|auth)[A-Za-z_]*["']?\s*[=:]\s*["']?)(?!Bearer\b|Basic\b)[^\s"']+/gi, "$1…"]
19958
- ];
19959
- function redact(text) {
19960
- return SECRETS.reduce((t, [pattern, by]) => t.replace(pattern, by), text);
19961
- }
19962
- /** A message the API takes (and the board shows), secrets out. */
19963
- function clip(text, max = 2e3) {
19964
- const clean = redact(text).trim();
19965
- return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;
19966
- }
19967
20960
  /** A command's first line ("pnpm test"), for "$ pnpm test". */
19968
20961
  function firstLine(command) {
19969
20962
  const text = typeof command === "string" ? command.trim() : "";
@@ -20023,26 +21016,7 @@ function codingAgent({ spec, command, args: extra = [], board, env = process.env
20023
21016
  start(run, report) {
20024
21017
  let cancelled = false;
20025
21018
  let agent = null;
20026
- const begin = (step) => {
20027
- const started = Date.now();
20028
- report.event({
20029
- kind: "step_started",
20030
- step,
20031
- attempt: 1,
20032
- status: "running"
20033
- });
20034
- return (status, message, data = {}) => report.event({
20035
- kind: "step_finished",
20036
- step,
20037
- attempt: 1,
20038
- status,
20039
- ...message && { message: clip(message) },
20040
- data: {
20041
- durationMs: Date.now() - started,
20042
- ...data
20043
- }
20044
- });
20045
- };
21019
+ const { step } = steps(report, () => cancelled);
20046
21020
  const warn = (message) => report.event({
20047
21021
  kind: "warning",
20048
21022
  message: clip(message)
@@ -20052,146 +21026,169 @@ function codingAgent({ spec, command, args: extra = [], board, env = process.env
20052
21026
  const tell = (body) => board.comment(ref, body).catch((err) => warn(`Couldn't comment on ${ref}: ${err.message}`));
20053
21027
  const flow = async () => {
20054
21028
  const ws = open(run.workdir, env);
20055
- let end = begin("prepare");
20056
- let branch;
20057
- let base;
20058
- let startSha;
20059
- let prompt;
20060
- let title;
20061
- try {
20062
- if (await ws.dirty()) {
20063
- const reason = `${run.workdir} has uncommitted changes: commit or stash them, then run it again.`;
20064
- end("failed", reason);
20065
- return {
20066
- status: "failed",
20067
- reason
20068
- };
20069
- }
20070
- const { task, comments } = await board.task(run.ref);
20071
- ref = task.ref;
20072
- title = task.title;
20073
- base = await ws.baseBranch();
20074
- if (!await ws.fetch(base)) warn(`Couldn't fetch ${base} from origin: it starts from the copy here.`);
20075
- branch = branchName(task.ref, task.title);
20076
- await ws.checkout(branch, base);
20077
- startSha = await ws.head();
20078
- const moved = await board.startWork(ref).catch((err) => {
20079
- warn(`Couldn't move ${ref}: ${err.message}`);
20080
- return null;
20081
- });
20082
- if (moved) report.event({
20083
- kind: "board",
20084
- message: clip(moved)
20085
- });
20086
- prompt = buildPrompt({
20087
- task,
20088
- comments,
20089
- branch
20090
- });
20091
- end("ok");
20092
- } catch (err) {
20093
- const reason = clip(`Couldn't get the folder ready: ${err.message}`, 1e3);
20094
- end("failed", reason);
20095
- return {
20096
- status: "failed",
20097
- reason
20098
- };
20099
- }
21029
+ const prepared = await step("prepare", async () => {
21030
+ try {
21031
+ if (await ws.dirty()) return failed(`${run.workdir} has uncommitted changes: commit or stash them, then run it again.`);
21032
+ const { task, comments } = await board.task(run.ref);
21033
+ ref = task.ref;
21034
+ const base = await ws.baseBranch();
21035
+ if (!await ws.fetch(base)) warn(`Couldn't fetch ${base} from origin: it starts from the copy here.`);
21036
+ const branch = branchName(task.ref, task.title);
21037
+ await ws.checkout(branch, base);
21038
+ const startSha = await ws.head();
21039
+ const moved = await board.startWork(ref).catch((err) => {
21040
+ warn(`Couldn't move ${ref}: ${err.message}`);
21041
+ return null;
21042
+ });
21043
+ if (moved) report.event({
21044
+ kind: "board",
21045
+ message: clip(moved)
21046
+ });
21047
+ return ok({
21048
+ branch,
21049
+ base,
21050
+ startSha,
21051
+ title: task.title,
21052
+ prompt: buildPrompt({
21053
+ task,
21054
+ comments,
21055
+ branch
21056
+ })
21057
+ });
21058
+ } catch (err) {
21059
+ return failed(clip(`Couldn't get the folder ready: ${err.message}`, 1e3));
21060
+ }
21061
+ }, { always: true });
21062
+ if (!prepared.ran || !prepared.value) return {
21063
+ status: "failed",
21064
+ reason: prepared.ran ? prepared.message : null
21065
+ };
21066
+ const { branch, base, startSha, title, prompt } = prepared.value;
20100
21067
  if (cancelled) return {
20101
21068
  status: "cancelled",
20102
21069
  reason: "Cancelled before the agent started."
20103
21070
  };
20104
- end = begin("code");
20105
- const limited = spec.limit?.(run.options);
20106
- if (limited) report.event({
20107
- kind: "warning",
20108
- step: "code",
20109
- message: clip(limited.warning)
20110
- });
20111
- const asked = limited ? {
20112
- ...run,
20113
- options: limited.options
20114
- } : run;
20115
- const dir = await mkdtemp(join(tmpdir(), "monoban-run-"));
20116
- const schemaFile = join(dir, "outcome.schema.json");
20117
- const schema = JSON.stringify(OUTCOME_SCHEMA);
20118
- await writeFile(schemaFile, schema);
20119
- const reader = spec.reader([run.workdir, await realpath(run.workdir).catch(() => run.workdir)]);
20120
- const activity = throttled((message) => report.event({
20121
- kind: "activity",
20122
- step: "code",
20123
- message: clip(message, 200)
20124
- }), activityMs);
20125
- const out = {
20126
- activity: (m) => m.trim() && activity.push(m),
20127
- warning: (m) => report.event({
21071
+ const coded = await step("code", async () => {
21072
+ const limited = spec.limit?.(run.options);
21073
+ if (limited) report.event({
20128
21074
  kind: "warning",
20129
21075
  step: "code",
20130
- message: clip(m)
20131
- }),
20132
- externalId: (id) => report.update({ externalId: id.slice(0, 128) })
21076
+ message: clip(limited.warning)
21077
+ });
21078
+ const asked = limited ? {
21079
+ ...run,
21080
+ options: limited.options
21081
+ } : run;
21082
+ const dir = await mkdtemp(join(tmpdir(), "monoban-run-"));
21083
+ const schemaFile = join(dir, "outcome.schema.json");
21084
+ const schema = JSON.stringify(OUTCOME_SCHEMA);
21085
+ await writeFile(schemaFile, schema);
21086
+ const reader = spec.reader([run.workdir, await realpath(run.workdir).catch(() => run.workdir)]);
21087
+ const activity = throttled((message) => report.event({
21088
+ kind: "activity",
21089
+ step: "code",
21090
+ message: clip(message, 200)
21091
+ }), activityMs);
21092
+ const out = {
21093
+ activity: (m) => m.trim() && activity.push(m),
21094
+ warning: (m) => report.event({
21095
+ kind: "warning",
21096
+ step: "code",
21097
+ message: clip(m)
21098
+ }),
21099
+ externalId: (id) => report.update({ externalId: id.slice(0, 128) })
21100
+ };
21101
+ agent = startProcess({
21102
+ command,
21103
+ args: spec.args(asked, {
21104
+ schema,
21105
+ schemaFile
21106
+ }, extra),
21107
+ cwd: run.workdir,
21108
+ env,
21109
+ stdin: prompt,
21110
+ onLine: (line) => {
21111
+ try {
21112
+ reader.line(line, out);
21113
+ } catch {}
21114
+ },
21115
+ ...spawn && { spawn },
21116
+ ...graceMs !== void 0 && { graceMs }
21117
+ });
21118
+ if (cancelled) agent.stop();
21119
+ const exit = await agent.done;
21120
+ agent = null;
21121
+ activity.stop();
21122
+ await rm$1(dir, {
21123
+ recursive: true,
21124
+ force: true
21125
+ });
21126
+ const result = reader.result();
21127
+ const data = {};
21128
+ if (result.costUsd !== null) {
21129
+ data.costUsd = result.costUsd;
21130
+ report.update({ costUsd: Math.round(result.costUsd * 1e4) / 1e4 });
21131
+ }
21132
+ if (result.tokens !== null) data.tokens = result.tokens;
21133
+ const outcome = parseOutcome(result.answer);
21134
+ const value = {
21135
+ spawnError: exit.spawnError,
21136
+ result,
21137
+ outcome,
21138
+ failure: null
21139
+ };
21140
+ if (cancelled) return {
21141
+ status: "cancelled",
21142
+ data,
21143
+ value
21144
+ };
21145
+ value.failure = exit.spawnError ?? result.failure ?? (exit.code === 0 ? null : `${label} stopped (exit code ${exit.code ?? "none"})${exit.lastError ? `: ${exit.lastError}` : "."}`);
21146
+ if (value.failure) return failed(value.failure, value, data);
21147
+ if (outcome?.status === "blocked") return {
21148
+ status: "needs_human",
21149
+ message: outcome.question || outcome.summary,
21150
+ data,
21151
+ value
21152
+ };
21153
+ return ok(value, data);
21154
+ }, { always: true });
21155
+ if (!coded.ran || !coded.value) return {
21156
+ status: "failed",
21157
+ reason: null
20133
21158
  };
20134
- agent = startProcess({
20135
- command,
20136
- args: spec.args(asked, {
20137
- schema,
20138
- schemaFile
20139
- }, extra),
20140
- cwd: run.workdir,
20141
- env,
20142
- stdin: prompt,
20143
- onLine: (line) => {
20144
- try {
20145
- reader.line(line, out);
20146
- } catch {}
20147
- },
20148
- ...spawn && { spawn },
20149
- ...graceMs !== void 0 && { graceMs }
20150
- });
20151
- if (cancelled) agent.stop();
20152
- const exit = await agent.done;
20153
- agent = null;
20154
- activity.stop();
20155
- await rm(dir, {
20156
- recursive: true,
20157
- force: true
20158
- });
20159
- const result = reader.result();
20160
- const data = {};
20161
- if (result.costUsd !== null) {
20162
- data.costUsd = result.costUsd;
20163
- report.update({ costUsd: Math.round(result.costUsd * 1e4) / 1e4 });
20164
- }
20165
- if (result.tokens !== null) data.tokens = result.tokens;
20166
- const outcome = parseOutcome(result.answer);
20167
- let failure = null;
20168
- if (cancelled) end("cancelled", null, data);
20169
- else {
20170
- failure = exit.spawnError ?? result.failure ?? (exit.code === 0 ? null : `${label} stopped (exit code ${exit.code ?? "none"})${exit.lastError ? `: ${exit.lastError}` : "."}`);
20171
- if (failure) end("failed", failure, data);
20172
- else if (outcome?.status === "blocked") end("needs_human", outcome.question || outcome.summary, data);
20173
- else end("ok", null, data);
20174
- }
20175
- if (exit.spawnError) return {
21159
+ const { spawnError, result, outcome } = coded.value;
21160
+ let { failure } = coded.value;
21161
+ if (spawnError) return {
20176
21162
  status: "failed",
20177
- reason: clip(exit.spawnError, 1e3)
21163
+ reason: clip(spawnError, 1e3)
20178
21164
  };
20179
- end = begin("commit");
20180
21165
  const unfinished = cancelled || failure !== null;
20181
- let commits = 0;
20182
- try {
20183
- const message = unfinished ? `${ref}: work in progress (the ${label} run ${cancelled ? "was cancelled" : "failed"})` : `${ref}: ${outcome?.prTitle || title}`;
20184
- const left = await ws.commitAll(message);
20185
- commits = await ws.commitsSince(startSha);
20186
- end(commits ? "ok" : "skipped", commits ? null : "nothing changed", { commits });
20187
- if (left && unfinished) report.event({
20188
- kind: "board",
20189
- message: `kept its unfinished work on ${branch}`
20190
- });
20191
- } catch (err) {
20192
- end("failed", err.message);
20193
- failure ??= `Couldn't commit its work: ${err.message}`;
20194
- }
21166
+ const committed = await step("commit", async () => {
21167
+ try {
21168
+ const message = unfinished ? `${ref}: work in progress (the ${label} run ${cancelled ? "was cancelled" : "failed"})` : `${ref}: ${outcome?.prTitle || title}`;
21169
+ const left = await ws.commitAll(message);
21170
+ const commits = await ws.commitsSince(startSha);
21171
+ const value = {
21172
+ commits,
21173
+ left
21174
+ };
21175
+ return commits ? ok(value, { commits }) : {
21176
+ ...skipped("nothing changed", { commits }),
21177
+ value
21178
+ };
21179
+ } catch (err) {
21180
+ failure ??= `Couldn't commit its work: ${err.message}`;
21181
+ return failed(err.message, {
21182
+ commits: 0,
21183
+ left: false
21184
+ });
21185
+ }
21186
+ }, { always: true });
21187
+ const { commits = 0, left = false } = committed.ran ? committed.value ?? {} : {};
21188
+ if (left && unfinished) report.event({
21189
+ kind: "board",
21190
+ message: `kept its unfinished work on ${branch}`
21191
+ });
20195
21192
  const kept = commits ? `\n\nIts work so far is on the branch \`${branch}\`.` : "";
20196
21193
  if (cancelled) return {
20197
21194
  status: "cancelled",
@@ -20227,13 +21224,18 @@ function codingAgent({ spec, command, args: extra = [], board, env = process.env
20227
21224
  }
20228
21225
  let url = null;
20229
21226
  const prTitle = clip(outcome?.prTitle || `${ref}: ${title}`, 200);
20230
- if (run.options.pr === "none") begin("pr")("skipped", `none asked for: the work is on ${branch}`);
21227
+ if (run.options.pr === "none") await step("pr", async () => skipped(`none asked for: the work is on ${branch}`));
20231
21228
  else {
20232
- end = begin("push");
20233
- try {
20234
- await ws.push(branch);
20235
- end("ok");
20236
- end = begin("pr");
21229
+ const up = async (fn) => {
21230
+ try {
21231
+ await fn();
21232
+ return ok();
21233
+ } catch (err) {
21234
+ return failed(clip(err.message, 1e3));
21235
+ }
21236
+ };
21237
+ const pushed = await step("push", () => up(() => ws.push(branch)));
21238
+ const opened = pushed.ran && pushed.status === "ok" ? await step("pr", () => up(async () => {
20237
21239
  url = await ws.pullRequestOf(branch) ?? await ws.openPullRequest({
20238
21240
  base,
20239
21241
  branch,
@@ -20248,10 +21250,9 @@ function codingAgent({ spec, command, args: extra = [], board, env = process.env
20248
21250
  message: url,
20249
21251
  data: { url }
20250
21252
  });
20251
- end("ok");
20252
- } catch (err) {
20253
- const reason = clip(err.message, 1e3);
20254
- end("failed", reason);
21253
+ })) : pushed;
21254
+ if (!opened.ran || opened.status !== "ok") {
21255
+ const reason = opened.ran && opened.message || "";
20255
21256
  await tell(`${label} finished, but couldn't put it up for review: ${reason}${kept}`);
20256
21257
  return {
20257
21258
  status: "failed",
@@ -20259,18 +21260,19 @@ function codingAgent({ spec, command, args: extra = [], board, env = process.env
20259
21260
  };
20260
21261
  }
20261
21262
  }
20262
- end = begin("report");
20263
- try {
20264
- if (url) await board.attach(ref, url, prTitle, run.options.pr === "draft");
20265
- await board.comment(ref, `${label} finished${url ? `: ${url}` : `, on the branch \`${branch}\``}.${summary ? `\n\n${clip(summary, 6e3)}` : ""}`);
20266
- report.event({
20267
- kind: "board",
20268
- message: url ? "attached the pull request, and commented" : "commented"
20269
- });
20270
- end("ok");
20271
- } catch (err) {
20272
- end("failed", err.message);
20273
- }
21263
+ await step("report", async () => {
21264
+ try {
21265
+ if (url) await board.attach(ref, url, prTitle, run.options.pr === "draft");
21266
+ await board.comment(ref, `${label} finished${url ? `: ${url}` : `, on the branch \`${branch}\``}.${summary ? `\n\n${clip(summary, 6e3)}` : ""}`);
21267
+ report.event({
21268
+ kind: "board",
21269
+ message: url ? "attached the pull request, and commented" : "commented"
21270
+ });
21271
+ return ok();
21272
+ } catch (err) {
21273
+ return failed(err.message);
21274
+ }
21275
+ });
20274
21276
  return {
20275
21277
  status: "succeeded",
20276
21278
  reason: null
@@ -20486,6 +21488,570 @@ const codexSpec = ({ allowFullAccess = false } = {}) => ({
20486
21488
  reader: codexReader
20487
21489
  });
20488
21490
  codexSpec();
21491
+ // src/runner/recipes/deliver.ts
21492
+ /**
21493
+ * `deliver` (docs/PLAN-AGENT-LOOPS.md §1.6): takes a task and delivers it as a pull request: `implement` opens it
21494
+ * (a draft), `review` reviews and fixes it, `checks` sees CI green (repairing it) and marks it ready, `feedback`
21495
+ * answers its review comments, and `merge` merges it when the run may (plan §1.12: the loop merges, a browser queued
21496
+ * the task, nothing but a browser rewrote it since, and this machine allows it). Otherwise the run ends with its pull
21497
+ * request ready for you to merge, saying why.
21498
+ */
21499
+ /** A deliver loop's options this recipe reads (the run's plan has them as the loop had them). */
21500
+ function options(run) {
21501
+ const o = run.plan.options;
21502
+ return {
21503
+ checksMinutes: o.checksMinutes ?? LOOP_DEFAULTS.checksMinutes,
21504
+ reviewTier: o.reviewTier ?? null
21505
+ };
21506
+ }
21507
+ /** The loop's review tier, if it names one: the preflight checks the folder's agentpipe has it. */
21508
+ const reviewTierOf = (run) => options(run).reviewTier;
21509
+ /** Money as agentpipe takes it: dollars, to the cent. */
21510
+ const usd = (n) => (Math.floor(n * 100) / 100).toFixed(2);
21511
+ /**
21512
+ * `agentpipe run` on the run's task: always `--autonomous` (nobody is there to answer), from an up-to-date base
21513
+ * (`--fresh-base`), opening a draft pull request (`checks` marks it ready once it's green), on what is left of the
21514
+ * budget. The dry run is the same command with `--dry-run`, so it checks what the run will do.
21515
+ */
21516
+ function implementArgs(run, budgetUsd) {
21517
+ return [
21518
+ "run",
21519
+ run.workdir,
21520
+ "--from-issue",
21521
+ run.ref ?? "",
21522
+ "--json",
21523
+ "--autonomous",
21524
+ "--fresh-base",
21525
+ "--draft",
21526
+ "--budget",
21527
+ usd(budgetUsd)
21528
+ ];
21529
+ }
21530
+ /** `agentpipe review` on the pull request, fixing what it finds, on the loop's tier when it names one. */
21531
+ function reviewArgs(run, pr, budgetUsd) {
21532
+ const tier = options(run).reviewTier;
21533
+ return [
21534
+ "review",
21535
+ String(pr.number),
21536
+ run.workdir,
21537
+ "--fix",
21538
+ "--json",
21539
+ "--budget",
21540
+ usd(budgetUsd),
21541
+ ...tier ? ["--tier", tier] : []
21542
+ ];
21543
+ }
21544
+ /**
21545
+ * `agentpipe ship --no-merge`: watches CI until it is green (re-running flakes, repairing what fails, within what
21546
+ * is left of the run's budget, on top of what earlier ships of this pull request spent) and marks it ready, giving
21547
+ * up at the loop's `checksMinutes`. `--force` takes over a lease an earlier ship left behind (leases.ts).
21548
+ */
21549
+ function checksArgs(run, pr, budgetUsd, { force = false } = {}) {
21550
+ return [
21551
+ "ship",
21552
+ String(pr.number),
21553
+ run.workdir,
21554
+ "--no-merge",
21555
+ "--json",
21556
+ "--deadline",
21557
+ String(options(run).checksMinutes * 60),
21558
+ "--additional-budget",
21559
+ usd(budgetUsd),
21560
+ ...force ? ["--force"] : []
21561
+ ];
21562
+ }
21563
+ /** `agentpipe address --apply --ship --no-merge`: answers the review comments, then sees CI green again. */
21564
+ function feedbackArgs(run, pr, budgetUsd) {
21565
+ return [
21566
+ "address",
21567
+ String(pr.number),
21568
+ run.workdir,
21569
+ "--apply",
21570
+ "--ship",
21571
+ "--no-merge",
21572
+ "--json",
21573
+ "--budget",
21574
+ usd(budgetUsd)
21575
+ ];
21576
+ }
21577
+ /**
21578
+ * `agentpipe merge --expect-run`: merges the pull request only if it is the one this machine's run opened (its
21579
+ * store has the run, the branch is the run's, the author is the `gh` user), refusing a required review or a blocked
21580
+ * one (§1.7). A refusal says the command that unblocks it.
21581
+ */
21582
+ function mergeArgs(run, pr, runId) {
21583
+ return [
21584
+ "merge",
21585
+ String(pr.number),
21586
+ run.workdir,
21587
+ "--expect-run",
21588
+ runId,
21589
+ "--json"
21590
+ ];
21591
+ }
21592
+ /** A step on the run's pull request, skipped when it has none (`implement` found nothing to change). */
21593
+ const onPr = (fn) => (ctx) => ctx.pr ? fn(ctx, ctx.pr) : Promise.resolve(skipped("There's no pull request."));
21594
+ /** A step's ending from how its command ended: agentpipe's word, else why it stopped without one. */
21595
+ /**
21596
+ * What a refused merge says: agentpipe's reason, with the command that unblocks it. agentpipe names one for most
21597
+ * (`agentpipe merge 42 --force-merge-on-green` past a review objection, `agentpipe merge 42` once a required review
21598
+ * is given); where it doesn't (checks failing or still running, a pull request this run didn't open), the person
21599
+ * merges it.
21600
+ */
21601
+ function unblocking(reason, pr) {
21602
+ const said = reason ?? "not merged";
21603
+ if (said.includes("`")) return said;
21604
+ return `${said}: merge #${pr.number} yourself once that's settled (\`gh pr merge ${pr.number}\`)`;
21605
+ }
21606
+ function endOf(result, what) {
21607
+ const value = {
21608
+ externalId: result.externalId,
21609
+ prUrl: result.prUrl
21610
+ };
21611
+ const data = result.costUsd ? { costUsd: result.costUsd } : void 0;
21612
+ const { ending, exit } = result;
21613
+ if (!ending) {
21614
+ if (exit.spawnError) return failed(exit.spawnError, value, data);
21615
+ const last = exit.lastError ? `: ${exit.lastError}` : ".";
21616
+ return failed(`${what} stopped (exit code ${exit.code ?? "none"}) without saying how it ended${last}`, value, data);
21617
+ }
21618
+ if (ending.status === "succeeded") return {
21619
+ status: "ok",
21620
+ ...ending.reason && { message: ending.reason },
21621
+ value,
21622
+ ...data && { data }
21623
+ };
21624
+ return {
21625
+ status: ending.status,
21626
+ ...ending.reason && { message: ending.reason },
21627
+ value,
21628
+ ...data && { data }
21629
+ };
21630
+ }
21631
+ const deliver = {
21632
+ steps: {
21633
+ implement: {
21634
+ pollSeconds: 15,
21635
+ run: async (ctx) => {
21636
+ if (!ctx.run.ref) return failed("A deliver run needs its task.");
21637
+ return endOf(await ctx.agentpipe(implementArgs(ctx.run, ctx.budgetUsd)), "agentpipe run");
21638
+ }
21639
+ },
21640
+ review: {
21641
+ pollSeconds: 15,
21642
+ run: onPr(async (ctx, pr) => endOf(await ctx.agentpipe(reviewArgs(ctx.run, pr, ctx.budgetUsd)), "agentpipe review"))
21643
+ },
21644
+ checks: {
21645
+ pollSeconds: null,
21646
+ run: onPr(async (ctx, pr) => {
21647
+ const args = checksArgs(ctx.run, pr, ctx.budgetUsd, { force: ctx.stranded(pr) });
21648
+ return endOf(await ctx.agentpipe(args), "agentpipe ship");
21649
+ })
21650
+ },
21651
+ feedback: {
21652
+ pollSeconds: 15,
21653
+ run: onPr(async (ctx, pr) => {
21654
+ const result = await ctx.agentpipe(feedbackArgs(ctx.run, pr, ctx.budgetUsd));
21655
+ if (result.said === "nothing_to_do") {
21656
+ const data = result.costUsd ? { costUsd: result.costUsd } : void 0;
21657
+ return skipped("There were no review comments to answer.", data);
21658
+ }
21659
+ return endOf(result, "agentpipe address");
21660
+ })
21661
+ },
21662
+ merge: {
21663
+ pollSeconds: 15,
21664
+ free: true,
21665
+ finishes: true,
21666
+ run: onPr(async (ctx, pr) => {
21667
+ if (!ctx.runId) return skipped("Ready for you to merge: agentpipe didn't say which run opened it.");
21668
+ const why = await ctx.mayMerge();
21669
+ if (why) return skipped(`Ready for you to merge: ${why}.`);
21670
+ const end = endOf(await ctx.agentpipe(mergeArgs(ctx.run, pr, ctx.runId)), "agentpipe merge");
21671
+ return end.status === "needs_human" ? {
21672
+ ...end,
21673
+ message: unblocking(end.message, pr)
21674
+ } : end;
21675
+ })
21676
+ }
21677
+ },
21678
+ dryRun: (run) => run.ref && run.plan.from !== "merge" ? [...implementArgs(run, run.budgetUsd), "--dry-run"] : null,
21679
+ tier: (run) => run.plan.from ? null : reviewTierOf(run),
21680
+ finished: ({ pr, last }) => {
21681
+ if (!pr) return null;
21682
+ if (last?.step === "merge" && last.status === "ok") return last.message ?? "Merged.";
21683
+ if (last?.step === "merge" && last.message) return last.message;
21684
+ return "Ready for you to merge.";
21685
+ }
21686
+ };
21687
+ // src/runner/recipes/leases.ts
21688
+ /**
21689
+ * `agentpipe ship` holds a lease on its pull request while it runs. Stopped with SIGTERM it frees it and says
21690
+ * `ship.end`; killed outright (or the machine restarted) it keeps it, and the next `ship` on that pull request is
21691
+ * refused unless it passes `--force` (docs/PLAN-AGENT-LOOPS.md §1.7, spike S8). So this machine notes each ship it
21692
+ * starts (agentpipe's pid, by pull request, in <config dir>/ships) and forgets it at `ship.end`: a note left with
21693
+ * its process gone is a lease nobody frees, the one case for `--force`.
21694
+ */
21695
+ function shipLeases(env) {
21696
+ const dir = join(configDir(env), "ships");
21697
+ const file = (prUrl) => join(dir, `${createHash("sha256").update(prUrl).digest("hex").slice(0, 32)}.json`);
21698
+ return {
21699
+ /** A ship on `prUrl` started, as process `pid`. */
21700
+ started(prUrl, pid) {
21701
+ mkdirSync(dir, {
21702
+ recursive: true,
21703
+ mode: 448
21704
+ });
21705
+ writeFileSync(file(prUrl), JSON.stringify({
21706
+ prUrl,
21707
+ pid
21708
+ }), { mode: 384 });
21709
+ },
21710
+ /** It said `ship.end`: it freed its lease. */
21711
+ ended(prUrl) {
21712
+ rmSync(file(prUrl), { force: true });
21713
+ },
21714
+ /** A ship on `prUrl` ended without freeing its lease, and its process is gone: the next one passes `--force`. */
21715
+ stranded(prUrl) {
21716
+ let pid;
21717
+ try {
21718
+ pid = JSON.parse(readFileSync(file(prUrl), "utf8")).pid;
21719
+ } catch {
21720
+ return false;
21721
+ }
21722
+ if (typeof pid !== "number") return true;
21723
+ return !alive(pid);
21724
+ }
21725
+ };
21726
+ }
21727
+ function alive(pid) {
21728
+ try {
21729
+ process.kill(pid, 0);
21730
+ return true;
21731
+ } catch (err) {
21732
+ return err.code === "EPERM";
21733
+ }
21734
+ }
21735
+ /**
21736
+ * `agentpipe scout`: surveys origin's default branch (`--fresh-base`) for what the loop's focus asks, and files what it
21737
+ * finds where the loop says, on what is left of the budget. The user's words go after `=`, so a focus starting with
21738
+ * `-` stays a value.
21739
+ */
21740
+ function scoutArgs(run, budgetUsd) {
21741
+ const { focus } = run.plan.options;
21742
+ return [
21743
+ "scout",
21744
+ run.workdir,
21745
+ "--json",
21746
+ "--fresh-base",
21747
+ `--focus=${focus}`,
21748
+ "--limit",
21749
+ String(Math.min(run.plan.limit ?? 0, 20)),
21750
+ "--track",
21751
+ `--column=${run.plan.columnName ?? ""}`,
21752
+ `--label=${run.plan.tagName ?? ""}`,
21753
+ "--budget",
21754
+ usd(budgetUsd)
21755
+ ];
21756
+ }
21757
+ const tasks = (n) => n === 1 ? "1 task" : `${n} tasks`;
21758
+ /** What a scout run filed, in words: the refs, what it left for later, and what was on the board already. */
21759
+ function filedSaying(result) {
21760
+ const { filed, counts } = result;
21761
+ const later = counts?.over_limit ?? 0;
21762
+ const already = counts?.already_filed ?? 0;
21763
+ const more = later ? `; ${later === 1 ? "1 more waits" : `${later} more wait`} until you close some` : "";
21764
+ if (filed.length) return `Filed ${tasks(filed.length)}: ${filed.join(", ")}${more}.`;
21765
+ if (already) return `Nothing new to file (${tasks(already)} it found ${already === 1 ? "is" : "are"} filed already)${more}.`;
21766
+ return `Nothing new to file${more}.`;
21767
+ }
21768
+ const scavenge = {
21769
+ steps: { scout: {
21770
+ pollSeconds: 15,
21771
+ run: async (ctx) => {
21772
+ const { limit, columnName, tagName } = ctx.run.plan;
21773
+ if (!limit || limit < 1) return skipped("Nothing to file: its open tasks are at its limit.");
21774
+ if (!columnName) return failed("The column it files in is gone: choose another for the loop.");
21775
+ if (!tagName) return failed("The tag it files with is gone: choose another for the loop.");
21776
+ const result = await ctx.agentpipe(scoutArgs(ctx.run, ctx.budgetUsd));
21777
+ const end = endOf(result, "agentpipe scout");
21778
+ if (end.status === "ok") return {
21779
+ ...end,
21780
+ message: filedSaying(result)
21781
+ };
21782
+ if (result.filed.length) return {
21783
+ ...end,
21784
+ message: `${end.message ?? "It stopped"} (it filed ${result.filed.join(", ")} first)`
21785
+ };
21786
+ return end;
21787
+ }
21788
+ } },
21789
+ dryRun: (run) => [
21790
+ "run",
21791
+ run.workdir,
21792
+ "--json",
21793
+ "--fresh-base",
21794
+ "--budget",
21795
+ usd(run.budgetUsd),
21796
+ "--dry-run"
21797
+ ],
21798
+ sandboxed: ["scout"],
21799
+ finished: ({ last }) => last?.message ?? null
21800
+ };
21801
+ // src/runner/recipes/index.ts
21802
+ /** A pull request's number, from its URL (…/pull/42), or null. */
21803
+ function prOf(url) {
21804
+ const n = url?.match(/\/pull\/(\d+)(?:[/?#]|$)/)?.[1];
21805
+ return url && n ? {
21806
+ url,
21807
+ number: Number(n)
21808
+ } : null;
21809
+ }
21810
+ const RECIPES = {
21811
+ deliver,
21812
+ scavenge
21813
+ };
21814
+ /** The recipes this monoban runs: a runner names these, of those its agentpipe can run (MON-202). */
21815
+ const RECIPES_HERE = RECIPE_NAMES.filter((name) => RECIPES[name] !== null);
21816
+ /** A step's name for an event: agentpipe's inner step under the recipe's (`implement.plan`), as the API takes it. */
21817
+ function innerStep(outer, inner) {
21818
+ if (!inner) return outer;
21819
+ return `${outer}.${inner.toLowerCase().replace(/[^a-z0-9_.-]+/g, "-")}`.slice(0, 40);
21820
+ }
21821
+ /** A note about a lease, which mustn't stop the run when this machine's config folder can't be written. */
21822
+ function safely(fn) {
21823
+ try {
21824
+ fn();
21825
+ return true;
21826
+ } catch {
21827
+ return false;
21828
+ }
21829
+ }
21830
+ /** A loop's run through its recipe: its steps in order, each confirmed with the server first. */
21831
+ function runRecipe(name, run, report, deps) {
21832
+ const recipe = RECIPES[name];
21833
+ let cancelled = false;
21834
+ let current = null;
21835
+ /** The step running now lets a cancel wait for it (RecipeStepRun.finishes). */
21836
+ let finishing = false;
21837
+ const { step } = steps(report, () => cancelled);
21838
+ /** What the run has spent so far, over all its commands. */
21839
+ let spent = 0;
21840
+ /**
21841
+ * Its pull request, and the run id the server keeps: the first agentpipe run's (`merge --expect-run` needs it). A
21842
+ * run that continues a pull request has both from the run that opened it (its plan, through the server).
21843
+ */
21844
+ let pr = prOf(run.plan.prUrl);
21845
+ let runId = run.plan.from ? run.plan.externalId : null;
21846
+ const leases = deps.leases ?? shipLeases(deps.env);
21847
+ const projectEnv = {
21848
+ ...deps.env,
21849
+ MONOBAN_PROJECT: run.project
21850
+ };
21851
+ const command = (outer) => async (args) => {
21852
+ if (cancelled) return {
21853
+ ending: {
21854
+ status: "cancelled",
21855
+ reason: "Cancelled."
21856
+ },
21857
+ exit: {
21858
+ code: null,
21859
+ spawnError: null,
21860
+ lastError: null
21861
+ },
21862
+ externalId: null,
21863
+ prUrl: null,
21864
+ costUsd: 0,
21865
+ said: null,
21866
+ filed: [],
21867
+ counts: null
21868
+ };
21869
+ let externalId = null;
21870
+ let prUrl = null;
21871
+ let cost = 0;
21872
+ const before = spent;
21873
+ const known = (url) => typeof url === "string" && url === pr?.url;
21874
+ const feed = agentpipeMapper({
21875
+ event: (e) => {
21876
+ if (e.kind === "pr_opened" && known(e.data?.url)) return;
21877
+ report.event({
21878
+ ...e,
21879
+ ...e.step !== void 0 && e.step !== null && { step: innerStep(outer, e.step) },
21880
+ ...e.message && { message: clip(e.message) }
21881
+ });
21882
+ },
21883
+ update: (u) => {
21884
+ const { externalId: id, prUrl: url, costUsd, ...rest } = u;
21885
+ if (id) externalId = id;
21886
+ if (url) prUrl = url;
21887
+ if (costUsd !== void 0) {
21888
+ cost = costUsd;
21889
+ spent = before + cost;
21890
+ }
21891
+ const first = id && !runId ? id : null;
21892
+ if (first) runId = first;
21893
+ const said = {
21894
+ ...rest,
21895
+ ...first && { externalId: first },
21896
+ ...url && !known(url) && { prUrl: url },
21897
+ ...costUsd !== void 0 && { costUsd: Math.round(spent * 1e4) / 1e4 }
21898
+ };
21899
+ if (Object.keys(said).length) report.update(said);
21900
+ }
21901
+ });
21902
+ const ships = args[0] === "ship" || args[0] === "address" && args.includes("--ship");
21903
+ const shipping = () => args[0] === "ship" || ships && feed.runEnded() && feed.said() === "ok";
21904
+ const leased = ships ? pr : null;
21905
+ let noted = false;
21906
+ let stopping = false;
21907
+ /**
21908
+ * Once its ship loop says something (it holds the lease by then; a refused one says only `ship.end`, and must
21909
+ * not overwrite a note of the process that does hold it), note the lease. And a cancel that came while
21910
+ * `address` was finishing reaches the ship loop that follows: it's stopped as soon as it starts.
21911
+ */
21912
+ const watch = (event) => {
21913
+ if (!shipping() || event.kind === "run.end") return;
21914
+ if (cancelled && !stopping) {
21915
+ stopping = true;
21916
+ started.terminate();
21917
+ }
21918
+ const pid = started.pid();
21919
+ if (noted || !leased || !pid || event.kind === "ship.end") return;
21920
+ noted = safely(() => leases.started(leased.url, pid));
21921
+ };
21922
+ const started = agentpipeCommand({
21923
+ command: deps.command,
21924
+ args,
21925
+ cwd: run.workdir,
21926
+ env: projectEnv,
21927
+ monobanBin: deps.monobanBin,
21928
+ map: (event) => {
21929
+ feed.take(event);
21930
+ if (current) current.externalId = externalId;
21931
+ watch(event);
21932
+ },
21933
+ ...deps.spawn && { spawn: deps.spawn }
21934
+ });
21935
+ current = {
21936
+ process: started,
21937
+ externalId: null,
21938
+ shipping,
21939
+ finishes: finishing
21940
+ };
21941
+ if (cancelled && !finishing) (shipping() ? started.terminate : started.interrupt)();
21942
+ const exit = await started.done;
21943
+ current = null;
21944
+ feed.flush();
21945
+ const said = feed.said();
21946
+ if (noted && leased && said !== null && said !== "ok") safely(() => leases.ended(leased.url));
21947
+ if (prUrl && !pr) pr = prOf(prUrl);
21948
+ return {
21949
+ ending: feed.ending(),
21950
+ exit,
21951
+ externalId,
21952
+ prUrl,
21953
+ costUsd: cost,
21954
+ said,
21955
+ filed: feed.filed(),
21956
+ counts: feed.counts()
21957
+ };
21958
+ };
21959
+ return {
21960
+ done: (async () => {
21961
+ if (!recipe) return {
21962
+ status: "failed",
21963
+ reason: `This monoban can't run ${name} loops yet.`
21964
+ };
21965
+ const order = RECIPES$1[name].steps;
21966
+ const from = run.plan.from ? order.indexOf(run.plan.from) : 0;
21967
+ if (run.plan.from) {
21968
+ if (from < 0 || !pr) return {
21969
+ status: "failed",
21970
+ reason: `There's no pull request to continue from ${run.plan.from}.`
21971
+ };
21972
+ report.update({
21973
+ prUrl: pr.url,
21974
+ ...runId && { externalId: runId }
21975
+ });
21976
+ }
21977
+ let last = null;
21978
+ for (const [i, stepName] of order.entries()) {
21979
+ const s = recipe.steps[stepName];
21980
+ if (!s) continue;
21981
+ if (i < from) {
21982
+ await step(stepName, async () => skipped(`The run it continues did this (it continues from ${run.plan.from}).`));
21983
+ continue;
21984
+ }
21985
+ const stop = await deps.recheck?.() ?? null;
21986
+ if (stop) return {
21987
+ status: "cancelled",
21988
+ reason: stop
21989
+ };
21990
+ if (cancelled) return {
21991
+ status: "cancelled",
21992
+ reason: "Cancelled."
21993
+ };
21994
+ const left = Math.max(0, Math.round((run.budgetUsd - spent) * 100) / 100);
21995
+ if (left < .1 && !s.free) return {
21996
+ status: "failed",
21997
+ reason: `Its budget (US$${run.budgetUsd}) is spent.`
21998
+ };
21999
+ deps.onStep?.(s.pollSeconds);
22000
+ const ctx = {
22001
+ run,
22002
+ budgetUsd: left,
22003
+ pr,
22004
+ agentpipe: command(stepName),
22005
+ stranded: (p) => leases.stranded(p.url),
22006
+ runId,
22007
+ mayMerge: async () => deps.mayMerge ? deps.mayMerge() : "this runner can't ask whether it may merge"
22008
+ };
22009
+ finishing = Boolean(s.finishes);
22010
+ const out = await step(stepName, () => s.run(ctx));
22011
+ finishing = false;
22012
+ if (!out.ran) return {
22013
+ status: "cancelled",
22014
+ reason: "Cancelled."
22015
+ };
22016
+ last = {
22017
+ step: stepName,
22018
+ status: out.status,
22019
+ message: out.message
22020
+ };
22021
+ if (out.status === "ok" || out.status === "skipped") continue;
22022
+ return {
22023
+ status: out.status === "needs_human" || out.status === "cancelled" ? out.status : "failed",
22024
+ reason: out.message ? clip(out.message, 1e3) : null
22025
+ };
22026
+ }
22027
+ return {
22028
+ status: "succeeded",
22029
+ reason: recipe.finished?.({
22030
+ pr,
22031
+ last
22032
+ }) ?? null
22033
+ };
22034
+ })().catch((err) => ({
22035
+ status: "failed",
22036
+ reason: clip(`The run stopped: ${err.message}`, 1e3)
22037
+ })),
22038
+ cancel: async () => {
22039
+ cancelled = true;
22040
+ const now = current;
22041
+ if (!now || now.finishes) return;
22042
+ if (now.shipping()) now.process.terminate();
22043
+ else if (now.externalId) {
22044
+ const env = agentpipeEnv(deps.env, deps.monobanBin);
22045
+ await (deps.execCommand ?? exec)(deps.command, [
22046
+ "cancel",
22047
+ now.externalId,
22048
+ "--reason",
22049
+ "Cancelled from monoban"
22050
+ ], env);
22051
+ } else now.process.interrupt();
22052
+ }
22053
+ };
22054
+ }
20489
22055
  // src/runner/agents/index.ts
20490
22056
  const DEFINITIONS = {
20491
22057
  agentpipe: { create: (d) => agentpipe({
@@ -20547,6 +22113,34 @@ function adaptersFor(found, settings, board, env, monobanBin = null) {
20547
22113
  monobanBin
20548
22114
  })]));
20549
22115
  }
22116
+ /**
22117
+ * The recipes this runner can run (docs/PLAN-AGENT-LOOPS.md §1.6): the ones this monoban runs whose agentpipe
22118
+ * commands the agentpipe here has (`agentpipe capabilities --json`). None with loops off, without agentpipe, or
22119
+ * with an agentpipe too old to say.
22120
+ */
22121
+ async function detectLoops(settings, found, env, { capabilities = agentpipeCapabilities, here = RECIPES_HERE } = {}) {
22122
+ if (!settings.loops.enabled) return {
22123
+ recipes: [],
22124
+ why: "off here (--no-loops, or loops.enabled in runner.json)"
22125
+ };
22126
+ if (!found.some((a) => a.name === "agentpipe")) return {
22127
+ recipes: [],
22128
+ why: "they need agentpipe (`monoban agentpipe install`)"
22129
+ };
22130
+ const said = await capabilities(settings.commands.agentpipe, env);
22131
+ if (!said) return {
22132
+ recipes: [],
22133
+ why: "this agentpipe can't say what it runs (`monoban agentpipe update`)"
22134
+ };
22135
+ const recipes = recipesOf(said).filter((r) => here.includes(r));
22136
+ return recipes.length ? {
22137
+ recipes,
22138
+ why: null
22139
+ } : {
22140
+ recipes,
22141
+ why: "none this monoban and agentpipe both run yet"
22142
+ };
22143
+ }
20550
22144
  // src/runner/board.ts
20551
22145
  function runBoard(api) {
20552
22146
  return {
@@ -20588,6 +22182,109 @@ function runBoard(api) {
20588
22182
  }
20589
22183
  };
20590
22184
  }
22185
+ // src/runner/recipes/preflight.ts
22186
+ /**
22187
+ * Before a loop's run starts, while it is still queued (docs/PLAN-AGENT-LOOPS.md §1.6): the recipe's dry run
22188
+ * (`agentpipe … --dry-run --json`), which spends nothing and says every precondition that would refuse it. Its
22189
+ * exit code is the verdict, its `run.preview` line the words. "Cannot finish on that budget" isn't a refusal
22190
+ * (agentpipe exits 0: it says so for any budget under the sum of its steps' ceilings, spike MON-194). The folder
22191
+ * check comes first, in the runner, as for every run.
22192
+ *
22193
+ * A loop's run goes on with nobody watching, so the preview must also say agentpipe's sandbox is on: for each model
22194
+ * step (its `boundary`) and for the repository's own commands (`commands.sandbox`, `[commands] sandbox`), spike S9,
22195
+ * AGE-157. A preview that doesn't say refuses it too. And a tier the recipe names (`--tier`) must be one the folder's
22196
+ * agentpipe has (`capabilities <folder> --json`, AGE-127).
22197
+ */
22198
+ async function preflight(run, recipe, deps) {
22199
+ const args = recipe.dryRun(run);
22200
+ if (args) {
22201
+ const refused = await dryRun(run, args, recipe.sandboxed ?? null, deps);
22202
+ if (refused) return refused;
22203
+ }
22204
+ const tier = recipe.tier?.(run) ?? null;
22205
+ if (tier) {
22206
+ const said = await (deps.capabilities ?? ((folder) => agentpipeCapabilities(deps.command, deps.env, folder)))(run.workdir);
22207
+ if (!said?.tiers) return `agentpipe couldn't say which tiers ${run.workdir} has, so the review tier ${tier} can't be checked.`;
22208
+ if (!said.tiers.includes(tier)) return clip(`agentpipe has no tier ${tier} in ${run.workdir} (it has ${said.tiers.join(", ") || "none"}).`, 1e3);
22209
+ }
22210
+ return null;
22211
+ }
22212
+ async function dryRun(run, args, only, deps) {
22213
+ let preview = null;
22214
+ const exit = await agentpipeCommand({
22215
+ command: deps.command,
22216
+ args,
22217
+ cwd: run.workdir,
22218
+ env: deps.env,
22219
+ monobanBin: deps.monobanBin,
22220
+ map: (event) => {
22221
+ if (event.kind === "run.preview") preview = event.data ?? {};
22222
+ },
22223
+ ...deps.spawn && { spawn: deps.spawn }
22224
+ }).done;
22225
+ if (exit.spawnError) return exit.spawnError;
22226
+ const said = preview;
22227
+ if (exit.code !== 0) {
22228
+ const refusals = (said?.refusals ?? []).map((r) => typeof r.message === "string" ? r.message : "").filter(Boolean);
22229
+ if (refusals.length) return clip(`agentpipe won't start it: ${refusals.join("; ")}`, 1e3);
22230
+ const last = exit.lastError ? `: ${exit.lastError}` : ".";
22231
+ return clip(`agentpipe's dry run refused it (exit code ${exit.code ?? "none"})${last}`, 1e3);
22232
+ }
22233
+ if (!said) return "agentpipe's dry run didn't say what the run would do, so its sandbox can't be checked.";
22234
+ const steps = said.steps ?? [];
22235
+ const unseen = (only ?? []).filter((name) => !steps.some((s) => s.name === name && s.boundary));
22236
+ if (unseen.length) return `agentpipe's dry run didn't show ${unseen.join(", ")}, so its sandbox can't be checked.`;
22237
+ const off = steps.filter((s) => s.boundary && s.boundary.sandbox !== true).filter((s) => !only || typeof s.name === "string" && only.includes(s.name)).map((s) => typeof s.name === "string" ? s.name : "a step");
22238
+ if (off.length) return clip(`agentpipe's sandbox is off for ${off.join(", ")}: a loop runs only with it on (each step's sandbox in .agentpipe/config.toml).`, 1e3);
22239
+ if (said.commands?.sandbox !== true) return "agentpipe's sandbox is off for the repository's own commands: a loop runs only with it on ([commands] sandbox = true in .agentpipe/config.toml).";
22240
+ return null;
22241
+ }
22242
+ // src/runner/spend.ts
22243
+ const DAY = 864e5;
22244
+ function spendFile(path, now = Date.now) {
22245
+ const read = async () => {
22246
+ try {
22247
+ const parsed = JSON.parse(await readFile(path, "utf8"));
22248
+ if (!Array.isArray(parsed)) return [];
22249
+ return parsed.filter((e) => typeof e?.at === "number" && typeof e?.usd === "number" && e.usd >= 0 && e.at > now() - DAY);
22250
+ } catch {
22251
+ return [];
22252
+ }
22253
+ };
22254
+ return {
22255
+ total: async () => (await read()).reduce((sum, e) => sum + e.usd, 0),
22256
+ add: async (usd) => {
22257
+ if (!(usd > 0)) return;
22258
+ const entries = [...await read(), {
22259
+ at: now(),
22260
+ usd
22261
+ }];
22262
+ await mkdir(dirname(path), {
22263
+ recursive: true,
22264
+ mode: 448
22265
+ });
22266
+ const temporary = `${path}.${process.pid}.tmp`;
22267
+ await writeFile(temporary, `${JSON.stringify(entries)}\n`, { mode: 384 });
22268
+ await rename(temporary, path);
22269
+ }
22270
+ };
22271
+ }
22272
+ /** The same, kept only while this runner runs (tests, and a runner with nowhere to write). */
22273
+ function spendInMemory(now = Date.now) {
22274
+ let entries = [];
22275
+ return {
22276
+ total: async () => {
22277
+ entries = entries.filter((e) => e.at > now() - DAY);
22278
+ return entries.reduce((sum, e) => sum + e.usd, 0);
22279
+ },
22280
+ add: async (usd) => {
22281
+ if (usd > 0) entries.push({
22282
+ at: now(),
22283
+ usd
22284
+ });
22285
+ }
22286
+ };
22287
+ }
20591
22288
  const sleepFor = (ms, signal) => new Promise((resolve) => {
20592
22289
  if (signal.aborted) return resolve();
20593
22290
  const timer = setTimeout(resolve, ms);
@@ -20610,12 +22307,32 @@ async function runRunner(ctx, settings, deps, options = {}) {
20610
22307
  const status = deps.onStatus ?? (() => {});
20611
22308
  let installed = deps.adapters;
20612
22309
  let adapters = Object.keys(installed);
20613
- const register = () => unwrap(api.POST("/v1/runners", { body: {
20614
- name: settings.name,
20615
- adapters,
20616
- version: VERSION,
20617
- pollSeconds: settings.pollSeconds
20618
- } }));
22310
+ let recipes = settings.loops.enabled ? [...deps.recipes ?? []] : [];
22311
+ const spend = deps.spend ?? spendInMemory();
22312
+ /** When each folder's ledger was last synced (syncLedgers). */
22313
+ const synced = /* @__PURE__ */ new Map();
22314
+ /** What this machine's day has left for loops' runs, in US dollars. */
22315
+ const dayLeft = async () => settings.loops.maxUsdPerDay - await spend.total();
22316
+ const register = async () => {
22317
+ const body = {
22318
+ name: settings.name,
22319
+ adapters,
22320
+ version: VERSION,
22321
+ pollSeconds: settings.pollSeconds
22322
+ };
22323
+ if (recipes.length) try {
22324
+ return await unwrap(api.POST("/v1/runners", { body: {
22325
+ ...body,
22326
+ recipes
22327
+ } }));
22328
+ } catch (err) {
22329
+ if (!(err instanceof ApiProblem && err.status === 400)) throw err;
22330
+ recipes = [];
22331
+ status({ recipes });
22332
+ ctx.err("The API doesn't take agent loops yet: this runner runs only the runs you start.");
22333
+ }
22334
+ return unwrap(api.POST("/v1/runners", { body }));
22335
+ };
20619
22336
  const redetectMs = deps.redetectMs ?? 6e4;
20620
22337
  let detectedAt = Date.now();
20621
22338
  /** Offers the agents installed now, when they changed (registering again tells the board). */
@@ -20640,10 +22357,13 @@ async function runRunner(ctx, settings, deps, options = {}) {
20640
22357
  let runner = await register();
20641
22358
  status({
20642
22359
  runnerId: runner.id,
20643
- agents: adapters
22360
+ agents: adapters,
22361
+ recipes
20644
22362
  });
20645
22363
  const stopWith = options.background ? "`monoban runner stop` stops it" : "Ctrl-C to stop";
20646
22364
  ctx.err(`Runner ${runner.name} is online with ${adapters.join(", ")}: waiting for runs (checking every ${settings.pollSeconds}s, every ${Math.min(settings.pollSeconds, 5)}s while one runs; ${stopWith}).`);
22365
+ if (recipes.length) ctx.err(`Agent loops: ${recipes.join(", ")}.`);
22366
+ else if (deps.loopsWhy) ctx.err(`Agent loops: ${deps.loopsWhy}.`);
20647
22367
  let active = null;
20648
22368
  let stopping = false;
20649
22369
  let interrupted = false;
@@ -20676,7 +22396,11 @@ async function runRunner(ctx, settings, deps, options = {}) {
20676
22396
  while (!leave && (!stopping || active)) {
20677
22397
  let work = null;
20678
22398
  try {
20679
- work = await heartbeat(api, runner.id);
22399
+ const free = !active && !stopping && !(options.once && took) && (!recipes.length || await dayLeft() >= 1);
22400
+ work = await heartbeat(api, runner.id, recipes.length ? {
22401
+ recipes,
22402
+ free
22403
+ } : void 0);
20680
22404
  if (unreachable) ctx.err("Reached the API again.");
20681
22405
  unreachable = false;
20682
22406
  status({
@@ -20684,7 +22408,7 @@ async function runRunner(ctx, settings, deps, options = {}) {
20684
22408
  unreachable: null
20685
22409
  });
20686
22410
  } catch (err) {
20687
- if (err instanceof NotSignedIn || err instanceof ApiProblem && err.status === 401) throw err;
22411
+ if (err instanceof NotSignedIn || err instanceof ApiProblem && (err.status === 401 || err.status === 426)) throw err;
20688
22412
  if (err instanceof ApiProblem && err.status === 404) {
20689
22413
  runner = await register();
20690
22414
  status({ runnerId: runner.id });
@@ -20703,10 +22427,13 @@ async function runRunner(ctx, settings, deps, options = {}) {
20703
22427
  ctx.err(`Cancelling ${active.ref}: asked from the board.`);
20704
22428
  active.cancel();
20705
22429
  }
20706
- } else if (first) await patch(api, run.id, {
20707
- status: "failed",
20708
- reason: "The runner stopped while it ran."
20709
- }).catch(() => {});
22430
+ } else if (first) {
22431
+ const status = run.recipe ? "cancelled" : "failed";
22432
+ await patch(api, run.id, {
22433
+ status,
22434
+ reason: "The runner stopped while it ran."
22435
+ }).catch(() => {});
22436
+ }
20710
22437
  first = false;
20711
22438
  const next = work.queued[0];
20712
22439
  if (!active && !stopping && next && !(options.once && took)) {
@@ -20723,11 +22450,12 @@ async function runRunner(ctx, settings, deps, options = {}) {
20723
22450
  }
20724
22451
  }
20725
22452
  }
22453
+ if (!active && !stopping && work?.waiting?.length && deps.agentpipe) await syncLedgers(work.waiting);
20726
22454
  await active?.flush();
20727
22455
  if (options.once && !active && (took || !work?.queued.length)) break;
20728
22456
  if (!active && !stopping) await redetect().catch(() => {});
20729
22457
  if (!leave && (!stopping || active)) {
20730
- const seconds = active ? Math.min(settings.pollSeconds, 5) : settings.pollSeconds;
22458
+ const seconds = active ? Math.min(settings.pollSeconds, active.pollSeconds) : settings.pollSeconds;
20731
22459
  await deps.sleep(seconds * 1e3, wake.signal);
20732
22460
  wake = new AbortController();
20733
22461
  }
@@ -20750,7 +22478,8 @@ async function runRunner(ctx, settings, deps, options = {}) {
20750
22478
  cancelled = true;
20751
22479
  await cancel();
20752
22480
  },
20753
- flush: () => outbox.flush()
22481
+ flush: () => outbox.flush(),
22482
+ pollSeconds: 5
20754
22483
  };
20755
22484
  return {
20756
22485
  active: self,
@@ -20762,12 +22491,33 @@ async function runRunner(ctx, settings, deps, options = {}) {
20762
22491
  reason
20763
22492
  }, run.version).catch(() => {});
20764
22493
  };
20765
- if (!ref) return refuse("failed", "Its task was deleted.");
22494
+ const recipe = run.recipe ? RECIPES[run.recipe] ?? null : null;
22495
+ let loopRun = null;
22496
+ if (run.recipe) {
22497
+ if (!recipe || !run.loopRun || !deps.agentpipe) return refuse("failed", `${runner.name} can't run ${run.recipe} loops.`);
22498
+ if (run.recipe === "deliver" && !ref) return refuse("cancelled", "Its task was deleted.");
22499
+ const left = await dayLeft();
22500
+ if (left < 1) return refuse("cancelled", `${runner.name} has spent its day for loops (US$${settings.loops.maxUsdPerDay}, loops.maxUsdPerDay).`);
22501
+ const budget = run.options.budgetUsd ?? run.loopRun.options.budgetUsd;
22502
+ loopRun = {
22503
+ id: run.id,
22504
+ ref,
22505
+ project: run.project.key,
22506
+ workdir: run.workdir,
22507
+ plan: run.loopRun,
22508
+ budgetUsd: Math.min(budget, left)
22509
+ };
22510
+ } else if (!ref) return refuse("failed", "Its task was deleted.");
20766
22511
  const adapter = installed[run.adapter];
20767
22512
  if (!adapter) return refuse("failed", `${runner.name} can't run ${run.adapter}.`);
20768
22513
  const problem = await deps.workdirProblem(run.workdir, run.project);
20769
22514
  if (problem) return refuse("failed", problem);
20770
- if (settings.confirm && !await ctx.confirm(`Run ${ref} with ${run.adapter} in ${run.workdir}?`)) return refuse("cancelled", `Declined on ${runner.name}.`);
22515
+ if (loopRun && recipe && deps.agentpipe) {
22516
+ const refused = await preflight(loopRun, recipe, deps.agentpipe);
22517
+ if (refused) return refuse("failed", refused);
22518
+ }
22519
+ const what = ref ?? `a ${run.recipe} run`;
22520
+ if (settings.confirm && !await ctx.confirm(`Run ${what} with ${run.adapter} in ${run.workdir}?`)) return refuse("cancelled", `Declined on ${runner.name}.`);
20771
22521
  if (cancelled) return refuse("cancelled", "Cancelled before it started.");
20772
22522
  try {
20773
22523
  await patch(api, run.id, { status: "running" }, run.version);
@@ -20775,43 +22525,106 @@ async function runRunner(ctx, settings, deps, options = {}) {
20775
22525
  if (err instanceof ApiProblem && (err.status === 412 || err.status === 409)) return;
20776
22526
  throw err;
20777
22527
  }
20778
- ctx.err(`▶ ${ref} in ${run.workdir} (${run.adapter})`);
22528
+ ctx.err(`▶ ${what} in ${run.workdir} (${run.recipe ? `${run.recipe} loop` : run.adapter})`);
20779
22529
  status({ run: {
20780
22530
  id: run.id,
20781
- ref,
22531
+ ref: what,
20782
22532
  workdir: run.workdir,
20783
22533
  adapter: run.adapter,
20784
22534
  startedAt: now()
20785
22535
  } });
20786
- const started = adapter.start({
20787
- ref,
20788
- workdir: run.workdir,
20789
- options: run.options
20790
- }, {
22536
+ const report = {
20791
22537
  event: (e) => {
20792
22538
  outbox.push(e);
20793
22539
  const line = describe$1(e);
20794
22540
  if (line) ctx.err(` ${line}`);
20795
22541
  },
20796
22542
  update: (u) => outbox.update(u)
20797
- });
22543
+ };
22544
+ const started = loopRun && deps.agentpipe ? runRecipe(run.recipe, loopRun, report, {
22545
+ ...deps.agentpipe,
22546
+ recheck: () => recheck(run.id),
22547
+ mayMerge: () => mayMerge(run.id),
22548
+ onStep: (seconds) => {
22549
+ self.pollSeconds = seconds ?? settings.pollSeconds;
22550
+ }
22551
+ }) : adapter.start({
22552
+ ref,
22553
+ workdir: run.workdir,
22554
+ options: run.options
22555
+ }, report);
20798
22556
  cancel = started.cancel;
20799
22557
  if (cancelled) started.cancel();
20800
22558
  const ending = await started.done;
20801
22559
  await outbox.flush();
22560
+ if (loopRun) await spend.add(outbox.updates().costUsd ?? 0).catch(() => {});
20802
22561
  await patch(api, run.id, {
20803
22562
  ...outbox.updates(),
20804
22563
  status: ending.status,
20805
22564
  reason: ending.reason
20806
22565
  }).catch((err) => ctx.err(`Couldn't record how ${ref} ended: ${err.message}`));
20807
22566
  const pr = outbox.updates().prUrl;
20808
- ctx.err(`${ENDINGS[ending.status]}: ${ref}${ending.reason ? ` (${ending.reason})` : ""}${pr ? ` ${pr}` : ""}`);
22567
+ ctx.err(`${ENDINGS[ending.status]}: ${what}${ending.reason ? ` (${ending.reason})` : ""}${pr ? ` ${pr}` : ""}`);
20809
22568
  })().catch((err) => ctx.err(`✗ ${self.ref}: ${err.message}`))
20810
22569
  };
20811
22570
  }
22571
+ /**
22572
+ * `agentpipe ledger sync` in the folders of its deliver loops with pull requests waiting for you (plan §1.4): it asks
22573
+ * GitHub what became of them, read-only, and a pull request merged by hand moves its task to Done. Once a folder
22574
+ * per check-in at most (an early wake doesn't repeat it), and only in a folder a run may work in (workdirProblem).
22575
+ */
22576
+ async function syncLedgers(waiting) {
22577
+ const agentpipe = deps.agentpipe;
22578
+ if (!agentpipe) return;
22579
+ const at = Date.parse(now());
22580
+ for (const loop of waiting) {
22581
+ if (at - (synced.get(loop.workdir) ?? Number.NEGATIVE_INFINITY) < settings.pollSeconds * 1e3) continue;
22582
+ synced.set(loop.workdir, at);
22583
+ if (await deps.workdirProblem(loop.workdir, loop.project)) continue;
22584
+ await ledgerSync(agentpipe, loop.workdir).catch(() => {});
22585
+ }
22586
+ }
22587
+ /**
22588
+ * Right before a loop's run merges (plan §1.12): null when it may, else why not. This machine's `loops.merge:
22589
+ * false` says no; otherwise the server, reading the run now (`mayMerge`). Anything but its yes is a no.
22590
+ */
22591
+ async function mayMerge(runId) {
22592
+ if (!settings.loops.merge) return "this machine doesn't merge loops' runs (loops.merge is false in runner.json)";
22593
+ try {
22594
+ const run = await unwrap(api.GET("/v1/runs/{runId}", { params: { path: { runId } } }));
22595
+ if (run.mayMerge === true) return null;
22596
+ return run.mergeHold ? describeMergeHold(run.mergeHold, ENGLISH) : "the server didn't say it may merge";
22597
+ } catch (err) {
22598
+ return `couldn't ask the server whether it may merge (${err.message})`;
22599
+ }
22600
+ }
22601
+ /**
22602
+ * Before each step of a loop's run: why it should stop now, or null. Asked from the board (cancelled, or no
22603
+ * longer running), or its task deleted, archived or done (read by the run's ref now: a task can move).
22604
+ */
22605
+ async function recheck(runId) {
22606
+ const run = await unwrap(api.GET("/v1/runs/{runId}", { params: { path: { runId } } }));
22607
+ if (run.status !== "running" || run.cancelRequested) return "Cancelled from the board.";
22608
+ if (!run.ref || run.recipe !== "deliver") return null;
22609
+ const key = run.ref.slice(0, run.ref.lastIndexOf("-"));
22610
+ try {
22611
+ const task = await unwrap(api.GET("/v1/tasks/{ref}", { params: { path: { ref: run.ref } } }));
22612
+ if (task.archivedAt) return `${task.ref} was archived.`;
22613
+ const { columns } = await unwrap(api.GET("/v1/projects/{key}", { params: { path: { key } } }));
22614
+ if (doneColumn(columns)?.id === task.columnId) return `${task.ref} is done.`;
22615
+ } catch (err) {
22616
+ if (err instanceof ApiProblem && err.status === 404) return `${run.ref} was deleted.`;
22617
+ throw err;
22618
+ }
22619
+ return null;
22620
+ }
20812
22621
  }
20813
- function heartbeat(api, runnerId) {
20814
- return unwrap(api.POST("/v1/runners/{runnerId}/heartbeat", { params: { path: { runnerId } } }));
22622
+ /** Checks in; a runner that runs loops says which recipes, and whether it's free to start one. */
22623
+ function heartbeat(api, runnerId, body) {
22624
+ return unwrap(api.POST("/v1/runners/{runnerId}/heartbeat", {
22625
+ params: { path: { runnerId } },
22626
+ ...body && { body }
22627
+ }));
20815
22628
  }
20816
22629
  function patch(api, runId, body, version) {
20817
22630
  return unwrap(api.PATCH("/v1/runs/{runId}", {
@@ -21002,7 +22815,7 @@ const LOG_LIMIT = 1048576;
21002
22815
  /** Moves a long log aside, keeping one older one. */
21003
22816
  async function rotateLog(path, limit = LOG_LIMIT) {
21004
22817
  if (await stat(path).then((s) => s.size, () => 0) <= limit) return;
21005
- await rm(`${path}.1`, { force: true });
22818
+ await rm$1(`${path}.1`, { force: true });
21006
22819
  await rename(path, `${path}.1`);
21007
22820
  }
21008
22821
  /** The last `count` lines of a file ([] when there's none). */
@@ -21068,7 +22881,8 @@ function flagsOf(options) {
21068
22881
  ...options.interval !== void 0 && { interval: options.interval },
21069
22882
  ...options.allow?.length && { allow: options.allow },
21070
22883
  ...options.agents !== void 0 && { agents: options.agents },
21071
- ...options.allowFullAccess && { allowFullAccess: true }
22884
+ ...options.allowFullAccess && { allowFullAccess: true },
22885
+ ...options.loops === false && { loops: false }
21072
22886
  };
21073
22887
  }
21074
22888
  /** Those flags as arguments. */
@@ -21078,7 +22892,8 @@ function argsOf(flags) {
21078
22892
  ...flags.interval !== void 0 ? ["--interval", flags.interval] : [],
21079
22893
  ...(flags.allow ?? []).flatMap((folder) => ["--allow", folder]),
21080
22894
  ...flags.agents !== void 0 ? ["--agents", flags.agents] : [],
21081
- ...flags.allowFullAccess ? ["--allow-full-access"] : []
22895
+ ...flags.allowFullAccess ? ["--allow-full-access"] : [],
22896
+ ...flags.loops === false ? ["--no-loops"] : []
21082
22897
  ];
21083
22898
  }
21084
22899
  /** Why it stopped, from what stopped it. */
@@ -21103,7 +22918,7 @@ function onSignals(signals, heard) {
21103
22918
  };
21104
22919
  }
21105
22920
  /**
21106
- * `monoban runner`: in the background unless told otherwise; in the foreground, the loop (runner/loop.ts) until
22921
+ * `monoban runner`: in the background unless told otherwise; in the foreground, the poll loop (runner/poll.ts) until
21107
22922
  * Ctrl-C, keeping its file current. It offers the agents installed here (or the ones --agents names), and says why
21108
22923
  * it doesn't offer the others.
21109
22924
  */
@@ -21156,7 +22971,7 @@ async function runner(ctx, options, overrides = {}) {
21156
22971
  };
21157
22972
  let reason = null;
21158
22973
  try {
21159
- const { detect = detectAgents, ...deps } = overrides;
22974
+ const { detect = detectAgents, detectLoops: _, ...deps } = overrides;
21160
22975
  let adapters = deps.adapters;
21161
22976
  let redetect = deps.redetect;
21162
22977
  if (!adapters) {
@@ -21168,6 +22983,18 @@ async function runner(ctx, options, overrides = {}) {
21168
22983
  ctx.err(`Agents: ${agentList(found)}.${missing.length ? ` Not offered: ${missing.join("; ")}.` : ""}`);
21169
22984
  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.");
21170
22985
  adapters = adaptersFor(found, settings, board, env, monobanBin);
22986
+ if (!deps.recipes) {
22987
+ const loops = await (overrides.detectLoops ?? detectLoops)(settings, found, env);
22988
+ deps.recipes = loops.recipes;
22989
+ deps.loopsWhy = loops.why;
22990
+ deps.agentpipe ??= {
22991
+ command: settings.commands.agentpipe,
22992
+ env,
22993
+ monobanBin
22994
+ };
22995
+ deps.spend ??= spendFile(join(runnersDir(ctx.env), "loops-spend.json"));
22996
+ file.save({ loopsWhy: loops.why });
22997
+ }
21171
22998
  redetect ??= async () => adaptersFor((await detect(settings, env)).found, settings, board, env, monobanBin);
21172
22999
  }
21173
23000
  await runRunner(ctx, settings, {
@@ -21324,6 +23151,7 @@ function describe({ state, running }, board, now) {
21324
23151
  if (running) {
21325
23152
  lines.push(`● ${state.name} running ${where$1(state)} · pid ${state.pid} · up ${since(state.startedAt, now)} · monoban ${state.version}`);
21326
23153
  if (state.agents.length) row("agents", state.agents.map(agentLabel).join(", "));
23154
+ if (state.recipes !== void 0) row("loops", state.recipes.length ? `on: ${state.recipes.join(", ")}` : `none: ${state.loopsWhy ?? "off"}`);
21327
23155
  if (state.run) row("run", `${state.run.ref} in ${state.run.workdir} (${agentLabel(state.run.adapter)}), for ${since(state.run.startedAt, now)}`);
21328
23156
  if (state.draining) row("stopping", state.run ? `once ${state.run.ref} ends` : "now");
21329
23157
  if (state.unreachable) row("board", `can't reach the API (${state.unreachable})`);
@@ -21331,7 +23159,7 @@ function describe({ state, running }, board, now) {
21331
23159
  const seenAgo = `checked in ${since(board.lastSeenAt, now)} ago (every ${board.pollSeconds}s)`;
21332
23160
  row("board", `${board.online ? "online" : "offline"} · ${seenAgo}`);
21333
23161
  } else if (!state.runnerId) row("board", "not on the board yet: it's starting");
21334
- if (state.version !== "1.8.0") {
23162
+ if (state.version !== "1.10.0") {
21335
23163
  const again = state.background ? "`monoban runner restart`" : "start it again in its terminal";
21336
23164
  row("update", `it runs monoban ${state.version}, this is ${VERSION}: ${again}`);
21337
23165
  }
@@ -21769,7 +23597,7 @@ async function checks(ctx, deps = {}) {
21769
23597
  const found = [];
21770
23598
  const latest = await (deps.latest ?? latestVersion)(ctx);
21771
23599
  const upgrade = UPGRADE[thisInstall()].command;
21772
- found.push(latest && newer(latest, "1.8.0") ? {
23600
+ found.push(latest && newer(latest, "1.10.0") ? {
21773
23601
  name: "monoban",
21774
23602
  status: "warn",
21775
23603
  detail: `${VERSION}; ${latest} is out`,
@@ -21932,6 +23760,89 @@ async function doctor(ctx, options, deps = {}) {
21932
23760
  }
21933
23761
  if (found.some((c) => c.status === "fail")) throw new CliError("", EXIT.error);
21934
23762
  }
23763
+ // src/commands/loops.ts
23764
+ /** Every loop of the project, in the API's order (oldest first). */
23765
+ async function loopsOf(api, key) {
23766
+ const all = [];
23767
+ for await (const loop of pages((cursor) => unwrap(api.GET("/v1/projects/{key}/loops", { params: {
23768
+ path: { key },
23769
+ query: { cursor }
23770
+ } })).then((page) => ({
23771
+ items: page.loops,
23772
+ nextCursor: page.nextCursor
23773
+ })))) all.push(loop);
23774
+ return all;
23775
+ }
23776
+ /** Where a project's loops are made, changed and resumed. */
23777
+ const loopsTab = (ctx, key) => `${ctx.webUrl}/p/${key}?view=loops`;
23778
+ /** What it's doing, in a few words: its state, and while a run goes, the step and task. */
23779
+ function loopDoing(loop, now = Date.now()) {
23780
+ const state = describeLoopState(loop.state, ENGLISH, now);
23781
+ const going = loop.going && [loop.going.step, loop.going.ref].filter(Boolean).join(" on ");
23782
+ return going ? `${state}: ${going}` : state;
23783
+ }
23784
+ /** "Deliver deliver running: implement on MON-12 mbp 24h: 2 runs, $1.23". */
23785
+ function loopLine(loop, widths, now = Date.now()) {
23786
+ const day = loop.last24h.runs ? `24h: ${loop.last24h.runs} ${loop.last24h.runs === 1 ? "run" : "runs"}, ${formatCost(loop.last24h.costUsd, ENGLISH)}` : "24h: no runs";
23787
+ return [
23788
+ loop.name.padEnd(widths.name),
23789
+ loop.recipe.padEnd(widths.recipe),
23790
+ loopDoing(loop, now),
23791
+ loop.runner.name,
23792
+ day
23793
+ ].join(" ");
23794
+ }
23795
+ /** `monoban loops`: the project's loops and what each is doing. */
23796
+ async function loops(ctx, options) {
23797
+ const api = apis(ctx).signedIn;
23798
+ const key = await resolveProject(ctx, api, options.project);
23799
+ const all = await loopsOf(api, key);
23800
+ if (options.json) return ctx.out(JSON.stringify(all, null, 2));
23801
+ if (!all.length) {
23802
+ ctx.err(`${key} has no loops yet. Make one in its loops tab: ${loopsTab(ctx, key)}`);
23803
+ return;
23804
+ }
23805
+ const widths = {
23806
+ name: Math.max(...all.map((l) => [...l.name].length)),
23807
+ recipe: Math.max(...all.map((l) => l.recipe.length))
23808
+ };
23809
+ for (const loop of all) ctx.out(loopLine(loop, widths));
23810
+ }
23811
+ /** The loop named `name` (any case, or its id), or a not-found error that names the project's loops. */
23812
+ function findLoop(all, name, key) {
23813
+ const wanted = name.trim().toLowerCase();
23814
+ const found = all.find((l) => l.name.toLowerCase() === wanted || l.id === name.trim());
23815
+ if (found) return found;
23816
+ const names = all.map((l) => `"${l.name}"`).join(", ");
23817
+ throw new CliError(`${key} has no loop named "${name}"${names ? ` (its loops: ${names})` : ""}.`, EXIT.notFound);
23818
+ }
23819
+ /**
23820
+ * `monoban loop pause NAME`: it starts no new run until it's resumed in the browser. A run it has going goes on:
23821
+ * cancel that from the board.
23822
+ */
23823
+ async function loopPause(ctx, name, options) {
23824
+ const api = apis(ctx).signedIn;
23825
+ const key = await resolveProject(ctx, api, options.project);
23826
+ const loop = findLoop(await loopsOf(api, key), name, key);
23827
+ let paused = loop;
23828
+ if (!loop.paused) paused = await unwrap(api.PATCH("/v1/loops/{loopId}", {
23829
+ params: {
23830
+ path: { loopId: loop.id },
23831
+ header: ifMatch(loop.version)
23832
+ },
23833
+ body: { paused: true }
23834
+ })).catch((err) => {
23835
+ if (err instanceof ApiProblem && err.status === 412) throw new CliError(`${loop.name} changed elsewhere in the meantime. Run \`monoban loops\` and try again.`);
23836
+ throw err;
23837
+ });
23838
+ if (options.json) ctx.out(JSON.stringify(paused, null, 2));
23839
+ else ctx.out(loop.paused ? `${loop.name} is already ${describeLoopState(loop.state, ENGLISH)}.` : `Paused ${loop.name}.`);
23840
+ if (paused.going) {
23841
+ const what = paused.going.ref ?? "its run";
23842
+ ctx.err(`Its run going now (${what}) goes on: cancel it from the board if it should stop too.`);
23843
+ }
23844
+ ctx.err(`Resume it in the browser: ${loopsTab(ctx, key)}`);
23845
+ }
21935
23846
  // src/commands/notes.ts
21936
23847
  const printNotes = (ctx, key, notes) => ctx.out(JSON.stringify({
21937
23848
  project: key,
@@ -22189,6 +24100,7 @@ const READ_ONLY = [
22189
24100
  "monoban comments",
22190
24101
  "monoban runs",
22191
24102
  "monoban runner status",
24103
+ "monoban loops",
22192
24104
  "monoban today",
22193
24105
  "monoban search",
22194
24106
  "monoban tags",
@@ -22325,6 +24237,7 @@ go?"). Once the user agrees:
22325
24237
  | \`monoban tags\` | the tags the project's tasks can have |
22326
24238
  | \`monoban notes show\` | the project's notes |
22327
24239
  | \`monoban runner status\` | whether this machine's runner (it runs agents on tasks, \`R\` on the board) is running, and why it stopped |
24240
+ | \`monoban loops\` | the project's agent loops (agents a runner starts on a timer) and what each is doing |
22328
24241
  | \`monoban add "TITLE" [-c COLUMN] [-t TAG]… [--date DAY] [-d TEXT \\| -d -]\` | add a task |
22329
24242
  | \`monoban edit MON-12 [--title TEXT] [-d TEXT \\| -d -]\` | replace its title or description |
22330
24243
  | \`monoban move MON-12 COLUMN\` | move it to the end of a column |
@@ -22336,6 +24249,7 @@ go?"). Once the user agrees:
22336
24249
  | \`monoban attach MON-12 --pr\` or \`monoban attach MON-12 URL\` | attach this branch's pull request, or any link |
22337
24250
  | \`monoban comment MON-12 TEXT\` (or \`-\` for stdin) | comment on it, in Markdown |
22338
24251
  | \`monoban notes add TEXT\` (or \`-\` for stdin) | add lines at the end of the notes |
24252
+ | \`monoban loop pause NAME\` | pause a loop when the user asks: it starts no new run until they resume it in the browser |
22339
24253
 
22340
24254
  Every command takes \`--json\`; project commands take \`-p KEY\`. \`monoban COMMAND --help\` has the rest.
22341
24255
  `;
@@ -22384,7 +24298,7 @@ async function setup(ctx, agent, options) {
22384
24298
  if (options.json) return report("none", "");
22385
24299
  return ctx.err(`The monoban skill isn't installed for ${name} at ${shown}.`);
22386
24300
  }
22387
- await rm(path);
24301
+ await rm$1(path);
22388
24302
  await rmdir(dirname(path)).catch(() => {});
22389
24303
  return report("removed", `Removed the monoban skill for ${name}: ${shown}.`);
22390
24304
  }
@@ -22605,7 +24519,7 @@ function program(ctx) {
22605
24519
  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));
22606
24520
  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));
22607
24521
  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));
22608
- cli.command("rm").argument("<task>", "like MON-12").description("Delete a task (asks first)").option("-y, --yes", "don't ask").addOption(json()).action(async (ref, options) => rm$1(await ctx(), ref, options));
24522
+ cli.command("rm").argument("<task>", "like MON-12").description("Delete a task (asks first)").option("-y, --yes", "don't ask").addOption(json()).action(async (ref, options) => rm(await ctx(), ref, options));
22609
24523
  cli.command("tag").argument("<task>", "like MON-12").argument("<tags...>", "tag names (a new name makes a tag in the task's project)").description("Put tags on a task").addOption(json()).action(async (ref, names, options) => tag(await ctx(), ref, names, options));
22610
24524
  cli.command("untag").argument("<task>", "like MON-12").argument("<tags...>", "tag names").description("Take tags off a task").addOption(json()).action(async (ref, names, options) => untag(await ctx(), ref, names, options));
22611
24525
  cli.command("attach").argument("[task]", "like MON-12 (else the one this branch is named after: mon-12-…)").argument("[link]", "a pull request, an issue, a commit, or any page").description("Attach a link to a task (again: refresh it); --pr attaches this branch's pull request").option("--pr", "this branch's pull request, with its title and state (needs gh)").option("--title <text>", "its title (a pull request's or an issue's comes from gh)").addOption(json()).action(async (task, link, options) => attach(await ctx(), [task, link].filter((a) => a !== void 0), options));
@@ -22615,8 +24529,8 @@ function program(ctx) {
22615
24529
  notes.command("show", { isDefault: true }).description("Print the notes (the default)").addOption(project()).addOption(json()).action(async (options) => notesShow(await ctx(), options));
22616
24530
  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));
22617
24531
  notes.command("edit").description("Edit the notes in $EDITOR").addOption(project()).addOption(json()).action(async (options) => notesEdit(await ctx(), options));
22618
- 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));
22619
- const runnerCommand = cli.command("runner").description("Run coding agents on this machine for the runs you start from the board, in the background: status, stop, restart, logs").enablePositionalOptions().option("--name <name>", "what the board calls this machine (default: its hostname)").option("--interval <seconds>", "how often to ask for work while idle (default 60; every 5 while a run is going)").option("--allow <folder>", "only run in this folder or below (repeat for more)", collect).option("--confirm", "ask here before starting each run (so it runs in this terminal)").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("--foreground", "run in this terminal, until Ctrl-C, instead of in the background").option("--once", "take one run (if one is waiting), then stop (in this terminal)").addHelpText("after", `
24532
+ 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(await ctx(), ref, options));
24533
+ const runnerCommand = cli.command("runner").description("Run coding agents on this machine for the runs you start from the board, in the background: status, stop, restart, logs").enablePositionalOptions().option("--name <name>", "what the board calls this machine (default: its hostname)").option("--interval <seconds>", "how often to ask for work while idle (default 60; every 5 while a run is going)").option("--allow <folder>", "only run in this folder or below (repeat for more)", collect).option("--confirm", "ask here before starting each run (so it runs in this terminal)").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("--no-loops", "run no agent loops here, only the runs you start (loops are on by default)").option("--foreground", "run in this terminal, until Ctrl-C, instead of in the background").option("--once", "take one run (if one is waiting), then stop (in this terminal)").addHelpText("after", `
22620
24534
  It starts in the background and keeps running when this terminal closes (not when you sign out or the machine
22621
24535
  restarts): \`monoban runner status\` shows it, \`monoban runner logs\` what it says, \`monoban runner stop\` stops it.
22622
24536
  A run works in the folder it was given, which must be a checkout of the task's project: its origin is the
@@ -22626,7 +24540,9 @@ in its sandbox). For Claude Code and Codex the runner makes the task's branch, c
22626
24540
  pushes, opens the pull request with gh and comments on the task. Codex keeps its sandbox unless this
22627
24541
  machine allows a run to turn it off. Settings can also go in runner.json in the config folder:
22628
24542
  {"pollSeconds": 60, "allow": ["/Users/me/code"], "confirm": false, "agents": ["claude"],
22629
- "adapters": {"claude": {"command": "claude", "args": []}, "codex": {"allowFullAccess": false}}}.`).action(async (options) => runner(await ctx(), options));
24543
+ "adapters": {"claude": {"command": "claude", "args": []}, "codex": {"allowFullAccess": false}},
24544
+ "loops": {"enabled": true, "merge": true, "maxUsdPerDay": 100}}. Agent loops (made in the browser) run here
24545
+ too when agentpipe can run them: --no-loops, or "enabled": false, says no; "merge": false never merges here.`).action(async (options) => runner(await ctx(), options));
22630
24546
  runnerCommand.command("status").description("This machine's runners: running or not, the run going on, what the board sees, why one stopped").option("--name <name>", "only this runner").addOption(json()).action(async (options) => runnerStatus(await ctx(), options));
22631
24547
  runnerCommand.command("stop").description("Stop this machine's runners (a run going on is cancelled; asks first)").option("--name <name>", "only this runner").option("--wait", "let the run going on finish first, then stop").option("-y, --yes", "don't ask before cancelling a run").action(async (options) => runnerStop(await ctx(), options));
22632
24548
  runnerCommand.command("restart").description("Stop the runner and start it again in the background, with the same flags (after an upgrade)").option("--name <name>", "which runner, when there are several").option("-y, --yes", "don't ask before cancelling a run").action(async (options) => runnerRestart(await ctx(), options));
@@ -22641,6 +24557,8 @@ machine allows a run to turn it off. Settings can also go in runner.json in the
22641
24557
  "full"
22642
24558
  ])).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));
22643
24559
  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));
24560
+ cli.command("loops").description("List a project's agent loops and what each is doing (make, change and resume them in the browser)").addOption(project()).addOption(json()).action(async (options) => loops(await ctx(), options));
24561
+ cli.command("loop").description("An agent loop: pause it (resume it in the browser)").command("pause").argument("<name>", "the loop's name, as `monoban loops` lists it").description("Pause a loop: it starts no new run until you resume it in the browser").addOption(project()).addOption(json()).action(async (name, options) => loopPause(await ctx(), name, options));
22644
24562
  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", `
22645
24563
  It goes in ~/.claude/skills/monoban (Claude Code) or ~/.agents/skills/monoban (Codex); with --project,
22646
24564
  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));