@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.
Files changed (68) hide show
  1. package/README.md +2 -1
  2. package/dashboard/server.mjs +1 -1
  3. package/dist/acp/agent.js +290 -62
  4. package/dist/acp/auth.js +44 -0
  5. package/dist/acp/prompt.js +41 -0
  6. package/dist/acp/run.js +40 -15
  7. package/dist/acp/tool-map.js +48 -0
  8. package/dist/auth/byo.js +15 -8
  9. package/dist/auth/client.js +12 -6
  10. package/dist/auth/commands.js +39 -4
  11. package/dist/auth/identity.js +136 -0
  12. package/dist/auth/store.js +7 -5
  13. package/dist/autonomy/board.js +3 -2
  14. package/dist/autonomy/cron.js +332 -0
  15. package/dist/autonomy/delegate.js +168 -0
  16. package/dist/autonomy/media-robot.js +2 -3
  17. package/dist/autonomy/routines.js +5 -4
  18. package/dist/autonomy/session-factory.js +6 -1
  19. package/dist/browser/cdp.js +266 -0
  20. package/dist/browser/session.js +286 -0
  21. package/dist/cli.js +75 -11
  22. package/dist/config/brand.js +3 -3
  23. package/dist/config/home.js +70 -0
  24. package/dist/config/managed.js +230 -0
  25. package/dist/config/persona.js +59 -9
  26. package/dist/config/scaffold.js +142 -0
  27. package/dist/config/settings.js +38 -4
  28. package/dist/config/skills-index.js +175 -0
  29. package/dist/consolidation/scheduler.js +3 -3
  30. package/dist/consolidation/sleep.js +3 -3
  31. package/dist/engine/agent.js +80 -13
  32. package/dist/engine/aurora.js +6 -0
  33. package/dist/engine/batch-scheduler.js +128 -0
  34. package/dist/engine/json-repair.js +105 -0
  35. package/dist/engine/messages.js +50 -3
  36. package/dist/engine/rolling-summary.js +7 -5
  37. package/dist/enterprise/cli.js +137 -0
  38. package/dist/flywheel/processor.js +30 -2
  39. package/dist/flywheel/secret-gate.js +123 -0
  40. package/dist/mcp/index.js +18 -24
  41. package/dist/memory/index.js +0 -0
  42. package/dist/memory/session-index.js +324 -0
  43. package/dist/memory/session-rewind.js +92 -0
  44. package/dist/memory/state-maintenance.js +441 -0
  45. package/dist/observability/index.js +3 -3
  46. package/dist/permissions/index.js +24 -12
  47. package/dist/router/models.js +27 -8
  48. package/dist/selfimprove/index.js +9 -7
  49. package/dist/session.js +16 -6
  50. package/dist/skills/catalogue.js +167 -0
  51. package/dist/telemetry/audit-verify.js +94 -0
  52. package/dist/telemetry/events.js +86 -6
  53. package/dist/telemetry/lifecycle.js +18 -0
  54. package/dist/tools/deferred.js +117 -0
  55. package/dist/tools/executor.js +19 -20
  56. package/dist/tools/memory.js +117 -0
  57. package/dist/tools/registry.js +152 -21
  58. package/dist/tools/sandbox.js +63 -17
  59. package/dist/tools/searxng.js +2 -2
  60. package/dist/tools/tool-output-spill.js +2 -2
  61. package/dist/ui/Transcript.js +14 -2
  62. package/dist/ui/useInputHistory.js +3 -3
  63. package/dist/vault/cli.js +48 -0
  64. package/dist/vault/store.js +157 -0
  65. package/dist/vault/tool.js +50 -0
  66. package/package.json +3 -5
  67. package/CHANGELOG.md +0 -2487
  68. package/dist/ui/BusTray.js +0 -70
