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,72 @@
|
|
|
1
|
+
export const V165_SCHEMA = `
|
|
2
|
+
CREATE TABLE IF NOT EXISTS flexible_thread_launch (
|
|
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
|
+
turn TEXT CHECK (turn IS NULL OR (length(turn) = 32 AND turn NOT GLOB '*[^0-9a-f]*')),
|
|
6
|
+
provider TEXT NOT NULL CHECK (provider IN ('claude', 'codex', 'gemini', 'openrouter')),
|
|
7
|
+
level TEXT NOT NULL CHECK (level IN ('supervised', 'auto', 'full')),
|
|
8
|
+
fence_digest TEXT NOT NULL CHECK (length(fence_digest) = 32 AND fence_digest NOT GLOB '*[^0-9a-f]*'),
|
|
9
|
+
holder TEXT NOT NULL CHECK (length(holder) BETWEEN 1 AND 128),
|
|
10
|
+
host TEXT NOT NULL,
|
|
11
|
+
machine_id TEXT,
|
|
12
|
+
boot_id TEXT,
|
|
13
|
+
marker TEXT NOT NULL CHECK (length(marker) = 32 AND marker NOT GLOB '*[^0-9a-f]*'),
|
|
14
|
+
leader_pid INTEGER CHECK (leader_pid IS NULL OR leader_pid > 1),
|
|
15
|
+
leader_start TEXT,
|
|
16
|
+
namespaces TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(namespaces) AND json_type(namespaces) = 'array'),
|
|
17
|
+
witnesses TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(witnesses) AND json_type(witnesses) = 'array'),
|
|
18
|
+
state TEXT NOT NULL CHECK (state IN ('spawning', 'live', 'stopping', 'exited', 'unresolved')),
|
|
19
|
+
started_at TEXT NOT NULL,
|
|
20
|
+
stop_reason TEXT CHECK (stop_reason IS NULL OR length(stop_reason) <= 200),
|
|
21
|
+
ended_at TEXT,
|
|
22
|
+
end_detail TEXT CHECK (end_detail IS NULL OR length(end_detail) <= 2000),
|
|
23
|
+
network_closed_at TEXT,
|
|
24
|
+
CHECK ((leader_pid IS NULL) = (leader_start IS NULL)),
|
|
25
|
+
CHECK (state NOT IN ('live', 'stopping', 'unresolved') OR leader_pid IS NOT NULL),
|
|
26
|
+
CHECK ((ended_at IS NULL) = (state <> 'exited'))
|
|
27
|
+
);
|
|
28
|
+
CREATE UNIQUE INDEX IF NOT EXISTS flexible_thread_launch_unsettled ON flexible_thread_launch (thread) WHERE state <> 'exited';
|
|
29
|
+
CREATE INDEX IF NOT EXISTS flexible_thread_launch_holder ON flexible_thread_launch (holder, state);
|
|
30
|
+
CREATE TRIGGER IF NOT EXISTS flexible_thread_launch_written_once BEFORE UPDATE ON flexible_thread_launch
|
|
31
|
+
WHEN NEW.id IS NOT OLD.id OR NEW.thread IS NOT OLD.thread OR NEW.turn IS NOT OLD.turn OR NEW.provider IS NOT OLD.provider OR NEW.level IS NOT OLD.level
|
|
32
|
+
OR NEW.fence_digest IS NOT OLD.fence_digest OR NEW.holder IS NOT OLD.holder OR NEW.host IS NOT OLD.host OR NEW.machine_id IS NOT OLD.machine_id
|
|
33
|
+
OR NEW.boot_id IS NOT OLD.boot_id OR NEW.marker IS NOT OLD.marker OR NEW.started_at IS NOT OLD.started_at
|
|
34
|
+
OR (OLD.leader_pid IS NOT NULL AND (NEW.leader_pid IS NOT OLD.leader_pid OR NEW.leader_start IS NOT OLD.leader_start))
|
|
35
|
+
OR (OLD.network_closed_at IS NOT NULL AND NEW.network_closed_at IS NOT OLD.network_closed_at)
|
|
36
|
+
OR OLD.state = 'exited'
|
|
37
|
+
OR (OLD.state = 'spawning' AND NEW.state NOT IN ('spawning', 'live', 'exited'))
|
|
38
|
+
OR (OLD.state = 'live' AND NEW.state = 'spawning')
|
|
39
|
+
OR (OLD.state IN ('stopping', 'unresolved') AND NEW.state NOT IN ('stopping', 'unresolved', 'exited'))
|
|
40
|
+
OR json_array_length(NEW.namespaces) < json_array_length(OLD.namespaces) OR json_array_length(NEW.witnesses) < json_array_length(OLD.witnesses)
|
|
41
|
+
BEGIN
|
|
42
|
+
SELECT RAISE(ABORT, 'a flexible launch is written once, its state only moves forward and what it saw only grows');
|
|
43
|
+
END;
|
|
44
|
+
CREATE TABLE IF NOT EXISTS flexible_relay_grant (
|
|
45
|
+
token_digest TEXT PRIMARY KEY CHECK (length(token_digest) = 64 AND token_digest NOT GLOB '*[^0-9a-f]*'),
|
|
46
|
+
thread TEXT NOT NULL CHECK (length(thread) = 32 AND thread NOT GLOB '*[^0-9a-f]*'),
|
|
47
|
+
turn TEXT NOT NULL CHECK (length(turn) = 32 AND turn NOT GLOB '*[^0-9a-f]*'),
|
|
48
|
+
launch TEXT NOT NULL CHECK (length(launch) = 32 AND launch NOT GLOB '*[^0-9a-f]*'),
|
|
49
|
+
issued_at TEXT NOT NULL,
|
|
50
|
+
revoked_at TEXT
|
|
51
|
+
);
|
|
52
|
+
CREATE INDEX IF NOT EXISTS flexible_relay_grant_launch ON flexible_relay_grant (launch, revoked_at);
|
|
53
|
+
CREATE TRIGGER IF NOT EXISTS flexible_relay_grant_written_once BEFORE UPDATE ON flexible_relay_grant
|
|
54
|
+
WHEN NEW.token_digest IS NOT OLD.token_digest OR NEW.thread IS NOT OLD.thread OR NEW.turn IS NOT OLD.turn OR NEW.launch IS NOT OLD.launch OR NEW.issued_at IS NOT OLD.issued_at
|
|
55
|
+
OR OLD.revoked_at IS NOT NULL OR NEW.revoked_at IS NULL
|
|
56
|
+
BEGIN
|
|
57
|
+
SELECT RAISE(ABORT, 'a relay grant is written once and only revoked');
|
|
58
|
+
END;
|
|
59
|
+
CREATE TABLE IF NOT EXISTS flexible_thread_level (
|
|
60
|
+
thread TEXT PRIMARY KEY CHECK (length(thread) = 32 AND thread NOT GLOB '*[^0-9a-f]*'),
|
|
61
|
+
level TEXT NOT NULL CHECK (level IN ('supervised', 'auto', 'full')),
|
|
62
|
+
set_by TEXT NOT NULL,
|
|
63
|
+
set_at TEXT NOT NULL
|
|
64
|
+
);
|
|
65
|
+
`;
|
|
66
|
+
export const V165_TABLES = Object.freeze(["flexible_thread_launch", "flexible_relay_grant", "flexible_thread_level"]);
|
|
67
|
+
export const V165_STEPS = Object.freeze(["thread-launch"]);
|
|
68
|
+
export const V165_OBJECTS = Object.freeze([
|
|
69
|
+
["table", "flexible_thread_launch"], ["index", "flexible_thread_launch_unsettled"], ["index", "flexible_thread_launch_holder"],
|
|
70
|
+
["trigger", "flexible_thread_launch_written_once"], ["table", "flexible_relay_grant"], ["index", "flexible_relay_grant_launch"],
|
|
71
|
+
["trigger", "flexible_relay_grant_written_once"], ["table", "flexible_thread_level"],
|
|
72
|
+
]);
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, rmdirSync, unlinkSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join } from "node:path";
|
|
4
|
+
import { hostname } from "node:os";
|
|
5
|
+
import { currentBootId } from "./boot-identity.js";
|
|
6
|
+
import { observeCustody, realCustodyIO, stopCustody, custodySettled } from "./flexible-custody.js";
|
|
7
|
+
import { interruptFlexibleThreadTurns } from "./flexible-turns.js";
|
|
8
|
+
import { currentMachineId } from "./machine-identity.js";
|
|
9
|
+
import { relayCancel } from "./flexible-relay-cancel.js";
|
|
10
|
+
export const FLEXIBLE_AGENT_PROVIDERS = ["claude", "codex", "gemini", "openrouter"];
|
|
11
|
+
const LAUNCH_ID = /^[0-9a-f]{32}$/;
|
|
12
|
+
const text = (value) => value === null || value === undefined ? null : String(value);
|
|
13
|
+
function list(json, valid) {
|
|
14
|
+
try {
|
|
15
|
+
const parsed = JSON.parse(String(json));
|
|
16
|
+
return Array.isArray(parsed) ? parsed.filter(valid) : [];
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return [];
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
const isNamespace = (one) => typeof one === "string" && /^pid:\[\d{1,20}\]$/.test(one);
|
|
23
|
+
const isWitness = (one) => typeof one === "object" && one !== null && Number.isSafeInteger(one.pid) && one.pid > 1
|
|
24
|
+
&& typeof one.start === "string" && /^[ts]\d{1,20}$/.test(one.start);
|
|
25
|
+
function readLaunch(row) {
|
|
26
|
+
if (row === undefined)
|
|
27
|
+
return null;
|
|
28
|
+
return { id: String(row["id"]), thread: String(row["thread"]), turn: text(row["turn"]), provider: String(row["provider"]), level: String(row["level"]),
|
|
29
|
+
fenceDigest: String(row["fence_digest"]), holder: String(row["holder"]), host: String(row["host"]), machineId: text(row["machine_id"]), bootId: text(row["boot_id"]), marker: String(row["marker"]),
|
|
30
|
+
leaderPid: row["leader_pid"] === null || row["leader_pid"] === undefined ? null : Number(row["leader_pid"]), leaderStart: text(row["leader_start"]),
|
|
31
|
+
namespaces: list(row["namespaces"], isNamespace), witnesses: list(row["witnesses"], isWitness), state: String(row["state"]),
|
|
32
|
+
startedAt: String(row["started_at"]), stopReason: text(row["stop_reason"]), endedAt: text(row["ended_at"]), endDetail: text(row["end_detail"]), networkClosedAt: text(row["network_closed_at"]) };
|
|
33
|
+
}
|
|
34
|
+
export function flexibleLaunch(store, id) {
|
|
35
|
+
if (!LAUNCH_ID.test(id))
|
|
36
|
+
return null;
|
|
37
|
+
return readLaunch(store.handle.prepare("SELECT * FROM flexible_thread_launch WHERE id = ?").get(id));
|
|
38
|
+
}
|
|
39
|
+
export function unsettledLaunch(store, thread) {
|
|
40
|
+
return readLaunch(store.handle.prepare("SELECT * FROM flexible_thread_launch WHERE thread = ? AND state <> 'exited'").get(thread));
|
|
41
|
+
}
|
|
42
|
+
export function custodyOf(launch, folder) {
|
|
43
|
+
return { host: launch.host, machineId: launch.machineId, bootId: launch.bootId, folder, namespaces: launch.namespaces, witnesses: launch.witnesses,
|
|
44
|
+
leader: launch.leaderPid === null || launch.leaderStart === null ? null : { pid: launch.leaderPid, start: launch.leaderStart } };
|
|
45
|
+
}
|
|
46
|
+
export const defaultCustodyIO = () => realCustodyIO(currentBootId);
|
|
47
|
+
export function recordSpawning(store, input) {
|
|
48
|
+
const id = randomBytes(16).toString("hex"), marker = randomBytes(16).toString("hex");
|
|
49
|
+
store.transact(() => {
|
|
50
|
+
const at = (input.clock ?? (() => new Date()))().toISOString();
|
|
51
|
+
store.handle.prepare(`INSERT INTO flexible_thread_launch (id, thread, turn, provider, level, fence_digest, holder, host, machine_id, boot_id, marker, state, started_at)
|
|
52
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'spawning', ?)`).run(id, input.thread, input.meta.turn, input.meta.provider, input.meta.level, input.fenceDigest, input.meta.holder, hostname(), currentMachineId(), input.bootId, marker, at);
|
|
53
|
+
});
|
|
54
|
+
return { id, marker };
|
|
55
|
+
}
|
|
56
|
+
export function recordLive(store, input) {
|
|
57
|
+
return store.transact(() => {
|
|
58
|
+
const at = (input.clock ?? (() => new Date()))().toISOString();
|
|
59
|
+
const live = store.handle.prepare("UPDATE flexible_thread_launch SET state = 'live', leader_pid = ?, leader_start = ? WHERE id = ? AND state = 'spawning'").run(input.pid, input.start, input.launch);
|
|
60
|
+
if (Number(live.changes) !== 1)
|
|
61
|
+
throw new Error("the launch's record moved");
|
|
62
|
+
const thread = store.handle.prepare("UPDATE flexible_thread SET live_pid = ?, live_since = ? WHERE id = ? AND state = 'ready'").run(input.pid, at, input.thread);
|
|
63
|
+
if (Number(thread.changes) !== 1)
|
|
64
|
+
throw new Error("the thread's record moved");
|
|
65
|
+
return true;
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
export function recordGateShut(store, input) {
|
|
69
|
+
store.transact(() => {
|
|
70
|
+
const at = (input.clock ?? (() => new Date()))().toISOString();
|
|
71
|
+
store.handle.prepare("UPDATE flexible_thread_launch SET state = 'exited', ended_at = ?, end_detail = ? WHERE id = ? AND state = 'live' AND leader_pid = ?").run(at, input.detail.slice(0, 2000), input.launch, input.pid);
|
|
72
|
+
store.handle.prepare("UPDATE flexible_thread SET live_pid = NULL, live_since = NULL WHERE id = ? AND live_pid = ?").run(input.thread, input.pid);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
const LAUNCHED = "flexible agent launched";
|
|
76
|
+
export function recordLaunchOpened(store, input) {
|
|
77
|
+
store.recordAction({ at: (input.clock ?? (() => new Date()))().toISOString(), actor: "toolroll", repo: null, taskId: null, runId: null, source: "policy", action: LAUNCHED, outcome: "launched",
|
|
78
|
+
detail: `turn ${input.turn ?? "none"} · thread ${input.thread} · launch ${input.launch}` });
|
|
79
|
+
}
|
|
80
|
+
export function flexibleTurnLaunched(store, turn) {
|
|
81
|
+
if (!/^[0-9a-f]{32}$/.test(turn))
|
|
82
|
+
return false;
|
|
83
|
+
return store.handle.prepare("SELECT 1 AS hit FROM action_ledger WHERE action = ? AND detail LIKE ? LIMIT 1").get(LAUNCHED, `turn ${turn} · %`) !== undefined;
|
|
84
|
+
}
|
|
85
|
+
export function recordNeverStarted(store, launch, detail, clock = () => new Date()) {
|
|
86
|
+
store.transact(() => {
|
|
87
|
+
store.handle.prepare("UPDATE flexible_thread_launch SET state = 'exited', ended_at = ?, end_detail = ? WHERE id = ? AND state = 'spawning'").run(clock().toISOString(), detail.slice(0, 2000), launch);
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
function recordSeen(store, launch, seen) {
|
|
91
|
+
if (seen.namespaces.length === 0 && seen.witnesses.length === 0)
|
|
92
|
+
return;
|
|
93
|
+
store.transact(() => {
|
|
94
|
+
const now = flexibleLaunch(store, launch.id);
|
|
95
|
+
if (now === null || now.state === "exited")
|
|
96
|
+
return;
|
|
97
|
+
const namespaces = [...new Set([...now.namespaces, ...seen.namespaces])];
|
|
98
|
+
const known = new Set(now.witnesses.map(one => `${one.pid}:${one.start}`));
|
|
99
|
+
const witnesses = [...now.witnesses, ...seen.witnesses.filter(one => !known.has(`${one.pid}:${one.start}`))].slice(0, Math.max(1000, now.witnesses.length));
|
|
100
|
+
store.handle.prepare("UPDATE flexible_thread_launch SET namespaces = ?, witnesses = ? WHERE id = ? AND state <> 'exited'").run(JSON.stringify(namespaces), JSON.stringify(witnesses), launch.id);
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
export function watchLaunch(store, launchId, folder, io = defaultCustodyIO(), everyMs = 500) {
|
|
104
|
+
let busy = false;
|
|
105
|
+
const tick = () => {
|
|
106
|
+
if (busy)
|
|
107
|
+
return;
|
|
108
|
+
busy = true;
|
|
109
|
+
void (async () => {
|
|
110
|
+
try {
|
|
111
|
+
const launch = flexibleLaunch(store, launchId);
|
|
112
|
+
if (launch === null || launch.state !== "live") {
|
|
113
|
+
const left = await revokeLaunch(launchId);
|
|
114
|
+
if (left === 0 && launch !== null)
|
|
115
|
+
markNetworkClosed(store, launchId);
|
|
116
|
+
if (left === 0 && (launch === null || launch.state === "exited"))
|
|
117
|
+
clearInterval(timer);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
recordSeen(store, launch, observeCustody(custodyOf(launch, folder), io));
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
}
|
|
124
|
+
finally {
|
|
125
|
+
busy = false;
|
|
126
|
+
}
|
|
127
|
+
})();
|
|
128
|
+
};
|
|
129
|
+
const timer = setInterval(tick, everyMs);
|
|
130
|
+
timer.unref();
|
|
131
|
+
tick();
|
|
132
|
+
return () => clearInterval(timer);
|
|
133
|
+
}
|
|
134
|
+
const revokers = new Map();
|
|
135
|
+
export function onLaunchStopped(launchId, revoke) {
|
|
136
|
+
revokers.set(launchId, [...revokers.get(launchId) ?? [], revoke]);
|
|
137
|
+
}
|
|
138
|
+
const held = new Map();
|
|
139
|
+
export function holdLaunch(launchId, child) { held.set(launchId, child); }
|
|
140
|
+
const leaderSignalOf = (launchId) => {
|
|
141
|
+
const child = held.get(launchId);
|
|
142
|
+
if (child === undefined)
|
|
143
|
+
return undefined;
|
|
144
|
+
return (signal) => {
|
|
145
|
+
if (child.exitCode !== null || child.signalCode !== null)
|
|
146
|
+
return "gone";
|
|
147
|
+
try {
|
|
148
|
+
return child.kill(signal) ? "sent" : "gone";
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return "denied";
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
};
|
|
155
|
+
function markNetworkClosed(store, launchId, clock = () => new Date()) {
|
|
156
|
+
store.transact(() => { store.handle.prepare("UPDATE flexible_thread_launch SET network_closed_at = ? WHERE id = ? AND network_closed_at IS NULL AND state <> 'exited'").run(clock().toISOString(), launchId); });
|
|
157
|
+
}
|
|
158
|
+
export async function revokeLaunch(launchId) {
|
|
159
|
+
const all = revokers.get(launchId) ?? [];
|
|
160
|
+
const failed = [];
|
|
161
|
+
for (const revoke of all) {
|
|
162
|
+
try {
|
|
163
|
+
await revoke();
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
failed.push(revoke);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const added = (revokers.get(launchId) ?? []).filter(one => !all.includes(one));
|
|
170
|
+
if (failed.length + added.length === 0)
|
|
171
|
+
revokers.delete(launchId);
|
|
172
|
+
else
|
|
173
|
+
revokers.set(launchId, [...failed, ...added]);
|
|
174
|
+
return failed.length + added.length;
|
|
175
|
+
}
|
|
176
|
+
const sha256 = (text) => createHash("sha256").update(text, "utf8").digest("hex");
|
|
177
|
+
export function issueRelayGrant(store, input) {
|
|
178
|
+
const token = `tr-relay-${randomBytes(24).toString("hex")}`;
|
|
179
|
+
store.transact(() => {
|
|
180
|
+
store.handle.prepare("INSERT INTO flexible_relay_grant (token_digest, thread, turn, launch, issued_at) VALUES (?, ?, ?, ?, ?)")
|
|
181
|
+
.run(sha256(token), input.thread, input.turn, input.launch, (input.clock ?? (() => new Date()))().toISOString());
|
|
182
|
+
});
|
|
183
|
+
return token;
|
|
184
|
+
}
|
|
185
|
+
export function relayGrantLive(store, token) {
|
|
186
|
+
if (typeof token !== "string" || !/^tr-relay-[0-9a-f]{48}$/.test(token))
|
|
187
|
+
return false;
|
|
188
|
+
const row = store.handle.prepare(`SELECT 1 AS ok FROM flexible_relay_grant g JOIN flexible_thread_launch l ON l.id = g.launch AND l.thread = g.thread
|
|
189
|
+
WHERE g.token_digest = ? AND g.revoked_at IS NULL AND l.state IN ('spawning', 'live')`).get(sha256(token));
|
|
190
|
+
return row !== undefined;
|
|
191
|
+
}
|
|
192
|
+
export function revokeRelayGrant(store, token, clock = () => new Date()) {
|
|
193
|
+
const revoked = store.transact(() => Number(store.handle.prepare("UPDATE flexible_relay_grant SET revoked_at = ? WHERE token_digest = ? AND revoked_at IS NULL").run(clock().toISOString(), sha256(token)).changes));
|
|
194
|
+
relayCancel({ digest: sha256(token) });
|
|
195
|
+
return revoked;
|
|
196
|
+
}
|
|
197
|
+
export function revokeLaunchGrants(store, launch, clock = () => new Date()) {
|
|
198
|
+
const revoked = store.transact(() => Number(store.handle.prepare("UPDATE flexible_relay_grant SET revoked_at = ? WHERE launch = ? AND revoked_at IS NULL").run(clock().toISOString(), launch).changes));
|
|
199
|
+
relayCancel({ launch });
|
|
200
|
+
return revoked;
|
|
201
|
+
}
|
|
202
|
+
export async function settleLaunch(store, input) {
|
|
203
|
+
const clock = input.clock ?? (() => new Date());
|
|
204
|
+
const launch = unsettledLaunch(store, input.thread);
|
|
205
|
+
if (launch === null)
|
|
206
|
+
return { ok: true, launch: null, how: "nothing-running", interrupted: 0 };
|
|
207
|
+
if (input.expect !== undefined && (launch.id !== input.expect.launch || launch.holder !== input.expect.holder))
|
|
208
|
+
return { ok: true, launch: null, how: "replaced", interrupted: 0 };
|
|
209
|
+
const io = input.io ?? defaultCustodyIO();
|
|
210
|
+
if (launch.state === "spawning" && launch.leaderPid === null) {
|
|
211
|
+
revokeLaunchGrants(store, launch.id, clock);
|
|
212
|
+
recordNeverStarted(store, launch.id, "its start gate never opened, so its agent never ran", clock);
|
|
213
|
+
return { ok: true, launch: launch.id, how: "never-started", interrupted: 0 };
|
|
214
|
+
}
|
|
215
|
+
revokeLaunchGrants(store, launch.id, clock);
|
|
216
|
+
let network = null;
|
|
217
|
+
if (held.has(launch.id)) {
|
|
218
|
+
const left = await revokeLaunch(launch.id);
|
|
219
|
+
if (left === 0)
|
|
220
|
+
markNetworkClosed(store, launch.id, clock);
|
|
221
|
+
else
|
|
222
|
+
network = `${left === 1 ? "1 of its network handles" : `${left} of its network handles`} couldn't be closed yet; Toolroll keeps trying`;
|
|
223
|
+
}
|
|
224
|
+
else if (input.holderGone === true) {
|
|
225
|
+
markNetworkClosed(store, launch.id, clock);
|
|
226
|
+
}
|
|
227
|
+
if (input.stop) {
|
|
228
|
+
store.transact(() => {
|
|
229
|
+
store.handle.prepare("UPDATE flexible_thread_launch SET state = 'stopping', stop_reason = COALESCE(stop_reason, ?) WHERE id = ? AND state IN ('live', 'unresolved', 'stopping')").run(input.reason.slice(0, 200), launch.id);
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
const custody = custodyOf(launch, input.folder);
|
|
233
|
+
const leaderSignal = leaderSignalOf(launch.id);
|
|
234
|
+
const outcome = input.stop ? await stopCustody(custody, io, leaderSignal === undefined ? {} : { leaderSignal }) : custodySettled(custody, io);
|
|
235
|
+
if (outcome.verified && outcome.how === "boot-changed")
|
|
236
|
+
markNetworkClosed(store, launch.id, clock);
|
|
237
|
+
if (network === null && flexibleLaunch(store, launch.id)?.networkClosedAt == null)
|
|
238
|
+
network = "the Toolroll process that started it hasn't confirmed its network handles closed yet";
|
|
239
|
+
return store.transact(() => {
|
|
240
|
+
const now = clock();
|
|
241
|
+
const at = now.toISOString();
|
|
242
|
+
recordSeenInside(store, launch.id, outcome);
|
|
243
|
+
if (!outcome.verified || network !== null) {
|
|
244
|
+
const why = outcome.verified ? network : outcome.why;
|
|
245
|
+
store.handle.prepare("UPDATE flexible_thread_launch SET state = 'unresolved', end_detail = ? WHERE id = ? AND state <> 'exited'").run(why.slice(0, 2000), launch.id);
|
|
246
|
+
store.recordAction({ at, actor: "toolroll", repo: null, taskId: null, runId: null, source: "policy", action: "flexible agent custody unresolved", outcome: "unresolved",
|
|
247
|
+
detail: `thread ${launch.thread} · launch ${launch.id} · ${why}` });
|
|
248
|
+
return { ok: false, launch: launch.id, survivors: outcome.verified ? [] : outcome.survivors, blockers: outcome.verified ? [] : outcome.blockers, why };
|
|
249
|
+
}
|
|
250
|
+
held.delete(launch.id);
|
|
251
|
+
const detail = outcome.how === "boot-changed" ? "the computer restarted since it was launched"
|
|
252
|
+
: outcome.how === "best-effort" ? "every process of it was found stopped (best effort on this computer: a signal went to a process number checked just before)"
|
|
253
|
+
: "every process of it was found stopped";
|
|
254
|
+
store.handle.prepare("UPDATE flexible_thread_launch SET state = 'exited', ended_at = ?, end_detail = ? WHERE id = ? AND state <> 'exited'").run(at, detail, launch.id);
|
|
255
|
+
store.handle.prepare("UPDATE flexible_thread SET live_pid = NULL, live_since = NULL WHERE id = ? AND live_pid IS ?").run(launch.thread, launch.leaderPid);
|
|
256
|
+
const turns = interruptFlexibleThreadTurns(store, { thread: launch.thread, detail: `the thread's agent was stopped (${input.reason})`, clock: () => now, ...(input.keepTurn === undefined ? {} : { except: input.keepTurn }) });
|
|
257
|
+
const ended = turns.ok ? turns.interrupted : 0;
|
|
258
|
+
store.recordAction({ at, actor: "toolroll", repo: null, taskId: null, runId: null, source: "policy", action: "flexible agent stopped", outcome: "exited",
|
|
259
|
+
detail: `thread ${launch.thread} · launch ${launch.id} · ${input.reason} · ${detail}` });
|
|
260
|
+
return { ok: true, launch: launch.id, how: outcome.how, interrupted: ended };
|
|
261
|
+
});
|
|
262
|
+
}
|
|
263
|
+
function recordSeenInside(store, launchId, seen) {
|
|
264
|
+
const launch = flexibleLaunch(store, launchId);
|
|
265
|
+
if (launch !== null)
|
|
266
|
+
recordSeen(store, launch, seen);
|
|
267
|
+
}
|
|
268
|
+
function ownRealFolder(path) {
|
|
269
|
+
try {
|
|
270
|
+
const held = lstatSync(path);
|
|
271
|
+
return held.isDirectory() && !held.isSymbolicLink() && (process.getuid === undefined || held.uid === process.getuid());
|
|
272
|
+
}
|
|
273
|
+
catch {
|
|
274
|
+
return false;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
function removeNoFollow(path) {
|
|
278
|
+
const held = lstatSync(path);
|
|
279
|
+
if (!held.isDirectory() || held.isSymbolicLink()) {
|
|
280
|
+
unlinkSync(path);
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
for (const name of readdirSync(path))
|
|
284
|
+
removeNoFollow(join(path, name));
|
|
285
|
+
rmdirSync(path);
|
|
286
|
+
}
|
|
287
|
+
export function freshProviderFolder(store, thread, paths, configHome) {
|
|
288
|
+
let quiet = false;
|
|
289
|
+
try {
|
|
290
|
+
quiet = unsettledLaunch(store, thread) === null;
|
|
291
|
+
}
|
|
292
|
+
catch {
|
|
293
|
+
quiet = false;
|
|
294
|
+
}
|
|
295
|
+
if (!quiet)
|
|
296
|
+
return "an earlier agent of the thread isn't proved stopped, so its folders weren't touched";
|
|
297
|
+
const provider = join(paths.cache, "provider");
|
|
298
|
+
if (dirname(configHome) !== provider)
|
|
299
|
+
return "its configuration folder isn't inside the thread's cache";
|
|
300
|
+
for (const folder of [paths.root, paths.folder, paths.cache])
|
|
301
|
+
if (!ownRealFolder(folder))
|
|
302
|
+
return `${basename(folder)} isn't a real folder of Toolroll's (a link or something else is there)`;
|
|
303
|
+
try {
|
|
304
|
+
if (realpathSync(paths.cache) !== paths.cache)
|
|
305
|
+
return "the thread's cache isn't where Toolroll put it";
|
|
306
|
+
}
|
|
307
|
+
catch {
|
|
308
|
+
return "the thread's cache can't be read";
|
|
309
|
+
}
|
|
310
|
+
try {
|
|
311
|
+
if (existsSync(provider) || isLink(provider)) {
|
|
312
|
+
if (!ownRealFolder(provider))
|
|
313
|
+
return "the cache's provider folder isn't a real folder (a link or something else is there)";
|
|
314
|
+
removeNoFollow(provider);
|
|
315
|
+
}
|
|
316
|
+
mkdirSync(provider, { mode: 0o700 });
|
|
317
|
+
if (!ownRealFolder(provider))
|
|
318
|
+
return "the cache's provider folder couldn't be made";
|
|
319
|
+
mkdirSync(configHome, { mode: 0o700 });
|
|
320
|
+
return null;
|
|
321
|
+
}
|
|
322
|
+
catch {
|
|
323
|
+
return "the cache's provider folder couldn't be made fresh";
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
const isLink = (path) => { try {
|
|
327
|
+
return lstatSync(path).isSymbolicLink();
|
|
328
|
+
}
|
|
329
|
+
catch {
|
|
330
|
+
return false;
|
|
331
|
+
} };
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
|
|
4
|
+
import { FLEXIBLE_UNAVAILABLE } from "./flexible.js";
|
|
5
|
+
import { NETWORK_POLICY_VERSION, proxyEnv, REGISTRY_HOSTS, repositoryEcosystems, startEgressProxy } from "./egress.js";
|
|
6
|
+
import { prepareProtectedStorage, storageRefusalOf } from "./protected-storage.js";
|
|
7
|
+
const WORDS = Object.freeze({
|
|
8
|
+
"not-available": FLEXIBLE_UNAVAILABLE,
|
|
9
|
+
"network-changed": "This project's network setting changed since the terms were shown. Look at them again before starting. Nothing was started.",
|
|
10
|
+
"storage": "Toolroll couldn't finish checking other apps' data for links to keep out of the thread, so nothing was started.",
|
|
11
|
+
"no-network": "The thread's network proxy couldn't be started, so nothing was started.",
|
|
12
|
+
});
|
|
13
|
+
const refuse = (reason, message = WORDS[reason]) => ({ ok: false, reason, message });
|
|
14
|
+
export function flexibleThreadNetwork(store, repo) {
|
|
15
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
16
|
+
return refuse("not-available");
|
|
17
|
+
const project = store.projectNetwork(repo);
|
|
18
|
+
if (project.mode === "open")
|
|
19
|
+
return { version: NETWORK_POLICY_VERSION, mode: "open", hosts: [], loopback: "proxy-only" };
|
|
20
|
+
const hosts = new Set([...repositoryEcosystems(repo).flatMap(one => REGISTRY_HOSTS[one]), ...project.hosts]);
|
|
21
|
+
return { version: NETWORK_POLICY_VERSION, mode: "allowlist", hosts: [...hosts].sort(), loopback: "proxy-only" };
|
|
22
|
+
}
|
|
23
|
+
export function flexibleNetworkDigest(network) {
|
|
24
|
+
return createHash("sha256").update(`standing-orders:flexible-network:${JSON.stringify({ mode: network.mode, hosts: network.hosts, loopback: network.loopback })}`, "utf8").digest("hex").slice(0, 32);
|
|
25
|
+
}
|
|
26
|
+
export function createFlexibleLauncher(store, seams = {}) {
|
|
27
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
28
|
+
return refuse("not-available");
|
|
29
|
+
const startProxy = seams.startProxy ?? ((options) => startEgressProxy(options));
|
|
30
|
+
const storageNow = seams.storage ?? (() => prepareProtectedStorage(homedir()));
|
|
31
|
+
const live = new Map();
|
|
32
|
+
let closed = false;
|
|
33
|
+
const closerOf = (proxy) => {
|
|
34
|
+
let closing = null;
|
|
35
|
+
return () => {
|
|
36
|
+
if (closing !== null)
|
|
37
|
+
return closing;
|
|
38
|
+
const attempt = (async () => { await proxy.close(); })().then(() => { live.delete(proxy); }, (error) => { if (closing === attempt)
|
|
39
|
+
closing = null; throw error; });
|
|
40
|
+
closing = attempt;
|
|
41
|
+
return attempt;
|
|
42
|
+
};
|
|
43
|
+
};
|
|
44
|
+
return {
|
|
45
|
+
...(seams.platform === undefined ? {} : { platform: seams.platform }),
|
|
46
|
+
open: () => live.size,
|
|
47
|
+
async prepare(thread, expect) {
|
|
48
|
+
if (closed)
|
|
49
|
+
return refuse("no-network");
|
|
50
|
+
const network = flexibleThreadNetwork(store, thread.repo);
|
|
51
|
+
if ("ok" in network)
|
|
52
|
+
return network;
|
|
53
|
+
if (expect !== undefined && flexibleNetworkDigest(network) !== expect.network)
|
|
54
|
+
return refuse("network-changed");
|
|
55
|
+
let storage;
|
|
56
|
+
try {
|
|
57
|
+
storage = await storageNow();
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
const words = storageRefusalOf(error)?.message;
|
|
61
|
+
return refuse("storage", words ?? WORDS.storage);
|
|
62
|
+
}
|
|
63
|
+
let proxy;
|
|
64
|
+
try {
|
|
65
|
+
proxy = await startProxy(network.mode === "open" ? { hosts: [], open: true } : { hosts: network.hosts });
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return refuse("no-network");
|
|
69
|
+
}
|
|
70
|
+
const close = closerOf(proxy);
|
|
71
|
+
live.set(proxy, close);
|
|
72
|
+
if (closed) {
|
|
73
|
+
try {
|
|
74
|
+
await close();
|
|
75
|
+
}
|
|
76
|
+
catch { }
|
|
77
|
+
return refuse("no-network");
|
|
78
|
+
}
|
|
79
|
+
return { ok: true, storage, network: { proxyPort: proxy.port, token: proxy.secret, proxyEnv: proxyEnv(proxy, "proxy-only"), close } };
|
|
80
|
+
},
|
|
81
|
+
async close() {
|
|
82
|
+
closed = true;
|
|
83
|
+
await Promise.allSettled([...live.values()].map(close => close()));
|
|
84
|
+
if (live.size > 0)
|
|
85
|
+
throw new Error(`${live.size} of the threads' network proxies couldn't be closed yet`);
|
|
86
|
+
},
|
|
87
|
+
};
|
|
88
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { FLEXIBLE_LEVEL_WORDS } from "./flexible.js";
|
|
2
|
+
const off = (why) => ({ offered: false, why });
|
|
3
|
+
const NO_CHANNEL = "its permission requests can't reach you yet, so this level can't ask you anything";
|
|
4
|
+
const CODEX = "Codex's own sandbox can't keep a Flexible thread away from threads and files made after it starts";
|
|
5
|
+
const OPENROUTER = "OpenRouter runs on the Codex harness, whose own sandbox can't keep a Flexible thread away from threads and files made after it starts";
|
|
6
|
+
const GEMINI = "Gemini's turns can't be recorded yet and it has no sign-in relay";
|
|
7
|
+
export const FLEXIBLE_PROVEN = Object.freeze({
|
|
8
|
+
claude: Object.freeze({
|
|
9
|
+
supervised: off(NO_CHANNEL),
|
|
10
|
+
auto: off(NO_CHANNEL),
|
|
11
|
+
full: { offered: true, how: "Claude Code with --permission-mode bypassPermissions inside the thread's sandbox, signed in only through Toolroll's relay" },
|
|
12
|
+
}),
|
|
13
|
+
codex: Object.freeze({ supervised: off(CODEX), auto: off(CODEX), full: off(CODEX) }),
|
|
14
|
+
openrouter: Object.freeze({ supervised: off(OPENROUTER), auto: off(OPENROUTER), full: off(OPENROUTER) }),
|
|
15
|
+
gemini: Object.freeze({ supervised: off(NO_CHANNEL), auto: off(NO_CHANNEL), full: off(GEMINI) }),
|
|
16
|
+
});
|
|
17
|
+
const AGENT_WORDS = Object.freeze({ claude: "Claude", codex: "Codex", gemini: "Gemini", openrouter: "OpenRouter" });
|
|
18
|
+
const RANK = Object.freeze({ supervised: 0, auto: 1, full: 2 });
|
|
19
|
+
const TOP = Object.freeze({ safe: "supervised", standard: "auto", escalated: "full" });
|
|
20
|
+
export function threadLevelAllowed(policy, agent, level, proven = FLEXIBLE_PROVEN) {
|
|
21
|
+
const entry = proven[agent]?.[level];
|
|
22
|
+
const top = TOP[policy.ceiling];
|
|
23
|
+
if (entry === undefined || RANK[level] === undefined)
|
|
24
|
+
return { ok: false, reason: "level-unavailable", message: "That agent or level isn't one Toolroll knows. Nothing was started." };
|
|
25
|
+
if (top === undefined || RANK[level] > RANK[top]) {
|
|
26
|
+
return { ok: false, reason: "above-ceiling", message: `Your organisation's permission ceiling doesn't allow ${FLEXIBLE_LEVEL_WORDS[level]} threads. Nothing was started.` };
|
|
27
|
+
}
|
|
28
|
+
if (!entry.offered)
|
|
29
|
+
return { ok: false, reason: "level-unavailable", message: `${AGENT_WORDS[agent]} threads can't run at ${FLEXIBLE_LEVEL_WORDS[level]}: ${entry.why}. Nothing was started.` };
|
|
30
|
+
if (policy.ceiling === "safe" && entry.asksBeforeEveryAction !== true) {
|
|
31
|
+
return { ok: false, reason: "above-ceiling", message: `Your organisation's permission ceiling allows only a Supervised that asks before every step, and ${AGENT_WORDS[agent]}'s doesn't yet. Nothing was started.` };
|
|
32
|
+
}
|
|
33
|
+
return { ok: true, how: entry.how };
|
|
34
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export const FLEXIBLE_FILED_PREFIX = "flexible:";
|
|
2
|
+
export const FLEXIBLE_MERGE_WORDS = "This result came from a Flexible thread. It merges only by itself, through its Ship, after its check passed on this exact commit.";
|
|
3
|
+
export function flexibleMergeRefusal(store, taskId, road, authority = {}, moment = "start") {
|
|
4
|
+
if (taskId === null)
|
|
5
|
+
return null;
|
|
6
|
+
const via = store.filedViaOf(taskId);
|
|
7
|
+
if (via === null || !via.startsWith(FLEXIBLE_FILED_PREFIX))
|
|
8
|
+
return null;
|
|
9
|
+
if (road !== "pull-request" || authority.anyway === true || authority.ship === undefined || authority.token === undefined || `${FLEXIBLE_FILED_PREFIX}${authority.ship}` !== via)
|
|
10
|
+
return FLEXIBLE_MERGE_WORDS;
|
|
11
|
+
let row;
|
|
12
|
+
try {
|
|
13
|
+
row = store.handle.prepare("SELECT state, merge_token FROM flexible_ship WHERE id = ? AND task_id = ?").get(authority.ship, taskId);
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return FLEXIBLE_MERGE_WORDS;
|
|
17
|
+
}
|
|
18
|
+
if (row === undefined)
|
|
19
|
+
return FLEXIBLE_MERGE_WORDS;
|
|
20
|
+
if (moment === "start")
|
|
21
|
+
return row["state"] === "completed" || (row["state"] === "merging" && row["merge_token"] === authority.token) ? null : FLEXIBLE_MERGE_WORDS;
|
|
22
|
+
return row["state"] === "merging" && row["merge_token"] === authority.token ? null : FLEXIBLE_MERGE_WORDS;
|
|
23
|
+
}
|
|
24
|
+
export const FLEXIBLE_CANDIDATE_FIXED = "A Flexible Ship's task checks exactly the commit its Ship imported, so its prepared commit can't be replaced. Ship again from the thread instead.";
|
|
25
|
+
export function flexibleCandidateChangeRefusal(store, taskId, previous, next) {
|
|
26
|
+
if (previous == null || (next ?? null) === previous)
|
|
27
|
+
return null;
|
|
28
|
+
return store.filedViaOf(taskId)?.startsWith(FLEXIBLE_FILED_PREFIX) === true ? FLEXIBLE_CANDIDATE_FIXED : null;
|
|
29
|
+
}
|
|
30
|
+
export function flexibleAdoption(store, taskId, prepared, scopeDigest) {
|
|
31
|
+
const via = store.filedViaOf(taskId);
|
|
32
|
+
if (via === null || !via.startsWith(FLEXIBLE_FILED_PREFIX))
|
|
33
|
+
return null;
|
|
34
|
+
const refusal = { refuse: "This task came from a Flexible thread, and its prepared commit isn't exactly the commit its Ship imported and sealed, so nothing was committed. Ship again from the thread." };
|
|
35
|
+
let row;
|
|
36
|
+
try {
|
|
37
|
+
row = store.handle.prepare("SELECT id, candidate, import_ref, scope_digest, state FROM flexible_ship WHERE task_id = ?").get(taskId);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return refusal;
|
|
41
|
+
}
|
|
42
|
+
if (row === undefined || via !== `${FLEXIBLE_FILED_PREFIX}${String(row["id"])}` || !["armed", "completed"].includes(String(row["state"])))
|
|
43
|
+
return refusal;
|
|
44
|
+
if (prepared === null || prepared !== row["candidate"] || scopeDigest === null || scopeDigest !== row["scope_digest"])
|
|
45
|
+
return refusal;
|
|
46
|
+
return { adopt: { importRef: String(row["import_ref"]), candidate: prepared } };
|
|
47
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
const MAX_REFS = 100_000;
|
|
3
|
+
export async function readProjectRefs(git, project) {
|
|
4
|
+
const listed = await git(project, ["for-each-ref", "--format=%(refname)%00%(objectname)"]);
|
|
5
|
+
if (listed.code !== 0)
|
|
6
|
+
return null;
|
|
7
|
+
const refs = {};
|
|
8
|
+
const lines = listed.stdout.split("\n").filter(line => line !== "");
|
|
9
|
+
if (lines.length > MAX_REFS)
|
|
10
|
+
return null;
|
|
11
|
+
for (const line of lines) {
|
|
12
|
+
const [name, sha, extra] = line.split("\0");
|
|
13
|
+
if (name === undefined || sha === undefined || extra !== undefined || !/^refs\/[^\0\n]{1,1000}$/.test(name) || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(sha))
|
|
14
|
+
return null;
|
|
15
|
+
refs[name] = sha;
|
|
16
|
+
}
|
|
17
|
+
return refs;
|
|
18
|
+
}
|
|
19
|
+
const refsJson = (refs) => JSON.stringify(Object.fromEntries(Object.entries(refs).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))));
|
|
20
|
+
export function saveRefSnapshot(store, thread, refs, at) {
|
|
21
|
+
const json = refsJson(refs);
|
|
22
|
+
store.handle.prepare(`INSERT INTO flexible_ref_snapshot (thread, taken_at, refs_json, digest) VALUES (?, ?, ?, ?)
|
|
23
|
+
ON CONFLICT (thread) DO UPDATE SET taken_at = excluded.taken_at, refs_json = excluded.refs_json, digest = excluded.digest`)
|
|
24
|
+
.run(thread, at.toISOString(), json, createHash("sha256").update(json, "utf8").digest("hex"));
|
|
25
|
+
}
|
|
26
|
+
export function refSnapshotOf(store, thread) {
|
|
27
|
+
const row = store.handle.prepare("SELECT refs_json, digest FROM flexible_ref_snapshot WHERE thread = ?").get(thread);
|
|
28
|
+
if (row === undefined)
|
|
29
|
+
return null;
|
|
30
|
+
const json = String(row["refs_json"]);
|
|
31
|
+
if (createHash("sha256").update(json, "utf8").digest("hex") !== row["digest"])
|
|
32
|
+
return null;
|
|
33
|
+
try {
|
|
34
|
+
const parsed = JSON.parse(json);
|
|
35
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
|
|
36
|
+
return null;
|
|
37
|
+
const refs = parsed;
|
|
38
|
+
return Object.values(refs).every(value => typeof value === "string") ? refs : null;
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
export function refsChangedOutside(before, after) {
|
|
45
|
+
const names = new Set([...Object.keys(before), ...Object.keys(after)]);
|
|
46
|
+
return [...names].filter(name => !name.startsWith("refs/toolroll/") && before[name] !== after[name]).sort();
|
|
47
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
const listeners = new Set();
|
|
2
|
+
export function onRelayCancel(hear, failed) {
|
|
3
|
+
const listener = { hear, failed };
|
|
4
|
+
listeners.add(listener);
|
|
5
|
+
return () => { listeners.delete(listener); };
|
|
6
|
+
}
|
|
7
|
+
export function relayCancel(cancel) {
|
|
8
|
+
for (const listener of [...listeners]) {
|
|
9
|
+
try {
|
|
10
|
+
listener.hear(cancel);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
try {
|
|
14
|
+
listener.failed();
|
|
15
|
+
}
|
|
16
|
+
catch { }
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
}
|