@0perator/operator 0.1.235 → 0.1.262

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 +104 -17
  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,142 @@
1
+ // Operator home scaffold — what a CLEAN enterprise install needs on disk before any module writes to it.
2
+ // Until now the home (~/.axe/operator, or a $KODE_PROFILE / $KODE_HOME one) was created lazily by whichever
3
+ // module wrote first, with `mkdir -p` defaults (0755): the credential/transcript/audit directory could be
4
+ // group/world-listable depending on startup order. This makes the contract explicit and idempotent:
5
+ // - the home root is 0700 (children inherit the protection: other users cannot traverse it);
6
+ // - a .gitignore that ignores EVERYTHING by default (the default home sits inside the ~/.axe monorepo —
7
+ // one blanket `git add` away from committing credentials.json / events.jsonl);
8
+ // - a README of the layout, a settings.example.json reference (never read), and a home.json marker.
9
+ // Node-only (fs); called once from cli.tsx at startup, never from the engine/browser graph. Never throws:
10
+ // a read-only or exotic filesystem must not stop Operator from starting — problems come back as `warnings`.
11
+ import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { get_operator_home } from "./home.js";
14
+ export const HOME_SCHEMA = 1;
15
+ const HOME_DIRS = ["sessions", "logs", "skills", "memories"];
16
+ const GITIGNORE = `# Operator home: credentials, transcripts, memory, the audit log. Never commit any of it.
17
+ # Created once by Operator and never overwritten — narrow it deliberately if you version parts of the home.
18
+ *
19
+ !.gitignore
20
+ !README.md
21
+ !settings.example.json
22
+ `;
23
+ const README = `# Operator home
24
+
25
+ Everything Operator keeps for one identity lives here. This directory is private to your OS user (mode 0700).
26
+
27
+ | Path | What | Sensitivity |
28
+ |---|---|---|
29
+ | settings.json | your configuration (see settings.example.json) | policy — protected from the agent when the sandbox is on |
30
+ | credentials.json | sign-in metadata; the token is in the OS keychain (file holds it only if there is no keychain) | SECRET (0600) |
31
+ | byo.json | bring-your-own vendor keys when no keychain exists | SECRET (0600) |
32
+ | vault/ | origin-bound website logins for the browser | SECRET |
33
+ | events.jsonl, audit/ | tamper-evident audit trail (hash-chained; \`operator audit verify\`) | audit |
34
+ | sessions/ | conversation transcripts (resume) | contains your prompts and tool output |
35
+ | memories/, skills/ | long-term memory and installed skills | your data |
36
+ | logs/, state/, cron/, flywheel/ | runtime state | varies |
37
+
38
+ Organisations: IT can deploy a root-owned \`managed-settings.json\` (macOS: /Library/Application Support/Operator, Linux: /etc/operator)
39
+ that users cannot override — tier, permission mode, sandbox, sign-in and audit rules. \`operator doctor\` shows what is in force.
40
+
41
+ Created by Operator (schema ${HOME_SCHEMA}). Safe to delete files here; Operator recreates what it needs.
42
+ `;
43
+ function settingsExample(version) {
44
+ return JSON.stringify({
45
+ _about: "Reference only — Operator never reads this file. Copy what you need into settings.json, or have IT deploy managed-settings.json (users cannot override it).",
46
+ _generated_by: `operator ${version}`,
47
+ permissions: { mode: "gated", tier: "enterprise", rules: { http_request: "deny" } },
48
+ sandbox: { mode: "workspace" },
49
+ computer: { enabled: false },
50
+ mcp: false,
51
+ selfImprove: { flywheel: false },
52
+ telemetry: { enabled: true },
53
+ autonomy: { maxRounds: 200, maxTurnWallClockSec: 900 },
54
+ }, null, 2) + "\n";
55
+ }
56
+ const tooOpen = (mode) => (mode & 0o077) !== 0;
57
+ /** Create/verify the Operator home. Idempotent; safe to call on every start. `explicit` homes ($KODE_HOME)
58
+ * are never chmod'ed when they already exist — that directory is the operator's choice, we only report. */
59
+ export function ensureOperatorHome(opts = {}) {
60
+ const home = opts.home ?? get_operator_home();
61
+ const explicit = opts.explicit ?? !!process.env.KODE_HOME;
62
+ const result = { home, firstRun: false, created: [], tightened: [], warnings: [] };
63
+ const version = opts.version ?? "unknown";
64
+ try {
65
+ const existed = existsSync(home);
66
+ if (!existed) {
67
+ mkdirSync(home, { recursive: true, mode: 0o700 });
68
+ result.created.push(home);
69
+ }
70
+ else if (process.platform !== "win32") {
71
+ const st = statSync(home);
72
+ if (tooOpen(st.mode)) {
73
+ if (explicit) {
74
+ result.warnings.push(`${home} is group/world accessible (mode ${(st.mode & 0o777).toString(8)}) — it holds credentials and transcripts; chmod 700 it`);
75
+ }
76
+ else {
77
+ chmodSync(home, 0o700);
78
+ result.tightened.push(home);
79
+ }
80
+ }
81
+ }
82
+ for (const d of HOME_DIRS) {
83
+ const p = join(home, d);
84
+ if (!existsSync(p)) {
85
+ mkdirSync(p, { recursive: true, mode: 0o700 });
86
+ result.created.push(p);
87
+ }
88
+ }
89
+ const marker = join(home, "home.json");
90
+ result.firstRun = !existsSync(marker);
91
+ if (result.firstRun) {
92
+ writeFileSync(marker, JSON.stringify({ schema: HOME_SCHEMA, createdAt: new Date().toISOString(), createdBy: version }, null, 2) + "\n", { mode: 0o600 });
93
+ result.created.push(marker);
94
+ }
95
+ const ignore = join(home, ".gitignore");
96
+ if (!existsSync(ignore)) {
97
+ writeFileSync(ignore, GITIGNORE, { mode: 0o644 });
98
+ result.created.push(ignore);
99
+ }
100
+ const readme = join(home, "README.md");
101
+ if (!existsSync(readme)) {
102
+ writeFileSync(readme, README, { mode: 0o644 });
103
+ result.created.push(readme);
104
+ }
105
+ const example = join(home, "settings.example.json");
106
+ if (!existsSync(example) || !readFileSync(example, "utf8").includes(`"_generated_by": "operator ${version}"`)) {
107
+ writeFileSync(example, settingsExample(version), { mode: 0o644 });
108
+ if (!result.created.includes(example))
109
+ result.created.push(example);
110
+ }
111
+ }
112
+ catch (e) {
113
+ result.warnings.push(`could not scaffold ${home}: ${e instanceof Error ? e.message : String(e)}`);
114
+ }
115
+ return result;
116
+ }
117
+ /** Read-only posture check of an existing home (for `operator doctor`): loose modes on the root or on any
118
+ * secret/audit file, and the no-keychain fallback (token on disk). Never modifies anything. */
119
+ export function auditHome(home = get_operator_home()) {
120
+ const out = [];
121
+ if (process.platform === "win32")
122
+ return out;
123
+ const check = (path, what, wantPrivate) => {
124
+ try {
125
+ const st = statSync(path);
126
+ if (wantPrivate && tooOpen(st.mode))
127
+ out.push({ path, severity: "warn", message: `${what} is group/world accessible (mode ${(st.mode & 0o777).toString(8)})` });
128
+ }
129
+ catch { /* absent — nothing to report */ }
130
+ };
131
+ check(home, "operator home", true);
132
+ for (const f of ["credentials.json", "byo.json", "events.jsonl", "identity.json"])
133
+ check(join(home, f), f, true);
134
+ check(join(home, "vault"), "vault/", true);
135
+ try {
136
+ const creds = JSON.parse(readFileSync(join(home, "credentials.json"), "utf8"));
137
+ if (creds.token)
138
+ out.push({ path: join(home, "credentials.json"), severity: "info", message: "sign-in token is stored in this 0600 file (no OS keychain available) — prefer a keychain-backed host" });
139
+ }
140
+ catch { /* no credentials file */ }
141
+ return out;
142
+ }
@@ -3,8 +3,10 @@
3
3
  // default. Never throws — a missing or malformed file just falls back to defaults, same as an env
