toolroll 0.9.112 → 0.9.114
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 +58 -0
- package/README.md +28 -29
- package/dist/backup.js +29 -0
- package/dist/contracts/console-api.js +5 -1
- package/dist/contracts/engine-api.js +12 -0
- package/dist/easy-start.js +12 -7
- package/dist/engine-reads.js +20 -2
- package/dist/fast-terms.js +8 -4
- package/dist/flexible-agents.js +2 -8
- package/dist/flexible-answers.js +4 -26
- package/dist/flexible-available.js +31 -1
- package/dist/flexible-import.js +2 -14
- package/dist/flexible-launch.js +15 -3
- package/dist/flexible-launcher.js +0 -5
- package/dist/flexible-relay.js +66 -75
- package/dist/flexible-session.js +130 -36
- package/dist/flexible-setting-schema.js +10 -0
- package/dist/flexible-ship.js +8 -18
- package/dist/flexible-sign-in-schema.js +47 -0
- package/dist/flexible-sign-in-slot.js +4 -0
- package/dist/flexible-sign-in.js +470 -0
- package/dist/flexible-start.js +27 -8
- package/dist/flexible-thread.js +21 -27
- package/dist/flexible-turns.js +22 -17
- package/dist/flexible.js +9 -11
- package/dist/flow-triggers.js +4 -1
- package/dist/live-terminal.js +28 -0
- package/dist/local-owner.js +1 -0
- package/dist/operate.js +170 -4
- package/dist/release.js +1 -0
- package/dist/serve.js +9 -0
- package/dist/server/engine-api.js +112 -32
- package/dist/server/mutation-key.js +6 -0
- package/dist/server/people-tokens.js +10 -1
- package/dist/server/route-table.js +6 -0
- package/dist/server/settings-section-table.js +7 -0
- package/dist/server/settings-sections.js +87 -1
- package/dist/server/settings.js +123 -3
- package/dist/server/terminals.js +3 -3
- package/dist/settings-groups-ui.js +3 -0
- package/dist/settings-proofs.js +5 -0
- package/dist/store.js +71 -5
- package/dist/tool-secret-store.js +105 -0
- package/dist/toolroll-update.js +2 -1
- 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-contract.js +2 -1
- package/dist/tui-launch.js +3 -1
- package/dist/work-index.js +4 -0
- package/package.json +1 -1
package/dist/flexible-import.js
CHANGED
|
@@ -1,16 +1,14 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, mkdirSync, mkdtempSync, opendirSync, openSync, readFileSync, readSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
3
3
|
import { basename, dirname, isAbsolute, join } from "node:path";
|
|
4
|
-
import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
|
|
5
4
|
import { FLEXIBLE_UNAVAILABLE } from "./flexible.js";
|
|
6
|
-
import { flexibleThread, flexibleThreadBranch, flexibleThreadPaths, withFlexibleThreadLock } from "./flexible-thread.js";
|
|
5
|
+
import { flexibleProjectKnown, flexibleThread, flexibleThreadBranch, flexibleThreadPaths, withFlexibleThreadLock } from "./flexible-thread.js";
|
|
7
6
|
import { readProjectRefs, refsChangedOutside, refSnapshotOf, saveRefSnapshot } from "./flexible-refs.js";
|
|
8
7
|
import { PROTECTED_FILES, protectedChanges, protectedLinks } from "./agent-fence.js";
|
|
9
8
|
import { scanPatchForSecrets } from "./evidence.js";
|
|
10
9
|
import { PROOF_LIMITS } from "./proof.js";
|
|
11
10
|
import { run } from "./exec.js";
|
|
12
11
|
import { hardenedGit, recordedCommonDir } from "./teardown-git.js";
|
|
13
|
-
import { projectRowKnown } from "./store.js";
|
|
14
12
|
const NOTHING = "Nothing was imported.";
|
|
15
13
|
const PRE_WORDS = {
|
|
16
14
|
"not-available": FLEXIBLE_UNAVAILABLE,
|
|
@@ -246,7 +244,7 @@ function sourceOf(store, id, limits, deadline) {
|
|
|
246
244
|
return pre("thread-unknown");
|
|
247
245
|
if (thread.state !== "ready")
|
|
248
246
|
return pre("thread-not-ready");
|
|
249
|
-
if (!
|
|
247
|
+
if (!flexibleProjectKnown(store, thread.repo))
|
|
250
248
|
return pre("not-a-project");
|
|
251
249
|
const state = stateFolderOf(store);
|
|
252
250
|
if (state === null)
|
|
@@ -333,8 +331,6 @@ async function changedEntries(read, repo, base, candidate) {
|
|
|
333
331
|
return entries;
|
|
334
332
|
}
|
|
335
333
|
export async function readFlexibleCandidate(store, input) {
|
|
336
|
-
if (!FLEXIBLE_AVAILABLE)
|
|
337
|
-
return pre("not-available");
|
|
338
334
|
const limits = limitsOf(input.limits);
|
|
339
335
|
const deadline = Date.now() + limits.importMs;
|
|
340
336
|
const source = sourceOf(store, input.thread, limits, deadline);
|
|
@@ -612,8 +608,6 @@ async function quarantineChecks(read, repo, source, candidate, limits) {
|
|
|
612
608
|
return null;
|
|
613
609
|
}
|
|
614
610
|
export async function importFlexibleCandidate(store, input) {
|
|
615
|
-
if (!FLEXIBLE_AVAILABLE)
|
|
616
|
-
return pre("not-available");
|
|
617
611
|
const locked = await withFlexibleThreadLock(input.thread, () => guarded(() => importLocked(store, input)));
|
|
618
612
|
if (locked.ok === false && (locked.reason === "not-available" || locked.reason === "thread-unknown"))
|
|
619
613
|
return pre(locked.reason);
|
|
@@ -692,8 +686,6 @@ async function importLocked(store, input) {
|
|
|
692
686
|
});
|
|
693
687
|
}
|
|
694
688
|
export async function removeFlexibleImportRefs(store, input) {
|
|
695
|
-
if (!FLEXIBLE_AVAILABLE)
|
|
696
|
-
return pre("not-available");
|
|
697
689
|
const locked = await withFlexibleThreadLock(input.thread, async () => {
|
|
698
690
|
const thread = flexibleThread(store, input.thread);
|
|
699
691
|
if (thread === null)
|
|
@@ -726,8 +718,6 @@ export async function removeFlexibleImportRefs(store, input) {
|
|
|
726
718
|
return locked;
|
|
727
719
|
}
|
|
728
720
|
export async function flexibleTaskBranch(store, input) {
|
|
729
|
-
if (!FLEXIBLE_AVAILABLE)
|
|
730
|
-
return false;
|
|
731
721
|
const thread = flexibleThread(store, input.thread);
|
|
732
722
|
if (thread === null || !SHA.test(input.at) || !/^toolroll\/flexible-[0-9a-f]{32}$/.test(input.branch))
|
|
733
723
|
return false;
|
|
@@ -746,8 +736,6 @@ export async function flexibleTaskBranch(store, input) {
|
|
|
746
736
|
return done.code === 0;
|
|
747
737
|
}
|
|
748
738
|
export async function settleInterruptedImport(store, input) {
|
|
749
|
-
if (!FLEXIBLE_AVAILABLE)
|
|
750
|
-
return pre("not-available");
|
|
751
739
|
const thread = flexibleThread(store, input.thread);
|
|
752
740
|
if (thread === null)
|
|
753
741
|
return pre("thread-unknown");
|
package/dist/flexible-launch.js
CHANGED
|
@@ -7,6 +7,7 @@ import { observeCustody, realCustodyIO, stopCustody, custodySettled } from "./fl
|
|
|
7
7
|
import { interruptFlexibleThreadTurns } from "./flexible-turns.js";
|
|
8
8
|
import { currentMachineId } from "./machine-identity.js";
|
|
9
9
|
import { relayCancel } from "./flexible-relay-cancel.js";
|
|
10
|
+
import { flexibleAvailable } from "./flexible-available.js";
|
|
10
11
|
export const FLEXIBLE_AGENT_PROVIDERS = ["claude", "codex", "gemini", "openrouter"];
|
|
11
12
|
const LAUNCH_ID = /^[0-9a-f]{32}$/;
|
|
12
13
|
const text = (value) => value === null || value === undefined ? null : String(value);
|
|
@@ -73,9 +74,20 @@ export function recordGateShut(store, input) {
|
|
|
73
74
|
});
|
|
74
75
|
}
|
|
75
76
|
const LAUNCHED = "flexible agent launched";
|
|
76
|
-
export function
|
|
77
|
-
store.
|
|
78
|
-
|
|
77
|
+
export function reserveLaunchOpen(store, input) {
|
|
78
|
+
return store.transact(() => {
|
|
79
|
+
if (!flexibleAvailable(store))
|
|
80
|
+
return "interactive agent threads were turned off";
|
|
81
|
+
const why = input.check();
|
|
82
|
+
if (why !== null)
|
|
83
|
+
return why;
|
|
84
|
+
const live = store.handle.prepare("SELECT 1 AS live FROM flexible_thread_launch WHERE id = ? AND thread = ? AND state = 'live'").get(input.launch, input.thread);
|
|
85
|
+
if (live === undefined)
|
|
86
|
+
return "its launch is no longer live";
|
|
87
|
+
store.recordAction({ at: (input.clock ?? (() => new Date()))().toISOString(), actor: "toolroll", repo: null, taskId: null, runId: null, source: "policy", action: LAUNCHED, outcome: "launched",
|
|
88
|
+
detail: `turn ${input.turn ?? "none"} · thread ${input.thread} · launch ${input.launch}` });
|
|
89
|
+
return null;
|
|
90
|
+
});
|
|
79
91
|
}
|
|
80
92
|
export function flexibleTurnLaunched(store, turn) {
|
|
81
93
|
if (!/^[0-9a-f]{32}$/.test(turn))
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
|
-
import { FLEXIBLE_AVAILABLE } from "./flexible-available.js";
|
|
4
3
|
import { FLEXIBLE_UNAVAILABLE } from "./flexible.js";
|
|
5
4
|
import { NETWORK_POLICY_VERSION, proxyEnv, REGISTRY_HOSTS, repositoryEcosystems, startEgressProxy } from "./egress.js";
|
|
6
5
|
import { prepareProtectedStorage, storageRefusalOf } from "./protected-storage.js";
|
|
@@ -12,8 +11,6 @@ const WORDS = Object.freeze({
|
|
|
12
11
|
});
|
|
13
12
|
const refuse = (reason, message = WORDS[reason]) => ({ ok: false, reason, message });
|
|
14
13
|
export function flexibleThreadNetwork(store, repo) {
|
|
15
|
-
if (!FLEXIBLE_AVAILABLE)
|
|
16
|
-
return refuse("not-available");
|
|
17
14
|
const project = store.projectNetwork(repo);
|
|
18
15
|
if (project.mode === "open")
|
|
19
16
|
return { version: NETWORK_POLICY_VERSION, mode: "open", hosts: [], loopback: "proxy-only" };
|
|
@@ -24,8 +21,6 @@ export function flexibleNetworkDigest(network) {
|
|
|
24
21
|
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
22
|
}
|
|
26
23
|
export function createFlexibleLauncher(store, seams = {}) {
|
|
27
|
-
if (!FLEXIBLE_AVAILABLE)
|
|
28
|
-
return refuse("not-available");
|
|
29
24
|
const startProxy = seams.startProxy ?? ((options) => startEgressProxy(options));
|
|
30
25
|
const storageNow = seams.storage ?? (() => prepareProtectedStorage(homedir()));
|
|
31
26
|
const live = new Map();
|
package/dist/flexible-relay.js
CHANGED
|
@@ -4,37 +4,37 @@ import { createServer, request as httpRequest } from "node:http";
|
|
|
4
4
|
import { request as httpsRequest } from "node:https";
|
|
5
5
|
import { dirname } from "node:path";
|
|
6
6
|
import { StringDecoder } from "node:string_decoder";
|
|
7
|
-
import {
|
|
7
|
+
import { flexibleAvailable } from "./flexible-available.js";
|
|
8
8
|
import { FLEXIBLE_UNAVAILABLE } from "./flexible.js";
|
|
9
9
|
import { issueRelayGrant, revokeRelayGrant } from "./flexible-launch.js";
|
|
10
10
|
import { onRelayCancel } from "./flexible-relay-cancel.js";
|
|
11
11
|
import { FLEXIBLE_RELAY_UPSTREAMS } from "./flexible-relay-upstreams.js";
|
|
12
|
-
import { chargeFlexibleTurn, flexibleTurn } from "./flexible-turns.js";
|
|
13
|
-
import {
|
|
12
|
+
import { chargeFlexibleTurn, flexibleTurn, interruptFlexibleTurnSignIn } from "./flexible-turns.js";
|
|
13
|
+
import { signInEpochOf, signInForTurn, signInHoldsFor, signInRefusedBy, signInRefusedWords, signInStandsAt } from "./flexible-sign-in.js";
|
|
14
14
|
const START_WORDS = Object.freeze({
|
|
15
15
|
"not-available": FLEXIBLE_UNAVAILABLE,
|
|
16
16
|
"invalid-request": "That isn't a thread Toolroll can start a sign-in relay for. Nothing was started.",
|
|
17
17
|
"thread-unknown": "There's no such thread, or it isn't ready.",
|
|
18
18
|
"no-state-folder": "Toolroll's state folder can't be found, so its sign-in relay can't start.",
|
|
19
|
-
"no-credential": "Toolroll holds no Claude sign-in for Flexible threads yet, so no thread can start. Nothing was started.",
|
|
20
19
|
});
|
|
21
20
|
const refuse = (reason) => ({ ok: false, reason, message: START_WORDS[reason] });
|
|
22
21
|
export const LINUX_SECOND_RELAY_PORT = 1080;
|
|
23
22
|
export function relayUrlInside(port, platform = process.platform) {
|
|
24
23
|
return platform === "linux" ? `http://127.0.0.1:${LINUX_SECOND_RELAY_PORT}` : `http://127.0.0.1:${port}`;
|
|
25
24
|
}
|
|
26
|
-
export const
|
|
27
|
-
|
|
28
|
-
unsettled: { status:
|
|
29
|
-
"check-failed": { status:
|
|
25
|
+
export const RELAY_CALL_ANSWERS = Object.freeze({
|
|
26
|
+
"threads-off": { status: 403, type: "permission_error", message: "Interactive agent threads were turned off in Toolroll, so nothing was sent to the model." },
|
|
27
|
+
unsettled: { status: 403, type: "permission_error", message: "Toolroll couldn't record an earlier model call in this turn yet, so it sent nothing more. Send your message again in a moment." },
|
|
28
|
+
"check-failed": { status: 403, type: "permission_error", message: "Toolroll couldn't check whether this thread may still use Claude, so nothing was sent. Send your message again; if this keeps happening, restart Toolroll." },
|
|
30
29
|
"credential-header": { status: 400, type: "invalid_request_error", message: "Toolroll's sign-in relay chooses the credential itself: a call can't carry its own key, sign-in or service override." },
|
|
31
30
|
header: { status: 400, type: "invalid_request_error", message: "A request header isn't in a form Toolroll's sign-in relay accepts." },
|
|
32
31
|
beta: { status: 400, type: "invalid_request_error", message: "That anthropic-beta feature isn't one Toolroll's sign-in relay allows." },
|
|
33
32
|
route: { status: 404, type: "not_found_error", message: "Toolroll's sign-in relay only forwards messages and token counts." },
|
|
34
33
|
"too-many": { status: 429, type: "rate_limit_error", message: "This thread has too many model calls running at once. Try again when one finishes." },
|
|
35
34
|
"no-turn": { status: 409, type: "invalid_request_error", message: "This thread has no turn running, so nothing was sent to the model." },
|
|
36
|
-
"billing-mismatch": { status: 403, type: "permission_error", message: "This turn was admitted for a different kind of Claude sign-in than the one
|
|
37
|
-
"no-
|
|
35
|
+
"billing-mismatch": { status: 403, type: "permission_error", message: "This turn was admitted for a different kind of Claude sign-in than the one saved, so nothing was sent." },
|
|
36
|
+
"no-sign-in": { status: 403, type: "permission_error", message: "The person who started this thread has no Claude sign-in for threads that counts now (none saved, removed, or their account changed), so nothing was sent. Save one in Settings → General, or with `toolroll config set flexible-sign-in`." },
|
|
37
|
+
"sign-in-refused": { status: 403, type: "permission_error", message: "Claude didn't accept this Claude sign-in for threads earlier, so nothing was sent. Save a new one in Settings → General, or with `toolroll config set flexible-sign-in`." },
|
|
38
38
|
"body-too-large": { status: 413, type: "request_too_large", message: "That request is larger than Toolroll's sign-in relay forwards." },
|
|
39
39
|
body: { status: 400, type: "invalid_request_error", message: "That request isn't JSON Toolroll's sign-in relay can read." },
|
|
40
40
|
model: { status: 400, type: "invalid_request_error", message: "That model isn't one this turn may use." },
|
|
@@ -44,46 +44,6 @@ const CALL_WORDS = Object.freeze({
|
|
|
44
44
|
});
|
|
45
45
|
const UNAUTHORIZED = "This relay token isn't authorized (it was never issued, its launch ended, or its thread was stopped).";
|
|
46
46
|
const errorBody = (type, message) => JSON.stringify({ type: "error", error: { type, message } });
|
|
47
|
-
function credentialOf(state, upstream) {
|
|
48
|
-
let text;
|
|
49
|
-
try {
|
|
50
|
-
text = readHeldSecret(state, FLEXIBLE_RELAY_CREDENTIAL.name, FLEXIBLE_RELAY_CREDENTIAL.file);
|
|
51
|
-
}
|
|
52
|
-
catch {
|
|
53
|
-
return null;
|
|
54
|
-
}
|
|
55
|
-
if (text === null)
|
|
56
|
-
return null;
|
|
57
|
-
try {
|
|
58
|
-
const parsed = JSON.parse(text);
|
|
59
|
-
const kind = parsed.kind === "setup-token" || parsed.kind === "api-key" ? parsed.kind : null;
|
|
60
|
-
if (kind === null || typeof parsed.value !== "string" || !upstream.auth[kind].shape.test(parsed.value))
|
|
61
|
-
return null;
|
|
62
|
-
return { kind, value: parsed.value };
|
|
63
|
-
}
|
|
64
|
-
catch {
|
|
65
|
-
return null;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
export function flexibleRelayBilling(store) {
|
|
69
|
-
if (!FLEXIBLE_AVAILABLE)
|
|
70
|
-
return refuse("not-available");
|
|
71
|
-
const file = store.databaseFile();
|
|
72
|
-
let state;
|
|
73
|
-
try {
|
|
74
|
-
if (file === null || file === "" || file === ":memory:")
|
|
75
|
-
return refuse("no-state-folder");
|
|
76
|
-
state = dirname(realpathSync(file));
|
|
77
|
-
}
|
|
78
|
-
catch {
|
|
79
|
-
return refuse("no-state-folder");
|
|
80
|
-
}
|
|
81
|
-
const upstream = FLEXIBLE_RELAY_UPSTREAMS.claude;
|
|
82
|
-
const credential = credentialOf(state, upstream);
|
|
83
|
-
if (credential === null)
|
|
84
|
-
return refuse("no-credential");
|
|
85
|
-
return { ok: true, billing: upstream.auth[credential.kind].billing };
|
|
86
|
-
}
|
|
87
47
|
const KEY_SHAPE = /sk-ant-[A-Za-z0-9_-]{6,}/g;
|
|
88
48
|
const REDACTED = "[redacted]";
|
|
89
49
|
function redact(text, secrets = []) {
|
|
@@ -163,10 +123,11 @@ function grantOf(store, token) {
|
|
|
163
123
|
}
|
|
164
124
|
const grantStillLive = (store, digest) => 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
|
|
165
125
|
WHERE g.token_digest = ? AND g.revoked_at IS NULL AND l.state = 'live'`).get(digest) !== undefined;
|
|
166
|
-
function authorizedNow(store, digest, turn) {
|
|
126
|
+
function authorizedNow(store, digest, turn, person, epoch) {
|
|
167
127
|
try {
|
|
168
128
|
return 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
|
|
169
|
-
JOIN thread_turn t ON t.id = ? AND t.thread = g.thread AND t.status = 'running' WHERE g.token_digest = ? AND g.revoked_at IS NULL AND l.state = 'live'`).get(turn, digest) !== undefined
|
|
129
|
+
JOIN thread_turn t ON t.id = ? AND t.thread = g.thread AND t.status = 'running' WHERE g.token_digest = ? AND g.revoked_at IS NULL AND l.state = 'live'`).get(turn, digest) !== undefined
|
|
130
|
+
&& signInHoldsFor(store, { turn, person, epoch });
|
|
170
131
|
}
|
|
171
132
|
catch {
|
|
172
133
|
return false;
|
|
@@ -178,7 +139,8 @@ function currentTurn(store, thread, grant, provider) {
|
|
|
178
139
|
if (rows.length !== 1)
|
|
179
140
|
return null;
|
|
180
141
|
const turn = flexibleTurn(store, String(rows[0]["id"]));
|
|
181
|
-
|
|
142
|
+
const starter = store.handle.prepare("SELECT created_by FROM flexible_thread WHERE id = ?").get(thread)?.["created_by"];
|
|
143
|
+
return turn !== null && turn.status === "running" && turn.provider === provider && turn.holder === grant.holder && typeof starter === "string" && turn.owner === starter ? turn : null;
|
|
182
144
|
}
|
|
183
145
|
const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
|
|
184
146
|
const PARSE_LIMIT = 16 * 1024 * 1024;
|
|
@@ -401,7 +363,7 @@ const UPSTREAM_IDLE_MS = 10 * 60_000;
|
|
|
401
363
|
const WATCH_MS = 250;
|
|
402
364
|
const THREAD_ID = /^[0-9a-f]{32}$/;
|
|
403
365
|
export async function startFlexibleRelay(store, input) {
|
|
404
|
-
if (!
|
|
366
|
+
if (!flexibleAvailable(store))
|
|
405
367
|
return refuse("not-available");
|
|
406
368
|
if (typeof input?.thread !== "string" || !THREAD_ID.test(input.thread) || (input.log !== undefined && typeof input.log !== "function"))
|
|
407
369
|
return refuse("invalid-request");
|
|
@@ -456,8 +418,12 @@ export async function startFlexibleRelay(store, input) {
|
|
|
456
418
|
}
|
|
457
419
|
}
|
|
458
420
|
const refused = record.status === "refused";
|
|
459
|
-
|
|
460
|
-
|
|
421
|
+
const signIn = record.signIn ?? null, signInRefused = signIn !== null && record.signInRefused === true && record.status === "upstream-error";
|
|
422
|
+
store.handle.prepare(`INSERT INTO thread_relay_call (thread, turn, launch, upstream, at, ended_at, route, model, streamed, status, reason, http_status, tokens_in, tokens_out, cache_read, cache_write, cost_microusd, cost_basis, detail,
|
|
423
|
+
sign_in_person, sign_in_generation, sign_in_refused, sign_in_epoch)
|
|
424
|
+
VALUES (?, ?, ?, 'claude', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(thread, record.turn, grant.launch, record.at, new Date().toISOString(), record.route, record.model !== null && record.model.length <= 200 ? record.model : null, record.streamed ? 1 : 0, record.status, record.reason, record.httpStatus, refused ? 0 : record.usage.input, refused ? 0 : record.usage.output, refused ? 0 : record.usage.cacheRead, refused ? 0 : record.usage.cacheWrite, cost, basis, detail === null ? null : redact(detail, secrets).slice(0, 500), signIn?.person ?? null, signIn?.generation ?? null, signInRefused ? 1 : null, signIn?.epoch ?? null);
|
|
425
|
+
if (signInRefused && record.turn !== null && record.httpStatus !== null)
|
|
426
|
+
interruptFlexibleTurnSignIn(store, { turn: record.turn, detail: signInRefusedWords(record.httpStatus) });
|
|
461
427
|
written = true;
|
|
462
428
|
});
|
|
463
429
|
}
|
|
@@ -477,14 +443,14 @@ export async function startFlexibleRelay(store, input) {
|
|
|
477
443
|
if (!charged.ok)
|
|
478
444
|
throw new Error(`its reservation couldn't be reconciled: ${charged.reason}`);
|
|
479
445
|
const now = new Date().toISOString();
|
|
480
|
-
store.handle.prepare(`INSERT INTO thread_relay_call (thread, turn, launch, upstream, at, ended_at, route, model, streamed, status, reason, http_status, cost_microusd, cost_basis, detail)
|
|
481
|
-
VALUES (?, ?, ?, 'claude', ?, ?, ?, NULL, 0, 'incomplete', NULL, NULL, 0, ?, ?)`).run(thread, turnId, String(row["launch"]), String(row["reserved_at"]), now, free ? "count-tokens" : "messages", charged.basis, free ? "a token count whose record was lost; it costs nothing" : "its charge was never recorded, so it counts as unknown");
|
|
446
|
+
store.handle.prepare(`INSERT INTO thread_relay_call (thread, turn, launch, upstream, at, ended_at, route, model, streamed, status, reason, http_status, cost_microusd, cost_basis, detail, sign_in_person, sign_in_generation, sign_in_epoch)
|
|
447
|
+
VALUES (?, ?, ?, 'claude', ?, ?, ?, NULL, 0, 'incomplete', NULL, NULL, 0, ?, ?, ?, ?, ?)`).run(thread, turnId, String(row["launch"]), String(row["reserved_at"]), now, free ? "count-tokens" : "messages", charged.basis, free ? "a token count whose record was lost; it costs nothing" : "its charge was never recorded, so it counts as unknown", row["sign_in_person"] ?? null, row["sign_in_generation"] ?? null, row["sign_in_epoch"] ?? null);
|
|
482
448
|
unsettled.delete(id);
|
|
483
449
|
};
|
|
484
450
|
const sweep = () => {
|
|
485
451
|
let rows;
|
|
486
452
|
try {
|
|
487
|
-
rows = store.handle.prepare("SELECT id, turn, launch, relay, route, reserved_at FROM thread_relay_pending WHERE thread = ? ORDER BY id").all(thread);
|
|
453
|
+
rows = store.handle.prepare("SELECT id, turn, launch, relay, route, reserved_at, sign_in_person, sign_in_generation, sign_in_epoch FROM thread_relay_pending WHERE thread = ? ORDER BY id").all(thread);
|
|
488
454
|
}
|
|
489
455
|
catch {
|
|
490
456
|
return;
|
|
@@ -524,7 +490,7 @@ export async function startFlexibleRelay(store, input) {
|
|
|
524
490
|
const xkey = request.headers["x-api-key"] === undefined ? undefined : String(request.headers["x-api-key"]);
|
|
525
491
|
if (bearer !== undefined && xkey !== undefined) {
|
|
526
492
|
request.resume();
|
|
527
|
-
reply(400, "invalid_request_error",
|
|
493
|
+
reply(400, "invalid_request_error", RELAY_CALL_ANSWERS["credential-header"].message);
|
|
528
494
|
return;
|
|
529
495
|
}
|
|
530
496
|
const tokenHeader = bearer !== undefined ? "authorization" : xkey !== undefined ? "x-api-key" : null;
|
|
@@ -546,7 +512,7 @@ export async function startFlexibleRelay(store, input) {
|
|
|
546
512
|
let route = null;
|
|
547
513
|
let model = null, streamed = false, turn = null;
|
|
548
514
|
const refused = (reason, detail = null, extra = {}) => {
|
|
549
|
-
const words =
|
|
515
|
+
const words = RELAY_CALL_ANSWERS[reason];
|
|
550
516
|
request.resume();
|
|
551
517
|
reply(words.status, words.type, words.message, extra);
|
|
552
518
|
settle(authed, { turn: turn?.id ?? null, at, route: route?.kind ?? "other", model, streamed, status: "refused", reason, httpStatus: words.status,
|
|
@@ -683,21 +649,28 @@ export async function startFlexibleRelay(store, input) {
|
|
|
683
649
|
refused("server-fetch", fetched);
|
|
684
650
|
return;
|
|
685
651
|
}
|
|
686
|
-
const
|
|
687
|
-
if (
|
|
688
|
-
refused(
|
|
652
|
+
const found = signInForTurn(store, state, turn);
|
|
653
|
+
if (!found.ok) {
|
|
654
|
+
refused(found.reason);
|
|
689
655
|
return;
|
|
690
656
|
}
|
|
657
|
+
const credential = found.signIn;
|
|
691
658
|
const auth = upstream.auth[credential.kind];
|
|
692
659
|
if (auth.billing !== turn.billing) {
|
|
693
660
|
refused("billing-mismatch");
|
|
694
661
|
return;
|
|
695
662
|
}
|
|
696
663
|
const secrets = [credential.value];
|
|
664
|
+
const signIn = { person: credential.person, generation: credential.generation };
|
|
697
665
|
let reservation = null;
|
|
666
|
+
let epoch = -1;
|
|
698
667
|
let blocked = null;
|
|
699
668
|
try {
|
|
700
669
|
store.transact(() => {
|
|
670
|
+
if (!flexibleAvailable(store)) {
|
|
671
|
+
blocked = "threads-off";
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
701
674
|
if (!grantStillLive(store, authed.digest)) {
|
|
702
675
|
blocked = "unauthorized";
|
|
703
676
|
return;
|
|
@@ -707,7 +680,13 @@ export async function startFlexibleRelay(store, input) {
|
|
|
707
680
|
blocked = "no-turn";
|
|
708
681
|
return;
|
|
709
682
|
}
|
|
710
|
-
|
|
683
|
+
const stands = signInStandsAt(store, { thread, turn: now.id, person: signIn.person, generation: signIn.generation });
|
|
684
|
+
if (stands !== null) {
|
|
685
|
+
blocked = stands;
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
epoch = signInEpochOf(store, signIn.person);
|
|
689
|
+
for (const row of store.handle.prepare("SELECT id, turn, launch, relay, route, reserved_at, sign_in_person, sign_in_generation, sign_in_epoch FROM thread_relay_pending WHERE thread = ? ORDER BY id").all(thread)) {
|
|
711
690
|
if (ours.has(Number(row["id"])))
|
|
712
691
|
continue;
|
|
713
692
|
if (row["relay"] === instance && flexibleTurn(store, String(row["turn"]))?.status === "running") {
|
|
@@ -716,8 +695,8 @@ export async function startFlexibleRelay(store, input) {
|
|
|
716
695
|
}
|
|
717
696
|
reconcile(row);
|
|
718
697
|
}
|
|
719
|
-
reservation = Number(store.handle.prepare("INSERT INTO thread_relay_pending (thread, turn, launch, holder, relay, route, reserved_at) VALUES (?, ?, ?, ?, ?, ?, ?)")
|
|
720
|
-
.run(thread, turn.id, authed.launch, authed.holder, instance, route.kind, new Date().toISOString()).lastInsertRowid);
|
|
698
|
+
reservation = Number(store.handle.prepare("INSERT INTO thread_relay_pending (thread, turn, launch, holder, relay, route, reserved_at, sign_in_person, sign_in_generation, sign_in_epoch) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
|
|
699
|
+
.run(thread, turn.id, authed.launch, authed.holder, instance, route.kind, new Date().toISOString(), signIn.person, signIn.generation, epoch).lastInsertRowid);
|
|
721
700
|
});
|
|
722
701
|
}
|
|
723
702
|
catch {
|
|
@@ -749,9 +728,9 @@ export async function startFlexibleRelay(store, input) {
|
|
|
749
728
|
headers[auth.header] = `${auth.prefix}${credential.value}`;
|
|
750
729
|
const routeKind = route.kind;
|
|
751
730
|
const turnId = turn.id;
|
|
752
|
-
const live = await forward(target, headers, sent, response, routeKind, streamed, upstream, secrets, one => { release(); calls.add(one); }, authed, turnId, result => {
|
|
731
|
+
const live = await forward(target, headers, sent, response, routeKind, streamed, upstream, secrets, one => { release(); calls.add(one); }, authed, turnId, signIn.person, epoch, result => {
|
|
753
732
|
const record = { turn: turnId, at, route: routeKind, model, streamed: result.streamed, status: result.status, reason: null, httpStatus: result.httpStatus,
|
|
754
|
-
usage: result.usage, charge: result.charge, detail: result.detail };
|
|
733
|
+
usage: result.usage, charge: result.charge, detail: result.detail, signIn: { ...signIn, epoch }, signInRefused: result.signInRefused };
|
|
755
734
|
if (!settle(authed, record, secrets, reserved))
|
|
756
735
|
unsettled.set(reserved, () => settle(authed, record, secrets, reserved));
|
|
757
736
|
ours.delete(reserved);
|
|
@@ -762,14 +741,14 @@ export async function startFlexibleRelay(store, input) {
|
|
|
762
741
|
release();
|
|
763
742
|
}
|
|
764
743
|
};
|
|
765
|
-
const forward = (target, headers, body, response, route, streamedAsked, upstream, secrets, started, grant, turn, ended) => new Promise(resolve => {
|
|
744
|
+
const forward = (target, headers, body, response, route, streamedAsked, upstream, secrets, started, grant, turn, person, epoch, ended) => new Promise(resolve => {
|
|
766
745
|
const free = route === "count-tokens";
|
|
767
746
|
let sent = false, settled = false, streamed = streamedAsked;
|
|
768
747
|
let meter = null;
|
|
769
748
|
const send = target.protocol === "https:" ? httpsRequest : httpRequest;
|
|
770
749
|
const outgoing = send({ protocol: target.protocol, hostname: target.hostname, port: target.port === "" ? undefined : Number(target.port), method: "POST",
|
|
771
750
|
path: `${target.pathname}${target.search}`, headers, agent: false, timeout: UPSTREAM_IDLE_MS, ...(target.protocol === "https:" ? { servername: target.hostname } : {}) });
|
|
772
|
-
const finish = (status, httpStatus, detail, complete, answer = () => { }) => {
|
|
751
|
+
const finish = (status, httpStatus, detail, complete, answer = () => { }, signInRefused = false) => {
|
|
773
752
|
if (settled)
|
|
774
753
|
return;
|
|
775
754
|
settled = true;
|
|
@@ -777,7 +756,7 @@ export async function startFlexibleRelay(store, input) {
|
|
|
777
756
|
const charge = free || (!sent && !complete) || status === "upstream-error" || status === "redirect-refused" ? { costUsd: 0, incomplete: false }
|
|
778
757
|
: complete ? { costUsd: null, incomplete: false } : { costUsd: null, incomplete: true };
|
|
779
758
|
try {
|
|
780
|
-
ended({ status, httpStatus, usage, charge, detail, streamed });
|
|
759
|
+
ended({ status, httpStatus, usage, charge, detail, streamed, signInRefused });
|
|
781
760
|
}
|
|
782
761
|
finally {
|
|
783
762
|
try {
|
|
@@ -787,7 +766,7 @@ export async function startFlexibleRelay(store, input) {
|
|
|
787
766
|
resolve(live);
|
|
788
767
|
}
|
|
789
768
|
};
|
|
790
|
-
const live = { digest: grant.digest, launch: grant.launch, turn, cut: false, abort: why => {
|
|
769
|
+
const live = { digest: grant.digest, launch: grant.launch, turn, person, epoch, cut: false, abort: why => {
|
|
791
770
|
live.cut = true;
|
|
792
771
|
outgoing.destroy();
|
|
793
772
|
finish("aborted", null, why, false, () => {
|
|
@@ -852,6 +831,14 @@ export async function startFlexibleRelay(store, input) {
|
|
|
852
831
|
kind = value.error.type;
|
|
853
832
|
}
|
|
854
833
|
catch { }
|
|
834
|
+
if (signInRefusedBy(status, kind)) {
|
|
835
|
+
const words = errorBody("permission_error", signInRefusedWords(status));
|
|
836
|
+
finish("upstream-error", status, `Claude didn't accept the sign-in (HTTP ${status})`, false, () => {
|
|
837
|
+
if (!response.headersSent)
|
|
838
|
+
response.writeHead(403, { "content-type": "application/json", "cache-control": "no-store" }).end(words);
|
|
839
|
+
}, true);
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
855
842
|
finish("upstream-error", status, `the model service said ${kind}`, false, () => { if (!response.headersSent)
|
|
856
843
|
response.writeHead(status, pass).end(out); });
|
|
857
844
|
});
|
|
@@ -906,7 +893,7 @@ export async function startFlexibleRelay(store, input) {
|
|
|
906
893
|
}
|
|
907
894
|
if (out === "")
|
|
908
895
|
return;
|
|
909
|
-
if (!authorizedNow(store, grant.digest, turn)) {
|
|
896
|
+
if (!authorizedNow(store, grant.digest, turn, person, epoch)) {
|
|
910
897
|
lapsed();
|
|
911
898
|
return;
|
|
912
899
|
}
|
|
@@ -921,7 +908,7 @@ export async function startFlexibleRelay(store, input) {
|
|
|
921
908
|
events += rest;
|
|
922
909
|
const out = streamed ? takeEvents(true) ?? "" : sanitizeWhole(held + rest, secrets);
|
|
923
910
|
const read = meter.finish();
|
|
924
|
-
if (!authorizedNow(store, grant.digest, turn)) {
|
|
911
|
+
if (!authorizedNow(store, grant.digest, turn, person, epoch)) {
|
|
925
912
|
lapsed();
|
|
926
913
|
return;
|
|
927
914
|
}
|
|
@@ -951,6 +938,8 @@ export async function startFlexibleRelay(store, input) {
|
|
|
951
938
|
cut(call, "this thread's agent was stopped");
|
|
952
939
|
else if (cancel.digest !== undefined && cancel.digest === call.digest)
|
|
953
940
|
cut(call, "its relay token was revoked");
|
|
941
|
+
else if (cancel.person !== undefined && cancel.person === call.person)
|
|
942
|
+
cut(call, "its Claude sign-in for threads was removed or ended");
|
|
954
943
|
}
|
|
955
944
|
if (turnEnded !== undefined)
|
|
956
945
|
queueMicrotask(sweep);
|
|
@@ -966,6 +955,8 @@ export async function startFlexibleRelay(store, input) {
|
|
|
966
955
|
why = "this thread's agent was stopped";
|
|
967
956
|
else if (flexibleTurn(store, call.turn)?.status !== "running")
|
|
968
957
|
why = "the turn ended";
|
|
958
|
+
else if (!signInHoldsFor(store, { turn: call.turn, person: call.person, epoch: call.epoch }))
|
|
959
|
+
why = "its Claude sign-in for threads ended";
|
|
969
960
|
}
|
|
970
961
|
catch {
|
|
971
962
|
why = "Toolroll couldn't check its authority";
|