toolroll 0.9.109 → 0.9.111
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +73 -0
- package/README.md +5 -1
- package/THIRD_PARTY_NOTICES.md +30 -0
- package/dist/agent-detect.js +244 -0
- package/dist/agent-fence.js +12 -1
- package/dist/agent-said-schema.js +4 -0
- package/dist/agent-said.js +23 -0
- package/dist/agentconfig.js +2 -2
- package/dist/approval-summary.js +375 -0
- package/dist/attest.js +2 -2
- package/dist/browser/THIRD_PARTY_NOTICES.txt +30 -0
- package/dist/browser/workspace.css +2 -2
- package/dist/browser/workspace.js +27 -27
- package/dist/builder.js +42 -3
- package/dist/chat-actions.js +24 -17
- package/dist/chat-core.js +3 -1
- package/dist/chat-decide.js +101 -46
- package/dist/chat-delivery-state.js +2 -0
- package/dist/chat-delivery.js +3 -2
- package/dist/chat-live.js +2 -1
- package/dist/chat-task-actions.js +6 -0
- package/dist/check-report.js +1 -1
- package/dist/claim.js +28 -13
- package/dist/cli-help.js +1 -1
- package/dist/cli.js +2 -0
- package/dist/codex-limits.js +21 -8
- package/dist/console-instance.js +11 -1
- package/dist/contracts/console-api.js +13 -7
- package/dist/contracts/engine-api.js +283 -0
- package/dist/contracts/route.js +1 -0
- package/dist/coordinator.js +2 -2
- package/dist/discord-api.js +4 -3
- package/dist/discord-chat.js +3 -1
- package/dist/dispatch.js +1 -1
- package/dist/dispose.js +15 -9
- package/dist/easy-start-args.js +7 -3
- package/dist/easy-start.js +40 -1
- package/dist/egress.js +72 -10
- package/dist/engine-handoff.js +34 -0
- package/dist/engine-reads.js +338 -0
- package/dist/eval-world.js +3 -2
- package/dist/evidence.js +2 -0
- package/dist/fast-start.js +68 -18
- package/dist/fast-terms.js +2 -2
- package/dist/first-run.js +10 -2
- package/dist/flexible-agents.js +234 -0
- package/dist/flexible-answers-schema.js +61 -0
- package/dist/flexible-answers.js +889 -0
- package/dist/flexible-custody.js +494 -0
- package/dist/flexible-import.js +782 -0
- package/dist/flexible-launch-schema.js +72 -0
- package/dist/flexible-launch.js +331 -0
- package/dist/flexible-launcher.js +88 -0
- package/dist/flexible-levels.js +34 -0
- package/dist/flexible-merge-guard.js +47 -0
- package/dist/flexible-refs.js +47 -0
- package/dist/flexible-relay-cancel.js +19 -0
- package/dist/flexible-relay-schema.js +55 -0
- package/dist/flexible-relay-upstreams.js +36 -0
- package/dist/flexible-relay.js +1032 -0
- package/dist/flexible-session.js +732 -0
- package/dist/flexible-ship-schema.js +81 -0
- package/dist/flexible-ship.js +694 -0
- package/dist/flexible-start.js +80 -0
- package/dist/flexible-thread.js +175 -25
- package/dist/flexible-turns-schema.js +69 -0
- package/dist/flexible-turns.js +490 -0
- package/dist/flexible.js +10 -1
- package/dist/flow-actions.js +6 -4
- package/dist/flow-steps.js +1 -1
- package/dist/flows-cli.js +2 -1
- package/dist/git-views.js +6 -3
- package/dist/install-mode.js +225 -0
- package/dist/integrations.js +6 -1
- package/dist/lead-doors.js +7 -1
- package/dist/limits-ui.js +7 -0
- package/dist/live-reply.js +6 -0
- package/dist/live-terminal.js +425 -29
- package/dist/local-owner.js +7 -0
- package/dist/model-choices.js +12 -6
- package/dist/needs-you.js +2 -0
- package/dist/notification-delivery.js +11 -0
- package/dist/operate.js +128 -37
- package/dist/outbound-privacy.js +204 -0
- package/dist/passwordless.js +2 -1
- package/dist/phase-routing.js +3 -1
- package/dist/plane-review.js +1 -1
- package/dist/project-delete.js +14 -0
- package/dist/proposal.js +2 -2
- package/dist/provider-connection.js +19 -5
- package/dist/publish.js +5 -0
- package/dist/pull-request-flow.js +26 -7
- package/dist/push.js +5 -1
- package/dist/release-card.js +11 -3
- package/dist/release.js +10 -1
- package/dist/route-store.js +3 -3
- package/dist/sandbox-launch.js +32 -8
- package/dist/sandbox-runtime.js +16 -7
- package/dist/sandbox-tools.js +176 -0
- package/dist/scope.js +12 -36
- package/dist/scout-net.js +7 -2
- package/dist/serve.js +62 -13
- package/dist/server/chrome.js +3 -1
- package/dist/server/console.css +33 -6
- package/dist/server/engine-api.js +378 -0
- package/dist/server/flows.js +2 -2
- package/dist/server/http.js +7 -0
- package/dist/server/link-redemption.js +52 -0
- package/dist/server/mutation-key.js +21 -7
- package/dist/server/pages.js +72 -40
- package/dist/server/people-tokens.js +17 -41
- package/dist/server/render-chat.js +1 -0
- package/dist/server/render-new-task.js +3 -3
- package/dist/server/render-results.js +4 -4
- package/dist/server/render-tasks.js +133 -139
- package/dist/server/route-table.js +32 -1
- package/dist/server/settings-section-table.js +6 -0
- package/dist/server/settings-sections.js +69 -0
- package/dist/server/settings.js +120 -10
- package/dist/server/task-views.js +8 -2
- package/dist/server/tasks.js +56 -12
- package/dist/server/terminals.js +181 -28
- package/dist/server/welcome.js +35 -10
- package/dist/settings-groups-ui.js +2 -2
- package/dist/settings-proofs.js +14 -9
- package/dist/slack-api.js +4 -3
- package/dist/slack-chat.js +5 -3
- package/dist/spend.js +46 -12
- package/dist/status-probe.js +343 -0
- package/dist/store.js +181 -12
- package/dist/task-sizing-schema.js +14 -0
- package/dist/task-sizing.js +76 -10
- package/dist/teams-api.js +4 -3
- package/dist/teams-chat.js +4 -2
- package/dist/telegram-lead.js +2 -1
- package/dist/telegram-live.js +2 -1
- package/dist/telegram-team.js +2 -1
- package/dist/telegram.js +17 -5
- package/dist/toolroll-update.js +3 -1
- package/dist/trusted-path.js +162 -0
- package/dist/tui/darwin-arm64/toolroll-tui +0 -0
- package/dist/tui/darwin-x64/toolroll-tui +0 -0
- package/dist/tui/linux-arm64/toolroll-tui +0 -0
- package/dist/tui/linux-x64/toolroll-tui +0 -0
- package/dist/tui-launch.js +282 -0
- package/dist/tui-source.js +5 -3
- package/dist/tui.js +1 -1
- package/dist/webhooks.js +14 -4
- package/dist/welcome-facts.js +22 -15
- package/dist/work-index.js +2 -2
- package/dist/workspace-ui.js +5 -0
- package/package.json +1 -1
- package/scripts/crash-canary.mjs +1 -1
- package/scripts/pilot.mjs +1 -1
- package/scripts/provider-canary.mjs +5 -3
|
@@ -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
|
+
}
|
package/dist/flexible.js
CHANGED
|
@@ -214,7 +214,16 @@ const levelsWords = (terms) => `max ${terms.max}, password-free ${terms.password
|
|
|
214
214
|
function endRow(store, id, reason, by, detail, now) {
|
|
215
215
|
const ended = store.handle.prepare("UPDATE flexible_terms SET ended_at = ?, ended_by = ?, end_reason = ?, end_detail = ? WHERE id = ? AND ended_at IS NULL")
|
|
216
216
|
.run(now.toISOString(), by, reason, detail, id);
|
|
217
|
-
|
|
217
|
+
if (Number(ended.changes) !== 1)
|
|
218
|
+
return false;
|
|
219
|
+
const ships = store.handle.prepare("SELECT id, repo, task_id FROM flexible_ship WHERE delegation_id = ? AND state IN ('armed', 'completed')").all(id);
|
|
220
|
+
for (const ship of ships) {
|
|
221
|
+
store.handle.prepare("UPDATE flexible_ship SET state = 'cancelled', detail = ?, state_at = ? WHERE id = ? AND state IN ('armed', 'completed')")
|
|
222
|
+
.run(`the project's Flexible terms it was shipped under ended (${reason})`, now.toISOString(), String(ship["id"]));
|
|
223
|
+
store.recordAction({ at: now.toISOString(), actor: by, repo: String(ship["repo"]), taskId: ship["task_id"] === null ? null : String(ship["task_id"]), runId: null, source: "policy",
|
|
224
|
+
action: "flexible merge cancelled", outcome: "cancelled", detail: `ship ${String(ship["id"])} · the Flexible terms ended (${reason})` });
|
|
225
|
+
}
|
|
226
|
+
return true;
|
|
218
227
|
}
|
|
219
228
|
function insertRow(store, row, now) {
|
|
220
229
|
const written = store.handle.prepare(`INSERT INTO flexible_terms (repo, terms_json, digest, signed_terms_json, signed_digest, signed_by, signed_at, proof, changed_by, changed_at, derived_from)
|
package/dist/flow-actions.js
CHANGED
|
@@ -7,6 +7,7 @@ import { readFlowSecrets, scrubSecrets } from "./flow-secrets.js";
|
|
|
7
7
|
export { readEmailSettings, saveEmailSettings } from "./email-settings.js";
|
|
8
8
|
import { callProjectTool, projectToolsOf, readToolSecrets, toolServerFor } from "./project-tools.js";
|
|
9
9
|
import { ALL_CREDENTIAL_ENV } from "./provider.js";
|
|
10
|
+
import { safeMail } from "./outbound-privacy.js";
|
|
10
11
|
const clip = (text, cap) => text.length <= cap ? text : `${text.slice(0, cap - 1)}…`;
|
|
11
12
|
const blank = (text) => redactSecretAssignments(redactSecretLines(text, scanForSecrets(text)));
|
|
12
13
|
const scrub = scrubSecrets;
|
|
@@ -123,7 +124,7 @@ export const sendThroughServer = async (settings, mail) => {
|
|
|
123
124
|
transport.close();
|
|
124
125
|
}
|
|
125
126
|
};
|
|
126
|
-
export async function sendEmail(stage, card, io, thread = null) {
|
|
127
|
+
export async function sendEmail(stage, card, io, thread = null, repo = null) {
|
|
127
128
|
const account = await sendingAccount(io.dir, io.fetch ?? fetch);
|
|
128
129
|
if (!account.ok)
|
|
129
130
|
return { state: account.permanent ? "failed" : "retry", said: account.said };
|
|
@@ -140,11 +141,12 @@ export async function sendEmail(stage, card, io, thread = null) {
|
|
|
140
141
|
const source = card.source?.mail;
|
|
141
142
|
const known = thread ?? (source?.id ? { inReplyTo: source.id, references: [...source.references, source.id].slice(-20), people: new Set([source.from]) } : null);
|
|
142
143
|
const threaded = known !== null && to.some(one => known.people.has(one.toLowerCase())) ? { inReplyTo: known.inReplyTo, references: known.references } : {};
|
|
143
|
-
const
|
|
144
|
-
const
|
|
144
|
+
const mail = safeMail({ from: settings.from, to, subject, text: body, ...threaded }, { project: repo });
|
|
145
|
+
const sent = await (io.mail ?? sendThroughServer)(settings, mail);
|
|
146
|
+
const log = `From ${settings.from} to ${to.join(", ")}\nSubject: ${mail.subject}\n\n${blank(mail.text)}`;
|
|
145
147
|
if (!sent.ok)
|
|
146
148
|
return { state: sent.permanent ? "failed" : "retry", said: sent.said, log };
|
|
147
|
-
return { state: "passed", said: `Emailed ${to.join(", ")}.`, log, output: `Sent to ${to.join(", ")}: “${subject}”`, mail: { id: sent.id, to } };
|
|
149
|
+
return { state: "passed", said: `Emailed ${to.join(", ")}.`, log, output: `Sent to ${to.join(", ")}: “${mail.subject}”`, mail: { id: sent.id, to } };
|
|
148
150
|
}
|
|
149
151
|
export function toolWaiting(store, stage, repo) {
|
|
150
152
|
const wanted = stage.tool?.server ?? "";
|
package/dist/flow-steps.js
CHANGED
|
@@ -129,7 +129,7 @@ export async function runFlowSteps(store, repo, now, io) {
|
|
|
129
129
|
: stage.kind === "sort" ? await sortCard(known.definition, stage, card, key, io)
|
|
130
130
|
: stage.kind === "draft" ? await draftCard(store, known.definition, stage, card, io, repo, now)
|
|
131
131
|
: stage.kind === "request" ? await runRequest(stage, card, repo, io)
|
|
132
|
-
: stage.kind === "email" ? await sendEmail(stage, card, io, threadOf(store, card))
|
|
132
|
+
: stage.kind === "email" ? await sendEmail(stage, card, io, threadOf(store, card), repo)
|
|
133
133
|
: stage.kind === "tool" ? await useTool(store, stage, card, repo, io)
|
|
134
134
|
: await updateSource(store, stage, card, io, now);
|
|
135
135
|
}
|
package/dist/flows-cli.js
CHANGED
|
@@ -407,7 +407,8 @@ export async function runFlowsCommand(positional, flags, context) {
|
|
|
407
407
|
const given = text('digest');
|
|
408
408
|
if (given === null)
|
|
409
409
|
return fail('usage', `Approve exactly what you read: flows browser ${flow.id} on --yes --digest <the digest the preview showed>.`, EXIT.usage);
|
|
410
|
-
const
|
|
410
|
+
const browserProof = proveCredential(store, acting.name, acting.token, flow.repo);
|
|
411
|
+
const signed = signFlowBrowser(store, { flow: flow.id, signer: who, proof: browserProof.ok ? browserProof.method : null, sawDigest: given }, now);
|
|
411
412
|
if (!signed.ok)
|
|
412
413
|
return refuse(flow.repo, 'refused', `${signed.message} Nothing was changed.`);
|
|
413
414
|
record(flow.repo, 'accepted', `flow #${flow.id} browser on`);
|
package/dist/git-views.js
CHANGED
|
@@ -83,14 +83,17 @@ export async function lockCheckout(home, checkout, timeoutMs = 10 * 60_000) {
|
|
|
83
83
|
}
|
|
84
84
|
const heldHere = new AsyncLocalStorage();
|
|
85
85
|
export async function withCheckoutLock(home, checkout, work, timeoutMs) {
|
|
86
|
-
const held = heldHere.getStore()
|
|
87
|
-
|
|
86
|
+
const held = heldHere.getStore();
|
|
87
|
+
const hold = held?.get(checkout);
|
|
88
|
+
if (hold !== undefined && !hold.released)
|
|
88
89
|
return work();
|
|
89
90
|
const release = await lockCheckout(home, checkout, timeoutMs);
|
|
91
|
+
const mine = { released: false };
|
|
90
92
|
try {
|
|
91
|
-
return await heldHere.run(new
|
|
93
|
+
return await heldHere.run(new Map([...(held ?? new Map()), [checkout, mine]]), work);
|
|
92
94
|
}
|
|
93
95
|
finally {
|
|
96
|
+
mine.released = true;
|
|
94
97
|
release();
|
|
95
98
|
}
|
|
96
99
|
}
|