4
4
  // var that was never set.
5
5
  import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
6
- import { homedir, totalmem } from "node:os";
7
- import { join, dirname } from "node:path";
6
+ import { totalmem } from "node:os";
7
+ import { dirname } from "node:path";
8
+ import { operatorPath } from "./home.js";
9
+ import { applyManagedPolicy, loadManagedPolicy } from "./managed.js";
8
10
  import { DEFAULT_MODEL_ID } from "../router/models.js";
9
11
  // The sole endpoint: Aurora on :8097 at its REAL served context — 307,200 tokens (300K; the llama-server
10
12
  // runs --ctx-size 307200 with q8_0 KV cache, standardized on JL1+JL2 2026-09-27). ctxWindow MUST match the
@@ -62,7 +64,7 @@ const DEFAULTS = {
62
64
  },
63
65
  };
64
66
  function settingsPath() {
65
- return process.env.KODE_TSI_SETTINGS ?? join(homedir(), ".axe", "operator", "settings.json");
67
+ return process.env.KODE_TSI_SETTINGS ?? operatorPath("settings.json");
66
68
  }
67
69
  function isPlainObject(v) {
68
70
  return typeof v === "object" && v !== null && !Array.isArray(v);
@@ -259,12 +261,44 @@ function resolveModelMode(s) {
259
261
  }
260
262
  return s;
261
263
  }