@@ -0,0 +1,441 @@
1
+ // State hygiene for the operator home (operator-home-v2 HV3-05a): a self-healing audit-and-repair
2
+ // layer over the session-index store at $KODE_HOME/state/state.db (and its JSON fallback at
3
+ // state/session-index.json, see src/memory/session-index.ts).
4
+ //
5
+ // The store is DERIVED data — every byte in it is re-indexable from $KODE_HOME/sessions/*.json —
6
+ // which makes aggressive repair safe: a corrupt or desynced store is quarantined (renamed
7
+ // `<name>.corrupt-<ts>`, never deleted) and rebuilt from the transcripts. The one thing we never
8
+ // touch is a store that is merely LOCKED by a concurrent writer; "database is locked" is health,
9
+ // not damage, and quarantining it would yank the rug out from under the live process.
10
+ //
11
+ // Surface (exported module only; parent wires registry/cron/home):
12
+ // inspectState() read-only audit — reports issues, repairs nothing;
13
+ // maintainState() audit + self-heal + verify, writes a heartbeat summary to
14
+ // state/maintenance.json; idempotent, safe to call every session.
15
+ // stateMaintenanceStatus() last summary (for the home surface / cron alerting), null before
16
+ // the first run.
17
+ //
18
+ // Browser-safe: node builtins load lazily (same dynamic-import idiom as session-index.ts) and
19
+ // without fs everything degrades to a clean no-op report — index.browser.ts must keep passing the
20
+ // esbuild --platform=neutral purity gate.
21
+ import { get_operator_home, operatorPath } from "../config/home.js";
22
+ import { indexSessions, sessionIndexBackendKind } from "./session-index.js";
23
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
24
+ let _fs = null;
25
+ let _path = null;
26
+ async function fsp() {
27
+ if (!_fs)
28
+ _fs = (await nodeImport("node:fs"));
29
+ if (!_path)
30
+ _path = (await nodeImport("node:path"));
31
+ return { fs: _fs, path: _path };
32
+ }
33
+ /** fs/path, or null on node-free hosts (JSCore/browser) where maintenance is a no-op. */
34
+ async function tryFs() {
35
+ try {
36
+ return await fsp();
37
+ }
38
+ catch {
39
+ return null;
40
+ }
41
+ }
42
+ const SQLITE_SIDECARS = ["-wal", "-shm", "-journal"];
43
+ const errMsg = (e) => (e instanceof Error ? e.message : String(e));
44
+ /** First value of the first row of a `.all()` result (PRAGMA/count queries vary in column name). */
45
+ function firstValue(rows) {
46
+ const row = rows[0];
47
+ if (row && typeof row === "object") {
48
+ const vals = Object.values(row);
49
+ if (vals.length)
50
+ return String(vals[0]);
51
+ }
52
+ return String(row);
53
+ }
54
+ function issue(code, detail) {
55
+ return { code, detail };
56
+ }
57
+ /** Map a sqlite/fs error onto our three repair classes: busy (hands-off), missing schema (create),
58
+ * anything else (treat the file as damaged — the store is re-derivable, quarantine is safe). */
59
+ function classifyError(err) {
60
+ const msg = errMsg(err);
61
+ if (/locked|busy/i.test(msg))
62
+ return "locked";
63
+ if (/no such table/i.test(msg))
64
+ return "schema";
65
+ return "damaged";
66
+ }
67
+ function emptyScan() {
68
+ return {
69
+ backend: "none", storeFile: null, sessions: new Map(), indexed: new Map(),
70
+ orphans: [], drifted: 0, issues: [], locked: false, needsQuarantine: false,
71
+ staleSidecarFiles: [],
72
+ };
73
+ }
74
+ async function listTranscripts(fs, path) {
75
+ const out = new Map();
76
+ const dir = operatorPath("sessions");
77
+ let names;
78
+ try {
79
+ names = fs.readdirSync(dir);
80
+ }
81
+ catch {
82
+ return out; // no sessions dir — nothing that should be indexed
83
+ }
84
+ for (const name of names) {
85
+ if (!name.endsWith(".json"))
86
+ continue;
87
+ try {
88
+ const st = fs.statSync(path.join(dir, name));
89
+ if (st.isFile())
90
+ out.set(name.slice(0, -".json".length), st.mtimeMs);
91
+ }
92
+ catch {
93
+ /* vanished mid-scan — a later run sees the truth */
94
+ }
95
+ }
96
+ return out;
97
+ }
98
+ async function openSqliteDb(dbFile) {
99
+ const sqlite = await nodeImport("node:sqlite");
100
+ if (!sqlite?.DatabaseSync)
101
+ throw new Error("node:sqlite unavailable");
102
+ return new sqlite.DatabaseSync(dbFile);
103
+ }
104
+ async function scanSqlite(dbFile) {
105
+ const issues = [];
106
+ const indexed = new Map();
107
+ let db;
108
+ try {
109
+ db = await openSqliteDb(dbFile);
110
+ }
111
+ catch (err) {
112
+ const k = classifyError(err);
113
+ if (k === "locked")
114
+ return { issues: [issue("locked-store", `state.db: ${errMsg(err)}`)], indexed, locked: true, needsQuarantine: false };
115
+ return { issues: [issue("corrupt-store", `state.db cannot be opened: ${errMsg(err)}`)], indexed, locked: false, needsQuarantine: true };
116
+ }
117
+ try {
118
+ try {
119
+ const rows = db.prepare("PRAGMA integrity_check").all();
120
+ const verdict = rows.length ? firstValue(rows) : "ok";
121
+ if (verdict !== "ok") {
122
+ return { issues: [issue("corrupt-store", `integrity_check: ${verdict}`)], indexed, locked: false, needsQuarantine: true };
123
+ }
124
+ }
125
+ catch (err) {
126
+ const k = classifyError(err);
127
+ if (k === "locked")
128
+ return { issues: [issue("locked-store", `integrity_check: ${errMsg(err)}`)], indexed, locked: true, needsQuarantine: false };
129
+ return { issues: [issue("corrupt-store", `integrity_check: ${errMsg(err)}`)], indexed, locked: false, needsQuarantine: true };
130
+ }
131
+ let metaRows;
132
+ try {
133
+ metaRows = db.prepare("SELECT id, mtime FROM sessions_meta").all();
134
+ }
135
+ catch (err) {
136
+ const k = classifyError(err);
137
+ if (k === "locked")
138
+ return { issues: [issue("locked-store", `sessions_meta: ${errMsg(err)}`)], indexed, locked: true, needsQuarantine: false };
139
+ if (k === "schema")
140
+ return { issues: [issue("schema-missing", "state.db has no sessions_meta table")], indexed, locked: false, needsQuarantine: false };
141
+ return { issues: [issue("corrupt-store", `sessions_meta: ${errMsg(err)}`)], indexed, locked: false, needsQuarantine: true };
142
+ }
143
+ for (const row of metaRows) {
144
+ indexed.set(String(row.id), Number(row.mtime));
145
+ }
146
+ try {
147
+ const ftsCount = Number(firstValue(db.prepare("SELECT count(*) AS n FROM sessions_fts").all()));
148
+ if (Number.isFinite(ftsCount) && ftsCount !== indexed.size) {
149
+ return {
150
+ issues: [issue("index-desync", `sessions_meta has ${indexed.size} rows, sessions_fts has ${ftsCount}`)],
151
+ indexed, locked: false, needsQuarantine: true,
152
+ };
153
+ }
154
+ }
155
+ catch (err) {
156
+ const k = classifyError(err);
157
+ if (k === "locked")
158
+ return { issues: [issue("locked-store", `sessions_fts: ${errMsg(err)}`)], indexed, locked: true, needsQuarantine: false };
159
+ if (k === "schema")
160
+ return { issues: [issue("index-desync", "state.db has no sessions_fts table")], indexed, locked: false, needsQuarantine: true };
161
+ return { issues: [issue("corrupt-store", `sessions_fts: ${errMsg(err)}`)], indexed, locked: false, needsQuarantine: true };
162
+ }
163
+ return { issues, indexed, locked: false, needsQuarantine: false };
164
+ }
165
+ finally {
166
+ try {
167
+ db.close();
168
+ }
169
+ catch {
170
+ /* best-effort */
171
+ }
172
+ }
173
+ }
174
+ function scanJson(fs, jsonFile) {
175
+ const indexed = new Map();
176
+ let raw;
177
+ try {
178
+ raw = fs.readFileSync(jsonFile, "utf8");
179
+ }
180
+ catch (err) {
181
+ const k = classifyError(err);
182
+ if (k === "locked")
183
+ return { issues: [issue("locked-store", `session-index.json: ${errMsg(err)}`)], indexed, locked: true, needsQuarantine: false };
184
+ return { issues: [issue("unreadable-store", `session-index.json: ${errMsg(err)}`)], indexed, locked: false, needsQuarantine: true };
185
+ }
186
+ let parsed;
187
+ try {
188
+ parsed = JSON.parse(raw);
189
+ }
190
+ catch (err) {
191
+ return { issues: [issue("corrupt-store", `session-index.json is not valid JSON: ${errMsg(err)}`)], indexed, locked: false, needsQuarantine: true };
192
+ }
193
+ if (parsed?.version !== 1 || !parsed.entries || typeof parsed.entries !== "object") {
194
+ return { issues: [issue("corrupt-store", "session-index.json has an unexpected shape (expected { version: 1, entries })")], indexed, locked: false, needsQuarantine: true };
195
+ }
196
+ for (const [id, e] of Object.entries(parsed.entries)) {
197
+ indexed.set(id, Number(e?.mtimeMs));
198
+ }
199
+ return { issues: [], indexed, locked: false, needsQuarantine: false };
200
+ }
201
+ async function scan() {
202
+ const f = await tryFs();
203
+ if (!f)
204
+ return emptyScan(); // node-free host: maintenance is a clean no-op
205
+ const { fs, path } = f;
206
+ const s = emptyScan();
207
+ s.sessions = await listTranscripts(fs, path);
208
+ const dbFile = operatorPath("state", "state.db");
209
+ const jsonFile = operatorPath("state", "session-index.json");
210
+ const exists = (p) => {
211
+ try {
212
+ return fs.existsSync(p);
213
+ }
214
+ catch {
215
+ return false;
216
+ }
217
+ };
218
+ if (exists(dbFile)) {
219
+ // sqlite is the effective store whenever its file exists — session-index prefers it (and the
220
+ // json file is then just an inactive fallback).
221
+ s.backend = "sqlite";
222
+ s.storeFile = dbFile;
223
+ Object.assign(s, await scanSqlite(dbFile));
224
+ }
225
+ else if (exists(jsonFile)) {
226
+ s.backend = "json";
227
+ s.storeFile = jsonFile;
228
+ Object.assign(s, scanJson(fs, jsonFile));
229
+ }
230
+ else {
231
+ for (const sidecar of SQLITE_SIDECARS.map((suffix) => dbFile + suffix)) {
232
+ if (exists(sidecar))
233
+ s.staleSidecarFiles.push(sidecar);
234
+ }
235
+ if (s.staleSidecarFiles.length) {
236
+ s.issues.push(issue("stale-sidecars", s.staleSidecarFiles.map((p) => path.basename(p)).join(", ") + " without a state.db"));
237
+ }
238
+ if (s.sessions.size) {
239
+ s.issues.push(issue("missing-index", `${s.sessions.size} transcript(s) present but no state store exists`));
240
+ }
241
+ return s;
242
+ }
243
+ // Entry drift only means something when the store could actually be read and isn't destined
244
+ // for a full quarantine + rebuild anyway.
245
+ if (!s.locked && !s.needsQuarantine && s.storeFile) {
246
+ s.orphans = [...s.indexed.keys()].filter((id) => !s.sessions.has(id)).sort();
247
+ s.drifted = [...s.sessions].filter(([id, mtime]) => s.indexed.get(id) !== mtime).length;
248
+ if (s.orphans.length) {
249
+ s.issues.push(issue("orphan-entries", `${s.orphans.length} indexed session(s) have no transcript file: ${s.orphans.slice(0, 6).join(", ")}`));
250
+ }
251
+ if (s.drifted > 0) {
252
+ s.issues.push(issue("stale-entries", `${s.drifted} transcript(s) changed since they were indexed (or are missing from the index)`));
253
+ }
254
+ }
255
+ return s;
256
+ }
257
+ // ---------------------------------------------------------------------------
258
+ // Repair
259
+ // ---------------------------------------------------------------------------
260
+ /** session-index caches its backend by the resolved-home STRING; after a quarantine the cached
261
+ * handle still points at the moved-aside file. Flipping KODE_HOME to an equivalent-but-distinct
262
+ * spelling (trailing separator — path.join normalizes it away, so it's the same directory)
263
+ * forces a close + fresh open under both spellings. */
264
+ async function invalidateSessionIndexCache() {
265
+ const env = globalThis.process?.env;
266
+ if (!env)
267
+ return;
268
+ const prev = env.KODE_HOME;
269
+ const home = get_operator_home();
270
+ try {
271
+ env.KODE_HOME = `${home}/`;
272
+ await sessionIndexBackendKind(); // backend() sees the key mismatch: closes the stale handle, opens the store fresh
273
+ }
274
+ catch {
275
+ /* best-effort — a failed reopen is re-attempted on the next call */
276
+ }
277
+ finally {
278
+ if (prev === undefined)
279
+ delete env.KODE_HOME;
280
+ else
281
+ env.KODE_HOME = prev;
282
+ }
283
+ }
284
+ /** Best-effort space reclaim on the sqlite store after prune/rebuild; silently skipped on json. */
285
+ async function vacuumSqliteStore(dbFile) {
286
+ let db = null;
287
+ try {
288
+ db = await openSqliteDb(dbFile);
289
+ db.exec("VACUUM");
290
+ return true;
291
+ }
292
+ catch {
293
+ return false;
294
+ }
295
+ finally {
296
+ try {
297
+ db?.close();
298
+ }
299
+ catch {
300
+ /* best-effort */
301
+ }
302
+ }
303
+ }
304
+ function summaryOf(r) {
305
+ return {
306
+ schemaVersion: 1,
307
+ ranAtMs: r.ranAtMs,
308
+ ok: r.ok,
309
+ backend: r.backend,
310
+ issues: r.issues,
311
+ unresolved: r.unresolved,
312
+ actions: r.actions,
313
+ };
314
+ }
315
+ async function writeSummary(fs, summary) {
316
+ try {
317
+ const file = operatorPath("state", "maintenance.json");
318
+ fs.mkdirSync(operatorPath("state"), { recursive: true });
319
+ fs.writeFileSync(file, JSON.stringify(summary, null, 2));
320
+ }
321
+ catch {
322
+ /* heartbeat file is best-effort; the report itself is the return value */
323
+ }
324
+ }
325
+ function buildReport(ranAtMs, before, after, actions, quarantined, rebuilt) {
326
+ return {
327
+ ranAtMs,
328
+ backend: after.backend,
329
+ storeFile: after.storeFile,
330
+ ok: after.issues.length === 0,
331
+ issues: before.issues,
332
+ unresolved: after.issues,
333
+ actions,
334
+ orphans: before.orphans,
335
+ drifted: before.drifted,
336
+ quarantined,
337
+ rebuilt,
338
+ sessionsPresent: before.sessions.size,
339
+ indexedEntries: before.indexed.size,
340
+ };
341
+ }
342
+ /** Read-only audit of $KODE_HOME/state: what exists, whether it's readable, and how far the index
343
+ * has drifted from $KODE_HOME/sessions. Repairs nothing; never writes anything. */
344
+ export async function inspectState() {
345
+ const ranAtMs = Date.now();
346
+ const s = await scan();
347
+ return buildReport(ranAtMs, s, s, [], null, false);
348
+ }
349
+ /** Audit, then self-heal: quarantine damaged stores (renamed, never deleted — the content is
350
+ * fully re-derivable from the transcripts), drop stale sidecars, re-sync orphans/drift/new files
351
+ * through session-index, vacuum, re-audit, and record a heartbeat at state/maintenance.json.
352
+ * A store that is merely locked is reported, never touched. Idempotent — a clean run is a no-op
353
+ * apart from the heartbeat — so wiring it to cron / session start is safe. */
354
+ export async function maintainState() {
355
+ const ranAtMs = Date.now();
356
+ const before = await scan();
357
+ const f = await tryFs();
358
+ const actions = [];
359
+ if (!f || before.issues.length === 0) {
360
+ const report = buildReport(ranAtMs, before, before, [], null, false);
361
+ if (f)
362
+ await writeSummary(f.fs, summaryOf(report));
363
+ return report;
364
+ }
365
+ const { fs, path } = f;
366
+ let quarantined = null;
367
+ let rebuilt = false;
368
+ if (before.locked) {
369
+ // Concurrent writer — the healthiest this store can be. Report and bail out untouched.
370
+ }
371
+ else {
372
+ for (const sidecar of before.staleSidecarFiles) {
373
+ try {
374
+ fs.rmSync(sidecar, { force: true });
375
+ actions.push(`removed stale sidecar ${path.basename(sidecar)}`);
376
+ }
377
+ catch {
378
+ actions.push(`could not remove ${path.basename(sidecar)}`);
379
+ }
380
+ }
381
+ if (before.needsQuarantine && before.storeFile) {
382
+ const kept = `${before.storeFile}.corrupt-${ranAtMs}`;
383
+ try {
384
+ fs.renameSync(before.storeFile, kept);
385
+ quarantined = kept;
386
+ actions.push(`quarantined ${path.basename(before.storeFile)} as ${path.basename(kept)}`);
387
+ for (const suffix of SQLITE_SIDECARS) {
388
+ const sidecar = before.storeFile + suffix;
389
+ try {
390
+ if (fs.existsSync(sidecar)) {
391
+ fs.renameSync(sidecar, `${sidecar}.corrupt-${ranAtMs}`);
392
+ actions.push(`quarantined ${path.basename(sidecar)}`);
393
+ }
394
+ }
395
+ catch {
396
+ /* sidecar cleanup is best-effort; a fresh state.db reopens clean regardless */
397
+ }
398
+ }
399
+ }
400
+ catch (err) {
401
+ actions.push(`quarantine of ${path.basename(before.storeFile)} failed: ${errMsg(err)}`);
402
+ }
403
+ }
404
+ const needsResync = quarantined !== null || before.issues.some((i) => i.code !== "stale-sidecars");
405
+ if (needsResync) {
406
+ await invalidateSessionIndexCache();
407
+ try {
408
+ const res = await indexSessions();
409
+ rebuilt = true;
410
+ actions.push(`resynced state store from ${before.sessions.size} transcript(s) (indexed ${res.indexed}, skipped ${res.skipped})`);
411
+ }
412
+ catch (err) {
413
+ actions.push(`resync failed: ${errMsg(err)}`);
414
+ }
415
+ if (rebuilt && (await sessionIndexBackendKind()) === "sqlite" && before.storeFile?.endsWith("state.db") && (quarantined !== null || before.orphans.length > 0)) {
416
+ if (await vacuumSqliteStore(before.storeFile))
417
+ actions.push("compacted state store (VACUUM)");
418
+ }
419
+ }
420
+ }
421
+ const after = before.locked ? before : await scan();
422
+ const report = buildReport(ranAtMs, before, after, actions, quarantined, rebuilt);
423
+ await writeSummary(fs, summaryOf(report));
424
+ return report;
425
+ }
426
+ /** The last maintainState() summary, read back from state/maintenance.json — null before the
427
+ * first run or if the heartbeat is unreadable. Home surfaces / cron alerting read this. */
428
+ export async function stateMaintenanceStatus() {
429
+ const f = await tryFs();
430
+ if (!f)
431
+ return null;
432
+ try {
433
+ const parsed = JSON.parse(f.fs.readFileSync(operatorPath("state", "maintenance.json"), "utf8"));
434
+ if (!parsed || typeof parsed !== "object" || typeof parsed.ranAtMs !== "number")
435
+ return null;
436
+ return parsed;
437
+ }
438
+ catch {
439
+ return null;
440
+ }
441
+ }
@@ -6,10 +6,10 @@
6
6
  // poster to KODE_TELEMETRY_URL — one wire shape for mobile, the dashboard, and the audit log; this module
