toolroll 0.9.116 → 0.9.118

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 (136) hide show
  1. package/CHANGELOG.md +46 -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 +93 -16
  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 +12 -2
  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/coding-context.js +16 -2
  31. package/dist/coding-provider.js +7 -3
  32. package/dist/coding-workspace.js +5 -5
  33. package/dist/connect-cli.js +257 -11
  34. package/dist/contracts/chat-actions.js +4 -0
  35. package/dist/contracts/console-api.js +14 -3
  36. package/dist/contracts/engine-api.js +331 -2
  37. package/dist/contracts/lead-tools.js +56 -2
  38. package/dist/contracts/provider.js +1 -1
  39. package/dist/contracts/route.js +1 -1
  40. package/dist/contracts/terminal-connection.js +50 -0
  41. package/dist/converse.js +80 -4
  42. package/dist/device-pair.js +280 -0
  43. package/dist/direct-chat-artifacts.js +347 -0
  44. package/dist/direct-chat-catalog.js +311 -0
  45. package/dist/direct-chat-fence.js +96 -0
  46. package/dist/direct-chat-git.js +343 -0
  47. package/dist/direct-chat-laptop.js +19 -0
  48. package/dist/direct-chat-schema.js +181 -0
  49. package/dist/direct-chat-ship.js +861 -0
  50. package/dist/direct-chat-workspace.js +389 -0
  51. package/dist/direct-chat.js +2107 -0
  52. package/dist/doctor.js +1 -1
  53. package/dist/easy-start.js +18 -0
  54. package/dist/egress.js +25 -4
  55. package/dist/engine-chat.js +454 -0
  56. package/dist/engine-reads.js +141 -13
  57. package/dist/exec.js +4 -3
  58. package/dist/flexible-agents.js +8 -16
  59. package/dist/flexible-session.js +91 -47
  60. package/dist/flexible-ship.js +87 -7
  61. package/dist/flexible-start.js +4 -1
  62. package/dist/flexible-thread.js +2 -3
  63. package/dist/flexible-turns.js +26 -5
  64. package/dist/flow-triggers.js +13 -4
  65. package/dist/flows-ui.js +54 -20
  66. package/dist/handoff-cli.js +630 -0
  67. package/dist/invoke.js +71 -17
  68. package/dist/lead-contract.js +5 -4
  69. package/dist/lead-doors.js +80 -1
  70. package/dist/lead-progress.js +9 -0
  71. package/dist/lead-tools.js +681 -10
  72. package/dist/lead.js +37 -9
  73. package/dist/live-bus.js +11 -0
  74. package/dist/live-terminal.js +132 -12
  75. package/dist/local-handoff.js +363 -0
  76. package/dist/local-owner-acts.js +264 -2
  77. package/dist/local-owner.js +16 -1
  78. package/dist/multiplayer-handoff.js +528 -0
  79. package/dist/multiplayer-presence.js +471 -0
  80. package/dist/names.js +17 -4
  81. package/dist/needs-you.js +10 -0
  82. package/dist/operate.js +280 -19
  83. package/dist/planner.js +6 -1
  84. package/dist/policy.js +2 -2
  85. package/dist/project-delete-ui.js +18 -11
  86. package/dist/project-delete.js +65 -4
  87. package/dist/project-skills.js +28 -13
  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/scout.js +6 -2
  102. package/dist/serve.js +49 -5
  103. package/dist/server/chat.js +94 -13
  104. package/dist/server/direct-chat.js +583 -0
  105. package/dist/server/engine-api.js +219 -21
  106. package/dist/server/flows.js +43 -10
  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/skills-manifest.js +57 -0
  123. package/dist/store.js +499 -56
  124. package/dist/subscription-chat.js +33 -6
  125. package/dist/subscription-usage.js +233 -0
  126. package/dist/task-live.js +2 -1
  127. package/dist/teardown-git.js +34 -4
  128. package/dist/terminal-connection.js +159 -0
  129. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  130. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  131. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  132. package/dist/tui/linux-x64/toolroll-tui +0 -0
  133. package/dist/tui-contract.js +1 -1
  134. package/dist/tui-launch.js +32 -1
  135. package/dist/workspace-identity-schema.js +21 -0
  136. package/package.json +4 -2
