@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.
@@ -0,0 +1,79 @@
1
+ // The short model list the gateway publishes on its /v1/models rows (portal registry `picker`). Ids, labels, order and
2
+ // who sees a row are the gateway's data, so a row is added, renamed or removed there with no change here. A gateway that
3
+ // cannot be read leaves the last list read; with none, /model keeps its built-in rows. Never throws.
4
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { dirname } from "node:path";
6
+ import { operatorPath } from "../config/home.js";
7
+ import { authHeaders, getOperatorToken } from "../engine/aurora.js";
8
+ import { catalogRows, DEFAULT_FREE_CTX } from "./free-models.js";
9
+ import { BUILTIN_MODELS, GATEWAY_BASE, LOCAL_GATEWAY_BASE, MODEL_ALIASES, RETIRED_MODEL_IDS } from "./models.js";
10
+ const ID = /^[a-z0-9][a-z0-9._:/-]{0,127}$/;
11
+ const defaultCache = () => operatorPath("model-list.json");
12
+ /** Pure: the listed rows of a catalog, in list order. A row with an unusable id or label is dropped. */
13
+ export function pickList(rows) {
14
+ const out = [];
15
+ for (const row of rows) {
16
+ const r = row;
17
+ if (r?.pickable !== true || typeof r.id !== "string" || !ID.test(r.id) || RETIRED_MODEL_IDS.has(r.id) || Object.hasOwn(MODEL_ALIASES, r.id))
18
+ continue;
19
+ if (typeof r.label !== "string" || !r.label.trim() || r.label.length > 80 || /[\u0000-\u001f\u007f-\u009f]/.test(r.label) || out.some((m) => m.id === r.id))
20
+ continue;
21
+ const ctx = typeof r.context_length === "number" && r.context_length > 0 ? r.context_length : undefined;
22
+ out.push({ id: r.id, label: r.label.trim(), order: typeof r.order === "number" ? r.order : out.length + 1, ...(ctx ? { ctx } : {}), paid: r.billing === "paid", thirdParty: r.hosting === "third_party", down: r.available === false });
23
+ }
24
+ return out.sort((a, b) => a.order - b.order);
25
+ }
26
+ /** The listed rows as profiles. A row settings.models names is left to settings; a built-in gateway row takes the list's
27
+ * label; a built-in on any other host is never re-pointed or renamed; an unknown id becomes a gateway row with no tier,
28
+ * so nothing picks it but the owner. Hosts are always ours: the list names models, never addresses. */
29
+ export function listedProfiles(list, own = []) {
30
+ return list.flatMap((r) => {
31
+ const built = BUILTIN_MODELS.find((m) => m.id === r.id);
32
+ if (own.some((m) => m.id === r.id) || (built && built.endpoint !== LOCAL_GATEWAY_BASE))
33
+ return [];
34
+ const base = built ?? { id: r.id, label: r.label, kind: "single", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: [r.id, r.id], model: r.id, ctx: DEFAULT_FREE_CTX };
35
+ return [{
36
+ ...base, label: r.label, params: undefined, hidden: false, tier: built && !built.hidden ? built.tier : undefined,
37
+ box: [r.thirdParty ? "third party" : "gateway", ...(r.paid ? ["paid"] : [])].join(", "),
38
+ desc: r.thirdParty ? "served by a third party through our gateway" : "served by our gateway",
39
+ ...(r.ctx ? { ctx: r.ctx } : {}),
40
+ ...(r.thirdParty ? { transport: "openai", maxOutput: 32768 } : {}),
41
+ }];
42
+ });
43
+ }
44
+ /** The last list read, so a saved pick still resolves at the next start. Availability is never remembered. */
45
+ export function cachedModelList(path = defaultCache()) {
46
+ try {
47
+ const rows = catalogRows(JSON.parse(readFileSync(path, "utf8")));
48
+ return rows ? pickList(rows) : [];
49
+ }
50
+ catch {
51
+ return [];
52
+ }
53
+ }
54
+ function remember(list, path) {
55
+ const data = list.map((m) => ({ pickable: true, id: m.id, label: m.label, order: m.order, context_length: m.ctx, billing: m.paid ? "paid" : undefined, hosting: m.thirdParty ? "third_party" : undefined }));
56
+ try {
57
+ mkdirSync(dirname(path), { recursive: true });
58
+ writeFileSync(path, JSON.stringify({ data }), { mode: 0o600 });
59
+ }
60
+ catch { /* an unwritable home costs only the restart */ }
61
+ }
62
+ /** The list from the local gateway, else (signed in) the public one: the first that answers decides, and an answer with
63
+ * no listed row means there is no list. undefined: nothing could be read. */
64
+ export async function fetchModelList(opts = {}) {
65
+ const f = opts.fetchImpl ?? fetch;
66
+ for (const base of [LOCAL_GATEWAY_BASE, ...(opts.cloud !== false && getOperatorToken() ? [GATEWAY_BASE] : [])]) {
67
+ try {
68
+ const res = await f(`${base}/models`, { headers: { Accept: "application/json", ...authHeaders({ base, model: "" }) }, signal: AbortSignal.timeout(opts.timeoutMs ?? 4000) });
69
+ const rows = res.ok ? catalogRows(await res.json()) : undefined;
70
+ if (!rows)
71
+ continue;
72
+ const list = pickList(rows);
73
+ remember(list, opts.cachePath ?? defaultCache());
74
+ return list;
75
+ }
76
+ catch { /* offline, timeout or junk: the next gateway */ }
77
+ }
78
+ return undefined;
79
+ }
@@ -13,6 +13,17 @@
13
13
  import { INFERENCE_API_HOST, LEGACY_API_HOST, PRODUCT_API_HOST } from "../config/product-hosts.js"; // no imports of its own — no cycle
