@discovery-tree/runner 0.1.21 → 0.1.23

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 +30 -16
  2. package/dist/cli.js +362 -40
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -86,21 +86,24 @@ readable only by you (mode 0600) because it holds the runner token. `login` writ
86
86
  }
87
87
  ```
88
88
 
89
- | Option | Default | Meaning |
90
- | ------------------------------ | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |
91
- | `maxSessions` | `2` | Sessions with a running Claude Code at once (1 to 64). Further starts are refused as busy and retried by the server. `--max-sessions` overrides it. |
92
- | `maxJobs` | `2` | [Jobs](#jobs) run at once (1 to 16), apart from sessions. `--max-jobs` overrides it. |
93
- | `reposDir` | `$XDG_DATA_HOME/discovery-tree/runner/repos` | Clone cache. `--repos-dir` overrides it. |
94
- | `worktreesDir` | `$XDG_DATA_HOME/discovery-tree/runner/worktrees` | One worktree per session. |
95
- | `permissionMode` | `auto` | Claude Code `--permission-mode`. See below. |
96
- | `allowedTools` | a development allow-list | Replaces the default `--allowedTools` list. |
97
- | `extraAllowedTools` | `[]` | Added to the allow-list. |
98
- | `disallowedTools` | credential locations (see below) | Replaces the default `--disallowedTools` deny list. Deny rules win over the allow-list. |
99
- | `extraDisallowedTools` | `[]` | Added to the deny list. |
100
- | `loadProjectSettings` | `false` | `true` lets Claude Code load the repository's own `.claude/settings.json` / `settings.local.json` (hooks, permissions). See below. |
101
- | `inheritClaudeCodePermissions` | `true` | Start each run with the permission rules you approved in your own Claude Code for that repository (see below). `false` turns it off. |
102
- | `gitProtocol` | `https` | `ssh` clones `git@github.com:owner/repo.git` instead. The cached clone's `origin` URL is rewritten to match on every session start (see below). |
103
- | `idleTimeoutMinutes` | `15` | An idle Claude Code process is ended after this long; the next message resumes it. |
89
+ | Option | Default | Meaning |
90
+ | ------------------------------ | ------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- |
91
+ | `maxSessions` | `2` | Sessions with a running Claude Code at once (1 to 64). Further starts are refused as busy and retried by the server. `--max-sessions` overrides it. |
92
+ | `maxJobs` | `2` | [Jobs](#jobs) run at once (1 to 16), apart from sessions. `--max-jobs` overrides it. |
93
+ | `jobLogRetentionDays` | `30` | Days an ended job's log files are kept (0: for good). `--job-log-retention-days` overrides it. See [Jobs](#jobs). |
94
+ | `jobDataRetentionDays` | `0` (kept for good) | Days an ended job's data folder is kept (0: for good). `--job-data-retention-days` overrides it. |
95
+ | `jobShell` | `powershell` | Windows only: the shell jobs run in: `powershell` (5.1, no `&&`), `pwsh` (PowerShell 7) or `cmd`. Not on the PATH: jobs are refused. `--job-shell` overrides it. |
96
+ | `reposDir` | `$XDG_DATA_HOME/discovery-tree/runner/repos` | Clone cache. `--repos-dir` overrides it. |
97
+ | `worktreesDir` | `$XDG_DATA_HOME/discovery-tree/runner/worktrees` | One worktree per session. |
98
+ | `permissionMode` | `auto` | Claude Code `--permission-mode`. See below. |
99
+ | `allowedTools` | a development allow-list | Replaces the default `--allowedTools` list. |
100
+ | `extraAllowedTools` | `[]` | Added to the allow-list. |
101
+ | `disallowedTools` | credential locations (see below) | Replaces the default `--disallowedTools` deny list. Deny rules win over the allow-list. |
102
+ | `extraDisallowedTools` | `[]` | Added to the deny list. |
103
+ | `loadProjectSettings` | `false` | `true` lets Claude Code load the repository's own `.claude/settings.json` / `settings.local.json` (hooks, permissions). See below. |
104
+ | `inheritClaudeCodePermissions` | `true` | Start each run with the permission rules you approved in your own Claude Code for that repository (see below). `false` turns it off. |
105
+ | `gitProtocol` | `https` | `ssh` clones `git@github.com:owner/repo.git` instead. The cached clone's `origin` URL is rewritten to match on every session start (see below). |
106
+ | `idleTimeoutMinutes` | `15` | An idle Claude Code process is ended after this long; the next message resumes it. |
104
107
 
105
108
  Environment variables: `DT_SERVER_URL` (server), `DT_RUNNER_TOKEN` (token; overrides the file),
106
109
  `DT_RUNNER_CLAUDE_BIN` (the `claude` binary to run).
@@ -354,10 +357,21 @@ it leaves it running (the session's worktree stays until the job ends, then goes
354
357
  - **Where it runs.** In the directory you approved, with the tree's environment over the
355
358
  runner's own (secrets in memory only, redacted from what is posted; never the runner's
356
359
  token). On macOS and Linux the command runs in `/bin/sh`, in a process group of its own; on
357
- Windows in Windows PowerShell (`powershell.exe`).
360
+ Windows in Windows PowerShell (`powershell.exe`) unless you set `jobShell` (below).
361
+ - **Its data folder.** Each job gets `<state>/jobs/<job id>/data/` (owner-only), its path in
362
+ `DT_JOB_DATA_DIR`, for what it produces (a recording, a report). It is outside every
363
+ session's checkout, so it stays when the checkout is removed (7 days after the job ends),
364
+ and a job taken up after a restart keeps it. Agents are told to write there, and to run
365
+ Python from a `.venv` in the folder the job runs in (`.venv/bin/python`, on Windows
366
+ `.venv\Scripts\python.exe`) rather than `python` from PATH.
358
367
  - **Its log.** Everything it writes is in `<state>/jobs/<job id>/stdout.log` and `stderr.log`
359
368
  (`dt-runner status` prints the state folder), kept after it ends. The runner posts the lines
360
369
  to Discovery Tree, which keeps the newest 2,000.
370
+ - **Cleaning up.** When the runner starts, and once a day after, it removes the log files of
371
+ jobs that ended more than `jobLogRetentionDays` ago (default 30; 0 keeps them) and whose
372
+ last report reached Discovery Tree, and logs what it removed. Their data folders are kept
373
+ unless you set `jobDataRetentionDays`; a job's small `job.json` record always stays. A job
374
+ still running, or still reporting, is never touched.
361
375
  - **Stopping it.** Stop it in Discovery Tree: the runner asks it to end (SIGTERM to its group;
362
376
  `taskkill /T` on Windows) and kills what is left of it 10 seconds later.
363
377
  - **The runner stopping.** Jobs keep running when the runner stops or restarts; the next
package/dist/cli.js CHANGED
@@ -469,7 +469,7 @@ function treeJobCwdProblem(cwd) {
469
469
  var MAX_JOB_REQUEST_PURPOSE_CHARS = 2e3;
470
470
  var MAX_JOB_REQUEST_EXPECT_SECONDS = 366 * 24 * 3600;
471
471
  var EXAMPLE_NAME = "Record Polymarket order books for 6 hours";
472
- var EXAMPLE_COMMAND = "python scripts/record_books.py --hours 6 --out data/books";
472
+ var EXAMPLE_COMMAND = '.venv/bin/python scripts/record_books.py --hours 6 --out "$DT_JOB_DATA_DIR/books"';
473
473
  var EXAMPLE_CHECKOUT = "/absolute/path/of/your/checkout";
474
474
  var JOB_REQUEST_INSTRUCTION = `## Jobs