@@ -0,0 +1,2107 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
4
+ import { readdir, rm } from "node:fs/promises";
5
+ import { homedir, hostname, tmpdir } from "node:os";
6
+ import { basename, dirname, isAbsolute, join, relative } from "node:path";
7
+ import { resolveExecutable } from "./attest.js";
8
+ import { currentBootId, provenDeadByBootChange } from "./boot-identity.js";
9
+ import { scanCustody } from "./flexible-custody.js";
10
+ import { defaultCustodyIO } from "./flexible-launch.js";
11
+ import { plainAgentEnv } from "./agent-fence.js";
12
+ import { directChatFence } from "./direct-chat-fence.js";
13
+ import { confined } from "./exec.js";
14
+ import { cleanLiveText, HIDDEN_LINE, liveSecretHit } from "./live-records.js";
15
+ import { projectName } from "./project.js";
16
+ import { captureNewWorkspaceArtifacts, extractBase64ImagesFromLine, getDirectChatArtifact, listArtifactsForThread, saveDirectChatArtifact, snapshotWorkspaceImages, } from "./direct-chat-artifacts.js";
17
+ import { assertManagedClonePath, assertTrustedCloneGit, cloneIsolatedRepoAsync, pinnedConfigBackupPath, repairCloneGitBinding, runTrustedCloneGit, } from "./direct-chat-git.js";
18
+ import { applyMainDirtyPatch, cloneSafeNodeModulesAsync } from "./direct-chat-workspace.js";
19
+ import { defaultContextWindowFor, normalizeDirectChatEffort, resolveAgyModelForEffort } from "./direct-chat-catalog.js";
20
+ export const DIRECT_CHAT_PROVIDERS = Object.freeze(["claude", "codex", "gemini"]);
21
+ export function isDirectChatProvider(value) {
22
+ return value === "claude" || value === "codex" || value === "gemini";
23
+ }
24
+ export function directChatPostureOf(provider) {
25
+ switch (provider) {
26
+ case "claude":
27
+ return {
28
+ summary: "Runs commands without asking",
29
+ detail: "Uses Claude auto mode inside this chat's isolated clone (no OS sandbox).",
30
+ sandboxed: false,
31
+ };
32
+ case "codex":
33
+ return {
34
+ summary: "Runs commands without asking",
35
+ detail: "Uses Codex workspace-write sandbox inside this chat's isolated clone.",
36
+ sandboxed: true,
37
+ };
38
+ case "gemini":
39
+ return {
40
+ summary: "Runs commands without asking",
41
+ detail: "Uses Antigravity auto mode with sandbox inside this chat's isolated clone.",
42
+ sandboxed: true,
43
+ };
44
+ }
45
+ }
46
+ export function defaultModelForProvider(provider) {
47
+ switch (provider) {
48
+ case "claude": return "opus";
49
+ case "codex": return "gpt-6-astra";
50
+ case "gemini": return "gemini-4-neon-high";
51
+ }
52
+ }
53
+ const HEX32 = /^[0-9a-f]{32}$/;
54
+ const MAX_LINE_BYTES = 8 * 1024 * 1024;
55
+ const MAX_DIFF_BYTES = 40_000;
56
+ const DEFAULT_STOP_GRACE_MS = 5_000;
57
+ const EMPTY_DIFF = Object.freeze({ changedFiles: [], diffText: "", dirty: false });
58
+ const HANDOFF_MAX_TURNS = 6;
59
+ const HANDOFF_MAX_CHARS = 6_000;
60
+ function sanitizeDisplay(raw) {
61
+ return raw
62
+ .replace(/\r\n/g, "\n")
63
+ .split("\n")
64
+ .map(line => {
65
+ const cleaned = cleanLiveText(line);
66
+ return liveSecretHit(cleaned) ? HIDDEN_LINE : cleaned;
67
+ })
68
+ .join("\n");
69
+ }
70
+ function sanitizeLine(raw) {
71
+ const cleaned = cleanLiveText(raw).replace(/\s+/g, " ").trim();
72
+ if (cleaned === "")
73
+ return "";
74
+ return liveSecretHit(cleaned) ? HIDDEN_LINE : cleaned;
75
+ }
76
+ function friendlyToolName(raw) {
77
+ switch (raw.toLowerCase()) {
78
+ case "view_file":
79
+ case "read":
80
+ case "read_file":
81
+ return "Read";
82
+ case "list_dir":
83
+ case "find_by_name":
84
+ return "Browse";
85
+ case "grep_search":
86
+ case "search_web":
87
+ return "Search";
88
+ case "replace_file_content":
89
+ case "multi_replace_file_content":
90
+ case "sed_file":
91
+ case "edit":
92
+ return "Edit";
93
+ case "write_to_file":
94
+ case "write":
95
+ return "Write";
96
+ case "run_command":
97
+ case "bash":
98
+ return "Run";
99
+ default:
100
+ return raw.replace(/_/g, " ").replace(/\b\w/g, c => c.toUpperCase());
101
+ }
102
+ }
103
+ function summarizeToolInput(input, homeDir = homedir()) {
104
+ if (!input || typeof input !== "object")
105
+ return "";
106
+ const keys = [
107
+ "CommandLine", "command",
108
+ "TargetFile", "AbsolutePath", "DirectoryPath", "SearchDirectory", "SearchPath", "Path",
109
+ "file_path", "path",
110
+ "Query", "Pattern", "pattern", "query",
111
+ "Url", "url",
112
+ "description",
113
+ ];
114
+ for (const key of keys) {
115
+ const val = input[key];
116
+ if (typeof val === "string" && val.trim() !== "") {
117
+ let cleaned = val.split(homeDir).join("~");
118
+ if (cleaned.startsWith("~/") || cleaned.startsWith("/")) {
119
+ const parts = cleaned.split("/").filter(Boolean);
120
+ if (parts.length > 3)
121
+ cleaned = parts.slice(-2).join("/");
122
+ }
123
+ return sanitizeLine(cleaned.slice(0, 120));
124
+ }
125
+ }
126
+ return "";
127
+ }
128
+ export function parseDirectChatLine(line, provider) {
129
+ const trimmed = line.trim();
130
+ if (trimmed === "" || Buffer.byteLength(trimmed, "utf8") > MAX_LINE_BYTES)
131
+ return [];
132
+ let json;
133
+ try {
134
+ const parsed = JSON.parse(trimmed);
135
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
136
+ return [];
137
+ json = parsed;
138
+ }
139
+ catch {
140
+ return [];
141
+ }
142
+ switch (provider) {
143
+ case "claude": return parseClaudeJson(json);
144
+ case "codex": return parseCodexJson(json);
145
+ case "gemini": return parseGeminiJson(json);
146
+ }
147
+ }
148
+ function finiteNonNeg(val) {
149
+ return typeof val === "number" && Number.isFinite(val) && val >= 0 ? Math.round(val) : 0;
150
+ }
151
+ function emptyUsage(contextWindow = null) {
152
+ return {
153
+ inputTokens: 0,
154
+ outputTokens: 0,
155
+ cacheReadTokens: 0,
156
+ cacheCreationTokens: 0,
157
+ thinkingTokens: 0,
158
+ contextTokens: 0,
159
+ contextWindow,
160
+ costUsd: null,
161
+ };
162
+ }
163
+ function parseUsageJson(raw) {
164
+ if (typeof raw !== "string" || raw.trim() === "")
165
+ return null;
166
+ try {
167
+ const parsed = JSON.parse(raw);
168
+ if (!parsed || typeof parsed !== "object")
169
+ return null;
170
+ return {
171
+ inputTokens: finiteNonNeg(parsed.inputTokens),
172
+ outputTokens: finiteNonNeg(parsed.outputTokens),
173
+ cacheReadTokens: finiteNonNeg(parsed.cacheReadTokens),
174
+ cacheCreationTokens: finiteNonNeg(parsed.cacheCreationTokens),
175
+ thinkingTokens: finiteNonNeg(parsed.thinkingTokens),
176
+ contextTokens: finiteNonNeg(parsed.contextTokens),
177
+ contextWindow: typeof parsed.contextWindow === "number" && Number.isFinite(parsed.contextWindow) && parsed.contextWindow > 0
178
+ ? Math.round(parsed.contextWindow)
179
+ : null,
180
+ costUsd: typeof parsed.costUsd === "number" && Number.isFinite(parsed.costUsd) && parsed.costUsd >= 0
181
+ ? parsed.costUsd
182
+ : null,
183
+ };
184
+ }
185
+ catch {
186
+ return null;
187
+ }
188
+ }
189
+ function parseClaudeJson(json) {
190
+ const events = [];
191
+ if (typeof json["session_id"] === "string" && json["session_id"] !== "") {
192
+ events.push({ kind: "session_id", sessionId: json["session_id"] });
193
+ }
194
+ const type = typeof json["type"] === "string" ? json["type"] : "";
195
+ if (type === "stream_event" && json["parent_tool_use_id"] == null && json["event"] && typeof json["event"] === "object" && !Array.isArray(json["event"])) {
196
+ const inner = json["event"];
197
+ const innerType = typeof inner["type"] === "string" ? inner["type"] : "";
198
+ if (innerType === "message_start") {
199
+ events.push({ kind: "message_start" });
200
+ }
201
+ else if (innerType === "content_block_start" && inner["content_block"] && typeof inner["content_block"] === "object") {
202
+ const block = inner["content_block"];
203
+ if (block["type"] === "tool_use") {
204
+ const name = typeof block["name"] === "string" ? block["name"] : "Tool";
205
+ const id = typeof block["id"] === "string" && block["id"] !== "" ? block["id"] : randomBytes(8).toString("hex");
206
+ events.push({ kind: "tool", id, name, detail: "", status: "running" });
207
+ }
208
+ }
209
+ else if (innerType === "content_block_delta" && inner["delta"] && typeof inner["delta"] === "object") {
210
+ const delta = inner["delta"];
211
+ if (delta["type"] === "text_delta" && typeof delta["text"] === "string" && delta["text"] !== "") {
212
+ events.push({ kind: "text_delta", delta: delta["text"] });
213
+ }
214
+ }
215
+ return events;
216
+ }
217
+ if (type === "assistant" && json["message"] && typeof json["message"] === "object") {
218
+ const message = json["message"];
219
+ const content = Array.isArray(message["content"]) ? message["content"] : [];
220
+ const textParts = [];
221
+ for (const rawBlock of content) {
222
+ if (!rawBlock || typeof rawBlock !== "object")
223
+ continue;
224
+ const block = rawBlock;
225
+ const bType = typeof block["type"] === "string" ? block["type"] : "";
226
+ if (bType === "text" && typeof block["text"] === "string" && block["text"] !== "") {
227
+ textParts.push(block["text"]);
228
+ }
229
+ else if (bType === "tool_use") {
230
+ const name = typeof block["name"] === "string" ? block["name"] : "Tool";
231
+ const input = (block["input"] && typeof block["input"] === "object") ? block["input"] : null;
232
+ const id = typeof block["id"] === "string" && block["id"] !== "" ? block["id"] : randomBytes(8).toString("hex");
233
+ events.push({ kind: "tool", id, name, detail: summarizeToolInput(input), status: "running" });
234
+ }
235
+ }
236
+ if (textParts.length > 0) {
237
+ events.push({ kind: "text_replace", text: sanitizeDisplay(textParts.join("\n")) });
238
+ }
239
+ if (message["usage"] && typeof message["usage"] === "object") {
240
+ const u = message["usage"];
241
+ const inputTokens = finiteNonNeg(u["input_tokens"]);
242
+ const cacheReadTokens = finiteNonNeg(u["cache_read_input_tokens"]);
243
+ const cacheCreationTokens = finiteNonNeg(u["cache_creation_input_tokens"]);
244
+ const outputTokens = finiteNonNeg(u["output_tokens"]);
245
+ const contextTokens = inputTokens + cacheReadTokens + cacheCreationTokens;
246
+ if (contextTokens > 0 || outputTokens > 0) {
247
+ events.push({
248
+ kind: "usage",
249
+ usage: { inputTokens, outputTokens, cacheReadTokens, cacheCreationTokens, contextTokens },
250
+ cumulative: false,
251
+ });
252
+ }
253
+ }
254
+ }
255
+ else if (type === "user" && json["message"] && typeof json["message"] === "object") {
256
+ const message = json["message"];
257
+ const content = Array.isArray(message["content"]) ? message["content"] : [];
258
+ for (const rawBlock of content) {
259
+ if (!rawBlock || typeof rawBlock !== "object")
260
+ continue;
261
+ const block = rawBlock;
262
+ if (block["type"] === "tool_result" && typeof block["tool_use_id"] === "string" && block["tool_use_id"] !== "") {
263
+ events.push({ kind: "tool_status", id: block["tool_use_id"], status: block["is_error"] === true ? "error" : "done" });
264
+ }
265
+ }
266
+ }
267
+ else if (type === "result") {
268
+ const rawUsage = json["usage"] && typeof json["usage"] === "object" ? json["usage"] : null;
269
+ const rawModelUsage = json["modelUsage"] && typeof json["modelUsage"] === "object" ? json["modelUsage"] : null;
270
+ let contextWindow = null;
271
+ let thinkingTokens = 0;
272
+ let modelCost = null;
273
+ if (rawModelUsage) {
274
+ for (const entry of Object.values(rawModelUsage)) {
275
+ if (!entry || typeof entry !== "object")
276
+ continue;
277
+ const m = entry;
278
+ if (typeof m["contextWindow"] === "number" && Number.isFinite(m["contextWindow"]) && m["contextWindow"] > 0) {
279
+ contextWindow = Math.round(m["contextWindow"]);
280
+ }
281
+ thinkingTokens += finiteNonNeg(m["thinkingTokens"]);
282
+ if (typeof m["costUSD"] === "number" && Number.isFinite(m["costUSD"]) && m["costUSD"] >= 0) {
283
+ modelCost = (modelCost ?? 0) + m["costUSD"];
284
+ }
285
+ }
286
+ }
287
+ const costUsd = typeof json["total_cost_usd"] === "number" && Number.isFinite(json["total_cost_usd"]) && json["total_cost_usd"] >= 0
288
+ ? json["total_cost_usd"]
289
+ : modelCost;
290
+ if (rawUsage) {
291
+ const outDetails = rawUsage["output_tokens_details"] && typeof rawUsage["output_tokens_details"] === "object"
292
+ ? rawUsage["output_tokens_details"]
293
+ : null;
294
+ if (thinkingTokens === 0 && outDetails) {
295
+ thinkingTokens = finiteNonNeg(outDetails["thinking_tokens"]);
296
+ }
297
+ const inputTokens = finiteNonNeg(rawUsage["input_tokens"]);
298
+ const cacheReadTokens = finiteNonNeg(rawUsage["cache_read_input_tokens"]);
299
+ const cacheCreationTokens = finiteNonNeg(rawUsage["cache_creation_input_tokens"]);
300
+ const outputTokens = finiteNonNeg(rawUsage["output_tokens"]);
301
+ events.push({
302
+ kind: "usage",
303
+ usage: {
304
+ inputTokens,
305
+ outputTokens,
306
+ cacheReadTokens,
307
+ cacheCreationTokens,
308
+ thinkingTokens,
309
+ ...(contextWindow !== null ? { contextWindow } : {}),
310
+ ...(costUsd !== null ? { costUsd } : {}),
311
+ },
312
+ cumulative: true,
313
+ });
314
+ }
315
+ else if (contextWindow !== null || costUsd !== null) {
316
+ events.push({
317
+ kind: "usage",
318
+ usage: {
319
+ ...(contextWindow !== null ? { contextWindow } : {}),
320
+ ...(costUsd !== null ? { costUsd } : {}),
321
+ },
322
+ cumulative: true,
323
+ });
324
+ }
325
+ const isError = json["is_error"] === true;
326
+ const resultText = typeof json["result"] === "string" ? json["result"] : "";
327
+ const denials = Array.isArray(json["permission_denials"]) ? json["permission_denials"] : [];
328
+ if (isError) {
329
+ events.push({ kind: "failed", message: resultText !== "" ? resultText : "Claude returned an error." });
330
+ }
331
+ else if (resultText !== "") {
332
+ events.push({ kind: "text_replace", text: resultText });
333
+ events.push({ kind: "completed" });
334
+ }
335
+ else if (denials.length > 0) {
336
+ const names = denials
337
+ .map(d => (d && typeof d === "object" && typeof d["tool_name"] === "string" ? String(d["tool_name"]) : "tool"))
338
+ .join(", ");
339
+ events.push({ kind: "failed", message: `Blocked by permission policy (${names}).` });
340
+ }
341
+ else {
342
+ events.push({ kind: "completed" });
343
+ }
344
+ }
345
+ return events;
346
+ }
347
+ function parseCodexJson(json) {
348
+ const events = [];
349
+ const type = typeof json["type"] === "string" ? json["type"] : "";
350
+ if (type === "thread.started" && typeof json["thread_id"] === "string" && json["thread_id"] !== "") {
351
+ events.push({ kind: "session_id", sessionId: json["thread_id"] });
352
+ }
353
+ else if ((type === "item.completed" || type === "item.started") && json["item"] && typeof json["item"] === "object") {
354
+ const item = json["item"];
355
+ const itemType = typeof item["type"] === "string" ? item["type"] : "";
356
+ const itemId = typeof item["id"] === "string" && item["id"] !== "" ? item["id"] : randomBytes(8).toString("hex");
357
+ if (itemType === "agent_message" && typeof item["text"] === "string" && item["text"] !== "") {
358
+ events.push({ kind: "text_replace", text: item["text"] });
359
+ }
360
+ else if (itemType === "command_execution") {
361
+ const cmd = typeof item["command"] === "string" ? item["command"] : "shell";
362
+ const status = type === "item.completed"
363
+ ? (typeof item["exit_code"] === "number" && item["exit_code"] !== 0 ? "error" : "done")
364
+ : "running";
365
+ events.push({ kind: "tool", id: itemId, name: "Run", detail: sanitizeLine(cmd.slice(0, 120)), status });
366
+ }
367
+ else if (itemType === "file_change") {
368
+ const changes = Array.isArray(item["changes"]) ? item["changes"] : [];
369
+ const paths = changes
370
+ .map(c => (c && typeof c === "object" && typeof c["path"] === "string" ? String(c["path"]) : ""))
371
+ .filter(Boolean)
372
+ .slice(0, 3)
373
+ .join(", ");
374
+ events.push({ kind: "tool", id: itemId, name: "Edit", detail: paths !== "" ? sanitizeLine(paths) : "Updated files", status: "done" });
375
+ }
376
+ else if (itemType === "mcp_tool_call") {
377
+ const tool = typeof item["tool"] === "string" ? item["tool"] : "Tool";
378
+ const server = typeof item["server"] === "string" ? item["server"] : "";
379
+ events.push({ kind: "tool", id: itemId, name: tool, detail: sanitizeLine(server), status: type === "item.completed" ? "done" : "running" });
380
+ }
381
+ }
382
+ else if (type === "turn.completed") {
383
+ if (json["usage"] && typeof json["usage"] === "object") {
384
+ const u = json["usage"];
385
+ const inputTokens = finiteNonNeg(u["input_tokens"]);
386
+ const cacheReadTokens = finiteNonNeg(u["cached_input_tokens"]);
387
+ const outputTokens = finiteNonNeg(u["output_tokens"]);
388
+ const contextTokens = inputTokens;
389
+ if (inputTokens > 0 || outputTokens > 0) {
390
+ events.push({
391
+ kind: "usage",
392
+ usage: { inputTokens, outputTokens, cacheReadTokens, contextTokens },
393
+ cumulative: true,
394
+ });
395
+ }
396
+ }
397
+ events.push({ kind: "completed" });
398
+ }
399
+ else if (type === "turn.failed" || type === "error") {
400
+ const errObj = (json["error"] && typeof json["error"] === "object") ? json["error"] : null;
401
+ const msg = (typeof errObj?.["message"] === "string" ? errObj["message"] : null)
402
+ ?? (typeof json["message"] === "string" ? json["message"] : null)
403
+ ?? "Codex turn failed.";
404
+ events.push({ kind: "failed", message: msg });
405
+ }
406
+ return events;
407
+ }
408
+ function parseGeminiJson(json) {
409
+ const events = [];
410
+ if (typeof json["conversation_id"] === "string" && json["conversation_id"] !== "") {
411
+ events.push({ kind: "session_id", sessionId: json["conversation_id"] });
412
+ }
413
+ const event = typeof json["event"] === "string" ? json["event"] : "";
414
+ if (event === "step_update" && json["step_update"] && typeof json["step_update"] === "object") {
415
+ const step = json["step_update"];
416
+ const stepType = typeof step["step_type"] === "string" ? step["step_type"] : "";
417
+ const state = (typeof step["state"] === "string" ? step["state"] : "").toUpperCase();
418
+ if (stepType === "agent_response" && typeof step["text_delta"] === "string" && step["text_delta"] !== "") {
419
+ events.push({ kind: "text_delta", delta: step["text_delta"] });
420
+ }
421
+ else if (stepType === "tool") {
422
+ const idx = typeof step["step_index"] === "number" ? step["step_index"] : 0;
423
+ const toolInfo = (step["tool_info"] && typeof step["tool_info"] === "object") ? step["tool_info"] : null;
424
+ const rawName = (typeof step["tool_name"] === "string" ? step["tool_name"] : null)
425
+ ?? (typeof toolInfo?.["name"] === "string" ? toolInfo["name"] : null)
426
+ ?? "Tool";
427
+ const params = (toolInfo?.["parameters"] && typeof toolInfo["parameters"] === "object") ? toolInfo["parameters"] : null;
428
+ const status = state === "DONE" ? "done" : state === "ERROR" ? "error" : "running";
429
+ events.push({
430
+ kind: "tool",
431
+ id: `agy-${idx}`,
432
+ name: friendlyToolName(rawName),
433
+ detail: summarizeToolInput(params),
434
+ status,
435
+ });
436
+ }
437
+ }
438
+ else if (event === "result" && json["result"] && typeof json["result"] === "object") {
439
+ const result = json["result"];
440
+ const stats = (result["usage"] && typeof result["usage"] === "object"
441
+ ? result["usage"]
442
+ : (result["stats"] && typeof result["stats"] === "object" ? result["stats"] : null));
443
+ if (stats) {
444
+ const inputTokens = finiteNonNeg(stats["input_tokens"] ?? stats["prompt_tokens"] ?? stats["inputTokens"]);
445
+ const outputTokens = finiteNonNeg(stats["output_tokens"] ?? stats["completion_tokens"] ?? stats["outputTokens"]);
446
+ const cacheReadTokens = finiteNonNeg(stats["cached_tokens"] ?? stats["cache_read_input_tokens"] ?? stats["cachedInputTokens"]);
447
+ const thinkingTokens = finiteNonNeg(stats["thinking_tokens"] ?? stats["thoughts_token_count"] ?? stats["thinkingTokens"]);
448
+ if (inputTokens > 0 || outputTokens > 0 || cacheReadTokens > 0) {
449
+ events.push({
450
+ kind: "usage",
451
+ usage: {
452
+ inputTokens,
453
+ outputTokens,
454
+ cacheReadTokens,
455
+ thinkingTokens,
456
+ contextTokens: inputTokens + cacheReadTokens,
457
+ },
458
+ cumulative: true,
459
+ });
460
+ }
461
+ }
462
+ if (typeof result["conversation_id"] === "string" && result["conversation_id"] !== "") {
463
+ events.push({ kind: "session_id", sessionId: result["conversation_id"] });
464
+ }
465
+ const status = (typeof result["status"] === "string" ? result["status"] : "").toUpperCase();
466
+ const rawResponse = typeof result["response"] === "string" ? result["response"] : "";
467
+ const trimmed = rawResponse.trim();
468
+ if (status === "SUCCESS" || status === "") {
469
+ if (trimmed !== "") {
470
+ events.push({ kind: "text_replace", text: rawResponse });
471
+ events.push({ kind: "completed" });
472
+ }
473
+ else if (Array.isArray(result["denied_actions"]) && result["denied_actions"].length > 0) {
474
+ const names = result["denied_actions"]
475
+ .map(d => (d && typeof d === "object"
476
+ ? String(d["display_name"] ?? d["action"] ?? "tool")
477
+ : "tool"))
478
+ .join(", ");
479
+ events.push({ kind: "failed", message: `Blocked by permission policy (${names}).` });
480
+ }
481
+ else {
482
+ events.push({ kind: "completed" });
483
+ }
484
+ }
485
+ else {
486
+ const msg = (typeof result["error"] === "string" ? result["error"] : null)
487
+ ?? (trimmed !== "" ? rawResponse : null)
488
+ ?? "Gemini run failed.";
489
+ events.push({ kind: "failed", message: msg });
490
+ }
491
+ }
492
+ return events;
493
+ }
494
+ export function buildProviderCommand(input) {
495
+ const { provider, modelId, prompt, sessionId } = input;
496
+ const effort = normalizeDirectChatEffort(input.effort, provider);
497
+ switch (provider) {
498
+ case "claude": {
499
+ const args = ["-p", "--output-format", "stream-json", "--verbose", "--include-partial-messages", "--permission-mode", "auto"];
500
+ if (modelId !== "")
501
+ args.push("--model", modelId);
502
+ if (effort !== null)
503
+ args.push("--effort", effort);
504
+ if (sessionId !== null && sessionId !== "")
505
+ args.push("--resume", sessionId);
506
+ args.push("--", prompt);
507
+ return args;
508
+ }
509
+ case "codex": {
510
+ const resuming = sessionId !== null && sessionId !== "";
511
+ const args = [
512
+ "exec",
513
+ ...(resuming
514
+ ? ["resume", sessionId, "-c", 'sandbox_mode="workspace-write"', "-c", 'approval_policy="never"']
515
+ : ["--sandbox", "workspace-write", "-c", 'approval_policy="never"']),
516
+ "--json",
517
+ "--skip-git-repo-check",
518
+ ];
519
+ if (modelId !== "")
520
+ args.push("-m", modelId);
521
+ if (effort !== null)
522
+ args.push("-c", `model_reasoning_effort="${effort}"`);
523
+ args.push("--", prompt);
524
+ return args;
525
+ }
526
+ case "gemini": {
527
+ const safePrompt = prompt.startsWith("-") ? ` ${prompt}` : prompt;
528
+ const args = ["-p", safePrompt, "--output-format", "stream-json", "--mode", "auto", "--sandbox"];
529
+ const effectiveModel = modelId !== "" ? resolveAgyModelForEffort(modelId, effort) : "";
530
+ if (effectiveModel !== "")
531
+ args.push("--model", effectiveModel);
532
+ if (effort !== null)
533
+ args.push("--effort", effort);
534
+ if (sessionId !== null && sessionId !== "")
535
+ args.push("--conversation", sessionId);
536
+ return args;
537
+ }
538
+ }
539
+ }
540
+ const DIRECT_CHAT_BINARIES = {
541
+ claude: "claude",
542
+ codex: "codex",
543
+ gemini: "agy",
544
+ };
545
+ export function locateDirectChatBinary(provider) {
546
+ return resolveExecutable(DIRECT_CHAT_BINARIES[provider]);
547
+ }
548
+ const SIGN_IN_LOCATION_ENV = {
549
+ claude: ["CLAUDE_CONFIG_DIR"],
550
+ codex: ["CODEX_HOME"],
551
+ gemini: [],
552
+ };
553
+ const XDG_FOLDERS = ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"];
554
+ export function buildSanitizedChildEnv(provider, baseEnv = process.env, homeDir = homedir()) {
555
+ const out = { ...plainAgentEnv(baseEnv) };
556
+ out["HOME"] = baseEnv["HOME"] ?? homeDir;
557
+ for (const name of ["TMPDIR", ...XDG_FOLDERS, ...SIGN_IN_LOCATION_ENV[provider]]) {
558
+ const value = baseEnv[name];
559
+ if (value !== undefined && value !== "")
560
+ out[name] = value;
561
+ }
562
+ const extraPath = `${homeDir}/.local/bin:${homeDir}/.gemini/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin`;
563
+ out["PATH"] = out["PATH"] ? `${extraPath}:${out["PATH"]}` : extraPath;
564
+ out["GIT_TERMINAL_PROMPT"] = "0";
565
+ return out;
566
+ }
567
+ export function buildTurnPrompt(input) {
568
+ const parts = [];
569
+ if (input.isFirstTurnForProvider) {
570
+ parts.push(`[Workspace boundary: you are working in an isolated local clone on branch ${input.branch} with no remote. Work only inside this directory; never push, force-reset, or delete files outside this workspace. Leave your changes in the working tree — do not run git commit or git push, because Toolroll commits and ships snapshots for you.]`);
571
+ if (input.priorTurns.length > 0) {
572
+ const slice = input.priorTurns.slice(-HANDOFF_MAX_TURNS);
573
+ let handoff = "[Context handed off from earlier turns in this chat:]\n";
574
+ for (const turn of slice) {
575
+ const entry = `User: ${turn.userPrompt.slice(0, 600)}\nAssistant: ${turn.assistantText.slice(0, 800)}\n`;
576
+ if (handoff.length + entry.length > HANDOFF_MAX_CHARS)
577
+ break;
578
+ handoff += entry;
579
+ }
580
+ parts.push(handoff.trim());
581
+ }
582
+ }
583
+ parts.push(input.userPrompt);
584
+ return parts.join("\n\n");
585
+ }
586
+ async function defaultPrepareCloneAsync(input) {
587
+ const cloned = await cloneIsolatedRepoAsync(input);
588
+ await cloneSafeNodeModulesAsync({ repo: input.repo, clonePath: input.clonePath });
589
+ return {
590
+ baseSha: cloned.baseSha,
591
+ gitDir: cloned.gitDir,
592
+ configSha256: cloned.configSha256,
593
+ mainDirtyFiles: cloned.mainDirtyFiles.map(sanitizeLine),
594
+ };
595
+ }
596
+ function defaultReadDiff(input) {
597
+ if (!existsSync(input.binding.clonePath))
598
+ return { changedFiles: [], diffText: "", dirty: false };
599
+ const verified = assertTrustedCloneGit(input.binding);
600
+ if (!verified.ok)
601
+ return { changedFiles: [], diffText: "", dirty: false };
602
+ try {
603
+ const statusLines = runTrustedCloneGit(input.binding, ["status", "--porcelain"])
604
+ .split("\n")
605
+ .map(line => line.trim())
606
+ .filter(Boolean);
607
+ const committedFiles = runTrustedCloneGit(input.binding, ["diff", "--no-ext-diff", "--no-textconv", "--name-only", input.baseSha])
608
+ .split("\n")
609
+ .map(line => line.trim())
610
+ .filter(Boolean);
611
+ const untracked = statusLines
612
+ .filter(line => line.startsWith("?? "))
613
+ .map(line => line.slice(3).trim())
614
+ .filter(Boolean);
615
+ const allFiles = [...new Set([...committedFiles, ...untracked])];
616
+ let diffText = "";
617
+ if (allFiles.length > 0) {
618
+ diffText = runTrustedCloneGit(input.binding, ["diff", "--no-ext-diff", "--no-textconv", "--no-color", input.baseSha]);
619
+ if (diffText.length > MAX_DIFF_BYTES) {
620
+ diffText = `${diffText.slice(0, MAX_DIFF_BYTES)}\n… (diff truncated)`;
621
+ }
622
+ }
623
+ return {
624
+ changedFiles: allFiles.map(sanitizeLine),
625
+ diffText: sanitizeDisplay(diffText),
626
+ dirty: allFiles.length > 0 || statusLines.length > 0,
627
+ };
628
+ }
629
+ catch {
630
+ return { changedFiles: [], diffText: "", dirty: false };
631
+ }
632
+ }
633
+ function snapshotCloneTree(binding) {
634
+ if (!existsSync(binding.clonePath))
635
+ return null;
636
+ const verified = assertTrustedCloneGit(binding);
637
+ if (!verified.ok)
638
+ return null;
639
+ const scratch = mkdtempSync(join(tmpdir(), "toolroll-dc-idx-"));
640
+ const indexPath = join(scratch, "index");
641
+ try {
642
+ const extraEnv = { GIT_INDEX_FILE: indexPath };
643
+ try {
644
+ runTrustedCloneGit(binding, ["read-tree", "HEAD"], undefined, extraEnv);
645
+ }
646
+ catch {
647
+ }
648
+ runTrustedCloneGit(binding, ["add", "-A"], undefined, extraEnv);
649
+ const tree = runTrustedCloneGit(binding, ["write-tree"], undefined, extraEnv).trim();
650
+ return /^[0-9a-f]{40}$/i.test(tree) ? tree : null;
651
+ }
652
+ catch {
653
+ return null;
654
+ }
655
+ finally {
656
+ rmSync(scratch, { recursive: true, force: true });
657
+ }
658
+ }
659
+ function readTreeRangeDiff(binding, fromTreeSha, toTreeSha) {
660
+ if (fromTreeSha === toTreeSha)
661
+ return { ...EMPTY_DIFF };
662
+ if (!existsSync(binding.clonePath))
663
+ return { ...EMPTY_DIFF };
664
+ const verified = assertTrustedCloneGit(binding);
665
+ if (!verified.ok)
666
+ return { ...EMPTY_DIFF };
667
+ try {
668
+ const files = runTrustedCloneGit(binding, ["diff", "--no-ext-diff", "--no-textconv", "--name-only", fromTreeSha, toTreeSha])
669
+ .split("\n")
670
+ .map(line => line.trim())
671
+ .filter(Boolean);
672
+ if (files.length === 0)
673
+ return { ...EMPTY_DIFF };
674
+ let diffText = runTrustedCloneGit(binding, ["diff", "--no-ext-diff", "--no-textconv", "--no-color", fromTreeSha, toTreeSha]);
675
+ if (diffText.length > MAX_DIFF_BYTES) {
676
+ diffText = `${diffText.slice(0, MAX_DIFF_BYTES)}\n… (diff truncated)`;
677
+ }
678
+ return {
679
+ changedFiles: files.map(sanitizeLine),
680
+ diffText: sanitizeDisplay(diffText),
681
+ dirty: true,
682
+ };
683
+ }
684
+ catch {
685
+ return { ...EMPTY_DIFF };
686
+ }
687
+ }
688
+ function defaultSpawnTurn(custody, input) {
689
+ const launch = input.fence === undefined ? { file: input.binary, args: input.args, env: {} }
690
+ : confined(input.binary, input.args, { fence: input.fence.launch.fence, fenceGrants: input.fence.launch.fenceGrants, confinement: input.fence.launch.confinement, cwd: input.cwd, temp: input.fence.temp });
691
+ mkdirSync(dirname(input.logPath), { recursive: true, mode: 0o700 });
692
+ const outFd = openSync(input.logPath, "a", 0o600);
693
+ const errFd = openSync(input.stderrPath, "a", 0o600);
694
+ try {
695
+ const opts = {
696
+ cwd: input.cwd,
697
+ env: input.fence === undefined ? input.env : { ...input.env, ...input.fence.env, ...launch.env },
698
+ detached: true,
699
+ stdio: ["ignore", outFd, errFd],
700
+ };
701
+ const child = spawn(launch.file, launch.args, opts);
702
+ if (child.pid === undefined) {
703
+ throw new Error(`Could not start ${basename(input.binary)}.`);
704
+ }
705
+ child.unref();
706
+ const pid = child.pid;
707
+ let row = null;
708
+ for (let attempt = 0; attempt < 3; attempt += 1) {
709
+ row = custody.table()?.find(one => one.pid === pid) ?? null;
710
+ if (row !== null)
711
+ break;
712
+ }
713
+ return { pid, pgid: row?.pgid ?? pid, startIdentity: row?.start ?? null };
714
+ }
715
+ finally {
716
+ closeSync(outFd);
717
+ closeSync(errFd);
718
+ }
719
+ }
720
+ export class DirectChatHost {
721
+ store;
722
+ stateRoot;
723
+ now;
724
+ custody;
725
+ bootId;
726
+ stopGraceMs;
727
+ locateBinary;
728
+ spawnTurnFn;
729
+ fenceTurnFn;
730
+ turnFences = new Map();
731
+ prepareCloneFn;
732
+ readDiffFn;
733
+ hasCustomReadDiff;
734
+ onNotify;
735
+ sawTerminalByTurn = new Set();
736
+ resetOnNextTextDelta = new Set();
737
+ leadNotifiedTurnIds = new Set();
738
+ pendingSwitchFrom = new Map();
739
+ preTurnImages = new Map();
740
+ preTurnTreeSha = new Map();
741
+ inFlightCreates = new Map();
742
+ pendingCleanups = new Set();
743
+ pollTimer = null;
744
+ pollTicks = 0;
745
+ constructor(store, seams) {
746
+ this.store = store;
747
+ this.stateRoot = seams.stateRoot;
748
+ this.now = seams.now ?? (() => new Date());
749
+ this.custody = seams.custody ?? defaultCustodyIO();
750
+ this.bootId = seams.bootId ?? (() => currentBootId());
751
+ this.stopGraceMs = seams.stopGraceMs ?? DEFAULT_STOP_GRACE_MS;
752
+ this.locateBinary = seams.locateBinary ?? (provider => locateDirectChatBinary(provider));
753
+ this.spawnTurnFn = seams.spawnTurn ?? (input => defaultSpawnTurn(this.custody, input));
754
+ this.fenceTurnFn = seams.fenceTurn ?? (seams.spawnTurn === undefined ? directChatFence(store) : null);
755
+ this.prepareCloneFn = seams.prepareClone ?? defaultPrepareCloneAsync;
756
+ this.hasCustomReadDiff = seams.readDiff !== undefined;
757
+ this.readDiffFn = seams.readDiff ?? defaultReadDiff;
758
+ this.onNotify = seams.onNotify ?? (() => { });
759
+ }
760
+ startPolling(intervalMs = 80) {
761
+ if (this.pollTimer !== null)
762
+ return;
763
+ this.pollTicks = 0;
764
+ this.sweepTrash();
765
+ const custodyEvery = Math.max(1, Math.round(500 / Math.max(20, intervalMs)));
766
+ this.reconcileRunningTurns();
767
+ this.pollTimer = setInterval(() => {
768
+ this.pollTicks += 1;
769
+ if (this.pollTicks % custodyEvery === 0) {
770
+ this.reconcileRunningTurns();
771
+ }
772
+ else {
773
+ this.drainRunningTurnLogs();
774
+ }
775
+ }, intervalMs);
776
+ this.pollTimer.unref?.();
777
+ }
778
+ close() {
779
+ if (this.pollTimer !== null) {
780
+ clearInterval(this.pollTimer);
781
+ this.pollTimer = null;
782
+ }
783
+ for (const turnId of [...this.turnFences.keys()])
784
+ this.closeTurnFence(turnId);
785
+ }
786
+ closeTurnFence(turnId) {
787
+ const close = this.turnFences.get(turnId);
788
+ if (close === undefined)
789
+ return;
790
+ this.turnFences.delete(turnId);
791
+ this.trackCleanup(close().catch((error) => {
792
+ const said = `Toolroll couldn't finish closing this turn's sandbox: ${error instanceof Error ? error.message : String(error)}.`;
793
+ console.warn(`direct chat turn ${turnId}: ${said}`);
794
+ try {
795
+ this.store.handle.prepare(`UPDATE direct_chat_turn SET error_text = CASE WHEN error_text IS NULL OR error_text = '' THEN ? ELSE error_text || char(10) || ? END WHERE id = ?`)
796
+ .run(said, said, turnId);
797
+ }
798
+ catch { }
799
+ }));
800
+ }
801
+ async drainPendingCleanups() {
802
+ while (this.pendingCleanups.size > 0) {
803
+ await Promise.allSettled([...this.pendingCleanups]);
804
+ }
805
+ }
806
+ trackCleanup(task) {
807
+ const wrapped = task.catch(() => { }).finally(() => {
808
+ this.pendingCleanups.delete(wrapped);
809
+ });
810
+ this.pendingCleanups.add(wrapped);
811
+ }
812
+ scheduleAsyncDelete(targetPath) {
813
+ if (!existsSync(targetPath))
814
+ return;
815
+ const trashRoot = join(this.stateRoot, "direct-chat", "trash");
816
+ let toRemove = targetPath;
817
+ try {
818
+ mkdirSync(trashRoot, { recursive: true, mode: 0o700 });
819
+ const staged = join(trashRoot, `${randomBytes(8).toString("hex")}-${basename(targetPath)}`);
820
+ renameSync(targetPath, staged);
821
+ toRemove = staged;
822
+ }
823
+ catch {
824
+ }
825
+ this.trackCleanup(rm(toRemove, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }));
826
+ }
827
+ sweepTrash() {
828
+ const trashRoot = join(this.stateRoot, "direct-chat", "trash");
829
+ if (!existsSync(trashRoot))
830
+ return;
831
+ this.trackCleanup((async () => {
832
+ const entries = await readdir(trashRoot);
833
+ await Promise.allSettled(entries.map(name => rm(join(trashRoot, name), { recursive: true, force: true, maxRetries: 3, retryDelay: 100 })));
834
+ })());
835
+ }
836
+ hasUnmergedChanges(thread) {
837
+ const binding = this.bindingOf(thread);
838
+ if (binding === null)
839
+ return false;
840
+ if (this.hasCustomReadDiff) {
841
+ return this.readDiffFn({ binding, baseSha: thread.baseSha }).dirty;
842
+ }
843
+ if (!existsSync(binding.clonePath))
844
+ return false;
845
+ const verified = assertTrustedCloneGit(binding);
846
+ if (!verified.ok)
847
+ return false;
848
+ try {
849
+ if (runTrustedCloneGit(binding, ["status", "--porcelain"]).trim() !== "")
850
+ return true;
851
+ if (runTrustedCloneGit(binding, ["diff", "--no-ext-diff", "--no-textconv", "--name-only", thread.baseSha]).trim() !== "")
852
+ return true;
853
+ return false;
854
+ }
855
+ catch {
856
+ return false;
857
+ }
858
+ }
859
+ bindingOf(thread) {
860
+ if (!thread.gitDir || !thread.configSha256)
861
+ return null;
862
+ return {
863
+ stateRoot: this.stateRoot,
864
+ clonePath: thread.clonePath,
865
+ gitDir: thread.gitDir,
866
+ configSha256: thread.configSha256,
867
+ };
868
+ }
869
+ refreshDiffCache(thread) {
870
+ const binding = this.bindingOf(thread);
871
+ const diff = binding === null ? { ...EMPTY_DIFF } : this.readDiffFn({ binding, baseSha: thread.baseSha });
872
+ this.store.handle
873
+ .prepare(`UPDATE direct_chat_thread SET diff_cache_json = ? WHERE id = ?`)
874
+ .run(JSON.stringify(diff), thread.id);
875
+ return diff;
876
+ }
877
+ inspectThreadDiff(owner, threadId) {
878
+ if (!HEX32.test(threadId))
879
+ return { ok: false, status: 400, error: "Invalid thread id." };
880
+ const thread = this.getThreadRecord(owner, threadId);
881
+ if (!thread)
882
+ return { ok: false, status: 404, error: "Chat thread not found." };
883
+ const running = this.store.handle
884
+ .prepare(`SELECT 1 FROM direct_chat_turn WHERE thread_id = ? AND status = 'running' LIMIT 1`)
885
+ .get(thread.id) !== undefined;
886
+ const diff = this.refreshDiffCache(thread);
887
+ return { ok: true, diff, running };
888
+ }
889
+ notifyOwnerLeadThread(thread, turnId, finalStatus, assistantText, errorText, diff, now) {
890
+ if (finalStatus !== "completed" && finalStatus !== "failed" && finalStatus !== "interrupted")
891
+ return;
892
+ if (this.leadNotifiedTurnIds.has(turnId))
893
+ return;
894
+ this.leadNotifiedTurnIds.add(turnId);
895
+ const openLead = this.store.handle
896
+ .prepare(`SELECT id FROM lead_thread WHERE approver = ? AND closed_at IS NULL ORDER BY id DESC LIMIT 1`)
897
+ .get(thread.owner);
898
+ if (openLead === undefined)
899
+ return;
900
+ const leadThreadId = Number(openLead["id"]);
901
+ if (!Number.isInteger(leadThreadId) || leadThreadId <= 0)
902
+ return;
903
+ const providerLabel = thread.provider === "claude" ? "Claude" : thread.provider === "codex" ? "Codex" : "Gemini";
904
+ const proj = projectName(thread.repo);
905
+ const title = sanitizeLine(thread.title).slice(0, 80) || "Direct Chat";
906
+ let text;
907
+ if (finalStatus === "completed") {
908
+ const changed = diff?.changedFiles.length ?? 0;
909
+ const diffPart = changed > 0
910
+ ? `${changed} ${changed === 1 ? "file" : "files"} changed — ready to review or ship.`
911
+ : "no file changes yet.";
912
+ const snippet = sanitizeLine(assistantText).slice(0, 160);
913
+ text = snippet !== ""
914
+ ? `Direct Chat finished — "${title}" (${providerLabel}, ${proj}): ${diffPart}\n${snippet}${assistantText.trim().length > 160 ? "…" : ""}`
915
+ : `Direct Chat finished — "${title}" (${providerLabel}, ${proj}): ${diffPart}`;
916
+ }
917
+ else {
918
+ const reason = sanitizeLine(errorText ?? "Ended without completing.").slice(0, 180);
919
+ text = `Direct Chat ${finalStatus} — "${title}" (${providerLabel}, ${proj}): ${reason}`;
920
+ }
921
+ this.store.appendLeadMessage({ thread: leadThreadId, turn: null, role: "assistant", text, activity: null }, now);
922
+ }
923
+ turnDiffPath(threadId, turnId) {
924
+ return join(this.stateRoot, "direct-chat", "turns", threadId, `${turnId}.diff.json`);
925
+ }
926
+ captureTurnDiff(thread, turnId) {
927
+ const beforeTree = this.preTurnTreeSha.get(turnId);
928
+ if (!beforeTree)
929
+ return null;
930
+ const binding = this.bindingOf(thread);
931
+ if (binding === null)
932
+ return null;
933
+ const afterTree = snapshotCloneTree(binding);
934
+ if (afterTree === null)
935
+ return null;
936
+ const diff = readTreeRangeDiff(binding, beforeTree, afterTree);
937
+ try {
938
+ const path = this.turnDiffPath(thread.id, turnId);
939
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
940
+ writeFileSync(path, JSON.stringify(diff), { mode: 0o600 });
941
+ }
942
+ catch {
943
+ }
944
+ return diff;
945
+ }
946
+ readTurnDiff(owner, threadId, turnId) {
947
+ const thread = this.getThreadRecord(owner, threadId);
948
+ if (!thread)
949
+ return null;
950
+ const turns = this.loadTurns(thread.id);
951
+ if (turns.length === 0)
952
+ return { ...EMPTY_DIFF };
953
+ let target;
954
+ if (turnId && HEX32.test(turnId)) {
955
+ target = turns.find(one => one.id === turnId);
956
+ }
957
+ else {
958
+ target = turns.at(-1);
959
+ }
960
+ if (!target)
961
+ return null;
962
+ if (target.status === "running") {
963
+ const beforeTree = this.preTurnTreeSha.get(target.id);
964
+ const binding = this.bindingOf(thread);
965
+ if (beforeTree && binding) {
966
+ const currentTree = snapshotCloneTree(binding);
967
+ if (currentTree)
968
+ return readTreeRangeDiff(binding, beforeTree, currentTree);
969
+ }
970
+ return { ...EMPTY_DIFF };
971
+ }
972
+ const savedPath = this.turnDiffPath(thread.id, target.id);
973
+ if (existsSync(savedPath)) {
974
+ try {
975
+ const parsed = JSON.parse(readFileSync(savedPath, "utf8"));
976
+ return {
977
+ changedFiles: Array.isArray(parsed.changedFiles) ? parsed.changedFiles.filter((x) => typeof x === "string") : [],
978
+ diffText: typeof parsed.diffText === "string" ? parsed.diffText : "",
979
+ dirty: parsed.dirty === true,
980
+ };
981
+ }
982
+ catch {
983
+ }
984
+ }
985
+ if (turns.length === 1) {
986
+ return this.refreshDiffCache(thread);
987
+ }
988
+ return { ...EMPTY_DIFF };
989
+ }
990
+ getThreadRecord(owner, threadId) {
991
+ if (!HEX32.test(threadId))
992
+ return null;
993
+ const raw = this.store.handle
994
+ .prepare(`SELECT * FROM direct_chat_thread WHERE id = ? AND owner = ? AND archived_at IS NULL`)
995
+ .get(threadId, owner);
996
+ return raw ? this.mapThread(raw) : null;
997
+ }
998
+ listThreads(owner, projectFilter) {
999
+ const rows = this.store.handle
1000
+ .prepare(`SELECT * FROM direct_chat_thread WHERE owner = ? AND archived_at IS NULL ORDER BY updated_at DESC LIMIT 80`)
1001
+ .all(owner);
1002
+ const out = [];
1003
+ for (const raw of rows) {
1004
+ const thread = this.mapThread(raw);
1005
+ if (projectFilter && projectFilter !== "" && thread.project.toLowerCase() !== projectFilter.toLowerCase() && thread.repo !== projectFilter) {
1006
+ continue;
1007
+ }
1008
+ const last = this.store.handle
1009
+ .prepare(`SELECT status FROM direct_chat_turn WHERE thread_id = ? ORDER BY seq DESC LIMIT 1`)
1010
+ .get(thread.id);
1011
+ const lastStatus = (typeof last?.["status"] === "string" ? last["status"] : null);
1012
+ out.push({
1013
+ ...thread,
1014
+ running: lastStatus === "running",
1015
+ lastStatus,
1016
+ changedFilesCount: thread.diffCache.changedFiles.length,
1017
+ });
1018
+ }
1019
+ return out;
1020
+ }
1021
+ getThread(owner, threadId) {
1022
+ if (!HEX32.test(threadId))
1023
+ return null;
1024
+ const raw = this.store.handle
1025
+ .prepare(`SELECT * FROM direct_chat_thread WHERE id = ? AND owner = ? AND archived_at IS NULL`)
1026
+ .get(threadId, owner);
1027
+ if (!raw)
1028
+ return null;
1029
+ const thread = this.mapThread(raw);
1030
+ const turns = this.loadTurns(thread.id);
1031
+ const attachments = listArtifactsForThread(this.store, thread.id).filter(a => a.kind === "attachment");
1032
+ const running = turns.some(t => t.status === "running");
1033
+ return { thread, turns, attachments, diff: thread.diffCache, running };
1034
+ }
1035
+ attachFile(input) {
1036
+ if (!HEX32.test(input.threadId))
1037
+ return { ok: false, status: 400, error: "Invalid thread id." };
1038
+ const thread = this.getThreadRecord(input.owner, input.threadId);
1039
+ if (!thread)
1040
+ return { ok: false, status: 404, error: "Chat thread not found." };
1041
+ const managed = assertManagedClonePath(this.stateRoot, thread.clonePath);
1042
+ if (!managed.ok)
1043
+ return { ok: false, status: 409, error: managed.error };
1044
+ const saved = saveDirectChatArtifact(this.store, {
1045
+ stateRoot: this.stateRoot,
1046
+ threadId: thread.id,
1047
+ turnId: null,
1048
+ kind: "attachment",
1049
+ filename: input.filename,
1050
+ mimeType: input.mimeType,
1051
+ bytes: input.bytes,
1052
+ clonePath: thread.clonePath,
1053
+ gitDir: thread.gitDir,
1054
+ now: this.now(),
1055
+ });
1056
+ if (saved.ok) {
1057
+ this.store.handle.prepare(`UPDATE direct_chat_thread SET updated_at = ? WHERE id = ?`).run(this.now().toISOString(), thread.id);
1058
+ this.onNotify({ threadId: thread.id, turnId: null, event: "change" });
1059
+ }
1060
+ return saved;
1061
+ }
1062
+ getArtifact(owner, threadId, artifactId) {
1063
+ if (!HEX32.test(threadId) || !HEX32.test(artifactId))
1064
+ return null;
1065
+ const raw = this.store.handle
1066
+ .prepare(`SELECT id FROM direct_chat_thread WHERE id = ? AND owner = ? AND archived_at IS NULL`)
1067
+ .get(threadId, owner);
1068
+ if (!raw)
1069
+ return null;
1070
+ return getDirectChatArtifact(this.store, this.stateRoot, threadId, artifactId);
1071
+ }
1072
+ applyMainEdits(owner, threadId) {
1073
+ if (!HEX32.test(threadId))
1074
+ return { ok: false, status: 400, error: "Invalid thread id." };
1075
+ const thread = this.getThreadRecord(owner, threadId);
1076
+ if (!thread)
1077
+ return { ok: false, status: 404, error: "Chat thread not found." };
1078
+ const binding = this.bindingOf(thread);
1079
+ if (binding === null)
1080
+ return { ok: false, status: 409, error: "This chat has no isolated clone workspace (read-only)." };
1081
+ const active = this.store.handle
1082
+ .prepare(`SELECT id FROM direct_chat_turn WHERE thread_id = ? AND status = 'running' LIMIT 1`)
1083
+ .get(thread.id);
1084
+ if (active)
1085
+ return { ok: false, status: 409, error: "Stop the running turn before bringing in uncommitted edits." };
1086
+ const res = applyMainDirtyPatch({ repo: thread.repo, binding });
1087
+ if (res.ok) {
1088
+ const stamp = this.now().toISOString();
1089
+ this.store.handle.prepare(`UPDATE direct_chat_thread SET main_dirty_files = NULL, updated_at = ? WHERE id = ?`).run(stamp, thread.id);
1090
+ this.refreshDiffCache(thread);
1091
+ this.onNotify({ threadId: thread.id, turnId: null, event: "change" });
1092
+ }
1093
+ return res;
1094
+ }
1095
+ repairCloneGit(owner, threadId) {
1096
+ if (!HEX32.test(threadId))
1097
+ return { ok: false, status: 400, error: "Invalid thread id." };
1098
+ const thread = this.getThreadRecord(owner, threadId);
1099
+ if (!thread)
1100
+ return { ok: false, status: 404, error: "Chat thread not found." };
1101
+ if (thread.isLegacy) {
1102
+ return { ok: false, status: 409, error: "Imported chats are read-only history." };
1103
+ }
1104
+ const active = this.store.handle
1105
+ .prepare(`SELECT id FROM direct_chat_turn WHERE thread_id = ? AND status = 'running' LIMIT 1`)
1106
+ .get(thread.id);
1107
+ if (active)
1108
+ return { ok: false, status: 409, error: "Stop the running turn before repairing the workspace git binding." };
1109
+ const binding = this.bindingOf(thread);
1110
+ if (binding === null)
1111
+ return { ok: false, status: 409, error: "This chat has no isolated clone workspace (read-only)." };
1112
+ const repaired = repairCloneGitBinding(binding);
1113
+ if (!repaired.ok)
1114
+ return { ok: false, status: 409, error: repaired.error };
1115
+ const stamp = this.now().toISOString();
1116
+ this.store.handle.prepare(`UPDATE direct_chat_thread SET updated_at = ? WHERE id = ?`).run(stamp, thread.id);
1117
+ this.refreshDiffCache(thread);
1118
+ this.onNotify({ threadId: thread.id, turnId: null, event: "change" });
1119
+ return { ok: true, said: "Workspace git binding repaired." };
1120
+ }
1121
+ async createThread(input) {
1122
+ const trimmedPrompt = input.prompt.trim();
1123
+ if (trimmedPrompt === "")
1124
+ return { ok: false, status: 400, error: "Write a message to start a chat." };
1125
+ if (!HEX32.test(input.requestId))
1126
+ return { ok: false, status: 400, error: "Invalid request id." };
1127
+ const dedupeKey = `${input.owner}:${input.requestId}`;
1128
+ const existingPromise = this.inFlightCreates.get(dedupeKey);
1129
+ if (existingPromise !== undefined) {
1130
+ return existingPromise;
1131
+ }
1132
+ const work = this.createThreadImpl(input, trimmedPrompt);
1133
+ this.inFlightCreates.set(dedupeKey, work);
1134
+ try {
1135
+ return await work;
1136
+ }
1137
+ finally {
1138
+ this.inFlightCreates.delete(dedupeKey);
1139
+ }
1140
+ }
1141
+ async createThreadImpl(input, trimmedPrompt) {
1142
+ const existing = this.store.handle
1143
+ .prepare(`SELECT * FROM direct_chat_thread WHERE owner = ? AND create_request_id = ?`)
1144
+ .get(input.owner, input.requestId);
1145
+ if (existing) {
1146
+ const thread = this.mapThread(existing);
1147
+ const turns = this.loadTurns(thread.id);
1148
+ if (turns[0])
1149
+ return { ok: true, thread, turn: turns[0], created: false };
1150
+ }
1151
+ const binary = this.locateBinary(input.provider);
1152
+ if (binary === null) {
1153
+ return { ok: false, status: 409, error: `${input.provider} CLI is not installed on this computer.` };
1154
+ }
1155
+ const threadId = randomBytes(16).toString("hex");
1156
+ const shortId = threadId.slice(0, 8);
1157
+ const safeRepo = basename(input.repo).replace(/[^A-Za-z0-9._-]/g, "_") || "repo";
1158
+ const clonePath = join(this.stateRoot, "direct-chat", "clones", `${safeRepo}-${shortId}`);
1159
+ const gitDir = join(this.stateRoot, "direct-chat", "gitdirs", threadId);
1160
+ const branch = `toolroll/chat-${shortId}`;
1161
+ let baseSha;
1162
+ let resolvedGitDir;
1163
+ let configSha256;
1164
+ let mainDirtyFiles;
1165
+ try {
1166
+ const prep = await this.prepareCloneFn({ stateRoot: this.stateRoot, repo: input.repo, clonePath, gitDir, branch });
1167
+ baseSha = prep.baseSha;
1168
+ resolvedGitDir = prep.gitDir;
1169
+ configSha256 = prep.configSha256;
1170
+ mainDirtyFiles = prep.mainDirtyFiles;
1171
+ }
1172
+ catch (error) {
1173
+ try {
1174
+ if (existsSync(clonePath))
1175
+ rmSync(clonePath, { recursive: true, force: true });
1176
+ if (existsSync(gitDir))
1177
+ rmSync(gitDir, { recursive: true, force: true });
1178
+ const backup = pinnedConfigBackupPath(gitDir);
1179
+ if (existsSync(backup))
1180
+ rmSync(backup, { force: true });
1181
+ }
1182
+ catch {
1183
+ }
1184
+ return { ok: false, status: 500, error: `Could not prepare isolated clone: ${error instanceof Error ? error.message : String(error)}` };
1185
+ }
1186
+ const firstLine = trimmedPrompt.split(/\r?\n/)[0]?.trim() ?? trimmedPrompt;
1187
+ const title = sanitizeLine(firstLine.slice(0, 72)) || "New chat";
1188
+ const modelId = (input.modelId && input.modelId.trim() !== "") ? input.modelId.trim() : defaultModelForProvider(input.provider);
1189
+ const effort = normalizeDirectChatEffort(input.effort, input.provider) ?? "";
1190
+ const stamp = this.now().toISOString();
1191
+ this.store.handle.prepare(`
1192
+ INSERT INTO direct_chat_thread (
1193
+ id, owner, local_generation, account_generation, create_request_id,
1194
+ title, repo, clone_path, git_dir, config_sha256, diff_cache_json, is_legacy,
1195
+ branch, base_sha, provider, model_id, effort,
1196
+ provider_session_id, main_dirty_files, archived_at, created_at, updated_at
1197
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?, ?, NULL, ?, NULL, ?, ?)
1198
+ `).run(threadId, input.owner, input.localGeneration, input.accountGeneration, input.requestId, title, input.repo, clonePath, resolvedGitDir, configSha256, JSON.stringify(EMPTY_DIFF), branch, baseSha, input.provider, modelId, effort, mainDirtyFiles.length > 0 ? JSON.stringify(mainDirtyFiles) : null, stamp, stamp);
1199
+ const started = await this.sendMessage({
1200
+ owner: input.owner,
1201
+ threadId,
1202
+ requestId: input.requestId,
1203
+ prompt: trimmedPrompt,
1204
+ });
1205
+ if (!started.ok) {
1206
+ return started;
1207
+ }
1208
+ const thread = this.mapThread(this.store.handle.prepare(`SELECT * FROM direct_chat_thread WHERE id = ?`).get(threadId));
1209
+ return { ok: true, thread, turn: started.turn, created: true };
1210
+ }
1211
+ async sendMessage(input) {
1212
+ const thread = HEX32.test(input.threadId) ? this.getThreadRecord(input.owner, input.threadId) : null;
1213
+ if (thread === null || thread.provider !== "claude" || thread.isLegacy || this.fenceTurnFn === null)
1214
+ return this.sendMessageNow(input, null);
1215
+ if (thread.gitDir === null)
1216
+ return { ok: false, status: 409, error: "This chat has no isolated Git folder, so its agent can't be fenced. Start a new chat instead." };
1217
+ const known = this.store.handle.prepare(`SELECT 1 FROM direct_chat_turn WHERE thread_id = ? AND request_id = ?`).get(thread.id, input.requestId);
1218
+ if (known !== undefined)
1219
+ return this.sendMessageNow(input, null);
1220
+ const made = await this.fenceTurnFn({ stateRoot: this.stateRoot, repo: thread.repo, clone: thread.clonePath, gitDir: thread.gitDir });
1221
+ if ("problem" in made)
1222
+ return { ok: false, status: 409, error: made.problem };
1223
+ const fence = "unfenced" in made ? null : made;
1224
+ let started;
1225
+ try {
1226
+ started = this.sendMessageNow(input, fence);
1227
+ }
1228
+ catch (error) {
1229
+ if (fence !== null)
1230
+ await fence.close();
1231
+ throw error;
1232
+ }
1233
+ if (fence !== null && (!started.ok || !started.created))
1234
+ await fence.close();
1235
+ return started;
1236
+ }
1237
+ sendMessageNow(input, fence) {
1238
+ if (!HEX32.test(input.threadId) || !HEX32.test(input.requestId)) {
1239
+ return { ok: false, status: 400, error: "Invalid thread or request id." };
1240
+ }
1241
+ const trimmed = input.prompt.trim();
1242
+ if (trimmed === "")
1243
+ return { ok: false, status: 400, error: "Write a message first." };
1244
+ const thread = this.getThreadRecord(input.owner, input.threadId);
1245
+ if (!thread)
1246
+ return { ok: false, status: 404, error: "Chat thread not found." };
1247
+ if (thread.isLegacy) {
1248
+ return { ok: false, status: 409, error: "Imported chats are read-only history. Start a new chat to continue." };
1249
+ }
1250
+ const managed = assertManagedClonePath(this.stateRoot, thread.clonePath);
1251
+ if (!managed.ok)
1252
+ return { ok: false, status: 409, error: managed.error };
1253
+ const dupTurn = this.store.handle
1254
+ .prepare(`SELECT * FROM direct_chat_turn WHERE thread_id = ? AND request_id = ?`)
1255
+ .get(thread.id, input.requestId);
1256
+ if (dupTurn) {
1257
+ return { ok: true, turn: this.mapTurn(dupTurn), created: false };
1258
+ }
1259
+ const active = this.store.handle
1260
+ .prepare(`SELECT id FROM direct_chat_turn WHERE thread_id = ? AND status = 'running' LIMIT 1`)
1261
+ .get(thread.id);
1262
+ if (active) {
1263
+ return { ok: false, status: 409, error: "A turn is already running or stopping in this chat." };
1264
+ }
1265
+ const binary = this.locateBinary(thread.provider);
1266
+ if (binary === null) {
1267
+ return { ok: false, status: 409, error: `${thread.provider} CLI is not installed on this computer.` };
1268
+ }
1269
+ const priorTurns = this.loadTurns(thread.id);
1270
+ const nextSeq = (priorTurns.at(-1)?.seq ?? 0) + 1;
1271
+ const turnId = randomBytes(16).toString("hex");
1272
+ const logPath = join(this.stateRoot, "direct-chat", "turns", thread.id, `${turnId}.jsonl`);
1273
+ const stderrPath = join(this.stateRoot, "direct-chat", "turns", thread.id, `${turnId}.stderr`);
1274
+ const isFirstForProvider = thread.providerSessionId === null || thread.providerSessionId === "";
1275
+ const effectivePrompt = buildTurnPrompt({
1276
+ userPrompt: trimmed,
1277
+ branch: thread.branch,
1278
+ isFirstTurnForProvider: isFirstForProvider,
1279
+ priorTurns: priorTurns.filter(t => t.assistantText !== "" || t.userPrompt !== ""),
1280
+ });
1281
+ const args = buildProviderCommand({
1282
+ provider: thread.provider,
1283
+ modelId: thread.modelId,
1284
+ effort: thread.effort,
1285
+ prompt: effectivePrompt,
1286
+ sessionId: thread.providerSessionId,
1287
+ });
1288
+ const stamp = this.now().toISOString();
1289
+ const beforeImages = snapshotWorkspaceImages(thread.clonePath);
1290
+ const bindingForTree = this.bindingOf(thread);
1291
+ const beforeTree = bindingForTree ? snapshotCloneTree(bindingForTree) : null;
1292
+ const switchedFrom = this.pendingSwitchFrom.get(thread.id) ?? null;
1293
+ this.store.handle.prepare(`
1294
+ INSERT INTO direct_chat_turn (
1295
+ id, thread_id, seq, request_id, user_prompt, switched_from_provider,
1296
+ log_path, stderr_path, byte_offset, pid, start_identity, pgid, boot_id,
1297
+ status, stop_requested_at, assistant_text, error_text, created_at, finished_at
1298
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0, NULL, NULL, NULL, ?, 'running', NULL, '', NULL, ?, NULL)
1299
+ `).run(turnId, thread.id, nextSeq, input.requestId, trimmed, switchedFrom, logPath, stderrPath, this.bootId(), stamp);
1300
+ let launched;
1301
+ try {
1302
+ launched = this.spawnTurnFn({
1303
+ binary,
1304
+ args,
1305
+ cwd: managed.realClone,
1306
+ env: buildSanitizedChildEnv(thread.provider),
1307
+ logPath,
1308
+ stderrPath,
1309
+ ...(fence === null ? {} : { fence }),
1310
+ });
1311
+ }
1312
+ catch (error) {
1313
+ const msg = `Could not launch ${thread.provider}: ${error instanceof Error ? error.message : String(error)}`;
1314
+ this.store.handle.prepare(`
1315
+ UPDATE direct_chat_turn SET status = 'failed', error_text = ?, finished_at = ? WHERE id = ?
1316
+ `).run(msg, this.now().toISOString(), turnId);
1317
+ return { ok: false, status: 500, error: msg };
1318
+ }
1319
+ this.pendingSwitchFrom.delete(thread.id);
1320
+ this.preTurnImages.set(turnId, beforeImages);
1321
+ if (beforeTree !== null) {
1322
+ this.preTurnTreeSha.set(turnId, beforeTree);
1323
+ }
1324
+ if (fence !== null)
1325
+ this.turnFences.set(turnId, fence.close);
1326
+ this.store.handle.prepare(`
1327
+ UPDATE direct_chat_turn SET pid = ?, start_identity = ?, pgid = ? WHERE id = ?
1328
+ `).run(launched.pid, launched.startIdentity, launched.pgid, turnId);
1329
+ this.store.handle.prepare(`UPDATE direct_chat_thread SET updated_at = ? WHERE id = ?`).run(stamp, thread.id);
1330
+ this.onNotify({ threadId: thread.id, turnId, event: "change" });
1331
+ const createdRow = this.store.handle.prepare(`SELECT * FROM direct_chat_turn WHERE id = ?`).get(turnId);
1332
+ return { ok: true, turn: this.mapTurn(createdRow), created: true };
1333
+ }
1334
+ switchModel(input) {
1335
+ if (!HEX32.test(input.threadId))
1336
+ return { ok: false, status: 400, error: "Invalid thread id." };
1337
+ const raw = this.store.handle
1338
+ .prepare(`SELECT * FROM direct_chat_thread WHERE id = ? AND owner = ? AND archived_at IS NULL`)
1339
+ .get(input.threadId, input.owner);
1340
+ if (!raw)
1341
+ return { ok: false, status: 404, error: "Chat thread not found." };
1342
+ const thread = this.mapThread(raw);
1343
+ const active = this.store.handle
1344
+ .prepare(`SELECT id FROM direct_chat_turn WHERE thread_id = ? AND status = 'running' LIMIT 1`)
1345
+ .get(thread.id);
1346
+ if (active)
1347
+ return { ok: false, status: 409, error: "Stop the running turn before switching models." };
1348
+ const providerChanged = thread.provider !== input.provider;
1349
+ if (providerChanged) {
1350
+ this.pendingSwitchFrom.set(thread.id, thread.provider);
1351
+ }
1352
+ const nextModel = input.modelId.trim() !== "" ? input.modelId.trim() : defaultModelForProvider(input.provider);
1353
+ const nextEffort = input.effort !== undefined
1354
+ ? (normalizeDirectChatEffort(input.effort, input.provider) ?? "")
1355
+ : (thread.effort ?? "");
1356
+ const stamp = this.now().toISOString();
1357
+ this.store.handle.prepare(`
1358
+ UPDATE direct_chat_thread
1359
+ SET provider = ?, model_id = ?, effort = ?, provider_session_id = ?, updated_at = ?
1360
+ WHERE id = ?
1361
+ `).run(input.provider, nextModel, nextEffort, providerChanged ? null : thread.providerSessionId, stamp, thread.id);
1362
+ this.onNotify({ threadId: thread.id, turnId: null, event: "change" });
1363
+ const updated = this.store.handle.prepare(`SELECT * FROM direct_chat_thread WHERE id = ?`).get(thread.id);
1364
+ return { ok: true, thread: this.mapThread(updated) };
1365
+ }
1366
+ stopThread(owner, threadId) {
1367
+ if (!HEX32.test(threadId))
1368
+ return { ok: false, status: 400, error: "Invalid thread id." };
1369
+ const thread = this.getThreadRecord(owner, threadId);
1370
+ if (!thread)
1371
+ return { ok: false, status: 404, error: "Chat thread not found." };
1372
+ const running = this.store.handle
1373
+ .prepare(`SELECT * FROM direct_chat_turn WHERE thread_id = ? AND status = 'running' ORDER BY seq DESC LIMIT 1`)
1374
+ .get(threadId);
1375
+ if (!running)
1376
+ return { ok: true, stopped: false, stopping: false };
1377
+ const turn = this.mapTurn(running);
1378
+ const stamp = this.now().toISOString();
1379
+ if (turn.stopRequestedAt === null) {
1380
+ this.store.handle
1381
+ .prepare(`UPDATE direct_chat_turn SET stop_requested_at = ? WHERE id = ? AND status = 'running'`)
1382
+ .run(stamp, turn.id);
1383
+ }
1384
+ const updatedTurn = this.reloadTurn(turn.id) ?? { ...turn, stopRequestedAt: turn.stopRequestedAt ?? stamp };
1385
+ const beforeStop = this.assessTurnCustody(updatedTurn, this.custody.table());
1386
+ if (beforeStop.state === "alive" && beforeStop.members.length > 0) {
1387
+ this.custody.signal(beforeStop.members, "SIGTERM");
1388
+ }
1389
+ const afterTable = this.custody.table();
1390
+ this.reconcileSingleTurn(thread, updatedTurn, afterTable);
1391
+ const latest = this.reloadTurn(turn.id);
1392
+ const finished = latest !== null && latest.status !== "running";
1393
+ return { ok: true, stopped: finished, stopping: !finished };
1394
+ }
1395
+ deleteThread(input) {
1396
+ if (!HEX32.test(input.threadId))
1397
+ return { ok: false, status: 400, error: "Invalid thread id." };
1398
+ const thread = this.getThreadRecord(input.owner, input.threadId);
1399
+ if (!thread)
1400
+ return { ok: false, status: 404, error: "Chat thread not found." };
1401
+ const active = this.store.handle
1402
+ .prepare(`SELECT id FROM direct_chat_turn WHERE thread_id = ? AND status = 'running' LIMIT 1`)
1403
+ .get(thread.id);
1404
+ if (active) {
1405
+ const stopAttempt = this.stopThread(input.owner, thread.id);
1406
+ if (!stopAttempt.ok)
1407
+ return stopAttempt;
1408
+ if (stopAttempt.stopping) {
1409
+ return {
1410
+ ok: false,
1411
+ status: 409,
1412
+ code: "turn_stopping",
1413
+ error: "This chat's agent is still stopping. Wait a moment for it to exit, then delete.",
1414
+ };
1415
+ }
1416
+ }
1417
+ if (!input.discardChanges && !input.keepClone) {
1418
+ if (this.hasUnmergedChanges(thread)) {
1419
+ return {
1420
+ ok: false,
1421
+ status: 409,
1422
+ code: "unmerged_changes",
1423
+ error: "This chat has unmerged changes. Confirm discarding changes or choose to keep the branch.",
1424
+ };
1425
+ }
1426
+ }
1427
+ const stamp = this.now().toISOString();
1428
+ this.store.handle.prepare(`UPDATE direct_chat_thread SET archived_at = ?, updated_at = ? WHERE id = ?`).run(stamp, stamp, thread.id);
1429
+ let removedClone = false;
1430
+ if (!input.keepClone) {
1431
+ const managed = assertManagedClonePath(this.stateRoot, thread.clonePath);
1432
+ if (managed.ok) {
1433
+ this.scheduleAsyncDelete(managed.realClone);
1434
+ removedClone = true;
1435
+ }
1436
+ if (thread.gitDir && existsSync(thread.gitDir)) {
1437
+ const gitDirsRoot = join(this.stateRoot, "direct-chat", "gitdirs");
1438
+ if (existsSync(gitDirsRoot)) {
1439
+ try {
1440
+ const realRoot = realpathSync(gitDirsRoot);
1441
+ const realGd = realpathSync(thread.gitDir);
1442
+ const rel = relative(realRoot, realGd);
1443
+ if (rel !== "" && rel !== ".." && !rel.startsWith(`..${"/"}`) && !isAbsolute(rel)) {
1444
+ this.scheduleAsyncDelete(realGd);
1445
+ const backup = pinnedConfigBackupPath(realGd);
1446
+ if (existsSync(backup))
1447
+ this.scheduleAsyncDelete(backup);
1448
+ }
1449
+ }
1450
+ catch {
1451
+ }
1452
+ }
1453
+ }
1454
+ }
1455
+ this.onNotify({ threadId: thread.id, turnId: null, event: "change" });
1456
+ return { ok: true, removedClone };
1457
+ }
1458
+ drainRunningTurnLogs() {
1459
+ const runningRows = this.store.handle
1460
+ .prepare(`SELECT t.* FROM direct_chat_turn t JOIN direct_chat_thread th ON th.id = t.thread_id WHERE t.status = 'running' AND th.archived_at IS NULL`)
1461
+ .all();
1462
+ if (runningRows.length === 0)
1463
+ return;
1464
+ for (const rawTurn of runningRows) {
1465
+ const turn = this.mapTurn(rawTurn);
1466
+ const rawThread = this.store.handle
1467
+ .prepare(`SELECT * FROM direct_chat_thread WHERE id = ?`)
1468
+ .get(turn.threadId);
1469
+ if (!rawThread)
1470
+ continue;
1471
+ const thread = this.mapThread(rawThread);
1472
+ const advanced = this.drainTurnLog(thread, turn, false);
1473
+ if (!advanced)
1474
+ continue;
1475
+ const latest = this.reloadTurn(turn.id) ?? turn;
1476
+ if (latest.status !== "running") {
1477
+ const preImages = this.preTurnImages.get(turn.id);
1478
+ const sinceMs = Date.parse(turn.createdAt);
1479
+ captureNewWorkspaceArtifacts(this.store, {
1480
+ stateRoot: this.stateRoot,
1481
+ threadId: thread.id,
1482
+ turnId: turn.id,
1483
+ clonePath: thread.clonePath,
1484
+ ...(preImages !== undefined ? { before: preImages } : Number.isFinite(sinceMs) ? { sinceMs } : {}),
1485
+ now: this.now(),
1486
+ });
1487
+ this.captureTurnDiff(thread, turn.id);
1488
+ const freshDiff = this.refreshDiffCache(thread);
1489
+ this.notifyOwnerLeadThread(thread, turn.id, latest.status, latest.assistantText, latest.errorText, freshDiff, this.now());
1490
+ this.cleanupTurnState(turn.id);
1491
+ this.onNotify({ threadId: thread.id, turnId: turn.id, event: "change" });
1492
+ }
1493
+ else {
1494
+ this.onNotify({ threadId: thread.id, turnId: turn.id, event: "turn" });
1495
+ }
1496
+ }
1497
+ }
1498
+ reconcileRunningTurns() {
1499
+ const runningRows = this.store.handle
1500
+ .prepare(`SELECT t.* FROM direct_chat_turn t JOIN direct_chat_thread th ON th.id = t.thread_id WHERE t.status = 'running' AND th.archived_at IS NULL`)
1501
+ .all();
1502
+ if (runningRows.length === 0)
1503
+ return;
1504
+ const tableSnapshot = this.custody.table();
1505
+ for (const rawTurn of runningRows) {
1506
+ const turn = this.mapTurn(rawTurn);
1507
+ const rawThread = this.store.handle
1508
+ .prepare(`SELECT * FROM direct_chat_thread WHERE id = ?`)
1509
+ .get(turn.threadId);
1510
+ if (!rawThread)
1511
+ continue;
1512
+ this.reconcileSingleTurn(this.mapThread(rawThread), turn, tableSnapshot);
1513
+ }
1514
+ }
1515
+ assessTurnCustody(turn, tableSnapshot) {
1516
+ if (turn.pid === null)
1517
+ return { state: "dead", members: [] };
1518
+ const curBoot = this.bootId();
1519
+ if (turn.bootId !== null && provenDeadByBootChange({ host: hostname(), bootId: turn.bootId }, { host: hostname(), bootId: curBoot })) {
1520
+ return { state: "dead", members: [] };
1521
+ }
1522
+ if (tableSnapshot === null)
1523
+ return { state: "unknown", members: [] };
1524
+ if (turn.startIdentity === null) {
1525
+ const row = tableSnapshot.find(one => one.pid === turn.pid && !one.zombie);
1526
+ return row ? { state: "unknown", members: [] } : { state: "dead", members: [] };
1527
+ }
1528
+ const launch = {
1529
+ host: hostname(),
1530
+ machineId: null,
1531
+ bootId: turn.bootId,
1532
+ leader: { pid: turn.pid, start: turn.startIdentity },
1533
+ namespaces: [],
1534
+ witnesses: [{ pid: turn.pid, start: turn.startIdentity }],
1535
+ folder: "",
1536
+ };
1537
+ const scan = scanCustody(launch, {
1538
+ ...this.custody,
1539
+ table: () => tableSnapshot,
1540
+ }, { holders: false });
1541
+ if (scan.incomplete !== null)
1542
+ return { state: "unknown", members: [] };
1543
+ if (scan.members.length > 0) {
1544
+ return {
1545
+ state: "alive",
1546
+ members: scan.members.map(m => ({ pid: m.pid, start: m.start })),
1547
+ };
1548
+ }
1549
+ return { state: "dead", members: [] };
1550
+ }
1551
+ reconcileSingleTurn(thread, turn, tableSnapshot) {
1552
+ const advanced = this.drainTurnLog(thread, turn, false);
1553
+ const custodyState = this.assessTurnCustody(turn, tableSnapshot);
1554
+ if (custodyState.state === "alive" || custodyState.state === "unknown") {
1555
+ if (turn.stopRequestedAt !== null && custodyState.state === "alive" && custodyState.members.length > 0) {
1556
+ const elapsedMs = this.now().getTime() - Date.parse(turn.stopRequestedAt);
1557
+ if (Number.isFinite(elapsedMs) && elapsedMs >= this.stopGraceMs) {
1558
+ this.custody.signal(custodyState.members, "SIGKILL");
1559
+ }
1560
+ }
1561
+ const latestAfterDrain = this.reloadTurn(turn.id) ?? turn;
1562
+ const missingIdentityExpiredStop = custodyState.state === "unknown"
1563
+ && turn.startIdentity === null
1564
+ && latestAfterDrain.stopRequestedAt !== null
1565
+ && Number.isFinite(this.now().getTime() - Date.parse(latestAfterDrain.stopRequestedAt))
1566
+ && (this.now().getTime() - Date.parse(latestAfterDrain.stopRequestedAt)) >= this.stopGraceMs;
1567
+ const missingIdentityTerminalLog = custodyState.state === "unknown"
1568
+ && turn.startIdentity === null
1569
+ && latestAfterDrain.status !== "running";
1570
+ if (!missingIdentityExpiredStop && !missingIdentityTerminalLog) {
1571
+ if (advanced) {
1572
+ this.onNotify({ threadId: thread.id, turnId: turn.id, event: "turn" });
1573
+ }
1574
+ return;
1575
+ }
1576
+ if (missingIdentityExpiredStop && latestAfterDrain.status === "running") {
1577
+ this.drainTurnLog(thread, latestAfterDrain, true);
1578
+ const stamp = this.now().toISOString();
1579
+ this.store.handle.prepare(`
1580
+ UPDATE direct_chat_turn
1581
+ SET status = 'interrupted', error_text = COALESCE(error_text, ?), finished_at = ?
1582
+ WHERE id = ? AND status = 'running'
1583
+ `).run("Stopped without verified process identity; check if an agent process is still running.", stamp, turn.id);
1584
+ this.store.handle.prepare(`
1585
+ UPDATE direct_chat_tool SET status = 'done', updated_at = ? WHERE turn_id = ? AND status = 'running'
1586
+ `).run(stamp, turn.id);
1587
+ this.store.handle.prepare(`UPDATE direct_chat_thread SET updated_at = ? WHERE id = ?`).run(stamp, thread.id);
1588
+ }
1589
+ this.captureTurnDiff(thread, turn.id);
1590
+ const freshDiff = this.refreshDiffCache(thread);
1591
+ const settledLatest = this.reloadTurn(turn.id) ?? latestAfterDrain;
1592
+ if (settledLatest.status !== "running") {
1593
+ this.notifyOwnerLeadThread(thread, turn.id, settledLatest.status, settledLatest.assistantText, settledLatest.errorText, freshDiff, this.now());
1594
+ }
1595
+ this.cleanupTurnState(turn.id);
1596
+ this.onNotify({ threadId: thread.id, turnId: turn.id, event: "change" });
1597
+ return;
1598
+ }
1599
+ this.drainTurnLog(thread, this.reloadTurn(turn.id) ?? turn, true);
1600
+ const latest = this.reloadTurn(turn.id) ?? turn;
1601
+ const preImages = this.preTurnImages.get(turn.id);
1602
+ const sinceMs = Date.parse(turn.createdAt);
1603
+ captureNewWorkspaceArtifacts(this.store, {
1604
+ stateRoot: this.stateRoot,
1605
+ threadId: thread.id,
1606
+ turnId: turn.id,
1607
+ clonePath: thread.clonePath,
1608
+ ...(preImages !== undefined ? { before: preImages } : Number.isFinite(sinceMs) ? { sinceMs } : {}),
1609
+ now: this.now(),
1610
+ });
1611
+ this.captureTurnDiff(thread, turn.id);
1612
+ const refreshedDiff = this.refreshDiffCache(thread);
1613
+ if (latest.status !== "running") {
1614
+ this.notifyOwnerLeadThread(thread, turn.id, latest.status, latest.assistantText, latest.errorText, refreshedDiff, this.now());
1615
+ this.cleanupTurnState(turn.id);
1616
+ this.onNotify({ threadId: thread.id, turnId: turn.id, event: "change" });
1617
+ return;
1618
+ }
1619
+ const stamp = this.now().toISOString();
1620
+ const wasStopRequested = latest.stopRequestedAt !== null;
1621
+ let finalStatus = wasStopRequested ? "stopped" : "completed";
1622
+ let errorText = latest.errorText;
1623
+ if (!wasStopRequested && !this.sawTerminalByTurn.has(turn.id)) {
1624
+ const stderrTail = this.readStderrTail(latest.stderrPath);
1625
+ if (latest.assistantText.trim() === "" && stderrTail !== "") {
1626
+ finalStatus = "failed";
1627
+ errorText = sanitizeDisplay(stderrTail);
1628
+ }
1629
+ else if (latest.assistantText.trim() === "" && latest.tools.length === 0) {
1630
+ finalStatus = "interrupted";
1631
+ errorText = "Turn ended before a response was recorded.";
1632
+ }
1633
+ }
1634
+ const settled = this.store.handle.prepare(`
1635
+ UPDATE direct_chat_turn
1636
+ SET status = ?, error_text = ?, finished_at = ?
1637
+ WHERE id = ? AND status = 'running'
1638
+ `).run(finalStatus, errorText, stamp, turn.id);
1639
+ this.store.handle.prepare(`
1640
+ UPDATE direct_chat_tool
1641
+ SET status = 'done', updated_at = ?
1642
+ WHERE turn_id = ? AND status = 'running'
1643
+ `).run(stamp, turn.id);
1644
+ this.store.handle.prepare(`UPDATE direct_chat_thread SET updated_at = ? WHERE id = ?`).run(stamp, thread.id);
1645
+ const freshDiff = finalStatus === "completed" ? this.refreshDiffCache(thread) : null;
1646
+ if (Number(settled.changes) === 1) {
1647
+ this.notifyOwnerLeadThread(thread, turn.id, finalStatus, latest.assistantText, errorText, freshDiff, this.now());
1648
+ }
1649
+ this.cleanupTurnState(turn.id);
1650
+ this.onNotify({ threadId: thread.id, turnId: turn.id, event: "change" });
1651
+ }
1652
+ drainTurnLog(thread, turn, flushPartial = false) {
1653
+ if (!existsSync(turn.logPath))
1654
+ return false;
1655
+ let fileSize;
1656
+ try {
1657
+ fileSize = statSync(turn.logPath).size;
1658
+ }
1659
+ catch {
1660
+ return false;
1661
+ }
1662
+ if (fileSize <= turn.byteOffset)
1663
+ return false;
1664
+ const length = Math.min(fileSize - turn.byteOffset, MAX_LINE_BYTES);
1665
+ const buf = Buffer.allocUnsafe(length);
1666
+ let bytesRead = 0;
1667
+ const fd = openSync(turn.logPath, "r");
1668
+ try {
1669
+ bytesRead = readSync(fd, buf, 0, length, turn.byteOffset);
1670
+ }
1671
+ finally {
1672
+ closeSync(fd);
1673
+ }
1674
+ if (bytesRead <= 0)
1675
+ return false;
1676
+ const slice = buf.subarray(0, bytesRead);
1677
+ const lastNewline = slice.lastIndexOf(0x0a);
1678
+ let consumedBytes = 0;
1679
+ if (lastNewline >= 0) {
1680
+ consumedBytes = lastNewline + 1;
1681
+ }
1682
+ else if (flushPartial || bytesRead >= MAX_LINE_BYTES) {
1683
+ consumedBytes = bytesRead;
1684
+ }
1685
+ else {
1686
+ return false;
1687
+ }
1688
+ const nextOffset = turn.byteOffset + consumedBytes;
1689
+ const chunk = slice.subarray(0, consumedBytes).toString("utf8");
1690
+ const parts = chunk.split("\n");
1691
+ let changed = nextOffset !== turn.byteOffset;
1692
+ let assistantText = turn.assistantText;
1693
+ let turnUsage = turn.usage ? { ...turn.usage } : null;
1694
+ let usageUpdated = false;
1695
+ let nextStatus = turn.status;
1696
+ let errorText = turn.errorText;
1697
+ let finishedAt = turn.finishedAt;
1698
+ let nextSessionId = null;
1699
+ let ordinalCounter = turn.tools.length;
1700
+ const stamp = this.now().toISOString();
1701
+ for (const line of parts) {
1702
+ if (line.trim() === "")
1703
+ continue;
1704
+ const embeddedImages = extractBase64ImagesFromLine(line, thread.provider);
1705
+ for (const img of embeddedImages) {
1706
+ saveDirectChatArtifact(this.store, {
1707
+ stateRoot: this.stateRoot,
1708
+ threadId: thread.id,
1709
+ turnId: turn.id,
1710
+ kind: "output",
1711
+ filename: img.filename,
1712
+ bytes: img.bytes,
1713
+ now: this.now(),
1714
+ });
1715
+ changed = true;
1716
+ }
1717
+ const events = parseDirectChatLine(line, thread.provider);
1718
+ for (const ev of events) {
1719
+ changed = true;
1720
+ switch (ev.kind) {
1721
+ case "session_id":
1722
+ nextSessionId = ev.sessionId;
1723
+ break;
1724
+ case "message_start":
1725
+ if (assistantText !== "") {
1726
+ this.resetOnNextTextDelta.add(turn.id);
1727
+ }
1728
+ break;
1729
+ case "text_delta":
1730
+ if (this.resetOnNextTextDelta.has(turn.id)) {
1731
+ assistantText = "";
1732
+ this.resetOnNextTextDelta.delete(turn.id);
1733
+ }
1734
+ assistantText = sanitizeDisplay(assistantText + ev.delta);
1735
+ break;
1736
+ case "text_replace":
1737
+ this.resetOnNextTextDelta.delete(turn.id);
1738
+ assistantText = sanitizeDisplay(ev.text);
1739
+ break;
1740
+ case "usage": {
1741
+ const base = turnUsage ?? emptyUsage(defaultContextWindowFor(thread.provider, thread.modelId));
1742
+ const patch = ev.usage;
1743
+ if (ev.cumulative) {
1744
+ if (patch.inputTokens !== undefined)
1745
+ base.inputTokens = patch.inputTokens;
1746
+ if (patch.outputTokens !== undefined)
1747
+ base.outputTokens = patch.outputTokens;
1748
+ if (patch.cacheReadTokens !== undefined)
1749
+ base.cacheReadTokens = patch.cacheReadTokens;
1750
+ if (patch.cacheCreationTokens !== undefined)
1751
+ base.cacheCreationTokens = patch.cacheCreationTokens;
1752
+ if (patch.thinkingTokens !== undefined)
1753
+ base.thinkingTokens = patch.thinkingTokens;
1754
+ if (patch.contextTokens !== undefined && patch.contextTokens > 0)
1755
+ base.contextTokens = patch.contextTokens;
1756
+ if (patch.contextWindow !== undefined && patch.contextWindow !== null)
1757
+ base.contextWindow = patch.contextWindow;
1758
+ if (patch.costUsd !== undefined && patch.costUsd !== null)
1759
+ base.costUsd = patch.costUsd;
1760
+ }
1761
+ else {
1762
+ if (patch.contextTokens !== undefined && patch.contextTokens > 0)
1763
+ base.contextTokens = patch.contextTokens;
1764
+ if (patch.inputTokens !== undefined)
1765
+ base.inputTokens += patch.inputTokens;
1766
+ if (patch.outputTokens !== undefined)
1767
+ base.outputTokens += patch.outputTokens;
1768
+ if (patch.cacheReadTokens !== undefined)
1769
+ base.cacheReadTokens = Math.max(base.cacheReadTokens, patch.cacheReadTokens);
1770
+ if (patch.cacheCreationTokens !== undefined)
1771
+ base.cacheCreationTokens += patch.cacheCreationTokens;
1772
+ if (patch.contextWindow !== undefined && patch.contextWindow !== null)
1773
+ base.contextWindow = patch.contextWindow;
1774
+ }
1775
+ if (base.contextWindow === null) {
1776
+ base.contextWindow = defaultContextWindowFor(thread.provider, thread.modelId);
1777
+ }
1778
+ turnUsage = base;
1779
+ usageUpdated = true;
1780
+ break;
1781
+ }
1782
+ case "tool": {
1783
+ const existing = this.store.handle
1784
+ .prepare(`SELECT ordinal FROM direct_chat_tool WHERE turn_id = ? AND id = ?`)
1785
+ .get(turn.id, ev.id);
1786
+ const ord = typeof existing?.["ordinal"] === "number" ? existing["ordinal"] : ++ordinalCounter;
1787
+ this.store.handle.prepare(`
1788
+ INSERT INTO direct_chat_tool (id, turn_id, ordinal, name, detail, status, updated_at)
1789
+ VALUES (?, ?, ?, ?, ?, ?, ?)
1790
+ ON CONFLICT(turn_id, id) DO UPDATE SET
1791
+ name = excluded.name,
1792
+ detail = excluded.detail,
1793
+ status = excluded.status,
1794
+ updated_at = excluded.updated_at
1795
+ `).run(ev.id, turn.id, ord, sanitizeLine(ev.name), sanitizeLine(ev.detail), ev.status, stamp);
1796
+ break;
1797
+ }
1798
+ case "tool_status":
1799
+ this.store.handle.prepare(`
1800
+ UPDATE direct_chat_tool SET status = ?, updated_at = ? WHERE turn_id = ? AND id = ?
1801
+ `).run(ev.status, stamp, turn.id, ev.id);
1802
+ break;
1803
+ case "completed":
1804
+ this.sawTerminalByTurn.add(turn.id);
1805
+ nextStatus = "completed";
1806
+ finishedAt = stamp;
1807
+ this.store.handle.prepare(`
1808
+ UPDATE direct_chat_tool SET status = 'done', updated_at = ? WHERE turn_id = ? AND status = 'running'
1809
+ `).run(stamp, turn.id);
1810
+ break;
1811
+ case "failed":
1812
+ this.sawTerminalByTurn.add(turn.id);
1813
+ nextStatus = "failed";
1814
+ errorText = sanitizeDisplay(ev.message);
1815
+ finishedAt = stamp;
1816
+ break;
1817
+ }
1818
+ }
1819
+ }
1820
+ if (changed) {
1821
+ this.store.handle.prepare(`
1822
+ UPDATE direct_chat_turn
1823
+ SET byte_offset = ?, assistant_text = ?, status = ?, error_text = ?, finished_at = ?, usage_json = ?
1824
+ WHERE id = ?
1825
+ `).run(nextOffset, assistantText, nextStatus, errorText, finishedAt, turnUsage ? JSON.stringify(turnUsage) : null, turn.id);
1826
+ const threadUsageJson = usageUpdated ? this.recomputeThreadUsageJson(thread) : null;
1827
+ if (nextSessionId !== null && threadUsageJson !== null) {
1828
+ this.store.handle.prepare(`UPDATE direct_chat_thread SET provider_session_id = ?, usage_json = ?, updated_at = ? WHERE id = ?`)
1829
+ .run(nextSessionId, threadUsageJson, stamp, thread.id);
1830
+ }
1831
+ else if (nextSessionId !== null) {
1832
+ this.store.handle.prepare(`UPDATE direct_chat_thread SET provider_session_id = ?, updated_at = ? WHERE id = ?`)
1833
+ .run(nextSessionId, stamp, thread.id);
1834
+ }
1835
+ else if (threadUsageJson !== null) {
1836
+ this.store.handle.prepare(`UPDATE direct_chat_thread SET usage_json = ?, updated_at = ? WHERE id = ?`)
1837
+ .run(threadUsageJson, stamp, thread.id);
1838
+ }
1839
+ else {
1840
+ this.store.handle.prepare(`UPDATE direct_chat_thread SET updated_at = ? WHERE id = ?`).run(stamp, thread.id);
1841
+ }
1842
+ }
1843
+ return changed;
1844
+ }
1845
+ recomputeThreadUsageJson(thread) {
1846
+ const rows = this.store.handle
1847
+ .prepare(`SELECT usage_json FROM direct_chat_turn WHERE thread_id = ? AND usage_json IS NOT NULL ORDER BY seq ASC`)
1848
+ .all(thread.id);
1849
+ if (rows.length === 0)
1850
+ return null;
1851
+ const total = emptyUsage(defaultContextWindowFor(thread.provider, thread.modelId));
1852
+ let anyCost = false;
1853
+ let costSum = 0;
1854
+ for (const row of rows) {
1855
+ const u = parseUsageJson(row.usage_json);
1856
+ if (!u)
1857
+ continue;
1858
+ total.inputTokens += u.inputTokens;
1859
+ total.outputTokens += u.outputTokens;
1860
+ total.cacheReadTokens += u.cacheReadTokens;
1861
+ total.cacheCreationTokens += u.cacheCreationTokens;
1862
+ total.thinkingTokens += u.thinkingTokens;
1863
+ if (u.contextTokens > 0)
1864
+ total.contextTokens = u.contextTokens;
1865
+ if (u.contextWindow !== null)
1866
+ total.contextWindow = u.contextWindow;
1867
+ if (u.costUsd !== null) {
1868
+ anyCost = true;
1869
+ costSum += u.costUsd;
1870
+ }
1871
+ }
1872
+ total.costUsd = anyCost ? costSum : null;
1873
+ return JSON.stringify(total);
1874
+ }
1875
+ readStderrTail(stderrPath) {
1876
+ if (!existsSync(stderrPath))
1877
+ return "";
1878
+ try {
1879
+ const raw = readFileSync(stderrPath, "utf8");
1880
+ const lines = raw.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
1881
+ return lines.slice(-3).join("\n");
1882
+ }
1883
+ catch {
1884
+ return "";
1885
+ }
1886
+ }
1887
+ cleanupTurnState(turnId) {
1888
+ this.closeTurnFence(turnId);
1889
+ this.sawTerminalByTurn.delete(turnId);
1890
+ this.resetOnNextTextDelta.delete(turnId);
1891
+ this.preTurnImages.delete(turnId);
1892
+ this.preTurnTreeSha.delete(turnId);
1893
+ }
1894
+ reloadTurn(turnId) {
1895
+ const raw = this.store.handle.prepare(`SELECT * FROM direct_chat_turn WHERE id = ?`).get(turnId);
1896
+ return raw ? this.mapTurn(raw) : null;
1897
+ }
1898
+ loadTurns(threadId) {
1899
+ const rows = this.store.handle
1900
+ .prepare(`SELECT * FROM direct_chat_turn WHERE thread_id = ? ORDER BY seq ASC`)
1901
+ .all(threadId);
1902
+ return rows.map(row => this.mapTurn(row));
1903
+ }
1904
+ mapTurn(raw) {
1905
+ const turnId = String(raw["id"]);
1906
+ const toolRows = this.store.handle
1907
+ .prepare(`SELECT * FROM direct_chat_tool WHERE turn_id = ? ORDER BY ordinal ASC`)
1908
+ .all(turnId);
1909
+ const artifactRows = this.store.handle
1910
+ .prepare(`SELECT * FROM direct_chat_artifact WHERE turn_id = ? ORDER BY created_at ASC`)
1911
+ .all(turnId);
1912
+ return {
1913
+ id: turnId,
1914
+ threadId: String(raw["thread_id"]),
1915
+ seq: Number(raw["seq"]),
1916
+ requestId: typeof raw["request_id"] === "string" ? raw["request_id"] : null,
1917
+ userPrompt: String(raw["user_prompt"]),
1918
+ switchedFromProvider: isDirectChatProvider(raw["switched_from_provider"]) ? raw["switched_from_provider"] : null,
1919
+ logPath: String(raw["log_path"]),
1920
+ stderrPath: String(raw["stderr_path"]),
1921
+ byteOffset: Number(raw["byte_offset"] ?? 0),
1922
+ pid: typeof raw["pid"] === "number" ? raw["pid"] : null,
1923
+ startIdentity: typeof raw["start_identity"] === "string" ? raw["start_identity"] : null,
1924
+ pgid: typeof raw["pgid"] === "number" ? raw["pgid"] : null,
1925
+ bootId: typeof raw["boot_id"] === "string" ? raw["boot_id"] : null,
1926
+ status: String(raw["status"]),
1927
+ stopRequestedAt: typeof raw["stop_requested_at"] === "string" ? raw["stop_requested_at"] : null,
1928
+ assistantText: String(raw["assistant_text"] ?? ""),
1929
+ errorText: typeof raw["error_text"] === "string" ? raw["error_text"] : null,
1930
+ createdAt: String(raw["created_at"]),
1931
+ finishedAt: typeof raw["finished_at"] === "string" ? raw["finished_at"] : null,
1932
+ usage: parseUsageJson(raw["usage_json"]),
1933
+ tools: toolRows.map(t => ({
1934
+ id: String(t["id"]),
1935
+ ordinal: Number(t["ordinal"]),
1936
+ name: String(t["name"]),
1937
+ detail: String(t["detail"] ?? ""),
1938
+ status: String(t["status"]),
1939
+ updatedAt: String(t["updated_at"]),
1940
+ })),
1941
+ artifacts: artifactRows.map(a => ({
1942
+ id: String(a["id"]),
1943
+ threadId: String(a["thread_id"]),
1944
+ turnId: typeof a["turn_id"] === "string" ? a["turn_id"] : null,
1945
+ kind: a["kind"] === "attachment" ? "attachment" : "output",
1946
+ filename: String(a["filename"]),
1947
+ mimeType: String(a["mime_type"]),
1948
+ byteSize: Number(a["byte_size"]),
1949
+ sha256: String(a["sha256"]),
1950
+ storagePath: String(a["storage_path"]),
1951
+ sourcePath: typeof a["source_path"] === "string" ? a["source_path"] : null,
1952
+ createdAt: String(a["created_at"]),
1953
+ })),
1954
+ };
1955
+ }
1956
+ mapThread(raw) {
1957
+ const repo = String(raw["repo"]);
1958
+ let mainDirtyFiles = [];
1959
+ if (typeof raw["main_dirty_files"] === "string" && raw["main_dirty_files"] !== "") {
1960
+ try {
1961
+ const parsed = JSON.parse(raw["main_dirty_files"]);
1962
+ if (Array.isArray(parsed))
1963
+ mainDirtyFiles = parsed.filter((x) => typeof x === "string");
1964
+ }
1965
+ catch {
1966
+ mainDirtyFiles = [];
1967
+ }
1968
+ }
1969
+ let diffCache = { changedFiles: [], diffText: "", dirty: false };
1970
+ if (typeof raw["diff_cache_json"] === "string" && raw["diff_cache_json"] !== "") {
1971
+ try {
1972
+ const parsed = JSON.parse(raw["diff_cache_json"]);
1973
+ diffCache = {
1974
+ changedFiles: Array.isArray(parsed.changedFiles) ? parsed.changedFiles.filter((x) => typeof x === "string") : [],
1975
+ diffText: typeof parsed.diffText === "string" ? parsed.diffText : "",
1976
+ dirty: parsed.dirty === true,
1977
+ };
1978
+ }
1979
+ catch {
1980
+ diffCache = { changedFiles: [], diffText: "", dirty: false };
1981
+ }
1982
+ }
1983
+ return {
1984
+ id: String(raw["id"]),
1985
+ owner: String(raw["owner"]),
1986
+ localGeneration: typeof raw["local_generation"] === "number" ? raw["local_generation"] : null,
1987
+ accountGeneration: Number(raw["account_generation"]),
1988
+ createRequestId: typeof raw["create_request_id"] === "string" ? raw["create_request_id"] : null,
1989
+ title: String(raw["title"]),
1990
+ repo,
1991
+ project: projectName(repo),
1992
+ clonePath: String(raw["clone_path"]),
1993
+ gitDir: typeof raw["git_dir"] === "string" && raw["git_dir"] !== "" ? raw["git_dir"] : null,
1994
+ configSha256: typeof raw["config_sha256"] === "string" && raw["config_sha256"] !== "" ? raw["config_sha256"] : null,
1995
+ branch: String(raw["branch"]),
1996
+ baseSha: String(raw["base_sha"]),
1997
+ provider: String(raw["provider"]),
1998
+ modelId: String(raw["model_id"]),
1999
+ effort: normalizeDirectChatEffort(typeof raw["effort"] === "string" ? raw["effort"] : null, String(raw["provider"])),
2000
+ providerSessionId: typeof raw["provider_session_id"] === "string" ? raw["provider_session_id"] : null,
2001
+ mainDirtyFiles,
2002
+ diffCache,
2003
+ usage: parseUsageJson(raw["usage_json"]),
2004
+ isLegacy: Number(raw["is_legacy"] ?? 0) === 1,
2005
+ archivedAt: typeof raw["archived_at"] === "string" ? raw["archived_at"] : null,
2006
+ createdAt: String(raw["created_at"]),
2007
+ updatedAt: String(raw["updated_at"]),
2008
+ };
2009
+ }
2010
+ }
2011
+ export function importLegacyDirectChatJson(input) {
2012
+ const path = input.jsonPath ?? join(homedir(), ".config", "toolroll", "chat-threads.json");
2013
+ if (!existsSync(path))
2014
+ return 0;
2015
+ let parsed;
2016
+ try {
2017
+ parsed = JSON.parse(readFileSync(path, "utf8"));
2018
+ }
2019
+ catch {
2020
+ return 0;
2021
+ }
2022
+ if (!Array.isArray(parsed))
2023
+ return 0;
2024
+ return input.store.transact(() => {
2025
+ let imported = 0;
2026
+ for (const raw of parsed) {
2027
+ if (!raw || typeof raw !== "object")
2028
+ continue;
2029
+ const item = raw;
2030
+ const rawId = typeof item["id"] === "string" ? item["id"].toLowerCase().replace(/-/g, "") : "";
2031
+ if (!HEX32.test(rawId))
2032
+ continue;
2033
+ const provider = isDirectChatProvider(item["provider"]) ? item["provider"] : "claude";
2034
+ const repo = typeof item["projectPath"] === "string" && item["projectPath"] !== ""
2035
+ ? item["projectPath"]
2036
+ : (typeof item["project"] === "string" && item["project"] !== "" ? item["project"] : homedir());
2037
+ const title = typeof item["title"] === "string" && item["title"] !== "" ? sanitizeLine(item["title"]) : "Imported chat";
2038
+ const modelId = typeof item["modelId"] === "string" && item["modelId"] !== ""
2039
+ ? item["modelId"]
2040
+ : (typeof item["modelID"] === "string" && item["modelID"] !== "" ? item["modelID"] : defaultModelForProvider(provider));
2041
+ const createdAt = typeof item["createdAt"] === "string" ? item["createdAt"] : new Date().toISOString();
2042
+ const updatedAt = typeof item["updatedAt"] === "string" ? item["updatedAt"] : createdAt;
2043
+ const sessionId = typeof item["sessionId"] === "string" && item["sessionId"] !== ""
2044
+ ? item["sessionId"]
2045
+ : (typeof item["providerSessionID"] === "string" && item["providerSessionID"] !== "" ? item["providerSessionID"] : null);
2046
+ const inserted = input.store.handle.prepare(`
2047
+ INSERT OR IGNORE INTO direct_chat_thread (
2048
+ id, owner, local_generation, account_generation, create_request_id,
2049
+ title, repo, clone_path, git_dir, config_sha256, diff_cache_json, is_legacy,
2050
+ branch, base_sha, provider, model_id,
2051
+ provider_session_id, main_dirty_files, archived_at, created_at, updated_at
2052
+ ) VALUES (?, ?, NULL, ?, NULL, ?, ?, '', NULL, NULL, NULL, 1, ?, '', ?, ?, ?, NULL, ?, ?, ?)
2053
+ `).run(rawId, input.owner, input.accountGeneration, title, repo, `imported/${rawId.slice(0, 8)}`, provider, modelId, sessionId, updatedAt, createdAt, updatedAt);
2054
+ if (Number(inserted.changes) === 0)
2055
+ continue;
2056
+ imported += 1;
2057
+ const messages = Array.isArray(item["messages"]) ? item["messages"] : [];
2058
+ let seq = 0;
2059
+ let pendingUserPrompt = null;
2060
+ for (const rawMsg of messages) {
2061
+ if (!rawMsg || typeof rawMsg !== "object")
2062
+ continue;
2063
+ const msg = rawMsg;
2064
+ const role = typeof msg["role"] === "string" ? msg["role"] : "";
2065
+ const text = typeof msg["text"] === "string" ? msg["text"] : "";
2066
+ if (role === "user") {
2067
+ pendingUserPrompt = text;
2068
+ }
2069
+ else if (role === "assistant" && pendingUserPrompt !== null) {
2070
+ seq += 1;
2071
+ const turnId = randomBytes(16).toString("hex");
2072
+ const isError = msg["isError"] === true;
2073
+ const ts = typeof msg["timestamp"] === "string" ? msg["timestamp"] : updatedAt;
2074
+ input.store.handle.prepare(`
2075
+ INSERT OR IGNORE INTO direct_chat_turn (
2076
+ id, thread_id, seq, request_id, user_prompt, switched_from_provider,
2077
+ log_path, stderr_path, byte_offset, pid, start_identity, pgid, boot_id,
2078
+ status, stop_requested_at, assistant_text, error_text, created_at, finished_at
2079
+ ) VALUES (?, ?, ?, NULL, ?, NULL, '', '', 0, NULL, NULL, NULL, NULL, ?, NULL, ?, ?, ?, ?)
2080
+ `).run(turnId, rawId, seq, pendingUserPrompt, isError ? "failed" : "completed", isError ? "" : sanitizeDisplay(text), isError ? sanitizeDisplay(text) : null, ts, ts);
2081
+ const tools = Array.isArray(msg["tools"]) ? msg["tools"] : [];
2082
+ let ord = 0;
2083
+ for (const rawTool of tools) {
2084
+ if (!rawTool || typeof rawTool !== "object")
2085
+ continue;
2086
+ const t = rawTool;
2087
+ ord += 1;
2088
+ const tid = typeof t["id"] === "string" && t["id"] !== "" ? t["id"] : `imp-${ord}`;
2089
+ const tname = typeof t["name"] === "string" ? t["name"] : "Tool";
2090
+ const tdetail = typeof t["detail"] === "string" ? t["detail"] : "";
2091
+ const tstatus = t["status"] === "error" ? "error" : "done";
2092
+ input.store.handle.prepare(`
2093
+ INSERT OR IGNORE INTO direct_chat_tool (id, turn_id, ordinal, name, detail, status, updated_at)
2094
+ VALUES (?, ?, ?, ?, ?, ?, ?)
2095
+ `).run(tid, turnId, ord, sanitizeLine(tname), sanitizeLine(tdetail), tstatus, ts);
2096
+ }
2097
+ pendingUserPrompt = null;
2098
+ }
2099
+ }
2100
+ }
2101
+ return imported;
2102
+ });
2103
+ }
2104
+ export function writeDirectChatLogFixture(logPath, lines) {
2105
+ mkdirSync(dirname(logPath), { recursive: true, mode: 0o700 });
2106
+ writeFileSync(logPath, `${lines.join("\n")}\n`, { mode: 0o600 });
2107
+ }