@0perator/operator 0.2.2-next.0 → 0.2.4

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.
@@ -3,7 +3,7 @@
3
3
  //
4
4
  // operator run "<task>"|- [--model ID] [--permissions gated|audit|bypass] [--cwd DIR]
5
5
  // [--output text|json|stream-json] [--json] [--log F] [--loop] [--max-turns N]
6
- // [--max-seconds S] [--keep-awake]
6
+ // [--max-seconds S] [--keep-awake] [--activate]
7
7
  // operator loop "<objective>" (alias for `run --loop`)
8
8
  // operator board <list|add "<task>"|run|status> [--json] [--max N] [--keep-awake]
9
9
  // operator routine <list|run <id>|install <id> [--crontab]|watch> [--keep-awake]
@@ -22,7 +22,8 @@ import { boardPath, addTask, readBoard } from "./board.js";
22
22
  import { routinesPath, readRoutines } from "./routines.js";
23
23
  import { readableRoutine, nextFire, runRoutine, launchdPlist, launchdLabel, crontabLine } from "./routine-run.js";
24
24
  import { ensureServices } from "../services/preflight.js";
25
- import { modelRegistry } from "../router/models.js";
25
+ import { modelRegistry, findModel, DEFAULT_ACTIVE_MODEL } from "../router/models.js";
26
+ import { activateForRun, ownerActivation } from "../router/activation.js";
26
27
  const AUTONOMY_COMMANDS = new Set(["run", "loop", "board", "routine", "dream", "acp", "media-robot"]);
27
28
  /** Split argv (after the subcommand) into --bool flags, --key value pairs, and positionals. `--` ends
28
29
  * flag parsing so a task string starting with a dash is preserved. */
