toolroll 0.9.108 → 0.9.109
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/CHANGELOG.md +34 -0
- package/dist/advanced-view.js +0 -1
- package/dist/agent-fence.js +35 -4
- package/dist/agent-state.js +5 -2
- package/dist/assignment-ui.js +5 -5
- package/dist/assignment.js +5 -2
- package/dist/browser/terminal.js +1 -1
- package/dist/browser/workspace.css +1 -1
- package/dist/browser/workspace.js +37 -34
- package/dist/browser-crew.js +4 -4
- package/dist/browser-workspace.js +4 -11
- package/dist/builder.js +9 -1
- package/dist/chat-controls.js +6 -5
- package/dist/chat-decide.js +1 -1
- package/dist/chat-quiet.js +3 -3
- package/dist/chat-voice.js +2 -2
- package/dist/cli-help.js +12 -13
- package/dist/cli.js +4 -3
- package/dist/console-chrome.js +10 -3
- package/dist/contracts/console-api.js +4 -3
- package/dist/contracts/handoff.js +4 -0
- package/dist/decision.js +17 -0
- package/dist/demo-chat.js +1 -1
- package/dist/demo.js +6 -0
- package/dist/design/kit.js +4 -3
- package/dist/dispatch.js +3 -8
- package/dist/flexible-available.js +1 -0
- package/dist/flexible-schema.js +32 -0
- package/dist/flexible-thread-schema.js +30 -0
- package/dist/flexible-thread.js +526 -0
- package/dist/flexible-ui.js +44 -0
- package/dist/flexible.js +359 -0
- package/dist/git-views.js +38 -38
- package/dist/guides.js +11 -10
- package/dist/keymap.js +1 -1
- package/dist/lead-context.js +1 -1
- package/dist/limits-ui.js +1 -1
- package/dist/live-bus.js +70 -13
- package/dist/needs-you.js +3 -3
- package/dist/nightly-github.js +2 -2
- package/dist/operate.js +111 -3
- package/dist/project-delete-ui.js +2 -1
- package/dist/project-delete.js +1 -0
- package/dist/provider-auth.js +1 -1
- package/dist/release.js +1 -0
- package/dist/result-actions.js +3 -0
- package/dist/result-evidence-readers.js +8 -2
- package/dist/result-review.js +20 -9
- package/dist/serve.js +32 -29
- package/dist/server/chat.js +9 -9
- package/dist/server/chrome.js +16 -16
- package/dist/server/guards.js +10 -4
- package/dist/server/home.js +37 -5
- package/dist/server/http.js +4 -2
- package/dist/server/in-place.js +5 -4
- package/dist/server/kit.js +2 -2
- package/dist/server/live.js +100 -10
- package/dist/server/pages.js +79 -53
- package/dist/server/render-chat.js +1 -1
- package/dist/server/render-history.js +18 -4
- package/dist/server/render-new-task.js +2 -2
- package/dist/server/render-pages.js +21 -39
- package/dist/server/render-people.js +2 -2
- package/dist/server/render-projects.js +5 -5
- package/dist/server/render-results.js +26 -10
- package/dist/server/render-tasks.js +26 -17
- package/dist/server/retired-routes.js +37 -4
- package/dist/server/route-policy.js +8 -0
- package/dist/server/route-table.js +13 -4
- package/dist/server/settings-computers.js +140 -0
- package/dist/server/settings-scripts.js +15 -0
- package/dist/server/settings-section-table.js +56 -0
- package/dist/server/settings-sections.js +258 -0
- package/dist/server/settings.js +164 -19
- package/dist/server/task-views.js +47 -13
- package/dist/server/tasks.js +143 -90
- package/dist/server/welcome.js +6 -5
- package/dist/settings-groups-ui.js +24 -105
- package/dist/settings-proofs.js +5 -2
- package/dist/sqlite-telemetry.js +70 -21
- package/dist/store.js +108 -9
- package/dist/task-link.js +64 -0
- package/dist/tui.js +1 -1
- package/dist/typed-words-schema.js +18 -0
- package/dist/welcome-facts.js +3 -2
- package/dist/work-index.js +126 -29
- package/dist/work-reads.js +279 -0
- package/package.json +4 -2
|
@@ -0,0 +1,526 @@
|
|
|
1
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
+
import { randomBytes } from "node:crypto";
|
|
3
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { homedir, tmpdir } from "node:os";
|
|
5
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
6
|
+
import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
|
|
7
|
+
import { FLEXIBLE_UNAVAILABLE } from "./flexible.js";
|
|
8
|
+
import { buildCacheEnv, fenceFor, FLEXIBLE_THREADS_DIR, grantFolder, PROTECTED_DIRS, PROTECTED_FILES, runFolders, srtTermsOf } from "./agent-fence.js";
|
|
9
|
+
import { ACP_AGENTS, ACP_PROVIDER_IDS } from "./acp-agents.js";
|
|
10
|
+
import { confined, ContainmentRefusal, run } from "./exec.js";
|
|
11
|
+
import { SANDBOX_LAUNCH_SPEC, SEATBELT_NO_KEYCHAIN } from "./sandbox-runtime.js";
|
|
12
|
+
import { hardenedGit, lazyFetchSetting, recordedCommonDir } from "./teardown-git.js";
|
|
13
|
+
import { withCheckoutLock } from "./git-views.js";
|
|
14
|
+
import { processMayBeAlive } from "./process-liveness.js";
|
|
15
|
+
import { projectRowKnown } from "./store.js";
|
|
16
|
+
import { poolRootOf } from "./worktree.js";
|
|
17
|
+
export const FLEXIBLE_THREAD_ID = /^[0-9a-f]{32}$/;
|
|
18
|
+
export const flexibleKeepRef = (id) => `refs/toolroll/threads/${id}/base`;
|
|
19
|
+
export const flexibleThreadBranch = (id) => `toolroll/code-${id}`;
|
|
20
|
+
export function flexibleThreadPaths(state, id) {
|
|
21
|
+
const root = join(state, FLEXIBLE_THREADS_DIR);
|
|
22
|
+
const folder = join(root, id);
|
|
23
|
+
return { root, folder, repo: join(folder, "repo"), tmp: join(folder, "tmp"), cache: join(folder, "cache"), home: join(folder, "home") };
|
|
24
|
+
}
|
|
25
|
+
function readThread(row) {
|
|
26
|
+
if (row === undefined)
|
|
27
|
+
return null;
|
|
28
|
+
return { id: String(row["id"]), repo: String(row["repo"]), baseSha: String(row["base_sha"]), keepRef: String(row["keep_ref"]), folder: String(row["folder"]), createdBy: String(row["created_by"]),
|
|
29
|
+
createdAt: String(row["created_at"]), state: String(row["state"]), endedAt: row["ended_at"] === null ? null : String(row["ended_at"]),
|
|
30
|
+
endDetail: row["end_detail"] === null ? null : String(row["end_detail"]), livePid: row["live_pid"] === null || row["live_pid"] === undefined ? null : Number(row["live_pid"]) };
|
|
31
|
+
}
|
|
32
|
+
export function flexibleThread(store, id) {
|
|
33
|
+
if (!FLEXIBLE_THREAD_ID.test(id))
|
|
34
|
+
return null;
|
|
35
|
+
return readThread(store.handle.prepare("SELECT * FROM flexible_thread WHERE id = ?").get(id));
|
|
36
|
+
}
|
|
37
|
+
const WORDS = Object.freeze({
|
|
38
|
+
"not-available": FLEXIBLE_UNAVAILABLE,
|
|
39
|
+
"no-state-folder": "Toolroll has no state folder to keep the thread's repository in, so no thread was started.",
|
|
40
|
+
"not-a-project": "That folder isn't a project in Toolroll, so no thread was started.",
|
|
41
|
+
"repository-unusable": "This project's repository can't hold a thread safely, so no thread was started.",
|
|
42
|
+
"base-unknown": "The starting commit couldn't be found in this project's repository, so no thread was started.",
|
|
43
|
+
"setup-failed": "The thread's repository couldn't be made. Nothing was left behind.",
|
|
44
|
+
"thread-unknown": "There's no such thread.",
|
|
45
|
+
"thread-not-ready": "This thread's repository isn't ready, so it can't run.",
|
|
46
|
+
"thread-folder-changed": "This thread's folder isn't the one Toolroll made, so it can't run.",
|
|
47
|
+
"network-required": "A thread can only run through its own network proxy, and it wasn't given one.",
|
|
48
|
+
"containment": "The sandbox couldn't hold this thread, so it didn't run.",
|
|
49
|
+
"thread-running": "This thread's agent may still be running, so its repository was left as it is.",
|
|
50
|
+
"codex-unsupported": "Codex's own sandbox can't keep a Flexible thread away from threads and files made after it starts, so a Codex thread can't run in it.",
|
|
51
|
+
});
|
|
52
|
+
const refuse = (reason, detail) => ({ ok: false, reason, message: detail === undefined ? WORDS[reason] : `${WORDS[reason]} (${detail})` });
|
|
53
|
+
const real = (path) => { try {
|
|
54
|
+
return realpathSync(path);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return resolve(path);
|
|
58
|
+
} };
|
|
59
|
+
const inside = (child, parent) => { const rel = relative(parent, child); return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel); };
|
|
60
|
+
function stateFolderOf(store) {
|
|
61
|
+
const file = store.databaseFile();
|
|
62
|
+
if (file === null || file === "" || file === ":memory:")
|
|
63
|
+
return null;
|
|
64
|
+
try {
|
|
65
|
+
return dirname(realpathSync(file));
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function ownFolder(path) {
|
|
72
|
+
try {
|
|
73
|
+
const held = lstatSync(path);
|
|
74
|
+
const uid = process.getuid?.();
|
|
75
|
+
return held.isDirectory() && !held.isSymbolicLink() && (uid === undefined || held.uid === uid) && (held.mode & 0o077) === 0 && realpathSync(path) === join(realpathSync(dirname(path)), basename(path));
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
return false;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function ensureThreadsRoot(state) {
|
|
82
|
+
const root = join(state, FLEXIBLE_THREADS_DIR);
|
|
83
|
+
try {
|
|
84
|
+
mkdirSync(root, { mode: 0o700 });
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (error.code !== "EEXIST")
|
|
88
|
+
throw error;
|
|
89
|
+
}
|
|
90
|
+
if (!ownFolder(root))
|
|
91
|
+
throw new Error(`${root} isn't a private folder of yours`);
|
|
92
|
+
return root;
|
|
93
|
+
}
|
|
94
|
+
function freshInit(repo, branch) {
|
|
95
|
+
const ran = spawnSync("git", ["-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", "-c", "protocol.allow=never", "init", "-q", "--template=", "-b", branch, repo], {
|
|
96
|
+
cwd: dirname(repo), encoding: "utf8", timeout: 30_000, env: { PATH: process.env["PATH"] ?? "/usr/bin:/bin", HOME: "/nonexistent", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", LANG: "C" },
|
|
97
|
+
});
|
|
98
|
+
if (ran.status !== 0)
|
|
99
|
+
throw new Error(`git init failed${ran.stderr ? `: ${ran.stderr.trim().slice(0, 200)}` : ""}`);
|
|
100
|
+
}
|
|
101
|
+
function gitIn(inner, mode) {
|
|
102
|
+
return async (cwd, args) => hardenedGit(inner, mode, { repo: cwd })("git", ["--no-replace-objects", ...args], { cwd, timeoutMs: 60_000 });
|
|
103
|
+
}
|
|
104
|
+
const BASE_NAME = /^(?:[0-9a-f]{40}|[0-9a-f]{64}|(?!-)[A-Za-z0-9._/-]{1,200})$/;
|
|
105
|
+
async function usableRepository(repo, read) {
|
|
106
|
+
const common = recordedCommonDir(repo);
|
|
107
|
+
const objects = join(common, "objects");
|
|
108
|
+
if (!ownObjects(objects))
|
|
109
|
+
throw new Error("its objects folder isn't a real folder");
|
|
110
|
+
if (existsSync(join(objects, "info", "alternates")) || existsSync(join(objects, "info", "http-alternates")))
|
|
111
|
+
throw new Error("it borrows objects from another repository");
|
|
112
|
+
const listing = await read(repo, ["config", "--list", "--show-scope", "-z"]);
|
|
113
|
+
if (listing.code !== 0)
|
|
114
|
+
throw new Error("its git config couldn't be read");
|
|
115
|
+
if (lazyFetchSetting(listing.stdout) !== null)
|
|
116
|
+
throw new Error("it is a partial clone");
|
|
117
|
+
return { common, objects: realpathSync(objects) };
|
|
118
|
+
}
|
|
119
|
+
const ownObjects = (path) => { try {
|
|
120
|
+
const held = lstatSync(path);
|
|
121
|
+
return held.isDirectory() && !held.isSymbolicLink();
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
return false;
|
|
125
|
+
} };
|
|
126
|
+
const TOP_PROTECTED = [...PROTECTED_FILES.filter(name => !name.startsWith(".git/")).map(name => ({ name, dir: false })),
|
|
127
|
+
...PROTECTED_DIRS.filter(name => !name.startsWith(".git/")).map(name => ({ name, dir: true }))];
|
|
128
|
+
function protectedEntry(top, name, dir) {
|
|
129
|
+
let at = top;
|
|
130
|
+
const parts = name.split("/");
|
|
131
|
+
for (const [index, part] of parts.entries()) {
|
|
132
|
+
at = join(at, part);
|
|
133
|
+
let held;
|
|
134
|
+
try {
|
|
135
|
+
held = lstatSync(at);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
return "absent";
|
|
139
|
+
}
|
|
140
|
+
const last = index === parts.length - 1;
|
|
141
|
+
if (held.isSymbolicLink() || (!last && !held.isDirectory()) || (last && (dir ? !held.isDirectory() : !held.isFile())))
|
|
142
|
+
return "bad";
|
|
143
|
+
}
|
|
144
|
+
return "ok";
|
|
145
|
+
}
|
|
146
|
+
function reserveProtectedNames(repo) {
|
|
147
|
+
const reserved = [];
|
|
148
|
+
for (const { name, dir } of TOP_PROTECTED) {
|
|
149
|
+
const found = protectedEntry(repo, name, dir);
|
|
150
|
+
if (found === "bad")
|
|
151
|
+
throw new Error(`the project has a link or an unexpected entry at ${name}`);
|
|
152
|
+
if (found === "ok")
|
|
153
|
+
continue;
|
|
154
|
+
const path = join(repo, name);
|
|
155
|
+
mkdirSync(dir ? path : dirname(path), { recursive: true, mode: 0o755 });
|
|
156
|
+
if (protectedEntry(repo, name.includes("/") ? name.slice(0, name.lastIndexOf("/")) : ".", true) === "bad")
|
|
157
|
+
throw new Error(`the project has a link on the way to ${name}`);
|
|
158
|
+
if (!dir)
|
|
159
|
+
writeFileSync(path, name.endsWith(".json") ? "{}\n" : "", { mode: 0o644, flag: "wx" });
|
|
160
|
+
reserved.push(dir ? `/${name}/` : `/${name}`);
|
|
161
|
+
}
|
|
162
|
+
mkdirSync(join(repo, ".git", "info"), { recursive: true, mode: 0o755 });
|
|
163
|
+
writeFileSync(join(repo, ".git", "info", "exclude"), ["# Toolroll: placeholders that hold protected names (flexible-thread.ts)", ...reserved, ""].join("\n"), { mode: 0o644, flag: "wx" });
|
|
164
|
+
}
|
|
165
|
+
export async function prepareFlexibleThread(store, input) {
|
|
166
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
167
|
+
return refuse("not-available");
|
|
168
|
+
const state = stateFolderOf(store);
|
|
169
|
+
if (state === null)
|
|
170
|
+
return refuse("no-state-folder");
|
|
171
|
+
if (!projectRowKnown(store, input.repo))
|
|
172
|
+
return refuse("not-a-project");
|
|
173
|
+
if (!BASE_NAME.test(input.base) || input.base.includes(".."))
|
|
174
|
+
return refuse("base-unknown");
|
|
175
|
+
const inner = input.runner ?? run;
|
|
176
|
+
const read = gitIn(inner, "read");
|
|
177
|
+
let project, objects;
|
|
178
|
+
try {
|
|
179
|
+
project = realpathSync(input.repo);
|
|
180
|
+
({ objects } = await usableRepository(project, read));
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
return refuse("repository-unusable", error instanceof Error ? error.message : undefined);
|
|
184
|
+
}
|
|
185
|
+
const resolved = await read(project, ["rev-parse", "--verify", "--quiet", "--end-of-options", `${input.base}^{commit}`]);
|
|
186
|
+
const baseSha = resolved.stdout.trim();
|
|
187
|
+
if (resolved.code !== 0 || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(baseSha))
|
|
188
|
+
return refuse("base-unknown");
|
|
189
|
+
const id = randomBytes(16).toString("hex");
|
|
190
|
+
const paths = flexibleThreadPaths(state, id);
|
|
191
|
+
const keepRef = flexibleKeepRef(id);
|
|
192
|
+
store.transact(() => {
|
|
193
|
+
store.handle.prepare(`INSERT INTO flexible_thread (id, repo, base_sha, keep_ref, folder, created_by, created_at, state) VALUES (?, ?, ?, ?, ?, ?, ?, 'preparing')`)
|
|
194
|
+
.run(id, input.repo, baseSha, keepRef, paths.folder, input.by, input.now.toISOString());
|
|
195
|
+
});
|
|
196
|
+
const zero = "0".repeat(baseSha.length);
|
|
197
|
+
let madeFolder = false, madeRef = false;
|
|
198
|
+
const build = gitIn(inner, "build");
|
|
199
|
+
try {
|
|
200
|
+
ensureThreadsRoot(state);
|
|
201
|
+
mkdirSync(paths.folder, { mode: 0o700 });
|
|
202
|
+
madeFolder = true;
|
|
203
|
+
for (const folder of [paths.repo, paths.tmp, paths.cache, paths.home])
|
|
204
|
+
mkdirSync(folder, { mode: 0o700 });
|
|
205
|
+
freshInit(paths.repo, flexibleThreadBranch(id));
|
|
206
|
+
const gitdir = join(paths.repo, ".git");
|
|
207
|
+
mkdirSync(join(gitdir, "hooks"), { mode: 0o755 });
|
|
208
|
+
mkdirSync(join(gitdir, "objects", "info"), { recursive: true, mode: 0o755 });
|
|
209
|
+
writeFileSync(join(gitdir, "objects", "info", "alternates"), `${objects}\n`, { mode: 0o644, flag: "wx" });
|
|
210
|
+
const kept = await build(project, ["update-ref", "--no-deref", "-m", "toolroll: keep a Flexible thread's base", keepRef, baseSha, zero]);
|
|
211
|
+
if (kept.code !== 0)
|
|
212
|
+
throw new Error("the project's repository refused the thread's keep-ref");
|
|
213
|
+
madeRef = true;
|
|
214
|
+
const branch = await build(paths.repo, ["update-ref", "--no-deref", `refs/heads/${flexibleThreadBranch(id)}`, baseSha, zero]);
|
|
215
|
+
if (branch.code !== 0)
|
|
216
|
+
throw new Error("the thread's branch couldn't be written");
|
|
217
|
+
const checkout = await build(paths.repo, ["reset", "-q", "--hard", baseSha]);
|
|
218
|
+
if (checkout.code !== 0)
|
|
219
|
+
throw new Error("the thread's files couldn't be checked out");
|
|
220
|
+
reserveProtectedNames(paths.repo);
|
|
221
|
+
const ready = store.transact(() => {
|
|
222
|
+
const moved = store.handle.prepare("UPDATE flexible_thread SET state = 'ready' WHERE id = ? AND state = 'preparing'").run(id);
|
|
223
|
+
if (Number(moved.changes) !== 1)
|
|
224
|
+
return false;
|
|
225
|
+
store.recordAction({ at: input.now.toISOString(), actor: input.by, repo: input.repo, taskId: null, runId: null, source: "policy", action: "flexible thread repository made", outcome: "ready",
|
|
226
|
+
detail: `thread ${id} · base ${baseSha} · ${keepRef}` });
|
|
227
|
+
return true;
|
|
228
|
+
});
|
|
229
|
+
if (!ready)
|
|
230
|
+
throw new Error("the thread's record changed while it was being made");
|
|
231
|
+
return { ok: true, thread: flexibleThread(store, id), paths };
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
const why = error instanceof Error ? error.message : String(error);
|
|
235
|
+
if (madeRef)
|
|
236
|
+
await build(project, ["update-ref", "--no-deref", "-d", keepRef, baseSha]);
|
|
237
|
+
if (madeFolder)
|
|
238
|
+
rmSync(paths.folder, { recursive: true, force: true });
|
|
239
|
+
store.transact(() => {
|
|
240
|
+
store.handle.prepare("UPDATE flexible_thread SET state = 'failed', ended_at = ?, end_detail = ? WHERE id = ? AND state = 'preparing'").run(input.now.toISOString(), why.slice(0, 2000), id);
|
|
241
|
+
});
|
|
242
|
+
return refuse("setup-failed", why);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
export async function removeFlexibleThread(store, input) {
|
|
246
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
247
|
+
return refuse("not-available");
|
|
248
|
+
if (!FLEXIBLE_THREAD_ID.test(input.id))
|
|
249
|
+
return refuse("thread-unknown");
|
|
250
|
+
return withThreadLock(input.id, () => removeLocked(store, input));
|
|
251
|
+
}
|
|
252
|
+
async function removeLocked(store, input) {
|
|
253
|
+
const state = stateFolderOf(store);
|
|
254
|
+
if (state === null)
|
|
255
|
+
return refuse("no-state-folder");
|
|
256
|
+
const thread = flexibleThread(store, input.id);
|
|
257
|
+
if (thread === null)
|
|
258
|
+
return refuse("thread-unknown");
|
|
259
|
+
if (thread.livePid !== null && processMayBeAlive(thread.livePid, true))
|
|
260
|
+
return refuse("thread-running");
|
|
261
|
+
const claimed = store.transact(() => Number(store.handle.prepare("UPDATE flexible_thread SET state = 'removing', live_pid = NULL, live_since = NULL WHERE id = ? AND state IN ('ready', 'removing') AND live_pid IS ?")
|
|
262
|
+
.run(thread.id, thread.livePid).changes) === 1);
|
|
263
|
+
if (!claimed)
|
|
264
|
+
return refuse("thread-not-ready");
|
|
265
|
+
const inner = input.runner ?? run;
|
|
266
|
+
const build = gitIn(inner, "build"), read = gitIn(inner, "read");
|
|
267
|
+
let keepRef = "already-gone";
|
|
268
|
+
let project = null;
|
|
269
|
+
try {
|
|
270
|
+
project = realpathSync(thread.repo);
|
|
271
|
+
recordedCommonDir(project);
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
project = null;
|
|
275
|
+
}
|
|
276
|
+
if (project !== null) {
|
|
277
|
+
const removed = await build(project, ["update-ref", "--no-deref", "-d", thread.keepRef, thread.baseSha]);
|
|
278
|
+
if (removed.code === 0)
|
|
279
|
+
keepRef = "removed";
|
|
280
|
+
else
|
|
281
|
+
keepRef = (await read(project, ["rev-parse", "--verify", "--quiet", "--end-of-options", thread.keepRef])).code === 0 ? "moved" : "already-gone";
|
|
282
|
+
}
|
|
283
|
+
const paths = flexibleThreadPaths(state, thread.id);
|
|
284
|
+
if (thread.folder === paths.folder && ownFolder(paths.root))
|
|
285
|
+
rmSync(paths.folder, { recursive: true, force: true });
|
|
286
|
+
store.transact(() => {
|
|
287
|
+
store.handle.prepare("UPDATE flexible_thread SET state = 'removed', ended_at = ?, end_detail = ? WHERE id = ? AND state = 'removing'")
|
|
288
|
+
.run(input.now.toISOString(), keepRef === "moved" ? "the keep-ref had been moved by someone else and was left as it was" : null, thread.id);
|
|
289
|
+
store.recordAction({ at: input.now.toISOString(), actor: input.by, repo: thread.repo, taskId: null, runId: null, source: "policy", action: "flexible thread repository removed", outcome: "removed",
|
|
290
|
+
detail: `thread ${thread.id} · keep-ref ${keepRef}` });
|
|
291
|
+
});
|
|
292
|
+
return { ok: true, keepRef };
|
|
293
|
+
}
|
|
294
|
+
export const THREAD_CREDENTIAL_PATHS = Object.freeze([
|
|
295
|
+
".ssh", ".aws", ".config/gh", ".git-credentials", ".netrc", ".docker/config.json", ".npmrc", ".pypirc", ".kube", ".gnupg",
|
|
296
|
+
".config/gcloud", ".azure", ".oci", ".config/doctl", ".terraform.d/credentials.tfrc.json", ".cargo/credentials", ".cargo/credentials.toml",
|
|
297
|
+
".gem/credentials", ".m2/settings.xml", ".gradle/gradle.properties", ".config/hub", ".config/glab-cli", ".config/op", ".password-store",
|
|
298
|
+
".vault-token", ".config/git/credentials", ".subversion/auth",
|
|
299
|
+
".claude", ".claude.json", ".codex", ".gemini", ".config/claude",
|
|
300
|
+
...ACP_PROVIDER_IDS.flatMap(id => ACP_AGENTS[id].home),
|
|
301
|
+
]);
|
|
302
|
+
export function threadCredentialPaths(home, env = process.env) {
|
|
303
|
+
const xdg = env["XDG_CONFIG_HOME"];
|
|
304
|
+
return [...new Set(THREAD_CREDENTIAL_PATHS.flatMap(name => [join(home, name), ...(name.startsWith(".config/") && xdg !== undefined && isAbsolute(xdg) ? [join(xdg, name.slice(".config/".length))] : [])]))].sort();
|
|
305
|
+
}
|
|
306
|
+
function folderChanged(paths, recorded, objects) {
|
|
307
|
+
if (recorded !== paths.folder)
|
|
308
|
+
return "its record names another folder";
|
|
309
|
+
for (const folder of [paths.root, paths.folder])
|
|
310
|
+
if (!ownFolder(folder))
|
|
311
|
+
return `${basename(folder)} isn't a private folder of yours`;
|
|
312
|
+
for (const folder of [paths.repo, paths.tmp, paths.cache, paths.home])
|
|
313
|
+
if (grantFolder(folder, false) !== folder)
|
|
314
|
+
return `its ${basename(folder)} folder isn't a real folder`;
|
|
315
|
+
const gitdir = join(paths.repo, ".git");
|
|
316
|
+
try {
|
|
317
|
+
const held = lstatSync(gitdir);
|
|
318
|
+
if (!held.isDirectory() || held.isSymbolicLink() || existsSync(join(gitdir, "commondir")))
|
|
319
|
+
return "its repository isn't a plain one";
|
|
320
|
+
const alternates = join(gitdir, "objects", "info", "alternates");
|
|
321
|
+
const named = lstatSync(alternates);
|
|
322
|
+
if (!named.isFile() || named.isSymbolicLink() || readFileSync(alternates, "utf8") !== `${objects}\n`)
|
|
323
|
+
return "its alternates changed";
|
|
324
|
+
}
|
|
325
|
+
catch {
|
|
326
|
+
return "its repository can't be read";
|
|
327
|
+
}
|
|
328
|
+
for (const { name, dir } of TOP_PROTECTED)
|
|
329
|
+
if (protectedEntry(paths.repo, name, dir) !== "ok")
|
|
330
|
+
return `its ${name} isn't the one Toolroll held`;
|
|
331
|
+
return null;
|
|
332
|
+
}
|
|
333
|
+
function threadReadOnly(paths) {
|
|
334
|
+
const gitdir = join(paths.repo, ".git");
|
|
335
|
+
return [join(gitdir, "config"), join(gitdir, "hooks"), join(gitdir, "objects", "info", "alternates"), join(gitdir, "info", "exclude"), paths.home,
|
|
336
|
+
...TOP_PROTECTED.map(one => join(paths.repo, one.name))].sort();
|
|
337
|
+
}
|
|
338
|
+
export function flexibleThreadFence(store, input) {
|
|
339
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
340
|
+
return refuse("not-available");
|
|
341
|
+
const network = input.network;
|
|
342
|
+
if (!Number.isSafeInteger(network.proxyPort) || network.proxyPort < 1 || network.proxyPort > 65_535 || typeof network.token !== "string" || network.token === "")
|
|
343
|
+
return refuse("network-required");
|
|
344
|
+
const databaseFile = store.databaseFile();
|
|
345
|
+
const state = stateFolderOf(store);
|
|
346
|
+
if (state === null || databaseFile === null)
|
|
347
|
+
return refuse("no-state-folder");
|
|
348
|
+
const thread = flexibleThread(store, input.id);
|
|
349
|
+
if (thread === null)
|
|
350
|
+
return refuse("thread-unknown");
|
|
351
|
+
if (thread.state !== "ready")
|
|
352
|
+
return refuse("thread-not-ready");
|
|
353
|
+
if (!projectRowKnown(store, thread.repo))
|
|
354
|
+
return refuse("not-a-project");
|
|
355
|
+
let project, objects;
|
|
356
|
+
try {
|
|
357
|
+
project = realpathSync(thread.repo);
|
|
358
|
+
const common = recordedCommonDir(project);
|
|
359
|
+
if (!ownObjects(join(common, "objects")))
|
|
360
|
+
throw new Error("objects");
|
|
361
|
+
objects = realpathSync(join(common, "objects"));
|
|
362
|
+
}
|
|
363
|
+
catch {
|
|
364
|
+
return refuse("repository-unusable");
|
|
365
|
+
}
|
|
366
|
+
const paths = flexibleThreadPaths(state, thread.id);
|
|
367
|
+
const changed = folderChanged(paths, thread.folder, objects);
|
|
368
|
+
if (changed !== null)
|
|
369
|
+
return refuse("thread-folder-changed", changed);
|
|
370
|
+
if (inside(project, paths.folder) || inside(paths.folder, project) || project === paths.folder)
|
|
371
|
+
return refuse("repository-unusable");
|
|
372
|
+
const home = real(homedir());
|
|
373
|
+
const credentials = threadCredentialPaths(home);
|
|
374
|
+
const stateDenies = ["", "-wal", "-shm", "-journal", ".coding.sqlite", ".coding.sqlite-wal", ".coding.sqlite-shm"].map(suffix => `${real(databaseFile)}${suffix}`);
|
|
375
|
+
const others = store.listProjects().map(one => real(one.path)).filter(path => path !== project);
|
|
376
|
+
const poolRoots = [paths.root, join(state, "worktrees"), join(state, "coding-worktrees"), join(state, "live-worktrees"), ...store.listWorktrees().map(record => poolRootOf(record.path, record.repo))];
|
|
377
|
+
const boundary = { protectedShell: [...input.storage.names], shell: credentials.filter(path => existsSync(path)), fileTools: [], readOnly: [], lookup: [], homeNames: credentials };
|
|
378
|
+
const made = fenceFor("build", {
|
|
379
|
+
storage: input.storage, databaseFile, worktree: paths.folder, boundary, binding: null, runFolders: runFolders(null), poolRoots, home, policy: 2,
|
|
380
|
+
extra: [project, ...others, ...stateDenies],
|
|
381
|
+
writes: { writes: { subpaths: [paths.repo, paths.tmp, paths.cache], prefixes: [] }, readOnly: threadReadOnly(paths) },
|
|
382
|
+
network: { mode: "allowlist", proxyPort: network.proxyPort, brokerPorts: [], loopback: "proxy-only", socketRoots: [], token: network.token },
|
|
383
|
+
});
|
|
384
|
+
const { keychain: _never, pool, ...rest } = made.fenceGrants;
|
|
385
|
+
const unread = pool === undefined ? undefined : (({ readable: _read, ...held }) => held)(pool);
|
|
386
|
+
const grants = { ...rest, readable: [...rest.readable, objects], exactFiles: [...rest.exactFiles ?? [], objects], noSharedTemp: true, readDenyOnly: [state],
|
|
387
|
+
ownReadBack: [paths.repo, paths.tmp, paths.cache, paths.home],
|
|
388
|
+
...(unread === undefined ? {} : { pool: unread }) };
|
|
389
|
+
return { ok: true, launch: { ...made, fenceGrants: grants }, paths, thread };
|
|
390
|
+
}
|
|
391
|
+
export function flexibleThreadEnv(paths, proxy, base = process.env) {
|
|
392
|
+
const kept = ["PATH", "LANG", "LC_ALL", "LC_CTYPE", "LC_MESSAGES", "TERM", "TZ", "USER", "LOGNAME", "SHELL", "COLORTERM"];
|
|
393
|
+
return {
|
|
394
|
+
...Object.fromEntries(kept.flatMap(name => base[name] === undefined ? [] : [[name, base[name]]])),
|
|
395
|
+
HOME: real(homedir()), TMPDIR: paths.tmp, ...buildCacheEnv(paths.cache),
|
|
396
|
+
GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1",
|
|
397
|
+
...proxy,
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
function outerEnv(env, platform) {
|
|
401
|
+
return platform === "linux" ? { ...env, TMPDIR: tmpdir() } : env;
|
|
402
|
+
}
|
|
403
|
+
function termsProblem(launch) {
|
|
404
|
+
const terms = srtTermsOf(launch.fence, launch.fenceGrants);
|
|
405
|
+
if (terms.keychain === true)
|
|
406
|
+
return "its sandbox would reach the keychain";
|
|
407
|
+
if (terms.network.kind !== "proxy" || terms.network.localServices || terms.network.unixSockets.length > 0)
|
|
408
|
+
return "its sandbox would reach a network other than its proxy";
|
|
409
|
+
return null;
|
|
410
|
+
}
|
|
411
|
+
function spawnProblem(spawned, platform) {
|
|
412
|
+
if (platform === "darwin") {
|
|
413
|
+
const command = spawned.args.at(-1) ?? "";
|
|
414
|
+
if (!command.includes("/usr/bin/sandbox-exec") || !command.includes(SEATBELT_NO_KEYCHAIN))
|
|
415
|
+
return "its sandbox profile doesn't deny the keychain";
|
|
416
|
+
return null;
|
|
417
|
+
}
|
|
418
|
+
try {
|
|
419
|
+
const spec = JSON.parse(spawned.env[SANDBOX_LAUNCH_SPEC] ?? "");
|
|
420
|
+
return spec.terms.keychain === true || spec.terms.network.kind !== "proxy" ? "its sandbox would reach the keychain or the network" : null;
|
|
421
|
+
}
|
|
422
|
+
catch {
|
|
423
|
+
return "its sandbox launch can't be read";
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
async function probeContainment(launch, paths, env, platform) {
|
|
427
|
+
const token = randomBytes(16).toString("hex");
|
|
428
|
+
const readable = join(paths.root, `.probe-${token}`);
|
|
429
|
+
const writable = join(paths.root, `.probe-${token}-written`);
|
|
430
|
+
writeFileSync(readable, token, { mode: 0o600, flag: "wx" });
|
|
431
|
+
try {
|
|
432
|
+
const script = '(: > "$1") 2>/dev/null; cat "$2" 2>/dev/null; echo; echo probe-ran';
|
|
433
|
+
let spawned;
|
|
434
|
+
try {
|
|
435
|
+
spawned = confined("/bin/sh", ["-c", script, "probe", writable, readable], { fence: launch.fence, fenceGrants: launch.fenceGrants, confinement: "required", cwd: paths.repo, temp: paths.tmp });
|
|
436
|
+
}
|
|
437
|
+
catch (error) {
|
|
438
|
+
return error instanceof ContainmentRefusal ? error.message : "the sandbox couldn't be made";
|
|
439
|
+
}
|
|
440
|
+
const problem = spawnProblem(spawned, platform);
|
|
441
|
+
if (problem !== null)
|
|
442
|
+
return problem;
|
|
443
|
+
const ran = await new Promise(done => {
|
|
444
|
+
const child = spawn(spawned.file, spawned.args, { cwd: paths.repo, env: { ...outerEnv(env, platform), ...spawned.env }, stdio: ["ignore", "pipe", "ignore"] });
|
|
445
|
+
let stdout = "";
|
|
446
|
+
const timer = setTimeout(() => child.kill("SIGKILL"), 20_000);
|
|
447
|
+
child.stdout.on("data", chunk => { if (stdout.length < 4096)
|
|
448
|
+
stdout += String(chunk); });
|
|
449
|
+
child.on("error", () => { clearTimeout(timer); done({ code: null, stdout }); });
|
|
450
|
+
child.on("close", code => { clearTimeout(timer); done({ code, stdout }); });
|
|
451
|
+
});
|
|
452
|
+
if (existsSync(writable) || ran.stdout.includes(token))
|
|
453
|
+
return "the sandbox let the probe reach Toolroll's state";
|
|
454
|
+
if (ran.code !== 0 || ran.stdout.trim() !== "probe-ran")
|
|
455
|
+
return "the sandbox didn't start";
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
458
|
+
finally {
|
|
459
|
+
rmSync(readable, { force: true });
|
|
460
|
+
rmSync(writable, { force: true });
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
function withThreadLock(id, work) {
|
|
464
|
+
return withCheckoutLock(real(homedir()), `flexible-thread:${id}`, work);
|
|
465
|
+
}
|
|
466
|
+
export async function flexibleThreadSpawn(store, input, file, args, start, platform = process.platform) {
|
|
467
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
468
|
+
return refuse("not-available");
|
|
469
|
+
if (!FLEXIBLE_THREAD_ID.test(input.id))
|
|
470
|
+
return refuse("thread-unknown");
|
|
471
|
+
return withThreadLock(input.id, () => spawnLocked(store, input, file, args, start, platform));
|
|
472
|
+
}
|
|
473
|
+
async function spawnLocked(store, input, file, args, start, platform) {
|
|
474
|
+
const fenced = flexibleThreadFence(store, input);
|
|
475
|
+
if (!fenced.ok)
|
|
476
|
+
return fenced;
|
|
477
|
+
const { launch, paths } = fenced;
|
|
478
|
+
const terms = termsProblem(launch);
|
|
479
|
+
if (terms !== null)
|
|
480
|
+
return refuse("containment", terms);
|
|
481
|
+
const env = flexibleThreadEnv(paths, input.proxyEnv);
|
|
482
|
+
const probed = await probeContainment(launch, paths, env, platform);
|
|
483
|
+
if (probed !== null)
|
|
484
|
+
return refuse("containment", probed);
|
|
485
|
+
const again = flexibleThreadFence(store, input);
|
|
486
|
+
if (!again.ok)
|
|
487
|
+
return again;
|
|
488
|
+
if (JSON.stringify(again.thread) !== JSON.stringify(fenced.thread))
|
|
489
|
+
return refuse("thread-not-ready", "it changed while the sandbox was checked");
|
|
490
|
+
if (again.thread.livePid !== null && processMayBeAlive(again.thread.livePid, true))
|
|
491
|
+
return refuse("thread-running");
|
|
492
|
+
let spawned;
|
|
493
|
+
try {
|
|
494
|
+
spawned = confined(file, args, { fence: launch.fence, fenceGrants: launch.fenceGrants, confinement: "required", cwd: paths.repo, temp: paths.tmp });
|
|
495
|
+
}
|
|
496
|
+
catch (error) {
|
|
497
|
+
return refuse("containment", error instanceof Error ? error.message : undefined);
|
|
498
|
+
}
|
|
499
|
+
const problem = spawnProblem(spawned, platform);
|
|
500
|
+
if (problem !== null)
|
|
501
|
+
return refuse("containment", problem);
|
|
502
|
+
const pid = start({ file: spawned.file, args: spawned.args, env: { ...outerEnv(env, platform), ...spawned.env }, cwd: paths.repo });
|
|
503
|
+
let registered = false;
|
|
504
|
+
try {
|
|
505
|
+
registered = Number.isSafeInteger(pid) && pid > 0 && store.transact(() => Number(store.handle.prepare("UPDATE flexible_thread SET live_pid = ?, live_since = ? WHERE id = ? AND state = 'ready'").run(pid, new Date().toISOString(), input.id).changes) === 1);
|
|
506
|
+
}
|
|
507
|
+
catch {
|
|
508
|
+
registered = false;
|
|
509
|
+
}
|
|
510
|
+
if (!registered) {
|
|
511
|
+
try {
|
|
512
|
+
if (Number.isSafeInteger(pid) && pid > 0)
|
|
513
|
+
process.kill(-pid, "SIGKILL");
|
|
514
|
+
}
|
|
515
|
+
catch { }
|
|
516
|
+
return refuse("containment", "the agent's process couldn't be registered, so it was stopped");
|
|
517
|
+
}
|
|
518
|
+
return { ok: true, pid, launch };
|
|
519
|
+
}
|
|
520
|
+
export function flexibleThreadCodexProfile(store, input) {
|
|
521
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
522
|
+
return refuse("not-available");
|
|
523
|
+
void store;
|
|
524
|
+
void input;
|
|
525
|
+
return refuse("codex-unsupported");
|
|
526
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { FLEXIBLE_LAPSE_WORDS, FLEXIBLE_LEVEL_WORDS, FLEXIBLE_LEVELS, flexibleTermsWords } from "./flexible.js";
|
|
2
|
+
import { html, joinHtml, postForm } from "./html.js";
|
|
3
|
+
import { acts, btn, disclose, formRow, note, notice, select, settingsSection } from "./server/kit.js";
|
|
4
|
+
import { kitSectionForm } from "./settings-kit.js";
|
|
5
|
+
const ACTION = "/settings/project/flexible";
|
|
6
|
+
const termsList = (terms) => html `<ul class="k-note">${flexibleTermsWords(terms).map(line => html `<li>${line}</li>`)}</ul>`;
|
|
7
|
+
function enableForm(view, label) {
|
|
8
|
+
if ("problem" in view.proposal)
|
|
9
|
+
return note(view.proposal.problem);
|
|
10
|
+
return kitSectionForm({ proof: "project-flexible", action: ACTION, id: "flexible-on", native: true, hidden: { repo: view.repo, action: "enable", digest: view.proposal.digest },
|
|
11
|
+
save: { label }, confirm: "Turn on Flexible",
|
|
12
|
+
body: joinHtml([termsList(view.proposal.terms), note("Turning this on asks for your password, every time.")]) });
|
|
13
|
+
}
|
|
14
|
+
function lowerAndOff(view, terms) {
|
|
15
|
+
const below = terms === null ? [] : FLEXIBLE_LEVELS.slice(0, FLEXIBLE_LEVELS.indexOf(terms.max));
|
|
16
|
+
return joinHtml([
|
|
17
|
+
below.length === 0 ? "" : postForm(ACTION, joinHtml([
|
|
18
|
+
formRow("Highest level", null, select({ id: "flexible-max", name: "max", items: below.map(level => [level, FLEXIBLE_LEVEL_WORDS[level]]), current: below.at(-1), sm: true }), "inline"),
|
|
19
|
+
acts(btn("Lower", { sm: true, type: "submit" })),
|
|
20
|
+
]), { hidden: { repo: view.repo, action: "lower" } }),
|
|
21
|
+
postForm(ACTION, acts(btn("Turn off Flexible", { sm: true, type: "submit" })), { hidden: { repo: view.repo, action: "off" } }),
|
|
22
|
+
]);
|
|
23
|
+
}
|
|
24
|
+
export function flexibleSettingsHtml(view) {
|
|
25
|
+
if (view === undefined)
|
|
26
|
+
return "";
|
|
27
|
+
const standing = view.standing;
|
|
28
|
+
const changer = view.canChange ? null : note("An approver for this project can change this.");
|
|
29
|
+
if (standing.state === "secure") {
|
|
30
|
+
return settingsSection({ id: "flexible", title: "How work starts", state: " · Secure", lead: "Work is planned and approved before it starts.",
|
|
31
|
+
body: changer ?? disclose("Turn on Flexible", enableForm(view, "Turn on Flexible")) });
|
|
32
|
+
}
|
|
33
|
+
if (standing.state === "unreadable") {
|
|
34
|
+
return settingsSection({ id: "flexible", title: "How work starts", state: " · Unavailable", lead: notice("This project's Flexible terms can't be read, so they allow nothing."),
|
|
35
|
+
body: changer ?? lowerAndOff(view, null) });
|
|
36
|
+
}
|
|
37
|
+
if (standing.state === "lapsed") {
|
|
38
|
+
return settingsSection({ id: "flexible", title: "How work starts", state: " · Flexible terms ended", lead: notice(`${FLEXIBLE_LAPSE_WORDS[standing.reason]} No new Flexible threads start.`),
|
|
39
|
+
body: changer ?? joinHtml([disclose("Turn on again", enableForm(view, "Turn on again")), lowerAndOff(view, null)]) });
|
|
40
|
+
}
|
|
41
|
+
return settingsSection({ id: "flexible", title: "How work starts", state: ` · Flexible, up to ${FLEXIBLE_LEVEL_WORDS[standing.terms.max]}`,
|
|
42
|
+
lead: `Agent threads start at once, at ${FLEXIBLE_LEVEL_WORDS[standing.terms.default]}. Turned on by ${standing.signedBy}.`,
|
|
43
|
+
body: joinHtml([disclose("Terms", termsList(standing.terms)), changer ?? lowerAndOff(view, standing.terms)]) });
|
|
44
|
+
}
|