@0perator/operator 0.1.352 → 0.1.353
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 +2 -2
- package/dist/acp/tool-map.js +5 -4
- package/dist/autonomy/delegate.js +54 -1
- package/dist/autonomy/headless.js +2 -0
- 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 +1066 -175
- 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 +444 -76
- package/dist/engine/anthropic-chat.js +13 -2
- package/dist/engine/aurora.js +43 -19
- package/dist/engine/batch-scheduler.js +27 -3
- package/dist/engine/compaction.js +12 -5
- package/dist/engine/continuation.js +14 -12
- 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/owner-act.js +52 -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 +350 -30
- 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,6 +339,8 @@ 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;
|
|
@@ -345,6 +372,12 @@ export class Session {
|
|
|
345
372
|
liveAgents;
|
|
346
373
|
slotSharers;
|
|
347
374
|
wakeTurn = false; // the turn in flight was started by the shell to deliver a report / job notice, not typed by the owner
|
|
375
|
+
maxLessons; // lines the global lessons section keeps — the same cap sleep consolidation curates to
|
|
376
|
+
lastRequest = ""; // what the owner last typed (a mentor-wake: its subject) — the task a wake turn serves (flywheel row `task`, loop lessons)
|
|
377
|
+
inflight; // the turn running now — what an interrupt or a signal records (recordInterruptedTurnSync)
|
|
378
|
+
selfImproveQueue = Promise.resolve(); // the self-improvement writes, in order (learn)
|
|
379
|
+
turnThinkOff = false; // this one turn runs enable_thinking:false ("continue, think off"); the system prompt is untouched
|
|
380
|
+
ownerAct = new OwnerAct(); // ctrl+y — "use what you have" (engine/owner-act.ts)
|
|
348
381
|
hooks;
|
|
349
382
|
cwd;
|
|
350
383
|
unattended;
|
|
@@ -353,6 +386,7 @@ export class Session {
|
|
|
353
386
|
compactionThreshold;
|
|
354
387
|
compactionCeilingTokens;
|
|
355
388
|
background;
|
|
389
|
+
owner;
|
|
356
390
|
temperature;
|
|
357
391
|
ctrl = null;
|
|
358
392
|
memory;
|
|
@@ -366,12 +400,16 @@ export class Session {
|
|
|
366
400
|
* from anywhere: the pending promise is swapped and failures were already swallowed by the module. */
|
|
367
401
|
async flushRouteShadow() { const p = this._shadowPending; this._shadowPending = Promise.resolve(); await p; }
|
|
368
402
|
decisionPoints;
|
|
403
|
+
planReview = false; // Autonomous mode: plan reviews instead of per-command prompts (setOperatingMode)
|
|
404
|
+
planReviewTold = false; // what the conversation last told the model about Autonomous mode (modeCarry)
|
|
405
|
+
planApproval = new PlanApproval(taskPlanRevision, openTaskCount); // the owner's standing plan approval, read by the policy
|
|
369
406
|
planMode = false; // /plan: research read-only + propose a plan, no mutations until the owner approves
|
|
370
407
|
thinkMode = "off"; // /think, /ultrathink — extended reasoning
|
|
371
408
|
recalled = false;
|
|
372
409
|
activeSkillBlock = ""; // capped skill instructions, carried in the conversation (pinnedSkill)
|
|
373
410
|
activeSkillName = ""; // name of the active skill (for status display)
|
|
374
411
|
skillNote = ""; // one-shot "stop following skill X" for the owner's next message (/skill off)
|
|
412
|
+
referenceNote = ""; // one-shot quoted third-party text for the owner's next message (referenceOnce)
|
|
375
413
|
// Rolling summarizer — instant compaction (Engine doc #2). A background process continuously
|
|
376
414
|
// maintains a structured session-memory/summary.md during the session. When compact() fires,
|
|
377
415
|
// it loads the pre-written summary — /compact went from up to 2 minutes to instant.
|
|
@@ -418,7 +456,7 @@ export class Session {
|
|
|
418
456
|
if (cfg.stopAgent)
|
|
419
457
|
reg.set("stop_agent", makeStopTool(cfg.stopAgent));
|
|
420
458
|
if (cfg.askUser)
|
|
421
|
-
reg.set("ask_user", makeAskTool(cfg.askUser));
|
|
459
|
+
reg.set("ask_user", makeAskTool(cfg.askUser, { on: () => this.planReview, approval: this.planApproval, planSteps: () => getAgentTasks().length }));
|
|
422
460
|
this.decisionPoints = decisionPointsEnabled(cfg.decisionPoints);
|
|
423
461
|
reg.set("self_status", makeSelfStatusTool(() => ({
|
|
424
462
|
model: this.currentModel(),
|
|
@@ -459,6 +497,7 @@ export class Session {
|
|
|
459
497
|
this.isOwner = (cfg.eventActor?.tier ?? "admin") === "admin"; // set before the startup setModel so a persisted owner-only activeModel resolves for the owner
|
|
460
498
|
this.moaConfig = cfg.moa;
|
|
461
499
|
this.onDemand = cfg.onDemand;
|
|
500
|
+
this.frontDoor = cfg.frontDoor;
|
|
462
501
|
this.classifier = cfg.classifier;
|
|
463
502
|
this.fastStartConfig = cfg.fastStart;
|
|
464
503
|
this.fastStartEnabled = isFeatureEnabled("fastStart", { features: cfg.features }) && !!cfg.fastStart;
|
|
@@ -484,6 +523,7 @@ export class Session {
|
|
|
484
523
|
this.compactionThreshold = cfg.compactionThreshold;
|
|
485
524
|
this.compactionCeilingTokens = cfg.compactionCeilingTokens;
|
|
486
525
|
this.background = cfg.background ?? false;
|
|
526
|
+
this.owner = cfg.owner;
|
|
487
527
|
this.temperature = cfg.temperature ?? 0.7;
|
|
488
528
|
this.memory = cfg.memory ?? new MemoryStore();
|
|
489
529
|
this.wantRecall = cfg.recall ?? true;
|
|
@@ -491,7 +531,8 @@ export class Session {
|
|
|
491
531
|
this.hub = cfg.mcpHub;
|
|
492
532
|
if (this.hub)
|
|
493
533
|
this.hub.spillSink = spillToolOutput; // GW-10-COMPLETE: offload huge MCP results too
|
|
494
|
-
this.
|
|
534
|
+
this.planReview = cfg.planReview === true;
|
|
535
|
+
this.permissionCfg = this.underReview(cfg.permissions ?? { mode: "bypass" });
|
|
495
536
|
this.policy = new PermissionPolicy(this.permissionCfg);
|
|
496
537
|
this.approve = cfg.approve;
|
|
497
538
|
this.telemetry = new Telemetry(cfg.telemetry);
|
|
@@ -499,6 +540,7 @@ export class Session {
|
|
|
499
540
|
this.eventActor = cfg.eventActor;
|
|
500
541
|
this.sessionId = cfg.sessionId;
|
|
501
542
|
this.tools = this.buildTools(); // local-only until first-turn MCP discovery rebinds it
|
|
543
|
+
this.maxLessons = cfg.sleepConsolidation?.maxLessonsPerFile;
|
|
502
544
|
// Initialize sleep-time consolidation if enabled (via settings or env).
|
|
503
545
|
const sleepEnabled = process.env.KODE_SLEEP_CONSOLIDATION === "1" || cfg.sleepConsolidation?.enabled;
|
|
504
546
|
if (sleepEnabled) {
|
|
@@ -613,6 +655,37 @@ export class Session {
|
|
|
613
655
|
currentPermissionMode() {
|
|
614
656
|
return this.policy.currentMode();
|
|
615
657
|
}
|
|
658
|
+
/** The interactive operating mode's policy (permissions/modes.ts): its permission config and whether Autonomous plan
|
|
659
|
+
* review is on. Plan mode stays separate (setPlanMode) and takes precedence while active. The system prompt does not
|
|
660
|
+
* change; the next owner message carries the switch (modeCarry). Leaving plan review keeps a standing approval; it
|
|
661
|
+
* ends when the plan changes. */
|
|
662
|
+
setOperatingMode(m) {
|
|
663
|
+
this.planReview = m.planReview;
|
|
664
|
+
// keep what /allow added this session: the mode's config is built from the startup settings, which lack it
|
|
665
|
+
const allow = [...new Set([...(m.permissions.allow ?? []), ...(this.permissionCfg.allow ?? [])])];
|
|
666
|
+
this.permissionCfg = this.underReview(allow.length ? { ...m.permissions, allow } : m.permissions);
|
|
667
|
+
this.policy = new PermissionPolicy(this.permissionCfg);
|
|
668
|
+
this.tools = this.buildTools();
|
|
669
|
+
}
|
|
670
|
+
inPlanReview() {
|
|
671
|
+
return this.planReview;
|
|
672
|
+
}
|
|
673
|
+
/** Autonomous mode's rules ride the conversation, like an active skill, so the system prompt stays byte-stable: the
|
|
674
|
+
* owner's next message after a switch carries the rules (on) or the note that they no longer apply (off). */
|
|
675
|
+
modeCarry() {
|
|
676
|
+
const on = this.planReview && !this.planMode;
|
|
677
|
+
return { note: on === this.planReviewTold ? "" : engineNote(on ? AUTONOMOUS_MODE_ON : AUTONOMOUS_MODE_OFF), on };
|
|
678
|
+
}
|
|
679
|
+
/** What a compaction summary must keep: the active skill, and Autonomous mode's rules while they apply. */
|
|
680
|
+
pinned() {
|
|
681
|
+
const mode = this.planReview && !this.planMode ? engineNote(AUTONOMOUS_MODE_ON) : "";
|
|
682
|
+
return [this.activeSkillBlock, mode].filter(Boolean).join("\n\n") || undefined;
|
|
683
|
+
}
|
|
684
|
+
/** `cfg` with this session's plan approval attached while plan review is on, and detached otherwise. */
|
|
685
|
+
underReview(cfg) {
|
|
686
|
+
const { planReview: _drop, ...rest } = cfg;
|
|
687
|
+
return this.planReview ? { ...rest, planReview: this.planApproval } : rest;
|
|
688
|
+
}
|
|
616
689
|
/** Set extended-reasoning mode (/think, /ultrathink). "think" re-enables Aurora's native reasoning for
|
|
617
690
|
* each turn; "ultrathink" also pushes for deeper step-by-step reasoning via the system prompt. */
|
|
618
691
|
setThinkMode(mode) {
|
|
@@ -636,6 +709,11 @@ export class Session {
|
|
|
636
709
|
this.skillNote = "";
|
|
637
710
|
return this.activeSkillBlock;
|
|
638
711
|
}
|
|
712
|
+
/** Third-party text the owner picked (the finder's unverified hub entries, skills/finder.ts quotedReference): it rides
|
|
713
|
+
* on the owner's next message once, as an engine note — never a standing directive, never pinned through a compaction. */
|
|
714
|
+
referenceOnce(text) {
|
|
715
|
+
this.referenceNote = engineNote(text);
|
|
716
|
+
}
|
|
639
717
|
deactivateSkill() {
|
|
640
718
|
if (this.activeSkillName)
|
|
641
719
|
this.skillNote = `[Skill '${this.activeSkillName}' is no longer active — stop following its instructions.]`;
|
|
@@ -672,6 +750,14 @@ export class Session {
|
|
|
672
750
|
meterKey() {
|
|
673
751
|
return endpointKey(this.lastBase ?? this.inner.base, this.lastModel ?? this.inner.model);
|
|
674
752
|
}
|
|
753
|
+
/** The tool executor a running turn holds: every call reads `this.tools` at that moment, so a mode switch mid-turn
|
|
754
|
+
* (/mode, /plan, Shift+Tab — each rebuilds `this.tools` with its policy) governs the turn's next tool call, not only
|
|
755
|
+
* the next turn. The running batch finishes under the policy it started with. */
|
|
756
|
+
liveTools = ((s) => ({
|
|
757
|
+
execute: (name, args) => s.tools.execute(name, args),
|
|
758
|
+
executeParallel: (calls, onSettle, signal) => s.tools.executeParallel(calls, onSettle, signal),
|
|
759
|
+
get sched() { return s.tools.sched; },
|
|
760
|
+
}))(this);
|
|
675
761
|
/** Full-request estimate (system + conversation + tool schemas) at the live endpoint's LEARNED
|
|
676
762
|
* chars/token — the one basis shared by the ctx% bar and the /compact freed math (SPEC §5). */
|
|
677
763
|
requestEstimate() {
|
|
@@ -679,6 +765,56 @@ export class Session {
|
|
|
679
765
|
const built = sys ? [{ role: "system", content: sys }, ...this.convo.all] : this.convo.all;
|
|
680
766
|
return globalTokenMeter.estimateRequestFor(this.meterKey(), built, this.allSchemas());
|
|
681
767
|
}
|
|
768
|
+
/** The full request as tokens (system + conversation + tool schemas), on the ctx% bar's calibrated basis — public, so
|
|
769
|
+
* the shell can price a re-read before it happens: the /model cost, the /think cost and the cold-read forecast. */
|
|
770
|
+
requestTokens() {
|
|
771
|
+
return this.requestEstimate();
|
|
772
|
+
}
|
|
773
|
+
/** What a /think toggle makes the next turn re-read: the think directive rides at the END of the system prompt, and
|
|
774
|
+
* chat templates put the tools and the conversation after it, so everything past the base system text misses the
|
|
775
|
+
* server's prefix cache. */
|
|
776
|
+
thinkRereadTokens() {
|
|
777
|
+
const base = this.sys();
|
|
778
|
+
const head = base ? globalTokenMeter.estimateRequestFor(this.meterKey(), [{ role: "system", content: base }], []) : 0;
|
|
779
|
+
return Math.max(0, this.requestEstimate() - head);
|
|
780
|
+
}
|
|
781
|
+
/** The re-read a switch to `modelId` costs: this conversation's whole request at THAT endpoint's learned chars/token
|
|
782
|
+
* (another server holds none of it in its prefix cache), and the window it has to fit. Undefined for an unknown id or
|
|
783
|
+
* a model with no endpoint of its own (moa spans several). */
|
|
784
|
+
rereadEstimate(modelId) {
|
|
785
|
+
const p = findModel(this.liveRegistry(), modelId);
|
|
786
|
+
if (p?.kind !== "single")
|
|
787
|
+
return undefined;
|
|
788
|
+
let base, model;
|
|
789
|
+
if (p.id === DEFAULT_MODEL_ID) {
|
|
790
|
+
const r = this.chain ?? this.inner;
|
|
791
|
+
base = r.base;
|
|
792
|
+
model = r.model;
|
|
793
|
+
}
|
|
794
|
+
else {
|
|
795
|
+
const ep = p.endpoints?.[0] ?? p.endpoint;
|
|
796
|
+
if (!ep)
|
|
797
|
+
return undefined;
|
|
798
|
+
base = endpointBase(ep);
|
|
799
|
+
model = p.endpointModels?.[0] ?? p.model ?? p.id;
|
|
800
|
+
}
|
|
801
|
+
const sys = this.sys();
|
|
802
|
+
const built = sys ? [{ role: "system", content: sys }, ...this.convo.all] : this.convo.all;
|
|
803
|
+
return { tokens: globalTokenMeter.estimateRequestFor(endpointKey(base, model), built, this.allSchemas()), window: p.ctx };
|
|
804
|
+
}
|
|
805
|
+
/** What /compact can promise before it runs (TUI A3.5 / A3.6): the request now, and AT MOST what is left after it — the
|
|
806
|
+
* last two turns verbatim (compactNow's minKeepTurns), the deterministic backstop compact() always appends (anchor
|
|
807
|
+
* index, the owner's own words, the pinned skill) and a summary capped at SUMMARY_MAX_TOKENS. An upper bound, never
|
|
808
|
+
* progress: fitToWindow may shed more. Null when there is nothing to evict. */
|
|
809
|
+
compactionEstimate() {
|
|
810
|
+
const split = compactionSplit(this.convo.all, 2);
|
|
811
|
+
if (!split?.evicted.length)
|
|
812
|
+
return null;
|
|
813
|
+
const backstop = { role: "user", content: `${renderAnchorIndex(split.evicted)}${verbatimUserTail(split.evicted)}${this.activeSkillBlock ? `\n\n${this.activeSkillBlock}` : ""}` };
|
|
814
|
+
const sys = this.sys();
|
|
815
|
+
const kept = [...(sys ? [{ role: "system", content: sys }] : []), backstop, ...split.kept];
|
|
816
|
+
return { before: this.requestEstimate(), afterMax: globalTokenMeter.estimateRequestFor(this.meterKey(), kept, this.allSchemas()) + SUMMARY_MAX_TOKENS, summaryMax: SUMMARY_MAX_TOKENS };
|
|
817
|
+
}
|
|
682
818
|
/** Estimated context usage of the live conversation against the window the engine runs on (the served limit
|
|
683
819
|
* under the owner's pin), 0-99. Calibrated: the meter's real ratio once observations land; exactly the old
|
|
684
820
|
* chars/4 prior cold. */
|
|
@@ -737,6 +873,18 @@ export class Session {
|
|
|
737
873
|
interrupt() {
|
|
738
874
|
this.ctrl?.abort();
|
|
739
875
|
}
|
|
876
|
+
/** ctrl+y — "use what you have": the twin of interrupt() that keeps the work. A live stream is cut and its partial
|
|
877
|
+
* kept; during the read it arms; during tools it applies before the next request. False when no turn runs. */
|
|
878
|
+
actNow() {
|
|
879
|
+
return !!this.ctrl && this.ownerAct.request();
|
|
880
|
+
}
|
|
881
|
+
/** The process is going down with a turn in flight (cli.tsx teardown — a signal, where nothing can be awaited): record it
|
|
882
|
+
* now, synchronously — its flywheel row and, when it looped, its lesson. No-op when idle or already recorded. */
|
|
883
|
+
recordInterruptedTurnSync() {
|
|
884
|
+
const r = this.inflight && this.interruptedRecord(this.inflight);
|
|
885
|
+
if (r)
|
|
886
|
+
runSelfImproveSync(this.selfImproveCfg(), r);
|
|
887
|
+
}
|
|
740
888
|
// ── Slash-command surface (used by the shell) ──────────────────────────
|
|
741
889
|
/** Configured endpoints, for /endpoints. */
|
|
742
890
|
endpoints() {
|
|
@@ -759,13 +907,22 @@ export class Session {
|
|
|
759
907
|
* and /compact used to report "nothing to compact yet" while the session was clearly over budget. So we
|
|
760
908
|
* ALSO fitToWindow: elide the largest tool outputs in place until it fits the ACTIVE endpoint's (learned)
|
|
761
909
|
* window. Returns tokens, not message count, because elision reduces chars without dropping messages. */
|
|
762
|
-
async compactNow() {
|
|
910
|
+
async compactNow(h) {
|
|
911
|
+
this.turnHandlers = h;
|
|
912
|
+
try {
|
|
913
|
+
return await this.compactNowInner();
|
|
914
|
+
}
|
|
915
|
+
finally {
|
|
916
|
+
this.turnHandlers = undefined;
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
async compactNowInner() {
|
|
763
920
|
const opts = {
|
|
764
921
|
ctxWindow: this.effectiveContext(),
|
|
765
922
|
systemPrompt: this.sys(),
|
|
766
923
|
summarize: this.summarize,
|
|
767
924
|
preservedState: renderActiveTasks() ?? undefined, // the active task list rides with the summary
|
|
768
|
-
pinnedContext: this.
|
|
925
|
+
pinnedContext: this.pinned(), // the active skill and Autonomous mode's rules ride the summary
|
|
769
926
|
minKeepTurns: 2,
|
|
770
927
|
tools: this.allSchemas(), // same full-request basis as the gate and the ctx% bar
|
|
771
928
|
meter: globalTokenMeter,
|
|
@@ -817,6 +974,8 @@ export class Session {
|
|
|
817
974
|
reset() {
|
|
818
975
|
this.convo.replaceAll([]);
|
|
819
976
|
this.rollingSummarizer.clear(); // clear the rolling summary on new session
|
|
977
|
+
this.planApproval.clear(); // a fresh conversation has no reviewed plan
|
|
978
|
+
this.planReviewTold = false; // …and has not been told the mode
|
|
820
979
|
}
|
|
821
980
|
/** Sleep-time consolidation — trigger memory reorganization. Returns the result. */
|
|
822
981
|
async consolidate() {
|
|
@@ -935,6 +1094,8 @@ export class Session {
|
|
|
935
1094
|
if (!ok)
|
|
936
1095
|
return false;
|
|
937
1096
|
this.convo.replaceAll(msgs);
|
|
1097
|
+
this.planApproval.clear(); // another conversation: its plan was never reviewed here
|
|
1098
|
+
this.planReviewTold = false; // …and it has not been told the mode
|
|
938
1099
|
return true;
|
|
939
1100
|
}
|
|
940
1101
|
/** The fact-preserving summarizer: engine prompt + content||reasoning fallback (Aurora empties content). */
|
|
@@ -948,6 +1109,8 @@ export class Session {
|
|
|
948
1109
|
// different endpoint, guaranteeing a full cache miss (and possibly a wrong-context-window 400).
|
|
949
1110
|
lastBase;
|
|
950
1111
|
lastModel;
|
|
1112
|
+
/** The handlers of the turn in flight (or of /compact), so the summarizer can report its own read progress. */
|
|
1113
|
+
turnHandlers;
|
|
951
1114
|
summarize = async (span) => {
|
|
952
1115
|
// Cache-safe compaction (Anthropic's cache-safe forking). The evicted span is the OLDEST slice of the
|
|
953
1116
|
// live conversation, so [system + tools + span] is an exact PREFIX of the request the live turn just
|
|
@@ -988,6 +1151,9 @@ export class Session {
|
|
|
988
1151
|
// The summarize request rides the SAME leg's key, wire and chat path as the live turn: a vendor row (Claude, Gemini,
|
|
989
1152
|
// a free row) went to /v1/chat/completions with no key before, so a session on it could never compact.
|
|
990
1153
|
const leg = [...this.inner.list(), ...(this.chain?.list() ?? [])].find((e) => e.base === sumBase && e.model === sumModel);
|
|
1154
|
+
const onWrite = this.turnHandlers?.onCompactionWrite;
|
|
1155
|
+
let wrote = 0;
|
|
1156
|
+
const written = onWrite ? () => onWrite(++wrote) : undefined; // its writing, so the line moves on from "reading" (review F2)
|
|
991
1157
|
let r;
|
|
992
1158
|
try {
|
|
993
1159
|
r = await chat(messages, {
|
|
@@ -1002,6 +1168,10 @@ export class Session {
|
|
|
1002
1168
|
maxTokens: leg?.transport === "anthropic" ? SUMMARY_MAX_TOKENS_THINKING : SUMMARY_MAX_TOKENS,
|
|
1003
1169
|
temperature: 0,
|
|
1004
1170
|
background: this.background, // a sub-agent's compaction summarize also yields to the interactive main turn
|
|
1171
|
+
owner: "compaction",
|
|
1172
|
+
onPromptProgress: this.turnHandlers?.onPromptProgress, // the compaction line shows the summarizer's own measured read
|
|
1173
|
+
onDelta: written,
|
|
1174
|
+
onReasoning: written,
|
|
1005
1175
|
signal, // ESC during "compacting" must tear down THIS request too, not just the main generation stream —
|
|
1006
1176
|
// without it a compaction summarize (which can be a large request on a slow/deep endpoint) runs to
|
|
1007
1177
|
// completion after the user already hit esc. Null ctrl (background pass outside a turn) → timeout-only.
|
|
@@ -1200,11 +1370,18 @@ export class Session {
|
|
|
1200
1370
|
if (this.ctrl)
|
|
1201
1371
|
throw new Error("Session.send called while a turn is in flight — serialize turns (the shell queues input)");
|
|
1202
1372
|
this.wakeTurn = flags?.wake === true;
|
|
1373
|
+
if (!this.wakeTurn)
|
|
1374
|
+
this.lastRequest = servedTask(text);
|
|
1375
|
+
this.turnThinkOff = flags?.thinkOff === true;
|
|
1376
|
+
this.ownerAct.reset();
|
|
1203
1377
|
// Arm the interrupt controller BEFORE maybeRecall. The host flips status to "thinking" the instant send() is
|
|
1204
1378
|
// called, so an esc during first-turn memory recall / MCP discovery (which hit the network and can be slow)
|
|
1205
1379
|
// would otherwise no-op — this.ctrl was null until execute(). execute() reuses this same controller.
|
|
1206
1380
|
this.ctrl = new AbortController();
|
|
1207
1381
|
try {
|
|
1382
|
+
const front = await this.viaFrontDoor(text, h); // before onDemand: a message the fast model answers never loads Aurora
|
|
1383
|
+
if (front)
|
|
1384
|
+
return front;
|
|
1208
1385
|
if (this.onDemand && this.modelId === DEFAULT_MODEL_ID) {
|
|
1209
1386
|
const fresh = await this.onDemand(this.ctrl.signal);
|
|
1210
1387
|
if (fresh)
|
|
@@ -1226,8 +1403,37 @@ export class Session {
|
|
|
1226
1403
|
finally {
|
|
1227
1404
|
this.ctrl = null; // execute() nulls on its own path too; this also covers the maybeRecall-abort early return
|
|
1228
1405
|
this.wakeTurn = false;
|
|
1406
|
+
this.turnThinkOff = false;
|
|
1229
1407
|
}
|
|
1230
1408
|
}
|
|
1409
|
+
/** The front door (engine/front-door.ts). On the default model and MOA, the gateway answers a message its classifier
|
|
1410
|
+
* is confident needs no tools with its fast model in this session's voice; the reply joins the conversation like any
|
|
1411
|
+
* other. Returns null to run the turn as usual: the gateway says work (the owner sees its status line at once), it
|
|
1412
|
+
* has no opinion or no answer, or its fast model escalated. */
|
|
1413
|
+
async viaFrontDoor(text, h) {
|
|
1414
|
+
this.frontDoorRoute = undefined;
|
|
1415
|
+
const fd = this.frontDoor;
|
|
1416
|
+
const active = findModel(this.liveRegistry(), this.modelId);
|
|
1417
|
+
if (!fd || (this.modelId !== DEFAULT_MODEL_ID && active?.kind !== "orchestrated"))
|
|
1418
|
+
return null;
|
|
1419
|
+
const t0 = Date.now();
|
|
1420
|
+
// The gateway's front door is configured on the default model's route; `name` is the model as the owner knows it
|
|
1421
|
+
// (activeModelBlock), so a MOA session is MOA to the fast model too.
|
|
1422
|
+
const name = active ? `${active.label}${active.params ? ` ${active.params}` : ""}` : this.modelId;
|
|
1423
|
+
const d = await askFrontDoor(fd, { model: DEFAULT_MODEL_ID, name, messages: [...recentTurns(this.convo.all), { role: "user", content: text }] }, this.ctrl?.signal);
|
|
1424
|
+
if (this.ctrl?.signal.aborted)
|
|
1425
|
+
return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
|
|
1426
|
+
this.frontDoorRoute = d?.route ?? null;
|
|
1427
|
+
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 });
|
|
1428
|
+
if (d?.route === "work")
|
|
1429
|
+
h.onTriage?.(d.line);
|
|
1430
|
+
if (d?.route !== "direct")
|
|
1431
|
+
return null;
|
|
1432
|
+
this.convo.user(text);
|
|
1433
|
+
this.convo.assistant(d.content);
|
|
1434
|
+
h.onDelta?.(d.content);
|
|
1435
|
+
return { content: d.content, rounds: 1, toolCalls: 0, interrupted: false, durationMs: Date.now() - t0 };
|
|
1436
|
+
}
|
|
1231
1437
|
/** MOA turn (engine/moa.ts): the planner takes the turn through the SAME runTurn loop as any turn (execute), on its
|
|
1232
1438
|
* own endpoint, with the planner brief in the system prompt — and every delegate_task in it defaults to the
|
|
1233
1439
|
* specialist. The brief is fixed per team, so the system prompt stays byte-stable across turns. */
|
|
@@ -1235,9 +1441,13 @@ export class Session {
|
|
|
1235
1441
|
const team = moaTeam(this.moaConfig); // setModel refuses to select "moa" without one
|
|
1236
1442
|
// The router (classifier/route.ts): a request it is confident needs no tools goes straight to the fast
|
|
1237
1443
|
// specialist — no planner round, no planner prefill. Anything else, or no answer from the router, is planned.
|
|
1238
|
-
|
|
1444
|
+
// With the front door on, the gateway already decided (viaFrontDoor): a message only gets here when it needs tools
|
|
1445
|
+
// (work, or a direct one its fast model escalated) or nothing answered, so it is planned, never sent to the
|
|
1446
|
+
// specialist with the full prompt.
|
|
1447
|
+
const fd = this.frontDoorRoute;
|
|
1448
|
+
const route = fd === undefined && this.classifier && this.classifier.mode !== "off" ? await routeTurn(text, this.classifier.endpoint) : null;
|
|
1239
1449
|
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 });
|
|
1450
|
+
this.telemetry.record({ type: "moa", planner: team.planner.id, specialist: team.specialist, route: specialist ? "direct" : route || fd === "work" ? "planned" : "unrouted", pDirect: route?.pDirect });
|
|
1241
1451
|
if (specialist)
|
|
1242
1452
|
return this.execute(text, h, this.wrap(this.routerForProfile(specialist)), this.sysWithThink(), specialist.id);
|
|
1243
1453
|
const plannerRouter = this.wrap(new AuroraRouter([
|
|
@@ -1321,25 +1531,35 @@ export class Session {
|
|
|
1321
1531
|
// only if execute() is somehow entered without send() arming it (defensive — every caller goes via send).
|
|
1322
1532
|
const controller = this.ctrl ?? new AbortController();
|
|
1323
1533
|
this.ctrl = controller;
|
|
1534
|
+
this.turnHandlers = h; // a mid-turn compaction's summarizer reports its read through this turn's handlers
|
|
1324
1535
|
const _t0 = performance.now();
|
|
1325
1536
|
// Snapshot the conversation length so we can slice out THIS turn's steps (user + assistant/tool messages)
|
|
1326
1537
|
// for the flywheel row — the per-step structure SRFT credit assignment needs. runTurn pushes the user
|
|
1327
1538
|
// message itself, so everything from here on is this turn's.
|
|
1328
1539
|
const convoStart = this.convo.all.length;
|
|
1540
|
+
const task = this.wakeTurn ? this.lastRequest || text : servedTask(text); // the asker's words, before any carried note
|
|
1329
1541
|
const statusFirst = isStatusAsk(text) ? engineNote(STATUS_FIRST_NOTE) : ""; // the owner's "update?" is answered before any work
|
|
1330
|
-
const
|
|
1542
|
+
const ownerText = text;
|
|
1543
|
+
const mode = this.modeCarry();
|
|
1544
|
+
const carry = [this.skillNote, this.referenceNote, this.pinnedSkill(), mode.note, statusFirst].filter(Boolean).join("\n\n");
|
|
1331
1545
|
this.skillNote = "";
|
|
1546
|
+
this.referenceNote = "";
|
|
1332
1547
|
if (carry)
|
|
1333
1548
|
text = `${carry}\n\n${text}`;
|
|
1549
|
+
const turn = { text, task, convoStart, t0: _t0 };
|
|
1550
|
+
this.inflight = turn;
|
|
1334
1551
|
try {
|
|
1335
1552
|
const res = await runTurn(text, this.convo, {
|
|
1553
|
+
ownerText,
|
|
1336
1554
|
router,
|
|
1337
|
-
tools: this.
|
|
1555
|
+
tools: this.liveTools, // read through at each call: a mid-turn /mode or Shift+Tab applies from the next tool call
|
|
1338
1556
|
toolSchemas: this.allSchemas(),
|
|
1339
1557
|
spill: spillToolOutput, // GW-10-COMPLETE: runTurn's fitToWindow offloads (node host)
|
|
1340
1558
|
systemPrompt: sys,
|
|
1341
1559
|
summarize: this.summarize,
|
|
1342
|
-
|
|
1560
|
+
request: task, // the asker's words: the loop reset quotes them and types the task by them, never the carried notes
|
|
1561
|
+
onTurnState: (read) => { turn.read = read; }, // an interrupted turn is recorded from it (interruptedRecord)
|
|
1562
|
+
pinnedContext: () => this.pinned(), // a summary is a rewrite anyway: the skill and Autonomous mode's rules ride it
|
|
1343
1563
|
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
1564
|
background: this.background, // endpoint gate: a sub-agent's rounds yield the shared slot to the main turn
|
|
1345
1565
|
liveSubAgents: this.wakeTurn ? this.liveAgents : undefined, // a wake turn with sub-agents live yields from its first idle round
|
|
@@ -1354,22 +1574,52 @@ export class Session {
|
|
|
1354
1574
|
compactionThreshold: this.compactionThreshold, // settings.compaction.threshold; undefined → runTurn default 0.85
|
|
1355
1575
|
compactionCeilingTokens: this.compactionCeilingTokens, // settings.compaction.ceilingTokens; undefined → no absolute ceiling
|
|
1356
1576
|
temperature: this.temperature,
|
|
1357
|
-
thinking: this.thinkMode !== "off", // /think, /ultrathink re-enable
|
|
1577
|
+
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
1578
|
signal: controller.signal,
|
|
1359
1579
|
onDelta: h.onDelta,
|
|
1360
1580
|
onReasoning: h.onReasoning,
|
|
1361
1581
|
onPromptProgress: h.onPromptProgress,
|
|
1362
1582
|
onTokens: h.onTokens,
|
|
1583
|
+
owner: this.owner ?? (this.background ? "sub-agent" : "main"),
|
|
1584
|
+
onQueued: h.onQueued,
|
|
1585
|
+
onSent: h.onSent,
|
|
1586
|
+
onCompactionStart: h.onCompactionStart,
|
|
1587
|
+
onCompactionEnd: h.onCompactionEnd,
|
|
1363
1588
|
onRoute: (ep) => h.onRoute?.(routeLabel ?? ep.label ?? "aurora", this.ctxPct()),
|
|
1364
1589
|
onToolStart: h.onToolStart,
|
|
1365
1590
|
onToolResult: h.onToolResult,
|
|
1591
|
+
onToolCallStart: h.onToolCallStart,
|
|
1592
|
+
onToolDraft: h.onToolDraft,
|
|
1366
1593
|
onToolBatch: h.onToolBatch,
|
|
1367
1594
|
onAutoContinue: h.onAutoContinue,
|
|
1368
1595
|
onCacheStats: h.onCacheStats,
|
|
1369
1596
|
onServed: h.onServed,
|
|
1370
1597
|
onSelfHeal: (kind, attempt) => { this.telemetry.record({ type: "self_heal", kind, attempt }); h.onSelfHeal?.(kind, attempt); },
|
|
1371
1598
|
onCompaction: (e) => { this.telemetry.record({ type: "compaction", ...e }); h.onCompaction?.(e); },
|
|
1599
|
+
onLoopCompaction: (e) => {
|
|
1600
|
+
if (e.replaced > 0)
|
|
1601
|
+
this.executor.resetTurn(); // its identical-call count saw results the digest replaced — restart it with the engine's
|
|
1602
|
+
this.telemetry.record({ type: "loop_compaction", ...e });
|
|
1603
|
+
this.eventSink?.emit({ kind: "control", session: this.sessionId ?? "", actor: this.eventActor ?? { tier: "admin", surface: "cli" }, control: {
|
|
1604
|
+
event: "loop_compaction",
|
|
1605
|
+
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`,
|
|
1606
|
+
} });
|
|
1607
|
+
h.onLoopCompaction?.(e);
|
|
1608
|
+
},
|
|
1609
|
+
onLoopRecovery: (e) => {
|
|
1610
|
+
this.telemetry.record({ type: "loop_recovery", attempt: e.attempt, max: e.max, rounds: e.rounds, replaced: e.replaced, calls: e.repeated.length });
|
|
1611
|
+
this.eventSink?.emit({ kind: "control", session: this.sessionId ?? "", actor: this.eventActor ?? { tier: "admin", surface: "cli" }, control: {
|
|
1612
|
+
event: "loop_recovery",
|
|
1613
|
+
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`,
|
|
1614
|
+
} });
|
|
1615
|
+
this.recordRecoveryLesson(turn); // the self-improvement loop learns from it now, not when the turn ends
|
|
1616
|
+
h.onLoopRecovery?.(e);
|
|
1617
|
+
},
|
|
1618
|
+
onLoopProceed: (e) => this.recordLoopPair(e), // the step the loop moved on with: a mentor pair
|
|
1372
1619
|
steer: h.steer,
|
|
1620
|
+
ownerSteer: h.ownerSteer,
|
|
1621
|
+
ownerAct: this.background ? undefined : this.ownerAct, // the owner's key: never a sub-agent's
|
|
1622
|
+
onOwnerAct: h.onOwnerAct,
|
|
1373
1623
|
// Truncation black-box: raw unparseable-args evidence → observability/blackbox.ts (content-bearing,
|
|
1374
1624
|
// local-only). NOT telemetry.jsonl — that stream is metrics-only by policy. A metrics-only marker
|
|
1375
1625
|
// still goes to telemetry so dashboards can count incidents without reading content.
|
|
@@ -1385,10 +1635,14 @@ export class Session {
|
|
|
1385
1635
|
// these now.") gets one nudge to actually do it (≤2/turn) instead of finalizing. Off in plan mode — there
|
|
1386
1636
|
// the text IS the deliverable ("I'll implement this once you approve") — and via KODE_TURN_CONTINUATION=0.
|
|
1387
1637
|
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
|
-
|
|
1638
|
+
// Decision points: a build turn's first change waits for the owner's choice of direction (ask_user) — in
|
|
1639
|
+
// Autonomous mode, for a plan review. Off in plan mode (the plan + exit picker IS the decision) and inert where
|
|
1640
|
+
// ask_user isn't registered (headless).
|
|
1641
|
+
decisionPoints: { enabled: this.decisionPoints && !this.planMode, planReview: this.planReview },
|
|
1391
1642
|
});
|
|
1643
|
+
// The conversation knows the mode only once the carried note is in it (a fast-start rewrite sends the raw text).
|
|
1644
|
+
if (mode.note && this.convo.all.slice(convoStart).some((m) => m.role === "user" && typeof m.content === "string" && m.content.includes(mode.note)))
|
|
1645
|
+
this.planReviewTold = mode.on;
|
|
1392
1646
|
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
1647
|
// MOA phase-0 ROUTE SHADOW (observability ONLY — routing is untouched): OPT-IN with KODE_MOA_SHADOW=1 (was on
|
|
1394
1648
|
// by default until 0.1.334). Its classifier call goes to the SAME endpoint as the turn, and on a single-slot
|
|
@@ -1440,23 +1694,25 @@ export class Session {
|
|
|
1440
1694
|
// Steps = the messages THIS turn added (user prompt → assistant rounds → tool results). A mid-turn
|
|
1441
1695
|
// compaction can splice the array (replaceAll), making the start index stale; if so the slice would be
|
|
1442
1696
|
// 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" }, {
|
|
1697
|
+
// A loop reset replaces this turn's rounds with one digest: the slice then holds the turn from that note on.
|
|
1698
|
+
turn.recorded = true;
|
|
1699
|
+
const record = {
|
|
1450
1700
|
input: text, content: res.content, rounds: res.rounds, toolCalls: res.toolCalls,
|
|
1451
1701
|
tokens: res.tokens, stopReason: res.stopReason, model: this.currentModel(),
|
|
1452
1702
|
cwd: process.cwd(), durationMs: Math.round(performance.now() - _t0), unverified: res.unverified,
|
|
1453
|
-
steps,
|
|
1454
|
-
}
|
|
1703
|
+
steps: this.turnSteps(convoStart, text), task, loop: res.loop, lessonTs: turn.lessonTs,
|
|
1704
|
+
};
|
|
1705
|
+
const cfg = this.selfImproveCfg();
|
|
1706
|
+
this.learn(() => runSelfImprove(cfg, record)); // after any lesson a loop recovery is still writing
|
|
1455
1707
|
return { ...res, interrupted: false, durationMs: Math.round(performance.now() - _t0) };
|
|
1456
1708
|
}
|
|
1457
1709
|
catch (e) {
|
|
1458
1710
|
if (e instanceof TurnAbortedError) {
|
|
1459
1711
|
this.telemetry.record({ type: "turn", rounds: 0, toolCalls: 0, interrupted: true, durationMs: Math.round(performance.now() - _t0), ctxPct: this.ctxPct() });
|
|
1712
|
+
const r = this.interruptedRecord(turn); // an esc is how the owner usually ends a loop: the loop still teaches
|
|
1713
|
+
const cfg = this.selfImproveCfg();
|
|
1714
|
+
if (r)
|
|
1715
|
+
this.learn(() => runSelfImprove(cfg, r));
|
|
1460
1716
|
return { content: "", rounds: 0, toolCalls: 0, interrupted: true };
|
|
1461
1717
|
}
|
|
1462
1718
|
this.telemetry.record({ type: "error", where: "send", errorClass: Telemetry.errorClass(e) });
|
|
@@ -1464,6 +1720,70 @@ export class Session {
|
|
|
1464
1720
|
}
|
|
1465
1721
|
finally {
|
|
1466
1722
|
this.ctrl = null;
|
|
1723
|
+
if (this.inflight === turn)
|
|
1724
|
+
this.inflight = undefined;
|
|
1725
|
+
this.turnHandlers = undefined;
|
|
1467
1726
|
}
|
|
1468
1727
|
}
|
|
1728
|
+
/** The self-improvement sinks: the flywheel (settings.selfImprove → KODE_SELFIMPROVE) and the memory sink
|
|
1729
|
+
* (settings.selfImprove.memory → KODE_SELFIMPROVE_MEMORY, ON by default — a looped or stuck turn's lesson → the global
|
|
1730
|
+
* memories.md; "0" opts out). */
|
|
1731
|
+
selfImproveCfg() {
|
|
1732
|
+
return { flywheel: process.env.KODE_SELFIMPROVE !== "0", memory: process.env.KODE_SELFIMPROVE_MEMORY !== "0", maxLessons: this.maxLessons };
|
|
1733
|
+
}
|
|
1734
|
+
/** The self-improvement writes, one after another: a loop recovery's lesson, then the turn's own row and lesson (same
|
|
1735
|
+
* stamp) — read-modify-writes of one memories file that must not interleave. Best-effort, never awaited by a turn. */
|
|
1736
|
+
learn(job) {
|
|
1737
|
+
this.selfImproveQueue = this.selfImproveQueue.then(job).catch(() => { });
|
|
1738
|
+
}
|
|
1739
|
+
/** 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
|
|
1740
|
+
* far, under the stamp the turn's every later write of it keeps (InflightTurn.lessonTs) — counted once, strongest
|
|
1741
|
+
* evidence kept (selfimprove/lessons.ts curateLessons). */
|
|
1742
|
+
recordRecoveryLesson(t) {
|
|
1743
|
+
const st = t.read?.();
|
|
1744
|
+
if (!st)
|
|
1745
|
+
return;
|
|
1746
|
+
const lessonTs = (t.lessonTs ??= Date.now());
|
|
1747
|
+
const r = {
|
|
1748
|
+
input: t.text, content: "", rounds: st.rounds, toolCalls: st.toolCalls, tokens: st.tokens, model: this.currentModel(),
|
|
1749
|
+
cwd: process.cwd(), durationMs: Math.round(performance.now() - t.t0), task: t.task, loop: st.loop, lessonTs,
|
|
1750
|
+
};
|
|
1751
|
+
const cfg = this.selfImproveCfg();
|
|
1752
|
+
this.learn(() => recordRecoveryLesson(cfg, r));
|
|
1753
|
+
}
|
|
1754
|
+
/** The step a recovered loop moved on with, after the calls it repeated: a mentor pair in the flywheel (selfimprove). */
|
|
1755
|
+
recordLoopPair(e) {
|
|
1756
|
+
if (this.selfImproveCfg().flywheel === false)
|
|
1757
|
+
return;
|
|
1758
|
+
if (isSubagentBrief(e.request))
|
|
1759
|
+
return; // a sub-agent's brief is not the owner's request: no mentor pair, as no lesson
|
|
1760
|
+
const ts = Date.now();
|
|
1761
|
+
const pair = loopMentorPair({ ts, attempt: e.attempt, request: e.request, model: this.currentModel(), repeated: e.repeated, forward: e.forward, answer: e.answer });
|
|
1762
|
+
this.learn(() => recordMentorPair(pair, ts));
|
|
1763
|
+
}
|
|
1764
|
+
/** The messages this turn added (its own message on), for the flywheel row. A mid-turn compaction can splice the array
|
|
1765
|
+
* (replaceAll), making the start index stale; then there are none and SRFT falls back cleanly rather than masking the
|
|
1766
|
+
* wrong rounds. */
|
|
1767
|
+
turnSteps(convoStart, text) {
|
|
1768
|
+
const intact = this.convo.all[convoStart]?.role === "user" && this.convo.all[convoStart]?.content === text;
|
|
1769
|
+
const turnMsgs = intact ? this.convo.all.slice(convoStart) : [];
|
|
1770
|
+
return turnMsgs.length ? turnMsgs.map((m) => ({
|
|
1771
|
+
role: m.role, content: m.content, tool_calls: m.tool_calls, tool_call_id: m.tool_call_id,
|
|
1772
|
+
})) : undefined;
|
|
1773
|
+
}
|
|
1774
|
+
/** The record of a turn that never returned (an esc, a signal): never promotable, and a lesson only when it looped. None
|
|
1775
|
+
* when it never settled a round (nothing to learn — a fast-start win aborts the turn there too) or was recorded. */
|
|
1776
|
+
interruptedRecord(t) {
|
|
1777
|
+
if (t.recorded)
|
|
1778
|
+
return undefined;
|
|
1779
|
+
t.recorded = true;
|
|
1780
|
+
const st = t.read?.();
|
|
1781
|
+
if (!st || st.rounds === 0)
|
|
1782
|
+
return undefined;
|
|
1783
|
+
return {
|
|
1784
|
+
input: t.text, content: "", rounds: st.rounds, toolCalls: st.toolCalls, tokens: st.tokens, model: this.currentModel(),
|
|
1785
|
+
cwd: process.cwd(), durationMs: Math.round(performance.now() - t.t0), steps: this.turnSteps(t.convoStart, t.text),
|
|
1786
|
+
task: t.task, loop: st.loop, interrupted: true, lessonTs: t.lessonTs,
|
|
1787
|
+
};
|
|
1788
|
+
}
|
|
1469
1789
|
}
|