@@ -59,7 +60,7 @@ function parseFlags(args, valued) {
59
60
  const VALUED = new Set(["log", "max-turns", "max-seconds", "max", "n", "source", "sink", "kind", "model", "permissions", "cwd", "output"]);
60
61
  const OUTPUTS = ["text", "json", "stream-json"];
61
62
  const PERMISSION_MODES = ["gated", "audit", "bypass"];
62
- const RUN_USAGE = `usage: operator run "<task>"|- [--model ID] [--permissions gated|audit|bypass] [--cwd DIR] [--output text|json|stream-json] [--max-turns N] [--max-seconds S]`;
63
+ const RUN_USAGE = `usage: operator run "<task>"|- [--model ID] [--permissions gated|audit|bypass] [--cwd DIR] [--output text|json|stream-json] [--max-turns N] [--max-seconds S] [--activate]`;
63
64
  /** Validate `operator run` flags. A string is the usage error (exit 2: the command line itself is wrong,
64
65
  * the shell convention; 1 stays "the task failed"). */
65
66
  export function runFlags(args) {
@@ -73,7 +74,7 @@ export function runFlags(args) {
73
74
  const model = f.val.get("model");
74
75
  if (model !== undefined && !model)
75
76
  return "--model needs a model id";
76
- return { output, model, permissions: pm, cwd: f.val.get("cwd") };
77
+ return { output, model, permissions: pm, cwd: f.val.get("cwd"), ...(f.bool.has("activate") ? { activate: true } : {}) };
77
78
  }
78
79
  /** `--model`: a registry id (`moa`, `cortana`, `gpt-oss-20b` …) selects that model — the same as `/model` — so an
79
80
  * orchestrated profile like MoA really runs as MoA; any other string is a raw model name on the primary endpoint. */
@@ -301,7 +302,7 @@ export async function dispatchAutonomy(argv, settings) {
301
302
  const rf = runFlags(argv.slice(3));
302
303
  if (typeof rf === "string")
303
304
  return usage(rf);
304
- const { output, model, permissions: pm, cwd } = rf;
305
+ const { output, model, permissions: pm, cwd, activate } = rf;
305
306
  if (cwd !== undefined) {
306
307
  try {
307
308
  process.chdir(cwd);
@@ -319,6 +320,14 @@ export async function dispatchAutonomy(argv, settings) {
319
320
  if (pm)
320
321
  settings.permissions = { ...settings.permissions, mode: pm };
321
322
  const loop = cmd === "loop" || f.bool.has("loop");
323
+ if (activate) {
324
+ const id = findModel(modelRegistry(settings.models), model ?? settings.activeModel ?? DEFAULT_ACTIVE_MODEL)?.id;
325
+ const failed = id ? await activateForRun(id, ownerActivation(id), (t) => process.stderr.write(t)) : undefined;
326
+ if (failed) {
327
+ process.stderr.write(`operator: ${failed}\n`);
328
+ return 1;
329
+ }
330
+ }
322
331
  return withKeepAwake(wantKeepAwake(settings, f), "Operator run", () => runHeadless(settings, prompt, {
323
332
  output,
324
333
  logFile: f.val.get("log"),
@@ -2,6 +2,7 @@
2
2
  // session (persona + project context + handoff, the Aurora router, permissions, telemetry) but with NO
3
3
  // Ink/TTY dependency, so `operator run/loop/board/dream` construct a real, tool-capable Session the same
4
4
  // way the shell does. Kept deliberately small: it composes existing building blocks, it does not fork them.
5
+ import { cachedModelList, listedProfiles } from "../router/model-list.js";
5
6
  import { randomUUID } from "node:crypto";
6
7
  import { Session } from "../session.js";
7
8
  import { AuroraRouter } from "../router/router.js";
@@ -10,7 +11,7 @@ import { composeSystemPrompt, subagentSystemPrompt } from "../config/persona.js"
10
11
  import { SUBAGENT_ROLES, SUBAGENT_TOOL_DENY } from "../engine/grandmaster.js";
11
12
  import { ensureScratchDir } from "../config/scratch.js";
12
13
  import { modelCtxFor, leanHarnessFor, CHAIN_MODEL_ID } from "../router/models.js";
13
- import { compactionThreshold, compactionCeilingTokens, compactionMinDecodeTps, turnWallClockMs, buildEndpointChain } from "../config/settings.js";
14
+ import { compactionThreshold, compactionCeilingTokens, compactionMinDecodeTps, compactionSpeedTargetTokens, compactionSummaryModel, turnWallClockMs, buildEndpointChain } from "../config/settings.js";
14
15
  import { resolveMode } from "../classifier/modes.js";
15
16
  import { classifierConfig } from "../classifier/config.js";
16
17
  import { setSpeculation, speculationEnabled } from "../engine/aurora.js";
@@ -64,12 +65,15 @@ export function createAutonomySession(settings, opts = {}) {
64
65
  temperature: settings.temperature,
65
66
  recall: settings.memory.recall,
66
67
  models: settings.models,
68
+ reasoningEffort: settings.ui?.effort,
69
+ voice: settings.services?.voice,
67
70
  moa: settings.moa,
68
71
  classifier: { mode: resolveMode(settings), endpoint: classifierConfig(settings).endpoint },
69
72
  fastStart: settings.fastStart,
70
73
  frontDoor: settings.frontDoor, // a message the gateway's front door answers (engine/front-door.ts) never runs a full turn
71
74
  features: settings.features, // feature flags — registers flag-gated tools (e.g. cloudAgents) only when on
72
75
  activeModel: settings.activeModel,
76
+ dynamicModels: () => listedProfiles(cachedModelList(), settings.models), // a saved pick from the gateway's list
73
77
  fallbackModel: settings.fallbackModel,
74
78
  contextPin: settings.contextPin, // the owner's /context choice (KODE_CONTEXT wins in loadSettings) holds for headless, ACP and delegated runs too
75
79
  contextFloor: settings.contextFloor,
@@ -81,6 +85,8 @@ export function createAutonomySession(settings, opts = {}) {
81
85
  compactionThreshold: compactionThreshold(settings),
82
86
  compactionCeilingTokens: compactionCeilingTokens(settings, "autonomy"), // the owner's compaction.autonomyCeilingTokens / env, else no ceiling — never the interactive ceilingTokens, so a snappy interactive setting can't throttle an unattended build into a compaction-thrash loop
83
87
  compactionMinDecodeTps: compactionMinDecodeTps(settings, "autonomy"), // only compaction.autonomyMinDecodeTps; the interactive floor never reaches an unattended run
88
+ compactionSpeedTargetTokens: compactionSpeedTargetTokens(settings),
89
+ compactionSummaryModel: compactionSummaryModel(settings),
84
90
  sleepConsolidation: settings.autonomy?.sleepConsolidation, // headless autonomy ("operator run/loop/dream") consolidates on idle too (0.1.177)
85
91
  ...opts.extra,
86
92
  });
package/dist/cli.js CHANGED
@@ -13,7 +13,8 @@ import { restKey } from "./ui/Composer.js";
13
13
  import { mastheadLines } from "./ui/Masthead.js";
14
14
  import { shouldPromptPlanExit, resolvePlanExit, PLAN_EXIT_OPTIONS } from "./ui/planExit.js";
15
15
  import { initialMode, modePolicy, nextMode, parseMode, planToggleTarget } from "./permissions/modes.js";
16
- import { FREE_ROW_PRESETS, PROVIDER_ROW_PRESETS, connectedAccounts, isMainModel, looksLikeSecret, contextLine, contextPickerView, keyStoredLine, mainPickerView, markModelRows, modelLine, modelPickerView, onceEach, pickerAnswer, providerPickerView, rereadConfirmView, wantsContextStep, wantsRereadConfirm } from "./ui/modelPicker.js";
16
+ import { createActivationFlow } from "./ui/activationFlow.js";
17
+ import { FREE_ROW_PRESETS, PROVIDER_ROW_PRESETS, connectedAccounts, isMainModel, mainIds, looksLikeSecret, contextLine, contextPickerView, keyStoredLine, mainPickerView, markModelRows, modelLine, modelPickerView, onceEach, pickerAnswer, providerPickerView, rereadConfirmView, wantsContextStep, wantsRereadConfirm } from "./ui/modelPicker.js";
17
18
  import { RemoteHost, toRemoteAgents } from "./remote/host.js";
18
19
  import { GrantStore, grantsEnabled } from "./remote/grants.js";
19
20
  import { REMOTE_SAFE_COMMANDS, REMOTE_SAFE_COMMAND_NAMES } from "./remote/safe-commands.js";
@@ -41,23 +42,24 @@ import { seedCalibration } from "./engine/calibration-seed.js";
41
42
  import { AuroraRouter } from "./router/router.js";
42
43
  import { BackgroundAgents } from "./background/index.js";
43
44
  import { clearResumable, pickUpSaved, quitSummary, resumeOnReopen, saveResumable, startSaved } from "./background/resume.js";
44
- import { loadSettings, saveSettings, settingsLoadProblems, compactionThreshold, compactionCeilingTokens, compactionMinDecodeTps, rcAutostart, eagerAuthAtBoot, applySeat, setActiveSeat, buildEndpointChain, parseContextArg, nextContextPin } from "./config/settings.js";
45
+ import { loadSettings, saveSettings, settingsLoadProblems, compactionThreshold, compactionCeilingTokens, compactionMinDecodeTps, compactionSpeedTargetTokens, compactionSummaryModel, rcAutostart, eagerAuthAtBoot, applySeat, setActiveSeat, buildEndpointChain, parseContextArg, nextContextPin } from "./config/settings.js";
45
46
  import { resolveSeat } from "./auth/identity.js";
46
47
  import { PermissionPolicy } from "./permissions/index.js";
47
48
  import { caps } from "./ui/capabilities.js";
48
- import { composeSystemPrompt, appendMemory, memoryBudgetNote, subagentSystemPrompt } from "./config/persona.js";
49
+ import { composeSystemPrompt, appendMemory, memoryBudgetNote, subagentSystemPrompt, handoffNotice } from "./config/persona.js";
49
50
  import { SUBAGENT_ROLES, SUBAGENT_TOOL_DENY, roleCanWrite } from "./engine/grandmaster.js";
50
51
  import { applyToolsBinPath, operatorPath } from "./config/home.js";
51
52
  import { ensureOperatorHome } from "./config/scaffold.js";
52
53
  import { listLocalSkills, skillCommand } from "./config/skills-index.js";
53
- import { modelCtxFor, leanHarnessFor, selectModel, modelRegistry, fmtCtx, shortName, BYO_PRESETS, CHAIN_MODEL_ID } from "./router/models.js";
54
+ import { modelCtxFor, leanHarnessFor, selectModel, modelRegistry, fmtCtx, shortName, BYO_PRESETS, CHAIN_MODEL_ID, EFFORT_LEVELS, parseEffort } from "./router/models.js";
54
55
  import { fetchPortalModels, offlineNote, portalIdFor } from "./router/portal.js";
55
56
  import { fetchFreeModels } from "./router/free-models.js";
56
57
  import { fetchProviderModels } from "./router/provider-models.js";
58
+ import { cachedModelList, fetchModelList, listedProfiles } from "./router/model-list.js";
57
59
  import { describeTurnError } from "./engine/net-error.js";
58
60
  import { fallbackNotice, gatewayFallbackLine, primaryRecoveredLine, recoveryLine } from "./engine/continuation.js";
59
61
  import { shownModelLabel } from "./engine/identity.js";
60
- import { speedCompactionLine } from "./engine/speed-compaction.js";
62
+ import { speedCompactionLine, speedTargetMissedLine } from "./engine/speed-compaction.js";
61
63
  import { hasByoToken, setByoToken } from "./auth/byo.js";
62
64
  import { getDiscoveredModels } from "./router/discovery.js";
63
65
  import { disposeShellSession, getAgentTasks, registry } from "./tools/registry.js";
@@ -157,7 +159,7 @@ if (process.argv.includes("--version") || process.argv.includes("-V")) {
157
159
  }
158
160
  if (process.argv.includes("--help")) {
159
161
  process.stdout.write(mastheadLines(`v${VERSION}`).join("\n") +
160
- "\n\nUsage:\n operator start the interactive session\n 0p short for operator (every subcommand works)\n operator --resume resume the last session in this directory\n operator update update to the latest release\n operator update --next install the next prerelease (built from develop); --latest goes back\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 gateway the local model runtime: start | stop | status | health | logs\n operator toolchain the llama-server store: status | verify | install | activate | rollback | migrate | which\n operator run <task>|- run one task headless (--model, --permissions, --output json, --cwd)\n operator selfimprove backfill [--since YYYY-MM-DD] [--dry-run]\n turn looped turns and mentor pairs into lessons\n operator --version print the version\n");
162
+ "\n\nUsage:\n operator start the interactive session\n 0p short for operator (every subcommand works)\n operator --resume resume the last session in this directory\n operator update update to the latest release\n operator update --next install the next prerelease (built from develop); --latest goes back\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 gateway the local model runtime: start | stop | status | health | logs\n operator toolchain the llama-server store: status | verify | install | activate | rollback | migrate | which\n operator run <task>|- run one task headless (--model, --activate, --permissions, --output json, --cwd)\n operator selfimprove backfill [--since YYYY-MM-DD] [--dry-run]\n turn looped turns and mentor pairs into lessons\n operator --version print the version\n");
161
163
  process.exit(0);
162
164
  }
163
165
  // `operator selfimprove backfill …` — offline: folds the flywheel's looped turns and the mentor pairs into the global
@@ -621,7 +623,7 @@ const HELP = [
621
623
  " /plan plan mode: read-only research + propose a plan (/plan again to execute)",
622
624
  " /mode [auto|manual|plan|gated] set operating mode (autonomous · manual · plan · gated); Shift+Tab cycles the first three",
623
625
  " /voice [on|off|status] voice mode: ctrl+t to talk (again to send), the answer is spoken back, esc stops it",
624
- " /think extended reasoning: Operator thinks before answering (/think again = off)",
626
+ " /think [level] extended reasoning: Operator thinks before answering (/think again = off); a level sets this model's reasoning effort",
625
627
  " /ultrathink deep, exhaustive reasoning for hard problems (/ultrathink again = off)",
626
628
  " /compact force-compact the conversation now",
627
629
  " /remember <note> store a note to recall in future sessions",
@@ -832,6 +834,9 @@ function Root() {
832
834
  // Session reads them on every registry access (dynamicModels), so a fetched row is pickable the moment it lands.
833
835
  const freeRowsRef = useRef([]);
834
836
  const freeStaleRef = useRef(false); // served from the disk cache after a failed read → the rows say " · cached"
837
+ // The gateway's short model list (router/model-list.ts): the last one read until /model reads it again.
838
+ const listRef = useRef(null);
839
+ listRef.current ??= cachedModelList();
835
840
  const sessionRef = useRef(null); // lazy — never reconstruct on re-render
836
841
  // MCP opts the foreground session into the fleet MCP tool surface (off by default: local tools
837
842
  // only, no network fan-out at session start). Background agents stay local-only + lean.
@@ -839,6 +844,8 @@ function Root() {
839
844
  sessionRef.current = new Session({
840
845
  systemPrompt: SYSTEM_PROMPT,
841
846
  thinkMode, // start in the SAME mode the badge shows (settings.ui.reasoning, default "think") — it was only ever the badge that defaulted on
847
+ reasoningEffort: settings.ui?.effort,
848
+ voice: settings.services?.voice,
842
849
  router: buildRouter(),
843
850
  applyActiveModel: true, // the persisted /model choice still applies with the shell's chain injected
844
851
  memory: buildMemory(settings.memory), // provider composite when configured; bare store (byte-identical) otherwise
@@ -852,11 +859,13 @@ function Root() {
852
859
  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)
853
860
  compactionThreshold: compactionThreshold(settings), // settings.compaction.threshold / KODE_COMPACTION_THRESHOLD; undefined → derived from the served window
854
861
  compactionCeilingTokens: compactionCeilingTokens(settings, "interactive"), // the owner's compaction.ceilingTokens / env, else no ceiling. Headless autonomy reads its own (session-factory.ts)
862
+ compactionSpeedTargetTokens: compactionSpeedTargetTokens(settings), // compaction.speedTargetTokens: where that compaction lands
863
+ compactionSummaryModel: compactionSummaryModel(settings), // compaction.summaryModel: the background rolling pass only
855
864
  compactionMinDecodeTps: compactionMinDecodeTps(settings, "interactive"), // compaction.minDecodeTps / KODE_COMPACT_MIN_TPS: compact when sustained decode falls under it; undefined → off
856
865
  temperature: settings.temperature,
857
866
  recall: settings.memory.recall,
858
867
  models: MERGED_MODELS, // discovered fleet nodes + settings.models overrides (built-ins in router/models.ts)
859
- dynamicModels: () => freeRowsRef.current, // the free vendor rows /model fetched this session
868
+ dynamicModels: () => [...listedProfiles(listRef.current ?? [], settings.models), ...freeRowsRef.current], // the gateway's list, and the free vendor rows /model fetched this session
860
869
  moa: settings.moa,
861
870
  classifier: { mode: resolveMode(settings), endpoint: classifierConfig(settings).endpoint }, // the turn router (classifier/route.ts) // MOA proposers/aggregator config (MOA-DESIGN.md); absent = "/model moa" explains
862
871
  fastStart: settings.fastStart, // fast-model-vs-real-turn race (feature: fastStart, default OFF)
@@ -989,6 +998,8 @@ function Root() {
989
998
  toolAllow: SUBAGENT_ROLES[role]?.tools,
990
999
  toolDeny: SUBAGENT_TOOL_DENY,
991
1000
  models: settings.models,
1001
+ reasoningEffort: settings.ui?.effort,
1002
+ voice: settings.services?.voice,
992
1003
  unattended: true, // nobody watches a background agent turn by turn: a real loop hard-stops (10/31: 54 rounds of warnings)
993
1004
  router: new AuroraRouter(buildEndpointChain(settings)), // same multi-tier self-heal chain as the foreground
994
1005
  memory: buildMemory(settings.memory), // sub-agents share the same provider-layer memory surface
@@ -1284,6 +1295,9 @@ function Root() {
1284
1295
  const sxUp = await probeSearxng().catch(() => false);
1285
1296
  push({ kind: "message", message: { id: nextId(), role: "system", content: `services: ${line} · searxng ${sxUp ? "✓" : "lazy"}` } });
1286
1297
  }
1298
+ const earlier = handoffNotice();
1299
+ if (earlier)
1300
+ push({ kind: "message", message: { id: nextId(), role: "system", content: earlier } });
1287
1301
  // Remote-control auto-start (rcAutostart: explicit remote.autostart / KODE_RC_AUTOSTART wins, else
1288
1302
  // ON for admin/VIP tier only — feature-flagged rollout). When enabled and this box is signed in, bring
1289
1303
  // up an RC host on boot by driving the EXACT /remotecontrol path
@@ -1530,6 +1544,7 @@ function Root() {
1530
1544
  setPhase("sent");
1531
1545
  },
1532
1546
  onSpeedCompaction: (e) => sys(speedCompactionLine(e)),
1547
+ onSpeedTargetMissed: (e) => sys(speedTargetMissedLine(e)),
1533
1548
  onCompactionStart: ({ before }) => {
1534
1549
  compactRef.current = { before, startedAt: Date.now(), ring: [], wrote: 0 };
1535
1550
  setStepLabel("compacting context");
@@ -2273,8 +2288,8 @@ function Root() {
2273
2288
  const pickerSeqRef = useRef(0);
2274
2289
  const openPicker = useCallback((question, rows, entries, onAnswer) => {
2275
2290
  const seq = ++pickerSeqRef.current;
2276
- const pending = (shown, from) => ({
2277
- question,
2291
+ const pending = (shown, from, asked = question) => ({
2292
+ question: asked,
2278
2293
  options: shown,
2279
2294
  key: seq, // a redraw of this open keeps the owner's place (QuestionPrompt.redrawState)
2280
2295
  resolve: (answer, index) => {
@@ -2286,9 +2301,30 @@ function Root() {
2286
2301
  },
2287
2302
  });
2288
2303
  setModelPicker(pending(rows, entries));
2289
- return (shown, from) => { if (pickerSeqRef.current === seq)
2290
- setModelPicker(pending(shown, from)); };
2304
+ return (shown, from, asked) => { if (pickerSeqRef.current === seq)
2305
+ setModelPicker(pending(shown, from, asked)); };
2291
2306
  }, []);
2307
+ // /model on a row with `activation`: the flow draws in the same picker slot.
2308
+ const activationRef = useRef(null);
2309
+ activationRef.current ??= createActivationFlow({
2310
+ sys: (line) => sys(line),
2311
+ current: () => session.currentModel(),
2312
+ idle: () => statusRef.current === "idle",
2313
+ open: (question, rows, entries, onAnswer) => {
2314
+ const redraw = openPicker(question, rows, entries, (a) => { if ("entry" in a)
2315
+ onAnswer(a.entry); });
2316
+ const seq = pickerSeqRef.current;
2317
+ const isOpen = () => pickerSeqRef.current === seq;
2318
+ return {
2319
+ update: (q, r, e) => redraw(r, e, q),
2320
+ isOpen,
2321
+ close: () => { if (isOpen()) {
2322
+ pickerSeqRef.current++;
2323
+ setModelPicker(null);
2324
+ } },
2325
+ };
2326
+ },
2327
+ });
2292
2328
  // "Context for this session": bare /context, and the step after a /model pick whose window beats the smallest pin.
2293
2329
  const openContextPicker = useCallback(() => {
2294
2330
  const { rows, pins } = contextPickerView(session.contextPin(), session.servedContext());
@@ -2323,6 +2359,13 @@ function Root() {
2323
2359
  freeStaleRef.current = stale;
2324
2360
  return changed;
2325
2361
  }, []);
2362
+ const refreshModelList = useCallback(async () => {
2363
+ const list = await fetchModelList({ cloud: settings.endpoints.cloudFailover !== false });
2364
+ if (!list || JSON.stringify(list) === JSON.stringify(listRef.current))
2365
+ return false;
2366
+ listRef.current = list;
2367
+ return true;
2368
+ }, []);
2326
2369
  const handleSlash = useCallback(async (cmd) => {
2327
2370
  const [name, ...rest] = cmd.slice(1).split(/\s+/);
2328
2371
  const arg = rest.join(" ").trim();
@@ -2394,8 +2437,14 @@ function Root() {
2394
2437
  sys(note); });
2395
2438
  return chosen;
2396
2439
  };
2440
+ // A row with an activation command is switched to only once that command says the model is served.
2441
+ const activate = (id, then) => {
2442
+ const target = looksLikeSecret(id) ? undefined : s.resolveSelection(id);
2443
+ return !!target && activationRef.current.pick(target.id, then);
2444
+ };
2397
2445
  if (arg) {
2398
- apply(arg);
2446
+ if (!activate(arg, () => { apply(arg); }))
2447
+ apply(arg);
2399
2448
  break;
2400
2449
  }
2401
2450
  // Each account is looked up at most once for this open, and only when a row needs it (a keychain miss spawns
@@ -2443,8 +2492,10 @@ function Root() {
2443
2492
  const active = s.currentModel();
2444
2493
  // Two screens (0.1.361): the main rows + "More models…", which opens every other row and the connect action.
2445
2494
  const view = (more) => {
2446
- const o = { active, servedCtx: s.servedContext(), staleFree: freeStaleRef.current, cost: (m) => costOf(m.id), cols: termCols() };
2447
- return more ? modelPickerView(s.modelRegistry().filter((m) => !isMainModel(m)), o) : mainPickerView(s.modelRegistry(), o);
2495
+ const listed = listRef.current ?? [];
2496
+ const main = mainIds(s.modelRegistry(), listed.map((m) => m.id));
2497
+ const o = { active, main, down: new Set(listed.filter((m) => m.down).map((m) => m.id)), servedCtx: s.servedContext(), staleFree: freeStaleRef.current, cost: (m) => costOf(m.id), cols: termCols() };
2498
+ return more ? modelPickerView(s.modelRegistry().filter((m) => !isMainModel(m, main)), o) : mainPickerView(s.modelRegistry(), o);
2448
2499
  };
2449
2500
  let cat;
2450
2501
  let refresh = () => { };
@@ -2453,7 +2504,9 @@ function Root() {
2453
2504
  let onScreen = first.rows;
2454
2505
  const redraw = openPicker(more ? "More models" : "Select a model", first.rows, first.entries, (a) => {
2455
2506
  if ("typed" in a) {
2456
- apply(a.typed);
2507
+ const typed = a.typed;
2508
+ if (!activate(typed, () => { apply(typed); }))
2509
+ apply(typed);
2457
2510
  return;
2458
2511
  } // the typed-id escape: an explicit id skips the context step
2459
2512
  if (a.entry.kind === "more") {
@@ -2465,8 +2518,10 @@ function Root() {
2465
2518
  return;
2466
2519
  }
2467
2520
  const id = a.entry.profile.id;
2468
- const go = () => { const chosen = apply(id); if (chosen && wantsContextStep(chosen, s.servedContext()))
2521
+ const go = (watched = true) => { const chosen = apply(id); if (watched && chosen && wantsContextStep(chosen, s.servedContext()))
2469
2522
  openContextPicker(); };
2523
+ if (activate(id, go))
2524
+ return;
2470
2525
  // A pick that costs a long re-read asks once, with the price: switch now, compact here first, or stay.
2471
2526
  const cost = costOf(id);
2472
2527
  if (!cost || !wantsRereadConfirm(cost)) {
@@ -2485,7 +2540,7 @@ function Root() {
2485
2540
  if (c.entry === "switch")
2486
2541
  go();
2487
2542
  else if (c.entry === "compact") {
2488
- flow.afterCompaction(go);
2543
+ flow.afterCompaction(() => go());
2489
2544
  void slashRef.current("/compact");
2490
2545
  } // compacts on the cache-warm model, then switches — before anything waiting can start a turn
2491
2546
  else
@@ -2512,6 +2567,10 @@ function Root() {
2512
2567
  } });
2513
2568
  void refreshFreeRows(isConnected).then((changed) => { if (changed)
2514
2569
  refresh(); });
2570
+ void refreshModelList().then((changed) => { if (changed) {
2571
+ refresh();
2572
+ remoteRef.current?.setCapabilities(buildCapabilities());
2573
+ } });
2515
2574
  break;
2516
2575
  }
2517
2576
  case "context":
@@ -3108,7 +3167,22 @@ function Root() {
3108
3167
  break;
3109
3168
  }
3110
3169
  case "think": {
3111
- const on = s.currentThinkMode() !== "think";
3170
+ const word = arg.trim().toLowerCase();
3171
+ if (word && word !== "on" && word !== "off") {
3172
+ const level = parseEffort(word);
3173
+ if (!level) {
3174
+ sys(`reasoning effort is ${s.currentReasoningEffort() ?? "the model's default"} — usage: /think ${EFFORT_LEVELS.join("|")}|default`);
3175
+ break;
3176
+ }
3177
+ const effort = s.setReasoningEffort(level);
3178
+ try {
3179
+ saveSettings({ ui: { ...loadSettings().ui, effort } });
3180
+ }
3181
+ catch { /* the session keeps it */ }
3182
+ sys(`reasoning effort for ${s.currentModel()}: ${s.currentReasoningEffort() ?? "the model's default"}. It applies from the next request; a model that writes it into its prompt re-reads the conversation once.`);
3183
+ break;
3184
+ }
3185
+ const on = word ? word === "on" : s.currentThinkMode() !== "think";
3112
3186
  s.setThinkMode(on ? "think" : "off");
3113
3187
  setThinkMode(on ? "think" : "off");
3114
3188
  sys((on ? "✲ think ON — Operator reasons (shown dimmed) before answering. /think again to turn off."
@@ -3538,7 +3612,7 @@ function Root() {
3538
3612
  submitRef.current(arg);
3539
3613
  }
3540
3614
  }
3541
- }, [exit, sys, bg, authUser, approval, settleApproval, settleQuestion, applyMode, applyContext, openPicker, openContextPicker, refreshFreeRows, remoteCommand, remotePrompt]);
3615
+ }, [exit, sys, bg, authUser, approval, settleApproval, settleQuestion, applyMode, applyContext, openPicker, openContextPicker, refreshFreeRows, refreshModelList, remoteCommand, remotePrompt]);
3542
3616
  const onSubmit = useCallback((text) => {
3543
3617
  // A submit that arrives while a turn runs (a remote follower's prompt or command, a wake) takes the same path the
3544
3618
  // keyboard does: a command by its mid-turn class, text as a steer — a second Session.send would throw mid-turn.
@@ -77,6 +77,13 @@ export const FEATURES = {
77
77
  default: false,
78
78
  description: "Add craft_create (a second way to make an artifact; artifact_create is the stock one). The artifact library tools are always on",
79
79
  },
80
+ /** micro assist (tools/micro-assist.ts): a large un-ranged file_read or long command output comes back as the `micro`
81
+ * MCP server's ranked verbatim extract plus a spill path, and Scribe is searched once for the first task. Default OFF
82
+ * until the reader passes its recall gate. Needs MCP on with the `micro` server; without it nothing changes. */
83
+ microAssist: {
84
+ default: false,
85
+ description: "Large reads and long output come back as a micro extract plus a spill path; one Scribe search for the first task",
86
+ },
80
87
  };
81
88
  /** Env var that overrides one feature: camelCase → UPPER_SNAKE, e.g. classifierGate → KODE_FEATURE_CLASSIFIER_GATE. */
82
89
  export function featureEnvName(name) {
@@ -3,6 +3,7 @@
3
3
  // picks up the SAME project context + handoff the TUI does, without importing cli.tsx (which mounts
4
4
  // Ink and refuses a non-TTY). Pure, best-effort, never throws — a missing file is normal.
5
5
  import { readFileSync, appendFileSync, mkdirSync, existsSync, writeFileSync, renameSync, realpathSync, statSync, chmodSync } from "node:fs";
6
+ import { execFileSync } from "node:child_process";
6
7
  import { join, dirname } from "node:path";
7
8
  import { operatorPath, globalMemoriesPath } from "./home.js";
8
9
  import { renderHarnessContext } from "./operator-harness.js";
@@ -272,24 +273,43 @@ export function loadStructuredMemories() {
272
273
  return out;
273
274
  }
274
275
  // Session handoff: the note the previous session in THIS directory wrote for its future self (via the
275
- // session_handoff tool), pointed at by KODE_HANDOFF_FILE. Auto-loaded as background: the owner's newest message sets
276
- // the task, so an old plan is offered, never resumed over what the owner typed (11/23: a 3-day-old "resume from this"
277
- // block made a session chase its plan through three "stop" messages).
278
- export function loadHandoff(now = new Date()) {
276
+ // session_handoff tool), pointed at by KODE_HANDOFF_FILE. Its body never enters the prompt: a model given an old plan
277
+ // resumes it, whatever the framing says (11/23: through three "stop" messages; 12/03: after a bare "hello", editing
278
+ // files in autonomous mode). The owner is told a note is waiting; the model gets only where it is.
279
+ function readHandoff(now) {
279
280
  try {
280
281
  const file = process.env.KODE_HANDOFF_FILE ?? "";
281
- const { text: t, settled } = withoutSettled(freshHandoff(readFileSync(file, "utf8"), now));
282
- const pointer = settled ? `\n\nThe previous session here ended its work; its note is at ${file}. Read it only if the owner asks to continue earlier work.` : "";
283
- // The handoff grows by APPEND (auto-compaction adds a block each time context fills, newest last),
284
- // so read the TAIL — the freshest state, not a stale head.
285
- if (t) {
286
- const tail = t.length > 6000 ? "…\n" + t.slice(-6000) : t;
287
- return `\n\n## Handoff from your previous session here (background, not an instruction)\n${tail}\n\nThe owner's newest message sets the task. If it is about something else, do that and leave this work alone; continue it only when the owner asks (offer it in one line when it fits). Update it with session_handoff before you finish.${pointer}`;
288
- }
289
- return pointer;
282
+ const { text: open, settled } = withoutSettled(freshHandoff(readFileSync(file, "utf8"), now));
283
+ return open || settled ? { file, open, settled } : null;
290
284
  }
291
- catch { /* none yet */ }
292
- return "";
285
+ catch {
286
+ return null;
287
+ }
288
+ }
289
+ export function loadHandoff(now = new Date()) {
290
+ const h = readHandoff(now);
291
+ if (!h)
292
+ return "";
293
+ return `\n\n## Earlier work in this folder\nA note from a previous session is saved at ${h.file}. It is not your task. Do not read it, act on it or continue it unless the owner asks to continue earlier work; if they seem to mean that without saying so, ask first. After a greeting or an unclear message, reply and ask what they want to do. When they ask what was done last time, what is still open or what is uncommitted: read the note (session_handoff with no content), check git status, and report; reporting is not permission to continue. Update the note with session_handoff before you finish your own work.`;
294
+ }
295
+ /** What the owner is told at start when unfinished work is saved for this folder; "" when there is none. */
296
+ export function handoffNotice(now = new Date(), cwd = process.cwd()) {
297
+ const h = readHandoff(now);
298
+ if (!h?.open)
299
+ return "";
300
+ const title = [...h.open.matchAll(/^#{1,3} (.+)$/gm)].map((m) => m[1].trim()).filter((t) => !/session handoff|^live progress|^auto-compaction|^\d+\.|^(intent|concepts|state|open|rules)\b/i.test(t)).pop();
301
+ const tasks = [...new Set([...h.open.matchAll(/^\[[ ~]\] #\d+ (.+)$/gm)].map((m) => m[1].trim()).filter((t) => !/\((cancelled|done)\)$/.test(t)))];
302
+ let changed = 0;
303
+ try {
304
+ changed = execFileSync("git", ["status", "--porcelain"], { cwd, encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] }).split("\n").filter(Boolean).length;
305
+ }
306
+ catch { /* not a repository */ }
307
+ return [
308
+ `last session here${title ? `: “${title.slice(0, 80)}”` : " left a note"}`,
309
+ ...(tasks.length ? [`open tasks (${tasks.length}): ${tasks.slice(-3).map((t) => t.slice(0, 60)).join(" · ")}`] : []),
310
+ ...(changed ? [`uncommitted: ${changed} file${changed === 1 ? "" : "s"} in this repository`] : []),
311
+ "on hold until you ask — “review last session” for a recap, “continue earlier work” to resume",
312
+ ].join("\n");
293
313
  }
294
314
  // The base Operator persona (vendor-neutral, AXE-branded), independent of the TUI's embodiment guide.
295
315
  // composeSystemPrompt (below) builds the full system prompt from settings.systemPrompt ?? this, and both
@@ -175,6 +175,13 @@ function readSettingsFile(path) {
175
175
  return { kind: "broken", reason: `the top level is ${shapeOf(value)}, not an object` };
176
176
  return { kind: "ok", value, text };
177
177
  }
178
+ /** The settings.models rows exactly as the owner's file has them — no built-ins, env, managed policy or gateway rows.
179
+ * An unreadable file has none. */
180
+ export function ownerModelEntries() {
181
+ const read = readSettingsFile(settingsPath());
182
+ const models = read.kind === "ok" ? read.value.models : undefined;
183
+ return Array.isArray(models) ? models.filter(isPlainObject) : [];
184
+ }
178
185
  const lastGoodPath = (path) => `${path}.last-good`;
179
186
  /** Write `text` to `path` atomically: a temp file in the same directory, fsync, rename. A symlinked settings file
180
187
  * keeps its link: the write lands on the target. */
@@ -410,6 +417,16 @@ export function compactionMinDecodeTps(s, mode = "interactive") {
410
417
  const v = mode === "autonomy" ? s.compaction?.autonomyMinDecodeTps : s.compaction?.minDecodeTps;
411
418
  return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : undefined;
412
419
  }
420
+ /** The request size a speed-triggered compaction must land at or under (`compaction.speedTargetTokens`), or undefined. */
421
+ export function compactionSpeedTargetTokens(s) {
422
+ const v = s.compaction?.speedTargetTokens;
423
+ return typeof v === "number" && Number.isFinite(v) && v >= 8000 ? Math.floor(v) : undefined;
424
+ }
425
+ /** The /model id the background rolling summary runs on (`compaction.summaryModel`), or undefined (the live endpoint). */
426
+ export function compactionSummaryModel(s) {
427
+ const v = s.compaction?.summaryModel;
428
+ return typeof v === "string" && v.trim() ? v.trim() : undefined;
429
+ }
413
430
  /** The per-turn WALL-CLOCK budget (ms) to hand runTurn — the only bound on TIME, the brake on hour-long turns.
414
431
  * settings.autonomy.maxTurnWallClockSec, env KODE_TURN_MAX_WALLCLOCK_SEC wins; 0/unset ⇒ undefined (no cap).
415
432
  * Resolved here so headless/autonomy (and any surface that opts in) read it identically. */
@@ -1280,6 +1280,7 @@ export async function runTurn(userInput, conversation, opts) {
1280
1280
  loopbackAuth: endpoint.loopbackAuth,
1281
1281
  transport: endpoint.transport,
1282
1282
  chatPath: endpoint.chatPath,
1283
+ ...endpoint.reasoning,
1283
1284
  maxTokens,
1284
1285
  // Empty-retry perturbation: a greedy (temp 0) empty is deterministic, so the retry must change the
1285
1286
  // sampling to escape it. One-shot — consumed right after this call so the normal path stays greedy.
@@ -1527,6 +1528,7 @@ export async function runTurn(userInput, conversation, opts) {
1527
1528
  loopbackAuth: endpoint.loopbackAuth,
1528
1529
  transport: endpoint.transport,
1529
1530
  chatPath: endpoint.chatPath,
1531
+ ...endpoint.reasoning,
1530
1532
  maxTokens: clampMaxTokens(retryMessages, compactionOptsFor(endpoint), opts.maxTokens ?? 8192),
1531
1533
  temperature: opts.temperature,
1532
1534
  tools: opts.toolSchemas,
@@ -1548,6 +1550,7 @@ export async function runTurn(userInput, conversation, opts) {
1548
1550
  // paths — a cut-off tool call and a cut-off text answer both carry stopReason "length".
1549
1551
  if (response.stopReason === "length")
1550
1552
  truncatedThisTurn = true;
1553
+ conversation.pendingReasoning = endpoint.reasoning?.preserveThinking ? response.reasoningContent : undefined;
1551
1554
  // LOCAL truncated-tool-call recovery (_ai-docs 2026-10-19): a settled tool-calling round can carry a
1552
1555
  // call whose arguments were cut off mid-JSON — stopReason is undefined here (a tool-calling turn is
1553
1556
  // legitimately terminal), so the length latch above never saw it. The OLD engine dispatched the