@0perator/operator 0.1.46 → 0.1.49
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 +49 -0
- package/dist/cli.js +66 -12
- package/dist/config/settings.js +20 -2
- package/dist/engine/moa.js +44 -0
- package/dist/remote/host.js +29 -3
- package/dist/router/models.js +35 -0
- package/dist/session.js +92 -8
- package/dist/tools/chauffeur.js +6 -0
- package/dist/tools/registry.js +45 -22
- package/dist/tools/sandbox.js +11 -0
- package/dist/tools/shell-session.js +118 -0
- package/dist/ui/App.js +2 -2
- package/dist/ui/QuestionPrompt.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,55 @@ Operator is AXE's terminal coding agent (npm `@0perator/operator`), running on t
|
|
|
4
4
|
Newest first. Every release bumps `src/cli.tsx` VERSION + `package.json`, adds an entry here, and ships to
|
|
5
5
|
npm + both git remotes (memjar/kode, axetechnologies/kode). Test counts are the full suite at that release.
|
|
6
6
|
|
|
7
|
+
## 0.1.48 — 2026-09-21
|
|
8
|
+
- Added: `/model` command — pick between `aurora-1m` (default, :8097), `aurora-128k` (:8096, lighter
|
|
9
|
+
RAM), or `moa` (Mixture of Agents) via an interactive picker (`/model`) or directly (`/model <id>`).
|
|
10
|
+
A single-profile switch rebuilds the session's router to point at that endpoint (`router/models.ts`,
|
|
11
|
+
`Session.setModel`) — no server is ever started/stopped, it only changes which endpoint THIS session
|
|
12
|
+
talks to. The choice persists to `operator/settings.json` (`activeModel`, `saveSettings`) and is
|
|
13
|
+
reapplied at startup. See `MOA-DESIGN.md`.
|
|
14
|
+
- Added: MOA (Mixture of Agents) execution mode (`engine/moa.ts`) — a turn fans out in PARALLEL to
|
|
15
|
+
`settings.moa`'s proposers (plain, tool-free chat completions), then runs the aggregator through the
|
|
16
|
+
normal turn loop (tool-calling, streaming, self-heal, telemetry all reused — v1 is aggregator-only
|
|
17
|
+
tool-calling) with the labelled candidate drafts folded into its system prompt. A proposer
|
|
18
|
+
failing/timing out is dropped, not fatal; zero survivors fall back to `aurora-1m` for that reply with
|
|
19
|
+
a clear note. `/model moa` without a `moa` block in settings explains what's missing instead of
|
|
20
|
+
running. Telemetry records which proposers ran, per-proposer latency, and which drafts survived.
|
|
21
|
+
- Added: `ask_user` remote-control relay emit (`RemoteHost.askUser`) — a clarification question is now
|
|
22
|
+
mirrored to `/remotecontrol` followers as a distinct `ask_user` frame (not folded into
|
|
23
|
+
`approval_request`); the follower's `ask_user_response` races first-wins against a local answer, same
|
|
24
|
+
pattern as approvals. Local (non-remote) `ask_user` is unchanged.
|
|
25
|
+
- Tests: +37 (`router/models.ts` registry + selection reducer, `engine/moa.ts` fan-out against real
|
|
26
|
+
local HTTP servers incl. a failing proposer, `Session.setModel`/MOA dispatch, `activeModel`
|
|
27
|
+
persistence round-trip, `RemoteHost` ask_user frame shape + response routing). Suite 317/317.
|
|
28
|
+
|
|
29
|
+
## 0.1.49 — 2026-09-21
|
|
30
|
+
- Added: **frontier `bash` tool** — a PERSISTENT shell session. `cd`, exported env vars, activated
|
|
31
|
+
venvs and shell functions now survive across bash calls like a real terminal, so the model sets
|
|
32
|
+
up once and reuses it instead of re-running `source .../activate && ...` on every call (the root
|
|
33
|
+
cause of the clumsy heredoc gymnastics + repeated-call loops seen in the wild). stdout/stderr come
|
|
34
|
+
back merged with the exit code; a per-command timeout kills+respawns the shell so a runaway command
|
|
35
|
+
can never wedge the session. `shell_exec` kept as a back-compat alias to the same engine.
|
|
36
|
+
- Implementation: `src/tools/shell-session.ts` (ShellSession, sentinel-framed, sandbox-wrapped via
|
|
37
|
+
`wrapInteractiveShell`); `registry.ts` routes shell_exec/bash through one per-process session; a
|
|
38
|
+
scoped `cwd` arg runs in a subshell so it doesn't silently move the session.
|
|
39
|
+
- Tests: +4 shell-session (cwd persists, env persists, stderr+exit surfaced, timeout recovers).
|
|
40
|
+
- 0.1.48 (Nova, merged earlier): /model command + MOA (Mixture of Agents) execution mode + model
|
|
41
|
+
registry (aurora-1m / aurora-128k / moa); ask_user remote-control relay emit; QuestionPrompt Ctrl-C
|
|
42
|
+
→ DISCUSS; RemoteHost inbound-frame sessionId/ownerSub guard. Variant B web on 0perator.co.
|
|
43
|
+
|
|
44
|
+
## 0.1.47 — 2026-09-21
|
|
45
|
+
- Added: agent-cursor overlay tools curated into chauffeur's unprompted read set
|
|
46
|
+
(`set_agent_cursor_enabled`, `set_agent_cursor_theme`, `get_agent_cursor_state`) so the owner can SEE the
|
|
47
|
+
agent's mouse move on screen instead of driving blind.
|
|
48
|
+
- Added: `verify_state` (bounded read-only post-condition check) curated as a read, so the model can confirm
|
|
49
|
+
an action landed instead of guessing from the next screenshot.
|
|
50
|
+
- Strengthened: EMBODIMENT_GUIDE now has a firm directive — for ANY on-screen/click/read/drive request the
|
|
51
|
+
model MUST call the chauffeur tools (first call: `list_windows`), never answer from memory or claim it
|
|
52
|
+
can't see the screen. It also now enables the agent cursor at the start of any on-screen task.
|
|
53
|
+
- Tests: +3 chauffeur curated-set tests (cursor tools land as unprompted reads, no duplicates and set stays
|
|
54
|
+
focused at 26 tools, no destructive/session-ending/recording/update tool sneaks in). Suite 280/280.
|
|
55
|
+
|
|
7
56
|
## 0.1.46 — 2026-09-21
|
|
8
57
|
- Added: `scratchpad` tool — a private per-session notes file OUTSIDE the workspace (read with no args;
|
|
9
58
|
append, or mode:"overwrite"), so the model can think/track progress without cluttering the repo.
|
package/dist/cli.js
CHANGED
|
@@ -12,7 +12,7 @@ import { RemoteHost } from "./remote/host.js";
|
|
|
12
12
|
import { Session } from "./session.js";
|
|
13
13
|
import { AuroraRouter } from "./router/router.js";
|
|
14
14
|
import { BackgroundAgents } from "./background/index.js";
|
|
15
|
-
import { loadSettings } from "./config/settings.js";
|
|
15
|
+
import { loadSettings, saveSettings } from "./config/settings.js";
|
|
16
16
|
import { EventSink } from "./telemetry/events.js";
|
|
17
17
|
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
18
18
|
import { expandFileMentions } from "./util/mentions.js";
|
|
@@ -21,7 +21,7 @@ import { homedir, hostname } from "node:os";
|
|
|
21
21
|
import { createHash } from "node:crypto";
|
|
22
22
|
// RELEASE CHECKLIST (every bump): update this + package.json "version", ADD A CHANGELOG.md ENTRY
|
|
23
23
|
// (improvements / fixes / tests), run the suite, then publish to npm + push both remotes.
|
|
24
|
-
const VERSION = "0.1.
|
|
24
|
+
const VERSION = "0.1.49";
|
|
25
25
|
// operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
|
|
26
26
|
const settings = loadSettings();
|
|
27
27
|
// Propagate the resolved sandbox mode to the tool layer (registry reads KODE_SANDBOX at exec time).
|
|
@@ -167,10 +167,14 @@ const EMBODIMENT_GUIDE = settings.computer.enabled
|
|
|
167
167
|
`computer_app_open / computer_app_activate, computer_type, computer_key, computer_click, computer_screenshot.` +
|
|
168
168
|
(chauffeurReady
|
|
169
169
|
? ` To SEE the screen use the chauffeur tools — NEVER shell_exec/osascript/System Events to read or drive ` +
|
|
170
|
-
`a GUI (AppleScript cannot read Electron apps like Slack/VS Code/Discord and just errors).
|
|
171
|
-
`
|
|
170
|
+
`a GUI (AppleScript cannot read Electron apps like Slack/VS Code/Discord and just errors). For ANY ` +
|
|
171
|
+
`request about what is on screen, or to click/read/drive an app, you MUST call the chauffeur tools — ` +
|
|
172
|
+
`never answer from memory and never say you cannot see the screen. First call: chauffeur:list_windows. ` +
|
|
173
|
+
`Correct usage, follow it exactly:\n` +
|
|
172
174
|
`- Do NOT pass a "session" argument to any chauffeur tool. Omit it — the implicit session is used ` +
|
|
173
175
|
`automatically. (Inventing a session label causes "session has ended" errors.)\n` +
|
|
176
|
+
`- At the START of any on-screen task, call chauffeur:set_agent_cursor_enabled {enabled: true} so the ` +
|
|
177
|
+
`owner can watch the agent's cursor move — do this before the first click/type/drag.\n` +
|
|
174
178
|
`- To read a window: call chauffeur:list_windows, take a window_id + pid FROM THAT RESULT, then ` +
|
|
175
179
|
`immediately chauffeur:get_window_state {pid, window_id} → a TEXT accessibility tree (roles, labels, ` +
|
|
176
180
|
`values, clickable elements + coordinates). window_ids go stale, so always list_windows again right ` +
|
|
@@ -217,7 +221,7 @@ const MAX_BG = 4; // concurrent background sub-agents — all share the single A
|
|
|
217
221
|
const HELP = [
|
|
218
222
|
"commands:",
|
|
219
223
|
" /help this list",
|
|
220
|
-
" /model
|
|
224
|
+
" /model [id] pick a model: aurora-1m · aurora-128k · moa (mixture-of-agents)",
|
|
221
225
|
" /endpoints show the aurora endpoint + live health",
|
|
222
226
|
" /services ensure/inspect the service lever (aurora+autopilot+searxng); /services stop",
|
|
223
227
|
" /audit [n] recent tool + control-plane events from the audit trail (default 15)",
|
|
@@ -270,11 +274,28 @@ function Root() {
|
|
|
270
274
|
// decision here and <ApprovalPrompt> renders it; the keystroke resolves the promise. "allow always"
|
|
271
275
|
// adds the tool to a per-session set so it stops prompting. (No approver ⇒ policy fail-safe denies.)
|
|
272
276
|
const [approval, setApproval] = useState(null);
|
|
273
|
-
// ask_user bridge: the model's clarification question, parked here until the owner
|
|
277
|
+
// ask_user bridge: the model's clarification question, parked here until the owner — locally, or a
|
|
278
|
+
// remote follower during /remotecontrol — picks an option. Mirrors the approval bridge's
|
|
279
|
+
// first-wins: both a local pick and a follower's ask_user_response settle through settleQuestion.
|
|
274
280
|
const [question, setQuestion] = useState(null);
|
|
281
|
+
const pendingQuestions = useRef(new Map());
|
|
282
|
+
const settleQuestion = useCallback((id, answer) => {
|
|
283
|
+
const resolve = pendingQuestions.current.get(id);
|
|
284
|
+
if (!resolve)
|
|
285
|
+
return; // already settled (first-wins)
|
|
286
|
+
pendingQuestions.current.delete(id);
|
|
287
|
+
resolve(answer);
|
|
288
|
+
setQuestion((cur) => (cur && cur.id === id ? null : cur));
|
|
289
|
+
}, []);
|
|
275
290
|
const askUser = useCallback((q, options) => new Promise((resolve) => {
|
|
276
|
-
|
|
277
|
-
|
|
291
|
+
const id = "q_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
|
|
292
|
+
pendingQuestions.current.set(id, resolve);
|
|
293
|
+
setQuestion({ id, question: q, options, resolve: (a) => settleQuestion(id, a) });
|
|
294
|
+
remoteRef.current?.askUser(id, q, options); // mirror to followers (owner-scoped)
|
|
295
|
+
}), [settleQuestion]);
|
|
296
|
+
// /model picker: same QuestionPrompt UI pattern as ask_user, but purely local (never relayed) —
|
|
297
|
+
// it's a session setting, not something the model is asking.
|
|
298
|
+
const [modelPicker, setModelPicker] = useState(null);
|
|
278
299
|
const alwaysAllowRef = useRef(new Set());
|
|
279
300
|
// Pending gated approvals by id. Both the local keystroke and a remote follower's approval_response
|
|
280
301
|
// route through settleApproval — FIRST answer wins (§7); the map delete makes it idempotent.
|
|
@@ -313,6 +334,9 @@ function Root() {
|
|
|
313
334
|
maxTokens: settings.maxTokens,
|
|
314
335
|
temperature: settings.temperature,
|
|
315
336
|
recall: settings.memory.recall,
|
|
337
|
+
models: settings.models, // /model registry overrides (router/models.ts has the built-in defaults)
|
|
338
|
+
moa: settings.moa, // MOA proposers/aggregator config (MOA-DESIGN.md); absent = "/model moa" explains
|
|
339
|
+
activeModel: settings.activeModel, // persisted /model choice, applied at startup
|
|
316
340
|
permissions: fgPermissions, // owner's policy + computer tools forced to "ask" when enabled (else bypass)
|
|
317
341
|
approve: approveFn, // renders the in-TUI approval prompt for any "ask" decision
|
|
318
342
|
askUser, // registers the ask_user tool so the model can put a clarifying question to the owner
|
|
@@ -581,9 +605,38 @@ function Root() {
|
|
|
581
605
|
setCtxPct(0);
|
|
582
606
|
sys("started a fresh conversation");
|
|
583
607
|
break;
|
|
584
|
-
case "model":
|
|
585
|
-
|
|
608
|
+
case "model": {
|
|
609
|
+
// Apply a selection (picker choice or `/model <id>`), persist it, and reflect it on the
|
|
610
|
+
// status rule right away — the router only updates its label mid-turn (onRoute), and MOA has
|
|
611
|
+
// no router of its own at all, so this is the one place that's always accurate immediately.
|
|
612
|
+
const apply = (id) => {
|
|
613
|
+
const r = s.setModel(id);
|
|
614
|
+
if (!r.ok) {
|
|
615
|
+
sys(`${r.error} — run /model for the list`);
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
setRoute(s.currentModel());
|
|
619
|
+
saveSettings({ activeModel: s.currentModel() });
|
|
620
|
+
sys(`model → ${s.currentModel()} · ctx ${s.ctxPct()}% · turns ${s.turnCount()}`);
|
|
621
|
+
};
|
|
622
|
+
if (arg) {
|
|
623
|
+
apply(arg);
|
|
624
|
+
break;
|
|
625
|
+
}
|
|
626
|
+
const active = s.currentModel();
|
|
627
|
+
const models = s.modelRegistry();
|
|
628
|
+
const options = models.map((m) => `${m.label}${m.id === active ? " (active)" : ""}`);
|
|
629
|
+
setModelPicker({
|
|
630
|
+
question: "Select a model",
|
|
631
|
+
options,
|
|
632
|
+
resolve: (answer) => {
|
|
633
|
+
setModelPicker(null);
|
|
634
|
+
const idx = options.indexOf(answer);
|
|
635
|
+
apply(idx >= 0 ? models[idx].id : answer.trim());
|
|
636
|
+
},
|
|
637
|
+
});
|
|
586
638
|
break;
|
|
639
|
+
}
|
|
587
640
|
case "route":
|
|
588
641
|
if (s.pinRoute(arg || "auto"))
|
|
589
642
|
sys(arg && arg !== "auto" ? `routing pinned to ${arg}` : "routing set to auto (by size)");
|
|
@@ -782,6 +835,7 @@ function Root() {
|
|
|
782
835
|
const rh = new RemoteHost(url, token, { title: `Operator · ${process.cwd().split("/").pop() || "session"}`, cwd: process.cwd(), host: hostname(), surface: "cli" }, {
|
|
783
836
|
onPrompt: (text) => submitRef.current(text), // follower drives a turn
|
|
784
837
|
onApprovalResponse: (id, approve) => settleApproval(id, approve), // first-wins with local
|
|
838
|
+
onAskUserResponse: (id, answer) => settleQuestion(id, answer), // first-wins with local
|
|
785
839
|
onInterrupt: () => s.interrupt(), // follower cancels the turn
|
|
786
840
|
onState: (st, detail) => {
|
|
787
841
|
if (st === "live")
|
|
@@ -804,7 +858,7 @@ function Root() {
|
|
|
804
858
|
}
|
|
805
859
|
default: sys(`unknown command /${name} — try /help`);
|
|
806
860
|
}
|
|
807
|
-
}, [exit, sys, bg, authUser, approval, settleApproval]);
|
|
861
|
+
}, [exit, sys, bg, authUser, approval, settleApproval, settleQuestion]);
|
|
808
862
|
const onSubmit = useCallback((text) => {
|
|
809
863
|
const t = text.trim();
|
|
810
864
|
if (t.startsWith("/")) {
|
|
@@ -853,7 +907,7 @@ function Root() {
|
|
|
853
907
|
? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
|
|
854
908
|
: `${spin} ${fmtMeta(elapsed, liveTok)}`
|
|
855
909
|
: metrics;
|
|
856
|
-
return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, route: route, ctxPct: ctxPct, version: VERSION, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, approval: approval, question: question, onApprovalDecide: (allow, always) => {
|
|
910
|
+
return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, route: route, ctxPct: ctxPct, version: VERSION, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, approval: approval, question: question, modelPicker: modelPicker, onApprovalDecide: (allow, always) => {
|
|
857
911
|
const cur = approval;
|
|
858
912
|
if (cur)
|
|
859
913
|
settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
|
package/dist/config/settings.js
CHANGED
|
@@ -2,9 +2,10 @@
|
|
|
2
2
|
// agent's settings.json. Loaded once at startup by cli.tsx. Precedence: env var > settings.json > built-in
|
|
3
3
|
// default. Never throws — a missing or malformed file just falls back to defaults, same as an env
|
|
4
4
|
// var that was never set.
|
|
5
|
-
import { readFileSync } from "node:fs";
|
|
5
|
+
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
6
6
|
import { homedir } from "node:os";
|
|
7
|
-
import { join } from "node:path";
|
|
7
|
+
import { join, dirname } from "node:path";
|
|
8
|
+
import { DEFAULT_MODEL_ID } from "../router/models.js";
|
|
8
9
|
// The sole endpoint: Aurora on :8097 at its REAL served context — 1,048,576 tokens (the native window
|
|
9
10
|
// of the Qwen3.5-MoE hybrid-linear-attention base; verified via /props). This is the one model
|
|
10
11
|
// kode/operator serves. Override base/model in settings.json to point at any OpenAI-compatible server.
|
|
@@ -33,6 +34,7 @@ const DEFAULTS = {
|
|
|
33
34
|
autopilot: { autostart: true, launchdLabel: "com.axe.autopilot", plistPath: "~/Library/LaunchAgents/com.axe.autopilot.plist", url: "http://127.0.0.1:9333" },
|
|
34
35
|
stopOnExit: { searxng: true }, // aurora/autopilot are shared + never stopped; only the SearXNG container is
|
|
35
36
|
},
|
|
37
|
+
activeModel: DEFAULT_MODEL_ID, // /model default — the 1M endpoint, unchanged from before /model existed
|
|
36
38
|
};
|
|
37
39
|
function settingsPath() {
|
|
38
40
|
return process.env.KODE_TSI_SETTINGS ?? join(homedir(), ".axe", "operator", "settings.json");
|
|
@@ -118,3 +120,19 @@ export function loadSettings() {
|
|
|
118
120
|
// otherwise flow through by reference and a later mutation would corrupt defaults process-wide.
|
|
119
121
|
return applyEnv(deepMerge(structuredClone(DEFAULTS), file));
|
|
120
122
|
}
|
|
123
|
+
/** Persist a partial settings patch onto whatever's on disk (deep-merged, file values win over
|
|
124
|
+
* defaults for anything the patch doesn't touch), so a runtime choice like /model survives a
|
|
125
|
+
* restart. Best-effort — same "never throws" contract as loadSettings; a write failure just means
|
|
126
|
+
* the choice doesn't survive a restart, it doesn't affect the running process. */
|
|
127
|
+
export function saveSettings(patch) {
|
|
128
|
+
const path = settingsPath();
|
|
129
|
+
const current = readSettingsFile(path);
|
|
130
|
+
const merged = deepMerge(isPlainObject(current) ? current : {}, patch);
|
|
131
|
+
try {
|
|
132
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
133
|
+
writeFileSync(path, JSON.stringify(merged, null, 2) + "\n", "utf8");
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
/* best-effort — see loadSettings */
|
|
137
|
+
}
|
|
138
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
const PROPOSER_TIMEOUT_MS = 60_000;
|
|
2
|
+
/** One proposer call: a plain (non-streaming, tool-free) OpenAI-compatible chat completion. Never
|
|
3
|
+
* throws — a failure or timeout comes back as a draft with empty content + an `error`, so the
|
|
4
|
+
* caller can drop it without the whole fan-out failing (a proposer is a nice-to-have, not a
|
|
5
|
+
* dependency). */
|
|
6
|
+
async function callProposer(p, messages) {
|
|
7
|
+
const t0 = performance.now();
|
|
8
|
+
const ctrl = new AbortController();
|
|
9
|
+
const timer = setTimeout(() => ctrl.abort(), PROPOSER_TIMEOUT_MS);
|
|
10
|
+
try {
|
|
11
|
+
const res = await fetch(`${p.endpoint.replace(/\/$/, "")}/chat/completions`, {
|
|
12
|
+
method: "POST",
|
|
13
|
+
headers: { "content-type": "application/json" },
|
|
14
|
+
body: JSON.stringify({ model: p.model, messages, stream: false }),
|
|
15
|
+
signal: ctrl.signal,
|
|
16
|
+
});
|
|
17
|
+
if (!res.ok)
|
|
18
|
+
return { id: p.id, content: "", ms: Math.round(performance.now() - t0), error: `http ${res.status}` };
|
|
19
|
+
const json = await res.json();
|
|
20
|
+
const content = String(json?.choices?.[0]?.message?.content ?? "").trim();
|
|
21
|
+
return { id: p.id, content, ms: Math.round(performance.now() - t0), error: content ? undefined : "empty completion" };
|
|
22
|
+
}
|
|
23
|
+
catch (e) {
|
|
24
|
+
return { id: p.id, content: "", ms: Math.round(performance.now() - t0), error: e.name || "error" };
|
|
25
|
+
}
|
|
26
|
+
finally {
|
|
27
|
+
clearTimeout(timer);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** Fan a turn out to every proposer in PARALLEL. Never throws or rejects — always resolves with one
|
|
31
|
+
* draft per proposer (empty content + `error` set on failure/timeout), so the caller decides how
|
|
32
|
+
* many survivors are enough (Session.sendMoa: >=1 aggregates, 0 falls back to aurora-1m). */
|
|
33
|
+
export function fanOutProposers(proposers, messages) {
|
|
34
|
+
return Promise.all(proposers.map((p) => callProposer(p, messages)));
|
|
35
|
+
}
|
|
36
|
+
/** Label + join the surviving (non-empty) drafts as "Candidate A: ..." (MOA-DESIGN.md), for the
|
|
37
|
+
* aggregator's input. Pure + testable without a network call. */
|
|
38
|
+
export function labelDrafts(drafts) {
|
|
39
|
+
return drafts
|
|
40
|
+
.filter((d) => d.content)
|
|
41
|
+
.map((d, i) => `Candidate ${String.fromCharCode(65 + i)} (${d.id}):\n${d.content}`)
|
|
42
|
+
.join("\n\n");
|
|
43
|
+
}
|
|
44
|
+
export const DEFAULT_AGGREGATOR_PROMPT = "You are given candidate answers from several models. Synthesize the single best, correct, complete answer. Do not mention the candidates.";
|
package/dist/remote/host.js
CHANGED
|
@@ -76,22 +76,43 @@ export class RemoteHost {
|
|
|
76
76
|
case "attach": // a follower joined — send a full snapshot BEFORE any further delta (§8)
|
|
77
77
|
this.sendSnapshot();
|
|
78
78
|
break;
|
|
79
|
+
// Drive frames (follower -> host actions). Defense-in-depth: the relay is SUPPOSED to only
|
|
80
|
+
// ever forward a frame that belongs to this connection's session, but a relay bug or a
|
|
81
|
+
// compromised relay could still hand us a stray/spoofed frame for a different session — so
|
|
82
|
+
// never act on one until it's checked against our own sessionId (+ ownerSub, if the frame
|
|
83
|
+
// carries one). isOwnFrame() also refuses everything before "welcome" has set sessionId.
|
|
79
84
|
case "prompt":
|
|
80
|
-
if (typeof f.payload?.text === "string")
|
|
85
|
+
if (this.isOwnFrame(f) && typeof f.payload?.text === "string")
|
|
81
86
|
this.cb.onPrompt(f.payload.text);
|
|
82
87
|
break;
|
|
83
88
|
case "approval_response":
|
|
84
|
-
if (f.payload?.id)
|
|
89
|
+
if (this.isOwnFrame(f) && f.payload?.id)
|
|
85
90
|
this.cb.onApprovalResponse(String(f.payload.id), !!f.payload.approve);
|
|
86
91
|
break;
|
|
92
|
+
case "ask_user_response":
|
|
93
|
+
if (this.isOwnFrame(f) && f.payload?.id)
|
|
94
|
+
this.cb.onAskUserResponse(String(f.payload.id), String(f.payload?.answer ?? ""));
|
|
95
|
+
break;
|
|
87
96
|
case "interrupt":
|
|
88
|
-
this.
|
|
97
|
+
if (this.isOwnFrame(f))
|
|
98
|
+
this.cb.onInterrupt();
|
|
89
99
|
break;
|
|
90
100
|
case "error":
|
|
91
101
|
this.cb.onState?.("error", f.payload?.message ?? f.payload?.code);
|
|
92
102
|
break;
|
|
93
103
|
}
|
|
94
104
|
}
|
|
105
|
+
/** True iff a drive frame's sessionId matches ours (and its ownerSub too, when the frame carries
|
|
106
|
+
* one — the relay doesn't always stamp it, so its absence is not itself a rejection). Before
|
|
107
|
+
* "welcome" there's no sessionId to compare against yet, so nothing drive-worthy is trusted. */
|
|
108
|
+
isOwnFrame(f) {
|
|
109
|
+
if (!this.sessionId || f.sessionId !== this.sessionId)
|
|
110
|
+
return false;
|
|
111
|
+
const claimedOwner = f.payload?.ownerSub;
|
|
112
|
+
if (this.ownerSub && claimedOwner !== undefined && claimedOwner !== this.ownerSub)
|
|
113
|
+
return false;
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
95
116
|
send(type, sessionId, payload, seq = null) {
|
|
96
117
|
if (!this.ws || this.ws.readyState !== 1)
|
|
97
118
|
return;
|
|
@@ -169,4 +190,9 @@ export class RemoteHost {
|
|
|
169
190
|
setActivity(state, label) { this.activity = state; this.state("activity", { state, ...(label ? { label } : {}) }); }
|
|
170
191
|
setStatus(ctxPct, route) { this.ctxPct = ctxPct; this.route = route; this.state("status", { ctxPct, route }); }
|
|
171
192
|
approvalRequest(id, tool, args) { this.state("approval_request", { id, tool, args }); }
|
|
193
|
+
/** Mirrors an ask_user clarification to followers — a DISTINCT frame type from approval_request
|
|
194
|
+
* (not folded into it), matching the web/mobile follower's contract. A local answer and a
|
|
195
|
+
* follower's ask_user_response race first-wins in the host (settleQuestion in cli.tsx); local
|
|
196
|
+
* ask_user keeps working unchanged when no remote-control session is active. */
|
|
197
|
+
askUser(id, question, options) { this.state("ask_user", { id, question, options }); }
|
|
172
198
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export const DEFAULT_MODEL_ID = "aurora-1m";
|
|
2
|
+
export const BUILTIN_MODELS = [
|
|
3
|
+
{ id: "aurora-1m", label: "Aurora 1M", kind: "single", desc: "1,048,576-token context (:8097)", endpoint: "http://127.0.0.1:8097/v1", model: "aurora-code-1", ctx: 1048576 },
|
|
4
|
+
{ id: "aurora-128k", label: "Aurora 128K", kind: "single", desc: "128K context, lighter RAM (:8096)", endpoint: "http://127.0.0.1:8096/v1", model: "aurora-code-1", ctx: 131072 },
|
|
5
|
+
{ id: "moa", label: "MOA (Mixture of Agents)", kind: "orchestrated", desc: "fan out to proposers, synthesize with an aggregator" },
|
|
6
|
+
];
|
|
7
|
+
/** The runtime registry: the built-ins, with any settings.models entries merged in (overriding a
|
|
8
|
+
* built-in by id, or adding a new one) — same shape either way, so /model doesn't care which. */
|
|
9
|
+
export function modelRegistry(overrides) {
|
|
10
|
+
if (!overrides?.length)
|
|
11
|
+
return BUILTIN_MODELS;
|
|
12
|
+
const byId = new Map(BUILTIN_MODELS.map((m) => [m.id, m]));
|
|
13
|
+
for (const m of overrides)
|
|
14
|
+
byId.set(m.id, { ...byId.get(m.id), ...m });
|
|
15
|
+
return [...byId.values()];
|
|
16
|
+
}
|
|
17
|
+
export function findModel(registry, id) {
|
|
18
|
+
return registry.find((m) => m.id === id);
|
|
19
|
+
}
|
|
20
|
+
/** Pure selection reducer for /model — no I/O (no settings read/write, no router mutation), so it's
|
|
21
|
+
* directly testable. The moa-needs-config check lives in Session.setModel (it needs settings.moa,
|
|
22
|
+
* which this module intentionally doesn't import). */
|
|
23
|
+
export function selectModel(registry, id) {
|
|
24
|
+
const profile = findModel(registry, id);
|
|
25
|
+
if (!profile)
|
|
26
|
+
return { error: `unknown model "${id}" — choices: ${registry.map((m) => m.id).join(", ")}` };
|
|
27
|
+
if (profile.kind === "single" && !profile.endpoint)
|
|
28
|
+
return { error: `model "${id}" has no endpoint configured` };
|
|
29
|
+
return { profile };
|
|
30
|
+
}
|
|
31
|
+
/** Strip a trailing /v1 so a ModelProfile/MoaAggregator endpoint can feed the AuroraRouter, whose
|
|
32
|
+
* base is bare (engine/aurora.ts's chat() appends /v1/chat/completions itself). */
|
|
33
|
+
export function endpointBase(endpoint) {
|
|
34
|
+
return endpoint.replace(/\/v1\/?$/, "");
|
|
35
|
+
}
|
package/dist/session.js
CHANGED
|
@@ -6,7 +6,9 @@ import { Conversation } from "./engine/messages.js";
|
|
|
6
6
|
import { chat, health } from "./engine/aurora.js";
|
|
7
7
|
import { summaryPrompt, compact } from "./engine/compaction.js";
|
|
8
8
|
import { engineRouter } from "./engine/router-adapter.js";
|
|
9
|
+
import { fanOutProposers, labelDrafts, DEFAULT_AGGREGATOR_PROMPT } from "./engine/moa.js";
|
|
9
10
|
import { AuroraRouter } from "./router/router.js";
|
|
11
|
+
import { modelRegistry, findModel, selectModel, endpointBase, DEFAULT_MODEL_ID } from "./router/models.js";
|
|
10
12
|
import { Executor } from "./tools/executor.js";
|
|
11
13
|
import { toSchemas, registry } from "./tools/registry.js";
|
|
12
14
|
import { MemoryStore } from "./memory/index.js";
|
|
@@ -74,8 +76,11 @@ function makeAskTool(handler) {
|
|
|
74
76
|
const SUMMARY_MAX_TOKENS = 1200; // room for Aurora's reasoning before the summary content lands
|
|
75
77
|
export class Session {
|
|
76
78
|
convo = new Conversation();
|
|
77
|
-
inner;
|
|
78
|
-
router;
|
|
79
|
+
inner; // was readonly — /model rebuilds it for a "single" profile switch
|
|
80
|
+
router; // rebuilt alongside inner (setModel)
|
|
81
|
+
registry; // /model's choices — built-ins + any settings.models
|
|
82
|
+
moaConfig;
|
|
83
|
+
modelId = DEFAULT_MODEL_ID; // active /model selection
|
|
79
84
|
executor;
|
|
80
85
|
localSchemas;
|
|
81
86
|
hub;
|
|
@@ -115,6 +120,14 @@ export class Session {
|
|
|
115
120
|
this.localSchemas = toSchemas(reg);
|
|
116
121
|
this.inner = cfg.router ?? new AuroraRouter();
|
|
117
122
|
this.router = engineRouter(this.inner);
|
|
123
|
+
this.registry = modelRegistry(cfg.models);
|
|
124
|
+
this.moaConfig = cfg.moa;
|
|
125
|
+
// Apply the persisted /model choice, unless a router was explicitly injected (tests / bg agents
|
|
126
|
+
// pinned to a fixed endpoint) — an injected router owns routing, /model doesn't override it.
|
|
127
|
+
if (!cfg.router && cfg.activeModel && cfg.activeModel !== DEFAULT_MODEL_ID) {
|
|
128
|
+
if (!this.setModel(cfg.activeModel).ok)
|
|
129
|
+
this.modelId = DEFAULT_MODEL_ID; // unavailable at startup → quiet fallback
|
|
130
|
+
}
|
|
118
131
|
this.systemPrompt = cfg.systemPrompt;
|
|
119
132
|
this.maxTokens = cfg.maxTokens ?? 2048;
|
|
120
133
|
this.temperature = cfg.temperature ?? 0.7;
|
|
@@ -237,10 +250,38 @@ export class Session {
|
|
|
237
250
|
turnCount() {
|
|
238
251
|
return this.convo.all.filter((m) => m.role === "user").length;
|
|
239
252
|
}
|
|
240
|
-
/** Currently-selected endpoint name (for /model). */
|
|
253
|
+
/** Currently-selected endpoint name (for /route, and a single-profile /model turn's status). */
|
|
241
254
|
currentRoute() {
|
|
242
255
|
return this.inner.currentName();
|
|
243
256
|
}
|
|
257
|
+
/** All model profiles the owner can pick between (/model) — built-ins plus any settings.models
|
|
258
|
+
* overrides passed in at construction. */
|
|
259
|
+
modelRegistry() {
|
|
260
|
+
return this.registry;
|
|
261
|
+
}
|
|
262
|
+
/** The active /model selection (id), for the status line + persistence. */
|
|
263
|
+
currentModel() {
|
|
264
|
+
return this.modelId;
|
|
265
|
+
}
|
|
266
|
+
/** Switch the active model (/model). A "single" profile rebuilds the router to point at that
|
|
267
|
+
* endpoint — no server is started/stopped, this only changes which endpoint THIS session talks
|
|
268
|
+
* to. "moa" has no endpoint of its own; send() special-cases it (sendMoa) instead. Returns an
|
|
269
|
+
* error instead of throwing, so the shell can show it inline: an unknown id, or "moa" selected
|
|
270
|
+
* with no settings.moa configured. */
|
|
271
|
+
setModel(id) {
|
|
272
|
+
const { profile, error } = selectModel(this.registry, id);
|
|
273
|
+
if (error || !profile)
|
|
274
|
+
return { ok: false, error };
|
|
275
|
+
if (profile.kind === "orchestrated" && !this.moaConfig?.proposers?.length) {
|
|
276
|
+
return { ok: false, error: `MOA needs a "moa" block (proposers + aggregator) in settings.json — see MOA-DESIGN.md` };
|
|
277
|
+
}
|
|
278
|
+
if (profile.kind === "single" && profile.endpoint) {
|
|
279
|
+
this.inner = new AuroraRouter([{ name: profile.id, base: endpointBase(profile.endpoint), model: profile.model ?? profile.id, ctxLimit: profile.ctx ?? this.inner.ctxLimit() }]);
|
|
280
|
+
this.router = engineRouter(this.inner);
|
|
281
|
+
}
|
|
282
|
+
this.modelId = profile.id;
|
|
283
|
+
return { ok: true };
|
|
284
|
+
}
|
|
244
285
|
/** The full conversation, for persistence (auto-save / --resume). */
|
|
245
286
|
snapshot() {
|
|
246
287
|
return this.convo.all.map((m) => ({ ...m }));
|
|
@@ -316,22 +357,65 @@ export class Session {
|
|
|
316
357
|
return this.memory.recallText(query, limit);
|
|
317
358
|
}
|
|
318
359
|
/** Run one user turn to completion, streaming via handlers. Resolves with the settled outcome;
|
|
319
|
-
* an interrupt resolves (interrupted:true), it does not throw — only a real transport error does.
|
|
360
|
+
* an interrupt resolves (interrupted:true), it does not throw — only a real transport error does.
|
|
361
|
+
* Dispatches to sendMoa when the active /model is "moa"; otherwise runs the normal single-model
|
|
362
|
+
* turn against whatever setModel last pointed the router at. */
|
|
320
363
|
async send(text, h = {}) {
|
|
321
364
|
if (this.ctrl)
|
|
322
365
|
throw new Error("Session.send called while a turn is in flight — serialize turns (the shell queues input)");
|
|
323
366
|
await this.maybeRecall(text); // fold past-session memory into the system prompt on the first turn
|
|
324
|
-
this.executor.resetTurn(); // clear the host executor's per-turn loop guard before this turn
|
|
325
367
|
this.inner.resetTurn(); // re-evaluate routing from the smallest endpoint + clear last turn's unhealthy set
|
|
368
|
+
const active = findModel(this.registry, this.modelId);
|
|
369
|
+
if (active?.kind === "orchestrated")
|
|
370
|
+
return this.sendMoa(text, h, active);
|
|
371
|
+
return this.execute(text, h, this.router, this.sysWithThink());
|
|
372
|
+
}
|
|
373
|
+
/** MOA turn (MOA-DESIGN.md): fan out to settings.moa's proposers in parallel, then run the
|
|
374
|
+
* aggregator through the SAME runTurn loop as a normal turn (execute) — pointed at the
|
|
375
|
+
* aggregator's endpoint, with the labelled drafts + aggregator_prompt folded into the system
|
|
376
|
+
* prompt. That reuse is what makes tool-calling, streaming, self-heal and telemetry "just work"
|
|
377
|
+
* for the aggregator without a second implementation. Zero survivors falls back to aurora-1m for
|
|
378
|
+
* this (and, until /model moa again, every subsequent) turn — a clear note prefixes the reply. */
|
|
379
|
+
async sendMoa(text, h, active) {
|
|
380
|
+
const moa = this.moaConfig; // setModel refuses to select "moa" without this
|
|
381
|
+
const history = [...this.convo.all, { role: "user", content: text }];
|
|
382
|
+
const drafts = await fanOutProposers(moa.proposers, history);
|
|
383
|
+
const survivors = drafts.filter((d) => d.content);
|
|
384
|
+
this.telemetry.record({
|
|
385
|
+
type: "moa",
|
|
386
|
+
proposers: moa.proposers.map((p) => p.id),
|
|
387
|
+
survived: survivors.map((d) => d.id),
|
|
388
|
+
latenciesMs: Object.fromEntries(drafts.map((d) => [d.id, d.ms])),
|
|
389
|
+
});
|
|
390
|
+
if (!survivors.length) {
|
|
391
|
+
h.onRoute?.(active.id, this.ctxPct());
|
|
392
|
+
this.modelId = DEFAULT_MODEL_ID; // fall back for this and future turns until /model moa retries
|
|
393
|
+
const note = "MOA: every proposer failed or timed out — falling back to aurora-1m for this reply.\n\n";
|
|
394
|
+
h.onDelta?.(note);
|
|
395
|
+
const res = await this.execute(text, h, this.router, this.sysWithThink());
|
|
396
|
+
return { ...res, content: note + res.content };
|
|
397
|
+
}
|
|
398
|
+
const aggRouter = engineRouter(new AuroraRouter([
|
|
399
|
+
{ name: moa.aggregator.id, base: endpointBase(moa.aggregator.endpoint), model: moa.aggregator.model, ctxLimit: this.inner.ctxLimit() },
|
|
400
|
+
]));
|
|
401
|
+
const aggSys = `${this.sysWithThink() ?? ""}\n\n## MOA aggregation\n${moa.aggregator_prompt ?? DEFAULT_AGGREGATOR_PROMPT}\n\n${labelDrafts(drafts)}`;
|
|
402
|
+
return this.execute(text, h, aggRouter, aggSys, moa.aggregator.id);
|
|
403
|
+
}
|
|
404
|
+
/** Shared turn execution: runs the tool-calling loop (runTurn) against the given router + system
|
|
405
|
+
* prompt, streaming via handlers, and records telemetry. Used by both a normal single-model turn
|
|
406
|
+
* (send) and a MOA aggregator turn (sendMoa) — the only difference between them is which router
|
|
407
|
+
* and system prompt they pass in. */
|
|
408
|
+
async execute(text, h, router, sys, routeLabel) {
|
|
409
|
+
this.executor.resetTurn(); // clear the host executor's per-turn loop guard before this turn
|
|
326
410
|
const controller = new AbortController();
|
|
327
411
|
this.ctrl = controller;
|
|
328
412
|
const _t0 = performance.now();
|
|
329
413
|
try {
|
|
330
414
|
const res = await runTurn(text, this.convo, {
|
|
331
|
-
router
|
|
415
|
+
router,
|
|
332
416
|
tools: this.tools,
|
|
333
417
|
toolSchemas: this.allSchemas(),
|
|
334
|
-
systemPrompt:
|
|
418
|
+
systemPrompt: sys,
|
|
335
419
|
summarize: this.summarize,
|
|
336
420
|
maxTokens: this.maxTokens,
|
|
337
421
|
temperature: this.temperature,
|
|
@@ -339,7 +423,7 @@ export class Session {
|
|
|
339
423
|
signal: controller.signal,
|
|
340
424
|
onDelta: h.onDelta,
|
|
341
425
|
onReasoning: h.onReasoning,
|
|
342
|
-
onRoute: (ep) => h.onRoute?.(ep.label ?? "aurora", this.ctxPct()),
|
|
426
|
+
onRoute: (ep) => h.onRoute?.(routeLabel ?? ep.label ?? "aurora", this.ctxPct()),
|
|
343
427
|
onToolStart: h.onToolStart,
|
|
344
428
|
onToolBatch: h.onToolBatch,
|
|
345
429
|
onAutoContinue: h.onAutoContinue,
|
package/dist/tools/chauffeur.js
CHANGED
|
@@ -16,6 +16,12 @@ export const CHAUFFEUR_READ_TOOLS = [
|
|
|
16
16
|
// Session lifecycle (control, non-mutating → unprompted). Chauffeur is session-based: without these the
|
|
17
17
|
// model can't recover from a "session has ended" error and every stateful read fails in a loop.
|
|
18
18
|
"start_session", "get_session", "list_sessions",
|
|
19
|
+
// Agent-cursor overlay (control, non-mutating → unprompted). Lets the owner SEE the agent's mouse move
|
|
20
|
+
// on screen instead of driving blind; toggling/theming/reading the overlay changes nothing it acts on.
|
|
21
|
+
"set_agent_cursor_enabled", "set_agent_cursor_theme", "get_agent_cursor_state",
|
|
22
|
+
// Bounded post-condition check (read-only verification, not an input event) — lets the model confirm an
|
|
23
|
+
// action landed instead of guessing from the next screenshot.
|
|
24
|
+
"verify_state",
|
|
19
25
|
];
|
|
20
26
|
export const CHAUFFEUR_ACTION_TOOLS = [
|
|
21
27
|
"launch_app", "bring_to_front", // window/app management
|
package/dist/tools/registry.js
CHANGED
|
@@ -14,35 +14,41 @@ import { ensureSearxng, noteSearxngUsed } from "./searxng.js";
|
|
|
14
14
|
function str(v, fallback = "") {
|
|
15
15
|
return v === undefined || v === null ? fallback : String(v);
|
|
16
16
|
}
|
|
17
|
+
// One persistent shell per Operator process (frontier-grade: cwd/env/venv persist across calls,
|
|
18
|
+
// like a real terminal — so the model sources a venv or `cd`s ONCE, not on every call). Lazily
|
|
19
|
+
// created; survives for the process lifetime.
|
|
20
|
+
let _shellSession = null;
|
|
21
|
+
async function getShellSession() {
|
|
22
|
+
if (!_shellSession) {
|
|
23
|
+
const { ShellSession } = await import("./shell-session.js");
|
|
24
|
+
_shellSession = new ShellSession();
|
|
25
|
+
}
|
|
26
|
+
return _shellSession;
|
|
27
|
+
}
|
|
17
28
|
async function shellExec(args) {
|
|
18
29
|
const command = str(args.command);
|
|
19
30
|
if (!command)
|
|
20
31
|
return "error: no command given";
|
|
21
|
-
const cwd = args.cwd ? expandPath(str(args.cwd)) : undefined;
|
|
22
32
|
const timeout = Number(args.timeout_ms ?? 120_000);
|
|
23
|
-
|
|
24
|
-
//
|
|
25
|
-
|
|
26
|
-
const {
|
|
27
|
-
const fmt = (o, err) => (o + (err ? `\n[stderr]\n${err}` : "")).trim();
|
|
33
|
+
// A `cwd` arg is scoped to this one call (subshell) so it doesn't silently move the persistent
|
|
34
|
+
// session's directory; an explicit `cd` INSIDE the command persists, exactly like a terminal.
|
|
35
|
+
const cwd = args.cwd ? expandPath(str(args.cwd)) : undefined;
|
|
36
|
+
const toRun = cwd ? `( cd ${JSON.stringify(cwd)} && { ${command}; } )` : command;
|
|
28
37
|
try {
|
|
29
|
-
const
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
// on no-match, `| head` can SIGPIPE a producer, `test`/`diff` signal via exit code. So NEVER discard
|
|
35
|
-
// real output — surface it. Only when there's genuinely nothing do we report the exit tersely.
|
|
36
|
-
const out = fmt(String(e.stdout ?? ""), String(e.stderr ?? ""));
|
|
37
|
-
if (e.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") {
|
|
38
|
-
return (out ? out + "\n" : "") + `[output exceeded ${Math.round(MAXBUF / 1e6)}MB and was truncated — narrow it: add a path, pipe to \`head\`, or use \`grep -l\`/\`grep -c\`]`;
|
|
39
|
-
}
|
|
40
|
-
if (e.killed || /ETIMEDOUT|timed out/i.test(String(e.message ?? ""))) {
|
|
41
|
-
return (out ? out + "\n" : "") + `[timed out after ${timeout}ms — narrow the command or pass a larger timeout_ms]`;
|
|
38
|
+
const sess = await getShellSession();
|
|
39
|
+
const r = await sess.run(toRun, timeout);
|
|
40
|
+
let out = r.output || "";
|
|
41
|
+
if (r.timedOut) {
|
|
42
|
+
return (out ? out + "\n" : "") + `[timed out after ${timeout}ms — the shell was reset (cwd/env cleared); narrow the command or pass a larger timeout_ms]`;
|
|
42
43
|
}
|
|
44
|
+
if (r.truncated)
|
|
45
|
+
out += `\n[output truncated at 8MB — narrow it: add a path, pipe to \`head\`, or use \`grep -l\`/\`grep -c\`]`;
|
|
43
46
|
if (out)
|
|
44
|
-
return out; //
|
|
45
|
-
return `(no output; exit ${
|
|
47
|
+
return out; // real output — including non-zero exits (grep no-match, diff, test)
|
|
48
|
+
return r.exitCode === 0 ? "(no output)" : `(no output; exit ${r.exitCode ?? "?"})`;
|
|
49
|
+
}
|
|
50
|
+
catch (e) {
|
|
51
|
+
return `error running command: ${String(e?.message ?? e)}`;
|
|
46
52
|
}
|
|
47
53
|
}
|
|
48
54
|
// Un-ranged reads default to a bounded window (like the host Read tool) instead of dumping an entire
|
|
@@ -490,8 +496,25 @@ async function taskUpdate(args) {
|
|
|
490
496
|
}
|
|
491
497
|
const TOOLS = [
|
|
492
498
|
{
|
|
499
|
+
name: "bash", safe: false,
|
|
500
|
+
description: "Run a bash command in a PERSISTENT shell session — a real terminal that stays open across " +
|
|
501
|
+
"calls. State PERSISTS: a `cd`, an exported variable, an activated venv, or a defined function " +
|
|
502
|
+
"in one call is still in effect on the next. So set things up ONCE and reuse them — do NOT " +
|
|
503
|
+
"re-run `source .../activate && ...` or re-`cd` on every call; activate/enter once, then just " +
|
|
504
|
+
"run the command. stdout and stderr come back merged (like a terminal) with the exit code. " +
|
|
505
|
+
"Optional `cwd` runs that one command in a subshell without moving the session. For a " +
|
|
506
|
+
"long-running server/build/watcher use shell_background instead so this shell isn't blocked.",
|
|
507
|
+
parameters: { type: "object", properties: {
|
|
508
|
+
command: { type: "string", description: "the bash command to run in the persistent shell" },
|
|
509
|
+
cwd: { type: "string", description: "optional: run this one command from here (scoped; does not move the session)" },
|
|
510
|
+
timeout_ms: { type: "number", description: "optional per-command timeout (default 120000); on timeout the shell is reset" },
|
|
511
|
+
}, required: ["command"] },
|
|
512
|
+
run: shellExec,
|
|
513
|
+
},
|
|
514
|
+
{
|
|
515
|
+
// Back-compat alias: older prompts/skills call `shell_exec`. Same persistent-session engine as `bash`.
|
|
493
516
|
name: "shell_exec", safe: false,
|
|
494
|
-
description: "
|
|
517
|
+
description: "Alias of `bash` — runs a command in the same persistent shell session (state persists across calls).",
|
|
495
518
|
parameters: { type: "object", properties: {
|
|
496
519
|
command: { type: "string" }, cwd: { type: "string" }, timeout_ms: { type: "number" },
|
|
497
520
|
}, required: ["command"] },
|
package/dist/tools/sandbox.js
CHANGED
|
@@ -204,3 +204,14 @@ export async function wrapShell(command) {
|
|
|
204
204
|
}
|
|
205
205
|
return { file: "/bin/bash", args: ["-c", command] };
|
|
206
206
|
}
|
|
207
|
+
/** Argv for a PERSISTENT interactive shell (reads commands on stdin) under the same OS sandbox
|
|
208
|
+
* as wrapShell. Used by ShellSession so cwd/env persist across bash tool calls like a real
|
|
209
|
+
* terminal. `-i` is deliberately omitted: an interactive shell would emit prompts/job-control
|
|
210
|
+
* noise; the session drives framing itself with a sentinel. */
|
|
211
|
+
export async function wrapInteractiveShell() {
|
|
212
|
+
const mode = sandboxMode();
|
|
213
|
+
if (mode !== "off" && (await hasSandboxExec())) {
|
|
214
|
+
return { file: "/usr/bin/sandbox-exec", args: ["-p", seatbeltProfile(mode), "/bin/bash", "-s"] };
|
|
215
|
+
}
|
|
216
|
+
return { file: "/bin/bash", args: ["-s"] };
|
|
217
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
// Persistent interactive shell — the difference between a clumsy one-shot exec and a frontier
|
|
2
|
+
// bash tool. A single bash process is kept alive per Operator session, so `cd`, exported env
|
|
3
|
+
// vars, activated venvs and shell functions PERSIST across bash tool calls exactly like a real
|
|
4
|
+
// terminal. This is why the model no longer needs to re-run `source .../activate && ...` on
|
|
5
|
+
// every call: it sources once and the state sticks.
|
|
6
|
+
//
|
|
7
|
+
// Framing: each command is written to the shell's stdin followed by a sentinel that prints a
|
|
8
|
+
// unique nonce and `$?`. We read stdout+stderr (merged, like a terminal) until the sentinel
|
|
9
|
+
// line appears; everything before it is the command's output, and the nonce line carries the
|
|
10
|
+
// exit code. On a per-command timeout we kill and transparently respawn the shell (cwd/env are
|
|
11
|
+
// lost only in that exceptional case), so a runaway command can never wedge the session.
|
|
12
|
+
//
|
|
13
|
+
// node-only; imported lazily from the tool layer so the neutral (mobile) bundle never pulls it.
|
|
14
|
+
import { wrapInteractiveShell } from "./sandbox.js";
|
|
15
|
+
const SENTINEL = "__KODE_SH_DONE__";
|
|
16
|
+
const OUTPUT_CAP = 8 * 1024 * 1024; // 8MB per command; beyond this we truncate and say so
|
|
17
|
+
export class ShellSession {
|
|
18
|
+
proc = null;
|
|
19
|
+
buf = "";
|
|
20
|
+
cwd;
|
|
21
|
+
starting = null;
|
|
22
|
+
constructor(cwd) {
|
|
23
|
+
this.cwd = cwd;
|
|
24
|
+
}
|
|
25
|
+
async ensure() {
|
|
26
|
+
if (this.proc && this.proc.exitCode === null && !this.proc.killed)
|
|
27
|
+
return;
|
|
28
|
+
if (this.starting)
|
|
29
|
+
return this.starting;
|
|
30
|
+
this.starting = (async () => {
|
|
31
|
+
const { spawn } = await import("node:child_process");
|
|
32
|
+
const { file, args } = await wrapInteractiveShell();
|
|
33
|
+
const p = spawn(file, args, {
|
|
34
|
+
cwd: this.cwd,
|
|
35
|
+
env: { ...process.env, PS1: "", PROMPT_COMMAND: "", TERM: "dumb" },
|
|
36
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
37
|
+
});
|
|
38
|
+
p.stdout.setEncoding("utf8");
|
|
39
|
+
p.stderr.setEncoding("utf8");
|
|
40
|
+
const onData = (d) => { this.buf += d; };
|
|
41
|
+
p.stdout.on("data", onData);
|
|
42
|
+
p.stderr.on("data", onData); // merge stderr into the same stream, like a real terminal
|
|
43
|
+
p.on("exit", () => { this.proc = null; });
|
|
44
|
+
p.on("error", () => { this.proc = null; });
|
|
45
|
+
this.proc = p;
|
|
46
|
+
// Don't let the long-lived shell (or its pipes) keep the process alive at exit — a tool's
|
|
47
|
+
// background shell must never block Operator (or a test runner) from exiting cleanly.
|
|
48
|
+
// Streams over pipes are Sockets (which have unref) but TS types them as Readable/Writable
|
|
49
|
+
// (no unref); cast. p.unref() on the ChildProcess is the load-bearing one.
|
|
50
|
+
try {
|
|
51
|
+
p.unref();
|
|
52
|
+
p.stdout?.unref?.();
|
|
53
|
+
p.stderr?.unref?.();
|
|
54
|
+
p.stdin?.unref?.();
|
|
55
|
+
}
|
|
56
|
+
catch { /* */ }
|
|
57
|
+
// Quiet the shell and disable history expansion so commands frame cleanly.
|
|
58
|
+
p.stdin.write("export PS1='' PROMPT_COMMAND=''; set +o history 2>/dev/null; true\n");
|
|
59
|
+
await new Promise((r) => setTimeout(r, 30));
|
|
60
|
+
this.buf = "";
|
|
61
|
+
})();
|
|
62
|
+
try {
|
|
63
|
+
await this.starting;
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
this.starting = null;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** Run one command in the persistent shell and return its merged output + exit code. */
|
|
70
|
+
async run(command, timeoutMs = 120_000) {
|
|
71
|
+
await this.ensure();
|
|
72
|
+
const p = this.proc;
|
|
73
|
+
if (!p)
|
|
74
|
+
return { output: "error: shell failed to start", exitCode: null, timedOut: false, truncated: false };
|
|
75
|
+
const nonce = Math.random().toString(36).slice(2, 10);
|
|
76
|
+
const marker = `${SENTINEL}${nonce}`;
|
|
77
|
+
// A trailing newline before the command guards against a previous no-newline write; the
|
|
78
|
+
// sentinel prints on its own line regardless of whether `command` ended in a newline.
|
|
79
|
+
this.buf = "";
|
|
80
|
+
p.stdin.write(`${command}\nprintf '\\n%s:%s\\n' '${marker}' "$?"\n`);
|
|
81
|
+
const re = new RegExp(`\\n?${marker}:(-?\\d+)\\r?\\n`);
|
|
82
|
+
const deadline = Date.now() + Math.max(1000, timeoutMs);
|
|
83
|
+
while (true) {
|
|
84
|
+
const m = this.buf.match(re);
|
|
85
|
+
if (m) {
|
|
86
|
+
let output = this.buf.slice(0, m.index).replace(/\r/g, "");
|
|
87
|
+
let truncated = false;
|
|
88
|
+
if (output.length > OUTPUT_CAP) {
|
|
89
|
+
output = output.slice(0, OUTPUT_CAP);
|
|
90
|
+
truncated = true;
|
|
91
|
+
}
|
|
92
|
+
this.buf = "";
|
|
93
|
+
return { output: output.replace(/\n+$/, ""), exitCode: Number(m[1]), timedOut: false, truncated };
|
|
94
|
+
}
|
|
95
|
+
if (Date.now() > deadline) {
|
|
96
|
+
// Non-interactive bash won't job-control a SIGINT to the foreground child, so the only
|
|
97
|
+
// reliable stop is to kill the shell and respawn on the next call. cwd/env reset only here.
|
|
98
|
+
const partial = this.buf.replace(/\r/g, "").slice(0, OUTPUT_CAP);
|
|
99
|
+
try {
|
|
100
|
+
p.kill("SIGKILL");
|
|
101
|
+
}
|
|
102
|
+
catch { /* */ }
|
|
103
|
+
this.proc = null;
|
|
104
|
+
this.buf = "";
|
|
105
|
+
return { output: partial.replace(/\n+$/, ""), exitCode: null, timedOut: true, truncated: false };
|
|
106
|
+
}
|
|
107
|
+
await new Promise((r) => setTimeout(r, 15));
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
dispose() {
|
|
111
|
+
try {
|
|
112
|
+
this.proc?.kill("SIGKILL");
|
|
113
|
+
}
|
|
114
|
+
catch { /* */ }
|
|
115
|
+
this.proc = null;
|
|
116
|
+
this.buf = "";
|
|
117
|
+
}
|
|
118
|
+
}
|
package/dist/ui/App.js
CHANGED
|
@@ -10,10 +10,10 @@ import { BgPanel } from "./BgPanel.js";
|
|
|
10
10
|
import { ApprovalPrompt } from "./ApprovalPrompt.js";
|
|
11
11
|
import { QuestionPrompt } from "./QuestionPrompt.js";
|
|
12
12
|
export function App(props) {
|
|
13
|
-
const { messages, live = null, status, thinkingVerb, verbs, stepLabel, route, ctxPct, version, build, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, onSubmit, onQueue, onInterrupt, approval = null, onApprovalDecide, question = null } = props;
|
|
13
|
+
const { messages, live = null, status, thinkingVerb, verbs, stepLabel, route, ctxPct, version, build, metrics, sessionTokens, authUser, tier, planMode, thinkMode, bgAgents, onSubmit, onQueue, onInterrupt, approval = null, onApprovalDecide, question = null, modelPicker = null } = props;
|
|
14
14
|
const thinking = status === "thinking" || status === "streaming";
|
|
15
15
|
const showSpinner = status === "recovering" || status === "executing" || thinking;
|
|
16
16
|
return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Transcript, { entries: messages, live: live }), showSpinner && (_jsx(Box, { marginTop: 1, marginBottom: 1, children: status === "recovering" ? _jsx(RecoverSpinner, { active: true, label: stepLabel })
|
|
17
17
|
: status === "executing" ? _jsx(StepSpinner, { active: true, label: stepLabel })
|
|
18
|
-
: _jsx(ThinkingSpinner, { active: true, verb: thinkingVerb, verbs: verbs, metrics: metrics }) })), _jsx(BgPanel, { agents: bgAgents }), _jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(QuestionPrompt, { pending: question }), _jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, disabled: status !== "idle", suspended: !!approval || !!question }), _jsx(InputRule, {})] }));
|
|
18
|
+
: _jsx(ThinkingSpinner, { active: true, verb: thinkingVerb, verbs: verbs, metrics: metrics }) })), _jsx(BgPanel, { agents: bgAgents }), _jsx(ApprovalPrompt, { approval: approval, onDecide: onApprovalDecide ?? (() => { }) }), _jsx(QuestionPrompt, { pending: question }), _jsx(QuestionPrompt, { pending: modelPicker }), _jsx(StatusRule, { route: route, ctxPct: ctxPct, version: version, build: build, user: authUser, tier: tier, planMode: planMode, thinkMode: thinkMode, sessionTokens: sessionTokens }), _jsx(Composer, { onSubmit: onSubmit, onQueue: onQueue, onInterrupt: onInterrupt, disabled: status !== "idle", suspended: !!approval || !!question || !!modelPicker }), _jsx(InputRule, {})] }));
|
|
19
19
|
}
|
|
@@ -28,7 +28,7 @@ export function questionKey(st, input, key, options) {
|
|
|
28
28
|
return {};
|
|
29
29
|
}
|
|
30
30
|
if (key.ctrl && input.toLowerCase() === "c")
|
|
31
|
-
return { resolve:
|
|
31
|
+
return { resolve: DISCUSS }; // bail = discuss, NEVER a silently-picked real answer
|
|
32
32
|
const chatIndex = options.length + 1;
|
|
33
33
|
const n = Number(input);
|
|
34
34
|
if (Number.isInteger(n) && n >= 1 && n <= options.length)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@0perator/operator",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.49",
|
|
4
4
|
"description": "Operator (KODE) — TypeScript + Ink terminal coding agent. Full-frame render, single-engine core shared across CLI/web/mobile; runs against a local Aurora model.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|