code60-transmission-server 0.0.0-stage → 0.1.0-staging.12
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/LICENSE +180 -0
- package/README.engine.md +463 -0
- package/README.md +376 -2
- package/dist/src/broker/filesystem.js +385 -0
- package/dist/src/broker/index.js +734 -0
- package/dist/src/broker/native/README.md +207 -0
- package/dist/src/broker/native/build.js +46 -0
- package/dist/src/broker/native/command-helper.c +93 -0
- package/dist/src/broker/native/fs-helper.c +529 -0
- package/dist/src/broker/native/git-helper.c +205 -0
- package/dist/src/broker/policy.js +149 -0
- package/dist/src/broker/startup-lock.js +14 -0
- package/dist/src/broker/types.js +11 -0
- package/dist/src/cli/configure.js +208 -0
- package/dist/src/cli/daemon.js +369 -0
- package/dist/src/cli/helpers.js +112 -0
- package/dist/src/cli/main.js +189 -0
- package/dist/src/cli/runtime-build.js +38 -0
- package/dist/src/config/coding-policy.js +4 -0
- package/dist/src/config/deployment.js +183 -0
- package/dist/src/config/documents.js +29 -0
- package/dist/src/config/profile-validation.js +129 -0
- package/dist/src/config/schema-graph.js +237 -0
- package/dist/src/config/schema-loader.js +185 -0
- package/dist/src/config/validation-pool.js +105 -0
- package/dist/src/config/validation-protocol.js +1 -0
- package/dist/src/config/validation-worker.js +106 -0
- package/dist/src/config/workflow-language.js +9 -0
- package/dist/src/config/workflow-schema.json +545 -0
- package/dist/src/config/workflow-types.js +1 -0
- package/dist/src/config/workflow-validation.js +95 -0
- package/dist/src/engine/budgets.js +50 -0
- package/dist/src/engine/clocks.js +27 -0
- package/dist/src/engine/commands.js +477 -0
- package/dist/src/engine/contracts.js +11 -0
- package/dist/src/engine/drain-state.js +31 -0
- package/dist/src/engine/effective-permissions.js +120 -0
- package/dist/src/engine/instruction-pins.js +205 -0
- package/dist/src/engine/retries.js +50 -0
- package/dist/src/engine/state.js +1 -0
- package/dist/src/engine/timing.js +23 -0
- package/dist/src/engine/tool-observations.js +87 -0
- package/dist/src/engine/workflow-engine.js +1862 -0
- package/dist/src/main.js +28 -0
- package/dist/src/mcp/catalog.js +71 -0
- package/dist/src/mcp/main.js +26 -0
- package/dist/src/mcp/server.js +177 -0
- package/dist/src/runtime/codex-app-server.js +91 -0
- package/dist/src/runtime/codex-executable.js +50 -0
- package/dist/src/runtime/containment.js +82 -0
- package/dist/src/runtime/engine-driver.js +221 -0
- package/dist/src/runtime/json-line-writer.js +192 -0
- package/dist/src/runtime/pinned-instruction-sources.js +24 -0
- package/dist/src/runtime/protocol-client.js +264 -0
- package/dist/src/runtime/protocol-pool.js +183 -0
- package/dist/src/runtime/protocol-projection.js +393 -0
- package/dist/src/runtime/protocol-types.js +1 -0
- package/dist/src/runtime/protocol-worker.js +18 -0
- package/dist/src/runtime/provider-bridge.js +290 -0
- package/dist/src/runtime/provider-credentials.js +41 -0
- package/dist/src/runtime/provider-transport.js +406 -0
- package/dist/src/runtime/runtime-broker.js +213 -0
- package/dist/src/runtime/workspace-instructions.js +120 -0
- package/dist/src/runtime/workspace-view.js +74 -0
- package/dist/src/server/api-contract.json +11629 -0
- package/dist/src/server/api-types.js +1 -0
- package/dist/src/server/application.js +44 -0
- package/dist/src/server/auth.js +67 -0
- package/dist/src/server/broker-handlers.js +242 -0
- package/dist/src/server/coding.js +281 -0
- package/dist/src/server/control-plane.js +50 -0
- package/dist/src/server/deployment.js +249 -0
- package/dist/src/server/errors.js +22 -0
- package/dist/src/server/history-handlers.js +127 -0
- package/dist/src/server/http.js +124 -0
- package/dist/src/server/paging.js +56 -0
- package/dist/src/server/publication.js +119 -0
- package/dist/src/server/tool-event-handler.js +77 -0
- package/dist/src/server/workspace-handlers.js +34 -0
- package/dist/src/storage/coordinator.js +224 -0
- package/dist/src/storage/startup-lock.js +71 -0
- package/dist/src/storage/store.js +167 -0
- package/dist/src/tools/check-worker.js +81 -0
- package/dist/src/tools/checks.js +117 -0
- package/dist/src/tools/command-check.js +34 -0
- package/dist/src/tools/commands.js +312 -0
- package/dist/src/tools/developer.js +353 -0
- package/dist/src/tools/dns.js +248 -0
- package/dist/src/tools/http-contract.js +38 -0
- package/dist/src/tools/http.js +358 -0
- package/dist/src/tools/index.js +194 -0
- package/dist/src/tools/worker-check.js +73 -0
- package/dist/src/workspaces/git.js +227 -0
- package/dist/src/workspaces/index.js +937 -0
- package/dist/src/workspaces/source.js +295 -0
- package/examples/deployment.local.json +22 -0
- package/package.json +71 -4
- package/scripts/postinstall.mjs +26 -0
|
@@ -0,0 +1,734 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { actionDigests, canonical, digest, evaluate, jsonCopy, normalizeResources, validatePolicy } from "./policy.js";
|
|
3
|
+
import { BrokerError } from "./types.js";
|
|
4
|
+
import { SqliteCoordinator } from "../storage/coordinator.js";
|
|
5
|
+
import { runSqlCommitHook } from "../engine/contracts.js";
|
|
6
|
+
export * from "./types.js";
|
|
7
|
+
export * from "./policy.js";
|
|
8
|
+
export const BROKER_MIGRATION = { id: "broker-v1", sql: `
|
|
9
|
+
CREATE TABLE IF NOT EXISTS broker_owner (singleton INTEGER PRIMARY KEY CHECK(singleton=1), owner TEXT NOT NULL);
|
|
10
|
+
CREATE TABLE IF NOT EXISTS broker_runs (id TEXT PRIMARY KEY, body TEXT NOT NULL);
|
|
11
|
+
CREATE TABLE IF NOT EXISTS broker_sessions (id TEXT PRIMARY KEY, body TEXT NOT NULL, fenced INTEGER NOT NULL DEFAULT 0);
|
|
12
|
+
CREATE TABLE IF NOT EXISTS broker_actions (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, epoch INTEGER NOT NULL,
|
|
13
|
+
client_id TEXT NOT NULL, request_digest TEXT NOT NULL, body TEXT NOT NULL, UNIQUE(session_id,epoch,client_id));
|
|
14
|
+
CREATE TABLE IF NOT EXISTS broker_approvals (id TEXT PRIMARY KEY, run_id TEXT NOT NULL, body TEXT NOT NULL);
|
|
15
|
+
CREATE TABLE IF NOT EXISTS broker_policy_audit (action_id TEXT PRIMARY KEY, body TEXT NOT NULL);
|
|
16
|
+
CREATE TABLE IF NOT EXISTS broker_dispatches (id TEXT PRIMARY KEY, action_id TEXT NOT NULL UNIQUE, state TEXT NOT NULL,
|
|
17
|
+
owner TEXT NOT NULL, body TEXT NOT NULL, result TEXT);
|
|
18
|
+
CREATE TABLE IF NOT EXISTS broker_receipts (scope TEXT NOT NULL, key TEXT NOT NULL, request_digest TEXT NOT NULL,
|
|
19
|
+
body TEXT NOT NULL, PRIMARY KEY(scope,key));
|
|
20
|
+
CREATE TABLE IF NOT EXISTS broker_work (run_id TEXT NOT NULL, id TEXT NOT NULL, state TEXT NOT NULL, PRIMARY KEY(run_id,id));
|
|
21
|
+
` };
|
|
22
|
+
/** One fenced ordering authority per database. Explicit recovery revokes the old
|
|
23
|
+
* authority, preserves active/uncertain work and closes dispatch behind a hold.
|
|
24
|
+
* No timer, model callback or SQL receipt by itself grants an execution right. */
|
|
25
|
+
export class ActionBroker {
|
|
26
|
+
db;
|
|
27
|
+
owner = randomUUID();
|
|
28
|
+
now;
|
|
29
|
+
timeout;
|
|
30
|
+
tools;
|
|
31
|
+
waiters = new Map();
|
|
32
|
+
invocations = new Map();
|
|
33
|
+
revision = 0;
|
|
34
|
+
closed = false;
|
|
35
|
+
coordinator;
|
|
36
|
+
admitToolSql;
|
|
37
|
+
onToolCompletedSql;
|
|
38
|
+
constructor(db, tools, options = {}) {
|
|
39
|
+
this.db = db;
|
|
40
|
+
this.coordinator = options.coordinator ?? new SqliteCoordinator(db);
|
|
41
|
+
if (this.coordinator.db !== db)
|
|
42
|
+
throw new BrokerError("coordinator_database_mismatch", 422);
|
|
43
|
+
this.coordinator.assertOutsideTransaction();
|
|
44
|
+
this.admitToolSql = options.admitToolSql;
|
|
45
|
+
this.onToolCompletedSql = options.onToolCompletedSql;
|
|
46
|
+
this.tools = new Map(tools);
|
|
47
|
+
this.now = options.now ?? Date.now;
|
|
48
|
+
this.timeout = options.approvalTimeoutMs ?? 86_400_000;
|
|
49
|
+
if (!Number.isFinite(this.timeout) || this.timeout <= 0)
|
|
50
|
+
throw new BrokerError("invalid_approval_timeout", 422);
|
|
51
|
+
for (const [name, tool] of this.tools) {
|
|
52
|
+
if (tool.name !== name)
|
|
53
|
+
throw new BrokerError("tool_registry_mismatch", 422);
|
|
54
|
+
}
|
|
55
|
+
if (!options.coordinator) {
|
|
56
|
+
db.exec("PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;");
|
|
57
|
+
this.coordinator.migrate([BROKER_MIGRATION]);
|
|
58
|
+
}
|
|
59
|
+
this.coordinator.atomic(() => {
|
|
60
|
+
const previous = this.get("SELECT owner FROM broker_owner WHERE singleton=1");
|
|
61
|
+
if (previous?.owner && !options.recover)
|
|
62
|
+
throw new BrokerError("coordinator_already_owned");
|
|
63
|
+
db.prepare("INSERT INTO broker_owner VALUES (1,?) ON CONFLICT(singleton) DO UPDATE SET owner=excluded.owner").run(this.owner);
|
|
64
|
+
db.prepare("UPDATE broker_dispatches SET state='uncertain' WHERE state IN ('claimed','started')").run();
|
|
65
|
+
if (options.recover) {
|
|
66
|
+
db.prepare("UPDATE broker_work SET state='uncertain'").run();
|
|
67
|
+
db.prepare("UPDATE broker_sessions SET fenced=1").run();
|
|
68
|
+
for (const row of this.rows("SELECT body FROM broker_actions")) {
|
|
69
|
+
this.invalidate(JSON.parse(String(row.body)), "invalidated");
|
|
70
|
+
}
|
|
71
|
+
for (const row of this.rows("SELECT id,body FROM broker_runs")) {
|
|
72
|
+
const gate = JSON.parse(String(row.body));
|
|
73
|
+
gate.holds = [...new Set([...gate.holds, "recovery"])];
|
|
74
|
+
this.write("broker_runs", String(row.id), gate);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
get(sql, ...args) {
|
|
80
|
+
return this.db.prepare(sql).get(...args);
|
|
81
|
+
}
|
|
82
|
+
rows(sql, ...args) {
|
|
83
|
+
return this.db.prepare(sql).all(...args);
|
|
84
|
+
}
|
|
85
|
+
read(table, id) {
|
|
86
|
+
const row = this.get(`SELECT body FROM ${table} WHERE id=?`, id);
|
|
87
|
+
if (!row)
|
|
88
|
+
throw new BrokerError("not_found", 404);
|
|
89
|
+
return JSON.parse(String(row.body));
|
|
90
|
+
}
|
|
91
|
+
approvalTimeout(gate) {
|
|
92
|
+
if (!Object.prototype.hasOwnProperty.call(gate, "approvalTimeoutMs"))
|
|
93
|
+
return this.timeout;
|
|
94
|
+
const timeout = gate.approvalTimeoutMs;
|
|
95
|
+
if (typeof timeout !== "number" || !Number.isFinite(timeout) || timeout <= 0)
|
|
96
|
+
throw new BrokerError("invalid_approval_timeout", 422);
|
|
97
|
+
return timeout;
|
|
98
|
+
}
|
|
99
|
+
write(table, id, value) {
|
|
100
|
+
this.db.prepare(`UPDATE ${table} SET body=? WHERE id=?`).run(canonical(value), id);
|
|
101
|
+
}
|
|
102
|
+
owned() {
|
|
103
|
+
if (this.closed || this.get("SELECT owner FROM broker_owner WHERE singleton=1")?.owner !== this.owner) {
|
|
104
|
+
throw new BrokerError("coordinator_fenced");
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
atomic(operation, lifecycleJoin = false, hooks = {}) {
|
|
108
|
+
if (!lifecycleJoin)
|
|
109
|
+
this.coordinator.assertOutsideTransaction();
|
|
110
|
+
this.owned();
|
|
111
|
+
let preserveHookError = false;
|
|
112
|
+
return this.coordinator.atomic(() => {
|
|
113
|
+
const before = this.get("SELECT total_changes() AS count").count;
|
|
114
|
+
this.owned();
|
|
115
|
+
let failed = false;
|
|
116
|
+
try {
|
|
117
|
+
return operation();
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
failed = true;
|
|
121
|
+
if (error instanceof BrokerError && error.persist && hooks.onCommittedErrorSql) {
|
|
122
|
+
// Only the error projection is reversible. Revoked authority outside
|
|
123
|
+
// this savepoint must survive an ordinary failing/replayed hook.
|
|
124
|
+
preserveHookError = true;
|
|
125
|
+
this.coordinator.savepoint(() => runSqlCommitHook(hooks.onCommittedErrorSql, { code: error.code, status: error.status }));
|
|
126
|
+
}
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
if (this.get("SELECT total_changes() AS count").count !== before) {
|
|
131
|
+
try {
|
|
132
|
+
this.coordinator.afterCommit(() => this.changed());
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
if (!failed)
|
|
136
|
+
throw error;
|
|
137
|
+
} // Do not disguise a fatal undo failure or replay sentinel.
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}, { commitOnError: error => preserveHookError || (error instanceof BrokerError && error.persist) });
|
|
141
|
+
}
|
|
142
|
+
admitted(hooks, receipt) {
|
|
143
|
+
runSqlCommitHook(hooks.onAdmittedSql, receipt.value);
|
|
144
|
+
return receipt;
|
|
145
|
+
}
|
|
146
|
+
admitTool(binding, preflight = false) {
|
|
147
|
+
if (!this.admitToolSql)
|
|
148
|
+
return;
|
|
149
|
+
const check = () => runSqlCommitHook(this.admitToolSql, Object.freeze(jsonCopy(this.session(binding))));
|
|
150
|
+
if (preflight)
|
|
151
|
+
this.atomic(check);
|
|
152
|
+
else
|
|
153
|
+
check();
|
|
154
|
+
}
|
|
155
|
+
changed() {
|
|
156
|
+
this.revision++;
|
|
157
|
+
for (const group of this.waiters.values())
|
|
158
|
+
for (const wake of group)
|
|
159
|
+
wake();
|
|
160
|
+
this.waiters.clear();
|
|
161
|
+
}
|
|
162
|
+
wait(runId, revision, expiresAt) {
|
|
163
|
+
if (revision !== this.revision)
|
|
164
|
+
return Promise.resolve();
|
|
165
|
+
return new Promise(resolve => {
|
|
166
|
+
const group = this.waiters.get(runId) ?? new Set();
|
|
167
|
+
const wake = () => { clearTimeout(timer); group.delete(wake); resolve(); };
|
|
168
|
+
const timer = setTimeout(wake, Math.max(1, Math.min(2_147_483_647, expiresAt - this.now())));
|
|
169
|
+
group.add(wake);
|
|
170
|
+
this.waiters.set(runId, group);
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
replay(scope, key, request) {
|
|
174
|
+
if (!key || key.length > 200)
|
|
175
|
+
throw new BrokerError("invalid_idempotency_key", 400);
|
|
176
|
+
const row = this.get("SELECT * FROM broker_receipts WHERE scope=? AND key=?", scope, key);
|
|
177
|
+
if (!row)
|
|
178
|
+
return undefined;
|
|
179
|
+
if (row.request_digest !== digest(request))
|
|
180
|
+
throw new BrokerError("idempotency_conflict");
|
|
181
|
+
return { value: JSON.parse(String(row.body)), replay: true };
|
|
182
|
+
}
|
|
183
|
+
receipt(scope, key, request, value) {
|
|
184
|
+
this.db.prepare("INSERT INTO broker_receipts VALUES (?,?,?,?)").run(scope, key, digest(request), canonical(value));
|
|
185
|
+
return { value: jsonCopy(value), replay: false };
|
|
186
|
+
}
|
|
187
|
+
session(binding) {
|
|
188
|
+
const row = this.get("SELECT * FROM broker_sessions WHERE id=?", binding.sessionId);
|
|
189
|
+
if (!row || row.fenced)
|
|
190
|
+
throw new BrokerError("stale_epoch");
|
|
191
|
+
const actual = JSON.parse(String(row.body));
|
|
192
|
+
for (const key of ["runId", "stepExecutionId", "sessionId", "epoch", "profileVersionId", "role"]) {
|
|
193
|
+
if (actual[key] !== binding[key])
|
|
194
|
+
throw new BrokerError("stale_epoch");
|
|
195
|
+
}
|
|
196
|
+
return actual;
|
|
197
|
+
}
|
|
198
|
+
registerSession(binding, deadlineAt = null) {
|
|
199
|
+
const copy = jsonCopy(binding);
|
|
200
|
+
if (!Number.isInteger(copy.epoch) || copy.epoch < 1 || !copy.sessionId || !copy.runId ||
|
|
201
|
+
!copy.stepExecutionId || !copy.profileVersionId || !["worker", "verifier", "handoff"].includes(copy.role) ||
|
|
202
|
+
copy.configuredTools.some(t => !this.tools.has(t)))
|
|
203
|
+
throw new BrokerError("unsupported_session", 422);
|
|
204
|
+
validatePolicy(copy.permissions);
|
|
205
|
+
validatePolicy(copy.deploymentPermissions);
|
|
206
|
+
if (deadlineAt !== null && !Number.isFinite(deadlineAt))
|
|
207
|
+
throw new BrokerError("invalid_deadline", 422);
|
|
208
|
+
this.atomic(() => {
|
|
209
|
+
const old = this.get("SELECT body,fenced FROM broker_sessions WHERE id=?", copy.sessionId);
|
|
210
|
+
if (old) {
|
|
211
|
+
if (old.fenced)
|
|
212
|
+
throw new BrokerError("stale_epoch");
|
|
213
|
+
if (String(old.body) !== canonical(copy))
|
|
214
|
+
throw new BrokerError("session_binding_conflict");
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
this.db.prepare("INSERT OR IGNORE INTO broker_runs VALUES (?,?)").run(copy.runId, canonical({ operatorPaused: false, cancelled: false, holds: [], deadlineAt }));
|
|
218
|
+
this.db.prepare("INSERT INTO broker_sessions(id,body) VALUES (?,?)").run(copy.sessionId, canonical(copy));
|
|
219
|
+
}, true);
|
|
220
|
+
}
|
|
221
|
+
setDeploymentPolicy(binding, policy) {
|
|
222
|
+
validatePolicy(policy);
|
|
223
|
+
this.atomic(() => { const current = this.session(binding); current.deploymentPermissions = jsonCopy(policy); this.write("broker_sessions", binding.sessionId, current); });
|
|
224
|
+
}
|
|
225
|
+
invalidate(action, state) {
|
|
226
|
+
if (["consumed", "denied", "expired", "invalidated"].includes(action.state))
|
|
227
|
+
return;
|
|
228
|
+
action.state = state;
|
|
229
|
+
action.version++;
|
|
230
|
+
this.write("broker_actions", action.id, action);
|
|
231
|
+
if (action.approvalId) {
|
|
232
|
+
const approval = this.read("broker_approvals", action.approvalId);
|
|
233
|
+
approval.state = state;
|
|
234
|
+
approval.version++;
|
|
235
|
+
this.write("broker_approvals", approval.id, approval);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
expire(runId) {
|
|
239
|
+
for (const row of this.rows("SELECT body FROM broker_actions")) {
|
|
240
|
+
const action = JSON.parse(String(row.body));
|
|
241
|
+
if (action.runId === runId && action.expiresAt <= this.now())
|
|
242
|
+
this.invalidate(action, "expired");
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
action(binding, id) {
|
|
246
|
+
this.owned();
|
|
247
|
+
this.session(binding);
|
|
248
|
+
return this.atomic(() => {
|
|
249
|
+
const action = this.read("broker_actions", id);
|
|
250
|
+
if (action.sessionId !== binding.sessionId || action.epoch !== binding.epoch)
|
|
251
|
+
throw new BrokerError("action_scope", 403);
|
|
252
|
+
this.expire(binding.runId);
|
|
253
|
+
return this.read("broker_actions", id);
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
approval(id) { this.owned(); return this.read("broker_approvals", id); }
|
|
257
|
+
snapshotInner(runId) {
|
|
258
|
+
const gate = this.read("broker_runs", runId);
|
|
259
|
+
const pendingApprovalIds = this.rows("SELECT id,body FROM broker_approvals WHERE run_id=?", runId)
|
|
260
|
+
.filter(r => JSON.parse(String(r.body)).state === "pending").map(r => String(r.id)).sort();
|
|
261
|
+
const activeWorkIds = this.rows("SELECT id FROM broker_work WHERE run_id=?", runId).map(r => String(r.id)).sort();
|
|
262
|
+
return { operatorPaused: gate.operatorPaused, cancelled: gate.cancelled, holds: gate.holds,
|
|
263
|
+
pendingApprovalIds, activeWorkIds,
|
|
264
|
+
pauseState: !gate.operatorPaused ? "running" : activeWorkIds.length ? "pausing" : "paused",
|
|
265
|
+
approvalState: !pendingApprovalIds.length ? "none" : activeWorkIds.length ? "draining" : "waiting" };
|
|
266
|
+
}
|
|
267
|
+
snapshot(runId) {
|
|
268
|
+
return this.atomic(() => { this.expire(runId); return this.snapshotInner(runId); });
|
|
269
|
+
}
|
|
270
|
+
gate(runId, allowApprovalWait = false) {
|
|
271
|
+
this.expire(runId);
|
|
272
|
+
const state = this.read("broker_runs", runId);
|
|
273
|
+
const snapshot = this.snapshotInner(runId);
|
|
274
|
+
if (state.cancelled)
|
|
275
|
+
throw new BrokerError("cancelled");
|
|
276
|
+
if (state.deadlineAt !== null && state.deadlineAt <= this.now())
|
|
277
|
+
throw new BrokerError("deadline_expired");
|
|
278
|
+
if (state.operatorPaused || state.holds.length || (!allowApprovalWait && snapshot.pendingApprovalIds.length)) {
|
|
279
|
+
throw new BrokerError("execution_held");
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
changeGate(runId, change) {
|
|
283
|
+
return this.atomic(() => {
|
|
284
|
+
const state = this.read("broker_runs", runId);
|
|
285
|
+
change(state);
|
|
286
|
+
this.write("broker_runs", runId, state);
|
|
287
|
+
return this.snapshotInner(runId);
|
|
288
|
+
}, true);
|
|
289
|
+
}
|
|
290
|
+
pause(runId) { return this.changeGate(runId, s => { s.operatorPaused = true; }); }
|
|
291
|
+
resume(runId) { return this.changeGate(runId, s => { s.operatorPaused = false; }); }
|
|
292
|
+
setHold(runId, name, held) {
|
|
293
|
+
if (!name)
|
|
294
|
+
throw new BrokerError("invalid_hold", 400);
|
|
295
|
+
return this.changeGate(runId, s => { s.holds = held ? [...new Set([...s.holds, name])].sort() : s.holds.filter(h => h !== name); });
|
|
296
|
+
}
|
|
297
|
+
cancel(runId) {
|
|
298
|
+
return this.atomic(() => {
|
|
299
|
+
const state = this.read("broker_runs", runId);
|
|
300
|
+
state.cancelled = true;
|
|
301
|
+
this.write("broker_runs", runId, state);
|
|
302
|
+
for (const row of this.rows("SELECT body FROM broker_actions")) {
|
|
303
|
+
const action = JSON.parse(String(row.body));
|
|
304
|
+
if (action.runId === runId)
|
|
305
|
+
this.invalidate(action, "invalidated");
|
|
306
|
+
}
|
|
307
|
+
return this.snapshotInner(runId);
|
|
308
|
+
}, true);
|
|
309
|
+
}
|
|
310
|
+
invalidateSessionActions(binding) {
|
|
311
|
+
this.atomic(() => {
|
|
312
|
+
this.session(binding);
|
|
313
|
+
for (const row of this.rows("SELECT body FROM broker_actions WHERE session_id=? AND epoch=?", binding.sessionId, binding.epoch)) {
|
|
314
|
+
const action = JSON.parse(String(row.body));
|
|
315
|
+
if (["pending_approval", "allowed", "approved"].includes(action.state))
|
|
316
|
+
this.invalidate(action, "invalidated");
|
|
317
|
+
}
|
|
318
|
+
}, true);
|
|
319
|
+
}
|
|
320
|
+
fenceSession(binding) {
|
|
321
|
+
this.atomic(() => {
|
|
322
|
+
this.session(binding);
|
|
323
|
+
this.db.prepare("UPDATE broker_sessions SET fenced=1 WHERE id=?").run(binding.sessionId);
|
|
324
|
+
for (const row of this.rows("SELECT body FROM broker_actions WHERE session_id=?", binding.sessionId)) {
|
|
325
|
+
this.invalidate(JSON.parse(String(row.body)), "invalidated");
|
|
326
|
+
}
|
|
327
|
+
}, true);
|
|
328
|
+
}
|
|
329
|
+
beginWork(runId, id, binding) {
|
|
330
|
+
this.atomic(() => {
|
|
331
|
+
if (binding) {
|
|
332
|
+
this.session(binding);
|
|
333
|
+
if (binding.runId !== runId)
|
|
334
|
+
throw new BrokerError("work_scope", 403);
|
|
335
|
+
}
|
|
336
|
+
this.gate(runId);
|
|
337
|
+
if (binding)
|
|
338
|
+
this.admitTool(binding);
|
|
339
|
+
this.db.prepare("INSERT INTO broker_work VALUES (?,?,'active')").run(runId, `external:${id}`);
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
endWork(runId, id) {
|
|
343
|
+
this.atomic(() => { this.db.prepare("DELETE FROM broker_work WHERE run_id=? AND id=? AND state='active'").run(runId, `external:${id}`); }, true);
|
|
344
|
+
}
|
|
345
|
+
async prepare(toolId, args, binding) {
|
|
346
|
+
this.coordinator.assertOutsideTransaction();
|
|
347
|
+
const tool = this.tools.get(toolId);
|
|
348
|
+
if (!tool)
|
|
349
|
+
throw new BrokerError("unsupported_tool", 422);
|
|
350
|
+
return tool.prepare(jsonCopy(args), Object.freeze(jsonCopy(this.session(binding))));
|
|
351
|
+
}
|
|
352
|
+
async prepareExisting(binding, action, dispatchId, hooks = {}) {
|
|
353
|
+
try {
|
|
354
|
+
return await this.prepare(action.action.toolId, action.action.arguments, binding);
|
|
355
|
+
}
|
|
356
|
+
catch {
|
|
357
|
+
this.atomic(() => {
|
|
358
|
+
this.session(binding);
|
|
359
|
+
const current = this.read("broker_actions", action.id);
|
|
360
|
+
if (current.sessionId !== binding.sessionId || current.epoch !== binding.epoch ||
|
|
361
|
+
current.profileVersionId !== binding.profileVersionId)
|
|
362
|
+
throw new BrokerError("action_scope", 403);
|
|
363
|
+
if (dispatchId !== undefined) {
|
|
364
|
+
const row = this.get("SELECT * FROM broker_dispatches WHERE id=?", dispatchId);
|
|
365
|
+
if (!row || row.action_id !== current.id)
|
|
366
|
+
throw new BrokerError("dispatch_scope", 403);
|
|
367
|
+
const authorization = JSON.parse(String(row.body));
|
|
368
|
+
if (authorization.sessionId !== binding.sessionId || authorization.epoch !== binding.epoch) {
|
|
369
|
+
throw new BrokerError("dispatch_scope", 403);
|
|
370
|
+
}
|
|
371
|
+
if (row.state === "claimed" && row.owner === this.owner) {
|
|
372
|
+
this.db.prepare("UPDATE broker_dispatches SET state='invalidated' WHERE id=?").run(dispatchId);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
else
|
|
376
|
+
this.invalidate(current, "invalidated");
|
|
377
|
+
throw new BrokerError("resource_changed", 409, true);
|
|
378
|
+
}, false, hooks);
|
|
379
|
+
throw new BrokerError("resource_changed");
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
async authorize(binding, input, key, hooks = {}) {
|
|
383
|
+
this.coordinator.assertOutsideTransaction();
|
|
384
|
+
if (Object.keys(input).some(k => !["clientActionId", "toolId", "arguments"].includes(k)) ||
|
|
385
|
+
!input.clientActionId || typeof input.arguments !== "object" || input.arguments === null || Array.isArray(input.arguments)) {
|
|
386
|
+
throw new BrokerError("untrusted_action_shape", 400);
|
|
387
|
+
}
|
|
388
|
+
const request = jsonCopy(input);
|
|
389
|
+
this.owned();
|
|
390
|
+
this.session(binding);
|
|
391
|
+
const scope = `authorize:${binding.sessionId}:${binding.epoch}`;
|
|
392
|
+
const prior = this.replay(scope, key, request);
|
|
393
|
+
if (prior)
|
|
394
|
+
return this.atomic(() => this.admitted(hooks, prior), false, hooks);
|
|
395
|
+
if (!this.tools.has(request.toolId))
|
|
396
|
+
throw new BrokerError("unsupported_tool", 422);
|
|
397
|
+
this.admitTool(binding, true);
|
|
398
|
+
// New authority validates trusted context before resource preparation.
|
|
399
|
+
// Existing client identity aliases retain their already-issued expiry.
|
|
400
|
+
if (!this.get("SELECT 1 FROM broker_actions WHERE session_id=? AND epoch=? AND client_id=?", binding.sessionId, binding.epoch, request.clientActionId))
|
|
401
|
+
this.approvalTimeout(this.read("broker_runs", binding.runId));
|
|
402
|
+
let prepared;
|
|
403
|
+
try {
|
|
404
|
+
prepared = await this.prepare(request.toolId, request.arguments, binding);
|
|
405
|
+
}
|
|
406
|
+
catch {
|
|
407
|
+
// Before actual-resource authority exists, failure details would reveal
|
|
408
|
+
// existence/type/permissions of a target the caller may not read.
|
|
409
|
+
// Record the same denial shape used for a resolved policy denial.
|
|
410
|
+
}
|
|
411
|
+
try {
|
|
412
|
+
return this.atomic(() => {
|
|
413
|
+
const actual = this.session(binding);
|
|
414
|
+
const replay = this.replay(scope, key, request);
|
|
415
|
+
if (replay)
|
|
416
|
+
return this.admitted(hooks, replay);
|
|
417
|
+
this.admitTool(actual);
|
|
418
|
+
const existing = this.get("SELECT * FROM broker_actions WHERE session_id=? AND epoch=? AND client_id=?", binding.sessionId, binding.epoch, request.clientActionId);
|
|
419
|
+
if (existing) {
|
|
420
|
+
if (existing.request_digest !== digest(request))
|
|
421
|
+
throw new BrokerError("client_action_conflict");
|
|
422
|
+
return this.admitted(hooks, this.receipt(scope, key, request, JSON.parse(String(existing.body))));
|
|
423
|
+
}
|
|
424
|
+
this.gate(binding.runId, true);
|
|
425
|
+
const gate = this.read("broker_runs", binding.runId), timeout = this.approvalTimeout(gate);
|
|
426
|
+
let resolved = [];
|
|
427
|
+
let policyEffect = "deny";
|
|
428
|
+
let resolution = "failed";
|
|
429
|
+
if (prepared) {
|
|
430
|
+
try {
|
|
431
|
+
resolved = normalizeResources(prepared.revalidate());
|
|
432
|
+
if (digest(resolved) !== digest(normalizeResources(prepared.resources)))
|
|
433
|
+
throw new BrokerError("resource_changed");
|
|
434
|
+
policyEffect = evaluate(actual, request.toolId, resolved);
|
|
435
|
+
resolution = "resolved";
|
|
436
|
+
}
|
|
437
|
+
catch {
|
|
438
|
+
resolved = []; // No target-derived detail in adapter/model denial.
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
const resources = policyEffect === "deny" ? [] : resolved;
|
|
442
|
+
const action = {
|
|
443
|
+
id: randomUUID(), runId: binding.runId, stepExecutionId: binding.stepExecutionId,
|
|
444
|
+
sessionId: binding.sessionId, epoch: binding.epoch, profileVersionId: binding.profileVersionId,
|
|
445
|
+
clientActionId: request.clientActionId, action: { toolId: request.toolId, arguments: request.arguments, resources },
|
|
446
|
+
...actionDigests(actual, request.toolId, request.arguments, resources), policyEffect,
|
|
447
|
+
state: policyEffect === "deny" ? "denied" : policyEffect === "allow" ? "allowed" : "pending_approval",
|
|
448
|
+
version: 1, createdAt: this.now(), expiresAt: Math.min(this.now() + timeout, gate.deadlineAt ?? Infinity),
|
|
449
|
+
};
|
|
450
|
+
if (policyEffect === "require_approval") {
|
|
451
|
+
action.approvalId = randomUUID();
|
|
452
|
+
const approval = { id: action.approvalId, actionRequestId: action.id, runId: binding.runId,
|
|
453
|
+
state: "pending", version: 1, actionDigest: action.actionDigest };
|
|
454
|
+
this.db.prepare("INSERT INTO broker_approvals VALUES (?,?,?)").run(approval.id, binding.runId, canonical(approval));
|
|
455
|
+
}
|
|
456
|
+
this.db.prepare("INSERT INTO broker_actions VALUES (?,?,?,?,?,?)").run(action.id, binding.sessionId, binding.epoch, request.clientActionId, digest(request), canonical(action));
|
|
457
|
+
// Trusted operator audit is separate from the adapter-visible receipt.
|
|
458
|
+
// It must never be exposed through adapter action/claim/model responses.
|
|
459
|
+
this.db.prepare("INSERT INTO broker_policy_audit VALUES (?,?)").run(action.id, canonical({ resources: resolved, resolution, policyEffect }));
|
|
460
|
+
return this.admitted(hooks, this.receipt(scope, key, request, action));
|
|
461
|
+
}, false, hooks);
|
|
462
|
+
}
|
|
463
|
+
finally {
|
|
464
|
+
prepared?.dispose?.();
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
decide(id, input, hooks = {}) {
|
|
468
|
+
const scope = `decision:${input.actor}:${id}`;
|
|
469
|
+
const { expectedVersion: _etag, idempotencyKey: key, ...request } = input;
|
|
470
|
+
return this.atomic(() => {
|
|
471
|
+
const replay = this.replay(scope, key, request);
|
|
472
|
+
if (replay)
|
|
473
|
+
return this.admitted(hooks, replay);
|
|
474
|
+
const approval = this.read("broker_approvals", id);
|
|
475
|
+
this.expire(approval.runId);
|
|
476
|
+
const current = this.read("broker_approvals", id);
|
|
477
|
+
if (input.expectedVersion === undefined)
|
|
478
|
+
throw new BrokerError("precondition_required", 428);
|
|
479
|
+
if (current.version !== input.expectedVersion)
|
|
480
|
+
throw new BrokerError("precondition_failed", 412);
|
|
481
|
+
if (!input.actor || !["approve", "deny"].includes(input.decision) || current.state !== "pending" ||
|
|
482
|
+
current.actionDigest !== input.actionDigest)
|
|
483
|
+
throw new BrokerError("stale_approval");
|
|
484
|
+
const action = this.read("broker_actions", current.actionRequestId);
|
|
485
|
+
const binding = this.read("broker_sessions", action.sessionId);
|
|
486
|
+
this.session(binding);
|
|
487
|
+
const effect = evaluate(binding, action.action.toolId, action.action.resources);
|
|
488
|
+
if (effect === "deny") {
|
|
489
|
+
this.invalidate(action, "invalidated");
|
|
490
|
+
throw new BrokerError("policy_denied", 409, true);
|
|
491
|
+
}
|
|
492
|
+
current.state = input.decision === "approve" ? "approved" : "denied";
|
|
493
|
+
current.actor = input.actor;
|
|
494
|
+
current.version++;
|
|
495
|
+
action.state = current.state;
|
|
496
|
+
action.version++;
|
|
497
|
+
this.write("broker_approvals", id, current);
|
|
498
|
+
this.write("broker_actions", action.id, action);
|
|
499
|
+
return this.admitted(hooks, this.receipt(scope, key, request, current));
|
|
500
|
+
}, false, hooks);
|
|
501
|
+
}
|
|
502
|
+
async claim(binding, id, input, hooks = {}) {
|
|
503
|
+
this.coordinator.assertOutsideTransaction();
|
|
504
|
+
this.owned();
|
|
505
|
+
this.session(binding);
|
|
506
|
+
const scope = `claim:${binding.sessionId}:${binding.epoch}:${id}`;
|
|
507
|
+
const { expectedVersion: _etag, idempotencyKey: key, ...request } = input;
|
|
508
|
+
const prior = this.replay(scope, key, request);
|
|
509
|
+
if (prior)
|
|
510
|
+
return this.atomic(() => this.admitted(hooks, prior), false, hooks);
|
|
511
|
+
const action = this.action(binding, id);
|
|
512
|
+
// A denied/expired/consumed handle cannot trigger fresh resource probing.
|
|
513
|
+
// Besides having no authority, such probing would turn claim errors into
|
|
514
|
+
// another existence/type oracle for the uniformly denied action.
|
|
515
|
+
if (input.expectedVersion === undefined)
|
|
516
|
+
throw new BrokerError("precondition_required", 428);
|
|
517
|
+
if (action.version !== input.expectedVersion)
|
|
518
|
+
throw new BrokerError("precondition_failed", 412);
|
|
519
|
+
if (!["allowed", "approved"].includes(action.state))
|
|
520
|
+
throw new BrokerError("action_not_claimable");
|
|
521
|
+
this.admitTool(binding, true);
|
|
522
|
+
const prepared = await this.prepareExisting(binding, action, undefined, hooks);
|
|
523
|
+
try {
|
|
524
|
+
return this.atomic(() => {
|
|
525
|
+
const currentBinding = this.session(binding);
|
|
526
|
+
const replay = this.replay(scope, key, request);
|
|
527
|
+
if (replay)
|
|
528
|
+
return this.admitted(hooks, replay);
|
|
529
|
+
this.expire(binding.runId);
|
|
530
|
+
const current = this.read("broker_actions", id);
|
|
531
|
+
if (input.expectedVersion === undefined)
|
|
532
|
+
throw new BrokerError("precondition_required", 428);
|
|
533
|
+
if (current.version !== input.expectedVersion)
|
|
534
|
+
throw new BrokerError("precondition_failed", 412);
|
|
535
|
+
if (!["allowed", "approved"].includes(current.state))
|
|
536
|
+
throw new BrokerError("action_not_claimable");
|
|
537
|
+
this.admitTool(currentBinding);
|
|
538
|
+
this.checkActual(currentBinding, current, prepared, input);
|
|
539
|
+
this.gate(binding.runId);
|
|
540
|
+
const dispatch = { id: randomUUID(), actionRequestId: id, sessionId: binding.sessionId,
|
|
541
|
+
epoch: binding.epoch, profileVersionId: binding.profileVersionId,
|
|
542
|
+
actionDigest: current.actionDigest, resourceDigest: current.resourceDigest,
|
|
543
|
+
mode: "single_use", claimedAt: this.now(), expiresAt: current.expiresAt };
|
|
544
|
+
current.state = "consumed";
|
|
545
|
+
current.version++;
|
|
546
|
+
this.write("broker_actions", id, current);
|
|
547
|
+
if (current.approvalId) {
|
|
548
|
+
const approval = this.read("broker_approvals", current.approvalId);
|
|
549
|
+
approval.state = "consumed";
|
|
550
|
+
approval.version++;
|
|
551
|
+
this.write("broker_approvals", approval.id, approval);
|
|
552
|
+
}
|
|
553
|
+
this.db.prepare("INSERT INTO broker_dispatches VALUES (?,?, 'claimed',?,?,NULL)").run(dispatch.id, id, this.owner, canonical(dispatch));
|
|
554
|
+
return this.admitted(hooks, this.receipt(scope, key, request, dispatch));
|
|
555
|
+
}, false, hooks);
|
|
556
|
+
}
|
|
557
|
+
finally {
|
|
558
|
+
prepared.dispose?.();
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
checkActual(binding, action, prepared, expected) {
|
|
562
|
+
let resources;
|
|
563
|
+
try {
|
|
564
|
+
resources = normalizeResources(prepared.revalidate());
|
|
565
|
+
}
|
|
566
|
+
catch {
|
|
567
|
+
this.invalidate(action, "invalidated");
|
|
568
|
+
throw new BrokerError("resource_changed", 409, true);
|
|
569
|
+
}
|
|
570
|
+
const actual = actionDigests(binding, action.action.toolId, action.action.arguments, resources);
|
|
571
|
+
if (actual.actionDigest !== action.actionDigest || actual.resourceDigest !== action.resourceDigest ||
|
|
572
|
+
expected.actionDigest !== actual.actionDigest || expected.resourceDigest !== actual.resourceDigest) {
|
|
573
|
+
this.invalidate(action, "invalidated");
|
|
574
|
+
throw new BrokerError("resource_changed", 409, true);
|
|
575
|
+
}
|
|
576
|
+
const effect = evaluate(binding, action.action.toolId, resources);
|
|
577
|
+
if (effect === "deny" || (effect === "require_approval" && !action.approvalId)) {
|
|
578
|
+
this.invalidate(action, "invalidated");
|
|
579
|
+
throw new BrokerError("policy_changed", 409, true);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
async dispatch(binding, id) {
|
|
583
|
+
this.coordinator.assertOutsideTransaction();
|
|
584
|
+
this.owned();
|
|
585
|
+
this.session(binding);
|
|
586
|
+
const row = this.get("SELECT * FROM broker_dispatches WHERE id=?", id);
|
|
587
|
+
if (!row)
|
|
588
|
+
throw new BrokerError("not_found", 404);
|
|
589
|
+
const authorization = JSON.parse(String(row.body));
|
|
590
|
+
if (authorization.sessionId !== binding.sessionId || authorization.epoch !== binding.epoch)
|
|
591
|
+
throw new BrokerError("dispatch_scope", 403);
|
|
592
|
+
if (row.state !== "claimed" || row.owner !== this.owner)
|
|
593
|
+
throw new BrokerError("dispatch_not_reusable");
|
|
594
|
+
const action = this.action(binding, authorization.actionRequestId);
|
|
595
|
+
this.admitTool(binding, true);
|
|
596
|
+
const prepared = await this.prepareExisting(binding, action, id);
|
|
597
|
+
let effect;
|
|
598
|
+
try {
|
|
599
|
+
const admittedBinding = this.atomic(() => {
|
|
600
|
+
const current = this.session(binding);
|
|
601
|
+
const latest = this.get("SELECT * FROM broker_dispatches WHERE id=?", id);
|
|
602
|
+
if (latest?.state !== "claimed" || latest.owner !== this.owner)
|
|
603
|
+
throw new BrokerError("dispatch_not_reusable");
|
|
604
|
+
this.admitTool(current);
|
|
605
|
+
if (authorization.expiresAt <= this.now())
|
|
606
|
+
throw new BrokerError("action_expired");
|
|
607
|
+
this.gate(binding.runId);
|
|
608
|
+
this.checkActual(current, action, prepared, authorization);
|
|
609
|
+
this.db.prepare("UPDATE broker_dispatches SET state='started' WHERE id=?").run(id);
|
|
610
|
+
this.db.prepare("INSERT INTO broker_work VALUES (?,?,'active')").run(binding.runId, `effect:${id}`);
|
|
611
|
+
return current;
|
|
612
|
+
});
|
|
613
|
+
// No await/yield between committed active intent and invoking the protected effect.
|
|
614
|
+
// A reentrant pause inside execute sees active work and can only enter draining.
|
|
615
|
+
this.coordinator.assertOutsideTransaction();
|
|
616
|
+
effect = prepared.execute(id);
|
|
617
|
+
const result = jsonCopy(await effect);
|
|
618
|
+
if (typeof result.success !== "boolean" || typeof result.text !== "string")
|
|
619
|
+
throw new BrokerError("invalid_tool_result", 500);
|
|
620
|
+
// A completion projection failure must roll back even if its error
|
|
621
|
+
// carries the broker's authority-invalidation persist marker.
|
|
622
|
+
this.atomic(() => this.coordinator.atomic(() => {
|
|
623
|
+
this.db.prepare("UPDATE broker_dispatches SET state='completed',result=? WHERE id=?").run(canonical(result), id);
|
|
624
|
+
if (this.onToolCompletedSql)
|
|
625
|
+
runSqlCommitHook(this.onToolCompletedSql, Object.freeze({
|
|
626
|
+
binding: jsonCopy(admittedBinding), dispatch: { ...authorization }, result: { ...result },
|
|
627
|
+
}));
|
|
628
|
+
this.db.prepare("DELETE FROM broker_work WHERE run_id=? AND id=?").run(binding.runId, `effect:${id}`);
|
|
629
|
+
}));
|
|
630
|
+
return result;
|
|
631
|
+
}
|
|
632
|
+
catch (error) {
|
|
633
|
+
// Errors after execute may follow a partial effect. Never retry this identity.
|
|
634
|
+
if (this.get("SELECT owner FROM broker_owner WHERE singleton=1")?.owner === this.owner &&
|
|
635
|
+
this.get("SELECT state FROM broker_dispatches WHERE id=?", id)?.state === "started") {
|
|
636
|
+
this.atomic(() => {
|
|
637
|
+
this.db.prepare("UPDATE broker_dispatches SET state='uncertain' WHERE id=?").run(id);
|
|
638
|
+
this.db.prepare("UPDATE broker_work SET state='uncertain' WHERE run_id=? AND id=?").run(binding.runId, `effect:${id}`);
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
else if (error instanceof BrokerError && ["resource_changed", "policy_changed", "action_expired"].includes(error.code) &&
|
|
642
|
+
this.get("SELECT owner FROM broker_owner WHERE singleton=1")?.owner === this.owner) {
|
|
643
|
+
this.atomic(() => {
|
|
644
|
+
this.db.prepare("UPDATE broker_dispatches SET state='invalidated' WHERE id=? AND state='claimed'").run(id);
|
|
645
|
+
});
|
|
646
|
+
}
|
|
647
|
+
throw error;
|
|
648
|
+
}
|
|
649
|
+
finally {
|
|
650
|
+
prepared.dispose?.();
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
bind(binding) {
|
|
654
|
+
const bound = jsonCopy(binding);
|
|
655
|
+
this.owned();
|
|
656
|
+
this.session(bound);
|
|
657
|
+
const catalog = Object.freeze(bound.configuredTools.map(name => {
|
|
658
|
+
const tool = this.tools.get(name);
|
|
659
|
+
return Object.freeze({ name, description: tool.description, inputSchema: jsonCopy(tool.inputSchema) });
|
|
660
|
+
}));
|
|
661
|
+
return Object.freeze({
|
|
662
|
+
catalog,
|
|
663
|
+
invoke: (input) => this.invoke(bound, input),
|
|
664
|
+
pause: () => this.pause(bound.runId), resume: () => this.resume(bound.runId),
|
|
665
|
+
cancel: () => this.cancel(bound.runId), snapshot: () => this.snapshot(bound.runId),
|
|
666
|
+
setHold: (name, held) => this.setHold(bound.runId, name, held),
|
|
667
|
+
beginWork: (id) => this.beginWork(bound.runId, `${bound.sessionId}:${bound.epoch}:${id}`, bound),
|
|
668
|
+
endWork: (id) => this.endWork(bound.runId, `${bound.sessionId}:${bound.epoch}:${id}`),
|
|
669
|
+
});
|
|
670
|
+
}
|
|
671
|
+
invoke(binding, input) {
|
|
672
|
+
this.coordinator.assertOutsideTransaction();
|
|
673
|
+
this.owned();
|
|
674
|
+
this.session(binding);
|
|
675
|
+
const request = digest({ toolName: input.toolName, arguments: input.arguments });
|
|
676
|
+
const key = `${binding.sessionId}:${binding.epoch}:${input.invocationId}`;
|
|
677
|
+
const running = this.invocations.get(key);
|
|
678
|
+
if (running) {
|
|
679
|
+
if (running.request !== request)
|
|
680
|
+
return Promise.reject(new BrokerError("client_action_conflict"));
|
|
681
|
+
return running.promise;
|
|
682
|
+
}
|
|
683
|
+
const promise = this.performInvoke(binding, input);
|
|
684
|
+
const entry = { request, promise };
|
|
685
|
+
this.invocations.set(key, entry);
|
|
686
|
+
const settled = () => {
|
|
687
|
+
if (this.invocations.get(key) === entry)
|
|
688
|
+
this.invocations.delete(key);
|
|
689
|
+
};
|
|
690
|
+
void promise.then(settled, settled);
|
|
691
|
+
return promise;
|
|
692
|
+
}
|
|
693
|
+
async performInvoke(binding, input) {
|
|
694
|
+
try {
|
|
695
|
+
const receipt = await this.authorize(binding, { clientActionId: input.invocationId,
|
|
696
|
+
toolId: input.toolName, arguments: jsonCopy(input.arguments) }, `invoke:${input.invocationId}`);
|
|
697
|
+
for (;;) {
|
|
698
|
+
const action = this.action(binding, receipt.value.id);
|
|
699
|
+
if (["denied", "expired", "invalidated"].includes(action.state))
|
|
700
|
+
return { success: false, text: `broker:${action.state}` };
|
|
701
|
+
if (action.state === "consumed") {
|
|
702
|
+
const row = this.get("SELECT state,result FROM broker_dispatches WHERE action_id=?", action.id);
|
|
703
|
+
return row?.state === "completed" && row.result ? JSON.parse(String(row.result)) :
|
|
704
|
+
{ success: false, text: "broker:consumed_effect_requires_reconciliation" };
|
|
705
|
+
}
|
|
706
|
+
const snapshot = this.snapshot(binding.runId);
|
|
707
|
+
if (snapshot.cancelled)
|
|
708
|
+
return { success: false, text: "broker:cancelled" };
|
|
709
|
+
if (action.state !== "pending_approval" && !snapshot.operatorPaused && !snapshot.holds.length && !snapshot.pendingApprovalIds.length) {
|
|
710
|
+
const claim = await this.claim(binding, action.id, { idempotencyKey: `invoke:${input.invocationId}`,
|
|
711
|
+
expectedVersion: action.version, actionDigest: action.actionDigest, resourceDigest: action.resourceDigest });
|
|
712
|
+
return await this.dispatch(binding, claim.value.id);
|
|
713
|
+
}
|
|
714
|
+
const revision = this.revision;
|
|
715
|
+
await this.wait(binding.runId, revision, action.expiresAt);
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
catch (error) {
|
|
719
|
+
if (error instanceof BrokerError && error.code !== "idempotency_conflict" && error.code !== "client_action_conflict") {
|
|
720
|
+
return { success: false, text: `broker:${error.code}` };
|
|
721
|
+
}
|
|
722
|
+
throw error;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
close() {
|
|
726
|
+
this.atomic(() => {
|
|
727
|
+
if (this.rows("SELECT id FROM broker_work").length)
|
|
728
|
+
throw new BrokerError("active_work_requires_reconciliation");
|
|
729
|
+
this.db.prepare("UPDATE broker_owner SET owner='' WHERE singleton=1 AND owner=?").run(this.owner);
|
|
730
|
+
});
|
|
731
|
+
this.closed = true;
|
|
732
|
+
this.changed();
|
|
733
|
+
}
|
|
734
|
+
}
|