@0perator/operator 0.2.2-next.1 → 0.2.5

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.
Files changed (65) hide show
  1. package/dist/autonomy/index.js +14 -5
  2. package/dist/autonomy/session-factory.js +7 -1
  3. package/dist/cli.js +90 -19
  4. package/dist/config/features.js +7 -0
  5. package/dist/config/persona.js +6 -3
  6. package/dist/config/settings.js +17 -0
  7. package/dist/engine/agent.js +8 -0
  8. package/dist/engine/aurora.js +51 -12
  9. package/dist/engine/batch-hints.js +45 -0
  10. package/dist/engine/batch-scheduler.js +23 -7
  11. package/dist/engine/compaction.js +8 -1
  12. package/dist/engine/messages.js +5 -0
  13. package/dist/engine/native-vision-node.js +88 -10
  14. package/dist/engine/native-vision.js +25 -7
  15. package/dist/engine/rolling-summary.js +3 -2
  16. package/dist/engine/router-adapter.js +1 -0
  17. package/dist/engine/speed-compaction.js +7 -0
  18. package/dist/engine/token-meter.js +1 -1
  19. package/dist/mcp/index.js +2 -2
  20. package/dist/products/voice.js +44 -9
  21. package/dist/router/activation.js +132 -0
  22. package/dist/router/discovery.js +4 -3
  23. package/dist/router/model-list.js +79 -0
  24. package/dist/router/models.js +12 -1
  25. package/dist/router/router.js +0 -11
  26. package/dist/session.js +239 -33
  27. package/dist/tools/classes.js +2 -0
  28. package/dist/tools/deferred.js +11 -6
  29. package/dist/tools/executor.js +17 -3
  30. package/dist/tools/micro-assist.js +105 -0
  31. package/dist/tools/read-ledger.js +4 -0
  32. package/dist/tools/readonly-shell.js +92 -0
  33. package/dist/tools/registry.js +68 -61
  34. package/dist/tools/sandbox.js +1 -1
  35. package/dist/tools/semantic-compress.js +1 -9
  36. package/dist/tools/shell-session.js +56 -1
  37. package/dist/tools/tool-output-spill.js +1 -1
  38. package/dist/ui/ActivitySpinner.js +2 -2
  39. package/dist/ui/App.js +8 -8
  40. package/dist/ui/ApprovalPrompt.js +5 -4
  41. package/dist/ui/ArtifactPicker.js +4 -3
  42. package/dist/ui/AuthScreen.js +2 -1
  43. package/dist/ui/BgPanel.js +6 -6
  44. package/dist/ui/Composer.js +4 -3
  45. package/dist/ui/Header.js +2 -2
  46. package/dist/ui/Markdown.js +50 -77
  47. package/dist/ui/PlanPane.js +5 -5
  48. package/dist/ui/QuestionPrompt.js +2 -1
  49. package/dist/ui/SecretPrompt.js +2 -1
  50. package/dist/ui/SessionPicker.js +4 -3
  51. package/dist/ui/SkillFinder.js +3 -2
  52. package/dist/ui/StatsCard.js +2 -2
  53. package/dist/ui/StatusRule.js +2 -2
  54. package/dist/ui/SummaryCard.js +2 -2
  55. package/dist/ui/Table.js +25 -24
  56. package/dist/ui/ThinkingSpinner.js +2 -1
  57. package/dist/ui/ToolBatch.js +3 -3
  58. package/dist/ui/ToolStep.js +4 -4
  59. package/dist/ui/Transcript.js +12 -12
  60. package/dist/ui/UpdatePrompt.js +2 -1
  61. package/dist/ui/activationFlow.js +126 -0
  62. package/dist/ui/inline.js +109 -0
  63. package/dist/ui/modelPicker.js +12 -7
  64. package/dist/ui/theme.js +4 -0
  65. package/package.json +1 -1
package/dist/session.js CHANGED
@@ -1,21 +1,25 @@
1
1
  // Headless session controller — owns the conversation + engine wiring for ONE interactive session,
2
2
  // with no UI dependency, so it is testable end-to-end without a TTY. cli.tsx is a thin Ink shell
3
3
  // that maps these callbacks onto React state; a test can drive the same `send()` directly.
4
+ import { DELEGATION } from "./tools/classes.js";
4
5
  import { runTurn, TurnAbortedError } from "./engine/agent.js";
5
6
  import { recordTruncation } from "./observability/blackbox.js";
6
7
  import { Conversation, placeSessionContext, SESSION_CONTEXT_OPEN, SESSION_CONTEXT_CLOSE, SESSION_CONTEXT_REQUEST_LINE } from "./engine/messages.js";
7
8
  import { scratchDirFor } from "./config/scratch.js";
8
9
  import { homedir } from "node:os";
9
- import { detectVision, markVisionRejected } from "./engine/native-vision.js";
10
- import { extractImagePaths } from "./engine/native-vision-node.js";
10
+ import { detectVision, markVisionRejected, visionRejected } from "./engine/native-vision.js";
11
+ import { voiceConfig, withTranscripts } from "./products/voice.js";
12
+ import { readFileSync } from "node:fs";
13
+ import { extractAudioPaths, extractImagePaths, extractVideoPaths } from "./engine/native-vision-node.js";
11
14
  import { planFanOut } from "./engine/fanout.js";
12
15
  import { withCodeActDelegateSchema } from "./moa/codeact-lane.js";
13
16
  import { codeActEnabled } from "./moa/codeact.js";
17
+ import { effortFor } from "./router/models.js";
14
18
  import { chat, health, reachable, gateKey, isRemoteBase, shipsLlamaCacheKnobs, requiresOperatorToken, operatorTrustedUrl } from "./engine/aurora.js";
15
19
  import { claimSlot, releaseSlot } from "./engine/kv-slot.js";
