@0perator/operator 0.1.222 → 0.1.261
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 +6 -5
- package/dashboard/server.mjs +1 -1
- package/dist/acp/agent.js +320 -53
- package/dist/acp/auth.js +44 -0
- package/dist/acp/config-options.js +34 -0
- package/dist/acp/prompt.js +41 -0
- package/dist/acp/run.js +116 -10
- package/dist/acp/tool-map.js +48 -0
- package/dist/auth/byo.js +125 -0
- package/dist/auth/client.js +12 -6
- package/dist/auth/commands.js +71 -3
- package/dist/auth/identity.js +136 -0
- package/dist/auth/store.js +7 -5
- package/dist/autonomy/board.js +3 -2
- package/dist/autonomy/cron.js +332 -0
- package/dist/autonomy/delegate.js +168 -0
- package/dist/autonomy/dream.js +1 -1
- package/dist/autonomy/index.js +16 -2
- package/dist/autonomy/media-robot.js +137 -0
- package/dist/autonomy/profile.js +77 -0
- package/dist/autonomy/routines.js +5 -4
- package/dist/autonomy/session-factory.js +19 -10
- package/dist/background/index.js +8 -1
- package/dist/browser/cdp.js +266 -0
- package/dist/browser/session.js +286 -0
- package/dist/cli.js +207 -106
- package/dist/compose/client.js +56 -0
- package/dist/config/brand.js +3 -3
- package/dist/config/home.js +70 -0
- package/dist/config/managed.js +230 -0
- package/dist/config/persona.js +243 -21
- package/dist/config/scaffold.js +142 -0
- package/dist/config/settings.js +87 -20
- package/dist/config/skills-index.js +175 -0
- package/dist/consolidation/scheduler.js +10 -7
- package/dist/consolidation/sleep.js +17 -3
- package/dist/engine/agent.js +231 -21
- package/dist/engine/aurora.js +79 -14
- package/dist/engine/batch-scheduler.js +128 -0
- package/dist/engine/compaction.js +129 -2
- package/dist/engine/computer-event.js +139 -0
- package/dist/engine/continuation.js +55 -0
- package/dist/engine/contract.js +3 -1
- package/dist/engine/grandmaster.js +13 -3
- package/dist/engine/json-repair.js +105 -0
- package/dist/engine/messages.js +52 -5
- package/dist/engine/redact.js +25 -0
- package/dist/engine/rolling-summary.js +28 -11
- package/dist/engine/router-adapter.js +2 -0
- package/dist/engine/unrestricted.js +51 -0
- package/dist/engine/verify-gate.js +6 -0
- package/dist/enterprise/cli.js +137 -0
- package/dist/flywheel/processor.js +30 -2
- package/dist/flywheel/secret-gate.js +123 -0
- package/dist/index.browser.js +4 -0
- package/dist/index.js +4 -0
- package/dist/mcp/index.js +18 -24
- package/dist/memory/index.js +0 -0
- package/dist/memory/session-index.js +324 -0
- package/dist/memory/session-rewind.js +92 -0
- package/dist/memory/state-maintenance.js +441 -0
- package/dist/observability/index.js +3 -3
- package/dist/permissions/audit.js +4 -1
- package/dist/permissions/index.js +24 -12
- package/dist/permissions/policy.js +4 -3
- package/dist/permissions/tier.js +31 -14
- package/dist/remote/host.js +9 -2
- package/dist/router/models.js +62 -2
- package/dist/selfimprove/index.js +9 -7
- package/dist/session.js +129 -42
- package/dist/skills/catalogue.js +167 -0
- package/dist/telemetry/audit-verify.js +94 -0
- package/dist/telemetry/events.js +92 -7
- package/dist/telemetry/lifecycle.js +18 -0
- package/dist/tools/computer.js +1 -1
- package/dist/tools/deferred.js +117 -0
- package/dist/tools/executor.js +27 -23
- package/dist/tools/memory.js +117 -0
- package/dist/tools/mutating.js +6 -0
- package/dist/tools/registry.js +1022 -46
- package/dist/tools/sandbox.js +63 -17
- package/dist/tools/searxng.js +2 -2
- package/dist/tools/shell-session.js +36 -1
- package/dist/tools/tool-output-spill.js +4 -4
- package/dist/ui/ActivitySpinner.js +17 -6
- package/dist/ui/App.js +36 -14
- package/dist/ui/ArtifactPicker.js +109 -0
- package/dist/ui/Composer.js +39 -8
- package/dist/ui/Markdown.js +5 -3
- package/dist/ui/MouseProvider.js +99 -19
- package/dist/ui/QuestionPrompt.js +24 -3
- package/dist/ui/ThinkingSpinner.js +9 -5
- package/dist/ui/ToolStep.js +17 -12
- package/dist/ui/Transcript.js +28 -9
- package/dist/ui/capabilities.js +0 -9
- package/dist/ui/listhit.js +23 -0
- package/dist/ui/mouse.js +22 -0
- package/dist/ui/osc.js +7 -4
- package/dist/ui/progressbar.js +46 -0
- package/dist/ui/shimmer.js +43 -0
- package/dist/ui/theme.js +2 -0
- package/dist/ui/tick.js +48 -0
- package/dist/ui/toolicons.js +69 -0
- package/dist/ui/useInputHistory.js +3 -3
- package/dist/util/slash.js +1 -0
- package/dist/vault/cli.js +48 -0
- package/dist/vault/store.js +157 -0
- package/dist/vault/tool.js +50 -0
- package/package.json +3 -5
- package/CHANGELOG.md +0 -1629
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Offline verifier for the hash-chained audit log written by EventSink (telemetry/events.ts). NODE-ONLY (fs +
|
|
2
|
+
// crypto, static imports) — it is reached only from the `operator audit` / `operator doctor` commands, never
|
|
3
|
+
// from the engine or the browser bundle.
|
|
4
|
+
//
|
|
5
|
+
// Each line is the event JSON plus `cid` (chain id), `seq` and `h` = sha256(previous h + the line's body, i.e.
|
|
6
|
+
// everything before `,"h":"…"}`). Chains are per sink instance (per process), so several Operator processes can
|
|
7
|
+
// append to one file; verification groups by `cid`. What it proves: no line was edited, deleted from the middle,
|
|
8
|
+
// or reordered within a chain. What it cannot: tail truncation, or a forgery by someone who can recompute the
|
|
9
|
+
// chain — the append-only remote copy (KODE_TELEMETRY_URL / a SIEM forwarder) is the anchor for that.
|
|
10
|
+
import { createHash } from "node:crypto";
|
|
11
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
12
|
+
import { dirname, join } from "node:path";
|
|
13
|
+
/** Rotated files (oldest first) then the active file, for one active-file path. */
|
|
14
|
+
export function auditFilesFor(active) {
|
|
15
|
+
const dir = join(dirname(active), "audit");
|
|
16
|
+
let rotated = [];
|
|
17
|
+
try {
|
|
18
|
+
rotated = readdirSync(dir).filter((n) => /^events-.*\.jsonl$/.test(n)).sort().map((n) => join(dir, n));
|
|
19
|
+
}
|
|
20
|
+
catch { /* no rotations yet */ }
|
|
21
|
+
return [...rotated, ...(existsSync(active) ? [active] : [])];
|
|
22
|
+
}
|
|
23
|
+
const TAIL = /^(.*),"h":"([0-9a-f]{64})"\}$/;
|
|
24
|
+
const sha = (prev, body) => createHash("sha256").update(prev).update(body).digest("hex");
|
|
25
|
+
export function verifyAuditFiles(files) {
|
|
26
|
+
const rep = { files, events: 0, chained: 0, unchained: 0, chains: 0, midstream: [], breaks: [], ok: true };
|
|
27
|
+
const state = new Map();
|
|
28
|
+
for (const file of files) {
|
|
29
|
+
let text;
|
|
30
|
+
try {
|
|
31
|
+
text = readFileSync(file, "utf8");
|
|
32
|
+
}
|
|
33
|
+
catch (e) {
|
|
34
|
+
rep.breaks.push({ file, line: 0, cid: "?", reason: `unreadable: ${e instanceof Error ? e.message : String(e)}` });
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const lines = text.split("\n");
|
|
38
|
+
for (let i = 0; i < lines.length; i++) {
|
|
39
|
+
const line = lines[i];
|
|
40
|
+
if (!line.trim())
|
|
41
|
+
continue;
|
|
42
|
+
rep.events++;
|
|
43
|
+
const m = TAIL.exec(line);
|
|
44
|
+
if (!m) {
|
|
45
|
+
let obj = null;
|
|
46
|
+
try {
|
|
47
|
+
obj = JSON.parse(line);
|
|
48
|
+
}
|
|
49
|
+
catch { /* handled below */ }
|
|
50
|
+
if (!obj)
|
|
51
|
+
rep.breaks.push({ file, line: i + 1, cid: "?", reason: "unparseable line" });
|
|
52
|
+
else if (obj.cid !== undefined)
|
|
53
|
+
rep.breaks.push({ file, line: i + 1, cid: String(obj.cid), reason: "chain fields present but hash missing/invalid" });
|
|
54
|
+
else
|
|
55
|
+
rep.unchained++;
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const body = m[1] + "}";
|
|
59
|
+
const h = m[2];
|
|
60
|
+
let obj;
|
|
61
|
+
try {
|
|
62
|
+
obj = JSON.parse(body);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
rep.breaks.push({ file, line: i + 1, cid: "?", reason: "chained body is not valid JSON" });
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
if (typeof obj.cid !== "string" || typeof obj.seq !== "number") {
|
|
69
|
+
rep.breaks.push({ file, line: i + 1, cid: "?", reason: "chained line without cid/seq" });
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
rep.chained++;
|
|
73
|
+
const prior = state.get(obj.cid);
|
|
74
|
+
if (!prior) {
|
|
75
|
+
rep.chains++;
|
|
76
|
+
if (obj.seq === 0) {
|
|
77
|
+
if (sha("genesis", body) !== h)
|
|
78
|
+
rep.breaks.push({ file, line: i + 1, cid: obj.cid, reason: "hash mismatch (line was edited)" });
|
|
79
|
+
}
|
|
80
|
+
else
|
|
81
|
+
rep.midstream.push(obj.cid); // start rotated out: no predecessor to check against
|
|
82
|
+
}
|
|
83
|
+
else if (obj.seq !== prior.seq + 1) {
|
|
84
|
+
rep.breaks.push({ file, line: i + 1, cid: obj.cid, reason: obj.seq > prior.seq + 1 ? `${obj.seq - prior.seq - 1} line(s) missing before seq ${obj.seq}` : `seq ${obj.seq} after ${prior.seq} (duplicated or reordered)` });
|
|
85
|
+
}
|
|
86
|
+
else if (sha(prior.h, body) !== h) {
|
|
87
|
+
rep.breaks.push({ file, line: i + 1, cid: obj.cid, reason: "hash mismatch (line was edited)" });
|
|
88
|
+
}
|
|
89
|
+
state.set(obj.cid, { seq: obj.seq, h }); // resync on the STORED hash so one edit is reported once, not for every later line
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
rep.ok = rep.breaks.length === 0;
|
|
93
|
+
return rep;
|
|
94
|
+
}
|
package/dist/telemetry/events.js
CHANGED
|
@@ -9,17 +9,46 @@
|
|
|
9
9
|
// simply never reached (a mobile host injects its own sink). Best-effort by construction: a sink failure
|
|
10
10
|
// never blocks or fails a turn — observability is not a gate.
|
|
11
11
|
const nodeImport = (m) => import(/* @vite-ignore */ m);
|
|
12
|
+
// redact is pure regex + node-free — the static import keeps this module bundle-safe (GW-10 graph).
|
|
13
|
+
import { redactSecrets } from "../engine/redact.js";
|
|
12
14
|
export const EVENT_V = 1;
|
|
15
|
+
/** The machine-wide audit file: an explicit KODE_EVENTS_FILE / KODE_AUDIT_FILE, else `$KODE_HOME/events.jsonl`,
|
|
16
|
+
* else `~/.axe/operator/events.jsonl` (unexpanded `~/`). Deliberately NOT profile-scoped: one audit trail per
|
|
17
|
+
* OS user is what a security team collects and what the swarm console tails. */
|
|
18
|
+
export function defaultEventsFile() {
|
|
19
|
+
const e = process.env;
|
|
20
|
+
return e.KODE_EVENTS_FILE || e.KODE_AUDIT_FILE || (e.KODE_HOME ? e.KODE_HOME + "/events.jsonl" : "~/.axe/operator/events.jsonl");
|
|
21
|
+
}
|
|
22
|
+
const DEFAULT_AUDIT_MAX_BYTES = 64 * 1024 * 1024;
|
|
23
|
+
const DEFAULT_AUDIT_KEEP = 20;
|
|
24
|
+
const envPosInt = (name, fallback) => {
|
|
25
|
+
const n = Number(process.env[name]);
|
|
26
|
+
return Number.isFinite(n) && n >= 0 && process.env[name] !== undefined && process.env[name] !== "" ? Math.floor(n) : fallback;
|
|
27
|
+
};
|
|
13
28
|
/** Emits OperatorEvents to a local JSONL file and, if configured, an HTTP sink. Both best-effort. The
|
|
14
|
-
* HTTP POST is fire-and-forget with a short timeout so a slow/down sink never stalls a turn.
|
|
29
|
+
* HTTP POST is fire-and-forget with a short timeout so a slow/down sink never stalls a turn.
|
|
30
|
+
*
|
|
31
|
+
* The FILE is a tamper-evident audit trail (see telemetry/audit-verify.ts): every line this sink writes carries
|
|
32
|
+
* `cid` (a chain id, one per sink instance), `seq` (0,1,2… within the chain) and `h` = sha256(previous h + the
|
|
33
|
+
* line's own body). Editing, deleting or reordering a line breaks `operator audit verify`. It also rotates by
|
|
34
|
+
* size into `<dir>/audit/` so the log cannot grow without bound. Honest limit: the chain is unkeyed, so
|
|
35
|
+
* someone who can write the file AND recompute from the edit point can forge it — the append-only remote copy
|
|
36
|
+
* (KODE_TELEMETRY_URL / a SIEM forwarder) is the anchor, and the sandbox keeps the agent away from the file. */
|
|
15
37
|
export class EventSink {
|
|
16
38
|
file;
|
|
17
39
|
url;
|
|
18
40
|
onEvent;
|
|
19
41
|
subscribers = new Set();
|
|
20
42
|
lastWrite = Promise.resolve(); // chained so appends land in emit order (an audit log must be ordered)
|
|
43
|
+
cid = "";
|
|
44
|
+
seq = 0;
|
|
45
|
+
prevH = "genesis";
|
|
46
|
+
sinceStat = Number.POSITIVE_INFINITY; // stat the file on the first write, then every `rotateEvery`
|
|
47
|
+
rotations = 0;
|
|
48
|
+
rotateEvery;
|
|
21
49
|
constructor(opts = {}) {
|
|
22
|
-
this.file = opts.file ??
|
|
50
|
+
this.file = opts.file ?? defaultEventsFile();
|
|
51
|
+
this.rotateEvery = opts.rotateEvery ?? 50;
|
|
23
52
|
this.url = opts.url ?? process.env.KODE_TELEMETRY_URL;
|
|
24
53
|
// In-process callback bridge — the ONLY path that works on mobile (JSCore has no fs and the phone is
|
|
25
54
|
// not a KODE_TELEMETRY_URL backend), same pattern as the bg-agents host bridge. A native/web host sets
|
|
@@ -53,15 +82,71 @@ export class EventSink {
|
|
|
53
82
|
}
|
|
54
83
|
async write(e) {
|
|
55
84
|
try {
|
|
56
|
-
const [
|
|
57
|
-
nodeImport("node:fs/promises"), nodeImport("node:os"), nodeImport("node:path"),
|
|
85
|
+
const [fsp, os, { join, dirname }, crypto] = await Promise.all([
|
|
86
|
+
nodeImport("node:fs/promises"), nodeImport("node:os"), nodeImport("node:path"), nodeImport("node:crypto"),
|
|
58
87
|
]);
|
|
59
88
|
const file = this.file.startsWith("~/") ? join(os.homedir(), this.file.slice(2)) : this.file;
|
|
60
|
-
await mkdir(dirname(file), { recursive: true });
|
|
61
|
-
await
|
|
89
|
+
await fsp.mkdir(dirname(file), { recursive: true, mode: 0o700 });
|
|
90
|
+
await this.maybeRotate(file, fsp, join, dirname);
|
|
91
|
+
// H4 (audit-tools §1): events sit next to bearer-token args in tool payloads; the file was
|
|
92
|
+
// world-readable by default and unmasked. 0700/0600 + redactSecrets — the POST sink below gets
|
|
93
|
+
// the identical treatment; claims of "secret-free" in this file's header are now ENFORCED.
|
|
94
|
+
// The hash is over the REDACTED body (what is actually on disk), so verification needs no secret.
|
|
95
|
+
if (!this.cid)
|
|
96
|
+
this.cid = crypto.randomBytes(6).toString("hex");
|
|
97
|
+
const body = redactSecrets(JSON.stringify({ ...e, cid: this.cid, seq: this.seq }));
|
|
98
|
+
const h = crypto.createHash("sha256").update(this.prevH).update(body).digest("hex");
|
|
99
|
+
await fsp.appendFile(file, body.slice(0, -1) + `,"h":"${h}"}\n`, { encoding: "utf8", mode: 0o600 });
|
|
100
|
+
this.prevH = h; // advance only after the line landed, so a failed append never forks the chain
|
|
101
|
+
this.seq++;
|
|
62
102
|
}
|
|
63
103
|
catch { /* best-effort: no fs (mobile) or a write failure must never break a turn */ }
|
|
64
104
|
}
|
|
105
|
+
/** Size-based rotation into `<dir>/audit/events-<utc>-<pid>.jsonl` (0600), pruning the oldest beyond
|
|
106
|
+
* KODE_AUDIT_KEEP (default 20; 0 = keep everything, for orgs that ship the files to a SIEM). Soft limit
|
|
107
|
+
* (KODE_AUDIT_MAX_BYTES, default 64MB), checked every few writes — several Operator processes share the file. */
|
|
108
|
+
async maybeRotate(file, fsp, join, dirname) {
|
|
109
|
+
if (this.sinceStat++ < this.rotateEvery)
|
|
110
|
+
return;
|
|
111
|
+
this.sinceStat = 0;
|
|
112
|
+
const max = envPosInt("KODE_AUDIT_MAX_BYTES", DEFAULT_AUDIT_MAX_BYTES);
|
|
113
|
+
if (max <= 0)
|
|
114
|
+
return;
|
|
115
|
+
let size;
|
|
116
|
+
try {
|
|
117
|
+
size = (await fsp.stat(file)).size;
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
if (size < max)
|
|
123
|
+
return;
|
|
124
|
+
const dir = join(dirname(file), "audit");
|
|
125
|
+
await fsp.mkdir(dir, { recursive: true, mode: 0o700 });
|
|
126
|
+
// Re-check immediately before the rename: a sibling process may have rotated it a moment ago.
|
|
127
|
+
try {
|
|
128
|
+
if ((await fsp.stat(file)).size < max)
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
catch {
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
// utc timestamp, then a per-process counter: two rotations in the same millisecond must neither collide (rename
|
|
135
|
+
// REPLACES an existing file — that silently destroyed a rotated log in testing) nor sort out of order.
|
|
136
|
+
const dest = join(dir, `events-${new Date().toISOString().replace(/[:.]/g, "-")}-${String(++this.rotations).padStart(4, "0")}-${process.pid}.jsonl`);
|
|
137
|
+
try {
|
|
138
|
+
await fsp.stat(dest);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
catch { /* free to use */ }
|
|
142
|
+
await fsp.rename(file, dest);
|
|
143
|
+
const keep = envPosInt("KODE_AUDIT_KEEP", DEFAULT_AUDIT_KEEP);
|
|
144
|
+
if (keep > 0) {
|
|
145
|
+
const old = (await fsp.readdir(dir)).filter((n) => /^events-.*\.jsonl$/.test(n)).sort();
|
|
146
|
+
for (const n of old.slice(0, Math.max(0, old.length - keep)))
|
|
147
|
+
await fsp.rm(join(dir, n), { force: true });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
65
150
|
async post(e) {
|
|
66
151
|
if (!this.url)
|
|
67
152
|
return;
|
|
@@ -71,7 +156,7 @@ export class EventSink {
|
|
|
71
156
|
await fetch(this.url, {
|
|
72
157
|
method: "POST",
|
|
73
158
|
headers: { "content-type": "application/json" },
|
|
74
|
-
body: JSON.stringify(e),
|
|
159
|
+
body: redactSecrets(JSON.stringify(e)), // H4: never egress an unmasked token
|
|
75
160
|
signal: ctrl.signal,
|
|
76
161
|
});
|
|
77
162
|
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
// One-shot audit events for CLI commands that run outside any Session (`operator auth …`). Honors the same
|
|
2
|
+
// inert-by-default rule as the permission wrapper: a seat that is not audited (bypass + admin, no rules) writes
|
|
3
|
+
// nothing; an audited one (a narrowed tier, audit/gated mode, or a managed policy) gets a line per credential
|
|
4
|
+
// lifecycle action — who signed in/out, which vendor key was stored or removed (the NAME only, never a value).
|
|
5
|
+
// Awaits the sink's flush: these commands `process.exit` right after, which would otherwise drop the append.
|
|
6
|
+
import { PermissionPolicy } from "../permissions/index.js";
|
|
7
|
+
import { EventSink } from "./events.js";
|
|
8
|
+
export async function auditControl(settings, event, detail, sub, sink = new EventSink()) {
|
|
9
|
+
if (!settings || !new PermissionPolicy(settings.permissions).audits)
|
|
10
|
+
return;
|
|
11
|
+
sink.emit({
|
|
12
|
+
kind: "control",
|
|
13
|
+
session: `cli-${process.pid}`,
|
|
14
|
+
actor: { tier: settings.permissions.tier ?? "admin", surface: "cli", sub: sub ?? settings.seat?.sub },
|
|
15
|
+
control: { event, detail: detail.slice(0, 300) },
|
|
16
|
+
});
|
|
17
|
+
await sink.flushed();
|
|
18
|
+
}
|
package/dist/tools/computer.js
CHANGED
|
@@ -8,7 +8,7 @@ export function computerEnabled() { return ENABLED; }
|
|
|
8
8
|
function str(v, fallback = "") {
|
|
9
9
|
return v === undefined || v === null ? fallback : String(v);
|
|
10
10
|
}
|
|
11
|
-
const DISABLED_MSG = "computer control is disabled. Enable it with
|
|
11
|
+
const DISABLED_MSG = "computer control is disabled. Enable it with computer.enabled in settings.json, " +
|
|
12
12
|
"and grant the terminal app macOS permissions (run computer_doctor for the exact steps).";
|
|
13
13
|
// macOS is the only supported host for now (osascript/screencapture). Fail clearly elsewhere rather
|
|
14
14
|
// than silently no-op.
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { runBatch, defaultKeys } from "../engine/batch-scheduler.js";
|
|
2
|
+
/** Defer once the MCP surface is big enough for schemas to actually cost us (measured: 12+ tools). */
|
|
3
|
+
export const DEFERRED_THRESHOLD = 12;
|
|
4
|
+
export const DEFERRED_META_NAMES = ["tool_search", "tool_describe", "tool_call"];
|
|
5
|
+
export function deferredState(schemas) {
|
|
6
|
+
const defs = new Map();
|
|
7
|
+
for (const s of schemas) {
|
|
8
|
+
const fn = s?.function;
|
|
9
|
+
if (fn?.name)
|
|
10
|
+
defs.set(fn.name, s);
|
|
11
|
+
}
|
|
12
|
+
return { defs, loaded: new Set() };
|
|
13
|
+
}
|
|
14
|
+
const metaSchema = (name, description, properties, required) => ({
|
|
15
|
+
type: "function",
|
|
16
|
+
function: { name, description, parameters: { type: "object", properties, required } },
|
|
17
|
+
});
|
|
18
|
+
/** The three meta-tools' schemas — these ALWAYS ride the request when deferral is on. */
|
|
19
|
+
export function deferredMetaSchemas() {
|
|
20
|
+
return [
|
|
21
|
+
metaSchema("tool_search", "Search the DEFERRED tool catalog (fleet/local MCP tools whose full schemas are not loaded). Returns 'name — description' lines, max 15. Loaded tools become callable directly; describe first for exact parameter schemas.", { query: { type: "string", description: "case-insensitive substring(s) matched against tool names and descriptions" } }, ["query"]),
|
|
22
|
+
metaSchema("tool_describe", "Load full JSON schemas for named catalog tools (comma-separated or array, max 6). Described tools join the callable set for the rest of the session.", { names: { description: "tool name(s) from tool_search" } }, ["names"]),
|
|
23
|
+
metaSchema("tool_call", "Execute a catalog tool by exact name with a JSON args object — permission-gated per tool exactly like calling it directly. Prefer describing first; direct search->call is allowed for simple tools.", { name: { type: "string" }, args: { type: "object" } }, ["name"]),
|
|
24
|
+
];
|
|
25
|
+
}
|
|
26
|
+
/** The request-time `tools` array under deferral: locals + described MCP + the meta trio. */
|
|
27
|
+
export function deferredRequestSchemas(localSchemas, st) {
|
|
28
|
+
const loaded = [...st.loaded].map((n) => st.defs.get(n)).filter(Boolean);
|
|
29
|
+
return [...localSchemas, ...loaded, ...deferredMetaSchemas()];
|
|
30
|
+
}
|
|
31
|
+
function search(st, query) {
|
|
32
|
+
const q = query.toLowerCase();
|
|
33
|
+
const hits = [];
|
|
34
|
+
for (const [name, schema] of st.defs) {
|
|
35
|
+
const fn = schema.function ?? {};
|
|
36
|
+
const desc = String(fn.description ?? "");
|
|
37
|
+
if (!q || name.toLowerCase().includes(q) || desc.toLowerCase().includes(q))
|
|
38
|
+
hits.push(`${name} — ${desc.slice(0, 100)}`);
|
|
39
|
+
if (hits.length >= 15)
|
|
40
|
+
break;
|
|
41
|
+
}
|
|
42
|
+
return hits.length
|
|
43
|
+
? hits.join("\n") + (st.loaded.size ? `\n(${st.loaded.size} already loaded)` : "\ndescribe a name with tool_describe for its full schema")
|
|
44
|
+
: "tool catalog: no matches";
|
|
45
|
+
}
|
|
46
|
+
function describe(st, names) {
|
|
47
|
+
const list = (Array.isArray(names) ? names : String(names ?? "").split(/[,\s]+/)).map(String).filter(Boolean).slice(0, 6);
|
|
48
|
+
if (!list.length)
|
|
49
|
+
return "tool_describe: pass one or more names from tool_search";
|
|
50
|
+
const out = [];
|
|
51
|
+
for (const n of list) {
|
|
52
|
+
const def = st.defs.get(n);
|
|
53
|
+
if (!def) {
|
|
54
|
+
out.push(`${n}: NOT in the deferred catalog (check tool_search)`);
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
st.loaded.add(n);
|
|
58
|
+
out.push(JSON.stringify(def));
|
|
59
|
+
}
|
|
60
|
+
return out.join("\n");
|
|
61
|
+
}
|
|
62
|
+
/** Wrap a composed executor; meta names route here, everything else falls through in order. */
|
|
63
|
+
export function withDeferred(base, st) {
|
|
64
|
+
const runMeta = async (name, args) => {
|
|
65
|
+
if (name === "tool_search")
|
|
66
|
+
return search(st, String(args.query ?? ""));
|
|
67
|
+
if (name === "tool_describe")
|
|
68
|
+
return describe(st, args.names);
|
|
69
|
+
if (name === "tool_call") {
|
|
70
|
+
const target = String(args.name ?? "");
|
|
71
|
+
if (!st.defs.has(target))
|
|
72
|
+
return `tool_call: '${target}' is not in the deferred catalog — run tool_search`;
|
|
73
|
+
if (!st.loaded.has(target)) {
|
|
74
|
+
st.loaded.add(target); // auto-load so follow-up direct calls work; disclosure happens on the first result
|
|
75
|
+
return `tool_call ${target} (auto-described): ${await base.execute(target, args.args ?? {})}`;
|
|
76
|
+
}
|
|
77
|
+
return base.execute(target, args.args ?? {});
|
|
78
|
+
}
|
|
79
|
+
return `deferred: unknown meta '${name}'`;
|
|
80
|
+
};
|
|
81
|
+
return {
|
|
82
|
+
async execute(name, args) {
|
|
83
|
+
if (DEFERRED_META_NAMES.includes(name))
|
|
84
|
+
return runMeta(name, args);
|
|
85
|
+
return base.execute(name, args);
|
|
86
|
+
},
|
|
87
|
+
async executeParallel(calls, onSettle) {
|
|
88
|
+
// BTX finding B/C follow-through: meta trio and base calls share ONE scheduled batch —
|
|
89
|
+
// tool_call used to runMeta-inline (racing the base batch it dispatches INTO), and the meta
|
|
90
|
+
// Promise.all barrier made base calls wait for every meta first. Now: search/describe classify
|
|
91
|
+
// read, tool_call is an exclusive barrier (it can invoke ANYTHING downstream), pass-through
|
|
92
|
+
// keeps the chain's truth. sched is exposed so any outer wrapper propagates it.
|
|
93
|
+
return runBatch(calls, {
|
|
94
|
+
classify: (n) => (n === "tool_call" ? "barrier"
|
|
95
|
+
: n === "tool_search" || n === "tool_describe" ? "read"
|
|
96
|
+
: base.sched ? base.sched.classify(n) : "write"),
|
|
97
|
+
keys: (n, a) => (base.sched ? base.sched.keys(n, a) : defaultKeys(n, a)),
|
|
98
|
+
runOne: (c) => (DEFERRED_META_NAMES.includes(c.name)
|
|
99
|
+
? runMeta(c.name, c.args) : base.execute(c.name, c.args)),
|
|
100
|
+
onSettle,
|
|
101
|
+
});
|
|
102
|
+
},
|
|
103
|
+
sched: {
|
|
104
|
+
classify: (n) => (n === "tool_call" ? "barrier"
|
|
105
|
+
: n === "tool_search" || n === "tool_describe" ? "read"
|
|
106
|
+
: base.sched ? base.sched.classify(n) : "write"),
|
|
107
|
+
keys: (n, a) => (base.sched ? base.sched.keys(n, a) : defaultKeys(n, a)),
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
export function deferredEnabled(mcpToolCount, env) {
|
|
112
|
+
if (env?.KODE_MCP_DEFER === "0")
|
|
113
|
+
return false;
|
|
114
|
+
if (env?.KODE_MCP_DEFER === "1")
|
|
115
|
+
return mcpToolCount > 0;
|
|
116
|
+
return mcpToolCount >= DEFERRED_THRESHOLD;
|
|
117
|
+
}
|
package/dist/tools/executor.js
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
// Interface consumed by the engine (Karpathy's lane):
|
|
3
3
|
// execute(name, args) -> Promise<string> one call; never throws, always resolves
|
|
4
4
|
// executeParallel(calls) -> Promise<string[]> one round's tool_calls, in input order;
|
|
5
|
-
//
|
|
6
|
-
//
|
|
5
|
+
// executed in input order: a contiguous run of safe
|
|
6
|
+
// (read-only) tools runs concurrently, every other
|
|
7
|
+
// call runs alone, awaited in place
|
|
7
8
|
// resetTurn() -> void clear loop-guard history; call once per
|
|
8
9
|
// new user turn (not required by SPEC §3's
|
|
9
10
|
// round loop itself, but needed so the guard
|
|
@@ -16,10 +17,14 @@ import { shellKeyStore } from "./shell-context.js";
|
|
|
16
17
|
import { capToolResult } from "./result-cap.js";
|
|
17
18
|
import { spillToolOutput } from "./tool-output-spill.js"; // GW-10: lossless eviction — spill big outputs, hand back a re-readable pointer
|
|
18
19
|
export { TOOL_RESULT_MAX_CHARS, capToolResult } from "./result-cap.js";
|
|
20
|
+
import { runBatch, defaultClassify, defaultKeys } from "../engine/batch-scheduler.js";
|
|
19
21
|
// Command tools whose working directory should default to the executor root (they take an optional `cwd`).
|
|
20
22
|
const CWD_TOOLS = new Set(["bash", "shell_exec", "shell_background", "git", "git_command", "git_status"]);
|
|
21
23
|
// Args that name a filesystem path the file tools read/write; a RELATIVE one is resolved under the root.
|
|
22
24
|
const PATH_ARGS = ["path", "file", "filename", "workspace"];
|
|
25
|
+
// Tools that take an optional `workspace` and otherwise fall back to process.cwd() — a rooted session must
|
|
26
|
+
// default it to its own root or the call lands in whatever directory the host process happens to run in.
|
|
27
|
+
const WORKSPACE_TOOLS = new Set(["checkpoint"]);
|
|
23
28
|
/** Reroot a tool call's args under `root` so a session's file/shell tools all act inside its own directory
|
|
24
29
|
* (e.g. a background agent's git worktree) instead of the shared process cwd. Pure: relative path args are
|
|
25
30
|
* joined under root; command tools default their cwd to root; absolute and ~ paths are left untouched
|
|
@@ -35,10 +40,12 @@ export function rootArgs(name, args, root) {
|
|
|
35
40
|
a.cwd = join(root, a.cwd);
|
|
36
41
|
else if (a.cwd == null && CWD_TOOLS.has(name))
|
|
37
42
|
a.cwd = root;
|
|
43
|
+
if (a.workspace == null && WORKSPACE_TOOLS.has(name))
|
|
44
|
+
a.workspace = root;
|
|
38
45
|
return a;
|
|
39
46
|
}
|
|
40
47
|
const LOOP_GUARD_THRESHOLD = 5; // must match agent.ts LOOP_GUARD_LIMIT so this secondary guard never fires first
|
|
41
|
-
import {
|
|
48
|
+
import { mutationLanded } from "./mutating.js"; // single source of truth (see tools/mutating.ts) — a LANDED workspace edit ⇒ prior identical-call counts are stale
|
|
42
49
|
const LOOP_GUARD_EXEMPT = new Set(["agent_status", "bash_output"]); // poll/status tools — repeated calls are legit, never guarded
|
|
43
50
|
// Unique fallback id per Executor instance, so two sessions with no sessionId and no root (the
|
|
44
51
|
// foreground and a read-only sub-agent lane) still get DISTINCT shell keys. One Executor lives for
|
|
@@ -81,9 +88,10 @@ export class Executor {
|
|
|
81
88
|
// Run the tool inside THIS session's shell-key context so a persistent-shell tool (bash) picks
|
|
82
89
|
// this session's own ShellSession, not a process-wide singleton shared with other sub-agents.
|
|
83
90
|
const out = capToolResult(await shellKeyStore.run(this.shellKey, () => tool.run(args)), spillToolOutput);
|
|
84
|
-
// A file edit changed the workspace, so prior identical-call counts are stale — re-running the
|
|
85
|
-
// test/build after an edit is verify-after-fix iteration, not a loop. Clear so repeats start fresh.
|
|
86
|
-
|
|
91
|
+
// A file edit that LANDED changed the workspace, so prior identical-call counts are stale — re-running the
|
|
92
|
+
// same test/build after an edit is verify-after-fix iteration, not a loop. Clear so repeats start fresh.
|
|
93
|
+
// A FAILING edit ("error: old_string not found") changed nothing, so it must not reset the count.
|
|
94
|
+
if (mutationLanded(name, out))
|
|
87
95
|
this.seen.clear();
|
|
88
96
|
return out;
|
|
89
97
|
}
|
|
@@ -91,23 +99,19 @@ export class Executor {
|
|
|
91
99
|
return `error running ${name}: ${e?.message ?? e}`;
|
|
92
100
|
}
|
|
93
101
|
}
|
|
102
|
+
sched = {
|
|
103
|
+
classify: defaultClassify("", (n) => this.reg.get(n)?.safe === true),
|
|
104
|
+
keys: defaultKeys,
|
|
105
|
+
};
|
|
94
106
|
async executeParallel(calls, onSettle) {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
}));
|
|
105
|
-
for (let i = 0; i < calls.length; i++) {
|
|
106
|
-
if (safeIdx.has(i))
|
|
107
|
-
continue;
|
|
108
|
-
results[i] = await this.execute(calls[i].name, calls[i].args);
|
|
109
|
-
onSettle?.(i, results[i]);
|
|
110
|
-
}
|
|
111
|
-
return results;
|
|
107
|
+
// BTX: one shared DAG scheduler (engine/batch-scheduler.ts) — per-resource write chains,
|
|
108
|
+
// reads wait only for conflicting prior writes, device tools barrier-serialize. This replaces
|
|
109
|
+
// the 0.1.225 contiguous walk: same guarantees, strictly more overlap.
|
|
110
|
+
return runBatch(calls, {
|
|
111
|
+
classify: this.sched.classify,
|
|
112
|
+
keys: (n, a) => this.sched.keys(n, a),
|
|
113
|
+
runOne: (c) => this.execute(c.name, c.args),
|
|
114
|
+
onSettle,
|
|
115
|
+
});
|
|
112
116
|
}
|
|
113
117
|
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
// Browser-safe: this module is reachable from the engine bundle through the tool registry, so the
|
|
2
|
+
// node builtins load via dynamic import — the same nodeImport pattern as registry.ts / sandbox.ts —
|
|
3
|
+
// keeping esbuild --platform=neutral from statically resolving them (index.browser.ts must stay
|
|
4
|
+
// node-free). On the mobile surface the tools run natively in Swift and never hit this path.
|
|
5
|
+
import { operatorPath } from "../config/home.js";
|
|
6
|
+
const nodeImport = (m) => import(/* @vite-ignore */ m);
|
|
7
|
+
let _fs = null;
|
|
8
|
+
let _path = null;
|
|
9
|
+
async function fsp() {
|
|
10
|
+
if (!_fs)
|
|
11
|
+
_fs = (await nodeImport("node:fs"));
|
|
12
|
+
if (!_path)
|
|
13
|
+
_path = (await nodeImport("node:path"));
|
|
14
|
+
return { fs: _fs, path: _path };
|
|
15
|
+
}
|
|
16
|
+
const BUDGETS = { memory: 2200, user: 1375 };
|
|
17
|
+
const TARGETS = { memory: "MEMORY.md", user: "USER.md" };
|
|
18
|
+
function filePath(target) { return operatorPath("memories", TARGETS[target]); }
|
|
19
|
+
function lockPath(target) { return filePath(target) + ".lock"; }
|
|
20
|
+
const LOCK_STALE_MS = 30_000; // a lock older than this belongs to a crashed writer — reclaim it
|
|
21
|
+
async function acquireLock(target) {
|
|
22
|
+
const { fs, path } = await fsp();
|
|
23
|
+
const lp = lockPath(target);
|
|
24
|
+
fs.mkdirSync(path.dirname(lp), { recursive: true });
|
|
25
|
+
const pid = globalThis.process?.pid ?? 0;
|
|
26
|
+
// "wx" = atomic create-exclusive — the race-free lock (existsSync+writeFileSync is TOCTOU).
|
|
27
|
+
// On EEXIST: reclaim the lock if it is stale (writer crashed), else report the live holder.
|
|
28
|
+
for (let attempt = 0;; attempt++) {
|
|
29
|
+
try {
|
|
30
|
+
fs.writeFileSync(lp, `${pid}\n`, { flag: "wx" });
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
catch (e) {
|
|
34
|
+
if (e?.code !== "EEXIST")
|
|
35
|
+
throw e;
|
|
36
|
+
let ageMs = 0;
|
|
37
|
+
try {
|
|
38
|
+
ageMs = Date.now() - fs.statSync(lp).mtimeMs;
|
|
39
|
+
}
|
|
40
|
+
catch { /* vanished mid-check — retry */ }
|
|
41
|
+
if (ageMs < LOCK_STALE_MS) {
|
|
42
|
+
let holder = "?";
|
|
43
|
+
try {
|
|
44
|
+
holder = fs.readFileSync(lp, "utf8").trim() || "?";
|
|
45
|
+
}
|
|
46
|
+
catch { /* best-effort */ }
|
|
47
|
+
throw new Error(`memory: ${target} is locked by pid ${holder} (${lp}) — another write is in progress`);
|
|
48
|
+
}
|
|
49
|
+
if (attempt >= 1)
|
|
50
|
+
throw new Error(`memory: ${target} lock could not be reclaimed (${lp})`);
|
|
51
|
+
try {
|
|
52
|
+
fs.unlinkSync(lp);
|
|
53
|
+
}
|
|
54
|
+
catch { /* someone else reclaimed it — loop retries the create */ }
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
async function releaseLock(target) {
|
|
59
|
+
try {
|
|
60
|
+
const { fs } = await fsp();
|
|
61
|
+
fs.unlinkSync(lockPath(target));
|
|
62
|
+
}
|
|
63
|
+
catch { /* best-effort */ }
|
|
64
|
+
}
|
|
65
|
+
export async function runMemoryTool(args) {
|
|
66
|
+
const target = String(args.target ?? "memory");
|
|
67
|
+
if (!TARGETS[target])
|
|
68
|
+
return `error: target must be 'memory' or 'user', got '${target}'`;
|
|
69
|
+
const ops = args.operations;
|
|
70
|
+
if (!Array.isArray(ops) || !ops.length)
|
|
71
|
+
return "error: operations must be a non-empty array of {action, content?, old_text?}";
|
|
72
|
+
const { fs, path } = await fsp();
|
|
73
|
+
const fp = filePath(target);
|
|
74
|
+
await acquireLock(target);
|
|
75
|
+
try {
|
|
76
|
+
let text = "";
|
|
77
|
+
try {
|
|
78
|
+
text = fs.readFileSync(fp, "utf8");
|
|
79
|
+
}
|
|
80
|
+
catch { /* file may not exist yet */ }
|
|
81
|
+
for (const op of ops) {
|
|
82
|
+
switch (op.action) {
|
|
83
|
+
case "add":
|
|
84
|
+
if (!op.content)
|
|
85
|
+
return "error: add needs content";
|
|
86
|
+
text = text ? text.trimEnd() + "\n" + op.content + "\n" : op.content + "\n";
|
|
87
|
+
break;
|
|
88
|
+
case "replace":
|
|
89
|
+
if (!op.old_text || !op.content)
|
|
90
|
+
return "error: replace needs old_text and content";
|
|
91
|
+
if (!text.includes(op.old_text))
|
|
92
|
+
return `error: old_text not found in ${TARGETS[target]}`;
|
|
93
|
+
text = text.replace(op.old_text, op.content);
|
|
94
|
+
break;
|
|
95
|
+
case "remove":
|
|
96
|
+
if (!op.old_text)
|
|
97
|
+
return "error: remove needs old_text";
|
|
98
|
+
if (!text.includes(op.old_text))
|
|
99
|
+
return `error: old_text not found in ${TARGETS[target]}`;
|
|
100
|
+
text = text.replace(op.old_text, "");
|
|
101
|
+
break;
|
|
102
|
+
default:
|
|
103
|
+
return `error: unknown action '${op.action}' — use add, replace, or remove`;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
text = text.replace(/\n{3,}/g, "\n\n").trim() + "\n";
|
|
107
|
+
const budget = BUDGETS[target];
|
|
108
|
+
if (text.length > budget)
|
|
109
|
+
return `error: result is ${text.length} chars, exceeds ${target} budget of ${budget} — reduce content`;
|
|
110
|
+
fs.mkdirSync(path.dirname(fp), { recursive: true });
|
|
111
|
+
fs.writeFileSync(fp, text);
|
|
112
|
+
return `wrote ${TARGETS[target]} (${text.length}/${budget} chars, ${ops.length} op${ops.length === 1 ? "" : "s"} applied)`;
|
|
113
|
+
}
|
|
114
|
+
finally {
|
|
115
|
+
await releaseLock(target);
|
|
116
|
+
}
|
|
117
|
+
}
|
package/dist/tools/mutating.js
CHANGED
|
@@ -7,3 +7,9 @@
|
|
|
7
7
|
export const MUTATING_TOOLS = new Set(["file_write", "file_edit"]);
|
|
8
8
|
/** True when a tool call's name is a workspace mutation. Tolerates undefined (a malformed/partial call). */
|
|
9
9
|
export const isMutatingTool = (name) => MUTATING_TOOLS.has(name ?? "");
|
|
10
|
+
/** True when a mutating call actually LANDED. file_write/file_edit report failure as a returned `error: …`
|
|
11
|
+
* string (not a throw), and a gated/denied or loop-guarded call never ran, so the tool NAME alone proves
|
|
12
|
+
* nothing. The loop-guard clears its identical-call counts only on a landed mutation — a failing edit must not
|
|
13
|
+
* grant a spinning model a fresh runway (the model can otherwise alternate a failing edit with the same
|
|
14
|
+
* poisoned call forever). */
|
|
15
|
+
export const mutationLanded = (name, result) => isMutatingTool(name) && !/^(?:error|loop guard|permission denied)/i.test(result.trimStart());
|