nexum-code 0.7.0 → 0.7.10
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/{app-DDsPnVUr.mjs → app-MzrtWfvw.mjs} +2411 -463
- package/dist/assets/tokenizers.darwin-universal-BJ7w7c9-.node +0 -0
- package/dist/assets/tokenizers.linux-x64-gnu-BGGFQRsL.node +0 -0
- package/dist/{esm-RYfZ46Tf.mjs → esm-PKa8Krwc.mjs} +2 -2
- package/dist/main.mjs +1 -1
- package/package.json +91 -88
- package/scripts/postinstall.mjs +88 -101
- package/dist/pdf-F2kQiIQy.mjs +0 -26642
- package/dist/pdf.worker-ByxNbF6P.mjs +0 -82061
- package/dist/{src-BxVYaO-v.mjs → src-C6XAfwit.mjs} +1 -1
|
@@ -25,6 +25,7 @@ import { z } from "zod";
|
|
|
25
25
|
import * as os from "node:os";
|
|
26
26
|
import { arch, homedir, hostname, release, tmpdir, type } from "node:os";
|
|
27
27
|
import { exec, execFile, execFileSync, execSync, spawn, spawnSync } from "node:child_process";
|
|
28
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
28
29
|
import { DatabaseSync } from "node:sqlite";
|
|
29
30
|
import { StringDecoder } from "node:string_decoder";
|
|
30
31
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
@@ -32,7 +33,6 @@ import * as posixPath from "node:path/posix";
|
|
|
32
33
|
import * as win32Path from "node:path/win32";
|
|
33
34
|
import { createServer } from "node:http";
|
|
34
35
|
import * as z$1 from "zod/v4";
|
|
35
|
-
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
36
36
|
import { parse as parse$1, stringify } from "smol-toml";
|
|
37
37
|
import "zod/v3";
|
|
38
38
|
import * as z4mini from "zod/v4-mini";
|
|
@@ -904,6 +904,38 @@ function normalizeToolCallIdsForProvider(messages, policy) {
|
|
|
904
904
|
});
|
|
905
905
|
return changed ? normalizedMessages : messages;
|
|
906
906
|
}
|
|
907
|
+
function removeInvalidToolExchangesForProvider(messages) {
|
|
908
|
+
let changed = false;
|
|
909
|
+
const repaired = [];
|
|
910
|
+
let index = 0;
|
|
911
|
+
while (index < messages.length) {
|
|
912
|
+
const message = messages[index];
|
|
913
|
+
if (message === void 0) break;
|
|
914
|
+
if (message.role === "tool") {
|
|
915
|
+
changed = true;
|
|
916
|
+
index++;
|
|
917
|
+
continue;
|
|
918
|
+
}
|
|
919
|
+
if (message.role !== "assistant" || message.toolCalls.length === 0) {
|
|
920
|
+
repaired.push(message);
|
|
921
|
+
index++;
|
|
922
|
+
continue;
|
|
923
|
+
}
|
|
924
|
+
const requiredToolCallIds = new Set(message.toolCalls.map((toolCall) => toolCall.id));
|
|
925
|
+
const toolResults = [];
|
|
926
|
+
let cursor = index + 1;
|
|
927
|
+
while (cursor < messages.length && messages[cursor]?.role === "tool") {
|
|
928
|
+
const toolMessage = messages[cursor];
|
|
929
|
+
if (toolMessage.toolCallId !== void 0 && requiredToolCallIds.delete(toolMessage.toolCallId)) toolResults.push(toolMessage);
|
|
930
|
+
else changed = true;
|
|
931
|
+
cursor++;
|
|
932
|
+
}
|
|
933
|
+
if (requiredToolCallIds.size === 0) repaired.push(message, ...toolResults);
|
|
934
|
+
else changed = true;
|
|
935
|
+
index = cursor;
|
|
936
|
+
}
|
|
937
|
+
return changed ? repaired : messages;
|
|
938
|
+
}
|
|
907
939
|
function collectToolCallIds(messages) {
|
|
908
940
|
const ids = [];
|
|
909
941
|
const seen = /* @__PURE__ */ new Set();
|
|
@@ -10434,7 +10466,7 @@ var require_gaxios = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
10434
10466
|
}
|
|
10435
10467
|
static async #getFetch() {
|
|
10436
10468
|
const hasWindow = typeof window !== "undefined" && !!window;
|
|
10437
|
-
this.#fetch ||= hasWindow ? window.fetch : (await import("./src-
|
|
10469
|
+
this.#fetch ||= hasWindow ? window.fetch : (await import("./src-C6XAfwit.mjs")).default;
|
|
10438
10470
|
return this.#fetch;
|
|
10439
10471
|
}
|
|
10440
10472
|
/**
|
|
@@ -48666,7 +48698,7 @@ var NexumChatProvider = class {
|
|
|
48666
48698
|
};
|
|
48667
48699
|
}
|
|
48668
48700
|
async generate(systemPrompt, tools, history, options) {
|
|
48669
|
-
const normalizedHistory = normalizeToolCallIdsForProvider(history, OPENAI_CHAT_TOOL_CALL_ID_POLICY$1);
|
|
48701
|
+
const normalizedHistory = removeInvalidToolExchangesForProvider(normalizeToolCallIdsForProvider(history, OPENAI_CHAT_TOOL_CALL_ID_POLICY$1));
|
|
48670
48702
|
const messages = [];
|
|
48671
48703
|
if (systemPrompt) messages.push({
|
|
48672
48704
|
role: "system",
|
|
@@ -48953,7 +48985,7 @@ var OpenAILegacyChatProvider = class {
|
|
|
48953
48985
|
role: "system",
|
|
48954
48986
|
content: systemPrompt
|
|
48955
48987
|
});
|
|
48956
|
-
const normalizedHistory = normalizeToolCallIdsForProvider(history, OPENAI_CHAT_TOOL_CALL_ID_POLICY);
|
|
48988
|
+
const normalizedHistory = removeInvalidToolExchangesForProvider(normalizeToolCallIdsForProvider(history, OPENAI_CHAT_TOOL_CALL_ID_POLICY));
|
|
48957
48989
|
for (const msg of normalizedHistory) messages.push(convertMessage$1(msg, this._reasoningKey, this._toolMessageConversion));
|
|
48958
48990
|
const kwargs = { ...this._generationKwargs };
|
|
48959
48991
|
let reasoningEffort = this._reasoningEffort;
|
|
@@ -49583,7 +49615,7 @@ var OpenAIResponsesChatProvider = class {
|
|
|
49583
49615
|
if (usesOpenAIResponsesDeveloperRole(this._model)) sysItem["role"] = "developer";
|
|
49584
49616
|
input.push(sysItem);
|
|
49585
49617
|
}
|
|
49586
|
-
const normalizedHistory = normalizeToolCallIdsForProvider(history, OPENAI_RESPONSES_TOOL_CALL_ID_POLICY);
|
|
49618
|
+
const normalizedHistory = removeInvalidToolExchangesForProvider(normalizeToolCallIdsForProvider(history, OPENAI_RESPONSES_TOOL_CALL_ID_POLICY));
|
|
49587
49619
|
for (const msg of normalizedHistory) input.push(...convertMessage(msg, this._model, this._toolMessageConversion));
|
|
49588
49620
|
const kwargs = { ...this._generationKwargs };
|
|
49589
49621
|
const reasoningEffort = kwargs["reasoning_effort"];
|
|
@@ -55220,8 +55252,11 @@ const ToolAccesses = {
|
|
|
55220
55252
|
none() {
|
|
55221
55253
|
return [];
|
|
55222
55254
|
},
|
|
55223
|
-
all() {
|
|
55224
|
-
return [{
|
|
55255
|
+
all(scope = "global") {
|
|
55256
|
+
return [{
|
|
55257
|
+
kind: "all",
|
|
55258
|
+
scope
|
|
55259
|
+
}];
|
|
55225
55260
|
},
|
|
55226
55261
|
file(operation, path, options = {}) {
|
|
55227
55262
|
return [{
|
|
@@ -55254,13 +55289,47 @@ const ToolAccesses = {
|
|
|
55254
55289
|
},
|
|
55255
55290
|
conflict(left, right) {
|
|
55256
55291
|
return left.some((leftAccess) => right.some((rightAccess) => resourceAccessesConflict(leftAccess, rightAccess)));
|
|
55292
|
+
},
|
|
55293
|
+
/**
|
|
55294
|
+
* Normalize a file path for resource conflict comparison.
|
|
55295
|
+
*
|
|
55296
|
+
* - Resolves `.` and `..` segments.
|
|
55297
|
+
* - Resolves relative paths against `cwd`.
|
|
55298
|
+
* - Converts backslashes to forward slashes.
|
|
55299
|
+
* - Optionally folds case (Windows default is case-insensitive).
|
|
55300
|
+
* - Strips trailing slashes except for the root `/`.
|
|
55301
|
+
*/
|
|
55302
|
+
normalizePath(filePath, options) {
|
|
55303
|
+
const cwd = options?.cwd ?? process.cwd();
|
|
55304
|
+
let normalized = path$9.resolve(cwd, filePath).replace(/\\/g, "/").replace(/\/+/g, "/");
|
|
55305
|
+
if (!(options?.caseSensitive ?? defaultCaseSensitivity())) normalized = normalized.toLowerCase();
|
|
55306
|
+
if (normalized.length > 1 && normalized.endsWith("/")) normalized = normalized.slice(0, -1);
|
|
55307
|
+
return normalized;
|
|
55257
55308
|
}
|
|
55258
55309
|
};
|
|
55310
|
+
function defaultCaseSensitivity() {
|
|
55311
|
+
return process.platform !== "win32";
|
|
55312
|
+
}
|
|
55259
55313
|
function resourceAccessesConflict(left, right) {
|
|
55260
|
-
if (left.kind === "all"
|
|
55314
|
+
if (left.kind === "all" && right.kind === "all") return scopesConflict(left.scope, right.scope);
|
|
55315
|
+
if (left.kind === "all") return broadAccessConflictsWithFile(left.scope, right);
|
|
55316
|
+
if (right.kind === "all") return broadAccessConflictsWithFile(right.scope, left);
|
|
55261
55317
|
if (!fileOperationsConflict(left.operation, right.operation)) return false;
|
|
55262
55318
|
return fileAccessesOverlap(left, right);
|
|
55263
55319
|
}
|
|
55320
|
+
function scopesConflict(left, right) {
|
|
55321
|
+
if (left === "global" || right === "global") return true;
|
|
55322
|
+
return left === right;
|
|
55323
|
+
}
|
|
55324
|
+
function broadAccessConflictsWithFile(scope, file) {
|
|
55325
|
+
switch (scope) {
|
|
55326
|
+
case "global": return true;
|
|
55327
|
+
case "filesystem":
|
|
55328
|
+
case "workspace": return true;
|
|
55329
|
+
case "network": return false;
|
|
55330
|
+
case "process": return file.operation === "write" || file.operation === "readwrite";
|
|
55331
|
+
}
|
|
55332
|
+
}
|
|
55264
55333
|
function fileOperationsConflict(left, right) {
|
|
55265
55334
|
return fileOperationWrites(left) || fileOperationWrites(right);
|
|
55266
55335
|
}
|
|
@@ -55273,17 +55342,15 @@ function fileOperationWrites(operation) {
|
|
|
55273
55342
|
}
|
|
55274
55343
|
}
|
|
55275
55344
|
function fileAccessesOverlap(left, right) {
|
|
55276
|
-
const leftPath =
|
|
55277
|
-
const rightPath =
|
|
55345
|
+
const leftPath = normalizeAccessPath(left.path);
|
|
55346
|
+
const rightPath = normalizeAccessPath(right.path);
|
|
55278
55347
|
if (leftPath === rightPath) return true;
|
|
55279
55348
|
const leftPrefix = leftPath.endsWith("/") ? leftPath : `${leftPath}/`;
|
|
55280
55349
|
const rightPrefix = rightPath.endsWith("/") ? rightPath : `${rightPath}/`;
|
|
55281
55350
|
return left.recursive === true && rightPath.startsWith(leftPrefix) || right.recursive === true && leftPath.startsWith(rightPrefix);
|
|
55282
55351
|
}
|
|
55283
|
-
function
|
|
55284
|
-
|
|
55285
|
-
if (folded.length > 1 && folded.endsWith("/")) return folded.slice(0, -1);
|
|
55286
|
-
return folded;
|
|
55352
|
+
function normalizeAccessPath(filePath) {
|
|
55353
|
+
return ToolAccesses.normalizePath(filePath);
|
|
55287
55354
|
}
|
|
55288
55355
|
//#endregion
|
|
55289
55356
|
//#region ../../packages/agent-core/src/utils/abort.ts
|
|
@@ -55367,7 +55434,7 @@ var agent_background_disabled_default = "Background agent execution is disabled
|
|
|
55367
55434
|
var agent_background_enabled_default = "When `run_in_background=true`, the subagent runs detached from this turn. The completion arrives in a later turn as a synthetic user-role message containing its result — you do not need to poll, sleep, or check on its progress. Continue with other work or respond to the user. Never fabricate or predict what the result will say.\r\n\r\nFor a background task, when `timeout` is omitted it falls back to the operator-configured background timeout, if one is set. If the operator has not configured a background timeout, an omitted `timeout` means the task runs with no time limit.\r\n";
|
|
55368
55435
|
//#endregion
|
|
55369
55436
|
//#region ../../packages/agent-core/src/tools/builtin/collaboration/agent.md
|
|
55370
|
-
var agent_default$1 = "Launch a subagent to handle a task.
|
|
55437
|
+
var agent_default$1 = "Launch a subagent to handle a focused task. Prefer this tool over doing the work yourself when the task matches one of the specialists below.\n\nSpecialist subagents:\n- `coder` - concrete coding, editing, refactoring\n- `explore` - read-only codebase investigation\n- `plan` - implementation planning and architecture\n- `verify` - build/test/lint checks\n- `reviewer` - code review\n- `oracle` - deep debugging and second opinions\n- `writer` - reports and documentation\n\r\n## Required prompt structure\r\n\r\nThe final prompt sent to the subagent MUST contain these sections. Provide them either by writing them directly into the `prompt` field, or by using the structured `target`, `change`, and `acceptance` fields — they will be appended to `prompt` automatically.\r\n\r\n```markdown\r\n# Target\r\nExact files, symbols, or directories to touch. Explicit non-goals.\r\n\r\n# Change\r\nStep-by-step what to add, remove, or modify. Include concrete examples when possible.\r\n\r\n# Acceptance\r\nObservable result that proves completion: a passing test, a build command, a specific file content, or a verification step the subagent must run.\r\n```\r\n\r\nOmitting a section causes the subagent to miss context and increases the chance of a wrong or incomplete result.\r\n\r\nWriting the prompt:\r\n- The subagent starts with zero context — it has not seen this conversation. Brief it like a colleague who just walked into the room: state the goal, list what you already know, hand over the specifics.\r\n- Lookups (read this file, run that test): put the exact path or command in the prompt. The subagent should not have to search for things you already know.\r\n- Investigations (figure out X, find why Y): give the question, not prescribed steps — fixed steps become dead weight when the premise is wrong.\r\n- Do not delegate understanding. If the task hinges on a file path or line number, find it yourself first and write it into the prompt.\r\n- The `Acceptance` section is not optional. The subagent MUST verify against it before returning.\r\n\r\nUsage notes:\r\n- When the task continues earlier work a subagent already did, prefer resuming that agent (pass its `resume` id) over spawning a fresh instance — the resumed agent keeps its prior context.\r\n- A subagent's result is only visible to you, not to the user. When the user needs to see what a subagent produced, summarize the relevant parts yourself in your own reply.\r\n\r\nWhen NOT to use Agent: skip delegation for trivial one-step work, such as reading a known file. Almost everything else is a candidate for delegation.\n\r\nOnce a subagent is running, leave that scope to it: do not redo its searches or reads in parallel, and do not abandon it midway and finish the job manually. Both undo the context savings the delegation was meant to buy.\n";
|
|
55371
55438
|
//#endregion
|
|
55372
55439
|
//#region ../../packages/agent-core/src/tools/builtin/collaboration/agent.ts
|
|
55373
55440
|
/**
|
|
@@ -86891,7 +86958,7 @@ function createPdfjsPageRenderer(options = {}) {
|
|
|
86891
86958
|
const scale = options.scale ?? 2;
|
|
86892
86959
|
return { async renderPage(filePath, pageIndex) {
|
|
86893
86960
|
const canvasModule = await loadCanvasModule();
|
|
86894
|
-
const document = await (await loadPdfjs$1()).getDocument(
|
|
86961
|
+
const document = await (await loadPdfjs$1()).getDocument(createPdfjsDocumentOptions(filePath)).promise;
|
|
86895
86962
|
try {
|
|
86896
86963
|
const page = await document.getPage(pageIndex + 1);
|
|
86897
86964
|
const viewport = page.getViewport({ scale });
|
|
@@ -86913,8 +86980,22 @@ function createPdfjsPageRenderer(options = {}) {
|
|
|
86913
86980
|
}
|
|
86914
86981
|
} };
|
|
86915
86982
|
}
|
|
86983
|
+
function createPdfjsDocumentOptions(filePath) {
|
|
86984
|
+
const pdfjsModulePath = createRequire(import.meta.url).resolve("pdfjs-dist/legacy/build/pdf.mjs");
|
|
86985
|
+
const pdfjsRoot = path$9.resolve(path$9.dirname(pdfjsModulePath), "../..");
|
|
86986
|
+
return {
|
|
86987
|
+
url: filePath,
|
|
86988
|
+
cMapUrl: pdfjsAssetDirectory(pdfjsRoot, "cmaps"),
|
|
86989
|
+
cMapPacked: true,
|
|
86990
|
+
standardFontDataUrl: pdfjsAssetDirectory(pdfjsRoot, "standard_fonts"),
|
|
86991
|
+
wasmUrl: pdfjsAssetDirectory(pdfjsRoot, "wasm")
|
|
86992
|
+
};
|
|
86993
|
+
}
|
|
86994
|
+
function pdfjsAssetDirectory(pdfjsRoot, directoryName) {
|
|
86995
|
+
return `${path$9.join(pdfjsRoot, directoryName).replaceAll(/[\\/]+$/g, "")}/`;
|
|
86996
|
+
}
|
|
86916
86997
|
async function loadPdfjs$1() {
|
|
86917
|
-
return import("
|
|
86998
|
+
return import("pdfjs-dist/legacy/build/pdf.mjs");
|
|
86918
86999
|
}
|
|
86919
87000
|
async function loadCanvasModule() {
|
|
86920
87001
|
try {
|
|
@@ -86932,7 +87013,7 @@ function assessPageQuality(page, minCharsPerPage, textQualityThreshold) {
|
|
|
86932
87013
|
const pageArea = (page.width ?? 1) * (page.height ?? 1);
|
|
86933
87014
|
const estimatedCharArea = charCount * 12 * 12;
|
|
86934
87015
|
const coverage = pageArea > 0 ? estimatedCharArea / pageArea : 0;
|
|
86935
|
-
const needsOcr =
|
|
87016
|
+
const needsOcr = charCount < minCharsPerPage && coverage < textQualityThreshold;
|
|
86936
87017
|
return {
|
|
86937
87018
|
pageIndex: page.pageIndex,
|
|
86938
87019
|
charCount,
|
|
@@ -86998,7 +87079,7 @@ function createPdfTextParser(options = {}) {
|
|
|
86998
87079
|
const pdfjs = await loadPdfjs();
|
|
86999
87080
|
let document;
|
|
87000
87081
|
try {
|
|
87001
|
-
document = await pdfjs.getDocument(
|
|
87082
|
+
document = await pdfjs.getDocument(createPdfjsDocumentOptions(ingestion.filePath)).promise;
|
|
87002
87083
|
} catch (error) {
|
|
87003
87084
|
throw new ParseError$1(`Failed to parse PDF ${String(ingestion.metadata["originalName"])}: ${error instanceof Error ? error.message : String(error)}`, false);
|
|
87004
87085
|
}
|
|
@@ -87041,11 +87122,11 @@ function createPdfTextParser(options = {}) {
|
|
|
87041
87122
|
}
|
|
87042
87123
|
async function loadPdfjs() {
|
|
87043
87124
|
await loadPdfjsWorker();
|
|
87044
|
-
return import("
|
|
87125
|
+
return import("pdfjs-dist/legacy/build/pdf.mjs");
|
|
87045
87126
|
}
|
|
87046
87127
|
async function loadPdfjsWorker() {
|
|
87047
87128
|
if (globalThis.pdfjsWorker?.WorkerMessageHandler !== void 0) return;
|
|
87048
|
-
await import("
|
|
87129
|
+
await import("pdfjs-dist/legacy/build/pdf.worker.mjs");
|
|
87049
87130
|
}
|
|
87050
87131
|
function textItemToBlock(item, pageIndex, index, pageHeight) {
|
|
87051
87132
|
return {
|
|
@@ -88802,8 +88883,8 @@ function createTesseractOcrProvider(options = {}) {
|
|
|
88802
88883
|
provider: "tesseract",
|
|
88803
88884
|
pages: [{
|
|
88804
88885
|
pageIndex: 0,
|
|
88805
|
-
width: metadata.width ?? maxRight(lines),
|
|
88806
|
-
height: metadata.height ?? maxBottom(lines),
|
|
88886
|
+
width: metadata.width ?? maxRight$1(lines),
|
|
88887
|
+
height: metadata.height ?? maxBottom$1(lines),
|
|
88807
88888
|
rotation: metadata.orientation,
|
|
88808
88889
|
language: resolved.language,
|
|
88809
88890
|
lines
|
|
@@ -88863,7 +88944,7 @@ function parseTsv(tsv) {
|
|
|
88863
88944
|
if (columns[index("level")] !== "5") continue;
|
|
88864
88945
|
const text = columns[index("text")]?.trim() ?? "";
|
|
88865
88946
|
if (text.length === 0) continue;
|
|
88866
|
-
const confidence = normalizeConfidence(Number.parseFloat(columns[index("conf")] ?? "0"));
|
|
88947
|
+
const confidence = normalizeConfidence$1(Number.parseFloat(columns[index("conf")] ?? "0"));
|
|
88867
88948
|
const word = {
|
|
88868
88949
|
text,
|
|
88869
88950
|
bbox: {
|
|
@@ -88917,6 +88998,242 @@ function unionBBoxes(boxes) {
|
|
|
88917
88998
|
function numberAt(columns, index) {
|
|
88918
88999
|
return Number.parseFloat(columns[index] ?? "0") || 0;
|
|
88919
89000
|
}
|
|
89001
|
+
function normalizeConfidence$1(value) {
|
|
89002
|
+
if (Number.isNaN(value) || value < 0) return 0;
|
|
89003
|
+
return Math.max(0, Math.min(1, value / 100));
|
|
89004
|
+
}
|
|
89005
|
+
function maxRight$1(lines) {
|
|
89006
|
+
return Math.max(0, ...lines.map((line) => line.bbox.x + line.bbox.width));
|
|
89007
|
+
}
|
|
89008
|
+
function maxBottom$1(lines) {
|
|
89009
|
+
return Math.max(0, ...lines.map((line) => line.bbox.y + line.bbox.height));
|
|
89010
|
+
}
|
|
89011
|
+
//#endregion
|
|
89012
|
+
//#region ../../packages/document-intelligence/src/ocr/tesseract-js-provider.ts
|
|
89013
|
+
const DEFAULT_CACHE_DIR = path$9.join(os.homedir(), ".nexum-code", "ocr-cache");
|
|
89014
|
+
const MIN_USEFUL_FULL_PAGE_CHARS = 24;
|
|
89015
|
+
const MIN_USEFUL_LINE_CONFIDENCE = .3;
|
|
89016
|
+
const IMAGE_BAND_COUNT = 4;
|
|
89017
|
+
const MIN_IMAGE_BAND_HEIGHT = 1020;
|
|
89018
|
+
const IMAGE_BAND_OVERLAP = 80;
|
|
89019
|
+
function createTesseractJsOcrProvider(options = {}) {
|
|
89020
|
+
const defaultLanguage = options.language ?? process.env["NEXUM_OCR_LANGUAGE"] ?? "chi_sim+eng";
|
|
89021
|
+
const cachePath = options.cachePath ?? process.env["NEXUM_OCR_CACHE_DIR"] ?? DEFAULT_CACHE_DIR;
|
|
89022
|
+
return {
|
|
89023
|
+
name: "tesseract.js",
|
|
89024
|
+
async recognize(filePath, ocrOptions = {}) {
|
|
89025
|
+
const language = ocrOptions.language ?? defaultLanguage;
|
|
89026
|
+
const metadata = await readImageMetadata(filePath).catch(() => ({}));
|
|
89027
|
+
let worker;
|
|
89028
|
+
try {
|
|
89029
|
+
await fs$11.mkdir(cachePath, { recursive: true });
|
|
89030
|
+
const tesseract = await loadTesseractJs();
|
|
89031
|
+
const langPath = await prepareBundledLanguagePath(language, cachePath);
|
|
89032
|
+
worker = await tesseract.createWorker(normalizeLanguage(language), 1, {
|
|
89033
|
+
langPath,
|
|
89034
|
+
cachePath,
|
|
89035
|
+
cacheMethod: "write",
|
|
89036
|
+
gzip: true,
|
|
89037
|
+
logger: () => void 0
|
|
89038
|
+
});
|
|
89039
|
+
const psm = tesseract.PSM?.AUTO ?? "3";
|
|
89040
|
+
const primaryLines = extractLines((await worker.recognize(filePath, {
|
|
89041
|
+
tessedit_pageseg_mode: psm,
|
|
89042
|
+
preserve_interword_spaces: "1",
|
|
89043
|
+
user_defined_dpi: "300"
|
|
89044
|
+
}, {
|
|
89045
|
+
text: true,
|
|
89046
|
+
blocks: true
|
|
89047
|
+
})).data);
|
|
89048
|
+
const lines = selectAdaptiveOcrLines(primaryLines, shouldRecognizeHorizontalBands(metadata, primaryLines) ? await recognizeHorizontalBands(worker, filePath, psm) : []);
|
|
89049
|
+
const dimensions = displayedDimensions(metadata);
|
|
89050
|
+
return {
|
|
89051
|
+
provider: "tesseract.js",
|
|
89052
|
+
pages: [{
|
|
89053
|
+
pageIndex: 0,
|
|
89054
|
+
width: dimensions.width ?? maxRight(lines),
|
|
89055
|
+
height: dimensions.height ?? maxBottom(lines),
|
|
89056
|
+
rotation: 0,
|
|
89057
|
+
language,
|
|
89058
|
+
lines
|
|
89059
|
+
}]
|
|
89060
|
+
};
|
|
89061
|
+
} catch (error) {
|
|
89062
|
+
throw new ParseError$1(`Tesseract.js OCR failed. ${error instanceof Error ? error.message : String(error)}`, true);
|
|
89063
|
+
} finally {
|
|
89064
|
+
await worker?.terminate().catch(() => void 0);
|
|
89065
|
+
}
|
|
89066
|
+
}
|
|
89067
|
+
};
|
|
89068
|
+
}
|
|
89069
|
+
function selectAdaptiveOcrLines(primaryLines, bands) {
|
|
89070
|
+
const primary = filterUsefulLines(primaryLines);
|
|
89071
|
+
if (bands.length === 0) return primary;
|
|
89072
|
+
const seen = /* @__PURE__ */ new Set();
|
|
89073
|
+
const combined = [];
|
|
89074
|
+
for (const band of bands) for (const line of filterUsefulLines(band.lines)) {
|
|
89075
|
+
const key = line.text.replaceAll(/\s+/g, "");
|
|
89076
|
+
if (seen.has(key)) continue;
|
|
89077
|
+
seen.add(key);
|
|
89078
|
+
combined.push(offsetLine(line, band.offsetY));
|
|
89079
|
+
}
|
|
89080
|
+
const primaryChars = totalMeaningfulCharacters(primary);
|
|
89081
|
+
return totalMeaningfulCharacters(combined) > primaryChars ? combined : primary;
|
|
89082
|
+
}
|
|
89083
|
+
async function recognizeHorizontalBands(worker, filePath, psm) {
|
|
89084
|
+
const canvas = await import("@napi-rs/canvas");
|
|
89085
|
+
const image = await canvas.loadImage(filePath);
|
|
89086
|
+
const tempDir = await fs$11.mkdtemp(path$9.join(os.tmpdir(), "nexum-ocr-bands-"));
|
|
89087
|
+
const bandHeight = Math.max(MIN_IMAGE_BAND_HEIGHT, Math.ceil(image.height / IMAGE_BAND_COUNT));
|
|
89088
|
+
const results = [];
|
|
89089
|
+
try {
|
|
89090
|
+
for (let index = 0; index < IMAGE_BAND_COUNT; index++) {
|
|
89091
|
+
const offsetY = Math.max(0, index * bandHeight - (index === 0 ? 0 : IMAGE_BAND_OVERLAP));
|
|
89092
|
+
const height = Math.min(image.height - offsetY, bandHeight + (index === 0 ? IMAGE_BAND_OVERLAP : IMAGE_BAND_OVERLAP * 2));
|
|
89093
|
+
if (height <= 0) continue;
|
|
89094
|
+
const bandCanvas = canvas.createCanvas(image.width, height);
|
|
89095
|
+
bandCanvas.getContext("2d").drawImage(image, 0, offsetY, image.width, height, 0, 0, image.width, height);
|
|
89096
|
+
const bandPath = path$9.join(tempDir, `band-${index}.png`);
|
|
89097
|
+
await fs$11.writeFile(bandPath, bandCanvas.toBuffer("image/png"));
|
|
89098
|
+
const result = await worker.recognize(bandPath, {
|
|
89099
|
+
tessedit_pageseg_mode: psm,
|
|
89100
|
+
preserve_interword_spaces: "1",
|
|
89101
|
+
user_defined_dpi: "300"
|
|
89102
|
+
}, {
|
|
89103
|
+
text: true,
|
|
89104
|
+
blocks: true
|
|
89105
|
+
});
|
|
89106
|
+
results.push({
|
|
89107
|
+
offsetY,
|
|
89108
|
+
lines: extractLines(result.data)
|
|
89109
|
+
});
|
|
89110
|
+
}
|
|
89111
|
+
return results;
|
|
89112
|
+
} finally {
|
|
89113
|
+
await fs$11.rm(tempDir, {
|
|
89114
|
+
recursive: true,
|
|
89115
|
+
force: true
|
|
89116
|
+
}).catch(() => void 0);
|
|
89117
|
+
}
|
|
89118
|
+
}
|
|
89119
|
+
function hasUsefulFullPageText(lines) {
|
|
89120
|
+
return totalMeaningfulCharacters(filterUsefulLines(lines)) >= MIN_USEFUL_FULL_PAGE_CHARS;
|
|
89121
|
+
}
|
|
89122
|
+
function shouldRecognizeHorizontalBands(metadata, primaryLines) {
|
|
89123
|
+
const dimensions = displayedDimensions(metadata);
|
|
89124
|
+
return (dimensions.width ?? 0) * (dimensions.height ?? 0) >= 4e6 || !hasUsefulFullPageText(primaryLines);
|
|
89125
|
+
}
|
|
89126
|
+
function filterUsefulLines(lines) {
|
|
89127
|
+
return lines.map((line) => ({
|
|
89128
|
+
...line,
|
|
89129
|
+
text: normalizeOcrText(line.text)
|
|
89130
|
+
})).filter((line) => line.confidence >= MIN_USEFUL_LINE_CONFIDENCE && meaningfulCharacterCount(line.text) >= 2);
|
|
89131
|
+
}
|
|
89132
|
+
function totalMeaningfulCharacters(lines) {
|
|
89133
|
+
return lines.reduce((sum, line) => sum + meaningfulCharacterCount(line.text), 0);
|
|
89134
|
+
}
|
|
89135
|
+
function normalizeOcrText(text) {
|
|
89136
|
+
return text.trim().replaceAll(/(?<=\p{Script=Han})\s+(?=\p{Script=Han})/gu, "");
|
|
89137
|
+
}
|
|
89138
|
+
function meaningfulCharacterCount(text) {
|
|
89139
|
+
return Array.from(text.matchAll(/[\p{L}\p{N}]/gu)).length;
|
|
89140
|
+
}
|
|
89141
|
+
function offsetLine(line, offsetY) {
|
|
89142
|
+
return {
|
|
89143
|
+
...line,
|
|
89144
|
+
bbox: {
|
|
89145
|
+
...line.bbox,
|
|
89146
|
+
y: line.bbox.y + offsetY
|
|
89147
|
+
},
|
|
89148
|
+
words: line.words.map((word) => ({
|
|
89149
|
+
...word,
|
|
89150
|
+
bbox: {
|
|
89151
|
+
...word.bbox,
|
|
89152
|
+
y: word.bbox.y + offsetY
|
|
89153
|
+
}
|
|
89154
|
+
}))
|
|
89155
|
+
};
|
|
89156
|
+
}
|
|
89157
|
+
function displayedDimensions(metadata) {
|
|
89158
|
+
return metadata.orientation !== void 0 && metadata.orientation >= 5 && metadata.orientation <= 8 ? {
|
|
89159
|
+
width: metadata.height,
|
|
89160
|
+
height: metadata.width
|
|
89161
|
+
} : {
|
|
89162
|
+
width: metadata.width,
|
|
89163
|
+
height: metadata.height
|
|
89164
|
+
};
|
|
89165
|
+
}
|
|
89166
|
+
async function loadTesseractJs() {
|
|
89167
|
+
const mod = await import("tesseract.js");
|
|
89168
|
+
return mod.default ?? mod;
|
|
89169
|
+
}
|
|
89170
|
+
async function prepareBundledLanguagePath(language, cachePath) {
|
|
89171
|
+
const targetDir = path$9.join(cachePath, "lang-data");
|
|
89172
|
+
await fs$11.mkdir(targetDir, { recursive: true });
|
|
89173
|
+
for (const lang of splitLanguageCodes(language)) await copyIfChanged(bundledTrainedDataPath(lang), path$9.join(targetDir, `${lang}.traineddata.gz`));
|
|
89174
|
+
return targetDir;
|
|
89175
|
+
}
|
|
89176
|
+
function bundledTrainedDataPath(language) {
|
|
89177
|
+
try {
|
|
89178
|
+
const packageUrl = import.meta.resolve(`@tesseract.js-data/${language}`);
|
|
89179
|
+
const packageDir = path$9.dirname(fileURLToPath(packageUrl));
|
|
89180
|
+
return path$9.join(packageDir, "4.0.0", `${language}.traineddata.gz`);
|
|
89181
|
+
} catch (error) {
|
|
89182
|
+
throw new ParseError$1(`Bundled OCR language data for "${language}" was not found. ${error instanceof Error ? error.message : String(error)}`, true);
|
|
89183
|
+
}
|
|
89184
|
+
}
|
|
89185
|
+
async function copyIfChanged(sourcePath, targetPath) {
|
|
89186
|
+
const [sourceStat, targetStat] = await Promise.all([fs$11.stat(sourcePath), fs$11.stat(targetPath).catch(() => void 0)]);
|
|
89187
|
+
if (targetStat?.size === sourceStat.size) return;
|
|
89188
|
+
await fs$11.copyFile(sourcePath, targetPath);
|
|
89189
|
+
}
|
|
89190
|
+
function normalizeLanguage(language) {
|
|
89191
|
+
return splitLanguageCodes(language).join("+");
|
|
89192
|
+
}
|
|
89193
|
+
function splitLanguageCodes(language) {
|
|
89194
|
+
const codes = language.split("+").map((lang) => lang.trim()).filter(Boolean);
|
|
89195
|
+
if (codes.length === 0) return ["eng"];
|
|
89196
|
+
return codes;
|
|
89197
|
+
}
|
|
89198
|
+
function extractLines(page) {
|
|
89199
|
+
const lines = [];
|
|
89200
|
+
for (const block of page.blocks ?? []) for (const paragraph of block.paragraphs) for (const line of paragraph.lines) {
|
|
89201
|
+
const words = line.words.map(wordToOcrWord);
|
|
89202
|
+
lines.push({
|
|
89203
|
+
text: line.text.trim(),
|
|
89204
|
+
bbox: bboxToRect(line.bbox),
|
|
89205
|
+
confidence: normalizeConfidence(line.confidence),
|
|
89206
|
+
words
|
|
89207
|
+
});
|
|
89208
|
+
}
|
|
89209
|
+
if (lines.length > 0) return lines.filter((line) => line.text.length > 0);
|
|
89210
|
+
return page.text.split(/\r?\n/g).map((text) => text.trim()).filter(Boolean).map((text) => ({
|
|
89211
|
+
text,
|
|
89212
|
+
bbox: {
|
|
89213
|
+
x: 0,
|
|
89214
|
+
y: 0,
|
|
89215
|
+
width: 0,
|
|
89216
|
+
height: 0
|
|
89217
|
+
},
|
|
89218
|
+
confidence: normalizeConfidence(page.confidence),
|
|
89219
|
+
words: []
|
|
89220
|
+
}));
|
|
89221
|
+
}
|
|
89222
|
+
function wordToOcrWord(word) {
|
|
89223
|
+
return {
|
|
89224
|
+
text: word.text,
|
|
89225
|
+
bbox: bboxToRect(word.bbox),
|
|
89226
|
+
confidence: normalizeConfidence(word.confidence)
|
|
89227
|
+
};
|
|
89228
|
+
}
|
|
89229
|
+
function bboxToRect(bbox) {
|
|
89230
|
+
return {
|
|
89231
|
+
x: bbox.x0,
|
|
89232
|
+
y: bbox.y0,
|
|
89233
|
+
width: Math.max(0, bbox.x1 - bbox.x0),
|
|
89234
|
+
height: Math.max(0, bbox.y1 - bbox.y0)
|
|
89235
|
+
};
|
|
89236
|
+
}
|
|
88920
89237
|
function normalizeConfidence(value) {
|
|
88921
89238
|
if (Number.isNaN(value) || value < 0) return 0;
|
|
88922
89239
|
return Math.max(0, Math.min(1, value / 100));
|
|
@@ -88928,6 +89245,42 @@ function maxBottom(lines) {
|
|
|
88928
89245
|
return Math.max(0, ...lines.map((line) => line.bbox.y + line.bbox.height));
|
|
88929
89246
|
}
|
|
88930
89247
|
//#endregion
|
|
89248
|
+
//#region ../../packages/document-intelligence/src/ocr/default-provider.ts
|
|
89249
|
+
function createDefaultOcrProvider(options = {}) {
|
|
89250
|
+
const requestedProvider = process.env["NEXUM_OCR_PROVIDER"];
|
|
89251
|
+
if (requestedProvider === "tesseract.js") return createTesseractJsOcrProvider(options);
|
|
89252
|
+
if (requestedProvider === "tesseract") return createTesseractOcrProvider(options);
|
|
89253
|
+
const nativeProvider = createTesseractOcrProvider(options);
|
|
89254
|
+
let jsProvider;
|
|
89255
|
+
return {
|
|
89256
|
+
name: "tesseract-auto",
|
|
89257
|
+
async recognize(filePath, ocrOptions = {}) {
|
|
89258
|
+
try {
|
|
89259
|
+
return await nativeProvider.recognize(filePath, ocrOptions);
|
|
89260
|
+
} catch (nativeError) {
|
|
89261
|
+
jsProvider ??= createTesseractJsOcrProvider(options);
|
|
89262
|
+
try {
|
|
89263
|
+
return {
|
|
89264
|
+
...await jsProvider.recognize(filePath, ocrOptions),
|
|
89265
|
+
provider: "tesseract.js"
|
|
89266
|
+
};
|
|
89267
|
+
} catch (jsError) {
|
|
89268
|
+
throw combineErrors(nativeError, jsError);
|
|
89269
|
+
}
|
|
89270
|
+
}
|
|
89271
|
+
}
|
|
89272
|
+
};
|
|
89273
|
+
}
|
|
89274
|
+
function combineErrors(nativeError, jsError) {
|
|
89275
|
+
const nativeMessage = nativeError instanceof Error ? nativeError.message : String(nativeError);
|
|
89276
|
+
const jsMessage = jsError instanceof Error ? jsError.message : String(jsError);
|
|
89277
|
+
return new ParseError$1([
|
|
89278
|
+
"OCR failed with both native Tesseract and bundled tesseract.js.",
|
|
89279
|
+
`Native Tesseract: ${nativeMessage}`,
|
|
89280
|
+
`Bundled tesseract.js: ${jsMessage}`
|
|
89281
|
+
].join("\n"), true);
|
|
89282
|
+
}
|
|
89283
|
+
//#endregion
|
|
88931
89284
|
//#region ../../packages/document-intelligence/src/validation/confidence.ts
|
|
88932
89285
|
const DEFAULT_CONFIDENCE_THRESHOLD = .7;
|
|
88933
89286
|
function isBelowThreshold(score, threshold = DEFAULT_CONFIDENCE_THRESHOLD) {
|
|
@@ -89447,7 +89800,7 @@ function extensionForFormat(format) {
|
|
|
89447
89800
|
}
|
|
89448
89801
|
//#endregion
|
|
89449
89802
|
//#region ../../packages/agent-core/src/tools/builtin/document/document-batch.md
|
|
89450
|
-
var document_batch_default = "Process local document files for office/department workflows.\n\nUse this tool when the user asks to read, summarize, inspect, review, extract, organize, inventory, consolidate, convert, or export information from one or more local documents, files, scans, PDFs, Word files, Excel files, CSV files, or images. Examples include \"read this Word document and tell me what it contains\", \"summarize these PDFs\", \"extract key fields from this folder of materials\", \"make an Excel inventory\", \"review these reports for issues\", or \"convert this document set to markdown\".\n\nDo not use this tool for code review, source-code editing, general filesystem inspection, or ordinary questions that merely mention a path. For code and text files, use Read, Grep, Glob, Edit, Write, and Bash as appropriate.\n\nInput path can be a single supported file or a directory. Directories are scanned recursively by default. The tool writes exports under the Nexum document jobs directory and returns the export paths plus a markdown processing summary. Choose markdown for readable summaries/reports, excel for inventories/tables/ledgers/Excel/xlsx requests, review-markdown for review workflows, csv for raw table extraction, and json for downstream machine processing.\n\nDo not use Bash, Python, Node.js, npm/pnpm/npx installs, `pdftotext`, `pdfinfo`, `unzip`, LibreOffice, or ad-hoc scripts to read, parse, extract, summarize, convert, inspect, review, consolidate, or export supported document formats. Use this tool
|
|
89803
|
+
var document_batch_default = "Process local document files for office/department workflows.\n\nUse this tool when the user asks to read, summarize, inspect, review, extract, organize, inventory, consolidate, convert, or export information from one or more local documents, files, scans, PDFs, Word files, Excel files, CSV files, or images. Examples include \"read this Word document and tell me what it contains\", \"summarize these PDFs\", \"extract key fields from this folder of materials\", \"make an Excel inventory\", \"review these reports for issues\", or \"convert this document set to markdown\".\n\nDo not use this tool for code review, source-code editing, general filesystem inspection, or ordinary questions that merely mention a path. For code and text files, use Read, Grep, Glob, Edit, Write, and Bash as appropriate.\n\nInput path can be a single supported file or a directory. Directories are scanned recursively by default. The tool writes exports under the Nexum document jobs directory and returns the export paths plus a markdown processing summary. Choose markdown for readable summaries/reports, excel for inventories/tables/ledgers/Excel/xlsx requests, review-markdown for review workflows, csv for raw table extraction, and json for downstream machine processing.\n\nDo not use Bash, Python, Node.js, npm/pnpm/npx installs, `pdftotext`, `pdfinfo`, `unzip`, LibreOffice, or ad-hoc scripts to read, parse, extract, summarize, convert, inspect, review, consolidate, or export supported document formats. Use this tool for document work involving local PDFs, Word files, Excel files, CSV files, or scanned/image documents. If this tool fails or extracts no text, report that document-tool failure and do not switch to shell/package-manager probing unless the user explicitly asks for a custom script/toolchain implementation.\n\nWhen the user asks for a ledger, inventory, table, Excel workbook, or xlsx output, call this tool with `purpose: \"inventory\"` and `format: \"excel\"`.\n\nAccuracy contract: do not claim perfect extraction. Text-native PDFs, Word files, Excel files, and CSV files are generally more reliable than scanned images. OCR, photos, low-quality scans, unusual layouts, and cross-page tables can be wrong. Treat `needs_review`, validation issues, failed files, and OCR/scanned inputs as requiring human review. If the user asks for guaranteed accuracy, explain that the tool provides traceable outputs and review flags rather than a 100% guarantee.\n\nSupported file types: PDF, DOCX, DOC, XLSX, XLS, CSV, PNG, JPG/JPEG, GIF, WEBP, TIF/TIFF.\n";
|
|
89451
89804
|
//#endregion
|
|
89452
89805
|
//#region ../../packages/agent-core/src/tools/builtin/document/document-batch.ts
|
|
89453
89806
|
const SUPPORTED_EXTENSIONS$2 = new Set([
|
|
@@ -89535,7 +89888,7 @@ var DocumentProcessTool = class {
|
|
|
89535
89888
|
const outputDir = path$9.join(this.outputRoot, "document-process");
|
|
89536
89889
|
const service = new DocumentIntelligenceService({
|
|
89537
89890
|
outputDir,
|
|
89538
|
-
ocrProvider:
|
|
89891
|
+
ocrProvider: createDefaultOcrProvider(),
|
|
89539
89892
|
pdfPageRenderer: createPdfjsPageRenderer(),
|
|
89540
89893
|
usePdfOcrFallback: true
|
|
89541
89894
|
});
|
|
@@ -89610,6 +89963,11 @@ async function processOne(service, filePath, format) {
|
|
|
89610
89963
|
job: finalJob,
|
|
89611
89964
|
error: "Document job produced no exportable result."
|
|
89612
89965
|
};
|
|
89966
|
+
if (countTextBlocks$1(finalJob.result) === 0) return {
|
|
89967
|
+
filePath,
|
|
89968
|
+
job: finalJob,
|
|
89969
|
+
error: "Document processing completed but no text blocks were extracted; OCR may have found no readable text."
|
|
89970
|
+
};
|
|
89613
89971
|
return {
|
|
89614
89972
|
filePath,
|
|
89615
89973
|
job: finalJob,
|
|
@@ -89705,6 +90063,9 @@ function buildResultTable(results, sourcePath) {
|
|
|
89705
90063
|
function isCompleted(result) {
|
|
89706
90064
|
return !result.error && (result.job.state === "completed" || result.job.state === "needs_review");
|
|
89707
90065
|
}
|
|
90066
|
+
function countTextBlocks$1(result) {
|
|
90067
|
+
return result.pages.reduce((sum, page) => sum + page.blocks.filter((block) => block.text.trim().length > 0).length, 0);
|
|
90068
|
+
}
|
|
89708
90069
|
function timestampForFileName$1() {
|
|
89709
90070
|
return (/* @__PURE__ */ new Date()).toISOString().replaceAll(/[:.]/g, "-");
|
|
89710
90071
|
}
|
|
@@ -89822,7 +90183,7 @@ var ToolResultBuilder = class {
|
|
|
89822
90183
|
};
|
|
89823
90184
|
//#endregion
|
|
89824
90185
|
//#region ../../packages/agent-core/src/tools/builtin/document/document-read.md
|
|
89825
|
-
var document_read_default = "Read one local document file and return extracted content.\n\nUse this tool when the user asks what a local PDF, Word, Excel, CSV, scanned image, or other supported document contains; asks to read, summarize, inspect, review, convert, or extract information from a specific document file; or provides a concrete document path and asks about its content.\n\nDo not use Bash, Python, Node.js, npm/pnpm/npx installs, `pdftotext`, `pdfinfo`, `unzip`, LibreOffice, or ad-hoc scripts to read, parse, extract, summarize, convert, inspect, or review supported document formats. Use this tool
|
|
90186
|
+
var document_read_default = "Read one local document file and return extracted content.\n\nUse this tool when the user asks what a local PDF, Word, Excel, CSV, scanned image, or other supported document contains; asks to read, summarize, inspect, review, convert, or extract information from a specific document file; or provides a concrete document path and asks about its content.\n\nDo not use Bash, Python, Node.js, npm/pnpm/npx installs, `pdftotext`, `pdfinfo`, `unzip`, LibreOffice, or ad-hoc scripts to read, parse, extract, summarize, convert, inspect, or review supported document formats. Use this tool for a single `.docx`, `.pdf`, `.xlsx`, `.xls`, `.csv`, or common image document. If this tool fails or extracts no text, report that document-tool failure and do not switch to shell/package-manager probing unless the user explicitly asks for a custom script/toolchain implementation.\n\nDo not use this tool for source code files, plain UTF-8 text, logs, JSON, Markdown, or configuration files; use Read, Grep, Glob, Edit, Write, and Bash for those.\n\nAccuracy contract: do not claim perfect extraction. Text-native documents are generally more reliable than scanned images and OCR. OCR, photos, low-quality scans, unusual layouts, and cross-page tables can be wrong. Treat validation issues, failed files, and OCR/scanned inputs as requiring human review. If the user asks for guaranteed accuracy, explain that the tool provides traceable extracted content and review flags rather than a 100% guarantee.\n\nSupported file types: PDF, DOCX, DOC, XLSX, XLS, CSV, PNG, JPG/JPEG, GIF, WEBP, TIF/TIFF.\n";
|
|
89826
90187
|
//#endregion
|
|
89827
90188
|
//#region ../../packages/agent-core/src/tools/builtin/document/document-read.ts
|
|
89828
90189
|
const SUPPORTED_EXTENSIONS$1 = new Set([
|
|
@@ -89895,7 +90256,7 @@ var DocumentReadTool = class {
|
|
|
89895
90256
|
};
|
|
89896
90257
|
const service = new DocumentIntelligenceService({
|
|
89897
90258
|
outputDir: path$9.join(this.outputRoot, "document-read"),
|
|
89898
|
-
ocrProvider:
|
|
90259
|
+
ocrProvider: createDefaultOcrProvider(),
|
|
89899
90260
|
pdfPageRenderer: createPdfjsPageRenderer(),
|
|
89900
90261
|
usePdfOcrFallback: true
|
|
89901
90262
|
});
|
|
@@ -89916,6 +90277,14 @@ var DocumentReadTool = class {
|
|
|
89916
90277
|
isError: true,
|
|
89917
90278
|
output: "Document job produced no result."
|
|
89918
90279
|
};
|
|
90280
|
+
if (countTextBlocks(finalJob.result) === 0) return {
|
|
90281
|
+
isError: true,
|
|
90282
|
+
output: [
|
|
90283
|
+
"Document processing completed but no text blocks were extracted.",
|
|
90284
|
+
"OCR is enabled for images and scanned PDFs; if this is a blank or low-quality scan, review the source file manually.",
|
|
90285
|
+
`Source: ${safePath}`
|
|
90286
|
+
].join("\n")
|
|
90287
|
+
};
|
|
89919
90288
|
const exported = await service.exportJob(finalJob.id, "markdown");
|
|
89920
90289
|
const markdown = documentToMarkdown(finalJob.result);
|
|
89921
90290
|
const builder = new ToolResultBuilder({
|
|
@@ -89943,6 +90312,9 @@ var DocumentReadTool = class {
|
|
|
89943
90312
|
}
|
|
89944
90313
|
}
|
|
89945
90314
|
};
|
|
90315
|
+
function countTextBlocks(result) {
|
|
90316
|
+
return result.pages.reduce((sum, page) => sum + page.blocks.filter((block) => block.text.trim().length > 0).length, 0);
|
|
90317
|
+
}
|
|
89946
90318
|
async function waitForJob$1(service, jobId, timeoutMs = 12e4) {
|
|
89947
90319
|
const deadline = Date.now() + timeoutMs;
|
|
89948
90320
|
while (Date.now() < deadline) {
|
|
@@ -90166,6 +90538,31 @@ var GoalMode = class {
|
|
|
90166
90538
|
restoreClear(_record) {
|
|
90167
90539
|
this.state = void 0;
|
|
90168
90540
|
}
|
|
90541
|
+
restoreNote(record) {
|
|
90542
|
+
const state = this.state;
|
|
90543
|
+
if (state === void 0 || state.goalId !== record.goalId) return;
|
|
90544
|
+
state.notes.push({
|
|
90545
|
+
content: record.content,
|
|
90546
|
+
time: record.time
|
|
90547
|
+
});
|
|
90548
|
+
if (state.notes.length > MAX_GOAL_NOTES) state.notes = state.notes.slice(-10);
|
|
90549
|
+
}
|
|
90550
|
+
/**
|
|
90551
|
+
* Checkpoint elapsed wall-clock time into the durable goal state.
|
|
90552
|
+
*
|
|
90553
|
+
* Called at step/turn boundaries so the wall-clock budget reflects time
|
|
90554
|
+
* spent waiting for subagents and background tasks, not just state
|
|
90555
|
+
* transitions. The elapsed slice is persisted silently (no UI event) to
|
|
90556
|
+
* avoid record churn, and `wallClockResumedAt` is reset so the next slice
|
|
90557
|
+
* starts from now.
|
|
90558
|
+
*/
|
|
90559
|
+
checkpointWallClock() {
|
|
90560
|
+
const state = this.state;
|
|
90561
|
+
if (state === void 0 || state.status !== "active" || state.wallClockResumedAt === void 0) return;
|
|
90562
|
+
const now = Date.now();
|
|
90563
|
+
state.wallClockMs += Math.max(0, now - state.wallClockResumedAt);
|
|
90564
|
+
state.wallClockResumedAt = now;
|
|
90565
|
+
}
|
|
90169
90566
|
getGoal() {
|
|
90170
90567
|
const state = this.state;
|
|
90171
90568
|
return { goal: state === void 0 ? null : this.toSnapshot(state) };
|
|
@@ -90307,16 +90704,24 @@ var GoalMode = class {
|
|
|
90307
90704
|
const state = this.state;
|
|
90308
90705
|
if (state === void 0 || state.status !== "active") return null;
|
|
90309
90706
|
state.tokensUsed += Math.max(0, tokenDelta);
|
|
90707
|
+
this.checkpointWallClock();
|
|
90310
90708
|
this.persistState(state, { silent: true });
|
|
90311
|
-
this.appendGoalUpdate({
|
|
90709
|
+
this.appendGoalUpdate({
|
|
90710
|
+
tokensUsed: state.tokensUsed,
|
|
90711
|
+
wallClockMs: liveWallClockMs(state, Date.now())
|
|
90712
|
+
});
|
|
90312
90713
|
return this.toSnapshot(state);
|
|
90313
90714
|
}
|
|
90314
90715
|
async incrementTurn() {
|
|
90315
90716
|
const state = this.state;
|
|
90316
90717
|
if (state === void 0 || state.status !== "active") return null;
|
|
90317
90718
|
state.turnsUsed += 1;
|
|
90719
|
+
this.checkpointWallClock();
|
|
90318
90720
|
this.persistState(state);
|
|
90319
|
-
this.appendGoalUpdate({
|
|
90721
|
+
this.appendGoalUpdate({
|
|
90722
|
+
turnsUsed: state.turnsUsed,
|
|
90723
|
+
wallClockMs: liveWallClockMs(state, Date.now())
|
|
90724
|
+
});
|
|
90320
90725
|
return this.toSnapshot(state);
|
|
90321
90726
|
}
|
|
90322
90727
|
async addNote(content) {
|
|
@@ -90324,12 +90729,19 @@ var GoalMode = class {
|
|
|
90324
90729
|
if (state === void 0 || state.status !== "active") return null;
|
|
90325
90730
|
const trimmed = content.trim().slice(0, MAX_NOTE_LENGTH);
|
|
90326
90731
|
if (trimmed.length === 0) return this.toSnapshot(state);
|
|
90327
|
-
|
|
90732
|
+
const note = {
|
|
90328
90733
|
content: trimmed,
|
|
90329
90734
|
time: Date.now()
|
|
90330
|
-
}
|
|
90735
|
+
};
|
|
90736
|
+
state.notes.push(note);
|
|
90331
90737
|
if (state.notes.length > MAX_GOAL_NOTES) state.notes = state.notes.slice(-10);
|
|
90332
90738
|
this.persistState(state, { silent: true });
|
|
90739
|
+
this.agent.records.logRecord({
|
|
90740
|
+
type: "goal.note",
|
|
90741
|
+
goalId: state.goalId,
|
|
90742
|
+
content: note.content,
|
|
90743
|
+
time: note.time
|
|
90744
|
+
});
|
|
90333
90745
|
return this.toSnapshot(state);
|
|
90334
90746
|
}
|
|
90335
90747
|
clearInternal(actor, opts = {}) {
|
|
@@ -90655,7 +91067,7 @@ function rankMemos(memos, query, options = {}) {
|
|
|
90655
91067
|
const intent = detectQueryIntent(query);
|
|
90656
91068
|
const hasVectorScores = vectorScores !== void 0 && vectorScores.size > 0;
|
|
90657
91069
|
return memos.map((memo) => {
|
|
90658
|
-
const keywordScore = computeRelevanceScore(memo, query, 0, currentProjectDir, projectTagCloud, intent);
|
|
91070
|
+
const keywordScore = computeRelevanceScore(memo, query, memo.usageCount ?? 0, currentProjectDir, projectTagCloud, intent);
|
|
90659
91071
|
const vectorScore = vectorScores?.get(memo.id) ?? 0;
|
|
90660
91072
|
return {
|
|
90661
91073
|
memo,
|
|
@@ -90875,6 +91287,7 @@ function generateId() {
|
|
|
90875
91287
|
return `memo-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
90876
91288
|
}
|
|
90877
91289
|
function createMemoryMemo(partial) {
|
|
91290
|
+
const projectDir = partial.projectDir ?? "";
|
|
90878
91291
|
return {
|
|
90879
91292
|
id: partial.id ?? generateId(),
|
|
90880
91293
|
sourceSessionId: partial.sourceSessionId,
|
|
@@ -90886,10 +91299,35 @@ function createMemoryMemo(partial) {
|
|
|
90886
91299
|
whatWorked: partial.whatWorked,
|
|
90887
91300
|
extractionSource: partial.extractionSource,
|
|
90888
91301
|
recordedAt: partial.recordedAt ?? Date.now(),
|
|
90889
|
-
|
|
90890
|
-
|
|
91302
|
+
sourceFingerprint: partial.sourceFingerprint ?? computeMemoFingerprint({
|
|
91303
|
+
sourceSessionId: partial.sourceSessionId,
|
|
91304
|
+
projectDir,
|
|
91305
|
+
userNeed: partial.userNeed,
|
|
91306
|
+
approach: partial.approach,
|
|
91307
|
+
outcome: partial.outcome
|
|
91308
|
+
}),
|
|
91309
|
+
usageCount: partial.usageCount ?? 0,
|
|
91310
|
+
projectDir,
|
|
91311
|
+
tags: normalizedTags(partial.tags),
|
|
91312
|
+
intent: partial.intent ?? void 0
|
|
90891
91313
|
};
|
|
90892
91314
|
}
|
|
91315
|
+
function computeMemoFingerprint(memo) {
|
|
91316
|
+
const text = [
|
|
91317
|
+
memo.sourceSessionId,
|
|
91318
|
+
memo.projectDir,
|
|
91319
|
+
memo.userNeed,
|
|
91320
|
+
memo.approach,
|
|
91321
|
+
memo.outcome
|
|
91322
|
+
].join("\0");
|
|
91323
|
+
let hash = 0;
|
|
91324
|
+
for (let i = 0; i < text.length; i++) {
|
|
91325
|
+
const char = text.charCodeAt(i);
|
|
91326
|
+
hash = (hash << 5) - hash + char;
|
|
91327
|
+
hash |= 0;
|
|
91328
|
+
}
|
|
91329
|
+
return `fp-${Math.abs(hash).toString(36)}`;
|
|
91330
|
+
}
|
|
90893
91331
|
function normalizedTags(value) {
|
|
90894
91332
|
const tags = normalizeTags(value);
|
|
90895
91333
|
return tags.length > 0 ? tags : void 0;
|
|
@@ -90905,9 +91343,12 @@ function toSummary(memo) {
|
|
|
90905
91343
|
whatFailed: memo.whatFailed,
|
|
90906
91344
|
whatWorked: memo.whatWorked,
|
|
90907
91345
|
extractionSource: memo.extractionSource,
|
|
91346
|
+
sourceFingerprint: memo.sourceFingerprint,
|
|
91347
|
+
usageCount: memo.usageCount,
|
|
90908
91348
|
recordedAt: memo.recordedAt,
|
|
90909
91349
|
projectDir: memo.projectDir,
|
|
90910
|
-
tags: memo.tags
|
|
91350
|
+
tags: memo.tags,
|
|
91351
|
+
intent: memo.intent
|
|
90911
91352
|
};
|
|
90912
91353
|
}
|
|
90913
91354
|
//#endregion
|
|
@@ -90969,7 +91410,7 @@ function createFastEmbedEngine() {
|
|
|
90969
91410
|
}
|
|
90970
91411
|
async function loadEmbedder() {
|
|
90971
91412
|
try {
|
|
90972
|
-
const { FlagEmbedding, EmbeddingModel } = await import("./esm-
|
|
91413
|
+
const { FlagEmbedding, EmbeddingModel } = await import("./esm-PKa8Krwc.mjs");
|
|
90973
91414
|
return await FlagEmbedding.init({ model: EmbeddingModel.BGESmallZH });
|
|
90974
91415
|
} catch {
|
|
90975
91416
|
return null;
|
|
@@ -91048,14 +91489,33 @@ var MemoryMemoStore = class MemoryMemoStore {
|
|
|
91048
91489
|
await this.init();
|
|
91049
91490
|
if (this.db === void 0) return;
|
|
91050
91491
|
const projectDir = options?.projectDir;
|
|
91051
|
-
const
|
|
91052
|
-
const
|
|
91492
|
+
const intent = options?.intent;
|
|
91493
|
+
const conditions = [];
|
|
91494
|
+
const params = [];
|
|
91495
|
+
if (projectDir !== void 0) {
|
|
91496
|
+
conditions.push("project_dir = ? OR project_dir = ''");
|
|
91497
|
+
params.push(projectDir);
|
|
91498
|
+
}
|
|
91499
|
+
if (intent !== void 0) {
|
|
91500
|
+
conditions.push("intent = ?");
|
|
91501
|
+
params.push(intent);
|
|
91502
|
+
}
|
|
91503
|
+
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
91504
|
+
const rows = this.db.prepare(`SELECT * FROM memos ${where} ORDER BY recorded_at DESC`).all(...params);
|
|
91053
91505
|
for (const row of rows) yield rowToMemo(row);
|
|
91054
91506
|
}
|
|
91055
91507
|
/** Append a memo. */
|
|
91056
91508
|
async append(entry) {
|
|
91057
91509
|
return this.withWriteLock(() => this.appendInternal(entry));
|
|
91058
91510
|
}
|
|
91511
|
+
/** Increment the usage counter for a memo. */
|
|
91512
|
+
async incrementUsage(id) {
|
|
91513
|
+
return this.withWriteLock(async () => {
|
|
91514
|
+
await this.init();
|
|
91515
|
+
if (this.db === void 0) return;
|
|
91516
|
+
this.db.prepare("UPDATE memos SET usage_count = usage_count + 1 WHERE id = ?").run(id);
|
|
91517
|
+
});
|
|
91518
|
+
}
|
|
91059
91519
|
/** Delete a memo by id. */
|
|
91060
91520
|
async delete(id) {
|
|
91061
91521
|
return this.withWriteLock(() => this.deleteInternal(id));
|
|
@@ -91081,14 +91541,24 @@ var MemoryMemoStore = class MemoryMemoStore {
|
|
|
91081
91541
|
if (ftsQuery === void 0) return [];
|
|
91082
91542
|
const limit = options?.candidateLimit ?? 200;
|
|
91083
91543
|
const projectDir = options?.projectDir;
|
|
91084
|
-
const
|
|
91085
|
-
|
|
91086
|
-
|
|
91087
|
-
|
|
91544
|
+
const intent = options?.intent;
|
|
91545
|
+
const conditions = ["f.memos_fts MATCH ?"];
|
|
91546
|
+
const params = [ftsQuery];
|
|
91547
|
+
if (projectDir !== void 0) {
|
|
91548
|
+
conditions.push("(m.project_dir = ? OR m.project_dir = '')");
|
|
91549
|
+
params.push(projectDir);
|
|
91550
|
+
}
|
|
91551
|
+
if (intent !== void 0) {
|
|
91552
|
+
conditions.push("m.intent = ?");
|
|
91553
|
+
params.push(intent);
|
|
91554
|
+
}
|
|
91555
|
+
const sql = `SELECT m.* FROM memos m
|
|
91088
91556
|
JOIN memos_fts f ON m.rowid = f.rowid
|
|
91089
|
-
WHERE
|
|
91090
|
-
ORDER BY m.recorded_at DESC LIMIT
|
|
91091
|
-
|
|
91557
|
+
WHERE ${conditions.join(" AND ")}
|
|
91558
|
+
ORDER BY m.recorded_at DESC LIMIT ?`;
|
|
91559
|
+
const stmt = this.db.prepare(sql);
|
|
91560
|
+
params.push(limit);
|
|
91561
|
+
return stmt.all(...params).map(rowToMemo);
|
|
91092
91562
|
}
|
|
91093
91563
|
/** List memos with optional full-text search and pagination. */
|
|
91094
91564
|
async list(options) {
|
|
@@ -91101,9 +91571,16 @@ var MemoryMemoStore = class MemoryMemoStore {
|
|
|
91101
91571
|
const limit = options?.limit ?? 50;
|
|
91102
91572
|
const offset = options?.offset ?? 0;
|
|
91103
91573
|
const projectDir = options?.projectDir;
|
|
91574
|
+
const intent = options?.intent;
|
|
91104
91575
|
if (search !== void 0 && search.length > 0) {
|
|
91105
|
-
let candidates = await this.search(search, {
|
|
91106
|
-
|
|
91576
|
+
let candidates = await this.search(search, {
|
|
91577
|
+
projectDir,
|
|
91578
|
+
intent
|
|
91579
|
+
});
|
|
91580
|
+
if (candidates.length === 0) for await (const memo of this.read({
|
|
91581
|
+
projectDir,
|
|
91582
|
+
intent
|
|
91583
|
+
})) candidates.push(memo);
|
|
91107
91584
|
const filtered = candidates.filter((memo) => memoMatchesSearch(memo, search));
|
|
91108
91585
|
const total = filtered.length;
|
|
91109
91586
|
return {
|
|
@@ -91111,7 +91588,7 @@ var MemoryMemoStore = class MemoryMemoStore {
|
|
|
91111
91588
|
total
|
|
91112
91589
|
};
|
|
91113
91590
|
}
|
|
91114
|
-
const { rows, total } = this.listAll(limit, offset, projectDir);
|
|
91591
|
+
const { rows, total } = this.listAll(limit, offset, projectDir, intent);
|
|
91115
91592
|
return {
|
|
91116
91593
|
memos: rows.map(toSummary),
|
|
91117
91594
|
total
|
|
@@ -91226,11 +91703,16 @@ var MemoryMemoStore = class MemoryMemoStore {
|
|
|
91226
91703
|
what_worked TEXT NOT NULL DEFAULT 'none',
|
|
91227
91704
|
extraction_source TEXT NOT NULL CHECK(extraction_source IN ('compaction', 'exit', 'manual')),
|
|
91228
91705
|
recorded_at INTEGER NOT NULL,
|
|
91706
|
+
source_fingerprint TEXT,
|
|
91707
|
+
usage_count INTEGER NOT NULL DEFAULT 0,
|
|
91229
91708
|
project_dir TEXT NOT NULL DEFAULT '',
|
|
91230
|
-
tags TEXT NOT NULL DEFAULT '[]'
|
|
91709
|
+
tags TEXT NOT NULL DEFAULT '[]',
|
|
91710
|
+
intent TEXT
|
|
91231
91711
|
);
|
|
91232
91712
|
|
|
91233
91713
|
CREATE INDEX IF NOT EXISTS idx_memos_project_dir ON memos(project_dir);
|
|
91714
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_memos_source_fingerprint
|
|
91715
|
+
ON memos(source_fingerprint) WHERE source_fingerprint IS NOT NULL;
|
|
91234
91716
|
|
|
91235
91717
|
CREATE VIRTUAL TABLE IF NOT EXISTS memos_fts USING fts5(
|
|
91236
91718
|
user_need,
|
|
@@ -91257,8 +91739,13 @@ var MemoryMemoStore = class MemoryMemoStore {
|
|
|
91257
91739
|
const info = this.db.prepare("PRAGMA table_info(memos)").all();
|
|
91258
91740
|
if (!info.some((col) => col.name === "project_dir")) this.db.exec("ALTER TABLE memos ADD COLUMN project_dir TEXT NOT NULL DEFAULT ''");
|
|
91259
91741
|
if (!info.some((col) => col.name === "tags")) this.db.exec("ALTER TABLE memos ADD COLUMN tags TEXT NOT NULL DEFAULT '[]'");
|
|
91742
|
+
if (!info.some((col) => col.name === "source_fingerprint")) this.db.exec("ALTER TABLE memos ADD COLUMN source_fingerprint TEXT");
|
|
91743
|
+
if (!info.some((col) => col.name === "usage_count")) this.db.exec("ALTER TABLE memos ADD COLUMN usage_count INTEGER NOT NULL DEFAULT 0");
|
|
91744
|
+
if (!info.some((col) => col.name === "intent")) this.db.exec("ALTER TABLE memos ADD COLUMN intent TEXT");
|
|
91260
91745
|
this.db.exec(`
|
|
91261
91746
|
CREATE INDEX IF NOT EXISTS idx_memos_project_dir ON memos(project_dir);
|
|
91747
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_memos_source_fingerprint
|
|
91748
|
+
ON memos(source_fingerprint) WHERE source_fingerprint IS NOT NULL;
|
|
91262
91749
|
CREATE INDEX IF NOT EXISTS idx_memory_embeddings_created_at ON memory_embeddings(created_at DESC);
|
|
91263
91750
|
`);
|
|
91264
91751
|
}
|
|
@@ -91300,15 +91787,15 @@ var MemoryMemoStore = class MemoryMemoStore {
|
|
|
91300
91787
|
if (this.db === void 0 || memos.length === 0) return;
|
|
91301
91788
|
const insert = this.db.prepare(`INSERT OR IGNORE INTO memos (
|
|
91302
91789
|
id, source_session_id, source_session_title, user_need, approach,
|
|
91303
|
-
outcome, what_failed, what_worked, extraction_source, recorded_at, project_dir, tags
|
|
91304
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
91790
|
+
outcome, what_failed, what_worked, extraction_source, recorded_at, project_dir, tags, intent
|
|
91791
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
91305
91792
|
RETURNING rowid`);
|
|
91306
91793
|
const insertFts = this.db.prepare(`INSERT INTO memos_fts(rowid, user_need, approach, what_failed, what_worked, source_session_title)
|
|
91307
91794
|
VALUES (?, ?, ?, ?, ?, ?)`);
|
|
91308
91795
|
this.db.exec("BEGIN TRANSACTION");
|
|
91309
91796
|
try {
|
|
91310
91797
|
for (const memo of memos) {
|
|
91311
|
-
const row = insert.get(memo.id, memo.sourceSessionId, memo.sourceSessionTitle ?? null, memo.userNeed, memo.approach, memo.outcome, memo.whatFailed, memo.whatWorked, memo.extractionSource, memo.recordedAt, memo.projectDir ?? "", JSON.stringify(memo.tags ?? []));
|
|
91798
|
+
const row = insert.get(memo.id, memo.sourceSessionId, memo.sourceSessionTitle ?? null, memo.userNeed, memo.approach, memo.outcome, memo.whatFailed, memo.whatWorked, memo.extractionSource, memo.recordedAt, memo.projectDir ?? "", JSON.stringify(memo.tags ?? []), memo.intent ?? null);
|
|
91312
91799
|
insertFts.run(row.rowid, toFtsText(memo.userNeed), toFtsText(memo.approach), toFtsText(memo.whatFailed), toFtsText(memo.whatWorked), toFtsText(memo.sourceSessionTitle ?? ""));
|
|
91313
91800
|
}
|
|
91314
91801
|
this.db.exec("COMMIT");
|
|
@@ -91320,22 +91807,31 @@ var MemoryMemoStore = class MemoryMemoStore {
|
|
|
91320
91807
|
async appendInternal(entry) {
|
|
91321
91808
|
await this.init();
|
|
91322
91809
|
if (this.db === void 0) return;
|
|
91810
|
+
const fingerprint = entry.sourceFingerprint;
|
|
91811
|
+
if (fingerprint !== void 0) {
|
|
91812
|
+
const existing = this.db.prepare("SELECT id, rowid FROM memos WHERE source_fingerprint = ?").get(fingerprint);
|
|
91813
|
+
if (existing !== void 0) {
|
|
91814
|
+
const merged = this.mergeMemoFields(existing.id, entry);
|
|
91815
|
+
await this.updateInternal(existing.id, merged);
|
|
91816
|
+
return;
|
|
91817
|
+
}
|
|
91818
|
+
}
|
|
91323
91819
|
const insert = this.db.prepare(`INSERT INTO memos (
|
|
91324
91820
|
id, source_session_id, source_session_title, user_need, approach,
|
|
91325
|
-
outcome, what_failed, what_worked, extraction_source, recorded_at, project_dir, tags
|
|
91326
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
91821
|
+
outcome, what_failed, what_worked, extraction_source, recorded_at, source_fingerprint, usage_count, project_dir, tags, intent
|
|
91822
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
91327
91823
|
RETURNING rowid`);
|
|
91328
91824
|
const insertFts = this.db.prepare(`INSERT INTO memos_fts(rowid, user_need, approach, what_failed, what_worked, source_session_title)
|
|
91329
91825
|
VALUES (?, ?, ?, ?, ?, ?)`);
|
|
91330
91826
|
this.db.exec("BEGIN TRANSACTION");
|
|
91331
91827
|
try {
|
|
91332
|
-
const row = insert.get(entry.id, entry.sourceSessionId, entry.sourceSessionTitle ?? null, entry.userNeed, entry.approach, entry.outcome, entry.whatFailed, entry.whatWorked, entry.extractionSource, entry.recordedAt, entry.projectDir ?? "", JSON.stringify(entry.tags ?? []));
|
|
91828
|
+
const row = insert.get(entry.id, entry.sourceSessionId, entry.sourceSessionTitle ?? null, entry.userNeed, entry.approach, entry.outcome, entry.whatFailed, entry.whatWorked, entry.extractionSource, entry.recordedAt, fingerprint ?? null, entry.usageCount ?? 0, entry.projectDir ?? "", JSON.stringify(entry.tags ?? []), entry.intent ?? null);
|
|
91333
91829
|
insertFts.run(row.rowid, toFtsText(entry.userNeed), toFtsText(entry.approach), toFtsText(entry.whatFailed), toFtsText(entry.whatWorked), toFtsText(entry.sourceSessionTitle ?? ""));
|
|
91334
91830
|
this.db.exec("COMMIT");
|
|
91335
91831
|
this.scheduleEmbedding(entry);
|
|
91336
|
-
} catch {
|
|
91832
|
+
} catch (error) {
|
|
91337
91833
|
this.db.exec("ROLLBACK");
|
|
91338
|
-
throw new Error(
|
|
91834
|
+
throw new Error(`Failed to append memo: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
91339
91835
|
}
|
|
91340
91836
|
}
|
|
91341
91837
|
/** Update a memo by id. Returns true if the memo existed and was updated. */
|
|
@@ -91343,6 +91839,25 @@ var MemoryMemoStore = class MemoryMemoStore {
|
|
|
91343
91839
|
return this.withWriteLock(() => this.updateInternal(id, patch));
|
|
91344
91840
|
}
|
|
91345
91841
|
/** @internal */
|
|
91842
|
+
mergeMemoFields(id, incoming) {
|
|
91843
|
+
const existing = this.db?.prepare("SELECT * FROM memos WHERE id = ?").get(id);
|
|
91844
|
+
if (existing === void 0) return incoming;
|
|
91845
|
+
const existingMemo = rowToMemo(existing);
|
|
91846
|
+
const mergedApproach = mergeText(existingMemo.approach, incoming.approach);
|
|
91847
|
+
const mergedWhatWorked = mergeText(existingMemo.whatWorked, incoming.whatWorked);
|
|
91848
|
+
const mergedWhatFailed = mergeText(existingMemo.whatFailed, incoming.whatFailed);
|
|
91849
|
+
const mergedTags = [...new Set([...existingMemo.tags ?? [], ...incoming.tags ?? []])];
|
|
91850
|
+
return {
|
|
91851
|
+
...incoming,
|
|
91852
|
+
approach: mergedApproach,
|
|
91853
|
+
whatWorked: mergedWhatWorked,
|
|
91854
|
+
whatFailed: mergedWhatFailed,
|
|
91855
|
+
tags: mergedTags,
|
|
91856
|
+
recordedAt: Math.max(existingMemo.recordedAt, incoming.recordedAt),
|
|
91857
|
+
usageCount: Math.max(existingMemo.usageCount ?? 0, incoming.usageCount ?? 0)
|
|
91858
|
+
};
|
|
91859
|
+
}
|
|
91860
|
+
/** @internal */
|
|
91346
91861
|
async updateInternal(id, patch) {
|
|
91347
91862
|
await this.init();
|
|
91348
91863
|
if (this.db === void 0) return false;
|
|
@@ -91364,8 +91879,11 @@ var MemoryMemoStore = class MemoryMemoStore {
|
|
|
91364
91879
|
what_worked = ?,
|
|
91365
91880
|
extraction_source = ?,
|
|
91366
91881
|
recorded_at = ?,
|
|
91882
|
+
source_fingerprint = ?,
|
|
91883
|
+
usage_count = ?,
|
|
91367
91884
|
project_dir = ?,
|
|
91368
|
-
tags =
|
|
91885
|
+
tags = ?,
|
|
91886
|
+
intent = ?
|
|
91369
91887
|
WHERE id = ?
|
|
91370
91888
|
RETURNING rowid`);
|
|
91371
91889
|
const updateFts = this.db.prepare(`INSERT INTO memos_fts(rowid, user_need, approach, what_failed, what_worked, source_session_title)
|
|
@@ -91378,7 +91896,7 @@ var MemoryMemoStore = class MemoryMemoStore {
|
|
|
91378
91896
|
this.db.exec("ROLLBACK");
|
|
91379
91897
|
return false;
|
|
91380
91898
|
}
|
|
91381
|
-
const row = update.get(updated.sourceSessionId, updated.sourceSessionTitle ?? null, updated.userNeed, updated.approach, updated.outcome, updated.whatFailed, updated.whatWorked, updated.extractionSource, updated.recordedAt, updated.projectDir ?? "", JSON.stringify(updated.tags ?? []), id);
|
|
91899
|
+
const row = update.get(updated.sourceSessionId, updated.sourceSessionTitle ?? null, updated.userNeed, updated.approach, updated.outcome, updated.whatFailed, updated.whatWorked, updated.extractionSource, updated.recordedAt, updated.sourceFingerprint ?? null, updated.usageCount ?? 0, updated.projectDir ?? "", JSON.stringify(updated.tags ?? []), updated.intent ?? null, id);
|
|
91382
91900
|
if (row === void 0) {
|
|
91383
91901
|
this.db.exec("ROLLBACK");
|
|
91384
91902
|
return false;
|
|
@@ -91442,31 +91960,32 @@ var MemoryMemoStore = class MemoryMemoStore {
|
|
|
91442
91960
|
if (this.db === void 0) return [];
|
|
91443
91961
|
const limit = options?.candidateLimit ?? 200;
|
|
91444
91962
|
const projectDir = options?.projectDir;
|
|
91963
|
+
const intent = options?.intent;
|
|
91445
91964
|
const recencyCutoffDays = options?.recencyCutoffDays;
|
|
91446
91965
|
const cutoffMs = recencyCutoffDays !== void 0 && recencyCutoffDays > 0 ? Date.now() - recencyCutoffDays * 24 * 60 * 60 * 1e3 : void 0;
|
|
91447
|
-
|
|
91966
|
+
const conditions = [];
|
|
91967
|
+
const params = [];
|
|
91448
91968
|
if (projectDir !== void 0) {
|
|
91449
|
-
|
|
91450
|
-
|
|
91451
|
-
|
|
91452
|
-
|
|
91453
|
-
|
|
91454
|
-
|
|
91455
|
-
|
|
91456
|
-
|
|
91457
|
-
|
|
91458
|
-
|
|
91459
|
-
|
|
91460
|
-
|
|
91461
|
-
|
|
91462
|
-
|
|
91463
|
-
|
|
91464
|
-
|
|
91465
|
-
|
|
91466
|
-
|
|
91467
|
-
|
|
91468
|
-
|
|
91469
|
-
}
|
|
91969
|
+
conditions.push("(m.project_dir = ? OR m.project_dir = '')");
|
|
91970
|
+
params.push(projectDir);
|
|
91971
|
+
}
|
|
91972
|
+
if (intent !== void 0) {
|
|
91973
|
+
conditions.push("m.intent = ?");
|
|
91974
|
+
params.push(intent);
|
|
91975
|
+
}
|
|
91976
|
+
if (cutoffMs !== void 0) {
|
|
91977
|
+
conditions.push("e.created_at > ?");
|
|
91978
|
+
params.push(cutoffMs);
|
|
91979
|
+
}
|
|
91980
|
+
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
91981
|
+
const rows = this.db.prepare(`
|
|
91982
|
+
SELECT e.memory_id, e.embedding_json
|
|
91983
|
+
FROM memory_embeddings e
|
|
91984
|
+
JOIN memos m ON m.id = e.memory_id
|
|
91985
|
+
${where}
|
|
91986
|
+
ORDER BY e.created_at DESC
|
|
91987
|
+
LIMIT ?
|
|
91988
|
+
`).all(...params, limit);
|
|
91470
91989
|
if (rows.length === 0) return [];
|
|
91471
91990
|
const scored = [];
|
|
91472
91991
|
for (const row of rows) try {
|
|
@@ -91584,16 +92103,25 @@ var MemoryMemoStore = class MemoryMemoStore {
|
|
|
91584
92103
|
lastError: this.lastEmbeddingError?.message
|
|
91585
92104
|
};
|
|
91586
92105
|
}
|
|
91587
|
-
listAll(limit, offset, projectDir) {
|
|
92106
|
+
listAll(limit, offset, projectDir, intent) {
|
|
91588
92107
|
if (this.db === void 0) return {
|
|
91589
92108
|
rows: [],
|
|
91590
92109
|
total: 0
|
|
91591
92110
|
};
|
|
91592
|
-
const
|
|
91593
|
-
const
|
|
91594
|
-
|
|
92111
|
+
const conditions = [];
|
|
92112
|
+
const params = [];
|
|
92113
|
+
if (projectDir !== void 0) {
|
|
92114
|
+
conditions.push("project_dir = ? OR project_dir = ''");
|
|
92115
|
+
params.push(projectDir);
|
|
92116
|
+
}
|
|
92117
|
+
if (intent !== void 0) {
|
|
92118
|
+
conditions.push("intent = ?");
|
|
92119
|
+
params.push(intent);
|
|
92120
|
+
}
|
|
92121
|
+
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
|
|
92122
|
+
const total = this.db.prepare(`SELECT COUNT(*) as total FROM memos ${where}`).get(...params)?.total ?? 0;
|
|
91595
92123
|
return {
|
|
91596
|
-
rows: (
|
|
92124
|
+
rows: this.db.prepare(`SELECT * FROM memos ${where} ORDER BY recorded_at DESC LIMIT ? OFFSET ?`).all(...params, limit, offset).map(rowToMemo),
|
|
91597
92125
|
total
|
|
91598
92126
|
};
|
|
91599
92127
|
}
|
|
@@ -91609,6 +92137,8 @@ var MemoryMemoStore = class MemoryMemoStore {
|
|
|
91609
92137
|
function rowToMemo(row) {
|
|
91610
92138
|
const sourceSessionTitle = row["source_session_title"];
|
|
91611
92139
|
const projectDir = row["project_dir"];
|
|
92140
|
+
const sourceFingerprint = row["source_fingerprint"];
|
|
92141
|
+
const intent = row["intent"];
|
|
91612
92142
|
return {
|
|
91613
92143
|
id: String(row["id"]),
|
|
91614
92144
|
sourceSessionId: String(row["source_session_id"]),
|
|
@@ -91620,8 +92150,11 @@ function rowToMemo(row) {
|
|
|
91620
92150
|
whatWorked: String(row["what_worked"]),
|
|
91621
92151
|
extractionSource: row["extraction_source"],
|
|
91622
92152
|
recordedAt: Number(row["recorded_at"]),
|
|
92153
|
+
sourceFingerprint: typeof sourceFingerprint === "string" ? sourceFingerprint : void 0,
|
|
92154
|
+
usageCount: Number(row["usage_count"] ?? 0),
|
|
91623
92155
|
projectDir: typeof projectDir === "string" ? projectDir : "",
|
|
91624
|
-
tags: parseTags(row["tags"])
|
|
92156
|
+
tags: parseTags(row["tags"]),
|
|
92157
|
+
intent: typeof intent === "string" && intent.length > 0 ? intent : void 0
|
|
91625
92158
|
};
|
|
91626
92159
|
}
|
|
91627
92160
|
function parseTags(value) {
|
|
@@ -91661,6 +92194,13 @@ function toFtsText(text) {
|
|
|
91661
92194
|
}
|
|
91662
92195
|
return tokens.join(" ");
|
|
91663
92196
|
}
|
|
92197
|
+
function mergeText(a, b) {
|
|
92198
|
+
if (a.length === 0 || a === "none") return b;
|
|
92199
|
+
if (b.length === 0 || b === "none") return a;
|
|
92200
|
+
if (a === b) return a;
|
|
92201
|
+
if (a.includes(b) || b.includes(a)) return a.length >= b.length ? a : b;
|
|
92202
|
+
return `${a}\n\n---\n\n${b}`;
|
|
92203
|
+
}
|
|
91664
92204
|
function buildFtsQuery(search) {
|
|
91665
92205
|
const tokens = toFtsText(search).split(/\s+/).filter((t) => t.length > 0);
|
|
91666
92206
|
if (tokens.length === 0) return void 0;
|
|
@@ -91685,6 +92225,7 @@ function parseMemoryMemos(text) {
|
|
|
91685
92225
|
if (userNeed.length === 0) continue;
|
|
91686
92226
|
const rawTags = parsed["tags"];
|
|
91687
92227
|
const tags = Array.isArray(rawTags) ? normalizeTags(rawTags) : void 0;
|
|
92228
|
+
const intent = typeof parsed["intent"] === "string" ? parsed["intent"].trim() || void 0 : void 0;
|
|
91688
92229
|
memos.push(createMemoryMemo({
|
|
91689
92230
|
userNeed,
|
|
91690
92231
|
approach: typeof parsed["approach"] === "string" ? parsed["approach"].trim() : "",
|
|
@@ -91692,6 +92233,7 @@ function parseMemoryMemos(text) {
|
|
|
91692
92233
|
whatFailed: typeof parsed["whatFailed"] === "string" ? parsed["whatFailed"].trim() : "none",
|
|
91693
92234
|
whatWorked: typeof parsed["whatWorked"] === "string" ? parsed["whatWorked"].trim() : "none",
|
|
91694
92235
|
tags,
|
|
92236
|
+
intent,
|
|
91695
92237
|
extractionSource: "compaction",
|
|
91696
92238
|
sourceSessionId: "",
|
|
91697
92239
|
sourceSessionTitle: ""
|
|
@@ -91720,7 +92262,8 @@ function buildExitExtractionPrompt(sessionId, messageCount, sampleText) {
|
|
|
91720
92262
|
"outcome": "<最终结果,如'完成'、'部分完成'、'失败:原因'>",
|
|
91721
92263
|
"whatFailed": "<踩坑记录:试了但不行的路,无则填 'none'>",
|
|
91722
92264
|
"whatWorked": "<成功经验:最终奏效的关键动作,无则填 'none'>",
|
|
91723
|
-
"tags": ["<标签1>", "<标签2>", "<标签3>"]
|
|
92265
|
+
"tags": ["<标签1>", "<标签2>", "<标签3>"],
|
|
92266
|
+
"intent": "<可选:该任务对应的意图,如 'debug'、'plan'、'explore'、'test'、'refactor',没有则省略>"
|
|
91724
92267
|
}
|
|
91725
92268
|
\`\`\`
|
|
91726
92269
|
|
|
@@ -92324,7 +92867,8 @@ const MemoryLookupInputSchema = z.object({
|
|
|
92324
92867
|
query: z.string().min(1).describe("Search query describing the current task, error, approach, or keywords to look up in the memory memo store."),
|
|
92325
92868
|
limit: z.number().int().min(1).max(MAX_LIMIT).optional().describe(`Maximum number of memos to return (default ${DEFAULT_LIMIT}, max ${MAX_LIMIT}).`),
|
|
92326
92869
|
min_score: z.number().min(0).max(1).optional().describe(`Minimum relevance score threshold from 0 to 1 (default ${DEFAULT_MIN_SCORE}).`),
|
|
92327
|
-
scope: z.enum(["project", "global"]).optional().describe(`Search scope: 'global' (default) searches across all projects; 'project' limits results to the current working directory.`)
|
|
92870
|
+
scope: z.enum(["project", "global"]).optional().describe(`Search scope: 'global' (default) searches across all projects; 'project' limits results to the current working directory.`),
|
|
92871
|
+
intent: z.string().max(50).optional().describe("Optional intent label (e.g., \"debug\", \"plan\", \"explore\", \"test\") to filter memories that were tagged with the same intent.")
|
|
92328
92872
|
});
|
|
92329
92873
|
/**
|
|
92330
92874
|
* Lets the model actively search the memory memo store for historical
|
|
@@ -92357,13 +92901,18 @@ var MemoryLookupTool = class {
|
|
|
92357
92901
|
const limit = Math.min(args.limit ?? DEFAULT_LIMIT, MAX_LIMIT);
|
|
92358
92902
|
const minScore = args.min_score ?? DEFAULT_MIN_SCORE;
|
|
92359
92903
|
const scope = args.scope ?? "global";
|
|
92904
|
+
const intent = args.intent;
|
|
92360
92905
|
const projectDir = scope === "project" ? this.agent.config.cwd : void 0;
|
|
92361
92906
|
const candidateLimit = Math.max((args.limit ?? DEFAULT_LIMIT) * 10, 200);
|
|
92362
92907
|
let candidates = await store.search(query, {
|
|
92363
92908
|
candidateLimit,
|
|
92364
|
-
projectDir
|
|
92909
|
+
projectDir,
|
|
92910
|
+
intent
|
|
92365
92911
|
});
|
|
92366
|
-
if (candidates.length === 0) for await (const memo of store.read({
|
|
92912
|
+
if (candidates.length === 0) for await (const memo of store.read({
|
|
92913
|
+
projectDir,
|
|
92914
|
+
intent
|
|
92915
|
+
})) candidates.push(memo);
|
|
92367
92916
|
const all = candidates.map(toSummary);
|
|
92368
92917
|
let vectorScores;
|
|
92369
92918
|
const engine = store.getEmbeddingEngine();
|
|
@@ -92380,6 +92929,7 @@ var MemoryLookupTool = class {
|
|
|
92380
92929
|
const vectorResults = await store.searchByVector(queryVec, {
|
|
92381
92930
|
candidateLimit,
|
|
92382
92931
|
projectDir,
|
|
92932
|
+
intent,
|
|
92383
92933
|
recencyCutoffDays: 90
|
|
92384
92934
|
});
|
|
92385
92935
|
if (vectorResults.length > 0) vectorScores = new Map(vectorResults.map((r) => [r.memo.id, r.score]));
|
|
@@ -92399,6 +92949,7 @@ var MemoryLookupTool = class {
|
|
|
92399
92949
|
projectTagCloud: scope === "global" ? buildProjectTagCloud(all, currentProjectDir) : void 0,
|
|
92400
92950
|
vectorScores
|
|
92401
92951
|
});
|
|
92952
|
+
for (const { memo } of ranked) await store.incrementUsage(memo.id).catch(() => void 0);
|
|
92402
92953
|
if (ranked.length === 0) return {
|
|
92403
92954
|
isError: false,
|
|
92404
92955
|
output: `No relevant memory memos found for query "${query}".`
|
|
@@ -105308,6 +105859,80 @@ function validateSkillPlan(plan, nameHint) {
|
|
|
105308
105859
|
}
|
|
105309
105860
|
}
|
|
105310
105861
|
//#endregion
|
|
105862
|
+
//#region ../../packages/agent-core/src/loop/concurrency-budget.ts
|
|
105863
|
+
var ConcurrencyBudget = class {
|
|
105864
|
+
activeCount = 0;
|
|
105865
|
+
maxConcurrency;
|
|
105866
|
+
name;
|
|
105867
|
+
waiters = [];
|
|
105868
|
+
constructor(options) {
|
|
105869
|
+
this.maxConcurrency = Math.max(1, Math.floor(options.maxConcurrency));
|
|
105870
|
+
this.name = options.name ?? "default";
|
|
105871
|
+
}
|
|
105872
|
+
get active() {
|
|
105873
|
+
return this.activeCount;
|
|
105874
|
+
}
|
|
105875
|
+
get max() {
|
|
105876
|
+
return this.maxConcurrency;
|
|
105877
|
+
}
|
|
105878
|
+
get available() {
|
|
105879
|
+
return Math.max(0, this.maxConcurrency - this.activeCount);
|
|
105880
|
+
}
|
|
105881
|
+
/**
|
|
105882
|
+
* Try to reserve a slot synchronously. Returns the slot if available, or
|
|
105883
|
+
* undefined if the budget is exhausted.
|
|
105884
|
+
*/
|
|
105885
|
+
tryReserve() {
|
|
105886
|
+
if (this.activeCount >= this.maxConcurrency) return void 0;
|
|
105887
|
+
this.activeCount += 1;
|
|
105888
|
+
let released = false;
|
|
105889
|
+
return { release: () => {
|
|
105890
|
+
if (released) return;
|
|
105891
|
+
released = true;
|
|
105892
|
+
this.activeCount -= 1;
|
|
105893
|
+
this.pumpWaiter();
|
|
105894
|
+
} };
|
|
105895
|
+
}
|
|
105896
|
+
/**
|
|
105897
|
+
* Reserve a slot, waiting if necessary until one becomes available.
|
|
105898
|
+
*/
|
|
105899
|
+
async reserve(signal) {
|
|
105900
|
+
const slot = this.tryReserve();
|
|
105901
|
+
if (slot !== void 0) return slot;
|
|
105902
|
+
return new Promise((resolve, reject) => {
|
|
105903
|
+
const waiter = {
|
|
105904
|
+
resolve,
|
|
105905
|
+
reject
|
|
105906
|
+
};
|
|
105907
|
+
this.waiters.push(waiter);
|
|
105908
|
+
if (signal !== void 0) {
|
|
105909
|
+
const onAbort = () => {
|
|
105910
|
+
const index = this.waiters.indexOf(waiter);
|
|
105911
|
+
if (index >= 0) this.waiters.splice(index, 1);
|
|
105912
|
+
reject(signal.reason);
|
|
105913
|
+
};
|
|
105914
|
+
if (signal.aborted) {
|
|
105915
|
+
onAbort();
|
|
105916
|
+
return;
|
|
105917
|
+
}
|
|
105918
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
105919
|
+
}
|
|
105920
|
+
});
|
|
105921
|
+
}
|
|
105922
|
+
pumpWaiter() {
|
|
105923
|
+
if (this.waiters.length === 0) return;
|
|
105924
|
+
if (this.activeCount >= this.maxConcurrency) return;
|
|
105925
|
+
const waiter = this.waiters.shift();
|
|
105926
|
+
if (waiter === void 0) return;
|
|
105927
|
+
const slot = this.tryReserve();
|
|
105928
|
+
if (slot === void 0) {
|
|
105929
|
+
this.waiters.unshift(waiter);
|
|
105930
|
+
return;
|
|
105931
|
+
}
|
|
105932
|
+
waiter.resolve(slot);
|
|
105933
|
+
}
|
|
105934
|
+
};
|
|
105935
|
+
//#endregion
|
|
105311
105936
|
//#region ../../packages/agent-core/src/tools/builtin/collaboration/wolfpack.md
|
|
105312
105937
|
var wolfpack_default = "Use WolfPack to spawn multiple subagents in parallel for batch operations.\r\nThis is ideal when processing many independent items (files, checks, searches)\r\nthat all use the same subagent type and follow a similar pattern.\r\n\r\nInput:\r\n- description: Brief (3-5 word) task summary.\r\n- subagent_type: Subagent profile name. Defaults to \"coder\". Choose the profile\r\n that best matches the batch task — using the right type materially improves\r\n output quality. See the agent type list below for which type fits which job.\r\n- prompt_template: A prompt pattern where each item value is substituted in\r\n to produce a per-item prompt. See the parameter schema for placeholder syntax.\r\n- items: Array of item strings. Each item gets its own subagent (no limit).\r\n\r\nItems must be independent — no subagent depends on another's output.\r\nIf items depend on each other, use separate Agent calls instead.\r\n\r\nChoosing subagent_type for the batch:\r\n- Batch code review, audit, or bug-finding across files → reviewer\r\n- Batch writing, reports, or long-form content → writer\r\n- Batch read-only exploration (find files, grep, understand modules) → explore\r\n- Batch verification (run build/test/lint per item) → verify\r\n- Batch deep debugging or architecture decisions → oracle\r\n- Batch planning or design work → plan\r\n- General engineering tasks with no specialised match → coder (default)\r\n\r\nExample: review source files for OWASP vulnerabilities by setting items to the file\r\npaths, subagent_type to \"reviewer\", and prompt_template to the review instruction.\r\nAll items are processed in parallel.\r\n\r\n";
|
|
105313
105938
|
//#endregion
|
|
@@ -105315,10 +105940,12 @@ var wolfpack_default = "Use WolfPack to spawn multiple subagents in parallel for
|
|
|
105315
105940
|
/**
|
|
105316
105941
|
* WolfPackTool — batch parallel subagent execution.
|
|
105317
105942
|
*
|
|
105318
|
-
* Spawns multiple subagents using a template + items pattern.
|
|
105943
|
+
* Spawns multiple subagents in parallel using a template + items pattern.
|
|
105319
105944
|
* Each item gets its own subagent; results are batched together in input order.
|
|
105945
|
+
* By default there is no artificial concurrency cap; callers may pass a
|
|
105946
|
+
* ConcurrencyBudget when they need a local rate-limit guard.
|
|
105320
105947
|
*/
|
|
105321
|
-
const DEFAULT_WOLFPACK_MAX_CONCURRENCY =
|
|
105948
|
+
const DEFAULT_WOLFPACK_MAX_CONCURRENCY = Number.MAX_SAFE_INTEGER;
|
|
105322
105949
|
const WolfPackToolInputSchema = z.object({
|
|
105323
105950
|
description: z.string().min(1).describe("Short task description (3-5 words, e.g., \"Security review all files\")"),
|
|
105324
105951
|
subagent_type: z.string().default("coder").describe("Subagent type for all spawned agents (e.g., coder, explore, verify)"),
|
|
@@ -105342,10 +105969,12 @@ var WolfPackTool = class {
|
|
|
105342
105969
|
this.description = typeLines ? `${wolfpack_default}\n\nAvailable agent types (pass via subagent_type):\n${typeLines}` : wolfpack_default;
|
|
105343
105970
|
this.log = options?.log;
|
|
105344
105971
|
this.maxConcurrency = normalizeConcurrency(options?.maxConcurrency);
|
|
105972
|
+
this.budget = options?.budget ?? new ConcurrencyBudget({ maxConcurrency: this.maxConcurrency });
|
|
105345
105973
|
this.onBatchUpdate = options?.onBatchUpdate;
|
|
105346
105974
|
}
|
|
105347
105975
|
log;
|
|
105348
105976
|
maxConcurrency;
|
|
105977
|
+
budget;
|
|
105349
105978
|
onBatchUpdate;
|
|
105350
105979
|
itemStates = [];
|
|
105351
105980
|
getItemStates() {
|
|
@@ -105400,7 +106029,7 @@ var WolfPackTool = class {
|
|
|
105400
106029
|
this.emitBatchUpdate(ctx, {
|
|
105401
106030
|
kind: "started",
|
|
105402
106031
|
totalItems: args.items.length,
|
|
105403
|
-
maxConcurrency: Math.min(this.
|
|
106032
|
+
maxConcurrency: Math.min(this.budget.max, args.items.length),
|
|
105404
106033
|
states: this.snapshotStates()
|
|
105405
106034
|
});
|
|
105406
106035
|
const completions = await this.runItems(args, profileName, template, ctx);
|
|
@@ -105451,13 +106080,18 @@ var WolfPackTool = class {
|
|
|
105451
106080
|
const worker = async () => {
|
|
105452
106081
|
while (nextIndex < args.items.length) {
|
|
105453
106082
|
ctx.signal.throwIfAborted();
|
|
106083
|
+
const slot = await this.budget.reserve(ctx.signal);
|
|
105454
106084
|
const index = nextIndex;
|
|
105455
|
-
nextIndex
|
|
106085
|
+
nextIndex += 1;
|
|
105456
106086
|
const item = args.items[index];
|
|
105457
|
-
|
|
106087
|
+
try {
|
|
106088
|
+
results[index] = await this.runItem(args, profileName, template, item, index, ctx);
|
|
106089
|
+
} finally {
|
|
106090
|
+
slot.release();
|
|
106091
|
+
}
|
|
105458
106092
|
}
|
|
105459
106093
|
};
|
|
105460
|
-
const workerCount = Math.min(this.
|
|
106094
|
+
const workerCount = Math.min(this.budget.max, args.items.length);
|
|
105461
106095
|
const settlements = await Promise.allSettled(Array.from({ length: workerCount }, () => worker()));
|
|
105462
106096
|
ctx.signal.throwIfAborted();
|
|
105463
106097
|
for (const settlement of settlements) if (settlement.status === "rejected") throw settlement.reason;
|
|
@@ -106591,7 +107225,7 @@ z.object({
|
|
|
106591
107225
|
numMatches: z.number().int().nonnegative().optional(),
|
|
106592
107226
|
appliedLimit: z.number().int().nonnegative().optional()
|
|
106593
107227
|
});
|
|
106594
|
-
const DEFAULT_TIMEOUT_MS
|
|
107228
|
+
const DEFAULT_TIMEOUT_MS = 2e4;
|
|
106595
107229
|
const SIGTERM_GRACE_MS$1 = 5e3;
|
|
106596
107230
|
const MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
|
|
106597
107231
|
const RG_MAX_COLUMNS = 500;
|
|
@@ -106694,7 +107328,7 @@ var GrepTool = class {
|
|
|
106694
107328
|
if (bufferTruncated || timedOut) stdoutText = omitIncompleteTrailingRecord(stdoutText, mode);
|
|
106695
107329
|
if (timedOut && stdoutText.trim() === "") return {
|
|
106696
107330
|
isError: true,
|
|
106697
|
-
output: `Grep timed out after ${String(DEFAULT_TIMEOUT_MS
|
|
107331
|
+
output: `Grep timed out after ${String(DEFAULT_TIMEOUT_MS / 1e3)}s. Try a more specific path or pattern.`
|
|
106698
107332
|
};
|
|
106699
107333
|
if (signal.aborted) return {
|
|
106700
107334
|
isError: true,
|
|
@@ -106734,7 +107368,7 @@ var GrepTool = class {
|
|
|
106734
107368
|
else messages.push(paginationNotice);
|
|
106735
107369
|
}
|
|
106736
107370
|
if (bufferTruncated) messages.push(`[stdout truncated at ${String(MAX_OUTPUT_BYTES)} bytes; incomplete trailing line omitted]`);
|
|
106737
|
-
if (timedOut) messages.push(`Grep timed out after ${String(DEFAULT_TIMEOUT_MS
|
|
107371
|
+
if (timedOut) messages.push(`Grep timed out after ${String(DEFAULT_TIMEOUT_MS / 1e3)}s; partial results returned`);
|
|
106738
107372
|
const contentIncludesLineNumbers = mode === "content" && args["-n"] !== false;
|
|
106739
107373
|
const contentBody = limited.map((line) => formatDisplayLine(line, mode, this.workspace.workspaceDir, pathClass, contentIncludesLineNumbers)).join("\n");
|
|
106740
107374
|
const visibleBody = orderedLines.length === 0 && filteredSensitive.size > 0 ? "No non-sensitive matches found" : contentBody;
|
|
@@ -106851,7 +107485,7 @@ async function runRipgrepOnce(jian, rgArgs, signal) {
|
|
|
106851
107485
|
const timeoutHandle = setTimeout(() => {
|
|
106852
107486
|
timedOut = true;
|
|
106853
107487
|
killProc();
|
|
106854
|
-
}, DEFAULT_TIMEOUT_MS
|
|
107488
|
+
}, DEFAULT_TIMEOUT_MS);
|
|
106855
107489
|
let exitCode = 0;
|
|
106856
107490
|
let stdoutText = "";
|
|
106857
107491
|
let stderrText = "";
|
|
@@ -108037,6 +108671,69 @@ var ReadTool = class {
|
|
|
108037
108671
|
}
|
|
108038
108672
|
};
|
|
108039
108673
|
//#endregion
|
|
108674
|
+
//#region ../../packages/agent-core/src/tools/builtin/file/read-chunk.ts
|
|
108675
|
+
const ReadChunkInputSchema = z.object({
|
|
108676
|
+
path: z.string().describe("Path to a text file. Relative paths resolve against the working directory; a path outside the working directory must be absolute."),
|
|
108677
|
+
offset: z.number().int().min(0).describe("Byte offset to start reading from. Use the nextOffset returned by a previous ReadChunk call to paginate."),
|
|
108678
|
+
length: z.number().int().positive().max(100 * 1024).describe("Maximum number of bytes to read. Cannot exceed 100 KB.")
|
|
108679
|
+
});
|
|
108680
|
+
const MAX_CHUNK_BYTES = 100 * 1024;
|
|
108681
|
+
/**
|
|
108682
|
+
* Reads a byte-range chunk from a text file. Designed for paginating through
|
|
108683
|
+
* oversized tool outputs or files that exceed the standard Read limits.
|
|
108684
|
+
*/
|
|
108685
|
+
var ReadChunkTool = class {
|
|
108686
|
+
jian;
|
|
108687
|
+
workspace;
|
|
108688
|
+
name = "ReadChunk";
|
|
108689
|
+
description = "Read a byte-range chunk from a text file. Use this to paginate through very large outputs or files when the standard Read tool hits its limit. Pass the nextOffset from the previous result to continue reading.";
|
|
108690
|
+
parameters = toInputJsonSchema(ReadChunkInputSchema);
|
|
108691
|
+
constructor(jian, workspace) {
|
|
108692
|
+
this.jian = jian;
|
|
108693
|
+
this.workspace = workspace;
|
|
108694
|
+
}
|
|
108695
|
+
resolveExecution(args) {
|
|
108696
|
+
const path = resolvePathAccessPath(args.path, {
|
|
108697
|
+
jian: this.jian,
|
|
108698
|
+
workspace: this.workspace,
|
|
108699
|
+
operation: "read"
|
|
108700
|
+
});
|
|
108701
|
+
return {
|
|
108702
|
+
accesses: ToolAccesses.readFile(path),
|
|
108703
|
+
description: `Reading chunk of ${args.path}`,
|
|
108704
|
+
display: {
|
|
108705
|
+
kind: "file_io",
|
|
108706
|
+
operation: "read",
|
|
108707
|
+
path
|
|
108708
|
+
},
|
|
108709
|
+
approvalRule: literalRulePattern(this.name, path),
|
|
108710
|
+
matchesRule: (ruleArgs) => matchesPathRuleSubject(ruleArgs, path, {
|
|
108711
|
+
cwd: this.workspace.workspaceDir,
|
|
108712
|
+
pathClass: this.jian.pathClass(),
|
|
108713
|
+
homeDir: this.jian.gethome()
|
|
108714
|
+
}),
|
|
108715
|
+
execute: () => this.execution(args, path)
|
|
108716
|
+
};
|
|
108717
|
+
}
|
|
108718
|
+
async execution(args, safePath) {
|
|
108719
|
+
const text = await this.jian.readText(safePath, { encoding: "utf8" });
|
|
108720
|
+
const buffer = Buffer.from(text, "utf8");
|
|
108721
|
+
const totalBytes = buffer.length;
|
|
108722
|
+
const offset = Math.min(args.offset, totalBytes);
|
|
108723
|
+
const length = Math.min(args.length, MAX_CHUNK_BYTES, totalBytes - offset);
|
|
108724
|
+
const content = buffer.subarray(offset, offset + length).toString("utf8");
|
|
108725
|
+
const nextOffset = offset + length;
|
|
108726
|
+
return { output: JSON.stringify({
|
|
108727
|
+
content,
|
|
108728
|
+
offset,
|
|
108729
|
+
length,
|
|
108730
|
+
totalBytes,
|
|
108731
|
+
hasMore: nextOffset < totalBytes,
|
|
108732
|
+
nextOffset
|
|
108733
|
+
}, null, 2) };
|
|
108734
|
+
}
|
|
108735
|
+
};
|
|
108736
|
+
//#endregion
|
|
108040
108737
|
//#region ../../packages/agent-core/src/tools/builtin/file/read-group.md
|
|
108041
108738
|
var read_group_default = "Read multiple files in parallel.\r\n\r\nUse this when you need to inspect several files in the same step. It performs the same path-access checks and file-type validation as Read, but batches the calls into one tool invocation.\r\n\r\nInputs:\r\n- paths: array of file paths (max 20). Relative paths resolve against the working directory.\r\n- line_offset: optional starting line number (1-based; negative values read from the end).\r\n- n_lines: optional maximum lines per file.\r\n\r\nOutput:\r\nA single aggregated string grouped by file extension. Each group has a header like `── .ts (3) ──` followed by the files in that group. Within a group, files appear in input order. If a file fails, the error is included inline and the rest continue.\r\n\r\nAfter the file contents, the output may include footers:\r\n- `Skipped missing paths:` when some paths did not exist.\r\n- `Conflict markers detected —` when any file contains unresolved merge conflict markers.\r\n- `Imports:` a cross-file import summary for TypeScript/JavaScript files, showing relative import specifiers (e.g. `a.ts → ./b, ./c`).\r\n\r\nUse Read (single file) when only one file is needed; use ReadGroup when you want 2-20 files at once.\r\n";
|
|
108042
108739
|
//#endregion
|
|
@@ -108428,6 +109125,71 @@ var ReadMediaFileTool = class {
|
|
|
108428
109125
|
}
|
|
108429
109126
|
};
|
|
108430
109127
|
//#endregion
|
|
109128
|
+
//#region ../../packages/agent-core/src/tools/builtin/file/summarize-output.ts
|
|
109129
|
+
const SummarizeOutputInputSchema = z.object({
|
|
109130
|
+
text: z.string().min(1).describe("The text to summarize. This is typically a long tool output or file content that would bloat the context window."),
|
|
109131
|
+
maxTokens: z.number().int().positive().max(4e3).optional().describe("Target maximum tokens for the summary. Defaults to 400."),
|
|
109132
|
+
focus: z.string().max(200).optional().describe("Optional hint about what to preserve (e.g., \"error messages\", \"file paths\", \"key numbers\").")
|
|
109133
|
+
});
|
|
109134
|
+
const DEFAULT_MAX_TOKENS = 400;
|
|
109135
|
+
const MAX_INPUT_TOKENS_FOR_SUMMARY = 12e3;
|
|
109136
|
+
const SUMMARY_SYSTEM_PROMPT = "You are a precise summarizer. Condense the user-provided text into the requested token budget. Preserve facts, names, file paths, error messages, and numbers. Do not add information not present in the text. Respond with the summary only, no meta-commentary.";
|
|
109137
|
+
/**
|
|
109138
|
+
* Summarizes a long text using the agent's configured LLM. Useful for keeping
|
|
109139
|
+
* oversized tool outputs from polluting the context window.
|
|
109140
|
+
*/
|
|
109141
|
+
var SummarizeOutputTool = class {
|
|
109142
|
+
agent;
|
|
109143
|
+
name = "SummarizeOutput";
|
|
109144
|
+
description = "Summarize a long text to fit within a token budget. Use this when a tool output is too large to keep in context or when you need a compact recap before the next step.";
|
|
109145
|
+
parameters = toInputJsonSchema(SummarizeOutputInputSchema);
|
|
109146
|
+
constructor(agent) {
|
|
109147
|
+
this.agent = agent;
|
|
109148
|
+
}
|
|
109149
|
+
resolveExecution(args) {
|
|
109150
|
+
return {
|
|
109151
|
+
description: "Summarizing output",
|
|
109152
|
+
approvalRule: this.name,
|
|
109153
|
+
execute: async (ctx) => {
|
|
109154
|
+
const maxTokens = args.maxTokens ?? DEFAULT_MAX_TOKENS;
|
|
109155
|
+
const text = this.prepareText(args.text);
|
|
109156
|
+
const prompt = this.buildPrompt(text, maxTokens, args.focus);
|
|
109157
|
+
try {
|
|
109158
|
+
const response = await this.agent.rawGenerate(this.agent.config.provider, SUMMARY_SYSTEM_PROMPT, [], [{
|
|
109159
|
+
role: "user",
|
|
109160
|
+
content: [{
|
|
109161
|
+
type: "text",
|
|
109162
|
+
text: prompt
|
|
109163
|
+
}],
|
|
109164
|
+
toolCalls: []
|
|
109165
|
+
}], void 0, { signal: ctx.signal });
|
|
109166
|
+
const summary = this.extractText(response);
|
|
109167
|
+
return { output: `Summary (target ~${String(maxTokens)} tokens, actual ${String(estimateTokens$1(summary))} tokens):\n\n${summary}` };
|
|
109168
|
+
} catch (error) {
|
|
109169
|
+
return {
|
|
109170
|
+
isError: true,
|
|
109171
|
+
output: `Summarization failed: ${error instanceof Error ? error.message : String(error)}`
|
|
109172
|
+
};
|
|
109173
|
+
}
|
|
109174
|
+
}
|
|
109175
|
+
};
|
|
109176
|
+
}
|
|
109177
|
+
prepareText(text) {
|
|
109178
|
+
if (estimateTokens$1(text) <= MAX_INPUT_TOKENS_FOR_SUMMARY) return text;
|
|
109179
|
+
const maxChars = MAX_INPUT_TOKENS_FOR_SUMMARY * 4;
|
|
109180
|
+
return `${text.slice(0, maxChars)}\n[truncated before summarization]`;
|
|
109181
|
+
}
|
|
109182
|
+
buildPrompt(text, maxTokens, focus) {
|
|
109183
|
+
let prompt = `Summarize the following text in at most ${String(maxTokens)} tokens.`;
|
|
109184
|
+
if (focus !== void 0 && focus.length > 0) prompt += ` Preserve details relevant to: ${focus}.`;
|
|
109185
|
+
prompt += `\n\n${text}`;
|
|
109186
|
+
return prompt;
|
|
109187
|
+
}
|
|
109188
|
+
extractText(response) {
|
|
109189
|
+
return (response.message.content ?? []).filter((p) => p.type === "text" && typeof p.text === "string").map((p) => p.text).join("").trim();
|
|
109190
|
+
}
|
|
109191
|
+
};
|
|
109192
|
+
//#endregion
|
|
108431
109193
|
//#region ../../packages/agent-core/src/tools/builtin/file/write.md
|
|
108432
109194
|
var write_default = "Overwrite or append to a file with content exactly as provided, creating the file if needed; the parent directory must already exist. Defaults to overwrite; append adds content to the end without adding a newline. Write does not use the Read/Edit model text view and does not preserve or infer the previous line-ending style: \\n stays LF, \\r\\n stays CRLF. Use Edit for targeted changes to existing files. When the content is very large, you can split it across multiple calls: write the first chunk with overwrite, then add the remaining chunks with append. Write refuses content containing `<<<<<<<`/`=======`/`>>>>>>>` merge conflict markers — resolve conflicts first.\r\n";
|
|
108433
109195
|
//#endregion
|
|
@@ -108543,6 +109305,288 @@ var WriteTool = class {
|
|
|
108543
109305
|
}
|
|
108544
109306
|
};
|
|
108545
109307
|
//#endregion
|
|
109308
|
+
//#region ../../packages/agent-core/src/tools/builtin/introspection/get-active-tools.ts
|
|
109309
|
+
const GetActiveToolsInputSchema = z.object({}).strict();
|
|
109310
|
+
/**
|
|
109311
|
+
* Returns the tools currently available to the model, including whether each
|
|
109312
|
+
* tool is active and its source (built-in, user-registered, or MCP server).
|
|
109313
|
+
*/
|
|
109314
|
+
var GetActiveToolsTool = class {
|
|
109315
|
+
agent;
|
|
109316
|
+
name = "GetActiveTools";
|
|
109317
|
+
description = "List all tools currently available to the model, with their active status and source.";
|
|
109318
|
+
parameters = toInputJsonSchema(GetActiveToolsInputSchema);
|
|
109319
|
+
constructor(agent) {
|
|
109320
|
+
this.agent = agent;
|
|
109321
|
+
}
|
|
109322
|
+
resolveExecution(_args) {
|
|
109323
|
+
return {
|
|
109324
|
+
description: "Listing available tools",
|
|
109325
|
+
approvalRule: this.name,
|
|
109326
|
+
execute: async () => {
|
|
109327
|
+
const tools = this.agent.tools.data();
|
|
109328
|
+
return { output: JSON.stringify(tools, null, 2) };
|
|
109329
|
+
}
|
|
109330
|
+
};
|
|
109331
|
+
}
|
|
109332
|
+
};
|
|
109333
|
+
//#endregion
|
|
109334
|
+
//#region ../../packages/agent-core/src/tools/builtin/introspection/get-context-usage.ts
|
|
109335
|
+
const GetContextUsageInputSchema = z.object({}).strict();
|
|
109336
|
+
/**
|
|
109337
|
+
* Returns the current context-window usage so the model can decide whether to
|
|
109338
|
+
* compact, fetch more history, or write results to files instead of chat.
|
|
109339
|
+
*/
|
|
109340
|
+
var GetContextUsageTool = class {
|
|
109341
|
+
agent;
|
|
109342
|
+
name = "GetContextUsage";
|
|
109343
|
+
description = "Return the current context-window usage (tokens used, history size, and model limit) so you can budget long outputs.";
|
|
109344
|
+
parameters = toInputJsonSchema(GetContextUsageInputSchema);
|
|
109345
|
+
constructor(agent) {
|
|
109346
|
+
this.agent = agent;
|
|
109347
|
+
}
|
|
109348
|
+
resolveExecution(_args) {
|
|
109349
|
+
return {
|
|
109350
|
+
description: "Reading context usage",
|
|
109351
|
+
approvalRule: this.name,
|
|
109352
|
+
execute: async () => {
|
|
109353
|
+
const context = this.agent.context;
|
|
109354
|
+
const maxTokens = this.agent.config.modelCapabilities.max_context_tokens;
|
|
109355
|
+
const info = {
|
|
109356
|
+
tokenCount: context.tokenCount,
|
|
109357
|
+
tokenCountWithPending: context.tokenCountWithPending,
|
|
109358
|
+
historyMessageCount: context.history.length,
|
|
109359
|
+
maxContextTokens: maxTokens > 0 ? maxTokens : null
|
|
109360
|
+
};
|
|
109361
|
+
return { output: JSON.stringify(info, null, 2) };
|
|
109362
|
+
}
|
|
109363
|
+
};
|
|
109364
|
+
}
|
|
109365
|
+
};
|
|
109366
|
+
//#endregion
|
|
109367
|
+
//#region ../../packages/agent-core/src/tools/builtin/introspection/get-plan-state.ts
|
|
109368
|
+
const GetPlanStateInputSchema = z.object({}).strict();
|
|
109369
|
+
/**
|
|
109370
|
+
* Returns the current plan-mode state: whether it is active, the plan id and
|
|
109371
|
+
* strategy, and the current plan file content.
|
|
109372
|
+
*/
|
|
109373
|
+
var GetPlanStateTool = class {
|
|
109374
|
+
agent;
|
|
109375
|
+
name = "GetPlanState";
|
|
109376
|
+
description = "Return the current plan-mode state (active, plan id, strategy, and plan content).";
|
|
109377
|
+
parameters = toInputJsonSchema(GetPlanStateInputSchema);
|
|
109378
|
+
constructor(agent) {
|
|
109379
|
+
this.agent = agent;
|
|
109380
|
+
}
|
|
109381
|
+
resolveExecution(_args) {
|
|
109382
|
+
return {
|
|
109383
|
+
description: "Reading plan state",
|
|
109384
|
+
approvalRule: this.name,
|
|
109385
|
+
execute: async () => {
|
|
109386
|
+
const plan = this.agent.planMode;
|
|
109387
|
+
const data = await plan.data();
|
|
109388
|
+
const info = {
|
|
109389
|
+
active: plan.isActive,
|
|
109390
|
+
id: data?.id ?? null,
|
|
109391
|
+
strategy: plan.strategy,
|
|
109392
|
+
path: data?.path ?? null,
|
|
109393
|
+
content: data?.content ?? null
|
|
109394
|
+
};
|
|
109395
|
+
return { output: JSON.stringify(info, null, 2) };
|
|
109396
|
+
}
|
|
109397
|
+
};
|
|
109398
|
+
}
|
|
109399
|
+
};
|
|
109400
|
+
//#endregion
|
|
109401
|
+
//#region ../../packages/agent-core/src/agent/tool/capability/index.ts
|
|
109402
|
+
const CAPABILITY_DESCRIPTIONS = {
|
|
109403
|
+
filesystem: "Read, write, search, and edit local files.",
|
|
109404
|
+
execution: "Run shell commands and interact with processes.",
|
|
109405
|
+
web: "Fetch web pages and run web searches.",
|
|
109406
|
+
memory: "Recall and update cross-session memories.",
|
|
109407
|
+
planning: "Enter/exit plan mode and inspect plan state.",
|
|
109408
|
+
introspection: "Inspect agent state, context usage, and active tools.",
|
|
109409
|
+
meta: "Create skills, manage goals, and orchestrate subagents.",
|
|
109410
|
+
general: "General-purpose tools with no specific capability tag."
|
|
109411
|
+
};
|
|
109412
|
+
/** Built-in tool name → capabilities. */
|
|
109413
|
+
const BUILTIN_TOOL_CAPABILITIES = {
|
|
109414
|
+
Read: ["filesystem"],
|
|
109415
|
+
ReadGroup: ["filesystem"],
|
|
109416
|
+
ReadChunk: ["filesystem"],
|
|
109417
|
+
ReadMediaFile: ["filesystem"],
|
|
109418
|
+
Write: ["filesystem"],
|
|
109419
|
+
Edit: ["filesystem"],
|
|
109420
|
+
Grep: ["filesystem"],
|
|
109421
|
+
Glob: ["filesystem"],
|
|
109422
|
+
Bash: ["execution"],
|
|
109423
|
+
WebSearch: ["web"],
|
|
109424
|
+
FetchURL: ["web"],
|
|
109425
|
+
MemoryLookup: ["memory"],
|
|
109426
|
+
MemoryEdit: ["memory"],
|
|
109427
|
+
MemoryWrite: ["memory"],
|
|
109428
|
+
MemoryConsolidatePlan: ["memory"],
|
|
109429
|
+
MemoryConsolidateApply: ["memory"],
|
|
109430
|
+
EnterPlanMode: ["planning"],
|
|
109431
|
+
ExitPlanMode: ["planning"],
|
|
109432
|
+
GetPlanState: ["planning", "introspection"],
|
|
109433
|
+
SetTodoList: ["meta"],
|
|
109434
|
+
TodoList: ["meta"],
|
|
109435
|
+
TaskList: ["meta"],
|
|
109436
|
+
TaskOutput: ["meta"],
|
|
109437
|
+
CronList: ["meta"],
|
|
109438
|
+
CronCreate: ["meta"],
|
|
109439
|
+
CronDelete: ["meta"],
|
|
109440
|
+
Agent: ["meta"],
|
|
109441
|
+
AskUserQuestion: ["meta"],
|
|
109442
|
+
Skill: ["meta"],
|
|
109443
|
+
WolfPack: ["meta"],
|
|
109444
|
+
CreateGoal: ["meta"],
|
|
109445
|
+
UpdateGoal: ["meta"],
|
|
109446
|
+
GetGoal: ["meta"],
|
|
109447
|
+
SetGoalBudget: ["meta"],
|
|
109448
|
+
WriteGoalNote: ["meta"],
|
|
109449
|
+
MakeSkillPlan: ["meta"],
|
|
109450
|
+
MakeSkillApply: ["meta"],
|
|
109451
|
+
GetActiveTools: ["introspection"],
|
|
109452
|
+
GetContextUsage: ["introspection"],
|
|
109453
|
+
GetWorkingSet: ["introspection"],
|
|
109454
|
+
GetToolsByCapability: ["introspection"],
|
|
109455
|
+
SummarizeOutput: ["filesystem", "introspection"]
|
|
109456
|
+
};
|
|
109457
|
+
/** Intent → capabilities most relevant for that intent. */
|
|
109458
|
+
const INTENT_CAPABILITY_MAP = {
|
|
109459
|
+
explore: ["filesystem", "introspection"],
|
|
109460
|
+
edit: ["filesystem", "execution"],
|
|
109461
|
+
search: ["filesystem", "web"],
|
|
109462
|
+
debug: [
|
|
109463
|
+
"filesystem",
|
|
109464
|
+
"execution",
|
|
109465
|
+
"introspection"
|
|
109466
|
+
],
|
|
109467
|
+
test: ["execution", "filesystem"],
|
|
109468
|
+
plan: ["planning", "introspection"],
|
|
109469
|
+
remember: ["memory"],
|
|
109470
|
+
chat: ["general", "introspection"]
|
|
109471
|
+
};
|
|
109472
|
+
/**
|
|
109473
|
+
* Returns the capabilities associated with a tool name. Falls back to
|
|
109474
|
+
* `['general']` for unknown tools (user-registered or MCP tools).
|
|
109475
|
+
*/
|
|
109476
|
+
function getToolCapabilities(toolName) {
|
|
109477
|
+
return BUILTIN_TOOL_CAPABILITIES[toolName] ?? ["general"];
|
|
109478
|
+
}
|
|
109479
|
+
/**
|
|
109480
|
+
* Returns the capabilities that should be active for a given intent.
|
|
109481
|
+
* Unknown intents get `['general']`.
|
|
109482
|
+
*/
|
|
109483
|
+
function getCapabilitiesForIntent(intent) {
|
|
109484
|
+
return INTENT_CAPABILITY_MAP[intent.toLowerCase()] ?? ["general"];
|
|
109485
|
+
}
|
|
109486
|
+
/**
|
|
109487
|
+
* Filters a list of tool names to those that match at least one of the given
|
|
109488
|
+
* capabilities.
|
|
109489
|
+
*/
|
|
109490
|
+
function filterToolsByCapabilities(tools, capabilities) {
|
|
109491
|
+
const set = new Set(capabilities);
|
|
109492
|
+
return tools.map((tool) => ({
|
|
109493
|
+
name: tool.name,
|
|
109494
|
+
capabilities: getToolCapabilities(tool.name)
|
|
109495
|
+
})).filter((tool) => tool.capabilities.some((c) => set.has(c)));
|
|
109496
|
+
}
|
|
109497
|
+
/**
|
|
109498
|
+
* Filters a list of tool names to those that are relevant for a given intent.
|
|
109499
|
+
*/
|
|
109500
|
+
function filterToolsByIntent(tools, intent) {
|
|
109501
|
+
return filterToolsByCapabilities(tools, getCapabilitiesForIntent(intent));
|
|
109502
|
+
}
|
|
109503
|
+
//#endregion
|
|
109504
|
+
//#region ../../packages/agent-core/src/tools/builtin/introspection/get-tools-by-capability.ts
|
|
109505
|
+
const GetToolsByCapabilityInputSchema = z.object({
|
|
109506
|
+
intent: z.string().max(50).optional().describe("Optional intent keyword (e.g., \"explore\", \"debug\", \"test\", \"plan\", \"remember\"). If provided, returns tools relevant to that intent."),
|
|
109507
|
+
capability: z.string().max(50).optional().describe("Optional capability keyword (e.g., \"filesystem\", \"execution\", \"web\", \"memory\", \"planning\", \"introspection\", \"meta\"). If provided, returns tools tagged with that capability.")
|
|
109508
|
+
});
|
|
109509
|
+
/**
|
|
109510
|
+
* Returns the active tools filtered by capability or intent. Helps the model
|
|
109511
|
+
* discover which tools are appropriate for the current task without scanning
|
|
109512
|
+
* the full tool list.
|
|
109513
|
+
*/
|
|
109514
|
+
var GetToolsByCapabilityTool = class {
|
|
109515
|
+
agent;
|
|
109516
|
+
name = "GetToolsByCapability";
|
|
109517
|
+
description = "List active tools filtered by capability or intent. Use this when you want to narrow the available tool set to those relevant for the current task (e.g., debugging, testing, planning).";
|
|
109518
|
+
parameters = toInputJsonSchema(GetToolsByCapabilityInputSchema);
|
|
109519
|
+
constructor(agent) {
|
|
109520
|
+
this.agent = agent;
|
|
109521
|
+
}
|
|
109522
|
+
resolveExecution(args) {
|
|
109523
|
+
return {
|
|
109524
|
+
description: "Listing tools by capability",
|
|
109525
|
+
approvalRule: this.name,
|
|
109526
|
+
execute: async () => {
|
|
109527
|
+
let tools;
|
|
109528
|
+
let matchedCapabilities;
|
|
109529
|
+
let note;
|
|
109530
|
+
if (args.capability !== void 0 && args.capability.length > 0) {
|
|
109531
|
+
matchedCapabilities = [args.capability];
|
|
109532
|
+
tools = Array.from(this.agent.tools.getToolsByCapability(args.capability));
|
|
109533
|
+
note = `Tools tagged with capability "${args.capability}".`;
|
|
109534
|
+
} else if (args.intent !== void 0 && args.intent.length > 0) {
|
|
109535
|
+
matchedCapabilities = getCapabilitiesForIntent(args.intent);
|
|
109536
|
+
tools = Array.from(this.agent.tools.getToolsByIntent(args.intent));
|
|
109537
|
+
note = `Tools relevant for intent "${args.intent}" (capabilities: ${matchedCapabilities.join(", ")}).`;
|
|
109538
|
+
} else {
|
|
109539
|
+
tools = Array.from(this.agent.tools.data());
|
|
109540
|
+
note = "All active tools. Provide an intent or capability to filter.";
|
|
109541
|
+
matchedCapabilities = [];
|
|
109542
|
+
}
|
|
109543
|
+
const capabilityDescriptions = Object.fromEntries(matchedCapabilities.map((c) => [c, CAPABILITY_DESCRIPTIONS[c] ?? ""]));
|
|
109544
|
+
return { output: JSON.stringify({
|
|
109545
|
+
note,
|
|
109546
|
+
capabilities: matchedCapabilities,
|
|
109547
|
+
capabilityDescriptions,
|
|
109548
|
+
tools: tools.map((t) => ({
|
|
109549
|
+
name: t.name,
|
|
109550
|
+
description: t.description
|
|
109551
|
+
}))
|
|
109552
|
+
}, null, 2) };
|
|
109553
|
+
}
|
|
109554
|
+
};
|
|
109555
|
+
}
|
|
109556
|
+
};
|
|
109557
|
+
//#endregion
|
|
109558
|
+
//#region ../../packages/agent-core/src/tools/builtin/introspection/get-working-set.ts
|
|
109559
|
+
const GetWorkingSetInputSchema = z.object({}).strict();
|
|
109560
|
+
/**
|
|
109561
|
+
* Returns the files the agent has recently touched, which ones still have
|
|
109562
|
+
* unverified changes, and suggested verification commands for the project.
|
|
109563
|
+
*/
|
|
109564
|
+
var GetWorkingSetTool = class {
|
|
109565
|
+
agent;
|
|
109566
|
+
name = "GetWorkingSet";
|
|
109567
|
+
description = "Return the set of files the agent has recently read or modified, which ones still have unverified changes, and suggested verification commands.";
|
|
109568
|
+
parameters = toInputJsonSchema(GetWorkingSetInputSchema);
|
|
109569
|
+
constructor(agent) {
|
|
109570
|
+
this.agent = agent;
|
|
109571
|
+
}
|
|
109572
|
+
resolveExecution(_args) {
|
|
109573
|
+
return {
|
|
109574
|
+
description: "Reading working set",
|
|
109575
|
+
approvalRule: this.name,
|
|
109576
|
+
execute: async () => {
|
|
109577
|
+
const workingSet = this.agent.workingSet;
|
|
109578
|
+
const info = {
|
|
109579
|
+
paths: workingSet.getPaths(),
|
|
109580
|
+
unverifiedPaths: workingSet.getUnverifiedPaths(),
|
|
109581
|
+
suggestedVerificationCommands: workingSet.suggestVerificationCommands(this.agent.config.cwd),
|
|
109582
|
+
verificationCount: workingSet.getVerificationCount()
|
|
109583
|
+
};
|
|
109584
|
+
return { output: JSON.stringify(info, null, 2) };
|
|
109585
|
+
}
|
|
109586
|
+
};
|
|
109587
|
+
}
|
|
109588
|
+
};
|
|
109589
|
+
//#endregion
|
|
108546
109590
|
//#region ../../packages/agent-core/src/tools/builtin/planning/enter-plan-mode.md
|
|
108547
109591
|
var enter_plan_mode_default = "Use this tool proactively when you're about to start a non-trivial implementation task.\r\nGetting user sign-off on your approach via ExitPlanMode before writing code prevents wasted effort.\r\n\r\n## Planning Modes\r\n\r\nThe host supports two planning strategies. You can request either one via this tool:\r\n\r\n- **Normal plan** (default): You investigate the codebase, design a single implementation approach, write it to the plan file, and present it for approval. Best when the task is straightforward or you are already confident about the right approach.\r\n- **Fusion plan**: The host spawns multiple independent planning subagents in parallel, each exploring a different angle, then synthesizes their outputs into one consolidated plan. Best when the task is ambiguous, has many valid approaches, crosses many files, or when exploration itself adds significant value. Fusion plan may take longer but tends to surface risks and alternatives you might miss.\r\n\r\nTo request a fusion plan, include `mode: 'fusion'` in your tool arguments. If you omit `mode` or set it to `normal`, the host uses the normal plan flow.\r\n\r\n### When to choose which mode\r\n\r\nPrefer **normal plan** when:\r\n1. The user gave specific, detailed instructions.\r\n2. The change is small or localized (1-3 files, single concern).\r\n3. You are confident about the codebase structure and the right approach.\r\n4. Speed matters more than exploring alternatives.\r\n\r\nPrefer **fusion plan** when:\r\n1. The task is open-ended or ambiguous (e.g. \"improve performance\", \"refactor auth\").\r\n2. Multiple valid architectures or approaches exist.\r\n3. The change spans more than 3-5 files or touches core abstractions.\r\n4. You are unfamiliar with the relevant code paths and want parallel exploration.\r\n5. The user explicitly asked for a thorough plan or mentioned comparing options.\r\n\r\nIf unsure, choose normal plan for small fixes and fusion plan for larger design tasks.\r\n\r\n## When to Use\r\n\r\nUse this tool when ANY of these conditions apply:\r\n\r\n1. New Feature Implementation - e.g. \"Add a caching layer to the API\"\r\n2. Multiple Valid Approaches - e.g. \"Optimize database queries\" (indexing vs rewrite vs caching)\r\n3. Code Modifications - e.g. \"Refactor auth module to support OAuth\"\r\n4. Architectural Decisions - e.g. \"Add WebSocket support\"\r\n5. Multi-File Changes - involves more than 2-3 files\r\n6. Unclear Requirements - need exploration to understand scope\r\n7. User Preferences Matter - if user input would materially change the implementation approach, use EnterPlanMode to structure the decision\r\n\r\nPermission mode notes:\r\n- EnterPlanMode enters plan mode automatically without an approval prompt in all permission modes.\r\n- In yolo and manual modes, ExitPlanMode still presents the plan to the user for approval.\r\n- In auto permission mode, do not use AskUserQuestion; make the best decision from available context.\r\n- In auto permission mode, ExitPlanMode exits plan mode without asking the user.\r\n- Use EnterPlanMode only when planning itself adds value.\r\n\r\nWhen NOT to use:\r\n- Single-line or few-line fixes (typos, obvious bugs, small tweaks)\r\n- User gave very specific, detailed instructions\r\n- Pure research/exploration tasks\r\n\r\n## What Happens in Plan Mode\r\nIn plan mode, you will:\r\n1. Identify 2-3 key questions about the codebase that are critical to your plan. If you are not confident about the codebase structure or relevant code paths, use `Agent(subagent_type=\"explore\")` to investigate these questions first - this is strongly recommended for non-trivial tasks.\r\n2. Explore the codebase using Glob, Grep, Read, and other read-only tools for any remaining quick lookups. Use Bash only when needed; Bash follows the normal permission mode and rules.\r\n3. Design an implementation approach based on your findings (or, for fusion plan, review the synthesized plan the host provides).\r\n4. Write the plan to the current plan file with Write or Edit.\r\n5. Present your plan to the user via ExitPlanMode for approval\r\n\r\nFor fusion plan, the host performs the parallel exploration and synthesis for you; you should still review the result, fill in any gaps, and ensure it matches the user's intent before exiting plan mode.\r\n";
|
|
108548
109592
|
//#endregion
|
|
@@ -108728,7 +109772,7 @@ function formatPlanForOutput(plan, path) {
|
|
|
108728
109772
|
}
|
|
108729
109773
|
//#endregion
|
|
108730
109774
|
//#region ../../packages/agent-core/src/tools/builtin/shell/bash.md
|
|
108731
|
-
var bash_default = "Execute a `{{ SHELL_NAME }}` command. Use this for shell semantics: pipes, env, processes, git, package managers, build/test runners, anything genuinely interactive or multi-step.\n\n**Translate these to a dedicated tool instead:**\n- `cat` / `head` / `tail` (known path): use `Read`\n- `sed` / `awk` (in-place edit): use `Edit`\n- `echo > file` / `cat <<EOF`: use `Write`\n- `find` / recursive `ls` to locate files by name pattern: use `Glob` (plain `ls <known-directory>` is fine for listing a directory)\n- `grep` / `rg` (search file contents): use `Grep`\n- PDF, Word, Excel, CSV, scanned image, or office-document parsing/extraction/conversion: use `DocumentRead` for one file or `DocumentProcess` for one or more files/directories\n- `echo` / `printf` (talk to the user): just output text directly\n\nThe dedicated tools render in the per-tool permission UI and keep raw stdout out of the conversation; that is why they are worth reaching for whenever one fits.\n\nDo not use shell utilities, Python, Node.js, npm/pnpm/npx installs, `pdftotext`, `pdfinfo`, `unzip`, LibreOffice, or ad-hoc scripts to process supported document formats unless the relevant document tool fails or the user explicitly asks for a custom script/toolchain implementation.\n\n**Output:**\nThe stdout and stderr will be combined and returned as a string. The output may be truncated if it is too long. If the command failed, the output will end with a `Command failed with exit code: N` line stating the non-zero exit code.\n\nIf `run_in_background=true`, the command will be started as a background task and this tool will return a task ID instead of waiting for command completion. When doing that, you must provide a short `description`. Background commands default to a {{ DEFAULT_BACKGROUND_TIMEOUT_S }}s timeout and `timeout` is capped at {{ MAX_BACKGROUND_TIMEOUT_S }}s; set `disable_timeout=true` only when the task should run without a timeout. You will be automatically notified when the task completes. Use `TaskOutput` for a non-blocking status/output snapshot, and only set `block=true` when you explicitly want to wait for completion. Use `TaskStop` only if the task must be cancelled. If a human user wants to inspect background tasks themselves, point them to the `/tasks` command, which opens an interactive panel; it has no subcommands.\n\n**Guidelines for safety and security:**\n- Each shell tool call will be executed in a fresh shell environment. The shell variables, current working directory changes, and the shell history is not preserved between calls.\n- The tool call will return after the command is finished. You shall not use this tool to execute an interactive command or a command that may run forever. For possibly long-running foreground commands, set the `timeout` argument in seconds. Foreground commands default to {{ DEFAULT_TIMEOUT_S }}s and allow up to {{ MAX_TIMEOUT_S }}s.\n- Avoid using `..` to access files or directories outside of the working directory.\n- Avoid modifying files outside of the working directory unless explicitly instructed to do so.\n- Never run commands that require superuser privileges unless explicitly instructed to do so.\n\n**Guidelines for efficiency:**\n- For multiple related commands, use `&&` to chain them in a single call, e.g. `cd /path && ls -la`\n- Use `;` to run commands sequentially regardless of success/failure\n- Use `||` for conditional execution (run second command only if first fails)\n- Use pipe operations (`|`) and redirections (`>`, `>>`) to chain input and output between commands\n- Always quote file paths containing spaces with double quotes (e.g., cd \"/path with spaces/\")\n- Compose multi-step logic in a single call with `if` / `case` / `for` / `while` control flows.\n- Prefer `run_in_background=true` for long-running builds, tests, watchers, or servers when you need the conversation to continue before the command finishes.\n\n**Commands available:**\nThe following common command categories are usually available. Availability still depends on the host, so when in doubt run `which <command>` first to confirm a command exists before relying on it.\n- Navigation and inspection: `ls`, `pwd`, `cd`, `stat`, `file`, `du`, `df`, `tree`\n- File and directory management: `cp`, `mv`, `rm`, `mkdir`, `touch`, `ln`, `chmod`, `chown`\n- Text and data processing: `wc`, `sort`, `uniq`, `cut`, `tr`, `diff`, `xargs`\n- Archives and compression: `tar`, `gzip`, `gunzip`, `zip`, `unzip`\n- Networking and transfer: `curl`, `wget`, `ping`, `ssh`, `scp`\n- Version control: `git`\n- Process and system: `ps`, `kill`, `top`, `env`, `date`, `uname`, `whoami`\n- Language and package toolchains: `node`, `npm`, `pnpm`, `yarn`, `python`, `pip` (use whichever the project actually relies on)\n";
|
|
109775
|
+
var bash_default = "Execute a `{{ SHELL_NAME }}` command. Use this for shell semantics: pipes, env, processes, git, package managers, build/test runners, anything genuinely interactive or multi-step.\r\n\r\n**Translate these to a dedicated tool instead:**\r\n- `cat` / `head` / `tail` (known path): use `Read`\r\n- `sed` / `awk` (in-place edit): use `Edit`\r\n- `echo > file` / `cat <<EOF`: use `Write`\r\n- `find` / recursive `ls` to locate files by name pattern: use `Glob` (plain `ls <known-directory>` is fine for listing a directory)\r\n- `grep` / `rg` (search file contents): use `Grep`\r\n- PDF, Word, Excel, CSV, scanned image, or office-document parsing/extraction/conversion: use `DocumentRead` for one file or `DocumentProcess` for one or more files/directories\r\n- `echo` / `printf` (talk to the user): just output text directly\r\n\r\nThe dedicated tools render in the per-tool permission UI and keep raw stdout out of the conversation; that is why they are worth reaching for whenever one fits.\r\n\r\nDo not use shell utilities, Python, Node.js, npm/pnpm/npx installs, `pdftotext`, `pdfinfo`, `unzip`, LibreOffice, or ad-hoc scripts to process supported document formats unless the relevant document tool fails or the user explicitly asks for a custom script/toolchain implementation.\r\n\r\n**Output:**\r\nThe stdout and stderr will be combined and returned as a string. The output may be truncated if it is too long. If the command failed, the output will end with a `Command failed with exit code: N` line stating the non-zero exit code.\r\n\r\nIf `run_in_background=true`, the command will be started as a background task and this tool will return a task ID instead of waiting for command completion. When doing that, you must provide a short `description`. Background commands default to a {{ DEFAULT_BACKGROUND_TIMEOUT_S }}s timeout and `timeout` is capped at {{ MAX_BACKGROUND_TIMEOUT_S }}s; set `disable_timeout=true` only when the task should run without a timeout. You will be automatically notified when the task completes. Use `TaskOutput` for a non-blocking status/output snapshot, and only set `block=true` when you explicitly want to wait for completion. Use `TaskStop` only if the task must be cancelled. If a human user wants to inspect background tasks themselves, point them to the `/tasks` command, which opens an interactive panel; it has no subcommands.\r\n\r\n**Guidelines for safety and security:**\r\n- Each shell tool call will be executed in a fresh shell environment. The shell variables, current working directory changes, and the shell history is not preserved between calls.\r\n- The tool call will return after the command is finished. You shall not use this tool to execute an interactive command or a command that may run forever. For possibly long-running foreground commands, set the `timeout` argument in seconds. Foreground commands default to {{ DEFAULT_TIMEOUT_S }}s and allow up to {{ MAX_TIMEOUT_S }}s.\r\n- Avoid using `..` to access files or directories outside of the working directory.\r\n- Avoid modifying files outside of the working directory unless explicitly instructed to do so.\r\n- Never run commands that require superuser privileges unless explicitly instructed to do so.\r\n\r\n**Guidelines for efficiency:**\r\n- For multiple related commands, use `&&` to chain them in a single call, e.g. `cd /path && ls -la`\r\n- Use `;` to run commands sequentially regardless of success/failure\r\n- Use `||` for conditional execution (run second command only if first fails)\r\n- Use pipe operations (`|`) and redirections (`>`, `>>`) to chain input and output between commands\r\n- Always quote file paths containing spaces with double quotes (e.g., cd \"/path with spaces/\")\r\n- Compose multi-step logic in a single call with `if` / `case` / `for` / `while` control flows.\r\n- Prefer `run_in_background=true` for long-running builds, tests, watchers, or servers when you need the conversation to continue before the command finishes.\r\n\r\n**Commands available:**\r\nThe following common command categories are usually available. Availability still depends on the host, so when in doubt run `which <command>` first to confirm a command exists before relying on it.\r\n- Navigation and inspection: `ls`, `pwd`, `cd`, `stat`, `file`, `du`, `df`, `tree`\r\n- File and directory management: `cp`, `mv`, `rm`, `mkdir`, `touch`, `ln`, `chmod`, `chown`\r\n- Text and data processing: `wc`, `sort`, `uniq`, `cut`, `tr`, `diff`, `xargs`\r\n- Archives and compression: `tar`, `gzip`, `gunzip`, `zip`, `unzip`\r\n- Networking and transfer: `curl`, `wget`, `ping`, `ssh`, `scp`\r\n- Version control: `git`\r\n- Process and system: `ps`, `kill`, `top`, `env`, `date`, `uname`, `whoami`\r\n- Language and package toolchains: `node`, `npm`, `pnpm`, `yarn`, `python`, `pip` (use whichever the project actually relies on)\r\n";
|
|
108732
109776
|
//#endregion
|
|
108733
109777
|
//#region ../../packages/agent-core/src/tools/builtin/shell/bash.ts
|
|
108734
109778
|
const MS_PER_SECOND = 1e3;
|
|
@@ -108822,6 +109866,12 @@ const ANTI_PATTERNS = [
|
|
|
108822
109866
|
pattern: /(^|[;&]|\$\()\s*(python|python3|py|node|bun|tsx|npx|npm|pnpm)\b[^\n;&|]*\.(pdf|docx?|xlsx?|csv|png|jpe?g|gif|webp|tiff?)\b/i,
|
|
108823
109867
|
hint: "Use DocumentRead or DocumentProcess for supported document formats instead of ad-hoc Python/Node/npm document processing."
|
|
108824
109868
|
},
|
|
109869
|
+
{
|
|
109870
|
+
name: "probe document OCR dependencies via shell",
|
|
109871
|
+
tools: ["DocumentRead", "DocumentProcess"],
|
|
109872
|
+
pattern: /(^|[;&]|\$\()\s*((python|python3|py)\s+-m\s+pip|pip3?|npm|pnpm|npx|bun|uv|conda)\b[^\n]*(pdf|ocr|tesseract|paddle|pymupdf|fitz|opencv|pillow|docx?|xlsx?|excel)/i,
|
|
109873
|
+
hint: "Use DocumentRead or DocumentProcess for document/OCR work; Nexum includes OCR support and should not probe or install document parsers through shell package managers."
|
|
109874
|
+
},
|
|
108825
109875
|
{
|
|
108826
109876
|
name: "edit files via sed/perl/awk",
|
|
108827
109877
|
tools: ["Edit"],
|
|
@@ -109607,6 +110657,39 @@ function buildBackgroundTaskNotificationBody(info, isAgentTask) {
|
|
|
109607
110657
|
].join("\n")}`;
|
|
109608
110658
|
}
|
|
109609
110659
|
//#endregion
|
|
110660
|
+
//#region ../../packages/agent-core/src/agent/memory/promotion.ts
|
|
110661
|
+
function createMemoryPromotionCursor(initial = []) {
|
|
110662
|
+
const fingerprints = new Set(initial);
|
|
110663
|
+
return {
|
|
110664
|
+
has(fingerprint) {
|
|
110665
|
+
return fingerprints.has(fingerprint);
|
|
110666
|
+
},
|
|
110667
|
+
mark(fingerprint) {
|
|
110668
|
+
fingerprints.add(fingerprint);
|
|
110669
|
+
},
|
|
110670
|
+
reset() {
|
|
110671
|
+
fingerprints.clear();
|
|
110672
|
+
},
|
|
110673
|
+
fingerprints() {
|
|
110674
|
+
return Array.from(fingerprints);
|
|
110675
|
+
}
|
|
110676
|
+
};
|
|
110677
|
+
}
|
|
110678
|
+
/**
|
|
110679
|
+
* Compute a stable fingerprint for a chunk of conversation material that will
|
|
110680
|
+
* be summarized into memory memos.
|
|
110681
|
+
*/
|
|
110682
|
+
function computeMemorySourceFingerprint(sourceSessionId, material) {
|
|
110683
|
+
const text = `${sourceSessionId}\0${material}`;
|
|
110684
|
+
let hash = 0;
|
|
110685
|
+
for (let i = 0; i < text.length; i++) {
|
|
110686
|
+
const char = text.charCodeAt(i);
|
|
110687
|
+
hash = (hash << 5) - hash + char;
|
|
110688
|
+
hash |= 0;
|
|
110689
|
+
}
|
|
110690
|
+
return `memosrc-${Math.abs(hash).toString(36)}`;
|
|
110691
|
+
}
|
|
110692
|
+
//#endregion
|
|
109610
110693
|
//#region ../../node_modules/.pnpm/@antfu+utils@9.3.0/node_modules/@antfu/utils/dist/index.mjs
|
|
109611
110694
|
function uniq(array) {
|
|
109612
110695
|
return Array.from(new Set(array));
|
|
@@ -109964,6 +111047,7 @@ const MAX_CONSECUTIVE_FAILURES = 3;
|
|
|
109964
111047
|
const COMPACTION_SYSTEM_PROMPT = "You are a conversation context compaction assistant. Your job is to summarize the conversation above into a structured summary. Output text only. DO NOT CALL ANY TOOLS. Follow the compaction instruction in the last user message exactly. Pay special attention to the Memory Memo Extraction section — you MUST output memory-memo blocks for every completed task loop.";
|
|
109965
111048
|
var FullCompaction = class {
|
|
109966
111049
|
agent;
|
|
111050
|
+
memoryPromotionCursor;
|
|
109967
111051
|
compactionCountInTurn = 0;
|
|
109968
111052
|
consecutiveCompactionFailures = 0;
|
|
109969
111053
|
_shouldInjectSessionSummary = false;
|
|
@@ -109971,8 +111055,9 @@ var FullCompaction = class {
|
|
|
109971
111055
|
compacting = null;
|
|
109972
111056
|
_compactedHistory = [];
|
|
109973
111057
|
strategy;
|
|
109974
|
-
constructor(agent, strategy) {
|
|
111058
|
+
constructor(agent, strategy, memoryPromotionCursor) {
|
|
109975
111059
|
this.agent = agent;
|
|
111060
|
+
this.memoryPromotionCursor = memoryPromotionCursor;
|
|
109976
111061
|
this.strategy = strategy ?? new DefaultCompactionStrategy(() => agent.config.modelCapabilities.max_context_tokens, {
|
|
109977
111062
|
...DEFAULT_COMPACTION_CONFIG,
|
|
109978
111063
|
reservedContextSize: agent.nexumConfig?.loopControl?.reservedContextSize ?? DEFAULT_COMPACTION_CONFIG.reservedContextSize,
|
|
@@ -110251,11 +111336,16 @@ var FullCompaction = class {
|
|
|
110251
111336
|
this.agent.log.info("Memory memo store not available, skipping extraction");
|
|
110252
111337
|
return;
|
|
110253
111338
|
}
|
|
111339
|
+
const sessionId = this.agent.homedir ? basename$1(dirname$2(dirname$2(this.agent.homedir))) : "unknown";
|
|
111340
|
+
const fingerprint = computeMemorySourceFingerprint(sessionId, summary);
|
|
111341
|
+
if (this.memoryPromotionCursor?.has(fingerprint) === true) {
|
|
111342
|
+
this.agent.log.info("Compaction summary already promoted, skipping memo extraction");
|
|
111343
|
+
return;
|
|
111344
|
+
}
|
|
110254
111345
|
this.agent.log.info("Scanning compaction summary for memory memos", { summaryLen: summary.length });
|
|
110255
111346
|
const memos = parseMemoryMemos(summary);
|
|
110256
111347
|
this.agent.log.info("Memory memo parse result", { memoCount: memos.length });
|
|
110257
111348
|
if (memos.length === 0) return;
|
|
110258
|
-
const sessionId = this.agent.homedir ? basename$1(dirname$2(dirname$2(this.agent.homedir))) : "unknown";
|
|
110259
111349
|
const sessionTitle = await this.agent.getSessionTitle();
|
|
110260
111350
|
const failed = (await Promise.allSettled(memos.map((memo) => {
|
|
110261
111351
|
memo.sourceSessionId = sessionId;
|
|
@@ -110267,6 +111357,7 @@ var FullCompaction = class {
|
|
|
110267
111357
|
failed,
|
|
110268
111358
|
total: memos.length
|
|
110269
111359
|
});
|
|
111360
|
+
this.memoryPromotionCursor?.mark(fingerprint);
|
|
110270
111361
|
this.agent.log.info("Extracted memory memos from compaction", {
|
|
110271
111362
|
count: memos.length,
|
|
110272
111363
|
sessionId
|
|
@@ -113072,15 +114163,24 @@ var DynamicInjector = class {
|
|
|
113072
114163
|
if (index < this.injectedAt) this.injectedAt--;
|
|
113073
114164
|
else if (index === this.injectedAt) this.injectedAt = null;
|
|
113074
114165
|
}
|
|
113075
|
-
|
|
113076
|
-
|
|
113077
|
-
|
|
113078
|
-
|
|
113079
|
-
|
|
113080
|
-
|
|
113081
|
-
|
|
113082
|
-
|
|
113083
|
-
|
|
114166
|
+
/**
|
|
114167
|
+
* Marks this injector as having injected at the given history index.
|
|
114168
|
+
* Called by InjectionManager after a record is accepted.
|
|
114169
|
+
*/
|
|
114170
|
+
markInjected(at) {
|
|
114171
|
+
this.injectedAt = at;
|
|
114172
|
+
}
|
|
114173
|
+
/**
|
|
114174
|
+
* Helper to build an injection record with auto-estimated token cost.
|
|
114175
|
+
*/
|
|
114176
|
+
buildRecord(content, priority, overrides) {
|
|
114177
|
+
return {
|
|
114178
|
+
variant: this.injectionVariant,
|
|
114179
|
+
content,
|
|
114180
|
+
priority,
|
|
114181
|
+
estimatedTokenCost: estimateTokens$1(content),
|
|
114182
|
+
...overrides
|
|
114183
|
+
};
|
|
113084
114184
|
}
|
|
113085
114185
|
};
|
|
113086
114186
|
//#endregion
|
|
@@ -113088,15 +114188,18 @@ var DynamicInjector = class {
|
|
|
113088
114188
|
const GOAL_REMINDER_INTERVAL = 5;
|
|
113089
114189
|
var GoalInjector = class extends DynamicInjector {
|
|
113090
114190
|
injectionVariant = "goal";
|
|
113091
|
-
|
|
114191
|
+
inject() {
|
|
113092
114192
|
const goal = this.agent.goal.getGoal().goal;
|
|
113093
114193
|
if (goal === null) return void 0;
|
|
113094
114194
|
if (this.injectedAt !== null) {
|
|
113095
114195
|
if (this.countAssistantTurnsSince(this.injectedAt) < GOAL_REMINDER_INTERVAL) return void 0;
|
|
113096
114196
|
}
|
|
113097
|
-
|
|
113098
|
-
if (goal.status === "
|
|
113099
|
-
if (goal.status === "
|
|
114197
|
+
let content;
|
|
114198
|
+
if (goal.status === "active") content = buildGoalReminder(goal);
|
|
114199
|
+
else if (goal.status === "blocked") content = buildBlockedNote(goal);
|
|
114200
|
+
else if (goal.status === "paused") content = buildPausedNote(goal);
|
|
114201
|
+
else return void 0;
|
|
114202
|
+
return this.buildRecord(content, 50);
|
|
113100
114203
|
}
|
|
113101
114204
|
countAssistantTurnsSince(from) {
|
|
113102
114205
|
let count = 0;
|
|
@@ -113194,20 +114297,20 @@ const AUTO_MODE_EXIT_REMINDER = ["Auto permission mode is no longer active. Tool
|
|
|
113194
114297
|
var PermissionModeInjector = class extends DynamicInjector {
|
|
113195
114298
|
injectionVariant = "permission_mode";
|
|
113196
114299
|
lastMode;
|
|
113197
|
-
|
|
114300
|
+
inject() {
|
|
113198
114301
|
const mode = this.agent.permission.mode;
|
|
113199
114302
|
const previousMode = this.lastMode;
|
|
113200
114303
|
if (mode === previousMode) return void 0;
|
|
113201
114304
|
this.lastMode = mode;
|
|
113202
|
-
if (mode === "auto") return AUTO_MODE_ENTER_REMINDER;
|
|
113203
|
-
if (previousMode === "auto") return AUTO_MODE_EXIT_REMINDER;
|
|
114305
|
+
if (mode === "auto") return this.buildRecord(AUTO_MODE_ENTER_REMINDER, 70);
|
|
114306
|
+
if (previousMode === "auto") return this.buildRecord(AUTO_MODE_EXIT_REMINDER, 70);
|
|
113204
114307
|
}
|
|
113205
114308
|
};
|
|
113206
114309
|
//#endregion
|
|
113207
114310
|
//#region ../../packages/agent-core/src/agent/injection/plugin-session-start.ts
|
|
113208
114311
|
var PluginSessionStartInjector = class extends DynamicInjector {
|
|
113209
114312
|
injectionVariant = "plugin_session_start";
|
|
113210
|
-
async
|
|
114313
|
+
async inject() {
|
|
113211
114314
|
if (this.injectedAt !== null) return void 0;
|
|
113212
114315
|
const replayedAt = this.agent.context.history.findIndex((message) => message.origin?.kind === "injection" && message.origin.variant === this.injectionVariant);
|
|
113213
114316
|
if (replayedAt >= 0) {
|
|
@@ -113231,7 +114334,7 @@ var PluginSessionStartInjector = class extends DynamicInjector {
|
|
|
113231
114334
|
blocks.push(renderSessionStartBlock(sessionStart, skill, registry.renderSkillPrompt(skill, "")));
|
|
113232
114335
|
}
|
|
113233
114336
|
if (blocks.length === 0) return void 0;
|
|
113234
|
-
return blocks.join("\n");
|
|
114337
|
+
return this.buildRecord(blocks.join("\n"), 100);
|
|
113235
114338
|
}
|
|
113236
114339
|
};
|
|
113237
114340
|
function renderSessionStartBlock(sessionStart, skill, skillContent) {
|
|
@@ -113251,22 +114354,23 @@ var PlanModeInjector = class extends DynamicInjector {
|
|
|
113251
114354
|
super.onContextClear();
|
|
113252
114355
|
this.wasActive = this.agent.planMode.isActive;
|
|
113253
114356
|
}
|
|
113254
|
-
async
|
|
114357
|
+
async inject() {
|
|
113255
114358
|
const { isActive, planFilePath } = this.agent.planMode;
|
|
113256
114359
|
if (!isActive) {
|
|
113257
114360
|
if (!this.wasActive) return;
|
|
113258
114361
|
this.wasActive = false;
|
|
113259
114362
|
this.injectedAt = null;
|
|
113260
|
-
return exitReminder();
|
|
114363
|
+
return this.buildRecord(exitReminder(), 80);
|
|
113261
114364
|
}
|
|
113262
114365
|
if (!this.wasActive) {
|
|
113263
114366
|
this.injectedAt = null;
|
|
113264
114367
|
this.wasActive = true;
|
|
113265
|
-
if (await this.hasCurrentPlanContent()) return reentryReminder(planFilePath);
|
|
114368
|
+
if (await this.hasCurrentPlanContent()) return this.buildRecord(reentryReminder(planFilePath), 80);
|
|
113266
114369
|
}
|
|
113267
114370
|
const variant = this.getVariant();
|
|
113268
114371
|
if (variant === null) return void 0;
|
|
113269
|
-
|
|
114372
|
+
const content = variant === "full" ? fullReminder(planFilePath) : variant === "sparse" ? sparseReminder(planFilePath) : reentryReminder(planFilePath);
|
|
114373
|
+
return this.buildRecord(content, 80);
|
|
113270
114374
|
}
|
|
113271
114375
|
getVariant() {
|
|
113272
114376
|
if (this.injectedAt === null) return "full";
|
|
@@ -113394,11 +114498,11 @@ const TODO_LIST_REMINDER_TURNS_BETWEEN_REMINDERS = 10;
|
|
|
113394
114498
|
*/
|
|
113395
114499
|
var TodoListReminderInjector = class extends DynamicInjector {
|
|
113396
114500
|
injectionVariant = TODO_LIST_REMINDER_VARIANT;
|
|
113397
|
-
|
|
114501
|
+
inject() {
|
|
113398
114502
|
if (!this.isTodoListActive()) return void 0;
|
|
113399
114503
|
const counts = getTodoListReminderTurnCounts(this.agent.context.history);
|
|
113400
114504
|
if (counts.turnsSinceLastWrite < TODO_LIST_REMINDER_TURNS_SINCE_WRITE || counts.turnsSinceLastReminder < TODO_LIST_REMINDER_TURNS_BETWEEN_REMINDERS) return;
|
|
113401
|
-
return renderTodoListReminder(this.currentTodos());
|
|
114505
|
+
return this.buildRecord(renderTodoListReminder(this.currentTodos()), 60);
|
|
113402
114506
|
}
|
|
113403
114507
|
isTodoListActive() {
|
|
113404
114508
|
return this.agent.tools.data().some((tool) => {
|
|
@@ -113492,19 +114596,19 @@ const WOLFPACK_MODE_EXIT_REMINDER = "WolfPack mode is no longer active. The Wolf
|
|
|
113492
114596
|
var WolfPackModeInjector = class extends DynamicInjector {
|
|
113493
114597
|
injectionVariant = "wolfpack";
|
|
113494
114598
|
wasActive = false;
|
|
113495
|
-
|
|
114599
|
+
inject() {
|
|
113496
114600
|
if (!this.agent.wolfpackMode.isActive) {
|
|
113497
114601
|
if (this.wasActive) {
|
|
113498
114602
|
this.wasActive = false;
|
|
113499
114603
|
this.injectedAt = null;
|
|
113500
|
-
return WOLFPACK_MODE_EXIT_REMINDER;
|
|
114604
|
+
return this.buildRecord(WOLFPACK_MODE_EXIT_REMINDER, 90);
|
|
113501
114605
|
}
|
|
113502
114606
|
return;
|
|
113503
114607
|
}
|
|
113504
114608
|
if (!this.wasActive) {
|
|
113505
114609
|
this.injectedAt = null;
|
|
113506
114610
|
this.wasActive = true;
|
|
113507
|
-
return WOLFPACK_MODE_ENTER_REMINDER;
|
|
114611
|
+
return this.buildRecord(WOLFPACK_MODE_ENTER_REMINDER, 90);
|
|
113508
114612
|
}
|
|
113509
114613
|
}
|
|
113510
114614
|
};
|
|
@@ -113513,13 +114617,13 @@ var WolfPackModeInjector = class extends DynamicInjector {
|
|
|
113513
114617
|
const WORKING_SET_REMINDER_INTERVAL = 3;
|
|
113514
114618
|
var WorkingSetInjector = class extends DynamicInjector {
|
|
113515
114619
|
injectionVariant = "working-set";
|
|
113516
|
-
|
|
114620
|
+
inject() {
|
|
113517
114621
|
const paths = this.agent.workingSet.getPaths();
|
|
113518
114622
|
if (paths.length === 0) return void 0;
|
|
113519
114623
|
if (this.injectedAt !== null) {
|
|
113520
114624
|
if (this.countAssistantTurnsSince(this.injectedAt) < WORKING_SET_REMINDER_INTERVAL) return void 0;
|
|
113521
114625
|
}
|
|
113522
|
-
|
|
114626
|
+
const content = [
|
|
113523
114627
|
"## Working Set",
|
|
113524
114628
|
"",
|
|
113525
114629
|
"当前任务可能涉及以下文件:",
|
|
@@ -113527,6 +114631,7 @@ var WorkingSetInjector = class extends DynamicInjector {
|
|
|
113527
114631
|
"",
|
|
113528
114632
|
"优先检查这些文件,避免重复读取未修改文件。"
|
|
113529
114633
|
].join("\n");
|
|
114634
|
+
return this.buildRecord(content, 40);
|
|
113530
114635
|
}
|
|
113531
114636
|
countAssistantTurnsSince(from) {
|
|
113532
114637
|
let count = 0;
|
|
@@ -113537,6 +114642,21 @@ var WorkingSetInjector = class extends DynamicInjector {
|
|
|
113537
114642
|
};
|
|
113538
114643
|
//#endregion
|
|
113539
114644
|
//#region ../../packages/agent-core/src/agent/injection/manager.ts
|
|
114645
|
+
/** Default token headroom reserved for the LLM response and next-step growth. */
|
|
114646
|
+
const RESPONSE_HEADROOM_TOKENS = 2e3;
|
|
114647
|
+
/** Default injection budget as a fraction of the available context window. */
|
|
114648
|
+
const DEFAULT_INJECTION_BUDGET_FRACTION = .25;
|
|
114649
|
+
/** Priority boost applied to records whose variant matches the current intent. */
|
|
114650
|
+
const INTENT_PRIORITY_BOOST = 25;
|
|
114651
|
+
/** Intent → variants that should be boosted for that intent. */
|
|
114652
|
+
const INTENT_VARIANT_BOOSTS = {
|
|
114653
|
+
debug: ["working-set", "goal"],
|
|
114654
|
+
test: ["working-set", "goal"],
|
|
114655
|
+
edit: ["working-set", "goal"],
|
|
114656
|
+
plan: ["plan_mode"],
|
|
114657
|
+
explore: ["working-set"],
|
|
114658
|
+
remember: ["goal"]
|
|
114659
|
+
};
|
|
113540
114660
|
var InjectionManager = class {
|
|
113541
114661
|
agent;
|
|
113542
114662
|
injectors;
|
|
@@ -113552,10 +114672,26 @@ var InjectionManager = class {
|
|
|
113552
114672
|
new WorkingSetInjector(agent)
|
|
113553
114673
|
];
|
|
113554
114674
|
}
|
|
113555
|
-
async inject() {
|
|
113556
|
-
|
|
114675
|
+
async inject(intent) {
|
|
114676
|
+
const records = [];
|
|
114677
|
+
for (const injector of this.injectors) {
|
|
114678
|
+
const record = await injector.inject();
|
|
114679
|
+
if (record) records.push(record);
|
|
114680
|
+
}
|
|
114681
|
+
const budget = this.computeBudget();
|
|
114682
|
+
const selected = this.selectRecords(records, intent, budget);
|
|
114683
|
+
for (const record of selected) {
|
|
114684
|
+
const injector = this.injectors.find((i) => i.injectionVariant === record.variant);
|
|
114685
|
+
this.agent.context.appendSystemReminder(record.content, {
|
|
114686
|
+
kind: "injection",
|
|
114687
|
+
variant: record.variant
|
|
114688
|
+
});
|
|
114689
|
+
if (injector !== void 0) injector.markInjected(this.agent.context.history.length - 1);
|
|
114690
|
+
}
|
|
113557
114691
|
}
|
|
113558
|
-
/**
|
|
114692
|
+
/**
|
|
114693
|
+
* Resets per-turn injection state. Called at the beginning of each turn.
|
|
114694
|
+
*/
|
|
113559
114695
|
resetForTurn() {}
|
|
113560
114696
|
onContextClear() {
|
|
113561
114697
|
for (const injector of this.injectors) injector.onContextClear();
|
|
@@ -113574,6 +114710,37 @@ var InjectionManager = class {
|
|
|
113574
114710
|
continue;
|
|
113575
114711
|
}
|
|
113576
114712
|
}
|
|
114713
|
+
/**
|
|
114714
|
+
* Returns the current injection budget. The budget is a fraction of the
|
|
114715
|
+
* available context window after accounting for current usage and a response
|
|
114716
|
+
* headroom.
|
|
114717
|
+
*/
|
|
114718
|
+
computeBudget() {
|
|
114719
|
+
const maxContextTokens = this.agent.config.modelCapabilities.max_context_tokens;
|
|
114720
|
+
if (maxContextTokens <= 0) return 4e3;
|
|
114721
|
+
const available = Math.max(0, maxContextTokens - this.agent.context.tokenCount - RESPONSE_HEADROOM_TOKENS);
|
|
114722
|
+
return Math.max(0, Math.floor(available * DEFAULT_INJECTION_BUDGET_FRACTION));
|
|
114723
|
+
}
|
|
114724
|
+
/**
|
|
114725
|
+
* Sort and prune records according to the current intent and budget.
|
|
114726
|
+
*/
|
|
114727
|
+
selectRecords(records, intent, budget) {
|
|
114728
|
+
const boosted = new Set(intent ? INTENT_VARIANT_BOOSTS[intent.toLowerCase()] ?? [] : []);
|
|
114729
|
+
const sorted = records.map((record) => ({
|
|
114730
|
+
...record,
|
|
114731
|
+
priority: boosted.has(record.variant) ? record.priority + INTENT_PRIORITY_BOOST : record.priority
|
|
114732
|
+
})).sort((a, b) => b.priority - a.priority);
|
|
114733
|
+
const selected = [];
|
|
114734
|
+
let used = 0;
|
|
114735
|
+
for (const record of sorted) {
|
|
114736
|
+
const cost = record.estimatedTokenCost ?? estimateTokens$1(record.content);
|
|
114737
|
+
if (used + cost <= budget) {
|
|
114738
|
+
selected.push(record);
|
|
114739
|
+
used += cost;
|
|
114740
|
+
}
|
|
114741
|
+
}
|
|
114742
|
+
return selected;
|
|
114743
|
+
}
|
|
113577
114744
|
};
|
|
113578
114745
|
//#endregion
|
|
113579
114746
|
//#region ../../packages/agent-core/src/agent/permission/policies/auto-mode-approve.ts
|
|
@@ -113609,6 +114776,9 @@ var AutoModeAskUserQuestionDenyPermissionPolicy = class {
|
|
|
113609
114776
|
//#region ../../packages/agent-core/src/agent/permission/policies/default-tool-approve.ts
|
|
113610
114777
|
const DEFAULT_APPROVE_TOOLS = {
|
|
113611
114778
|
Read: true,
|
|
114779
|
+
ReadGroup: true,
|
|
114780
|
+
ReadChunk: true,
|
|
114781
|
+
SummarizeOutput: true,
|
|
113612
114782
|
Grep: true,
|
|
113613
114783
|
Glob: true,
|
|
113614
114784
|
ReadMediaFile: true,
|
|
@@ -113629,7 +114799,12 @@ const DEFAULT_APPROVE_TOOLS = {
|
|
|
113629
114799
|
SetGoalBudget: true,
|
|
113630
114800
|
WriteGoalNote: true,
|
|
113631
114801
|
MakeSkillPlan: true,
|
|
113632
|
-
MakeSkillApply: true
|
|
114802
|
+
MakeSkillApply: true,
|
|
114803
|
+
GetActiveTools: true,
|
|
114804
|
+
GetToolsByCapability: true,
|
|
114805
|
+
GetContextUsage: true,
|
|
114806
|
+
GetWorkingSet: true,
|
|
114807
|
+
GetPlanState: true
|
|
113633
114808
|
};
|
|
113634
114809
|
var DefaultToolApprovePermissionPolicy = class {
|
|
113635
114810
|
name = "default-tool-approve";
|
|
@@ -115635,6 +116810,9 @@ function restoreAgentRecord(agent, input) {
|
|
|
115635
116810
|
case "goal.clear":
|
|
115636
116811
|
agent.goal.restoreClear(input);
|
|
115637
116812
|
return;
|
|
116813
|
+
case "goal.note":
|
|
116814
|
+
agent.goal.restoreNote(input);
|
|
116815
|
+
return;
|
|
115638
116816
|
case "context.append_message":
|
|
115639
116817
|
agent.context.appendMessage(input.message);
|
|
115640
116818
|
return;
|
|
@@ -115797,6 +116975,166 @@ var SkillManager = class {
|
|
|
115797
116975
|
}
|
|
115798
116976
|
};
|
|
115799
116977
|
//#endregion
|
|
116978
|
+
//#region ../../packages/agent-core/src/loop/resource-ledger.ts
|
|
116979
|
+
/**
|
|
116980
|
+
* Compare two cursors lexicographically. Returns a negative number if `left`
|
|
116981
|
+
* is earlier, zero if equal, and a positive number if `left` is later.
|
|
116982
|
+
*/
|
|
116983
|
+
function compareCursor(left, right) {
|
|
116984
|
+
if (left.turnId !== right.turnId) return left.turnId.localeCompare(right.turnId);
|
|
116985
|
+
return left.stepNumber - right.stepNumber;
|
|
116986
|
+
}
|
|
116987
|
+
/**
|
|
116988
|
+
* Cross-turn resource ledger.
|
|
116989
|
+
*
|
|
116990
|
+
* Tracks file/resource accesses across the lifetime of a session so the agent
|
|
116991
|
+
* can:
|
|
116992
|
+
* - detect stale reads (a read after a previous write to the same path),
|
|
116993
|
+
* - skip redundant reads when the file has not changed since the last read,
|
|
116994
|
+
* - reason about which files have been touched or verified in the current turn.
|
|
116995
|
+
*
|
|
116996
|
+
* The ledger does not perform I/O itself; it normalizes paths using
|
|
116997
|
+
* {@link ToolAccesses.normalizePath} and accepts resolved paths when available.
|
|
116998
|
+
*/
|
|
116999
|
+
var ResourceLedger = class {
|
|
117000
|
+
entries = [];
|
|
117001
|
+
options;
|
|
117002
|
+
constructor(options) {
|
|
117003
|
+
this.options = options ?? {};
|
|
117004
|
+
}
|
|
117005
|
+
/**
|
|
117006
|
+
* Register that a tool is about to start. Returns the entry, which should be
|
|
117007
|
+
* marked completed via {@link complete} when the tool finishes.
|
|
117008
|
+
*/
|
|
117009
|
+
register(turnId, stepNumber, toolCallId, accesses) {
|
|
117010
|
+
const entry = {
|
|
117011
|
+
turnId,
|
|
117012
|
+
stepNumber,
|
|
117013
|
+
toolCallId,
|
|
117014
|
+
accesses,
|
|
117015
|
+
resolvedPaths: extractNormalizedPaths(accesses, this.options),
|
|
117016
|
+
status: "active"
|
|
117017
|
+
};
|
|
117018
|
+
this.entries.push(entry);
|
|
117019
|
+
return entry;
|
|
117020
|
+
}
|
|
117021
|
+
/** Mark a previously registered entry as completed. */
|
|
117022
|
+
complete(toolCallId) {
|
|
117023
|
+
const entry = this.entries.find((e) => e.toolCallId === toolCallId && e.status === "active");
|
|
117024
|
+
if (entry !== void 0) entry.status = "completed";
|
|
117025
|
+
}
|
|
117026
|
+
/**
|
|
117027
|
+
* Remove an entry entirely (e.g. when a tool was cancelled before it could be
|
|
117028
|
+
* observed as completed).
|
|
117029
|
+
*/
|
|
117030
|
+
remove(toolCallId) {
|
|
117031
|
+
const index = this.entries.findIndex((e) => e.toolCallId === toolCallId);
|
|
117032
|
+
if (index >= 0) this.entries.splice(index, 1);
|
|
117033
|
+
}
|
|
117034
|
+
/** Drop all entries. Useful on session resume or major context reset. */
|
|
117035
|
+
reset() {
|
|
117036
|
+
this.entries.length = 0;
|
|
117037
|
+
}
|
|
117038
|
+
/**
|
|
117039
|
+
* Return the most recent completed write to `path` at or before the given
|
|
117040
|
+
* cursor.
|
|
117041
|
+
*/
|
|
117042
|
+
lastWrite(path, options) {
|
|
117043
|
+
return this.findLast(path, options ?? {}, (entry, normalized) => accessWritesPath(entry.accesses, normalized, this.options));
|
|
117044
|
+
}
|
|
117045
|
+
/**
|
|
117046
|
+
* Return the most recent completed read of `path` at or before the given
|
|
117047
|
+
* cursor.
|
|
117048
|
+
*/
|
|
117049
|
+
lastRead(path, options) {
|
|
117050
|
+
return this.findLast(path, options ?? {}, (entry, normalized) => accessReadsPath(entry.accesses, normalized, this.options));
|
|
117051
|
+
}
|
|
117052
|
+
findLast(path, options, matches) {
|
|
117053
|
+
const normalized = ToolAccesses.normalizePath(path, this.options);
|
|
117054
|
+
const before = options.before;
|
|
117055
|
+
const inclusive = options.inclusive ?? false;
|
|
117056
|
+
for (let i = this.entries.length - 1; i >= 0; i--) {
|
|
117057
|
+
const entry = this.entries[i];
|
|
117058
|
+
if (entry === void 0) continue;
|
|
117059
|
+
if (entry.status !== "completed") continue;
|
|
117060
|
+
if (!matches(entry, normalized)) continue;
|
|
117061
|
+
if (before !== void 0 && !isBeforeOrAt(entry, before, inclusive)) continue;
|
|
117062
|
+
return entry;
|
|
117063
|
+
}
|
|
117064
|
+
}
|
|
117065
|
+
/**
|
|
117066
|
+
* Return true if reading `path` after `since` would be stale because the file
|
|
117067
|
+
* was written later.
|
|
117068
|
+
*/
|
|
117069
|
+
isReadStale(path, since) {
|
|
117070
|
+
const normalized = ToolAccesses.normalizePath(path, this.options);
|
|
117071
|
+
const write = this.lastWrite(normalized);
|
|
117072
|
+
if (write === void 0) return false;
|
|
117073
|
+
return isAfter(write, since);
|
|
117074
|
+
}
|
|
117075
|
+
/**
|
|
117076
|
+
* Find a previous completed read of `path` that is still fresh (no write
|
|
117077
|
+
* happened after it). Returns the matching ledger entry or undefined.
|
|
117078
|
+
*/
|
|
117079
|
+
findFreshRead(path, at) {
|
|
117080
|
+
const normalized = ToolAccesses.normalizePath(path, this.options);
|
|
117081
|
+
const read = this.lastRead(normalized);
|
|
117082
|
+
if (read === void 0) return void 0;
|
|
117083
|
+
const write = this.lastWrite(normalized);
|
|
117084
|
+
if (write === void 0) return read;
|
|
117085
|
+
if (isAfter(write, read)) return void 0;
|
|
117086
|
+
return read;
|
|
117087
|
+
}
|
|
117088
|
+
/**
|
|
117089
|
+
* Return all file paths touched (read or written) during the given turn.
|
|
117090
|
+
*/
|
|
117091
|
+
pathsTouchedInTurn(turnId) {
|
|
117092
|
+
const paths = /* @__PURE__ */ new Set();
|
|
117093
|
+
for (const entry of this.entries) {
|
|
117094
|
+
if (entry.turnId !== turnId) continue;
|
|
117095
|
+
for (const p of entry.resolvedPaths) paths.add(p);
|
|
117096
|
+
}
|
|
117097
|
+
return paths;
|
|
117098
|
+
}
|
|
117099
|
+
/** Return all entries for debugging/observability. */
|
|
117100
|
+
allEntries() {
|
|
117101
|
+
return this.entries;
|
|
117102
|
+
}
|
|
117103
|
+
};
|
|
117104
|
+
function isBeforeOrAt(entry, cursor, inclusive) {
|
|
117105
|
+
const cmp = compareCursor(entry, cursor);
|
|
117106
|
+
return inclusive ? cmp <= 0 : cmp < 0;
|
|
117107
|
+
}
|
|
117108
|
+
function isAfter(entry, cursor) {
|
|
117109
|
+
return compareCursor(entry, cursor) > 0;
|
|
117110
|
+
}
|
|
117111
|
+
function extractNormalizedPaths(accesses, options) {
|
|
117112
|
+
const paths = /* @__PURE__ */ new Set();
|
|
117113
|
+
for (const access of accesses) if (access.kind === "file") paths.add(ToolAccesses.normalizePath(access.path, options));
|
|
117114
|
+
return paths;
|
|
117115
|
+
}
|
|
117116
|
+
function accessWritesPath(accesses, normalizedPath, options) {
|
|
117117
|
+
return accesses.some((access) => fileAccessMatches(access, normalizedPath, ["write", "readwrite"], options));
|
|
117118
|
+
}
|
|
117119
|
+
function accessReadsPath(accesses, normalizedPath, options) {
|
|
117120
|
+
return accesses.some((access) => fileAccessMatches(access, normalizedPath, [
|
|
117121
|
+
"read",
|
|
117122
|
+
"readwrite",
|
|
117123
|
+
"search"
|
|
117124
|
+
], options));
|
|
117125
|
+
}
|
|
117126
|
+
function fileAccessMatches(access, normalizedPath, operations, options) {
|
|
117127
|
+
if (access.kind !== "file") return false;
|
|
117128
|
+
if (!operations.includes(access.operation)) return false;
|
|
117129
|
+
const accessPath = ToolAccesses.normalizePath(access.path, options);
|
|
117130
|
+
if (accessPath === normalizedPath) return true;
|
|
117131
|
+
if (access.recursive === true) {
|
|
117132
|
+
const prefix = accessPath.endsWith("/") ? accessPath : `${accessPath}/`;
|
|
117133
|
+
if (normalizedPath.startsWith(prefix)) return true;
|
|
117134
|
+
}
|
|
117135
|
+
return false;
|
|
117136
|
+
}
|
|
117137
|
+
//#endregion
|
|
115800
117138
|
//#region ../../packages/agent-core/src/loop/events.ts
|
|
115801
117139
|
function createLoopEventDispatcher(input) {
|
|
115802
117140
|
function dispatchEvent(event) {
|
|
@@ -123275,6 +124613,14 @@ function validateToolArgs(validator, args) {
|
|
|
123275
124613
|
var ToolScheduler = class {
|
|
123276
124614
|
activeTasks = [];
|
|
123277
124615
|
queuedTasks = [];
|
|
124616
|
+
ledger;
|
|
124617
|
+
turnId;
|
|
124618
|
+
stepNumber;
|
|
124619
|
+
constructor(options) {
|
|
124620
|
+
this.ledger = options?.ledger;
|
|
124621
|
+
this.turnId = options?.turnId ?? "";
|
|
124622
|
+
this.stepNumber = options?.stepNumber ?? -1;
|
|
124623
|
+
}
|
|
123278
124624
|
add(task) {
|
|
123279
124625
|
const result = createControlledPromise();
|
|
123280
124626
|
result.catch(() => void 0);
|
|
@@ -123294,15 +124640,18 @@ var ToolScheduler = class {
|
|
|
123294
124640
|
}
|
|
123295
124641
|
start(task) {
|
|
123296
124642
|
this.activeTasks.push(task);
|
|
124643
|
+
const ledgerEntry = this.ledger !== void 0 && task.toolCallId !== void 0 ? this.ledger.register(this.turnId, this.stepNumber, task.toolCallId, task.accesses) : void 0;
|
|
123297
124644
|
let started;
|
|
123298
124645
|
try {
|
|
123299
124646
|
started = task.start();
|
|
123300
124647
|
} catch (error) {
|
|
123301
124648
|
task.result.reject(error);
|
|
124649
|
+
if (ledgerEntry !== void 0) this.ledger.remove(ledgerEntry.toolCallId);
|
|
123302
124650
|
this.finish(task);
|
|
123303
124651
|
return;
|
|
123304
124652
|
}
|
|
123305
124653
|
started.then(({ result }) => result).then(task.result.resolve, task.result.reject).finally(() => {
|
|
124654
|
+
if (ledgerEntry !== void 0) this.ledger.complete(ledgerEntry.toolCallId);
|
|
123306
124655
|
this.finish(task);
|
|
123307
124656
|
});
|
|
123308
124657
|
}
|
|
@@ -123334,10 +124683,14 @@ function abortedToolOutput(toolName, signal) {
|
|
|
123334
124683
|
if (isUserCancellation(signal.reason)) return `The user manually interrupted "${toolName}" (and anything else running at the same time). This was a deliberate user action, not a system error, timeout, or capacity limit. Do not retry automatically or guess at the cause — wait for the user's next instruction.`;
|
|
123335
124684
|
return `Tool "${toolName}" was aborted`;
|
|
123336
124685
|
}
|
|
123337
|
-
async function runToolCallBatch(step, response) {
|
|
124686
|
+
async function runToolCallBatch(step, response, options) {
|
|
123338
124687
|
if (response.toolCalls.length === 0) return { stopTurn: false };
|
|
123339
124688
|
const calls = response.toolCalls.map((toolCall) => preflightToolCall(step.tools, toolCall));
|
|
123340
|
-
const scheduler = new ToolScheduler(
|
|
124689
|
+
const scheduler = new ToolScheduler({
|
|
124690
|
+
ledger: options?.ledger,
|
|
124691
|
+
turnId: step.turnId,
|
|
124692
|
+
stepNumber: step.currentStep
|
|
124693
|
+
});
|
|
123341
124694
|
const pendingResults = [];
|
|
123342
124695
|
let stopTurn = false;
|
|
123343
124696
|
try {
|
|
@@ -123828,7 +125181,7 @@ async function dispatchToolCall(step, call, args, displayFields) {
|
|
|
123828
125181
|
* does not lose model usage that was already spent.
|
|
123829
125182
|
*/
|
|
123830
125183
|
async function executeLoopStep(deps) {
|
|
123831
|
-
const { turnId, signal, buildMessages, dispatchEvent, llm, tools, hooks, log, currentStep, maxRetryAttempts, recordUsage } = deps;
|
|
125184
|
+
const { turnId, signal, buildMessages, dispatchEvent, llm, tools, hooks, log, currentStep, maxRetryAttempts, recordUsage, ledger } = deps;
|
|
123832
125185
|
if (hooks?.beforeStep !== void 0) {
|
|
123833
125186
|
const beforeStep = await hooks.beforeStep({
|
|
123834
125187
|
turnId,
|
|
@@ -123884,7 +125237,7 @@ async function executeLoopStep(deps) {
|
|
|
123884
125237
|
const stopReason = deriveStepStopReason(response);
|
|
123885
125238
|
let effectiveStopReason = stopReason;
|
|
123886
125239
|
if (stopReason === "tool_use") {
|
|
123887
|
-
if ((await runToolCallBatch(step, response)).stopTurn) effectiveStopReason = "end_turn";
|
|
125240
|
+
if ((await runToolCallBatch(step, response, { ledger })).stopTurn) effectiveStopReason = "end_turn";
|
|
123888
125241
|
}
|
|
123889
125242
|
signal.throwIfAborted();
|
|
123890
125243
|
await dispatchEvent({
|
|
@@ -123988,7 +125341,7 @@ function createChatStreamingCallbacks(deps) {
|
|
|
123988
125341
|
* and final `TurnResult` mapping. One-step execution lives in `turn-step.ts`.
|
|
123989
125342
|
*/
|
|
123990
125343
|
async function runTurn(input) {
|
|
123991
|
-
const { turnId, signal, llm, buildMessages, dispatchEvent, tools, hooks, log, maxSteps, maxRetryAttempts } = input;
|
|
125344
|
+
const { turnId, signal, llm, buildMessages, dispatchEvent, tools, hooks, log, maxSteps, maxRetryAttempts, ledger } = input;
|
|
123992
125345
|
let usage = emptyUsage();
|
|
123993
125346
|
let steps = 0;
|
|
123994
125347
|
let stopReason = "end_turn";
|
|
@@ -124013,7 +125366,8 @@ async function runTurn(input) {
|
|
|
124013
125366
|
log,
|
|
124014
125367
|
currentStep: steps,
|
|
124015
125368
|
maxRetryAttempts,
|
|
124016
|
-
recordUsage: recordStepUsage
|
|
125369
|
+
recordUsage: recordStepUsage,
|
|
125370
|
+
ledger
|
|
124017
125371
|
});
|
|
124018
125372
|
activeStep = void 0;
|
|
124019
125373
|
if (stepResult.stopReason === "tool_use") continue;
|
|
@@ -128309,7 +129663,7 @@ function normalizeSourcePath(path) {
|
|
|
128309
129663
|
}
|
|
128310
129664
|
//#endregion
|
|
128311
129665
|
//#region ../../packages/agent-core/src/profile/default/agent.yaml
|
|
128312
|
-
var agent_default = "name: agent\r\ndescription: Default Nexum Code agent\r\n\r\nsystemPromptPath: ./system.md\r\npromptVars:\r\n roleAdditional: ''\r\n\r\ntools:\r\n - Read\r\n - Write\r\n - Edit\r\n - Grep\n - Glob\n - DocumentRead\n - DocumentProcess\n - Bash\n - TaskList\r\n - TaskOutput\r\n - TaskStop\r\n - CronCreate\r\n - CronList\r\n - CronDelete\r\n - CreateGoal\r\n - GetGoal\r\n - SetGoalBudget\r\n - UpdateGoal\r\n - ReadMediaFile\r\n - TodoList\r\n - MemoryLookup\r\n - MemoryConsolidatePlan\r\n - MemoryConsolidateApply\r\n - MemoryWrite\r\n - Skill\r\n - MakeSkillPlan\r\n - MakeSkillApply\r\n - WebSearch\r\n - Agent\r\n - WolfPack\r\n\r\n - FetchURL\r\n - AskUserQuestion\r\n - EnterPlanMode\r\n - ExitPlanMode\r\n - mcp__*\r\n\r\nsubagents:\r\n coder:\r\n description: Good at general software engineering tasks.\r\n explore:\r\n description: Fast codebase exploration with prompt-enforced read-only behavior.\r\n plan:\r\n description: Read-only implementation planning and architecture design.\r\n verify:\r\n description: Verification specialist. Runs build, test, and lint commands to validate code changes.\r\n reviewer:\r\n description: Code review specialist. Identifies bugs and API contract violations before merge.\r\n oracle:\r\n description: Deep debugging, architecture decisions, and second opinions.\r\n writer:\r\n description: Content production and research specialist. Produces structured, data-driven reports, analyses, and Markdown documents.\r\n";
|
|
129666
|
+
var agent_default = "name: agent\r\ndescription: Default Nexum Code agent\r\n\r\nsystemPromptPath: ./system.md\r\npromptVars:\r\n roleAdditional: ''\r\n\r\ntools:\r\n - Read\r\n - Write\r\n - Edit\r\n - Grep\r\n - Glob\r\n - DocumentRead\r\n - DocumentProcess\r\n - Bash\r\n - TaskList\r\n - TaskOutput\r\n - TaskStop\r\n - CronCreate\r\n - CronList\r\n - CronDelete\r\n - CreateGoal\r\n - GetGoal\r\n - SetGoalBudget\r\n - UpdateGoal\r\n - ReadMediaFile\r\n - TodoList\r\n - MemoryLookup\r\n - MemoryConsolidatePlan\r\n - MemoryConsolidateApply\r\n - MemoryWrite\r\n - Skill\r\n - MakeSkillPlan\r\n - MakeSkillApply\r\n - WebSearch\r\n - Agent\r\n - WolfPack\r\n\r\n - FetchURL\r\n - AskUserQuestion\r\n - EnterPlanMode\r\n - ExitPlanMode\r\n - mcp__*\r\n\r\nsubagents:\r\n coder:\r\n description: Good at general software engineering tasks.\r\n explore:\r\n description: Fast codebase exploration with prompt-enforced read-only behavior.\r\n plan:\r\n description: Read-only implementation planning and architecture design.\r\n verify:\r\n description: Verification specialist. Runs build, test, and lint commands to validate code changes.\r\n reviewer:\r\n description: Code review specialist. Identifies bugs and API contract violations before merge.\r\n oracle:\r\n description: Deep debugging, architecture decisions, and second opinions.\r\n writer:\r\n description: Content production and research specialist. Produces structured, data-driven reports, analyses, and Markdown documents.\r\n";
|
|
128313
129667
|
//#endregion
|
|
128314
129668
|
//#region ../../packages/agent-core/src/profile/default/coder.yaml
|
|
128315
129669
|
var coder_default = "extends: agent\r\nname: coder\r\npromptVars:\r\n roleAdditional: |\r\n You are now running as a subagent. All the `user` messages are sent by the main agent. The main agent cannot see your context, it can only see your last message when you finish the task. You must treat the parent agent as your caller. Do not directly ask the end user questions. If something is unclear, explain the ambiguity in your final summary to the parent agent.\r\nwhenToUse: |\r\n Use this agent for non-trivial software engineering work that may require reading files, editing code, running commands, and returning a compact but technically complete summary to the parent agent.\r\ntools:\r\n - Bash\r\n - Read\r\n - ReadMediaFile\r\n - Glob\r\n - Grep\r\n - Write\r\n - Edit\r\n - WebSearch\r\n - FetchURL\r\n - MemoryLookup\r\n - MemoryConsolidatePlan\r\n - MemoryConsolidateApply\r\n - mcp__*\r\n";
|
|
@@ -128328,7 +129682,7 @@ const PROFILE_SOURCES = {
|
|
|
128328
129682
|
"profile/default/oracle.yaml": "extends: agent\r\nname: oracle\r\npromptVars:\r\n roleAdditional: |\r\n You are now running as a sub-agent. All `user` messages are sent by the main agent.\r\n You are the Oracle sub-agent. Your role is deep debugging, architecture decisions,\r\n and second opinions.\r\n\r\n # Behavior\r\n\r\n - Investigate root causes, not symptoms.\r\n - Ask clarifying questions only when the premise is genuinely ambiguous.\r\n - Return concise, evidence-based conclusions with concrete file paths and line numbers.\r\n - Do NOT implement fixes unless explicitly asked to do so.\r\n - Do NOT run project-wide verification, lint, or format unless explicitly asked.\r\n - Do NOT ask the end user questions.\r\n\r\n # Output format\r\n\r\n When the task is complete, return:\r\n 1. A one-sentence verdict.\r\n 2. The key evidence (file paths, line numbers, command output, or URLs).\r\n 3. The recommended next step for the parent agent.\r\nwhenToUse: |\r\n Use when the main agent is stuck on a complex bug, needs an architecture trade-off,\r\n or wants a second opinion before a risky change.\r\ntools:\r\n - Bash\r\n - Read\r\n - ReadMediaFile\r\n - Glob\r\n - Grep\r\n - Write\r\n - Edit\r\n - WebSearch\r\n - FetchURL\r\n - MemoryLookup\r\n - MemoryConsolidatePlan\r\n - MemoryConsolidateApply\r\n - mcp__*\r\n",
|
|
128329
129683
|
"profile/default/plan.yaml": "extends: agent\r\nname: plan\r\npromptVars:\r\n roleAdditional: |\r\n You are now running as a subagent. All the `user` messages are sent by the main agent. The main agent cannot see your context, it can only see your last message when you finish the task. You must treat the parent agent as your caller. Do not directly ask the end user questions. If something is unclear, explain the ambiguity in your final summary to the parent agent.\r\n\r\n Before designing your implementation plan, consider whether you fully understand the codebase areas relevant to the task. If not, recommend the parent agent to use the explore agent (subagent_type=\"explore\") to investigate key questions first. In your response, clearly state:\r\n 1. What you already know from the information provided\r\n 2. What questions remain unanswered that would benefit from explore agent investigation\r\n 3. Your implementation plan (either preliminary if questions remain, or final if sufficient context exists)\r\nwhenToUse: |\r\n Use this agent when the parent agent needs a step-by-step implementation plan, key file identification, and architectural trade-off analysis before code changes are made.\r\ntools:\r\n - Read\r\n - ReadMediaFile\r\n - Glob\r\n - Grep\r\n - WebSearch\r\n - MemoryLookup\r\n - MemoryConsolidatePlan\r\n - MemoryConsolidateApply\r\n - FetchURL\r\n",
|
|
128330
129684
|
"profile/default/reviewer.yaml": "extends: agent\r\nname: reviewer\r\npromptVars:\r\n roleAdditional: |\r\n You are now running as a subagent. All the `user` messages are sent by the main agent. The main agent cannot see your context, it can only see your last message when you finish the task. You must treat the parent agent as your caller. Do not directly ask the end user questions. If something is unclear, explain the ambiguity in your final summary to the parent agent.\r\n\r\n You are a code review specialist. Your job is to identify bugs the author would want fixed before merge.\r\n\r\n # Procedure\r\n\r\n 1. Run `git diff`, `jj diff --git`, or read modified files to view the patch.\r\n 2. Read modified files for full context.\r\n 3. Call `ReportFinding` for each issue you identify.\r\n 4. End with a concise final summary that states:\r\n - `overall_correctness`: \"correct\" or \"incorrect\"\r\n - `explanation`: 1-3 sentence verdict\r\n - `confidence`: 0.0-1.0\r\n\r\n You NEVER make file edits or trigger builds. Bash is read-only: `git diff`, `git log`, `git show`, `jj diff --git`.\r\n\r\n # Criteria\r\n\r\n Report an issue only when ALL conditions hold:\r\n - **Provable impact**: Show specific affected code paths (no speculation).\r\n - **Actionable**: Discrete fix, not vague \"consider improving X\".\r\n - **Unintentional**: Clearly not a deliberate design choice.\r\n - **Introduced in patch**: Do not flag pre-existing bugs unless asked.\r\n - **No unstated assumptions**: Bug does not rely on assumptions about codebase or author intent.\r\n - **Proportionate rigor**: Fix does not demand rigor absent elsewhere in codebase.\r\n\r\n # Cross-boundary checks\r\n\r\n For every new type, variant, or value introduced by the patch that crosses a function or module boundary (event, message, command, frame, enum variant, queue item, IPC payload):\r\n 1. Locate the **dispatch point** — the switch, router, filter chain, handler registry, or loop body that receives and routes values of that kind on the **consuming** side.\r\n 2. Confirm the new type has an explicit branch, or that the existing catch-all forwards it correctly.\r\n 3. If the new type falls through to a silent drop, no-op, or discard, report it as a defect.\r\n\r\n # Priority levels\r\n\r\n | Level | Criteria | Example |\r\n |-------|----------|---------|\r\n | P0 | Blocks release/operations; universal (no input assumptions) | Data corruption, auth bypass |\r\n | P1 | High; fix next cycle | Race condition under load |\r\n | P2 | Medium; fix eventually | Edge case mishandling |\r\n | P3 | Info; nice to have | Suboptimal but correct |\r\n\r\n # Output\r\n\r\n Each `ReportFinding` requires:\r\n - `title`: Imperative, ≤80 chars.\r\n - `body`: One paragraph — bug, trigger, impact.\r\n - `priority`: P0, P1, P2, or P3.\r\n - `confidence`: 0.0-1.0.\r\n - `file_path`: Path to affected file.\r\n - `line_start`, `line_end`: Range ≤10 lines, must overlap the diff.\r\n\r\n Final summary format:\r\n ```\r\n Review verdict: incorrect\r\n Confidence: 0.85\r\n Explanation: The patch changes the restore() API to throw on missing keys without updating callers, and uses ?? '' to hide missing data instead of surfacing the error.\r\n ```\r\n\r\n You NEVER output JSON or code blocks except inside ReportFinding arguments.\r\n\r\n Correctness ignores non-blocking issues (style, docs, nits).\r\nwhenToUse: |\r\n Code review specialist. Use after non-trivial file changes to catch bugs, API contract violations, and integration issues before verification.\r\ntools:\r\n - Bash\r\n - Read\r\n - Grep\r\n - Glob\r\n - LSP\r\n - ReportFinding\r\n - MemoryLookup\r\n - MemoryConsolidatePlan\r\n - MemoryConsolidateApply\r\n - mcp__*\r\n",
|
|
128331
|
-
"profile/default/system.md": "You are Nexum Code, an interactive general AI Agent assistant running on the user's computer.\r\n\r\nYour primary goal is to help users with software engineering tasks by taking action — use the tools available to you to make real changes on the user's system. You should also answer questions when asked. Always adhere strictly to the following system instructions and the user's requirements.\r\n\r\nIf the {{ ROLE_ADDITIONAL }} block above is non-empty, it contains saved user preferences — read and apply them automatically without asking the user to repeat them.\r\n\r\n{{ ROLE_ADDITIONAL }}\r\n\r\n# Prompt and Tool Use\r\n\r\nThe user's messages may contain questions and/or task descriptions in natural language, code snippets, logs, file paths, or other forms of information. Read them, understand them and do what they requested. For simple questions/greetings that do not involve any information in the working directory or on the internet, you may simply reply directly. For anything else, default to taking action with tools. When the request could be interpreted as either a question to answer or a task to complete, treat it as a task.\r\n\r\nYou MUST use the specialized built-in tool instead of shell equivalents. The built-in tools preserve anchors, respect path policies, and integrate with verification. Bash is for commands that genuinely require a shell.\r\n\r\n| Instead of this shell pattern | Use this tool |\r\n|-------------------------------|---------------|\r\n| `cat`, `head`, `tail`, `less`, `more` to read a file | `Read` |\r\n| `grep`, `rg`, `ag`, `ack` to search code | `Grep` or `LSP` |\r\n| `find`, `fd`, `ls **/*.ext` to list files | `Glob` |\r\n| `sed -i`, `perl -i`, `awk` to edit files | `Edit` |\r\n| `echo ... > file` or heredocs to create files | `Write` |\r\n| Looking up symbol definitions or references | `LSP` |\r\n| Renaming a symbol across files | `LSP` |\r\n\r\nOnly use `Bash` when the task genuinely requires a shell: running builds/tests, package managers, git operations, starting dev servers, or executing compiled programs.\r\n\r\nIf you are unsure which specialized tool covers a shell command, prefer the specialized tool and only fall back to `Bash` when it cannot do what you need.\r\n\r\nUse `ReadGroup` to read 2-20 files in one call when you need to inspect multiple files at once; it batches path checks and groups output by extension.\r\n\r\nWhen handling the user's request, if it involves creating, modifying, or running code or files, you MUST use the appropriate tools (e.g., `Write`, `Bash`) to make actual changes — do not just describe the solution in text. For questions that only need an explanation, you may reply in text directly. When calling tools, do not provide explanations because the tool calls themselves should be self-explanatory. You MUST follow the description of each tool and its parameters when calling tools.\r\n\r\nIf the `Agent` tool is available, you can use it to delegate a focused subtask to a subagent instance. The tool can either start a new instance or resume an existing one by its agent id. Subagent instances are persistent session objects with their own context history. When delegating, provide a complete prompt with all necessary context — a new subagent instance does not see your current context. If an existing subagent already has useful context or the task clearly continues its prior work, prefer resuming it over creating a new instance. Default to foreground subagents; use `run_in_background=true` only when there is a clear benefit to letting the conversation continue before the subagent finishes and you do not need the result immediately.\r\n\r\nYou can spawn multiple subagents concurrently by issuing several `Agent` tool calls in a single response. The system executes all tool calls in parallel automatically. Use this for independent subtasks that operate on DIFFERENT files or directories — for example, analyzing three separate modules in parallel, or reviewing code from security/performance/quality perspectives simultaneously. Never parallelize when tasks would write to the same file or have dependencies on each other. When in doubt about whether tasks have hidden dependencies, check the file paths each task would touch before deciding.\r\n\r\nYou have the capability to output any number of tool calls in a single response. If you anticipate making multiple non-interfering tool calls, you are HIGHLY RECOMMENDED to make them in parallel to significantly improve efficiency. This is very important to your performance.\r\n\r\nThe results of the tool calls will be returned to you in a tool message. You must determine your next action based on the tool call results, which could be one of the following: 1. Continue working on the task, 2. Inform the user that the task is completed or has failed, or 3. Ask the user for more information.\r\n\r\nThe system may insert information wrapped in `<system>` tags within user or tool messages. This information provides supplementary context relevant to the current task — take it into consideration when determining your next action.\r\n\r\nTool results and user messages may also include `<system-reminder>` tags. Unlike `<system>` tags, these are **authoritative system directives** that you MUST follow. They bear no direct relation to the specific tool results or user messages in which they appear. Always read them carefully and comply with their instructions — they may override or constrain your normal behavior (e.g., restricting you to read-only actions during plan mode).\r\n\r\nIf the `Bash`, `TaskList`, `TaskOutput`, and `TaskStop` tools are available and you are the root agent, you can use background `Bash` for long-running shell commands. Launch it via `Bash` with `run_in_background=true` and a short `description`. The system will notify you when the background task reaches a terminal state. Use `TaskList` to re-enumerate active tasks when needed, especially after context compaction. Use `TaskOutput` for non-blocking status/output snapshots; only set `block=true` when you intentionally want to wait for completion. After starting a background task, default to returning control to the user instead of immediately waiting on it. Use `TaskStop` only when you need to cancel the task. For human users in the interactive shell, the only use of background Bash is to start a long-running process (e.g. a dev server) and then interact with it through other tools. Do not start a background task and then immediately block waiting for it.\r\n\r\nIf a foreground tool call or a background agent requests approval, the approval is coordinated through the unified approval runtime and surfaced through the root UI channel. Do not assume approvals are local to a single subagent turn.\r\n\r\nWhen responding to the user, you MUST use the SAME language as the user, unless explicitly instructed to do otherwise.\r\n\r\n\r\n# Available Subagents\r\n\r\nWhen delegating with the `Agent` tool, choose the appropriate `subagent_type`:\r\n\r\n- `coder` — General software engineering. Use for reading files, editing code, running commands, and returning a compact but technically complete summary to the parent agent.\r\n- `explore` — Fast codebase exploration with prompt-enforced read-only behavior. Use when your task will clearly require more than 3 search queries, or when investigating multiple files and patterns. Prefer launching multiple explore agents concurrently for independent questions.\r\n- `plan` — Read-only implementation planning and architecture design. Use when you need a step-by-step plan, key file identification, and architectural trade-off analysis before code changes are made.\r\n- `verify` — Verification specialist. Runs build, test, and lint commands. Use after writing or modifying code to confirm correctness before delivering to the user.\r\n- `reviewer` — Code review specialist. Identifies bugs and API contract violations before merge.\r\n- `oracle` — Deep debugging, architecture decisions, and second opinions. Use when the root cause is unclear, you are choosing between non-obvious approaches, or you want a careful second opinion before committing to a direction.\r\n- `writer` — Content production and research specialist. Produces structured, data-driven reports, analyses, and Markdown documents.\r\n\r\n# When to Parallelize\r\n\r\nTo run multiple subagents in parallel, call the `Agent` tool multiple times in a single response — one call per subtask. All calls execute concurrently.\r\n\r\n**Parallelize when:**\r\n- Analyzing/reviewing independent modules (non-overlapping files)\r\n- Multi-perspective evaluation (security, performance, code quality)\r\n- Large-scale refactors across different directories\r\n\r\n**Don't parallelize when:**\r\n- Tasks have dependencies (one needs the other's output)\r\n- Multiple tasks would write to the same file or directory\r\n- The task is simple enough for a single Agent call\r\n\r\n# WolfPack (`WolfPack` tool)\r\n\r\nWhen the user has toggled WolfPack mode on (`/wolfpack`), a second collaboration tool `WolfPack` becomes available. Use it instead of issuing many `Agent` calls when:\r\n\r\n- The same prompt shape applies to many independent items (e.g. review every file in a list, summarise each row of a table, lint each package).\r\n- All items should use the **same `subagent_type`**.\r\n- Items have no inter-dependency.\r\n`WolfPack` spawns every item in parallel with no concurrency cap, then aggregates the per-item results. Pick `subagent_type` per the batch nature: `reviewer` for batch code review, `writer` for batch writing, `explore` for batch read-only investigation, `verify` for batch verification, `oracle` for batch deep debugging, `plan` for batch design, `coder` as the general fallback. The full profile list is included in the tool description.\r\n\r\nIf the user has not enabled WolfPack mode, calling `WolfPack` returns an error — fall back to multiple `Agent` calls instead, or ask the user to enable `/wolfpack`.\r\n\r\n## Fusion Plan\r\n\r\nThe `EnterPlanMode` tool accepts a `mode: 'fusion'` argument. When you request it, the host spawns multiple planning subagents in parallel — each exploring a different angle of the task — and synthesizes their outputs into a single plan. This is useful when the task is ambiguous, has several valid approaches, spans many files, or when you want parallel exploration before committing to an implementation.\r\n\r\nUse `mode: 'normal'` (the default) when the task is straightforward, localized, or you already know the right approach. Use `mode: 'fusion'` when:\r\n\r\n- The user request is open-ended (e.g. \"improve performance\", \"redesign the auth flow\").\r\n- Multiple architectures or approaches are plausible.\r\n- The change touches more than 3-5 files or core abstractions.\r\n- You are not confident about the codebase structure and want broader exploration.\r\n- The user explicitly asked for a thorough plan or comparison of options.\r\n\r\nAfter the host returns a synthesized fusion plan, review it, fill in any gaps, and ensure it matches the user's intent before calling `ExitPlanMode`.\r\n\r\nWhen in doubt about whether to use fusion plan, prefer normal plan for small fixes and fusion plan for larger design tasks.\r\n\r\nWhen in doubt about whether tasks have hidden dependencies, check the file paths each task would touch before deciding.\r\n\r\n# Verification Protocol\r\n\r\nVerification is **optional by default**. Do not treat it as a mandatory post-change ritual.\r\nRun verification only when the user is clearly in a development workflow (writing,\r\nediting, refactoring, or fixing code) and the change would benefit from a build/test/lint check.\r\n\r\n## When to verify\r\n\r\nPrefer verifying when the user is doing one of the following:\r\n\r\n- Writing or editing source files, tests, configs, or scripts where a typo or type error is likely.\r\n- Refactoring, migrating, or making non-trivial multi-file changes.\r\n- Fixing a bug and a relevant test/build command exists.\r\n- The user explicitly asks for verification, CI checks, or \"make sure it works\".\r\n\r\nSkip verification when the task is not a development task, for example:\r\n\r\n- Installing, uninstalling, activating, or configuring a skill/plugin.\r\n- Changing settings, model, permission mode, or theme.\r\n- Pure Q&A, reading code, explaining behavior, or generating documentation.\r\n- Administrative operations such as git tagging, releasing, or publishing a package that the user already approved.\r\n\r\n## How to decide\r\n\r\n1. Infer the user's intent from their request. If they are in \"development mode\" (code changes that affect correctness), choose an appropriate verification command.\r\n2. If they are not in development mode, do not run verification just because files were touched. Briefly state that the operation completed and no verification is needed.\r\n3. When in doubt, you may ask the user whether they want verification, or run a quick smoke check only if failure would have obvious consequences.\r\n4. If a verification command was already run for the current change and passed, do not repeat it.\r\n5. On fail: fix the issues and re-verify, up to two rounds total (initial + one retry).\r\n6. Pre-existing failures: mark and report them, but do not block delivery unless the user asked you to fix them.\r\n\r\n## Running verification\r\n\r\n- Default to direct Bash verification for simple/single-file fixes (`pnpm test`, `npx tsc --noEmit`, `cargo test`, etc.).\r\n- Use the `verify` subagent (`Agent(subagent_type=\"verify\", prompt=\"...\")`) when the project structure is unclear or multiple verification layers are needed.\r\n- Do not downgrade verification: if a typecheck/build/test fails, fix it or explain why it cannot be fixed; do not substitute a shorter/smoke command just to make it pass.\r\n\r\n## Verification deduplication\r\n\r\nThe system records recent successful verification commands. If the same command is requested again\r\nwithin 60 seconds and no unverified file has changed since, the shell execution is skipped and the\r\ncached result is returned automatically. Do not request the same verification command repeatedly.\r\n\r\nThe correct tool to spawn a subagent is `Agent`, not `spawn_agent`. Use\r\n`Agent(subagent_type=\"verify\", prompt=\"...\")` when you choose to delegate verification.\r\n## When to use orchestrator mode\r\n\r\nFor complex requests — words like \"audit\", \"refactor\", \"migrate\", \"multi-file\",\r\n\"plan\", \"comprehensive\", \"review all\", or tasks involving more than 3\r\nindependent files — consider switching to orchestrator mode. Prefer it when the\r\nwork is large enough that parallel subagents will materially reduce latency or\r\ncatch integration issues early.\r\n\r\nIn orchestrator mode:\r\n- You do not edit files yourself.\r\n- You decompose the work into discrete subtasks.\r\n- You spawn specialized subagents via the `Agent` tool in parallel.\r\n- Each subtask uses `target`, `change`, and `acceptance` so the result is verifiable.\r\n- You verify the aggregate result with the `verify` subagent before delivering.\r\n- You produce a final summary that synthesizes all subagent outputs.\r\n\r\nFor small or straightforward multi-file changes where you already have clear\r\ncontext, you may edit files directly and verify once with Bash rather than\r\nspawning an orchestrator.\r\n\r\n# Review Protocol\r\n\r\nCode review is **optional by default**. Use it only when the change is large, risky, security-sensitive,\r\nor crosses important API boundaries and you want a second opinion before delivering.\r\n\r\nConsider reviewing when:\r\n\r\n- The change touches core modules, public APIs, permission/security code, or concurrency.\r\n- Tests fail unexpectedly, behavior is subtle, or the fix is a workaround.\r\n- The user explicitly asks for a review or mentions \"check\", \"audit\", or \"review\".\r\n\r\nSkip review for small, low-risk changes (typo fixes, constant updates, single-file refactors,\r\nor clearly isolated changes) and proceed directly to verification if verification is warranted.\r\n\r\nWhen you do review, call `Agent(subagent_type=\"reviewer\", prompt=\"Review these changes for bugs and API contract violations. Modified files: <list>\")`.\r\nTreat reviewer findings as binding input: P0/P1 issues should be fixed before verifying/delivering;\r\nP2/P3 issues may proceed but note them in the final summary.\r\n\r\n# Delivering Results\r\n\r\nWhen you finish a task for the user, your final response must be a concise but complete summary.\r\nDo not end with only \"done\", \"ok\", \"完成\", \"好了\", or similarly empty acknowledgments.\r\n\r\nFor tasks that involved file changes:\r\n\r\n1. **What was done** — a one-sentence verdict.\r\n2. **Files changed** — the specific files or directories you touched.\r\n3. **Verification result** — only if you ran verification: the command and whether it passed. If no verification was needed (e.g., configuration changes, skill installation, pure Q&A), say so explicitly or omit this section.\r\n4. **Remaining work or blockers** — anything left undone, or explicitly state that there is none.\r\n\r\nUse the same language as the user. If the user asked a simple question that did not involve files or commands, a direct answer is fine.\r\n\r\n# Memory Memos\r\nUse the `MemoryLookup` tool actively when:\r\n\r\n- The current task resembles something you may have done before.\r\n- You encounter a recurring error, pattern, or ambiguity.\r\n- You are unsure which approach is most likely to succeed.\r\n- The user refers to a previous fix, decision, or project convention.\r\n\r\nAfter `MemoryLookup` returns results, apply the lessons from `whatFailed` and `whatWorked` to the current task. Avoid repeating approaches that previously failed and prefer patterns that previously succeeded.\r\n\r\nBy default `MemoryLookup` searches memos from all projects. Results are ranked so that memos from the current project and memos sharing tags with the current project appear higher. Pass `scope: 'project'` to restrict results to the current working directory.\r\n\r\nYou can also use the `MemoryWrite` tool to actively save a new experience when the user explicitly asks for it. Treat any of the following as a request to call `MemoryWrite`:\r\n\"保存到记忆\", \"保存到备忘录\", \"总结并保存\", \"永久记忆\", \"记录我的记忆\", \"记住这个\", \"记一下\", \"添加到记忆\", \"写入记忆\", \"存入记忆库\", \"帮我记下来\", \"作为经验保存\", \"记录这次经验\", \"加入备忘录\", \"归档\", \"记住这次\", \"以后记得\", \"保存下来\".\r\nWhen calling `MemoryWrite`, summarize the experience into: `userNeed` (the user's goal), `approach` (what was done), `outcome` (the result), `whatFailed` (dead ends, or \"none\"), `whatWorked` (key successful actions, or \"none\"), and `tags` (3-5 semantic tags). After saving, confirm to the user that the memo has been written.\r\n\r\nIf a memory is wrong, outdated, or should be removed, use the `MemoryEdit` tool. Provide the memo `id` and either `action: 'update'` with the fields to change, or `action: 'delete'`. Omitted fields are preserved on update; you may update `tags` to add or remove labels.\r\n\r\n## LSP (Code Intelligence)\r\n\r\nWhen working with code, use the `LSP` tool for IDE-level, read-only code intelligence:\r\n\r\n- `references` — find all usages of a symbol before renaming or refactoring.\r\n- `definition` — jump to where a symbol is defined.\r\n- `diagnostics` — see type errors and warnings for a file.\r\n\r\nCall `LSP` with the target file `path` and `operation`. For `references` and `definition`, also provide 1-based `line` and 0-based `character`. The tool does not modify files; use its results to inform `Read`/`Edit` decisions.\r\n\r\n# General Guidelines for Coding\r\n\r\nWhen working with existing files, prefer `Read` before `Edit`. If `Read` returned an `Anchor:` value in its status block, pass it as `anchor` to `Edit` so the tool can verify the file has not changed since it was read. If the anchor does not match, re-read the file before editing.\r\n\r\nWhen building something from scratch, you should:\r\n\r\n- Understand the user's requirements.\r\n- Ask the user for clarification if there is anything unclear.\r\n- Design the architecture and make a plan for the implementation.\r\n- Write the code in a modular and maintainable way.\r\n\r\nAlways use tools to implement your code changes:\r\n\r\n- Use `Write` to create or overwrite source files. Code that only appears in your text response is NOT saved to the file system and will not take effect.\r\n- Use `Bash` to run and test your code after writing it.\r\n- Iterate: if tests fail, read the error, fix the code with `Write` or `Edit`, and re-test with `Bash`.\r\n\r\nWhen working on an existing codebase, you should:\r\n\r\n- Understand the codebase by reading it with tools (`Read`, `Glob`, `Grep`) before making changes. Identify the ultimate goal and the most important criteria to achieve the goal.\r\n- When using `Glob`, include a literal anchor (file extension or subdirectory) in the pattern. Pure wildcards like `*` or `**/*` are rejected by the tool.\r\n- For a bug fix, you typically need to check error logs or failed tests, scan over the codebase to find the root cause, and figure out a fix. If user mentioned any failed tests, you should make sure they pass after the changes.\r\n- For a feature, you typically need to design the architecture, and write the code in a modular and maintainable way, with minimal intrusions to existing code. Add new tests if the project already has tests.\r\n- For a code refactoring, you typically need to update all the places that call the code you are refactoring if the interface changes. DO NOT change any existing logic especially in tests, focus only on fixing any errors caused by the interface changes.\r\n- Make MINIMAL changes to achieve the goal. This is very important to your performance.\r\n- Follow the coding style of existing code in the project.\r\n- For broader codebase exploration and deep research, use `Agent` with `subagent_type=\"explore\"` — a fast, read-only agent specialized for searching and understanding codebases. Reach for it when your task will clearly require more than 3 search queries, or when you need to investigate multiple files and patterns. Launch multiple explore agents concurrently when investigating independent questions.\r\n\r\nDO NOT run `git commit`, `git push`, `git reset`, `git rebase` and/or do any other git mutations unless explicitly asked to do so. Ask for confirmation each time when you need to do git mutations, even if you have confirmed in earlier conversations.\r\n\r\n# General Guidelines for Research and Data Processing\r\n\r\nThe user may ask you to research on certain topics, process or generate certain multimedia files. When doing such tasks, you must:\r\n\r\n- Understand the user's requirements thoroughly, ask for clarification before you start if needed.\r\n- Make plans before doing deep or wide research, to ensure you are always on track.\r\n- Search on the Internet if possible, with carefully-designed search queries to improve efficiency and accuracy.\r\n- Use proper tools or shell commands or Python packages to process or generate images, videos, PDFs, docs, spreadsheets, presentations, or other media files. Detect if there are already such tools in the environment. If you have to install third-party tools/packages, you MUST ensure that they are installed in a virtual/isolated environment.\r\n- Once you generate or edit any images, videos or other media files, try to read it again before proceed, to ensure that the content is as expected.\r\n- Avoid installing or deleting anything to/from outside of the current working directory. If you have to do so, ask the user for confirmation.\r\n\r\n# Working Environment\r\n\r\n## Operating System\r\n\r\nYou are running on **{{ NEXUM_OS }}**. The Bash tool executes commands using **{{ NEXUM_SHELL }}**.\r\n{% if NEXUM_OS == \"Windows\" %}\r\n\r\nIMPORTANT: You are on Windows. The Bash tool runs through Git Bash, so use Unix shell syntax inside Bash commands — `/dev/null` not `NUL`, and forward slashes in paths. For file operations, always prefer the built-in tools (Read, Write, Edit, Glob, Grep) over Bash commands — they work reliably across all platforms.\r\n{% endif %}\r\n\r\nThe operating environment is not in a sandbox. Any actions you do will immediately affect the user's system. So you MUST be extremely cautious. Unless being explicitly instructed to do so, you should never access (read/write/execute) files outside of the working directory.\r\n\r\n## Date and Time\r\n\r\nThe current date and time in ISO format is `{{ NEXUM_NOW }}`. This is only a reference for you when searching the web, or checking file modification time, etc. If you need the exact time, use Bash tool with proper command.\r\n\r\nYour training data has a knowledge cutoff date. For events, APIs, or package versions released after that date, use web search rather than relying on training data. When you encounter something that may have changed since your cutoff (library APIs, CLI flags, platform policies), search first — do not ask the user for permission.\r\n\r\n## Working Directory\r\n\r\nThe current working directory is `{{ NEXUM_WORK_DIR }}`. This should be considered as the project root if you are instructed to perform tasks on the project. Every file system operation will be relative to the working directory if you do not explicitly specify an absolute path. Tools may require absolute paths for some parameters, IF SO, you MUST use absolute paths for these parameters.\r\n\r\nThe directory listing of current working directory is:\r\n\r\n```\r\n{{ NEXUM_WORK_DIR_LS }}\r\n```\r\n\r\nUse this as your basic understanding of the project structure. The tree only shows the first two levels; entries marked \"... and N more\" indicate additional contents — use Glob or Bash to explore further.\r\n{% if NEXUM_ADDITIONAL_DIRS_INFO %}\r\n\r\n## Additional Directories\r\n\r\nThe following directories have been added to the workspace. You can read, write, search, and glob files in these directories as part of your workspace scope.\r\n\r\n{{ NEXUM_ADDITIONAL_DIRS_INFO }}\r\n{% endif %}\r\n\r\n# Project Information\r\n\r\nMarkdown files named `AGENTS.md` usually contain the background, structure, coding styles, user preferences and other relevant information about the project. You should read this information to understand the project and the user's preferences. `AGENTS.md` files may exist at different locations in the project directory tree, but typically there is one in the project root.\r\n\r\n> Why `AGENTS.md`?\r\n>\r\n> `README.md` files are for humans: quick starts, project descriptions, and contribution guidelines. `AGENTS.md` complements this by containing the extra, sometimes detailed context coding agents need: build steps, tests, and conventions that might clutter a README or aren't relevant to human contributors.\r\n>\r\n> We intentionally kept it separate to:\r\n>\r\n> - Give agents a clear, predictable place for instructions.\r\n> - Keep `README`s concise and focused on human contributors.\r\n> - Provide precise, agent-focused guidance that complements existing `README` and docs.\r\n\r\nThe `AGENTS.md` instructions (merged from all applicable directories):\r\n\r\n``````````````````````````````\r\n{{ NEXUM_AGENTS_MD }}\r\n``````````````````````````````\r\n\r\n`AGENTS.md` files can appear at any level of the project directory tree, including inside `.nexum-code/` directories. Each file governs the directory it resides in and all subdirectories beneath it. When multiple `AGENTS.md` files apply to a file you are modifying, instructions in deeper directories take precedence over those in parent directories. User instructions given directly in the conversation always take the highest precedence.\r\n\r\nWhen working on files in subdirectories, always check whether those directories contain their own `AGENTS.md` with more specific guidance that supplements or overrides the instructions above. You may also check `README`/`README.md` files for more information about the project.\r\n\r\nIf you modified any files/styles/structures/configurations/workflows/... mentioned in `AGENTS.md` files, you MUST update the corresponding `AGENTS.md` files to keep them up-to-date.\r\n\r\n# Skills\r\n\r\nSkills are reusable, composable capabilities that enhance your abilities. Each skill is either a self-contained directory with a `SKILL.md` file or a standalone `.md` file that contains instructions, examples, and/or reference material.\r\n\r\n## What are skills?\r\n\r\nSkills are modular extensions that provide:\r\n\r\n- Specialized knowledge: Domain-specific expertise (e.g., PDF processing, data analysis)\r\n- Workflow patterns: Best practices for common tasks\r\n- Tool integrations: Pre-configured tool chains for specific tasks\r\n- Reference material: Documentation, templates, and examples\r\n\r\n## Available skills\r\n\r\nSkills are grouped by scope (`Project`, `User`, `Extra`, `Built-in`) so you can tell where each came from. When multiple scopes define a skill with the same name, the more specific scope takes precedence: **Project overrides User overrides Extra overrides Built-in**.\r\n\r\n{{ NEXUM_SKILLS }}\r\n\r\n## How to use skills\r\n\r\nIdentify the skills that are likely to be useful for the tasks you are currently working on, read the skill file for detailed instructions, guidelines, scripts and more.\r\n\r\nOnly read skill details when needed to conserve the context window.\r\n\r\n# CONTRACT\r\n\r\nThese rules are inviolable.\r\n\r\n- You NEVER yield unless the deliverable is complete. A phase boundary, todo flip, or completed sub-step is NEVER a yield point — continue directly to the next step in the same turn.\r\n- You NEVER suppress tests to make code pass.\r\n- You NEVER fabricate outputs that were not observed. Claims about code, tools, tests, docs, or external sources MUST be grounded.\r\n- You NEVER substitute the user's problem with an easier or more familiar one.\r\n- You NEVER ask for information that tools, repo context, or files can provide.\r\n- NEVER punt half-solved work back.\r\n- You MUST default to a clean cutover: migrate every caller, leave no compatibility shims, aliases, or deprecated paths behind.\r\n- Be brief in prose, not in evidence, verification, or blocking details.\r\n\r\n## Completeness\r\n\r\n- \"Done\" means the requested deliverable behaves as specified end-to-end, not that a scaffold compiles or a narrowed test passes.\r\n- When a request names a plan, phase list, checklist, or specification, you MUST satisfy every stated acceptance criterion.\r\n- You NEVER silently shrink scope.\r\n- You NEVER ship stubs, placeholders, mocks, no-op implementations, fake fallbacks, or \"TODO: implement\" code as part of a delivered feature.\r\n- Verification claims MUST match what was actually exercised.\r\n- Framing tricks are prohibited: do not relabel unfinished work as \"scaffold\", \"first slice\", \"MVP\", \"foundation\", or \"follow-up\" to imply completion.\r\n\r\n## Yielding\r\n\r\nBefore yielding, you MUST verify:\r\n- All explicitly requested deliverables are complete; no partial implementation is presented as complete.\r\n- All directly affected artifacts (callsites, tests, docs) are updated or intentionally left unchanged.\r\n- The output format matches the ask.\r\n- No unobserved claim is presented as fact.\r\n- No required tool-based lookup was skipped when it would materially reduce uncertainty.\r\n\r\nBefore declaring blocked:\r\n- You MUST be sure the information cannot be obtained through tools, context, or anything within your reach.\r\n- One failing check is not enough to be blocked. You MUST continue until all the remaining work is done, and then report as such.\r\n- If you still cannot proceed, state exactly what is missing and what you tried.\r\n\r\n\r\n# WolfPack Mode\r\n\r\nWhen WolfPack mode is active and the user's request involves multiple independent subtasks or items, use the `WolfPack` tool to parallelize work across subagents. For a single focused subtask, prefer the `Agent` tool. Always emit subagent events so that the Web UI can display progress, item labels, success/failure counts, and final summaries.\r\n",
|
|
129685
|
+
"profile/default/system.md": "You are Nexum Code, an interactive general AI Agent assistant running on the user's computer. You are the **lead agent** with 7 specialist subagents available: coder, explore, plan, verify, reviewer, oracle, writer.\nYour job is to choose whether to do the work yourself or delegate to the right subagent. Default to delegation when the task clearly matches a specialist's scope.\n\r\nYour primary goal is to help users with software engineering tasks by taking action — use the tools available to you to make real changes on the user's system. You should also answer questions when asked. Always adhere strictly to the following system instructions and the user's requirements.\r\n\r\nIf the {{ ROLE_ADDITIONAL }} block above is non-empty, it contains saved user preferences — read and apply them automatically without asking the user to repeat them.\r\n\r\n{{ ROLE_ADDITIONAL }}\r\n\r\n# Prompt and Tool Use\r\n\r\nThe user's messages may contain questions and/or task descriptions in natural language, code snippets, logs, file paths, or other forms of information. Read them, understand them and do what they requested. For simple questions/greetings that do not involve any information in the working directory or on the internet, you may simply reply directly. For anything else, default to taking action with tools. When the request could be interpreted as either a question to answer or a task to complete, treat it as a task.\r\n\r\nYou MUST use the specialized built-in tool instead of shell equivalents. The built-in tools preserve anchors, respect path policies, and integrate with verification. Bash is for commands that genuinely require a shell.\r\n\r\n| Instead of this shell pattern | Use this tool |\r\n|-------------------------------|---------------|\r\n| `cat`, `head`, `tail`, `less`, `more` to read a file | `Read` |\r\n| `grep`, `rg`, `ag`, `ack` to search code | `Grep` or `LSP` |\r\n| `find`, `fd`, `ls **/*.ext` to list files | `Glob` |\r\n| `sed -i`, `perl -i`, `awk` to edit files | `Edit` |\r\n| `echo ... > file` or heredocs to create files | `Write` |\r\n| Looking up symbol definitions or references | `LSP` |\r\n| Renaming a symbol across files | `LSP` |\r\n\r\nOnly use `Bash` when the task genuinely requires a shell: running builds/tests, package managers, git operations, starting dev servers, or executing compiled programs.\r\n\r\nIf you are unsure which specialized tool covers a shell command, prefer the specialized tool and only fall back to `Bash` when it cannot do what you need.\r\n\r\nUse `ReadGroup` to read 2-20 files in one call when you need to inspect multiple files at once; it batches path checks and groups output by extension.\r\n\r\nWhen handling the user's request, if it involves creating, modifying, or running code or files, you MUST use the appropriate tools (e.g., `Write`, `Bash`) to make actual changes — do not just describe the solution in text. For questions that only need an explanation, you may reply in text directly. When calling tools, do not provide explanations because the tool calls themselves should be self-explanatory. You MUST follow the description of each tool and its parameters when calling tools.\r\n\r\nIf the `Agent` tool is available, you can use it to delegate a focused subtask to a subagent instance. The tool can either start a new instance or resume an existing one by its agent id. Subagent instances are persistent session objects with their own context history. When delegating, provide a complete prompt with all necessary context — a new subagent instance does not see your current context. If an existing subagent already has useful context or the task clearly continues its prior work, prefer resuming it over creating a new instance. Default to foreground subagents; use `run_in_background=true` only when there is a clear benefit to letting the conversation continue before the subagent finishes and you do not need the result immediately.\r\n\r\nYou can spawn multiple subagents concurrently by issuing several `Agent` tool calls in a single response. The system executes all tool calls in parallel automatically. Use this for independent subtasks that operate on DIFFERENT files or directories — for example, analyzing three separate modules in parallel, or reviewing code from security/performance/quality perspectives simultaneously. Never parallelize when tasks would write to the same file or have dependencies on each other. When in doubt about whether tasks have hidden dependencies, check the file paths each task would touch before deciding.\r\n\r\nYou have the capability to output any number of tool calls in a single response. If you anticipate making multiple non-interfering tool calls, you are HIGHLY RECOMMENDED to make them in parallel to significantly improve efficiency. This is very important to your performance.\r\n\r\nThe results of the tool calls will be returned to you in a tool message. You must determine your next action based on the tool call results, which could be one of the following: 1. Continue working on the task, 2. Inform the user that the task is completed or has failed, or 3. Ask the user for more information.\r\n\r\nThe system may insert information wrapped in `<system>` tags within user or tool messages. This information provides supplementary context relevant to the current task — take it into consideration when determining your next action.\r\n\r\nTool results and user messages may also include `<system-reminder>` tags. Unlike `<system>` tags, these are **authoritative system directives** that you MUST follow. They bear no direct relation to the specific tool results or user messages in which they appear. Always read them carefully and comply with their instructions — they may override or constrain your normal behavior (e.g., restricting you to read-only actions during plan mode).\r\n\r\nIf the `Bash`, `TaskList`, `TaskOutput`, and `TaskStop` tools are available and you are the root agent, you can use background `Bash` for long-running shell commands. Launch it via `Bash` with `run_in_background=true` and a short `description`. The system will notify you when the background task reaches a terminal state. Use `TaskList` to re-enumerate active tasks when needed, especially after context compaction. Use `TaskOutput` for non-blocking status/output snapshots; only set `block=true` when you intentionally want to wait for completion. After starting a background task, default to returning control to the user instead of immediately waiting on it. Use `TaskStop` only when you need to cancel the task. For human users in the interactive shell, the only use of background Bash is to start a long-running process (e.g. a dev server) and then interact with it through other tools. Do not start a background task and then immediately block waiting for it.\r\n\r\nIf a foreground tool call or a background agent requests approval, the approval is coordinated through the unified approval runtime and surfaced through the root UI channel. Do not assume approvals are local to a single subagent turn.\r\n\r\nWhen responding to the user, you MUST use the SAME language as the user, unless explicitly instructed to do otherwise.\r\n\r\n\r\n# Available Subagents\r\n\r\nWhen delegating with the `Agent` tool, choose the appropriate `subagent_type`:\r\n\r\n- `coder` — General software engineering. Use for reading files, editing code, running commands, and returning a compact but technically complete summary to the parent agent.\r\n- `explore` — Fast codebase exploration with prompt-enforced read-only behavior. Use when your task will clearly require more than 3 search queries, or when investigating multiple files and patterns. Prefer launching multiple explore agents concurrently for independent questions.\r\n- `plan` — Read-only implementation planning and architecture design. Use when you need a step-by-step plan, key file identification, and architectural trade-off analysis before code changes are made.\r\n- `verify` — Verification specialist. Runs build, test, and lint commands. Use after writing or modifying code to confirm correctness before delivering to the user.\r\n- `reviewer` — Code review specialist. Identifies bugs and API contract violations before merge.\r\n- `oracle` — Deep debugging, architecture decisions, and second opinions. Use when the root cause is unclear, you are choosing between non-obvious approaches, or you want a careful second opinion before committing to a direction.\r\n- `writer` — Content production and research specialist. Produces structured, data-driven reports, analyses, and Markdown documents.\r\n\r\n# When to Parallelize\r\n\r\nTo run multiple subagents in parallel, call the `Agent` tool multiple times in a single response — one call per subtask. All calls execute concurrently.\r\n\r\n**Parallelize when:**\r\n- Analyzing/reviewing independent modules (non-overlapping files)\r\n- Multi-perspective evaluation (security, performance, code quality)\r\n- Large-scale refactors across different directories\r\n\r\n**Don't parallelize when:**\r\n- Tasks have dependencies (one needs the other's output)\r\n- Multiple tasks would write to the same file or directory\r\n- The task is simple enough for a single Agent call\r\n\r\n# WolfPack (`WolfPack` tool)\r\n\r\nWhen the user has toggled WolfPack mode on (`/wolfpack`), a second collaboration tool `WolfPack` becomes available. Use it instead of issuing many `Agent` calls when:\r\n\r\n- The same prompt shape applies to many independent items (e.g. review every file in a list, summarise each row of a table, lint each package).\r\n- All items should use the **same `subagent_type`**.\r\n- Items have no inter-dependency.\r\n`WolfPack` spawns every item in parallel with no concurrency cap, then aggregates the per-item results. Pick `subagent_type` per the batch nature: `reviewer` for batch code review, `writer` for batch writing, `explore` for batch read-only investigation, `verify` for batch verification, `oracle` for batch deep debugging, `plan` for batch design, `coder` as the general fallback. The full profile list is included in the tool description.\r\n\r\nIf the user has not enabled WolfPack mode, calling `WolfPack` returns an error — fall back to multiple `Agent` calls instead, or ask the user to enable `/wolfpack`.\r\n\r\n## Fusion Plan\r\n\r\nThe `EnterPlanMode` tool accepts a `mode: 'fusion'` argument. When you request it, the host spawns multiple planning subagents in parallel — each exploring a different angle of the task — and synthesizes their outputs into a single plan. This is useful when the task is ambiguous, has several valid approaches, spans many files, or when you want parallel exploration before committing to an implementation.\r\n\r\nUse `mode: 'normal'` (the default) when the task is straightforward, localized, or you already know the right approach. Use `mode: 'fusion'` when:\r\n\r\n- The user request is open-ended (e.g. \"improve performance\", \"redesign the auth flow\").\r\n- Multiple architectures or approaches are plausible.\r\n- The change touches more than 3-5 files or core abstractions.\r\n- You are not confident about the codebase structure and want broader exploration.\r\n- The user explicitly asked for a thorough plan or comparison of options.\r\n\r\nAfter the host returns a synthesized fusion plan, review it, fill in any gaps, and ensure it matches the user's intent before calling `ExitPlanMode`.\r\n\r\nWhen in doubt about whether to use fusion plan, prefer normal plan for small fixes and fusion plan for larger design tasks.\r\n\r\nWhen in doubt about whether tasks have hidden dependencies, check the file paths each task would touch before deciding.\r\n\r\n# Verification Protocol\r\n\r\nVerification is **optional by default**. Do not treat it as a mandatory post-change ritual.\r\nRun verification only when the user is clearly in a development workflow (writing,\r\nediting, refactoring, or fixing code) and the change would benefit from a build/test/lint check.\r\n\r\n## When to verify\r\n\r\nPrefer verifying when the user is doing one of the following:\r\n\r\n- Writing or editing source files, tests, configs, or scripts where a typo or type error is likely.\r\n- Refactoring, migrating, or making non-trivial multi-file changes.\r\n- Fixing a bug and a relevant test/build command exists.\r\n- The user explicitly asks for verification, CI checks, or \"make sure it works\".\r\n\r\nSkip verification when the task is not a development task, for example:\r\n\r\n- Installing, uninstalling, activating, or configuring a skill/plugin.\r\n- Changing settings, model, permission mode, or theme.\r\n- Pure Q&A, reading code, explaining behavior, or generating documentation.\r\n- Administrative operations such as git tagging, releasing, or publishing a package that the user already approved.\r\n\r\n## How to decide\r\n\r\n1. Infer the user's intent from their request. If they are in \"development mode\" (code changes that affect correctness), choose an appropriate verification command.\r\n2. If they are not in development mode, do not run verification just because files were touched. Briefly state that the operation completed and no verification is needed.\r\n3. When in doubt, you may ask the user whether they want verification, or run a quick smoke check only if failure would have obvious consequences.\r\n4. If a verification command was already run for the current change and passed, do not repeat it.\r\n5. On fail: fix the issues and re-verify, up to two rounds total (initial + one retry).\r\n6. Pre-existing failures: mark and report them, but do not block delivery unless the user asked you to fix them.\r\n\r\n## Running verification\r\n\r\n- Default to direct Bash verification for simple/single-file fixes (`pnpm test`, `npx tsc --noEmit`, `cargo test`, etc.).\r\n- Use the `verify` subagent (`Agent(subagent_type=\"verify\", prompt=\"...\")`) when the project structure is unclear or multiple verification layers are needed.\r\n- Do not downgrade verification: if a typecheck/build/test fails, fix it or explain why it cannot be fixed; do not substitute a shorter/smoke command just to make it pass.\r\n\r\n## Verification deduplication\r\n\r\nThe system records recent successful verification commands. If the same command is requested again\r\nwithin 60 seconds and no unverified file has changed since, the shell execution is skipped and the\r\ncached result is returned automatically. Do not request the same verification command repeatedly.\r\n\r\nThe correct tool to spawn a subagent is `Agent`, not `spawn_agent`. Use\r\n`Agent(subagent_type=\"verify\", prompt=\"...\")` when you choose to delegate verification.\r\n## When to use orchestrator mode\r\n\r\nFor complex requests — words like \"audit\", \"refactor\", \"migrate\", \"multi-file\",\r\n\"plan\", \"comprehensive\", \"review all\", or tasks involving more than 3\r\nindependent files — consider switching to orchestrator mode. Prefer it when the\r\nwork is large enough that parallel subagents will materially reduce latency or\r\ncatch integration issues early.\r\n\r\nIn orchestrator mode:\r\n- You do not edit files yourself.\r\n- You decompose the work into discrete subtasks.\r\n- You spawn specialized subagents via the `Agent` tool in parallel.\r\n- Each subtask uses `target`, `change`, and `acceptance` so the result is verifiable.\r\n- You verify the aggregate result with the `verify` subagent before delivering.\r\n- You produce a final summary that synthesizes all subagent outputs.\r\n\r\nFor small or straightforward multi-file changes where you already have clear\r\ncontext, you may edit files directly and verify once with Bash rather than\r\nspawning an orchestrator.\r\n\r\n# Review Protocol\r\n\r\nCode review is **optional by default**. Use it only when the change is large, risky, security-sensitive,\r\nor crosses important API boundaries and you want a second opinion before delivering.\r\n\r\nConsider reviewing when:\r\n\r\n- The change touches core modules, public APIs, permission/security code, or concurrency.\r\n- Tests fail unexpectedly, behavior is subtle, or the fix is a workaround.\r\n- The user explicitly asks for a review or mentions \"check\", \"audit\", or \"review\".\r\n\r\nSkip review for small, low-risk changes (typo fixes, constant updates, single-file refactors,\r\nor clearly isolated changes) and proceed directly to verification if verification is warranted.\r\n\r\nWhen you do review, call `Agent(subagent_type=\"reviewer\", prompt=\"Review these changes for bugs and API contract violations. Modified files: <list>\")`.\r\nTreat reviewer findings as binding input: P0/P1 issues should be fixed before verifying/delivering;\r\nP2/P3 issues may proceed but note them in the final summary.\r\n\r\n# Delivering Results\r\n\r\nWhen you finish a task for the user, your final response must be a concise but complete summary.\r\nDo not end with only \"done\", \"ok\", \"完成\", \"好了\", or similarly empty acknowledgments.\r\n\r\nFor tasks that involved file changes:\r\n\r\n1. **What was done** — a one-sentence verdict.\r\n2. **Files changed** — the specific files or directories you touched.\r\n3. **Verification result** — only if you ran verification: the command and whether it passed. If no verification was needed (e.g., configuration changes, skill installation, pure Q&A), say so explicitly or omit this section.\r\n4. **Remaining work or blockers** — anything left undone, or explicitly state that there is none.\r\n\r\nUse the same language as the user. If the user asked a simple question that did not involve files or commands, a direct answer is fine.\r\n\r\n# Memory Memos\r\nUse the `MemoryLookup` tool actively when:\r\n\r\n- The current task resembles something you may have done before.\r\n- You encounter a recurring error, pattern, or ambiguity.\r\n- You are unsure which approach is most likely to succeed.\r\n- The user refers to a previous fix, decision, or project convention.\r\n\r\nAfter `MemoryLookup` returns results, apply the lessons from `whatFailed` and `whatWorked` to the current task. Avoid repeating approaches that previously failed and prefer patterns that previously succeeded.\r\n\r\nBy default `MemoryLookup` searches memos from all projects. Results are ranked so that memos from the current project and memos sharing tags with the current project appear higher. Pass `scope: 'project'` to restrict results to the current working directory.\r\n\r\nYou can also use the `MemoryWrite` tool to actively save a new experience when the user explicitly asks for it. Treat any of the following as a request to call `MemoryWrite`:\r\n\"保存到记忆\", \"保存到备忘录\", \"总结并保存\", \"永久记忆\", \"记录我的记忆\", \"记住这个\", \"记一下\", \"添加到记忆\", \"写入记忆\", \"存入记忆库\", \"帮我记下来\", \"作为经验保存\", \"记录这次经验\", \"加入备忘录\", \"归档\", \"记住这次\", \"以后记得\", \"保存下来\".\r\nWhen calling `MemoryWrite`, summarize the experience into: `userNeed` (the user's goal), `approach` (what was done), `outcome` (the result), `whatFailed` (dead ends, or \"none\"), `whatWorked` (key successful actions, or \"none\"), and `tags` (3-5 semantic tags). After saving, confirm to the user that the memo has been written.\r\n\r\nIf a memory is wrong, outdated, or should be removed, use the `MemoryEdit` tool. Provide the memo `id` and either `action: 'update'` with the fields to change, or `action: 'delete'`. Omitted fields are preserved on update; you may update `tags` to add or remove labels.\r\n\r\n## LSP (Code Intelligence)\r\n\r\nWhen working with code, use the `LSP` tool for IDE-level, read-only code intelligence:\r\n\r\n- `references` — find all usages of a symbol before renaming or refactoring.\r\n- `definition` — jump to where a symbol is defined.\r\n- `diagnostics` — see type errors and warnings for a file.\r\n\r\nCall `LSP` with the target file `path` and `operation`. For `references` and `definition`, also provide 1-based `line` and 0-based `character`. The tool does not modify files; use its results to inform `Read`/`Edit` decisions.\r\n\r\n# General Guidelines for Coding\r\n\r\nWhen working with existing files, prefer `Read` before `Edit`. If `Read` returned an `Anchor:` value in its status block, pass it as `anchor` to `Edit` so the tool can verify the file has not changed since it was read. If the anchor does not match, re-read the file before editing.\r\n\r\nWhen building something from scratch, you should:\r\n\r\n- Understand the user's requirements.\r\n- Ask the user for clarification if there is anything unclear.\r\n- Design the architecture and make a plan for the implementation.\r\n- Write the code in a modular and maintainable way.\r\n\r\nAlways use tools to implement your code changes:\r\n\r\n- Use `Write` to create or overwrite source files. Code that only appears in your text response is NOT saved to the file system and will not take effect.\r\n- Use `Bash` to run and test your code after writing it.\r\n- Iterate: if tests fail, read the error, fix the code with `Write` or `Edit`, and re-test with `Bash`.\r\n\r\nWhen working on an existing codebase, you should:\r\n\r\n- Understand the codebase by reading it with tools (`Read`, `Glob`, `Grep`) before making changes. Identify the ultimate goal and the most important criteria to achieve the goal.\r\n- When using `Glob`, include a literal anchor (file extension or subdirectory) in the pattern. Pure wildcards like `*` or `**/*` are rejected by the tool.\r\n- For a bug fix, you typically need to check error logs or failed tests, scan over the codebase to find the root cause, and figure out a fix. If user mentioned any failed tests, you should make sure they pass after the changes.\r\n- For a feature, you typically need to design the architecture, and write the code in a modular and maintainable way, with minimal intrusions to existing code. Add new tests if the project already has tests.\r\n- For a code refactoring, you typically need to update all the places that call the code you are refactoring if the interface changes. DO NOT change any existing logic especially in tests, focus only on fixing any errors caused by the interface changes.\r\n- Make MINIMAL changes to achieve the goal. This is very important to your performance.\r\n- Follow the coding style of existing code in the project.\r\n- For broader codebase exploration and deep research, use `Agent` with `subagent_type=\"explore\"` — a fast, read-only agent specialized for searching and understanding codebases. Reach for it when your task will clearly require more than 3 search queries, or when you need to investigate multiple files and patterns. Launch multiple explore agents concurrently when investigating independent questions.\r\n\r\nDO NOT run `git commit`, `git push`, `git reset`, `git rebase` and/or do any other git mutations unless explicitly asked to do so. Ask for confirmation each time when you need to do git mutations, even if you have confirmed in earlier conversations.\r\n\r\n# General Guidelines for Research and Data Processing\r\n\r\nThe user may ask you to research on certain topics, process or generate certain multimedia files. When doing such tasks, you must:\r\n\r\n- Understand the user's requirements thoroughly, ask for clarification before you start if needed.\r\n- Make plans before doing deep or wide research, to ensure you are always on track.\r\n- Search on the Internet if possible, with carefully-designed search queries to improve efficiency and accuracy.\r\n- Use proper tools or shell commands or Python packages to process or generate images, videos, PDFs, docs, spreadsheets, presentations, or other media files. Detect if there are already such tools in the environment. If you have to install third-party tools/packages, you MUST ensure that they are installed in a virtual/isolated environment.\r\n- Once you generate or edit any images, videos or other media files, try to read it again before proceed, to ensure that the content is as expected.\r\n- Avoid installing or deleting anything to/from outside of the current working directory. If you have to do so, ask the user for confirmation.\r\n\r\n# Working Environment\r\n\r\n## Operating System\r\n\r\nYou are running on **{{ NEXUM_OS }}**. The Bash tool executes commands using **{{ NEXUM_SHELL }}**.\r\n{% if NEXUM_OS == \"Windows\" %}\r\n\r\nIMPORTANT: You are on Windows. The Bash tool runs through Git Bash, so use Unix shell syntax inside Bash commands — `/dev/null` not `NUL`, and forward slashes in paths. For file operations, always prefer the built-in tools (Read, Write, Edit, Glob, Grep) over Bash commands — they work reliably across all platforms.\r\n{% endif %}\r\n\r\nThe operating environment is not in a sandbox. Any actions you do will immediately affect the user's system. So you MUST be extremely cautious. Unless being explicitly instructed to do so, you should never access (read/write/execute) files outside of the working directory.\r\n\r\n## Date and Time\r\n\r\nThe current date and time in ISO format is `{{ NEXUM_NOW }}`. This is only a reference for you when searching the web, or checking file modification time, etc. If you need the exact time, use Bash tool with proper command.\r\n\r\nYour training data has a knowledge cutoff date. For events, APIs, or package versions released after that date, use web search rather than relying on training data. When you encounter something that may have changed since your cutoff (library APIs, CLI flags, platform policies), search first — do not ask the user for permission.\r\n\r\n## Working Directory\r\n\r\nThe current working directory is `{{ NEXUM_WORK_DIR }}`. This should be considered as the project root if you are instructed to perform tasks on the project. Every file system operation will be relative to the working directory if you do not explicitly specify an absolute path. Tools may require absolute paths for some parameters, IF SO, you MUST use absolute paths for these parameters.\r\n\r\nThe directory listing of current working directory is:\r\n\r\n```\r\n{{ NEXUM_WORK_DIR_LS }}\r\n```\r\n\r\nUse this as your basic understanding of the project structure. The tree only shows the first two levels; entries marked \"... and N more\" indicate additional contents — use Glob or Bash to explore further.\r\n{% if NEXUM_ADDITIONAL_DIRS_INFO %}\r\n\r\n## Additional Directories\r\n\r\nThe following directories have been added to the workspace. You can read, write, search, and glob files in these directories as part of your workspace scope.\r\n\r\n{{ NEXUM_ADDITIONAL_DIRS_INFO }}\r\n{% endif %}\r\n\r\n# Project Information\r\n\r\nMarkdown files named `AGENTS.md` usually contain the background, structure, coding styles, user preferences and other relevant information about the project. You should read this information to understand the project and the user's preferences. `AGENTS.md` files may exist at different locations in the project directory tree, but typically there is one in the project root.\r\n\r\n> Why `AGENTS.md`?\r\n>\r\n> `README.md` files are for humans: quick starts, project descriptions, and contribution guidelines. `AGENTS.md` complements this by containing the extra, sometimes detailed context coding agents need: build steps, tests, and conventions that might clutter a README or aren't relevant to human contributors.\r\n>\r\n> We intentionally kept it separate to:\r\n>\r\n> - Give agents a clear, predictable place for instructions.\r\n> - Keep `README`s concise and focused on human contributors.\r\n> - Provide precise, agent-focused guidance that complements existing `README` and docs.\r\n\r\nThe `AGENTS.md` instructions (merged from all applicable directories):\r\n\r\n``````````````````````````````\r\n{{ NEXUM_AGENTS_MD }}\r\n``````````````````````````````\r\n\r\n`AGENTS.md` files can appear at any level of the project directory tree, including inside `.nexum-code/` directories. Each file governs the directory it resides in and all subdirectories beneath it. When multiple `AGENTS.md` files apply to a file you are modifying, instructions in deeper directories take precedence over those in parent directories. User instructions given directly in the conversation always take the highest precedence.\r\n\r\nWhen working on files in subdirectories, always check whether those directories contain their own `AGENTS.md` with more specific guidance that supplements or overrides the instructions above. You may also check `README`/`README.md` files for more information about the project.\r\n\r\nIf you modified any files/styles/structures/configurations/workflows/... mentioned in `AGENTS.md` files, you MUST update the corresponding `AGENTS.md` files to keep them up-to-date.\r\n\r\n# Skills\r\n\r\nSkills are reusable, composable capabilities that enhance your abilities. Each skill is either a self-contained directory with a `SKILL.md` file or a standalone `.md` file that contains instructions, examples, and/or reference material.\r\n\r\n## What are skills?\r\n\r\nSkills are modular extensions that provide:\r\n\r\n- Specialized knowledge: Domain-specific expertise (e.g., PDF processing, data analysis)\r\n- Workflow patterns: Best practices for common tasks\r\n- Tool integrations: Pre-configured tool chains for specific tasks\r\n- Reference material: Documentation, templates, and examples\r\n\r\n## Available skills\r\n\r\nSkills are grouped by scope (`Project`, `User`, `Extra`, `Built-in`) so you can tell where each came from. When multiple scopes define a skill with the same name, the more specific scope takes precedence: **Project overrides User overrides Extra overrides Built-in**.\r\n\r\n{{ NEXUM_SKILLS }}\r\n\r\n## How to use skills\r\n\r\nIdentify the skills that are likely to be useful for the tasks you are currently working on, read the skill file for detailed instructions, guidelines, scripts and more.\r\n\r\nOnly read skill details when needed to conserve the context window.\r\n\r\n# CONTRACT\r\n\r\nThese rules are inviolable.\r\n\r\n- You NEVER yield unless the deliverable is complete. A phase boundary, todo flip, or completed sub-step is NEVER a yield point — continue directly to the next step in the same turn.\r\n- You NEVER suppress tests to make code pass.\r\n- You NEVER fabricate outputs that were not observed. Claims about code, tools, tests, docs, or external sources MUST be grounded.\r\n- You NEVER substitute the user's problem with an easier or more familiar one.\r\n- You NEVER ask for information that tools, repo context, or files can provide.\r\n- NEVER punt half-solved work back.\r\n- You MUST default to a clean cutover: migrate every caller, leave no compatibility shims, aliases, or deprecated paths behind.\r\n- Be brief in prose, not in evidence, verification, or blocking details.\r\n\r\n## Completeness\r\n\r\n- \"Done\" means the requested deliverable behaves as specified end-to-end, not that a scaffold compiles or a narrowed test passes.\r\n- When a request names a plan, phase list, checklist, or specification, you MUST satisfy every stated acceptance criterion.\r\n- You NEVER silently shrink scope.\r\n- You NEVER ship stubs, placeholders, mocks, no-op implementations, fake fallbacks, or \"TODO: implement\" code as part of a delivered feature.\r\n- Verification claims MUST match what was actually exercised.\r\n- Framing tricks are prohibited: do not relabel unfinished work as \"scaffold\", \"first slice\", \"MVP\", \"foundation\", or \"follow-up\" to imply completion.\r\n\r\n## Yielding\r\n\r\nBefore yielding, you MUST verify:\r\n- All explicitly requested deliverables are complete; no partial implementation is presented as complete.\r\n- All directly affected artifacts (callsites, tests, docs) are updated or intentionally left unchanged.\r\n- The output format matches the ask.\r\n- No unobserved claim is presented as fact.\r\n- No required tool-based lookup was skipped when it would materially reduce uncertainty.\r\n\r\nBefore declaring blocked:\r\n- You MUST be sure the information cannot be obtained through tools, context, or anything within your reach.\r\n- One failing check is not enough to be blocked. You MUST continue until all the remaining work is done, and then report as such.\r\n- If you still cannot proceed, state exactly what is missing and what you tried.\r\n\r\n\r\n# WolfPack Mode\r\n\r\nWhen WolfPack mode is active and the user's request involves multiple independent subtasks or items, use the `WolfPack` tool to parallelize work across subagents. For a single focused subtask, prefer the `Agent` tool. Always emit subagent events so that the Web UI can display progress, item labels, success/failure counts, and final summaries.\r\n",
|
|
128332
129686
|
"profile/default/verify.yaml": "extends: agent\r\nname: verify\r\npromptVars:\r\n roleAdditional: |\r\n You are now running as a sub-agent. All `user` messages are sent by the main agent.\r\n You are the Verify sub-agent. Use me when the main agent is unsure which verification\r\n command to run for a project, or when the project has multiple verification layers\r\n (typecheck, build, test, lint) that need coordinated execution.\r\n\r\n For simple / single-file fixes, the main agent should run the obvious command directly\r\n (e.g. `npx -p typescript tsc --noEmit --strict file.ts`, `python3 -m py_compile file.py`)\r\n instead of spawning this subagent.\r\n\r\n Your sole responsibility is to detect the project type and run verification commands.\r\n Do NOT try to fix anything. Do NOT repeat verification work the parent agent has already\r\n performed.\r\n # Phase 1: Detect project type (deterministic lookup — no guessing)\r\n\r\n Use `Read` to check for these files in order (first match wins).\r\n Read the file content, then look up the exact commands from this table:\r\n\r\n ## package.json exists — read it and check dependencies/devDependencies and scripts:\r\n\r\n | Condition | Type | Build | Test | Lint | Typecheck |\r\n |-----------|------|-------|------|------|-----------|\r\n | `dependencies.next` or `devDependencies.next` | Next.js | `npx next build` | `npm test` (if script exists) | `npx next lint` | `npx tsc --noEmit` or script `typecheck` |\r\n | `dependencies.react-scripts` | CRA | `npx react-scripts build` | `npm test` (if exists) | `npm run lint` (if exists) | `npx tsc --noEmit` or script `typecheck` |\r\n | `devDependencies.vite` or `dependencies.vite` | Vite | `npx vite build` | `npx vitest run` (if script exists) | `npm run lint` (if exists) | `npx tsc --noEmit` or script `typecheck` |\r\n | `devDependencies.@sveltejs/kit` | SvelteKit | `npx vite build` | `npm test` (if exists) | `npm run lint` (if exists) | `npx tsc --noEmit` or script `typecheck` |\r\n | `dependencies.astro` | Astro | `npx astro build` | `npm test` (if exists) | `npm run lint` (if exists) | `npx tsc --noEmit` or script `typecheck` |\r\n | none of the above | Node.js | `npm run build` (if script exists) | `npm test` (if script exists) | `npm run lint` (if script exists) | `npx tsc --noEmit` or script `typecheck` |\r\n\r\n Check `scripts` in package.json for `test`, `lint`, `build`, `typecheck` — only include commands whose scripts actually exist. Look for alternatives: `test:ci`, `test:unit`, `check`, `format:check`.\r\n\r\n IMPORTANT: If `tsconfig.json` exists in the project root or the directory you are verifying, you MUST run a TypeScript typecheck command. Prefer the script `typecheck` if it exists, otherwise run `npx tsc --noEmit` (or `pnpm tsc --noEmit` / `yarn tsc --noEmit` matching the package manager). Do NOT skip typechecking. Do NOT substitute a runtime test for a typecheck failure.\r\n\r\n ## Other ecosystems:\r\n\r\n | File | Type | Build | Test | Lint |\r\n |------|------|-------|------|------|\r\n | `requirements.txt` or `pyproject.toml` | Python | — | `python -m pytest` (if tests/ dir exists) or `python -m unittest` | `ruff check .` |\r\n | `go.mod` | Go | `go build ./...` | `go test ./...` | `go vet ./...` |\r\n | `Cargo.toml` | Rust | `cargo build` | `cargo test` | `cargo clippy` |\r\n | `pom.xml` | Maven | `mvn package -q` | `mvn test` | — |\r\n | `build.gradle` or `build.gradle.kts` | Gradle | `./gradlew build` (or `gradle build`) | `./gradlew test` (or `gradle test`) | — |\r\n | `Makefile` | Make | `make build` (if target exists) | `make test` (if target exists) | `make check` or `make lint` (if target exists) |\r\n\r\n ## Fallback:\r\n If none of the above match, report: \"No supported project type detected.\" and stop.\r\n\r\n # Phase 2: Run commands\r\n\r\n Run each command in order: typecheck → build → test → lint.\r\n For Python/Go/Rust, skip build if the command is not available.\r\n Capture stdout and stderr for each. Time each command.\r\n\r\n If a command fails because the binary is not found (e.g. `command not found: tsc`), report the exact error and stop — do not invent an alternative command. The parent agent must install or locate the correct binary.\r\n\r\n # Phase 3: Report\r\n\r\n Use this exact format (each command gets ONE line):\r\n\r\n ## Verify Report\r\n\r\n **Project:** <detected type>\r\n\r\n ✅ typecheck: passed (<N>s)\r\n ❌ typecheck: failed (<N>s)\r\n <first 30 lines of stderr/stdout with errors>\r\n ✅ build: passed (<N>s)\r\n ❌ test: <N> failed, <M> passed (<N>s)\r\n FAIL <file> > <test name>\r\n <error message>\r\n ⚠️ lint: <N> warnings, no errors (<N>s)\r\n ⏭️ lint: skipped: not configured\r\n\r\n If all pass:\r\n **Result:** ✅ All checks passed.\r\n\r\n If any fail:\r\n **Result:** ❌ <N> check(s) failed. See details above.\r\n\r\n # Phase 4: Machine-readable status\r\n\r\n You MUST end your response with a machine-readable `[verification_status]` block:\r\n\r\n On success:\r\n ```\r\n [verification_status]\r\n passed: true\r\n command: <the primary verification command that was run>\r\n exit_code: 0\r\n ```\r\n\r\n On failure:\r\n ```\r\n [verification_status]\r\n passed: false\r\n command: <command that failed>\r\n exit_code: <non-zero exit code>\r\n ```\r\n\r\n If no supported project type was detected:\r\n ```\r\n [verification_status]\r\n passed: true\r\n command: none\r\n exit_code: 0\r\n ```\r\n\r\n # Rules\r\n\r\n - Do NOT try to fix anything. Report only.\r\n - Do NOT ask questions. Run and report.\r\n - Do NOT run runtime smoke tests as a substitute for a failed typecheck/build/test.\r\n - Skip commands whose scripts/tools don't exist — mark as \"⏭️ skipped: not configured\".\r\n - If the SAME test was already failing before this change (the parent agent will tell you), mark it \"⏭️ pre-existing\" not \"❌\".\r\n\r\nwhenToUse: |\r\n Verification specialist. Detects project type deterministically and runs\r\n build, test, lint, and typecheck commands. Use after writing or modifying code to\r\n confirm correctness before delivering to the user.\r\ntools:\r\n - Bash\r\n - Read\r\n - Glob\r\n - Grep\r\n - MemoryLookup\r\n - MemoryConsolidatePlan\r\n - MemoryConsolidateApply\r\n",
|
|
128333
129687
|
"profile/default/writer.yaml": "extends: agent\r\nname: writer\r\npromptVars:\r\n roleAdditional: |\r\n You are now running as a subagent. All the `user` messages are sent by the main agent. The main agent cannot see your context, it can only see your last message when you finish the task. You must treat the parent agent as your caller. Do not directly ask the end user questions. If something is unclear, explain the ambiguity in your final summary to the parent agent.\r\n\r\n You are a content production and research specialist. Your output is not merely text — it is structured, evidence-based analysis presented in Markdown. Every piece of content you produce must demonstrate depth, traceability, and intellectual honesty.\r\n\r\n ## Core Methodology: Three-Layer Deep Analysis\r\n\r\n Before you write a single paragraph, you must perform a three-layer analysis of the request. This is your most important responsibility. Surface-level writing is not acceptable.\r\n\r\n **Layer 1 — The Ask:** What did the user explicitly request? What is the surface-level topic, format, and scope?\r\n\r\n **Layer 2 — The Purpose:** Why does the user want this? What decision will this content inform? What outcome are they trying to achieve? If the request is a report, who is the audience and what do they need to decide? If it is an analysis, what hypothesis is being tested?\r\n\r\n **Layer 3 — The Origin:** How did this purpose come to be? What is the broader context, market force, organizational pressure, or personal motivation that created this need? What would happen if this need were left unaddressed?\r\n\r\n Your final output must reflect all three layers. The content should not just describe — it should explain, contextualize, and anticipate. The reader should finish reading and think, \"This person truly understands why I needed this.\"\r\n\r\n ## Your Strengths\r\n\r\n - **Multi-dimensional analysis**: You do not settle for a single angle. You examine topics through multiple lenses — economic, technical, social, temporal, competitive — and synthesize them into a coherent narrative.\r\n - **Evidence-based writing**: Every significant claim has a source. You prefer primary sources and data over secondary opinion. You cite sources inline or in a dedicated Evidence section.\r\n - **Objective rigor**: You distinguish fact from inference and inference from speculation. You present counter-arguments. You flag uncertainty explicitly rather than hiding it behind confident language.\r\n - **Table precision**: When data is involved, you present it in clean, accurate Markdown tables. You verify column alignment, unit consistency, and mathematical correctness before outputting.\r\n\r\n ## Guidelines\r\n\r\n ### Deep Analysis\r\n - Start every substantial piece with a \"Why This Matters\" section that captures your three-layer analysis.\r\n - Do not merely list facts. Explain the relationships between them. Cause and effect, trade-offs, second-order consequences.\r\n - When comparing options, use a structured comparison table that covers all relevant dimensions, not just the obvious ones.\r\n - Anticipate the reader's next three questions and address them proactively.\r\n\r\n ### Sources and Evidence\r\n - For data claims, cite the source. Prefer: `SearchWeb`, `FetchURL`, or files provided by the caller.\r\n - If you cannot verify a claim, say so explicitly: \"This figure could not be independently verified.\"\r\n - Distinguish between \"confirmed\" (you checked it), \"reported\" (a source claims it), and \"estimated\" (your inference).\r\n - Include an Evidence section in your output listing sources and verification methods.\r\n\r\n ### Objectivity\r\n - Present both supporting and contradicting evidence.\r\n - Avoid adjectives that imply certainty without proof: \"obviously\", \"undoubtedly\", \"inevitably\".\r\n - Use probabilistic language when appropriate: \"based on current data, the most likely outcome is...\"\r\n - Separate \"what is\" (fact) from \"what it means\" (interpretation) from \"what should be done\" (recommendation).\r\n\r\n ### Markdown Tables (Mandatory for Data)\r\n - All tables use standard Markdown pipe syntax.\r\n - Headers are bold and semantically clear.\r\n - Numbers are right-aligned; text is left-aligned; status/tags are centered.\r\n - Every table has a descriptive caption above it (e.g., \"Table 1: Q1-Q4 Revenue by Region\").\r\n - Keep columns ≤ 8. If more are needed, split into related tables.\r\n - Verify arithmetic: totals, percentages, and growth rates must be correct.\r\n - Use consistent units within a column.\r\n\r\n ### Content Structure\r\n - Use clear heading hierarchies (`#`, `##`, `###`).\r\n - Each major section begins with a concise summary of what the section covers.\r\n - Each major section ends with a \"So What\" takeaway that connects the facts back to the reader's purpose.\r\n - Complex comparisons always use tables. Narrative descriptions of tabular data are insufficient.\r\n\r\n ## Output Format\r\n\r\n Your final response must include:\r\n\r\n ```markdown\r\n ## SUMMARY\r\n A concise executive summary capturing the three-layer analysis and key conclusions.\r\n\r\n ## WHY THIS MATTERS\r\n The three-layer deep analysis (Ask → Purpose → Origin) that frames everything below.\r\n\r\n ## [Main Content Sections]\r\n The body of the analysis, report, or document.\r\n\r\n ## EVIDENCE\r\n - Source A: description and verification method\r\n - Source B: description and verification method\r\n\r\n ## RISKS & LIMITATIONS\r\n What is uncertain, unverified, or context-dependent in this analysis.\r\n ```\r\n\r\n ## Important Reminders\r\n\r\n - Your only output is Markdown content. You do not generate .docx, .pdf, or any other format.\r\n - If the caller asks for a specific file format, output Markdown and note that format conversion is the caller's responsibility.\r\n - If the user provides a template or sample file, Read it first and match its depth, tone, and structure.\r\n - After writing, verify: logical self-consistency, source accuracy, table arithmetic, and structural completeness.\r\n - Never fabricate data. If data is missing, say so and explain the impact of the gap.\r\nwhenToUse: |\r\n Use this agent when the task involves producing substantial written content that requires depth: research reports, competitive analysis, data-driven documents, strategic proposals, or any work where understanding the \"why\" behind the request is as important as the \"what.\" This agent excels at multi-dimensional analysis, evidence-based reasoning, and structured Markdown output with precise tables.\r\ntools:\r\n - Bash\r\n - Read\r\n - ReadMediaFile\r\n - Glob\r\n - Grep\r\n - Write\r\n - Edit\r\n - WebSearch\r\n - FetchURL\r\n - MemoryLookup\r\n - MemoryConsolidatePlan\r\n - MemoryConsolidateApply\r\n - mcp__*\r\n"
|
|
128334
129688
|
};
|
|
@@ -128845,6 +130199,22 @@ var ToolManager = class {
|
|
|
128845
130199
|
source: "mcp"
|
|
128846
130200
|
};
|
|
128847
130201
|
}
|
|
130202
|
+
/**
|
|
130203
|
+
* Returns active tools filtered by capability.
|
|
130204
|
+
*/
|
|
130205
|
+
getToolsByCapability(capability) {
|
|
130206
|
+
return filterToolsByCapabilities(this.data(), [capability]).map((match) => {
|
|
130207
|
+
return this.data().find((t) => t.name === match.name);
|
|
130208
|
+
});
|
|
130209
|
+
}
|
|
130210
|
+
/**
|
|
130211
|
+
* Returns active tools filtered by intent.
|
|
130212
|
+
*/
|
|
130213
|
+
getToolsByIntent(intent) {
|
|
130214
|
+
return filterToolsByIntent(this.data(), intent).map((match) => {
|
|
130215
|
+
return this.data().find((t) => t.name === match.name);
|
|
130216
|
+
});
|
|
130217
|
+
}
|
|
128848
130218
|
data() {
|
|
128849
130219
|
return Array.from(this.toolInfos());
|
|
128850
130220
|
}
|
|
@@ -128863,6 +130233,8 @@ var ToolManager = class {
|
|
|
128863
130233
|
this.builtinTools = new Map([
|
|
128864
130234
|
new ReadTool(jian, workspace),
|
|
128865
130235
|
new ReadGroupTool(jian, workspace),
|
|
130236
|
+
new ReadChunkTool(jian, workspace),
|
|
130237
|
+
new SummarizeOutputTool(this.agent),
|
|
128866
130238
|
new WriteTool(jian, workspace),
|
|
128867
130239
|
new EditTool(jian, workspace),
|
|
128868
130240
|
new GrepTool(jian, workspace),
|
|
@@ -128895,14 +130267,19 @@ var ToolManager = class {
|
|
|
128895
130267
|
this.agent.type === "main" && this.agent.memoStore && new MemoryConsolidatePlanTool(this.agent),
|
|
128896
130268
|
this.agent.type === "main" && this.agent.memoStore && new MemoryConsolidateApplyTool(this.agent),
|
|
128897
130269
|
this.agent.type === "main" && this.agent.memoStore && new MemoryWriteTool(this.agent),
|
|
130270
|
+
this.agent.type === "main" && new GetActiveToolsTool(this.agent),
|
|
130271
|
+
this.agent.type === "main" && new GetToolsByCapabilityTool(this.agent),
|
|
130272
|
+
this.agent.type === "main" && new GetContextUsageTool(this.agent),
|
|
130273
|
+
this.agent.type === "main" && new GetWorkingSetTool(this.agent),
|
|
130274
|
+
this.agent.type === "main" && new GetPlanStateTool(this.agent),
|
|
128898
130275
|
this.agent.skills?.registry.listInvocableSkills().length && new SkillTool(this.agent),
|
|
128899
130276
|
this.agent.type === "main" && new MakeSkillPlanTool(this.agent),
|
|
128900
130277
|
this.agent.type === "main" && new MakeSkillApplyTool(this.agent),
|
|
128901
|
-
this.agent.subagentHost && new AgentTool(this.agent.subagentHost, background, DEFAULT_AGENT_PROFILES["agent"]?.subagents, {
|
|
130278
|
+
this.agent.subagentHost && this.agent.type !== "sub" && new AgentTool(this.agent.subagentHost, background, DEFAULT_AGENT_PROFILES["agent"]?.subagents, {
|
|
128902
130279
|
allowBackground,
|
|
128903
130280
|
log: this.agent.log
|
|
128904
130281
|
}),
|
|
128905
|
-
this.agent.subagentHost && new WolfPackTool(this.agent.subagentHost, () => this.agent.wolfpackMode.isActive, {
|
|
130282
|
+
this.agent.subagentHost && this.agent.type !== "sub" && new WolfPackTool(this.agent.subagentHost, () => this.agent.wolfpackMode.isActive, {
|
|
128906
130283
|
subagents: DEFAULT_AGENT_PROFILES["agent"]?.subagents,
|
|
128907
130284
|
log: this.agent.log
|
|
128908
130285
|
}),
|
|
@@ -129122,7 +130499,49 @@ var ToolCallDeduplicator = class {
|
|
|
129122
130499
|
}
|
|
129123
130500
|
};
|
|
129124
130501
|
//#endregion
|
|
130502
|
+
//#region ../../packages/agent-core/src/agent/turn/intent-convergence.ts
|
|
130503
|
+
function isGoalActive(goal) {
|
|
130504
|
+
return goal?.status === "active" || goal?.status === "complete";
|
|
130505
|
+
}
|
|
130506
|
+
var IntentConvergenceGate = class {
|
|
130507
|
+
options;
|
|
130508
|
+
constructor(options) {
|
|
130509
|
+
this.options = options;
|
|
130510
|
+
}
|
|
130511
|
+
evaluate(input) {
|
|
130512
|
+
if (input.convergenceInjections < input.maxConvergenceInjections) {
|
|
130513
|
+
const reasons = this.collectHardReasons(input);
|
|
130514
|
+
if (reasons.length > 0) return {
|
|
130515
|
+
continue: true,
|
|
130516
|
+
reasons,
|
|
130517
|
+
isSummaryGuard: false
|
|
130518
|
+
};
|
|
130519
|
+
}
|
|
130520
|
+
if (!input.summaryGuardInjected && input.turnHadMeaningfulWork && input.lastAssistantMessageIsTrivial) return {
|
|
130521
|
+
continue: true,
|
|
130522
|
+
reasons: ["Your final response is too brief or only acknowledges completion. Before ending the turn, provide a concise but complete summary: what was done, which files changed, the verification result, and any remaining work or blockers."],
|
|
130523
|
+
isSummaryGuard: true
|
|
130524
|
+
};
|
|
130525
|
+
return {
|
|
130526
|
+
continue: false,
|
|
130527
|
+
reasons: [],
|
|
130528
|
+
isSummaryGuard: false
|
|
130529
|
+
};
|
|
130530
|
+
}
|
|
130531
|
+
collectHardReasons(input) {
|
|
130532
|
+
const reasons = [];
|
|
130533
|
+
if (!input.currentStepHadContent) reasons.push("The last assistant step produced no content or tool calls. Continue the task.");
|
|
130534
|
+
if (isGoalActive(input.goal) && !input.todoSeenThisTurn) reasons.push("An active goal exists but no TodoList update was made this turn. Update TodoList and continue.");
|
|
130535
|
+
const hasPassedVerification = input.latestVerification?.passed === true;
|
|
130536
|
+
if (input.lastToolFailure?.isExploratory === false && !hasPassedVerification) reasons.push(`A required tool (${input.lastToolFailure.toolName}) failed this turn. Analyze the error and fix it before reporting completion.`);
|
|
130537
|
+
if (input.latestVerification !== void 0 && !input.latestVerification.passed && !input.verificationFailureInjected) reasons.push(`The last verification command failed (${input.latestVerification.command}). Fix the failure before re-running verification. Do NOT downgrade to runtime smoke tests.`);
|
|
130538
|
+
return reasons;
|
|
130539
|
+
}
|
|
130540
|
+
};
|
|
130541
|
+
//#endregion
|
|
129125
130542
|
//#region ../../packages/agent-core/src/agent/turn/index.ts
|
|
130543
|
+
/** Maximum buffered steer messages while a turn is already running. */
|
|
130544
|
+
const MAX_STEER_BUFFER = 32;
|
|
129126
130545
|
const GOAL_CONTINUATION_PROMPT = [
|
|
129127
130546
|
"Continue working toward the active goal.",
|
|
129128
130547
|
"Keep the self-audit brief. Do not explore unrelated interpretations once the goal can be",
|
|
@@ -129159,8 +130578,15 @@ var TurnFlow = class {
|
|
|
129159
130578
|
turnStartVerificationCount = 0;
|
|
129160
130579
|
verificationFailureInjected = false;
|
|
129161
130580
|
MIN_FINAL_RESPONSE_LENGTH = 60;
|
|
130581
|
+
ledger;
|
|
130582
|
+
convergenceGate;
|
|
129162
130583
|
constructor(agent) {
|
|
129163
130584
|
this.agent = agent;
|
|
130585
|
+
this.ledger = new ResourceLedger();
|
|
130586
|
+
this.convergenceGate = new IntentConvergenceGate({
|
|
130587
|
+
maxConvergenceInjections: this.MAX_CONVERGENCE_INJECTIONS,
|
|
130588
|
+
minFinalResponseLength: this.MIN_FINAL_RESPONSE_LENGTH
|
|
130589
|
+
});
|
|
129164
130590
|
}
|
|
129165
130591
|
prompt(input, origin = USER_PROMPT_ORIGIN) {
|
|
129166
130592
|
this.agent.records.logRecord({
|
|
@@ -129177,10 +130603,7 @@ var TurnFlow = class {
|
|
|
129177
130603
|
origin
|
|
129178
130604
|
});
|
|
129179
130605
|
if (this.activeTurn) {
|
|
129180
|
-
this.
|
|
129181
|
-
input,
|
|
129182
|
-
origin
|
|
129183
|
-
});
|
|
130606
|
+
this.bufferSteer(input, origin);
|
|
129184
130607
|
return null;
|
|
129185
130608
|
}
|
|
129186
130609
|
return this.launch(input, origin);
|
|
@@ -129210,10 +130633,7 @@ var TurnFlow = class {
|
|
|
129210
130633
|
}
|
|
129211
130634
|
restoreSteer(input, origin) {
|
|
129212
130635
|
if (this.activeTurn) {
|
|
129213
|
-
this.
|
|
129214
|
-
input,
|
|
129215
|
-
origin
|
|
129216
|
-
});
|
|
130636
|
+
this.bufferSteer(input, origin);
|
|
129217
130637
|
return;
|
|
129218
130638
|
}
|
|
129219
130639
|
this.turnId += 1;
|
|
@@ -129261,6 +130681,47 @@ var TurnFlow = class {
|
|
|
129261
130681
|
steers.length = 0;
|
|
129262
130682
|
return true;
|
|
129263
130683
|
}
|
|
130684
|
+
bufferSteer(input, origin) {
|
|
130685
|
+
if (this.steerBuffer.length < MAX_STEER_BUFFER) {
|
|
130686
|
+
this.steerBuffer.push({
|
|
130687
|
+
input,
|
|
130688
|
+
origin
|
|
130689
|
+
});
|
|
130690
|
+
return;
|
|
130691
|
+
}
|
|
130692
|
+
if (isBackgroundOrCronOrigin(origin)) {
|
|
130693
|
+
const coalescedCount = this.coalesceBackgroundSteers() + 1;
|
|
130694
|
+
this.steerBuffer.push({
|
|
130695
|
+
input: [{
|
|
130696
|
+
type: "text",
|
|
130697
|
+
text: `${coalescedCount} 个后台事件待处理`
|
|
130698
|
+
}],
|
|
130699
|
+
origin: {
|
|
130700
|
+
kind: "system_trigger",
|
|
130701
|
+
name: "background_events_backpressure"
|
|
130702
|
+
}
|
|
130703
|
+
});
|
|
130704
|
+
return;
|
|
130705
|
+
}
|
|
130706
|
+
const dropIndex = this.steerBuffer.findIndex((steer) => steer.origin.kind !== "user");
|
|
130707
|
+
if (dropIndex !== -1) this.steerBuffer.splice(dropIndex, 1);
|
|
130708
|
+
else this.steerBuffer.shift();
|
|
130709
|
+
this.steerBuffer.push({
|
|
130710
|
+
input,
|
|
130711
|
+
origin
|
|
130712
|
+
});
|
|
130713
|
+
}
|
|
130714
|
+
coalesceBackgroundSteers() {
|
|
130715
|
+
let count = 0;
|
|
130716
|
+
this.steerBuffer = this.steerBuffer.filter((steer) => {
|
|
130717
|
+
if (isBackgroundOrCronOrigin(steer.origin)) {
|
|
130718
|
+
count += 1;
|
|
130719
|
+
return false;
|
|
130720
|
+
}
|
|
130721
|
+
return true;
|
|
130722
|
+
});
|
|
130723
|
+
return count;
|
|
130724
|
+
}
|
|
129264
130725
|
finishResume() {
|
|
129265
130726
|
if (this.activeTurn === "resuming") this.activeTurn = null;
|
|
129266
130727
|
this.steerBuffer.length = 0;
|
|
@@ -129292,6 +130753,7 @@ var TurnFlow = class {
|
|
|
129292
130753
|
let turnInput = input;
|
|
129293
130754
|
let turnOrigin = origin;
|
|
129294
130755
|
while (true) {
|
|
130756
|
+
this.agent.goal.checkpointWallClock();
|
|
129295
130757
|
const goalBeforeTurn = this.agent.goal.getGoal().goal;
|
|
129296
130758
|
if (goalBeforeTurn?.status === "active") {
|
|
129297
130759
|
if (effectiveMaxGoalTurns > 0 && goalBeforeTurn.budget.turnBudget === null && goalBeforeTurn.turnsUsed >= effectiveMaxGoalTurns) {
|
|
@@ -129423,6 +130885,7 @@ var TurnFlow = class {
|
|
|
129423
130885
|
this.agent.emitEvent(ended);
|
|
129424
130886
|
if (standalone && this.currentId === turnId) this.activeTurn = null;
|
|
129425
130887
|
if (errorEvent !== void 0) this.agent.emitEvent(errorEvent);
|
|
130888
|
+
this.agent.goal.checkpointWallClock();
|
|
129426
130889
|
this.currentStepByTurn.delete(turnId);
|
|
129427
130890
|
return {
|
|
129428
130891
|
event: ended,
|
|
@@ -129501,6 +130964,7 @@ var TurnFlow = class {
|
|
|
129501
130964
|
log: this.agent.log,
|
|
129502
130965
|
maxSteps: loopControl?.maxStepsPerTurn,
|
|
129503
130966
|
maxRetryAttempts: loopControl?.maxRetriesPerStep,
|
|
130967
|
+
ledger: this.ledger,
|
|
129504
130968
|
hooks: {
|
|
129505
130969
|
beforeStep: async ({ signal: stepSignal, stepNumber }) => {
|
|
129506
130970
|
this.flushSteerBuffer();
|
|
@@ -129531,6 +130995,7 @@ var TurnFlow = class {
|
|
|
129531
130995
|
},
|
|
129532
130996
|
afterStep: async ({ usage }) => {
|
|
129533
130997
|
this.agent.usage.record(model, usage, "turn");
|
|
130998
|
+
this.agent.goal.checkpointWallClock();
|
|
129534
130999
|
await this.agent.goal.recordTokenUsage(grandTotal(usage));
|
|
129535
131000
|
await this.agent.fullCompaction.afterStep();
|
|
129536
131001
|
deduper.endStep();
|
|
@@ -129539,28 +131004,29 @@ var TurnFlow = class {
|
|
|
129539
131004
|
if (this.flushSteerBuffer()) return { continue: true };
|
|
129540
131005
|
signal.throwIfAborted();
|
|
129541
131006
|
const latestVerification = this.agent.workingSet.getLatestVerificationForTurn(this.currentTurnId);
|
|
129542
|
-
const
|
|
129543
|
-
|
|
129544
|
-
|
|
129545
|
-
|
|
129546
|
-
|
|
129547
|
-
|
|
129548
|
-
|
|
129549
|
-
|
|
129550
|
-
|
|
129551
|
-
|
|
129552
|
-
|
|
131007
|
+
const currentGoal = this.agent.goal.getGoal().goal;
|
|
131008
|
+
const gateResult = this.convergenceGate.evaluate({
|
|
131009
|
+
currentStepHadContent: this.currentStepHadContent,
|
|
131010
|
+
goal: currentGoal === null ? void 0 : { status: currentGoal.status },
|
|
131011
|
+
todoSeenThisTurn: this.todoSeenThisTurn,
|
|
131012
|
+
lastToolFailure: this.lastToolFailure,
|
|
131013
|
+
latestVerification,
|
|
131014
|
+
verificationFailureInjected: this.verificationFailureInjected,
|
|
131015
|
+
turnHadMeaningfulWork: this.turnHadMeaningfulWork(),
|
|
131016
|
+
lastAssistantMessageIsTrivial: this.lastAssistantMessageIsTrivial(),
|
|
131017
|
+
convergenceInjections: this.convergenceInjections,
|
|
131018
|
+
maxConvergenceInjections: this.MAX_CONVERGENCE_INJECTIONS,
|
|
131019
|
+
summaryGuardInjected: this.summaryGuardInjected,
|
|
131020
|
+
minFinalResponseLength: this.MIN_FINAL_RESPONSE_LENGTH
|
|
131021
|
+
});
|
|
131022
|
+
if (gateResult.continue) {
|
|
131023
|
+
if (gateResult.isSummaryGuard) this.summaryGuardInjected = true;
|
|
131024
|
+
else {
|
|
129553
131025
|
this.convergenceInjections += 1;
|
|
129554
|
-
|
|
129555
|
-
kind: "system_trigger",
|
|
129556
|
-
name: "convergence_gate"
|
|
129557
|
-
});
|
|
129558
|
-
return { continue: true };
|
|
131026
|
+
if (latestVerification !== void 0 && !latestVerification.passed) this.verificationFailureInjected = true;
|
|
129559
131027
|
}
|
|
129560
|
-
|
|
129561
|
-
|
|
129562
|
-
this.summaryGuardInjected = true;
|
|
129563
|
-
this.agent.context.appendSystemReminder("Your final response is too brief or only acknowledges completion. Before ending the turn, provide a concise but complete summary: what was done, which files changed, the verification result, and any remaining work or blockers.", {
|
|
131028
|
+
const reminderText = gateResult.isSummaryGuard ? gateResult.reasons.join("\n") : `${gateResult.reasons.join("\n")}\n\nDo not report completion until the above is resolved.`;
|
|
131029
|
+
this.agent.context.appendSystemReminder(reminderText, {
|
|
129564
131030
|
kind: "system_trigger",
|
|
129565
131031
|
name: "convergence_gate"
|
|
129566
131032
|
});
|
|
@@ -129785,6 +131251,10 @@ var TurnFlow = class {
|
|
|
129785
131251
|
].some((pattern) => pattern.test(normalized));
|
|
129786
131252
|
}
|
|
129787
131253
|
};
|
|
131254
|
+
function isBackgroundOrCronOrigin(origin) {
|
|
131255
|
+
const kind = origin.kind;
|
|
131256
|
+
return kind === "background_task" || kind === "cron_job" || kind === "cron_missed";
|
|
131257
|
+
}
|
|
129788
131258
|
function getAssistantMessageText(message) {
|
|
129789
131259
|
if (message.role !== "assistant") return "";
|
|
129790
131260
|
return message.content.filter((part) => part.type === "text").map((part) => part.text).join("");
|
|
@@ -130365,6 +131835,7 @@ var Agent = class {
|
|
|
130365
131835
|
workingSet;
|
|
130366
131836
|
dreamTracker;
|
|
130367
131837
|
replayBuilder;
|
|
131838
|
+
memoryPromotionCursor;
|
|
130368
131839
|
lastLlmConfigLogSignature;
|
|
130369
131840
|
constructor(options) {
|
|
130370
131841
|
this.type = options.type ?? "main";
|
|
@@ -130381,6 +131852,7 @@ var Agent = class {
|
|
|
130381
131852
|
this.mcp = options.mcp;
|
|
130382
131853
|
this.hooks = options.hookEngine;
|
|
130383
131854
|
this.log = options.log ?? log;
|
|
131855
|
+
this.memoryPromotionCursor = createMemoryPromotionCursor();
|
|
130384
131856
|
this.blobStore = options.homedir ? new BlobStore({ blobsDir: join$1(options.homedir, "blobs") }) : void 0;
|
|
130385
131857
|
this.records = new AgentRecords(this, options.persistence ?? (options.homedir ? new FileSystemAgentRecordPersistence(join$1(options.homedir, "wire.jsonl"), {
|
|
130386
131858
|
onError: (error) => {
|
|
@@ -130388,7 +131860,7 @@ var Agent = class {
|
|
|
130388
131860
|
},
|
|
130389
131861
|
blobStore: this.blobStore
|
|
130390
131862
|
}) : void 0));
|
|
130391
|
-
this.fullCompaction = new FullCompaction(this, options.compactionStrategy);
|
|
131863
|
+
this.fullCompaction = new FullCompaction(this, options.compactionStrategy, this.memoryPromotionCursor);
|
|
130392
131864
|
this.microCompaction = new MicroCompaction(this);
|
|
130393
131865
|
this.context = new ContextMemory(this);
|
|
130394
131866
|
this.config = new ConfigState(this);
|
|
@@ -135061,11 +136533,13 @@ var SessionSubagentHost = class {
|
|
|
135061
136533
|
session;
|
|
135062
136534
|
ownerAgentId;
|
|
135063
136535
|
backgroundTaskTimeoutMs;
|
|
136536
|
+
modelBindings;
|
|
135064
136537
|
activeChildren = /* @__PURE__ */ new Map();
|
|
135065
|
-
constructor(session, ownerAgentId, backgroundTaskTimeoutMs) {
|
|
136538
|
+
constructor(session, ownerAgentId, backgroundTaskTimeoutMs, modelBindings) {
|
|
135066
136539
|
this.session = session;
|
|
135067
136540
|
this.ownerAgentId = ownerAgentId;
|
|
135068
136541
|
this.backgroundTaskTimeoutMs = backgroundTaskTimeoutMs;
|
|
136542
|
+
this.modelBindings = modelBindings;
|
|
135069
136543
|
}
|
|
135070
136544
|
async spawn(profileName, options) {
|
|
135071
136545
|
options.signal.throwIfAborted();
|
|
@@ -135121,7 +136595,13 @@ var SessionSubagentHost = class {
|
|
|
135121
136595
|
...options,
|
|
135122
136596
|
signal: controller.signal
|
|
135123
136597
|
}, () => {
|
|
135124
|
-
|
|
136598
|
+
const binding = this.resolveModelBinding(profileName);
|
|
136599
|
+
const modelAlias = this.resolveValidModelAlias(parent, binding);
|
|
136600
|
+
const thinkingLevel = this.resolveThinkingLevel(parent, binding, parent.config.thinkingLevel);
|
|
136601
|
+
child.config.update({
|
|
136602
|
+
modelAlias,
|
|
136603
|
+
thinkingLevel
|
|
136604
|
+
});
|
|
135125
136605
|
return Promise.resolve();
|
|
135126
136606
|
}).finally(() => {
|
|
135127
136607
|
unlinkAbortSignal();
|
|
@@ -135220,20 +136700,50 @@ var SessionSubagentHost = class {
|
|
|
135220
136700
|
type: "subagent.failed",
|
|
135221
136701
|
subagentId: childId,
|
|
135222
136702
|
parentToolCallId: options.parentToolCallId,
|
|
135223
|
-
error: message
|
|
136703
|
+
error: message,
|
|
136704
|
+
usage: child.usage.data().total
|
|
135224
136705
|
});
|
|
135225
136706
|
throw error;
|
|
135226
136707
|
}
|
|
135227
136708
|
}
|
|
135228
136709
|
async configureChild(parent, child, profile) {
|
|
136710
|
+
const binding = this.resolveModelBinding(profile.name);
|
|
136711
|
+
const modelAlias = this.resolveValidModelAlias(parent, binding);
|
|
136712
|
+
const thinkingLevel = this.resolveThinkingLevel(parent, binding, parent.config.thinkingLevel);
|
|
135229
136713
|
child.config.update({
|
|
135230
136714
|
cwd: parent.config.cwd,
|
|
135231
|
-
modelAlias
|
|
135232
|
-
thinkingLevel
|
|
136715
|
+
modelAlias,
|
|
136716
|
+
thinkingLevel
|
|
135233
136717
|
});
|
|
135234
136718
|
const context = await prepareSystemPromptContext(child.jian);
|
|
135235
136719
|
child.useProfile(profile, context);
|
|
135236
136720
|
}
|
|
136721
|
+
resolveModelBinding(profileName) {
|
|
136722
|
+
const bindings = this.modelBindings?.();
|
|
136723
|
+
if (bindings === void 0) return void 0;
|
|
136724
|
+
const alias = bindings[profileName];
|
|
136725
|
+
if (typeof alias !== "string" || alias.trim().length === 0) return void 0;
|
|
136726
|
+
return alias;
|
|
136727
|
+
}
|
|
136728
|
+
resolveValidModelAlias(parent, binding) {
|
|
136729
|
+
if (binding === void 0) return parent.config.modelAlias;
|
|
136730
|
+
if (parent.modelProvider === void 0) return parent.config.modelAlias;
|
|
136731
|
+
try {
|
|
136732
|
+
parent.modelProvider.resolveProviderConfig(binding);
|
|
136733
|
+
return binding;
|
|
136734
|
+
} catch (error) {
|
|
136735
|
+
this.session.log?.warn(`subagent binding "${binding}" no longer resolves in the provider registry; falling back to parent model "${parent.config.modelAlias}"`, error);
|
|
136736
|
+
return parent.config.modelAlias;
|
|
136737
|
+
}
|
|
136738
|
+
}
|
|
136739
|
+
resolveThinkingLevel(parent, binding, parentLevel) {
|
|
136740
|
+
if (binding === void 0 || parent.modelProvider === void 0) return parentLevel;
|
|
136741
|
+
try {
|
|
136742
|
+
return parent.modelProvider.resolveProviderConfig(binding).modelCapabilities.thinking ? parentLevel : "off";
|
|
136743
|
+
} catch {
|
|
136744
|
+
return parentLevel;
|
|
136745
|
+
}
|
|
136746
|
+
}
|
|
135237
136747
|
async triggerSubagentStart(parent, profileName, prompt, signal) {
|
|
135238
136748
|
await parent.hooks?.trigger("SubagentStart", {
|
|
135239
136749
|
matcherValue: profileName,
|
|
@@ -135597,7 +137107,7 @@ var Session$1 = class {
|
|
|
135597
137107
|
rpc: proxyWithExtraPayload(this.rpc, { agentId: id }),
|
|
135598
137108
|
modelProvider: this.options.providerManager,
|
|
135599
137109
|
hookEngine: config.hookEngine ?? this.hookEngine,
|
|
135600
|
-
subagentHost: config.subagentHost ?? new SessionSubagentHost(this, id, this.backgroundTaskTimeoutMs()),
|
|
137110
|
+
subagentHost: config.subagentHost ?? new SessionSubagentHost(this, id, this.backgroundTaskTimeoutMs(), this.options.subagentModelBindings),
|
|
135601
137111
|
mcp: this.mcp,
|
|
135602
137112
|
permission: this.permissionOptions(parentAgentId, config.permission),
|
|
135603
137113
|
log: this.log.createChild({ agentId: id }),
|
|
@@ -150980,6 +152490,7 @@ var NexumCore = class {
|
|
|
150980
152490
|
nexumRequestHeaders;
|
|
150981
152491
|
resolveOAuthTokenProvider;
|
|
150982
152492
|
skillDirs;
|
|
152493
|
+
subagentModelBindings;
|
|
150983
152494
|
sessionStore;
|
|
150984
152495
|
plugins;
|
|
150985
152496
|
pluginsReady;
|
|
@@ -151000,6 +152511,7 @@ var NexumCore = class {
|
|
|
151000
152511
|
this.nexumRequestHeaders = options.nexumRequestHeaders;
|
|
151001
152512
|
this.resolveOAuthTokenProvider = options.resolveOAuthTokenProvider;
|
|
151002
152513
|
this.skillDirs = options.skillDirs ?? [];
|
|
152514
|
+
this.subagentModelBindings = options.subagentModelBindings;
|
|
151003
152515
|
ensureNexumHome(this.homeDir);
|
|
151004
152516
|
this.config = loadRuntimeConfig(this.configPath);
|
|
151005
152517
|
this.sessionStore = new SessionStore(this.homeDir);
|
|
@@ -151009,6 +152521,9 @@ var NexumCore = class {
|
|
|
151009
152521
|
});
|
|
151010
152522
|
this.sdk = rpcClient(this);
|
|
151011
152523
|
}
|
|
152524
|
+
setSubagentModelBindings(getter) {
|
|
152525
|
+
this.subagentModelBindings = getter;
|
|
152526
|
+
}
|
|
151012
152527
|
/** Resolve the shell environment so missing Git Bash is surfaced early. */
|
|
151013
152528
|
async preflight() {
|
|
151014
152529
|
await this.jian;
|
|
@@ -151050,7 +152565,8 @@ var NexumCore = class {
|
|
|
151050
152565
|
permissionRules: config.permission?.rules,
|
|
151051
152566
|
skills: this.resolveSessionSkillConfig(config),
|
|
151052
152567
|
mcpConfig,
|
|
151053
|
-
pluginSessionStarts
|
|
152568
|
+
pluginSessionStarts,
|
|
152569
|
+
subagentModelBindings: this.subagentModelBindings
|
|
151054
152570
|
});
|
|
151055
152571
|
try {
|
|
151056
152572
|
session.metadata = {
|
|
@@ -151128,7 +152644,8 @@ var NexumCore = class {
|
|
|
151128
152644
|
skills: this.resolveSessionSkillConfig(config),
|
|
151129
152645
|
mcpConfig,
|
|
151130
152646
|
initializeMainAgent: false,
|
|
151131
|
-
pluginSessionStarts
|
|
152647
|
+
pluginSessionStarts,
|
|
152648
|
+
subagentModelBindings: this.subagentModelBindings
|
|
151132
152649
|
});
|
|
151133
152650
|
let warning;
|
|
151134
152651
|
try {
|
|
@@ -151728,7 +153245,7 @@ var DocumentJobsClient = class {
|
|
|
151728
153245
|
const enableLocalOcr = options.enableLocalOcr ?? true;
|
|
151729
153246
|
this.service = new DocumentIntelligenceService({
|
|
151730
153247
|
outputDir: options.outputDir,
|
|
151731
|
-
ocrProvider: enableLocalOcr ?
|
|
153248
|
+
ocrProvider: enableLocalOcr ? createDefaultOcrProvider() : void 0,
|
|
151732
153249
|
pdfPageRenderer: enableLocalOcr ? createPdfjsPageRenderer() : void 0,
|
|
151733
153250
|
usePdfOcrFallback: enableLocalOcr
|
|
151734
153251
|
});
|
|
@@ -151780,7 +153297,8 @@ var SDKRpcClient = class {
|
|
|
151780
153297
|
configPath: options.configPath,
|
|
151781
153298
|
nexumRequestHeaders,
|
|
151782
153299
|
resolveOAuthTokenProvider: options.resolveOAuthTokenProvider,
|
|
151783
|
-
skillDirs: options.skillDirs
|
|
153300
|
+
skillDirs: options.skillDirs,
|
|
153301
|
+
subagentModelBindings: options.subagentModelBindings
|
|
151784
153302
|
});
|
|
151785
153303
|
this.ready = sdkRpc(new ClientAPI(this)).then((rpc) => {
|
|
151786
153304
|
this.rpc = rpc;
|
|
@@ -152781,6 +154299,9 @@ var NexumHarness = class {
|
|
|
152781
154299
|
set interactiveAgentId(agentId) {
|
|
152782
154300
|
this.rpc.interactiveAgentId = agentId;
|
|
152783
154301
|
}
|
|
154302
|
+
setSubagentModelBindings(getter) {
|
|
154303
|
+
this.rpc.core.setSubagentModelBindings(getter);
|
|
154304
|
+
}
|
|
152784
154305
|
async createSession(options) {
|
|
152785
154306
|
if (typeof options.workDir !== "string" || options.workDir.trim().length === 0) throw new NexumError(ErrorCodes.REQUEST_WORK_DIR_REQUIRED, "createSession requires workDir");
|
|
152786
154307
|
const summary = await this.rpc.createSession({
|
|
@@ -153155,10 +154676,10 @@ function optionalBuildString(value) {
|
|
|
153155
154676
|
return typeof value === "string" && value.length > 0 ? value : void 0;
|
|
153156
154677
|
}
|
|
153157
154678
|
const NEXUM_BUILD_INFO = {
|
|
153158
|
-
version:
|
|
153159
|
-
channel:
|
|
153160
|
-
commit:
|
|
153161
|
-
buildTarget:
|
|
154679
|
+
version: optionalBuildString("0.7.6"),
|
|
154680
|
+
channel: optionalBuildString(""),
|
|
154681
|
+
commit: optionalBuildString(""),
|
|
154682
|
+
buildTarget: optionalBuildString("win32-x64")
|
|
153162
154683
|
};
|
|
153163
154684
|
//#endregion
|
|
153164
154685
|
//#region src/cli/version.ts
|
|
@@ -153384,6 +154905,157 @@ function validateOptions(opts) {
|
|
|
153384
154905
|
};
|
|
153385
154906
|
}
|
|
153386
154907
|
//#endregion
|
|
154908
|
+
//#region src/tui/config.ts
|
|
154909
|
+
/**
|
|
154910
|
+
* TUI-owned configuration.
|
|
154911
|
+
*
|
|
154912
|
+
* Agent/runtime settings live in core's `config.toml`; this file owns only
|
|
154913
|
+
* terminal UI preferences for the nexum-code client.
|
|
154914
|
+
*/
|
|
154915
|
+
const INVALID_TUI_CONFIG_MESSAGE = "~/.nexum-code/tui.toml 中的 TUI 配置无效;使用默认配置。";
|
|
154916
|
+
const TuiThemeSchema = z.enum([
|
|
154917
|
+
"dark",
|
|
154918
|
+
"light",
|
|
154919
|
+
"auto"
|
|
154920
|
+
]);
|
|
154921
|
+
const NotificationConditionSchema = z.enum(["unfocused", "always"]);
|
|
154922
|
+
const NotificationsConfigSchema = z.object({
|
|
154923
|
+
enabled: z.boolean(),
|
|
154924
|
+
condition: NotificationConditionSchema
|
|
154925
|
+
});
|
|
154926
|
+
const TuiLikePreferencesSchema = z.object({
|
|
154927
|
+
nickname: z.string().optional(),
|
|
154928
|
+
tone: z.string().optional(),
|
|
154929
|
+
other: z.string().optional()
|
|
154930
|
+
});
|
|
154931
|
+
const TuiConfigFileSchema = z.object({
|
|
154932
|
+
theme: TuiThemeSchema.optional(),
|
|
154933
|
+
editor: z.object({ command: z.string().optional() }).optional(),
|
|
154934
|
+
notifications: z.object({
|
|
154935
|
+
enabled: z.boolean().optional(),
|
|
154936
|
+
notification_condition: NotificationConditionSchema.optional()
|
|
154937
|
+
}).optional(),
|
|
154938
|
+
like: TuiLikePreferencesSchema.optional(),
|
|
154939
|
+
subagentModels: z.record(z.string(), z.string()).optional()
|
|
154940
|
+
});
|
|
154941
|
+
const TuiConfigSchema = z.object({
|
|
154942
|
+
theme: TuiThemeSchema,
|
|
154943
|
+
editorCommand: z.string().nullable(),
|
|
154944
|
+
notifications: NotificationsConfigSchema,
|
|
154945
|
+
like: TuiLikePreferencesSchema,
|
|
154946
|
+
subagentModels: z.record(z.string(), z.string())
|
|
154947
|
+
});
|
|
154948
|
+
const DEFAULT_NOTIFICATIONS_CONFIG = {
|
|
154949
|
+
enabled: true,
|
|
154950
|
+
condition: "unfocused"
|
|
154951
|
+
};
|
|
154952
|
+
const DEFAULT_LIKE_PREFERENCES = {
|
|
154953
|
+
nickname: void 0,
|
|
154954
|
+
tone: void 0,
|
|
154955
|
+
other: void 0
|
|
154956
|
+
};
|
|
154957
|
+
const DEFAULT_TUI_CONFIG = TuiConfigSchema.parse({
|
|
154958
|
+
theme: "auto",
|
|
154959
|
+
editorCommand: null,
|
|
154960
|
+
notifications: DEFAULT_NOTIFICATIONS_CONFIG,
|
|
154961
|
+
like: DEFAULT_LIKE_PREFERENCES,
|
|
154962
|
+
subagentModels: {}
|
|
154963
|
+
});
|
|
154964
|
+
/**
|
|
154965
|
+
* Thrown by `loadTuiConfig` when the on-disk TOML cannot be parsed.
|
|
154966
|
+
* Carries `fallback` so the caller can recover without re-running the
|
|
154967
|
+
* I/O, and use `message` (== `INVALID_TUI_CONFIG_MESSAGE`) as a
|
|
154968
|
+
* user-facing notice.
|
|
154969
|
+
*/
|
|
154970
|
+
var TuiConfigParseError = class extends Error {
|
|
154971
|
+
name = "TuiConfigParseError";
|
|
154972
|
+
fallback;
|
|
154973
|
+
constructor(fallback) {
|
|
154974
|
+
super(INVALID_TUI_CONFIG_MESSAGE);
|
|
154975
|
+
this.fallback = fallback;
|
|
154976
|
+
}
|
|
154977
|
+
};
|
|
154978
|
+
function getTuiConfigPath() {
|
|
154979
|
+
return join(getDataDir(), "tui.toml");
|
|
154980
|
+
}
|
|
154981
|
+
async function loadTuiConfig(filePath = getTuiConfigPath()) {
|
|
154982
|
+
if (!existsSync(filePath)) {
|
|
154983
|
+
await saveTuiConfig(DEFAULT_TUI_CONFIG, filePath);
|
|
154984
|
+
return DEFAULT_TUI_CONFIG;
|
|
154985
|
+
}
|
|
154986
|
+
try {
|
|
154987
|
+
return parseTuiConfig(await readFile(filePath, "utf-8"));
|
|
154988
|
+
} catch {
|
|
154989
|
+
throw new TuiConfigParseError(DEFAULT_TUI_CONFIG);
|
|
154990
|
+
}
|
|
154991
|
+
}
|
|
154992
|
+
function parseTuiConfig(tomlText) {
|
|
154993
|
+
if (tomlText.trim().length === 0) return DEFAULT_TUI_CONFIG;
|
|
154994
|
+
const raw = parse$1(tomlText);
|
|
154995
|
+
return normalizeTuiConfig(TuiConfigFileSchema.parse(raw));
|
|
154996
|
+
}
|
|
154997
|
+
async function saveTuiConfig(config, filePath = getTuiConfigPath()) {
|
|
154998
|
+
await mkdir(dirname$1(filePath), { recursive: true });
|
|
154999
|
+
await writeFile(filePath, renderTuiConfig(config), "utf-8");
|
|
155000
|
+
}
|
|
155001
|
+
function normalizeTuiConfig(config) {
|
|
155002
|
+
const command = config.editor?.command?.trim();
|
|
155003
|
+
return TuiConfigSchema.parse({
|
|
155004
|
+
theme: config.theme ?? DEFAULT_TUI_CONFIG.theme,
|
|
155005
|
+
editorCommand: command === void 0 || command.length === 0 ? null : command,
|
|
155006
|
+
notifications: {
|
|
155007
|
+
enabled: config.notifications?.enabled ?? DEFAULT_NOTIFICATIONS_CONFIG.enabled,
|
|
155008
|
+
condition: config.notifications?.notification_condition ?? DEFAULT_NOTIFICATIONS_CONFIG.condition
|
|
155009
|
+
},
|
|
155010
|
+
like: {
|
|
155011
|
+
nickname: config.like?.nickname,
|
|
155012
|
+
tone: config.like?.tone,
|
|
155013
|
+
other: config.like?.other
|
|
155014
|
+
},
|
|
155015
|
+
subagentModels: normalizeSubagentModels(config.subagentModels)
|
|
155016
|
+
});
|
|
155017
|
+
}
|
|
155018
|
+
function normalizeSubagentModels(raw) {
|
|
155019
|
+
if (raw === void 0) return {};
|
|
155020
|
+
const out = {};
|
|
155021
|
+
for (const [profileName, alias] of Object.entries(raw)) {
|
|
155022
|
+
const key = profileName.trim();
|
|
155023
|
+
const val = typeof alias === "string" ? alias.trim() : "";
|
|
155024
|
+
if (key.length > 0 && val.length > 0) out[key] = val;
|
|
155025
|
+
}
|
|
155026
|
+
return out;
|
|
155027
|
+
}
|
|
155028
|
+
function renderTuiConfig(config) {
|
|
155029
|
+
const like = config.like ?? DEFAULT_LIKE_PREFERENCES;
|
|
155030
|
+
const subagentModelsBlock = renderSubagentModelsBlock(config.subagentModels ?? {});
|
|
155031
|
+
return `# ~/.nexum-code/tui.toml
|
|
155032
|
+
# Terminal UI preferences for nexum-code.
|
|
155033
|
+
# Agent/runtime settings stay in ~/.nexum-code/config.toml.
|
|
155034
|
+
|
|
155035
|
+
theme = "${config.theme}" # "auto" | "dark" | "light"
|
|
155036
|
+
|
|
155037
|
+
[editor]
|
|
155038
|
+
command = "${escapeTomlBasicString(config.editorCommand ?? "")}" # Empty uses $VISUAL / $EDITOR
|
|
155039
|
+
|
|
155040
|
+
[notifications]
|
|
155041
|
+
enabled = ${String(config.notifications.enabled)} # true | false
|
|
155042
|
+
notification_condition = "${config.notifications.condition}" # "unfocused" | "always"
|
|
155043
|
+
|
|
155044
|
+
[like]
|
|
155045
|
+
nickname = "${escapeTomlBasicString(like.nickname ?? "")}"
|
|
155046
|
+
tone = "${escapeTomlBasicString(like.tone ?? "")}"
|
|
155047
|
+
other = "${escapeTomlBasicString(like.other ?? "")}"
|
|
155048
|
+
${subagentModelsBlock}`;
|
|
155049
|
+
}
|
|
155050
|
+
function renderSubagentModelsBlock(models) {
|
|
155051
|
+
const entries = Object.entries(models);
|
|
155052
|
+
if (entries.length === 0) return "";
|
|
155053
|
+
return `\n[subagentModels]\n${entries.map(([name, alias]) => `${name} = "${escapeTomlBasicString(alias)}"`).join("\n")}\n`;
|
|
155054
|
+
}
|
|
155055
|
+
function escapeTomlBasicString(value) {
|
|
155056
|
+
return value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("\b", "\\b").replaceAll(" ", "\\t").replaceAll("\n", "\\n").replaceAll("\f", "\\f").replaceAll("\r", "\\r");
|
|
155057
|
+
}
|
|
155058
|
+
//#endregion
|
|
153387
155059
|
//#region src/cli/run-prompt.ts
|
|
153388
155060
|
const PROMPT_UI_MODE = "print";
|
|
153389
155061
|
const PROMPT_MAIN_AGENT_ID = "main";
|
|
@@ -153400,6 +155072,15 @@ async function runPrompt(opts, version, io = {}) {
|
|
|
153400
155072
|
uiMode: PROMPT_UI_MODE,
|
|
153401
155073
|
skillDirs: opts.skillsDirs
|
|
153402
155074
|
});
|
|
155075
|
+
let promptTuiConfig;
|
|
155076
|
+
try {
|
|
155077
|
+
promptTuiConfig = await loadTuiConfig();
|
|
155078
|
+
} catch (error) {
|
|
155079
|
+
if (!(error instanceof TuiConfigParseError)) throw error;
|
|
155080
|
+
promptTuiConfig = error.fallback;
|
|
155081
|
+
}
|
|
155082
|
+
const promptSubagentModels = promptTuiConfig.subagentModels;
|
|
155083
|
+
harness.setSubagentModelBindings(() => promptSubagentModels);
|
|
153403
155084
|
log.info("nexum-code starting", {
|
|
153404
155085
|
version,
|
|
153405
155086
|
uiMode: PROMPT_UI_MODE,
|
|
@@ -153840,137 +155521,6 @@ function formatTurnEndedFailure(event) {
|
|
|
153840
155521
|
return `提示回合结束,原因:${event.reason}`;
|
|
153841
155522
|
}
|
|
153842
155523
|
//#endregion
|
|
153843
|
-
//#region src/tui/config.ts
|
|
153844
|
-
/**
|
|
153845
|
-
* TUI-owned configuration.
|
|
153846
|
-
*
|
|
153847
|
-
* Agent/runtime settings live in core's `config.toml`; this file owns only
|
|
153848
|
-
* terminal UI preferences for the nexum-code client.
|
|
153849
|
-
*/
|
|
153850
|
-
const INVALID_TUI_CONFIG_MESSAGE = "~/.nexum-code/tui.toml 中的 TUI 配置无效;使用默认配置。";
|
|
153851
|
-
const TuiThemeSchema = z.enum([
|
|
153852
|
-
"dark",
|
|
153853
|
-
"light",
|
|
153854
|
-
"auto"
|
|
153855
|
-
]);
|
|
153856
|
-
const NotificationConditionSchema = z.enum(["unfocused", "always"]);
|
|
153857
|
-
const NotificationsConfigSchema = z.object({
|
|
153858
|
-
enabled: z.boolean(),
|
|
153859
|
-
condition: NotificationConditionSchema
|
|
153860
|
-
});
|
|
153861
|
-
const TuiLikePreferencesSchema = z.object({
|
|
153862
|
-
nickname: z.string().optional(),
|
|
153863
|
-
tone: z.string().optional(),
|
|
153864
|
-
other: z.string().optional()
|
|
153865
|
-
});
|
|
153866
|
-
const TuiConfigFileSchema = z.object({
|
|
153867
|
-
theme: TuiThemeSchema.optional(),
|
|
153868
|
-
editor: z.object({ command: z.string().optional() }).optional(),
|
|
153869
|
-
notifications: z.object({
|
|
153870
|
-
enabled: z.boolean().optional(),
|
|
153871
|
-
notification_condition: NotificationConditionSchema.optional()
|
|
153872
|
-
}).optional(),
|
|
153873
|
-
like: TuiLikePreferencesSchema.optional()
|
|
153874
|
-
});
|
|
153875
|
-
const TuiConfigSchema = z.object({
|
|
153876
|
-
theme: TuiThemeSchema,
|
|
153877
|
-
editorCommand: z.string().nullable(),
|
|
153878
|
-
notifications: NotificationsConfigSchema,
|
|
153879
|
-
like: TuiLikePreferencesSchema
|
|
153880
|
-
});
|
|
153881
|
-
const DEFAULT_NOTIFICATIONS_CONFIG = {
|
|
153882
|
-
enabled: true,
|
|
153883
|
-
condition: "unfocused"
|
|
153884
|
-
};
|
|
153885
|
-
const DEFAULT_LIKE_PREFERENCES = {
|
|
153886
|
-
nickname: void 0,
|
|
153887
|
-
tone: void 0,
|
|
153888
|
-
other: void 0
|
|
153889
|
-
};
|
|
153890
|
-
const DEFAULT_TUI_CONFIG = TuiConfigSchema.parse({
|
|
153891
|
-
theme: "auto",
|
|
153892
|
-
editorCommand: null,
|
|
153893
|
-
notifications: DEFAULT_NOTIFICATIONS_CONFIG,
|
|
153894
|
-
like: DEFAULT_LIKE_PREFERENCES
|
|
153895
|
-
});
|
|
153896
|
-
/**
|
|
153897
|
-
* Thrown by `loadTuiConfig` when the on-disk TOML cannot be parsed.
|
|
153898
|
-
* Carries `fallback` so the caller can recover without re-running the
|
|
153899
|
-
* I/O, and use `message` (== `INVALID_TUI_CONFIG_MESSAGE`) as a
|
|
153900
|
-
* user-facing notice.
|
|
153901
|
-
*/
|
|
153902
|
-
var TuiConfigParseError = class extends Error {
|
|
153903
|
-
name = "TuiConfigParseError";
|
|
153904
|
-
fallback;
|
|
153905
|
-
constructor(fallback) {
|
|
153906
|
-
super(INVALID_TUI_CONFIG_MESSAGE);
|
|
153907
|
-
this.fallback = fallback;
|
|
153908
|
-
}
|
|
153909
|
-
};
|
|
153910
|
-
function getTuiConfigPath() {
|
|
153911
|
-
return join(getDataDir(), "tui.toml");
|
|
153912
|
-
}
|
|
153913
|
-
async function loadTuiConfig(filePath = getTuiConfigPath()) {
|
|
153914
|
-
if (!existsSync(filePath)) {
|
|
153915
|
-
await saveTuiConfig(DEFAULT_TUI_CONFIG, filePath);
|
|
153916
|
-
return DEFAULT_TUI_CONFIG;
|
|
153917
|
-
}
|
|
153918
|
-
try {
|
|
153919
|
-
return parseTuiConfig(await readFile(filePath, "utf-8"));
|
|
153920
|
-
} catch {
|
|
153921
|
-
throw new TuiConfigParseError(DEFAULT_TUI_CONFIG);
|
|
153922
|
-
}
|
|
153923
|
-
}
|
|
153924
|
-
function parseTuiConfig(tomlText) {
|
|
153925
|
-
if (tomlText.trim().length === 0) return DEFAULT_TUI_CONFIG;
|
|
153926
|
-
const raw = parse$1(tomlText);
|
|
153927
|
-
return normalizeTuiConfig(TuiConfigFileSchema.parse(raw));
|
|
153928
|
-
}
|
|
153929
|
-
async function saveTuiConfig(config, filePath = getTuiConfigPath()) {
|
|
153930
|
-
await mkdir(dirname$1(filePath), { recursive: true });
|
|
153931
|
-
await writeFile(filePath, renderTuiConfig(config), "utf-8");
|
|
153932
|
-
}
|
|
153933
|
-
function normalizeTuiConfig(config) {
|
|
153934
|
-
const command = config.editor?.command?.trim();
|
|
153935
|
-
return TuiConfigSchema.parse({
|
|
153936
|
-
theme: config.theme ?? DEFAULT_TUI_CONFIG.theme,
|
|
153937
|
-
editorCommand: command === void 0 || command.length === 0 ? null : command,
|
|
153938
|
-
notifications: {
|
|
153939
|
-
enabled: config.notifications?.enabled ?? DEFAULT_NOTIFICATIONS_CONFIG.enabled,
|
|
153940
|
-
condition: config.notifications?.notification_condition ?? DEFAULT_NOTIFICATIONS_CONFIG.condition
|
|
153941
|
-
},
|
|
153942
|
-
like: {
|
|
153943
|
-
nickname: config.like?.nickname,
|
|
153944
|
-
tone: config.like?.tone,
|
|
153945
|
-
other: config.like?.other
|
|
153946
|
-
}
|
|
153947
|
-
});
|
|
153948
|
-
}
|
|
153949
|
-
function renderTuiConfig(config) {
|
|
153950
|
-
const like = config.like ?? DEFAULT_LIKE_PREFERENCES;
|
|
153951
|
-
return `# ~/.nexum-code/tui.toml
|
|
153952
|
-
# Terminal UI preferences for nexum-code.
|
|
153953
|
-
# Agent/runtime settings stay in ~/.nexum-code/config.toml.
|
|
153954
|
-
|
|
153955
|
-
theme = "${config.theme}" # "auto" | "dark" | "light"
|
|
153956
|
-
|
|
153957
|
-
[editor]
|
|
153958
|
-
command = "${escapeTomlBasicString(config.editorCommand ?? "")}" # Empty uses $VISUAL / $EDITOR
|
|
153959
|
-
|
|
153960
|
-
[notifications]
|
|
153961
|
-
enabled = ${String(config.notifications.enabled)} # true | false
|
|
153962
|
-
notification_condition = "${config.notifications.condition}" # "unfocused" | "always"
|
|
153963
|
-
|
|
153964
|
-
[like]
|
|
153965
|
-
nickname = "${escapeTomlBasicString(like.nickname ?? "")}"
|
|
153966
|
-
tone = "${escapeTomlBasicString(like.tone ?? "")}"
|
|
153967
|
-
other = "${escapeTomlBasicString(like.other ?? "")}"
|
|
153968
|
-
`;
|
|
153969
|
-
}
|
|
153970
|
-
function escapeTomlBasicString(value) {
|
|
153971
|
-
return value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("\b", "\\b").replaceAll(" ", "\\t").replaceAll("\n", "\\n").replaceAll("\f", "\\f").replaceAll("\r", "\\r");
|
|
153972
|
-
}
|
|
153973
|
-
//#endregion
|
|
153974
155524
|
//#region src/tui/constant/rendering.ts
|
|
153975
155525
|
const MAX_SHELL_OUTPUT_BYTES = 128 * 1024;
|
|
153976
155526
|
const BRAILLE_SPINNER_FRAMES = [
|
|
@@ -155596,6 +157146,111 @@ var SettingsSelectorComponent = class extends ChoicePickerComponent {
|
|
|
155596
157146
|
}
|
|
155597
157147
|
};
|
|
155598
157148
|
//#endregion
|
|
157149
|
+
//#region src/tui/components/dialogs/subagent-model-binder.ts
|
|
157150
|
+
const FOLLOW_MAIN = "__follow_main__";
|
|
157151
|
+
const SUBAGENT_PROFILES = [
|
|
157152
|
+
{
|
|
157153
|
+
name: "coder",
|
|
157154
|
+
description: "通用软件工程任务"
|
|
157155
|
+
},
|
|
157156
|
+
{
|
|
157157
|
+
name: "reviewer",
|
|
157158
|
+
description: "代码审查,发现 bug 和 API 契约违反"
|
|
157159
|
+
},
|
|
157160
|
+
{
|
|
157161
|
+
name: "writer",
|
|
157162
|
+
description: "内容生产与研究报告"
|
|
157163
|
+
},
|
|
157164
|
+
{
|
|
157165
|
+
name: "explore",
|
|
157166
|
+
description: "快速代码库探索(只读)"
|
|
157167
|
+
},
|
|
157168
|
+
{
|
|
157169
|
+
name: "oracle",
|
|
157170
|
+
description: "深度调试与架构决策"
|
|
157171
|
+
},
|
|
157172
|
+
{
|
|
157173
|
+
name: "plan",
|
|
157174
|
+
description: "实现规划与架构设计(只读)"
|
|
157175
|
+
},
|
|
157176
|
+
{
|
|
157177
|
+
name: "verify",
|
|
157178
|
+
description: "运行构建/测试/lint 验证改动"
|
|
157179
|
+
}
|
|
157180
|
+
];
|
|
157181
|
+
function showSubagentModelBinder(host) {
|
|
157182
|
+
mountProfileList(host);
|
|
157183
|
+
}
|
|
157184
|
+
function mountProfileList(host) {
|
|
157185
|
+
const { subagentModels: bindings, availableModels } = host.state.appState;
|
|
157186
|
+
const options = SUBAGENT_PROFILES.map((profile) => {
|
|
157187
|
+
const alias = bindings[profile.name];
|
|
157188
|
+
const bindingLabel = alias === void 0 ? "跟随主模型" : modelDisplayName$1(alias, availableModels[alias]);
|
|
157189
|
+
return {
|
|
157190
|
+
value: profile.name,
|
|
157191
|
+
label: `${profile.name} -> ${bindingLabel}`,
|
|
157192
|
+
description: profile.description
|
|
157193
|
+
};
|
|
157194
|
+
});
|
|
157195
|
+
host.mountEditorReplacement(new ChoicePickerComponent({
|
|
157196
|
+
title: "子代理模型绑定",
|
|
157197
|
+
hint: "↑↓ 选择子代理 · Enter 绑定模型 · Esc 取消",
|
|
157198
|
+
options,
|
|
157199
|
+
colors: host.state.theme.colors,
|
|
157200
|
+
onSelect: (profileName) => {
|
|
157201
|
+
mountModelPicker(host, profileName);
|
|
157202
|
+
},
|
|
157203
|
+
onCancel: () => {
|
|
157204
|
+
host.restoreEditor();
|
|
157205
|
+
}
|
|
157206
|
+
}));
|
|
157207
|
+
}
|
|
157208
|
+
function mountModelPicker(host, profileName) {
|
|
157209
|
+
const { subagentModels: bindings, availableModels } = host.state.appState;
|
|
157210
|
+
const currentBinding = bindings[profileName] ?? FOLLOW_MAIN;
|
|
157211
|
+
const options = [{
|
|
157212
|
+
value: FOLLOW_MAIN,
|
|
157213
|
+
label: "跟随主模型",
|
|
157214
|
+
description: "使用主代理当前模型(默认)"
|
|
157215
|
+
}, ...Object.entries(availableModels).map(([alias, cfg]) => ({
|
|
157216
|
+
value: alias,
|
|
157217
|
+
label: modelDisplayName$1(alias, cfg)
|
|
157218
|
+
}))];
|
|
157219
|
+
host.mountEditorReplacement(new ChoicePickerComponent({
|
|
157220
|
+
title: `绑定 ${profileName}`,
|
|
157221
|
+
hint: "↑↓ 选择模型 · Enter 确认 · Esc 返回",
|
|
157222
|
+
options,
|
|
157223
|
+
currentValue: currentBinding,
|
|
157224
|
+
colors: host.state.theme.colors,
|
|
157225
|
+
searchable: true,
|
|
157226
|
+
onSelect: (value) => {
|
|
157227
|
+
applyBinding(host, profileName, value);
|
|
157228
|
+
},
|
|
157229
|
+
onCancel: () => {
|
|
157230
|
+
mountProfileList(host);
|
|
157231
|
+
}
|
|
157232
|
+
}));
|
|
157233
|
+
}
|
|
157234
|
+
async function applyBinding(host, profileName, value) {
|
|
157235
|
+
const configPath = getTuiConfigPath();
|
|
157236
|
+
try {
|
|
157237
|
+
const current = await loadTuiConfig(configPath);
|
|
157238
|
+
const updated = { ...current.subagentModels };
|
|
157239
|
+
if (value === FOLLOW_MAIN) delete updated[profileName];
|
|
157240
|
+
else updated[profileName] = value;
|
|
157241
|
+
await saveTuiConfig({
|
|
157242
|
+
...current,
|
|
157243
|
+
subagentModels: updated
|
|
157244
|
+
}, configPath);
|
|
157245
|
+
host.setAppState({ subagentModels: updated });
|
|
157246
|
+
const label = value === FOLLOW_MAIN ? "跟随主模型" : modelDisplayName$1(value, host.state.appState.availableModels[value]);
|
|
157247
|
+
host.showStatus(`${profileName} -> ${label}`, host.state.theme.colors.success);
|
|
157248
|
+
} catch (error) {
|
|
157249
|
+
host.showError(`保存失败:${error instanceof Error ? error.message : String(error)}`);
|
|
157250
|
+
}
|
|
157251
|
+
mountProfileList(host);
|
|
157252
|
+
}
|
|
157253
|
+
//#endregion
|
|
155599
157254
|
//#region src/tui/components/dialogs/theme-selector.ts
|
|
155600
157255
|
const THEME_OPTIONS = [
|
|
155601
157256
|
{
|
|
@@ -155639,6 +157294,8 @@ const TERMINAL_FOCUS_IN = `[I`;
|
|
|
155639
157294
|
const TERMINAL_FOCUS_OUT = `[O`;
|
|
155640
157295
|
const ENABLE_TERMINAL_FOCUS_REPORTING = `[?1004h`;
|
|
155641
157296
|
const DISABLE_TERMINAL_FOCUS_REPORTING = `[?1004l`;
|
|
157297
|
+
const ENABLE_TERMINAL_MOUSE_REPORTING = `[?1000h[?1006h`;
|
|
157298
|
+
const DISABLE_TERMINAL_MOUSE_REPORTING = `[?1000l[?1006l`;
|
|
155642
157299
|
const OSC11_QUERY = `]11;?`;
|
|
155643
157300
|
const OSC11_RESPONSE = new RegExp(String.raw`${"\x1B"}?\]11;rgb:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})${`(?:|\\\\)`}`, "i");
|
|
155644
157301
|
const OSC11_RESPONSE_PREFIX = `]11;rgb:`;
|
|
@@ -155958,6 +157615,14 @@ function resolveThemeSync(theme) {
|
|
|
155958
157615
|
return theme;
|
|
155959
157616
|
}
|
|
155960
157617
|
//#endregion
|
|
157618
|
+
//#region src/tui/utils/app-state.ts
|
|
157619
|
+
function isStreaming(state) {
|
|
157620
|
+
return state.streamingPhase !== "idle";
|
|
157621
|
+
}
|
|
157622
|
+
function isBusy(state) {
|
|
157623
|
+
return isStreaming(state) || state.isCompacting;
|
|
157624
|
+
}
|
|
157625
|
+
//#endregion
|
|
155961
157626
|
//#region src/utils/usage/usage-format.ts
|
|
155962
157627
|
/**
|
|
155963
157628
|
* Formatting helpers for the `/usage` slash command.
|
|
@@ -156044,6 +157709,22 @@ function buildManagedUsageSection(usage, error, accent, value, muted, errorStyle
|
|
|
156044
157709
|
}
|
|
156045
157710
|
return out;
|
|
156046
157711
|
}
|
|
157712
|
+
function buildSubagentUsageSection(usage, accent, value, muted) {
|
|
157713
|
+
const entries = Object.entries(usage ?? {});
|
|
157714
|
+
if (entries.length === 0) return [];
|
|
157715
|
+
const lines = [accent("子 Agent 用量")];
|
|
157716
|
+
let totalInput = 0;
|
|
157717
|
+
let totalOutput = 0;
|
|
157718
|
+
for (const [name, row] of entries) {
|
|
157719
|
+
const input = usageInputTotal$1(row);
|
|
157720
|
+
const output = usageNumber(row.output);
|
|
157721
|
+
totalInput += input;
|
|
157722
|
+
totalOutput += output;
|
|
157723
|
+
lines.push(` ${muted(name)} 输入 ${value(formatTokenCount$1(input))} 输出 ${value(formatTokenCount$1(output))} 总计 ${value(formatTokenCount$1(input + output))}`);
|
|
157724
|
+
}
|
|
157725
|
+
if (entries.length > 1) lines.push(` ${muted("总计")} 输入 ${value(formatTokenCount$1(totalInput))} 输出 ${value(formatTokenCount$1(totalOutput))} 总计 ${value(formatTokenCount$1(totalInput + totalOutput))}`);
|
|
157726
|
+
return lines;
|
|
157727
|
+
}
|
|
156047
157728
|
function buildManagedUsageReportLines(options) {
|
|
156048
157729
|
const colors = options.colors;
|
|
156049
157730
|
const accent = chalk.hex(colors.primary).bold;
|
|
@@ -156079,6 +157760,11 @@ function buildUsageReportLines(options) {
|
|
|
156079
157760
|
lines.push("");
|
|
156080
157761
|
lines.push(...managedSection);
|
|
156081
157762
|
}
|
|
157763
|
+
const subagentSection = buildSubagentUsageSection(options.subagentUsage, accent, value, muted);
|
|
157764
|
+
if (subagentSection.length > 0) {
|
|
157765
|
+
lines.push("");
|
|
157766
|
+
lines.push(...subagentSection);
|
|
157767
|
+
}
|
|
156082
157768
|
return lines;
|
|
156083
157769
|
}
|
|
156084
157770
|
var UsagePanelComponent = class {
|
|
@@ -156222,7 +157908,8 @@ async function showUsage(host) {
|
|
|
156222
157908
|
contextTokens: host.state.appState.contextTokens,
|
|
156223
157909
|
maxContextTokens: host.state.appState.maxContextTokens,
|
|
156224
157910
|
managedUsage: managedUsage?.usage,
|
|
156225
|
-
managedUsageError: managedUsage?.error
|
|
157911
|
+
managedUsageError: managedUsage?.error,
|
|
157912
|
+
subagentUsage: host.state.appState.subagentUsage
|
|
156226
157913
|
}), host.state.theme.colors.primary);
|
|
156227
157914
|
host.state.transcriptContainer.addChild(panel);
|
|
156228
157915
|
host.state.ui.requestRender();
|
|
@@ -156296,15 +157983,15 @@ async function handlePlanCommand(host, args) {
|
|
|
156296
157983
|
host.showNotice("计划已清除");
|
|
156297
157984
|
return;
|
|
156298
157985
|
}
|
|
156299
|
-
let
|
|
156300
|
-
if (subcmd.length === 0)
|
|
156301
|
-
else if (subcmd === "on")
|
|
156302
|
-
else if (subcmd === "off")
|
|
157986
|
+
let state;
|
|
157987
|
+
if (subcmd.length === 0) state = host.state.appState.planMode === "off" ? "plan" : "off";
|
|
157988
|
+
else if (subcmd === "on") state = "plan";
|
|
157989
|
+
else if (subcmd === "off") state = "off";
|
|
156303
157990
|
else {
|
|
156304
157991
|
host.showError(`Unknown plan subcommand: ${subcmd}`);
|
|
156305
157992
|
return;
|
|
156306
157993
|
}
|
|
156307
|
-
await applyPlanMode(host, session,
|
|
157994
|
+
await applyPlanMode(host, session, state);
|
|
156308
157995
|
}
|
|
156309
157996
|
async function handleFusionPlanCommand(host, args) {
|
|
156310
157997
|
const session = host.session;
|
|
@@ -156318,26 +158005,24 @@ async function handleFusionPlanCommand(host, args) {
|
|
|
156318
158005
|
host.showNotice("融合计划已清除");
|
|
156319
158006
|
return;
|
|
156320
158007
|
}
|
|
156321
|
-
let
|
|
156322
|
-
if (subcmd.length === 0)
|
|
156323
|
-
else if (subcmd === "on")
|
|
156324
|
-
else if (subcmd === "off")
|
|
158008
|
+
let state;
|
|
158009
|
+
if (subcmd.length === 0) state = host.state.appState.planMode === "fusionplan" ? "off" : "fusionplan";
|
|
158010
|
+
else if (subcmd === "on") state = "fusionplan";
|
|
158011
|
+
else if (subcmd === "off") state = "off";
|
|
156325
158012
|
else {
|
|
156326
158013
|
host.showError(`Unknown fusionplan subcommand: ${subcmd}`);
|
|
156327
158014
|
return;
|
|
156328
158015
|
}
|
|
156329
|
-
await applyPlanMode(host, session,
|
|
158016
|
+
await applyPlanMode(host, session, state);
|
|
156330
158017
|
}
|
|
156331
|
-
async function applyPlanMode(host, session,
|
|
158018
|
+
async function applyPlanMode(host, session, state) {
|
|
158019
|
+
const enabled = state !== "off";
|
|
156332
158020
|
try {
|
|
156333
158021
|
if (((await session.getStatus().catch(() => null))?.planMode ?? false) !== enabled) await session.setPlanMode(enabled);
|
|
156334
|
-
|
|
156335
|
-
if (enabled)
|
|
156336
|
-
|
|
156337
|
-
|
|
156338
|
-
return;
|
|
156339
|
-
}
|
|
156340
|
-
host.showNotice("计划模式:关闭");
|
|
158022
|
+
let planPath;
|
|
158023
|
+
if (enabled) planPath = (await session.getPlan().catch(() => null))?.path;
|
|
158024
|
+
host.setAppState({ planMode: state });
|
|
158025
|
+
host.setPlanModeBanner(state, planPath);
|
|
156341
158026
|
} catch (error) {
|
|
156342
158027
|
const msg = formatErrorMessage(error);
|
|
156343
158028
|
host.showError(`Failed to set plan mode: ${msg}`);
|
|
@@ -156480,7 +158165,12 @@ async function handleThemeCommand(host, args) {
|
|
|
156480
158165
|
await applyThemeChoice(host, theme);
|
|
156481
158166
|
}
|
|
156482
158167
|
function handleModelCommand(host, args) {
|
|
156483
|
-
const
|
|
158168
|
+
const trimmed = args.trim();
|
|
158169
|
+
if (trimmed === "diy") {
|
|
158170
|
+
showSubagentModelBinder(host);
|
|
158171
|
+
return;
|
|
158172
|
+
}
|
|
158173
|
+
const alias = trimmed;
|
|
156484
158174
|
if (alias.length === 0) {
|
|
156485
158175
|
showModelPicker(host);
|
|
156486
158176
|
return;
|
|
@@ -156516,7 +158206,8 @@ async function applyEditorChoice(host, value) {
|
|
|
156516
158206
|
theme: host.state.appState.theme,
|
|
156517
158207
|
editorCommand,
|
|
156518
158208
|
notifications: host.state.appState.notifications,
|
|
156519
|
-
like: host.state.appState.like
|
|
158209
|
+
like: host.state.appState.like,
|
|
158210
|
+
subagentModels: host.state.appState.subagentModels
|
|
156520
158211
|
});
|
|
156521
158212
|
} catch (error) {
|
|
156522
158213
|
host.showStatus(`Failed to save editor: ${formatErrorMessage(error)}`, host.state.theme.colors.error);
|
|
@@ -156547,7 +158238,7 @@ function showModelPicker(host, selectedValue = host.state.appState.model) {
|
|
|
156547
158238
|
}));
|
|
156548
158239
|
}
|
|
156549
158240
|
async function performModelSwitch(host, alias, thinkingLevel) {
|
|
156550
|
-
if (host.state.appState
|
|
158241
|
+
if (isBusy(host.state.appState)) {
|
|
156551
158242
|
host.showError("Cannot switch models while streaming — press Esc or Ctrl-C first.");
|
|
156552
158243
|
return;
|
|
156553
158244
|
}
|
|
@@ -156644,7 +158335,8 @@ async function applyThemeChoice(host, theme) {
|
|
|
156644
158335
|
theme,
|
|
156645
158336
|
editorCommand: host.state.appState.editorCommand,
|
|
156646
158337
|
notifications: host.state.appState.notifications,
|
|
156647
|
-
like: host.state.appState.like
|
|
158338
|
+
like: host.state.appState.like,
|
|
158339
|
+
subagentModels: host.state.appState.subagentModels
|
|
156648
158340
|
});
|
|
156649
158341
|
} catch (error) {
|
|
156650
158342
|
host.showStatus(`Failed to save theme: ${formatErrorMessage(error)}`, host.state.theme.colors.error);
|
|
@@ -157171,6 +158863,13 @@ var GoalStatusMessageComponent = class {
|
|
|
157171
158863
|
}
|
|
157172
158864
|
};
|
|
157173
158865
|
//#endregion
|
|
158866
|
+
//#region src/tui/utils/goal-loop-conflict.ts
|
|
158867
|
+
function detectGoalLoopConflict(state, action) {
|
|
158868
|
+
if (action === "enable_loop" && state.goalActive) return "goal_active";
|
|
158869
|
+
if (action === "enable_goal" && state.loopModeEnabled) return "loop_active";
|
|
158870
|
+
return null;
|
|
158871
|
+
}
|
|
158872
|
+
//#endregion
|
|
157174
158873
|
//#region src/tui/commands/goal.ts
|
|
157175
158874
|
const GOAL_STATUS_DISMISS_MS = 1e4;
|
|
157176
158875
|
let activeGoalPanel;
|
|
@@ -157242,10 +158941,14 @@ async function createGoal(host, parsed) {
|
|
|
157242
158941
|
host.showError("没有活跃的会话。");
|
|
157243
158942
|
return;
|
|
157244
158943
|
}
|
|
158944
|
+
if (detectGoalLoopConflict(host.state.appState, "enable_goal") === "loop_active") {
|
|
158945
|
+
host.showNotice("Storm Breaker(风暴守护者)", "当前已开启循环模式(/loop)。/goal 与 /loop 语义冲突:loop 每轮重置上下文,会破坏 goal 的工作笔记迭代。请先 /loop 关闭循环模式,再设置目标。");
|
|
158946
|
+
return;
|
|
158947
|
+
}
|
|
157245
158948
|
try {
|
|
157246
158949
|
await session.createGoal(parsed.objective, { replace: parsed.replace });
|
|
157247
158950
|
host.showStatus(`🎯 目标已设置:${parsed.objective}`);
|
|
157248
|
-
if (host.state.appState
|
|
158951
|
+
if (!isBusy(host.state.appState)) host.sendQueuedMessage(session, {
|
|
157249
158952
|
text: parsed.objective,
|
|
157250
158953
|
agentId: void 0
|
|
157251
158954
|
});
|
|
@@ -157289,7 +158992,7 @@ async function resumeGoal(host) {
|
|
|
157289
158992
|
}
|
|
157290
158993
|
await session.updateGoalStatus("active");
|
|
157291
158994
|
host.showStatus("🎯 目标已恢复。");
|
|
157292
|
-
if (host.state.appState
|
|
158995
|
+
if (!isBusy(host.state.appState)) host.sendQueuedMessage(session, {
|
|
157293
158996
|
text: "继续执行当前目标。",
|
|
157294
158997
|
agentId: void 0
|
|
157295
158998
|
});
|
|
@@ -157348,12 +159051,14 @@ function dismissGoalPanel(host) {
|
|
|
157348
159051
|
host.state.ui.requestRender();
|
|
157349
159052
|
}
|
|
157350
159053
|
}
|
|
159054
|
+
const startTime = Date.now();
|
|
159055
|
+
function getBreathingFrame() {
|
|
159056
|
+
return Math.floor((Date.now() - startTime) / 40) % 120;
|
|
159057
|
+
}
|
|
157351
159058
|
//#endregion
|
|
157352
159059
|
//#region src/tui/components/chrome/welcome.ts
|
|
157353
159060
|
const HUE_STOPS = 24;
|
|
157354
159061
|
const SUB_STEPS = 5;
|
|
157355
|
-
const BREATHE_STEPS = HUE_STOPS * SUB_STEPS;
|
|
157356
|
-
const BREATHE_INTERVAL_MS$1 = 40;
|
|
157357
159062
|
const WELCOME_TIPS = [
|
|
157358
159063
|
"/config 配置模型",
|
|
157359
159064
|
"/sessions 恢复历史会话",
|
|
@@ -157462,7 +159167,6 @@ var WelcomeComponent = class {
|
|
|
157462
159167
|
state;
|
|
157463
159168
|
colors;
|
|
157464
159169
|
ui;
|
|
157465
|
-
breatheFrame = 0;
|
|
157466
159170
|
breatheTimer = null;
|
|
157467
159171
|
breathePalette;
|
|
157468
159172
|
recentSessions;
|
|
@@ -157480,20 +159184,17 @@ var WelcomeComponent = class {
|
|
|
157480
159184
|
clearInterval(this.breatheTimer);
|
|
157481
159185
|
this.breatheTimer = null;
|
|
157482
159186
|
}
|
|
157483
|
-
|
|
157484
|
-
this.breatheFrame = 0;
|
|
157485
|
-
this.ui.requestRender();
|
|
157486
|
-
}
|
|
159187
|
+
this.ui.requestRender();
|
|
157487
159188
|
}
|
|
157488
159189
|
startBreathing() {
|
|
157489
159190
|
this.breatheTimer = setInterval(() => {
|
|
157490
|
-
this.breatheFrame = (this.breatheFrame + 1) % BREATHE_STEPS;
|
|
157491
159191
|
this.ui.requestRender();
|
|
157492
|
-
},
|
|
159192
|
+
}, 40);
|
|
157493
159193
|
}
|
|
157494
159194
|
invalidate() {}
|
|
157495
159195
|
render(width) {
|
|
157496
|
-
const
|
|
159196
|
+
const breatheFrame = getBreathingFrame();
|
|
159197
|
+
const breatheColor = this.breathePalette[breatheFrame] ?? this.colors.primary;
|
|
157497
159198
|
const boxColor = chalk.hex(breatheColor);
|
|
157498
159199
|
const dim = chalk.hex(this.colors.textDim);
|
|
157499
159200
|
const muted = chalk.hex(this.colors.textMuted);
|
|
@@ -157509,7 +159210,7 @@ var WelcomeComponent = class {
|
|
|
157509
159210
|
let versionValue;
|
|
157510
159211
|
if (this.state.hasNewVersion && this.state.latestVersion !== null) versionValue = chalk.hex(this.colors.warning)(this.state.version) + " " + dim("(" + this.state.latestVersion + ")");
|
|
157511
159212
|
else versionValue = this.state.version;
|
|
157512
|
-
const frame = LOGO_FRAMES[this.breatheTimer !== null ? Math.floor(
|
|
159213
|
+
const frame = LOGO_FRAMES[this.breatheTimer !== null ? Math.floor(breatheFrame / 24) % LOGO_FRAMES.length : 0];
|
|
157513
159214
|
const logo = [boxColor(frame[0]), boxColor(frame[1])];
|
|
157514
159215
|
const tipLines = [];
|
|
157515
159216
|
for (const tip of WELCOME_TIPS) tipLines.push(` ${dim("•")} ${muted(tip)}`);
|
|
@@ -160608,7 +162309,7 @@ function getTranscriptComponentEntry(component) {
|
|
|
160608
162309
|
//#endregion
|
|
160609
162310
|
//#region src/tui/commands/revoke.ts
|
|
160610
162311
|
async function handleRevokeCommand(host, args = "") {
|
|
160611
|
-
if (host.state.appState
|
|
162312
|
+
if (isBusy(host.state.appState)) {
|
|
160612
162313
|
host.showError("无法在 streaming 中撤回 — 请先按 Esc 或 Ctrl-C 取消。");
|
|
160613
162314
|
return;
|
|
160614
162315
|
}
|
|
@@ -161510,7 +163211,7 @@ async function runInstallStep(cmd, args, cwd, label, timeoutMs = INSTALL_TIMEOUT
|
|
|
161510
163211
|
return promise;
|
|
161511
163212
|
}
|
|
161512
163213
|
async function handleUpdateCommand(host) {
|
|
161513
|
-
if (host.state.appState
|
|
163214
|
+
if (isBusy(host.state.appState)) {
|
|
161514
163215
|
host.showError("请在空闲时执行更新。");
|
|
161515
163216
|
return;
|
|
161516
163217
|
}
|
|
@@ -162204,7 +163905,7 @@ async function handleMakeSkillCommand(host, args) {
|
|
|
162204
163905
|
host.showError(NO_ACTIVE_SESSION_MESSAGE);
|
|
162205
163906
|
return;
|
|
162206
163907
|
}
|
|
162207
|
-
if (host.state.appState
|
|
163908
|
+
if (isBusy(host.state.appState)) {
|
|
162208
163909
|
host.showError("请等待当前回复完成后再使用 /make-skill");
|
|
162209
163910
|
return;
|
|
162210
163911
|
}
|
|
@@ -163732,6 +165433,10 @@ async function handleLoopCommand(host, args) {
|
|
|
163732
165433
|
host.showError(parsed);
|
|
163733
165434
|
return;
|
|
163734
165435
|
}
|
|
165436
|
+
if (detectGoalLoopConflict(host.state.appState, "enable_loop") === "goal_active") {
|
|
165437
|
+
host.showNotice("Storm Breaker(风暴守护者)", "当前已有激活的目标(/goal)。/loop 与 /goal 语义冲突:loop 每轮重置上下文,会破坏 goal 的工作笔记迭代。请先 /goal off 关闭目标,再开启循环模式。");
|
|
165438
|
+
return;
|
|
165439
|
+
}
|
|
163735
165440
|
const loopLimit = createLoopLimitRuntime(parsed.limit);
|
|
163736
165441
|
host.setAppState({
|
|
163737
165442
|
loopModeEnabled: true,
|
|
@@ -163739,7 +165444,8 @@ async function handleLoopCommand(host, args) {
|
|
|
163739
165444
|
loopLimit,
|
|
163740
165445
|
loopVerifier: parsed.verifier ? makeVerifier(parsed.verifier.command) : void 0,
|
|
163741
165446
|
loopIteration: 0,
|
|
163742
|
-
loopLastVerifyPassed: void 0
|
|
165447
|
+
loopLastVerifyPassed: void 0,
|
|
165448
|
+
loopVerifying: false
|
|
163743
165449
|
});
|
|
163744
165450
|
await ensureAutoPermission(host);
|
|
163745
165451
|
const limitSuffix = parsed.limit ? ` 限制:${describeLoopLimit(parsed.limit)}。` : "";
|
|
@@ -163764,7 +165470,8 @@ function disableLoopMode(host, message) {
|
|
|
163764
165470
|
loopLimit: void 0,
|
|
163765
165471
|
loopVerifier: void 0,
|
|
163766
165472
|
loopIteration: 0,
|
|
163767
|
-
loopLastVerifyPassed: void 0
|
|
165473
|
+
loopLastVerifyPassed: void 0,
|
|
165474
|
+
loopVerifying: false
|
|
163768
165475
|
});
|
|
163769
165476
|
if (message) host.showStatus(message);
|
|
163770
165477
|
}
|
|
@@ -165074,7 +166781,7 @@ var EditorKeyboardController = class {
|
|
|
165074
166781
|
this.cancelCurrentCompaction();
|
|
165075
166782
|
return;
|
|
165076
166783
|
}
|
|
165077
|
-
if (host.state.appState
|
|
166784
|
+
if (isStreaming(host.state.appState)) {
|
|
165078
166785
|
this.clearPendingExit();
|
|
165079
166786
|
this.cancelCurrentStream();
|
|
165080
166787
|
return;
|
|
@@ -165105,7 +166812,7 @@ var EditorKeyboardController = class {
|
|
|
165105
166812
|
this.cancelCurrentCompaction();
|
|
165106
166813
|
return;
|
|
165107
166814
|
}
|
|
165108
|
-
if (host.state.appState
|
|
166815
|
+
if (isStreaming(host.state.appState)) {
|
|
165109
166816
|
this.cancelCurrentStream();
|
|
165110
166817
|
return;
|
|
165111
166818
|
}
|
|
@@ -165131,7 +166838,7 @@ var EditorKeyboardController = class {
|
|
|
165131
166838
|
};
|
|
165132
166839
|
editor.onTogglePlanExpand = () => host.togglePlanExpansion();
|
|
165133
166840
|
editor.onCtrlS = () => {
|
|
165134
|
-
if (host.state.appState
|
|
166841
|
+
if (!isBusy(host.state.appState)) return;
|
|
165135
166842
|
const text = editor.getText().trim();
|
|
165136
166843
|
const queuedTexts = host.state.queuedMessages.map((m) => m.text);
|
|
165137
166844
|
host.clearQueuedMessages();
|
|
@@ -165154,7 +166861,7 @@ var EditorKeyboardController = class {
|
|
|
165154
166861
|
host.cancelPendingMemoryExtraction();
|
|
165155
166862
|
};
|
|
165156
166863
|
editor.onUpArrowEmpty = () => {
|
|
165157
|
-
if (
|
|
166864
|
+
if (!isBusy(host.state.appState)) return false;
|
|
165158
166865
|
const recalled = host.recallLastQueued();
|
|
165159
166866
|
if (recalled !== void 0) {
|
|
165160
166867
|
editor.setText(recalled);
|
|
@@ -165564,7 +167271,41 @@ function nextTranscriptId() {
|
|
|
165564
167271
|
return `entry-${String(transcriptIdCounter)}`;
|
|
165565
167272
|
}
|
|
165566
167273
|
//#endregion
|
|
167274
|
+
//#region src/tui/streaming-phase.ts
|
|
167275
|
+
function canTransitionTo(from, to) {
|
|
167276
|
+
return from !== to;
|
|
167277
|
+
}
|
|
167278
|
+
//#endregion
|
|
167279
|
+
//#region src/tui/utils/compaction-anomaly.ts
|
|
167280
|
+
const RAPID_REFIRE_MS = 3e4;
|
|
167281
|
+
const FIRST_STEP_BLOWUP_RATIO = .7;
|
|
167282
|
+
function detectCompactionAnomaly(input) {
|
|
167283
|
+
if (input.lastFinishedAt !== void 0) {
|
|
167284
|
+
const elapsed = input.now - input.lastFinishedAt;
|
|
167285
|
+
if (elapsed >= 0 && elapsed < RAPID_REFIRE_MS) return {
|
|
167286
|
+
kind: "rapid_refire",
|
|
167287
|
+
detail: `上次压缩结束仅 ${(elapsed / 1e3).toFixed(1)} 秒后再次触发自动压缩。`
|
|
167288
|
+
};
|
|
167289
|
+
}
|
|
167290
|
+
if (input.autoCompactionCount === 0 && input.maxContextTokens > 0) {
|
|
167291
|
+
const ratio = input.currentTokens / input.maxContextTokens;
|
|
167292
|
+
if (ratio >= FIRST_STEP_BLOWUP_RATIO) return {
|
|
167293
|
+
kind: "first_step_blowup",
|
|
167294
|
+
detail: `会话首次自动压缩时上下文已达 ${(ratio * 100).toFixed(0)}%,可能存在巨型文件读取或初始 prompt 过大。`
|
|
167295
|
+
};
|
|
167296
|
+
}
|
|
167297
|
+
return null;
|
|
167298
|
+
}
|
|
167299
|
+
//#endregion
|
|
165567
167300
|
//#region src/tui/controllers/session-event-handler.ts
|
|
167301
|
+
function addTokenUsage(a, b) {
|
|
167302
|
+
return {
|
|
167303
|
+
inputOther: a.inputOther + b.inputOther,
|
|
167304
|
+
inputCacheRead: a.inputCacheRead + b.inputCacheRead,
|
|
167305
|
+
inputCacheCreation: a.inputCacheCreation + b.inputCacheCreation,
|
|
167306
|
+
output: a.output + b.output
|
|
167307
|
+
};
|
|
167308
|
+
}
|
|
165568
167309
|
var SessionEventHandler = class {
|
|
165569
167310
|
host;
|
|
165570
167311
|
constructor(host) {
|
|
@@ -165577,6 +167318,7 @@ var SessionEventHandler = class {
|
|
|
165577
167318
|
renderedSkillActivationIds = /* @__PURE__ */ new Set();
|
|
165578
167319
|
renderedMcpServerStatusKeys = /* @__PURE__ */ new Map();
|
|
165579
167320
|
mcpServerStatusSpinners = /* @__PURE__ */ new Map();
|
|
167321
|
+
lastCompactionTrigger;
|
|
165580
167322
|
resetRuntimeState() {
|
|
165581
167323
|
this.backgroundAgentMetadata.clear();
|
|
165582
167324
|
this.backgroundTasks.clear();
|
|
@@ -165585,6 +167327,7 @@ var SessionEventHandler = class {
|
|
|
165585
167327
|
this.renderedSkillActivationIds.clear();
|
|
165586
167328
|
this.renderedMcpServerStatusKeys.clear();
|
|
165587
167329
|
this.stopAllMcpServerStatusSpinners();
|
|
167330
|
+
this.host.setAppState({ subagentUsage: {} });
|
|
165588
167331
|
}
|
|
165589
167332
|
startSubscription() {
|
|
165590
167333
|
const { host } = this;
|
|
@@ -165837,10 +167580,7 @@ var SessionEventHandler = class {
|
|
|
165837
167580
|
pendingApproval: null,
|
|
165838
167581
|
pendingQuestion: null
|
|
165839
167582
|
});
|
|
165840
|
-
this.host.setAppState({
|
|
165841
|
-
streamingPhase: "waiting",
|
|
165842
|
-
streamingStartTime: Date.now()
|
|
165843
|
-
});
|
|
167583
|
+
this.host.setAppState({ streamingPhase: "waiting" });
|
|
165844
167584
|
}
|
|
165845
167585
|
handleTurnEnd(event, sendQueued) {
|
|
165846
167586
|
this.host.streamingUI.flushNow();
|
|
@@ -165869,7 +167609,8 @@ var SessionEventHandler = class {
|
|
|
165869
167609
|
loopLimit: void 0,
|
|
165870
167610
|
loopVerifier: void 0,
|
|
165871
167611
|
loopIteration: 0,
|
|
165872
|
-
loopLastVerifyPassed: void 0
|
|
167612
|
+
loopLastVerifyPassed: void 0,
|
|
167613
|
+
loopVerifying: false
|
|
165873
167614
|
});
|
|
165874
167615
|
this.host.showStatus(message);
|
|
165875
167616
|
}
|
|
@@ -165880,14 +167621,22 @@ var SessionEventHandler = class {
|
|
|
165880
167621
|
this.host.setAppState({ loopIteration: currentIteration });
|
|
165881
167622
|
const verifier = state.loopVerifier;
|
|
165882
167623
|
if (verifier) {
|
|
167624
|
+
this.host.setAppState({ loopVerifying: true });
|
|
165883
167625
|
const result = await runShellVerifier(verifier, state.workDir);
|
|
165884
167626
|
const after = this.host.state.appState;
|
|
165885
|
-
if (!after.loopModeEnabled || after.loopPrompt !== loopPrompt)
|
|
167627
|
+
if (!after.loopModeEnabled || after.loopPrompt !== loopPrompt) {
|
|
167628
|
+
this.host.setAppState({ loopVerifying: false });
|
|
167629
|
+
return;
|
|
167630
|
+
}
|
|
165886
167631
|
if (result.passed) {
|
|
167632
|
+
this.host.setAppState({ loopVerifying: false });
|
|
165887
167633
|
this.disableLoop(`✓ 验证通过,循环结束(${currentIteration} 次迭代)。`);
|
|
165888
167634
|
return;
|
|
165889
167635
|
}
|
|
165890
|
-
this.host.setAppState({
|
|
167636
|
+
this.host.setAppState({
|
|
167637
|
+
loopVerifying: false,
|
|
167638
|
+
loopLastVerifyPassed: false
|
|
167639
|
+
});
|
|
165891
167640
|
}
|
|
165892
167641
|
if (!consumeLoopLimitIteration(this.host.state.appState.loopLimit)) {
|
|
165893
167642
|
const reason = this.host.state.appState.loopLimit?.kind === "duration" ? "时间" : "次数";
|
|
@@ -165907,10 +167656,7 @@ var SessionEventHandler = class {
|
|
|
165907
167656
|
pendingApproval: null,
|
|
165908
167657
|
pendingQuestion: null
|
|
165909
167658
|
});
|
|
165910
|
-
this.host.setAppState({
|
|
165911
|
-
streamingPhase: "waiting",
|
|
165912
|
-
streamingStartTime: Date.now()
|
|
165913
|
-
});
|
|
167659
|
+
this.host.setAppState({ streamingPhase: "waiting" });
|
|
165914
167660
|
}
|
|
165915
167661
|
handleStepCompleted(event) {
|
|
165916
167662
|
this.host.streamingUI.flushNow();
|
|
@@ -165950,11 +167696,7 @@ var SessionEventHandler = class {
|
|
|
165950
167696
|
handleThinkingDelta(event) {
|
|
165951
167697
|
const { state, streamingUI } = this.host;
|
|
165952
167698
|
streamingUI.appendThinkingDelta(event.delta);
|
|
165953
|
-
this.host.
|
|
165954
|
-
if (state.appState.streamingPhase !== "thinking") this.host.setAppState({
|
|
165955
|
-
streamingPhase: "thinking",
|
|
165956
|
-
streamingStartTime: Date.now()
|
|
165957
|
-
});
|
|
167699
|
+
if (canTransitionTo(state.appState.streamingPhase, "thinking")) this.host.setAppState({ streamingPhase: "thinking" });
|
|
165958
167700
|
streamingUI.scheduleFlush();
|
|
165959
167701
|
}
|
|
165960
167702
|
handleAssistantDelta(event) {
|
|
@@ -165962,14 +167704,10 @@ var SessionEventHandler = class {
|
|
|
165962
167704
|
if (streamingUI.hasThinkingDraft()) streamingUI.flushThinkingToTranscript("idle");
|
|
165963
167705
|
streamingUI.appendAssistantDelta(event.delta);
|
|
165964
167706
|
this.host.patchLivePane({
|
|
165965
|
-
mode: "idle",
|
|
165966
167707
|
pendingApproval: null,
|
|
165967
167708
|
pendingQuestion: null
|
|
165968
167709
|
});
|
|
165969
|
-
if (state.appState.streamingPhase
|
|
165970
|
-
streamingPhase: "composing",
|
|
165971
|
-
streamingStartTime: Date.now()
|
|
165972
|
-
});
|
|
167710
|
+
if (canTransitionTo(state.appState.streamingPhase, "composing")) this.host.setAppState({ streamingPhase: "composing" });
|
|
165973
167711
|
streamingUI.scheduleFlush();
|
|
165974
167712
|
}
|
|
165975
167713
|
handleHookResult(event) {
|
|
@@ -166004,24 +167742,20 @@ var SessionEventHandler = class {
|
|
|
166004
167742
|
};
|
|
166005
167743
|
streamingUI.registerToolCall(toolCall);
|
|
166006
167744
|
this.host.patchLivePane({
|
|
166007
|
-
mode: "tool",
|
|
166008
167745
|
pendingApproval: null,
|
|
166009
167746
|
pendingQuestion: null
|
|
166010
167747
|
});
|
|
167748
|
+
if (canTransitionTo(this.host.state.appState.streamingPhase, "tool")) this.host.setAppState({ streamingPhase: "tool" });
|
|
166011
167749
|
}
|
|
166012
167750
|
handleToolCallDelta(event) {
|
|
166013
167751
|
if (event.toolCallId.length === 0) return;
|
|
166014
167752
|
const { state, streamingUI } = this.host;
|
|
166015
167753
|
streamingUI.accumulateToolCallDelta(event.toolCallId, event.name, event.argumentsPart);
|
|
166016
167754
|
this.host.patchLivePane({
|
|
166017
|
-
mode: "tool",
|
|
166018
167755
|
pendingApproval: null,
|
|
166019
167756
|
pendingQuestion: null
|
|
166020
167757
|
});
|
|
166021
|
-
if (state.appState.streamingPhase
|
|
166022
|
-
streamingPhase: "composing",
|
|
166023
|
-
streamingStartTime: Date.now()
|
|
166024
|
-
});
|
|
167758
|
+
if (canTransitionTo(state.appState.streamingPhase, "tool")) this.host.setAppState({ streamingPhase: "tool" });
|
|
166025
167759
|
streamingUI.scheduleFlush();
|
|
166026
167760
|
}
|
|
166027
167761
|
handleToolProgress(event) {
|
|
@@ -166053,7 +167787,7 @@ var SessionEventHandler = class {
|
|
|
166053
167787
|
streamingUI.setTodoList(sanitized);
|
|
166054
167788
|
}
|
|
166055
167789
|
}
|
|
166056
|
-
this.host.
|
|
167790
|
+
if (canTransitionTo(this.host.state.appState.streamingPhase, "waiting")) this.host.setAppState({ streamingPhase: "waiting" });
|
|
166057
167791
|
}
|
|
166058
167792
|
handleStatusUpdate(event) {
|
|
166059
167793
|
const patch = {};
|
|
@@ -166191,21 +167925,37 @@ var SessionEventHandler = class {
|
|
|
166191
167925
|
}
|
|
166192
167926
|
handleCompactionBegin(event) {
|
|
166193
167927
|
this.host.streamingUI.finalizeLiveTextBuffers("waiting");
|
|
167928
|
+
this.lastCompactionTrigger = event.trigger;
|
|
167929
|
+
if (event.trigger === "auto") {
|
|
167930
|
+
const anomaly = detectCompactionAnomaly({
|
|
167931
|
+
lastFinishedAt: this.host.state.appState.lastCompactionFinishedAt,
|
|
167932
|
+
autoCompactionCount: this.host.state.appState.autoCompactionCount,
|
|
167933
|
+
currentTokens: this.host.state.appState.contextTokens,
|
|
167934
|
+
maxContextTokens: this.host.state.appState.maxContextTokens,
|
|
167935
|
+
now: Date.now()
|
|
167936
|
+
});
|
|
167937
|
+
if (anomaly !== null) this.host.showNotice("Storm Breaker(风暴守护者)", `检测到异常压缩节奏:${anomaly.detail}可能存在工具调用循环或超长输出,建议查看最近几步的对话记录。`);
|
|
167938
|
+
}
|
|
166194
167939
|
this.host.setAppState({
|
|
166195
167940
|
isCompacting: true,
|
|
166196
|
-
streamingPhase: "waiting"
|
|
166197
|
-
streamingStartTime: Date.now()
|
|
167941
|
+
streamingPhase: "waiting"
|
|
166198
167942
|
});
|
|
166199
167943
|
this.host.streamingUI.beginCompaction(event.instruction);
|
|
166200
167944
|
}
|
|
166201
167945
|
handleCompactionEnd(event, sendQueued) {
|
|
166202
167946
|
this.host.streamingUI.endCompaction(event.result.tokensBefore, event.result.tokensAfter);
|
|
166203
167947
|
this.host.markMemoryExtracted();
|
|
167948
|
+
if (this.lastCompactionTrigger === "auto") this.host.setAppState({
|
|
167949
|
+
lastCompactionFinishedAt: Date.now(),
|
|
167950
|
+
autoCompactionCount: this.host.state.appState.autoCompactionCount + 1
|
|
167951
|
+
});
|
|
167952
|
+
this.lastCompactionTrigger = void 0;
|
|
166204
167953
|
this.finishCompaction(sendQueued);
|
|
166205
167954
|
}
|
|
166206
167955
|
handleCompactionCancel(event, sendQueued) {
|
|
166207
167956
|
if (event.reason) this.host.showStatus(event.reason, this.host.state.theme.colors.warning);
|
|
166208
167957
|
this.host.streamingUI.cancelCompaction();
|
|
167958
|
+
this.lastCompactionTrigger = void 0;
|
|
166209
167959
|
this.finishCompaction(sendQueued);
|
|
166210
167960
|
}
|
|
166211
167961
|
finishCompaction(sendQueued) {
|
|
@@ -166261,6 +168011,7 @@ var SessionEventHandler = class {
|
|
|
166261
168011
|
});
|
|
166262
168012
|
}
|
|
166263
168013
|
handleSubagentCompleted(event) {
|
|
168014
|
+
this.recordSubagentUsage(event.subagentId, void 0, event.usage);
|
|
166264
168015
|
const { streamingUI } = this.host;
|
|
166265
168016
|
const backgroundMeta = this.backgroundAgentMetadata.get(event.subagentId);
|
|
166266
168017
|
if (backgroundMeta !== void 0) {
|
|
@@ -166283,6 +168034,7 @@ var SessionEventHandler = class {
|
|
|
166283
168034
|
streamingUI.removeToolComponentIfInactive(event.parentToolCallId);
|
|
166284
168035
|
}
|
|
166285
168036
|
handleSubagentFailed(event) {
|
|
168037
|
+
this.recordSubagentUsage(event.subagentId, void 0, event.usage);
|
|
166286
168038
|
const { streamingUI } = this.host;
|
|
166287
168039
|
const backgroundMeta = this.backgroundAgentMetadata.get(event.subagentId);
|
|
166288
168040
|
if (backgroundMeta !== void 0) {
|
|
@@ -166305,6 +168057,16 @@ var SessionEventHandler = class {
|
|
|
166305
168057
|
tc.onSubagentFailed({ error: event.error });
|
|
166306
168058
|
streamingUI.removeToolComponentIfInactive(event.parentToolCallId);
|
|
166307
168059
|
}
|
|
168060
|
+
recordSubagentUsage(subagentId, subagentName, usage) {
|
|
168061
|
+
if (usage === void 0) return;
|
|
168062
|
+
const name = this.subagentInfo.get(subagentId)?.name ?? subagentName ?? subagentId;
|
|
168063
|
+
const current = this.host.state.appState.subagentUsage[name];
|
|
168064
|
+
const next = {
|
|
168065
|
+
...this.host.state.appState.subagentUsage,
|
|
168066
|
+
[name]: current === void 0 ? usage : addTokenUsage(current, usage)
|
|
168067
|
+
};
|
|
168068
|
+
this.host.setAppState({ subagentUsage: next });
|
|
168069
|
+
}
|
|
166308
168070
|
createStandaloneSubagentToolCall(event) {
|
|
166309
168071
|
const { streamingUI } = this.host;
|
|
166310
168072
|
const description = event.description ?? `Run ${event.subagentName} agent`;
|
|
@@ -169349,6 +171111,7 @@ var TranscriptController = class TranscriptController {
|
|
|
169349
171111
|
state.errorBanner.clear();
|
|
169350
171112
|
imageStore.clear();
|
|
169351
171113
|
this.renderWelcome();
|
|
171114
|
+
state.transcriptViewport.scrollToBottom();
|
|
169352
171115
|
}
|
|
169353
171116
|
showStatus(message, color) {
|
|
169354
171117
|
this.host.state.transcriptContainer.addChild(new StatusMessageComponent(message, this.host.state.theme.colors, color));
|
|
@@ -169416,34 +171179,6 @@ var TranscriptController = class TranscriptController {
|
|
|
169416
171179
|
}
|
|
169417
171180
|
};
|
|
169418
171181
|
//#endregion
|
|
169419
|
-
//#region src/tui/components/chrome/gutter-container.ts
|
|
169420
|
-
/**
|
|
169421
|
-
* Container that reserves left/right gutter columns around its children,
|
|
169422
|
-
* so the chrome (statusline, transcript, panels) lines up with the input
|
|
169423
|
-
* box's inner content area instead of butting up against the terminal edge.
|
|
169424
|
-
*
|
|
169425
|
-
* Children are rendered at `width - left - right` and each emitted line is
|
|
169426
|
-
* prefixed with `left` plain spaces. Right padding is logical only — we
|
|
169427
|
-
* never emit trailing spaces, since terminals already paint background to
|
|
169428
|
-
* the edge and adding them would just churn the diff renderer.
|
|
169429
|
-
*/
|
|
169430
|
-
var GutterContainer = class extends Container {
|
|
169431
|
-
leftPad;
|
|
169432
|
-
rightPad;
|
|
169433
|
-
constructor(leftPad, rightPad) {
|
|
169434
|
-
super();
|
|
169435
|
-
this.leftPad = leftPad;
|
|
169436
|
-
this.rightPad = rightPad;
|
|
169437
|
-
}
|
|
169438
|
-
render(width) {
|
|
169439
|
-
const inner = Math.max(1, width - this.leftPad - this.rightPad);
|
|
169440
|
-
const lead = " ".repeat(this.leftPad);
|
|
169441
|
-
const out = [];
|
|
169442
|
-
for (const child of this.children) for (const line of child.render(inner)) out.push(lead + line);
|
|
169443
|
-
return out;
|
|
169444
|
-
}
|
|
169445
|
-
};
|
|
169446
|
-
//#endregion
|
|
169447
171182
|
//#region src/tui/theme/bundle.ts
|
|
169448
171183
|
function createNexumTUIThemeBundle(theme, resolvedTheme) {
|
|
169449
171184
|
const actualTheme = resolvedTheme ?? resolveThemeSync(theme);
|
|
@@ -169668,6 +171403,41 @@ function installTerminalThemeTracking(state, onTheme) {
|
|
|
169668
171403
|
};
|
|
169669
171404
|
}
|
|
169670
171405
|
//#endregion
|
|
171406
|
+
//#region src/tui/utils/transcript-scroll-input.ts
|
|
171407
|
+
const SGR_MOUSE_RE = /^\u001B\[<(\d+);(\d+);(\d+)([mM])$/;
|
|
171408
|
+
const WHEEL_STEP_ROWS = 3;
|
|
171409
|
+
const WHEEL_UP = 64;
|
|
171410
|
+
const WHEEL_DOWN = 65;
|
|
171411
|
+
function parseSgrMouseWheel(data) {
|
|
171412
|
+
const match = SGR_MOUSE_RE.exec(data);
|
|
171413
|
+
if (match === null) return void 0;
|
|
171414
|
+
const baseButton = Number(match[1]) & -29;
|
|
171415
|
+
if (baseButton === WHEEL_UP) return -3;
|
|
171416
|
+
if (baseButton === WHEEL_DOWN) return WHEEL_STEP_ROWS;
|
|
171417
|
+
return 0;
|
|
171418
|
+
}
|
|
171419
|
+
function shouldLeaveInputToDialog(state) {
|
|
171420
|
+
return state.activeDialog !== null || state.ui.hasOverlay();
|
|
171421
|
+
}
|
|
171422
|
+
function installTranscriptScrollInput(state) {
|
|
171423
|
+
return state.ui.addInputListener((data) => {
|
|
171424
|
+
if (shouldLeaveInputToDialog(state)) return void 0;
|
|
171425
|
+
const wheelDelta = parseSgrMouseWheel(data);
|
|
171426
|
+
if (wheelDelta !== void 0) {
|
|
171427
|
+
if (wheelDelta !== 0 && state.transcriptViewport.scrollBy(wheelDelta)) state.ui.requestRender();
|
|
171428
|
+
return { consume: true };
|
|
171429
|
+
}
|
|
171430
|
+
if (matchesKey(data, Key.pageUp) || data === "") {
|
|
171431
|
+
if (state.transcriptViewport.pageBy(-1)) state.ui.requestRender();
|
|
171432
|
+
return { consume: true };
|
|
171433
|
+
}
|
|
171434
|
+
if (matchesKey(data, Key.pageDown) || data === "") {
|
|
171435
|
+
if (state.transcriptViewport.pageBy(1)) state.ui.requestRender();
|
|
171436
|
+
return { consume: true };
|
|
171437
|
+
}
|
|
171438
|
+
});
|
|
171439
|
+
}
|
|
171440
|
+
//#endregion
|
|
169671
171441
|
//#region src/tui/components/chrome/pulse-wave-loader.ts
|
|
169672
171442
|
const FULL_BOX = "■";
|
|
169673
171443
|
const DIM_DOT = "⬝";
|
|
@@ -169768,6 +171538,8 @@ var LifecycleController = class LifecycleController {
|
|
|
169768
171538
|
lastMemoryExtractionTime = 0;
|
|
169769
171539
|
terminalFocusTrackingDispose;
|
|
169770
171540
|
terminalThemeTrackingDispose;
|
|
171541
|
+
transcriptScrollInputDispose;
|
|
171542
|
+
terminalMouseReportingEnabled = false;
|
|
169771
171543
|
lastActivityMode;
|
|
169772
171544
|
static MEMORY_IDLE_MS = 900 * 1e3;
|
|
169773
171545
|
static MEMORY_COUNTDOWN_MS = 15 * 1e3;
|
|
@@ -169880,7 +171652,7 @@ var LifecycleController = class LifecycleController {
|
|
|
169880
171652
|
async performIdleMemoryExtraction() {
|
|
169881
171653
|
if (Date.now() - this.lastMemoryExtractionTime < LifecycleController.MEMORY_EXTRACT_COOLDOWN_MS) return;
|
|
169882
171654
|
const { state, session } = this.host;
|
|
169883
|
-
if (state.appState
|
|
171655
|
+
if (isStreaming(state.appState)) return;
|
|
169884
171656
|
if (state.appState.isCompacting) return;
|
|
169885
171657
|
if (state.appState.isReplaying) return;
|
|
169886
171658
|
if (session === void 0) return;
|
|
@@ -169903,23 +171675,25 @@ var LifecycleController = class LifecycleController {
|
|
|
169903
171675
|
}
|
|
169904
171676
|
startEventLoop() {
|
|
169905
171677
|
this.host.state.ui.start();
|
|
171678
|
+
this.transcriptScrollInputDispose = installTranscriptScrollInput(this.host.state);
|
|
171679
|
+
this.host.state.terminal.write(ENABLE_TERMINAL_MOUSE_REPORTING);
|
|
171680
|
+
this.terminalMouseReportingEnabled = true;
|
|
169906
171681
|
this.terminalFocusTrackingDispose = installTerminalFocusTracking(this.host.state);
|
|
169907
171682
|
this.refreshTerminalThemeTracking();
|
|
169908
171683
|
}
|
|
169909
171684
|
buildLayout() {
|
|
169910
171685
|
const { ui } = this.host.state;
|
|
169911
171686
|
ui.clear();
|
|
169912
|
-
ui.addChild(this.host.state.
|
|
171687
|
+
ui.addChild(this.host.state.transcriptViewport);
|
|
169913
171688
|
ui.addChild(this.host.state.activityContainer);
|
|
169914
171689
|
ui.addChild(this.host.state.todoPanelContainer);
|
|
169915
171690
|
ui.addChild(this.host.state.queueContainer);
|
|
169916
171691
|
ui.addChild(this.host.state.errorBannerContainer);
|
|
171692
|
+
ui.addChild(this.host.state.planModeBannerContainer);
|
|
169917
171693
|
ui.addChild(this.host.state.editorContainer);
|
|
169918
171694
|
}
|
|
169919
171695
|
mountFooter() {
|
|
169920
|
-
|
|
169921
|
-
footerWrap.addChild(this.host.state.footer);
|
|
169922
|
-
this.host.state.ui.addChild(footerWrap);
|
|
171696
|
+
this.host.state.ui.addChild(this.host.state.footerContainer);
|
|
169923
171697
|
}
|
|
169924
171698
|
refreshTerminalThemeTracking() {
|
|
169925
171699
|
this.stopTerminalThemeTracking();
|
|
@@ -169933,6 +171707,14 @@ var LifecycleController = class LifecycleController {
|
|
|
169933
171707
|
this.terminalThemeTrackingDispose = void 0;
|
|
169934
171708
|
}
|
|
169935
171709
|
disposeTerminalTracking() {
|
|
171710
|
+
this.transcriptScrollInputDispose?.();
|
|
171711
|
+
this.transcriptScrollInputDispose = void 0;
|
|
171712
|
+
if (this.terminalMouseReportingEnabled) {
|
|
171713
|
+
this.terminalMouseReportingEnabled = false;
|
|
171714
|
+
try {
|
|
171715
|
+
this.host.state.terminal.write(DISABLE_TERMINAL_MOUSE_REPORTING);
|
|
171716
|
+
} catch {}
|
|
171717
|
+
}
|
|
169936
171718
|
this.stopTerminalThemeTracking();
|
|
169937
171719
|
this.terminalFocusTrackingDispose?.();
|
|
169938
171720
|
this.terminalFocusTrackingDispose = void 0;
|
|
@@ -170007,9 +171789,7 @@ var LifecycleController = class LifecycleController {
|
|
|
170007
171789
|
if (state.appState.isCompacting) return "hidden";
|
|
170008
171790
|
if (state.livePane.pendingQuestion !== null) return "hidden";
|
|
170009
171791
|
const streamingPhase = state.appState.streamingPhase;
|
|
170010
|
-
if (
|
|
170011
|
-
if (streamingPhase === "thinking" || streamingPhase === "composing") return streamingPhase;
|
|
170012
|
-
}
|
|
171792
|
+
if (streamingPhase === "waiting" || streamingPhase === "thinking" || streamingPhase === "composing" || streamingPhase === "tool") return streamingPhase;
|
|
170013
171793
|
return state.livePane.mode;
|
|
170014
171794
|
}
|
|
170015
171795
|
shouldShowTerminalProgress(effectiveMode) {
|
|
@@ -170454,7 +172234,6 @@ const WORKER_ANGLES = [
|
|
|
170454
172234
|
}
|
|
170455
172235
|
];
|
|
170456
172236
|
const DEFAULT_WORKER_COUNT = 3;
|
|
170457
|
-
const DEFAULT_TIMEOUT_MS = 12e4;
|
|
170458
172237
|
const DEFAULT_MAX_OUTPUT_BYTES = 8e3;
|
|
170459
172238
|
const DEFAULT_SYNTHESIS_MAX_OUTPUT_BYTES = 12e3;
|
|
170460
172239
|
function buildPlannerPrompt(input) {
|
|
@@ -170578,7 +172357,7 @@ async function runWorker(input) {
|
|
|
170578
172357
|
model: input.model
|
|
170579
172358
|
});
|
|
170580
172359
|
const { command, prefixArgs } = resolveNexumCommand(input.NexumBin);
|
|
170581
|
-
const timeoutMs = input.timeoutMs
|
|
172360
|
+
const timeoutMs = input.timeoutMs;
|
|
170582
172361
|
result.command = [
|
|
170583
172362
|
command,
|
|
170584
172363
|
...prefixArgs,
|
|
@@ -170638,12 +172417,14 @@ async function runWorker(input) {
|
|
|
170638
172417
|
if (stdoutBuffer.trim()) processLine(stdoutBuffer);
|
|
170639
172418
|
safeResolve(code ?? 0);
|
|
170640
172419
|
});
|
|
170641
|
-
|
|
170642
|
-
|
|
170643
|
-
|
|
170644
|
-
|
|
170645
|
-
|
|
170646
|
-
|
|
172420
|
+
if (timeoutMs !== void 0) {
|
|
172421
|
+
timeout = setTimeout(() => {
|
|
172422
|
+
result.timedOut = true;
|
|
172423
|
+
proc.kill("SIGTERM");
|
|
172424
|
+
setTimeout(() => proc.kill("SIGKILL"), 5e3).unref();
|
|
172425
|
+
}, timeoutMs);
|
|
172426
|
+
timeout.unref();
|
|
172427
|
+
}
|
|
170647
172428
|
});
|
|
170648
172429
|
result.exitCode = exitCode;
|
|
170649
172430
|
result.ok = exitCode === 0 && !result.timedOut && result.output.trim().length > 0;
|
|
@@ -170691,7 +172472,7 @@ async function runFusionPlan(input) {
|
|
|
170691
172472
|
};
|
|
170692
172473
|
const workerCount = Math.max(1, Math.min(8, input.workerCount ?? DEFAULT_WORKER_COUNT));
|
|
170693
172474
|
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
|
170694
|
-
const timeoutMs = input.timeoutMs
|
|
172475
|
+
const timeoutMs = input.timeoutMs;
|
|
170695
172476
|
const promptDir = await createPromptDir();
|
|
170696
172477
|
const workerStates = [];
|
|
170697
172478
|
for (let i = 0; i < workerCount; i += 1) {
|
|
@@ -170770,8 +172551,6 @@ async function runFusionPlan(input) {
|
|
|
170770
172551
|
}
|
|
170771
172552
|
//#endregion
|
|
170772
172553
|
//#region src/tui/controllers/input-controller.ts
|
|
170773
|
-
const BREATHE_FRAMES = 120;
|
|
170774
|
-
const BREATHE_INTERVAL_MS = 40;
|
|
170775
172554
|
function hexToRgb$1(hex) {
|
|
170776
172555
|
const v = parseInt(hex.slice(1), 16);
|
|
170777
172556
|
return [
|
|
@@ -170833,7 +172612,6 @@ var InputController = class {
|
|
|
170833
172612
|
host;
|
|
170834
172613
|
lastHistoryContent;
|
|
170835
172614
|
breatheTimer = null;
|
|
170836
|
-
breatheFrame = 0;
|
|
170837
172615
|
isFusionPlanRunning = false;
|
|
170838
172616
|
fusionPlanEntry;
|
|
170839
172617
|
fusionPlanComponent;
|
|
@@ -170992,7 +172770,7 @@ var InputController = class {
|
|
|
170992
172770
|
for (const part of input) this.enqueueMessage(part);
|
|
170993
172771
|
return;
|
|
170994
172772
|
}
|
|
170995
|
-
if (this.host.state.appState
|
|
172773
|
+
if (!isStreaming(this.host.state.appState)) {
|
|
170996
172774
|
for (const part of input) this.sendMessageInternal(session, part);
|
|
170997
172775
|
return;
|
|
170998
172776
|
}
|
|
@@ -171043,15 +172821,13 @@ var InputController = class {
|
|
|
171043
172821
|
const primaryHex = this.host.state.theme.colors.primary;
|
|
171044
172822
|
const [r, g, b] = hexToRgb$1(primaryHex);
|
|
171045
172823
|
const [baseHue] = rgbToHsl(r, g, b);
|
|
171046
|
-
this.breatheFrame = 0;
|
|
171047
172824
|
const editor = this.host.state.editor;
|
|
171048
172825
|
const ui = this.host.state.ui;
|
|
171049
172826
|
this.breatheTimer = setInterval(() => {
|
|
171050
|
-
const hex = hslToHex((baseHue +
|
|
172827
|
+
const hex = hslToHex((baseHue + getBreathingFrame() / 120 * 360) % 360, 90, 70);
|
|
171051
172828
|
editor.borderColor = (s) => chalk.hex(hex)(s);
|
|
171052
172829
|
ui.requestRender();
|
|
171053
|
-
|
|
171054
|
-
}, BREATHE_INTERVAL_MS);
|
|
172830
|
+
}, 40);
|
|
171055
172831
|
}
|
|
171056
172832
|
#stopBreathing() {
|
|
171057
172833
|
if (!this.breatheTimer) return;
|
|
@@ -171066,7 +172842,7 @@ var InputController = class {
|
|
|
171066
172842
|
messages: queued,
|
|
171067
172843
|
colors: this.host.state.theme.colors,
|
|
171068
172844
|
isCompacting: this.host.state.appState.isCompacting,
|
|
171069
|
-
isStreaming: this.host.state.appState
|
|
172845
|
+
isStreaming: isStreaming(this.host.state.appState),
|
|
171070
172846
|
canSteerImmediately: !this.host.deferUserMessages
|
|
171071
172847
|
}));
|
|
171072
172848
|
}
|
|
@@ -171121,7 +172897,7 @@ var InputController = class {
|
|
|
171121
172897
|
});
|
|
171122
172898
|
}
|
|
171123
172899
|
sendMessage(session, input, options) {
|
|
171124
|
-
if (this.host.deferUserMessages || this.host.state.appState
|
|
172900
|
+
if (this.host.deferUserMessages || isBusy(this.host.state.appState)) {
|
|
171125
172901
|
this.enqueueMessage(input, options);
|
|
171126
172902
|
return;
|
|
171127
172903
|
}
|
|
@@ -171385,6 +173161,14 @@ var ErrorBannerComponent = class {
|
|
|
171385
173161
|
}
|
|
171386
173162
|
};
|
|
171387
173163
|
//#endregion
|
|
173164
|
+
//#region src/tui/loop-state.ts
|
|
173165
|
+
function resolveLoopSubstate(state) {
|
|
173166
|
+
if (!state.loopModeEnabled) return "idle";
|
|
173167
|
+
if (state.loopVerifying) return "verifying";
|
|
173168
|
+
if (state.loopPrompt === void 0) return "paused";
|
|
173169
|
+
return "running";
|
|
173170
|
+
}
|
|
173171
|
+
//#endregion
|
|
171388
173172
|
//#region src/tui/utils/shimmer.ts
|
|
171389
173173
|
const SHIMMER_SPEED_CELLS_PER_S = 30;
|
|
171390
173174
|
const PADDING = 10;
|
|
@@ -171940,7 +173724,7 @@ function lerpGradient(t) {
|
|
|
171940
173724
|
function buildStatusLine(streamingPhase, livePaneMode, streamingStartTime) {
|
|
171941
173725
|
if (streamingPhase === "idle" && livePaneMode !== "tool") return "○ 空闲";
|
|
171942
173726
|
let label;
|
|
171943
|
-
if (livePaneMode === "tool") label = "执行中";
|
|
173727
|
+
if (streamingPhase === "tool" || livePaneMode === "tool") label = "执行中";
|
|
171944
173728
|
else if (streamingPhase === "waiting") label = "等待响应";
|
|
171945
173729
|
else if (streamingPhase === "thinking") label = "思考中";
|
|
171946
173730
|
else if (streamingPhase === "composing") label = "输出中";
|
|
@@ -172075,6 +173859,7 @@ var FooterComponent = class {
|
|
|
172075
173859
|
const remainMs = Math.max(0, limit.deadlineMs - Date.now());
|
|
172076
173860
|
badge = remainMs >= 6e4 ? `loop ${Math.ceil(remainMs / 6e4)}m` : `loop ${Math.max(1, Math.ceil(remainMs / 1e3))}s`;
|
|
172077
173861
|
}
|
|
173862
|
+
if (resolveLoopSubstate(state) === "verifying") badge += " · 验证中";
|
|
172078
173863
|
if (state.loopLastVerifyPassed === false) badge += " · ✗";
|
|
172079
173864
|
left.push(chalk.hex(colors.primary).bold(badge));
|
|
172080
173865
|
}
|
|
@@ -172121,6 +173906,72 @@ var FooterComponent = class {
|
|
|
172121
173906
|
}
|
|
172122
173907
|
};
|
|
172123
173908
|
//#endregion
|
|
173909
|
+
//#region src/tui/components/chrome/gutter-container.ts
|
|
173910
|
+
/**
|
|
173911
|
+
* Container that reserves left/right gutter columns around its children,
|
|
173912
|
+
* so the chrome (statusline, transcript, panels) lines up with the input
|
|
173913
|
+
* box's inner content area instead of butting up against the terminal edge.
|
|
173914
|
+
*
|
|
173915
|
+
* Children are rendered at `width - left - right` and each emitted line is
|
|
173916
|
+
* prefixed with `left` plain spaces. Right padding is logical only — we
|
|
173917
|
+
* never emit trailing spaces, since terminals already paint background to
|
|
173918
|
+
* the edge and adding them would just churn the diff renderer.
|
|
173919
|
+
*/
|
|
173920
|
+
var GutterContainer = class extends Container {
|
|
173921
|
+
leftPad;
|
|
173922
|
+
rightPad;
|
|
173923
|
+
constructor(leftPad, rightPad) {
|
|
173924
|
+
super();
|
|
173925
|
+
this.leftPad = leftPad;
|
|
173926
|
+
this.rightPad = rightPad;
|
|
173927
|
+
}
|
|
173928
|
+
render(width) {
|
|
173929
|
+
const inner = Math.max(1, width - this.leftPad - this.rightPad);
|
|
173930
|
+
const lead = " ".repeat(this.leftPad);
|
|
173931
|
+
const out = [];
|
|
173932
|
+
for (const child of this.children) for (const line of child.render(inner)) out.push(lead + line);
|
|
173933
|
+
return out;
|
|
173934
|
+
}
|
|
173935
|
+
};
|
|
173936
|
+
//#endregion
|
|
173937
|
+
//#region src/tui/components/chrome/plan-mode-banner.ts
|
|
173938
|
+
const PLAN_LABEL = {
|
|
173939
|
+
plan: "计划模式",
|
|
173940
|
+
fusionplan: "融合计划模式"
|
|
173941
|
+
};
|
|
173942
|
+
var PlanModeBannerComponent = class {
|
|
173943
|
+
colors;
|
|
173944
|
+
mode = "off";
|
|
173945
|
+
planPath;
|
|
173946
|
+
constructor(colors) {
|
|
173947
|
+
this.colors = colors;
|
|
173948
|
+
}
|
|
173949
|
+
setPlanMode(mode, planPath) {
|
|
173950
|
+
this.mode = mode;
|
|
173951
|
+
this.planPath = planPath;
|
|
173952
|
+
}
|
|
173953
|
+
setMode(mode) {
|
|
173954
|
+
this.mode = mode;
|
|
173955
|
+
}
|
|
173956
|
+
invalidate() {}
|
|
173957
|
+
render(width) {
|
|
173958
|
+
if (this.mode === "off") return [];
|
|
173959
|
+
const tone = this.mode === "fusionplan" ? this.colors.fusionPlanMode : this.colors.planMode;
|
|
173960
|
+
const label = PLAN_LABEL[this.mode];
|
|
173961
|
+
const prefix = `${chalk.hex(tone)(STATUS_BULLET)}${chalk.hex(tone).bold(label)}`;
|
|
173962
|
+
const basename = this.planPath !== void 0 && this.planPath.length > 0 ? path$9.basename(this.planPath) : void 0;
|
|
173963
|
+
if (basename === void 0 || basename.length === 0) return [truncateToWidth(prefix, width)];
|
|
173964
|
+
const sep = chalk.hex(this.colors.textDim)(" · ");
|
|
173965
|
+
const line = `${prefix}${sep}${path$9.isAbsolute(this.planPath) ? toTerminalHyperlink$1(chalk.hex(this.colors.text)(basename), pathToFileURL(this.planPath).href) : chalk.hex(this.colors.text)(basename)}`;
|
|
173966
|
+
if (visibleWidth(line) <= width) return [line];
|
|
173967
|
+
const fixedWidth = visibleWidth(prefix) + visibleWidth(sep);
|
|
173968
|
+
const budget = Math.max(0, width - fixedWidth);
|
|
173969
|
+
if (budget < 4) return [truncateToWidth(prefix, width)];
|
|
173970
|
+
const truncated = truncateToWidth(basename, budget, "…");
|
|
173971
|
+
return [`${prefix}${sep}${chalk.hex(this.colors.text)(truncated)}`];
|
|
173972
|
+
}
|
|
173973
|
+
};
|
|
173974
|
+
//#endregion
|
|
172124
173975
|
//#region src/tui/components/chrome/todo-panel.ts
|
|
172125
173976
|
const MAX_VISIBLE = 5;
|
|
172126
173977
|
/**
|
|
@@ -172542,6 +174393,60 @@ function injectThinkLabel(lines, width, thinkingLevel, paint) {
|
|
|
172542
174393
|
lines[topIdx] = paint("─".repeat(leftDashCount) + labelBlock + "─");
|
|
172543
174394
|
}
|
|
172544
174395
|
//#endregion
|
|
174396
|
+
//#region src/tui/components/transcript/transcript-viewport.ts
|
|
174397
|
+
function clamp(value, min, max) {
|
|
174398
|
+
return Math.max(min, Math.min(value, max));
|
|
174399
|
+
}
|
|
174400
|
+
var TranscriptViewportComponent = class {
|
|
174401
|
+
content;
|
|
174402
|
+
getViewportRows;
|
|
174403
|
+
scrollTop = 0;
|
|
174404
|
+
pinnedToBottom = true;
|
|
174405
|
+
lastMaxScroll = 0;
|
|
174406
|
+
lastViewportRows = 1;
|
|
174407
|
+
constructor(content, getViewportRows) {
|
|
174408
|
+
this.content = content;
|
|
174409
|
+
this.getViewportRows = getViewportRows;
|
|
174410
|
+
}
|
|
174411
|
+
invalidate() {
|
|
174412
|
+
this.content.invalidate();
|
|
174413
|
+
}
|
|
174414
|
+
scrollBy(delta) {
|
|
174415
|
+
const maxScroll = this.lastMaxScroll;
|
|
174416
|
+
if (maxScroll <= 0) return false;
|
|
174417
|
+
const current = this.pinnedToBottom ? maxScroll : this.scrollTop;
|
|
174418
|
+
const next = clamp(current + delta, 0, maxScroll);
|
|
174419
|
+
if (next === current && this.pinnedToBottom === next >= maxScroll) return false;
|
|
174420
|
+
this.scrollTop = next;
|
|
174421
|
+
this.pinnedToBottom = next >= maxScroll;
|
|
174422
|
+
return true;
|
|
174423
|
+
}
|
|
174424
|
+
pageBy(pages) {
|
|
174425
|
+
const rows = Math.max(1, this.lastViewportRows - 1);
|
|
174426
|
+
return this.scrollBy(pages * rows);
|
|
174427
|
+
}
|
|
174428
|
+
scrollToBottom() {
|
|
174429
|
+
const maxScroll = this.lastMaxScroll;
|
|
174430
|
+
const changed = !this.pinnedToBottom || this.scrollTop !== maxScroll;
|
|
174431
|
+
this.scrollTop = maxScroll;
|
|
174432
|
+
this.pinnedToBottom = true;
|
|
174433
|
+
return changed;
|
|
174434
|
+
}
|
|
174435
|
+
render(width) {
|
|
174436
|
+
const viewportRows = Math.max(1, this.getViewportRows(width));
|
|
174437
|
+
const lines = this.content.render(width);
|
|
174438
|
+
const maxScroll = Math.max(0, lines.length - viewportRows);
|
|
174439
|
+
this.lastViewportRows = viewportRows;
|
|
174440
|
+
this.lastMaxScroll = maxScroll;
|
|
174441
|
+
if (this.pinnedToBottom) this.scrollTop = maxScroll;
|
|
174442
|
+
else {
|
|
174443
|
+
this.scrollTop = clamp(this.scrollTop, 0, maxScroll);
|
|
174444
|
+
if (this.scrollTop >= maxScroll) this.pinnedToBottom = true;
|
|
174445
|
+
}
|
|
174446
|
+
return lines.slice(this.scrollTop, this.scrollTop + viewportRows);
|
|
174447
|
+
}
|
|
174448
|
+
};
|
|
174449
|
+
//#endregion
|
|
172545
174450
|
//#region src/tui/utils/terminal-state.ts
|
|
172546
174451
|
function createTerminalState() {
|
|
172547
174452
|
return {
|
|
@@ -172792,24 +174697,37 @@ function createTUIState(options) {
|
|
|
172792
174697
|
const errorBanner = new ErrorBannerComponent(theme.colors);
|
|
172793
174698
|
const errorBannerContainer = new GutterContainer(1, 1);
|
|
172794
174699
|
errorBannerContainer.addChild(errorBanner);
|
|
174700
|
+
const planModeBanner = new PlanModeBannerComponent(theme.colors);
|
|
174701
|
+
const planModeBannerContainer = new GutterContainer(1, 1);
|
|
174702
|
+
planModeBannerContainer.addChild(planModeBanner);
|
|
172795
174703
|
const editorContainer = new GutterContainer(1, 1);
|
|
172796
174704
|
const editor = new CustomEditor(ui, theme.colors);
|
|
172797
174705
|
editor.thinking = initialAppState.thinkingLevel !== "off";
|
|
172798
174706
|
editor.thinkingLevel = initialAppState.thinkingLevel;
|
|
174707
|
+
const footer = new FooterComponent({ ...initialAppState }, theme.colors, ui, () => {
|
|
174708
|
+
ui.requestRender();
|
|
174709
|
+
});
|
|
174710
|
+
const footerContainer = new GutterContainer(1, 1);
|
|
174711
|
+
footerContainer.addChild(footer);
|
|
172799
174712
|
return {
|
|
172800
174713
|
ui,
|
|
172801
174714
|
terminal,
|
|
172802
174715
|
transcriptContainer,
|
|
174716
|
+
transcriptViewport: new TranscriptViewportComponent(transcriptContainer, (width) => {
|
|
174717
|
+
const reservedRows = activityContainer.render(width).length + todoPanelContainer.render(width).length + queueContainer.render(width).length + errorBannerContainer.render(width).length + planModeBannerContainer.render(width).length + editorContainer.render(width).length + footerContainer.render(width).length;
|
|
174718
|
+
return terminal.rows - reservedRows;
|
|
174719
|
+
}),
|
|
172803
174720
|
activityContainer,
|
|
172804
174721
|
todoPanelContainer,
|
|
172805
174722
|
todoPanel,
|
|
172806
174723
|
queueContainer,
|
|
172807
174724
|
errorBanner,
|
|
172808
174725
|
errorBannerContainer,
|
|
174726
|
+
planModeBanner,
|
|
174727
|
+
planModeBannerContainer,
|
|
172809
174728
|
editorContainer,
|
|
172810
|
-
footer
|
|
172811
|
-
|
|
172812
|
-
}),
|
|
174729
|
+
footer,
|
|
174730
|
+
footerContainer,
|
|
172813
174731
|
editor,
|
|
172814
174732
|
theme,
|
|
172815
174733
|
appState: { ...initialAppState },
|
|
@@ -173384,7 +175302,7 @@ var SessionManager = class {
|
|
|
173384
175302
|
this.host.showStatus("已在该会话中。");
|
|
173385
175303
|
return { switched: true };
|
|
173386
175304
|
}
|
|
173387
|
-
if (this.host.state.appState
|
|
175305
|
+
if (isBusy(this.host.state.appState)) {
|
|
173388
175306
|
this.host.showError("流式传输期间无法切换会话 — 请先按 Esc 或 Ctrl-C。");
|
|
173389
175307
|
return { switched: false };
|
|
173390
175308
|
}
|
|
@@ -175407,6 +177325,8 @@ function createInitialAppState(input) {
|
|
|
175407
177325
|
contextTokens: 0,
|
|
175408
177326
|
maxContextTokens: 0,
|
|
175409
177327
|
isCompacting: false,
|
|
177328
|
+
lastCompactionFinishedAt: void 0,
|
|
177329
|
+
autoCompactionCount: 0,
|
|
175410
177330
|
isReplaying: false,
|
|
175411
177331
|
streamingPhase: "idle",
|
|
175412
177332
|
streamingStartTime: 0,
|
|
@@ -175418,6 +177338,7 @@ function createInitialAppState(input) {
|
|
|
175418
177338
|
editorCommand: input.tuiConfig.editorCommand,
|
|
175419
177339
|
notifications: input.tuiConfig.notifications,
|
|
175420
177340
|
like: input.tuiConfig.like ?? {},
|
|
177341
|
+
subagentModels: input.tuiConfig.subagentModels ?? {},
|
|
175421
177342
|
availableModels: {},
|
|
175422
177343
|
availableProviders: {},
|
|
175423
177344
|
sessionTitle: null,
|
|
@@ -175432,7 +177353,9 @@ function createInitialAppState(input) {
|
|
|
175432
177353
|
loopVerifier: void 0,
|
|
175433
177354
|
loopIteration: 0,
|
|
175434
177355
|
loopLastVerifyPassed: void 0,
|
|
175435
|
-
|
|
177356
|
+
loopVerifying: false,
|
|
177357
|
+
recentSessions: [],
|
|
177358
|
+
subagentUsage: {}
|
|
175436
177359
|
};
|
|
175437
177360
|
}
|
|
175438
177361
|
var NexumTUI = class {
|
|
@@ -175486,6 +177409,7 @@ var NexumTUI = class {
|
|
|
175486
177409
|
this.options = tuiOptions;
|
|
175487
177410
|
this.startupNotice = startupInput.startupNotice;
|
|
175488
177411
|
this.state = createTUIState(tuiOptions);
|
|
177412
|
+
this.harness.setSubagentModelBindings(() => this.state.appState.subagentModels);
|
|
175489
177413
|
this.reverseRpcDisposers.push(...registerReverseRPCHandlers(this.approvalController, this.questionController, {
|
|
175490
177414
|
showApprovalPanel: (payload) => {
|
|
175491
177415
|
this.showApprovalPanel(payload);
|
|
@@ -175710,10 +177634,7 @@ var NexumTUI = class {
|
|
|
175710
177634
|
pendingApproval: null,
|
|
175711
177635
|
pendingQuestion: null
|
|
175712
177636
|
});
|
|
175713
|
-
this.setAppState({
|
|
175714
|
-
streamingPhase: "waiting",
|
|
175715
|
-
streamingStartTime: Date.now()
|
|
175716
|
-
});
|
|
177637
|
+
this.setAppState({ streamingPhase: "waiting" });
|
|
175717
177638
|
}
|
|
175718
177639
|
failSessionRequest(message) {
|
|
175719
177640
|
this.setAppState({ streamingPhase: "idle" });
|
|
@@ -175795,10 +177716,21 @@ var NexumTUI = class {
|
|
|
175795
177716
|
}
|
|
175796
177717
|
}
|
|
175797
177718
|
setAppState(patch) {
|
|
177719
|
+
if ("streamingPhase" in patch && patch.streamingPhase !== void 0 && patch.streamingPhase !== this.state.appState.streamingPhase) patch = {
|
|
177720
|
+
...patch,
|
|
177721
|
+
streamingStartTime: patch.streamingPhase === "idle" ? 0 : Date.now()
|
|
177722
|
+
};
|
|
175798
177723
|
if (!hasPatchChanges(this.state.appState, patch)) return;
|
|
175799
177724
|
const busyChanged = "streamingPhase" in patch || "isCompacting" in patch;
|
|
177725
|
+
const prevPlanMode = this.state.appState.planMode;
|
|
177726
|
+
const prevSessionId = this.state.appState.sessionId;
|
|
175800
177727
|
Object.assign(this.state.appState, patch);
|
|
175801
|
-
|
|
177728
|
+
const planModeChanged = "planMode" in patch && prevPlanMode !== this.state.appState.planMode;
|
|
177729
|
+
const sessionChanged = "sessionId" in patch && this.state.appState.sessionId !== prevSessionId;
|
|
177730
|
+
if (planModeChanged || sessionChanged) {
|
|
177731
|
+
this.updateEditorBorderHighlight();
|
|
177732
|
+
this.state.planModeBanner.setPlanMode(this.state.appState.planMode ?? "off");
|
|
177733
|
+
}
|
|
175802
177734
|
if ("thinking" in patch) this.state.editor.thinking = patch.thinking ?? false;
|
|
175803
177735
|
if ("streamingPhase" in patch && patch.streamingPhase !== "idle") this.transcriptController.stopWelcomeBreathing();
|
|
175804
177736
|
this.state.footer.setState(this.state.appState);
|
|
@@ -175889,6 +177821,10 @@ var NexumTUI = class {
|
|
|
175889
177821
|
showNotice(title, detail) {
|
|
175890
177822
|
this.transcriptController.showNotice(title, detail);
|
|
175891
177823
|
}
|
|
177824
|
+
setPlanModeBanner(mode, planPath) {
|
|
177825
|
+
this.state.planModeBanner.setPlanMode(mode, planPath);
|
|
177826
|
+
this.state.ui.requestRender();
|
|
177827
|
+
}
|
|
175892
177828
|
showError(message) {
|
|
175893
177829
|
this.transcriptController.showError(message);
|
|
175894
177830
|
}
|
|
@@ -176232,6 +178168,9 @@ async function runShell(opts, version) {
|
|
|
176232
178168
|
});
|
|
176233
178169
|
await harness.ensureConfigFile();
|
|
176234
178170
|
await harness.preflight();
|
|
178171
|
+
refreshUpdateCache().catch((error) => {
|
|
178172
|
+
log.warn("update cache refresh failed", { error });
|
|
178173
|
+
});
|
|
176235
178174
|
await runLoadingAnimation(resolvedTheme);
|
|
176236
178175
|
const tui = new NexumTUI(harness, {
|
|
176237
178176
|
cliOptions: opts,
|
|
@@ -176772,6 +178711,15 @@ async function runStreamJson(opts) {
|
|
|
176772
178711
|
uiMode: "print",
|
|
176773
178712
|
skillDirs: opts.skillsDirs
|
|
176774
178713
|
});
|
|
178714
|
+
let streamTuiConfig;
|
|
178715
|
+
try {
|
|
178716
|
+
streamTuiConfig = await loadTuiConfig();
|
|
178717
|
+
} catch (error) {
|
|
178718
|
+
if (!(error instanceof TuiConfigParseError)) throw error;
|
|
178719
|
+
streamTuiConfig = error.fallback;
|
|
178720
|
+
}
|
|
178721
|
+
const streamSubagentModels = streamTuiConfig.subagentModels;
|
|
178722
|
+
harness.setSubagentModelBindings(() => streamSubagentModels);
|
|
176775
178723
|
const writer = new ClaudeStreamJsonWriter((line) => {
|
|
176776
178724
|
process.stdout.write(`${line}\n`);
|
|
176777
178725
|
});
|