@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,332 @@
1
+ // Cron — Hermes-shaped scheduled headless runs (operator-home-v2 §7). Jobs live in
2
+ // <home>/cron/jobs.json; every execution appends one JSONL line to <home>/cron/executions.jsonl and
3
+ // drops the run's output text under <home>/cron/output/<id>-<ts>.txt. A job is either a fixed
4
+ // interval ({kind:"interval", everyMinutes}) or a 5-field cron expression ({kind:"cron", expr}).
5
+ //
6
+ // WHY this shape: routines.json (autonomy/routines.ts) generates OS-scheduler entries; cron is the
7
+ // in-process superset — it survives restarts via the jobs file, reports via the execution log, and
8
+ // is driven by an INJECTABLE executor so tests never spawn a real session.
9
+ //
10
+ // Browser-safe: this module is reachable from the tool registry (the `cronjob` tool) which rides in
11
+ // the engine bundle's graph, so node builtins load via the dynamic nodeImport idiom (same as
12
+ // src/tools/memory.ts) and the schedule math below is pure. The session-spawning default executor
13
+ // is ALSO lazily imported — session-factory pulls node-only modules statically.
14
+ import { operatorPath } from "../config/home.js";
15
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
16
+ let _fs = null;
17
+ let _path = null;
18
+ async function fsp() {
19
+ if (!_fs)
20
+ _fs = (await nodeImport("node:fs"));
21
+ if (!_path)
22
+ _path = (await nodeImport("node:path"));
23
+ return { fs: _fs, path: _path };
24
+ }
25
+ function parseField(field, min, max) {
26
+ const out = new Set();
27
+ for (const part of field.split(",")) {
28
+ if (!part)
29
+ return null;
30
+ const [rangePart, stepPart] = part.split("/");
31
+ const step = stepPart === undefined ? 1 : parseInt(stepPart, 10);
32
+ if (!Number.isFinite(step) || step < 1)
33
+ return null;
34
+ let lo = min, hi = max;
35
+ if (rangePart !== "*" && rangePart !== "") {
36
+ const [a, b] = rangePart.split("-");
37
+ lo = parseInt(a, 10);
38
+ hi = b !== undefined ? parseInt(b, 10) : lo;
39
+ if (!Number.isFinite(lo) || !Number.isFinite(hi) || lo < min || hi > max || lo > hi)
40
+ return null;
41
+ }
42
+ else if (part.split("/").length > 1 && rangePart === "") {
43
+ return null; // "/5" with no range part
44
+ }
45
+ for (let n = lo; n <= hi; n += step)
46
+ out.add(n);
47
+ }
48
+ return out.size ? out : null;
49
+ }
50
+ /** Parse a 5-field cron expression, or null when invalid. dow 7 is normalized to 0 (Sunday). */
51
+ export function parseCronFields(expr) {
52
+ const f = String(expr ?? "").trim().split(/\s+/);
53
+ if (f.length !== 5)
54
+ return null;
55
+ const minute = parseField(f[0], 0, 59);
56
+ const hour = parseField(f[1], 0, 23);
57
+ const dom = parseField(f[2], 1, 31);
58
+ const month = parseField(f[3], 1, 12);
59
+ const dowRaw = parseField(f[4], 0, 7);
60
+ if (!minute || !hour || !dom || !month || !dowRaw)
61
+ return null;
62
+ const dow = new Set();
63
+ for (const d of dowRaw)
64
+ dow.add(d === 7 ? 0 : d);
65
+ return { minute, hour, dom, month, dow, domStar: f[2] === "*", dowStar: f[4] === "*" };
66
+ }
67
+ function cronMatches(spec, d) {
68
+ const domOk = spec.dom.has(d.getDate());
69
+ const dowOk = spec.dow.has(d.getDay());
70
+ const dayOk = spec.domStar && spec.dowStar ? true
71
+ : spec.domStar ? dowOk
72
+ : spec.dowStar ? domOk
73
+ : domOk || dowOk;
74
+ return dayOk && spec.minute.has(d.getMinutes()) && spec.hour.has(d.getHours()) && spec.month.has(d.getMonth() + 1);
75
+ }
76
+ const CRON_SCAN_LIMIT = 366 * 2 * 24 * 60; // minutes in ~2 years — guards impossible specs (Feb 31)
77
+ /**
78
+ * Next fire STRICTLY AFTER `fromMs` (epoch ms, evaluated in LOCAL time like cron), or null when the
79
+ * schedule is invalid / never fires within ~2 years. Intervals simply advance everyMinutes from
80
+ * `fromMs` — so nextRun(schedule, lastRunAt) is the natural re-arm after an execution.
81
+ */
82
+ export function nextRun(schedule, fromMs) {
83
+ if (!Number.isFinite(fromMs))
84
+ return null;
85
+ if (!schedule || typeof schedule !== "object")
86
+ return null;
87
+ if (schedule.kind === "interval") {
88
+ const m = Number(schedule.everyMinutes);
89
+ if (!Number.isFinite(m) || m < 1)
90
+ return null;
91
+ return fromMs + Math.round(m) * 60_000;
92
+ }
93
+ if (schedule.kind === "cron") {
94
+ const spec = parseCronFields(schedule.expr);
95
+ if (!spec)
96
+ return null;
97
+ const d = new Date(fromMs);
98
+ d.setSeconds(0, 0);
99
+ d.setMinutes(d.getMinutes() + 1);
100
+ for (let i = 0; i < CRON_SCAN_LIMIT; i++) {
101
+ if (cronMatches(spec, d))
102
+ return d.getTime();
103
+ d.setMinutes(d.getMinutes() + 1);
104
+ }
105
+ return null;
106
+ }
107
+ return null;
108
+ }
109
+ /** The enabled jobs due at `nowMs`: nextRunAt <= now. A missing nextRunAt is computed from
110
+ * lastRunAt/schedule; a job that never ran and has no nextRunAt is due immediately. An invalid
111
+ * schedule (nextRun → null) is never due. Pure — does not mutate the input jobs. */
112
+ export function dueJobs(jobs, nowMs) {
113
+ return (jobs ?? []).filter((j) => j && j.enabled !== false).filter((j) => {
114
+ let next = typeof j.nextRunAt === "number" ? j.nextRunAt : null;
115
+ if (next === null) {
116
+ next = typeof j.lastRunAt === "number" ? nextRun(j.schedule, j.lastRunAt) : 0;
117
+ }
118
+ return next !== null && next <= nowMs;
119
+ });
120
+ }
121
+ // ── I/O half (node builtins loaded lazily; see header) ──────────────────────
122
+ export function cronJobsPath() { return operatorPath("cron", "jobs.json"); }
123
+ export function cronExecutionsPath() { return operatorPath("cron", "executions.jsonl"); }
124
+ export function cronOutputDir() { return operatorPath("cron", "output"); }
125
+ /** Read cron/jobs.json. Missing/malformed file ⇒ [] (a partially-written file never crashes a tick). */
126
+ export async function loadJobs() {
127
+ try {
128
+ const { fs } = await fsp();
129
+ const parsed = JSON.parse(fs.readFileSync(cronJobsPath(), "utf8"));
130
+ return Array.isArray(parsed) ? parsed : [];
131
+ }
132
+ catch {
133
+ return [];
134
+ }
135
+ }
136
+ export async function saveJobs(jobs) {
137
+ const { fs, path } = await fsp();
138
+ const p = cronJobsPath();
139
+ fs.mkdirSync(path.dirname(p), { recursive: true });
140
+ fs.writeFileSync(p, JSON.stringify(jobs, null, 2) + "\n", "utf8");
141
+ }
142
+ /** Append one execution record to cron/executions.jsonl (audit trail; never throws). */
143
+ export async function recordExecution(jobId, ok, note) {
144
+ try {
145
+ const { fs, path } = await fsp();
146
+ const p = cronExecutionsPath();
147
+ fs.mkdirSync(path.dirname(p), { recursive: true });
148
+ fs.appendFileSync(p, JSON.stringify({ t: Date.now(), jobId, ok, note }) + "\n", "utf8");
149
+ }
150
+ catch { /* best-effort — the log must never break a run */ }
151
+ }
152
+ /** Save a run's output text under cron/output/<id>-<ts>.txt. Returns the file path ("" on failure). */
153
+ export async function writeOutput(jobId, text) {
154
+ try {
155
+ const { fs, path } = await fsp();
156
+ const dir = cronOutputDir();
157
+ fs.mkdirSync(dir, { recursive: true });
158
+ const safeId = String(jobId).replace(/[^A-Za-z0-9._-]/g, "-");
159
+ const p = path.join(dir, `${safeId}-${Date.now()}.txt`);
160
+ fs.writeFileSync(p, text ?? "", "utf8");
161
+ return p;
162
+ }
163
+ catch {
164
+ return "";
165
+ }
166
+ }
167
+ /** Run one job through `execute`, record the execution, save the output, and advance
168
+ * lastRunAt/nextRunAt in the jobs file. Shared by runDueJobs and runJobNow. */
169
+ async function executeAndRecord(jobs, job, execute, startedAt) {
170
+ let ok = false, note, output = "";
171
+ try {
172
+ output = (await execute(job)) ?? "";
173
+ ok = true;
174
+ }
175
+ catch (e) {
176
+ note = e instanceof Error ? e.message : String(e);
177
+ }
178
+ await recordExecution(job.id, ok, note);
179
+ if (ok)
180
+ await writeOutput(job.id, output);
181
+ const j = jobs.find((x) => x.id === job.id);
182
+ if (j) {
183
+ j.lastRunAt = startedAt;
184
+ const next = nextRun(j.schedule, startedAt);
185
+ if (next !== null)
186
+ j.nextRunAt = next;
187
+ else
188
+ delete j.nextRunAt;
189
+ }
190
+ return { ok, note, output };
191
+ }
192
+ /**
193
+ * Fire every due job (see dueJobs) through the injectable `execute` — the seam that keeps this
194
+ * testable without spawning real sessions. Schedules advance even on failure (the execution log
195
+ * carries the error) so a broken job can't hot-loop every tick. Returns per-batch counts.
196
+ */
197
+ export async function runDueJobs(execute, nowMs = Date.now()) {
198
+ const jobs = await loadJobs();
199
+ const due = dueJobs(jobs, nowMs);
200
+ let ok = 0, failed = 0;
201
+ for (const dj of due) {
202
+ const r = await executeAndRecord(jobs, dj, execute, Date.now());
203
+ if (r.ok)
204
+ ok++;
205
+ else
206
+ failed++;
207
+ }
208
+ if (due.length)
209
+ await saveJobs(jobs);
210
+ return { ran: due.length, ok, failed };
211
+ }
212
+ /** Force one job NOW (the `cronjob run` tool action), regardless of its schedule. */
213
+ export async function runJobNow(id, execute) {
214
+ const jobs = await loadJobs();
215
+ const job = jobs.find((j) => j.id === id);
216
+ if (!job)
217
+ return `error: no cron job "${id}"`;
218
+ const r = await executeAndRecord(jobs, job, execute, Date.now());
219
+ await saveJobs(jobs);
220
+ const next = job.nextRunAt ? new Date(job.nextRunAt).toISOString() : "n/a";
221
+ return r.ok
222
+ ? `ran ${job.id}: ok — next ${next} (${r.output.length} chars output)`
223
+ : `ran ${job.id}: FAILED — ${r.note ?? "unknown error"} (next ${next})`;
224
+ }
225
+ // ── Default executor: spawn a headless session (node-only, lazily imported) ─
226
+ /** Run a job's task on a fresh headless Session — the same construction board/media-robot use
227
+ * (session-factory), one turn, content as the output text. Imported lazily: session-factory is
228
+ * node-bound and must not enter this module's static graph. */
229
+ export async function sessionExecutor(job) {
230
+ const { loadSettings } = (await nodeImport("../config/settings.js"));
231
+ const { createAutonomySession } = (await nodeImport("./session-factory.js"));
232
+ const session = createAutonomySession(loadSettings());
233
+ try {
234
+ const outcome = await session.send(job.task);
235
+ return outcome.content;
236
+ }
237
+ finally {
238
+ try {
239
+ session.shutdown();
240
+ }
241
+ catch { /* idle */ }
242
+ }
243
+ }
244
+ // ── The `cronjob` tool surface (registry wires run: runCronTool) ────────────
245
+ function genJobId() {
246
+ return `c${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
247
+ }
248
+ /** Accept the tool's flexible `schedule` param: a 5-field cron string, an interval-minutes number,
249
+ * or the explicit {kind,...} object. Returns null when unusable. */
250
+ export function parseScheduleInput(v) {
251
+ if (typeof v === "number") {
252
+ return Number.isFinite(v) && v >= 1 ? { kind: "interval", everyMinutes: v } : null;
253
+ }
254
+ if (typeof v === "string") {
255
+ const s = v.trim();
256
+ if (/^\d+$/.test(s)) {
257
+ const n = parseInt(s, 10);
258
+ return n >= 1 ? { kind: "interval", everyMinutes: n } : null;
259
+ }
260
+ if (s.split(/\s+/).length === 5 && parseCronFields(s))
261
+ return { kind: "cron", expr: s };
262
+ return null;
263
+ }
264
+ if (v && typeof v === "object") {
265
+ const o = v;
266
+ if (o.kind === "interval") {
267
+ const n = Number(o.everyMinutes);
268
+ return Number.isFinite(n) && n >= 1 ? { kind: "interval", everyMinutes: n } : null;
269
+ }
270
+ if (o.kind === "cron" && typeof o.expr === "string" && parseCronFields(o.expr)) {
271
+ return { kind: "cron", expr: o.expr.trim() };
272
+ }
273
+ }
274
+ return null;
275
+ }
276
+ function readableSchedule(s) {
277
+ return s.kind === "interval" ? `every ${s.everyMinutes}m` : `cron "${s.expr}"`;
278
+ }
279
+ /** The `cronjob` tool: action = create | list | remove | run. Compact human-readable results,
280
+ * matching the neighboring tools' style. */
281
+ export async function runCronTool(args) {
282
+ const action = String(args.action ?? "").trim();
283
+ if (action === "create") {
284
+ const task = String(args.task ?? "").trim();
285
+ if (!task)
286
+ return "error: create needs a `task` (the prompt run headlessly on each fire)";
287
+ const schedule = parseScheduleInput(args.schedule);
288
+ if (!schedule)
289
+ return "error: bad `schedule` — use a 5-field cron string (\"30 2 * * *\"), interval minutes (30), or {kind:'interval',everyMinutes}|{kind:'cron',expr}";
290
+ const now = Date.now();
291
+ const next = nextRun(schedule, now);
292
+ const job = {
293
+ id: genJobId(),
294
+ ...(String(args.name ?? "").trim() ? { name: String(args.name).trim() } : {}),
295
+ schedule, task, enabled: true, nextRunAt: next ?? undefined,
296
+ };
297
+ const jobs = await loadJobs();
298
+ jobs.push(job);
299
+ await saveJobs(jobs);
300
+ return `created cron job ${job.id} (${readableSchedule(schedule)}) — next ${next ? new Date(next).toISOString() : "never (invalid cron dates)"}`;
301
+ }
302
+ if (action === "list") {
303
+ const jobs = await loadJobs();
304
+ if (!jobs.length)
305
+ return `no cron jobs (${cronJobsPath()})`;
306
+ const lines = jobs.map((j) => {
307
+ const state = j.enabled !== false ? "on " : "off";
308
+ const next = j.nextRunAt ? new Date(j.nextRunAt).toISOString() : "n/a";
309
+ const last = j.lastRunAt ? new Date(j.lastRunAt).toISOString() : "never";
310
+ return `${state} ${j.id} ${j.name ? `${j.name} ` : ""}${readableSchedule(j.schedule)} next ${next} last ${last}\n ${j.task.slice(0, 96)}`;
311
+ });
312
+ return `${jobs.length} cron job(s):\n${lines.join("\n")}`;
313
+ }
314
+ if (action === "remove") {
315
+ const id = String(args.id ?? "").trim();
316
+ if (!id)
317
+ return "error: remove needs an `id`";
318
+ const jobs = await loadJobs();
319
+ const kept = jobs.filter((j) => j.id !== id);
320
+ if (kept.length === jobs.length)
321
+ return `error: no cron job "${id}"`;
322
+ await saveJobs(kept);
323
+ return `removed cron job ${id}`;
324
+ }
325
+ if (action === "run") {
326
+ const id = String(args.id ?? "").trim();
327
+ if (!id)
328
+ return "error: run needs an `id`";
329
+ return runJobNow(id, sessionExecutor);
330
+ }
331
+ return "error: action must be one of create|list|remove|run";
332
+ }
@@ -0,0 +1,168 @@
1
+ // delegate_task — the planner -> executor seam. Operator (the planner) hands ONE self-contained subtask to
2
+ // a sub-agent running on a CHOSEN fleet model and gets its final answer back as the tool result: the first
3
+ // step toward orchestrating our own models (Scout for the cheap/fast pass, Cortana for the hard one, ...).
4
+ //
5
+ // A sub-agent is not a new engine. It is a child headless Session built by the SAME createAutonomySession
6
+ // factory `operator run/loop/board/cron` use, pointed at a registry model (router/models.ts) exactly the
7
+ // way /model points a session at one (Session.setModel — which also resolves BYO keys + wire dialect). The
8
+ // turn loop is untouched; this module only derives settings, runs one turn, and tears the session down.
9
+ //
10
+ // Browser-safe: reachable from the tool registry (which rides in the engine bundle's graph), so node
11
+ // builtins and the node-bound session factory load lazily via the nodeImport idiom (same as autonomy/cron.ts).
12
+ import { modelRegistry, selectModel, endpointBase } from "../router/models.js";
13
+ import { MemoryStore } from "../memory/index.js";
14
+ const nodeImport = (m) => import(/* @vite-ignore */ m);
15
+ /** Model a delegation lands on when the planner names none — the fast local tier. */
16
+ export const DEFAULT_DELEGATE_MODEL = "scout";
17
+ /** How many sub-agent levels may stack. 1 = the planner may delegate; a sub-agent may NOT delegate again. */
18
+ export const MAX_DELEGATE_DEPTH = 1;
19
+ /** Env floor on the depth, read-only here: a harness (or a parent process) that exports it >= MAX disables
20
+ * delegate_task outright. The tool never writes it — process.env is shared by every session in the process. */
21
+ export const DELEGATE_DEPTH_ENV = "KODE_DELEGATE_DEPTH";
22
+ /** Hard wall-clock bound on one delegation. Tool.run gets no abort signal and the planner's turn awaits it,
23
+ * so an unreachable or wedged endpoint must not be able to hold the planner forever. */
24
+ export const DELEGATE_TIMEOUT_MS = 10 * 60_000;
25
+ /** Absolute per-turn round ceiling for a sub-agent — the same cap background sub-agents get (cli.tsx): a
26
+ * delegated agent that hits it isn't converging, and each round burns a (possibly shared) model slot. */
27
+ export const DELEGATE_MAX_ROUNDS = 50;
28
+ // Default deps: loaded lazily — session-factory pulls node-only modules statically (see cron.sessionExecutor).
29
+ const defaultDeps = {
30
+ loadSettings: async () => (await nodeImport("../config/settings.js")).loadSettings(),
31
+ createSession: async (settings, opts) => (await nodeImport("./session-factory.js")).createAutonomySession(settings, opts),
32
+ };
33
+ // ── Recursion guard ─────────────────────────────────────────────────────────
34
+ // The depth rides an AsyncLocalStorage, not a module counter or process.env: sessions share the process
35
+ // (background sub-agents, a remote host, parallel delegations), and only async-context scoping keeps one
36
+ // delegation's depth from leaking onto an unrelated session's tool calls. Every tool call the child makes
37
+ // happens inside the .run() below, so a delegate_task issued by the child sees depth 1 and is refused.
38
+ let _depthStore = null;
39
+ function depthStore() {
40
+ return (_depthStore ??= nodeImport("node:async_hooks").then((m) => new m.AsyncLocalStorage()));
41
+ }
42
+ /** Current delegation depth: the async-context depth, floored by KODE_DELEGATE_DEPTH. 0 = a planner. */
43
+ export async function delegationDepth() {
44
+ const scoped = (await depthStore()).getStore() ?? 0;
45
+ const env = Number(globalThis.process?.env?.[DELEGATE_DEPTH_ENV]);
46
+ return Math.max(scoped, Number.isFinite(env) && env > 0 ? Math.floor(env) : 0);
47
+ }
48
+ // ── Settings + brief ────────────────────────────────────────────────────────
49
+ /** Point a settings object at `profile`'s endpoint. Pure (the base is never mutated). `activeModel` + the
50
+ * ctx window are what size the child's lean-harness prompt and compaction ceiling (a 32K Scout must not be
51
+ * budgeted like the 300K Aurora); no failover (a sub-agent must not silently hop to a different model);
52
+ * MCP off (a heavy tool catalogue overruns a small-context model, and each delegation would otherwise spawn
53
+ * the owner's MCP servers). The router binding itself is Session.setModel's job, not this function's. */
54
+ export function deriveDelegateSettings(base, profile) {
55
+ return {
56
+ ...base,
57
+ endpoints: {
58
+ aurora: {
59
+ base: endpointBase(profile.endpoint ?? ""),
60
+ model: profile.model ?? profile.id,
61
+ ctxWindow: profile.ctx ?? base.endpoints.aurora.ctxWindow,
62
+ },
63
+ },
64
+ activeModel: profile.id,
65
+ mcp: false,
66
+ };
67
+ }
68
+ /** The user message the sub-agent receives: the planner's task, framed so a model with no conversation
69
+ * history knows its last message is what comes back, and that it can't ask or delegate. */
70
+ function briefFor(task) {
71
+ return [
72
+ "You are a delegated sub-agent. A planner handed you ONE self-contained subtask; it cannot answer questions",
73
+ "and cannot see your work — only your final message is returned to it, verbatim. Do the subtask with your",
74
+ "tools, then reply with just the result (concise, no preamble). If you cannot finish, say exactly what blocked",
75
+ "you. You cannot delegate further.",
76
+ "",
77
+ "## Subtask",
78
+ task,
79
+ ].join("\n");
80
+ }
81
+ /** The turn loop hands back its OWN "no answer" notes as ordinary `content`: `[stopped …]` / `[paused …]` (the
82
+ * flywheel-prefix contract, _ai-docs/conventions) and the two parenthesized empty-reply notes in engine/agent.ts.
83
+ * Returned verbatim they would reach the planner AS the sub-agent's answer — seen live: Scout on a tool task
84
+ * emitted whitespace twice and the planner would have been told "(the model returned an empty response…)". */
85
+ const NO_ANSWER = /^\s*(\[(stopped|paused)\b|\((the model returned an empty response|hit the output limit before an answer landed))/;
86
+ let _seq = 0;
87
+ const TIMED_OUT = Symbol("delegate-timeout");
88
+ /** Race a send against the wall-clock bound. On timeout the session is interrupted (so a cooperative turn
89
+ * stops) AND the race resolves immediately (so a wedged one can't hold the planner). */
90
+ function sendWithTimeout(send, ms, interrupt) {
91
+ return new Promise((resolve, reject) => {
92
+ const timer = setTimeout(() => { try {
93
+ interrupt();
94
+ }
95
+ catch { /* idle */ } resolve(TIMED_OUT); }, ms);
96
+ send.then((o) => { clearTimeout(timer); resolve(o); }, (e) => { clearTimeout(timer); reject(e); });
97
+ });
98
+ }
99
+ const msg = (e) => (e instanceof Error ? e.message : String(e));
100
+ // ── The `delegate_task` tool (registry wires run: runDelegateTask) ──────────
101
+ /**
102
+ * Run `args.task` on a sub-agent backed by `args.model` (default "scout") and return its final answer, or an
103
+ * `error: ...` string (the tool contract: never throws). Result size is bounded downstream — the executor's
104
+ * capToolResult spills anything over 40KB to disk and hands the planner a re-readable pointer.
105
+ */
106
+ export async function runDelegateTask(args, deps = defaultDeps) {
107
+ const depth = await delegationDepth();
108
+ if (depth >= MAX_DELEGATE_DEPTH) {
109
+ return `error: delegate_task refused — already inside a delegated sub-agent (depth ${depth}, max ${MAX_DELEGATE_DEPTH}). Sub-agents cannot delegate; do the work directly with your own tools.`;
110
+ }
111
+ const task = String(args.task ?? "").trim();
112
+ if (!task)
113
+ return "error: delegate_task needs a non-empty `task` — a self-contained subtask; the sub-agent sees nothing else";
114
+ const modelId = String(args.model ?? "").trim() || DEFAULT_DELEGATE_MODEL;
115
+ const settings = await deps.loadSettings();
116
+ const { profile, error } = selectModel(modelRegistry(settings.models), modelId);
117
+ if (error || !profile)
118
+ return `error: delegate_task: ${error ?? `unknown model "${modelId}"`}`;
119
+ if (profile.kind !== "single") {
120
+ return `error: delegate_task: "${profile.id}" is an orchestrated profile with no endpoint of its own — pick a single-endpoint model`;
121
+ }
122
+ const id = `delegate-${profile.id}-${Date.now().toString(36)}-${++_seq}`;
123
+ // Isolation: the child never writes the owner's live memory / rolling summary (see autonomy/profile.ts).
124
+ const { tmpdir } = (await nodeImport("node:os"));
125
+ const dir = `${tmpdir()}/operator-${id}`;
126
+ let session;
127
+ try {
128
+ session = await deps.createSession(deriveDelegateSettings(settings, profile), {
129
+ extra: {
130
+ sessionId: id,
131
+ memory: new MemoryStore(`${dir}/Operator_Memory.jsonl`),
132
+ rollingSummaryPath: `${dir}/summary.md`,
133
+ maxRoundsHard: DELEGATE_MAX_ROUNDS,
134
+ sleepConsolidation: { enabled: false }, // a short-lived child must not consolidate the owner's knowledge base
135
+ },
136
+ });
137
+ }
138
+ catch (e) {
139
+ return `error: delegate_task: could not start a sub-agent on ${profile.id} — ${msg(e)}`;
140
+ }
141
+ try {
142
+ const bound = session.setModel(profile.id); // router -> this profile's endpoint (+ BYO key / wire dialect); refuses a BYO model with no key
143
+ if (!bound.ok)
144
+ return `error: delegate_task: ${bound.error ?? `could not select "${profile.id}"`}`;
145
+ const timeoutMs = deps.timeoutMs ?? DELEGATE_TIMEOUT_MS;
146
+ const store = await depthStore();
147
+ const outcome = await sendWithTimeout(store.run(depth + 1, () => session.send(briefFor(task))), timeoutMs, () => session.interrupt());
148
+ if (outcome === TIMED_OUT) {
149
+ return `error: delegate_task timed out after ${Math.round(timeoutMs / 1000)}s — the sub-agent on ${profile.id} was interrupted; narrow the subtask or pick a faster model`;
150
+ }
151
+ if (outcome.interrupted)
152
+ return `error: delegate_task: the sub-agent on ${profile.id} was interrupted before it finished`;
153
+ const text = String(outcome.content ?? "").trim();
154
+ if (!text || NO_ANSWER.test(text)) {
155
+ return `error: delegate_task: the sub-agent on ${profile.id} produced no answer (${outcome.rounds} rounds, ${outcome.toolCalls} tool calls)${text ? ` — it reported: ${text.slice(0, 300)}` : ""}. Retry with a smaller, clearer subtask or a stronger model.`;
156
+ }
157
+ return text;
158
+ }
159
+ catch (e) {
160
+ return `error: delegate_task: the sub-agent on ${profile.id} failed — ${msg(e)}`;
161
+ }
162
+ finally {
163
+ try {
164
+ session.shutdown();
165
+ }
166
+ catch { /* already down */ }
167
+ }
168
+ }
@@ -12,9 +12,8 @@
12
12
  // so an idle robot costs nothing.
13
13
  import { registry } from "../tools/registry.js";
14
14
  async function homeFile(name) {
15
- const os = await import("node:os");
16
- const { join } = await import("node:path");
17
- return join(os.homedir(), ".axe", "operator", name);
15
+ const { operatorPath } = await import("../config/home.js");
16
+ return operatorPath(name);
18
17
  }
19
18
  /** Parse the provenance corpus (one JSON object per line, malformed lines skipped). */
20
19
  async function readCorpus(file) {
@@ -9,12 +9,13 @@
9
9
  // path and says so.
10
10
  import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
11
11
  import { homedir } from "node:os";
12
- import { join, dirname } from "node:path";
12
+ import { dirname } from "node:path";
13
+ import { operatorPath } from "../config/home.js";
13
14
  export function routinesPath(settings) {
14
15
  const p = settings?.autonomy?.routinesFile;
15
16
  if (p)
16
17
  return p.replace(/^~(?=\/|$)/, homedir());
17
- return join(homedir(), ".axe", "operator", "routines.json");
18
+ return operatorPath("routines.json");
18
19
  }
19
20
  export function readRoutines(file) {
20
21
  try {
@@ -152,8 +153,8 @@ ${argXml}
152
153
  ${cal.join("\n")}
153
154
  </dict>
154
155
  <key>RunAtLoad</key><false/>
155
- <key>StandardOutPath</key><string>${escapeXml(join(homedir(), ".axe", "operator", "logs", `${routine.id}.out.log`))}</string>
156
- <key>StandardErrorPath</key><string>${escapeXml(join(homedir(), ".axe", "operator", "logs", `${routine.id}.err.log`))}</string>
156
+ <key>StandardOutPath</key><string>${escapeXml(operatorPath("logs", `${routine.id}.out.log`))}</string>
157
+ <key>StandardErrorPath</key><string>${escapeXml(operatorPath("logs", `${routine.id}.err.log`))}</string>
157
158
  </dict></plist>
158
159
  `;
159
160
  }
