pi-braid 0.40.6 → 0.41.1
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/README.md +13 -1
- package/build-info.json +4 -4
- package/docs/CONTEXT-MAP.md +1 -1
- package/docs/FLEET.md +134 -0
- package/package.json +5 -1
- package/scripts/fleet/cli.mjs +540 -0
- package/scripts/fleet/driver-rpc.mjs +376 -0
- package/scripts/fleet/driver-scripted.mjs +239 -0
- package/scripts/fleet/journal.mjs +1124 -0
- package/scripts/fleet/procs.mjs +76 -0
- package/scripts/fleet/supervisor.mjs +1649 -0
- package/scripts/fleet/tool-guard.mjs +467 -0
- package/skills/release-pipeline/SKILL.md +20 -4
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The fleet's pre-execution duplication guard.
|
|
3
|
+
*
|
|
4
|
+
* Loaded as a pi extension inside every node's child, it refuses a tool call
|
|
5
|
+
* whose effect the node's journal already recorded on an earlier turn of the
|
|
6
|
+
* run it is resuming, before the tool runs. That is the difference between a
|
|
7
|
+
* promise and an executor: a resumed turn can be talked into repeating work,
|
|
8
|
+
* but a tool call it re-issues cannot reach the world.
|
|
9
|
+
*
|
|
10
|
+
* The identity is (node_id, tool_name, canonical arguments) and it contains no
|
|
11
|
+
* turn id on purpose. `effectKey` in journal.mjs hashes the turn, so it changes
|
|
12
|
+
* on every resume by construction and can only ever match within one turn; this
|
|
13
|
+
* key is the one that survives a crash. The turn id is not in it, and the
|
|
14
|
+
* current turn is excluded from the history it is compared against, so a node
|
|
15
|
+
* that runs the same command twice inside one turn is doing work and is left
|
|
16
|
+
* alone.
|
|
17
|
+
*
|
|
18
|
+
* The history it is compared against is the recovery window, not the project's
|
|
19
|
+
* lifetime. A fleet root outlives every turn (`<cwd>/.fleet` by default), so a
|
|
20
|
+
* filter that read "an earlier turn" as "any earlier turn" made every effect a
|
|
21
|
+
* node had ever recorded permanent: one `ls -la` in the project's past blocked
|
|
22
|
+
* that command for the rest of the project's life, and `replayPolicy("bash")`
|
|
23
|
+
* is `never`, so every shell command a node had completed became unrunnable -
|
|
24
|
+
* the inspection commands a resumed turn needs first of all. The hazard this
|
|
25
|
+
* module exists for is narrow, and the window is now the same width: the
|
|
26
|
+
* current turn, plus every turn back to the last one that ended normally. That
|
|
27
|
+
* is the recovery chain - the turns of this unfinished run. A turn that ended
|
|
28
|
+
* normally (`settled`, `parked`, `done`) finished the work it was started for,
|
|
29
|
+
* so its effects are finished business: a later turn that repeats one is doing
|
|
30
|
+
* new work, and no crash can have left it half applied. An `interrupted` or
|
|
31
|
+
* `failed` turn, and a turn still `in_progress`, did not finish; its effects
|
|
32
|
+
* are what a resumed turn is at risk of re-issuing without knowing.
|
|
33
|
+
*
|
|
34
|
+
* Inside that window a row is history only if it may have reached the world:
|
|
35
|
+
* `completed` with `is_error = 0`, or `unknown`, which is the crash residue
|
|
36
|
+
* where the tool started and never reported. A call that threw applied
|
|
37
|
+
* nothing, so refusing its retry refused work that never happened. `attempted`
|
|
38
|
+
* is a call still in flight and `blocked` is one this guard refused; neither
|
|
39
|
+
* is history.
|
|
40
|
+
*
|
|
41
|
+
* "Canonical arguments" is not a string compare, because the two sides of it
|
|
42
|
+
* are two views of one tool call. The journal row was written from the RPC
|
|
43
|
+
* stream's `tool_execution_start` args, which are the model's raw arguments;
|
|
44
|
+
* this hook is handed the tool's own view of the same call. Measured for every
|
|
45
|
+
* shipped tool at pi 1.4.0: explicit nulls appear on one side and not the
|
|
46
|
+
* other (`{"command":"x","timeout":null}` against `{"command":"x"}`), the
|
|
47
|
+
* edit tool rewrites a legacy `{oldText,newText}` pair into
|
|
48
|
+
* `{edits:[{oldText,newText}]}` before the hook runs, a scalar the model typed
|
|
49
|
+
* as a string arrives as the tool's validated type (`timeout: "30"` recorded,
|
|
50
|
+
* `timeout: 30` handed to the hook), and `edits` sent as a JSON string arrives
|
|
51
|
+
* as the parsed array. So a call matches a recorded row when every argument it
|
|
52
|
+
* carries agrees with that row and unset fields are ignored, with those three
|
|
53
|
+
* dialects folded on both sides.
|
|
54
|
+
*
|
|
55
|
+
* Reads are never refused: `replayPolicy` in journal.mjs is the single policy
|
|
56
|
+
* table, and a call it calls `safe` runs again however often it is issued.
|
|
57
|
+
*
|
|
58
|
+
* Environment contract, and the reason it is env: the child inherits nothing
|
|
59
|
+
* else reliably. All three identifiers are required, and the guard is a
|
|
60
|
+
* complete no-op without them, so this module can be loaded anywhere.
|
|
61
|
+
*
|
|
62
|
+
* FLEET_GUARD_ROOT the fleet root holding fleet.sqlite
|
|
63
|
+
* FLEET_GUARD_NODE the node this child is driving
|
|
64
|
+
* FLEET_GUARD_TURN the turn this child is driving
|
|
65
|
+
* FLEET_GUARD=off the operator's escape hatch: the child is unguarded
|
|
66
|
+
*
|
|
67
|
+
* Failure behaviour is fail-open, deliberately. A guard that cannot read the
|
|
68
|
+
* journal does not know whether a call is a duplicate, and refusing work on a
|
|
69
|
+
* doubt turns a database hiccup into a frozen fleet. It reports loudly on
|
|
70
|
+
* stderr and in `<root>/guard-errors.log` and lets the call run, which is a
|
|
71
|
+
* trade-off and named as one, not an oversight.
|
|
72
|
+
*
|
|
73
|
+
* The record a refusal leaves is a row in `effects` with `state = 'blocked'`.
|
|
74
|
+
* That state is a value of an existing column, so no schema change and no
|
|
75
|
+
* `SCHEMA_VERSION` bump is involved, and `settledEffects` (state = completed)
|
|
76
|
+
* and `markUnknownEffects` (state = attempted) both ignore it: a refusal is
|
|
77
|
+
* neither an applied effect nor an unknown one.
|
|
78
|
+
*
|
|
79
|
+
* A refusal stays recoverable, deliberately through an operator and not
|
|
80
|
+
* through the model. A node that genuinely has to repeat a recorded effect and
|
|
81
|
+
* cannot express it differently - a shell command, whose arguments are the
|
|
82
|
+
* whole identity - is released by retiring exactly the row the refusal names
|
|
83
|
+
* in its `result_json`:
|
|
84
|
+
*
|
|
85
|
+
* sqlite3 <root>/fleet.sqlite "UPDATE effects SET state = 'superseded'
|
|
86
|
+
* WHERE turn_id = <duplicate_of_turn> AND tool_call_id = '<duplicate_of_tool_call>'"
|
|
87
|
+
*
|
|
88
|
+
* `superseded` is another value of the same state column, and every reader of
|
|
89
|
+
* `effects` in journal.mjs matches a positive list (`completed`, `attempted`),
|
|
90
|
+
* so the retired row stops counting as history without leaving the record.
|
|
91
|
+
* The statement is not offered to the model and nothing in the child runs it:
|
|
92
|
+
* the refusal tells the model to continue from the next unfinished step and
|
|
93
|
+
* names the release as an operator's decision. A model that goes around the
|
|
94
|
+
* guard to the database itself is attacking the instrument, and an in-process
|
|
95
|
+
* guard cannot defend against a process it is loaded inside.
|
|
96
|
+
*/
|
|
97
|
+
|
|
98
|
+
import { appendFileSync, existsSync } from "node:fs";
|
|
99
|
+
import { join, resolve } from "node:path";
|
|
100
|
+
import { DatabaseSync } from "node:sqlite";
|
|
101
|
+
|
|
102
|
+
import { effectKey, journalPath, replayPolicy } from "./journal.mjs";
|
|
103
|
+
|
|
104
|
+
/** The names the child reads. `off` is the switch, not an identifier. */
|
|
105
|
+
export const GUARD_ENV = {
|
|
106
|
+
root: "FLEET_GUARD_ROOT",
|
|
107
|
+
node: "FLEET_GUARD_NODE",
|
|
108
|
+
turn: "FLEET_GUARD_TURN",
|
|
109
|
+
off: "FLEET_GUARD",
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* A scalar leaf, with the one coercion the two views of a call disagree about.
|
|
114
|
+
*
|
|
115
|
+
* A model writes `timeout: "30"`; pi validates the arguments against the
|
|
116
|
+
* tool's schema and hands this hook `timeout: 30`; the journal kept the
|
|
117
|
+
* string. So the same argument arrives in two types and the row never
|
|
118
|
+
* matched. The rule that closes it is the narrowest one available: a string
|
|
119
|
+
* converts only when it converts back to itself, `String(Number(s)) === s`.
|
|
120
|
+
* `"30"` becomes 30 and matches a recorded 30; `"030"`, `" 30 "`, `"1e3"`,
|
|
121
|
+
* `"NaN"` and `""` all spell numbers and stay strings, because an argument
|
|
122
|
+
* typed as a string may legitimately hold one and merging it with a number
|
|
123
|
+
* would call two genuinely different arguments the same.
|
|
124
|
+
*
|
|
125
|
+
* The asymmetry of the two failure modes is why the rule is this narrow. A
|
|
126
|
+
* spelling that is not converted lets a duplicate run, which leaves the guard
|
|
127
|
+
* advisory for that spelling - the state every other tool shape is already in.
|
|
128
|
+
* A spelling that is converted too eagerly refuses a call that should run,
|
|
129
|
+
* permanently, which is the defect this canonicalisation exists to repair.
|
|
130
|
+
* `"true"` and `"false"` convert for the same reason and with the same
|
|
131
|
+
* exactness: only those two spellings, only to the boolean.
|
|
132
|
+
*/
|
|
133
|
+
function canonicalScalar(value) {
|
|
134
|
+
if (typeof value !== "string") return value;
|
|
135
|
+
if (value === "true") return true;
|
|
136
|
+
if (value === "false") return false;
|
|
137
|
+
const asNumber = Number(value);
|
|
138
|
+
return Number.isFinite(asNumber) && String(asNumber) === value ? asNumber : value;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Keys sorted at every depth, unset fields dropped, so two spellings of one
|
|
143
|
+
* call compare equal. A null is how these tool schemas spell "not given", and
|
|
144
|
+
* the two surfaces disagree about whether to carry it.
|
|
145
|
+
*/
|
|
146
|
+
export function canonicalArgs(value) {
|
|
147
|
+
if (value === null || value === undefined) return undefined;
|
|
148
|
+
if (typeof value !== "object") return canonicalScalar(value);
|
|
149
|
+
if (Array.isArray(value)) return value.map(canonicalArgs);
|
|
150
|
+
const sorted = {};
|
|
151
|
+
for (const key of Object.keys(value).sort()) {
|
|
152
|
+
const normalized = canonicalArgs(value[key]);
|
|
153
|
+
if (normalized === undefined) continue;
|
|
154
|
+
sorted[key] = normalized;
|
|
155
|
+
}
|
|
156
|
+
return sorted;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function canonicalKey(args) {
|
|
160
|
+
return JSON.stringify(canonicalArgs(args ?? null) ?? null);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Two of pi's models send `edits` as a JSON string instead of an array; the
|
|
165
|
+
* edit tool parses it before this hook runs, so the hook holds the array while
|
|
166
|
+
* the journal kept the string. Parse it on the recorded side and on the call
|
|
167
|
+
* side, so either direction compares equal. A string that does not parse to an
|
|
168
|
+
* array is left exactly as it is: it is then a genuinely different argument,
|
|
169
|
+
* not a dialect of the same one.
|
|
170
|
+
*/
|
|
171
|
+
function parseEditArgs(args) {
|
|
172
|
+
if (args === null || typeof args !== "object" || Array.isArray(args)) return args;
|
|
173
|
+
if (typeof args.edits !== "string") return args;
|
|
174
|
+
let parsed;
|
|
175
|
+
try {
|
|
176
|
+
parsed = JSON.parse(args.edits);
|
|
177
|
+
} catch {
|
|
178
|
+
return args;
|
|
179
|
+
}
|
|
180
|
+
return Array.isArray(parsed) ? { ...args, edits: parsed } : args;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** The edit tool's one rewrite, applied to whichever side carries the pair. */
|
|
184
|
+
function collapseEditShape(args) {
|
|
185
|
+
const edits = args?.edits;
|
|
186
|
+
if (!Array.isArray(edits) || edits.length !== 1) return args;
|
|
187
|
+
const [only] = edits;
|
|
188
|
+
if (!only || typeof only !== "object") return args;
|
|
189
|
+
const rest = {};
|
|
190
|
+
for (const key of Object.keys(args)) {
|
|
191
|
+
if (key !== "edits") rest[key] = args[key];
|
|
192
|
+
}
|
|
193
|
+
if (only.oldText !== undefined) rest.oldText = only.oldText;
|
|
194
|
+
if (only.newText !== undefined) rest.newText = only.newText;
|
|
195
|
+
return rest;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** No field at all is no identity, so it cannot be a duplicate of anything. */
|
|
199
|
+
function carriesFields(value) {
|
|
200
|
+
return value !== null && typeof value === "object" && Object.keys(value).length > 0;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Every field the call carries is present and equal in the recorded row. */
|
|
204
|
+
function covers(stored, call) {
|
|
205
|
+
if (call === undefined) return stored === undefined;
|
|
206
|
+
if (call === null) return stored === null;
|
|
207
|
+
if (typeof call !== "object") return Object.is(call, stored);
|
|
208
|
+
if (Array.isArray(call)) {
|
|
209
|
+
return Array.isArray(stored) && stored.length === call.length && call.every((item, index) => covers(stored[index], item));
|
|
210
|
+
}
|
|
211
|
+
if (stored === null || typeof stored !== "object" || Array.isArray(stored)) return false;
|
|
212
|
+
return Object.keys(call).every((key) => key in stored && covers(stored[key], call[key]));
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* Is this call the one the recorded row already ran? The recorded row may
|
|
217
|
+
* carry fields the call does not (a default the tool reports back, an explicit
|
|
218
|
+
* null); the call may not carry anything the row lacks. A call that carries no
|
|
219
|
+
* fields is refused a match outright, because vacuous agreement would block
|
|
220
|
+
* every argument-less call of a tool that has ever run.
|
|
221
|
+
*/
|
|
222
|
+
export function sameCall({ toolName, recorded, args }) {
|
|
223
|
+
const isEdit = toolName === "edit";
|
|
224
|
+
const call = canonicalArgs(isEdit ? parseEditArgs(args) : args);
|
|
225
|
+
const row = canonicalArgs(isEdit ? parseEditArgs(recorded) : recorded);
|
|
226
|
+
if (!carriesFields(call)) return false;
|
|
227
|
+
if (covers(row, call)) return true;
|
|
228
|
+
if (!isEdit) return false;
|
|
229
|
+
const collapsedCall = canonicalArgs(collapseEditShape(call));
|
|
230
|
+
if (!carriesFields(collapsedCall)) return false;
|
|
231
|
+
return covers(canonicalArgs(collapseEditShape(row)), collapsedCall);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Values of the switch that mean "off"; anything else leaves the guard on. */
|
|
235
|
+
const OFF_VALUES = new Set(["off", "0", "false", "no"]);
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* The context the child was given, or null when it was given none. A partial
|
|
239
|
+
* contract is no contract: a guard that knows the node but not the turn would
|
|
240
|
+
* exclude the wrong turn from its history and refuse same-turn repeats.
|
|
241
|
+
*
|
|
242
|
+
* The switch is read as an explicit "off" rather than as "set at all", so a
|
|
243
|
+
* typo or a `FLEET_GUARD=on` leaves the guard running. A guard that silently
|
|
244
|
+
* disables itself is worse than one that refuses a call the operator can see.
|
|
245
|
+
*/
|
|
246
|
+
export function guardContext(env = process.env) {
|
|
247
|
+
const root = env[GUARD_ENV.root];
|
|
248
|
+
const nodeId = env[GUARD_ENV.node];
|
|
249
|
+
const rawTurn = env[GUARD_ENV.turn];
|
|
250
|
+
if (!root || !nodeId || rawTurn == null || rawTurn === "") return null;
|
|
251
|
+
if (OFF_VALUES.has(String(env[GUARD_ENV.off] ?? "").trim().toLowerCase())) return null;
|
|
252
|
+
const turnId = Number(rawTurn);
|
|
253
|
+
if (!Number.isInteger(turnId) || turnId <= 0) return null;
|
|
254
|
+
return { root: resolve(String(root)), nodeId: String(nodeId), turnId };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* The states a turn can end in and be finished. `settled` is an ordinary turn,
|
|
259
|
+
* `parked` stopped to ask a human, `done` reported the charter complete; each
|
|
260
|
+
* finished the work it was started for, so the recovery window stops there.
|
|
261
|
+
* `interrupted` and `failed` are turns that were cut off, and `in_progress` is
|
|
262
|
+
* a turn that has not ended at all - all three are inside the window.
|
|
263
|
+
*/
|
|
264
|
+
export const SETTLED_TURN_STATES = Object.freeze(["settled", "parked", "done"]);
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* The journal, as the guard needs it: two reads and one write, each spelled
|
|
268
|
+
* here rather than added to journal.mjs so the shipped reader stays untouched.
|
|
269
|
+
*
|
|
270
|
+
* The supervisor holds its own connection to the same file, so every write is
|
|
271
|
+
* an upsert: the supervisor records the attempt from the RPC stream at about
|
|
272
|
+
* the same moment the guard refuses the call, and whichever lands second must
|
|
273
|
+
* not decide the outcome. `effectSettled` in journal.mjs only rewrites rows in
|
|
274
|
+
* `attempted`, so a row this module writes as `blocked` cannot be turned into a
|
|
275
|
+
* completed effect afterwards.
|
|
276
|
+
*/
|
|
277
|
+
export function openGuardJournal(root) {
|
|
278
|
+
const path = journalPath(root);
|
|
279
|
+
if (!existsSync(path)) throw new Error(`no fleet journal at ${path}`);
|
|
280
|
+
const db = new DatabaseSync(path);
|
|
281
|
+
db.exec("PRAGMA busy_timeout = 5000");
|
|
282
|
+
db.exec("PRAGMA synchronous = FULL");
|
|
283
|
+
// The floor of the recovery window: the last turn of this node that ended
|
|
284
|
+
// normally. `MAX` is what makes the window the recovery chain rather than
|
|
285
|
+
// "every turn that did not settle": an interruption older than a later
|
|
286
|
+
// settled turn was resolved by the run that settled, so its effects are
|
|
287
|
+
// finished business again.
|
|
288
|
+
const windowFloor = db.prepare(
|
|
289
|
+
`SELECT COALESCE(MAX(turn_id), 0) AS floor FROM turns
|
|
290
|
+
WHERE node_id = ? AND turn_id < ? AND state IN (${SETTLED_TURN_STATES.map(() => "?").join(", ")})`,
|
|
291
|
+
);
|
|
292
|
+
const findApplied = db.prepare(
|
|
293
|
+
`SELECT turn_id, tool_call_id, seq, args_json, state FROM effects
|
|
294
|
+
WHERE node_id = ? AND tool_name = ? AND turn_id <> ? AND turn_id > ?
|
|
295
|
+
AND (state = 'unknown' OR (state = 'completed' AND is_error = 0))
|
|
296
|
+
ORDER BY turn_id, seq`,
|
|
297
|
+
);
|
|
298
|
+
const upsertBlock = db.prepare(
|
|
299
|
+
`INSERT INTO effects (turn_id, node_id, tool_call_id, seq, tool_name, args_json, replay,
|
|
300
|
+
idempotency_key, state, result_json, is_error, started_at, ended_at)
|
|
301
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'blocked', ?, 1, ?, ?)
|
|
302
|
+
ON CONFLICT(turn_id, tool_call_id) DO UPDATE SET
|
|
303
|
+
state = 'blocked', result_json = excluded.result_json, is_error = 1, ended_at = excluded.ended_at`,
|
|
304
|
+
);
|
|
305
|
+
let floorFor = null;
|
|
306
|
+
return {
|
|
307
|
+
/**
|
|
308
|
+
* The oldest recorded effect for this call that may have reached the
|
|
309
|
+
* world, inside the recovery window. `unknown` is included on purpose: the
|
|
310
|
+
* tool started and never reported, so the effect may have half applied,
|
|
311
|
+
* which is the one class where repeating it is dangerous.
|
|
312
|
+
*
|
|
313
|
+
* The floor is read once per turn and not once per call: a turn that ended
|
|
314
|
+
* before this one cannot start ending differently while this one runs, and
|
|
315
|
+
* the only writer that touches an older turn is reconcile, which marks an
|
|
316
|
+
* open turn `interrupted` and never `settled`. So the window cannot move
|
|
317
|
+
* under a turn, and on a node issuing fifty shell commands a turn the
|
|
318
|
+
* second read would otherwise be fifty scans of `turns`.
|
|
319
|
+
*/
|
|
320
|
+
appliedDuplicate({ nodeId, toolName, args, currentTurnId }) {
|
|
321
|
+
const windowKey = `${nodeId}\u0000${currentTurnId}`;
|
|
322
|
+
if (floorFor?.key !== windowKey) {
|
|
323
|
+
floorFor = { key: windowKey, floor: windowFloor.get(nodeId, currentTurnId, ...SETTLED_TURN_STATES).floor };
|
|
324
|
+
}
|
|
325
|
+
for (const row of findApplied.all(nodeId, toolName, currentTurnId, floorFor.floor)) {
|
|
326
|
+
let stored;
|
|
327
|
+
try {
|
|
328
|
+
stored = JSON.parse(row.args_json);
|
|
329
|
+
} catch {
|
|
330
|
+
continue;
|
|
331
|
+
}
|
|
332
|
+
if (sameCall({ toolName, recorded: stored, args })) {
|
|
333
|
+
return { turnId: row.turn_id, toolCallId: row.tool_call_id, seq: row.seq, state: row.state };
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return null;
|
|
337
|
+
},
|
|
338
|
+
recordBlock({ turnId, nodeId, toolCallId, toolName, args, reason, duplicate }) {
|
|
339
|
+
const at = Date.now();
|
|
340
|
+
upsertBlock.run(
|
|
341
|
+
turnId,
|
|
342
|
+
nodeId,
|
|
343
|
+
toolCallId,
|
|
344
|
+
// The supervisor assigns this turn's sequence numbers from the RPC
|
|
345
|
+
// stream; the guard cannot know the next one, and the column is not
|
|
346
|
+
// part of the primary key, so a refusal sits at 0 and is found by
|
|
347
|
+
// state rather than by order.
|
|
348
|
+
0,
|
|
349
|
+
toolName,
|
|
350
|
+
JSON.stringify(args ?? null),
|
|
351
|
+
replayPolicy(toolName),
|
|
352
|
+
effectKey({ nodeId, turnId, toolCallId }),
|
|
353
|
+
JSON.stringify({
|
|
354
|
+
blocked: true,
|
|
355
|
+
reason,
|
|
356
|
+
duplicate_of_turn: duplicate.turnId,
|
|
357
|
+
duplicate_of_tool_call: duplicate.toolCallId,
|
|
358
|
+
duplicate_of_seq: duplicate.seq,
|
|
359
|
+
}),
|
|
360
|
+
at,
|
|
361
|
+
at,
|
|
362
|
+
);
|
|
363
|
+
},
|
|
364
|
+
close() {
|
|
365
|
+
db.close();
|
|
366
|
+
},
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function stderrReport(line) {
|
|
371
|
+
try {
|
|
372
|
+
process.stderr.write(`fleet-guard: ${line}\n`);
|
|
373
|
+
} catch {
|
|
374
|
+
// A closed stderr is not a reason to stop driving.
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* The decision, with the journal injected. `store` is a thunk so the extension
|
|
380
|
+
* can open the database on the first tool call and not in its factory.
|
|
381
|
+
*/
|
|
382
|
+
export function createGuard({ nodeId, turnId, store, report = stderrReport }) {
|
|
383
|
+
return {
|
|
384
|
+
nodeId,
|
|
385
|
+
turnId,
|
|
386
|
+
/**
|
|
387
|
+
* Called by pi before the tool executes. Returns a refusal, or nothing.
|
|
388
|
+
* The refusal text becomes the tool's result, so it has to tell the model
|
|
389
|
+
* what happened and what not to do next. It says who releases a blocked
|
|
390
|
+
* effect and does not say how: a model that could retire its own rows is a
|
|
391
|
+
* model policing itself, which is what this module exists instead of.
|
|
392
|
+
*/
|
|
393
|
+
onToolCall(event) {
|
|
394
|
+
const toolName = event?.toolName;
|
|
395
|
+
const toolCallId = event?.toolCallId;
|
|
396
|
+
if (!toolName || !toolCallId) return undefined;
|
|
397
|
+
if (replayPolicy(toolName) === "safe") return undefined;
|
|
398
|
+
const args = event.input ?? {};
|
|
399
|
+
let journal;
|
|
400
|
+
let duplicate;
|
|
401
|
+
try {
|
|
402
|
+
journal = store();
|
|
403
|
+
duplicate = journal.appliedDuplicate({ nodeId, toolName, args, currentTurnId: turnId });
|
|
404
|
+
} catch (error) {
|
|
405
|
+
// Cannot read, so cannot refuse: the alternative is a fleet that stops
|
|
406
|
+
// working when its journal does.
|
|
407
|
+
report(
|
|
408
|
+
`journal unreadable at ${nodeId} turn ${turnId} (${error.code ?? ""} ${error.message}); call ${toolCallId} ${toolName} allowed through unguarded`,
|
|
409
|
+
);
|
|
410
|
+
return undefined;
|
|
411
|
+
}
|
|
412
|
+
if (!duplicate) return undefined;
|
|
413
|
+
const recorded =
|
|
414
|
+
duplicate.state === "unknown"
|
|
415
|
+
? `was recorded on turn ${duplicate.turnId} of node ${nodeId} as an attempt that never reported back, so it may have reached the world`
|
|
416
|
+
: `was already completed on turn ${duplicate.turnId} of node ${nodeId}`;
|
|
417
|
+
const reason =
|
|
418
|
+
`fleet guard: refused ${toolName} call ${toolCallId}. The same call, with identical arguments, ${recorded}; ` +
|
|
419
|
+
`this turn is ${turnId} and it was not executed. Do not retry it: continue from the next unfinished step, ` +
|
|
420
|
+
`or change the call if the work genuinely differs. Repeating a recorded effect is not something this turn ` +
|
|
421
|
+
`can authorise - an operator has to release the recorded effect in the node's journal first, and the ` +
|
|
422
|
+
`refusal this call leaves records which row that is.`;
|
|
423
|
+
try {
|
|
424
|
+
journal.recordBlock({ turnId, nodeId, toolCallId, toolName, args, reason, duplicate });
|
|
425
|
+
} catch (error) {
|
|
426
|
+
// The refusal is the safety property and stands without its record.
|
|
427
|
+
// The record is the instrument, so its failure is reported, not hidden.
|
|
428
|
+
report(
|
|
429
|
+
`refused ${toolName} call ${toolCallId} at ${nodeId} turn ${turnId} but could not record it (${error.code ?? ""} ${error.message})`,
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
return { block: true, reason };
|
|
433
|
+
},
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** Where the guard reports when it has a root: stderr, and a line in the root. */
|
|
438
|
+
export function guardReport(root, line) {
|
|
439
|
+
stderrReport(line);
|
|
440
|
+
if (!root) return;
|
|
441
|
+
try {
|
|
442
|
+
appendFileSync(join(root, "guard-errors.log"), `${new Date().toISOString()} ${line}\n`);
|
|
443
|
+
} catch {
|
|
444
|
+
// The report is best effort; stderr already carried it.
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
export default function toolGuard(pi) {
|
|
449
|
+
const context = guardContext();
|
|
450
|
+
if (!context) return;
|
|
451
|
+
let store = null;
|
|
452
|
+
const guard = createGuard({
|
|
453
|
+
nodeId: context.nodeId,
|
|
454
|
+
turnId: context.turnId,
|
|
455
|
+
store: () => (store ??= openGuardJournal(context.root)),
|
|
456
|
+
report: (line) => guardReport(context.root, line),
|
|
457
|
+
});
|
|
458
|
+
pi.on("tool_call", (event) => guard.onToolCall(event));
|
|
459
|
+
pi.on("session_shutdown", () => {
|
|
460
|
+
try {
|
|
461
|
+
store?.close();
|
|
462
|
+
} catch {
|
|
463
|
+
// Nothing left to close.
|
|
464
|
+
}
|
|
465
|
+
store = null;
|
|
466
|
+
});
|
|
467
|
+
}
|
|
@@ -150,13 +150,28 @@ Rules the script enforces:
|
|
|
150
150
|
## Remote Publication
|
|
151
151
|
|
|
152
152
|
Remote publication uses `.github/workflows/publish.yml`, separate from the
|
|
153
|
-
local install path. A
|
|
154
|
-
|
|
155
|
-
`
|
|
153
|
+
local install path. A core release tag (`v<core version>`) runs the workflow,
|
|
154
|
+
and the tag must be **annotated**: the workflow's first step is
|
|
155
|
+
`test "$(git cat-file -t refs/tags/${GITHUB_REF_NAME})" = tag`, so a lightweight
|
|
156
|
+
tag pushed with plain `git tag` makes that test fail and the job dies in
|
|
157
|
+
seconds with no publish. Use `git tag -a v<core version> -m "<what shipped>"`.
|
|
158
|
+
`release:check` verifies the annotation too, reporting `annotated, matches`.
|
|
159
|
+
|
|
160
|
+
To publish one sibling package, dispatch from `main` with
|
|
161
|
+
`only=<workspace directory>`, where the accepted values are exactly
|
|
162
|
+
`core`, `skills`, `providers`, `telegram`, `contrib`: the **directory** names
|
|
163
|
+
under `packages/`, not the npm package names. `only=pi-braid-telegram` is
|
|
164
|
+
refused as an unknown package; `only=telegram` is the correct spelling.
|
|
165
|
+
Sibling tags do not run this release workflow, and iteration
|
|
156
166
|
tags are refused by its job condition. A release-tag run publishes each stable
|
|
157
167
|
workspace version not already present on npm through trusted publishing (OIDC);
|
|
158
168
|
the workflow uses no npm token.
|
|
159
169
|
|
|
170
|
+
A sibling whose version did not change is **skipped silently**: the run
|
|
171
|
+
succeeds and that package stays at its old version on the registry. Bump the
|
|
172
|
+
sibling's `package.json` and commit it before dispatching, or the fix it
|
|
173
|
+
carries ships in the repository and nowhere else.
|
|
174
|
+
|
|
160
175
|
Preparation:
|
|
161
176
|
|
|
162
177
|
- Commit the intended stable package versions. Refresh `package-lock.json` as
|
|
@@ -184,7 +199,8 @@ After release:
|
|
|
184
199
|
use the derived iteration version instead.
|
|
185
200
|
- Use `npm version` for semver bumps in the target workspace.
|
|
186
201
|
- A bare core release tag (`v<core version>`) runs the publish workflow. Publish
|
|
187
|
-
a sibling package by dispatching from `main` with `only=<
|
|
202
|
+
a sibling package by dispatching from `main` with `only=<workspace directory>`
|
|
203
|
+
(`core|skills|providers|telegram|contrib`, not the npm package name).
|
|
188
204
|
`tag-prerelease.mjs` creates package-scoped iteration tags; they do not
|
|
189
205
|
publish.
|
|
190
206
|
|