@discovery-tree/runner 0.1.20 → 0.1.21
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.
- package/README.md +33 -10
- package/dist/cli.js +717 -94
- 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;
|
|
@@ -189,6 +506,11 @@ Rules:
|
|
|
189
506
|
- Below \`---\`, what it is for and where its output goes, at most
|
|
190
507
|
${MAX_JOB_REQUEST_PURPOSE_CHARS} characters.
|
|
191
508
|
- The same job asked for again while it still waits or runs is not asked for twice.
|
|
509
|
+
- If a job you asked for fails or is lost, this run hears about it: a message while it is
|
|
510
|
+
still going, or a continuation if it has finished. Fix the command and ask again with a
|
|
511
|
+
new DT-JOB block. That ask still waits for the owner's approval. After several failures
|
|
512
|
+
in a row the run is not told again, and the job says that automatic tries have stopped.
|
|
513
|
+
A later run of the same job that exits cleanly starts that count over.
|
|
192
514
|
- 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
515
|
the checkout. Say where its output goes (below \`---\`), and when it is done record where to
|
|
194
516
|
find it, for example in a DT-RESULT block, so it is collected in time.
|
|
@@ -296,9 +618,15 @@ var NOT_GRANTABLE = /the person denied permission|has been denied by a (deny )?r
|
|
|
296
618
|
function isGrantableToolDenial(text) {
|
|
297
619
|
return !!text && GRANTABLE_DENIAL.test(text) && !NOT_GRANTABLE.test(text);
|
|
298
620
|
}
|
|
621
|
+
function isDenyRuleRefusal(text) {
|
|
622
|
+
return !!text && (NOT_GRANTABLE.test(text) || /\bdeny(?:[ -]?list| rules?)\b|\bdenied by (?:a |your )?(?:permission )?rules?\b|\bdenylist/i.test(
|
|
623
|
+
text
|
|
624
|
+
));
|
|
625
|
+
}
|
|
299
626
|
var TOOL_GRANT_RULE_MAX_LENGTH = 500;
|
|
300
627
|
var RUNNER_TOOL_GRANTS_MAX = 500;
|
|
301
628
|
var RULE_SHAPE = /^([A-Za-z][A-Za-z0-9_.-]*)(?:\(([\s\S]*)\))?$/;
|
|
629
|
+
var SHELL_RULE_TOOLS = /* @__PURE__ */ new Set(["Bash", "Shell"]);
|
|
302
630
|
function toolGrantRuleProblem(rule) {
|
|
303
631
|
if (typeof rule !== "string" || !rule.trim()) return "The rule is empty.";
|
|
304
632
|
const r = rule.trim();
|
|
@@ -311,15 +639,17 @@ function toolGrantRuleProblem(rule) {
|
|
|
311
639
|
return "The rule must be a tool name, optionally with what it may do in parentheses, such as Bash(pnpm test *).";
|
|
312
640
|
}
|
|
313
641
|
const [, tool, spec] = m;
|
|
642
|
+
const shell = SHELL_RULE_TOOLS.has(tool);
|
|
643
|
+
const example = tool === "Shell" ? "Shell(pnpm)" : "Bash(pnpm test *)";
|
|
314
644
|
if (spec === void 0) {
|
|
315
|
-
return
|
|
645
|
+
return shell ? `${tool} on its own would allow every shell command; name the command, such as ${example}.` : null;
|
|
316
646
|
}
|
|
317
647
|
if (!spec.trim()) return "Say what the tool may do inside the parentheses, or leave them out.";
|
|
318
648
|
if (/^[\s*:/\\~.]*$/.test(spec.replace(/^domain:/, ""))) {
|
|
319
649
|
return `${tool}(${spec}) would allow everything; narrow it.`;
|
|
320
650
|
}
|
|
321
|
-
if (
|
|
322
|
-
return
|
|
651
|
+
if (shell && /^[\s*]/.test(spec)) {
|
|
652
|
+
return `A shell rule must start with the command, such as ${example}.`;
|
|
323
653
|
}
|
|
324
654
|
return null;
|
|
325
655
|
}
|
|
@@ -331,7 +661,7 @@ function toolGrantRepositoryKey(url) {
|
|
|
331
661
|
}
|
|
332
662
|
|
|
333
663
|
// src/version.ts
|
|
334
|
-
var RUNNER_VERSION = true ? "0.1.
|
|
664
|
+
var RUNNER_VERSION = true ? "0.1.21" : "0.0.0-dev";
|
|
335
665
|
var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
|
|
336
666
|
|
|
337
667
|
// src/api.ts
|
|
@@ -2263,10 +2593,10 @@ var ClaudeCodeRules = class {
|
|
|
2263
2593
|
for (const [folder, entry] of Object.entries(projects)) {
|
|
2264
2594
|
if (!entry || entry.hasTrustDialogAccepted !== true) continue;
|
|
2265
2595
|
if (!isAbsolute3(folder) || this.excluded(folder)) continue;
|
|
2266
|
-
const
|
|
2267
|
-
const text =
|
|
2268
|
-
if (!
|
|
2269
|
-
const roots = [...new Set([folder, ...
|
|
2596
|
+
const git3 = await gitConfigOf(folder);
|
|
2597
|
+
const text = git3 ? await readText(git3.config) : null;
|
|
2598
|
+
if (!git3 || !text || !remoteKeys(text).has(key)) continue;
|
|
2599
|
+
const roots = [...new Set([folder, ...git3.roots].map((d) => resolve(d)))];
|
|
2270
2600
|
const legacy = Array.isArray(entry.allowedTools) ? entry.allowedTools : [];
|
|
2271
2601
|
checkouts.push({ folder, roots, legacy });
|
|
2272
2602
|
}
|
|
@@ -2341,6 +2671,7 @@ function summarizeToolInput(toolName, input) {
|
|
|
2341
2671
|
let summary = null;
|
|
2342
2672
|
switch (toolName) {
|
|
2343
2673
|
case "Bash":
|
|
2674
|
+
case "Shell":
|
|
2344
2675
|
summary = s(i.command);
|
|
2345
2676
|
break;
|
|
2346
2677
|
case "WebFetch":
|
|
@@ -2767,7 +3098,8 @@ var claudeCodeDriver = {
|
|
|
2767
3098
|
launch(input) {
|
|
2768
3099
|
const features = input.features;
|
|
2769
3100
|
const ask = input.askTools;
|
|
2770
|
-
const
|
|
3101
|
+
const ownRules = input.allowedTools.filter((r) => !/^\s*Shell\(/.test(r));
|
|
3102
|
+
const allowedTools = features.settingsFlag || ask.length === 0 ? ownRules : ownRules.filter((r) => !overlapsAsk(r, ask));
|
|
2771
3103
|
return launcherCommand(
|
|
2772
3104
|
input.bin,
|
|
2773
3105
|
claudeArgs({
|
|
@@ -3375,6 +3707,7 @@ function cursorArgs(launch) {
|
|
|
3375
3707
|
}
|
|
3376
3708
|
if (launch.resume) args.push(`--resume=${launch.resume}`);
|
|
3377
3709
|
args.push("--trust");
|
|
3710
|
+
args.push("--sandbox", launch.sandbox ? "enabled" : "disabled");
|
|
3378
3711
|
if (launch.force) args.push("--force");
|
|
3379
3712
|
args.push(launch.prompt.startsWith("-") ? `
|
|
3380
3713
|
${launch.prompt}` : launch.prompt);
|
|
@@ -3481,6 +3814,16 @@ var CursorStreamMapper = class {
|
|
|
3481
3814
|
tool.output = capped.text;
|
|
3482
3815
|
if (capped.truncated) tool.truncated = true;
|
|
3483
3816
|
}
|
|
3817
|
+
const rejected = rejectionOf(call.result);
|
|
3818
|
+
if (kind === "shellToolCall" && rejected !== null) {
|
|
3819
|
+
(out.failedTools ??= []).push({
|
|
3820
|
+
callId: key,
|
|
3821
|
+
name: "Shell",
|
|
3822
|
+
input: { command: typeof call.args?.command === "string" ? call.args.command : "" },
|
|
3823
|
+
text: rejected,
|
|
3824
|
+
denied: true
|
|
3825
|
+
});
|
|
3826
|
+
}
|
|
3484
3827
|
}
|
|
3485
3828
|
out.events.push({ type: "tool_call", providerEventId: key, tool });
|
|
3486
3829
|
}
|
|
@@ -3514,6 +3857,12 @@ function toolNameAndInput(kind, call) {
|
|
|
3514
3857
|
input: call.args ?? {}
|
|
3515
3858
|
};
|
|
3516
3859
|
}
|
|
3860
|
+
function rejectionOf(result) {
|
|
3861
|
+
if (!result || typeof result !== "object") return null;
|
|
3862
|
+
const rejected = result.rejected;
|
|
3863
|
+
if (rejected === void 0) return null;
|
|
3864
|
+
return describe(rejected) || "Rejected";
|
|
3865
|
+
}
|
|
3517
3866
|
function toolOutcome(kind, result) {
|
|
3518
3867
|
if (!result || typeof result !== "object") return { failed: false, output: null };
|
|
3519
3868
|
const r = result;
|
|
@@ -3538,6 +3887,170 @@ function describe(value) {
|
|
|
3538
3887
|
return value == null ? "" : JSON.stringify(value);
|
|
3539
3888
|
}
|
|
3540
3889
|
|
|
3890
|
+
// src/drivers/cursor/cursor-permissions.ts
|
|
3891
|
+
import { execFileSync } from "node:child_process";
|
|
3892
|
+
import {
|
|
3893
|
+
appendFileSync,
|
|
3894
|
+
existsSync,
|
|
3895
|
+
mkdirSync,
|
|
3896
|
+
readFileSync,
|
|
3897
|
+
rmSync,
|
|
3898
|
+
writeFileSync
|
|
3899
|
+
} from "node:fs";
|
|
3900
|
+
import { dirname as dirname4, isAbsolute as isAbsolute4, join as join6 } from "node:path";
|
|
3901
|
+
var CURSOR_PROJECT_CONFIG = join6(".cursor", "cli.json");
|
|
3902
|
+
var MARKER = join6(".cursor", ".dt-runner-permissions.json");
|
|
3903
|
+
function cursorRules(allowedTools) {
|
|
3904
|
+
return [...new Set(allowedTools.map((r) => r.trim()).filter((r) => /^Shell\(.+\)$/.test(r)))];
|
|
3905
|
+
}
|
|
3906
|
+
function applyCursorPermissions(cwd, rules) {
|
|
3907
|
+
if (!isAbsolute4(cwd) || !existsSync(cwd)) return;
|
|
3908
|
+
const file = join6(cwd, CURSOR_PROJECT_CONFIG);
|
|
3909
|
+
try {
|
|
3910
|
+
const marker = readMarker(cwd);
|
|
3911
|
+
if (rules.length === 0 && !marker) return;
|
|
3912
|
+
const text = existsSync(file) ? readFileSync(file, "utf8") : null;
|
|
3913
|
+
const read = readConfig(file);
|
|
3914
|
+
if (read === "unreadable") return;
|
|
3915
|
+
const hadPermissions = read !== null && isObject2(read.permissions);
|
|
3916
|
+
const hadAllow = hadPermissions && Array.isArray(read.permissions.allow);
|
|
3917
|
+
const config = read ?? {};
|
|
3918
|
+
const permissions = permissionsOf(config);
|
|
3919
|
+
const previous = new Set(marker?.added ?? []);
|
|
3920
|
+
const own = allowOf(permissions).filter((r) => !previous.has(r));
|
|
3921
|
+
const added = rules.filter((r) => !own.includes(r));
|
|
3922
|
+
if (added.length === 0) {
|
|
3923
|
+
removeCursorPermissions(cwd);
|
|
3924
|
+
return;
|
|
3925
|
+
}
|
|
3926
|
+
if (!keepOutOfCommits(cwd)) return;
|
|
3927
|
+
permissions.allow = [...own, ...added];
|
|
3928
|
+
config.permissions = permissions;
|
|
3929
|
+
const written = `${JSON.stringify(config, null, 2)}
|
|
3930
|
+
`;
|
|
3931
|
+
const next = marker ? { ...marker, added, written } : { added, created: read === null, original: text, written, hadPermissions, hadAllow };
|
|
3932
|
+
mkdirSync(dirname4(file), { recursive: true });
|
|
3933
|
+
writeFileSync(join6(cwd, MARKER), `${JSON.stringify(next)}
|
|
3934
|
+
`);
|
|
3935
|
+
writeFileSync(file, written);
|
|
3936
|
+
} catch {
|
|
3937
|
+
}
|
|
3938
|
+
}
|
|
3939
|
+
function removeCursorPermissions(cwd) {
|
|
3940
|
+
if (!isAbsolute4(cwd)) return;
|
|
3941
|
+
const marker = readMarker(cwd);
|
|
3942
|
+
if (!marker) return;
|
|
3943
|
+
const file = join6(cwd, CURSOR_PROJECT_CONFIG);
|
|
3944
|
+
try {
|
|
3945
|
+
const text = existsSync(file) ? readFileSync(file, "utf8") : null;
|
|
3946
|
+
if (text === marker.written || text === null) {
|
|
3947
|
+
if (marker.original === null) rmSync(file, { force: true });
|
|
3948
|
+
else if (text !== null) writeFileSync(file, marker.original);
|
|
3949
|
+
} else {
|
|
3950
|
+
const read = readConfig(file);
|
|
3951
|
+
if (read === "unreadable") return;
|
|
3952
|
+
if (read !== null) {
|
|
3953
|
+
const permissions = permissionsOf(read);
|
|
3954
|
+
const added = new Set(marker.added);
|
|
3955
|
+
const allow = allowOf(permissions).filter((r) => !added.has(r));
|
|
3956
|
+
if (allow.length || marker.hadAllow) permissions.allow = allow;
|
|
3957
|
+
else delete permissions.allow;
|
|
3958
|
+
if (Object.keys(permissions).length || marker.hadPermissions)
|
|
3959
|
+
read.permissions = permissions;
|
|
3960
|
+
else delete read.permissions;
|
|
3961
|
+
if (marker.created && Object.keys(read).length === 0) rmSync(file, { force: true });
|
|
3962
|
+
else writeFileSync(file, `${JSON.stringify(read, null, 2)}
|
|
3963
|
+
`);
|
|
3964
|
+
}
|
|
3965
|
+
}
|
|
3966
|
+
if (gitTracks(cwd, CURSOR_PROJECT_CONFIG) === true) {
|
|
3967
|
+
git2(cwd, ["update-index", "--no-skip-worktree", "--", CURSOR_PROJECT_CONFIG]);
|
|
3968
|
+
}
|
|
3969
|
+
} catch {
|
|
3970
|
+
return;
|
|
3971
|
+
}
|
|
3972
|
+
rmSync(join6(cwd, MARKER), { force: true });
|
|
3973
|
+
}
|
|
3974
|
+
function keepOutOfCommits(cwd) {
|
|
3975
|
+
const tracked = gitTracks(cwd, CURSOR_PROJECT_CONFIG);
|
|
3976
|
+
if (tracked === null) return true;
|
|
3977
|
+
try {
|
|
3978
|
+
excludeFromGit2(cwd, toPattern(MARKER));
|
|
3979
|
+
if (tracked) {
|
|
3980
|
+
git2(cwd, ["update-index", "--skip-worktree", "--", CURSOR_PROJECT_CONFIG]);
|
|
3981
|
+
} else {
|
|
3982
|
+
excludeFromGit2(cwd, toPattern(CURSOR_PROJECT_CONFIG));
|
|
3983
|
+
}
|
|
3984
|
+
return true;
|
|
3985
|
+
} catch {
|
|
3986
|
+
return false;
|
|
3987
|
+
}
|
|
3988
|
+
}
|
|
3989
|
+
function readMarker(cwd) {
|
|
3990
|
+
try {
|
|
3991
|
+
const m = JSON.parse(readFileSync(join6(cwd, MARKER), "utf8"));
|
|
3992
|
+
if (!Array.isArray(m.added) || typeof m.written !== "string") return null;
|
|
3993
|
+
return {
|
|
3994
|
+
added: m.added.filter((r) => typeof r === "string"),
|
|
3995
|
+
created: m.created === true,
|
|
3996
|
+
original: typeof m.original === "string" ? m.original : null,
|
|
3997
|
+
written: m.written,
|
|
3998
|
+
hadPermissions: m.hadPermissions === true,
|
|
3999
|
+
hadAllow: m.hadAllow === true
|
|
4000
|
+
};
|
|
4001
|
+
} catch {
|
|
4002
|
+
return null;
|
|
4003
|
+
}
|
|
4004
|
+
}
|
|
4005
|
+
var isObject2 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
4006
|
+
function readConfig(file) {
|
|
4007
|
+
if (!existsSync(file)) return null;
|
|
4008
|
+
try {
|
|
4009
|
+
const parsed = JSON.parse(readFileSync(file, "utf8"));
|
|
4010
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : "unreadable";
|
|
4011
|
+
} catch {
|
|
4012
|
+
return "unreadable";
|
|
4013
|
+
}
|
|
4014
|
+
}
|
|
4015
|
+
function permissionsOf(config) {
|
|
4016
|
+
const p = config.permissions;
|
|
4017
|
+
return p && typeof p === "object" && !Array.isArray(p) ? { ...p } : {};
|
|
4018
|
+
}
|
|
4019
|
+
function allowOf(permissions) {
|
|
4020
|
+
return Array.isArray(permissions.allow) ? permissions.allow.filter((r) => typeof r === "string") : [];
|
|
4021
|
+
}
|
|
4022
|
+
var toPattern = (path) => `/${path.split("\\").join("/")}`;
|
|
4023
|
+
function gitTracks(cwd, path) {
|
|
4024
|
+
try {
|
|
4025
|
+
git2(cwd, ["rev-parse", "--is-inside-work-tree"]);
|
|
4026
|
+
} catch {
|
|
4027
|
+
return null;
|
|
4028
|
+
}
|
|
4029
|
+
try {
|
|
4030
|
+
git2(cwd, ["ls-files", "--error-unmatch", "--", path]);
|
|
4031
|
+
return true;
|
|
4032
|
+
} catch {
|
|
4033
|
+
return false;
|
|
4034
|
+
}
|
|
4035
|
+
}
|
|
4036
|
+
function excludeFromGit2(cwd, pattern) {
|
|
4037
|
+
const rel = git2(cwd, ["rev-parse", "--git-path", "info/exclude"]).trim();
|
|
4038
|
+
const exclude = isAbsolute4(rel) ? rel : join6(cwd, rel);
|
|
4039
|
+
const current2 = existsSync(exclude) ? readFileSync(exclude, "utf8") : "";
|
|
4040
|
+
if (current2.split(/\r?\n/).includes(pattern)) return;
|
|
4041
|
+
mkdirSync(dirname4(exclude), { recursive: true });
|
|
4042
|
+
appendFileSync(exclude, `${current2 && !current2.endsWith("\n") ? "\n" : ""}${pattern}
|
|
4043
|
+
`);
|
|
4044
|
+
}
|
|
4045
|
+
function git2(cwd, args) {
|
|
4046
|
+
return execFileSync("git", args, {
|
|
4047
|
+
cwd,
|
|
4048
|
+
encoding: "utf8",
|
|
4049
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
4050
|
+
timeout: 1e4
|
|
4051
|
+
});
|
|
4052
|
+
}
|
|
4053
|
+
|
|
3541
4054
|
// src/drivers/cursor.ts
|
|
3542
4055
|
var cursorDriver = {
|
|
3543
4056
|
kind: "cursor",
|
|
@@ -3555,18 +4068,23 @@ var cursorDriver = {
|
|
|
3555
4068
|
doctor: doctor3,
|
|
3556
4069
|
validateModel: (model) => assertValidCursorModel(model),
|
|
3557
4070
|
launch(input) {
|
|
4071
|
+
applyCursorPermissions(input.cwd, cursorRules(input.allowedTools));
|
|
3558
4072
|
const prompt = input.resume ? input.prompt ?? "" : cursorFirstPrompt(input.systemPrompt, input.prompt ?? "");
|
|
3559
4073
|
return launcherCommand(
|
|
3560
4074
|
input.bin,
|
|
3561
4075
|
cursorArgs({
|
|
3562
4076
|
model: input.model,
|
|
3563
4077
|
resume: input.resume,
|
|
4078
|
+
// On unless the config turns the worktree sandbox off.
|
|
4079
|
+
sandbox: input.agentConfig?.cursorSandbox !== false,
|
|
3564
4080
|
force: input.agentConfig?.cursorForce === true,
|
|
3565
4081
|
prompt
|
|
3566
4082
|
})
|
|
3567
4083
|
);
|
|
3568
4084
|
},
|
|
3569
4085
|
createMapper: () => new CursorStreamMapper(),
|
|
4086
|
+
// The runner's rules come back out of `.cursor/cli.json` before it commits the agent's work.
|
|
4087
|
+
beforeCommit: (cwd) => removeCursorPermissions(cwd),
|
|
3570
4088
|
looksLikeSignInFailure: looksLikeCursorSignInFailure,
|
|
3571
4089
|
turnFailedToSignIn: (turn) => turn.isError && looksLikeCursorSignInFailure(turn.text),
|
|
3572
4090
|
signInFix: (env) => cursorSignInFix(env),
|
|
@@ -3650,7 +4168,7 @@ function agentDriverKinds() {
|
|
|
3650
4168
|
// src/config.ts
|
|
3651
4169
|
import { chmod, mkdir as mkdir3, readFile as readFile4, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
|
|
3652
4170
|
import { homedir as homedir2 } from "node:os";
|
|
3653
|
-
import { dirname as
|
|
4171
|
+
import { dirname as dirname5, join as join7 } from "node:path";
|
|
3654
4172
|
|
|
3655
4173
|
// src/invocation.ts
|
|
3656
4174
|
var RUNNER_PACKAGE = "@discovery-tree/runner";
|
|
@@ -3666,21 +4184,21 @@ function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
|
|
|
3666
4184
|
function runnerPaths(env = process.env) {
|
|
3667
4185
|
const home = homedir2();
|
|
3668
4186
|
if (process.platform === "win32") {
|
|
3669
|
-
const roaming = env.APPDATA ||
|
|
3670
|
-
const local = env.LOCALAPPDATA ||
|
|
4187
|
+
const roaming = env.APPDATA || join7(home, "AppData", "Roaming");
|
|
4188
|
+
const local = env.LOCALAPPDATA || join7(home, "AppData", "Local");
|
|
3671
4189
|
return {
|
|
3672
|
-
configFile:
|
|
3673
|
-
dataDir:
|
|
3674
|
-
stateDir:
|
|
4190
|
+
configFile: join7(roaming, "discovery-tree", "runner.json"),
|
|
4191
|
+
dataDir: join7(local, "discovery-tree", "runner"),
|
|
4192
|
+
stateDir: join7(local, "discovery-tree", "runner", "state")
|
|
3675
4193
|
};
|
|
3676
4194
|
}
|
|
3677
|
-
const config = env.XDG_CONFIG_HOME ||
|
|
3678
|
-
const data = env.XDG_DATA_HOME ||
|
|
3679
|
-
const state = env.XDG_STATE_HOME ||
|
|
4195
|
+
const config = env.XDG_CONFIG_HOME || join7(home, ".config");
|
|
4196
|
+
const data = env.XDG_DATA_HOME || join7(home, ".local", "share");
|
|
4197
|
+
const state = env.XDG_STATE_HOME || join7(home, ".local", "state");
|
|
3680
4198
|
return {
|
|
3681
|
-
configFile:
|
|
3682
|
-
dataDir:
|
|
3683
|
-
stateDir:
|
|
4199
|
+
configFile: join7(config, "discovery-tree", "runner.json"),
|
|
4200
|
+
dataDir: join7(data, "discovery-tree", "runner"),
|
|
4201
|
+
stateDir: join7(state, "discovery-tree", "runner")
|
|
3684
4202
|
};
|
|
3685
4203
|
}
|
|
3686
4204
|
var PERMISSION_MODES = [
|
|
@@ -3875,7 +4393,7 @@ var DEFAULT_DISALLOWED_TOOLS = [
|
|
|
3875
4393
|
];
|
|
3876
4394
|
function configDirRules(configFile, platform = process.platform) {
|
|
3877
4395
|
if (platform === "win32") return [];
|
|
3878
|
-
const dir =
|
|
4396
|
+
const dir = dirname5(configFile);
|
|
3879
4397
|
if (!dir.startsWith("/")) return [];
|
|
3880
4398
|
return [`Read(/${dir}/**)`, `Edit(/${dir}/**)`];
|
|
3881
4399
|
}
|
|
@@ -3899,7 +4417,7 @@ async function readConfigFile(file) {
|
|
|
3899
4417
|
}
|
|
3900
4418
|
}
|
|
3901
4419
|
async function writeConfigFile(file, config) {
|
|
3902
|
-
await mkdir3(
|
|
4420
|
+
await mkdir3(dirname5(file), { recursive: true, mode: 448 });
|
|
3903
4421
|
await writeFile2(file, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
|
|
3904
4422
|
await chmod(file, 384).catch(() => void 0);
|
|
3905
4423
|
}
|
|
@@ -3954,6 +4472,12 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
3954
4472
|
`codexNetworkAccess in ${paths.configFile} must be true or false (got ${JSON.stringify(codexNetwork)}).`
|
|
3955
4473
|
);
|
|
3956
4474
|
}
|
|
4475
|
+
const cursorSandbox = file?.cursorSandbox;
|
|
4476
|
+
if (cursorSandbox !== void 0 && typeof cursorSandbox !== "boolean") {
|
|
4477
|
+
throw new Error(
|
|
4478
|
+
`cursorSandbox in ${paths.configFile} must be true or false (got ${JSON.stringify(cursorSandbox)}).`
|
|
4479
|
+
);
|
|
4480
|
+
}
|
|
3957
4481
|
const cursorForce = file?.cursorForce;
|
|
3958
4482
|
if (cursorForce !== void 0 && typeof cursorForce !== "boolean") {
|
|
3959
4483
|
throw new Error(
|
|
@@ -3978,8 +4502,8 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
3978
4502
|
name: file?.name ?? null,
|
|
3979
4503
|
maxSessions,
|
|
3980
4504
|
maxJobs,
|
|
3981
|
-
reposDir: overrides.reposDir ?? file?.reposDir ??
|
|
3982
|
-
worktreesDir: file?.worktreesDir ??
|
|
4505
|
+
reposDir: overrides.reposDir ?? file?.reposDir ?? join7(paths.dataDir, "repos"),
|
|
4506
|
+
worktreesDir: file?.worktreesDir ?? join7(paths.dataDir, "worktrees"),
|
|
3983
4507
|
permissionMode: mode,
|
|
3984
4508
|
allowedTools: [...new Set(allowed)],
|
|
3985
4509
|
disallowedTools: [...new Set(disallowed)],
|
|
@@ -3990,6 +4514,8 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
3990
4514
|
idleTimeoutMs: (file?.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES) * 6e4,
|
|
3991
4515
|
codexSandbox,
|
|
3992
4516
|
codexNetworkAccess: codexNetwork === true,
|
|
4517
|
+
// On unless turned off (a value that is not a boolean was refused above).
|
|
4518
|
+
cursorSandbox: cursorSandbox !== false,
|
|
3993
4519
|
cursorForce: cursorForce === true,
|
|
3994
4520
|
stateDir: paths.stateDir,
|
|
3995
4521
|
configFile: paths.configFile
|
|
@@ -3997,7 +4523,7 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
3997
4523
|
}
|
|
3998
4524
|
|
|
3999
4525
|
// src/daemon.ts
|
|
4000
|
-
import { join as
|
|
4526
|
+
import { join as join16 } from "node:path";
|
|
4001
4527
|
|
|
4002
4528
|
// src/backoff.ts
|
|
4003
4529
|
function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
@@ -4020,7 +4546,7 @@ function sleep(ms, signal) {
|
|
|
4020
4546
|
// src/completion.ts
|
|
4021
4547
|
import { mkdtemp as mkdtemp2, rm as rm4 } from "node:fs/promises";
|
|
4022
4548
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
4023
|
-
import { join as
|
|
4549
|
+
import { join as join8 } from "node:path";
|
|
4024
4550
|
var COMPLETION_DENIED_TOOLS = [
|
|
4025
4551
|
"Read",
|
|
4026
4552
|
"Glob",
|
|
@@ -4068,7 +4594,7 @@ async function answerCompletion(req, deps) {
|
|
|
4068
4594
|
try {
|
|
4069
4595
|
const { bin, features } = await deps.claude();
|
|
4070
4596
|
const args = completionArgs(req, features);
|
|
4071
|
-
cwd = await mkdtemp2(
|
|
4597
|
+
cwd = await mkdtemp2(join8(tmpdir2(), "dt-runner-completion-"));
|
|
4072
4598
|
const run = deps.run ?? ((b, a, o) => exec(b, a, { ...o, ownTree: true }));
|
|
4073
4599
|
const input = req.systemPrompt ? `<instructions>
|
|
4074
4600
|
${req.systemPrompt}
|
|
@@ -4123,7 +4649,7 @@ function reportableSessionIds(ids, onDropped = () => void 0) {
|
|
|
4123
4649
|
import { randomBytes as randomBytes3, scrypt, timingSafeEqual } from "node:crypto";
|
|
4124
4650
|
import { realpathSync } from "node:fs";
|
|
4125
4651
|
import { mkdir as mkdir6, readFile as readFile8, readdir as readdir2, stat as stat4 } from "node:fs/promises";
|
|
4126
|
-
import { basename, dirname as
|
|
4652
|
+
import { basename, dirname as dirname8, isAbsolute as isAbsolute5, join as join11, resolve as resolve2, sep as sep3 } from "node:path";
|
|
4127
4653
|
|
|
4128
4654
|
// src/environment.ts
|
|
4129
4655
|
function sessionEnvironment(raw) {
|
|
@@ -4412,9 +4938,9 @@ function fitEvent(body) {
|
|
|
4412
4938
|
|
|
4413
4939
|
// src/fsutil.ts
|
|
4414
4940
|
import { mkdir as mkdir4, readFile as readFile5, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
|
|
4415
|
-
import { dirname as
|
|
4941
|
+
import { dirname as dirname6 } from "node:path";
|
|
4416
4942
|
async function writeJsonAtomic(file, value) {
|
|
4417
|
-
await mkdir4(
|
|
4943
|
+
await mkdir4(dirname6(file), { recursive: true });
|
|
4418
4944
|
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
4419
4945
|
await writeFile3(tmp, JSON.stringify(value), { mode: 384 });
|
|
4420
4946
|
await rename2(tmp, file);
|
|
@@ -4857,15 +5383,15 @@ var JobOutbox = class _JobOutbox {
|
|
|
4857
5383
|
|
|
4858
5384
|
// src/jobs/job-process.ts
|
|
4859
5385
|
import { execFile, spawn as spawn4 } from "node:child_process";
|
|
4860
|
-
import { closeSync, openSync, readFileSync, readdirSync } from "node:fs";
|
|
5386
|
+
import { closeSync, openSync, readFileSync as readFileSync2, readdirSync } from "node:fs";
|
|
4861
5387
|
import { readFile as readFile7, writeFile as writeFile4 } from "node:fs/promises";
|
|
4862
|
-
import { dirname as
|
|
5388
|
+
import { dirname as dirname7, join as join10 } from "node:path";
|
|
4863
5389
|
|
|
4864
5390
|
// src/lock.ts
|
|
4865
5391
|
import { mkdir as mkdir5, open as open2, readFile as readFile6, rm as rm5 } from "node:fs/promises";
|
|
4866
|
-
import { join as
|
|
5392
|
+
import { join as join9 } from "node:path";
|
|
4867
5393
|
function lockFile(stateDir) {
|
|
4868
|
-
return
|
|
5394
|
+
return join9(stateDir, "daemon.pid");
|
|
4869
5395
|
}
|
|
4870
5396
|
function pidAlive(pid) {
|
|
4871
5397
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
@@ -5021,9 +5547,9 @@ async function spawnJob(input) {
|
|
|
5021
5547
|
return { pid: child.pid, startedAt: Date.now() - 500, child, exited };
|
|
5022
5548
|
}
|
|
5023
5549
|
async function spawnWindowsJob(input) {
|
|
5024
|
-
const dir =
|
|
5025
|
-
const scriptFile =
|
|
5026
|
-
const commandFile =
|
|
5550
|
+
const dir = dirname7(input.exitFile);
|
|
5551
|
+
const scriptFile = join10(dir, "job.ps1");
|
|
5552
|
+
const commandFile = join10(dir, "command.ps1");
|
|
5027
5553
|
const bom = "\uFEFF";
|
|
5028
5554
|
await writeFile4(commandFile, bom + powershellCommandScript(input.command), { mode: 384 });
|
|
5029
5555
|
for (const f of [input.stdoutFile, input.stderrFile]) await writeFile4(f, "", { flag: "a" });
|
|
@@ -5138,7 +5664,7 @@ function parseElapsed(text) {
|
|
|
5138
5664
|
}
|
|
5139
5665
|
function procStat(pid) {
|
|
5140
5666
|
try {
|
|
5141
|
-
const stat5 =
|
|
5667
|
+
const stat5 = readFileSync2(`/proc/${pid}/stat`, "utf8");
|
|
5142
5668
|
return stat5.slice(stat5.lastIndexOf(")") + 2).split(" ");
|
|
5143
5669
|
} catch {
|
|
5144
5670
|
return null;
|
|
@@ -5244,7 +5770,7 @@ function secretWait() {
|
|
|
5244
5770
|
var JobManager = class {
|
|
5245
5771
|
constructor(opts) {
|
|
5246
5772
|
this.opts = opts;
|
|
5247
|
-
this.root =
|
|
5773
|
+
this.root = join11(opts.stateDir, "jobs");
|
|
5248
5774
|
}
|
|
5249
5775
|
jobs = /* @__PURE__ */ new Map();
|
|
5250
5776
|
/** Folders being removed now, with how many removals hold each (see `holdForRemoval`). */
|
|
@@ -5264,7 +5790,7 @@ var JobManager = class {
|
|
|
5264
5790
|
root;
|
|
5265
5791
|
/** The folder a job's record, log and outbox live in. */
|
|
5266
5792
|
jobDir(jobId) {
|
|
5267
|
-
return
|
|
5793
|
+
return join11(this.root, jobId);
|
|
5268
5794
|
}
|
|
5269
5795
|
/**
|
|
5270
5796
|
* Jobs the runner reports in `activeJobIds`: a live process, or an end not yet reported.
|
|
@@ -5360,7 +5886,7 @@ var JobManager = class {
|
|
|
5360
5886
|
let table = null;
|
|
5361
5887
|
for (const entry of entries) {
|
|
5362
5888
|
if (!isRunnerSessionId(entry)) continue;
|
|
5363
|
-
const record = await readJson(
|
|
5889
|
+
const record = await readJson(join11(this.jobDir(entry), "job.json")).catch(
|
|
5364
5890
|
() => null
|
|
5365
5891
|
);
|
|
5366
5892
|
if (!record || record.jobId !== entry || record.settled) continue;
|
|
@@ -5526,7 +6052,7 @@ var JobManager = class {
|
|
|
5526
6052
|
/* -------------------------------------------------------------------------------- */
|
|
5527
6053
|
async start(id, cmd) {
|
|
5528
6054
|
if (this.jobs.has(id)) return { ok: true };
|
|
5529
|
-
const earlier = await readJson(
|
|
6055
|
+
const earlier = await readJson(join11(this.jobDir(id), "job.json")).catch(() => null);
|
|
5530
6056
|
if (earlier) {
|
|
5531
6057
|
return earlier.pid === null || earlier.ended?.status === "failed" ? { ok: false, error: "The job could not be started on this runner." } : { ok: true };
|
|
5532
6058
|
}
|
|
@@ -5538,7 +6064,7 @@ var JobManager = class {
|
|
|
5538
6064
|
return { ok: false, error: "The job has no command to run." };
|
|
5539
6065
|
}
|
|
5540
6066
|
const cwd = typeof cmd.cwd === "string" ? cmd.cwd : "";
|
|
5541
|
-
const cwdProblem = treeJobCwdProblem(cwd) ?? (
|
|
6067
|
+
const cwdProblem = treeJobCwdProblem(cwd) ?? (isAbsolute5(cwd) ? null : "must be an absolute path");
|
|
5542
6068
|
if (cwdProblem) return { ok: false, error: `The job's directory ${cwdProblem}.` };
|
|
5543
6069
|
const isDir2 = await stat4(cwd).then(
|
|
5544
6070
|
(s) => s.isDirectory(),
|
|
@@ -5618,9 +6144,9 @@ var JobManager = class {
|
|
|
5618
6144
|
command,
|
|
5619
6145
|
cwd,
|
|
5620
6146
|
env,
|
|
5621
|
-
stdoutFile:
|
|
5622
|
-
stderrFile:
|
|
5623
|
-
exitFile:
|
|
6147
|
+
stdoutFile: join11(dir, "stdout.log"),
|
|
6148
|
+
stderrFile: join11(dir, "stderr.log"),
|
|
6149
|
+
exitFile: join11(dir, "exit-code")
|
|
5624
6150
|
});
|
|
5625
6151
|
} catch (err) {
|
|
5626
6152
|
const error = safeError(err, redactor);
|
|
@@ -5788,7 +6314,7 @@ var JobManager = class {
|
|
|
5788
6314
|
};
|
|
5789
6315
|
job.outbox = await JobOutbox.open({
|
|
5790
6316
|
jobId: record.jobId,
|
|
5791
|
-
file:
|
|
6317
|
+
file: join11(dir, "outbox.json"),
|
|
5792
6318
|
poster: this.opts.poster,
|
|
5793
6319
|
logger: this.opts.logger,
|
|
5794
6320
|
batchDelayMs: this.opts.outboxBatchDelayMs,
|
|
@@ -5810,8 +6336,8 @@ var JobManager = class {
|
|
|
5810
6336
|
});
|
|
5811
6337
|
const cursor = job.outbox.cursor ?? startCursor();
|
|
5812
6338
|
job.readers = [
|
|
5813
|
-
new LogFileReader(
|
|
5814
|
-
new LogFileReader(
|
|
6339
|
+
new LogFileReader(join11(dir, "stdout.log"), "stdout", cursor.stdout),
|
|
6340
|
+
new LogFileReader(join11(dir, "stderr.log"), "stderr", cursor.stderr)
|
|
5815
6341
|
];
|
|
5816
6342
|
return job;
|
|
5817
6343
|
}
|
|
@@ -6045,11 +6571,11 @@ function canonical(p) {
|
|
|
6045
6571
|
for (; ; ) {
|
|
6046
6572
|
try {
|
|
6047
6573
|
const real = realpathSync.native(head);
|
|
6048
|
-
return tail ?
|
|
6574
|
+
return tail ? join11(real, tail) : real;
|
|
6049
6575
|
} catch {
|
|
6050
|
-
const up =
|
|
6576
|
+
const up = dirname8(head);
|
|
6051
6577
|
if (up === head) return full;
|
|
6052
|
-
tail = tail ?
|
|
6578
|
+
tail = tail ? join11(basename(head), tail) : basename(head);
|
|
6053
6579
|
head = up;
|
|
6054
6580
|
}
|
|
6055
6581
|
}
|
|
@@ -6154,11 +6680,11 @@ function queueEndReport(outbox, ended) {
|
|
|
6154
6680
|
);
|
|
6155
6681
|
}
|
|
6156
6682
|
async function saveRecord(dir, record) {
|
|
6157
|
-
await writeJsonAtomic(
|
|
6683
|
+
await writeJsonAtomic(join11(dir, "job.json"), record);
|
|
6158
6684
|
}
|
|
6159
6685
|
async function readExitFile(dir) {
|
|
6160
6686
|
try {
|
|
6161
|
-
const code = Number.parseInt((await readFile8(
|
|
6687
|
+
const code = Number.parseInt((await readFile8(join11(dir, "exit-code"), "utf8")).trim(), 10);
|
|
6162
6688
|
return Number.isInteger(code) ? { code, signal: null } : null;
|
|
6163
6689
|
} catch {
|
|
6164
6690
|
return null;
|
|
@@ -6170,13 +6696,13 @@ function safeError(err, redactor) {
|
|
|
6170
6696
|
}
|
|
6171
6697
|
|
|
6172
6698
|
// src/session-manager.ts
|
|
6173
|
-
import { existsSync, lstatSync } from "node:fs";
|
|
6699
|
+
import { existsSync as existsSync2, lstatSync } from "node:fs";
|
|
6174
6700
|
import { mkdir as mkdir9, rm as rm7, writeFile as writeFile6 } from "node:fs/promises";
|
|
6175
|
-
import { basename as basename3, dirname as
|
|
6701
|
+
import { basename as basename3, dirname as dirname11, join as join15, resolve as resolve3 } from "node:path";
|
|
6176
6702
|
|
|
6177
6703
|
// src/prompt-images.ts
|
|
6178
6704
|
import { mkdir as mkdir7, writeFile as writeFile5 } from "node:fs/promises";
|
|
6179
|
-
import { join as
|
|
6705
|
+
import { join as join12 } from "node:path";
|
|
6180
6706
|
var EXTENSIONS = {
|
|
6181
6707
|
"image/png": ".png",
|
|
6182
6708
|
"image/jpeg": ".jpg",
|
|
@@ -6193,7 +6719,7 @@ function promptImageFileName(index, filename, mimeType) {
|
|
|
6193
6719
|
async function savePromptImages(input) {
|
|
6194
6720
|
const out = { saved: [], failed: [] };
|
|
6195
6721
|
if (input.images.length === 0) return out;
|
|
6196
|
-
const dir =
|
|
6722
|
+
const dir = join12(input.cwd, RUNNER_TASK_IMAGES_DIR);
|
|
6197
6723
|
await mkdir7(dir, { recursive: true });
|
|
6198
6724
|
if (input.inRepository) {
|
|
6199
6725
|
await excludeFromGit(
|
|
@@ -6205,7 +6731,7 @@ async function savePromptImages(input) {
|
|
|
6205
6731
|
for (const [index, image] of input.images.entries()) {
|
|
6206
6732
|
try {
|
|
6207
6733
|
const res = await input.fetcher.getPromptImage(input.sessionId, image.attachmentId);
|
|
6208
|
-
const path =
|
|
6734
|
+
const path = join12(
|
|
6209
6735
|
dir,
|
|
6210
6736
|
promptImageFileName(index, image.filename, res.mimeType || image.mimeType)
|
|
6211
6737
|
);
|
|
@@ -6465,11 +6991,11 @@ function takeBatch(pending) {
|
|
|
6465
6991
|
// src/session.ts
|
|
6466
6992
|
import { spawn as spawn5 } from "node:child_process";
|
|
6467
6993
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
6468
|
-
import { basename as basename2, dirname as
|
|
6994
|
+
import { basename as basename2, dirname as dirname10 } from "node:path";
|
|
6469
6995
|
import { createInterface as createInterface2 } from "node:readline";
|
|
6470
6996
|
|
|
6471
6997
|
// src/tool-grants.ts
|
|
6472
|
-
import { dirname as
|
|
6998
|
+
import { dirname as dirname9, join as join13, posix } from "node:path";
|
|
6473
6999
|
var isGrantableDenial = isGrantableToolDenial;
|
|
6474
7000
|
var FILE_TOOLS2 = /* @__PURE__ */ new Set(["Read", "Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
6475
7001
|
var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
@@ -6480,6 +7006,9 @@ function suggestRules(toolName, input, allowedTools = []) {
|
|
|
6480
7006
|
if (toolName === "Bash") {
|
|
6481
7007
|
const command = str(i.command);
|
|
6482
7008
|
if (command) out = bashRules(command, allowedTools);
|
|
7009
|
+
} else if (toolName === "Shell") {
|
|
7010
|
+
const command = str(i.command);
|
|
7011
|
+
if (command) out = cursorShellRules(command, allowedTools);
|
|
6483
7012
|
} else if (toolName === "WebFetch") {
|
|
6484
7013
|
const host = hostOf(str(i.url));
|
|
6485
7014
|
if (host) out = same(`WebFetch(domain:${host})`);
|
|
@@ -6538,6 +7067,76 @@ function bashRules(command, allowedTools) {
|
|
|
6538
7067
|
const once = segment.length <= 400 ? `Bash(${segment})` : prefix;
|
|
6539
7068
|
return { suggestedRule: prefix, onceRule: once };
|
|
6540
7069
|
}
|
|
7070
|
+
var CURSOR_RUNS_ANY_COMMAND = /* @__PURE__ */ new Set([
|
|
7071
|
+
"bash",
|
|
7072
|
+
"sh",
|
|
7073
|
+
"zsh",
|
|
7074
|
+
"dash",
|
|
7075
|
+
"ksh",
|
|
7076
|
+
"fish",
|
|
7077
|
+
"pwsh",
|
|
7078
|
+
"powershell",
|
|
7079
|
+
"cmd",
|
|
7080
|
+
"doas",
|
|
7081
|
+
"su",
|
|
7082
|
+
"eval",
|
|
7083
|
+
"watch",
|
|
7084
|
+
"parallel",
|
|
7085
|
+
"ssh",
|
|
7086
|
+
"setsid",
|
|
7087
|
+
"chroot",
|
|
7088
|
+
"ionice",
|
|
7089
|
+
"taskset",
|
|
7090
|
+
"flock",
|
|
7091
|
+
"busybox",
|
|
7092
|
+
"unbuffer",
|
|
7093
|
+
"script",
|
|
7094
|
+
"find",
|
|
7095
|
+
"strace",
|
|
7096
|
+
"gdb",
|
|
7097
|
+
"runuser",
|
|
7098
|
+
"chrt",
|
|
7099
|
+
"start",
|
|
7100
|
+
"call"
|
|
7101
|
+
]);
|
|
7102
|
+
function cursorShellRules(command, allowedTools) {
|
|
7103
|
+
const segment = shellSegments(command).find(
|
|
7104
|
+
(s) => !allowedTools.some((rule) => ruleAllows(rule, "Shell", { command: s }))
|
|
7105
|
+
);
|
|
7106
|
+
if (!segment) return null;
|
|
7107
|
+
const parsed = commandWordAt(segment);
|
|
7108
|
+
if (!parsed) return null;
|
|
7109
|
+
const { word, args } = parsed;
|
|
7110
|
+
const quotesBalanced = (segment.match(/'/g) ?? []).length % 2 === 0 && (segment.match(/"/g) ?? []).length % 2 === 0;
|
|
7111
|
+
const exact = args && quotesBalanced && args.length <= 400 && !/[()\r\n*?[\]]/.test(args) ? `Shell(${word}:${args})` : null;
|
|
7112
|
+
const name = word.split(/[\\/]/).pop().toLowerCase().replace(/\.(?:exe|cmd|bat)$/, "");
|
|
7113
|
+
if (CURSOR_RUNS_ANY_COMMAND.has(name) || Object.hasOwn(WRAPPERS, name)) {
|
|
7114
|
+
return exact ? same(exact) : null;
|
|
7115
|
+
}
|
|
7116
|
+
return { suggestedRule: `Shell(${word})`, onceRule: exact ?? `Shell(${word})` };
|
|
7117
|
+
}
|
|
7118
|
+
function commandWordAt(segment) {
|
|
7119
|
+
const words = segment.trim().split(/\s+/);
|
|
7120
|
+
let at = 0;
|
|
7121
|
+
while (at < words.length - 1 && /^[A-Za-z_]\w*=/.test(words[at])) at++;
|
|
7122
|
+
const word = words[at]?.replace(/^['"]|['"]$/g, "") ?? "";
|
|
7123
|
+
if (!word || /[()*?:]/.test(word)) return null;
|
|
7124
|
+
return { word, args: words.slice(at + 1).join(" ") };
|
|
7125
|
+
}
|
|
7126
|
+
function cursorShellMatches(spec, segment) {
|
|
7127
|
+
const colon = spec.indexOf(":");
|
|
7128
|
+
const base = (colon < 0 ? spec : spec.slice(0, colon)).trim();
|
|
7129
|
+
const args = colon < 0 ? null : spec.slice(colon + 1).trim();
|
|
7130
|
+
const words = segment.trim().split(/\s+/);
|
|
7131
|
+
let at = 0;
|
|
7132
|
+
while (at < words.length - 1 && /^[A-Za-z_]\w*=/.test(words[at])) at++;
|
|
7133
|
+
if (!words[at] || !globMatches(base, words[at])) return false;
|
|
7134
|
+
return args === null || globMatches(args, words.slice(at + 1).join(" "));
|
|
7135
|
+
}
|
|
7136
|
+
function globMatches(pattern, text) {
|
|
7137
|
+
const re = pattern.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
|
|
7138
|
+
return new RegExp(`^${re}$`, "s").test(text);
|
|
7139
|
+
}
|
|
6541
7140
|
function hostOf(url) {
|
|
6542
7141
|
if (!url) return null;
|
|
6543
7142
|
try {
|
|
@@ -6566,7 +7165,12 @@ function ruleAllows(rule, toolName, input) {
|
|
|
6566
7165
|
const ruleTool = parsed.tool === "Edit" && EDIT_TOOLS.has(toolName) ? toolName : parsed.tool;
|
|
6567
7166
|
if (ruleTool !== toolName) return false;
|
|
6568
7167
|
const i = input && typeof input === "object" ? input : {};
|
|
6569
|
-
if (parsed.spec === null) return toolName
|
|
7168
|
+
if (parsed.spec === null) return !SHELL_RULE_TOOLS.has(toolName);
|
|
7169
|
+
if (toolName === "Shell") {
|
|
7170
|
+
const command = typeof i.command === "string" ? i.command.trim() : "";
|
|
7171
|
+
const segments = shellSegments(command);
|
|
7172
|
+
return segments.length > 0 && segments.every((s) => cursorShellMatches(parsed.spec, s));
|
|
7173
|
+
}
|
|
6570
7174
|
if (toolName === "Bash") {
|
|
6571
7175
|
const command = typeof i.command === "string" ? i.command.trim() : "";
|
|
6572
7176
|
if (command && parsed.spec.trim() === command) return true;
|
|
@@ -6588,13 +7192,15 @@ function hasOpaqueShell(command) {
|
|
|
6588
7192
|
}
|
|
6589
7193
|
function grantsCover(granted, base, toolName, input) {
|
|
6590
7194
|
if (granted.length === 0) return false;
|
|
6591
|
-
if (
|
|
7195
|
+
if (!SHELL_RULE_TOOLS.has(toolName)) {
|
|
7196
|
+
return granted.some((rule) => ruleAllows(rule, toolName, input));
|
|
7197
|
+
}
|
|
6592
7198
|
const i = input && typeof input === "object" ? input : {};
|
|
6593
7199
|
const command = typeof i.command === "string" ? i.command.trim() : "";
|
|
6594
7200
|
if (!command) return false;
|
|
6595
7201
|
const exact = granted.some((rule) => {
|
|
6596
7202
|
const parsed = parseRule(rule);
|
|
6597
|
-
return parsed?.tool ===
|
|
7203
|
+
return parsed?.tool === toolName && parsed.spec !== null && parsed.spec.trim() === command;
|
|
6598
7204
|
});
|
|
6599
7205
|
if (exact) return true;
|
|
6600
7206
|
if (hasOpaqueShell(command)) return false;
|
|
@@ -6603,8 +7209,8 @@ function grantsCover(granted, base, toolName, input) {
|
|
|
6603
7209
|
let byGrant = false;
|
|
6604
7210
|
for (const segment of segments) {
|
|
6605
7211
|
const call = { command: segment };
|
|
6606
|
-
if (granted.some((rule) => ruleAllows(rule,
|
|
6607
|
-
else if (!base.some((rule) => ruleAllows(rule,
|
|
7212
|
+
if (granted.some((rule) => ruleAllows(rule, toolName, call))) byGrant = true;
|
|
7213
|
+
else if (!base.some((rule) => ruleAllows(rule, toolName, call))) return false;
|
|
6608
7214
|
}
|
|
6609
7215
|
return byGrant;
|
|
6610
7216
|
}
|
|
@@ -6667,7 +7273,7 @@ function filePatternMatches(spec, file) {
|
|
|
6667
7273
|
let pattern = spec.trim();
|
|
6668
7274
|
if (pattern.startsWith("~/")) {
|
|
6669
7275
|
if (!home) return false;
|
|
6670
|
-
pattern = rulePath(
|
|
7276
|
+
pattern = rulePath(join13(home, pattern.slice(2)).replace(/\\/g, "/"));
|
|
6671
7277
|
}
|
|
6672
7278
|
if (!pattern.startsWith("//")) return false;
|
|
6673
7279
|
const path = rulePath(file);
|
|
@@ -6688,7 +7294,7 @@ function shellPatternMatches(spec, command) {
|
|
|
6688
7294
|
return new RegExp(`^${re}${optionalTail ? "(?: .*)?" : ""}$`, "s").test(command);
|
|
6689
7295
|
}
|
|
6690
7296
|
function toolGrantsFile(configFile) {
|
|
6691
|
-
return
|
|
7297
|
+
return join13(dirname9(configFile), "tool-grants.json");
|
|
6692
7298
|
}
|
|
6693
7299
|
var ToolGrantStore = class {
|
|
6694
7300
|
constructor(file) {
|
|
@@ -6855,7 +7461,7 @@ function ghError(command, res) {
|
|
|
6855
7461
|
|
|
6856
7462
|
// src/session-store.ts
|
|
6857
7463
|
import { mkdir as mkdir8, readdir as readdir3, rm as rm6 } from "node:fs/promises";
|
|
6858
|
-
import { join as
|
|
7464
|
+
import { join as join14 } from "node:path";
|
|
6859
7465
|
var HANDLED_COMMAND_IDS_KEPT = 100;
|
|
6860
7466
|
var pendingWrites = /* @__PURE__ */ new Map();
|
|
6861
7467
|
var SessionStore = class {
|
|
@@ -6863,10 +7469,10 @@ var SessionStore = class {
|
|
|
6863
7469
|
this.stateDir = stateDir;
|
|
6864
7470
|
}
|
|
6865
7471
|
dir(sessionId) {
|
|
6866
|
-
return
|
|
7472
|
+
return join14(this.stateDir, "sessions", sessionId);
|
|
6867
7473
|
}
|
|
6868
7474
|
outboxFile(sessionId) {
|
|
6869
|
-
return
|
|
7475
|
+
return join14(this.dir(sessionId), "outbox.json");
|
|
6870
7476
|
}
|
|
6871
7477
|
/**
|
|
6872
7478
|
* Writes the record as it is now. A session's saves land in the order they were made:
|
|
@@ -6876,7 +7482,7 @@ var SessionStore = class {
|
|
|
6876
7482
|
*/
|
|
6877
7483
|
async save(record) {
|
|
6878
7484
|
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
6879
|
-
const file =
|
|
7485
|
+
const file = join14(this.dir(record.sessionId), "session.json");
|
|
6880
7486
|
const snapshot = JSON.parse(JSON.stringify(record));
|
|
6881
7487
|
const previous = pendingWrites.get(file) ?? Promise.resolve();
|
|
6882
7488
|
const write = previous.then(() => writeJsonAtomic(file, snapshot));
|
|
@@ -6888,23 +7494,23 @@ var SessionStore = class {
|
|
|
6888
7494
|
await write;
|
|
6889
7495
|
}
|
|
6890
7496
|
async list() {
|
|
6891
|
-
const root =
|
|
7497
|
+
const root = join14(this.stateDir, "sessions");
|
|
6892
7498
|
await mkdir8(root, { recursive: true });
|
|
6893
7499
|
const out = [];
|
|
6894
7500
|
for (const entry of await readdir3(root, { withFileTypes: true })) {
|
|
6895
7501
|
if (!entry.isDirectory()) continue;
|
|
6896
|
-
const rec = await readJson(
|
|
7502
|
+
const rec = await readJson(join14(root, entry.name, "session.json"));
|
|
6897
7503
|
if (rec?.sessionId === entry.name) out.push(upgradeRecord(rec));
|
|
6898
7504
|
}
|
|
6899
7505
|
return out;
|
|
6900
7506
|
}
|
|
6901
7507
|
async remove(sessionId) {
|
|
6902
|
-
await pendingWrites.get(
|
|
7508
|
+
await pendingWrites.get(join14(this.dir(sessionId), "session.json"));
|
|
6903
7509
|
await rm6(this.dir(sessionId), { recursive: true, force: true });
|
|
6904
7510
|
}
|
|
6905
7511
|
/** Scratch working directory for a session without a repository. */
|
|
6906
7512
|
scratchDir(sessionId) {
|
|
6907
|
-
return
|
|
7513
|
+
return join14(this.stateDir, "scratch", sessionId);
|
|
6908
7514
|
}
|
|
6909
7515
|
};
|
|
6910
7516
|
function upgradeRecord(stored) {
|
|
@@ -7035,7 +7641,12 @@ var AgentSession = class {
|
|
|
7035
7641
|
*/
|
|
7036
7642
|
suggestSafeRules(toolName, input) {
|
|
7037
7643
|
const redactor = this.deps.environment?.redactor;
|
|
7038
|
-
const allowed =
|
|
7644
|
+
const allowed = [
|
|
7645
|
+
...this.deps.allowedTools,
|
|
7646
|
+
...this.record.grantRules ?? [],
|
|
7647
|
+
...this.savedRulesNow,
|
|
7648
|
+
...this.inheritedNow.allow
|
|
7649
|
+
];
|
|
7039
7650
|
if (!redactor?.active) return suggestRules(toolName, input, allowed);
|
|
7040
7651
|
if (JSON.stringify(redactor.redactDeep(input)) === JSON.stringify(input)) {
|
|
7041
7652
|
return suggestRules(toolName, input, allowed);
|
|
@@ -7145,7 +7756,8 @@ var AgentSession = class {
|
|
|
7145
7756
|
reportFailedTools(failed) {
|
|
7146
7757
|
for (const f of failed) {
|
|
7147
7758
|
if (this.seenFailedCalls.has(f.callId)) continue;
|
|
7148
|
-
|
|
7759
|
+
const grantable = f.denied ? !isDenyRuleRefusal(f.text) : isGrantableDenial(f.text);
|
|
7760
|
+
if (grantable) this.reportDenial(f.callId, f.name, f.input);
|
|
7149
7761
|
else this.seenFailedCalls.add(f.callId);
|
|
7150
7762
|
}
|
|
7151
7763
|
}
|
|
@@ -7507,6 +8119,7 @@ ${text}` : text;
|
|
|
7507
8119
|
await this.prepareEvidenceDir();
|
|
7508
8120
|
const { bin, features } = await this.deps.resolveAgent();
|
|
7509
8121
|
const savedRules = await (this.deps.savedRules?.(this.record.repository) ?? []);
|
|
8122
|
+
this.savedRulesNow = savedRules;
|
|
7510
8123
|
this.inheritedNow = await this.readInheritedRules();
|
|
7511
8124
|
const allowedTools = [
|
|
7512
8125
|
.../* @__PURE__ */ new Set([
|
|
@@ -7729,7 +8342,12 @@ ${text}` : text;
|
|
|
7729
8342
|
interrupted ? turn.isError ? null : turn.text : turn.text,
|
|
7730
8343
|
screenshots
|
|
7731
8344
|
);
|
|
7732
|
-
const
|
|
8345
|
+
const loop = this.record.metricLoop ?? null;
|
|
8346
|
+
const openPr = !loop || metricLoopShouldOpenPullRequest({ loop, turnText: text, interrupted });
|
|
8347
|
+
const prUrl = push.branch && openPr ? await this.openPullRequest(text, screenshots) : null;
|
|
8348
|
+
if (loop) {
|
|
8349
|
+
this.record.metricLoop = { ...loop, previous: nextMetricLoopPrevious(loop, text) };
|
|
8350
|
+
}
|
|
7733
8351
|
this.record.turnActive = false;
|
|
7734
8352
|
await this.deps.store.save(this.record);
|
|
7735
8353
|
this.emit({
|
|
@@ -7855,7 +8473,7 @@ ${text}` : text;
|
|
|
7855
8473
|
async publishScreenshots() {
|
|
7856
8474
|
const { workBranch, repoDir, cwd, repository } = this.record;
|
|
7857
8475
|
const repo = parseRepoUrl(
|
|
7858
|
-
repository ?? (repoDir ? `https://github.com/${basename2(
|
|
8476
|
+
repository ?? (repoDir ? `https://github.com/${basename2(dirname10(repoDir))}/${basename2(repoDir)}` : "")
|
|
7859
8477
|
);
|
|
7860
8478
|
if (!workBranch || !repoDir || !repo) return "";
|
|
7861
8479
|
const res = await publishEvidence({ repoDir, worktree: cwd, workBranch, repo });
|
|
@@ -7890,6 +8508,7 @@ ${text}` : text;
|
|
|
7890
8508
|
const { workBranch, baseSha, cwd, repoDir } = this.record;
|
|
7891
8509
|
if (!workBranch || !baseSha) return { branch: null, failed: false };
|
|
7892
8510
|
await this.prepareEvidenceDir();
|
|
8511
|
+
this.driver.beforeCommit?.(cwd);
|
|
7893
8512
|
const res = await commitAndPush({
|
|
7894
8513
|
worktree: cwd,
|
|
7895
8514
|
workBranch,
|
|
@@ -8230,9 +8849,9 @@ var SessionManager = class {
|
|
|
8230
8849
|
});
|
|
8231
8850
|
const driver = this.driverFor(cmd.agent);
|
|
8232
8851
|
await this.opts.resolveAgent(driver);
|
|
8233
|
-
if (!driver.control &&
|
|
8852
|
+
if (!driver.control && cmd.relayPermissionRequests) {
|
|
8234
8853
|
this.opts.logger.info(
|
|
8235
|
-
`session ${cmd.sessionId}: ${driver.displayName} does not
|
|
8854
|
+
`session ${cmd.sessionId}: ${driver.displayName} does not relay permission requests; its sandbox and rules decide instead`
|
|
8236
8855
|
);
|
|
8237
8856
|
}
|
|
8238
8857
|
const resume = cmd.resume ?? null;
|
|
@@ -8290,6 +8909,7 @@ var SessionManager = class {
|
|
|
8290
8909
|
...cmd.reportToolDenials === true ? { reportToolDenials: true } : {},
|
|
8291
8910
|
...grantRules(cmd).length ? { grantRules: grantRules(cmd) } : {},
|
|
8292
8911
|
...environment?.names.length ? { environmentNames: environment.names } : {},
|
|
8912
|
+
...cmd.metricLoop ? { metricLoop: cmd.metricLoop } : {},
|
|
8293
8913
|
createdAt: now,
|
|
8294
8914
|
updatedAt: now
|
|
8295
8915
|
};
|
|
@@ -8371,10 +8991,10 @@ var SessionManager = class {
|
|
|
8371
8991
|
await mkdir9(record.cwd, { recursive: true });
|
|
8372
8992
|
if (cmd.reviewImages === true && this.opts.reviewImageUploader) {
|
|
8373
8993
|
record.reviewImages = true;
|
|
8374
|
-
await mkdir9(
|
|
8994
|
+
await mkdir9(join15(record.cwd, EVIDENCE_DIR), { recursive: true });
|
|
8375
8995
|
}
|
|
8376
8996
|
const reference = cmd.referenceRepository;
|
|
8377
|
-
const referenceDir =
|
|
8997
|
+
const referenceDir = join15(record.cwd, RUNNER_REFERENCE_REPOSITORY_DIR);
|
|
8378
8998
|
const fromEntry = keptEntry?.reference;
|
|
8379
8999
|
const entryUrl = () => fromEntry ? fromEntry.url ?? legacyUrl(fromEntry, this.opts.config.reposDir) : null;
|
|
8380
9000
|
const fromSession = keepWorkspace ? earlier.find((o) => o.record.cwd === record.cwd)?.record.referenceRepository : void 0;
|
|
@@ -8386,9 +9006,9 @@ var SessionManager = class {
|
|
|
8386
9006
|
dir: fromEntry.dir,
|
|
8387
9007
|
repoDir: fromEntry.repoDir
|
|
8388
9008
|
} : void 0);
|
|
8389
|
-
const keptReference = candidate &&
|
|
9009
|
+
const keptReference = candidate && existsSync2(candidate.dir) ? candidate : void 0;
|
|
8390
9010
|
const referenceHold = !reference?.url ? null : this.opts.jobs ? this.opts.jobs.holdForRemoval(referenceDir) : () => void 0;
|
|
8391
|
-
if (reference?.url && keepWorkspace && (keptReference ||
|
|
9011
|
+
if (reference?.url && keepWorkspace && (keptReference || existsSync2(referenceDir))) {
|
|
8392
9012
|
if (keptReference) record.referenceRepository = keptReference;
|
|
8393
9013
|
referenceHold?.();
|
|
8394
9014
|
this.opts.logger.info(
|
|
@@ -8404,7 +9024,7 @@ var SessionManager = class {
|
|
|
8404
9024
|
url: reference.url,
|
|
8405
9025
|
baseRef: reference.baseRef ?? null,
|
|
8406
9026
|
reposDir: this.opts.config.reposDir,
|
|
8407
|
-
dir:
|
|
9027
|
+
dir: join15(record.cwd, RUNNER_REFERENCE_REPOSITORY_DIR),
|
|
8408
9028
|
protocol: this.opts.config.gitProtocol
|
|
8409
9029
|
}).finally(() => referenceHold?.());
|
|
8410
9030
|
record.referenceRepository = {
|
|
@@ -8422,7 +9042,7 @@ var SessionManager = class {
|
|
|
8422
9042
|
}
|
|
8423
9043
|
const deliverable = resume?.deliverable;
|
|
8424
9044
|
if (typeof deliverable === "string" && deliverable.trim()) {
|
|
8425
|
-
await writeFile6(
|
|
9045
|
+
await writeFile6(join15(record.cwd, RUNNER_DELIVERABLE_FILE), deliverable, "utf8");
|
|
8426
9046
|
}
|
|
8427
9047
|
}
|
|
8428
9048
|
if (resume) {
|
|
@@ -8708,7 +9328,7 @@ var SessionManager = class {
|
|
|
8708
9328
|
}
|
|
8709
9329
|
}
|
|
8710
9330
|
keptFile() {
|
|
8711
|
-
return
|
|
9331
|
+
return join15(this.opts.config.stateDir, "kept-for-jobs.json");
|
|
8712
9332
|
}
|
|
8713
9333
|
/** The entry kept for `cwd` in `kept-for-jobs.json`, if any. */
|
|
8714
9334
|
async keptEntry(cwd) {
|
|
@@ -8886,6 +9506,7 @@ var SessionManager = class {
|
|
|
8886
9506
|
agentConfig: {
|
|
8887
9507
|
codexSandbox: this.opts.config.codexSandbox ?? "workspace-write",
|
|
8888
9508
|
codexNetworkAccess: this.opts.config.codexNetworkAccess === true,
|
|
9509
|
+
cursorSandbox: this.opts.config.cursorSandbox !== false,
|
|
8889
9510
|
cursorForce: this.opts.config.cursorForce === true
|
|
8890
9511
|
},
|
|
8891
9512
|
interruptGraceMs: this.opts.interruptGraceMs,
|
|
@@ -8919,8 +9540,8 @@ function alwaysAllowTools(cmd) {
|
|
|
8919
9540
|
}
|
|
8920
9541
|
function legacyUrl(entry, reposDir) {
|
|
8921
9542
|
const repoDir = resolve3(entry.repoDir);
|
|
8922
|
-
if (!samePath(
|
|
8923
|
-
const url = `https://github.com/${basename3(
|
|
9543
|
+
if (!samePath(dirname11(dirname11(repoDir)), reposDir)) return null;
|
|
9544
|
+
const url = `https://github.com/${basename3(dirname11(repoDir))}/${basename3(repoDir)}`;
|
|
8924
9545
|
return parseRepoUrl(url) ? url : null;
|
|
8925
9546
|
}
|
|
8926
9547
|
function gone(path) {
|
|
@@ -9200,6 +9821,8 @@ var RunnerDaemon = class {
|
|
|
9200
9821
|
relaysPermissionRequests: true,
|
|
9201
9822
|
// And reports denied tool calls, takes grants on them, and keeps saved rules.
|
|
9202
9823
|
grantsToolPermissions: true,
|
|
9824
|
+
// For Cursor sessions too: its refused shell commands, as `Shell(...)` rules.
|
|
9825
|
+
grantsCursorToolPermissions: true,
|
|
9203
9826
|
// And attaches a design proposal's rendered screens to its task (`reviewImages`).
|
|
9204
9827
|
uploadsReviewImages: true,
|
|
9205
9828
|
// And keeps a continued non-code run's deliverable whole (`resume.deliverable`).
|
|
@@ -9332,7 +9955,7 @@ var RunnerDaemon = class {
|
|
|
9332
9955
|
if (this.droppedSessionIds.has(id)) return;
|
|
9333
9956
|
this.droppedSessionIds.add(id);
|
|
9334
9957
|
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 ${
|
|
9958
|
+
`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
9959
|
);
|
|
9337
9960
|
});
|
|
9338
9961
|
}
|