toolroll 0.9.115 → 0.9.117

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +43 -26
  3. package/dist/acp-agents.js +14 -1
  4. package/dist/acp-client.js +19 -1
  5. package/dist/agent-change-check.js +60 -0
  6. package/dist/agent-change-schema.js +19 -0
  7. package/dist/agent-detect.js +11 -1
  8. package/dist/agent-fence.js +39 -10
  9. package/dist/agent-network-request.js +108 -0
  10. package/dist/agent-requests.js +105 -0
  11. package/dist/approval-summary.js +3 -3
  12. package/dist/backup.js +17 -1
  13. package/dist/batch-checks.js +81 -18
  14. package/dist/browser/terminal.js +41 -41
  15. package/dist/browser/workspace.css +2 -2
  16. package/dist/browser/workspace.js +36 -36
  17. package/dist/builder.js +3 -1
  18. package/dist/candidate-materialize.js +119 -0
  19. package/dist/central-enrollment-contract.js +156 -0
  20. package/dist/central-recovery-stage.js +329 -0
  21. package/dist/chat-actions.js +101 -2
  22. package/dist/chat-channel.js +40 -0
  23. package/dist/check-only-standing.js +13 -0
  24. package/dist/check-only.js +25 -13
  25. package/dist/check-recovery-hold.js +199 -0
  26. package/dist/check-recovery-index-schema.js +3 -0
  27. package/dist/check-screenshots.js +83 -0
  28. package/dist/cli.js +125 -6
  29. package/dist/codex-limits.js +4 -0
  30. package/dist/connect-cli.js +257 -11
  31. package/dist/contracts/chat-actions.js +4 -0
  32. package/dist/contracts/console-api.js +15 -4
  33. package/dist/contracts/engine-api.js +344 -2
  34. package/dist/contracts/lead-tools.js +56 -2
  35. package/dist/contracts/provider.js +1 -1
  36. package/dist/contracts/route.js +1 -1
  37. package/dist/contracts/terminal-connection.js +50 -0
  38. package/dist/converse.js +80 -4
  39. package/dist/device-pair.js +280 -0
  40. package/dist/direct-chat-artifacts.js +347 -0
  41. package/dist/direct-chat-catalog.js +311 -0
  42. package/dist/direct-chat-fence.js +96 -0
  43. package/dist/direct-chat-git.js +343 -0
  44. package/dist/direct-chat-laptop.js +19 -0
  45. package/dist/direct-chat-schema.js +181 -0
  46. package/dist/direct-chat-ship.js +861 -0
  47. package/dist/direct-chat-workspace.js +389 -0
  48. package/dist/direct-chat.js +2107 -0
  49. package/dist/doctor.js +1 -1
  50. package/dist/easy-start.js +18 -0
  51. package/dist/egress.js +25 -4
  52. package/dist/engine-chat.js +454 -0
  53. package/dist/engine-reads.js +141 -13
  54. package/dist/exec.js +4 -3
  55. package/dist/flexible-agents.js +8 -16
  56. package/dist/flexible-authority-end.js +2 -0
  57. package/dist/flexible-interactive-schema.js +133 -0
  58. package/dist/flexible-interactive.js +94 -0
  59. package/dist/flexible-session.js +117 -49
  60. package/dist/flexible-ship.js +87 -7
  61. package/dist/flexible-sign-in.js +10 -0
  62. package/dist/flexible-start.js +21 -3
  63. package/dist/flexible-thread.js +2 -3
  64. package/dist/flexible-turns.js +26 -5
  65. package/dist/flexible.js +13 -0
  66. package/dist/flow-triggers.js +13 -4
  67. package/dist/flows-ui.js +54 -20
  68. package/dist/handoff-cli.js +630 -0
  69. package/dist/invoke.js +55 -13
  70. package/dist/lead-contract.js +5 -4
  71. package/dist/lead-doors.js +80 -1
  72. package/dist/lead-progress.js +9 -0
  73. package/dist/lead-tools.js +682 -10
  74. package/dist/lead.js +37 -9
  75. package/dist/live-bus.js +11 -0
  76. package/dist/live-terminal.js +132 -12
  77. package/dist/local-handoff.js +363 -0
  78. package/dist/local-owner-acts.js +264 -2
  79. package/dist/local-owner.js +16 -1
  80. package/dist/multiplayer-handoff.js +528 -0
  81. package/dist/multiplayer-presence.js +471 -0
  82. package/dist/names.js +17 -4
  83. package/dist/needs-you.js +10 -0
  84. package/dist/operate.js +280 -19
  85. package/dist/policy.js +2 -2
  86. package/dist/project-delete-ui.js +18 -11
  87. package/dist/project-delete.js +65 -4
  88. package/dist/project-tools.js +1 -1
  89. package/dist/prompt.js +1 -1
  90. package/dist/provider-connection.js +2 -0
  91. package/dist/provider-home.js +251 -8
  92. package/dist/provider.js +3 -2
  93. package/dist/publish.js +119 -64
  94. package/dist/pull-request-flow.js +35 -14
  95. package/dist/read-executor-worker.js +1 -1
  96. package/dist/read-executor.js +95 -1
  97. package/dist/restore-retirement.js +152 -0
  98. package/dist/result-follow-ups.js +116 -37
  99. package/dist/route-change.js +44 -4
  100. package/dist/scope.js +62 -5
  101. package/dist/serve.js +49 -5
  102. package/dist/server/chat.js +94 -13
  103. package/dist/server/console.css +9 -9
  104. package/dist/server/direct-chat.js +583 -0
  105. package/dist/server/engine-api.js +219 -21
  106. package/dist/server/flows.js +47 -13
  107. package/dist/server/found-repos.js +25 -0
  108. package/dist/server/guards.js +20 -6
  109. package/dist/server/live.js +81 -23
  110. package/dist/server/pages.js +67 -13
  111. package/dist/server/people-tokens.js +47 -6
  112. package/dist/server/remote.js +29 -0
  113. package/dist/server/render-results.js +6 -2
  114. package/dist/server/render-settings.js +4 -2
  115. package/dist/server/render-tasks.js +18 -17
  116. package/dist/server/route-table.js +69 -2
  117. package/dist/server/settings.js +22 -7
  118. package/dist/server/task-views.js +15 -3
  119. package/dist/server/tasks.js +39 -2
  120. package/dist/server/terminals.js +185 -11
  121. package/dist/settings-proofs.js +1 -1
  122. package/dist/spend-report.js +2 -2
  123. package/dist/spend.js +3 -3
  124. package/dist/store.js +600 -59
  125. package/dist/subagent-admin.js +23 -10
  126. package/dist/subagent-backup-schema.js +36 -0
  127. package/dist/subagent-backup.js +92 -0
  128. package/dist/subagent-week.js +2 -2
  129. package/dist/subagent-work.js +70 -47
  130. package/dist/subagents-ui.js +6 -2
  131. package/dist/subagents.js +5 -2
  132. package/dist/subscription-chat.js +36 -5
  133. package/dist/subscription-usage.js +233 -0
  134. package/dist/task-live.js +2 -1
  135. package/dist/teardown-git.js +34 -4
  136. package/dist/terminal-connection.js +159 -0
  137. package/dist/terminal-safety.js +114 -0
  138. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  139. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  140. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  141. package/dist/tui/linux-x64/toolroll-tui +0 -0
  142. package/dist/tui-contract.js +1 -1
  143. package/dist/tui-launch.js +32 -1
  144. package/dist/workspace-identity-schema.js +21 -0
  145. package/package.json +4 -2
