toolroll 0.9.108 → 0.9.110

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 (187) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/dist/advanced-view.js +0 -1
  3. package/dist/agent-detect.js +244 -0
  4. package/dist/agent-fence.js +47 -5
  5. package/dist/agent-state.js +5 -2
  6. package/dist/agentconfig.js +2 -2
  7. package/dist/approval-summary.js +344 -0
  8. package/dist/assignment-ui.js +5 -5
  9. package/dist/assignment.js +5 -2
  10. package/dist/attest.js +2 -2
  11. package/dist/browser/terminal.js +1 -1
  12. package/dist/browser/workspace.css +2 -2
  13. package/dist/browser/workspace.js +37 -34
  14. package/dist/browser-crew.js +4 -4
  15. package/dist/browser-workspace.js +4 -11
  16. package/dist/builder.js +45 -3
  17. package/dist/chat-actions.js +24 -17
  18. package/dist/chat-controls.js +6 -5
  19. package/dist/chat-core.js +3 -1
  20. package/dist/chat-decide.js +102 -47
  21. package/dist/chat-delivery-state.js +2 -0
  22. package/dist/chat-delivery.js +3 -2
  23. package/dist/chat-live.js +2 -1
  24. package/dist/chat-quiet.js +3 -3
  25. package/dist/chat-task-actions.js +6 -0
  26. package/dist/chat-voice.js +2 -2
  27. package/dist/check-report.js +1 -1
  28. package/dist/cli-help.js +12 -13
  29. package/dist/cli.js +6 -3
  30. package/dist/console-chrome.js +10 -3
  31. package/dist/console-instance.js +10 -1
  32. package/dist/contracts/console-api.js +14 -8
  33. package/dist/contracts/engine-api.js +271 -0
  34. package/dist/contracts/handoff.js +4 -0
  35. package/dist/coordinator.js +2 -2
  36. package/dist/decision.js +17 -0
  37. package/dist/demo-chat.js +1 -1
  38. package/dist/demo.js +6 -0
  39. package/dist/design/kit.js +4 -3
  40. package/dist/discord-api.js +4 -3
  41. package/dist/discord-chat.js +3 -1
  42. package/dist/dispatch.js +3 -8
  43. package/dist/easy-start-args.js +7 -3
  44. package/dist/easy-start.js +25 -0
  45. package/dist/egress.js +72 -10
  46. package/dist/engine-handoff.js +34 -0
  47. package/dist/engine-reads.js +261 -0
  48. package/dist/eval-world.js +3 -2
  49. package/dist/evidence.js +2 -0
  50. package/dist/fast-start.js +55 -14
  51. package/dist/fast-terms.js +2 -2
  52. package/dist/first-run.js +10 -2
  53. package/dist/flexible-agents.js +234 -0
  54. package/dist/flexible-answers-schema.js +61 -0
  55. package/dist/flexible-answers.js +889 -0
  56. package/dist/flexible-available.js +1 -0
  57. package/dist/flexible-custody.js +494 -0
  58. package/dist/flexible-import.js +782 -0
  59. package/dist/flexible-launch-schema.js +72 -0
  60. package/dist/flexible-launch.js +331 -0
  61. package/dist/flexible-launcher.js +88 -0
  62. package/dist/flexible-levels.js +34 -0
  63. package/dist/flexible-merge-guard.js +47 -0
  64. package/dist/flexible-refs.js +47 -0
  65. package/dist/flexible-relay-cancel.js +19 -0
  66. package/dist/flexible-relay-schema.js +55 -0
  67. package/dist/flexible-relay-upstreams.js +36 -0
  68. package/dist/flexible-relay.js +1032 -0
  69. package/dist/flexible-schema.js +32 -0
  70. package/dist/flexible-session.js +732 -0
  71. package/dist/flexible-ship-schema.js +81 -0
  72. package/dist/flexible-ship.js +694 -0
  73. package/dist/flexible-start.js +80 -0
  74. package/dist/flexible-thread-schema.js +30 -0
  75. package/dist/flexible-thread.js +676 -0
  76. package/dist/flexible-turns-schema.js +69 -0
  77. package/dist/flexible-turns.js +490 -0
  78. package/dist/flexible-ui.js +44 -0
  79. package/dist/flexible.js +368 -0
  80. package/dist/flow-actions.js +6 -4
  81. package/dist/flow-steps.js +1 -1
  82. package/dist/flows-cli.js +2 -1
  83. package/dist/git-views.js +44 -41
  84. package/dist/guides.js +11 -10
  85. package/dist/install-mode.js +225 -0
  86. package/dist/keymap.js +1 -1
  87. package/dist/lead-context.js +1 -1
  88. package/dist/lead-doors.js +7 -1
  89. package/dist/limits-ui.js +8 -1
  90. package/dist/live-bus.js +70 -13
  91. package/dist/live-reply.js +6 -0
  92. package/dist/live-terminal.js +425 -29
  93. package/dist/local-owner.js +6 -0
  94. package/dist/model-choices.js +12 -6
  95. package/dist/needs-you.js +3 -3
  96. package/dist/nightly-github.js +2 -2
  97. package/dist/notification-delivery.js +11 -0
  98. package/dist/operate.js +185 -33
  99. package/dist/outbound-privacy.js +204 -0
  100. package/dist/passwordless.js +2 -1
  101. package/dist/project-delete-ui.js +2 -1
  102. package/dist/project-delete.js +15 -0
  103. package/dist/provider-auth.js +1 -1
  104. package/dist/provider-connection.js +5 -3
  105. package/dist/publish.js +5 -0
  106. package/dist/pull-request-flow.js +26 -7
  107. package/dist/push.js +5 -1
  108. package/dist/release-card.js +11 -3
  109. package/dist/release.js +11 -1
  110. package/dist/result-actions.js +3 -0
  111. package/dist/result-evidence-readers.js +8 -2
  112. package/dist/result-review.js +20 -9
  113. package/dist/route-store.js +2 -2
  114. package/dist/sandbox-launch.js +32 -8
  115. package/dist/sandbox-runtime.js +16 -7
  116. package/dist/sandbox-tools.js +176 -0
  117. package/dist/scope.js +12 -36
  118. package/dist/scout-net.js +7 -2
  119. package/dist/serve.js +90 -40
  120. package/dist/server/chat.js +9 -9
  121. package/dist/server/chrome.js +19 -17
  122. package/dist/server/console.css +33 -6
  123. package/dist/server/engine-api.js +378 -0
  124. package/dist/server/flows.js +2 -2
  125. package/dist/server/guards.js +10 -4
  126. package/dist/server/home.js +37 -5
  127. package/dist/server/http.js +11 -2
  128. package/dist/server/in-place.js +5 -4
  129. package/dist/server/kit.js +2 -2
  130. package/dist/server/link-redemption.js +52 -0
  131. package/dist/server/live.js +100 -10
  132. package/dist/server/mutation-key.js +21 -7
  133. package/dist/server/pages.js +129 -74
  134. package/dist/server/people-tokens.js +17 -41
  135. package/dist/server/render-chat.js +2 -1
  136. package/dist/server/render-history.js +18 -4
  137. package/dist/server/render-new-task.js +4 -4
  138. package/dist/server/render-pages.js +21 -39
  139. package/dist/server/render-people.js +2 -2
  140. package/dist/server/render-projects.js +5 -5
  141. package/dist/server/render-results.js +30 -14
  142. package/dist/server/render-tasks.js +155 -155
  143. package/dist/server/retired-routes.js +37 -4
  144. package/dist/server/route-policy.js +8 -0
  145. package/dist/server/route-table.js +43 -5
  146. package/dist/server/settings-computers.js +140 -0
  147. package/dist/server/settings-scripts.js +15 -0
  148. package/dist/server/settings-section-table.js +59 -0
  149. package/dist/server/settings-sections.js +291 -0
  150. package/dist/server/settings.js +247 -28
  151. package/dist/server/task-views.js +55 -15
  152. package/dist/server/tasks.js +168 -98
  153. package/dist/server/terminals.js +181 -28
  154. package/dist/server/welcome.js +40 -14
  155. package/dist/settings-groups-ui.js +26 -107
  156. package/dist/settings-proofs.js +18 -11
  157. package/dist/slack-api.js +4 -3
  158. package/dist/slack-chat.js +5 -3
  159. package/dist/spend.js +46 -12
  160. package/dist/sqlite-telemetry.js +70 -21
  161. package/dist/status-probe.js +343 -0
  162. package/dist/store.js +206 -10
  163. package/dist/task-link.js +64 -0
  164. package/dist/teams-api.js +4 -3
  165. package/dist/teams-chat.js +4 -2
  166. package/dist/telegram-lead.js +2 -1
  167. package/dist/telegram-live.js +2 -1
  168. package/dist/telegram-team.js +2 -1
  169. package/dist/telegram.js +17 -5
  170. package/dist/trusted-path.js +162 -0
  171. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  172. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  173. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  174. package/dist/tui/linux-x64/toolroll-tui +0 -0
  175. package/dist/tui-launch.js +282 -0
  176. package/dist/tui-source.js +5 -3
  177. package/dist/tui.js +2 -2
  178. package/dist/typed-words-schema.js +18 -0
  179. package/dist/webhooks.js +8 -4
  180. package/dist/welcome-facts.js +25 -17
  181. package/dist/work-index.js +126 -29
  182. package/dist/work-reads.js +279 -0
  183. package/dist/workspace-ui.js +5 -0
  184. package/package.json +4 -2
  185. package/scripts/crash-canary.mjs +1 -1
  186. package/scripts/pilot.mjs +1 -1
  187. package/scripts/provider-canary.mjs +5 -3
