omnius 1.0.549 → 1.0.551

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/index.js CHANGED
@@ -155716,7 +155716,7 @@ var require_snapshot_recorder = __commonJS({
155716
155716
  "../node_modules/undici/lib/mock/snapshot-recorder.js"(exports, module) {
155717
155717
  "use strict";
155718
155718
  var { writeFile: writeFile27, readFile: readFile25, mkdir: mkdir23 } = __require("node:fs/promises");
155719
- var { dirname: dirname58, resolve: resolve82 } = __require("node:path");
155719
+ var { dirname: dirname59, resolve: resolve82 } = __require("node:path");
155720
155720
  var { setTimeout: setTimeout3, clearTimeout: clearTimeout3 } = __require("node:timers");
155721
155721
  var { InvalidArgumentError, UndiciError } = require_errors2();
155722
155722
  var { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = require_snapshot_utils();
@@ -155947,7 +155947,7 @@ var require_snapshot_recorder = __commonJS({
155947
155947
  throw new InvalidArgumentError("Snapshot path is required");
155948
155948
  }
155949
155949
  const resolvedPath = resolve82(path16);
155950
- await mkdir23(dirname58(resolvedPath), { recursive: true });
155950
+ await mkdir23(dirname59(resolvedPath), { recursive: true });
155951
155951
  const data = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({
155952
155952
  hash,
155953
155953
  snapshot
@@ -269609,15 +269609,15 @@ var init_ls = __esm({
269609
269609
  });
269610
269610
 
269611
269611
  // ../node_modules/@helia/unixfs/dist/src/commands/mkdir.js
269612
- async function mkdir6(parentCid, dirname58, blockstore, options2 = {}) {
269613
- if (dirname58.includes("/")) {
269612
+ async function mkdir6(parentCid, dirname59, blockstore, options2 = {}) {
269613
+ if (dirname59.includes("/")) {
269614
269614
  throw new InvalidParametersError4("Path must not have slashes");
269615
269615
  }
269616
269616
  const entry = await exporter2(parentCid, blockstore, options2);
269617
269617
  if (entry.type !== "directory") {
269618
269618
  throw new NotADirectoryError(`${parentCid.toString()} was not a UnixFS directory`);
269619
269619
  }
269620
- log16("creating %s", dirname58);
269620
+ log16("creating %s", dirname59);
269621
269621
  const metadata = new UnixFS({
269622
269622
  type: "directory",
269623
269623
  mode: options2.mode,
@@ -269633,9 +269633,9 @@ async function mkdir6(parentCid, dirname58, blockstore, options2 = {}) {
269633
269633
  await blockstore.put(emptyDirCid, buf);
269634
269634
  const [directory, pblink] = await Promise.all([
269635
269635
  cidToDirectory(parentCid, blockstore, options2),
269636
- cidToPBLink(emptyDirCid, dirname58, blockstore, options2)
269636
+ cidToPBLink(emptyDirCid, dirname59, blockstore, options2)
269637
269637
  ]);
269638
- log16("adding empty dir called %s to %c", dirname58, parentCid);
269638
+ log16("adding empty dir called %s to %c", dirname59, parentCid);
269639
269639
  const result = await addLink(directory, pblink, blockstore, {
269640
269640
  ...options2,
269641
269641
  allowOverwriting: options2.force
@@ -270134,8 +270134,8 @@ var init_unixfs2 = __esm({
270134
270134
  async *ls(cid, options2 = {}) {
270135
270135
  yield* ls(cid, this.components.blockstore, options2);
270136
270136
  }
270137
- async mkdir(cid, dirname58, options2 = {}) {
270138
- return mkdir6(cid, dirname58, this.components.blockstore, options2);
270137
+ async mkdir(cid, dirname59, options2 = {}) {
270138
+ return mkdir6(cid, dirname59, this.components.blockstore, options2);
270139
270139
  }
270140
270140
  async rm(cid, path16, options2 = {}) {
270141
270141
  return rm3(cid, path16, this.components.blockstore, options2);
@@ -516914,7 +516914,7 @@ var require_path_browserify = __commonJS({
516914
516914
  _makeLong: function _makeLong(path16) {
516915
516915
  return path16;
516916
516916
  },
516917
- dirname: function dirname58(path16) {
516917
+ dirname: function dirname59(path16) {
516918
516918
  assertPath(path16);
516919
516919
  if (path16.length === 0) return ".";
516920
516920
  var code8 = path16.charCodeAt(0);
@@ -566998,6 +566998,7 @@ function createCompletionLedger(input) {
566998
566998
  const ts = nowIso2(input.now);
566999
566999
  return {
567000
567000
  runId: input.runId,
567001
+ ...typeof input.taskEpoch === "number" ? { taskEpoch: input.taskEpoch } : {},
567001
567002
  goal: cleanText(input.goal, 2e3),
567002
567003
  createdAtIso: ts,
567003
567004
  updatedAtIso: ts,
@@ -567183,7 +567184,23 @@ function appendUnresolved(items, text2, source) {
567183
567184
  }
567184
567185
  ];
567185
567186
  }
567187
+ function classifyCompletionProgress(entry) {
567188
+ if (entry.progressClass)
567189
+ return entry.progressClass;
567190
+ const targets = [...entry.targetPaths ?? [], entry.rawRef ?? ""];
567191
+ if (targets.some((target) => CONTROLLER_ARTIFACT_RE.test(target))) {
567192
+ return "control_bookkeeping";
567193
+ }
567194
+ if (entry.role === "blocker")
567195
+ return "blocker";
567196
+ if (entry.kind === "file_change" || entry.role === "mutation") {
567197
+ return "work_product";
567198
+ }
567199
+ return "observation";
567200
+ }
567186
567201
  function isMutationEvidence(entry) {
567202
+ if (classifyCompletionProgress(entry) !== "work_product")
567203
+ return false;
567187
567204
  if (entry.role === "mutation")
567188
567205
  return true;
567189
567206
  if (entry.kind === "file_change")
@@ -567314,10 +567331,12 @@ function saveCompletionLedger(filePath, ledger) {
567314
567331
  function loadCompletionLedger(filePath) {
567315
567332
  return JSON.parse(readFileSync66(filePath, "utf8"));
567316
567333
  }
567334
+ var CONTROLLER_ARTIFACT_RE;
567317
567335
  var init_completionLedger = __esm({
567318
567336
  "packages/orchestrator/dist/completionLedger.js"() {
567319
567337
  "use strict";
567320
567338
  init_completionContract();
567339
+ CONTROLLER_ARTIFACT_RE = /(?:^|[\\/])\.omnius(?:[\\/]|$)/i;
567321
567340
  }
567322
567341
  });
567323
567342
 
@@ -571700,48 +571719,44 @@ function ago(ms) {
571700
571719
  const h = Math.floor(m2 / 60);
571701
571720
  return `${h}h ago`;
571702
571721
  }
571703
- function computeNextActionHint(reconciled, recentFailures, focusDirective) {
571704
- if (focusDirective?.requiredNextAction) {
571705
- const reason = focusDirective.reason ? ` Reason: ${focusDirective.reason.slice(0, 180)}.` : "";
571706
- return `Active recovery directive requires ${focusDirective.requiredNextAction}.${reason} Follow that before completion or unrelated work.`;
571707
- }
571722
+ function computeNextActionHint(reconciled, recentFailures, _focusDirective) {
571708
571723
  if (recentFailures.length > 0) {
571709
571724
  const first2 = recentFailures[0];
571710
- return `Resolve or explicitly account for unresolved failure "${first2.stem}" (${first2.attempts} attempt${first2.attempts === 1 ? "" : "s"}). Do not infer completion from plan state while failures remain.`;
571725
+ return `Unresolved failure: "${first2.stem}" (${first2.attempts} attempt${first2.attempts === 1 ? "" : "s"}).`;
571711
571726
  }
571712
571727
  const inProgress = reconciled.find((t2) => t2.reconciled === "in_progress");
571713
571728
  if (inProgress)
571714
- return `Continue your in-progress item: "${inProgress.content.slice(0, 100)}".`;
571729
+ return `In-progress plan item: "${inProgress.content.slice(0, 100)}".`;
571715
571730
  const claimedMissing = reconciled.filter((t2) => t2.reconciled === "claimed_missing");
571716
571731
  if (claimedMissing.length > 0) {
571717
571732
  const first2 = claimedMissing[0];
571718
571733
  const missing = first2.artifactCheck?.find((c9) => c9.reason === "missing")?.path;
571719
- return `A completed todo claims an artifact that is missing on disk: "${first2.content.slice(0, 60)}" expected ${missing ?? "an artifact"}. Either produce it or correct the todo.`;
571734
+ return `Plan/disk mismatch: completed todo "${first2.content.slice(0, 60)}" claims missing ${missing ?? "artifact"}.`;
571720
571735
  }
571721
571736
  const claimedEmpty = reconciled.filter((t2) => t2.reconciled === "claimed_empty");
571722
571737
  if (claimedEmpty.length > 0) {
571723
571738
  const first2 = claimedEmpty[0];
571724
- return `A completed todo declares an empty artifact: "${first2.content.slice(0, 60)}". Fill it in or revise the todo.`;
571739
+ return `Plan/disk mismatch: completed todo "${first2.content.slice(0, 60)}" declares an empty artifact.`;
571725
571740
  }
571726
571741
  const claimedNoProof = reconciled.filter((t2) => t2.reconciled === "claimed_no_proof");
571727
571742
  if (claimedNoProof.length > 0) {
571728
571743
  const first2 = claimedNoProof[0];
571729
- return `A completed todo has no on-disk evidence: "${first2.content.slice(0, 80)}". Add declaredArtifacts to the next todo_write so completion is verifiable.`;
571744
+ return `Plan evidence gap: completed todo "${first2.content.slice(0, 80)}" has no declared on-disk evidence.`;
571730
571745
  }
571731
571746
  const pending2 = reconciled.filter((t2) => t2.reconciled === "pending");
571732
571747
  if (pending2.length > 0) {
571733
571748
  const first2 = pending2[0];
571734
- return `Next pending plan item: "${first2.content.slice(0, 100)}". Take direct action toward it.`;
571749
+ return `Pending plan item: "${first2.content.slice(0, 100)}".`;
571735
571750
  }
571736
571751
  const completedUnverified = reconciled.filter((t2) => t2.reconciled === "completed_unverified");
571737
571752
  if (completedUnverified.length > 0) {
571738
571753
  const first2 = completedUnverified[0];
571739
- return `A completed todo has a verifyCommand that hasn't run during this snapshot: ${first2.rationale}`;
571754
+ return `Verification evidence is absent for completed todo: ${first2.rationale}`;
571740
571755
  }
571741
571756
  if (reconciled.length === 0) {
571742
- return `No declared plan items are available. Continue from the active goal and evidence; report completion only with direct verification.`;
571757
+ return `No declared plan items are available.`;
571743
571758
  }
571744
- return `Declared plan items have no visible gaps. Continue from the active goal and evidence; report completion only with direct verification.`;
571759
+ return `Declared plan items have no visible disk gaps in this snapshot.`;
571745
571760
  }
571746
571761
  function regenerate(opts) {
571747
571762
  const startMs = Date.now();
@@ -571836,22 +571851,11 @@ function regenerate(opts) {
571836
571851
  }
571837
571852
  }
571838
571853
  lines.push(``);
571839
- if (opts.focusDirective?.requiredNextAction) {
571840
- lines.push(`ACTIVE RECOVERY DIRECTIVE:`);
571841
- lines.push(` required_next_action=${opts.focusDirective.requiredNextAction}`);
571842
- if (opts.focusDirective.state) {
571843
- lines.push(` state=${opts.focusDirective.state}`);
571844
- }
571845
- if (opts.focusDirective.reason) {
571846
- lines.push(` reason=${opts.focusDirective.reason.slice(0, 240)}`);
571847
- }
571848
- lines.push(``);
571849
- }
571850
571854
  const nextActionHint = computeNextActionHint(reconciled, opts.recentFailures, opts.focusDirective);
571851
- lines.push(`SUGGESTED NEXT STEP (derived from gap analysis, not authoritative):`);
571855
+ lines.push(`PLAN / FAILURE DIAGNOSTIC:`);
571852
571856
  lines.push(` ${nextActionHint}`);
571853
571857
  lines.push(``);
571854
- lines.push(`This snapshot replaces re-derivation by tool calls. Prior <world-state> blocks have been stripped from this conversation. Re-listing the workspace or re-reading completed todos is unproductive — the data is in this block.`);
571858
+ lines.push(`Snapshot scope: workspace scan, reconciled plan, and unresolved failures at generation time. Prior world-state snapshots are replaced on regeneration.`);
571855
571859
  lines.push(`</world-state>`);
571856
571860
  const block = lines.join("\n");
571857
571861
  return {
@@ -572696,35 +572700,8 @@ ${item.outputPreview ?? ""}`));
572696
572700
  return directive;
572697
572701
  }
572698
572702
  function renderDirectiveAsMessage(d2) {
572699
- if (d2.parseFallback) {
572700
- return "";
572701
- }
572702
- const lines = [];
572703
- lines.push(`[STUCK-STATE META-ANALYZER — REG-49]`);
572704
- lines.push(``);
572705
- lines.push(`A meta-analyzer sub-agent reviewed the recent tool-call pattern, the`);
572706
- lines.push(`current world state, and the plan; it produced a single concrete`);
572707
- lines.push(`unblocking action for you to take.`);
572708
- lines.push(``);
572709
- lines.push(`DIAGNOSIS: ${d2.diagnosis}`);
572710
- lines.push(``);
572711
- lines.push(`STOP DOING (anti-pattern): ${d2.anti_pattern}`);
572712
- lines.push(``);
572713
- lines.push(`DO NEXT:`);
572714
- lines.push(` Tool: ${d2.next_action.tool}`);
572715
- const argsJson = JSON.stringify(d2.next_action.args_seed, null, 2);
572716
- lines.push(` Args:`);
572717
- for (const ln of argsJson.split("\n"))
572718
- lines.push(` ${ln}`);
572719
- lines.push(` Rationale: ${d2.next_action.rationale}`);
572720
- lines.push(``);
572721
- lines.push(`AFTER THE ACTION, verify with: ${d2.verification}`);
572722
- lines.push(``);
572723
- lines.push(`This directive comes from a meta-analysis of YOUR recent activity. Treat`);
572724
- lines.push(`the args as a bounded recommendation, not permission to invent a target.`);
572725
- lines.push(`If its evidence is stale or insufficient, first refresh the cited target`);
572726
- lines.push(`or run the listed verification; do not repeat the anti-pattern.`);
572727
- return lines.join("\n");
572703
+ void d2;
572704
+ return "";
572728
572705
  }
572729
572706
  async function runStuckAnalyzer(opts) {
572730
572707
  const startMs = Date.now();
@@ -573102,42 +573079,8 @@ function parseFrameVerdict(rawResponse) {
573102
573079
  };
573103
573080
  }
573104
573081
  function renderVerdictAsMessage(v) {
573105
- if (v.parseFallback)
573106
- return "";
573107
- if (v.verdict === "continue")
573108
- return "";
573109
- const lines = [];
573110
- lines.push(`[PROBLEM-FRAME VALIDATION — REG-51 — ${v.verdict.toUpperCase()}]`);
573111
- lines.push(``);
573112
- lines.push(`A meta-strategy validator reviewed your goal, current sub-task, and recent`);
573113
- lines.push(`activity. Verdict:`);
573114
- lines.push(``);
573115
- lines.push(` ${v.rationale}`);
573116
- lines.push(``);
573117
- if (v.verdict === "simplify" || v.verdict === "pivot") {
573118
- const rf = v.recommended_frame;
573119
- const verb = v.verdict === "simplify" ? "SHRINK YOUR CURRENT FRAME" : "PIVOT TO A DIFFERENT FRAME";
573120
- lines.push(`${verb}:`);
573121
- lines.push(``);
573122
- lines.push(` New sub-task: ${rf.new_subtask}`);
573123
- lines.push(` Why this is better: ${rf.why_better}`);
573124
- lines.push(` Done when: ${rf.success_criterion}`);
573125
- lines.push(``);
573126
- lines.push(`Update your todo list to reflect this new framing on your next response.`);
573127
- lines.push(`Then take ONE concrete action toward the new sub-task. Do NOT continue`);
573128
- lines.push(`the previous approach — it has been judged ${v.verdict === "pivot" ? "wrong" : "too ambitious"} for`);
573129
- lines.push(`your current state.`);
573130
- } else if (v.verdict === "declare-blocked") {
573131
- lines.push(`DECLARE BLOCKED:`);
573132
- lines.push(``);
573133
- lines.push(` ${v.blocker_summary}`);
573134
- lines.push(``);
573135
- lines.push(`Call task_complete with a summary that names this blocker EXPLICITLY. Do`);
573136
- lines.push(`not pretend the work is done; do not keep iterating. The validator has`);
573137
- lines.push(`determined no productive frame exists from this state. Surface the`);
573138
- lines.push(`blocker and let the user / next agent intervene.`);
573139
- }
573140
- return lines.join("\n");
573082
+ void v;
573083
+ return "";
573141
573084
  }
573142
573085
  async function runFrameValidator(opts) {
573143
573086
  const startMs = Date.now();
@@ -574029,9 +573972,8 @@ function buildTrajectoryCheckpoint(input) {
574029
573972
  doNotRepeat.push("Retrying the blocked action unchanged without new evidence.");
574030
573973
  } else if (focus) {
574031
573974
  assessment = "recovery_required";
574032
- nextAction = extractFocusNextAction(focus) || nextAction;
574033
- successEvidence = "The focus recovery requirement is satisfied by a fresh tool observation.";
574034
- doNotRepeat.push("Ignoring the active focus recovery directive.");
573975
+ const focusDiagnostic = extractFocusNextAction(focus);
573976
+ successEvidence = focusDiagnostic ? `Active controller directive remains unresolved: ${focusDiagnostic}` : "An active controller directive is unresolved; its evidence is recorded separately.";
574035
573977
  } else if (hasRecentFailure && !fullWriteRecoveredByMutation) {
574036
573978
  assessment = "recovery_required";
574037
573979
  nextAction = "Use the newest failure evidence to make one different, narrow diagnostic or repair action.";
@@ -574137,7 +574079,7 @@ function buildTrajectoryCheckpoint(input) {
574137
574079
  }
574138
574080
  function renderTrajectoryCheckpoint(checkpoint, maxChars = 1100) {
574139
574081
  const lines = [
574140
- "[TRAJECTORY CHECKPOINT]",
574082
+ "[TRAJECTORY DIAGNOSTIC]",
574141
574083
  `revision=${checkpoint.revision} turn=${checkpoint.turn} trigger=${checkpoint.trigger}`,
574142
574084
  `Goal: ${checkpoint.goal}`,
574143
574085
  `Assessment: ${checkpoint.assessment}`,
@@ -574145,8 +574087,8 @@ function renderTrajectoryCheckpoint(checkpoint, maxChars = 1100) {
574145
574087
  checkpoint.currentStep ? `Current step: ${checkpoint.currentStep}` : null,
574146
574088
  // Keep the action contract ahead of explanatory evidence so truncation can
574147
574089
  // never hide the guard that the main agent must follow.
574148
- `Required next action: ${checkpoint.nextAction}`,
574149
- `Success evidence: ${checkpoint.successEvidence}`,
574090
+ `Observed next action: ${checkpoint.nextAction}`,
574091
+ `Observed success evidence: ${checkpoint.successEvidence}`,
574150
574092
  checkpoint.situationAssessment ? `${checkpoint.groundingSource === "model" ? "Reasoned situation" : "Safety orientation"}: ${checkpoint.situationAssessment}` : null,
574151
574093
  checkpoint.groundingEvidenceRefs?.length ? `Grounding evidence: ${checkpoint.groundingEvidenceRefs.join(", ")}` : null,
574152
574094
  checkpoint.completedWork.length > 0 ? `Completed evidence-backed work: ${checkpoint.completedWork.join("; ")}` : null,
@@ -574154,9 +574096,8 @@ function renderTrajectoryCheckpoint(checkpoint, maxChars = 1100) {
574154
574096
  ...checkpoint.groundedFacts.map((fact) => `- [${fact.evidence}; ${fact.freshness}] ${fact.statement}`),
574155
574097
  checkpoint.openQuestions.length > 0 ? "Open questions:" : null,
574156
574098
  ...checkpoint.openQuestions.map((question) => `- ${question}`),
574157
- checkpoint.doNotRepeat.length > 0 ? "Do not repeat:" : null,
574158
- ...checkpoint.doNotRepeat.map((constraint) => `- ${constraint}`),
574159
- "Attention rule: reconcile the next tool call with this checkpoint. Treat stale or unknown evidence as a reason to read or verify. Do not quote this checkpoint or produce a reasoning transcript."
574099
+ checkpoint.doNotRepeat.length > 0 ? "Recorded retry risks:" : null,
574100
+ ...checkpoint.doNotRepeat.map((constraint) => `- ${constraint}`)
574160
574101
  ].filter((line) => Boolean(line));
574161
574102
  return truncate2(lines.join("\n"), maxChars);
574162
574103
  }
@@ -574466,6 +574407,8 @@ function writeTaskHandoff(omniusDir, handoff) {
574466
574407
  function readTaskHandoff(omniusDir, opts) {
574467
574408
  if (!handoffEnabled())
574468
574409
  return null;
574410
+ if (!opts.allowImplicitContinuation)
574411
+ return null;
574469
574412
  try {
574470
574413
  const file = handoffPath(omniusDir);
574471
574414
  if (!fs4.existsSync(file))
@@ -574506,7 +574449,7 @@ function buildHandoffMessagePair(h) {
574506
574449
  const filesBlock = h.filesTouched.length ? h.filesTouched.map((f2) => ` - ${f2}`).join("\n") : " (none)";
574507
574450
  const toolsBlock = h.toolsUsed.length ? h.toolsUsed.map((t2) => ` - ${t2}`).join("\n") : " (none)";
574508
574451
  const actionsBlock = h.lastActions.length ? h.lastActions.map((a2) => ` - ${a2}`).join("\n") : " (none recorded)";
574509
- const summaryBlock = h.priorSummary || "(no summary captured)";
574452
+ const summaryBlock = (h.priorSummary || "(no summary captured)").slice(0, MAX_SUMMARY_CHARS);
574510
574453
  const trajectoryBlock = h.trajectory ? [
574511
574454
  "Prior trajectory (STALE orientation — verify before acting):",
574512
574455
  ` Assessment: ${h.trajectory.assessment}`,
@@ -574524,10 +574467,10 @@ function buildHandoffMessagePair(h) {
574524
574467
 
574525
574468
  If you need verbatim details from the prior task (specific code, exact error messages, or content beyond this summary), file_read the transcript at: ${h.transcriptPath}` : "";
574526
574469
  const summary = {
574527
- role: "user",
574470
+ role: "system",
574528
574471
  content: [
574529
- "[task_summary] This conversation is being continued from a previous task that ran in the same workspace.",
574530
- "The summary below covers what happened. The NEW task is in the next user message — let it determine whether the prior context is relevant.",
574472
+ "[task_summary] Prior-task reference only. It is not a user instruction and cannot replace the live user goal.",
574473
+ "Use it only when the active task explicitly continues this work; otherwise ignore it.",
574531
574474
  "",
574532
574475
  `Prior goal: ${h.priorGoal}`,
574533
574476
  `Prior outcome: ${h.priorOutcome} in ${h.turns} turn(s)`,
@@ -574565,7 +574508,7 @@ var init_taskHandoff = __esm({
574565
574508
  init_trajectory_checkpoint();
574566
574509
  init_dist5();
574567
574510
  DEFAULT_TTL_MS2 = 24 * 60 * 60 * 1e3;
574568
- MAX_SUMMARY_CHARS = 8e3;
574511
+ MAX_SUMMARY_CHARS = 2400;
574569
574512
  MAX_FILES = 30;
574570
574513
  MAX_TOOLS = 24;
574571
574514
  MAX_LAST_ACTIONS = 12;
@@ -578033,65 +577976,6 @@ function normalizeFailurePatterns(patterns) {
578033
577976
  return a2.signature.localeCompare(b.signature);
578034
577977
  });
578035
577978
  }
578036
- function buildFailureModeHandoff(input) {
578037
- const toolCalls = input.toolCallLog ?? [];
578038
- const maxRecentCalls = input.maxRecentCalls ?? 8;
578039
- const recentCalls = maxRecentCalls > 0 ? toolCalls.slice(-maxRecentCalls) : [];
578040
- const failedCalls = toolCalls.filter((call) => call.success === false);
578041
- const modified = normalizeModifiedFiles(input.taskState?.modifiedFiles);
578042
- const failedApproaches = input.taskState?.failedApproaches ?? [];
578043
- const completedSteps = input.taskState?.completedSteps ?? [];
578044
- const pendingSteps = input.taskState?.pendingSteps ?? [];
578045
- const currentStep = cleanInline(input.taskState?.currentStep, 180);
578046
- const nextAction = cleanInline(input.taskState?.nextAction, 180);
578047
- const goal = cleanInline(input.taskGoal || input.taskState?.goal || input.taskState?.originalGoal || "", 260);
578048
- const patterns = normalizeFailurePatterns(input.errorPatterns).slice(0, input.maxPatterns ?? 10);
578049
- if (patterns.length === 0 && recentCalls.length === 0 && modified.length === 0 && failedApproaches.length === 0 && !goal) {
578050
- return null;
578051
- }
578052
- const lines = ["[FAILURE-MODE INTAKE]"];
578053
- if (goal)
578054
- lines.push(`Goal: ${goal}`);
578055
- if (patterns.length > 0) {
578056
- lines.push("Top persisted failure modes:");
578057
- for (const p2 of patterns) {
578058
- const guidance = p2.guidance ? ` - ${p2.guidance}` : "";
578059
- lines.push(`- ${p2.signature} x${p2.count}${guidance}`);
578060
- }
578061
- }
578062
- if (recentCalls.length > 0) {
578063
- const total = toolCalls.length;
578064
- const failed = failedCalls.length;
578065
- const mutations = toolCalls.filter((call) => call.mutated || (call.mutatedFiles?.length ?? 0) > 0).length;
578066
- lines.push(`Current run: ${total} tool calls, ${failed} failed, ${mutations} mutation calls.`);
578067
- const lastFailure = failedCalls[failedCalls.length - 1];
578068
- if (lastFailure) {
578069
- const preview = cleanInline(lastFailure.outputPreview, 240);
578070
- lines.push(`Last raw failure: ${lastFailure.name}${preview ? ` - ${preview}` : ""}`);
578071
- }
578072
- }
578073
- if (modified.length > 0) {
578074
- lines.push(`Files touched: ${modified.slice(-8).map(([path16, action]) => `${path16} (${action})`).join(", ")}`);
578075
- } else {
578076
- lines.push("Files touched: none recorded.");
578077
- }
578078
- if (completedSteps.length > 0) {
578079
- lines.push(`Recent completed steps: ${completedSteps.slice(-4).join("; ")}`);
578080
- }
578081
- if (currentStep)
578082
- lines.push(`Current step: ${currentStep}`);
578083
- if (failedApproaches.length > 0) {
578084
- lines.push(`Failed approaches: ${failedApproaches.slice(-4).join("; ")}`);
578085
- }
578086
- if (pendingSteps.length > 0) {
578087
- lines.push(`Remaining work: ${pendingSteps.slice(0, 5).join("; ")}`);
578088
- } else if (nextAction) {
578089
- lines.push(`Next action: ${nextAction}`);
578090
- }
578091
- lines.push("Operating rule: base the next move on the raw failure/output state above; do not repeat the same failed approach unchanged.");
578092
- lines.push("[/FAILURE-MODE INTAKE]");
578093
- return lines.join("\n");
578094
- }
578095
577979
  function computeCommitProgressGate(input) {
578096
577980
  const cooldown = input.cooldownTurns ?? 4;
578097
577981
  if (typeof input.lastInjectedTurn === "number" && input.lastInjectedTurn >= 0 && input.turn - input.lastInjectedTurn < cooldown) {
@@ -578678,6 +578562,88 @@ context_fabric: included=${included.length} dropped=${dropped.length} truncated=
578678
578562
  });
578679
578563
 
578680
578564
  // packages/orchestrator/dist/context-compiler.js
578565
+ function isControllerStateMessage(message2) {
578566
+ return typeof message2.content === "string" && message2.content.includes(CONTROLLER_STATE_MARKER);
578567
+ }
578568
+ function isActionGroundTruthMessage(message2) {
578569
+ return typeof message2.content === "string" && message2.content.includes(ACTION_GROUND_TRUTH_MARKER);
578570
+ }
578571
+ function isProtectedControllerMessage(message2) {
578572
+ return isControllerStateMessage(message2) || isActionGroundTruthMessage(message2);
578573
+ }
578574
+ function modelFacingMessageCap(message2) {
578575
+ if (isControllerStateMessage(message2)) {
578576
+ return MODEL_FACING_CONTROLLER_STATE_CHAR_CAP;
578577
+ }
578578
+ if (isActionGroundTruthMessage(message2)) {
578579
+ return MODEL_FACING_ACTION_GROUND_TRUTH_CHAR_CAP;
578580
+ }
578581
+ if (message2.role === "tool")
578582
+ return MODEL_FACING_TOOL_CHAR_CAP;
578583
+ if (message2.role === "system")
578584
+ return MODEL_FACING_SYSTEM_CHAR_CAP;
578585
+ return messageText(message2.content).length;
578586
+ }
578587
+ function stripLegacyRuntimeControlFragments(content) {
578588
+ let out = content;
578589
+ out = out.replace(new RegExp(`(?:^|\\n)\\s*${LEGACY_RUNTIME_CONTROL_BLOCK_START_RE.source}[\\s\\S]*?(?=\\n\\s*\\n|\\n(?=\\s*#{1,6}\\s)|\\n(?=\\s*\\[(?:CONTROLLER STATE v1|RECENT ACTION GROUND TRUTH)\\])|$)`, "gim"), "\n");
578590
+ const pieces = out.split(/(\n\s*\n)/);
578591
+ out = pieces.map((piece) => LEGACY_RUNTIME_CONTROL_FRAGMENT_RE.test(piece) ? "" : piece).join("");
578592
+ return collapseWhitespace(out);
578593
+ }
578594
+ function splitOversizedSystemMessages(messages2) {
578595
+ const out = [];
578596
+ for (const message2 of messages2) {
578597
+ if (message2.role !== "system" || typeof message2.content !== "string" || isProtectedControllerMessage(message2) || message2.content.length <= MODEL_FACING_SYSTEM_CHAR_CAP) {
578598
+ out.push(message2);
578599
+ continue;
578600
+ }
578601
+ let remaining = message2.content.trim();
578602
+ while (remaining.length > MODEL_FACING_SYSTEM_CHAR_CAP) {
578603
+ const window2 = remaining.slice(0, MODEL_FACING_SYSTEM_CHAR_CAP);
578604
+ const boundary = Math.max(window2.lastIndexOf("\n\n"), window2.lastIndexOf("\n"));
578605
+ const cut = boundary >= Math.floor(MODEL_FACING_SYSTEM_CHAR_CAP * 0.5) ? boundary : MODEL_FACING_SYSTEM_CHAR_CAP;
578606
+ const chunk = remaining.slice(0, cut).trim();
578607
+ if (chunk)
578608
+ out.push({ ...message2, content: chunk });
578609
+ remaining = remaining.slice(cut).trimStart();
578610
+ }
578611
+ if (remaining)
578612
+ out.push({ ...message2, content: remaining });
578613
+ }
578614
+ return out;
578615
+ }
578616
+ function isCurrentGoalMessage(message2) {
578617
+ return typeof message2.content === "string" && message2.content.includes("[CURRENT USER GOAL]");
578618
+ }
578619
+ function applyModelFacingBudget(messages2, preserveFirstSystem) {
578620
+ const reservedTransaction = latestResolvedToolTransaction(messages2);
578621
+ const reservedChars = [...reservedTransaction].reduce((sum2, index) => sum2 + modelFacingReservedChars(messages2[index]), 0);
578622
+ let remaining = Math.max(0, MODEL_FACING_CONTEXT_CHAR_BUDGET - reservedChars);
578623
+ const kept = [];
578624
+ for (let index = 0; index < messages2.length; index++) {
578625
+ const message2 = messages2[index];
578626
+ const content = messageText(message2.content);
578627
+ const isReservedTransactionMessage = reservedTransaction.has(index);
578628
+ const isPriorityIntent = message2.role === "user" || isCurrentGoalMessage(message2);
578629
+ const perMessageCap = modelFacingMessageCap(message2);
578630
+ const isProtectedController = isProtectedControllerMessage(message2);
578631
+ const allowed = isReservedTransactionMessage ? perMessageCap : isPriorityIntent ? content.length : isProtectedController ? perMessageCap : Math.min(remaining, perMessageCap);
578632
+ if (!isReservedTransactionMessage && !isPriorityIntent && !isProtectedController && allowed <= 0) {
578633
+ continue;
578634
+ }
578635
+ const bounded = content.length > allowed && allowed > 0 ? `${content.slice(0, Math.max(0, allowed - 83))}
578636
+ [truncated_by_context_budget: retained higher-priority current intent/evidence]` : content;
578637
+ if (!isReservedTransactionMessage && !isPriorityIntent && !isProtectedController && !bounded) {
578638
+ continue;
578639
+ }
578640
+ kept.push(typeof message2.content === "string" ? { ...message2, content: bounded } : message2);
578641
+ if (!isReservedTransactionMessage && !isPriorityIntent) {
578642
+ remaining = Math.max(0, remaining - bounded.length);
578643
+ }
578644
+ }
578645
+ return kept;
578646
+ }
578681
578647
  function collapseWhitespace(text2) {
578682
578648
  return text2.replace(/\r\n/g, "\n").split("\n").map((line) => line.trimEnd()).join("\n").replace(/\n{3,}/g, "\n\n").trim();
578683
578649
  }
@@ -578710,10 +578676,89 @@ function messageText(content) {
578710
578676
  return "";
578711
578677
  }).filter(Boolean).join("\n");
578712
578678
  }
578679
+ function toolCallIds(message2) {
578680
+ const calls = message2["tool_calls"];
578681
+ if (!Array.isArray(calls))
578682
+ return [];
578683
+ return calls.flatMap((call) => {
578684
+ if (!call || typeof call !== "object")
578685
+ return [];
578686
+ const id2 = call["id"];
578687
+ return typeof id2 === "string" && id2 ? [id2] : [];
578688
+ });
578689
+ }
578690
+ function hasToolCallsMetadata(message2) {
578691
+ return Array.isArray(message2["tool_calls"]);
578692
+ }
578693
+ function linkedToolCallId(message2) {
578694
+ const id2 = message2["tool_call_id"];
578695
+ return typeof id2 === "string" && id2 ? id2 : null;
578696
+ }
578697
+ function latestResolvedToolTransaction(messages2) {
578698
+ const resultIndexesById = /* @__PURE__ */ new Map();
578699
+ for (let index = 0; index < messages2.length; index++) {
578700
+ const message2 = messages2[index];
578701
+ if (message2.role !== "tool")
578702
+ continue;
578703
+ const id2 = linkedToolCallId(message2);
578704
+ if (!id2)
578705
+ continue;
578706
+ const indexes = resultIndexesById.get(id2) ?? [];
578707
+ indexes.push(index);
578708
+ resultIndexesById.set(id2, indexes);
578709
+ }
578710
+ for (let index = messages2.length - 1; index >= 0; index--) {
578711
+ const message2 = messages2[index];
578712
+ if (message2.role !== "assistant")
578713
+ continue;
578714
+ const callIds = toolCallIds(message2);
578715
+ if (callIds.length === 0 || !callIds.every((id2) => resultIndexesById.has(id2))) {
578716
+ continue;
578717
+ }
578718
+ const transaction = /* @__PURE__ */ new Set([index]);
578719
+ for (const id2 of callIds) {
578720
+ for (const resultIndex of resultIndexesById.get(id2) ?? []) {
578721
+ transaction.add(resultIndex);
578722
+ }
578723
+ }
578724
+ return transaction;
578725
+ }
578726
+ return /* @__PURE__ */ new Set();
578727
+ }
578728
+ function modelFacingReservedChars(message2) {
578729
+ const content = messageText(message2.content);
578730
+ const cap = modelFacingMessageCap(message2);
578731
+ return Math.min(content.length, cap);
578732
+ }
578733
+ function retireLinkedAssistantReadIntents(messages2) {
578734
+ const resolvedToolCallIds = new Set(messages2.filter((message2) => message2.role === "tool").map(linkedToolCallId).filter((id2) => id2 !== null));
578735
+ return messages2.map((message2, index) => {
578736
+ const callIds = toolCallIds(message2);
578737
+ let nextNonSystemMessage;
578738
+ for (let candidateIndex = index + 1; candidateIndex < messages2.length; candidateIndex++) {
578739
+ const candidate = messages2[candidateIndex];
578740
+ if (candidate.role === "system")
578741
+ continue;
578742
+ nextNonSystemMessage = candidate;
578743
+ break;
578744
+ }
578745
+ const hasLegacyAdjacentToolResult = message2.role === "assistant" && !hasToolCallsMetadata(message2) && nextNonSystemMessage?.role === "tool" && linkedToolCallId(nextNonSystemMessage) === null;
578746
+ if (message2.role !== "assistant" || typeof message2.content !== "string" || !(callIds.some((id2) => resolvedToolCallIds.has(id2)) || hasLegacyAdjacentToolResult) || !/\b(?:i|we)\s+(?:need|will|should|have)\s+to\s+(?:read|inspect|open)\b/i.test(message2.content)) {
578747
+ return message2;
578748
+ }
578749
+ return { ...message2, content: ASSISTANT_READ_INTENT_RETIRED_MARKER };
578750
+ });
578751
+ }
578713
578752
  function runtimeControlSemanticKey(content) {
578714
578753
  const normalized = content.replace(/\s+/g, " ").trim().toLowerCase();
578715
578754
  if (!normalized)
578716
578755
  return null;
578756
+ if (content.includes(CONTROLLER_STATE_MARKER)) {
578757
+ return "context.controller-state";
578758
+ }
578759
+ if (content.includes(ACTION_GROUND_TRUTH_MARKER)) {
578760
+ return "context.action-ground-truth";
578761
+ }
578717
578762
  if (content.includes("[ACTIVE CONTEXT FRAME]"))
578718
578763
  return "context.active-frame";
578719
578764
  if (content.includes("[TRAJECTORY CHECKPOINT]"))
@@ -578799,8 +578844,16 @@ function retireDuplicateToolFailures(messages2) {
578799
578844
  function prepareModelFacingApiMessages(input) {
578800
578845
  const preserveFirstSystem = input.preserveFirstSystem !== false;
578801
578846
  const sanitized = [];
578802
- for (let index = 0; index < input.messages.length; index++) {
578803
- const message2 = input.messages[index];
578847
+ const withoutLegacyControl = input.messages.flatMap((message2) => {
578848
+ if (message2.role !== "system" || typeof message2.content !== "string" || isProtectedControllerMessage(message2)) {
578849
+ return [message2];
578850
+ }
578851
+ const stripped = stripLegacyRuntimeControlFragments(message2.content);
578852
+ return stripped ? [{ ...message2, content: stripped }] : [];
578853
+ });
578854
+ const independentlyBounded = splitOversizedSystemMessages(withoutLegacyControl);
578855
+ for (let index = 0; index < independentlyBounded.length; index++) {
578856
+ const message2 = independentlyBounded[index];
578804
578857
  if (message2.role === "system" && typeof message2.content === "string") {
578805
578858
  if (preserveFirstSystem && sanitized.length === 0) {
578806
578859
  sanitized.push({ ...message2 });
@@ -578859,7 +578912,7 @@ function prepareModelFacingApiMessages(input) {
578859
578912
  const insertAt = preserveFirstSystem && deduped[0]?.role === "system" ? 1 : 0;
578860
578913
  deduped.splice(insertAt, 0, goalMessage);
578861
578914
  }
578862
- return deduped;
578915
+ return retireLinkedAssistantReadIntents(applyModelFacingBudget(deduped, preserveFirstSystem));
578863
578916
  }
578864
578917
  function deriveCurrentGoal(input) {
578865
578918
  const explicit = sanitizeModelVisibleContextText(input.explicitGoal ?? "");
@@ -578892,9 +578945,36 @@ function normalizeContextSignalsForModel(signals) {
578892
578945
  }
578893
578946
  return { signals: normalized, rejected };
578894
578947
  }
578948
+ function typeControllerSignal(signal) {
578949
+ if (signal.modelVisible === false)
578950
+ return signal;
578951
+ if (signal.content.includes(CONTROLLER_STATE_MARKER)) {
578952
+ return {
578953
+ ...signal,
578954
+ id: "controller-state-v1",
578955
+ dedupeKey: "context.controller_state_v1",
578956
+ semanticKey: "context.controller_state_v1",
578957
+ conflictGroup: "context.controller_state",
578958
+ priority: Math.max(signal.priority ?? 0, PRIORITY.GOAL + 15),
578959
+ ttlTurns: 1
578960
+ };
578961
+ }
578962
+ if (signal.content.includes(ACTION_GROUND_TRUTH_MARKER)) {
578963
+ return {
578964
+ ...signal,
578965
+ id: "recent-action-ground-truth",
578966
+ dedupeKey: "context.recent_action_ground_truth",
578967
+ semanticKey: "context.recent_action_ground_truth",
578968
+ conflictGroup: "context.action_ground_truth",
578969
+ priority: Math.max(signal.priority ?? 0, PRIORITY.GOAL + 14),
578970
+ ttlTurns: 1
578971
+ };
578972
+ }
578973
+ return signal;
578974
+ }
578895
578975
  function compileContextFrameV2(input) {
578896
578976
  const builder = input.builder ?? new ContextFrameBuilder();
578897
- const normalized = normalizeContextSignalsForModel(input.signals);
578977
+ const normalized = normalizeContextSignalsForModel(input.signals.map(typeControllerSignal));
578898
578978
  const goal = deriveCurrentGoal({
578899
578979
  explicitGoal: input.currentGoal,
578900
578980
  signals: normalized.signals
@@ -578927,15 +579007,28 @@ function compileContextFrameV2(input) {
578927
579007
  warnings: [...new Set(warnings)],
578928
579008
  admittedSignals: frame.included.length,
578929
579009
  rejectedSignals: normalized.rejected.length,
578930
- hadConcreteGoal: goal.concrete
579010
+ hadConcreteGoal: goal.concrete,
579011
+ admittedChars: frame.included.reduce((total, signal) => total + signal.content.length, 0),
579012
+ droppedChars: normalized.rejected.reduce((total, signal) => total + signal.content.length, 0),
579013
+ droppedSources: normalized.rejected.map((signal) => signal.source)
578931
579014
  }
578932
579015
  };
578933
579016
  }
578934
- var RESTORE_NOISE_LINE_RE, RUNTIME_GUIDANCE_RE, ACTIVE_CONTEXT_RE;
579017
+ var MODEL_FACING_CONTEXT_CHAR_BUDGET, MODEL_FACING_TOOL_CHAR_CAP, MODEL_FACING_SYSTEM_CHAR_CAP, MODEL_FACING_CONTROLLER_STATE_CHAR_CAP, MODEL_FACING_ACTION_GROUND_TRUTH_CHAR_CAP, CONTROLLER_STATE_MARKER, ACTION_GROUND_TRUTH_MARKER, LEGACY_RUNTIME_CONTROL_FRAGMENT_RE, LEGACY_RUNTIME_CONTROL_BLOCK_START_RE, ASSISTANT_READ_INTENT_RETIRED_MARKER, RESTORE_NOISE_LINE_RE, RUNTIME_GUIDANCE_RE, ACTIVE_CONTEXT_RE;
578935
579018
  var init_context_compiler = __esm({
578936
579019
  "packages/orchestrator/dist/context-compiler.js"() {
578937
579020
  "use strict";
578938
579021
  init_context_fabric();
579022
+ MODEL_FACING_CONTEXT_CHAR_BUDGET = 48e3;
579023
+ MODEL_FACING_TOOL_CHAR_CAP = 6e3;
579024
+ MODEL_FACING_SYSTEM_CHAR_CAP = 8e3;
579025
+ MODEL_FACING_CONTROLLER_STATE_CHAR_CAP = 4e3;
579026
+ MODEL_FACING_ACTION_GROUND_TRUTH_CHAR_CAP = 5500;
579027
+ CONTROLLER_STATE_MARKER = "[CONTROLLER STATE v1]";
579028
+ ACTION_GROUND_TRUTH_MARKER = "[RECENT ACTION GROUND TRUTH]";
579029
+ LEGACY_RUNTIME_CONTROL_FRAGMENT_RE = /(?:\bREG-\d+\b|\bfocus supervisor\b|\bworld[ -]state\b|\brecent tool failures\b|\bstop\s*[—-]\s*retry loop\b|\bstagnation replan\b|\bfirst-edit nudge\b|\bintra-run lesson\b|\blocal error-informed nudge\b|\b(?:failure|failing)\s+(?:recovery|replan|loop)\b|\bdoom-loop\b|\b(?:prior\s+)?failure reflection\b|\breflexion\b|\b(?:cross-session|prior)\s+lessons?\b|\bprogress gate\b|\bforecast\b)/i;
579030
+ LEGACY_RUNTIME_CONTROL_BLOCK_START_RE = /(?:\[(?:REG-\d+|FOCUS SUPERVISOR[^\]]*|WORLD[ -]STATE[^\]]*|RECENT TOOL FAILURES|STOP\s*[—-]\s*RETRY LOOP|STAGNATION REPLAN[^\]]*|FIRST-EDIT NUDGE[^\]]*|INTRA-RUN LESSON[^\]]*|LOCAL ERROR-INFORMED NUDGE[^\]]*|FORECAST[^\]]*|PROGRESS GATE[^\]]*|FAIL(?:URE|ING)[^\]]*(?:RECOVERY|REPLAN|LOOP)[^\]]*|DOOM-LOOP[^\]]*)\]|<(?:world-state|focus-supervisor|failure-recovery|reflection|lessons?)[^>]*>)/i;
579031
+ ASSISTANT_READ_INTENT_RETIRED_MARKER = "[assistant read intent retired: the linked tool result is already available; decide from that evidence instead of restating a read plan]";
578939
579032
  RESTORE_NOISE_LINE_RE = /^\s*(?:🔊|E Task timeout reached|E Incomplete:|⚠ Task incomplete|Tokens:\s*[\d,]+|▹\s*continue\b|·\s*(?:Starting fresh|Context (?:auto-)?restored|Nexus P2P network connected|REST API:|Voice feedback enabled|Memory maintenance:)|.*\bSHELL TRANSCRIPT\b.*|.*speaker emoji.*).*$/i;
578940
579033
  RUNTIME_GUIDANCE_RE = /\[RUNTIME_GUIDANCE_INTAKE v\d+\][\s\S]*?<<<RUNTIME_GUIDANCE>>>\s*([\s\S]*?)\s*<<<END_RUNTIME_GUIDANCE>>>[\s\S]*?\[\/RUNTIME_GUIDANCE_INTAKE\]/g;
578941
579034
  ACTIVE_CONTEXT_RE = /\[ACTIVE CONTEXT FRAME\][\s\S]*?(?=\n\[ACTIVE CONTEXT FRAME\]|$)/g;
@@ -580067,8 +580160,8 @@ var init_adversaryStream = __esm({
580067
580160
  return;
580068
580161
  try {
580069
580162
  const { writeFileSync: writeFileSync97, mkdirSync: mkdirSync114, existsSync: existsSync177 } = __require("node:fs");
580070
- const { dirname: dirname58 } = __require("node:path");
580071
- const dir = dirname58(this.persistPath);
580163
+ const { dirname: dirname59 } = __require("node:path");
580164
+ const dir = dirname59(this.persistPath);
580072
580165
  if (!existsSync177(dir))
580073
580166
  mkdirSync114(dir, { recursive: true });
580074
580167
  writeFileSync97(this.persistPath, JSON.stringify({ ledger: this.ledger }, null, 2));
@@ -580922,6 +581015,37 @@ var init_debugArtifactLibrary = __esm({
580922
581015
  });
580923
581016
 
580924
581017
  // packages/orchestrator/dist/focusSupervisor.js
581018
+ function satisfactionForRequiredAction(action) {
581019
+ switch (action) {
581020
+ case "read_authoritative_target":
581021
+ case "disambiguate_edit_match":
581022
+ return { kind: "fresh_read" };
581023
+ case "run_verification":
581024
+ return { kind: "verification" };
581025
+ case "update_todos":
581026
+ return { kind: "todo_update" };
581027
+ case "report_blocked":
581028
+ case "report_incomplete":
581029
+ return { kind: "blocked_completion" };
581030
+ default:
581031
+ return { kind: "distinct_action" };
581032
+ }
581033
+ }
581034
+ function inferDirectiveSource(input) {
581035
+ if (/stale|hash|authoritative target|ambiguous/i.test(input.reason)) {
581036
+ return "stale_write";
581037
+ }
581038
+ if (input.requiredNextAction === "run_verification") {
581039
+ return "verification_failure";
581040
+ }
581041
+ if (input.requiredNextAction === "use_cached_evidence") {
581042
+ return "duplicate_action";
581043
+ }
581044
+ if (input.requiredNextAction === "report_blocked" || input.requiredNextAction === "report_incomplete") {
581045
+ return "completion_gate";
581046
+ }
581047
+ return "repeated_failure";
581048
+ }
580925
581049
  function resolveFocusSupervisorSilent(envValue = process.env["OMNIUS_FOCUS_SUPERVISOR_SILENT"]) {
580926
581050
  const normalized = String(envValue ?? "").trim().toLowerCase();
580927
581051
  if (normalized === "0" || normalized === "false" || normalized === "off") {
@@ -581294,6 +581418,10 @@ var init_focusSupervisor = __esm({
581294
581418
  availableTools = null;
581295
581419
  /** SILENCE: when true, block() downgrades to pass() (never stops a call). */
581296
581420
  silent;
581421
+ taskEpoch;
581422
+ directiveTtlTurns;
581423
+ lastObservedTurn = 0;
581424
+ onDirectiveLifecycle;
581297
581425
  constructor(options2 = {}) {
581298
581426
  this.mode = options2.mode ?? "auto";
581299
581427
  this.modelTier = options2.modelTier ?? "large";
@@ -581302,6 +581430,9 @@ var init_focusSupervisor = __esm({
581302
581430
  this.availableTools = options2.availableTools ? new Set(Array.from(options2.availableTools)) : null;
581303
581431
  this.convergenceBreaker = options2.convergenceBreaker ?? null;
581304
581432
  this.familyCwd = options2.cwd;
581433
+ this.taskEpoch = Math.max(0, Math.floor(options2.taskEpoch ?? 0));
581434
+ this.directiveTtlTurns = Math.max(1, Math.floor(options2.directiveTtlTurns ?? (this.modelTier === "large" ? 1 : 2)));
581435
+ this.onDirectiveLifecycle = options2.onDirectiveLifecycle;
581305
581436
  }
581306
581437
  get enabled() {
581307
581438
  return this.mode !== "off";
@@ -581309,6 +581440,69 @@ var init_focusSupervisor = __esm({
581309
581440
  get currentDirective() {
581310
581441
  return this.directive;
581311
581442
  }
581443
+ /**
581444
+ * A task redirect/replacement is a control boundary. Old directives remain
581445
+ * auditable through telemetry but cannot survive into the new task epoch.
581446
+ */
581447
+ setTaskEpoch(taskEpoch, turn = this.lastObservedTurn) {
581448
+ const next = Math.max(0, Math.floor(taskEpoch));
581449
+ if (next === this.taskEpoch)
581450
+ return;
581451
+ if (this.directive) {
581452
+ this.transitionDirective("superseded", turn, `task epoch changed from ${this.taskEpoch} to ${next}`);
581453
+ }
581454
+ this.taskEpoch = next;
581455
+ this.state = "observe";
581456
+ this.ignoredDirectiveStreak = 0;
581457
+ this.lastIgnoredDirectiveTurn = null;
581458
+ this.repeatedViolationCounts.clear();
581459
+ }
581460
+ /**
581461
+ * Controller integration point for structured detectors. It replaces the
581462
+ * current directive only when the supplied evidence is newer or materially
581463
+ * changes the recovery requirement; callers must not pass model prose alone.
581464
+ */
581465
+ activateEvidenceDirective(input) {
581466
+ if (!this.enabled)
581467
+ return null;
581468
+ this.lastObservedTurn = Math.max(this.lastObservedTurn, input.turn);
581469
+ return this.setDirective({
581470
+ turn: input.turn,
581471
+ state: input.state ?? "single_next_action",
581472
+ reason: input.reason,
581473
+ requiredNextAction: input.requiredNextAction,
581474
+ forbiddenActionFamilies: input.forbiddenActionFamilies ?? [],
581475
+ source: input.source,
581476
+ evidenceRefs: input.evidenceRefs,
581477
+ evidenceStateVersion: input.evidenceStateVersion,
581478
+ satisfaction: input.satisfaction
581479
+ });
581480
+ }
581481
+ supersedeActiveDirective(reason, turn = this.lastObservedTurn, supersededBy) {
581482
+ this.transitionDirective("superseded", turn, reason, supersededBy);
581483
+ }
581484
+ cancelActiveDirective(reason, turn = this.lastObservedTurn) {
581485
+ this.transitionDirective("cancelled", turn, reason);
581486
+ }
581487
+ /** A compact, factual record for a controller frame; no directive history. */
581488
+ compactDirective(turn = this.lastObservedTurn) {
581489
+ this.lastObservedTurn = Math.max(this.lastObservedTurn, turn);
581490
+ this.expireDirectiveIfNeeded(this.lastObservedTurn);
581491
+ const directive = this.directive;
581492
+ if (!directive)
581493
+ return null;
581494
+ return {
581495
+ id: directive.id,
581496
+ taskEpoch: directive.taskEpoch ?? this.taskEpoch,
581497
+ source: directive.source ?? "manual",
581498
+ state: directive.state,
581499
+ requiredNextAction: directive.requiredNextAction,
581500
+ evidenceRefs: directive.evidenceRefs ?? [],
581501
+ evidenceStateVersion: directive.evidenceStateVersion ?? 0,
581502
+ expiresAfterTurn: directive.expiresAfterTurn,
581503
+ satisfaction: directive.satisfaction
581504
+ };
581505
+ }
581312
581506
  /**
581313
581507
  * CE-A1: the runner rehydrated evicted evidence back into the model's
581314
581508
  * window. Any read-oriented directive is now satisfiable (or already
@@ -581345,7 +581539,10 @@ var init_focusSupervisor = __esm({
581345
581539
  shellFailureRequiredNextAction() {
581346
581540
  return this.silent && this.modelTier === "small" ? "creative_pivot_or_research" : "use_cached_evidence";
581347
581541
  }
581348
- snapshot() {
581542
+ snapshot(turn) {
581543
+ const observedTurn = turn === void 0 ? this.lastObservedTurn : Math.max(this.lastObservedTurn, Math.max(0, Math.floor(turn)));
581544
+ this.lastObservedTurn = observedTurn;
581545
+ this.expireDirectiveIfNeeded(observedTurn);
581349
581546
  return {
581350
581547
  mode: this.mode,
581351
581548
  enabled: this.enabled,
@@ -581359,22 +581556,36 @@ var init_focusSupervisor = __esm({
581359
581556
  observeContext(snapshot) {
581360
581557
  this.lastContext = snapshot;
581361
581558
  }
581362
- renderFrame() {
581559
+ renderFrame(turn = this.lastObservedTurn) {
581560
+ this.lastObservedTurn = Math.max(this.lastObservedTurn, turn);
581561
+ this.expireDirectiveIfNeeded(this.lastObservedTurn);
581363
581562
  if (!this.enabled || !this.directive)
581364
581563
  return null;
581564
+ if (this.modelTier === "large")
581565
+ return null;
581365
581566
  const d2 = this.directive;
581366
581567
  return [
581367
- "[FOCUS SUPERVISOR]",
581568
+ "[ACTIVE DIRECTIVE STATE]",
581569
+ `task_epoch=${d2.taskEpoch ?? this.taskEpoch}`,
581368
581570
  `state=${d2.state}`,
581369
581571
  `directive_id=${d2.id}`,
581572
+ `lifecycle=${d2.lifecycleState ?? "active"}`,
581573
+ `source=${d2.source ?? "manual"}`,
581370
581574
  `required_next_action=${d2.requiredNextAction}`,
581371
- `reason=${d2.reason}`,
581575
+ `evidence_refs=${(d2.evidenceRefs ?? []).join(",") || "none"}`,
581576
+ `evidence_state_version=${d2.evidenceStateVersion ?? 0}`,
581577
+ d2.expiresAfterTurn !== void 0 ? `expires_after_turn=${d2.expiresAfterTurn}` : "expires_after_turn=unknown",
581578
+ d2.satisfaction ? `satisfaction=${d2.satisfaction.kind}` : "",
581579
+ `diagnosis=${d2.reason}`,
581372
581580
  d2.forbiddenActionFamilies.length ? `forbidden_action_families=${d2.forbiddenActionFamilies.join(", ")}` : "",
581373
- d2.ignoredCount > 0 ? `ignored_count=${d2.ignoredCount}` : "",
581374
- "Follow the required next action before returning to broad exploration or completion."
581581
+ d2.ignoredCount > 0 ? `ignored_count=${d2.ignoredCount}` : ""
581375
581582
  ].filter(Boolean).join("\n");
581376
581583
  }
581377
581584
  evaluateProposedCall(input) {
581585
+ this.lastObservedTurn = Math.max(this.lastObservedTurn, input.turn);
581586
+ if (input.taskEpoch !== void 0)
581587
+ this.setTaskEpoch(input.taskEpoch, input.turn);
581588
+ this.expireDirectiveIfNeeded(input.turn);
581378
581589
  this.lastContext = input.context ?? this.lastContext;
581379
581590
  if (!this.enabled)
581380
581591
  return this.pass();
@@ -581534,14 +581745,14 @@ var init_focusSupervisor = __esm({
581534
581745
  return this.pass();
581535
581746
  }
581536
581747
  observeToolResult(input) {
581748
+ this.lastObservedTurn = Math.max(this.lastObservedTurn, input.turn);
581749
+ this.expireDirectiveIfNeeded(input.turn);
581537
581750
  if (!this.enabled)
581538
581751
  return;
581539
- if (input.mutated) {
581752
+ if (input.mutated)
581540
581753
  this.sawMutationSinceFailure = true;
581541
- this.clearSatisfiedDirective("mutation landed", input.turn);
581542
- return;
581543
- }
581544
- if (input.success && input.alreadyApplied) {
581754
+ const satisfiesAlreadyApplied = this.directive?.satisfaction?.kind === "distinct_action" || this.directive?.satisfaction?.kind === "fresh_read" && input.usedAuthoritativeTargetEvidence === true && isEditTool(input.toolName);
581755
+ if (input.success && input.alreadyApplied && satisfiesAlreadyApplied) {
581545
581756
  this.clearSatisfiedDirective("requested edit already applied", input.turn);
581546
581757
  return;
581547
581758
  }
@@ -581576,7 +581787,7 @@ var init_focusSupervisor = __esm({
581576
581787
  this.lastReason = "runtime-authored control result did not execute the requested tool";
581577
581788
  return;
581578
581789
  }
581579
- if (input.toolName === "todo_write" && input.success) {
581790
+ if (input.toolName === "todo_write" && input.success && this.directive?.satisfaction?.kind === "todo_update") {
581580
581791
  if (input.noop) {
581581
581792
  this.lastDecision = "todo_noop_not_satisfied";
581582
581793
  this.lastReason = "todo_write returned no-op; checklist state did not change";
@@ -581709,10 +581920,11 @@ var init_focusSupervisor = __esm({
581709
581920
  return;
581710
581921
  this.setDirective({
581711
581922
  turn,
581712
- state: "forced_replan",
581713
- reason: `${reason} — do NOT report incomplete and do NOT repeat a variant of what failed. TRIAGE: web_search the exact error/blocker to find how it is solved, OR pivot to a fundamentally different approach you have not tried, then act on it.`,
581714
- requiredNextAction: "creative_pivot_or_research",
581715
- forbiddenActionFamilies: ["brute_force"]
581923
+ state: "terminal_incomplete",
581924
+ reason,
581925
+ requiredNextAction: "report_incomplete",
581926
+ forbiddenActionFamilies: ["brute_force"],
581927
+ source: "completion_gate"
581716
581928
  });
581717
581929
  }
581718
581930
  shouldStrictlyIntervene(context2) {
@@ -581741,7 +581953,12 @@ var init_focusSupervisor = __esm({
581741
581953
  }
581742
581954
  setDirective(input) {
581743
581955
  const existing = this.directive;
581744
- const stable = existing && existing.state === input.state && existing.reason === input.reason && existing.requiredNextAction === input.requiredNextAction;
581956
+ const evidenceStateVersion = input.evidenceStateVersion ?? 0;
581957
+ const stable = existing && existing.state === input.state && existing.reason === input.reason && existing.requiredNextAction === input.requiredNextAction && (existing.evidenceStateVersion ?? 0) >= evidenceStateVersion;
581958
+ if (existing && !stable) {
581959
+ this.transitionDirective("superseded", input.turn, "replaced by newer evidence or a different recovery requirement");
581960
+ }
581961
+ const source = input.source ?? inferDirectiveSource(input);
581745
581962
  const directive = stable ? {
581746
581963
  ...existing,
581747
581964
  forbiddenActionFamilies: uniqueLimited([
@@ -581749,13 +581966,20 @@ var init_focusSupervisor = __esm({
581749
581966
  ...input.forbiddenActionFamilies
581750
581967
  ])
581751
581968
  } : {
581752
- id: `focus_${++directiveCounter}`,
581969
+ id: `focus_${this.taskEpoch}_${++directiveCounter}`,
581753
581970
  state: input.state,
581754
581971
  reason: input.reason,
581755
581972
  requiredNextAction: input.requiredNextAction,
581756
581973
  forbiddenActionFamilies: uniqueLimited(input.forbiddenActionFamilies),
581757
581974
  createdTurn: input.turn,
581758
- ignoredCount: 0
581975
+ ignoredCount: 0,
581976
+ taskEpoch: this.taskEpoch,
581977
+ lifecycleState: "active",
581978
+ source,
581979
+ evidenceRefs: uniqueLimited(input.evidenceRefs ?? [`turn:${input.turn}`]),
581980
+ evidenceStateVersion,
581981
+ expiresAfterTurn: input.turn + this.directiveTtlTurns,
581982
+ satisfaction: input.satisfaction ?? satisfactionForRequiredAction(input.requiredNextAction)
581759
581983
  };
581760
581984
  if (!stable && (!existing || existing.state !== input.state || existing.requiredNextAction !== input.requiredNextAction)) {
581761
581985
  this.repeatedViolationCounts.clear();
@@ -581765,12 +581989,45 @@ var init_focusSupervisor = __esm({
581765
581989
  this.lastReason = directive.reason;
581766
581990
  if (!stable)
581767
581991
  this.lastIgnoredDirectiveTurn = null;
581992
+ if (!stable) {
581993
+ this.emitDirectiveLifecycle({
581994
+ directive,
581995
+ taskEpoch: this.taskEpoch,
581996
+ transition: "created",
581997
+ turn: input.turn,
581998
+ reason: directive.reason
581999
+ });
582000
+ }
581768
582001
  return directive;
581769
582002
  }
581770
- clearSatisfiedDirective(reason, _turn) {
581771
- if (!this.directive)
582003
+ clearSatisfiedDirective(reason, turn) {
582004
+ this.transitionDirective("satisfied", turn, reason);
582005
+ }
582006
+ expireDirectiveIfNeeded(turn) {
582007
+ const expires = this.directive?.expiresAfterTurn;
582008
+ if (expires !== void 0 && turn >= expires) {
582009
+ this.transitionDirective("expired", turn, "directive TTL elapsed without new evidence");
582010
+ }
582011
+ }
582012
+ transitionDirective(transition, turn, reason, supersededBy) {
582013
+ const directive = this.directive;
582014
+ if (!directive)
581772
582015
  return;
581773
- this.lastDecision = "directive_satisfied";
582016
+ const resolved = {
582017
+ ...directive,
582018
+ lifecycleState: transition,
582019
+ resolvedTurn: turn,
582020
+ resolutionReason: reason,
582021
+ ...supersededBy ? { supersededBy } : {}
582022
+ };
582023
+ this.emitDirectiveLifecycle({
582024
+ directive: resolved,
582025
+ taskEpoch: this.taskEpoch,
582026
+ transition,
582027
+ turn,
582028
+ reason
582029
+ });
582030
+ this.lastDecision = transition === "satisfied" ? "directive_satisfied" : `directive_${transition}`;
581774
582031
  this.lastReason = reason;
581775
582032
  this.directive = null;
581776
582033
  this.state = "observe";
@@ -581778,6 +582035,12 @@ var init_focusSupervisor = __esm({
581778
582035
  this.lastIgnoredDirectiveTurn = null;
581779
582036
  this.repeatedViolationCounts.clear();
581780
582037
  }
582038
+ emitDirectiveLifecycle(event) {
582039
+ try {
582040
+ this.onDirectiveLifecycle?.(event);
582041
+ } catch {
582042
+ }
582043
+ }
581781
582044
  pass() {
581782
582045
  return {
581783
582046
  kind: "pass",
@@ -587788,8 +588051,6 @@ function flattenErrorText(err) {
587788
588051
  function computeEffectiveThink(params) {
587789
588052
  if (process.env["OMNIUS_FORCE_NO_THINK"] === "1")
587790
588053
  return false;
587791
- if (process.env["OMNIUS_ENABLE_THINKING"] !== "1")
587792
- return false;
587793
588054
  if (params.suppressed)
587794
588055
  return false;
587795
588056
  if (params.hasTools)
@@ -587826,6 +588087,9 @@ function sanitizeHistoryThink(messages2) {
587826
588087
  const collapsed = collapseDegenerateAssistantRepetition(content);
587827
588088
  content = collapsed ?? content;
587828
588089
  }
588090
+ if (m2.role === "assistant" && Array.isArray(m2.tool_calls) && m2.tool_calls.some((call) => referencedToolCallIds.has(call.id)) && /\b(?:i|we)\s+(?:need|will|should|have)\s+to\s+(?:read|inspect|open)\b/i.test(content)) {
588091
+ content = "[assistant read intent retired: the linked tool result is already available; decide from that evidence instead of restating a read plan]";
588092
+ }
587829
588093
  return { ...m2, content };
587830
588094
  });
587831
588095
  const sanitized = [];
@@ -588178,6 +588442,18 @@ var init_agenticRunner = __esm({
588178
588442
  _onTypedEvent;
588179
588443
  handlers = [];
588180
588444
  pendingUserMessages = [];
588445
+ /** Typed source of truth for user steering; pendingUserMessages remains a compatibility queue. */
588446
+ pendingSteeringInputs = [];
588447
+ _steeringSequence = 0;
588448
+ _taskEpoch = 0;
588449
+ _activeRunId = "";
588450
+ /** Session storage is retained for compatibility; superseded task leaves are hidden from active guards. */
588451
+ _supersededTodoIds = /* @__PURE__ */ new Set();
588452
+ /** Cross-task restoration is opt-in only for an explicit continuation/append. */
588453
+ _allowImplicitContinuation = false;
588454
+ /** Abort scope for only the in-flight model/tool turn. Never use for permanent stop. */
588455
+ _turnAbortController = new AbortController();
588456
+ _pendingSteeringPreemption = null;
588181
588457
  pendingRuntimeGuidanceMessages = [];
588182
588458
  aborted = false;
588183
588459
  _abortController = new AbortController();
@@ -588678,6 +588954,9 @@ var init_agenticRunner = __esm({
588678
588954
  _branchEvidenceCache = /* @__PURE__ */ new Map();
588679
588955
  /** Latest curated node per canonical path for safe post-compaction recovery. */
588680
588956
  _branchEvidenceByPath = /* @__PURE__ */ new Map();
588957
+ /** Exact read fingerprints resolved from canonical evidence, not a fresh tool call. */
588958
+ _resolvedReadEvidence = /* @__PURE__ */ new Map();
588959
+ _deterministicNarrowReadFallbacks = /* @__PURE__ */ new Set();
588681
588960
  // OBS-1: durable "current observed state" for non-file_read tool outputs
588682
588961
  // (shell/web_fetch/list_directory/…). EvidenceLedger's counterpart for the
588683
588962
  // observation channels that were previously invisible after compaction —
@@ -588786,7 +589065,7 @@ var init_agenticRunner = __esm({
588786
589065
  return this._workboard;
588787
589066
  }
588788
589067
  const dir = this._workboardDir();
588789
- const runId = this._sessionId;
589068
+ const runId = this.currentArtifactRunId();
588790
589069
  const existing = loadWorkboardSnapshot(dir, runId);
588791
589070
  if (existing) {
588792
589071
  this._workboard = this._seedWorkboardCardsIfNeeded(existing, goal);
@@ -588897,7 +589176,7 @@ var init_agenticRunner = __esm({
588897
589176
  if (!diagnosis.createRecoveryCard && count < 2)
588898
589177
  return;
588899
589178
  const dir = this._workboardDir();
588900
- const runId = this._sessionId;
589179
+ const runId = this.currentArtifactRunId();
588901
589180
  const actor = this.options.subAgent ? "sub-agent" : "agent";
588902
589181
  const cardInput = this._failureRecoveryCardInput(diagnosis);
588903
589182
  try {
@@ -589009,7 +589288,7 @@ var init_agenticRunner = __esm({
589009
589288
  return;
589010
589289
  const cards = activeLeaves.map((todo) => this._todoWorkboardCardInput(todo, this._todoPath(todo, index)));
589011
589290
  const dir = this._workboardDir();
589012
- const runId = this._sessionId;
589291
+ const runId = this.currentArtifactRunId();
589013
589292
  const actor = this.options.subAgent ? "sub-agent" : "agent";
589014
589293
  try {
589015
589294
  let board = readActiveWorkboardSnapshot(dir, runId) ?? this._workboard ?? null;
@@ -589230,7 +589509,7 @@ ${parts.join("\n")}
589230
589509
  }
589231
589510
  _currentWorkboardSnapshotForFrame() {
589232
589511
  const dir = this._workboardDir();
589233
- const fromDisk = readActiveWorkboardSnapshot(dir, this._sessionId);
589512
+ const fromDisk = readActiveWorkboardSnapshot(dir, this.currentArtifactRunId());
589234
589513
  const goal = this._taskState.originalGoal || this._taskState.goal || "";
589235
589514
  const initialCards = this._initialWorkboardCardsForGoal(goal);
589236
589515
  if (fromDisk) {
@@ -589359,8 +589638,9 @@ ${parts.join("\n")}
589359
589638
  case "creative_pivot_or_research":
589360
589639
  return "a FUNDAMENTALLY different approach: web_search the exact error/blocker to find how it is solved, or pivot to a method you have NOT tried — not a variant of what failed, and NOT task_complete";
589361
589640
  case "report_blocked":
589641
+ return 'call task_complete with status="blocked", a concise external blocker, and the next prerequisite; do not create a bookkeeping artifact as the recovery action';
589362
589642
  case "report_incomplete":
589363
- return "a fundamentally different approach or web_search the blocker — do not report incomplete";
589643
+ return 'call task_complete with status="incomplete" or status="blocked" only when the evidence shows no remaining substantive action; otherwise take a fundamentally different approach or web_search the blocker';
589364
589644
  default:
589365
589645
  return "choose the narrowest tool that advances the current card";
589366
589646
  }
@@ -589389,12 +589669,6 @@ ${parts.join("\n")}
589389
589669
  const gitContract = renderGitProgressActionContract(this._gitProgress);
589390
589670
  if (gitContract)
589391
589671
  lines.push(gitContract);
589392
- const focus = this._focusSupervisor?.snapshot().directive ?? null;
589393
- if (focus) {
589394
- lines.push(`focus_required_next_action=${focus.requiredNextAction}`);
589395
- lines.push(`focus_valid_tools=${this._focusToolsForRequiredAction(focus.requiredNextAction)}`);
589396
- lines.push(`focus_reason=${focus.reason}`);
589397
- }
589398
589672
  const snapshot = this._currentWorkboardSnapshotForFrame();
589399
589673
  const action = snapshot ? this._deriveWorkboardActionContract(snapshot) : null;
589400
589674
  if (snapshot && action) {
@@ -589525,7 +589799,7 @@ ${parts.join("\n")}
589525
589799
  const discovery = cards.get("discover-current-state");
589526
589800
  if (discovery && discovery.status !== "verified" && discovery.evidence.length > 0) {
589527
589801
  const completed = completeWorkboardCard(dir, {
589528
- runId: this._sessionId,
589802
+ runId: this.currentArtifactRunId(),
589529
589803
  cardId: discovery.id,
589530
589804
  actor,
589531
589805
  outcome: "completed",
@@ -589536,7 +589810,7 @@ ${parts.join("\n")}
589536
589810
  const completedDiscovery = cards.get("discover-current-state");
589537
589811
  if (completedDiscovery?.status === "completed") {
589538
589812
  const verified = completeWorkboardCard(dir, {
589539
- runId: this._sessionId,
589813
+ runId: this.currentArtifactRunId(),
589540
589814
  cardId: completedDiscovery.id,
589541
589815
  actor,
589542
589816
  outcome: "verified",
@@ -589549,7 +589823,7 @@ ${parts.join("\n")}
589549
589823
  const implementation2 = cards.get("implement-repair");
589550
589824
  if (implementation2 && (implementation2.status === "open" || implementation2.status === "needs_changes")) {
589551
589825
  current = updateWorkboardCard(dir, {
589552
- runId: this._sessionId,
589826
+ runId: this.currentArtifactRunId(),
589553
589827
  cardId: implementation2.id,
589554
589828
  actor,
589555
589829
  updates: { status: "in_progress", lane: "worker" },
@@ -589563,7 +589837,7 @@ ${parts.join("\n")}
589563
589837
  const integration = cards.get("integrate-and-run");
589564
589838
  if (integration && this._workboardHasEditEvidence(implementation2) && (integration.status === "open" || integration.status === "needs_changes")) {
589565
589839
  current = updateWorkboardCard(dir, {
589566
- runId: this._sessionId,
589840
+ runId: this.currentArtifactRunId(),
589567
589841
  cardId: integration.id,
589568
589842
  actor,
589569
589843
  updates: { status: "in_progress", lane: "verification" },
@@ -589618,7 +589892,7 @@ ${parts.join("\n")}
589618
589892
  return;
589619
589893
  }
589620
589894
  attachWorkboardEvidence(dir, {
589621
- runId: this._sessionId,
589895
+ runId: this.currentArtifactRunId(),
589622
589896
  cardId: targetCard.id,
589623
589897
  actor,
589624
589898
  evidence
@@ -589633,7 +589907,7 @@ ${parts.join("\n")}
589633
589907
  return;
589634
589908
  try {
589635
589909
  const dir = this._workboardDir();
589636
- const refreshed = readActiveWorkboardSnapshot(dir, this._sessionId);
589910
+ const refreshed = readActiveWorkboardSnapshot(dir, this.currentArtifactRunId());
589637
589911
  if (refreshed)
589638
589912
  this._workboard = refreshed;
589639
589913
  } catch {
@@ -589824,7 +590098,7 @@ ${parts.join("\n")}
589824
590098
  stage: stage2,
589825
590099
  agentType,
589826
590100
  sessionId: this._sessionId,
589827
- runId: this._sessionId,
590101
+ runId: this.currentArtifactRunId(),
589828
590102
  turn,
589829
590103
  attempt,
589830
590104
  model: this._backendModelLabel(this.backend),
@@ -589849,7 +590123,7 @@ ${parts.join("\n")}
589849
590123
  recordDebugContextWindowDump({
589850
590124
  cwd: this.authoritativeWorkingDirectory(),
589851
590125
  stateDir: this.omniusStateDir(),
589852
- runId: this._sessionId,
590126
+ runId: this.currentArtifactRunId(),
589853
590127
  sessionId: this._sessionId,
589854
590128
  record
589855
590129
  });
@@ -590072,7 +590346,7 @@ ${parts.join("\n")}
590072
590346
  try {
590073
590347
  const dir = _pathJoin(this.omniusStateDir(), "completion-contracts");
590074
590348
  _fsMkdirSync(dir, { recursive: true });
590075
- _fsWriteFileSync(_pathJoin(dir, `${this._sessionId}.json`), JSON.stringify({
590349
+ _fsWriteFileSync(_pathJoin(dir, `${this.currentArtifactRunId()}.json`), JSON.stringify({
590076
590350
  sessionId: this._sessionId,
590077
590351
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
590078
590352
  contract
@@ -590238,28 +590512,8 @@ ${parts.join("\n")}
590238
590512
  const pressureCue = pressureCheck(task);
590239
590513
  const rawPrompt = getSystemPromptForTier(this.options.modelTier);
590240
590514
  const basePrompt = rawPrompt + pressureCue;
590241
- const todoBatchGuidance = this._todoWriteAvailable() ? " Use todo_write between batches to mark progress." : "";
590242
- const _BATCH_GUIDANCE = {
590243
- small: `
590244
-
590245
- ## Response batching
590246
-
590247
- Emit AT MOST 2 tool calls per response. After observing their results, plan the next 2 in your following response. Smaller batches let the orchestrator deliver cache/failure/progress signals to you between actions. Tool calls beyond the cap are dropped.${todoBatchGuidance}`,
590248
- medium: `
590249
-
590250
- ## Response batching
590251
-
590252
- Emit AT MOST 4 tool calls per response. After observing their results, plan the next batch in your following response. Smaller batches let the orchestrator deliver cache/failure/progress signals to you between actions. Tool calls beyond the cap are dropped.${todoBatchGuidance}`,
590253
- large: `
590254
-
590255
- ## Response batching
590256
-
590257
- Emit AT MOST 6 tool calls per response. Smaller batches receive better feedback (cache/failure/progress signals between actions). Tool calls beyond the cap are dropped.${todoBatchGuidance}`
590258
- };
590259
- const batchGuidance = _BATCH_GUIDANCE[this.options.modelTier ?? "large"] ?? _BATCH_GUIDANCE.large;
590260
- const shellGuidance = "\n\n## Shell command patterns\n\nWhen investigating a build/test/install failure, RUN THE COMMAND WITHOUT TRUNCATION FIRST to see the full error.\nAvoid `| tail -N` / `| head -N` / `| sed -n '1,Np'` on commands you don't yet trust — they drop the part of the output where errors usually appear.\nPipefail is on by default in this orchestrator: a pipeline's exit code reflects the FIRST failing stage, not just the last. So `<cmd> | tail -80` returns non-zero if `<cmd>` failed.\nWhen you DO want to limit context (after diagnosis), prefer `<cmd> 2>&1 | tail -300` (or larger) so you keep enough output to see the actual error block.\nIf your command exited 0 but produced suspiciously short output (~< 800 chars), the orchestrator will inject a [HINT — pipe-to-truncator detected] block telling you to re-run without truncation.";
590261
- const editTransportGuidance = "\n\n## Existing-file edit loop\n\nFor an existing non-trivial file, use this loop: (1) file_read the implicated range or whole small file, (2) file_patch a contiguous line range or file_edit exact current text, (3) inspect the resulting diff/changed range, and (4) run the declared verifier live. Use batch_edit only for multiple exact replacements built from one fresh read.\nfile_write is for new files, empty/placeholder files, and deliberate replacement of a genuinely small file. Never use file_write as a fallback for stale hashes, old_string mismatches, malformed patch arguments, or repeated edit failures. A 'different approach' means refresh evidence or change the diagnostic/patch shape; it does not mean broaden a local repair into a whole-file rewrite.\nPreviously observed or compacted results are orientation only. Re-run file_read whenever a freshness/hash guard asks for current text, and re-run the exact verifier after every relevant mutation; cached output never proves current file state or completion.";
590262
- const basePromptWithBatching = basePrompt + batchGuidance + shellGuidance + editTransportGuidance;
590515
+ const toolProtocol = "\n\n## Tool protocol\nUse a bounded tool batch, inspect returned evidence before the next batch, and use structured tool calls. For an existing file, provide fresh target evidence for a mutation; hash and scope validation are enforced by the tools. Verify a claimed end state with current evidence.";
590516
+ const basePromptWithBatching = basePrompt + toolProtocol;
590263
590517
  sections.push({
590264
590518
  label: "c_instr",
590265
590519
  content: basePromptWithBatching,
@@ -590621,7 +590875,7 @@ Your hypotheses MUST address this specific error, not generic causes.
590621
590875
  stage: opts?.dumpStage ?? "aux_inference",
590622
590876
  agentType: "internal",
590623
590877
  sessionId: this._sessionId,
590624
- runId: this._sessionId,
590878
+ runId: this.currentArtifactRunId(),
590625
590879
  model: this._backendModelLabel(this.backend),
590626
590880
  cwd: this._workingDirectory || process.cwd(),
590627
590881
  request: r2
@@ -591135,7 +591389,8 @@ Pick the SMALLEST concrete deliverable from the spec — typically the project e
591135
591389
  readSessionTodos() {
591136
591390
  try {
591137
591391
  const sid = this._sessionId || process.env["OMNIUS_SESSION_ID"] || "default";
591138
- return readTodos(sid);
591392
+ const todos = readTodos(sid);
591393
+ return this._supersededTodoIds.size === 0 ? todos : todos.filter((todo) => !this._supersededTodoIds.has(todo.id));
591139
591394
  } catch {
591140
591395
  return null;
591141
591396
  }
@@ -591667,13 +591922,13 @@ ${extras.join("\n")}`;
591667
591922
  if (!existing) {
591668
591923
  this._workboard = addWorkboardCard(dir, {
591669
591924
  ...compileFixCardToWorkboardInput(card),
591670
- runId: this._sessionId,
591925
+ runId: this.currentArtifactRunId(),
591671
591926
  actor,
591672
591927
  decisionReason: "compile_error_card_created"
591673
591928
  });
591674
591929
  } else if (card.status === "assigned" && existing.status === "open") {
591675
591930
  this._workboard = updateWorkboardCard(dir, {
591676
- runId: this._sessionId,
591931
+ runId: this.currentArtifactRunId(),
591677
591932
  cardId: card.id,
591678
591933
  actor,
591679
591934
  updates: {
@@ -591694,7 +591949,7 @@ ${extras.join("\n")}`;
591694
591949
  "patch touched only owned files"
591695
591950
  ];
591696
591951
  this._workboard = attachWorkboardEvidence(dir, {
591697
- runId: this._sessionId,
591952
+ runId: this.currentArtifactRunId(),
591698
591953
  cardId: card.id,
591699
591954
  actor,
591700
591955
  evidence: {
@@ -591716,7 +591971,7 @@ ${extras.join("\n")}`;
591716
591971
  const wbCard = active?.cards.find((item) => item.id === card.id);
591717
591972
  if (wbCard && wbCard.status !== "completed" && wbCard.status !== "verified") {
591718
591973
  this._workboard = completeWorkboardCard(dir, {
591719
- runId: this._sessionId,
591974
+ runId: this.currentArtifactRunId(),
591720
591975
  cardId: card.id,
591721
591976
  actor,
591722
591977
  outcome: "completed",
@@ -591728,7 +591983,7 @@ ${extras.join("\n")}`;
591728
591983
  const latestCard = latest?.cards.find((item) => item.id === card.id);
591729
591984
  if (latestCard?.status === "completed") {
591730
591985
  this._workboard = completeWorkboardCard(dir, {
591731
- runId: this._sessionId,
591986
+ runId: this.currentArtifactRunId(),
591732
591987
  cardId: card.id,
591733
591988
  actor,
591734
591989
  outcome: "verified",
@@ -591749,7 +592004,7 @@ ${extras.join("\n")}`;
591749
592004
  if (!existing || existing.status !== "open")
591750
592005
  return;
591751
592006
  this._workboard = updateWorkboardCard(dir, {
591752
- runId: this._sessionId,
592007
+ runId: this.currentArtifactRunId(),
591753
592008
  cardId: card.id,
591754
592009
  actor: this.options.subAgent ? "sub-agent" : "agent",
591755
592010
  updates: {
@@ -591773,6 +592028,11 @@ ${extras.join("\n")}`;
591773
592028
  state.verifierDirtySinceTurn = turn;
591774
592029
  state.lastVerifierPassedTurn = null;
591775
592030
  state.lastMutationTurn = turn;
592031
+ this._focusSupervisor?.markCompletionBlocked({
592032
+ turn,
592033
+ reason: "A source mutation invalidated the declared verifier; verifier evidence now owns the active focus.",
592034
+ requiredNextAction: "run_verification"
592035
+ });
591776
592036
  for (const card of state.cards) {
591777
592037
  if (card.status === "assigned" && (normalized.length === 0 || normalized.some((pathValue) => card.ownedFiles.some((ownedPath) => this._pathsOverlapForVerifier(pathValue, ownedPath))))) {
591778
592038
  card.status = "patched";
@@ -591825,8 +592085,9 @@ ${extras.join("\n")}`;
591825
592085
  state.preflightBlockStreak = 0;
591826
592086
  return null;
591827
592087
  }
591828
- if (!shellLikelyMutatesFilesystem)
592088
+ if (!shellLikelyMutatesFilesystem) {
591829
592089
  return null;
592090
+ }
591830
592091
  const extraction = extractShellMutationPaths(command, {
591831
592092
  workingDir: this.authoritativeWorkingDirectory()
591832
592093
  });
@@ -591837,7 +592098,7 @@ ${extras.join("\n")}`;
591837
592098
  } else if (!this._isProjectEditTool(toolName)) {
591838
592099
  return null;
591839
592100
  }
591840
- const yieldAfter = _AgenticRunner.COMPILE_FIX_GATE_YIELD_AFTER;
592101
+ const yieldAfter = Number.MAX_SAFE_INTEGER;
591841
592102
  const streak = (state.preflightBlockStreak ?? 0) + 1;
591842
592103
  if (streak > yieldAfter) {
591843
592104
  state.preflightBlockStreak = 0;
@@ -591869,7 +592130,7 @@ ${extras.join("\n")}`;
591869
592130
  `lastMutationTurn: ${state.lastMutationTurn}`,
591870
592131
  `lastVerifierRunTurn: ${state.lastVerifierRunTurn}`,
591871
592132
  `blockedTool: ${toolName}`,
591872
- `consecutiveBlocks: ${streak}/${yieldAfter} (gate yields after ${yieldAfter})`
592133
+ `consecutiveBlocks: ${streak} (verifier focus is retained until a live verifier settles)`
591873
592134
  ].join("\n");
591874
592135
  this.emit({
591875
592136
  type: "status",
@@ -592330,6 +592591,9 @@ ${result.output ?? ""}`;
592330
592591
  return /^\s*(BLOCKED|INCOMPLETE|NEEDS[_ -]?INPUT)\b\s*:?/i.test(summary);
592331
592592
  }
592332
592593
  _shouldBypassTodoCompletionGuardForTaskComplete(args) {
592594
+ if (completionStatusFromTaskCompleteArgs(args) === "blocked") {
592595
+ return this._hasEvidenceBackedBlockedCompletion(args);
592596
+ }
592333
592597
  if (!this._taskCompleteArgsReportDegraded(args))
592334
592598
  return false;
592335
592599
  if (this._completionIncompleteVerification)
@@ -592387,6 +592651,32 @@ ${result.output ?? ""}`;
592387
592651
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
592388
592652
  });
592389
592653
  }
592654
+ /**
592655
+ * Admit a BLOCKED terminal state only when every unresolved leaf is blocked
592656
+ * by observed external evidence. Controller-authored notes, todo churn, and
592657
+ * recovery artifacts are deliberately not evidence: otherwise the recovery
592658
+ * loop can manufacture its own next blocker.
592659
+ */
592660
+ _hasEvidenceBackedBlockedCompletion(args) {
592661
+ if (completionStatusFromTaskCompleteArgs(args) !== "blocked")
592662
+ return false;
592663
+ const summary = extractTaskCompleteSummary(args).trim();
592664
+ if (!summary)
592665
+ return false;
592666
+ const leaves = openTodoLeaves(this._normalizeTodosForPrompt(this.readSessionTodos() ?? [])).filter((todo) => todo.status !== "completed");
592667
+ if (leaves.length === 0)
592668
+ return false;
592669
+ const controllerArtifact = /(?:status artifact|blocker note|recovery (?:note|report|artifact)|todo_(?:write|read)|workboard|completion ledger|session diary)/i;
592670
+ const externalBlocker = /(?:enoent|not found|missing|permission|access denied|credential|network|remote|upstream|service unavailable|waiting for|user input|third[- ]party)/i;
592671
+ const hasObservedExternalFailure = this._recentFailures.some((failure) => externalBlocker.test(`${failure.error || ""}
592672
+ ${failure.output || ""}`));
592673
+ if (!hasObservedExternalFailure)
592674
+ return false;
592675
+ return leaves.every((todo) => {
592676
+ const blocker = typeof todo.blocker === "string" ? todo.blocker.trim() : "";
592677
+ return todo.status === "blocked" && blocker.length > 0 && externalBlocker.test(blocker) && !controllerArtifact.test(blocker);
592678
+ });
592679
+ }
592390
592680
  buildTodoCompletionGuard(openItems) {
592391
592681
  const list = openItems.slice(0, 20).map((t2, i2) => `${i2 + 1}. [${t2.status}] ${t2.content}`).join("\n");
592392
592682
  const full = this.readSessionTodos() || [];
@@ -594574,7 +594864,6 @@ ${latest.output || ""}`.trim();
594574
594864
  `files=${scan.files.length}${scan.truncated ? "+" : ""}`,
594575
594865
  `dirs=${scan.dirs.length}`,
594576
594866
  `bytes=${totalBytes}`,
594577
- focusSnapshot?.directive?.requiredNextAction ? `supervisor_required_next_action=${focusSnapshot.directive.requiredNextAction}` : `supervisor_required_next_action=none`,
594578
594867
  recentActionLines.length ? `recent_actions=${recentActions.length}` : `recent_actions=0`,
594579
594868
  recentActionLines.length ? recentActionLines.join("\n") : "",
594580
594869
  ""
@@ -594627,7 +594916,6 @@ ${latest.output || ""}`.trim();
594627
594916
  `root=${root}`,
594628
594917
  `files=${scan.files.length}${scan.truncated ? "+" : ""} dirs=${scan.dirs.length} total_bytes=${totalBytes}`,
594629
594918
  `artifact=${artifactDisplay}`,
594630
- focusSnapshot?.directive?.requiredNextAction ? `supervisor_required_next_action=${focusSnapshot.directive.requiredNextAction}` : `supervisor_required_next_action=none`,
594631
594919
  recentActionLines.length ? `recent_actions:
594632
594920
  ${recentActionLines.join("\n")}` : "recent_actions=none",
594633
594921
  "Use this tree for path orientation. It includes empty directories; it does not include file contents.",
@@ -595214,9 +595502,9 @@ ${String(concreteGoal).replace(/\s+/g, " ").trim().slice(0, 1200)}` : null
595214
595502
  const artifactContractBlock = this._contractRegistry.format(15);
595215
595503
  const todoBlock = this._renderTodoStateBlock(turn);
595216
595504
  const gitBlock = this._renderGitProgressBlock(turn);
595217
- const failureBlock = this._renderRecentFailuresBlock(turn);
595218
- const churnBlock = this._renderWriteChurnBlock(turn);
595219
- const focusBlock = this._focusSupervisor?.renderFrame() ?? null;
595505
+ const failureBlock = null;
595506
+ const churnBlock = null;
595507
+ const focusBlock = null;
595220
595508
  const actionContractBlock = this._renderNextActionContract(turn);
595221
595509
  const trajectoryCheckpoint = await this._refreshTrajectoryCheckpoint(turn, focusBlock, [
595222
595510
  workspaceTreeBlock,
@@ -595232,8 +595520,7 @@ ${String(concreteGoal).replace(/\s+/g, " ").trim().slice(0, 1200)}` : null
595232
595520
  const toolCacheBlock = recentToolResults ? this._renderKnowledgeBlock(recentToolResults) : null;
595233
595521
  const observationBlock = process.env["OMNIUS_DISABLE_OBSERVATION_FRAME"] === "1" ? null : this._observationLedger.renderBlock(5e3);
595234
595522
  const anchorsBlock = this.surfaceAnchors(messages2);
595235
- const pprMemoryBlock = this._lastPprMemoryLines.length > 0 ? `[Associative Memory - related prior experience]
595236
- ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
595523
+ const pprMemoryBlock = null;
595237
595524
  const activeItems = await this._collectActiveSemanticContextItems({
595238
595525
  goalBlock,
595239
595526
  filesystemBlock,
@@ -595322,15 +595609,6 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
595322
595609
  createdTurn: turn,
595323
595610
  ttlTurns: 1
595324
595611
  }),
595325
- signalFromBlock("task_state", "turn.focus-supervisor", focusBlock, {
595326
- id: "focus-supervisor",
595327
- dedupeKey: "turn.focus-supervisor",
595328
- semanticKey: "context.focus-supervisor",
595329
- conflictGroup: "context.focus-supervisor",
595330
- priority: 98,
595331
- createdTurn: turn,
595332
- ttlTurns: 1
595333
- }),
595334
595612
  signalFromBlock("recent_failure", "turn.failures", failureBlock, {
595335
595613
  id: "recent-failures",
595336
595614
  dedupeKey: "turn.failures",
@@ -596594,8 +596872,48 @@ ${notice}`;
596594
596872
  }
596595
596873
  /** Inject a user message into the running conversation (mid-task steering) */
596596
596874
  injectUserMessage(content) {
596597
- this.pendingUserMessages.push(this.scrubUserInput(content, "injected-user-message"));
596875
+ this.injectSteeringInput({
596876
+ inputId: `legacy-steering-${Date.now()}-${++this._steeringSequence}`,
596877
+ content,
596878
+ source: "legacy-injectUserMessage",
596879
+ receivedAt: (/* @__PURE__ */ new Date()).toISOString(),
596880
+ intent: "append",
596881
+ state: "received",
596882
+ taskEpoch: this._taskEpoch || void 0
596883
+ });
596884
+ }
596885
+ /**
596886
+ * Queue a typed user instruction and return an acknowledgement receipt.
596887
+ * The receipt is emitted and ledgered before a redirect can cancel the
596888
+ * active turn, which closes the old bridge-to-runner message-loss race.
596889
+ */
596890
+ injectSteeringInput(input) {
596891
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
596892
+ const content = this.scrubUserInput(input.content, "steering-input").trim();
596893
+ const record = {
596894
+ ...input,
596895
+ inputId: input.inputId.trim() || `steering-${Date.now()}-${++this._steeringSequence}`,
596896
+ content,
596897
+ source: input.source || "unknown",
596898
+ receivedAt: input.receivedAt || now2,
596899
+ state: "received",
596900
+ taskEpoch: input.taskEpoch ?? (this._taskEpoch || void 0)
596901
+ };
596902
+ this.pendingSteeringInputs.push(record);
596903
+ this._emitSteeringLifecycle(record, "received by runner");
596904
+ if (!content) {
596905
+ record.state = "cancelled";
596906
+ this._emitSteeringLifecycle(record, "empty steering input rejected");
596907
+ return this._steeringReceipt(record);
596908
+ }
596909
+ this.pendingUserMessages.push(content);
596910
+ record.state = "queued";
596911
+ this._emitSteeringLifecycle(record, "queued for next safe turn boundary");
596912
+ if (record.intent === "redirect" || record.intent === "replace" || record.intent === "cancel") {
596913
+ this._requestSteeringPreemption(record);
596914
+ }
596598
596915
  this._trajectoryDirtyCauses.add("user_steering");
596916
+ return this._steeringReceipt(record);
596599
596917
  }
596600
596918
  /** Inject bounded runtime guidance without treating it as user steering. */
596601
596919
  injectRuntimeGuidance(content) {
@@ -596621,12 +596939,22 @@ ${notice}`;
596621
596939
  retractLastPendingMessage() {
596622
596940
  if (this.pendingUserMessages.length === 0)
596623
596941
  return null;
596624
- return this.pendingUserMessages.pop();
596942
+ const content = this.pendingUserMessages.pop();
596943
+ const record = [...this.pendingSteeringInputs].reverse().find((candidate) => candidate.content === content && (candidate.state === "queued" || candidate.state === "acknowledged"));
596944
+ if (record) {
596945
+ record.state = "cancelled";
596946
+ if (this._pendingSteeringPreemption?.inputId === record.inputId) {
596947
+ this._pendingSteeringPreemption = null;
596948
+ }
596949
+ this._emitSteeringLifecycle(record, "retracted before consumption");
596950
+ }
596951
+ return content;
596625
596952
  }
596626
596953
  /** Abort the current task run — cancels in-flight requests and kills child processes */
596627
596954
  abort() {
596628
596955
  this.aborted = true;
596629
596956
  this._abortController.abort();
596957
+ this._turnAbortController.abort();
596630
596958
  const shellTool = this.tools.get("shell");
596631
596959
  if (shellTool && typeof shellTool.killAll === "function") {
596632
596960
  shellTool.killAll();
@@ -596638,7 +596966,245 @@ ${notice}`;
596638
596966
  }
596639
596967
  /** Get the current abort signal for passing to fetch/spawn */
596640
596968
  get abortSignal() {
596641
- return this._abortController.signal;
596969
+ return this._turnAbortController.signal;
596970
+ }
596971
+ /** Current run identity and epoch, exposed for frontends that persist intake. */
596972
+ get taskEpoch() {
596973
+ return this._taskEpoch;
596974
+ }
596975
+ get activeRunId() {
596976
+ return this._activeRunId;
596977
+ }
596978
+ /** Immutable run key for artifacts; sessionId remains correlation metadata. */
596979
+ currentArtifactRunId() {
596980
+ return this._activeRunId || this._sessionId;
596981
+ }
596982
+ _steeringReceipt(record) {
596983
+ return {
596984
+ inputId: record.inputId,
596985
+ intent: record.intent,
596986
+ state: record.state,
596987
+ taskEpoch: record.taskEpoch,
596988
+ runId: this._activeRunId || void 0,
596989
+ acceptedAt: (/* @__PURE__ */ new Date()).toISOString()
596990
+ };
596991
+ }
596992
+ /**
596993
+ * Retire a satisfied read-plan from the exact outbound request. Tool-call
596994
+ * metadata and tool-result links are retained untouched for provider
596995
+ * protocol correctness; only stale assistant-visible planning prose changes.
596996
+ */
596997
+ _retireLinkedAssistantReadIntents(messages2) {
596998
+ const resolvedToolCallIds = new Set(messages2.filter((message2) => message2.role === "tool" && message2.tool_call_id).map((message2) => message2.tool_call_id));
596999
+ for (const message2 of messages2) {
597000
+ if (message2.role !== "assistant" || typeof message2.content !== "string" || !Array.isArray(message2.tool_calls) || !message2.tool_calls.some((call) => resolvedToolCallIds.has(call.id)) || !/\b(?:i|we)\s+(?:need|will|should|have)\s+to\s+(?:read|inspect|open)\b/i.test(message2.content)) {
597001
+ continue;
597002
+ }
597003
+ message2.content = "[assistant read intent retired: the linked tool result is present below; decide from that evidence rather than planning the same read]";
597004
+ }
597005
+ }
597006
+ _emitSteeringLifecycle(record, reason) {
597007
+ const receipt = this._steeringReceipt(record);
597008
+ this.emit({
597009
+ type: "status",
597010
+ content: `Steering ${record.inputId} ${record.state}: ${reason}`,
597011
+ steering: receipt,
597012
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
597013
+ });
597014
+ appendSteeringLedgerEntry(this._workingDirectory || process.cwd(), {
597015
+ type: "lifecycle",
597016
+ packetId: record.inputId,
597017
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
597018
+ intake: { ...record },
597019
+ summary: reason
597020
+ });
597021
+ }
597022
+ _setBackendTurnAbortSignal(signal) {
597023
+ if (typeof this.backend.setAbortSignal === "function") {
597024
+ this.backend.setAbortSignal(signal);
597025
+ }
597026
+ }
597027
+ _requestSteeringPreemption(record) {
597028
+ this._pendingSteeringPreemption = record;
597029
+ record.state = "acknowledged";
597030
+ this._emitSteeringLifecycle(record, "preemption acknowledged");
597031
+ this._turnAbortController.abort(new Error(`steering ${record.intent}: ${record.inputId}`));
597032
+ const shellTool = this.tools.get("shell");
597033
+ if (shellTool && typeof shellTool.killAll === "function") {
597034
+ shellTool.killAll();
597035
+ }
597036
+ this._turnAbortController = new AbortController();
597037
+ this._setBackendTurnAbortSignal(this._turnAbortController.signal);
597038
+ }
597039
+ _prepareSteeringInputsForRun() {
597040
+ const initialInputs = this.pendingSteeringInputs.filter((record) => record.state === "queued" || record.state === "acknowledged");
597041
+ this._allowImplicitContinuation = initialInputs.some((record) => record.intent === "append" || record.intent === "clarify") && !initialInputs.some((record) => record.intent === "redirect" || record.intent === "replace" || record.intent === "cancel");
597042
+ for (const record of this.pendingSteeringInputs) {
597043
+ if (record.state !== "queued" && record.state !== "acknowledged")
597044
+ continue;
597045
+ if (record.taskEpoch && record.taskEpoch !== this._taskEpoch) {
597046
+ record.state = "superseded";
597047
+ this._emitSteeringLifecycle(record, "superseded by a later task run");
597048
+ const index = this.pendingUserMessages.lastIndexOf(record.content);
597049
+ if (index >= 0)
597050
+ this.pendingUserMessages.splice(index, 1);
597051
+ continue;
597052
+ }
597053
+ record.taskEpoch = this._taskEpoch;
597054
+ this._emitSteeringLifecycle(record, "bound to active task epoch");
597055
+ }
597056
+ }
597057
+ /** Archive prior task-epoch state before its session-backed records are hidden. */
597058
+ _archiveSupersededTaskState(taskEpoch, steering) {
597059
+ const todos = this.readSessionTodos() ?? [];
597060
+ const archive = {
597061
+ runId: this._activeRunId || this._sessionId,
597062
+ sessionId: this._sessionId,
597063
+ taskEpoch,
597064
+ supersededAt: (/* @__PURE__ */ new Date()).toISOString(),
597065
+ steering: {
597066
+ inputId: steering.inputId,
597067
+ intent: steering.intent,
597068
+ content: steering.content
597069
+ },
597070
+ todos,
597071
+ workboard: this._workboard,
597072
+ completionLedger: this._completionLedger
597073
+ };
597074
+ try {
597075
+ const dir = _pathJoin(this.omniusStateDir(), "task-epoch-archives");
597076
+ _fsMkdirSync(dir, { recursive: true });
597077
+ _fsWriteFileSync(_pathJoin(dir, `${this._activeRunId || this._sessionId}-epoch-${taskEpoch}.json`), JSON.stringify(archive, null, 2), "utf8");
597078
+ } catch {
597079
+ }
597080
+ for (const todo of todos)
597081
+ this._supersededTodoIds.add(todo.id);
597082
+ this._workboard = null;
597083
+ }
597084
+ _steeringRecordForContent(content) {
597085
+ return this.pendingSteeringInputs.find((record) => record.content === content && (record.state === "queued" || record.state === "acknowledged") && record.taskEpoch === this._taskEpoch);
597086
+ }
597087
+ _canonicalReadEvidencePayload(canonicalPath, contentHash2) {
597088
+ const branch = this._branchEvidenceByPath.get(canonicalPath);
597089
+ if (branch && branch.contentHash === contentHash2)
597090
+ return branch.output;
597091
+ return null;
597092
+ }
597093
+ _rehydrateResolvedReadEvidence(input) {
597094
+ const previous = this._resolvedReadEvidence.get(input.fingerprint);
597095
+ const handle2 = previous?.handle ?? `evidence:${input.canonicalPath}:${input.contentHash.slice(0, 16)}`;
597096
+ this._resolvedReadEvidence.set(input.fingerprint, {
597097
+ state: "resolved_from_cache",
597098
+ handle: handle2,
597099
+ path: input.canonicalPath,
597100
+ contentHash: input.contentHash,
597101
+ resolvedTurn: input.turn,
597102
+ consumed: false
597103
+ });
597104
+ return [
597105
+ "[REHYDRATED_FILE_EVIDENCE]",
597106
+ `handle=${handle2}`,
597107
+ "fingerprint_state=resolved_from_cache",
597108
+ `path=${input.canonicalPath}`,
597109
+ `sha256=${input.contentHash}`,
597110
+ "Facts below are canonical current-run evidence. Consume these facts in the next decision; do not repeat the identical read.",
597111
+ "[CANONICAL_FACTS]",
597112
+ input.payload.slice(0, 7e3),
597113
+ "[/CANONICAL_FACTS]"
597114
+ ].join("\n");
597115
+ }
597116
+ _rejectRepeatedResolvedRead(tc, messages2) {
597117
+ if (tc.name !== "file_read") {
597118
+ for (const state2 of this._resolvedReadEvidence.values()) {
597119
+ state2.consumed = true;
597120
+ }
597121
+ return null;
597122
+ }
597123
+ const fingerprint = this._buildToolFingerprint(tc.name, tc.arguments);
597124
+ const state = this._resolvedReadEvidence.get(fingerprint);
597125
+ if (!state)
597126
+ return null;
597127
+ const latestAssistant = [...messages2].reverse().find((message2) => message2.role === "assistant" && typeof message2.content === "string");
597128
+ if (latestAssistant && typeof latestAssistant.content === "string" && latestAssistant.content.includes(state.handle)) {
597129
+ state.consumed = true;
597130
+ }
597131
+ return [
597132
+ "[REPEATED_READ_REJECTED]",
597133
+ `handle=${state.handle}`,
597134
+ `fingerprint_state=${state.state}`,
597135
+ state.consumed ? "The evidence handle was acknowledged, but an identical read cannot add facts. Change file/range/query scope or take the evidence-backed next action." : "Consume the rehydrated evidence handle in your next decision before requesting another read. Change file/range/query scope if a different fact is required."
597136
+ ].join("\n");
597137
+ }
597138
+ async _drainPendingSteeringMessages(messages2, turn) {
597139
+ this.drainPendingRuntimeGuidance(turn);
597140
+ while (this.pendingUserMessages.length > 0) {
597141
+ const userMsg = this.pendingUserMessages.shift();
597142
+ const record = this._steeringRecordForContent(userMsg);
597143
+ const replacement = this._pendingSteeringPreemption;
597144
+ if (replacement?.intent === "replace" && record && record.inputId !== replacement.inputId) {
597145
+ record.state = "superseded";
597146
+ this._emitSteeringLifecycle(record, `superseded before consumption by replacement ${replacement.inputId}`);
597147
+ continue;
597148
+ }
597149
+ await this.appendInjectedUserMessage(userMsg, messages2, turn);
597150
+ if (record) {
597151
+ record.state = "consumed";
597152
+ this._emitSteeringLifecycle(record, `consumed at turn ${turn}`);
597153
+ }
597154
+ }
597155
+ }
597156
+ /** Apply a preemption only at a safe boundary after its user content is visible. */
597157
+ _applyPendingSteeringPreemption(messages2, turn) {
597158
+ const record = this._pendingSteeringPreemption;
597159
+ if (!record)
597160
+ return false;
597161
+ this._pendingSteeringPreemption = null;
597162
+ if (record.intent === "cancel") {
597163
+ record.state = "cancelled";
597164
+ this._emitSteeringLifecycle(record, `cancelled active task at turn ${turn}`);
597165
+ this.abort();
597166
+ return true;
597167
+ }
597168
+ const previousEpoch = this._taskEpoch;
597169
+ this._archiveSupersededTaskState(previousEpoch, record);
597170
+ this._allowImplicitContinuation = false;
597171
+ this._taskEpoch += 1;
597172
+ record.taskEpoch = this._taskEpoch;
597173
+ if (record.intent === "replace") {
597174
+ for (const candidate of this.pendingSteeringInputs) {
597175
+ if (candidate.inputId !== record.inputId && candidate.taskEpoch === previousEpoch && (candidate.state === "queued" || candidate.state === "acknowledged")) {
597176
+ candidate.state = "superseded";
597177
+ this._emitSteeringLifecycle(candidate, `superseded by replacement ${record.inputId}`);
597178
+ }
597179
+ }
597180
+ }
597181
+ this._completionContract = null;
597182
+ this._completionLedger = this.writesUserTaskArtifacts() ? createCompletionLedger({
597183
+ runId: this.currentArtifactRunId(),
597184
+ goal: record.content
597185
+ }) : null;
597186
+ if (this._completionLedger) {
597187
+ this._completionLedger.taskEpoch = this._taskEpoch;
597188
+ }
597189
+ this._completionHoldState.count = 0;
597190
+ this._completionHoldState.total = 0;
597191
+ this._completionHoldState.lastKey = "";
597192
+ this._completionIncompleteVerification = null;
597193
+ this._taskState.goal = record.content;
597194
+ this._taskState.originalGoal = record.content;
597195
+ messages2.push({
597196
+ role: "system",
597197
+ content: [
597198
+ "[ACTIVE USER STEERING - HIGHEST USER PRIORITY]",
597199
+ `inputId=${record.inputId} taskEpoch=${this._taskEpoch} intent=${record.intent}`,
597200
+ "The prior task epoch is historical evidence only. Do not continue its plan, todos, recovery cards, or completion contract.",
597201
+ "Replan from this active user instruction before any further tool call:",
597202
+ record.content
597203
+ ].join("\n")
597204
+ });
597205
+ record.state = "consumed";
597206
+ this._emitSteeringLifecycle(record, `applied at turn ${turn}; epoch ${previousEpoch} -> ${this._taskEpoch}`);
597207
+ return true;
596642
597208
  }
596643
597209
  /**
596644
597210
  * Pause the current task gracefully. The run loop will suspend at the next
@@ -596899,28 +597465,32 @@ ${notice}`;
596899
597465
  const cacheKey = `${canonicalPath}|${fullHash}|${offset ?? 0}:${limit ?? "EOF"}|${contractFingerprint}`;
596900
597466
  const cached = this._branchEvidenceCache.get(cacheKey);
596901
597467
  if (cached) {
596902
- const duplicateBlocked = [
596903
- `[BRANCH-DUPLICATE-BLOCKED] path=${rawPath} sha256=${fullHash} contract=${contractFingerprint}`,
596904
- `The unchanged source was already branch-extracted into the current evidence ledger; the registered file_read was not executed and raw content was not re-injected.`,
596905
- `Use the existing curated anchors. If a required discovery is unresolved, issue one narrower grep_search or a range whose projected payload stays below the 20% limit; otherwise take the next task action.`
596906
- ].join("\n");
597468
+ const fingerprint = this._buildToolFingerprint(input.toolName, input.args);
597469
+ const rehydrated = this._rehydrateResolvedReadEvidence({
597470
+ fingerprint,
597471
+ canonicalPath,
597472
+ contentHash: fullHash,
597473
+ payload: cached.output,
597474
+ turn: input.turn
597475
+ });
596907
597476
  this.emit({
596908
597477
  type: "status",
596909
597478
  toolName: input.toolName,
596910
- content: `Branch-extract cache hit: ${rawPath} sha256=${fullHash.slice(0, 12)} contract=${contractFingerprint}`,
597479
+ content: `Branch-extract cache rehydrated: ${rawPath} sha256=${fullHash.slice(0, 12)} contract=${contractFingerprint} fingerprint_state=resolved_from_cache`,
596911
597480
  turn: input.turn,
596912
597481
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
596913
597482
  });
596914
597483
  return {
596915
597484
  success: true,
596916
- output: duplicateBlocked,
596917
- llmContent: duplicateBlocked,
597485
+ output: rehydrated,
597486
+ llmContent: rehydrated,
596918
597487
  beforeHash: fullHash,
596919
597488
  runtimeAuthored: true,
596920
597489
  noop: true,
596921
597490
  completionEvidenceMetrics: {
596922
597491
  branchSourceBytes: cached.sourceBytes,
596923
- branchCacheHit: true
597492
+ branchCacheHit: true,
597493
+ fingerprintState: "resolved_from_cache"
596924
597494
  }
596925
597495
  };
596926
597496
  }
@@ -597439,7 +598009,7 @@ ${inventory}`
597439
598009
  });
597440
598010
  this._onTypedEvent?.({
597441
598011
  type: "trajectory_checkpoint",
597442
- runId: this._sessionId,
598012
+ runId: this.currentArtifactRunId(),
597443
598013
  revision: checkpoint.revision,
597444
598014
  assessment: checkpoint.assessment,
597445
598015
  nextAction: checkpoint.nextAction,
@@ -597450,7 +598020,7 @@ ${inventory}`
597450
598020
  recordDebugTrajectoryCheckpoint({
597451
598021
  cwd: this.authoritativeWorkingDirectory(),
597452
598022
  stateDir: this.omniusStateDir(),
597453
- runId: this._sessionId,
598023
+ runId: this.currentArtifactRunId(),
597454
598024
  sessionId: this._sessionId,
597455
598025
  checkpoint
597456
598026
  });
@@ -597691,6 +598261,9 @@ Respond with the assessment and take the selected evidence-backed action.`;
597691
598261
  async run(task, context2, actualUserGoal) {
597692
598262
  this.aborted = false;
597693
598263
  this._abortController = new AbortController();
598264
+ this._turnAbortController = new AbortController();
598265
+ this._taskEpoch += 1;
598266
+ this._activeRunId = `${this._sessionId || "run"}-${Date.now()}-${this._taskEpoch}`;
597694
598267
  this._fileWritesThisRun = 0;
597695
598268
  this._backwardPassCyclesUsed = 0;
597696
598269
  this._completionVerifyRejections = 0;
@@ -597716,7 +598289,7 @@ Respond with the assessment and take the selected evidence-backed action.`;
597716
598289
  this._resetVisualEvidenceState();
597717
598290
  this._verifyFailuresBaseline = new Set(this._verifyFailures);
597718
598291
  if (typeof this.backend.setAbortSignal === "function") {
597719
- this.backend.setAbortSignal(this._abortController.signal);
598292
+ this.backend.setAbortSignal(this._turnAbortController.signal);
597720
598293
  }
597721
598294
  const cleanedTask = cleanForStorage(task) || task.slice(0, 500);
597722
598295
  const start2 = Date.now();
@@ -597847,7 +598420,7 @@ Respond with the assessment and take the selected evidence-backed action.`;
597847
598420
  }
597848
598421
  this._loadResolutionMemory();
597849
598422
  this._pauseResolve = null;
597850
- this.pendingUserMessages.length = 0;
598423
+ this._prepareSteeringInputsForRun();
597851
598424
  const persistentTaskGoal = cleanForStorage(actualUserGoal || "") || cleanedTask;
597852
598425
  const userGoal = persistentTaskGoal.slice(0, 500);
597853
598426
  this._taskRelevantErrorPatterns = process.env["OMNIUS_DISABLE_FAILURE_HANDOFF"] === "1" ? /* @__PURE__ */ new Map() : await this._selectTaskRelevantErrorPatterns(persistentTaskGoal, 10);
@@ -597952,9 +598525,10 @@ Respond with the assessment and take the selected evidence-backed action.`;
597952
598525
  if (this.writesUserTaskArtifacts()) {
597953
598526
  this._initializeCompletionContract(task, context2, actualUserGoal);
597954
598527
  this._completionLedger = createCompletionLedger({
597955
- runId: this._sessionId,
598528
+ runId: this._activeRunId || this._sessionId,
597956
598529
  goal: userGoal
597957
598530
  });
598531
+ this._completionLedger.taskEpoch = this._taskEpoch;
597958
598532
  } else {
597959
598533
  this._completionContract = null;
597960
598534
  this._completionLedger = null;
@@ -598071,7 +598645,11 @@ Respond with the assessment and take the selected evidence-backed action.`;
598071
598645
  }
598072
598646
  }
598073
598647
  const contextComposition = await this.assembleContext(task, context2);
598074
- let systemPrompt = contextComposition.assembled;
598648
+ const staticContextLabels = /* @__PURE__ */ new Set(["c_instr", "c_conventions", "c_state"]);
598649
+ let systemPrompt = contextComposition.sections.filter((section) => staticContextLabels.has(section.label)).map((section) => section.content).join("");
598650
+ const dynamicProjectContext = contextComposition.sections.filter((section) => !staticContextLabels.has(section.label) && section.label !== "c_lessons").map((section) => section.content).join("");
598651
+ if (!systemPrompt)
598652
+ systemPrompt = contextComposition.assembled;
598075
598653
  try {
598076
598654
  systemPrompt = `${systemPrompt}
598077
598655
 
@@ -598143,7 +598721,7 @@ TASK: ${scrubbedTask}` : scrubbedTask;
598143
598721
  kind: "system_prompt",
598144
598722
  capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
598145
598723
  taskPreview: persistentTaskGoal.slice(0, 240),
598146
- assembledCharCount: systemPrompt.length,
598724
+ assembledCharCount: systemPrompt.length + dynamicProjectContext.length,
598147
598725
  totalTokenEstimate: contextComposition.totalTokenEstimate,
598148
598726
  sections: contextComposition.sections.map((section, order) => ({
598149
598727
  label: section.label,
@@ -598167,17 +598745,20 @@ TASK: ${scrubbedTask}` : scrubbedTask;
598167
598745
  const messages2 = [
598168
598746
  { role: "system", content: systemPrompt },
598169
598747
  ...missionCompletionContract ? [{ role: "system", content: missionCompletionContract }] : [],
598748
+ ...dynamicProjectContext ? [
598749
+ {
598750
+ role: "system",
598751
+ content: `[DYNAMIC PROJECT STATE]
598752
+ ${dynamicProjectContext}`
598753
+ }
598754
+ ] : [],
598170
598755
  { role: "user", content: userContent }
598171
598756
  ];
598172
598757
  const preflightMemoryRecall = await this._buildPreflightTaskMemoryRecall(persistentTaskGoal);
598173
598758
  if (preflightMemoryRecall) {
598174
- messages2.splice(messages2.length - 1, 0, {
598175
- role: "system",
598176
- content: preflightMemoryRecall
598177
- });
598178
598759
  this.emit({
598179
598760
  type: "status",
598180
- content: "Preflight memory recall injected for task-relevant prior episodes",
598761
+ content: "Preflight memory recall retained for telemetry; omitted from model context",
598181
598762
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
598182
598763
  });
598183
598764
  }
@@ -598260,9 +598841,9 @@ TASK: ${scrubbedTask}` : scrubbedTask;
598260
598841
  if (process.env["OMNIUS_FRESH_SESSION"] === "1")
598261
598842
  throw "skip-handoff-fresh";
598262
598843
  const omniusDir = this._workingDirectory ? _pathJoin(this._workingDirectory, ".omnius") : _pathJoin(process.cwd(), ".omnius");
598263
- const chainPairs = loadMessagePairsFromLog(omniusDir, {
598844
+ const chainPairs = this._allowImplicitContinuation ? loadMessagePairsFromLog(omniusDir, {
598264
598845
  currentTask: persistentTaskGoal
598265
- });
598846
+ }) : [];
598266
598847
  if (chainPairs.length > 0) {
598267
598848
  messages2.splice(1, 0, ...chainPairs);
598268
598849
  this.emit({
@@ -598273,7 +598854,8 @@ TASK: ${scrubbedTask}` : scrubbedTask;
598273
598854
  } else {
598274
598855
  const prior = readTaskHandoff(omniusDir, {
598275
598856
  currentSessionId: this._sessionId,
598276
- currentTask: persistentTaskGoal
598857
+ currentTask: persistentTaskGoal,
598858
+ allowImplicitContinuation: this._allowImplicitContinuation
598277
598859
  });
598278
598860
  if (prior) {
598279
598861
  const handoffPair = buildHandoffMessagePair(prior);
@@ -598301,17 +598883,17 @@ TASK: ${scrubbedTask}` : scrubbedTask;
598301
598883
  const reflections = this._reflectionBuffer.getRelevantReflections(persistentTaskGoal, 3);
598302
598884
  if (reflections.length > 0) {
598303
598885
  const reflectionCtx = this._reflectionBuffer.formatForContext(reflections);
598304
- messages2.push({ role: "system", content: reflectionCtx });
598886
+ void reflectionCtx;
598305
598887
  this.emit({
598306
598888
  type: "status",
598307
- content: `Reflexion: injected ${reflections.length} prior failure reflection(s) for this task type`,
598889
+ content: `Reflexion: retained ${reflections.length} prior failure reflection(s) for telemetry only`,
598308
598890
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
598309
598891
  });
598310
598892
  }
598311
598893
  }
598312
598894
  } catch {
598313
598895
  }
598314
- if (process.env["OMNIUS_DISABLE_FAILURE_HANDOFF"] !== "1") {
598896
+ if (false) {
598315
598897
  try {
598316
598898
  const failureHandoff = buildFailureModeHandoff({
598317
598899
  taskGoal: persistentTaskGoal,
@@ -598328,8 +598910,7 @@ TASK: ${scrubbedTask}` : scrubbedTask;
598328
598910
  priority: 85,
598329
598911
  createdTurn: 0
598330
598912
  });
598331
- if (signal)
598332
- this._contextLedger.upsert(signal);
598913
+ void signal;
598333
598914
  }
598334
598915
  } catch {
598335
598916
  }
@@ -598388,7 +598969,7 @@ TASK: ${scrubbedTask}` : scrubbedTask;
598388
598969
  }),
598389
598970
  persistPath,
598390
598971
  sessionId: this._sessionId,
598391
- runId: this._sessionId,
598972
+ runId: this.currentArtifactRunId(),
598392
598973
  cwd: this._workingDirectory || process.cwd(),
598393
598974
  model: this._backendModelLabel(this.backend),
598394
598975
  onCritique: (critique2, sourceTurn) => {
@@ -598634,6 +599215,19 @@ TASK: ${scrubbedTask}` : scrubbedTask;
598634
599215
  return completionHoldEscapeMax * 2;
598635
599216
  })();
598636
599217
  const holdTaskCompleteGates = (args, turn) => {
599218
+ if (this._hasEvidenceBackedBlockedCompletion(args)) {
599219
+ this._completionHoldState.count = 0;
599220
+ this._completionHoldState.lastKey = "";
599221
+ this._completionHoldState.total = 0;
599222
+ lastCompletionGateCode = "";
599223
+ this.emit({
599224
+ type: "status",
599225
+ content: "task_complete admitted as evidence-backed blocked state",
599226
+ turn,
599227
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
599228
+ });
599229
+ return false;
599230
+ }
598637
599231
  if (this._completionHoldState.total >= completionHoldHardMax) {
598638
599232
  const incompleteSummary = [
598639
599233
  `INCOMPLETE_VERIFICATION: completion was requested after ${this._completionHoldState.total} gate hold(s), but required evidence is still missing.`,
@@ -598853,6 +599447,8 @@ ${lastCompletionGateFeedback.trim().slice(0, 4e3)}` : ""
598853
599447
  }
598854
599448
  }
598855
599449
  for (let turn = 0; turn < turnCap; turn++) {
599450
+ this._turnAbortController = new AbortController();
599451
+ this._setBackendTurnAbortSignal(this._turnAbortController.signal);
598856
599452
  clearTurnState(this._appState);
598857
599453
  this._maybeApplyThinkGuard();
598858
599454
  if (this._paused) {
@@ -598865,7 +599461,7 @@ ${lastCompletionGateFeedback.trim().slice(0, 4e3)}` : ""
598865
599461
  });
598866
599462
  this._onTypedEvent?.({
598867
599463
  type: "run_failed",
598868
- runId: this._sessionId ?? "unknown",
599464
+ runId: this.currentArtifactRunId(),
598869
599465
  error: "Task aborted by user",
598870
599466
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
598871
599467
  });
@@ -598880,7 +599476,7 @@ ${lastCompletionGateFeedback.trim().slice(0, 4e3)}` : ""
598880
599476
  });
598881
599477
  this._onTypedEvent?.({
598882
599478
  type: "run_failed",
598883
- runId: this._sessionId ?? "unknown",
599479
+ runId: this.currentArtifactRunId(),
598884
599480
  error: "Task aborted by user",
598885
599481
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
598886
599482
  });
@@ -598954,7 +599550,7 @@ ${lastCompletionGateFeedback.trim().slice(0, 4e3)}` : ""
598954
599550
  });
598955
599551
  this._onTypedEvent?.({
598956
599552
  type: "completion_requested",
598957
- runId: this._sessionId ?? "unknown",
599553
+ runId: this.currentArtifactRunId(),
598958
599554
  summary: summary.slice(0, 500),
598959
599555
  sourcePath: "direct",
598960
599556
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -599109,7 +599705,7 @@ ${lastCompletionGateFeedback.trim().slice(0, 4e3)}` : ""
599109
599705
  });
599110
599706
  } else {
599111
599707
  const directive = this._failingApproachDirective(faSignal);
599112
- messages2.push({ role: "system", content: directive });
599708
+ void directive;
599113
599709
  this.emit({
599114
599710
  type: "adversary_reaction",
599115
599711
  adversary: {
@@ -599146,7 +599742,7 @@ Respond with EXACTLY this structure before your next tool call:
599146
599742
  NEXT ACTION: <a single creative edit — file_write / file_edit / batch_edit — that tests the picked hypothesis>
599147
599743
 
599148
599744
  If the hypothesis cannot be tested by a creative edit, ask the human via task_complete with summary 'BLOCKED: <reason>'.`;
599149
- messages2.push({ role: "system", content: replan });
599745
+ void replan;
599150
599746
  stagnationCooldownUntilTurn = turn + 8;
599151
599747
  const _tel58 = this._describeTopClusterTelemetry();
599152
599748
  const _telSuffix58 = _tel58 ? `; rca3_preamble=applied; top_cluster=${_tel58.code} (${_tel58.observations}×); has_hint=${_tel58.hasHint}` : `; rca3_preamble=none`;
@@ -599177,7 +599773,7 @@ Respond with EXACTLY this structure before your next tool call:
599177
599773
  WHY: <one sentence>
599178
599774
  FALSIFICATION: <observable signal that would refute the pick>
599179
599775
  NEXT ACTION: <a single targeted edit — file_edit / file_patch / batch_edit; file_write only for a verified-new file>`;
599180
- messages2.push({ role: "system", content: _replan60 });
599776
+ void _replan60;
599181
599777
  stagnationCooldownUntilTurn = turn + REG60_COOLDOWN_TURNS;
599182
599778
  const _tel60 = this._describeTopClusterTelemetry();
599183
599779
  const _telSuffix60 = _tel60 ? `; rca3_preamble=applied; top_cluster=${_tel60.code} (${_tel60.observations}×); has_hint=${_tel60.hasHint}` : `; rca3_preamble=none`;
@@ -599242,7 +599838,7 @@ Respond with EXACTLY this structure before your next tool call:
599242
599838
  ].join("\n");
599243
599839
  }
599244
599840
  }
599245
- messages2.push({ role: "system", content: _stagBody });
599841
+ void _stagBody;
599246
599842
  stagnationCooldownUntilTurn = turn + 5;
599247
599843
  try {
599248
599844
  const memMod = await Promise.resolve().then(() => (init_dist(), dist_exports));
@@ -599274,12 +599870,7 @@ Respond with EXACTLY this structure before your next tool call:
599274
599870
  const recipes = this._episodeStore ? memMod.lookupBySignature(this._episodeStore, sig, 1) : [];
599275
599871
  if (recipes.length > 0) {
599276
599872
  const r2 = recipes[0];
599277
- messages2.push({
599278
- role: "system",
599279
- content: `[STAGNATION RECIPE — found from prior run with same failure shape]
599280
- ${r2.content}
599281
- If this matches your current shape, try it before continuing.`
599282
- });
599873
+ void r2;
599283
599874
  this.emit({
599284
599875
  type: "status",
599285
599876
  content: `[STAGNATION RECIPE] surfaced prior recipe (sig=${sig}) for current failure shape`,
@@ -599447,30 +600038,6 @@ If this matches your current shape, try it before continuing.`
599447
600038
  ``,
599448
600039
  ` (e) REPORT BLOCKED: only when evidence shows a missing dependency, ambiguous requirement, or external service issue. State the blocker and prerequisite; do not call \`task_complete\` merely because this detector fired.`
599449
600040
  ];
599450
- messages2.push({
599451
- role: "system",
599452
- content: [
599453
- `[STUCK DETECTOR HALT — REG-44]`,
599454
- ``,
599455
- `Window: last ${_windowCalls.length} tool calls.`,
599456
- ` • Reads/exploration calls: ${_readCount}`,
599457
- ` • Productive mutations: ${_mutationCount}`,
599458
- ` • Stale (cached/blocked/no-op) results: ${_staleCount}`,
599459
- ` • Triggers fired: ${_trigLabels.join(", ")}`,
599460
- ``,
599461
- `You are consuming turns without accumulating decision-ready evidence or verified progress. Every shape of “stuck” — read-heavy without a narrowing question, repeated cache hits, blocked-shell loops, no-op todo updates, or blind mutation retries — can produce this signal. The exact tool names do not decide the fix; the freshest evidence does.`,
599462
- ``,
599463
- ..._reg44ChoiceLines,
599464
- ``,
599465
- `Recent failures (real or synthetic):`,
599466
- _failureBlocks,
599467
- ``,
599468
- _staleSamples.length > 0 ? `Stale-result samples in this window:
599469
- ${_staleSamples.join("\n")}` : ``,
599470
- ``,
599471
- `Do NOT in your next response: re-read a file you've already read this turn, re-run a shell command that just got blocked, or update todos without changing them. Those are the moves that landed you here.`
599472
- ].filter(Boolean).join("\n")
599473
- });
599474
600041
  this.emit({
599475
600042
  type: "status",
599476
600043
  content: `REG-44 STUCK detector fired at turn ${turn} — triggers=[${_trigLabels.join(",")}], reads=${_readCount}, mutations=${_mutationCount}, stale=${_staleCount}, window=${_windowCalls.length}`,
@@ -599541,10 +600108,7 @@ ${_staleSamples.join("\n")}` : ``,
599541
600108
  callable: _smaCallable
599542
600109
  }).then((_smaResult) => {
599543
600110
  if (_smaResult.injection && !_smaResult.directive.parseFallback) {
599544
- messages2.push({
599545
- role: "system",
599546
- content: _smaResult.injection
599547
- });
600111
+ void _smaResult.injection;
599548
600112
  this.emit({
599549
600113
  type: "status",
599550
600114
  content: `REG-49 stuck-meta-analyzer fired at turn ${turn} — diagnosis="${_smaResult.directive.diagnosis.slice(0, 80)}", next=${_smaResult.directive.next_action.tool}, ${_smaResult.durationMs}ms`,
@@ -599635,19 +600199,6 @@ ${_staleSamples.join("\n")}` : ``,
599635
600199
  ``,
599636
600200
  `Do NOT in your next response: write to ${_wtWorstPath} again without first running and reading the failing command's output.`
599637
600201
  ];
599638
- messages2.push({
599639
- role: "system",
599640
- content: [
599641
- `[WRITE-THRASH HALT — REG-50]`,
599642
- ``,
599643
- `In the last ${_wtWindow.length} tool calls you have written the same file ${_wtWorstCount} times:`,
599644
- ` ${_wtWorstPath}`,
599645
- ``,
599646
- `No successful test/build/typecheck command ran between writes — you are iterating the file blind, hoping the next variation works. This is a write-thrash anti-pattern. Repeated edits without verification confirm nothing.`,
599647
- ``,
599648
- ..._reg50ChoiceLines
599649
- ].join("\n")
599650
- });
599651
600202
  this.emit({
599652
600203
  type: "status",
599653
600204
  content: `REG-50 WRITE-THRASH halt fired at turn ${turn} — file=${_wtWorstPath}, count=${_wtWorstCount}/${_wtThreshold}, no successful verify in window`,
@@ -599714,10 +600265,7 @@ ${_staleSamples.join("\n")}` : ``,
599714
600265
  callable: _smaCallable50
599715
600266
  }).then((_smaResult) => {
599716
600267
  if (_smaResult.injection && !_smaResult.directive.parseFallback) {
599717
- messages2.push({
599718
- role: "system",
599719
- content: _smaResult.injection
599720
- });
600268
+ void _smaResult.injection;
599721
600269
  this.emit({
599722
600270
  type: "status",
599723
600271
  content: `REG-50 → SSMA fired at turn ${turn} — diagnosis="${_smaResult.directive.diagnosis.slice(0, 80)}", next=${_smaResult.directive.next_action.tool}, ${_smaResult.durationMs}ms`,
@@ -599781,19 +600329,6 @@ ${_staleSamples.join("\n")}` : ``,
599781
600329
  ``,
599782
600330
  `Do NOT in your next response: call file_edit or batch_edit on ${_efWorstPath} again with another guess at old_string.`
599783
600331
  ];
599784
- messages2.push({
599785
- role: "system",
599786
- content: [
599787
- `[EDIT-FAIL-THRASH HALT — REG-53]`,
599788
- ``,
599789
- `In the last ${_efWindow.length} tool calls you have failed file_edit/batch_edit on the same file ${_efWorstCount} times:`,
599790
- ` ${_efWorstPath}`,
599791
- ``,
599792
- `Each failure means your old_string did not match the file content. Your remembered version of this file has diverged from what's on disk — likely because an earlier edit succeeded and shifted things, or because you guessed at the file's content.`,
599793
- ``,
599794
- ..._reg53ChoiceLines
599795
- ].join("\n")
599796
- });
599797
600332
  this.emit({
599798
600333
  type: "status",
599799
600334
  content: `REG-53 EDIT-FAIL-THRASH halt fired at turn ${turn} — file=${_efWorstPath}, failures=${_efWorstCount}/${_efThreshold}`,
@@ -599871,10 +600406,7 @@ ${_staleSamples.join("\n")}` : ``,
599871
600406
  callable: _pfvCallable
599872
600407
  }).then((_pfvResult) => {
599873
600408
  if (_pfvResult.injection && !_pfvResult.verdict.parseFallback && _pfvResult.verdict.verdict !== "continue") {
599874
- messages2.push({
599875
- role: "system",
599876
- content: _pfvResult.injection
599877
- });
600409
+ void _pfvResult.injection;
599878
600410
  this.emit({
599879
600411
  type: "status",
599880
600412
  content: `REG-51 PFV fired at turn ${turn} — verdict=${_pfvResult.verdict.verdict}, trigger=${_pfvTriggerReason}, ssmaCount=${this._ssmaFiredCount}, ${_pfvResult.durationMs}ms`,
@@ -599939,18 +600471,6 @@ ${_staleSamples.join("\n")}` : ``,
599939
600471
  ].join("\n");
599940
600472
  }
599941
600473
  }
599942
- messages2.push({
599943
- role: "system",
599944
- content: [
599945
- `[STICKY ESCALATION — REG-45 — failure persists across turns]`,
599946
- ``,
599947
- `You have an unresolved high-attempt failure that you may have stopped trying to fix. Every turn that this remains unresolved, this reflection will resurface so the issue stays visible:`,
599948
- ``,
599949
- _body,
599950
- ``,
599951
- `If this failure is genuinely irrelevant now (e.g. the goal moved on), the only way to clear this notice is to make a successful attempt of the same call (or close-equivalent) — that resets the failure record. Otherwise, address it now.`
599952
- ].join("\n")
599953
- });
599954
600474
  this._stickyEscalationsSurfacedThisTurn.add(_stem);
599955
600475
  this._reflectionsInjectedThisTurn.add(_stem);
599956
600476
  this.emit({
@@ -600019,10 +600539,11 @@ ${_staleSamples.join("\n")}` : ``,
600019
600539
  });
600020
600540
  }
600021
600541
  }
600022
- this.drainPendingRuntimeGuidance(turn);
600023
- while (this.pendingUserMessages.length > 0) {
600024
- const userMsg = this.pendingUserMessages.shift();
600025
- await this.appendInjectedUserMessage(userMsg, messages2, turn);
600542
+ await this._drainPendingSteeringMessages(messages2, turn);
600543
+ if (this._applyPendingSteeringPreemption(messages2, turn)) {
600544
+ if (this.aborted)
600545
+ break;
600546
+ continue;
600026
600547
  }
600027
600548
  if (!this.options.disableTodoPlanningNudges) {
600028
600549
  const maybeReminder = this.getTodoReminderContent(turn);
@@ -600252,7 +600773,7 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
600252
600773
  toolEvents: this._toolEvents,
600253
600774
  memoryHints: [],
600254
600775
  runState: {
600255
- runId: this._sessionId,
600776
+ runId: this.currentArtifactRunId(),
600256
600777
  tokenBudget: _limits.compactionThreshold,
600257
600778
  completionContract: this._completionContract ? formatCompletionContract(this._completionContract) : void 0
600258
600779
  }
@@ -600397,7 +600918,7 @@ ${memoryLines.join("\n")}`
600397
600918
  toolEvents: this._toolEvents,
600398
600919
  memoryHints: [],
600399
600920
  runState: {
600400
- runId: this._sessionId,
600921
+ runId: this.currentArtifactRunId(),
600401
600922
  tokenBudget: _limits.compactionThreshold,
600402
600923
  completionContract: this._completionContract ? formatCompletionContract(this._completionContract) : void 0
600403
600924
  }
@@ -600425,6 +600946,12 @@ ${memoryLines.join("\n")}`
600425
600946
  const echoBoostedTemp = this._echoTempBoostTurns > 0 ? Math.max(this.options.temperature ?? 0, 0.7) : this.options.temperature;
600426
600947
  if (this._echoTempBoostTurns > 0)
600427
600948
  this._echoTempBoostTurns--;
600949
+ this._stripLegacyControlMessages(requestMessages);
600950
+ requestMessages.push({
600951
+ role: "system",
600952
+ content: this._buildRecentActionGroundTruth(turn)
600953
+ });
600954
+ this._retireLinkedAssistantReadIntents(requestMessages);
600428
600955
  const chatRequest = {
600429
600956
  messages: requestMessages,
600430
600957
  tools: toolDefs,
@@ -600508,6 +601035,15 @@ ${memoryLines.join("\n")}`
600508
601035
  try {
600509
601036
  response = this.options.streamEnabled && this.hasStreamingSupport() ? await this.streamingRequest(chatRequest, turn) : await this.backend.chatCompletion(chatRequest);
600510
601037
  } catch (reqErr) {
601038
+ if (this._pendingSteeringPreemption) {
601039
+ this.emit({
601040
+ type: "status",
601041
+ content: "Model request interrupted by pending user steering; skipping recovery.",
601042
+ turn,
601043
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
601044
+ });
601045
+ continue;
601046
+ }
600511
601047
  if (reqErr instanceof Error && reqErr.fatal) {
600512
601048
  this.emit({
600513
601049
  type: "error",
@@ -600516,7 +601052,7 @@ ${memoryLines.join("\n")}`
600516
601052
  });
600517
601053
  this._onTypedEvent?.({
600518
601054
  type: "run_failed",
600519
- runId: this._sessionId ?? "unknown",
601055
+ runId: this.currentArtifactRunId(),
600520
601056
  error: reqErr.message,
600521
601057
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
600522
601058
  });
@@ -600535,7 +601071,7 @@ ${memoryLines.join("\n")}`
600535
601071
  });
600536
601072
  this._onTypedEvent?.({
600537
601073
  type: "run_failed",
600538
- runId: this._sessionId ?? "unknown",
601074
+ runId: this.currentArtifactRunId(),
600539
601075
  error: retryMsg,
600540
601076
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
600541
601077
  });
@@ -600559,7 +601095,7 @@ ${memoryLines.join("\n")}`
600559
601095
  });
600560
601096
  this._onTypedEvent?.({
600561
601097
  type: "run_failed",
600562
- runId: this._sessionId ?? "unknown",
601098
+ runId: this.currentArtifactRunId(),
600563
601099
  error: `Model not found: ${errMsg}`,
600564
601100
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
600565
601101
  });
@@ -600634,7 +601170,7 @@ ${memoryLines.join("\n")}`
600634
601170
  summary = String(parsed.args?.summary ?? content);
600635
601171
  this._onTypedEvent?.({
600636
601172
  type: "completion_requested",
600637
- runId: this._sessionId ?? "unknown",
601173
+ runId: this.currentArtifactRunId(),
600638
601174
  summary: summary.slice(0, 500),
600639
601175
  sourcePath: this.options.streamEnabled ? "stream" : "batch",
600640
601176
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -600657,7 +601193,7 @@ ${memoryLines.join("\n")}`
600657
601193
  });
600658
601194
  this._onTypedEvent?.({
600659
601195
  type: "run_failed",
600660
- runId: this._sessionId ?? "unknown",
601196
+ runId: this.currentArtifactRunId(),
600661
601197
  error: msg2,
600662
601198
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
600663
601199
  });
@@ -600672,7 +601208,7 @@ ${memoryLines.join("\n")}`
600672
601208
  });
600673
601209
  this._onTypedEvent?.({
600674
601210
  type: "run_failed",
600675
- runId: this._sessionId ?? "unknown",
601211
+ runId: this.currentArtifactRunId(),
600676
601212
  error: `Backend unavailable: ${errMsg}`,
600677
601213
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
600678
601214
  });
@@ -600682,10 +601218,10 @@ ${memoryLines.join("\n")}`
600682
601218
  response = recovered ?? response;
600683
601219
  }
600684
601220
  }
600685
- totalTokens += response.usage?.totalTokens ?? 0;
600686
- promptTokens += response.usage?.promptTokens ?? 0;
601221
+ totalTokens += response.usage?.totalTokens || (response.usage?.promptEvalCount ?? response.usage?.promptTokens ?? 0) + (response.usage?.completionTokens ?? 0);
601222
+ promptTokens += response.usage?.promptEvalCount ?? response.usage?.promptTokens ?? 0;
600687
601223
  completionTokens += response.usage?.completionTokens ?? 0;
600688
- const turnPromptTokens = response.usage?.promptTokens ?? 0;
601224
+ const turnPromptTokens = response.usage?.promptEvalCount ?? response.usage?.promptTokens ?? 0;
600689
601225
  const turnCompletionTokens = response.usage?.completionTokens ?? 0;
600690
601226
  if (turnPromptTokens || turnCompletionTokens) {
600691
601227
  recordTokenUsage(this._appState, turnPromptTokens, turnCompletionTokens, 0, false);
@@ -600903,8 +601439,19 @@ ${memoryLines.join("\n")}`
600903
601439
  reservations: /* @__PURE__ */ new Map()
600904
601440
  };
600905
601441
  executeSingle = async (tc) => {
600906
- if (this.aborted)
601442
+ if (this.aborted || this._pendingSteeringPreemption)
600907
601443
  return null;
601444
+ const resolvedReadBlock = this._rejectRepeatedResolvedRead(tc, messages2);
601445
+ if (resolvedReadBlock) {
601446
+ this.emit({
601447
+ type: "status",
601448
+ toolName: tc.name,
601449
+ content: "Repeated planned file_read rejected until evidence scope changes.",
601450
+ turn,
601451
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
601452
+ });
601453
+ return { tc, output: resolvedReadBlock, success: true };
601454
+ }
600908
601455
  const cohortKey = this.buildArgCohortKey(tc.name, tc.arguments);
600909
601456
  const cohort = this._argCohorts.get(cohortKey);
600910
601457
  if (cohort && cohort.failure >= 3 && cohort.success === 0) {
@@ -600948,10 +601495,7 @@ Corrective action: try a different approach first: read relevant files, adjust a
600948
601495
  const pattern = rawPattern;
600949
601496
  if (pattern.tool === tc.name && (pattern.count ?? 0) >= 2 && !currentRunToolAlreadySucceeded && !this._errorGuidanceInjected.has(sig)) {
600950
601497
  this._errorGuidanceInjected.add(sig);
600951
- messages2.push({
600952
- role: "system",
600953
- content: `[LEARNED FROM EXPERIENCE] ${tc.name} has failed ${pattern.count} times with "${pattern.errorType}" errors. Guidance: ${pattern.guidance}`
600954
- });
601498
+ void pattern;
600955
601499
  }
600956
601500
  }
600957
601501
  }
@@ -601166,7 +601710,7 @@ Corrective action: try a different approach first: read relevant files, adjust a
601166
601710
  ``,
601167
601711
  _localFailureNudge
601168
601712
  ].join("\n");
601169
- pushSoftInjection("system", reg61SteerMsg);
601713
+ void reg61SteerMsg;
601170
601714
  this.emit({
601171
601715
  type: "status",
601172
601716
  content: `REG-61 STEER — nudge injected for '${tc.name}' at turn ${turn}; tool ALLOWED; gate stays active${_dbgLoop.detected ? `; REG-66 debug-loop variant (${_dbgLoop.kind} "${_debugLoopSampleSafe.slice(0, 60)}" ${_dbgLoop.count}×)` : ""}`,
@@ -601509,11 +602053,8 @@ Read the current file if needed, make a different concrete edit, or move to veri
601509
602053
  ].join("\n");
601510
602054
  }
601511
602055
  }
601512
- if (_isEscalation) {
601513
- messages2.push({ role: "system", content: _reflBody });
601514
- } else {
601515
- pushSoftInjection("system", _reflBody);
601516
- }
602056
+ void _isEscalation;
602057
+ void _reflBody;
601517
602058
  this.emit({
601518
602059
  type: "status",
601519
602060
  content: `REG-26 reflection surfaced for stem '${_reflStem.slice(0, 60)}' (attempts=${_reflEntry.attempts}, distinct_errors=${_reflEntry.errorSignatures?.size ?? 0}, escalation=${_isEscalation})`,
@@ -601709,7 +602250,7 @@ ${cachedResult}`,
601709
602250
  });
601710
602251
  if (focusDecision.kind === "block_tool_call" && this._maybeAutoDelegate(tc, focusDecision.directive, messages2, turn)) {
601711
602252
  } else if (focusDecision.kind === "inject_guidance") {
601712
- pushSoftInjection("system", focusDecision.message);
602253
+ void focusDecision.message;
601713
602254
  } else if (!repeatShortCircuit) {
601714
602255
  repeatShortCircuit = {
601715
602256
  success: focusDecision.success,
@@ -601920,30 +602461,70 @@ ${cachedResult}`,
601920
602461
  const currentRead = this._fileReadDiskIdentity(tc.arguments);
601921
602462
  if (currentRead && currentRead.contentHash === priorRead.contentHash) {
601922
602463
  exactFileReadObservations.set(exactReadKey, currentRead);
601923
- const duplicateOutput = [
601924
- `[DUPLICATE_READ_BLOCKED] path=${currentRead.path} sha256=${currentRead.contentHash}`,
601925
- `The exact file_read arguments already produced evidence from this unchanged source during the current run. The tool was not re-executed and the raw body was not re-injected.`,
601926
- `Use the existing evidence/anchors now. To discover something different, issue one narrower offset/limit or grep_search with a new symbol; otherwise take the next mutation, verification, or completion action.`
601927
- ].join("\n");
601928
- branchPreempted = {
601929
- success: true,
601930
- output: duplicateOutput,
601931
- llmContent: duplicateOutput,
601932
- beforeHash: currentRead.contentHash,
601933
- runtimeAuthored: true,
601934
- noop: true,
601935
- completionEvidenceMetrics: {
601936
- duplicateReadBlocked: true,
601937
- duplicateReadSourceBytes: currentRead.byteCount
602464
+ const canonicalPayload = this._canonicalReadEvidencePayload(currentRead.canonicalPath, currentRead.contentHash);
602465
+ if (canonicalPayload) {
602466
+ const rehydrated = this._rehydrateResolvedReadEvidence({
602467
+ fingerprint: exactReadKey,
602468
+ canonicalPath: currentRead.canonicalPath,
602469
+ contentHash: currentRead.contentHash,
602470
+ payload: canonicalPayload,
602471
+ turn
602472
+ });
602473
+ branchPreempted = {
602474
+ success: true,
602475
+ output: rehydrated,
602476
+ llmContent: rehydrated,
602477
+ beforeHash: currentRead.contentHash,
602478
+ runtimeAuthored: true,
602479
+ noop: true,
602480
+ completionEvidenceMetrics: {
602481
+ duplicateReadResolvedFromCache: true,
602482
+ duplicateReadSourceBytes: currentRead.byteCount,
602483
+ fingerprintState: "resolved_from_cache"
602484
+ }
602485
+ };
602486
+ this.emit({
602487
+ type: "status",
602488
+ toolName: normalizedDispatchName,
602489
+ content: `Exact unchanged file_read rehydrated: ${currentRead.path} sha256=${currentRead.contentHash.slice(0, 12)} fingerprint_state=resolved_from_cache`,
602490
+ turn,
602491
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
602492
+ });
602493
+ } else {
602494
+ if (this._deterministicNarrowReadFallbacks.has(exactReadKey)) {
602495
+ const fallbackBlocked = [
602496
+ "[REPEATED_NARROW_READ_REJECTED]",
602497
+ `path=${currentRead.path}`,
602498
+ "No canonical payload was produced by the allowed narrow reread. Change scope with a new range or symbol query; do not repeat identical arguments."
602499
+ ].join("\n");
602500
+ branchPreempted = {
602501
+ success: true,
602502
+ output: fallbackBlocked,
602503
+ llmContent: fallbackBlocked,
602504
+ beforeHash: currentRead.contentHash,
602505
+ runtimeAuthored: true,
602506
+ noop: true
602507
+ };
602508
+ } else {
602509
+ this._deterministicNarrowReadFallbacks.add(exactReadKey);
602510
+ const previousOffset = tc.arguments["offset"];
602511
+ const previousLimit = tc.arguments["limit"];
602512
+ Object.assign(finalArgs, {
602513
+ offset: typeof previousOffset === "number" && Number.isFinite(previousOffset) ? Math.max(1, Math.floor(previousOffset)) : 1,
602514
+ limit: typeof previousLimit === "number" && Number.isFinite(previousLimit) ? Math.max(1, Math.min(160, Math.floor(previousLimit))) : 160
602515
+ });
602516
+ tc.arguments = finalArgs;
602517
+ this._deterministicNarrowReadFallbacks.add(this._buildToolFingerprint("file_read", tc.arguments));
602518
+ exactFileReadObservations.delete(exactReadKey);
602519
+ this.emit({
602520
+ type: "status",
602521
+ toolName: normalizedDispatchName,
602522
+ content: `Exact read cache lacked canonical payload; allowing one deterministic narrow reread: ${currentRead.path} offset=${tc.arguments["offset"]} limit=${tc.arguments["limit"]}`,
602523
+ turn,
602524
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
602525
+ });
601938
602526
  }
601939
- };
601940
- this.emit({
601941
- type: "status",
601942
- toolName: normalizedDispatchName,
601943
- content: `Exact unchanged file_read blocked before dispatch: ${currentRead.path} sha256=${currentRead.contentHash.slice(0, 12)}`,
601944
- turn,
601945
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
601946
- });
602527
+ }
601947
602528
  } else {
601948
602529
  exactFileReadObservations.delete(exactReadKey);
601949
602530
  }
@@ -602044,21 +602625,7 @@ ${cachedResult}`,
602044
602625
  });
602045
602626
  if (process.env["OMNIUS_DISABLE_REG59"] !== "1") {
602046
602627
  const _errCtx59 = this._buildErrorContextPreamble();
602047
- messages2.push({
602048
- role: "system",
602049
- content: `[STAGNATION REPLAN — REG-59 same-error escalation]
602050
- The error cluster you keep hitting has occurred 5+ times. Your current approach is NOT working. STOP retrying it.
602051
- ` + _errCtx59 + `
602052
- Respond with EXACTLY this structure before your next tool call:
602053
- HYPOTHESES (3 NEW theories — must be DIFFERENT from anything tried so far):
602054
- 1. ...
602055
- 2. ...
602056
- 3. ...
602057
- PICK: <number 1-3>
602058
- WHY: <one sentence — what makes this hypothesis NEW>
602059
- FALSIFICATION: <observable signal that would refute the pick>
602060
- NEXT ACTION: <single tool call that tests the picked hypothesis — preferably a creative edit, not a read>`
602061
- });
602628
+ void _errCtx59;
602062
602629
  stagnationCooldownUntilTurn = turn + 8;
602063
602630
  const _tel59 = this._describeTopClusterTelemetry();
602064
602631
  const _telSuffix59 = _tel59 ? `; rca3_preamble=applied; top_cluster=${_tel59.code} (${_tel59.observations}×); has_hint=${_tel59.hasHint}` : `; rca3_preamble=none`;
@@ -602119,6 +602686,7 @@ Respond with EXACTLY this structure before your next tool call:
602119
602686
  args: tc.arguments,
602120
602687
  result
602121
602688
  });
602689
+ this._reconcileCreationGroundTruth(resolvedTool?.name ?? tc.name, tc.arguments, result, turn);
602122
602690
  if (observedStateMutation) {
602123
602691
  this._markAdversaryObservedStateMutation();
602124
602692
  }
@@ -602209,7 +602777,7 @@ Respond with EXACTLY this structure before your next tool call:
602209
602777
  writeCount: prev?.writeCount
602210
602778
  });
602211
602779
  }
602212
- if (p2 && result.success && result.output) {
602780
+ if (p2 && result.success && result.output && !(result.runtimeAuthored === true && result.noop === true)) {
602213
602781
  const rOffset = typeof tc.arguments?.["offset"] === "number" ? tc.arguments["offset"] : void 0;
602214
602782
  const rLimit = typeof tc.arguments?.["limit"] === "number" ? tc.arguments["limit"] : void 0;
602215
602783
  const start3 = rOffset === void 0 && rLimit === void 0 ? 0 : Math.max(1, rOffset ?? 1);
@@ -603080,7 +603648,7 @@ Respond with EXACTLY this structure before your next tool call:
603080
603648
  ``,
603081
603649
  this._renderLocalFailureNudge(turn)
603082
603650
  ].join("\n");
603083
- pushSoftInjection("system", opaqueMessage);
603651
+ void opaqueMessage;
603084
603652
  this.emit({
603085
603653
  type: "status",
603086
603654
  content: `REG-32 opaque-error local nudge fired for stem '${_refStem.slice(0, 60)}'`,
@@ -603537,7 +604105,7 @@ ${delegateDir}` : delegateDir;
603537
604105
  recordDebugToolEvent({
603538
604106
  cwd: this.authoritativeWorkingDirectory(),
603539
604107
  stateDir: this.omniusStateDir(),
603540
- runId: this._sessionId,
604108
+ runId: this.currentArtifactRunId(),
603541
604109
  sessionId: this._sessionId,
603542
604110
  turn,
603543
604111
  toolCallId: tc.id,
@@ -603748,8 +604316,7 @@ Then use file_read on individual FILES inside it.`);
603748
604316
  createdTurn: turn,
603749
604317
  ttlTurns: 4
603750
604318
  });
603751
- if (signal)
603752
- this._contextLedger.upsert(signal);
604319
+ void signal;
603753
604320
  lastShellPivotTurn = turn;
603754
604321
  this.emit({
603755
604322
  type: "status",
@@ -603758,7 +604325,7 @@ Then use file_read on individual FILES inside it.`);
603758
604325
  });
603759
604326
  }
603760
604327
  }
603761
- if (process.env["OMNIUS_DISABLE_FAILURE_HANDOFF"] !== "1" && !result.success && turn - lastFailureHandoffTurn >= 4) {
604328
+ if (false) {
603762
604329
  const runtimeHandoff = buildFailureModeHandoff({
603763
604330
  taskGoal: persistentTaskGoal,
603764
604331
  errorPatterns: this._taskRelevantErrorPatterns,
@@ -603775,8 +604342,7 @@ Then use file_read on individual FILES inside it.`);
603775
604342
  createdTurn: turn,
603776
604343
  ttlTurns: 4
603777
604344
  });
603778
- if (signal)
603779
- this._contextLedger.upsert(signal);
604345
+ void signal;
603780
604346
  lastFailureHandoffTurn = turn;
603781
604347
  }
603782
604348
  }
@@ -603791,7 +604357,7 @@ Then use file_read on individual FILES inside it.`);
603791
604357
  });
603792
604358
  this._onTypedEvent?.({
603793
604359
  type: "tool_call_finished",
603794
- runId: this._sessionId ?? "unknown",
604360
+ runId: this.currentArtifactRunId(),
603795
604361
  toolName: tc.name,
603796
604362
  callId: tc.id,
603797
604363
  success: result.success === true,
@@ -603803,8 +604369,7 @@ Then use file_read on individual FILES inside it.`);
603803
604369
  return {
603804
604370
  tc,
603805
604371
  output,
603806
- success: result.success,
603807
- ...runtimeSystemGuidance ? { systemGuidance: runtimeSystemGuidance } : {}
604372
+ success: result.success
603808
604373
  };
603809
604374
  };
603810
604375
  const rawToolCalls = msg.toolCalls;
@@ -603903,7 +604468,7 @@ ${sr.result.output}`;
603903
604468
  summary = extractTaskCompleteSummary(taskCompleteArgs);
603904
604469
  this._onTypedEvent?.({
603905
604470
  type: "completion_requested",
603906
- runId: this._sessionId ?? "unknown",
604471
+ runId: this.currentArtifactRunId(),
603907
604472
  summary: (summary ?? "").slice(0, 500),
603908
604473
  sourcePath: this.options.streamEnabled ? "stream" : "batch",
603909
604474
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -603926,17 +604491,12 @@ ${sr.result.output}`;
603926
604491
  if (!completed && !this._completionIncompleteVerification) {
603927
604492
  const unhandled = rawToolCalls.filter((tc) => !handledIds.has(tc.id));
603928
604493
  for (const tc of unhandled) {
603929
- if (this.aborted)
604494
+ if (this.aborted || this._pendingSteeringPreemption)
603930
604495
  break;
603931
604496
  const r2 = await executeSingle(tc);
603932
604497
  if (r2) {
603933
604498
  messages2.push(this.buildModelFacingToolMessage(r2.output, r2.tc.id, r2.tc.name, r2.tc.arguments, r2.success));
603934
- if (r2.systemGuidance) {
603935
- messages2.push({
603936
- role: "system",
603937
- content: r2.systemGuidance
603938
- });
603939
- }
604499
+ void r2.systemGuidance;
603940
604500
  if (r2.tc.name === "task_complete") {
603941
604501
  if (!r2.success) {
603942
604502
  messages2.push({
@@ -603978,7 +604538,7 @@ ${sr.result.output}`;
603978
604538
  summary = extractTaskCompleteSummary(taskCompleteArgs);
603979
604539
  this._onTypedEvent?.({
603980
604540
  type: "completion_requested",
603981
- runId: this._sessionId ?? "unknown",
604541
+ runId: this.currentArtifactRunId(),
603982
604542
  summary: (summary ?? "").slice(0, 500),
603983
604543
  sourcePath: this.options.streamEnabled ? "stream" : "batch",
603984
604544
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -604008,7 +604568,7 @@ ${sr.result.output}`;
604008
604568
  }));
604009
604569
  const batches = partitionToolCalls(batchToolCalls);
604010
604570
  for (const batch2 of batches) {
604011
- if (this.aborted)
604571
+ if (this.aborted || this._pendingSteeringPreemption)
604012
604572
  break;
604013
604573
  const batchFingerprintFirstId = /* @__PURE__ */ new Map();
604014
604574
  const batchInFlight = /* @__PURE__ */ new Map();
@@ -604045,12 +604605,7 @@ ${sr.result.output}`;
604045
604605
  for (const r2 of results) {
604046
604606
  if (r2) {
604047
604607
  messages2.push(this.buildModelFacingToolMessage(r2.output, r2.tc.id, r2.tc.name, r2.tc.arguments, r2.success));
604048
- if (r2.systemGuidance) {
604049
- messages2.push({
604050
- role: "system",
604051
- content: r2.systemGuidance
604052
- });
604053
- }
604608
+ void r2.systemGuidance;
604054
604609
  if (r2.tc.name === "task_complete") {
604055
604610
  if (!r2.success) {
604056
604611
  messages2.push({
@@ -604092,7 +604647,7 @@ ${sr.result.output}`;
604092
604647
  summary = extractTaskCompleteSummary(taskCompleteArgs);
604093
604648
  this._onTypedEvent?.({
604094
604649
  type: "completion_requested",
604095
- runId: this._sessionId ?? "unknown",
604650
+ runId: this.currentArtifactRunId(),
604096
604651
  summary: (summary ?? "").slice(0, 500),
604097
604652
  sourcePath: this.options.streamEnabled ? "stream" : "batch",
604098
604653
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -604141,21 +604696,7 @@ ${sr.result.output}`;
604141
604696
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
604142
604697
  });
604143
604698
  const partialResults = this._taskState.completedSteps.length > 0 ? this._taskState.completedSteps.join(". ") : `Progress made before loop: ${topRepeated}`;
604144
- messages2.push({
604145
- role: "system",
604146
- content: `LOOP CIRCUIT BREAKER: ${loopInterventionCount} interventions attempted but repetition continues.
604147
-
604148
- MANDATORY: Change state before taking another action. Choose one:
604149
- 1. Try a completely different approach
604150
- 2. Re-read the exact current target once if the loop is caused by a stale edit
604151
- 3. Run verification if files changed since the last successful check
604152
- 4. Call ask_user if user input is the real blocker
604153
- 5. Report blocked/incomplete with the concrete blocker if no safe progress path remains
604154
-
604155
- Your partial progress: ${partialResults}
604156
-
604157
- Do not call task_complete solely because this circuit breaker fired.`
604158
- });
604699
+ void partialResults;
604159
604700
  loopInterventionCount = 0;
604160
604701
  }
604161
604702
  const findings = [];
@@ -604253,10 +604794,7 @@ Only call task_complete when the task is actually complete and the evidence is f
604253
604794
  callable: _smaCallable
604254
604795
  }).then((_smaResult) => {
604255
604796
  if (_smaResult.injection && !_smaResult.directive.parseFallback) {
604256
- messages2.push({
604257
- role: "system",
604258
- content: _smaResult.injection
604259
- });
604797
+ void _smaResult.injection;
604260
604798
  this.emit({
604261
604799
  type: "status",
604262
604800
  content: `REG-49 stuck-meta-analyzer fired (loop-intervention path) at turn ${turn} — diagnosis="${_smaResult.directive.diagnosis.slice(0, 80)}", next=${_smaResult.directive.next_action.tool}, ${_smaResult.durationMs}ms`,
@@ -604321,7 +604859,7 @@ Only call task_complete when the task is actually complete and the evidence is f
604321
604859
  summary = content;
604322
604860
  this._onTypedEvent?.({
604323
604861
  type: "completion_requested",
604324
- runId: this._sessionId ?? "unknown",
604862
+ runId: this.currentArtifactRunId(),
604325
604863
  summary: content.slice(0, 500),
604326
604864
  sourcePath: this.options.streamEnabled ? "stream" : "batch",
604327
604865
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -604570,7 +605108,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
604570
605108
  toolEvents: this._toolEvents,
604571
605109
  memoryHints: [],
604572
605110
  runState: {
604573
- runId: this._sessionId,
605111
+ runId: this.currentArtifactRunId(),
604574
605112
  tokenBudget: _limits.compactionThreshold,
604575
605113
  completionContract: this._completionContract ? formatCompletionContract(this._completionContract) : void 0
604576
605114
  }
@@ -604594,7 +605132,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
604594
605132
  });
604595
605133
  this._onTypedEvent?.({
604596
605134
  type: "run_failed",
604597
- runId: this._sessionId ?? "unknown",
605135
+ runId: this.currentArtifactRunId(),
604598
605136
  error: "Task aborted by user",
604599
605137
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
604600
605138
  });
@@ -604609,7 +605147,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
604609
605147
  });
604610
605148
  this._onTypedEvent?.({
604611
605149
  type: "run_failed",
604612
- runId: this._sessionId ?? "unknown",
605150
+ runId: this.currentArtifactRunId(),
604613
605151
  error: "Task aborted by user",
604614
605152
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
604615
605153
  });
@@ -604666,6 +605204,11 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
604666
605204
  const bfEchoBoostedTemp = this._echoTempBoostTurns > 0 ? Math.max(this.options.temperature ?? 0, 0.7) : this.options.temperature;
604667
605205
  if (this._echoTempBoostTurns > 0)
604668
605206
  this._echoTempBoostTurns--;
605207
+ this._stripLegacyControlMessages(modelFacingMessages);
605208
+ modelFacingMessages.push({
605209
+ role: "system",
605210
+ content: this._buildRecentActionGroundTruth(turn)
605211
+ });
604669
605212
  const chatRequest = {
604670
605213
  messages: modelFacingMessages,
604671
605214
  tools: toolDefs,
@@ -604687,7 +605230,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
604687
605230
  });
604688
605231
  this._onTypedEvent?.({
604689
605232
  type: "run_failed",
604690
- runId: this._sessionId ?? "unknown",
605233
+ runId: this.currentArtifactRunId(),
604691
605234
  error: "Task aborted by user",
604692
605235
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
604693
605236
  });
@@ -604706,7 +605249,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
604706
605249
  });
604707
605250
  this._onTypedEvent?.({
604708
605251
  type: "run_failed",
604709
- runId: this._sessionId ?? "unknown",
605252
+ runId: this.currentArtifactRunId(),
604710
605253
  error: bfRetryMsg,
604711
605254
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
604712
605255
  });
@@ -604729,7 +605272,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
604729
605272
  });
604730
605273
  this._onTypedEvent?.({
604731
605274
  type: "run_failed",
604732
- runId: this._sessionId ?? "unknown",
605275
+ runId: this.currentArtifactRunId(),
604733
605276
  error: errMsg2,
604734
605277
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
604735
605278
  });
@@ -604738,10 +605281,10 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
604738
605281
  response = recovered;
604739
605282
  }
604740
605283
  }
604741
- totalTokens += response.usage?.totalTokens ?? 0;
604742
- promptTokens += response.usage?.promptTokens ?? 0;
605284
+ totalTokens += response.usage?.totalTokens || (response.usage?.promptEvalCount ?? response.usage?.promptTokens ?? 0) + (response.usage?.completionTokens ?? 0);
605285
+ promptTokens += response.usage?.promptEvalCount ?? response.usage?.promptTokens ?? 0;
604743
605286
  completionTokens += response.usage?.completionTokens ?? 0;
604744
- const bfTurnPrompt = response.usage?.promptTokens ?? 0;
605287
+ const bfTurnPrompt = response.usage?.promptEvalCount ?? response.usage?.promptTokens ?? 0;
604745
605288
  const bfTurnCompletion = response.usage?.completionTokens ?? 0;
604746
605289
  if (bfTurnPrompt || bfTurnCompletion) {
604747
605290
  recordTokenUsage(this._appState, bfTurnPrompt, bfTurnCompletion, 0, false);
@@ -604824,12 +605367,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
604824
605367
  messages2.push(this.buildModelFacingToolMessage(r2.output, r2.tc.id, r2.tc.name, r2.tc.arguments, r2.success));
604825
605368
  this._toolLastUsedTurn.set(r2.tc.name, turn);
604826
605369
  this._advanceContextTreeOnToolCall(r2.tc.name, this._buildExactArgsKey(r2.tc.arguments ?? {}), turn, messages2);
604827
- if (r2.systemGuidance) {
604828
- messages2.push({
604829
- role: "system",
604830
- content: r2.systemGuidance
604831
- });
604832
- }
605370
+ void r2.systemGuidance;
604833
605371
  if (r2.tc.name === "task_complete") {
604834
605372
  if (!r2.success) {
604835
605373
  messages2.push({
@@ -604871,7 +605409,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
604871
605409
  summary = extractTaskCompleteSummary(taskCompleteArgs);
604872
605410
  this._onTypedEvent?.({
604873
605411
  type: "completion_requested",
604874
- runId: this._sessionId ?? "unknown",
605412
+ runId: this.currentArtifactRunId(),
604875
605413
  summary: (summary ?? "").slice(0, 500),
604876
605414
  sourcePath: this.options.streamEnabled ? "stream" : "batch",
604877
605415
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -604929,7 +605467,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
604929
605467
  summary = content;
604930
605468
  this._onTypedEvent?.({
604931
605469
  type: "completion_requested",
604932
- runId: this._sessionId ?? "unknown",
605470
+ runId: this.currentArtifactRunId(),
604933
605471
  summary: content.slice(0, 500),
604934
605472
  sourcePath: this.options.streamEnabled ? "stream" : "batch",
604935
605473
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -605024,7 +605562,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
605024
605562
  });
605025
605563
  this._onTypedEvent?.({
605026
605564
  type: "completion_requested",
605027
- runId: this._sessionId ?? "unknown",
605565
+ runId: this.currentArtifactRunId(),
605028
605566
  summary: summary.slice(0, 500),
605029
605567
  sourcePath: "direct",
605030
605568
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -605081,7 +605619,7 @@ ${caveat}` : caveat;
605081
605619
  });
605082
605620
  this._onTypedEvent?.({
605083
605621
  type: "run_finished",
605084
- runId: this._sessionId ?? "unknown",
605622
+ runId: this.currentArtifactRunId(),
605085
605623
  status: runStatus,
605086
605624
  success: completed,
605087
605625
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
@@ -605769,7 +606307,8 @@ ${caveat}` : caveat;
605769
606307
  const trajDir = path16.join(this.omniusStateDir(), "trajectories");
605770
606308
  fs14.mkdirSync(trajDir, { recursive: true });
605771
606309
  const trajectory = {
605772
- id: this._sessionId,
606310
+ id: this.currentArtifactRunId(),
606311
+ sessionId: this._sessionId,
605773
606312
  // CLEAN task — this file is the prerequisite for ALL future RL/RFT
605774
606313
  // training. Storing the scaffolded version would teach future models
605775
606314
  // to reproduce signpost text as part of their task understanding.
@@ -606002,7 +606541,7 @@ ${marker}` : marker);
606002
606541
  ].filter(Boolean).join("\n"));
606003
606542
  }
606004
606543
  shouldBypassDiscoveryCompaction(output) {
606005
- return output.includes("[IMAGE_BASE64:") || output.includes("[BRANCH-EXTRACT]") || output.includes("[REPEAT GATE - cached evidence not re-sent]") || output.includes("[CACHED READ — content unchanged") || output.includes("[REHYDRATED FROM CACHE") || output.includes("[Tool output truncated") || output.includes(TRIAGE_ENVELOPE_MARKER);
606544
+ return output.includes("[IMAGE_BASE64:") || output.includes("[BRANCH-EXTRACT]") || output.includes("[REPEAT GATE - cached evidence not re-sent]") || output.includes("[REPEATED_READ_REJECTED]") || output.includes("[REPEATED_NARROW_READ_REJECTED]") || output.includes("[CACHED READ — content unchanged") || output.includes("[REHYDRATED FROM CACHE") || output.includes("[Tool output truncated") || output.includes(TRIAGE_ENVELOPE_MARKER);
606006
606545
  }
606007
606546
  countTextLines(text2) {
606008
606547
  if (!text2)
@@ -607616,8 +608155,7 @@ ${tail}`;
607616
608155
  createdTurn: turn,
607617
608156
  ttlTurns: 20
607618
608157
  });
607619
- if (signal)
607620
- this._contextLedger.upsert(signal);
608158
+ void signal;
607621
608159
  }
607622
608160
  this.emit({
607623
608161
  type: "user_interrupt",
@@ -608052,37 +608590,13 @@ Describe what you see and integrate this into your current approach.` : "[User s
608052
608590
  let middle = messages2.slice(headEndIdx, recentStart);
608053
608591
  if (middle.length === 0)
608054
608592
  return messages2;
608055
- const DEFENSE_DIRECTIVE_PREFIXES = [
608056
- "[STUCK DETECTOR HALT REG-44]",
608057
- "[STUCK-STATE META-ANALYZER REG-49]",
608058
- "[WRITE-THRASH HALT REG-50]",
608059
- "[PROBLEM-FRAME VALIDATION — REG-51",
608060
- "[EDIT-FAIL-THRASH HALT — REG-53]"
608061
- ];
608062
- const isDefenseDirective = (msg) => {
608063
- const c9 = typeof msg.content === "string" ? msg.content : "";
608064
- return msg.role === "system" && DEFENSE_DIRECTIVE_PREFIXES.some((pfx) => c9.startsWith(pfx));
608065
- };
608066
- const stickyDefenses = [];
608067
- const filteredMiddle = [];
608068
- for (const msg of middle) {
608069
- if (isDefenseDirective(msg))
608070
- stickyDefenses.push(msg);
608071
- else
608072
- filteredMiddle.push(msg);
608073
- }
608074
- const filteredRecent = [];
608075
- for (const msg of recent) {
608076
- if (isDefenseDirective(msg))
608077
- stickyDefenses.push(msg);
608078
- else
608079
- filteredRecent.push(msg);
608080
- }
608081
- const stickyToKeep = stickyDefenses.slice(-10);
608082
- if (stickyToKeep.length > 0) {
608593
+ const filteredMiddle = middle.filter((message2) => !this._isLegacyControlMessage(message2));
608594
+ const filteredRecent = recent.filter((message2) => !this._isLegacyControlMessage(message2));
608595
+ const retiredLegacyCount = middle.length + recent.length - filteredMiddle.length - filteredRecent.length;
608596
+ if (retiredLegacyCount > 0) {
608083
608597
  this.emit({
608084
608598
  type: "status",
608085
- content: `REG-54 sticky-defenses preserved ${stickyToKeep.length} directive(s) across compaction (out of ${stickyDefenses.length} matched)`,
608599
+ content: `Controller cleanup retired ${retiredLegacyCount} legacy REG/recovery message(s) during compaction`,
608086
608600
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
608087
608601
  });
608088
608602
  }
@@ -608350,7 +608864,6 @@ ${telegramPersonaHead}` : stripped
608350
608864
  let result = [
608351
608865
  ...narrowedHead,
608352
608866
  compactionMsg,
608353
- ...stickyToKeep,
608354
608867
  ...filteredRecent
608355
608868
  ];
608356
608869
  const fileRecoveryBudget = Math.floor((this._branchRoutingContextWindow() || 32768) * 0.15);
@@ -608450,10 +608963,9 @@ ${content.slice(0, 8e3)}${truncated ? "\n[truncated recovery; use a narrow live
608450
608963
  createdTurn: this._taskState.toolCallCount,
608451
608964
  ttlTurns: 8
608452
608965
  });
608453
- if (signal)
608454
- this._contextLedger.upsert(signal);
608966
+ void signal;
608455
608967
  }
608456
- if (process.env["OMNIUS_DISABLE_FAILURE_HANDOFF"] !== "1") {
608968
+ if (false) {
608457
608969
  try {
608458
608970
  const compactFailureHandoff = buildFailureModeHandoff({
608459
608971
  taskGoal: this._taskState.goal,
@@ -608470,8 +608982,7 @@ ${content.slice(0, 8e3)}${truncated ? "\n[truncated recovery; use a narrow live
608470
608982
  createdTurn: this._taskState.toolCallCount,
608471
608983
  ttlTurns: 8
608472
608984
  });
608473
- if (signal)
608474
- this._contextLedger.upsert(signal);
608985
+ void signal;
608475
608986
  }
608476
608987
  } catch {
608477
608988
  }
@@ -608513,7 +609024,6 @@ ${content.slice(0, 8e3)}${truncated ? "\n[truncated recovery; use a narrow live
608513
609024
  result = [
608514
609025
  ...narrowedHead,
608515
609026
  compactionMsg,
608516
- ...stickyToKeep,
608517
609027
  ...protectedRecoveryMessages,
608518
609028
  ...trimmedRecent
608519
609029
  ];
@@ -608578,6 +609088,8 @@ ${trimmedNew}`;
608578
609088
  * adversary buffer, this is populated directly after tool execution and does
608579
609089
  * not depend on raw tool messages surviving compaction. */
608580
609090
  _recentToolOutcomes = [];
609091
+ /** Recent successful user-work mutations suppress generic "create again" nudges. */
609092
+ _groundTruthSuccessPaths = /* @__PURE__ */ new Map();
608581
609093
  /** Monotonic counter for observed local state changes.
608582
609094
  * Redundant-action classification is only valid within the same state
608583
609095
  * version; a repeated verifier after an edit is fresh evidence. */
@@ -608704,10 +609216,124 @@ ${trimmedNew}`;
608704
609216
  succeeded: input.result.success === true,
608705
609217
  ...outcomeEvidence
608706
609218
  });
609219
+ if (input.result.success === true && this._isRealProjectMutation(input.toolName, input.result)) {
609220
+ for (const rawPath of this._extractToolTargetPaths(input.toolName, input.args ?? {}, input.result)) {
609221
+ const path16 = this._normalizeEvidencePath(rawPath);
609222
+ if (!path16 || path16.startsWith(".omnius/"))
609223
+ continue;
609224
+ this._groundTruthSuccessPaths.set(path16, { turn: input.turn });
609225
+ }
609226
+ this._reg61CooldownUntilTurn = Math.max(this._reg61CooldownUntilTurn, input.turn + 5);
609227
+ }
608707
609228
  while (this._recentToolOutcomes.length > 40) {
608708
609229
  this._recentToolOutcomes.shift();
608709
609230
  }
608710
609231
  }
609232
+ /**
609233
+ * The only late control block visible to a model. It is regenerated from
609234
+ * authoritative run state on each request; it never carries prompt history.
609235
+ * Large models receive state only. Small/medium models may receive one
609236
+ * bounded directive with an explicit expiry and exit condition.
609237
+ */
609238
+ _buildRecentActionGroundTruth(turn) {
609239
+ const activePaths = [...this._taskState.modifiedFiles.entries()].map(([rawPath, rawAction]) => ({
609240
+ path: this._normalizeEvidencePath(rawPath),
609241
+ rawAction
609242
+ })).filter((entry) => entry.path && !entry.path.startsWith(".omnius/")).slice(-5);
609243
+ const todos = this.readSessionTodos() ?? [];
609244
+ const todoCounts = todos.reduce((counts, todo) => {
609245
+ const status = String(todo.status ?? "pending");
609246
+ if (status === "completed")
609247
+ counts.completed++;
609248
+ else if (status === "blocked")
609249
+ counts.blocked++;
609250
+ else if (status === "in_progress")
609251
+ counts.inProgress++;
609252
+ else
609253
+ counts.pending++;
609254
+ return counts;
609255
+ }, { completed: 0, blocked: 0, inProgress: 0, pending: 0 });
609256
+ const activeLeaf = todos.find((todo) => ["in_progress", "pending", "open", "needs_changes"].includes(String(todo.status ?? "")));
609257
+ const verifier = this._worldFacts.lastTest;
609258
+ const verifierState = verifier?.summary ? `outcome=${verifier.passed ? "passed" : "failed"} turn=${verifier.turn ?? "?"}` : "outcome=not_recorded";
609259
+ const verifierRequired = this._compileFixLoop?.active === true && this._compileFixLoop.verifierDirtySinceTurn !== null;
609260
+ const intent = this._taskState.originalGoal || this._taskState.goal || this._taskState.currentStep || "unspecified";
609261
+ const lines = [
609262
+ "[CONTROLLER STATE v1]",
609263
+ `task_epoch=${this._taskEpoch} turn=${turn} state_version=${this._adversaryStateVersion}`,
609264
+ `user_intent=${intent.replace(/\s+/g, " ").slice(0, 700)}`,
609265
+ `active_leaf=${String(activeLeaf?.content ?? this._taskState.currentStep ?? this._taskState.nextAction ?? "none").replace(/\s+/g, " ").slice(0, 360)}`,
609266
+ `todo_counts=completed:${todoCounts.completed},in_progress:${todoCounts.inProgress},pending:${todoCounts.pending},blocked:${todoCounts.blocked}`,
609267
+ `verifier=${verifierState}`
609268
+ ];
609269
+ const tier = this.options.modelTier ?? "large";
609270
+ const directive = this._focusSupervisor?.snapshot().directive;
609271
+ if (directive && tier !== "large") {
609272
+ const expiresTurn = Math.max(turn + 1, directive.createdTurn + 6);
609273
+ lines.push(`active_directive=next_action:${directive.requiredNextAction}; evidence:${directive.reason.replace(/\s+/g, " ").slice(0, 260)}; expires_turn:${expiresTurn}; exit_when:action_evidence_or_verified_mutation_or_user_redirect`);
609274
+ }
609275
+ for (const entry of activePaths) {
609276
+ const action = /creat/i.test(entry.rawAction) ? "created" : /delet/i.test(entry.rawAction) ? "deleted" : "modified";
609277
+ const evidence = this._evidenceLedger.get(entry.path);
609278
+ const fact = this._worldFacts.files.get(entry.path);
609279
+ const outcome = [...this._recentToolOutcomes].reverse().find((item) => item.path && this._normalizeEvidencePath(item.path) === entry.path);
609280
+ const resultState = outcome ? outcome.succeeded ? "tool_result=success" : "tool_result=failure" : "tool_result=not_recorded";
609281
+ const hash = evidence?.contentHash ?? "unknown";
609282
+ const bytes = fact && typeof fact.size === "number" ? String(fact.size) : "unknown";
609283
+ const nextAction = verifierRequired ? "run_declared_verifier" : outcome?.succeeded ? "verify_or_complete_distinct_leaf" : "inspect_external_blocker_or_change_scope";
609284
+ const doNot = action === "created" ? "do_not_create_again" : action === "modified" ? "do_not_full_rewrite_without_fresh_read" : "do_not_recreate_without_authoritative_target";
609285
+ lines.push(`${action} path=${entry.path} hash=${hash} bytes=${bytes} ${resultState} stateVersion=${outcome?.stateVersion ?? this._adversaryStateVersion} turn=${outcome?.turn ?? turn} next_valid_action=${nextAction} ${doNot}`);
609286
+ }
609287
+ lines.push("action_ground_truth=tool-derived only; controller artifacts and bookkeeping do not count as progress");
609288
+ return lines.join("\n").slice(0, 4200);
609289
+ }
609290
+ /** Legacy REG/recovery prose is retained in telemetry only, never in model history. */
609291
+ _isLegacyControlMessage(message2) {
609292
+ if (message2.role !== "system" || typeof message2.content !== "string")
609293
+ return false;
609294
+ return /^(?:\[(?:FIRST-EDIT NUDGE|STAGNATION(?: REPLAN| RECIPE)|STUCK DETECTOR HALT|STUCK-STATE META-ANALYZER|WRITE-THRASH HALT|EDIT-FAIL-THRASH HALT|PROBLEM-FRAME VALIDATION|STICKY ESCALATION|INTRA-RUN LESSON|LEARNED FROM EXPERIENCE|FOCUS SUPERVISOR|REG-\d+ directive active|OPAQUE LOCAL ERROR|LOCAL ERROR-INFORMED NUDGE|PRIOR LESSONS|FAILURE-MODE INTAKE|REFLECTION|Associative Memory)|LOOP CIRCUIT BREAKER)/.test(message2.content);
609295
+ }
609296
+ _stripLegacyControlMessages(messages2) {
609297
+ for (let index = messages2.length - 1; index >= 0; index--) {
609298
+ if (this._isLegacyControlMessage(messages2[index]))
609299
+ messages2.splice(index, 1);
609300
+ }
609301
+ }
609302
+ /** Mark a workboard target complete when a confirmed creation satisfies it. */
609303
+ _reconcileCreationGroundTruth(toolName, args, result, turn) {
609304
+ if (result.success !== true || !this._isRealProjectMutation(toolName, result)) {
609305
+ return;
609306
+ }
609307
+ const created = this._extractToolTargetPaths(toolName, args, result).map((path16) => this._normalizeEvidencePath(path16)).filter((path16) => path16 && !path16.startsWith(".omnius/") && /creat/i.test(this._taskState.modifiedFiles.get(path16) ?? ""));
609308
+ if (created.length === 0)
609309
+ return;
609310
+ const board = this._workboard ?? this.getOrCreateWorkboard();
609311
+ if (board) {
609312
+ const card = this._workboardTodoCardForPaths(board, created);
609313
+ if (card && (card.status === "open" || card.status === "in_progress" || card.status === "needs_changes")) {
609314
+ try {
609315
+ const completed = completeWorkboardCard(this._workboardDir(), {
609316
+ runId: this.currentArtifactRunId(),
609317
+ cardId: card.id,
609318
+ actor: this.options.subAgent ? "sub-agent" : "agent",
609319
+ outcome: "completed",
609320
+ reason: `Creation ground truth satisfied mapped target(s): ${created.join(", ")} at turn ${turn}.`
609321
+ });
609322
+ this._workboard = completed.snapshot;
609323
+ } catch {
609324
+ }
609325
+ }
609326
+ }
609327
+ for (const todo of this.readSessionTodos() ?? []) {
609328
+ const artifacts = Array.isArray(todo.declaredArtifacts) ? todo.declaredArtifacts.filter((path16) => typeof path16 === "string").map((path16) => this._normalizeEvidencePath(path16)) : [];
609329
+ if (todo.status !== "completed" && artifacts.length > 0 && artifacts.every((path16) => created.includes(path16))) {
609330
+ const marker = `created target evidence: ${todo.content}`;
609331
+ if (!this._taskState.completedSteps.includes(marker)) {
609332
+ this._taskState.completedSteps.push(marker);
609333
+ }
609334
+ }
609335
+ }
609336
+ }
608711
609337
  _recentToolActionsForWorldState() {
608712
609338
  if (this._recentToolOutcomes.length > 0)
608713
609339
  return this._recentToolOutcomes;
@@ -610462,7 +611088,7 @@ ${result}`
610462
611088
  stage: "vision_image_recovery",
610463
611089
  agentType: "internal",
610464
611090
  sessionId: this._sessionId,
610465
- runId: this._sessionId,
611091
+ runId: this._activeRunId || this._sessionId,
610466
611092
  turn,
610467
611093
  attempt: 0,
610468
611094
  model,
@@ -610490,7 +611116,7 @@ ${result}`
610490
611116
  stage: "vision_image_recovery",
610491
611117
  agentType: "internal",
610492
611118
  sessionId: this._sessionId,
610493
- runId: this._sessionId,
611119
+ runId: this._activeRunId || this._sessionId,
610494
611120
  turn,
610495
611121
  attempt: 1,
610496
611122
  model,
@@ -610570,7 +611196,7 @@ ${description}`
610570
611196
  * Returns the response on success, or null if recovery did not apply.
610571
611197
  */
610572
611198
  async retryOnTransient(initialErr, chatRequest, turn) {
610573
- if (this.aborted)
611199
+ if (this.aborted || this._pendingSteeringPreemption)
610574
611200
  return null;
610575
611201
  if (!this.isTransientError(initialErr))
610576
611202
  return null;
@@ -610584,7 +611210,7 @@ ${description}`
610584
611210
  const backend = this.backend;
610585
611211
  let attempt = 1;
610586
611212
  while (attempt <= (maxRetries === Infinity ? Number.MAX_SAFE_INTEGER : maxRetries)) {
610587
- if (this.aborted)
611213
+ if (this.aborted || this._pendingSteeringPreemption)
610588
611214
  return null;
610589
611215
  if (this.isPaymentRequiredError(initialErr) && typeof backend.rotateKey === "function") {
610590
611216
  const rotated = backend.rotateKey();
@@ -610651,7 +611277,7 @@ ${description}`
610651
611277
  });
610652
611278
  }
610653
611279
  await new Promise((r2) => setTimeout(r2, effectiveDelay));
610654
- if (this.aborted)
611280
+ if (this.aborted || this._pendingSteeringPreemption)
610655
611281
  return null;
610656
611282
  try {
610657
611283
  this._recordContextWindowDump("agent_turn_transient_retry", chatRequest, turn, attempt);
@@ -610719,7 +611345,7 @@ ${description}`
610719
611345
  }
610720
611346
  }
610721
611347
  for await (const chunk of backend.chatCompletionStream(request)) {
610722
- if (this.aborted)
611348
+ if (this.aborted || this._pendingSteeringPreemption)
610723
611349
  break;
610724
611350
  if (chunk.type === "usage" && chunk.usage) {
610725
611351
  streamUsage = chunk.usage;
@@ -611932,8 +612558,6 @@ var init_nexusBackend = __esm({
611932
612558
  effectiveThink(request) {
611933
612559
  if (process.env["OMNIUS_FORCE_NO_THINK"] === "1")
611934
612560
  return false;
611935
- if (process.env["OMNIUS_ENABLE_THINKING"] !== "1")
611936
- return false;
611937
612561
  if (Array.isArray(request.tools) && request.tools.length > 0)
611938
612562
  return false;
611939
612563
  if (request.think === true)
@@ -633315,11 +633939,149 @@ async function queryOpenAIContextSize(baseUrl2, modelName, apiKey) {
633315
633939
  return null;
633316
633940
  }
633317
633941
  }
633318
- async function queryContextSize(baseUrl2, modelName, apiKey) {
633319
- if (baseUrl2.startsWith("peer://")) return 32768;
633942
+ function llamaCppRootUrl(baseUrl2) {
633943
+ return normalizeBaseUrl(baseUrl2).replace(/\/v1$/i, "");
633944
+ }
633945
+ function asRecord(value2) {
633946
+ return value2 !== null && typeof value2 === "object" && !Array.isArray(value2) ? value2 : null;
633947
+ }
633948
+ function positiveInteger(value2) {
633949
+ const parsed = typeof value2 === "number" ? value2 : typeof value2 === "string" && /^\d+$/.test(value2.trim()) ? Number(value2) : NaN;
633950
+ return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : void 0;
633951
+ }
633952
+ function firstPositive(record, keys) {
633953
+ for (const key of keys) {
633954
+ const value2 = positiveInteger(record[key]);
633955
+ if (value2 !== void 0) return value2;
633956
+ }
633957
+ return void 0;
633958
+ }
633959
+ function contextCapacityFromRecord(record) {
633960
+ return firstPositive(record, [
633961
+ "n_ctx",
633962
+ "n_ctx_train",
633963
+ "context_length",
633964
+ "context_window",
633965
+ "max_model_len",
633966
+ "max_context_length"
633967
+ ]);
633968
+ }
633969
+ function telemetryHeaders(apiKey) {
633970
+ return apiKey ? { Authorization: `Bearer ${apiKey}` } : void 0;
633971
+ }
633972
+ async function fetchTelemetryJson(url, apiKey) {
633973
+ try {
633974
+ const response = await fetch(url, {
633975
+ headers: telemetryHeaders(apiKey),
633976
+ signal: AbortSignal.timeout(LLAMA_CPP_TELEMETRY_TIMEOUT_MS)
633977
+ });
633978
+ return response.ok ? await response.json() : null;
633979
+ } catch {
633980
+ return null;
633981
+ }
633982
+ }
633983
+ function llamaCppSlotsFromJson(raw, endpoint, model) {
633984
+ const root = asRecord(raw);
633985
+ const slots = Array.isArray(raw) ? raw : Array.isArray(root?.["slots"]) ? root["slots"] : null;
633986
+ if (!slots) return null;
633987
+ const active = slots.map(asRecord).filter((slot) => {
633988
+ if (!slot) return false;
633989
+ return slot["is_processing"] === true || firstPositive(slot, ["n_prompt_tokens", "n_past", "n_decoded", "n_tokens"]) !== void 0;
633990
+ });
633991
+ if (active.length === 0) {
633992
+ return { endpoint, model, activeSlotCount: 0, isLlamaCpp: true };
633993
+ }
633994
+ const measured = active.map((slot) => {
633995
+ const promptTokens = firstPositive(slot, ["n_prompt_tokens", "prompt_tokens"]);
633996
+ const decodedTokens = firstPositive(slot, ["n_decoded", "n_generated", "n_output_tokens"]);
633997
+ const observed = promptTokens !== void 0 ? promptTokens + (decodedTokens ?? 0) : firstPositive(slot, ["n_past", "n_tokens"]) ?? decodedTokens;
633998
+ return {
633999
+ capacityTokens: firstPositive(slot, ["n_ctx", "context_length"]),
634000
+ promptTokens,
634001
+ decodedTokens,
634002
+ outputReservationTokens: firstPositive(slot, ["n_predict", "n_predict_max", "n_output_reservation"]),
634003
+ estimatedContextTokens: observed
634004
+ };
634005
+ });
634006
+ const selected = measured.reduce(
634007
+ (best, candidate) => (candidate.estimatedContextTokens ?? 0) > (best.estimatedContextTokens ?? 0) ? candidate : best
634008
+ );
634009
+ return {
634010
+ endpoint,
634011
+ model,
634012
+ ...selected,
634013
+ capacitySource: selected.capacityTokens ? "llama_cpp_slots" : void 0,
634014
+ activeSlotCount: active.length,
634015
+ isLlamaCpp: true
634016
+ };
634017
+ }
634018
+ async function queryLlamaCppSlotTelemetry(baseUrl2, modelName, apiKey) {
634019
+ const endpoint = llamaCppRootUrl(baseUrl2);
634020
+ const slots = await fetchTelemetryJson(`${endpoint}/slots`, apiKey);
634021
+ return llamaCppSlotsFromJson(slots, endpoint, modelName);
634022
+ }
634023
+ function llamaCppModelCapacity(raw, modelName) {
634024
+ const root = asRecord(raw);
634025
+ if (!root) return void 0;
634026
+ const records = Array.isArray(root["data"]) ? root["data"].map(asRecord).filter((entry) => entry !== null) : [];
634027
+ const target = records.find(
634028
+ (entry) => [entry["id"], entry["name"], entry["model"]].some(
634029
+ (value2) => typeof value2 === "string" && value2 === modelName
634030
+ )
634031
+ );
634032
+ return (target && contextCapacityFromRecord(target)) ?? contextCapacityFromRecord(root);
634033
+ }
634034
+ async function queryLlamaCppContextTelemetry(baseUrl2, modelName, apiKey) {
634035
+ const endpoint = llamaCppRootUrl(baseUrl2);
634036
+ const [propsRaw, modelsRaw, slotsRaw] = await Promise.all([
634037
+ fetchTelemetryJson(`${endpoint}/props`, apiKey),
634038
+ fetchTelemetryJson(`${endpoint}/v1/models`, apiKey),
634039
+ fetchTelemetryJson(`${endpoint}/slots`, apiKey)
634040
+ ]);
634041
+ const props = asRecord(propsRaw);
634042
+ const slots = llamaCppSlotsFromJson(slotsRaw, endpoint, modelName);
634043
+ const propsCapacity = props ? contextCapacityFromRecord(props) : void 0;
634044
+ const modelsCapacity = llamaCppModelCapacity(modelsRaw, modelName);
634045
+ const isLlamaCpp = props !== null || slots !== null;
634046
+ if (!isLlamaCpp) return null;
634047
+ const capacityTokens = propsCapacity ?? modelsCapacity ?? slots?.capacityTokens;
634048
+ const capacitySource = propsCapacity ? "llama_cpp_props" : modelsCapacity ? "llama_cpp_models" : slots?.capacityTokens ? "llama_cpp_slots" : void 0;
634049
+ return {
634050
+ endpoint,
634051
+ model: modelName,
634052
+ ...slots,
634053
+ capacityTokens,
634054
+ capacitySource,
634055
+ isLlamaCpp: true
634056
+ };
634057
+ }
634058
+ async function queryContextTelemetry(baseUrl2, modelName, apiKey) {
634059
+ const endpoint = normalizeBaseUrl(baseUrl2);
634060
+ if (baseUrl2.startsWith("peer://")) {
634061
+ return {
634062
+ endpoint,
634063
+ model: modelName,
634064
+ capacityTokens: 32768,
634065
+ capacitySource: "peer_default"
634066
+ };
634067
+ }
633320
634068
  const ollamaSize = await queryModelContextSize(baseUrl2, modelName);
633321
- if (ollamaSize) return ollamaSize;
633322
- return queryOpenAIContextSize(baseUrl2, modelName, apiKey);
634069
+ if (ollamaSize) {
634070
+ return { endpoint, model: modelName, capacityTokens: ollamaSize, capacitySource: "ollama_show" };
634071
+ }
634072
+ const llama = await queryLlamaCppContextTelemetry(baseUrl2, modelName, apiKey);
634073
+ const openAiSize = await queryOpenAIContextSize(baseUrl2, modelName, apiKey);
634074
+ if (openAiSize) {
634075
+ return {
634076
+ ...llama ?? { endpoint, model: modelName },
634077
+ capacityTokens: openAiSize,
634078
+ capacitySource: llama?.capacitySource ?? "openai_models"
634079
+ };
634080
+ }
634081
+ return llama ?? { endpoint, model: modelName };
634082
+ }
634083
+ async function queryContextSize(baseUrl2, modelName, apiKey) {
634084
+ return (await queryContextTelemetry(baseUrl2, modelName, apiKey)).capacityTokens ?? null;
633323
634085
  }
633324
634086
  async function queryModelCapabilities(baseUrl2, modelName) {
633325
634087
  const caps = { vision: false, toolUse: false, thinking: false };
@@ -633412,7 +634174,7 @@ function formatRelativeTime(iso2) {
633412
634174
  const months = Math.floor(days / 30);
633413
634175
  return `${months}mo ago`;
633414
634176
  }
633415
- var IMAGE_GEN_PATTERNS;
634177
+ var IMAGE_GEN_PATTERNS, LLAMA_CPP_TELEMETRY_TIMEOUT_MS;
633416
634178
  var init_model_picker = __esm({
633417
634179
  "packages/cli/src/tui/model-picker.ts"() {
633418
634180
  init_dist6();
@@ -633426,6 +634188,7 @@ var init_model_picker = __esm({
633426
634188
  /midjourney/i,
633427
634189
  /imagen/i
633428
634190
  ];
634191
+ LLAMA_CPP_TELEMETRY_TIMEOUT_MS = 2500;
633429
634192
  }
633430
634193
  });
633431
634194
 
@@ -647905,6 +648668,7 @@ var init_status_bar = __esm({
647905
648668
  lastCompletionTokens: 0,
647906
648669
  contextWindowSize: 0
647907
648670
  };
648671
+ _contextCapacity = { status: "unknown" };
647908
648672
  // ── Metrics tracking for Telegram stats ──
647909
648673
  _backend = "ollama";
647910
648674
  _inferenceCount = 0;
@@ -649149,7 +649913,17 @@ var init_status_bar = __esm({
649149
649913
  }
649150
649914
  /** Context window size to display. Can be updated if model changes. */
649151
649915
  setContextWindowSize(size) {
649152
- this.metrics.contextWindowSize = size;
649916
+ this.setContextCapacity(
649917
+ Number.isFinite(size) && size > 0 ? { status: "known", totalTokens: Math.floor(size), source: "runtime" } : { status: "unknown", source: "unavailable" }
649918
+ );
649919
+ }
649920
+ /** Update capacity provenance without turning missing server metadata into zero percent. */
649921
+ setContextCapacity(state) {
649922
+ const totalTokens = state.status === "known" && (state.totalTokens ?? 0) > 0 ? Math.floor(state.totalTokens) : 0;
649923
+ this._contextCapacity = totalTokens > 0 ? { ...state, status: "known", totalTokens } : { ...state, status: "unknown", totalTokens: void 0 };
649924
+ this.metrics.contextWindowSize = totalTokens;
649925
+ this.pushSpinnerContextMetrics();
649926
+ if (this.active) this.renderFooterPreserveCursor();
649153
649927
  }
649154
649928
  /** Set the current package version for display in the metrics row */
649155
649929
  setVersion(version5) {
@@ -649630,6 +650404,8 @@ var init_status_bar = __esm({
649630
650404
  this.metrics.totalTokens = update2.totalTokens;
649631
650405
  if (update2.estimatedContextTokens !== void 0)
649632
650406
  this.metrics.estimatedContextTokens = update2.estimatedContextTokens;
650407
+ if (update2.contextOutputReservationTokens !== void 0)
650408
+ this.metrics.contextOutputReservationTokens = update2.contextOutputReservationTokens;
649633
650409
  if (update2.lastPromptTokens !== void 0)
649634
650410
  this.metrics.lastPromptTokens = update2.lastPromptTokens;
649635
650411
  if (update2.lastCompletionTokens !== void 0)
@@ -651769,7 +652545,7 @@ ${CONTENT_BG_SEQ}`);
651769
652545
  this.effectiveContextTotal(m2.contextWindowSize)
651770
652546
  );
651771
652547
  let ctxStr = "";
651772
- if (ctxTotal > 0) {
652548
+ if (this._contextCapacity.status === "known" && ctxTotal > 0) {
651773
652549
  const pct2 = Math.max(
651774
652550
  0,
651775
652551
  Math.min(100, Math.round((1 - ctxUsed / ctxTotal) * 100))
@@ -651781,6 +652557,10 @@ ${CONTENT_BG_SEQ}`);
651781
652557
  const bar = `\x1B[38;5;${barColor}m${"█".repeat(filled)}\x1B[0m\x1B[38;5;240m${"░".repeat(empty2)}\x1B[0m`;
651782
652558
  const pctColor = pct2 > 50 ? 120 : pct2 > 20 ? 222 : 210;
651783
652559
  ctxStr = `${bar} \x1B[38;5;${pctColor}m${pct2}%\x1B[0m`;
652560
+ } else {
652561
+ const usage = ctxUsed >= 1024 ? `${(ctxUsed / 1024).toFixed(ctxUsed >= 1e4 ? 0 : 1)}K` : String(Math.max(0, Math.round(ctxUsed)));
652562
+ const reservation = m2.contextOutputReservationTokens && m2.contextOutputReservationTokens > 0 ? ` +${m2.contextOutputReservationTokens >= 1024 ? `${Math.round(m2.contextOutputReservationTokens / 1024)}K` : m2.contextOutputReservationTokens} rsv` : "";
652563
+ ctxStr = `\x1B[38;5;245mCTX ? | ~${usage}${reservation}\x1B[0m`;
651784
652564
  }
651785
652565
  const arrow = `\x1B[38;5;240m▶\x1B[0m`;
651786
652566
  let rightSide;
@@ -670511,12 +671291,12 @@ async function ensureVoiceDeps(ctx3) {
670511
671291
  }
670512
671292
  }
670513
671293
  if (typeof mod3.getVenvPython === "function") {
670514
- const { dirname: dirname58 } = await import("node:path");
671294
+ const { dirname: dirname59 } = await import("node:path");
670515
671295
  const { existsSync: existsSync177 } = await import("node:fs");
670516
671296
  const venvPy = mod3.getVenvPython();
670517
671297
  if (existsSync177(venvPy)) {
670518
671298
  process.env.TRANSCRIBE_PYTHON = venvPy;
670519
- const venvBin = dirname58(venvPy);
671299
+ const venvBin = dirname59(venvPy);
670520
671300
  const sep8 = process.platform === "win32" ? ";" : ":";
670521
671301
  const cur = process.env.PATH || "";
670522
671302
  if (!cur.split(sep8).includes(venvBin)) {
@@ -673977,10 +674757,6 @@ Clone a new voice: /voice clone <wav-file> [name]`);
673977
674757
  renderWarning(
673978
674758
  "OMNIUS_FORCE_NO_THINK=1 forces off regardless of /think setting"
673979
674759
  );
673980
- else if (cur && process.env["OMNIUS_ENABLE_THINKING"] !== "1")
673981
- renderWarning(
673982
- "OMNIUS_ENABLE_THINKING is not set; /think is saved but backend requests remain direct-answer mode."
673983
- );
673984
674760
  return "handled";
673985
674761
  }
673986
674762
  if (token === "auto") {
@@ -674019,11 +674795,6 @@ Clone a new voice: /voice clone <wav-file> [name]`);
674019
674795
  renderInfo(
674020
674796
  "Note: max_tokens will auto-raise to ≥4096 per request to prevent <think> truncation."
674021
674797
  );
674022
- if (process.env["OMNIUS_ENABLE_THINKING"] !== "1") {
674023
- renderWarning(
674024
- "Thinking is hard-disabled by default. Set OMNIUS_ENABLE_THINKING=1 before launch for /think on or /think auto to affect backend requests."
674025
- );
674026
- }
674027
674798
  }
674028
674799
  return "handled";
674029
674800
  }
@@ -683925,14 +684696,14 @@ async function handlePeerEndpoint(peerId, authKey, ctx3, local, advertisedModels
683925
684696
  if (models.length > 0) {
683926
684697
  try {
683927
684698
  const { writeFileSync: writeFileSync97, mkdirSync: mkdirSync114 } = await import("node:fs");
683928
- const { join: join190, dirname: dirname58 } = await import("node:path");
684699
+ const { join: join190, dirname: dirname59 } = await import("node:path");
683929
684700
  const cachePath2 = join190(
683930
684701
  ctx3.repoRoot || process.cwd(),
683931
684702
  ".omnius",
683932
684703
  "nexus",
683933
684704
  "peer-models-cache.json"
683934
684705
  );
683935
- mkdirSync114(dirname58(cachePath2), { recursive: true });
684706
+ mkdirSync114(dirname59(cachePath2), { recursive: true });
683936
684707
  writeFileSync97(
683937
684708
  cachePath2,
683938
684709
  JSON.stringify(
@@ -684008,14 +684779,14 @@ async function handlePeerEndpoint(peerId, authKey, ctx3, local, advertisedModels
684008
684779
  );
684009
684780
  try {
684010
684781
  const { writeFileSync: writeFileSync97, mkdirSync: mkdirSync114 } = await import("node:fs");
684011
- const { join: join190, dirname: dirname58 } = await import("node:path");
684782
+ const { join: join190, dirname: dirname59 } = await import("node:path");
684012
684783
  const cachePath2 = join190(
684013
684784
  ctx3.repoRoot || process.cwd(),
684014
684785
  ".omnius",
684015
684786
  "nexus",
684016
684787
  "peer-models-cache.json"
684017
684788
  );
684018
- mkdirSync114(dirname58(cachePath2), { recursive: true });
684789
+ mkdirSync114(dirname59(cachePath2), { recursive: true });
684019
684790
  writeFileSync97(
684020
684791
  cachePath2,
684021
684792
  JSON.stringify(
@@ -685031,10 +685802,10 @@ async function handleUpdate(subcommand, ctx3) {
685031
685802
  try {
685032
685803
  const { createRequire: createRequire11 } = await import("node:module");
685033
685804
  const { fileURLToPath: fileURLToPath26 } = await import("node:url");
685034
- const { dirname: dirname58, join: join190 } = await import("node:path");
685805
+ const { dirname: dirname59, join: join190 } = await import("node:path");
685035
685806
  const { existsSync: existsSync177 } = await import("node:fs");
685036
685807
  const req3 = createRequire11(import.meta.url);
685037
- const thisDir = dirname58(fileURLToPath26(import.meta.url));
685808
+ const thisDir = dirname59(fileURLToPath26(import.meta.url));
685038
685809
  const candidates = [
685039
685810
  join190(thisDir, "..", "package.json"),
685040
685811
  join190(thisDir, "..", "..", "package.json"),
@@ -700693,6 +701464,7 @@ import {
700693
701464
  } from "node:fs";
700694
701465
  import {
700695
701466
  join as join170,
701467
+ dirname as dirname53,
700696
701468
  resolve as resolve73,
700697
701469
  basename as basename42,
700698
701470
  relative as relative21,
@@ -700700,7 +701472,11 @@ import {
700700
701472
  extname as extname21
700701
701473
  } from "node:path";
700702
701474
  import { homedir as homedir56 } from "node:os";
700703
- import { writeFile as writeFileAsync } from "node:fs/promises";
701475
+ import {
701476
+ appendFile as appendFileAsync,
701477
+ mkdir as mkdirAsync,
701478
+ writeFile as writeFileAsync
701479
+ } from "node:fs/promises";
700704
701480
  import { createHash as createHash49, randomBytes as randomBytes28, randomInt } from "node:crypto";
700705
701481
  function formatModelBytes(bytes) {
700706
701482
  if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";
@@ -703733,6 +704509,12 @@ Telegram link integrity contract:
703733
704509
  subAgents = /* @__PURE__ */ new Map();
703734
704510
  /** Debounced live-context packets for messages arriving during a runner. */
703735
704511
  telegramSubAgentContextBuffers = /* @__PURE__ */ new Map();
704512
+ /** Append-only, durable ingress ledger for every agent-routed Telegram task input. */
704513
+ telegramIntakeRecords = /* @__PURE__ */ new Map();
704514
+ telegramIntakeMessages = /* @__PURE__ */ new Map();
704515
+ telegramIntakeWriteTail = Promise.resolve();
704516
+ /** Intent epochs isolate redirected/replaced work inside a long-lived chat session. */
704517
+ telegramTaskEpochs = /* @__PURE__ */ new Map();
703736
704518
  /** Active direct chat completions, counted with Telegram activity in the TUI */
703737
704519
  activeChatViews = /* @__PURE__ */ new Set();
703738
704520
  /** Active direct chat completions by Telegram session key for admission. */
@@ -704634,7 +705416,7 @@ No scoped reflection artifact exists yet for this chat. Use <code>/reflect</code
704634
705416
  }
704635
705417
  this.refreshActiveTelegramInteractionCount();
704636
705418
  }
704637
- buildTelegramQueuedSessionWork(sessionKey, msg, toolContext, now2) {
705419
+ buildTelegramQueuedSessionWork(sessionKey, msg, toolContext, now2, intakeRecord) {
704638
705420
  const existing = this.telegramQueuedSessionWork.get(sessionKey);
704639
705421
  const messages2 = [...existing?.messages ?? [], msg].slice(
704640
705422
  -TELEGRAM_SUB_AGENT_BURST_CONTEXT_LIMIT
@@ -704643,6 +705425,7 @@ No scoped reflection artifact exists yet for this chat. Use <code>/reflect</code
704643
705425
  sessionKey,
704644
705426
  msg,
704645
705427
  messages: messages2,
705428
+ intakeRecords: [...existing?.intakeRecords ?? [], intakeRecord],
704646
705429
  toolContext,
704647
705430
  enqueuedAtMs: existing?.enqueuedAtMs ?? now2,
704648
705431
  lastSpokenAtMs: now2,
@@ -704668,14 +705451,15 @@ No scoped reflection artifact exists yet for this chat. Use <code>/reflect</code
704668
705451
  shouldAwaitTelegramQueuedWorkForTests() {
704669
705452
  return process.env["OMNIUS_TG_AWAIT_QUEUED_WORK"] === "1" || process.env["VITEST"] === "true";
704670
705453
  }
704671
- scheduleTelegramSessionWork(msg, toolContext) {
705454
+ scheduleTelegramSessionWork(msg, toolContext, intakeRecord) {
704672
705455
  const sessionKey = this.sessionKeyForMessage(msg);
704673
705456
  const now2 = Date.now();
704674
705457
  const existing = this.subAgents.get(sessionKey);
704675
705458
  if (existing && !existing.aborted) {
704676
705459
  return this.enqueueTelegramMessageForExistingSubAgent(
704677
705460
  msg,
704678
- existing
705461
+ existing,
705462
+ intakeRecord
704679
705463
  ).catch((err) => {
704680
705464
  this.tuiWrite(
704681
705465
  () => renderWarning(
@@ -704689,9 +705473,15 @@ No scoped reflection artifact exists yet for this chat. Use <code>/reflect</code
704689
705473
  sessionKey,
704690
705474
  msg,
704691
705475
  toolContext,
704692
- now2
705476
+ now2,
705477
+ intakeRecord
704693
705478
  );
704694
705479
  this.telegramQueuedSessionWork.set(sessionKey, queued);
705480
+ void this.transitionTelegramIntake(
705481
+ intakeRecord,
705482
+ "deferred",
705483
+ "queued behind Telegram session admission"
705484
+ );
704695
705485
  this.refreshActiveTelegramInteractionCount();
704696
705486
  this.dispatchQueuedTelegramSessionWorkSoon(
704697
705487
  Math.max(0, queued.dispatchAfterMs - now2)
@@ -704902,14 +705692,14 @@ ${message2}`)
704902
705692
  `live context injected (${buffer2.messages.length} message${buffer2.messages.length === 1 ? "" : "s"})`
704903
705693
  );
704904
705694
  } else {
704905
- subAgent.pendingMessages.push(packet);
705695
+ subAgent.pendingContextPackets.push(packet);
704906
705696
  this.subAgentViewCallbacks?.onWrite(
704907
705697
  subAgent.viewId,
704908
705698
  `live context staged (${buffer2.messages.length} message${buffer2.messages.length === 1 ? "" : "s"})`
704909
705699
  );
704910
705700
  }
704911
705701
  }
704912
- async enqueueTelegramMessageForExistingSubAgent(msg, subAgent) {
705702
+ async enqueueTelegramMessageForExistingSubAgent(msg, subAgent, intakeRecord) {
704913
705703
  const sessionKey = this.sessionKeyForMessage(msg);
704914
705704
  let mediaContext = "";
704915
705705
  if (msg.media || msg.replyToMedia) {
@@ -704928,11 +705718,16 @@ ${message2}`)
704928
705718
  } else {
704929
705719
  this.recordTelegramUserMessage(msg, "steering");
704930
705720
  }
704931
- this.enqueueTelegramSubAgentContext(
704932
- sessionKey,
705721
+ this.injectTelegramSteeringInput(
704933
705722
  subAgent,
704934
- context2,
704935
- msg.username
705723
+ intakeRecord,
705724
+ context2
705725
+ );
705726
+ void this.transitionTelegramIntake(
705727
+ intakeRecord,
705728
+ "accepted",
705729
+ "accepted by active Telegram runner",
705730
+ { runId: subAgent.runId }
704936
705731
  );
704937
705732
  this.tuiWrite(
704938
705733
  () => renderTelegramSubAgentEvent(
@@ -704944,8 +705739,259 @@ ${message2}`)
704944
705739
  async enqueueTelegramQueuedSessionWorkForExistingSubAgent(work, subAgent) {
704945
705740
  const messages2 = work.messages.length > 0 ? work.messages : [work.msg];
704946
705741
  for (const msg of messages2) {
704947
- await this.enqueueTelegramMessageForExistingSubAgent(msg, subAgent);
705742
+ const intakeRecord = work.intakeRecords.find(
705743
+ (record) => record.inputId === this.telegramInputIdForMessage(msg)
705744
+ );
705745
+ if (!intakeRecord) continue;
705746
+ await this.enqueueTelegramMessageForExistingSubAgent(
705747
+ msg,
705748
+ subAgent,
705749
+ intakeRecord
705750
+ );
705751
+ }
705752
+ }
705753
+ telegramInputIdForMessage(msg) {
705754
+ const thread = msg.messageThreadId ?? 0;
705755
+ return `telegram:${this.sessionKeyForMessage(msg)}:${thread}:${msg.messageId ?? "unknown"}`;
705756
+ }
705757
+ telegramTaskEpoch(sessionKey) {
705758
+ const current = this.telegramTaskEpochs.get(sessionKey);
705759
+ if (current !== void 0) return current;
705760
+ this.telegramTaskEpochs.set(sessionKey, 1);
705761
+ return 1;
705762
+ }
705763
+ advanceTelegramTaskEpoch(sessionKey) {
705764
+ const next = this.telegramTaskEpoch(sessionKey) + 1;
705765
+ this.telegramTaskEpochs.set(sessionKey, next);
705766
+ return next;
705767
+ }
705768
+ triageTelegramSteeringInput(msg) {
705769
+ const text2 = msg.text.trim();
705770
+ const lower = text2.toLowerCase();
705771
+ if (/^\/(?:stop|cancel|abort|halt)\b/.test(lower)) {
705772
+ return { intent: "cancel", reason: "explicit stop/cancel command" };
704948
705773
  }
705774
+ if (/^\/(?:redirect|reroute|pivot)\b/.test(lower)) {
705775
+ return { intent: "redirect", reason: "explicit redirect command" };
705776
+ }
705777
+ if (/^\/(?:replace|new[_-]?task)\b/.test(lower) || /^(?:new task|replace (?:the )?(?:current )?task|forget (?:that|the current task)|instead[,!:]?)/.test(
705778
+ lower
705779
+ )) {
705780
+ return { intent: "replace", reason: "explicit replacement/new-task request" };
705781
+ }
705782
+ if (/^\/(?:append|add|also)\b/.test(lower) || /^(?:also|add|include|one more thing)\b/.test(lower)) {
705783
+ return { intent: "append", reason: "explicit additive instruction" };
705784
+ }
705785
+ if (/\?$/.test(text2) || /^(?:clarify|correction|to be clear)\b/.test(lower)) {
705786
+ return { intent: "clarify", reason: "plain-text clarification; scope preserved" };
705787
+ }
705788
+ return { intent: "append", reason: "conservative plain-text intake; momentum preserved" };
705789
+ }
705790
+ telegramIntakePath(sessionKey) {
705791
+ const digest3 = createHash49("sha256").update(sessionKey).digest("hex").slice(0, 20);
705792
+ return join170(
705793
+ this.repoRoot ?? process.cwd(),
705794
+ ".omnius",
705795
+ "telegram-intake",
705796
+ `${digest3}.jsonl`
705797
+ );
705798
+ }
705799
+ appendTelegramIntakeJournal(sessionKey, entry) {
705800
+ const write2 = async () => {
705801
+ const path16 = this.telegramIntakePath(sessionKey);
705802
+ await mkdirAsync(dirname53(path16), { recursive: true });
705803
+ await appendFileAsync(path16, `${JSON.stringify(entry)}
705804
+ `, "utf8");
705805
+ };
705806
+ this.telegramIntakeWriteTail = this.telegramIntakeWriteTail.catch(() => {
705807
+ }).then(write2);
705808
+ return this.telegramIntakeWriteTail;
705809
+ }
705810
+ async registerTelegramIntake(msg, triage) {
705811
+ const sessionKey = this.sessionKeyForMessage(msg);
705812
+ const inputId = this.telegramInputIdForMessage(msg);
705813
+ const existing = this.telegramIntakeRecords.get(inputId);
705814
+ if (existing) return existing;
705815
+ const now2 = (/* @__PURE__ */ new Date()).toISOString();
705816
+ const record = {
705817
+ inputId,
705818
+ source: "telegram",
705819
+ receivedAt: now2,
705820
+ lifecycle: "received",
705821
+ lifecycleAt: now2,
705822
+ lifecycleReason: "Telegram update accepted before task routing",
705823
+ intent: triage.intent,
705824
+ classificationReason: triage.reason,
705825
+ sessionKey,
705826
+ chatId: String(msg.chatId),
705827
+ messageId: msg.messageId,
705828
+ messageThreadId: msg.messageThreadId,
705829
+ rawText: msg.text,
705830
+ taskEpoch: this.telegramTaskEpoch(sessionKey)
705831
+ };
705832
+ this.telegramIntakeRecords.set(inputId, record);
705833
+ this.telegramIntakeMessages.set(inputId, msg);
705834
+ await this.appendTelegramIntakeJournal(sessionKey, {
705835
+ kind: "intake_received",
705836
+ record
705837
+ });
705838
+ await this.transitionTelegramIntake(record, "classified", triage.reason);
705839
+ return record;
705840
+ }
705841
+ async transitionTelegramIntake(record, lifecycle, reason, links2 = {}) {
705842
+ const at = (/* @__PURE__ */ new Date()).toISOString();
705843
+ Object.assign(record, links2, {
705844
+ lifecycle,
705845
+ lifecycleAt: at,
705846
+ lifecycleReason: reason
705847
+ });
705848
+ await this.appendTelegramIntakeJournal(record.sessionKey, {
705849
+ kind: "intake_lifecycle",
705850
+ inputId: record.inputId,
705851
+ lifecycle,
705852
+ at,
705853
+ reason,
705854
+ taskEpoch: record.taskEpoch,
705855
+ runId: record.runId,
705856
+ runnerTurn: record.runnerTurn
705857
+ });
705858
+ }
705859
+ formatTelegramSteeringCompatibilityMessage(input) {
705860
+ return [
705861
+ "[TELEGRAM_STEERING_INTAKE]",
705862
+ `input_id: ${input.intake.inputId}`,
705863
+ `intent: ${input.intake.intent}`,
705864
+ `task_epoch: ${input.intake.taskEpoch}`,
705865
+ "This is a direct user intake. Reconcile it before the next action; do not treat it as passive transcript context.",
705866
+ input.content,
705867
+ "[/TELEGRAM_STEERING_INTAKE]"
705868
+ ].join("\n");
705869
+ }
705870
+ injectTelegramSteeringInput(subAgent, intake, content) {
705871
+ const pending2 = { intake, content };
705872
+ if (!subAgent.runner) {
705873
+ subAgent.pendingIntakeRecords.push(pending2);
705874
+ return;
705875
+ }
705876
+ const runner = subAgent.runner;
705877
+ if (typeof runner.injectSteeringInput === "function") {
705878
+ runner.injectSteeringInput({
705879
+ inputId: intake.inputId,
705880
+ content,
705881
+ source: "telegram",
705882
+ receivedAt: intake.receivedAt,
705883
+ intent: intake.intent,
705884
+ taskEpoch: intake.taskEpoch
705885
+ });
705886
+ return;
705887
+ }
705888
+ runner.injectUserMessage(this.formatTelegramSteeringCompatibilityMessage(pending2));
705889
+ }
705890
+ async preemptTelegramSubAgentForIntake(msg, subAgent, toolContext, intake) {
705891
+ const sessionKey = intake.sessionKey;
705892
+ await this.transitionTelegramIntake(
705893
+ intake,
705894
+ "acknowledged",
705895
+ "trusted Telegram steering receipt sent",
705896
+ { runId: subAgent.runId }
705897
+ );
705898
+ const receipt = intake.intent === "cancel" ? "Cancellation received. I am stopping the current task." : "Redirection received. I am stopping the current step and replanning from your latest instruction.";
705899
+ await this.replyToTelegramMessage(msg, receipt).catch(() => null);
705900
+ await this.transitionTelegramIntake(
705901
+ intake,
705902
+ "preempt_requested",
705903
+ "trusted admin-DM steering preemption requested",
705904
+ { runId: subAgent.runId }
705905
+ );
705906
+ subAgent.preempted = true;
705907
+ if (intake.intent !== "cancel") {
705908
+ const epoch = this.advanceTelegramTaskEpoch(sessionKey);
705909
+ const displaced = this.telegramQueuedSessionWork.get(sessionKey);
705910
+ if (displaced) {
705911
+ this.telegramQueuedSessionWork.delete(sessionKey);
705912
+ await Promise.all(
705913
+ displaced.intakeRecords.map(
705914
+ (record) => this.transitionTelegramIntake(
705915
+ record,
705916
+ "superseded",
705917
+ `superseded by trusted ${intake.intent} intake ${intake.inputId}`
705918
+ )
705919
+ )
705920
+ );
705921
+ }
705922
+ intake.taskEpoch = epoch;
705923
+ const queued = this.buildTelegramQueuedSessionWork(
705924
+ sessionKey,
705925
+ msg,
705926
+ toolContext,
705927
+ Date.now(),
705928
+ intake
705929
+ );
705930
+ this.telegramQueuedSessionWork.set(sessionKey, queued);
705931
+ await this.transitionTelegramIntake(
705932
+ intake,
705933
+ "deferred",
705934
+ "waiting for superseded runner cleanup before dispatch",
705935
+ { taskEpoch: epoch }
705936
+ );
705937
+ }
705938
+ const runner = subAgent.runner;
705939
+ if (typeof runner?.requestSteeringPreemption === "function") {
705940
+ runner.requestSteeringPreemption(intake.inputId);
705941
+ } else {
705942
+ runner?.abort?.();
705943
+ }
705944
+ await this.transitionTelegramIntake(
705945
+ intake,
705946
+ "preempted",
705947
+ "active runner interrupted for trusted steering intake",
705948
+ { runId: subAgent.runId }
705949
+ );
705950
+ this.dispatchQueuedTelegramSessionWorkSoon();
705951
+ }
705952
+ async requeuePendingTelegramIntakeOnFinalization(subAgent) {
705953
+ const pending2 = subAgent.pendingIntakeRecords.splice(0);
705954
+ if (pending2.length === 0) return;
705955
+ for (const item of pending2) {
705956
+ const msg = this.telegramIntakeMessages.get(item.intake.inputId);
705957
+ if (!msg || subAgent.preempted) {
705958
+ await this.transitionTelegramIntake(
705959
+ item.intake,
705960
+ subAgent.preempted ? "superseded" : "failed",
705961
+ subAgent.preempted ? "runner was superseded before pending intake dispatch" : "original Telegram message unavailable for pending intake requeue"
705962
+ );
705963
+ continue;
705964
+ }
705965
+ const work = this.buildTelegramQueuedSessionWork(
705966
+ item.intake.sessionKey,
705967
+ msg,
705968
+ subAgent.toolContext,
705969
+ Date.now(),
705970
+ item.intake
705971
+ );
705972
+ this.telegramQueuedSessionWork.set(item.intake.sessionKey, work);
705973
+ await this.transitionTelegramIntake(
705974
+ item.intake,
705975
+ "deferred",
705976
+ "runner finalized before pending intake dispatch; requeued atomically"
705977
+ );
705978
+ }
705979
+ this.dispatchQueuedTelegramSessionWorkSoon();
705980
+ }
705981
+ forwardTelegramRunnerIntakeLifecycle(event) {
705982
+ const typed = event;
705983
+ const inputId = typed.inputId ?? typed.steeringInputId;
705984
+ if (!inputId) return;
705985
+ const record = this.telegramIntakeRecords.get(inputId);
705986
+ if (!record) return;
705987
+ const lifecycle = typed.type === "steering_preempt_requested" ? "preempt_requested" : typed.type === "steering_preempted" ? "preempted" : typed.type === "steering_input_consumed" || typed.type === "steering_consumed" ? "consumed" : typed.type === "steering_input_accepted" || typed.type === "steering_received" ? "accepted" : null;
705988
+ if (!lifecycle) return;
705989
+ void this.transitionTelegramIntake(
705990
+ record,
705991
+ lifecycle,
705992
+ `runner lifecycle event: ${typed.type}`,
705993
+ typeof typed.turn === "number" ? { runnerTurn: typed.turn } : {}
705994
+ );
704949
705995
  }
704950
705996
  async replyWithTelegramHelp(msg, isAdmin) {
704951
705997
  const scope = isAdmin ? "admin" : "public";
@@ -712649,12 +713695,32 @@ Join: ${newUrl}`
712649
713695
  return;
712650
713696
  }
712651
713697
  }
713698
+ const intakeTriage = this.triageTelegramSteeringInput(msg);
713699
+ const intakeRecord = await this.registerTelegramIntake(msg, intakeTriage);
712652
713700
  const existing = this.subAgents.get(sessionKey);
712653
713701
  if (existing && !existing.aborted) {
712654
- await this.enqueueTelegramMessageForExistingSubAgent(msg, existing);
713702
+ const trustedPreemption = isAdminDM && (intakeRecord.intent === "cancel" || intakeRecord.intent === "redirect" || intakeRecord.intent === "replace");
713703
+ if (trustedPreemption) {
713704
+ await this.preemptTelegramSubAgentForIntake(
713705
+ msg,
713706
+ existing,
713707
+ toolContext,
713708
+ intakeRecord
713709
+ );
713710
+ return;
713711
+ }
713712
+ await this.enqueueTelegramMessageForExistingSubAgent(
713713
+ msg,
713714
+ existing,
713715
+ intakeRecord
713716
+ );
712655
713717
  return;
712656
713718
  }
712657
- const queuedWork = this.scheduleTelegramSessionWork(msg, toolContext);
713719
+ const queuedWork = this.scheduleTelegramSessionWork(
713720
+ msg,
713721
+ toolContext,
713722
+ intakeRecord
713723
+ );
712658
713724
  if (this.shouldAwaitTelegramQueuedWorkForTests()) await queuedWork;
712659
713725
  }
712660
713726
  async processTelegramMessageWork(work, workGeneration) {
@@ -712664,6 +713730,15 @@ Join: ${newUrl}`
712664
713730
  const isAdminDM = toolContext === "telegram-admin-dm";
712665
713731
  if (!this.telegramWorkGenerationIsCurrent(sessionKey, workGeneration))
712666
713732
  return;
713733
+ await Promise.all(
713734
+ work.intakeRecords.map(
713735
+ (record) => this.transitionTelegramIntake(
713736
+ record,
713737
+ "dispatched",
713738
+ "Telegram session work dispatched to runner admission"
713739
+ )
713740
+ )
713741
+ );
712667
713742
  const existing = this.subAgents.get(sessionKey);
712668
713743
  if (existing && !existing.aborted) {
712669
713744
  await this.enqueueTelegramQueuedSessionWorkForExistingSubAgent(
@@ -712742,6 +713817,15 @@ Join: ${newUrl}`
712742
713817
  msg,
712743
713818
  `live inference: no reply — ${decision2.reason}`
712744
713819
  );
713820
+ await Promise.all(
713821
+ work.intakeRecords.map(
713822
+ (intake) => this.transitionTelegramIntake(
713823
+ intake,
713824
+ "consumed",
713825
+ "Telegram attention router retained intake without visible reply"
713826
+ )
713827
+ )
713828
+ );
712745
713829
  return;
712746
713830
  }
712747
713831
  const decisionContext = this.formatTelegramAttentionDecisionContext(deliveredDecision);
@@ -712786,6 +713870,15 @@ Join: ${newUrl}`
712786
713870
  daydreamOpportunities
712787
713871
  );
712788
713872
  }
713873
+ await Promise.all(
713874
+ work.intakeRecords.map(
713875
+ (intake) => this.transitionTelegramIntake(
713876
+ intake,
713877
+ "consumed",
713878
+ "Telegram quick-chat path completed"
713879
+ )
713880
+ )
713881
+ );
712789
713882
  return;
712790
713883
  }
712791
713884
  const subAgent = {
@@ -712809,7 +713902,10 @@ Join: ${newUrl}`
712809
713902
  lastEditMs: 0,
712810
713903
  aborted: false,
712811
713904
  toolContext,
712812
- pendingMessages: [],
713905
+ pendingIntakeRecords: [],
713906
+ pendingContextPackets: [],
713907
+ runId: `telegram:${randomBytes28(8).toString("hex")}`,
713908
+ taskEpoch: work.intakeRecords[work.intakeRecords.length - 1]?.taskEpoch ?? this.telegramTaskEpoch(sessionKey),
712813
713909
  creativeWorkspaceRoot: this.creativeWorkspaceRootForMessage(
712814
713910
  msg,
712815
713911
  toolContext
@@ -712820,6 +713916,14 @@ Join: ${newUrl}`
712820
713916
  surfacedToolCallFingerprints: /* @__PURE__ */ new Set()
712821
713917
  };
712822
713918
  this.subAgents.set(sessionKey, subAgent);
713919
+ for (const intake of work.intakeRecords) {
713920
+ void this.transitionTelegramIntake(
713921
+ intake,
713922
+ "accepted",
713923
+ "admitted as the primary Telegram task prompt",
713924
+ { runId: subAgent.runId }
713925
+ );
713926
+ }
712823
713927
  this.refreshActiveTelegramInteractionCount();
712824
713928
  this.subAgentViewCallbacks?.onRegister(
712825
713929
  subAgent.viewId,
@@ -712870,6 +713974,20 @@ Join: ${newUrl}`
712870
713974
  mediaContext,
712871
713975
  subAgentProfile,
712872
713976
  [decisionContext, rapidContext].filter(Boolean).join("\n\n")
713977
+ ).catch((err) => {
713978
+ if (subAgent.preempted) return "";
713979
+ throw err;
713980
+ });
713981
+ if (subAgent.preempted) return;
713982
+ await Promise.all(
713983
+ work.intakeRecords.map(
713984
+ (intake) => this.transitionTelegramIntake(
713985
+ intake,
713986
+ "consumed",
713987
+ "primary Telegram task completed its runner lifecycle",
713988
+ { runId: subAgent.runId }
713989
+ )
713990
+ )
712873
713991
  );
712874
713992
  if (subAgent.typingInterval) {
712875
713993
  clearInterval(subAgent.typingInterval);
@@ -713061,6 +714179,7 @@ Join: ${newUrl}`
713061
714179
  }
713062
714180
  } finally {
713063
714181
  this.stopTelegramPublicProgressMessage(subAgent);
714182
+ await this.requeuePendingTelegramIntakeOnFinalization(subAgent);
713064
714183
  this.clearTelegramSubAgentContextBuffer(sessionKey);
713065
714184
  this.subAgents.delete(sessionKey);
713066
714185
  this.refreshActiveTelegramInteractionCount();
@@ -713091,7 +714210,10 @@ Join: ${newUrl}`
713091
714210
  lastEditMs: 0,
713092
714211
  aborted: false,
713093
714212
  toolContext,
713094
- pendingMessages: [],
714213
+ pendingIntakeRecords: [],
714214
+ pendingContextPackets: [],
714215
+ runId: `telegram:${randomBytes28(8).toString("hex")}`,
714216
+ taskEpoch: this.telegramTaskEpoch(sessionKey),
713095
714217
  creativeWorkspaceRoot: this.creativeWorkspaceRootForMessage(
713096
714218
  msg,
713097
714219
  toolContext
@@ -713102,6 +714224,17 @@ Join: ${newUrl}`
713102
714224
  surfacedToolCallFingerprints: /* @__PURE__ */ new Set()
713103
714225
  };
713104
714226
  this.subAgents.set(sessionKey, subAgent);
714227
+ const primaryIntake = this.telegramIntakeRecords.get(
714228
+ this.telegramInputIdForMessage(msg)
714229
+ );
714230
+ if (primaryIntake) {
714231
+ void this.transitionTelegramIntake(
714232
+ primaryIntake,
714233
+ "accepted",
714234
+ "admitted as the primary Telegram chat prompt",
714235
+ { runId: subAgent.runId }
714236
+ );
714237
+ }
713105
714238
  this.refreshActiveTelegramInteractionCount();
713106
714239
  this.subAgentViewCallbacks?.onRegister(
713107
714240
  subAgent.viewId,
@@ -713144,7 +714277,11 @@ Join: ${newUrl}`
713144
714277
  mediaContext,
713145
714278
  "chat",
713146
714279
  additionalContext
713147
- );
714280
+ ).catch((err) => {
714281
+ if (subAgent.preempted) return "";
714282
+ throw err;
714283
+ });
714284
+ if (subAgent.preempted) return;
713148
714285
  if (subAgent.typingInterval) {
713149
714286
  clearInterval(subAgent.typingInterval);
713150
714287
  subAgent.typingInterval = null;
@@ -713268,6 +714405,7 @@ Join: ${newUrl}`
713268
714405
  );
713269
714406
  }
713270
714407
  } finally {
714408
+ await this.requeuePendingTelegramIntakeOnFinalization(subAgent);
713271
714409
  this.clearTelegramSubAgentContextBuffer(sessionKey);
713272
714410
  this.subAgents.delete(sessionKey);
713273
714411
  this.refreshActiveTelegramInteractionCount();
@@ -713734,6 +714872,7 @@ ${conversationStream}`
713734
714872
  ...isAdminDM ? TELEGRAM_ADMIN_EVIDENCE_OPTIONS : TELEGRAM_PUBLIC_FAST_OPTIONS,
713735
714873
  // ── WO #03 (Typed Gateway Event Stream): structured event feed ──
713736
714874
  onTypedEvent: (event) => {
714875
+ this.forwardTelegramRunnerIntakeLifecycle(event);
713737
714876
  if (event.type === "run_finished") {
713738
714877
  subAgent.runnerCompleted = event.success;
713739
714878
  subAgent.runnerStatus = event.status;
@@ -713749,17 +714888,33 @@ ${conversationStream}`
713749
714888
  });
713750
714889
  runner.setWorkingDirectory(repoRoot);
713751
714890
  subAgent.runner = runner;
713752
- if (subAgent.pendingMessages.length > 0) {
713753
- for (const queued of subAgent.pendingMessages) {
713754
- runner.injectUserMessage(queued);
714891
+ if (subAgent.pendingIntakeRecords.length > 0) {
714892
+ for (const queued of subAgent.pendingIntakeRecords) {
714893
+ this.injectTelegramSteeringInput(
714894
+ subAgent,
714895
+ queued.intake,
714896
+ queued.content
714897
+ );
714898
+ void this.transitionTelegramIntake(
714899
+ queued.intake,
714900
+ "accepted",
714901
+ "initial Telegram intake handed to runner",
714902
+ { runId: subAgent.runId }
714903
+ );
713755
714904
  }
713756
714905
  this.tuiWrite(
713757
714906
  () => renderTelegramSubAgentEvent(
713758
714907
  msg.username,
713759
- `replayed ${subAgent.pendingMessages.length} queued message(s)`
714908
+ `replayed ${subAgent.pendingIntakeRecords.length} typed intake record(s)`
713760
714909
  )
713761
714910
  );
713762
- subAgent.pendingMessages.length = 0;
714911
+ subAgent.pendingIntakeRecords.length = 0;
714912
+ }
714913
+ if (subAgent.pendingContextPackets.length > 0) {
714914
+ for (const packet of subAgent.pendingContextPackets) {
714915
+ runner.injectUserMessage(packet);
714916
+ }
714917
+ subAgent.pendingContextPackets.length = 0;
713763
714918
  }
713764
714919
  const tools = this.buildSubAgentTools(
713765
714920
  ctx3,
@@ -721987,7 +723142,7 @@ var init_audit_log = __esm({
721987
723142
  // packages/cli/src/api/disk-task-output.ts
721988
723143
  import { open } from "node:fs/promises";
721989
723144
  import { existsSync as existsSync164, mkdirSync as mkdirSync102, statSync as statSync63 } from "node:fs";
721990
- import { dirname as dirname53 } from "node:path";
723145
+ import { dirname as dirname54 } from "node:path";
721991
723146
  import * as fsConstants from "node:constants";
721992
723147
  var O_NOFOLLOW2, O_APPEND2, O_CREAT2, O_WRONLY2, OPEN_FLAGS_WRITE, OPEN_MODE, DiskTaskOutput;
721993
723148
  var init_disk_task_output = __esm({
@@ -722005,7 +723160,7 @@ var init_disk_task_output = __esm({
722005
723160
  fileSize = 0;
722006
723161
  constructor(outputPath3) {
722007
723162
  this.path = outputPath3;
722008
- mkdirSync102(dirname53(outputPath3), { recursive: true });
723163
+ mkdirSync102(dirname54(outputPath3), { recursive: true });
722009
723164
  }
722010
723165
  /** Queue content for async append. Non-blocking. */
722011
723166
  append(chunk) {
@@ -741090,7 +742245,7 @@ var init_chat_followup = __esm({
741090
742245
  // packages/cli/src/docker.ts
741091
742246
  import { execSync as execSync39, spawn as spawn37 } from "node:child_process";
741092
742247
  import { existsSync as existsSync172, mkdirSync as mkdirSync108, writeFileSync as writeFileSync91 } from "node:fs";
741093
- import { join as join181, resolve as resolve76, dirname as dirname54 } from "node:path";
742248
+ import { join as join181, resolve as resolve76, dirname as dirname55 } from "node:path";
741094
742249
  import { homedir as homedir62 } from "node:os";
741095
742250
  import { fileURLToPath as fileURLToPath22 } from "node:url";
741096
742251
  function getDockerDir() {
@@ -741101,7 +742256,7 @@ function getDockerDir() {
741101
742256
  } catch {
741102
742257
  }
741103
742258
  try {
741104
- const thisDir = dirname54(fileURLToPath22(import.meta.url));
742259
+ const thisDir = dirname55(fileURLToPath22(import.meta.url));
741105
742260
  return join181(thisDir, "..", "..", "..", "docker");
741106
742261
  } catch {
741107
742262
  }
@@ -741566,7 +742721,7 @@ import * as http5 from "node:http";
741566
742721
  import * as https3 from "node:https";
741567
742722
  import { createRequire as createRequire8 } from "node:module";
741568
742723
  import { fileURLToPath as fileURLToPath23 } from "node:url";
741569
- import { dirname as dirname55, join as join183, resolve as resolve77 } from "node:path";
742724
+ import { dirname as dirname56, join as join183, resolve as resolve77 } from "node:path";
741570
742725
  import { homedir as homedir63 } from "node:os";
741571
742726
  import { spawn as spawn38, execSync as execSync40 } from "node:child_process";
741572
742727
  import {
@@ -741596,7 +742751,7 @@ function memoryDbPaths3(baseDir = process.cwd()) {
741596
742751
  }
741597
742752
  function getVersion3() {
741598
742753
  try {
741599
- const thisDir = dirname55(fileURLToPath23(import.meta.url));
742754
+ const thisDir = dirname56(fileURLToPath23(import.meta.url));
741600
742755
  const candidates = [
741601
742756
  join183(thisDir, "..", "package.json"),
741602
742757
  join183(thisDir, "..", "..", "package.json"),
@@ -744312,7 +745467,8 @@ async function handleV1ChatCompletions(req3, res, ollamaUrl) {
744312
745467
  return;
744313
745468
  }
744314
745469
  const callerProvidedThink = "think" in routedBody;
744315
- const thinkingAllowed = process.env["OMNIUS_ENABLE_THINKING"] === "1" && process.env["OMNIUS_FORCE_NO_THINK"] !== "1";
745470
+ const requestTools = routedBody["tools"];
745471
+ const thinkingAllowed = process.env["OMNIUS_FORCE_NO_THINK"] !== "1" && !(Array.isArray(requestTools) && requestTools.length > 0);
744316
745472
  const finalThink = thinkingAllowed && callerProvidedThink ? routedBody["think"] : false;
744317
745473
  const ollamaBody = { ...routedBody };
744318
745474
  if (finalThink === false && Array.isArray(ollamaBody["messages"])) {
@@ -745057,7 +746213,7 @@ async function handleV1Update(req3, res, requestId) {
745057
746213
  );
745058
746214
  const fs14 = require4("node:fs");
745059
746215
  const nodeBin = process.execPath;
745060
- const nodeDir = dirname55(nodeBin);
746216
+ const nodeDir = dirname56(nodeBin);
745061
746217
  const { execSync: es } = require4("node:child_process");
745062
746218
  const isWin2 = process.platform === "win32";
745063
746219
  let npmBin = "";
@@ -745072,7 +746228,7 @@ async function handleV1Update(req3, res, requestId) {
745072
746228
  const dir = join183(homedir63(), ".omnius");
745073
746229
  fs14.mkdirSync(dir, { recursive: true });
745074
746230
  const logFd = fs14.openSync(logPath3, "w");
745075
- const npmPrefix = dirname55(nodeDir);
746231
+ const npmPrefix = dirname56(nodeDir);
745076
746232
  let globalBinDir = "";
745077
746233
  try {
745078
746234
  if (isWin2) {
@@ -751021,7 +752177,7 @@ function startApiServer(options2 = {}) {
751021
752177
  if (process.env["OMNIUS_DAEMON"] === "1" && process.env["OMNIUS_NO_VERSION_GUARD"] !== "1") {
751022
752178
  const readDiskVersion = () => {
751023
752179
  try {
751024
- const here = dirname55(fileURLToPath23(import.meta.url));
752180
+ const here = dirname56(fileURLToPath23(import.meta.url));
751025
752181
  for (const rel of ["../package.json", "../../package.json", "../../../package.json", "../../../../package.json"]) {
751026
752182
  const p2 = join183(here, rel);
751027
752183
  if (existsSync173(p2)) {
@@ -752112,7 +753268,7 @@ var init_clipboard_media = __esm({
752112
753268
 
752113
753269
  // packages/cli/src/tui/interactive.ts
752114
753270
  import { cwd } from "node:process";
752115
- import { resolve as resolve78, join as join185, dirname as dirname56, extname as extname22, relative as relative22, sep as sep7 } from "node:path";
753271
+ import { resolve as resolve78, join as join185, dirname as dirname57, extname as extname22, relative as relative22, sep as sep7 } from "node:path";
752116
753272
  import { createRequire as createRequire9 } from "node:module";
752117
753273
  import { fileURLToPath as fileURLToPath24 } from "node:url";
752118
753274
  import { createHash as createHash53 } from "node:crypto";
@@ -752129,7 +753285,7 @@ import { existsSync as existsSync174 } from "node:fs";
752129
753285
  import {
752130
753286
  readFile as readFileAsync2,
752131
753287
  writeFile as writeFileAsync2,
752132
- mkdir as mkdirAsync
753288
+ mkdir as mkdirAsync2
752133
753289
  } from "node:fs/promises";
752134
753290
  import { homedir as homedir64 } from "node:os";
752135
753291
  function refreshLocalOllamaModelCache() {
@@ -752173,7 +753329,7 @@ function formatTimeAgo2(date) {
752173
753329
  function getVersion4() {
752174
753330
  try {
752175
753331
  const require5 = createRequire9(import.meta.url);
752176
- const thisDir = dirname56(fileURLToPath24(import.meta.url));
753332
+ const thisDir = dirname57(fileURLToPath24(import.meta.url));
752177
753333
  const candidates = [
752178
753334
  join185(thisDir, "..", "package.json"),
752179
753335
  join185(thisDir, "..", "..", "package.json"),
@@ -756081,7 +757237,7 @@ When done, either call task_complete with your answer, or use FINAL_VAR(variable
756081
757237
  if (existsSync174(ikFile)) {
756082
757238
  ikState = JSON.parse(await readFileAsync2(ikFile, "utf8"));
756083
757239
  } else {
756084
- await mkdirAsync(ikDir, { recursive: true });
757240
+ await mkdirAsync2(ikDir, { recursive: true });
756085
757241
  const machineId = Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
756086
757242
  ikState = {
756087
757243
  self_id: `omnius-${machineId}`,
@@ -757255,14 +758411,50 @@ ${result.summary}`
757255
758411
  } : null
757256
758412
  });
757257
758413
  let resolvedContextWindowSize = 0;
757258
- queryContextSize(config.backendUrl, config.model, config.apiKey).then((ctxSize) => {
757259
- if (ctxSize) {
757260
- resolvedContextWindowSize = ctxSize;
757261
- statusBar.setContextWindowSize(ctxSize);
757262
- setActiveTaskContextWindowSize(ctxSize);
757263
- telegramBridge?.setContextWindowSize(ctxSize);
758414
+ const contextTelemetryByScope = /* @__PURE__ */ new Map();
758415
+ const contextScope = (backendUrl2, model) => `${normalizeBaseUrl(backendUrl2).replace(/\/v1$/i, "")}\0${model}`;
758416
+ const currentContextScope = () => contextScope(currentConfig.backendUrl, currentConfig.model);
758417
+ const applyContextTelemetry = (telemetry) => {
758418
+ const scope = contextScope(telemetry.endpoint, telemetry.model);
758419
+ const previous = contextTelemetryByScope.get(scope);
758420
+ const merged = {
758421
+ ...previous,
758422
+ ...telemetry,
758423
+ capacityTokens: telemetry.capacityTokens ?? previous?.capacityTokens,
758424
+ capacitySource: telemetry.capacityTokens ? telemetry.capacitySource : previous?.capacitySource
758425
+ };
758426
+ contextTelemetryByScope.set(scope, merged);
758427
+ if (scope !== currentContextScope()) return;
758428
+ const capacity = merged.capacityTokens;
758429
+ resolvedContextWindowSize = capacity ?? 0;
758430
+ statusBar.setContextCapacity(capacity ? {
758431
+ status: "known",
758432
+ totalTokens: capacity,
758433
+ source: merged.capacitySource,
758434
+ endpoint: merged.endpoint,
758435
+ model: merged.model
758436
+ } : {
758437
+ status: "unknown",
758438
+ source: "provider_metadata_missing",
758439
+ endpoint: merged.endpoint,
758440
+ model: merged.model
758441
+ });
758442
+ setActiveTaskContextWindowSize(capacity ?? 0);
758443
+ telegramBridge?.setContextWindowSize(capacity ?? 0);
758444
+ if (merged.estimatedContextTokens !== void 0 || merged.outputReservationTokens !== void 0) {
758445
+ statusBar.updateMetrics({
758446
+ ...merged.estimatedContextTokens !== void 0 ? { estimatedContextTokens: merged.estimatedContextTokens } : {},
758447
+ ...merged.outputReservationTokens !== void 0 ? { contextOutputReservationTokens: merged.outputReservationTokens } : {}
758448
+ });
757264
758449
  }
757265
- }).catch(() => {
758450
+ };
758451
+ void queryContextTelemetry(config.backendUrl, config.model, config.apiKey).then(applyContextTelemetry).catch(() => {
758452
+ statusBar.setContextCapacity({
758453
+ status: "unknown",
758454
+ source: "query_failed",
758455
+ endpoint: normalizeBaseUrl(config.backendUrl),
758456
+ model: config.model
758457
+ });
757266
758458
  });
757267
758459
  let resolvedCaps = {
757268
758460
  vision: false,
@@ -757576,6 +758768,28 @@ Rationale: ${proposal.rationale}${provenanceNote}${dmnDevDiscipline(proposal.cat
757576
758768
  const runner = activeTask?.runner;
757577
758769
  if (runner) runner.setContextWindowSize(size);
757578
758770
  };
758771
+ let llamaCppSlotPollInFlight = false;
758772
+ const pollLlamaCppSlots = async () => {
758773
+ if (llamaCppSlotPollInFlight || !activeTask) return;
758774
+ llamaCppSlotPollInFlight = true;
758775
+ const pollScope = currentContextScope();
758776
+ const endpoint = currentConfig.backendUrl;
758777
+ const model = currentConfig.model;
758778
+ const apiKey = currentConfig.apiKey;
758779
+ try {
758780
+ const telemetry = await queryLlamaCppSlotTelemetry(endpoint, model, apiKey);
758781
+ if (telemetry && pollScope === currentContextScope()) {
758782
+ applyContextTelemetry(telemetry);
758783
+ }
758784
+ } catch {
758785
+ } finally {
758786
+ llamaCppSlotPollInFlight = false;
758787
+ }
758788
+ };
758789
+ const llamaCppSlotPollTimer = setInterval(() => {
758790
+ void pollLlamaCppSlots();
758791
+ }, 3e3);
758792
+ llamaCppSlotPollTimer.unref();
757579
758793
  const turnQueue = [];
757580
758794
  let queueDrainScheduled = false;
757581
758795
  let sessionTitle = null;
@@ -764397,7 +765611,7 @@ init_typed_node_events();
764397
765611
  init_dist5();
764398
765612
  import { parseArgs as nodeParseArgs2 } from "node:util";
764399
765613
  import { fileURLToPath as fileURLToPath25 } from "node:url";
764400
- import { dirname as dirname57, join as join189 } from "node:path";
765614
+ import { dirname as dirname58, join as join189 } from "node:path";
764401
765615
  import { createRequire as createRequire10 } from "node:module";
764402
765616
 
764403
765617
  // packages/cli/src/cli.ts
@@ -764545,7 +765759,7 @@ init_output();
764545
765759
  function getVersion5() {
764546
765760
  try {
764547
765761
  const require5 = createRequire10(import.meta.url);
764548
- const pkgPath = join189(dirname57(fileURLToPath25(import.meta.url)), "..", "package.json");
765762
+ const pkgPath = join189(dirname58(fileURLToPath25(import.meta.url)), "..", "package.json");
764549
765763
  const pkg = require5(pkgPath);
764550
765764
  return pkg.version;
764551
765765
  } catch {