@@ -2,6 +2,7 @@
2
2
  // session (persona + project context + handoff, the Aurora router, permissions, telemetry) but with NO
3
3
  // Ink/TTY dependency, so `operator run/loop/board/dream` construct a real, tool-capable Session the same
4
4
  // way the shell does. Kept deliberately small: it composes existing building blocks, it does not fork them.
5
+ import { randomUUID } from "node:crypto";
5
6
  import { Session } from "../session.js";
6
7
  import { AuroraRouter } from "../router/router.js";
7
8
  import { composeSystemPrompt } from "../config/persona.js";
@@ -33,8 +34,9 @@ export function buildHeadlessSystemPrompt(settings, cwd = process.cwd()) {
33
34
  * MCP tool set directly. Permissions default to the owner's configured policy. */
34
35
  export function createAutonomySession(settings, opts = {}) {
35
36
  return new Session({
36
- systemPrompt: buildHeadlessSystemPrompt(settings),
37
+ systemPrompt: buildHeadlessSystemPrompt(settings, opts.cwd),
37
38
  router: buildRouterFromSettings(settings),
39
+ cwd: opts.cwd,
38
40
  mcp: settings.mcp,
39
41
  maxTokens: settings.maxTokens,
40
42
  maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling; default unset ⇒ unattended runs are uncapped (free reign)
@@ -46,6 +48,9 @@ export function createAutonomySession(settings, opts = {}) {
46
48
  moa: settings.moa,
47
49
  activeModel: settings.activeModel,
48
50
  permissions: opts.permissions ?? settings.permissions,
51
+ // Audit attribution: without these every headless/cron/dream tool event carried session:"" and no seat.
52
+ sessionId: `hl-${randomUUID().slice(0, 12)}`,
53
+ eventActor: { tier: settings.permissions?.tier ?? "admin", surface: "cli", sub: settings.seat?.sub },
49
54
  telemetry: settings.telemetry,
50
55
  compactionThreshold: compactionThreshold(settings),
51
56
  compactionCeilingTokens: compactionCeilingTokens(settings, settings.endpoints.aurora.ctxWindow, "autonomy"), // AUTONOMY mode ⇒ the high headless ceiling (~100k, just under the swap cliff), independent of the tight interactive ceilingTokens — so a snappy interactive setting can't throttle an unattended build into a compaction-thrash loop