@0perator/operator 0.1.352 → 0.1.354
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp/agent.js +4 -2
- package/dist/acp/tool-map.js +5 -4
- package/dist/autonomy/delegate.js +55 -2
- package/dist/autonomy/headless.js +4 -1
- package/dist/autonomy/session-factory.js +1 -0
- package/dist/background/index.js +86 -10
- package/dist/background/notices.js +16 -4
- package/dist/cli.js +1072 -178
- package/dist/config/home.js +6 -0
- package/dist/config/memory-sections.js +92 -0
- package/dist/config/persona.js +144 -26
- package/dist/config/settings.js +15 -4
- package/dist/consolidation/scheduler.js +9 -2
- package/dist/consolidation/sleep.js +39 -278
- package/dist/engine/agent.js +547 -92
- package/dist/engine/anthropic-chat.js +13 -2
- package/dist/engine/aurora.js +135 -30
- package/dist/engine/batch-scheduler.js +27 -3
- package/dist/engine/compaction.js +12 -5
- package/dist/engine/continuation.js +51 -22
- package/dist/engine/contract.js +1 -1
- package/dist/engine/decision-points.js +7 -1
- package/dist/engine/front-door.js +59 -0
- package/dist/engine/grandmaster.js +13 -1
- package/dist/engine/loop-guard.js +694 -0
- package/dist/engine/net-error.js +2 -1
- package/dist/engine/owner-act.js +52 -0
- package/dist/engine/selfheal.js +48 -0
- package/dist/engine/verify-gate.js +52 -0
- package/dist/flywheel/processor.js +3 -1
- package/dist/flywheel/srft.js +8 -4
- package/dist/hooks/index.js +12 -8
- package/dist/mcp/index.js +9 -4
- package/dist/permissions/index.js +32 -11
- package/dist/permissions/modes.js +42 -0
- package/dist/permissions/plan-review.js +100 -0
- package/dist/permissions/policy.js +16 -5
- package/dist/permissions/signature.js +8 -3
- package/dist/remote/safe-commands.js +1 -1
- package/dist/router/read-rates.js +152 -0
- package/dist/selfimprove/backfill.js +174 -0
- package/dist/selfimprove/index.js +146 -57
- package/dist/selfimprove/lessons.js +429 -0
- package/dist/selfimprove/sync.js +58 -0
- package/dist/session.js +375 -31
- package/dist/skills/finder.js +219 -0
- package/dist/tools/deferred.js +28 -18
- package/dist/tools/executor.js +7 -3
- package/dist/tools/registry.js +34 -4
- package/dist/ui/ActivitySpinner.js +21 -12
- package/dist/ui/App.js +107 -30
- package/dist/ui/ApprovalPrompt.js +5 -3
- package/dist/ui/ArtifactPicker.js +3 -3
- package/dist/ui/BgPanel.js +105 -5
- package/dist/ui/Composer.js +85 -9
- package/dist/ui/PlanPane.js +72 -8
- package/dist/ui/QuestionPrompt.js +6 -4
- package/dist/ui/SecretPrompt.js +8 -3
- package/dist/ui/SessionPicker.js +2 -2
- package/dist/ui/SkillFinder.js +153 -0
- package/dist/ui/StatusRule.js +5 -2
- package/dist/ui/SummaryCard.js +3 -1
- package/dist/ui/ThinkingSpinner.js +11 -2
- package/dist/ui/ToolBatch.js +11 -2
- package/dist/ui/ToolStep.js +36 -13
- package/dist/ui/Transcript.js +13 -2
- package/dist/ui/actNow.js +61 -0
- package/dist/ui/batchLine.js +165 -0
- package/dist/ui/conversations.js +154 -0
- package/dist/ui/decodeHealth.js +77 -0
- package/dist/ui/expand.js +17 -0
- package/dist/ui/fit.js +40 -0
- package/dist/ui/fitTail.js +14 -0
- package/dist/ui/fold.js +149 -0
- package/dist/ui/format.js +46 -2
- package/dist/ui/liveTools.js +163 -13
- package/dist/ui/modelPicker.js +78 -6
- package/dist/ui/nextStep.js +103 -0
- package/dist/ui/pending.js +57 -0
- package/dist/ui/phase.js +105 -0
- package/dist/ui/planExit.js +0 -5
- package/dist/ui/progressbar.js +4 -26
- package/dist/ui/readForecast.js +44 -0
- package/dist/ui/readProgress.js +119 -0
- package/dist/ui/reportLine.js +62 -0
- package/dist/ui/slashCommands.js +1 -1
- package/dist/ui/theme.js +1 -0
- package/dist/ui/turnFlow.js +72 -0
- package/dist/ui/turnLedger.js +121 -0
- package/dist/ui/turnScope.js +11 -0
- package/dist/util/slash.js +18 -0
- package/package.json +1 -1
package/dist/session.js
CHANGED
|
@@ -6,7 +6,7 @@ import { recordTruncation } from "./observability/blackbox.js";
|
|
|
6
6
|
import { Conversation, placeSessionContext, SESSION_CONTEXT_OPEN, SESSION_CONTEXT_CLOSE } from "./engine/messages.js";
|
|
7
7
|
import { scratchDirFor } from "./config/scratch.js";
|
|
8
8
|
import { chat, health, reachable, requiresOperatorToken, operatorTrustedUrl } from "./engine/aurora.js";
|
|
9
|
-
import { compact, fitToWindow, turnStarts, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent, renderAnchorIndex, verbatimUserTail, applyAnchorVerification } from "./engine/compaction.js";
|
|
9
|
+
import { compact, compactionSplit, fitToWindow, turnStarts, SUMMARY_INSTRUCTION, stripTrailingOrphanToolCall, pickSummaryContent, renderAnchorIndex, verbatimUserTail, applyAnchorVerification } from "./engine/compaction.js";
|
|
10
10
|
import { globalTokenMeter, endpointKey } from "./engine/token-meter.js";
|
|
11
11
|
import { spillToolOutput } from "./tools/tool-output-spill.js"; // GW-10-COMPLETE: node-side spill sink
|
|
12
12
|
import { engineRouter } from "./engine/router-adapter.js";
|
|
@@ -23,19 +23,26 @@ import { operatorAgentPersona } from "./config/operator-harness.js";
|
|
|
23
23
|
import { modelRegistry, findModel, selectModel, visibleModels, endpointBase, profileEndpoint, fmtCtx, MIN_CONTEXT_PIN, DEFAULT_MODEL_ID, LEAN_HARNESS_CTX } from "./router/models.js";
|
|
24
24
|
import { probeServedCtx, usableCtx } from "./router/discovery.js";
|
|
25
25
|
import { FAST_START_INSTRUCTION, parseFastStartReply } from "./engine/fast-start.js";
|
|
26
|
+
import { askFrontDoor, recentTurns } from "./engine/front-door.js";
|
|
26
27
|
import { getByoToken, hasByoToken } from "./auth/byo.js";
|
|
27
28
|
import { Executor } from "./tools/executor.js";
|
|
28
|
-
import { toSchemas, registry, disposeShellSessionKey, requestShellDetach, cloudAgentToolsFor, renderActiveTasks } from "./tools/registry.js";
|
|
29
|
+
import { toSchemas, registry, disposeShellSessionKey, requestShellDetach, cloudAgentToolsFor, renderActiveTasks, getAgentTasks, taskPlanRevision, openTaskCount } from "./tools/registry.js";
|
|
29
30
|
import { isFeatureEnabled } from "./config/features.js";
|
|
30
31
|
import { MemoryStore } from "./memory/index.js";
|
|
31
32
|
import { McpHub, withMcp } from "./mcp/index.js";
|
|
32
33
|
import { deferredEnabled, deferredRequestSchemas, deferredState, withDeferred, nativeCatalog, setNativeCatalogMcp, withNativeDeferred } from "./tools/deferred.js";
|
|
33
34
|
import { withPermissions, PermissionPolicy } from "./permissions/index.js";
|
|
35
|
+
import { PlanApproval, planReviewOptions, planReviewReply, riskClasses } from "./permissions/plan-review.js";
|
|
36
|
+
import { AUTONOMOUS_MODE_ON, AUTONOMOUS_MODE_OFF } from "./config/persona.js";
|
|
34
37
|
import { withHooks } from "./hooks/index.js";
|
|
38
|
+
import { servedTask } from "./engine/loop-guard.js";
|
|
35
39
|
import { Telemetry } from "./observability/index.js";
|
|
36
|
-
import { runSelfImprove } from "./selfimprove/index.js";
|
|
40
|
+
import { loopMentorPair, recordMentorPair, recordRecoveryLesson, runSelfImprove } from "./selfimprove/index.js";
|
|
41
|
+
import { runSelfImproveSync } from "./selfimprove/sync.js";
|
|
42
|
+
import { isSubagentBrief } from "./selfimprove/lessons.js";
|
|
37
43
|
import { RollingSummarizer } from "./engine/rolling-summary.js";
|
|
38
44
|
import { decisionPointsEnabled } from "./engine/decision-points.js";
|
|
45
|
+
import { OwnerAct } from "./engine/owner-act.js";
|
|
39
46
|
import { createSleepScheduler } from "./consolidation/scheduler.js";
|
|
40
47
|
/** The system-prompt directive for an extended-reasoning mode ("" when off). The owner watches the model's
|
|
41
48
|
* reasoning stream live (dim, above the answer) and re-reads it in scrollback, so /think asks the model to
|
|
@@ -211,10 +218,7 @@ function makeStopTool(handler) {
|
|
|
211
218
|
},
|
|
212
219
|
};
|
|
213
220
|
}
|
|
214
|
-
|
|
215
|
-
// the chosen option back as the tool result. safe:false (an interaction, not a speculative read). The
|
|
216
|
-
// handler (the shell) renders the prompt and blocks until the owner answers.
|
|
217
|
-
function makeAskTool(handler) {
|
|
221
|
+
function makeAskTool(handler, review) {
|
|
218
222
|
return {
|
|
219
223
|
name: "ask_user",
|
|
220
224
|
safe: false,
|
|
@@ -224,13 +228,16 @@ function makeAskTool(handler) {
|
|
|
224
228
|
" step. DON'T ask for routine work (a typo, a small clear edit, a bug you found, a check) or what the code or" +
|
|
225
229
|
" request answers. Give 2-4 concrete options, the recommended one FIRST labelled \"(recommended)\", each a " +
|
|
226
230
|
"short line; the owner can always type their own. Then proceed. multiSelect:true when options are not " +
|
|
227
|
-
"exclusive."
|
|
231
|
+
"exclusive. planReview:true is Autonomous mode's review of the plan in the task list: the options become " +
|
|
232
|
+
"Approve / Adjust / Cancel, and risks names each money / prod / destructive class a step needs.",
|
|
228
233
|
parameters: {
|
|
229
234
|
type: "object",
|
|
230
235
|
properties: {
|
|
231
236
|
question: { type: "string", description: "the decision, one sentence" },
|
|
232
237
|
options: { type: "array", items: { type: "string" }, description: "2-4 concrete choices, recommended first (labelled \"(recommended)\")." },
|
|
233
238
|
multiSelect: { type: "boolean", description: "allow several choices (default false)" },
|
|
239
|
+
planReview: { type: "boolean", description: "review the plan in the task list (Autonomous mode); options are set for you" },
|
|
240
|
+
risks: { type: "array", items: { type: "string", enum: ["money", "prod", "destructive"] }, description: "with planReview: each risky class a step needs" },
|
|
234
241
|
},
|
|
235
242
|
required: ["question", "options"],
|
|
236
243
|
},
|
|
@@ -240,6 +247,24 @@ function makeAskTool(handler) {
|
|
|
240
247
|
const multiSelect = args.multiSelect === true || args.allowMultiple === true;
|
|
241
248
|
if (!question)
|
|
242
249
|
return "error: ask_user needs a question";
|
|
250
|
+
if (args.planReview === true) {
|
|
251
|
+
if (review && !review.planSteps())
|
|
252
|
+
return "error: planReview reviews the task list, and it is empty — task_add the plan's steps first, then ask";
|
|
253
|
+
const risks = riskClasses(args.risks);
|
|
254
|
+
const choices = planReviewOptions(risks);
|
|
255
|
+
const askedAt = review?.approval.currentRevision();
|
|
256
|
+
const answer = await handler(question, choices);
|
|
257
|
+
if (!review?.on())
|
|
258
|
+
return `The user replied: ${answer}`;
|
|
259
|
+
const r = planReviewReply(answer, choices, risks);
|
|
260
|
+
if (!r.approved) {
|
|
261
|
+
review.approval.clear();
|
|
262
|
+
return r.reply;
|
|
263
|
+
}
|
|
264
|
+
if (review.approval.approve(risks, askedAt))
|
|
265
|
+
return r.reply;
|
|
266
|
+
return "The user approved the plan as it was shown, but a step was added while the review was open, so the approval does not cover the plan now. Ask for review again (ask_user with planReview: true) with the steps as they stand.";
|
|
267
|
+
}
|
|
243
268
|
if (options.length < 2)
|
|
244
269
|
return "error: ask_user needs at least 2 options";
|
|
245
270
|
const answer = await handler(question, options.slice(0, 4), multiSelect);
|
|
@@ -314,10 +339,13 @@ export class Session {
|
|
|
314
339
|
servedByBase = new Map(); // raw n_ctx learned per base (probeServedContext)
|
|
315
340
|
moaConfig;
|
|
316
341
|
onDemand;
|
|
342
|
+
frontDoor;
|
|
343
|
+
frontDoorRoute; // the gateway's call on THIS turn (null = no answer; undefined = not asked), read by sendMoa
|
|
317
344
|
classifier;
|
|
318
345
|
fastStartConfig;
|
|
319
346
|
fastStartEnabled;
|
|
320
347
|
modelId = DEFAULT_MODEL_ID; // active /model selection
|
|
348
|
+
turnFellBack = false; // this turn's model fallback took over (turnModel): its rounds run on the default row
|
|
321
349
|
executor;
|
|
322
350
|
shellKey; // this session's persistent-shell key (see disposeShell)
|
|
323
351
|
localSchemas;
|
|
@@ -345,6 +373,12 @@ export class Session {
|
|
|
345
373
|
liveAgents;
|
|
346
374
|
slotSharers;
|
|
347
375
|
wakeTurn = false; // the turn in flight was started by the shell to deliver a report / job notice, not typed by the owner
|
|
376
|
+
maxLessons; // lines the global lessons section keeps — the same cap sleep consolidation curates to
|
|
377
|
+
lastRequest = ""; // what the owner last typed (a mentor-wake: its subject) — the task a wake turn serves (flywheel row `task`, loop lessons)
|
|
378
|
+
inflight; // the turn running now — what an interrupt or a signal records (recordInterruptedTurnSync)
|
|
379
|
+
selfImproveQueue = Promise.resolve(); // the self-improvement writes, in order (learn)
|
|
380
|
+
turnThinkOff = false; // this one turn runs enable_thinking:false ("continue, think off"); the system prompt is untouched
|
|
381
|
+
ownerAct = new OwnerAct(); // ctrl+y — "use what you have" (engine/owner-act.ts)
|
|
348
382
|
hooks;
|
|
349
383
|
cwd;
|
|
350
384
|
unattended;
|
|
@@ -353,6 +387,7 @@ export class Session {
|
|
|
353
387
|
compactionThreshold;
|
|
354
388
|
compactionCeilingTokens;
|
|
355
389
|
background;
|
|
390
|
+
owner;
|
|
356
391
|
temperature;
|
|
357
392
|
ctrl = null;
|
|
358
393
|
memory;
|
|
@@ -366,12 +401,16 @@ export class Session {
|
|
|
366
401
|
* from anywhere: the pending promise is swapped and failures were already swallowed by the module. */
|
|
367
402
|
async flushRouteShadow() { const p = this._shadowPending; this._shadowPending = Promise.resolve(); await p; }
|
|
368
403
|
decisionPoints;
|
|
404
|
+
planReview = false; // Autonomous mode: plan reviews instead of per-command prompts (setOperatingMode)
|
|
405
|
+
planReviewTold = false; // what the conversation last told the model about Autonomous mode (modeCarry)
|
|
406
|
+
planApproval = new PlanApproval(taskPlanRevision, openTaskCount); // the owner's standing plan approval, read by the policy
|
|
369
407
|
planMode = false; // /plan: research read-only + propose a plan, no mutations until the owner approves
|
|
370
408
|
thinkMode = "off"; // /think, /ultrathink — extended reasoning
|
|
371
409
|
recalled = false;
|
|
372
410
|
activeSkillBlock = ""; // capped skill instructions, carried in the conversation (pinnedSkill)
|
|
373
411
|
activeSkillName = ""; // name of the active skill (for status display)
|
|
374
412
|
skillNote = ""; // one-shot "stop following skill X" for the owner's next message (/skill off)
|
|
413
|
+
referenceNote = ""; // one-shot quoted third-party text for the owner's next message (referenceOnce)
|
|
375
414
|
// Rolling summarizer — instant compaction (Engine doc #2). A background process continuously
|
|
376
415
|
// maintains a structured session-memory/summary.md during the session. When compact() fires,
|
|
377
416
|
// it loads the pre-written summary — /compact went from up to 2 minutes to instant.
|
|
@@ -418,7 +457,7 @@ export class Session {
|
|
|
418
457
|
if (cfg.stopAgent)
|
|
419
458
|
reg.set("stop_agent", makeStopTool(cfg.stopAgent));
|
|
420
459
|
if (cfg.askUser)
|
|
421
|
-
reg.set("ask_user", makeAskTool(cfg.askUser));
|
|
460
|
+
reg.set("ask_user", makeAskTool(cfg.askUser, { on: () => this.planReview, approval: this.planApproval, planSteps: () => getAgentTasks().length }));
|
|
422
461
|
this.decisionPoints = decisionPointsEnabled(cfg.decisionPoints);
|
|
423
462
|
reg.set("self_status", makeSelfStatusTool(() => ({
|
|
424
463
|
model: this.currentModel(),
|
|
@@ -459,6 +498,7 @@ export class Session {
|
|
|
459
498
|
this.isOwner = (cfg.eventActor?.tier ?? "admin") === "admin"; // set before the startup setModel so a persisted owner-only activeModel resolves for the owner
|
|
460
499
|
this.moaConfig = cfg.moa;
|
|
461
500
|
this.onDemand = cfg.onDemand;
|
|
501
|
+
this.frontDoor = cfg.frontDoor;
|
|
462
502
|
this.classifier = cfg.classifier;
|
|
463
503
|
this.fastStartConfig = cfg.fastStart;
|
|
464
504
|
this.fastStartEnabled = isFeatureEnabled("fastStart", { features: cfg.features }) && !!cfg.fastStart;
|
|
@@ -484,6 +524,7 @@ export class Session {
|
|
|
484
524
|
this.compactionThreshold = cfg.compactionThreshold;
|
|
485
525
|
this.compactionCeilingTokens = cfg.compactionCeilingTokens;
|
|
486
526
|
this.background = cfg.background ?? false;
|
|
527
|
+
this.owner = cfg.owner;
|
|
487
528
|
this.temperature = cfg.temperature ?? 0.7;
|
|
488
529
|
this.memory = cfg.memory ?? new MemoryStore();
|
|
489
530
|
this.wantRecall = cfg.recall ?? true;
|
|
@@ -491,7 +532,8 @@ export class Session {
|
|
|
491
532
|
this.hub = cfg.mcpHub;
|
|
492
533
|
if (this.hub)
|
|
493
534
|
this.hub.spillSink = spillToolOutput; // GW-10-COMPLETE: offload huge MCP results too
|
|
494
|
-
this.
|
|
535
|
+
this.planReview = cfg.planReview === true;
|
|
536
|
+
this.permissionCfg = this.underReview(cfg.permissions ?? { mode: "bypass" });
|
|
495
537
|
this.policy = new PermissionPolicy(this.permissionCfg);
|
|
496
538
|
this.approve = cfg.approve;
|
|
497
539
|
this.telemetry = new Telemetry(cfg.telemetry);
|
|
@@ -499,6 +541,7 @@ export class Session {
|
|
|
499
541
|
this.eventActor = cfg.eventActor;
|
|
500
542
|
this.sessionId = cfg.sessionId;
|
|
501
543
|
this.tools = this.buildTools(); // local-only until first-turn MCP discovery rebinds it
|
|
544
|
+
this.maxLessons = cfg.sleepConsolidation?.maxLessonsPerFile;
|
|
502
545
|
// Initialize sleep-time consolidation if enabled (via settings or env).
|
|
503
546
|
const sleepEnabled = process.env.KODE_SLEEP_CONSOLIDATION === "1" || cfg.sleepConsolidation?.enabled;
|
|
504
547
|
if (sleepEnabled) {
|
|
@@ -613,6 +656,37 @@ export class Session {
|
|
|
613
656
|
currentPermissionMode() {
|
|
614
657
|
return this.policy.currentMode();
|
|
615
658
|
}
|
|
659
|
+
/** The interactive operating mode's policy (permissions/modes.ts): its permission config and whether Autonomous plan
|
|
660
|
+
* review is on. Plan mode stays separate (setPlanMode) and takes precedence while active. The system prompt does not
|
|
661
|
+
* change; the next owner message carries the switch (modeCarry). Leaving plan review keeps a standing approval; it
|
|
662
|
+
* ends when the plan changes. */
|
|
663
|
+
setOperatingMode(m) {
|
|
664
|
+
this.planReview = m.planReview;
|
|
665
|
+
// keep what /allow added this session: the mode's config is built from the startup settings, which lack it
|
|
666
|
+
const allow = [...new Set([...(m.permissions.allow ?? []), ...(this.permissionCfg.allow ?? [])])];
|
|
667
|
+
this.permissionCfg = this.underReview(allow.length ? { ...m.permissions, allow } : m.permissions);
|
|
668
|
+
this.policy = new PermissionPolicy(this.permissionCfg);
|
|
669
|
+
this.tools = this.buildTools();
|
|
670
|
+
}
|
|
671
|
+
inPlanReview() {
|
|
672
|
+
return this.planReview;
|
|
673
|
+
}
|
|
674
|
+
/** Autonomous mode's rules ride the conversation, like an active skill, so the system prompt stays byte-stable: the
|
|
675
|
+
* owner's next message after a switch carries the rules (on) or the note that they no longer apply (off). */
|
|
676
|
+
modeCarry() {
|
|
677
|
+
const on = this.planReview && !this.planMode;
|
|
678
|
+
return { note: on === this.planReviewTold ? "" : engineNote(on ? AUTONOMOUS_MODE_ON : AUTONOMOUS_MODE_OFF), on };
|
|
679
|
+
}
|
|
680
|
+
/** What a compaction summary must keep: the active skill, and Autonomous mode's rules while they apply. */
|
|
681
|
+
pinned() {
|
|
682
|
+
const mode = this.planReview && !this.planMode ? engineNote(AUTONOMOUS_MODE_ON) : "";
|
|
683
|
+
return [this.activeSkillBlock, mode].filter(Boolean).join("\n\n") || undefined;
|
|
684
|
+
}
|
|
685
|
+
/** `cfg` with this session's plan approval attached while plan review is on, and detached otherwise. */
|
|
686
|
+
underReview(cfg) {
|
|
687
|
+
const { planReview: _drop, ...rest } = cfg;
|
|
688
|
+
return this.planReview ? { ...rest, planReview: this.planApproval } : rest;
|
|
689
|
+
}
|
|
616
690
|
/** Set extended-reasoning mode (/think, /ultrathink). "think" re-enables Aurora's native reasoning for
|
|
617
691
|
* each turn; "ultrathink" also pushes for deeper step-by-step reasoning via the system prompt. */
|
|
618
692
|
setThinkMode(mode) {
|
|
@@ -636,6 +710,11 @@ export class Session {
|
|
|
636
710
|
this.skillNote = "";
|
|
637
711
|
return this.activeSkillBlock;
|
|
638
712
|
}
|
|
713
|
+
/** Third-party text the owner picked (the finder's unverified hub entries, skills/finder.ts quotedReference): it rides
|
|
714
|
+
* on the owner's next message once, as an engine note — never a standing directive, never pinned through a compaction. */
|
|
715
|
+
referenceOnce(text) {
|
|
716
|
+
this.referenceNote = engineNote(text);
|
|
717
|
+
}
|
|
639
718
|
deactivateSkill() {
|
|
640
719
|
if (this.activeSkillName)
|
|
641
720
|
this.skillNote = `[Skill '${this.activeSkillName}' is no longer active — stop following its instructions.]`;
|
|
@@ -672,6 +751,14 @@ export class Session {
|
|
|
672
751
|
meterKey() {
|
|
673
752
|
return endpointKey(this.lastBase ?? this.inner.base, this.lastModel ?? this.inner.model);
|
|
674
753
|
}
|
|
754
|
+
/** The tool executor a running turn holds: every call reads `this.tools` at that moment, so a mode switch mid-turn
|
|
755
|
+
* (/mode, /plan, Shift+Tab — each rebuilds `this.tools` with its policy) governs the turn's next tool call, not only
|
|
756
|
+
* the next turn. The running batch finishes under the policy it started with. */
|
|
757
|
+
liveTools = ((s) => ({
|
|
758
|
+
execute: (name, args) => s.tools.execute(name, args),
|
|
759
|
+
executeParallel: (calls, onSettle, signal) => s.tools.executeParallel(calls, onSettle, signal),
|
|
760
|
+
get sched() { return s.tools.sched; },
|
|
761
|
+
}))(this);
|
|
675
762
|
/** Full-request estimate (system + conversation + tool schemas) at the live endpoint's LEARNED
|
|
676
763
|
* chars/token — the one basis shared by the ctx% bar and the /compact freed math (SPEC §5). */
|
|
677
764
|
requestEstimate() {
|
|
@@ -679,6 +766,56 @@ export class Session {
|
|
|
679
766
|
const built = sys ? [{ role: "system", content: sys }, ...this.convo.all] : this.convo.all;
|
|
680
767
|
return globalTokenMeter.estimateRequestFor(this.meterKey(), built, this.allSchemas());
|
|
681
768
|
}
|
|
769
|
+
/** The full request as tokens (system + conversation + tool schemas), on the ctx% bar's calibrated basis — public, so
|
|
770
|
+
* the shell can price a re-read before it happens: the /model cost, the /think cost and the cold-read forecast. */
|
|
771
|
+
requestTokens() {
|
|
772
|
+
return this.requestEstimate();
|
|
773
|
+
}
|
|
774
|
+
/** What a /think toggle makes the next turn re-read: the think directive rides at the END of the system prompt, and
|
|
775
|
+
* chat templates put the tools and the conversation after it, so everything past the base system text misses the
|
|
776
|
+
* server's prefix cache. */
|
|
777
|
+
thinkRereadTokens() {
|
|
778
|
+
const base = this.sys();
|
|
779
|
+
const head = base ? globalTokenMeter.estimateRequestFor(this.meterKey(), [{ role: "system", content: base }], []) : 0;
|
|
780
|
+
return Math.max(0, this.requestEstimate() - head);
|
|
781
|
+
}
|
|
782
|
+
/** The re-read a switch to `modelId` costs: this conversation's whole request at THAT endpoint's learned chars/token
|
|
783
|
+
* (another server holds none of it in its prefix cache), and the window it has to fit. Undefined for an unknown id or
|
|
784
|
+
* a model with no endpoint of its own (moa spans several). */
|
|
785
|
+
rereadEstimate(modelId) {
|
|
786
|
+
const p = findModel(this.liveRegistry(), modelId);
|
|
787
|
+
if (p?.kind !== "single")
|
|
788
|
+
return undefined;
|
|
789
|
+
let base, model;
|
|
790
|
+
if (p.id === DEFAULT_MODEL_ID) {
|
|
791
|
+
const r = this.chain ?? this.inner;
|
|
792
|
+
base = r.base;
|
|
793
|
+
model = r.model;
|
|
794
|
+
}
|
|
795
|
+
else {
|
|
796
|
+
const ep = p.endpoints?.[0] ?? p.endpoint;
|
|
797
|
+
if (!ep)
|
|
798
|
+
return undefined;
|
|
799
|
+
base = endpointBase(ep);
|
|
800
|
+
model = p.endpointModels?.[0] ?? p.model ?? p.id;
|
|
801
|
+
}
|
|
802
|
+
const sys = this.sys();
|
|
803
|
+
const built = sys ? [{ role: "system", content: sys }, ...this.convo.all] : this.convo.all;
|
|
804
|
+
return { tokens: globalTokenMeter.estimateRequestFor(endpointKey(base, model), built, this.allSchemas()), window: p.ctx };
|
|
805
|
+
}
|
|
806
|
+
/** What /compact can promise before it runs (TUI A3.5 / A3.6): the request now, and AT MOST what is left after it — the
|
|
807
|
+
* last two turns verbatim (compactNow's minKeepTurns), the deterministic backstop compact() always appends (anchor
|
|
808
|
+
* index, the owner's own words, the pinned skill) and a summary capped at SUMMARY_MAX_TOKENS. An upper bound, never
|
|
809
|
+
* progress: fitToWindow may shed more. Null when there is nothing to evict. */
|
|
810
|
+
compactionEstimate() {
|
|
811
|
+
const split = compactionSplit(this.convo.all, 2);
|
|
812
|
+
if (!split?.evicted.length)
|
|
813
|
+
return null;
|
|
814
|
+
const backstop = { role: "user", content: `${renderAnchorIndex(split.evicted)}${verbatimUserTail(split.evicted)}${this.activeSkillBlock ? `\n\n${this.activeSkillBlock}` : ""}` };
|
|
815
|
+
const sys = this.sys();
|
|
816
|
+
const kept = [...(sys ? [{ role: "system", content: sys }] : []), backstop, ...split.kept];
|
|
817
|
+
return { before: this.requestEstimate(), afterMax: globalTokenMeter.estimateRequestFor(this.meterKey(), kept, this.allSchemas()) + SUMMARY_MAX_TOKENS, summaryMax: SUMMARY_MAX_TOKENS };
|
|
818
|
+
}
|
|
682
819
|
/** Estimated context usage of the live conversation against the window the engine runs on (the served limit
|
|
683
820
|
* under the owner's pin), 0-99. Calibrated: the meter's real ratio once observations land; exactly the old
|
|
684
821
|
* chars/4 prior cold. */
|
|
@@ -737,6 +874,18 @@ export class Session {
|
|
|
737
874
|
interrupt() {
|
|
738
875
|
this.ctrl?.abort();
|
|
739
876
|
}
|
|
877
|
+
/** ctrl+y — "use what you have": the twin of interrupt() that keeps the work. A live stream is cut and its partial
|
|
878
|
+
* kept; during the read it arms; during tools it applies before the next request. False when no turn runs. */
|
|
879
|
+
actNow() {
|
|
880
|
+
return !!this.ctrl && this.ownerAct.request();
|
|
881
|
+
}
|
|
882
|
+
/** The process is going down with a turn in flight (cli.tsx teardown — a signal, where nothing can be awaited): record it
|
|
883
|
+
* now, synchronously — its flywheel row and, when it looped, its lesson. No-op when idle or already recorded. */
|
|
884
|
+
recordInterruptedTurnSync() {
|
|
885
|
+
const r = this.inflight && this.interruptedRecord(this.inflight);
|
|
886
|
+
if (r)
|
|
887
|
+
runSelfImproveSync(this.selfImproveCfg(), r);
|
|
888
|
+
}
|
|
740
889
|
// ── Slash-command surface (used by the shell) ──────────────────────────
|
|
741
890
|
/** Configured endpoints, for /endpoints. */
|
|
742
891
|
endpoints() {
|
|
@@ -759,13 +908,22 @@ export class Session {
|
|
|
759
908
|
* and /compact used to report "nothing to compact yet" while the session was clearly over budget. So we
|
|
760
909
|
* ALSO fitToWindow: elide the largest tool outputs in place until it fits the ACTIVE endpoint's (learned)
|
|
761
910
|
* window. Returns tokens, not message count, because elision reduces chars without dropping messages. */
|
|
762
|
-
async compactNow() {
|
|
911
|
+
async compactNow(h) {
|
|
912
|
+
this.turnHandlers = h;
|
|
913
|
+
try {
|
|
914
|
+
return await this.compactNowInner();
|
|
915
|
+
}
|
|
916
|
+
finally {
|
|
917
|
+
this.turnHandlers = undefined;
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
async compactNowInner() {
|
|
763
921
|
const opts = {
|
|
764
922
|
ctxWindow: this.effectiveContext(),
|
|
765
923
|
systemPrompt: this.sys(),
|
|
766
924
|
summarize: this.summarize,
|
|
767
925
|
preservedState: renderActiveTasks() ?? undefined, // the active task list rides with the summary
|
|
768
|
-
pinnedContext: this.
|
|
926
|
+
pinnedContext: this.pinned(), // the active skill and Autonomous mode's rules ride the summary
|
|
769
927
|
minKeepTurns: 2,
|
|
770
928
|
tools: this.allSchemas(), // same full-request basis as the gate and the ctx% bar
|
|
771
929
|
meter: globalTokenMeter,
|
|
@@ -817,6 +975,8 @@ export class Session {
|
|
|
817
975
|
reset() {
|
|
818
976
|
this.convo.replaceAll([]);
|
|
819
977
|
this.rollingSummarizer.clear(); // clear the rolling summary on new session
|
|
978
|
+
this.planApproval.clear(); // a fresh conversation has no reviewed plan
|
|
979
|
+
this.planReviewTold = false; // …and has not been told the mode
|
|
820
980
|
}
|
|
821
981
|
/** Sleep-time consolidation — trigger memory reorganization. Returns the result. */
|
|
822
982
|
async consolidate() {
|
|
@@ -860,6 +1020,11 @@ export class Session {
|
|
|
860
1020
|
currentModel() {
|
|
861
1021
|
return this.modelId;
|
|
862
1022
|
}
|
|
1023
|
+
/** The model answering this turn — the /model pick, or the default row once the pick's fallback took the turn — so a
|
|
1024
|
+
* read or decode rate is credited to the model that did the work, never to the owner's pick. */
|
|
1025
|
+
answeringModel() {
|
|
1026
|
+
return this.turnFellBack ? DEFAULT_MODEL_ID : this.modelId;
|
|
1027
|
+
}
|
|
863
1028
|
/** The endpoint chain for a single-endpoint profile (/model, and the MoA specialist's fast path). */
|
|
864
1029
|
routerForProfile(profile) {
|
|
865
1030
|
// BYO connectors carry their vendor bearer (never the Operator token — see authHeaders scoping);
|
|
@@ -886,6 +1051,20 @@ export class Session {
|
|
|
886
1051
|
}));
|
|
887
1052
|
return new AuroraRouter(eps);
|
|
888
1053
|
}
|
|
1054
|
+
/** A turn's model as the owner reads it, and its fallback (runTurn's TurnModel): when every leg of another model
|
|
1055
|
+
* fails, or it keeps finishing with nothing, the default Aurora row answers that turn — the owner's choice stays, so
|
|
1056
|
+
* the next turn tries the chosen model first again. A row with `fallback: false` keeps its turns on its own legs. */
|
|
1057
|
+
turnModel(id) {
|
|
1058
|
+
const reg = this.liveRegistry();
|
|
1059
|
+
const profile = findModel(reg, id);
|
|
1060
|
+
if (profile?.kind !== "single")
|
|
1061
|
+
return undefined;
|
|
1062
|
+
const aurora = profile.id === DEFAULT_MODEL_ID || profile.fallback === false ? undefined : findModel(reg, DEFAULT_MODEL_ID);
|
|
1063
|
+
return {
|
|
1064
|
+
name: profile.label,
|
|
1065
|
+
fallback: aurora ? () => { this.turnFellBack = true; return { name: aurora.label, router: this.wrap(this.chain ?? this.routerForProfile(aurora)) }; } : undefined,
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
889
1068
|
/** Switch the active model (/model). A "single" profile rebuilds the router to point at that
|
|
890
1069
|
* endpoint — no server is started/stopped, this only changes which endpoint THIS session talks
|
|
891
1070
|
* to. "moa" has no endpoint of its own; send() special-cases it (sendMoa) instead. Returns an
|
|
@@ -935,6 +1114,8 @@ export class Session {
|
|
|
935
1114
|
if (!ok)
|
|
936
1115
|
return false;
|
|
937
1116
|
this.convo.replaceAll(msgs);
|
|
1117
|
+
this.planApproval.clear(); // another conversation: its plan was never reviewed here
|
|
1118
|
+
this.planReviewTold = false; // …and it has not been told the mode
|
|
938
1119
|
return true;
|
|
939
1120
|
}
|
|
940
1121
|
/** The fact-preserving summarizer: engine prompt + content||reasoning fallback (Aurora empties content). */
|
|
@@ -948,6 +1129,8 @@ export class Session {
|
|
|
948
1129
|
// different endpoint, guaranteeing a full cache miss (and possibly a wrong-context-window 400).
|
|
949
1130
|
lastBase;
|
|
950
1131
|
lastModel;
|
|
1132
|
+
/** The handlers of the turn in flight (or of /compact), so the summarizer can report its own read progress. */
|
|
1133
|
+
turnHandlers;
|
|
951
1134
|
summarize = async (span) => {
|
|
952
1135
|
// Cache-safe compaction (Anthropic's cache-safe forking). The evicted span is the OLDEST slice of the
|
|
953
1136
|
// live conversation, so [system + tools + span] is an exact PREFIX of the request the live turn just
|
|
@@ -988,6 +1171,9 @@ export class Session {
|
|
|
988
1171
|
// The summarize request rides the SAME leg's key, wire and chat path as the live turn: a vendor row (Claude, Gemini,
|
|
989
1172
|
// a free row) went to /v1/chat/completions with no key before, so a session on it could never compact.
|
|
990
1173
|
const leg = [...this.inner.list(), ...(this.chain?.list() ?? [])].find((e) => e.base === sumBase && e.model === sumModel);
|
|
1174
|
+
const onWrite = this.turnHandlers?.onCompactionWrite;
|
|
1175
|
+
let wrote = 0;
|
|
1176
|
+
const written = onWrite ? () => onWrite(++wrote) : undefined; // its writing, so the line moves on from "reading" (review F2)
|
|
991
1177
|
let r;
|
|
992
1178
|
try {
|
|
993
1179
|
r = await chat(messages, {
|
|
@@ -1002,6 +1188,10 @@ export class Session {
|
|
|
1002
1188
|
maxTokens: leg?.transport === "anthropic" ? SUMMARY_MAX_TOKENS_THINKING : SUMMARY_MAX_TOKENS,
|
|
1003
1189
|
temperature: 0,
|
|
1004
1190
|
background: this.background, // a sub-agent's compaction summarize also yields to the interactive main turn
|
|
1191
|
+
owner: "compaction",
|
|
1192
|
+
onPromptProgress: this.turnHandlers?.onPromptProgress, // the compaction line shows the summarizer's own measured read
|
|
1193
|
+
onDelta: written,
|
|
1194
|
+
onReasoning: written,
|
|
1005
1195
|
signal, // ESC during "compacting" must tear down THIS request too, not just the main generation stream —
|
|
1006
1196
|
// without it a compaction summarize (which can be a large request on a slow/deep endpoint) runs to
|
|
1007
1197
|
// completion after the user already hit esc. Null ctrl (background pass outside a turn) → timeout-only.
|
|
@@ -1200,11 +1390,19 @@ export class Session {
|
|
|
1200
1390
|
if (this.ctrl)
|
|
1201
1391
|
throw new Error("Session.send called while a turn is in flight — serialize turns (the shell queues input)");
|
|
1202
1392
|
this.wakeTurn = flags?.wake === true;
|
|
1393
|
+
if (!this.wakeTurn)
|
|
1394
|
+
this.lastRequest = servedTask(text);
|
|
1395
|
+
this.turnThinkOff = flags?.thinkOff === true;
|
|
1396
|
+
this.turnFellBack = false; // a new turn starts on the owner's model, whichever path answers it
|
|
1397
|
+
this.ownerAct.reset();
|
|
1203
1398
|
// Arm the interrupt controller BEFORE maybeRecall. The host flips status to "thinking" the instant send() is
|
|
1204
1399
|
// called, so an esc during first-turn memory recall / MCP discovery (which hit the network and can be slow)
|
|
1205
1400
|
// would otherwise no-op — this.ctrl was null until execute(). execute() reuses this same controller.
|
|
1206
1401
|
this.ctrl = new AbortController();
|
|
1207
1402
|
try {
|
|
1403
|
+
const front = await this.viaFrontDoor(text, h); // before onDemand: a message the fast model answers never loads Aurora
|
|
1404
|
+
if (front)
|
|
1405
|
+
return front;
|
|
1208
1406
|
if (this.onDemand && this.modelId === DEFAULT_MODEL_ID) {
|
|
1209
1407
|
const fresh = await this.onDemand(this.ctrl.signal);
|
|
1210
1408
|
if (fresh)
|
|
@@ -1226,8 +1424,37 @@ export class Session {
|
|
|
1226
1424
|
finally {
|
|
1227
1425
|
this.ctrl = null; // execute() nulls on its own path too; this also covers the maybeRecall-abort early return
|
|
1228
1426
|
this.wakeTurn = false;
|
|
1427
|
+
this.turnThinkOff = false;
|
|
1229
1428
|
}
|
|
1230
1429
|
}
|
|
1430
|
+
/** The front door (engine/front-door.ts). On the default model and MOA, the gateway answers a message its classifier
|
|
1431
|
+
* is confident needs no tools with its fast model in this session's voice; the reply joins the conversation like any
|
|
1432
|
+
* other. Returns null to run the turn as usual: the gateway says work (the owner sees its status line at once), it
|
|
1433
|
+
* has no opinion or no answer, or its fast model escalated. */
|
|
1434
|
+
async viaFrontDoor(text, h) {
|
|
1435
|
+
this.frontDoorRoute = undefined;
|
|
1436
|
+
const fd = this.frontDoor;
|
|
1437
|
+
const active = findModel(this.liveRegistry(), this.modelId);
|
|
1438
|
+
if (!fd || (this.modelId !== DEFAULT_MODEL_ID && active?.kind !== "orchestrated"))
|
|
1439
|
+
return null;
|
|
1440
|
+
const t0 = Date.now();
|
|
1441
|
+
// The gateway's front door is configured on the default model's route; `name` is the model as the owner knows it
|
|
1442
|
+
// (activeModelBlock), so a MOA session is MOA to the fast model too.
|
|
1443
|
+
const name = active ? `${active.label}${active.params ? ` ${active.params}` : ""}` : this.modelId;
|
|
1444
|
+
const d = await askFrontDoor(fd, { model: DEFAULT_MODEL_ID, name, messages: [...recentTurns(this.convo.all), { role: "user", content: text }] }, this.ctrl?.signal);
|
|
1445
|
+
if (this.ctrl?.signal.aborted)
|
|
1446
|
+
return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
|
|
1447
|
+
this.frontDoorRoute = d?.route ?? null;
|
|
1448
|
+
this.telemetry.record({ type: "front_door", outcome: !d ? "failed" : d.route === "direct" ? "answered" : d.route, ...(d?.route === "direct" && d.servedBy ? { servedBy: d.servedBy } : {}), ms: Date.now() - t0 });
|
|
1449
|
+
if (d?.route === "work")
|
|
1450
|
+
h.onTriage?.(d.line);
|
|
1451
|
+
if (d?.route !== "direct")
|
|
1452
|
+
return null;
|
|
1453
|
+
this.convo.user(text);
|
|
1454
|
+
this.convo.assistant(d.content);
|
|
1455
|
+
h.onDelta?.(d.content);
|
|
1456
|
+
return { content: d.content, rounds: 1, toolCalls: 0, interrupted: false, durationMs: Date.now() - t0 };
|
|
1457
|
+
}
|
|
1231
1458
|
/** MOA turn (engine/moa.ts): the planner takes the turn through the SAME runTurn loop as any turn (execute), on its
|
|
1232
1459
|
* own endpoint, with the planner brief in the system prompt — and every delegate_task in it defaults to the
|
|
1233
1460
|
* specialist. The brief is fixed per team, so the system prompt stays byte-stable across turns. */
|
|
@@ -1235,9 +1462,13 @@ export class Session {
|
|
|
1235
1462
|
const team = moaTeam(this.moaConfig); // setModel refuses to select "moa" without one
|
|
1236
1463
|
// The router (classifier/route.ts): a request it is confident needs no tools goes straight to the fast
|
|
1237
1464
|
// specialist — no planner round, no planner prefill. Anything else, or no answer from the router, is planned.
|
|
1238
|
-
|
|
1465
|
+
// With the front door on, the gateway already decided (viaFrontDoor): a message only gets here when it needs tools
|
|
1466
|
+
// (work, or a direct one its fast model escalated) or nothing answered, so it is planned, never sent to the
|
|
1467
|
+
// specialist with the full prompt.
|
|
1468
|
+
const fd = this.frontDoorRoute;
|
|
1469
|
+
const route = fd === undefined && this.classifier && this.classifier.mode !== "off" ? await routeTurn(text, this.classifier.endpoint) : null;
|
|
1239
1470
|
const specialist = route?.route === "direct" ? this.liveRegistry().find((m) => m.id === team.specialist && m.kind === "single") : undefined;
|
|
1240
|
-
this.telemetry.record({ type: "moa", planner: team.planner.id, specialist: team.specialist, route: specialist ? "direct" : route ? "planned" : "unrouted", pDirect: route?.pDirect });
|
|
1471
|
+
this.telemetry.record({ type: "moa", planner: team.planner.id, specialist: team.specialist, route: specialist ? "direct" : route || fd === "work" ? "planned" : "unrouted", pDirect: route?.pDirect });
|
|
1241
1472
|
if (specialist)
|
|
1242
1473
|
return this.execute(text, h, this.wrap(this.routerForProfile(specialist)), this.sysWithThink(), specialist.id);
|
|
1243
1474
|
const plannerRouter = this.wrap(new AuroraRouter([
|
|
@@ -1321,25 +1552,36 @@ export class Session {
|
|
|
1321
1552
|
// only if execute() is somehow entered without send() arming it (defensive — every caller goes via send).
|
|
1322
1553
|
const controller = this.ctrl ?? new AbortController();
|
|
1323
1554
|
this.ctrl = controller;
|
|
1555
|
+
this.turnHandlers = h; // a mid-turn compaction's summarizer reports its read through this turn's handlers
|
|
1324
1556
|
const _t0 = performance.now();
|
|
1325
1557
|
// Snapshot the conversation length so we can slice out THIS turn's steps (user + assistant/tool messages)
|
|
1326
1558
|
// for the flywheel row — the per-step structure SRFT credit assignment needs. runTurn pushes the user
|
|
1327
1559
|
// message itself, so everything from here on is this turn's.
|
|
1328
1560
|
const convoStart = this.convo.all.length;
|
|
1561
|
+
const task = this.wakeTurn ? this.lastRequest || text : servedTask(text); // the asker's words, before any carried note
|
|
1329
1562
|
const statusFirst = isStatusAsk(text) ? engineNote(STATUS_FIRST_NOTE) : ""; // the owner's "update?" is answered before any work
|
|
1330
|
-
const
|
|
1563
|
+
const ownerText = text;
|
|
1564
|
+
const mode = this.modeCarry();
|
|
1565
|
+
const carry = [this.skillNote, this.referenceNote, this.pinnedSkill(), mode.note, statusFirst].filter(Boolean).join("\n\n");
|
|
1331
1566
|
this.skillNote = "";
|
|
1567
|
+
this.referenceNote = "";
|
|
1332
1568
|
if (carry)
|
|
1333
1569
|
text = `${carry}\n\n${text}`;
|
|
1570
|
+
const turn = { text, task, convoStart, t0: _t0 };
|
|
1571
|
+
this.inflight = turn;
|
|
1572
|
+
const turnModelId = routeLabel ?? this.modelId; // the MoA specialist's own id, else the /model pick
|
|
1334
1573
|
try {
|
|
1335
1574
|
const res = await runTurn(text, this.convo, {
|
|
1575
|
+
ownerText,
|
|
1336
1576
|
router,
|
|
1337
|
-
tools: this.
|
|
1577
|
+
tools: this.liveTools, // read through at each call: a mid-turn /mode or Shift+Tab applies from the next tool call
|
|
1338
1578
|
toolSchemas: this.allSchemas(),
|
|
1339
1579
|
spill: spillToolOutput, // GW-10-COMPLETE: runTurn's fitToWindow offloads (node host)
|
|
1340
1580
|
systemPrompt: sys,
|
|
1341
1581
|
summarize: this.summarize,
|
|
1342
|
-
|
|
1582
|
+
request: task, // the asker's words: the loop reset quotes them and types the task by them, never the carried notes
|
|
1583
|
+
onTurnState: (read) => { turn.read = read; }, // an interrupted turn is recorded from it (interruptedRecord)
|
|
1584
|
+
pinnedContext: () => this.pinned(), // a summary is a rewrite anyway: the skill and Autonomous mode's rules ride it
|
|
1343
1585
|
preservedState: this.background ? undefined : () => renderActiveTasks() ?? undefined, // a mid-turn compaction keeps the active task list — the FOREGROUND's; the list is one module store, so a sub-agent must not see (or close on) the owner's items
|
|
1344
1586
|
background: this.background, // endpoint gate: a sub-agent's rounds yield the shared slot to the main turn
|
|
1345
1587
|
liveSubAgents: this.wakeTurn ? this.liveAgents : undefined, // a wake turn with sub-agents live yields from its first idle round
|
|
@@ -1354,22 +1596,54 @@ export class Session {
|
|
|
1354
1596
|
compactionThreshold: this.compactionThreshold, // settings.compaction.threshold; undefined → runTurn default 0.85
|
|
1355
1597
|
compactionCeilingTokens: this.compactionCeilingTokens, // settings.compaction.ceilingTokens; undefined → no absolute ceiling
|
|
1356
1598
|
temperature: this.temperature,
|
|
1357
|
-
thinking: this.thinkMode !== "off", // /think, /ultrathink re-enable
|
|
1599
|
+
thinking: () => !this.turnThinkOff && this.thinkMode !== "off", // /think, /ultrathink re-enable native reasoning — read per request, so a mid-turn /think applies from the next call; "continue, think off" turns it off for one turn without touching the prompt
|
|
1358
1600
|
signal: controller.signal,
|
|
1359
1601
|
onDelta: h.onDelta,
|
|
1360
1602
|
onReasoning: h.onReasoning,
|
|
1361
1603
|
onPromptProgress: h.onPromptProgress,
|
|
1362
1604
|
onTokens: h.onTokens,
|
|
1605
|
+
owner: this.owner ?? (this.background ? "sub-agent" : "main"),
|
|
1606
|
+
onQueued: h.onQueued,
|
|
1607
|
+
onSent: h.onSent,
|
|
1608
|
+
onCompactionStart: h.onCompactionStart,
|
|
1609
|
+
onCompactionEnd: h.onCompactionEnd,
|
|
1363
1610
|
onRoute: (ep) => h.onRoute?.(routeLabel ?? ep.label ?? "aurora", this.ctxPct()),
|
|
1364
1611
|
onToolStart: h.onToolStart,
|
|
1365
1612
|
onToolResult: h.onToolResult,
|
|
1613
|
+
onToolCallStart: h.onToolCallStart,
|
|
1614
|
+
onToolDraft: h.onToolDraft,
|
|
1366
1615
|
onToolBatch: h.onToolBatch,
|
|
1367
1616
|
onAutoContinue: h.onAutoContinue,
|
|
1368
1617
|
onCacheStats: h.onCacheStats,
|
|
1369
1618
|
onServed: h.onServed,
|
|
1370
|
-
onSelfHeal: (kind, attempt) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt); },
|
|
1619
|
+
onSelfHeal: (kind, attempt, step) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt, step); },
|
|
1620
|
+
model: this.turnModel(turnModelId),
|
|
1621
|
+
onFallback: (e) => { this.telemetry.record({ type: "model_fallback", from: turnModelId, to: DEFAULT_MODEL_ID, reason: e.reason, legs: e.legs.length }); h.onFallback?.(e); },
|
|
1371
1622
|
onCompaction: (e) => { this.telemetry.record({ type: "compaction", ...e }); h.onCompaction?.(e); },
|
|
1623
|
+
onLoopCompaction: (e) => {
|
|
1624
|
+
if (e.replaced > 0)
|
|
1625
|
+
this.executor.resetTurn(); // its identical-call count saw results the digest replaced — restart it with the engine's
|
|
1626
|
+
this.telemetry.record({ type: "loop_compaction", ...e });
|
|
1627
|
+
this.eventSink?.emit({ kind: "control", session: this.sessionId ?? "", actor: this.eventActor ?? { tier: "admin", surface: "cli" }, control: {
|
|
1628
|
+
event: "loop_compaction",
|
|
1629
|
+
detail: `reset ${e.attempt} after ${e.nudges} loop warnings (last: ${e.kind}); ${e.replaced} turn messages → 1 digest; ~${e.before} → ~${e.after} tokens; ${e.files} files named`,
|
|
1630
|
+
} });
|
|
1631
|
+
h.onLoopCompaction?.(e);
|
|
1632
|
+
},
|
|
1633
|
+
onLoopRecovery: (e) => {
|
|
1634
|
+
this.telemetry.record({ type: "loop_recovery", attempt: e.attempt, max: e.max, rounds: e.rounds, replaced: e.replaced, calls: e.repeated.length });
|
|
1635
|
+
this.eventSink?.emit({ kind: "control", session: this.sessionId ?? "", actor: this.eventActor ?? { tier: "admin", surface: "cli" }, control: {
|
|
1636
|
+
event: "loop_recovery",
|
|
1637
|
+
detail: `recovery ${e.attempt}/${e.max}: ${e.repeated.length} call${e.repeated.length === 1 ? "" : "s"} refused as repeats; ${e.rounds} looping round${e.rounds === 1 ? "" : "s"} (${e.replaced} turn messages) → 1 note of their results`,
|
|
1638
|
+
} });
|
|
1639
|
+
this.recordRecoveryLesson(turn); // the self-improvement loop learns from it now, not when the turn ends
|
|
1640
|
+
h.onLoopRecovery?.(e);
|
|
1641
|
+
},
|
|
1642
|
+
onLoopProceed: (e) => this.recordLoopPair(e), // the step the loop moved on with: a mentor pair
|
|
1372
1643
|
steer: h.steer,
|
|
1644
|
+
ownerSteer: h.ownerSteer,
|
|
1645
|
+
ownerAct: this.background ? undefined : this.ownerAct, // the owner's key: never a sub-agent's
|
|
1646
|
+
onOwnerAct: h.onOwnerAct,
|
|
1373
1647
|
// Truncation black-box: raw unparseable-args evidence → observability/blackbox.ts (content-bearing,
|
|
1374
1648
|
// local-only). NOT telemetry.jsonl — that stream is metrics-only by policy. A metrics-only marker
|
|
1375
1649
|
// still goes to telemetry so dashboards can count incidents without reading content.
|
|
@@ -1385,10 +1659,14 @@ export class Session {
|
|
|
1385
1659
|
// these now.") gets one nudge to actually do it (≤2/turn) instead of finalizing. Off in plan mode — there
|
|
1386
1660
|
// the text IS the deliverable ("I'll implement this once you approve") — and via KODE_TURN_CONTINUATION=0.
|
|
1387
1661
|
turnContinuation: { enabled: process.env.KODE_TURN_CONTINUATION !== "0" && !this.planMode },
|
|
1388
|
-
// Decision points: a build turn's first change waits for the owner's choice of direction (ask_user)
|
|
1389
|
-
// plan mode (the plan + exit picker IS the decision) and inert where
|
|
1390
|
-
|
|
1662
|
+
// Decision points: a build turn's first change waits for the owner's choice of direction (ask_user) — in
|
|
1663
|
+
// Autonomous mode, for a plan review. Off in plan mode (the plan + exit picker IS the decision) and inert where
|
|
1664
|
+
// ask_user isn't registered (headless).
|
|
1665
|
+
decisionPoints: { enabled: this.decisionPoints && !this.planMode, planReview: this.planReview },
|
|
1391
1666
|
});
|
|
1667
|
+
// The conversation knows the mode only once the carried note is in it (a fast-start rewrite sends the raw text).
|
|
1668
|
+
if (mode.note && this.convo.all.slice(convoStart).some((m) => m.role === "user" && typeof m.content === "string" && m.content.includes(mode.note)))
|
|
1669
|
+
this.planReviewTold = mode.on;
|
|
1392
1670
|
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 });
|
|
1393
1671
|
// MOA phase-0 ROUTE SHADOW (observability ONLY — routing is untouched): OPT-IN with KODE_MOA_SHADOW=1 (was on
|
|
1394
1672
|
// by default until 0.1.334). Its classifier call goes to the SAME endpoint as the turn, and on a single-slot
|
|
@@ -1440,23 +1718,25 @@ export class Session {
|
|
|
1440
1718
|
// Steps = the messages THIS turn added (user prompt → assistant rounds → tool results). A mid-turn
|
|
1441
1719
|
// compaction can splice the array (replaceAll), making the start index stale; if so the slice would be
|
|
1442
1720
|
// wrong, so we drop steps in that case and SRFT falls back cleanly rather than masking the wrong rounds.
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
})) : undefined;
|
|
1447
|
-
// memory sink honors settings.selfImprove.memory (projected to KODE_SELFIMPROVE_MEMORY) and is ON by
|
|
1448
|
-
// default — the proven failure-lesson → .operator/memories.md loop; set the setting / env to "0" to opt out.
|
|
1449
|
-
void runSelfImprove({ flywheel: process.env.KODE_SELFIMPROVE !== "0", memory: process.env.KODE_SELFIMPROVE_MEMORY !== "0" }, {
|
|
1721
|
+
// A loop reset replaces this turn's rounds with one digest: the slice then holds the turn from that note on.
|
|
1722
|
+
turn.recorded = true;
|
|
1723
|
+
const record = {
|
|
1450
1724
|
input: text, content: res.content, rounds: res.rounds, toolCalls: res.toolCalls,
|
|
1451
1725
|
tokens: res.tokens, stopReason: res.stopReason, model: this.currentModel(),
|
|
1452
1726
|
cwd: process.cwd(), durationMs: Math.round(performance.now() - _t0), unverified: res.unverified,
|
|
1453
|
-
steps,
|
|
1454
|
-
}
|
|
1727
|
+
steps: this.turnSteps(convoStart, text), task, loop: res.loop, lessonTs: turn.lessonTs,
|
|
1728
|
+
};
|
|
1729
|
+
const cfg = this.selfImproveCfg();
|
|
1730
|
+
this.learn(() => runSelfImprove(cfg, record)); // after any lesson a loop recovery is still writing
|
|
1455
1731
|
return { ...res, interrupted: false, durationMs: Math.round(performance.now() - _t0) };
|
|
1456
1732
|
}
|
|
1457
1733
|
catch (e) {
|
|
1458
1734
|
if (e instanceof TurnAbortedError) {
|
|
1459
1735
|
this.telemetry.record({ type: "turn", rounds: 0, toolCalls: 0, interrupted: true, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct() });
|
|
1736
|
+
const r = this.interruptedRecord(turn); // an esc is how the owner usually ends a loop: the loop still teaches
|
|
1737
|
+
const cfg = this.selfImproveCfg();
|
|
1738
|
+
if (r)
|
|
1739
|
+
this.learn(() => runSelfImprove(cfg, r));
|
|
1460
1740
|
return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
|
|
1461
1741
|
}
|
|
1462
1742
|
this.telemetry.record({ type: "error", where: "send", errorClass: Telemetry.errorClass(e) });
|
|
@@ -1464,6 +1744,70 @@ export class Session {
|
|
|
1464
1744
|
}
|
|
1465
1745
|
finally {
|
|
1466
1746
|
this.ctrl = null;
|
|
1747
|
+
if (this.inflight === turn)
|
|
1748
|
+
this.inflight = undefined;
|
|
1749
|
+
this.turnHandlers = undefined;
|
|
1467
1750
|
}
|
|
1468
1751
|
}
|
|
1752
|
+
/** The self-improvement sinks: the flywheel (settings.selfImprove → KODE_SELFIMPROVE) and the memory sink
|
|
1753
|
+
* (settings.selfImprove.memory → KODE_SELFIMPROVE_MEMORY, ON by default — a looped or stuck turn's lesson → the global
|
|
1754
|
+
* memories.md; "0" opts out). */
|
|
1755
|
+
selfImproveCfg() {
|
|
1756
|
+
return { flywheel: process.env.KODE_SELFIMPROVE !== "0", memory: process.env.KODE_SELFIMPROVE_MEMORY !== "0", maxLessons: this.maxLessons };
|
|
1757
|
+
}
|
|
1758
|
+
/** The self-improvement writes, one after another: a loop recovery's lesson, then the turn's own row and lesson (same
|
|
1759
|
+
* stamp) — read-modify-writes of one memories file that must not interleave. Best-effort, never awaited by a turn. */
|
|
1760
|
+
learn(job) {
|
|
1761
|
+
this.selfImproveQueue = this.selfImproveQueue.then(job).catch(() => { });
|
|
1762
|
+
}
|
|
1763
|
+
/** A loop recovery is a lesson at once, not when the turn ends (it may run for an hour yet, or die): the turn's record so
|
|
1764
|
+
* far, under the stamp the turn's every later write of it keeps (InflightTurn.lessonTs) — counted once, strongest
|
|
1765
|
+
* evidence kept (selfimprove/lessons.ts curateLessons). */
|
|
1766
|
+
recordRecoveryLesson(t) {
|
|
1767
|
+
const st = t.read?.();
|
|
1768
|
+
if (!st)
|
|
1769
|
+
return;
|
|
1770
|
+
const lessonTs = (t.lessonTs ??= Date.now());
|
|
1771
|
+
const r = {
|
|
1772
|
+
input: t.text, content: "", rounds: st.rounds, toolCalls: st.toolCalls, tokens: st.tokens, model: this.currentModel(),
|
|
1773
|
+
cwd: process.cwd(), durationMs: Math.round(performance.now() - t.t0), task: t.task, loop: st.loop, lessonTs,
|
|
1774
|
+
};
|
|
1775
|
+
const cfg = this.selfImproveCfg();
|
|
1776
|
+
this.learn(() => recordRecoveryLesson(cfg, r));
|
|
1777
|
+
}
|
|
1778
|
+
/** The step a recovered loop moved on with, after the calls it repeated: a mentor pair in the flywheel (selfimprove). */
|
|
1779
|
+
recordLoopPair(e) {
|
|
1780
|
+
if (this.selfImproveCfg().flywheel === false)
|
|
1781
|
+
return;
|
|
1782
|
+
if (isSubagentBrief(e.request))
|
|
1783
|
+
return; // a sub-agent's brief is not the owner's request: no mentor pair, as no lesson
|
|
1784
|
+
const ts = Date.now();
|
|
1785
|
+
const pair = loopMentorPair({ ts, attempt: e.attempt, request: e.request, model: this.currentModel(), repeated: e.repeated, forward: e.forward, answer: e.answer });
|
|
1786
|
+
this.learn(() => recordMentorPair(pair, ts));
|
|
1787
|
+
}
|
|
1788
|
+
/** The messages this turn added (its own message on), for the flywheel row. A mid-turn compaction can splice the array
|
|
1789
|
+
* (replaceAll), making the start index stale; then there are none and SRFT falls back cleanly rather than masking the
|
|
1790
|
+
* wrong rounds. */
|
|
1791
|
+
turnSteps(convoStart, text) {
|
|
1792
|
+
const intact = this.convo.all[convoStart]?.role === "user" && this.convo.all[convoStart]?.content === text;
|
|
1793
|
+
const turnMsgs = intact ? this.convo.all.slice(convoStart) : [];
|
|
1794
|
+
return turnMsgs.length ? turnMsgs.map((m) => ({
|
|
1795
|
+
role: m.role, content: m.content, tool_calls: m.tool_calls, tool_call_id: m.tool_call_id,
|
|
1796
|
+
})) : undefined;
|
|
1797
|
+
}
|
|
1798
|
+
/** The record of a turn that never returned (an esc, a signal): never promotable, and a lesson only when it looped. None
|
|
1799
|
+
* when it never settled a round (nothing to learn — a fast-start win aborts the turn there too) or was recorded. */
|
|
1800
|
+
interruptedRecord(t) {
|
|
1801
|
+
if (t.recorded)
|
|
1802
|
+
return undefined;
|
|
1803
|
+
t.recorded = true;
|
|
1804
|
+
const st = t.read?.();
|
|
1805
|
+
if (!st || st.rounds === 0)
|
|
1806
|
+
return undefined;
|
|
1807
|
+
return {
|
|
1808
|
+
input: t.text, content: "", rounds: st.rounds, toolCalls: st.toolCalls, tokens: st.tokens, model: this.currentModel(),
|
|
1809
|
+
cwd: process.cwd(), durationMs: Math.round(performance.now() - t.t0), steps: this.turnSteps(t.convoStart, t.text),
|
|
1810
|
+
task: t.task, loop: st.loop, interrupted: true, lessonTs: t.lessonTs,
|
|
1811
|
+
};
|
|
1812
|
+
}
|
|
1469
1813
|
}
|