omnius 1.0.546 → 1.0.548
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 +1433 -302
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -6559,11 +6559,29 @@ import { resolve as resolve4 } from "node:path";
|
|
|
6559
6559
|
function computeMaxUngatedLines(contextWindow) {
|
|
6560
6560
|
if (contextWindow <= 0)
|
|
6561
6561
|
return 200;
|
|
6562
|
-
const budget = Math.floor(contextWindow * 0.
|
|
6562
|
+
const budget = Math.floor(contextWindow * 0.2);
|
|
6563
6563
|
const maxLines = Math.floor(budget / 10);
|
|
6564
6564
|
return Math.max(80, Math.min(500, maxLines));
|
|
6565
6565
|
}
|
|
6566
|
-
function
|
|
6566
|
+
function exceedsInlineCharacterBudget(lines, contextWindow) {
|
|
6567
|
+
const sourceBytes = Buffer.byteLength(lines.join("\n"), "utf8");
|
|
6568
|
+
const projectedTokens = Math.ceil((sourceBytes + lines.length * 10 + 512) / 4);
|
|
6569
|
+
const tokenBudget = contextWindow > 0 ? Math.floor(contextWindow * 0.2) : 2e3;
|
|
6570
|
+
return projectedTokens > tokenBudget;
|
|
6571
|
+
}
|
|
6572
|
+
function boundedBranchPreview(prefix, preview, contextWindow) {
|
|
6573
|
+
const tokenBudget = contextWindow > 0 ? Math.floor(contextWindow * 0.2) : 2e3;
|
|
6574
|
+
const maxChars = Math.max(192, Math.max(0, tokenBudget - 128) * 4);
|
|
6575
|
+
const combined = `${prefix}
|
|
6576
|
+
${preview}`;
|
|
6577
|
+
if (combined.length <= maxChars)
|
|
6578
|
+
return combined;
|
|
6579
|
+
const suffix = "\n[preview truncated to the 20% context budget; use AgenticRunner branch extraction]";
|
|
6580
|
+
if (suffix.length >= maxChars)
|
|
6581
|
+
return suffix.slice(0, maxChars);
|
|
6582
|
+
return `${combined.slice(0, maxChars - suffix.length).trimEnd()}${suffix}`;
|
|
6583
|
+
}
|
|
6584
|
+
function buildStructuralPreview(lines, filePath, maxLines, lineOffset = 0) {
|
|
6567
6585
|
const total = lines.length;
|
|
6568
6586
|
const HEAD = Math.min(30, Math.floor(maxLines * 0.35));
|
|
6569
6587
|
const TAIL = Math.min(15, Math.floor(maxLines * 0.15));
|
|
@@ -6572,13 +6590,14 @@ function buildStructuralPreview(lines, filePath, maxLines) {
|
|
|
6572
6590
|
`);
|
|
6573
6591
|
parts.push(`## Lines 1-${HEAD}:`);
|
|
6574
6592
|
for (let i2 = 0; i2 < HEAD; i2++) {
|
|
6575
|
-
|
|
6593
|
+
const line = lines[i2] ?? "";
|
|
6594
|
+
parts.push(`${String(lineOffset + i2 + 1).padStart(6)} | ${line.slice(0, 400)}${line.length > 400 ? "…" : ""}`);
|
|
6576
6595
|
}
|
|
6577
6596
|
const sigs = [];
|
|
6578
6597
|
for (let i2 = HEAD; i2 < total - TAIL; i2++) {
|
|
6579
6598
|
const line = lines[i2];
|
|
6580
6599
|
if (SIG_PATTERNS.some((p2) => p2.test(line))) {
|
|
6581
|
-
sigs.push(`${String(i2 + 1).padStart(6)} | ${line}`);
|
|
6600
|
+
sigs.push(`${String(lineOffset + i2 + 1).padStart(6)} | ${line.slice(0, 400)}${line.length > 400 ? "…" : ""}`);
|
|
6582
6601
|
}
|
|
6583
6602
|
}
|
|
6584
6603
|
if (sigs.length > 0) {
|
|
@@ -6600,7 +6619,8 @@ function buildStructuralPreview(lines, filePath, maxLines) {
|
|
|
6600
6619
|
parts.push(`
|
|
6601
6620
|
## Lines ${tailStart + 1}-${total}:`);
|
|
6602
6621
|
for (let i2 = tailStart; i2 < total; i2++) {
|
|
6603
|
-
|
|
6622
|
+
const line = lines[i2] ?? "";
|
|
6623
|
+
parts.push(`${String(lineOffset + i2 + 1).padStart(6)} | ${line.slice(0, 400)}${line.length > 400 ? "…" : ""}`);
|
|
6604
6624
|
}
|
|
6605
6625
|
}
|
|
6606
6626
|
parts.push(``);
|
|
@@ -6656,7 +6676,7 @@ var init_file_read = __esm({
|
|
|
6656
6676
|
FileReadTool = class {
|
|
6657
6677
|
name = "file_read";
|
|
6658
6678
|
aliases = ["read_file", "read", "cat"];
|
|
6659
|
-
description = "Read
|
|
6679
|
+
description = "Read file contents. Payloads projected above 20% of context are branch-extracted by the agent runner; direct use returns a bounded structural preview. offset/limit does not bypass the budget.";
|
|
6660
6680
|
parameters = {
|
|
6661
6681
|
type: "object",
|
|
6662
6682
|
properties: {
|
|
@@ -6701,7 +6721,21 @@ var init_file_read = __esm({
|
|
|
6701
6721
|
const totalLines = lines.length;
|
|
6702
6722
|
if (offset !== void 0 || limit !== void 0) {
|
|
6703
6723
|
const startIdx = Math.max(0, (offset ?? 1) - 1);
|
|
6704
|
-
lines = lines.slice(startIdx, limit ? startIdx + limit : void 0);
|
|
6724
|
+
lines = lines.slice(startIdx, limit !== void 0 ? startIdx + Math.max(0, limit) : void 0);
|
|
6725
|
+
if (exceedsInlineCharacterBudget(lines, this._contextWindowSize)) {
|
|
6726
|
+
const maxLines2 = computeMaxUngatedLines(this._contextWindowSize);
|
|
6727
|
+
return {
|
|
6728
|
+
success: true,
|
|
6729
|
+
output: boundedBranchPreview([
|
|
6730
|
+
fileContextHeader(filePath, content, { offset, limit }),
|
|
6731
|
+
`[BRANCH_REQUIRED] The selected range exceeds 20% of the context window and was not inlined. An AgenticRunner must route this request through branch extraction; direct callers receive only this bounded structural preview.`
|
|
6732
|
+
].join("\n"), buildStructuralPreview(lines, filePath, maxLines2, startIdx), this._contextWindowSize),
|
|
6733
|
+
durationMs: performance.now() - start2,
|
|
6734
|
+
mutated: false,
|
|
6735
|
+
mutatedFiles: [],
|
|
6736
|
+
beforeHash: contentHash(content)
|
|
6737
|
+
};
|
|
6738
|
+
}
|
|
6705
6739
|
const numbered2 = lines.map((line, i2) => `${String(startIdx + i2 + 1).padStart(6)} | ${line}`).join("\n");
|
|
6706
6740
|
const hash = contentHash(content);
|
|
6707
6741
|
return {
|
|
@@ -6716,12 +6750,14 @@ ${numbered2}`,
|
|
|
6716
6750
|
}
|
|
6717
6751
|
touchFile(this.workingDir, filePath);
|
|
6718
6752
|
const maxLines = computeMaxUngatedLines(this._contextWindowSize);
|
|
6719
|
-
if (
|
|
6753
|
+
if (exceedsInlineCharacterBudget(lines, this._contextWindowSize)) {
|
|
6720
6754
|
const notes = getFileNotes(this.workingDir, filePath);
|
|
6721
6755
|
return {
|
|
6722
6756
|
success: true,
|
|
6723
|
-
output:
|
|
6724
|
-
|
|
6757
|
+
output: boundedBranchPreview([
|
|
6758
|
+
fileContextHeader(filePath, content),
|
|
6759
|
+
`[BRANCH_REQUIRED] This file exceeds 20% of the context window and was not inlined. An AgenticRunner must route it through branch extraction.`
|
|
6760
|
+
].join("\n"), `${buildStructuralPreview(lines, filePath, maxLines)}${notes ? "\n\n" + notes : ""}`, this._contextWindowSize),
|
|
6725
6761
|
durationMs: performance.now() - start2,
|
|
6726
6762
|
mutated: false,
|
|
6727
6763
|
mutatedFiles: [],
|
|
@@ -119450,7 +119486,7 @@ var require_auto = __commonJS({
|
|
|
119450
119486
|
// ../node_modules/acme-client/src/client.js
|
|
119451
119487
|
var require_client = __commonJS({
|
|
119452
119488
|
"../node_modules/acme-client/src/client.js"(exports, module) {
|
|
119453
|
-
var { createHash:
|
|
119489
|
+
var { createHash: createHash54 } = __require("crypto");
|
|
119454
119490
|
var { getPemBodyAsB64u } = require_crypto();
|
|
119455
119491
|
var { log: log22 } = require_logger();
|
|
119456
119492
|
var HttpClient = require_http();
|
|
@@ -119761,14 +119797,14 @@ var require_client = __commonJS({
|
|
|
119761
119797
|
*/
|
|
119762
119798
|
async getChallengeKeyAuthorization(challenge) {
|
|
119763
119799
|
const jwk = this.http.getJwk();
|
|
119764
|
-
const keysum =
|
|
119800
|
+
const keysum = createHash54("sha256").update(JSON.stringify(jwk));
|
|
119765
119801
|
const thumbprint = keysum.digest("base64url");
|
|
119766
119802
|
const result = `${challenge.token}.${thumbprint}`;
|
|
119767
119803
|
if (challenge.type === "http-01") {
|
|
119768
119804
|
return result;
|
|
119769
119805
|
}
|
|
119770
119806
|
if (challenge.type === "dns-01") {
|
|
119771
|
-
return
|
|
119807
|
+
return createHash54("sha256").update(result).digest("base64url");
|
|
119772
119808
|
}
|
|
119773
119809
|
if (challenge.type === "tls-alpn-01") {
|
|
119774
119810
|
return result;
|
|
@@ -124395,9 +124431,9 @@ var require_sha256 = __commonJS({
|
|
|
124395
124431
|
var forge = require_forge();
|
|
124396
124432
|
require_md();
|
|
124397
124433
|
require_util2();
|
|
124398
|
-
var
|
|
124399
|
-
forge.md.sha256 = forge.md.algorithms.sha256 =
|
|
124400
|
-
|
|
124434
|
+
var sha2566 = module.exports = forge.sha256 = forge.sha256 || {};
|
|
124435
|
+
forge.md.sha256 = forge.md.algorithms.sha256 = sha2566;
|
|
124436
|
+
sha2566.create = function() {
|
|
124401
124437
|
if (!_initialized) {
|
|
124402
124438
|
_init();
|
|
124403
124439
|
}
|
|
@@ -262448,7 +262484,7 @@ var require_websocket2 = __commonJS({
|
|
|
262448
262484
|
var http6 = __require("http");
|
|
262449
262485
|
var net5 = __require("net");
|
|
262450
262486
|
var tls2 = __require("tls");
|
|
262451
|
-
var { randomBytes: randomBytes31, createHash:
|
|
262487
|
+
var { randomBytes: randomBytes31, createHash: createHash54 } = __require("crypto");
|
|
262452
262488
|
var { Duplex: Duplex3, Readable } = __require("stream");
|
|
262453
262489
|
var { URL: URL3 } = __require("url");
|
|
262454
262490
|
var PerMessageDeflate3 = require_permessage_deflate2();
|
|
@@ -263108,7 +263144,7 @@ var require_websocket2 = __commonJS({
|
|
|
263108
263144
|
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
263109
263145
|
return;
|
|
263110
263146
|
}
|
|
263111
|
-
const digest3 =
|
|
263147
|
+
const digest3 = createHash54("sha1").update(key + GUID).digest("base64");
|
|
263112
263148
|
if (res.headers["sec-websocket-accept"] !== digest3) {
|
|
263113
263149
|
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
263114
263150
|
return;
|
|
@@ -263475,7 +263511,7 @@ var require_websocket_server = __commonJS({
|
|
|
263475
263511
|
var EventEmitter15 = __require("events");
|
|
263476
263512
|
var http6 = __require("http");
|
|
263477
263513
|
var { Duplex: Duplex3 } = __require("stream");
|
|
263478
|
-
var { createHash:
|
|
263514
|
+
var { createHash: createHash54 } = __require("crypto");
|
|
263479
263515
|
var extension3 = require_extension2();
|
|
263480
263516
|
var PerMessageDeflate3 = require_permessage_deflate2();
|
|
263481
263517
|
var subprotocol3 = require_subprotocol();
|
|
@@ -263776,7 +263812,7 @@ var require_websocket_server = __commonJS({
|
|
|
263776
263812
|
);
|
|
263777
263813
|
}
|
|
263778
263814
|
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
263779
|
-
const digest3 =
|
|
263815
|
+
const digest3 = createHash54("sha1").update(key + GUID).digest("base64");
|
|
263780
263816
|
const headers = [
|
|
263781
263817
|
"HTTP/1.1 101 Switching Protocols",
|
|
263782
263818
|
"Upgrade: websocket",
|
|
@@ -276583,13 +276619,13 @@ Justification: ${justification || "(none provided)"}`,
|
|
|
276583
276619
|
}
|
|
276584
276620
|
const snapshot = JSON.stringify(this.selfState, null, 2);
|
|
276585
276621
|
try {
|
|
276586
|
-
const { createHash:
|
|
276622
|
+
const { createHash: createHash54 } = await import("node:crypto");
|
|
276587
276623
|
const snapshotDir = join44(this.cwd, ".omnius", "identity", "snapshots");
|
|
276588
276624
|
await mkdir7(snapshotDir, { recursive: true });
|
|
276589
276625
|
const version5 = this.selfState.version;
|
|
276590
276626
|
const snapshotPath = join44(snapshotDir, `v${version5}.json`);
|
|
276591
276627
|
await writeFile12(snapshotPath, snapshot, "utf8");
|
|
276592
|
-
const hash =
|
|
276628
|
+
const hash = createHash54("sha256").update(snapshot).digest("hex");
|
|
276593
276629
|
await writeFile12(join44(this.cwd, ".omnius", "identity", "latest-hash.txt"), hash, "utf8");
|
|
276594
276630
|
let ipfsCid = "";
|
|
276595
276631
|
try {
|
|
@@ -276722,8 +276758,8 @@ New: ${newNarrative.slice(0, 200)}...`,
|
|
|
276722
276758
|
}
|
|
276723
276759
|
// ── Helpers ──────────────────────────────────────────────────────────────
|
|
276724
276760
|
createDefaultState() {
|
|
276725
|
-
const { createHash:
|
|
276726
|
-
const machineId =
|
|
276761
|
+
const { createHash: createHash54 } = __require("node:crypto");
|
|
276762
|
+
const machineId = createHash54("sha256").update(this.cwd).digest("hex").slice(0, 12);
|
|
276727
276763
|
return {
|
|
276728
276764
|
self_id: `omnius-${machineId}`,
|
|
276729
276765
|
version: 1,
|
|
@@ -276805,9 +276841,9 @@ New: ${newNarrative.slice(0, 200)}...`,
|
|
|
276805
276841
|
let cid;
|
|
276806
276842
|
if (this.selfState.version > prevVersion) {
|
|
276807
276843
|
try {
|
|
276808
|
-
const { createHash:
|
|
276844
|
+
const { createHash: createHash54 } = await import("node:crypto");
|
|
276809
276845
|
const stateJson = JSON.stringify(this.selfState);
|
|
276810
|
-
const hash =
|
|
276846
|
+
const hash = createHash54("sha256").update(stateJson).digest("hex").slice(0, 32);
|
|
276811
276847
|
const cidsPath = join44(this.cwd, ".omnius", "identity", "cids.json");
|
|
276812
276848
|
const cidsData = { latest: "", hash, version: this.selfState.version };
|
|
276813
276849
|
try {
|
|
@@ -566192,6 +566228,31 @@ var init_textSanitize = __esm({
|
|
|
566192
566228
|
});
|
|
566193
566229
|
|
|
566194
566230
|
// packages/orchestrator/dist/text-echo-guard.js
|
|
566231
|
+
function parseFloatEnv(name10, fallback, min, max) {
|
|
566232
|
+
const raw = process.env[name10];
|
|
566233
|
+
if (raw == null || raw.trim().length === 0)
|
|
566234
|
+
return fallback;
|
|
566235
|
+
const parsed = Number.parseFloat(raw);
|
|
566236
|
+
if (!Number.isFinite(parsed))
|
|
566237
|
+
return fallback;
|
|
566238
|
+
return Math.min(max, Math.max(min, parsed));
|
|
566239
|
+
}
|
|
566240
|
+
function parseIntEnv(name10, fallback, min, max) {
|
|
566241
|
+
const raw = process.env[name10];
|
|
566242
|
+
if (raw == null || raw.trim().length === 0)
|
|
566243
|
+
return fallback;
|
|
566244
|
+
const parsed = Number.parseInt(raw, 10);
|
|
566245
|
+
if (!Number.isFinite(parsed))
|
|
566246
|
+
return fallback;
|
|
566247
|
+
return Math.min(max, Math.max(min, parsed));
|
|
566248
|
+
}
|
|
566249
|
+
function readTextEchoGuardOptionsFromEnv() {
|
|
566250
|
+
return {
|
|
566251
|
+
similarityThreshold: parseFloatEnv("OMNIUS_TEXT_ECHO_SIMILARITY_THRESHOLD", DEFAULTS.similarityThreshold, 0, 1),
|
|
566252
|
+
minLength: parseIntEnv("OMNIUS_TEXT_ECHO_MIN_LENGTH", DEFAULTS.minLength, 1, 8192),
|
|
566253
|
+
window: parseIntEnv("OMNIUS_TEXT_ECHO_WINDOW", DEFAULTS.window, 1, 64)
|
|
566254
|
+
};
|
|
566255
|
+
}
|
|
566195
566256
|
function normalizeForEcho(text2) {
|
|
566196
566257
|
return text2.replace(/<think>[\s\S]*?<\/think>/gi, "").replace(/<reasoning>[\s\S]*?<\/reasoning>/gi, "").replace(/```[\s\S]*?```/g, " ").replace(/[*_`#>|-]+/g, " ").toLowerCase().replace(/\s+/g, " ").trim();
|
|
566197
566258
|
}
|
|
@@ -577071,6 +577132,7 @@ var init_streaming_executor = __esm({
|
|
|
577071
577132
|
reset() {
|
|
577072
577133
|
this.tools.clear();
|
|
577073
577134
|
this.insertionOrder = [];
|
|
577135
|
+
this.executeFn = null;
|
|
577074
577136
|
}
|
|
577075
577137
|
// ─────────────────────────────────────────────────────────
|
|
577076
577138
|
// Internal — Hannover-aligned concurrency control
|
|
@@ -578943,9 +579005,11 @@ var init_evidenceLedger = __esm({
|
|
|
578943
579005
|
if (!path16 || !content)
|
|
578944
579006
|
return;
|
|
578945
579007
|
const built = buildExtract(content);
|
|
579008
|
+
if (input.fidelity)
|
|
579009
|
+
built.fidelity = input.fidelity;
|
|
578946
579010
|
const existing = this.entries.get(path16);
|
|
578947
579011
|
if (existing && existing.readVersion === fileVersion && !existing.stale) {
|
|
578948
|
-
const keepNew = built.text.length >= existing.content.length;
|
|
579012
|
+
const keepNew = input.fidelity === "extract" || built.text.length >= existing.content.length;
|
|
578949
579013
|
this.entries.set(path16, {
|
|
578950
579014
|
...existing,
|
|
578951
579015
|
content: keepNew ? built.text : existing.content,
|
|
@@ -584082,6 +584146,7 @@ var init_completion_resolution_verifier = __esm({
|
|
|
584082
584146
|
});
|
|
584083
584147
|
|
|
584084
584148
|
// packages/orchestrator/dist/evidenceBranch.js
|
|
584149
|
+
import { createHash as createHash33 } from "node:crypto";
|
|
584085
584150
|
function buildBranchExtractionBrief(input) {
|
|
584086
584151
|
const path16 = cleanBriefText(input.path, 320) || "the requested file";
|
|
584087
584152
|
const intent = firstBriefText([
|
|
@@ -584091,37 +584156,75 @@ function buildBranchExtractionBrief(input) {
|
|
|
584091
584156
|
]);
|
|
584092
584157
|
const openQuestion = cleanBriefText(input.trajectoryOpenQuestion, 280);
|
|
584093
584158
|
const focus = openQuestion || intent;
|
|
584159
|
+
const goalAnchor = cleanBriefText(input.goalAnchor || input.currentStep || input.trajectoryAssessment || intent, 320);
|
|
584094
584160
|
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.`;
|
|
584161
|
+
const rangeLabel2 = input.requestedRange ? `requested range offset=${input.requestedRange.offset ?? 1}, limit=${input.requestedRange.limit ?? "EOF"}` : "whole-file read";
|
|
584162
|
+
const budgetLabel = input.projectedReadTokens && input.contextWindowTokens ? ` The projected payload is ~${Math.max(0, input.projectedReadTokens)} tokens of a ${Math.max(0, input.contextWindowTokens)}-token context.` : "";
|
|
584095
584163
|
const triggerEvidence = uniqueBriefLines([
|
|
584096
|
-
`The active action is a
|
|
584164
|
+
`The active action is a ${rangeLabel2} of ${path16}; disk inspection found ${Math.max(0, input.lineCount)} lines selected / ${Math.max(0, input.byteCount)} bytes selected.${budgetLabel}`,
|
|
584165
|
+
input.routingReason ? `Branch routing reason: ${cleanBriefText(input.routingReason, 300)}` : "",
|
|
584097
584166
|
input.trajectoryAssessment ? `Current trajectory assessment: ${cleanBriefText(input.trajectoryAssessment, 360)}` : "No current file-level evidence has been returned to the parent yet.",
|
|
584098
584167
|
input.currentStep ? `Current task step: ${cleanBriefText(input.currentStep, 260)}` : "",
|
|
584099
584168
|
input.recentFailure ? `Recent unresolved evidence: ${cleanBriefText(input.recentFailure, 320)}` : ""
|
|
584100
584169
|
]);
|
|
584101
584170
|
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.";
|
|
584102
|
-
const
|
|
584103
|
-
path16,
|
|
584104
|
-
focus,
|
|
584171
|
+
const requirementQuestions = uniqueBriefLines([
|
|
584105
584172
|
openQuestion,
|
|
584106
|
-
|
|
584173
|
+
intent,
|
|
584174
|
+
input.currentStep && input.currentStep !== intent ? input.currentStep : "",
|
|
584175
|
+
input.recentFailure ? `Which file-local declaration, value, or behavior explains this unresolved failure: ${cleanBriefText(input.recentFailure, 260)}` : ""
|
|
584176
|
+
]).slice(0, 3);
|
|
584177
|
+
if (requirementQuestions.length === 0) {
|
|
584178
|
+
requirementQuestions.push(`Which declarations, values, and behavior in this file are required for the next narrow action?`);
|
|
584179
|
+
}
|
|
584180
|
+
const requirements = requirementQuestions.map((question, index) => ({
|
|
584181
|
+
id: `R${index + 1}`,
|
|
584182
|
+
question,
|
|
584183
|
+
required: index === 0 || requirementQuestions.length === 1,
|
|
584184
|
+
expectedEvidence: "Exact source declarations, literal values, control/configuration behavior, and their line anchors.",
|
|
584185
|
+
searchTerms: queryTerms(question).slice(0, 16)
|
|
584186
|
+
}));
|
|
584187
|
+
const retrievalQuery = uniqueBriefLines([
|
|
584188
|
+
...requirements.map((requirement) => requirement.question),
|
|
584189
|
+
input.recentFailure
|
|
584107
584190
|
]).join(" ");
|
|
584191
|
+
const discoveryContract = {
|
|
584192
|
+
version: 1,
|
|
584193
|
+
path: path16,
|
|
584194
|
+
goalAnchor: goalAnchor || "Choose the next narrow evidence-backed action.",
|
|
584195
|
+
query: cleanBriefText(retrievalQuery, 700),
|
|
584196
|
+
requirements,
|
|
584197
|
+
completionCriteria: [
|
|
584198
|
+
"Every required requirement is either supported by an exact anchored segment or explicitly marked unresolved.",
|
|
584199
|
+
"Every returned factual claim names its source line span; discontiguous evidence remains separate.",
|
|
584200
|
+
"Stop when the contract is satisfied, no new query/range is available, or the bounded search budget is exhausted."
|
|
584201
|
+
],
|
|
584202
|
+
budget: {
|
|
584203
|
+
maxRounds: 3,
|
|
584204
|
+
maxWindowsPerRound: 3,
|
|
584205
|
+
maxTotalWindows: MAX_WINDOWS,
|
|
584206
|
+
maxPresentedLines: MAX_SNIPPET_LINES,
|
|
584207
|
+
maxInjectedChars: 2400
|
|
584208
|
+
}
|
|
584209
|
+
};
|
|
584108
584210
|
return {
|
|
584109
584211
|
request: cleanBriefText(request, 520),
|
|
584110
|
-
triggerEvidence: triggerEvidence.slice(0,
|
|
584212
|
+
triggerEvidence: triggerEvidence.slice(0, 5),
|
|
584111
584213
|
returnContract: cleanBriefText(returnContract, 520),
|
|
584112
|
-
retrievalQuery: cleanBriefText(retrievalQuery, 700)
|
|
584214
|
+
retrievalQuery: cleanBriefText(retrievalQuery, 700),
|
|
584215
|
+
discoveryContract
|
|
584113
584216
|
};
|
|
584114
584217
|
}
|
|
584115
|
-
function buildStructuralPreview2(lines, path16, query) {
|
|
584218
|
+
function buildStructuralPreview2(lines, path16, query, sourceLineOffset = 0) {
|
|
584116
584219
|
const n2 = lines.length;
|
|
584117
584220
|
const clip3 = (l2) => l2.length > 180 ? l2.slice(0, 180) + "…" : l2;
|
|
584118
|
-
const head = lines.slice(0, HEAD_LINES2).map((l2, i2) => `${i2 + 1}: ${clip3(l2)}`);
|
|
584221
|
+
const head = lines.slice(0, HEAD_LINES2).map((l2, i2) => `${sourceLineOffset + i2 + 1}: ${clip3(l2)}`);
|
|
584119
584222
|
const isStructural = (l2) => /^\s*(<[A-Za-z!]|#{1,6}\s|def |class |function |export |interface |type |async |public |private |\[[^\]]+\]|[A-Za-z_][\w.]*\s*=)/.test(l2) && l2.trim().length > 0 && l2.trim().length <= 180;
|
|
584120
584223
|
const markers = [];
|
|
584121
584224
|
for (let i2 = HEAD_LINES2; i2 < n2; i2++) {
|
|
584122
584225
|
const l2 = lines[i2];
|
|
584123
584226
|
if (isStructural(l2))
|
|
584124
|
-
markers.push(`${i2 + 1}: ${clip3(l2.trim())}`);
|
|
584227
|
+
markers.push(`${sourceLineOffset + i2 + 1}: ${clip3(l2.trim())}`);
|
|
584125
584228
|
}
|
|
584126
584229
|
const MAX_MARKERS = 30;
|
|
584127
584230
|
const sampled = markers.length > MAX_MARKERS ? Array.from({ length: MAX_MARKERS }, (_, k) => markers[Math.floor(k * markers.length / MAX_MARKERS)]) : markers;
|
|
@@ -584207,7 +584310,9 @@ function selectWindows(lines, terms2) {
|
|
|
584207
584310
|
return chosen.sort((a2, b) => a2.start - b.start).map((m2) => ({
|
|
584208
584311
|
start: m2.start + 1,
|
|
584209
584312
|
end: m2.end + 1,
|
|
584210
|
-
|
|
584313
|
+
// A one-line minified artifact can be hundreds of KB. The branch prompt
|
|
584314
|
+
// is bounded independently of line count; exact source remains local.
|
|
584315
|
+
text: lines.slice(m2.start, m2.end + 1).map((line) => line.length > 400 ? `${line.slice(0, 400)}…` : line).join("\n"),
|
|
584211
584316
|
score: m2.score
|
|
584212
584317
|
}));
|
|
584213
584318
|
}
|
|
@@ -584222,6 +584327,8 @@ ${w.text}`).join("\n\n");
|
|
|
584222
584327
|
...brief.triggerEvidence.map((evidence) => `- ${evidence}`),
|
|
584223
584328
|
`Return contract: ${brief.returnContract}`,
|
|
584224
584329
|
`Retrieval focus: ${brief.retrievalQuery}`,
|
|
584330
|
+
brief.discoveryContract ? `Discovery contract: ${JSON.stringify(brief.discoveryContract)}` : "",
|
|
584331
|
+
`Search-loop contract: resolve required facts from the supplied windows; if unresolved, return NEW narrow search terms. Never request or summarize the whole file.`,
|
|
584225
584332
|
``,
|
|
584226
584333
|
`File excerpts:`,
|
|
584227
584334
|
blocks,
|
|
@@ -584231,8 +584338,10 @@ ${w.text}`).join("\n\n");
|
|
|
584231
584338
|
` "source_start":<1-based line where the answer is, or null>,`,
|
|
584232
584339
|
` "source_end":<1-based end line, or null>,`,
|
|
584233
584340
|
` "confidence":0.0-1.0, // how sure the excerpts actually contain the answer`,
|
|
584341
|
+
` "satisfied_requirement_ids":["R1"],`,
|
|
584342
|
+
` "refined_search_terms":["new exact symbol or phrase"],`,
|
|
584234
584343
|
` "found":true|false}`
|
|
584235
|
-
].join("\n");
|
|
584344
|
+
].filter(Boolean).join("\n");
|
|
584236
584345
|
}
|
|
584237
584346
|
function parseExtraction(raw) {
|
|
584238
584347
|
if (!raw)
|
|
@@ -584256,127 +584365,442 @@ function parseExtraction(raw) {
|
|
|
584256
584365
|
sourceStart: num3(o2["source_start"]),
|
|
584257
584366
|
sourceEnd: num3(o2["source_end"]),
|
|
584258
584367
|
confidence: Math.min(1, Math.max(0, conf)),
|
|
584259
|
-
found: o2["found"] !== false
|
|
584368
|
+
found: o2["found"] !== false,
|
|
584369
|
+
satisfiedRequirementIds: Array.isArray(o2["satisfied_requirement_ids"]) ? o2["satisfied_requirement_ids"].map((value2) => cleanBriefText(value2, 40)).filter(Boolean).slice(0, 8) : [],
|
|
584370
|
+
refinedSearchTerms: Array.isArray(o2["refined_search_terms"]) ? o2["refined_search_terms"].map((value2) => cleanBriefText(value2, 80)).filter(Boolean).slice(0, 8) : []
|
|
584260
584371
|
};
|
|
584261
584372
|
}
|
|
584373
|
+
function sha2564(text2) {
|
|
584374
|
+
return createHash33("sha256").update(text2).digest("hex");
|
|
584375
|
+
}
|
|
584376
|
+
function lineNumberedExcerpt(lines, startIndex, endIndex, sourceLineOffset, maxLineChars = 240) {
|
|
584377
|
+
return lines.slice(startIndex, endIndex + 1).map((line, index) => {
|
|
584378
|
+
const clipped = line.length > maxLineChars ? `${line.slice(0, maxLineChars)}…` : line;
|
|
584379
|
+
return `${sourceLineOffset + startIndex + index + 1}: ${clipped}`;
|
|
584380
|
+
}).join("\n");
|
|
584381
|
+
}
|
|
584382
|
+
function rangesOverlap(a2, b) {
|
|
584383
|
+
return a2.startLine <= b.endLine + 1 && b.startLine <= a2.endLine + 1;
|
|
584384
|
+
}
|
|
584385
|
+
function makeSegment(input) {
|
|
584386
|
+
const segmentHash = sha2564(input.excerpt);
|
|
584387
|
+
return {
|
|
584388
|
+
id: `E${input.index + 1}-${segmentHash.slice(0, 10)}`,
|
|
584389
|
+
requirementIds: [...new Set(input.requirementIds)],
|
|
584390
|
+
summary: cleanBriefText(input.summary, 280),
|
|
584391
|
+
excerpt: input.excerpt,
|
|
584392
|
+
confidence: Math.min(1, Math.max(0, input.confidence)),
|
|
584393
|
+
anchor: {
|
|
584394
|
+
path: input.path,
|
|
584395
|
+
startLine: input.startLine,
|
|
584396
|
+
endLine: input.endLine,
|
|
584397
|
+
contentHash: input.contentHash,
|
|
584398
|
+
segmentHash
|
|
584399
|
+
}
|
|
584400
|
+
};
|
|
584401
|
+
}
|
|
584402
|
+
function renderSegments(segments, maxChars) {
|
|
584403
|
+
const blocks = [];
|
|
584404
|
+
let used = 0;
|
|
584405
|
+
for (const segment of segments) {
|
|
584406
|
+
const block = [
|
|
584407
|
+
`[${segment.id} ${segment.anchor.path}:L${segment.anchor.startLine}-L${segment.anchor.endLine} requirements=${segment.requirementIds.join(",") || "supporting"}]`,
|
|
584408
|
+
segment.excerpt
|
|
584409
|
+
].join("\n");
|
|
584410
|
+
if (used + block.length > maxChars && blocks.length > 0)
|
|
584411
|
+
break;
|
|
584412
|
+
const clipped = block.slice(0, Math.max(0, maxChars - used));
|
|
584413
|
+
blocks.push(clipped);
|
|
584414
|
+
used += clipped.length + 1;
|
|
584415
|
+
}
|
|
584416
|
+
return blocks.join("\n");
|
|
584417
|
+
}
|
|
584418
|
+
function legacyContiguousSpan(segments) {
|
|
584419
|
+
if (segments.length === 0)
|
|
584420
|
+
return { start: null, end: null };
|
|
584421
|
+
const sorted = [...segments].sort((a2, b) => a2.anchor.startLine - b.anchor.startLine);
|
|
584422
|
+
for (let index = 1; index < sorted.length; index++) {
|
|
584423
|
+
if (sorted[index].anchor.startLine > sorted[index - 1].anchor.endLine + 1) {
|
|
584424
|
+
return { start: null, end: null };
|
|
584425
|
+
}
|
|
584426
|
+
}
|
|
584427
|
+
return {
|
|
584428
|
+
start: sorted[0].anchor.startLine,
|
|
584429
|
+
end: sorted.at(-1).anchor.endLine
|
|
584430
|
+
};
|
|
584431
|
+
}
|
|
584432
|
+
function requirementSearchPasses(brief) {
|
|
584433
|
+
const requirements = brief.discoveryContract?.requirements ?? [];
|
|
584434
|
+
const passes = requirements.map((requirement) => ({
|
|
584435
|
+
id: requirement.id,
|
|
584436
|
+
query: requirement.question,
|
|
584437
|
+
strategy: "literal"
|
|
584438
|
+
}));
|
|
584439
|
+
if (passes.length === 0 && brief.retrievalQuery) {
|
|
584440
|
+
passes.push({ id: "R1", query: brief.retrievalQuery, strategy: "literal" });
|
|
584441
|
+
}
|
|
584442
|
+
return passes.slice(0, brief.discoveryContract?.budget.maxRounds ?? 3);
|
|
584443
|
+
}
|
|
584444
|
+
function deterministicSegments(input) {
|
|
584445
|
+
const { lines, path: path16, contentHash: contentHash2, sourceLineOffset, brief } = input;
|
|
584446
|
+
const segments = [];
|
|
584447
|
+
const satisfied = /* @__PURE__ */ new Set();
|
|
584448
|
+
const rounds = [];
|
|
584449
|
+
const lowers = lines.map((line) => line.toLowerCase());
|
|
584450
|
+
const lineCount = Math.max(1, lines.length);
|
|
584451
|
+
const passes = requirementSearchPasses(brief);
|
|
584452
|
+
let totalMatches = 0;
|
|
584453
|
+
for (const pass of passes) {
|
|
584454
|
+
const terms2 = queryTerms(pass.query);
|
|
584455
|
+
const weights = /* @__PURE__ */ new Map();
|
|
584456
|
+
for (const term of terms2) {
|
|
584457
|
+
let documentFrequency = 0;
|
|
584458
|
+
for (const line of lowers)
|
|
584459
|
+
if (line.includes(term))
|
|
584460
|
+
documentFrequency++;
|
|
584461
|
+
weights.set(term, documentFrequency === 0 ? 0 : Math.log(lineCount / documentFrequency) + 0.1);
|
|
584462
|
+
}
|
|
584463
|
+
const hits = [];
|
|
584464
|
+
for (let index = 0; index < lines.length; index++) {
|
|
584465
|
+
const matched = terms2.filter((term) => lowers[index].includes(term));
|
|
584466
|
+
const score = matched.reduce((sum2, term) => sum2 + (weights.get(term) ?? 0), 0);
|
|
584467
|
+
if (score > 0)
|
|
584468
|
+
hits.push({ index, score, matched });
|
|
584469
|
+
}
|
|
584470
|
+
totalMatches += hits.length;
|
|
584471
|
+
const ranked = hits.sort((a2, b) => b.score - a2.score).slice(0, 4);
|
|
584472
|
+
for (const hit of ranked) {
|
|
584473
|
+
if (segments.length >= input.maxSegments)
|
|
584474
|
+
break;
|
|
584475
|
+
const startIndex = Math.max(0, hit.index - 2);
|
|
584476
|
+
const endIndex = Math.min(lines.length - 1, hit.index + 2);
|
|
584477
|
+
const absolute = {
|
|
584478
|
+
startLine: sourceLineOffset + startIndex + 1,
|
|
584479
|
+
endLine: sourceLineOffset + endIndex + 1
|
|
584480
|
+
};
|
|
584481
|
+
if (segments.some((segment) => rangesOverlap(segment.anchor, absolute))) {
|
|
584482
|
+
continue;
|
|
584483
|
+
}
|
|
584484
|
+
const discriminatingTerms = terms2.filter((term) => (weights.get(term) ?? 0) > 0);
|
|
584485
|
+
const coverage = discriminatingTerms.length > 0 ? hit.matched.length / discriminatingTerms.length : 0;
|
|
584486
|
+
const confidence2 = Math.min(1, Math.max(0.2, coverage));
|
|
584487
|
+
if (confidence2 < EXTRACT_CONFIDENCE_FLOOR)
|
|
584488
|
+
continue;
|
|
584489
|
+
const excerpt = lineNumberedExcerpt(lines, startIndex, endIndex, sourceLineOffset);
|
|
584490
|
+
segments.push(makeSegment({
|
|
584491
|
+
path: path16,
|
|
584492
|
+
contentHash: contentHash2,
|
|
584493
|
+
requirementIds: [pass.id],
|
|
584494
|
+
summary: `Literal/identifier evidence for ${pass.query}`,
|
|
584495
|
+
excerpt,
|
|
584496
|
+
startLine: absolute.startLine,
|
|
584497
|
+
endLine: absolute.endLine,
|
|
584498
|
+
confidence: confidence2,
|
|
584499
|
+
index: segments.length
|
|
584500
|
+
}));
|
|
584501
|
+
satisfied.add(pass.id);
|
|
584502
|
+
}
|
|
584503
|
+
}
|
|
584504
|
+
rounds.push({
|
|
584505
|
+
round: 1,
|
|
584506
|
+
strategy: "literal",
|
|
584507
|
+
query: cleanBriefText(passes.map((pass) => pass.query).join(" | "), 180),
|
|
584508
|
+
matches: totalMatches
|
|
584509
|
+
});
|
|
584510
|
+
return { segments, satisfied: [...satisfied], rounds };
|
|
584511
|
+
}
|
|
584262
584512
|
async function extractEvidence(opts) {
|
|
584263
584513
|
const { path: path16, content, fileVersion, backend } = opts;
|
|
584514
|
+
const sourceLineOffset = Math.max(0, Math.floor(opts.sourceLineOffset ?? 0));
|
|
584264
584515
|
const brief = opts.brief ?? buildBranchExtractionBrief({
|
|
584265
584516
|
path: path16,
|
|
584266
584517
|
lineCount: content.split("\n").length,
|
|
584267
|
-
byteCount: content
|
|
584518
|
+
byteCount: Buffer.byteLength(content, "utf8"),
|
|
584268
584519
|
assistantIntent: opts.query
|
|
584269
584520
|
});
|
|
584270
584521
|
const query = brief.retrievalQuery || opts.query;
|
|
584271
584522
|
const lines = content.split("\n");
|
|
584272
|
-
const
|
|
584273
|
-
|
|
584274
|
-
|
|
584275
|
-
|
|
584276
|
-
|
|
584277
|
-
|
|
584278
|
-
|
|
584279
|
-
|
|
584280
|
-
|
|
584281
|
-
df++;
|
|
584282
|
-
weight.set(t2, df === 0 ? 0 : Math.log(N / df) + 0.1);
|
|
584523
|
+
const contentHash2 = opts.contentHash || sha2564(content);
|
|
584524
|
+
const byteCount = Buffer.byteLength(content, "utf8");
|
|
584525
|
+
const requirements = brief.discoveryContract?.requirements ?? [
|
|
584526
|
+
{
|
|
584527
|
+
id: "R1",
|
|
584528
|
+
question: query,
|
|
584529
|
+
required: true,
|
|
584530
|
+
expectedEvidence: "Anchored source evidence",
|
|
584531
|
+
searchTerms: queryTerms(query)
|
|
584283
584532
|
}
|
|
584284
|
-
|
|
584285
|
-
|
|
584286
|
-
|
|
584287
|
-
|
|
584288
|
-
|
|
584289
|
-
|
|
584290
|
-
|
|
584291
|
-
|
|
584292
|
-
|
|
584293
|
-
|
|
584294
|
-
|
|
584295
|
-
|
|
584296
|
-
|
|
584297
|
-
|
|
584298
|
-
|
|
584299
|
-
|
|
584300
|
-
|
|
584301
|
-
|
|
584302
|
-
|
|
584303
|
-
|
|
584304
|
-
|
|
584305
|
-
|
|
584306
|
-
|
|
584307
|
-
|
|
584308
|
-
|
|
584309
|
-
|
|
584310
|
-
|
|
584533
|
+
];
|
|
584534
|
+
const maxSegments = Math.max(1, Math.min(brief.discoveryContract?.budget.maxTotalWindows ?? MAX_WINDOWS, MAX_WINDOWS));
|
|
584535
|
+
const maxInjectedChars = Math.max(600, Math.min(brief.discoveryContract?.budget.maxInjectedChars ?? 2400, 4e3));
|
|
584536
|
+
const deterministic = deterministicSegments({
|
|
584537
|
+
lines,
|
|
584538
|
+
path: path16,
|
|
584539
|
+
contentHash: contentHash2,
|
|
584540
|
+
sourceLineOffset,
|
|
584541
|
+
brief,
|
|
584542
|
+
maxSegments
|
|
584543
|
+
});
|
|
584544
|
+
const requiredIds = requirements.filter((requirement) => requirement.required).map((requirement) => requirement.id);
|
|
584545
|
+
const deterministicSatisfied = new Set(deterministic.satisfied);
|
|
584546
|
+
if (deterministic.segments.length > 0 && requiredIds.every((id2) => deterministicSatisfied.has(id2))) {
|
|
584547
|
+
const claim = renderSegments(deterministic.segments, maxInjectedChars);
|
|
584548
|
+
const legacySpan = legacyContiguousSpan(deterministic.segments);
|
|
584549
|
+
return {
|
|
584550
|
+
path: path16,
|
|
584551
|
+
query,
|
|
584552
|
+
claim,
|
|
584553
|
+
sourceStart: legacySpan.start,
|
|
584554
|
+
sourceEnd: legacySpan.end,
|
|
584555
|
+
fileVersion,
|
|
584556
|
+
confidence: Math.max(...deterministic.segments.map((segment) => segment.confidence)),
|
|
584557
|
+
exploredLines: lines.length,
|
|
584558
|
+
injectedChars: claim.length,
|
|
584559
|
+
segments: deterministic.segments,
|
|
584560
|
+
satisfiedRequirementIds: [...deterministicSatisfied],
|
|
584561
|
+
unresolvedRequirementIds: requirements.map((requirement) => requirement.id).filter((id2) => !deterministicSatisfied.has(id2)),
|
|
584562
|
+
provenance: {
|
|
584563
|
+
contentHash: contentHash2,
|
|
584564
|
+
byteCount,
|
|
584565
|
+
lineCount: lines.length,
|
|
584566
|
+
fileVersion,
|
|
584567
|
+
exploredRanges: deterministic.segments.map((segment) => ({
|
|
584568
|
+
startLine: segment.anchor.startLine,
|
|
584569
|
+
endLine: segment.anchor.endLine
|
|
584570
|
+
})),
|
|
584571
|
+
searchRounds: deterministic.rounds,
|
|
584572
|
+
truncated: deterministic.segments.length >= maxSegments
|
|
584573
|
+
}
|
|
584574
|
+
};
|
|
584575
|
+
}
|
|
584576
|
+
const seenQueries = /* @__PURE__ */ new Set();
|
|
584577
|
+
let activeQuery = query;
|
|
584578
|
+
let parsed = null;
|
|
584579
|
+
let parsedWindows = [];
|
|
584580
|
+
const searchRounds = [...deterministic.rounds];
|
|
584581
|
+
let remainingWindows = Math.min(MAX_WINDOWS, brief.discoveryContract?.budget.maxTotalWindows ?? MAX_WINDOWS);
|
|
584582
|
+
let remainingPresentedLines = Math.min(MAX_SNIPPET_LINES, brief.discoveryContract?.budget.maxPresentedLines ?? MAX_SNIPPET_LINES);
|
|
584583
|
+
if (backend) {
|
|
584584
|
+
const maxSemanticRounds = Math.max(0, (brief.discoveryContract?.budget.maxRounds ?? 3) - searchRounds.length);
|
|
584585
|
+
for (let attempt = 0; attempt < Math.min(2, maxSemanticRounds); attempt++) {
|
|
584586
|
+
const queryKey = cleanBriefText(activeQuery, 700).toLowerCase();
|
|
584587
|
+
if (!queryKey || seenQueries.has(queryKey))
|
|
584588
|
+
break;
|
|
584589
|
+
seenQueries.add(queryKey);
|
|
584590
|
+
const activeTerms = queryTerms(activeQuery);
|
|
584591
|
+
const perRound = Math.min(remainingWindows, brief.discoveryContract?.budget.maxWindowsPerRound ?? 3);
|
|
584592
|
+
const selectedWindows = [];
|
|
584593
|
+
for (const window2 of selectWindows(lines, activeTerms)) {
|
|
584594
|
+
if (selectedWindows.length >= perRound)
|
|
584595
|
+
break;
|
|
584596
|
+
const windowLines = window2.end - window2.start + 1;
|
|
584597
|
+
if (windowLines > remainingPresentedLines)
|
|
584311
584598
|
continue;
|
|
584312
|
-
|
|
584313
|
-
|
|
584314
|
-
}
|
|
584315
|
-
|
|
584316
|
-
const
|
|
584317
|
-
|
|
584318
|
-
|
|
584319
|
-
|
|
584320
|
-
|
|
584321
|
-
|
|
584322
|
-
|
|
584323
|
-
|
|
584324
|
-
|
|
584325
|
-
|
|
584326
|
-
|
|
584327
|
-
|
|
584328
|
-
|
|
584329
|
-
|
|
584330
|
-
|
|
584331
|
-
|
|
584332
|
-
|
|
584333
|
-
|
|
584599
|
+
selectedWindows.push(window2);
|
|
584600
|
+
remainingPresentedLines -= windowLines;
|
|
584601
|
+
}
|
|
584602
|
+
remainingWindows -= selectedWindows.length;
|
|
584603
|
+
const relativeWindows = selectedWindows.map((window2) => ({
|
|
584604
|
+
start: window2.start + sourceLineOffset,
|
|
584605
|
+
end: window2.end + sourceLineOffset,
|
|
584606
|
+
text: window2.text
|
|
584607
|
+
}));
|
|
584608
|
+
if (relativeWindows.length === 0)
|
|
584609
|
+
break;
|
|
584610
|
+
parsedWindows = relativeWindows;
|
|
584611
|
+
searchRounds.push({
|
|
584612
|
+
round: searchRounds.length + 1,
|
|
584613
|
+
strategy: attempt === 0 ? "semantic" : "refined",
|
|
584614
|
+
query: cleanBriefText(activeQuery, 180),
|
|
584615
|
+
matches: relativeWindows.length
|
|
584616
|
+
});
|
|
584617
|
+
try {
|
|
584618
|
+
const resp = await backend.chatCompletion({
|
|
584619
|
+
messages: [
|
|
584620
|
+
{
|
|
584621
|
+
role: "system",
|
|
584622
|
+
content: "You extract precise facts from bounded file excerpts. Output ONLY a JSON object and never invent source text or line spans."
|
|
584623
|
+
},
|
|
584624
|
+
{ role: "user", content: extractionPrompt(brief, path16, relativeWindows) }
|
|
584625
|
+
],
|
|
584626
|
+
tools: [],
|
|
584627
|
+
temperature: 0,
|
|
584628
|
+
maxTokens: 900,
|
|
584629
|
+
timeoutMs: opts.timeoutMs ?? 3e4
|
|
584630
|
+
});
|
|
584631
|
+
parsed = parseExtraction(resp.choices?.[0]?.message?.content ?? "");
|
|
584632
|
+
} catch {
|
|
584633
|
+
parsed = null;
|
|
584334
584634
|
}
|
|
584635
|
+
if (parsed?.found)
|
|
584636
|
+
break;
|
|
584637
|
+
const refined = uniqueBriefLines(parsed?.refinedSearchTerms ?? []).join(" ");
|
|
584638
|
+
if (!refined || seenQueries.has(refined.toLowerCase()))
|
|
584639
|
+
break;
|
|
584640
|
+
activeQuery = refined;
|
|
584335
584641
|
}
|
|
584336
584642
|
}
|
|
584337
|
-
|
|
584338
|
-
|
|
584339
|
-
|
|
584340
|
-
|
|
584341
|
-
|
|
584342
|
-
|
|
584343
|
-
|
|
584344
|
-
|
|
584345
|
-
|
|
584346
|
-
|
|
584347
|
-
|
|
584348
|
-
|
|
584349
|
-
|
|
584350
|
-
|
|
584643
|
+
let semanticSegment = null;
|
|
584644
|
+
if (parsed?.found && parsed.claim && Number.isInteger(parsed.sourceStart) && Number.isInteger(parsed.sourceEnd) && parsed.sourceStart <= parsed.sourceEnd && parsedWindows.some((window2) => parsed.sourceStart >= window2.start && parsed.sourceEnd <= window2.end)) {
|
|
584645
|
+
const startIndex = parsed.sourceStart - sourceLineOffset - 1;
|
|
584646
|
+
const endIndex = parsed.sourceEnd - sourceLineOffset - 1;
|
|
584647
|
+
if (startIndex >= 0 && endIndex < lines.length) {
|
|
584648
|
+
semanticSegment = makeSegment({
|
|
584649
|
+
path: path16,
|
|
584650
|
+
contentHash: contentHash2,
|
|
584651
|
+
requirementIds: parsed.satisfiedRequirementIds.length > 0 ? parsed.satisfiedRequirementIds : [requirements[0].id],
|
|
584652
|
+
summary: parsed.claim,
|
|
584653
|
+
excerpt: lineNumberedExcerpt(lines, startIndex, endIndex, sourceLineOffset),
|
|
584654
|
+
startLine: parsed.sourceStart,
|
|
584655
|
+
endLine: parsed.sourceEnd,
|
|
584656
|
+
confidence: parsed.confidence,
|
|
584657
|
+
index: deterministic.segments.length
|
|
584351
584658
|
});
|
|
584352
|
-
parsed = parseExtraction(resp.choices?.[0]?.message?.content ?? "");
|
|
584353
|
-
} catch {
|
|
584354
|
-
parsed = null;
|
|
584355
584659
|
}
|
|
584356
584660
|
}
|
|
584357
|
-
const
|
|
584661
|
+
const segments = [...deterministic.segments];
|
|
584662
|
+
if (semanticSegment && !segments.some((segment) => rangesOverlap(segment.anchor, semanticSegment.anchor))) {
|
|
584663
|
+
segments.push(semanticSegment);
|
|
584664
|
+
}
|
|
584665
|
+
const satisfied = new Set(deterministic.satisfied);
|
|
584666
|
+
for (const segment of segments) {
|
|
584667
|
+
for (const id2 of segment.requirementIds)
|
|
584668
|
+
satisfied.add(id2);
|
|
584669
|
+
}
|
|
584670
|
+
if (segments.length > 0) {
|
|
584671
|
+
const claim = renderSegments(segments, maxInjectedChars);
|
|
584672
|
+
const legacySpan = legacyContiguousSpan(segments);
|
|
584673
|
+
return {
|
|
584674
|
+
path: path16,
|
|
584675
|
+
query,
|
|
584676
|
+
claim,
|
|
584677
|
+
sourceStart: legacySpan.start,
|
|
584678
|
+
sourceEnd: legacySpan.end,
|
|
584679
|
+
fileVersion,
|
|
584680
|
+
confidence: Math.max(...segments.map((segment) => segment.confidence)),
|
|
584681
|
+
exploredLines: Math.min(lines.length, parsedWindows.reduce((sum2, window2) => sum2 + (window2.end - window2.start + 1), 0) || lines.length),
|
|
584682
|
+
injectedChars: claim.length,
|
|
584683
|
+
segments,
|
|
584684
|
+
satisfiedRequirementIds: [...satisfied],
|
|
584685
|
+
unresolvedRequirementIds: requirements.map((requirement) => requirement.id).filter((id2) => !satisfied.has(id2)),
|
|
584686
|
+
provenance: {
|
|
584687
|
+
contentHash: contentHash2,
|
|
584688
|
+
byteCount,
|
|
584689
|
+
lineCount: lines.length,
|
|
584690
|
+
fileVersion,
|
|
584691
|
+
exploredRanges: segments.map((segment) => ({
|
|
584692
|
+
startLine: segment.anchor.startLine,
|
|
584693
|
+
endLine: segment.anchor.endLine
|
|
584694
|
+
})),
|
|
584695
|
+
searchRounds,
|
|
584696
|
+
truncated: segments.length >= maxSegments
|
|
584697
|
+
}
|
|
584698
|
+
};
|
|
584699
|
+
}
|
|
584700
|
+
const structuralClaim = buildStructuralPreview2(lines, path16, query, sourceLineOffset);
|
|
584701
|
+
const headEndIndex = Math.max(0, Math.min(lines.length - 1, HEAD_LINES2 - 1));
|
|
584702
|
+
const structuralSegment = makeSegment({
|
|
584703
|
+
path: path16,
|
|
584704
|
+
contentHash: contentHash2,
|
|
584705
|
+
requirementIds: [],
|
|
584706
|
+
summary: "Structural navigation anchor; required facts remain unresolved.",
|
|
584707
|
+
excerpt: lineNumberedExcerpt(lines, 0, headEndIndex, sourceLineOffset),
|
|
584708
|
+
startLine: sourceLineOffset + 1,
|
|
584709
|
+
endLine: sourceLineOffset + headEndIndex + 1,
|
|
584710
|
+
confidence: 0.2,
|
|
584711
|
+
index: 0
|
|
584712
|
+
});
|
|
584713
|
+
const maxRounds = brief.discoveryContract?.budget.maxRounds ?? 3;
|
|
584714
|
+
if (searchRounds.length < maxRounds) {
|
|
584715
|
+
searchRounds.push({
|
|
584716
|
+
round: searchRounds.length + 1,
|
|
584717
|
+
strategy: "structural",
|
|
584718
|
+
query: cleanBriefText(query, 180),
|
|
584719
|
+
matches: 1
|
|
584720
|
+
});
|
|
584721
|
+
}
|
|
584358
584722
|
return {
|
|
584359
584723
|
path: path16,
|
|
584360
584724
|
query,
|
|
584361
|
-
claim,
|
|
584362
|
-
sourceStart:
|
|
584363
|
-
sourceEnd:
|
|
584725
|
+
claim: structuralClaim.slice(0, maxInjectedChars),
|
|
584726
|
+
sourceStart: structuralSegment.anchor.startLine,
|
|
584727
|
+
sourceEnd: structuralSegment.anchor.endLine,
|
|
584364
584728
|
fileVersion,
|
|
584365
|
-
confidence:
|
|
584366
|
-
exploredLines,
|
|
584367
|
-
injectedChars:
|
|
584729
|
+
confidence: 0.2,
|
|
584730
|
+
exploredLines: Math.min(lines.length, HEAD_LINES2),
|
|
584731
|
+
injectedChars: Math.min(structuralClaim.length, maxInjectedChars),
|
|
584732
|
+
segments: [structuralSegment],
|
|
584733
|
+
satisfiedRequirementIds: [],
|
|
584734
|
+
unresolvedRequirementIds: requirements.map((requirement) => requirement.id),
|
|
584735
|
+
provenance: {
|
|
584736
|
+
contentHash: contentHash2,
|
|
584737
|
+
byteCount,
|
|
584738
|
+
lineCount: lines.length,
|
|
584739
|
+
fileVersion,
|
|
584740
|
+
exploredRanges: [
|
|
584741
|
+
{
|
|
584742
|
+
startLine: structuralSegment.anchor.startLine,
|
|
584743
|
+
endLine: structuralSegment.anchor.endLine
|
|
584744
|
+
}
|
|
584745
|
+
],
|
|
584746
|
+
searchRounds,
|
|
584747
|
+
truncated: true
|
|
584748
|
+
}
|
|
584368
584749
|
};
|
|
584369
584750
|
}
|
|
584370
|
-
function shouldBranchRead(contentLength, lineCount,
|
|
584371
|
-
if (hasExplicitSmallRange)
|
|
584372
|
-
return false;
|
|
584751
|
+
function shouldBranchRead(contentLength, lineCount, _hasExplicitSmallRange, thresholdChars = 8e3) {
|
|
584373
584752
|
return contentLength > thresholdChars || lineCount > 200;
|
|
584374
584753
|
}
|
|
584375
|
-
|
|
584754
|
+
function estimateFileReadInjectionTokens(sourceBytes, sourceLines) {
|
|
584755
|
+
const bytes = Math.max(0, Math.floor(sourceBytes));
|
|
584756
|
+
const lines = Math.max(0, Math.floor(sourceLines));
|
|
584757
|
+
return Math.ceil((bytes + lines * 10 + 512) / 4);
|
|
584758
|
+
}
|
|
584759
|
+
function assessBranchRead(input) {
|
|
584760
|
+
const projectedReadTokens = Math.max(0, Math.ceil(input.projectedReadTokens ?? estimateFileReadInjectionTokens(input.sourceBytes, input.sourceLines)));
|
|
584761
|
+
const contextWindowTokens = Math.max(0, Math.floor(input.contextWindowTokens));
|
|
584762
|
+
if (contextWindowTokens <= 0) {
|
|
584763
|
+
const legacy = shouldBranchRead(input.sourceBytes, input.sourceLines, false);
|
|
584764
|
+
return {
|
|
584765
|
+
branch: legacy,
|
|
584766
|
+
reasons: legacy ? ["legacy_size"] : [],
|
|
584767
|
+
projectedReadTokens,
|
|
584768
|
+
fractionLimitTokens: 0,
|
|
584769
|
+
availableHeadroomTokens: Number.POSITIVE_INFINITY,
|
|
584770
|
+
projectedFraction: 0,
|
|
584771
|
+
...input.requestedRange ? { requestedRange: input.requestedRange } : {}
|
|
584772
|
+
};
|
|
584773
|
+
}
|
|
584774
|
+
const fraction = Math.min(0.9, Math.max(0.01, input.maxInlineFraction ?? DEFAULT_BRANCH_READ_CONTEXT_FRACTION));
|
|
584775
|
+
const fractionLimitTokens = Math.floor(contextWindowTokens * fraction);
|
|
584776
|
+
const resident = Math.max(0, Math.ceil(input.residentContextTokens ?? 0));
|
|
584777
|
+
const reserved = Math.max(0, Math.ceil(input.reservedTokens ?? 0));
|
|
584778
|
+
const pending2 = Math.max(0, Math.ceil(input.pendingInlineReadTokens ?? 0));
|
|
584779
|
+
const safeCeiling = Math.max(0, Math.min(contextWindowTokens, Math.floor(input.safeContextTokens ?? contextWindowTokens)));
|
|
584780
|
+
const availableHeadroomTokens = Math.max(0, safeCeiling - resident - reserved - pending2);
|
|
584781
|
+
const reasons = [];
|
|
584782
|
+
if (projectedReadTokens > fractionLimitTokens)
|
|
584783
|
+
reasons.push("read_fraction");
|
|
584784
|
+
if (projectedReadTokens > availableHeadroomTokens)
|
|
584785
|
+
reasons.push("headroom");
|
|
584786
|
+
if (pending2 > 0 && pending2 + projectedReadTokens > fractionLimitTokens) {
|
|
584787
|
+
reasons.push("batch_budget");
|
|
584788
|
+
}
|
|
584789
|
+
return {
|
|
584790
|
+
branch: reasons.length > 0,
|
|
584791
|
+
reasons: [...new Set(reasons)],
|
|
584792
|
+
projectedReadTokens,
|
|
584793
|
+
fractionLimitTokens,
|
|
584794
|
+
availableHeadroomTokens,
|
|
584795
|
+
projectedFraction: projectedReadTokens / contextWindowTokens,
|
|
584796
|
+
...input.requestedRange ? { requestedRange: input.requestedRange } : {}
|
|
584797
|
+
};
|
|
584798
|
+
}
|
|
584799
|
+
var MAX_WINDOWS, SNIPPET_CONTEXT, HEAD_LINES2, MAX_SNIPPET_LINES, EXTRACT_CONFIDENCE_FLOOR, STOPWORDS2, DEFAULT_BRANCH_READ_CONTEXT_FRACTION;
|
|
584376
584800
|
var init_evidenceBranch = __esm({
|
|
584377
584801
|
"packages/orchestrator/dist/evidenceBranch.js"() {
|
|
584378
584802
|
"use strict";
|
|
584379
|
-
|
|
584803
|
+
MAX_WINDOWS = 6;
|
|
584380
584804
|
SNIPPET_CONTEXT = 4;
|
|
584381
584805
|
HEAD_LINES2 = 10;
|
|
584382
584806
|
MAX_SNIPPET_LINES = 220;
|
|
@@ -584414,6 +584838,7 @@ var init_evidenceBranch = __esm({
|
|
|
584414
584838
|
"report",
|
|
584415
584839
|
"tell"
|
|
584416
584840
|
]);
|
|
584841
|
+
DEFAULT_BRANCH_READ_CONTEXT_FRACTION = 0.2;
|
|
584417
584842
|
}
|
|
584418
584843
|
});
|
|
584419
584844
|
|
|
@@ -584836,7 +585261,7 @@ var init_prompt_cache = __esm({
|
|
|
584836
585261
|
|
|
584837
585262
|
// packages/orchestrator/dist/git-progress.js
|
|
584838
585263
|
import { existsSync as existsSync104, readFileSync as readFileSync80, statSync as statSync41 } from "node:fs";
|
|
584839
|
-
import { createHash as
|
|
585264
|
+
import { createHash as createHash34 } from "node:crypto";
|
|
584840
585265
|
import { relative as relative13, resolve as resolve56, sep as sep4 } from "node:path";
|
|
584841
585266
|
function isRunnerOwnedGitPath(path16) {
|
|
584842
585267
|
const normalized = normalizeGitPath(path16);
|
|
@@ -584863,7 +585288,7 @@ function pathHash(repoRoot, relPath) {
|
|
|
584863
585288
|
const st = statSync41(absolute);
|
|
584864
585289
|
if (!st.isFile())
|
|
584865
585290
|
return `non-file:${st.size}:${Math.floor(st.mtimeMs)}`;
|
|
584866
|
-
return
|
|
585291
|
+
return createHash34("sha256").update(readFileSync80(absolute)).digest("hex");
|
|
584867
585292
|
} catch {
|
|
584868
585293
|
return void 0;
|
|
584869
585294
|
}
|
|
@@ -585763,7 +586188,7 @@ __export(preflightSnapshot_exports, {
|
|
|
585763
586188
|
import { existsSync as existsSync105, readFileSync as readFileSync81, statSync as statSync42, statfsSync as statfsSync6 } from "node:fs";
|
|
585764
586189
|
import { homedir as homedir36, platform as platform4, arch as arch2, totalmem as totalmem4, freemem as freemem3, hostname as hostname3 } from "node:os";
|
|
585765
586190
|
import { join as join113 } from "node:path";
|
|
585766
|
-
import { createHash as
|
|
586191
|
+
import { createHash as createHash35 } from "node:crypto";
|
|
585767
586192
|
function capturePreflightSnapshot(workingDir) {
|
|
585768
586193
|
const warnings = [];
|
|
585769
586194
|
const configFingerprints = {};
|
|
@@ -585777,7 +586202,7 @@ function capturePreflightSnapshot(workingDir) {
|
|
|
585777
586202
|
} catch {
|
|
585778
586203
|
continue;
|
|
585779
586204
|
}
|
|
585780
|
-
configFingerprints[det.path] =
|
|
586205
|
+
configFingerprints[det.path] = sha2565(raw);
|
|
585781
586206
|
for (const w of det.check(raw)) {
|
|
585782
586207
|
warnings.push({ ...w, source: expanded });
|
|
585783
586208
|
}
|
|
@@ -585795,7 +586220,7 @@ function capturePreflightSnapshot(workingDir) {
|
|
|
585795
586220
|
} catch {
|
|
585796
586221
|
continue;
|
|
585797
586222
|
}
|
|
585798
|
-
configFingerprints[`<cwd>/${localName}`] =
|
|
586223
|
+
configFingerprints[`<cwd>/${localName}`] = sha2565(raw);
|
|
585799
586224
|
for (const w of det.check(raw)) {
|
|
585800
586225
|
warnings.push({ ...w, source: projectPath });
|
|
585801
586226
|
}
|
|
@@ -585931,8 +586356,8 @@ function expandPath(p2) {
|
|
|
585931
586356
|
return join113(homedir36(), p2.slice(2));
|
|
585932
586357
|
return p2;
|
|
585933
586358
|
}
|
|
585934
|
-
function
|
|
585935
|
-
return
|
|
586359
|
+
function sha2565(s2) {
|
|
586360
|
+
return createHash35("sha256").update(s2).digest("hex").slice(0, 16);
|
|
585936
586361
|
}
|
|
585937
586362
|
function freeDiskBytes(path16 = "/tmp") {
|
|
585938
586363
|
try {
|
|
@@ -587992,7 +588417,7 @@ var init_agenticRunner = __esm({
|
|
|
587992
588417
|
// 0.77–1.00 similarity, zero tool calls). Detects echoes, collapses the
|
|
587993
588418
|
// earlier duplicates out of the live context (removing the attractor), and
|
|
587994
588419
|
// requests a one-shot sampling perturbation for the next completion.
|
|
587995
|
-
_textEchoGuard = new TextEchoGuard();
|
|
588420
|
+
_textEchoGuard = new TextEchoGuard(readTextEchoGuardOptionsFromEnv());
|
|
587996
588421
|
// Turns remaining with a temperature floor applied to knock a greedy
|
|
587997
588422
|
// decoder off a repetition attractor. Set on echo detection; decremented
|
|
587998
588423
|
// when a request is built.
|
|
@@ -588246,6 +588671,13 @@ var init_agenticRunner = __esm({
|
|
|
588246
588671
|
// sees the evidence it already has instead of re-deriving it. See
|
|
588247
588672
|
// evidenceLedger.ts.
|
|
588248
588673
|
_evidenceLedger = new EvidenceLedger();
|
|
588674
|
+
/**
|
|
588675
|
+
* Curated branch nodes keyed by source hash + discovery contract. Raw source
|
|
588676
|
+
* is deliberately absent so retries/compaction cannot rehydrate it.
|
|
588677
|
+
*/
|
|
588678
|
+
_branchEvidenceCache = /* @__PURE__ */ new Map();
|
|
588679
|
+
/** Latest curated node per canonical path for safe post-compaction recovery. */
|
|
588680
|
+
_branchEvidenceByPath = /* @__PURE__ */ new Map();
|
|
588249
588681
|
// OBS-1: durable "current observed state" for non-file_read tool outputs
|
|
588250
588682
|
// (shell/web_fetch/list_directory/…). EvidenceLedger's counterpart for the
|
|
588251
588683
|
// observation channels that were previously invisible after compaction —
|
|
@@ -596099,7 +596531,31 @@ Rewrite it now for ${ctx3.model}.`;
|
|
|
596099
596531
|
};
|
|
596100
596532
|
}
|
|
596101
596533
|
try {
|
|
596102
|
-
const
|
|
596534
|
+
const callId = `runTool:${resolved.name}:${Date.now()}:${Math.random()}`;
|
|
596535
|
+
const batchBudget = {
|
|
596536
|
+
inlineTokens: 0,
|
|
596537
|
+
reservations: /* @__PURE__ */ new Map()
|
|
596538
|
+
};
|
|
596539
|
+
const preempted = await this._preemptFileReadWithBranch({
|
|
596540
|
+
callId,
|
|
596541
|
+
toolName: resolved.name,
|
|
596542
|
+
args,
|
|
596543
|
+
messages: [],
|
|
596544
|
+
turn: this._taskState.toolCallCount,
|
|
596545
|
+
batchBudget
|
|
596546
|
+
});
|
|
596547
|
+
if (preempted)
|
|
596548
|
+
return preempted;
|
|
596549
|
+
let result = await tool.execute(args);
|
|
596550
|
+
result = await this._guardMaterializedFileReadResult({
|
|
596551
|
+
callId,
|
|
596552
|
+
toolName: resolved.name,
|
|
596553
|
+
args,
|
|
596554
|
+
result,
|
|
596555
|
+
messages: [],
|
|
596556
|
+
turn: this._taskState.toolCallCount,
|
|
596557
|
+
batchBudget
|
|
596558
|
+
});
|
|
596103
596559
|
return this.applyRegisteredToolResultTriage(result, resolved.name, tool);
|
|
596104
596560
|
} catch (e2) {
|
|
596105
596561
|
return { success: false, output: "", error: e2?.message || String(e2) };
|
|
@@ -596324,8 +596780,309 @@ ${notice}`;
|
|
|
596324
596780
|
trajectoryNextAction: trajectory?.nextAction || this._taskState.nextAction,
|
|
596325
596781
|
trajectoryOpenQuestion: trajectory?.openQuestions[0],
|
|
596326
596782
|
currentStep: this._taskState.currentStep,
|
|
596327
|
-
recentFailure
|
|
596783
|
+
recentFailure,
|
|
596784
|
+
goalAnchor: trajectory?.currentStep || this._taskState.currentStep || this._taskState.nextAction,
|
|
596785
|
+
requestedRange: input.requestedRange,
|
|
596786
|
+
projectedReadTokens: input.routingDecision?.projectedReadTokens,
|
|
596787
|
+
contextWindowTokens: this._branchRoutingContextWindow(),
|
|
596788
|
+
routingReason: input.routingDecision?.reasons.join(", ")
|
|
596789
|
+
});
|
|
596790
|
+
}
|
|
596791
|
+
/** The usable total window for mandatory read routing. */
|
|
596792
|
+
_branchRoutingContextWindow() {
|
|
596793
|
+
const declared = Math.max(0, this.options.contextWindowSize ?? 0);
|
|
596794
|
+
const effective = Math.max(0, this.effectiveContextWindow());
|
|
596795
|
+
if (declared > 0 && effective > 0)
|
|
596796
|
+
return Math.min(declared, effective);
|
|
596797
|
+
return declared || effective;
|
|
596798
|
+
}
|
|
596799
|
+
_branchReadReservedTokens(contextWindow) {
|
|
596800
|
+
if (contextWindow <= 0)
|
|
596801
|
+
return 0;
|
|
596802
|
+
const generation = Math.min(this.contextLimits().maxOutputTokens, Math.max(1024, Math.floor(contextWindow * 0.15)));
|
|
596803
|
+
return generation + Math.max(512, Math.floor(contextWindow * 0.05));
|
|
596804
|
+
}
|
|
596805
|
+
_branchReadPath(args) {
|
|
596806
|
+
for (const key of ["path", "file", "file_path", "filename", "filepath"]) {
|
|
596807
|
+
const value2 = args[key];
|
|
596808
|
+
if (typeof value2 === "string" && value2.trim())
|
|
596809
|
+
return value2.trim();
|
|
596810
|
+
}
|
|
596811
|
+
return "";
|
|
596812
|
+
}
|
|
596813
|
+
/** Content identity used to prove an exact local read is still unchanged. */
|
|
596814
|
+
_fileReadDiskIdentity(args) {
|
|
596815
|
+
const path16 = this._branchReadPath(args);
|
|
596816
|
+
if (!path16)
|
|
596817
|
+
return null;
|
|
596818
|
+
try {
|
|
596819
|
+
const absolutePath = this._absoluteToolPath(path16);
|
|
596820
|
+
const stat9 = _fsStatSync(absolutePath);
|
|
596821
|
+
if (!stat9.isFile())
|
|
596822
|
+
return null;
|
|
596823
|
+
const content = _fsReadFileSync(absolutePath, "utf8");
|
|
596824
|
+
return {
|
|
596825
|
+
path: path16,
|
|
596826
|
+
canonicalPath: this._normalizeEvidencePath(path16),
|
|
596827
|
+
contentHash: _createHash("sha256").update(content).digest("hex"),
|
|
596828
|
+
byteCount: stat9.size,
|
|
596829
|
+
mtimeMs: stat9.mtimeMs
|
|
596830
|
+
};
|
|
596831
|
+
} catch {
|
|
596832
|
+
return null;
|
|
596833
|
+
}
|
|
596834
|
+
}
|
|
596835
|
+
/**
|
|
596836
|
+
* Mandatory pre-dispatch router for local file reads. It resolves exactly
|
|
596837
|
+
* once against the authoritative run directory, computes the actual selected
|
|
596838
|
+
* range, and intercepts unsafe reads before registered tool code or any
|
|
596839
|
+
* transcript/evidence consumer can observe raw content.
|
|
596840
|
+
*/
|
|
596841
|
+
async _preemptFileReadWithBranch(input) {
|
|
596842
|
+
if (this.lookupRegisteredTool(input.toolName)?.name !== "file_read") {
|
|
596843
|
+
return null;
|
|
596844
|
+
}
|
|
596845
|
+
const rawPath = this._branchReadPath(input.args);
|
|
596846
|
+
if (!rawPath)
|
|
596847
|
+
return null;
|
|
596848
|
+
let fullContent;
|
|
596849
|
+
let stat9;
|
|
596850
|
+
let absolutePath;
|
|
596851
|
+
try {
|
|
596852
|
+
absolutePath = this._absoluteToolPath(rawPath);
|
|
596853
|
+
stat9 = _fsStatSync(absolutePath);
|
|
596854
|
+
if (!stat9.isFile())
|
|
596855
|
+
return null;
|
|
596856
|
+
fullContent = _fsReadFileSync(absolutePath, "utf8");
|
|
596857
|
+
} catch {
|
|
596858
|
+
return null;
|
|
596859
|
+
}
|
|
596860
|
+
const allLines = fullContent.split("\n");
|
|
596861
|
+
const rawOffset = input.args["offset"];
|
|
596862
|
+
const rawLimit = input.args["limit"];
|
|
596863
|
+
const hasRange = typeof rawOffset === "number" || typeof rawLimit === "number";
|
|
596864
|
+
const offset = typeof rawOffset === "number" && Number.isFinite(rawOffset) ? Math.max(1, Math.floor(rawOffset)) : void 0;
|
|
596865
|
+
const limit = typeof rawLimit === "number" && Number.isFinite(rawLimit) ? Math.max(0, Math.floor(rawLimit)) : void 0;
|
|
596866
|
+
const startIndex = hasRange ? Math.max(0, (offset ?? 1) - 1) : 0;
|
|
596867
|
+
const selectedLines = hasRange ? allLines.slice(startIndex, limit === void 0 ? void 0 : startIndex + limit) : allLines;
|
|
596868
|
+
const selectedContent = selectedLines.join("\n");
|
|
596869
|
+
const selectedBytes = Buffer.byteLength(selectedContent, "utf8");
|
|
596870
|
+
const contextWindow = this._branchRoutingContextWindow();
|
|
596871
|
+
const residentTokens = estimateMessagesTokens2(input.messages);
|
|
596872
|
+
const reservedTokens = this._branchReadReservedTokens(contextWindow);
|
|
596873
|
+
const decision2 = assessBranchRead({
|
|
596874
|
+
sourceBytes: selectedBytes,
|
|
596875
|
+
sourceLines: selectedLines.length,
|
|
596876
|
+
contextWindowTokens: contextWindow,
|
|
596877
|
+
residentContextTokens: residentTokens,
|
|
596878
|
+
reservedTokens,
|
|
596879
|
+
pendingInlineReadTokens: input.batchBudget.inlineTokens,
|
|
596880
|
+
safeContextTokens: this.contextLimits().compactionThreshold,
|
|
596881
|
+
...hasRange ? { requestedRange: { offset, limit } } : {}
|
|
596882
|
+
});
|
|
596883
|
+
if (!decision2.branch) {
|
|
596884
|
+
input.batchBudget.inlineTokens += decision2.projectedReadTokens;
|
|
596885
|
+
input.batchBudget.reservations.set(input.callId, decision2.projectedReadTokens);
|
|
596886
|
+
return null;
|
|
596887
|
+
}
|
|
596888
|
+
const fullHash = _createHash("sha256").update(fullContent).digest("hex");
|
|
596889
|
+
const branchBrief = this._buildBranchExtractionBrief({
|
|
596890
|
+
path: rawPath,
|
|
596891
|
+
lineCount: selectedLines.length,
|
|
596892
|
+
byteCount: selectedBytes,
|
|
596893
|
+
messages: input.messages,
|
|
596894
|
+
...hasRange ? { requestedRange: { offset, limit } } : {},
|
|
596895
|
+
routingDecision: decision2
|
|
596896
|
+
});
|
|
596897
|
+
const contractFingerprint = _createHash("sha256").update(JSON.stringify(branchBrief.discoveryContract ?? branchBrief)).digest("hex").slice(0, 20);
|
|
596898
|
+
const canonicalPath = this._normalizeEvidencePath(rawPath);
|
|
596899
|
+
const cacheKey = `${canonicalPath}|${fullHash}|${offset ?? 0}:${limit ?? "EOF"}|${contractFingerprint}`;
|
|
596900
|
+
const cached = this._branchEvidenceCache.get(cacheKey);
|
|
596901
|
+
if (cached) {
|
|
596902
|
+
const duplicateBlocked = [
|
|
596903
|
+
`[BRANCH-DUPLICATE-BLOCKED] path=${rawPath} sha256=${fullHash} contract=${contractFingerprint}`,
|
|
596904
|
+
`The unchanged source was already branch-extracted into the current evidence ledger; the registered file_read was not executed and raw content was not re-injected.`,
|
|
596905
|
+
`Use the existing curated anchors. If a required discovery is unresolved, issue one narrower grep_search or a range whose projected payload stays below the 20% limit; otherwise take the next task action.`
|
|
596906
|
+
].join("\n");
|
|
596907
|
+
this.emit({
|
|
596908
|
+
type: "status",
|
|
596909
|
+
toolName: input.toolName,
|
|
596910
|
+
content: `Branch-extract cache hit: ${rawPath} sha256=${fullHash.slice(0, 12)} contract=${contractFingerprint}`,
|
|
596911
|
+
turn: input.turn,
|
|
596912
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
596913
|
+
});
|
|
596914
|
+
return {
|
|
596915
|
+
success: true,
|
|
596916
|
+
output: duplicateBlocked,
|
|
596917
|
+
llmContent: duplicateBlocked,
|
|
596918
|
+
beforeHash: fullHash,
|
|
596919
|
+
runtimeAuthored: true,
|
|
596920
|
+
noop: true,
|
|
596921
|
+
completionEvidenceMetrics: {
|
|
596922
|
+
branchSourceBytes: cached.sourceBytes,
|
|
596923
|
+
branchCacheHit: true
|
|
596924
|
+
}
|
|
596925
|
+
};
|
|
596926
|
+
}
|
|
596927
|
+
const extractionBackend = process.env["OMNIUS_DISABLE_BRANCH_EXTRACT"] === "1" ? void 0 : this._auxInferenceBackend();
|
|
596928
|
+
const ev = await extractEvidence({
|
|
596929
|
+
path: rawPath,
|
|
596930
|
+
query: branchBrief.retrievalQuery,
|
|
596931
|
+
brief: branchBrief,
|
|
596932
|
+
content: selectedContent,
|
|
596933
|
+
contentHash: fullHash,
|
|
596934
|
+
sourceLineOffset: startIndex,
|
|
596935
|
+
fileVersion: this._worldFacts.files.get(rawPath)?.writeCount ?? 0,
|
|
596936
|
+
backend: extractionBackend,
|
|
596937
|
+
timeoutMs: 3e4
|
|
596938
|
+
});
|
|
596939
|
+
const verboseOutput = [
|
|
596940
|
+
`[BRANCH-EXTRACT v2] path=${rawPath}`,
|
|
596941
|
+
`routing=mandatory reasons=${decision2.reasons.join(",")} projected_read_tokens=${decision2.projectedReadTokens} fraction_limit_tokens=${decision2.fractionLimitTokens} available_headroom_tokens=${decision2.availableHeadroomTokens}`,
|
|
596942
|
+
`source=sha256:${fullHash} selected_lines=${selectedLines.length} selected_bytes=${selectedBytes}${hasRange ? ` range=${offset ?? 1}:${limit ?? "EOF"}` : " range=whole"}`,
|
|
596943
|
+
`[DISCOVERY CONTRACT]`,
|
|
596944
|
+
`Goal anchor: ${branchBrief.discoveryContract?.goalAnchor ?? this._taskState.currentStep}`,
|
|
596945
|
+
`Request: ${branchBrief.request}`,
|
|
596946
|
+
`Required discoveries:`,
|
|
596947
|
+
...(branchBrief.discoveryContract?.requirements ?? []).map((requirement) => `- ${requirement.id}${requirement.required ? " [required]" : ""}: ${requirement.question}`),
|
|
596948
|
+
`Stop conditions: ${(branchBrief.discoveryContract?.completionCriteria ?? []).join(" | ")}`,
|
|
596949
|
+
`[CURATED SEGMENTS]`,
|
|
596950
|
+
ev.claim,
|
|
596951
|
+
`satisfied=${ev.satisfiedRequirementIds.join(",") || "none"}`,
|
|
596952
|
+
`unresolved=${ev.unresolvedRequirementIds.join(",") || "none"}`,
|
|
596953
|
+
`provenance=content:${ev.provenance.contentHash} searches:${ev.provenance.searchRounds.length} ranges:${ev.provenance.exploredRanges.map((range) => `L${range.startLine}-L${range.endLine}`).join(",")}`,
|
|
596954
|
+
`Contract: use these anchors as evidence. If a required item remains unresolved, issue one narrow grep_search or bounded file_read for that item; never re-read the whole file or expand a range past the 20% budget.`
|
|
596955
|
+
].join("\n");
|
|
596956
|
+
const outputBudgetChars = Math.max(800, decision2.fractionLimitTokens * 4);
|
|
596957
|
+
let output = verboseOutput;
|
|
596958
|
+
if (verboseOutput.length > outputBudgetChars) {
|
|
596959
|
+
const required = (branchBrief.discoveryContract?.requirements ?? []).filter((requirement) => requirement.required).map((requirement) => `${requirement.id}:${requirement.question.slice(0, 180)}`).join(" | ");
|
|
596960
|
+
const prefix = [
|
|
596961
|
+
`[BRANCH-EXTRACT v2] path=${rawPath} sha256=${fullHash}`,
|
|
596962
|
+
`routing=${decision2.reasons.join(",")} projected=${decision2.projectedReadTokens}/${contextWindow}t limit=${decision2.fractionLimitTokens}t`,
|
|
596963
|
+
`[DISCOVERY CONTRACT] required=${required || "next narrow file-local fact"}`,
|
|
596964
|
+
`[CURATED SEGMENTS]`
|
|
596965
|
+
].join("\n");
|
|
596966
|
+
const suffix = [
|
|
596967
|
+
`unresolved=${ev.unresolvedRequirementIds.join(",") || "none"}`,
|
|
596968
|
+
`anchors=${ev.provenance.exploredRanges.map((range) => `L${range.startLine}-L${range.endLine}`).join(",")}`,
|
|
596969
|
+
`Do not whole-read again; act on these anchors or issue one narrower search.`
|
|
596970
|
+
].join("\n");
|
|
596971
|
+
const claimBudget = Math.max(120, outputBudgetChars - prefix.length - suffix.length - 2);
|
|
596972
|
+
output = `${prefix}
|
|
596973
|
+
${ev.claim.slice(0, claimBudget)}
|
|
596974
|
+
${suffix}`.slice(0, outputBudgetChars);
|
|
596975
|
+
}
|
|
596976
|
+
this._branchEvidenceCache.set(cacheKey, {
|
|
596977
|
+
output,
|
|
596978
|
+
path: canonicalPath,
|
|
596979
|
+
contentHash: fullHash,
|
|
596980
|
+
sourceBytes: stat9.size,
|
|
596981
|
+
createdAt: Date.now()
|
|
596982
|
+
});
|
|
596983
|
+
this._branchEvidenceByPath.set(canonicalPath, {
|
|
596984
|
+
output,
|
|
596985
|
+
contentHash: fullHash,
|
|
596986
|
+
mtimeMs: stat9.mtimeMs
|
|
596987
|
+
});
|
|
596988
|
+
this.emit({
|
|
596989
|
+
type: "status",
|
|
596990
|
+
toolName: input.toolName,
|
|
596991
|
+
content: `Branch-extract preempted ${rawPath}: ${decision2.projectedReadTokens}/${contextWindow} projected tokens (${(decision2.projectedFraction * 100).toFixed(1)}%); resident=${residentTokens}t reserve=${reservedTokens}t pending_reads=${input.batchBudget.inlineTokens}t; ${selectedBytes}B → ${output.length} curated chars; reasons=${decision2.reasons.join(",")}`,
|
|
596992
|
+
turn: input.turn,
|
|
596993
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
596994
|
+
});
|
|
596995
|
+
return {
|
|
596996
|
+
success: true,
|
|
596997
|
+
output,
|
|
596998
|
+
llmContent: output,
|
|
596999
|
+
beforeHash: fullHash,
|
|
597000
|
+
runtimeAuthored: true,
|
|
597001
|
+
mutated: false,
|
|
597002
|
+
mutatedFiles: [],
|
|
597003
|
+
completionEvidenceMetrics: {
|
|
597004
|
+
branchSourceBytes: stat9.size,
|
|
597005
|
+
branchSelectedBytes: selectedBytes,
|
|
597006
|
+
branchProjectedTokens: decision2.projectedReadTokens
|
|
597007
|
+
}
|
|
597008
|
+
};
|
|
597009
|
+
}
|
|
597010
|
+
/** Fail-safe for virtual/custom file_read tools that cannot be statted locally. */
|
|
597011
|
+
async _guardMaterializedFileReadResult(input) {
|
|
597012
|
+
if (this.lookupRegisteredTool(input.toolName)?.name !== "file_read") {
|
|
597013
|
+
return input.result;
|
|
597014
|
+
}
|
|
597015
|
+
const reservedForThisCall = input.batchBudget.reservations.get(input.callId) ?? 0;
|
|
597016
|
+
if (!input.result.success) {
|
|
597017
|
+
if (reservedForThisCall > 0) {
|
|
597018
|
+
input.batchBudget.inlineTokens = Math.max(0, input.batchBudget.inlineTokens - reservedForThisCall);
|
|
597019
|
+
input.batchBudget.reservations.delete(input.callId);
|
|
597020
|
+
}
|
|
597021
|
+
return input.result;
|
|
597022
|
+
}
|
|
597023
|
+
if (!input.result.output)
|
|
597024
|
+
return input.result;
|
|
597025
|
+
const lines = input.result.output.split("\n");
|
|
597026
|
+
const contextWindow = this._branchRoutingContextWindow();
|
|
597027
|
+
const decision2 = assessBranchRead({
|
|
597028
|
+
sourceBytes: Buffer.byteLength(input.result.output, "utf8"),
|
|
597029
|
+
sourceLines: lines.length,
|
|
597030
|
+
contextWindowTokens: contextWindow,
|
|
597031
|
+
residentContextTokens: estimateMessagesTokens2(input.messages),
|
|
597032
|
+
reservedTokens: this._branchReadReservedTokens(contextWindow),
|
|
597033
|
+
pendingInlineReadTokens: Math.max(0, input.batchBudget.inlineTokens - reservedForThisCall),
|
|
597034
|
+
safeContextTokens: this.contextLimits().compactionThreshold
|
|
597035
|
+
});
|
|
597036
|
+
if (!decision2.branch) {
|
|
597037
|
+
if (reservedForThisCall === 0) {
|
|
597038
|
+
input.batchBudget.inlineTokens += decision2.projectedReadTokens;
|
|
597039
|
+
input.batchBudget.reservations.set(input.callId, decision2.projectedReadTokens);
|
|
597040
|
+
}
|
|
597041
|
+
return input.result;
|
|
597042
|
+
}
|
|
597043
|
+
if (reservedForThisCall > 0) {
|
|
597044
|
+
input.batchBudget.inlineTokens = Math.max(0, input.batchBudget.inlineTokens - reservedForThisCall);
|
|
597045
|
+
input.batchBudget.reservations.delete(input.callId);
|
|
597046
|
+
}
|
|
597047
|
+
const path16 = this._branchReadPath(input.args) || "virtual:file_read";
|
|
597048
|
+
const brief = this._buildBranchExtractionBrief({
|
|
597049
|
+
path: path16,
|
|
597050
|
+
lineCount: lines.length,
|
|
597051
|
+
byteCount: Buffer.byteLength(input.result.output, "utf8"),
|
|
597052
|
+
messages: input.messages,
|
|
597053
|
+
routingDecision: decision2
|
|
597054
|
+
});
|
|
597055
|
+
const ev = await extractEvidence({
|
|
597056
|
+
path: path16,
|
|
597057
|
+
query: brief.retrievalQuery,
|
|
597058
|
+
brief,
|
|
597059
|
+
content: input.result.output,
|
|
597060
|
+
fileVersion: 0,
|
|
597061
|
+
backend: process.env["OMNIUS_DISABLE_BRANCH_EXTRACT"] === "1" ? void 0 : this._auxInferenceBackend(),
|
|
597062
|
+
timeoutMs: 3e4
|
|
596328
597063
|
});
|
|
597064
|
+
const output = [
|
|
597065
|
+
`[BRANCH-EXTRACT v2] path=${path16}`,
|
|
597066
|
+
`routing=post-execution-failsafe reasons=${decision2.reasons.join(",")} projected_read_tokens=${decision2.projectedReadTokens}`,
|
|
597067
|
+
`[DISCOVERY CONTRACT] ${brief.request}`,
|
|
597068
|
+
`[CURATED SEGMENTS]`,
|
|
597069
|
+
ev.claim,
|
|
597070
|
+
`unresolved=${ev.unresolvedRequirementIds.join(",") || "none"}`,
|
|
597071
|
+
`provenance=content:${ev.provenance.contentHash} ranges:${ev.provenance.exploredRanges.map((range) => `L${range.startLine}-L${range.endLine}`).join(",")}`
|
|
597072
|
+
].join("\n").slice(0, Math.max(800, decision2.fractionLimitTokens * 4));
|
|
597073
|
+
return {
|
|
597074
|
+
...input.result,
|
|
597075
|
+
output,
|
|
597076
|
+
llmContent: output,
|
|
597077
|
+
beforeHash: input.result.beforeHash ?? ev.provenance.contentHash,
|
|
597078
|
+
runtimeAuthored: true,
|
|
597079
|
+
completionEvidenceMetrics: {
|
|
597080
|
+
...input.result.completionEvidenceMetrics,
|
|
597081
|
+
branchSourceBytes: Buffer.byteLength(input.result.output, "utf8"),
|
|
597082
|
+
branchSelectedBytes: Buffer.byteLength(input.result.output, "utf8"),
|
|
597083
|
+
branchProjectedTokens: decision2.projectedReadTokens
|
|
597084
|
+
}
|
|
597085
|
+
};
|
|
596329
597086
|
}
|
|
596330
597087
|
/**
|
|
596331
597088
|
* Build a child-task request from the live parent state. This is the common
|
|
@@ -597610,6 +598367,8 @@ TASK: ${scrubbedTask}` : scrubbedTask;
|
|
|
597610
598367
|
let completionTokens = 0;
|
|
597611
598368
|
let estimatedTokens = 0;
|
|
597612
598369
|
let toolCallCount = 0;
|
|
598370
|
+
let substantiveProgressCount = 0;
|
|
598371
|
+
const substantiveProgressFingerprints = /* @__PURE__ */ new Set();
|
|
597613
598372
|
let completed = false;
|
|
597614
598373
|
let summary = "";
|
|
597615
598374
|
let bruteForceCycle = 0;
|
|
@@ -597678,6 +598437,7 @@ TASK: ${scrubbedTask}` : scrubbedTask;
|
|
|
597678
598437
|
let lastCommitGateTurn = -1;
|
|
597679
598438
|
let lastShellPivotTurn = -1;
|
|
597680
598439
|
const recentToolResults = /* @__PURE__ */ new Map();
|
|
598440
|
+
const exactFileReadObservations = /* @__PURE__ */ new Map();
|
|
597681
598441
|
let fileMutationEpoch = 0;
|
|
597682
598442
|
const dedupHitCount = /* @__PURE__ */ new Map();
|
|
597683
598443
|
const noopedMemoryWriteFingerprints = /* @__PURE__ */ new Set();
|
|
@@ -599523,8 +600283,8 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
|
|
|
599523
600283
|
if (process.env["OMNIUS_DISABLE_ADAPTIVE_RETRIEVAL"] !== "1") {
|
|
599524
600284
|
const goalForSig = (this._taskState.goal || "").slice(0, 200);
|
|
599525
600285
|
const recentTools = this._toolSequence.slice(-5).join("|");
|
|
599526
|
-
const { createHash:
|
|
599527
|
-
const sig =
|
|
600286
|
+
const { createHash: createHash54 } = await import("node:crypto");
|
|
600287
|
+
const sig = createHash54("sha256").update(`${goalForSig}::${recentTools}`).digest("hex").slice(0, 16);
|
|
599528
600288
|
if (this._lastPprSig === sig && this._lastPprMemoryLines.length > 0) {
|
|
599529
600289
|
compacted.push({
|
|
599530
600290
|
role: "system",
|
|
@@ -599863,9 +600623,7 @@ ${memoryLines.join("\n")}`
|
|
|
599863
600623
|
const parsed = JSON.parse(jsonMatch[1]);
|
|
599864
600624
|
const resolvedParsedTool = parsed.tool ? this.lookupRegisteredTool(parsed.tool) : null;
|
|
599865
600625
|
if (parsed.tool && resolvedParsedTool) {
|
|
599866
|
-
const
|
|
599867
|
-
const rawResult = await tool.execute(parsed.args ?? {});
|
|
599868
|
-
const result = this.applyRegisteredToolResultTriage(rawResult, resolvedParsedTool.name, tool);
|
|
600626
|
+
const result = await this.runToolByName(resolvedParsedTool.name, parsed.args ?? {});
|
|
599869
600627
|
messages2.push({ role: "assistant", content });
|
|
599870
600628
|
messages2.push({
|
|
599871
600629
|
role: "system",
|
|
@@ -600140,6 +600898,10 @@ ${memoryLines.join("\n")}`
|
|
|
600140
600898
|
});
|
|
600141
600899
|
}
|
|
600142
600900
|
let editFeedbackRequiredBeforeMoreEdits = null;
|
|
600901
|
+
const branchReadBatchBudget = {
|
|
600902
|
+
inlineTokens: 0,
|
|
600903
|
+
reservations: /* @__PURE__ */ new Map()
|
|
600904
|
+
};
|
|
600143
600905
|
executeSingle = async (tc) => {
|
|
600144
600906
|
if (this.aborted)
|
|
600145
600907
|
return null;
|
|
@@ -600998,6 +601760,7 @@ ${cachedResult}`,
|
|
|
600998
601760
|
const resolvedTool = this.lookupRegisteredTool(tc.name);
|
|
600999
601761
|
const tool = resolvedTool?.tool;
|
|
601000
601762
|
let result;
|
|
601763
|
+
let fileReadSafetyChecked = false;
|
|
601001
601764
|
let runtimeSystemGuidance = null;
|
|
601002
601765
|
if (repeatShortCircuit) {
|
|
601003
601766
|
result = repeatShortCircuit;
|
|
@@ -601147,22 +601910,86 @@ ${cachedResult}`,
|
|
|
601147
601910
|
}
|
|
601148
601911
|
}
|
|
601149
601912
|
try {
|
|
601150
|
-
|
|
601151
|
-
|
|
601152
|
-
|
|
601153
|
-
|
|
601154
|
-
|
|
601155
|
-
|
|
601156
|
-
|
|
601157
|
-
|
|
601158
|
-
|
|
601159
|
-
|
|
601160
|
-
|
|
601161
|
-
|
|
601913
|
+
tc.arguments = finalArgs;
|
|
601914
|
+
const normalizedDispatchName = resolvedTool?.name ?? tc.name;
|
|
601915
|
+
let branchPreempted = null;
|
|
601916
|
+
if (normalizedDispatchName === "file_read") {
|
|
601917
|
+
const exactReadKey = this._buildToolFingerprint("file_read", tc.arguments);
|
|
601918
|
+
const priorRead = exactFileReadObservations.get(exactReadKey);
|
|
601919
|
+
if (priorRead) {
|
|
601920
|
+
const currentRead = this._fileReadDiskIdentity(tc.arguments);
|
|
601921
|
+
if (currentRead && currentRead.contentHash === priorRead.contentHash) {
|
|
601922
|
+
exactFileReadObservations.set(exactReadKey, currentRead);
|
|
601923
|
+
const duplicateOutput = [
|
|
601924
|
+
`[DUPLICATE_READ_BLOCKED] path=${currentRead.path} sha256=${currentRead.contentHash}`,
|
|
601925
|
+
`The exact file_read arguments already produced evidence from this unchanged source during the current run. The tool was not re-executed and the raw body was not re-injected.`,
|
|
601926
|
+
`Use the existing evidence/anchors now. To discover something different, issue one narrower offset/limit or grep_search with a new symbol; otherwise take the next mutation, verification, or completion action.`
|
|
601927
|
+
].join("\n");
|
|
601928
|
+
branchPreempted = {
|
|
601929
|
+
success: true,
|
|
601930
|
+
output: duplicateOutput,
|
|
601931
|
+
llmContent: duplicateOutput,
|
|
601932
|
+
beforeHash: currentRead.contentHash,
|
|
601933
|
+
runtimeAuthored: true,
|
|
601934
|
+
noop: true,
|
|
601935
|
+
completionEvidenceMetrics: {
|
|
601936
|
+
duplicateReadBlocked: true,
|
|
601937
|
+
duplicateReadSourceBytes: currentRead.byteCount
|
|
601938
|
+
}
|
|
601939
|
+
};
|
|
601940
|
+
this.emit({
|
|
601941
|
+
type: "status",
|
|
601942
|
+
toolName: normalizedDispatchName,
|
|
601943
|
+
content: `Exact unchanged file_read blocked before dispatch: ${currentRead.path} sha256=${currentRead.contentHash.slice(0, 12)}`,
|
|
601944
|
+
turn,
|
|
601945
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
601946
|
+
});
|
|
601947
|
+
} else {
|
|
601948
|
+
exactFileReadObservations.delete(exactReadKey);
|
|
601949
|
+
}
|
|
601162
601950
|
}
|
|
601163
|
-
|
|
601951
|
+
}
|
|
601952
|
+
if (!branchPreempted) {
|
|
601953
|
+
branchPreempted = await this._preemptFileReadWithBranch({
|
|
601954
|
+
callId: tc.id,
|
|
601955
|
+
toolName: normalizedDispatchName,
|
|
601956
|
+
args: tc.arguments,
|
|
601957
|
+
messages: messages2,
|
|
601958
|
+
turn,
|
|
601959
|
+
batchBudget: branchReadBatchBudget
|
|
601960
|
+
});
|
|
601961
|
+
}
|
|
601962
|
+
if (branchPreempted) {
|
|
601963
|
+
result = branchPreempted;
|
|
601964
|
+
fileReadSafetyChecked = true;
|
|
601164
601965
|
} else {
|
|
601165
|
-
|
|
601966
|
+
if (typeof tool.executeStream === "function") {
|
|
601967
|
+
const gen = tool.executeStream(finalArgs);
|
|
601968
|
+
let iterResult = await gen.next();
|
|
601969
|
+
while (!iterResult.done) {
|
|
601970
|
+
const progress = String(iterResult.value);
|
|
601971
|
+
this.emit({
|
|
601972
|
+
type: "status",
|
|
601973
|
+
toolName: tc.name,
|
|
601974
|
+
content: progress,
|
|
601975
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
601976
|
+
});
|
|
601977
|
+
iterResult = await gen.next();
|
|
601978
|
+
}
|
|
601979
|
+
result = iterResult.value;
|
|
601980
|
+
} else {
|
|
601981
|
+
result = await tool.execute(finalArgs);
|
|
601982
|
+
}
|
|
601983
|
+
result = await this._guardMaterializedFileReadResult({
|
|
601984
|
+
callId: tc.id,
|
|
601985
|
+
toolName: resolvedTool?.name ?? tc.name,
|
|
601986
|
+
args: tc.arguments,
|
|
601987
|
+
result,
|
|
601988
|
+
messages: messages2,
|
|
601989
|
+
turn,
|
|
601990
|
+
batchBudget: branchReadBatchBudget
|
|
601991
|
+
});
|
|
601992
|
+
fileReadSafetyChecked = true;
|
|
601166
601993
|
}
|
|
601167
601994
|
result = this.applyRegisteredToolResultTriage(result, resolvedTool?.name ?? tc.name, tool);
|
|
601168
601995
|
if (tc.name === "shell" && result.success === true) {
|
|
@@ -601262,6 +602089,23 @@ Respond with EXACTLY this structure before your next tool call:
|
|
|
601262
602089
|
}
|
|
601263
602090
|
}
|
|
601264
602091
|
}
|
|
602092
|
+
if (!fileReadSafetyChecked) {
|
|
602093
|
+
result = await this._guardMaterializedFileReadResult({
|
|
602094
|
+
callId: tc.id,
|
|
602095
|
+
toolName: resolvedTool?.name ?? tc.name,
|
|
602096
|
+
args: tc.arguments,
|
|
602097
|
+
result,
|
|
602098
|
+
messages: messages2,
|
|
602099
|
+
turn,
|
|
602100
|
+
batchBudget: branchReadBatchBudget
|
|
602101
|
+
});
|
|
602102
|
+
}
|
|
602103
|
+
if ((resolvedTool?.name ?? tc.name) === "file_read" && result.success === true && result.noop !== true) {
|
|
602104
|
+
const observedIdentity = this._fileReadDiskIdentity(tc.arguments);
|
|
602105
|
+
if (observedIdentity && (!result.beforeHash || result.beforeHash === observedIdentity.contentHash)) {
|
|
602106
|
+
exactFileReadObservations.set(this._buildToolFingerprint("file_read", tc.arguments), observedIdentity);
|
|
602107
|
+
}
|
|
602108
|
+
}
|
|
601265
602109
|
const shellFilesystemMutation = tc.name === "shell" && result.success === true && this._shellCommandLikelyMutatesFilesystem(String(tc.arguments?.["command"] ?? tc.arguments?.["cmd"] ?? ""));
|
|
601266
602110
|
this._releaseMutationWorkerLeaseForArgs(resolvedTool?.name ?? tc.name, tc.arguments, result, turn);
|
|
601267
602111
|
const shellMutationPaths = shellFilesystemMutation ? extractShellMutationPaths(String(tc.arguments?.["command"] ?? tc.arguments?.["cmd"] ?? ""), { workingDir: this.authoritativeWorkingDirectory() }).paths : [];
|
|
@@ -601312,6 +602156,13 @@ Respond with EXACTLY this structure before your next tool call:
|
|
|
601312
602156
|
writeCount: nextWriteCount
|
|
601313
602157
|
});
|
|
601314
602158
|
this._evidenceLedger.markMutated(this._normalizeEvidencePath(p2), nextWriteCount, turn);
|
|
602159
|
+
const branchPath = this._normalizeEvidencePath(p2);
|
|
602160
|
+
this._branchEvidenceByPath.delete(branchPath);
|
|
602161
|
+
for (const [cacheKey, cached] of this._branchEvidenceCache) {
|
|
602162
|
+
if (cached.path === branchPath) {
|
|
602163
|
+
this._branchEvidenceCache.delete(cacheKey);
|
|
602164
|
+
}
|
|
602165
|
+
}
|
|
601315
602166
|
{
|
|
601316
602167
|
const _normMut = this._normalizeEvidencePath(p2);
|
|
601317
602168
|
for (const _covKey of this._readCoverage.keys()) {
|
|
@@ -601351,7 +602202,7 @@ Respond with EXACTLY this structure before your next tool call:
|
|
|
601351
602202
|
const prev = this._worldFacts.files.get(p2);
|
|
601352
602203
|
this._worldFacts.files.set(p2, {
|
|
601353
602204
|
exists: result.success,
|
|
601354
|
-
size: (result.output || "").length,
|
|
602205
|
+
size: typeof result.completionEvidenceMetrics?.["branchSourceBytes"] === "number" ? result.completionEvidenceMetrics["branchSourceBytes"] : (result.output || "").length,
|
|
601355
602206
|
hashSample: (result.output || "").slice(0, 32),
|
|
601356
602207
|
lastSeenTurn: turn,
|
|
601357
602208
|
lastWriteTurn: prev?.lastWriteTurn,
|
|
@@ -601370,7 +602221,8 @@ Respond with EXACTLY this structure before your next tool call:
|
|
|
601370
602221
|
range: { start: start3, end },
|
|
601371
602222
|
fileVersion: this._worldFacts.files.get(p2)?.writeCount ?? 0,
|
|
601372
602223
|
mtimeMs: this._statMtimeMsForToolPath(p2),
|
|
601373
|
-
turn
|
|
602224
|
+
turn,
|
|
602225
|
+
fidelity: result.runtimeAuthored === true && result.output.startsWith("[BRANCH-EXTRACT") ? "extract" : void 0
|
|
601374
602226
|
});
|
|
601375
602227
|
}
|
|
601376
602228
|
if (this._fileSummaryStore && result.success && result.output && result.output.length > 100) {
|
|
@@ -602275,74 +603127,6 @@ Respond with EXACTLY this structure before your next tool call:
|
|
|
602275
603127
|
result = await this.offloadEmbeddedImageResult(result, tc.name, turn);
|
|
602276
603128
|
}
|
|
602277
603129
|
let output = this.normalizeToolOutput(result, tc.name, tc.arguments, turn);
|
|
602278
|
-
if (process.env["OMNIUS_DISABLE_BRANCH_EXTRACT"] !== "1" && this.lookupRegisteredTool(tc.name)?.name === "file_read" && result.success && this.backend && typeof this.backend.chatCompletion === "function") {
|
|
602279
|
-
const a2 = tc.arguments ?? {};
|
|
602280
|
-
const hasExplicitRange = typeof a2["offset"] === "number" || typeof a2["limit"] === "number";
|
|
602281
|
-
const pRaw = String(a2["path"] ?? a2["file"] ?? a2["file_path"] ?? "");
|
|
602282
|
-
if (!hasExplicitRange && pRaw) {
|
|
602283
|
-
let fullContent = null;
|
|
602284
|
-
let trueLines = 0;
|
|
602285
|
-
let trueBytes = 0;
|
|
602286
|
-
for (const cand of [
|
|
602287
|
-
pRaw,
|
|
602288
|
-
_pathResolve(this._workingDirectory || process.cwd(), pRaw)
|
|
602289
|
-
]) {
|
|
602290
|
-
try {
|
|
602291
|
-
const st = _fsStatSync(cand);
|
|
602292
|
-
if (st.isFile()) {
|
|
602293
|
-
trueBytes = st.size;
|
|
602294
|
-
if (trueBytes > 8e3) {
|
|
602295
|
-
fullContent = _fsReadFileSync(cand, "utf-8");
|
|
602296
|
-
trueLines = fullContent.split("\n").length;
|
|
602297
|
-
}
|
|
602298
|
-
break;
|
|
602299
|
-
}
|
|
602300
|
-
} catch {
|
|
602301
|
-
}
|
|
602302
|
-
}
|
|
602303
|
-
if (fullContent && shouldBranchRead(trueBytes, trueLines, false)) {
|
|
602304
|
-
const branchBrief = this._buildBranchExtractionBrief({
|
|
602305
|
-
path: pRaw,
|
|
602306
|
-
lineCount: trueLines,
|
|
602307
|
-
byteCount: trueBytes,
|
|
602308
|
-
messages: messages2
|
|
602309
|
-
});
|
|
602310
|
-
try {
|
|
602311
|
-
const ev = await extractEvidence({
|
|
602312
|
-
path: pRaw,
|
|
602313
|
-
query: branchBrief.retrievalQuery,
|
|
602314
|
-
brief: branchBrief,
|
|
602315
|
-
content: fullContent,
|
|
602316
|
-
// the REAL body, not the preview
|
|
602317
|
-
fileVersion: this._worldFacts.files.get(pRaw)?.writeCount ?? 0,
|
|
602318
|
-
// Native /api/chat so the extractor LLM fallback isn't
|
|
602319
|
-
// silently empty on qwen3-family models.
|
|
602320
|
-
backend: this._auxInferenceBackend(),
|
|
602321
|
-
timeoutMs: 3e4
|
|
602322
|
-
});
|
|
602323
|
-
output = [
|
|
602324
|
-
`[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.`,
|
|
602325
|
-
`[AGENTIC EXTRACTION REQUEST] ${branchBrief.request}`,
|
|
602326
|
-
`Evidence driving this request:`,
|
|
602327
|
-
...branchBrief.triggerEvidence.map((evidence) => `- ${evidence}`),
|
|
602328
|
-
`Looking for: ${branchBrief.returnContract}`,
|
|
602329
|
-
`Retrieval focus: "${branchBrief.retrievalQuery.slice(0, 240)}"`,
|
|
602330
|
-
`Relevant evidence (lines ${ev.sourceStart ?? "?"}-${ev.sourceEnd ?? "?"}, confidence ${ev.confidence.toFixed(2)}):`,
|
|
602331
|
-
ev.claim,
|
|
602332
|
-
`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.`
|
|
602333
|
-
].join("\n");
|
|
602334
|
-
this.emit({
|
|
602335
|
-
type: "status",
|
|
602336
|
-
toolName: tc.name,
|
|
602337
|
-
content: `Branch-extract: ${pRaw} (${trueLines} lines / ${trueBytes}B) → ${ev.injectedChars} chars to context (${(trueBytes / Math.max(1, ev.injectedChars)).toFixed(0)}× smaller)`,
|
|
602338
|
-
turn,
|
|
602339
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
602340
|
-
});
|
|
602341
|
-
} catch {
|
|
602342
|
-
}
|
|
602343
|
-
}
|
|
602344
|
-
}
|
|
602345
|
-
}
|
|
602346
603130
|
if (criticGuidance && !repeatShortCircuit) {
|
|
602347
603131
|
output += `
|
|
602348
603132
|
|
|
@@ -602426,6 +603210,22 @@ Evidence: ${evidencePreview}`.slice(0, 500);
|
|
|
602426
603210
|
turn,
|
|
602427
603211
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
602428
603212
|
});
|
|
603213
|
+
const branchCacheHit = result.completionEvidenceMetrics?.["branchCacheHit"] === true;
|
|
603214
|
+
const nonSubstantiveResult = result.noop === true || branchCacheHit || repeatShortCircuit !== null && result.runtimeAuthored === true;
|
|
603215
|
+
if (!nonSubstantiveResult) {
|
|
603216
|
+
const observationFingerprint = [
|
|
603217
|
+
this._buildToolFingerprint(tc.name, tc.arguments ?? {}),
|
|
603218
|
+
result.success ? "ok" : "error",
|
|
603219
|
+
result.beforeHash ?? "",
|
|
603220
|
+
result.afterHash ?? "",
|
|
603221
|
+
realMutationPaths.join(","),
|
|
603222
|
+
this.quickHash(String(result.output ?? result.error ?? result.llmContent ?? ""))
|
|
603223
|
+
].join("|");
|
|
603224
|
+
if (!substantiveProgressFingerprints.has(observationFingerprint)) {
|
|
603225
|
+
substantiveProgressFingerprints.add(observationFingerprint);
|
|
603226
|
+
substantiveProgressCount++;
|
|
603227
|
+
}
|
|
603228
|
+
}
|
|
602429
603229
|
this._taskState.toolCallCount++;
|
|
602430
603230
|
if (realFileMutation) {
|
|
602431
603231
|
this._lastFileWriteTurn = turn;
|
|
@@ -603716,24 +604516,24 @@ Your most recent tool calls SUCCEEDED. If the task is complete, call task_comple
|
|
|
603716
604516
|
} catch {
|
|
603717
604517
|
}
|
|
603718
604518
|
}
|
|
603719
|
-
let
|
|
604519
|
+
let prevCycleSubstantiveProgress = substantiveProgressCount;
|
|
603720
604520
|
while (!completed && !this.aborted && !this._completionIncompleteVerification && this.options.bruteForce && bruteForceCycle < this.options.bruteForceMaxCycles) {
|
|
603721
604521
|
bruteForceCycle++;
|
|
603722
604522
|
const totalTurns = messages2.filter((m2) => m2.role === "assistant").length;
|
|
603723
|
-
if (bruteForceCycle > 1 &&
|
|
604523
|
+
if (bruteForceCycle > 1 && substantiveProgressCount === prevCycleSubstantiveProgress) {
|
|
603724
604524
|
this.emit({
|
|
603725
604525
|
type: "status",
|
|
603726
|
-
content: `Stopping re-engagement —
|
|
604526
|
+
content: `Stopping re-engagement — cycle ${bruteForceCycle - 1} produced no new executed fingerprint, mutation, todo transition, or verifier evidence (${toolCallCount} attempted tool calls; ${substantiveProgressCount} substantive observations).`,
|
|
603727
604527
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
603728
604528
|
});
|
|
603729
604529
|
break;
|
|
603730
604530
|
}
|
|
603731
|
-
|
|
604531
|
+
prevCycleSubstantiveProgress = substantiveProgressCount;
|
|
603732
604532
|
consecutiveTextOnly = 0;
|
|
603733
604533
|
consecutiveThinkOnly = 0;
|
|
603734
604534
|
this.emit({
|
|
603735
604535
|
type: "status",
|
|
603736
|
-
content: `Re-engaging — cycle ${bruteForceCycle} (${totalTurns} turns, ${toolCallCount}
|
|
604536
|
+
content: `Re-engaging — cycle ${bruteForceCycle} (${totalTurns} turns, ${toolCallCount} attempted calls / ${substantiveProgressCount} substantive observations)`,
|
|
603737
604537
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
603738
604538
|
});
|
|
603739
604539
|
this._reg61CooldownUntilTurn = -1;
|
|
@@ -607553,7 +608353,7 @@ ${telegramPersonaHead}` : stripped
|
|
|
607553
608353
|
...stickyToKeep,
|
|
607554
608354
|
...filteredRecent
|
|
607555
608355
|
];
|
|
607556
|
-
const fileRecoveryBudget = Math.floor((this.
|
|
608356
|
+
const fileRecoveryBudget = Math.floor((this._branchRoutingContextWindow() || 32768) * 0.15);
|
|
607557
608357
|
const maxRecoverFiles = tier === "small" ? 3 : tier === "medium" ? 4 : 5;
|
|
607558
608358
|
const recoveredFiles = [];
|
|
607559
608359
|
if (this._fileRegistry.size > 0) {
|
|
@@ -607568,8 +608368,45 @@ ${telegramPersonaHead}` : stripped
|
|
|
607568
608368
|
for (const [filePath, entry] of entries) {
|
|
607569
608369
|
try {
|
|
607570
608370
|
const { readFileSync: readFileSync144 } = await import("node:fs");
|
|
607571
|
-
const
|
|
608371
|
+
const absolutePath = this._absoluteToolPath(filePath);
|
|
608372
|
+
const content = readFileSync144(absolutePath, "utf8");
|
|
607572
608373
|
const tokenEst = Math.ceil(content.length / 4);
|
|
608374
|
+
const canonicalPath = this._normalizeEvidencePath(filePath);
|
|
608375
|
+
const branchNode = this._branchEvidenceByPath.get(canonicalPath);
|
|
608376
|
+
const currentMtime = this._statMtimeMsForToolPath(filePath) ?? 0;
|
|
608377
|
+
if (branchNode && branchNode.mtimeMs === currentMtime) {
|
|
608378
|
+
const nodeTokens = Math.ceil(branchNode.output.length / 4);
|
|
608379
|
+
if (recoveredTokens + nodeTokens > fileRecoveryBudget)
|
|
608380
|
+
continue;
|
|
608381
|
+
result.push({
|
|
608382
|
+
role: "system",
|
|
608383
|
+
content: `<recovered-branch-evidence path="${filePath}" sha256="${branchNode.contentHash}">
|
|
608384
|
+
${branchNode.output}
|
|
608385
|
+
</recovered-branch-evidence>`
|
|
608386
|
+
});
|
|
608387
|
+
recoveredFiles.push(filePath);
|
|
608388
|
+
recoveredTokens += nodeTokens;
|
|
608389
|
+
continue;
|
|
608390
|
+
}
|
|
608391
|
+
const recoveryDecision = assessBranchRead({
|
|
608392
|
+
sourceBytes: Buffer.byteLength(content, "utf8"),
|
|
608393
|
+
sourceLines: content.split("\n").length,
|
|
608394
|
+
contextWindowTokens: this._branchRoutingContextWindow(),
|
|
608395
|
+
residentContextTokens: estimateMessagesTokens2(result),
|
|
608396
|
+
reservedTokens: this._branchReadReservedTokens(this._branchRoutingContextWindow()),
|
|
608397
|
+
pendingInlineReadTokens: recoveredTokens,
|
|
608398
|
+
safeContextTokens: this.contextLimits().compactionThreshold
|
|
608399
|
+
});
|
|
608400
|
+
if (recoveryDecision.branch) {
|
|
608401
|
+
const reference = `<recovered-file-reference path="${filePath}" status="${entry.modified ? "modified" : "read"}" routing="branch-required" projected_tokens="${recoveryDecision.projectedReadTokens}">Raw recovery suppressed by the 20% context contract; use the existing evidence ledger or issue one goal-scoped file_read.</recovered-file-reference>`;
|
|
608402
|
+
const referenceTokens = Math.ceil(reference.length / 4);
|
|
608403
|
+
if (recoveredTokens + referenceTokens <= fileRecoveryBudget) {
|
|
608404
|
+
result.push({ role: "system", content: reference });
|
|
608405
|
+
recoveredFiles.push(filePath);
|
|
608406
|
+
recoveredTokens += referenceTokens;
|
|
608407
|
+
}
|
|
608408
|
+
continue;
|
|
608409
|
+
}
|
|
607573
608410
|
if (recoveredTokens + tokenEst > fileRecoveryBudget)
|
|
607574
608411
|
break;
|
|
607575
608412
|
const truncated = content.length > 8e3;
|
|
@@ -607639,6 +608476,7 @@ ${content.slice(0, 8e3)}${truncated ? "\n[truncated recovery; use a narrow live
|
|
|
607639
608476
|
} catch {
|
|
607640
608477
|
}
|
|
607641
608478
|
}
|
|
608479
|
+
const protectedRecoveryMessages = result.filter((message2) => message2.role === "system" && typeof message2.content === "string" && /^<recovered-(?:branch-evidence|file-reference|file)\b/.test(message2.content));
|
|
607642
608480
|
const ctxWindow = this.options.contextWindowSize;
|
|
607643
608481
|
if (ctxWindow > 0) {
|
|
607644
608482
|
const _safetyImgPat = /\[IMAGE_BASE64:[^\]]+\]/g;
|
|
@@ -607676,6 +608514,7 @@ ${content.slice(0, 8e3)}${truncated ? "\n[truncated recovery; use a narrow live
|
|
|
607676
608514
|
...narrowedHead,
|
|
607677
608515
|
compactionMsg,
|
|
607678
608516
|
...stickyToKeep,
|
|
608517
|
+
...protectedRecoveryMessages,
|
|
607679
608518
|
...trimmedRecent
|
|
607680
608519
|
];
|
|
607681
608520
|
}
|
|
@@ -612690,7 +613529,7 @@ var init_composite_scorer = __esm({
|
|
|
612690
613529
|
});
|
|
612691
613530
|
|
|
612692
613531
|
// packages/orchestrator/dist/memory/materialization-policy.js
|
|
612693
|
-
import { createHash as
|
|
613532
|
+
import { createHash as createHash36 } from "node:crypto";
|
|
612694
613533
|
function materializeMemoryItems(items, options2 = {}) {
|
|
612695
613534
|
const config = options2.config ?? DEFAULT_WEIGHTING_CONFIG;
|
|
612696
613535
|
const sorted = [...items].sort((a2, b) => b.weight - a2.weight || a2.id.localeCompare(b.id));
|
|
@@ -612928,7 +613767,7 @@ function estimateTokens4(text2) {
|
|
|
612928
613767
|
return Math.max(1, Math.ceil(text2.length / 4));
|
|
612929
613768
|
}
|
|
612930
613769
|
function hashText2(text2) {
|
|
612931
|
-
return
|
|
613770
|
+
return createHash36("sha256").update(text2).digest("hex");
|
|
612932
613771
|
}
|
|
612933
613772
|
var init_materialization_policy = __esm({
|
|
612934
613773
|
"packages/orchestrator/dist/memory/materialization-policy.js"() {
|
|
@@ -613092,7 +613931,7 @@ var init_config_loader = __esm({
|
|
|
613092
613931
|
});
|
|
613093
613932
|
|
|
613094
613933
|
// packages/orchestrator/dist/memory/stability-tracker.js
|
|
613095
|
-
import { createHash as
|
|
613934
|
+
import { createHash as createHash37 } from "node:crypto";
|
|
613096
613935
|
import { existsSync as existsSync109, mkdirSync as mkdirSync60, readFileSync as readFileSync84, writeFileSync as writeFileSync51 } from "node:fs";
|
|
613097
613936
|
import { dirname as dirname36, join as join117 } from "node:path";
|
|
613098
613937
|
function stabilityFilePath(repoRoot) {
|
|
@@ -613156,7 +613995,7 @@ function computeStabilityHash(item) {
|
|
|
613156
613995
|
item.scope.name,
|
|
613157
613996
|
item.topicKey
|
|
613158
613997
|
].join("|");
|
|
613159
|
-
return
|
|
613998
|
+
return createHash37("sha256").update(normalized).digest("hex");
|
|
613160
613999
|
}
|
|
613161
614000
|
function normalizeContent2(content) {
|
|
613162
614001
|
return content.replace(/\s+/g, " ").trim();
|
|
@@ -617176,10 +618015,10 @@ var init_project_arc = __esm({
|
|
|
617176
618015
|
});
|
|
617177
618016
|
|
|
617178
618017
|
// packages/orchestrator/dist/dedup-gate.js
|
|
617179
|
-
import { createHash as
|
|
618018
|
+
import { createHash as createHash38 } from "node:crypto";
|
|
617180
618019
|
function fingerprintCall(name10, args) {
|
|
617181
618020
|
const canon = canonicalize(args);
|
|
617182
|
-
return
|
|
618021
|
+
return createHash38("sha1").update(`${name10}\0${canon}`).digest("hex").slice(0, 16);
|
|
617183
618022
|
}
|
|
617184
618023
|
function canonicalize(value2) {
|
|
617185
618024
|
if (value2 === null || typeof value2 !== "object")
|
|
@@ -628111,7 +628950,7 @@ var require_websocket3 = __commonJS({
|
|
|
628111
628950
|
var http6 = __require("http");
|
|
628112
628951
|
var net5 = __require("net");
|
|
628113
628952
|
var tls2 = __require("tls");
|
|
628114
|
-
var { randomBytes: randomBytes31, createHash:
|
|
628953
|
+
var { randomBytes: randomBytes31, createHash: createHash54 } = __require("crypto");
|
|
628115
628954
|
var { Duplex: Duplex3, Readable } = __require("stream");
|
|
628116
628955
|
var { URL: URL3 } = __require("url");
|
|
628117
628956
|
var PerMessageDeflate3 = require_permessage_deflate3();
|
|
@@ -628771,7 +629610,7 @@ var require_websocket3 = __commonJS({
|
|
|
628771
629610
|
abortHandshake(websocket, socket, "Invalid Upgrade header");
|
|
628772
629611
|
return;
|
|
628773
629612
|
}
|
|
628774
|
-
const digest3 =
|
|
629613
|
+
const digest3 = createHash54("sha1").update(key + GUID).digest("base64");
|
|
628775
629614
|
if (res.headers["sec-websocket-accept"] !== digest3) {
|
|
628776
629615
|
abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
|
|
628777
629616
|
return;
|
|
@@ -629138,7 +629977,7 @@ var require_websocket_server2 = __commonJS({
|
|
|
629138
629977
|
var EventEmitter15 = __require("events");
|
|
629139
629978
|
var http6 = __require("http");
|
|
629140
629979
|
var { Duplex: Duplex3 } = __require("stream");
|
|
629141
|
-
var { createHash:
|
|
629980
|
+
var { createHash: createHash54 } = __require("crypto");
|
|
629142
629981
|
var extension3 = require_extension3();
|
|
629143
629982
|
var PerMessageDeflate3 = require_permessage_deflate3();
|
|
629144
629983
|
var subprotocol3 = require_subprotocol2();
|
|
@@ -629439,7 +630278,7 @@ var require_websocket_server2 = __commonJS({
|
|
|
629439
630278
|
);
|
|
629440
630279
|
}
|
|
629441
630280
|
if (this._state > RUNNING) return abortHandshake(socket, 503);
|
|
629442
|
-
const digest3 =
|
|
630281
|
+
const digest3 = createHash54("sha1").update(key + GUID).digest("base64");
|
|
629443
630282
|
const headers = [
|
|
629444
630283
|
"HTTP/1.1 101 Switching Protocols",
|
|
629445
630284
|
"Upgrade: websocket",
|
|
@@ -632905,6 +633744,7 @@ __export(render_exports, {
|
|
|
632905
633744
|
setContentWriteHook: () => setContentWriteHook,
|
|
632906
633745
|
setEmojisEnabled: () => setEmojisEnabled,
|
|
632907
633746
|
stripTrustTierWrapperForTui: () => stripTrustTierWrapperForTui,
|
|
633747
|
+
summarizeInternalControlOutput: () => summarizeInternalControlOutput,
|
|
632908
633748
|
ui: () => ui
|
|
632909
633749
|
});
|
|
632910
633750
|
function stdoutIsTTY() {
|
|
@@ -633559,6 +634399,186 @@ function sanitizeToolBoxContent(text2) {
|
|
|
633559
634399
|
}
|
|
633560
634400
|
return out;
|
|
633561
634401
|
}
|
|
634402
|
+
function compactForDisplay(text2, max = 170) {
|
|
634403
|
+
const clean5 = text2.replace(/\s+/g, " ").trim();
|
|
634404
|
+
return clean5.length <= max ? clean5 : `${clean5.slice(0, Math.max(0, max - 1)).trimEnd()}…`;
|
|
634405
|
+
}
|
|
634406
|
+
function parseAssignmentMap(line) {
|
|
634407
|
+
const out = {};
|
|
634408
|
+
const assignmentRe = /(\w+)=([^\s]+)/g;
|
|
634409
|
+
let m2;
|
|
634410
|
+
while ((m2 = assignmentRe.exec(line)) !== null) {
|
|
634411
|
+
out[m2[1].toLowerCase()] = m2[2];
|
|
634412
|
+
}
|
|
634413
|
+
return out;
|
|
634414
|
+
}
|
|
634415
|
+
function extractFirstMatch(lines, pattern) {
|
|
634416
|
+
for (const line of lines) {
|
|
634417
|
+
const match = line.match(pattern);
|
|
634418
|
+
if (match?.[1]) return match[1].trim();
|
|
634419
|
+
}
|
|
634420
|
+
return "";
|
|
634421
|
+
}
|
|
634422
|
+
function formatBranchExtractSummary(output) {
|
|
634423
|
+
const lines = output.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
|
634424
|
+
if (lines.length === 0) return null;
|
|
634425
|
+
const first2 = lines[0].toLowerCase();
|
|
634426
|
+
const isBranchExtract = first2.startsWith("[branch-extract") || first2.startsWith("[branch-duplicate-blocked]");
|
|
634427
|
+
if (!isBranchExtract) return null;
|
|
634428
|
+
const routingLine = lines.find((line) => line.toLowerCase().startsWith("routing=")) || "";
|
|
634429
|
+
const assignment = parseAssignmentMap(routingLine);
|
|
634430
|
+
const route = assignment.routing ?? "mandatory";
|
|
634431
|
+
const reasons = assignment.reasons?.split(",").map((r2) => r2.trim()).filter(Boolean).join(", ") || "context protection";
|
|
634432
|
+
const projected = assignment.projected_read_tokens || assignment.projectedreadtokens || assignment.projected;
|
|
634433
|
+
const fractionLimit = assignment.fraction_limit_tokens || assignment.fractionlimittokens || assignment.fraction_limit || "";
|
|
634434
|
+
const available = assignment.available_headroom_tokens || assignment.available_headroom;
|
|
634435
|
+
const path16 = extractFirstMatch(
|
|
634436
|
+
lines,
|
|
634437
|
+
/(?:^|\s)path=(\S+)/
|
|
634438
|
+
) || extractFirstMatch(lines, /\[branch-extract[^\]]*?\]\s*path=([^\s]+)/) || "unknown path";
|
|
634439
|
+
const discoveryStart = lines.findIndex(
|
|
634440
|
+
(line) => /^\[discovery contract\]/i.test(line)
|
|
634441
|
+
);
|
|
634442
|
+
const curatedStart = lines.findIndex(
|
|
634443
|
+
(line) => /^\[curated segments\]/i.test(line)
|
|
634444
|
+
);
|
|
634445
|
+
let goalAnchor = "";
|
|
634446
|
+
let request = "";
|
|
634447
|
+
const required = [];
|
|
634448
|
+
let inRequired = false;
|
|
634449
|
+
let stopCondition = "";
|
|
634450
|
+
if (discoveryStart >= 0) {
|
|
634451
|
+
for (let i2 = discoveryStart + 1; i2 < lines.length; i2 += 1) {
|
|
634452
|
+
const line = lines[i2];
|
|
634453
|
+
if (/^\[curated segments\]/i.test(line)) break;
|
|
634454
|
+
if (/^Goal anchor:/i.test(line)) {
|
|
634455
|
+
goalAnchor = line.replace(/^Goal anchor:\s*/i, "");
|
|
634456
|
+
continue;
|
|
634457
|
+
}
|
|
634458
|
+
if (/^Request:/i.test(line)) {
|
|
634459
|
+
request = line.replace(/^Request:\s*/i, "");
|
|
634460
|
+
inRequired = false;
|
|
634461
|
+
continue;
|
|
634462
|
+
}
|
|
634463
|
+
if (/^Stop conditions?:/i.test(line)) {
|
|
634464
|
+
stopCondition = line.replace(/^Stop conditions?:\s*/i, "");
|
|
634465
|
+
inRequired = false;
|
|
634466
|
+
continue;
|
|
634467
|
+
}
|
|
634468
|
+
if (/^Required discoveries:/i.test(line)) {
|
|
634469
|
+
inRequired = true;
|
|
634470
|
+
continue;
|
|
634471
|
+
}
|
|
634472
|
+
if (inRequired && line.startsWith("- ")) {
|
|
634473
|
+
required.push(line.replace(/^- /, "").slice(0, 170));
|
|
634474
|
+
}
|
|
634475
|
+
}
|
|
634476
|
+
}
|
|
634477
|
+
let curatedSummary = "";
|
|
634478
|
+
let unresolved = "";
|
|
634479
|
+
let satisfied = "";
|
|
634480
|
+
let provenance = "";
|
|
634481
|
+
if (curatedStart >= 0) {
|
|
634482
|
+
for (let i2 = curatedStart + 1; i2 < lines.length; i2 += 1) {
|
|
634483
|
+
const line = lines[i2];
|
|
634484
|
+
if (/^satisfied=/i.test(line) || /^unresolved=/i.test(line) || /^provenance=/i.test(line)) {
|
|
634485
|
+
if (line.startsWith("satisfied=")) {
|
|
634486
|
+
satisfied = line.replace(/^satisfied=/i, "");
|
|
634487
|
+
} else if (line.startsWith("unresolved=")) {
|
|
634488
|
+
unresolved = line.replace(/^unresolved=/i, "");
|
|
634489
|
+
} else if (line.startsWith("provenance=")) {
|
|
634490
|
+
provenance = line.replace(/^provenance=/i, "");
|
|
634491
|
+
}
|
|
634492
|
+
continue;
|
|
634493
|
+
}
|
|
634494
|
+
if (/^Contract:/i.test(line)) {
|
|
634495
|
+
continue;
|
|
634496
|
+
}
|
|
634497
|
+
if (curatedSummary.length < 240) {
|
|
634498
|
+
curatedSummary = curatedSummary ? `${curatedSummary} ${compactForDisplay(line, 120)}` : compactForDisplay(line, 120);
|
|
634499
|
+
}
|
|
634500
|
+
}
|
|
634501
|
+
}
|
|
634502
|
+
const isDuplicate = /^\[branch-duplicate-blocked\]/i.test(lines[0]);
|
|
634503
|
+
const header = isDuplicate ? "Branch-extract duplicate reuse" : "Branch-extract preempted";
|
|
634504
|
+
const whatHappened = isDuplicate ? "a cache-safe duplicate was detected" : "read was auto-summarized before injecting into context";
|
|
634505
|
+
const out = [
|
|
634506
|
+
`↳ ${header}`,
|
|
634507
|
+
` ├ what happened: ${whatHappened}`,
|
|
634508
|
+
` ├ why: ${compactForDisplay(reasons, 140)}`,
|
|
634509
|
+
` ├ path: ${compactForDisplay(path16, 140)}`,
|
|
634510
|
+
` ├ decision scope: ${route}`
|
|
634511
|
+
];
|
|
634512
|
+
if (projected) {
|
|
634513
|
+
const projectedText = fractionLimit ? `${projected} projected → ${fractionLimit} limit` : `${projected} projected`;
|
|
634514
|
+
const availText = available ? `; available headroom ${available}` : "";
|
|
634515
|
+
out.push(` ├ budget: ${projectedText}${availText}`);
|
|
634516
|
+
}
|
|
634517
|
+
if (goalAnchor) out.push(` ├ goal anchor: ${compactForDisplay(goalAnchor, 120)}`);
|
|
634518
|
+
if (request) out.push(` ├ request: ${compactForDisplay(request, 150)}`);
|
|
634519
|
+
if (required.length > 0) {
|
|
634520
|
+
out.push(` ├ required: ${compactForDisplay(required.slice(0, 3).join(", "), 180)}`);
|
|
634521
|
+
}
|
|
634522
|
+
if (stopCondition) {
|
|
634523
|
+
out.push(` ├ stop: ${compactForDisplay(stopCondition, 140)}`);
|
|
634524
|
+
}
|
|
634525
|
+
if (curatedSummary) {
|
|
634526
|
+
out.push(` ├ curated segment: ${compactForDisplay(curatedSummary, 180)}`);
|
|
634527
|
+
}
|
|
634528
|
+
if (satisfied || unresolved) {
|
|
634529
|
+
out.push(
|
|
634530
|
+
` ├ state: satisfied=${compactForDisplay(satisfied || "none", 90)}; unresolved=${compactForDisplay(unresolved || "none", 90)}`
|
|
634531
|
+
);
|
|
634532
|
+
}
|
|
634533
|
+
if (provenance) {
|
|
634534
|
+
out.push(` ├ provenance: ${compactForDisplay(provenance, 120)}`);
|
|
634535
|
+
}
|
|
634536
|
+
if (out.length > 1) {
|
|
634537
|
+
const last2 = out.length - 1;
|
|
634538
|
+
out[last2] = out[last2]?.replace(/^ ├ /, " └ ") ?? out[last2];
|
|
634539
|
+
}
|
|
634540
|
+
return out.length > 0 ? out : null;
|
|
634541
|
+
}
|
|
634542
|
+
function formatSupersededPlanSummary() {
|
|
634543
|
+
return [
|
|
634544
|
+
"↳ Mode-collapse guard",
|
|
634545
|
+
" ├ what happened: near-duplicate assistant plan was suppressed",
|
|
634546
|
+
" ├ why: loop prevention to stop re-entering the same plan text",
|
|
634547
|
+
" └ next action: tool call or concrete evidence request before restating the plan"
|
|
634548
|
+
];
|
|
634549
|
+
}
|
|
634550
|
+
function formatEchoGuardSummary(output) {
|
|
634551
|
+
const lower = output.toLowerCase();
|
|
634552
|
+
const match = output.match(/echo-1:\s*text-only echo\s*#?(\d+)/i);
|
|
634553
|
+
const echoCount = match?.[1] ? `#${match[1]}` : "";
|
|
634554
|
+
const similarityMatch = output.match(/(\d+)% similar/);
|
|
634555
|
+
const similarity3 = similarityMatch?.[1] ? ` (${similarityMatch[1]}% similar to earlier response)` : "";
|
|
634556
|
+
const collapsed = output.match(/collapsed\s+(\d+)\s+duplicate/);
|
|
634557
|
+
const duplicates = collapsed?.[1] ? `${collapsed[1]} duplicate(s) collapsed` : "";
|
|
634558
|
+
const out = [
|
|
634559
|
+
`↳ ECHO-1 mode-collapse guard${echoCount ? ` ${echoCount}` : ""}${similarity3}`,
|
|
634560
|
+
" ├ what happened: repeated text-only plan was intercepted",
|
|
634561
|
+
" ├ why: duplicate plan text was detected from the model loop",
|
|
634562
|
+
` ├ action: pattern-breaker${duplicates ? ` (${duplicates})` : ""}`,
|
|
634563
|
+
" └ next action: resume with tool-backed evidence"
|
|
634564
|
+
];
|
|
634565
|
+
return out;
|
|
634566
|
+
}
|
|
634567
|
+
function summarizeInternalControlOutput(output) {
|
|
634568
|
+
if (!output) return null;
|
|
634569
|
+
const firstLine = output.split(/\r?\n/)[0]?.trim().toLowerCase() ?? "";
|
|
634570
|
+
const lower = output.toLowerCase();
|
|
634571
|
+
if (firstLine.includes("[branch-extract") || firstLine.includes("[branch-duplicate-blocked]") || lower.includes("branch-extract preempted")) {
|
|
634572
|
+
return formatBranchExtractSummary(output);
|
|
634573
|
+
}
|
|
634574
|
+
if (firstLine.includes("[echo break") || firstLine.includes("[echo-break") || lower.includes("echo-1:")) {
|
|
634575
|
+
return formatEchoGuardSummary(output);
|
|
634576
|
+
}
|
|
634577
|
+
if (lower.includes("[superseded near-duplicate plan removed")) {
|
|
634578
|
+
return formatSupersededPlanSummary();
|
|
634579
|
+
}
|
|
634580
|
+
return null;
|
|
634581
|
+
}
|
|
633562
634582
|
function stripTrustTierWrapperForTui(text2, maxWrapperChars = 400) {
|
|
633563
634583
|
const trustWrapper = new RegExp(
|
|
633564
634584
|
`^\\[trust_tier:[^\\]\\n]{0,${Math.max(0, maxWrapperChars)}}\\][ \\t]*(?:\\n)?`,
|
|
@@ -634018,6 +635038,14 @@ function resolveToolOutputMaxLines(verbose) {
|
|
|
634018
635038
|
}
|
|
634019
635039
|
function buildToolResultBody(toolName, success, output, verbose) {
|
|
634020
635040
|
const debug = loadConfig()?.debug ?? false;
|
|
635041
|
+
const internalControlSummary = summarizeInternalControlOutput(output);
|
|
635042
|
+
if (internalControlSummary && internalControlSummary.length > 0) {
|
|
635043
|
+
return internalControlSummary.map((line) => ({
|
|
635044
|
+
text: line,
|
|
635045
|
+
mode: "wrap",
|
|
635046
|
+
kind: "plain"
|
|
635047
|
+
}));
|
|
635048
|
+
}
|
|
634021
635049
|
if (toolName === "file_edit" || toolName === "file_patch") {
|
|
634022
635050
|
if (!success) {
|
|
634023
635051
|
return [
|
|
@@ -636220,14 +637248,14 @@ var init_voice_session = __esm({
|
|
|
636220
637248
|
});
|
|
636221
637249
|
|
|
636222
637250
|
// packages/cli/src/tui/scoped-personality.ts
|
|
636223
|
-
import { createHash as
|
|
637251
|
+
import { createHash as createHash39 } from "node:crypto";
|
|
636224
637252
|
import { appendFileSync as appendFileSync13, existsSync as existsSync120, mkdirSync as mkdirSync72, readFileSync as readFileSync97, writeFileSync as writeFileSync60 } from "node:fs";
|
|
636225
637253
|
import { join as join131, resolve as resolve60 } from "node:path";
|
|
636226
637254
|
function safeName(input) {
|
|
636227
637255
|
return input.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 80) || "default";
|
|
636228
637256
|
}
|
|
636229
637257
|
function scopeHash(scope) {
|
|
636230
|
-
return
|
|
637258
|
+
return createHash39("sha1").update(`${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
|
|
636231
637259
|
}
|
|
636232
637260
|
function scopedPersonalityDir(repoRoot, kind) {
|
|
636233
637261
|
return resolve60(repoRoot, ".omnius", "scoped-personality", kind);
|
|
@@ -636598,7 +637626,7 @@ var init_scoped_personality = __esm({
|
|
|
636598
637626
|
});
|
|
636599
637627
|
|
|
636600
637628
|
// packages/cli/src/tui/voice-soul.ts
|
|
636601
|
-
import { createHash as
|
|
637629
|
+
import { createHash as createHash40 } from "node:crypto";
|
|
636602
637630
|
import { existsSync as existsSync121, readdirSync as readdirSync38, readFileSync as readFileSync98 } from "node:fs";
|
|
636603
637631
|
import { basename as basename26, join as join132, resolve as resolve61 } from "node:path";
|
|
636604
637632
|
function compactText(text2, limit) {
|
|
@@ -636613,7 +637641,7 @@ function blockText(text2, limit) {
|
|
|
636613
637641
|
... [truncated]`;
|
|
636614
637642
|
}
|
|
636615
637643
|
function scopeStateKey(scope, surface) {
|
|
636616
|
-
return
|
|
637644
|
+
return createHash40("sha1").update(`${surface}:${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
|
|
636617
637645
|
}
|
|
636618
637646
|
function safeName2(input) {
|
|
636619
637647
|
return input.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 80) || "default";
|
|
@@ -639253,7 +640281,7 @@ var init_types3 = __esm({
|
|
|
639253
640281
|
});
|
|
639254
640282
|
|
|
639255
640283
|
// packages/cli/src/tui/p2p/secret-vault.ts
|
|
639256
|
-
import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes23, scryptSync as scryptSync2, createHash as
|
|
640284
|
+
import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes23, scryptSync as scryptSync2, createHash as createHash41 } from "node:crypto";
|
|
639257
640285
|
import { readFileSync as readFileSync100, writeFileSync as writeFileSync62, existsSync as existsSync123, mkdirSync as mkdirSync74 } from "node:fs";
|
|
639258
640286
|
import { dirname as dirname39 } from "node:path";
|
|
639259
640287
|
var PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, CIPHER_ALGO, SALT_LEN, IV_LEN, KEY_LEN, SecretVault;
|
|
@@ -639497,7 +640525,7 @@ var init_secret_vault = __esm({
|
|
|
639497
640525
|
/** Generate a deterministic fingerprint of vault contents (for sync verification) */
|
|
639498
640526
|
fingerprint() {
|
|
639499
640527
|
const names = Array.from(this.secrets.keys()).sort();
|
|
639500
|
-
const hash =
|
|
640528
|
+
const hash = createHash41("sha256");
|
|
639501
640529
|
for (const name10 of names) {
|
|
639502
640530
|
hash.update(name10 + ":");
|
|
639503
640531
|
hash.update(this.secrets.get(name10).value);
|
|
@@ -639512,7 +640540,7 @@ var init_secret_vault = __esm({
|
|
|
639512
640540
|
// packages/cli/src/tui/p2p/peer-mesh.ts
|
|
639513
640541
|
import { EventEmitter as EventEmitter9 } from "node:events";
|
|
639514
640542
|
import { createServer as createServer6 } from "node:http";
|
|
639515
|
-
import { randomBytes as randomBytes24, createHash as
|
|
640543
|
+
import { randomBytes as randomBytes24, createHash as createHash42, generateKeyPairSync } from "node:crypto";
|
|
639516
640544
|
var PING_INTERVAL_MS, PEER_TIMEOUT_MS, GOSSIP_INTERVAL_MS, MAX_PEERS, PeerMesh;
|
|
639517
640545
|
var init_peer_mesh = __esm({
|
|
639518
640546
|
"packages/cli/src/tui/p2p/peer-mesh.ts"() {
|
|
@@ -639528,7 +640556,7 @@ var init_peer_mesh = __esm({
|
|
|
639528
640556
|
const { publicKey: publicKey2, privateKey } = generateKeyPairSync("ed25519");
|
|
639529
640557
|
this.publicKey = publicKey2.export({ type: "spki", format: "der" });
|
|
639530
640558
|
this.privateKey = privateKey.export({ type: "pkcs8", format: "der" });
|
|
639531
|
-
this.peerId =
|
|
640559
|
+
this.peerId = createHash42("sha256").update(this.publicKey).digest("base64url").slice(0, 22);
|
|
639532
640560
|
this.capabilities = options2.capabilities;
|
|
639533
640561
|
this.displayName = options2.displayName;
|
|
639534
640562
|
this._authKey = options2.authKey ?? randomBytes24(24).toString("base64url");
|
|
@@ -640894,7 +641922,7 @@ __export(omnius_directory_exports, {
|
|
|
640894
641922
|
import { appendFileSync as appendFileSync14, cpSync as cpSync2, existsSync as existsSync125, mkdirSync as mkdirSync76, readFileSync as readFileSync102, writeFileSync as writeFileSync64, readdirSync as readdirSync41, statSync as statSync51, unlinkSync as unlinkSync23, openSync as openSync2, closeSync as closeSync2, renameSync as renameSync11, watch as fsWatch2 } from "node:fs";
|
|
640895
641923
|
import { join as join136, relative as relative17, basename as basename27, dirname as dirname40, resolve as resolve62 } from "node:path";
|
|
640896
641924
|
import { homedir as homedir42 } from "node:os";
|
|
640897
|
-
import { createHash as
|
|
641925
|
+
import { createHash as createHash44 } from "node:crypto";
|
|
640898
641926
|
function isGitRoot(dir) {
|
|
640899
641927
|
const gitPath = join136(dir, ".git");
|
|
640900
641928
|
if (!existsSync125(gitPath)) return false;
|
|
@@ -641392,7 +642420,7 @@ function buildHandoffPrompt(repoRoot) {
|
|
|
641392
642420
|
return lines.join("\n");
|
|
641393
642421
|
}
|
|
641394
642422
|
function computeDedupeHash(task, savedAt) {
|
|
641395
|
-
return
|
|
642423
|
+
return createHash44("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
|
|
641396
642424
|
}
|
|
641397
642425
|
function generateSessionId() {
|
|
641398
642426
|
const timestamp = Date.now().toString(36);
|
|
@@ -668986,7 +670014,7 @@ __export(commands_exports, {
|
|
|
668986
670014
|
});
|
|
668987
670015
|
import * as nodeOs from "node:os";
|
|
668988
670016
|
import { spawn as nodeSpawn2 } from "node:child_process";
|
|
668989
|
-
import { createHash as
|
|
670017
|
+
import { createHash as createHash45 } from "node:crypto";
|
|
668990
670018
|
import {
|
|
668991
670019
|
existsSync as existsSync147,
|
|
668992
670020
|
readFileSync as readFileSync119,
|
|
@@ -682346,7 +683374,7 @@ async function collectSponsorMediaStream(args) {
|
|
|
682346
683374
|
};
|
|
682347
683375
|
}
|
|
682348
683376
|
if (artifact.sha256) {
|
|
682349
|
-
const sha =
|
|
683377
|
+
const sha = createHash45("sha256").update(bytes).digest("hex");
|
|
682350
683378
|
if (sha !== artifact.sha256)
|
|
682351
683379
|
return { ok: false, error: `Artifact hash mismatch for ${artifactId}` };
|
|
682352
683380
|
}
|
|
@@ -688972,6 +690000,18 @@ var init_stream_renderer = __esm({
|
|
|
688972
690000
|
* runs. Tracked in VISIBLE chars (ANSI escapes stripped).
|
|
688973
690001
|
*/
|
|
688974
690002
|
_cursorCol = 0;
|
|
690003
|
+
/**
|
|
690004
|
+
* RESIZE-REWRAP: raw (un-highlighted) text of the CURRENT in-progress
|
|
690005
|
+
* logical content line — everything streamed since the last "\n",
|
|
690006
|
+
* including already-flushed partials. Streaming hard-breaks rows at the
|
|
690007
|
+
* width current at flush time, so without this raw copy a SIGWINCH left
|
|
690008
|
+
* the in-progress line "locked" at the old width (the reported artifact).
|
|
690009
|
+
* onResize() erases the line's visual rows and re-emits from this buffer
|
|
690010
|
+
* wrapped at the new width.
|
|
690011
|
+
*/
|
|
690012
|
+
_currentLineRaw = "";
|
|
690013
|
+
/** Visual rows (newlines) already emitted for the current logical line. */
|
|
690014
|
+
_wrapRowsEmitted = 0;
|
|
688975
690015
|
/** Called when a new model response starts streaming */
|
|
688976
690016
|
onStreamStart() {
|
|
688977
690017
|
this.lineBuffer = "";
|
|
@@ -688983,6 +690023,8 @@ var init_stream_renderer = __esm({
|
|
|
688983
690023
|
this.jsonBlobSize = 0;
|
|
688984
690024
|
this.jsonBlobSuppressed = false;
|
|
688985
690025
|
this._cursorCol = 0;
|
|
690026
|
+
this._currentLineRaw = "";
|
|
690027
|
+
this._wrapRowsEmitted = 0;
|
|
688986
690028
|
this.enabled = true;
|
|
688987
690029
|
this.tokenCount = 0;
|
|
688988
690030
|
this.startTime = Date.now();
|
|
@@ -689071,6 +690113,34 @@ var init_stream_renderer = __esm({
|
|
|
689071
690113
|
process.stdout.write("\n");
|
|
689072
690114
|
this.lineStarted = false;
|
|
689073
690115
|
}
|
|
690116
|
+
this._currentLineRaw = "";
|
|
690117
|
+
this._wrapRowsEmitted = 0;
|
|
690118
|
+
this._cursorCol = 0;
|
|
690119
|
+
}
|
|
690120
|
+
/**
|
|
690121
|
+
* RESIZE-REWRAP: re-render the in-progress logical content line at the new
|
|
690122
|
+
* terminal width. Streaming hard-breaks rows at flush-time width, so after
|
|
690123
|
+
* a SIGWINCH the current line was left "locked" at the old width — wrapped
|
|
690124
|
+
* rows missing the pipe gutter or overflowing. Erases the rows this line
|
|
690125
|
+
* occupies (tracked in _wrapRowsEmitted) and re-emits from the raw buffer.
|
|
690126
|
+
* Completed lines live in terminal scrollback and are not repainted.
|
|
690127
|
+
* Call AFTER setTermSize() so termCols() reflects the new width.
|
|
690128
|
+
*/
|
|
690129
|
+
onResize() {
|
|
690130
|
+
if (!this.enabled) return;
|
|
690131
|
+
const raw = this._currentLineRaw;
|
|
690132
|
+
if (!raw) return;
|
|
690133
|
+
if (isTTY8) {
|
|
690134
|
+
const rowsUp = Math.min(this._wrapRowsEmitted, 40);
|
|
690135
|
+
let seq = "\r\x1B[2K";
|
|
690136
|
+
for (let i2 = 0; i2 < rowsUp; i2++) seq += "\x1B[A\x1B[2K";
|
|
690137
|
+
process.stdout.write(`\x1B[?25l\x1B[?7l${seq}\x1B[?7h`);
|
|
690138
|
+
}
|
|
690139
|
+
this._cursorCol = 0;
|
|
690140
|
+
this.lineStarted = false;
|
|
690141
|
+
this._currentLineRaw = "";
|
|
690142
|
+
this._wrapRowsEmitted = 0;
|
|
690143
|
+
this.writeHighlighted(raw, "content");
|
|
689074
690144
|
}
|
|
689075
690145
|
/** Called when streaming ends for this response */
|
|
689076
690146
|
onStreamEnd() {
|
|
@@ -689111,6 +690181,9 @@ var init_stream_renderer = __esm({
|
|
|
689111
690181
|
if (this.lineStarted) {
|
|
689112
690182
|
process.stdout.write("\n");
|
|
689113
690183
|
this.lineStarted = false;
|
|
690184
|
+
this._currentLineRaw = "";
|
|
690185
|
+
this._wrapRowsEmitted = 0;
|
|
690186
|
+
this._cursorCol = 0;
|
|
689114
690187
|
}
|
|
689115
690188
|
return;
|
|
689116
690189
|
}
|
|
@@ -689180,6 +690253,14 @@ var init_stream_renderer = __esm({
|
|
|
689180
690253
|
this.jsonBlobSuppressed = false;
|
|
689181
690254
|
}
|
|
689182
690255
|
}
|
|
690256
|
+
const trackedContent = kind === "content" && !this.inCodeBlock && !this.looksLikeJson(raw);
|
|
690257
|
+
if (trackedContent) this._currentLineRaw += raw;
|
|
690258
|
+
const endTrackedLine = () => {
|
|
690259
|
+
if (trackedContent && hasNewline) {
|
|
690260
|
+
this._currentLineRaw = "";
|
|
690261
|
+
this._wrapRowsEmitted = 0;
|
|
690262
|
+
}
|
|
690263
|
+
};
|
|
689183
690264
|
const prefix = this.lineStarted ? "" : " │ ";
|
|
689184
690265
|
const maxW = Math.max(10, termCols() - 6);
|
|
689185
690266
|
let rendered;
|
|
@@ -689190,6 +690271,7 @@ var init_stream_renderer = __esm({
|
|
|
689190
690271
|
const firstChunkLen = Math.min(text3.length, Math.max(1, remaining));
|
|
689191
690272
|
if (remaining < 8 && text3.length > remaining) {
|
|
689192
690273
|
this.writeRaw("\n");
|
|
690274
|
+
if (trackedContent) this._wrapRowsEmitted++;
|
|
689193
690275
|
this.lineStarted = false;
|
|
689194
690276
|
} else if (text3.length > remaining) {
|
|
689195
690277
|
const window2 = text3.slice(0, firstChunkLen);
|
|
@@ -689198,12 +690280,13 @@ var init_stream_renderer = __esm({
|
|
|
689198
690280
|
const head = text3.slice(0, wb).replace(/\s+$/, "");
|
|
689199
690281
|
const tail = text3.slice(wb).replace(/^\s+/, "");
|
|
689200
690282
|
this.writeRaw(highlight(head) + "\n");
|
|
690283
|
+
if (trackedContent) this._wrapRowsEmitted++;
|
|
689201
690284
|
this.lineStarted = false;
|
|
689202
690285
|
text3 = tail;
|
|
689203
690286
|
if (!text3) return;
|
|
689204
690287
|
}
|
|
689205
690288
|
}
|
|
689206
|
-
const usePrefix = this.lineStarted && this._cursorCol > 0 ? "" :
|
|
690289
|
+
const usePrefix = this.lineStarted && this._cursorCol > 0 ? "" : " │ ";
|
|
689207
690290
|
const usableW = this.lineStarted ? maxW : Math.max(1, maxW - usePrefix.length);
|
|
689208
690291
|
const lines = text3.length > usableW ? this.wordWrap(text3, usableW) : [text3];
|
|
689209
690292
|
const isBlockquote = kind === "content" && /^>\s/.test(text3);
|
|
@@ -689216,12 +690299,14 @@ var init_stream_renderer = __esm({
|
|
|
689216
690299
|
this.writeRaw(
|
|
689217
690300
|
dimText(lp) + highlight(chunk) + (needsNewline ? "\n" : "")
|
|
689218
690301
|
);
|
|
690302
|
+
if (trackedContent && needsNewline) this._wrapRowsEmitted++;
|
|
689219
690303
|
}
|
|
689220
690304
|
this.lineStarted = !trailingNewline;
|
|
689221
690305
|
};
|
|
689222
690306
|
switch (kind) {
|
|
689223
690307
|
case "thinking":
|
|
689224
690308
|
emitWrapped(raw, dimItalic, hasNewline);
|
|
690309
|
+
endTrackedLine();
|
|
689225
690310
|
return;
|
|
689226
690311
|
case "tool_args":
|
|
689227
690312
|
rendered = this.highlightJson(raw, true);
|
|
@@ -689245,6 +690330,7 @@ var init_stream_renderer = __esm({
|
|
|
689245
690330
|
} else {
|
|
689246
690331
|
if (visibleLength(raw) > maxW || this.lineStarted && this._cursorCol + visibleLength(raw) > maxW) {
|
|
689247
690332
|
emitWrapped(raw, (s2) => this.highlightMarkdown(s2), hasNewline);
|
|
690333
|
+
endTrackedLine();
|
|
689248
690334
|
return;
|
|
689249
690335
|
}
|
|
689250
690336
|
rendered = this.highlightMarkdown(raw);
|
|
@@ -689254,10 +690340,12 @@ var init_stream_renderer = __esm({
|
|
|
689254
690340
|
}
|
|
689255
690341
|
if (kind === "content" && this.lineStarted && this._cursorCol + visibleLength(raw) > maxW) {
|
|
689256
690342
|
emitWrapped(raw, (s2) => this.highlightMarkdown(s2), hasNewline);
|
|
690343
|
+
endTrackedLine();
|
|
689257
690344
|
return;
|
|
689258
690345
|
}
|
|
689259
690346
|
this.writeRaw(dimText(prefix) + rendered + (hasNewline ? "\n" : ""));
|
|
689260
690347
|
this.lineStarted = !hasNewline;
|
|
690348
|
+
endTrackedLine();
|
|
689261
690349
|
}
|
|
689262
690350
|
/** In-place update of the compact thinking box content row (cursor-up + rewrite) */
|
|
689263
690351
|
updateThinkingBox(text2, width) {
|
|
@@ -696814,7 +697902,7 @@ import {
|
|
|
696814
697902
|
unlinkSync as unlinkSync34
|
|
696815
697903
|
} from "node:fs";
|
|
696816
697904
|
import { join as join168 } from "node:path";
|
|
696817
|
-
import { createHash as
|
|
697905
|
+
import { createHash as createHash46 } from "node:crypto";
|
|
696818
697906
|
function safeFilePart(value2) {
|
|
696819
697907
|
return value2.replace(/[^A-Za-z0-9_.-]+/g, "_").slice(0, 80) || "telegram";
|
|
696820
697908
|
}
|
|
@@ -696822,7 +697910,7 @@ function daydreamRoot(repoRoot) {
|
|
|
696822
697910
|
return join168(repoRoot, ".omnius", "telegram-daydreams");
|
|
696823
697911
|
}
|
|
696824
697912
|
function sessionDir(repoRoot, sessionKey) {
|
|
696825
|
-
const hash =
|
|
697913
|
+
const hash = createHash46("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
696826
697914
|
return join168(daydreamRoot(repoRoot), safeFilePart(hash));
|
|
696827
697915
|
}
|
|
696828
697916
|
function compactLine2(value2, max = 220) {
|
|
@@ -696933,7 +698021,7 @@ function buildReplyOpportunities(input, openQuestions) {
|
|
|
696933
698021
|
return opportunities;
|
|
696934
698022
|
}
|
|
696935
698023
|
function daydreamOpportunityId(input, trigger) {
|
|
696936
|
-
return
|
|
698024
|
+
return createHash46("sha1").update(`${input.sessionKey}:${input.generatedAtMs}:${trigger}`).digest("hex").slice(0, 16);
|
|
696937
698025
|
}
|
|
696938
698026
|
function clamp0115(value2) {
|
|
696939
698027
|
if (!Number.isFinite(value2)) return 0;
|
|
@@ -697338,7 +698426,7 @@ function buildTelegramChannelDaydream(input, corpus, extraction, extractionCommi
|
|
|
697338
698426
|
const seed = `${input.sessionKey}:${input.generatedAtMs}:${input.history.length}`;
|
|
697339
698427
|
return {
|
|
697340
698428
|
version: 3,
|
|
697341
|
-
id:
|
|
698429
|
+
id: createHash46("sha1").update(seed).digest("hex").slice(0, 16),
|
|
697342
698430
|
sessionKey: input.sessionKey,
|
|
697343
698431
|
chatId: input.chatId,
|
|
697344
698432
|
chatTitle: input.chatTitle,
|
|
@@ -697650,12 +698738,12 @@ var init_telegram_channel_dmn = __esm({
|
|
|
697650
698738
|
});
|
|
697651
698739
|
|
|
697652
698740
|
// packages/cli/src/tui/telegram-reflection-corpus.ts
|
|
697653
|
-
import { createHash as
|
|
698741
|
+
import { createHash as createHash47 } from "node:crypto";
|
|
697654
698742
|
function telegramReflectionMemoryDbPaths(repoRoot) {
|
|
697655
698743
|
return omniusMemoryDbPaths(repoRoot);
|
|
697656
698744
|
}
|
|
697657
698745
|
function stableHash2(value2, length4 = 16) {
|
|
697658
|
-
return
|
|
698746
|
+
return createHash47("sha1").update(value2).digest("hex").slice(0, length4);
|
|
697659
698747
|
}
|
|
697660
698748
|
function clean3(value2) {
|
|
697661
698749
|
return String(value2 ?? "").replace(/\s+/g, " ").trim();
|
|
@@ -698468,7 +699556,7 @@ var init_telegram_reflection_extraction = __esm({
|
|
|
698468
699556
|
});
|
|
698469
699557
|
|
|
698470
699558
|
// packages/cli/src/tui/telegram-social-state-types.ts
|
|
698471
|
-
import { createHash as
|
|
699559
|
+
import { createHash as createHash48 } from "node:crypto";
|
|
698472
699560
|
function telegramSocialActorKey(actor) {
|
|
698473
699561
|
if (!actor) return "unknown";
|
|
698474
699562
|
if (typeof actor.userId === "number") return `user:${actor.userId}`;
|
|
@@ -698501,7 +699589,7 @@ function appendUnique(items, value2, max) {
|
|
|
698501
699589
|
return next.slice(-max);
|
|
698502
699590
|
}
|
|
698503
699591
|
function hashTelegramSocialId(parts) {
|
|
698504
|
-
return
|
|
699592
|
+
return createHash48("sha1").update(parts.map((part) => String(part ?? "")).join(":")).digest("hex").slice(0, 16);
|
|
698505
699593
|
}
|
|
698506
699594
|
function cleanUsername(value2) {
|
|
698507
699595
|
if (typeof value2 !== "string") return void 0;
|
|
@@ -699561,7 +700649,7 @@ import {
|
|
|
699561
700649
|
} from "node:path";
|
|
699562
700650
|
import { homedir as homedir56 } from "node:os";
|
|
699563
700651
|
import { writeFile as writeFileAsync } from "node:fs/promises";
|
|
699564
|
-
import { createHash as
|
|
700652
|
+
import { createHash as createHash49, randomBytes as randomBytes28, randomInt } from "node:crypto";
|
|
699565
700653
|
function formatModelBytes(bytes) {
|
|
699566
700654
|
if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";
|
|
699567
700655
|
const units = ["B", "KB", "MB", "GB", "TB"];
|
|
@@ -700501,11 +701589,29 @@ function isTelegramNoReplySentinel(text2) {
|
|
|
700501
701589
|
const lower = compactTelegramVisibleText(text2).toLowerCase();
|
|
700502
701590
|
return lower === "no_reply" || lower.startsWith("no_reply");
|
|
700503
701591
|
}
|
|
701592
|
+
function isTelegramInternalControlText(text2) {
|
|
701593
|
+
const compact4 = compactTelegramVisibleText(text2);
|
|
701594
|
+
if (!compact4) return false;
|
|
701595
|
+
const lower = compact4.toLowerCase();
|
|
701596
|
+
const patterns = [
|
|
701597
|
+
/\[superseded near-duplicate plan removed/i,
|
|
701598
|
+
/\[echo break/i,
|
|
701599
|
+
/\[branch-extract\b/i,
|
|
701600
|
+
/\[discovery contract\]/i,
|
|
701601
|
+
/\[curated segments\]/i,
|
|
701602
|
+
/\[branch-duplicate-blocked\]/i,
|
|
701603
|
+
/branch-extract preempted/i,
|
|
701604
|
+
/contract: use these anchors as evidence/i,
|
|
701605
|
+
/\becho break\b/i
|
|
701606
|
+
];
|
|
701607
|
+
return patterns.some((pattern) => pattern.test(lower));
|
|
701608
|
+
}
|
|
700504
701609
|
function isTelegramInternalStatusText(text2) {
|
|
700505
701610
|
const compact4 = compactTelegramVisibleText(text2);
|
|
700506
701611
|
if (!compact4) return false;
|
|
700507
701612
|
const lower = compact4.toLowerCase();
|
|
700508
701613
|
if (isTelegramNoReplySentinel(compact4)) return true;
|
|
701614
|
+
if (isTelegramInternalControlText(compact4)) return true;
|
|
700509
701615
|
if (lower === "complete" || lower === "completed") return true;
|
|
700510
701616
|
if (/^memory stage:/i.test(compact4)) return true;
|
|
700511
701617
|
if (/^\[ppr[-_\s]?skip\]/i.test(compact4)) return true;
|
|
@@ -700560,6 +701666,7 @@ function cleanTelegramVisibleReply(text2, options2 = {}) {
|
|
|
700560
701666
|
if (!clean5) return "";
|
|
700561
701667
|
if (options2.suppressPotentialNoReplyPrefix && isTelegramPotentialNoReplyPrefix(clean5))
|
|
700562
701668
|
return "";
|
|
701669
|
+
if (isTelegramInternalControlText(clean5)) return "";
|
|
700563
701670
|
if (isTelegramInternalStatusText(clean5)) return "";
|
|
700564
701671
|
const filtered = stripTelegramStuckSelfTalk(clean5).trim();
|
|
700565
701672
|
if (!filtered) return "";
|
|
@@ -700806,7 +701913,7 @@ function buildTelegramRuntimeContext(now2 = /* @__PURE__ */ new Date(), repoRoot
|
|
|
700806
701913
|
return buildConversationRuntimeContext(now2, repoRoot);
|
|
700807
701914
|
}
|
|
700808
701915
|
function telegramSessionIdFromKey(sessionKey) {
|
|
700809
|
-
return `telegram-${
|
|
701916
|
+
return `telegram-${createHash49("sha1").update(sessionKey).digest("hex").slice(0, 16)}`;
|
|
700810
701917
|
}
|
|
700811
701918
|
function normalizeTelegramSubAgentLimit(value2) {
|
|
700812
701919
|
const parsed = typeof value2 === "number" ? value2 : typeof value2 === "string" && value2.trim() ? Number(value2.trim()) : TELEGRAM_SUB_AGENT_DEFAULT_LIMIT;
|
|
@@ -700846,6 +701953,7 @@ function formatTelegramProgressEvent(event) {
|
|
|
700846
701953
|
}
|
|
700847
701954
|
if (event.type === "tool_result") {
|
|
700848
701955
|
const preview = sanitizeTelegramProgressText(event.content || "", 1500);
|
|
701956
|
+
if (isTelegramInternalControlText(preview)) return null;
|
|
700849
701957
|
if (isTelegramInternalStatusText(preview)) return null;
|
|
700850
701958
|
return toolResultBlock(
|
|
700851
701959
|
event.toolName || "tool",
|
|
@@ -700981,6 +702089,7 @@ function applyTelegramAdminLivePanelEvent(state, event) {
|
|
|
700981
702089
|
}
|
|
700982
702090
|
if (event.type === "tool_result" && event.toolName && event.toolName !== "task_complete") {
|
|
700983
702091
|
const preview = sanitizeTelegramProgressText(event.content || "", 260);
|
|
702092
|
+
if (isTelegramInternalControlText(preview)) return;
|
|
700984
702093
|
const line = `${event.success ? "✓" : "✗"} ${event.toolName}${preview ? `: ${preview}` : ""}`;
|
|
700985
702094
|
if (TELEGRAM_ADMIN_LIVE_MUTATION_TOOLS.has(event.toolName)) {
|
|
700986
702095
|
pushTelegramAdminPanelMutationLine(state, line);
|
|
@@ -702970,7 +704079,7 @@ Telegram link integrity contract:
|
|
|
702970
704079
|
return !!this.adminAuthChallenge && this.adminAuthChallenge.expiresAtMs > Date.now();
|
|
702971
704080
|
}
|
|
702972
704081
|
hashAdminAuthCode(code8) {
|
|
702973
|
-
return
|
|
704082
|
+
return createHash49("sha256").update(`omnius-telegram-admin:${code8.trim()}`).digest("hex");
|
|
702974
704083
|
}
|
|
702975
704084
|
viewIdForMessage(msg) {
|
|
702976
704085
|
return `telegram-${this.sessionKeyForMessage(msg).replace(/[^A-Za-z0-9_-]/g, "-")}`;
|
|
@@ -705042,11 +706151,11 @@ ${mediaContext}` : ""
|
|
|
705042
706151
|
return payload;
|
|
705043
706152
|
}
|
|
705044
706153
|
telegramConversationPath(sessionKey) {
|
|
705045
|
-
const safe =
|
|
706154
|
+
const safe = createHash49("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
705046
706155
|
return join170(this.telegramConversationDir, `${safe}.json`);
|
|
705047
706156
|
}
|
|
705048
706157
|
telegramConversationLedgerPath(sessionKey) {
|
|
705049
|
-
const safe =
|
|
706158
|
+
const safe = createHash49("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
705050
706159
|
return join170(this.telegramConversationDir, `${safe}.events.jsonl`);
|
|
705051
706160
|
}
|
|
705052
706161
|
telegramDb() {
|
|
@@ -705279,7 +706388,7 @@ ${mediaContext}` : ""
|
|
|
705279
706388
|
relationships: Array.isArray(raw.relationships) ? raw.relationships.slice(0, TELEGRAM_ASSOCIATIVE_RELATION_LIMIT).map((fact) => this.normalizeTelegramAssociativeFact(fact)) : [],
|
|
705280
706389
|
actions: Array.isArray(raw.actions) ? raw.actions.slice(-TELEGRAM_ASSOCIATIVE_ACTION_LIMIT).map((action) => ({
|
|
705281
706390
|
id: String(
|
|
705282
|
-
action.id ||
|
|
706391
|
+
action.id || createHash49("sha1").update(JSON.stringify(action)).digest("hex").slice(0, 12)
|
|
705283
706392
|
),
|
|
705284
706393
|
ts: typeof action.ts === "number" ? action.ts : Date.now(),
|
|
705285
706394
|
role: action.role === "assistant" ? "assistant" : "user",
|
|
@@ -705298,7 +706407,7 @@ ${mediaContext}` : ""
|
|
|
705298
706407
|
const now2 = Date.now();
|
|
705299
706408
|
return {
|
|
705300
706409
|
id: String(
|
|
705301
|
-
raw.id ||
|
|
706410
|
+
raw.id || createHash49("sha1").update(text2 || String(now2)).digest("hex").slice(0, 12)
|
|
705302
706411
|
),
|
|
705303
706412
|
text: text2,
|
|
705304
706413
|
tags: Array.isArray(raw.tags) ? raw.tags.map(String).slice(0, 16) : [],
|
|
@@ -705755,7 +706864,7 @@ ${mediaContext}` : ""
|
|
|
705755
706864
|
telegramHistoryBackfillMessageId(sessionKey, entry, index) {
|
|
705756
706865
|
if (typeof entry.messageId === "number" && Number.isFinite(entry.messageId))
|
|
705757
706866
|
return entry.messageId;
|
|
705758
|
-
const digest3 =
|
|
706867
|
+
const digest3 = createHash49("sha1").update(
|
|
705759
706868
|
`${sessionKey}:${index}:${entry.role}:${entry.ts ?? ""}:${entry.text}`
|
|
705760
706869
|
).digest("hex").slice(0, 8);
|
|
705761
706870
|
return -Number.parseInt(digest3, 16);
|
|
@@ -706945,7 +708054,7 @@ ${mediaContext}` : ""
|
|
|
706945
708054
|
const now2 = entry.ts ?? Date.now();
|
|
706946
708055
|
memory.updatedAt = now2;
|
|
706947
708056
|
const speaker = telegramHistorySpeaker(entry);
|
|
706948
|
-
const actionId =
|
|
708057
|
+
const actionId = createHash49("sha1").update(
|
|
706949
708058
|
`${sessionKey}:${entry.role}:${entry.messageId ?? ""}:${now2}:${entry.text}`
|
|
706950
708059
|
).digest("hex").slice(0, 16);
|
|
706951
708060
|
if (!memory.actions.some((action) => action.id === actionId)) {
|
|
@@ -707108,7 +708217,7 @@ ${mediaContext}` : ""
|
|
|
707108
708217
|
let fact = facts.find((item) => item.text.toLowerCase() === key);
|
|
707109
708218
|
if (!fact) {
|
|
707110
708219
|
fact = {
|
|
707111
|
-
id:
|
|
708220
|
+
id: createHash49("sha1").update(`${entry.chatId ?? ""}:${key}`).digest("hex").slice(0, 12),
|
|
707112
708221
|
text: clean5,
|
|
707113
708222
|
tags: telegramMemoryTags(clean5, entry.mediaSummary),
|
|
707114
708223
|
speakers: [],
|
|
@@ -707193,7 +708302,7 @@ ${mediaContext}` : ""
|
|
|
707193
708302
|
const titleTags = tags.slice(0, 4);
|
|
707194
708303
|
const title = titleTags.length > 0 ? `${speaker} / ${titleTags.join(" ")}` : `${speaker} / conversation`;
|
|
707195
708304
|
const card = {
|
|
707196
|
-
id:
|
|
708305
|
+
id: createHash49("sha1").update(`${sessionKey}:${now2}:${speaker}:${text2}`).digest("hex").slice(0, 12),
|
|
707197
708306
|
title,
|
|
707198
708307
|
notes: [],
|
|
707199
708308
|
tags: [],
|
|
@@ -709957,7 +711066,7 @@ ${list}` : "No shared group target is currently known for this sender. Ask in th
|
|
|
709957
711066
|
}
|
|
709958
711067
|
telegramRunnerStateDir(sessionKey) {
|
|
709959
711068
|
if (!this.repoRoot) return void 0;
|
|
709960
|
-
const safe =
|
|
711069
|
+
const safe = createHash49("sha1").update(sessionKey).digest("hex").slice(0, 20);
|
|
709961
711070
|
return join170(this.repoRoot, ".omnius", "telegram-runner-state", safe);
|
|
709962
711071
|
}
|
|
709963
711072
|
buildTelegramAdminOverviewContext(currentSessionKey) {
|
|
@@ -720652,14 +721761,14 @@ var init_access_policy = __esm({
|
|
|
720652
721761
|
});
|
|
720653
721762
|
|
|
720654
721763
|
// packages/cli/src/api/project-preferences.ts
|
|
720655
|
-
import { createHash as
|
|
721764
|
+
import { createHash as createHash50 } from "node:crypto";
|
|
720656
721765
|
import { existsSync as existsSync162, mkdirSync as mkdirSync100, readFileSync as readFileSync133, renameSync as renameSync16, writeFileSync as writeFileSync87, unlinkSync as unlinkSync37 } from "node:fs";
|
|
720657
721766
|
import { homedir as homedir58 } from "node:os";
|
|
720658
721767
|
import { join as join172, resolve as resolve75 } from "node:path";
|
|
720659
721768
|
import { randomUUID as randomUUID20 } from "node:crypto";
|
|
720660
721769
|
function projectKey(root) {
|
|
720661
721770
|
const canonical = resolve75(root);
|
|
720662
|
-
return
|
|
721771
|
+
return createHash50("sha256").update(canonical).digest("hex").slice(0, 16);
|
|
720663
721772
|
}
|
|
720664
721773
|
function projectDir(root) {
|
|
720665
721774
|
return join172(PROJECTS_DIR, projectKey(root));
|
|
@@ -720950,7 +722059,7 @@ var init_disk_task_output = __esm({
|
|
|
720950
722059
|
});
|
|
720951
722060
|
|
|
720952
722061
|
// packages/cli/src/api/http.ts
|
|
720953
|
-
import { createHash as
|
|
722062
|
+
import { createHash as createHash51 } from "node:crypto";
|
|
720954
722063
|
function problemDetails(opts) {
|
|
720955
722064
|
const p2 = {
|
|
720956
722065
|
type: opts.type ?? "about:blank",
|
|
@@ -721013,7 +722122,7 @@ function paginated(items, page2, total) {
|
|
|
721013
722122
|
}
|
|
721014
722123
|
function computeEtag(payload) {
|
|
721015
722124
|
const json = typeof payload === "string" ? payload : JSON.stringify(payload);
|
|
721016
|
-
const hash =
|
|
722125
|
+
const hash = createHash51("sha1").update(json).digest("hex").slice(0, 16);
|
|
721017
722126
|
return `W/"${hash}"`;
|
|
721018
722127
|
}
|
|
721019
722128
|
function checkNotModified(req3, res, etag) {
|
|
@@ -740424,7 +741533,7 @@ import {
|
|
|
740424
741533
|
closeSync as closeSync6
|
|
740425
741534
|
} from "node:fs";
|
|
740426
741535
|
import { randomBytes as randomBytes29, randomUUID as randomUUID21, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
|
|
740427
|
-
import { createHash as
|
|
741536
|
+
import { createHash as createHash52 } from "node:crypto";
|
|
740428
741537
|
function memoryDbPaths3(baseDir = process.cwd()) {
|
|
740429
741538
|
const dir = join183(baseDir, ".omnius");
|
|
740430
741539
|
return {
|
|
@@ -748593,7 +749702,7 @@ function listScheduledTasks() {
|
|
|
748593
749702
|
);
|
|
748594
749703
|
const enabled2 = typeof t2?.enabled === "boolean" ? t2.enabled : true;
|
|
748595
749704
|
const realId = typeof t2?.id === "string" && t2.id ? t2.id : null;
|
|
748596
|
-
const fallbackId =
|
|
749705
|
+
const fallbackId = createHash52("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
|
|
748597
749706
|
const uid = realId || fallbackId;
|
|
748598
749707
|
const key = `${uid}`;
|
|
748599
749708
|
if (seen.has(key)) return;
|
|
@@ -748731,8 +749840,8 @@ function deleteScheduledById(id2) {
|
|
|
748731
749840
|
if (typeof entry?.id === "string" && entry.id && !candidates.includes(entry.id))
|
|
748732
749841
|
candidates.push(entry.id);
|
|
748733
749842
|
try {
|
|
748734
|
-
const { createHash:
|
|
748735
|
-
const fallback =
|
|
749843
|
+
const { createHash: createHash54 } = require4("node:crypto");
|
|
749844
|
+
const fallback = createHash54("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
|
|
748736
749845
|
if (!candidates.includes(fallback)) candidates.push(fallback);
|
|
748737
749846
|
} catch {
|
|
748738
749847
|
}
|
|
@@ -750969,7 +752078,7 @@ import { cwd } from "node:process";
|
|
|
750969
752078
|
import { resolve as resolve78, join as join185, dirname as dirname56, extname as extname22, relative as relative22, sep as sep7 } from "node:path";
|
|
750970
752079
|
import { createRequire as createRequire9 } from "node:module";
|
|
750971
752080
|
import { fileURLToPath as fileURLToPath24 } from "node:url";
|
|
750972
|
-
import { createHash as
|
|
752081
|
+
import { createHash as createHash53 } from "node:crypto";
|
|
750973
752082
|
import {
|
|
750974
752083
|
readFileSync as readFileSync142,
|
|
750975
752084
|
writeFileSync as writeFileSync94,
|
|
@@ -751903,7 +753012,7 @@ function truncateSubAgentViewText(s2, n2) {
|
|
|
751903
753012
|
return s2.length > n2 ? `${s2.slice(0, n2)}…` : s2;
|
|
751904
753013
|
}
|
|
751905
753014
|
function childAgentTaskHash(task) {
|
|
751906
|
-
return
|
|
753015
|
+
return createHash53("sha256").update(task).digest("hex").slice(0, 12);
|
|
751907
753016
|
}
|
|
751908
753017
|
function stripAnsiForParentContext(value2) {
|
|
751909
753018
|
return value2.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "");
|
|
@@ -752065,6 +753174,11 @@ function writeSubAgentEventForView(statusBar, agentId, event, verbose = false) {
|
|
|
752065
753174
|
}
|
|
752066
753175
|
}
|
|
752067
753176
|
function formatSubAgentEventForView(event) {
|
|
753177
|
+
const summarizeEventContent = (content) => {
|
|
753178
|
+
const summaryLines = summarizeInternalControlOutput(content);
|
|
753179
|
+
if (!summaryLines || summaryLines.length === 0) return null;
|
|
753180
|
+
return truncateSubAgentViewText(summaryLines.join("\n"), 420);
|
|
753181
|
+
};
|
|
752068
753182
|
switch (event.type) {
|
|
752069
753183
|
case "tool_call": {
|
|
752070
753184
|
let args = "";
|
|
@@ -752077,17 +753191,26 @@ function formatSubAgentEventForView(event) {
|
|
|
752077
753191
|
}
|
|
752078
753192
|
case "tool_result": {
|
|
752079
753193
|
const mark = event.success === false ? "✗" : "✓";
|
|
752080
|
-
const
|
|
753194
|
+
const output = event.content ?? "";
|
|
753195
|
+
const summary = summarizeEventContent(output);
|
|
753196
|
+
const body = summary ? `${summary}` : output.split("\n").slice(0, 3).join(" ").trim();
|
|
753197
|
+
if (summary) {
|
|
753198
|
+
const compact4 = `${mark} ${event.toolName ?? "tool"}
|
|
753199
|
+
${summary}`;
|
|
753200
|
+
return truncateSubAgentViewText(compact4, 420);
|
|
753201
|
+
}
|
|
752081
753202
|
return `${mark} ${event.toolName ?? "tool"}${body ? `: ${truncateSubAgentViewText(body, 300)}` : ""}`;
|
|
752082
753203
|
}
|
|
752083
753204
|
case "assistant_text":
|
|
752084
753205
|
case "model_response": {
|
|
752085
|
-
const
|
|
753206
|
+
const summary = summarizeEventContent(event.content ?? "");
|
|
753207
|
+
const t2 = summary ?? (event.content ?? "").trim();
|
|
752086
753208
|
return t2 ? truncateSubAgentViewText(t2, 1e3) : null;
|
|
752087
753209
|
}
|
|
752088
753210
|
case "status": {
|
|
752089
|
-
const
|
|
752090
|
-
|
|
753211
|
+
const summary = summarizeEventContent(event.content ?? "");
|
|
753212
|
+
const t2 = summary ?? (event.content ?? "").trim();
|
|
753213
|
+
return t2 ? `· ${truncateSubAgentViewText(t2, 420)}` : null;
|
|
752091
753214
|
}
|
|
752092
753215
|
case "trajectory_checkpoint": {
|
|
752093
753216
|
const assessment = event.trajectory?.assessment ?? "updated";
|
|
@@ -754648,12 +755771,14 @@ ${entry.fullContent}`
|
|
|
754648
755771
|
break;
|
|
754649
755772
|
}
|
|
754650
755773
|
const statusContent = event.content ?? "";
|
|
755774
|
+
const compactStatusLines = summarizeInternalControlOutput(statusContent);
|
|
755775
|
+
const compactStatusContent = compactStatusLines?.length ? compactStatusLines.join("\n") : statusContent;
|
|
754651
755776
|
const gpuWaitingStatus = /^Waiting for free GPU\.{3,}$/.test(
|
|
754652
|
-
|
|
755777
|
+
compactStatusContent
|
|
754653
755778
|
);
|
|
754654
|
-
const gpuResumeStatus =
|
|
755779
|
+
const gpuResumeStatus = compactStatusContent === "GPU Free, Resuming";
|
|
754655
755780
|
if (gpuWaitingStatus) {
|
|
754656
|
-
const dotCount =
|
|
755781
|
+
const dotCount = compactStatusContent.match(/\.+$/)?.[0]?.length ?? 3;
|
|
754657
755782
|
if (startGpuRecoveryBlock(dotCount)) break;
|
|
754658
755783
|
} else if (gpuResumeStatus && finishGpuRecoveryBlock()) {
|
|
754659
755784
|
break;
|
|
@@ -754662,13 +755787,13 @@ ${entry.fullContent}`
|
|
|
754662
755787
|
if (!config.debug && !gpuRecoveryStatus) break;
|
|
754663
755788
|
if (isNeovimActive()) {
|
|
754664
755789
|
writeToNeovimOutput(
|
|
754665
|
-
`\x1B[38;5;250m${
|
|
755790
|
+
`\x1B[38;5;250m${compactStatusContent}\x1B[0m\r
|
|
754666
755791
|
`
|
|
754667
755792
|
);
|
|
754668
755793
|
} else {
|
|
754669
|
-
contentWrite(() => renderInfo(
|
|
754670
|
-
if (
|
|
754671
|
-
lastProvenancePath =
|
|
755794
|
+
contentWrite(() => renderInfo(compactStatusContent));
|
|
755795
|
+
if (statusContent && statusContent.startsWith("Provenance saved: ")) {
|
|
755796
|
+
lastProvenancePath = statusContent.slice("Provenance saved: ".length).trim();
|
|
754672
755797
|
}
|
|
754673
755798
|
}
|
|
754674
755799
|
break;
|
|
@@ -757008,6 +758133,12 @@ This is an independent background session started from /background.`
|
|
|
757008
758133
|
process.stdout.on("resize", () => {
|
|
757009
758134
|
statusBar.handleResize();
|
|
757010
758135
|
setTermSize(process.stdout.rows ?? 24, process.stdout.columns ?? 80);
|
|
758136
|
+
if (!isNeovimActive()) {
|
|
758137
|
+
try {
|
|
758138
|
+
streamRenderer.onResize();
|
|
758139
|
+
} catch {
|
|
758140
|
+
}
|
|
758141
|
+
}
|
|
757011
758142
|
if (isNeovimActive()) {
|
|
757012
758143
|
const contentRows = statusBar.isActive ? statusBar.availableContentRows : Math.max(5, termRows() - 6);
|
|
757013
758144
|
resizeNeovim(termCols(), contentRows);
|
|
@@ -761224,13 +762355,13 @@ ${taskInput}`;
|
|
|
761224
762355
|
writeContent(() => renderError(errMsg));
|
|
761225
762356
|
if (failureStore) {
|
|
761226
762357
|
try {
|
|
761227
|
-
const { createHash:
|
|
762358
|
+
const { createHash: createHash54 } = await import("node:crypto");
|
|
761228
762359
|
failureStore.insert({
|
|
761229
762360
|
taskId: "",
|
|
761230
762361
|
sessionId: `${Date.now()}`,
|
|
761231
762362
|
repoRoot,
|
|
761232
762363
|
failureType: "runtime-error",
|
|
761233
|
-
fingerprint:
|
|
762364
|
+
fingerprint: createHash54("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
|
|
761234
762365
|
filePath: null,
|
|
761235
762366
|
errorMessage: errMsg.slice(0, 500),
|
|
761236
762367
|
context: null,
|