@0perator/operator 0.1.222 → 0.1.261
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -5
- package/dashboard/server.mjs +1 -1
- package/dist/acp/agent.js +320 -53
- package/dist/acp/auth.js +44 -0
- package/dist/acp/config-options.js +34 -0
- package/dist/acp/prompt.js +41 -0
- package/dist/acp/run.js +116 -10
- package/dist/acp/tool-map.js +48 -0
- package/dist/auth/byo.js +125 -0
- package/dist/auth/client.js +12 -6
- package/dist/auth/commands.js +71 -3
- package/dist/auth/identity.js +136 -0
- package/dist/auth/store.js +7 -5
- package/dist/autonomy/board.js +3 -2
- package/dist/autonomy/cron.js +332 -0
- package/dist/autonomy/delegate.js +168 -0
- package/dist/autonomy/dream.js +1 -1
- package/dist/autonomy/index.js +16 -2
- package/dist/autonomy/media-robot.js +137 -0
- package/dist/autonomy/profile.js +77 -0
- package/dist/autonomy/routines.js +5 -4
- package/dist/autonomy/session-factory.js +19 -10
- package/dist/background/index.js +8 -1
- package/dist/browser/cdp.js +266 -0
- package/dist/browser/session.js +286 -0
- package/dist/cli.js +207 -106
- package/dist/compose/client.js +56 -0
- package/dist/config/brand.js +3 -3
- package/dist/config/home.js +70 -0
- package/dist/config/managed.js +230 -0
- package/dist/config/persona.js +243 -21
- package/dist/config/scaffold.js +142 -0
- package/dist/config/settings.js +87 -20
- package/dist/config/skills-index.js +175 -0
- package/dist/consolidation/scheduler.js +10 -7
- package/dist/consolidation/sleep.js +17 -3
- package/dist/engine/agent.js +231 -21
- package/dist/engine/aurora.js +79 -14
- package/dist/engine/batch-scheduler.js +128 -0
- package/dist/engine/compaction.js +129 -2
- package/dist/engine/computer-event.js +139 -0
- package/dist/engine/continuation.js +55 -0
- package/dist/engine/contract.js +3 -1
- package/dist/engine/grandmaster.js +13 -3
- package/dist/engine/json-repair.js +105 -0
- package/dist/engine/messages.js +52 -5
- package/dist/engine/redact.js +25 -0
- package/dist/engine/rolling-summary.js +28 -11
- package/dist/engine/router-adapter.js +2 -0
- package/dist/engine/unrestricted.js +51 -0
- package/dist/engine/verify-gate.js +6 -0
- package/dist/enterprise/cli.js +137 -0
- package/dist/flywheel/processor.js +30 -2
- package/dist/flywheel/secret-gate.js +123 -0
- package/dist/index.browser.js +4 -0
- package/dist/index.js +4 -0
- package/dist/mcp/index.js +18 -24
- package/dist/memory/index.js +0 -0
- package/dist/memory/session-index.js +324 -0
- package/dist/memory/session-rewind.js +92 -0
- package/dist/memory/state-maintenance.js +441 -0
- package/dist/observability/index.js +3 -3
- package/dist/permissions/audit.js +4 -1
- package/dist/permissions/index.js +24 -12
- package/dist/permissions/policy.js +4 -3
- package/dist/permissions/tier.js +31 -14
- package/dist/remote/host.js +9 -2
- package/dist/router/models.js +62 -2
- package/dist/selfimprove/index.js +9 -7
- package/dist/session.js +129 -42
- package/dist/skills/catalogue.js +167 -0
- package/dist/telemetry/audit-verify.js +94 -0
- package/dist/telemetry/events.js +92 -7
- package/dist/telemetry/lifecycle.js +18 -0
- package/dist/tools/computer.js +1 -1
- package/dist/tools/deferred.js +117 -0
- package/dist/tools/executor.js +27 -23
- package/dist/tools/memory.js +117 -0
- package/dist/tools/mutating.js +6 -0
- package/dist/tools/registry.js +1022 -46
- package/dist/tools/sandbox.js +63 -17
- package/dist/tools/searxng.js +2 -2
- package/dist/tools/shell-session.js +36 -1
- package/dist/tools/tool-output-spill.js +4 -4
- package/dist/ui/ActivitySpinner.js +17 -6
- package/dist/ui/App.js +36 -14
- package/dist/ui/ArtifactPicker.js +109 -0
- package/dist/ui/Composer.js +39 -8
- package/dist/ui/Markdown.js +5 -3
- package/dist/ui/MouseProvider.js +99 -19
- package/dist/ui/QuestionPrompt.js +24 -3
- package/dist/ui/ThinkingSpinner.js +9 -5
- package/dist/ui/ToolStep.js +17 -12
- package/dist/ui/Transcript.js +28 -9
- package/dist/ui/capabilities.js +0 -9
- package/dist/ui/listhit.js +23 -0
- package/dist/ui/mouse.js +22 -0
- package/dist/ui/osc.js +7 -4
- package/dist/ui/progressbar.js +46 -0
- package/dist/ui/shimmer.js +43 -0
- package/dist/ui/theme.js +2 -0
- package/dist/ui/tick.js +48 -0
- package/dist/ui/toolicons.js +69 -0
- package/dist/ui/useInputHistory.js +3 -3
- package/dist/util/slash.js +1 -0
- package/dist/vault/cli.js +48 -0
- package/dist/vault/store.js +157 -0
- package/dist/vault/tool.js +50 -0
- package/package.json +3 -5
- package/CHANGELOG.md +0 -1629
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
// Autonomous media robot — a triggerable, broker-agnostic pass that mines the media-gen flywheel corpus,
|
|
2
|
+
// regenerates prompts best-of-N, SELF-REVIEWS each candidate with the fleet vision model (a reward signal),
|
|
3
|
+
// keeps the winner, and logs the SCORED outcome to a results sink. This is the flywheel's compounding loop
|
|
4
|
+
// made autonomous: media-gen.jsonl (every generation) → best-of-N + vision-judge (which output is good) →
|
|
5
|
+
// media-robot.jsonl (scored winners) → the retrieval/reward layer learns "good". It composes the shipped
|
|
6
|
+
// media tools (image_generate / video_generate / image_analyze) through the tool registry — NO new model, NO
|
|
7
|
+
// broker change — so it inherits every broker upgrade (e.g. the reference/identity broker) with zero change
|
|
8
|
+
// here: a reference-bearing request just routes to a better backend and scores higher.
|
|
9
|
+
//
|
|
10
|
+
// Safe by default: a SINGLE pass (`--once` is implicit), small best-of-N, image-only — never an unattended
|
|
11
|
+
// GPU loop unless the operator explicitly schedules it (`operator routine`). The brokers are scale-to-zero,
|
|
12
|
+
// so an idle robot costs nothing.
|
|
13
|
+
import { registry } from "../tools/registry.js";
|
|
14
|
+
async function homeFile(name) {
|
|
15
|
+
const { operatorPath } = await import("../config/home.js");
|
|
16
|
+
return operatorPath(name);
|
|
17
|
+
}
|
|
18
|
+
/** Parse the provenance corpus (one JSON object per line, malformed lines skipped). */
|
|
19
|
+
async function readCorpus(file) {
|
|
20
|
+
const { readFile } = await import("node:fs/promises");
|
|
21
|
+
const txt = await readFile(file, "utf8").catch(() => "");
|
|
22
|
+
const recs = [];
|
|
23
|
+
for (const line of txt.split("\n")) {
|
|
24
|
+
const s = line.trim();
|
|
25
|
+
if (!s)
|
|
26
|
+
continue;
|
|
27
|
+
try {
|
|
28
|
+
recs.push(JSON.parse(s));
|
|
29
|
+
}
|
|
30
|
+
catch { /* skip malformed */ }
|
|
31
|
+
}
|
|
32
|
+
return recs;
|
|
33
|
+
}
|
|
34
|
+
/** Pick the prompts to (re)generate: most-recent unique SUCCESSFUL prompts for the requested kind, preferring
|
|
35
|
+
* the richer EXPANDED prompt when one was logged (the flywheel's own prior improvement). */
|
|
36
|
+
function selectPrompts(corpus, kind, max) {
|
|
37
|
+
const want = kind === "video" ? "video_generate" : "image_generate";
|
|
38
|
+
const seen = new Set();
|
|
39
|
+
const out = [];
|
|
40
|
+
for (let i = corpus.length - 1; i >= 0 && out.length < max; i--) {
|
|
41
|
+
const r = corpus[i];
|
|
42
|
+
if (r.tool !== want || r.ok === false)
|
|
43
|
+
continue;
|
|
44
|
+
const p = (r.expanded || r.prompt || "").trim();
|
|
45
|
+
if (!p || seen.has(p))
|
|
46
|
+
continue;
|
|
47
|
+
seen.add(p);
|
|
48
|
+
out.push(p);
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
const URL_RE = /https?:\/\/\S+?\.(?:png|mp4|jpg|jpeg|webp)/i;
|
|
53
|
+
/** Pull the renderable reference out of a generate tool's string result (public URL first, else a local path). */
|
|
54
|
+
function extractRef(toolResult) {
|
|
55
|
+
const url = toolResult.match(URL_RE);
|
|
56
|
+
if (url)
|
|
57
|
+
return url[0];
|
|
58
|
+
const path = toolResult.match(/→\s+(\/\S+\.(?:png|mp4|jpg|jpeg|webp))/i);
|
|
59
|
+
return path ? path[1] : undefined;
|
|
60
|
+
}
|
|
61
|
+
/** Vision-judge a generated image against its prompt → a 0..10 score, using the SAME fleet vision model the
|
|
62
|
+
* tools use (image_analyze). This is the reward signal for best-of-N selection. Returns score -1 when the
|
|
63
|
+
* judge is unreachable or its answer can't be parsed (that candidate is simply not preferred). */
|
|
64
|
+
async function judgeImage(ref, prompt) {
|
|
65
|
+
const analyze = registry.get("image_analyze");
|
|
66
|
+
if (!analyze)
|
|
67
|
+
return { score: -1, note: "no image_analyze tool available" };
|
|
68
|
+
const q = `On a scale of 0 to 10, how well does this image match the description: "${prompt}"? ` +
|
|
69
|
+
`Weigh subject, composition, style, lighting, and detail. ` +
|
|
70
|
+
`Answer with ONLY a number 0-10, then a dash and a brief reason.`;
|
|
71
|
+
const out = (await analyze.run({ image: ref, question: q, max_tokens: 120 })).trim();
|
|
72
|
+
if (out.startsWith("error:"))
|
|
73
|
+
return { score: -1, note: out.slice(0, 160) };
|
|
74
|
+
const m = out.match(/\d+(?:\.\d+)?/);
|
|
75
|
+
const score = m ? Math.max(0, Math.min(10, parseFloat(m[0]))) : -1;
|
|
76
|
+
return { score, note: out.replace(/\s+/g, " ").slice(0, 160) };
|
|
77
|
+
}
|
|
78
|
+
/** One autonomous pass: read the corpus → select prompts → best-of-N generate → self-review → log winners. */
|
|
79
|
+
export async function runMediaRobot(_settings, opts = {}) {
|
|
80
|
+
const kind = opts.kind === "video" ? "video" : "image";
|
|
81
|
+
const n = Math.max(1, Math.min(opts.n ?? 2, 4));
|
|
82
|
+
const max = Math.max(1, Math.min(opts.max ?? 3, 20));
|
|
83
|
+
const source = opts.source || (await homeFile("media-gen.jsonl"));
|
|
84
|
+
const sink = opts.sink || (await homeFile("media-robot.jsonl"));
|
|
85
|
+
const log = (s) => process.stderr.write(s + "\n");
|
|
86
|
+
const corpus = await readCorpus(source);
|
|
87
|
+
const prompts = selectPrompts(corpus, kind, max);
|
|
88
|
+
log(`media-robot: ${corpus.length} corpus record(s) → ${prompts.length} ${kind} prompt(s), best-of-${n}${opts.dry ? " [DRY]" : ""}`);
|
|
89
|
+
if (!prompts.length) {
|
|
90
|
+
log(`media-robot: nothing to do — no successful ${kind} generations in ${source} yet. Run some ${kind} gens first; each one seeds the robot.`);
|
|
91
|
+
return 0;
|
|
92
|
+
}
|
|
93
|
+
if (opts.dry) {
|
|
94
|
+
prompts.forEach((p, i) => log(` ${i + 1}. ${p.length > 100 ? p.slice(0, 100) + "…" : p}`));
|
|
95
|
+
return 0;
|
|
96
|
+
}
|
|
97
|
+
const gen = registry.get(kind === "video" ? "video_generate" : "image_generate");
|
|
98
|
+
if (!gen) {
|
|
99
|
+
log("media-robot: no generate tool in registry");
|
|
100
|
+
return 1;
|
|
101
|
+
}
|
|
102
|
+
const { appendFile, mkdir } = await import("node:fs/promises");
|
|
103
|
+
const { dirname } = await import("node:path");
|
|
104
|
+
await mkdir(dirname(sink), { recursive: true }).catch(() => { });
|
|
105
|
+
const outcomes = [];
|
|
106
|
+
for (const prompt of prompts) {
|
|
107
|
+
const cands = [];
|
|
108
|
+
for (let i = 0; i < n; i++) {
|
|
109
|
+
const res = await gen.run(kind === "video" ? { prompt } : { prompt, size: "1024x1024" });
|
|
110
|
+
const ref = extractRef(res);
|
|
111
|
+
if (!ref) {
|
|
112
|
+
log(` ✗ gen failed: ${res.slice(0, 120)}`);
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
// Image candidates get a real vision-judged score (best-of-N reward). Video self-review is qualitative
|
|
116
|
+
// only for now (a numeric video-judge via video_analyze is a follow-up), so video keeps every candidate.
|
|
117
|
+
const j = kind === "image" ? await judgeImage(ref, prompt) : { score: 0, note: "video: self-review TODO (video_analyze judge)" };
|
|
118
|
+
cands.push({ ref, score: j.score, note: j.note });
|
|
119
|
+
log(` • cand ${i + 1}/${n} score ${j.score >= 0 ? j.score : "?"} → ${ref}`);
|
|
120
|
+
}
|
|
121
|
+
if (!cands.length)
|
|
122
|
+
continue;
|
|
123
|
+
cands.sort((a, b) => b.score - a.score); // highest score wins; -1 (unjudged) sinks to the bottom
|
|
124
|
+
const best = cands[0];
|
|
125
|
+
const rec = {
|
|
126
|
+
ts: new Date().toISOString(), kind, prompt, n,
|
|
127
|
+
best_ref: best.ref, best_score: best.score, best_note: best.note, candidates: cands,
|
|
128
|
+
};
|
|
129
|
+
outcomes.push(rec);
|
|
130
|
+
await appendFile(sink, JSON.stringify(rec) + "\n", { encoding: "utf8", mode: 0o600 }).catch(() => { });
|
|
131
|
+
log(` ✓ best (score ${best.score >= 0 ? best.score : "unjudged"}) → ${best.ref}`);
|
|
132
|
+
}
|
|
133
|
+
log(`media-robot: pass complete — ${outcomes.length} winner(s) logged to ${sink}`);
|
|
134
|
+
if (opts.json)
|
|
135
|
+
process.stdout.write(JSON.stringify({ kind, processed: outcomes.length, outcomes }, null, 2) + "\n");
|
|
136
|
+
return 0;
|
|
137
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// Profile-bound headless sessions — the engine seam for Bot Mode (GW-OHV3-A / Hermes-parity gap #1).
|
|
2
|
+
// A "bot" the messaging gateway runs (one per Telegram/Discord/Slack identity) is nothing more than a
|
|
3
|
+
// long-lived headless Session with its OWN model, persona, memory, and working dir — i.e. a $KODE_PROFILE.
|
|
4
|
+
// This module turns a ProfileConfig into such a Session by DERIVING settings and composing the existing
|
|
5
|
+
// createAutonomySession factory; it does not fork or modify the engine loop. The gateway owns the fan-out
|
|
6
|
+
// (N bots = N sessions) and drives each with session.send(inboundMessage) per chat turn.
|
|
7
|
+
//
|
|
8
|
+
// Why a Session per bot (not a fresh runHeadless per message): a Session carries the conversation + the
|
|
9
|
+
// recalled memory across turns, so a bot actually remembers the chat. runHeadless is one-shot; a bot is a
|
|
10
|
+
// standing conversation. The Session satisfies Worker (send/interrupt/shutdown), which is all the gateway
|
|
11
|
+
// needs.
|
|
12
|
+
//
|
|
13
|
+
// Isolation is the load-bearing part: each profile gets its OWN memory file and rolling-summary path under
|
|
14
|
+
// its home dir. The engine's default memory/summary files are LIVE PRODUCT STATE (the owner's own Operator
|
|
15
|
+
// memory) — a bot writing there would poison the owner's recall and leak one bot's context into another.
|
|
16
|
+
// So a profile NEVER shares those; deriveProfilePaths() sends each bot to ~/.axe/operator/profiles/<id>/.
|
|
17
|
+
import { createAutonomySession } from "./session-factory.js";
|
|
18
|
+
import { MemoryStore } from "../memory/index.js";
|
|
19
|
+
/** A gated, approver-less policy: safe/read tools run, every mutating tool asks → denies. The fail-safe
|
|
20
|
+
* default for a public bot, mirroring dreamPermissions()'s read-mostly posture. */
|
|
21
|
+
function defaultBotPermissions(base) {
|
|
22
|
+
return { mode: "gated", tier: base.permissions.tier };
|
|
23
|
+
}
|
|
24
|
+
/** Resolve a profile's isolated home + the memory/summary files under it. Pure (no I/O) so it's testable;
|
|
25
|
+
* the MemoryStore + the engine create the files lazily on first write. */
|
|
26
|
+
export function deriveProfilePaths(profile, home = defaultHome()) {
|
|
27
|
+
const root = profile.home ?? `${home}/profiles/${profile.id}`;
|
|
28
|
+
return { home: root, memoryFile: `${root}/Operator_Memory.jsonl`, summaryFile: `${root}/summary.md` };
|
|
29
|
+
}
|
|
30
|
+
/** ~/.axe/operator — the Operator home that the default memory file lives under. Resolved lazily (env/HOME
|
|
31
|
+
* at call time), matching memory/index.ts's defaultFile(). */
|
|
32
|
+
function defaultHome() {
|
|
33
|
+
return process.env.KODE_HOME ?? `${process.env.HOME ?? ""}/.axe/operator`;
|
|
34
|
+
}
|
|
35
|
+
/** Derive this bot's OperatorSettings from the base: swap the served model/endpoint, persona, recall. The
|
|
36
|
+
* base is never mutated (shallow clone of the touched branches), so N profiles derive from one base safely. */
|
|
37
|
+
export function deriveProfileSettings(base, profile) {
|
|
38
|
+
const endpoints = {
|
|
39
|
+
...base.endpoints,
|
|
40
|
+
aurora: {
|
|
41
|
+
...base.endpoints.aurora,
|
|
42
|
+
...(profile.model ? { model: profile.model } : {}),
|
|
43
|
+
...(profile.modelBase ? { base: profile.modelBase } : {}),
|
|
44
|
+
},
|
|
45
|
+
};
|
|
46
|
+
return {
|
|
47
|
+
...base,
|
|
48
|
+
endpoints,
|
|
49
|
+
...(profile.model ? { activeModel: profile.model } : {}),
|
|
50
|
+
...(profile.persona !== undefined ? { systemPrompt: profile.persona } : {}),
|
|
51
|
+
...(profile.recall !== undefined ? { memory: { ...base.memory, recall: profile.recall } } : {}),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Build a long-lived, memory-isolated Session for one bot. The gateway calls this ONCE per configured bot,
|
|
56
|
+
* then drives it with session.send(inboundMessage, handlers) per chat turn — the Session keeps the
|
|
57
|
+
* conversation + recalled memory across turns, so the bot remembers. session.interrupt() cancels the
|
|
58
|
+
* in-flight turn; session.shutdown() tears it down.
|
|
59
|
+
*
|
|
60
|
+
* Model / persona / permissions come from the profile; memory + rolling summary are isolated to the bot's
|
|
61
|
+
* home dir so no bot ever touches the owner's live Operator memory. A ComputerEvent feed (for a "bot is
|
|
62
|
+
* working" indicator) is opt-in: pass through opts.extra.onComputerEvent / computerEnv — unset by default.
|
|
63
|
+
*/
|
|
64
|
+
export function createProfileSession(base, profile, opts = {}) {
|
|
65
|
+
const paths = deriveProfilePaths(profile);
|
|
66
|
+
const settings = deriveProfileSettings(base, profile);
|
|
67
|
+
return createAutonomySession(settings, {
|
|
68
|
+
permissions: opts.permissions ?? profile.permissions ?? defaultBotPermissions(base),
|
|
69
|
+
extra: {
|
|
70
|
+
sessionId: `profile:${profile.id}`,
|
|
71
|
+
cwd: profile.cwd ?? paths.home,
|
|
72
|
+
memory: new MemoryStore(paths.memoryFile),
|
|
73
|
+
rollingSummaryPath: paths.summaryFile,
|
|
74
|
+
...opts.extra, // a caller (tests, or a host wanting onComputerEvent) can still override/extend
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
}
|
|
@@ -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 {
|
|
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
|
|
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(
|
|
156
|
-
<key>StandardErrorPath</key><string>${escapeXml(
|
|
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,11 +2,12 @@
|
|
|
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
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import { compactionThreshold, compactionCeilingTokens } from "../config/settings.js";
|
|
8
|
+
import { composeSystemPrompt } from "../config/persona.js";
|
|
9
|
+
import { modelCtxFor, LEAN_HARNESS_CTX } from "../router/models.js";
|
|
10
|
+
import { compactionThreshold, compactionCeilingTokens, turnWallClockMs } from "../config/settings.js";
|
|
10
11
|
/** Build the Aurora router (primary + optional degraded failover) from settings — the headless twin of
|
|
11
12
|
* cli.tsx's buildRouter(). */
|
|
12
13
|
export function buildRouterFromSettings(settings) {
|
|
@@ -21,31 +22,39 @@ export function buildRouterFromSettings(settings) {
|
|
|
21
22
|
eps.push({ name: "failover", base: fo.base, model: fo.model, ctxLimit: fo.ctxWindow });
|
|
22
23
|
return new AuroraRouter(eps);
|
|
23
24
|
}
|
|
24
|
-
/** The full headless system prompt:
|
|
25
|
-
*
|
|
25
|
+
/** The full headless system prompt: the SAME composeSystemPrompt the TUI calls (persona + project context +
|
|
26
|
+
* memory + handoff + catalogue), non-interactive — minus the TUI-only Sub-agents + embodiment sections. */
|
|
26
27
|
export function buildHeadlessSystemPrompt(settings, cwd = process.cwd()) {
|
|
27
|
-
const
|
|
28
|
-
|
|
28
|
+
const ctxTokens = modelCtxFor(settings.activeModel, settings.models);
|
|
29
|
+
const lean = ctxTokens < LEAN_HARNESS_CTX; // small-ctx model → drop heavy memory/handoff (persona kept → stays uncensored)
|
|
30
|
+
return composeSystemPrompt({ settings, cwd, ctxTokens, lean, interactive: false });
|
|
29
31
|
}
|
|
30
32
|
/** Construct a headless Session from settings. Unattended runs get NO ask_user handler (there's no owner
|
|
31
33
|
* to answer) and no spawn_agent (a bg fork would outlive the run) — the model works with the local +
|
|
32
34
|
* MCP tool set directly. Permissions default to the owner's configured policy. */
|
|
33
35
|
export function createAutonomySession(settings, opts = {}) {
|
|
34
36
|
return new Session({
|
|
35
|
-
systemPrompt: buildHeadlessSystemPrompt(settings),
|
|
37
|
+
systemPrompt: buildHeadlessSystemPrompt(settings, opts.cwd),
|
|
36
38
|
router: buildRouterFromSettings(settings),
|
|
39
|
+
cwd: opts.cwd,
|
|
37
40
|
mcp: settings.mcp,
|
|
38
41
|
maxTokens: settings.maxTokens,
|
|
39
|
-
maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling
|
|
42
|
+
maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling; default unset ⇒ unattended runs are uncapped (free reign)
|
|
43
|
+
maxTurnWallClockMs: turnWallClockMs(settings), // per-turn TIME brake (default 15min) — stops the hour-long crawling turn; loop mode continues the objective next turn
|
|
44
|
+
maxRounds: settings.autonomy?.maxRounds, // soft per-turn round budget (default 200) — a deep unattended build runs to completion before the wrap-up nudge; was never passed here, so headless runs fell back to the engine's 10-round floor and cut long missions short
|
|
40
45
|
temperature: settings.temperature,
|
|
41
46
|
recall: settings.memory.recall,
|
|
42
47
|
models: settings.models,
|
|
43
48
|
moa: settings.moa,
|
|
44
49
|
activeModel: settings.activeModel,
|
|
45
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 },
|
|
46
54
|
telemetry: settings.telemetry,
|
|
47
55
|
compactionThreshold: compactionThreshold(settings),
|
|
48
|
-
compactionCeilingTokens: compactionCeilingTokens(settings),
|
|
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
|
|
57
|
+
sleepConsolidation: settings.autonomy?.sleepConsolidation, // headless autonomy ("operator run/loop/dream") consolidates on idle too (0.1.177)
|
|
49
58
|
...opts.extra,
|
|
50
59
|
});
|
|
51
60
|
}
|
package/dist/background/index.js
CHANGED
|
@@ -187,6 +187,13 @@ export class BackgroundAgents {
|
|
|
187
187
|
// Isolation: a file-editing child gets its own git worktree so it can't touch the foreground tree; its
|
|
188
188
|
// Session's tools are rooted there (Executor cwd). Read-only lanes (search/review/plan) share the live
|
|
189
189
|
// cwd — they SHOULD see the real tree, and a snapshot copy would be stale. Best-effort: no repo → no wt.
|
|
190
|
+
// Capture diffSha BEFORE the worktree — the HEAD at the point the task was spawned (the "before" state).
|
|
191
|
+
let diffSha;
|
|
192
|
+
try {
|
|
193
|
+
const { execSync } = await import("node:child_process");
|
|
194
|
+
diffSha = execSync("git rev-parse HEAD", { cwd: process.cwd(), encoding: "utf8", stdio: "pipe" }).trim();
|
|
195
|
+
}
|
|
196
|
+
catch { /* not a git repo — mutation check will be skipped */ }
|
|
190
197
|
const wt = (type === "code-edit" && process.env.KODE_BG_WORKTREE !== "0") ? await createWorktree(id, process.cwd()) : null;
|
|
191
198
|
const cwd = wt?.dir;
|
|
192
199
|
let session;
|
|
@@ -295,7 +302,7 @@ export class BackgroundAgents {
|
|
|
295
302
|
// Mechanism 3: verify-before-done (never on the model's say-so). Verify runs IN the worktree, so a
|
|
296
303
|
// code-editing child's declared verify_command tests the files it actually changed (in isolation).
|
|
297
304
|
if (fa.ok && fa.value) {
|
|
298
|
-
const v = await verifyFinalAnswer(fa.value, type, cwd ?? process.cwd());
|
|
305
|
+
const v = await verifyFinalAnswer(fa.value, type, cwd ?? process.cwd(), { diffSha });
|
|
299
306
|
info.verified = v.verified;
|
|
300
307
|
info.verifyDetail = v.detail;
|
|
301
308
|
}
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
// Browser automation core (HV3-02) — a zero-new-dependency Chrome DevTools Protocol client.
|
|
2
|
+
// WHY: web_fetch is a dumb GET; agents need a REAL page — JS-rendered content, forms, clicks, and
|
|
3
|
+
// session state across calls. The discipline inherited from Hermes' browser layer: TEXT-FIRST —
|
|
4
|
+
// read pages as DOM text / JS eval; screenshots only when a human must see pixels.
|
|
5
|
+
// Purity: EVERY node builtin is reached via lazy getBuiltinModule/import (same contract as
|
|
6
|
+
// src/tools/shell-session.ts) — registry.ts imports this module's wrapper, and run() bodies only
|
|
7
|
+
// ever execute on the node CLI (never the neutral browser bundle).
|
|
8
|
+
// Transport: global WebSocket (node >=22); falls back to the shipped `ws` dependency on node 20.
|
|
9
|
+
const IDLE_TTL_MS = 9 * 60_000; // an idle browser decommissions after 9 min (mirrors the persistent shell)
|
|
10
|
+
const CALL_TIMEOUT_MS = 20_000; // per CDP call
|
|
11
|
+
const NAV_TIMEOUT_MS = 30_000; // page-load budget
|
|
12
|
+
const LAUNCH_TIMEOUT_MS = 15_000; // DevTools URL handshake
|
|
13
|
+
async function nodeImport(id) {
|
|
14
|
+
const g = globalThis;
|
|
15
|
+
try {
|
|
16
|
+
const m = g.process?.getBuiltinModule?.(id);
|
|
17
|
+
if (m)
|
|
18
|
+
return m;
|
|
19
|
+
}
|
|
20
|
+
catch { /* fall through to dynamic import */ }
|
|
21
|
+
return import(id);
|
|
22
|
+
}
|
|
23
|
+
async function webSocketCtor() {
|
|
24
|
+
if (typeof globalThis.WebSocket === "function") {
|
|
25
|
+
return globalThis.WebSocket;
|
|
26
|
+
}
|
|
27
|
+
// string-typed specifier: node 20 fallback to the shipped ws dep without pulling its types into tsc
|
|
28
|
+
const modName = "ws";
|
|
29
|
+
const mod = (await import(/* webpackIgnore: true */ modName));
|
|
30
|
+
return mod.default ?? mod;
|
|
31
|
+
}
|
|
32
|
+
// ── URL policy — the browser can read anything the USER's session can; that is exactly why the
|
|
33
|
+
// policy exists: no file:// (secret paths adjacent), no chrome:// internals.
|
|
34
|
+
export function checkNavigationUrl(raw) {
|
|
35
|
+
let u;
|
|
36
|
+
try {
|
|
37
|
+
u = new URL(raw);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return `browser: not a valid URL: ${raw.slice(0, 120)}`;
|
|
41
|
+
}
|
|
42
|
+
const scheme = u.protocol;
|
|
43
|
+
if (scheme === "http:" || scheme === "https:" || scheme === "about:" || scheme === "data:")
|
|
44
|
+
return null;
|
|
45
|
+
return `browser: scheme '${scheme}' blocked (allow: http, https, about, data — file:// and chrome:// are off the policy)`;
|
|
46
|
+
}
|
|
47
|
+
/** One CDP connection: id-matched requests, event fan-out, flat multi-session routing. */
|
|
48
|
+
export class CdpConnection {
|
|
49
|
+
url;
|
|
50
|
+
nextId = 1;
|
|
51
|
+
pending = new Map();
|
|
52
|
+
handlers = new Map();
|
|
53
|
+
ws = null;
|
|
54
|
+
closed = false;
|
|
55
|
+
constructor(url) {
|
|
56
|
+
this.url = url;
|
|
57
|
+
}
|
|
58
|
+
async connect() {
|
|
59
|
+
const Ctor = await webSocketCtor();
|
|
60
|
+
this.ws = new Ctor(this.url);
|
|
61
|
+
const w = this.ws;
|
|
62
|
+
await new Promise((res, rej) => {
|
|
63
|
+
const to = setTimeout(() => rej(new Error(`browser: ws connect timeout (${CALL_TIMEOUT_MS / 1000}s)`)), CALL_TIMEOUT_MS);
|
|
64
|
+
const ok = () => { clearTimeout(to); res(); };
|
|
65
|
+
const bad = (m) => { clearTimeout(to); rej(new Error(m)); };
|
|
66
|
+
if (typeof w.addEventListener === "function") {
|
|
67
|
+
w.addEventListener("open", ok);
|
|
68
|
+
w.addEventListener("error", (e) => bad(`browser: ws error: ${String(e?.message ?? e)}`));
|
|
69
|
+
}
|
|
70
|
+
else if (typeof w.on === "function") {
|
|
71
|
+
w.on("open", ok);
|
|
72
|
+
w.on("error", (e) => bad(`browser: ws error: ${String(e)}`));
|
|
73
|
+
}
|
|
74
|
+
else
|
|
75
|
+
bad("browser: no usable WebSocket API");
|
|
76
|
+
});
|
|
77
|
+
const onData = (data) => {
|
|
78
|
+
let msg;
|
|
79
|
+
try {
|
|
80
|
+
msg = JSON.parse(typeof data === "string" ? data : String(data));
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
if (typeof msg.id === "number") {
|
|
86
|
+
const p = this.pending.get(msg.id);
|
|
87
|
+
if (p) {
|
|
88
|
+
this.pending.delete(msg.id);
|
|
89
|
+
clearTimeout(p.timer);
|
|
90
|
+
if (msg.error)
|
|
91
|
+
p.reject(new Error(`cdp ${msg.method ?? "?"}: ${msg.error.message}`));
|
|
92
|
+
else
|
|
93
|
+
p.resolve(msg.result);
|
|
94
|
+
}
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
if (msg.method) {
|
|
98
|
+
const set = this.handlers.get(msg.method);
|
|
99
|
+
if (set)
|
|
100
|
+
for (const f of set) {
|
|
101
|
+
try {
|
|
102
|
+
f(msg.params);
|
|
103
|
+
}
|
|
104
|
+
catch { /* a listener never breaks the stream */ }
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
};
|
|
108
|
+
if (typeof this.ws.addEventListener === "function")
|
|
109
|
+
this.ws.addEventListener("message", (e) => onData(e.data));
|
|
110
|
+
else if (typeof this.ws.on === "function")
|
|
111
|
+
this.ws.on("message", onData);
|
|
112
|
+
}
|
|
113
|
+
send(method, params, sessionId) {
|
|
114
|
+
if (this.closed || !this.ws)
|
|
115
|
+
return Promise.reject(new Error("browser: connection closed"));
|
|
116
|
+
const id = this.nextId++;
|
|
117
|
+
const payload = sessionId ? { id, method, params, sessionId } : { id, method, params };
|
|
118
|
+
return new Promise((res, rej) => {
|
|
119
|
+
const timer = setTimeout(() => { this.pending.delete(id); rej(new Error(`cdp timeout: ${method}`)); }, CALL_TIMEOUT_MS);
|
|
120
|
+
this.pending.set(id, { resolve: res, reject: rej, timer });
|
|
121
|
+
try {
|
|
122
|
+
this.ws.send(JSON.stringify(payload));
|
|
123
|
+
}
|
|
124
|
+
catch (e) {
|
|
125
|
+
this.pending.delete(id);
|
|
126
|
+
clearTimeout(timer);
|
|
127
|
+
rej(e);
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
on(method, fn) {
|
|
132
|
+
let set = this.handlers.get(method);
|
|
133
|
+
if (!set) {
|
|
134
|
+
set = new Set();
|
|
135
|
+
this.handlers.set(method, set);
|
|
136
|
+
}
|
|
137
|
+
set.add(fn);
|
|
138
|
+
return () => set.delete(fn);
|
|
139
|
+
}
|
|
140
|
+
once(method) {
|
|
141
|
+
return new Promise((res) => { const off = this.on(method, (p) => { off(); res(p); }); });
|
|
142
|
+
}
|
|
143
|
+
close() {
|
|
144
|
+
this.closed = true;
|
|
145
|
+
try {
|
|
146
|
+
this.ws?.close();
|
|
147
|
+
}
|
|
148
|
+
catch { /* already gone */ }
|
|
149
|
+
for (const p of this.pending.values()) {
|
|
150
|
+
clearTimeout(p.timer);
|
|
151
|
+
p.reject(new Error("browser: connection closed"));
|
|
152
|
+
}
|
|
153
|
+
this.pending.clear();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
// ── Chrome discovery + launch ───────────────────────────────────────────────
|
|
157
|
+
export function chromeCandidates() {
|
|
158
|
+
const env = globalThis.process?.env;
|
|
159
|
+
if (env?.KODE_CHROME)
|
|
160
|
+
return [env.KODE_CHROME];
|
|
161
|
+
return [
|
|
162
|
+
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
|
163
|
+
"/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary",
|
|
164
|
+
"/Applications/Chromium.app/Contents/MacOS/Chromium",
|
|
165
|
+
"/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser",
|
|
166
|
+
];
|
|
167
|
+
}
|
|
168
|
+
export function chromeArgv(wsPort, profileDir) {
|
|
169
|
+
return [
|
|
170
|
+
"--headless=new", `--remote-debugging-port=${wsPort}`, `--user-data-dir=${profileDir}`,
|
|
171
|
+
"--no-first-run", "--no-default-browser-check", "--disable-background-networking",
|
|
172
|
+
"--disable-component-update", "--disable-sync", "about:blank",
|
|
173
|
+
];
|
|
174
|
+
}
|
|
175
|
+
/** Launch a headless Chrome, resolve its DevTools WebSocket URL from the "DevTools listening on" line. */
|
|
176
|
+
export async function launchChrome() {
|
|
177
|
+
const cp = await nodeImport("node:child_process");
|
|
178
|
+
const fs = await nodeImport("node:fs");
|
|
179
|
+
const { spawn } = cp;
|
|
180
|
+
const exe = chromeCandidates().find((c) => fs.existsSync(c));
|
|
181
|
+
if (!exe)
|
|
182
|
+
throw new Error(`browser: no Chrome found among: ${chromeCandidates().join(", ")} — install Chrome or set the browser executable override in the environment`);
|
|
183
|
+
let profileDir;
|
|
184
|
+
try {
|
|
185
|
+
const { operatorPath } = await nodeImport("../config/home.js");
|
|
186
|
+
profileDir = operatorPath("browser"); // $KODE_HOME/browser — profile persists across relaunches
|
|
187
|
+
fs.mkdirSync(profileDir, { recursive: true });
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
const os = await nodeImport("node:os");
|
|
191
|
+
profileDir = fs.mkdtempSync(`${os.tmpdir()}/kode-browser-`);
|
|
192
|
+
}
|
|
193
|
+
// Hardening: pre-seed profile prefs so Chrome never saves submitted credentials into the
|
|
194
|
+
// profile's Login Data (the vault owns secrets; a browser profile that silently hoards them
|
|
195
|
+
// would break the zero-secret invariant the HV3-02b proof asserts).
|
|
196
|
+
try {
|
|
197
|
+
const prefDir = `${profileDir}/Default`;
|
|
198
|
+
fs.mkdirSync(prefDir, { recursive: true });
|
|
199
|
+
const prefFile = `${prefDir}/Preferences`;
|
|
200
|
+
if (!fs.existsSync(prefFile)) {
|
|
201
|
+
fs.writeFileSync(prefFile, JSON.stringify({
|
|
202
|
+
credentials_enable_service: false,
|
|
203
|
+
profile: { password_manager_enabled: false },
|
|
204
|
+
}));
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
catch { /* best-effort; e2e scan is the backstop */ }
|
|
208
|
+
const proc = spawn(exe, chromeArgv(0, profileDir), { stdio: ["ignore", "ignore", "pipe"], detached: false });
|
|
209
|
+
const wsUrl = await new Promise((res, rej) => {
|
|
210
|
+
let buf = "";
|
|
211
|
+
const to = setTimeout(() => rej(new Error(`browser: Chrome printed no DevTools URL within ${LAUNCH_TIMEOUT_MS / 1000}s${buf ? `; stderr tail: ${buf.slice(-300)}` : ""}`)), LAUNCH_TIMEOUT_MS);
|
|
212
|
+
proc.stderr?.on("data", (d) => {
|
|
213
|
+
buf += d.toString("utf8");
|
|
214
|
+
const m = buf.match(/DevTools listening on (ws:\/\/\S+)/);
|
|
215
|
+
if (m) {
|
|
216
|
+
clearTimeout(to);
|
|
217
|
+
res(m[1]);
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
proc.on("exit", (code) => {
|
|
221
|
+
const late = buf.match(/DevTools listening on (ws:\/\/\S+)/);
|
|
222
|
+
if (late) {
|
|
223
|
+
clearTimeout(to);
|
|
224
|
+
res(late[1]);
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
clearTimeout(to);
|
|
228
|
+
rej(new Error(`browser: Chrome exited (code ${code}) before DevTools: ${buf.slice(0, 300)}`));
|
|
229
|
+
});
|
|
230
|
+
proc.on("error", (e) => { clearTimeout(to); rej(new Error(`browser: spawn failed: ${e.message}`)); });
|
|
231
|
+
});
|
|
232
|
+
return { proc, wsUrl };
|
|
233
|
+
}
|
|
234
|
+
// ── Runtime value shaping ───────────────────────────────────────────────────
|
|
235
|
+
/** Shape a Runtime.evaluate response into plain text, or throw a readable error. Exported for tests. */
|
|
236
|
+
export function evalResultToText(raw) {
|
|
237
|
+
if (raw?.exceptionDetails) {
|
|
238
|
+
const e = raw.exceptionDetails;
|
|
239
|
+
throw new Error(`browser js error: ${e.exception?.description ?? e.text ?? "unknown"}`);
|
|
240
|
+
}
|
|
241
|
+
const v = raw?.result?.value;
|
|
242
|
+
if (typeof v === "string")
|
|
243
|
+
return v;
|
|
244
|
+
if (v === undefined || v === null)
|
|
245
|
+
return String(v);
|
|
246
|
+
try {
|
|
247
|
+
return JSON.stringify(v);
|
|
248
|
+
}
|
|
249
|
+
catch {
|
|
250
|
+
return String(v);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
/** JS that fills an input like a user (React/Vue-safe: native value setter, then input+change events). */
|
|
254
|
+
export function fillScript(selector, value) {
|
|
255
|
+
return `(() => {
|
|
256
|
+
const el = document.querySelector(${JSON.stringify(selector)});
|
|
257
|
+
if (!el) throw new Error("element not found: " + ${JSON.stringify(selector)});
|
|
258
|
+
const proto = el.tagName === "TEXTAREA" ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
|
|
259
|
+
const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
|
|
260
|
+
if (setter) setter.call(el, ${JSON.stringify(value)}); else el.value = ${JSON.stringify(value)};
|
|
261
|
+
el.dispatchEvent(new Event("input", { bubbles: true }));
|
|
262
|
+
el.dispatchEvent(new Event("change", { bubbles: true }));
|
|
263
|
+
return String(el.value);
|
|
264
|
+
})()`;
|
|
265
|
+
}
|
|
266
|
+
export const BROWSER_CONSTANTS = { IDLE_TTL_MS, CALL_TIMEOUT_MS, NAV_TIMEOUT_MS, LAUNCH_TIMEOUT_MS };
|