@0perator/operator 0.1.235 → 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 +2 -1
- package/dashboard/server.mjs +1 -1
- package/dist/acp/agent.js +290 -62
- package/dist/acp/auth.js +44 -0
- package/dist/acp/prompt.js +41 -0
- package/dist/acp/run.js +40 -15
- package/dist/acp/tool-map.js +48 -0
- package/dist/auth/byo.js +15 -8
- package/dist/auth/client.js +12 -6
- package/dist/auth/commands.js +39 -4
- 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/media-robot.js +2 -3
- package/dist/autonomy/routines.js +5 -4
- package/dist/autonomy/session-factory.js +6 -1
- package/dist/browser/cdp.js +266 -0
- package/dist/browser/session.js +286 -0
- package/dist/cli.js +75 -11
- 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 +59 -9
- package/dist/config/scaffold.js +142 -0
- package/dist/config/settings.js +38 -4
- package/dist/config/skills-index.js +175 -0
- package/dist/consolidation/scheduler.js +3 -3
- package/dist/consolidation/sleep.js +3 -3
- package/dist/engine/agent.js +80 -13
- package/dist/engine/aurora.js +6 -0
- package/dist/engine/batch-scheduler.js +128 -0
- package/dist/engine/json-repair.js +105 -0
- package/dist/engine/messages.js +50 -3
- package/dist/engine/rolling-summary.js +7 -5
- package/dist/enterprise/cli.js +137 -0
- package/dist/flywheel/processor.js +30 -2
- package/dist/flywheel/secret-gate.js +123 -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/index.js +24 -12
- package/dist/router/models.js +27 -8
- package/dist/selfimprove/index.js +9 -7
- package/dist/session.js +16 -6
- package/dist/skills/catalogue.js +167 -0
- package/dist/telemetry/audit-verify.js +94 -0
- package/dist/telemetry/events.js +86 -6
- package/dist/telemetry/lifecycle.js +18 -0
- package/dist/tools/deferred.js +117 -0
- package/dist/tools/executor.js +19 -20
- package/dist/tools/memory.js +117 -0
- package/dist/tools/registry.js +152 -21
- package/dist/tools/sandbox.js +63 -17
- package/dist/tools/searxng.js +2 -2
- package/dist/tools/tool-output-spill.js +2 -2
- package/dist/ui/Transcript.js +14 -2
- package/dist/ui/useInputHistory.js +3 -3
- 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 -2487
- package/dist/ui/BusTray.js +0 -70
package/dist/session.js
CHANGED
|
@@ -9,8 +9,8 @@ import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
|
|
|
9
9
|
import { spillToolOutput } from "./tools/tool-output-spill.js"; // GW-10-COMPLETE: node-side spill sink
|
|
10
10
|
import { engineRouter } from "./engine/router-adapter.js";
|
|
11
11
|
import { appendFileSync, mkdirSync } from "node:fs";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
12
|
+
import { dirname } from "node:path";
|
|
13
|
+
import { operatorPath } from "./config/home.js";
|
|
14
14
|
import { fanOutProposers, labelDrafts, DEFAULT_AGGREGATOR_PROMPT } from "./engine/moa.js";
|
|
15
15
|
import { AuroraRouter } from "./router/router.js";
|
|
16
16
|
import { operatorAgentPersona } from "./config/operator-harness.js";
|
|
@@ -20,6 +20,7 @@ import { Executor } from "./tools/executor.js";
|
|
|
20
20
|
import { toSchemas, registry, disposeShellSessionKey } from "./tools/registry.js";
|
|
21
21
|
import { MemoryStore } from "./memory/index.js";
|
|
22
22
|
import { McpHub, withMcp } from "./mcp/index.js";
|
|
23
|
+
import { deferredEnabled, deferredRequestSchemas, deferredState, withDeferred } from "./tools/deferred.js";
|
|
23
24
|
import { withPermissions, PermissionPolicy } from "./permissions/index.js";
|
|
24
25
|
import { Telemetry } from "./observability/index.js";
|
|
25
26
|
import { runSelfImprove } from "./selfimprove/index.js";
|
|
@@ -234,6 +235,7 @@ export class Session {
|
|
|
234
235
|
eventActor;
|
|
235
236
|
sessionId;
|
|
236
237
|
mcpSchemas = []; // merged in after first-turn discovery (empty until then)
|
|
238
|
+
deferred = null; // HV3-04: set when the MCP surface crosses the threshold
|
|
237
239
|
wantMcp; // mutable: `/mcp on` flips it for the live session (enableMcp)
|
|
238
240
|
systemPrompt;
|
|
239
241
|
maxTokens;
|
|
@@ -266,7 +268,7 @@ export class Session {
|
|
|
266
268
|
// Calibration durability (SPEC §5, token-meter): learned chars/token persist beside the operator
|
|
267
269
|
// state dir, so the FIRST deep session after a restart already sizes correctly instead of running
|
|
268
270
|
// on the cold prior. Best-effort by construction: a no-op off node, a cold start on corrupt/missing.
|
|
269
|
-
globalTokenMeter.setPersistence(
|
|
271
|
+
globalTokenMeter.setPersistence(operatorPath("token-calibration.json"));
|
|
270
272
|
// Per-session tool registry: the base set, plus `spawn_agent` when the shell provides a delegate
|
|
271
273
|
// handler (foreground only). Both the executor (dispatch) and localSchemas (what the model sees)
|
|
272
274
|
// are built from the same map, so the tool is advertised iff it's runnable.
|
|
@@ -367,7 +369,8 @@ export class Session {
|
|
|
367
369
|
? new PermissionPolicy({ mode: "gated", tier: this.policy.currentTier() }) // read-only: safe tools allow, mutating ask→deny (no approve fn)
|
|
368
370
|
: this.policy;
|
|
369
371
|
const approve = this.planMode ? undefined : this.approve; // no approver in plan mode = hard read-only
|
|
370
|
-
|
|
372
|
+
const base = withPermissions(withMcp(this.executor, this.hub), policy, { approve, sink: this.eventSink, actor: this.eventActor, session: this.sessionId });
|
|
373
|
+
return this.deferred ? withDeferred(base, this.deferred) : base;
|
|
371
374
|
}
|
|
372
375
|
/** Enter/leave plan mode (/plan). Read-only research + a proposed plan until the owner approves. */
|
|
373
376
|
setPlanMode(on) {
|
|
@@ -655,7 +658,7 @@ export class Session {
|
|
|
655
658
|
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
|
|
656
659
|
this.handoffFile = envFile && envFile.trim()
|
|
657
660
|
? envFile
|
|
658
|
-
:
|
|
661
|
+
: operatorPath("handoff", `session-${stamp}.md`);
|
|
659
662
|
mkdirSync(dirname(this.handoffFile), { recursive: true });
|
|
660
663
|
}
|
|
661
664
|
const block = `\n## Auto-compaction @ ${new Date().toISOString()} (evicted ${evicted} msg)\n\n${summary}\n`;
|
|
@@ -712,6 +715,10 @@ export class Session {
|
|
|
712
715
|
await this.hub.discover();
|
|
713
716
|
this.tools = this.buildTools(); // rebind so dispatch sees the discovered tools
|
|
714
717
|
this.mcpSchemas = this.hub.schemas();
|
|
718
|
+
// HV3-04: when the MCP surface is fat, its schemas stop riding every request — they move
|
|
719
|
+
// behind tool_search/describe/call meta-tools, loaded on demand.
|
|
720
|
+
this.deferred = deferredEnabled(this.mcpSchemas.length, globalThis.process?.env) ? deferredState(this.mcpSchemas) : null;
|
|
721
|
+
this.tools = this.buildTools(); // rebind again so the deferred layer wraps the permission stack
|
|
715
722
|
}
|
|
716
723
|
catch { /* gateway unreachable — stay local-only */ }
|
|
717
724
|
}
|
|
@@ -722,8 +729,11 @@ export class Session {
|
|
|
722
729
|
await this.discoverMcp();
|
|
723
730
|
return this.mcpToolCount();
|
|
724
731
|
}
|
|
725
|
-
/** Local registry schemas plus any fleet MCP tool schemas discovered this session.
|
|
732
|
+
/** Local registry schemas plus any fleet MCP tool schemas discovered this session.
|
|
733
|
+
* Under HV3-04 deferral: locals + only the MCP tools described this session + the meta trio. */
|
|
726
734
|
allSchemas() {
|
|
735
|
+
if (this.deferred)
|
|
736
|
+
return deferredRequestSchemas(this.localSchemas, this.deferred);
|
|
727
737
|
return this.mcpSchemas.length ? [...this.localSchemas, ...this.mcpSchemas] : this.localSchemas;
|
|
728
738
|
}
|
|
729
739
|
/** How many fleet MCP tools were discovered this session (0 until first turn / if MCP is off). */
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// HV3-07 — official optional-skills catalogue: browse/install/remove against the gated catalog that
|
|
2
|
+
// ships in the repo (operator-home/skills-catalogue/), activating a skill = copying its tree into
|
|
3
|
+
// $KODE_HOME/skills/<category>/<name>/ where the operator-home-v2 phase-3 local-skills index picks it
|
|
4
|
+
// up immediately (skill_list/skill_fetch unchanged). Nothing in the catalogue is ever injected on its
|
|
5
|
+
// own — that gating is the whole point (Hermes ships these as "not activated by default").
|
|
6
|
+
// Node builtins stay behind lazy variable-specifier imports (purity contract, session-rewind idiom).
|
|
7
|
+
import { operatorPath } from "../config/home.js";
|
|
8
|
+
async function nodeImport(id) {
|
|
9
|
+
const g = globalThis;
|
|
10
|
+
try {
|
|
11
|
+
const m = g.process?.getBuiltinModule?.(id);
|
|
12
|
+
if (m)
|
|
13
|
+
return m;
|
|
14
|
+
}
|
|
15
|
+
catch { /* dynamic */ }
|
|
16
|
+
const spec = id;
|
|
17
|
+
return import(spec);
|
|
18
|
+
}
|
|
19
|
+
/** Catalogue root; overridable for tests via env, else repo-relative to this module. */
|
|
20
|
+
export function catalogueDir() {
|
|
21
|
+
const env = globalThis.process?.env;
|
|
22
|
+
if (env?.KODE_CATALOGUE_DIR)
|
|
23
|
+
return env.KODE_CATALOGUE_DIR;
|
|
24
|
+
// src/skills/catalogue.ts and dist/skills/catalogue.js are both two levels below kode-tsi/.
|
|
25
|
+
// import.meta is absent in the neutral iife bundle (schema-side reach only, run() never fires
|
|
26
|
+
// there) — try/catch degrades to "" and existsSync() reports "no catalogue" instead of throwing.
|
|
27
|
+
try {
|
|
28
|
+
return new URL("../../operator-home/skills-catalogue", import.meta.url).pathname;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return "";
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
function parseFrontmatter(text) {
|
|
35
|
+
const m = /^---\n([\s\S]*?)\n---/.exec(text);
|
|
36
|
+
if (!m)
|
|
37
|
+
return {};
|
|
38
|
+
const out = {};
|
|
39
|
+
for (const line of m[1].split("\n")) {
|
|
40
|
+
const kv = /^(name|description)\s*:\s*(.+)$/.exec(line);
|
|
41
|
+
if (kv)
|
|
42
|
+
out[kv[1]] = kv[2].replace(/^["']|["']$/g, "").trim();
|
|
43
|
+
}
|
|
44
|
+
return out;
|
|
45
|
+
}
|
|
46
|
+
/** Walk the catalogue at ANY depth: <cat>/<skill>, <cat>/<group>/<skill>, <cat>/SKILL.md all
|
|
47
|
+
* resolve to one entry each — the count browse reports always equals the SKILL.md count on disk
|
|
48
|
+
* (the live e2e asserts exactly this; the fixed-depth version shipped blind to mlops subgroups). */
|
|
49
|
+
export async function listCatalogue() {
|
|
50
|
+
const fs = await nodeImport("node:fs");
|
|
51
|
+
const path = await nodeImport("node:path");
|
|
52
|
+
const root = catalogueDir();
|
|
53
|
+
if (!root || !fs.existsSync(root))
|
|
54
|
+
return [];
|
|
55
|
+
const out = [];
|
|
56
|
+
const found = [];
|
|
57
|
+
const walk = (dir, rel) => {
|
|
58
|
+
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
59
|
+
if (!e.isDirectory() || e.name.startsWith("."))
|
|
60
|
+
continue;
|
|
61
|
+
const sub = path.join(dir, e.name);
|
|
62
|
+
const rsub = rel ? `${rel}/${e.name}` : e.name;
|
|
63
|
+
if (fs.existsSync(path.join(sub, "SKILL.md")))
|
|
64
|
+
found.push({ dir: sub, rel: rsub });
|
|
65
|
+
else
|
|
66
|
+
walk(sub, rsub);
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
walk(root, "");
|
|
70
|
+
for (const { dir, rel } of found) {
|
|
71
|
+
const fm = parseFrontmatter(fs.readFileSync(path.join(dir, "SKILL.md"), "utf8"));
|
|
72
|
+
let files = 0;
|
|
73
|
+
try {
|
|
74
|
+
const count = (d) => { for (const e of fs.readdirSync(d, { withFileTypes: true })) {
|
|
75
|
+
if (e.isDirectory())
|
|
76
|
+
count(path.join(d, e.name));
|
|
77
|
+
else
|
|
78
|
+
files++;
|
|
79
|
+
} };
|
|
80
|
+
count(dir);
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
files = 1;
|
|
84
|
+
}
|
|
85
|
+
out.push({
|
|
86
|
+
category: rel.split("/")[0] ?? rel,
|
|
87
|
+
name: fm.name?.trim() ? fm.name.trim() : path.basename(dir),
|
|
88
|
+
description: (fm.description ?? "").slice(0, 140),
|
|
89
|
+
path: rel,
|
|
90
|
+
files,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
return out.sort((a, b) => a.category.localeCompare(b.category) || a.name.localeCompare(b.name));
|
|
94
|
+
}
|
|
95
|
+
/** Install = copy the tree into $KODE_HOME/skills/<path> + a source marker; refuses overwrite. */
|
|
96
|
+
export async function installSkill(name) {
|
|
97
|
+
const fs = await nodeImport("node:fs");
|
|
98
|
+
const path = await nodeImport("node:path");
|
|
99
|
+
const entry = (await listCatalogue()).find((e) => e.name === name);
|
|
100
|
+
if (!entry)
|
|
101
|
+
return `skill_catalog: '${name}' not in the catalogue (browse first)`;
|
|
102
|
+
const dest = operatorPath("skills", entry.category, name);
|
|
103
|
+
if (fs.existsSync(dest))
|
|
104
|
+
return `skill_catalog: already installed at skills/${entry.category}/${name} (remove first to reinstall)`;
|
|
105
|
+
const src = path.join(catalogueDir(), entry.path);
|
|
106
|
+
try {
|
|
107
|
+
fs.cpSync(src, dest, { recursive: true });
|
|
108
|
+
fs.writeFileSync(path.join(dest, ".from-catalogue"), `source: operator-home/skills-catalogue/${entry.path}\ninstalled: ${new Date().toISOString()}\n`);
|
|
109
|
+
}
|
|
110
|
+
catch (e) {
|
|
111
|
+
return `skill_catalog install failed: ${e.message}`;
|
|
112
|
+
}
|
|
113
|
+
return `installed '${name}' (${entry.category}, ${entry.files} files) -> skills/${entry.path} — live in skill_list/skill_fetch next session; ${entry.description.slice(0, 80)}`;
|
|
114
|
+
}
|
|
115
|
+
/** Remove = delete ONLY catalogue-marked trees (never a hand-written skill dir). */
|
|
116
|
+
export async function removeSkill(name) {
|
|
117
|
+
const fs = await nodeImport("node:fs");
|
|
118
|
+
const path = await nodeImport("node:path");
|
|
119
|
+
const home = operatorPath("skills");
|
|
120
|
+
let hits = [];
|
|
121
|
+
try {
|
|
122
|
+
for (const cat of fs.readdirSync(home, { withFileTypes: true })) {
|
|
123
|
+
if (!cat.isDirectory())
|
|
124
|
+
continue;
|
|
125
|
+
const cand = path.join(home, cat.name, name);
|
|
126
|
+
if (fs.existsSync(path.join(cand, ".from-catalogue")))
|
|
127
|
+
hits.push(cand);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
catch { /* no skills dir */ }
|
|
131
|
+
if (!hits.length)
|
|
132
|
+
return `skill_catalog: no catalogue-installed '${name}' found (hand-installed skills are never removed here)`;
|
|
133
|
+
try {
|
|
134
|
+
for (const h of hits)
|
|
135
|
+
fs.rmSync(h, { recursive: true, force: true });
|
|
136
|
+
}
|
|
137
|
+
catch (e) {
|
|
138
|
+
return `skill_catalog remove failed: ${e.message}`;
|
|
139
|
+
}
|
|
140
|
+
return `removed ${hits.length} installed copy(ies) of '${name}' (catalogue source untouched)`;
|
|
141
|
+
}
|
|
142
|
+
/** run() for the `skill_catalog` registry tool. */
|
|
143
|
+
export async function runSkillCatalog(args) {
|
|
144
|
+
const action = String(args.action ?? "browse");
|
|
145
|
+
try {
|
|
146
|
+
if (action === "browse") {
|
|
147
|
+
const entries = await listCatalogue();
|
|
148
|
+
if (!entries.length)
|
|
149
|
+
return "skill_catalog: no catalogue present (operator-home/skills-catalogue missing)";
|
|
150
|
+
const q = String(args.query ?? "").toLowerCase();
|
|
151
|
+
const matched = entries.filter((e) => !q || e.name.toLowerCase().includes(q) || e.category.toLowerCase().includes(q) || e.description.toLowerCase().includes(q));
|
|
152
|
+
const shown = matched.slice(0, 120);
|
|
153
|
+
const cats = new Set(matched.map((e) => e.category));
|
|
154
|
+
return `${matched.length} of ${entries.length} catalogue entries (${cats.size} categories)\n` +
|
|
155
|
+
shown.map((e) => `${e.name} [${e.category}] — ${e.description}`).join("\n") +
|
|
156
|
+
(matched.length > shown.length ? `\n… +${matched.length - shown.length} more — refine with query` : "");
|
|
157
|
+
}
|
|
158
|
+
if (action === "install")
|
|
159
|
+
return await installSkill(String(args.name ?? ""));
|
|
160
|
+
if (action === "remove")
|
|
161
|
+
return await removeSkill(String(args.name ?? ""));
|
|
162
|
+
return `skill_catalog: unknown action '${action}' (browse|install|remove)`;
|
|
163
|
+
}
|
|
164
|
+
catch (e) {
|
|
165
|
+
return `skill_catalog error: ${e.message}`;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
@@ -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
|
@@ -12,16 +12,43 @@ const nodeImport = (m) => import(/* @vite-ignore */ m);
|
|
|
12
12
|
// redact is pure regex + node-free — the static import keeps this module bundle-safe (GW-10 graph).
|
|
13
13
|
import { redactSecrets } from "../engine/redact.js";
|
|
14
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
|
+
};
|
|
15
28
|
/** Emits OperatorEvents to a local JSONL file and, if configured, an HTTP sink. Both best-effort. The
|
|
16
|
-
* 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. */
|
|
17
37
|
export class EventSink {
|
|
18
38
|
file;
|
|
19
39
|
url;
|
|
20
40
|
onEvent;
|
|
21
41
|
subscribers = new Set();
|
|
22
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;
|
|
23
49
|
constructor(opts = {}) {
|
|
24
|
-
this.file = opts.file ??
|
|
50
|
+
this.file = opts.file ?? defaultEventsFile();
|
|
51
|
+
this.rotateEvery = opts.rotateEvery ?? 50;
|
|
25
52
|
this.url = opts.url ?? process.env.KODE_TELEMETRY_URL;
|
|
26
53
|
// In-process callback bridge — the ONLY path that works on mobile (JSCore has no fs and the phone is
|
|
27
54
|
// not a KODE_TELEMETRY_URL backend), same pattern as the bg-agents host bridge. A native/web host sets
|
|
@@ -55,18 +82,71 @@ export class EventSink {
|
|
|
55
82
|
}
|
|
56
83
|
async write(e) {
|
|
57
84
|
try {
|
|
58
|
-
const [
|
|
59
|
-
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"),
|
|
60
87
|
]);
|
|
61
88
|
const file = this.file.startsWith("~/") ? join(os.homedir(), this.file.slice(2)) : this.file;
|
|
62
|
-
await mkdir(dirname(file), { recursive: true, mode: 0o700 });
|
|
89
|
+
await fsp.mkdir(dirname(file), { recursive: true, mode: 0o700 });
|
|
90
|
+
await this.maybeRotate(file, fsp, join, dirname);
|
|
63
91
|
// H4 (audit-tools §1): events sit next to bearer-token args in tool payloads; the file was
|
|
64
92
|
// world-readable by default and unmasked. 0700/0600 + redactSecrets — the POST sink below gets
|
|
65
93
|
// the identical treatment; claims of "secret-free" in this file's header are now ENFORCED.
|
|
66
|
-
|
|
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++;
|
|
67
102
|
}
|
|
68
103
|
catch { /* best-effort: no fs (mobile) or a write failure must never break a turn */ }
|
|
69
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
|
+
}
|
|
70
150
|
async post(e) {
|
|
71
151
|
if (!this.url)
|
|
72
152
|
return;
|
|
@@ -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
|
+
}
|
|
@@ -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
|
+
}
|