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,69 @@
1
+ export const V164_SCHEMA = `
2
+ CREATE TABLE IF NOT EXISTS thread_turn (
3
+ id TEXT PRIMARY KEY CHECK (length(id) = 32 AND id NOT GLOB '*[^0-9a-f]*'),
4
+ thread TEXT NOT NULL CHECK (length(thread) = 32 AND thread NOT GLOB '*[^0-9a-f]*'),
5
+ seq INTEGER NOT NULL CHECK (seq >= 1),
6
+ repo TEXT NOT NULL,
7
+ owner TEXT NOT NULL,
8
+ owner_generation INTEGER NOT NULL,
9
+ terms_id INTEGER NOT NULL,
10
+ terms_digest TEXT NOT NULL,
11
+ level TEXT NOT NULL CHECK (level IN ('supervised', 'auto', 'full')),
12
+ provider TEXT NOT NULL CHECK (provider IN ('claude', 'codex')),
13
+ model TEXT NOT NULL CHECK (length(model) BETWEEN 1 AND 200),
14
+ billing TEXT NOT NULL CHECK (billing IN ('subscription', 'api-key')),
15
+ request_key TEXT NOT NULL CHECK (length(request_key) BETWEEN 1 AND 128),
16
+ holder TEXT NOT NULL CHECK (length(holder) BETWEEN 1 AND 128),
17
+ admitted_at TEXT NOT NULL,
18
+ utc_day TEXT NOT NULL CHECK (utc_day = substr(admitted_at, 1, 10)),
19
+ rail_reserved INTEGER NOT NULL DEFAULT 0 CHECK (rail_reserved IN (0, 1)),
20
+ status TEXT NOT NULL CHECK (status IN ('admitted', 'running', 'finished', 'interrupted', 'unknown', 'withdrawn')),
21
+ started_at TEXT,
22
+ ended_at TEXT,
23
+ end_detail TEXT CHECK (end_detail IS NULL OR length(end_detail) <= 2000),
24
+ tokens_in INTEGER NOT NULL DEFAULT 0 CHECK (tokens_in >= 0),
25
+ tokens_out INTEGER NOT NULL DEFAULT 0 CHECK (tokens_out >= 0),
26
+ cost_microusd INTEGER NOT NULL DEFAULT 0 CHECK (cost_microusd >= 0),
27
+ relay_calls INTEGER NOT NULL DEFAULT 0 CHECK (relay_calls >= 0),
28
+ cost_basis TEXT CHECK (cost_basis IS NULL OR cost_basis IN ('measured', 'estimated', 'unknown')),
29
+ CHECK ((status IN ('admitted', 'withdrawn')) = (started_at IS NULL)),
30
+ CHECK ((status IN ('admitted', 'running')) = (ended_at IS NULL)),
31
+ CHECK (status NOT IN ('admitted', 'withdrawn') OR (tokens_in = 0 AND tokens_out = 0 AND cost_microusd = 0 AND relay_calls = 0 AND cost_basis IS NULL)),
32
+ CHECK (status NOT IN ('finished', 'interrupted', 'unknown') OR cost_basis IS NOT NULL),
33
+ UNIQUE (thread, seq)
34
+ );
35
+ CREATE UNIQUE INDEX IF NOT EXISTS thread_turn_request ON thread_turn (thread, request_key) WHERE status <> 'withdrawn';
36
+ CREATE UNIQUE INDEX IF NOT EXISTS thread_turn_live ON thread_turn (thread) WHERE status IN ('admitted', 'running');
37
+ CREATE INDEX IF NOT EXISTS thread_turn_day ON thread_turn (utc_day, repo);
38
+ CREATE INDEX IF NOT EXISTS thread_turn_owner_day ON thread_turn (owner, utc_day);
39
+ CREATE TRIGGER IF NOT EXISTS thread_turn_written_once BEFORE UPDATE ON thread_turn
40
+ WHEN NEW.id IS NOT OLD.id OR NEW.thread IS NOT OLD.thread OR NEW.seq IS NOT OLD.seq OR NEW.repo IS NOT OLD.repo OR NEW.owner IS NOT OLD.owner
41
+ OR NEW.owner_generation IS NOT OLD.owner_generation OR NEW.terms_id IS NOT OLD.terms_id OR NEW.terms_digest IS NOT OLD.terms_digest
42
+ OR NEW.level IS NOT OLD.level OR NEW.provider IS NOT OLD.provider OR NEW.model IS NOT OLD.model OR NEW.billing IS NOT OLD.billing
43
+ OR NEW.request_key IS NOT OLD.request_key OR NEW.holder IS NOT OLD.holder OR NEW.admitted_at IS NOT OLD.admitted_at
44
+ OR NEW.utc_day IS NOT OLD.utc_day OR NEW.rail_reserved IS NOT OLD.rail_reserved
45
+ OR OLD.status = 'withdrawn'
46
+ OR (OLD.status = 'admitted' AND NEW.status NOT IN ('admitted', 'running', 'withdrawn'))
47
+ OR (OLD.status = 'running' AND NEW.status IN ('admitted', 'withdrawn'))
48
+ OR (OLD.status IN ('finished', 'interrupted', 'unknown') AND (NEW.status IS NOT OLD.status OR NEW.ended_at IS NOT OLD.ended_at OR NEW.end_detail IS NOT OLD.end_detail
49
+ OR (NEW.cost_basis IS NOT OLD.cost_basis AND NOT (NEW.cost_basis = 'unknown' OR (NEW.cost_basis = 'estimated' AND OLD.cost_basis = 'measured')))))
50
+ OR (OLD.started_at IS NOT NULL AND NEW.started_at IS NOT OLD.started_at)
51
+ OR NEW.tokens_in < OLD.tokens_in OR NEW.tokens_out < OLD.tokens_out OR NEW.cost_microusd < OLD.cost_microusd OR NEW.relay_calls < OLD.relay_calls
52
+ BEGIN
53
+ SELECT RAISE(ABORT, 'a flexible turn is written once, its status only moves forward and its usage only grows');
54
+ END;
55
+ CREATE TABLE IF NOT EXISTS flexible_installation_caps (
56
+ id INTEGER PRIMARY KEY CHECK (id = 1),
57
+ live_threads INTEGER CHECK (live_threads IS NULL OR live_threads BETWEEN 1 AND 1000),
58
+ turns_per_day INTEGER CHECK (turns_per_day IS NULL OR turns_per_day BETWEEN 1 AND 1000000),
59
+ measured_microusd_per_day INTEGER CHECK (measured_microusd_per_day IS NULL OR measured_microusd_per_day BETWEEN 1 AND 100000000000000),
60
+ updated_by TEXT NOT NULL,
61
+ updated_at TEXT NOT NULL
62
+ );
63
+ `;
64
+ export const V164_TABLES = Object.freeze(["thread_turn", "flexible_installation_caps"]);
65
+ export const V164_STEPS = Object.freeze(["thread-turn"]);
66
+ export const V164_OBJECTS = Object.freeze([
67
+ ["table", "thread_turn"], ["index", "thread_turn_request"], ["index", "thread_turn_live"], ["index", "thread_turn_day"], ["index", "thread_turn_owner_day"],
68
+ ["trigger", "thread_turn_written_once"], ["table", "flexible_installation_caps"],
69
+ ]);
@@ -0,0 +1,490 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
3
+ import { threadLevelAllowed } from "./flexible-levels.js";
4
+ import { flexibleDelegationAtUse, FLEXIBLE_LEVEL_WORDS, FLEXIBLE_LEVELS, FLEXIBLE_UNAVAILABLE, isFlexibleLevel } from "./flexible.js";
5
+ import { budgetHoldWords, budgetLabel, budgetStates, canPrice, countsToward, monthOf, priceWork, spendItems } from "./spend.js";
6
+ import { relayCancel } from "./flexible-relay-cancel.js";
7
+ const TURN_ID = /^[0-9a-f]{32}$/;
8
+ const KEY = /^[A-Za-z0-9._:-]{1,128}$/;
9
+ const MODEL = /^[A-Za-z0-9._:/@+-]{1,200}$/;
10
+ const text = (value) => value === null || value === undefined ? null : String(value);
11
+ function readTurn(row) {
12
+ if (row === undefined)
13
+ return null;
14
+ return { id: String(row["id"]), thread: String(row["thread"]), seq: Number(row["seq"]), repo: String(row["repo"]), owner: String(row["owner"]), ownerGeneration: Number(row["owner_generation"]),
15
+ termsId: Number(row["terms_id"]), termsDigest: String(row["terms_digest"]), level: String(row["level"]), provider: String(row["provider"]),
16
+ model: String(row["model"]), billing: row["billing"] === "subscription" ? "subscription" : "api-key", requestKey: String(row["request_key"]), holder: String(row["holder"]),
17
+ admittedAt: String(row["admitted_at"]), utcDay: String(row["utc_day"]), status: String(row["status"]), startedAt: text(row["started_at"]), endedAt: text(row["ended_at"]),
18
+ tokensIn: Number(row["tokens_in"]), tokensOut: Number(row["tokens_out"]), costMicrousd: Number(row["cost_microusd"]), relayCalls: Number(row["relay_calls"]),
19
+ costBasis: row["cost_basis"] === null ? null : String(row["cost_basis"]) };
20
+ }
21
+ export function flexibleTurn(store, id) {
22
+ if (!TURN_ID.test(id))
23
+ return null;
24
+ return readTurn(store.handle.prepare("SELECT * FROM thread_turn WHERE id = ?").get(id));
25
+ }
26
+ export function flexibleInstallationCaps(store) {
27
+ const row = store.handle.prepare("SELECT live_threads, turns_per_day, measured_microusd_per_day FROM flexible_installation_caps WHERE id = 1").get();
28
+ const limit = (value) => value === null || value === undefined ? null : Number(value);
29
+ return { liveThreads: limit(row?.["live_threads"]), turnsPerDay: limit(row?.["turns_per_day"]), measuredMicrousdPerDay: limit(row?.["measured_microusd_per_day"]) };
30
+ }
31
+ const WORDS = Object.freeze({
32
+ "not-available": FLEXIBLE_UNAVAILABLE,
33
+ "invalid-request": "That turn request isn't one Toolroll can read. Nothing was started.",
34
+ "thread-unknown": "There's no such thread.",
35
+ "thread-not-ready": "This thread isn't ready, so it can't take a turn. Start a new thread.",
36
+ "not-owner": "Only the person who started this thread can send it messages.",
37
+ "already-sent": "That message already started a turn. Nothing new was started.",
38
+ "turn-in-progress": "This thread is already working on a turn. Wait for it to finish, or stop it.",
39
+ "turn-unknown": "There's no such turn.",
40
+ "turn-not-admitted": "This turn isn't waiting to start, so it wasn't started again.",
41
+ "turn-not-running": "This turn isn't running, so nothing was charged to it.",
42
+ "held-elsewhere": "Another Toolroll process holds this turn, so this one didn't touch it.",
43
+ "not-an-operator": "Only an instance operator can change the installation's Flexible limits. Nothing changed.",
44
+ "request-changed": "That message is already waiting to start with different settings (level, agent, billing or session). Send it again as a new message.",
45
+ "turn-expired": "This turn waited past midnight UTC, so it didn't start. Send the message again.",
46
+ });
47
+ const refuse = (reason) => ({ ok: false, reason, message: WORDS[reason] });
48
+ function timeOf(clock) {
49
+ const now = (clock ?? (() => new Date()))();
50
+ if (!(now instanceof Date) || !Number.isFinite(now.getTime()))
51
+ throw new Error("the Flexible turn clock gave no usable time");
52
+ return now;
53
+ }
54
+ const clockOk = (clock) => clock === undefined || typeof clock === "function";
55
+ const nextUtcDay = (now) => new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1)).toISOString();
56
+ const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
57
+ const dollars = (microusd) => `$${(microusd / 1_000_000).toFixed(2)}`;
58
+ const PROVIDER_WORDS = Object.freeze({ claude: "Claude", codex: "Codex" });
59
+ const TOMORROW = "New turns can start after midnight UTC.";
60
+ function capReached(cap, message, resetsAt) {
61
+ return { ok: false, reason: "cap-reached", message, cap, resetsAt };
62
+ }
63
+ function usageOf(store, day, repo) {
64
+ const where = repo === null ? "" : " AND repo = ?";
65
+ const params = repo === null ? [day] : [day, repo];
66
+ const today = store.handle.prepare(`SELECT COUNT(*) AS turns, COALESCE(SUM(cost_microusd), 0) AS spent,
67
+ COALESCE(SUM(CASE WHEN billing = 'api-key' AND status IN ('finished', 'interrupted', 'unknown') AND (cost_basis = 'unknown' OR id IN (SELECT turn FROM thread_relay_pending)) THEN 1 ELSE 0 END), 0) AS blind
68
+ FROM thread_turn WHERE utc_day = ? AND status <> 'withdrawn'${where}`).get(...params);
69
+ const live = store.handle.prepare(`SELECT COUNT(DISTINCT thread) AS n FROM thread_turn WHERE status IN ('admitted', 'running')${where}`).get(...(repo === null ? [] : [repo]));
70
+ return { threads: Number(live["n"]), turns: Number(today["turns"]), spent: Number(today["spent"]), blind: Number(today["blind"]) };
71
+ }
72
+ function dollarsRefusal(cap, who, limit, usage, now) {
73
+ if (limit === null)
74
+ return null;
75
+ if (usage.blind > 0) {
76
+ return { ok: false, reason: "spend-unknown", cap, resetsAt: nextUtcDay(now),
77
+ message: `A turn today on an API key ended without a cost Toolroll could measure, so ${who} ${dollars(limit)} daily limit can't be checked. ${TOMORROW}` };
78
+ }
79
+ return usage.spent >= limit ? capReached(cap, `${who[0].toUpperCase()}${who.slice(1)} measured spend today reached its ${dollars(limit)} limit. ${TOMORROW}`, nextUtcDay(now)) : null;
80
+ }
81
+ function planSpent(store, provider, now) {
82
+ const stamp = now.toISOString();
83
+ const window = store.handle.prepare("SELECT resets_at FROM provider_limit WHERE provider = ? AND reached = 1 AND (resets_at IS NULL OR resets_at > ?) ORDER BY resets_at IS NULL DESC, resets_at DESC LIMIT 1").get(provider, stamp);
84
+ if (window !== undefined)
85
+ return { until: text(window["resets_at"]) };
86
+ const quota = store.handle.prepare("SELECT reset_at FROM quota WHERE provider = ? AND state = 'exhausted' AND (reset_at IS NULL OR reset_at > ?) ORDER BY reset_at IS NULL DESC, reset_at DESC LIMIT 1").get(provider, stamp);
87
+ return quota === undefined ? null : { until: text(quota["reset_at"]) };
88
+ }
89
+ function modeDollarCap(store, repo, now) {
90
+ const mode = store.activeMode(repo, now);
91
+ if (mode === null)
92
+ return null;
93
+ try {
94
+ const terms = JSON.parse(mode.termsJson);
95
+ return typeof terms.dailyMeasuredCapMicrousd === "number" ? terms.dailyMeasuredCapMicrousd : null;
96
+ }
97
+ catch {
98
+ return null;
99
+ }
100
+ }
101
+ const reservedStarts = (store, repo, day) => Number(store.handle.prepare("SELECT reserved_starts FROM mode_rail WHERE repo = ? AND utc_day = ?").get(repo, day)?.["reserved_starts"] ?? 0);
102
+ function releaseRail(store, turn) {
103
+ if (turn.relayCalls !== 0 || turn.startedAt !== null)
104
+ return;
105
+ const row = store.handle.prepare("SELECT rail_reserved FROM thread_turn WHERE id = ?").get(turn.id);
106
+ if (Number(row?.["rail_reserved"] ?? 0) !== 1)
107
+ return;
108
+ store.handle.prepare("UPDATE mode_rail SET reserved_starts = reserved_starts - 1 WHERE repo = ? AND utc_day = ? AND reserved_starts > 0").run(turn.repo, turn.utcDay);
109
+ }
110
+ function withdrawTurn(store, turn, detail, at) {
111
+ releaseRail(store, turn);
112
+ store.handle.prepare("UPDATE thread_turn SET status = 'withdrawn', ended_at = ?, end_detail = ? WHERE id = ? AND status = 'admitted'").run(at, detail.slice(0, 2000), turn.id);
113
+ }
114
+ function budgetRefusal(store, repo, person, provider, now) {
115
+ const hard = store.budgets().filter(one => one.hardStop);
116
+ if (hard.length === 0)
117
+ return null;
118
+ const month = monthOf(now);
119
+ const items = spendItems(store.handle, month.from, month.to);
120
+ const mine = budgetStates(hard, items).filter(one => countsToward({ project: repo, person, subagent: null }, one));
121
+ if (mine.length === 0)
122
+ return null;
123
+ const over = mine.find(one => one.spentMicrousd >= one.limitMicrousd) ?? null;
124
+ if (over !== null) {
125
+ const hold = { over, why: "used-up", unpricedProvider: null, remainingMicrousd: null };
126
+ return capReached("budget", `${budgetHoldWords(hold, month.name)}. Turns on an API key wait for next month or a higher budget.`, month.to);
127
+ }
128
+ const blind = mine.find(budget => items.some(item => item.kind === "flexible" && item.microusd === null && countsToward(item, budget))) ?? null;
129
+ if (blind !== null) {
130
+ return { ok: false, reason: "spend-unknown", cap: "budget", resetsAt: month.to,
131
+ message: `A turn this month on an API key ended without a cost Toolroll could measure, so ${budgetLabel(blind).replace(/^The /, "the ")} budget can't be checked. Turns on an API key it covers wait for next month.` };
132
+ }
133
+ if (!canPrice(store.handle, provider)) {
134
+ const hold = { over: mine[0], why: "unpriced", unpricedProvider: provider, remainingMicrousd: null };
135
+ return capReached("budget", `${budgetHoldWords(hold, month.name)}.`, null);
136
+ }
137
+ return null;
138
+ }
139
+ function modeSpentToday(store, repo, day) {
140
+ const runs = store.handle.prepare(`SELECT COALESCE(SUM(CAST(ROUND(run.cost_usd * 1000000) AS INTEGER)), 0) AS total FROM run JOIN task_ref ON task_ref.id = run.task_ref
141
+ WHERE task_ref.repo = ? AND run.cost_usd IS NOT NULL AND run.provider_started_at >= ? AND run.provider_started_at < ?`).get(repo, `${day}T00:00:00.000Z`, `${day}T23:59:59.999Z`);
142
+ const threads = store.handle.prepare("SELECT COALESCE(SUM(cost_microusd), 0) AS total FROM thread_turn WHERE repo = ? AND utc_day = ? AND status <> 'withdrawn'").get(repo, day);
143
+ return Number(runs?.["total"] ?? 0) + Number(threads?.["total"] ?? 0);
144
+ }
145
+ function validRequest(input) {
146
+ return typeof input === "object" && input !== null && TURN_ID.test(input.thread) && typeof input.starter?.name === "string" && Number.isSafeInteger(input.starter.generation)
147
+ && typeof input.digest === "string" && isFlexibleLevel(input.level) && typeof input.freshProof === "boolean" && (input.provider === "claude" || input.provider === "codex")
148
+ && typeof input.model === "string" && MODEL.test(input.model) && (input.billing === "subscription" || input.billing === "api-key")
149
+ && typeof input.requestKey === "string" && KEY.test(input.requestKey) && typeof input.holder === "string" && KEY.test(input.holder)
150
+ && (input.opening === undefined || typeof input.opening === "boolean") && clockOk(input.clock);
151
+ }
152
+ export function admitFlexibleTurn(store, input) {
153
+ if (!FLEXIBLE_AVAILABLE)
154
+ return refuse("not-available");
155
+ if (!validRequest(input))
156
+ return refuse("invalid-request");
157
+ return store.transact(() => {
158
+ const now = timeOf(input.clock);
159
+ const thread = store.handle.prepare("SELECT repo, state, created_by, live_pid FROM flexible_thread WHERE id = ?").get(input.thread);
160
+ if (thread === undefined)
161
+ return refuse("thread-unknown");
162
+ const opening = input.opening === true && thread["state"] === "preparing"
163
+ && store.handle.prepare("SELECT 1 AS hit FROM thread_turn WHERE thread = ? LIMIT 1").get(input.thread) === undefined;
164
+ if (thread["state"] !== "ready" && !opening)
165
+ return refuse("thread-not-ready");
166
+ if (thread["created_by"] !== input.starter.name)
167
+ return refuse("not-owner");
168
+ const repo = String(thread["repo"]);
169
+ const delegation = flexibleDelegationAtUse(store, { repo, starter: input.starter, digest: input.digest, level: input.level, freshProof: input.freshProof });
170
+ if (!delegation.ok)
171
+ return delegation;
172
+ const same = readTurn(store.handle.prepare("SELECT * FROM thread_turn WHERE thread = ? AND request_key = ? AND status <> 'withdrawn'").get(input.thread, input.requestKey));
173
+ if (same !== null) {
174
+ if (same.status !== "admitted")
175
+ return refuse("already-sent");
176
+ if (same.termsId !== delegation.termsId) {
177
+ withdrawTurn(store, same, "admitted under terms that have since ended", now.toISOString());
178
+ }
179
+ else {
180
+ const exact = same.owner === input.starter.name && same.ownerGeneration === input.starter.generation && same.termsDigest === delegation.digest && same.level === input.level
181
+ && same.provider === input.provider && same.model === input.model && same.billing === input.billing && same.holder === input.holder;
182
+ return exact ? { ok: true, turn: same.id, seq: same.seq, replayed: true } : refuse("request-changed");
183
+ }
184
+ }
185
+ if (store.handle.prepare("SELECT 1 AS hit FROM thread_turn WHERE thread = ? AND status IN ('admitted', 'running')").get(input.thread) !== undefined)
186
+ return refuse("turn-in-progress");
187
+ const launch = store.handle.prepare("SELECT level, provider, state FROM flexible_thread_launch WHERE thread = ? AND state <> 'exited'").get(input.thread);
188
+ if (launch !== undefined) {
189
+ if (launch["state"] !== "live") {
190
+ return { ok: false, reason: "level-pending", message: "Some of this thread's agent's processes are still being stopped, so no new turn starts until they have. Try again in a moment." };
191
+ }
192
+ if (launch["level"] !== input.level || launch["provider"] !== input.provider) {
193
+ const was = isFlexibleLevel(launch["level"]) ? FLEXIBLE_LEVEL_WORDS[launch["level"]] : "another level";
194
+ return { ok: false, reason: "level-pending", message: `This thread's agent is still running at ${was}. Stop it, and its next turn starts at ${FLEXIBLE_LEVEL_WORDS[input.level]}.` };
195
+ }
196
+ }
197
+ const chosen = store.handle.prepare("SELECT level FROM flexible_thread_level WHERE thread = ?").get(input.thread);
198
+ const chosenLevel = chosen !== undefined && isFlexibleLevel(chosen["level"]) ? chosen["level"] : null;
199
+ if (chosenLevel !== null && FLEXIBLE_LEVELS.indexOf(input.level) > FLEXIBLE_LEVELS.indexOf(chosenLevel) && input.freshProof !== true) {
200
+ return { ok: false, reason: "proof-required", message: `This thread was lowered to ${FLEXIBLE_LEVEL_WORDS[chosenLevel]}. Raising it to ${FLEXIBLE_LEVEL_WORDS[input.level]} needs your password.` };
201
+ }
202
+ const allowed = threadLevelAllowed(store.orgPolicy(), input.provider, input.level);
203
+ if (!allowed.ok)
204
+ return allowed;
205
+ const limits = countsRefusal(store, repo, input.starter.name, delegation.terms, now) ?? spendRefusal(store, repo, input.starter.name, input.provider, input.billing, delegation.terms, now, false);
206
+ if (limits !== null)
207
+ return limits;
208
+ const day = now.toISOString().slice(0, 10);
209
+ const before = reservedStarts(store, repo, day);
210
+ const rail = store.reserveModeRail(repo, 1, now);
211
+ if (!rail.ok)
212
+ return capReached(rail.rail === "daily-runs" ? "mode-runs" : "mode-dollars", `This project's mode limits it: ${rail.detail}.`, nextUtcDay(now));
213
+ const railReserved = reservedStarts(store, repo, day) > before ? 1 : 0;
214
+ const id = randomBytes(16).toString("hex");
215
+ const seq = Number(store.handle.prepare("SELECT COALESCE(MAX(seq), 0) + 1 AS n FROM thread_turn WHERE thread = ?").get(input.thread)["n"]);
216
+ const at = now.toISOString();
217
+ store.handle.prepare(`INSERT INTO thread_turn (id, thread, seq, repo, owner, owner_generation, terms_id, terms_digest, level, provider, model, billing, request_key, holder, admitted_at, utc_day, rail_reserved, status)
218
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'admitted')`).run(id, input.thread, seq, repo, input.starter.name, input.starter.generation, delegation.termsId, delegation.digest, input.level, input.provider, input.model, input.billing, input.requestKey, input.holder, at, day, railReserved);
219
+ if (chosenLevel !== null && FLEXIBLE_LEVELS.indexOf(input.level) > FLEXIBLE_LEVELS.indexOf(chosenLevel)) {
220
+ store.handle.prepare("UPDATE flexible_thread_level SET level = ?, set_by = ?, set_at = ? WHERE thread = ?").run(input.level, input.starter.name, at, input.thread);
221
+ }
222
+ store.recordAction({ at, actor: input.starter.name, repo, taskId: null, runId: null, source: "policy", action: "flexible turn admitted", outcome: "admitted",
223
+ detail: `thread ${input.thread} · turn ${seq} · ${input.level} · ${input.provider} ${input.model} · ${input.billing} · terms ${delegation.digest}` });
224
+ return { ok: true, turn: id, seq, replayed: false };
225
+ });
226
+ }
227
+ function countsRefusal(store, repo, person, terms, now) {
228
+ const day = now.toISOString().slice(0, 10);
229
+ const tomorrow = nextUtcDay(now);
230
+ const caps = terms.caps;
231
+ const project = usageOf(store, day, repo);
232
+ if (project.threads >= caps.liveThreads) {
233
+ return capReached("project-threads", `This project already has ${plural(project.threads, "thread")} working, the most its Flexible terms allow. Try again when one finishes.`, null);
234
+ }
235
+ if (project.turns >= caps.turnsPerDayProject)
236
+ return capReached("project-turns", `This project used its ${plural(caps.turnsPerDayProject, "agent turn")} for today. ${TOMORROW}`, tomorrow);
237
+ const personTurns = Number(store.handle.prepare("SELECT COUNT(*) AS n FROM thread_turn WHERE owner = ? AND utc_day = ? AND status <> 'withdrawn'").get(person, day)["n"]);
238
+ if (personTurns >= caps.turnsPerDayPerson)
239
+ return capReached("person-turns", `You used your ${plural(caps.turnsPerDayPerson, "agent turn")} for today across Flexible projects. ${TOMORROW}`, tomorrow);
240
+ const own = flexibleInstallationCaps(store);
241
+ if (own.liveThreads !== null || own.turnsPerDay !== null) {
242
+ const all = usageOf(store, day, null);
243
+ if (own.liveThreads !== null && all.threads >= own.liveThreads) {
244
+ return capReached("installation-threads", `Toolroll already has ${plural(all.threads, "thread")} working, the most this installation allows. Try again when one finishes.`, null);
245
+ }
246
+ if (own.turnsPerDay !== null && all.turns >= own.turnsPerDay)
247
+ return capReached("installation-turns", `This installation used its ${plural(own.turnsPerDay, "agent turn")} for today. ${TOMORROW}`, tomorrow);
248
+ }
249
+ return null;
250
+ }
251
+ function spendRefusal(store, repo, owner, provider, billing, terms, now, modeReached) {
252
+ const day = now.toISOString().slice(0, 10);
253
+ const own = flexibleInstallationCaps(store);
254
+ if (own.measuredMicrousdPerDay !== null) {
255
+ const installation = dollarsRefusal("installation-dollars", "the installation's", own.measuredMicrousdPerDay, usageOf(store, day, null), now);
256
+ if (installation !== null)
257
+ return installation;
258
+ }
259
+ const project = usageOf(store, day, repo);
260
+ const projectDollars = dollarsRefusal("project-dollars", "this project's", terms.caps.measuredMicrousdPerDay, project, now);
261
+ if (projectDollars !== null)
262
+ return projectDollars;
263
+ const modeCap = modeDollarCap(store, repo, now);
264
+ if (modeCap !== null && (project.blind > 0 || modeReached)) {
265
+ const mode = dollarsRefusal("mode-dollars", "this project's mode", modeCap, { spent: modeReached ? modeSpentToday(store, repo, day) : 0, blind: project.blind }, now);
266
+ if (mode !== null)
267
+ return mode;
268
+ }
269
+ if (billing === "subscription") {
270
+ const spent = planSpent(store, provider, now);
271
+ if (spent !== null) {
272
+ const when = spent.until === null ? "when it resets" : `after it resets at ${spent.until.slice(11, 16)} UTC on ${spent.until.slice(0, 10)}`;
273
+ return capReached("plan", `Your ${PROVIDER_WORDS[provider]} plan's usage limit is reached. New turns can start ${when}.`, spent.until);
274
+ }
275
+ return null;
276
+ }
277
+ return budgetRefusal(store, repo, owner, provider, now);
278
+ }
279
+ export function beginFlexibleTurn(store, input) {
280
+ if (!FLEXIBLE_AVAILABLE)
281
+ return refuse("not-available");
282
+ if (!clockOk(input.clock))
283
+ return refuse("invalid-request");
284
+ return store.transact(() => {
285
+ const now = timeOf(input.clock);
286
+ const turn = flexibleTurn(store, input.turn);
287
+ if (turn === null)
288
+ return refuse("turn-unknown");
289
+ if (turn.status !== "admitted")
290
+ return refuse("turn-not-admitted");
291
+ if (turn.holder !== input.holder)
292
+ return refuse("held-elsewhere");
293
+ const at = now.toISOString();
294
+ const withdraw = (refusal) => { withdrawTurn(store, turn, refusal.message, at); return refusal; };
295
+ if (at.slice(0, 10) !== turn.utcDay)
296
+ return withdraw(refuse("turn-expired"));
297
+ const thread = store.handle.prepare("SELECT state, created_by FROM flexible_thread WHERE id = ?").get(turn.thread);
298
+ if (thread === undefined || thread["state"] !== "ready")
299
+ return withdraw(refuse("thread-not-ready"));
300
+ if (thread["created_by"] !== turn.owner)
301
+ return withdraw(refuse("not-owner"));
302
+ const delegation = flexibleDelegationAtUse(store, { repo: turn.repo, starter: { name: turn.owner, generation: turn.ownerGeneration }, digest: turn.termsDigest, level: turn.level, freshProof: true });
303
+ if (!delegation.ok)
304
+ return withdraw(delegation);
305
+ const chosen = store.handle.prepare("SELECT level FROM flexible_thread_level WHERE thread = ?").get(turn.thread);
306
+ if (chosen !== undefined && isFlexibleLevel(chosen["level"]) && FLEXIBLE_LEVELS.indexOf(turn.level) > FLEXIBLE_LEVELS.indexOf(chosen["level"])) {
307
+ return withdraw({ ok: false, reason: "level-pending", message: `This thread was lowered to ${FLEXIBLE_LEVEL_WORDS[chosen["level"]]} after this message was sent, so it didn't start. Send it again.` });
308
+ }
309
+ if (delegation.termsId !== turn.termsId) {
310
+ return withdraw({ ok: false, reason: "terms-changed", message: "This project's Flexible terms changed since this turn was admitted, so it didn't start. Send the message again." });
311
+ }
312
+ const spend = spendRefusal(store, turn.repo, turn.owner, turn.provider, turn.billing, delegation.terms, now, true);
313
+ if (spend !== null)
314
+ return withdraw(spend);
315
+ store.handle.prepare("UPDATE thread_turn SET status = 'running', started_at = ? WHERE id = ? AND status = 'admitted'").run(at, turn.id);
316
+ return { ok: true, turn: flexibleTurn(store, turn.id) };
317
+ });
318
+ }
319
+ const BASIS_RANK = Object.freeze({ measured: 0, estimated: 1, unknown: 2 });
320
+ const worse = (a, b) => a === null || BASIS_RANK[b] > BASIS_RANK[a] ? b : a;
321
+ const validUsage = (usage) => typeof usage === "object" && usage !== null && Number.isSafeInteger(usage.tokensIn) && usage.tokensIn >= 0
322
+ && Number.isSafeInteger(usage.tokensOut) && usage.tokensOut >= 0 && (usage.costUsd === null || (typeof usage.costUsd === "number" && Number.isFinite(usage.costUsd) && usage.costUsd >= 0));
323
+ function priced(store, turn, usage, model) {
324
+ const price = priceWork(store.handle, { provider: turn.provider, model, costUsd: usage.costUsd, tokensIn: usage.tokensIn, tokensOut: usage.tokensOut, billing: turn.billing });
325
+ if (price.microusd === null || price.source === "unpriced")
326
+ return { microusd: 0, basis: "unknown" };
327
+ return { microusd: Math.max(0, price.microusd), basis: price.source === "reported" ? "measured" : "estimated" };
328
+ }
329
+ export function chargeFlexibleTurn(store, input) {
330
+ if (!FLEXIBLE_AVAILABLE)
331
+ return refuse("not-available");
332
+ if (!validUsage(input.usage) || (input.model !== undefined && (typeof input.model !== "string" || !MODEL.test(input.model)))
333
+ || (input.incomplete !== undefined && typeof input.incomplete !== "boolean"))
334
+ return refuse("invalid-request");
335
+ return store.transact(() => {
336
+ const turn = flexibleTurn(store, input.turn);
337
+ if (turn === null)
338
+ return refuse("turn-unknown");
339
+ if (turn.status === "admitted" || turn.status === "withdrawn")
340
+ return refuse("turn-not-running");
341
+ const priced1 = priced(store, turn, input.usage, input.model ?? turn.model);
342
+ const cost = input.incomplete === true ? { microusd: priced1.microusd, basis: "unknown" } : priced1;
343
+ const basis = turn.status === "running" ? worse(turn.costBasis, cost.basis) : cost.basis === "unknown" ? "unknown" : turn.costBasis;
344
+ store.handle.prepare("UPDATE thread_turn SET tokens_in = tokens_in + ?, tokens_out = tokens_out + ?, cost_microusd = cost_microusd + ?, relay_calls = relay_calls + 1, cost_basis = ? WHERE id = ?")
345
+ .run(input.usage.tokensIn, input.usage.tokensOut, cost.microusd, basis, turn.id);
346
+ return { ok: true, costMicrousd: cost.microusd, basis: cost.basis };
347
+ });
348
+ }
349
+ export function finishFlexibleTurn(store, input) {
350
+ if (!FLEXIBLE_AVAILABLE)
351
+ return refuse("not-available");
352
+ if ((input.outcome !== "finished" && input.outcome !== "unknown") || (input.usage !== null && !validUsage(input.usage)) || !clockOk(input.clock))
353
+ return refuse("invalid-request");
354
+ return store.transact(() => {
355
+ const turn = flexibleTurn(store, input.turn);
356
+ if (turn === null)
357
+ return refuse("turn-unknown");
358
+ if (turn.status !== "running")
359
+ return refuse("turn-not-running");
360
+ if (turn.holder !== input.holder)
361
+ return refuse("held-elsewhere");
362
+ const at = timeOf(input.clock).toISOString();
363
+ const detail = input.detail === undefined ? null : input.detail.slice(0, 2000);
364
+ if (turn.relayCalls > 0) {
365
+ store.handle.prepare("UPDATE thread_turn SET status = ?, ended_at = ?, end_detail = ?, cost_basis = ? WHERE id = ?").run(input.outcome, at, detail, turn.costBasis ?? "unknown", turn.id);
366
+ }
367
+ else if (input.usage !== null) {
368
+ const cost = priced(store, turn, input.usage, turn.model);
369
+ store.handle.prepare("UPDATE thread_turn SET status = ?, ended_at = ?, end_detail = ?, tokens_in = ?, tokens_out = ?, cost_microusd = ?, cost_basis = ? WHERE id = ?")
370
+ .run(input.outcome, at, detail, input.usage.tokensIn, input.usage.tokensOut, cost.microusd, cost.basis, turn.id);
371
+ }
372
+ else {
373
+ store.handle.prepare("UPDATE thread_turn SET status = ?, ended_at = ?, end_detail = ?, cost_basis = 'unknown' WHERE id = ?").run(input.outcome, at, detail, turn.id);
374
+ }
375
+ relayCancel({ turn: turn.id });
376
+ return { ok: true, turn: flexibleTurn(store, turn.id) };
377
+ });
378
+ }
379
+ export function interruptFlexibleTurnsOf(store, input) {
380
+ if (!FLEXIBLE_AVAILABLE)
381
+ return refuse("not-available");
382
+ if (typeof input.holder !== "string" || !KEY.test(input.holder) || !clockOk(input.clock))
383
+ return refuse("invalid-request");
384
+ return store.transact(() => {
385
+ const at = timeOf(input.clock).toISOString();
386
+ let withdrawn = 0, interrupted = 0;
387
+ for (const row of store.handle.prepare("SELECT * FROM thread_turn WHERE holder = ? AND status IN ('admitted', 'running') ORDER BY admitted_at, id").all(input.holder)) {
388
+ const turn = readTurn(row);
389
+ if (turn.status === "admitted") {
390
+ withdrawTurn(store, turn, "not started before Toolroll restarted", at);
391
+ withdrawn++;
392
+ }
393
+ else {
394
+ const basis = turn.billing === "subscription" ? turn.costBasis ?? "unknown" : "unknown";
395
+ store.handle.prepare("UPDATE thread_turn SET status = 'interrupted', ended_at = ?, end_detail = 'interrupted when Toolroll restarted', cost_basis = ? WHERE id = ?").run(at, basis, turn.id);
396
+ relayCancel({ turn: turn.id });
397
+ interrupted++;
398
+ }
399
+ }
400
+ if (withdrawn + interrupted > 0) {
401
+ store.recordAction({ at, actor: "toolroll", repo: null, taskId: null, runId: null, source: "policy", action: "flexible turns ended at restart", outcome: "interrupted",
402
+ detail: `${plural(interrupted, "turn")} interrupted, ${plural(withdrawn, "turn")} not started withdrawn` });
403
+ }
404
+ return { ok: true, withdrawn, interrupted };
405
+ });
406
+ }
407
+ const INSTALLATION_LIMITS = { liveThreads: 1000, turnsPerDay: 1_000_000, measuredMicrousdPerDay: 100_000_000 * 1_000_000 };
408
+ const limitOk = (value, max) => value === null || (typeof value === "number" && Number.isSafeInteger(value) && value >= 1 && value <= max);
409
+ export function setFlexibleInstallationCaps(store, input) {
410
+ if (!FLEXIBLE_AVAILABLE)
411
+ return refuse("not-available");
412
+ const caps = input.caps;
413
+ if (typeof caps !== "object" || caps === null || !limitOk(caps.liveThreads, INSTALLATION_LIMITS.liveThreads) || !limitOk(caps.turnsPerDay, INSTALLATION_LIMITS.turnsPerDay)
414
+ || !limitOk(caps.measuredMicrousdPerDay, INSTALLATION_LIMITS.measuredMicrousdPerDay) || !clockOk(input.clock))
415
+ return refuse("invalid-request");
416
+ return store.transact(() => {
417
+ const account = store.accountOf(input.by);
418
+ if (account === null || account.revokedAt !== null || !store.isInstanceOperator(input.by))
419
+ return refuse("not-an-operator");
420
+ const before = flexibleInstallationCaps(store);
421
+ const at = timeOf(input.clock).toISOString();
422
+ store.handle.prepare(`INSERT INTO flexible_installation_caps (id, live_threads, turns_per_day, measured_microusd_per_day, updated_by, updated_at) VALUES (1, ?, ?, ?, ?, ?)
423
+ ON CONFLICT (id) DO UPDATE SET live_threads = excluded.live_threads, turns_per_day = excluded.turns_per_day, measured_microusd_per_day = excluded.measured_microusd_per_day,
424
+ updated_by = excluded.updated_by, updated_at = excluded.updated_at`).run(caps.liveThreads, caps.turnsPerDay, caps.measuredMicrousdPerDay, input.by, at);
425
+ const words = (one) => `threads ${one.liveThreads ?? "none"}, turns a day ${one.turnsPerDay ?? "none"}, dollars a day ${one.measuredMicrousdPerDay === null ? "none" : dollars(one.measuredMicrousdPerDay)}`;
426
+ store.recordAction({ at, actor: input.by, repo: null, taskId: null, runId: null, source: "policy", action: "flexible installation limits changed", outcome: "changed", detail: `${words(before)} → ${words(caps)}` });
427
+ return { ok: true, caps: { liveThreads: caps.liveThreads, turnsPerDay: caps.turnsPerDay, measuredMicrousdPerDay: caps.measuredMicrousdPerDay } };
428
+ });
429
+ }
430
+ export function withdrawFlexibleTurn(store, input) {
431
+ if (!FLEXIBLE_AVAILABLE)
432
+ return refuse("not-available");
433
+ if (typeof input.detail !== "string" || !clockOk(input.clock))
434
+ return refuse("invalid-request");
435
+ return store.transact(() => {
436
+ const at = timeOf(input.clock).toISOString();
437
+ const turn = flexibleTurn(store, input.turn);
438
+ if (turn === null)
439
+ return refuse("turn-unknown");
440
+ if (turn.status !== "admitted")
441
+ return refuse("turn-not-admitted");
442
+ if (turn.holder !== input.holder)
443
+ return refuse("held-elsewhere");
444
+ withdrawTurn(store, turn, input.detail, at);
445
+ return { ok: true };
446
+ });
447
+ }
448
+ export function interruptFlexibleThreadTurns(store, input) {
449
+ if (!FLEXIBLE_AVAILABLE)
450
+ return refuse("not-available");
451
+ if (typeof input.thread !== "string" || typeof input.detail !== "string" || !clockOk(input.clock))
452
+ return refuse("invalid-request");
453
+ return store.transact(() => {
454
+ const at = timeOf(input.clock).toISOString();
455
+ let withdrawn = 0, interrupted = 0;
456
+ for (const row of store.handle.prepare("SELECT * FROM thread_turn WHERE thread = ? AND status IN ('admitted', 'running')").all(input.thread)) {
457
+ const turn = readTurn(row);
458
+ if (turn.id === input.except)
459
+ continue;
460
+ if (turn.status === "admitted") {
461
+ withdrawTurn(store, turn, input.detail, at);
462
+ withdrawn++;
463
+ continue;
464
+ }
465
+ const basis = turn.billing === "subscription" ? turn.costBasis ?? "unknown" : "unknown";
466
+ store.handle.prepare("UPDATE thread_turn SET status = 'interrupted', ended_at = ?, end_detail = ?, cost_basis = ? WHERE id = ? AND status = 'running'").run(at, input.detail.slice(0, 2000), basis, turn.id);
467
+ relayCancel({ turn: turn.id });
468
+ interrupted++;
469
+ }
470
+ return { ok: true, withdrawn, interrupted };
471
+ });
472
+ }
473
+ export function withdrawFlexibleTurnsAbove(store, input) {
474
+ if (!FLEXIBLE_AVAILABLE)
475
+ return refuse("not-available");
476
+ if (typeof input.thread !== "string" || !isFlexibleLevel(input.level) || typeof input.detail !== "string" || !clockOk(input.clock))
477
+ return refuse("invalid-request");
478
+ return store.transact(() => {
479
+ const at = timeOf(input.clock).toISOString();
480
+ let withdrawn = 0;
481
+ for (const row of store.handle.prepare("SELECT * FROM thread_turn WHERE thread = ? AND status = 'admitted'").all(input.thread)) {
482
+ const turn = readTurn(row);
483
+ if (FLEXIBLE_LEVELS.indexOf(turn.level) <= FLEXIBLE_LEVELS.indexOf(input.level))
484
+ continue;
485
+ withdrawTurn(store, turn, input.detail, at);
486
+ withdrawn++;
487
+ }
488
+ return { ok: true, withdrawn };
489
+ });
490
+ }
@@ -0,0 +1,44 @@
1
+ import { FLEXIBLE_LAPSE_WORDS, FLEXIBLE_LEVEL_WORDS, FLEXIBLE_LEVELS, flexibleTermsWords } from "./flexible.js";
2
+ import { html, joinHtml, postForm } from "./html.js";
3
+ import { acts, btn, disclose, formRow, note, notice, select, settingsSection } from "./server/kit.js";
4
+ import { kitSectionForm } from "./settings-kit.js";
5
+ const ACTION = "/settings/project/flexible";
6
+ const termsList = (terms) => html `<ul class="k-note">${flexibleTermsWords(terms).map(line => html `<li>${line}</li>`)}</ul>`;
7
+ function enableForm(view, label) {
8
+ if ("problem" in view.proposal)
9
+ return note(view.proposal.problem);
10
+ return kitSectionForm({ proof: "project-flexible", action: ACTION, id: "flexible-on", native: true, hidden: { repo: view.repo, action: "enable", digest: view.proposal.digest },
11
+ save: { label }, confirm: "Turn on Flexible",
12
+ body: joinHtml([termsList(view.proposal.terms), note("Turning this on asks for your password, every time.")]) });
13
+ }
14
+ function lowerAndOff(view, terms) {
15
+ const below = terms === null ? [] : FLEXIBLE_LEVELS.slice(0, FLEXIBLE_LEVELS.indexOf(terms.max));
16
+ return joinHtml([
17
+ below.length === 0 ? "" : postForm(ACTION, joinHtml([
18
+ formRow("Highest level", null, select({ id: "flexible-max", name: "max", items: below.map(level => [level, FLEXIBLE_LEVEL_WORDS[level]]), current: below.at(-1), sm: true }), "inline"),
19
+ acts(btn("Lower", { sm: true, type: "submit" })),
20
+ ]), { hidden: { repo: view.repo, action: "lower" } }),
21
+ postForm(ACTION, acts(btn("Turn off Flexible", { sm: true, type: "submit" })), { hidden: { repo: view.repo, action: "off" } }),
22
+ ]);
23
+ }
24
+ export function flexibleSettingsHtml(view) {
25
+ if (view === undefined)
26
+ return "";
27
+ const standing = view.standing;
28
+ const changer = view.canChange ? null : note("An approver for this project can change this.");
29
+ if (standing.state === "secure") {
30
+ return settingsSection({ id: "flexible", title: "How work starts", state: " · Secure", lead: "Work is planned and approved before it starts.",
31
+ body: changer ?? disclose("Turn on Flexible", enableForm(view, "Turn on Flexible")) });
32
+ }
33
+ if (standing.state === "unreadable") {
34
+ return settingsSection({ id: "flexible", title: "How work starts", state: " · Unavailable", lead: notice("This project's Flexible terms can't be read, so they allow nothing."),
35
+ body: changer ?? lowerAndOff(view, null) });
36
+ }
37
+ if (standing.state === "lapsed") {
38
+ return settingsSection({ id: "flexible", title: "How work starts", state: " · Flexible terms ended", lead: notice(`${FLEXIBLE_LAPSE_WORDS[standing.reason]} No new Flexible threads start.`),
39
+ body: changer ?? joinHtml([disclose("Turn on again", enableForm(view, "Turn on again")), lowerAndOff(view, null)]) });
40
+ }
41
+ return settingsSection({ id: "flexible", title: "How work starts", state: ` · Flexible, up to ${FLEXIBLE_LEVEL_WORDS[standing.terms.max]}`,
42
+ lead: `Agent threads start at once, at ${FLEXIBLE_LEVEL_WORDS[standing.terms.default]}. Turned on by ${standing.signedBy}.`,
43
+ body: joinHtml([disclose("Terms", termsList(standing.terms)), changer ?? lowerAndOff(view, standing.terms)]) });
44
+ }