16
20
  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";
21
+ import { recordDecodeSample, speedCompactionDue, SPEED_REARM_TOKENS } from "./engine/speed-compaction.js";
22
+ import { compact, compactionSplit, fitToWindow, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent, renderAnchorIndex, verbatimUserTail, archiveEvicted, defaultThreshold, fixedRequestTokens } from "./engine/compaction.js";
19
23
  import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
20
24
  import { spillToolOutput } from "./tools/tool-output-spill.js"; // GW-10-COMPLETE: node-side spill sink
21
25
  import { engineRouter } from "./engine/router-adapter.js";
@@ -35,7 +39,7 @@ import { routeShadowTurn, shadowPrompt } from "./moa/shadow.js"; // MOA phase-0
35
39
  import { AuroraRouter } from "./router/router.js";
36
40
  import { operatorAgentPersona } from "./config/operator-harness.js";
37
41
  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";
42
+ 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
43
  import { probeServed, usableCtx } from "./router/discovery.js";
40
44
  import { FAST_START_INSTRUCTION, parseFastStartReply } from "./engine/fast-start.js";
41
45
  import { askFrontDoor, recentTurns } from "./engine/front-door.js";
@@ -44,6 +48,7 @@ import { Executor } from "./tools/executor.js";
44
48
  import { autoDeliverReport, autoDeliverFailure, wakeRoot } from "./bus/inbox.js";
45
49
  import { toSchemas, registry, disposeShellSessionKey, requestShellDetach, cloudAgentToolsFor, mdocToolsFor, craftToolsFor, renderActiveTasks, getAgentTasks, taskPlanRevision, openTaskCount } from "./tools/registry.js";
46
50
  import { isFeatureEnabled } from "./config/features.js";
51
+ import { createMicroAssist } from "./tools/micro-assist.js";
47
52
  import { MemoryStore } from "./memory/index.js";
48
53
  import { McpHub, withMcp } from "./mcp/index.js";
49
54
  import { deferredEnabled, deferredRequestSchemas, deferredState, withDeferred, nativeCatalog, setNativeCatalogMcp, withNativeDeferred } from "./tools/deferred.js";
