omnius 1.0.540 → 1.0.542

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
@@ -573266,6 +573266,9 @@ function trajectoryCheckpointFingerprint(checkpoint) {
573266
573266
  checkpoint.goal,
573267
573267
  checkpoint.phase ?? "",
573268
573268
  checkpoint.currentStep ?? "",
573269
+ checkpoint.situationAssessment ?? "",
573270
+ checkpoint.groundingSource ?? "",
573271
+ checkpoint.groundingEvidenceRefs?.join("") ?? "",
573269
573272
  checkpoint.completedWork.join(""),
573270
573273
  checkpoint.groundedFacts.map((fact) => `${fact.statement}\0${fact.evidence}\0${fact.freshness}`).join(""),
573271
573274
  checkpoint.openQuestions.join(""),
@@ -573381,19 +573384,39 @@ function buildTrajectoryCheckpoint(input) {
573381
573384
  if (state.pendingSteps.length > 0 && !state.nextAction.trim()) {
573382
573385
  openQuestions.push(`Choose the next pending task: ${sanitizeTrajectoryText(state.pendingSteps[0], 180)}`);
573383
573386
  }
573387
+ const generated = input.generatedGrounding ?? null;
573388
+ const canUseGenerated = Boolean(generated?.situationAssessment);
573389
+ const groundingSource = canUseGenerated ? "model" : "deterministic";
573390
+ const situationAssessment = canUseGenerated ? sanitizeTrajectoryText(generated?.situationAssessment, 420) : deterministicSituationAssessment({
573391
+ goal,
573392
+ outcomeText,
573393
+ focus,
573394
+ assessment,
573395
+ targetPath
573396
+ });
573397
+ const currentStep = canUseGenerated && generated?.currentStep ? sanitizeTrajectoryText(generated.currentStep, 180) : sanitizeTrajectoryText(state.currentStep, 180);
573398
+ const generatedOpenQuestions = canUseGenerated ? generated.openQuestions.map((value2) => sanitizeTrajectoryText(value2, 180)) : [];
573399
+ const generatedConstraints = canUseGenerated ? generated.doNotRepeat.map((value2) => sanitizeTrajectoryText(value2, 220)) : [];
573400
+ if (canUseGenerated && assessment === "on_trajectory") {
573401
+ nextAction = sanitizeTrajectoryText(generated?.nextAction, 320) || nextAction;
573402
+ successEvidence = sanitizeTrajectoryText(generated?.successEvidence, 280) || successEvidence;
573403
+ }
573384
573404
  const checkpointWithoutIdentity = {
573385
573405
  schemaVersion: 1,
573386
573406
  trigger: sanitizeTrajectoryText(input.trigger || inferTrigger(outcome), 80),
573387
573407
  assessment,
573388
573408
  goal,
573389
573409
  phase: sanitizeTrajectoryText(state.phase, 60) || void 0,
573390
- currentStep: sanitizeTrajectoryText(state.currentStep, 180) || void 0,
573410
+ currentStep: currentStep || void 0,
573411
+ situationAssessment,
573412
+ groundingSource,
573413
+ groundingEvidenceRefs: canUseGenerated ? unique2(generated.evidenceRefs, MAX_FACTS) : void 0,
573391
573414
  completedWork,
573392
573415
  groundedFacts: groundedFacts.slice(0, MAX_FACTS),
573393
- openQuestions: unique2(openQuestions, 2),
573416
+ openQuestions: unique2([...openQuestions, ...generatedOpenQuestions], 2),
573394
573417
  nextAction: sanitizeTrajectoryText(nextAction, 320),
573395
573418
  successEvidence: sanitizeTrajectoryText(successEvidence, 280),
573396
- doNotRepeat: unique2(doNotRepeat, MAX_CONSTRAINTS)
573419
+ doNotRepeat: unique2([...doNotRepeat, ...generatedConstraints], MAX_CONSTRAINTS)
573397
573420
  };
573398
573421
  const fingerprint = trajectoryCheckpointFingerprint(checkpointWithoutIdentity);
573399
573422
  return {
@@ -573411,19 +573434,87 @@ function renderTrajectoryCheckpoint(checkpoint, maxChars = 1100) {
573411
573434
  `Assessment: ${checkpoint.assessment}`,
573412
573435
  checkpoint.phase ? `Phase: ${checkpoint.phase}` : null,
573413
573436
  checkpoint.currentStep ? `Current step: ${checkpoint.currentStep}` : null,
573437
+ // Keep the action contract ahead of explanatory evidence so truncation can
573438
+ // never hide the guard that the main agent must follow.
573439
+ `Required next action: ${checkpoint.nextAction}`,
573440
+ `Success evidence: ${checkpoint.successEvidence}`,
573441
+ checkpoint.situationAssessment ? `${checkpoint.groundingSource === "model" ? "Reasoned situation" : "Safety orientation"}: ${checkpoint.situationAssessment}` : null,
573442
+ checkpoint.groundingEvidenceRefs?.length ? `Grounding evidence: ${checkpoint.groundingEvidenceRefs.join(", ")}` : null,
573414
573443
  checkpoint.completedWork.length > 0 ? `Completed evidence-backed work: ${checkpoint.completedWork.join("; ")}` : null,
573415
573444
  checkpoint.groundedFacts.length > 0 ? "Grounded facts:" : null,
573416
573445
  ...checkpoint.groundedFacts.map((fact) => `- [${fact.evidence}; ${fact.freshness}] ${fact.statement}`),
573417
573446
  checkpoint.openQuestions.length > 0 ? "Open questions:" : null,
573418
573447
  ...checkpoint.openQuestions.map((question) => `- ${question}`),
573419
- `Required next action: ${checkpoint.nextAction}`,
573420
- `Success evidence: ${checkpoint.successEvidence}`,
573421
573448
  checkpoint.doNotRepeat.length > 0 ? "Do not repeat:" : null,
573422
573449
  ...checkpoint.doNotRepeat.map((constraint) => `- ${constraint}`),
573423
573450
  "Attention rule: reconcile the next tool call with this checkpoint. Treat stale or unknown evidence as a reason to read or verify. Do not quote this checkpoint or produce a reasoning transcript."
573424
573451
  ].filter((line) => Boolean(line));
573425
573452
  return truncate(lines.join("\n"), maxChars);
573426
573453
  }
573454
+ function buildTrajectoryGroundingPrompt(checkpoint, supplementalEvidence = []) {
573455
+ const evidenceRefs = [
573456
+ "goal",
573457
+ ...checkpoint.groundedFacts.map((fact) => fact.evidence),
573458
+ "unknown"
573459
+ ];
573460
+ const evidence = supplementalEvidence.map((value2) => sanitizeTrajectoryText(value2, 700)).filter(Boolean).slice(0, 6);
573461
+ return [
573462
+ "[TRAJECTORY GROUNDING REQUEST]",
573463
+ "Before the main agent takes its first action, form a compact, task-specific orientation from the supplied evidence.",
573464
+ "Reason about what is known, what remains unknown, and why the next action is the best immediate move. Do not use generic filler such as 'take a narrow action'.",
573465
+ "Do not invent files, source contents, tool results, verification results, or completed work. Do not reveal private chain-of-thought; provide only a concise, auditable situation assessment.",
573466
+ "The deterministic assessment and constraints below are safety facts. You may refine the plan, but never weaken a recovery, verification, or blocker constraint.",
573467
+ "Return ONLY JSON with this schema:",
573468
+ JSON.stringify({
573469
+ situation_assessment: "1-3 concise, evidence-bound sentences",
573470
+ current_step: "optional concrete current phase",
573471
+ open_questions: ["specific unknown that gates the next action"],
573472
+ next_action: "one concrete next action",
573473
+ success_evidence: "what observable result proves the action helped",
573474
+ do_not_repeat: ["specific unsafe or ungrounded retry to avoid"],
573475
+ evidence_refs: ["one or more labels from allowed_evidence_refs"]
573476
+ }),
573477
+ "Authoritative trajectory input:",
573478
+ JSON.stringify({
573479
+ goal: checkpoint.goal,
573480
+ assessment: checkpoint.assessment,
573481
+ current_step: checkpoint.currentStep,
573482
+ completed_work: checkpoint.completedWork,
573483
+ grounded_facts: checkpoint.groundedFacts,
573484
+ open_questions: checkpoint.openQuestions,
573485
+ required_next_action: checkpoint.nextAction,
573486
+ success_evidence: checkpoint.successEvidence,
573487
+ do_not_repeat: checkpoint.doNotRepeat,
573488
+ allowed_evidence_refs: evidenceRefs,
573489
+ supplemental_evidence: evidence
573490
+ }, null, 2)
573491
+ ].join("\n\n");
573492
+ }
573493
+ function parseTrajectoryGeneratedGrounding(raw, allowedEvidenceRefs) {
573494
+ const parsed = parseJsonObject3(raw);
573495
+ if (!parsed)
573496
+ return null;
573497
+ const situationAssessment = sanitizeTrajectoryText(parsed["situation_assessment"] ?? parsed["situationAssessment"], 420);
573498
+ if (!situationAssessment)
573499
+ return null;
573500
+ const allowed = /* @__PURE__ */ new Set([
573501
+ "goal",
573502
+ "unknown",
573503
+ ...allowedEvidenceRefs.map((value2) => sanitizeTrajectoryText(value2, 160))
573504
+ ]);
573505
+ const refs = stringArray3(parsed["evidence_refs"] ?? parsed["evidenceRefs"], 5).filter((value2) => allowed.has(value2));
573506
+ return {
573507
+ situationAssessment,
573508
+ currentStep: sanitizeTrajectoryText(parsed["current_step"] ?? parsed["currentStep"], 180) || void 0,
573509
+ openQuestions: stringArray3(parsed["open_questions"] ?? parsed["openQuestions"], 3),
573510
+ nextAction: sanitizeTrajectoryText(parsed["next_action"] ?? parsed["nextAction"], 320) || void 0,
573511
+ successEvidence: sanitizeTrajectoryText(parsed["success_evidence"] ?? parsed["successEvidence"], 280) || void 0,
573512
+ doNotRepeat: stringArray3(parsed["do_not_repeat"] ?? parsed["doNotRepeat"], MAX_CONSTRAINTS),
573513
+ // A goal is always an allowed fact; retain it as a conservative fallback
573514
+ // for models that omit the optional citation field.
573515
+ evidenceRefs: refs.length > 0 ? unique2(refs, MAX_FACTS) : ["goal"]
573516
+ };
573517
+ }
573427
573518
  function scopeTrajectoryCheckpoint(checkpoint, delegatedScope, exitEvidence) {
573428
573519
  if (!checkpoint)
573429
573520
  return null;
@@ -573521,6 +573612,41 @@ function extractFocusNextAction(value2) {
573521
573612
  function unique2(values, limit) {
573522
573613
  return [...new Set(values.map((value2) => sanitizeTrajectoryText(value2)).filter(Boolean))].slice(0, limit);
573523
573614
  }
573615
+ function deterministicSituationAssessment(input) {
573616
+ if (input.outcomeText) {
573617
+ return `The latest observed result is ${input.outcomeText}. The next step must respond to that evidence rather than assume the task state changed.`;
573618
+ }
573619
+ if (input.focus) {
573620
+ return `An active recovery directive is present: ${input.focus}. It takes precedence over a generic continuation plan.`;
573621
+ }
573622
+ if (input.assessment !== "on_trajectory") {
573623
+ return `The runner has classified this task as ${input.assessment.replace(/_/g, " ")}${input.targetPath ? ` around ${input.targetPath}` : ""}; preserve the stated safety contract while collecting the next observation.`;
573624
+ }
573625
+ return `No file, tool, or verifier observation has been recorded yet for "${input.goal}". Treat the user goal as the only established fact until the first project observation is made.`;
573626
+ }
573627
+ function parseJsonObject3(raw) {
573628
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
573629
+ return raw;
573630
+ }
573631
+ const text2 = String(raw ?? "").trim();
573632
+ if (!text2)
573633
+ return null;
573634
+ const start2 = text2.indexOf("{");
573635
+ const end = text2.lastIndexOf("}");
573636
+ if (start2 < 0 || end <= start2)
573637
+ return null;
573638
+ try {
573639
+ const parsed = JSON.parse(text2.slice(start2, end + 1));
573640
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
573641
+ } catch {
573642
+ return null;
573643
+ }
573644
+ }
573645
+ function stringArray3(value2, limit) {
573646
+ if (!Array.isArray(value2))
573647
+ return [];
573648
+ return unique2(value2.map((item) => sanitizeTrajectoryText(item, 280)), limit);
573649
+ }
573524
573650
  function truncate(value2, max) {
573525
573651
  const clean5 = String(value2 ?? "").trim();
573526
573652
  return clean5.length > max ? `${clean5.slice(0, Math.max(0, max - 1))}…` : clean5;
@@ -579225,6 +579351,9 @@ function recordDebugTrajectoryCheckpoint(input) {
579225
579351
  trajectory: {
579226
579352
  revision: checkpoint.revision,
579227
579353
  assessment: checkpoint.assessment,
579354
+ groundingSource: checkpoint.groundingSource,
579355
+ situationAssessment: checkpoint.situationAssessment ? trim(checkpoint.situationAssessment, 700) : void 0,
579356
+ groundingEvidenceRefs: checkpoint.groundingEvidenceRefs?.slice(0, 5).map((value2) => trim(value2, 160)),
579228
579357
  nextAction: trim(checkpoint.nextAction, 500),
579229
579358
  successEvidence: trim(checkpoint.successEvidence, 500),
579230
579359
  doNotRepeat: checkpoint.doNotRepeat.slice(0, 3).map((value2) => trim(value2, 300))
@@ -583109,6 +583238,36 @@ var init_completion_resolution_verifier = __esm({
583109
583238
  });
583110
583239
 
583111
583240
  // packages/orchestrator/dist/evidenceBranch.js
583241
+ function buildBranchExtractionBrief(input) {
583242
+ const path16 = cleanBriefText(input.path, 320) || "the requested file";
583243
+ const intent = firstBriefText([
583244
+ input.assistantIntent,
583245
+ input.trajectoryNextAction,
583246
+ input.currentStep
583247
+ ]);
583248
+ const openQuestion = cleanBriefText(input.trajectoryOpenQuestion, 280);
583249
+ const focus = openQuestion || intent;
583250
+ const request = openQuestion ? `Determine the exact file-local facts in ${path16} that answer this unresolved agent question: ${openQuestion}` : intent ? `Identify the exact file-local facts in ${path16} that the active agent needs before it can ${asActionClause(intent)}.` : `Identify the exact declarations, behavior, and configuration in ${path16} needed to choose the next narrow action.`;
583251
+ const triggerEvidence = uniqueBriefLines([
583252
+ `The active action is a whole-file read of ${path16}; disk inspection found ${Math.max(0, input.lineCount)} lines / ${Math.max(0, input.byteCount)} bytes, so the parent context would otherwise receive only a preview.`,
583253
+ input.trajectoryAssessment ? `Current trajectory assessment: ${cleanBriefText(input.trajectoryAssessment, 360)}` : "No current file-level evidence has been returned to the parent yet.",
583254
+ input.currentStep ? `Current task step: ${cleanBriefText(input.currentStep, 260)}` : "",
583255
+ input.recentFailure ? `Recent unresolved evidence: ${cleanBriefText(input.recentFailure, 320)}` : ""
583256
+ ]);
583257
+ const returnContract = focus ? `Return only the exact declarations, values, behavior, and line spans that resolve: ${focus}` : "Return only the exact declarations, values, behavior, and line spans needed for the next safe action.";
583258
+ const retrievalQuery = uniqueBriefLines([
583259
+ path16,
583260
+ focus,
583261
+ openQuestion,
583262
+ "relevant declarations behavior configuration line spans"
583263
+ ]).join(" ");
583264
+ return {
583265
+ request: cleanBriefText(request, 520),
583266
+ triggerEvidence: triggerEvidence.slice(0, 4),
583267
+ returnContract: cleanBriefText(returnContract, 520),
583268
+ retrievalQuery: cleanBriefText(retrievalQuery, 700)
583269
+ };
583270
+ }
583112
583271
  function buildStructuralPreview2(lines, path16, query) {
583113
583272
  const n2 = lines.length;
583114
583273
  const clip3 = (l2) => l2.length > 180 ? l2.slice(0, 180) + "…" : l2;
@@ -583135,6 +583294,29 @@ function queryTerms(query) {
583135
583294
  ...new Set(query.toLowerCase().replace(/[^a-z0-9_<>./-]+/g, " ").split(/\s+/).filter((w) => w.length > 2 && !STOPWORDS2.has(w)))
583136
583295
  ];
583137
583296
  }
583297
+ function cleanBriefText(value2, max) {
583298
+ const clean5 = String(value2 ?? "").replace(/\x1B\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\x00-\x1F\x7F]/g, " ").replace(/\s+/g, " ").trim();
583299
+ return clean5.length > max ? `${clean5.slice(0, Math.max(0, max - 1))}…` : clean5;
583300
+ }
583301
+ function firstBriefText(values) {
583302
+ for (const value2 of values) {
583303
+ const clean5 = cleanBriefText(value2, 320);
583304
+ if (!clean5)
583305
+ continue;
583306
+ if (/^take one narrow, evidence-backed action/i.test(clean5))
583307
+ continue;
583308
+ return clean5;
583309
+ }
583310
+ return "";
583311
+ }
583312
+ function uniqueBriefLines(values) {
583313
+ return [
583314
+ ...new Set(values.map((value2) => cleanBriefText(value2, 700)).filter(Boolean))
583315
+ ];
583316
+ }
583317
+ function asActionClause(value2) {
583318
+ return cleanBriefText(value2, 320).replace(/^to\s+/i, "").replace(/[.?!]+$/, "").replace(/^([A-Z])/, (match) => match.toLowerCase());
583319
+ }
583138
583320
  function selectWindows(lines, terms2) {
583139
583321
  const matched = [];
583140
583322
  for (let i2 = 0; i2 < lines.length; i2++) {
@@ -583185,12 +583367,17 @@ function selectWindows(lines, terms2) {
583185
583367
  score: m2.score
583186
583368
  }));
583187
583369
  }
583188
- function extractionPrompt(query, path16, windows) {
583370
+ function extractionPrompt(brief, path16, windows) {
583189
583371
  const blocks = windows.map((w) => `--- ${path16} lines ${w.start}-${w.end} ---
583190
583372
  ${w.text}`).join("\n\n");
583191
583373
  return [
583192
- `You are an extraction worker in a throwaway context. Extract ONLY what answers the query; do not summarize the whole file.`,
583193
- `Query: ${query}`,
583374
+ `You are an extraction worker in a throwaway context. Extract ONLY the information requested by the active agent; do not summarize the whole file.`,
583375
+ `[AGENTIC BRANCH REQUEST]`,
583376
+ `Request: ${brief.request}`,
583377
+ `Why this branch is needed now:`,
583378
+ ...brief.triggerEvidence.map((evidence) => `- ${evidence}`),
583379
+ `Return contract: ${brief.returnContract}`,
583380
+ `Retrieval focus: ${brief.retrievalQuery}`,
583194
583381
  ``,
583195
583382
  `File excerpts:`,
583196
583383
  blocks,
@@ -583229,7 +583416,14 @@ function parseExtraction(raw) {
583229
583416
  };
583230
583417
  }
583231
583418
  async function extractEvidence(opts) {
583232
- const { path: path16, query, content, fileVersion, backend } = opts;
583419
+ const { path: path16, content, fileVersion, backend } = opts;
583420
+ const brief = opts.brief ?? buildBranchExtractionBrief({
583421
+ path: path16,
583422
+ lineCount: content.split("\n").length,
583423
+ byteCount: content.length,
583424
+ assistantIntent: opts.query
583425
+ });
583426
+ const query = brief.retrievalQuery || opts.query;
583233
583427
  const lines = content.split("\n");
583234
583428
  const terms2 = queryTerms(query);
583235
583429
  if (terms2.length > 0) {
@@ -583304,7 +583498,7 @@ async function extractEvidence(opts) {
583304
583498
  const resp = await backend.chatCompletion({
583305
583499
  messages: [
583306
583500
  { role: "system", content: "You extract precise facts from file excerpts. Output ONLY a JSON object." },
583307
- { role: "user", content: extractionPrompt(query, path16, windows) }
583501
+ { role: "user", content: extractionPrompt(brief, path16, windows) }
583308
583502
  ],
583309
583503
  tools: [],
583310
583504
  temperature: 0,
@@ -585808,6 +586002,16 @@ function resolveTrajectoryCheckpointCadence(explicit) {
585808
586002
  const candidate = typeof explicit === "number" ? explicit : Number(process.env["OMNIUS_TRAJECTORY_CHECKPOINT_EVERY_TURNS"] ?? 4);
585809
586003
  return Number.isFinite(candidate) ? Math.max(1, Math.min(32, Math.floor(candidate))) : 4;
585810
586004
  }
586005
+ function resolveTrajectoryGroundingMode(explicit, subAgent) {
586006
+ if (explicit === "off" || explicit === "initial" || explicit === "adaptive") {
586007
+ return explicit;
586008
+ }
586009
+ const env2 = String(process.env["OMNIUS_TRAJECTORY_GROUNDING"] ?? "").trim().toLowerCase();
586010
+ if (env2 === "off" || env2 === "initial" || env2 === "adaptive") {
586011
+ return env2;
586012
+ }
586013
+ return subAgent ? "off" : "adaptive";
586014
+ }
585811
586015
  function upsertContextFrame(messages2, frame, marker = "[ACTIVE CONTEXT FRAME]") {
585812
586016
  for (let i2 = messages2.length - 1; i2 >= 0; i2--) {
585813
586017
  const m2 = messages2[i2];
@@ -586673,6 +586877,9 @@ var init_agenticRunner = __esm({
586673
586877
  _trajectoryRevision = 0;
586674
586878
  _trajectoryDirtyCauses = /* @__PURE__ */ new Set();
586675
586879
  _trajectoryLastEmittedToolCall = -1;
586880
+ _trajectoryGroundingAttemptedFingerprint = "";
586881
+ _trajectoryGroundingFingerprint = "";
586882
+ _trajectoryGeneratedGrounding = null;
586676
586883
  // -- File State Registry (SWE-agent inspired) --
586677
586884
  _fileRegistry = /* @__PURE__ */ new Map();
586678
586885
  // -- Memex Experience Archive (arXiv:2603.04257 inspired) --
@@ -588115,6 +588322,7 @@ ${parts.join("\n")}
588115
588322
  focusSupervisor: resolveFocusSupervisorMode(options2?.focusSupervisor),
588116
588323
  trajectoryCheckpoint: resolveTrajectoryCheckpointMode(options2?.trajectoryCheckpoint),
588117
588324
  trajectoryCheckpointEveryTurns: resolveTrajectoryCheckpointCadence(options2?.trajectoryCheckpointEveryTurns),
588325
+ trajectoryGrounding: resolveTrajectoryGroundingMode(options2?.trajectoryGrounding, options2?.subAgent),
588118
588326
  supervisorModel: options2?.supervisorModel ?? process.env["OMNIUS_SUPERVISOR_MODEL"] ?? "",
588119
588327
  supervisorTimeoutMs: options2?.supervisorTimeoutMs ?? Number(process.env["OMNIUS_SUPERVISOR_TIMEOUT_MS"] ?? 2e4),
588120
588328
  supervisorMaxTokens: options2?.supervisorMaxTokens ?? 900,
@@ -593645,7 +593853,16 @@ ${String(concreteGoal).replace(/\s+/g, " ").trim().slice(0, 1200)}` : null
593645
593853
  const churnBlock = this._renderWriteChurnBlock(turn);
593646
593854
  const focusBlock = this._focusSupervisor?.renderFrame() ?? null;
593647
593855
  const actionContractBlock = this._renderNextActionContract(turn);
593648
- const trajectoryCheckpoint = this._refreshTrajectoryCheckpoint(turn, focusBlock);
593856
+ const trajectoryCheckpoint = await this._refreshTrajectoryCheckpoint(turn, focusBlock, [
593857
+ workspaceTreeBlock,
593858
+ filesystemBlock,
593859
+ todoBlock,
593860
+ gitBlock,
593861
+ failureBlock,
593862
+ churnBlock,
593863
+ actionContractBlock,
593864
+ environmentBlock ?? null
593865
+ ].filter((block) => Boolean(block)));
593649
593866
  const trajectoryBlock = this.options.trajectoryCheckpoint === "shadow" ? null : trajectoryCheckpoint ? renderTrajectoryCheckpoint(trajectoryCheckpoint) : null;
593650
593867
  const toolCacheBlock = recentToolResults ? this._renderKnowledgeBlock(recentToolResults) : null;
593651
593868
  const anchorsBlock = this.surfaceAnchors(messages2);
@@ -595137,17 +595354,39 @@ ${notice}`;
595137
595354
  return "unknown";
595138
595355
  return entry.stale ? "stale" : "fresh";
595139
595356
  }
595357
+ /**
595358
+ * Turn a large whole-file read into an explicit request from the active
595359
+ * agent state, rather than treating the original user prompt as the query.
595360
+ */
595361
+ _buildBranchExtractionBrief(input) {
595362
+ const visibleAssistantIntent = [...input.messages].reverse().find((message2) => message2.role === "assistant" && typeof message2.content === "string" && message2.content.trim().length > 0);
595363
+ const assistantIntent = visibleAssistantIntent ? sanitizeTrajectoryText(sanitizeModelVisibleContextText(String(visibleAssistantIntent.content)), 320) : "";
595364
+ const trajectory = this._trajectoryCheckpoint;
595365
+ const latestFailure = this._recentFailures.at(-1);
595366
+ const recentFailure = latestFailure ? `${latestFailure.tool} at turn ${latestFailure.turn}: ${sanitizeTrajectoryText(latestFailure.error || latestFailure.output, 320)}` : "";
595367
+ return buildBranchExtractionBrief({
595368
+ path: input.path,
595369
+ lineCount: input.lineCount,
595370
+ byteCount: input.byteCount,
595371
+ assistantIntent,
595372
+ trajectoryAssessment: trajectory?.situationAssessment,
595373
+ trajectoryNextAction: trajectory?.nextAction || this._taskState.nextAction,
595374
+ trajectoryOpenQuestion: trajectory?.openQuestions[0],
595375
+ currentStep: this._taskState.currentStep,
595376
+ recentFailure
595377
+ });
595378
+ }
595140
595379
  /**
595141
595380
  * Rebuild the one current checkpoint at the context boundary. This shared
595142
595381
  * method is deliberately used by normal and brute-force loops via
595143
595382
  * _buildTurnContextFrame(), preventing separate prompt injections from
595144
595383
  * drifting apart or accumulating in history.
595145
595384
  */
595146
- _refreshTrajectoryCheckpoint(turn, focusDirective) {
595385
+ async _refreshTrajectoryCheckpoint(turn, focusDirective, supplementalEvidence = []) {
595147
595386
  if (this.options.trajectoryCheckpoint === "off")
595148
595387
  return null;
595149
595388
  const trigger = [...this._trajectoryDirtyCauses].join(",") || (this._trajectoryCheckpoint ? "cadence" : "task_start");
595150
- const provisional = buildTrajectoryCheckpoint({
595389
+ const buildInput = (generatedGrounding2) => ({
595151
595390
  turn,
595152
595391
  revision: Math.max(1, this._trajectoryRevision || 1),
595153
595392
  trigger,
@@ -595157,8 +595396,12 @@ ${notice}`;
595157
595396
  focusDirective,
595158
595397
  lastVerifier: this._worldFacts.lastTest,
595159
595398
  lastMutationTurn: this._lastFileWriteTurn,
595160
- evidenceFreshness: (path16) => this._trajectoryEvidenceFreshness(path16)
595399
+ evidenceFreshness: (path16) => this._trajectoryEvidenceFreshness(path16),
595400
+ generatedGrounding: generatedGrounding2
595161
595401
  });
595402
+ const deterministic = buildTrajectoryCheckpoint(buildInput());
595403
+ const generatedGrounding = await this._resolveTrajectoryGrounding(deterministic, trigger, turn, supplementalEvidence);
595404
+ const provisional = buildTrajectoryCheckpoint(buildInput(generatedGrounding));
595162
595405
  const { id: _id2, revision: _revision, turn: _turn, ...fingerprintInput } = provisional;
595163
595406
  const fingerprint = trajectoryCheckpointFingerprint(fingerprintInput);
595164
595407
  const changed = fingerprint !== this._trajectoryFingerprint;
@@ -595167,16 +595410,8 @@ ${notice}`;
595167
595410
  this._trajectoryFingerprint = fingerprint;
595168
595411
  }
595169
595412
  const checkpoint = buildTrajectoryCheckpoint({
595170
- turn,
595171
- revision: Math.max(1, this._trajectoryRevision),
595172
- trigger,
595173
- taskState: this._taskState,
595174
- observations: this._trajectoryObservations,
595175
- recentFailures: this._recentFailures,
595176
- focusDirective,
595177
- lastVerifier: this._worldFacts.lastTest,
595178
- lastMutationTurn: this._lastFileWriteTurn,
595179
- evidenceFreshness: (path16) => this._trajectoryEvidenceFreshness(path16)
595413
+ ...buildInput(generatedGrounding),
595414
+ revision: Math.max(1, this._trajectoryRevision)
595180
595415
  });
595181
595416
  this._trajectoryCheckpoint = checkpoint;
595182
595417
  const cadenceReached = this._taskState.toolCallCount - this._trajectoryLastEmittedToolCall >= this.options.trajectoryCheckpointEveryTurns;
@@ -595213,6 +595448,84 @@ ${notice}`;
595213
595448
  }
595214
595449
  return checkpoint;
595215
595450
  }
595451
+ /**
595452
+ * Run one bounded, tool-less orientation pass before the main agent acts.
595453
+ * Its output is treated as advisory language over an authoritative
595454
+ * deterministic safety checkpoint, so it can improve attention without
595455
+ * inventing a new file state or bypassing a recovery constraint.
595456
+ */
595457
+ async _resolveTrajectoryGrounding(checkpoint, trigger, turn, supplementalEvidence) {
595458
+ if (this.options.trajectoryCheckpoint === "shadow" || this.options.trajectoryGrounding === "off") {
595459
+ return null;
595460
+ }
595461
+ const { id: _id2, revision: _revision, turn: _turn, ...base3 } = checkpoint;
595462
+ const baseFingerprint = trajectoryCheckpointFingerprint(base3);
595463
+ if (this._trajectoryGroundingFingerprint === baseFingerprint) {
595464
+ return this._trajectoryGeneratedGrounding;
595465
+ }
595466
+ if (this._trajectoryGroundingAttemptedFingerprint === baseFingerprint) {
595467
+ return null;
595468
+ }
595469
+ const isInitial = !this._trajectoryCheckpoint || /(?:^|,)task_start(?:,|$)/.test(trigger);
595470
+ const assessmentChanged = checkpoint.assessment !== this._trajectoryCheckpoint?.assessment;
595471
+ const materialTrigger = /tool_failure|(?:^|,)error(?:,|$)|user_steering|compaction|status_change/.test(trigger);
595472
+ if (!isInitial && (this.options.trajectoryGrounding === "initial" || !assessmentChanged && !materialTrigger)) {
595473
+ return null;
595474
+ }
595475
+ this._trajectoryGroundingAttemptedFingerprint = baseFingerprint;
595476
+ try {
595477
+ this._emitModelResolutionTelemetry("trajectory_grounding", turn);
595478
+ const backend = this._auxInferenceBackend({
595479
+ dumpStage: "trajectory_grounding"
595480
+ });
595481
+ const response = await backend.chatCompletion({
595482
+ messages: [
595483
+ {
595484
+ role: "system",
595485
+ content: "You are Omnius's pre-action trajectory grounder. Return only the requested JSON. Produce a concrete, evidence-bound orientation, not generic process advice and not private chain-of-thought."
595486
+ },
595487
+ {
595488
+ role: "user",
595489
+ content: buildTrajectoryGroundingPrompt(checkpoint, supplementalEvidence)
595490
+ }
595491
+ ],
595492
+ tools: [],
595493
+ temperature: 0.15,
595494
+ maxTokens: 900,
595495
+ timeoutMs: Math.max(5e3, Math.min(this.options.requestTimeoutMs, 3e4)),
595496
+ // The output is an explicit concise assessment, not a hidden-think
595497
+ // transcript. Keep Qwen's structured response path reliable.
595498
+ think: false
595499
+ });
595500
+ const generated = parseTrajectoryGeneratedGrounding(response.choices?.[0]?.message?.content ?? "", checkpoint.groundedFacts.map((fact) => fact.evidence));
595501
+ if (!generated) {
595502
+ this.emit({
595503
+ type: "status",
595504
+ content: "Trajectory grounding returned no usable assessment; retaining deterministic safety orientation",
595505
+ turn,
595506
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
595507
+ });
595508
+ return null;
595509
+ }
595510
+ this._trajectoryGroundingFingerprint = baseFingerprint;
595511
+ this._trajectoryGeneratedGrounding = generated;
595512
+ this.emit({
595513
+ type: "status",
595514
+ content: `Trajectory grounding: model assessed ${isInitial ? "the initial task state" : "the changed task state"}`,
595515
+ turn,
595516
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
595517
+ });
595518
+ return generated;
595519
+ } catch {
595520
+ this.emit({
595521
+ type: "status",
595522
+ content: "Trajectory grounding unavailable; retaining deterministic safety orientation",
595523
+ turn,
595524
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
595525
+ });
595526
+ return null;
595527
+ }
595528
+ }
595216
595529
  emit(event) {
595217
595530
  this._observeTrajectoryEvent(event);
595218
595531
  for (const handler of this.handlers) {
@@ -595512,6 +595825,9 @@ Respond with your assessment, then take action.`;
595512
595825
  this._trajectoryRevision = 0;
595513
595826
  this._trajectoryDirtyCauses = /* @__PURE__ */ new Set(["task_start"]);
595514
595827
  this._trajectoryLastEmittedToolCall = -1;
595828
+ this._trajectoryGroundingAttemptedFingerprint = "";
595829
+ this._trajectoryGroundingFingerprint = "";
595830
+ this._trajectoryGeneratedGrounding = null;
595515
595831
  this._runStartTime = Date.now();
595516
595832
  this._runErrorCount = 0;
595517
595833
  this._runErrorPatterns = [];
@@ -600620,15 +600936,17 @@ Respond with EXACTLY this structure before your next tool call:
600620
600936
  }
600621
600937
  }
600622
600938
  if (fullContent && shouldBranchRead(trueBytes, trueLines, false)) {
600623
- const lastAssistant = [...messages2].reverse().find((m2) => m2.role === "assistant" && typeof m2.content === "string");
600624
- const query = [
600625
- this._taskState.goal ?? "",
600626
- typeof lastAssistant?.content === "string" ? lastAssistant.content : ""
600627
- ].join(" ").trim().slice(0, 400) || "key facts, configuration, and structure";
600939
+ const branchBrief = this._buildBranchExtractionBrief({
600940
+ path: pRaw,
600941
+ lineCount: trueLines,
600942
+ byteCount: trueBytes,
600943
+ messages: messages2
600944
+ });
600628
600945
  try {
600629
600946
  const ev = await extractEvidence({
600630
600947
  path: pRaw,
600631
- query,
600948
+ query: branchBrief.retrievalQuery,
600949
+ brief: branchBrief,
600632
600950
  content: fullContent,
600633
600951
  // the REAL body, not the preview
600634
600952
  fileVersion: this._worldFacts.files.get(pRaw)?.writeCount ?? 0,
@@ -600639,7 +600957,11 @@ Respond with EXACTLY this structure before your next tool call:
600639
600957
  });
600640
600958
  output = [
600641
600959
  `[BRANCH-EXTRACT] ${pRaw} is large (${trueLines} lines, ${trueBytes} bytes); a whole-file read only returns a preview, so it was read in an isolated branch and distilled.`,
600642
- `Distilled for: "${query.slice(0, 160)}"`,
600960
+ `[AGENTIC EXTRACTION REQUEST] ${branchBrief.request}`,
600961
+ `Evidence driving this request:`,
600962
+ ...branchBrief.triggerEvidence.map((evidence) => `- ${evidence}`),
600963
+ `Looking for: ${branchBrief.returnContract}`,
600964
+ `Retrieval focus: "${branchBrief.retrievalQuery.slice(0, 240)}"`,
600643
600965
  `Relevant evidence (lines ${ev.sourceStart ?? "?"}-${ev.sourceEnd ?? "?"}, confidence ${ev.confidence.toFixed(2)}):`,
600644
600966
  ev.claim,
600645
600967
  `If you need a different region, call file_read with a specific offset+limit. Do NOT re-read the whole file — you already have the relevant content above.`
@@ -615887,6 +616209,7 @@ __export(dist_exports3, {
615887
616209
  buildSteeringPacket: () => buildSteeringPacket,
615888
616210
  buildSubAgentSystemPrompt: () => buildSubAgentSystemPrompt,
615889
616211
  buildTrajectoryCheckpoint: () => buildTrajectoryCheckpoint,
616212
+ buildTrajectoryGroundingPrompt: () => buildTrajectoryGroundingPrompt,
615890
616213
  buildUnitTodos: () => buildUnitTodos,
615891
616214
  checkMilestoneComplete: () => checkMilestoneComplete,
615892
616215
  chooseCheapModelRoute: () => chooseCheapModelRoute,
@@ -616033,6 +616356,7 @@ __export(dist_exports3, {
616033
616356
  parseMetaCritique: () => parseMetaCritique,
616034
616357
  parsePlan: () => parsePlan,
616035
616358
  parseTextToolCalls: () => parseTextToolCalls,
616359
+ parseTrajectoryGeneratedGrounding: () => parseTrajectoryGeneratedGrounding,
616036
616360
  partitionToolCalls: () => partitionToolCalls,
616037
616361
  persistAgentTaskSidecar: () => persistAgentTaskSidecar,
616038
616362
  persistPlannerArtefacts: () => persistPlannerArtefacts,
@@ -620024,7 +620348,7 @@ function mergeRecentById(existing, incoming, limit) {
620024
620348
  for (const item of [...existing ?? [], ...incoming]) merged.set(item.id, item);
620025
620349
  return [...merged.values()].sort((a2, b) => b.observedAt - a2.observedAt).slice(0, limit);
620026
620350
  }
620027
- function parseJsonObject3(value2) {
620351
+ function parseJsonObject4(value2) {
620028
620352
  if (typeof value2 !== "string" || !value2.trim()) return null;
620029
620353
  try {
620030
620354
  const parsed = JSON.parse(value2);
@@ -620034,7 +620358,7 @@ function parseJsonObject3(value2) {
620034
620358
  }
620035
620359
  }
620036
620360
  function parseJsonObjectFromText(value2) {
620037
- const direct = parseJsonObject3(value2);
620361
+ const direct = parseJsonObject4(value2);
620038
620362
  if (direct) return direct;
620039
620363
  const text2 = String(value2 ?? "");
620040
620364
  const candidates = [];
@@ -620072,7 +620396,7 @@ function parseJsonObjectFromText(value2) {
620072
620396
  }
620073
620397
  }
620074
620398
  for (const candidate of candidates.reverse()) {
620075
- const parsed = parseJsonObject3(candidate);
620399
+ const parsed = parseJsonObject4(candidate);
620076
620400
  if (parsed) return parsed;
620077
620401
  }
620078
620402
  return null;
@@ -621083,7 +621407,7 @@ function formatLiveDashboardFromSnapshot(snapshot, opts = {}) {
621083
621407
  return lines;
621084
621408
  }
621085
621409
  function parseLiveMediaPayload(value2) {
621086
- const parsed = parseJsonObject3(value2);
621410
+ const parsed = parseJsonObject4(value2);
621087
621411
  if (!parsed) return null;
621088
621412
  if (!Array.isArray(parsed["objects"]) && !Array.isArray(parsed["tracks"]) && !Array.isArray(parsed["faces"]) && !Array.isArray(parsed["segments"])) return null;
621089
621413
  return parsed;
@@ -621104,7 +621428,7 @@ function parseFaceIdentity(face) {
621104
621428
  };
621105
621429
  }
621106
621430
  const raw = face.identity_candidates;
621107
- const parsed = typeof raw === "string" ? parseJsonObject3(raw) : typeof raw === "object" && raw !== null ? raw : null;
621431
+ const parsed = typeof raw === "string" ? parseJsonObject4(raw) : typeof raw === "object" && raw !== null ? raw : null;
621108
621432
  const faces = Array.isArray(parsed?.["faces"]) ? parsed["faces"] : [];
621109
621433
  const identified = faces.find((candidate) => candidate["identified"] === true && typeof candidate["name"] === "string" && candidate["name"]);
621110
621434
  if (identified) {
@@ -641970,6 +642294,17 @@ function buildTrajectoryLiveBlockLines(checkpoint, width, phase, truecolor = sup
641970
642294
  const bottom = `╰${"─".repeat(Math.max(0, w - 2))}╯`;
641971
642295
  const lines = [paint2(top, stage2, phase, 0, truecolor)];
641972
642296
  lines.push(row(`Goal: ${checkpoint.goal}`, inner, stage2, phase, truecolor));
642297
+ if (checkpoint.situationAssessment) {
642298
+ lines.push(
642299
+ row(
642300
+ `${checkpoint.groundingSource === "model" ? "Reasoned" : "Safety"}: ${checkpoint.situationAssessment}`,
642301
+ inner,
642302
+ stage2,
642303
+ phase,
642304
+ truecolor
642305
+ )
642306
+ );
642307
+ }
641973
642308
  lines.push(
641974
642309
  row(
641975
642310
  `Next: ${checkpoint.nextAction}`,
@@ -696240,7 +696575,7 @@ function numberArray(value2) {
696240
696575
  if (!Array.isArray(value2)) return [];
696241
696576
  return [...new Set(value2.map((item) => Number(item)).filter((item) => Number.isFinite(item)).map((item) => Math.trunc(item)))];
696242
696577
  }
696243
- function stringArray3(value2) {
696578
+ function stringArray4(value2) {
696244
696579
  if (!Array.isArray(value2)) return [];
696245
696580
  return [...new Set(value2.map((item) => clean4(item, 180)).filter(Boolean))];
696246
696581
  }
@@ -696311,7 +696646,7 @@ function buildTelegramReflectionExtractionPrompt(options2) {
696311
696646
  episodes || "none"
696312
696647
  ].join("\n");
696313
696648
  }
696314
- function parseJsonObject4(raw) {
696649
+ function parseJsonObject5(raw) {
696315
696650
  const text2 = raw.trim();
696316
696651
  if (!text2) return null;
696317
696652
  const fenced = text2.match(/```(?:json)?\s*([\s\S]*?)```/i)?.[1]?.trim();
@@ -696325,7 +696660,7 @@ function parseJsonObject4(raw) {
696325
696660
  }
696326
696661
  }
696327
696662
  function parseTelegramReflectionExtraction(raw) {
696328
- const parsed = parseJsonObject4(raw);
696663
+ const parsed = parseJsonObject5(raw);
696329
696664
  if (!parsed) return null;
696330
696665
  const tags = Array.isArray(parsed.tags) ? parsed.tags.map((item) => {
696331
696666
  const obj = item;
@@ -696334,8 +696669,8 @@ function parseTelegramReflectionExtraction(raw) {
696334
696669
  kind: clean4(obj.kind, 40) || "topic",
696335
696670
  confidence: clampConfidence(obj.confidence),
696336
696671
  sourceMessageIds: numberArray(obj.source_message_ids ?? obj.sourceMessageIds),
696337
- targetEpisodeIds: stringArray3(obj.target_episode_ids ?? obj.targetEpisodeIds),
696338
- targetNodeIds: stringArray3(obj.target_node_ids ?? obj.targetNodeIds)
696672
+ targetEpisodeIds: stringArray4(obj.target_episode_ids ?? obj.targetEpisodeIds),
696673
+ targetNodeIds: stringArray4(obj.target_node_ids ?? obj.targetNodeIds)
696339
696674
  };
696340
696675
  }).filter((item) => item.label) : [];
696341
696676
  const summaries = Array.isArray(parsed.summaries) ? parsed.summaries.map((item) => {
@@ -696346,7 +696681,7 @@ function parseTelegramReflectionExtraction(raw) {
696346
696681
  text: clean4(obj.text, 1200),
696347
696682
  confidence: clampConfidence(obj.confidence),
696348
696683
  sourceMessageIds: numberArray(obj.source_message_ids ?? obj.sourceMessageIds),
696349
- targetEpisodeIds: stringArray3(obj.target_episode_ids ?? obj.targetEpisodeIds)
696684
+ targetEpisodeIds: stringArray4(obj.target_episode_ids ?? obj.targetEpisodeIds)
696350
696685
  };
696351
696686
  }).filter((item) => item.title && item.text) : [];
696352
696687
  const titles = Array.isArray(parsed.titles) ? parsed.titles.map((item) => {
@@ -696356,7 +696691,7 @@ function parseTelegramReflectionExtraction(raw) {
696356
696691
  target: clean4(obj.target, 60) || "artifact",
696357
696692
  confidence: clampConfidence(obj.confidence),
696358
696693
  sourceMessageIds: numberArray(obj.source_message_ids ?? obj.sourceMessageIds),
696359
- targetEpisodeIds: stringArray3(obj.target_episode_ids ?? obj.targetEpisodeIds)
696694
+ targetEpisodeIds: stringArray4(obj.target_episode_ids ?? obj.targetEpisodeIds)
696360
696695
  };
696361
696696
  }).filter((item) => item.title) : [];
696362
696697
  const extractions = Array.isArray(parsed.extractions) ? parsed.extractions.map((item) => {
@@ -696366,8 +696701,8 @@ function parseTelegramReflectionExtraction(raw) {
696366
696701
  text: clean4(obj.text, 1e3),
696367
696702
  confidence: clampConfidence(obj.confidence),
696368
696703
  sourceMessageIds: numberArray(obj.source_message_ids ?? obj.sourceMessageIds),
696369
- targetEpisodeIds: stringArray3(obj.target_episode_ids ?? obj.targetEpisodeIds),
696370
- targetNodeIds: stringArray3(obj.target_node_ids ?? obj.targetNodeIds)
696704
+ targetEpisodeIds: stringArray4(obj.target_episode_ids ?? obj.targetEpisodeIds),
696705
+ targetNodeIds: stringArray4(obj.target_node_ids ?? obj.targetNodeIds)
696371
696706
  };
696372
696707
  }).filter((item) => item.text) : [];
696373
696708
  const links2 = Array.isArray(parsed.links) ? parsed.links.map((item) => {
@@ -696379,7 +696714,7 @@ function parseTelegramReflectionExtraction(raw) {
696379
696714
  confidence: clampConfidence(obj.confidence),
696380
696715
  fact: clean4(obj.fact, 500),
696381
696716
  sourceMessageIds: numberArray(obj.source_message_ids ?? obj.sourceMessageIds),
696382
- targetEpisodeIds: stringArray3(obj.target_episode_ids ?? obj.targetEpisodeIds)
696717
+ targetEpisodeIds: stringArray4(obj.target_episode_ids ?? obj.targetEpisodeIds)
696383
696718
  };
696384
696719
  }).filter((item) => item.srcNodeText && item.dstNodeText) : [];
696385
696720
  const followups = Array.isArray(parsed.followups) ? parsed.followups.map((item) => {
@@ -751658,7 +751993,10 @@ Only tools allowed by this profile are visible and executable.`
751658
751993
  personality: personality ? getPreset(personality) : void 0,
751659
751994
  personalityName: personality ?? void 0,
751660
751995
  identityInjection,
751661
- environmentProvider
751996
+ environmentProvider,
751997
+ // A real pre-action orientation is required before the main TUI agent
751998
+ // chooses its first tool; later failure/direction changes re-ground it.
751999
+ trajectoryGrounding: "adaptive"
751662
752000
  // Text tool mode is set dynamically after runner creation (async check)
751663
752001
  // The runner also auto-detects this when Ollama returns HTTP 400 for tools
751664
752002
  });
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "omnius",
3
- "version": "1.0.540",
3
+ "version": "1.0.542",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "omnius",
9
- "version": "1.0.540",
9
+ "version": "1.0.542",
10
10
  "bundleDependencies": [
11
11
  "image-to-ascii"
12
12
  ],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omnius",
3
- "version": "1.0.540",
3
+ "version": "1.0.542",
4
4
  "description": "AI coding agent powered by open-source models (Ollama/vLLM) — interactive TUI with agentic tool-calling loop",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",