264
+ // The seat this process resolved at startup (auth/identity.ts). Re-applied by every loadSettings() so a later
265
+ // caller (cron, delegate_task) can never see a WIDER tier than the one the identity was narrowed to.
266
+ let activeSeat = null;
267
+ let warnedManaged = false;
268
+ const TIER_RANK = { readonly: 0, enterprise: 1, admin: 2 };
269
+ /** Narrow `s` to `seat` (never widen) and drop the training-flywheel default for a narrowed seat that did not
270
+ * ask for it. Pure. */
271
+ export function applySeat(s, seat) {
272
+ const cur = seat.configured ?? s.seat?.configured ?? s.permissions.tier ?? "admin";
273
+ const tier = TIER_RANK[seat.tier] < TIER_RANK[cur] ? seat.tier : cur;
274
+ const out = { ...s, seat: { ...seat, tier, configured: cur }, permissions: { ...s.permissions, tier } };
275
+ if (tier !== "admin" && !s.explicit?.flywheel)
276
+ out.selfImprove = { ...s.selfImprove, flywheel: false };
277
+ return out;
278
+ }
279
+ export function setActiveSeat(seat) { activeSeat = seat; }
262
280
  export function loadSettings() {
263
281
  const file = readSettingsFile(settingsPath());
264
282
  // structuredClone the base so a returned settings object never aliases the module-level DEFAULTS —
265
283
  // deepMerge only recurses into keys the override touches, so an untouched nested endpoint would
266
284
  // otherwise flow through by reference and a later mutation would corrupt defaults process-wide.
267
- return resolveModelMode(applyEnv(deepMerge(structuredClone(DEFAULTS), file)));
285
+ const merged = applyEnv(deepMerge(structuredClone(DEFAULTS), file));
286
+ // Managed policy goes LAST: over defaults, the user's file and env. Absent file = identity function.
287
+ const managed = loadManagedPolicy();
288
+ const flywheelPinned = (isPlainObject(file) && isPlainObject(file.selfImprove) && typeof file.selfImprove.flywheel === "boolean") ||
289
+ process.env.KODE_SELFIMPROVE !== undefined ||
290
+ typeof managed.policy?.selfImprove?.flywheel === "boolean";
291
+ let out = applyManagedPolicy({ ...merged, explicit: { flywheel: flywheelPinned } }, managed);
292
+ if (managed.info.status === "invalid" && !warnedManaged) {
293
+ warnedManaged = true;
294
+ process.stderr.write(`[operator] managed policy ${managed.info.path} is not usable (${managed.info.errors.join("; ")}) — running locked down (read-only) until it is fixed\n`);
295
+ }
296
+ // Enterprise default: a narrowed seat does not feed the training flywheel unless it explicitly says so.
297
+ if ((out.permissions.tier ?? "admin") !== "admin" && !flywheelPinned)
298
+ out = { ...out, selfImprove: { ...out.selfImprove, flywheel: false } };
299
+ if (activeSeat)
300
+ out = applySeat(out, activeSeat);
301
+ return resolveModelMode(out);
268
302
  }
