@0perator/operator 0.1.61 → 0.1.153
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/CHANGELOG.md +1037 -1
- package/LICENSE +19 -0
- package/dist/acp/agent.js +103 -0
- package/dist/acp/run.js +23 -0
- package/dist/auth/client.js +4 -1
- package/dist/auth/login-intent.js +12 -0
- package/dist/autonomy/board-run.js +65 -0
- package/dist/autonomy/board.js +83 -0
- package/dist/autonomy/dream.js +71 -0
- package/dist/autonomy/headless.js +70 -0
- package/dist/autonomy/index.js +260 -0
- package/dist/autonomy/keepawake.js +84 -0
- package/dist/autonomy/loop.js +82 -0
- package/dist/autonomy/reporter.js +54 -0
- package/dist/autonomy/routine-run.js +25 -0
- package/dist/autonomy/routines.js +173 -0
- package/dist/autonomy/session-factory.js +61 -0
- package/dist/background/index.js +269 -20
- package/dist/background/worktree.js +62 -0
- package/dist/cli.js +535 -112
- package/dist/config/brand.js +81 -0
- package/dist/config/operator-harness.js +86 -0
- package/dist/config/persona.js +174 -0
- package/dist/config/settings.js +98 -9
- package/dist/engine/agent.js +447 -51
- package/dist/engine/aurora.js +180 -64
- package/dist/engine/compaction.js +97 -5
- package/dist/engine/grandmaster.js +69 -10
- package/dist/engine/router-adapter.js +3 -0
- package/dist/engine/selfheal.js +35 -0
- package/dist/engine/verify-gate.js +81 -0
- package/dist/mcp/index.js +1 -1
- package/dist/permissions/index.js +13 -7
- package/dist/router/models.js +13 -4
- package/dist/router/router.js +46 -7
- package/dist/selfimprove/index.js +88 -0
- package/dist/services/preflight.js +42 -1
- package/dist/session.js +228 -21
- package/dist/telemetry/events.js +9 -0
- package/dist/tools/executor.js +48 -24
- package/dist/tools/git-status.js +71 -0
- package/dist/tools/mutating.js +9 -0
- package/dist/tools/registry.js +214 -11
- package/dist/tools/result-cap.js +23 -0
- package/dist/tools/searxng.js +42 -2
- package/dist/ui/ActivitySpinner.js +6 -5
- package/dist/ui/App.js +23 -5
- package/dist/ui/AuthScreen.js +1 -1
- package/dist/ui/BgPanel.js +60 -5
- package/dist/ui/Composer.js +135 -13
- package/dist/ui/Header.js +14 -6
- package/dist/ui/InputRule.js +2 -1
- package/dist/ui/Markdown.js +69 -10
- package/dist/ui/Masthead.js +6 -4
- package/dist/ui/PlanPane.js +23 -0
- package/dist/ui/QuestionPrompt.js +22 -8
- package/dist/ui/StatsCard.js +15 -0
- package/dist/ui/StatusRule.js +13 -4
- package/dist/ui/SummaryCard.js +18 -0
- package/dist/ui/Table.js +114 -0
- package/dist/ui/ThinkingSpinner.js +6 -4
- package/dist/ui/ToolBatch.js +12 -0
- package/dist/ui/ToolStep.js +12 -4
- package/dist/ui/Transcript.js +30 -6
- package/dist/ui/chart.js +34 -0
- package/dist/ui/editdiff.js +84 -0
- package/dist/ui/highlight.js +89 -0
- package/dist/ui/osc.js +32 -0
- package/dist/ui/planExit.js +26 -0
- package/dist/ui/term.js +16 -0
- package/dist/ui/theme.js +60 -0
- package/dist/ui/tree.js +71 -0
- package/dist/util/slash.js +15 -0
- package/dist/util/throttle.js +28 -0
- package/package.json +10 -1
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// Harness-enforced verify-before-done (0.1.71). A turn-local ledger + predicate that let the main loop
|
|
2
|
+
// (engine/agent.ts) COMPUTE — never trust the model to self-report — whether a turn that CHANGED code
|
|
3
|
+
// also RAN a real check before claiming done. Pure string ops, zero imports: neutral/JSCore-bundle safe.
|
|
4
|
+
// Full design + rationale (Karpathy/Carmack/Boris/Hinton panel): docs/verify-before-done.md.
|
|
5
|
+
//
|
|
6
|
+
// Why this exists: persona rules 0.1.69/0.1.70 tell the model to verify by running, but a weak local
|
|
7
|
+
// model can ignore a prompt — a live session shipped a Skill Graph Engine reported "37/37, engine works"
|
|
8
|
+
// when the CLI didn't parse and the resolver returned empty. The 37 "tests" were file-exists checks. The
|
|
9
|
+
// only durable fix is to make "done" a fact the harness observes, not a phrase the model emits.
|
|
10
|
+
// A verify is a command whose HEAD (after stripping VAR= and `cd x &&` prefixes, per pipeline segment,
|
|
11
|
+
// basenamed) is a known test/build/typecheck/run tool. An ALLOWLIST, so echo/cat/ls/true/grep/test/git
|
|
12
|
+
// are excluded for free — which is exactly what makes SGE's file-exists checks NOT count as verification.
|
|
13
|
+
const VERIFY_HEADS = new Set([
|
|
14
|
+
"npm", "pnpm", "yarn", "bun", "npx", "node", "deno", "tsc", "tsx", "vitest", "jest", "mocha",
|
|
15
|
+
"pytest", "python", "python3", "unittest", "go", "cargo", "rustc", "make", "cmake", "ctest",
|
|
16
|
+
"gradle", "mvn", "dotnet", "rspec", "rake", "ruff", "mypy", "pyright", "eslint", "phpunit", "bats",
|
|
17
|
+
]);
|
|
18
|
+
function segmentHeads(cmd) {
|
|
19
|
+
return cmd
|
|
20
|
+
.split(/\|\||&&|[;|&\n]/) // pipeline / list segments
|
|
21
|
+
.map((s) => s.trim())
|
|
22
|
+
.filter(Boolean)
|
|
23
|
+
.map((s) => s.replace(/^(?:[A-Za-z_][A-Za-z0-9_]*=\S+\s+)+/, "")) // strip leading VAR=val env prefixes
|
|
24
|
+
.map((s) => s.replace(/^(?:cd\s+\S+\s*(?:&&|;)\s*)/, "")) // strip a leading `cd x &&`
|
|
25
|
+
.map((s) => (s.split(/\s+/)[0] || "").replace(/^.*\//, "")); // basename of the head token
|
|
26
|
+
}
|
|
27
|
+
/** True when `cmd` is a real build/test/typecheck/run — i.e. counts as a verification. */
|
|
28
|
+
export function isVerifyCmd(cmd) {
|
|
29
|
+
if (!cmd)
|
|
30
|
+
return false;
|
|
31
|
+
if (segmentHeads(cmd).some((h) => VERIFY_HEADS.has(h)))
|
|
32
|
+
return true;
|
|
33
|
+
// Running a local script/binary is also a verify: ./x, bash x.sh, sh x.sh — but not `bash -c '...'`.
|
|
34
|
+
return /(?:^|\|\||&&|[;|&]\s*)\s*\.?\/\S/.test(cmd) || /\b(?:bash|sh|zsh)\s+[^-]\S*/.test(cmd);
|
|
35
|
+
}
|
|
36
|
+
/** True when a verify command demonstrably FAILED, so it must NOT count as a pass. Keys on the exit
|
|
37
|
+
* trailer surfaced by tools/registry.ts shellExec; absence of a failure marker = exit 0 = pass. */
|
|
38
|
+
export function ranButFailed(result) {
|
|
39
|
+
const m = result.match(/\[exit (-?\d+)\]/) || result.match(/\(no output; exit (-?\d+)\)/);
|
|
40
|
+
if (m)
|
|
41
|
+
return Number(m[1]) !== 0;
|
|
42
|
+
if (/timed out after \d+ms/.test(result))
|
|
43
|
+
return true;
|
|
44
|
+
if (/^error running command:/i.test(result.trim()))
|
|
45
|
+
return true;
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
import { MUTATING_TOOLS } from "../tools/mutating.js"; // single source of truth (see tools/mutating.ts)
|
|
49
|
+
const VERIFY_TOOLS = new Set(["bash", "shell_exec"]);
|
|
50
|
+
/** Turn-local ledger. The loop calls observe() after each tool batch, then gate() at the done-exit.
|
|
51
|
+
* Turn-scoped (one runTurn = one task): a verify from an earlier turn must not satisfy this turn's new
|
|
52
|
+
* changes — the same reason grandmaster re-derives `verified` per result and never trusts prior state. */
|
|
53
|
+
export class TaskVerification {
|
|
54
|
+
mutated = false;
|
|
55
|
+
verified = false;
|
|
56
|
+
/** names[i] / commands[i] / results[i] are index-aligned: a batch of tool calls and their result
|
|
57
|
+
* strings. `commands[i]` is the shell command for bash/shell_exec calls, "" otherwise. */
|
|
58
|
+
observe(names, commands, results) {
|
|
59
|
+
for (let i = 0; i < names.length; i++) {
|
|
60
|
+
const name = names[i];
|
|
61
|
+
const res = results[i] ?? "";
|
|
62
|
+
if (MUTATING_TOOLS.has(name) && !/^error/i.test(res.trim()))
|
|
63
|
+
this.mutated = true;
|
|
64
|
+
if (VERIFY_TOOLS.has(name) && isVerifyCmd(commands[i] ?? "") && !ranButFailed(res))
|
|
65
|
+
this.verified = true;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** True ⇒ this turn changed code but never ran a passing check ⇒ nudge, then annotate. */
|
|
69
|
+
gate() {
|
|
70
|
+
return this.mutated && !this.verified;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** Injected as a user-role message for the ONE extra round. Prefixed so its provenance is unmistakably the
|
|
74
|
+
* harness, not the user. Authorizes an honest escape so a docs edit / no-test repo ends cleanly, not stuck. */
|
|
75
|
+
export const VERIFY_REMINDER = "[verify-before-done] You changed files this turn and are wrapping up, but no test, build, or run was " +
|
|
76
|
+
"observed. Run the real check now — the test suite, the build (e.g. npm run build / tsc), or the exact " +
|
|
77
|
+
"command or CLI you changed — and report what it printed. If there is genuinely nothing runnable to " +
|
|
78
|
+
"check, say so in one line and name what stays unverified. Don't apologize or re-explain; just run it, " +
|
|
79
|
+
"or state plainly why you can't.";
|
|
80
|
+
/** Prefixed to the final answer when a turn changed files but never ran a passing check (nudge spent). */
|
|
81
|
+
export const NOT_VERIFIED_BANNER = "⚠ Not verified — I changed files but did not run a passing check this turn.\n\n";
|
package/dist/mcp/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { loadMcpConfig } from "./config.js";
|
|
2
2
|
import { McpHttpClient } from "./client.js";
|
|
3
3
|
import { McpStdioClient } from "./stdio.js";
|
|
4
|
-
import { capToolResult } from "../tools/
|
|
4
|
+
import { capToolResult } from "../tools/result-cap.js"; // browser-safe: never import tools/executor.js here (node:path + registry)
|
|
5
5
|
const SEP = ":"; // namespace separator: "compose:compose_list"
|
|
6
6
|
// MCP servers that ship STANDARD with Operator — always available, independent of the full-fleet `mcp`
|
|
7
7
|
// setting. report-mcp (ReportLab PDF generation) is core: a coding agent should be able to produce a
|
|
@@ -12,7 +12,10 @@ export function withPermissions(inner, policy, opts = {}) {
|
|
|
12
12
|
const actor = opts.actor ?? { tier: policy.currentTier(), surface: "cli" };
|
|
13
13
|
const session = opts.session ?? "";
|
|
14
14
|
const tool = (t) => sink?.emit({ kind: "tool", session, actor, tool: t });
|
|
15
|
-
|
|
15
|
+
// `batch` carries the round identity a PendingToolCall was stamped with (engine/agent.ts's
|
|
16
|
+
// runToolCalls) onto every ToolEvent this call emits — absent for the single-call execute() path,
|
|
17
|
+
// which has no round context.
|
|
18
|
+
async function gate(name, args, exec, batch) {
|
|
16
19
|
const digest = digestArgs(name, args);
|
|
17
20
|
const decision = policy.decide(name, args);
|
|
18
21
|
const t0 = performance.now();
|
|
@@ -20,10 +23,10 @@ export function withPermissions(inner, policy, opts = {}) {
|
|
|
20
23
|
// Distinguish a tier-ceiling denial (this seat can't have the tool at all) from a rule/mode denial.
|
|
21
24
|
if (!policy.allowsTool(name)) {
|
|
22
25
|
sink?.emit({ kind: "control", session, actor, control: { event: "tool_denied_by_tier", detail: `${name} @ ${actor.tier}` } });
|
|
23
|
-
tool({ name, args: digest, decision, outcome: "denied", approved: false });
|
|
26
|
+
tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch });
|
|
24
27
|
return TIER_DENIED(name, actor.tier);
|
|
25
28
|
}
|
|
26
|
-
tool({ name, args: digest, decision, outcome: "denied", approved: false });
|
|
29
|
+
tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch });
|
|
27
30
|
return DENIED(name);
|
|
28
31
|
}
|
|
29
32
|
let approved;
|
|
@@ -35,7 +38,7 @@ export function withPermissions(inner, policy, opts = {}) {
|
|
|
35
38
|
sink?.emit({ kind: "control", session, actor, control: { event: "signature_required", detail: `${line}: ${name}` } });
|
|
36
39
|
approved = opts.approve ? await opts.approve(name, args) : false; // no approver ⇒ fail-safe deny
|
|
37
40
|
if (!approved) {
|
|
38
|
-
tool({ name, args: digest, decision, outcome: "denied", approved: false });
|
|
41
|
+
tool({ name, args: digest, decision, outcome: "denied", approved: false, ...batch });
|
|
39
42
|
return DENIED(name);
|
|
40
43
|
}
|
|
41
44
|
}
|
|
@@ -45,11 +48,11 @@ export function withPermissions(inner, policy, opts = {}) {
|
|
|
45
48
|
}
|
|
46
49
|
catch (e) {
|
|
47
50
|
// The inner executor's contract is resolve-not-reject; if one ever throws, record + surface as a string.
|
|
48
|
-
tool({ name, args: digest, decision, outcome: "error", approved, durationMs: performance.now() - t0 });
|
|
51
|
+
tool({ name, args: digest, decision, outcome: "error", approved, durationMs: performance.now() - t0, ...batch });
|
|
49
52
|
return `error: ${e instanceof Error ? e.message : String(e)}`;
|
|
50
53
|
}
|
|
51
54
|
const outcome = /^error/i.test(result.trim()) ? "error" : "ok";
|
|
52
|
-
tool({ name, args: digest, decision, outcome, approved, durationMs: performance.now() - t0 });
|
|
55
|
+
tool({ name, args: digest, decision, outcome, approved, durationMs: performance.now() - t0, ...batch });
|
|
53
56
|
return result;
|
|
54
57
|
}
|
|
55
58
|
return {
|
|
@@ -59,7 +62,10 @@ export function withPermissions(inner, policy, opts = {}) {
|
|
|
59
62
|
// pre-denied call to inner.executeParallel, so route per-call through execute (the executor's
|
|
60
63
|
// own read-only/mutating parallelism still applies to the ones that reach it via execute).
|
|
61
64
|
Promise.all(calls.map(async (c, i) => {
|
|
62
|
-
const
|
|
65
|
+
const batch = c.batchId !== undefined
|
|
66
|
+
? { batchId: c.batchId, batchSize: c.batchSize ?? calls.length, batchIndex: c.batchIndex ?? i }
|
|
67
|
+
: undefined;
|
|
68
|
+
const r = await gate(c.name, c.args, () => inner.execute(c.name, c.args), batch);
|
|
63
69
|
onSettle?.(i, r);
|
|
64
70
|
return r;
|
|
65
71
|
})),
|
package/dist/router/models.js
CHANGED
|
@@ -1,7 +1,15 @@
|
|
|
1
|
-
export const DEFAULT_MODEL_ID = "
|
|
1
|
+
export const DEFAULT_MODEL_ID = "operator-1m";
|
|
2
|
+
// Back-compat aliases: the user-facing ids were renamed aurora-* -> operator-* (the outward name is
|
|
3
|
+
// Operator; "aurora" is the internal model, never shown). The OLD ids still resolve — a persisted
|
|
4
|
+
// settings.activeModel: "aurora-1m", a `/model aurora-1m`, or any muscle memory keeps working — so the
|
|
5
|
+
// rename loses nothing. The served model name ("aurora-code-1") + endpoints stay internal, untouched.
|
|
6
|
+
export const MODEL_ALIASES = {
|
|
7
|
+
"aurora-1m": "operator-1m",
|
|
8
|
+
"aurora-128k": "operator-128k",
|
|
9
|
+
};
|
|
2
10
|
export const BUILTIN_MODELS = [
|
|
3
|
-
{ id: "
|
|
4
|
-
{ id: "
|
|
11
|
+
{ id: "operator-1m", label: "Operator 300K", kind: "single", desc: "307,200-token (300K) context (:8097)", endpoint: "http://127.0.0.1:8097/v1", model: "aurora-code-1", ctx: 307200 },
|
|
12
|
+
{ id: "operator-128k", label: "Operator 128K", kind: "single", desc: "128K context, lighter RAM (:8096)", endpoint: "http://127.0.0.1:8096/v1", model: "aurora-code-1", ctx: 131072 },
|
|
5
13
|
{ id: "moa", label: "MOA (Mixture of Agents)", kind: "orchestrated", desc: "fan out to proposers, synthesize with an aggregator" },
|
|
6
14
|
];
|
|
7
15
|
/** The runtime registry: the built-ins, with any settings.models entries merged in (overriding a
|
|
@@ -15,7 +23,8 @@ export function modelRegistry(overrides) {
|
|
|
15
23
|
return [...byId.values()];
|
|
16
24
|
}
|
|
17
25
|
export function findModel(registry, id) {
|
|
18
|
-
|
|
26
|
+
const canon = MODEL_ALIASES[id] ?? id; // aurora-1m -> operator-1m (old ids keep resolving)
|
|
27
|
+
return registry.find((m) => m.id === canon);
|
|
19
28
|
}
|
|
20
29
|
/** Pure selection reducer for /model — no I/O (no settings read/write, no router mutation), so it's
|
|
21
30
|
* directly testable. The moa-needs-config check lives in Session.setModel (it needs settings.moa,
|
package/dist/router/router.js
CHANGED
|
@@ -1,16 +1,21 @@
|
|
|
1
1
|
// ONE model: Aurora at its native 1M context on :8097 (the air/1m/saddle roster collapsed here once 1M
|
|
2
2
|
// served at full speed). The router still handles N endpoints generically; this default just has one.
|
|
3
3
|
const DEFAULT_ENDPOINTS = [
|
|
4
|
-
{ name: "aurora", base: "http://127.0.0.1:8097", model: "aurora", ctxLimit:
|
|
4
|
+
{ name: "aurora", base: "http://127.0.0.1:8097", model: "aurora", ctxLimit: 307200 },
|
|
5
5
|
];
|
|
6
6
|
// Leave headroom under the hard ctx limit — mirrors SPEC §5's 0.85 compaction threshold, so
|
|
7
7
|
// routing and compaction agree on what "fits."
|
|
8
8
|
const FIT_MARGIN = 0.85;
|
|
9
|
+
const UNHEALTHY_COOLDOWN_MS = 45_000; // circuit-breaker half-open: a failed endpoint is retried after this,
|
|
10
|
+
// so a session that failed over to a standby CLIMBS BACK to the
|
|
11
|
+
// primary once it recovers instead of stranding on failover forever.
|
|
9
12
|
export class AuroraRouter {
|
|
10
13
|
endpoints;
|
|
11
14
|
idx = 0;
|
|
12
|
-
|
|
13
|
-
|
|
15
|
+
sizeFloor = 0; // highest index SIZE-escalation has required — sticky upward (never de-escalate on
|
|
16
|
+
// size). Kept separate from failover so a health-hop can recover without losing it.
|
|
17
|
+
unhealthy = new Map(); // endpoint name -> when its unhealthy mark expires (ms)
|
|
18
|
+
pinned = typeof process !== "undefined" && process.env?.KODE_NO_ROUTER === "1";
|
|
14
19
|
constructor(endpoints = DEFAULT_ENDPOINTS) {
|
|
15
20
|
if (!endpoints.length)
|
|
16
21
|
throw new Error("AuroraRouter needs at least one endpoint");
|
|
@@ -31,19 +36,37 @@ export class AuroraRouter {
|
|
|
31
36
|
routeBySize(approxTokens) {
|
|
32
37
|
if (this.pinned)
|
|
33
38
|
return this.current();
|
|
34
|
-
|
|
39
|
+
// Expire stale unhealthy marks first, so a recovered endpoint becomes eligible again (auto-recover).
|
|
40
|
+
const now = Date.now();
|
|
41
|
+
for (const [name, until] of this.unhealthy)
|
|
42
|
+
if (until <= now)
|
|
43
|
+
this.unhealthy.delete(name);
|
|
44
|
+
// Size need: smallest endpoint that fits. Raise the sticky floor to it — never de-escalate on size.
|
|
45
|
+
let need = this.endpoints.length - 1;
|
|
46
|
+
for (let i = 0; i < this.endpoints.length; i++) {
|
|
35
47
|
if (approxTokens <= this.endpoints[i].ctxLimit * FIT_MARGIN) {
|
|
48
|
+
need = i;
|
|
49
|
+
break;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
this.sizeFloor = Math.max(this.sizeFloor, need);
|
|
53
|
+
// From the size floor upward, pick the first HEALTHY endpoint. Starting at the floor (not at the last
|
|
54
|
+
// failover index) is what lets a failed-over session CLIMB BACK once the primary/lower endpoint's
|
|
55
|
+
// unhealthy mark expires — without ever dropping below what size requires.
|
|
56
|
+
for (let i = this.sizeFloor; i < this.endpoints.length; i++) {
|
|
57
|
+
if (!this.unhealthy.has(this.endpoints[i].name)) {
|
|
36
58
|
this.idx = i;
|
|
37
59
|
return this.current();
|
|
38
60
|
}
|
|
39
61
|
}
|
|
40
|
-
//
|
|
62
|
+
// Everything at/above the floor is still in cooldown — best effort: the largest endpoint.
|
|
41
63
|
this.idx = this.endpoints.length - 1;
|
|
42
64
|
return this.current();
|
|
43
65
|
}
|
|
44
66
|
escalate() {
|
|
45
67
|
if (this.pinned)
|
|
46
68
|
return this.current();
|
|
69
|
+
this.sizeFloor = this.endpoints.length - 1; // jump to the largest and stay there (sticky, like size)
|
|
47
70
|
this.idx = this.endpoints.length - 1;
|
|
48
71
|
return this.current();
|
|
49
72
|
}
|
|
@@ -51,7 +74,7 @@ export class AuroraRouter {
|
|
|
51
74
|
if (this.pinned)
|
|
52
75
|
return this.current();
|
|
53
76
|
const failed = this.current().name;
|
|
54
|
-
this.unhealthy.
|
|
77
|
+
this.unhealthy.set(failed, Date.now() + UNHEALTHY_COOLDOWN_MS);
|
|
55
78
|
const candidate = this.endpoints.find(e => e.name !== failed && !this.unhealthy.has(e.name))
|
|
56
79
|
?? this.endpoints.find(e => e.name !== failed)
|
|
57
80
|
?? this.current();
|
|
@@ -62,6 +85,19 @@ export class AuroraRouter {
|
|
|
62
85
|
markHealthy(name) {
|
|
63
86
|
this.unhealthy.delete(name);
|
|
64
87
|
}
|
|
88
|
+
/** Learn an endpoint's REAL served context window from a server that just rejected a request for
|
|
89
|
+
* exceeding it (its 400 body names n_ctx). The configured ctxLimit is often optimistic — a node's
|
|
90
|
+
* llama.cpp `-c` can be smaller than the roster claims (09-26: JL2 served 64K, configured 256K) — so we
|
|
91
|
+
* clamp DOWN to what the server enforces. Monotonic (never raises), so size-routing and compaction stop
|
|
92
|
+
* overflowing it for the rest of the session. Matched by base URL; a no-op if none matches or the
|
|
93
|
+
* observed value isn't smaller than what's configured. */
|
|
94
|
+
observeContextLimit(base, servedCtx) {
|
|
95
|
+
if (!(servedCtx > 0))
|
|
96
|
+
return;
|
|
97
|
+
const ep = this.endpoints.find((e) => e.base === base);
|
|
98
|
+
if (ep && servedCtx < ep.ctxLimit)
|
|
99
|
+
ep.ctxLimit = servedCtx;
|
|
100
|
+
}
|
|
65
101
|
/** All configured endpoints (for /endpoints). */
|
|
66
102
|
list() {
|
|
67
103
|
return this.endpoints;
|
|
@@ -80,6 +116,7 @@ export class AuroraRouter {
|
|
|
80
116
|
if (i < 0)
|
|
81
117
|
return false;
|
|
82
118
|
this.idx = i;
|
|
119
|
+
this.sizeFloor = i; // a pin is a hard position — after unpin, stay here until resetTurn (not failover-soft)
|
|
83
120
|
this.pinned = true;
|
|
84
121
|
return true;
|
|
85
122
|
}
|
|
@@ -88,7 +125,9 @@ export class AuroraRouter {
|
|
|
88
125
|
// an endpoint that had a transient failure last turn isn't permanently blacklisted from failover.
|
|
89
126
|
resetTurn() {
|
|
90
127
|
this.unhealthy.clear();
|
|
91
|
-
if (!this.pinned)
|
|
128
|
+
if (!this.pinned) {
|
|
92
129
|
this.idx = 0;
|
|
130
|
+
this.sizeFloor = 0;
|
|
131
|
+
}
|
|
93
132
|
}
|
|
94
133
|
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Operator self-improvement loop. Every completed turn is captured as a graded trajectory (the FLYWHEEL
|
|
2
|
+
// sink) so the fleet compounds from real usage — this is the "out of the box" learning loop. The same
|
|
3
|
+
// per-turn hook is where the other sinks layer in: MEMORY distillation, SKILL capture, and post-task
|
|
4
|
+
// REFLECTION. All sinks are best-effort and MUST never block or throw into a turn. Node imports are lazy
|
|
5
|
+
// (same mobile/JSCore-bundle discipline as services/preflight.ts) so the neutral bundle carries none of it.
|
|
6
|
+
const nodeImport = (m) => import(/* @vite-ignore */ m);
|
|
7
|
+
/** FLYWHEEL sink — append the turn as one JSONL row to a daily capture the fleet's training pipeline reads.
|
|
8
|
+
* A turn that produced content, ran ≥1 round, and wasn't cut for repetition/abort is marked graded:true,
|
|
9
|
+
* so downstream can filter to promotable trajectories without re-judging every row. */
|
|
10
|
+
async function captureFlywheel(r) {
|
|
11
|
+
try {
|
|
12
|
+
const { appendFile, mkdir } = await nodeImport("node:fs/promises");
|
|
13
|
+
const { join } = await nodeImport("node:path");
|
|
14
|
+
const home = process.env.HOME ?? "";
|
|
15
|
+
if (!home)
|
|
16
|
+
return;
|
|
17
|
+
const dir = join(home, ".axe", "operator", "flywheel");
|
|
18
|
+
await mkdir(dir, { recursive: true });
|
|
19
|
+
// graded = a promotable trajectory. A turn that changed files but never ran a passing check
|
|
20
|
+
// (unverified, per the verify-before-done gate) is NOT promotable — that is precisely the hollow
|
|
21
|
+
// "done" this whole loop exists to stop the fleet from training on.
|
|
22
|
+
const graded = !!r.content.trim() && r.stopReason !== "repetition" && r.rounds > 0 && !r.unverified;
|
|
23
|
+
const row = JSON.stringify({ ts: Date.now(), graded, ...r }) + "\n";
|
|
24
|
+
await appendFile(join(dir, `${new Date().toISOString().slice(0, 10)}.jsonl`), row);
|
|
25
|
+
}
|
|
26
|
+
catch { /* best-effort — capture never blocks or fails a turn */ }
|
|
27
|
+
}
|
|
28
|
+
/** True when a turn ended STUCK — a loop/guard stop, not a normal completion. The forced-redirect and
|
|
29
|
+
* self-loop guards both hand back a "[stopped — …]" note; a repetition stopReason is the other signal.
|
|
30
|
+
* A normal answer, or an empty (aborted) turn, is NOT a lesson. */
|
|
31
|
+
function endedStuck(r) {
|
|
32
|
+
return r.stopReason === "repetition" || /^\[stopped\s[—-]/.test(r.content.trim());
|
|
33
|
+
}
|
|
34
|
+
/** MEMORY sink (the closed self-improvement loop). When a turn ends STUCK, append a concise, deduplicated
|
|
35
|
+
* LESSON to this repo's `.operator/memories.md` — the flat memory `persona.loadMemories()` injects into
|
|
36
|
+
* EVERY future session's system prompt here. So a failure the agent hit once becomes durable, always-loaded
|
|
37
|
+
* context and it doesn't walk into the same trap next time. Deterministic (no LLM pass): the lesson is the
|
|
38
|
+
* task + the gist of what it got stuck on + the standing advice (decompose / switch / do sub-agent work
|
|
39
|
+
* inline). Best-effort, never blocks a turn, and OPT-IN (settings.selfImprove.memory, default off) since it
|
|
40
|
+
* writes into the repo. An LLM-distilled, higher-insight version is the next increment. */
|
|
41
|
+
async function captureFailureLesson(r) {
|
|
42
|
+
try {
|
|
43
|
+
if (!endedStuck(r) || !r.cwd)
|
|
44
|
+
return;
|
|
45
|
+
const gist = r.content.trim().replace(/\s+/g, " ").slice(0, 220);
|
|
46
|
+
const task = r.input.trim().replace(/\s+/g, " ").slice(0, 90);
|
|
47
|
+
const { readFile, appendFile, writeFile, mkdir } = await nodeImport("node:fs/promises");
|
|
48
|
+
const { join, dirname } = await nodeImport("node:path");
|
|
49
|
+
const file = join(r.cwd, ".operator", "memories.md");
|
|
50
|
+
let existing = "";
|
|
51
|
+
try {
|
|
52
|
+
existing = await readFile(file, "utf8");
|
|
53
|
+
}
|
|
54
|
+
catch { /* none yet */ }
|
|
55
|
+
// Dedup: skip if a lesson for this task with this gist is already recorded (avoids re-logging a
|
|
56
|
+
// repeated failure every session).
|
|
57
|
+
const dedupKey = gist.slice(0, 70);
|
|
58
|
+
if (existing.includes(`task "${task}"`) && existing.includes(dedupKey))
|
|
59
|
+
return;
|
|
60
|
+
const date = new Date().toISOString().slice(0, 10);
|
|
61
|
+
const lesson = `- [${date}] Got stuck on task "${task}": ${gist} — next time, break the step down or switch approach ` +
|
|
62
|
+
`early instead of repeating; if it involved sub-agents contending for one model endpoint, do the work inline.`;
|
|
63
|
+
const HEADING = "## Lessons (auto-captured from stuck sessions)";
|
|
64
|
+
if (!existing.trim()) {
|
|
65
|
+
await mkdir(dirname(file), { recursive: true });
|
|
66
|
+
await writeFile(file, `# Operator memory — ${r.cwd}\n\n${HEADING}\n${lesson}\n`);
|
|
67
|
+
}
|
|
68
|
+
else if (existing.includes(HEADING)) {
|
|
69
|
+
await appendFile(file, `${lesson}\n`);
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
await appendFile(file, `\n${HEADING}\n${lesson}\n`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
catch { /* best-effort — never blocks or fails a turn */ }
|
|
76
|
+
}
|
|
77
|
+
/** Run the enabled self-improvement sinks for one completed turn. Fire-and-forget from the session. */
|
|
78
|
+
export async function runSelfImprove(cfg, r) {
|
|
79
|
+
if (!cfg)
|
|
80
|
+
return;
|
|
81
|
+
if (cfg.flywheel !== false)
|
|
82
|
+
await captureFlywheel(r);
|
|
83
|
+
if (cfg.memory)
|
|
84
|
+
await captureFailureLesson(r); // opt-in closed loop: a stuck session leaves a durable lesson
|
|
85
|
+
// skills / reflect sinks hang off this same hook — implemented incrementally.
|
|
86
|
+
}
|
|
87
|
+
// Exposed for tests: the stuck-detection predicate is the trigger for the memory sink.
|
|
88
|
+
export { endedStuck };
|
|
@@ -17,6 +17,18 @@ const nodeImport = (m) => import(/* @vite-ignore */ m);
|
|
|
17
17
|
function expandHome(p) {
|
|
18
18
|
return p.startsWith("~/") ? `${process.env.HOME ?? ""}${p.slice(1)}` : p;
|
|
19
19
|
}
|
|
20
|
+
/** True iff the path exists. Lazy fs import (same mobile-bundle discipline as launchctl) — on a bundle
|
|
21
|
+
* with no node:fs it resolves false, so a missing-plist guard degrades to "skip", never a throw. */
|
|
22
|
+
async function fileExists(p) {
|
|
23
|
+
try {
|
|
24
|
+
const { access } = await nodeImport("node:fs/promises");
|
|
25
|
+
await access(p);
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
20
32
|
/** Run a launchctl subcommand, resolving { code, out }. Never throws (missing binary -> code 127). */
|
|
21
33
|
async function launchctl(args, timeoutMs = 15_000) {
|
|
22
34
|
const { execFile } = await nodeImport("node:child_process");
|
|
@@ -75,6 +87,18 @@ async function ensureLaunchd(name, healthUrl, okOnly, cfg, onProgress) {
|
|
|
75
87
|
const uid = typeof process.getuid === "function" ? process.getuid() : NaN;
|
|
76
88
|
if (!label || Number.isNaN(uid))
|
|
77
89
|
return { name, state: "down", detail: "down (no launchd label/uid)" };
|
|
90
|
+
// A plist that isn't on disk can never be bootstrapped — running the launchctl dance and then polling
|
|
91
|
+
// a port that will never answer is exactly the ~45s "frozen on 'starting … via launchd…'" boot hang
|
|
92
|
+
// (a fresh box with no autopilot installed). Skip INSTANTLY. Optionally kick a detached installer so a
|
|
93
|
+
// later launch has it, but NEVER block the REPL on an optional companion's install.
|
|
94
|
+
if (cfg.plistPath && !(await fileExists(expandHome(cfg.plistPath)))) {
|
|
95
|
+
if (process.env.KODE_AUTO_INSTALL_SERVICES === "1") {
|
|
96
|
+
onProgress?.(`${name} not installed — installing in background…`);
|
|
97
|
+
void installCompanion(name).catch(() => undefined);
|
|
98
|
+
return { name, state: "skipped", detail: `not installed — installing in background (operator setup-services)` };
|
|
99
|
+
}
|
|
100
|
+
return { name, state: "skipped", detail: `not installed (${expandHome(cfg.plistPath)} missing) — run: operator setup-services` };
|
|
101
|
+
}
|
|
78
102
|
onProgress?.(`starting ${name} via launchd…`);
|
|
79
103
|
const target = `gui/${uid}/${label}`;
|
|
80
104
|
// 1) fast path: the job is loaded but its port died — kick it.
|
|
@@ -103,10 +127,27 @@ export async function ensureServices(cfg) {
|
|
|
103
127
|
reports.push(await ensureLaunchd("aurora", `${cfg.aurora.base.replace(/\/$/, "")}/health`, true, cfg.aurora, cfg.onProgress));
|
|
104
128
|
if (cfg.autopilot) {
|
|
105
129
|
const url = (cfg.autopilot.url ?? "http://127.0.0.1:9333").replace(/\/$/, "");
|
|
106
|
-
|
|
130
|
+
// Optional service: cap the readiness wait hard so a present-but-unhealthy autopilot can never hold
|
|
131
|
+
// the REPL for the required-service budget (Aurora's 90s). A real `node serve` answers in <2s.
|
|
132
|
+
const apCfg = { ...cfg.autopilot, waitSec: Math.min(cfg.autopilot.waitSec ?? 8, 8) };
|
|
133
|
+
reports.push(await ensureLaunchd("autopilot", `${url}/`, false, apCfg, cfg.onProgress));
|
|
107
134
|
}
|
|
108
135
|
return reports;
|
|
109
136
|
}
|
|
137
|
+
/** Best-effort install of an optional companion (autopilot / chauffeur) via the packaged setup script,
|
|
138
|
+
* DETACHED so it never blocks boot. Sourcing (fleet rsync / clone) lives in scripts/setup-services.sh —
|
|
139
|
+
* kept out of the JS so the mobile bundle carries no installer. No-ops if the script or spawn is absent. */
|
|
140
|
+
async function installCompanion(name) {
|
|
141
|
+
try {
|
|
142
|
+
const { spawn } = await nodeImport("node:child_process");
|
|
143
|
+
const script = new URL("../../scripts/setup-services.sh", import.meta.url).pathname;
|
|
144
|
+
if (!(await fileExists(script)))
|
|
145
|
+
return;
|
|
146
|
+
const child = spawn("bash", [script, name], { detached: true, stdio: "ignore" });
|
|
147
|
+
child.unref?.();
|
|
148
|
+
}
|
|
149
|
+
catch { /* installer unavailable — the boot already skipped cleanly, nothing else to do */ }
|
|
150
|
+
}
|
|
110
151
|
/** Prime a just-started (cold) Aurora with a 1-token request so the FIRST real turn doesn't pay the
|
|
111
152
|
* graph/Metal-shader warmup (the plist runs --no-warmup, so otherwise the owner's first turn eats it).
|
|
112
153
|
* Fire-and-forget: never awaited from boot, never throws — a failed warmup just means the old behavior. */
|