7
7
  // no longer POSTs its own ad-hoc shape to that URL (that would collide with the frozen stream).
8
8
  import { appendFile, mkdir } from "node:fs/promises";
9
- import { homedir } from "node:os";
10
- import { join, dirname } from "node:path";
9
+ import { dirname } from "node:path";
10
+ import { operatorPath } from "../config/home.js";
11
11
  import { randomUUID } from "node:crypto";
12
- const DEFAULT_FILE = process.env.KODE_TELEMETRY_FILE ?? join(homedir(), ".axe", "operator", "telemetry.jsonl");
12
+ const DEFAULT_FILE = process.env.KODE_TELEMETRY_FILE ?? operatorPath("telemetry.jsonl");
13
13
  export class Telemetry {
14
14
  enabled;
15
15
  file;
@@ -1,5 +1,7 @@
1
1
  import { digestArgs } from "./audit.js";
2
2
  import { EventSink } from "../telemetry/events.js";
3
+ import { runBatch, defaultClassify, defaultKeys } from "../engine/batch-scheduler.js";
4
+ import { registrySafeTools } from "./tier.js";
3
5
  export { PermissionPolicy } from "./policy.js";
4
6
  const DENIED = (name) => `Permission denied: "${name}" was refused by the operator permission policy. ` +
5
7
  `Ask the user to approve it, or run in a mode that allows it.`;
@@ -57,17 +59,27 @@ export function withPermissions(inner, policy, opts = {}) {
57
59
  }
58
60
  return {
59
61
  execute: (name, args) => gate(name, args, () => inner.execute(name, args)),
60
- executeParallel: (calls, onSettle) =>
61
- // Gate each call individually (its own decision + event), preserving order. We can't hand a
62
- // pre-denied call to inner.executeParallel, so route per-call through execute (the executor's
63
- // own read-only/mutating parallelism still applies to the ones that reach it via execute).
64
- Promise.all(calls.map(async (c, i) => {
65
- const batch = c.batchId !== undefined
66
- ? { batchId: c.batchId, batchSize: c.batchSize ?? calls.length, batchIndex: c.batchIndex ?? i }
67
- : undefined;
68
- const r = await gate(c.name, c.args, () => inner.execute(c.name, c.args), batch);
69
- onSettle?.(i, r);
70
- return r;
71
- })),
62
+ // BTX: batch ordering is SCHEDULED, not Promise.raced. Each slot's run is the FULL gate chain
63
+ // (decision + approval + inner.execute), so per-call modal latency pipelines exactly as before —
64
+ // but conflicting resources serialize in input order through the shared DAG scheduler. The old
65
+ // Promise.all-over-execute() dropped the 0.1.225 walk at this layer: a gated batch of
66
+ // [write f, read f] raced, the read deterministically observing pre-write state on slow writes.
67
+ executeParallel: (calls, onSettle) => {
68
+ const safe = new Set(registrySafeTools());
69
+ return runBatch(calls, {
70
+ // prefer the INNER executor's classification truth (per-session toolset); fall back to the
71
+ // global registry's safe list only when inner exposes no sched (third-party executors).
72
+ classify: inner.sched ? inner.sched.classify : defaultClassify("", (n) => safe.has(n)),
73
+ keys: inner.sched ? (n, a) => inner.sched.keys(n, a) : defaultKeys,
74
+ runOne: (c) => {
75
+ const sc = c;
76
+ const batch = sc.batchId !== undefined
77
+ ? { batchId: sc.batchId, batchSize: sc.batchSize ?? calls.length, batchIndex: sc.batchIndex ?? calls.findIndex((x) => x.id === sc.id) }
78
+ : undefined;
79
+ return gate(sc.name, sc.args, () => inner.execute(sc.name, sc.args), batch);
80
+ },
81
+ onSettle,
82
+ });
83
+ },
72
84
  };
73
85
  }