269
303
  /** Persist a partial settings patch onto whatever's on disk (deep-merged, file values win over
270
304
  * defaults for anything the patch doesn't touch), so a runtime choice like /model survives a
@@ -0,0 +1,175 @@
1
+ // Local profile skills — flat `skills/*.md` and directory `skills/<cat>/<name>/SKILL.md`.
2
+ // No static `node:` imports: process.getBuiltinModule keeps the engine bundle node-free.
3
+ // renderSkillsIndex is sync so composeSystemPrompt can drop it in without going async.
4
+ import { get_operator_home } from "./home.js";
5
+ const INDEX_CAP = 4000;
6
+ const INDEX_DESC = 57;
7
+ function nodeBuiltins() {
8
+ try {
9
+ const proc = globalThis.process;
10
+ const fs = proc?.getBuiltinModule?.("node:fs");
11
+ const path = proc?.getBuiltinModule?.("node:path");
12
+ const os = proc?.getBuiltinModule?.("node:os");
13
+ if (!fs || !path || !os)
14
+ return null;
15
+ return { fs, path, os, env: proc?.env ?? {} };
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ }
21
+ export function localSkillsDir() {
22
+ const b = nodeBuiltins();
23
+ if (!b)
24
+ return "";
25
+ return b.path.join(get_operator_home(), "skills");
26
+ }
27
+ function yamlScalar(raw) {
28
+ const v = raw.trim();
29
+ if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'")))
30
+ return v.slice(1, -1);
31
+ return v.replace(/\s+#.*$/, "").trim();
32
+ }
33
+ function frontmatter(raw) {
34
+ if (!raw.startsWith("---"))
35
+ return null;
36
+ const nl = raw.startsWith("---\r\n") ? "\r\n" : "\n";
37
+ const end = raw.indexOf(`${nl}---`, 3);
38
+ if (end === -1)
39
+ return null;
40
+ return raw.slice(3 + nl.length, end);
41
+ }
42
+ function field(fm, key) {
43
+ const m = fm.match(new RegExp(`^${key}:\\s*(.*)$`, "m"));
44
+ return m ? yamlScalar(m[1]) : "";
45
+ }
46
+ function parseDescription(raw) {
47
+ const fm = frontmatter(raw);
48
+ if (fm) {
49
+ const desc = field(fm, "description");
50
+ if (desc && desc !== "|" && desc !== ">")
51
+ return desc;
52
+ }
53
+ const body = fm === null ? raw : raw.slice(raw.indexOf("---", 3) + 3);
54
+ for (const line of body.split(/\r?\n/)) {
55
+ const t = line.trim();
56
+ if (!t || t === "---" || t.startsWith("#"))
57
+ continue;
58
+ return t;
59
+ }
60
+ return "";
61
+ }
62
+ function parseName(raw, fallback) {
63
+ const fm = frontmatter(raw);
64
+ if (fm) {
65
+ const name = field(fm, "name");
66
+ if (name)
67
+ return name;
68
+ }
69
+ return fallback;
70
+ }
71
+ function isFile(fs, p) {
72
+ try {
73
+ return fs.statSync(p).isFile();
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ }
79
+ function readSkill(fs, file) {
80
+ let raw = "";
81
+ try {
82
+ raw = fs.readFileSync(file, "utf8");
83
+ }
84
+ catch { /* empty */ }
85
+ const fallback = file.replace(/\\/g, "/").split("/").pop()?.replace(/\.md$/i, "") || "skill";
86
+ const leaf = fallback === "SKILL" ? (file.replace(/\\/g, "/").split("/").slice(-2, -1)[0] || "skill") : fallback;
87
+ return { name: parseName(raw, leaf), description: parseDescription(raw) };
88
+ }
89
+ export function listLocalSkills() {
90
+ const b = nodeBuiltins();
91
+ if (!b)
92
+ return [];
93
+ const root = localSkillsDir();
94
+ if (!root)
95
+ return [];
96
+ let ents = [];
97
+ try {
98
+ ents = b.fs.readdirSync(root, { withFileTypes: true });
99
+ }
100
+ catch {
101
+ return [];
102
+ }
103
+ const found = [];
104
+ for (const ent of ents) {
105
+ if (ent.name.startsWith("."))
106
+ continue;
107
+ const full = b.path.join(root, ent.name);
108
+ if (ent.isFile() && ent.name.endsWith(".md")) {
109
+ const meta = readSkill(b.fs, full);
110
+ found.push({ name: meta.name, file: full, dir: false, description: meta.description });
111
+ }
112
+ }
113
+ const walk = (dir, depth) => {
114
+ if (depth >= 2)
115
+ return;
116
+ let kids = [];
117
+ try {
118
+ kids = b.fs.readdirSync(dir, { withFileTypes: true });
119
+ }
120
+ catch {
121
+ return;
122
+ }
123
+ for (const ent of kids) {
124
+ if (ent.name.startsWith(".") || !ent.isDirectory())
125
+ continue;
126
+ const full = b.path.join(dir, ent.name);
127
+ const skillMd = b.path.join(full, "SKILL.md");
128
+ if (isFile(b.fs, skillMd)) {
129
+ const meta = readSkill(b.fs, skillMd);
130
+ found.push({ name: meta.name, file: skillMd, dir: true, root: full, description: meta.description });
131
+ }
132
+ else {
133
+ walk(full, depth + 1);
134
+ }
135
+ }
136
+ };
137
+ walk(root, 0);
138
+ found.sort((a, c) => a.file.localeCompare(c.file));
139
+ const byName = new Map();
140
+ for (const s of found) {
141
+ const prev = byName.get(s.name);
142
+ if (!prev || (s.dir && !prev.dir))
143
+ byName.set(s.name, s);
144
+ }
145
+ return [...byName.values()].sort((a, c) => a.name.localeCompare(c.name));
146
+ }
147
+ export function resolveSkillFile(skillRoot, filePath) {
148
+ const b = nodeBuiltins();
149
+ if (!b || !filePath)
150
+ return null;
151
+ if (b.path.isAbsolute(filePath))
152
+ return null;
153
+ const target = b.path.resolve(skillRoot, filePath);
154
+ const rel = b.path.relative(skillRoot, target);
155
+ if (!rel || rel.startsWith("..") || b.path.isAbsolute(rel))
156
+ return null;
157
+ return target;
158
+ }
159
+ export function renderSkillsIndex() {
160
+ const skills = listLocalSkills();
161
+ if (!skills.length)
162
+ return "";
163
+ const lines = [];
164
+ let used = 0;
165
+ for (const s of skills) {
166
+ const desc = s.description.replace(/\s+/g, " ").trim().slice(0, INDEX_DESC);
167
+ const line = `${s.name}: ${desc}`;
168
+ const next = used + line.length + (lines.length ? 1 : 0);
169
+ if (next > INDEX_CAP)
170
+ break;
171
+ lines.push(line);
172
+ used = next;
173
+ }
174
+ return lines.join("\n");
175
+ }
@@ -3,9 +3,9 @@
3
3
  // background memory reorganization while the main agent is idle.
4
4
  import { runConsolidationPass } from "./sleep.js";
5
5
  import { appendFileSync, mkdirSync } from "node:fs";
6
- import { join, dirname } from "node:path";
7
- import { homedir } from "node:os";
8
- const DEFAULT_LOG = join(homedir(), ".axe/operator/sleep-consolidation.log");
6
+ import { dirname } from "node:path";
7
+ import { operatorPath } from "../config/home.js";
8
+ const DEFAULT_LOG = operatorPath("sleep-consolidation.log");
9
9
  let schedulerInstance = null;
10
10
  /** Get or create the singleton sleep scheduler. */
