omnius 1.0.380 → 1.0.381

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
@@ -1033,8 +1033,8 @@ var init_model_broker = __esm({
1033
1033
  }
1034
1034
  /** Restore a set of previously evicted Ollama models, oldest first. */
1035
1035
  async restoreOllamaModels(models, options2 = {}) {
1036
- const unique2 = dedupeLoadedModels(models.filter((m2) => m2.host === "ollama")).sort((a2, b) => a2.lastUsedAt - b.lastUsedAt);
1037
- for (const model of unique2) {
1036
+ const unique3 = dedupeLoadedModels(models.filter((m2) => m2.host === "ollama")).sort((a2, b) => a2.lastUsedAt - b.lastUsedAt);
1037
+ for (const model of unique3) {
1038
1038
  await this.warmOllamaModel(model.name, options2.keepAlive ?? "30m").catch(() => false);
1039
1039
  }
1040
1040
  }
@@ -14187,8 +14187,8 @@ var init_unifiedMemoryStore = __esm({
14187
14187
  return matches.filter((match) => match.score >= (options2.minScore ?? 0)).sort((a2, b) => b.score - a2.score).slice(0, limit).map((match, index) => ({ ...match, rank: index + 1 }));
14188
14188
  }
14189
14189
  recordAccess(itemIds) {
14190
- const unique2 = [...new Set(itemIds)].filter(Boolean);
14191
- if (unique2.length === 0)
14190
+ const unique3 = [...new Set(itemIds)].filter(Boolean);
14191
+ if (unique3.length === 0)
14192
14192
  return;
14193
14193
  const update2 = this.db.prepare(`
14194
14194
  UPDATE memory_item
@@ -14198,7 +14198,7 @@ var init_unifiedMemoryStore = __esm({
14198
14198
  `);
14199
14199
  const now2 = this.nowIso();
14200
14200
  const txn = this.db.transaction(() => {
14201
- for (const id of unique2)
14201
+ for (const id of unique3)
14202
14202
  update2.run(now2, id);
14203
14203
  });
14204
14204
  txn();
@@ -498530,11 +498530,11 @@ ${options2.prefix}` : "\n" : options2.prefix
498530
498530
  return true;
498531
498531
  }
498532
498532
  const set = /* @__PURE__ */ new Map();
498533
- let unique2 = 0;
498533
+ let unique3 = 0;
498534
498534
  for (const v of arr1) {
498535
498535
  if (set.get(v) !== true) {
498536
498536
  set.set(v, true);
498537
- unique2++;
498537
+ unique3++;
498538
498538
  }
498539
498539
  }
498540
498540
  for (const v of arr2) {
@@ -498544,10 +498544,10 @@ ${options2.prefix}` : "\n" : options2.prefix
498544
498544
  }
498545
498545
  if (isSet === true) {
498546
498546
  set.set(v, false);
498547
- unique2--;
498547
+ unique3--;
498548
498548
  }
498549
498549
  }
498550
- return unique2 === 0;
498550
+ return unique3 === 0;
498551
498551
  }
498552
498552
  function typeAcquisitionChanged(opt1, opt2) {
498553
498553
  return opt1.enable !== opt2.enable || !setIsEqualTo(opt1.include, opt2.include) || !setIsEqualTo(opt1.exclude, opt2.exclude);
@@ -559210,9 +559210,9 @@ function deriveClaimsFromProposedText(input) {
559210
559210
  if (!raw)
559211
559211
  return [];
559212
559212
  const segments = raw.replace(/\b(?:done|completed|verified)\s*:\s*/gi, "").split(/(?:\n+|;\s+|,\s+(?=(?:and\s+)?(?:sent|built|created|updated|published|verified|tested|fixed|added|removed|deployed|wrote)\b)|\.\s+)/i).map((part) => cleanText(part, 300)).filter((part) => part.length > 0);
559213
- const unique2 = Array.from(new Set(segments.length > 0 ? segments : [cleanText(raw, 300)]));
559213
+ const unique3 = Array.from(new Set(segments.length > 0 ? segments : [cleanText(raw, 300)]));
559214
559214
  const existingIds = new Set((input.existing ?? []).map((claim) => claim.id));
559215
- return unique2.map((text2, index) => {
559215
+ return unique3.map((text2, index) => {
559216
559216
  const base3 = normalizeCompletionKey(text2, `claim_${index + 1}`).slice(0, 64);
559217
559217
  let id = base3 || `claim_${index + 1}`;
559218
559218
  let suffix = 2;
@@ -568681,6 +568681,7 @@ function recordContextWindowDump(input) {
568681
568681
  ...input.model ? { model: input.model } : {},
568682
568682
  cwd: cwd4,
568683
568683
  ...input.note ? { note: input.note } : {},
568684
+ ...input.focusSupervisor ? { focusSupervisor: compactFocusSupervisor(input.focusSupervisor) } : {},
568684
568685
  metrics: analyzeContextWindowDumpRequest(input.request),
568685
568686
  request: input.request
568686
568687
  };
@@ -568838,6 +568839,31 @@ function toSummary(record, path12) {
568838
568839
  const { request: _request, ...summary } = record;
568839
568840
  return { ...summary, path: path12 };
568840
568841
  }
568842
+ function compactFocusSupervisor(input) {
568843
+ const directive = input.directive ? {
568844
+ id: input.directive.id,
568845
+ state: input.directive.state,
568846
+ reason: trimString(input.directive.reason, 500),
568847
+ requiredNextAction: input.directive.requiredNextAction,
568848
+ forbiddenActionFamilies: input.directive.forbiddenActionFamilies?.slice(0, 12),
568849
+ createdTurn: input.directive.createdTurn,
568850
+ ignoredCount: input.directive.ignoredCount
568851
+ } : input.directive ?? null;
568852
+ return {
568853
+ mode: input.mode,
568854
+ enabled: input.enabled,
568855
+ state: input.state,
568856
+ lastDecision: input.lastDecision,
568857
+ lastReason: trimString(input.lastReason, 500),
568858
+ directive,
568859
+ ...input.context ? { context: input.context } : {}
568860
+ };
568861
+ }
568862
+ function trimString(value2, max) {
568863
+ if (typeof value2 !== "string" || !value2.trim())
568864
+ return void 0;
568865
+ return value2.trim().slice(0, max);
568866
+ }
568841
568867
  function safeId(value2) {
568842
568868
  return String(value2 || "unknown").replace(/[^a-zA-Z0-9_.:-]/g, "_").slice(0, 160);
568843
568869
  }
@@ -569216,6 +569242,338 @@ var init_adversaryStream = __esm({
569216
569242
  }
569217
569243
  });
569218
569244
 
569245
+ // packages/orchestrator/dist/focusSupervisor.js
569246
+ function resolveFocusSupervisorMode(configured, envValue = process.env["OMNIUS_FOCUS_SUPERVISOR"]) {
569247
+ if (configured)
569248
+ return configured;
569249
+ const normalized = String(envValue ?? "").trim().toLowerCase();
569250
+ if (normalized === "off" || normalized === "0" || normalized === "false") {
569251
+ return "off";
569252
+ }
569253
+ if (normalized === "strict")
569254
+ return "strict";
569255
+ return "auto";
569256
+ }
569257
+ function violatesDirective(directive, input) {
569258
+ if (input.toolName === "task_complete") {
569259
+ return directive.state === "terminal_incomplete";
569260
+ }
569261
+ const family = actionFamily(input.toolName, input.args);
569262
+ if (directive.forbiddenActionFamilies.includes(family))
569263
+ return true;
569264
+ if (directive.forbiddenActionFamilies.includes(input.toolName))
569265
+ return true;
569266
+ switch (directive.requiredNextAction) {
569267
+ case "update_todos":
569268
+ return input.toolName !== "todo_write";
569269
+ case "read_authoritative_target":
569270
+ return input.toolName !== "file_read";
569271
+ case "run_verification":
569272
+ return input.toolName !== "shell";
569273
+ case "report_blocked":
569274
+ case "report_incomplete":
569275
+ return input.toolName !== "task_complete";
569276
+ case "edit_different_target":
569277
+ return input.toolName === "shell" || input.isReadLike || directive.forbiddenActionFamilies.includes(family);
569278
+ case "use_cached_evidence":
569279
+ return directive.forbiddenActionFamilies.includes(family);
569280
+ default:
569281
+ return false;
569282
+ }
569283
+ }
569284
+ function actionFamily(toolName, args) {
569285
+ const target = args?.["path"] ?? args?.["file"] ?? args?.["filePath"] ?? args?.["file_path"] ?? args?.["command"] ?? args?.["cmd"] ?? "";
569286
+ return `${toolName}:${normalizeTarget(String(target ?? "")) || "no-target"}`;
569287
+ }
569288
+ function failureFamilyKey(toolName, args, error, output) {
569289
+ const sample = cleanFailureSample(error || output || "");
569290
+ return `${actionFamily(toolName, args)}:${sample}`;
569291
+ }
569292
+ function cleanFailureSample(text2) {
569293
+ return String(text2 || "").replace(/\s+/g, " ").trim().slice(0, 180);
569294
+ }
569295
+ function normalizeTarget(text2) {
569296
+ return text2.replace(/\s+/g, " ").trim().slice(0, 220);
569297
+ }
569298
+ function unique2(values) {
569299
+ return [...new Set(values.filter((value2) => value2.trim().length > 0))];
569300
+ }
569301
+ var directiveCounter, FocusSupervisor;
569302
+ var init_focusSupervisor = __esm({
569303
+ "packages/orchestrator/dist/focusSupervisor.js"() {
569304
+ "use strict";
569305
+ directiveCounter = 0;
569306
+ FocusSupervisor = class {
569307
+ mode;
569308
+ modelTier;
569309
+ repeatGateMax;
569310
+ state = "observe";
569311
+ directive = null;
569312
+ lastDecision = "pass";
569313
+ lastReason = "";
569314
+ lastContext = null;
569315
+ failureFamilies = /* @__PURE__ */ new Map();
569316
+ constructor(options2 = {}) {
569317
+ this.mode = options2.mode ?? "auto";
569318
+ this.modelTier = options2.modelTier ?? "large";
569319
+ this.repeatGateMax = Math.max(0, Math.floor(options2.repeatGateMax ?? 3));
569320
+ }
569321
+ get enabled() {
569322
+ return this.mode !== "off";
569323
+ }
569324
+ get currentDirective() {
569325
+ return this.directive;
569326
+ }
569327
+ snapshot() {
569328
+ return {
569329
+ mode: this.mode,
569330
+ enabled: this.enabled,
569331
+ state: this.state,
569332
+ directive: this.directive,
569333
+ lastDecision: this.lastDecision,
569334
+ lastReason: this.lastReason,
569335
+ ...this.lastContext ? { context: this.lastContext } : {}
569336
+ };
569337
+ }
569338
+ observeContext(snapshot) {
569339
+ this.lastContext = snapshot;
569340
+ }
569341
+ renderFrame() {
569342
+ if (!this.enabled || !this.directive)
569343
+ return null;
569344
+ const d2 = this.directive;
569345
+ return [
569346
+ "[FOCUS SUPERVISOR]",
569347
+ `state=${d2.state}`,
569348
+ `directive_id=${d2.id}`,
569349
+ `required_next_action=${d2.requiredNextAction}`,
569350
+ `reason=${d2.reason}`,
569351
+ d2.forbiddenActionFamilies.length ? `forbidden_action_families=${d2.forbiddenActionFamilies.join(", ")}` : "",
569352
+ d2.ignoredCount > 0 ? `ignored_count=${d2.ignoredCount}` : "",
569353
+ "Follow the required next action before returning to broad exploration or completion."
569354
+ ].filter(Boolean).join("\n");
569355
+ }
569356
+ evaluateProposedCall(input) {
569357
+ this.lastContext = input.context ?? this.lastContext;
569358
+ if (!this.enabled)
569359
+ return this.pass();
569360
+ const family = actionFamily(input.toolName, input.args);
569361
+ const prior = this.directive;
569362
+ if (prior && violatesDirective(prior, input)) {
569363
+ prior.ignoredCount++;
569364
+ const strict = this.shouldStrictlyIntervene(input.context);
569365
+ if (strict && prior.ignoredCount >= 1) {
569366
+ const directive = this.setDirective({
569367
+ turn: input.turn,
569368
+ state: "single_next_action",
569369
+ reason: `model ignored prior directive ${prior.id}: ${prior.reason}`,
569370
+ requiredNextAction: prior.requiredNextAction,
569371
+ forbiddenActionFamilies: unique2([
569372
+ ...prior.forbiddenActionFamilies,
569373
+ family
569374
+ ])
569375
+ });
569376
+ return this.block(directive, [
569377
+ `[FOCUS SUPERVISOR BLOCK] The previous directive was ignored: ${prior.reason}`,
569378
+ `Required next action: ${directive.requiredNextAction}.`,
569379
+ `Blocked action family: ${family}.`,
569380
+ "Take the required next action, or report blocked/incomplete with evidence."
569381
+ ].join("\n"), false);
569382
+ }
569383
+ }
569384
+ if (input.stalePreflightMessage) {
569385
+ const directive = this.setDirective({
569386
+ turn: input.turn,
569387
+ state: "single_next_action",
569388
+ reason: "stale edit preflight detected a repeated stale target",
569389
+ requiredNextAction: "read_authoritative_target",
569390
+ forbiddenActionFamilies: [family]
569391
+ });
569392
+ return this.block(directive, `${input.stalePreflightMessage}
569393
+
569394
+ [FOCUS SUPERVISOR] Required next action: file_read the authoritative current target once, then build a new edit from current evidence or report incomplete.`, false);
569395
+ }
569396
+ const duplicateHitCount = input.duplicateHitCount ?? 0;
569397
+ if (input.cachedResult && duplicateHitCount > 0) {
569398
+ const strict = this.shouldStrictlyIntervene(input.context);
569399
+ const advisoryOnly = this.repeatGateMax === 0;
569400
+ const hitLimit = input.cachedResultFailed ? 1 : Math.max(1, this.repeatGateMax - 1);
569401
+ const state = input.cachedResultFailed || duplicateHitCount >= hitLimit ? "cached_evidence" : "warn";
569402
+ const directive = this.setDirective({
569403
+ turn: input.turn,
569404
+ state,
569405
+ reason: input.cachedResultFailed ? `cached failed ${input.toolName} evidence already exists` : `duplicate ${input.toolName} call has cached evidence`,
569406
+ requiredNextAction: input.cachedResultFailed ? "edit_different_target" : "use_cached_evidence",
569407
+ forbiddenActionFamilies: [family]
569408
+ });
569409
+ if (strict && !advisoryOnly && (input.cachedResultFailed || duplicateHitCount >= hitLimit)) {
569410
+ return this.block(directive, [
569411
+ input.cachedResultFailed ? "[FOCUS SUPERVISOR: CACHED FAILURE]" : "[FOCUS SUPERVISOR: CACHED EVIDENCE]",
569412
+ `This ${input.toolName} action family has already produced evidence and should not be re-executed unchanged.`,
569413
+ `Required next action: ${directive.requiredNextAction}.`,
569414
+ "",
569415
+ input.cachedResult.slice(0, 8e3)
569416
+ ].join("\n"), !input.cachedResultFailed);
569417
+ }
569418
+ return this.inject(directive, `[FOCUS SUPERVISOR] ${directive.reason}. Required next action: ${directive.requiredNextAction}.`);
569419
+ }
569420
+ if (this.hasLowSignalContext(input.context) && input.isReadLike) {
569421
+ const directive = this.setDirective({
569422
+ turn: input.turn,
569423
+ state: "forced_replan",
569424
+ reason: "raw discovery is dominating active evidence in the context window",
569425
+ requiredNextAction: "update_todos",
569426
+ forbiddenActionFamilies: [family]
569427
+ });
569428
+ return this.inject(directive, "[FOCUS SUPERVISOR] Discovery noise is crowding the live context. Update the todo decomposition, then act on active evidence instead of broad rereads.");
569429
+ }
569430
+ this.lastDecision = "pass";
569431
+ this.lastReason = "";
569432
+ return this.pass();
569433
+ }
569434
+ observeToolResult(input) {
569435
+ if (!this.enabled)
569436
+ return;
569437
+ if (input.mutated) {
569438
+ this.clearSatisfiedDirective("mutation landed", input.turn);
569439
+ return;
569440
+ }
569441
+ if (input.toolName === "todo_write" && input.success) {
569442
+ this.clearSatisfiedDirective("todo plan updated", input.turn);
569443
+ return;
569444
+ }
569445
+ if (input.toolName === "file_read" && input.success) {
569446
+ if (this.directive?.requiredNextAction === "read_authoritative_target" || this.directive?.requiredNextAction === "use_cached_evidence") {
569447
+ this.clearSatisfiedDirective("authoritative evidence refreshed", input.turn);
569448
+ }
569449
+ return;
569450
+ }
569451
+ if (input.toolName === "shell" && input.success) {
569452
+ if (this.directive?.requiredNextAction === "run_verification") {
569453
+ this.clearSatisfiedDirective("verification ran successfully", input.turn);
569454
+ }
569455
+ return;
569456
+ }
569457
+ if (input.success)
569458
+ return;
569459
+ const family = failureFamilyKey(input.toolName, input.args, input.error, input.output);
569460
+ const existing = this.failureFamilies.get(family);
569461
+ const next = {
569462
+ count: (existing?.count ?? 0) + 1,
569463
+ lastTurn: input.turn,
569464
+ sample: cleanFailureSample(input.error || input.output || "")
569465
+ };
569466
+ this.failureFamilies.set(family, next);
569467
+ if (next.count >= 2 && this.shouldStrictlyIntervene(this.lastContext)) {
569468
+ this.setDirective({
569469
+ turn: input.turn,
569470
+ state: "forced_replan",
569471
+ reason: `same ${input.toolName} failure family repeated ${next.count} times: ${next.sample}`,
569472
+ requiredNextAction: input.toolName === "shell" ? "read_authoritative_target" : "update_todos",
569473
+ forbiddenActionFamilies: [actionFamily(input.toolName, input.args)]
569474
+ });
569475
+ }
569476
+ }
569477
+ markCompletionBlocked(input) {
569478
+ if (!this.enabled)
569479
+ return;
569480
+ this.setDirective({
569481
+ turn: input.turn,
569482
+ state: "verify_or_block",
569483
+ reason: input.reason,
569484
+ requiredNextAction: input.requiredNextAction ?? "run_verification",
569485
+ forbiddenActionFamilies: ["task_complete"]
569486
+ });
569487
+ }
569488
+ markTerminalIncomplete(reason, turn) {
569489
+ if (!this.enabled)
569490
+ return;
569491
+ this.setDirective({
569492
+ turn,
569493
+ state: "terminal_incomplete",
569494
+ reason,
569495
+ requiredNextAction: "report_incomplete",
569496
+ forbiddenActionFamilies: ["brute_force", "task_complete"]
569497
+ });
569498
+ }
569499
+ shouldStrictlyIntervene(context2) {
569500
+ if (this.mode === "strict")
569501
+ return true;
569502
+ if (this.mode === "off")
569503
+ return false;
569504
+ if (this.modelTier === "small" || this.modelTier === "medium")
569505
+ return true;
569506
+ if (!context2)
569507
+ return false;
569508
+ const pressure = context2.pressureRatio ?? 0;
569509
+ const ratio = context2.signalToNoiseRatio;
569510
+ return pressure >= 0.85 || ratio !== null && ratio !== void 0 && ratio < 1.2;
569511
+ }
569512
+ hasLowSignalContext(context2) {
569513
+ if (!context2)
569514
+ return false;
569515
+ const raw = context2.rawDiscoveryChars ?? 0;
569516
+ const evidence = (context2.activeEvidenceChars ?? 0) + (context2.activeFrameChars ?? 0);
569517
+ if (raw < 2e3)
569518
+ return false;
569519
+ if (evidence === 0)
569520
+ return true;
569521
+ return raw > evidence * 2;
569522
+ }
569523
+ setDirective(input) {
569524
+ const existing = this.directive;
569525
+ const stable = existing && existing.state === input.state && existing.reason === input.reason && existing.requiredNextAction === input.requiredNextAction;
569526
+ const directive = stable ? {
569527
+ ...existing,
569528
+ forbiddenActionFamilies: unique2([
569529
+ ...existing.forbiddenActionFamilies,
569530
+ ...input.forbiddenActionFamilies
569531
+ ])
569532
+ } : {
569533
+ id: `focus_${++directiveCounter}`,
569534
+ state: input.state,
569535
+ reason: input.reason,
569536
+ requiredNextAction: input.requiredNextAction,
569537
+ forbiddenActionFamilies: unique2(input.forbiddenActionFamilies),
569538
+ createdTurn: input.turn,
569539
+ ignoredCount: 0
569540
+ };
569541
+ this.directive = directive;
569542
+ this.state = directive.state;
569543
+ this.lastReason = directive.reason;
569544
+ return directive;
569545
+ }
569546
+ clearSatisfiedDirective(reason, _turn) {
569547
+ if (!this.directive)
569548
+ return;
569549
+ this.lastDecision = "directive_satisfied";
569550
+ this.lastReason = reason;
569551
+ this.directive = null;
569552
+ this.state = "observe";
569553
+ }
569554
+ pass() {
569555
+ return { kind: "pass", state: this.state, ...this.directive ? { directive: this.directive } : {} };
569556
+ }
569557
+ inject(directive, message2) {
569558
+ this.lastDecision = "inject_guidance";
569559
+ this.lastReason = directive.reason;
569560
+ return { kind: "inject_guidance", state: directive.state, directive, message: message2 };
569561
+ }
569562
+ block(directive, message2, success) {
569563
+ this.lastDecision = "block_tool_call";
569564
+ this.lastReason = directive.reason;
569565
+ return {
569566
+ kind: "block_tool_call",
569567
+ state: directive.state,
569568
+ directive,
569569
+ message: message2,
569570
+ success
569571
+ };
569572
+ }
569573
+ };
569574
+ }
569575
+ });
569576
+
569219
569577
  // packages/orchestrator/dist/completion-resolution-verifier.js
569220
569578
  function resolutionSystemPrompt() {
569221
569579
  return [
@@ -571727,6 +572085,7 @@ var init_agenticRunner = __esm({
571727
572085
  init_evidenceLedger();
571728
572086
  init_adversaryStream();
571729
572087
  init_contextWindowDump();
572088
+ init_focusSupervisor();
571730
572089
  init_completion_resolution_verifier();
571731
572090
  init_todoTruth();
571732
572091
  init_evidenceBranch();
@@ -572240,6 +572599,10 @@ var init_agenticRunner = __esm({
572240
572599
  // adjacent to the main loop. Initialized per run when the step critic is
572241
572600
  // enabled and a backend is available. See adversaryStream.ts.
572242
572601
  _adversaryStream = null;
572602
+ // Stateful small-model focus supervisor. It consolidates repeat gates,
572603
+ // stale edit loops, completion holds, and context pressure into a single
572604
+ // next-action contract injected through the active context frame.
572605
+ _focusSupervisor = null;
572243
572606
  // Generic, cross-session failure→resolution learning: learns the token-level
572244
572607
  // change that turned a failed command into a working one (e.g. python→python3)
572245
572608
  // from observed pairs, and surfaces it before a matching command runs — so
@@ -572443,6 +572806,10 @@ ${parts.join("\n")}
572443
572806
  completionProvenanceGuard: options2?.completionProvenanceGuard ?? true,
572444
572807
  backwardPassReview: options2?.backwardPassReview,
572445
572808
  completionVerifyCommand: options2?.completionVerifyCommand,
572809
+ focusSupervisor: resolveFocusSupervisorMode(options2?.focusSupervisor),
572810
+ supervisorModel: options2?.supervisorModel ?? process.env["OMNIUS_SUPERVISOR_MODEL"] ?? "",
572811
+ supervisorTimeoutMs: options2?.supervisorTimeoutMs ?? Number(process.env["OMNIUS_SUPERVISOR_TIMEOUT_MS"] ?? 2e4),
572812
+ supervisorMaxTokens: options2?.supervisorMaxTokens ?? 900,
572446
572813
  disableAdversaryCritic,
572447
572814
  disableStepCritic: disableAdversaryCritic,
572448
572815
  modelTier: options2?.modelTier ?? "large",
@@ -572512,10 +572879,48 @@ ${parts.join("\n")}
572512
572879
  attempt,
572513
572880
  model: this._backendModelLabel(this.backend),
572514
572881
  cwd: this._workingDirectory || process.cwd(),
572515
- request
572882
+ request,
572883
+ focusSupervisor: this._focusSupervisor?.snapshot()
572516
572884
  });
572885
+ if (record) {
572886
+ this._focusSupervisor?.observeContext({
572887
+ estimatedTokens: record.metrics.estimatedTokens,
572888
+ rawDiscoveryChars: record.metrics.rawDiscoveryToolChars,
572889
+ activeEvidenceChars: record.metrics.activeEvidenceChars,
572890
+ activeFrameChars: record.metrics.activeContextFrameChars,
572891
+ signalToNoiseRatio: record.metrics.signalToNoise.ratio,
572892
+ pressureRatio: this._lastContextPressureSnapshot?.rawRatio ?? (this.options.contextWindowSize ? record.metrics.estimatedTokens / this.options.contextWindowSize : 0),
572893
+ droppedSignals: this._lastContextFrameDiagnostics?.droppedSignals ?? this._lastContextPressureSnapshot?.droppedSignals,
572894
+ truncatedSignals: this._lastContextFrameDiagnostics?.truncatedSignals ?? this._lastContextPressureSnapshot?.truncatedSignals
572895
+ });
572896
+ }
572517
572897
  return record?.id ?? null;
572518
572898
  }
572899
+ _emitFocusSupervisorEvent(input) {
572900
+ this.emit({
572901
+ type: "focus_supervisor",
572902
+ content: `${input.decision}: ${input.reason}`,
572903
+ turn: input.turn,
572904
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
572905
+ focusSupervisor: {
572906
+ state: input.state ?? this._focusSupervisor?.snapshot().state ?? "observe",
572907
+ decision: input.decision,
572908
+ ...input.directiveId ? { directiveId: input.directiveId } : {},
572909
+ reason: input.reason,
572910
+ ...input.requiredNextAction ? { requiredNextAction: input.requiredNextAction } : {},
572911
+ ...input.blockedTool ? { blockedTool: input.blockedTool } : {}
572912
+ }
572913
+ });
572914
+ }
572915
+ _buildFocusContextSnapshot() {
572916
+ return {
572917
+ pressureRatio: this._lastContextPressureSnapshot?.rawRatio ?? 0,
572918
+ estimatedTokens: this._lastContextPressureSnapshot?.rawTokens,
572919
+ activeFrameChars: this._lastContextFrameDiagnostics?.totalChars,
572920
+ droppedSignals: this._lastContextFrameDiagnostics?.droppedSignals ?? this._lastContextPressureSnapshot?.droppedSignals,
572921
+ truncatedSignals: this._lastContextFrameDiagnostics?.truncatedSignals ?? this._lastContextPressureSnapshot?.truncatedSignals
572922
+ };
572923
+ }
572519
572924
  _emitModelResolutionTelemetry(purpose, turn) {
572520
572925
  try {
572521
572926
  const backendName = this.backend.constructor?.name ?? "unknown";
@@ -574772,6 +575177,7 @@ ${_checks}`
574772
575177
  completionScenarioDecomposition
574773
575178
  ].join("\n")
574774
575179
  };
575180
+ this._focusSupervisor?.markTerminalIncomplete(reason, turn);
574775
575181
  this.emit({
574776
575182
  type: "status",
574777
575183
  content: `REG-47 backward-pass runner threw: ${e2 instanceof Error ? e2.message : String(e2)}. Ending as incomplete_verification instead of completing.`,
@@ -574835,6 +575241,7 @@ ${_checks}`
574835
575241
  feedback
574836
575242
  ].join("\n")
574837
575243
  };
575244
+ this._focusSupervisor?.markTerminalIncomplete(reason, turn);
574838
575245
  this.emit({
574839
575246
  type: "status",
574840
575247
  content: `REG-47 critic BLOCKED completion. Rationale: ${result.verdict.rationale.slice(0, 200)}`,
@@ -576023,21 +576430,21 @@ ${sections.join("\n")}` : sections.join("\n");
576023
576430
  sections.push(`Compacted cached entries still count as already-known results (${compactedCount}); an exact repeat will be served from cache or skipped, not produce new information.`);
576024
576431
  }
576025
576432
  if (filesRead.length > 0) {
576026
- const unique2 = [...new Set(filesRead)].slice(0, 30);
576027
- sections.push(`Files already read (${unique2.length}): ${unique2.join(", ")}`);
576433
+ const unique3 = [...new Set(filesRead)].slice(0, 30);
576434
+ sections.push(`Files already read (${unique3.length}): ${unique3.join(", ")}`);
576028
576435
  }
576029
576436
  if (dirsListed.length > 0) {
576030
- const unique2 = [...new Set(dirsListed)].slice(0, 15);
576031
- sections.push(`Directories already listed (${unique2.length}): ${unique2.join(", ")}`);
576437
+ const unique3 = [...new Set(dirsListed)].slice(0, 15);
576438
+ sections.push(`Directories already listed (${unique3.length}): ${unique3.join(", ")}`);
576032
576439
  sections.push(`Do not call list_directory again on these exact directories unless you changed their contents. Use the listed child paths directly with file_read/edit/delegation.`);
576033
576440
  }
576034
576441
  if (searches.length > 0) {
576035
- const unique2 = [...new Set(searches)].slice(0, 15);
576036
- sections.push(`Searches already run (${unique2.length}): ${unique2.join(", ")}`);
576442
+ const unique3 = [...new Set(searches)].slice(0, 15);
576443
+ sections.push(`Searches already run (${unique3.length}): ${unique3.join(", ")}`);
576037
576444
  }
576038
576445
  if (shells.length > 0) {
576039
- const unique2 = [...new Set(shells)].slice(0, 15);
576040
- sections.push(`Shell commands already executed (${unique2.length}): ${unique2.join(", ")}`);
576446
+ const unique3 = [...new Set(shells)].slice(0, 15);
576447
+ sections.push(`Shell commands already executed (${unique3.length}): ${unique3.join(", ")}`);
576041
576448
  }
576042
576449
  if (sections.length <= 1)
576043
576450
  return null;
@@ -576370,6 +576777,7 @@ ${chunk.content}`, {
576370
576777
  const todoBlock = this._renderTodoStateBlock(turn);
576371
576778
  const failureBlock = this._renderRecentFailuresBlock(turn);
576372
576779
  const churnBlock = this._renderWriteChurnBlock(turn);
576780
+ const focusBlock = this._focusSupervisor?.renderFrame() ?? null;
576373
576781
  const toolCacheBlock = recentToolResults ? this._renderKnowledgeBlock(recentToolResults) : null;
576374
576782
  const anchorsBlock = this.surfaceAnchors(messages2);
576375
576783
  const pprMemoryBlock = this._lastPprMemoryLines.length > 0 ? `[Associative Memory - related prior experience]
@@ -576414,6 +576822,13 @@ ${this._lastPprMemoryLines.slice(0, 5).join("\n")}` : null;
576414
576822
  createdTurn: turn,
576415
576823
  ttlTurns: 1
576416
576824
  }),
576825
+ signalFromBlock("task_state", "turn.focus-supervisor", focusBlock, {
576826
+ id: "focus-supervisor",
576827
+ dedupeKey: "turn.focus-supervisor",
576828
+ priority: 98,
576829
+ createdTurn: turn,
576830
+ ttlTurns: 1
576831
+ }),
576417
576832
  signalFromBlock("recent_failure", "turn.failures", failureBlock, {
576418
576833
  id: "recent-failures",
576419
576834
  dedupeKey: "turn.failures",
@@ -577703,6 +578118,41 @@ Respond with your assessment, then take action.`;
577703
578118
  const cleanedTask = cleanForStorage(task) || task.slice(0, 500);
577704
578119
  const start2 = Date.now();
577705
578120
  const taskTimeoutMs = this.options.taskTimeoutMs;
578121
+ const hardDeadlineMs = Number.isFinite(taskTimeoutMs) && taskTimeoutMs > 0 ? start2 + taskTimeoutMs : Number.POSITIVE_INFINITY;
578122
+ let timedOut = false;
578123
+ let timeoutSummary = "";
578124
+ const remainingTaskMs = () => Number.isFinite(hardDeadlineMs) ? Math.max(0, hardDeadlineMs - Date.now()) : Number.POSITIVE_INFINITY;
578125
+ const boundedRequestTimeoutMs = () => {
578126
+ const configured = Number.isFinite(this.options.requestTimeoutMs) && this.options.requestTimeoutMs > 0 ? this.options.requestTimeoutMs : 3e5;
578127
+ const remaining = remainingTaskMs();
578128
+ return Number.isFinite(remaining) ? Math.max(1, Math.min(configured, remaining)) : configured;
578129
+ };
578130
+ const markTaskTimedOut = (phase, turn) => {
578131
+ if (timedOut)
578132
+ return;
578133
+ timedOut = true;
578134
+ timeoutSummary = `Incomplete: task timed out after ${taskTimeoutMs}ms during ${phase}.`;
578135
+ this.emit({
578136
+ type: "error",
578137
+ content: timeoutSummary,
578138
+ ...typeof turn === "number" ? { turn } : {},
578139
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
578140
+ });
578141
+ this._onTypedEvent?.({
578142
+ type: "run_failed",
578143
+ runId: this._sessionId ?? "unknown",
578144
+ error: timeoutSummary,
578145
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
578146
+ });
578147
+ };
578148
+ const checkTaskTimeout = (phase, turn) => {
578149
+ if (!Number.isFinite(hardDeadlineMs))
578150
+ return false;
578151
+ if (Date.now() < hardDeadlineMs)
578152
+ return false;
578153
+ markTaskTimedOut(phase, turn);
578154
+ return true;
578155
+ };
577706
578156
  const selfEvalInterval = taskTimeoutMs;
577707
578157
  let nextSelfEval = start2 + selfEvalInterval;
577708
578158
  let selfEvalCount = 0;
@@ -577723,6 +578173,11 @@ Respond with your assessment, then take action.`;
577723
578173
  this._lastActiveForgettingReport = null;
577724
578174
  this._lastContextConsolidationTurn = -1e3;
577725
578175
  this._contextFrameBuilder = new ContextFrameBuilder();
578176
+ this._focusSupervisor = this.options.focusSupervisor === "off" ? null : new FocusSupervisor({
578177
+ mode: this.options.focusSupervisor,
578178
+ modelTier: this.options.modelTier,
578179
+ repeatGateMax: this._resolveRepeatGateMax()
578180
+ });
577726
578181
  if (!this._workingDirectory) {
577727
578182
  this._workingDirectory = _pathResolve(process.cwd());
577728
578183
  }
@@ -578471,6 +578926,23 @@ TASK: ${scrubbedTask}` : scrubbedTask;
578471
578926
  lastCompletionGateCode = "";
578472
578927
  return false;
578473
578928
  }
578929
+ this._focusSupervisor?.markCompletionBlocked({
578930
+ turn,
578931
+ reason: lastCompletionGateReason || "completion requested before required evidence was present",
578932
+ requiredNextAction: lastCompletionGateCode === "todo_verification" ? "run_verification" : "update_todos"
578933
+ });
578934
+ const focusDirective = this._focusSupervisor?.snapshot().directive;
578935
+ if (focusDirective) {
578936
+ this._emitFocusSupervisorEvent({
578937
+ decision: "completion_blocked",
578938
+ state: focusDirective.state,
578939
+ directiveId: focusDirective.id,
578940
+ reason: focusDirective.reason,
578941
+ requiredNextAction: focusDirective.requiredNextAction,
578942
+ blockedTool: "task_complete",
578943
+ turn
578944
+ });
578945
+ }
578474
578946
  const key = lastCompletionGateCode || (extractTaskCompleteSummary(args) || "").trim().slice(0, 200);
578475
578947
  if (key && key === this._completionHoldState.lastKey) {
578476
578948
  this._completionHoldState.count += 1;
@@ -578497,6 +578969,19 @@ TASK: ${scrubbedTask}` : scrubbedTask;
578497
578969
  reason,
578498
578970
  summary: incompleteSummary
578499
578971
  };
578972
+ this._focusSupervisor?.markTerminalIncomplete(reason, turn);
578973
+ const terminalDirective = this._focusSupervisor?.snapshot().directive;
578974
+ if (terminalDirective) {
578975
+ this._emitFocusSupervisorEvent({
578976
+ decision: "terminal_incomplete",
578977
+ state: terminalDirective.state,
578978
+ directiveId: terminalDirective.id,
578979
+ reason: terminalDirective.reason,
578980
+ requiredNextAction: terminalDirective.requiredNextAction,
578981
+ blockedTool: "task_complete",
578982
+ turn
578983
+ });
578984
+ }
578500
578985
  messages2.push({
578501
578986
  role: "system",
578502
578987
  content: `[INCOMPLETE VERIFICATION TERMINAL STATE] task_complete was held ${this._completionHoldState.count} times by the same completion gate without new evidence. The run is ending as incomplete_verification, not completed. Report the missing evidence plainly.`
@@ -578540,6 +579025,8 @@ TASK: ${scrubbedTask}` : scrubbedTask;
578540
579025
  };
578541
579026
  const turnCap = this.options.maxTurns && this.options.maxTurns > 0 ? this.options.maxTurns : Number.MAX_SAFE_INTEGER;
578542
579027
  for (let turn = 0; turn < turnCap; turn++) {
579028
+ if (checkTaskTimeout("primary turn", turn))
579029
+ break;
578543
579030
  clearTurnState(this._appState);
578544
579031
  this._maybeApplyThinkGuard();
578545
579032
  if (this._paused) {
@@ -580049,7 +580536,7 @@ ${memoryLines.join("\n")}`
580049
580536
  tools: toolDefs,
580050
580537
  temperature: this.options.temperature,
580051
580538
  maxTokens: effectiveMaxTokens,
580052
- timeoutMs: this.options.requestTimeoutMs
580539
+ timeoutMs: boundedRequestTimeoutMs()
580053
580540
  };
580054
580541
  if ((this.options.contextWindowSize ?? 0) > 0) {
580055
580542
  chatRequest.numCtx = this.options.contextWindowSize;
@@ -580161,8 +580648,10 @@ ${memoryLines.join("\n")}`
580161
580648
  break;
580162
580649
  }
580163
580650
  } else {
580164
- const recovered = await this.retryOnTransient(reqErr, chatRequest, turn);
580651
+ const recovered = await this.retryOnTransient(reqErr, chatRequest, turn, hardDeadlineMs);
580165
580652
  if (!recovered) {
580653
+ if (checkTaskTimeout("backend request", turn))
580654
+ break;
580166
580655
  const errMsg = reqErr instanceof Error ? reqErr.message : String(reqErr);
580167
580656
  const cause = reqErr instanceof Error && reqErr.cause ? ` (${reqErr.cause.message ?? ""} ${reqErr.cause?.code ?? ""})` : "";
580168
580657
  this.emit({
@@ -580873,6 +581362,27 @@ Use the saved fact to continue the promised synthesis or next concrete step, or
580873
581362
  }
580874
581363
  const staleEditBlock = this.staleEditPreflightBlock(tc.name, tc.arguments ?? {});
580875
581364
  if (staleEditBlock) {
581365
+ const focusDecision2 = this._focusSupervisor?.evaluateProposedCall({
581366
+ turn,
581367
+ toolName: tc.name,
581368
+ args: tc.arguments ?? {},
581369
+ fingerprint: toolFingerprint,
581370
+ isReadLike: false,
581371
+ stalePreflightMessage: staleEditBlock,
581372
+ context: this._buildFocusContextSnapshot()
581373
+ });
581374
+ const staleBlockOutput = focusDecision2?.kind === "block_tool_call" ? focusDecision2.message : staleEditBlock;
581375
+ if (focusDecision2 && focusDecision2.kind !== "pass") {
581376
+ this._emitFocusSupervisorEvent({
581377
+ decision: focusDecision2.kind,
581378
+ state: focusDecision2.state,
581379
+ directiveId: focusDecision2.directive.id,
581380
+ reason: focusDecision2.directive.reason,
581381
+ requiredNextAction: focusDecision2.directive.requiredNextAction,
581382
+ blockedTool: tc.name,
581383
+ turn
581384
+ });
581385
+ }
580876
581386
  this.emit({
580877
581387
  type: "tool_call",
580878
581388
  toolName: tc.name,
@@ -580884,7 +581394,7 @@ Use the saved fact to continue the promised synthesis or next concrete step, or
580884
581394
  type: "tool_result",
580885
581395
  toolName: tc.name,
580886
581396
  success: false,
580887
- content: staleEditBlock.slice(0, 120),
581397
+ content: staleBlockOutput.slice(0, 120),
580888
581398
  turn,
580889
581399
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
580890
581400
  });
@@ -580896,20 +581406,41 @@ Use the saved fact to continue the promised synthesis or next concrete step, or
580896
581406
  this._completionLedger = recordToolEvidence(this._completionLedger, {
580897
581407
  name: tc.name,
580898
581408
  success: false,
580899
- outputPreview: staleEditBlock.slice(0, 500),
581409
+ outputPreview: staleBlockOutput.slice(0, 500),
580900
581410
  argsKey: tc.arguments ? JSON.stringify(tc.arguments).slice(0, 300) : ""
580901
581411
  });
580902
581412
  this._saveCompletionLedgerSafe();
580903
581413
  }
580904
581414
  return {
580905
581415
  tc,
580906
- output: staleEditBlock,
581416
+ output: staleBlockOutput,
580907
581417
  success: false,
580908
- systemGuidance: staleEditBlock
581418
+ systemGuidance: staleBlockOutput
580909
581419
  };
580910
581420
  }
580911
581421
  const staleRewriteBlock = this.staleEditOverwritePreflightBlock(tc.name, tc.arguments ?? {});
580912
581422
  if (staleRewriteBlock) {
581423
+ const focusDecision2 = this._focusSupervisor?.evaluateProposedCall({
581424
+ turn,
581425
+ toolName: tc.name,
581426
+ args: tc.arguments ?? {},
581427
+ fingerprint: toolFingerprint,
581428
+ isReadLike: false,
581429
+ stalePreflightMessage: staleRewriteBlock,
581430
+ context: this._buildFocusContextSnapshot()
581431
+ });
581432
+ const staleRewriteOutput = focusDecision2?.kind === "block_tool_call" ? focusDecision2.message : staleRewriteBlock;
581433
+ if (focusDecision2 && focusDecision2.kind !== "pass") {
581434
+ this._emitFocusSupervisorEvent({
581435
+ decision: focusDecision2.kind,
581436
+ state: focusDecision2.state,
581437
+ directiveId: focusDecision2.directive.id,
581438
+ reason: focusDecision2.directive.reason,
581439
+ requiredNextAction: focusDecision2.directive.requiredNextAction,
581440
+ blockedTool: tc.name,
581441
+ turn
581442
+ });
581443
+ }
580913
581444
  this.emit({
580914
581445
  type: "tool_call",
580915
581446
  toolName: tc.name,
@@ -580921,7 +581452,7 @@ Use the saved fact to continue the promised synthesis or next concrete step, or
580921
581452
  type: "tool_result",
580922
581453
  toolName: tc.name,
580923
581454
  success: false,
580924
- content: staleRewriteBlock.slice(0, 120),
581455
+ content: staleRewriteOutput.slice(0, 120),
580925
581456
  turn,
580926
581457
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
580927
581458
  });
@@ -580933,16 +581464,16 @@ Use the saved fact to continue the promised synthesis or next concrete step, or
580933
581464
  this._completionLedger = recordToolEvidence(this._completionLedger, {
580934
581465
  name: tc.name,
580935
581466
  success: false,
580936
- outputPreview: staleRewriteBlock.slice(0, 500),
581467
+ outputPreview: staleRewriteOutput.slice(0, 500),
580937
581468
  argsKey: tc.arguments ? JSON.stringify(tc.arguments).slice(0, 300) : ""
580938
581469
  });
580939
581470
  this._saveCompletionLedgerSafe();
580940
581471
  }
580941
581472
  return {
580942
581473
  tc,
580943
- output: staleRewriteBlock,
581474
+ output: staleRewriteOutput,
580944
581475
  success: false,
580945
- systemGuidance: staleRewriteBlock
581476
+ systemGuidance: staleRewriteOutput
580946
581477
  };
580947
581478
  }
580948
581479
  const baseIsReadLike = ![
@@ -581075,7 +581606,8 @@ Use the saved fact to continue the promised synthesis or next concrete step, or
581075
581606
  });
581076
581607
  }
581077
581608
  const _repeatGateMax = this._resolveRepeatGateMax();
581078
- const repeatGateEligible = isReadLike || tc.name === "memory_write";
581609
+ const isFailedShellRepeat = tc.name === "shell" && typeof _existingFp?.result === "string" && _existingFp.result.includes("status: failure");
581610
+ const repeatGateEligible = isReadLike || tc.name === "memory_write" || isFailedShellRepeat;
581079
581611
  if (repeatGateEligible && _existingFp !== void 0 && _repeatGateMax > 0) {
581080
581612
  if (criticDecision.hitNumber >= _repeatGateMax) {
581081
581613
  if (isReadLike) {
@@ -581086,6 +581618,13 @@ Use the saved fact to continue the promised synthesis or next concrete step, or
581086
581618
 
581087
581619
  ` + cachedResult
581088
581620
  };
581621
+ } else if (isFailedShellRepeat) {
581622
+ repeatShortCircuit = {
581623
+ success: false,
581624
+ output: this.sanitizeCachedToolResult(tc.name, _existingFp.result),
581625
+ error: this._buildRepeatGateBlock(tc.name, tc.arguments ?? {}, criticDecision.hitNumber),
581626
+ runtimeAuthored: true
581627
+ };
581089
581628
  } else {
581090
581629
  repeatShortCircuit = {
581091
581630
  success: false,
@@ -581095,7 +581634,14 @@ Use the saved fact to continue the promised synthesis or next concrete step, or
581095
581634
  }
581096
581635
  } else {
581097
581636
  const cachedResult = this.sanitizeCachedToolResult(tc.name, _existingFp.result);
581098
- repeatShortCircuit = {
581637
+ repeatShortCircuit = isFailedShellRepeat ? {
581638
+ success: false,
581639
+ output: `[STOP RE-RUNNING FAILED COMMAND — this exact shell command already failed and no real file mutation has invalidated that evidence. It was NOT executed again. Use the cached failure below to change approach, inspect a different target, or report incomplete.]
581640
+
581641
+ ${cachedResult}`,
581642
+ error: "Repeated failing shell command was not re-executed.",
581643
+ runtimeAuthored: true
581644
+ } : {
581099
581645
  success: true,
581100
581646
  output: cachedResult
581101
581647
  };
@@ -581109,6 +581655,40 @@ Use the saved fact to continue the promised synthesis or next concrete step, or
581109
581655
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
581110
581656
  });
581111
581657
  }
581658
+ const focusCachedEntry = recentToolResults.get(toolFingerprint);
581659
+ const focusDuplicateHits = criticDecision.decision === "guidance" ? criticDecision.hitNumber : dedupHitCount.get(toolFingerprint) ?? 0;
581660
+ const focusDecision = this._focusSupervisor?.evaluateProposedCall({
581661
+ turn,
581662
+ toolName: tc.name,
581663
+ args: tc.arguments ?? {},
581664
+ fingerprint: toolFingerprint,
581665
+ isReadLike,
581666
+ cachedResult: focusCachedEntry?.result,
581667
+ cachedResultFailed: tc.name === "shell" && typeof focusCachedEntry?.result === "string" && focusCachedEntry.result.includes("status: failure"),
581668
+ duplicateHitCount: focusDuplicateHits,
581669
+ context: this._buildFocusContextSnapshot()
581670
+ });
581671
+ if (focusDecision && focusDecision.kind !== "pass") {
581672
+ this._emitFocusSupervisorEvent({
581673
+ decision: focusDecision.kind,
581674
+ state: focusDecision.state,
581675
+ directiveId: focusDecision.directive.id,
581676
+ reason: focusDecision.directive.reason,
581677
+ requiredNextAction: focusDecision.directive.requiredNextAction,
581678
+ blockedTool: focusDecision.kind === "block_tool_call" ? tc.name : void 0,
581679
+ turn
581680
+ });
581681
+ if (focusDecision.kind === "inject_guidance") {
581682
+ pushSoftInjection("system", focusDecision.message);
581683
+ } else if (!repeatShortCircuit) {
581684
+ repeatShortCircuit = {
581685
+ success: focusDecision.success,
581686
+ output: focusDecision.message,
581687
+ error: focusDecision.success ? void 0 : focusDecision.message,
581688
+ runtimeAuthored: true
581689
+ };
581690
+ }
581691
+ }
581112
581692
  this.emit({
581113
581693
  type: "tool_call",
581114
581694
  toolName: tc.name,
@@ -582510,6 +583090,31 @@ Evidence: ${evidencePreview}`.slice(0, 500);
582510
583090
  const filePath = typeof tc.arguments?.path === "string" ? tc.arguments.path : "";
582511
583091
  recordToolExecution(this._appState, tc.name, performance.now() - toolStart, result.success, filePath || void 0);
582512
583092
  this.noteStaleEditGuardOutcome(tc.name, tc.arguments ?? {}, result, turn);
583093
+ {
583094
+ const beforeDirective = this._focusSupervisor?.snapshot().directive?.id ?? null;
583095
+ this._focusSupervisor?.observeToolResult({
583096
+ turn,
583097
+ toolName: tc.name,
583098
+ args: tc.arguments ?? {},
583099
+ fingerprint: toolFingerprint,
583100
+ success: result.success,
583101
+ output: result.output ?? result.llmContent ?? "",
583102
+ error: result.error ?? "",
583103
+ mutated: realFileMutation,
583104
+ isReadLike
583105
+ });
583106
+ const afterDirective = this._focusSupervisor?.snapshot().directive ?? null;
583107
+ if (afterDirective && afterDirective.id !== beforeDirective) {
583108
+ this._emitFocusSupervisorEvent({
583109
+ decision: "directive_created",
583110
+ state: afterDirective.state,
583111
+ directiveId: afterDirective.id,
583112
+ reason: afterDirective.reason,
583113
+ requiredNextAction: afterDirective.requiredNextAction,
583114
+ turn
583115
+ });
583116
+ }
583117
+ }
582513
583118
  if (tc.name === "todo_write") {
582514
583119
  this._lastTodoWriteTurn = turn;
582515
583120
  }
@@ -583403,7 +584008,9 @@ Your most recent tool calls SUCCEEDED. If the task is complete, call task_comple
583403
584008
  }
583404
584009
  }
583405
584010
  let prevCycleToolCalls = toolCallCount;
583406
- while (!completed && !this.aborted && this.options.bruteForce && bruteForceCycle < this.options.bruteForceMaxCycles) {
584011
+ while (!completed && !this.aborted && !this._completionIncompleteVerification && !timedOut && this.options.bruteForce && bruteForceCycle < this.options.bruteForceMaxCycles) {
584012
+ if (checkTaskTimeout("brute-force re-engagement"))
584013
+ break;
583407
584014
  bruteForceCycle++;
583408
584015
  const totalTurns = messages2.filter((m2) => m2.role === "assistant").length;
583409
584016
  if (bruteForceCycle > 1 && toolCallCount === prevCycleToolCalls) {
@@ -583467,6 +584074,10 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
583467
584074
  }
583468
584075
  const restartTurnCap = this.options.maxTurns && this.options.maxTurns > 0 ? this.options.maxTurns : Number.MAX_SAFE_INTEGER;
583469
584076
  for (let turn = 0; turn < restartTurnCap; turn++) {
584077
+ if (checkTaskTimeout("brute-force turn", turn))
584078
+ break;
584079
+ if (this._completionIncompleteVerification)
584080
+ break;
583470
584081
  this._maybeApplyThinkGuard();
583471
584082
  if (this._paused) {
583472
584083
  const shouldContinue = await this.waitIfPaused();
@@ -583548,7 +584159,7 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
583548
584159
  tools: toolDefs,
583549
584160
  temperature: this.options.temperature,
583550
584161
  maxTokens: this.options.maxTokens,
583551
- timeoutMs: this.options.requestTimeoutMs,
584162
+ timeoutMs: boundedRequestTimeoutMs(),
583552
584163
  numCtx: this.options.contextWindowSize || void 0
583553
584164
  };
583554
584165
  this._recordContextWindowDump("brute_force_turn", chatRequest, turn);
@@ -583590,8 +584201,10 @@ ${this.options.maxTurns && this.options.maxTurns > 0 ? `You have ${this.options.
583590
584201
  break;
583591
584202
  }
583592
584203
  } else {
583593
- const recovered = await this.retryOnTransient(reqErr, chatRequest, turn);
584204
+ const recovered = await this.retryOnTransient(reqErr, chatRequest, turn, hardDeadlineMs);
583594
584205
  if (!recovered) {
584206
+ if (checkTaskTimeout("brute-force backend request", turn))
584207
+ break;
583595
584208
  const errMsg2 = reqErr instanceof Error ? reqErr.message : String(reqErr);
583596
584209
  const cause2 = reqErr instanceof Error && reqErr.cause ? ` (${reqErr.cause.message ?? ""} ${reqErr.cause?.code ?? ""})` : "";
583597
584210
  this.emit({
@@ -584067,6 +584680,9 @@ Full content available via: repl_exec(code="data = retrieve('${handleId}')") or
584067
584680
  }
584068
584681
  const durationMs = Date.now() - start2;
584069
584682
  const incompleteVerification = this._completionIncompleteVerification;
584683
+ if (timedOut && !summary) {
584684
+ summary = timeoutSummary || `Incomplete: task timed out after ${taskTimeoutMs}ms.`;
584685
+ }
584070
584686
  if (incompleteVerification && !summary) {
584071
584687
  summary = incompleteVerification.summary;
584072
584688
  }
@@ -588547,7 +589163,7 @@ ${description}`
588547
589163
  * until recovery; other transient backend errors use bounded backoff.
588548
589164
  * Returns the response on success, or null if recovery did not apply.
588549
589165
  */
588550
- async retryOnTransient(initialErr, chatRequest, turn) {
589166
+ async retryOnTransient(initialErr, chatRequest, turn, hardDeadlineMs) {
588551
589167
  if (!this.isTransientError(initialErr))
588552
589168
  return null;
588553
589169
  const errMsg = flattenErrorText(initialErr);
@@ -588562,6 +589178,15 @@ ${description}`
588562
589178
  while (attempt <= (maxRetries === Infinity ? Number.MAX_SAFE_INTEGER : maxRetries)) {
588563
589179
  if (this.aborted)
588564
589180
  return null;
589181
+ if (Number.isFinite(hardDeadlineMs) && Date.now() >= hardDeadlineMs) {
589182
+ this.emit({
589183
+ type: "error",
589184
+ content: "Task timeout reached during backend retry",
589185
+ turn,
589186
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
589187
+ });
589188
+ return null;
589189
+ }
588565
589190
  if (this.isPaymentRequiredError(initialErr) && typeof backend.rotateKey === "function") {
588566
589191
  const rotated = backend.rotateKey();
588567
589192
  if (rotated) {
@@ -588611,6 +589236,7 @@ ${description}`
588611
589236
  }
588612
589237
  }
588613
589238
  const delay3 = isGpuSlotUnavailable ? baseDelayMs : Math.min(baseDelayMs * Math.pow(2, attempt - 1), maxDelayMs);
589239
+ const effectiveDelay = Number.isFinite(hardDeadlineMs) ? Math.max(0, Math.min(delay3, hardDeadlineMs - Date.now())) : delay3;
588614
589240
  const attemptLabel = maxRetries === Infinity ? `${attempt}` : `${attempt}/${maxRetries}`;
588615
589241
  if (isGpuSlotUnavailable) {
588616
589242
  this.emit({
@@ -588621,13 +589247,22 @@ ${description}`
588621
589247
  } else {
588622
589248
  this.emit({
588623
589249
  type: "status",
588624
- content: `Backend error — retrying in ${(delay3 / 1e3).toFixed(0)}s (attempt ${attemptLabel})`,
589250
+ content: `Backend error — retrying in ${(effectiveDelay / 1e3).toFixed(0)}s (attempt ${attemptLabel})`,
588625
589251
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
588626
589252
  });
588627
589253
  }
588628
- await new Promise((r2) => setTimeout(r2, delay3));
589254
+ await new Promise((r2) => setTimeout(r2, effectiveDelay));
588629
589255
  if (this.aborted)
588630
589256
  return null;
589257
+ if (Number.isFinite(hardDeadlineMs) && Date.now() >= hardDeadlineMs) {
589258
+ this.emit({
589259
+ type: "error",
589260
+ content: "Task timeout reached before backend retry could resume",
589261
+ turn,
589262
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
589263
+ });
589264
+ return null;
589265
+ }
588631
589266
  try {
588632
589267
  this._recordContextWindowDump("agent_turn_transient_retry", chatRequest, turn, attempt);
588633
589268
  const response = this.options.streamEnabled && this.hasStreamingSupport() ? await this.streamingRequest(chatRequest, turn) : await this.backend.chatCompletion(chatRequest);
@@ -595514,6 +596149,7 @@ __export(dist_exports3, {
595514
596149
  EditorRunner: () => EditorRunner,
595515
596150
  FLOWSTATE_PROMPT: () => FLOWSTATE_PROMPT,
595516
596151
  FRONTEND_WORKER_SKILL: () => FRONTEND_WORKER_SKILL,
596152
+ FocusSupervisor: () => FocusSupervisor,
595517
596153
  HookManager: () => HookManager,
595518
596154
  INFRA_WORKER_SKILL: () => INFRA_WORKER_SKILL,
595519
596155
  ImportanceBudget: () => ImportanceBudget,
@@ -595712,6 +596348,7 @@ __export(dist_exports3, {
595712
596348
  resetPluginRegistry: () => resetPluginRegistry,
595713
596349
  resolveAgentTools: () => resolveAgentTools,
595714
596350
  resolveDefaultPoolConfig: () => resolveDefaultPoolConfig,
596351
+ resolveFocusSupervisorMode: () => resolveFocusSupervisorMode,
595715
596352
  resolveModelProfile: () => resolveModelProfile,
595716
596353
  restoreAgentTasks: () => restoreAgentTasks,
595717
596354
  retentionStrength: () => retentionStrength,
@@ -595780,6 +596417,7 @@ var init_dist8 = __esm({
595780
596417
  init_flowstatePrompt();
595781
596418
  init_contextEngine();
595782
596419
  init_contextWindowDump();
596420
+ init_focusSupervisor();
595783
596421
  init_completionLedger();
595784
596422
  init_runEvents();
595785
596423
  init_costTracker();
@@ -653310,14 +653948,14 @@ function loadFailurePatterns(store2) {
653310
653948
  const unresolved = store2.listUnresolved();
653311
653949
  if (unresolved.length === 0) return "";
653312
653950
  const seen = /* @__PURE__ */ new Set();
653313
- const unique2 = unresolved.filter((f2) => {
653951
+ const unique3 = unresolved.filter((f2) => {
653314
653952
  if (seen.has(f2.fingerprint)) return false;
653315
653953
  seen.add(f2.fingerprint);
653316
653954
  return true;
653317
653955
  });
653318
- if (unique2.length === 0) return "";
653956
+ if (unique3.length === 0) return "";
653319
653957
  const lines = ["Known failure patterns (avoid repeating these):"];
653320
- for (const f2 of unique2.slice(0, 8)) {
653958
+ for (const f2 of unique3.slice(0, 8)) {
653321
653959
  const file = f2.filePath ? ` in ${f2.filePath}` : "";
653322
653960
  lines.push(`- [${f2.failureType}]${file}: ${f2.errorMessage.slice(0, 150)}`);
653323
653961
  }
@@ -656101,8 +656739,8 @@ function generateDescriptors(repoRoot) {
656101
656739
  if (repoName2 && !tags.includes(repoName2)) {
656102
656740
  tags.push(repoName2);
656103
656741
  }
656104
- const unique2 = [...new Set(tags.map((t2) => t2.toLowerCase().trim()).filter((t2) => t2.length > 1 && t2.length < 60))];
656105
- const phrases = unique2.map((text2) => ({
656742
+ const unique3 = [...new Set(tags.map((t2) => t2.toLowerCase().trim()).filter((t2) => t2.length > 1 && t2.length < 60))];
656743
+ const phrases = unique3.map((text2) => ({
656106
656744
  text: text2,
656107
656745
  color: weightedColor(profile)
656108
656746
  }));
@@ -656123,7 +656761,7 @@ function generateDescriptors(repoRoot) {
656123
656761
  ];
656124
656762
  for (const fb of fallbacks) {
656125
656763
  if (phrases.length >= 20) break;
656126
- if (!unique2.includes(fb)) {
656764
+ if (!unique3.includes(fb)) {
656127
656765
  phrases.push({ text: fb, color: weightedColor(profile) });
656128
656766
  }
656129
656767
  }
@@ -661454,13 +662092,13 @@ function buildScopedToolList(scope) {
661454
662092
  const commandSigs = commands.flatMap((cmd) => cmd.signatures);
661455
662093
  const allSigs = [...syntheticSigs, ...commandSigs];
661456
662094
  const seen = /* @__PURE__ */ new Set();
661457
- const unique2 = allSigs.filter((sig) => {
662095
+ const unique3 = allSigs.filter((sig) => {
661458
662096
  if (seen.has(sig.signature)) return false;
661459
662097
  seen.add(sig.signature);
661460
662098
  return true;
661461
662099
  });
661462
662100
  const entries = [];
661463
- for (const sig of unique2) {
662101
+ for (const sig of unique3) {
661464
662102
  const matchingCmd = commands.find(
661465
662103
  (cmd) => cmd.signatures.some((s2) => s2.signature === sig.signature)
661466
662104
  );
@@ -666402,14 +667040,14 @@ function parseTelegramReplyPreferenceUpdate(parsed) {
666402
667040
  }
666403
667041
  function uniqueTelegramJsonCandidates(candidates) {
666404
667042
  const seen = /* @__PURE__ */ new Set();
666405
- const unique2 = [];
667043
+ const unique3 = [];
666406
667044
  for (const candidate of candidates) {
666407
667045
  const clean5 = candidate.trim();
666408
667046
  if (!clean5 || seen.has(clean5)) continue;
666409
667047
  seen.add(clean5);
666410
- unique2.push(clean5);
667048
+ unique3.push(clean5);
666411
667049
  }
666412
- return unique2;
667050
+ return unique3;
666413
667051
  }
666414
667052
  function extractBalancedTelegramJsonObjects(text2) {
666415
667053
  const objects = [];
@@ -667408,10 +668046,10 @@ function telegramHistoryTime(entry) {
667408
668046
  });
667409
668047
  }
667410
668048
  function formatTelegramIdentitySignals(signals) {
667411
- const unique2 = [
668049
+ const unique3 = [
667412
668050
  ...new Set(signals.map((signal) => signal.trim()).filter(Boolean))
667413
668051
  ];
667414
- return unique2.length > 0 ? unique2.join(", ") : "none";
668052
+ return unique3.length > 0 ? unique3.join(", ") : "none";
667415
668053
  }
667416
668054
  function summarizeTelegramMessageAttachments(msg) {
667417
668055
  const parts = [];
@@ -667932,12 +668570,12 @@ function buildTelegramHelpHTML(scope, maxPublicCommands = 24) {
667932
668570
  ...commands.flatMap((cmd) => cmd.signatures)
667933
668571
  ];
667934
668572
  const seen = /* @__PURE__ */ new Set();
667935
- const unique2 = signatures.filter((sig) => {
668573
+ const unique3 = signatures.filter((sig) => {
667936
668574
  if (seen.has(sig.signature)) return false;
667937
668575
  seen.add(sig.signature);
667938
668576
  return true;
667939
668577
  });
667940
- const visible = scope === "public" ? unique2.slice(0, maxPublicCommands) : unique2;
668578
+ const visible = scope === "public" ? unique3.slice(0, maxPublicCommands) : unique3;
667941
668579
  const lines = [
667942
668580
  `<b>Commands (${scope === "admin" ? "admin full scope" : "public secure scope"})</b>`,
667943
668581
  "",
@@ -667945,7 +668583,7 @@ function buildTelegramHelpHTML(scope, maxPublicCommands = 24) {
667945
668583
  (sig) => `<code>${escapeTelegramHTML(sig.signature)}</code> - ${escapeTelegramHTML(sig.description)}`
667946
668584
  )
667947
668585
  ];
667948
- if (scope === "public" && unique2.length > visible.length) {
668586
+ if (scope === "public" && unique3.length > visible.length) {
667949
668587
  lines.push("");
667950
668588
  lines.push(
667951
668589
  `Public scope truncated to ${visible.length} safe commands. Authenticate as admin for full command help.`
@@ -682177,20 +682815,20 @@ Scoped workspace: ${scopedRoot}`,
682177
682815
  };
682178
682816
  }
682179
682817
  async deleteTelegramMessages(chatId, messageIds, currentMsg) {
682180
- const unique2 = [...new Set(messageIds)].filter((id) => Number.isFinite(id));
682181
- if (unique2.length === 0)
682818
+ const unique3 = [...new Set(messageIds)].filter((id) => Number.isFinite(id));
682819
+ if (unique3.length === 0)
682182
682820
  throw new Error(
682183
682821
  "deleteTelegramMessages requires at least one message id."
682184
682822
  );
682185
682823
  await this.assertTelegramBotRightsForAction(
682186
682824
  "delete_messages",
682187
682825
  chatId,
682188
- unique2,
682826
+ unique3,
682189
682827
  currentMsg
682190
682828
  );
682191
682829
  const chunks = [];
682192
- for (let idx = 0; idx < unique2.length; idx += 100)
682193
- chunks.push(unique2.slice(idx, idx + 100));
682830
+ for (let idx = 0; idx < unique3.length; idx += 100)
682831
+ chunks.push(unique3.slice(idx, idx + 100));
682194
682832
  const results = [];
682195
682833
  for (const chunk of chunks) {
682196
682834
  const result = await this.apiCall("deleteMessages", {
@@ -682208,9 +682846,9 @@ Scoped workspace: ${scopedRoot}`,
682208
682846
  telegram_method: "deleteMessages",
682209
682847
  ok: true,
682210
682848
  chat_id: chatId,
682211
- message_ids: unique2,
682849
+ message_ids: unique3,
682212
682850
  batches: results,
682213
- bot_rights_checked: !this.telegramTargetLooksPrivate(chatId, currentMsg) && !unique2.every((id) => this.isKnownAssistantTelegramMessage(chatId, id)),
682851
+ bot_rights_checked: !this.telegramTargetLooksPrivate(chatId, currentMsg) && !unique3.every((id) => this.isKnownAssistantTelegramMessage(chatId, id)),
682214
682852
  policy_scope: this.telegramToolPolicy.chatOverrides?.[String(chatId)] ? "chat" : "global/default"
682215
682853
  };
682216
682854
  }