toolroll 0.9.109 → 0.9.110
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +35 -0
- package/dist/agent-detect.js +244 -0
- package/dist/agent-fence.js +12 -1
- package/dist/agentconfig.js +2 -2
- package/dist/approval-summary.js +344 -0
- package/dist/attest.js +2 -2
- package/dist/browser/workspace.css +2 -2
- package/dist/browser/workspace.js +27 -27
- package/dist/builder.js +36 -2
- 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/cli.js +2 -0
- package/dist/console-instance.js +10 -1
- package/dist/contracts/console-api.js +10 -5
- package/dist/contracts/engine-api.js +271 -0
- package/dist/coordinator.js +2 -2
- package/dist/discord-api.js +4 -3
- package/dist/discord-chat.js +3 -1
- package/dist/easy-start-args.js +7 -3
- package/dist/easy-start.js +25 -0
- package/dist/egress.js +72 -10
- package/dist/engine-handoff.js +34 -0
- package/dist/engine-reads.js +261 -0
- package/dist/eval-world.js +3 -2
- package/dist/evidence.js +2 -0
- package/dist/fast-start.js +55 -14
- 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/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 +6 -0
- package/dist/model-choices.js +12 -6
- package/dist/notification-delivery.js +11 -0
- package/dist/operate.js +74 -30
- package/dist/outbound-privacy.js +204 -0
- package/dist/passwordless.js +2 -1
- package/dist/project-delete.js +14 -0
- package/dist/provider-connection.js +5 -3
- 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 +2 -2
- 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 +58 -11
- 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 +69 -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 +129 -138
- package/dist/server/route-table.js +30 -1
- package/dist/server/settings-section-table.js +3 -0
- package/dist/server/settings-sections.js +33 -0
- package/dist/server/settings.js +84 -10
- package/dist/server/task-views.js +8 -2
- package/dist/server/tasks.js +25 -8
- 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 +13 -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 +102 -5
- 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/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 +8 -4
- package/dist/welcome-facts.js +22 -15
- 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,889 @@
|
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { closeSync, constants as fsConstants, lstatSync, openSync, realpathSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join, relative, isAbsolute } from "node:path";
|
|
4
|
+
import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
|
|
5
|
+
import { flexibleDelegationAtUse, FLEXIBLE_LEVELS, FLEXIBLE_UNAVAILABLE, isFlexibleLevel } from "./flexible.js";
|
|
6
|
+
import { flexibleLaunch } from "./flexible-launch.js";
|
|
7
|
+
import { flexibleTurn } from "./flexible-turns.js";
|
|
8
|
+
import { sqliteRuntime } from "./sqlite-runtime.js";
|
|
9
|
+
import { platformAcl } from "./trusted-path.js";
|
|
10
|
+
export const FLEXIBLE_ANSWER_ACK_MS = 120_000;
|
|
11
|
+
export const FLEXIBLE_ANSWER_WRITE_MS = 10_000;
|
|
12
|
+
const MAX_ANSWER_BYTES = 1_048_576;
|
|
13
|
+
export const FLEXIBLE_ANSWER_RULES = Object.freeze({
|
|
14
|
+
"no-channel": "decline",
|
|
15
|
+
lowered: "cancel",
|
|
16
|
+
});
|
|
17
|
+
const WORDS = Object.freeze({
|
|
18
|
+
"not-available": FLEXIBLE_UNAVAILABLE,
|
|
19
|
+
"invalid-request": "That answer isn't one Toolroll can read. Nothing was sent.",
|
|
20
|
+
"request-unknown": "There's no such request.",
|
|
21
|
+
"not-a-person": "Only a person can answer an agent's request. Nothing was sent.",
|
|
22
|
+
"token-mismatch": "This card isn't the one Toolroll made for this request. Nothing was sent.",
|
|
23
|
+
"already-answered": "This request isn't waiting for an answer any more. Nothing was sent.",
|
|
24
|
+
"card-changed": "The request changed since you saw it. Look at it again before answering. Nothing was sent.",
|
|
25
|
+
"not-owner": "Only the person whose turn this is can answer it. Nothing was sent.",
|
|
26
|
+
"stale-generation": "Your account changed since this started. Sign in again. Nothing was sent.",
|
|
27
|
+
"authority-changed": "You can no longer answer for this thread (its Flexible terms or your access changed). Nothing was sent.",
|
|
28
|
+
"thread-changed": "This thread isn't running any more. Nothing was sent.",
|
|
29
|
+
"turn-changed": "The agent's turn ended or changed. Nothing was sent; if it asks again, you'll get a new card.",
|
|
30
|
+
"connection-changed": "The agent that asked has stopped or restarted. Nothing was sent; if it asks again, you'll get a new card.",
|
|
31
|
+
"stores-disagree": "Toolroll's records of this answer don't agree, so it wasn't sent.",
|
|
32
|
+
"too-late": "Your answer was already sent, so it can't be cancelled.",
|
|
33
|
+
"not-sent": "Your answer wasn't sent.",
|
|
34
|
+
"uncertain": "We couldn't confirm the agent got your answer. Check its activity. If it asks again, you'll get a new card.",
|
|
35
|
+
"catalog-unsafe": "Toolroll's record of agents' requests isn't where, or what, Toolroll made it, so it wasn't opened.",
|
|
36
|
+
"scope-unshown": "This request couldn't be shown in full, so it can't be allowed. You can deny it. Nothing was sent.",
|
|
37
|
+
});
|
|
38
|
+
const refuse = (reason, state, message = WORDS[reason]) => state === undefined ? { ok: false, reason, message } : { ok: false, reason, message, state };
|
|
39
|
+
export const FLEXIBLE_ANSWER_UNCERTAIN = WORDS["uncertain"];
|
|
40
|
+
export function streamAnswerSender(stream) {
|
|
41
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
42
|
+
return refuse("not-available");
|
|
43
|
+
return (bytes, { deadlineMs, signal }) => new Promise(resolve => {
|
|
44
|
+
if (stream.destroyed || !stream.writable || signal.aborted) {
|
|
45
|
+
resolve({ written: 0, complete: false });
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
let settled = false;
|
|
49
|
+
const finish = (result) => {
|
|
50
|
+
if (settled)
|
|
51
|
+
return;
|
|
52
|
+
settled = true;
|
|
53
|
+
clearTimeout(timer);
|
|
54
|
+
signal.removeEventListener("abort", onAbort);
|
|
55
|
+
resolve(result);
|
|
56
|
+
};
|
|
57
|
+
const onAbort = () => finish({ written: null, complete: false });
|
|
58
|
+
const timer = setTimeout(onAbort, deadlineMs);
|
|
59
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
60
|
+
try {
|
|
61
|
+
stream.write(bytes, error => finish(error == null ? { written: bytes.length, complete: true } : { written: null, complete: false }));
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
finish({ written: null, complete: false });
|
|
65
|
+
}
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
const CATALOG_SCHEMA = `
|
|
69
|
+
CREATE TABLE IF NOT EXISTS thread_request (
|
|
70
|
+
id TEXT PRIMARY KEY CHECK (length(id) = 32 AND id NOT GLOB '*[^0-9a-f]*'),
|
|
71
|
+
thread TEXT NOT NULL CHECK (length(thread) = 32 AND thread NOT GLOB '*[^0-9a-f]*'),
|
|
72
|
+
turn TEXT NOT NULL CHECK (length(turn) = 32 AND turn NOT GLOB '*[^0-9a-f]*'),
|
|
73
|
+
connection_id TEXT NOT NULL CHECK (length(connection_id) = 32 AND connection_id NOT GLOB '*[^0-9a-f]*'),
|
|
74
|
+
holder TEXT NOT NULL CHECK (length(holder) BETWEEN 1 AND 128),
|
|
75
|
+
owner TEXT NOT NULL CHECK (length(owner) BETWEEN 1 AND 200),
|
|
76
|
+
owner_generation INTEGER NOT NULL,
|
|
77
|
+
request_ref TEXT NOT NULL CHECK (length(request_ref) BETWEEN 1 AND 200),
|
|
78
|
+
kind TEXT NOT NULL CHECK (kind IN ('permission', 'question')),
|
|
79
|
+
card TEXT NOT NULL CHECK (json_valid(card) AND length(card) <= 65536),
|
|
80
|
+
request_digest TEXT NOT NULL CHECK (length(request_digest) = 64 AND request_digest NOT GLOB '*[^0-9a-f]*'),
|
|
81
|
+
correlation TEXT CHECK (correlation IS NULL OR length(correlation) BETWEEN 1 AND 200),
|
|
82
|
+
token_digest TEXT NOT NULL UNIQUE CHECK (length(token_digest) = 64 AND token_digest NOT GLOB '*[^0-9a-f]*'),
|
|
83
|
+
state TEXT NOT NULL CHECK (state IN ('pending', 'decided', 'sending', 'sent', 'delivered', 'not-sent', 'uncertain', 'withdrawn')),
|
|
84
|
+
decision_id TEXT CHECK (decision_id IS NULL OR (length(decision_id) = 32 AND decision_id NOT GLOB '*[^0-9a-f]*')),
|
|
85
|
+
source TEXT CHECK (source IS NULL OR source IN ('person', 'policy')),
|
|
86
|
+
decision TEXT CHECK (decision IS NULL OR decision IN ('accept', 'decline', 'cancel', 'answer')),
|
|
87
|
+
answer TEXT CHECK (answer IS NULL OR (json_valid(answer) AND length(answer) <= 200000)),
|
|
88
|
+
payload_digest TEXT CHECK (payload_digest IS NULL OR (length(payload_digest) = 64 AND payload_digest NOT GLOB '*[^0-9a-f]*')),
|
|
89
|
+
decided_by TEXT,
|
|
90
|
+
decided_at TEXT,
|
|
91
|
+
created_at TEXT NOT NULL,
|
|
92
|
+
attempt_id TEXT CHECK (attempt_id IS NULL OR (length(attempt_id) = 32 AND attempt_id NOT GLOB '*[^0-9a-f]*')),
|
|
93
|
+
write_started_at TEXT,
|
|
94
|
+
sent_at TEXT,
|
|
95
|
+
ended_at TEXT,
|
|
96
|
+
detail TEXT CHECK (detail IS NULL OR length(detail) <= 500),
|
|
97
|
+
CHECK ((attempt_id IS NULL) = (write_started_at IS NULL)),
|
|
98
|
+
CHECK (attempt_id IS NULL OR state IN ('sending', 'sent', 'delivered', 'uncertain')),
|
|
99
|
+
CHECK ((decision_id IS NULL) = (source IS NULL) AND (decision_id IS NULL) = (decision IS NULL) AND (decision_id IS NULL) = (answer IS NULL)
|
|
100
|
+
AND (decision_id IS NULL) = (payload_digest IS NULL) AND (decision_id IS NULL) = (decided_by IS NULL) AND (decision_id IS NULL) = (decided_at IS NULL)),
|
|
101
|
+
CHECK (state <> 'pending' OR decision_id IS NULL),
|
|
102
|
+
CHECK (state IN ('pending', 'withdrawn') OR decision_id IS NOT NULL),
|
|
103
|
+
CHECK ((ended_at IS NULL) = (state IN ('pending', 'decided', 'sending', 'sent'))),
|
|
104
|
+
CHECK (sent_at IS NULL OR state IN ('sent', 'delivered', 'uncertain')),
|
|
105
|
+
CHECK (state NOT IN ('sent', 'delivered') OR sent_at IS NOT NULL),
|
|
106
|
+
CHECK (state NOT IN ('sent', 'delivered') OR attempt_id IS NOT NULL)
|
|
107
|
+
);
|
|
108
|
+
CREATE UNIQUE INDEX IF NOT EXISTS thread_request_ref ON thread_request (connection_id, request_ref);
|
|
109
|
+
CREATE INDEX IF NOT EXISTS thread_request_open ON thread_request (thread, state);
|
|
110
|
+
CREATE TRIGGER IF NOT EXISTS thread_request_moves BEFORE UPDATE ON thread_request
|
|
111
|
+
WHEN NEW.id IS NOT OLD.id OR NEW.thread IS NOT OLD.thread OR NEW.turn IS NOT OLD.turn OR NEW.connection_id IS NOT OLD.connection_id OR NEW.holder IS NOT OLD.holder
|
|
112
|
+
OR NEW.owner IS NOT OLD.owner OR NEW.owner_generation IS NOT OLD.owner_generation OR NEW.request_ref IS NOT OLD.request_ref OR NEW.kind IS NOT OLD.kind
|
|
113
|
+
OR NEW.card IS NOT OLD.card OR NEW.request_digest IS NOT OLD.request_digest OR NEW.correlation IS NOT OLD.correlation OR NEW.token_digest IS NOT OLD.token_digest
|
|
114
|
+
OR NEW.created_at IS NOT OLD.created_at
|
|
115
|
+
OR (OLD.decision_id IS NOT NULL AND (NEW.decision_id IS NOT OLD.decision_id OR NEW.source IS NOT OLD.source OR NEW.decision IS NOT OLD.decision
|
|
116
|
+
OR NEW.answer IS NOT OLD.answer OR NEW.payload_digest IS NOT OLD.payload_digest OR NEW.decided_by IS NOT OLD.decided_by OR NEW.decided_at IS NOT OLD.decided_at))
|
|
117
|
+
OR (OLD.sent_at IS NOT NULL AND NEW.sent_at IS NOT OLD.sent_at)
|
|
118
|
+
OR (OLD.attempt_id IS NOT NULL AND (NEW.attempt_id IS NOT OLD.attempt_id OR NEW.write_started_at IS NOT OLD.write_started_at))
|
|
119
|
+
OR (OLD.attempt_id IS NULL AND NEW.attempt_id IS NOT NULL AND (OLD.state <> 'sending' OR NEW.state <> 'sending'))
|
|
120
|
+
OR OLD.state IN ('delivered', 'not-sent', 'uncertain', 'withdrawn')
|
|
121
|
+
OR (OLD.state = 'pending' AND NEW.state NOT IN ('pending', 'decided', 'withdrawn'))
|
|
122
|
+
OR (OLD.state = 'decided' AND NEW.state NOT IN ('decided', 'sending', 'not-sent', 'uncertain'))
|
|
123
|
+
OR (OLD.state = 'sending' AND NEW.state NOT IN ('sending', 'sent', 'not-sent', 'uncertain'))
|
|
124
|
+
OR (OLD.state = 'sent' AND NEW.state NOT IN ('sent', 'delivered', 'uncertain'))
|
|
125
|
+
BEGIN
|
|
126
|
+
SELECT RAISE(ABORT, 'a thread request is written once and its answer only moves forward');
|
|
127
|
+
END
|
|
128
|
+
`;
|
|
129
|
+
const CATALOG_OBJECTS = Object.freeze([["table", "thread_request"], ["index", "thread_request_ref"], ["index", "thread_request_open"], ["trigger", "thread_request_moves"]]);
|
|
130
|
+
const squash = (sql) => sql.replace(/\bIF NOT EXISTS\b/i, "").replace(/\s+/g, " ").replace(/;$/, "").trim();
|
|
131
|
+
const handles = new WeakMap();
|
|
132
|
+
const dbOf = (catalog) => {
|
|
133
|
+
const db = handles.get(catalog);
|
|
134
|
+
if (db === undefined)
|
|
135
|
+
throw new Error("not a Flexible answer catalog");
|
|
136
|
+
return db;
|
|
137
|
+
};
|
|
138
|
+
function folderBoundaryProblem(folder, acl = platformAcl()) {
|
|
139
|
+
const uid = process.getuid?.();
|
|
140
|
+
if (uid === undefined)
|
|
141
|
+
return "who owns its folder can't be checked on this system";
|
|
142
|
+
try {
|
|
143
|
+
const held = lstatSync(folder);
|
|
144
|
+
if (!held.isDirectory() || held.isSymbolicLink())
|
|
145
|
+
return "its folder isn't a folder";
|
|
146
|
+
if (held.uid !== uid)
|
|
147
|
+
return "its folder is owned by another user";
|
|
148
|
+
if ((held.mode & 0o022) !== 0)
|
|
149
|
+
return "others can change its folder (group- or world-writable)";
|
|
150
|
+
const verdict = acl?.(folder);
|
|
151
|
+
if (verdict !== undefined && !verdict.ok)
|
|
152
|
+
return `its folder's ACL ${verdict.why}`;
|
|
153
|
+
for (let last = folder, up = dirname(folder); up !== last; last = up, up = dirname(up)) {
|
|
154
|
+
const dir = lstatSync(up);
|
|
155
|
+
if (!dir.isDirectory())
|
|
156
|
+
return `${up} isn't a folder`;
|
|
157
|
+
if (dir.uid !== uid && dir.uid !== 0)
|
|
158
|
+
return `${up} is owned by another user`;
|
|
159
|
+
if ((dir.mode & 0o022) !== 0 && (dir.mode & 0o1000) === 0)
|
|
160
|
+
return `others can change ${up} (group- or world-writable)`;
|
|
161
|
+
const above = acl?.(up);
|
|
162
|
+
if (above !== undefined && !above.ok)
|
|
163
|
+
return `the ACL of ${up} ${above.why}`;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
catch {
|
|
167
|
+
return "its folder can't be checked";
|
|
168
|
+
}
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
function fileProblem(path) {
|
|
172
|
+
let held;
|
|
173
|
+
try {
|
|
174
|
+
held = lstatSync(path);
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
return error.code === "ENOENT" ? null : "it can't be read";
|
|
178
|
+
}
|
|
179
|
+
if (held.isSymbolicLink())
|
|
180
|
+
return "it is a link";
|
|
181
|
+
if (!held.isFile())
|
|
182
|
+
return "it isn't a file";
|
|
183
|
+
if (process.getuid !== undefined && held.uid !== process.getuid())
|
|
184
|
+
return "it isn't this user's";
|
|
185
|
+
if (held.nlink !== 1)
|
|
186
|
+
return "it has another name";
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
export function openFlexibleAnswerCatalog(store) {
|
|
190
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
191
|
+
return refuse("not-available");
|
|
192
|
+
const database = store.databaseFile();
|
|
193
|
+
if (database === null || !isAbsolute(database))
|
|
194
|
+
return refuse("catalog-unsafe");
|
|
195
|
+
const folder = dirname(database), file = join(folder, `${basename(database)}.coding.sqlite`);
|
|
196
|
+
const unsafe = (why) => refuse("catalog-unsafe", undefined, `${WORDS["catalog-unsafe"]} (${why})`);
|
|
197
|
+
let real;
|
|
198
|
+
try {
|
|
199
|
+
real = realpathSync(folder);
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return unsafe("its folder can't be read");
|
|
203
|
+
}
|
|
204
|
+
if (real !== folder)
|
|
205
|
+
return unsafe("its folder is reached through a link");
|
|
206
|
+
try {
|
|
207
|
+
if (dirname(realpathSync(database)) !== folder)
|
|
208
|
+
return unsafe("it isn't in the store's own state folder");
|
|
209
|
+
}
|
|
210
|
+
catch {
|
|
211
|
+
return unsafe("the store's file can't be read");
|
|
212
|
+
}
|
|
213
|
+
if (/(^|\/)threads\/[0-9a-f]{32}(\/|$)/.test(folder))
|
|
214
|
+
return unsafe("it is inside a thread's folder");
|
|
215
|
+
const boundary = folderBoundaryProblem(folder);
|
|
216
|
+
if (boundary !== null)
|
|
217
|
+
return unsafe(boundary);
|
|
218
|
+
const threads = join(folder, "threads");
|
|
219
|
+
const fromThreads = relative(threads, file);
|
|
220
|
+
if (fromThreads === "" || (!fromThreads.startsWith("..") && !isAbsolute(fromThreads)))
|
|
221
|
+
return unsafe("it is inside the threads' folder");
|
|
222
|
+
for (const one of [file, `${file}-wal`, `${file}-shm`, `${file}-journal`]) {
|
|
223
|
+
const problem = fileProblem(one);
|
|
224
|
+
if (problem !== null)
|
|
225
|
+
return unsafe(`${basename(one)}: ${problem}`);
|
|
226
|
+
}
|
|
227
|
+
try {
|
|
228
|
+
closeSync(openSync(file, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY | fsConstants.O_NOFOLLOW, 0o600));
|
|
229
|
+
}
|
|
230
|
+
catch (error) {
|
|
231
|
+
if (error.code !== "EEXIST")
|
|
232
|
+
return unsafe("it couldn't be made");
|
|
233
|
+
}
|
|
234
|
+
const before = lstatSync(file);
|
|
235
|
+
if (fileProblem(file) !== null || (before.mode & 0o077) !== 0)
|
|
236
|
+
return unsafe("it isn't a private file of this user's");
|
|
237
|
+
const db = new (sqliteRuntime().DatabaseSync)(file);
|
|
238
|
+
try {
|
|
239
|
+
const after = lstatSync(file);
|
|
240
|
+
if (after.ino !== before.ino || after.dev !== before.dev || fileProblem(file) !== null) {
|
|
241
|
+
db.close();
|
|
242
|
+
return unsafe("it changed while it was opened");
|
|
243
|
+
}
|
|
244
|
+
db.exec("PRAGMA journal_mode=WAL; PRAGMA busy_timeout=3000;");
|
|
245
|
+
for (const one of [`${file}-wal`, `${file}-shm`, `${file}-journal`]) {
|
|
246
|
+
const problem = fileProblem(one);
|
|
247
|
+
if (problem !== null) {
|
|
248
|
+
db.close();
|
|
249
|
+
return unsafe(`${basename(one)}: ${problem}`);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
db.exec(CATALOG_SCHEMA);
|
|
253
|
+
const statements = CATALOG_SCHEMA.split(/;\s*\n(?=CREATE )/).map(squash).filter(one => one !== "");
|
|
254
|
+
for (const [type, name] of CATALOG_OBJECTS) {
|
|
255
|
+
const row = db.prepare("SELECT sql FROM sqlite_master WHERE type = ? AND name = ?").get(type, name);
|
|
256
|
+
const want = statements.find(one => new RegExp(`^CREATE (?:UNIQUE )?${type.toUpperCase()} ${name}\\b`).test(one));
|
|
257
|
+
if (row === undefined || want === undefined || squash(String(row["sql"])) !== want)
|
|
258
|
+
throw new Error(`${file}: the Flexible answers ${type} ${name} has an unknown shape`);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
db.close();
|
|
263
|
+
throw error;
|
|
264
|
+
}
|
|
265
|
+
const catalog = { file, close: () => { handles.delete(catalog); db.close(); } };
|
|
266
|
+
handles.set(catalog, db);
|
|
267
|
+
return { ok: true, catalog };
|
|
268
|
+
}
|
|
269
|
+
function readRequest(row) {
|
|
270
|
+
if (row === undefined)
|
|
271
|
+
return null;
|
|
272
|
+
const text = (value) => value === null || value === undefined ? null : String(value);
|
|
273
|
+
return { id: String(row["id"]), thread: String(row["thread"]), turn: String(row["turn"]), connection: String(row["connection_id"]), holder: String(row["holder"]),
|
|
274
|
+
owner: String(row["owner"]), ownerGeneration: Number(row["owner_generation"]), requestRef: String(row["request_ref"]), kind: String(row["kind"]),
|
|
275
|
+
card: String(row["card"]), requestDigest: String(row["request_digest"]), correlation: text(row["correlation"]), tokenDigest: String(row["token_digest"]),
|
|
276
|
+
state: String(row["state"]), decisionId: text(row["decision_id"]), answer: text(row["answer"]), payloadDigest: text(row["payload_digest"]),
|
|
277
|
+
attemptId: text(row["attempt_id"]), writeStartedAt: text(row["write_started_at"]), sentAt: text(row["sent_at"]) };
|
|
278
|
+
}
|
|
279
|
+
const requestOf = (catalog, id) => readRequest(dbOf(catalog).prepare("SELECT * FROM thread_request WHERE id = ?").get(id));
|
|
280
|
+
function decisionOf(store, request) {
|
|
281
|
+
const row = store.handle.prepare("SELECT * FROM thread_decision WHERE request = ?").get(request);
|
|
282
|
+
if (row === undefined)
|
|
283
|
+
return null;
|
|
284
|
+
return { id: Number(row["id"]), decisionId: String(row["decision_id"]), thread: String(row["thread"]), turn: String(row["turn"]), request: row["request"] === null ? null : String(row["request"]),
|
|
285
|
+
source: String(row["source"]), by: String(row["by"]), byGeneration: row["by_generation"] === null ? null : Number(row["by_generation"]),
|
|
286
|
+
payloadDigest: row["payload_digest"] === null ? null : String(row["payload_digest"]), connection: String(row["connection_id"]), state: String(row["state"]),
|
|
287
|
+
writeStartedAt: row["write_started_at"] === null ? null : String(row["write_started_at"]), attemptId: row["attempt_id"] === null ? null : String(row["attempt_id"]), stateAt: String(row["state_at"]) };
|
|
288
|
+
}
|
|
289
|
+
const ID = /^[0-9a-f]{32}$/;
|
|
290
|
+
const HOLDER = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
291
|
+
const REF = /^[\x21-\x7e]{1,200}$/;
|
|
292
|
+
const sha256 = (text) => createHash("sha256").update(text, "utf8").digest("hex");
|
|
293
|
+
const sameDigest = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
|
294
|
+
const systemClock = () => new Date();
|
|
295
|
+
const OPEN = new Set(["pending", "decided", "sending", "sent"]);
|
|
296
|
+
const attempted = new Set();
|
|
297
|
+
function ledger(store, at, actor, source, outcome, row, detail) {
|
|
298
|
+
store.recordAction({ at, actor, repo: null, taskId: null, runId: null, source, action: "flexible answer", outcome,
|
|
299
|
+
detail: `thread ${row.thread} · turn ${row.turn} · decision ${row.decisionId}${detail === undefined ? "" : ` · ${detail}`}` });
|
|
300
|
+
}
|
|
301
|
+
function settle(store, catalog, request, decision, to, at, detail, actor = "toolroll") {
|
|
302
|
+
const from = to === "delivered" ? ["sent"] : to === "not-sent" ? ["decided", "sending"] : ["decided", "sending", "sent"];
|
|
303
|
+
const unattempted = to === "not-sent" ? " AND attempt_id IS NULL" : "";
|
|
304
|
+
dbOf(catalog).prepare(`UPDATE thread_request SET state = ?, ended_at = ?, detail = ? WHERE id = ? AND state IN (${from.map(() => "?").join(", ")})${unattempted}`)
|
|
305
|
+
.run(to, at, detail.slice(0, 500), request.id, ...from);
|
|
306
|
+
if (decision === null || !["decided", "sending", "sent"].includes(decision.state) || (to === "not-sent" && decision.attemptId !== null))
|
|
307
|
+
return;
|
|
308
|
+
store.handle.prepare("UPDATE thread_decision SET state = ?, state_at = ?, detail = ? WHERE id = ?").run(to, at, detail.slice(0, 500), decision.id);
|
|
309
|
+
ledger(store, at, actor, decision.source === "person" ? "work" : "policy", to, { thread: decision.thread, turn: decision.turn, decisionId: decision.decisionId }, detail);
|
|
310
|
+
}
|
|
311
|
+
function standing(store, bound, person) {
|
|
312
|
+
const thread = store.handle.prepare("SELECT state FROM flexible_thread WHERE id = ?").get(bound.thread);
|
|
313
|
+
if (thread === undefined || thread["state"] !== "ready")
|
|
314
|
+
return refuse("thread-changed");
|
|
315
|
+
const turn = flexibleTurn(store, bound.turn);
|
|
316
|
+
if (turn === null || turn.thread !== bound.thread || turn.status !== "running" || turn.holder !== bound.holder || turn.owner !== bound.owner || turn.ownerGeneration !== bound.ownerGeneration) {
|
|
317
|
+
return refuse("turn-changed");
|
|
318
|
+
}
|
|
319
|
+
const launch = flexibleLaunch(store, bound.connection);
|
|
320
|
+
if (launch === null || launch.thread !== bound.thread || launch.state !== "live" || launch.holder !== bound.holder)
|
|
321
|
+
return refuse("connection-changed");
|
|
322
|
+
if (person === null)
|
|
323
|
+
return null;
|
|
324
|
+
if (person.name !== bound.owner)
|
|
325
|
+
return refuse("not-owner");
|
|
326
|
+
const account = store.accountOf(bound.owner);
|
|
327
|
+
if (account === null || account.revokedAt !== null)
|
|
328
|
+
return refuse("authority-changed");
|
|
329
|
+
if (account.generation !== bound.ownerGeneration || person.generation !== bound.ownerGeneration)
|
|
330
|
+
return refuse("stale-generation");
|
|
331
|
+
const delegation = flexibleDelegationAtUse(store, { repo: turn.repo, starter: { name: turn.owner, generation: turn.ownerGeneration }, digest: turn.termsDigest, level: turn.level, freshProof: true });
|
|
332
|
+
if (!delegation.ok || delegation.termsId !== turn.termsId)
|
|
333
|
+
return refuse("authority-changed");
|
|
334
|
+
const chosen = store.handle.prepare("SELECT level FROM flexible_thread_level WHERE thread = ?").get(bound.thread);
|
|
335
|
+
if (chosen !== undefined && isFlexibleLevel(chosen["level"]) && FLEXIBLE_LEVELS.indexOf(turn.level) > FLEXIBLE_LEVELS.indexOf(chosen["level"]))
|
|
336
|
+
return refuse("authority-changed");
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
const boundOf = (row) => ({ thread: row.thread, turn: row.turn, connection: row.connection, holder: row.holder, owner: row.owner, ownerGeneration: row.ownerGeneration });
|
|
340
|
+
const RESERVED_IDS = new Set(["__proto__", "constructor", "prototype"]);
|
|
341
|
+
function cardProblem(kind, card) {
|
|
342
|
+
if (kind !== "permission" && kind !== "question")
|
|
343
|
+
return "kind";
|
|
344
|
+
if (typeof card !== "object" || card === null || Array.isArray(card))
|
|
345
|
+
return "card";
|
|
346
|
+
const c = card;
|
|
347
|
+
if (typeof c["title"] !== "string" || c["title"].length < 1 || c["title"].length > 200)
|
|
348
|
+
return "title";
|
|
349
|
+
if (c["detail"] !== undefined && (typeof c["detail"] !== "string" || c["detail"].length > 32_000))
|
|
350
|
+
return "detail";
|
|
351
|
+
if (c["tool"] !== undefined && (typeof c["tool"] !== "string" || !/^[\x21-\x7e]{1,100}$/.test(c["tool"])))
|
|
352
|
+
return "tool";
|
|
353
|
+
if (c["input"] !== undefined && (typeof c["input"] !== "string" || !/^[0-9a-f]{64}$/.test(c["input"])))
|
|
354
|
+
return "input";
|
|
355
|
+
if (c["complete"] !== undefined && typeof c["complete"] !== "boolean")
|
|
356
|
+
return "complete";
|
|
357
|
+
if (kind === "permission" && (c["tool"] === undefined || c["input"] === undefined))
|
|
358
|
+
return "scope";
|
|
359
|
+
const questions = c["questions"];
|
|
360
|
+
if (kind === "question" && (!Array.isArray(questions) || questions.length < 1))
|
|
361
|
+
return "questions";
|
|
362
|
+
if (questions !== undefined) {
|
|
363
|
+
if (!Array.isArray(questions) || questions.length > 20)
|
|
364
|
+
return "questions";
|
|
365
|
+
const ids = new Set();
|
|
366
|
+
for (const one of questions) {
|
|
367
|
+
const q = one;
|
|
368
|
+
if (typeof one !== "object" || one === null || typeof q["id"] !== "string" || !/^[\x21-\x7e]{1,100}$/.test(q["id"]) || RESERVED_IDS.has(q["id"]) || ids.has(q["id"]) || typeof q["question"] !== "string" || q["question"].length > 4000)
|
|
369
|
+
return "questions";
|
|
370
|
+
ids.add(q["id"]);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return null;
|
|
374
|
+
}
|
|
375
|
+
function answerFor(kind, card, decision, answers) {
|
|
376
|
+
if (kind === "permission")
|
|
377
|
+
return decision === "accept" || decision === "decline" || decision === "cancel" ? { decision } : null;
|
|
378
|
+
if (decision === "cancel" || decision === "decline")
|
|
379
|
+
return { answers: {} };
|
|
380
|
+
if (decision !== "answer" || typeof answers !== "object" || answers === null || Array.isArray(answers))
|
|
381
|
+
return null;
|
|
382
|
+
const prototype = Object.getPrototypeOf(answers);
|
|
383
|
+
if (prototype !== Object.prototype && prototype !== null)
|
|
384
|
+
return null;
|
|
385
|
+
const questions = JSON.parse(card).questions ?? [];
|
|
386
|
+
const given = answers;
|
|
387
|
+
if (Object.keys(given).some(key => RESERVED_IDS.has(key) || !questions.some(q => q.id === key)))
|
|
388
|
+
return null;
|
|
389
|
+
const entries = [];
|
|
390
|
+
for (const q of questions) {
|
|
391
|
+
if (RESERVED_IDS.has(q.id) || !Object.hasOwn(given, q.id))
|
|
392
|
+
return null;
|
|
393
|
+
const entry = given[q.id];
|
|
394
|
+
if (typeof entry !== "object" || entry === null || !Object.hasOwn(entry, "answers"))
|
|
395
|
+
return null;
|
|
396
|
+
const values = entry.answers;
|
|
397
|
+
if (!Array.isArray(values) || values.length < 1 || values.length > 10 || values.some(v => typeof v !== "string" || v.length > 16_000))
|
|
398
|
+
return null;
|
|
399
|
+
entries.push([q.id, { answers: [...values] }]);
|
|
400
|
+
}
|
|
401
|
+
return { answers: Object.fromEntries(entries) };
|
|
402
|
+
}
|
|
403
|
+
export function recordFlexibleRequest(store, catalog, input) {
|
|
404
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
405
|
+
return refuse("not-available");
|
|
406
|
+
if (![input.thread, input.turn, input.connection].every(id => typeof id === "string" && ID.test(id)) || typeof input.holder !== "string" || !HOLDER.test(input.holder)
|
|
407
|
+
|| typeof input.requestRef !== "string" || !REF.test(input.requestRef) || cardProblem(input.kind, input.card) !== null
|
|
408
|
+
|| (input.correlation != null && (typeof input.correlation !== "string" || !REF.test(input.correlation))))
|
|
409
|
+
return refuse("invalid-request");
|
|
410
|
+
const card = JSON.stringify(input.card);
|
|
411
|
+
if (card.length > 65_536)
|
|
412
|
+
return refuse("invalid-request");
|
|
413
|
+
return store.transact(() => {
|
|
414
|
+
const at = (input.clock ?? systemClock)().toISOString();
|
|
415
|
+
const turn = flexibleTurn(store, input.turn);
|
|
416
|
+
if (turn === null)
|
|
417
|
+
return refuse("turn-changed");
|
|
418
|
+
const problem = standing(store, { thread: input.thread, turn: input.turn, connection: input.connection, holder: input.holder, owner: turn.owner, ownerGeneration: turn.ownerGeneration }, null);
|
|
419
|
+
if (problem !== null)
|
|
420
|
+
return problem;
|
|
421
|
+
const id = randomBytes(16).toString("hex"), token = randomBytes(32).toString("hex"), requestDigest = sha256(card);
|
|
422
|
+
dbOf(catalog).prepare(`INSERT INTO thread_request (id, thread, turn, connection_id, holder, owner, owner_generation, request_ref, kind, card, request_digest, correlation, token_digest, state, created_at)
|
|
423
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?)`).run(id, input.thread, input.turn, input.connection, input.holder, turn.owner, turn.ownerGeneration, input.requestRef, input.kind, card, requestDigest, input.correlation ?? null, sha256(token), at);
|
|
424
|
+
return { ok: true, request: id, token, requestDigest };
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
function decide(store, catalog, input, who, decision, answers) {
|
|
428
|
+
const clock = input.clock ?? systemClock;
|
|
429
|
+
const made = store.transact(() => {
|
|
430
|
+
const at = clock().toISOString();
|
|
431
|
+
const row = requestOf(catalog, input.request);
|
|
432
|
+
if (row === null)
|
|
433
|
+
return refuse("request-unknown");
|
|
434
|
+
if (who.source === "person" && !sameDigest(sha256(who.token), row.tokenDigest))
|
|
435
|
+
return refuse("token-mismatch");
|
|
436
|
+
if (row.state !== "pending" || decisionOf(store, row.id) !== null)
|
|
437
|
+
return refuse("already-answered", row.state);
|
|
438
|
+
if (who.source === "person" && who.shownDigest !== row.requestDigest)
|
|
439
|
+
return refuse("card-changed");
|
|
440
|
+
const problem = standing(store, boundOf(row), who.source === "person" ? { name: who.name, generation: who.generation } : null);
|
|
441
|
+
if (problem !== null)
|
|
442
|
+
return problem;
|
|
443
|
+
if (who.source === "person" && who.held !== undefined) {
|
|
444
|
+
let held = false;
|
|
445
|
+
try {
|
|
446
|
+
held = who.held() === true;
|
|
447
|
+
}
|
|
448
|
+
catch {
|
|
449
|
+
held = false;
|
|
450
|
+
}
|
|
451
|
+
if (!held)
|
|
452
|
+
return refuse("authority-changed");
|
|
453
|
+
}
|
|
454
|
+
if (decision === "accept" && row.kind === "permission" && JSON.parse(row.card).complete !== true)
|
|
455
|
+
return refuse("scope-unshown");
|
|
456
|
+
const payload = answerFor(row.kind, row.card, decision, answers);
|
|
457
|
+
if (payload === null)
|
|
458
|
+
return refuse("invalid-request");
|
|
459
|
+
const answer = JSON.stringify(payload), payloadDigest = sha256(answer), decisionId = randomBytes(16).toString("hex");
|
|
460
|
+
const by = who.source === "person" ? who.name : "toolroll";
|
|
461
|
+
store.handle.prepare(`INSERT INTO thread_decision (decision_id, thread, turn, request, request_ref, source, rule, decision, request_digest, payload_digest, connection_id, state, at, by, by_generation, state_at)
|
|
462
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'decided', ?, ?, ?, ?)`).run(decisionId, row.thread, row.turn, row.id, row.requestRef, who.source, who.source === "policy" ? who.rule : null, decision, row.requestDigest, payloadDigest, row.connection, at, by, who.source === "person" ? who.generation : null, at);
|
|
463
|
+
ledger(store, at, by, who.source === "person" ? "work" : "policy", "intended", { thread: row.thread, turn: row.turn, decisionId }, `${decision} · request ${row.id}${who.source === "policy" ? ` · rule ${who.rule}` : ""}`);
|
|
464
|
+
return { decisionId, answer, payloadDigest, tokenDigest: row.tokenDigest, at, row };
|
|
465
|
+
});
|
|
466
|
+
if ("ok" in made)
|
|
467
|
+
return made;
|
|
468
|
+
const swapped = dbOf(catalog).prepare(`UPDATE thread_request SET state = 'decided', decision_id = ?, source = ?, decision = ?, answer = ?, payload_digest = ?, decided_by = ?, decided_at = ?
|
|
469
|
+
WHERE id = ? AND state = 'pending' AND token_digest = ?`).run(made.decisionId, who.source, decision, made.answer, made.payloadDigest, who.source === "person" ? who.name : "toolroll", made.at, made.row.id, made.tokenDigest);
|
|
470
|
+
if (Number(swapped.changes) !== 1) {
|
|
471
|
+
store.transact(() => settle(store, catalog, made.row, decisionOf(store, made.row.id), "not-sent", clock().toISOString(), "the request moved before the answer was recorded"));
|
|
472
|
+
return refuse("already-answered", "not-sent");
|
|
473
|
+
}
|
|
474
|
+
return { ok: true, decisionId: made.decisionId, state: "decided" };
|
|
475
|
+
}
|
|
476
|
+
export function decideFlexibleAnswer(store, catalog, input) {
|
|
477
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
478
|
+
return refuse("not-available");
|
|
479
|
+
if (input.by?.kind !== "person")
|
|
480
|
+
return refuse("not-a-person");
|
|
481
|
+
if (typeof input.request !== "string" || !ID.test(input.request) || typeof input.token !== "string" || !/^[0-9a-f]{64}$/.test(input.token)
|
|
482
|
+
|| typeof input.shownDigest !== "string" || typeof input.by.name !== "string" || !Number.isSafeInteger(input.by.generation)
|
|
483
|
+
|| !["accept", "decline", "cancel", "answer"].includes(input.decision) || (input.held !== undefined && typeof input.held !== "function"))
|
|
484
|
+
return refuse("invalid-request");
|
|
485
|
+
return decide(store, catalog, input, { source: "person", name: input.by.name, generation: input.by.generation, token: input.token, shownDigest: input.shownDigest,
|
|
486
|
+
...(input.held === undefined ? {} : { held: input.held }) }, input.decision, input.answers);
|
|
487
|
+
}
|
|
488
|
+
export function decideFlexibleAnswerByPolicy(store, catalog, input) {
|
|
489
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
490
|
+
return refuse("not-available");
|
|
491
|
+
if (typeof input.request !== "string" || !ID.test(input.request) || !Object.hasOwn(FLEXIBLE_ANSWER_RULES, input.rule))
|
|
492
|
+
return refuse("invalid-request");
|
|
493
|
+
return decide(store, catalog, input, { source: "policy", rule: input.rule }, FLEXIBLE_ANSWER_RULES[input.rule], undefined);
|
|
494
|
+
}
|
|
495
|
+
function agreeing(store, catalog, request) {
|
|
496
|
+
const row = requestOf(catalog, request), decision = row === null ? null : decisionOf(store, row.id);
|
|
497
|
+
if (row === null || decision === null || row.decisionId === null || row.answer === null || row.payloadDigest === null || decision.payloadDigest === null)
|
|
498
|
+
return { row, decision, problem: true };
|
|
499
|
+
const agree = row.decisionId === decision.decisionId && sameDigest(sha256(row.answer), decision.payloadDigest) && sameDigest(row.payloadDigest, decision.payloadDigest)
|
|
500
|
+
&& row.connection === decision.connection && row.turn === decision.turn && row.thread === decision.thread;
|
|
501
|
+
return agree ? { row, decision } : { row, decision, problem: true };
|
|
502
|
+
}
|
|
503
|
+
export async function sendFlexibleAnswer(store, catalog, input) {
|
|
504
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
505
|
+
return refuse("not-available");
|
|
506
|
+
if (typeof input.request !== "string" || !ID.test(input.request) || typeof input.holder !== "string" || !HOLDER.test(input.holder)
|
|
507
|
+
|| typeof input.connection?.id !== "string" || typeof input.connection.frame !== "function" || typeof input.connection.send !== "function"
|
|
508
|
+
|| (input.writeMs !== undefined && (!Number.isSafeInteger(input.writeMs) || input.writeMs < 1 || input.writeMs > 60_000))
|
|
509
|
+
|| (input.held !== undefined && typeof input.held !== "function"))
|
|
510
|
+
return refuse("invalid-request");
|
|
511
|
+
const clock = input.clock ?? systemClock;
|
|
512
|
+
const connection = input.connection;
|
|
513
|
+
const writeMs = input.writeMs ?? FLEXIBLE_ANSWER_WRITE_MS;
|
|
514
|
+
const blocked = (row, decision) => {
|
|
515
|
+
if (connection.id !== row.connection || input.holder !== row.holder)
|
|
516
|
+
return refuse("connection-changed");
|
|
517
|
+
const problem = standing(store, boundOf(row), decision.source === "person" ? { name: decision.by, generation: decision.byGeneration ?? -1 } : null);
|
|
518
|
+
if (problem !== null)
|
|
519
|
+
return problem;
|
|
520
|
+
let held = true;
|
|
521
|
+
try {
|
|
522
|
+
held = input.held === undefined || input.held() === true;
|
|
523
|
+
}
|
|
524
|
+
catch {
|
|
525
|
+
held = false;
|
|
526
|
+
}
|
|
527
|
+
return held ? null : refuse("authority-changed");
|
|
528
|
+
};
|
|
529
|
+
const queued = store.transact(() => {
|
|
530
|
+
const at = clock().toISOString();
|
|
531
|
+
const both = agreeing(store, catalog, input.request);
|
|
532
|
+
if (both.row === null)
|
|
533
|
+
return refuse("request-unknown");
|
|
534
|
+
if (both.decision === null || both.row.state !== "decided" || both.decision.state !== "decided")
|
|
535
|
+
return refuse("already-answered", both.decision?.state ?? both.row.state);
|
|
536
|
+
if ("problem" in both) {
|
|
537
|
+
settle(store, catalog, both.row, both.decision, "not-sent", at, "the two records of this answer disagree");
|
|
538
|
+
return refuse("stores-disagree", "not-sent");
|
|
539
|
+
}
|
|
540
|
+
const problem = blocked(both.row, both.decision);
|
|
541
|
+
if (problem !== null) {
|
|
542
|
+
settle(store, catalog, both.row, both.decision, "not-sent", at, problem.message);
|
|
543
|
+
return { ...problem, state: "not-sent" };
|
|
544
|
+
}
|
|
545
|
+
const moved = dbOf(catalog).prepare("UPDATE thread_request SET state = 'sending' WHERE id = ? AND state = 'decided' AND decision_id = ?").run(both.row.id, both.decision.decisionId);
|
|
546
|
+
if (Number(moved.changes) !== 1)
|
|
547
|
+
return refuse("stores-disagree");
|
|
548
|
+
store.handle.prepare("UPDATE thread_decision SET state = 'sending', state_at = ? WHERE id = ? AND state = 'decided'").run(at, both.decision.id);
|
|
549
|
+
return { decisionId: both.decision.decisionId };
|
|
550
|
+
});
|
|
551
|
+
if ("ok" in queued)
|
|
552
|
+
return queued;
|
|
553
|
+
let readyFailed = false;
|
|
554
|
+
try {
|
|
555
|
+
await connection.ready?.();
|
|
556
|
+
}
|
|
557
|
+
catch {
|
|
558
|
+
readyFailed = true;
|
|
559
|
+
}
|
|
560
|
+
let attempt;
|
|
561
|
+
try {
|
|
562
|
+
attempt = store.transact(() => {
|
|
563
|
+
const at = clock().toISOString();
|
|
564
|
+
const both = agreeing(store, catalog, input.request);
|
|
565
|
+
if (both.row === null || both.decision === null)
|
|
566
|
+
return refuse("stores-disagree");
|
|
567
|
+
if (both.decision.state !== "sending" || both.decision.attemptId !== null || both.row.attemptId !== null || attempted.has(both.decision.decisionId)) {
|
|
568
|
+
return refuse(both.decision.state === "not-sent" ? "not-sent" : "already-answered", both.decision.state);
|
|
569
|
+
}
|
|
570
|
+
if ("problem" in both || both.row.state !== "sending") {
|
|
571
|
+
settle(store, catalog, both.row, both.decision, "not-sent", at, "the two records of this answer disagree");
|
|
572
|
+
return refuse("stores-disagree", "not-sent");
|
|
573
|
+
}
|
|
574
|
+
const problem = readyFailed ? refuse("connection-changed") : blocked(both.row, both.decision);
|
|
575
|
+
if (problem !== null) {
|
|
576
|
+
settle(store, catalog, both.row, both.decision, "not-sent", at, problem.message);
|
|
577
|
+
return { ...problem, state: "not-sent" };
|
|
578
|
+
}
|
|
579
|
+
const { row, decision } = both;
|
|
580
|
+
let bytes;
|
|
581
|
+
try {
|
|
582
|
+
bytes = connection.frame(row.requestRef, JSON.parse(row.answer));
|
|
583
|
+
}
|
|
584
|
+
catch {
|
|
585
|
+
bytes = null;
|
|
586
|
+
}
|
|
587
|
+
if (!(bytes instanceof Uint8Array) || bytes.length === 0 || bytes.length > MAX_ANSWER_BYTES) {
|
|
588
|
+
settle(store, catalog, row, decision, "not-sent", at, "the answer couldn't be put in the agent's form");
|
|
589
|
+
return refuse("not-sent", "not-sent");
|
|
590
|
+
}
|
|
591
|
+
const attemptId = randomBytes(16).toString("hex");
|
|
592
|
+
const marked = dbOf(catalog).prepare("UPDATE thread_request SET attempt_id = ?, write_started_at = ? WHERE id = ? AND state = 'sending' AND attempt_id IS NULL AND decision_id = ?")
|
|
593
|
+
.run(attemptId, at, row.id, decision.decisionId);
|
|
594
|
+
if (Number(marked.changes) !== 1)
|
|
595
|
+
return refuse("stores-disagree");
|
|
596
|
+
attempted.add(decision.decisionId);
|
|
597
|
+
store.handle.prepare("UPDATE thread_decision SET attempt_id = ?, write_started_at = ? WHERE id = ? AND state = 'sending' AND attempt_id IS NULL").run(attemptId, at, decision.id);
|
|
598
|
+
ledger(store, at, decision.source === "person" ? decision.by : "toolroll", decision.source === "person" ? "work" : "policy", "attempt", { thread: row.thread, turn: row.turn, decisionId: decision.decisionId }, `attempt ${attemptId} · marked in the coding catalog first, then here`);
|
|
599
|
+
return { attempt: { attemptId, bytes, requestId: row.id } };
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
catch {
|
|
603
|
+
markUncertain(store, catalog, input.request, clock, "the answer's attempt couldn't be recorded in both stores");
|
|
604
|
+
return refuse("uncertain", "uncertain");
|
|
605
|
+
}
|
|
606
|
+
if (!("attempt" in attempt))
|
|
607
|
+
return attempt;
|
|
608
|
+
const { attemptId, bytes } = attempt.attempt;
|
|
609
|
+
const decisionId = queued.decisionId;
|
|
610
|
+
attempting.add(decisionId);
|
|
611
|
+
let result;
|
|
612
|
+
try {
|
|
613
|
+
result = await boundedSend(connection, bytes, writeMs);
|
|
614
|
+
}
|
|
615
|
+
finally {
|
|
616
|
+
attempting.delete(decisionId);
|
|
617
|
+
}
|
|
618
|
+
const outcome = result.complete && result.written === bytes.length ? "sent" : "uncertain";
|
|
619
|
+
try {
|
|
620
|
+
const recorded = store.transact(() => {
|
|
621
|
+
const at = clock().toISOString();
|
|
622
|
+
const row = requestOf(catalog, input.request), decision = decisionOf(store, input.request);
|
|
623
|
+
if (row === null || decision === null || decision.attemptId !== attemptId || decision.state !== "sending" || row.attemptId !== attemptId || row.state !== "sending")
|
|
624
|
+
return false;
|
|
625
|
+
const moved = outcome === "sent"
|
|
626
|
+
? dbOf(catalog).prepare("UPDATE thread_request SET state = 'sent', sent_at = ? WHERE id = ? AND attempt_id = ? AND state = 'sending'").run(at, row.id, attemptId)
|
|
627
|
+
: dbOf(catalog).prepare("UPDATE thread_request SET state = 'uncertain', ended_at = ?, detail = ? WHERE id = ? AND attempt_id = ? AND state = 'sending'").run(at, "the send didn't finish", row.id, attemptId);
|
|
628
|
+
if (Number(moved.changes) !== 1)
|
|
629
|
+
return false;
|
|
630
|
+
store.handle.prepare("UPDATE thread_decision SET state = ?, state_at = ?, detail = ? WHERE id = ? AND attempt_id = ? AND state = 'sending'")
|
|
631
|
+
.run(outcome, at, outcome === "sent" ? null : result.written === null ? "the send didn't finish in time" : `${result.written} of ${bytes.length} bytes were handed over`, decision.id, attemptId);
|
|
632
|
+
ledger(store, at, decision.source === "person" ? decision.by : "toolroll", decision.source === "person" ? "work" : "policy", outcome, { thread: row.thread, turn: row.turn, decisionId: decision.decisionId });
|
|
633
|
+
return true;
|
|
634
|
+
});
|
|
635
|
+
if (!recorded) {
|
|
636
|
+
markUncertain(store, catalog, input.request, clock, "the answer's attempt changed while it was sent");
|
|
637
|
+
return refuse("uncertain", "uncertain");
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
catch {
|
|
641
|
+
markUncertain(store, catalog, input.request, clock, "the send's outcome couldn't be recorded");
|
|
642
|
+
return refuse("uncertain", "uncertain");
|
|
643
|
+
}
|
|
644
|
+
return outcome === "sent" ? { ok: true, state: "sent", decisionId } : refuse("uncertain", "uncertain");
|
|
645
|
+
}
|
|
646
|
+
const attempting = new Set();
|
|
647
|
+
async function boundedSend(connection, bytes, writeMs) {
|
|
648
|
+
const unknown = { written: null, complete: false };
|
|
649
|
+
const controller = new AbortController();
|
|
650
|
+
let timer;
|
|
651
|
+
const late = new Promise(resolve => { timer = setTimeout(() => { controller.abort(); resolve(unknown); }, writeMs); });
|
|
652
|
+
const valid = (result) => typeof result === "object" && result !== null && typeof result.complete === "boolean"
|
|
653
|
+
&& (result.written === null || (Number.isSafeInteger(result.written) && result.written >= 0));
|
|
654
|
+
try {
|
|
655
|
+
const sent = Promise.resolve().then(() => connection.send(bytes, { deadlineMs: writeMs, signal: controller.signal })).then(result => valid(result) ? result : unknown, () => unknown);
|
|
656
|
+
return await Promise.race([sent, late]);
|
|
657
|
+
}
|
|
658
|
+
finally {
|
|
659
|
+
clearTimeout(timer);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
function markUncertain(store, catalog, request, clock, detail) {
|
|
663
|
+
try {
|
|
664
|
+
store.transact(() => {
|
|
665
|
+
const row = requestOf(catalog, request);
|
|
666
|
+
if (row !== null)
|
|
667
|
+
settle(store, catalog, row, decisionOf(store, request), "uncertain", clock().toISOString(), detail);
|
|
668
|
+
});
|
|
669
|
+
}
|
|
670
|
+
catch { }
|
|
671
|
+
}
|
|
672
|
+
const stoppable = (decision, row) => decision !== null && row !== null && (decision.state === "decided" || decision.state === "sending") && (row.state === "decided" || row.state === "sending")
|
|
673
|
+
&& decision.attemptId === null && row.attemptId === null && !attempted.has(decision.decisionId);
|
|
674
|
+
export function cancelFlexibleAnswer(store, catalog, input) {
|
|
675
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
676
|
+
return refuse("not-available");
|
|
677
|
+
if (input.by?.kind !== "person")
|
|
678
|
+
return refuse("not-a-person");
|
|
679
|
+
if (typeof input.request !== "string" || !ID.test(input.request) || typeof input.by.name !== "string" || !Number.isSafeInteger(input.by.generation))
|
|
680
|
+
return refuse("invalid-request");
|
|
681
|
+
return store.transact(() => {
|
|
682
|
+
const at = (input.clock ?? systemClock)().toISOString();
|
|
683
|
+
const row = requestOf(catalog, input.request);
|
|
684
|
+
if (row === null)
|
|
685
|
+
return refuse("request-unknown");
|
|
686
|
+
if (input.by.name !== row.owner)
|
|
687
|
+
return refuse("not-owner");
|
|
688
|
+
const account = store.accountOf(row.owner);
|
|
689
|
+
if (account === null || account.revokedAt !== null || account.generation !== input.by.generation || input.by.generation !== row.ownerGeneration)
|
|
690
|
+
return refuse("stale-generation");
|
|
691
|
+
const decision = decisionOf(store, row.id);
|
|
692
|
+
if (!stoppable(decision, row))
|
|
693
|
+
return refuse(decision === null ? "already-answered" : "too-late", decision?.state ?? row.state);
|
|
694
|
+
settle(store, catalog, row, decision, "not-sent", at, `cancelled by ${input.by.name}`, input.by.name);
|
|
695
|
+
return { ok: true, state: "not-sent" };
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
export function revokeFlexibleAnswers(store, catalog, input) {
|
|
699
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
700
|
+
return refuse("not-available");
|
|
701
|
+
if (![input.thread, ...(input.turn === undefined ? [] : [input.turn]), ...(input.connection === undefined ? [] : [input.connection])].every(id => typeof id === "string" && ID.test(id))
|
|
702
|
+
|| typeof input.reason !== "string" || input.reason.length < 1 || input.reason.length > 200)
|
|
703
|
+
return refuse("invalid-request");
|
|
704
|
+
return store.transact(() => {
|
|
705
|
+
const at = (input.clock ?? systemClock)().toISOString();
|
|
706
|
+
let withdrawn = 0, notSent = 0;
|
|
707
|
+
const rows = dbOf(catalog).prepare("SELECT * FROM thread_request WHERE thread = ? AND state IN ('pending', 'decided', 'sending')").all(input.thread)
|
|
708
|
+
.map(one => readRequest(one)).filter(one => (input.turn === undefined || one.turn === input.turn) && (input.connection === undefined || one.connection === input.connection));
|
|
709
|
+
for (const row of rows) {
|
|
710
|
+
const decision = decisionOf(store, row.id);
|
|
711
|
+
if (row.state === "pending") {
|
|
712
|
+
dbOf(catalog).prepare("UPDATE thread_request SET state = 'withdrawn', ended_at = ?, detail = ? WHERE id = ? AND state = 'pending'").run(at, input.reason, row.id);
|
|
713
|
+
withdrawn++;
|
|
714
|
+
if (decision !== null)
|
|
715
|
+
settle(store, catalog, row, decision, "not-sent", at, input.reason);
|
|
716
|
+
}
|
|
717
|
+
else if (stoppable(decision, row)) {
|
|
718
|
+
settle(store, catalog, row, decision, "not-sent", at, input.reason);
|
|
719
|
+
notSent++;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
return { ok: true, withdrawn, notSent };
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
export function ackFlexibleAnswer(store, catalog, input) {
|
|
726
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
727
|
+
return refuse("not-available");
|
|
728
|
+
if (typeof input.connection !== "string" || !ID.test(input.connection) || typeof input.requestRef !== "string" || !REF.test(input.requestRef))
|
|
729
|
+
return refuse("invalid-request");
|
|
730
|
+
return store.transact(() => {
|
|
731
|
+
const at = (input.clock ?? systemClock)().toISOString();
|
|
732
|
+
const row = readRequest(dbOf(catalog).prepare("SELECT * FROM thread_request WHERE connection_id = ? AND request_ref = ?").get(input.connection, input.requestRef));
|
|
733
|
+
if (row === null || row.state !== "sent")
|
|
734
|
+
return { ok: true, delivered: false };
|
|
735
|
+
const decision = decisionOf(store, row.id);
|
|
736
|
+
if (decision === null || decision.state !== "sent" || decision.decisionId !== row.decisionId)
|
|
737
|
+
return { ok: true, delivered: false };
|
|
738
|
+
settle(store, catalog, row, decision, "delivered", at, "the agent acknowledged it");
|
|
739
|
+
return { ok: true, delivered: true };
|
|
740
|
+
});
|
|
741
|
+
}
|
|
742
|
+
export function noteFlexibleToolActivity(store, catalog, input) {
|
|
743
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
744
|
+
return refuse("not-available");
|
|
745
|
+
if (![input.connection, input.turn].every(id => typeof id === "string" && ID.test(id)) || typeof input.correlation !== "string" || !REF.test(input.correlation))
|
|
746
|
+
return refuse("invalid-request");
|
|
747
|
+
return store.transact(() => {
|
|
748
|
+
const at = (input.clock ?? systemClock)().toISOString();
|
|
749
|
+
const open = dbOf(catalog).prepare("SELECT * FROM thread_request WHERE connection_id = ? AND turn = ? AND correlation = ?")
|
|
750
|
+
.all(input.connection, input.turn, input.correlation).map(one => readRequest(one));
|
|
751
|
+
if (open.length !== 1 || open[0].state !== "sent")
|
|
752
|
+
return { ok: true, delivered: null, matched: open.length };
|
|
753
|
+
const row = open[0], decision = decisionOf(store, row.id);
|
|
754
|
+
if (decision === null || decision.state !== "sent" || decision.decisionId !== row.decisionId)
|
|
755
|
+
return { ok: true, delivered: null, matched: 1 };
|
|
756
|
+
settle(store, catalog, row, decision, "delivered", at, "the agent's next tool activity matched it");
|
|
757
|
+
return { ok: true, delivered: row.id, matched: 1 };
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
export function expireFlexibleAnswers(store, catalog, input = {}) {
|
|
761
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
762
|
+
return refuse("not-available");
|
|
763
|
+
const ackMs = input.ackMs ?? FLEXIBLE_ANSWER_ACK_MS, writeMs = input.writeMs ?? FLEXIBLE_ANSWER_WRITE_MS;
|
|
764
|
+
if (!Number.isSafeInteger(ackMs) || ackMs < 0 || !Number.isSafeInteger(writeMs) || writeMs < 0)
|
|
765
|
+
return refuse("invalid-request");
|
|
766
|
+
return store.transact(() => {
|
|
767
|
+
const now = (input.clock ?? systemClock)();
|
|
768
|
+
const at = now.toISOString();
|
|
769
|
+
const within = (since, limit) => { const t = Date.parse(String(since)); return Number.isFinite(t) && now.getTime() - t < limit; };
|
|
770
|
+
let uncertain = 0;
|
|
771
|
+
for (const raw of dbOf(catalog).prepare("SELECT * FROM thread_request WHERE state IN ('sending', 'sent')").all()) {
|
|
772
|
+
const row = readRequest(raw);
|
|
773
|
+
const decision = decisionOf(store, row.id);
|
|
774
|
+
if (decision !== null && attempting.has(decision.decisionId))
|
|
775
|
+
continue;
|
|
776
|
+
const launch = flexibleLaunch(store, row.connection);
|
|
777
|
+
const gone = launch === null || launch.state !== "live";
|
|
778
|
+
let why = null;
|
|
779
|
+
if (row.state === "sent" || decision?.state === "sent") {
|
|
780
|
+
if (row.state !== decision?.state)
|
|
781
|
+
why = "the two records of this answer disagree";
|
|
782
|
+
else if (gone)
|
|
783
|
+
why = "the agent stopped before it acknowledged the answer";
|
|
784
|
+
else if (!within(row.sentAt, ackMs))
|
|
785
|
+
why = "the agent never acknowledged the answer";
|
|
786
|
+
}
|
|
787
|
+
else {
|
|
788
|
+
const started = row.writeStartedAt ?? decision?.writeStartedAt ?? null;
|
|
789
|
+
if (started !== null && !within(started, writeMs))
|
|
790
|
+
why = "the answer's send was interrupted";
|
|
791
|
+
}
|
|
792
|
+
if (why === null)
|
|
793
|
+
continue;
|
|
794
|
+
settle(store, catalog, row, decision, "uncertain", at, why);
|
|
795
|
+
uncertain++;
|
|
796
|
+
}
|
|
797
|
+
for (const one of store.handle.prepare("SELECT request FROM thread_decision WHERE state IN ('sending', 'sent') AND request IS NOT NULL").all()) {
|
|
798
|
+
const decision = decisionOf(store, String(one["request"]));
|
|
799
|
+
if (decision === null || attempting.has(decision.decisionId))
|
|
800
|
+
continue;
|
|
801
|
+
const row = requestOf(catalog, String(one["request"]));
|
|
802
|
+
if (row !== null && OPEN.has(row.state))
|
|
803
|
+
continue;
|
|
804
|
+
store.handle.prepare("UPDATE thread_decision SET state = 'uncertain', state_at = ?, detail = ? WHERE id = ?").run(at, "the two records of this answer disagree", decision.id);
|
|
805
|
+
ledger(store, at, "toolroll", decision.source === "person" ? "work" : "policy", "uncertain", { thread: decision.thread, turn: decision.turn, decisionId: decision.decisionId }, "the two records of this answer disagree");
|
|
806
|
+
uncertain++;
|
|
807
|
+
}
|
|
808
|
+
return { ok: true, uncertain };
|
|
809
|
+
});
|
|
810
|
+
}
|
|
811
|
+
export function recoverFlexibleAnswersOf(store, catalog, input) {
|
|
812
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
813
|
+
return refuse("not-available");
|
|
814
|
+
if (typeof input.holder !== "string" || !HOLDER.test(input.holder))
|
|
815
|
+
return refuse("invalid-request");
|
|
816
|
+
return store.transact(() => {
|
|
817
|
+
const at = (input.clock ?? systemClock)().toISOString();
|
|
818
|
+
let withdrawn = 0, uncertain = 0, notSent = 0;
|
|
819
|
+
const rows = dbOf(catalog).prepare("SELECT * FROM thread_request WHERE holder = ? AND state IN ('pending', 'decided', 'sending', 'sent')").all(input.holder).map(one => readRequest(one));
|
|
820
|
+
for (const row of rows) {
|
|
821
|
+
const decision = decisionOf(store, row.id);
|
|
822
|
+
if (row.state === "pending") {
|
|
823
|
+
dbOf(catalog).prepare("UPDATE thread_request SET state = 'withdrawn', ended_at = ?, detail = ? WHERE id = ? AND state = 'pending'").run(at, "Toolroll restarted", row.id);
|
|
824
|
+
withdrawn++;
|
|
825
|
+
if (decision !== null) {
|
|
826
|
+
settle(store, catalog, row, decision, "not-sent", at, "Toolroll restarted before the answer was recorded");
|
|
827
|
+
notSent++;
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
else {
|
|
831
|
+
settle(store, catalog, row, decision, "uncertain", at, "Toolroll restarted before the answer was confirmed");
|
|
832
|
+
uncertain++;
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
const open = store.handle.prepare(`SELECT d.request FROM thread_decision d JOIN flexible_thread_launch l ON l.id = d.connection_id
|
|
836
|
+
WHERE l.holder = ? AND d.state IN ('decided', 'sending', 'sent') AND d.request IS NOT NULL`).all(input.holder).map(one => String(one["request"]));
|
|
837
|
+
for (const request of open) {
|
|
838
|
+
const decision = decisionOf(store, request);
|
|
839
|
+
if (decision === null)
|
|
840
|
+
continue;
|
|
841
|
+
const row = requestOf(catalog, request);
|
|
842
|
+
const to = decision.state === "decided" && (row === null || row.state === "pending" || row.state === "withdrawn" || row.state === "not-sent") ? "not-sent" : "uncertain";
|
|
843
|
+
store.handle.prepare("UPDATE thread_decision SET state = ?, state_at = ?, detail = ? WHERE id = ?").run(to, at, "Toolroll restarted", decision.id);
|
|
844
|
+
ledger(store, at, "toolroll", decision.source === "person" ? "work" : "policy", to, { thread: decision.thread, turn: decision.turn, decisionId: decision.decisionId }, "Toolroll restarted");
|
|
845
|
+
if (to === "not-sent")
|
|
846
|
+
notSent++;
|
|
847
|
+
else
|
|
848
|
+
uncertain++;
|
|
849
|
+
}
|
|
850
|
+
return { ok: true, withdrawn, uncertain, notSent };
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
export function recordFlexibleProviderDecision(store, input) {
|
|
854
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
855
|
+
return refuse("not-available");
|
|
856
|
+
if (![input.thread, input.turn, input.connection].every(id => typeof id === "string" && ID.test(id)) || typeof input.holder !== "string" || !HOLDER.test(input.holder)
|
|
857
|
+
|| typeof input.requestRef !== "string" || !REF.test(input.requestRef) || (input.decision !== "accept" && input.decision !== "decline")
|
|
858
|
+
|| typeof input.provider !== "string" || !/^[a-z][a-z0-9-]{0,39}$/.test(input.provider))
|
|
859
|
+
return refuse("invalid-request");
|
|
860
|
+
return store.transact(() => {
|
|
861
|
+
const at = (input.clock ?? systemClock)().toISOString();
|
|
862
|
+
const turn = flexibleTurn(store, input.turn);
|
|
863
|
+
if (turn === null)
|
|
864
|
+
return refuse("turn-changed");
|
|
865
|
+
const problem = standing(store, { thread: input.thread, turn: input.turn, connection: input.connection, holder: input.holder, owner: turn.owner, ownerGeneration: turn.ownerGeneration }, null);
|
|
866
|
+
if (problem !== null)
|
|
867
|
+
return problem;
|
|
868
|
+
const decisionId = randomBytes(16).toString("hex");
|
|
869
|
+
store.handle.prepare(`INSERT INTO thread_decision (decision_id, thread, turn, request, request_ref, source, decision, connection_id, state, at, by, state_at, detail)
|
|
870
|
+
VALUES (?, ?, ?, NULL, ?, 'provider', ?, ?, 'delivered', ?, ?, ?, 'decided by the agent''s own rules')`).run(decisionId, input.thread, input.turn, input.requestRef, input.decision, input.connection, at, `provider:${input.provider}`, at);
|
|
871
|
+
return { ok: true, decisionId };
|
|
872
|
+
});
|
|
873
|
+
}
|
|
874
|
+
export function flexibleRequestsOf(catalog, input) {
|
|
875
|
+
if (!FLEXIBLE_AVAILABLE)
|
|
876
|
+
return refuse("not-available");
|
|
877
|
+
const limit = input.limit ?? 20;
|
|
878
|
+
if (typeof input.thread !== "string" || !ID.test(input.thread) || (input.turn !== undefined && (typeof input.turn !== "string" || !ID.test(input.turn)))
|
|
879
|
+
|| !Number.isSafeInteger(limit) || limit < 1 || limit > 100)
|
|
880
|
+
return refuse("invalid-request");
|
|
881
|
+
const rows = dbOf(catalog).prepare(`SELECT * FROM thread_request WHERE thread = ? AND (? IS NULL OR turn = ?)
|
|
882
|
+
ORDER BY (state IN ('pending', 'decided', 'sending', 'sent')) DESC, created_at DESC, id LIMIT ?`).all(input.thread, input.turn ?? null, input.turn ?? null, limit);
|
|
883
|
+
const requests = rows.map(raw => {
|
|
884
|
+
const row = readRequest(raw);
|
|
885
|
+
return { request: row.id, turn: row.turn, connection: row.connection, requestRef: row.requestRef, kind: row.kind, card: JSON.parse(row.card), requestDigest: row.requestDigest,
|
|
886
|
+
state: row.state, decision: raw["decision"] === null ? null : String(raw["decision"]), detail: raw["detail"] === null ? null : String(raw["detail"]), createdAt: String(raw["created_at"]) };
|
|
887
|
+
}).sort((a, b) => a.createdAt < b.createdAt ? -1 : a.createdAt > b.createdAt ? 1 : a.request < b.request ? -1 : 1);
|
|
888
|
+
return { ok: true, requests };
|
|
889
|
+
}
|