@@ -0,0 +1,732 @@
1
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
2
+ import { StringDecoder } from "node:string_decoder";
3
+ import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
4
+ import { FLEXIBLE_LEVEL_WORDS, FLEXIBLE_UNAVAILABLE, isFlexibleLevel } from "./flexible.js";
5
+ import { lowerFlexibleThreadLevel, recoverFlexibleLaunchesOf, startFlexibleTurn } from "./flexible-agents.js";
6
+ import { decideFlexibleAnswer, expireFlexibleAnswers, flexibleRequestsOf, noteFlexibleToolActivity, openFlexibleAnswerCatalog, recordFlexibleRequest, recoverFlexibleAnswersOf, revokeFlexibleAnswers, sendFlexibleAnswer, streamAnswerSender, } from "./flexible-answers.js";
7
+ import { startIdentityOf } from "./flexible-custody.js";
8
+ import { defaultCustodyIO, flexibleTurnLaunched } from "./flexible-launch.js";
9
+ import { flexibleRelayBilling, startFlexibleRelay } from "./flexible-relay.js";
10
+ import { flexibleThread, prepareFlexibleThread, removeFlexibleThread, stopFlexibleThreadAgent } from "./flexible-thread.js";
11
+ import { admitFlexibleTurn, finishFlexibleTurn, flexibleTurn, withdrawFlexibleTurn } from "./flexible-turns.js";
12
+ import { userFrame } from "./live-input.js";
13
+ import { cleanLiveText, createLiveRecorder, HIDDEN_LINE, liveSecretHit } from "./live-records.js";
14
+ import { primaryResultEvent } from "./stream-scope.js";
15
+ const WORDS = Object.freeze({
16
+ "not-available": FLEXIBLE_UNAVAILABLE,
17
+ "invalid-request": "That isn't a request Toolroll can read. Nothing changed.",
18
+ "no-holder": "Toolroll can't tell which process this is, so it holds no threads.",
19
+ "thread-unknown": "There's no such thread.",
20
+ "not-owner": "Only the person who started this thread can answer its agent. Nothing was sent.",
21
+ "scope-unshown": "This request couldn't be shown in full, so it can't be allowed from here. You can deny it. Nothing was sent.",
22
+ "not-answerable": "This question can't be answered from here: Toolroll restarted since it was asked, or another Toolroll holds it. Nothing was sent.",
23
+ "no-network": "This console can't give a thread its network yet, so no thread was started.",
24
+ });
25
+ const refuse = (reason) => ({ ok: false, reason, message: WORDS[reason] });
26
+ const ID = /^[0-9a-f]{32}$/;
27
+ const REF = /^[\x21-\x7e]{1,200}$/;
28
+ const systemClock = () => new Date();
29
+ export const FLEXIBLE_RECORDS_KEPT = 5_000;
30
+ const WINDOW_RECORDS = 500;
31
+ const LINE_CAP = 1_048_576;
32
+ function bump(sessions, thread) {
33
+ sessions.changes.set(thread, (sessions.changes.get(thread) ?? 0) + 1);
34
+ const waiting = sessions.waiters.get(thread);
35
+ if (waiting === undefined)
36
+ return;
37
+ sessions.waiters.delete(thread);
38
+ for (const wake of waiting) {
39
+ try {
40
+ wake();
41
+ }
42
+ catch { }
43
+ }
44
+ }
45
+ function bumpAll(sessions) {
46
+ for (const thread of new Set([...sessions.threads.keys(), ...sessions.waiters.keys()]))
47
+ bump(sessions, thread);
48
+ }
49
+ const sha16 = (text) => createHash("sha256").update(text, "utf8").digest("hex").slice(0, 16);
50
+ const HOLDER = /^console:([1-9][0-9]{0,9}):([0-9a-f]{16})$/;
51
+ function holderOf(pid, io) {
52
+ const start = startIdentityOf(pid, io);
53
+ return start === null ? null : `console:${pid}:${sha16(start)}`;
54
+ }
55
+ function holderLife(holder, io) {
56
+ const named = HOLDER.exec(holder);
57
+ if (named === null)
58
+ return "unknown";
59
+ let table;
60
+ try {
61
+ table = io.table();
62
+ }
63
+ catch {
64
+ return "unknown";
65
+ }
66
+ if (table === null)
67
+ return "unknown";
68
+ const pid = Number(named[1]);
69
+ const row = table.find(one => one.pid === pid && !one.zombie);
70
+ if (row === undefined)
71
+ return "gone";
72
+ if (row.start === null)
73
+ return "unknown";
74
+ return sha16(row.start) === named[2] ? "alive" : "gone";
75
+ }
76
+ export function openFlexibleSessions(store, input = {}) {
77
+ if (!FLEXIBLE_AVAILABLE)
78
+ return refuse("not-available");
79
+ const io = input.io ?? defaultCustodyIO();
80
+ const holder = holderOf(input.pid ?? process.pid, io);
81
+ if (holder === null)
82
+ return refuse("no-holder");
83
+ const opened = openFlexibleAnswerCatalog(store);
84
+ if (!opened.ok)
85
+ return opened;
86
+ return { ok: true, sessions: { holder, catalog: opened.catalog, io, threads: new Map(), changes: new Map(), waiters: new Map() } };
87
+ }
88
+ export async function closeFlexibleSessions(store, sessions, input = {}) {
89
+ if (!FLEXIBLE_AVAILABLE)
90
+ return refuse("not-available");
91
+ for (const thread of [...sessions.threads.keys()]) {
92
+ try {
93
+ await stopFlexibleThreadSession(store, sessions, { thread, reason: "Toolroll stopped", ...(input.clock === undefined ? {} : { clock: input.clock }) });
94
+ }
95
+ catch { }
96
+ }
97
+ sessions.catalog.close();
98
+ bumpAll(sessions);
99
+ return { ok: true };
100
+ }
101
+ export function tickFlexibleSessions(store, sessions, input = {}) {
102
+ if (!FLEXIBLE_AVAILABLE)
103
+ return refuse("not-available");
104
+ const expired = expireFlexibleAnswers(store, sessions.catalog, input.clock === undefined ? {} : { clock: input.clock });
105
+ if (expired.ok && expired.uncertain > 0)
106
+ bumpAll(sessions);
107
+ return expired;
108
+ }
109
+ export async function recoverFlexibleHolders(store, sessions, input = {}) {
110
+ if (!FLEXIBLE_AVAILABLE)
111
+ return refuse("not-available");
112
+ const clocked = input.clock === undefined ? {} : { clock: input.clock };
113
+ const holders = new Set([
114
+ ...store.handle.prepare("SELECT DISTINCT holder FROM flexible_thread_launch WHERE state <> 'exited'").all().map(row => String(row["holder"])),
115
+ ...store.handle.prepare("SELECT DISTINCT holder FROM thread_turn WHERE status IN ('admitted', 'running')").all().map(row => String(row["holder"])),
116
+ ]);
117
+ const recovered = [], unresolved = [], unknown = [];
118
+ for (const holder of [...holders].sort()) {
119
+ if (holder === sessions.holder)
120
+ continue;
121
+ const life = holderLife(holder, sessions.io);
122
+ if (life === "unknown" && HOLDER.test(holder))
123
+ unknown.push(holder);
124
+ if (life !== "gone")
125
+ continue;
126
+ const launches = await recoverFlexibleLaunchesOf(store, { holder, ...clocked, io: sessions.io });
127
+ const answers = recoverFlexibleAnswersOf(store, sessions.catalog, { holder, ...clocked });
128
+ if (!launches.ok || launches.unresolved > 0 || !answers.ok)
129
+ unresolved.push(holder);
130
+ else
131
+ recovered.push(holder);
132
+ }
133
+ if (recovered.length + unresolved.length > 0)
134
+ bumpAll(sessions);
135
+ return { ok: true, recovered, unresolved, unknown };
136
+ }
137
+ export async function startFlexibleThreadSession(store, sessions, input) {
138
+ if (!FLEXIBLE_AVAILABLE)
139
+ return refuse("not-available");
140
+ if (typeof input.thread !== "string" || !ID.test(input.thread))
141
+ return refuse("invalid-request");
142
+ const held = sessions.threads.get(input.thread);
143
+ if (held?.relay != null)
144
+ return { ok: true, relayPort: held.relay.port };
145
+ const relay = await startFlexibleRelay(store, { thread: input.thread });
146
+ if ("ok" in relay)
147
+ return relay;
148
+ const session = held ?? { thread: input.thread, relay: null, agent: null, records: [], dropped: 0, epoch: randomBytes(8).toString("hex"), asked: new Map(), title: null };
149
+ session.relay = relay;
150
+ sessions.threads.set(input.thread, session);
151
+ return { ok: true, relayPort: relay.port };
152
+ }
153
+ export async function stopFlexibleThreadSession(store, sessions, input) {
154
+ if (!FLEXIBLE_AVAILABLE)
155
+ return refuse("not-available");
156
+ if (typeof input.thread !== "string" || !ID.test(input.thread) || typeof input.reason !== "string" || input.reason.length < 1 || input.reason.length > 200)
157
+ return refuse("invalid-request");
158
+ const clocked = input.clock === undefined ? {} : { clock: input.clock };
159
+ const revoked = revokeFlexibleAnswers(store, sessions.catalog, { thread: input.thread, reason: input.reason, ...clocked });
160
+ if (!revoked.ok)
161
+ return revoked;
162
+ const session = sessions.threads.get(input.thread);
163
+ if (session?.agent != null) {
164
+ try {
165
+ session.agent.stdin.end();
166
+ }
167
+ catch { }
168
+ }
169
+ const stopped = await stopFlexibleThreadAgent(store, { id: input.thread, reason: input.reason, ...clocked, io: sessions.io });
170
+ if (session !== undefined) {
171
+ session.agent = null;
172
+ try {
173
+ await session.relay?.close();
174
+ }
175
+ catch { }
176
+ session.relay = null;
177
+ sessions.threads.delete(input.thread);
178
+ }
179
+ bump(sessions, input.thread);
180
+ if ("reason" in stopped)
181
+ return stopped;
182
+ return { ok: true, stopped: stopped.ok, why: stopped.ok ? null : stopped.why };
183
+ }
184
+ function cardText(given, cap) {
185
+ if (typeof given !== "string")
186
+ return "";
187
+ const one = cleanLiveText(given).trim().slice(0, cap);
188
+ return liveSecretHit(one) ? HIDDEN_LINE : one;
189
+ }
190
+ function canonical(value) {
191
+ if (Array.isArray(value))
192
+ return `[${value.map(canonical).join(",")}]`;
193
+ if (typeof value === "object" && value !== null) {
194
+ return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
195
+ }
196
+ return JSON.stringify(value) ?? "null";
197
+ }
198
+ function flexibleInputDigest(tool, input) {
199
+ return createHash("sha256").update(canonical({ tool, input }), "utf8").digest("hex");
200
+ }
201
+ const TAB_MARK = "→";
202
+ const TAB_SHOWN = `${TAB_MARK} `;
203
+ export const FLEXIBLE_SCOPE_LINES = 200;
204
+ export const FLEXIBLE_SCOPE_CHARS = 16_000;
205
+ const FLEXIBLE_DETAIL_CHARS = 30_000;
206
+ const FILE_TOOLS = ["Edit", "Write", "MultiEdit", "NotebookEdit"];
207
+ function scopeOf(tool, input) {
208
+ const unshown = (raw, why) => {
209
+ const preview = raw.slice(0, 10).map(line => cardText(line, 300));
210
+ return { lines: [...preview, ...(raw.length > 10 ? [`… and ${raw.length - 10} more lines`] : []), `This can't be allowed from here: ${why}. You can deny it.`], complete: false, why };
211
+ };
212
+ const raw = [];
213
+ const text = (value) => typeof value === "string" ? value : JSON.stringify(value) ?? "";
214
+ const rest = (skip) => {
215
+ for (const key of Object.keys(input).sort())
216
+ if (!skip.includes(key))
217
+ raw.push(`${key}: ${text(input[key])}`);
218
+ };
219
+ if (tool === "Bash") {
220
+ raw.push(...text(input["command"]).split("\n"));
221
+ rest(["command"]);
222
+ }
223
+ else if (tool === "Write") {
224
+ const content = text(input["content"]);
225
+ raw.push(`file: ${text(input["file_path"])}`, `content (${Buffer.byteLength(content, "utf8")} bytes):`, ...content.split("\n").map(line => `+ ${line}`));
226
+ rest(["file_path", "content"]);
227
+ }
228
+ else if (tool === "Edit") {
229
+ raw.push(`file: ${text(input["file_path"])}`, ...text(input["old_string"]).split("\n").map(line => `- ${line}`), ...text(input["new_string"]).split("\n").map(line => `+ ${line}`));
230
+ rest(["file_path", "old_string", "new_string"]);
231
+ }
232
+ else {
233
+ raw.push(...JSON.stringify(input, null, 2).split("\n"));
234
+ }
235
+ const shown = raw.map(line => line.replace(/\t/g, TAB_SHOWN));
236
+ const why = shown.length > FLEXIBLE_SCOPE_LINES || shown.reduce((sum, line) => sum + line.length + 1, 0) > FLEXIBLE_SCOPE_CHARS ? "it is too long to show here"
237
+ : raw.some(line => liveSecretHit(line)) ? "part of it is shaped like a secret, so it isn't shown"
238
+ : raw.some(line => line.includes("\t")) && raw.some(line => line.includes(TAB_MARK)) ? "its tabs couldn't be told apart from its own text"
239
+ : shown.some(line => cleanLiveText(line) !== line) ? "it holds characters a terminal can't show"
240
+ : null;
241
+ if (why !== null)
242
+ return unshown(raw, why);
243
+ if (shown.join("\n").length > FLEXIBLE_DETAIL_CHARS)
244
+ return unshown(raw, "it is too long to show here");
245
+ return { lines: shown, complete: true, why: null };
246
+ }
247
+ function cardOf(tool, input) {
248
+ const inputDigest = flexibleInputDigest(tool, input);
249
+ const toolShown = /^[\x21-\x7e]{1,100}$/.test(tool);
250
+ const bound = { tool: toolShown ? tool : "unnamed", input: inputDigest };
251
+ if (tool === "AskUserQuestion") {
252
+ const given = Array.isArray(input["questions"]) ? input["questions"].slice(0, 9) : [];
253
+ const questions = [];
254
+ const texts = [];
255
+ let complete = toolShown && input["questions"]?.length === given.length;
256
+ for (const [index, one] of given.entries()) {
257
+ if (typeof one !== "object" || one === null)
258
+ return null;
259
+ const q = one;
260
+ const question = cardText(q["question"], 4000);
261
+ if (question === "" || typeof q["question"] !== "string")
262
+ return null;
263
+ if (question !== q["question"])
264
+ complete = false;
265
+ const options = (Array.isArray(q["options"]) ? q["options"].slice(0, 9) : [])
266
+ .map(option => ({ label: cardText(typeof option === "object" && option !== null ? option["label"] : null, 200) }))
267
+ .filter(option => option.label !== "");
268
+ questions.push({ id: String(index + 1), question, ...(options.length === 0 ? {} : { options }) });
269
+ texts.push(q["question"]);
270
+ }
271
+ if (questions.length === 0)
272
+ return null;
273
+ return { kind: "question", card: { title: questions.length === 1 ? "The agent asks you" : `The agent asks you ${questions.length} things`, ...bound, complete, questions }, questions: texts, inputDigest };
274
+ }
275
+ const scope = scopeOf(tool, input);
276
+ const title = tool === "Bash" ? "Allow this command?" : FILE_TOOLS.includes(tool) ? "Allow this change to a file?"
277
+ : tool === "WebFetch" || tool === "WebSearch" ? "Allow this lookup?" : `Allow the agent's ${bound.tool} step?`;
278
+ const lines = toolShown ? scope.lines : [...scope.lines, "This can't be allowed from here: the agent's name for this step can't be shown as it is. You can deny it."];
279
+ const detail = lines.join("\n");
280
+ const whole = scope.complete && toolShown && detail.length <= FLEXIBLE_DETAIL_CHARS;
281
+ return { kind: "permission", card: { title, detail: whole ? detail : detail.slice(0, FLEXIBLE_DETAIL_CHARS), ...bound, complete: whole }, questions: [], inputDigest };
282
+ }
283
+ function frameFor(session, requestRef, answer) {
284
+ const asked = [...session.asked.values()].find(one => one.ref === requestRef);
285
+ if (asked === undefined)
286
+ throw new Error("no such request on this connection");
287
+ let response;
288
+ if ("decision" in answer) {
289
+ response = answer.decision === "accept" ? { behavior: "allow", updatedInput: asked.input }
290
+ : { behavior: "deny", message: answer.decision === "cancel" ? "The person cancelled this." : "The person declined this." };
291
+ }
292
+ else {
293
+ const given = Object.entries(answer.answers);
294
+ if (given.length === 0)
295
+ response = { behavior: "deny", message: "The person didn't answer." };
296
+ else {
297
+ const answers = Object.fromEntries(asked.questions.map((text, index) => [text, answer.answers[String(index + 1)]?.answers.join(", ") ?? ""]));
298
+ response = { behavior: "allow", updatedInput: { ...asked.input, answers } };
299
+ }
300
+ }
301
+ return Buffer.from(`${JSON.stringify({ type: "control_response", response: { subtype: "success", request_id: requestRef, response } })}\n`, "utf8");
302
+ }
303
+ export function attachFlexibleAgent(store, sessions, input) {
304
+ if (!FLEXIBLE_AVAILABLE)
305
+ return refuse("not-available");
306
+ if (typeof input.thread !== "string" || !ID.test(input.thread) || typeof input.launch !== "string" || !ID.test(input.launch) || (input.turn !== null && (typeof input.turn !== "string" || !ID.test(input.turn))))
307
+ return refuse("invalid-request");
308
+ const session = sessions.threads.get(input.thread);
309
+ const thread = flexibleThread(store, input.thread);
310
+ if (session === undefined || thread === null)
311
+ return refuse("thread-unknown");
312
+ const send = streamAnswerSender(input.stdin);
313
+ if (typeof send !== "function")
314
+ return send;
315
+ const clock = input.clock ?? systemClock;
316
+ const clocked = { clock };
317
+ const link = { launch: input.launch, turn: input.turn, stdin: input.stdin,
318
+ connection: { id: input.launch, frame: (ref, answer) => frameFor(session, ref, answer), send },
319
+ recorder: createLiveRecorder({ base: thread.folder === "" ? null : `${thread.folder}/repo`, commands: false, clock }) };
320
+ session.agent = link;
321
+ const keep = (records) => {
322
+ if (records.length === 0)
323
+ return;
324
+ session.records.push(...records);
325
+ if (session.records.length > FLEXIBLE_RECORDS_KEPT) {
326
+ const drop = session.records.length - FLEXIBLE_RECORDS_KEPT;
327
+ session.records.splice(0, drop);
328
+ session.dropped += drop;
329
+ }
330
+ bump(sessions, input.thread);
331
+ };
332
+ const event = (raw) => {
333
+ if (session.agent !== link)
334
+ return;
335
+ if (raw["type"] === "control_request") {
336
+ const request = raw["request"];
337
+ const ref = raw["request_id"];
338
+ if (typeof request !== "object" || request === null || request["subtype"] !== "can_use_tool" || typeof ref !== "string" || !REF.test(ref) || link.turn === null)
339
+ return;
340
+ const given = request["input"];
341
+ const toolInput = typeof given === "object" && given !== null && !Array.isArray(given) ? given : {};
342
+ const tool = String(request["tool_name"] ?? "");
343
+ const shown = cardOf(tool, toolInput);
344
+ if (shown === null)
345
+ return;
346
+ const correlation = typeof request["tool_use_id"] === "string" && REF.test(request["tool_use_id"]) ? request["tool_use_id"] : null;
347
+ const made = recordFlexibleRequest(store, sessions.catalog, { thread: input.thread, turn: link.turn, connection: link.launch, holder: sessions.holder, requestRef: ref,
348
+ kind: shown.kind, card: shown.card, correlation, ...clocked });
349
+ if (made.ok)
350
+ session.asked.set(made.request, { request: made.request, token: made.token, ref, kind: shown.kind, tool, input: structuredClone(toolInput), inputDigest: shown.inputDigest,
351
+ complete: shown.card.complete !== false, questions: shown.questions });
352
+ bump(sessions, input.thread);
353
+ return;
354
+ }
355
+ if (raw["type"] === "user" && link.turn !== null) {
356
+ const content = raw["message"]?.["content"];
357
+ for (const part of Array.isArray(content) ? content : []) {
358
+ const id = typeof part === "object" && part !== null && part["type"] === "tool_result" ? part["tool_use_id"] : null;
359
+ if (typeof id === "string" && REF.test(id)) {
360
+ noteFlexibleToolActivity(store, sessions.catalog, { connection: link.launch, turn: link.turn, correlation: id, ...clocked });
361
+ bump(sessions, input.thread);
362
+ }
363
+ }
364
+ }
365
+ keep(link.recorder.observe(raw));
366
+ if (primaryResultEvent(raw) && link.turn !== null) {
367
+ void endFlexibleThreadTurn(store, sessions, { thread: input.thread, turn: link.turn, outcome: "finished", ...clocked });
368
+ }
369
+ };
370
+ const decoder = new StringDecoder("utf8");
371
+ let carry = "", skipping = false;
372
+ input.stdout.on("data", (chunk) => {
373
+ carry += typeof chunk === "string" ? chunk : decoder.write(chunk);
374
+ let end;
375
+ while ((end = carry.indexOf("\n")) >= 0) {
376
+ const line = carry.slice(0, end);
377
+ carry = carry.slice(end + 1);
378
+ if (skipping) {
379
+ skipping = false;
380
+ continue;
381
+ }
382
+ try {
383
+ const parsed = JSON.parse(line);
384
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed))
385
+ event(parsed);
386
+ }
387
+ catch { }
388
+ }
389
+ if (carry.length > LINE_CAP) {
390
+ carry = "";
391
+ skipping = true;
392
+ }
393
+ });
394
+ input.exited(() => {
395
+ if (session.agent === link) {
396
+ keep(link.recorder.end());
397
+ session.agent = null;
398
+ }
399
+ revokeFlexibleAnswers(store, sessions.catalog, { thread: input.thread, connection: link.launch, reason: "the agent stopped", ...clocked });
400
+ bump(sessions, input.thread);
401
+ });
402
+ return { ok: true };
403
+ }
404
+ export function endFlexibleThreadTurn(store, sessions, input) {
405
+ if (!FLEXIBLE_AVAILABLE)
406
+ return refuse("not-available");
407
+ if (typeof input.thread !== "string" || !ID.test(input.thread) || typeof input.turn !== "string" || !ID.test(input.turn))
408
+ return refuse("invalid-request");
409
+ const clocked = input.clock === undefined ? {} : { clock: input.clock };
410
+ const finished = finishFlexibleTurn(store, { turn: input.turn, holder: sessions.holder, outcome: input.outcome, usage: null, ...(input.detail === undefined ? {} : { detail: input.detail }), ...clocked });
411
+ const revoked = revokeFlexibleAnswers(store, sessions.catalog, { thread: input.thread, turn: input.turn, reason: "the turn ended", ...clocked });
412
+ const agent = sessions.threads.get(input.thread)?.agent;
413
+ if (agent != null && agent.turn === input.turn)
414
+ agent.turn = null;
415
+ bump(sessions, input.thread);
416
+ if (!revoked.ok)
417
+ return revoked;
418
+ if (!finished.ok && finished.reason !== "turn-not-running")
419
+ return finished;
420
+ return revoked;
421
+ }
422
+ export async function lowerFlexibleThreadSession(store, sessions, input) {
423
+ if (!FLEXIBLE_AVAILABLE)
424
+ return refuse("not-available");
425
+ if (typeof input.thread !== "string" || !ID.test(input.thread) || !isFlexibleLevel(input.level))
426
+ return refuse("invalid-request");
427
+ const clocked = input.clock === undefined ? {} : { clock: input.clock };
428
+ const lowered = await lowerFlexibleThreadLevel(store, { thread: input.thread, by: input.by, level: input.level, ...clocked, io: sessions.io });
429
+ if (!lowered.ok)
430
+ return lowered;
431
+ const revoked = revokeFlexibleAnswers(store, sessions.catalog, { thread: input.thread, reason: `the thread was lowered to ${FLEXIBLE_LEVEL_WORDS[input.level]}`, ...clocked });
432
+ bump(sessions, input.thread);
433
+ if (!revoked.ok)
434
+ return revoked;
435
+ return lowered;
436
+ }
437
+ export async function beginFlexibleThreadTurn(store, sessions, input) {
438
+ if (!FLEXIBLE_AVAILABLE)
439
+ return refuse("not-available");
440
+ if (typeof input.turn !== "string" || !ID.test(input.turn) || typeof input.message !== "string" || input.message.trim() === "" || input.message.length > 100_000)
441
+ return refuse("invalid-request");
442
+ if (input.launcher === null)
443
+ return refuse("no-network");
444
+ const turn = flexibleTurn(store, input.turn);
445
+ if (turn === null)
446
+ return refuse("invalid-request");
447
+ const thread = flexibleThread(store, turn.thread);
448
+ if (thread === null)
449
+ return refuse("thread-unknown");
450
+ const relayed = await startFlexibleThreadSession(store, sessions, { thread: turn.thread });
451
+ if (!relayed.ok)
452
+ return relayed;
453
+ const session = sessions.threads.get(turn.thread);
454
+ const clocked = input.clock === undefined ? {} : { clock: input.clock };
455
+ const prepared = await input.launcher.prepare({ id: thread.id, repo: thread.repo }, input.expectNetwork === undefined ? undefined : { network: input.expectNetwork });
456
+ if (!prepared.ok) {
457
+ withdrawFlexibleTurn(store, { turn: input.turn, holder: sessions.holder, detail: prepared.message, ...clocked });
458
+ bump(sessions, turn.thread);
459
+ return prepared;
460
+ }
461
+ const network = prepared.network;
462
+ let started;
463
+ try {
464
+ started = await startFlexibleTurn(store, { turn: input.turn, holder: sessions.holder, ...clocked, network, relay: session.relay, storage: prepared.storage,
465
+ ...(input.launcher.platform === undefined ? {} : { platform: input.launcher.platform }), ...(input.seams === undefined ? {} : { seams: input.seams }), ...(input.proven === undefined ? {} : { proven: input.proven }) });
466
+ }
467
+ catch (error) {
468
+ try {
469
+ await network.close();
470
+ }
471
+ catch { }
472
+ try {
473
+ withdrawFlexibleTurn(store, { turn: input.turn, holder: sessions.holder, detail: "the agent couldn't be started", ...clocked });
474
+ }
475
+ catch { }
476
+ bump(sessions, turn.thread);
477
+ throw error;
478
+ }
479
+ if (!started.ok) {
480
+ bump(sessions, turn.thread);
481
+ return started;
482
+ }
483
+ if (started.launched === "started") {
484
+ const child = started.child;
485
+ if (child.stdout === null || child.stdin === null)
486
+ return refuse("invalid-request");
487
+ const attached = attachFlexibleAgent(store, sessions, { thread: turn.thread, turn: input.turn, launch: started.launchId, stdout: child.stdout, stdin: child.stdin,
488
+ exited: listener => { child.once("exit", listener); }, ...clocked });
489
+ if (!attached.ok)
490
+ return attached;
491
+ }
492
+ else if (session.agent !== null && session.agent.launch === started.launchId) {
493
+ session.agent.turn = input.turn;
494
+ }
495
+ session.title ??= cardText(input.message.split("\n")[0], 80) || null;
496
+ try {
497
+ session.agent?.stdin.write(`${userFrame(input.message, randomUUID())}\n`);
498
+ }
499
+ catch { }
500
+ bump(sessions, turn.thread);
501
+ return { ok: true, launched: started.launched, launchId: started.launchId };
502
+ }
503
+ export async function startFlexibleThread(store, sessions, input) {
504
+ if (!FLEXIBLE_AVAILABLE)
505
+ return refuse("not-available");
506
+ if (typeof input.repo !== "string" || typeof input.digest !== "string" || typeof input.model !== "string" || typeof input.message !== "string" || input.message.trim() === ""
507
+ || typeof input.startKey !== "string" || !/^[0-9a-f]{32}$/.test(input.startKey) || (input.billing !== "subscription" && input.billing !== "api-key"))
508
+ return refuse("invalid-request");
509
+ if (input.launcher === null)
510
+ return refuse("no-network");
511
+ const clock = input.clock ?? systemClock;
512
+ const requestKey = `start:${input.startKey}`;
513
+ let replay = null;
514
+ let turn = null;
515
+ const prepared = await prepareFlexibleThread(store, { repo: input.repo, base: "HEAD", by: input.by.name, now: clock(),
516
+ reserve: id => {
517
+ const same = store.handle.prepare(`SELECT t.id AS turn, t.thread AS thread, t.status AS status FROM thread_turn t JOIN flexible_thread f ON f.id = t.thread
518
+ WHERE t.owner = ? AND t.request_key = ? AND t.status <> 'withdrawn' AND f.state IN ('preparing', 'ready') ORDER BY t.admitted_at DESC LIMIT 1`).get(input.by.name, requestKey);
519
+ if (same !== undefined) {
520
+ if (flexibleTurnLaunched(store, String(same["turn"]))) {
521
+ replay = { thread: String(same["thread"]), turn: String(same["turn"]) };
522
+ return { ok: false, reason: "replayed", message: "This thread has already started." };
523
+ }
524
+ if (same["status"] === "admitted" || same["status"] === "running") {
525
+ return { ok: false, reason: "start-in-progress", message: "This thread is still starting. Nothing new was started; look at your threads in a moment." };
526
+ }
527
+ }
528
+ const billing = flexibleRelayBilling(store);
529
+ if (!billing.ok)
530
+ return billing;
531
+ if (billing.billing !== input.billing)
532
+ return { ok: false, reason: "billing-changed", message: "Toolroll's Claude sign-in for Flexible threads changed since the terms were shown. Look at them again before starting. Nothing was started." };
533
+ const admitted = admitFlexibleTurn(store, { thread: id, starter: input.by, digest: input.digest, level: "full", freshProof: input.freshProof === true, provider: "claude", model: input.model,
534
+ billing: input.billing, requestKey, holder: sessions.holder, clock, opening: true });
535
+ if (!admitted.ok)
536
+ return admitted;
537
+ turn = admitted.turn;
538
+ return { ok: true };
539
+ },
540
+ release: (_id, why) => {
541
+ if (turn !== null)
542
+ withdrawFlexibleTurn(store, { turn, holder: sessions.holder, detail: `the thread's repository couldn't be made: ${why}`.slice(0, 500), clock });
543
+ } });
544
+ const replayed = replay;
545
+ if (!prepared.ok)
546
+ return replayed !== null ? { ok: true, thread: replayed.thread, turn: replayed.turn, replayed: true } : prepared;
547
+ const thread = prepared.thread.id;
548
+ const first = turn;
549
+ if (first === null)
550
+ return refuse("invalid-request");
551
+ let begun;
552
+ try {
553
+ begun = await beginFlexibleThreadTurn(store, sessions, { turn: first, message: input.message, launcher: input.launcher, clock,
554
+ ...(input.expectNetwork === undefined ? {} : { expectNetwork: input.expectNetwork }), ...(input.seams === undefined ? {} : { seams: input.seams }), ...(input.proven === undefined ? {} : { proven: input.proven }) });
555
+ }
556
+ catch (error) {
557
+ await discardRefusedStart(store, sessions, { thread, turn: first, by: input.by.name, detail: "the agent couldn't be started", clock });
558
+ throw error;
559
+ }
560
+ if (!begun.ok) {
561
+ await discardRefusedStart(store, sessions, { thread, turn: first, by: input.by.name, detail: begun.message, clock });
562
+ return begun;
563
+ }
564
+ return { ok: true, thread, turn: first, replayed: false };
565
+ }
566
+ async function discardRefusedStart(store, sessions, input) {
567
+ try {
568
+ withdrawFlexibleTurn(store, { turn: input.turn, holder: sessions.holder, detail: input.detail.slice(0, 500), clock: input.clock });
569
+ }
570
+ catch { }
571
+ try {
572
+ await stopFlexibleThreadSession(store, sessions, { thread: input.thread, reason: "its start was refused", clock: input.clock });
573
+ }
574
+ catch { }
575
+ try {
576
+ await removeFlexibleThread(store, { id: input.thread, by: input.by, now: input.clock() });
577
+ }
578
+ catch { }
579
+ }
580
+ export async function answerFlexibleRequest(store, sessions, input) {
581
+ if (!FLEXIBLE_AVAILABLE)
582
+ return refuse("not-available");
583
+ if (typeof input.thread !== "string" || !ID.test(input.thread) || typeof input.request !== "string" || !ID.test(input.request) || typeof input.shownDigest !== "string"
584
+ || typeof input.choice !== "object" || input.choice === null || typeof input.held !== "function")
585
+ return refuse("invalid-request");
586
+ if (input.by?.kind !== "person" || typeof input.by.name !== "string" || !Number.isSafeInteger(input.by.generation))
587
+ return refuse("not-owner");
588
+ const account = store.accountOf(input.by.name);
589
+ if (ownThread(store, input.thread, { name: input.by.name }) === null || account === null || account.revokedAt !== null || account.generation !== input.by.generation)
590
+ return refuse("not-owner");
591
+ const session = sessions.threads.get(input.thread);
592
+ const asked = session?.asked.get(input.request);
593
+ if (session === undefined || asked === undefined)
594
+ return refuse("not-answerable");
595
+ const choice = input.choice;
596
+ const decision = "decision" in choice ? (choice.decision === "accept" || choice.decision === "decline" ? choice.decision : null) : asked.kind === "question" ? "answer" : null;
597
+ if (decision === null || (!("decision" in choice) && (typeof choice.question !== "string" || typeof choice.answer !== "string" || choice.answer.length < 1 || choice.answer.length > 16_000)))
598
+ return refuse("invalid-request");
599
+ if (decision === "accept" && (!asked.complete || flexibleInputDigest(asked.tool, asked.input) !== asked.inputDigest))
600
+ return refuse("scope-unshown");
601
+ const clocked = input.clock === undefined ? {} : { clock: input.clock };
602
+ const answers = "decision" in choice ? undefined : { [choice.question]: { answers: [choice.answer] } };
603
+ const decided = decideFlexibleAnswer(store, sessions.catalog, { request: input.request, token: asked.token, shownDigest: input.shownDigest, by: input.by, decision, ...(answers === undefined ? {} : { answers }),
604
+ held: input.held, ...clocked });
605
+ bump(sessions, input.thread);
606
+ if (!decided.ok)
607
+ return decided;
608
+ const agent = session.agent;
609
+ const connection = agent?.connection ?? { id: "0".repeat(32), frame: () => new Uint8Array(0), send: async () => ({ written: 0, complete: false }) };
610
+ const sent = await sendFlexibleAnswer(store, sessions.catalog, { request: input.request, connection, holder: sessions.holder, held: input.held, ...clocked, ...(input.writeMs === undefined ? {} : { writeMs: input.writeMs }) });
611
+ if (!sent.ok && sent.reason === "uncertain" && agent != null) {
612
+ try {
613
+ agent.stdin.destroy();
614
+ }
615
+ catch { }
616
+ }
617
+ bump(sessions, input.thread);
618
+ return sent.ok ? { ok: true, state: "sent" } : sent;
619
+ }
620
+ function levelOf(store, thread) {
621
+ const chosen = store.handle.prepare("SELECT level FROM flexible_thread_level WHERE thread = ?").get(thread)?.["level"];
622
+ if (isFlexibleLevel(chosen))
623
+ return chosen;
624
+ const last = store.handle.prepare("SELECT level FROM thread_turn WHERE thread = ? AND status <> 'withdrawn' ORDER BY seq DESC LIMIT 1").get(thread)?.["level"];
625
+ return isFlexibleLevel(last) ? last : null;
626
+ }
627
+ function factsOf(store, sessions, thread, session) {
628
+ const last = store.handle.prepare("SELECT id FROM thread_turn WHERE thread = ? AND status <> 'withdrawn' ORDER BY seq DESC LIMIT 1").get(thread.id)?.["id"];
629
+ const turn = typeof last === "string" ? flexibleTurn(store, last) : null;
630
+ const read = turn === null ? null : flexibleRequestsOf(sessions.catalog, { thread: thread.id, turn: turn.id });
631
+ const questions = read === null || !read.ok ? [] : read.requests.map(one => ({
632
+ request: one.request, kind: one.kind, title: one.card.title, detail: one.card.detail ?? null, tool: one.card.tool ?? null, complete: one.card.complete !== false, digest: one.requestDigest, state: one.state,
633
+ answerable: one.state === "pending" && session?.asked.has(one.request) === true && session.agent?.launch === one.connection,
634
+ parts: (one.card.questions ?? []).map(q => ({ id: q.id, question: q.question, options: (q.options ?? []).map(option => option.label) })),
635
+ }));
636
+ const project = store.handle.prepare("SELECT name FROM project WHERE path = ?").get(thread.repo)?.["name"];
637
+ const facts = {
638
+ title: session?.title ?? `Thread ${thread.id.slice(0, 8)}`,
639
+ project: typeof project === "string" ? project : null,
640
+ level: levelOf(store, thread.id),
641
+ agent: turn === null ? null : { provider: turn.provider, model: turn.model },
642
+ turn: turn === null ? null : { seq: turn.seq, status: turn.status, costUsd: turn.costBasis === null ? null : turn.costMicrousd / 1_000_000, costBasis: turn.costBasis },
643
+ questions,
644
+ };
645
+ return { version: sha16(JSON.stringify(facts)), ...facts };
646
+ }
647
+ function ownThread(store, thread, viewer) {
648
+ const row = typeof thread === "string" && ID.test(thread) ? flexibleThread(store, thread) : null;
649
+ return row === null || row.state !== "ready" || row.createdBy !== viewer.name ? null : row;
650
+ }
651
+ export function flexibleThreadLiveOf(store, sessions, input) {
652
+ if (!FLEXIBLE_AVAILABLE)
653
+ return refuse("not-available");
654
+ const thread = ownThread(store, input.thread, input.viewer);
655
+ if (thread === null)
656
+ return refuse("thread-unknown");
657
+ const session = sessions.threads.get(thread.id);
658
+ const facts = factsOf(store, sessions, thread, session);
659
+ const live = session?.agent != null;
660
+ if (input.file === "sub" || session === undefined)
661
+ return { ok: true, live, window: { ok: false, reason: "missing" }, facts };
662
+ const total = session.dropped + session.records.length;
663
+ const named = input.cursor === null ? null : /^([0-9a-f]{16})\.(0|[1-9][0-9]{0,11})$/.exec(input.cursor);
664
+ const restarted = input.cursor !== null && (named === null || named[1] !== session.epoch || Number(named[2]) > total);
665
+ let from = named !== null && !restarted ? Number(named[2]) : session.dropped;
666
+ const earlier = from < session.dropped;
667
+ if (earlier)
668
+ from = session.dropped;
669
+ const records = session.records.slice(from - session.dropped, from - session.dropped + WINDOW_RECORDS);
670
+ const next = from + records.length;
671
+ return { ok: true, live, window: { ok: true, records, cursor: `${session.epoch}.${next}`, restarted, earlier, quarantined: 0, skipped: 0, more: next < total }, facts };
672
+ }
673
+ export function flexibleThreadsOf(store, sessions, input) {
674
+ if (!FLEXIBLE_AVAILABLE)
675
+ return refuse("not-available");
676
+ if (typeof input.owner !== "string")
677
+ return refuse("invalid-request");
678
+ const rows = store.handle.prepare("SELECT id FROM flexible_thread WHERE created_by = ? AND state = 'ready' ORDER BY created_at DESC, id LIMIT 50").all(input.owner).map(row => String(row["id"]));
679
+ const threads = rows.map(id => flexibleThread(store, id)).filter(one => one !== null).map(thread => {
680
+ const session = sessions.threads.get(thread.id);
681
+ const facts = factsOf(store, sessions, thread, session);
682
+ return { ...facts, id: thread.id, repo: thread.repo, live: session?.agent != null, waiting: facts.questions.filter(one => one.answerable).length };
683
+ });
684
+ return { ok: true, threads };
685
+ }
686
+ export function admitFlexibleThreadOwner(store, sessions, input) {
687
+ if (!FLEXIBLE_AVAILABLE)
688
+ return refuse("not-available");
689
+ const thread = ownThread(store, input.thread, input.viewer);
690
+ return thread === null || !input.canAccess(thread.repo) ? refuse("thread-unknown") : { ok: true, repo: thread.repo };
691
+ }
692
+ export const FLEXIBLE_WAIT_MS = 20_000;
693
+ export const FLEXIBLE_WAITERS_MAX = 64;
694
+ export function flexibleThreadChangeOf(sessions, input) {
695
+ if (!FLEXIBLE_AVAILABLE)
696
+ return refuse("not-available");
697
+ if (typeof input.thread !== "string" || !ID.test(input.thread))
698
+ return refuse("invalid-request");
699
+ return { ok: true, change: sessions.changes.get(input.thread) ?? 0 };
700
+ }
701
+ export function waitFlexibleThreadChange(sessions, input) {
702
+ if (!FLEXIBLE_AVAILABLE)
703
+ return refuse("not-available");
704
+ if (typeof input.thread !== "string" || !ID.test(input.thread) || !Number.isSafeInteger(input.since) || !Number.isSafeInteger(input.ms) || input.ms < 0 || input.ms > FLEXIBLE_WAIT_MS)
705
+ return refuse("invalid-request");
706
+ if ((sessions.changes.get(input.thread) ?? 0) !== input.since)
707
+ return Promise.resolve({ ok: true, woke: "changed" });
708
+ const waiting = [...sessions.waiters.values()].reduce((sum, set) => sum + set.size, 0);
709
+ if (waiting >= FLEXIBLE_WAITERS_MAX)
710
+ return Promise.resolve({ ok: true, woke: "busy" });
711
+ return new Promise(resolve => {
712
+ let done = false;
713
+ const finish = (woke) => {
714
+ if (done)
715
+ return;
716
+ done = true;
717
+ clearTimeout(timer);
718
+ const set = sessions.waiters.get(input.thread);
719
+ set?.delete(wake);
720
+ if (set !== undefined && set.size === 0)
721
+ sessions.waiters.delete(input.thread);
722
+ resolve({ ok: true, woke });
723
+ };
724
+ const wake = () => finish("changed");
725
+ const timer = setTimeout(() => finish("timeout"), input.ms);
726
+ timer.unref();
727
+ const set = sessions.waiters.get(input.thread) ?? new Set();
728
+ set.add(wake);
729
+ sessions.waiters.set(input.thread, set);
730
+ input.abandoned?.(() => finish("abandoned"));
731
+ });
732
+ }