14
14
  /** Fallback walk order, strongest → cheapest. */
15
15
  export const TIER_LADDER = ["power_turbo", "power", "economy", "lite", "free"];
16
+ export const EFFORT_LEVELS = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
17
+ /** A `/think` argument as a reasoning effort ("default" clears the override), or undefined for anything else. */
18
+ export function parseEffort(arg) {
19
+ const v = arg.trim().toLowerCase();
20
+ return v === "default" || EFFORT_LEVELS.includes(v) ? v : undefined;
21
+ }
22
+ /** The effort a model runs at: the saved `/think <level>` override, else its profile's. */
23
+ export function effortFor(overrides, profile) {
24
+ const own = overrides[profile.id];
25
+ return own && own !== "default" ? own : profile.reasoningEffort;
26
+ }
16
27
  export function isRetired(p) {
17
28
  return p?.status === "retired";
18
29
  }
@@ -65,7 +76,7 @@ export const ANTHROPIC_MAX_OUTPUT = 128_000;
65
76
  export const BUILTIN_MODELS = [
66
77
  // ── main: the /model rows, in this order (ui/modelPicker.ts MAIN_MODEL_IDS; operator-dense hidden 11/30) ─────────────────
67
78
  // Router routes of the same name, gateway-first like every gateway row. `ctx` is the window the route serves.
68
- { id: "operator-flash", tier: "power", label: "Operator-Flash", params: "125B-A6B", box: "gateway", kind: "single", desc: "the default model: a fast MoE with n-gram speculation", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["operator-flash", "operator-flash"], model: "operator-flash", ctx: 131072 },
79
+ { id: "operator-flash", tier: "power", label: "Operator-Flash", params: "125B-A6B", box: "gateway", kind: "single", desc: "the default model: a fast MoE with n-gram speculation", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["operator-flash", "operator-flash"], model: "operator-flash", ctx: 131072, vision: true },
69
80
  { id: "kimi-linear-48b", tier: "power", label: "Kimi-Linear", params: "48B-A3B", box: "gateway", kind: "single", desc: "long-context MoE", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["kimi-linear-48b", "kimi-linear-48b"], model: "kimi-linear-48b", ctx: 262144 },
70
81
  { id: "operator-dense", tier: "power", label: "Operator-Dense", params: "27B", box: "gateway", kind: "single", desc: "dense model with n-gram and MTP speculation; loads on demand", endpoint: LOCAL_GATEWAY_BASE, endpoints: [LOCAL_GATEWAY_BASE, GATEWAY_BASE], endpointModels: ["operator-dense", "operator-dense"], model: "operator-dense", ctx: 131072, hidden: true },
71
82
  // ── retired ─────────────────────────────────────────────────────────────────────────────────────────────
@@ -1,14 +1,3 @@
1
- // Endpoint routing & self-heal — SPEC §4. Two Aurora endpoints: Air (fast, small ctx) and
2
- // 1M (slow, huge ctx). Interface consumed by the engine (Karpathy's lane):
3
- // base, model -> current endpoint's connection info
4
- // ctxLimit() -> current endpoint's context window
5
- // routeBySize(n) -> pick the smallest endpoint that fits n tokens, escalating Air->1M as
6
- // the conversation grows; NEVER moves to a smaller endpoint on its own
7
- // escalate() -> jump straight to the largest endpoint (used on repeated 400s with no
8
- // room left to compact)
9
- // failover() -> hop to a healthy endpoint after a busy/5xx response; prefers a smaller
10
- // endpoint over the one that just failed, per SPEC §4's "self-heal"
11
- // KODE_NO_ROUTER=1 pins the router to whatever endpoint is current and disables all movement.
12
1
  import { LOCAL_GATEWAY_BASE } from "./models.js";
13
2
  // One endpoint by default: the local router's `main` (buildEndpointChain's built-in primary). The router still handles
14
3
  // N endpoints generically.
package/dist/session.js CHANGED
@@ -6,16 +6,19 @@ import { recordTruncation } from "./observability/blackbox.js";
6
6
  import { Conversation, placeSessionContext, SESSION_CONTEXT_OPEN, SESSION_CONTEXT_CLOSE, SESSION_CONTEXT_REQUEST_LINE } from "./engine/messages.js";
7
7
  import { scratchDirFor } from "./config/scratch.js";
8
8
  import { homedir } from "node:os";
9
- import { detectVision, markVisionRejected } from "./engine/native-vision.js";
10
- import { extractImagePaths } from "./engine/native-vision-node.js";
9
+ import { detectVision, markVisionRejected, visionRejected } from "./engine/native-vision.js";
10
+ import { voiceConfig, withTranscripts } from "./products/voice.js";
11
+ import { readFileSync } from "node:fs";
12
+ import { extractAudioPaths, extractImagePaths, extractVideoPaths } from "./engine/native-vision-node.js";
11
13
  import { planFanOut } from "./engine/fanout.js";
12
14
  import { withCodeActDelegateSchema } from "./moa/codeact-lane.js";
13
15
  import { codeActEnabled } from "./moa/codeact.js";
16
+ import { effortFor } from "./router/models.js";
14
17
  import { chat, health, reachable, gateKey, isRemoteBase, shipsLlamaCacheKnobs, requiresOperatorToken, operatorTrustedUrl } from "./engine/aurora.js";
15
18
  import { claimSlot, releaseSlot } from "./engine/kv-slot.js";
16
19
  import { randomUUID } from "node:crypto";
17
- import { recordDecodeSample, speedCompactionDue } from "./engine/speed-compaction.js";
18
- import { compact, compactionSplit, fitToWindow, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent, renderAnchorIndex, verbatimUserTail } from "./engine/compaction.js";
20
+ import { recordDecodeSample, speedCompactionDue, SPEED_REARM_TOKENS } from "./engine/speed-compaction.js";
21
+ import { compact, compactionSplit, fitToWindow, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent, renderAnchorIndex, verbatimUserTail, archiveEvicted, defaultThreshold, fixedRequestTokens } from "./engine/compaction.js";
19
22
  import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
20
23
  import { spillToolOutput } from "./tools/tool-output-spill.js"; // GW-10-COMPLETE: node-side spill sink
21
24
  import { engineRouter } from "./engine/router-adapter.js";
@@ -35,7 +38,7 @@ import { routeShadowTurn, shadowPrompt } from "./moa/shadow.js"; // MOA phase-0
35
38
  import { AuroraRouter } from "./router/router.js";
36
39
  import { operatorAgentPersona } from "./config/operator-harness.js";
37
40
  import { progressDeadline, summaryCeilingMs, DeadlineError } from "./engine/progress-deadline.js";
38
- import { modelRegistry, findModel, fallbackProfile, selectModel, visibleModels, endpointBase, profileEndpoint, fmtCtx, MIN_CONTEXT_PIN, AGENT_CTX_FLOOR, AGENT_CTX_TARGET, CHAIN_MODEL_ID, LEAN_HARNESS_CTX, resolveModel } from "./router/models.js";
41
+ import { modelRegistry, findModel, fallbackProfile, selectModel, visibleModels, endpointBase, profileEndpoint, fmtCtx, MIN_CONTEXT_PIN, AGENT_CTX_FLOOR, AGENT_CTX_TARGET, CHAIN_MODEL_ID, LEAN_HARNESS_CTX, resolveModel, isRetired } from "./router/models.js";
39
42
  import { probeServed, usableCtx } from "./router/discovery.js";
40
43
  import { FAST_START_INSTRUCTION, parseFastStartReply } from "./engine/fast-start.js";
41
44
  import { askFrontDoor, recentTurns } from "./engine/front-door.js";
@@ -44,6 +47,7 @@ import { Executor } from "./tools/executor.js";
44
47
  import { autoDeliverReport, autoDeliverFailure, wakeRoot } from "./bus/inbox.js";
45
48
  import { toSchemas, registry, disposeShellSessionKey, requestShellDetach, cloudAgentToolsFor, mdocToolsFor, craftToolsFor, renderActiveTasks, getAgentTasks, taskPlanRevision, openTaskCount } from "./tools/registry.js";
46
49
  import { isFeatureEnabled } from "./config/features.js";
50
+ import { createMicroAssist } from "./tools/micro-assist.js";
47
51
  import { MemoryStore } from "./memory/index.js";
48
52
  import { McpHub, withMcp } from "./mcp/index.js";
49
53
  import { deferredEnabled, deferredRequestSchemas, deferredState, withDeferred, nativeCatalog, setNativeCatalogMcp, withNativeDeferred } from "./tools/deferred.js";
@@ -461,6 +465,12 @@ export class Session {
461
465
  compactionThreshold;
462
466
  compactionCeilingTokens;
463
467
  compactionMinDecodeTps;
468
+ compactionSpeedTargetTokens;
469
+ speedRearmAt; // the speed target was missed: no speed compaction below this request size
470
+ speedMissTold = false;
471
+ compactionSummaryModel;
472
+ summaryModelTold = false;
473
+ summarySlots = new Map(); // background slots claimed for the summary model, apart from kvSlots
464
474
  decodeSamples = []; // the last measured turns' decode, for the speed trigger
465
475
  fallbackModelId; // settings.fallbackModel (turnModel)
466
476
  background;
@@ -485,11 +495,16 @@ export class Session {
485
495
  planApproval = new PlanApproval(taskPlanRevision, openTaskCount); // the owner's standing plan approval, read by the policy
486
496
  planMode = false; // /plan: research read-only + propose a plan, no mutations until the owner approves
487
497
  thinkMode = "off"; // /think, /ultrathink — extended reasoning
498
+ efforts;
499
+ voice;
488
500
  recalled = false;
489
501
  activeSkillBlock = ""; // capped skill instructions, carried in the conversation (pinnedSkill)
490
502
  activeSkillName = ""; // name of the active skill (for status display)
491
503
  skillNote = ""; // one-shot "stop following skill X" for the owner's next message (/skill off)
492
504
  referenceNote = ""; // one-shot quoted third-party text for the owner's next message (referenceOnce)
505
+ microRecall; // `microAssist`: unset once the session's one search has run
506
+ memoryNote = ""; // its hits, appended after the owner's words in that one message
507
+ unpromptedTools; // the assist's own calls: gatedTools with nobody to ask
493
508
  // Rolling summarizer (engine/rolling-summary.ts): bounded background passes keep a summary of the conversation so
494
509
  // far, so a compaction reads only the tail the summary does not cover yet.
495
510
  rollingSummarizer;
@@ -574,6 +589,13 @@ export class Session {
574
589
  if (dt && cfg.moa && codeActEnabled(cfg.moa.codeact))
575
590
  reg.set("delegate_task", withCodeActDelegateSchema(dt));
576
591
  this.executor = new Executor(reg, cfg.cwd, cfg.sessionId);
592
+ if (isFeatureEnabled("microAssist", { features: cfg.features })) {
593
+ const hub = () => this.hub && { has: (n) => this.hub.has(n), call: (n, a) => this.unpromptedTools.execute(n, a) };
594
+ const micro = createMicroAssist({ hub, task: () => this.lastRequest });
595
+ this.executor.assist = micro.result;
596
+ if (!cfg.background)
597
+ this.microRecall = micro.recall;
598
+ }
577
599
  this.shellKey = this.executor.shellKey; // for disposeShell() on teardown
578
600
  this.localSchemas = toSchemas(reg);
579
601
  // Main sessions only: a sub-agent's prompt (subagentSystemPrompt) lists its tools as attached, and a role's
@@ -584,6 +606,8 @@ export class Session {
584
606
  this.inner = cfg.router ?? new AuroraRouter();
585
607
  this.router = this.wrap(this.inner);
586
608
  this.chain = cfg.router;
609
+ this.efforts = { ...cfg.reasoningEffort };
610
+ this.voice = cfg.voice;
587
611
  this.models = cfg.models;
588
612
  this.dynamicModels = cfg.dynamicModels;
589
613
  this.registry = modelRegistry(cfg.models);
@@ -619,6 +643,8 @@ export class Session {
619
643
  this.compactionThreshold = cfg.compactionThreshold;
620
644
  this.compactionCeilingTokens = cfg.compactionCeilingTokens;
621
645
  this.compactionMinDecodeTps = cfg.compactionMinDecodeTps;
646
+ this.compactionSpeedTargetTokens = cfg.compactionSpeedTargetTokens;
647
+ this.compactionSummaryModel = cfg.compactionSummaryModel;
622
648
  this.fallbackModelId = cfg.fallbackModel;
623
649
  this.contextFloor = cfg.contextFloor ?? AGENT_CTX_FLOOR;
624
650
  this.background = cfg.background ?? false;
@@ -730,10 +756,19 @@ export class Session {
730
756
  * In plan mode a read-only gated policy (no approver → mutating tools fail-safe deny) overrides the
731
757
  * normal policy, so nothing can be modified regardless of the owner's mode/tier. */
732
758
  buildTools() {
759
+ if (this.executor.assist)
760
+ this.unpromptedTools = this.gatedTools(); // `microAssist`'s own calls
761
+ const hooked = this.gatedTools(this.planMode ? undefined : this.approve, this.planMode ? undefined : this.askUser); // no approver in plan mode = hard read-only
762
+ if (this.nativeDeferred)
763
+ return withNativeDeferred(hooked, this.nativeDeferred);
764
+ return this.deferred ? withDeferred(hooked, this.deferred) : hooked;
765
+ }
766
+ /** Every gate a tool call passes: hooks, delegate fence, PR preflight, permissions. With no approver and no asker, a
767
+ * call that needs the owner is refused instead of prompted. */
768
+ gatedTools(approve, ask) {
733
769
  const policy = this.planMode
734
770
  ? new PermissionPolicy({ mode: "gated", tier: this.policy.currentTier() }) // read-only: safe tools allow, mutating ask→deny (no approve fn)
735
771
  : this.policy;
736
- const approve = this.planMode ? undefined : this.approve; // no approver in plan mode = hard read-only
737
772
  const base = withPermissions(withMcp(this.executor, this.hub), policy, { approve, sink: this.eventSink, actor: this.eventActor, session: this.sessionId });
738
773
  // The PR preflight holds code from a PR Operator did not write until the owner picks host or isolation (sub-agents
739
774
  // and headless runs: isolation or refuse). It sits under the delegate fence, so a fenced call never asks.
@@ -741,7 +776,7 @@ export class Session {
741
776
  const preflighted = withPrPreflight(base, {
742
777
  cwd, scratch: scratchDirFor(cwd), shell: this.prShell,
743
778
  trees: () => PR_TREES.getStore() ?? this.prTrees, within: (t, fn) => PR_TREES.run(t, fn),
744
- git: prGit, probe: () => probeIsolation(), ask: this.planMode ? undefined : this.askUser,
779
+ git: prGit, probe: () => probeIsolation(), ask,
745
780
  audit: (line) => this.prAudit(line),
746
781
  });
747
782
  // Delegate mode's fence sits above the gate: a call it refuses never asks the owner to approve it. Off = pass-through.
@@ -751,10 +786,7 @@ export class Session {
751
786
  catch {
752
787
  return p;
753
788
  } } });
754
- const hooked = withHooks(guarded, this.hooks, { cwd: this.cwd ?? process.cwd(), session: this.sessionId ?? "" });
755
- if (this.nativeDeferred)
756
- return withNativeDeferred(hooked, this.nativeDeferred);
757
- return this.deferred ? withDeferred(hooked, this.deferred) : hooked;
789
+ return withHooks(guarded, this.hooks, { cwd: this.cwd ?? process.cwd(), session: this.sessionId ?? "" });
758
790
  }
759
791
  /** One PR preflight audit line: the event trail (when recorded) and `<operator home>/audit/pr-preflight.jsonl`. */
760
792
  prAudit(line) {
@@ -956,7 +988,7 @@ export class Session {
956
988
  // The notes are folded once over their cap, and they can never hold more than was written into them: one fold
957
989
  // (SUMMARY_MAX_TOKENS) plus a note per pass, and a background pass reads at least dueTokens. So a short session's
958
990
  // bound stays below the session itself instead of jumping to the cap a long one needs.
959
- const b = rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS);
991
+ const b = this.rollBudget();
960
992
  const passes = Math.ceil(globalTokenMeter.estimateRequestFor(this.meterKey(), this.convo.all) / b.dueTokens) + 1;
961
993
  const summaryMax = Math.min(b.capTokens, SUMMARY_MAX_TOKENS + b.noteTokens * passes);
962
994
  return { before: this.requestEstimate(), afterMax: globalTokenMeter.estimateRequestFor(this.meterKey(), kept, this.allSchemas()) + summaryMax, summaryMax };
@@ -1083,7 +1115,7 @@ export class Session {
1083
1115
  this.turnHandlers = undefined;
1084
1116
  }
1085
1117
  }
1086
- async compactNowInner() {
1118
+ async compactNowInner(speed) {
1087
1119
  const opts = {
1088
1120
  ctxWindow: this.effectiveContext(),
1089
1121
  systemPrompt: this.sys(),
@@ -1097,13 +1129,25 @@ export class Session {
1097
1129
  spill: spillToolOutput, // GW-10-COMPLETE: /compact's fitToWindow OFFLOADS (re-readable), never erases
1098
1130
  };
1099
1131
  const before = this.requestEstimate();
1100
- this.convo.replaceAll(fitToWindow(await compact(this.convo.all, opts), opts));
1132
+ if (speed)
1133
+ opts.onSkip = () => { speed.failed = true; };
1134
+ const evicted = compactionSplit(this.convo.all, 2)?.evicted;
1135
+ const compacted = await compact(this.convo.all, opts);
1136
+ if (speed && !speed.failed) {
1137
+ if (evicted?.length)
1138
+ archiveEvicted(compacted[0], evicted, spillToolOutput);
1139
+ const ratio = Math.min(opts.threshold ?? defaultThreshold(opts.ctxWindow), speed.target / opts.ctxWindow);
1140
+ this.convo.replaceAll(fitToWindow(compacted, { ...opts, minShedChars: 600 }, ratio));
1141
+ }
1142
+ else
1143
+ this.convo.replaceAll(fitToWindow(compacted, opts));
1101
1144
  return Math.max(0, before - this.requestEstimate()); // CALIBRATED tokens freed — one basis with the bar
1102
1145
  }
1103
1146
  /** Reset the conversation to empty (for /new). */
1104
1147
  reset() {
1105
1148
  this.convo.replaceAll([]);
1106
1149
  this.decodeSamples = [];
1150
+ this.clearSpeedMiss();
1107
1151
  this.rollingSummarizer.clear(); // clear the rolling summary on new session
1108
1152
  this.planApproval.clear(); // a fresh conversation has no reviewed plan
1109
1153
  this.planReviewTold = false; // …and has not been told the mode
@@ -1140,6 +1184,10 @@ export class Session {
1140
1184
  const dyn = this.dynamicModels?.() ?? [];
1141
1185
  return dyn.length ? modelRegistry([...(this.models ?? []), ...dyn]) : this.registry;
1142
1186
  }
1187
+ /** The row a pick of `id` would run on (aliases and retired ids followed), without selecting it. */
1188
+ resolveSelection(id) {
1189
+ return selectModel(this.liveRegistry(), id, hasByoToken, this.isOwner).profile;
1190
+ }
1143
1191
  /** All model profiles the owner can pick between (/model) — built-ins plus any settings.models
1144
1192
  * overrides passed in at construction, plus the dynamic rows. BYO connectors appear ONLY when their vendor
1145
1193
  * key is connected (SPEC/providers.md §1 "Honest availability": the picker shows what can actually run). */
@@ -1178,9 +1226,28 @@ export class Session {
1178
1226
  chatPath: profile.chatPath,
1179
1227
  maxOutput: profile.maxOutput,
1180
1228
  provider: profile.box,
1229
+ reasoning: this.reasoningFor(profile),
1181
1230
  }));
1182
1231
  return new AuroraRouter(eps);
1183
1232
  }
1233
+ /** A profile's thinking knobs. The effort is read per request, so `/think <level>` applies from the next one. */
1234
+ reasoningFor(profile) {
1235
+ const efforts = () => this.efforts;
1236
+ return {
1237
+ get reasoningEffort() { return effortFor(efforts(), profile); },
1238
+ preserveThinking: profile.preserveThinking === true,
1239
+ };
1240
+ }
1241
+ /** The active model's reasoning effort, or undefined for the server's default. */
1242
+ currentReasoningEffort() {
1243
+ return effortFor(this.efforts, findModel(this.liveRegistry(), this.modelId) ?? { id: this.modelId });
1244
+ }
1245
+ /** `/think <level>`: override the active model's effort ("default" returns to the profile's). Returns the overrides
1246
+ * to save. */
1247
+ setReasoningEffort(level) {
1248
+ this.efforts[this.modelId] = level; // "default" is stored too: the saved map is merged, so a removed key would return
1249
+ return { ...this.efforts };
1250
+ }
1184
1251
  /** A turn's model as the owner reads it, and its fallback (runTurn's TurnModel): when every leg of another model
1185
1252
  * fails, or it keeps finishing with nothing, settings.fallbackModel answers that turn (default: the router's `main`,
1186
1253
  * never the launchd-owned Aurora row) — the owner's choice stays, so the next turn tries the chosen model first again.
@@ -1230,6 +1297,7 @@ export class Session {
1230
1297
  if (error || !profile)
1231
1298
  return { ok: false, error };
1232
1299
  this.decodeSamples = []; // another model's rate says nothing about this one
1300
+ this.clearSpeedMiss();
1233
1301
  if (profile.kind === "orchestrated" && profile.id !== WATERFALL_MODEL_ID) { // Waterfall builds its teams from gateway seats
1234
1302
  const team = moaTeam(this.moaConfig);
1235
1303
  if (!team)
@@ -1355,6 +1423,7 @@ export class Session {
1355
1423
  loopbackAuth: leg?.loopbackAuth,
1356
1424
  transport: leg?.transport,
1357
1425
  chatPath: leg?.chatPath,
1426
+ ...leg?.reasoning,
1358
1427
  tools, // identical tools → the span prefix-matches the live turn's cached KV
1359
1428
  maxTokens,
1360
1429
  temperature: 0,
@@ -1417,6 +1486,51 @@ export class Session {
1417
1486
  }
1418
1487
  catch { /* handoff is a durability convenience, never a hard dependency */ }
1419
1488
  }
1489
+ rollBudget() {
1490
+ return rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS, this.compactionSpeedTargetTokens);
1491
+ }
1492
+ /** Where compaction.summaryModel may take a background pass: its first leg on a private address that is proven to
1493
+ * stay there — a llama-server answering `/props` itself, or a router route marked `fleet_only` — with room for a
1494
+ * pass. A provider-key row, the Anthropic wire, a retired row and a gateway host never qualify: the pass carries
1495
+ * conversation text. Asked before every pass (a router's table reloads live). Undefined = the live endpoint. */
1496
+ async summaryLeg(b) {
1497
+ const id = this.compactionSummaryModel;
1498
+ if (!id)
1499
+ return undefined;
1500
+ const p = findModel(this.liveRegistry(), id);
1501
+ if (p?.kind !== "single" || isRetired(p) || !profileEndpoint(p))
1502
+ return this.summaryRefused("not a model id with an endpoint of its own");
1503
+ if (p.byo || p.transport === "anthropic")
1504
+ return this.summaryRefused("a cloud provider row");
1505
+ const need = Math.max(b.chunkTokens, b.capTokens + b.summaryTokens) + b.summaryTokens + 1024;
1506
+ for (const leg of this.routerForProfile(p).list()) {
1507
+ if (requiresOperatorToken(leg.base) || !operatorTrustedUrl(leg.base))
1508
+ continue;
1509
+ const s = await probeServed(leg.base, { timeoutMs: 1500, model: leg.model });
1510
+ if ((!s.direct && !s.fleetOnly) || (s.ctx ?? p.ctx ?? 0) < need)
1511
+ continue;
1512
+ return { leg, ...(s.direct && s.slots && s.slots > 1 ? { slots: s.slots } : {}) };
1513
+ }
1514
+ return this.summaryRefused("no leg proven to stay on your own machines with room for a pass");
1515
+ }
1516
+ summaryRefused(reason) {
1517
+ if (!this.summaryModelTold)
1518
+ this.telemetry.record({ type: "summary_model_unavailable", model: this.compactionSummaryModel, reason });
1519
+ this.summaryModelTold = true;
1520
+ return undefined;
1521
+ }
1522
+ /** The summary model's request identity: always a background conversation of its own, so it never holds or demotes
1523
+ * the interactive lease; on a llama-server reached directly, a slot claimed from the background end. */
1524
+ summaryAffinity(side) {
1525
+ const own = { session: `${this.kvSession}-summary`, sessionRole: "background" };
1526
+ if (!side.slots || process.env.KODE_SLOT_AFFINITY === "0")
1527
+ return own;
1528
+ const key = gateKey(side.leg.base, side.leg.model);
1529
+ let slot = this.summarySlots.get(key);
1530
+ if (slot === undefined)
1531
+ this.summarySlots.set(key, slot = claimSlot(key, side.slots, false, this.kvSlotDir));
1532
+ return { ...own, slot };
1533
+ }
1420
1534
  /** One rolling pass, a lean request (no system prompt, no tools) so what it reads is its own prompt whatever the
1421
1535
  * server has cached. A note pass reads the next uncovered chunk before `upTo` and appends its note; a live one (a
1422
1536
  * compaction, the owner waiting) takes the whole uncovered tail at once. Once the notes are over their cap the pass
@@ -1425,7 +1539,7 @@ export class Session {
1425
1539
  async rollingPass(upTo, signal, live) {
1426
1540
  const all = this.convo.all;
1427
1541
  const rs = this.rollingSummarizer;
1428
- const b = rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS);
1542
+ const b = this.rollBudget();
1429
1543
  // An earlier compaction's note IS the notes so far: adopted as written, never digested again by a note pass.
1430
1544
  const adopted = rs.coveredCount(all) ? undefined : adoptedNotes(all[0]?.content);
1431
1545
  if (adopted !== undefined)
@@ -1447,10 +1561,10 @@ export class Session {
1447
1561
  let wrote = 0;
1448
1562
  const written = h?.onCompactionWrite ? () => h.onCompactionWrite?.(++wrote) : undefined;
1449
1563
  const t0 = performance.now();
1450
- const r = await chat([{ role: "user", content: fold ? foldPrompt(old, b) : notePrompt(chunk.text, b, noteTokens) }], {
1451
- base, model, token: leg?.token, loopbackAuth: leg?.loopbackAuth, transport: leg?.transport, chatPath: leg?.chatPath,
1452
- ...this.affinity({ base, model, transport: leg?.transport }), // the live turn's slot or session: the span is cached there
1453
- maxTokens: leg?.transport === "anthropic" ? SUMMARY_MAX_TOKENS_THINKING : fold ? SUMMARY_MAX_TOKENS : noteTokens,
1564
+ const ask = (to, at, affinity) => chat([{ role: "user", content: fold ? foldPrompt(old, b) : notePrompt(chunk.text, b, noteTokens) }], {
1565
+ ...at, token: to?.token, loopbackAuth: to?.loopbackAuth, transport: to?.transport, chatPath: to?.chatPath, ...to?.reasoning,
1566
+ ...affinity,
1567
+ maxTokens: to?.transport === "anthropic" ? SUMMARY_MAX_TOKENS_THINKING : fold ? SUMMARY_MAX_TOKENS : noteTokens,
1454
1568
  temperature: 0,
1455
1569
  background: !live || this.background, // the endpoint gate: a background pass never takes a slot an interactive request waits for
1456
1570
  owner: "compaction",
@@ -1459,6 +1573,25 @@ export class Session {
1459
1573
  onReasoning: written,
1460
1574
  signal,
1461
1575
  });
1576
+ let r;
1577
+ const side = live ? undefined : await this.summaryLeg(b);
1578
+ if (signal?.aborted)
1579
+ return false;
1580
+ if (side) {
1581
+ try {
1582
+ r = await ask(side.leg, { base: side.leg.base, model: side.leg.model }, this.summaryAffinity(side));
1583
+ if (!pickSummaryContent(r.content, r.reasoningContent))
1584
+ r = undefined;
1585
+ }
1586
+ catch (e) {
1587
+ if (signal?.aborted)
1588
+ throw e;
1589
+ }
1590
+ if (!r)
1591
+ this.summaryRefused("its request failed or came back empty");
1592
+ }
1593
+ const via = r ? this.compactionSummaryModel : undefined;
1594
+ r ??= await ask(leg, { base, model }, this.affinity({ base, model, transport: leg?.transport })); // the live turn's slot or session: the span is cached there
1462
1595
  const text = pickSummaryContent(r.content, r.reasoningContent);
1463
1596
  if (!text || signal?.aborted || this.convo.all !== all)
1464
1597
  return false;
@@ -1466,7 +1599,7 @@ export class Session {
1466
1599
  rs.advance(foldedNotes(old, text, recent, b), all, covered);
1467
1600
  else
1468
1601
  rs.advance(appendNote(notes, text), all, chunk.end);
1469
- this.telemetry.record({ type: "rolling_summary", live, fold, read, covered: fold ? covered : chunk.end, ms: Math.round(performance.now() - t0) });
1602
+ this.telemetry.record({ type: "rolling_summary", ...(via ? { model: via } : {}), live, fold, read, covered: fold ? covered : chunk.end, ms: Math.round(performance.now() - t0) });
1470
1603
  return true;
1471
1604
  }
1472
1605
  /** After a settled turn: while half a chunk or more is uncovered (or the notes are over their cap), summarize it in
@@ -1477,7 +1610,7 @@ export class Session {
1477
1610
  fireRollingSummary() {
1478
1611
  if (this.rollingRun || this.background || process.env.KODE_ROLLING_SUMMARY === "0")
1479
1612
  return;
1480
- const b = rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS);
1613
+ const b = this.rollBudget();
1481
1614
  const due = () => {
1482
1615
  const all = this.convo.all;
1483
1616
  return uncoveredTokens(all, this.rollingSummarizer.coveredCount(all), all.length, b) >= b.dueTokens || notesOverCap(this.rollingSummarizer.getSummary(), b);
@@ -1508,7 +1641,7 @@ export class Session {
1508
1641
  this.rollingAbort?.abort();
1509
1642
  await this.rollingRun;
1510
1643
  const rs = this.rollingSummarizer;
1511
- const b = rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS);
1644
+ const b = this.rollBudget();
1512
1645
  const pending = () => rs.coveredCount(all) < n || notesOverCap(rs.getSummary(), b);
1513
1646
  if (!pending()) {
1514
1647
  this.turnHandlers?.onCompactionCoverage?.({ covered: globalTokenMeter.estimateRequestFor(this.meterKey(), span), reading: 0 });
@@ -1617,6 +1750,8 @@ export class Session {
1617
1750
  this.disposeShell();
1618
1751
  for (const [key, slot] of this.kvSlots)
1619
1752
  releaseSlot(key, slot, this.kvSlotDir);
1753
+ for (const [key, slot] of this.summarySlots)
1754
+ releaseSlot(key, slot, this.kvSlotDir);
1620
1755
  this.kvSlots.clear();
1621
1756
  this.sleepScheduler?.dispose(); // tear down the sleep consolidation scheduler
1622
1757
  }
@@ -1665,12 +1800,22 @@ export class Session {
1665
1800
  this.rollingAbort?.abort(); // the owner's turn takes the model: a background summary pass gives it up at once
1666
1801
  try {
1667
1802
  this.turnImages = await this.nativeImagesFor(text);
1803
+ text = await this.withHeardAudio(text);
1804
+ if (this.ctrl.signal.aborted)
1805
+ return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1668
1806
  const front = await this.viaFrontDoor(text, h);
1669
1807
  if (front)
1670
1808
  return front;
1671
1809
  await this.maybeRecall(text); // fold past-session memory into the system prompt on the first turn
1672
1810
  if (this.ctrl.signal.aborted)
1673
1811
  return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1812
+ if (this.microRecall && !this.wakeTurn) {
1813
+ const recall = this.microRecall;
1814
+ this.microRecall = undefined;
1815
+ this.memoryNote = await recall(text);
1816
+ if (this.ctrl.signal.aborted)
1817
+ return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1818
+ }
1674
1819
  await this.maybeSpeedCompact(h);
1675
1820
  if (this.ctrl.signal.aborted)
1676
1821
  return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
@@ -1692,19 +1837,20 @@ export class Session {
1692
1837
  this.turnThinkOff = false;
1693
1838
  }
1694
1839
  }
1695
- /** The image files in the owner's message that go to the model as pictures, not through image_analyze: only when the
1840
+ /** The image and video files in the owner's message that go to the model directly, not through image_analyze: only when the
1696
1841
  * model answering can see (the profile says so, else its server does; an unknown is tried, and a server that turns
1697
1842
  * the image down puts it back on the tool). Never for a sub-agent, a wake turn or a remote url. */
1698
1843
  async nativeImagesFor(text) {
1699
1844
  if (this.background || this.wakeTurn)
1700
1845
  return [];
1701
- const paths = extractImagePaths(text);
1846
+ const p = findModel(this.liveRegistry(), this.modelId);
1847
+ // video only where the profile declares native vision; a probed or vendor model keeps video_analyze
1848
+ const paths = [...extractImagePaths(text), ...(p?.vision === true ? extractVideoPaths(text) : [])];
1702
1849
  if (!paths.length)
1703
1850
  return [];
1704
- const p = findModel(this.liveRegistry(), this.modelId);
1705
1851
  if (p?.kind !== "single" || p.transport === "anthropic" || p.vision === false)
1706
1852
  return [];
1707
- if (p.vision === true || p.byo)
1853
+ if (p.byo)
1708
1854
  return paths;
1709
1855
  let base, model;
1710
1856
  if (p.id === CHAIN_MODEL_ID) {
@@ -1719,14 +1865,33 @@ export class Session {
1719
1865
  base = endpointBase(ep);
1720
1866
  model = p.endpointModels?.[0] ?? p.model ?? p.id;
1721
1867
  }
1868
+ if (p.vision === true)
1869
+ return visionRejected(base, model) ? [] : paths;
1722
1870
  return (await detectVision(base, model)) === "no" ? [] : paths;
1723
1871
  }
1872
+ /** The owner's message with the audio files it names transcribed under it (the gateway's speech-to-text route): a
1873
+ * natively multimodal model sees pictures but is given no audio. Only for a profile that declares native vision, and
1874
+ * never for a sub-agent or a wake turn. */
1875
+ async withHeardAudio(text) {
1876
+ if (this.background || this.wakeTurn || findModel(this.liveRegistry(), this.modelId)?.vision !== true)
1877
+ return text;
1878
+ const files = extractAudioPaths(text).flatMap((path) => {
1879
+ try {
1880
+ return [{ path, audio: readFileSync(path) }];
1881
+ }
1882
+ catch {
1883
+ return [];
1884
+ }
1885
+ });
1886
+ return files.length ? withTranscripts(text, files, voiceConfig(this.voice), { signal: this.ctrl?.signal }) : text;
1887
+ }
1724
1888
  /** Speed-aware compaction: the last measured turns decoded under compaction.minDecodeTps at a request big enough
1725
1889
  * for compaction to help, so compact now, before this turn's first request. The samples are cleared either way, so
1726
1890
  * the next trigger needs two fresh slow turns. A failed summarizer leaves the conversation as it was. */
1727
1891
  async maybeSpeedCompact(h) {
1728
1892
  const due = speedCompactionDue(this.decodeSamples, this.compactionMinDecodeTps, this.requestEstimate());
1729
- if (!due)
1893
+ const target = this.compactionSpeedTargetTokens;
1894
+ if (!due || (target && (due.ctxTokens <= target || due.ctxTokens < (this.speedRearmAt ?? 0))))
1730
1895
  return;
1731
1896
  this.decodeSamples = [];
1732
1897
  h.onSpeedCompaction?.(due);
@@ -1734,8 +1899,9 @@ export class Session {
1734
1899
  h.onCompactionStart?.({ before });
1735
1900
  this.turnHandlers = h;
1736
1901
  let skipped;
1902
+ const speed = target ? { target } : undefined;
1737
1903
  try {
1738
- await this.compactNowInner();
1904
+ await this.compactNowInner(speed);
1739
1905
  }
1740
1906
  catch {
1741
1907
  skipped = "summarizer_error"; // the turn still runs; the window-fill gate stays the backstop
@@ -1745,8 +1911,26 @@ export class Session {
1745
1911
  const after = this.requestEstimate();
1746
1912
  this.telemetry.record({ type: "compaction", before, after, trigger: "decode", tps: Math.round(due.tps * 10) / 10, floorTps: due.floorTps, ...(skipped ? { skipped } : {}) });
1747
1913
  h.onCompactionEnd?.({ before, after });
1914
+ if (speed && !speed.failed && !skipped)
1915
+ this.noteSpeedTarget(speed.target, after, h);
1748
1916
  }
1749
1917
  }
1918
+ noteSpeedTarget(target, after, h) {
1919
+ if (after <= target) {
1920
+ this.speedRearmAt = undefined;
1921
+ return;
1922
+ }
1923
+ this.speedRearmAt = after + SPEED_REARM_TOKENS;
1924
+ if (this.speedMissTold)
1925
+ return;
1926
+ this.speedMissTold = true;
1927
+ const floor = fixedRequestTokens({ ctxWindow: this.effectiveContext(), systemPrompt: this.sys(), tools: this.allSchemas(), meter: globalTokenMeter, meterKey: this.meterKey(), summarize: this.summarizeEvicted });
1928
+ h.onSpeedTargetMissed?.({ target, after, floor });
1929
+ }
1930
+ clearSpeedMiss() {
1931
+ this.speedRearmAt = undefined;
1932
+ this.speedMissTold = false;
1933
+ }
1750
1934
  /** The front door (engine/front-door.ts). On the default model and MOA, the gateway answers a message its classifier
1751
1935
  * is confident needs no tools with its fast model in this session's voice; the reply joins the conversation like any
1752
1936
  * other. Returns null to run the turn as usual: the gateway says work (the owner sees its status line at once), it
@@ -1914,6 +2098,9 @@ export class Session {
1914
2098
  this.referenceNote = "";
1915
2099
  if (carry)
1916
2100
  text = `${carry}\n\n${text}`;
2101
+ if (this.memoryNote)
2102
+ text = `${text}\n\n${this.memoryNote}`; // after the owner's words: a leading note would mark the message as the engine's
2103
+ this.memoryNote = "";
1917
2104
  const turn = { text, task, convoStart, t0: _t0 };
1918
2105
  this.inflight = turn;
1919
2106
  const turnModelId = routeLabel ?? this.modelId; // the MoA specialist's own id, else the /model pick