@discovery-tree/runner 0.1.19 → 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 +35 -14
- package/dist/cli.js +718 -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({
|
|
@@ -3374,6 +3706,8 @@ function cursorArgs(launch) {
|
|
|
3374
3706
|
args.push(`--model=${launch.model}`);
|
|
3375
3707
|
}
|
|
3376
3708
|
if (launch.resume) args.push(`--resume=${launch.resume}`);
|
|
3709
|
+
args.push("--trust");
|
|
3710
|
+
args.push("--sandbox", launch.sandbox ? "enabled" : "disabled");
|
|
3377
3711
|
if (launch.force) args.push("--force");
|
|
3378
3712
|
args.push(launch.prompt.startsWith("-") ? `
|
|
3379
3713
|
${launch.prompt}` : launch.prompt);
|
|
@@ -3480,6 +3814,16 @@ var CursorStreamMapper = class {
|
|
|
3480
3814
|
tool.output = capped.text;
|
|
3481
3815
|
if (capped.truncated) tool.truncated = true;
|
|
3482
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
|
+
}
|
|
3483
3827
|
}
|
|
3484
3828
|
out.events.push({ type: "tool_call", providerEventId: key, tool });
|
|
3485
3829
|
}
|
|
@@ -3513,6 +3857,12 @@ function toolNameAndInput(kind, call) {
|
|
|
3513
3857
|
input: call.args ?? {}
|
|
3514
3858
|
};
|
|
3515
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
|
+
}
|
|
3516
3866
|
function toolOutcome(kind, result) {
|
|
3517
3867
|
if (!result || typeof result !== "object") return { failed: false, output: null };
|
|
3518
3868
|
const r = result;
|
|
@@ -3537,6 +3887,170 @@ function describe(value) {
|
|
|
3537
3887
|
return value == null ? "" : JSON.stringify(value);
|
|
3538
3888
|
}
|
|
3539
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
|
+
|
|
3540
4054
|
// src/drivers/cursor.ts
|
|
3541
4055
|
var cursorDriver = {
|
|
3542
4056
|
kind: "cursor",
|
|
@@ -3554,18 +4068,23 @@ var cursorDriver = {
|
|
|
3554
4068
|
doctor: doctor3,
|
|
3555
4069
|
validateModel: (model) => assertValidCursorModel(model),
|
|
3556
4070
|
launch(input) {
|
|
4071
|
+
applyCursorPermissions(input.cwd, cursorRules(input.allowedTools));
|
|
3557
4072
|
const prompt = input.resume ? input.prompt ?? "" : cursorFirstPrompt(input.systemPrompt, input.prompt ?? "");
|
|
3558
4073
|
return launcherCommand(
|
|
3559
4074
|
input.bin,
|
|
3560
4075
|
cursorArgs({
|
|
3561
4076
|
model: input.model,
|
|
3562
4077
|
resume: input.resume,
|
|
4078
|
+
// On unless the config turns the worktree sandbox off.
|
|
4079
|
+
sandbox: input.agentConfig?.cursorSandbox !== false,
|
|
3563
4080
|
force: input.agentConfig?.cursorForce === true,
|
|
3564
4081
|
prompt
|
|
3565
4082
|
})
|
|
3566
4083
|
);
|
|
3567
4084
|
},
|
|
3568
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),
|
|
3569
4088
|
looksLikeSignInFailure: looksLikeCursorSignInFailure,
|
|
3570
4089
|
turnFailedToSignIn: (turn) => turn.isError && looksLikeCursorSignInFailure(turn.text),
|
|
3571
4090
|
signInFix: (env) => cursorSignInFix(env),
|
|
@@ -3649,7 +4168,7 @@ function agentDriverKinds() {
|
|
|
3649
4168
|
// src/config.ts
|
|
3650
4169
|
import { chmod, mkdir as mkdir3, readFile as readFile4, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
|
|
3651
4170
|
import { homedir as homedir2 } from "node:os";
|
|
3652
|
-
import { dirname as
|
|
4171
|
+
import { dirname as dirname5, join as join7 } from "node:path";
|
|
3653
4172
|
|
|
3654
4173
|
// src/invocation.ts
|
|
3655
4174
|
var RUNNER_PACKAGE = "@discovery-tree/runner";
|
|
@@ -3665,21 +4184,21 @@ function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
|
|
|
3665
4184
|
function runnerPaths(env = process.env) {
|
|
3666
4185
|
const home = homedir2();
|
|
3667
4186
|
if (process.platform === "win32") {
|
|
3668
|
-
const roaming = env.APPDATA ||
|
|
3669
|
-
const local = env.LOCALAPPDATA ||
|
|
4187
|
+
const roaming = env.APPDATA || join7(home, "AppData", "Roaming");
|
|
4188
|
+
const local = env.LOCALAPPDATA || join7(home, "AppData", "Local");
|
|
3670
4189
|
return {
|
|
3671
|
-
configFile:
|
|
3672
|
-
dataDir:
|
|
3673
|
-
stateDir:
|
|
4190
|
+
configFile: join7(roaming, "discovery-tree", "runner.json"),
|
|
4191
|
+
dataDir: join7(local, "discovery-tree", "runner"),
|
|
4192
|
+
stateDir: join7(local, "discovery-tree", "runner", "state")
|
|
3674
4193
|
};
|
|
3675
4194
|
}
|
|
3676
|
-
const config = env.XDG_CONFIG_HOME ||
|
|
3677
|
-
const data = env.XDG_DATA_HOME ||
|
|
3678
|
-
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");
|
|
3679
4198
|
return {
|
|
3680
|
-
configFile:
|
|
3681
|
-
dataDir:
|
|
3682
|
-
stateDir:
|
|
4199
|
+
configFile: join7(config, "discovery-tree", "runner.json"),
|
|
4200
|
+
dataDir: join7(data, "discovery-tree", "runner"),
|
|
4201
|
+
stateDir: join7(state, "discovery-tree", "runner")
|
|
3683
4202
|
};
|
|
3684
4203
|
}
|
|
3685
4204
|
var PERMISSION_MODES = [
|
|
@@ -3874,7 +4393,7 @@ var DEFAULT_DISALLOWED_TOOLS = [
|
|
|
3874
4393
|
];
|
|
3875
4394
|
function configDirRules(configFile, platform = process.platform) {
|
|
3876
4395
|
if (platform === "win32") return [];
|
|
3877
|
-
const dir =
|
|
4396
|
+
const dir = dirname5(configFile);
|
|
3878
4397
|
if (!dir.startsWith("/")) return [];
|
|
3879
4398
|
return [`Read(/${dir}/**)`, `Edit(/${dir}/**)`];
|
|
3880
4399
|
}
|
|
@@ -3898,7 +4417,7 @@ async function readConfigFile(file) {
|
|
|
3898
4417
|
}
|
|
3899
4418
|
}
|
|
3900
4419
|
async function writeConfigFile(file, config) {
|
|
3901
|
-
await mkdir3(
|
|
4420
|
+
await mkdir3(dirname5(file), { recursive: true, mode: 448 });
|
|
3902
4421
|
await writeFile2(file, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
|
|
3903
4422
|
await chmod(file, 384).catch(() => void 0);
|
|
3904
4423
|
}
|
|
@@ -3953,6 +4472,12 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
3953
4472
|
`codexNetworkAccess in ${paths.configFile} must be true or false (got ${JSON.stringify(codexNetwork)}).`
|
|
3954
4473
|
);
|
|
3955
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
|
+
}
|
|
3956
4481
|
const cursorForce = file?.cursorForce;
|
|
3957
4482
|
if (cursorForce !== void 0 && typeof cursorForce !== "boolean") {
|
|
3958
4483
|
throw new Error(
|
|
@@ -3977,8 +4502,8 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
3977
4502
|
name: file?.name ?? null,
|
|
3978
4503
|
maxSessions,
|
|
3979
4504
|
maxJobs,
|
|
3980
|
-
reposDir: overrides.reposDir ?? file?.reposDir ??
|
|
3981
|
-
worktreesDir: file?.worktreesDir ??
|
|
4505
|
+
reposDir: overrides.reposDir ?? file?.reposDir ?? join7(paths.dataDir, "repos"),
|
|
4506
|
+
worktreesDir: file?.worktreesDir ?? join7(paths.dataDir, "worktrees"),
|
|
3982
4507
|
permissionMode: mode,
|
|
3983
4508
|
allowedTools: [...new Set(allowed)],
|
|
3984
4509
|
disallowedTools: [...new Set(disallowed)],
|
|
@@ -3989,6 +4514,8 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
3989
4514
|
idleTimeoutMs: (file?.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES) * 6e4,
|
|
3990
4515
|
codexSandbox,
|
|
3991
4516
|
codexNetworkAccess: codexNetwork === true,
|
|
4517
|
+
// On unless turned off (a value that is not a boolean was refused above).
|
|
4518
|
+
cursorSandbox: cursorSandbox !== false,
|
|
3992
4519
|
cursorForce: cursorForce === true,
|
|
3993
4520
|
stateDir: paths.stateDir,
|
|
3994
4521
|
configFile: paths.configFile
|
|
@@ -3996,7 +4523,7 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
3996
4523
|
}
|
|
3997
4524
|
|
|
3998
4525
|
// src/daemon.ts
|
|
3999
|
-
import { join as
|
|
4526
|
+
import { join as join16 } from "node:path";
|
|
4000
4527
|
|
|
4001
4528
|
// src/backoff.ts
|
|
4002
4529
|
function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
@@ -4019,7 +4546,7 @@ function sleep(ms, signal) {
|
|
|
4019
4546
|
// src/completion.ts
|
|
4020
4547
|
import { mkdtemp as mkdtemp2, rm as rm4 } from "node:fs/promises";
|
|
4021
4548
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
4022
|
-
import { join as
|
|
4549
|
+
import { join as join8 } from "node:path";
|
|
4023
4550
|
var COMPLETION_DENIED_TOOLS = [
|
|
4024
4551
|
"Read",
|
|
4025
4552
|
"Glob",
|
|
@@ -4067,7 +4594,7 @@ async function answerCompletion(req, deps) {
|
|
|
4067
4594
|
try {
|
|
4068
4595
|
const { bin, features } = await deps.claude();
|
|
4069
4596
|
const args = completionArgs(req, features);
|
|
4070
|
-
cwd = await mkdtemp2(
|
|
4597
|
+
cwd = await mkdtemp2(join8(tmpdir2(), "dt-runner-completion-"));
|
|
4071
4598
|
const run = deps.run ?? ((b, a, o) => exec(b, a, { ...o, ownTree: true }));
|
|
4072
4599
|
const input = req.systemPrompt ? `<instructions>
|
|
4073
4600
|
${req.systemPrompt}
|
|
@@ -4122,7 +4649,7 @@ function reportableSessionIds(ids, onDropped = () => void 0) {
|
|
|
4122
4649
|
import { randomBytes as randomBytes3, scrypt, timingSafeEqual } from "node:crypto";
|
|
4123
4650
|
import { realpathSync } from "node:fs";
|
|
4124
4651
|
import { mkdir as mkdir6, readFile as readFile8, readdir as readdir2, stat as stat4 } from "node:fs/promises";
|
|
4125
|
-
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";
|
|
4126
4653
|
|
|
4127
4654
|
// src/environment.ts
|
|
4128
4655
|
function sessionEnvironment(raw) {
|
|
@@ -4411,9 +4938,9 @@ function fitEvent(body) {
|
|
|
4411
4938
|
|
|
4412
4939
|
// src/fsutil.ts
|
|
4413
4940
|
import { mkdir as mkdir4, readFile as readFile5, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
|
|
4414
|
-
import { dirname as
|
|
4941
|
+
import { dirname as dirname6 } from "node:path";
|
|
4415
4942
|
async function writeJsonAtomic(file, value) {
|
|
4416
|
-
await mkdir4(
|
|
4943
|
+
await mkdir4(dirname6(file), { recursive: true });
|
|
4417
4944
|
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
|
|
4418
4945
|
await writeFile3(tmp, JSON.stringify(value), { mode: 384 });
|
|
4419
4946
|
await rename2(tmp, file);
|
|
@@ -4856,15 +5383,15 @@ var JobOutbox = class _JobOutbox {
|
|
|
4856
5383
|
|
|
4857
5384
|
// src/jobs/job-process.ts
|
|
4858
5385
|
import { execFile, spawn as spawn4 } from "node:child_process";
|
|
4859
|
-
import { closeSync, openSync, readFileSync, readdirSync } from "node:fs";
|
|
5386
|
+
import { closeSync, openSync, readFileSync as readFileSync2, readdirSync } from "node:fs";
|
|
4860
5387
|
import { readFile as readFile7, writeFile as writeFile4 } from "node:fs/promises";
|
|
4861
|
-
import { dirname as
|
|
5388
|
+
import { dirname as dirname7, join as join10 } from "node:path";
|
|
4862
5389
|
|
|
4863
5390
|
// src/lock.ts
|
|
4864
5391
|
import { mkdir as mkdir5, open as open2, readFile as readFile6, rm as rm5 } from "node:fs/promises";
|
|
4865
|
-
import { join as
|
|
5392
|
+
import { join as join9 } from "node:path";
|
|
4866
5393
|
function lockFile(stateDir) {
|
|
4867
|
-
return
|
|
5394
|
+
return join9(stateDir, "daemon.pid");
|
|
4868
5395
|
}
|
|
4869
5396
|
function pidAlive(pid) {
|
|
4870
5397
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
@@ -5020,9 +5547,9 @@ async function spawnJob(input) {
|
|
|
5020
5547
|
return { pid: child.pid, startedAt: Date.now() - 500, child, exited };
|
|
5021
5548
|
}
|
|
5022
5549
|
async function spawnWindowsJob(input) {
|
|
5023
|
-
const dir =
|
|
5024
|
-
const scriptFile =
|
|
5025
|
-
const commandFile =
|
|
5550
|
+
const dir = dirname7(input.exitFile);
|
|
5551
|
+
const scriptFile = join10(dir, "job.ps1");
|
|
5552
|
+
const commandFile = join10(dir, "command.ps1");
|
|
5026
5553
|
const bom = "\uFEFF";
|
|
5027
5554
|
await writeFile4(commandFile, bom + powershellCommandScript(input.command), { mode: 384 });
|
|
5028
5555
|
for (const f of [input.stdoutFile, input.stderrFile]) await writeFile4(f, "", { flag: "a" });
|
|
@@ -5137,7 +5664,7 @@ function parseElapsed(text) {
|
|
|
5137
5664
|
}
|
|
5138
5665
|
function procStat(pid) {
|
|
5139
5666
|
try {
|
|
5140
|
-
const stat5 =
|
|
5667
|
+
const stat5 = readFileSync2(`/proc/${pid}/stat`, "utf8");
|
|
5141
5668
|
return stat5.slice(stat5.lastIndexOf(")") + 2).split(" ");
|
|
5142
5669
|
} catch {
|
|
5143
5670
|
return null;
|
|
@@ -5243,7 +5770,7 @@ function secretWait() {
|
|
|
5243
5770
|
var JobManager = class {
|
|
5244
5771
|
constructor(opts) {
|
|
5245
5772
|
this.opts = opts;
|
|
5246
|
-
this.root =
|
|
5773
|
+
this.root = join11(opts.stateDir, "jobs");
|
|
5247
5774
|
}
|
|
5248
5775
|
jobs = /* @__PURE__ */ new Map();
|
|
5249
5776
|
/** Folders being removed now, with how many removals hold each (see `holdForRemoval`). */
|
|
@@ -5263,7 +5790,7 @@ var JobManager = class {
|
|
|
5263
5790
|
root;
|
|
5264
5791
|
/** The folder a job's record, log and outbox live in. */
|
|
5265
5792
|
jobDir(jobId) {
|
|
5266
|
-
return
|
|
5793
|
+
return join11(this.root, jobId);
|
|
5267
5794
|
}
|
|
5268
5795
|
/**
|
|
5269
5796
|
* Jobs the runner reports in `activeJobIds`: a live process, or an end not yet reported.
|
|
@@ -5359,7 +5886,7 @@ var JobManager = class {
|
|
|
5359
5886
|
let table = null;
|
|
5360
5887
|
for (const entry of entries) {
|
|
5361
5888
|
if (!isRunnerSessionId(entry)) continue;
|
|
5362
|
-
const record = await readJson(
|
|
5889
|
+
const record = await readJson(join11(this.jobDir(entry), "job.json")).catch(
|
|
5363
5890
|
() => null
|
|
5364
5891
|
);
|
|
5365
5892
|
if (!record || record.jobId !== entry || record.settled) continue;
|
|
@@ -5525,7 +6052,7 @@ var JobManager = class {
|
|
|
5525
6052
|
/* -------------------------------------------------------------------------------- */
|
|
5526
6053
|
async start(id, cmd) {
|
|
5527
6054
|
if (this.jobs.has(id)) return { ok: true };
|
|
5528
|
-
const earlier = await readJson(
|
|
6055
|
+
const earlier = await readJson(join11(this.jobDir(id), "job.json")).catch(() => null);
|
|
5529
6056
|
if (earlier) {
|
|
5530
6057
|
return earlier.pid === null || earlier.ended?.status === "failed" ? { ok: false, error: "The job could not be started on this runner." } : { ok: true };
|
|
5531
6058
|
}
|
|
@@ -5537,7 +6064,7 @@ var JobManager = class {
|
|
|
5537
6064
|
return { ok: false, error: "The job has no command to run." };
|
|
5538
6065
|
}
|
|
5539
6066
|
const cwd = typeof cmd.cwd === "string" ? cmd.cwd : "";
|
|
5540
|
-
const cwdProblem = treeJobCwdProblem(cwd) ?? (
|
|
6067
|
+
const cwdProblem = treeJobCwdProblem(cwd) ?? (isAbsolute5(cwd) ? null : "must be an absolute path");
|
|
5541
6068
|
if (cwdProblem) return { ok: false, error: `The job's directory ${cwdProblem}.` };
|
|
5542
6069
|
const isDir2 = await stat4(cwd).then(
|
|
5543
6070
|
(s) => s.isDirectory(),
|
|
@@ -5617,9 +6144,9 @@ var JobManager = class {
|
|
|
5617
6144
|
command,
|
|
5618
6145
|
cwd,
|
|
5619
6146
|
env,
|
|
5620
|
-
stdoutFile:
|
|
5621
|
-
stderrFile:
|
|
5622
|
-
exitFile:
|
|
6147
|
+
stdoutFile: join11(dir, "stdout.log"),
|
|
6148
|
+
stderrFile: join11(dir, "stderr.log"),
|
|
6149
|
+
exitFile: join11(dir, "exit-code")
|
|
5623
6150
|
});
|
|
5624
6151
|
} catch (err) {
|
|
5625
6152
|
const error = safeError(err, redactor);
|
|
@@ -5787,7 +6314,7 @@ var JobManager = class {
|
|
|
5787
6314
|
};
|
|
5788
6315
|
job.outbox = await JobOutbox.open({
|
|
5789
6316
|
jobId: record.jobId,
|
|
5790
|
-
file:
|
|
6317
|
+
file: join11(dir, "outbox.json"),
|
|
5791
6318
|
poster: this.opts.poster,
|
|
5792
6319
|
logger: this.opts.logger,
|
|
5793
6320
|
batchDelayMs: this.opts.outboxBatchDelayMs,
|
|
@@ -5809,8 +6336,8 @@ var JobManager = class {
|
|
|
5809
6336
|
});
|
|
5810
6337
|
const cursor = job.outbox.cursor ?? startCursor();
|
|
5811
6338
|
job.readers = [
|
|
5812
|
-
new LogFileReader(
|
|
5813
|
-
new LogFileReader(
|
|
6339
|
+
new LogFileReader(join11(dir, "stdout.log"), "stdout", cursor.stdout),
|
|
6340
|
+
new LogFileReader(join11(dir, "stderr.log"), "stderr", cursor.stderr)
|
|
5814
6341
|
];
|
|
5815
6342
|
return job;
|
|
5816
6343
|
}
|
|
@@ -6044,11 +6571,11 @@ function canonical(p) {
|
|
|
6044
6571
|
for (; ; ) {
|
|
6045
6572
|
try {
|
|
6046
6573
|
const real = realpathSync.native(head);
|
|
6047
|
-
return tail ?
|
|
6574
|
+
return tail ? join11(real, tail) : real;
|
|
6048
6575
|
} catch {
|
|
6049
|
-
const up =
|
|
6576
|
+
const up = dirname8(head);
|
|
6050
6577
|
if (up === head) return full;
|
|
6051
|
-
tail = tail ?
|
|
6578
|
+
tail = tail ? join11(basename(head), tail) : basename(head);
|
|
6052
6579
|
head = up;
|
|
6053
6580
|
}
|
|
6054
6581
|
}
|
|
@@ -6153,11 +6680,11 @@ function queueEndReport(outbox, ended) {
|
|
|
6153
6680
|
);
|
|
6154
6681
|
}
|
|
6155
6682
|
async function saveRecord(dir, record) {
|
|
6156
|
-
await writeJsonAtomic(
|
|
6683
|
+
await writeJsonAtomic(join11(dir, "job.json"), record);
|
|
6157
6684
|
}
|
|
6158
6685
|
async function readExitFile(dir) {
|
|
6159
6686
|
try {
|
|
6160
|
-
const code = Number.parseInt((await readFile8(
|
|
6687
|
+
const code = Number.parseInt((await readFile8(join11(dir, "exit-code"), "utf8")).trim(), 10);
|
|
6161
6688
|
return Number.isInteger(code) ? { code, signal: null } : null;
|
|
6162
6689
|
} catch {
|
|
6163
6690
|
return null;
|
|
@@ -6169,13 +6696,13 @@ function safeError(err, redactor) {
|
|
|
6169
6696
|
}
|
|
6170
6697
|
|
|
6171
6698
|
// src/session-manager.ts
|
|
6172
|
-
import { existsSync, lstatSync } from "node:fs";
|
|
6699
|
+
import { existsSync as existsSync2, lstatSync } from "node:fs";
|
|
6173
6700
|
import { mkdir as mkdir9, rm as rm7, writeFile as writeFile6 } from "node:fs/promises";
|
|
6174
|
-
import { basename as basename3, dirname as
|
|
6701
|
+
import { basename as basename3, dirname as dirname11, join as join15, resolve as resolve3 } from "node:path";
|
|
6175
6702
|
|
|
6176
6703
|
// src/prompt-images.ts
|
|
6177
6704
|
import { mkdir as mkdir7, writeFile as writeFile5 } from "node:fs/promises";
|
|
6178
|
-
import { join as
|
|
6705
|
+
import { join as join12 } from "node:path";
|
|
6179
6706
|
var EXTENSIONS = {
|
|
6180
6707
|
"image/png": ".png",
|
|
6181
6708
|
"image/jpeg": ".jpg",
|
|
@@ -6192,7 +6719,7 @@ function promptImageFileName(index, filename, mimeType) {
|
|
|
6192
6719
|
async function savePromptImages(input) {
|
|
6193
6720
|
const out = { saved: [], failed: [] };
|
|
6194
6721
|
if (input.images.length === 0) return out;
|
|
6195
|
-
const dir =
|
|
6722
|
+
const dir = join12(input.cwd, RUNNER_TASK_IMAGES_DIR);
|
|
6196
6723
|
await mkdir7(dir, { recursive: true });
|
|
6197
6724
|
if (input.inRepository) {
|
|
6198
6725
|
await excludeFromGit(
|
|
@@ -6204,7 +6731,7 @@ async function savePromptImages(input) {
|
|
|
6204
6731
|
for (const [index, image] of input.images.entries()) {
|
|
6205
6732
|
try {
|
|
6206
6733
|
const res = await input.fetcher.getPromptImage(input.sessionId, image.attachmentId);
|
|
6207
|
-
const path =
|
|
6734
|
+
const path = join12(
|
|
6208
6735
|
dir,
|
|
6209
6736
|
promptImageFileName(index, image.filename, res.mimeType || image.mimeType)
|
|
6210
6737
|
);
|
|
@@ -6464,11 +6991,11 @@ function takeBatch(pending) {
|
|
|
6464
6991
|
// src/session.ts
|
|
6465
6992
|
import { spawn as spawn5 } from "node:child_process";
|
|
6466
6993
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
6467
|
-
import { basename as basename2, dirname as
|
|
6994
|
+
import { basename as basename2, dirname as dirname10 } from "node:path";
|
|
6468
6995
|
import { createInterface as createInterface2 } from "node:readline";
|
|
6469
6996
|
|
|
6470
6997
|
// src/tool-grants.ts
|
|
6471
|
-
import { dirname as
|
|
6998
|
+
import { dirname as dirname9, join as join13, posix } from "node:path";
|
|
6472
6999
|
var isGrantableDenial = isGrantableToolDenial;
|
|
6473
7000
|
var FILE_TOOLS2 = /* @__PURE__ */ new Set(["Read", "Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
6474
7001
|
var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
@@ -6479,6 +7006,9 @@ function suggestRules(toolName, input, allowedTools = []) {
|
|
|
6479
7006
|
if (toolName === "Bash") {
|
|
6480
7007
|
const command = str(i.command);
|
|
6481
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);
|
|
6482
7012
|
} else if (toolName === "WebFetch") {
|
|
6483
7013
|
const host = hostOf(str(i.url));
|
|
6484
7014
|
if (host) out = same(`WebFetch(domain:${host})`);
|
|
@@ -6537,6 +7067,76 @@ function bashRules(command, allowedTools) {
|
|
|
6537
7067
|
const once = segment.length <= 400 ? `Bash(${segment})` : prefix;
|
|
6538
7068
|
return { suggestedRule: prefix, onceRule: once };
|
|
6539
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
|
+
}
|
|
6540
7140
|
function hostOf(url) {
|
|
6541
7141
|
if (!url) return null;
|
|
6542
7142
|
try {
|
|
@@ -6565,7 +7165,12 @@ function ruleAllows(rule, toolName, input) {
|
|
|
6565
7165
|
const ruleTool = parsed.tool === "Edit" && EDIT_TOOLS.has(toolName) ? toolName : parsed.tool;
|
|
6566
7166
|
if (ruleTool !== toolName) return false;
|
|
6567
7167
|
const i = input && typeof input === "object" ? input : {};
|
|
6568
|
-
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
|
+
}
|
|
6569
7174
|
if (toolName === "Bash") {
|
|
6570
7175
|
const command = typeof i.command === "string" ? i.command.trim() : "";
|
|
6571
7176
|
if (command && parsed.spec.trim() === command) return true;
|
|
@@ -6587,13 +7192,15 @@ function hasOpaqueShell(command) {
|
|
|
6587
7192
|
}
|
|
6588
7193
|
function grantsCover(granted, base, toolName, input) {
|
|
6589
7194
|
if (granted.length === 0) return false;
|
|
6590
|
-
if (
|
|
7195
|
+
if (!SHELL_RULE_TOOLS.has(toolName)) {
|
|
7196
|
+
return granted.some((rule) => ruleAllows(rule, toolName, input));
|
|
7197
|
+
}
|
|
6591
7198
|
const i = input && typeof input === "object" ? input : {};
|
|
6592
7199
|
const command = typeof i.command === "string" ? i.command.trim() : "";
|
|
6593
7200
|
if (!command) return false;
|
|
6594
7201
|
const exact = granted.some((rule) => {
|
|
6595
7202
|
const parsed = parseRule(rule);
|
|
6596
|
-
return parsed?.tool ===
|
|
7203
|
+
return parsed?.tool === toolName && parsed.spec !== null && parsed.spec.trim() === command;
|
|
6597
7204
|
});
|
|
6598
7205
|
if (exact) return true;
|
|
6599
7206
|
if (hasOpaqueShell(command)) return false;
|
|
@@ -6602,8 +7209,8 @@ function grantsCover(granted, base, toolName, input) {
|
|
|
6602
7209
|
let byGrant = false;
|
|
6603
7210
|
for (const segment of segments) {
|
|
6604
7211
|
const call = { command: segment };
|
|
6605
|
-
if (granted.some((rule) => ruleAllows(rule,
|
|
6606
|
-
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;
|
|
6607
7214
|
}
|
|
6608
7215
|
return byGrant;
|
|
6609
7216
|
}
|
|
@@ -6666,7 +7273,7 @@ function filePatternMatches(spec, file) {
|
|
|
6666
7273
|
let pattern = spec.trim();
|
|
6667
7274
|
if (pattern.startsWith("~/")) {
|
|
6668
7275
|
if (!home) return false;
|
|
6669
|
-
pattern = rulePath(
|
|
7276
|
+
pattern = rulePath(join13(home, pattern.slice(2)).replace(/\\/g, "/"));
|
|
6670
7277
|
}
|
|
6671
7278
|
if (!pattern.startsWith("//")) return false;
|
|
6672
7279
|
const path = rulePath(file);
|
|
@@ -6687,7 +7294,7 @@ function shellPatternMatches(spec, command) {
|
|
|
6687
7294
|
return new RegExp(`^${re}${optionalTail ? "(?: .*)?" : ""}$`, "s").test(command);
|
|
6688
7295
|
}
|
|
6689
7296
|
function toolGrantsFile(configFile) {
|
|
6690
|
-
return
|
|
7297
|
+
return join13(dirname9(configFile), "tool-grants.json");
|
|
6691
7298
|
}
|
|
6692
7299
|
var ToolGrantStore = class {
|
|
6693
7300
|
constructor(file) {
|
|
@@ -6854,7 +7461,7 @@ function ghError(command, res) {
|
|
|
6854
7461
|
|
|
6855
7462
|
// src/session-store.ts
|
|
6856
7463
|
import { mkdir as mkdir8, readdir as readdir3, rm as rm6 } from "node:fs/promises";
|
|
6857
|
-
import { join as
|
|
7464
|
+
import { join as join14 } from "node:path";
|
|
6858
7465
|
var HANDLED_COMMAND_IDS_KEPT = 100;
|
|
6859
7466
|
var pendingWrites = /* @__PURE__ */ new Map();
|
|
6860
7467
|
var SessionStore = class {
|
|
@@ -6862,10 +7469,10 @@ var SessionStore = class {
|
|
|
6862
7469
|
this.stateDir = stateDir;
|
|
6863
7470
|
}
|
|
6864
7471
|
dir(sessionId) {
|
|
6865
|
-
return
|
|
7472
|
+
return join14(this.stateDir, "sessions", sessionId);
|
|
6866
7473
|
}
|
|
6867
7474
|
outboxFile(sessionId) {
|
|
6868
|
-
return
|
|
7475
|
+
return join14(this.dir(sessionId), "outbox.json");
|
|
6869
7476
|
}
|
|
6870
7477
|
/**
|
|
6871
7478
|
* Writes the record as it is now. A session's saves land in the order they were made:
|
|
@@ -6875,7 +7482,7 @@ var SessionStore = class {
|
|
|
6875
7482
|
*/
|
|
6876
7483
|
async save(record) {
|
|
6877
7484
|
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
6878
|
-
const file =
|
|
7485
|
+
const file = join14(this.dir(record.sessionId), "session.json");
|
|
6879
7486
|
const snapshot = JSON.parse(JSON.stringify(record));
|
|
6880
7487
|
const previous = pendingWrites.get(file) ?? Promise.resolve();
|
|
6881
7488
|
const write = previous.then(() => writeJsonAtomic(file, snapshot));
|
|
@@ -6887,23 +7494,23 @@ var SessionStore = class {
|
|
|
6887
7494
|
await write;
|
|
6888
7495
|
}
|
|
6889
7496
|
async list() {
|
|
6890
|
-
const root =
|
|
7497
|
+
const root = join14(this.stateDir, "sessions");
|
|
6891
7498
|
await mkdir8(root, { recursive: true });
|
|
6892
7499
|
const out = [];
|
|
6893
7500
|
for (const entry of await readdir3(root, { withFileTypes: true })) {
|
|
6894
7501
|
if (!entry.isDirectory()) continue;
|
|
6895
|
-
const rec = await readJson(
|
|
7502
|
+
const rec = await readJson(join14(root, entry.name, "session.json"));
|
|
6896
7503
|
if (rec?.sessionId === entry.name) out.push(upgradeRecord(rec));
|
|
6897
7504
|
}
|
|
6898
7505
|
return out;
|
|
6899
7506
|
}
|
|
6900
7507
|
async remove(sessionId) {
|
|
6901
|
-
await pendingWrites.get(
|
|
7508
|
+
await pendingWrites.get(join14(this.dir(sessionId), "session.json"));
|
|
6902
7509
|
await rm6(this.dir(sessionId), { recursive: true, force: true });
|
|
6903
7510
|
}
|
|
6904
7511
|
/** Scratch working directory for a session without a repository. */
|
|
6905
7512
|
scratchDir(sessionId) {
|
|
6906
|
-
return
|
|
7513
|
+
return join14(this.stateDir, "scratch", sessionId);
|
|
6907
7514
|
}
|
|
6908
7515
|
};
|
|
6909
7516
|
function upgradeRecord(stored) {
|
|
@@ -7034,7 +7641,12 @@ var AgentSession = class {
|
|
|
7034
7641
|
*/
|
|
7035
7642
|
suggestSafeRules(toolName, input) {
|
|
7036
7643
|
const redactor = this.deps.environment?.redactor;
|
|
7037
|
-
const allowed =
|
|
7644
|
+
const allowed = [
|
|
7645
|
+
...this.deps.allowedTools,
|
|
7646
|
+
...this.record.grantRules ?? [],
|
|
7647
|
+
...this.savedRulesNow,
|
|
7648
|
+
...this.inheritedNow.allow
|
|
7649
|
+
];
|
|
7038
7650
|
if (!redactor?.active) return suggestRules(toolName, input, allowed);
|
|
7039
7651
|
if (JSON.stringify(redactor.redactDeep(input)) === JSON.stringify(input)) {
|
|
7040
7652
|
return suggestRules(toolName, input, allowed);
|
|
@@ -7144,7 +7756,8 @@ var AgentSession = class {
|
|
|
7144
7756
|
reportFailedTools(failed) {
|
|
7145
7757
|
for (const f of failed) {
|
|
7146
7758
|
if (this.seenFailedCalls.has(f.callId)) continue;
|
|
7147
|
-
|
|
7759
|
+
const grantable = f.denied ? !isDenyRuleRefusal(f.text) : isGrantableDenial(f.text);
|
|
7760
|
+
if (grantable) this.reportDenial(f.callId, f.name, f.input);
|
|
7148
7761
|
else this.seenFailedCalls.add(f.callId);
|
|
7149
7762
|
}
|
|
7150
7763
|
}
|
|
@@ -7506,6 +8119,7 @@ ${text}` : text;
|
|
|
7506
8119
|
await this.prepareEvidenceDir();
|
|
7507
8120
|
const { bin, features } = await this.deps.resolveAgent();
|
|
7508
8121
|
const savedRules = await (this.deps.savedRules?.(this.record.repository) ?? []);
|
|
8122
|
+
this.savedRulesNow = savedRules;
|
|
7509
8123
|
this.inheritedNow = await this.readInheritedRules();
|
|
7510
8124
|
const allowedTools = [
|
|
7511
8125
|
.../* @__PURE__ */ new Set([
|
|
@@ -7728,7 +8342,12 @@ ${text}` : text;
|
|
|
7728
8342
|
interrupted ? turn.isError ? null : turn.text : turn.text,
|
|
7729
8343
|
screenshots
|
|
7730
8344
|
);
|
|
7731
|
-
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
|
+
}
|
|
7732
8351
|
this.record.turnActive = false;
|
|
7733
8352
|
await this.deps.store.save(this.record);
|
|
7734
8353
|
this.emit({
|
|
@@ -7854,7 +8473,7 @@ ${text}` : text;
|
|
|
7854
8473
|
async publishScreenshots() {
|
|
7855
8474
|
const { workBranch, repoDir, cwd, repository } = this.record;
|
|
7856
8475
|
const repo = parseRepoUrl(
|
|
7857
|
-
repository ?? (repoDir ? `https://github.com/${basename2(
|
|
8476
|
+
repository ?? (repoDir ? `https://github.com/${basename2(dirname10(repoDir))}/${basename2(repoDir)}` : "")
|
|
7858
8477
|
);
|
|
7859
8478
|
if (!workBranch || !repoDir || !repo) return "";
|
|
7860
8479
|
const res = await publishEvidence({ repoDir, worktree: cwd, workBranch, repo });
|
|
@@ -7889,6 +8508,7 @@ ${text}` : text;
|
|
|
7889
8508
|
const { workBranch, baseSha, cwd, repoDir } = this.record;
|
|
7890
8509
|
if (!workBranch || !baseSha) return { branch: null, failed: false };
|
|
7891
8510
|
await this.prepareEvidenceDir();
|
|
8511
|
+
this.driver.beforeCommit?.(cwd);
|
|
7892
8512
|
const res = await commitAndPush({
|
|
7893
8513
|
worktree: cwd,
|
|
7894
8514
|
workBranch,
|
|
@@ -8229,9 +8849,9 @@ var SessionManager = class {
|
|
|
8229
8849
|
});
|
|
8230
8850
|
const driver = this.driverFor(cmd.agent);
|
|
8231
8851
|
await this.opts.resolveAgent(driver);
|
|
8232
|
-
if (!driver.control &&
|
|
8852
|
+
if (!driver.control && cmd.relayPermissionRequests) {
|
|
8233
8853
|
this.opts.logger.info(
|
|
8234
|
-
`session ${cmd.sessionId}: ${driver.displayName} does not
|
|
8854
|
+
`session ${cmd.sessionId}: ${driver.displayName} does not relay permission requests; its sandbox and rules decide instead`
|
|
8235
8855
|
);
|
|
8236
8856
|
}
|
|
8237
8857
|
const resume = cmd.resume ?? null;
|
|
@@ -8289,6 +8909,7 @@ var SessionManager = class {
|
|
|
8289
8909
|
...cmd.reportToolDenials === true ? { reportToolDenials: true } : {},
|
|
8290
8910
|
...grantRules(cmd).length ? { grantRules: grantRules(cmd) } : {},
|
|
8291
8911
|
...environment?.names.length ? { environmentNames: environment.names } : {},
|
|
8912
|
+
...cmd.metricLoop ? { metricLoop: cmd.metricLoop } : {},
|
|
8292
8913
|
createdAt: now,
|
|
8293
8914
|
updatedAt: now
|
|
8294
8915
|
};
|
|
@@ -8370,10 +8991,10 @@ var SessionManager = class {
|
|
|
8370
8991
|
await mkdir9(record.cwd, { recursive: true });
|
|
8371
8992
|
if (cmd.reviewImages === true && this.opts.reviewImageUploader) {
|
|
8372
8993
|
record.reviewImages = true;
|
|
8373
|
-
await mkdir9(
|
|
8994
|
+
await mkdir9(join15(record.cwd, EVIDENCE_DIR), { recursive: true });
|
|
8374
8995
|
}
|
|
8375
8996
|
const reference = cmd.referenceRepository;
|
|
8376
|
-
const referenceDir =
|
|
8997
|
+
const referenceDir = join15(record.cwd, RUNNER_REFERENCE_REPOSITORY_DIR);
|
|
8377
8998
|
const fromEntry = keptEntry?.reference;
|
|
8378
8999
|
const entryUrl = () => fromEntry ? fromEntry.url ?? legacyUrl(fromEntry, this.opts.config.reposDir) : null;
|
|
8379
9000
|
const fromSession = keepWorkspace ? earlier.find((o) => o.record.cwd === record.cwd)?.record.referenceRepository : void 0;
|
|
@@ -8385,9 +9006,9 @@ var SessionManager = class {
|
|
|
8385
9006
|
dir: fromEntry.dir,
|
|
8386
9007
|
repoDir: fromEntry.repoDir
|
|
8387
9008
|
} : void 0);
|
|
8388
|
-
const keptReference = candidate &&
|
|
9009
|
+
const keptReference = candidate && existsSync2(candidate.dir) ? candidate : void 0;
|
|
8389
9010
|
const referenceHold = !reference?.url ? null : this.opts.jobs ? this.opts.jobs.holdForRemoval(referenceDir) : () => void 0;
|
|
8390
|
-
if (reference?.url && keepWorkspace && (keptReference ||
|
|
9011
|
+
if (reference?.url && keepWorkspace && (keptReference || existsSync2(referenceDir))) {
|
|
8391
9012
|
if (keptReference) record.referenceRepository = keptReference;
|
|
8392
9013
|
referenceHold?.();
|
|
8393
9014
|
this.opts.logger.info(
|
|
@@ -8403,7 +9024,7 @@ var SessionManager = class {
|
|
|
8403
9024
|
url: reference.url,
|
|
8404
9025
|
baseRef: reference.baseRef ?? null,
|
|
8405
9026
|
reposDir: this.opts.config.reposDir,
|
|
8406
|
-
dir:
|
|
9027
|
+
dir: join15(record.cwd, RUNNER_REFERENCE_REPOSITORY_DIR),
|
|
8407
9028
|
protocol: this.opts.config.gitProtocol
|
|
8408
9029
|
}).finally(() => referenceHold?.());
|
|
8409
9030
|
record.referenceRepository = {
|
|
@@ -8421,7 +9042,7 @@ var SessionManager = class {
|
|
|
8421
9042
|
}
|
|
8422
9043
|
const deliverable = resume?.deliverable;
|
|
8423
9044
|
if (typeof deliverable === "string" && deliverable.trim()) {
|
|
8424
|
-
await writeFile6(
|
|
9045
|
+
await writeFile6(join15(record.cwd, RUNNER_DELIVERABLE_FILE), deliverable, "utf8");
|
|
8425
9046
|
}
|
|
8426
9047
|
}
|
|
8427
9048
|
if (resume) {
|
|
@@ -8707,7 +9328,7 @@ var SessionManager = class {
|
|
|
8707
9328
|
}
|
|
8708
9329
|
}
|
|
8709
9330
|
keptFile() {
|
|
8710
|
-
return
|
|
9331
|
+
return join15(this.opts.config.stateDir, "kept-for-jobs.json");
|
|
8711
9332
|
}
|
|
8712
9333
|
/** The entry kept for `cwd` in `kept-for-jobs.json`, if any. */
|
|
8713
9334
|
async keptEntry(cwd) {
|
|
@@ -8885,6 +9506,7 @@ var SessionManager = class {
|
|
|
8885
9506
|
agentConfig: {
|
|
8886
9507
|
codexSandbox: this.opts.config.codexSandbox ?? "workspace-write",
|
|
8887
9508
|
codexNetworkAccess: this.opts.config.codexNetworkAccess === true,
|
|
9509
|
+
cursorSandbox: this.opts.config.cursorSandbox !== false,
|
|
8888
9510
|
cursorForce: this.opts.config.cursorForce === true
|
|
8889
9511
|
},
|
|
8890
9512
|
interruptGraceMs: this.opts.interruptGraceMs,
|
|
@@ -8918,8 +9540,8 @@ function alwaysAllowTools(cmd) {
|
|
|
8918
9540
|
}
|
|
8919
9541
|
function legacyUrl(entry, reposDir) {
|
|
8920
9542
|
const repoDir = resolve3(entry.repoDir);
|
|
8921
|
-
if (!samePath(
|
|
8922
|
-
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)}`;
|
|
8923
9545
|
return parseRepoUrl(url) ? url : null;
|
|
8924
9546
|
}
|
|
8925
9547
|
function gone(path) {
|
|
@@ -9199,6 +9821,8 @@ var RunnerDaemon = class {
|
|
|
9199
9821
|
relaysPermissionRequests: true,
|
|
9200
9822
|
// And reports denied tool calls, takes grants on them, and keeps saved rules.
|
|
9201
9823
|
grantsToolPermissions: true,
|
|
9824
|
+
// For Cursor sessions too: its refused shell commands, as `Shell(...)` rules.
|
|
9825
|
+
grantsCursorToolPermissions: true,
|
|
9202
9826
|
// And attaches a design proposal's rendered screens to its task (`reviewImages`).
|
|
9203
9827
|
uploadsReviewImages: true,
|
|
9204
9828
|
// And keeps a continued non-code run's deliverable whole (`resume.deliverable`).
|
|
@@ -9331,7 +9955,7 @@ var RunnerDaemon = class {
|
|
|
9331
9955
|
if (this.droppedSessionIds.has(id)) return;
|
|
9332
9956
|
this.droppedSessionIds.add(id);
|
|
9333
9957
|
this.opts.logger.warn(
|
|
9334
|
-
`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)})`
|
|
9335
9959
|
);
|
|
9336
9960
|
});
|
|
9337
9961
|
}
|