@discovery-tree/runner 0.1.20 → 0.1.22

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 +46 -10
  2. package/dist/cli.js +917 -111
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -28,6 +28,47 @@ var AGENT_WORK_IDLE_AFTER_MS = 24 * 60 * 60 * 1e3;
28
28
  var DEFAULT_TASK_MODEL_MAX_LENGTH = 32 + 1 + AI_CATEGORY_MODEL_MAX_LENGTH;
29
29
 
30
30
  // ../contracts/src/ui-evidence.ts
31
+ var TRUSTED_SCREENSHOT_HOSTS = [
32
+ "user-images.githubusercontent.com",
33
+ "private-user-images.githubusercontent.com",
34
+ "raw.githubusercontent.com",
35
+ "objects.githubusercontent.com",
36
+ "media.githubusercontent.com"
37
+ ];
38
+ var GITHUB_ATTACHMENT_PATH = /^\/user-attachments\/assets\/[\w.-]+$/;
39
+ var GITHUB_RAW_FILE_PATH = /^\/([\w.-]+)\/([\w.-]+)\/raw\/([0-9a-f]{40})\/((?:[\w.%-]+\/)*[\w.%-]+)$/;
40
+ function githubRawContentUrl(url) {
41
+ if (!url) return null;
42
+ let parsed;
43
+ try {
44
+ parsed = new URL(url.trim());
45
+ } catch {
46
+ return null;
47
+ }
48
+ if (parsed.protocol !== "https:" || parsed.hostname.toLowerCase() !== "github.com") return null;
49
+ if (parsed.search || parsed.hash) return null;
50
+ const m = GITHUB_RAW_FILE_PATH.exec(parsed.pathname);
51
+ if (!m || m[4].split("/").some((seg) => seg === "." || seg === "..")) return null;
52
+ return `https://raw.githubusercontent.com/${m[1]}/${m[2]}/${m[3]}/${m[4]}`;
53
+ }
54
+ var CURSOR_ARTIFACT_HOST = "cursor.com";
55
+ var CURSOR_ARTIFACT_PATH = /^\/artifacts\/[\w.-]+\/[\w.-]+$/;
56
+ function isTrustedScreenshotUrl(url) {
57
+ if (!url) return false;
58
+ let parsed;
59
+ try {
60
+ parsed = new URL(url.trim());
61
+ } catch {
62
+ return false;
63
+ }
64
+ if (parsed.protocol !== "https:") return false;
65
+ const host = parsed.hostname.toLowerCase();
66
+ if (host === "github.com") {
67
+ return GITHUB_ATTACHMENT_PATH.test(parsed.pathname) || githubRawContentUrl(url) !== null;
68
+ }
69
+ if (host === CURSOR_ARTIFACT_HOST) return CURSOR_ARTIFACT_PATH.test(parsed.pathname);
70
+ return TRUSTED_SCREENSHOT_HOSTS.includes(host);
71
+ }
31
72
  var UI_EVIDENCE_EXPECTATION = [
32
73
  "Visual evidence (required for user-visible changes): if your change alters anything a person sees or interacts with \u2014 a component, layout, styling, copy, empty state, or navigation \u2014 capture a screenshot of the change and embed it in the pull request description using markdown image syntax. Attach one image per state you changed, including before/after when the change modifies existing UI, and both themes when the product has light and dark.",
33
74
  "Prefer uploading images to the pull request itself (drag-and-drop or the GitHub attachment endpoint) so they are served from GitHub. If your platform hosts the screenshots it captures and cannot upload them, embed its own artifact address instead of dropping the evidence \u2014 that is shown to reviewers too, provided the host is one the workspace already trusts. An image on some other third-party host is not shown, so do not settle for one. Write a short caption in the alt text saying what the image shows.",
@@ -89,14 +130,85 @@ Rules:
89
130
  - For an \`ai\` task, rate \`complexity\` and \`impact\` (low, medium, high) with a one-line
90
131
  \`model_reason\`; they choose the model it runs on.`;
91
132
 
133
+ // ../contracts/src/destination-outcome.ts
134
+ var DESTINATION_OUTCOME_EVIDENCE_KINDS = ["link", "image"];
135
+ var DESTINATION_OUTCOME_EVIDENCE_MAX = 12;
136
+ var DESTINATION_OUTCOME_EVIDENCE_URL_MAX = 2048;
137
+ var DESTINATION_OUTCOME_EVIDENCE_CAPTION_MAX = 280;
138
+ function isObject(value) {
139
+ return !!value && typeof value === "object" && !Array.isArray(value);
140
+ }
141
+ function httpUrl(value) {
142
+ try {
143
+ const parsed = new URL(value);
144
+ return parsed.protocol === "https:" || parsed.protocol === "http:";
145
+ } catch {
146
+ return false;
147
+ }
148
+ }
149
+ function optionalText(value, label, max) {
150
+ if (value === void 0 || value === null) return null;
151
+ if (typeof value !== "string") return { error: `${label} must be text` };
152
+ const text = value.trim();
153
+ if (!text) return null;
154
+ if (text.length > max) return { error: `${label} must be at most ${max} characters` };
155
+ return text;
156
+ }
157
+ function parseDestinationOutcomeEvidence(value) {
158
+ if (!isObject(value)) return { ok: false, message: "evidence items must be objects" };
159
+ const kind = value.kind;
160
+ if (typeof kind !== "string" || !DESTINATION_OUTCOME_EVIDENCE_KINDS.includes(kind)) {
161
+ return {
162
+ ok: false,
163
+ message: `evidence kind must be one of ${DESTINATION_OUTCOME_EVIDENCE_KINDS.join(", ")}`
164
+ };
165
+ }
166
+ if (typeof value.url !== "string" || !value.url.trim()) {
167
+ return { ok: false, message: "evidence url is required" };
168
+ }
169
+ const url = value.url.trim();
170
+ if (url.length > DESTINATION_OUTCOME_EVIDENCE_URL_MAX) {
171
+ return {
172
+ ok: false,
173
+ message: `evidence url must be at most ${DESTINATION_OUTCOME_EVIDENCE_URL_MAX} characters`
174
+ };
175
+ }
176
+ if (!httpUrl(url)) {
177
+ return { ok: false, message: "evidence url must be an absolute http(s) URL" };
178
+ }
179
+ if (kind === "image" && !isTrustedScreenshotUrl(url)) {
180
+ return {
181
+ ok: false,
182
+ message: `evidence image ${url} is not on a host images are shown from; attach it as a link`
183
+ };
184
+ }
185
+ const caption = optionalText(
186
+ value.caption,
187
+ "evidence caption",
188
+ DESTINATION_OUTCOME_EVIDENCE_CAPTION_MAX
189
+ );
190
+ if (caption && typeof caption === "object") return { ok: false, message: caption.error };
191
+ return {
192
+ ok: true,
193
+ value: { url, caption, kind }
194
+ };
195
+ }
196
+
92
197
  // ../contracts/src/run-result.ts
93
198
  var MAX_RUN_RESULTS_PER_TURN = 5;
94
199
  var MAX_RUN_RESULT_METRICS = 20;
95
200
  var MAX_RUN_RESULT_SUMMARY_CHARS = 2e3;
201
+ var MAX_RUN_RESULT_TITLE_CHARS = 255;
96
202
  var MAX_RUN_RESULT_METRIC_NAME_CHARS = 120;
97
203
  var MAX_RUN_RESULT_METRIC_VALUE_CHARS = 120;
98
204
  var MAX_RUN_RESULT_METRIC_UNIT_CHARS = 40;
99
205
  var MAX_RUN_RESULT_METRIC_LINE_CHARS = MAX_RUN_RESULT_METRIC_NAME_CHARS + MAX_RUN_RESULT_METRIC_VALUE_CHARS + MAX_RUN_RESULT_METRIC_UNIT_CHARS + 20;
206
+ var MAX_RUN_RESULT_EVIDENCE = DESTINATION_OUTCOME_EVIDENCE_MAX;
207
+ var RUN_RESULT_VERDICTS = ["met", "not_met", "inconclusive", "info"];
208
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
209
+ function isRunResultVerdict(value) {
210
+ return typeof value === "string" && RUN_RESULT_VERDICTS.includes(value);
211
+ }
100
212
  var EXAMPLE_TITLE2 = "Backtest of the four entry strategies, 2024 data";
101
213
  var RUN_RESULT_INSTRUCTION = `## Results
102
214
 
@@ -124,15 +236,220 @@ Rules:
124
236
  - At most ${MAX_RUN_RESULTS_PER_TURN} blocks, ${MAX_RUN_RESULT_METRICS} \`metric:\` lines each.
125
237
  - \`title\`: what was measured or checked, one line.
126
238
  - \`about: this\` for this task; or the id of a destination this task's work leads to, when the
127
- result checks that destination's outcome.
239
+ result checks that destination's outcome. Those ids are listed under "Destinations this task
240
+ leads to" when the task has any.
128
241
  - \`verdict\`: \`met\` (it holds), \`not_met\` (it does not), \`inconclusive\` (checked, could
129
242
  not tell) or \`info\` (a measurement with no pass or fail).
130
243
  - \`metric: name = value unit\`, one per line; the value a number where there is one.
131
244
  - \`evidence:\` an http(s) URL (a report, a dashboard, a pull request), then an optional caption.
132
245
  - Below \`---\`, a summary of what it showed, at most ${MAX_RUN_RESULT_SUMMARY_CHARS} characters.
133
246
  - Do not write \`-->\` inside a block: it ends the block.`;
247
+ function metricByName(metrics, name) {
248
+ const key = name.trim().toLowerCase();
249
+ if (!key || !metrics) return null;
250
+ let found = null;
251
+ for (const metric of metrics) {
252
+ if (metric.name.trim().toLowerCase() === key) found = metric;
253
+ }
254
+ return found;
255
+ }
256
+ function isStoredNumber(value) {
257
+ return typeof value === "number" && Number.isFinite(value);
258
+ }
259
+ function compareStoredMetrics(previous, next, direction) {
260
+ if (!next || !isStoredNumber(next.value)) {
261
+ return { kind: "uncompared", reason: next ? "not_numeric" : "missing" };
262
+ }
263
+ if (!previous || !isStoredNumber(previous.value)) {
264
+ return previous && !isStoredNumber(previous.value) ? { kind: "uncompared", reason: "not_numeric" } : { kind: "baseline" };
265
+ }
266
+ const better = direction === "lower" ? next.value < previous.value : next.value > previous.value;
267
+ if (better) return { kind: "improved", previous: previous.value, next: next.value };
268
+ return {
269
+ kind: "not_improved",
270
+ relation: next.value === previous.value ? "equal" : "worse",
271
+ previous: previous.value,
272
+ next: next.value
273
+ };
274
+ }
275
+ function taskMetricThisTurn(turnText, metric) {
276
+ const parsed = parseRunResults(turnText);
277
+ let found = null;
278
+ for (const result of parsed.results) {
279
+ if (result.about.kind !== "this") continue;
280
+ const named = metricByName(result.metrics, metric);
281
+ if (named) found = named;
282
+ }
283
+ return found;
284
+ }
285
+ function metricLoopShouldOpenPullRequest(input) {
286
+ if (!input.loop) return true;
287
+ if (input.interrupted) return false;
288
+ const next = taskMetricThisTurn(input.turnText, input.loop.metric);
289
+ const previous = input.loop.previous === null ? null : { name: input.loop.metric, value: input.loop.previous, unit: null };
290
+ return compareStoredMetrics(previous, next, input.loop.direction).kind === "improved";
291
+ }
292
+ function nextMetricLoopPrevious(loop, turnText) {
293
+ const next = taskMetricThisTurn(turnText, loop.metric);
294
+ if (!next || !isStoredNumber(next.value)) return loop.previous;
295
+ return next.value;
296
+ }
297
+ var BLOCK_PATTERN = /<!--\s*DT-RESULT\b([\s\S]*?)-->/g;
298
+ var HEADER_PATTERN = /^([a-z_]+)\s*:\s*(.*)$/i;
299
+ var HEADERS = /* @__PURE__ */ new Set(["title", "about", "verdict", "metric", "evidence"]);
300
+ var NUMBER = /^[-+]?(?:\d{1,3}(?:,\d{3})+|\d+)?(?:\.\d+)?(?:e[-+]?\d+)?$/i;
134
301
  var NUM = String.raw`[-+]?[\d.,]*\d[\d.,]*(?:e[-+]?\d+)?`;
135
302
  var NUMERIC_TOKEN = new RegExp(String.raw`^[~<>≈≤≥]?${NUM}(?:\s*(?:-|–|to)\s*${NUM})?%?$`, "i");
303
+ var IMAGE_PATH = /\.(?:png|jpe?g|gif|webp)$/i;
304
+ function clip(text, max) {
305
+ const trimmed = text.trim();
306
+ return trimmed.length <= max ? trimmed : `${trimmed.slice(0, max - 1).trimEnd()}\u2026`;
307
+ }
308
+ function titleKey(title) {
309
+ return title.trim().toLowerCase().replace(/\s+/g, " ").replace(/[.!?:;,\s]+$/, "");
310
+ }
311
+ function looksNumeric(text) {
312
+ return /\d/.test(text) && NUMBER.test(text);
313
+ }
314
+ function asNumber(text) {
315
+ if (!looksNumeric(text)) return void 0;
316
+ const plain = text.replace(/,/g, "");
317
+ if (plain.startsWith("+") || /e/i.test(plain) || /^-?0\d/.test(plain)) return void 0;
318
+ const n = Number(plain);
319
+ if (!Number.isFinite(n) || Number.isInteger(n) && !Number.isSafeInteger(n)) return void 0;
320
+ let written = plain.replace(/^(-?)\./, "$10.");
321
+ if (written.includes(".")) written = written.replace(/0+$/, "").replace(/\.$/, "");
322
+ return String(n) === written ? n : void 0;
323
+ }
324
+ function verdictOf(raw) {
325
+ const v = (raw ?? "").trim().toLowerCase().replace(/[\s-]+/g, "_");
326
+ return isRunResultVerdict(v) ? v : void 0;
327
+ }
328
+ function parseRunResultMetric(line) {
329
+ if (typeof line !== "string" || line.length > MAX_RUN_RESULT_METRIC_LINE_CHARS) return void 0;
330
+ const eq = line.indexOf("=");
331
+ if (eq < 0) return void 0;
332
+ const name = line.slice(0, eq).trim();
333
+ const rest = line.slice(eq + 1).trim();
334
+ if (!name || !rest || name.length > MAX_RUN_RESULT_METRIC_NAME_CHARS) return void 0;
335
+ const tokens = rest.split(/\s+/);
336
+ let valueText = rest;
337
+ let unit = null;
338
+ for (const take of [3, 1]) {
339
+ if (tokens.length < take) continue;
340
+ const head = tokens.slice(0, take).join(" ");
341
+ if (NUMERIC_TOKEN.test(head)) {
342
+ valueText = head;
343
+ unit = tokens.slice(take).join(" ") || null;
344
+ break;
345
+ }
346
+ }
347
+ if (valueText.endsWith("%") && looksNumeric(valueText.slice(0, -1))) {
348
+ unit = unit ? `% ${unit}` : "%";
349
+ valueText = valueText.slice(0, -1);
350
+ }
351
+ const number = asNumber(valueText);
352
+ if (number === void 0 && valueText.length > MAX_RUN_RESULT_METRIC_VALUE_CHARS)
353
+ return void 0;
354
+ if (unit && unit.length > MAX_RUN_RESULT_METRIC_UNIT_CHARS)
355
+ unit = clip(unit, MAX_RUN_RESULT_METRIC_UNIT_CHARS);
356
+ return { name, value: number ?? valueText, unit };
357
+ }
358
+ function evidenceKind(url) {
359
+ if (!isTrustedScreenshotUrl(url)) return "link";
360
+ try {
361
+ const path = new URL(url).pathname;
362
+ return IMAGE_PATH.test(path) || path.startsWith("/user-attachments/assets/") ? "image" : "link";
363
+ } catch {
364
+ return "link";
365
+ }
366
+ }
367
+ function readEvidenceLine(line) {
368
+ const [url, ...caption] = line.trim().split(/\s+/);
369
+ if (!url) return void 0;
370
+ const parsed = parseDestinationOutcomeEvidence({
371
+ url,
372
+ caption: caption.length > 0 ? clip(caption.join(" "), DESTINATION_OUTCOME_EVIDENCE_CAPTION_MAX) : null,
373
+ kind: evidenceKind(url)
374
+ });
375
+ return parsed.ok ? parsed.value : void 0;
376
+ }
377
+ function readBlock(body) {
378
+ const lines = body.replace(/\r\n?/g, "\n").split("\n");
379
+ const headers = {};
380
+ const metricLines = [];
381
+ const evidenceLines = [];
382
+ let i = 0;
383
+ for (; i < lines.length; i++) {
384
+ const line = lines[i].trim();
385
+ if (line === "---") {
386
+ i++;
387
+ break;
388
+ }
389
+ if (line.length === 0 || line.startsWith("```")) continue;
390
+ const header = HEADER_PATTERN.exec(line);
391
+ if (!header || !HEADERS.has(header[1].toLowerCase())) break;
392
+ const key = header[1].toLowerCase();
393
+ const value = header[2].trim();
394
+ if (key === "metric") metricLines.push(value);
395
+ else if (key === "evidence") evidenceLines.push(value);
396
+ else if (!(key in headers)) headers[key] = value;
397
+ }
398
+ const summaryText = lines.slice(i).filter((line) => !line.trim().startsWith("```")).join("\n").trim();
399
+ const title = headers.title ? clip(headers.title, MAX_RUN_RESULT_TITLE_CHARS) : "";
400
+ if (!title) return { reason: "it has no title" };
401
+ const verdict = headers.verdict === void 0 ? "info" : verdictOf(headers.verdict);
402
+ if (!verdict) {
403
+ return { title, reason: `verdict must be one of ${RUN_RESULT_VERDICTS.join(", ")}` };
404
+ }
405
+ const aboutText = (headers.about ?? "").trim();
406
+ let about;
407
+ if (!aboutText || aboutText.toLowerCase() === "this") about = { kind: "this" };
408
+ else if (UUID.test(aboutText)) about = { kind: "node", nodeId: aboutText.toLowerCase() };
409
+ else return { title, reason: "about must be this or a destination id" };
410
+ const metrics = metricLines.map(parseRunResultMetric).filter((m) => !!m).slice(0, MAX_RUN_RESULT_METRICS);
411
+ const seenUrls = /* @__PURE__ */ new Set();
412
+ const evidence = evidenceLines.map(readEvidenceLine).filter((e) => {
413
+ if (!e || seenUrls.has(e.url)) return false;
414
+ seenUrls.add(e.url);
415
+ return true;
416
+ }).slice(0, MAX_RUN_RESULT_EVIDENCE);
417
+ return {
418
+ title,
419
+ about,
420
+ verdict,
421
+ metrics,
422
+ evidence,
423
+ summary: summaryText ? clip(summaryText, MAX_RUN_RESULT_SUMMARY_CHARS) : null
424
+ };
425
+ }
426
+ function parseRunResults(agentOutput) {
427
+ const out = { results: [], skipped: [] };
428
+ if (typeof agentOutput !== "string" || agentOutput.length === 0) return out;
429
+ try {
430
+ const example = titleKey(EXAMPLE_TITLE2);
431
+ const pattern = new RegExp(BLOCK_PATTERN.source, BLOCK_PATTERN.flags);
432
+ for (let m = pattern.exec(agentOutput); m; m = pattern.exec(agentOutput)) {
433
+ const read = readBlock(m[1]);
434
+ if (!("verdict" in read)) {
435
+ out.skipped.push(read);
436
+ continue;
437
+ }
438
+ if (titleKey(read.title) === example) continue;
439
+ if (out.results.length >= MAX_RUN_RESULTS_PER_TURN) {
440
+ out.skipped.push({
441
+ title: read.title,
442
+ reason: `a turn records at most ${MAX_RUN_RESULTS_PER_TURN}`
443
+ });
444
+ continue;
445
+ }
446
+ out.results.push(read);
447
+ }
448
+ return out;
449
+ } catch {
450
+ return { results: [], skipped: [] };
451
+ }
452
+ }
136
453
 
137
454
  // ../contracts/src/tree-jobs.ts
138
455
  var TREE_JOB_OUTPUT_KEPT_MS = 7 * 24 * 60 * 60 * 1e3;
@@ -152,7 +469,7 @@ function treeJobCwdProblem(cwd) {
152
469
  var MAX_JOB_REQUEST_PURPOSE_CHARS = 2e3;
153
470
  var MAX_JOB_REQUEST_EXPECT_SECONDS = 366 * 24 * 3600;
154
471
  var EXAMPLE_NAME = "Record Polymarket order books for 6 hours";
155
- 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"';
156
473
  var EXAMPLE_CHECKOUT = "/absolute/path/of/your/checkout";
157
474
  var JOB_REQUEST_INSTRUCTION = `## Jobs
158
475
 
@@ -169,7 +486,7 @@ cwd: .
169
486
  url: http://localhost:8000
170
487
  expect: 6h
171
488
  ---
172
- Records the order books the backtest reads from data/books.
489
+ Records order books into $DT_JOB_DATA_DIR/books, which the backtest reads.
173
490
  -->
174
491
 
175
492
  Rules:
@@ -179,6 +496,19 @@ Rules:
179
496
  directory. Say in your answer what you asked for; do not wait for it to start.
180
497
  - \`name\`: what it does, one line.
181
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"\`.
182
512
  - \`checkout\`: the absolute path of your checkout, as \`git rev-parse --show-toplevel\` prints
183
513
  it (or \`pwd\` in the folder you started in, when there is no repository).
184
514
  - \`cwd\`: where to run it, relative to \`checkout\`: \`.\` for its root. Never absolute, never
@@ -189,9 +519,15 @@ Rules:
189
519
  - Below \`---\`, what it is for and where its output goes, at most
190
520
  ${MAX_JOB_REQUEST_PURPOSE_CHARS} characters.
191
521
  - The same job asked for again while it still waits or runs is not asked for twice.
522
+ - If a job you asked for fails or is lost, this run hears about it: a message while it is
523
+ still going, or a continuation if it has finished. Fix the command and ask again with a
524
+ new DT-JOB block. That ask still waits for the owner's approval. After several failures
525
+ in a row the run is not told again, and the job says that automatic tries have stopped.
526
+ A later run of the same job that exits cleanly starts that count over.
192
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
193
- the checkout. Say where its output goes (below \`---\`), and when it is done record where to
194
- 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.
195
531
  - Do not write \`-->\` inside a block: it ends the block.`;
196
532
 
197
533
  // ../contracts/src/environments.ts
@@ -296,9 +632,15 @@ var NOT_GRANTABLE = /the person denied permission|has been denied by a (deny )?r
296
632
  function isGrantableToolDenial(text) {
297
633
  return !!text && GRANTABLE_DENIAL.test(text) && !NOT_GRANTABLE.test(text);
298
634
  }
635
+ function isDenyRuleRefusal(text) {
636
+ return !!text && (NOT_GRANTABLE.test(text) || /\bdeny(?:[ -]?list| rules?)\b|\bdenied by (?:a |your )?(?:permission )?rules?\b|\bdenylist/i.test(
637
+ text
638
+ ));
639
+ }
299
640
  var TOOL_GRANT_RULE_MAX_LENGTH = 500;
300
641
  var RUNNER_TOOL_GRANTS_MAX = 500;
301
642
  var RULE_SHAPE = /^([A-Za-z][A-Za-z0-9_.-]*)(?:\(([\s\S]*)\))?$/;
643
+ var SHELL_RULE_TOOLS = /* @__PURE__ */ new Set(["Bash", "Shell"]);
302
644
  function toolGrantRuleProblem(rule) {
303
645
  if (typeof rule !== "string" || !rule.trim()) return "The rule is empty.";
304
646
  const r = rule.trim();
@@ -311,15 +653,17 @@ function toolGrantRuleProblem(rule) {
311
653
  return "The rule must be a tool name, optionally with what it may do in parentheses, such as Bash(pnpm test *).";
312
654
  }
313
655
  const [, tool, spec] = m;
656
+ const shell = SHELL_RULE_TOOLS.has(tool);
657
+ const example = tool === "Shell" ? "Shell(pnpm)" : "Bash(pnpm test *)";
314
658
  if (spec === void 0) {
315
- return tool === "Bash" ? "Bash on its own would allow every shell command; name the command, such as Bash(pnpm test *)." : null;
659
+ return shell ? `${tool} on its own would allow every shell command; name the command, such as ${example}.` : null;
316
660
  }
317
661
  if (!spec.trim()) return "Say what the tool may do inside the parentheses, or leave them out.";
318
662
  if (/^[\s*:/\\~.]*$/.test(spec.replace(/^domain:/, ""))) {
319
663
  return `${tool}(${spec}) would allow everything; narrow it.`;
320
664
  }
321
- if (tool === "Bash" && /^[\s*]/.test(spec)) {
322
- return "A shell rule must start with the command, such as Bash(pnpm test *).";
665
+ if (shell && /^[\s*]/.test(spec)) {
666
+ return `A shell rule must start with the command, such as ${example}.`;
323
667
  }
324
668
  return null;
325
669
  }
@@ -330,8 +674,11 @@ function toolGrantRepositoryKey(url) {
330
674
  return `${m[1]}/${m[2]}`.toLowerCase();
331
675
  }
332
676
 
677
+ // ../contracts/src/run-activity.ts
678
+ var RUN_STUCK_TOOL_CALL_AFTER_MS = 15 * 6e4;
679
+
333
680
  // src/version.ts
334
- var RUNNER_VERSION = true ? "0.1.20" : "0.0.0-dev";
681
+ var RUNNER_VERSION = true ? "0.1.22" : "0.0.0-dev";
335
682
  var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
336
683
 
337
684
  // src/api.ts
@@ -2263,10 +2610,10 @@ var ClaudeCodeRules = class {
2263
2610
  for (const [folder, entry] of Object.entries(projects)) {
2264
2611
  if (!entry || entry.hasTrustDialogAccepted !== true) continue;
2265
2612
  if (!isAbsolute3(folder) || this.excluded(folder)) continue;
2266
- const git2 = await gitConfigOf(folder);
2267
- const text = git2 ? await readText(git2.config) : null;
2268
- if (!git2 || !text || !remoteKeys(text).has(key)) continue;
2269
- const roots = [...new Set([folder, ...git2.roots].map((d) => resolve(d)))];
2613
+ const git3 = await gitConfigOf(folder);
2614
+ const text = git3 ? await readText(git3.config) : null;
2615
+ if (!git3 || !text || !remoteKeys(text).has(key)) continue;
2616
+ const roots = [...new Set([folder, ...git3.roots].map((d) => resolve(d)))];
2270
2617
  const legacy = Array.isArray(entry.allowedTools) ? entry.allowedTools : [];
2271
2618
  checkouts.push({ folder, roots, legacy });
2272
2619
  }
@@ -2341,6 +2688,7 @@ function summarizeToolInput(toolName, input) {
2341
2688
  let summary = null;
2342
2689
  switch (toolName) {
2343
2690
  case "Bash":
2691
+ case "Shell":
2344
2692
  summary = s(i.command);
2345
2693
  break;
2346
2694
  case "WebFetch":
@@ -2767,7 +3115,8 @@ var claudeCodeDriver = {
2767
3115
  launch(input) {
2768
3116
  const features = input.features;
2769
3117
  const ask = input.askTools;
2770
- const allowedTools = features.settingsFlag || ask.length === 0 ? input.allowedTools : input.allowedTools.filter((r) => !overlapsAsk(r, ask));
3118
+ const ownRules = input.allowedTools.filter((r) => !/^\s*Shell\(/.test(r));
3119
+ const allowedTools = features.settingsFlag || ask.length === 0 ? ownRules : ownRules.filter((r) => !overlapsAsk(r, ask));
2771
3120
  return launcherCommand(
2772
3121
  input.bin,
2773
3122
  claudeArgs({
@@ -3375,6 +3724,7 @@ function cursorArgs(launch) {
3375
3724
  }
3376
3725
  if (launch.resume) args.push(`--resume=${launch.resume}`);
3377
3726
  args.push("--trust");
3727
+ args.push("--sandbox", launch.sandbox ? "enabled" : "disabled");
3378
3728
  if (launch.force) args.push("--force");
3379
3729
  args.push(launch.prompt.startsWith("-") ? `
3380
3730
  ${launch.prompt}` : launch.prompt);
@@ -3481,6 +3831,16 @@ var CursorStreamMapper = class {
3481
3831
  tool.output = capped.text;
3482
3832
  if (capped.truncated) tool.truncated = true;
3483
3833
  }
3834
+ const rejected = rejectionOf(call.result);
3835
+ if (kind === "shellToolCall" && rejected !== null) {
3836
+ (out.failedTools ??= []).push({
3837
+ callId: key,
3838
+ name: "Shell",
3839
+ input: { command: typeof call.args?.command === "string" ? call.args.command : "" },
3840
+ text: rejected,
3841
+ denied: true
3842
+ });
3843
+ }
3484
3844
  }
3485
3845
  out.events.push({ type: "tool_call", providerEventId: key, tool });
3486
3846
  }
@@ -3514,6 +3874,12 @@ function toolNameAndInput(kind, call) {
3514
3874
  input: call.args ?? {}
3515
3875
  };
3516
3876
  }
3877
+ function rejectionOf(result) {
3878
+ if (!result || typeof result !== "object") return null;
3879
+ const rejected = result.rejected;
3880
+ if (rejected === void 0) return null;
3881
+ return describe(rejected) || "Rejected";
3882
+ }
3517
3883
  function toolOutcome(kind, result) {
3518
3884
  if (!result || typeof result !== "object") return { failed: false, output: null };
3519
3885
  const r = result;
@@ -3538,6 +3904,170 @@ function describe(value) {
3538
3904
  return value == null ? "" : JSON.stringify(value);
3539
3905
  }
3540
3906
 
3907
+ // src/drivers/cursor/cursor-permissions.ts
3908
+ import { execFileSync } from "node:child_process";
3909
+ import {
3910
+ appendFileSync,
3911
+ existsSync,
3912
+ mkdirSync,
3913
+ readFileSync,
3914
+ rmSync,
3915
+ writeFileSync
3916
+ } from "node:fs";
3917
+ import { dirname as dirname4, isAbsolute as isAbsolute4, join as join6 } from "node:path";
3918
+ var CURSOR_PROJECT_CONFIG = join6(".cursor", "cli.json");
3919
+ var MARKER = join6(".cursor", ".dt-runner-permissions.json");
3920
+ function cursorRules(allowedTools) {
3921
+ return [...new Set(allowedTools.map((r) => r.trim()).filter((r) => /^Shell\(.+\)$/.test(r)))];
3922
+ }
3923
+ function applyCursorPermissions(cwd, rules) {
3924
+ if (!isAbsolute4(cwd) || !existsSync(cwd)) return;
3925
+ const file = join6(cwd, CURSOR_PROJECT_CONFIG);
3926
+ try {
3927
+ const marker = readMarker(cwd);
3928
+ if (rules.length === 0 && !marker) return;
3929
+ const text = existsSync(file) ? readFileSync(file, "utf8") : null;
3930
+ const read = readConfig(file);
3931
+ if (read === "unreadable") return;
3932
+ const hadPermissions = read !== null && isObject2(read.permissions);
3933
+ const hadAllow = hadPermissions && Array.isArray(read.permissions.allow);
3934
+ const config = read ?? {};
3935
+ const permissions = permissionsOf(config);
3936
+ const previous = new Set(marker?.added ?? []);
3937
+ const own = allowOf(permissions).filter((r) => !previous.has(r));
3938
+ const added = rules.filter((r) => !own.includes(r));
3939
+ if (added.length === 0) {
3940
+ removeCursorPermissions(cwd);
3941
+ return;
3942
+ }
3943
+ if (!keepOutOfCommits(cwd)) return;
3944
+ permissions.allow = [...own, ...added];
3945
+ config.permissions = permissions;
3946
+ const written = `${JSON.stringify(config, null, 2)}
3947
+ `;
3948
+ const next = marker ? { ...marker, added, written } : { added, created: read === null, original: text, written, hadPermissions, hadAllow };
3949
+ mkdirSync(dirname4(file), { recursive: true });
3950
+ writeFileSync(join6(cwd, MARKER), `${JSON.stringify(next)}
3951
+ `);
3952
+ writeFileSync(file, written);
3953
+ } catch {
3954
+ }
3955
+ }
3956
+ function removeCursorPermissions(cwd) {
3957
+ if (!isAbsolute4(cwd)) return;
3958
+ const marker = readMarker(cwd);
3959
+ if (!marker) return;
3960
+ const file = join6(cwd, CURSOR_PROJECT_CONFIG);
3961
+ try {
3962
+ const text = existsSync(file) ? readFileSync(file, "utf8") : null;
3963
+ if (text === marker.written || text === null) {
3964
+ if (marker.original === null) rmSync(file, { force: true });
3965
+ else if (text !== null) writeFileSync(file, marker.original);
3966
+ } else {
3967
+ const read = readConfig(file);
3968
+ if (read === "unreadable") return;
3969
+ if (read !== null) {
3970
+ const permissions = permissionsOf(read);
3971
+ const added = new Set(marker.added);
3972
+ const allow = allowOf(permissions).filter((r) => !added.has(r));
3973
+ if (allow.length || marker.hadAllow) permissions.allow = allow;
3974
+ else delete permissions.allow;
3975
+ if (Object.keys(permissions).length || marker.hadPermissions)
3976
+ read.permissions = permissions;
3977
+ else delete read.permissions;
3978
+ if (marker.created && Object.keys(read).length === 0) rmSync(file, { force: true });
3979
+ else writeFileSync(file, `${JSON.stringify(read, null, 2)}
3980
+ `);
3981
+ }
3982
+ }
3983
+ if (gitTracks(cwd, CURSOR_PROJECT_CONFIG) === true) {
3984
+ git2(cwd, ["update-index", "--no-skip-worktree", "--", CURSOR_PROJECT_CONFIG]);
3985
+ }
3986
+ } catch {
3987
+ return;
3988
+ }
3989
+ rmSync(join6(cwd, MARKER), { force: true });
3990
+ }
3991
+ function keepOutOfCommits(cwd) {
3992
+ const tracked = gitTracks(cwd, CURSOR_PROJECT_CONFIG);
3993
+ if (tracked === null) return true;
3994
+ try {
3995
+ excludeFromGit2(cwd, toPattern(MARKER));
3996
+ if (tracked) {
3997
+ git2(cwd, ["update-index", "--skip-worktree", "--", CURSOR_PROJECT_CONFIG]);
3998
+ } else {
3999
+ excludeFromGit2(cwd, toPattern(CURSOR_PROJECT_CONFIG));
4000
+ }
4001
+ return true;
4002
+ } catch {
4003
+ return false;
4004
+ }
4005
+ }
4006
+ function readMarker(cwd) {
4007
+ try {
4008
+ const m = JSON.parse(readFileSync(join6(cwd, MARKER), "utf8"));
4009
+ if (!Array.isArray(m.added) || typeof m.written !== "string") return null;
4010
+ return {
4011
+ added: m.added.filter((r) => typeof r === "string"),
4012
+ created: m.created === true,
4013
+ original: typeof m.original === "string" ? m.original : null,
4014
+ written: m.written,
4015
+ hadPermissions: m.hadPermissions === true,
4016
+ hadAllow: m.hadAllow === true
4017
+ };
4018
+ } catch {
4019
+ return null;
4020
+ }
4021
+ }
4022
+ var isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
4023
+ function readConfig(file) {
4024
+ if (!existsSync(file)) return null;
4025
+ try {
4026
+ const parsed = JSON.parse(readFileSync(file, "utf8"));
4027
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : "unreadable";
4028
+ } catch {
4029
+ return "unreadable";
4030
+ }
4031
+ }
4032
+ function permissionsOf(config) {
4033
+ const p = config.permissions;
4034
+ return p && typeof p === "object" && !Array.isArray(p) ? { ...p } : {};
4035
+ }
4036
+ function allowOf(permissions) {
4037
+ return Array.isArray(permissions.allow) ? permissions.allow.filter((r) => typeof r === "string") : [];
4038
+ }
4039
+ var toPattern = (path) => `/${path.split("\\").join("/")}`;
4040
+ function gitTracks(cwd, path) {
4041
+ try {
4042
+ git2(cwd, ["rev-parse", "--is-inside-work-tree"]);
4043
+ } catch {
4044
+ return null;
4045
+ }
4046
+ try {
4047
+ git2(cwd, ["ls-files", "--error-unmatch", "--", path]);
4048
+ return true;
4049
+ } catch {
4050
+ return false;
4051
+ }
4052
+ }
4053
+ function excludeFromGit2(cwd, pattern) {
4054
+ const rel = git2(cwd, ["rev-parse", "--git-path", "info/exclude"]).trim();
4055
+ const exclude = isAbsolute4(rel) ? rel : join6(cwd, rel);
4056
+ const current2 = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
4057
+ if (current2.split(/\r?\n/).includes(pattern)) return;
4058
+ mkdirSync(dirname4(exclude), { recursive: true });
4059
+ appendFileSync(exclude, `${current2 && !current2.endsWith("\n") ? "\n" : ""}${pattern}
4060
+ `);
4061
+ }
4062
+ function git2(cwd, args) {
4063
+ return execFileSync("git", args, {
4064
+ cwd,
4065
+ encoding: "utf8",
4066
+ stdio: ["ignore", "pipe", "ignore"],
4067
+ timeout: 1e4
4068
+ });
4069
+ }
4070
+
3541
4071
  // src/drivers/cursor.ts
3542
4072
  var cursorDriver = {
3543
4073
  kind: "cursor",
@@ -3555,18 +4085,23 @@ var cursorDriver = {
3555
4085
  doctor: doctor3,
3556
4086
  validateModel: (model) => assertValidCursorModel(model),
3557
4087
  launch(input) {
4088
+ applyCursorPermissions(input.cwd, cursorRules(input.allowedTools));
3558
4089
  const prompt = input.resume ? input.prompt ?? "" : cursorFirstPrompt(input.systemPrompt, input.prompt ?? "");
3559
4090
  return launcherCommand(
3560
4091
  input.bin,
3561
4092
  cursorArgs({
3562
4093
  model: input.model,
3563
4094
  resume: input.resume,
4095
+ // On unless the config turns the worktree sandbox off.
4096
+ sandbox: input.agentConfig?.cursorSandbox !== false,
3564
4097
  force: input.agentConfig?.cursorForce === true,
3565
4098
  prompt
3566
4099
  })
3567
4100
  );
3568
4101
  },
3569
4102
  createMapper: () => new CursorStreamMapper(),
4103
+ // The runner's rules come back out of `.cursor/cli.json` before it commits the agent's work.
4104
+ beforeCommit: (cwd) => removeCursorPermissions(cwd),
3570
4105
  looksLikeSignInFailure: looksLikeCursorSignInFailure,
3571
4106
  turnFailedToSignIn: (turn) => turn.isError && looksLikeCursorSignInFailure(turn.text),
3572
4107
  signInFix: (env) => cursorSignInFix(env),
@@ -3650,7 +4185,7 @@ function agentDriverKinds() {
3650
4185
  // src/config.ts
3651
4186
  import { chmod, mkdir as mkdir3, readFile as readFile4, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
3652
4187
  import { homedir as homedir2 } from "node:os";
3653
- import { dirname as dirname4, join as join6 } from "node:path";
4188
+ import { dirname as dirname5, join as join7 } from "node:path";
3654
4189
 
3655
4190
  // src/invocation.ts
3656
4191
  var RUNNER_PACKAGE = "@discovery-tree/runner";
@@ -3666,21 +4201,21 @@ function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
3666
4201
  function runnerPaths(env = process.env) {
3667
4202
  const home = homedir2();
3668
4203
  if (process.platform === "win32") {
3669
- const roaming = env.APPDATA || join6(home, "AppData", "Roaming");
3670
- const local = env.LOCALAPPDATA || join6(home, "AppData", "Local");
4204
+ const roaming = env.APPDATA || join7(home, "AppData", "Roaming");
4205
+ const local = env.LOCALAPPDATA || join7(home, "AppData", "Local");
3671
4206
  return {
3672
- configFile: join6(roaming, "discovery-tree", "runner.json"),
3673
- dataDir: join6(local, "discovery-tree", "runner"),
3674
- stateDir: join6(local, "discovery-tree", "runner", "state")
4207
+ configFile: join7(roaming, "discovery-tree", "runner.json"),
4208
+ dataDir: join7(local, "discovery-tree", "runner"),
4209
+ stateDir: join7(local, "discovery-tree", "runner", "state")
3675
4210
  };
3676
4211
  }
3677
- const config = env.XDG_CONFIG_HOME || join6(home, ".config");
3678
- const data = env.XDG_DATA_HOME || join6(home, ".local", "share");
3679
- const state = env.XDG_STATE_HOME || join6(home, ".local", "state");
4212
+ const config = env.XDG_CONFIG_HOME || join7(home, ".config");
4213
+ const data = env.XDG_DATA_HOME || join7(home, ".local", "share");
4214
+ const state = env.XDG_STATE_HOME || join7(home, ".local", "state");
3680
4215
  return {
3681
- configFile: join6(config, "discovery-tree", "runner.json"),
3682
- dataDir: join6(data, "discovery-tree", "runner"),
3683
- stateDir: join6(state, "discovery-tree", "runner")
4216
+ configFile: join7(config, "discovery-tree", "runner.json"),
4217
+ dataDir: join7(data, "discovery-tree", "runner"),
4218
+ stateDir: join7(state, "discovery-tree", "runner")
3684
4219
  };
3685
4220
  }
3686
4221
  var PERMISSION_MODES = [
@@ -3875,13 +4410,15 @@ var DEFAULT_DISALLOWED_TOOLS = [
3875
4410
  ];
3876
4411
  function configDirRules(configFile, platform = process.platform) {
3877
4412
  if (platform === "win32") return [];
3878
- const dir = dirname4(configFile);
4413
+ const dir = dirname5(configFile);
3879
4414
  if (!dir.startsWith("/")) return [];
3880
4415
  return [`Read(/${dir}/**)`, `Edit(/${dir}/**)`];
3881
4416
  }
3882
4417
  var DEFAULT_SERVER_URL = "https://discovery-tree-backend.onrender.com";
3883
4418
  var DEFAULT_MAX_SESSIONS = 2;
3884
4419
  var DEFAULT_IDLE_TIMEOUT_MINUTES = 15;
4420
+ var DEFAULT_JOB_LOG_RETENTION_DAYS = 30;
4421
+ var JOB_RETENTION_DAYS_LIMIT = 3650;
3885
4422
  async function readConfigFile(file) {
3886
4423
  let raw;
3887
4424
  try {
@@ -3899,7 +4436,7 @@ async function readConfigFile(file) {
3899
4436
  }
3900
4437
  }
3901
4438
  async function writeConfigFile(file, config) {
3902
- await mkdir3(dirname4(file), { recursive: true, mode: 448 });
4439
+ await mkdir3(dirname5(file), { recursive: true, mode: 448 });
3903
4440
  await writeFile2(file, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
3904
4441
  await chmod(file, 384).catch(() => void 0);
3905
4442
  }
@@ -3936,6 +4473,14 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
3936
4473
  `maxJobs must be a whole number from 1 to ${RUNNER_MAX_JOBS_LIMIT} (got ${maxJobs}).`
3937
4474
  );
3938
4475
  }
4476
+ const jobLogRetentionDays = retentionDays(
4477
+ "jobLogRetentionDays",
4478
+ overrides.jobLogRetentionDays ?? file?.jobLogRetentionDays ?? DEFAULT_JOB_LOG_RETENTION_DAYS
4479
+ );
4480
+ const jobDataRetentionDays = retentionDays(
4481
+ "jobDataRetentionDays",
4482
+ overrides.jobDataRetentionDays ?? file?.jobDataRetentionDays ?? 0
4483
+ );
3939
4484
  const inherit = file?.inheritClaudeCodePermissions;
3940
4485
  if (inherit !== void 0 && typeof inherit !== "boolean") {
3941
4486
  throw new Error(
@@ -3954,6 +4499,12 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
3954
4499
  `codexNetworkAccess in ${paths.configFile} must be true or false (got ${JSON.stringify(codexNetwork)}).`
3955
4500
  );
3956
4501
  }
4502
+ const cursorSandbox = file?.cursorSandbox;
4503
+ if (cursorSandbox !== void 0 && typeof cursorSandbox !== "boolean") {
4504
+ throw new Error(
4505
+ `cursorSandbox in ${paths.configFile} must be true or false (got ${JSON.stringify(cursorSandbox)}).`
4506
+ );
4507
+ }
3957
4508
  const cursorForce = file?.cursorForce;
3958
4509
  if (cursorForce !== void 0 && typeof cursorForce !== "boolean") {
3959
4510
  throw new Error(
@@ -3978,8 +4529,10 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
3978
4529
  name: file?.name ?? null,
3979
4530
  maxSessions,
3980
4531
  maxJobs,
3981
- reposDir: overrides.reposDir ?? file?.reposDir ?? join6(paths.dataDir, "repos"),
3982
- worktreesDir: file?.worktreesDir ?? join6(paths.dataDir, "worktrees"),
4532
+ jobLogRetentionDays,
4533
+ jobDataRetentionDays,
4534
+ reposDir: overrides.reposDir ?? file?.reposDir ?? join7(paths.dataDir, "repos"),
4535
+ worktreesDir: file?.worktreesDir ?? join7(paths.dataDir, "worktrees"),
3983
4536
  permissionMode: mode,
3984
4537
  allowedTools: [...new Set(allowed)],
3985
4538
  disallowedTools: [...new Set(disallowed)],
@@ -3990,14 +4543,28 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
3990
4543
  idleTimeoutMs: (file?.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES) * 6e4,
3991
4544
  codexSandbox,
3992
4545
  codexNetworkAccess: codexNetwork === true,
4546
+ // On unless turned off (a value that is not a boolean was refused above).
4547
+ cursorSandbox: cursorSandbox !== false,
3993
4548
  cursorForce: cursorForce === true,
3994
4549
  stateDir: paths.stateDir,
3995
4550
  configFile: paths.configFile
3996
4551
  };
3997
4552
  }
4553
+ function retentionDays(key, days) {
4554
+ if (!Number.isInteger(days) || days < 0 || days > JOB_RETENTION_DAYS_LIMIT) {
4555
+ throw new Error(
4556
+ `${key} must be a whole number of days from 0 (keep for good) to ${JOB_RETENTION_DAYS_LIMIT} (got ${days}).`
4557
+ );
4558
+ }
4559
+ return days;
4560
+ }
4561
+ function numberFlag(value) {
4562
+ if (value === void 0) return void 0;
4563
+ return value.trim() ? Number(value) : Number.NaN;
4564
+ }
3998
4565
 
3999
4566
  // src/daemon.ts
4000
- import { join as join15 } from "node:path";
4567
+ import { join as join16 } from "node:path";
4001
4568
 
4002
4569
  // src/backoff.ts
4003
4570
  function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
@@ -4020,7 +4587,7 @@ function sleep(ms, signal) {
4020
4587
  // src/completion.ts
4021
4588
  import { mkdtemp as mkdtemp2, rm as rm4 } from "node:fs/promises";
4022
4589
  import { tmpdir as tmpdir2 } from "node:os";
4023
- import { join as join7 } from "node:path";
4590
+ import { join as join8 } from "node:path";
4024
4591
  var COMPLETION_DENIED_TOOLS = [
4025
4592
  "Read",
4026
4593
  "Glob",
@@ -4068,7 +4635,7 @@ async function answerCompletion(req, deps) {
4068
4635
  try {
4069
4636
  const { bin, features } = await deps.claude();
4070
4637
  const args = completionArgs(req, features);
4071
- cwd = await mkdtemp2(join7(tmpdir2(), "dt-runner-completion-"));
4638
+ cwd = await mkdtemp2(join8(tmpdir2(), "dt-runner-completion-"));
4072
4639
  const run = deps.run ?? ((b, a, o) => exec(b, a, { ...o, ownTree: true }));
4073
4640
  const input = req.systemPrompt ? `<instructions>
4074
4641
  ${req.systemPrompt}
@@ -4122,8 +4689,8 @@ function reportableSessionIds(ids, onDropped = () => void 0) {
4122
4689
  // src/jobs/job-manager.ts
4123
4690
  import { randomBytes as randomBytes3, scrypt, timingSafeEqual } from "node:crypto";
4124
4691
  import { realpathSync } from "node:fs";
4125
- import { mkdir as mkdir6, readFile as readFile8, readdir as readdir2, stat as stat4 } from "node:fs/promises";
4126
- import { basename, dirname as dirname7, isAbsolute as isAbsolute4, join as join10, resolve as resolve2, sep as sep3 } from "node:path";
4692
+ import { mkdir as mkdir6, readFile as readFile8, readdir as readdir2, rm as rm6, stat as stat4 } from "node:fs/promises";
4693
+ import { basename, dirname as dirname8, isAbsolute as isAbsolute5, join as join11, resolve as resolve2, sep as sep3 } from "node:path";
4127
4694
 
4128
4695
  // src/environment.ts
4129
4696
  function sessionEnvironment(raw) {
@@ -4412,9 +4979,9 @@ function fitEvent(body) {
4412
4979
 
4413
4980
  // src/fsutil.ts
4414
4981
  import { mkdir as mkdir4, readFile as readFile5, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
4415
- import { dirname as dirname5 } from "node:path";
4982
+ import { dirname as dirname6 } from "node:path";
4416
4983
  async function writeJsonAtomic(file, value) {
4417
- await mkdir4(dirname5(file), { recursive: true });
4984
+ await mkdir4(dirname6(file), { recursive: true });
4418
4985
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
4419
4986
  await writeFile3(tmp, JSON.stringify(value), { mode: 384 });
4420
4987
  await rename2(tmp, file);
@@ -4857,15 +5424,15 @@ var JobOutbox = class _JobOutbox {
4857
5424
 
4858
5425
  // src/jobs/job-process.ts
4859
5426
  import { execFile, spawn as spawn4 } from "node:child_process";
4860
- import { closeSync, openSync, readFileSync, readdirSync } from "node:fs";
5427
+ import { closeSync, openSync, readFileSync as readFileSync2, readdirSync } from "node:fs";
4861
5428
  import { readFile as readFile7, writeFile as writeFile4 } from "node:fs/promises";
4862
- import { dirname as dirname6, join as join9 } from "node:path";
5429
+ import { dirname as dirname7, join as join10 } from "node:path";
4863
5430
 
4864
5431
  // src/lock.ts
4865
5432
  import { mkdir as mkdir5, open as open2, readFile as readFile6, rm as rm5 } from "node:fs/promises";
4866
- import { join as join8 } from "node:path";
5433
+ import { join as join9 } from "node:path";
4867
5434
  function lockFile(stateDir) {
4868
- return join8(stateDir, "daemon.pid");
5435
+ return join9(stateDir, "daemon.pid");
4869
5436
  }
4870
5437
  function pidAlive(pid) {
4871
5438
  if (!Number.isInteger(pid) || pid <= 0) return false;
@@ -5021,9 +5588,9 @@ async function spawnJob(input) {
5021
5588
  return { pid: child.pid, startedAt: Date.now() - 500, child, exited };
5022
5589
  }
5023
5590
  async function spawnWindowsJob(input) {
5024
- const dir = dirname6(input.exitFile);
5025
- const scriptFile = join9(dir, "job.ps1");
5026
- const commandFile = join9(dir, "command.ps1");
5591
+ const dir = dirname7(input.exitFile);
5592
+ const scriptFile = join10(dir, "job.ps1");
5593
+ const commandFile = join10(dir, "command.ps1");
5027
5594
  const bom = "\uFEFF";
5028
5595
  await writeFile4(commandFile, bom + powershellCommandScript(input.command), { mode: 384 });
5029
5596
  for (const f of [input.stdoutFile, input.stderrFile]) await writeFile4(f, "", { flag: "a" });
@@ -5138,7 +5705,7 @@ function parseElapsed(text) {
5138
5705
  }
5139
5706
  function procStat(pid) {
5140
5707
  try {
5141
- const stat5 = readFileSync(`/proc/${pid}/stat`, "utf8");
5708
+ const stat5 = readFileSync2(`/proc/${pid}/stat`, "utf8");
5142
5709
  return stat5.slice(stat5.lastIndexOf(")") + 2).split(" ");
5143
5710
  } catch {
5144
5711
  return null;
@@ -5236,6 +5803,9 @@ var CENSUS_INTERVAL_MS2 = 3e4;
5236
5803
  var JOB_SECRETS_WAIT_MS = 9e4;
5237
5804
  var JOB_SECRETS_END_WAIT_MS = 12e4;
5238
5805
  var JOB_LOST_POSTING_MS = RUNNER_JOB_MISSING_GRACE_MS + 3e4;
5806
+ var JOB_DATA_DIR_NAME = "data";
5807
+ var JOB_DATA_DIR_ENV = "DT_JOB_DATA_DIR";
5808
+ var JOB_PRUNE_INTERVAL_MS = 24 * 36e5;
5239
5809
  function secretWait() {
5240
5810
  let end = () => void 0;
5241
5811
  const over = new Promise((resolve4) => end = resolve4);
@@ -5244,7 +5814,7 @@ function secretWait() {
5244
5814
  var JobManager = class {
5245
5815
  constructor(opts) {
5246
5816
  this.opts = opts;
5247
- this.root = join10(opts.stateDir, "jobs");
5817
+ this.root = join11(opts.stateDir, "jobs");
5248
5818
  }
5249
5819
  jobs = /* @__PURE__ */ new Map();
5250
5820
  /** Folders being removed now, with how many removals hold each (see `holdForRemoval`). */
@@ -5257,6 +5827,9 @@ var JobManager = class {
5257
5827
  queues = /* @__PURE__ */ new Map();
5258
5828
  timer = null;
5259
5829
  censusTimer = null;
5830
+ pruneTimer = null;
5831
+ /** The prune under way, so prunes never overlap. */
5832
+ pruning = null;
5260
5833
  ticking = false;
5261
5834
  shuttingDown = false;
5262
5835
  /** Resolves when the runner begins to stop: an end waiting for secrets waits no more. */
@@ -5264,7 +5837,15 @@ var JobManager = class {
5264
5837
  root;
5265
5838
  /** The folder a job's record, log and outbox live in. */
5266
5839
  jobDir(jobId) {
5267
- return join10(this.root, jobId);
5840
+ return join11(this.root, jobId);
5841
+ }
5842
+ /**
5843
+ * The folder a job writes its output to (`DT_JOB_DATA_DIR`): its own, apart from any
5844
+ * session's checkout, so it outlives the session's cleanup. Pruned only when the runner's
5845
+ * owner set `jobDataRetentionDays`.
5846
+ */
5847
+ jobDataDir(jobId) {
5848
+ return join11(this.jobDir(jobId), JOB_DATA_DIR_NAME);
5268
5849
  }
5269
5850
  /**
5270
5851
  * Jobs the runner reports in `activeJobIds`: a live process, or an end not yet reported.
@@ -5360,7 +5941,7 @@ var JobManager = class {
5360
5941
  let table = null;
5361
5942
  for (const entry of entries) {
5362
5943
  if (!isRunnerSessionId(entry)) continue;
5363
- const record = await readJson(join10(this.jobDir(entry), "job.json")).catch(
5944
+ const record = await readJson(join11(this.jobDir(entry), "job.json")).catch(
5364
5945
  () => null
5365
5946
  );
5366
5947
  if (!record || record.jobId !== entry || record.settled) continue;
@@ -5377,6 +5958,106 @@ var JobManager = class {
5377
5958
  }
5378
5959
  this.ensureTimers();
5379
5960
  }
5961
+ /**
5962
+ * Prunes settled jobs now, then once a day until the runner stops (see
5963
+ * {@link pruneSettledJobs}). Nothing to do when both retentions keep everything.
5964
+ */
5965
+ startPruning() {
5966
+ if (this.shuttingDown || this.pruneTimer || !this.pruneEnabled()) return;
5967
+ const run = () => void this.pruneSettledJobs().catch(() => void 0);
5968
+ run();
5969
+ this.pruneTimer = setInterval(run, JOB_PRUNE_INTERVAL_MS);
5970
+ this.pruneTimer.unref?.();
5971
+ }
5972
+ pruneEnabled() {
5973
+ return retentionMs(this.opts.logRetentionDays) !== null || retentionMs(this.opts.dataRetentionDays) !== null;
5974
+ }
5975
+ /**
5976
+ * Removes what settled jobs left past their retention, counted from when each ended:
5977
+ * their log files after `logRetentionDays` (everything in the job's folder but `job.json`
5978
+ * and `data/`), and their `data/` after `dataRetentionDays`, each only when set (0 or
5979
+ * unset keeps it). `job.json` stays, so a start delivered again is still answered from it.
5980
+ * A job that is not settled (running, or its last report still to go) is never touched.
5981
+ * Logs what it removed.
5982
+ */
5983
+ pruneSettledJobs(now = Date.now()) {
5984
+ if (this.pruning) return this.pruning;
5985
+ const run = this.prune(now).finally(() => {
5986
+ if (this.pruning === run) this.pruning = null;
5987
+ });
5988
+ this.pruning = run;
5989
+ return run;
5990
+ }
5991
+ async prune(now) {
5992
+ const result = { logs: [], data: [] };
5993
+ const logsMs = retentionMs(this.opts.logRetentionDays);
5994
+ const dataMs = retentionMs(this.opts.dataRetentionDays);
5995
+ if (logsMs === null && dataMs === null) return result;
5996
+ let entries = [];
5997
+ try {
5998
+ entries = await readdir2(this.root);
5999
+ } catch (err) {
6000
+ if (err.code !== "ENOENT") {
6001
+ this.opts.logger.warn("could not read the jobs folder to prune it", {
6002
+ error: err.message
6003
+ });
6004
+ }
6005
+ return result;
6006
+ }
6007
+ for (const entry of entries) {
6008
+ if (this.shuttingDown) break;
6009
+ if (!isRunnerSessionId(entry) || this.jobs.has(entry) || this.starting.has(entry)) continue;
6010
+ const dir = this.jobDir(entry);
6011
+ const record = await readJson(join11(dir, "job.json")).catch(() => null);
6012
+ if (!record || record.jobId !== entry || !record.settled) continue;
6013
+ const endedAt = Date.parse(record.ended?.at ?? record.createdAt);
6014
+ if (!Number.isFinite(endedAt)) continue;
6015
+ const age = now - endedAt;
6016
+ if (logsMs !== null && age > logsMs) {
6017
+ const files = await readdir2(dir).catch(() => []);
6018
+ const logs = files.filter((f) => f !== "job.json" && f !== JOB_DATA_DIR_NAME);
6019
+ const removed = await this.removeAll(
6020
+ entry,
6021
+ logs.map((f) => join11(dir, f))
6022
+ );
6023
+ if (removed.length) {
6024
+ result.logs.push(entry);
6025
+ this.opts.logger.info(
6026
+ `job ${entry}: removed its log files (${removed.join(", ")}), ended over ${this.opts.logRetentionDays} day(s) ago`
6027
+ );
6028
+ }
6029
+ }
6030
+ if (dataMs !== null && age > dataMs) {
6031
+ const dataDir = this.jobDataDir(entry);
6032
+ const exists3 = await stat4(dataDir).then(
6033
+ () => true,
6034
+ () => false
6035
+ );
6036
+ if (exists3 && (await this.removeAll(entry, [dataDir])).length) {
6037
+ result.data.push(entry);
6038
+ this.opts.logger.info(
6039
+ `job ${entry}: removed its data folder ${dataDir}, ended over ${this.opts.dataRetentionDays} day(s) ago`
6040
+ );
6041
+ }
6042
+ }
6043
+ }
6044
+ return result;
6045
+ }
6046
+ /** Removes each path (a folder with what is in it), returning the names of those that went. */
6047
+ async removeAll(jobId, paths) {
6048
+ const removed = [];
6049
+ for (const p of paths) {
6050
+ try {
6051
+ await rm6(p, { recursive: true, force: true });
6052
+ removed.push(basename(p));
6053
+ } catch (err) {
6054
+ this.opts.logger.warn(`job ${jobId}: could not remove ${p}`, {
6055
+ error: err.message
6056
+ });
6057
+ }
6058
+ }
6059
+ return removed;
6060
+ }
5380
6061
  async restoreJob(record, table) {
5381
6062
  const job = await this.openJob(record, null, null);
5382
6063
  if (record.ended) {
@@ -5504,7 +6185,9 @@ var JobManager = class {
5504
6185
  this.stopped.end();
5505
6186
  if (this.timer) clearInterval(this.timer);
5506
6187
  if (this.censusTimer) clearInterval(this.censusTimer);
5507
- this.timer = this.censusTimer = null;
6188
+ if (this.pruneTimer) clearInterval(this.pruneTimer);
6189
+ this.timer = this.censusTimer = this.pruneTimer = null;
6190
+ await this.pruning?.catch(() => void 0);
5508
6191
  await Promise.allSettled([...this.queues.values()]);
5509
6192
  await Promise.allSettled([...this.finishing]);
5510
6193
  const jobs = [...this.jobs.values()];
@@ -5526,7 +6209,7 @@ var JobManager = class {
5526
6209
  /* -------------------------------------------------------------------------------- */
5527
6210
  async start(id, cmd) {
5528
6211
  if (this.jobs.has(id)) return { ok: true };
5529
- const earlier = await readJson(join10(this.jobDir(id), "job.json")).catch(() => null);
6212
+ const earlier = await readJson(join11(this.jobDir(id), "job.json")).catch(() => null);
5530
6213
  if (earlier) {
5531
6214
  return earlier.pid === null || earlier.ended?.status === "failed" ? { ok: false, error: "The job could not be started on this runner." } : { ok: true };
5532
6215
  }
@@ -5538,7 +6221,7 @@ var JobManager = class {
5538
6221
  return { ok: false, error: "The job has no command to run." };
5539
6222
  }
5540
6223
  const cwd = typeof cmd.cwd === "string" ? cmd.cwd : "";
5541
- const cwdProblem = treeJobCwdProblem(cwd) ?? (isAbsolute4(cwd) ? null : "must be an absolute path");
6224
+ const cwdProblem = treeJobCwdProblem(cwd) ?? (isAbsolute5(cwd) ? null : "must be an absolute path");
5542
6225
  if (cwdProblem) return { ok: false, error: `The job's directory ${cwdProblem}.` };
5543
6226
  const isDir2 = await stat4(cwd).then(
5544
6227
  (s) => s.isDirectory(),
@@ -5575,7 +6258,8 @@ var JobManager = class {
5575
6258
  const environment = sessionEnvironment(cmd.environment);
5576
6259
  const redactor = environment ? jobLineRedactor(environment) : null;
5577
6260
  const dir = this.jobDir(id);
5578
- await mkdir6(dir, { recursive: true, mode: 448 });
6261
+ const dataDir = this.jobDataDir(id);
6262
+ await mkdir6(dataDir, { recursive: true, mode: 448 });
5579
6263
  const record = {
5580
6264
  jobId: id,
5581
6265
  name,
@@ -5598,7 +6282,7 @@ var JobManager = class {
5598
6282
  }
5599
6283
  }
5600
6284
  await saveRecord(dir, record);
5601
- this.opts.logger.info(`job ${id}: starting "${name}"`, { cwd });
6285
+ this.opts.logger.info(`job ${id}: starting "${name}"`, { cwd, dataDir });
5602
6286
  const shortLines = environment ? secretsWithShortLines(environment) : [];
5603
6287
  if (environment?.unredacted.length || shortLines.length) {
5604
6288
  this.opts.logger.warn(
@@ -5610,7 +6294,11 @@ var JobManager = class {
5610
6294
  `job ${id}: left out of the job's environment (not a name it may set): ${environment.skipped.slice(0, 20).join(", ")}`
5611
6295
  );
5612
6296
  }
5613
- const env = { ...process.env, ...environment?.env };
6297
+ const env = {
6298
+ ...process.env,
6299
+ ...environment?.env,
6300
+ [JOB_DATA_DIR_ENV]: resolve2(dataDir)
6301
+ };
5614
6302
  delete env.DT_RUNNER_TOKEN;
5615
6303
  let started;
5616
6304
  try {
@@ -5618,9 +6306,9 @@ var JobManager = class {
5618
6306
  command,
5619
6307
  cwd,
5620
6308
  env,
5621
- stdoutFile: join10(dir, "stdout.log"),
5622
- stderrFile: join10(dir, "stderr.log"),
5623
- exitFile: join10(dir, "exit-code")
6309
+ stdoutFile: join11(dir, "stdout.log"),
6310
+ stderrFile: join11(dir, "stderr.log"),
6311
+ exitFile: join11(dir, "exit-code")
5624
6312
  });
5625
6313
  } catch (err) {
5626
6314
  const error = safeError(err, redactor);
@@ -5788,7 +6476,7 @@ var JobManager = class {
5788
6476
  };
5789
6477
  job.outbox = await JobOutbox.open({
5790
6478
  jobId: record.jobId,
5791
- file: join10(dir, "outbox.json"),
6479
+ file: join11(dir, "outbox.json"),
5792
6480
  poster: this.opts.poster,
5793
6481
  logger: this.opts.logger,
5794
6482
  batchDelayMs: this.opts.outboxBatchDelayMs,
@@ -5810,8 +6498,8 @@ var JobManager = class {
5810
6498
  });
5811
6499
  const cursor = job.outbox.cursor ?? startCursor();
5812
6500
  job.readers = [
5813
- new LogFileReader(join10(dir, "stdout.log"), "stdout", cursor.stdout),
5814
- new LogFileReader(join10(dir, "stderr.log"), "stderr", cursor.stderr)
6501
+ new LogFileReader(join11(dir, "stdout.log"), "stdout", cursor.stdout),
6502
+ new LogFileReader(join11(dir, "stderr.log"), "stderr", cursor.stderr)
5815
6503
  ];
5816
6504
  return job;
5817
6505
  }
@@ -5959,7 +6647,7 @@ var JobManager = class {
5959
6647
  }
5960
6648
  signalGroup2(tree.pid, "SIGKILL");
5961
6649
  }
5962
- /** Its last report is through: the job is let go (its folder and log stay). */
6650
+ /** Its last report is through: the job is let go (its folder and log stay, until pruned). */
5963
6651
  async settle(job) {
5964
6652
  if (this.jobs.get(job.record.jobId) !== job || job.phase !== "ended") return;
5965
6653
  this.jobs.delete(job.record.jobId);
@@ -6045,11 +6733,11 @@ function canonical(p) {
6045
6733
  for (; ; ) {
6046
6734
  try {
6047
6735
  const real = realpathSync.native(head);
6048
- return tail ? join10(real, tail) : real;
6736
+ return tail ? join11(real, tail) : real;
6049
6737
  } catch {
6050
- const up = dirname7(head);
6738
+ const up = dirname8(head);
6051
6739
  if (up === head) return full;
6052
- tail = tail ? join10(basename(head), tail) : basename(head);
6740
+ tail = tail ? join11(basename(head), tail) : basename(head);
6053
6741
  head = up;
6054
6742
  }
6055
6743
  }
@@ -6153,12 +6841,15 @@ function queueEndReport(outbox, ended) {
6153
6841
  ended.status === "stopped" ? { status: "stopped", exitCode: ended.exitCode, signal: ended.signal } : { status: "exited", exitCode: ended.exitCode, signal: ended.signal }
6154
6842
  );
6155
6843
  }
6844
+ function retentionMs(days) {
6845
+ return typeof days === "number" && Number.isFinite(days) && days > 0 ? days * 864e5 : null;
6846
+ }
6156
6847
  async function saveRecord(dir, record) {
6157
- await writeJsonAtomic(join10(dir, "job.json"), record);
6848
+ await writeJsonAtomic(join11(dir, "job.json"), record);
6158
6849
  }
6159
6850
  async function readExitFile(dir) {
6160
6851
  try {
6161
- const code = Number.parseInt((await readFile8(join10(dir, "exit-code"), "utf8")).trim(), 10);
6852
+ const code = Number.parseInt((await readFile8(join11(dir, "exit-code"), "utf8")).trim(), 10);
6162
6853
  return Number.isInteger(code) ? { code, signal: null } : null;
6163
6854
  } catch {
6164
6855
  return null;
@@ -6170,13 +6861,13 @@ function safeError(err, redactor) {
6170
6861
  }
6171
6862
 
6172
6863
  // src/session-manager.ts
6173
- import { existsSync, lstatSync } from "node:fs";
6174
- import { mkdir as mkdir9, rm as rm7, writeFile as writeFile6 } from "node:fs/promises";
6175
- import { basename as basename3, dirname as dirname10, join as join14, resolve as resolve3 } from "node:path";
6864
+ import { existsSync as existsSync2, lstatSync } from "node:fs";
6865
+ import { mkdir as mkdir9, rm as rm8, writeFile as writeFile6 } from "node:fs/promises";
6866
+ import { basename as basename3, dirname as dirname11, join as join15, resolve as resolve3 } from "node:path";
6176
6867
 
6177
6868
  // src/prompt-images.ts
6178
6869
  import { mkdir as mkdir7, writeFile as writeFile5 } from "node:fs/promises";
6179
- import { join as join11 } from "node:path";
6870
+ import { join as join12 } from "node:path";
6180
6871
  var EXTENSIONS = {
6181
6872
  "image/png": ".png",
6182
6873
  "image/jpeg": ".jpg",
@@ -6193,7 +6884,7 @@ function promptImageFileName(index, filename, mimeType) {
6193
6884
  async function savePromptImages(input) {
6194
6885
  const out = { saved: [], failed: [] };
6195
6886
  if (input.images.length === 0) return out;
6196
- const dir = join11(input.cwd, RUNNER_TASK_IMAGES_DIR);
6887
+ const dir = join12(input.cwd, RUNNER_TASK_IMAGES_DIR);
6197
6888
  await mkdir7(dir, { recursive: true });
6198
6889
  if (input.inRepository) {
6199
6890
  await excludeFromGit(
@@ -6205,7 +6896,7 @@ async function savePromptImages(input) {
6205
6896
  for (const [index, image] of input.images.entries()) {
6206
6897
  try {
6207
6898
  const res = await input.fetcher.getPromptImage(input.sessionId, image.attachmentId);
6208
- const path = join11(
6899
+ const path = join12(
6209
6900
  dir,
6210
6901
  promptImageFileName(index, image.filename, res.mimeType || image.mimeType)
6211
6902
  );
@@ -6465,11 +7156,11 @@ function takeBatch(pending) {
6465
7156
  // src/session.ts
6466
7157
  import { spawn as spawn5 } from "node:child_process";
6467
7158
  import { randomUUID as randomUUID2 } from "node:crypto";
6468
- import { basename as basename2, dirname as dirname9 } from "node:path";
7159
+ import { basename as basename2, dirname as dirname10 } from "node:path";
6469
7160
  import { createInterface as createInterface2 } from "node:readline";
6470
7161
 
6471
7162
  // src/tool-grants.ts
6472
- import { dirname as dirname8, join as join12, posix } from "node:path";
7163
+ import { dirname as dirname9, join as join13, posix } from "node:path";
6473
7164
  var isGrantableDenial = isGrantableToolDenial;
6474
7165
  var FILE_TOOLS2 = /* @__PURE__ */ new Set(["Read", "Edit", "MultiEdit", "Write", "NotebookEdit"]);
6475
7166
  var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
@@ -6480,6 +7171,9 @@ function suggestRules(toolName, input, allowedTools = []) {
6480
7171
  if (toolName === "Bash") {
6481
7172
  const command = str(i.command);
6482
7173
  if (command) out = bashRules(command, allowedTools);
7174
+ } else if (toolName === "Shell") {
7175
+ const command = str(i.command);
7176
+ if (command) out = cursorShellRules(command, allowedTools);
6483
7177
  } else if (toolName === "WebFetch") {
6484
7178
  const host = hostOf(str(i.url));
6485
7179
  if (host) out = same(`WebFetch(domain:${host})`);
@@ -6538,6 +7232,76 @@ function bashRules(command, allowedTools) {
6538
7232
  const once = segment.length <= 400 ? `Bash(${segment})` : prefix;
6539
7233
  return { suggestedRule: prefix, onceRule: once };
6540
7234
  }
7235
+ var CURSOR_RUNS_ANY_COMMAND = /* @__PURE__ */ new Set([
7236
+ "bash",
7237
+ "sh",
7238
+ "zsh",
7239
+ "dash",
7240
+ "ksh",
7241
+ "fish",
7242
+ "pwsh",
7243
+ "powershell",
7244
+ "cmd",
7245
+ "doas",
7246
+ "su",
7247
+ "eval",
7248
+ "watch",
7249
+ "parallel",
7250
+ "ssh",
7251
+ "setsid",
7252
+ "chroot",
7253
+ "ionice",
7254
+ "taskset",
7255
+ "flock",
7256
+ "busybox",
7257
+ "unbuffer",
7258
+ "script",
7259
+ "find",
7260
+ "strace",
7261
+ "gdb",
7262
+ "runuser",
7263
+ "chrt",
7264
+ "start",
7265
+ "call"
7266
+ ]);
7267
+ function cursorShellRules(command, allowedTools) {
7268
+ const segment = shellSegments(command).find(
7269
+ (s) => !allowedTools.some((rule) => ruleAllows(rule, "Shell", { command: s }))
7270
+ );
7271
+ if (!segment) return null;
7272
+ const parsed = commandWordAt(segment);
7273
+ if (!parsed) return null;
7274
+ const { word, args } = parsed;
7275
+ const quotesBalanced = (segment.match(/'/g) ?? []).length % 2 === 0 && (segment.match(/"/g) ?? []).length % 2 === 0;
7276
+ const exact = args && quotesBalanced && args.length <= 400 && !/[()\r\n*?[\]]/.test(args) ? `Shell(${word}:${args})` : null;
7277
+ const name = word.split(/[\\/]/).pop().toLowerCase().replace(/\.(?:exe|cmd|bat)$/, "");
7278
+ if (CURSOR_RUNS_ANY_COMMAND.has(name) || Object.hasOwn(WRAPPERS, name)) {
7279
+ return exact ? same(exact) : null;
7280
+ }
7281
+ return { suggestedRule: `Shell(${word})`, onceRule: exact ?? `Shell(${word})` };
7282
+ }
7283
+ function commandWordAt(segment) {
7284
+ const words = segment.trim().split(/\s+/);
7285
+ let at = 0;
7286
+ while (at < words.length - 1 && /^[A-Za-z_]\w*=/.test(words[at])) at++;
7287
+ const word = words[at]?.replace(/^['"]|['"]$/g, "") ?? "";
7288
+ if (!word || /[()*?:]/.test(word)) return null;
7289
+ return { word, args: words.slice(at + 1).join(" ") };
7290
+ }
7291
+ function cursorShellMatches(spec, segment) {
7292
+ const colon = spec.indexOf(":");
7293
+ const base = (colon < 0 ? spec : spec.slice(0, colon)).trim();
7294
+ const args = colon < 0 ? null : spec.slice(colon + 1).trim();
7295
+ const words = segment.trim().split(/\s+/);
7296
+ let at = 0;
7297
+ while (at < words.length - 1 && /^[A-Za-z_]\w*=/.test(words[at])) at++;
7298
+ if (!words[at] || !globMatches(base, words[at])) return false;
7299
+ return args === null || globMatches(args, words.slice(at + 1).join(" "));
7300
+ }
7301
+ function globMatches(pattern, text) {
7302
+ const re = pattern.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
7303
+ return new RegExp(`^${re}$`, "s").test(text);
7304
+ }
6541
7305
  function hostOf(url) {
6542
7306
  if (!url) return null;
6543
7307
  try {
@@ -6566,7 +7330,12 @@ function ruleAllows(rule, toolName, input) {
6566
7330
  const ruleTool = parsed.tool === "Edit" && EDIT_TOOLS.has(toolName) ? toolName : parsed.tool;
6567
7331
  if (ruleTool !== toolName) return false;
6568
7332
  const i = input && typeof input === "object" ? input : {};
6569
- if (parsed.spec === null) return toolName !== "Bash";
7333
+ if (parsed.spec === null) return !SHELL_RULE_TOOLS.has(toolName);
7334
+ if (toolName === "Shell") {
7335
+ const command = typeof i.command === "string" ? i.command.trim() : "";
7336
+ const segments = shellSegments(command);
7337
+ return segments.length > 0 && segments.every((s) => cursorShellMatches(parsed.spec, s));
7338
+ }
6570
7339
  if (toolName === "Bash") {
6571
7340
  const command = typeof i.command === "string" ? i.command.trim() : "";
6572
7341
  if (command && parsed.spec.trim() === command) return true;
@@ -6588,13 +7357,15 @@ function hasOpaqueShell(command) {
6588
7357
  }
6589
7358
  function grantsCover(granted, base, toolName, input) {
6590
7359
  if (granted.length === 0) return false;
6591
- if (toolName !== "Bash") return granted.some((rule) => ruleAllows(rule, toolName, input));
7360
+ if (!SHELL_RULE_TOOLS.has(toolName)) {
7361
+ return granted.some((rule) => ruleAllows(rule, toolName, input));
7362
+ }
6592
7363
  const i = input && typeof input === "object" ? input : {};
6593
7364
  const command = typeof i.command === "string" ? i.command.trim() : "";
6594
7365
  if (!command) return false;
6595
7366
  const exact = granted.some((rule) => {
6596
7367
  const parsed = parseRule(rule);
6597
- return parsed?.tool === "Bash" && parsed.spec !== null && parsed.spec.trim() === command;
7368
+ return parsed?.tool === toolName && parsed.spec !== null && parsed.spec.trim() === command;
6598
7369
  });
6599
7370
  if (exact) return true;
6600
7371
  if (hasOpaqueShell(command)) return false;
@@ -6603,8 +7374,8 @@ function grantsCover(granted, base, toolName, input) {
6603
7374
  let byGrant = false;
6604
7375
  for (const segment of segments) {
6605
7376
  const call = { command: segment };
6606
- if (granted.some((rule) => ruleAllows(rule, "Bash", call))) byGrant = true;
6607
- else if (!base.some((rule) => ruleAllows(rule, "Bash", call))) return false;
7377
+ if (granted.some((rule) => ruleAllows(rule, toolName, call))) byGrant = true;
7378
+ else if (!base.some((rule) => ruleAllows(rule, toolName, call))) return false;
6608
7379
  }
6609
7380
  return byGrant;
6610
7381
  }
@@ -6667,7 +7438,7 @@ function filePatternMatches(spec, file) {
6667
7438
  let pattern = spec.trim();
6668
7439
  if (pattern.startsWith("~/")) {
6669
7440
  if (!home) return false;
6670
- pattern = rulePath(join12(home, pattern.slice(2)).replace(/\\/g, "/"));
7441
+ pattern = rulePath(join13(home, pattern.slice(2)).replace(/\\/g, "/"));
6671
7442
  }
6672
7443
  if (!pattern.startsWith("//")) return false;
6673
7444
  const path = rulePath(file);
@@ -6688,7 +7459,7 @@ function shellPatternMatches(spec, command) {
6688
7459
  return new RegExp(`^${re}${optionalTail ? "(?: .*)?" : ""}$`, "s").test(command);
6689
7460
  }
6690
7461
  function toolGrantsFile(configFile) {
6691
- return join12(dirname8(configFile), "tool-grants.json");
7462
+ return join13(dirname9(configFile), "tool-grants.json");
6692
7463
  }
6693
7464
  var ToolGrantStore = class {
6694
7465
  constructor(file) {
@@ -6854,8 +7625,8 @@ function ghError(command, res) {
6854
7625
  }
6855
7626
 
6856
7627
  // src/session-store.ts
6857
- import { mkdir as mkdir8, readdir as readdir3, rm as rm6 } from "node:fs/promises";
6858
- import { join as join13 } from "node:path";
7628
+ import { mkdir as mkdir8, readdir as readdir3, rm as rm7 } from "node:fs/promises";
7629
+ import { join as join14 } from "node:path";
6859
7630
  var HANDLED_COMMAND_IDS_KEPT = 100;
6860
7631
  var pendingWrites = /* @__PURE__ */ new Map();
6861
7632
  var SessionStore = class {
@@ -6863,10 +7634,10 @@ var SessionStore = class {
6863
7634
  this.stateDir = stateDir;
6864
7635
  }
6865
7636
  dir(sessionId) {
6866
- return join13(this.stateDir, "sessions", sessionId);
7637
+ return join14(this.stateDir, "sessions", sessionId);
6867
7638
  }
6868
7639
  outboxFile(sessionId) {
6869
- return join13(this.dir(sessionId), "outbox.json");
7640
+ return join14(this.dir(sessionId), "outbox.json");
6870
7641
  }
6871
7642
  /**
6872
7643
  * Writes the record as it is now. A session's saves land in the order they were made:
@@ -6876,7 +7647,7 @@ var SessionStore = class {
6876
7647
  */
6877
7648
  async save(record) {
6878
7649
  record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
6879
- const file = join13(this.dir(record.sessionId), "session.json");
7650
+ const file = join14(this.dir(record.sessionId), "session.json");
6880
7651
  const snapshot = JSON.parse(JSON.stringify(record));
6881
7652
  const previous = pendingWrites.get(file) ?? Promise.resolve();
6882
7653
  const write = previous.then(() => writeJsonAtomic(file, snapshot));
@@ -6888,23 +7659,23 @@ var SessionStore = class {
6888
7659
  await write;
6889
7660
  }
6890
7661
  async list() {
6891
- const root = join13(this.stateDir, "sessions");
7662
+ const root = join14(this.stateDir, "sessions");
6892
7663
  await mkdir8(root, { recursive: true });
6893
7664
  const out = [];
6894
7665
  for (const entry of await readdir3(root, { withFileTypes: true })) {
6895
7666
  if (!entry.isDirectory()) continue;
6896
- const rec = await readJson(join13(root, entry.name, "session.json"));
7667
+ const rec = await readJson(join14(root, entry.name, "session.json"));
6897
7668
  if (rec?.sessionId === entry.name) out.push(upgradeRecord(rec));
6898
7669
  }
6899
7670
  return out;
6900
7671
  }
6901
7672
  async remove(sessionId) {
6902
- await pendingWrites.get(join13(this.dir(sessionId), "session.json"));
6903
- await rm6(this.dir(sessionId), { recursive: true, force: true });
7673
+ await pendingWrites.get(join14(this.dir(sessionId), "session.json"));
7674
+ await rm7(this.dir(sessionId), { recursive: true, force: true });
6904
7675
  }
6905
7676
  /** Scratch working directory for a session without a repository. */
6906
7677
  scratchDir(sessionId) {
6907
- return join13(this.stateDir, "scratch", sessionId);
7678
+ return join14(this.stateDir, "scratch", sessionId);
6908
7679
  }
6909
7680
  };
6910
7681
  function upgradeRecord(stored) {
@@ -7035,7 +7806,12 @@ var AgentSession = class {
7035
7806
  */
7036
7807
  suggestSafeRules(toolName, input) {
7037
7808
  const redactor = this.deps.environment?.redactor;
7038
- const allowed = this.deps.allowedTools;
7809
+ const allowed = [
7810
+ ...this.deps.allowedTools,
7811
+ ...this.record.grantRules ?? [],
7812
+ ...this.savedRulesNow,
7813
+ ...this.inheritedNow.allow
7814
+ ];
7039
7815
  if (!redactor?.active) return suggestRules(toolName, input, allowed);
7040
7816
  if (JSON.stringify(redactor.redactDeep(input)) === JSON.stringify(input)) {
7041
7817
  return suggestRules(toolName, input, allowed);
@@ -7145,7 +7921,8 @@ var AgentSession = class {
7145
7921
  reportFailedTools(failed) {
7146
7922
  for (const f of failed) {
7147
7923
  if (this.seenFailedCalls.has(f.callId)) continue;
7148
- if (isGrantableDenial(f.text)) this.reportDenial(f.callId, f.name, f.input);
7924
+ const grantable = f.denied ? !isDenyRuleRefusal(f.text) : isGrantableDenial(f.text);
7925
+ if (grantable) this.reportDenial(f.callId, f.name, f.input);
7149
7926
  else this.seenFailedCalls.add(f.callId);
7150
7927
  }
7151
7928
  }
@@ -7507,6 +8284,7 @@ ${text}` : text;
7507
8284
  await this.prepareEvidenceDir();
7508
8285
  const { bin, features } = await this.deps.resolveAgent();
7509
8286
  const savedRules = await (this.deps.savedRules?.(this.record.repository) ?? []);
8287
+ this.savedRulesNow = savedRules;
7510
8288
  this.inheritedNow = await this.readInheritedRules();
7511
8289
  const allowedTools = [
7512
8290
  .../* @__PURE__ */ new Set([
@@ -7729,7 +8507,12 @@ ${text}` : text;
7729
8507
  interrupted ? turn.isError ? null : turn.text : turn.text,
7730
8508
  screenshots
7731
8509
  );
7732
- const prUrl = push.branch ? await this.openPullRequest(text, screenshots) : null;
8510
+ const loop = this.record.metricLoop ?? null;
8511
+ const openPr = !loop || metricLoopShouldOpenPullRequest({ loop, turnText: text, interrupted });
8512
+ const prUrl = push.branch && openPr ? await this.openPullRequest(text, screenshots) : null;
8513
+ if (loop) {
8514
+ this.record.metricLoop = { ...loop, previous: nextMetricLoopPrevious(loop, text) };
8515
+ }
7733
8516
  this.record.turnActive = false;
7734
8517
  await this.deps.store.save(this.record);
7735
8518
  this.emit({
@@ -7855,7 +8638,7 @@ ${text}` : text;
7855
8638
  async publishScreenshots() {
7856
8639
  const { workBranch, repoDir, cwd, repository } = this.record;
7857
8640
  const repo = parseRepoUrl(
7858
- repository ?? (repoDir ? `https://github.com/${basename2(dirname9(repoDir))}/${basename2(repoDir)}` : "")
8641
+ repository ?? (repoDir ? `https://github.com/${basename2(dirname10(repoDir))}/${basename2(repoDir)}` : "")
7859
8642
  );
7860
8643
  if (!workBranch || !repoDir || !repo) return "";
7861
8644
  const res = await publishEvidence({ repoDir, worktree: cwd, workBranch, repo });
@@ -7890,6 +8673,7 @@ ${text}` : text;
7890
8673
  const { workBranch, baseSha, cwd, repoDir } = this.record;
7891
8674
  if (!workBranch || !baseSha) return { branch: null, failed: false };
7892
8675
  await this.prepareEvidenceDir();
8676
+ this.driver.beforeCommit?.(cwd);
7893
8677
  const res = await commitAndPush({
7894
8678
  worktree: cwd,
7895
8679
  workBranch,
@@ -8230,9 +9014,9 @@ var SessionManager = class {
8230
9014
  });
8231
9015
  const driver = this.driverFor(cmd.agent);
8232
9016
  await this.opts.resolveAgent(driver);
8233
- if (!driver.control && (cmd.relayPermissionRequests || cmd.reportToolDenials)) {
9017
+ if (!driver.control && cmd.relayPermissionRequests) {
8234
9018
  this.opts.logger.info(
8235
- `session ${cmd.sessionId}: ${driver.displayName} does not support relaying permission requests or reporting tool denials; its sandbox decides instead`
9019
+ `session ${cmd.sessionId}: ${driver.displayName} does not relay permission requests; its sandbox and rules decide instead`
8236
9020
  );
8237
9021
  }
8238
9022
  const resume = cmd.resume ?? null;
@@ -8290,6 +9074,7 @@ var SessionManager = class {
8290
9074
  ...cmd.reportToolDenials === true ? { reportToolDenials: true } : {},
8291
9075
  ...grantRules(cmd).length ? { grantRules: grantRules(cmd) } : {},
8292
9076
  ...environment?.names.length ? { environmentNames: environment.names } : {},
9077
+ ...cmd.metricLoop ? { metricLoop: cmd.metricLoop } : {},
8293
9078
  createdAt: now,
8294
9079
  updatedAt: now
8295
9080
  };
@@ -8371,10 +9156,10 @@ var SessionManager = class {
8371
9156
  await mkdir9(record.cwd, { recursive: true });
8372
9157
  if (cmd.reviewImages === true && this.opts.reviewImageUploader) {
8373
9158
  record.reviewImages = true;
8374
- await mkdir9(join14(record.cwd, EVIDENCE_DIR), { recursive: true });
9159
+ await mkdir9(join15(record.cwd, EVIDENCE_DIR), { recursive: true });
8375
9160
  }
8376
9161
  const reference = cmd.referenceRepository;
8377
- const referenceDir = join14(record.cwd, RUNNER_REFERENCE_REPOSITORY_DIR);
9162
+ const referenceDir = join15(record.cwd, RUNNER_REFERENCE_REPOSITORY_DIR);
8378
9163
  const fromEntry = keptEntry?.reference;
8379
9164
  const entryUrl = () => fromEntry ? fromEntry.url ?? legacyUrl(fromEntry, this.opts.config.reposDir) : null;
8380
9165
  const fromSession = keepWorkspace ? earlier.find((o) => o.record.cwd === record.cwd)?.record.referenceRepository : void 0;
@@ -8386,9 +9171,9 @@ var SessionManager = class {
8386
9171
  dir: fromEntry.dir,
8387
9172
  repoDir: fromEntry.repoDir
8388
9173
  } : void 0);
8389
- const keptReference = candidate && existsSync(candidate.dir) ? candidate : void 0;
9174
+ const keptReference = candidate && existsSync2(candidate.dir) ? candidate : void 0;
8390
9175
  const referenceHold = !reference?.url ? null : this.opts.jobs ? this.opts.jobs.holdForRemoval(referenceDir) : () => void 0;
8391
- if (reference?.url && keepWorkspace && (keptReference || existsSync(referenceDir))) {
9176
+ if (reference?.url && keepWorkspace && (keptReference || existsSync2(referenceDir))) {
8392
9177
  if (keptReference) record.referenceRepository = keptReference;
8393
9178
  referenceHold?.();
8394
9179
  this.opts.logger.info(
@@ -8404,7 +9189,7 @@ var SessionManager = class {
8404
9189
  url: reference.url,
8405
9190
  baseRef: reference.baseRef ?? null,
8406
9191
  reposDir: this.opts.config.reposDir,
8407
- dir: join14(record.cwd, RUNNER_REFERENCE_REPOSITORY_DIR),
9192
+ dir: join15(record.cwd, RUNNER_REFERENCE_REPOSITORY_DIR),
8408
9193
  protocol: this.opts.config.gitProtocol
8409
9194
  }).finally(() => referenceHold?.());
8410
9195
  record.referenceRepository = {
@@ -8422,7 +9207,7 @@ var SessionManager = class {
8422
9207
  }
8423
9208
  const deliverable = resume?.deliverable;
8424
9209
  if (typeof deliverable === "string" && deliverable.trim()) {
8425
- await writeFile6(join14(record.cwd, RUNNER_DELIVERABLE_FILE), deliverable, "utf8");
9210
+ await writeFile6(join15(record.cwd, RUNNER_DELIVERABLE_FILE), deliverable, "utf8");
8426
9211
  }
8427
9212
  }
8428
9213
  if (resume) {
@@ -8704,11 +9489,11 @@ var SessionManager = class {
8704
9489
  })
8705
9490
  );
8706
9491
  }
8707
- await rm7(w.cwd, { recursive: true, force: true }).catch(() => void 0);
9492
+ await rm8(w.cwd, { recursive: true, force: true }).catch(() => void 0);
8708
9493
  }
8709
9494
  }
8710
9495
  keptFile() {
8711
- return join14(this.opts.config.stateDir, "kept-for-jobs.json");
9496
+ return join15(this.opts.config.stateDir, "kept-for-jobs.json");
8712
9497
  }
8713
9498
  /** The entry kept for `cwd` in `kept-for-jobs.json`, if any. */
8714
9499
  async keptEntry(cwd) {
@@ -8886,6 +9671,7 @@ var SessionManager = class {
8886
9671
  agentConfig: {
8887
9672
  codexSandbox: this.opts.config.codexSandbox ?? "workspace-write",
8888
9673
  codexNetworkAccess: this.opts.config.codexNetworkAccess === true,
9674
+ cursorSandbox: this.opts.config.cursorSandbox !== false,
8889
9675
  cursorForce: this.opts.config.cursorForce === true
8890
9676
  },
8891
9677
  interruptGraceMs: this.opts.interruptGraceMs,
@@ -8919,8 +9705,8 @@ function alwaysAllowTools(cmd) {
8919
9705
  }
8920
9706
  function legacyUrl(entry, reposDir) {
8921
9707
  const repoDir = resolve3(entry.repoDir);
8922
- if (!samePath(dirname10(dirname10(repoDir)), reposDir)) return null;
8923
- const url = `https://github.com/${basename3(dirname10(repoDir))}/${basename3(repoDir)}`;
9708
+ if (!samePath(dirname11(dirname11(repoDir)), reposDir)) return null;
9709
+ const url = `https://github.com/${basename3(dirname11(repoDir))}/${basename3(repoDir)}`;
8924
9710
  return parseRepoUrl(url) ? url : null;
8925
9711
  }
8926
9712
  function gone(path) {
@@ -8971,6 +9757,8 @@ var RunnerDaemon = class {
8971
9757
  this.jobs = new JobManager({
8972
9758
  stateDir: opts.config.stateDir,
8973
9759
  maxJobs: opts.config.maxJobs,
9760
+ logRetentionDays: opts.config.jobLogRetentionDays,
9761
+ dataRetentionDays: opts.config.jobDataRetentionDays,
8974
9762
  poster: this.api,
8975
9763
  logger: opts.logger,
8976
9764
  onUnauthorized: (err) => this.unauthorized(err),
@@ -9047,6 +9835,7 @@ var RunnerDaemon = class {
9047
9835
  await this.jobs.restore();
9048
9836
  await this.manager.restore();
9049
9837
  await this.manager.releaseKeptForJobs();
9838
+ this.jobs.startPruning();
9050
9839
  logger.info(`dt-runner ${RUNNER_VERSION} connected to ${config.server}`, {
9051
9840
  maxSessions: config.maxSessions,
9052
9841
  maxJobs: config.maxJobs,
@@ -9200,6 +9989,8 @@ var RunnerDaemon = class {
9200
9989
  relaysPermissionRequests: true,
9201
9990
  // And reports denied tool calls, takes grants on them, and keeps saved rules.
9202
9991
  grantsToolPermissions: true,
9992
+ // For Cursor sessions too: its refused shell commands, as `Shell(...)` rules.
9993
+ grantsCursorToolPermissions: true,
9203
9994
  // And attaches a design proposal's rendered screens to its task (`reviewImages`).
9204
9995
  uploadsReviewImages: true,
9205
9996
  // And keeps a continued non-code run's deliverable whole (`resume.deliverable`).
@@ -9332,7 +10123,7 @@ var RunnerDaemon = class {
9332
10123
  if (this.droppedSessionIds.has(id)) return;
9333
10124
  this.droppedSessionIds.add(id);
9334
10125
  this.opts.logger.warn(
9335
- `session ${id}: not a Discovery Tree session id, so it is left out of the heartbeat (its state is in ${join15(this.opts.config.stateDir, "sessions", id)})`
10126
+ `session ${id}: not a Discovery Tree session id, so it is left out of the heartbeat (its state is in ${join16(this.opts.config.stateDir, "sessions", id)})`
9336
10127
  );
9337
10128
  });
9338
10129
  }
@@ -9648,9 +10439,13 @@ Usage:
9648
10439
  dt-runner login [--server <url>] [--name <name>] [--no-browser] [--yes]
9649
10440
  Pair this computer with your Discovery Tree account.
9650
10441
  --yes skips the "is this your account?" question.
9651
- dt-runner start [--max-sessions <n>] [--max-jobs <n>] [--repos-dir <dir>] [--json] [--verbose]
10442
+ dt-runner start [--max-sessions <n>] [--max-jobs <n>] [--job-log-retention-days <n>]
10443
+ [--job-data-retention-days <n>] [--repos-dir <dir>] [--json] [--verbose]
9652
10444
  Run: wait for agent sessions and run them with Claude Code,
9653
10445
  and run the jobs you approve (up to --max-jobs at once).
10446
+ Ended jobs' logs are removed after --job-log-retention-days
10447
+ (default 30; 0 keeps them), their data folders after
10448
+ --job-data-retention-days (default 0: kept).
9654
10449
  dt-runner status Show the configuration and check the connection.
9655
10450
  dt-runner doctor Check Node.js, git and Claude Code on this computer.
9656
10451
  dt-runner logout Forget this runner's token (deletes the config file).
@@ -9681,6 +10476,8 @@ async function main(argv) {
9681
10476
  yes: { type: "boolean", short: "y" },
9682
10477
  "max-sessions": { type: "string" },
9683
10478
  "max-jobs": { type: "string" },
10479
+ "job-log-retention-days": { type: "string" },
10480
+ "job-data-retention-days": { type: "string" },
9684
10481
  "repos-dir": { type: "string" },
9685
10482
  json: { type: "boolean" },
9686
10483
  verbose: { type: "boolean" },
@@ -9702,8 +10499,10 @@ async function main(argv) {
9702
10499
  return login(values.server, values.name, !values["no-browser"], values.yes === true);
9703
10500
  case "start":
9704
10501
  return start({
9705
- maxSessions: values["max-sessions"] !== void 0 ? Number(values["max-sessions"]) : void 0,
9706
- maxJobs: values["max-jobs"] !== void 0 ? Number(values["max-jobs"]) : void 0,
10502
+ maxSessions: numberFlag(values["max-sessions"]),
10503
+ maxJobs: numberFlag(values["max-jobs"]),
10504
+ jobLogRetentionDays: numberFlag(values["job-log-retention-days"]),
10505
+ jobDataRetentionDays: numberFlag(values["job-data-retention-days"]),
9707
10506
  reposDir: values["repos-dir"],
9708
10507
  json: values.json,
9709
10508
  verbose: values.verbose
@@ -9789,6 +10588,8 @@ async function start(opts) {
9789
10588
  const config = resolveConfig(await readConfigFile(paths.configFile), {
9790
10589
  maxSessions: opts.maxSessions,
9791
10590
  maxJobs: opts.maxJobs,
10591
+ jobLogRetentionDays: opts.jobLogRetentionDays,
10592
+ jobDataRetentionDays: opts.jobDataRetentionDays,
9792
10593
  reposDir: opts.reposDir
9793
10594
  });
9794
10595
  if (!config.token) {
@@ -9870,6 +10671,9 @@ async function start(opts) {
9870
10671
  logger.info("dt-runner stopped");
9871
10672
  return exit === "unauthorized" ? 1 : 0;
9872
10673
  }
10674
+ function keptFor(days) {
10675
+ return days > 0 ? `kept ${days} day(s)` : "kept for good";
10676
+ }
9873
10677
  async function status() {
9874
10678
  const paths = runnerPaths();
9875
10679
  const file = await readConfigFile(paths.configFile);
@@ -9886,6 +10690,8 @@ async function status() {
9886
10690
  `Sessions: up to ${config.maxSessions} at once, permission mode ${config.permissionMode}`
9887
10691
  );
9888
10692
  console.log(`Jobs: up to ${config.maxJobs} at once`);
10693
+ console.log(`Job logs: ${keptFor(config.jobLogRetentionDays)} after a job ends`);
10694
+ console.log(`Job data: ${keptFor(config.jobDataRetentionDays)} after a job ends`);
9889
10695
  console.log(`Repos: ${config.reposDir}`);
9890
10696
  console.log(`Worktrees: ${config.worktreesDir}`);
9891
10697
  console.log(`State: ${config.stateDir}`);