475
475
 
@@ -486,7 +486,7 @@ cwd: .
486
486
  url: http://localhost:8000
487
487
  expect: 6h
488
488
  ---
489
- Records the order books the backtest reads from data/books.
489
+ Records order books into $DT_JOB_DATA_DIR/books, which the backtest reads.
490
490
  -->
491
491
 
492
492
  Rules:
@@ -496,6 +496,19 @@ Rules:
496
496
  directory. Say in your answer what you asked for; do not wait for it to start.
497
497
  - \`name\`: what it does, one line.
498
498
  - \`command\`: one line, exactly as you would type it in a shell here.
499
+ - Write what the job produces to the folder named by \`$DT_JOB_DATA_DIR\`
500
+ (\`$env:DT_JOB_DATA_DIR\` on Windows), not into your checkout: the job gets a data folder
501
+ of its own on this computer, which stays when the checkout is removed. Pass it in the
502
+ command (an output flag) or read it in the code, and have the job print the folder it
503
+ writes to as it starts, so its log says where the output is. It is set only for the job:
504
+ when you try the command here, set DT_JOB_DATA_DIR to a scratch folder first.
505
+ - Python: create a virtual environment in the folder the job runs in (\`cwd\`) during this
506
+ run (\`python3 -m venv .venv\`, then install with \`.venv/bin/pip\`) and call
507
+ \`.venv/bin/python\` (Windows \`.venv\\Scripts\\python.exe\`) directly in the command, never
508
+ \`python\` or \`python3\` from PATH: that may be another interpreter, without your packages,
509
+ or one the system refuses permission to run.
510
+ - The example is for macOS and Linux. On Windows the command runs in PowerShell:
511
+ \`.venv\\Scripts\\python.exe scripts\\record_books.py --hours 6 --out "$env:DT_JOB_DATA_DIR\\books"\`.
499
512
  - \`checkout\`: the absolute path of your checkout, as \`git rev-parse --show-toplevel\` prints
500
513
  it (or \`pwd\` in the folder you started in, when there is no repository).
501
514
  - \`cwd\`: where to run it, relative to \`checkout\`: \`.\` for its root. Never absolute, never
@@ -512,8 +525,9 @@ Rules:
512
525
  in a row the run is not told again, and the job says that automatic tries have stopped.
513
526
  A later run of the same job that exits cleanly starts that count over.
514
527
  - What the job writes in your checkout is kept for ${TREE_JOB_OUTPUT_KEPT_MS / 864e5} days after the job ends, then removed with
515
- the checkout. Say where its output goes (below \`---\`), and when it is done record where to
516
- find it, for example in a DT-RESULT block, so it is collected in time.
528
+ the checkout; its data folder stays. Say where its output goes (below \`---\`), and say in a
529
+ DT-RESULT block where to find it: in the job's data folder (its log names the path), and
530
+ where in it, so it is collected.
517
531
  - Do not write \`-->\` inside a block: it ends the block.`;
518
532
 
519
533
  // ../contracts/src/environments.ts
@@ -569,6 +583,7 @@ var ENV_SETUP_SCRIPT_MAX_LENGTH = 16 * 1024;
569
583
 
570
584
  // ../contracts/src/tree-autonomy.ts
571
585
  var MAX_AUTO_RETRY_DELAY_MINUTES = 24 * 60;
586
+ var MAX_AUTO_DECIDE_GRACE_MINUTES = 7 * 24 * 60;
572
587
 
573
588
  // ../contracts/src/shared-artifacts.ts
574
589
  var SHARED_ARTIFACT_TEXT_MAX_BYTES = 1024 * 1024;
@@ -660,8 +675,11 @@ function toolGrantRepositoryKey(url) {
660
675
  return `${m[1]}/${m[2]}`.toLowerCase();
661
676
  }
662
677
 
678
+ // ../contracts/src/run-activity.ts
679
+ var RUN_STUCK_TOOL_CALL_AFTER_MS = 15 * 6e4;
680
+
663
681
  // src/version.ts
664
- var RUNNER_VERSION = true ? "0.1.21" : "0.0.0-dev";
682
+ var RUNNER_VERSION = true ? "0.1.23" : "0.0.0-dev";
665
683
  var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
666
684
 
667
685
  // src/api.ts