@@ -0,0 +1,96 @@
1
+ import { mkdtempSync, realpathSync, rmSync } from "node:fs";
2
+ import { homedir, tmpdir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { fenceFor, FENCE_POLICY_CURRENT, linuxFenceAvailable, macosFenceAvailable, runFolders, taskBoundary, writeAllowlist } from "./agent-fence.js";
5
+ import { proxyEnv, repositoryEcosystems, resolveNetwork, startEgressProxy } from "./egress.js";
6
+ import { readDenyPath } from "./project-sandbox.js";
7
+ import { prepareProtectedStorage, storageRefusalOf } from "./protected-storage.js";
8
+ import { poolRootOf } from "./worktree.js";
9
+ const real = (path) => { try {
10
+ return realpathSync(path);
11
+ }
12
+ catch {
13
+ return path;
14
+ } };
15
+ export function directChatFence(store) {
16
+ return async (input) => {
17
+ if (!macosFenceAvailable() && !linuxFenceAvailable()) {
18
+ return store.unfencedAgentsAllowed() ? { unfenced: true }
19
+ : { problem: "This computer can't confine the chat's agent (no macOS sandbox, no working bubblewrap), so nothing was started." };
20
+ }
21
+ const databaseFile = store.databaseFile();
22
+ if (databaseFile === null || databaseFile === "" || databaseFile === ":memory:")
23
+ return { problem: "Direct Chat has no state folder to fence, so nothing was started." };
24
+ let clone, gitDir, repo;
25
+ try {
26
+ clone = realpathSync(input.clone);
27
+ gitDir = realpathSync(input.gitDir);
28
+ repo = realpathSync(input.repo);
29
+ }
30
+ catch {
31
+ return { problem: "The chat's workspace couldn't be found, so nothing was started." };
32
+ }
33
+ let storage;
34
+ try {
35
+ storage = await prepareProtectedStorage();
36
+ }
37
+ catch (error) {
38
+ return { problem: storageRefusalOf(error)?.message ?? "Toolroll couldn't finish checking other apps' data, so nothing was started." };
39
+ }
40
+ const chats = real(join(input.stateRoot, "direct-chat"));
41
+ const policy = resolveNetwork("claude", store.projectNetwork(input.repo), repositoryEcosystems(input.repo));
42
+ let proxy;
43
+ try {
44
+ proxy = await startEgressProxy(policy.mode === "open" ? { hosts: [], open: true } : { hosts: policy.hosts });
45
+ }
46
+ catch {
47
+ return { problem: "The chat's network proxy couldn't be started, so nothing was started." };
48
+ }
49
+ let temp = null;
50
+ let closed = null;
51
+ const close = () => closed ??= (async () => {
52
+ const failures = [];
53
+ try {
54
+ await proxy.close();
55
+ }
56
+ catch (error) {
57
+ failures.push(`its network proxy didn't close (${error instanceof Error ? error.message : String(error)})`);
58
+ }
59
+ if (temp !== null) {
60
+ try {
61
+ rmSync(temp, { recursive: true, force: true });
62
+ }
63
+ catch (error) {
64
+ failures.push(`its temp folder wasn't removed (${error instanceof Error ? error.message : String(error)})`);
65
+ }
66
+ }
67
+ if (failures.length > 0)
68
+ throw new Error(failures.join("; "));
69
+ })();
70
+ try {
71
+ temp = realpathSync(mkdtempSync(join(tmpdir(), "so-net-")));
72
+ const home = homedir();
73
+ const poolRoots = [join(dirname(databaseFile), "worktrees"), ...store.listWorktrees().map(record => poolRootOf(record.path, record.repo))];
74
+ const boundary = taskBoundary({ worktree: clone, provider: "claude", binding: null, policy: FENCE_POLICY_CURRENT, storage });
75
+ const allowed = writeAllowlist({ provider: "claude", home, worktree: clone, binding: null, launchFolder: temp, cache: null });
76
+ const gitReadOnly = ["config", "hooks", "info"].map(name => join(gitDir, name));
77
+ const made = fenceFor("build", {
78
+ databaseFile, worktree: clone, boundary, binding: null, runFolders: runFolders(temp), poolRoots, storage, policy: FENCE_POLICY_CURRENT, provider: "claude",
79
+ extra: [repo, ...allowed.deny],
80
+ readDeny: store.projectSandbox(input.repo).readDeny.map(one => readDenyPath(one, home)),
81
+ writes: { writes: { subpaths: [...allowed.writes.subpaths, gitDir], prefixes: allowed.writes.prefixes }, readOnly: [...allowed.readOnly, ...gitReadOnly] },
82
+ network: { mode: "allowlist", proxyPort: proxy.port, brokerPorts: [], loopback: policy.loopback, socketRoots: [clone, temp], token: proxy.secret },
83
+ });
84
+ const grants = { ...made.fenceGrants, readDenyOnly: [...made.fenceGrants.readDenyOnly ?? [], chats],
85
+ readable: [...made.fenceGrants.readable, clone, gitDir], exactFiles: [...made.fenceGrants.exactFiles ?? [], clone, gitDir] };
86
+ return { launch: { ...made, fenceGrants: grants }, temp, env: { ...proxyEnv(proxy, policy.loopback), TMPDIR: temp, TMP: temp, TEMP: temp, CLAUDE_CODE_TMPDIR: temp }, close };
87
+ }
88
+ catch (error) {
89
+ try {
90
+ await close();
91
+ }
92
+ catch { }
93
+ return { problem: `The chat's fence couldn't be made, so nothing was started: ${error instanceof Error ? error.message : String(error)}` };
94
+ }
95
+ };
96
+ }
@@ -0,0 +1,343 @@
1
+ import { execFile, execFileSync } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
6
+ import { promisify } from "node:util";
7
+ import { run } from "./exec.js";
8
+ import { ENV, ENV_ALLOWLIST } from "./remote-main.js";
9
+ import { checkoutGit, refusal, TEARDOWN_FLAGS, viewedGitSync } from "./teardown-git.js";
10
+ const execFileAsync = promisify(execFile);
11
+ const EXTRA_DIRECT_CHAT_GIT_FLAGS = [
12
+ ...TEARDOWN_FLAGS,
13
+ "-c", "diff.external=",
14
+ "-c", "core.attributesfile=/dev/null",
15
+ "-c", "transfer.fsckObjects=true",
16
+ ];
17
+ function cleanGitEnv(extra) {
18
+ return {
19
+ PATH: process.env["PATH"] ?? "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin",
20
+ HOME: homedir(),
21
+ GIT_CONFIG_NOSYSTEM: "1",
22
+ GIT_CONFIG_GLOBAL: "/dev/null",
23
+ GIT_TERMINAL_PROMPT: "0",
24
+ ...extra,
25
+ };
26
+ }
27
+ export function sha256Buffer(bytes) {
28
+ return createHash("sha256").update(bytes).digest("hex");
29
+ }
30
+ export function sha256File(path) {
31
+ return sha256Buffer(readFileSync(path));
32
+ }
33
+ export function pinnedConfigBackupPath(realGitDir) {
34
+ return `${realGitDir}.pinned-config`;
35
+ }
36
+ function hasCommonDirEntry(realGitDir) {
37
+ try {
38
+ lstatSync(join(realGitDir, "commondir"));
39
+ return true;
40
+ }
41
+ catch (error) {
42
+ return error.code !== "ENOENT";
43
+ }
44
+ }
45
+ export function assertManagedClonePath(stateRoot, clonePath) {
46
+ if (!clonePath || clonePath.trim() === "") {
47
+ return { ok: false, error: "This chat has no isolated clone workspace (read-only)." };
48
+ }
49
+ const clonesRoot = join(stateRoot, "direct-chat", "clones");
50
+ if (!existsSync(clonesRoot) || !existsSync(clonePath)) {
51
+ return { ok: false, error: "This chat's isolated clone workspace does not exist." };
52
+ }
53
+ try {
54
+ const st = lstatSync(clonePath);
55
+ if (!st.isDirectory() || st.isSymbolicLink()) {
56
+ return { ok: false, error: "Chat workspace must be a real directory, not a symlink." };
57
+ }
58
+ const realRoot = realpathSync(clonesRoot);
59
+ const realClone = realpathSync(clonePath);
60
+ const rel = relative(realRoot, realClone);
61
+ if (rel === "" || rel === ".." || rel.startsWith(`..${"/"}`) || rel.startsWith(`..${"\\"}`) || isAbsolute(rel)) {
62
+ return { ok: false, error: "Chat workspace path is outside Toolroll's isolated clones folder." };
63
+ }
64
+ return { ok: true, realClone };
65
+ }
66
+ catch {
67
+ return { ok: false, error: "Could not verify chat workspace location." };
68
+ }
69
+ }
70
+ export function assertTrustedCloneGit(binding) {
71
+ const managed = assertManagedClonePath(binding.stateRoot, binding.clonePath);
72
+ if (!managed.ok)
73
+ return managed;
74
+ if (!binding.gitDir || !binding.configSha256) {
75
+ return { ok: false, error: "Chat clone is missing its trusted separate git-dir or pinned config hash." };
76
+ }
77
+ const gitDirsRoot = join(binding.stateRoot, "direct-chat", "gitdirs");
78
+ if (!existsSync(gitDirsRoot) || !existsSync(binding.gitDir)) {
79
+ return { ok: false, error: "Chat clone's separate git-dir is missing." };
80
+ }
81
+ try {
82
+ const gdStat = lstatSync(binding.gitDir);
83
+ if (!gdStat.isDirectory() || gdStat.isSymbolicLink()) {
84
+ return { ok: false, error: "Chat git-dir must be a real directory, not a symlink." };
85
+ }
86
+ const realGdRoot = realpathSync(gitDirsRoot);
87
+ const realGitDir = realpathSync(binding.gitDir);
88
+ const relGd = relative(realGdRoot, realGitDir);
89
+ if (relGd === "" || relGd === ".." || relGd.startsWith(`..${"/"}`) || relGd.startsWith(`..${"\\"}`) || isAbsolute(relGd)) {
90
+ return { ok: false, error: "Chat git-dir is outside Toolroll's managed gitdirs folder." };
91
+ }
92
+ if (hasCommonDirEntry(realGitDir)) {
93
+ return { ok: false, error: "Chat git-dir contains an unexpected commondir redirect; repair the workspace git binding to continue." };
94
+ }
95
+ const dotGit = join(managed.realClone, ".git");
96
+ const dgStat = lstatSync(dotGit);
97
+ if (!dgStat.isFile() || dgStat.isSymbolicLink()) {
98
+ return { ok: false, error: "Chat clone's .git pointer was replaced or tampered with; repair the workspace git binding to continue." };
99
+ }
100
+ const pointerText = readFileSync(dotGit, "utf8").trim();
101
+ const match = /^gitdir:\s*(.+)$/.exec(pointerText);
102
+ if (match === null) {
103
+ return { ok: false, error: "Chat clone's .git pointer is malformed; repair the workspace git binding to continue." };
104
+ }
105
+ const pointedReal = realpathSync(resolve(managed.realClone, match[1].trim()));
106
+ if (pointedReal !== realGitDir) {
107
+ return { ok: false, error: "Chat clone's .git pointer no longer matches Toolroll's trusted git-dir; repair the workspace git binding to continue." };
108
+ }
109
+ const configPath = join(realGitDir, "config");
110
+ const cfgStat = lstatSync(configPath);
111
+ if (!cfgStat.isFile() || cfgStat.isSymbolicLink()) {
112
+ return { ok: false, error: "Chat git config was replaced with a non-file; repair the workspace git binding to continue." };
113
+ }
114
+ if (sha256File(configPath) !== binding.configSha256) {
115
+ return { ok: false, error: "Chat git config changed since clone creation; repair the workspace git binding to continue." };
116
+ }
117
+ return { ok: true, realClone: managed.realClone, realGitDir };
118
+ }
119
+ catch {
120
+ return { ok: false, error: "Could not verify chat git-dir binding." };
121
+ }
122
+ }
123
+ export function repairCloneGitBinding(binding) {
124
+ const managed = assertManagedClonePath(binding.stateRoot, binding.clonePath);
125
+ if (!managed.ok)
126
+ return managed;
127
+ if (!binding.gitDir || !binding.configSha256) {
128
+ return { ok: false, error: "Chat clone has no recorded trusted git-dir or pinned config hash." };
129
+ }
130
+ const gitDirsRoot = join(binding.stateRoot, "direct-chat", "gitdirs");
131
+ if (!existsSync(gitDirsRoot) || !existsSync(binding.gitDir)) {
132
+ return { ok: false, error: "Chat clone's separate git-dir is missing." };
133
+ }
134
+ try {
135
+ const gdStat = lstatSync(binding.gitDir);
136
+ if (!gdStat.isDirectory() || gdStat.isSymbolicLink()) {
137
+ return { ok: false, error: "Chat git-dir must be a real directory, not a symlink." };
138
+ }
139
+ const realGdRoot = realpathSync(gitDirsRoot);
140
+ const realGitDir = realpathSync(binding.gitDir);
141
+ const relGd = relative(realGdRoot, realGitDir);
142
+ if (relGd === "" || relGd === ".." || relGd.startsWith(`..${"/"}`) || relGd.startsWith(`..${"\\"}`) || isAbsolute(relGd)) {
143
+ return { ok: false, error: "Chat git-dir is outside Toolroll's managed gitdirs folder." };
144
+ }
145
+ const backupPath = pinnedConfigBackupPath(realGitDir);
146
+ const backupStat = lstatSync(backupPath);
147
+ if (!backupStat.isFile() || backupStat.isSymbolicLink()) {
148
+ return { ok: false, error: "Pinned git config backup is missing or invalid; start a new chat instead." };
149
+ }
150
+ const pinnedBytes = readFileSync(backupPath);
151
+ if (sha256Buffer(pinnedBytes) !== binding.configSha256) {
152
+ return { ok: false, error: "Pinned git config backup does not match the recorded hash; start a new chat instead." };
153
+ }
154
+ const commonDirPath = join(realGitDir, "commondir");
155
+ if (hasCommonDirEntry(realGitDir)) {
156
+ const cdStat = lstatSync(commonDirPath);
157
+ if (cdStat.isDirectory() && !cdStat.isSymbolicLink()) {
158
+ return { ok: false, error: "Chat git-dir has an unexpected commondir directory; start a new chat instead." };
159
+ }
160
+ unlinkSync(commonDirPath);
161
+ }
162
+ const configPath = join(realGitDir, "config");
163
+ try {
164
+ const cfgStat = lstatSync(configPath);
165
+ if (cfgStat.isDirectory() && !cfgStat.isSymbolicLink()) {
166
+ return { ok: false, error: "Chat git config was replaced with a directory; start a new chat instead." };
167
+ }
168
+ unlinkSync(configPath);
169
+ }
170
+ catch (error) {
171
+ if (error.code !== "ENOENT")
172
+ throw error;
173
+ }
174
+ writeFileSync(configPath, pinnedBytes, { mode: 0o600 });
175
+ const dotGit = join(managed.realClone, ".git");
176
+ try {
177
+ const dgStat = lstatSync(dotGit);
178
+ if (dgStat.isDirectory() && !dgStat.isSymbolicLink()) {
179
+ return { ok: false, error: "Chat clone's .git was replaced with a directory; start a new chat instead." };
180
+ }
181
+ unlinkSync(dotGit);
182
+ }
183
+ catch (error) {
184
+ if (error.code !== "ENOENT")
185
+ throw error;
186
+ }
187
+ writeFileSync(dotGit, `gitdir: ${realGitDir}\n`, { mode: 0o600 });
188
+ const recheck = assertTrustedCloneGit(binding);
189
+ if (!recheck.ok)
190
+ return recheck;
191
+ return { ok: true };
192
+ }
193
+ catch (error) {
194
+ return { ok: false, error: `Could not repair chat git binding: ${error instanceof Error ? error.message : String(error)}` };
195
+ }
196
+ }
197
+ const MAIN_GIT_BUFFER = 16 * 1024 * 1024;
198
+ export function runHardenedMainGit(args, repoCwd, options = {}) {
199
+ let ran;
200
+ try {
201
+ ran = viewedGitSync(repoCwd, args, { maxBuffer: MAIN_GIT_BUFFER, binding: { repo: repoCwd }, timeoutMs: 120_000, ...(options.write === true ? { write: true } : {}) });
202
+ }
203
+ catch (error) {
204
+ throw Object.assign(new Error(`Toolroll won't run git in this project: ${error instanceof Error ? error.message : String(error)}`), { status: null });
205
+ }
206
+ if (ran.status !== 0) {
207
+ const said = ran.stderr.trim().split("\n").find(line => line.trim() !== "") ?? `git ${args[0] ?? ""} failed`;
208
+ throw Object.assign(new Error(said), { status: ran.status });
209
+ }
210
+ return ran.stdout;
211
+ }
212
+ export async function runHardenedMainGitAsync(args, repoCwd) {
213
+ const ran = await checkoutGit(run, "read", { repo: repoCwd })("git", [...args], { cwd: repoCwd, envAllowlist: ENV_ALLOWLIST, env: { ...ENV }, maxBuffer: MAIN_GIT_BUFFER, timeoutMs: 120_000 });
214
+ const refused = refusal(ran);
215
+ if (refused !== null)
216
+ throw new Error(`Toolroll won't run git in this project: ${refused}`);
217
+ if (ran.code !== 0)
218
+ throw new Error(ran.stderr.trim().split("\n").find(line => line.trim() !== "") ?? `git ${args[0] ?? ""} failed`);
219
+ return ran.stdout;
220
+ }
221
+ const CLONE_SOURCE_FLAGS = ["-c", "core.alternateRefsCommand=", "-c", "uploadpack.packObjectsHook=", "-c", "protocol.file.allow=always"];
222
+ export function runTrustedCloneGit(binding, args, input, extraEnv) {
223
+ const verified = assertTrustedCloneGit(binding);
224
+ if (!verified.ok) {
225
+ throw new Error(verified.error);
226
+ }
227
+ return execFileSync("git", [
228
+ ...EXTRA_DIRECT_CHAT_GIT_FLAGS,
229
+ `--git-dir=${verified.realGitDir}`,
230
+ `--work-tree=${verified.realClone}`,
231
+ ...args,
232
+ ], {
233
+ cwd: verified.realClone,
234
+ encoding: "utf8",
235
+ env: cleanGitEnv({ GIT_COMMON_DIR: verified.realGitDir, ...(extraEnv ?? {}) }),
236
+ input,
237
+ maxBuffer: 16 * 1024 * 1024,
238
+ stdio: [input === undefined ? "ignore" : "pipe", "pipe", "pipe"],
239
+ });
240
+ }
241
+ function pinCloneGitConfig(realGitDir) {
242
+ const configPath = join(realGitDir, "config");
243
+ try {
244
+ chmodSync(configPath, 0o600);
245
+ }
246
+ catch {
247
+ }
248
+ const configBytes = readFileSync(configPath);
249
+ writeFileSync(pinnedConfigBackupPath(realGitDir), configBytes, { mode: 0o600 });
250
+ return sha256Buffer(configBytes);
251
+ }
252
+ export function cloneIsolatedRepo(input) {
253
+ mkdirSync(dirname(input.clonePath), { recursive: true, mode: 0o700 });
254
+ mkdirSync(dirname(input.gitDir), { recursive: true, mode: 0o700 });
255
+ const baseSha = runHardenedMainGit(["rev-parse", "HEAD"], input.repo).trim();
256
+ let mainDirtyFiles = [];
257
+ try {
258
+ const status = runHardenedMainGit(["status", "--porcelain"], input.repo);
259
+ mainDirtyFiles = status
260
+ .split("\n")
261
+ .map(line => line.slice(3).trim())
262
+ .filter(Boolean)
263
+ .slice(0, 20);
264
+ }
265
+ catch {
266
+ mainDirtyFiles = [];
267
+ }
268
+ execFileSync("git", [
269
+ ...EXTRA_DIRECT_CHAT_GIT_FLAGS,
270
+ ...CLONE_SOURCE_FLAGS,
271
+ "clone", "--local",
272
+ `--separate-git-dir=${input.gitDir}`,
273
+ "--",
274
+ input.repo,
275
+ input.clonePath,
276
+ ], {
277
+ cwd: dirname(input.clonePath),
278
+ encoding: "utf8",
279
+ env: cleanGitEnv(),
280
+ maxBuffer: 8 * 1024 * 1024,
281
+ stdio: ["ignore", "pipe", "pipe"],
282
+ });
283
+ const realClone = realpathSync(input.clonePath);
284
+ const realGitDir = realpathSync(input.gitDir);
285
+ const cloneEnv = cleanGitEnv({ GIT_COMMON_DIR: realGitDir });
286
+ try {
287
+ execFileSync("git", [...EXTRA_DIRECT_CHAT_GIT_FLAGS, `--git-dir=${realGitDir}`, `--work-tree=${realClone}`, "remote", "remove", "origin"], { cwd: realClone, encoding: "utf8", env: cloneEnv, stdio: ["ignore", "pipe", "pipe"] });
288
+ }
289
+ catch {
290
+ }
291
+ execFileSync("git", [...EXTRA_DIRECT_CHAT_GIT_FLAGS, `--git-dir=${realGitDir}`, `--work-tree=${realClone}`, "checkout", "-b", input.branch, baseSha], { cwd: realClone, encoding: "utf8", env: cloneEnv, stdio: ["ignore", "pipe", "pipe"] });
292
+ const configSha256 = pinCloneGitConfig(realGitDir);
293
+ return { baseSha, gitDir: realGitDir, configSha256, mainDirtyFiles };
294
+ }
295
+ export async function cloneIsolatedRepoAsync(input) {
296
+ mkdirSync(dirname(input.clonePath), { recursive: true, mode: 0o700 });
297
+ mkdirSync(dirname(input.gitDir), { recursive: true, mode: 0o700 });
298
+ const baseSha = (await runHardenedMainGitAsync(["rev-parse", "HEAD"], input.repo)).trim();
299
+ let mainDirtyFiles = [];
300
+ try {
301
+ const status = await runHardenedMainGitAsync(["status", "--porcelain"], input.repo);
302
+ mainDirtyFiles = status
303
+ .split("\n")
304
+ .map(line => line.slice(3).trim())
305
+ .filter(Boolean)
306
+ .slice(0, 20);
307
+ }
308
+ catch {
309
+ mainDirtyFiles = [];
310
+ }
311
+ await execFileAsync("git", [
312
+ ...EXTRA_DIRECT_CHAT_GIT_FLAGS,
313
+ ...CLONE_SOURCE_FLAGS,
314
+ "clone", "--local",
315
+ `--separate-git-dir=${input.gitDir}`,
316
+ "--",
317
+ input.repo,
318
+ input.clonePath,
319
+ ], {
320
+ cwd: dirname(input.clonePath),
321
+ encoding: "utf8",
322
+ env: cleanGitEnv(),
323
+ maxBuffer: 8 * 1024 * 1024,
324
+ });
325
+ const realClone = realpathSync(input.clonePath);
326
+ const realGitDir = realpathSync(input.gitDir);
327
+ const cloneEnv = cleanGitEnv({ GIT_COMMON_DIR: realGitDir });
328
+ try {
329
+ await execFileAsync("git", [...EXTRA_DIRECT_CHAT_GIT_FLAGS, `--git-dir=${realGitDir}`, `--work-tree=${realClone}`, "remote", "remove", "origin"], { cwd: realClone, encoding: "utf8", env: cloneEnv });
330
+ }
331
+ catch {
332
+ }
333
+ await execFileAsync("git", [...EXTRA_DIRECT_CHAT_GIT_FLAGS, `--git-dir=${realGitDir}`, `--work-tree=${realClone}`, "checkout", "-b", input.branch, baseSha], { cwd: realClone, encoding: "utf8", env: cloneEnv });
334
+ const configSha256 = pinCloneGitConfig(realGitDir);
335
+ return { baseSha, gitDir: realGitDir, configSha256, mainDirtyFiles };
336
+ }
337
+ export function fetchTrustedSnapshotIntoMainRepo(input) {
338
+ const verified = assertTrustedCloneGit(input.binding);
339
+ if (!verified.ok) {
340
+ throw new Error(verified.error);
341
+ }
342
+ runHardenedMainGit(["fetch", "--no-tags", "--no-write-fetch-head", verified.realGitDir, `${input.candidateSha}:${input.targetRef}`], input.repo, { write: true });
343
+ }
@@ -0,0 +1,19 @@
1
+ import { laptopShipProblem } from "./flexible-laptop.js";
2
+ export function directChatShipSealAllowed(store, input) {
3
+ const match = /^dc-([0-9a-f]{32})$/.exec(input.taskId);
4
+ if (match === null)
5
+ return false;
6
+ const row = store.handle
7
+ .prepare("SELECT approved_by, state, candidate_sha, proof, local_generation FROM direct_chat_ship WHERE id = ?")
8
+ .get(match[1]);
9
+ if (!row)
10
+ return false;
11
+ if (row["approved_by"] !== input.by
12
+ || row["state"] !== "imported"
13
+ || row["proof"] !== "local-owner"
14
+ || row["candidate_sha"] !== input.candidate
15
+ || typeof row["local_generation"] !== "number") {
16
+ return false;
17
+ }
18
+ return laptopShipProblem(store, { owner: input.by, localGeneration: row["local_generation"] }) === null;
19
+ }
@@ -0,0 +1,181 @@
1
+ export const V181_THREAD_SCHEMA = `
2
+ CREATE TABLE IF NOT EXISTS direct_chat_thread (
3
+ id TEXT PRIMARY KEY,
4
+ owner TEXT NOT NULL,
5
+ local_generation INTEGER,
6
+ account_generation INTEGER NOT NULL,
7
+ create_request_id TEXT,
8
+ title TEXT NOT NULL,
9
+ repo TEXT NOT NULL,
10
+ clone_path TEXT NOT NULL,
11
+ branch TEXT NOT NULL,
12
+ base_sha TEXT NOT NULL,
13
+ provider TEXT NOT NULL CHECK (provider IN ('claude', 'codex', 'gemini')),
14
+ model_id TEXT NOT NULL,
15
+ provider_session_id TEXT,
16
+ main_dirty_files TEXT,
17
+ archived_at TEXT,
18
+ created_at TEXT NOT NULL,
19
+ updated_at TEXT NOT NULL
20
+ );
21
+ `;
22
+ export const V181_TURN_SCHEMA = `
23
+ CREATE TABLE IF NOT EXISTS direct_chat_turn (
24
+ id TEXT PRIMARY KEY,
25
+ thread_id TEXT NOT NULL REFERENCES direct_chat_thread(id) ON DELETE CASCADE,
26
+ seq INTEGER NOT NULL,
27
+ request_id TEXT,
28
+ user_prompt TEXT NOT NULL,
29
+ switched_from_provider TEXT,
30
+ log_path TEXT NOT NULL,
31
+ stderr_path TEXT NOT NULL,
32
+ byte_offset INTEGER NOT NULL DEFAULT 0,
33
+ pid INTEGER,
34
+ start_identity TEXT,
35
+ pgid INTEGER,
36
+ boot_id TEXT,
37
+ status TEXT NOT NULL CHECK (status IN ('running', 'completed', 'stopped', 'failed', 'interrupted')),
38
+ assistant_text TEXT NOT NULL DEFAULT '',
39
+ error_text TEXT,
40
+ created_at TEXT NOT NULL,
41
+ finished_at TEXT,
42
+ UNIQUE (thread_id, seq)
43
+ );
44
+ `;
45
+ export const V181_TOOL_SCHEMA = `
46
+ CREATE TABLE IF NOT EXISTS direct_chat_tool (
47
+ id TEXT NOT NULL,
48
+ turn_id TEXT NOT NULL REFERENCES direct_chat_turn(id) ON DELETE CASCADE,
49
+ ordinal INTEGER NOT NULL,
50
+ name TEXT NOT NULL,
51
+ detail TEXT NOT NULL DEFAULT '',
52
+ status TEXT NOT NULL CHECK (status IN ('running', 'done', 'error')),
53
+ updated_at TEXT NOT NULL,
54
+ PRIMARY KEY (turn_id, id)
55
+ );
56
+ `;
57
+ export const V181_INDEX_SCHEMA = `
58
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_direct_chat_thread_create_req
59
+ ON direct_chat_thread(owner, create_request_id)
60
+ WHERE create_request_id IS NOT NULL;
61
+ CREATE INDEX IF NOT EXISTS idx_direct_chat_thread_owner_updated
62
+ ON direct_chat_thread(owner, updated_at DESC);
63
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_direct_chat_turn_req
64
+ ON direct_chat_turn(thread_id, request_id)
65
+ WHERE request_id IS NOT NULL;
66
+ CREATE INDEX IF NOT EXISTS idx_direct_chat_turn_running
67
+ ON direct_chat_turn(status)
68
+ WHERE status = 'running';
69
+ `;
70
+ export const V181_SCHEMA = `${V181_THREAD_SCHEMA}${V181_TURN_SCHEMA}${V181_TOOL_SCHEMA}${V181_INDEX_SCHEMA}`;
71
+ export const V181_TABLES = Object.freeze([
72
+ "direct_chat_thread",
73
+ "direct_chat_turn",
74
+ "direct_chat_tool",
75
+ ]);
76
+ export const V181_TABLE_DDLS = Object.freeze({
77
+ direct_chat_thread: V181_THREAD_SCHEMA,
78
+ direct_chat_turn: V181_TURN_SCHEMA,
79
+ direct_chat_tool: V181_TOOL_SCHEMA,
80
+ });
81
+ export const V181_STEPS = Object.freeze(["direct-chat-tables"]);
82
+ export const V182_ARTIFACT_SCHEMA = `
83
+ CREATE TABLE IF NOT EXISTS direct_chat_artifact (
84
+ id TEXT PRIMARY KEY,
85
+ thread_id TEXT NOT NULL REFERENCES direct_chat_thread(id) ON DELETE CASCADE,
86
+ turn_id TEXT REFERENCES direct_chat_turn(id) ON DELETE CASCADE,
87
+ kind TEXT NOT NULL CHECK (kind IN ('output', 'attachment')),
88
+ filename TEXT NOT NULL,
89
+ mime_type TEXT NOT NULL,
90
+ byte_size INTEGER NOT NULL,
91
+ sha256 TEXT NOT NULL,
92
+ storage_path TEXT NOT NULL,
93
+ source_path TEXT,
94
+ created_at TEXT NOT NULL
95
+ );
96
+ `;
97
+ export const V182_SHIP_SCHEMA = `
98
+ CREATE TABLE IF NOT EXISTS direct_chat_ship (
99
+ id TEXT PRIMARY KEY,
100
+ thread_id TEXT NOT NULL REFERENCES direct_chat_thread(id) ON DELETE CASCADE,
101
+ seq INTEGER NOT NULL,
102
+ repo TEXT NOT NULL,
103
+ mode TEXT NOT NULL CHECK (mode IN ('ship', 'keep-branch')),
104
+ base_sha TEXT NOT NULL,
105
+ candidate_sha TEXT NOT NULL,
106
+ branch TEXT NOT NULL,
107
+ terms_json TEXT NOT NULL,
108
+ approved_by TEXT NOT NULL,
109
+ approved_generation INTEGER NOT NULL,
110
+ local_generation INTEGER,
111
+ proof TEXT NOT NULL CHECK (proof IN ('password-now', 'solo-session', 'local-owner')),
112
+ state TEXT NOT NULL CHECK (state IN ('kept', 'imported', 'armed', 'completed', 'merging', 'merged', 'cancelled', 'failed')),
113
+ task_id TEXT,
114
+ scope_digest TEXT,
115
+ pr_url TEXT,
116
+ detail TEXT,
117
+ created_at TEXT NOT NULL,
118
+ state_at TEXT NOT NULL,
119
+ UNIQUE (thread_id, seq)
120
+ );
121
+ `;
122
+ export const V182_INDEX_SCHEMA = `
123
+ CREATE INDEX IF NOT EXISTS idx_direct_chat_artifact_thread
124
+ ON direct_chat_artifact(thread_id, created_at ASC);
125
+ CREATE INDEX IF NOT EXISTS idx_direct_chat_artifact_turn
126
+ ON direct_chat_artifact(turn_id)
127
+ WHERE turn_id IS NOT NULL;
128
+ CREATE INDEX IF NOT EXISTS idx_direct_chat_ship_thread
129
+ ON direct_chat_ship(thread_id, seq DESC);
130
+ CREATE INDEX IF NOT EXISTS idx_direct_chat_ship_active
131
+ ON direct_chat_ship(state)
132
+ WHERE state IN ('armed', 'completed', 'merging');
133
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_direct_chat_ship_task
134
+ ON direct_chat_ship(task_id)
135
+ WHERE task_id IS NOT NULL;
136
+ `;
137
+ export const V182_SCHEMA = `${V182_ARTIFACT_SCHEMA}${V182_SHIP_SCHEMA}${V182_INDEX_SCHEMA}`;
138
+ export const V182_TABLES = Object.freeze([
139
+ "direct_chat_artifact",
140
+ "direct_chat_ship",
141
+ ]);
142
+ export const V182_TABLE_DDLS = Object.freeze({
143
+ direct_chat_artifact: V182_ARTIFACT_SCHEMA,
144
+ direct_chat_ship: V182_SHIP_SCHEMA,
145
+ });
146
+ export const V182_STEPS = Object.freeze(["direct-chat-phase1b-tables"]);
147
+ export const V183_ADDED_COLUMNS = Object.freeze({
148
+ direct_chat_thread: {
149
+ git_dir: { definition: "TEXT" },
150
+ config_sha256: { definition: "TEXT" },
151
+ diff_cache_json: { definition: "TEXT" },
152
+ is_legacy: { definition: "INTEGER NOT NULL DEFAULT 0" },
153
+ },
154
+ direct_chat_turn: {
155
+ stop_requested_at: { definition: "TEXT" },
156
+ },
157
+ direct_chat_ship: {
158
+ merge_token: { definition: "TEXT" },
159
+ merge_reserved_at: { definition: "TEXT" },
160
+ },
161
+ });
162
+ export const V181_REQUIRED_COLUMNS = Object.freeze({
163
+ direct_chat_thread: ["id", "owner", "local_generation", "account_generation", "create_request_id", "title", "repo", "clone_path", "branch", "base_sha", "provider", "model_id", "provider_session_id", "main_dirty_files", "archived_at", "created_at", "updated_at"],
164
+ direct_chat_turn: ["id", "thread_id", "seq", "request_id", "user_prompt", "switched_from_provider", "log_path", "stderr_path", "byte_offset", "pid", "start_identity", "pgid", "boot_id", "status", "assistant_text", "error_text", "created_at", "finished_at"],
165
+ direct_chat_tool: ["id", "turn_id", "ordinal", "name", "detail", "status", "updated_at"],
166
+ });
167
+ export const V182_REQUIRED_COLUMNS = Object.freeze({
168
+ direct_chat_artifact: ["id", "thread_id", "turn_id", "kind", "filename", "mime_type", "byte_size", "sha256", "storage_path", "source_path", "created_at"],
169
+ direct_chat_ship: ["id", "thread_id", "seq", "repo", "mode", "base_sha", "candidate_sha", "branch", "terms_json", "approved_by", "approved_generation", "local_generation", "proof", "state", "task_id", "scope_digest", "pr_url", "detail", "created_at", "state_at"],
170
+ });
171
+ export const V183_STEPS = Object.freeze(["direct-chat-hardening-columns"]);
172
+ export const V184_ADDED_COLUMNS = Object.freeze({
173
+ direct_chat_thread: {
174
+ effort: { definition: "TEXT NOT NULL DEFAULT ''" },
175
+ usage_json: { definition: "TEXT" },
176
+ },
177
+ direct_chat_turn: {
178
+ usage_json: { definition: "TEXT" },
179
+ },
180
+ });
181
+ export const V184_STEPS = Object.freeze(["direct-chat-effort-usage-columns"]);