@@ -461,6 +466,12 @@ export class Session {
461
466
  compactionThreshold;
462
467
  compactionCeilingTokens;
463
468
  compactionMinDecodeTps;
469
+ compactionSpeedTargetTokens;
470
+ speedRearmAt; // the speed target was missed: no speed compaction below this request size
471
+ speedMissTold = false;
472
+ compactionSummaryModel;
473
+ summaryModelTold = false;
474
+ summarySlots = new Map(); // background slots claimed for the summary model, apart from kvSlots
464
475
  decodeSamples = []; // the last measured turns' decode, for the speed trigger
465
476
  fallbackModelId; // settings.fallbackModel (turnModel)
466
477
  background;
@@ -485,11 +496,16 @@ export class Session {
485
496
  planApproval = new PlanApproval(taskPlanRevision, openTaskCount); // the owner's standing plan approval, read by the policy
486
497
  planMode = false; // /plan: research read-only + propose a plan, no mutations until the owner approves
487
498
  thinkMode = "off"; // /think, /ultrathink — extended reasoning
499
+ efforts;
500
+ voice;
488
501
  recalled = false;
489
502
  activeSkillBlock = ""; // capped skill instructions, carried in the conversation (pinnedSkill)
490
503
  activeSkillName = ""; // name of the active skill (for status display)
491
504
  skillNote = ""; // one-shot "stop following skill X" for the owner's next message (/skill off)
492
505
  referenceNote = ""; // one-shot quoted third-party text for the owner's next message (referenceOnce)
506
+ microRecall; // `microAssist`: unset once the session's one search has run
507
+ memoryNote = ""; // its hits, appended after the owner's words in that one message
508
+ unpromptedTools; // the assist's own calls: gatedTools with nobody to ask
493
509
  // Rolling summarizer (engine/rolling-summary.ts): bounded background passes keep a summary of the conversation so
494
510
  // far, so a compaction reads only the tail the summary does not cover yet.
495
511
  rollingSummarizer;
@@ -574,6 +590,13 @@ export class Session {
574
590
  if (dt && cfg.moa && codeActEnabled(cfg.moa.codeact))
575
591
  reg.set("delegate_task", withCodeActDelegateSchema(dt));
576
592
  this.executor = new Executor(reg, cfg.cwd, cfg.sessionId);
593
+ if (isFeatureEnabled("microAssist", { features: cfg.features })) {
594
+ const hub = () => this.hub && { has: (n) => this.hub.has(n), call: (n, a) => this.unpromptedTools.execute(n, a) };
595
+ const micro = createMicroAssist({ hub, task: () => this.lastRequest });
596
+ this.executor.assist = micro.result;
597
+ if (!cfg.background)
598
+ this.microRecall = micro.recall;
599
+ }
577
600
  this.shellKey = this.executor.shellKey; // for disposeShell() on teardown
578
601
  this.localSchemas = toSchemas(reg);
579
602
  // Main sessions only: a sub-agent's prompt (subagentSystemPrompt) lists its tools as attached, and a role's
@@ -584,6 +607,8 @@ export class Session {
584
607
  this.inner = cfg.router ?? new AuroraRouter();
585
608
  this.router = this.wrap(this.inner);
586
609
  this.chain = cfg.router;
610
+ this.efforts = { ...cfg.reasoningEffort };
611
+ this.voice = cfg.voice;
587
612
  this.models = cfg.models;
588
613
  this.dynamicModels = cfg.dynamicModels;
589
614
  this.registry = modelRegistry(cfg.models);
@@ -619,6 +644,8 @@ export class Session {
619
644
  this.compactionThreshold = cfg.compactionThreshold;
620
645
  this.compactionCeilingTokens = cfg.compactionCeilingTokens;
621
646
  this.compactionMinDecodeTps = cfg.compactionMinDecodeTps;
647
+ this.compactionSpeedTargetTokens = cfg.compactionSpeedTargetTokens;
648
+ this.compactionSummaryModel = cfg.compactionSummaryModel;
622
649
  this.fallbackModelId = cfg.fallbackModel;
623
650
  this.contextFloor = cfg.contextFloor ?? AGENT_CTX_FLOOR;
624
651
  this.background = cfg.background ?? false;
@@ -730,10 +757,19 @@ export class Session {
730
757
  * In plan mode a read-only gated policy (no approver → mutating tools fail-safe deny) overrides the
731
758
  * normal policy, so nothing can be modified regardless of the owner's mode/tier. */
732
759
  buildTools() {
760
+ if (this.executor.assist)
761
+ this.unpromptedTools = this.gatedTools(); // `microAssist`'s own calls
762
+ const hooked = this.gatedTools(this.planMode ? undefined : this.approve, this.planMode ? undefined : this.askUser); // no approver in plan mode = hard read-only
763
+ if (this.nativeDeferred)
764
+ return withNativeDeferred(hooked, this.nativeDeferred);
765
+ return this.deferred ? withDeferred(hooked, this.deferred) : hooked;
766
+ }
767
+ /** Every gate a tool call passes: hooks, delegate fence, PR preflight, permissions. With no approver and no asker, a
768
+ * call that needs the owner is refused instead of prompted. */
769
+ gatedTools(approve, ask) {
733
770
  const policy = this.planMode
734
771
  ? new PermissionPolicy({ mode: "gated", tier: this.policy.currentTier() }) // read-only: safe tools allow, mutating ask→deny (no approve fn)
735
772
  : this.policy;
736
- const approve = this.planMode ? undefined : this.approve; // no approver in plan mode = hard read-only
737
773
  const base = withPermissions(withMcp(this.executor, this.hub), policy, { approve, sink: this.eventSink, actor: this.eventActor, session: this.sessionId });
738
774
  // The PR preflight holds code from a PR Operator did not write until the owner picks host or isolation (sub-agents
739
775
  // and headless runs: isolation or refuse). It sits under the delegate fence, so a fenced call never asks.
@@ -741,7 +777,7 @@ export class Session {
741
777
  const preflighted = withPrPreflight(base, {
742
778
  cwd, scratch: scratchDirFor(cwd), shell: this.prShell,
743
779
  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,
780
+ git: prGit, probe: () => probeIsolation(), ask,
745
781
  audit: (line) => this.prAudit(line),
746
782
  });
747
783
  // Delegate mode's fence sits above the gate: a call it refuses never asks the owner to approve it. Off = pass-through.
@@ -751,10 +787,7 @@ export class Session {
751
787
  catch {
752
788
  return p;
753
789
  } } });
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;
790
+ return withHooks(guarded, this.hooks, { cwd: this.cwd ?? process.cwd(), session: this.sessionId ?? "" });
758
791
  }
759
792
  /** One PR preflight audit line: the event trail (when recorded) and `<operator home>/audit/pr-preflight.jsonl`. */
760
793
  prAudit(line) {
@@ -956,7 +989,7 @@ export class Session {
956
989
  // The notes are folded once over their cap, and they can never hold more than was written into them: one fold
957
990
  // (SUMMARY_MAX_TOKENS) plus a note per pass, and a background pass reads at least dueTokens. So a short session's
958
991
  // 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);
992
+ const b = this.rollBudget();
960
993
  const passes = Math.ceil(globalTokenMeter.estimateRequestFor(this.meterKey(), this.convo.all) / b.dueTokens) + 1;
961
994
  const summaryMax = Math.min(b.capTokens, SUMMARY_MAX_TOKENS + b.noteTokens * passes);
962
995
  return { before: this.requestEstimate(), afterMax: globalTokenMeter.estimateRequestFor(this.meterKey(), kept, this.allSchemas()) + summaryMax, summaryMax };
@@ -1083,7 +1116,7 @@ export class Session {
1083
1116
  this.turnHandlers = undefined;
1084
1117
  }
1085
1118
  }
1086
- async compactNowInner() {
1119
+ async compactNowInner(speed) {
1087
1120
  const opts = {
1088
1121
  ctxWindow: this.effectiveContext(),
1089
1122
  systemPrompt: this.sys(),
@@ -1097,13 +1130,25 @@ export class Session {
1097
1130
  spill: spillToolOutput, // GW-10-COMPLETE: /compact's fitToWindow OFFLOADS (re-readable), never erases
1098
1131
  };
1099
1132
  const before = this.requestEstimate();
1100
- this.convo.replaceAll(fitToWindow(await compact(this.convo.all, opts), opts));
1133
+ if (speed)
1134
+ opts.onSkip = () => { speed.failed = true; };
1135
+ const evicted = compactionSplit(this.convo.all, 2)?.evicted;
1136
+ const compacted = await compact(this.convo.all, opts);
1137
+ if (speed && !speed.failed) {
1138
+ if (evicted?.length)
1139
+ archiveEvicted(compacted[0], evicted, spillToolOutput);
1140
+ const ratio = Math.min(opts.threshold ?? defaultThreshold(opts.ctxWindow), speed.target / opts.ctxWindow);
1141
+ this.convo.replaceAll(fitToWindow(compacted, { ...opts, minShedChars: 600 }, ratio));
1142
+ }
1143
+ else
1144
+ this.convo.replaceAll(fitToWindow(compacted, opts));
1101
1145
  return Math.max(0, before - this.requestEstimate()); // CALIBRATED tokens freed — one basis with the bar
1102
1146
  }
1103
1147
  /** Reset the conversation to empty (for /new). */
1104
1148
  reset() {
1105
1149
  this.convo.replaceAll([]);
1106
1150
  this.decodeSamples = [];
1151
+ this.clearSpeedMiss();
1107
1152
  this.rollingSummarizer.clear(); // clear the rolling summary on new session
1108
1153
  this.planApproval.clear(); // a fresh conversation has no reviewed plan
1109
1154
  this.planReviewTold = false; // …and has not been told the mode
@@ -1140,6 +1185,10 @@ export class Session {
1140
1185
  const dyn = this.dynamicModels?.() ?? [];
1141
1186
  return dyn.length ? modelRegistry([...(this.models ?? []), ...dyn]) : this.registry;
1142
1187
  }
1188
+ /** The row a pick of `id` would run on (aliases and retired ids followed), without selecting it. */
1189
+ resolveSelection(id) {
1190
+ return selectModel(this.liveRegistry(), id, hasByoToken, this.isOwner).profile;
1191
+ }
1143
1192
  /** All model profiles the owner can pick between (/model) — built-ins plus any settings.models
1144
1193
  * overrides passed in at construction, plus the dynamic rows. BYO connectors appear ONLY when their vendor
1145
1194
  * key is connected (SPEC/providers.md §1 "Honest availability": the picker shows what can actually run). */
@@ -1178,9 +1227,28 @@ export class Session {
1178
1227
  chatPath: profile.chatPath,
1179
1228
  maxOutput: profile.maxOutput,
1180
1229
  provider: profile.box,
1230
+ reasoning: this.reasoningFor(profile),
1181
1231
  }));
1182
1232
  return new AuroraRouter(eps);
1183
1233
  }
1234
+ /** A profile's thinking knobs. The effort is read per request, so `/think <level>` applies from the next one. */
1235
+ reasoningFor(profile) {
1236
+ const efforts = () => this.efforts;
1237
+ return {
1238
+ get reasoningEffort() { return effortFor(efforts(), profile); },
1239
+ preserveThinking: profile.preserveThinking === true,
1240
+ };
1241
+ }
1242
+ /** The active model's reasoning effort, or undefined for the server's default. */
1243
+ currentReasoningEffort() {
1244
+ return effortFor(this.efforts, findModel(this.liveRegistry(), this.modelId) ?? { id: this.modelId });
1245
+ }
1246
+ /** `/think <level>`: override the active model's effort ("default" returns to the profile's). Returns the overrides
1247
+ * to save. */
1248
+ setReasoningEffort(level) {
1249
+ this.efforts[this.modelId] = level; // "default" is stored too: the saved map is merged, so a removed key would return
1250
+ return { ...this.efforts };
1251
+ }
1184
1252
  /** A turn's model as the owner reads it, and its fallback (runTurn's TurnModel): when every leg of another model
1185
1253
  * fails, or it keeps finishing with nothing, settings.fallbackModel answers that turn (default: the router's `main`,
1186
1254
  * never the launchd-owned Aurora row) — the owner's choice stays, so the next turn tries the chosen model first again.
@@ -1230,6 +1298,7 @@ export class Session {
1230
1298
  if (error || !profile)
1231
1299
  return { ok: false, error };
1232
1300
  this.decodeSamples = []; // another model's rate says nothing about this one
1301
+ this.clearSpeedMiss();
1233
1302
  if (profile.kind === "orchestrated" && profile.id !== WATERFALL_MODEL_ID) { // Waterfall builds its teams from gateway seats
1234
1303
  const team = moaTeam(this.moaConfig);
1235
1304
  if (!team)
@@ -1355,6 +1424,7 @@ export class Session {
1355
1424
  loopbackAuth: leg?.loopbackAuth,
1356
1425
  transport: leg?.transport,
1357
1426
  chatPath: leg?.chatPath,
1427
+ ...leg?.reasoning,
1358
1428
  tools, // identical tools → the span prefix-matches the live turn's cached KV
1359
1429
  maxTokens,
1360
1430
  temperature: 0,
@@ -1417,15 +1487,67 @@ export class Session {
1417
1487
  }
1418
1488
  catch { /* handoff is a durability convenience, never a hard dependency */ }
1419
1489
  }
1490
+ rollBudget() {
1491
+ return rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS, this.compactionSpeedTargetTokens);
1492
+ }
1493
+ /** Where compaction.summaryModel may take a background pass: its first leg, on a server other than the
1494
+ * conversation's own, at a private address that is proven to
1495
+ * stay there — a llama-server answering `/props` itself, or a router route marked `fleet_only` — with room for a
1496
+ * pass. A provider-key row, the Anthropic wire, a retired row and a gateway host never qualify: the pass carries
1497
+ * conversation text. Asked before every pass (a router's table reloads live). Undefined = the live endpoint. */
1498
+ async summaryLeg(b) {
1499
+ const live = { base: this.lastBase ?? this.inner.base, model: this.lastModel ?? this.inner.model };
1500
+ const id = this.compactionSummaryModel;
1501
+ if (!id)
1502
+ return undefined;
1503
+ const p = findModel(this.liveRegistry(), id);
1504
+ if (p?.kind !== "single" || isRetired(p) || !profileEndpoint(p))
1505
+ return this.summaryRefused("not a model id with an endpoint of its own");
1506
+ if (p.byo || p.transport === "anthropic")
1507
+ return this.summaryRefused("a cloud provider row");
1508
+ const need = Math.max(b.chunkTokens, b.capTokens + b.summaryTokens) + b.summaryTokens + 1024;
1509
+ for (const leg of this.routerForProfile(p).list()) {
1510
+ if (requiresOperatorToken(leg.base) || !operatorTrustedUrl(leg.base))
1511
+ continue;
1512
+ const s = await probeServed(leg.base, { timeoutMs: 1500, model: leg.model });
1513
+ if ((!s.direct && !s.fleetOnly) || (s.ctx ?? p.ctx ?? 0) < need)
1514
+ continue;
1515
+ // One llama-server answers every model name; a router tells its servers apart only by route.
1516
+ if (new URL(leg.base).origin === new URL(live.base).origin && (s.direct || leg.model === live.model))
1517
+ continue;
1518
+ return { leg, ...(s.direct && s.slots && s.slots > 1 ? { slots: s.slots } : {}) };
1519
+ }
1520
+ return this.summaryRefused("no leg on another server, proven to stay on your own machines, with room for a pass");
1521
+ }
1522
+ summaryRefused(reason) {
1523
+ if (!this.summaryModelTold)
1524
+ this.telemetry.record({ type: "summary_model_unavailable", model: this.compactionSummaryModel, reason });
1525
+ this.summaryModelTold = true;
1526
+ return undefined;
1527
+ }
1528
+ /** The summary model's request identity: always a background conversation of its own, so it never holds or demotes
1529
+ * the interactive lease; on a llama-server reached directly, a slot claimed from the background end. */
1530
+ summaryAffinity(side) {
1531
+ const own = { session: `${this.kvSession}-summary`, sessionRole: "background" };
1532
+ if (!side.slots || process.env.KODE_SLOT_AFFINITY === "0")
1533
+ return own;
1534
+ const key = gateKey(side.leg.base, side.leg.model);
1535
+ let slot = this.summarySlots.get(key);
1536
+ if (slot === undefined)
1537
+ this.summarySlots.set(key, slot = claimSlot(key, side.slots, false, this.kvSlotDir));
1538
+ return { ...own, slot };
1539
+ }
1420
1540
  /** One rolling pass, a lean request (no system prompt, no tools) so what it reads is its own prompt whatever the
1421
- * server has cached. A note pass reads the next uncovered chunk before `upTo` and appends its note; a live one (a
1541
+ * server has cached. It shares no prefix with the conversation, so on a llama.cpp leg it would replace the cache the
1542
+ * next turn needs (a hybrid model cannot rewind, and a long session is too big to keep aside): a background pass
1543
+ * runs there only on a separate summary model, and otherwise waits for compaction. A note pass reads the next uncovered chunk before `upTo` and appends its note; a live one (a
1422
1544
  * compaction, the owner waiting) takes the whole uncovered tail at once. Once the notes are over their cap the pass
1423
1545
  * folds their older half into one summary instead. False when nothing advanced: nothing left, an empty answer, or
1424
1546
  * the conversation was replaced meanwhile. */
1425
1547
  async rollingPass(upTo, signal, live) {
1426
1548
  const all = this.convo.all;
1427
1549
  const rs = this.rollingSummarizer;
1428
- const b = rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS);
1550
+ const b = this.rollBudget();
1429
1551
  // An earlier compaction's note IS the notes so far: adopted as written, never digested again by a note pass.
1430
1552
  const adopted = rs.coveredCount(all) ? undefined : adoptedNotes(all[0]?.content);
1431
1553
  if (adopted !== undefined)
@@ -1447,10 +1569,10 @@ export class Session {
1447
1569
  let wrote = 0;
1448
1570
  const written = h?.onCompactionWrite ? () => h.onCompactionWrite?.(++wrote) : undefined;
1449
1571
  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,
1572
+ const ask = (to, at, affinity) => chat([{ role: "user", content: fold ? foldPrompt(old, b) : notePrompt(chunk.text, b, noteTokens) }], {
1573
+ ...at, token: to?.token, loopbackAuth: to?.loopbackAuth, transport: to?.transport, chatPath: to?.chatPath, ...to?.reasoning,
1574
+ ...affinity,
1575
+ maxTokens: to?.transport === "anthropic" ? SUMMARY_MAX_TOKENS_THINKING : fold ? SUMMARY_MAX_TOKENS : noteTokens,
1454
1576
  temperature: 0,
1455
1577
  background: !live || this.background, // the endpoint gate: a background pass never takes a slot an interactive request waits for
1456
1578
  owner: "compaction",
@@ -1459,6 +1581,28 @@ export class Session {
1459
1581
  onReasoning: written,
1460
1582
  signal,
1461
1583
  });
1584
+ let r;
1585
+ const side = live ? undefined : await this.summaryLeg(b);
1586
+ const keepsOurCache = !live && shipsLlamaCacheKnobs(base, leg?.transport);
1587
+ if (signal?.aborted || (keepsOurCache && !side))
1588
+ return false;
1589
+ if (side) {
1590
+ try {
1591
+ r = await ask(side.leg, { base: side.leg.base, model: side.leg.model }, this.summaryAffinity(side));
1592
+ if (!pickSummaryContent(r.content, r.reasoningContent))
1593
+ r = undefined;
1594
+ }
1595
+ catch (e) {
1596
+ if (signal?.aborted)
1597
+ throw e;
1598
+ }
1599
+ if (!r)
1600
+ this.summaryRefused("its request failed or came back empty");
1601
+ if (!r && keepsOurCache)
1602
+ return false;
1603
+ }
1604
+ const via = r ? this.compactionSummaryModel : undefined;
1605
+ 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
1606
  const text = pickSummaryContent(r.content, r.reasoningContent);
1463
1607
  if (!text || signal?.aborted || this.convo.all !== all)
1464
1608
  return false;
@@ -1466,18 +1610,18 @@ export class Session {
1466
1610
  rs.advance(foldedNotes(old, text, recent, b), all, covered);
1467
1611
  else
1468
1612
  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) });
1613
+ this.telemetry.record({ type: "rolling_summary", ...(via ? { model: via } : {}), live, fold, read, covered: fold ? covered : chunk.end, ms: Math.round(performance.now() - t0) });
1470
1614
  return true;
1471
1615
  }
1472
1616
  /** After a settled turn: while half a chunk or more is uncovered (or the notes are over their cap), summarize it in
1473
- * the background, one bounded pass at a time. send() aborts the pass in flight, so the owner's next message never
1617
+ * the background, where a pass may run at all (rollingPass), one bounded pass at a time. send() aborts the pass in flight, so the owner's next message never
1474
1618
  * waits for it; what a pass had not finished is picked up after the next turn, or read live at compaction. Never
1475
1619
  * for a sub-agent: its session ends with its turn, and nothing would abort its pass when the owner's turn wants
1476
1620
  * the model. */
1477
1621
  fireRollingSummary() {
1478
1622
  if (this.rollingRun || this.background || process.env.KODE_ROLLING_SUMMARY === "0")
1479
1623
  return;
1480
- const b = rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS);
1624
+ const b = this.rollBudget();
1481
1625
  const due = () => {
1482
1626
  const all = this.convo.all;
1483
1627
  return uncoveredTokens(all, this.rollingSummarizer.coveredCount(all), all.length, b) >= b.dueTokens || notesOverCap(this.rollingSummarizer.getSummary(), b);
@@ -1508,7 +1652,7 @@ export class Session {
1508
1652
  this.rollingAbort?.abort();
1509
1653
  await this.rollingRun;
1510
1654
  const rs = this.rollingSummarizer;
1511
- const b = rollingBudget(this.effectiveContext(), SUMMARY_MAX_TOKENS);
1655
+ const b = this.rollBudget();
1512
1656
  const pending = () => rs.coveredCount(all) < n || notesOverCap(rs.getSummary(), b);
1513
1657
  if (!pending()) {
1514
1658
  this.turnHandlers?.onCompactionCoverage?.({ covered: globalTokenMeter.estimateRequestFor(this.meterKey(), span), reading: 0 });
@@ -1617,6 +1761,8 @@ export class Session {
1617
1761
  this.disposeShell();
1618
1762
  for (const [key, slot] of this.kvSlots)
1619
1763
  releaseSlot(key, slot, this.kvSlotDir);
1764
+ for (const [key, slot] of this.summarySlots)
1765
+ releaseSlot(key, slot, this.kvSlotDir);
1620
1766
  this.kvSlots.clear();
1621
1767
  this.sleepScheduler?.dispose(); // tear down the sleep consolidation scheduler
1622
1768
  }
@@ -1665,12 +1811,22 @@ export class Session {
1665
1811
  this.rollingAbort?.abort(); // the owner's turn takes the model: a background summary pass gives it up at once
1666
1812
  try {
1667
1813
  this.turnImages = await this.nativeImagesFor(text);
1814
+ text = await this.withHeardAudio(text);
1815
+ if (this.ctrl.signal.aborted)
1816
+ return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1668
1817
  const front = await this.viaFrontDoor(text, h);
1669
1818
  if (front)
1670
1819
  return front;
1671
1820
  await this.maybeRecall(text); // fold past-session memory into the system prompt on the first turn
1672
1821
  if (this.ctrl.signal.aborted)
1673
1822
  return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1823
+ if (this.microRecall && !this.wakeTurn) {
1824
+ const recall = this.microRecall;
1825
+ this.microRecall = undefined;
1826
+ this.memoryNote = await recall(text);
1827
+ if (this.ctrl.signal.aborted)
1828
+ return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
1829
+ }
1674
1830
  await this.maybeSpeedCompact(h);
1675
1831
  if (this.ctrl.signal.aborted)
1676
1832
  return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
@@ -1692,19 +1848,20 @@ export class Session {
1692
1848
  this.turnThinkOff = false;
1693
1849
  }
1694
1850
  }
1695
- /** The image files in the owner's message that go to the model as pictures, not through image_analyze: only when the
1851
+ /** The image and video files in the owner's message that go to the model directly, not through image_analyze: only when the
1696
1852
  * model answering can see (the profile says so, else its server does; an unknown is tried, and a server that turns
1697
1853
  * the image down puts it back on the tool). Never for a sub-agent, a wake turn or a remote url. */
1698
1854
  async nativeImagesFor(text) {
1699
1855
  if (this.background || this.wakeTurn)
1700
1856
  return [];
1701
- const paths = extractImagePaths(text);
1857
+ const p = findModel(this.liveRegistry(), this.modelId);
1858
+ // video only where the profile declares native vision; a probed or vendor model keeps video_analyze
1859
+ const paths = [...extractImagePaths(text), ...(p?.vision === true ? extractVideoPaths(text) : [])];
1702
1860
  if (!paths.length)
1703
1861
  return [];
1704
- const p = findModel(this.liveRegistry(), this.modelId);
1705
1862
  if (p?.kind !== "single" || p.transport === "anthropic" || p.vision === false)
1706
1863
  return [];
1707
- if (p.vision === true || p.byo)
1864
+ if (p.byo)
1708
1865
  return paths;
1709
1866
  let base, model;
1710
1867
  if (p.id === CHAIN_MODEL_ID) {
@@ -1719,14 +1876,33 @@ export class Session {
1719
1876
  base = endpointBase(ep);
1720
1877
  model = p.endpointModels?.[0] ?? p.model ?? p.id;
1721
1878
  }
1879
+ if (p.vision === true)
1880
+ return visionRejected(base, model) ? [] : paths;
1722
1881
  return (await detectVision(base, model)) === "no" ? [] : paths;
1723
1882
  }
1883
+ /** The owner's message with the audio files it names transcribed under it (the gateway's speech-to-text route): a
1884
+ * natively multimodal model sees pictures but is given no audio. Only for a profile that declares native vision, and
1885
+ * never for a sub-agent or a wake turn. */
1886
+ async withHeardAudio(text) {
1887
+ if (this.background || this.wakeTurn || findModel(this.liveRegistry(), this.modelId)?.vision !== true)
1888
+ return text;
1889
+ const files = extractAudioPaths(text).flatMap((path) => {
1890
+ try {
1891
+ return [{ path, audio: readFileSync(path) }];
1892
+ }
1893
+ catch {
1894
+ return [];
1895
+ }
1896
+ });
1897
+ return files.length ? withTranscripts(text, files, voiceConfig(this.voice), { signal: this.ctrl?.signal }) : text;
1898
+ }
1724
1899
  /** Speed-aware compaction: the last measured turns decoded under compaction.minDecodeTps at a request big enough
1725
1900
  * for compaction to help, so compact now, before this turn's first request. The samples are cleared either way, so
1726
1901
  * the next trigger needs two fresh slow turns. A failed summarizer leaves the conversation as it was. */
1727
1902
  async maybeSpeedCompact(h) {
1728
1903
  const due = speedCompactionDue(this.decodeSamples, this.compactionMinDecodeTps, this.requestEstimate());
1729
- if (!due)
1904
+ const target = this.compactionSpeedTargetTokens;
1905
+ if (!due || (target && (due.ctxTokens <= target || due.ctxTokens < (this.speedRearmAt ?? 0))))
1730
1906
  return;
1731
1907
  this.decodeSamples = [];
1732
1908
  h.onSpeedCompaction?.(due);
@@ -1734,8 +1910,9 @@ export class Session {
1734
1910
  h.onCompactionStart?.({ before });
1735
1911
  this.turnHandlers = h;
1736
1912
  let skipped;
1913
+ const speed = target ? { target } : undefined;
1737
1914
  try {
1738
- await this.compactNowInner();
1915
+ await this.compactNowInner(speed);
1739
1916
  }
1740
1917
  catch {
1741
1918
  skipped = "summarizer_error"; // the turn still runs; the window-fill gate stays the backstop
@@ -1745,8 +1922,26 @@ export class Session {
1745
1922
  const after = this.requestEstimate();
1746
1923
  this.telemetry.record({ type: "compaction", before, after, trigger: "decode", tps: Math.round(due.tps * 10) / 10, floorTps: due.floorTps, ...(skipped ? { skipped } : {}) });
1747
1924
  h.onCompactionEnd?.({ before, after });
1925
+ if (speed && !speed.failed && !skipped)
1926
+ this.noteSpeedTarget(speed.target, after, h);
1748
1927
  }
1749
1928
  }
1929
+ noteSpeedTarget(target, after, h) {
1930
+ if (after <= target) {
1931
+ this.speedRearmAt = undefined;
1932
+ return;
1933
+ }
1934
+ this.speedRearmAt = after + SPEED_REARM_TOKENS;
1935
+ if (this.speedMissTold)
1936
+ return;
1937
+ this.speedMissTold = true;
1938
+ const floor = fixedRequestTokens({ ctxWindow: this.effectiveContext(), systemPrompt: this.sys(), tools: this.allSchemas(), meter: globalTokenMeter, meterKey: this.meterKey(), summarize: this.summarizeEvicted });
1939
+ h.onSpeedTargetMissed?.({ target, after, floor });
1940
+ }
1941
+ clearSpeedMiss() {
1942
+ this.speedRearmAt = undefined;
1943
+ this.speedMissTold = false;
1944
+ }
1750
1945
  /** The front door (engine/front-door.ts). On the default model and MOA, the gateway answers a message its classifier
1751
1946
  * is confident needs no tools with its fast model in this session's voice; the reply joins the conversation like any
1752
1947
  * other. Returns null to run the turn as usual: the gateway says work (the owner sees its status line at once), it
@@ -1914,9 +2109,13 @@ export class Session {
1914
2109
  this.referenceNote = "";
1915
2110
  if (carry)
1916
2111
  text = `${carry}\n\n${text}`;
2112
+ if (this.memoryNote)
2113
+ text = `${text}\n\n${this.memoryNote}`; // after the owner's words: a leading note would mark the message as the engine's
2114
+ this.memoryNote = "";
1917
2115
  const turn = { text, task, convoStart, t0: _t0 };
1918
2116
  this.inflight = turn;
1919
2117
  const turnModelId = routeLabel ?? this.modelId; // the MoA specialist's own id, else the /model pick
2118
+ const shape = { toolRounds: 0, multiCallRounds: 0, subAgentCalls: 0 }; // for the turn's telemetry record
1920
2119
  try {
1921
2120
  const res = await runTurn(text, this.convo, {
1922
2121
  ownerText,
@@ -1963,7 +2162,14 @@ export class Session {
1963
2162
  onToolResult: h.onToolResult,
1964
2163
  onToolCallStart: h.onToolCallStart,
1965
2164
  onToolDraft: h.onToolDraft,
1966
- onToolBatch: h.onToolBatch,
2165
+ onToolBatch: (events, durationMs) => {
2166
+ shape.toolRounds++;
2167
+ if (events.length > 1)
2168
+ shape.multiCallRounds++;
2169
+ shape.subAgentCalls += events.filter((e) => DELEGATION.has(e.name)).length;
2170
+ h.onToolBatch?.(events, durationMs);
2171
+ },
2172
+ batchHints: !this.background,
1967
2173
  onAutoContinue: h.onAutoContinue,
1968
2174
  onCacheStats: h.onCacheStats,
1969
2175
  onServed: h.onServed,
@@ -2018,7 +2224,7 @@ export class Session {
2018
2224
  // The conversation knows the mode only once the carried note is in it (a fast-start rewrite sends the raw text).
2019
2225
  if (mode.note && this.convo.all.slice(convoStart).some((m) => m.role === "user" && typeof m.content === "string" && m.content.includes(mode.note)))
2020
2226
  this.planReviewTold = mode.on;
2021
- this.telemetry.record({ type: "turn", rounds: res.rounds, toolCalls: res.toolCalls, interrupted: false, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct(), stopReason: res.stopReason });
2227
+ this.telemetry.record({ type: "turn", ...shape, model: turnModelId, rounds: res.rounds, toolCalls: res.toolCalls, interrupted: false, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct(), stopReason: res.stopReason });
2022
2228
  // MOA phase-0 ROUTE SHADOW (observability ONLY — routing is untouched): OPT-IN with KODE_MOA_SHADOW=1 (was on
2023
2229
  // by default until 0.1.334). Its classifier call goes to the SAME endpoint as the turn, and on a single-slot
2024
2230
  // llama-server (Cortana, --parallel 1) that 8-token call evicted the session's cached prompt after every turn:
@@ -2088,7 +2294,7 @@ export class Session {
2088
2294
  }
2089
2295
  catch (e) {
2090
2296
  if (e instanceof TurnAbortedError) {
2091
- this.telemetry.record({ type: "turn", rounds: 0, toolCalls: 0, interrupted: true, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct() });
2297
+ this.telemetry.record({ type: "turn", ...shape, rounds: 0, toolCalls: 0, interrupted: true, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct() });
2092
2298
  const r = this.interruptedRecord(turn); // an esc is how the owner usually ends a loop: the loop still teaches
2093
2299
  const cfg = this.selfImproveCfg();
2094
2300
  if (r)
@@ -29,6 +29,8 @@ export const WEB_SEARCH = set("web_search", "deep_research");
29
29
  export const WEB_FETCH = set("web_fetch", "browser", "browser_read", "http_request");
30
30
  /** Everything that only looks something up: the "reads" a sub-agent's activity counters add up. */
31
31
  export const LOOKUP = set(FILE_READ, "list_directory", LOCAL_SEARCH, WEB_SEARCH, WEB_FETCH);
32
+ /** Reads worth sending together: one of these alone, round after round, draws the batching note (engine/batch-hints.ts). */
33
+ export const BATCHABLE_READ = set(FILE_READ, "list_directory", LOCAL_SEARCH, WEB_SEARCH, "web_fetch", "git_status");
32
34
  /** Read-only tools: the same call returning the same result again is no new information. */
33
35
  export const IDEMPOTENT = set("file_read", "read_files", "search", "grep_search", "list_directory", "find_files", "locate", "web_search", "web_fetch", "git_status", "memory_search", "session_search", "session_read", "skill_catalog", "skill_fetch", "skill_list");
34
36
  // ── Plan, agents, polling ─────────────────────────────────────────────────────────────────────────────────
@@ -94,10 +94,13 @@ export function withDeferred(base, st) {
94
94
  // Promise.all barrier made base calls wait for every meta first. Now: search/describe classify
95
95
  // read, tool_call is an exclusive barrier (it can invoke ANYTHING downstream), pass-through
96
96
  // keeps the chain's truth. sched is exposed so any outer wrapper propagates it.
97
+ // No meta call: the chain below owns the whole round (its batch ids, its gates).
98
+ if (!calls.some((c) => DEFERRED_META_NAMES.includes(c.name)))
99
+ return base.executeParallel(calls, onSettle, signal, onStart);
97
100
  return runBatch(calls, {
98
- classify: (n) => (n === "tool_call" ? "barrier"
101
+ classify: (n, a) => (n === "tool_call" ? "barrier"
99
102
  : n === "tool_search" || n === "tool_describe" ? "read"
100
- : base.sched ? base.sched.classify(n) : "write"),
103
+ : base.sched ? base.sched.classify(n, a) : "write"),
101
104
  keys: (n, a) => (base.sched ? base.sched.keys(n, a) : defaultKeys(n, a)),
102
105
  runOne: (c, report) => (DEFERRED_META_NAMES.includes(c.name)
103
106
  ? runMeta(c.name, c.args, report) : base.execute(c.name, c.args, report)),
@@ -108,9 +111,9 @@ export function withDeferred(base, st) {
108
111
  });
109
112
  },
110
113
  sched: {
111
- classify: (n) => (n === "tool_call" ? "barrier"
114
+ classify: (n, a) => (n === "tool_call" ? "barrier"
112
115
  : n === "tool_search" || n === "tool_describe" ? "read"
113
- : base.sched ? base.sched.classify(n) : "write"),
116
+ : base.sched ? base.sched.classify(n, a) : "write"),
114
117
  keys: (n, a) => (base.sched ? base.sched.keys(n, a) : defaultKeys(n, a)),
115
118
  },
116
119
  };
@@ -281,15 +284,17 @@ export function withNativeDeferred(base, cat) {
281
284
  return base.execute(target, toolArgs, report);
282
285
  };
283
286
  const isMeta = (n) => NATIVE_META_NAMES.includes(n);
284
- const classify = (n) => (n === "tool_call" ? "barrier"
287
+ const classify = (n, a) => (n === "tool_call" ? "barrier"
285
288
  : n === "tool_search" ? "read"
286
- : base.sched ? base.sched.classify(n) : "write");
289
+ : base.sched ? base.sched.classify(n, a) : "write");
287
290
  const keys = (n, a) => (base.sched ? base.sched.keys(n, a) : defaultKeys(n, a));
288
291
  return {
289
292
  async execute(name, args, report) {
290
293
  return isMeta(name) ? runMeta(name, args, report) : base.execute(name, args, report);
291
294
  },
292
295
  async executeParallel(calls, onSettle, signal, onStart) {
296
+ if (!calls.some((c) => isMeta(c.name)))
297
+ return base.executeParallel(calls, onSettle, signal, onStart);
293
298
  return runBatch(calls, {
294
299
  classify, keys,
295
300
  runOne: (c, report) => (isMeta(c.name) ? runMeta(c.name, c.args, report) : base.execute(c.name, c.args, report)),