@@ -6,6 +6,7 @@ export const DEFAULT_MODEL_ID = "operator-1m";
6
6
  export const MODEL_ALIASES = {
7
7
  "aurora-1m": "operator-1m",
8
8
  "aurora-128k": "operator-128k",
9
+ "spectre": "cortana", // flagship renamed Spectre -> Cortana 35B (2026-10-07); old id keeps resolving
9
10
  };
10
11
  export const BUILTIN_MODELS = [
11
12
  { id: "operator-1m", label: "Operator 300K", kind: "single", desc: "307,200-token (300K) context (:8097)", endpoint: "http://127.0.0.1:8097/v1", model: "aurora-code-1", ctx: 307200 },
@@ -16,19 +17,37 @@ export const BUILTIN_MODELS = [
16
17
  // to the served truth (observeContext).
17
18
  { id: "qwen3.8-max", label: "Qwen 3.8 Max", kind: "single", desc: "BYO QwenCloud Token Plan — credits from your plan", endpoint: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", model: "qwen3.8-max", ctx: 262144, byo: "qwen", transport: "openai" },
18
19
  { id: "qwen3.8-flash", label: "Qwen 3.8 Flash", kind: "single", desc: "BYO QwenCloud Token Plan — fast tier, your credits", endpoint: "https://token-plan.maas.qwencloudapi.com/compatible-mode/v1", model: "qwen3.8-flash", ctx: 262144, byo: "qwen", transport: "openai" },
19
- // Ghost 32B — self-hosted ABLITERATED Qwen3-VL-32B (Huihui, Q4_K_M) served via llama.cpp on JL1:8101 at
20
- // 128K ctx, bound 0.0.0.0 for LAN. Uncensored at the weights + vision-capable; a 300K-class alternative to
21
- // Aurora for side-by-side testing. Replaced the held venice-24b — JL1's 64G can't host a 24B + a 32B + Aurora
22
- // warm at once (the 32B's 128K KV OOM-killed Venice), so one small/mid model shares the box with Aurora.
23
- // 128K ctx ≥ LEAN_HARNESS_CTX → full harness + cache-safe same-endpoint compaction. (venice-24b: re-add when
24
- // JL1 RAM frees or Venice lands on another node.)
25
- { id: "ghost-32b", label: "Ghost 32B (abliterated)", kind: "single", desc: "self-hosted abliterated Qwen3-VL-32B, 128K ctx (fleet llama.cpp, JL1:8101)", endpoint: "http://192.168.1.103:8101/v1", model: "/Users/home/models/qwen3-vl-32b-operatorx/Huihui-Qwen3-VL-32B-Instruct-abliterated.Q4_K_M.gguf", ctx: 131072 },
20
+ // AXE Token Plan connector — the INVERSE of the QwenCloud entries: here AXE is the vendor
21
+ // (_ai-docs/architecture/axe-model-vendor.md, phase V1). api.axe.onl is AXE's own gateway
22
+ // (nginx + LiteLLM); third-party users paste an `sk-axe-…` virtual key (`operator auth byo axe`),
23
+ // stored under keychain account "axe" — a separate account from the operator token, so the two
24
+ // can never be confused (auth/byo.ts separation guard). Gateway-side sk-axe acceptance is the V0
25
+ // deployment step; until then the connector stays hidden (honest availability). A ghost-32b API
26
+ // SKU joins once the gateway routes JL1:8101 (reverse tunnel owed — api/README "524" note).
27
+ { id: "axe-aurora-300k", label: "AXE Aurora 300K (API)", kind: "single", desc: "BYO AXE Token Plan — agent-tuned 300K reasoner via api.axe.onl", endpoint: "https://api.axe.onl/v1", model: "aurora-code-1", ctx: 307200, byo: "axe", transport: "openai" },
28
+ // Spectre — the flagship, replacing Ghost (2026-10-07). Ghost 32B was the prior self-hosted abliterated
29
+ // Qwen3-VL-32B on this slot; retired when Spectre proved 4× faster at equal capability (its weights + restore
30
+ // command are kept at ~/.axe/logs/ghost-restore-cmd.txt — reversible). Spectre = Huihui-Qwen3.6-35B-A3B-
31
+ // abliterated: a 35B MoE with ~3B ACTIVE per token → ~40 tok/s (4× Ghost's dense-32B ~10), still abliterated
32
+ // (uncensored) AND vision-capable (ships an mmproj). Served on JL1:8101 via launchd com.axe.spectre-serve,
33
+ // thinking defaulted OFF server-side (--reasoning off) so it answers cleanly (no empty-content reasoning trap).
34
+ // ctx 32000 = the TRUTH: the llama.cpp server serves n_ctx=32768 (--ctx-size 32768, verified via /props), NOT the
35
+ // 65536 the profile claimed before 0.1.260. The 65536 lie made the engine overrun the real 32768 wall → the server
36
+ // truncated a round at token 32767 (finish=length) mid-tool-call, and that cut call poisoned the session (0.1.259).
37
+ // 32000 sits just UNDER the real wall (margin) AND under LEAN_HARNESS_CTX so Cortana drops the heavy memory/handoff
38
+ // (which alone was ~16K = half the window) — persona + unrestricted layer kept. Raise ONLY if the server's --ctx-size does.
39
+ { id: "cortana", label: "Cortana 35B", kind: "single", desc: "flagship — abliterated Qwen3.6-35B-A3B MoE (~3B active, ~40 tok/s), uncensored + vision (JL1:8112, llama.cpp, 32K ctx)", endpoint: "http://192.168.1.103:8112/v1", model: "/Volumes/Ai Storage/jl1-local/models/aurorax/Huihui-Qwen3.6-35B-A3B-abliterated.Q4_K_M.gguf", ctx: 32000 },
26
40
  // Qwen3-4B — fast LOCAL tier (stock qwen3-4b-mlx-q4, 2.26GB MLX 4-bit, ctx 40960) served via mlx_lm.server
27
41
  // on JL1:8110. Qwen3 vocab (151936) — the same family as ghost-32b, so it's the review-recommended quick tier
28
42
  // AND the vocab lineage for ghost spec-decode (the actual draft is Qwen3-0.6B, too small to list here). Runs
29
43
  // /no_think for speed. Picked (2026-10-07) from a fleet-wide 3B-class review; no 3B had been execution-graded,
30
44
  // so this is the evidence-led default pending a dyno/coding-eval bench. 40960 ≥ LEAN_HARNESS_CTX → full harness.
31
- { id: "scout", label: "Scout", kind: "single", desc: "fast local tier — Qwen3-4B /no_think, Qwen3 vocab (JL1:8110, MLX 4-bit)", endpoint: "http://192.168.1.103:8110/v1", model: "/Volumes/Ai Storage/axe-models/qwen3-4b-mlx-q4", ctx: 32000 },
45
+ { id: "scout", label: "Scout 4B", kind: "single", desc: "fast local tier — Qwen3-4B /no_think, Qwen3 vocab (JL1:8110, MLX 4-bit)", endpoint: "http://192.168.1.103:8110/v1", model: "/Volumes/Ai Storage/axe-models/qwen3-4b-mlx-q4", ctx: 32000 },
46
+ // Venice 24B — a LIGHTER uncensored alternative to the 35B Spectre: Dolphin-Mistral-24B-Venice-Edition
47
+ // (Q4_K_M, ~14GB) with a bolted-on Mistral-Small-3.1 mmproj for vision. Dense 24B (not MoE), served on
48
+ // JL1:8114 via llama.cpp (--jinja, q8 KV). ctx 32768 ≥ LEAN_HARNESS_CTX → full harness. A quick drop-in to
49
+ // test a smaller/different flavour alongside Spectre without the 35B footprint.
50
+ { id: "venice-24b", label: "Venice 24B", kind: "single", desc: "lighter uncensored tier — Dolphin-Mistral-24B-Venice + vision (JL1:8114, llama.cpp)", endpoint: "http://192.168.1.103:8114/v1", model: "/Volumes/Ai Storage/exotic-models/dolphin-mistral-24b-venice-gguf/cognitivecomputations_Dolphin-Mistral-24B-Venice-Edition-Q4_K_M.gguf", ctx: 32768 },
32
51
  { id: "moa", label: "MOA (Mixture of Agents)", kind: "orchestrated", desc: "fan out to proposers, synthesize with an aggregator" },
33
52
  ];
34
53
  /** The runtime registry: the built-ins, with any settings.models entries merged in (overriding a
@@ -3,6 +3,8 @@
3
3
  // per-turn hook is where the other sinks layer in: MEMORY distillation, SKILL capture, and post-task
4
4
  // REFLECTION. All sinks are best-effort and MUST never block or throw into a turn. Node imports are lazy
5
5
  // (same mobile/JSCore-bundle discipline as services/preflight.ts) so the neutral bundle carries none of it.
6
+ import { operatorPath } from "../config/home.js";
7
+ import { redactSecrets } from "../engine/redact.js";
6
8
  const nodeImport = (m) => import(/* @vite-ignore */ m);
7
9
  // GW-18 (flywheel gate): markers of a STRUCTURED tool call that leaked into the assistant's plain text instead
8
10
  // of being parsed into tool_calls — the documented Qwen3 failure when the server runs without `--jinja` (the
@@ -25,11 +27,8 @@ async function captureFlywheel(r) {
25
27
  try {
26
28
  const { appendFile, mkdir } = await nodeImport("node:fs/promises");
27
29
  const { join } = await nodeImport("node:path");
28
- const home = process.env.HOME ?? "";
29
- if (!home)
30
- return;
31
- const dir = join(home, ".axe", "operator", "flywheel");
32
- await mkdir(dir, { recursive: true });
30
+ const dir = operatorPath("flywheel"); // follows $KODE_HOME/$KODE_PROFILE — one identity's prompts never land in another's corpus
31
+ await mkdir(dir, { recursive: true, mode: 0o700 });
33
32
  // graded = a promotable trajectory. A turn that changed files but never ran a passing check
34
33
  // (unverified, per the verify-before-done gate) is NOT promotable — that is precisely the hollow
35
34
  // "done" this whole loop exists to stop the fleet from training on.
@@ -38,8 +37,11 @@ async function captureFlywheel(r) {
38
37
  // and the serving side (GW-01/GW-18 `--jinja`) can be verified by the trend going to ~0.
39
38
  const parseFallback = hasLeakedToolCall(r.content);
40
39
  const graded = !!r.content.trim() && r.stopReason !== "repetition" && r.rounds > 0 && !r.unverified && !parseFallback;
41
- const row = JSON.stringify({ ts: Date.now(), graded, parse_fallback: parseFallback, ...r }) + "\n";
42
- await appendFile(join(dir, `${new Date().toISOString().slice(0, 10)}.jsonl`), row);
40
+ // The row carries the user's PROMPT and the full answer, and the corpus is read by the training pipeline —
41
+ // mask known secret shapes before they reach disk (the same boundary events.jsonl enforces) and keep the
42
+ // file owner-only; this used to be a 0644 file in a 0755 dir with raw prompts in it.
43
+ const row = redactSecrets(JSON.stringify({ ts: Date.now(), graded, parse_fallback: parseFallback, ...r })) + "\n";
44
+ await appendFile(join(dir, `${new Date().toISOString().slice(0, 10)}.jsonl`), row, { encoding: "utf8", mode: 0o600 });
43
45
  }
44
46
  catch { /* best-effort — capture never blocks or fails a turn */ }
45
47
  }