@@ -3914,6 +3932,7 @@ function applyCursorPermissions(cwd, rules) {
3914
3932
  if (read === "unreadable") return;
3915
3933
  const hadPermissions = read !== null && isObject2(read.permissions);
3916
3934
  const hadAllow = hadPermissions && Array.isArray(read.permissions.allow);
3935
+ const hadDeny = hadPermissions && Array.isArray(read.permissions.deny);
3917
3936
  const config = read ?? {};
3918
3937
  const permissions = permissionsOf(config);
3919
3938
  const previous = new Set(marker?.added ?? []);
@@ -3925,10 +3944,19 @@ function applyCursorPermissions(cwd, rules) {
3925
3944
  }
3926
3945
  if (!keepOutOfCommits(cwd)) return;
3927
3946
  permissions.allow = [...own, ...added];
3947
+ if (permissions.deny === void 0) permissions.deny = [];
3928
3948
  config.permissions = permissions;
3929
3949
  const written = `${JSON.stringify(config, null, 2)}
3930
3950
  `;
3931
- const next = marker ? { ...marker, added, written } : { added, created: read === null, original: text, written, hadPermissions, hadAllow };
3951
+ const next = marker ? { ...marker, added, written } : {
3952
+ added,
3953
+ created: read === null,
3954
+ original: text,
3955
+ written,
3956
+ hadPermissions,
3957
+ hadAllow,
3958
+ hadDeny
3959
+ };
3932
3960
  mkdirSync(dirname4(file), { recursive: true });
3933
3961
  writeFileSync(join6(cwd, MARKER), `${JSON.stringify(next)}
3934
3962
  `);
@@ -3955,6 +3983,8 @@ function removeCursorPermissions(cwd) {
3955
3983
  const allow = allowOf(permissions).filter((r) => !added.has(r));
3956
3984
  if (allow.length || marker.hadAllow) permissions.allow = allow;
3957
3985
  else delete permissions.allow;
3986
+ const deny = permissions.deny;
3987
+ if (!marker.hadDeny && Array.isArray(deny) && deny.length === 0) delete permissions.deny;
3958
3988
  if (Object.keys(permissions).length || marker.hadPermissions)
3959
3989
  read.permissions = permissions;
3960
3990
  else delete read.permissions;
@@ -3990,18 +4020,31 @@ function readMarker(cwd) {
3990
4020
  try {
3991
4021
  const m = JSON.parse(readFileSync(join6(cwd, MARKER), "utf8"));
3992
4022
  if (!Array.isArray(m.added) || typeof m.written !== "string") return null;
4023
+ const original = typeof m.original === "string" ? m.original : null;
3993
4024
  return {
3994
4025
  added: m.added.filter((r) => typeof r === "string"),
3995
4026
  created: m.created === true,
3996
- original: typeof m.original === "string" ? m.original : null,
4027
+ original,
3997
4028
  written: m.written,
3998
4029
  hadPermissions: m.hadPermissions === true,
3999
- hadAllow: m.hadAllow === true
4030
+ hadAllow: m.hadAllow === true,
4031
+ // A marker from before the runner wrote `deny` (0.1.21) says nothing of it: the file as
4032
+ // it was before the runner first wrote it does.
4033
+ hadDeny: typeof m.hadDeny === "boolean" ? m.hadDeny : originalHadDeny(original)
4000
4034
  };
4001
4035
  } catch {
4002
4036
  return null;
4003
4037
  }
4004
4038
  }
4039
+ function originalHadDeny(original) {
4040
+ if (original === null) return false;
4041
+ try {
4042
+ const parsed = JSON.parse(original);
4043
+ return Array.isArray(parsed?.permissions?.deny);
4044
+ } catch {
4045
+ return false;
4046
+ }
4047
+ }
4005
4048
  var isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
4006
4049
  function readConfig(file) {
4007
4050
  if (!existsSync(file)) return null;
@@ -4096,6 +4139,9 @@ var cursorDriver = {
4096
4139
  if (cursorResumeNotFound(stderr)) {
4097
4140
  return " The Cursor chat to resume was not found on this computer.";
4098
4141
  }
4142
+ if (cursorConfigInvalid(stderr)) {
4143
+ return " The Cursor Agent CLI rejected a config file: check the worktree\u2019s `.cursor/cli.json` and `~/.cursor/cli-config.json` on the runner\u2019s computer (each `permissions` needs both `allow` and `deny` lists).";
4144
+ }
4099
4145
  return "";
4100
4146
  },
4101
4147
  resumeNotFound: (stderr) => cursorResumeNotFound(stderr)
@@ -4105,6 +4151,9 @@ function cursorResumeNotFound(text) {
4105
4151
  text
4106
4152
  );
4107
4153
  }
4154
+ function cursorConfigInvalid(text) {
4155
+ return /Invalid input: expected \w+, received \w+/.test(text);
4156
+ }
4108
4157
  function turnErrorMessage3(turn) {
4109
4158
  if (turn.isError && looksLikeCursorSignInFailure(turn.text)) {
4110
4159
  return `The Cursor Agent CLI could not sign in (${turn.text.slice(0, 200)}). ${cursorSignInFix()} Then send a message here to try again.`;
@@ -4400,6 +4449,10 @@ function configDirRules(configFile, platform = process.platform) {
4400
4449
  var DEFAULT_SERVER_URL = "https://discovery-tree-backend.onrender.com";
4401
4450
  var DEFAULT_MAX_SESSIONS = 2;
4402
4451
  var DEFAULT_IDLE_TIMEOUT_MINUTES = 15;
4452
+ var JOB_SHELLS = ["powershell", "pwsh", "cmd"];
4453
+ var DEFAULT_JOB_SHELL = "powershell";
4454
+ var DEFAULT_JOB_LOG_RETENTION_DAYS = 30;
4455
+ var JOB_RETENTION_DAYS_LIMIT = 3650;
4403
4456
  async function readConfigFile(file) {
4404
4457
  let raw;
4405
4458
  try {
@@ -4454,6 +4507,15 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
4454
4507
  `maxJobs must be a whole number from 1 to ${RUNNER_MAX_JOBS_LIMIT} (got ${maxJobs}).`
4455
4508
  );
4456
4509
  }
4510
+ const jobLogRetentionDays = retentionDays(
4511
+ "jobLogRetentionDays",
4512
+ overrides.jobLogRetentionDays ?? file?.jobLogRetentionDays ?? DEFAULT_JOB_LOG_RETENTION_DAYS
4513
+ );
4514
+ const jobDataRetentionDays = retentionDays(
4515
+ "jobDataRetentionDays",
4516
+ overrides.jobDataRetentionDays ?? file?.jobDataRetentionDays ?? 0
4517
+ );
4518
+ const jobShell = jobShellOf(overrides.jobShell ?? file?.jobShell);
4457
4519
  const inherit = file?.inheritClaudeCodePermissions;
4458
4520
  if (inherit !== void 0 && typeof inherit !== "boolean") {
4459
4521
  throw new Error(
@@ -4502,6 +4564,9 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
4502
4564
  name: file?.name ?? null,
4503
4565
  maxSessions,
4504
4566
  maxJobs,
4567
+ jobLogRetentionDays,
4568
+ jobDataRetentionDays,
4569
+ jobShell,
4505
4570
  reposDir: overrides.reposDir ?? file?.reposDir ?? join7(paths.dataDir, "repos"),
4506
4571
  worktreesDir: file?.worktreesDir ?? join7(paths.dataDir, "worktrees"),
4507
4572
  permissionMode: mode,
@@ -4521,6 +4586,29 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
4521
4586
  configFile: paths.configFile
4522
4587
  };
4523
4588
  }
4589
+ function jobShellOf(value) {
4590
+ if (value === void 0) return DEFAULT_JOB_SHELL;
4591
+ const name = typeof value === "string" ? value.trim().toLowerCase() : "";
4592
+ const shell = JOB_SHELLS.find((s) => s === name);
4593
+ if (!shell) {
4594
+ throw new Error(
4595
+ `jobShell must be one of ${JOB_SHELLS.join(", ")} (got ${typeof value === "string" ? `"${value}"` : JSON.stringify(value)}).`
4596
+ );
4597
+ }
4598
+ return shell;
4599
+ }
4600
+ function retentionDays(key, days) {
4601
+ if (!Number.isInteger(days) || days < 0 || days > JOB_RETENTION_DAYS_LIMIT) {
4602
+ throw new Error(
4603
+ `${key} must be a whole number of days from 0 (keep for good) to ${JOB_RETENTION_DAYS_LIMIT} (got ${days}).`
4604
+ );
4605
+ }
4606
+ return days;
4607
+ }
4608
+ function numberFlag(value) {
4609
+ if (value === void 0) return void 0;
4610
+ return value.trim() ? Number(value) : Number.NaN;
4611
+ }
4524
4612
 
4525
4613
  // src/daemon.ts
4526
4614
  import { join as join16 } from "node:path";
@@ -4648,7 +4736,7 @@ function reportableSessionIds(ids, onDropped = () => void 0) {
4648
4736
  // src/jobs/job-manager.ts
4649
4737
  import { randomBytes as randomBytes3, scrypt, timingSafeEqual } from "node:crypto";
4650
4738
  import { realpathSync } from "node:fs";
4651
- import { mkdir as mkdir6, readFile as readFile8, readdir as readdir2, stat as stat4 } from "node:fs/promises";
4739
+ import { mkdir as mkdir6, readFile as readFile8, readdir as readdir2, rm as rm6, stat as stat4 } from "node:fs/promises";
4652
4740
  import { basename, dirname as dirname8, isAbsolute as isAbsolute5, join as join11, resolve as resolve2, sep as sep3 } from "node:path";
4653
4741
 
4654
4742
  // src/environment.ts
@@ -5383,9 +5471,9 @@ var JobOutbox = class _JobOutbox {
5383
5471
 
5384
5472
  // src/jobs/job-process.ts
5385
5473
  import { execFile, spawn as spawn4 } from "node:child_process";
5386
- import { closeSync, openSync, readFileSync as readFileSync2, readdirSync } from "node:fs";
5474
+ import { closeSync, existsSync as existsSync2, openSync, readFileSync as readFileSync2, readdirSync } from "node:fs";
5387
5475
  import { readFile as readFile7, writeFile as writeFile4 } from "node:fs/promises";
5388
- import { dirname as dirname7, join as join10 } from "node:path";
5476
+ import { dirname as dirname7, join as join10, win32 } from "node:path";
5389
5477
 
5390
5478
  // src/lock.ts
5391
5479
  import { mkdir as mkdir5, open as open2, readFile as readFile6, rm as rm5 } from "node:fs/promises";
@@ -5448,6 +5536,31 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
5448
5536
 
5449
5537
  // src/jobs/job-process.ts
5450
5538
  var JOB_IS_WINDOWS = process.platform === "win32";
5539
+ function jobShellProgram(shell) {
5540
+ return shell === "cmd" ? "cmd.exe" : shell === "pwsh" ? "pwsh.exe" : "powershell.exe";
5541
+ }
5542
+ function findJobShell(shell, env = process.env) {
5543
+ const program = jobShellProgram(shell);
5544
+ const pathKey = Object.keys(env).find((k) => k.toLowerCase() === "path");
5545
+ const dirs = (pathKey ? env[pathKey] ?? "" : "").split(";").map((d) => d.trim().replace(/^"|"$/g, ""));
5546
+ const root = env.SystemRoot ?? env.SYSTEMROOT ?? env.windir;
5547
+ if (root) {
5548
+ const system32 = win32.join(root, "System32");
5549
+ if (shell === "cmd") dirs.push(system32);
5550
+ if (shell === "powershell") dirs.push(win32.join(system32, "WindowsPowerShell", "v1.0"));
5551
+ }
5552
+ for (const dir of dirs) {
5553
+ if (!dir) continue;
5554
+ const candidate = win32.join(dir, program);
5555
+ if (existsSync2(candidate)) return candidate;
5556
+ }
5557
+ return null;
5558
+ }
5559
+ function jobShellProblem(shell, env = process.env) {
5560
+ if (!JOB_IS_WINDOWS || findJobShell(shell, env)) return null;
5561
+ const others = ["powershell", "pwsh", "cmd"].filter((s) => s !== shell);
5562
+ return `The job shell "${shell}" (${jobShellProgram(shell)}) is not on this computer's PATH, so jobs are refused. Install it, or set jobShell to ${others.map((s) => `"${s}"`).join(" or ")} in the runner's config (or start with --job-shell).`;
5563
+ }
5451
5564
  var POWERSHELL_FLAGS = [
5452
5565
  "-NoLogo",
5453
5566
  "-NoProfile",
@@ -5489,29 +5602,58 @@ function powershellCommandScript(command) {
5489
5602
  "if ($dtRunnerOk) { exit 0 } elseif ($dtRunnerLast) { exit $dtRunnerLast } else { exit 1 }"
5490
5603
  ].join("\n");
5491
5604
  }
5492
- function powershellJobScript(commandFile, exitFile) {
5605
+ function powershellJobScript(commandFile, exitFile, host = "powershell.exe") {
5493
5606
  return [
5494
5607
  "$ErrorActionPreference = 'Continue'",
5495
5608
  "$ProgressPreference = 'SilentlyContinue'",
5496
5609
  "try { [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false } catch {}",
5497
- `& powershell.exe ${POWERSHELL_FLAGS.join(" ")} -File ${psQuote(commandFile)}`,
5610
+ `& ${psQuote(host)} ${POWERSHELL_FLAGS.join(" ")} -File ${psQuote(commandFile)}`,
5498
5611
  "$dtRunnerCode = $LASTEXITCODE",
5499
5612
  "if ($null -eq $dtRunnerCode) { $dtRunnerCode = 1 }",
5500
5613
  `try { [IO.File]::WriteAllText(${psQuote(exitFile)}, [string]$dtRunnerCode) } catch {}`,
5501
5614
  "exit $dtRunnerCode"
5502
5615
  ].join("\n");
5503
5616
  }
5617
+ function batchPath(path) {
5618
+ return path.replace(/%/g, "%%");
5619
+ }
5620
+ function cmdCommandScript(command) {
5621
+ return [
5622
+ "@echo off",
5623
+ "@chcp 65001 >nul",
5624
+ command.replace(/\r?\n/g, "\r\n"),
5625
+ "exit /b %ERRORLEVEL%",
5626
+ ""
5627
+ ].join("\r\n");
5628
+ }
5629
+ function cmdJobScript(commandFile, exitFile, cmdPath = "cmd.exe") {
5630
+ const tmp = `${exitFile}.tmp`;
5631
+ return [
5632
+ "@echo off",
5633
+ // Before any path: `cmd` reads this file in the OEM code page until then, and the state
5634
+ // folder may be under a user name with an accented letter.
5635
+ "@chcp 65001 >nul",
5636
+ `"${batchPath(cmdPath)}" /d /s /c ""${batchPath(commandFile)}""`,
5637
+ 'set "DT_RUNNER_CODE=%ERRORLEVEL%"',
5638
+ // The code is written next to the file and renamed, so a half-written one is never read.
5639
+ `>"${batchPath(tmp)}" echo %DT_RUNNER_CODE%`,
5640
+ `move /y "${batchPath(tmp)}" "${batchPath(exitFile)}" >nul`,
5641
+ "exit /b %DT_RUNNER_CODE%",
5642
+ ""
5643
+ ].join("\r\n");
5644
+ }
5504
5645
  function psLiteralPath(path) {
5505
5646
  return `([WildcardPattern]::Escape(${psQuote(path)}))`;
5506
5647
  }
5507
5648
  function windowsLauncherScript(input) {
5508
- const args = [...POWERSHELL_FLAGS, "-File", `"${input.scriptFile}"`].join(" ");
5649
+ const shell = input.shell ?? DEFAULT_JOB_SHELL;
5650
+ const args = shell === "cmd" ? ["/d", "/s", "/c", `""${input.scriptFile}""`].join(" ") : [...POWERSHELL_FLAGS, "-File", `"${input.scriptFile}"`].join(" ");
5509
5651
  return [
5510
5652
  "$ErrorActionPreference = 'Stop'",
5511
5653
  "$ProgressPreference = 'SilentlyContinue'",
5512
5654
  // Started here: Start-Process takes the current location as the job's directory.
5513
5655
  `Set-Location -LiteralPath ${psQuote(input.cwd)}`,
5514
- `$p = Start-Process -FilePath 'powershell.exe' -ArgumentList ${psQuote(args)} -NoNewWindow -PassThru -RedirectStandardOutput ${psLiteralPath(input.stdoutFile)} -RedirectStandardError ${psLiteralPath(input.stderrFile)}`,
5656
+ `$p = Start-Process -FilePath ${psQuote(input.shellPath ?? jobShellProgram(shell))} -ArgumentList ${psQuote(args)} -NoNewWindow -PassThru -RedirectStandardOutput ${psLiteralPath(input.stdoutFile)} -RedirectStandardError ${psLiteralPath(input.stderrFile)}`,
5515
5657
  // A command that is over already has no start time to read: now is close enough.
5516
5658
  "$dtRunnerAt = $null",
5517
5659
  "try { $dtRunnerAt = ([DateTimeOffset]$p.StartTime).ToUnixTimeMilliseconds() } catch { $dtRunnerAt = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() }",
@@ -5547,21 +5689,32 @@ async function spawnJob(input) {
5547
5689
  return { pid: child.pid, startedAt: Date.now() - 500, child, exited };
5548
5690
  }
5549
5691
  async function spawnWindowsJob(input) {
5692
+ const shell = input.shell ?? DEFAULT_JOB_SHELL;
5693
+ const shellPath = findJobShell(shell, process.env);
5694
+ if (!shellPath) throw new Error(jobShellProblem(shell, process.env) ?? `${shell} was not found.`);
5550
5695
  const dir = dirname7(input.exitFile);
5551
- const scriptFile = join10(dir, "job.ps1");
5552
- const commandFile = join10(dir, "command.ps1");
5553
- const bom = "\uFEFF";
5554
- await writeFile4(commandFile, bom + powershellCommandScript(input.command), { mode: 384 });
5696
+ const cmd = shell === "cmd";
5697
+ const scriptFile = join10(dir, cmd ? "job.cmd" : "job.ps1");
5698
+ const commandFile = join10(dir, cmd ? "command.cmd" : "command.ps1");
5699
+ if (cmd) {
5700
+ await writeFile4(commandFile, cmdCommandScript(input.command), { mode: 384 });
5701
+ } else {
5702
+ await writeFile4(commandFile, "\uFEFF" + powershellCommandScript(input.command), {
5703
+ mode: 384
5704
+ });
5705
+ }
5555
5706
  for (const f of [input.stdoutFile, input.stderrFile]) await writeFile4(f, "", { flag: "a" });
5556
- await writeFile4(scriptFile, bom + powershellJobScript(commandFile, input.exitFile), {
5557
- mode: 384
5558
- });
5707
+ await writeFile4(
5708
+ scriptFile,
5709
+ cmd ? cmdJobScript(commandFile, input.exitFile, shellPath) : "\uFEFF" + powershellJobScript(commandFile, input.exitFile, shellPath),
5710
+ { mode: 384 }
5711
+ );
5559
5712
  const launcher = spawn4(
5560
5713
  "powershell.exe",
5561
5714
  [
5562
5715
  ...POWERSHELL_FLAGS,
5563
5716
  "-EncodedCommand",
5564
- encoded(windowsLauncherScript({ ...input, scriptFile }))
5717
+ encoded(windowsLauncherScript({ ...input, scriptFile, shell, shellPath }))
5565
5718
  ],
5566
5719
  // Piped (nothing inherited), so Node gives it a console without a window.
5567
5720
  { cwd: input.cwd, env: input.env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
@@ -5762,6 +5915,9 @@ var CENSUS_INTERVAL_MS2 = 3e4;
5762
5915
  var JOB_SECRETS_WAIT_MS = 9e4;
5763
5916
  var JOB_SECRETS_END_WAIT_MS = 12e4;
5764
5917
  var JOB_LOST_POSTING_MS = RUNNER_JOB_MISSING_GRACE_MS + 3e4;
5918
+ var JOB_DATA_DIR_NAME = "data";
5919
+ var JOB_DATA_DIR_ENV = "DT_JOB_DATA_DIR";
5920
+ var JOB_PRUNE_INTERVAL_MS = 24 * 36e5;
5765
5921
  function secretWait() {
5766
5922
  let end = () => void 0;
5767
5923
  const over = new Promise((resolve4) => end = resolve4);
@@ -5771,6 +5927,8 @@ var JobManager = class {
5771
5927
  constructor(opts) {
5772
5928
  this.opts = opts;
5773
5929
  this.root = join11(opts.stateDir, "jobs");
5930
+ const problem = this.shellProblem();
5931
+ if (problem) opts.logger.error(problem);
5774
5932
  }
5775
5933
  jobs = /* @__PURE__ */ new Map();
5776
5934
  /** Folders being removed now, with how many removals hold each (see `holdForRemoval`). */
@@ -5783,15 +5941,33 @@ var JobManager = class {
5783
5941
  queues = /* @__PURE__ */ new Map();
5784
5942
  timer = null;
5785
5943
  censusTimer = null;
5944
+ pruneTimer = null;
5945
+ /** The prune under way, so prunes never overlap. */
5946
+ pruning = null;
5786
5947
  ticking = false;
5787
5948
  shuttingDown = false;
5788
5949
  /** Resolves when the runner begins to stop: an end waiting for secrets waits no more. */
5789
5950
  stopped = secretWait();
5790
5951
  root;
5952
+ /** Why jobs cannot run in the job shell (not on the PATH), when they cannot. */
5953
+ shellProblem() {
5954
+ return (this.opts.checkJobShell ?? ((s) => jobShellProblem(s)))(this.shell);
5955
+ }
5956
+ get shell() {
5957
+ return this.opts.jobShell ?? DEFAULT_JOB_SHELL;
5958
+ }
5791
5959
  /** The folder a job's record, log and outbox live in. */
5792
5960
  jobDir(jobId) {
5793
5961
  return join11(this.root, jobId);
5794
5962
  }
5963
+ /**
5964
+ * The folder a job writes its output to (`DT_JOB_DATA_DIR`): its own, apart from any
5965
+ * session's checkout, so it outlives the session's cleanup. Pruned only when the runner's
5966
+ * owner set `jobDataRetentionDays`.
5967
+ */
5968
+ jobDataDir(jobId) {
5969
+ return join11(this.jobDir(jobId), JOB_DATA_DIR_NAME);
5970
+ }
5795
5971
  /**
5796
5972
  * Jobs the runner reports in `activeJobIds`: a live process, or an end not yet reported.
5797
5973
  * Not a start still under way: the server takes a listed job as up, settling its
@@ -5903,6 +6079,106 @@ var JobManager = class {
5903
6079
  }
5904
6080
  this.ensureTimers();
5905
6081
  }
6082
+ /**
6083
+ * Prunes settled jobs now, then once a day until the runner stops (see
6084
+ * {@link pruneSettledJobs}). Nothing to do when both retentions keep everything.
6085
+ */
6086
+ startPruning() {
6087
+ if (this.shuttingDown || this.pruneTimer || !this.pruneEnabled()) return;
6088
+ const run = () => void this.pruneSettledJobs().catch(() => void 0);
6089
+ run();
6090
+ this.pruneTimer = setInterval(run, JOB_PRUNE_INTERVAL_MS);
6091
+ this.pruneTimer.unref?.();
6092
+ }
6093
+ pruneEnabled() {
6094
+ return retentionMs(this.opts.logRetentionDays) !== null || retentionMs(this.opts.dataRetentionDays) !== null;
6095
+ }
6096
+ /**
6097
+ * Removes what settled jobs left past their retention, counted from when each ended:
6098
+ * their log files after `logRetentionDays` (everything in the job's folder but `job.json`
6099
+ * and `data/`), and their `data/` after `dataRetentionDays`, each only when set (0 or
6100
+ * unset keeps it). `job.json` stays, so a start delivered again is still answered from it.
6101
+ * A job that is not settled (running, or its last report still to go) is never touched.
6102
+ * Logs what it removed.
6103
+ */
6104
+ pruneSettledJobs(now = Date.now()) {
6105
+ if (this.pruning) return this.pruning;
6106
+ const run = this.prune(now).finally(() => {
6107
+ if (this.pruning === run) this.pruning = null;
6108
+ });
6109
+ this.pruning = run;
6110
+ return run;
6111
+ }
6112
+ async prune(now) {
6113
+ const result = { logs: [], data: [] };
6114
+ const logsMs = retentionMs(this.opts.logRetentionDays);
6115
+ const dataMs = retentionMs(this.opts.dataRetentionDays);
6116
+ if (logsMs === null && dataMs === null) return result;
6117
+ let entries = [];
6118
+ try {
6119
+ entries = await readdir2(this.root);
6120
+ } catch (err) {
6121
+ if (err.code !== "ENOENT") {
6122
+ this.opts.logger.warn("could not read the jobs folder to prune it", {
6123
+ error: err.message
6124
+ });
6125
+ }
6126
+ return result;
6127
+ }
6128
+ for (const entry of entries) {
6129
+ if (this.shuttingDown) break;
6130
+ if (!isRunnerSessionId(entry) || this.jobs.has(entry) || this.starting.has(entry)) continue;
6131
+ const dir = this.jobDir(entry);
6132
+ const record = await readJson(join11(dir, "job.json")).catch(() => null);
6133
+ if (!record || record.jobId !== entry || !record.settled) continue;
6134
+ const endedAt = Date.parse(record.ended?.at ?? record.createdAt);
6135
+ if (!Number.isFinite(endedAt)) continue;
6136
+ const age = now - endedAt;
6137
+ if (logsMs !== null && age > logsMs) {
6138
+ const files = await readdir2(dir).catch(() => []);
6139
+ const logs = files.filter((f) => f !== "job.json" && f !== JOB_DATA_DIR_NAME);
6140
+ const removed = await this.removeAll(
6141
+ entry,
6142
+ logs.map((f) => join11(dir, f))
6143
+ );
6144
+ if (removed.length) {
6145
+ result.logs.push(entry);
6146
+ this.opts.logger.info(
6147
+ `job ${entry}: removed its log files (${removed.join(", ")}), ended over ${this.opts.logRetentionDays} day(s) ago`
6148
+ );
6149
+ }
6150
+ }
6151
+ if (dataMs !== null && age > dataMs) {
6152
+ const dataDir = this.jobDataDir(entry);
6153
+ const exists3 = await stat4(dataDir).then(
6154
+ () => true,
6155
+ () => false
6156
+ );
6157
+ if (exists3 && (await this.removeAll(entry, [dataDir])).length) {
6158
+ result.data.push(entry);
6159
+ this.opts.logger.info(
6160
+ `job ${entry}: removed its data folder ${dataDir}, ended over ${this.opts.dataRetentionDays} day(s) ago`
6161
+ );
6162
+ }
6163
+ }
6164
+ }
6165
+ return result;
6166
+ }
6167
+ /** Removes each path (a folder with what is in it), returning the names of those that went. */
6168
+ async removeAll(jobId, paths) {
6169
+ const removed = [];
6170
+ for (const p of paths) {
6171
+ try {
6172
+ await rm6(p, { recursive: true, force: true });
6173
+ removed.push(basename(p));
6174
+ } catch (err) {
6175
+ this.opts.logger.warn(`job ${jobId}: could not remove ${p}`, {
6176
+ error: err.message
6177
+ });
6178
+ }
6179
+ }
6180
+ return removed;
6181
+ }
5906
6182
  async restoreJob(record, table) {
5907
6183
  const job = await this.openJob(record, null, null);
5908
6184
  if (record.ended) {
@@ -6030,7 +6306,9 @@ var JobManager = class {
6030
6306
  this.stopped.end();
6031
6307
  if (this.timer) clearInterval(this.timer);
6032
6308
  if (this.censusTimer) clearInterval(this.censusTimer);
6033
- this.timer = this.censusTimer = null;
6309
+ if (this.pruneTimer) clearInterval(this.pruneTimer);
6310
+ this.timer = this.censusTimer = this.pruneTimer = null;
6311
+ await this.pruning?.catch(() => void 0);
6034
6312
  await Promise.allSettled([...this.queues.values()]);
6035
6313
  await Promise.allSettled([...this.finishing]);
6036
6314
  const jobs = [...this.jobs.values()];
@@ -6059,6 +6337,8 @@ var JobManager = class {
6059
6337
  if (this.shuttingDown) {
6060
6338
  return { ok: false, retryable: true, error: "The runner is shutting down." };
6061
6339
  }
6340
+ const shellProblem = this.shellProblem();
6341
+ if (shellProblem) return { ok: false, error: shellProblem };
6062
6342
  const command = typeof cmd.command === "string" ? cmd.command : "";
6063
6343
  if (!command.trim() || command.includes("\0")) {
6064
6344
  return { ok: false, error: "The job has no command to run." };
@@ -6101,7 +6381,8 @@ var JobManager = class {
6101
6381
  const environment = sessionEnvironment(cmd.environment);
6102
6382
  const redactor = environment ? jobLineRedactor(environment) : null;
6103
6383
  const dir = this.jobDir(id);
6104
- await mkdir6(dir, { recursive: true, mode: 448 });
6384
+ const dataDir = this.jobDataDir(id);
6385
+ await mkdir6(dataDir, { recursive: true, mode: 448 });
6105
6386
  const record = {
6106
6387
  jobId: id,
6107
6388
  name,
@@ -6124,7 +6405,7 @@ var JobManager = class {
6124
6405
  }
6125
6406
  }
6126
6407
  await saveRecord(dir, record);
6127
- this.opts.logger.info(`job ${id}: starting "${name}"`, { cwd });
6408
+ this.opts.logger.info(`job ${id}: starting "${name}"`, { cwd, dataDir });
6128
6409
  const shortLines = environment ? secretsWithShortLines(environment) : [];
6129
6410
  if (environment?.unredacted.length || shortLines.length) {
6130
6411
  this.opts.logger.warn(
@@ -6136,7 +6417,11 @@ var JobManager = class {
6136
6417
  `job ${id}: left out of the job's environment (not a name it may set): ${environment.skipped.slice(0, 20).join(", ")}`
6137
6418
  );
6138
6419
  }
6139
- const env = { ...process.env, ...environment?.env };
6420
+ const env = {
6421
+ ...process.env,
6422
+ ...environment?.env,
6423
+ [JOB_DATA_DIR_ENV]: resolve2(dataDir)
6424
+ };
6140
6425
  delete env.DT_RUNNER_TOKEN;
6141
6426
  let started;
6142
6427
  try {
@@ -6146,7 +6431,8 @@ var JobManager = class {
6146
6431
  env,
6147
6432
  stdoutFile: join11(dir, "stdout.log"),
6148
6433
  stderrFile: join11(dir, "stderr.log"),
6149
- exitFile: join11(dir, "exit-code")
6434
+ exitFile: join11(dir, "exit-code"),
6435
+ shell: this.shell
6150
6436
  });
6151
6437
  } catch (err) {
6152
6438
  const error = safeError(err, redactor);
@@ -6485,7 +6771,7 @@ var JobManager = class {
6485
6771
  }
6486
6772
  signalGroup2(tree.pid, "SIGKILL");
6487
6773
  }
6488
- /** Its last report is through: the job is let go (its folder and log stay). */
6774
+ /** Its last report is through: the job is let go (its folder and log stay, until pruned). */
6489
6775
  async settle(job) {
6490
6776
  if (this.jobs.get(job.record.jobId) !== job || job.phase !== "ended") return;
6491
6777
  this.jobs.delete(job.record.jobId);
@@ -6679,6 +6965,9 @@ function queueEndReport(outbox, ended) {
6679
6965
  ended.status === "stopped" ? { status: "stopped", exitCode: ended.exitCode, signal: ended.signal } : { status: "exited", exitCode: ended.exitCode, signal: ended.signal }
6680
6966
  );
6681
6967
  }
6968
+ function retentionMs(days) {
6969
+ return typeof days === "number" && Number.isFinite(days) && days > 0 ? days * 864e5 : null;
6970
+ }
6682
6971
  async function saveRecord(dir, record) {
6683
6972
  await writeJsonAtomic(join11(dir, "job.json"), record);
6684
6973
  }
@@ -6696,8 +6985,8 @@ function safeError(err, redactor) {
6696
6985
  }
6697
6986
 
6698
6987
  // src/session-manager.ts
6699
- import { existsSync as existsSync2, lstatSync } from "node:fs";
6700
- import { mkdir as mkdir9, rm as rm7, writeFile as writeFile6 } from "node:fs/promises";
6988
+ import { existsSync as existsSync3, lstatSync } from "node:fs";
6989
+ import { mkdir as mkdir9, rm as rm8, writeFile as writeFile6 } from "node:fs/promises";
6701
6990
  import { basename as basename3, dirname as dirname11, join as join15, resolve as resolve3 } from "node:path";
6702
6991
 
6703
6992
  // src/prompt-images.ts
@@ -7460,7 +7749,7 @@ function ghError(command, res) {
7460
7749
  }
7461
7750
 
7462
7751
  // src/session-store.ts
7463
- import { mkdir as mkdir8, readdir as readdir3, rm as rm6 } from "node:fs/promises";
7752
+ import { mkdir as mkdir8, readdir as readdir3, rm as rm7 } from "node:fs/promises";
7464
7753
  import { join as join14 } from "node:path";
7465
7754
  var HANDLED_COMMAND_IDS_KEPT = 100;
7466
7755
  var pendingWrites = /* @__PURE__ */ new Map();
@@ -7506,7 +7795,7 @@ var SessionStore = class {
7506
7795
  }
7507
7796
  async remove(sessionId) {
7508
7797
  await pendingWrites.get(join14(this.dir(sessionId), "session.json"));
7509
- await rm6(this.dir(sessionId), { recursive: true, force: true });
7798
+ await rm7(this.dir(sessionId), { recursive: true, force: true });
7510
7799
  }
7511
7800
  /** Scratch working directory for a session without a repository. */
7512
7801
  scratchDir(sessionId) {
@@ -9006,9 +9295,9 @@ var SessionManager = class {
9006
9295
  dir: fromEntry.dir,
9007
9296
  repoDir: fromEntry.repoDir
9008
9297
  } : void 0);
9009
- const keptReference = candidate && existsSync2(candidate.dir) ? candidate : void 0;
9298
+ const keptReference = candidate && existsSync3(candidate.dir) ? candidate : void 0;
9010
9299
  const referenceHold = !reference?.url ? null : this.opts.jobs ? this.opts.jobs.holdForRemoval(referenceDir) : () => void 0;
9011
- if (reference?.url && keepWorkspace && (keptReference || existsSync2(referenceDir))) {
9300
+ if (reference?.url && keepWorkspace && (keptReference || existsSync3(referenceDir))) {
9012
9301
  if (keptReference) record.referenceRepository = keptReference;
9013
9302
  referenceHold?.();
9014
9303
  this.opts.logger.info(
@@ -9324,7 +9613,7 @@ var SessionManager = class {
9324
9613
  })
9325
9614
  );
9326
9615
  }
9327
- await rm7(w.cwd, { recursive: true, force: true }).catch(() => void 0);
9616
+ await rm8(w.cwd, { recursive: true, force: true }).catch(() => void 0);
9328
9617
  }
9329
9618
  }
9330
9619
  keptFile() {
@@ -9592,6 +9881,9 @@ var RunnerDaemon = class {
9592
9881
  this.jobs = new JobManager({
9593
9882
  stateDir: opts.config.stateDir,
9594
9883
  maxJobs: opts.config.maxJobs,
9884
+ jobShell: opts.config.jobShell,
9885
+ logRetentionDays: opts.config.jobLogRetentionDays,
9886
+ dataRetentionDays: opts.config.jobDataRetentionDays,
9595
9887
  poster: this.api,
9596
9888
  logger: opts.logger,
9597
9889
  onUnauthorized: (err) => this.unauthorized(err),
@@ -9668,6 +9960,7 @@ var RunnerDaemon = class {
9668
9960
  await this.jobs.restore();
9669
9961
  await this.manager.restore();
9670
9962
  await this.manager.releaseKeptForJobs();
9963
+ this.jobs.startPruning();
9671
9964
  logger.info(`dt-runner ${RUNNER_VERSION} connected to ${config.server}`, {
9672
9965
  maxSessions: config.maxSessions,
9673
9966
  maxJobs: config.maxJobs,
@@ -10271,9 +10564,15 @@ Usage:
10271
10564
  dt-runner login [--server <url>] [--name <name>] [--no-browser] [--yes]
10272
10565
  Pair this computer with your Discovery Tree account.
10273
10566
  --yes skips the "is this your account?" question.
10274
- dt-runner start [--max-sessions <n>] [--max-jobs <n>] [--repos-dir <dir>] [--json] [--verbose]
10567
+ dt-runner start [--max-sessions <n>] [--max-jobs <n>] [--job-log-retention-days <n>]
10568
+ [--job-data-retention-days <n>] [--job-shell powershell|pwsh|cmd]
10569
+ [--repos-dir <dir>] [--json] [--verbose]
10275
10570
  Run: wait for agent sessions and run them with Claude Code,
10276
10571
  and run the jobs you approve (up to --max-jobs at once).
10572
+ Ended jobs' logs are removed after --job-log-retention-days
10573
+ (default 30; 0 keeps them), their data folders after
10574
+ --job-data-retention-days (default 0: kept).
10575
+ On Windows, jobs run in --job-shell (default powershell).
10277
10576
  dt-runner status Show the configuration and check the connection.
10278
10577
  dt-runner doctor Check Node.js, git and Claude Code on this computer.
10279
10578
  dt-runner logout Forget this runner's token (deletes the config file).
@@ -10304,6 +10603,9 @@ async function main(argv) {
10304
10603
  yes: { type: "boolean", short: "y" },
10305
10604
  "max-sessions": { type: "string" },
10306
10605
  "max-jobs": { type: "string" },
10606
+ "job-log-retention-days": { type: "string" },
10607
+ "job-data-retention-days": { type: "string" },
10608
+ "job-shell": { type: "string" },
10307
10609
  "repos-dir": { type: "string" },
10308
10610
  json: { type: "boolean" },
10309
10611
  verbose: { type: "boolean" },
@@ -10325,8 +10627,11 @@ async function main(argv) {
10325
10627
  return login(values.server, values.name, !values["no-browser"], values.yes === true);
10326
10628
  case "start":
10327
10629
  return start({
10328
- maxSessions: values["max-sessions"] !== void 0 ? Number(values["max-sessions"]) : void 0,
10329
- maxJobs: values["max-jobs"] !== void 0 ? Number(values["max-jobs"]) : void 0,
10630
+ maxSessions: numberFlag(values["max-sessions"]),
10631
+ maxJobs: numberFlag(values["max-jobs"]),
10632
+ jobLogRetentionDays: numberFlag(values["job-log-retention-days"]),
10633
+ jobDataRetentionDays: numberFlag(values["job-data-retention-days"]),
10634
+ jobShell: values["job-shell"],
10330
10635
  reposDir: values["repos-dir"],
10331
10636
  json: values.json,
10332
10637
  verbose: values.verbose
@@ -10409,11 +10714,20 @@ async function login(server, name, openBrowser, yes) {
10409
10714
  async function start(opts) {
10410
10715
  const logger = createLogger({ json: opts.json, verbose: opts.verbose });
10411
10716
  const paths = runnerPaths();
10412
- const config = resolveConfig(await readConfigFile(paths.configFile), {
10717
+ const file = await readConfigFile(paths.configFile);
10718
+ const config = resolveConfig(file, {
10413
10719
  maxSessions: opts.maxSessions,
10414
10720
  maxJobs: opts.maxJobs,
10721
+ jobLogRetentionDays: opts.jobLogRetentionDays,
10722
+ jobDataRetentionDays: opts.jobDataRetentionDays,
10723
+ jobShell: opts.jobShell,
10415
10724
  reposDir: opts.reposDir
10416
10725
  });
10726
+ if (process.platform !== "win32" && (opts.jobShell !== void 0 || file?.jobShell !== void 0)) {
10727
+ logger.warn(
10728
+ `jobShell "${config.jobShell}" is ignored: jobs run in /bin/sh here. It only chooses the shell on Windows.`
10729
+ );
10730
+ }
10417
10731
  if (!config.token) {
10418
10732
  logger.error(`This computer is not paired yet. Run \`${runnerCommand("login")}\` first.`);
10419
10733
  return 1;
@@ -10493,6 +10807,9 @@ async function start(opts) {
10493
10807
  logger.info("dt-runner stopped");
10494
10808
  return exit === "unauthorized" ? 1 : 0;
10495
10809
  }
10810
+ function keptFor(days) {
10811
+ return days > 0 ? `kept ${days} day(s)` : "kept for good";
10812
+ }
10496
10813
  async function status() {
10497
10814
  const paths = runnerPaths();
10498
10815
  const file = await readConfigFile(paths.configFile);
@@ -10509,6 +10826,11 @@ async function status() {
10509
10826
  `Sessions: up to ${config.maxSessions} at once, permission mode ${config.permissionMode}`
10510
10827
  );
10511
10828
  console.log(`Jobs: up to ${config.maxJobs} at once`);
10829
+ console.log(`Job logs: ${keptFor(config.jobLogRetentionDays)} after a job ends`);
10830
+ console.log(`Job data: ${keptFor(config.jobDataRetentionDays)} after a job ends`);
10831
+ console.log(
10832
+ `Job shell: ${process.platform === "win32" ? config.jobShell : `/bin/sh (jobShell "${config.jobShell}" only applies on Windows)`}`
10833
+ );
10512
10834
  console.log(`Repos: ${config.reposDir}`);
10513
10835
  console.log(`Worktrees: ${config.worktreesDir}`);
10514
10836
  console.log(`State: ${config.stateDir}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@discovery-tree/runner",
3
- "version": "0.1.21",
3
+ "version": "0.1.23",
4
4
  "description": "dt-runner: run Discovery Tree agent sessions on your own computer with your own signed-in Claude Code",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {