@a-t-h-i/bot-lobby 0.6.61 → 0.6.63
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 +8 -8
- package/package.json +2 -1
- package/prompts/designer.md +25 -15
- package/prompts/master.md +284 -491
- package/prompts/panel.md +7 -0
- package/prompts/planner.md +15 -4
- package/prompts/qa.md +5 -1
- package/prompts/worker.md +0 -7
- package/scripts/builtin/affected_packages.mjs +106 -0
- package/scripts/builtin/check_changed.mjs +51 -0
- package/scripts/builtin/check_contract_breakage.mjs +118 -0
- package/scripts/builtin/circular_dependency_check.mjs +79 -0
- package/scripts/builtin/code_duplication_check.mjs +86 -0
- package/scripts/builtin/diff_summary.mjs +62 -0
- package/scripts/builtin/failure_digest.mjs +107 -0
- package/scripts/builtin/find_generated_files.mjs +79 -0
- package/scripts/builtin/find_symbol.mjs +81 -0
- package/scripts/builtin/find_test_fixtures.mjs +73 -0
- package/scripts/builtin/find_tests_for.mjs +12 -0
- package/scripts/builtin/lib/common.mjs +267 -0
- package/scripts/builtin/outline_file.mjs +77 -0
- package/scripts/builtin/project_commands.mjs +49 -0
- package/scripts/builtin/recent_changes.mjs +14 -0
- package/scripts/builtin/repo_map.mjs +65 -0
- package/scripts/builtin/run_changed_tests.mjs +48 -0
- package/src/delivery/transport.ts +1 -1
- package/src/desk/client-extension.ts +1 -31
- package/src/desk/ipc.ts +1 -11
- package/src/desk/session.ts +4 -101
- package/src/execution/agent-runner.ts +50 -8
- package/src/execution/assigned-session.ts +263 -0
- package/src/execution/assignment-discovery.ts +128 -0
- package/src/execution/assignment-policy.ts +46 -0
- package/src/execution/assignment.ts +175 -0
- package/src/execution/delegation.ts +9 -94
- package/src/execution/pi-runner.ts +99 -9
- package/src/harness/instructions.ts +1 -1
- package/src/index.ts +3 -0
- package/src/knowledge/design-record.ts +394 -0
- package/src/knowledge/file-notes.ts +36 -8
- package/src/lobby/ask.ts +6 -0
- package/src/lobby/exec.ts +28 -0
- package/src/lobby/host.ts +2 -11
- package/src/lobby/pi-commands.ts +83 -0
- package/src/lobby/planner.ts +50 -124
- package/src/lobby/prompts.ts +1 -7
- package/src/lobby/runtime.ts +2 -26
- package/src/lobby/service.ts +28 -27
- package/src/lobby/topics.ts +0 -2
- package/src/master/evidence-freshness.ts +96 -0
- package/src/master/master.ts +248 -74
- package/src/master/scout-cache.ts +1 -1
- package/src/master/scout-lock.ts +44 -0
- package/src/master/scout-prefetch.ts +78 -0
- package/src/pi/activity.ts +2 -0
- package/src/pi/assignment-guard.ts +157 -0
- package/src/pi/delegation.ts +2 -21
- package/src/pi/model-support.ts +0 -6
- package/src/pi/start-task.ts +18 -7
- package/src/pi/tools.ts +41 -8
- package/src/roles/scout.ts +3 -1
- package/src/roles/worker.ts +107 -5
- package/src/schemas/configuration.ts +11 -45
- package/src/schemas/findings.ts +3 -0
- package/src/schemas/task.ts +30 -12
- package/src/scripts/library.ts +31 -1
- package/src/scripts/pick.ts +31 -15
- package/src/state/archive.ts +10 -0
- package/src/state/checkpoint.ts +0 -1
- package/src/state/gitignore.ts +39 -0
- package/src/state/persistence.ts +56 -0
- package/src/state/recovery.ts +33 -1
- package/src/webui/api/index.ts +6 -35
- package/src/webui/api/retention.ts +44 -0
- package/src/webui/api/status.ts +5 -6
- package/src/webui/dev/fake-service.ts +8 -117
- package/src/webui/dev/fixtures.ts +2 -16
- package/src/webui/protocol.ts +3 -142
- package/src/workflow/draft-assignments.ts +118 -0
- package/src/workflow/workflow.ts +271 -214
- package/webui/dist/assets/{CodeSurface-BtzJOVyH.js → CodeSurface-CdyiJTYa.js} +1 -1
- package/webui/dist/assets/{TerminalView-Cz-KNWsq.js → TerminalView-D2nbR2J1.js} +1 -1
- package/webui/dist/assets/index-BTyu99rI.css +2 -0
- package/webui/dist/assets/index-BUGK22Z6.js +112 -0
- package/webui/dist/build.json +32 -68
- package/webui/dist/index.html +2 -2
- package/prompts/expert.md +0 -17
- package/prompts/goal-check.md +0 -44
- package/prompts/pr-review.md +0 -62
- package/prompts/splitter.md +0 -58
- package/src/execution/worker-trees.ts +0 -396
- package/src/lobby/issues.ts +0 -219
- package/src/lobby/pr-review.ts +0 -366
- package/src/lobby/pulls.ts +0 -250
- package/src/lobby/split.ts +0 -262
- package/src/master/goal-check.ts +0 -115
- package/src/webui/api/gh-error.ts +0 -17
- package/src/webui/api/git.ts +0 -98
- package/src/webui/api/issues.ts +0 -50
- package/webui/dist/assets/index-D5fvY8f8.js +0 -112
- package/webui/dist/assets/index-DFvk8ADr.css +0 -2
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// purpose: outline a source file: its imports count, top-level functions, classes, types and exports with line numbers, so only the needed range is read; each function shows its length and deepest nesting, and long or deep ones are flagged
|
|
3
|
+
// usage: node {script} <file> [more files…] [--complex] (--complex lists only the flagged functions)
|
|
4
|
+
import { readFileSync } from "node:fs";
|
|
5
|
+
import { extname } from "node:path";
|
|
6
|
+
import { declarations, fail, parseArgs } from "./lib/common.mjs";
|
|
7
|
+
|
|
8
|
+
const { flags, rest } = parseArgs();
|
|
9
|
+
// `--complex file.ts` reads the file as the flag's value.
|
|
10
|
+
if (typeof flags.complex === "string") rest.unshift(flags.complex);
|
|
11
|
+
const LONG = 60;
|
|
12
|
+
const DEEP = 4;
|
|
13
|
+
if (rest.length === 0) fail("usage: outline_file.mjs <file> [more files…]");
|
|
14
|
+
const JS = [
|
|
15
|
+
/^\s*export\s+(default\s+)?(async\s+)?function\*?\s+([\w$]+)/,
|
|
16
|
+
/^\s*(async\s+)?function\*?\s+([\w$]+)/,
|
|
17
|
+
/^\s*export\s+(default\s+)?(abstract\s+)?class\s+([\w$]+)/,
|
|
18
|
+
/^\s*(abstract\s+)?class\s+([\w$]+)/,
|
|
19
|
+
/^\s*export\s+(interface|type|enum)\s+([\w$]+)/,
|
|
20
|
+
/^\s*(interface|type|enum)\s+([\w$]+)/,
|
|
21
|
+
/^\s*export\s+const\s+([\w$]+)/,
|
|
22
|
+
/^\s*const\s+([\w$]+)\s*=\s*(async\s*)?(\(|function|[\w$]+\s*=>)/,
|
|
23
|
+
/^\s{2,4}(public\s+|private\s+|protected\s+|static\s+|async\s+|get\s+|set\s+)*([\w$]+)\s*\([^)]*\)\s*(:\s*[^{]+)?\{\s*$/,
|
|
24
|
+
/^\s*(describe|test|it)\(["'`]/,
|
|
25
|
+
];
|
|
26
|
+
const PY = [/^\s*(async\s+)?def\s+(\w+)/, /^\s*class\s+(\w+)/];
|
|
27
|
+
const GO = [/^func\s+(\([^)]*\)\s*)?(\w+)/, /^type\s+(\w+)/];
|
|
28
|
+
const RS = [/^\s*(pub(\([^)]*\))?\s+)?(async\s+)?fn\s+(\w+)/, /^\s*(pub\s+)?(struct|enum|trait|impl|mod)\b/];
|
|
29
|
+
const PATTERNS = { ".py": PY, ".go": GO, ".rs": RS };
|
|
30
|
+
for (const file of rest) {
|
|
31
|
+
let text;
|
|
32
|
+
try {
|
|
33
|
+
text = readFileSync(file, "utf8");
|
|
34
|
+
} catch {
|
|
35
|
+
console.log(`## ${file}: cannot read`);
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
const rows = text.split("\n");
|
|
39
|
+
const patterns = PATTERNS[extname(file)] ?? JS;
|
|
40
|
+
const imports = rows.filter((row) => /^\s*(import\s|from\s+\S+\s+import|use\s|require\()/.test(row)).length;
|
|
41
|
+
// Length and deepest nesting of each declaration, by brackets (or indentation in Python).
|
|
42
|
+
const spans = new Map(declarations(text, file).map((decl) => [decl.start, decl]));
|
|
43
|
+
const strip = (row) => row.replace(/(["'`])(?:\\.|(?!\1).)*\1/g, "").replace(/\/\/.*$/, "");
|
|
44
|
+
const measure = (decl) => {
|
|
45
|
+
let depth = 0;
|
|
46
|
+
let deepest = 0;
|
|
47
|
+
let end = decl.end;
|
|
48
|
+
let opened = false;
|
|
49
|
+
for (let i = decl.start - 1; i < decl.end; i++) {
|
|
50
|
+
const row = rows[i];
|
|
51
|
+
if (file.endsWith(".py")) {
|
|
52
|
+
if (row.trim()) deepest = Math.max(deepest, Math.floor((row.length - row.trimStart().length - decl.indent) / 4) - 1);
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
for (const ch of strip(row)) {
|
|
56
|
+
if (ch === "{") { opened = true; deepest = Math.max(deepest, ++depth - 1); }
|
|
57
|
+
else if (ch === "}") depth -= 1;
|
|
58
|
+
}
|
|
59
|
+
// The body ends where its brackets close; a one-line statement ends on its own line.
|
|
60
|
+
if ((opened && depth <= 0) || (!opened && /;\s*$/.test(row))) { end = i + 1; break; }
|
|
61
|
+
}
|
|
62
|
+
return { length: end - decl.start + 1, depth: Math.max(0, deepest) };
|
|
63
|
+
};
|
|
64
|
+
const flagged = [];
|
|
65
|
+
const out = [];
|
|
66
|
+
rows.forEach((row, index) => {
|
|
67
|
+
if (!patterns.some((pattern) => pattern.test(row))) return;
|
|
68
|
+
const decl = spans.get(index + 1);
|
|
69
|
+
const size = decl && decl.end > decl.start ? measure(decl) : undefined;
|
|
70
|
+
// A class or interface is long by nature; only functions are flagged.
|
|
71
|
+
const warn = size && !/\b(class|interface|type|enum|struct|trait|impl)\s/.test(row) && (size.length > LONG || size.depth > DEEP);
|
|
72
|
+
if (warn) flagged.push(decl.name);
|
|
73
|
+
if (!flags.complex || warn) out.push(`${String(index + 1).padStart(5)} ${row.trim().replace(/\s*\{\s*$/, "").slice(0, 120)}${size ? ` [${size.length} lines, depth ${size.depth}${warn ? " !" : ""}]` : ""}`);
|
|
74
|
+
});
|
|
75
|
+
console.log(`## ${file} (${rows.length} lines, ${imports} imports${flagged.length ? `, ${flagged.length} long or deeply nested: over ${LONG} lines or ${DEEP} levels, marked !` : ""})`);
|
|
76
|
+
for (const row of out) console.log(row);
|
|
77
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// purpose: list how this project builds, tests, lints, formats and runs: package.json scripts, Makefile and justfile targets, Python, Go and Rust commands; never guess a command
|
|
3
|
+
// usage: node {script}
|
|
4
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { detect, projectRoot, runScript } from "./lib/common.mjs";
|
|
7
|
+
|
|
8
|
+
const root = projectRoot();
|
|
9
|
+
const tool = detect(root);
|
|
10
|
+
const read = (file) => {
|
|
11
|
+
try {
|
|
12
|
+
return readFileSync(join(root, file), "utf8");
|
|
13
|
+
} catch {
|
|
14
|
+
return "";
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
let any = false;
|
|
18
|
+
const section = (title, rows) => {
|
|
19
|
+
if (rows.length === 0) return;
|
|
20
|
+
any = true;
|
|
21
|
+
console.log(`## ${title}`);
|
|
22
|
+
for (const row of rows) console.log(row);
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
if (tool.pkg?.scripts) {
|
|
26
|
+
const scripts = Object.entries(tool.pkg.scripts);
|
|
27
|
+
const order = (name) => ["test", "build", "lint", "typecheck", "check", "format", "dev", "start"].findIndex((key) => name === key || name.startsWith(`${key}:`));
|
|
28
|
+
scripts.sort((a, b) => (order(a[0]) < 0 ? 99 : order(a[0])) - (order(b[0]) < 0 ? 99 : order(b[0])));
|
|
29
|
+
section(`package.json scripts (${tool.pm})`, scripts.map(([name, body]) => `- ${runScript(tool.pm, name)} → ${String(body).slice(0, 140)}`));
|
|
30
|
+
}
|
|
31
|
+
const make = read("Makefile");
|
|
32
|
+
if (make) section("Makefile", [...make.matchAll(/^([A-Za-z0-9_.-]+):(?!=)/gm)].map((m) => m[1]).filter((t) => !t.startsWith(".")).slice(0, 30).map((t) => `- make ${t}`));
|
|
33
|
+
const just = read("justfile") || read("Justfile");
|
|
34
|
+
if (just) section("justfile", [...just.matchAll(/^([A-Za-z0-9_-]+)[^:\n]*:/gm)].map((m) => `- just ${m[1]}`).slice(0, 30));
|
|
35
|
+
if (tool.python) {
|
|
36
|
+
const py = read("pyproject.toml");
|
|
37
|
+
const rows = [];
|
|
38
|
+
if (/\[tool\.pytest|pytest/.test(py) || existsSync(join(root, "pytest.ini")) || existsSync(join(root, "tests"))) rows.push("- python3 -m pytest -q");
|
|
39
|
+
if (/\[tool\.ruff/.test(py)) rows.push("- ruff check . && ruff format --check .");
|
|
40
|
+
if (/\[tool\.mypy/.test(py)) rows.push("- python3 -m mypy .");
|
|
41
|
+
for (const m of py.matchAll(/^\[(?:project|tool\.poetry)\.scripts\]\n((?:[^\[\n].*\n?)*)/gm)) for (const row of m[1].split("\n").filter((r) => r.includes("="))) rows.push(`- ${row.split("=")[0].trim()} (console script)`);
|
|
42
|
+
if (existsSync(join(root, "manage.py"))) rows.push("- python3 manage.py runserver / test");
|
|
43
|
+
section("Python", rows);
|
|
44
|
+
}
|
|
45
|
+
if (tool.go) section("Go", ["- go build ./...", "- go test ./...", "- go vet ./..."]);
|
|
46
|
+
if (tool.rust) section("Rust", ["- cargo build", "- cargo test", "- cargo clippy"]);
|
|
47
|
+
const ci = [".github/workflows"].filter((dir) => existsSync(join(root, dir)));
|
|
48
|
+
if (ci.length > 0) section("CI", ["- .github/workflows/ holds what CI runs; match it locally"]);
|
|
49
|
+
if (!any) console.log("No build, test or lint commands found. Look in README.md before running anything.");
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// purpose: show the latest commits that touched a file or folder (date, author, message, size), to learn why code is the way it is before changing it
|
|
3
|
+
// usage: node {script} <path> [--n <count>]
|
|
4
|
+
import { fail, parseArgs, projectRoot, sh } from "./lib/common.mjs";
|
|
5
|
+
|
|
6
|
+
const { flags, rest } = parseArgs();
|
|
7
|
+
const path = rest[0];
|
|
8
|
+
if (!path) fail("usage: recent_changes.mjs <path> [--n <count>]");
|
|
9
|
+
const root = projectRoot();
|
|
10
|
+
const n = Number(flags.n ?? 10);
|
|
11
|
+
const log = sh("git", ["log", `-n${n}`, "--date=short", "--format=%h %ad %an: %s", "--shortstat", "--follow", "--", path], { cwd: process.cwd() });
|
|
12
|
+
const fallback = log.code === 0 ? log : sh("git", ["log", `-n${n}`, "--date=short", "--format=%h %ad %an: %s", "--shortstat", "--", path], { cwd: root });
|
|
13
|
+
const out = fallback.out.split("\n").filter((row) => row.trim()).map((row) => (row.startsWith(" ") ? ` ${row.trim()}` : row)).join("\n");
|
|
14
|
+
console.log(out || `No commits touch ${path}.`);
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// purpose: a short map of the project: folders with file counts, languages, entry points, test folders and config files, to orient before reading code
|
|
3
|
+
// usage: node {script} [folder] [--depth <n>]
|
|
4
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
5
|
+
import { extname, join } from "node:path";
|
|
6
|
+
import { detect, isTest, lines, parseArgs, projectRoot, sh } from "./lib/common.mjs";
|
|
7
|
+
|
|
8
|
+
const { flags, rest } = parseArgs();
|
|
9
|
+
const root = projectRoot();
|
|
10
|
+
const under = (rest[0] ?? "").replace(/^\.\/?/, "").replace(/\/$/, "");
|
|
11
|
+
const depth = Number(flags.depth ?? 2);
|
|
12
|
+
const files = lines(sh("git", ["ls-files", "--cached", "--others", "--exclude-standard", ...(under ? ["--", under] : [])], { cwd: root }).out);
|
|
13
|
+
if (files.length === 0) {
|
|
14
|
+
console.log("No tracked files here.");
|
|
15
|
+
process.exit(0);
|
|
16
|
+
}
|
|
17
|
+
const tool = detect(root);
|
|
18
|
+
|
|
19
|
+
// Folders to `depth`, with how many files sit under each.
|
|
20
|
+
const counts = new Map();
|
|
21
|
+
for (const file of files) {
|
|
22
|
+
const parts = (under ? file.slice(under.length + 1) : file).split("/").slice(0, -1);
|
|
23
|
+
for (let level = 1; level <= Math.min(depth, parts.length); level++) {
|
|
24
|
+
const dir = parts.slice(0, level).join("/");
|
|
25
|
+
counts.set(dir, (counts.get(dir) ?? 0) + 1);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
console.log(`## ${under || "Project"} (${files.length} files)`);
|
|
29
|
+
for (const dir of [...counts.keys()].sort()) {
|
|
30
|
+
const level = dir.split("/").length - 1;
|
|
31
|
+
console.log(`${" ".repeat(level)}${dir.split("/").pop()}/ ${counts.get(dir)}`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const langs = new Map();
|
|
35
|
+
for (const file of files) {
|
|
36
|
+
const ext = extname(file) || "(none)";
|
|
37
|
+
langs.set(ext, (langs.get(ext) ?? 0) + 1);
|
|
38
|
+
}
|
|
39
|
+
console.log(`## Languages: ${[...langs].sort((a, b) => b[1] - a[1]).slice(0, 8).map(([ext, n]) => `${ext} ${n}`).join(", ")}`);
|
|
40
|
+
|
|
41
|
+
const entries = [];
|
|
42
|
+
if (tool.pkg) {
|
|
43
|
+
for (const key of ["main", "module", "types"]) if (typeof tool.pkg[key] === "string") entries.push(`${key}: ${tool.pkg[key]}`);
|
|
44
|
+
if (tool.pkg.bin) entries.push(`bin: ${typeof tool.pkg.bin === "string" ? tool.pkg.bin : Object.values(tool.pkg.bin).join(", ")}`);
|
|
45
|
+
if (tool.pkg.exports) entries.push(`exports: ${JSON.stringify(tool.pkg.exports).slice(0, 160)}`);
|
|
46
|
+
for (const [key, value] of Object.entries(tool.pkg)) if (value && typeof value === "object" && Array.isArray(value.extensions)) entries.push(`${key}.extensions: ${value.extensions.join(", ")}`);
|
|
47
|
+
}
|
|
48
|
+
for (const file of files) if (/(^|\/)(main|index|app|server|cli)\.(ts|tsx|js|mjs|py|go|rs)$|(^|\/)manage\.py$|(^|\/)cmd\/[^/]+\/main\.go$/.test(file) && file.split("/").length <= 3) entries.push(file);
|
|
49
|
+
if (entries.length > 0) console.log(`## Entry points\n${[...new Set(entries)].slice(0, 15).map((entry) => `- ${entry}`).join("\n")}`);
|
|
50
|
+
|
|
51
|
+
const testDirs = new Map();
|
|
52
|
+
for (const file of files.filter(isTest)) {
|
|
53
|
+
const dir = file.split("/").slice(0, -1).join("/") || ".";
|
|
54
|
+
testDirs.set(dir, (testDirs.get(dir) ?? 0) + 1);
|
|
55
|
+
}
|
|
56
|
+
if (testDirs.size > 0) console.log(`## Tests (${[...testDirs.values()].reduce((a, b) => a + b, 0)} files)\n${[...testDirs].sort((a, b) => b[1] - a[1]).slice(0, 10).map(([dir, n]) => `- ${dir}/ ${n}`).join("\n")}`);
|
|
57
|
+
|
|
58
|
+
const configs = files.filter((file) => !file.includes("/") && /^(package\.json|tsconfig.*\.json|vite\.config\.\w+|next\.config\.\w+|playwright\.config\.\w+|vitest\.config\.\w+|jest\.config\.\w+|eslint\.config\.\w+|\.eslintrc.*|biome\.jsonc?|tailwind\.config\.\w+|pyproject\.toml|setup\.cfg|requirements.*\.txt|go\.mod|Cargo\.toml|Makefile|justfile|Dockerfile|docker-compose\.ya?ml|\.env\.example)$/.test(file));
|
|
59
|
+
if (configs.length > 0) console.log(`## Config: ${configs.join(", ")}`);
|
|
60
|
+
const readme = ["README.md", "readme.md", "CLAUDE.md", "AGENTS.md", "CONTRIBUTING.md"].filter((file) => existsSync(join(root, file)));
|
|
61
|
+
if (readme.length > 0) console.log(`## Docs to read first: ${readme.join(", ")}`);
|
|
62
|
+
if (existsSync(join(root, "CLAUDE.md"))) {
|
|
63
|
+
const head = readFileSync(join(root, "CLAUDE.md"), "utf8").split("\n").slice(0, 3).join(" ").slice(0, 200);
|
|
64
|
+
console.log(` CLAUDE.md starts: ${head}`);
|
|
65
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// purpose: run only the tests that cover the files changed on this branch (or given files), with a timeout; prints the command, the tail of its output and the exit code
|
|
3
|
+
// usage: node {script} [files…] [--base <ref>] [--timeout <seconds>] [--dry-run]
|
|
4
|
+
import { baseRef, changedFiles, detect, isTest, parseArgs, projectRoot, sh, tail, testsFor } from "./lib/common.mjs";
|
|
5
|
+
|
|
6
|
+
const { flags, rest } = parseArgs();
|
|
7
|
+
const root = projectRoot();
|
|
8
|
+
const tool = detect(root);
|
|
9
|
+
const files = rest.length > 0 ? rest : changedFiles(root, baseRef(root, flags.base));
|
|
10
|
+
if (files.length === 0) {
|
|
11
|
+
console.log("No changed files: nothing to test.");
|
|
12
|
+
process.exit(0);
|
|
13
|
+
}
|
|
14
|
+
const covered = testsFor(root, files);
|
|
15
|
+
const tests = [...new Set([...covered.values()].flat())];
|
|
16
|
+
const untested = [...covered].filter(([file, hits]) => hits.length === 0 && !isTest(file)).map(([file]) => file);
|
|
17
|
+
|
|
18
|
+
function plan() {
|
|
19
|
+
const goTests = files.filter((file) => file.endsWith(".go"));
|
|
20
|
+
if (tool.go && goTests.length > 0) return { cmd: "go", args: ["test", ...new Set(goTests.map((file) => `./${file.split("/").slice(0, -1).join("/") || "."}`))] };
|
|
21
|
+
const py = tests.filter((file) => file.endsWith(".py"));
|
|
22
|
+
if (tool.python && py.length > 0) return { cmd: "python3", args: ["-m", "pytest", "-q", ...py] };
|
|
23
|
+
if (tool.rust && files.some((file) => file.endsWith(".rs"))) return { cmd: "cargo", args: ["test", "--quiet"] };
|
|
24
|
+
const js = tests.filter((file) => /\.[cm]?[jt]sx?$/.test(file));
|
|
25
|
+
if (!tool.pkg || js.length === 0) return undefined;
|
|
26
|
+
const testScript = tool.pkg.scripts?.test ?? "";
|
|
27
|
+
if (tool.deps.vitest || /vitest/.test(testScript)) return { cmd: "npx", args: ["vitest", "run", ...js] };
|
|
28
|
+
if (tool.deps.jest || /jest/.test(testScript)) return { cmd: "npx", args: ["jest", ...js] };
|
|
29
|
+
if (tool.deps.mocha || /mocha/.test(testScript)) return { cmd: "npx", args: ["mocha", ...js] };
|
|
30
|
+
if (/@playwright\/test/.test(JSON.stringify(tool.deps)) && js.every((file) => /e2e|playwright|\/web\//.test(file))) return { cmd: "npx", args: ["playwright", "test", ...js] };
|
|
31
|
+
if (/node\s+--test/.test(testScript) || js.length > 0) return { cmd: "node", args: ["--test", ...js.filter((file) => !/\/(e2e|web)\//.test(file))] };
|
|
32
|
+
return undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const run = plan();
|
|
36
|
+
console.log(`Changed: ${files.length} file(s). Tests covering them: ${tests.length}.`);
|
|
37
|
+
if (untested.length > 0) console.log(`No test found for: ${untested.slice(0, 15).join(", ")}${untested.length > 15 ? ", …" : ""}`);
|
|
38
|
+
if (!run || run.args.length === 0) {
|
|
39
|
+
console.log("No targeted test command for these files. Run the project's test command (see project_commands.mjs) if the change needs it.");
|
|
40
|
+
process.exit(0);
|
|
41
|
+
}
|
|
42
|
+
console.log(`$ ${run.cmd} ${run.args.join(" ")}`);
|
|
43
|
+
if (flags["dry-run"]) process.exit(0);
|
|
44
|
+
const seconds = Number(flags.timeout ?? 300);
|
|
45
|
+
const result = sh(run.cmd, run.args, { cwd: root, timeout: seconds * 1000, env: { ...process.env, CI: "1", FORCE_COLOR: "0" } });
|
|
46
|
+
console.log(tail(`${result.out}${result.err ? `\n${result.err}` : ""}`));
|
|
47
|
+
console.log(result.code === 0 ? "PASS" : `FAIL (exit ${result.code}${result.code === 1 && seconds ? "" : ""})`);
|
|
48
|
+
process.exit(result.code === 0 ? 0 : 1);
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
8
8
|
import { Type } from "typebox";
|
|
9
9
|
import { createDeskClient, type DeskClient } from "./ipc.ts";
|
|
10
|
-
import {
|
|
10
|
+
import { DESK_ENV, isEditTool, MAX_WAIT_MS } from "./session.ts";
|
|
11
11
|
|
|
12
12
|
function text(value: string) {
|
|
13
13
|
return { content: [{ type: "text" as const, text: value }], details: undefined };
|
|
@@ -98,34 +98,4 @@ export function registerDeskClient(pi: ExtensionAPI, client?: DeskClient): void
|
|
|
98
98
|
return text((await desk.request({ op: "wait", timeoutMs }, timeoutMs + 5000)).text);
|
|
99
99
|
},
|
|
100
100
|
});
|
|
101
|
-
|
|
102
|
-
pi.registerTool({
|
|
103
|
-
name: "ask_peer",
|
|
104
|
-
label: "Ask a peer",
|
|
105
|
-
description:
|
|
106
|
-
"Ask another worker in this batch a short question about its part (a field name, a route, a shape it settled) and wait for its answer, instead of guessing. Name the peer (DEV, DESIGN or QA), or give a file path to ask whoever holds it. Questions only: peers cannot give each other work. Waits up to 90 seconds by default.",
|
|
107
|
-
parameters: Type.Object({
|
|
108
|
-
question: Type.String({ description: "The question, in one or two sentences" }),
|
|
109
|
-
to: Type.Optional(Type.String({ description: "DEV, DESIGN or QA" })),
|
|
110
|
-
path: Type.Optional(Type.String({ description: "Ask whoever holds this file instead" })),
|
|
111
|
-
seconds: Type.Optional(Type.Number({ description: "How long to wait, at most 180 seconds" })),
|
|
112
|
-
}),
|
|
113
|
-
async execute(_id, params) {
|
|
114
|
-
const timeoutMs = Math.min(MAX_ASK_WAIT_MS, Math.max(5, params.seconds ?? ASK_WAIT_MS / 1000) * 1000);
|
|
115
|
-
return text((await desk.request({ op: "ask", text: params.question, to: params.to ?? "", path: params.path ?? "", timeoutMs }, timeoutMs + 5000)).text);
|
|
116
|
-
},
|
|
117
|
-
});
|
|
118
|
-
|
|
119
|
-
pi.registerTool({
|
|
120
|
-
name: "answer_peer",
|
|
121
|
-
label: "Answer a peer",
|
|
122
|
-
description: "Answer a question another worker asked you (the desk tells you its id). Answer from what you know or have built, in a line or two, then carry on with your own work.",
|
|
123
|
-
parameters: Type.Object({
|
|
124
|
-
id: Type.Number({ description: "The question's id" }),
|
|
125
|
-
answer: Type.String({ description: "Your answer" }),
|
|
126
|
-
}),
|
|
127
|
-
async execute(_id, params) {
|
|
128
|
-
return text((await desk.request({ op: "answer", questionId: params.id, text: params.answer })).text);
|
|
129
|
-
},
|
|
130
|
-
});
|
|
131
101
|
}
|
package/src/desk/ipc.ts
CHANGED
|
@@ -18,12 +18,8 @@ export type DeskOp =
|
|
|
18
18
|
| "wait"
|
|
19
19
|
| "delegate"
|
|
20
20
|
| "cancel_delegate"
|
|
21
|
-
| "consult"
|
|
22
|
-
| "cancel_consult"
|
|
23
21
|
| "post"
|
|
24
22
|
| "ack"
|
|
25
|
-
| "ask"
|
|
26
|
-
| "answer"
|
|
27
23
|
| "artifact";
|
|
28
24
|
|
|
29
25
|
export interface DeskRequest {
|
|
@@ -44,12 +40,6 @@ export interface DeskRequest {
|
|
|
44
40
|
targets?: string[];
|
|
45
41
|
/** ack: the board events (sequences or stable ids) the caller says it incorporated. */
|
|
46
42
|
events?: Array<string | number>;
|
|
47
|
-
/** ask: who the question is for (DEV, DESIGN, QA); `path` asks whoever holds that file. */
|
|
48
|
-
to?: string;
|
|
49
|
-
/** answer: the question being answered. */
|
|
50
|
-
questionId?: number;
|
|
51
|
-
/** An expert consult's own id, so the worker can cancel it. */
|
|
52
|
-
consultId?: string;
|
|
53
43
|
/** artifact: the caller's own assignment id; volunteered, never trusted on its own. */
|
|
54
44
|
assignment?: string;
|
|
55
45
|
/** artifact: the O-… reference to open. */
|
|
@@ -203,7 +193,7 @@ export function createDeskClient(address: string, worker: string): DeskClient {
|
|
|
203
193
|
request(request, timeoutMs = 10_000) {
|
|
204
194
|
const id = nextId++;
|
|
205
195
|
return new Promise((done) => {
|
|
206
|
-
// 0 waits for as long as the answer takes (a delegation
|
|
196
|
+
// 0 waits for as long as the answer takes (a delegation): no time limit.
|
|
207
197
|
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
208
198
|
pending.delete(id);
|
|
209
199
|
done({ id, ok: false, text: "the file desk did not answer" });
|
package/src/desk/session.ts
CHANGED
|
@@ -15,15 +15,6 @@ import { deliveryPath, markDelivered, markHandled, markSeen, readDelivery, repla
|
|
|
15
15
|
/** Tools the desk adds to every parallel worker's allowlist. */
|
|
16
16
|
export const DESK_TOOLS: readonly string[] = ["claim_file", "handover_file", "my_files", "wait_for_files"];
|
|
17
17
|
|
|
18
|
-
/** The desk tools of a worker with a checkout of its own: questions only, no claims. */
|
|
19
|
-
export const PEER_TOOLS: readonly string[] = ["ask_peer", "answer_peer"];
|
|
20
|
-
|
|
21
|
-
/** How long `ask_peer` waits for an answer by default, and at most. */
|
|
22
|
-
export const ASK_WAIT_MS = 90_000;
|
|
23
|
-
export const MAX_ASK_WAIT_MS = 180_000;
|
|
24
|
-
const MAX_QUESTION = 800;
|
|
25
|
-
const MAX_ANSWER = 1500;
|
|
26
|
-
|
|
27
18
|
/** Env names the desk client extension reads inside a worker process. */
|
|
28
19
|
export const DESK_ENV = { address: "BOT_LOBBY_DESK", worker: "BOT_LOBBY_DESK_ID" } as const;
|
|
29
20
|
|
|
@@ -43,25 +34,6 @@ function label(worker: WorkerId): string {
|
|
|
43
34
|
/** A holder named for a handover message: its role when it has one (the note speaks for the role), its full identity otherwise. */
|
|
44
35
|
const roleLabel = (worker: WorkerId): string => label((roleOf(worker) ?? worker) as WorkerId);
|
|
45
36
|
|
|
46
|
-
/** A peer named the way workers know each other (DEV, DESIGN, QA) or by domain; a child run id is itself. */
|
|
47
|
-
export function peerId(name: string): WorkerId {
|
|
48
|
-
return recipientId(name) as WorkerId;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function flat(text: string, max: number): string {
|
|
52
|
-
const value = text.replace(/\s+/g, " ").trim();
|
|
53
|
-
return value.length > max ? `${value.slice(0, max - 1)}…` : value;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
interface PeerQuestion {
|
|
57
|
-
id: number;
|
|
58
|
-
from: WorkerId;
|
|
59
|
-
to: WorkerId;
|
|
60
|
-
question: string;
|
|
61
|
-
resolve: (answer: string | undefined) => void;
|
|
62
|
-
timer: ReturnType<typeof setTimeout>;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
37
|
function queueLines(queue: readonly Claim[]): string {
|
|
66
38
|
return queue.map((claim, index) => `${index + 1}) ${label(claim.worker)} — ${claim.intent}`).join("; ");
|
|
67
39
|
}
|
|
@@ -93,10 +65,6 @@ export interface DeskSessionOptions {
|
|
|
93
65
|
cwd: string;
|
|
94
66
|
/** The task board's file: workers post to it through the desk, and contracts and blockers reach the other workers at once. */
|
|
95
67
|
boardPath?: string;
|
|
96
|
-
/** False when every worker has a checkout of its own: edits need no claim, and the desk only carries questions and the board. */
|
|
97
|
-
claims?: boolean;
|
|
98
|
-
/** Workers of one parallel batch may ask each other questions (`ask_peer`). */
|
|
99
|
-
peers?: boolean;
|
|
100
68
|
/** A worker that finished without handing a file over leaves this note for the next worker. */
|
|
101
69
|
onHandover?: (handover: Handover) => void;
|
|
102
70
|
}
|
|
@@ -114,8 +82,6 @@ export class DeskSession {
|
|
|
114
82
|
private readonly handles = new Map<WorkerId, AgentHandle>();
|
|
115
83
|
private readonly greeted = new Set<WorkerId>();
|
|
116
84
|
private readonly options: DeskSessionOptions;
|
|
117
|
-
private readonly questions = new Map<number, PeerQuestion>();
|
|
118
|
-
private nextQuestion = 1;
|
|
119
85
|
|
|
120
86
|
constructor(options: DeskSessionOptions) {
|
|
121
87
|
this.options = options;
|
|
@@ -139,14 +105,9 @@ export class DeskSession {
|
|
|
139
105
|
this.catchUp(worker);
|
|
140
106
|
}
|
|
141
107
|
|
|
142
|
-
/**
|
|
143
|
-
get usesClaims(): boolean {
|
|
144
|
-
return this.options.claims !== false;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
/** The desk tools its workers get: claims, questions, or both. */
|
|
108
|
+
/** The desk tools its workers get. */
|
|
148
109
|
tools(): readonly string[] {
|
|
149
|
-
return
|
|
110
|
+
return DESK_TOOLS;
|
|
150
111
|
}
|
|
151
112
|
|
|
152
113
|
/** True once the worker's desk extension has checked in. */
|
|
@@ -158,10 +119,6 @@ export class DeskSession {
|
|
|
158
119
|
release(worker: WorkerId, note: (path: string, next: Claim) => string): void {
|
|
159
120
|
this.releaseFiles(worker, note);
|
|
160
121
|
this.handles.delete(worker);
|
|
161
|
-
// A finished worker can no longer answer, and its own questions need no answer.
|
|
162
|
-
for (const question of [...this.questions.values()]) {
|
|
163
|
-
if (question.to === worker || question.from === worker) this.settle(question, undefined);
|
|
164
|
-
}
|
|
165
122
|
}
|
|
166
123
|
|
|
167
124
|
|
|
@@ -176,7 +133,6 @@ export class DeskSession {
|
|
|
176
133
|
}
|
|
177
134
|
|
|
178
135
|
async close(): Promise<void> {
|
|
179
|
-
for (const question of [...this.questions.values()]) this.settle(question, undefined);
|
|
180
136
|
if (this.server) sessions.delete(this.server.address);
|
|
181
137
|
this.desk.close();
|
|
182
138
|
await this.server?.close();
|
|
@@ -220,17 +176,13 @@ export class DeskSession {
|
|
|
220
176
|
return this.post(request.from?.trim() || worker, worker, request.kind ?? "", request.text ?? "", request.files ?? [], request.targets ?? []);
|
|
221
177
|
case "ack":
|
|
222
178
|
return this.ack(worker, request.events ?? []);
|
|
223
|
-
case "ask":
|
|
224
|
-
return this.ask(worker, request.to ?? "", request.path ?? "", request.text ?? "", Math.min(MAX_ASK_WAIT_MS, Math.max(5000, request.timeoutMs ?? ASK_WAIT_MS)));
|
|
225
|
-
case "answer":
|
|
226
|
-
return this.answer(worker, request.questionId ?? 0, request.text ?? "");
|
|
227
179
|
default:
|
|
228
180
|
return { ok: false, text: `unknown desk operation ${String(request.op)}` };
|
|
229
181
|
}
|
|
230
182
|
}
|
|
231
183
|
|
|
232
184
|
private check(worker: WorkerId, path: string): Omit<DeskResponse, "id"> {
|
|
233
|
-
if (this.
|
|
185
|
+
if (this.desk.holds(worker, path)) return { ok: true, allowed: true, text: "" };
|
|
234
186
|
const key = this.desk.normalize(path);
|
|
235
187
|
const holder = this.desk.holderOf(path);
|
|
236
188
|
if (!holder) {
|
|
@@ -320,12 +272,11 @@ export class DeskSession {
|
|
|
320
272
|
return [...this.handles.keys()].filter((peer) => peer !== worker && routedTo(post, this.scopeFor(peer)));
|
|
321
273
|
}
|
|
322
274
|
|
|
323
|
-
/** One peer's delivery scope: its subscription, its role, and the files it holds or is queued for
|
|
275
|
+
/** One peer's delivery scope: its subscription, its role, and the files it holds or is queued for. */
|
|
324
276
|
private scopeFor(peer: WorkerId): RecipientScope {
|
|
325
277
|
const kinds = subscriptionFor(peer);
|
|
326
278
|
const role = roleOf(peer);
|
|
327
279
|
const base = { recipient: peer, ...(role && role !== peer ? { role } : {}), kinds };
|
|
328
|
-
if (!this.usesClaims) return base;
|
|
329
280
|
const files = [...this.desk.heldBy(peer).map((file) => file.path), ...this.desk.waitingFor(peer).map((entry) => entry.path)];
|
|
330
281
|
return { ...base, files };
|
|
331
282
|
}
|
|
@@ -364,54 +315,6 @@ export class DeskSession {
|
|
|
364
315
|
markDelivered(path, worker, through);
|
|
365
316
|
}
|
|
366
317
|
|
|
367
|
-
private async ask(worker: WorkerId, to: string, path: string, question: string, timeoutMs: number): Promise<Omit<DeskResponse, "id">> {
|
|
368
|
-
if (!this.options.peers) return { ok: false, text: "No peers work alongside you here." };
|
|
369
|
-
const text = flat(question, MAX_QUESTION);
|
|
370
|
-
if (!text) return { ok: false, text: "ask_peer needs a question." };
|
|
371
|
-
if (path.trim() && !this.usesClaims) return { ok: false, text: "Every worker in this batch has a checkout of its own, so nobody holds files: name the peer (DEV, DESIGN or QA) instead." };
|
|
372
|
-
const target = path.trim() ? this.desk.holderOf(path)?.worker : to.trim() ? peerId(to) : undefined;
|
|
373
|
-
if (!target) return { ok: false, text: path.trim() ? `Nobody holds \`${this.desk.normalize(path)}\`; read it yourself.` : "Name the peer (DEV, DESIGN or QA) or a file its holder should answer about." };
|
|
374
|
-
if (target === worker) return { ok: false, text: "That is you." };
|
|
375
|
-
if (!this.handles.has(target)) return { ok: false, text: `${label(target)} is not working right now. Post a \`question\` on the board instead; the oracle sees it.` };
|
|
376
|
-
// A worker waiting on its own question cannot answer until that returns: asking it would chain the waits (or close a cycle).
|
|
377
|
-
const theirs = [...this.questions.values()].find((entry) => entry.from === target);
|
|
378
|
-
if (theirs?.to === worker) return { ok: false, text: `${label(target)} is waiting on your answer to its question #${theirs.id} ("${theirs.question}"). Answer it with answer_peer first.` };
|
|
379
|
-
if (theirs) return { ok: false, text: `${label(target)} is waiting on an answer from ${label(theirs.to)} and cannot answer yet. Carry on with your other work and ask again shortly, or post a \`question\` on the board.` };
|
|
380
|
-
const id = this.nextQuestion++;
|
|
381
|
-
const answer = await new Promise<string | undefined>((resolve) => {
|
|
382
|
-
const timer = setTimeout(() => this.settle(this.questions.get(id), undefined), timeoutMs);
|
|
383
|
-
this.questions.set(id, { id, from: worker, to: target, question: text, resolve, timer });
|
|
384
|
-
this.steer(target, `bot-lobby desk: question #${id} from ${label(worker)}: ${text} Answer it now with answer_peer (id ${id}) in a line or two, from what you know or have built, then carry on with your own work. It is a question, not a task: you take work only from your brief.`);
|
|
385
|
-
this.handles.get(worker)?.annotate({ note: `asked ${label(target)}`, noteKind: "info" });
|
|
386
|
-
});
|
|
387
|
-
if (answer === undefined) {
|
|
388
|
-
return { ok: true, text: `${label(target)} did not answer within ${Math.round(timeoutMs / 1000)} seconds (it may be in a long command, or it finished). Carry on with your best reading of the brief and the board, and list the open question under Notes.` };
|
|
389
|
-
}
|
|
390
|
-
if (this.options.boardPath) {
|
|
391
|
-
try {
|
|
392
|
-
appendPost(this.options.boardPath, { from: worker, kind: "note", text: `Asked ${label(target)}: ${text} Answer: ${answer}` });
|
|
393
|
-
} catch {
|
|
394
|
-
// The answer still reaches the asker.
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
return { ok: true, text: `${label(target)} answers: ${answer}` };
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
private answer(worker: WorkerId, id: number, text: string): Omit<DeskResponse, "id"> {
|
|
401
|
-
const question = this.questions.get(id);
|
|
402
|
-
if (!question || question.to !== worker) return { ok: false, text: `There is no open question #${id} for you (it may have timed out).` };
|
|
403
|
-
const answer = flat(text, MAX_ANSWER);
|
|
404
|
-
if (!answer) return { ok: false, text: "answer_peer needs an answer." };
|
|
405
|
-
this.settle(question, answer);
|
|
406
|
-
return { ok: true, text: `Answer sent to ${label(question.from)}.` };
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
private settle(question: PeerQuestion | undefined, answer: string | undefined): void {
|
|
410
|
-
if (!question || !this.questions.has(question.id)) return;
|
|
411
|
-
clearTimeout(question.timer);
|
|
412
|
-
this.questions.delete(question.id);
|
|
413
|
-
question.resolve(answer);
|
|
414
|
-
}
|
|
415
318
|
}
|
|
416
319
|
|
|
417
320
|
/** A handover note for `next`, written from a finished worker's report. */
|
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { validateAssignment, type WorkerAssignment } from "./assignment.ts";
|
|
3
|
+
import { assignmentPrompt } from "../roles/worker.ts";
|
|
4
|
+
import { selectAssignmentTools } from "./assignment-policy.ts";
|
|
5
|
+
import { prepareAssignmentDiscovery } from "./assignment-discovery.ts";
|
|
6
|
+
import { delegationHost } from "./delegation.ts";
|
|
7
|
+
import { grantableTools } from "../pi/grants.ts";
|
|
2
8
|
import { createLiveRun } from "./live-run.ts";
|
|
3
9
|
import type { Domain, Role } from "../schemas/agent.ts";
|
|
4
10
|
import type { AgentRun } from "../schemas/findings.ts";
|
|
5
11
|
import { roleSpec } from "../roles/registry.ts";
|
|
6
12
|
import { compilePrompt } from "../prompts/compiler.ts";
|
|
7
13
|
import { EditLog } from "../state/changes.ts";
|
|
8
|
-
import { runPiAgent, spawnPiProcess, type ProcessRunner, type RelayAsk } from "./pi-runner.ts";
|
|
14
|
+
import { MCP_RESOURCE_TOOLS, runPiAgent, spawnPiProcess, type PiRunOptions, type ProcessRunner, type RelayAsk } from "./pi-runner.ts";
|
|
9
15
|
import { KNOWLEDGE_TOOLS, TASK_ID_ENV } from "../knowledge/catalog-tools.ts";
|
|
10
16
|
import { ASK_ENV } from "../ask/relay.ts";
|
|
11
17
|
import type { EffortRouter, RunProfileLike } from "../classifier/effort.ts";
|
|
@@ -37,6 +43,8 @@ export interface AgentHandle {
|
|
|
37
43
|
}
|
|
38
44
|
|
|
39
45
|
export interface AgentRequest {
|
|
46
|
+
/** Host-owned storage and master-authored brief; never inferred from worker output. */
|
|
47
|
+
assignment?: { brief: WorkerAssignment; taskDir: string };
|
|
40
48
|
taskId: string;
|
|
41
49
|
domain: Domain;
|
|
42
50
|
role: Role;
|
|
@@ -54,9 +62,7 @@ export interface AgentRequest {
|
|
|
54
62
|
autoCompact?: boolean;
|
|
55
63
|
/** Tokens at which this agent compacts, when its settings set it. */
|
|
56
64
|
compactAt?: number;
|
|
57
|
-
delegationQuota?: { used: number
|
|
58
|
-
/** See PiRunOptions.expert. */
|
|
59
|
-
expert?: { model?: string; thinking: string };
|
|
65
|
+
delegationQuota?: { used: number };
|
|
60
66
|
thinking?: string;
|
|
61
67
|
/** Skill files this agent may load; absent keeps pi's own discovery. */
|
|
62
68
|
skills?: string[];
|
|
@@ -112,6 +118,13 @@ function retryable(run: AgentRun): boolean {
|
|
|
112
118
|
* time limit: an agent works until it reports, is cancelled, or stalls.
|
|
113
119
|
*/
|
|
114
120
|
export async function runAgent(request: AgentRequest, run: ProcessRunner = spawnPiProcess): Promise<AgentRun> {
|
|
121
|
+
if (request.assignment !== undefined) {
|
|
122
|
+
if (!request.assignment || typeof request.assignment !== "object") throw new Error("Invalid structured assignment: expected brief and host-owned taskDir.");
|
|
123
|
+
if (request.role !== "worker") throw new Error("Structured assignments require the worker role.");
|
|
124
|
+
if (!request.assignment.taskDir) throw new Error("Assigned execution requires host-owned task storage.");
|
|
125
|
+
const brief = await validateAssignment(request.assignment.brief, request.cwd);
|
|
126
|
+
request = { ...request, assignment: { ...request.assignment, brief } };
|
|
127
|
+
}
|
|
115
128
|
const startedAt = new Date().toISOString();
|
|
116
129
|
const attempts = Math.max(1, (request.retries ?? 0) + 1);
|
|
117
130
|
// A failed attempt may have edited files before the retry: the run owns every edit.
|
|
@@ -163,6 +176,23 @@ function toolsFor(request: AgentRequest): readonly string[] | undefined {
|
|
|
163
176
|
return [...(tools ?? []), ...extra];
|
|
164
177
|
}
|
|
165
178
|
|
|
179
|
+
/** Inspect complete existing grants, then replace them; never dispatch through the temporary host. */
|
|
180
|
+
async function prepareAssignedPolicy(options: PiRunOptions, request: AgentRequest, run: ProcessRunner): Promise<void> {
|
|
181
|
+
if (!request.assignment) return;
|
|
182
|
+
const host = await delegationHost(options, run);
|
|
183
|
+
try {
|
|
184
|
+
const connected = grantableTools().map((tool) => tool.name);
|
|
185
|
+
// MCP resource tools are never appended for an assigned run: the master selects them, and only an MCP grant permits them.
|
|
186
|
+
const granted = [...host.tools, ...host.mcpTools, ...(host.mcpTools.length > 0 ? MCP_RESOURCE_TOOLS : [])];
|
|
187
|
+
const available = [...host.tools.filter((name) => !name.startsWith("mcp__")), ...connected, ...MCP_RESOURCE_TOOLS];
|
|
188
|
+
const selected = selectAssignmentTools(request.assignment.brief, { granted, known: [...granted, ...connected, ...MCP_RESOURCE_TOOLS], available });
|
|
189
|
+
// The grants stay as they are for the run's host; the selection replaces them inside it.
|
|
190
|
+
options.assignedTools = selected;
|
|
191
|
+
const state = await prepareAssignmentDiscovery(request.assignment.taskDir, request.assignment.brief.id, request.assignment.brief.revision, request.assignment.brief.discoveryLimit);
|
|
192
|
+
options.assignedSession!.consumedDiscovery = state.consumed;
|
|
193
|
+
} finally { await host.close(); }
|
|
194
|
+
}
|
|
195
|
+
|
|
166
196
|
/**
|
|
167
197
|
* Run one domain/role agent in an isolated pi process. The role's tool
|
|
168
198
|
* allowlist comes from its spec, so read-only roles cannot modify anything.
|
|
@@ -182,11 +212,10 @@ async function runAgentOnce(request: AgentRequest, run: ProcessRunner, attempt:
|
|
|
182
212
|
const signal = request.signal ? AbortSignal.any([request.signal, controller.signal]) : controller.signal;
|
|
183
213
|
try {
|
|
184
214
|
const systemPrompt = request.systemPrompt ?? compilePrompt({ domain: request.domain, role: request.role, ...request.context });
|
|
185
|
-
const
|
|
215
|
+
const options: PiRunOptions = {
|
|
186
216
|
cwd: request.cwd,
|
|
187
217
|
agent: { runId: base.runId, taskId: request.taskId, domain: request.domain, role: request.role },
|
|
188
218
|
delegationQuota: quota,
|
|
189
|
-
...(request.expert ? { expert: request.expert } : {}),
|
|
190
219
|
effort: request.effort,
|
|
191
220
|
effortProfile: request.effortProfile,
|
|
192
221
|
onChildRun: (child) => {
|
|
@@ -197,7 +226,17 @@ async function runAgentOnce(request: AgentRequest, run: ProcessRunner, attempt:
|
|
|
197
226
|
...(request.skills ? { skills: request.skills } : {}),
|
|
198
227
|
...(request.autoCompact === false ? { autoCompact: false } : {}),
|
|
199
228
|
...(request.compactAt ? { compactAt: request.compactAt } : {}),
|
|
200
|
-
task: request.instruction,
|
|
229
|
+
task: [request.instruction, request.assignment ? assignmentPrompt(request.assignment.brief) : ""].filter(Boolean).join("\n\n"),
|
|
230
|
+
...(request.assignment ? { assignedSession: {
|
|
231
|
+
taskDir: request.assignment.taskDir,
|
|
232
|
+
assignmentId: request.assignment.brief.id,
|
|
233
|
+
revision: request.assignment.brief.revision,
|
|
234
|
+
evidence: request.assignment.brief.evidence,
|
|
235
|
+
completedWork: request.assignment.brief.completedWork,
|
|
236
|
+
needs: request.assignment.brief.needs,
|
|
237
|
+
files: request.assignment.brief.files,
|
|
238
|
+
verification: request.assignment.brief.verification,
|
|
239
|
+
} } : {}),
|
|
201
240
|
systemPrompt,
|
|
202
241
|
tools: toolsFor(request),
|
|
203
242
|
model: request.model,
|
|
@@ -214,7 +253,10 @@ async function runAgentOnce(request: AgentRequest, run: ProcessRunner, attempt:
|
|
|
214
253
|
live.onEvent(event);
|
|
215
254
|
},
|
|
216
255
|
onStart: (handle) => request.onStart?.({ runId: base.runId, steer: handle.steer, annotate: live.annotate }),
|
|
217
|
-
}
|
|
256
|
+
};
|
|
257
|
+
await prepareAssignedPolicy(options, request, run);
|
|
258
|
+
// An assigned run gets its own conversation and in-process guard; a harness is refused before any request.
|
|
259
|
+
const result = await runPiAgent(options, run);
|
|
218
260
|
const current = live.current();
|
|
219
261
|
const final: AgentRun = {
|
|
220
262
|
...base,
|