omnius 1.0.554 → 1.0.555

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
@@ -566247,12 +566247,18 @@ function stripThinkTags(text2) {
566247
566247
  return "";
566248
566248
  return String(text2).replace(THINK_BLOCK_RE, "").trim();
566249
566249
  }
566250
+ function stripNoThinkPromptDirectives(text2) {
566251
+ if (text2 == null)
566252
+ return "";
566253
+ return String(text2).replace(NO_THINK_PROMPT_DIRECTIVE_RE, "").replace(/[ \t]+\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
566254
+ }
566250
566255
  function cleanForStorage(text2) {
566251
566256
  if (text2 == null)
566252
566257
  return "";
566253
566258
  let out = String(text2);
566254
566259
  out = cleanScaffolding(out);
566255
566260
  out = stripThinkTags(out);
566261
+ out = stripNoThinkPromptDirectives(out);
566256
566262
  out = out.replace(ANSI_ESCAPE_RE, "");
566257
566263
  out = out.replace(/\s+/g, " ").trim();
566258
566264
  return out;
@@ -566286,7 +566292,7 @@ function extractTaskCompleteSummary(args) {
566286
566292
  }
566287
566293
  return "";
566288
566294
  }
566289
- var SIGNPOST_RE, NEW_TASK_RE, RESTORED_BLOCK_RE, SYSTEM_BLOCK_RE, THINK_BLOCK_RE, ANSI_ESCAPE_RE;
566295
+ var SIGNPOST_RE, NEW_TASK_RE, RESTORED_BLOCK_RE, SYSTEM_BLOCK_RE, THINK_BLOCK_RE, NO_THINK_PROMPT_DIRECTIVE_RE, ANSI_ESCAPE_RE;
566290
566296
  var init_textSanitize = __esm({
566291
566297
  "packages/orchestrator/dist/textSanitize.js"() {
566292
566298
  "use strict";
@@ -566295,6 +566301,7 @@ var init_textSanitize = __esm({
566295
566301
  RESTORED_BLOCK_RE = /^[\s\S]*?\n---\s*\n\s*NEW TASK:\s*/m;
566296
566302
  SYSTEM_BLOCK_RE = /^<system>[\s\S]*?<\/system>\s*\n*/m;
566297
566303
  THINK_BLOCK_RE = /<think>[\s\S]*?<\/think>/g;
566304
+ NO_THINK_PROMPT_DIRECTIVE_RE = /\/(?:no[_-]?think)\b/gi;
566298
566305
  ANSI_ESCAPE_RE = /\x1b\[[0-9;]*[a-zA-Z]|\x1b\][^\x07]*\x07/g;
566299
566306
  }
566300
566307
  });
@@ -566513,6 +566520,28 @@ import { randomUUID as randomUUID16 } from "node:crypto";
566513
566520
  import { appendFileSync as appendFileSync6, existsSync as existsSync88, mkdirSync as mkdirSync50, readFileSync as readFileSync65 } from "node:fs";
566514
566521
  import { join as join98 } from "node:path";
566515
566522
  import { z as z16 } from "zod";
566523
+ function classifySteeringIntent(content, requestedIntent) {
566524
+ if (requestedIntent === "redirect" || requestedIntent === "replace" || requestedIntent === "cancel") {
566525
+ return requestedIntent;
566526
+ }
566527
+ const normalized = content.toLowerCase().replace(/\s+/g, " ").trim();
566528
+ const constraint = /\b(?:do not|don't|never|must not|forbid|forbidden|avoid|read[ -]?only|no (?:file )?(?:writes?|mutations?)|without modifying|scope|safety|safe(?:ty)?|only modify|do not publish)\b/.test(normalized);
566529
+ if (constraint || requestedIntent === "constraint")
566530
+ return "constraint";
566531
+ const priority = /\b(?:prioriti[sz]e|priority|urgent|first|before .*?(?:else|anything)|defer|hold|focus on|instead of)\b/.test(normalized);
566532
+ if (priority || requestedIntent === "priority_change") {
566533
+ return "priority_change";
566534
+ }
566535
+ if (requestedIntent === "context_only")
566536
+ return "context_only";
566537
+ return "context_only";
566538
+ }
566539
+ function steeringRequiresReconciliation(intent) {
566540
+ return intent !== "cancel";
566541
+ }
566542
+ function steeringGatesOldPlan(intent) {
566543
+ return intent === "constraint" || intent === "priority_change";
566544
+ }
566516
566545
  function createSteeringIngress(input) {
566517
566546
  return {
566518
566547
  id: randomUUID16(),
@@ -578644,8 +578673,11 @@ function isControllerStateMessage(message2) {
578644
578673
  function isActionGroundTruthMessage(message2) {
578645
578674
  return typeof message2.content === "string" && message2.content.includes(ACTION_GROUND_TRUTH_MARKER);
578646
578675
  }
578676
+ function isActiveSteeringMessage(message2) {
578677
+ return typeof message2.content === "string" && message2.content.includes("[ACTIVE USER STEERING]");
578678
+ }
578647
578679
  function isProtectedControllerMessage(message2) {
578648
- return isControllerStateMessage(message2) || isActionGroundTruthMessage(message2);
578680
+ return isControllerStateMessage(message2) || isActionGroundTruthMessage(message2) || isActiveSteeringMessage(message2);
578649
578681
  }
578650
578682
  function modelFacingMessageCap(message2) {
578651
578683
  if (isControllerStateMessage(message2)) {
@@ -578654,6 +578686,9 @@ function modelFacingMessageCap(message2) {
578654
578686
  if (isActionGroundTruthMessage(message2)) {
578655
578687
  return MODEL_FACING_ACTION_GROUND_TRUTH_CHAR_CAP;
578656
578688
  }
578689
+ if (isActiveSteeringMessage(message2)) {
578690
+ return Math.max(MODEL_FACING_ACTION_GROUND_TRUTH_CHAR_CAP, 7e3);
578691
+ }
578657
578692
  if (message2.role === "tool")
578658
578693
  return MODEL_FACING_TOOL_CHAR_CAP;
578659
578694
  if (message2.role === "system")
@@ -578701,7 +578736,7 @@ function applyModelFacingBudget(messages2, preserveFirstSystem) {
578701
578736
  const message2 = messages2[index];
578702
578737
  const content = messageText(message2.content);
578703
578738
  const isReservedTransactionMessage = reservedTransaction.has(index);
578704
- const isPriorityIntent = message2.role === "user" || isCurrentGoalMessage(message2);
578739
+ const isPriorityIntent = message2.role === "user" || isCurrentGoalMessage(message2) || isActiveSteeringMessage(message2);
578705
578740
  const perMessageCap = modelFacingMessageCap(message2);
578706
578741
  const isProtectedController = isProtectedControllerMessage(message2);
578707
578742
  const allowed = isReservedTransactionMessage ? perMessageCap : isPriorityIntent ? content.length : isProtectedController ? perMessageCap : Math.min(remaining, perMessageCap);
@@ -578724,7 +578759,7 @@ function collapseWhitespace(text2) {
578724
578759
  return text2.replace(/\r\n/g, "\n").split("\n").map((line) => line.trimEnd()).join("\n").replace(/\n{3,}/g, "\n\n").trim();
578725
578760
  }
578726
578761
  function sanitizeModelVisibleContextText(text2) {
578727
- let out = String(text2 ?? "");
578762
+ let out = stripNoThinkPromptDirectives(String(text2 ?? ""));
578728
578763
  out = out.replace(RUNTIME_GUIDANCE_RE, (_match, inner) => {
578729
578764
  return `[runtime_guidance]
578730
578765
  ${String(inner ?? "").trim()}`;
@@ -578739,6 +578774,18 @@ ${out}`.trim();
578739
578774
  }
578740
578775
  return collapseWhitespace(out);
578741
578776
  }
578777
+ function stripNoThinkFromMessageContent(content) {
578778
+ if (typeof content === "string")
578779
+ return stripNoThinkPromptDirectives(content);
578780
+ if (!Array.isArray(content))
578781
+ return content;
578782
+ return content.map((part) => {
578783
+ if (!part || typeof part !== "object")
578784
+ return part;
578785
+ const rec = part;
578786
+ return rec["type"] === "text" && typeof rec["text"] === "string" ? { ...rec, text: stripNoThinkPromptDirectives(rec["text"]) } : part;
578787
+ });
578788
+ }
578742
578789
  function messageText(content) {
578743
578790
  if (typeof content === "string")
578744
578791
  return content;
@@ -578932,7 +578979,11 @@ function prepareModelFacingApiMessages(input) {
578932
578979
  });
578933
578980
  const independentlyBounded = splitOversizedSystemMessages(withoutLegacyControl);
578934
578981
  for (let index = 0; index < independentlyBounded.length; index++) {
578935
- const message2 = independentlyBounded[index];
578982
+ const rawMessage = independentlyBounded[index];
578983
+ const message2 = {
578984
+ ...rawMessage,
578985
+ content: stripNoThinkFromMessageContent(rawMessage.content)
578986
+ };
578936
578987
  if (message2.role === "system" && typeof message2.content === "string") {
578937
578988
  if (preserveFirstSystem && sanitized.length === 0) {
578938
578989
  sanitized.push({ ...message2 });
@@ -579110,6 +579161,7 @@ var init_context_compiler = __esm({
579110
579161
  "packages/orchestrator/dist/context-compiler.js"() {
579111
579162
  "use strict";
579112
579163
  init_context_fabric();
579164
+ init_textSanitize();
579113
579165
  MODEL_FACING_CONTEXT_CHAR_BUDGET = 48e3;
579114
579166
  MODEL_FACING_TOOL_CHAR_CAP = 6e3;
579115
579167
  MODEL_FACING_SYSTEM_CHAR_CAP = 8e3;
@@ -579727,6 +579779,9 @@ function analyzeContextWindowDumpRequest(request) {
579727
579779
  };
579728
579780
  }
579729
579781
  function contextSourceForMessage(role, text2) {
579782
+ if (/\[ACTIVE USER STEERING\]/.test(text2)) {
579783
+ return "active_user_steering";
579784
+ }
579730
579785
  if (/\[ACTIVE USER INTENT\]|\[CURRENT USER GOAL\]/.test(text2)) {
579731
579786
  return "current_user_intent";
579732
579787
  }
@@ -579864,7 +579919,7 @@ function isRawDiscoveryToolResult(text2) {
579864
579919
  const isDiscovery = DISCOVERY_SOURCE_TOOLS.some((t2) => text2.includes(t2));
579865
579920
  if (!isDiscovery)
579866
579921
  return false;
579867
- return !text2.includes("[DISCOVERY COMPACTED") && !text2.includes("[DISCOVERY BOUNDED") && !text2.includes("[STOP RE-READING") && !text2.includes("[BRANCH-EXTRACT]");
579922
+ return !text2.includes("[DISCOVERY COMPACTED") && !text2.includes("[DISCOVERY BOUNDED") && !text2.includes("[STOP RE-READING") && !/^\[BRANCH-EXTRACT(?:\s+v\d+)?\]/m.test(text2);
579868
579923
  }
579869
579924
  function toSummary(record, path16) {
579870
579925
  const { request: _request, ...summary } = record;
@@ -584623,6 +584678,7 @@ function buildBranchExtractionBrief(input) {
584623
584678
  maxWindowsPerRound: 3,
584624
584679
  maxTotalWindows: MAX_WINDOWS,
584625
584680
  maxPresentedLines: MAX_SNIPPET_LINES,
584681
+ maxPresentedChars: MAX_PRESENTED_CHARS,
584626
584682
  maxInjectedChars: 2400
584627
584683
  }
584628
584684
  };
@@ -584962,7 +585018,8 @@ async function extractEvidence(opts) {
584962
585018
  });
584963
585019
  const requiredIds = requirements.filter((requirement) => requirement.required).map((requirement) => requirement.id);
584964
585020
  const deterministicSatisfied = new Set(deterministic.satisfied);
584965
- if (deterministic.segments.length > 0 && requiredIds.every((id2) => deterministicSatisfied.has(id2))) {
585021
+ const deterministicComplete = deterministic.segments.length > 0 && requiredIds.every((id2) => deterministicSatisfied.has(id2));
585022
+ if (deterministicComplete && !backend) {
584966
585023
  const claim = renderSegments(deterministic.segments, maxInjectedChars);
584967
585024
  const legacySpan = legacyContiguousSpan(deterministic.segments);
584968
585025
  return {
@@ -584999,6 +585056,7 @@ async function extractEvidence(opts) {
584999
585056
  const searchRounds = [...deterministic.rounds];
585000
585057
  let remainingWindows = Math.min(MAX_WINDOWS, brief.discoveryContract?.budget.maxTotalWindows ?? MAX_WINDOWS);
585001
585058
  let remainingPresentedLines = Math.min(MAX_SNIPPET_LINES, brief.discoveryContract?.budget.maxPresentedLines ?? MAX_SNIPPET_LINES);
585059
+ let remainingPresentedChars = Math.min(MAX_PRESENTED_CHARS, brief.discoveryContract?.budget.maxPresentedChars ?? MAX_PRESENTED_CHARS);
585002
585060
  if (backend) {
585003
585061
  const maxSemanticRounds = Math.max(0, (brief.discoveryContract?.budget.maxRounds ?? 3) - searchRounds.length);
585004
585062
  for (let attempt = 0; attempt < Math.min(2, maxSemanticRounds); attempt++) {
@@ -585013,10 +585071,13 @@ async function extractEvidence(opts) {
585013
585071
  if (selectedWindows.length >= perRound)
585014
585072
  break;
585015
585073
  const windowLines = window2.end - window2.start + 1;
585016
- if (windowLines > remainingPresentedLines)
585074
+ const windowChars = window2.text.length;
585075
+ if (windowLines > remainingPresentedLines || windowChars > remainingPresentedChars) {
585017
585076
  continue;
585077
+ }
585018
585078
  selectedWindows.push(window2);
585019
585079
  remainingPresentedLines -= windowLines;
585080
+ remainingPresentedChars -= windowChars;
585020
585081
  }
585021
585082
  remainingWindows -= selectedWindows.length;
585022
585083
  const relativeWindows = selectedWindows.map((window2) => ({
@@ -585215,7 +585276,7 @@ function assessBranchRead(input) {
585215
585276
  ...input.requestedRange ? { requestedRange: input.requestedRange } : {}
585216
585277
  };
585217
585278
  }
585218
- var MAX_WINDOWS, SNIPPET_CONTEXT, HEAD_LINES2, MAX_SNIPPET_LINES, EXTRACT_CONFIDENCE_FLOOR, STOPWORDS2, DEFAULT_BRANCH_READ_CONTEXT_FRACTION;
585279
+ var MAX_WINDOWS, SNIPPET_CONTEXT, HEAD_LINES2, MAX_SNIPPET_LINES, MAX_PRESENTED_CHARS, EXTRACT_CONFIDENCE_FLOOR, STOPWORDS2, DEFAULT_BRANCH_READ_CONTEXT_FRACTION;
585219
585280
  var init_evidenceBranch = __esm({
585220
585281
  "packages/orchestrator/dist/evidenceBranch.js"() {
585221
585282
  "use strict";
@@ -585223,6 +585284,7 @@ var init_evidenceBranch = __esm({
585223
585284
  SNIPPET_CONTEXT = 4;
585224
585285
  HEAD_LINES2 = 10;
585225
585286
  MAX_SNIPPET_LINES = 220;
585287
+ MAX_PRESENTED_CHARS = 24e3;
585226
585288
  EXTRACT_CONFIDENCE_FLOOR = 0.3;
585227
585289
  STOPWORDS2 = /* @__PURE__ */ new Set([
585228
585290
  "the",
@@ -588139,34 +588201,6 @@ function stripThinkBlocks(s2) {
588139
588201
  return s2;
588140
588202
  return s2.replace(/<think>[\s\S]*?<\/think>/g, "").trim();
588141
588203
  }
588142
- function injectNoThinkDirective(messages2) {
588143
- if (!Array.isArray(messages2) || messages2.length === 0)
588144
- return messages2;
588145
- let lastUserIdx = -1;
588146
- for (let i2 = messages2.length - 1; i2 >= 0; i2--) {
588147
- if (messages2[i2]?.role === "user") {
588148
- lastUserIdx = i2;
588149
- break;
588150
- }
588151
- }
588152
- if (lastUserIdx === -1)
588153
- return messages2;
588154
- const target = messages2[lastUserIdx];
588155
- if (!target || typeof target.content !== "string")
588156
- return messages2;
588157
- const hasOllamaNoThink = /\/nothink\b/i.test(target.content);
588158
- const hasQwenNoThink = /\/no[_-]think\b/i.test(target.content);
588159
- if (hasOllamaNoThink && hasQwenNoThink)
588160
- return messages2;
588161
- const suffix = [
588162
- hasOllamaNoThink ? null : "/nothink",
588163
- hasQwenNoThink ? null : "/no_think"
588164
- ].filter(Boolean).join("\n");
588165
- const annotated = `${target.content}
588166
-
588167
- ${suffix}`;
588168
- return messages2.map((m2, i2) => i2 === lastUserIdx ? { ...m2, content: annotated } : m2);
588169
- }
588170
588204
  function backendHttpErrorDetail(text2) {
588171
588205
  const trimmed = text2.trimStart();
588172
588206
  const isHtml = trimmed.startsWith("<!") || trimmed.startsWith("<html");
@@ -588238,7 +588272,7 @@ function sanitizeHistoryThink(messages2) {
588238
588272
  if (m2.role === "assistant") {
588239
588273
  content = stripThinkBlocks(content);
588240
588274
  }
588241
- content = content.replace(/\/nothink\b/gi, "").replace(/\/no[_-]think\b/gi, "");
588275
+ content = stripNoThinkPromptDirectives(content);
588242
588276
  if (m2.role === "assistant") {
588243
588277
  const collapsed = collapseDegenerateAssistantRepetition(content);
588244
588278
  content = collapsed ?? content;
@@ -588612,6 +588646,10 @@ var init_agenticRunner = __esm({
588612
588646
  /** Abort scope for only the in-flight model/tool turn. Never use for permanent stop. */
588613
588647
  _turnAbortController = new AbortController();
588614
588648
  _pendingSteeringPreemption = null;
588649
+ /** One authoritative, request-protected steering state; never reconstructed from transcript. */
588650
+ _activeSteering = null;
588651
+ /** Logical turn currently making a model/tool decision across both run loops. */
588652
+ _currentSteeringTurn = 0;
588615
588653
  pendingRuntimeGuidanceMessages = [];
588616
588654
  aborted = false;
588617
588655
  _abortController = new AbortController();
@@ -597176,7 +597214,7 @@ Rewrite it now for ${ctx3.model}.`;
597176
597214
  inlineTokens: 0,
597177
597215
  reservations: /* @__PURE__ */ new Map()
597178
597216
  };
597179
- const preempted = await this._preemptFileReadWithBranch({
597217
+ const extracted = await this._extractFileReadEvidence({
597180
597218
  callId,
597181
597219
  toolName: resolved.name,
597182
597220
  args,
@@ -597184,8 +597222,8 @@ Rewrite it now for ${ctx3.model}.`;
597184
597222
  turn: this._taskState.toolCallCount,
597185
597223
  batchBudget
597186
597224
  });
597187
- if (preempted)
597188
- return preempted;
597225
+ if (extracted)
597226
+ return extracted;
597189
597227
  let result = await tool.execute(args);
597190
597228
  result = await this._guardMaterializedFileReadResult({
597191
597229
  callId,
@@ -597239,7 +597277,7 @@ ${notice}`;
597239
597277
  content,
597240
597278
  source: "legacy-injectUserMessage",
597241
597279
  receivedAt: (/* @__PURE__ */ new Date()).toISOString(),
597242
- intent: "append",
597280
+ intent: classifySteeringIntent(content, "append"),
597243
597281
  state: "received",
597244
597282
  taskEpoch: this._taskEpoch || void 0
597245
597283
  });
@@ -597258,6 +597296,7 @@ ${notice}`;
597258
597296
  content,
597259
597297
  source: input.source || "unknown",
597260
597298
  receivedAt: input.receivedAt || now2,
597299
+ intent: classifySteeringIntent(content, input.intent),
597261
597300
  state: "received",
597262
597301
  taskEpoch: input.taskEpoch ?? (this._taskEpoch || void 0)
597263
597302
  };
@@ -597268,9 +597307,17 @@ ${notice}`;
597268
597307
  this._emitSteeringLifecycle(record, "empty steering input rejected");
597269
597308
  return this._steeringReceipt(record);
597270
597309
  }
597271
- this.pendingUserMessages.push(content);
597272
597310
  record.state = "queued";
597273
597311
  this._emitSteeringLifecycle(record, "queued for next safe turn boundary");
597312
+ if (steeringGatesOldPlan(record.intent)) {
597313
+ this._activeSteering = {
597314
+ input: record,
597315
+ appliedTurn: this._currentSteeringTurn,
597316
+ requiresReconciliation: true,
597317
+ gatesOldPlan: true,
597318
+ visibleRequestTurns: []
597319
+ };
597320
+ }
597274
597321
  if (record.intent === "redirect" || record.intent === "replace" || record.intent === "cancel") {
597275
597322
  this._requestSteeringPreemption(record);
597276
597323
  }
@@ -597319,18 +597366,15 @@ ${notice}`;
597319
597366
  /** Retract the last pending user message (Esc cancel).
597320
597367
  * Returns the retracted text, or null if queue is empty or already consumed. */
597321
597368
  retractLastPendingMessage() {
597322
- if (this.pendingUserMessages.length === 0)
597369
+ const record = [...this.pendingSteeringInputs].reverse().find((candidate) => candidate.state === "queued" || candidate.state === "acknowledged");
597370
+ if (!record)
597323
597371
  return null;
597324
- const content = this.pendingUserMessages.pop();
597325
- const record = [...this.pendingSteeringInputs].reverse().find((candidate) => candidate.content === content && (candidate.state === "queued" || candidate.state === "acknowledged"));
597326
- if (record) {
597327
- record.state = "cancelled";
597328
- if (this._pendingSteeringPreemption?.inputId === record.inputId) {
597329
- this._pendingSteeringPreemption = null;
597330
- }
597331
- this._emitSteeringLifecycle(record, "retracted before consumption");
597372
+ record.state = "cancelled";
597373
+ if (this._pendingSteeringPreemption?.inputId === record.inputId) {
597374
+ this._pendingSteeringPreemption = null;
597332
597375
  }
597333
- return content;
597376
+ this._emitSteeringLifecycle(record, "retracted before admission at a safe boundary");
597377
+ return record.content;
597334
597378
  }
597335
597379
  /** Abort the current task run — cancels in-flight requests and kills child processes */
597336
597380
  abort() {
@@ -597393,6 +597437,16 @@ ${notice}`;
597393
597437
  steering: receipt,
597394
597438
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
597395
597439
  });
597440
+ this._onTypedEvent?.({
597441
+ type: "steering_lifecycle",
597442
+ runId: this.currentArtifactRunId(),
597443
+ inputId: record.inputId,
597444
+ intent: record.intent,
597445
+ state: record.state,
597446
+ taskEpoch: record.taskEpoch,
597447
+ summary: reason,
597448
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
597449
+ });
597396
597450
  appendSteeringLedgerEntry(this._workingDirectory || process.cwd(), {
597397
597451
  type: "lifecycle",
597398
597452
  packetId: record.inputId,
@@ -597427,9 +597481,6 @@ ${notice}`;
597427
597481
  if (record.taskEpoch && record.taskEpoch !== this._taskEpoch) {
597428
597482
  record.state = "superseded";
597429
597483
  this._emitSteeringLifecycle(record, "superseded by a later task run");
597430
- const index = this.pendingUserMessages.lastIndexOf(record.content);
597431
- if (index >= 0)
597432
- this.pendingUserMessages.splice(index, 1);
597433
597484
  continue;
597434
597485
  }
597435
597486
  record.taskEpoch = this._taskEpoch;
@@ -597463,13 +597514,31 @@ ${notice}`;
597463
597514
  this._supersededTodoIds.add(todo.id);
597464
597515
  this._workboard = null;
597465
597516
  }
597466
- _steeringRecordForContent(content) {
597467
- return this.pendingSteeringInputs.find((record) => record.content === content && (record.state === "queued" || record.state === "acknowledged") && record.taskEpoch === this._taskEpoch);
597517
+ _activateSteering(record, turn) {
597518
+ const requiresReconciliation = steeringRequiresReconciliation(record.intent);
597519
+ const gatesOldPlan = steeringGatesOldPlan(record.intent);
597520
+ const prior = this._activeSteering;
597521
+ if (prior && prior.input.inputId !== record.inputId && !prior.reconciliation && (record.intent === "redirect" || record.intent === "replace")) {
597522
+ prior.input.state = "superseded";
597523
+ this._emitSteeringLifecycle(prior.input, `superseded by ${record.intent} ${record.inputId}`);
597524
+ }
597525
+ this._activeSteering = {
597526
+ input: record,
597527
+ appliedTurn: turn,
597528
+ requiresReconciliation,
597529
+ gatesOldPlan,
597530
+ visibleRequestTurns: []
597531
+ };
597532
+ if (requiresReconciliation) {
597533
+ record.state = "reconciliation_required";
597534
+ this._emitSteeringLifecycle(record, gatesOldPlan ? `admitted at turn ${turn}; old-plan actions are gated pending structured reconciliation` : `admitted at turn ${turn}; awaiting structured reconciliation`);
597535
+ }
597468
597536
  }
597469
597537
  _canonicalReadEvidencePayload(canonicalPath, contentHash2) {
597470
597538
  const branch = this._branchEvidenceByPath.get(canonicalPath);
597471
- if (branch && branch.contentHash === contentHash2)
597539
+ if (branch && branch.contentHash === contentHash2 && branch.taskEpoch === this._taskEpoch) {
597472
597540
  return branch.output;
597541
+ }
597473
597542
  return null;
597474
597543
  }
597475
597544
  _rehydrateResolvedReadEvidence(input) {
@@ -597519,33 +597588,38 @@ ${notice}`;
597519
597588
  }
597520
597589
  async _drainPendingSteeringMessages(messages2, turn) {
597521
597590
  this.drainPendingRuntimeGuidance(turn);
597522
- while (this.pendingUserMessages.length > 0) {
597523
- const userMsg = this.pendingUserMessages.shift();
597524
- const record = this._steeringRecordForContent(userMsg);
597591
+ const pending2 = this.pendingSteeringInputs.filter((record) => (record.state === "queued" || record.state === "acknowledged") && (!record.taskEpoch || record.taskEpoch === this._taskEpoch));
597592
+ for (const record of pending2) {
597525
597593
  const replacement = this._pendingSteeringPreemption;
597526
- if (replacement?.intent === "replace" && record && record.inputId !== replacement.inputId) {
597594
+ if (replacement?.intent === "replace" && record.inputId !== replacement.inputId) {
597527
597595
  record.state = "superseded";
597528
597596
  this._emitSteeringLifecycle(record, `superseded before consumption by replacement ${replacement.inputId}`);
597529
597597
  continue;
597530
597598
  }
597531
- await this.appendInjectedUserMessage(userMsg, messages2, turn);
597532
- if (record) {
597533
- record.state = "consumed";
597534
- this._emitSteeringLifecycle(record, `consumed at turn ${turn}`);
597535
- }
597599
+ await this.appendInjectedUserMessage(record.content, messages2, turn);
597600
+ this._activateSteering(record, turn);
597601
+ }
597602
+ while (this.pendingUserMessages.length > 0) {
597603
+ await this.appendInjectedUserMessage(this.pendingUserMessages.shift(), messages2, turn);
597536
597604
  }
597537
597605
  }
597538
- /** Apply a preemption only at a safe boundary after its user content is visible. */
597539
- _applyPendingSteeringPreemption(messages2, turn) {
597606
+ /**
597607
+ * The only legal steering boundary for every runner loop. It materializes
597608
+ * typed input, applies epoch preemption, and deliberately never equates
597609
+ * transcript insertion with model acknowledgement.
597610
+ */
597611
+ async _applySteeringAtSafeBoundary(messages2, turn) {
597612
+ this._currentSteeringTurn = turn;
597613
+ await this._drainPendingSteeringMessages(messages2, turn);
597540
597614
  const record = this._pendingSteeringPreemption;
597541
597615
  if (!record)
597542
- return false;
597616
+ return "continue";
597543
597617
  this._pendingSteeringPreemption = null;
597544
597618
  if (record.intent === "cancel") {
597545
597619
  record.state = "cancelled";
597546
597620
  this._emitSteeringLifecycle(record, `cancelled active task at turn ${turn}`);
597547
597621
  this.abort();
597548
- return true;
597622
+ return "abort";
597549
597623
  }
597550
597624
  const previousEpoch = this._taskEpoch;
597551
597625
  this._archiveSupersededTaskState(previousEpoch, record);
@@ -597576,19 +597650,155 @@ ${notice}`;
597576
597650
  this._completionIncompleteVerification = null;
597577
597651
  this._taskState.goal = record.content;
597578
597652
  this._taskState.originalGoal = record.content;
597579
- messages2.push({
597580
- role: "system",
597581
- content: [
597582
- "[ACTIVE USER STEERING - HIGHEST USER PRIORITY]",
597583
- `inputId=${record.inputId} taskEpoch=${this._taskEpoch} intent=${record.intent}`,
597584
- "The prior task epoch is historical evidence only. Do not continue its plan, todos, recovery cards, or completion contract.",
597585
- "Replan from this active user instruction before any further tool call:",
597586
- record.content
597587
- ].join("\n")
597588
- });
597589
- record.state = "consumed";
597590
- this._emitSteeringLifecycle(record, `applied at turn ${turn}; epoch ${previousEpoch} -> ${this._taskEpoch}`);
597591
- return true;
597653
+ this._activateSteering(record, turn);
597654
+ this._emitSteeringLifecycle(record, `epoch transition applied at turn ${turn}; ${previousEpoch} -> ${this._taskEpoch}`);
597655
+ return "restart";
597656
+ }
597657
+ /** A single late, protected steering slot rendered for every request until acknowledgement. */
597658
+ _renderActiveSteeringSlot() {
597659
+ const active = this._activeSteering;
597660
+ if (!active)
597661
+ return null;
597662
+ const { input, reconciliation } = active;
597663
+ if (reconciliation && reconciliation.status !== "needs_clarification") {
597664
+ return null;
597665
+ }
597666
+ const needsClarification = reconciliation?.status === "needs_clarification";
597667
+ return [
597668
+ "[ACTIVE USER STEERING]",
597669
+ `input_id=${input.inputId}`,
597670
+ `task_epoch=${input.taskEpoch ?? this._taskEpoch}`,
597671
+ `kind=${input.intent}`,
597672
+ `admission=${active.gatesOldPlan ? "old_plan_gated" : "context_active"}`,
597673
+ "This is current user authority, not historical transcript context.",
597674
+ input.intent === "redirect" || input.intent === "replace" ? "The prior task epoch is historical evidence only. Do not continue its plan, todos, recovery cards, or completion contract." : null,
597675
+ needsClarification ? "You requested clarification. Do not call tools or resume the old plan; ask the user one concise question." : active.requiresReconciliation ? [
597676
+ "Before any tool call, respond with exactly one structured reconciliation and no tool calls in that response:",
597677
+ "[STEERING_RECONCILIATION]",
597678
+ JSON.stringify({
597679
+ inputId: input.inputId,
597680
+ status: "applied | not_applicable | needs_clarification",
597681
+ changedConstraints: ["concrete constraint or []"],
597682
+ revisedNextAction: "one concrete next action"
597683
+ }),
597684
+ "[/STEERING_RECONCILIATION]"
597685
+ ].join("\n") : null,
597686
+ "User instruction:",
597687
+ input.content.slice(0, 6e3),
597688
+ "[/ACTIVE USER STEERING]"
597689
+ ].filter(Boolean).join("\n");
597690
+ }
597691
+ _markActiveSteeringVisible(turn) {
597692
+ const active = this._activeSteering;
597693
+ if (!active || active.reconciliation || active.visibleRequestTurns.includes(turn))
597694
+ return;
597695
+ active.visibleRequestTurns.push(turn);
597696
+ active.input.state = "visible_in_request";
597697
+ this._emitSteeringLifecycle(active.input, `visible in model request at turn ${turn}`);
597698
+ }
597699
+ _firstJsonObject(text2) {
597700
+ const start2 = text2.indexOf("{");
597701
+ if (start2 < 0)
597702
+ return null;
597703
+ let depth = 0;
597704
+ let quoted = false;
597705
+ let escaped = false;
597706
+ for (let index = start2; index < text2.length; index++) {
597707
+ const char = text2[index];
597708
+ if (quoted) {
597709
+ if (escaped)
597710
+ escaped = false;
597711
+ else if (char === "\\")
597712
+ escaped = true;
597713
+ else if (char === '"')
597714
+ quoted = false;
597715
+ continue;
597716
+ }
597717
+ if (char === '"')
597718
+ quoted = true;
597719
+ else if (char === "{")
597720
+ depth++;
597721
+ else if (char === "}") {
597722
+ depth--;
597723
+ if (depth === 0)
597724
+ return text2.slice(start2, index + 1);
597725
+ }
597726
+ }
597727
+ return null;
597728
+ }
597729
+ /** Parse and validate the model's explicit acknowledgement, never a vague textual mention. */
597730
+ _reconcileActiveSteeringFromModel(content, turn) {
597731
+ const active = this._activeSteering;
597732
+ if (!active || !active.requiresReconciliation || !content)
597733
+ return false;
597734
+ const tagged = content.match(/\[STEERING_RECONCILIATION\]([\s\S]*?)(?:\[\/STEERING_RECONCILIATION\]|$)/i);
597735
+ if (!tagged)
597736
+ return false;
597737
+ const candidate = this._firstJsonObject(tagged[1] ?? "");
597738
+ if (!candidate)
597739
+ return false;
597740
+ try {
597741
+ const parsed = JSON.parse(candidate);
597742
+ const status = parsed["status"];
597743
+ const inputId = parsed["inputId"];
597744
+ if (inputId !== active.input.inputId || status !== "applied" && status !== "not_applicable" && status !== "needs_clarification") {
597745
+ return false;
597746
+ }
597747
+ const changedConstraints = Array.isArray(parsed["changedConstraints"]) ? parsed["changedConstraints"].filter((item) => typeof item === "string").map((item) => item.trim()).filter(Boolean).slice(0, 12) : [];
597748
+ const revisedNextAction = typeof parsed["revisedNextAction"] === "string" ? parsed["revisedNextAction"].trim().slice(0, 1e3) : "";
597749
+ if (!revisedNextAction)
597750
+ return false;
597751
+ active.reconciliation = {
597752
+ inputId: active.input.inputId,
597753
+ status,
597754
+ changedConstraints,
597755
+ revisedNextAction
597756
+ };
597757
+ active.reconciledTurn = turn;
597758
+ active.requiresReconciliation = status === "needs_clarification";
597759
+ active.gatesOldPlan = status === "needs_clarification";
597760
+ this._taskState.nextAction = revisedNextAction;
597761
+ if (changedConstraints.length > 0) {
597762
+ this._taskState.steeringConstraints = [
597763
+ .../* @__PURE__ */ new Set([...this._taskState.steeringConstraints ?? [], ...changedConstraints])
597764
+ ].slice(-20);
597765
+ }
597766
+ active.input.state = "reconciled";
597767
+ this._emitSteeringLifecycle(active.input, `reconciled by model at turn ${turn}: ${status}`);
597768
+ return true;
597769
+ } catch {
597770
+ return false;
597771
+ }
597772
+ }
597773
+ _steeringToolGate(turn) {
597774
+ const active = this._activeSteering;
597775
+ if (!active || !active.gatesOldPlan)
597776
+ return null;
597777
+ if (!active.reconciliation) {
597778
+ return `[STEERING_RECONCILIATION_REQUIRED]
597779
+ input_id=${active.input.inputId}
597780
+ Do not execute the old-plan tool call. First emit the exact [STEERING_RECONCILIATION] JSON required by ACTIVE USER STEERING.`;
597781
+ }
597782
+ if (active.reconciliation.status === "needs_clarification") {
597783
+ return `[STEERING_CLARIFICATION_REQUIRED]
597784
+ input_id=${active.input.inputId}
597785
+ The model requested user clarification. Do not execute tools or resume the old plan.`;
597786
+ }
597787
+ if (active.reconciledTurn === turn) {
597788
+ return `[STEERING_REPLAN_TURN_REQUIRED]
597789
+ input_id=${active.input.inputId}
597790
+ The steering reconciliation was emitted this turn. Wait for the next model decision before executing a tool.`;
597791
+ }
597792
+ return null;
597793
+ }
597794
+ _markFirstSteeringAffectedAction(toolName, turn) {
597795
+ const active = this._activeSteering;
597796
+ if (!active || !active.reconciliation || active.reconciliation.status === "needs_clarification" || active.firstAffectedAction || active.reconciledTurn === turn) {
597797
+ return;
597798
+ }
597799
+ active.firstAffectedAction = { toolName, turn };
597800
+ active.input.state = "first_affected_action";
597801
+ this._emitSteeringLifecycle(active.input, `first affected action ${toolName} started at turn ${turn}`);
597592
597802
  }
597593
597803
  /**
597594
597804
  * Pause the current task gracefully. The run loop will suspend at the next
@@ -597783,12 +597993,13 @@ ${notice}`;
597783
597993
  }
597784
597994
  }
597785
597995
  /**
597786
- * Mandatory pre-dispatch router for local file reads. It resolves exactly
597787
- * once against the authoritative run directory, computes the actual selected
597788
- * range, and intercepts unsafe reads before registered tool code or any
597789
- * transcript/evidence consumer can observe raw content.
597996
+ * Mandatory on-read extraction path for local file reads. It resolves
597997
+ * exactly once against the authoritative run directory, creates an isolated
597998
+ * inference frame when the selected range cannot safely enter the parent
597999
+ * context, and returns only the verified evidence frame. Registered tool
598000
+ * code and parent transcript consumers never observe the raw oversized body.
597790
598001
  */
597791
- async _preemptFileReadWithBranch(input) {
598002
+ async _extractFileReadEvidence(input) {
597792
598003
  if (this.lookupRegisteredTool(input.toolName)?.name !== "file_read") {
597793
598004
  return null;
597794
598005
  }
@@ -597846,7 +598057,8 @@ ${notice}`;
597846
598057
  });
597847
598058
  const contractFingerprint = _createHash("sha256").update(JSON.stringify(branchBrief.discoveryContract ?? branchBrief)).digest("hex").slice(0, 20);
597848
598059
  const canonicalPath = this._normalizeEvidencePath(rawPath);
597849
- const cacheKey = `${canonicalPath}|${fullHash}|${offset ?? 0}:${limit ?? "EOF"}|${contractFingerprint}`;
598060
+ const branchRequestId = `branch:${this._taskEpoch}:${_createHash("sha256").update(`${canonicalPath}|${fullHash}|${offset ?? 0}:${limit ?? "EOF"}|${contractFingerprint}`).digest("hex").slice(0, 20)}`;
598061
+ const cacheKey = `${this._taskEpoch}|${canonicalPath}|${fullHash}|${offset ?? 0}:${limit ?? "EOF"}|${contractFingerprint}`;
597850
598062
  const cached2 = this._branchEvidenceCache.get(cacheKey);
597851
598063
  if (cached2) {
597852
598064
  const fingerprint = this._buildToolFingerprint(input.toolName, input.args);
@@ -597875,6 +598087,17 @@ ${notice}`;
597875
598087
  branchSourceBytes: cached2.sourceBytes,
597876
598088
  branchCacheHit: true,
597877
598089
  fingerprintState: "resolved_from_cache"
598090
+ },
598091
+ branchEvidence: {
598092
+ schema: "omnius.branch-evidence.v1",
598093
+ requestId: cached2.requestId,
598094
+ taskEpoch: this._taskEpoch,
598095
+ path: canonicalPath,
598096
+ contentHash: fullHash,
598097
+ sourceRange: {
598098
+ startLine: startIndex + 1,
598099
+ endLine: startIndex + Math.max(1, selectedLines.length)
598100
+ }
597878
598101
  }
597879
598102
  };
597880
598103
  }
@@ -597892,6 +598115,7 @@ ${notice}`;
597892
598115
  });
597893
598116
  const verboseOutput = [
597894
598117
  `[BRANCH-EXTRACT v2] path=${rawPath}`,
598118
+ `[VERIFIED_RUNTIME_FILE_READ] request_id=${branchRequestId} task_epoch=${this._taskEpoch}`,
597895
598119
  `routing=mandatory reasons=${decision2.reasons.join(",")} projected_read_tokens=${decision2.projectedReadTokens} fraction_limit_tokens=${decision2.fractionLimitTokens} available_headroom_tokens=${decision2.availableHeadroomTokens}`,
597896
598120
  `source=sha256:${fullHash} selected_lines=${selectedLines.length} selected_bytes=${selectedBytes}${hasRange ? ` range=${offset ?? 1}:${limit ?? "EOF"}` : " range=whole"}`,
597897
598121
  `[DISCOVERY CONTRACT]`,
@@ -597913,6 +598137,7 @@ ${notice}`;
597913
598137
  const required = (branchBrief.discoveryContract?.requirements ?? []).filter((requirement) => requirement.required).map((requirement) => `${requirement.id}:${requirement.question.slice(0, 180)}`).join(" | ");
597914
598138
  const prefix = [
597915
598139
  `[BRANCH-EXTRACT v2] path=${rawPath} sha256=${fullHash}`,
598140
+ `[VERIFIED_RUNTIME_FILE_READ] request_id=${branchRequestId} task_epoch=${this._taskEpoch}`,
597916
598141
  `routing=${decision2.reasons.join(",")} projected=${decision2.projectedReadTokens}/${contextWindow}t limit=${decision2.fractionLimitTokens}t`,
597917
598142
  `[DISCOVERY CONTRACT] required=${required || "next narrow file-local fact"}`,
597918
598143
  `[CURATED SEGMENTS]`
@@ -597932,17 +598157,20 @@ ${suffix}`.slice(0, outputBudgetChars);
597932
598157
  path: canonicalPath,
597933
598158
  contentHash: fullHash,
597934
598159
  sourceBytes: stat9.size,
597935
- createdAt: Date.now()
598160
+ createdAt: Date.now(),
598161
+ taskEpoch: this._taskEpoch,
598162
+ requestId: branchRequestId
597936
598163
  });
597937
598164
  this._branchEvidenceByPath.set(canonicalPath, {
597938
598165
  output,
597939
598166
  contentHash: fullHash,
597940
- mtimeMs: stat9.mtimeMs
598167
+ mtimeMs: stat9.mtimeMs,
598168
+ taskEpoch: this._taskEpoch
597941
598169
  });
597942
598170
  this.emit({
597943
598171
  type: "status",
597944
598172
  toolName: input.toolName,
597945
- content: `Branch-extract preempted ${rawPath}: ${decision2.projectedReadTokens}/${contextWindow} projected tokens (${(decision2.projectedFraction * 100).toFixed(1)}%); resident=${residentTokens}t reserve=${reservedTokens}t pending_reads=${input.batchBudget.inlineTokens}t; ${selectedBytes}B → ${output.length} curated chars; reasons=${decision2.reasons.join(",")}`,
598173
+ content: `Branch extraction executed for file_read ${rawPath}: ${decision2.projectedReadTokens}/${contextWindow} projected tokens (${(decision2.projectedFraction * 100).toFixed(1)}%); resident=${residentTokens}t reserve=${reservedTokens}t pending_reads=${input.batchBudget.inlineTokens}t; ${selectedBytes}B → ${output.length} curated chars; reasons=${decision2.reasons.join(",")}`,
597946
598174
  turn: input.turn,
597947
598175
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
597948
598176
  });
@@ -597958,6 +598186,17 @@ ${suffix}`.slice(0, outputBudgetChars);
597958
598186
  branchSourceBytes: stat9.size,
597959
598187
  branchSelectedBytes: selectedBytes,
597960
598188
  branchProjectedTokens: decision2.projectedReadTokens
598189
+ },
598190
+ branchEvidence: {
598191
+ schema: "omnius.branch-evidence.v1",
598192
+ requestId: branchRequestId,
598193
+ taskEpoch: this._taskEpoch,
598194
+ path: canonicalPath,
598195
+ contentHash: fullHash,
598196
+ sourceRange: {
598197
+ startLine: startIndex + 1,
598198
+ endLine: startIndex + Math.max(1, selectedLines.length)
598199
+ }
597961
598200
  }
597962
598201
  };
597963
598202
  }
@@ -598017,6 +598256,7 @@ ${suffix}`.slice(0, outputBudgetChars);
598017
598256
  });
598018
598257
  const output = [
598019
598258
  `[BRANCH-EXTRACT v2] path=${path16}`,
598259
+ `[VERIFIED_RUNTIME_FILE_READ] request_id=branch:${this._taskEpoch}:${input.callId} task_epoch=${this._taskEpoch}`,
598020
598260
  `routing=post-execution-failsafe reasons=${decision2.reasons.join(",")} projected_read_tokens=${decision2.projectedReadTokens}`,
598021
598261
  `[DISCOVERY CONTRACT] ${brief.request}`,
598022
598262
  `[CURATED SEGMENTS]`,
@@ -598035,6 +598275,17 @@ ${suffix}`.slice(0, outputBudgetChars);
598035
598275
  branchSourceBytes: Buffer.byteLength(input.result.output, "utf8"),
598036
598276
  branchSelectedBytes: Buffer.byteLength(input.result.output, "utf8"),
598037
598277
  branchProjectedTokens: decision2.projectedReadTokens
598278
+ },
598279
+ branchEvidence: {
598280
+ schema: "omnius.branch-evidence.v1",
598281
+ requestId: `branch:${this._taskEpoch}:${input.callId}`,
598282
+ taskEpoch: this._taskEpoch,
598283
+ path: this._normalizeEvidencePath(path16),
598284
+ contentHash: ev.provenance.contentHash,
598285
+ sourceRange: {
598286
+ startLine: 1,
598287
+ endLine: Math.max(1, lines.length)
598288
+ }
598038
598289
  }
598039
598290
  };
598040
598291
  }
@@ -600926,9 +601177,9 @@ Respond with EXACTLY this structure before your next tool call:
600926
601177
  });
600927
601178
  }
600928
601179
  }
600929
- await this._drainPendingSteeringMessages(messages2, turn);
600930
- if (this._applyPendingSteeringPreemption(messages2, turn)) {
600931
- if (this.aborted)
601180
+ const steeringBoundary = await this._applySteeringAtSafeBoundary(messages2, turn);
601181
+ if (steeringBoundary !== "continue") {
601182
+ if (steeringBoundary === "abort" || this.aborted)
600932
601183
  break;
600933
601184
  continue;
600934
601185
  }
@@ -601338,6 +601589,11 @@ ${memoryLines.join("\n")}`
601338
601589
  role: "system",
601339
601590
  content: this._buildRecentActionGroundTruth(turn)
601340
601591
  });
601592
+ const activeSteeringSlot = this._renderActiveSteeringSlot();
601593
+ if (activeSteeringSlot) {
601594
+ requestMessages.push({ role: "system", content: activeSteeringSlot });
601595
+ this._markActiveSteeringVisible(turn);
601596
+ }
601341
601597
  this._retireLinkedAssistantReadIntents(requestMessages);
601342
601598
  const chatRequest = {
601343
601599
  messages: requestMessages,
@@ -601726,6 +601982,7 @@ ${memoryLines.join("\n")}`
601726
601982
  if (!choice)
601727
601983
  break;
601728
601984
  const msg = choice.message;
601985
+ this._reconcileActiveSteeringFromModel(msg.content, turn);
601729
601986
  const isThinkOnly = response._thinkOnly === true;
601730
601987
  const isEmptyResponse = !isThinkOnly && (!msg.content || !msg.content.trim()) && (!msg.toolCalls || msg.toolCalls.length === 0);
601731
601988
  if (isEmptyResponse) {
@@ -601827,6 +602084,18 @@ ${memoryLines.join("\n")}`
601827
602084
  executeSingle = async (tc) => {
601828
602085
  if (this.aborted || this._pendingSteeringPreemption)
601829
602086
  return null;
602087
+ const steeringGate = this._steeringToolGate(this._currentSteeringTurn);
602088
+ if (steeringGate) {
602089
+ this.emit({
602090
+ type: "status",
602091
+ toolName: tc.name,
602092
+ content: `Tool call gated by active user steering ${this._activeSteering?.input.inputId ?? "unknown"}`,
602093
+ turn: this._currentSteeringTurn,
602094
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
602095
+ });
602096
+ return { tc, output: steeringGate, success: false };
602097
+ }
602098
+ this._markFirstSteeringAffectedAction(tc.name, this._currentSteeringTurn);
601830
602099
  const resolvedReadBlock = this._rejectRepeatedResolvedRead(tc, messages2);
601831
602100
  if (resolvedReadBlock) {
601832
602101
  this.emit({
@@ -602476,12 +602745,11 @@ Read the current file if needed, make a different concrete edit, or move to veri
602476
602745
  const exactReadPath = String(exactReadArgs?.["path"] ?? exactReadArgs?.["file"] ?? "");
602477
602746
  const exactReadEvidence = exactReadEvidenceEpochs.get(toolFingerprint);
602478
602747
  const exactReadEvidenceFresh = tc.name === "file_read" && exactReadPath.length > 0 && this._evidenceLedger.validateFreshness(this._normalizeEvidencePath(exactReadPath), this._absoluteToolPath(exactReadPath));
602479
- const exactReadEvidenceEntry = tc.name === "file_read" && exactReadPath ? this._evidenceLedger.get(this._normalizeEvidencePath(exactReadPath)) : void 0;
602480
- const exactReadHasCuratedPayload = exactReadEvidenceEntry?.fidelity === "extract";
602481
- if (tc.name === "file_read" && exactReadEvidenceFresh && exactReadHasCuratedPayload && exactReadEvidence?.taskEpoch === this._taskEpoch && exactReadEvidence.mutationEpoch === fileMutationEpoch) {
602748
+ if (tc.name === "file_read" && exactReadEvidenceFresh && exactReadEvidence?.taskEpoch === this._taskEpoch && exactReadEvidence.mutationEpoch === fileMutationEpoch) {
602482
602749
  const path16 = this._normalizeEvidencePath(exactReadPath);
602483
602750
  const evidence = this._evidenceLedger.get(path16);
602484
- const curated = this._branchEvidenceByPath.get(path16) ?? [...this._branchEvidenceByPath.entries()].find(([candidate]) => this._normalizeEvidencePath(candidate) === path16)?.[1];
602751
+ const rawCurated = this._branchEvidenceByPath.get(path16) ?? [...this._branchEvidenceByPath.entries()].find(([candidate]) => this._normalizeEvidencePath(candidate) === path16)?.[1];
602752
+ const curated = rawCurated?.taskEpoch === this._taskEpoch ? rawCurated : void 0;
602485
602753
  const curatedPayload = curated?.output ?? (evidence?.fidelity === "extract" && evidence.content.includes("[BRANCH-EXTRACT") ? evidence.content : null);
602486
602754
  repeatShortCircuit = {
602487
602755
  success: true,
@@ -602581,11 +602849,12 @@ Read the current file if needed, make a different concrete edit, or move to veri
602581
602849
  }
602582
602850
  }
602583
602851
  const exactReadEvidence2 = exactReadEvidenceEpochs.get(toolFingerprint);
602584
- const exactFileReadReference = tc.name === "file_read" && exactReadEvidenceFresh2 && exactReadHasCuratedPayload && exactReadEvidence2?.taskEpoch === this._taskEpoch && exactReadEvidence2.mutationEpoch === fileMutationEpoch;
602852
+ const exactFileReadReference = tc.name === "file_read" && exactReadEvidenceFresh2 && exactReadEvidence2?.taskEpoch === this._taskEpoch && exactReadEvidence2.mutationEpoch === fileMutationEpoch;
602585
602853
  if (exactFileReadReference) {
602586
602854
  const path16 = this._normalizeEvidencePath(String(tc.arguments?.["path"] ?? tc.arguments?.["file"] ?? ""));
602587
602855
  const evidence = this._evidenceLedger?.get(path16);
602588
- const curated = this._branchEvidenceByPath.get(path16) ?? [...this._branchEvidenceByPath.entries()].find(([candidate]) => this._normalizeEvidencePath(candidate) === path16)?.[1];
602856
+ const rawCurated = this._branchEvidenceByPath.get(path16) ?? [...this._branchEvidenceByPath.entries()].find(([candidate]) => this._normalizeEvidencePath(candidate) === path16)?.[1];
602857
+ const curated = rawCurated?.taskEpoch === this._taskEpoch ? rawCurated : void 0;
602589
602858
  const curatedPayload = curated?.output ?? (evidence?.fidelity === "extract" && evidence.content.includes("[BRANCH-EXTRACT") ? evidence.content : null);
602590
602859
  repeatShortCircuit = {
602591
602860
  success: true,
@@ -602918,7 +603187,7 @@ ${cachedResult}`,
602918
603187
  try {
602919
603188
  tc.arguments = finalArgs;
602920
603189
  const normalizedDispatchName = resolvedTool?.name ?? tc.name;
602921
- let branchPreempted = null;
603190
+ let branchEvidenceResult = null;
602922
603191
  if (normalizedDispatchName === "file_read") {
602923
603192
  const exactReadKey = this._buildToolFingerprint("file_read", tc.arguments);
602924
603193
  const priorRead = exactFileReadObservations.get(exactReadKey);
@@ -602935,7 +603204,7 @@ ${cachedResult}`,
602935
603204
  payload: canonicalPayload,
602936
603205
  turn
602937
603206
  });
602938
- branchPreempted = {
603207
+ branchEvidenceResult = {
602939
603208
  success: true,
602940
603209
  output: rehydrated,
602941
603210
  llmContent: rehydrated,
@@ -602962,7 +603231,7 @@ ${cachedResult}`,
602962
603231
  `path=${currentRead.path}`,
602963
603232
  "No canonical payload was produced by the allowed narrow reread. Change scope with a new range or symbol query; do not repeat identical arguments."
602964
603233
  ].join("\n");
602965
- branchPreempted = {
603234
+ branchEvidenceResult = {
602966
603235
  success: true,
602967
603236
  output: fallbackBlocked,
602968
603237
  llmContent: fallbackBlocked,
@@ -602995,8 +603264,8 @@ ${cachedResult}`,
602995
603264
  }
602996
603265
  }
602997
603266
  }
602998
- if (!branchPreempted) {
602999
- branchPreempted = await this._preemptFileReadWithBranch({
603267
+ if (!branchEvidenceResult) {
603268
+ branchEvidenceResult = await this._extractFileReadEvidence({
603000
603269
  callId: tc.id,
603001
603270
  toolName: normalizedDispatchName,
603002
603271
  args: tc.arguments,
@@ -603005,8 +603274,8 @@ ${cachedResult}`,
603005
603274
  batchBudget: branchReadBatchBudget
603006
603275
  });
603007
603276
  }
603008
- if (branchPreempted) {
603009
- result = branchPreempted;
603277
+ if (branchEvidenceResult) {
603278
+ result = branchEvidenceResult;
603010
603279
  fileReadSafetyChecked = true;
603011
603280
  } else {
603012
603281
  if (typeof tool.executeStream === "function") {
@@ -603261,6 +603530,7 @@ ${cachedResult}`,
603261
603530
  taskEpoch: this._taskEpoch,
603262
603531
  mutationEpoch: fileMutationEpoch
603263
603532
  });
603533
+ this._registerReadCoverage("file_read", tc.arguments, toolFingerprint);
603264
603534
  }
603265
603535
  if (this._fileSummaryStore && result.success && result.output && result.output.length > 100) {
603266
603536
  try {
@@ -605316,9 +605586,7 @@ Only call task_complete when the task is actually complete and the evidence is f
605316
605586
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
605317
605587
  });
605318
605588
  }
605319
- const pendingBeforeAdversary = this.pendingUserMessages.length;
605320
605589
  this.adversaryObserve(messages2, turn);
605321
- const adversaryAddedGuidance = this.pendingUserMessages.length > pendingBeforeAdversary;
605322
605590
  if (/task.?complete|all tests pass/i.test(content)) {
605323
605591
  const completionArgs = { summary: content };
605324
605592
  if (holdTaskCompleteGates(completionArgs, turn)) {
@@ -605378,13 +605646,6 @@ Your most recent tool calls SUCCEEDED. If the task is complete, call task_comple
605378
605646
  role: "system",
605379
605647
  content: this._textEchoGuard.buildIntervention(echoObs)
605380
605648
  });
605381
- if (adversaryAddedGuidance) {
605382
- this.drainPendingRuntimeGuidance(turn);
605383
- while (this.pendingUserMessages.length > 0) {
605384
- const userMsg = this.pendingUserMessages.shift();
605385
- await this.appendInjectedUserMessage(userMsg, messages2, turn);
605386
- }
605387
- }
605388
605649
  continue;
605389
605650
  }
605390
605651
  }
@@ -605417,6 +605678,18 @@ Your most recent tool calls SUCCEEDED. If the task is complete, call task_comple
605417
605678
  }
605418
605679
  const shellTool = this.tools.get("shell");
605419
605680
  if (shellTool) {
605681
+ const steeringGate = this._steeringToolGate(this._currentSteeringTurn);
605682
+ if (steeringGate) {
605683
+ messages2.push({ role: "system", content: steeringGate });
605684
+ this.emit({
605685
+ type: "status",
605686
+ content: "Narrated shell code block blocked by active user steering",
605687
+ turn,
605688
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
605689
+ });
605690
+ continue;
605691
+ }
605692
+ this._markFirstSteeringAffectedAction("shell", this._currentSteeringTurn);
605420
605693
  this.emit({
605421
605694
  type: "status",
605422
605695
  content: `Auto-executing code block: ${shellCommands.slice(0, 80)}...`,
@@ -605478,13 +605751,6 @@ Your most recent tool calls SUCCEEDED. If the task is complete, call task_comple
605478
605751
  content: "Continue working. Use tools to read files, make changes, and run validation. Call task_complete when done."
605479
605752
  });
605480
605753
  }
605481
- if (adversaryAddedGuidance) {
605482
- this.drainPendingRuntimeGuidance(turn);
605483
- while (this.pendingUserMessages.length > 0) {
605484
- const userMsg = this.pendingUserMessages.shift();
605485
- await this.appendInjectedUserMessage(userMsg, messages2, turn);
605486
- }
605487
- }
605488
605754
  }
605489
605755
  try {
605490
605756
  const turnLogTail = toolCallLog.filter((t2) => t2.turn === turn || t2.turn === void 0);
@@ -605641,10 +605907,11 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
605641
605907
  });
605642
605908
  nextSelfEval = bfNow + selfEvalInterval;
605643
605909
  }
605644
- this.drainPendingRuntimeGuidance(turn);
605645
- while (this.pendingUserMessages.length > 0) {
605646
- const userMsg = this.pendingUserMessages.shift();
605647
- await this.appendInjectedUserMessage(userMsg, messages2, turn);
605910
+ const steeringBoundary = await this._applySteeringAtSafeBoundary(messages2, turn);
605911
+ if (steeringBoundary !== "continue") {
605912
+ if (steeringBoundary === "abort" || this.aborted)
605913
+ break;
605914
+ continue;
605648
605915
  }
605649
605916
  let compactedMsgs;
605650
605917
  if (this._pendingCompaction) {
@@ -605680,6 +605947,11 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
605680
605947
  role: "system",
605681
605948
  content: this._buildRecentActionGroundTruth(turn)
605682
605949
  });
605950
+ const activeSteeringSlot = this._renderActiveSteeringSlot();
605951
+ if (activeSteeringSlot) {
605952
+ modelFacingMessages.push({ role: "system", content: activeSteeringSlot });
605953
+ this._markActiveSteeringVisible(turn);
605954
+ }
605683
605955
  const chatRequest = {
605684
605956
  messages: modelFacingMessages,
605685
605957
  tools: toolDefs,
@@ -605804,6 +606076,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
605804
606076
  if (!choice)
605805
606077
  break;
605806
606078
  const msg = choice.message;
606079
+ this._reconcileActiveSteeringFromModel(msg.content, turn);
605807
606080
  const isThinkOnlyBF = response._thinkOnly === true;
605808
606081
  if (msg.toolCalls && msg.toolCalls.length > 0) {
605809
606082
  consecutiveTextOnly = 0;
@@ -607012,7 +607285,7 @@ ${marker}` : marker);
607012
607285
  ].filter(Boolean).join("\n"));
607013
607286
  }
607014
607287
  shouldBypassDiscoveryCompaction(output) {
607015
- 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);
607288
+ return output.includes("[IMAGE_BASE64:") || /^\[BRANCH-EXTRACT(?:\s+v\d+)?\]/m.test(output) || 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);
607016
607289
  }
607017
607290
  countTextLines(text2) {
607018
607291
  if (!text2)
@@ -609359,7 +609632,7 @@ ${telegramPersonaHead}` : stripped
609359
609632
  const canonicalPath = this._normalizeEvidencePath(filePath);
609360
609633
  const branchNode = this._branchEvidenceByPath.get(canonicalPath);
609361
609634
  const currentMtime = this._statMtimeMsForToolPath(filePath) ?? 0;
609362
- if (branchNode && branchNode.mtimeMs === currentMtime) {
609635
+ if (branchNode && branchNode.taskEpoch === this._taskEpoch && branchNode.mtimeMs === currentMtime) {
609363
609636
  const nodeTokens = Math.ceil(branchNode.output.length / 4);
609364
609637
  if (recoveredTokens + nodeTokens > fileRecoveryBudget)
609365
609638
  continue;
@@ -612350,7 +612623,7 @@ ${description}`
612350
612623
  if (effectiveThink === true && (effectiveMaxTokens ?? 0) < 4096) {
612351
612624
  effectiveMaxTokens = 4096;
612352
612625
  }
612353
- const requestMessages = effectiveThink ? cleanedMessages : injectNoThinkDirective(cleanedMessages);
612626
+ const requestMessages = cleanedMessages;
612354
612627
  const responseFormat = request.responseFormat ?? request.response_format;
612355
612628
  const isOllama = shouldUseOllamaPoolForBaseUrl(this.baseUrl);
612356
612629
  const body = {
@@ -612486,7 +612759,7 @@ ${description}`
612486
612759
  }
612487
612760
  }
612488
612761
  if (shouldRetryThinkGuard || shouldRecoverFromEmpty) {
612489
- const retryMessages = injectNoThinkDirective(requestMessages);
612762
+ const retryMessages = requestMessages;
612490
612763
  const retryBody = {
612491
612764
  model: this.model,
612492
612765
  messages: retryMessages,
@@ -612567,7 +612840,7 @@ ${description}`
612567
612840
  }
612568
612841
  async nativeOllamaChatCompletion(request) {
612569
612842
  const cleanedMessages = applyMemoryPrefixToMessages(normalizeMessagesForStrictOpenAI(sanitizeHistoryThink(request.messages)), request.memoryPrefix);
612570
- const requestMessages = injectNoThinkDirective(cleanedMessages);
612843
+ const requestMessages = cleanedMessages;
612571
612844
  const responseFormat = request.responseFormat ?? request.response_format;
612572
612845
  const options2 = {
612573
612846
  temperature: request.temperature,
@@ -612751,7 +613024,7 @@ ${description}`
612751
613024
  if (effectiveThink === true && (effectiveMaxTokens ?? 0) < 4096) {
612752
613025
  effectiveMaxTokens = 4096;
612753
613026
  }
612754
- const requestMessages = effectiveThink ? cleanedMessages : injectNoThinkDirective(cleanedMessages);
613027
+ const requestMessages = cleanedMessages;
612755
613028
  const responseFormat = request.responseFormat ?? request.response_format;
612756
613029
  const body = {
612757
613030
  model: this.model,
@@ -613036,6 +613309,7 @@ var NexusAgenticBackend;
613036
613309
  var init_nexusBackend = __esm({
613037
613310
  "packages/orchestrator/dist/nexusBackend.js"() {
613038
613311
  "use strict";
613312
+ init_textSanitize();
613039
613313
  NexusAgenticBackend = class _NexusAgenticBackend {
613040
613314
  sendFn;
613041
613315
  model;
@@ -613066,32 +613340,10 @@ var init_nexusBackend = __esm({
613066
613340
  return this.thinking === true;
613067
613341
  }
613068
613342
  noThinkMessages(messages2) {
613069
- let lastUserIdx = -1;
613070
- for (let i2 = messages2.length - 1; i2 >= 0; i2--) {
613071
- if (messages2[i2]?.role === "user") {
613072
- lastUserIdx = i2;
613073
- break;
613074
- }
613075
- }
613076
- if (lastUserIdx < 0)
613077
- return messages2;
613078
- const target = messages2[lastUserIdx];
613079
- if (!target || typeof target.content !== "string")
613080
- return messages2;
613081
- const hasOllamaNoThink = /\/nothink\b/i.test(target.content);
613082
- const hasQwenNoThink = /\/no[_-]think\b/i.test(target.content);
613083
- if (hasOllamaNoThink && hasQwenNoThink)
613084
- return messages2;
613085
- const suffix = [
613086
- hasOllamaNoThink ? null : "/nothink",
613087
- hasQwenNoThink ? null : "/no_think"
613088
- ].filter(Boolean).join("\n");
613089
- return messages2.map((m2, i2) => i2 === lastUserIdx ? { ...m2, content: `${target.content}
613090
-
613091
- ${suffix}` } : m2);
613343
+ return messages2.map((message2) => typeof message2.content === "string" ? { ...message2, content: stripNoThinkPromptDirectives(message2.content) } : message2);
613092
613344
  }
613093
613345
  requestMessages(request, effectiveThink) {
613094
- return effectiveThink ? request.messages : this.noThinkMessages(request.messages);
613346
+ return this.noThinkMessages(request.messages);
613095
613347
  }
613096
613348
  applyOptionalRequestFields(daemonArgs, request) {
613097
613349
  const responseFormat = request.responseFormat ?? request.response_format;
@@ -619640,6 +619892,7 @@ __export(dist_exports3, {
619640
619892
  classifyHandoff: () => classifyHandoff,
619641
619893
  classifyKind: () => classifyKind,
619642
619894
  classifyOllamaProcesses: () => classifyOllamaProcesses,
619895
+ classifySteeringIntent: () => classifySteeringIntent,
619643
619896
  cleanForStorage: () => cleanForStorage,
619644
619897
  cleanScaffolding: () => cleanScaffolding,
619645
619898
  cleanupStaleOllamaProcesses: () => cleanupStaleOllamaProcesses,
@@ -619858,6 +620111,9 @@ __export(dist_exports3, {
619858
620111
  skillShouldShow: () => skillShouldShow,
619859
620112
  specificityScore: () => specificityScore,
619860
620113
  stabilityFilePath: () => stabilityFilePath,
620114
+ steeringGatesOldPlan: () => steeringGatesOldPlan,
620115
+ steeringRequiresReconciliation: () => steeringRequiresReconciliation,
620116
+ stripNoThinkPromptDirectives: () => stripNoThinkPromptDirectives,
619861
620117
  stripThinkTags: () => stripThinkTags,
619862
620118
  stripXmlControlBlocks: () => stripXmlControlBlocks,
619863
620119
  stripYamlFrontmatter: () => stripYamlFrontmatter,
@@ -635229,8 +635485,8 @@ function formatBranchExtractSummary(output) {
635229
635485
  }
635230
635486
  }
635231
635487
  const isDuplicate = /^\[branch-duplicate-blocked\]/i.test(lines[0]);
635232
- const header = isDuplicate ? "Branch-extract duplicate reuse" : "Branch-extract preempted";
635233
- const whatHappened = isDuplicate ? "a cache-safe duplicate was detected" : "read was auto-summarized before injecting into context";
635488
+ const header = isDuplicate ? "Branch-extract duplicate reuse" : "Branch extraction completed";
635489
+ const whatHappened = isDuplicate ? "a cache-safe duplicate was detected" : "an isolated inference worker returned bounded, verified evidence";
635234
635490
  const out = [
635235
635491
  `↳ ${header}`,
635236
635492
  ` ├ what happened: ${whatHappened}`,
@@ -635296,7 +635552,7 @@ function summarizeInternalControlOutput(output) {
635296
635552
  if (!output) return null;
635297
635553
  const firstLine = output.split(/\r?\n/)[0]?.trim().toLowerCase() ?? "";
635298
635554
  const lower = output.toLowerCase();
635299
- if (firstLine.includes("[branch-extract") || firstLine.includes("[branch-duplicate-blocked]") || lower.includes("branch-extract preempted")) {
635555
+ if (firstLine.includes("[branch-extract") || firstLine.includes("[branch-duplicate-blocked]") || lower.includes("branch extraction executed") || lower.includes("branch extraction completed")) {
635300
635556
  return formatBranchExtractSummary(output);
635301
635557
  }
635302
635558
  if (firstLine.includes("[echo break") || firstLine.includes("[echo-break") || lower.includes("echo-1:")) {
@@ -663866,6 +664122,7 @@ var daemon_exports = {};
663866
664122
  __export(daemon_exports, {
663867
664123
  claimDaemonEndpoint: () => claimDaemonEndpoint,
663868
664124
  ensureDaemon: () => ensureDaemon,
664125
+ ensureDaemonVersion: () => ensureDaemonVersion,
663869
664126
  forceKillDaemon: () => forceKillDaemon,
663870
664127
  getDaemonPid: () => getDaemonPid,
663871
664128
  getDaemonReportedVersion: () => getDaemonReportedVersion,
@@ -664029,7 +664286,19 @@ async function getDaemonReportedVersion(port) {
664029
664286
  return null;
664030
664287
  }
664031
664288
  }
664032
- async function restartDaemon(port) {
664289
+ async function waitForDaemonReady(port, expectedVersion, attempts = 24) {
664290
+ let observedVersion = null;
664291
+ for (let attempt = 0; attempt < attempts; attempt++) {
664292
+ await new Promise((resolve82) => setTimeout(resolve82, 500));
664293
+ if (!await isDaemonRunning(port)) continue;
664294
+ observedVersion = await getDaemonReportedVersion(port);
664295
+ if (!expectedVersion || expectedVersion === "0.0.0" || observedVersion === expectedVersion) {
664296
+ return { ok: true, observedVersion };
664297
+ }
664298
+ }
664299
+ return { ok: false, observedVersion };
664300
+ }
664301
+ async function restartDaemon(port, expectedVersion) {
664033
664302
  const p2 = port ?? getDaemonPort();
664034
664303
  try {
664035
664304
  const { spawnSync: spawnSync9 } = await import("node:child_process");
@@ -664039,12 +664308,14 @@ async function restartDaemon(port) {
664039
664308
  });
664040
664309
  if (enabled2.status === 0) {
664041
664310
  spawnSync9("systemctl", ["--user", "restart", "omnius-daemon.service"], { stdio: "ignore", timeout: 2e4 });
664042
- return;
664311
+ return (await waitForDaemonReady(p2, expectedVersion)).ok;
664043
664312
  }
664044
664313
  } catch {
664045
664314
  }
664046
664315
  await forceKillDaemon(p2);
664047
- await startDaemon();
664316
+ const pid = await startDaemon();
664317
+ if (!pid) return false;
664318
+ return (await waitForDaemonReady(p2, expectedVersion)).ok;
664048
664319
  }
664049
664320
  function getDaemonPid() {
664050
664321
  if (!existsSync140(PID_FILE2)) return null;
@@ -664246,24 +664517,18 @@ async function forceKillDaemon(port) {
664246
664517
  }
664247
664518
  return killed;
664248
664519
  }
664249
- async function ensureDaemon() {
664250
- const port = getDaemonPort();
664520
+ async function ensureDaemonVersion(expectedVersion = getLocalCliVersion(), port = getDaemonPort()) {
664521
+ const finish = (ok3, action, observedVersion) => ({ ok: ok3, action, expectedVersion, observedVersion, port });
664251
664522
  if (await isDaemonRunning(port)) {
664252
664523
  if (process.env["OMNIUS_NO_VERSION_GUARD"] !== "1") {
664253
664524
  const running = await getDaemonReportedVersion(port);
664254
- const local = getLocalCliVersion();
664255
- if (running && local !== "0.0.0" && running !== local) {
664256
- await restartDaemon(port);
664257
- for (let i2 = 0; i2 < 24; i2++) {
664258
- await new Promise((r2) => setTimeout(r2, 500));
664259
- if (await isDaemonRunning(port) && await getDaemonReportedVersion(port) === local) {
664260
- return true;
664261
- }
664262
- }
664263
- return await isDaemonRunning(port);
664525
+ if (expectedVersion !== "0.0.0" && running !== expectedVersion) {
664526
+ const ok3 = await restartDaemon(port, expectedVersion);
664527
+ const observedVersion = await getDaemonReportedVersion(port);
664528
+ return finish(ok3 && observedVersion === expectedVersion, ok3 ? "restarted" : "failed", observedVersion);
664264
664529
  }
664265
664530
  }
664266
- return true;
664531
+ return finish(true, "unchanged", await getDaemonReportedVersion(port));
664267
664532
  }
664268
664533
  const stalePid = getDaemonPid();
664269
664534
  if (stalePid) {
@@ -664280,16 +664545,16 @@ async function ensureDaemon() {
664280
664545
  if (!pid) {
664281
664546
  for (let i2 = 0; i2 < 20; i2++) {
664282
664547
  await new Promise((r2) => setTimeout(r2, 500));
664283
- if (await isDaemonRunning(port)) return true;
664284
- }
664285
- return false;
664286
- }
664287
- for (let i2 = 0; i2 < 20; i2++) {
664288
- await new Promise((r2) => setTimeout(r2, 500));
664289
- if (await isDaemonRunning(port)) {
664290
- return true;
664548
+ if (await isDaemonRunning(port)) {
664549
+ const observedVersion = await getDaemonReportedVersion(port);
664550
+ const versionMatches = expectedVersion === "0.0.0" || observedVersion === expectedVersion;
664551
+ return finish(versionMatches, versionMatches ? "started" : "failed", observedVersion);
664552
+ }
664291
664553
  }
664554
+ return finish(false, "failed", null);
664292
664555
  }
664556
+ const ready = await waitForDaemonReady(port, expectedVersion, 20);
664557
+ if (ready.ok) return finish(true, "started", ready.observedVersion);
664293
664558
  try {
664294
664559
  process.kill(pid, "SIGTERM");
664295
664560
  } catch {
@@ -664299,7 +664564,10 @@ async function ensureDaemon() {
664299
664564
  } catch {
664300
664565
  }
664301
664566
  releaseDaemonEndpointForCurrentProcess(port);
664302
- return false;
664567
+ return finish(false, "failed", ready.observedVersion);
664568
+ }
664569
+ async function ensureDaemon() {
664570
+ return (await ensureDaemonVersion()).ok;
664303
664571
  }
664304
664572
  async function getDaemonStatus() {
664305
664573
  const port = getDaemonPort();
@@ -687908,6 +688176,23 @@ async function handleUpdate(subcommand, ctx3) {
687908
688176
  installOverlay.dismiss();
687909
688177
  return;
687910
688178
  }
688179
+ installOverlay.setPhase("Daemon");
688180
+ installOverlay.setStatus("Gracefully upgrading shared daemon...");
688181
+ const { ensureDaemonVersion: ensureDaemonVersion2, getLocalCliVersion: getLocalCliVersion2 } = await Promise.resolve().then(() => (init_daemon(), daemon_exports));
688182
+ const expectedDaemonVersion = getLocalCliVersion2();
688183
+ const daemonUpgrade = await ensureDaemonVersion2(expectedDaemonVersion);
688184
+ if (!daemonUpgrade.ok) {
688185
+ installOverlay.stop("Update installed, but daemon upgrade was not verified");
688186
+ await new Promise((r2) => setTimeout(r2, 1200));
688187
+ installOverlay.dismiss();
688188
+ renderError(
688189
+ `Updated CLI to ${expectedDaemonVersion}, but the shared daemon still reports ${daemonUpgrade.observedVersion ?? "unavailable"}. The TUI will remain open; retry /update after resolving the daemon service.`
688190
+ );
688191
+ return;
688192
+ }
688193
+ installOverlay.setStatus(
688194
+ daemonUpgrade.action === "restarted" ? `Daemon upgraded to ${expectedDaemonVersion}` : `Daemon verified at ${expectedDaemonVersion}`
688195
+ );
687911
688196
  registry2.killAll();
687912
688197
  ctx3.contextSave?.();
687913
688198
  const hadActiveTask = ctx3.savePendingTaskState?.() ?? false;
@@ -703031,34 +703316,9 @@ function telegramRouterDiagnosticIsDualEmptyVisible(diag) {
703031
703316
  return diag.jsonModeStatus === "empty-after-strip" && diag.plainStatus === "empty-after-strip";
703032
703317
  }
703033
703318
  function telegramThinkSuppressedRequest(request) {
703034
- const messages2 = Array.isArray(request.messages) ? request.messages.slice() : [];
703035
- let appended = false;
703036
- for (let i2 = messages2.length - 1; i2 >= 0; i2--) {
703037
- const m2 = messages2[i2];
703038
- if (!m2 || m2.role !== "user") continue;
703039
- const content = typeof m2.content === "string" ? m2.content : "";
703040
- const hasOllamaNoThink = /\/nothink\b/i.test(content);
703041
- const hasQwenNoThink = /\/no[_-]think\b/i.test(content);
703042
- if (hasOllamaNoThink && hasQwenNoThink) {
703043
- appended = true;
703044
- break;
703045
- }
703046
- const suffix = [
703047
- hasOllamaNoThink ? null : "/nothink",
703048
- hasQwenNoThink ? null : "/no_think"
703049
- ].filter(Boolean).join("\n");
703050
- messages2[i2] = {
703051
- ...m2,
703052
- content: content.endsWith("\n") ? `${content}${suffix}` : `${content}
703053
-
703054
- ${suffix}`
703055
- };
703056
- appended = true;
703057
- break;
703058
- }
703059
- if (!appended) {
703060
- messages2.push({ role: "user", content: "/nothink\n/no_think" });
703061
- }
703319
+ const messages2 = Array.isArray(request.messages) ? request.messages.map(
703320
+ (message2) => message2 && typeof message2.content === "string" ? { ...message2, content: stripNoThinkPromptDirectives(message2.content) } : message2
703321
+ ) : [];
703062
703322
  return { ...request, messages: messages2, think: false };
703063
703323
  }
703064
703324
  function parseTelegramInteractionDecision(text2, forcedRoute, options2 = {}) {
@@ -703511,7 +703771,7 @@ function isTelegramInternalControlText(text2) {
703511
703771
  /\[discovery contract\]/i,
703512
703772
  /\[curated segments\]/i,
703513
703773
  /\[branch-duplicate-blocked\]/i,
703514
- /branch-extract preempted/i,
703774
+ /branch extraction (?:executed|completed)/i,
703515
703775
  /contract: use these anchors as evidence/i,
703516
703776
  /\becho break\b/i
703517
703777
  ];
@@ -706879,7 +707139,11 @@ ${message2}`)
706879
707139
  if (/\?$/.test(text2) || /^(?:clarify|correction|to be clear)\b/.test(lower)) {
706880
707140
  return { intent: "clarify", reason: "plain-text clarification; scope preserved" };
706881
707141
  }
706882
- return { intent: "append", reason: "conservative plain-text intake; momentum preserved" };
707142
+ const classified = classifySteeringIntent(text2, "append");
707143
+ return {
707144
+ intent: classified,
707145
+ reason: classified === "constraint" || classified === "priority_change" ? "shared safety/scope/priority steering classifier" : "conservative context-only intake; momentum preserved"
707146
+ };
706883
707147
  }
706884
707148
  telegramIntakePath(sessionKey) {
706885
707149
  const digest3 = createHash49("sha256").update(sessionKey).digest("hex").slice(0, 20);
@@ -707051,13 +707315,16 @@ ${message2}`)
707051
707315
  if (!inputId) return;
707052
707316
  const record = this.telegramIntakeRecords.get(inputId);
707053
707317
  if (!record) return;
707054
- 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;
707318
+ const lifecycle = typed.type === "steering_lifecycle" ? typed.state === "received" ? "acknowledged" : typed.state === "visible_in_request" ? "visible_in_request" : typed.state === "reconciliation_required" ? "reconciliation_required" : typed.state === "reconciled" ? "reconciled" : typed.state === "first_affected_action" ? "first_affected_action" : typed.state === "cancelled" ? "cancelled" : typed.state === "superseded" ? "superseded" : null : typed.type === "steering_preempt_requested" ? "preempt_requested" : typed.type === "steering_preempted" ? "preempted" : typed.type === "steering_input_accepted" || typed.type === "steering_received" ? "accepted" : null;
707055
707319
  if (!lifecycle) return;
707056
707320
  void this.transitionTelegramIntake(
707057
707321
  record,
707058
707322
  lifecycle,
707059
- `runner lifecycle event: ${typed.type}`,
707060
- typeof typed.turn === "number" ? { runnerTurn: typed.turn } : {}
707323
+ typed.summary || `runner lifecycle event: ${typed.type}`,
707324
+ {
707325
+ ...typeof typed.turn === "number" ? { runnerTurn: typed.turn } : {},
707326
+ ...typeof typed.taskEpoch === "number" ? { taskEpoch: typed.taskEpoch } : {}
707327
+ }
707061
707328
  );
707062
707329
  }
707063
707330
  async replyWithTelegramHelp(msg, isAdmin) {
@@ -711612,9 +711879,7 @@ ${lines.join("\n")}`
711612
711879
  observationContext,
711613
711880
  "",
711614
711881
  `Current Telegram message text (untrusted user data):
711615
- ${this.quoteTelegramContextBlock(msg.text, 1200)}`,
711616
- "",
711617
- "/nothink\n/no_think"
711882
+ ${this.quoteTelegramContextBlock(msg.text, 1200)}`
711618
711883
  ].filter(Boolean).join("\n");
711619
711884
  try {
711620
711885
  const result = await this.telegramRouterJsonCompletion(
@@ -712112,10 +712377,7 @@ ${this.quoteTelegramContextBlock(msg.text, 1200)}`,
712112
712377
  TELEGRAM_INTERACTION_DECISION_REPAIR_SCHEMA,
712113
712378
  ``,
712114
712379
  `Original router output:`,
712115
- rawPreview,
712116
- ``,
712117
- `/nothink
712118
- /no_think`
712380
+ rawPreview
712119
712381
  ].join("\n");
712120
712382
  try {
712121
712383
  const result = await this.telegramRouterJsonCompletion(
@@ -712190,10 +712452,7 @@ ${userPrompt.slice(-4e3)}` : userPrompt;
712190
712452
  invalidPreview,
712191
712453
  ``,
712192
712454
  `Router context (trailing-window):`,
712193
- trimmedUserPrompt,
712194
- ``,
712195
- `/nothink
712196
- /no_think`
712455
+ trimmedUserPrompt
712197
712456
  ].join("\n");
712198
712457
  try {
712199
712458
  const result = await this.telegramRouterJsonCompletion(
@@ -744452,29 +744711,11 @@ async function writeMemoryEpisodes(sessionId, userMessage, assistantContent, too
744452
744711
  function sanitizeChatContent(raw) {
744453
744712
  return sanitizeAgentOutputForUser(raw);
744454
744713
  }
744455
- function appendNoThinkDirectivesToMessages(messages2) {
744456
- let lastUserIdx = -1;
744457
- for (let i2 = messages2.length - 1; i2 >= 0; i2--) {
744458
- if (messages2[i2]?.role === "user") {
744459
- lastUserIdx = i2;
744460
- break;
744461
- }
744462
- }
744463
- if (lastUserIdx < 0) return messages2;
744464
- const target = messages2[lastUserIdx];
744465
- if (!target || typeof target.content !== "string") return messages2;
744466
- const hasOllamaNoThink = /\/nothink\b/i.test(target.content);
744467
- const hasQwenNoThink = /\/no[_-]think\b/i.test(target.content);
744468
- if (hasOllamaNoThink && hasQwenNoThink) return messages2;
744469
- const suffix = [
744470
- hasOllamaNoThink ? null : "/nothink",
744471
- hasQwenNoThink ? null : "/no_think"
744472
- ].filter(Boolean).join("\n");
744473
- return messages2.map(
744474
- (m2, i2) => i2 === lastUserIdx ? { ...m2, content: `${target.content}
744475
-
744476
- ${suffix}` } : m2
744477
- );
744714
+ function sanitizeNoThinkTransportMessages(messages2) {
744715
+ return messages2.map((message2) => ({
744716
+ ...message2,
744717
+ content: stripNoThinkPromptDirectives(message2.content)
744718
+ }));
744478
744719
  }
744479
744720
  async function directChatBackend(opts) {
744480
744721
  const { model, messages: messages2, stream, res, sessionId, ollamaUrl, extraFields } = opts;
@@ -744605,7 +744846,7 @@ async function directChatBackend(opts) {
744605
744846
  const ollamaFormat = ollamaFormatFromOpenAIResponseFormat(
744606
744847
  ef["response_format"]
744607
744848
  );
744608
- const ollamaMessages = appendNoThinkDirectivesToMessages(messages2);
744849
+ const ollamaMessages = sanitizeNoThinkTransportMessages(messages2);
744609
744850
  const reqBody = JSON.stringify({
744610
744851
  model: cleanModel,
744611
744852
  messages: ollamaMessages,
@@ -744918,7 +745159,7 @@ async function completeRealtimeTextOnly(opts) {
744918
745159
  ) ?? originalModel;
744919
745160
  }
744920
745161
  const makeOllamaChatBody = (modelName) => {
744921
- const rtMessages = Array.isArray(requestBody["messages"]) ? appendNoThinkDirectivesToMessages(
745162
+ const rtMessages = Array.isArray(requestBody["messages"]) ? sanitizeNoThinkTransportMessages(
744922
745163
  requestBody["messages"]
744923
745164
  ) : requestBody["messages"];
744924
745165
  return JSON.stringify({
@@ -746593,7 +746834,7 @@ async function handleV1ChatCompletions(req3, res, ollamaUrl) {
746593
746834
  const finalThink = thinkingAllowed && callerProvidedThink ? routedBody["think"] : false;
746594
746835
  const ollamaBody = { ...routedBody };
746595
746836
  if (finalThink === false && Array.isArray(ollamaBody["messages"])) {
746596
- ollamaBody["messages"] = appendNoThinkDirectivesToMessages(
746837
+ ollamaBody["messages"] = sanitizeNoThinkTransportMessages(
746597
746838
  ollamaBody["messages"]
746598
746839
  );
746599
746840
  }
@@ -750547,25 +750788,6 @@ data: ${JSON.stringify(data)}
750547
750788
  jsonResponse(res, 200, { ok: true, enabled: config.torEnabled });
750548
750789
  return;
750549
750790
  }
750550
- if (pathname === "/v1/update" && method === "POST") {
750551
- const config = loadConfig();
750552
- config.updating = true;
750553
- try {
750554
- require4("./config").saveConfig?.(config);
750555
- } catch {
750556
- }
750557
- setImmediate(() => {
750558
- try {
750559
- const { execSync: execSync41 } = require4("node:child_process");
750560
- execSync41("npm update -g omnius 2>/dev/null || true", {
750561
- stdio: "pipe"
750562
- });
750563
- } catch {
750564
- }
750565
- });
750566
- jsonResponse(res, 200, { ok: true, message: "Update initiated" });
750567
- return;
750568
- }
750569
750791
  if (pathname === "/v1/share/generate" && method === "POST") {
750570
750792
  const body = await parseJsonBody(req3);
750571
750793
  const config = loadConfig();
@@ -758085,6 +758307,17 @@ ${entry.fullContent}`
758085
758307
  case "status":
758086
758308
  if (_apiCallbacks?.onStatus)
758087
758309
  _apiCallbacks.onStatus(event.content ?? "");
758310
+ if (event.steering) {
758311
+ const stage2 = event.steering.state.replace(/_/g, " ");
758312
+ const line = `Steering ${stage2}: ${event.content ?? event.steering.inputId}`;
758313
+ if (isNeovimActive()) {
758314
+ writeToNeovimOutput(`\x1B[38;5;81m${line}\x1B[0m\r
758315
+ `);
758316
+ } else {
758317
+ contentWrite(() => renderInfo(line));
758318
+ }
758319
+ break;
758320
+ }
758088
758321
  if (event.toolName === "shell" && liveShellBlock && !isNeovimActive()) {
758089
758322
  appendShellLiveChunk(liveShellBlock.state, event.content ?? "");
758090
758323
  scheduleLiveShellRepaint();
@@ -761122,26 +761355,15 @@ Log: ${nexusLogPath}`
761122
761355
  currentConfig.backendUrl
761123
761356
  );
761124
761357
  });
761125
- Promise.resolve().then(() => (init_daemon(), daemon_exports)).then(async ({ ensureDaemon: ensureDaemon2, isDaemonRunning: isDaemonRunning2 }) => {
761358
+ Promise.resolve().then(() => (init_daemon(), daemon_exports)).then(async ({ ensureDaemonVersion: ensureDaemonVersion2 }) => {
761126
761359
  const apiPort = parseInt(process.env["OMNIUS_PORT"] || "11435", 10);
761127
- if (await isDaemonRunning2(apiPort)) {
761128
- setTimeout(() => {
761129
- if (statusBar.isActive)
761130
- writeContent(
761131
- () => renderInfo(
761132
- `REST API: http://localhost:${apiPort} (shared daemon)`
761133
- )
761134
- );
761135
- }, 1500);
761136
- return;
761137
- }
761138
- const daemonOk = await ensureDaemon2();
761139
- if (daemonOk) {
761360
+ const daemon = await ensureDaemonVersion2();
761361
+ if (daemon.ok) {
761140
761362
  setTimeout(() => {
761141
761363
  if (statusBar.isActive)
761142
761364
  writeContent(
761143
761365
  () => renderInfo(
761144
- `REST API: http://localhost:${apiPort} (daemon started)`
761366
+ `REST API: http://localhost:${apiPort} (${daemon.action === "restarted" ? "daemon upgraded" : daemon.action === "started" ? "daemon started" : "shared daemon"})`
761145
761367
  )
761146
761368
  );
761147
761369
  }, 1500);
@@ -764328,7 +764550,14 @@ ${result.text}`;
764328
764550
  interpretation = null;
764329
764551
  }
764330
764552
  const packet = buildSteeringPacket(ingress, interpretation);
764331
- activeTask.runner.injectUserMessage(packet);
764553
+ activeTask.runner.injectSteeringInput({
764554
+ inputId: ingress.id,
764555
+ content: packet,
764556
+ source: "tui",
764557
+ receivedAt: ingress.timestamp,
764558
+ intent: isReplacement ? "replace" : classifySteeringIntent(input, "context_only"),
764559
+ state: "received"
764560
+ });
764332
764561
  activeTask.steeringPacketIds.add(ingress.id);
764333
764562
  appendSteeringLedgerEntry(repoRoot, {
764334
764563
  type: "ingress",