11
11
  export function getSleepScheduler() {
@@ -14,7 +14,7 @@
14
14
  // - Curates candidate deltas from captureFailureLesson into final lessons
15
15
  import { readFileSync, writeFileSync, existsSync, appendFileSync, mkdirSync } from "node:fs";
16
16
  import { dirname } from "node:path";
17
- import { homedir } from "node:os";
17
+ import { operatorPath } from "../config/home.js";
18
18
  import { FlywheelProcessor } from "../flywheel/processor.js";
19
19
  const DEFAULTS = {
20
20
  enabled: false,
@@ -280,7 +280,7 @@ export async function runConsolidationPass(opts = {}) {
280
280
  }
281
281
  try {
282
282
  // 1. Extract candidate lessons from flywheel
283
- const flywheelDir = merged.flywheelDir ?? `${homedir()}/.axe/operator/flywheel`;
283
+ const flywheelDir = merged.flywheelDir ?? operatorPath("flywheel");
284
284
  const candidates = await extractFlywheelLessons(flywheelDir);
285
285
  result.lessonsExtracted = candidates.length;
286
286
  // 1b. Recursive self-improvement: run the full flywheel processor over graded trajectories — SRFT
@@ -299,7 +299,7 @@ export async function runConsolidationPass(opts = {}) {
299
299
  const curated = curateLessons(candidates);
300
300
  result.lessonsPersisted = curated.length;
301
301
  // 3. Persist to memory file
302
- const memFile = merged.memoryFile ?? `${homedir()}/.axe/operator/Operator_Memory.jsonl`;
302
+ const memFile = merged.memoryFile ?? operatorPath("Operator_Memory.jsonl");
303
303
  if (curated.length > 0) {
304
304
  result.lessonsCurated = curated.length;
305
305
  persistLessons(memFile, curated);
@@ -3,6 +3,7 @@
3
3
  // NOT implemented here — this file depends only on the two interfaces below, which the
4
4
  // kode-tsi/src/tools/** + kode-tsi/src/router/** lane implements.
5
5
  import { chat } from "./aurora.js";
6
+ import { parseToolArgs } from "./json-repair.js";
6
7
  import { buildMessages } from "./messages.js";
7
8
  import { recoverToolCalls } from "./toolcalls.js";
8
9
  import { compact, needsCompaction, shouldProactivelyCompact, fitToWindow, clampMaxTokens } from "./compaction.js";
@@ -62,6 +63,14 @@ const SELF_LOOP_STOP = 3; // model admits it's looping this many rounds (no file
62
63
  // stop on circles.
63
64
  const NO_CONVERGE_LIMIT = 25;
64
65
  const NO_EDIT_NUDGE = 15; // tool rounds that change NO file ⇒ ONE soft "converge, or say you're blocked" nudge (never a stop)
66
+ // Think-spiral latch: with /think ON, a reasoning model can spend round after round in heavy reasoning that
67
+ // keeps acting (a poll/read tool) but never edits a file or answers. The churn lives in the reasoning
68
+ // channel, so every content-based guard above misses it (and its phrasing varies enough to dodge the prose
69
+ // fingerprint); meanwhile it eats the shared token budget — the answer gets cut off — and floods the
70
+ // transcript. After THINK_SPIRAL_ROUNDS such rounds we latch native thinking OFF for the rest of the turn
71
+ // and push the model to act or answer. Reversible (per-turn), never a hard stop; a file edit clears it.
72
+ const THINK_SPIRAL_ROUNDS = 5; // consecutive heavy-reasoning, no-file-edit rounds (while /think on) ⇒ latch think OFF
73
+ const THINK_SPIRAL_MIN_REASON_CHARS = 400; // a round counts as "heavy reasoning" only past this much reasoning_content
65
74
  const REHYDRATE_MAX_FILES = 5; // after a compaction, name up to this many recently-touched files for the model to re-read
66
75
  const COMPACTION_FAIL_LIMIT = 3; // rounds still OVER the window after compaction ran ⇒ it can't free space (summarizer failing / un-evictable bulk); stop spinning into the same wall
67
76
  const MAX_TRUNC_RETRIES = 3; // chunk-write nudges before a repeatedly-truncated tool call surfaces honestly — a
@@ -135,6 +144,26 @@ function contentSignature(content) {
135
144
  .trim()
136
145
  .slice(0, 200);
137
146
  }
147
+ // A single high-fanout round (e.g. 15 parallel web_search / fetch calls) can dump more tool output than the
148
+ // whole context window holds — which overflows the server (hard 400) AND defeats compaction, since compaction
149
+ // summarizes OLD history and preserves the RECENT turn where that bloat lives. Per-result caps (tools/registry)
150
+ // bound ONE result; this bounds the ROUND's TOTAL, so autonomous multi-tool work keeps running uninterrupted.
151
+ const TOOL_ROUND_CHAR_BUDGET = 80_000; // ~20K tokens max of tool output added per round, trimmed proportionally
152
+ /** Cap a round's total tool output to TOOL_ROUND_CHAR_BUDGET, trimming the largest results proportionally with
153
+ * a truncation note. Returns new Msg objects (originals are left intact for the verify/progress ledgers, which
154
+ * need the full results). A round at or under budget is returned unchanged. */
155
+ export function capToolRound(msgs) {
156
+ const total = msgs.reduce((n, m) => n + (m.content?.length ?? 0), 0);
157
+ if (total <= TOOL_ROUND_CHAR_BUDGET)
158
+ return msgs;
159
+ return msgs.map((m) => {
160
+ const c = m.content ?? "";
161
+ const share = Math.max(1200, Math.floor(TOOL_ROUND_CHAR_BUDGET * (c.length / total)));
162
+ if (c.length <= share)
163
+ return m;
164
+ return { ...m, content: `${c.slice(0, share)}\n…[tool result truncated to fit the round's context budget — ${c.length - share} more chars dropped; narrow the query, fetch fewer items, or request one at a time]` };
165
+ });
166
+ }
138
167
  /** A tool batch "progressed" if any result shows the batch advanced the world. Gates BOTH the no-progress
139
168
  * stall streak and the narration-loop guard, so a templated narration over PRODUCTIVE work is never
140
169
  * mistaken for a loop. A result is a STALL sentinel only if it's empty, a FAILED silent command
@@ -217,17 +246,11 @@ function stripScratchpad(content) {
217
246
  .trim();
218
247
  }
219
248
  function parseArgs(raw) {
220
- if (!raw || raw.trim() === "")
221
- return { ok: true, args: {} };
222
- try {
223
- const parsed = JSON.parse(raw);
224
- if (typeof parsed === "object" && parsed !== null)
225
- return { ok: true, args: parsed };
226
- return { ok: false, error: "arguments did not parse to an object" };
227
- }
228
- catch (err) {
229
- return { ok: false, error: err instanceof Error ? err.message : String(err) };
230
- }
249
+ // json-repair: control chars inside strings get escaped (multi-line bash -c scripts survive), and
250
+ // truncation-vs-malformed is classified so the error the model sees is ACTIONABLE (the generic
251
+ // "Unterminated string" reply sent a live review session on a 69-tool-call hallucination spiral).
252
+ const r = parseToolArgs(raw);
253
+ return r.ok ? { ok: true, args: r.args } : { ok: false, error: r.error };
231
254
  }
232
255
  /**
233
256
  * Runs tool_calls (structured or text-recovered) through the executor, honoring the loop
@@ -357,6 +380,8 @@ export async function runTurn(userInput, conversation, opts) {
357
380
  let progressed = true; // did the PREVIOUS tool batch advance? gates the guard (progress clears it)
358
381
  let noProgressStreak = 0; // consecutive tool batches that returned nothing new; reset by any real progress
359
382
  let selfLoopStreak = 0; // consecutive rounds the model admitted it's looping, uninterrupted by a file edit
383
+ let thinkSpiralStreak = 0; // consecutive heavy-reasoning, no-file-edit rounds while /think is on
384
+ let thinkLatched = false; // once a think-spiral is detected, force thinking:false for the rest of the turn
360
385
  let noEditStreak = 0; // consecutive tool rounds that changed no file — investigating, not fixing
361
386
  let noEditNudged = false; // the soft no-edit nudge fires at most once per turn
362
387
  const touchedFiles = []; // files read/edited this turn (LRU) — re-surfaced by rehydration after a compaction
@@ -390,6 +415,18 @@ export async function runTurn(userInput, conversation, opts) {
390
415
  const continuationEnabled = opts.turnContinuation?.enabled !== false && (opts.toolSchemas?.length ?? 0) > 0;
391
416
  const continuationMax = Math.max(0, opts.turnContinuation?.maxNudges ?? ANNOUNCE_NUDGE_MAX);
392
417
  let announceNudges = 0;
418
+ // Spectre-parity (b): bounded auto-continue after a LENGTH truncation (see gate at finalize).
419
+ let truncationContinues = 0;
420
+ const TRUNCATION_CONTINUE_MAX = 3;
421
+ // Cortana think-on truncation fix (task #14): once a round this turn hits the output-token limit, native
422
+ // reasoning (/think) is the thing that ate the budget — a think-heavy model spends the window reasoning,
423
+ // then the tool-call JSON (or answer) is cut off mid-generation. Re-running the recovery round WITH think
424
+ // still on just re-truncates and burns all 3 continue slots. So after the first length-truncation this
425
+ // turn, force reasoning OFF for the remaining rounds: the cut-off tool call re-emits compactly and fits in
426
+ // ONE round. Sticky for the turn (the model proved it over-reasons here), resets next turn, and leaves the
427
+ // owner's /think preference untouched for turns that don't truncate. The flag is per-call (aurora.ts
428
+ // enable_thinking), so this is a pure round-local override, no server/config change.
429
+ let truncatedThisTurn = false;
393
430
  // Converge-or-stop guard (NO_CONVERGE_LIMIT): consecutive tool rounds with no new narration and no landed edit.
394
431
  let convergeStreak = 0;
395
432
  const narratedSigs = new Set(); // prose fingerprints already spoken this turn — repeating one is not "new" text
@@ -535,7 +572,7 @@ export async function runTurn(userInput, conversation, opts) {
535
572
  maxTokens,
536
573
  temperature: opts.temperature,
537
574
  tools: opts.toolSchemas,
538
- thinking: opts.thinking,
575
+ thinking: (truncatedThisTurn || thinkLatched) ? false : opts.thinking, // read LIVE: task #14 truncation latch OR the think-spiral latch disables native reasoning for the rest of the turn
539
576
  signal: opts.signal,
540
577
  background: opts.background, // endpoint gate: sub-agents yield the shared slot to the interactive main turn
541
578
  onDelta: opts.onDelta,
@@ -576,6 +613,12 @@ export async function runTurn(userInput, conversation, opts) {
576
613
  // that still truncate, surface it honestly rather than loop. The failed round added nothing to the
577
614
  // conversation (chat() threw before streaming), so a bare user-role nudge is safe here (no leak).
578
615
  if (recovery === "truncated_tool_call") {
616
+ // Task #14 (second truncation path): the SERVER rejected a malformed/truncated tool call (not a
617
+ // local stopReason "length"). Same root cause — reasoning ate the per-round budget so the multi-line
618
+ // tool-call JSON came through cut off — so latch reasoning OFF for the retry rounds. Without this the
619
+ // nudge-and-retry below re-ran with /think still on and re-truncated until the hand-back (the exact
620
+ // mobile failure James hit). Mirrors the length-path latch; sticky for the turn, resets next turn.
621
+ truncatedThisTurn = true;
579
622
  if (truncRetries >= MAX_TRUNC_RETRIES) {
580
623
  // Enterprise-grade: NEVER leave the user frozen re-hitting the same malformed-tool-call 500.
581
624
  // Once the nudges are spent, end the turn with a clean, actionable message (not a raw 500 throw)
@@ -683,7 +726,7 @@ export async function runTurn(userInput, conversation, opts) {
683
726
  maxTokens: clampMaxTokens(retryMessages, compactionOptsFor(endpoint), opts.maxTokens ?? 8192),
684
727
  temperature: opts.temperature,
685
728
  tools: opts.toolSchemas,
686
- thinking: opts.thinking,
729
+ thinking: (truncatedThisTurn || thinkLatched) ? false : opts.thinking, // read LIVE: task #14 truncation latch OR the think-spiral latch disables native reasoning for the rest of the turn
687
730
  signal: opts.signal,
688
731
  background: opts.background,
689
732
  onDelta: opts.onDelta,
@@ -691,6 +734,12 @@ export async function runTurn(userInput, conversation, opts) {
691
734
  });
692
735
  }
693
736
  }
737
+ // Task #14: latch the think-off recovery the moment any round this turn is cut off by the output limit.
738
+ // Set here, after the response is settled for the round, so the NEXT round (the truncated-tool-call retry
739
+ // at the top, or the length-continue below) re-runs with reasoning off and fits. Covers both truncation
740
+ // paths — a cut-off tool call and a cut-off text answer both carry stopReason "length".
741
+ if (response.stopReason === "length")
742
+ truncatedThisTurn = true;
694
743
  // Round-loop guard: a true loop repeats the SAME STEP — identical narration AND identical intended
695
744
  // actions (tool name+args), or identical narration with no action at all. The signature is the WHOLE
696
745
  // round (prose + the calls it drives), NOT the prose alone: a model doing DIFFERENT work each round
@@ -755,6 +804,32 @@ export async function runTurn(userInput, conversation, opts) {
755
804
  }
756
805
  }
757
806
  }
807
+ // Think-spiral latch (THINK_SPIRAL_* above): with /think ON, a reasoning model can burn round after
808
+ // round in heavy reasoning that keeps acting (a poll/read tool) but never edits a file or answers —
809
+ // invisible to the content guards, since the churn is in the reasoning channel and its wording varies
810
+ // enough to dodge the prose fingerprint. Only count rounds that keep ACTING (tool calls) and are NOT
811
+ // fixing (no file edit) and are reasoning HEAVILY — a round that answers or edits never counts. After
812
+ // THINK_SPIRAL_ROUNDS, latch native thinking OFF for the rest of the turn and push the model to act or
813
+ // answer. Reversible (per-turn), never a hard stop.
814
+ if (opts.thinking && !thinkLatched) {
815
+ const heavyReasoning = (response.reasoningContent?.length ?? 0) >= THINK_SPIRAL_MIN_REASON_CHARS;
816
+ const mutating = response.toolCalls.some((c) => MUTATING_TOOLS.has(c.function?.name ?? ""));
817
+ if (response.toolCalls.length > 0 && !mutating && heavyReasoning) {
818
+ thinkSpiralStreak += 1;
819
+ if (thinkSpiralStreak >= THINK_SPIRAL_ROUNDS) {
820
+ thinkLatched = true;
821
+ opts.onSelfHeal?.("server_error", thinkSpiralStreak); // footer ↻ — breaking a reasoning spiral
822
+ conversation.user(`You've spent ${thinkSpiralStreak} rounds thinking at length while only polling/reading — no file ` +
823
+ `changed and no answer given. That is a reasoning loop. Stop deliberating: if you know the next ` +
824
+ `concrete action, take it now with a tool; if you have enough to answer, answer directly and ` +
825
+ `concisely. Extended thinking is now off for the rest of this turn.`);
826
+ continue; // re-prompt with thinking disabled; don't dispatch this spiral round's calls
827
+ }
828
+ }
829
+ else {
830
+ thinkSpiralStreak = 0; // a file edit, an answer, or a light-reasoning round broke the spiral
831
+ }
832
+ }
758
833
  // Stuck-turn guard (SELF_LOOP_* above): the model's own admission it's looping is the one signal the
759
834
  // signature guards miss. Only counts when the model wants to keep ACTING (has tool calls) and is NOT
760
835
  // fixing (no file edit this round) — so a final answer that merely mentions "a different approach", and a
@@ -786,8 +861,8 @@ export async function runTurn(userInput, conversation, opts) {
786
861
  // Race the batch against the abort signal so esc breaks even a hung tool (a frozen child process) —
787
862
  // the abandoned tool runs to its own timeout, but the turn is never wedged.
788
863
  const toolMsgs = await abortable(runToolCalls(response.toolCalls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx), opts.signal);
789
- for (const tm of toolMsgs)
790
- conversation.tool(tm.tool_call_id, tm.content);
864
+ for (const tm of capToolRound(toolMsgs))
865
+ conversation.tool(tm.tool_call_id, tm.content); // cap the ROUND's total tool output so a high-fanout round can't overflow the window / defeat compaction
791
866
  observeVerify(verify, response.toolCalls, toolMsgs); // verify-before-done: record mutation / verify signal
792
867
  toolCallTotal += response.toolCalls.length;
793
868
  progressed = batchProgressed(toolMsgs);
@@ -804,8 +879,8 @@ export async function runTurn(userInput, conversation, opts) {
804
879
  throwIfAborted(opts.signal);
805
880
  conversation.assistant(recovered.cleanedContent, recovered.calls);
806
881
  const toolMsgs = await abortable(runToolCalls(recovered.calls, opts.tools, callCounts, opts.onToolBatch, onToolStartFx, onToolResultFx), opts.signal);
807
- for (const tm of toolMsgs)
808
- conversation.tool(tm.tool_call_id, tm.content);
882
+ for (const tm of capToolRound(toolMsgs))
883
+ conversation.tool(tm.tool_call_id, tm.content); // cap the ROUND's total tool output so a high-fanout round can't overflow the window / defeat compaction
809
884
  observeVerify(verify, recovered.calls, toolMsgs); // verify-before-done: record mutation / verify signal
810
885
  toolCallTotal += recovered.calls.length;
811
886
  progressed = batchProgressed(toolMsgs);
@@ -845,6 +920,18 @@ export async function runTurn(userInput, conversation, opts) {
845
920
  // answered as the instruction it is) to actually call the tool(s), and keep going. Bounded per turn
846
921
  // (continuationMax) so it can never force an unbounded turn; the converge guard stops circling. A truncated
847
922
  // reply ("length") has an unreliable tail, so it is left to the normal finalize path.
923
+ // Spectre-parity fix (b), verified by nova's loop trace + live screenshot: a round CUT OFF by the
924
+ // output limit that still produced non-empty text was finalizing the turn — the model was mid-work,
925
+ // the owner saw it stop halfway, and think-mode models hit this most (long reasoning eats the budget).
926
+ // Keep the partial artifact, demand an exact continuation, bounded (3/turn) so a pathological model
927
+ // cannot loiter on the tail. Deliberately NOT gated on continuationEnabled: long-form generations
928
+ // without tools need this just as badly. The announce-nudge below already excludes length rounds.
929
+ if (response.stopReason === "length" && final && final.trim().length > 0 && truncationContinues < TRUNCATION_CONTINUE_MAX) {
930
+ truncationContinues++;
931
+ conversation.assistant(final);
932
+ conversation.user("Your output hit the token limit and was CUT OFF mid-stream. Continue EXACTLY from where you stopped — no preamble, no re-analysis. If you were emitting a tool call, re-emit it complete and keep arguments short: for long scripts, file_write the script then bash the file.");
933
+ continue;
934
+ }
848
935
  if (continuationEnabled && final && response.stopReason !== "length" && announceNudges < continuationMax && detectUnfinishedAction(final)) {
849
936
  announceNudges++;
850
937
  conversation.assistant(final);
@@ -74,6 +74,12 @@ function hostOf(base) {
74
74
  return "";
75
75
  }
76
76
  }
77
+ /** True when `base` is an AXE gateway host that fronts the model with operator-bearer auth (…axe.onl). LAN and
78
+ * loopback fleet nodes are trusted but unauthenticated, so they never need a signed-in identity. */
79
+ export function requiresOperatorToken(base) {
80
+ const h = hostOf(base ?? "");
81
+ return h === "axe.onl" || h.endsWith(".axe.onl");
82
+ }
77
83
  function isOperatorTrustedHost(h) {
78
84
  if (!h)
79
85
  return false;