@0perator/operator 0.1.285 → 0.1.321
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 +24 -2
- package/dist/acp/agent.js +2 -1
- package/dist/acp/config-options.js +3 -1
- package/dist/acp/tool-map.js +2 -1
- package/dist/auth/commands.js +69 -13
- package/dist/autonomy/agent-cli.js +308 -0
- package/dist/autonomy/cloud-agent.js +439 -0
- package/dist/autonomy/cron-lifecycle.js +78 -0
- package/dist/autonomy/cron-lock.js +121 -0
- package/dist/autonomy/cron.js +217 -44
- package/dist/autonomy/delegate.js +34 -5
- package/dist/autonomy/incidents.js +135 -0
- package/dist/autonomy/index.js +22 -0
- package/dist/autonomy/profile.js +1 -1
- package/dist/autonomy/session-factory.js +25 -16
- package/dist/background/index.js +40 -0
- package/dist/browser/cdp.js +1 -1
- package/dist/bus/inbox.js +20 -0
- package/dist/classifier/config.js +47 -0
- package/dist/classifier/modes.js +41 -0
- package/dist/classifier/types.js +1 -0
- package/dist/cli.js +645 -93
- package/dist/config/features.js +69 -0
- package/dist/config/persona.js +143 -107
- package/dist/config/scaffold.js +15 -0
- package/dist/config/settings.js +107 -12
- package/dist/consolidation/sleep.js +73 -11
- package/dist/engine/agent.js +279 -20
- package/dist/engine/anthropic-chat.js +343 -0
- package/dist/engine/aurora.js +109 -16
- package/dist/engine/batch-scheduler.js +41 -9
- package/dist/engine/classifier.js +85 -0
- package/dist/engine/compaction.js +25 -6
- package/dist/engine/fast-start.js +25 -0
- package/dist/engine/loop-guard.js +448 -0
- package/dist/engine/net-error.js +24 -0
- package/dist/engine/repetition-guard.js +180 -0
- package/dist/engine/router-adapter.js +1 -0
- package/dist/engine/selfheal.js +8 -0
- package/dist/engine/toolcalls.js +51 -1
- package/dist/engine/verify-gate.js +2 -0
- package/dist/flywheel/processor.js +78 -31
- package/dist/flywheel/srft.js +13 -0
- package/dist/hooks/index.js +196 -0
- package/dist/idle/activity.js +20 -0
- package/dist/idle/index.js +5 -0
- package/dist/idle/monitor.js +71 -0
- package/dist/idle/policy.js +66 -0
- package/dist/idle/proc.js +22 -0
- package/dist/idle/reaper.js +69 -0
- package/dist/idle/session-record.js +59 -0
- package/dist/index.js +1 -1
- package/dist/mcp/config.js +93 -15
- package/dist/mcp/index.js +9 -2
- package/dist/memory/index.js +0 -0
- package/dist/memory/providers.js +210 -0
- package/dist/memory/session-catalog.js +422 -0
- package/dist/memory/session-providers.js +121 -0
- package/dist/memory/session-sources.js +335 -0
- package/dist/memory/skylark.js +131 -0
- package/dist/models/bench.js +103 -0
- package/dist/models/registry.js +144 -0
- package/dist/models/switch.js +69 -0
- package/dist/observability/blackbox.js +37 -0
- package/dist/permissions/index.js +22 -7
- package/dist/permissions/policy.js +31 -6
- package/dist/permissions/tier.js +1 -1
- package/dist/remote/host.js +20 -2
- package/dist/remote/safe-commands.js +38 -0
- package/dist/router/discovery.js +127 -0
- package/dist/router/models.js +107 -16
- package/dist/router/portal.js +100 -0
- package/dist/router/router.js +1 -1
- package/dist/services/preflight.js +108 -8
- package/dist/services/store-sync.js +111 -0
- package/dist/session-teardown.js +10 -1
- package/dist/session.js +338 -46
- package/dist/skills/catalogue.js +1 -1
- package/dist/tools/chauffeur-native.js +155 -0
- package/dist/tools/chauffeur.js +26 -3
- package/dist/tools/download.js +229 -0
- package/dist/tools/executor.js +19 -9
- package/dist/tools/find-files.js +483 -0
- package/dist/tools/git-pr.js +94 -0
- package/dist/tools/incident-tools.js +82 -0
- package/dist/tools/memory.js +12 -2
- package/dist/tools/monitoring-tools.js +312 -0
- package/dist/tools/paths.js +154 -0
- package/dist/tools/registry.js +582 -95
- package/dist/tools/semantic-compress.js +124 -0
- package/dist/tools/shell-context.js +1 -0
- package/dist/tools/shell-jobs.js +163 -0
- package/dist/tools/shell-session.js +174 -6
- package/dist/tools/tool-output-spill.js +1 -1
- package/dist/tools/wave-tools.js +609 -0
- package/dist/tools/wave2-tools.js +411 -0
- package/dist/ui/App.js +15 -4
- package/dist/ui/BgPanel.js +30 -6
- package/dist/ui/Composer.js +15 -2
- package/dist/ui/QuestionPrompt.js +32 -12
- package/dist/ui/SessionPicker.js +86 -0
- package/dist/ui/StatusRule.js +5 -5
- package/dist/ui/ToolStep.js +17 -1
- package/dist/ui/Transcript.js +17 -1
- package/dist/ui/index.js +1 -1
- package/dist/ui/liveTools.js +21 -3
- package/dist/ui/slashCommands.js +2 -0
- package/dist/util/mentions.js +1 -1
- package/dist/util/screenshots.js +74 -8
- package/dist/util/slash.js +2 -2
- package/dist/vault/store.js +1 -1
- package/mcp/README.md +88 -0
- package/mcp/ocr-macos.swift +45 -0
- package/mcp/powertools-media.mjs +464 -0
- package/mcp/powertools-toolbox.mjs +1114 -0
- package/mcp/powertools.md +210 -0
- package/mcp/powertools.mjs +861 -0
- package/package.json +9 -2
package/dist/cli.js
CHANGED
|
@@ -10,17 +10,19 @@ import { App } from "./ui/index.js";
|
|
|
10
10
|
import { mastheadLines } from "./ui/Masthead.js";
|
|
11
11
|
import { shouldPromptPlanExit, resolvePlanExit, PLAN_EXIT_OPTIONS } from "./ui/planExit.js";
|
|
12
12
|
import { RemoteHost } from "./remote/host.js";
|
|
13
|
+
import { REMOTE_SAFE_COMMANDS, REMOTE_SAFE_COMMAND_NAMES } from "./remote/safe-commands.js";
|
|
13
14
|
import { newCode, pairURL } from "./remote/pairing.js";
|
|
14
15
|
import { qrToTerminal } from "./ui/qr.js";
|
|
15
|
-
import { pollBus, pollSent, selfAgent } from "./bus/inbox.js";
|
|
16
|
+
import { pollBus, pollSent, selfAgent, buildMentorWake, selectReadyWakes } from "./bus/inbox.js";
|
|
16
17
|
import { isErrorResult, resultPreview } from "./ui/format.js";
|
|
17
18
|
import { seedLiveTools, settleLiveTool } from "./ui/liveTools.js";
|
|
18
19
|
import { Session } from "./session.js";
|
|
20
|
+
import { buildMemory } from "./memory/providers.js";
|
|
19
21
|
import { cacheBustNotice } from "./engine/aurora.js";
|
|
20
22
|
import { seedCalibration } from "./engine/calibration-seed.js";
|
|
21
23
|
import { AuroraRouter } from "./router/router.js";
|
|
22
24
|
import { BackgroundAgents } from "./background/index.js";
|
|
23
|
-
import { loadSettings, saveSettings, compactionThreshold, compactionCeilingTokens, rcAutostart, applySeat, setActiveSeat } from "./config/settings.js";
|
|
25
|
+
import { loadSettings, saveSettings, compactionThreshold, compactionCeilingTokens, rcAutostart, applySeat, setActiveSeat, buildEndpointChain } from "./config/settings.js";
|
|
24
26
|
import { resolveSeat } from "./auth/identity.js";
|
|
25
27
|
import { PermissionPolicy } from "./permissions/index.js";
|
|
26
28
|
import { caps } from "./ui/capabilities.js";
|
|
@@ -28,21 +30,32 @@ import { composeSystemPrompt, appendMemory } from "./config/persona.js";
|
|
|
28
30
|
import { applyToolsBinPath, operatorPath } from "./config/home.js";
|
|
29
31
|
import { ensureOperatorHome } from "./config/scaffold.js";
|
|
30
32
|
import { listLocalSkills } from "./config/skills-index.js";
|
|
31
|
-
import { modelCtxFor,
|
|
32
|
-
import {
|
|
33
|
+
import { modelCtxFor, leanHarnessFor, selectModel, modelRegistry, DEFAULT_MODEL_ID } from "./router/models.js";
|
|
34
|
+
import { fetchPortalModels, markPickerOptions, offlineNote, portalIdFor } from "./router/portal.js";
|
|
35
|
+
import { describeTurnError } from "./engine/net-error.js";
|
|
36
|
+
import { hasByoToken } from "./auth/byo.js";
|
|
37
|
+
import { getDiscoveredModels } from "./router/discovery.js";
|
|
38
|
+
import { disposeShellSession, getAgentTasks, registry } from "./tools/registry.js";
|
|
39
|
+
import { drainJobNotices, getJobNoticeMode, listShellJobs, onJobEvent, parseJobsArgs, pendingJobNotices, renderJobsList, runningJobCount, setJobNoticeMode, stopShellJob } from "./tools/shell-jobs.js";
|
|
40
|
+
import { lastActiveAt as idleLastActiveAt, resolveIdlePolicy, startIdleMonitor, touchWork } from "./idle/index.js";
|
|
33
41
|
import { disposeBrowserNow } from "./browser/session.js";
|
|
34
42
|
import { EventSink, defaultEventsFile } from "./telemetry/events.js";
|
|
35
43
|
import { SessionTracker } from "./telemetry/lifecycle.js";
|
|
36
44
|
import { centralRecording, defaultIngest, setCentralEnabled } from "./telemetry/ingest.js";
|
|
37
45
|
import { Teardown } from "./util/teardown.js";
|
|
38
46
|
import { installProcessTeardown } from "./session-teardown.js";
|
|
47
|
+
import { createStoreClient, resolveStoreKey } from "./services/store-sync.js";
|
|
39
48
|
import { reapStaleChildren } from "./util/owned-children.js";
|
|
40
|
-
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
49
|
+
import { readFileSync, writeFileSync, mkdirSync, readdirSync, statSync, existsSync } from "node:fs";
|
|
41
50
|
import { expandFileMentions } from "./util/mentions.js";
|
|
42
51
|
import { snapshotEphemeralImages } from "./util/screenshots.js";
|
|
52
|
+
import { isFeatureEnabled } from "./config/features.js";
|
|
53
|
+
import { classifyActVsAsk, actAskGateDirective } from "./engine/classifier.js";
|
|
43
54
|
import { throttle } from "./util/throttle.js";
|
|
44
55
|
import { isSlashCommand } from "./util/slash.js";
|
|
45
56
|
import * as compose from "./compose/client.js";
|
|
57
|
+
import { catalogEntry, continuationContext, folderExists, indexCatalog, searchCatalog, sessionSearchConfig } from "./memory/session-catalog.js";
|
|
58
|
+
import { titleFrom } from "./memory/session-sources.js";
|
|
46
59
|
import { execFile } from "node:child_process";
|
|
47
60
|
import { join, dirname } from "node:path";
|
|
48
61
|
import { homedir, hostname } from "node:os";
|
|
@@ -59,6 +72,27 @@ const VERSION = (() => {
|
|
|
59
72
|
return "0.0.0";
|
|
60
73
|
}
|
|
61
74
|
})();
|
|
75
|
+
// Masthead context badge — the served window of the ACTIVE model, truthfully (1,000,000 → "1M", 131072 →
|
|
76
|
+
// "128K"). Pure (no I/O), so the --help fast path below stays instant; the boot masthead passes the live
|
|
77
|
+
// value. Replaces a long-hardcoded "300K" that drifted the moment the model/window changed.
|
|
78
|
+
function ctxBadge(n) {
|
|
79
|
+
if (!(n > 0))
|
|
80
|
+
return "";
|
|
81
|
+
if (n >= 1_000_000)
|
|
82
|
+
return Number.isInteger(n / 1_000_000) ? `${n / 1_000_000}M` : `${(n / 1_000_000).toFixed(1)}M`;
|
|
83
|
+
return n >= 1024 ? `${Math.round(n / 1024)}K` : String(n);
|
|
84
|
+
}
|
|
85
|
+
// The model the session will actually start on — NOT the raw persisted id. Mirrors Session's startup
|
|
86
|
+
// resolution (session.ts: setModel(cfg.activeModel) else DEFAULT_MODEL_ID) so the boot masthead badges the
|
|
87
|
+
// window of the model that answers, not a persisted id that the owner-only gate / missing-endpoint check
|
|
88
|
+
// drops back to operator-1m. Pure (selectModel is a pure reducer, no health I/O), so the fast paths stay instant.
|
|
89
|
+
function startupModelId(s, actor) {
|
|
90
|
+
const id = s.activeModel;
|
|
91
|
+
if (!id || id === DEFAULT_MODEL_ID)
|
|
92
|
+
return DEFAULT_MODEL_ID;
|
|
93
|
+
const isOwner = (actor.tier ?? "admin") === "admin";
|
|
94
|
+
return selectModel(modelRegistry(s.models), id, hasByoToken, isOwner).profile ? id : DEFAULT_MODEL_ID;
|
|
95
|
+
}
|
|
62
96
|
// Fast paths that must NOT mount Ink/React (so `operator --version` works with no TTY and returns instantly)
|
|
63
97
|
// — and must not do ANY identity I/O either. They used to sit BELOW the boot credential load, so even
|
|
64
98
|
// `--version` paid a keychain child-process spawn on the critical path: with a hung `security` helper the
|
|
@@ -69,7 +103,7 @@ if (process.argv.includes("--version") || process.argv.includes("-V")) {
|
|
|
69
103
|
process.exit(0);
|
|
70
104
|
}
|
|
71
105
|
if (process.argv.includes("--help")) {
|
|
72
|
-
process.stdout.write(mastheadLines(`
|
|
106
|
+
process.stdout.write(mastheadLines(`v${VERSION}`).join("\n") +
|
|
73
107
|
"\n\nUsage:\n operator start the interactive session\n operator --resume resume the last session in this directory\n operator --update update to the latest build (git fast-forward)\n operator --fullscreen fullscreen layout: composer pinned to the bottom (or settings.ui.fullscreen)\n operator auth sign in / manage your AXE account\n operator run <task> run one task headless\n operator --version print the version\n");
|
|
74
108
|
process.exit(0);
|
|
75
109
|
}
|
|
@@ -103,14 +137,15 @@ if (settings.search?.autopilotUrl)
|
|
|
103
137
|
process.env.KODE_AUTOPILOT_URL = settings.search.autopilotUrl;
|
|
104
138
|
if (settings.selfImprove?.flywheel === false)
|
|
105
139
|
process.env.KODE_SELFIMPROVE = "0"; // opt out of turn-capture
|
|
106
|
-
if (settings.selfImprove?.memory)
|
|
107
|
-
process.env.KODE_SELFIMPROVE_MEMORY = "
|
|
140
|
+
if (settings.selfImprove?.memory === false)
|
|
141
|
+
process.env.KODE_SELFIMPROVE_MEMORY = "0"; // opt out of the closed loop (a stuck session leaves a durable lesson in .operator/memories.md) — ON by default
|
|
108
142
|
if (settings.verifyGate?.enabled === false)
|
|
109
143
|
process.env.KODE_VERIFY_GATE = "0"; // opt out of verify-before-done
|
|
110
144
|
if (settings.verifyGate?.maxNudges != null)
|
|
111
145
|
process.env.KODE_VERIFY_GATE_MAX = String(settings.verifyGate.maxNudges);
|
|
112
146
|
if (settings.background?.maxConcurrent != null)
|
|
113
147
|
process.env.KODE_BG_MAX = String(settings.background.maxConcurrent); // cap concurrent bg sub-agents
|
|
148
|
+
setJobNoticeMode(settings.background?.jobNotices ?? "wake"); // what a finished background shell job does: wake / queue / off
|
|
114
149
|
if (settings.background?.worktree === false)
|
|
115
150
|
process.env.KODE_BG_WORKTREE = "0"; // opt out of bg-agent git-worktree isolation
|
|
116
151
|
// Inline (native scrollback + the masthead boot) is the DEFAULT. Fullscreen (alt-screen; composer pinned
|
|
@@ -163,6 +198,13 @@ if (SEAT.dropToken) {
|
|
|
163
198
|
const { setOperatorToken } = await import("./engine/aurora.js");
|
|
164
199
|
setOperatorToken(undefined);
|
|
165
200
|
}
|
|
201
|
+
// Fleet model discovery (router/discovery.ts): auto-catalog each LIVE fleet node by what it advertises
|
|
202
|
+
// (/props + /v1/models) so a server dropped onto the fleet appears in /model — named + truthfully sized
|
|
203
|
+
// from the server, no code change. Merged UNDER settings.models so a hand override by id always wins.
|
|
204
|
+
// Fail-safe + bounded: a node that doesn't answer in 1.5s is simply absent (startup never blocks on a
|
|
205
|
+
// slow/down box). Skipped for auth/version/help so signed-out commands stay instant.
|
|
206
|
+
const DISCOVERED_MODELS = SKIP_SEAT ? [] : await getDiscoveredModels(settings.fleet?.auroraNodes ?? [], { timeoutMs: 1500 });
|
|
207
|
+
const MERGED_MODELS = [...DISCOVERED_MODELS, ...(settings.models ?? [])];
|
|
166
208
|
// Computer control (opt-in, macOS embodiment). When enabled: register the control tools into the shared
|
|
167
209
|
// registry and compute permission rules. The FOREGROUND forces each computer_* tool to "ask" so every
|
|
168
210
|
// action prompts the owner via the approve() bridge in <Root>; BACKGROUND sub-agents get them DENIED —
|
|
@@ -240,6 +282,57 @@ try {
|
|
|
240
282
|
mkdirSync(dirname(process.env.KODE_HANDOFF_FILE), { recursive: true });
|
|
241
283
|
}
|
|
242
284
|
catch { /* best-effort; the tools guard too */ }
|
|
285
|
+
// Session search keeps EVERY session (memory/session-catalog.ts): the resume file above is overwritten by the
|
|
286
|
+
// next session in this folder, so each session is also archived as its own file under sessions/archive/ with
|
|
287
|
+
// its folder, title and model. A resumed session adopts its archive, so continuing it never duplicates it.
|
|
288
|
+
const ARCHIVE_DIR = join(SESSION_DIR, "archive");
|
|
289
|
+
const freshArchive = () => ({
|
|
290
|
+
file: join(ARCHIVE_DIR, `${WORKSPACE_HASH}-${new Date().toISOString().replace(/[-:]/g, "").slice(0, 15)}-${randomUUID().slice(0, 8)}.json`),
|
|
291
|
+
cwd: process.cwd(),
|
|
292
|
+
startedAt: Date.now(),
|
|
293
|
+
});
|
|
294
|
+
const sessionArchive = freshArchive();
|
|
295
|
+
// A conversation that replaces the one on screen (/new, a legacy resume, continuing another agent's session)
|
|
296
|
+
// archives to a new file, so it never overwrites the session it replaced.
|
|
297
|
+
function newArchive() { Object.assign(sessionArchive, freshArchive()); }
|
|
298
|
+
function archiveSession(messages, model) {
|
|
299
|
+
const first = messages.find((m) => m.role === "user" && m.content.trim());
|
|
300
|
+
if (!first)
|
|
301
|
+
return; // nothing said yet — not a session worth keeping
|
|
302
|
+
const doc = {
|
|
303
|
+
version: 1, id: sessionArchive.file.slice(ARCHIVE_DIR.length + 1, -".json".length), cwd: sessionArchive.cwd,
|
|
304
|
+
title: titleFrom(first.content), model, startedAt: sessionArchive.startedAt, updatedAt: Date.now(), messages,
|
|
305
|
+
};
|
|
306
|
+
try {
|
|
307
|
+
mkdirSync(ARCHIVE_DIR, { recursive: true, mode: 0o700 });
|
|
308
|
+
writeFileSync(sessionArchive.file, JSON.stringify(doc), { mode: 0o600 });
|
|
309
|
+
}
|
|
310
|
+
catch { /* best-effort, like the resume file */ }
|
|
311
|
+
}
|
|
312
|
+
function adoptArchive(file) {
|
|
313
|
+
try {
|
|
314
|
+
const doc = JSON.parse(readFileSync(file, "utf8"));
|
|
315
|
+
Object.assign(sessionArchive, { file, cwd: doc.cwd ?? sessionArchive.cwd, startedAt: doc.startedAt ?? sessionArchive.startedAt });
|
|
316
|
+
}
|
|
317
|
+
catch { /* unreadable — keep archiving to this session's own file */ }
|
|
318
|
+
}
|
|
319
|
+
// The newest archive written from this folder (what `--resume` just reloaded), if any.
|
|
320
|
+
function latestArchiveHere() {
|
|
321
|
+
try {
|
|
322
|
+
const mine = readdirSync(ARCHIVE_DIR).filter((n) => n.startsWith(WORKSPACE_HASH + "-") && n.endsWith(".json")).map((n) => join(ARCHIVE_DIR, n));
|
|
323
|
+
return mine.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)[0] ?? null;
|
|
324
|
+
}
|
|
325
|
+
catch {
|
|
326
|
+
return null;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
// Saved messages → transcript rows (the user/assistant turns a resume shows).
|
|
330
|
+
function transcriptEntries(saved) {
|
|
331
|
+
return saved
|
|
332
|
+
.filter((m) => (m.role === "user" || m.role === "assistant") && m.content.trim())
|
|
333
|
+
.map((m) => ({ kind: "message", message: { id: nextId(), role: m.role, content: m.content } }));
|
|
334
|
+
}
|
|
335
|
+
const compactCount = (n) => (n >= 1000 ? `${(n / 1000).toFixed(n >= 10_000 ? 0 : 1)}K` : String(n));
|
|
243
336
|
const EVENT_ACTOR = { tier: settings.permissions.tier ?? "admin", surface: process.argv[2] === "acp" ? "acp" : "cli", sub: settings.seat?.sub };
|
|
244
337
|
const eventSink = new EventSink();
|
|
245
338
|
// Startup audit — only for a seat that is audited at all (a narrowed tier / audit / gated mode); the inert owner
|
|
@@ -266,12 +359,28 @@ const tracker = new SessionTracker(eventSink, SESSION_ID, EVENT_ACTOR, VERSION,
|
|
|
266
359
|
// at rest, SIGINT/SIGHUP/SIGTERM and a plain process exit all call into it (wired below, before render), so it runs exactly once.
|
|
267
360
|
// It stops SESSION-owned things only — never the launchd-owned Aurora/autopilot (preflight only ever brings those UP).
|
|
268
361
|
const teardown = new Teardown();
|
|
362
|
+
const storeClient = settings.store?.endpoint
|
|
363
|
+
? createStoreClient((process.env.KODE_STORE_URL || settings.store.endpoint).replace(/\/+$/, ""), resolveStoreKey(settings.store))
|
|
364
|
+
: undefined;
|
|
269
365
|
installProcessTeardown(teardown, {
|
|
270
|
-
recordEnd: (r) => tracker.end(r === "quit" ? "ok" : r),
|
|
366
|
+
recordEnd: (r) => tracker.end(r === "quit" || r === "idle" ? "ok" : r),
|
|
271
367
|
flushTelemetry: () => defaultIngest().shutdown(2000),
|
|
272
368
|
flushTelemetrySync: () => defaultIngest().persistSync(),
|
|
273
369
|
disposeShells: disposeShellSession,
|
|
274
370
|
disposeBrowser: disposeBrowserNow,
|
|
371
|
+
storeClient,
|
|
372
|
+
buildArchive: () => {
|
|
373
|
+
try {
|
|
374
|
+
const raw = readFileSync(sessionArchive.file, "utf8");
|
|
375
|
+
const doc = JSON.parse(raw);
|
|
376
|
+
if (!doc.messages?.length)
|
|
377
|
+
return null;
|
|
378
|
+
return doc;
|
|
379
|
+
}
|
|
380
|
+
catch {
|
|
381
|
+
return null;
|
|
382
|
+
}
|
|
383
|
+
},
|
|
275
384
|
});
|
|
276
385
|
// Children a previous Operator left behind (it crashed, or was killed -9; detached shells/jobs and Chrome outlive their parent).
|
|
277
386
|
let REAPED = { owners: 0, killed: [], skipped: 0 };
|
|
@@ -279,14 +388,11 @@ let REAPED = { owners: 0, killed: [], skipped: 0 };
|
|
|
279
388
|
// and `operator+` serve the same single tier (the air/1m/saddle roster collapsed once Aurora ran true
|
|
280
389
|
// 1,048,576-token context at full speed). No size-based routing decision remains.
|
|
281
390
|
function buildRouter() {
|
|
282
|
-
|
|
283
|
-
//
|
|
284
|
-
//
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
if (fo)
|
|
288
|
-
eps.push({ name: "failover", base: fo.base, model: fo.model, ctxLimit: fo.ctxWindow });
|
|
289
|
-
return new AuroraRouter(eps);
|
|
391
|
+
// Primary first; the fleet nodes + optional failover + cloud tier are reached only via the router's
|
|
392
|
+
// health-gated recover() when the current endpoint errors/degrades (routeBySize always picks the primary
|
|
393
|
+
// at index 0 since 1M fits every prompt). buildEndpointChain is the single source of truth shared with the
|
|
394
|
+
// headless session factory, so interactive + autonomy paths route around a wedged box identically.
|
|
395
|
+
return new AuroraRouter(buildEndpointChain(settings));
|
|
290
396
|
}
|
|
291
397
|
// One-line status for a sub-agent — shared by /bg (human) and the agent_status tool (model), so both
|
|
292
398
|
// surfaces agree on what "status" means instead of drifting into two formats.
|
|
@@ -314,6 +420,48 @@ function formatAgentDetail(a) {
|
|
|
314
420
|
parts.push("— errored");
|
|
315
421
|
return parts.join(" ");
|
|
316
422
|
}
|
|
423
|
+
// Full per-agent view for /agents <id> — everything the one-liner can't fit (task, model/lane, verify
|
|
424
|
+
// outcome, live tool steps, mission line) plus the msg/stop controls for a still-running child.
|
|
425
|
+
function formatAgentDeepView(a) {
|
|
426
|
+
const ds = DISPLAY_STATUS[a.status] ?? a.status;
|
|
427
|
+
const lines = [];
|
|
428
|
+
lines.push(`── ${a.id} [${ds}] ──`);
|
|
429
|
+
lines.push(` label: ${a.label}`);
|
|
430
|
+
if (a.task)
|
|
431
|
+
lines.push(` task: ${a.task.length > 120 ? a.task.slice(0, 119) + "…" : a.task}`);
|
|
432
|
+
if (a.model)
|
|
433
|
+
lines.push(` model: ${a.model}${a.lane ? ` · ${a.lane}` : ""}`);
|
|
434
|
+
lines.push(` round: ${a.round ?? 0}`);
|
|
435
|
+
const tokStr = a.tokens != null && a.tokens > 0 ? (a.tokens >= 1000 ? `${(a.tokens / 1000).toFixed(1)}k` : `${a.tokens}`) : "0";
|
|
436
|
+
lines.push(` tokens: ${tokStr}`);
|
|
437
|
+
const ms = a.status === "working" ? (a.startedAt != null ? Date.now() - a.startedAt : undefined) : a.durationMs;
|
|
438
|
+
if (ms != null)
|
|
439
|
+
lines.push(` elapsed: ${(ms / 1000).toFixed(1)}s`);
|
|
440
|
+
if (a.verified != null)
|
|
441
|
+
lines.push(` verified: ${a.verified ? "✓ yes" : `✗ no${a.verifyDetail ? " — " + a.verifyDetail : ""}`}`);
|
|
442
|
+
if (a.malformed)
|
|
443
|
+
lines.push(` malformed: ⚠ final_answer schema failure`);
|
|
444
|
+
if (a.progress)
|
|
445
|
+
lines.push(` mission: ${a.progress.slice(0, 100)}`);
|
|
446
|
+
if (a.steps && a.steps.length) {
|
|
447
|
+
lines.push(` tools:`);
|
|
448
|
+
for (const s of a.steps) {
|
|
449
|
+
lines.push(` ${s.running ? "▸" : "·"} ${s.name}${s.arg ? ` ${s.arg}` : ""}${s.running ? " …" : ""}`);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
if (a.lastOutput)
|
|
453
|
+
lines.push(` output: ${a.lastOutput.slice(0, 100)}`);
|
|
454
|
+
if (a.thought)
|
|
455
|
+
lines.push(` thinking: ${a.thought.slice(0, 100)}`);
|
|
456
|
+
if (a.status === "idle")
|
|
457
|
+
lines.push(`\n result posted to transcript — scroll up to see it`);
|
|
458
|
+
if (a.status === "working" || a.status === "queued") {
|
|
459
|
+
lines.push(`\n controls:`);
|
|
460
|
+
lines.push(` /agents ${a.id} msg <text> send a message to re-steer`);
|
|
461
|
+
lines.push(` /agents ${a.id} stop stop this agent`);
|
|
462
|
+
}
|
|
463
|
+
return lines.join("\n");
|
|
464
|
+
}
|
|
317
465
|
// The system prompt is assembled by config/persona.ts composeSystemPrompt — the SAME call the headless
|
|
318
466
|
// autonomy runners (autonomy/session-factory.ts) make — so the TUI and an unattended `operator run/loop`
|
|
319
467
|
// share one persona (Direct/unrestricted, media, verify-by-running) + project context + handoff.
|
|
@@ -324,7 +472,7 @@ const chauffeurReady = !!chauffeurServer || settings.mcp;
|
|
|
324
472
|
// for Aurora's 300K, it fills the window and the model recites it instead of answering. Below
|
|
325
473
|
// LEAN_HARNESS_CTX, drop the heavy memory/handoff, KEEPING the base persona (incl. the Direct/unrestricted
|
|
326
474
|
// section) so the model stays uncensored.
|
|
327
|
-
const LEAN_HARNESS =
|
|
475
|
+
const LEAN_HARNESS = leanHarnessFor(settings.activeModel, settings.models);
|
|
328
476
|
// TODO(R1b): built once at startup — a mid-session /model does not rebuild it (ctxTokens + lean follow the startup model).
|
|
329
477
|
const SYSTEM_PROMPT = composeSystemPrompt({ settings, cwd: process.cwd(), ctxTokens: modelCtxFor(settings.activeModel, settings.models), lean: LEAN_HARNESS, interactive: true, chauffeurReady });
|
|
330
478
|
const HELP = [
|
|
@@ -338,6 +486,7 @@ const HELP = [
|
|
|
338
486
|
" /stats session dashboard: turns · tools · tokens · throughput trend · context fill",
|
|
339
487
|
" /dashboard launch the live swarm console (watches every Operator session)",
|
|
340
488
|
" /artifacts browse + attach your Compose (compose.casa) artifacts: search · attach · copy url · delete",
|
|
489
|
+
" /sessions [query] search Operator's and other agents' sessions (providers in agents.md) and pick one up",
|
|
341
490
|
" /plan plan mode: read-only research + propose a plan (/plan again to execute)",
|
|
342
491
|
" /mode [plan|manual|auto] set operating mode (plan · manual · autonomous); also Shift+Tab to cycle",
|
|
343
492
|
" /think extended reasoning: Operator thinks before answering (/think again = off)",
|
|
@@ -345,9 +494,11 @@ const HELP = [
|
|
|
345
494
|
" /compact force-compact the conversation now",
|
|
346
495
|
" /remember <note> store a note to recall in future sessions",
|
|
347
496
|
" /memory [query] show remembered notes (all, or matching query)",
|
|
348
|
-
" /
|
|
497
|
+
" /allow <tool:args> auto-allow a tool+args glob pattern in gated mode (e.g. bash:npm test*)",
|
|
498
|
+
" /skill <name|off> activate a skill as a system-prompt directive (/skill off to deactivate)",
|
|
499
|
+
" /mcp [on|off] fleet MCP: status · on/off (saved) · /mcp reload (from disk) · /mcp add powertools <root>",
|
|
349
500
|
" /login · /logout · /whoami /login opens the browser to approve; or /login <email> for a 6-digit code (then /login <code>); /login <token>",
|
|
350
|
-
" /agents
|
|
501
|
+
" /agents [id] detailed sub-agent status, or /agents <id> for a deep view + controls (msg/stop)",
|
|
351
502
|
" /bg <task|stop id> spawn a background sub-agent, list, or stop one",
|
|
352
503
|
" /new start a fresh conversation",
|
|
353
504
|
" /clear clear the screen (keeps the conversation)",
|
|
@@ -356,37 +507,7 @@ const HELP = [
|
|
|
356
507
|
].join("\n");
|
|
357
508
|
// Slash commands a remote-control FOLLOWER is allowed to drive (RemoteHost `command` frame →
|
|
358
509
|
// SPEC/remote-session.md extension; see REMOTE_RICH_HEAD_AUDIT.md). This is BOTH the allowlist enforced
|
|
359
|
-
//
|
|
360
|
-
// one list, so a follower's command palette never offers something the host will actually refuse.
|
|
361
|
-
// Deliberately excludes: exit/quit (kills the host process), login/logout (mutates the owner's stored
|
|
362
|
-
// AXE credentials), and remotecontrol/remote (a follower must never be able to kick every other
|
|
363
|
-
// follower off the session it's attached to). Those four are the only slash commands that act OUTSIDE
|
|
364
|
-
// the tool/permission system (direct switch-case side effects, ungated whether local or remote) —
|
|
365
|
-
// everything below still runs with the same local privilege a `prompt` frame already has today.
|
|
366
|
-
const REMOTE_SAFE_COMMANDS = [
|
|
367
|
-
{ name: "help", description: "list available commands" },
|
|
368
|
-
{ name: "model", description: "pick a model: operator-1m · operator-128k · moa (mixture-of-agents)", args: "[id]" },
|
|
369
|
-
{ name: "route", description: "pin routing to an endpoint, or auto (by size)", args: "[endpoint|auto]" },
|
|
370
|
-
{ name: "endpoints", description: "show the Operator endpoint + live health" },
|
|
371
|
-
{ name: "services", description: "ensure/inspect the service lever (Operator+autopilot+searxng); stop searxng", args: "[stop]" },
|
|
372
|
-
{ name: "audit", description: "recent tool + control-plane events from the audit trail", args: "[n]" },
|
|
373
|
-
{ name: "dashboard", description: "launch the live swarm console" },
|
|
374
|
-
{ name: "plan", description: "toggle plan mode (read-only research + propose a plan)" },
|
|
375
|
-
{ name: "mode", description: "set operating mode: plan · manual · autonomous", args: "[plan|manual|auto]" },
|
|
376
|
-
{ name: "think", description: "toggle extended reasoning" },
|
|
377
|
-
{ name: "ultrathink", description: "toggle deep, exhaustive reasoning" },
|
|
378
|
-
{ name: "compact", description: "force-compact the conversation now" },
|
|
379
|
-
{ name: "remember", description: "store a note to recall in future sessions", args: "<note>" },
|
|
380
|
-
{ name: "memory", description: "show remembered notes", args: "[query]" },
|
|
381
|
-
{ name: "mcp", description: "fleet MCP tools: status · switch the layer on/off", args: "[on|off]" },
|
|
382
|
-
{ name: "whoami", description: "show signed-in identity" },
|
|
383
|
-
{ name: "agents", description: "detailed sub-agent status with metrics" },
|
|
384
|
-
{ name: "monitor", description: "toggle live event stream (tool decisions, turns, control)" },
|
|
385
|
-
{ name: "bg", description: "spawn a background sub-agent, list, or stop one", args: "<task|stop id>" },
|
|
386
|
-
{ name: "new", description: "start a fresh conversation" },
|
|
387
|
-
{ name: "clear", description: "clear the screen (keeps the conversation)" },
|
|
388
|
-
];
|
|
389
|
-
const REMOTE_SAFE_COMMAND_NAMES = new Set(REMOTE_SAFE_COMMANDS.map((c) => c.name));
|
|
510
|
+
// REMOTE_SAFE_COMMANDS / NAMES imported from ./remote/safe-commands.js (follower allowlist).
|
|
390
511
|
let ID = 0;
|
|
391
512
|
const nextId = () => `e${++ID}`;
|
|
392
513
|
// Time+token readout in the "(7m 8s · 22.6k tokens)" shape: minutes+seconds past a minute, k-abbreviated
|
|
@@ -401,6 +522,8 @@ function Root() {
|
|
|
401
522
|
const [entries, setEntries] = useState([]);
|
|
402
523
|
const [live, setLive] = useState(null);
|
|
403
524
|
const [status, setStatus] = useState("idle");
|
|
525
|
+
const [prefill, setPrefill] = useState(""); // "reading context N%" during a long prefill
|
|
526
|
+
const prefillRef = useRef("");
|
|
404
527
|
const [stepLabel, setStepLabel] = useState(""); // tool(s) currently executing, for the step animation
|
|
405
528
|
const [liveTools, setLiveTools] = useState([]); // one row per call in the CURRENT batch,
|
|
406
529
|
// live: seeded "running" by onToolStart, each flips to done/error independently as onToolResult fires
|
|
@@ -415,6 +538,7 @@ function Root() {
|
|
|
415
538
|
// status rule as tokens stream (each SSE delta ≈ 1 token). Zero extra renders: it rides the per-delta
|
|
416
539
|
// setLive re-render that already happens, so there's no performance cost and no animation timer.
|
|
417
540
|
const [bgAgents, setBgAgents] = useState([]);
|
|
541
|
+
const [shellJobs, setShellJobs] = useState([]); // background SHELL jobs (shN), shown beside the sub-agents but never mixed with their ids
|
|
418
542
|
const [tasks, setTasks] = useState([]); // session TODO list for the plan pane, refreshed after task_* tools
|
|
419
543
|
const [authUser, setAuthUser] = useState(""); // signed-in identity for the status rule
|
|
420
544
|
const [planMode, setPlanMode] = useState(false); // /plan: read-only research + propose, shown as a status badge
|
|
@@ -445,11 +569,11 @@ function Root() {
|
|
|
445
569
|
resolve(answer);
|
|
446
570
|
setQuestion((cur) => (cur && cur.id === id ? null : cur));
|
|
447
571
|
}, []);
|
|
448
|
-
const askUser = useCallback((q, options) => new Promise((resolve) => {
|
|
572
|
+
const askUser = useCallback((q, options, multiSelect) => new Promise((resolve) => {
|
|
449
573
|
const id = "q_" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
|
|
450
574
|
pendingQuestions.current.set(id, resolve);
|
|
451
|
-
setQuestion({ id, question: q, options, resolve: (a) => settleQuestion(id, a) });
|
|
452
|
-
remoteRef.current?.askUser(id, q, options); // mirror to followers (owner-scoped)
|
|
575
|
+
setQuestion({ id, question: q, options, resolve: (a) => settleQuestion(id, a), multiSelect });
|
|
576
|
+
remoteRef.current?.askUser(id, q, options); // mirror to followers (owner-scoped; follower prompt is single-select)
|
|
453
577
|
}), [settleQuestion]);
|
|
454
578
|
// /model picker: same QuestionPrompt UI pattern as ask_user, but purely local (never relayed) —
|
|
455
579
|
// it's a session setting, not something the model is asking.
|
|
@@ -460,6 +584,7 @@ function Root() {
|
|
|
460
584
|
const planProposedRef = useRef(false);
|
|
461
585
|
const [planExitPicker, setPlanExitPicker] = useState(null);
|
|
462
586
|
const [artifactsPicker, setArtifactsPicker] = useState(null);
|
|
587
|
+
const [sessionsPicker, setSessionsPicker] = useState(null);
|
|
463
588
|
const alwaysAllowRef = useRef(new Set());
|
|
464
589
|
// Remembers the email a `/login <email>` sent a 6-digit code to, so the follow-up `/login <code>`
|
|
465
590
|
// knows which address to verify against — the in-session twin of the shell's email-code login.
|
|
@@ -500,18 +625,23 @@ function Root() {
|
|
|
500
625
|
systemPrompt: SYSTEM_PROMPT,
|
|
501
626
|
thinkMode, // start in the SAME mode the badge shows (settings.ui.reasoning, default "think") — it was only ever the badge that defaulted on
|
|
502
627
|
router: buildRouter(),
|
|
628
|
+
memory: buildMemory(settings.memory), // provider composite when configured; bare store (byte-identical) otherwise
|
|
503
629
|
mcp: settings.mcp,
|
|
504
630
|
mcpHub: embodimentHub, // scoped chauffeur hub when embodiment is on (undefined otherwise → no change)
|
|
505
631
|
maxTokens: settings.maxTokens,
|
|
506
632
|
maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling (total tokens); undefined → no cap
|
|
633
|
+
loopGuard: settings.loopGuard, // tool-loop + repetition guard thresholds (interactive: notices only unless hardStop is set)
|
|
634
|
+
hooks: settings.hooks, // lifecycle hooks (settings.hooks); inert unless tool hooks are configured
|
|
507
635
|
maxRounds: settings.autonomy?.maxRounds, // soft per-turn round budget (default 200) — a real build isn't cut off at 10
|
|
508
636
|
sleepConsolidation: settings.autonomy?.sleepConsolidation, // idle "dreaming": consolidate transcript→memory + run the flywheel while the owner is away (0.1.177 — was never threaded through, so it never fired)
|
|
509
637
|
compactionThreshold: compactionThreshold(settings), // settings.compaction.threshold / KODE_COMPACTION_THRESHOLD; undefined → 0.85
|
|
510
638
|
compactionCeilingTokens: compactionCeilingTokens(settings, settings.endpoints.aurora.ctxWindow, "interactive"), // INTERACTIVE mode ⇒ the tight ceiling (~24k) so each owner-facing reply decodes fast; compaction.ceilingTokens/env override, then the RAM-aware clamp. Headless autonomy uses the separate high ceiling (session-factory.ts)
|
|
511
639
|
temperature: settings.temperature,
|
|
512
640
|
recall: settings.memory.recall,
|
|
513
|
-
models:
|
|
641
|
+
models: MERGED_MODELS, // discovered fleet nodes + settings.models overrides (built-ins in router/models.ts)
|
|
514
642
|
moa: settings.moa, // MOA proposers/aggregator config (MOA-DESIGN.md); absent = "/model moa" explains
|
|
643
|
+
fastStart: settings.fastStart, // fast-model-vs-real-turn race (feature: fastStart, default OFF)
|
|
644
|
+
features: settings.features, // feature flags — registers flag-gated tools (e.g. cloudAgents) only when on
|
|
515
645
|
activeModel: settings.activeModel, // persisted /model choice, applied at startup
|
|
516
646
|
permissions: fgPermissions, // owner's policy + computer tools forced to "ask" when enabled (else bypass)
|
|
517
647
|
approve: approveFn, // renders the in-TUI approval prompt for any "ask" decision
|
|
@@ -597,11 +727,12 @@ function Root() {
|
|
|
597
727
|
if (!bgRef.current) {
|
|
598
728
|
bgRef.current = new BackgroundAgents((cwd) => new Session({
|
|
599
729
|
systemPrompt: SYSTEM_PROMPT,
|
|
600
|
-
router: new AuroraRouter(
|
|
601
|
-
|
|
602
|
-
]),
|
|
730
|
+
router: new AuroraRouter(buildEndpointChain(settings)), // same multi-tier self-heal chain as the foreground
|
|
731
|
+
memory: buildMemory(settings.memory), // sub-agents share the same provider-layer memory surface
|
|
603
732
|
maxTokens: settings.maxTokens,
|
|
604
733
|
maxTurnTokens: settings.maxTurnTokens, // opt-in per-turn cost ceiling also bounds a sub-agent's spend
|
|
734
|
+
loopGuard: settings.loopGuard,
|
|
735
|
+
hooks: settings.hooks, // sub-agents are gated by the same hooks (e.g. git-safety)
|
|
605
736
|
maxRoundsHard: 50, // a focused delegated sub-agent that hits 50 rounds isn't converging — cap it well below the foreground's 200 so a review/fix agent can't run away to round 40+ burning the shared Aurora (seen live 09-26)
|
|
606
737
|
background: true, // endpoint gate: this is a sub-agent — its Aurora requests yield the shared single slot to the interactive main turn (fixes the sub-agent-contention crawl + "4 min for a prompt")
|
|
607
738
|
cwd, // isolation: a code-editing bg agent gets its own worktree dir here so it can't touch the foreground tree
|
|
@@ -639,8 +770,11 @@ function Root() {
|
|
|
639
770
|
// state mutation below also mirrors to it so attached followers see identical transcript/tool/activity.
|
|
640
771
|
const remoteRef = useRef(null);
|
|
641
772
|
const [rcConnected, setRcConnected] = useState(false); // remote-control live? drives the footer controller icon
|
|
773
|
+
const rcConnectedRef = useRef(false);
|
|
774
|
+
rcConnectedRef.current = rcConnected; // a follower attached = someone is watching: the idle monitor reads this
|
|
642
775
|
const [rcActive, setRcActive] = useState(false); // remote-control ENABLED/listening (host up) — distinct from rcConnected (a follower is attached); the footer shows OFF(gray) vs ON-waiting(amber) vs LIVE(green)
|
|
643
|
-
const setStat = (s) => { statusRef.current = s; setStatus(s); remoteRef.current?.setActivity(s);
|
|
776
|
+
const setStat = (s) => { statusRef.current = s; setStatus(s); remoteRef.current?.setActivity(s); if (s === "idle")
|
|
777
|
+
touchWork(); };
|
|
644
778
|
const push = (e) => setEntries((prev) => [...prev, e]);
|
|
645
779
|
const submitRef = useRef(() => { });
|
|
646
780
|
// AXE skills fetched/saved THIS session (name -> a best-effort description) — there's no persistent
|
|
@@ -688,11 +822,23 @@ function Root() {
|
|
|
688
822
|
let reports = [];
|
|
689
823
|
try {
|
|
690
824
|
const preflight = await import("./services/preflight.js");
|
|
825
|
+
const auroraCfg = { base: settings.endpoints.aurora.base, ...settings.services?.aurora };
|
|
691
826
|
reports = await preflight.ensureServices({
|
|
692
|
-
aurora:
|
|
827
|
+
aurora: auroraCfg,
|
|
693
828
|
autopilot: settings.services?.autopilot,
|
|
829
|
+
vision: settings.services?.vision,
|
|
694
830
|
onProgress: setBootDetail,
|
|
695
831
|
});
|
|
832
|
+
// ensureServices discovers the dynamic port from server.json and mutates auroraCfg.base —
|
|
833
|
+
// propagate it back so the router, warmup, and health checks use the live endpoint.
|
|
834
|
+
if (auroraCfg.base && auroraCfg.base !== settings.endpoints.aurora.base) {
|
|
835
|
+
settings.endpoints.aurora.base = auroraCfg.base;
|
|
836
|
+
}
|
|
837
|
+
// The supervisor publishes the gateway's api_key alongside its port (server.json) — carry it onto the
|
|
838
|
+
// endpoint config so the router authenticates to the loopback gateway (resolveEndpointApiKey → token).
|
|
839
|
+
const bootKey = auroraCfg.apiKey;
|
|
840
|
+
if (bootKey && !settings.endpoints.aurora.apiKey)
|
|
841
|
+
settings.endpoints.aurora.apiKey = bootKey;
|
|
696
842
|
// If the lever COLD-STARTED Aurora, prime it (fire-and-forget) so the first real turn doesn't
|
|
697
843
|
// eat the graph/Metal warmup. Skipped when Aurora was already up (state "up").
|
|
698
844
|
if (reports.find((r) => r.name === "aurora")?.state === "started") {
|
|
@@ -711,16 +857,33 @@ function Root() {
|
|
|
711
857
|
try {
|
|
712
858
|
const saved = JSON.parse(readFileSync(SESSION_FILE, "utf8"));
|
|
713
859
|
if (session.restore(saved)) {
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
860
|
+
setEntries(transcriptEntries(saved));
|
|
861
|
+
const archived = latestArchiveHere();
|
|
862
|
+
if (archived)
|
|
863
|
+
adoptArchive(archived);
|
|
718
864
|
setCtxPct(session.ctxPct());
|
|
719
865
|
push({ kind: "message", message: { id: nextId(), role: "system", content: `resumed ${session.turnCount()} prior turns` } });
|
|
720
866
|
}
|
|
721
867
|
}
|
|
722
868
|
catch { /* no saved session to resume */ }
|
|
723
869
|
}
|
|
870
|
+
// Session search: keep the catalog warm in the background (incremental — only changed files are read)
|
|
871
|
+
// and say once, the first time it is ready, how much it can search and how to turn it off.
|
|
872
|
+
void sessionSearchConfig().then(async (cfg) => {
|
|
873
|
+
if (!cfg.enabled)
|
|
874
|
+
return;
|
|
875
|
+
const marker = operatorPath("state", "session-search-ready");
|
|
876
|
+
const first = !existsSync(marker);
|
|
877
|
+
const r = await indexCatalog(cfg.providers);
|
|
878
|
+
if (!first)
|
|
879
|
+
return;
|
|
880
|
+
try {
|
|
881
|
+
writeFileSync(marker, new Date().toISOString() + "\n");
|
|
882
|
+
}
|
|
883
|
+
catch { /* shown again next launch — harmless */ }
|
|
884
|
+
push({ kind: "message", message: { id: nextId(), role: "system", content: `Session search is ready — ${r.sessions} sessions · ${compactCount(r.messages)} messages searchable (Operator's and other agents' sessions on this machine — providers are listed in agents.md in your Operator home; the index never leaves it). ` +
|
|
885
|
+
`/sessions to search them and pick one up — I can search them too. Turn it off with "sessionSearch": { "enabled": false } in settings.json.` } });
|
|
886
|
+
}).catch(() => { });
|
|
724
887
|
// Feed the service-lever outcome to the frozen event stream (dashboard service-health tiles).
|
|
725
888
|
if (emitTelemetry) {
|
|
726
889
|
for (const r of reports) {
|
|
@@ -769,9 +932,20 @@ function Root() {
|
|
|
769
932
|
catch { /* auth is optional — never block the REPL */ }
|
|
770
933
|
})();
|
|
771
934
|
}, []);
|
|
772
|
-
const sendTurn = useCallback(async (text) => {
|
|
773
|
-
|
|
774
|
-
|
|
935
|
+
const sendTurn = useCallback(async (text, opts) => {
|
|
936
|
+
// Finished background shell jobs are announced at the start of the next turn (capped notices, never the
|
|
937
|
+
// full output). A wake turn has no user text: the notices are the whole prompt.
|
|
938
|
+
const notices = drainJobNotices();
|
|
939
|
+
if (notices) {
|
|
940
|
+
const heads = notices.split("\n\n").map((n) => "⤷ " + n.split("\n")[0].replace(/^\[system notice\] /, "")).join("\n");
|
|
941
|
+
push({ kind: "message", message: { id: nextId(), role: "system", content: heads } });
|
|
942
|
+
remoteRef.current?.system(heads);
|
|
943
|
+
}
|
|
944
|
+
const toSend = (notices ? notices + "\n\n" : "") + (opts?.wake ? "A background job finished (notice above). Continue the task if it matters; otherwise reply in one line." : text);
|
|
945
|
+
if (!opts?.wake) {
|
|
946
|
+
push({ kind: "message", message: { id: nextId(), role: "user", content: text } });
|
|
947
|
+
remoteRef.current?.userPrompt(text); // mirror to followers
|
|
948
|
+
}
|
|
775
949
|
remoteRef.current?.turnStart(); // allocate this turn's assistant id (stable stream→final)
|
|
776
950
|
liveText.current = "";
|
|
777
951
|
liveReasoning.current = "";
|
|
@@ -783,7 +957,19 @@ function Root() {
|
|
|
783
957
|
setElapsed(0);
|
|
784
958
|
setStat("thinking");
|
|
785
959
|
try {
|
|
786
|
-
|
|
960
|
+
// Options-vs-act gate (feature classifierGate, default OFF). When enabled, classify the turn via the
|
|
961
|
+
// axe-classifier sidecar; on "ask" inject the memories.md EXCEPTION directive for THIS turn only. Degraded
|
|
962
|
+
// (sidecar unreachable/slow) or flag OFF → no directive, behavior byte-identical to today.
|
|
963
|
+
let turnDirective;
|
|
964
|
+
if (isFeatureEnabled("classifierGate", settings)) {
|
|
965
|
+
const gate = await classifyActVsAsk(text, {
|
|
966
|
+
endpoint: settings.classifier?.endpoint,
|
|
967
|
+
apiKey: settings.classifier?.apiKey,
|
|
968
|
+
minScore: settings.classifier?.gateMinScore,
|
|
969
|
+
});
|
|
970
|
+
turnDirective = actAskGateDirective(true, gate) ?? undefined;
|
|
971
|
+
}
|
|
972
|
+
const outcome = await session.send(expandFileMentions(snapshotEphemeralImages(toSend)), {
|
|
787
973
|
onRoute: (label, pct) => {
|
|
788
974
|
setRoute(label);
|
|
789
975
|
setCtxPct(pct);
|
|
@@ -804,7 +990,18 @@ function Root() {
|
|
|
804
990
|
}
|
|
805
991
|
}
|
|
806
992
|
},
|
|
993
|
+
onPromptProgress: ({ processed, total }) => {
|
|
994
|
+
const label = `reading context ${Math.min(100, Math.round((processed / total) * 100))}%`;
|
|
995
|
+
if (label !== prefillRef.current) {
|
|
996
|
+
prefillRef.current = label;
|
|
997
|
+
setPrefill(label);
|
|
998
|
+
}
|
|
999
|
+
},
|
|
807
1000
|
onDelta: (chunk) => {
|
|
1001
|
+
if (prefillRef.current) {
|
|
1002
|
+
prefillRef.current = "";
|
|
1003
|
+
setPrefill("");
|
|
1004
|
+
}
|
|
808
1005
|
liveText.current += chunk;
|
|
809
1006
|
liveTokRef.current += 1; // ≈1 token per streamed delta; flushed to the counter on the throttled tick
|
|
810
1007
|
setStat("streaming");
|
|
@@ -815,6 +1012,10 @@ function Root() {
|
|
|
815
1012
|
// Thinking streams before/between content — accumulate it and show it dimmed in the live entry
|
|
816
1013
|
// (renderEntry renders `reasoning` above the answer, dimColor). Distinct from onDelta so the
|
|
817
1014
|
// thought process reads at lower opacity than the real answer, per the requested look.
|
|
1015
|
+
if (prefillRef.current) {
|
|
1016
|
+
prefillRef.current = "";
|
|
1017
|
+
setPrefill("");
|
|
1018
|
+
}
|
|
818
1019
|
liveReasoning.current += chunk;
|
|
819
1020
|
liveTokRef.current += 1; // reasoning tokens ARE generated tokens — count them so the live
|
|
820
1021
|
// counter + tok/s keep moving during a long thinking phase (they were frozen before content).
|
|
@@ -907,7 +1108,7 @@ function Root() {
|
|
|
907
1108
|
setTasks(getAgentTasks()); // refresh the plan pane
|
|
908
1109
|
setStat("thinking");
|
|
909
1110
|
},
|
|
910
|
-
});
|
|
1111
|
+
}, turnDirective);
|
|
911
1112
|
// A completed (not interrupted) turn while still in plan mode counts as "a plan was proposed" —
|
|
912
1113
|
// arms the exit-time Approve & run picker (see applyMode).
|
|
913
1114
|
if (!outcome.interrupted && session.inPlanMode())
|
|
@@ -958,7 +1159,8 @@ function Root() {
|
|
|
958
1159
|
}
|
|
959
1160
|
}
|
|
960
1161
|
catch (e) {
|
|
961
|
-
|
|
1162
|
+
const activeLabel = session.modelRegistry().find((m) => m.id === session.currentModel())?.label;
|
|
1163
|
+
push({ kind: "message", message: { id: nextId(), role: "assistant", content: describeTurnError(e.message, { label: activeLabel, bases: session.endpoints().map((x) => x.base) }) } });
|
|
962
1164
|
}
|
|
963
1165
|
finally {
|
|
964
1166
|
tracker.noteTurn();
|
|
@@ -966,6 +1168,8 @@ function Root() {
|
|
|
966
1168
|
setLive(null);
|
|
967
1169
|
setLiveTools([]); // an interrupt/error mid-batch must not leave stale "running" rows on screen
|
|
968
1170
|
setCtxPct(session.ctxPct());
|
|
1171
|
+
prefillRef.current = "";
|
|
1172
|
+
setPrefill("");
|
|
969
1173
|
setStat("idle");
|
|
970
1174
|
const live = bg.list().filter((a) => a.status === "working" || a.status === "queued");
|
|
971
1175
|
if (live.length)
|
|
@@ -975,6 +1179,7 @@ function Root() {
|
|
|
975
1179
|
writeFileSync(SESSION_FILE, JSON.stringify(session.snapshot()), { mode: 0o600 });
|
|
976
1180
|
}
|
|
977
1181
|
catch { /* auto-save is best-effort */ }
|
|
1182
|
+
archiveSession(session.snapshot(), session.currentModel());
|
|
978
1183
|
// Re-check capabilities after every turn: MCP discovery (first-turn only) may have just landed,
|
|
979
1184
|
// and any skill_fetch/skill_save this turn updated skillsRef above. A no-op diff never hits the wire.
|
|
980
1185
|
remoteRef.current?.setCapabilities(buildCapabilities());
|
|
@@ -983,12 +1188,58 @@ function Root() {
|
|
|
983
1188
|
setQueuedPreview("");
|
|
984
1189
|
if (q)
|
|
985
1190
|
submitRef.current(q);
|
|
1191
|
+
else
|
|
1192
|
+
wakeIfIdleRef.current();
|
|
986
1193
|
}
|
|
987
1194
|
}, []);
|
|
1195
|
+
// A background shell job finished (wake mode): start a turn so Operator reacts without being polled. Only when
|
|
1196
|
+
// idle with nothing typed-ahead; otherwise the notice rides along on the next turn. Jobs ending together coalesce.
|
|
1197
|
+
const wakeIfIdleRef = useRef(() => { });
|
|
1198
|
+
wakeIfIdleRef.current = () => {
|
|
1199
|
+
if (getJobNoticeMode() !== "wake" || pendingJobNotices() === 0)
|
|
1200
|
+
return;
|
|
1201
|
+
if (statusRef.current !== "idle" || queued.current)
|
|
1202
|
+
return;
|
|
1203
|
+
void sendTurn("", { wake: true });
|
|
1204
|
+
};
|
|
1205
|
+
useEffect(() => {
|
|
1206
|
+
let timer;
|
|
1207
|
+
const off = onJobEvent((e) => {
|
|
1208
|
+
setShellJobs(listShellJobs().filter((j) => j.status === "running"));
|
|
1209
|
+
if (e.type !== "finished")
|
|
1210
|
+
return;
|
|
1211
|
+
if (timer)
|
|
1212
|
+
clearTimeout(timer);
|
|
1213
|
+
timer = setTimeout(() => wakeIfIdleRef.current(), 400);
|
|
1214
|
+
});
|
|
1215
|
+
return () => { off(); if (timer)
|
|
1216
|
+
clearTimeout(timer); };
|
|
1217
|
+
}, []);
|
|
988
1218
|
const sys = useCallback((text) => {
|
|
989
1219
|
push({ kind: "message", message: { id: nextId(), role: "system", content: text } });
|
|
990
1220
|
remoteRef.current?.system(text);
|
|
991
1221
|
}, []);
|
|
1222
|
+
// Idle-session policy (idle/): end a session nobody has touched for a while, never one that is working. This is the one entry that
|
|
1223
|
+
// mounts an interactive TUI, so headless/ACP/serve sessions are never subject to it. Ends through the SAME Teardown as /exit.
|
|
1224
|
+
useEffect(() => {
|
|
1225
|
+
const policy = resolveIdlePolicy(settings.idle);
|
|
1226
|
+
if (!policy.enabled)
|
|
1227
|
+
return;
|
|
1228
|
+
const startedAt = Date.now();
|
|
1229
|
+
const mon = startIdleMonitor({
|
|
1230
|
+
policy,
|
|
1231
|
+
version: VERSION,
|
|
1232
|
+
state: () => ({
|
|
1233
|
+
startedAt,
|
|
1234
|
+
lastActiveAt: idleLastActiveAt(),
|
|
1235
|
+
busy: statusRef.current !== "idle" || runningJobCount() > 0 || (bgRef.current?.activeCount() ?? 0) > 0 || rcConnectedRef.current,
|
|
1236
|
+
}),
|
|
1237
|
+
notify: sys,
|
|
1238
|
+
end: () => { void teardown.run("idle"); exit(); },
|
|
1239
|
+
});
|
|
1240
|
+
teardown.add("idle-monitor", () => mon.stop(), { order: 20 });
|
|
1241
|
+
return () => mon.stop();
|
|
1242
|
+
}, []);
|
|
992
1243
|
// Say so when this launch cleaned up after a previous one — silently killing processes would be worse than the orphans.
|
|
993
1244
|
useEffect(() => {
|
|
994
1245
|
const n = REAPED.killed.length;
|
|
@@ -1073,6 +1324,7 @@ function Root() {
|
|
|
1073
1324
|
setEntries([]);
|
|
1074
1325
|
setLive(null);
|
|
1075
1326
|
setCtxPct(0);
|
|
1327
|
+
newArchive();
|
|
1076
1328
|
sys("started a fresh conversation");
|
|
1077
1329
|
break;
|
|
1078
1330
|
case "model": {
|
|
@@ -1089,6 +1341,12 @@ function Root() {
|
|
|
1089
1341
|
saveSettings({ activeModel: s.currentModel() });
|
|
1090
1342
|
sys(`model → ${s.currentModel()} · ctx ${s.ctxPct()}% · turns ${s.turnCount()}`);
|
|
1091
1343
|
remoteRef.current?.setCapabilities(buildCapabilities()); // active model changed — re-sync attached followers
|
|
1344
|
+
// One honest line when the portal reports the chosen model down. Non-blocking (cache or ≤3s), silent when
|
|
1345
|
+
// the portal is unreachable or doesn't know the model — selection is never refused on portal state.
|
|
1346
|
+
const chosen = s.modelRegistry().find((m) => m.id === s.currentModel());
|
|
1347
|
+
if (chosen)
|
|
1348
|
+
void fetchPortalModels().then((cat) => { const note = offlineNote(chosen.label, cat?.get(portalIdFor(chosen))); if (note)
|
|
1349
|
+
sys(note); });
|
|
1092
1350
|
};
|
|
1093
1351
|
if (arg) {
|
|
1094
1352
|
apply(arg);
|
|
@@ -1096,16 +1354,29 @@ function Root() {
|
|
|
1096
1354
|
}
|
|
1097
1355
|
const active = s.currentModel();
|
|
1098
1356
|
const models = s.modelRegistry();
|
|
1099
|
-
const
|
|
1357
|
+
const plain = models.map((m) => `${m.label}${m.id === active ? " (active)" : ""}`);
|
|
1358
|
+
let shown = plain; // what the picker currently displays — resolve() maps the chosen text back through THIS
|
|
1100
1359
|
setModelPicker({
|
|
1101
1360
|
question: "Select a model",
|
|
1102
|
-
options,
|
|
1361
|
+
options: shown,
|
|
1103
1362
|
resolve: (answer) => {
|
|
1104
1363
|
setModelPicker(null);
|
|
1105
|
-
const idx =
|
|
1364
|
+
const idx = shown.indexOf(answer);
|
|
1106
1365
|
apply(idx >= 0 ? models[idx].id : answer.trim());
|
|
1107
1366
|
},
|
|
1108
1367
|
});
|
|
1368
|
+
// Live state markers from the portal: the picker opens instantly as before; if the catalog arrives it
|
|
1369
|
+
// re-renders the SAME rows (same order, same count) with a leading marker where the portal knows the model.
|
|
1370
|
+
// Any failure leaves the picker exactly as it was.
|
|
1371
|
+
void fetchPortalModels().then((cat) => {
|
|
1372
|
+
if (!cat)
|
|
1373
|
+
return;
|
|
1374
|
+
const marked = markPickerOptions(plain, models.map(portalIdFor), cat);
|
|
1375
|
+
if (marked.every((t, i) => t === plain[i]))
|
|
1376
|
+
return;
|
|
1377
|
+
shown = marked;
|
|
1378
|
+
setModelPicker((cur) => (cur && cur.question === "Select a model" ? { ...cur, options: marked } : cur));
|
|
1379
|
+
});
|
|
1109
1380
|
break;
|
|
1110
1381
|
}
|
|
1111
1382
|
case "artifacts": {
|
|
@@ -1171,6 +1442,94 @@ function Root() {
|
|
|
1171
1442
|
void load(() => compose.listMine());
|
|
1172
1443
|
break;
|
|
1173
1444
|
}
|
|
1445
|
+
case "sessions": {
|
|
1446
|
+
// Search every agent session on this machine (memory/session-catalog.ts) and pick one up. An Operator
|
|
1447
|
+
// session resumes in place; another agent's session (a provider in agents.md) continues HERE with its newest messages as a
|
|
1448
|
+
// framed turn (the submitRef inject path /artifacts uses), and the command that reopens it in its own
|
|
1449
|
+
// agent is printed alongside — both, so the owner chooses where to carry on.
|
|
1450
|
+
const cfg = await sessionSearchConfig();
|
|
1451
|
+
if (!cfg.enabled) {
|
|
1452
|
+
sys('session search is off — set "sessionSearch": { "enabled": true } in settings.json');
|
|
1453
|
+
break;
|
|
1454
|
+
}
|
|
1455
|
+
const setPatch = (patch) => setSessionsPicker((p) => (p ? { ...p, ...patch } : p));
|
|
1456
|
+
let seq = 0; // keystrokes search as you type; only the newest search may land
|
|
1457
|
+
const search = async (query, scope) => {
|
|
1458
|
+
const mine = ++seq;
|
|
1459
|
+
try {
|
|
1460
|
+
const hits = await searchCatalog(query, { scope, limit: 50 });
|
|
1461
|
+
const items = await Promise.all(hits.map(async (h) => ({ ...h, gone: h.cwd ? !(await folderExists(h.cwd)) : false })));
|
|
1462
|
+
if (mine === seq)
|
|
1463
|
+
setPatch({ items, loading: false, error: undefined });
|
|
1464
|
+
}
|
|
1465
|
+
catch (e) {
|
|
1466
|
+
if (mine === seq)
|
|
1467
|
+
setPatch({ loading: false, error: e.message });
|
|
1468
|
+
}
|
|
1469
|
+
};
|
|
1470
|
+
const onIntent = async (intent) => {
|
|
1471
|
+
switch (intent.kind) {
|
|
1472
|
+
case "close":
|
|
1473
|
+
setSessionsPicker(null);
|
|
1474
|
+
break;
|
|
1475
|
+
case "query":
|
|
1476
|
+
await search(intent.query, intent.scope);
|
|
1477
|
+
break;
|
|
1478
|
+
case "open": {
|
|
1479
|
+
const e = await catalogEntry(intent.id);
|
|
1480
|
+
if (!e) {
|
|
1481
|
+
setPatch({ error: "that session is no longer indexed — reopen /sessions" });
|
|
1482
|
+
break;
|
|
1483
|
+
}
|
|
1484
|
+
setSessionsPicker(null);
|
|
1485
|
+
if (e.source === "operator") {
|
|
1486
|
+
let saved;
|
|
1487
|
+
try {
|
|
1488
|
+
saved = JSON.parse(readFileSync(e.file, "utf8"));
|
|
1489
|
+
}
|
|
1490
|
+
catch { /* handled below */ }
|
|
1491
|
+
const msgs = (Array.isArray(saved) ? saved : saved?.messages);
|
|
1492
|
+
if (!msgs || !s.restore(msgs)) {
|
|
1493
|
+
sys(`could not resume "${e.title}" — its transcript is unreadable`);
|
|
1494
|
+
break;
|
|
1495
|
+
}
|
|
1496
|
+
setEntries(transcriptEntries(msgs));
|
|
1497
|
+
setLive(null);
|
|
1498
|
+
setCtxPct(s.ctxPct());
|
|
1499
|
+
if (e.file.startsWith(ARCHIVE_DIR))
|
|
1500
|
+
adoptArchive(e.file);
|
|
1501
|
+
else
|
|
1502
|
+
newArchive();
|
|
1503
|
+
sys(`resumed "${e.title}" — ${s.turnCount()} prior turns${e.cwd && e.cwd !== process.cwd() ? ` (from ${e.cwd})` : ""}`);
|
|
1504
|
+
break;
|
|
1505
|
+
}
|
|
1506
|
+
const ctx = await continuationContext(e.id);
|
|
1507
|
+
if (!ctx) {
|
|
1508
|
+
sys(`could not read "${e.title}" — its transcript moved or is unreadable`);
|
|
1509
|
+
break;
|
|
1510
|
+
}
|
|
1511
|
+
s.reset();
|
|
1512
|
+
setEntries([]);
|
|
1513
|
+
setLive(null);
|
|
1514
|
+
setCtxPct(0);
|
|
1515
|
+
newArchive(); // a fresh conversation, archived on its own
|
|
1516
|
+
sys(`continuing the ${e.agent} session "${e.title}" here.${e.resume ? `\nTo reopen it in ${e.agent} instead: ${e.resume}` : ""}`);
|
|
1517
|
+
submitRef.current(ctx.text);
|
|
1518
|
+
break;
|
|
1519
|
+
}
|
|
1520
|
+
}
|
|
1521
|
+
};
|
|
1522
|
+
setSessionsPicker({ items: [], loading: true, initialQuery: arg, initialScope: "all", onIntent });
|
|
1523
|
+
try {
|
|
1524
|
+
await indexCatalog(cfg.providers);
|
|
1525
|
+
}
|
|
1526
|
+
catch (e) {
|
|
1527
|
+
setPatch({ loading: false, error: `indexing failed: ${e.message}` });
|
|
1528
|
+
break;
|
|
1529
|
+
}
|
|
1530
|
+
await search(arg, "all");
|
|
1531
|
+
break;
|
|
1532
|
+
}
|
|
1174
1533
|
case "route":
|
|
1175
1534
|
if (s.pinRoute(arg || "auto"))
|
|
1176
1535
|
sys(arg && arg !== "auto" ? `routing pinned to ${arg}` : "routing set to auto (by size)");
|
|
@@ -1223,6 +1582,33 @@ function Root() {
|
|
|
1223
1582
|
sys(m || "(no memories yet — /remember <note> to add one)");
|
|
1224
1583
|
break;
|
|
1225
1584
|
}
|
|
1585
|
+
case "skill": {
|
|
1586
|
+
if (!arg) {
|
|
1587
|
+
const c = s.currentSkill();
|
|
1588
|
+
sys(c ? `active skill: ${c} — /skill off to deactivate` : "no skill active — /skill <name> to activate");
|
|
1589
|
+
break;
|
|
1590
|
+
}
|
|
1591
|
+
if (arg === "off") {
|
|
1592
|
+
const was = s.currentSkill();
|
|
1593
|
+
s.deactivateSkill();
|
|
1594
|
+
sys(was ? `skill '${was}' deactivated` : "no skill was active");
|
|
1595
|
+
break;
|
|
1596
|
+
}
|
|
1597
|
+
const fetchTool = registry.get("skill_fetch");
|
|
1598
|
+
if (!fetchTool) {
|
|
1599
|
+
sys("skill system not available");
|
|
1600
|
+
break;
|
|
1601
|
+
}
|
|
1602
|
+
sys(`loading skill '${arg}'…`);
|
|
1603
|
+
const content = await fetchTool.run({ slug: arg });
|
|
1604
|
+
if (content.startsWith("error:")) {
|
|
1605
|
+
sys(content);
|
|
1606
|
+
break;
|
|
1607
|
+
}
|
|
1608
|
+
s.activateSkill(arg, content);
|
|
1609
|
+
sys(`skill '${arg}' activated — its instructions are now injected into the system prompt`);
|
|
1610
|
+
break;
|
|
1611
|
+
}
|
|
1226
1612
|
case "whoami":
|
|
1227
1613
|
sys(authUser ? `signed in as ${authUser}` : "not signed in — run `operator auth login` in your shell");
|
|
1228
1614
|
break;
|
|
@@ -1338,7 +1724,9 @@ function Root() {
|
|
|
1338
1724
|
break;
|
|
1339
1725
|
}
|
|
1340
1726
|
case "mcp": {
|
|
1341
|
-
const
|
|
1727
|
+
const raw = (arg ?? "").trim();
|
|
1728
|
+
const [verb, ...rest] = raw.split(/\s+/);
|
|
1729
|
+
const a = (verb ?? "").toLowerCase();
|
|
1342
1730
|
if (a === "on") {
|
|
1343
1731
|
sys("enabling MCP tools…");
|
|
1344
1732
|
const n = await s.enableMcp();
|
|
@@ -1349,10 +1737,54 @@ function Root() {
|
|
|
1349
1737
|
saveSettings({ mcp: false });
|
|
1350
1738
|
sys("MCP off for new sessions (saved) — tools already loaded stay until you restart");
|
|
1351
1739
|
}
|
|
1740
|
+
else if (a === "reload") {
|
|
1741
|
+
sys("reloading MCP from disk (base + the extra MCP config)…");
|
|
1742
|
+
const n = await s.reloadMcp();
|
|
1743
|
+
saveSettings({ mcp: true });
|
|
1744
|
+
sys(n > 0 ? `MCP reloaded · ${n} fleet tools` : "MCP reloaded, but no tools discovered — check mcp_servers.json and the extra MCP config");
|
|
1745
|
+
}
|
|
1746
|
+
else if (a === "add") {
|
|
1747
|
+
// Live-drive: `/mcp add powertools [root]` upserts into writable overlay then reloads.
|
|
1748
|
+
const kind = (rest[0] ?? "").toLowerCase();
|
|
1749
|
+
if (kind === "powertools" || kind === "pt") {
|
|
1750
|
+
const root = rest[1] || process.cwd();
|
|
1751
|
+
const { resolve: pathResolve } = await import("node:path");
|
|
1752
|
+
const { fileURLToPath } = await import("node:url");
|
|
1753
|
+
// powertools.mjs ships next to this package's mcp/ folder — resolve from kode-tsi root.
|
|
1754
|
+
const powertoolsPath = pathResolve(fileURLToPath(new URL(".", import.meta.url)), "..", "mcp", "powertools.mjs");
|
|
1755
|
+
const absRoot = pathResolve(root);
|
|
1756
|
+
try {
|
|
1757
|
+
const { upsertMcpServer } = await import("./mcp/config.js");
|
|
1758
|
+
// No tools allowlist — advertise whatever powertools soft-miss surface is present (v0.3 toolbox).
|
|
1759
|
+
const written = await upsertMcpServer("powertools", {
|
|
1760
|
+
transport: "stdio",
|
|
1761
|
+
command: "node",
|
|
1762
|
+
args: [powertoolsPath],
|
|
1763
|
+
env: { POWERTOOLS_ROOT: absRoot },
|
|
1764
|
+
});
|
|
1765
|
+
const n = await s.reloadMcp();
|
|
1766
|
+
saveSettings({ mcp: true });
|
|
1767
|
+
sys(`powertools added · root=${absRoot} · wrote ${written} · ${n} fleet tools (alias: pt)`);
|
|
1768
|
+
}
|
|
1769
|
+
catch (e) {
|
|
1770
|
+
sys(`couldn't add powertools: ${e instanceof Error ? e.message : String(e)}`);
|
|
1771
|
+
}
|
|
1772
|
+
}
|
|
1773
|
+
else {
|
|
1774
|
+
sys("usage: /mcp add powertools [root] — upserts secure CLI powertools MCP (root sandboxes path tools)");
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1352
1777
|
else {
|
|
1353
1778
|
const n = s.mcpToolCount();
|
|
1354
|
-
|
|
1355
|
-
|
|
1779
|
+
const servers = s.mcpServers();
|
|
1780
|
+
const inv = servers.length
|
|
1781
|
+
? "\n" + servers.map((sv) => ` · ${sv.name}: ${sv.tools.map((t) => t.name).join(", ") || "(no tools)"}`).join("\n")
|
|
1782
|
+
: "";
|
|
1783
|
+
sys(n > 0
|
|
1784
|
+
? `${n} fleet MCP tools this session · /mcp reload · /mcp off${inv}`
|
|
1785
|
+
: settings.mcp
|
|
1786
|
+
? "MCP is on — tools are discovered when you send your first message · /mcp reload after config edits"
|
|
1787
|
+
: "no MCP tools loaded — /mcp on · /mcp add powertools [root] · /mcp reload");
|
|
1356
1788
|
}
|
|
1357
1789
|
break;
|
|
1358
1790
|
}
|
|
@@ -1384,6 +1816,21 @@ function Root() {
|
|
|
1384
1816
|
void sendTurn(`Use the deep_research tool to research this thoroughly and give me a cited, multi-source brief: ${arg}`);
|
|
1385
1817
|
break;
|
|
1386
1818
|
}
|
|
1819
|
+
case "allow": {
|
|
1820
|
+
if (!arg) {
|
|
1821
|
+
sys("usage: /allow <tool:args> e.g. /allow bash:npm test*");
|
|
1822
|
+
break;
|
|
1823
|
+
}
|
|
1824
|
+
const colon = arg.indexOf(":");
|
|
1825
|
+
const pat = colon > 0 ? { tool: arg.slice(0, colon), args: arg.slice(colon + 1) } : { tool: arg };
|
|
1826
|
+
const sx = s;
|
|
1827
|
+
if (!sx.permissionCfg.allow)
|
|
1828
|
+
sx.permissionCfg.allow = [];
|
|
1829
|
+
sx.permissionCfg.allow.push(pat);
|
|
1830
|
+
sx.policy.addAllowPattern(pat);
|
|
1831
|
+
sys(`allow pattern added: ${pat.tool}${pat.args ? ":" + pat.args : ""}`);
|
|
1832
|
+
break;
|
|
1833
|
+
}
|
|
1387
1834
|
case "endpoints": {
|
|
1388
1835
|
const h = await s.endpointHealth();
|
|
1389
1836
|
sys("endpoints:\n" + s.endpoints().map((e) => ` ${h[e.name] ? "●" : "○"} ${e.name} ${e.base} ${e.model} ctx ${e.ctxWindow.toLocaleString()}`).join("\n"));
|
|
@@ -1545,10 +1992,18 @@ function Root() {
|
|
|
1545
1992
|
}
|
|
1546
1993
|
sys("checking services…");
|
|
1547
1994
|
const { ensureServices } = await import("./services/preflight.js");
|
|
1995
|
+
const svcAuroraCfg = { base: settings.endpoints.aurora.base, ...settings.services?.aurora };
|
|
1548
1996
|
const reports = await ensureServices({
|
|
1549
|
-
aurora:
|
|
1997
|
+
aurora: svcAuroraCfg,
|
|
1550
1998
|
autopilot: settings.services?.autopilot,
|
|
1999
|
+
vision: settings.services?.vision,
|
|
1551
2000
|
});
|
|
2001
|
+
if (svcAuroraCfg.base && svcAuroraCfg.base !== settings.endpoints.aurora.base) {
|
|
2002
|
+
settings.endpoints.aurora.base = svcAuroraCfg.base;
|
|
2003
|
+
}
|
|
2004
|
+
const svcKey = svcAuroraCfg.apiKey;
|
|
2005
|
+
if (svcKey && !settings.endpoints.aurora.apiKey)
|
|
2006
|
+
settings.endpoints.aurora.apiKey = svcKey;
|
|
1552
2007
|
const { searxngStatus, probeSearxng } = await import("./tools/searxng.js");
|
|
1553
2008
|
const sxActive = searxngStatus() === "active";
|
|
1554
2009
|
const sxUp = sxActive || await probeSearxng().catch(() => false);
|
|
@@ -1562,16 +2017,56 @@ function Root() {
|
|
|
1562
2017
|
}
|
|
1563
2018
|
case "agents": {
|
|
1564
2019
|
const l = bg.list();
|
|
1565
|
-
if (!
|
|
1566
|
-
|
|
2020
|
+
if (!arg) {
|
|
2021
|
+
if (!l.length) {
|
|
2022
|
+
sys("no sub-agents spawned this session");
|
|
2023
|
+
break;
|
|
2024
|
+
}
|
|
2025
|
+
const running = l.filter((a) => a.status === "working").length;
|
|
2026
|
+
const queued = l.filter((a) => a.status === "queued").length;
|
|
2027
|
+
const done = l.filter((a) => a.status === "idle").length;
|
|
2028
|
+
const errored = l.filter((a) => a.status === "stopped").length;
|
|
2029
|
+
const counts = [running ? `${running} running` : "", queued ? `${queued} queued` : "", done ? `${done} done` : "", errored ? `${errored} errored` : ""].filter(Boolean).join(" · ");
|
|
2030
|
+
sys(`sub-agents (${counts}):\n` + l.map((a) => ` ${formatAgentDetail(a)}`).join("\n"));
|
|
2031
|
+
break;
|
|
2032
|
+
}
|
|
2033
|
+
const parts = arg.split(/\s+/);
|
|
2034
|
+
const targetId = parts[0];
|
|
2035
|
+
const subCmd = parts[1];
|
|
2036
|
+
const subArg = parts.slice(2).join(" ");
|
|
2037
|
+
// A finished agent decommissions out of the live map after its reap TTL — still show its
|
|
2038
|
+
// record (same honesty rule as agent_status's retiredList fallback) instead of "unknown".
|
|
2039
|
+
const target = l.find((a) => a.id === targetId) ?? bg.retiredList().find((a) => a.id === targetId);
|
|
2040
|
+
if (!target) {
|
|
2041
|
+
sys(`unknown agent ${targetId} — spawned this session: ${l.length ? l.map((x) => x.id).join(", ") : "none"}`);
|
|
1567
2042
|
break;
|
|
1568
2043
|
}
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
2044
|
+
if (subCmd === "msg" || subCmd === "message") {
|
|
2045
|
+
if (!subArg) {
|
|
2046
|
+
sys("usage: /agents <id> msg <text>");
|
|
2047
|
+
break;
|
|
2048
|
+
}
|
|
2049
|
+
const ok = bg.sendToAgent(targetId, subArg);
|
|
2050
|
+
sys(ok ? `message sent to ${targetId}` : `${targetId} is not running — can only message working/queued agents`);
|
|
2051
|
+
}
|
|
2052
|
+
else if (subCmd === "stop" || subCmd === "kill") {
|
|
2053
|
+
sys(bg.stop(targetId) ? `stopped ${targetId}` : `${targetId} already finished`);
|
|
2054
|
+
}
|
|
2055
|
+
else {
|
|
2056
|
+
sys(formatAgentDeepView(target));
|
|
2057
|
+
}
|
|
2058
|
+
break;
|
|
2059
|
+
}
|
|
2060
|
+
case "jobs": {
|
|
2061
|
+
const cmd = parseJobsArgs(arg);
|
|
2062
|
+
if (cmd.kind === "error")
|
|
2063
|
+
sys(cmd.message);
|
|
2064
|
+
else if (cmd.kind === "stop") {
|
|
2065
|
+
sys(stopShellJob(cmd.id));
|
|
2066
|
+
setShellJobs(listShellJobs().filter((j) => j.status === "running"));
|
|
2067
|
+
}
|
|
2068
|
+
else
|
|
2069
|
+
sys("shell jobs:\n" + renderJobsList(listShellJobs()).split("\n").map((l) => " " + l).join("\n"));
|
|
1575
2070
|
break;
|
|
1576
2071
|
}
|
|
1577
2072
|
case "bg":
|
|
@@ -1743,13 +2238,15 @@ function Root() {
|
|
|
1743
2238
|
}, [sendTurn, handleSlash]);
|
|
1744
2239
|
submitRef.current = onSubmit;
|
|
1745
2240
|
const onQueue = useCallback((text) => { queued.current = queued.current ? `${queued.current}\n${text}` : text; setQueuedPreview(queued.current); }, []);
|
|
1746
|
-
// Shift+Tab cycles the operating mode (Claude
|
|
2241
|
+
// Shift+Tab cycles the operating mode (matches Claude Code). auto→manual→plan→auto. Auto drives with
|
|
1747
2242
|
// no approval gate; Manual gates mutating tools through the approve() bridge; Plan is read-only research.
|
|
1748
2243
|
const onCycleMode = useCallback(() => {
|
|
1749
2244
|
const cur = opModeRef.current;
|
|
1750
2245
|
const next = cur === "auto" ? "manual" : cur === "manual" ? "plan" : "auto";
|
|
1751
2246
|
applyMode(next);
|
|
1752
2247
|
}, [applyMode]);
|
|
2248
|
+
// ctrl+b: move the running shell command to the background so the turn continues. Nothing running → nothing happens.
|
|
2249
|
+
const onBackground = useCallback(() => { session.detachShell(); }, []);
|
|
1753
2250
|
const onInterrupt = useCallback(() => {
|
|
1754
2251
|
if (statusRef.current === "idle") {
|
|
1755
2252
|
void teardown.run("quit");
|
|
@@ -1779,11 +2276,66 @@ function Root() {
|
|
|
1779
2276
|
if (boot !== "ready")
|
|
1780
2277
|
return;
|
|
1781
2278
|
const self = selfAgent();
|
|
2279
|
+
const WAKE_COOLDOWN_MS = 30000; // per-source min gap between wake injections (ping-pong guard, Ghost-reviewed)
|
|
2280
|
+
const lastWakeBySource = new Map();
|
|
2281
|
+
let wakeBuffer = [];
|
|
2282
|
+
// FAILSAFE (2026-10-22 live incident — the same [mentor-wake] turn was submitted twice, double-padding
|
|
2283
|
+
// context on the way to a wedged "compacting" session): dedupe by message id at the point of delivery, so
|
|
2284
|
+
// a message can never be rendered or woken on twice NO MATTER the cause (a re-entrant/overlapping pull()
|
|
2285
|
+
// tick, a double-mounted effect, a requeue on turn interrupt) — defense at the layer where the duplicate
|
|
2286
|
+
// actually becomes user-visible, instead of chasing every possible way two polls could overlap. Bounded
|
|
2287
|
+
// (not unbounded growth) by dropping ids once they've aged well past any plausible re-delivery window.
|
|
2288
|
+
const deliveredIds = new Map(); // msg.id -> first-seen ts
|
|
2289
|
+
const DEDUPE_TTL_MS = 10 * 60_000;
|
|
2290
|
+
const seen = (id, now) => {
|
|
2291
|
+
for (const [staleId, ts] of deliveredIds)
|
|
2292
|
+
if (now - ts > DEDUPE_TTL_MS)
|
|
2293
|
+
deliveredIds.delete(staleId);
|
|
2294
|
+
if (deliveredIds.has(id))
|
|
2295
|
+
return true;
|
|
2296
|
+
deliveredIds.set(id, now);
|
|
2297
|
+
return false;
|
|
2298
|
+
};
|
|
2299
|
+
let pulling = false; // reentrancy guard — pollBus's consume-once rename can still race if pull() overlaps itself
|
|
1782
2300
|
const pull = () => {
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
2301
|
+
if (pulling)
|
|
2302
|
+
return;
|
|
2303
|
+
pulling = true;
|
|
2304
|
+
try {
|
|
2305
|
+
const now = Date.now();
|
|
2306
|
+
const incoming = pollBus(self).filter((m) => !seen(`in:${m.id}`, now));
|
|
2307
|
+
for (const msg of incoming)
|
|
2308
|
+
push({ kind: "bus", id: nextId(), msg, direction: "in", at: Date.now() });
|
|
2309
|
+
for (const msg of pollSent(self).filter((m) => !seen(`out:${m.id}`, now))) {
|
|
2310
|
+
push({ kind: "bus", id: nextId(), msg, direction: "out", at: Date.now() });
|
|
2311
|
+
}
|
|
2312
|
+
// Wake-on-mentor (feature: wakeOnMentor, default OFF): a rendered bus message is only PIXELS for the human —
|
|
2313
|
+
// it never enters the model's context, so an idle autonomous session SEES a peer/teacher message but can't
|
|
2314
|
+
// ACT on it. When enabled, inject incoming messages as a turn via the user-prompt path (submit when idle,
|
|
2315
|
+
// queue when busy — never interrupt a running turn). PER-SOURCE COOLDOWN (ping-pong guard, Ghost-reviewed):
|
|
2316
|
+
// a source's first message wakes immediately; further messages from the SAME source within WAKE_COOLDOWN_MS
|
|
2317
|
+
// buffer and coalesce into one wake AFTER the window, so two agents waking each other can't run away — and
|
|
2318
|
+
// no message is dropped. settings.wakeOnMentor.from narrows which senders may drive a turn (unset = any).
|
|
2319
|
+
if (isFeatureEnabled("wakeOnMentor", settings)) {
|
|
2320
|
+
const allow = settings.wakeOnMentor?.from;
|
|
2321
|
+
const eligible = allow?.length ? incoming.filter((m) => allow.includes(m.from)) : incoming;
|
|
2322
|
+
wakeBuffer.push(...eligible);
|
|
2323
|
+
const ready = selectReadyWakes(wakeBuffer, lastWakeBySource, now, WAKE_COOLDOWN_MS);
|
|
2324
|
+
const wakeText = ready.length ? buildMentorWake(ready) : null;
|
|
2325
|
+
if (wakeText) {
|
|
2326
|
+
if (statusRef.current === "idle")
|
|
2327
|
+
submitRef.current?.(wakeText);
|
|
2328
|
+
else
|
|
2329
|
+
onQueue(wakeText);
|
|
2330
|
+
for (const m of ready)
|
|
2331
|
+
lastWakeBySource.set(m.from, now);
|
|
2332
|
+
wakeBuffer = wakeBuffer.filter((m) => !ready.includes(m));
|
|
2333
|
+
}
|
|
2334
|
+
}
|
|
2335
|
+
}
|
|
2336
|
+
finally {
|
|
2337
|
+
pulling = false;
|
|
2338
|
+
}
|
|
1787
2339
|
};
|
|
1788
2340
|
pull();
|
|
1789
2341
|
const id = setInterval(pull, 3000);
|
|
@@ -1792,7 +2344,7 @@ function Root() {
|
|
|
1792
2344
|
if (boot === "checking")
|
|
1793
2345
|
return _jsx(Text, { dimColor: true, children: bootDetail || "connecting to Operator…" });
|
|
1794
2346
|
if (boot === "down") {
|
|
1795
|
-
return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: "Can't reach Operator on the configured endpoint." }), bootDetail ? _jsx(Text, { dimColor: true, children: bootDetail }) : null, _jsx(Text, { dimColor: true, children: "The Operator model is launchd-owned. Recover it with: launchctl kickstart -k gui/$(id -u)/
|
|
2347
|
+
return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: "Can't reach Operator on the configured endpoint." }), bootDetail ? _jsx(Text, { dimColor: true, children: bootDetail }) : null, _jsx(Text, { dimColor: true, children: "The Operator model is launchd-owned. Recover it with: launchctl kickstart -k gui/$(id -u)/ai.operator.gateway" })] }));
|
|
1796
2348
|
}
|
|
1797
2349
|
// While a turn runs, show a LIVE line: braille spinner + climbing token count + live tok/s + elapsed
|
|
1798
2350
|
// seconds. When idle, show the last turn's final "N tok · X tok/s · Ys". Never freeze on the previous
|
|
@@ -1808,7 +2360,7 @@ function Root() {
|
|
|
1808
2360
|
? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
|
|
1809
2361
|
: `${spin} ${fmtMeta(elapsed, liveTok)}`
|
|
1810
2362
|
: metrics;
|
|
1811
|
-
return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, liveTools: liveTools, route: route, ctxPct: ctxPct, version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, queuedPreview: queuedPreview, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, rcConnected: rcConnected, rcActive: rcActive, approval: approval, question: question, modelPicker: modelPicker, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, onApprovalDecide: (allow, always) => {
|
|
2363
|
+
return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, prefill: prefill, liveTools: liveTools, route: route, ctxPct: ctxPct, version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, shellJobs: shellJobs, onBackground: onBackground, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, queuedPreview: queuedPreview, onInterrupt: onInterrupt, onCycleMode: onCycleMode, opMode: opMode, rcConnected: rcConnected, rcActive: rcActive, approval: approval, question: question, modelPicker: modelPicker, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, sessionsPicker: sessionsPicker, onApprovalDecide: (allow, always) => {
|
|
1812
2364
|
const cur = approval;
|
|
1813
2365
|
if (cur)
|
|
1814
2366
|
settleApproval(cur.id, allow, always); // first-wins with any remote follower answer
|
|
@@ -1882,7 +2434,7 @@ if (FULLSCREEN) {
|
|
|
1882
2434
|
process.once(sig, () => { leaveAltScreen(); process.exit(0); });
|
|
1883
2435
|
}
|
|
1884
2436
|
else {
|
|
1885
|
-
process.stdout.write(mastheadLines(
|
|
2437
|
+
process.stdout.write(mastheadLines(`${ctxBadge(modelCtxFor(startupModelId(settings, EVENT_ACTOR), settings.models))} · v${VERSION}`).join("\n") + "\n");
|
|
1886
2438
|
// ONE-TIME ONLY: on a terminal without clickable links / copy-on-select (Terminal.app, or an unknown one),
|
|
1887
2439
|
// point the owner at the terminals Operator is built for — then persist the flag so it NEVER shows again.
|
|
1888
2440
|
// This is a single first-run pointer, not the per-boot tip that was removed. iTerm2/Ghostty/Kitty/WezTerm
|