scream-code 0.6.10 → 0.7.1
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-BRE6Pm0i.mjs → app-DupTD-8y.mjs} +2009 -390
- package/dist/assets/tokenizers.linux-x64-gnu-BGGFQRsL.node +0 -0
- package/dist/assets/tokenizers.win32-x64-msvc-7FuPBfvC.node +0 -0
- package/dist/{esm-Du2MwXei.mjs → esm-CLWbX2Ym.mjs} +2 -2
- package/dist/main.mjs +1 -1
- package/package.json +1 -1
- package/dist/{src-BMbLXrAA.mjs → src-Dae4j3bv.mjs} +2 -2
|
@@ -41,6 +41,8 @@ import { parse as parse$1, stringify } from "smol-toml";
|
|
|
41
41
|
import "zod/v3";
|
|
42
42
|
import * as z4mini from "zod/v4-mini";
|
|
43
43
|
import process$1 from "node:process";
|
|
44
|
+
import { lookup } from "node:dns/promises";
|
|
45
|
+
import { isIP } from "node:net";
|
|
44
46
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
45
47
|
import { Command, Option } from "commander";
|
|
46
48
|
import { CombinedAutocompleteProvider, Container, Editor, Image, Input, Key, Markdown, ProcessTerminal, Spacer, TUI, Text, decodeKittyPrintable, deleteAllKittyImages, fuzzyFilter, fuzzyMatch, getCapabilities, getImageDimensions, isKeyRelease, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
@@ -48,6 +50,7 @@ import chalk, { chalkStderr } from "chalk";
|
|
|
48
50
|
import { createInterface } from "node:readline/promises";
|
|
49
51
|
import { highlight, supportsLanguage } from "cli-highlight";
|
|
50
52
|
import { diffWords } from "diff";
|
|
53
|
+
import { promisify } from "node:util";
|
|
51
54
|
import { gt, valid } from "semver";
|
|
52
55
|
import { createInterface as createInterface$1 } from "node:readline";
|
|
53
56
|
//#region ../../node_modules/.pnpm/pathe@2.0.3/node_modules/pathe/dist/shared/pathe.M-eThtNZ.mjs
|
|
@@ -10455,7 +10458,7 @@ var require_gaxios = /* @__PURE__ */ __commonJSMin(((exports) => {
|
|
|
10455
10458
|
}
|
|
10456
10459
|
static async #getFetch() {
|
|
10457
10460
|
const hasWindow = typeof window !== "undefined" && !!window;
|
|
10458
|
-
this.#fetch ||= hasWindow ? window.fetch : (await import("./src-
|
|
10461
|
+
this.#fetch ||= hasWindow ? window.fetch : (await import("./src-Dae4j3bv.mjs")).default;
|
|
10459
10462
|
return this.#fetch;
|
|
10460
10463
|
}
|
|
10461
10464
|
/**
|
|
@@ -56831,7 +56834,7 @@ function createFastEmbedEngine() {
|
|
|
56831
56834
|
}
|
|
56832
56835
|
async function loadEmbedder() {
|
|
56833
56836
|
try {
|
|
56834
|
-
const { FlagEmbedding, EmbeddingModel } = await import("./esm-
|
|
56837
|
+
const { FlagEmbedding, EmbeddingModel } = await import("./esm-CLWbX2Ym.mjs");
|
|
56835
56838
|
return await FlagEmbedding.init({ model: EmbeddingModel.BGESmallZH });
|
|
56836
56839
|
} catch {
|
|
56837
56840
|
return null;
|
|
@@ -58343,17 +58346,22 @@ var LspClient = class {
|
|
|
58343
58346
|
command;
|
|
58344
58347
|
workspaceRoot;
|
|
58345
58348
|
jian;
|
|
58349
|
+
initializationOptions;
|
|
58346
58350
|
process;
|
|
58347
58351
|
nextId = 1;
|
|
58348
58352
|
pending = /* @__PURE__ */ new Map();
|
|
58349
58353
|
collectedDiagnostics = /* @__PURE__ */ new Map();
|
|
58354
|
+
openedDocuments = /* @__PURE__ */ new Set();
|
|
58355
|
+
documentVersion = /* @__PURE__ */ new Map();
|
|
58350
58356
|
buffer = "";
|
|
58357
|
+
bufferBytes = 0;
|
|
58351
58358
|
contentLength = -1;
|
|
58352
58359
|
started = false;
|
|
58353
|
-
constructor(command, workspaceRoot, jian) {
|
|
58360
|
+
constructor(command, workspaceRoot, jian, initializationOptions) {
|
|
58354
58361
|
this.command = command;
|
|
58355
58362
|
this.workspaceRoot = workspaceRoot;
|
|
58356
58363
|
this.jian = jian;
|
|
58364
|
+
this.initializationOptions = initializationOptions;
|
|
58357
58365
|
}
|
|
58358
58366
|
async start() {
|
|
58359
58367
|
if (this.started) return;
|
|
@@ -58366,7 +58374,9 @@ var LspClient = class {
|
|
|
58366
58374
|
throw new Error(`Failed to start language server ${this.command[0]}: ${message}`, { cause: error });
|
|
58367
58375
|
}
|
|
58368
58376
|
this.process.stdout.on("data", (chunk) => {
|
|
58369
|
-
|
|
58377
|
+
const text = chunk.toString("utf8");
|
|
58378
|
+
this.buffer += text;
|
|
58379
|
+
this.bufferBytes += Buffer.byteLength(text, "utf8");
|
|
58370
58380
|
this.processMessages();
|
|
58371
58381
|
});
|
|
58372
58382
|
this.process.stderr.on("data", (chunk) => {});
|
|
@@ -58379,8 +58389,16 @@ var LspClient = class {
|
|
|
58379
58389
|
willSaveWaitUntil: false,
|
|
58380
58390
|
didSave: false
|
|
58381
58391
|
},
|
|
58392
|
+
publishDiagnostics: {
|
|
58393
|
+
relatedInformation: true,
|
|
58394
|
+
versionSupport: false,
|
|
58395
|
+
tagSupport: { valueSet: [1, 2] },
|
|
58396
|
+
codeDescriptionSupport: true,
|
|
58397
|
+
dataSupport: true
|
|
58398
|
+
},
|
|
58382
58399
|
rename: { prepareSupport: false }
|
|
58383
|
-
} }
|
|
58400
|
+
} },
|
|
58401
|
+
initializationOptions: this.initializationOptions
|
|
58384
58402
|
});
|
|
58385
58403
|
this.notify("initialized", {});
|
|
58386
58404
|
}
|
|
@@ -58390,22 +58408,52 @@ var LspClient = class {
|
|
|
58390
58408
|
reject(/* @__PURE__ */ new Error("LSP client stopped"));
|
|
58391
58409
|
}
|
|
58392
58410
|
this.pending.clear();
|
|
58411
|
+
this.collectedDiagnostics.clear();
|
|
58412
|
+
this.openedDocuments.clear();
|
|
58413
|
+
this.documentVersion.clear();
|
|
58414
|
+
this.started = false;
|
|
58415
|
+
this.buffer = "";
|
|
58416
|
+
this.bufferBytes = 0;
|
|
58417
|
+
this.contentLength = -1;
|
|
58393
58418
|
if (this.process === void 0) return;
|
|
58394
58419
|
try {
|
|
58395
|
-
this.
|
|
58420
|
+
await this.request("shutdown", {});
|
|
58421
|
+
} catch {}
|
|
58422
|
+
try {
|
|
58396
58423
|
this.notify("exit", {});
|
|
58424
|
+
} catch {}
|
|
58425
|
+
try {
|
|
58397
58426
|
await this.process.kill("SIGTERM");
|
|
58398
58427
|
} catch {}
|
|
58399
58428
|
this.process = void 0;
|
|
58400
58429
|
}
|
|
58401
58430
|
didOpen(path, content, languageId) {
|
|
58431
|
+
const uri = pathToUri(path);
|
|
58432
|
+
if (this.openedDocuments.has(uri)) {
|
|
58433
|
+
this.didChange(path, content);
|
|
58434
|
+
return;
|
|
58435
|
+
}
|
|
58436
|
+
this.openedDocuments.add(uri);
|
|
58437
|
+
this.documentVersion.set(uri, 1);
|
|
58402
58438
|
this.notify("textDocument/didOpen", { textDocument: {
|
|
58403
|
-
uri
|
|
58439
|
+
uri,
|
|
58404
58440
|
languageId,
|
|
58405
58441
|
version: 1,
|
|
58406
58442
|
text: content
|
|
58407
58443
|
} });
|
|
58408
58444
|
}
|
|
58445
|
+
didChange(path, content) {
|
|
58446
|
+
const uri = pathToUri(path);
|
|
58447
|
+
const version = (this.documentVersion.get(uri) ?? 1) + 1;
|
|
58448
|
+
this.documentVersion.set(uri, version);
|
|
58449
|
+
this.notify("textDocument/didChange", {
|
|
58450
|
+
textDocument: {
|
|
58451
|
+
uri,
|
|
58452
|
+
version
|
|
58453
|
+
},
|
|
58454
|
+
contentChanges: [{ text: content }]
|
|
58455
|
+
});
|
|
58456
|
+
}
|
|
58409
58457
|
async references(path, line, character, includeDeclaration) {
|
|
58410
58458
|
return await this.request("textDocument/references", {
|
|
58411
58459
|
textDocument: { uri: pathToUri(path) },
|
|
@@ -58489,19 +58537,20 @@ var LspClient = class {
|
|
|
58489
58537
|
if (headerEnd === -1) return;
|
|
58490
58538
|
const header = this.buffer.slice(0, headerEnd);
|
|
58491
58539
|
const match = /Content-Length:\s*(\d+)/i.exec(header);
|
|
58492
|
-
|
|
58493
|
-
|
|
58494
|
-
|
|
58495
|
-
|
|
58540
|
+
const headerEndChar = headerEnd + 4;
|
|
58541
|
+
const droppedHeader = this.buffer.slice(0, headerEndChar);
|
|
58542
|
+
this.bufferBytes -= Buffer.byteLength(droppedHeader, "utf8");
|
|
58543
|
+
this.buffer = this.buffer.slice(headerEndChar);
|
|
58544
|
+
if (match === null) continue;
|
|
58496
58545
|
this.contentLength = Number(match[1]);
|
|
58497
|
-
this.buffer = this.buffer.slice(headerEnd + 4);
|
|
58498
58546
|
}
|
|
58499
|
-
if (this.
|
|
58500
|
-
const
|
|
58501
|
-
this.buffer = this.buffer.slice(
|
|
58547
|
+
if (this.bufferBytes < this.contentLength) return;
|
|
58548
|
+
const { text, consumedChars, consumedBytes } = sliceByBytes(this.buffer, this.contentLength);
|
|
58549
|
+
this.buffer = this.buffer.slice(consumedChars);
|
|
58550
|
+
this.bufferBytes -= consumedBytes;
|
|
58502
58551
|
this.contentLength = -1;
|
|
58503
58552
|
try {
|
|
58504
|
-
const message = JSON.parse(
|
|
58553
|
+
const message = JSON.parse(text);
|
|
58505
58554
|
this.handleMessage(message);
|
|
58506
58555
|
} catch {}
|
|
58507
58556
|
}
|
|
@@ -58550,6 +58599,39 @@ function sleep$1(ms) {
|
|
|
58550
58599
|
setTimeout(resolve, ms);
|
|
58551
58600
|
});
|
|
58552
58601
|
}
|
|
58602
|
+
function byteLengthOfCodePoint(codePoint) {
|
|
58603
|
+
if (codePoint <= 127) return 1;
|
|
58604
|
+
if (codePoint <= 2047) return 2;
|
|
58605
|
+
if (codePoint <= 65535) return 3;
|
|
58606
|
+
return 4;
|
|
58607
|
+
}
|
|
58608
|
+
/**
|
|
58609
|
+
* Slice `targetBytes` worth of UTF-8 from the head of `text`.
|
|
58610
|
+
*
|
|
58611
|
+
* LSP `Content-Length` is a byte count, but JS strings are UTF-16 code units.
|
|
58612
|
+
* Slicing by `string.length` misaligns messages containing multi-byte chars
|
|
58613
|
+
* (Chinese diagnostics, emoji). This walks code points, summing UTF-8 bytes,
|
|
58614
|
+
* and never splits a multi-byte character mid-sequence so `JSON.parse` won't
|
|
58615
|
+
* choke on a half-character.
|
|
58616
|
+
*/
|
|
58617
|
+
function sliceByBytes(text, targetBytes) {
|
|
58618
|
+
let chars = 0;
|
|
58619
|
+
let bytes = 0;
|
|
58620
|
+
while (chars < text.length && bytes < targetBytes) {
|
|
58621
|
+
const codePoint = text.codePointAt(chars);
|
|
58622
|
+
if (codePoint === void 0) break;
|
|
58623
|
+
const charLen = codePoint > 65535 ? 2 : 1;
|
|
58624
|
+
const charBytes = byteLengthOfCodePoint(codePoint);
|
|
58625
|
+
if (bytes + charBytes > targetBytes) break;
|
|
58626
|
+
bytes += charBytes;
|
|
58627
|
+
chars += charLen;
|
|
58628
|
+
}
|
|
58629
|
+
return {
|
|
58630
|
+
text: text.slice(0, chars),
|
|
58631
|
+
consumedChars: chars,
|
|
58632
|
+
consumedBytes: bytes
|
|
58633
|
+
};
|
|
58634
|
+
}
|
|
58553
58635
|
function formatLocation(location) {
|
|
58554
58636
|
const uri = location.uri.startsWith("file://") ? location.uri.slice(7) : location.uri;
|
|
58555
58637
|
const { start } = location.range;
|
|
@@ -69291,7 +69373,7 @@ async function resolveGithubSource(input) {
|
|
|
69291
69373
|
}, 3e4);
|
|
69292
69374
|
let headProbe;
|
|
69293
69375
|
try {
|
|
69294
|
-
headProbe = await fetch(`https://codeload.github.com/${owner}/${repo}/zip/HEAD`, {
|
|
69376
|
+
headProbe = await fetch(`https://codeload.github.com/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/zip/HEAD`, {
|
|
69295
69377
|
method: "HEAD",
|
|
69296
69378
|
signal: headController.signal
|
|
69297
69379
|
});
|
|
@@ -69301,7 +69383,7 @@ async function resolveGithubSource(input) {
|
|
|
69301
69383
|
if (headProbe.status === 404) throw new Error(`Repository \`${owner}/${repo}\` not found or not accessible.`);
|
|
69302
69384
|
if (!headProbe.ok) throw new Error(`Could not access \`${owner}/${repo}\`: HTTP ${headProbe.status} ${headProbe.statusText}.`);
|
|
69303
69385
|
return {
|
|
69304
|
-
tarballUrl: `https://codeload.github.com/${owner}/${repo}/zip/HEAD`,
|
|
69386
|
+
tarballUrl: `https://codeload.github.com/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/zip/HEAD`,
|
|
69305
69387
|
displayVersion: "HEAD",
|
|
69306
69388
|
ref: {
|
|
69307
69389
|
kind: "branch",
|
|
@@ -69322,7 +69404,7 @@ async function resolveGithubSource(input) {
|
|
|
69322
69404
|
* not tell them.
|
|
69323
69405
|
*/
|
|
69324
69406
|
async function tryResolveLatestReleaseTag(owner, repo) {
|
|
69325
|
-
const url = `https://github.com/${owner}/${repo}/releases/latest`;
|
|
69407
|
+
const url = `https://github.com/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/releases/latest`;
|
|
69326
69408
|
const controller = new AbortController();
|
|
69327
69409
|
const timeoutHandle = setTimeout(() => {
|
|
69328
69410
|
controller.abort();
|
|
@@ -69349,7 +69431,7 @@ async function tryResolveLatestReleaseTag(owner, repo) {
|
|
|
69349
69431
|
}
|
|
69350
69432
|
}
|
|
69351
69433
|
function codeloadUrl(owner, repo, ref) {
|
|
69352
|
-
const base = `https://codeload.github.com/${owner}/${repo}/zip`;
|
|
69434
|
+
const base = `https://codeload.github.com/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/zip`;
|
|
69353
69435
|
const encoded = encodeCodeloadRefPath(ref.value);
|
|
69354
69436
|
if (ref.kind === "sha") return `${base}/${encoded}`;
|
|
69355
69437
|
if (ref.kind === "tag") return `${base}/refs/tags/${encoded}`;
|
|
@@ -70130,6 +70212,7 @@ async function writeInstalled(screamHomeDir, data) {
|
|
|
70130
70212
|
//#endregion
|
|
70131
70213
|
//#region ../../packages/agent-core/src/plugin/source.ts
|
|
70132
70214
|
const SHA_RE = /^[0-9a-f]{7,40}$/;
|
|
70215
|
+
const GITHUB_NAME_RE = /^[A-Za-z0-9._-]+$/;
|
|
70133
70216
|
function resolveInstallSource(source) {
|
|
70134
70217
|
const trimmed = source.trim();
|
|
70135
70218
|
const github = parseGithubUrl(trimmed);
|
|
@@ -70157,6 +70240,7 @@ function parseGithubUrl(raw) {
|
|
|
70157
70240
|
const owner = segments[0];
|
|
70158
70241
|
const repoRaw = segments[1];
|
|
70159
70242
|
if (owner === void 0 || repoRaw === void 0) return void 0;
|
|
70243
|
+
if (!GITHUB_NAME_RE.test(owner) || !GITHUB_NAME_RE.test(repoRaw)) return void 0;
|
|
70160
70244
|
const repo = repoRaw.endsWith(".git") ? repoRaw.slice(0, -4) : repoRaw;
|
|
70161
70245
|
const rest = segments.slice(2);
|
|
70162
70246
|
if (rest.length === 0) return {
|
|
@@ -70965,7 +71049,7 @@ function validateSkillPlan(plan, nameHint) {
|
|
|
70965
71049
|
}
|
|
70966
71050
|
//#endregion
|
|
70967
71051
|
//#region ../../packages/agent-core/src/tools/builtin/collaboration/wolfpack.md
|
|
70968
|
-
var wolfpack_default = "Use WolfPack to spawn multiple subagents in parallel for batch operations.\nThis is ideal when processing many independent items (files, checks, searches)\nthat all use the same subagent type and follow a similar pattern.\n\nInput:\n- description: Brief (3-5 word) task summary.\n- subagent_type: Subagent profile name. Defaults to \"coder\".\n- prompt_template: A prompt pattern where each item value is substituted in\n to produce a per-item prompt. See the parameter schema for placeholder syntax.\n- items: Array of item strings. Each item gets its own subagent (
|
|
71052
|
+
var wolfpack_default = "Use WolfPack to spawn multiple subagents in parallel for batch operations.\nThis is ideal when processing many independent items (files, checks, searches)\nthat all use the same subagent type and follow a similar pattern.\n\nInput:\n- description: Brief (3-5 word) task summary.\n- subagent_type: Subagent profile name. Defaults to \"coder\". Choose the profile\n that best matches the batch task — using the right type materially improves\n output quality. See the agent type list below for which type fits which job.\n- prompt_template: A prompt pattern where each item value is substituted in\n to produce a per-item prompt. See the parameter schema for placeholder syntax.\n- items: Array of item strings. Each item gets its own subagent (no limit).\n\nItems must be independent — no subagent depends on another's output.\nIf items depend on each other, use separate Agent calls instead.\n\nChoosing subagent_type for the batch:\n- Batch code review, audit, or bug-finding across files → reviewer\n- Batch writing, reports, or long-form content → writer\n- Batch read-only exploration (find files, grep, understand modules) → explore\n- Batch verification (run build/test/lint per item) → verify\n- Batch deep debugging or architecture decisions → oracle\n- Batch planning or design work → plan\n- General engineering tasks with no specialised match → coder (default)\n\nExample: review source files for OWASP vulnerabilities by setting items to the file\npaths, subagent_type to \"reviewer\", and prompt_template to the review instruction.\nAll items are processed in parallel.\n\n";
|
|
70969
71053
|
//#endregion
|
|
70970
71054
|
//#region ../../packages/agent-core/src/tools/builtin/collaboration/wolfpack.ts
|
|
70971
71055
|
/**
|
|
@@ -70973,25 +71057,28 @@ var wolfpack_default = "Use WolfPack to spawn multiple subagents in parallel for
|
|
|
70973
71057
|
*
|
|
70974
71058
|
* Spawns multiple subagents in parallel using a template + items pattern.
|
|
70975
71059
|
* Each item gets its own subagent; results are batched together.
|
|
70976
|
-
*
|
|
71060
|
+
* There is no artificial concurrency cap: all items spawn and run in parallel.
|
|
70977
71061
|
*/
|
|
70978
|
-
const MAX_ITEMS = 20;
|
|
70979
71062
|
const WolfPackToolInputSchema = z.object({
|
|
70980
71063
|
description: z.string().min(1).describe("Short task description (3-5 words, e.g., \"Security review all files\")"),
|
|
70981
71064
|
subagent_type: z.string().default("coder").describe("Subagent type for all spawned agents (e.g., coder, explore, verify)"),
|
|
70982
71065
|
prompt_template: z.string().min(1).describe("Prompt template with {{item}} placeholder. Each item is substituted in."),
|
|
70983
|
-
items: z.array(z.string().min(1)).min(1).
|
|
71066
|
+
items: z.array(z.string().min(1)).min(1).describe("Array of items to process. Each item gets its own subagent.")
|
|
70984
71067
|
});
|
|
70985
71068
|
var WolfPackTool = class {
|
|
70986
71069
|
subagentHost;
|
|
70987
71070
|
isEnabled;
|
|
70988
71071
|
name = "WolfPack";
|
|
70989
|
-
description
|
|
71072
|
+
description;
|
|
70990
71073
|
parameters = toInputJsonSchema(WolfPackToolInputSchema);
|
|
70991
|
-
constructor(subagentHost, isEnabled,
|
|
71074
|
+
constructor(subagentHost, isEnabled, options) {
|
|
70992
71075
|
this.subagentHost = subagentHost;
|
|
70993
71076
|
this.isEnabled = isEnabled;
|
|
71077
|
+
const typeLines = buildSubagentDescriptions(options?.subagents);
|
|
71078
|
+
this.description = typeLines ? `${wolfpack_default}\n\nAvailable agent types (pass via subagent_type):\n${typeLines}` : wolfpack_default;
|
|
71079
|
+
this.log = options?.log;
|
|
70994
71080
|
}
|
|
71081
|
+
log;
|
|
70995
71082
|
resolveExecution(args) {
|
|
70996
71083
|
return {
|
|
70997
71084
|
description: `WolfPack: ${args.description} (${args.items.length} agents)`,
|
|
@@ -71014,13 +71101,8 @@ var WolfPackTool = class {
|
|
|
71014
71101
|
output: "WolfPack 模式未开启。请输入 /wolfpack 打开后再试。",
|
|
71015
71102
|
isError: true
|
|
71016
71103
|
};
|
|
71017
|
-
if (args.items.length > MAX_ITEMS) return {
|
|
71018
|
-
output: `WolfPack max ${MAX_ITEMS} items. Got ${args.items.length}.`,
|
|
71019
|
-
isError: true
|
|
71020
|
-
};
|
|
71021
71104
|
const profileName = args.subagent_type ?? "coder";
|
|
71022
71105
|
const template = args.prompt_template;
|
|
71023
|
-
const WOLFPACK_CONCURRENCY = 8;
|
|
71024
71106
|
const handlePromises = args.items.map(async (item) => {
|
|
71025
71107
|
ctx.signal.throwIfAborted();
|
|
71026
71108
|
try {
|
|
@@ -71042,14 +71124,7 @@ var WolfPackTool = class {
|
|
|
71042
71124
|
};
|
|
71043
71125
|
}
|
|
71044
71126
|
});
|
|
71045
|
-
const
|
|
71046
|
-
for (let i = 0; i < handlePromises.length; i += WOLFPACK_CONCURRENCY) {
|
|
71047
|
-
ctx.signal.throwIfAborted();
|
|
71048
|
-
const batch = handlePromises.slice(i, i + WOLFPACK_CONCURRENCY);
|
|
71049
|
-
const batchResults = await Promise.allSettled(batch);
|
|
71050
|
-
handleResults.push(...batchResults);
|
|
71051
|
-
}
|
|
71052
|
-
const completionPromises = handleResults.map(async (settled) => {
|
|
71127
|
+
const completionPromises = (await Promise.allSettled(handlePromises)).map(async (settled) => {
|
|
71053
71128
|
if (settled.status === "rejected") return {
|
|
71054
71129
|
item: "unknown",
|
|
71055
71130
|
result: `Spawn failed: ${settled.reason instanceof Error ? settled.reason.message : String(settled.reason)}`,
|
|
@@ -71123,6 +71198,193 @@ var WolfPackTool = class {
|
|
|
71123
71198
|
}
|
|
71124
71199
|
};
|
|
71125
71200
|
//#endregion
|
|
71201
|
+
//#region ../../packages/agent-core/src/tools/builtin/file/conflict-detect.ts
|
|
71202
|
+
/**
|
|
71203
|
+
* Detect unresolved git merge conflict markers in read output.
|
|
71204
|
+
*
|
|
71205
|
+
* Scans for well-formed `<<<<<<<` / `=======` / `>>>>>>>` blocks at column 0
|
|
71206
|
+
* and, when found, appends a notice to the read result so the model does not
|
|
71207
|
+
* silently edit a file with unresolved conflicts.
|
|
71208
|
+
*
|
|
71209
|
+
* Marker shape is strict (ported from oh-my-pi `conflict-detect.ts:171-176`):
|
|
71210
|
+
* prefix alone, or prefix + single space + label. Lines that merely start
|
|
71211
|
+
* with `<` or `=` never match. Only fully-closed blocks (opener + separator
|
|
71212
|
+
* + closer all present in the scanned window) are reported — an open block
|
|
71213
|
+
* whose closer is past the read window is dropped so the agent can widen the
|
|
71214
|
+
* read instead of being told about a half-seen conflict.
|
|
71215
|
+
*/
|
|
71216
|
+
const OURS_PREFIX = "<<<<<<<";
|
|
71217
|
+
const BASE_PREFIX = "|||||||";
|
|
71218
|
+
const SEPARATOR = "=======";
|
|
71219
|
+
const THEIRS_PREFIX = ">>>>>>>";
|
|
71220
|
+
/**
|
|
71221
|
+
* Return the label after a marker prefix when the line is a valid column-0
|
|
71222
|
+
* marker, or `null` when it isn't. Strict shape: prefix alone, or prefix +
|
|
71223
|
+
* single space + label.
|
|
71224
|
+
*/
|
|
71225
|
+
function matchMarker(line, prefix) {
|
|
71226
|
+
if (!line.startsWith(prefix)) return null;
|
|
71227
|
+
if (line.length === prefix.length) return "";
|
|
71228
|
+
if (line.codePointAt(prefix.length) !== 32) return null;
|
|
71229
|
+
return line.slice(prefix.length + 1);
|
|
71230
|
+
}
|
|
71231
|
+
function stripTrailingCr(line) {
|
|
71232
|
+
return line.endsWith("\r") ? line.slice(0, -1) : line;
|
|
71233
|
+
}
|
|
71234
|
+
/**
|
|
71235
|
+
* Scan an already-collected array of file lines for completed conflict blocks.
|
|
71236
|
+
* `firstLineNumber` is the 1-indexed line number of `lines[0]`.
|
|
71237
|
+
*/
|
|
71238
|
+
function scanConflictLines(lines, firstLineNumber = 1) {
|
|
71239
|
+
const blocks = [];
|
|
71240
|
+
let phase = "idle";
|
|
71241
|
+
let partial = null;
|
|
71242
|
+
for (let i = 0; i < lines.length; i++) {
|
|
71243
|
+
const line = stripTrailingCr(lines[i]);
|
|
71244
|
+
const ln = firstLineNumber + i;
|
|
71245
|
+
if (matchMarker(line, OURS_PREFIX) !== null) {
|
|
71246
|
+
partial = { startLine: ln };
|
|
71247
|
+
phase = "ours";
|
|
71248
|
+
continue;
|
|
71249
|
+
}
|
|
71250
|
+
if (phase === "idle" || partial === null) continue;
|
|
71251
|
+
if (matchMarker(line, BASE_PREFIX) !== null) {
|
|
71252
|
+
if (phase !== "ours") {
|
|
71253
|
+
partial = null;
|
|
71254
|
+
phase = "idle";
|
|
71255
|
+
continue;
|
|
71256
|
+
}
|
|
71257
|
+
partial.baseLine = ln;
|
|
71258
|
+
phase = "base";
|
|
71259
|
+
continue;
|
|
71260
|
+
}
|
|
71261
|
+
if (line === SEPARATOR) {
|
|
71262
|
+
if (phase === "ours" || phase === "base") {
|
|
71263
|
+
partial.separatorLine = ln;
|
|
71264
|
+
phase = "theirs";
|
|
71265
|
+
} else {
|
|
71266
|
+
partial = null;
|
|
71267
|
+
phase = "idle";
|
|
71268
|
+
}
|
|
71269
|
+
continue;
|
|
71270
|
+
}
|
|
71271
|
+
if (matchMarker(line, THEIRS_PREFIX) !== null) {
|
|
71272
|
+
if (phase === "theirs" && partial.separatorLine !== void 0) blocks.push({
|
|
71273
|
+
startLine: partial.startLine,
|
|
71274
|
+
separatorLine: partial.separatorLine,
|
|
71275
|
+
endLine: ln,
|
|
71276
|
+
baseLine: partial.baseLine
|
|
71277
|
+
});
|
|
71278
|
+
partial = null;
|
|
71279
|
+
phase = "idle";
|
|
71280
|
+
continue;
|
|
71281
|
+
}
|
|
71282
|
+
}
|
|
71283
|
+
return blocks;
|
|
71284
|
+
}
|
|
71285
|
+
/**
|
|
71286
|
+
* Format the conflict notice appended to read output. Returns an empty
|
|
71287
|
+
* string when there are no blocks so callers can skip the append entirely.
|
|
71288
|
+
*/
|
|
71289
|
+
function formatConflictNotice(blocks) {
|
|
71290
|
+
if (blocks.length === 0) return "";
|
|
71291
|
+
const list = blocks.map((b) => `lines ${String(b.startLine)}-${String(b.endLine)}`).join(", ");
|
|
71292
|
+
return `⚠ ${String(blocks.length)} unresolved merge conflict(s) detected: ${list}`;
|
|
71293
|
+
}
|
|
71294
|
+
//#endregion
|
|
71295
|
+
//#region ../../packages/agent-core/src/tools/builtin/file/lsp-diagnostics.ts
|
|
71296
|
+
const DIAGNOSTICS_TIMEOUT_MS = 1500;
|
|
71297
|
+
const MAX_DIAGNOSTICS_LINES = 8;
|
|
71298
|
+
/** Returns true when any diagnostic is severity 1 (Error) per LSP spec. */
|
|
71299
|
+
function hasErrors(diagnostics) {
|
|
71300
|
+
return diagnostics.some((d) => d.severity === 1);
|
|
71301
|
+
}
|
|
71302
|
+
/**
|
|
71303
|
+
* Fetch diagnostics for a file after it has been edited. Reads the current
|
|
71304
|
+
* file content, notifies the LSP server (didOpen for first open, didChange
|
|
71305
|
+
* internally for subsequent edits), then polls for published diagnostics.
|
|
71306
|
+
*
|
|
71307
|
+
* Never throws — LSP failures are swallowed so Edit/Write always succeed.
|
|
71308
|
+
* When the LSP is unavailable, `reason` distinguishes unsupported file types
|
|
71309
|
+
* from a missing language server binary so the caller can decide whether to
|
|
71310
|
+
* surface an install hint.
|
|
71311
|
+
*/
|
|
71312
|
+
async function fetchDiagnostics(registry, jian, path, workspaceRoot) {
|
|
71313
|
+
if (registry === void 0) return {
|
|
71314
|
+
available: false,
|
|
71315
|
+
diagnostics: [],
|
|
71316
|
+
hasErrors: false,
|
|
71317
|
+
reason: "unsupported"
|
|
71318
|
+
};
|
|
71319
|
+
const languageId = registry.languageIdForPath(path);
|
|
71320
|
+
if (languageId === void 0) return {
|
|
71321
|
+
available: false,
|
|
71322
|
+
diagnostics: [],
|
|
71323
|
+
hasErrors: false,
|
|
71324
|
+
reason: "unsupported"
|
|
71325
|
+
};
|
|
71326
|
+
const serverCommand = registry.commandForPath(path)?.[0];
|
|
71327
|
+
let client;
|
|
71328
|
+
try {
|
|
71329
|
+
client = await registry.getClient(path, workspaceRoot);
|
|
71330
|
+
} catch {
|
|
71331
|
+
return {
|
|
71332
|
+
available: false,
|
|
71333
|
+
diagnostics: [],
|
|
71334
|
+
hasErrors: false,
|
|
71335
|
+
reason: "server-missing",
|
|
71336
|
+
serverCommand
|
|
71337
|
+
};
|
|
71338
|
+
}
|
|
71339
|
+
if (client === void 0) return {
|
|
71340
|
+
available: false,
|
|
71341
|
+
diagnostics: [],
|
|
71342
|
+
hasErrors: false,
|
|
71343
|
+
reason: "unsupported"
|
|
71344
|
+
};
|
|
71345
|
+
try {
|
|
71346
|
+
const content = await jian.readText(path);
|
|
71347
|
+
client.didOpen(path, content, languageId);
|
|
71348
|
+
const diags = await client.diagnostics(path, DIAGNOSTICS_TIMEOUT_MS);
|
|
71349
|
+
return {
|
|
71350
|
+
available: true,
|
|
71351
|
+
diagnostics: diags,
|
|
71352
|
+
hasErrors: hasErrors(diags)
|
|
71353
|
+
};
|
|
71354
|
+
} catch {
|
|
71355
|
+
return {
|
|
71356
|
+
available: true,
|
|
71357
|
+
diagnostics: [],
|
|
71358
|
+
hasErrors: false
|
|
71359
|
+
};
|
|
71360
|
+
}
|
|
71361
|
+
}
|
|
71362
|
+
/**
|
|
71363
|
+
* Format diagnostics as text to append to tool output. Returns an empty
|
|
71364
|
+
* string when no diagnostics were reported, so callers can unconditionally
|
|
71365
|
+
* append without a guard.
|
|
71366
|
+
*/
|
|
71367
|
+
function formatDiagnosticsNotice(result) {
|
|
71368
|
+
if (!result.available || result.diagnostics.length === 0) return "";
|
|
71369
|
+
const lines = result.diagnostics.slice(0, MAX_DIAGNOSTICS_LINES).map((d) => formatDiagnostic(d));
|
|
71370
|
+
const remaining = result.diagnostics.length - MAX_DIAGNOSTICS_LINES;
|
|
71371
|
+
const header = `[LSP] ${String(result.diagnostics.length)} diagnostic(s):`;
|
|
71372
|
+
const tail = remaining > 0 ? `\n… (${String(remaining)} more)` : "";
|
|
71373
|
+
return `${header}\n${lines.join("\n")}${tail}`;
|
|
71374
|
+
}
|
|
71375
|
+
/**
|
|
71376
|
+
* Build a friendly hint shown after Edit/Write when the language server is
|
|
71377
|
+
* missing for a supported file type. Returns an empty string for unsupported
|
|
71378
|
+
* file types (no point suggesting a server that wouldn't apply) and when the
|
|
71379
|
+
* server did start successfully.
|
|
71380
|
+
*/
|
|
71381
|
+
function formatDiagnosticsHint(result) {
|
|
71382
|
+
if (result.reason !== "server-missing") return "";
|
|
71383
|
+
const cmd = result.serverCommand;
|
|
71384
|
+
if (cmd === void 0) return "";
|
|
71385
|
+
return `\n提示:为获得编辑后的类型与语法诊断,建议安装语言服务器 \`${cmd}\`。`;
|
|
71386
|
+
}
|
|
71387
|
+
//#endregion
|
|
71126
71388
|
//#region ../../packages/agent-core/src/tools/builtin/file/line-endings.ts
|
|
71127
71389
|
function detectLineEndingStyle(text) {
|
|
71128
71390
|
let hasCrLf = false;
|
|
@@ -71163,7 +71425,7 @@ function computeAnchor(text) {
|
|
|
71163
71425
|
}
|
|
71164
71426
|
//#endregion
|
|
71165
71427
|
//#region ../../packages/agent-core/src/tools/builtin/file/edit.md
|
|
71166
|
-
var edit_default = "Perform exact string replacements against the text view returned by Read.\n\n- When copying from Read output, omit the line-number prefix and tab; match only the file content.\n- By default, old_string must occur exactly once. If it matches multiple locations, add surrounding context or set replace_all when every occurrence should change.\n- Prefer Edit for targeted changes to existing files; use Write only for new files or complete overwrites.\n- To modify a file, always use Edit; do not run a Shell `sed` command for edits.\n- When making several independent changes, issue multiple Edit calls in parallel within a single response; edits to the same file are serialized automatically by a write lock.\n- When several parallel Edit calls target the same file, a write lock serializes them; they apply in the order the calls appear in your response. An edit fails with `old_string not found` if its old_string was taken from text an earlier edit already replaced — base every old_string on the latest Read view and order dependent edits accordingly.\n- For pure CRLF files, Read shows LF and Edit.old_string/new_string should use LF; Edit writes the file back with CRLF preserved.\n- For mixed line endings or lone carriage returns, Read displays carriage returns as \\r; include actual \\r escapes in old_string/new_string for those positions.\n- When Read returned an `Anchor:` value in its status block, pass it as `anchor` to verify the file has not changed since it was read. If the anchor does not match, re-read the file before editing.";
|
|
71428
|
+
var edit_default = "Perform exact string replacements against the text view returned by Read.\n\n- When copying from Read output, omit the line-number prefix and tab; match only the file content.\n- By default, old_string must occur exactly once. If it matches multiple locations, add surrounding context or set replace_all when every occurrence should change.\n- Prefer Edit for targeted changes to existing files; use Write only for new files or complete overwrites.\n- To modify a file, always use Edit; do not run a Shell `sed` command for edits.\n- When making several independent changes, issue multiple Edit calls in parallel within a single response; edits to the same file are serialized automatically by a write lock.\n- When several parallel Edit calls target the same file, a write lock serializes them; they apply in the order the calls appear in your response. An edit fails with `old_string not found` if its old_string was taken from text an earlier edit already replaced — base every old_string on the latest Read view and order dependent edits accordingly.\n- For pure CRLF files, Read shows LF and Edit.old_string/new_string should use LF; Edit writes the file back with CRLF preserved.\n- For mixed line endings or lone carriage returns, Read displays carriage returns as \\r; include actual \\r escapes in old_string/new_string for those positions.\n- When Read returned an `Anchor:` value in its status block, pass it as `anchor` to verify the file has not changed since it was read. If the anchor does not match, re-read the file before editing.\n- Edit refuses if `old_string` lands inside an unresolved merge conflict block, or if `new_string` would introduce `<<<<<<<`/`=======`/`>>>>>>>` markers. To clean up a conflict, include the markers in `old_string` so Edit replaces them.";
|
|
71167
71429
|
//#endregion
|
|
71168
71430
|
//#region ../../packages/agent-core/src/tools/builtin/file/edit.ts
|
|
71169
71431
|
const EditInputSchema = z.object({
|
|
@@ -71181,12 +71443,14 @@ function replaceOnceLiteral(content, oldString, newString) {
|
|
|
71181
71443
|
var EditTool = class {
|
|
71182
71444
|
jian;
|
|
71183
71445
|
workspace;
|
|
71446
|
+
lspRegistry;
|
|
71184
71447
|
name = "Edit";
|
|
71185
71448
|
description = edit_default;
|
|
71186
71449
|
parameters = toInputJsonSchema(EditInputSchema);
|
|
71187
|
-
constructor(jian, workspace) {
|
|
71450
|
+
constructor(jian, workspace, lspRegistry) {
|
|
71188
71451
|
this.jian = jian;
|
|
71189
71452
|
this.workspace = workspace;
|
|
71453
|
+
this.lspRegistry = lspRegistry;
|
|
71190
71454
|
}
|
|
71191
71455
|
resolveExecution(args) {
|
|
71192
71456
|
const path = resolvePathAccessPath(args.path, {
|
|
@@ -71218,10 +71482,36 @@ var EditTool = class {
|
|
|
71218
71482
|
isError: true,
|
|
71219
71483
|
output: "No changes to make: old_string and new_string are exactly the same."
|
|
71220
71484
|
};
|
|
71485
|
+
if (scanConflictLines(args.new_string.split("\n")).length > 0) return {
|
|
71486
|
+
isError: true,
|
|
71487
|
+
output: "new_string contains merge conflict markers (<<<<<<< / ======= / >>>>>>>). Remove them before writing. These markers indicate an unresolved merge and should not be introduced into files."
|
|
71488
|
+
};
|
|
71221
71489
|
try {
|
|
71222
71490
|
const modelView = toModelTextView(await this.jian.readText(safePath));
|
|
71223
71491
|
const content = modelView.text;
|
|
71224
71492
|
const replaceAll = args.replace_all ?? false;
|
|
71493
|
+
const existingBlocks = scanConflictLines(content.split("\n"));
|
|
71494
|
+
if (existingBlocks.length > 0) {
|
|
71495
|
+
const oldStringLineCount = args.old_string.split("\n").length;
|
|
71496
|
+
let pos = 0;
|
|
71497
|
+
let conflictViolation = null;
|
|
71498
|
+
while (pos < content.length) {
|
|
71499
|
+
const idx = content.indexOf(args.old_string, pos);
|
|
71500
|
+
if (idx === -1) break;
|
|
71501
|
+
const matchStartLine = content.slice(0, idx).split("\n").length;
|
|
71502
|
+
const matchEndLine = matchStartLine + oldStringLineCount - 1;
|
|
71503
|
+
if (existingBlocks.some((b) => matchStartLine > b.startLine && matchEndLine < b.endLine)) {
|
|
71504
|
+
const blockList = existingBlocks.map((b) => `lines ${String(b.startLine)}-${String(b.endLine)}`).join(", ");
|
|
71505
|
+
conflictViolation = `${args.path} has unresolved merge conflict markers (${blockList}). Resolve the conflict before editing inside it, or include the conflict markers in old_string to replace them.`;
|
|
71506
|
+
break;
|
|
71507
|
+
}
|
|
71508
|
+
pos = idx + args.old_string.length;
|
|
71509
|
+
}
|
|
71510
|
+
if (conflictViolation !== null) return {
|
|
71511
|
+
isError: true,
|
|
71512
|
+
output: conflictViolation
|
|
71513
|
+
};
|
|
71514
|
+
}
|
|
71225
71515
|
if (args.anchor !== void 0) {
|
|
71226
71516
|
const currentAnchor = computeAnchor(content);
|
|
71227
71517
|
if (currentAnchor !== args.anchor) return {
|
|
@@ -71249,7 +71539,12 @@ var EditTool = class {
|
|
|
71249
71539
|
};
|
|
71250
71540
|
const newContent = replaceOnceLiteral(content, args.old_string, args.new_string);
|
|
71251
71541
|
await this.jian.writeText(safePath, materializeModelText(newContent, modelView.lineEndingStyle));
|
|
71252
|
-
|
|
71542
|
+
const { notice, hasErrors } = await this.appendDiagnostics(safePath);
|
|
71543
|
+
const output = `Replaced 1 occurrence in ${args.path}${notice}`;
|
|
71544
|
+
return hasErrors ? {
|
|
71545
|
+
isError: true,
|
|
71546
|
+
output
|
|
71547
|
+
} : { output };
|
|
71253
71548
|
}
|
|
71254
71549
|
const parts = content.split(args.old_string);
|
|
71255
71550
|
const replacementCount = parts.length - 1;
|
|
@@ -71260,7 +71555,12 @@ var EditTool = class {
|
|
|
71260
71555
|
};
|
|
71261
71556
|
const newContent = parts.join(args.new_string);
|
|
71262
71557
|
await this.jian.writeText(safePath, materializeModelText(newContent, modelView.lineEndingStyle));
|
|
71263
|
-
|
|
71558
|
+
const { notice, hasErrors } = await this.appendDiagnostics(safePath);
|
|
71559
|
+
const output = `Replaced ${String(replacementCount)} occurrences in ${args.path}${notice}`;
|
|
71560
|
+
return hasErrors ? {
|
|
71561
|
+
isError: true,
|
|
71562
|
+
output
|
|
71563
|
+
} : { output };
|
|
71264
71564
|
} catch (error) {
|
|
71265
71565
|
if (error?.code === "EISDIR") return {
|
|
71266
71566
|
isError: true,
|
|
@@ -71272,6 +71572,13 @@ var EditTool = class {
|
|
|
71272
71572
|
};
|
|
71273
71573
|
}
|
|
71274
71574
|
}
|
|
71575
|
+
async appendDiagnostics(safePath) {
|
|
71576
|
+
const result = await fetchDiagnostics(this.lspRegistry, this.jian, safePath, this.workspace.workspaceDir);
|
|
71577
|
+
return {
|
|
71578
|
+
notice: [formatDiagnosticsNotice(result), formatDiagnosticsHint(result)].filter((s) => s.length > 0).join(""),
|
|
71579
|
+
hasErrors: result.hasErrors
|
|
71580
|
+
};
|
|
71581
|
+
}
|
|
71275
71582
|
};
|
|
71276
71583
|
async function collectEntries(jian, dirPath, maxWidth) {
|
|
71277
71584
|
const all = [];
|
|
@@ -71391,7 +71698,7 @@ var GlobTool = class {
|
|
|
71391
71698
|
workspace: this.workspace,
|
|
71392
71699
|
operation: "search",
|
|
71393
71700
|
policy: {
|
|
71394
|
-
guardMode: "
|
|
71701
|
+
guardMode: "absolute-outside-allowed",
|
|
71395
71702
|
checkSensitive: false
|
|
71396
71703
|
}
|
|
71397
71704
|
});
|
|
@@ -74781,47 +75088,42 @@ Error: ${cause instanceof Error ? cause.message : typeof cause === "string" ? ca
|
|
|
74781
75088
|
//#endregion
|
|
74782
75089
|
//#region ../../packages/agent-core/src/tools/support/result-builder.ts
|
|
74783
75090
|
const DEFAULT_MAX_CHARS = 5e4;
|
|
75091
|
+
const DEFAULT_TAIL_CHARS = 2e4;
|
|
74784
75092
|
const DEFAULT_MAX_LINE_LENGTH = 2e3;
|
|
74785
75093
|
const TRUNCATION_MARKER = "[...truncated]";
|
|
74786
75094
|
const TRUNCATION_MESSAGE = "Output is truncated to fit in the message.";
|
|
74787
75095
|
var ToolResultBuilder = class {
|
|
74788
75096
|
maxChars;
|
|
75097
|
+
maxTailChars;
|
|
74789
75098
|
maxLineLength;
|
|
74790
75099
|
buffer = [];
|
|
74791
75100
|
nCharsValue = 0;
|
|
74792
75101
|
truncationHappened = false;
|
|
75102
|
+
headTruncated = false;
|
|
75103
|
+
tailBuf = [];
|
|
75104
|
+
tailCharsValue = 0;
|
|
74793
75105
|
constructor(options = {}) {
|
|
74794
75106
|
this.maxChars = options.maxChars ?? DEFAULT_MAX_CHARS;
|
|
75107
|
+
this.maxTailChars = options.maxTailChars ?? DEFAULT_TAIL_CHARS;
|
|
74795
75108
|
this.maxLineLength = options.maxLineLength === void 0 ? DEFAULT_MAX_LINE_LENGTH : options.maxLineLength;
|
|
74796
75109
|
if (this.maxLineLength !== null && this.maxLineLength <= 14) throw new Error("maxLineLength must be greater than the truncation marker length.");
|
|
74797
75110
|
}
|
|
74798
75111
|
get nChars() {
|
|
74799
|
-
return this.nCharsValue;
|
|
75112
|
+
return this.nCharsValue + this.tailCharsValue;
|
|
74800
75113
|
}
|
|
74801
75114
|
toString() {
|
|
74802
|
-
|
|
75115
|
+
const head = this.buffer.join("");
|
|
75116
|
+
if (!this.headTruncated || this.tailCharsValue === 0) return head;
|
|
75117
|
+
this.trimTail();
|
|
75118
|
+
const tail = this.tailBuf.join("");
|
|
75119
|
+
return `${head}${head.endsWith("\n") ? "" : "\n"}${TRUNCATION_MARKER}\n${tail}`;
|
|
74803
75120
|
}
|
|
74804
75121
|
write(text) {
|
|
74805
|
-
if (
|
|
74806
|
-
if (text.length > 0 && !this.truncationHappened) {
|
|
74807
|
-
this.buffer.push(TRUNCATION_MARKER);
|
|
74808
|
-
this.nCharsValue += 14;
|
|
74809
|
-
this.truncationHappened = true;
|
|
74810
|
-
}
|
|
74811
|
-
return 0;
|
|
74812
|
-
}
|
|
75122
|
+
if (text.length === 0) return 0;
|
|
74813
75123
|
const lines = text.match(/[^\r\n]*(?:\r\n|[\n\r])|[^\r\n]+/g) ?? [];
|
|
74814
75124
|
if (lines.length === 0) return 0;
|
|
74815
75125
|
let charsWritten = 0;
|
|
74816
|
-
for (const originalLine of lines) {
|
|
74817
|
-
if (this.nCharsValue >= this.maxChars) {
|
|
74818
|
-
if (!this.truncationHappened) {
|
|
74819
|
-
this.buffer.push(TRUNCATION_MARKER);
|
|
74820
|
-
this.nCharsValue += 14;
|
|
74821
|
-
this.truncationHappened = true;
|
|
74822
|
-
}
|
|
74823
|
-
break;
|
|
74824
|
-
}
|
|
75126
|
+
for (const originalLine of lines) if (this.nCharsValue < this.maxChars) {
|
|
74825
75127
|
const remainingChars = this.maxChars - this.nCharsValue;
|
|
74826
75128
|
const limit = this.maxLineLength === null ? remainingChars : Math.min(remainingChars, this.maxLineLength);
|
|
74827
75129
|
let line = originalLine;
|
|
@@ -74829,19 +75131,49 @@ var ToolResultBuilder = class {
|
|
|
74829
75131
|
const suffix = TRUNCATION_MARKER + (/[\r\n]+$/.exec(line)?.[0] ?? "");
|
|
74830
75132
|
const effectiveMaxLength = Math.max(limit, suffix.length);
|
|
74831
75133
|
line = line.slice(0, effectiveMaxLength - suffix.length) + suffix;
|
|
75134
|
+
this.truncationHappened = true;
|
|
74832
75135
|
}
|
|
74833
|
-
if (line !== originalLine) this.truncationHappened = true;
|
|
74834
75136
|
this.buffer.push(line);
|
|
74835
75137
|
charsWritten += line.length;
|
|
74836
75138
|
this.nCharsValue += line.length;
|
|
75139
|
+
if (this.nCharsValue >= this.maxChars) {
|
|
75140
|
+
this.headTruncated = true;
|
|
75141
|
+
this.truncationHappened = true;
|
|
75142
|
+
}
|
|
75143
|
+
} else {
|
|
75144
|
+
this.appendTail(originalLine);
|
|
75145
|
+
charsWritten += originalLine.length;
|
|
75146
|
+
this.headTruncated = true;
|
|
75147
|
+
this.truncationHappened = true;
|
|
74837
75148
|
}
|
|
74838
75149
|
return charsWritten;
|
|
74839
75150
|
}
|
|
75151
|
+
appendTail(text) {
|
|
75152
|
+
if (text.length === 0) return;
|
|
75153
|
+
if (this.maxTailChars === 0) return;
|
|
75154
|
+
if (text.length >= this.maxTailChars) {
|
|
75155
|
+
const trimmed = text.slice(-this.maxTailChars);
|
|
75156
|
+
this.tailBuf.length = 0;
|
|
75157
|
+
this.tailBuf.push(trimmed);
|
|
75158
|
+
this.tailCharsValue = trimmed.length;
|
|
75159
|
+
return;
|
|
75160
|
+
}
|
|
75161
|
+
this.tailBuf.push(text);
|
|
75162
|
+
this.tailCharsValue += text.length;
|
|
75163
|
+
if (this.tailCharsValue > this.maxTailChars * 2) this.trimTail();
|
|
75164
|
+
}
|
|
75165
|
+
trimTail() {
|
|
75166
|
+
if (this.tailCharsValue <= this.maxTailChars) return;
|
|
75167
|
+
const trimmed = this.tailBuf.join("").slice(-this.maxTailChars);
|
|
75168
|
+
this.tailBuf.length = 0;
|
|
75169
|
+
this.tailBuf.push(trimmed);
|
|
75170
|
+
this.tailCharsValue = trimmed.length;
|
|
75171
|
+
}
|
|
74840
75172
|
ok(message = "", options = {}) {
|
|
74841
75173
|
let finalMessage = message;
|
|
74842
75174
|
if (finalMessage.length > 0 && !finalMessage.endsWith(".")) finalMessage += ".";
|
|
74843
75175
|
if (this.truncationHappened) finalMessage = finalMessage.length === 0 ? TRUNCATION_MESSAGE : `${finalMessage} ${TRUNCATION_MESSAGE}`;
|
|
74844
|
-
const output = this.
|
|
75176
|
+
const output = this.toString();
|
|
74845
75177
|
return {
|
|
74846
75178
|
isError: false,
|
|
74847
75179
|
output: finalMessage.length > 0 && (this.truncationHappened || output.length === 0) ? output.length === 0 ? finalMessage : output.endsWith("\n") ? `${output}${finalMessage}` : `${output}\n${finalMessage}` : output,
|
|
@@ -74852,7 +75184,7 @@ var ToolResultBuilder = class {
|
|
|
74852
75184
|
}
|
|
74853
75185
|
error(message, options = {}) {
|
|
74854
75186
|
const finalMessage = this.truncationHappened ? message.length === 0 ? TRUNCATION_MESSAGE : `${message} ${TRUNCATION_MESSAGE}` : message;
|
|
74855
|
-
const output = this.
|
|
75187
|
+
const output = this.toString();
|
|
74856
75188
|
return {
|
|
74857
75189
|
isError: true,
|
|
74858
75190
|
output: finalMessage.length === 0 ? output : output.length === 0 ? finalMessage : output.endsWith("\n") ? `${output}${finalMessage}` : `${output}\n${finalMessage}`,
|
|
@@ -74906,6 +75238,7 @@ const MAX_OUTPUT_BYTES = 10 * 1024 * 1024;
|
|
|
74906
75238
|
const RG_MAX_COLUMNS = 500;
|
|
74907
75239
|
const DEFAULT_HEAD_LIMIT = 250;
|
|
74908
75240
|
const MTIME_STAT_CONCURRENCY = 32;
|
|
75241
|
+
const MAX_DISPLAY_MATCHES = 100;
|
|
74909
75242
|
const VCS_DIRECTORIES_TO_EXCLUDE = [
|
|
74910
75243
|
".git",
|
|
74911
75244
|
".svn",
|
|
@@ -75050,9 +75383,59 @@ var GrepTool = class {
|
|
|
75050
75383
|
const combined = visibleBody === "" && messages.length === 0 ? emptyResultMessage : messages.length > 0 ? visibleBody === "" ? messages.join("\n") : `${visibleBody}\n${messages.join("\n")}` : visibleBody;
|
|
75051
75384
|
const builder = new ToolResultBuilder();
|
|
75052
75385
|
builder.write(combined);
|
|
75053
|
-
|
|
75386
|
+
const result = builder.ok(sideChannelMessages.join("\n"));
|
|
75387
|
+
const display = buildSearchResultsDisplay(args, limited, mode, contentIncludesLineNumbers);
|
|
75388
|
+
if (display === void 0) return result;
|
|
75389
|
+
if (result.isError === true) return result;
|
|
75390
|
+
return {
|
|
75391
|
+
...result,
|
|
75392
|
+
display
|
|
75393
|
+
};
|
|
75054
75394
|
}
|
|
75055
75395
|
};
|
|
75396
|
+
/**
|
|
75397
|
+
* Build the structured `search_results` side channel for TUI renderers.
|
|
75398
|
+
*
|
|
75399
|
+
* Only `content` mode carries per-line `lineNum:text` payloads worth surfacing
|
|
75400
|
+
* as structured matches; `files_with_matches` and `count_matches` modes have
|
|
75401
|
+
* empty or count-only payloads and would mislead renderers that expect real
|
|
75402
|
+
* line/text data. Returns `undefined` when there are no records to surface.
|
|
75403
|
+
*
|
|
75404
|
+
* Records are taken from the already-paginated `limited` view so the
|
|
75405
|
+
* structured display mirrors what the text `output` shows.
|
|
75406
|
+
*/
|
|
75407
|
+
function buildSearchResultsDisplay(args, limited, mode, contentIncludesLineNumbers) {
|
|
75408
|
+
if (mode !== "content") return void 0;
|
|
75409
|
+
const matches = [];
|
|
75410
|
+
for (const entry of limited) {
|
|
75411
|
+
if (entry.kind !== "record") continue;
|
|
75412
|
+
const { filePath, payload } = entry;
|
|
75413
|
+
if (contentIncludesLineNumbers) {
|
|
75414
|
+
const m = /^(\d+)([:-])(.*)$/.exec(payload);
|
|
75415
|
+
if (m !== null && m[1] !== void 0 && m[3] !== void 0) matches.push({
|
|
75416
|
+
file: filePath,
|
|
75417
|
+
line: Number.parseInt(m[1], 10),
|
|
75418
|
+
text: m[3]
|
|
75419
|
+
});
|
|
75420
|
+
else matches.push({
|
|
75421
|
+
file: filePath,
|
|
75422
|
+
line: 0,
|
|
75423
|
+
text: payload
|
|
75424
|
+
});
|
|
75425
|
+
} else matches.push({
|
|
75426
|
+
file: filePath,
|
|
75427
|
+
line: 0,
|
|
75428
|
+
text: payload
|
|
75429
|
+
});
|
|
75430
|
+
if (matches.length >= MAX_DISPLAY_MATCHES) break;
|
|
75431
|
+
}
|
|
75432
|
+
if (matches.length === 0) return void 0;
|
|
75433
|
+
return {
|
|
75434
|
+
kind: "search_results",
|
|
75435
|
+
query: args.pattern,
|
|
75436
|
+
matches
|
|
75437
|
+
};
|
|
75438
|
+
}
|
|
75056
75439
|
var GrepAbortedError = class extends Error {
|
|
75057
75440
|
constructor() {
|
|
75058
75441
|
super("Grep aborted");
|
|
@@ -75851,6 +76234,90 @@ function detectFileType(path, header) {
|
|
|
75851
76234
|
};
|
|
75852
76235
|
}
|
|
75853
76236
|
//#endregion
|
|
76237
|
+
//#region ../../packages/agent-core/src/tools/support/suffix-match.ts
|
|
76238
|
+
const SUFFIX_MATCH_TIMEOUT_MS = 5e3;
|
|
76239
|
+
function escapeGlobMetachars(value) {
|
|
76240
|
+
return value.replaceAll(/[*?[{]/g, "[$&]");
|
|
76241
|
+
}
|
|
76242
|
+
async function findUniqueSuffixMatch(rawPath, searchRoot, jian, cache) {
|
|
76243
|
+
const normalized = rawPath.replaceAll(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
|
|
76244
|
+
if (!normalized) return null;
|
|
76245
|
+
if (cache !== void 0) {
|
|
76246
|
+
const hit = cache.get(rawPath);
|
|
76247
|
+
if (hit !== void 0) return hit;
|
|
76248
|
+
}
|
|
76249
|
+
const pattern = `**/${escapeGlobMetachars(normalized)}`;
|
|
76250
|
+
const matches = [];
|
|
76251
|
+
let timer;
|
|
76252
|
+
try {
|
|
76253
|
+
const globPromise = (async () => {
|
|
76254
|
+
for await (const filePath of jian.glob(searchRoot, pattern)) {
|
|
76255
|
+
matches.push(filePath);
|
|
76256
|
+
if (matches.length > 1) break;
|
|
76257
|
+
}
|
|
76258
|
+
})();
|
|
76259
|
+
const timeoutPromise = new Promise((resolve) => {
|
|
76260
|
+
timer = setTimeout(resolve, SUFFIX_MATCH_TIMEOUT_MS);
|
|
76261
|
+
timer.unref?.();
|
|
76262
|
+
});
|
|
76263
|
+
await Promise.race([globPromise, timeoutPromise]);
|
|
76264
|
+
} catch {
|
|
76265
|
+
if (cache !== void 0) cache.set(rawPath, null);
|
|
76266
|
+
return null;
|
|
76267
|
+
} finally {
|
|
76268
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
76269
|
+
}
|
|
76270
|
+
if (matches.length !== 1) {
|
|
76271
|
+
if (cache !== void 0) cache.set(rawPath, null);
|
|
76272
|
+
return null;
|
|
76273
|
+
}
|
|
76274
|
+
const matched = matches[0];
|
|
76275
|
+
const result = {
|
|
76276
|
+
absolutePath: matched,
|
|
76277
|
+
displayPath: matched
|
|
76278
|
+
};
|
|
76279
|
+
if (cache !== void 0) cache.set(rawPath, result);
|
|
76280
|
+
return result;
|
|
76281
|
+
}
|
|
76282
|
+
function suffixResolutionNotice(from, to) {
|
|
76283
|
+
return `[Path '${from}' not found; resolved to '${to}' via suffix match]`;
|
|
76284
|
+
}
|
|
76285
|
+
function isFileNotFoundErrorLike(error) {
|
|
76286
|
+
if (typeof error !== "object" || error === null) return false;
|
|
76287
|
+
const code = error["code"];
|
|
76288
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
76289
|
+
}
|
|
76290
|
+
async function partitionExistingPaths(paths, jian, workspace) {
|
|
76291
|
+
const settled = await Promise.all(paths.map(async (path) => {
|
|
76292
|
+
try {
|
|
76293
|
+
const safePath = resolvePathAccessPath(path, {
|
|
76294
|
+
jian,
|
|
76295
|
+
workspace,
|
|
76296
|
+
operation: "read"
|
|
76297
|
+
});
|
|
76298
|
+
await jian.stat(safePath);
|
|
76299
|
+
return {
|
|
76300
|
+
path,
|
|
76301
|
+
exists: true
|
|
76302
|
+
};
|
|
76303
|
+
} catch (error) {
|
|
76304
|
+
if (isFileNotFoundErrorLike(error)) return {
|
|
76305
|
+
path,
|
|
76306
|
+
exists: false
|
|
76307
|
+
};
|
|
76308
|
+
throw error;
|
|
76309
|
+
}
|
|
76310
|
+
}));
|
|
76311
|
+
const valid = [];
|
|
76312
|
+
const missing = [];
|
|
76313
|
+
for (const entry of settled) if (entry.exists) valid.push(entry.path);
|
|
76314
|
+
else missing.push(entry.path);
|
|
76315
|
+
return {
|
|
76316
|
+
valid,
|
|
76317
|
+
missing
|
|
76318
|
+
};
|
|
76319
|
+
}
|
|
76320
|
+
//#endregion
|
|
75854
76321
|
//#region ../../packages/agent-core/src/tools/builtin/file/read.md
|
|
75855
76322
|
var read_default = "Read a text file from the local filesystem.\n\nIf the user provides a concrete file path to a text file, call Read directly. Do not `Glob`, `ls`, or otherwise pre-check known text file paths; missing or invalid file paths return errors you can handle. Do not use Read for directories; use `ls` via Bash for a known directory, or Glob when you need files/directories matching a pattern. Use `Grep` only when the task is to search for unknown content or locations.\n\nWhen you need several files, prefer to read them in parallel: emit multiple `Read` calls in a single response instead of reading one file per turn.\n\n- Relative paths resolve against the working directory; a path outside the working directory must be absolute.\n- Returns up to {{ MAX_LINES }} lines or {{ MAX_BYTES_KB }} KB per call, whichever comes first; lines longer than {{ MAX_LINE_LENGTH }} chars are truncated mid-line.\n- Page larger files with `line_offset` (1-based start line) and `n_lines`. Omit `n_lines` to read up to the {{ MAX_LINES }}-line cap.\n- Sensitive files (`.env` files, credential stores, SSH keys, and similar secrets) are refused to protect secrets; do not attempt to read them.\n- Only UTF-8 text files can be read. Non-UTF-8 encodings, binary files, and files containing NUL bytes are refused; use `ReadMediaFile` for images or video, and Bash or an MCP tool for other binary formats.\n- Negative line_offset reads from the end of the file (for example, -100 reads the last 100 lines); the absolute value cannot exceed {{ MAX_LINES }}.\n- Output format: `<line-number>\\t<content>` per line.\n- A `<system>...</system>` status block is appended after the file content; it summarizes how much was read (line and byte counts, truncation, line-ending notes) and is not part of the file itself. The status block includes an `Anchor: <hash>` value that can be passed to `Edit.anchor` to verify the file has not changed before editing.\n- Pure CRLF files are displayed with LF line endings; `Edit` matches this output and preserves CRLF when writing back.\n- Mixed or lone carriage-return line endings are shown as `\\r` and require exact `Edit.old_string` escapes.\n- After a successful `Edit`/`Write`, do not re-read solely to prove the write landed. When the task depends on an exact file, API, or output shape, inspect the final external contract before finishing.\n";
|
|
75856
76323
|
//#endregion
|
|
@@ -75915,6 +76382,22 @@ function isFileNotFoundError(error) {
|
|
|
75915
76382
|
const code = error["code"];
|
|
75916
76383
|
return code === "ENOENT" || code === "ENOTDIR";
|
|
75917
76384
|
}
|
|
76385
|
+
function prependNotice(result, notice) {
|
|
76386
|
+
if (typeof result.output === "string") {
|
|
76387
|
+
const prefixed = result.output.length > 0 ? `${notice}\n${result.output}` : notice;
|
|
76388
|
+
return {
|
|
76389
|
+
...result,
|
|
76390
|
+
output: prefixed
|
|
76391
|
+
};
|
|
76392
|
+
}
|
|
76393
|
+
return {
|
|
76394
|
+
...result,
|
|
76395
|
+
output: [{
|
|
76396
|
+
type: "text",
|
|
76397
|
+
text: notice
|
|
76398
|
+
}, ...result.output]
|
|
76399
|
+
};
|
|
76400
|
+
}
|
|
75918
76401
|
function isTextDecodeError(error) {
|
|
75919
76402
|
if (typeof error !== "object" || error === null) return false;
|
|
75920
76403
|
if (error["code"] === "ERR_ENCODING_INVALID_ENCODED_DATA") return true;
|
|
@@ -75965,16 +76448,42 @@ var ReadTool = class {
|
|
|
75965
76448
|
execute: () => this.execution(args, path)
|
|
75966
76449
|
};
|
|
75967
76450
|
}
|
|
75968
|
-
async
|
|
76451
|
+
async trySuffixMatchRead(args) {
|
|
76452
|
+
const suffixMatch = await findUniqueSuffixMatch(args.path, this.workspace.workspaceDir, this.jian);
|
|
76453
|
+
if (suffixMatch === null) return null;
|
|
76454
|
+
try {
|
|
76455
|
+
if (!isRegularFileMode((await this.jian.stat(suffixMatch.absolutePath)).stMode)) return null;
|
|
76456
|
+
} catch {
|
|
76457
|
+
return null;
|
|
76458
|
+
}
|
|
76459
|
+
const notice = suffixResolutionNotice(args.path, suffixMatch.displayPath);
|
|
76460
|
+
return prependNotice(await this.execution(args, suffixMatch.absolutePath, true), notice);
|
|
76461
|
+
}
|
|
76462
|
+
async fileNotFoundResult(displayPath) {
|
|
76463
|
+
let tree;
|
|
76464
|
+
try {
|
|
76465
|
+
tree = await listDirectory(this.jian, this.workspace.workspaceDir);
|
|
76466
|
+
} catch {
|
|
76467
|
+
tree = "(listing unavailable)";
|
|
76468
|
+
}
|
|
76469
|
+
return {
|
|
76470
|
+
isError: true,
|
|
76471
|
+
output: `"${displayPath}" does not exist.\n\nTop of ${this.workspace.workspaceDir}:\n${tree}`
|
|
76472
|
+
};
|
|
76473
|
+
}
|
|
76474
|
+
async execution(args, safePath, suffixResolved = false) {
|
|
75969
76475
|
try {
|
|
75970
76476
|
let stat;
|
|
75971
76477
|
try {
|
|
75972
76478
|
stat = await this.jian.stat(safePath);
|
|
75973
76479
|
} catch (error) {
|
|
75974
|
-
if (isFileNotFoundError(error))
|
|
75975
|
-
|
|
75976
|
-
|
|
75977
|
-
|
|
76480
|
+
if (isFileNotFoundError(error)) {
|
|
76481
|
+
if (!suffixResolved) {
|
|
76482
|
+
const resolved = await this.trySuffixMatchRead(args);
|
|
76483
|
+
if (resolved !== null) return resolved;
|
|
76484
|
+
}
|
|
76485
|
+
return await this.fileNotFoundResult(args.path);
|
|
76486
|
+
}
|
|
75978
76487
|
throw error;
|
|
75979
76488
|
}
|
|
75980
76489
|
if (!isRegularFileMode(stat.stMode)) return {
|
|
@@ -76142,7 +76651,13 @@ var ReadTool = class {
|
|
|
76142
76651
|
});
|
|
76143
76652
|
}
|
|
76144
76653
|
finishReadResult(input) {
|
|
76145
|
-
|
|
76654
|
+
const message = this.finishMessage(input);
|
|
76655
|
+
const notice = formatConflictNotice(scanConflictLines(input.renderedLines.map((l) => {
|
|
76656
|
+
const tabIdx = l.indexOf(" ");
|
|
76657
|
+
return tabIdx === -1 ? l : l.slice(tabIdx + 1);
|
|
76658
|
+
}), input.startLine));
|
|
76659
|
+
const fullMessage = notice.length > 0 ? `${message} ${notice}` : message;
|
|
76660
|
+
return { output: this.finishOutput(input.renderedLines, fullMessage) };
|
|
76146
76661
|
}
|
|
76147
76662
|
finishOutput(renderedLines, message) {
|
|
76148
76663
|
const rendered = renderedLines.join("\n");
|
|
@@ -76164,7 +76679,7 @@ var ReadTool = class {
|
|
|
76164
76679
|
};
|
|
76165
76680
|
//#endregion
|
|
76166
76681
|
//#region ../../packages/agent-core/src/tools/builtin/file/read-group.md
|
|
76167
|
-
var read_group_default = "Read multiple files in parallel.\n\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.\n\nInputs:\n- paths: array of file paths (max
|
|
76682
|
+
var read_group_default = "Read multiple files in parallel.\n\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.\n\nInputs:\n- paths: array of file paths (max 20). Relative paths resolve against the working directory.\n- line_offset: optional starting line number (1-based; negative values read from the end).\n- n_lines: optional maximum lines per file.\n\nOutput:\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.\n\nAfter the file contents, the output may include footers:\n- `Skipped missing paths:` when some paths did not exist.\n- `Conflict markers detected —` when any file contains unresolved merge conflict markers.\n- `Imports:` a cross-file import summary for TypeScript/JavaScript files, showing relative import specifiers (e.g. `a.ts → ./b, ./c`).\n\nUse Read (single file) when only one file is needed; use ReadGroup when you want 2-20 files at once.\n";
|
|
76168
76683
|
//#endregion
|
|
76169
76684
|
//#region ../../packages/agent-core/src/tools/builtin/file/read-group.ts
|
|
76170
76685
|
function toolOutputText$1(output) {
|
|
@@ -76173,9 +76688,62 @@ function toolOutputText$1(output) {
|
|
|
76173
76688
|
return typeof part === "object" && part !== null && part.type === "text";
|
|
76174
76689
|
}).map((part) => part.text).join("");
|
|
76175
76690
|
}
|
|
76176
|
-
|
|
76691
|
+
/**
|
|
76692
|
+
* Scan a Read result's output for merge conflict markers. Returns a formatted
|
|
76693
|
+
* notice string (empty when no conflicts found). Strips the `NNN\t` line-number
|
|
76694
|
+
* prefix Read adds before scanning, and extracts the first line number so
|
|
76695
|
+
* reported conflict line ranges match the file's actual line numbers.
|
|
76696
|
+
*/
|
|
76697
|
+
function conflictNoticeForReadResult(result) {
|
|
76698
|
+
if (result.isError === true) return "";
|
|
76699
|
+
const lines = toolOutputText$1(result.output).split("\n");
|
|
76700
|
+
let firstLineNumber = 1;
|
|
76701
|
+
for (const line of lines) {
|
|
76702
|
+
const tabIdx = line.indexOf(" ");
|
|
76703
|
+
if (tabIdx > 0) {
|
|
76704
|
+
const num = parseInt(line.slice(0, tabIdx), 10);
|
|
76705
|
+
if (!Number.isNaN(num)) firstLineNumber = num;
|
|
76706
|
+
break;
|
|
76707
|
+
}
|
|
76708
|
+
if (line.length === 0 || line.startsWith("<system>")) continue;
|
|
76709
|
+
break;
|
|
76710
|
+
}
|
|
76711
|
+
return formatConflictNotice(scanConflictLines(extractRawContentLines(result), firstLineNumber));
|
|
76712
|
+
}
|
|
76713
|
+
const IMPORTABLE_EXTENSIONS = new Set([
|
|
76714
|
+
"ts",
|
|
76715
|
+
"tsx",
|
|
76716
|
+
"js",
|
|
76717
|
+
"jsx",
|
|
76718
|
+
"mjs"
|
|
76719
|
+
]);
|
|
76720
|
+
const IMPORT_RE = /^\s*(?:import|export)\s+.*\sfrom\s+['"](\.\/[^'"]+)['"]/;
|
|
76721
|
+
const MAX_IMPORT_EDGES = 10;
|
|
76722
|
+
function fileExtension$1(path) {
|
|
76723
|
+
const base = path.split(/[\\/]/).at(-1) ?? path;
|
|
76724
|
+
const dotIdx = base.lastIndexOf(".");
|
|
76725
|
+
if (dotIdx <= 0) return "no-ext";
|
|
76726
|
+
return base.slice(dotIdx + 1).toLowerCase();
|
|
76727
|
+
}
|
|
76728
|
+
function extractRawContentLines(result) {
|
|
76729
|
+
if (result.isError === true) return [];
|
|
76730
|
+
return toolOutputText$1(result.output).split("\n").map((line) => {
|
|
76731
|
+
const tabIdx = line.indexOf(" ");
|
|
76732
|
+
return tabIdx === -1 ? line : line.slice(tabIdx + 1);
|
|
76733
|
+
});
|
|
76734
|
+
}
|
|
76735
|
+
function extractImportTargets(rawLines) {
|
|
76736
|
+
const targets = [];
|
|
76737
|
+
for (const line of rawLines) {
|
|
76738
|
+
if (line.startsWith("<system>")) continue;
|
|
76739
|
+
const match = IMPORT_RE.exec(line);
|
|
76740
|
+
if (match && match[1] !== void 0) targets.push(match[1]);
|
|
76741
|
+
}
|
|
76742
|
+
return targets;
|
|
76743
|
+
}
|
|
76744
|
+
const NonEmptyStringArraySchema = z.array(z.string().min(1)).min(1).max(20);
|
|
76177
76745
|
const ReadGroupInputSchema = z.object({
|
|
76178
|
-
paths: NonEmptyStringArraySchema.describe(`Array of file paths to read in parallel (1-${String(
|
|
76746
|
+
paths: NonEmptyStringArraySchema.describe(`Array of file paths to read in parallel (1-${String(20)} files).`),
|
|
76179
76747
|
line_offset: z.number().int().optional().describe("Starting line number applied to every file."),
|
|
76180
76748
|
n_lines: z.number().int().positive().optional().describe("Maximum lines per file.")
|
|
76181
76749
|
});
|
|
@@ -76191,28 +76759,33 @@ var ReadGroupTool = class {
|
|
|
76191
76759
|
this.workspace = workspace;
|
|
76192
76760
|
}
|
|
76193
76761
|
resolveExecution(args) {
|
|
76194
|
-
const paths = args.paths.slice(0,
|
|
76762
|
+
const paths = args.paths.slice(0, 20);
|
|
76195
76763
|
const readTool = new ReadTool(this.jian, this.workspace);
|
|
76196
|
-
const
|
|
76197
|
-
for (const path of paths) {
|
|
76764
|
+
const items = [];
|
|
76765
|
+
for (const path of paths) try {
|
|
76198
76766
|
const exec = readTool.resolveExecution({
|
|
76199
76767
|
path,
|
|
76200
76768
|
line_offset: args.line_offset,
|
|
76201
76769
|
n_lines: args.n_lines
|
|
76202
76770
|
});
|
|
76203
|
-
if ("isError" in exec && exec.isError === true)
|
|
76771
|
+
if ("isError" in exec && exec.isError === true) items.push({
|
|
76204
76772
|
path,
|
|
76205
76773
|
error: toolOutputText$1(exec.output)
|
|
76206
76774
|
});
|
|
76207
|
-
else
|
|
76775
|
+
else items.push({
|
|
76208
76776
|
path,
|
|
76209
76777
|
exec
|
|
76210
76778
|
});
|
|
76779
|
+
} catch (error) {
|
|
76780
|
+
items.push({
|
|
76781
|
+
path,
|
|
76782
|
+
error: error instanceof Error ? error.message : String(error)
|
|
76783
|
+
});
|
|
76211
76784
|
}
|
|
76212
|
-
const accesses =
|
|
76785
|
+
const accesses = items.filter((e) => "exec" in e).flatMap((e) => e.exec.accesses ?? ToolAccesses.none());
|
|
76213
76786
|
const sortedPaths = [...paths].toSorted();
|
|
76214
76787
|
const approvalRule = literalRulePattern(this.name, sortedPaths.join("\n"));
|
|
76215
|
-
const deniedCount =
|
|
76788
|
+
const deniedCount = items.filter((e) => "error" in e).length;
|
|
76216
76789
|
return {
|
|
76217
76790
|
accesses,
|
|
76218
76791
|
description: deniedCount > 0 ? `Reading ${String(paths.length)} files (${String(deniedCount)} denied)` : `Reading ${String(paths.length)} files`,
|
|
@@ -76223,11 +76796,27 @@ var ReadGroupTool = class {
|
|
|
76223
76796
|
},
|
|
76224
76797
|
approvalRule,
|
|
76225
76798
|
matchesRule: (ruleArgs) => ruleArgs === approvalRule,
|
|
76226
|
-
execute: (ctx) => this.execution(
|
|
76227
|
-
};
|
|
76228
|
-
}
|
|
76229
|
-
async execution(
|
|
76230
|
-
const
|
|
76799
|
+
execute: (ctx) => this.execution(args, items, ctx)
|
|
76800
|
+
};
|
|
76801
|
+
}
|
|
76802
|
+
async execution(args, items, ctx) {
|
|
76803
|
+
const paths = items.map((i) => i.path);
|
|
76804
|
+
let missingPaths = [];
|
|
76805
|
+
if (paths.length > 1) {
|
|
76806
|
+
const probePaths = items.filter((i) => "exec" in i).map((i) => i.path);
|
|
76807
|
+
if (probePaths.length > 0) try {
|
|
76808
|
+
const partition = await partitionExistingPaths(probePaths, this.jian, this.workspace);
|
|
76809
|
+
missingPaths = partition.missing;
|
|
76810
|
+
if (partition.valid.length === 0 && items.every((i) => "exec" in i)) return {
|
|
76811
|
+
isError: true,
|
|
76812
|
+
output: `Paths not found: ${missingPaths.join(", ")}`
|
|
76813
|
+
};
|
|
76814
|
+
} catch {
|
|
76815
|
+
missingPaths = [];
|
|
76816
|
+
}
|
|
76817
|
+
}
|
|
76818
|
+
const missingSet = new Set(missingPaths);
|
|
76819
|
+
const results = await Promise.all(items.map(async (item) => {
|
|
76231
76820
|
if ("error" in item) return {
|
|
76232
76821
|
path: item.path,
|
|
76233
76822
|
result: {
|
|
@@ -76235,6 +76824,13 @@ var ReadGroupTool = class {
|
|
|
76235
76824
|
output: item.error
|
|
76236
76825
|
}
|
|
76237
76826
|
};
|
|
76827
|
+
if (missingSet.has(item.path)) return {
|
|
76828
|
+
path: item.path,
|
|
76829
|
+
result: {
|
|
76830
|
+
isError: true,
|
|
76831
|
+
output: `"${item.path}" does not exist.`
|
|
76832
|
+
}
|
|
76833
|
+
};
|
|
76238
76834
|
try {
|
|
76239
76835
|
const result = await item.exec.execute(ctx);
|
|
76240
76836
|
return {
|
|
@@ -76251,15 +76847,58 @@ var ReadGroupTool = class {
|
|
|
76251
76847
|
};
|
|
76252
76848
|
}
|
|
76253
76849
|
}));
|
|
76850
|
+
const orderIndex = new Map(paths.map((p, i) => [p, i]));
|
|
76851
|
+
results.sort((a, b) => (orderIndex.get(a.path) ?? 0) - (orderIndex.get(b.path) ?? 0));
|
|
76852
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
76853
|
+
for (const { path, result } of results) {
|
|
76854
|
+
const ext = fileExtension$1(path);
|
|
76855
|
+
const group = grouped.get(ext) ?? [];
|
|
76856
|
+
group.push({
|
|
76857
|
+
path,
|
|
76858
|
+
result
|
|
76859
|
+
});
|
|
76860
|
+
grouped.set(ext, group);
|
|
76861
|
+
}
|
|
76862
|
+
const sortedExts = [...grouped.keys()].sort();
|
|
76254
76863
|
const parts = [];
|
|
76255
76864
|
let hasError = false;
|
|
76256
|
-
for (const
|
|
76865
|
+
for (const ext of sortedExts) {
|
|
76866
|
+
const group = grouped.get(ext);
|
|
76867
|
+
if (group === void 0) continue;
|
|
76257
76868
|
if (parts.length > 0) parts.push("");
|
|
76258
|
-
parts.push(
|
|
76259
|
-
|
|
76260
|
-
|
|
76261
|
-
|
|
76262
|
-
|
|
76869
|
+
parts.push(`── .${ext} (${String(group.length)}) ──`);
|
|
76870
|
+
for (const { path, result } of group) {
|
|
76871
|
+
parts.push("", `--- ${path} ---`);
|
|
76872
|
+
if (result.isError === true) {
|
|
76873
|
+
hasError = true;
|
|
76874
|
+
parts.push(`[ERROR] ${toolOutputText$1(result.output)}`);
|
|
76875
|
+
} else parts.push(toolOutputText$1(result.output));
|
|
76876
|
+
}
|
|
76877
|
+
}
|
|
76878
|
+
if (missingPaths.length > 0) parts.push("", `Skipped missing paths: ${missingPaths.join(", ")}`);
|
|
76879
|
+
const conflictNotices = results.map((r) => ({
|
|
76880
|
+
path: r.path,
|
|
76881
|
+
notice: conflictNoticeForReadResult(r.result)
|
|
76882
|
+
})).filter((r) => r.notice.length > 0);
|
|
76883
|
+
if (conflictNotices.length > 0) {
|
|
76884
|
+
const list = conflictNotices.map((r) => `${r.path}: ${r.notice}`).join("; ");
|
|
76885
|
+
parts.push("", `Conflict markers detected — ${list}`);
|
|
76886
|
+
}
|
|
76887
|
+
const importEdges = [];
|
|
76888
|
+
for (const { path, result } of results) {
|
|
76889
|
+
if (result.isError === true) continue;
|
|
76890
|
+
const ext = fileExtension$1(path);
|
|
76891
|
+
if (!IMPORTABLE_EXTENSIONS.has(ext)) continue;
|
|
76892
|
+
const targets = extractImportTargets(extractRawContentLines(result));
|
|
76893
|
+
if (targets.length > 0) {
|
|
76894
|
+
const base = path.split(/[\\/]/).at(-1) ?? path;
|
|
76895
|
+
importEdges.push(`${base} → ${targets.join(", ")}`);
|
|
76896
|
+
}
|
|
76897
|
+
}
|
|
76898
|
+
if (importEdges.length > 0) {
|
|
76899
|
+
const shown = importEdges.slice(0, MAX_IMPORT_EDGES);
|
|
76900
|
+
const more = importEdges.length > MAX_IMPORT_EDGES ? ` (+${String(importEdges.length - MAX_IMPORT_EDGES)} more)` : "";
|
|
76901
|
+
parts.push("", `Imports: ${shown.join("; ")}${more}`);
|
|
76263
76902
|
}
|
|
76264
76903
|
return {
|
|
76265
76904
|
isError: hasError,
|
|
@@ -76431,7 +77070,7 @@ var ReadMediaFileTool = class {
|
|
|
76431
77070
|
};
|
|
76432
77071
|
//#endregion
|
|
76433
77072
|
//#region ../../packages/agent-core/src/tools/builtin/file/write.md
|
|
76434
|
-
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.\n";
|
|
77073
|
+
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.\n";
|
|
76435
77074
|
//#endregion
|
|
76436
77075
|
//#region ../../packages/agent-core/src/tools/builtin/file/write.ts
|
|
76437
77076
|
/** Mask isolating the file-type bits of a stat mode. */
|
|
@@ -76449,12 +77088,14 @@ bytesWritten: z.number().int().nonnegative() });
|
|
|
76449
77088
|
var WriteTool = class {
|
|
76450
77089
|
jian;
|
|
76451
77090
|
workspace;
|
|
77091
|
+
lspRegistry;
|
|
76452
77092
|
name = "Write";
|
|
76453
77093
|
description = write_default;
|
|
76454
77094
|
parameters = toInputJsonSchema(WriteInputSchema);
|
|
76455
|
-
constructor(jian, workspace) {
|
|
77095
|
+
constructor(jian, workspace, lspRegistry) {
|
|
76456
77096
|
this.jian = jian;
|
|
76457
77097
|
this.workspace = workspace;
|
|
77098
|
+
this.lspRegistry = lspRegistry;
|
|
76458
77099
|
}
|
|
76459
77100
|
resolveExecution(args) {
|
|
76460
77101
|
const path = resolvePathAccessPath(args.path, {
|
|
@@ -76486,12 +77127,22 @@ var WriteTool = class {
|
|
|
76486
77127
|
isError: true,
|
|
76487
77128
|
output: parentError
|
|
76488
77129
|
};
|
|
77130
|
+
const contentBlocks = scanConflictLines(args.content.split("\n"));
|
|
77131
|
+
if (contentBlocks.length > 0) return {
|
|
77132
|
+
isError: true,
|
|
77133
|
+
output: `Content contains merge conflict markers (${contentBlocks.map((b) => `lines ${String(b.startLine)}-${String(b.endLine)}`).join(", ")}). Resolve the conflict before writing. Merge conflict markers (<<<<<<< / ======= / >>>>>>>) indicate an unresolved merge.`
|
|
77134
|
+
};
|
|
76489
77135
|
try {
|
|
76490
77136
|
const mode = args.mode ?? "overwrite";
|
|
76491
77137
|
if (mode === "append") await this.jian.writeText(safePath, args.content, { mode: "a" });
|
|
76492
77138
|
else await this.jian.writeText(safePath, args.content);
|
|
76493
77139
|
const bytesWritten = Buffer.byteLength(args.content, "utf8");
|
|
76494
|
-
|
|
77140
|
+
const { notice, hasErrors } = await this.appendDiagnostics(safePath);
|
|
77141
|
+
const output = `${mode === "append" ? "Appended" : "Wrote"} ${String(bytesWritten)} bytes to ${args.path}${notice}`;
|
|
77142
|
+
return hasErrors ? {
|
|
77143
|
+
isError: true,
|
|
77144
|
+
output
|
|
77145
|
+
} : { output };
|
|
76495
77146
|
} catch (error) {
|
|
76496
77147
|
if (error?.code === "ENOENT") return {
|
|
76497
77148
|
isError: true,
|
|
@@ -76524,6 +77175,13 @@ var WriteTool = class {
|
|
|
76524
77175
|
}
|
|
76525
77176
|
if ((stat.stMode & S_IFMT$2) !== S_IFDIR$1) return `Parent path is not a directory: ${parent}.`;
|
|
76526
77177
|
}
|
|
77178
|
+
async appendDiagnostics(safePath) {
|
|
77179
|
+
const result = await fetchDiagnostics(this.lspRegistry, this.jian, safePath, this.workspace.workspaceDir);
|
|
77180
|
+
return {
|
|
77181
|
+
notice: [formatDiagnosticsNotice(result), formatDiagnosticsHint(result)].filter((s) => s.length > 0).join(""),
|
|
77182
|
+
hasErrors: result.hasErrors
|
|
77183
|
+
};
|
|
77184
|
+
}
|
|
76527
77185
|
};
|
|
76528
77186
|
//#endregion
|
|
76529
77187
|
//#region ../../packages/agent-core/src/tools/builtin/planning/enter-plan-mode.md
|
|
@@ -76774,51 +77432,53 @@ function rejectDangerousCommand(pattern, hint) {
|
|
|
76774
77432
|
output: `Scream Code self-protection blocked this command.\n\nThe command matches a dangerous pattern (${pattern}) that could kill Scream Code's own process.\n\nInstead: ${hint}`
|
|
76775
77433
|
};
|
|
76776
77434
|
}
|
|
76777
|
-
const
|
|
77435
|
+
const BASH_INTERCEPTOR_RULES = [
|
|
77436
|
+
{
|
|
77437
|
+
pattern: /^\s*(cat|head|tail|less|more)\s+/i,
|
|
77438
|
+
tool: "Read",
|
|
77439
|
+
message: "Use the Read tool instead of cat/head/tail. It provides better context and handles binary files."
|
|
77440
|
+
},
|
|
76778
77441
|
{
|
|
76779
|
-
|
|
76780
|
-
|
|
76781
|
-
|
|
77442
|
+
pattern: /^\s*(grep|rg|ripgrep|ag|ack)\s+/i,
|
|
77443
|
+
tool: "Grep",
|
|
77444
|
+
message: "Use the Grep tool instead of grep/rg. It respects .gitignore and provides structured output."
|
|
76782
77445
|
},
|
|
76783
77446
|
{
|
|
76784
|
-
|
|
76785
|
-
|
|
76786
|
-
|
|
77447
|
+
pattern: /^\s*sed\s+(-i|--in-place)/i,
|
|
77448
|
+
tool: "Edit",
|
|
77449
|
+
message: "Use the Edit tool instead of sed -i. It provides diff preview and fuzzy matching."
|
|
76787
77450
|
},
|
|
76788
77451
|
{
|
|
76789
|
-
|
|
76790
|
-
|
|
76791
|
-
|
|
77452
|
+
pattern: /^\s*perl\s+.*-[pn]?i/i,
|
|
77453
|
+
tool: "Edit",
|
|
77454
|
+
message: "Use the Edit tool instead of perl -i. It provides diff preview and fuzzy matching."
|
|
76792
77455
|
},
|
|
76793
77456
|
{
|
|
76794
|
-
|
|
76795
|
-
|
|
76796
|
-
|
|
77457
|
+
pattern: /^\s*awk\s+.*-i\s+inplace/i,
|
|
77458
|
+
tool: "Edit",
|
|
77459
|
+
message: "Use the Edit tool instead of awk -i inplace. It provides diff preview and fuzzy matching."
|
|
76797
77460
|
},
|
|
76798
77461
|
{
|
|
76799
|
-
|
|
76800
|
-
|
|
76801
|
-
|
|
77462
|
+
pattern: /^\s*(echo|printf|cat\s*<<)\s+(?:[^"'>]|"[^"]*"|'[^']*')*(?<!\|)>{1,2}\|?\s*[$\w./~"'-]/i,
|
|
77463
|
+
tool: "Write",
|
|
77464
|
+
message: "Use the Write tool instead of echo/cat redirection. It handles encoding and provides confirmation."
|
|
76802
77465
|
}
|
|
76803
77466
|
];
|
|
76804
|
-
function
|
|
76805
|
-
for (const
|
|
76806
|
-
|
|
76807
|
-
|
|
76808
|
-
|
|
77467
|
+
function checkBashInterception(command, availableTools) {
|
|
77468
|
+
for (const rule of BASH_INTERCEPTOR_RULES) {
|
|
77469
|
+
if (!availableTools.has(rule.tool)) continue;
|
|
77470
|
+
if (rule.pattern.test(command)) return {
|
|
77471
|
+
isError: true,
|
|
77472
|
+
output: `Blocked: ${rule.message}\n\nOriginal command: ${command}`
|
|
77473
|
+
};
|
|
77474
|
+
}
|
|
76809
77475
|
return null;
|
|
76810
77476
|
}
|
|
76811
|
-
function looksLikeCommandNotFound(
|
|
77477
|
+
function looksLikeCommandNotFound(_command, output) {
|
|
76812
77478
|
const lowerOutput = output.toLowerCase();
|
|
76813
|
-
|
|
76814
|
-
|
|
76815
|
-
|
|
76816
|
-
function commandNotFoundHint(command) {
|
|
76817
|
-
const lower = command.toLowerCase();
|
|
76818
|
-
if (lower.includes("tsc") || lower.includes("typescript")) return "Hint: TypeScript compiler not found. Use `npx -p typescript tsc --noEmit` (or a project script such as `pnpm typecheck`) instead of calling `tsc` directly.";
|
|
76819
|
-
if (lower.includes("pnpm ")) return "Hint: Ensure pnpm is installed and you are in the project root. If the binary is missing, try `npm install` or use `corepack pnpm ...`.";
|
|
76820
|
-
if (lower.includes("cargo ")) return "Hint: Ensure Rust/Cargo is installed and you are in a crate workspace.";
|
|
76821
|
-
if (lower.includes("pytest ") || lower.includes("python ")) return "Hint: Ensure Python and the required packages are installed in the active environment.";
|
|
77479
|
+
return lowerOutput.includes("command not found") || lowerOutput.includes("not recognized as an internal or external command") || lowerOutput.includes("was not found") || lowerOutput.includes("cannot find");
|
|
77480
|
+
}
|
|
77481
|
+
function commandNotFoundHint() {
|
|
76822
77482
|
return "Hint: The command binary was not found. Check that the required toolchain is installed and use the project-specific script when available.";
|
|
76823
77483
|
}
|
|
76824
77484
|
function validateCommand(command, isWindows) {
|
|
@@ -76849,12 +77509,14 @@ var BashTool = class {
|
|
|
76849
77509
|
parameters = toInputJsonSchema(BashInputSchema);
|
|
76850
77510
|
isWindowsBash;
|
|
76851
77511
|
allowBackground;
|
|
77512
|
+
availableTools;
|
|
76852
77513
|
constructor(jian, cwd, backgroundManager, options) {
|
|
76853
77514
|
this.jian = jian;
|
|
76854
77515
|
this.cwd = cwd;
|
|
76855
77516
|
this.backgroundManager = backgroundManager;
|
|
76856
77517
|
this.isWindowsBash = this.jian.osEnv.osKind === "Windows";
|
|
76857
77518
|
this.allowBackground = options?.allowBackground ?? this.backgroundManager !== void 0;
|
|
77519
|
+
this.availableTools = options?.availableTools ?? /* @__PURE__ */ new Set();
|
|
76858
77520
|
const rendered = renderBashDescription(this.jian.osEnv.shellName);
|
|
76859
77521
|
this.description = this.allowBackground ? rendered : withoutBackgroundDescription(rendered);
|
|
76860
77522
|
}
|
|
@@ -76902,8 +77564,8 @@ var BashTool = class {
|
|
|
76902
77564
|
};
|
|
76903
77565
|
const validationError = validateCommand(args.command, this.isWindowsBash);
|
|
76904
77566
|
if (validationError !== null) return validationError;
|
|
76905
|
-
const
|
|
76906
|
-
if (
|
|
77567
|
+
const interception = checkBashInterception(args.command, this.availableTools);
|
|
77568
|
+
if (interception !== null) return interception;
|
|
76907
77569
|
if (args.run_in_background) {
|
|
76908
77570
|
if (!this.allowBackground) return {
|
|
76909
77571
|
isError: true,
|
|
@@ -76970,7 +77632,7 @@ var BashTool = class {
|
|
|
76970
77632
|
const isError = exitCode !== 0;
|
|
76971
77633
|
if (isError && builder.nChars === 0) builder.write(`Process exited with code ${String(exitCode)}`);
|
|
76972
77634
|
if (!isError) return builder.ok("Command executed successfully.");
|
|
76973
|
-
const hint = looksLikeCommandNotFound(command, builder.toString()) ? `\\n${commandNotFoundHint(
|
|
77635
|
+
const hint = looksLikeCommandNotFound(command, builder.toString()) ? `\\n${commandNotFoundHint()}` : "";
|
|
76974
77636
|
return builder.error(`Command failed with exit code: ${String(exitCode)}.${hint}`, { brief: `Failed with exit code: ${String(exitCode)}` });
|
|
76975
77637
|
} catch (error) {
|
|
76976
77638
|
return {
|
|
@@ -78266,6 +78928,84 @@ function extractCompactionSummary(response) {
|
|
|
78266
78928
|
}
|
|
78267
78929
|
const COMPACTION_INSTRUCTION = (customInstruction = "") => renderPrompt(compaction_instruction_default, { customInstruction });
|
|
78268
78930
|
//#endregion
|
|
78931
|
+
//#region ../../packages/agent-core/src/flags/registry.ts
|
|
78932
|
+
/**
|
|
78933
|
+
* Experimental feature flags. Empty by default — there are no experimental features yet.
|
|
78934
|
+
*
|
|
78935
|
+
* To add one, append an entry and gate the feature with `flags.enabled('my-feature')`:
|
|
78936
|
+
* { id: 'my-feature', env: 'SCREAM_CODE_EXPERIMENTAL_MY_FEATURE', default: false, surface: 'both' }
|
|
78937
|
+
*
|
|
78938
|
+
* Keep the `as const satisfies` — it derives the literal `FlagId` union that gives `enabled()`
|
|
78939
|
+
* autocomplete and typo-checking. `env` must start with 'SCREAM_CODE_EXPERIMENTAL_', be unique, and
|
|
78940
|
+
* not equal the master switch 'SCREAM_CODE_EXPERIMENTAL_FLAG'; `id` must not be 'flag'.
|
|
78941
|
+
*/
|
|
78942
|
+
const FLAG_DEFINITIONS = [{
|
|
78943
|
+
id: "micro-compaction",
|
|
78944
|
+
env: "SCREAM_CODE_EXPERIMENTAL_MICRO_COMPACTION",
|
|
78945
|
+
default: true,
|
|
78946
|
+
surface: "both"
|
|
78947
|
+
}, {
|
|
78948
|
+
id: "wolfpack",
|
|
78949
|
+
env: "SCREAM_CODE_EXPERIMENTAL_WOLFPACK",
|
|
78950
|
+
default: false,
|
|
78951
|
+
surface: "both"
|
|
78952
|
+
}];
|
|
78953
|
+
//#endregion
|
|
78954
|
+
//#region ../../packages/agent-core/src/config/resolve.ts
|
|
78955
|
+
const TRUE_BOOLEAN_ENV_VALUES = new Set([
|
|
78956
|
+
"1",
|
|
78957
|
+
"true",
|
|
78958
|
+
"yes",
|
|
78959
|
+
"on"
|
|
78960
|
+
]);
|
|
78961
|
+
const FALSE_BOOLEAN_ENV_VALUES = new Set([
|
|
78962
|
+
"0",
|
|
78963
|
+
"false",
|
|
78964
|
+
"no",
|
|
78965
|
+
"off"
|
|
78966
|
+
]);
|
|
78967
|
+
function resolveConfigValue(input) {
|
|
78968
|
+
return input.parseEnv(input.env?.[input.envKey]) ?? input.configValue ?? input.defaultValue;
|
|
78969
|
+
}
|
|
78970
|
+
function parseBooleanEnv(value) {
|
|
78971
|
+
const normalized = value?.trim().toLowerCase();
|
|
78972
|
+
if (normalized === void 0 || normalized.length === 0) return void 0;
|
|
78973
|
+
if (TRUE_BOOLEAN_ENV_VALUES.has(normalized)) return true;
|
|
78974
|
+
if (FALSE_BOOLEAN_ENV_VALUES.has(normalized)) return false;
|
|
78975
|
+
}
|
|
78976
|
+
/**
|
|
78977
|
+
* Pure, synchronous flag resolver. State comes entirely from (env, registry) and nothing is
|
|
78978
|
+
* cached: env is read live on every call, so a single shared instance always reflects the current
|
|
78979
|
+
* process env. Defaults to process.env + FLAG_DEFINITIONS; tests can inject a custom env / defs.
|
|
78980
|
+
*
|
|
78981
|
+
* Precedence (highest wins):
|
|
78982
|
+
* L1 master switch SCREAM_CODE_EXPERIMENTAL_FLAG → every flag is on
|
|
78983
|
+
* L2 per-feature def.env (parseBooleanEnv, may force on or off)
|
|
78984
|
+
* L3 registry default
|
|
78985
|
+
*/
|
|
78986
|
+
var FlagResolver = class {
|
|
78987
|
+
env;
|
|
78988
|
+
byId;
|
|
78989
|
+
constructor(env = process.env, definitions = FLAG_DEFINITIONS) {
|
|
78990
|
+
this.env = env;
|
|
78991
|
+
this.byId = new Map(definitions.map((def) => [def.id, def]));
|
|
78992
|
+
}
|
|
78993
|
+
enabled(id) {
|
|
78994
|
+
const def = this.byId.get(id);
|
|
78995
|
+
if (def === void 0) return false;
|
|
78996
|
+
if (parseBooleanEnv(this.env["SCREAM_CODE_EXPERIMENTAL_FLAG"]) === true) return true;
|
|
78997
|
+
const override = parseBooleanEnv(this.env[def.env]);
|
|
78998
|
+
if (override !== void 0) return override;
|
|
78999
|
+
return def.default;
|
|
79000
|
+
}
|
|
79001
|
+
};
|
|
79002
|
+
/**
|
|
79003
|
+
* Process-global flag accessor. Flags are env-driven and process-global, so a single shared
|
|
79004
|
+
* instance (reading live process.env) is the canonical way to consult them — import this directly
|
|
79005
|
+
* rather than constructing or injecting a resolver.
|
|
79006
|
+
*/
|
|
79007
|
+
const flags = new FlagResolver();
|
|
79008
|
+
//#endregion
|
|
78269
79009
|
//#region ../../packages/agent-core/src/agent/compaction/micro.ts
|
|
78270
79010
|
const DEFAULT_CONFIG = {
|
|
78271
79011
|
keepRecentMessages: 20,
|
|
@@ -78336,6 +79076,7 @@ var MicroCompaction = class {
|
|
|
78336
79076
|
}
|
|
78337
79077
|
/** Check whether micro-compaction is warranted and advance the cutoff. */
|
|
78338
79078
|
detect() {
|
|
79079
|
+
if (!flags.enabled("micro-compaction")) return;
|
|
78339
79080
|
const config = this.config;
|
|
78340
79081
|
const { history } = this.agent.context;
|
|
78341
79082
|
const maxContextTokens = this.agent.config.modelCapabilities.max_context_tokens;
|
|
@@ -80512,7 +81253,7 @@ const WOLFPACK_MODE_ENTER_REMINDER = [
|
|
|
80512
81253
|
"",
|
|
80513
81254
|
"This spawns one subagent per item in parallel. Results are batched and returned together.",
|
|
80514
81255
|
"Items must be independent — do not use WolfPack when one item depends on another's output.",
|
|
80515
|
-
"
|
|
81256
|
+
"There is no item limit; use as many items as needed."
|
|
80516
81257
|
].join("\n");
|
|
80517
81258
|
const WOLFPACK_MODE_EXIT_REMINDER = "WolfPack mode is no longer active. The WolfPack tool for batch parallel execution is no longer available.";
|
|
80518
81259
|
var WolfPackModeInjector = class extends DynamicInjector {
|
|
@@ -95235,7 +95976,7 @@ const PROFILE_SOURCES = {
|
|
|
95235
95976
|
"profile/default/oracle.yaml": "extends: agent\nname: oracle\npromptVars:\n roleAdditional: |\n You are now running as a sub-agent. All `user` messages are sent by the main agent.\n You are the Oracle sub-agent. Your role is deep debugging, architecture decisions,\n and second opinions.\n\n # Behavior\n\n - Investigate root causes, not symptoms.\n - Ask clarifying questions only when the premise is genuinely ambiguous.\n - Return concise, evidence-based conclusions with concrete file paths and line numbers.\n - Do NOT implement fixes unless explicitly asked to do so.\n - Do NOT run project-wide verification, lint, or format unless explicitly asked.\n - Do NOT ask the end user questions.\n\n # Output format\n\n When the task is complete, return:\n 1. A one-sentence verdict.\n 2. The key evidence (file paths, line numbers, command output, or URLs).\n 3. The recommended next step for the parent agent.\nwhenToUse: |\n Use when the main agent is stuck on a complex bug, needs an architecture trade-off,\n or wants a second opinion before a risky change.\ntools:\n - Bash\n - Read\n - ReadMediaFile\n - Glob\n - Grep\n - Write\n - Edit\n - WebSearch\n - FetchURL\n - MemoryLookup\n - MemoryConsolidatePlan\n - MemoryConsolidateApply\n - mcp__*\n",
|
|
95236
95977
|
"profile/default/plan.yaml": "extends: agent\nname: plan\npromptVars:\n roleAdditional: |\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.\n\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:\n 1. What you already know from the information provided\n 2. What questions remain unanswered that would benefit from explore agent investigation\n 3. Your implementation plan (either preliminary if questions remain, or final if sufficient context exists)\nwhenToUse: |\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.\ntools:\n - Read\n - ReadMediaFile\n - Glob\n - Grep\n - WebSearch\n - MemoryLookup\n - MemoryConsolidatePlan\n - MemoryConsolidateApply\n - FetchURL\n",
|
|
95237
95978
|
"profile/default/reviewer.yaml": "extends: agent\nname: reviewer\npromptVars:\n roleAdditional: |\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.\n\n You are a code review specialist. Your job is to identify bugs the author would want fixed before merge.\n\n # Procedure\n\n 1. Run `git diff`, `jj diff --git`, or read modified files to view the patch.\n 2. Read modified files for full context.\n 3. Call `ReportFinding` for each issue you identify.\n 4. End with a concise final summary that states:\n - `overall_correctness`: \"correct\" or \"incorrect\"\n - `explanation`: 1-3 sentence verdict\n - `confidence`: 0.0-1.0\n\n You NEVER make file edits or trigger builds. Bash is read-only: `git diff`, `git log`, `git show`, `jj diff --git`.\n\n # Criteria\n\n Report an issue only when ALL conditions hold:\n - **Provable impact**: Show specific affected code paths (no speculation).\n - **Actionable**: Discrete fix, not vague \"consider improving X\".\n - **Unintentional**: Clearly not a deliberate design choice.\n - **Introduced in patch**: Do not flag pre-existing bugs unless asked.\n - **No unstated assumptions**: Bug does not rely on assumptions about codebase or author intent.\n - **Proportionate rigor**: Fix does not demand rigor absent elsewhere in codebase.\n\n # Cross-boundary checks\n\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):\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.\n 2. Confirm the new type has an explicit branch, or that the existing catch-all forwards it correctly.\n 3. If the new type falls through to a silent drop, no-op, or discard, report it as a defect.\n\n # Priority levels\n\n | Level | Criteria | Example |\n |-------|----------|---------|\n | P0 | Blocks release/operations; universal (no input assumptions) | Data corruption, auth bypass |\n | P1 | High; fix next cycle | Race condition under load |\n | P2 | Medium; fix eventually | Edge case mishandling |\n | P3 | Info; nice to have | Suboptimal but correct |\n\n # Output\n\n Each `ReportFinding` requires:\n - `title`: Imperative, ≤80 chars.\n - `body`: One paragraph — bug, trigger, impact.\n - `priority`: P0, P1, P2, or P3.\n - `confidence`: 0.0-1.0.\n - `file_path`: Path to affected file.\n - `line_start`, `line_end`: Range ≤10 lines, must overlap the diff.\n\n Final summary format:\n ```\n Review verdict: incorrect\n Confidence: 0.85\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.\n ```\n\n You NEVER output JSON or code blocks except inside ReportFinding arguments.\n\n Correctness ignores non-blocking issues (style, docs, nits).\nwhenToUse: |\n Code review specialist. Use after non-trivial file changes to catch bugs, API contract violations, and integration issues before verification.\ntools:\n - Bash\n - Read\n - Grep\n - Glob\n - LSP\n - ReportFinding\n - MemoryLookup\n - MemoryConsolidatePlan\n - MemoryConsolidateApply\n - mcp__*\n",
|
|
95238
|
-
"profile/default/system.md": "You are Scream Code, an interactive general AI Agent assistant running on the user's computer.\n\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.\n\n{{ ROLE_ADDITIONAL }}\n\n# Prompt and Tool Use\n\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.\n\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.\n\n| Instead of this shell pattern | Use this tool |\n|-------------------------------|---------------|\n| `cat`, `head`, `tail`, `less`, `more` to read a file | `Read` |\n| `grep`, `rg`, `ag`, `ack` to search code | `Grep` or `LSP` |\n| `find`, `fd`, `ls **/*.ext` to list files | `Glob` |\n| `sed -i`, `perl -i`, `awk` to edit files | `Edit` |\n| `echo ... > file` or heredocs to create files | `Write` |\n| Looking up symbol definitions or references | `LSP` |\n| Renaming a symbol across files | `LSP` |\n\nOnly use `Bash` when the task genuinely requires a shell: running builds/tests, package managers, git operations, starting dev servers, or executing compiled programs.\n\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.\n\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.\n\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.\n\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.\n\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.\n\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.\n\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.\n\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).\n\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.\n\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.\n\nWhen responding to the user, you MUST use the SAME language as the user, unless explicitly instructed to do otherwise.\n\n\n# Available Subagents\n\nWhen delegating with the `Agent` tool, choose the appropriate `subagent_type`:\n\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.\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.\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.\n- `verify` — Verification specialist. Runs build, test, and lint commands. Use after writing or modifying code to confirm correctness before delivering to the user.\n- `reviewer` — Code review specialist. Identifies bugs and API contract violations before merge.\n- `writer` — Content production and research specialist. Produces structured, data-driven reports, analyses, and Markdown documents.\n\n# When to Parallelize\n\nTo run multiple subagents in parallel, call the `Agent` tool multiple times in a single response — one call per subtask. All calls execute concurrently.\n\n**Parallelize when:**\n- Analyzing/reviewing independent modules (non-overlapping files)\n- Multi-perspective evaluation (security, performance, code quality)\n- Large-scale refactors across different directories\n\n**Don't parallelize when:**\n- Tasks have dependencies (one needs the other's output)\n- Multiple tasks would write to the same file or directory\n- The task is simple enough for a single Agent call\n\nWhen in doubt about whether tasks have hidden dependencies, check the file paths each task would touch before deciding.\n\n# Verification Protocol\n\nVerification is **optional by default**. Do not treat it as a mandatory post-change ritual.\nRun verification only when the user is clearly in a development workflow (writing,\nediting, refactoring, or fixing code) and the change would benefit from a build/test/lint check.\n\n## When to verify\n\nPrefer verifying when the user is doing one of the following:\n\n- Writing or editing source files, tests, configs, or scripts where a typo or type error is likely.\n- Refactoring, migrating, or making non-trivial multi-file changes.\n- Fixing a bug and a relevant test/build command exists.\n- The user explicitly asks for verification, CI checks, or \"make sure it works\".\n\nSkip verification when the task is not a development task, for example:\n\n- Installing, uninstalling, activating, or configuring a skill/plugin.\n- Changing settings, model, permission mode, or theme.\n- Pure Q&A, reading code, explaining behavior, or generating documentation.\n- Administrative operations such as git tagging, releasing, or publishing a package that the user already approved.\n\n## How to decide\n\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.\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.\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.\n4. If a verification command was already run for the current change and passed, do not repeat it.\n5. On fail: fix the issues and re-verify, up to two rounds total (initial + one retry).\n6. Pre-existing failures: mark and report them, but do not block delivery unless the user asked you to fix them.\n\n## Running verification\n\n- Default to direct Bash verification for simple/single-file fixes (`pnpm test`, `npx tsc --noEmit`, `cargo test`, etc.).\n- Use the `verify` subagent (`Agent(subagent_type=\"verify\", prompt=\"...\")`) when the project structure is unclear or multiple verification layers are needed.\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.\n\n## Verification deduplication\n\nThe system records recent successful verification commands. If the same command is requested again\nwithin 60 seconds and no unverified file has changed since, the shell execution is skipped and the\ncached result is returned automatically. Do not request the same verification command repeatedly.\n\nThe correct tool to spawn a subagent is `Agent`, not `spawn_agent`. Use\n`Agent(subagent_type=\"verify\", prompt=\"...\")` when you choose to delegate verification.\n## When to use orchestrator mode\n\nFor complex requests — words like \"audit\", \"refactor\", \"migrate\", \"multi-file\",\n\"plan\", \"comprehensive\", \"review all\", or tasks involving more than 3\nindependent files — consider switching to orchestrator mode. Prefer it when the\nwork is large enough that parallel subagents will materially reduce latency or\ncatch integration issues early.\n\nIn orchestrator mode:\n- You do not edit files yourself.\n- You decompose the work into discrete subtasks.\n- You spawn specialized subagents via the `Agent` tool in parallel.\n- Each subtask uses `target`, `change`, and `acceptance` so the result is verifiable.\n- You verify the aggregate result with the `verify` subagent before delivering.\n- You produce a final summary that synthesizes all subagent outputs.\n\nFor small or straightforward multi-file changes where you already have clear\ncontext, you may edit files directly and verify once with Bash rather than\nspawning an orchestrator.\n\n# Review Protocol\n\nCode review is **optional by default**. Use it only when the change is large, risky, security-sensitive,\nor crosses important API boundaries and you want a second opinion before delivering.\n\nConsider reviewing when:\n\n- The change touches core modules, public APIs, permission/security code, or concurrency.\n- Tests fail unexpectedly, behavior is subtle, or the fix is a workaround.\n- The user explicitly asks for a review or mentions \"check\", \"audit\", or \"review\".\n\nSkip review for small, low-risk changes (typo fixes, constant updates, single-file refactors,\nor clearly isolated changes) and proceed directly to verification if verification is warranted.\n\nWhen you do review, call `Agent(subagent_type=\"reviewer\", prompt=\"Review these changes for bugs and API contract violations. Modified files: <list>\")`.\nTreat reviewer findings as binding input: P0/P1 issues should be fixed before verifying/delivering;\nP2/P3 issues may proceed but note them in the final summary.\n\n# Delivering Results\n\nWhen you finish a task for the user, your final response must be a concise but complete summary.\nDo not end with only \"done\", \"ok\", \"完成\", \"好了\", or similarly empty acknowledgments.\n\nFor tasks that involved file changes:\n\n1. **What was done** — a one-sentence verdict.\n2. **Files changed** — the specific files or directories you touched.\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.\n4. **Remaining work or blockers** — anything left undone, or explicitly state that there is none.\n\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.\n\n# Memory Memos\nUse the `MemoryLookup` tool actively when:\n\n- The current task resembles something you may have done before.\n- You encounter a recurring error, pattern, or ambiguity.\n- You are unsure which approach is most likely to succeed.\n- The user refers to a previous fix, decision, or project convention.\n\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.\n\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.\n\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`:\n\"保存到记忆\", \"保存到备忘录\", \"总结并保存\", \"永久记忆\", \"记录我的记忆\", \"记住这个\", \"记一下\", \"添加到记忆\", \"写入记忆\", \"存入记忆库\", \"帮我记下来\", \"作为经验保存\", \"记录这次经验\", \"加入备忘录\", \"归档\", \"记住这次\", \"以后记得\", \"保存下来\".\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.\n\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.\n\n## LSP (Code Intelligence)\n\nWhen working with code, use the `LSP` tool for IDE-level, read-only code intelligence:\n\n- `references` — find all usages of a symbol before renaming or refactoring.\n- `definition` — jump to where a symbol is defined.\n- `diagnostics` — see type errors and warnings for a file.\n\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.\n\n# General Guidelines for Coding\n\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.\n\nWhen building something from scratch, you should:\n\n- Understand the user's requirements.\n- Ask the user for clarification if there is anything unclear.\n- Design the architecture and make a plan for the implementation.\n- Write the code in a modular and maintainable way.\n\nAlways use tools to implement your code changes:\n\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.\n- Use `Bash` to run and test your code after writing it.\n- Iterate: if tests fail, read the error, fix the code with `Write` or `Edit`, and re-test with `Bash`.\n\nWhen working on an existing codebase, you should:\n\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.\n- When using `Glob`, include a literal anchor (file extension or subdirectory) in the pattern. Pure wildcards like `*` or `**/*` are rejected by the tool.\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.\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.\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.\n- Make MINIMAL changes to achieve the goal. This is very important to your performance.\n- Follow the coding style of existing code in the project.\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.\n\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.\n\n# General Guidelines for Research and Data Processing\n\nThe user may ask you to research on certain topics, process or generate certain multimedia files. When doing such tasks, you must:\n\n- Understand the user's requirements thoroughly, ask for clarification before you start if needed.\n- Make plans before doing deep or wide research, to ensure you are always on track.\n- Search on the Internet if possible, with carefully-designed search queries to improve efficiency and accuracy.\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.\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.\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.\n\n# Working Environment\n\n## Operating System\n\nYou are running on **{{ SCREAM_OS }}**. The Bash tool executes commands using **{{ SCREAM_SHELL }}**.\n{% if SCREAM_OS == \"Windows\" %}\n\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.\n{% endif %}\n\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.\n\n## Date and Time\n\nThe current date and time in ISO format is `{{ SCREAM_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.\n\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.\n\n## Working Directory\n\nThe current working directory is `{{ SCREAM_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.\n\nThe directory listing of current working directory is:\n\n```\n{{ SCREAM_WORK_DIR_LS }}\n```\n\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.\n{% if SCREAM_ADDITIONAL_DIRS_INFO %}\n\n## Additional Directories\n\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.\n\n{{ SCREAM_ADDITIONAL_DIRS_INFO }}\n{% endif %}\n\n# Project Information\n\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.\n\n> Why `AGENTS.md`?\n>\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.\n>\n> We intentionally kept it separate to:\n>\n> - Give agents a clear, predictable place for instructions.\n> - Keep `README`s concise and focused on human contributors.\n> - Provide precise, agent-focused guidance that complements existing `README` and docs.\n\nThe `AGENTS.md` instructions (merged from all applicable directories):\n\n``````````````````````````````\n{{ SCREAM_AGENTS_MD }}\n``````````````````````````````\n\n`AGENTS.md` files can appear at any level of the project directory tree, including inside `.scream-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.\n\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.\n\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.\n\n# Skills\n\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.\n\n## What are skills?\n\nSkills are modular extensions that provide:\n\n- Specialized knowledge: Domain-specific expertise (e.g., PDF processing, data analysis)\n- Workflow patterns: Best practices for common tasks\n- Tool integrations: Pre-configured tool chains for specific tasks\n- Reference material: Documentation, templates, and examples\n\n## Available skills\n\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**.\n\n{{ SCREAM_SKILLS }}\n\n## How to use skills\n\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.\n\nOnly read skill details when needed to conserve the context window.\n\n# CONTRACT\n\nThese rules are inviolable.\n\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.\n- You NEVER suppress tests to make code pass.\n- You NEVER fabricate outputs that were not observed. Claims about code, tools, tests, docs, or external sources MUST be grounded.\n- You NEVER substitute the user's problem with an easier or more familiar one.\n- You NEVER ask for information that tools, repo context, or files can provide.\n- NEVER punt half-solved work back.\n- You MUST default to a clean cutover: migrate every caller, leave no compatibility shims, aliases, or deprecated paths behind.\n- Be brief in prose, not in evidence, verification, or blocking details.\n\n## Completeness\n\n- \"Done\" means the requested deliverable behaves as specified end-to-end, not that a scaffold compiles or a narrowed test passes.\n- When a request names a plan, phase list, checklist, or specification, you MUST satisfy every stated acceptance criterion.\n- You NEVER silently shrink scope.\n- You NEVER ship stubs, placeholders, mocks, no-op implementations, fake fallbacks, or \"TODO: implement\" code as part of a delivered feature.\n- Verification claims MUST match what was actually exercised.\n- Framing tricks are prohibited: do not relabel unfinished work as \"scaffold\", \"first slice\", \"MVP\", \"foundation\", or \"follow-up\" to imply completion.\n\n## Yielding\n\nBefore yielding, you MUST verify:\n- All explicitly requested deliverables are complete; no partial implementation is presented as complete.\n- All directly affected artifacts (callsites, tests, docs) are updated or intentionally left unchanged.\n- The output format matches the ask.\n- No unobserved claim is presented as fact.\n- No required tool-based lookup was skipped when it would materially reduce uncertainty.\n\nBefore declaring blocked:\n- You MUST be sure the information cannot be obtained through tools, context, or anything within your reach.\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.\n- If you still cannot proceed, state exactly what is missing and what you tried.\n",
|
|
95979
|
+
"profile/default/system.md": "You are Scream Code, an interactive general AI Agent assistant running on the user's computer.\n\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.\n\n{{ ROLE_ADDITIONAL }}\n\n# Prompt and Tool Use\n\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.\n\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.\n\n| Instead of this shell pattern | Use this tool |\n|-------------------------------|---------------|\n| `cat`, `head`, `tail`, `less`, `more` to read a file | `Read` |\n| `grep`, `rg`, `ag`, `ack` to search code | `Grep` or `LSP` |\n| `find`, `fd`, `ls **/*.ext` to list files | `Glob` |\n| `sed -i`, `perl -i`, `awk` to edit files | `Edit` |\n| `echo ... > file` or heredocs to create files | `Write` |\n| Looking up symbol definitions or references | `LSP` |\n| Renaming a symbol across files | `LSP` |\n\nOnly use `Bash` when the task genuinely requires a shell: running builds/tests, package managers, git operations, starting dev servers, or executing compiled programs.\n\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.\n\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.\n\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.\n\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.\n\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.\n\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.\n\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.\n\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.\n\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).\n\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.\n\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.\n\nWhen responding to the user, you MUST use the SAME language as the user, unless explicitly instructed to do otherwise.\n\n\n# Available Subagents\n\nWhen delegating with the `Agent` tool, choose the appropriate `subagent_type`:\n\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.\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.\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.\n- `verify` — Verification specialist. Runs build, test, and lint commands. Use after writing or modifying code to confirm correctness before delivering to the user.\n- `reviewer` — Code review specialist. Identifies bugs and API contract violations before merge.\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.\n- `writer` — Content production and research specialist. Produces structured, data-driven reports, analyses, and Markdown documents.\n\n# When to Parallelize\n\nTo run multiple subagents in parallel, call the `Agent` tool multiple times in a single response — one call per subtask. All calls execute concurrently.\n\n**Parallelize when:**\n- Analyzing/reviewing independent modules (non-overlapping files)\n- Multi-perspective evaluation (security, performance, code quality)\n- Large-scale refactors across different directories\n\n**Don't parallelize when:**\n- Tasks have dependencies (one needs the other's output)\n- Multiple tasks would write to the same file or directory\n- The task is simple enough for a single Agent call\n\n# WolfPack (`WolfPack` tool)\n\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:\n\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).\n- All items should use the **same `subagent_type`**.\n- Items have no inter-dependency.\n\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.\n\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`.\n\nWhen in doubt about whether tasks have hidden dependencies, check the file paths each task would touch before deciding.\n\n# Verification Protocol\n\nVerification is **optional by default**. Do not treat it as a mandatory post-change ritual.\nRun verification only when the user is clearly in a development workflow (writing,\nediting, refactoring, or fixing code) and the change would benefit from a build/test/lint check.\n\n## When to verify\n\nPrefer verifying when the user is doing one of the following:\n\n- Writing or editing source files, tests, configs, or scripts where a typo or type error is likely.\n- Refactoring, migrating, or making non-trivial multi-file changes.\n- Fixing a bug and a relevant test/build command exists.\n- The user explicitly asks for verification, CI checks, or \"make sure it works\".\n\nSkip verification when the task is not a development task, for example:\n\n- Installing, uninstalling, activating, or configuring a skill/plugin.\n- Changing settings, model, permission mode, or theme.\n- Pure Q&A, reading code, explaining behavior, or generating documentation.\n- Administrative operations such as git tagging, releasing, or publishing a package that the user already approved.\n\n## How to decide\n\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.\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.\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.\n4. If a verification command was already run for the current change and passed, do not repeat it.\n5. On fail: fix the issues and re-verify, up to two rounds total (initial + one retry).\n6. Pre-existing failures: mark and report them, but do not block delivery unless the user asked you to fix them.\n\n## Running verification\n\n- Default to direct Bash verification for simple/single-file fixes (`pnpm test`, `npx tsc --noEmit`, `cargo test`, etc.).\n- Use the `verify` subagent (`Agent(subagent_type=\"verify\", prompt=\"...\")`) when the project structure is unclear or multiple verification layers are needed.\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.\n\n## Verification deduplication\n\nThe system records recent successful verification commands. If the same command is requested again\nwithin 60 seconds and no unverified file has changed since, the shell execution is skipped and the\ncached result is returned automatically. Do not request the same verification command repeatedly.\n\nThe correct tool to spawn a subagent is `Agent`, not `spawn_agent`. Use\n`Agent(subagent_type=\"verify\", prompt=\"...\")` when you choose to delegate verification.\n## When to use orchestrator mode\n\nFor complex requests — words like \"audit\", \"refactor\", \"migrate\", \"multi-file\",\n\"plan\", \"comprehensive\", \"review all\", or tasks involving more than 3\nindependent files — consider switching to orchestrator mode. Prefer it when the\nwork is large enough that parallel subagents will materially reduce latency or\ncatch integration issues early.\n\nIn orchestrator mode:\n- You do not edit files yourself.\n- You decompose the work into discrete subtasks.\n- You spawn specialized subagents via the `Agent` tool in parallel.\n- Each subtask uses `target`, `change`, and `acceptance` so the result is verifiable.\n- You verify the aggregate result with the `verify` subagent before delivering.\n- You produce a final summary that synthesizes all subagent outputs.\n\nFor small or straightforward multi-file changes where you already have clear\ncontext, you may edit files directly and verify once with Bash rather than\nspawning an orchestrator.\n\n# Review Protocol\n\nCode review is **optional by default**. Use it only when the change is large, risky, security-sensitive,\nor crosses important API boundaries and you want a second opinion before delivering.\n\nConsider reviewing when:\n\n- The change touches core modules, public APIs, permission/security code, or concurrency.\n- Tests fail unexpectedly, behavior is subtle, or the fix is a workaround.\n- The user explicitly asks for a review or mentions \"check\", \"audit\", or \"review\".\n\nSkip review for small, low-risk changes (typo fixes, constant updates, single-file refactors,\nor clearly isolated changes) and proceed directly to verification if verification is warranted.\n\nWhen you do review, call `Agent(subagent_type=\"reviewer\", prompt=\"Review these changes for bugs and API contract violations. Modified files: <list>\")`.\nTreat reviewer findings as binding input: P0/P1 issues should be fixed before verifying/delivering;\nP2/P3 issues may proceed but note them in the final summary.\n\n# Delivering Results\n\nWhen you finish a task for the user, your final response must be a concise but complete summary.\nDo not end with only \"done\", \"ok\", \"完成\", \"好了\", or similarly empty acknowledgments.\n\nFor tasks that involved file changes:\n\n1. **What was done** — a one-sentence verdict.\n2. **Files changed** — the specific files or directories you touched.\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.\n4. **Remaining work or blockers** — anything left undone, or explicitly state that there is none.\n\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.\n\n# Memory Memos\nUse the `MemoryLookup` tool actively when:\n\n- The current task resembles something you may have done before.\n- You encounter a recurring error, pattern, or ambiguity.\n- You are unsure which approach is most likely to succeed.\n- The user refers to a previous fix, decision, or project convention.\n\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.\n\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.\n\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`:\n\"保存到记忆\", \"保存到备忘录\", \"总结并保存\", \"永久记忆\", \"记录我的记忆\", \"记住这个\", \"记一下\", \"添加到记忆\", \"写入记忆\", \"存入记忆库\", \"帮我记下来\", \"作为经验保存\", \"记录这次经验\", \"加入备忘录\", \"归档\", \"记住这次\", \"以后记得\", \"保存下来\".\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.\n\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.\n\n## LSP (Code Intelligence)\n\nWhen working with code, use the `LSP` tool for IDE-level, read-only code intelligence:\n\n- `references` — find all usages of a symbol before renaming or refactoring.\n- `definition` — jump to where a symbol is defined.\n- `diagnostics` — see type errors and warnings for a file.\n\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.\n\n# General Guidelines for Coding\n\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.\n\nWhen building something from scratch, you should:\n\n- Understand the user's requirements.\n- Ask the user for clarification if there is anything unclear.\n- Design the architecture and make a plan for the implementation.\n- Write the code in a modular and maintainable way.\n\nAlways use tools to implement your code changes:\n\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.\n- Use `Bash` to run and test your code after writing it.\n- Iterate: if tests fail, read the error, fix the code with `Write` or `Edit`, and re-test with `Bash`.\n\nWhen working on an existing codebase, you should:\n\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.\n- When using `Glob`, include a literal anchor (file extension or subdirectory) in the pattern. Pure wildcards like `*` or `**/*` are rejected by the tool.\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.\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.\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.\n- Make MINIMAL changes to achieve the goal. This is very important to your performance.\n- Follow the coding style of existing code in the project.\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.\n\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.\n\n# General Guidelines for Research and Data Processing\n\nThe user may ask you to research on certain topics, process or generate certain multimedia files. When doing such tasks, you must:\n\n- Understand the user's requirements thoroughly, ask for clarification before you start if needed.\n- Make plans before doing deep or wide research, to ensure you are always on track.\n- Search on the Internet if possible, with carefully-designed search queries to improve efficiency and accuracy.\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.\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.\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.\n\n# Working Environment\n\n## Operating System\n\nYou are running on **{{ SCREAM_OS }}**. The Bash tool executes commands using **{{ SCREAM_SHELL }}**.\n{% if SCREAM_OS == \"Windows\" %}\n\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.\n{% endif %}\n\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.\n\n## Date and Time\n\nThe current date and time in ISO format is `{{ SCREAM_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.\n\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.\n\n## Working Directory\n\nThe current working directory is `{{ SCREAM_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.\n\nThe directory listing of current working directory is:\n\n```\n{{ SCREAM_WORK_DIR_LS }}\n```\n\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.\n{% if SCREAM_ADDITIONAL_DIRS_INFO %}\n\n## Additional Directories\n\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.\n\n{{ SCREAM_ADDITIONAL_DIRS_INFO }}\n{% endif %}\n\n# Project Information\n\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.\n\n> Why `AGENTS.md`?\n>\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.\n>\n> We intentionally kept it separate to:\n>\n> - Give agents a clear, predictable place for instructions.\n> - Keep `README`s concise and focused on human contributors.\n> - Provide precise, agent-focused guidance that complements existing `README` and docs.\n\nThe `AGENTS.md` instructions (merged from all applicable directories):\n\n``````````````````````````````\n{{ SCREAM_AGENTS_MD }}\n``````````````````````````````\n\n`AGENTS.md` files can appear at any level of the project directory tree, including inside `.scream-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.\n\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.\n\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.\n\n# Skills\n\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.\n\n## What are skills?\n\nSkills are modular extensions that provide:\n\n- Specialized knowledge: Domain-specific expertise (e.g., PDF processing, data analysis)\n- Workflow patterns: Best practices for common tasks\n- Tool integrations: Pre-configured tool chains for specific tasks\n- Reference material: Documentation, templates, and examples\n\n## Available skills\n\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**.\n\n{{ SCREAM_SKILLS }}\n\n## How to use skills\n\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.\n\nOnly read skill details when needed to conserve the context window.\n\n# CONTRACT\n\nThese rules are inviolable.\n\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.\n- You NEVER suppress tests to make code pass.\n- You NEVER fabricate outputs that were not observed. Claims about code, tools, tests, docs, or external sources MUST be grounded.\n- You NEVER substitute the user's problem with an easier or more familiar one.\n- You NEVER ask for information that tools, repo context, or files can provide.\n- NEVER punt half-solved work back.\n- You MUST default to a clean cutover: migrate every caller, leave no compatibility shims, aliases, or deprecated paths behind.\n- Be brief in prose, not in evidence, verification, or blocking details.\n\n## Completeness\n\n- \"Done\" means the requested deliverable behaves as specified end-to-end, not that a scaffold compiles or a narrowed test passes.\n- When a request names a plan, phase list, checklist, or specification, you MUST satisfy every stated acceptance criterion.\n- You NEVER silently shrink scope.\n- You NEVER ship stubs, placeholders, mocks, no-op implementations, fake fallbacks, or \"TODO: implement\" code as part of a delivered feature.\n- Verification claims MUST match what was actually exercised.\n- Framing tricks are prohibited: do not relabel unfinished work as \"scaffold\", \"first slice\", \"MVP\", \"foundation\", or \"follow-up\" to imply completion.\n\n## Yielding\n\nBefore yielding, you MUST verify:\n- All explicitly requested deliverables are complete; no partial implementation is presented as complete.\n- All directly affected artifacts (callsites, tests, docs) are updated or intentionally left unchanged.\n- The output format matches the ask.\n- No unobserved claim is presented as fact.\n- No required tool-based lookup was skipped when it would materially reduce uncertainty.\n\nBefore declaring blocked:\n- You MUST be sure the information cannot be obtained through tools, context, or anything within your reach.\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.\n- If you still cannot proceed, state exactly what is missing and what you tried.\n",
|
|
95239
95980
|
"profile/default/verify.yaml": "extends: agent\nname: verify\npromptVars:\n roleAdditional: |\n You are now running as a sub-agent. All `user` messages are sent by the main agent.\n You are the Verify sub-agent. Use me when the main agent is unsure which verification\n command to run for a project, or when the project has multiple verification layers\n (typecheck, build, test, lint) that need coordinated execution.\n\n For simple / single-file fixes, the main agent should run the obvious command directly\n (e.g. `npx -p typescript tsc --noEmit --strict file.ts`, `python3 -m py_compile file.py`)\n instead of spawning this subagent.\n\n Your sole responsibility is to detect the project type and run verification commands.\n Do NOT try to fix anything. Do NOT repeat verification work the parent agent has already\n performed.\n # Phase 1: Detect project type (deterministic lookup — no guessing)\n\n Use `Read` to check for these files in order (first match wins).\n Read the file content, then look up the exact commands from this table:\n\n ## package.json exists — read it and check dependencies/devDependencies and scripts:\n\n | Condition | Type | Build | Test | Lint | Typecheck |\n |-----------|------|-------|------|------|-----------|\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` |\n | `dependencies.react-scripts` | CRA | `npx react-scripts build` | `npm test` (if exists) | `npm run lint` (if exists) | `npx tsc --noEmit` or script `typecheck` |\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` |\n | `devDependencies.@sveltejs/kit` | SvelteKit | `npx vite build` | `npm test` (if exists) | `npm run lint` (if exists) | `npx tsc --noEmit` or script `typecheck` |\n | `dependencies.astro` | Astro | `npx astro build` | `npm test` (if exists) | `npm run lint` (if exists) | `npx tsc --noEmit` or script `typecheck` |\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` |\n\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`.\n\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.\n\n ## Other ecosystems:\n\n | File | Type | Build | Test | Lint |\n |------|------|-------|------|------|\n | `requirements.txt` or `pyproject.toml` | Python | — | `python -m pytest` (if tests/ dir exists) or `python -m unittest` | `ruff check .` |\n | `go.mod` | Go | `go build ./...` | `go test ./...` | `go vet ./...` |\n | `Cargo.toml` | Rust | `cargo build` | `cargo test` | `cargo clippy` |\n | `pom.xml` | Maven | `mvn package -q` | `mvn test` | — |\n | `build.gradle` or `build.gradle.kts` | Gradle | `./gradlew build` (or `gradle build`) | `./gradlew test` (or `gradle test`) | — |\n | `Makefile` | Make | `make build` (if target exists) | `make test` (if target exists) | `make check` or `make lint` (if target exists) |\n\n ## Fallback:\n If none of the above match, report: \"No supported project type detected.\" and stop.\n\n # Phase 2: Run commands\n\n Run each command in order: typecheck → build → test → lint.\n For Python/Go/Rust, skip build if the command is not available.\n Capture stdout and stderr for each. Time each command.\n\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.\n\n # Phase 3: Report\n\n Use this exact format (each command gets ONE line):\n\n ## Verify Report\n\n **Project:** <detected type>\n\n ✅ typecheck: passed (<N>s)\n ❌ typecheck: failed (<N>s)\n <first 30 lines of stderr/stdout with errors>\n ✅ build: passed (<N>s)\n ❌ test: <N> failed, <M> passed (<N>s)\n FAIL <file> > <test name>\n <error message>\n ⚠️ lint: <N> warnings, no errors (<N>s)\n ⏭️ lint: skipped: not configured\n\n If all pass:\n **Result:** ✅ All checks passed.\n\n If any fail:\n **Result:** ❌ <N> check(s) failed. See details above.\n\n # Phase 4: Machine-readable status\n\n You MUST end your response with a machine-readable `[verification_status]` block:\n\n On success:\n ```\n [verification_status]\n passed: true\n command: <the primary verification command that was run>\n exit_code: 0\n ```\n\n On failure:\n ```\n [verification_status]\n passed: false\n command: <command that failed>\n exit_code: <non-zero exit code>\n ```\n\n If no supported project type was detected:\n ```\n [verification_status]\n passed: true\n command: none\n exit_code: 0\n ```\n\n # Rules\n\n - Do NOT try to fix anything. Report only.\n - Do NOT ask questions. Run and report.\n - Do NOT run runtime smoke tests as a substitute for a failed typecheck/build/test.\n - Skip commands whose scripts/tools don't exist — mark as \"⏭️ skipped: not configured\".\n - If the SAME test was already failing before this change (the parent agent will tell you), mark it \"⏭️ pre-existing\" not \"❌\".\n\nwhenToUse: |\n Verification specialist. Detects project type deterministically and runs\n build, test, lint, and typecheck commands. Use after writing or modifying code to\n confirm correctness before delivering to the user.\ntools:\n - Bash\n - Read\n - Glob\n - Grep\n - MemoryLookup\n - MemoryConsolidatePlan\n - MemoryConsolidateApply\n",
|
|
95240
95981
|
"profile/default/writer.yaml": "extends: agent\nname: writer\npromptVars:\n roleAdditional: |\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.\n\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.\n\n ## Core Methodology: Three-Layer Deep Analysis\n\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.\n\n **Layer 1 — The Ask:** What did the user explicitly request? What is the surface-level topic, format, and scope?\n\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?\n\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?\n\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.\"\n\n ## Your Strengths\n\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.\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.\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.\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.\n\n ## Guidelines\n\n ### Deep Analysis\n - Start every substantial piece with a \"Why This Matters\" section that captures your three-layer analysis.\n - Do not merely list facts. Explain the relationships between them. Cause and effect, trade-offs, second-order consequences.\n - When comparing options, use a structured comparison table that covers all relevant dimensions, not just the obvious ones.\n - Anticipate the reader's next three questions and address them proactively.\n\n ### Sources and Evidence\n - For data claims, cite the source. Prefer: `SearchWeb`, `FetchURL`, or files provided by the caller.\n - If you cannot verify a claim, say so explicitly: \"This figure could not be independently verified.\"\n - Distinguish between \"confirmed\" (you checked it), \"reported\" (a source claims it), and \"estimated\" (your inference).\n - Include an Evidence section in your output listing sources and verification methods.\n\n ### Objectivity\n - Present both supporting and contradicting evidence.\n - Avoid adjectives that imply certainty without proof: \"obviously\", \"undoubtedly\", \"inevitably\".\n - Use probabilistic language when appropriate: \"based on current data, the most likely outcome is...\"\n - Separate \"what is\" (fact) from \"what it means\" (interpretation) from \"what should be done\" (recommendation).\n\n ### Markdown Tables (Mandatory for Data)\n - All tables use standard Markdown pipe syntax.\n - Headers are bold and semantically clear.\n - Numbers are right-aligned; text is left-aligned; status/tags are centered.\n - Every table has a descriptive caption above it (e.g., \"Table 1: Q1-Q4 Revenue by Region\").\n - Keep columns ≤ 8. If more are needed, split into related tables.\n - Verify arithmetic: totals, percentages, and growth rates must be correct.\n - Use consistent units within a column.\n\n ### Content Structure\n - Use clear heading hierarchies (`#`, `##`, `###`).\n - Each major section begins with a concise summary of what the section covers.\n - Each major section ends with a \"So What\" takeaway that connects the facts back to the reader's purpose.\n - Complex comparisons always use tables. Narrative descriptions of tabular data are insufficient.\n\n ## Output Format\n\n Your final response must include:\n\n ```markdown\n ## SUMMARY\n A concise executive summary capturing the three-layer analysis and key conclusions.\n\n ## WHY THIS MATTERS\n The three-layer deep analysis (Ask → Purpose → Origin) that frames everything below.\n\n ## [Main Content Sections]\n The body of the analysis, report, or document.\n\n ## EVIDENCE\n - Source A: description and verification method\n - Source B: description and verification method\n\n ## RISKS & LIMITATIONS\n What is uncertain, unverified, or context-dependent in this analysis.\n ```\n\n ## Important Reminders\n\n - Your only output is Markdown content. You do not generate .docx, .pdf, or any other format.\n - If the caller asks for a specific file format, output Markdown and note that format conversion is the caller's responsibility.\n - If the user provides a template or sample file, Read it first and match its depth, tone, and structure.\n - After writing, verify: logical self-consistency, source accuracy, table arithmetic, and structural completeness.\n - Never fabricate data. If data is missing, say so and explain the impact of the gap.\nwhenToUse: |\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.\ntools:\n - Bash\n - Read\n - ReadMediaFile\n - Glob\n - Grep\n - Write\n - Edit\n - WebSearch\n - FetchURL\n - MemoryLookup\n - MemoryConsolidatePlan\n - MemoryConsolidateApply\n - mcp__*\n"
|
|
95241
95982
|
};
|
|
@@ -95252,22 +95993,27 @@ const DEFAULT_AGENT_PROFILES = loadAgentProfilesFromSources([
|
|
|
95252
95993
|
].map((file) => `profile/default/${file}`), PROFILE_SOURCES);
|
|
95253
95994
|
//#endregion
|
|
95254
95995
|
//#region ../../packages/agent-core/src/lsp/registry.ts
|
|
95996
|
+
const TYPESCRIPT_SERVER_COMMAND = ["typescript-language-server", "--stdio"];
|
|
95255
95997
|
const LANGUAGE_SERVERS = {
|
|
95256
95998
|
".ts": {
|
|
95257
|
-
command:
|
|
95258
|
-
languageId: "typescript"
|
|
95999
|
+
command: TYPESCRIPT_SERVER_COMMAND,
|
|
96000
|
+
languageId: "typescript",
|
|
96001
|
+
initOptions: typescriptInitOptions
|
|
95259
96002
|
},
|
|
95260
96003
|
".tsx": {
|
|
95261
|
-
command:
|
|
95262
|
-
languageId: "typescriptreact"
|
|
96004
|
+
command: TYPESCRIPT_SERVER_COMMAND,
|
|
96005
|
+
languageId: "typescriptreact",
|
|
96006
|
+
initOptions: typescriptInitOptions
|
|
95263
96007
|
},
|
|
95264
96008
|
".js": {
|
|
95265
|
-
command:
|
|
95266
|
-
languageId: "javascript"
|
|
96009
|
+
command: TYPESCRIPT_SERVER_COMMAND,
|
|
96010
|
+
languageId: "javascript",
|
|
96011
|
+
initOptions: typescriptInitOptions
|
|
95267
96012
|
},
|
|
95268
96013
|
".jsx": {
|
|
95269
|
-
command:
|
|
95270
|
-
languageId: "javascriptreact"
|
|
96014
|
+
command: TYPESCRIPT_SERVER_COMMAND,
|
|
96015
|
+
languageId: "javascriptreact",
|
|
96016
|
+
initOptions: typescriptInitOptions
|
|
95271
96017
|
},
|
|
95272
96018
|
".py": {
|
|
95273
96019
|
command: ["pyright-langserver", "--stdio"],
|
|
@@ -95282,6 +96028,37 @@ const LANGUAGE_SERVERS = {
|
|
|
95282
96028
|
languageId: "go"
|
|
95283
96029
|
}
|
|
95284
96030
|
};
|
|
96031
|
+
/**
|
|
96032
|
+
* Resolve a `tsserver` lib directory for `typescript-language-server`.
|
|
96033
|
+
*
|
|
96034
|
+
* `typescript-language-server` is only the LSP protocol layer; it shells out to
|
|
96035
|
+
* TypeScript's own `tsserver.js` to compute diagnostics. It searches the
|
|
96036
|
+
* workspace's `node_modules/typescript` by default, so editing a standalone
|
|
96037
|
+
* `.ts` file outside any JS project makes it exit with "Could not find a valid
|
|
96038
|
+
* TypeScript installation." Passing `initializationOptions.tsserver.path`
|
|
96039
|
+
* points it at a known-good install so diagnostics work regardless of where
|
|
96040
|
+
* the edited file lives.
|
|
96041
|
+
*
|
|
96042
|
+
* Resolution order: workspace `node_modules/typescript`, then the
|
|
96043
|
+
* `typescript` dependency bundled with scream-code itself (resolved via
|
|
96044
|
+
* `require.resolve`). Returns undefined when neither is available, in which
|
|
96045
|
+
* case the server will fall back to its own search (and likely fail for
|
|
96046
|
+
* project-less files).
|
|
96047
|
+
*/
|
|
96048
|
+
function resolveTsserverPath(workspaceRoot) {
|
|
96049
|
+
const workspaceCandidate = join(workspaceRoot, "node_modules", "typescript", "lib");
|
|
96050
|
+
if (existsSync(join(workspaceCandidate, "tsserver.js"))) return workspaceCandidate;
|
|
96051
|
+
try {
|
|
96052
|
+
return createRequire(import.meta.url).resolve("typescript/lib/tsserver.js").slice(0, -12);
|
|
96053
|
+
} catch {
|
|
96054
|
+
return;
|
|
96055
|
+
}
|
|
96056
|
+
}
|
|
96057
|
+
function typescriptInitOptions(workspaceRoot) {
|
|
96058
|
+
const tsserverPath = resolveTsserverPath(workspaceRoot);
|
|
96059
|
+
if (tsserverPath === void 0) return void 0;
|
|
96060
|
+
return { tsserver: { path: tsserverPath } };
|
|
96061
|
+
}
|
|
95285
96062
|
var LspRegistry = class {
|
|
95286
96063
|
jian;
|
|
95287
96064
|
clients = /* @__PURE__ */ new Map();
|
|
@@ -95291,25 +96068,43 @@ var LspRegistry = class {
|
|
|
95291
96068
|
/**
|
|
95292
96069
|
* Get or create an LSP client for the given file path and workspace root.
|
|
95293
96070
|
* Returns undefined if the file type is not supported.
|
|
96071
|
+
*
|
|
96072
|
+
* Caches the in-flight `Promise<LspClient>` rather than the client instance
|
|
96073
|
+
* so concurrent callers share the same startup and never receive a client
|
|
96074
|
+
* whose `initialize` has not completed.
|
|
95294
96075
|
*/
|
|
95295
96076
|
async getClient(path, workspaceRoot) {
|
|
95296
96077
|
const config = LANGUAGE_SERVERS[path.slice(path.lastIndexOf(".")).toLowerCase()];
|
|
95297
96078
|
if (config === void 0) return void 0;
|
|
95298
96079
|
const key = `${workspaceRoot}\0${config.command.join(" ")}`;
|
|
95299
|
-
let
|
|
95300
|
-
if (
|
|
95301
|
-
|
|
95302
|
-
this.clients.set(key,
|
|
96080
|
+
let clientPromise = this.clients.get(key);
|
|
96081
|
+
if (clientPromise === void 0) {
|
|
96082
|
+
clientPromise = this.createAndStartClient(config, workspaceRoot, key);
|
|
96083
|
+
this.clients.set(key, clientPromise);
|
|
96084
|
+
}
|
|
96085
|
+
return clientPromise;
|
|
96086
|
+
}
|
|
96087
|
+
async createAndStartClient(config, workspaceRoot, key) {
|
|
96088
|
+
const client = new LspClient(config.command, workspaceRoot, this.jian, config.initOptions?.(workspaceRoot));
|
|
96089
|
+
try {
|
|
95303
96090
|
await client.start();
|
|
96091
|
+
return client;
|
|
96092
|
+
} catch (error) {
|
|
96093
|
+
this.clients.delete(key);
|
|
96094
|
+
throw error;
|
|
95304
96095
|
}
|
|
95305
|
-
return client;
|
|
95306
96096
|
}
|
|
95307
96097
|
languageIdForPath(path) {
|
|
95308
96098
|
return LANGUAGE_SERVERS[path.slice(path.lastIndexOf(".")).toLowerCase()]?.languageId;
|
|
95309
96099
|
}
|
|
96100
|
+
/** Returns the server command for the path's extension, or undefined when unsupported. */
|
|
96101
|
+
commandForPath(path) {
|
|
96102
|
+
return LANGUAGE_SERVERS[path.slice(path.lastIndexOf(".")).toLowerCase()]?.command;
|
|
96103
|
+
}
|
|
95310
96104
|
async stopAll() {
|
|
95311
|
-
|
|
96105
|
+
const promises = [...this.clients.values()];
|
|
95312
96106
|
this.clients.clear();
|
|
96107
|
+
await Promise.allSettled(promises.map((promise) => promise.then((client) => client.stop())));
|
|
95313
96108
|
}
|
|
95314
96109
|
};
|
|
95315
96110
|
//#endregion
|
|
@@ -95757,11 +96552,14 @@ var ToolManager = class {
|
|
|
95757
96552
|
this.builtinTools = new Map([
|
|
95758
96553
|
new ReadTool(jian, workspace),
|
|
95759
96554
|
new ReadGroupTool(jian, workspace),
|
|
95760
|
-
new WriteTool(jian, workspace),
|
|
95761
|
-
new EditTool(jian, workspace),
|
|
96555
|
+
new WriteTool(jian, workspace, this.lspRegistry),
|
|
96556
|
+
new EditTool(jian, workspace, this.lspRegistry),
|
|
95762
96557
|
new GrepTool(jian, workspace),
|
|
95763
96558
|
new GlobTool(jian, workspace),
|
|
95764
|
-
new BashTool(jian, cwd, background, {
|
|
96559
|
+
new BashTool(jian, cwd, background, {
|
|
96560
|
+
allowBackground,
|
|
96561
|
+
availableTools: this.enabledTools
|
|
96562
|
+
}),
|
|
95765
96563
|
(modelCapabilities.image_in || modelCapabilities.video_in) && new ReadMediaFileTool(jian, workspace, modelCapabilities, videoUploader),
|
|
95766
96564
|
new EnterPlanModeTool(this.agent),
|
|
95767
96565
|
new ExitPlanModeTool(this.agent),
|
|
@@ -95791,7 +96589,10 @@ var ToolManager = class {
|
|
|
95791
96589
|
allowBackground,
|
|
95792
96590
|
log: this.agent.log
|
|
95793
96591
|
}),
|
|
95794
|
-
this.agent.subagentHost && new WolfPackTool(this.agent.subagentHost, () => this.agent.wolfpackMode.isActive, {
|
|
96592
|
+
this.agent.subagentHost && new WolfPackTool(this.agent.subagentHost, () => this.agent.wolfpackMode.isActive, {
|
|
96593
|
+
subagents: DEFAULT_AGENT_PROFILES["agent"]?.subagents,
|
|
96594
|
+
log: this.agent.log
|
|
96595
|
+
}),
|
|
95795
96596
|
toolServices?.webSearcher && new WebSearchTool(toolServices.webSearcher),
|
|
95796
96597
|
toolServices?.urlFetcher && new FetchURLTool(toolServices.urlFetcher),
|
|
95797
96598
|
this.lspRegistry && new LspTool(this.agent, workspace, this.lspRegistry)
|
|
@@ -96530,7 +97331,7 @@ var TurnFlow = class {
|
|
|
96530
97331
|
isExploratory
|
|
96531
97332
|
};
|
|
96532
97333
|
} else if (isError !== true && this.lastToolFailure?.toolName === ctx.toolCall.name) {
|
|
96533
|
-
if (this.lastToolFailure.isExploratory) this.lastToolFailure = null;
|
|
97334
|
+
if (ctx.toolCall.name !== "Bash" || this.lastToolFailure.isExploratory) this.lastToolFailure = null;
|
|
96534
97335
|
}
|
|
96535
97336
|
const event = isError === true ? "PostToolUseFailure" : "PostToolUse";
|
|
96536
97337
|
this.agent.hooks?.fireAndForgetTrigger(event, {
|
|
@@ -96724,7 +97525,8 @@ function mapLoopEvent(event, turnId) {
|
|
|
96724
97525
|
turnId,
|
|
96725
97526
|
toolCallId: event.toolCallId,
|
|
96726
97527
|
output: event.result.output,
|
|
96727
|
-
isError: event.result.isError
|
|
97528
|
+
isError: event.result.isError,
|
|
97529
|
+
display: event.result.isError === true ? void 0 : event.result.display
|
|
96728
97530
|
};
|
|
96729
97531
|
case "turn.interrupted":
|
|
96730
97532
|
if (event.activeStep === void 0) return void 0;
|
|
@@ -97360,7 +98162,7 @@ var Agent = class {
|
|
|
97360
98162
|
getTools: () => this.tools.data(),
|
|
97361
98163
|
getBackground: (payload) => this.background.list(payload.activeOnly ?? false, payload.limit),
|
|
97362
98164
|
extractMemoriesOnExit: async () => {
|
|
97363
|
-
|
|
98165
|
+
return this.extractMemoriesOnExit();
|
|
97364
98166
|
},
|
|
97365
98167
|
sideQuestion: async (payload) => {
|
|
97366
98168
|
return { answer: await this.sideQuestion(payload.question) };
|
|
@@ -97414,13 +98216,13 @@ var Agent = class {
|
|
|
97414
98216
|
}
|
|
97415
98217
|
/** Extract memory memos from the full conversation history on session exit. */
|
|
97416
98218
|
async extractMemoriesOnExit() {
|
|
97417
|
-
if (!this.memoStore) return;
|
|
98219
|
+
if (!this.memoStore) return 0;
|
|
97418
98220
|
await this.memoStore.init();
|
|
97419
98221
|
const history = this.context.history;
|
|
97420
|
-
if (history.length < 4) return;
|
|
98222
|
+
if (history.length < 4) return 0;
|
|
97421
98223
|
const sessionId = this.homedir ? basename$1(dirname$2(dirname$2(this.homedir))) : "unknown";
|
|
97422
98224
|
const sessionTitle = await this.getSessionTitle();
|
|
97423
|
-
const sampleText = history.slice(-
|
|
98225
|
+
const sampleText = history.slice(-50).map((m) => {
|
|
97424
98226
|
const text = m.content.filter((p) => p.type === "text").map((p) => p.text).join(" ");
|
|
97425
98227
|
return `[${m.role}] ${text.slice(0, 300)}`;
|
|
97426
98228
|
}).join("\n");
|
|
@@ -97435,7 +98237,7 @@ var Agent = class {
|
|
|
97435
98237
|
toolCalls: []
|
|
97436
98238
|
}]);
|
|
97437
98239
|
const memos = parseMemoryMemos(typeof response.message.content === "string" ? response.message.content : response.message.content.map((p) => p.type === "text" ? p.text : "").join(""));
|
|
97438
|
-
if (memos.length === 0) return;
|
|
98240
|
+
if (memos.length === 0) return 0;
|
|
97439
98241
|
const store = this.memoStore;
|
|
97440
98242
|
const failed = (await Promise.allSettled(memos.map((memo) => {
|
|
97441
98243
|
memo.sourceSessionId = sessionId;
|
|
@@ -97448,12 +98250,15 @@ var Agent = class {
|
|
|
97448
98250
|
failed,
|
|
97449
98251
|
total: memos.length
|
|
97450
98252
|
});
|
|
98253
|
+
const stored = memos.length - failed;
|
|
97451
98254
|
this.log.info("Extracted memory memos on session exit", {
|
|
97452
|
-
count:
|
|
98255
|
+
count: stored,
|
|
97453
98256
|
sessionId
|
|
97454
98257
|
});
|
|
98258
|
+
return stored;
|
|
97455
98259
|
} catch (error) {
|
|
97456
98260
|
this.log.warn("Exit memory extraction failed", { error: String(error) });
|
|
98261
|
+
throw error;
|
|
97457
98262
|
}
|
|
97458
98263
|
}
|
|
97459
98264
|
async sideQuestion(question) {
|
|
@@ -97611,29 +98416,6 @@ function ensureScreamHome(homeDir) {
|
|
|
97611
98416
|
});
|
|
97612
98417
|
}
|
|
97613
98418
|
//#endregion
|
|
97614
|
-
//#region ../../packages/agent-core/src/config/resolve.ts
|
|
97615
|
-
const TRUE_BOOLEAN_ENV_VALUES = new Set([
|
|
97616
|
-
"1",
|
|
97617
|
-
"true",
|
|
97618
|
-
"yes",
|
|
97619
|
-
"on"
|
|
97620
|
-
]);
|
|
97621
|
-
const FALSE_BOOLEAN_ENV_VALUES = new Set([
|
|
97622
|
-
"0",
|
|
97623
|
-
"false",
|
|
97624
|
-
"no",
|
|
97625
|
-
"off"
|
|
97626
|
-
]);
|
|
97627
|
-
function resolveConfigValue(input) {
|
|
97628
|
-
return input.parseEnv(input.env?.[input.envKey]) ?? input.configValue ?? input.defaultValue;
|
|
97629
|
-
}
|
|
97630
|
-
function parseBooleanEnv(value) {
|
|
97631
|
-
const normalized = value?.trim().toLowerCase();
|
|
97632
|
-
if (normalized === void 0 || normalized.length === 0) return void 0;
|
|
97633
|
-
if (TRUE_BOOLEAN_ENV_VALUES.has(normalized)) return true;
|
|
97634
|
-
if (FALSE_BOOLEAN_ENV_VALUES.has(normalized)) return false;
|
|
97635
|
-
}
|
|
97636
|
-
//#endregion
|
|
97637
98419
|
//#region ../../packages/agent-core/src/config/env-model.ts
|
|
97638
98420
|
/** Reserved keys for the env-driven synthetic provider / model alias. */
|
|
97639
98421
|
const ENV_MODEL_PROVIDER_KEY = "__scream_env__";
|
|
@@ -115213,14 +115995,20 @@ const DEFAULT_MAX_BYTES = 10 * 1024 * 1024;
|
|
|
115213
115995
|
const parseHTML = parseHTML$1;
|
|
115214
115996
|
/**
|
|
115215
115997
|
* SSRF guard — reject non-http(s) schemes and (by default) any hostname
|
|
115216
|
-
* that is, or
|
|
115217
|
-
*
|
|
115218
|
-
*
|
|
115219
|
-
*
|
|
115220
|
-
*
|
|
115221
|
-
*
|
|
115222
|
-
|
|
115223
|
-
|
|
115998
|
+
* that is, or resolves to, a private / loopback / link-local / ULA IP.
|
|
115999
|
+
*
|
|
116000
|
+
* Two layers:
|
|
116001
|
+
* 1. Static check against the URL string (scheme, hostname patterns,
|
|
116002
|
+
* IP literal ranges).
|
|
116003
|
+
* 2. DNS resolution of the hostname; if any resolved address is private,
|
|
116004
|
+
* the request is blocked (prevents DNS-rebinding to internal IPs).
|
|
116005
|
+
*
|
|
116006
|
+
* A TOCTOU window remains between resolution and the actual fetch (the
|
|
116007
|
+
* DNS answer could change), but this is materially stronger than a pure
|
|
116008
|
+
* static check. Pinning the resolved IP through to the connection is
|
|
116009
|
+
* left for a follow-up.
|
|
116010
|
+
*/
|
|
116011
|
+
async function assertSafeFetchTarget(url, allowPrivate, dnsLookup) {
|
|
115224
116012
|
let parsed;
|
|
115225
116013
|
try {
|
|
115226
116014
|
parsed = new URL(url);
|
|
@@ -115232,8 +116020,27 @@ function assertSafeFetchTarget(url, allowPrivate) {
|
|
|
115232
116020
|
const hostRaw = parsed.hostname.toLowerCase();
|
|
115233
116021
|
const host = hostRaw.startsWith("[") && hostRaw.endsWith("]") ? hostRaw.slice(1, -1) : hostRaw;
|
|
115234
116022
|
if (host === "localhost" || host.endsWith(".localhost")) throw new Error(`Refusing to fetch private host: "${host}"`);
|
|
115235
|
-
if (
|
|
115236
|
-
|
|
116023
|
+
if (isIP(host) !== 0) {
|
|
116024
|
+
if (isPrivateIp(host)) throw new Error(`Refusing to fetch private address: "${host}"`);
|
|
116025
|
+
return;
|
|
116026
|
+
}
|
|
116027
|
+
let addresses;
|
|
116028
|
+
try {
|
|
116029
|
+
addresses = await dnsLookup(host);
|
|
116030
|
+
} catch {
|
|
116031
|
+
throw new Error(`DNS resolution failed for "${host}"`);
|
|
116032
|
+
}
|
|
116033
|
+
for (const address of addresses) if (isPrivateIp(address)) throw new Error(`Refusing to fetch "${host}" — resolves to private address ${address}`);
|
|
116034
|
+
}
|
|
116035
|
+
/**
|
|
116036
|
+
* Returns true for loopback, private, link-local, ULA, and other
|
|
116037
|
+
* non-routable IP addresses (both IPv4 and IPv6).
|
|
116038
|
+
*/
|
|
116039
|
+
function isPrivateIp(ip) {
|
|
116040
|
+
const lower = ip.toLowerCase();
|
|
116041
|
+
const mapped = /^::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/.exec(lower);
|
|
116042
|
+
if (mapped !== null) return isPrivateIp(mapped[1]);
|
|
116043
|
+
const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(ip);
|
|
115237
116044
|
if (v4 !== null) {
|
|
115238
116045
|
const octets = [
|
|
115239
116046
|
v4[1],
|
|
@@ -115241,32 +116048,38 @@ function assertSafeFetchTarget(url, allowPrivate) {
|
|
|
115241
116048
|
v4[3],
|
|
115242
116049
|
v4[4]
|
|
115243
116050
|
].map(Number);
|
|
115244
|
-
if (octets.some((n) => !Number.isInteger(n) || n < 0 || n > 255))
|
|
116051
|
+
if (octets.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return false;
|
|
115245
116052
|
const [a, b] = octets;
|
|
115246
|
-
|
|
116053
|
+
return a === 127 || a === 10 || a === 192 && b === 168 || a === 172 && b >= 16 && b <= 31 || a === 169 && b === 254 || a === 0 || a === 100 && b >= 64 && b <= 127;
|
|
115247
116054
|
}
|
|
116055
|
+
return lower === "::1" || lower === "::" || lower.startsWith("fe80:") || lower.startsWith("fc") || lower.startsWith("fd");
|
|
115248
116056
|
}
|
|
115249
116057
|
function cacheKey$1(url, allowPrivate, maxBytes, userAgent) {
|
|
115250
116058
|
return `local:${url}:${String(allowPrivate)}:${String(maxBytes)}:${userAgent}`;
|
|
115251
116059
|
}
|
|
116060
|
+
const defaultDnsLookup = async (hostname) => {
|
|
116061
|
+
return (await lookup(hostname, { all: true })).map((a) => a.address);
|
|
116062
|
+
};
|
|
115252
116063
|
var LocalFetchURLProvider = class {
|
|
115253
116064
|
userAgent;
|
|
115254
116065
|
fetchImpl;
|
|
115255
116066
|
maxBytes;
|
|
115256
116067
|
allowPrivateAddresses;
|
|
115257
116068
|
cache;
|
|
116069
|
+
dnsLookup;
|
|
115258
116070
|
constructor(options = {}) {
|
|
115259
116071
|
this.userAgent = options.userAgent ?? DEFAULT_USER_AGENT;
|
|
115260
116072
|
this.fetchImpl = options.fetchImpl ?? globalThis.fetch.bind(globalThis);
|
|
115261
116073
|
this.maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
115262
116074
|
this.allowPrivateAddresses = options.allowPrivateAddresses ?? false;
|
|
115263
116075
|
this.cache = options.cache ?? new FetchCache();
|
|
116076
|
+
this.dnsLookup = options.dnsLookup ?? defaultDnsLookup;
|
|
115264
116077
|
}
|
|
115265
116078
|
async fetch(url, _options) {
|
|
115266
|
-
assertSafeFetchTarget(url, this.allowPrivateAddresses);
|
|
115267
116079
|
const key = cacheKey$1(url, this.allowPrivateAddresses, this.maxBytes, this.userAgent);
|
|
115268
116080
|
const cached = this.cache.get(key);
|
|
115269
116081
|
if (cached !== void 0) return cached;
|
|
116082
|
+
await assertSafeFetchTarget(url, this.allowPrivateAddresses, this.dnsLookup);
|
|
115270
116083
|
const result = await this.fetchFresh(url);
|
|
115271
116084
|
this.cache.set(key, result);
|
|
115272
116085
|
return result;
|
|
@@ -115678,61 +116491,6 @@ async function safeReadText(response) {
|
|
|
115678
116491
|
}
|
|
115679
116492
|
}
|
|
115680
116493
|
//#endregion
|
|
115681
|
-
//#region ../../packages/agent-core/src/flags/registry.ts
|
|
115682
|
-
/**
|
|
115683
|
-
* Experimental feature flags. Empty by default — there are no experimental features yet.
|
|
115684
|
-
*
|
|
115685
|
-
* To add one, append an entry and gate the feature with `flags.enabled('my-feature')`:
|
|
115686
|
-
* { id: 'my-feature', env: 'SCREAM_CODE_EXPERIMENTAL_MY_FEATURE', default: false, surface: 'both' }
|
|
115687
|
-
*
|
|
115688
|
-
* Keep the `as const satisfies` — it derives the literal `FlagId` union that gives `enabled()`
|
|
115689
|
-
* autocomplete and typo-checking. `env` must start with 'SCREAM_CODE_EXPERIMENTAL_', be unique, and
|
|
115690
|
-
* not equal the master switch 'SCREAM_CODE_EXPERIMENTAL_FLAG'; `id` must not be 'flag'.
|
|
115691
|
-
*/
|
|
115692
|
-
const FLAG_DEFINITIONS = [{
|
|
115693
|
-
id: "micro-compaction",
|
|
115694
|
-
env: "SCREAM_CODE_EXPERIMENTAL_MICRO_COMPACTION",
|
|
115695
|
-
default: false,
|
|
115696
|
-
surface: "both"
|
|
115697
|
-
}, {
|
|
115698
|
-
id: "wolfpack",
|
|
115699
|
-
env: "SCREAM_CODE_EXPERIMENTAL_WOLFPACK",
|
|
115700
|
-
default: false,
|
|
115701
|
-
surface: "both"
|
|
115702
|
-
}];
|
|
115703
|
-
/**
|
|
115704
|
-
* Pure, synchronous flag resolver. State comes entirely from (env, registry) and nothing is
|
|
115705
|
-
* cached: env is read live on every call, so a single shared instance always reflects the current
|
|
115706
|
-
* process env. Defaults to process.env + FLAG_DEFINITIONS; tests can inject a custom env / defs.
|
|
115707
|
-
*
|
|
115708
|
-
* Precedence (highest wins):
|
|
115709
|
-
* L1 master switch SCREAM_CODE_EXPERIMENTAL_FLAG → every flag is on
|
|
115710
|
-
* L2 per-feature def.env (parseBooleanEnv, may force on or off)
|
|
115711
|
-
* L3 registry default
|
|
115712
|
-
*/
|
|
115713
|
-
var FlagResolver = class {
|
|
115714
|
-
env;
|
|
115715
|
-
byId;
|
|
115716
|
-
constructor(env = process.env, definitions = FLAG_DEFINITIONS) {
|
|
115717
|
-
this.env = env;
|
|
115718
|
-
this.byId = new Map(definitions.map((def) => [def.id, def]));
|
|
115719
|
-
}
|
|
115720
|
-
enabled(id) {
|
|
115721
|
-
const def = this.byId.get(id);
|
|
115722
|
-
if (def === void 0) return false;
|
|
115723
|
-
if (parseBooleanEnv(this.env["SCREAM_CODE_EXPERIMENTAL_FLAG"]) === true) return true;
|
|
115724
|
-
const override = parseBooleanEnv(this.env[def.env]);
|
|
115725
|
-
if (override !== void 0) return override;
|
|
115726
|
-
return def.default;
|
|
115727
|
-
}
|
|
115728
|
-
};
|
|
115729
|
-
/**
|
|
115730
|
-
* Process-global flag accessor. Flags are env-driven and process-global, so a single shared
|
|
115731
|
-
* instance (reading live process.env) is the canonical way to consult them — import this directly
|
|
115732
|
-
* rather than constructing or injecting a resolver.
|
|
115733
|
-
*/
|
|
115734
|
-
const flags = new FlagResolver();
|
|
115735
|
-
//#endregion
|
|
115736
116494
|
//#region ../../packages/agent-core/src/session/export/manifest.ts
|
|
115737
116495
|
const WIRE_PROTOCOL_VERSION = "1.3";
|
|
115738
116496
|
function buildExportManifest(args) {
|
|
@@ -120177,7 +120935,7 @@ var Session = class {
|
|
|
120177
120935
|
/** Fire-and-forget: extract memory memos on session exit. */
|
|
120178
120936
|
async extractMemoriesOnExit() {
|
|
120179
120937
|
this.ensureOpen();
|
|
120180
|
-
|
|
120938
|
+
return this.rpc.extractMemoriesOnExit({ sessionId: this.id });
|
|
120181
120939
|
}
|
|
120182
120940
|
async sideQuestion(question) {
|
|
120183
120941
|
this.ensureOpen();
|
|
@@ -120569,7 +121327,6 @@ const SCREAM_CODE_UPDATE_STATE_FILE_NAME = "latest.json";
|
|
|
120569
121327
|
const SCREAM_CODE_INPUT_HISTORY_DIR_NAME = "user-history";
|
|
120570
121328
|
const DEFAULT_OAUTH_PROVIDER_NAME = "managed:scream-code";
|
|
120571
121329
|
ErrorCodes.AUTH_LOGIN_REQUIRED;
|
|
120572
|
-
const SCREAM_CODE_CDN_LATEST_URL = "https://api.github.com/repos/LIUTod/scream-code/releases/latest";
|
|
120573
121330
|
const SCREAM_CODE_PLUGIN_MARKETPLACE_URL_ENV = "SCREAM_CODE_PLUGIN_MARKETPLACE_URL";
|
|
120574
121331
|
//#endregion
|
|
120575
121332
|
//#region src/migration/command.ts
|
|
@@ -120635,7 +121392,7 @@ new Set(Object.keys(ScreamConfigSchema.shape).filter((k) => k !== "raw" && k !==
|
|
|
120635
121392
|
//#region src/cli/update/types.ts
|
|
120636
121393
|
function emptyUpdateCache() {
|
|
120637
121394
|
return {
|
|
120638
|
-
source: "
|
|
121395
|
+
source: "npm",
|
|
120639
121396
|
checkedAt: null,
|
|
120640
121397
|
latest: null
|
|
120641
121398
|
};
|
|
@@ -121581,12 +122338,19 @@ const BUILTIN_SLASH_COMMANDS = [
|
|
|
121581
122338
|
name: "goal",
|
|
121582
122339
|
aliases: ["goaloff"],
|
|
121583
122340
|
description: "查看/管理自动目标",
|
|
121584
|
-
priority:
|
|
122341
|
+
priority: 122,
|
|
121585
122342
|
availability: (args) => {
|
|
121586
122343
|
const trimmed = args.trim();
|
|
121587
122344
|
return trimmed === "" || trimmed === "status" || trimmed === "pause" || trimmed === "off" ? "always" : "idle-only";
|
|
121588
122345
|
}
|
|
121589
122346
|
},
|
|
122347
|
+
{
|
|
122348
|
+
name: "loop",
|
|
122349
|
+
aliases: [],
|
|
122350
|
+
description: "循环模式(无状态重试,配 --verify 验证结果)",
|
|
122351
|
+
priority: 121,
|
|
122352
|
+
availability: "always"
|
|
122353
|
+
},
|
|
121590
122354
|
{
|
|
121591
122355
|
name: "memory",
|
|
121592
122356
|
aliases: ["memo", "mem"],
|
|
@@ -124743,7 +125507,6 @@ const BREATHE_INTERVAL_MS$1 = 40;
|
|
|
124743
125507
|
const WELCOME_TIPS = [
|
|
124744
125508
|
"/config 配置模型",
|
|
124745
125509
|
"/sessions 恢复历史会话",
|
|
124746
|
-
"/skill 打开 Skill 中心",
|
|
124747
125510
|
"/ 输入后打开快捷菜单"
|
|
124748
125511
|
];
|
|
124749
125512
|
const WELCOME_SESSION_SLOTS = 3;
|
|
@@ -125247,6 +126010,15 @@ var BackgroundAgentStatusComponent = class {
|
|
|
125247
126010
|
//#endregion
|
|
125248
126011
|
//#region src/tui/components/messages/read-group.ts
|
|
125249
126012
|
const THROTTLE_MS = 200;
|
|
126013
|
+
const CONFLICT_MARKER_RE = /^(<<<<<<<|=======|>>>>>>>)/;
|
|
126014
|
+
function detectConflictMarkers(contentLines) {
|
|
126015
|
+
for (const raw of contentLines) {
|
|
126016
|
+
const tabIdx = raw.indexOf(" ");
|
|
126017
|
+
const line = tabIdx >= 0 ? raw.slice(tabIdx + 1) : raw;
|
|
126018
|
+
if (CONFLICT_MARKER_RE.test(line)) return true;
|
|
126019
|
+
}
|
|
126020
|
+
return false;
|
|
126021
|
+
}
|
|
125250
126022
|
function parseReadGroupOutput(output) {
|
|
125251
126023
|
const results = [];
|
|
125252
126024
|
const lines = output.split("\n");
|
|
@@ -125275,10 +126047,12 @@ function parseReadGroupOutput(output) {
|
|
|
125275
126047
|
}
|
|
125276
126048
|
}
|
|
125277
126049
|
}
|
|
126050
|
+
const hasConflicts = detectConflictMarkers(contentLines);
|
|
125278
126051
|
results.push({
|
|
125279
126052
|
filePath: path,
|
|
125280
126053
|
lines: lineCount,
|
|
125281
|
-
failed: false
|
|
126054
|
+
failed: false,
|
|
126055
|
+
hasConflicts
|
|
125282
126056
|
});
|
|
125283
126057
|
};
|
|
125284
126058
|
for (const line of lines) {
|
|
@@ -125428,7 +126202,10 @@ var ReadGroupComponent = class extends Container {
|
|
|
125428
126202
|
const pathPart = chalk.hex(colors.text)(result.filePath);
|
|
125429
126203
|
let tail;
|
|
125430
126204
|
if (result.failed) tail = chalk.hex(colors.error)(" · 失败");
|
|
125431
|
-
else
|
|
126205
|
+
else {
|
|
126206
|
+
tail = dim(` · ${String(result.lines)} 行`);
|
|
126207
|
+
if (result.hasConflicts) tail = `${tail}${chalk.hex(colors.warning)(" ⚠ 冲突")}`;
|
|
126208
|
+
}
|
|
125432
126209
|
return ` ${branch} ${pathPart}${tail}`;
|
|
125433
126210
|
}
|
|
125434
126211
|
/** Releases throttle timers so destroyed components cannot refresh later. */
|
|
@@ -126119,7 +126896,7 @@ var PlanBoxComponent = class {
|
|
|
126119
126896
|
//#endregion
|
|
126120
126897
|
//#region src/tui/components/messages/tool-renderers/types.ts
|
|
126121
126898
|
const PREVIEW_LINES = 3;
|
|
126122
|
-
function strArg(args, ...keys) {
|
|
126899
|
+
function strArg$1(args, ...keys) {
|
|
126123
126900
|
for (const key of keys) {
|
|
126124
126901
|
const v = args[key];
|
|
126125
126902
|
if (typeof v === "string" && v.length > 0) return v;
|
|
@@ -126442,8 +127219,8 @@ function formatBytes(bytes) {
|
|
|
126442
127219
|
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
126443
127220
|
}
|
|
126444
127221
|
function computeEditStats(args) {
|
|
126445
|
-
const oldStr = strArg(args, "old_string");
|
|
126446
|
-
const newStr = strArg(args, "new_string");
|
|
127222
|
+
const oldStr = strArg$1(args, "old_string");
|
|
127223
|
+
const newStr = strArg$1(args, "new_string");
|
|
126447
127224
|
if (oldStr.length === 0 && newStr.length === 0) return {
|
|
126448
127225
|
added: 0,
|
|
126449
127226
|
removed: 0
|
|
@@ -126459,7 +127236,7 @@ function computeEditStats(args) {
|
|
|
126459
127236
|
};
|
|
126460
127237
|
}
|
|
126461
127238
|
function computeWriteStats(args) {
|
|
126462
|
-
const content = strArg(args, "content");
|
|
127239
|
+
const content = strArg$1(args, "content");
|
|
126463
127240
|
const normalized = content.endsWith("\n") ? content.slice(0, -1) : content;
|
|
126464
127241
|
return { lines: normalized.length > 0 ? normalized.split("\n").length : 0 };
|
|
126465
127242
|
}
|
|
@@ -126513,13 +127290,18 @@ function pickChip(toolName) {
|
|
|
126513
127290
|
//#endregion
|
|
126514
127291
|
//#region src/tui/components/messages/tool-renderers/summary.ts
|
|
126515
127292
|
const GLANCE_SAMPLES = 3;
|
|
127293
|
+
const MAX_EXTENSION_COUNTS = 4;
|
|
127294
|
+
const MAX_DIRECTORY_GROUPS = 3;
|
|
126516
127295
|
function withGlance(glance) {
|
|
126517
127296
|
return (toolCall, result, ctx) => {
|
|
126518
127297
|
if (result.is_error) return renderTruncated(toolCall, result, ctx);
|
|
126519
127298
|
const out = [];
|
|
126520
127299
|
if (glance !== null) {
|
|
126521
|
-
const line = glance(toolCall, result);
|
|
126522
|
-
if (line.length > 0)
|
|
127300
|
+
const line = glance(toolCall, result, ctx.colors);
|
|
127301
|
+
if (line.length > 0) {
|
|
127302
|
+
const indented = line.split("\n").map((l) => ` ${l}`).join("\n");
|
|
127303
|
+
out.push(new Text(indented, 0, 0));
|
|
127304
|
+
}
|
|
126523
127305
|
}
|
|
126524
127306
|
if (ctx.expanded && result.output.length > 0) out.push(new Text(chalk.dim(result.output), 4, 0));
|
|
126525
127307
|
return out;
|
|
@@ -126536,28 +127318,119 @@ function pathFromGrepLine(line) {
|
|
|
126536
127318
|
if (second <= 0) return line;
|
|
126537
127319
|
return line.slice(0, second);
|
|
126538
127320
|
}
|
|
126539
|
-
|
|
127321
|
+
function readSearchResultsMatches(result) {
|
|
127322
|
+
const display = result.display;
|
|
127323
|
+
if (display === void 0) return void 0;
|
|
127324
|
+
if (display.kind !== "search_results") return void 0;
|
|
127325
|
+
return display.matches;
|
|
127326
|
+
}
|
|
127327
|
+
function truncateMatchText(text, max = 80) {
|
|
127328
|
+
if (text.length <= max) return text;
|
|
127329
|
+
return `${text.slice(0, max - 1)}…`;
|
|
127330
|
+
}
|
|
127331
|
+
const grepGlance = (_toolCall, result, colors) => {
|
|
127332
|
+
const matches = readSearchResultsMatches(result);
|
|
127333
|
+
if (matches !== void 0 && matches.length > 0) {
|
|
127334
|
+
const fileColor = chalk.hex(colors.roleTool);
|
|
127335
|
+
const lines = matches.slice(0, GLANCE_SAMPLES).map((m) => {
|
|
127336
|
+
return `${m.line > 0 ? `${fileColor(m.file)}${chalk.dim(":")}${chalk.hex(colors.primary)(String(m.line))}` : fileColor(m.file)}${chalk.dim(` ${truncateMatchText(m.text.trim())}`)}`;
|
|
127337
|
+
});
|
|
127338
|
+
const remaining = matches.length - GLANCE_SAMPLES;
|
|
127339
|
+
if (remaining > 0) lines.push(chalk.dim(`+${String(remaining)} more`));
|
|
127340
|
+
return lines.join("\n");
|
|
127341
|
+
}
|
|
126540
127342
|
const lines = nonEmptyLines(result.output);
|
|
126541
127343
|
if (lines.length === 0) return "";
|
|
126542
127344
|
const samples = lines.slice(0, GLANCE_SAMPLES).map(pathFromGrepLine);
|
|
126543
127345
|
const remaining = lines.length - samples.length;
|
|
126544
|
-
const
|
|
126545
|
-
|
|
126546
|
-
};
|
|
126547
|
-
|
|
127346
|
+
const fileColor = chalk.hex(colors.roleTool);
|
|
127347
|
+
const out = samples.map((s) => fileColor(s));
|
|
127348
|
+
if (remaining > 0) out.push(chalk.dim(`+${String(remaining)} more`));
|
|
127349
|
+
return out.join("\n");
|
|
127350
|
+
};
|
|
127351
|
+
function fileBasename(path) {
|
|
127352
|
+
const idx = path.lastIndexOf("/");
|
|
127353
|
+
return idx >= 0 ? path.slice(idx + 1) : path;
|
|
127354
|
+
}
|
|
127355
|
+
function fileDirname(path) {
|
|
127356
|
+
const idx = path.lastIndexOf("/");
|
|
127357
|
+
if (idx < 0) return ".";
|
|
127358
|
+
if (idx === 0) return "/";
|
|
127359
|
+
return path.slice(0, idx);
|
|
127360
|
+
}
|
|
127361
|
+
function fileExtension(path) {
|
|
127362
|
+
const base = fileBasename(path);
|
|
127363
|
+
const dot = base.lastIndexOf(".");
|
|
127364
|
+
if (dot <= 0) return "";
|
|
127365
|
+
return base.slice(dot + 1).toLowerCase();
|
|
127366
|
+
}
|
|
127367
|
+
function groupByDirectory(paths) {
|
|
127368
|
+
const groups = /* @__PURE__ */ new Map();
|
|
127369
|
+
for (const path of paths) {
|
|
127370
|
+
const dir = fileDirname(path);
|
|
127371
|
+
const group = groups.get(dir) ?? [];
|
|
127372
|
+
group.push(fileBasename(path));
|
|
127373
|
+
groups.set(dir, group);
|
|
127374
|
+
}
|
|
127375
|
+
return groups;
|
|
127376
|
+
}
|
|
127377
|
+
function countExtensions(paths) {
|
|
127378
|
+
const counts = /* @__PURE__ */ new Map();
|
|
127379
|
+
for (const path of paths) {
|
|
127380
|
+
const ext = fileExtension(path);
|
|
127381
|
+
const key = ext.length > 0 ? `.${ext}` : "(no-ext)";
|
|
127382
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
127383
|
+
}
|
|
127384
|
+
return counts;
|
|
127385
|
+
}
|
|
127386
|
+
const globGlance = (_toolCall, result, colors) => {
|
|
126548
127387
|
const lines = nonEmptyLines(result.output);
|
|
126549
127388
|
if (lines.length === 0) return "";
|
|
126550
|
-
const
|
|
126551
|
-
const
|
|
126552
|
-
const
|
|
126553
|
-
|
|
127389
|
+
const dirColor = chalk.hex(colors.roleTool);
|
|
127390
|
+
const nameColor = chalk.hex(colors.primary);
|
|
127391
|
+
const dim = chalk.dim;
|
|
127392
|
+
const dirLine = [...groupByDirectory(lines).entries()].slice(0, MAX_DIRECTORY_GROUPS).map(([dir, names]) => {
|
|
127393
|
+
const head = `${dirColor(`${dir}/`)}${dim(" · ")}`;
|
|
127394
|
+
const shown = names.slice(0, GLANCE_SAMPLES).map((n) => nameColor(n)).join(dim(", "));
|
|
127395
|
+
const more = names.length - GLANCE_SAMPLES;
|
|
127396
|
+
return `${head}${shown}${more > 0 ? dim(` (+${String(more)})`) : ""}`;
|
|
127397
|
+
}).join(dim(" "));
|
|
127398
|
+
const extLine = [...countExtensions(lines).entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, MAX_EXTENSION_COUNTS).map(([ext, count]) => `${dim(ext)}:${dim(` ${String(count)}`)}`).join(dim(", "));
|
|
127399
|
+
if (extLine.length === 0) return dirLine;
|
|
127400
|
+
return `${dirLine}${dim(" ")}${extLine}`;
|
|
127401
|
+
};
|
|
127402
|
+
function strArg(args, ...keys) {
|
|
127403
|
+
for (const key of keys) {
|
|
127404
|
+
const v = args[key];
|
|
127405
|
+
if (typeof v === "string" && v.length > 0) return v;
|
|
127406
|
+
}
|
|
127407
|
+
return "";
|
|
127408
|
+
}
|
|
127409
|
+
function countOutputLines(output) {
|
|
127410
|
+
if (output.length === 0) return 0;
|
|
127411
|
+
let count = 0;
|
|
127412
|
+
for (const line of output.split("\n")) if (line.length > 0) count += 1;
|
|
127413
|
+
return count;
|
|
127414
|
+
}
|
|
127415
|
+
const readGlance = (toolCall, result, colors) => {
|
|
127416
|
+
const path = strArg(toolCall.args, "path", "file_path", "filePath");
|
|
127417
|
+
if (path.length === 0) return "";
|
|
127418
|
+
const lineCount = countOutputLines(result.output);
|
|
127419
|
+
const ext = fileExtension(path);
|
|
127420
|
+
const dim = chalk.dim;
|
|
127421
|
+
const accentColor = chalk.hex(colors.primary);
|
|
127422
|
+
const parts = [];
|
|
127423
|
+
if (lineCount > 0) parts.push(`${String(lineCount)} lines`);
|
|
127424
|
+
if (ext.length > 0) parts.push(accentColor(ext));
|
|
127425
|
+
if (parts.length === 0) return "";
|
|
127426
|
+
return parts.join(dim(" · "));
|
|
126554
127427
|
};
|
|
126555
|
-
const readSummary = withGlance(null);
|
|
126556
127428
|
const fetchSummary = withGlance(null);
|
|
126557
127429
|
const webSearchSummary = withGlance(null);
|
|
126558
127430
|
const thinkSummary = withGlance(null);
|
|
126559
127431
|
const editSummary = withGlance(null);
|
|
126560
127432
|
const writeSummary = withGlance(null);
|
|
127433
|
+
const readSummary = withGlance(readGlance);
|
|
126561
127434
|
const grepSummary = withGlance(grepGlance);
|
|
126562
127435
|
const globSummary = withGlance(globGlance);
|
|
126563
127436
|
//#endregion
|
|
@@ -127030,7 +127903,8 @@ var ToolCallComponent = class ToolCallComponent extends Container {
|
|
|
127030
127903
|
name: call.name,
|
|
127031
127904
|
args: call.args,
|
|
127032
127905
|
output: call.result.output,
|
|
127033
|
-
isError: call.result.is_error ?? false
|
|
127906
|
+
isError: call.result.is_error ?? false,
|
|
127907
|
+
display: call.result.display
|
|
127034
127908
|
});
|
|
127035
127909
|
this.upsertSubToolActivity(call.id, call.name, call.args, call.result.is_error === true ? "failed" : "done");
|
|
127036
127910
|
}
|
|
@@ -127368,7 +128242,8 @@ var ToolCallComponent = class ToolCallComponent extends Container {
|
|
|
127368
128242
|
name: ongoing.name,
|
|
127369
128243
|
args: ongoing.args,
|
|
127370
128244
|
output: result.output,
|
|
127371
|
-
isError: result.is_error ?? false
|
|
128245
|
+
isError: result.is_error ?? false,
|
|
128246
|
+
display: result.display
|
|
127372
128247
|
});
|
|
127373
128248
|
this.upsertSubToolActivity(result.tool_call_id, ongoing.name, ongoing.args, result.is_error === true ? "failed" : "done");
|
|
127374
128249
|
while (this.finishedSubCalls.length > MAX_SUB_TOOL_CALLS_SHOWN) {
|
|
@@ -128018,6 +128893,20 @@ function ccConnectSupportsDaemon() {
|
|
|
128018
128893
|
}
|
|
128019
128894
|
}
|
|
128020
128895
|
/**
|
|
128896
|
+
* Detect the installed cc-connect version string (e.g. "1.2.3"), or undefined.
|
|
128897
|
+
*/
|
|
128898
|
+
function ccConnectVersion() {
|
|
128899
|
+
try {
|
|
128900
|
+
return execSync("cc-connect --version 2>&1", {
|
|
128901
|
+
encoding: "utf-8",
|
|
128902
|
+
timeout: 5e3,
|
|
128903
|
+
windowsHide: true
|
|
128904
|
+
}).match(/v?(\d+\.\d+\.\d+)/)?.[1] ?? void 0;
|
|
128905
|
+
} catch {
|
|
128906
|
+
return;
|
|
128907
|
+
}
|
|
128908
|
+
}
|
|
128909
|
+
/**
|
|
128021
128910
|
* Resolve the real JavaScript entry point of the globally-installed cc-connect
|
|
128022
128911
|
* package, bypassing platform wrapper scripts (.cmd / shell launchers).
|
|
128023
128912
|
*
|
|
@@ -128168,11 +129057,16 @@ function getDaemonInstructions(configDir) {
|
|
|
128168
129057
|
/**
|
|
128169
129058
|
* /cc slash command — one-click cc-connect daemon lifecycle management.
|
|
128170
129059
|
*
|
|
128171
|
-
* Typing /cc opens a picker with
|
|
129060
|
+
* Typing /cc opens a picker with four options: Start, Stop, Restart, Uninstall.
|
|
128172
129061
|
* Selecting one runs the appropriate command for the current platform:
|
|
128173
129062
|
* - macOS / Linux → cc-connect daemon start/stop/restart
|
|
128174
129063
|
* - Windows (daemon supported) → cc-connect daemon start/stop/restart
|
|
128175
129064
|
* - Windows (no daemon, pm2) → pm2 start/stop/restart cc-connect
|
|
129065
|
+
*
|
|
129066
|
+
* Uninstall removes cc-connect completely: stops the daemon, removes the
|
|
129067
|
+
* scheduled task / pm2 process, deletes ~/.cc-connect, and runs
|
|
129068
|
+
* `npm uninstall -g cc-connect`. After confirming, the machine is as if
|
|
129069
|
+
* cc-connect was never installed.
|
|
128176
129070
|
*/
|
|
128177
129071
|
const ACTIONS = [
|
|
128178
129072
|
{
|
|
@@ -128189,6 +129083,12 @@ const ACTIONS = [
|
|
|
128189
129083
|
label: "重启",
|
|
128190
129084
|
action: "restart",
|
|
128191
129085
|
description: "重启 cc-connect 后台守护进程"
|
|
129086
|
+
},
|
|
129087
|
+
{
|
|
129088
|
+
label: "卸载",
|
|
129089
|
+
action: "uninstall",
|
|
129090
|
+
description: "彻底卸载 cc-connect(守护进程 + 配置 + npm 包)",
|
|
129091
|
+
tone: "danger"
|
|
128192
129092
|
}
|
|
128193
129093
|
];
|
|
128194
129094
|
function resolveDaemonMode() {
|
|
@@ -128229,12 +129129,89 @@ function runCmd(command) {
|
|
|
128229
129129
|
});
|
|
128230
129130
|
});
|
|
128231
129131
|
}
|
|
129132
|
+
function detectCcConnectInstall() {
|
|
129133
|
+
return {
|
|
129134
|
+
entry: detectCcConnectEntry(),
|
|
129135
|
+
version: ccConnectVersion()
|
|
129136
|
+
};
|
|
129137
|
+
}
|
|
129138
|
+
function isCcConnectInstalled(install) {
|
|
129139
|
+
return install.entry !== null || install.version !== void 0;
|
|
129140
|
+
}
|
|
129141
|
+
/**
|
|
129142
|
+
* Scan pm2 process list for any cc-connect-related processes (by name or
|
|
129143
|
+
* script path). Used to catch stray/residual processes that weren't cleaned
|
|
129144
|
+
* up by the named `pm2 delete cc-connect`.
|
|
129145
|
+
*/
|
|
129146
|
+
async function findStrayCcConnectPm2ProcessNames() {
|
|
129147
|
+
const { ok, output } = await runCmd("pm2 jlist 2>nul");
|
|
129148
|
+
if (!ok || !output) return [];
|
|
129149
|
+
try {
|
|
129150
|
+
return JSON.parse(output).filter((p) => {
|
|
129151
|
+
const name = p.name ?? "";
|
|
129152
|
+
const execPath = p.pm2_env?.pm_exec_path ?? "";
|
|
129153
|
+
return name.includes("cc-connect") || execPath.includes("cc-connect");
|
|
129154
|
+
}).map((p) => p.name ?? "").filter((n) => n.length > 0);
|
|
129155
|
+
} catch {
|
|
129156
|
+
return [];
|
|
129157
|
+
}
|
|
129158
|
+
}
|
|
129159
|
+
/**
|
|
129160
|
+
* Scan a directory for entries whose name contains "cc-connect".
|
|
129161
|
+
* Returns absolute paths. Returns [] if the directory doesn't exist or
|
|
129162
|
+
* can't be read.
|
|
129163
|
+
*/
|
|
129164
|
+
async function scanDirForCcConnect(dir) {
|
|
129165
|
+
try {
|
|
129166
|
+
return (await readdir(dir)).filter((e) => e.toLowerCase().includes("cc-connect")).map((e) => join(dir, e));
|
|
129167
|
+
} catch {
|
|
129168
|
+
return [];
|
|
129169
|
+
}
|
|
129170
|
+
}
|
|
129171
|
+
/**
|
|
129172
|
+
* Find residual cc-connect files outside the main config dir.
|
|
129173
|
+
*
|
|
129174
|
+
* The main config + session dir is `~/.cc-connect` (handled separately because
|
|
129175
|
+
* it's the most critical). This function scans for stragglers that, if left
|
|
129176
|
+
* behind, would cause the next install to collide:
|
|
129177
|
+
*
|
|
129178
|
+
* - macOS launchd plists: `~/Library/LaunchAgents/cc-connect*.plist`
|
|
129179
|
+
* (if `cc-connect daemon uninstall` failed to remove them)
|
|
129180
|
+
* - Linux systemd units: `~/.config/systemd/user/cc-connect*`
|
|
129181
|
+
* (same fallback as above)
|
|
129182
|
+
* - pm2 logs: `~/.pm2/logs/cc-connect*`
|
|
129183
|
+
* (pm2 never cleans these up; resurrect doesn't need them but they
|
|
129184
|
+
* confuse debugging on next install)
|
|
129185
|
+
*
|
|
129186
|
+
* npm bin shims are deliberately NOT scanned here — `npm uninstall -g
|
|
129187
|
+
* cc-connect` (Step 4) is responsible for those, and scanning manually
|
|
129188
|
+
* risks deleting `node_modules/cc-connect` before npm gets to it.
|
|
129189
|
+
*
|
|
129190
|
+
* `excludePath` is the main config dir — already handled, so skipped here.
|
|
129191
|
+
*/
|
|
129192
|
+
async function findCcConnectResidualPaths(excludePath) {
|
|
129193
|
+
const paths = /* @__PURE__ */ new Set();
|
|
129194
|
+
const home = homedir();
|
|
129195
|
+
if (process.platform === "darwin") for (const p of await scanDirForCcConnect(join(home, "Library", "LaunchAgents"))) paths.add(p);
|
|
129196
|
+
if (process.platform === "linux") for (const p of await scanDirForCcConnect(join(home, ".config", "systemd", "user"))) paths.add(p);
|
|
129197
|
+
for (const p of await scanDirForCcConnect(join(home, ".pm2", "logs"))) paths.add(p);
|
|
129198
|
+
const existing = [];
|
|
129199
|
+
for (const p of paths) {
|
|
129200
|
+
if (p === excludePath) continue;
|
|
129201
|
+
try {
|
|
129202
|
+
await stat(p);
|
|
129203
|
+
existing.push(p);
|
|
129204
|
+
} catch {}
|
|
129205
|
+
}
|
|
129206
|
+
return existing.sort();
|
|
129207
|
+
}
|
|
128232
129208
|
async function handleCcCommand(host) {
|
|
128233
129209
|
const daemon = resolveDaemonMode();
|
|
128234
129210
|
const options = ACTIONS.map((a) => ({
|
|
128235
129211
|
label: a.label,
|
|
128236
129212
|
value: a.action,
|
|
128237
|
-
description: a.description
|
|
129213
|
+
description: a.description,
|
|
129214
|
+
tone: a.tone
|
|
128238
129215
|
}));
|
|
128239
129216
|
const picker = new ChoicePickerComponent({
|
|
128240
129217
|
title: `cc-connect 守护进程管理 (${daemon.method})`,
|
|
@@ -128242,17 +129219,12 @@ async function handleCcCommand(host) {
|
|
|
128242
129219
|
colors: host.state.theme.colors,
|
|
128243
129220
|
onSelect: (value) => {
|
|
128244
129221
|
const action = value;
|
|
128245
|
-
const label = action === "start" ? "启动" : action === "stop" ? "关闭" : "重启";
|
|
128246
|
-
const cmd = daemon.buildCmd(action);
|
|
128247
129222
|
host.restoreEditor();
|
|
128248
|
-
|
|
128249
|
-
|
|
128250
|
-
|
|
128251
|
-
|
|
128252
|
-
|
|
128253
|
-
host.refreshCcStatus();
|
|
128254
|
-
} else host.showError(`❌ ${label}失败:${output || "未知错误"}`);
|
|
128255
|
-
})();
|
|
129223
|
+
if (action === "uninstall") {
|
|
129224
|
+
confirmAndUninstall(host, daemon);
|
|
129225
|
+
return;
|
|
129226
|
+
}
|
|
129227
|
+
runLifecycleAction(host, daemon, action);
|
|
128256
129228
|
},
|
|
128257
129229
|
onCancel: () => {
|
|
128258
129230
|
host.restoreEditor();
|
|
@@ -128260,6 +129232,189 @@ async function handleCcCommand(host) {
|
|
|
128260
129232
|
});
|
|
128261
129233
|
host.mountEditorReplacement(picker);
|
|
128262
129234
|
}
|
|
129235
|
+
function runLifecycleAction(host, daemon, action) {
|
|
129236
|
+
const label = action === "start" ? "启动" : action === "stop" ? "关闭" : "重启";
|
|
129237
|
+
const cmd = daemon.buildCmd(action);
|
|
129238
|
+
host.showStatus(`正在${label} cc-connect...`);
|
|
129239
|
+
(async () => {
|
|
129240
|
+
const { ok, output } = await runCmd(cmd);
|
|
129241
|
+
if (ok) {
|
|
129242
|
+
host.showStatus(`✅ cc-connect 已${label}` + (output ? `(${output})` : ""), host.state.theme.colors.success);
|
|
129243
|
+
host.refreshCcStatus();
|
|
129244
|
+
} else host.showError(`❌ ${label}失败:${output || "未知错误"}`);
|
|
129245
|
+
})();
|
|
129246
|
+
}
|
|
129247
|
+
const CC_CONNECT_CONFIG_DIR = () => join(homedir(), ".cc-connect");
|
|
129248
|
+
function buildUninstallSummary(daemon, install, residualPaths = []) {
|
|
129249
|
+
const lines = [
|
|
129250
|
+
"将执行以下清理:",
|
|
129251
|
+
`· 停止并卸载 ${daemon.method} 守护进程`,
|
|
129252
|
+
"· 删除配置目录 ~/.cc-connect(含会话记录、配置、日志)",
|
|
129253
|
+
"· 执行 npm uninstall -g cc-connect"
|
|
129254
|
+
];
|
|
129255
|
+
if (install.version) lines.push(`· 当前版本:v${install.version}`);
|
|
129256
|
+
if (install.entry) lines.push(`· 安装路径:${install.entry}`);
|
|
129257
|
+
if (daemon.method.includes("pm2")) lines.splice(2, 0, "· 删除 pm2 进程 + 启动项(startup.bat / schtasks)");
|
|
129258
|
+
if (residualPaths.length > 0) lines.push(`· 清理 ${residualPaths.length} 个残留文件(launchd/systemd/pm2 日志)`);
|
|
129259
|
+
return lines.join("\n");
|
|
129260
|
+
}
|
|
129261
|
+
async function confirmAndUninstall(host, daemon) {
|
|
129262
|
+
const install = detectCcConnectInstall();
|
|
129263
|
+
if (!isCcConnectInstalled(install)) {
|
|
129264
|
+
host.showNotice("未识别 cc-connect 安装", "未在默认 npm 全局路径下检测到 cc-connect 安装,已中止卸载。\n建议将此情况发送给 scream,由其指导手动清理。");
|
|
129265
|
+
return;
|
|
129266
|
+
}
|
|
129267
|
+
const configDir = CC_CONNECT_CONFIG_DIR();
|
|
129268
|
+
const residualPaths = await findCcConnectResidualPaths(configDir);
|
|
129269
|
+
if (!await confirmCcConnectUninstall(host, buildUninstallSummary(daemon, install, residualPaths))) return;
|
|
129270
|
+
const spinner = host.showProgressSpinner("正在卸载 cc-connect…");
|
|
129271
|
+
const steps = [];
|
|
129272
|
+
const stopResult = await runCmd(daemon.buildCmd("stop"));
|
|
129273
|
+
steps.push({
|
|
129274
|
+
label: "停止守护进程",
|
|
129275
|
+
ok: stopResult.ok,
|
|
129276
|
+
output: stopResult.output
|
|
129277
|
+
});
|
|
129278
|
+
await cleanupSchedulerOrPm2(daemon, steps);
|
|
129279
|
+
try {
|
|
129280
|
+
await rm(configDir, {
|
|
129281
|
+
recursive: true,
|
|
129282
|
+
force: true
|
|
129283
|
+
});
|
|
129284
|
+
steps.push({
|
|
129285
|
+
label: `删除 ${configDir}`,
|
|
129286
|
+
ok: true,
|
|
129287
|
+
output: ""
|
|
129288
|
+
});
|
|
129289
|
+
} catch (error) {
|
|
129290
|
+
steps.push({
|
|
129291
|
+
label: `删除 ${configDir}`,
|
|
129292
|
+
ok: false,
|
|
129293
|
+
output: error instanceof Error ? error.message : String(error)
|
|
129294
|
+
});
|
|
129295
|
+
}
|
|
129296
|
+
if (residualPaths.length > 0) {
|
|
129297
|
+
const deleted = [];
|
|
129298
|
+
const failed = [];
|
|
129299
|
+
for (const p of residualPaths) try {
|
|
129300
|
+
await rm(p, {
|
|
129301
|
+
recursive: true,
|
|
129302
|
+
force: true
|
|
129303
|
+
});
|
|
129304
|
+
deleted.push(p);
|
|
129305
|
+
} catch (error) {
|
|
129306
|
+
failed.push(`${p}: ${error instanceof Error ? error.message : String(error)}`);
|
|
129307
|
+
}
|
|
129308
|
+
steps.push({
|
|
129309
|
+
label: `清理残留文件 (${residualPaths.length})`,
|
|
129310
|
+
ok: failed.length === 0,
|
|
129311
|
+
output: [...deleted, ...failed].join("\n")
|
|
129312
|
+
});
|
|
129313
|
+
}
|
|
129314
|
+
const npmResult = await runCmd("npm uninstall -g cc-connect");
|
|
129315
|
+
steps.push({
|
|
129316
|
+
label: "npm uninstall -g cc-connect",
|
|
129317
|
+
ok: npmResult.ok,
|
|
129318
|
+
output: npmResult.output
|
|
129319
|
+
});
|
|
129320
|
+
const allOk = steps.every((s) => s.ok);
|
|
129321
|
+
spinner.stop({
|
|
129322
|
+
ok: allOk,
|
|
129323
|
+
label: allOk ? "cc-connect 已彻底卸载" : "部分步骤失败,详见下方提示"
|
|
129324
|
+
});
|
|
129325
|
+
const summary = steps.map((s) => `${s.ok ? "✓" : "✗"} ${s.label}${s.output ? `:${s.output}` : ""}`).join("\n");
|
|
129326
|
+
if (allOk) host.showNotice("cc-connect 已卸载", `${summary}\n\n建议重启 Scream Code 以确保 cc-connect 状态完全清空。`);
|
|
129327
|
+
else host.showNotice("卸载部分失败", summary);
|
|
129328
|
+
host.refreshCcStatus();
|
|
129329
|
+
}
|
|
129330
|
+
async function cleanupSchedulerOrPm2(daemon, steps) {
|
|
129331
|
+
if (daemon.method.includes("pm2")) {
|
|
129332
|
+
const pm2Delete = await runCmd("pm2 delete cc-connect 2>nul");
|
|
129333
|
+
steps.push({
|
|
129334
|
+
label: "pm2 delete cc-connect",
|
|
129335
|
+
ok: pm2Delete.ok,
|
|
129336
|
+
output: pm2Delete.output
|
|
129337
|
+
});
|
|
129338
|
+
const strayNames = await findStrayCcConnectPm2ProcessNames();
|
|
129339
|
+
for (const name of strayNames) {
|
|
129340
|
+
if (name === "cc-connect") continue;
|
|
129341
|
+
if (!/^[a-zA-Z0-9._-]+$/.test(name)) continue;
|
|
129342
|
+
const r = await runCmd(`pm2 delete "${name}" 2>nul`);
|
|
129343
|
+
steps.push({
|
|
129344
|
+
label: `pm2 delete ${name} (残留)`,
|
|
129345
|
+
ok: r.ok,
|
|
129346
|
+
output: r.output
|
|
129347
|
+
});
|
|
129348
|
+
}
|
|
129349
|
+
const pm2Save = await runCmd("pm2 save 2>nul");
|
|
129350
|
+
steps.push({
|
|
129351
|
+
label: "pm2 save",
|
|
129352
|
+
ok: pm2Save.ok,
|
|
129353
|
+
output: pm2Save.output
|
|
129354
|
+
});
|
|
129355
|
+
const startupBat = await runCmd(`if exist "%APPDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\cc-connect-startup.bat" del /q "%APPDATA%\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\cc-connect-startup.bat"`);
|
|
129356
|
+
steps.push({
|
|
129357
|
+
label: "删除 cc-connect-startup.bat",
|
|
129358
|
+
ok: startupBat.ok,
|
|
129359
|
+
output: startupBat.output
|
|
129360
|
+
});
|
|
129361
|
+
const schtask = await runCmd("schtasks /query /tn \"cc-connect-pm2\" 2>nul && schtasks /delete /tn \"cc-connect-pm2\" /f || echo no-such-task");
|
|
129362
|
+
steps.push({
|
|
129363
|
+
label: "删除 schtasks cc-connect-pm2",
|
|
129364
|
+
ok: schtask.ok,
|
|
129365
|
+
output: schtask.output
|
|
129366
|
+
});
|
|
129367
|
+
return;
|
|
129368
|
+
}
|
|
129369
|
+
if (process.platform === "win32") {
|
|
129370
|
+
const daemonUninstall = await runCmd("cc-connect daemon uninstall");
|
|
129371
|
+
steps.push({
|
|
129372
|
+
label: "cc-connect daemon uninstall",
|
|
129373
|
+
ok: daemonUninstall.ok,
|
|
129374
|
+
output: daemonUninstall.output
|
|
129375
|
+
});
|
|
129376
|
+
const schtask = await runCmd("schtasks /query /tn \"cc-connect-daemon\" 2>nul && schtasks /delete /tn \"cc-connect-daemon\" /f || echo no-such-task");
|
|
129377
|
+
steps.push({
|
|
129378
|
+
label: "删除 schtasks cc-connect-daemon",
|
|
129379
|
+
ok: schtask.ok,
|
|
129380
|
+
output: schtask.output
|
|
129381
|
+
});
|
|
129382
|
+
return;
|
|
129383
|
+
}
|
|
129384
|
+
const daemonUninstall = await runCmd("cc-connect daemon uninstall");
|
|
129385
|
+
steps.push({
|
|
129386
|
+
label: "cc-connect daemon uninstall",
|
|
129387
|
+
ok: daemonUninstall.ok,
|
|
129388
|
+
output: daemonUninstall.output
|
|
129389
|
+
});
|
|
129390
|
+
}
|
|
129391
|
+
function confirmCcConnectUninstall(host, summary) {
|
|
129392
|
+
return new Promise((resolve) => {
|
|
129393
|
+
const picker = new ChoicePickerComponent({
|
|
129394
|
+
title: "确认彻底卸载 cc-connect?",
|
|
129395
|
+
hint: "此操作不可撤销,所有 cc-connect 数据将被清除",
|
|
129396
|
+
options: [{
|
|
129397
|
+
value: "no",
|
|
129398
|
+
label: "取消"
|
|
129399
|
+
}, {
|
|
129400
|
+
value: "yes",
|
|
129401
|
+
label: "确认卸载",
|
|
129402
|
+
tone: "danger",
|
|
129403
|
+
description: summary
|
|
129404
|
+
}],
|
|
129405
|
+
colors: host.state.theme.colors,
|
|
129406
|
+
onSelect: (value) => {
|
|
129407
|
+
host.restoreEditor();
|
|
129408
|
+
resolve(value === "yes");
|
|
129409
|
+
},
|
|
129410
|
+
onCancel: () => {
|
|
129411
|
+
host.restoreEditor();
|
|
129412
|
+
resolve(false);
|
|
129413
|
+
}
|
|
129414
|
+
});
|
|
129415
|
+
host.mountEditorReplacement(picker);
|
|
129416
|
+
});
|
|
129417
|
+
}
|
|
128263
129418
|
//#endregion
|
|
128264
129419
|
//#region src/utils/persistence.ts
|
|
128265
129420
|
/**
|
|
@@ -128331,7 +129486,7 @@ async function appendJsonlLine(filePath, lineSchema, value) {
|
|
|
128331
129486
|
//#endregion
|
|
128332
129487
|
//#region src/cli/update/cache.ts
|
|
128333
129488
|
const UpdateCacheSchema = z.object({
|
|
128334
|
-
source: z.literal("
|
|
129489
|
+
source: z.literal("npm"),
|
|
128335
129490
|
checkedAt: z.string().min(1).nullable(),
|
|
128336
129491
|
latest: z.string().min(1).nullable()
|
|
128337
129492
|
}).strict();
|
|
@@ -128347,35 +129502,43 @@ async function writeUpdateCache(value, filePath = getUpdateStateFile()) {
|
|
|
128347
129502
|
}
|
|
128348
129503
|
//#endregion
|
|
128349
129504
|
//#region src/cli/update/cdn.ts
|
|
129505
|
+
const NPM_TIMEOUT_MS = 15e3;
|
|
128350
129506
|
/**
|
|
128351
|
-
*
|
|
129507
|
+
* Query the latest published Scream Code version from the npm registry
|
|
129508
|
+
* via `npm view scream-code version`.
|
|
128352
129509
|
*
|
|
128353
|
-
* **Throws** on any failure (network error,
|
|
128354
|
-
*
|
|
129510
|
+
* **Throws** on any failure (network error, npm not in PATH, non-semver
|
|
129511
|
+
* output). Callers must catch — `refreshUpdateCache` deliberately lets the
|
|
128355
129512
|
* error propagate so the existing cache stays intact instead of being
|
|
128356
129513
|
* overwritten with a null `latest` on a transient blip.
|
|
128357
129514
|
*
|
|
128358
|
-
* `
|
|
128359
|
-
*/
|
|
128360
|
-
async function
|
|
128361
|
-
const
|
|
128362
|
-
|
|
128363
|
-
|
|
128364
|
-
|
|
128365
|
-
|
|
129515
|
+
* `execFileImpl` is injectable for tests; defaults to a promisified spawn.
|
|
129516
|
+
*/
|
|
129517
|
+
async function fetchLatestVersionFromNpm(execFileImpl = execFile) {
|
|
129518
|
+
const { stdout } = await promisify(execFileImpl)("npm", [
|
|
129519
|
+
"view",
|
|
129520
|
+
"scream-code",
|
|
129521
|
+
"version"
|
|
129522
|
+
], {
|
|
129523
|
+
timeout: NPM_TIMEOUT_MS,
|
|
129524
|
+
maxBuffer: 1024,
|
|
129525
|
+
shell: process.platform === "win32"
|
|
129526
|
+
});
|
|
129527
|
+
const raw = stdout.trim();
|
|
129528
|
+
if (valid(raw) === null) throw new Error(`npm view 返回的版本号不是合法 semver: ${JSON.stringify(raw)}`);
|
|
128366
129529
|
return raw;
|
|
128367
129530
|
}
|
|
128368
129531
|
//#endregion
|
|
128369
129532
|
//#region src/cli/update/refresh.ts
|
|
128370
129533
|
async function refreshUpdateCache(overrides = {}) {
|
|
128371
129534
|
const resolved = {
|
|
128372
|
-
fetchLatest: overrides.fetchLatest ?? (() =>
|
|
129535
|
+
fetchLatest: overrides.fetchLatest ?? (() => fetchLatestVersionFromNpm()),
|
|
128373
129536
|
writeCache: overrides.writeCache ?? writeUpdateCache,
|
|
128374
129537
|
now: overrides.now ?? (() => /* @__PURE__ */ new Date())
|
|
128375
129538
|
};
|
|
128376
129539
|
const latest = await resolved.fetchLatest();
|
|
128377
129540
|
const cache = {
|
|
128378
|
-
source: "
|
|
129541
|
+
source: "npm",
|
|
128379
129542
|
checkedAt: resolved.now().toISOString(),
|
|
128380
129543
|
latest
|
|
128381
129544
|
};
|
|
@@ -128395,16 +129558,10 @@ function selectUpdateTarget(currentVersion, latest) {
|
|
|
128395
129558
|
/**
|
|
128396
129559
|
* /update slash command — manually install the latest Scream Code update.
|
|
128397
129560
|
*
|
|
128398
|
-
* Runs `
|
|
128399
|
-
*
|
|
128400
|
-
* error detection with user-friendly Chinese prompts.
|
|
129561
|
+
* Runs `npm install -g scream-code@latest`, then asks the user to restart.
|
|
129562
|
+
* Network-error detection with user-friendly Chinese prompts.
|
|
128401
129563
|
*/
|
|
128402
|
-
const
|
|
128403
|
-
const TIMEOUTS = {
|
|
128404
|
-
"git pull": 12e4,
|
|
128405
|
-
"pnpm install": 18e4,
|
|
128406
|
-
"pnpm -r build": 18e4
|
|
128407
|
-
};
|
|
129564
|
+
const INSTALL_TIMEOUT_MS = 3e5;
|
|
128408
129565
|
const NETWORK_ERROR_PATTERNS = [
|
|
128409
129566
|
/ETIMEDOUT/i,
|
|
128410
129567
|
/ENOTFOUND/i,
|
|
@@ -128425,12 +129582,12 @@ const NETWORK_ERROR_PATTERNS = [
|
|
|
128425
129582
|
function isNetworkError(message) {
|
|
128426
129583
|
return NETWORK_ERROR_PATTERNS.some((p) => p.test(message));
|
|
128427
129584
|
}
|
|
128428
|
-
async function runInstallStep(cmd, args, cwd, label) {
|
|
128429
|
-
const timeoutMs = TIMEOUTS[`${cmd} ${args[0]}`] ?? 12e4;
|
|
129585
|
+
async function runInstallStep(cmd, args, cwd, label, timeoutMs = INSTALL_TIMEOUT_MS) {
|
|
128430
129586
|
return new Promise((resolve) => {
|
|
128431
129587
|
const child = spawn(cmd, args, {
|
|
128432
129588
|
cwd,
|
|
128433
|
-
stdio: "pipe"
|
|
129589
|
+
stdio: "pipe",
|
|
129590
|
+
shell: process.platform === "win32"
|
|
128434
129591
|
});
|
|
128435
129592
|
let stderr = "";
|
|
128436
129593
|
let settled = false;
|
|
@@ -128499,33 +129656,15 @@ async function handleUpdateCommand(host) {
|
|
|
128499
129656
|
return;
|
|
128500
129657
|
}
|
|
128501
129658
|
host.showStatus(`正在更新到 ${target.version}...`);
|
|
128502
|
-
|
|
128503
|
-
|
|
128504
|
-
|
|
128505
|
-
|
|
128506
|
-
|
|
128507
|
-
|
|
128508
|
-
|
|
128509
|
-
|
|
128510
|
-
|
|
128511
|
-
},
|
|
128512
|
-
{
|
|
128513
|
-
label: "安装依赖",
|
|
128514
|
-
cmd: "pnpm",
|
|
128515
|
-
args: ["install"]
|
|
128516
|
-
},
|
|
128517
|
-
{
|
|
128518
|
-
label: "编译",
|
|
128519
|
-
cmd: "pnpm",
|
|
128520
|
-
args: ["-r", "build"]
|
|
128521
|
-
}
|
|
128522
|
-
]) {
|
|
128523
|
-
host.showStatus(`正在${step.label}...`);
|
|
128524
|
-
const result = await runInstallStep(step.cmd, step.args, INSTALL_DIR, step.label);
|
|
128525
|
-
if (!result.ok) {
|
|
128526
|
-
host.showError(`❌ ${result.message}`);
|
|
128527
|
-
return;
|
|
128528
|
-
}
|
|
129659
|
+
host.showStatus("正在通过 npm 安装最新版本...");
|
|
129660
|
+
const result = await runInstallStep("npm", [
|
|
129661
|
+
"install",
|
|
129662
|
+
"-g",
|
|
129663
|
+
"scream-code@latest"
|
|
129664
|
+
], void 0, "安装 scream-code");
|
|
129665
|
+
if (!result.ok) {
|
|
129666
|
+
host.showError(`❌ ${result.message}`);
|
|
129667
|
+
return;
|
|
128529
129668
|
}
|
|
128530
129669
|
host.showStatus("✅ 更新完成。请重启 Scream Code 以使用新版本。", host.state.theme.colors.success);
|
|
128531
129670
|
host.setAppState({
|
|
@@ -129623,18 +130762,20 @@ function buildOptions(host, skills, plugins, marketplace) {
|
|
|
129623
130762
|
});
|
|
129624
130763
|
for (const skill of skills) {
|
|
129625
130764
|
const actionKeys = {};
|
|
129626
|
-
if (skill.pluginId !== void 0)
|
|
129627
|
-
|
|
129628
|
-
|
|
129629
|
-
|
|
129630
|
-
|
|
130765
|
+
if (skill.pluginId !== void 0) {
|
|
130766
|
+
const plugin = plugins.find((p) => p.id === skill.pluginId);
|
|
130767
|
+
actionKeys["d"] = () => {
|
|
130768
|
+
host.restoreEditor();
|
|
130769
|
+
uninstallByPluginId(host, skill.pluginId, plugin);
|
|
130770
|
+
};
|
|
130771
|
+
} else actionKeys["d"] = () => {
|
|
129631
130772
|
host.restoreEditor();
|
|
129632
130773
|
uninstallManualSkill(host, skill);
|
|
129633
130774
|
};
|
|
129634
130775
|
options.push({
|
|
129635
130776
|
value: `activate:${skill.name}`,
|
|
129636
130777
|
label: skill.name,
|
|
129637
|
-
description: formatSkillDescription(skill),
|
|
130778
|
+
description: formatSkillDescription(skill, plugins),
|
|
129638
130779
|
actionKeys
|
|
129639
130780
|
});
|
|
129640
130781
|
}
|
|
@@ -129710,7 +130851,7 @@ async function installInjectActivate(host, source) {
|
|
|
129710
130851
|
host.sendSkillActivation(session, first.name, "");
|
|
129711
130852
|
return;
|
|
129712
130853
|
}
|
|
129713
|
-
await pickAndActivateSkill(host, pluginSkills);
|
|
130854
|
+
await pickAndActivateSkill(host, pluginSkills, [summary]);
|
|
129714
130855
|
} catch (error) {
|
|
129715
130856
|
spinner.stop({
|
|
129716
130857
|
ok: false,
|
|
@@ -129719,7 +130860,7 @@ async function installInjectActivate(host, source) {
|
|
|
129719
130860
|
host.showError(`安装失败: ${error instanceof Error ? error.message : String(error)}`);
|
|
129720
130861
|
}
|
|
129721
130862
|
}
|
|
129722
|
-
async function pickAndActivateSkill(host, skills) {
|
|
130863
|
+
async function pickAndActivateSkill(host, skills, plugins = []) {
|
|
129723
130864
|
const session = host.session;
|
|
129724
130865
|
if (!session) return;
|
|
129725
130866
|
const picker = new ChoicePickerComponent({
|
|
@@ -129728,7 +130869,7 @@ async function pickAndActivateSkill(host, skills) {
|
|
|
129728
130869
|
options: skills.map((skill) => ({
|
|
129729
130870
|
value: skill.name,
|
|
129730
130871
|
label: skill.name,
|
|
129731
|
-
description: formatSkillDescription(skill)
|
|
130872
|
+
description: formatSkillDescription(skill, plugins)
|
|
129732
130873
|
})),
|
|
129733
130874
|
colors: host.state.theme.colors,
|
|
129734
130875
|
searchable: true,
|
|
@@ -129743,18 +130884,18 @@ async function pickAndActivateSkill(host, skills) {
|
|
|
129743
130884
|
});
|
|
129744
130885
|
host.mountEditorReplacement(picker);
|
|
129745
130886
|
}
|
|
129746
|
-
async function uninstallByPluginId(host, pluginId) {
|
|
130887
|
+
async function uninstallByPluginId(host, pluginId, plugin) {
|
|
129747
130888
|
const session = host.session;
|
|
129748
130889
|
if (!session) {
|
|
129749
130890
|
host.showError("未连接到会话。请先创建或恢复一个会话。");
|
|
129750
130891
|
return;
|
|
129751
130892
|
}
|
|
129752
|
-
|
|
129753
|
-
|
|
129754
|
-
plugins = await session.listPlugins();
|
|
130893
|
+
if (plugin === void 0) try {
|
|
130894
|
+
plugin = (await session.listPlugins()).find((p) => p.id === pluginId);
|
|
129755
130895
|
} catch {}
|
|
129756
|
-
const label =
|
|
129757
|
-
|
|
130896
|
+
const label = plugin?.displayName ?? pluginId;
|
|
130897
|
+
const skillCount = plugin?.skillCount;
|
|
130898
|
+
if (!await confirmUninstall(host, label, skillCount !== void 0 && skillCount > 0 ? `将卸载整个包(共 ${skillCount} 个 Skill),无法只删除单个 Skill` : "将卸载整个 Skill 包")) {
|
|
129758
130899
|
await openSkillCenter(host);
|
|
129759
130900
|
return;
|
|
129760
130901
|
}
|
|
@@ -129831,10 +130972,13 @@ async function confirmUninstall(host, label, description) {
|
|
|
129831
130972
|
host.mountEditorReplacement(picker);
|
|
129832
130973
|
});
|
|
129833
130974
|
}
|
|
129834
|
-
function formatSkillDescription(skill) {
|
|
130975
|
+
function formatSkillDescription(skill, plugins = []) {
|
|
129835
130976
|
const parts = [];
|
|
129836
130977
|
if (skill.source) parts.push(`来源: ${skill.source}`);
|
|
129837
|
-
if (skill.pluginId !== void 0)
|
|
130978
|
+
if (skill.pluginId !== void 0) {
|
|
130979
|
+
const label = plugins.find((p) => p.id === skill.pluginId)?.displayName ?? skill.pluginId;
|
|
130980
|
+
parts.push(`插件: ${label}`);
|
|
130981
|
+
}
|
|
129838
130982
|
if (skill.description) parts.push(truncate$1(skill.description, SKILL_DESC_MAX));
|
|
129839
130983
|
return parts.join(" · ");
|
|
129840
130984
|
}
|
|
@@ -129969,6 +131113,294 @@ async function handleBtwCommand(host, args) {
|
|
|
129969
131113
|
}
|
|
129970
131114
|
}
|
|
129971
131115
|
//#endregion
|
|
131116
|
+
//#region src/tui/utils/loop-limit.ts
|
|
131117
|
+
const TIME_UNITS_MS = {
|
|
131118
|
+
s: 1e3,
|
|
131119
|
+
sec: 1e3,
|
|
131120
|
+
secs: 1e3,
|
|
131121
|
+
second: 1e3,
|
|
131122
|
+
seconds: 1e3,
|
|
131123
|
+
m: 6e4,
|
|
131124
|
+
min: 6e4,
|
|
131125
|
+
mins: 6e4,
|
|
131126
|
+
minute: 6e4,
|
|
131127
|
+
minutes: 6e4,
|
|
131128
|
+
h: 36e5,
|
|
131129
|
+
hr: 36e5,
|
|
131130
|
+
hrs: 36e5,
|
|
131131
|
+
hour: 36e5,
|
|
131132
|
+
hours: 36e5
|
|
131133
|
+
};
|
|
131134
|
+
const LOOP_USAGE = "用法:/loop [次数|时长] [提示词]。示例:/loop 10、/loop 5m、/loop 10 继续优化";
|
|
131135
|
+
/**
|
|
131136
|
+
* 将 `/loop` 参数解析为可选的前置限制和可选的内联提示词。
|
|
131137
|
+
* 看起来像限制(以数字或正负号开头)但解析失败的 token 视为硬错误;
|
|
131138
|
+
* 其他内容都视为提示词文本,因此 `/loop` 后面跟普通 prose 会开启无限制循环。
|
|
131139
|
+
* 失败时返回错误信息字符串。
|
|
131140
|
+
*/
|
|
131141
|
+
const VERIFY_USAGE = "验证命令需用引号包裹,例如:--verify \"pnpm lint\"";
|
|
131142
|
+
function extractVerifyFlag(input) {
|
|
131143
|
+
const match = input.match(/--verify\s+["']([^"']+)["']/);
|
|
131144
|
+
if (match && match[1]) {
|
|
131145
|
+
const command = match[1];
|
|
131146
|
+
const remaining = input.replace(match[0], "").replace(/\s{2,}/g, " ").trim();
|
|
131147
|
+
return {
|
|
131148
|
+
verifier: { command },
|
|
131149
|
+
remaining
|
|
131150
|
+
};
|
|
131151
|
+
}
|
|
131152
|
+
if (/\b--verify\b/.test(input)) return VERIFY_USAGE;
|
|
131153
|
+
}
|
|
131154
|
+
function parseLoopLimitArgs(args) {
|
|
131155
|
+
const trimmed = args.trim();
|
|
131156
|
+
if (!trimmed) return {};
|
|
131157
|
+
const extracted = extractVerifyFlag(trimmed);
|
|
131158
|
+
if (typeof extracted === "string") return extracted;
|
|
131159
|
+
const verifier = extracted?.verifier;
|
|
131160
|
+
const remaining = extracted ? extracted.remaining : trimmed;
|
|
131161
|
+
if (!remaining) return verifier ? { verifier } : {};
|
|
131162
|
+
const firstSpace = remaining.search(/\s/);
|
|
131163
|
+
const firstToken = firstSpace === -1 ? remaining : remaining.slice(0, firstSpace);
|
|
131164
|
+
const rest = firstSpace === -1 ? "" : remaining.slice(firstSpace + 1).trim();
|
|
131165
|
+
const token = firstToken.toLowerCase();
|
|
131166
|
+
if (!/^[+-]?\d/.test(token)) return {
|
|
131167
|
+
prompt: remaining,
|
|
131168
|
+
verifier
|
|
131169
|
+
};
|
|
131170
|
+
if (/^[+-]?\d+$/.test(token)) {
|
|
131171
|
+
if (token.startsWith("-")) return "循环次数必须是正整数。";
|
|
131172
|
+
if (rest) {
|
|
131173
|
+
const restTokens = rest.split(/\s+/);
|
|
131174
|
+
const firstRestToken = restTokens[0];
|
|
131175
|
+
if (firstRestToken !== void 0) {
|
|
131176
|
+
const unitMs = TIME_UNITS_MS[firstRestToken.toLowerCase()];
|
|
131177
|
+
if (unitMs !== void 0) {
|
|
131178
|
+
const limit = makeDuration(token, unitMs);
|
|
131179
|
+
if (typeof limit === "string") return limit;
|
|
131180
|
+
return {
|
|
131181
|
+
limit,
|
|
131182
|
+
prompt: restTokens.slice(1).join(" ").trim() || void 0,
|
|
131183
|
+
verifier
|
|
131184
|
+
};
|
|
131185
|
+
}
|
|
131186
|
+
}
|
|
131187
|
+
}
|
|
131188
|
+
const limit = makeIterations(token);
|
|
131189
|
+
if (typeof limit === "string") return limit;
|
|
131190
|
+
return {
|
|
131191
|
+
limit,
|
|
131192
|
+
prompt: rest || void 0,
|
|
131193
|
+
verifier
|
|
131194
|
+
};
|
|
131195
|
+
}
|
|
131196
|
+
const duration = parseCompoundDuration(token);
|
|
131197
|
+
if (duration !== void 0) {
|
|
131198
|
+
if (typeof duration === "string") return duration;
|
|
131199
|
+
return {
|
|
131200
|
+
limit: duration,
|
|
131201
|
+
prompt: rest || void 0,
|
|
131202
|
+
verifier
|
|
131203
|
+
};
|
|
131204
|
+
}
|
|
131205
|
+
return LOOP_USAGE;
|
|
131206
|
+
}
|
|
131207
|
+
function makeIterations(amountText) {
|
|
131208
|
+
const amount = Number(amountText);
|
|
131209
|
+
if (!Number.isSafeInteger(amount) || amount <= 0) return "循环次数必须是正整数。";
|
|
131210
|
+
return {
|
|
131211
|
+
kind: "iterations",
|
|
131212
|
+
iterations: amount
|
|
131213
|
+
};
|
|
131214
|
+
}
|
|
131215
|
+
function makeDuration(amountText, unitMs) {
|
|
131216
|
+
const amount = Number(amountText);
|
|
131217
|
+
if (!Number.isSafeInteger(amount) || amount <= 0) return "循环时长必须为正数。";
|
|
131218
|
+
return {
|
|
131219
|
+
kind: "duration",
|
|
131220
|
+
durationMs: amount * unitMs
|
|
131221
|
+
};
|
|
131222
|
+
}
|
|
131223
|
+
function parseCompoundDuration(token) {
|
|
131224
|
+
if (!/^(?:\d+[a-z]+)+$/.test(token)) return void 0;
|
|
131225
|
+
const segments = token.match(/\d+[a-z]+/g);
|
|
131226
|
+
if (!segments) return void 0;
|
|
131227
|
+
let totalMs = 0;
|
|
131228
|
+
for (const segment of segments) {
|
|
131229
|
+
const match = /^(\d+)([a-z]+)$/.exec(segment);
|
|
131230
|
+
if (!match) return LOOP_USAGE;
|
|
131231
|
+
const unitName = match[2];
|
|
131232
|
+
if (unitName === void 0) return LOOP_USAGE;
|
|
131233
|
+
const unitMs = TIME_UNITS_MS[unitName];
|
|
131234
|
+
if (unitMs === void 0) return "循环时长单位必须是秒、分钟或小时。";
|
|
131235
|
+
const amount = Number(match[1]);
|
|
131236
|
+
if (!Number.isSafeInteger(amount) || amount <= 0) return "循环时长必须为正数。";
|
|
131237
|
+
totalMs += amount * unitMs;
|
|
131238
|
+
}
|
|
131239
|
+
if (totalMs <= 0) return "循环时长必须为正数。";
|
|
131240
|
+
return {
|
|
131241
|
+
kind: "duration",
|
|
131242
|
+
durationMs: totalMs
|
|
131243
|
+
};
|
|
131244
|
+
}
|
|
131245
|
+
function createLoopLimitRuntime(config, nowMs = Date.now()) {
|
|
131246
|
+
if (!config) return void 0;
|
|
131247
|
+
if (config.kind === "iterations") return {
|
|
131248
|
+
kind: "iterations",
|
|
131249
|
+
initial: config.iterations,
|
|
131250
|
+
remaining: config.iterations
|
|
131251
|
+
};
|
|
131252
|
+
return {
|
|
131253
|
+
kind: "duration",
|
|
131254
|
+
durationMs: config.durationMs,
|
|
131255
|
+
deadlineMs: nowMs + config.durationMs
|
|
131256
|
+
};
|
|
131257
|
+
}
|
|
131258
|
+
function consumeLoopLimitIteration(limit, nowMs = Date.now()) {
|
|
131259
|
+
if (!limit) return true;
|
|
131260
|
+
if (limit.kind === "duration") return nowMs < limit.deadlineMs;
|
|
131261
|
+
if (limit.remaining <= 0) return false;
|
|
131262
|
+
limit.remaining -= 1;
|
|
131263
|
+
return true;
|
|
131264
|
+
}
|
|
131265
|
+
function isLoopLimitExpired(limit, nowMs = Date.now()) {
|
|
131266
|
+
if (!limit) return false;
|
|
131267
|
+
if (limit.kind === "duration") return nowMs >= limit.deadlineMs;
|
|
131268
|
+
return limit.remaining <= 0;
|
|
131269
|
+
}
|
|
131270
|
+
function describeLoopLimit(config) {
|
|
131271
|
+
if (config.kind === "iterations") return `${config.iterations} 次`;
|
|
131272
|
+
return formatDuration$1(config.durationMs);
|
|
131273
|
+
}
|
|
131274
|
+
function describeLoopLimitRuntime(limit, nowMs = Date.now()) {
|
|
131275
|
+
if (limit.kind === "iterations") return `剩余 ${limit.remaining}/${limit.initial} 次`;
|
|
131276
|
+
const remainingMs = limit.deadlineMs - nowMs;
|
|
131277
|
+
if (remainingMs <= 0) return "已过期";
|
|
131278
|
+
return `剩余 ${formatDuration$1(remainingMs)}`;
|
|
131279
|
+
}
|
|
131280
|
+
function formatDuration$1(durationMs) {
|
|
131281
|
+
if (durationMs % 36e5 === 0) return `${durationMs / 36e5} 小时`;
|
|
131282
|
+
if (durationMs % 6e4 === 0) return `${durationMs / 6e4} 分钟`;
|
|
131283
|
+
return `${durationMs / 1e3} 秒`;
|
|
131284
|
+
}
|
|
131285
|
+
//#endregion
|
|
131286
|
+
//#region src/tui/commands/loop.ts
|
|
131287
|
+
const DEFAULT_VERIFY_TIMEOUT_MS = 6e4;
|
|
131288
|
+
function makeVerifier(command) {
|
|
131289
|
+
return {
|
|
131290
|
+
command,
|
|
131291
|
+
timeoutMs: DEFAULT_VERIFY_TIMEOUT_MS
|
|
131292
|
+
};
|
|
131293
|
+
}
|
|
131294
|
+
/**
|
|
131295
|
+
* 循环模式不能每轮等用户审批,开启时若处于 manual 权限,自动切到 auto。
|
|
131296
|
+
* 失败时不阻塞 loop 开启,仅静默跳过。
|
|
131297
|
+
*/
|
|
131298
|
+
async function ensureAutoPermission(host) {
|
|
131299
|
+
if (host.state.appState.permissionMode !== "manual") return;
|
|
131300
|
+
try {
|
|
131301
|
+
await host.requireSession().setPermission("auto");
|
|
131302
|
+
host.setAppState({ permissionMode: "auto" });
|
|
131303
|
+
host.showStatus("权限已切到 auto(循环期间不再弹审批)。");
|
|
131304
|
+
} catch {}
|
|
131305
|
+
}
|
|
131306
|
+
/**
|
|
131307
|
+
* 循环模式(无状态重试)。
|
|
131308
|
+
*
|
|
131309
|
+
* 定位:自动重试机 + 客观验证门。每轮重发同一条 prompt,AI 不记得上一轮
|
|
131310
|
+
* 的输出。适合配 `--verify` 验证命令,让客观 exit code 决定循环何时结束。
|
|
131311
|
+
*
|
|
131312
|
+
* 适合场景:任务与上次结果无关(等 CI、轮询健康检查、等服务起来、单次
|
|
131313
|
+
* 可能失败需要重试几次的幂等任务)。
|
|
131314
|
+
*
|
|
131315
|
+
* 不适合:任务需要根据上次失败调整策略 → 用 /goal(AI 带工作笔记迭代)。
|
|
131316
|
+
*
|
|
131317
|
+
* 行为:
|
|
131318
|
+
* - /loop (未开启)显示帮助
|
|
131319
|
+
* - /loop (已开启)关闭循环模式
|
|
131320
|
+
* - /loop 10 [提示词] 开启循环,限制 10 次
|
|
131321
|
+
* - /loop 5m [提示词] 开启循环,限制 5 分钟
|
|
131322
|
+
* - /loop <提示词> (已暂停)恢复循环并使用该提示词
|
|
131323
|
+
* - /loop 10 ... --verify "命令" 每轮后跑验证命令,通过即停
|
|
131324
|
+
*/
|
|
131325
|
+
async function handleLoopCommand(host, args) {
|
|
131326
|
+
const trimmed = args.trim();
|
|
131327
|
+
if (host.state.appState.loopModeEnabled) {
|
|
131328
|
+
if (!trimmed) {
|
|
131329
|
+
disableLoopMode(host, "循环模式已关闭。");
|
|
131330
|
+
return;
|
|
131331
|
+
}
|
|
131332
|
+
const parsed = parseLoopLimitArgs(args);
|
|
131333
|
+
if (typeof parsed === "string") {
|
|
131334
|
+
host.showError(parsed);
|
|
131335
|
+
return;
|
|
131336
|
+
}
|
|
131337
|
+
const wasPaused = host.state.appState.loopPrompt === void 0;
|
|
131338
|
+
const loopLimit = parsed.limit ? createLoopLimitRuntime(parsed.limit) : host.state.appState.loopLimit;
|
|
131339
|
+
const loopPrompt = parsed.prompt ?? host.state.appState.loopPrompt;
|
|
131340
|
+
const loopVerifier = parsed.verifier ? makeVerifier(parsed.verifier.command) : host.state.appState.loopVerifier;
|
|
131341
|
+
host.setAppState({
|
|
131342
|
+
loopLimit,
|
|
131343
|
+
loopPrompt,
|
|
131344
|
+
loopVerifier
|
|
131345
|
+
});
|
|
131346
|
+
if (wasPaused && loopPrompt !== void 0) host.sendNormalUserInput(loopPrompt);
|
|
131347
|
+
else host.showStatus("循环提示词已更新。");
|
|
131348
|
+
return;
|
|
131349
|
+
}
|
|
131350
|
+
if (!trimmed) {
|
|
131351
|
+
host.showNotice("/loop 循环模式", "无状态重试:每轮重发同一条 prompt,AI 不记得上一轮输出。配 --verify 验证命令,让客观 exit code 决定循环何时结束。\n\n用法:/loop [次数|时长] [提示词] [--verify \"验证命令\"]\n· /loop 10 [提示词] — 限制 10 次迭代\n· /loop 5m [提示词] — 限制 5 分钟\n· /loop 1h30m [提示词] — 组合时长限制\n· /loop 10 修复 lint --verify \"pnpm lint\" — 每轮后跑验证,通过即停\n\n适合:等 CI 通过、轮询健康检查、单次可能失败需重试的幂等任务。\n不适合:需要根据上次失败调整策略 → 用 /goal(AI 带工作笔记迭代)。\n\n按 Esc 暂停当前迭代;再次输入 /loop 关闭循环。");
|
|
131352
|
+
return;
|
|
131353
|
+
}
|
|
131354
|
+
if (host.state.appState.model.trim().length === 0) {
|
|
131355
|
+
host.showError(LLM_NOT_SET_MESSAGE);
|
|
131356
|
+
return;
|
|
131357
|
+
}
|
|
131358
|
+
if (host.session === void 0) {
|
|
131359
|
+
host.showError(NO_ACTIVE_SESSION_MESSAGE);
|
|
131360
|
+
return;
|
|
131361
|
+
}
|
|
131362
|
+
const parsed = parseLoopLimitArgs(args);
|
|
131363
|
+
if (typeof parsed === "string") {
|
|
131364
|
+
host.showError(parsed);
|
|
131365
|
+
return;
|
|
131366
|
+
}
|
|
131367
|
+
const loopLimit = createLoopLimitRuntime(parsed.limit);
|
|
131368
|
+
host.setAppState({
|
|
131369
|
+
loopModeEnabled: true,
|
|
131370
|
+
loopPrompt: void 0,
|
|
131371
|
+
loopLimit,
|
|
131372
|
+
loopVerifier: parsed.verifier ? makeVerifier(parsed.verifier.command) : void 0,
|
|
131373
|
+
loopIteration: 0,
|
|
131374
|
+
loopLastVerifyPassed: void 0
|
|
131375
|
+
});
|
|
131376
|
+
await ensureAutoPermission(host);
|
|
131377
|
+
const limitSuffix = parsed.limit ? ` 限制:${describeLoopLimit(parsed.limit)}。` : "";
|
|
131378
|
+
const remainingSuffix = loopLimit ? ` ${describeLoopLimitRuntime(loopLimit)}。` : "";
|
|
131379
|
+
const verifierSuffix = parsed.verifier ? ` 验证命令:${parsed.verifier.command}(通过即停)。` : "";
|
|
131380
|
+
const promptBehavior = parsed.prompt ? "已固定提示词,每轮结束后自动重发。" : "下一条提示词将在每轮结束后自动重发。";
|
|
131381
|
+
host.showNotice("循环模式已开启", `${promptBehavior}${limitSuffix}${remainingSuffix}${verifierSuffix}\n\n提示:每轮重发同一条 prompt,AI 不记得上一轮输出。需要根据上次失败调整策略时,用 /goal 更合适。
|
|
131382
|
+
|
|
131383
|
+
/loop 命令说明:
|
|
131384
|
+
· /loop — 切换循环开关
|
|
131385
|
+
· /loop 10 [提示词] — 限制 10 次迭代
|
|
131386
|
+
· /loop 5m [提示词] — 限制 5 分钟
|
|
131387
|
+
· /loop 1h30m [提示词] — 组合时长限制
|
|
131388
|
+
· /loop 10 ... --verify "命令" — 每轮后跑验证,通过即停
|
|
131389
|
+
按 Esc 暂停当前迭代;再次输入 /loop 关闭循环。`);
|
|
131390
|
+
if (parsed.prompt) host.sendNormalUserInput(parsed.prompt);
|
|
131391
|
+
}
|
|
131392
|
+
function disableLoopMode(host, message) {
|
|
131393
|
+
host.setAppState({
|
|
131394
|
+
loopModeEnabled: false,
|
|
131395
|
+
loopPrompt: void 0,
|
|
131396
|
+
loopLimit: void 0,
|
|
131397
|
+
loopVerifier: void 0,
|
|
131398
|
+
loopIteration: 0,
|
|
131399
|
+
loopLastVerifyPassed: void 0
|
|
131400
|
+
});
|
|
131401
|
+
if (message) host.showStatus(message);
|
|
131402
|
+
}
|
|
131403
|
+
//#endregion
|
|
129972
131404
|
//#region src/tui/commands/dispatch.ts
|
|
129973
131405
|
function dispatchInput(host, text) {
|
|
129974
131406
|
if (parseSlashInput(text) !== null) {
|
|
@@ -130085,6 +131517,9 @@ async function handleBuiltInSlashCommand(host, name, args) {
|
|
|
130085
131517
|
case "wolfpack":
|
|
130086
131518
|
await handleWolfpackCommand(host, args);
|
|
130087
131519
|
return;
|
|
131520
|
+
case "loop":
|
|
131521
|
+
await handleLoopCommand(host, args);
|
|
131522
|
+
return;
|
|
130088
131523
|
case "revoke":
|
|
130089
131524
|
await handleRevokeCommand(host, args);
|
|
130090
131525
|
return;
|
|
@@ -130929,7 +132364,14 @@ var EditorKeyboardController = class {
|
|
|
130929
132364
|
this.cancelCurrentCompaction();
|
|
130930
132365
|
return;
|
|
130931
132366
|
}
|
|
130932
|
-
if (host.state.appState.streamingPhase !== "idle")
|
|
132367
|
+
if (host.state.appState.streamingPhase !== "idle") {
|
|
132368
|
+
this.cancelCurrentStream();
|
|
132369
|
+
return;
|
|
132370
|
+
}
|
|
132371
|
+
if (host.state.appState.loopModeEnabled && host.state.appState.loopPrompt) {
|
|
132372
|
+
host.setAppState({ loopPrompt: void 0 });
|
|
132373
|
+
host.showStatus("循环已暂停。输入 /loop <提示词> 恢复或修改。");
|
|
132374
|
+
}
|
|
130933
132375
|
};
|
|
130934
132376
|
editor.onShiftTab = () => {
|
|
130935
132377
|
if (host.session === void 0) {
|
|
@@ -130966,6 +132408,9 @@ var EditorKeyboardController = class {
|
|
|
130966
132408
|
host.updateQueueDisplay();
|
|
130967
132409
|
host.state.ui.requestRender();
|
|
130968
132410
|
};
|
|
132411
|
+
editor.onCtrlW = () => {
|
|
132412
|
+
host.cancelPendingMemoryExtraction();
|
|
132413
|
+
};
|
|
130969
132414
|
editor.onUpArrowEmpty = () => {
|
|
130970
132415
|
if (host.state.appState.streamingPhase === "idle" && !host.state.appState.isCompacting) return false;
|
|
130971
132416
|
const recalled = host.recallLastQueued();
|
|
@@ -131347,6 +132792,35 @@ function formatDuration(ms) {
|
|
|
131347
132792
|
return `${(ms / 1e3).toFixed(1)}s`;
|
|
131348
132793
|
}
|
|
131349
132794
|
//#endregion
|
|
132795
|
+
//#region src/tui/utils/loop-verifier.ts
|
|
132796
|
+
const execAsync = promisify(exec);
|
|
132797
|
+
async function runShellVerifier(config, cwd) {
|
|
132798
|
+
const start = Date.now();
|
|
132799
|
+
try {
|
|
132800
|
+
const { stdout, stderr } = await execAsync(config.command, {
|
|
132801
|
+
cwd,
|
|
132802
|
+
timeout: config.timeoutMs,
|
|
132803
|
+
maxBuffer: 1024 * 1024
|
|
132804
|
+
});
|
|
132805
|
+
return {
|
|
132806
|
+
passed: true,
|
|
132807
|
+
output: trimOutput(stdout + stderr),
|
|
132808
|
+
durationMs: Date.now() - start
|
|
132809
|
+
};
|
|
132810
|
+
} catch (err) {
|
|
132811
|
+
const e = err;
|
|
132812
|
+
return {
|
|
132813
|
+
passed: false,
|
|
132814
|
+
output: trimOutput((e.stdout ?? "") + (e.stderr ?? "")),
|
|
132815
|
+
durationMs: Date.now() - start,
|
|
132816
|
+
exitCode: e.killed ? -1 : e.code ?? 1
|
|
132817
|
+
};
|
|
132818
|
+
}
|
|
132819
|
+
}
|
|
132820
|
+
function trimOutput(text) {
|
|
132821
|
+
return text.slice(-2e3);
|
|
132822
|
+
}
|
|
132823
|
+
//#endregion
|
|
131350
132824
|
//#region src/tui/utils/transcript-id.ts
|
|
131351
132825
|
let transcriptIdCounter = 0;
|
|
131352
132826
|
function nextTranscriptId() {
|
|
@@ -131569,7 +133043,8 @@ var SessionEventHandler = class {
|
|
|
131569
133043
|
toolCall.finishSubToolCall({
|
|
131570
133044
|
tool_call_id: `${subagentId}:${event.toolCallId}`,
|
|
131571
133045
|
output: serializeToolResultOutput(event.output),
|
|
131572
|
-
is_error: event.isError
|
|
133046
|
+
is_error: event.isError,
|
|
133047
|
+
display: event.display
|
|
131573
133048
|
});
|
|
131574
133049
|
return true;
|
|
131575
133050
|
case "agent.status.updated": {
|
|
@@ -131625,6 +133100,54 @@ var SessionEventHandler = class {
|
|
|
131625
133100
|
if (todos.length > 0 && todos.every((t) => t.status === "done")) this.host.streamingUI.setTodoList([]);
|
|
131626
133101
|
this.host.streamingUI.resetToolUi();
|
|
131627
133102
|
this.host.streamingUI.finalizeTurn(sendQueued);
|
|
133103
|
+
this.maybeScheduleLoopAutoSubmit();
|
|
133104
|
+
}
|
|
133105
|
+
maybeScheduleLoopAutoSubmit() {
|
|
133106
|
+
const { loopModeEnabled, loopPrompt, loopLimit } = this.host.state.appState;
|
|
133107
|
+
if (!loopModeEnabled || loopPrompt === void 0) return;
|
|
133108
|
+
if (isLoopLimitExpired(loopLimit)) {
|
|
133109
|
+
const reason = loopLimit?.kind === "duration" ? "时间" : "次数";
|
|
133110
|
+
this.disableLoop(`循环${reason}限制已到,循环模式已关闭。`);
|
|
133111
|
+
return;
|
|
133112
|
+
}
|
|
133113
|
+
setTimeout(() => {
|
|
133114
|
+
this.advanceLoopIteration(loopPrompt);
|
|
133115
|
+
}, 800);
|
|
133116
|
+
}
|
|
133117
|
+
disableLoop(message) {
|
|
133118
|
+
this.host.setAppState({
|
|
133119
|
+
loopModeEnabled: false,
|
|
133120
|
+
loopPrompt: void 0,
|
|
133121
|
+
loopLimit: void 0,
|
|
133122
|
+
loopVerifier: void 0,
|
|
133123
|
+
loopIteration: 0,
|
|
133124
|
+
loopLastVerifyPassed: void 0
|
|
133125
|
+
});
|
|
133126
|
+
this.host.showStatus(message);
|
|
133127
|
+
}
|
|
133128
|
+
async advanceLoopIteration(loopPrompt) {
|
|
133129
|
+
const state = this.host.state.appState;
|
|
133130
|
+
if (!state.loopModeEnabled || state.loopPrompt !== loopPrompt || state.streamingPhase !== "idle") return;
|
|
133131
|
+
const currentIteration = state.loopIteration + 1;
|
|
133132
|
+
this.host.setAppState({ loopIteration: currentIteration });
|
|
133133
|
+
const verifier = state.loopVerifier;
|
|
133134
|
+
if (verifier) {
|
|
133135
|
+
const result = await runShellVerifier(verifier, state.workDir);
|
|
133136
|
+
const after = this.host.state.appState;
|
|
133137
|
+
if (!after.loopModeEnabled || after.loopPrompt !== loopPrompt) return;
|
|
133138
|
+
if (result.passed) {
|
|
133139
|
+
this.disableLoop(`✓ 验证通过,循环结束(${currentIteration} 次迭代)。`);
|
|
133140
|
+
return;
|
|
133141
|
+
}
|
|
133142
|
+
this.host.setAppState({ loopLastVerifyPassed: false });
|
|
133143
|
+
}
|
|
133144
|
+
if (!consumeLoopLimitIteration(this.host.state.appState.loopLimit)) {
|
|
133145
|
+
const reason = this.host.state.appState.loopLimit?.kind === "duration" ? "时间" : "次数";
|
|
133146
|
+
const suffix = verifier ? ",验证未通过" : "";
|
|
133147
|
+
this.disableLoop(`循环${reason}限制已到${suffix},循环模式已关闭。`);
|
|
133148
|
+
return;
|
|
133149
|
+
}
|
|
133150
|
+
this.host.sendNormalUserInput(loopPrompt);
|
|
131628
133151
|
}
|
|
131629
133152
|
handleStepBegin(event) {
|
|
131630
133153
|
this.host.streamingUI.flushNow();
|
|
@@ -131764,7 +133287,8 @@ var SessionEventHandler = class {
|
|
|
131764
133287
|
tool_call_id: event.toolCallId,
|
|
131765
133288
|
output: serializeToolResultOutput(event.output),
|
|
131766
133289
|
is_error: event.isError,
|
|
131767
|
-
synthetic: event.synthetic
|
|
133290
|
+
synthetic: event.synthetic,
|
|
133291
|
+
display: event.display
|
|
131768
133292
|
};
|
|
131769
133293
|
const matchedCall = streamingUI.completeToolResult(event.toolCallId, resultData);
|
|
131770
133294
|
if (matchedCall !== void 0 && matchedCall.name === "TodoList" && !event.isError) {
|
|
@@ -134930,6 +136454,7 @@ var TranscriptController = class TranscriptController {
|
|
|
134930
136454
|
this.clearTerminalInlineImages();
|
|
134931
136455
|
state.todoPanel.clear();
|
|
134932
136456
|
state.todoPanelContainer.clear();
|
|
136457
|
+
state.errorBanner.clear();
|
|
134933
136458
|
imageStore.clear();
|
|
134934
136459
|
this.renderWelcome();
|
|
134935
136460
|
}
|
|
@@ -134942,7 +136467,10 @@ var TranscriptController = class TranscriptController {
|
|
|
134942
136467
|
this.host.state.ui.requestRender();
|
|
134943
136468
|
}
|
|
134944
136469
|
showError(message) {
|
|
134945
|
-
|
|
136470
|
+
const cleaned = replaceTabs(message);
|
|
136471
|
+
this.showStatus(`错误:${truncateErrorMessage(cleaned)}`, this.host.state.theme.colors.error);
|
|
136472
|
+
this.host.state.errorBanner.setMessage(cleaned);
|
|
136473
|
+
this.host.state.ui.requestRender();
|
|
134946
136474
|
}
|
|
134947
136475
|
showProgressSpinner(label) {
|
|
134948
136476
|
const tint = (s) => chalk.hex(this.host.state.theme.colors.primary)(s);
|
|
@@ -135347,11 +136875,13 @@ var LifecycleController = class LifecycleController {
|
|
|
135347
136875
|
signalCleanupHandlers = [];
|
|
135348
136876
|
ccConnectPollTimer;
|
|
135349
136877
|
memoryIdleTimer;
|
|
136878
|
+
memoryCountdownTimer;
|
|
135350
136879
|
lastMemoryExtractionTime = 0;
|
|
135351
136880
|
terminalFocusTrackingDispose;
|
|
135352
136881
|
terminalThemeTrackingDispose;
|
|
135353
136882
|
lastActivityMode;
|
|
135354
136883
|
static MEMORY_IDLE_MS = 900 * 1e3;
|
|
136884
|
+
static MEMORY_COUNTDOWN_MS = 15 * 1e3;
|
|
135355
136885
|
static MEMORY_EXTRACT_COOLDOWN_MS = 600 * 1e3;
|
|
135356
136886
|
constructor(host) {
|
|
135357
136887
|
this.host = host;
|
|
@@ -135382,12 +136912,16 @@ var LifecycleController = class LifecycleController {
|
|
|
135382
136912
|
};
|
|
135383
136913
|
process.stdout.on("error", terminalErrorHandler);
|
|
135384
136914
|
process.stderr.on("error", terminalErrorHandler);
|
|
136915
|
+
process.stdin.on("error", terminalErrorHandler);
|
|
135385
136916
|
this.signalCleanupHandlers.push(() => {
|
|
135386
136917
|
process.stdout.off("error", terminalErrorHandler);
|
|
135387
136918
|
});
|
|
135388
136919
|
this.signalCleanupHandlers.push(() => {
|
|
135389
136920
|
process.stderr.off("error", terminalErrorHandler);
|
|
135390
136921
|
});
|
|
136922
|
+
this.signalCleanupHandlers.push(() => {
|
|
136923
|
+
process.stdin.off("error", terminalErrorHandler);
|
|
136924
|
+
});
|
|
135391
136925
|
}
|
|
135392
136926
|
uninstallSignalHandlers() {
|
|
135393
136927
|
const handlers = this.signalCleanupHandlers;
|
|
@@ -135424,7 +136958,8 @@ var LifecycleController = class LifecycleController {
|
|
|
135424
136958
|
startMemoryIdleTimer() {
|
|
135425
136959
|
this.stopMemoryIdleTimer();
|
|
135426
136960
|
this.memoryIdleTimer = setTimeout(() => {
|
|
135427
|
-
this.
|
|
136961
|
+
this.memoryIdleTimer = void 0;
|
|
136962
|
+
this.startExtractionCountdown();
|
|
135428
136963
|
}, LifecycleController.MEMORY_IDLE_MS);
|
|
135429
136964
|
}
|
|
135430
136965
|
stopMemoryIdleTimer() {
|
|
@@ -135432,6 +136967,26 @@ var LifecycleController = class LifecycleController {
|
|
|
135432
136967
|
clearTimeout(this.memoryIdleTimer);
|
|
135433
136968
|
this.memoryIdleTimer = void 0;
|
|
135434
136969
|
}
|
|
136970
|
+
if (this.memoryCountdownTimer !== void 0) {
|
|
136971
|
+
clearTimeout(this.memoryCountdownTimer);
|
|
136972
|
+
this.memoryCountdownTimer = void 0;
|
|
136973
|
+
}
|
|
136974
|
+
}
|
|
136975
|
+
startExtractionCountdown() {
|
|
136976
|
+
if (this.memoryCountdownTimer !== void 0) return;
|
|
136977
|
+
this.host.showNotice("15 分钟未操作,即将整理会话记忆", `按 Ctrl+W 取消(${Math.round(LifecycleController.MEMORY_COUNTDOWN_MS / 1e3)} 秒后自动开始)`);
|
|
136978
|
+
this.host.state.ui.requestRender();
|
|
136979
|
+
this.memoryCountdownTimer = setTimeout(() => {
|
|
136980
|
+
this.memoryCountdownTimer = void 0;
|
|
136981
|
+
this.performIdleMemoryExtraction();
|
|
136982
|
+
}, LifecycleController.MEMORY_COUNTDOWN_MS);
|
|
136983
|
+
}
|
|
136984
|
+
cancelPendingMemoryExtraction() {
|
|
136985
|
+
if (this.memoryCountdownTimer === void 0) return;
|
|
136986
|
+
clearTimeout(this.memoryCountdownTimer);
|
|
136987
|
+
this.memoryCountdownTimer = void 0;
|
|
136988
|
+
this.host.showStatus("已取消记忆提取", this.host.state.theme.colors.textDim);
|
|
136989
|
+
this.startMemoryIdleTimer();
|
|
135435
136990
|
}
|
|
135436
136991
|
async performIdleMemoryExtraction() {
|
|
135437
136992
|
if (Date.now() - this.lastMemoryExtractionTime < LifecycleController.MEMORY_EXTRACT_COOLDOWN_MS) return;
|
|
@@ -135440,14 +136995,15 @@ var LifecycleController = class LifecycleController {
|
|
|
135440
136995
|
if (state.appState.isCompacting) return;
|
|
135441
136996
|
if (state.appState.isReplaying) return;
|
|
135442
136997
|
if (session === void 0) return;
|
|
135443
|
-
|
|
136998
|
+
this.host.showStatus("正在整理会话记忆...", state.theme.colors.textDim);
|
|
135444
136999
|
state.ui.requestRender();
|
|
135445
137000
|
try {
|
|
135446
|
-
await session.extractMemoriesOnExit();
|
|
137001
|
+
const count = await session.extractMemoriesOnExit();
|
|
137002
|
+
this.host.showStatus(count > 0 ? `已沉淀 ${count} 条记忆至备忘录` : "本次无需沉淀新记忆", state.theme.colors.textDim);
|
|
137003
|
+
} catch {
|
|
137004
|
+
this.host.showStatus("记忆整理失败,稍后再试", state.theme.colors.warning);
|
|
137005
|
+
} finally {
|
|
135447
137006
|
this.lastMemoryExtractionTime = Date.now();
|
|
135448
|
-
this.host.showStatus("已沉淀关键信息至记忆备忘录");
|
|
135449
|
-
} catch {} finally {
|
|
135450
|
-
state.footer.setTransientHint(null);
|
|
135451
137007
|
state.ui.requestRender();
|
|
135452
137008
|
}
|
|
135453
137009
|
}
|
|
@@ -135469,6 +137025,7 @@ var LifecycleController = class LifecycleController {
|
|
|
135469
137025
|
ui.addChild(this.host.state.activityContainer);
|
|
135470
137026
|
ui.addChild(this.host.state.todoPanelContainer);
|
|
135471
137027
|
ui.addChild(this.host.state.queueContainer);
|
|
137028
|
+
ui.addChild(this.host.state.errorBannerContainer);
|
|
135472
137029
|
ui.addChild(this.host.state.editorContainer);
|
|
135473
137030
|
}
|
|
135474
137031
|
mountFooter() {
|
|
@@ -136024,10 +137581,7 @@ var InputController = class {
|
|
|
136024
137581
|
this.host = host;
|
|
136025
137582
|
}
|
|
136026
137583
|
setupAutocomplete() {
|
|
136027
|
-
const slashCommands = this.host.getSlashCommands().filter((cmd) => !cmd.name.startsWith("skill:")).map((cmd) =>
|
|
136028
|
-
value: cmd.name,
|
|
136029
|
-
label: `/${cmd.name} — ${cmd.description}`
|
|
136030
|
-
}));
|
|
137584
|
+
const slashCommands = this.host.getSlashCommands().filter((cmd) => !cmd.name.startsWith("skill:")).map((cmd) => cmd);
|
|
136031
137585
|
const { state } = this.host;
|
|
136032
137586
|
const provider = new FileMentionProvider(slashCommands, state.appState.workDir, state.fdPath, state.gitLsFilesCache);
|
|
136033
137587
|
state.editor.setAutocompleteProvider(provider);
|
|
@@ -136059,6 +137613,10 @@ var InputController = class {
|
|
|
136059
137613
|
this.host.showError(LLM_NOT_SET_MESSAGE);
|
|
136060
137614
|
return;
|
|
136061
137615
|
}
|
|
137616
|
+
if (this.host.state.appState.loopModeEnabled && !this.host.state.appState.loopPrompt) {
|
|
137617
|
+
this.host.setAppState({ loopPrompt: text });
|
|
137618
|
+
consumeLoopLimitIteration(this.host.state.appState.loopLimit);
|
|
137619
|
+
}
|
|
136062
137620
|
if (extraction.hasMedia) this.sendMessage(session, text, {
|
|
136063
137621
|
hasMedia: true,
|
|
136064
137622
|
parts: extraction.parts,
|
|
@@ -136084,6 +137642,7 @@ var InputController = class {
|
|
|
136084
137642
|
renderMode: "plain",
|
|
136085
137643
|
content: part
|
|
136086
137644
|
});
|
|
137645
|
+
this.host.state.errorBanner.clear();
|
|
136087
137646
|
session.steer(input.join("\n\n")).catch((error) => {
|
|
136088
137647
|
const message = formatErrorMessage(error);
|
|
136089
137648
|
this.host.showError(`引导失败:${message}`);
|
|
@@ -136175,6 +137734,7 @@ var InputController = class {
|
|
|
136175
137734
|
}
|
|
136176
137735
|
sendMessageInternal(session, input, options) {
|
|
136177
137736
|
const imageAttachmentIds = options?.imageAttachmentIds !== void 0 && options.imageAttachmentIds.length > 0 ? options.imageAttachmentIds : void 0;
|
|
137737
|
+
this.host.state.errorBanner.clear();
|
|
136178
137738
|
this.host.appendTranscriptEntry({
|
|
136179
137739
|
id: nextTranscriptId(),
|
|
136180
137740
|
kind: "user",
|
|
@@ -136423,6 +137983,44 @@ const INITIAL_LIVE_PANE = {
|
|
|
136423
137983
|
pendingQuestion: null
|
|
136424
137984
|
};
|
|
136425
137985
|
//#endregion
|
|
137986
|
+
//#region src/tui/components/chrome/error-banner.ts
|
|
137987
|
+
const MAX_BANNER_LINES = 3;
|
|
137988
|
+
const CONTINUATION_INDENT = " ";
|
|
137989
|
+
var ErrorBannerComponent = class {
|
|
137990
|
+
message;
|
|
137991
|
+
colors;
|
|
137992
|
+
constructor(colors) {
|
|
137993
|
+
this.colors = colors;
|
|
137994
|
+
}
|
|
137995
|
+
setMessage(message) {
|
|
137996
|
+
this.message = message;
|
|
137997
|
+
}
|
|
137998
|
+
clear() {
|
|
137999
|
+
this.message = void 0;
|
|
138000
|
+
}
|
|
138001
|
+
invalidate() {}
|
|
138002
|
+
render(width) {
|
|
138003
|
+
if (this.message === void 0) return [];
|
|
138004
|
+
const lines = truncateErrorMessage(this.message, MAX_BANNER_LINES).split("\n");
|
|
138005
|
+
const err = chalk.hex(this.colors.error);
|
|
138006
|
+
const dim = chalk.hex(this.colors.textDim);
|
|
138007
|
+
const contentWidth = Math.max(10, width - Math.max(2, 2));
|
|
138008
|
+
const out = [""];
|
|
138009
|
+
for (let i = 0; i < lines.length; i++) {
|
|
138010
|
+
const line = lines[i];
|
|
138011
|
+
if (i === 0) {
|
|
138012
|
+
const trimmed = truncateToWidth(line, contentWidth);
|
|
138013
|
+
out.push(err(`${STATUS_BULLET}${trimmed}`));
|
|
138014
|
+
} else if (line.startsWith("… ")) out.push(dim(CONTINUATION_INDENT + line));
|
|
138015
|
+
else {
|
|
138016
|
+
const trimmed = truncateToWidth(line, contentWidth);
|
|
138017
|
+
out.push(err(CONTINUATION_INDENT + trimmed));
|
|
138018
|
+
}
|
|
138019
|
+
}
|
|
138020
|
+
return out;
|
|
138021
|
+
}
|
|
138022
|
+
};
|
|
138023
|
+
//#endregion
|
|
136426
138024
|
//#region src/tui/utils/shimmer.ts
|
|
136427
138025
|
const SHIMMER_SPEED_CELLS_PER_S = 30;
|
|
136428
138026
|
const PADDING = 10;
|
|
@@ -136929,20 +138527,12 @@ function formatContextStatus(usage, tokens, maxTokens) {
|
|
|
136929
138527
|
if (maxTokens && maxTokens > 0 && tokens !== void 0) return `上下文:${pct} (${formatTokenCount(tokens)}/${formatTokenCount(maxTokens)})`;
|
|
136930
138528
|
return `上下文:${pct}`;
|
|
136931
138529
|
}
|
|
136932
|
-
const CONTEXT_WARNING_PERCENT_THRESHOLD =
|
|
136933
|
-
const CONTEXT_WARNING_TOKEN_THRESHOLD = 14e4;
|
|
138530
|
+
const CONTEXT_WARNING_PERCENT_THRESHOLD = 60;
|
|
136934
138531
|
const CONTEXT_ERROR_PERCENT_THRESHOLD = 90;
|
|
136935
|
-
|
|
136936
|
-
function reachesThreshold(percent, maxTokens, percentThreshold, tokenThreshold) {
|
|
136937
|
-
if (!Number.isFinite(percent) || percent <= 0) return false;
|
|
136938
|
-
if (maxTokens === void 0 || !Number.isFinite(maxTokens) || maxTokens <= 0) return percent >= percentThreshold;
|
|
136939
|
-
const tokenPercentThreshold = tokenThreshold / maxTokens * 100;
|
|
136940
|
-
return percent >= Math.min(percentThreshold, tokenPercentThreshold);
|
|
136941
|
-
}
|
|
136942
|
-
function pickContextColor(usage, maxTokens, colors) {
|
|
138532
|
+
function pickContextColor(usage, colors) {
|
|
136943
138533
|
const percent = safeUsage(usage) * 100;
|
|
136944
|
-
if (
|
|
136945
|
-
if (
|
|
138534
|
+
if (percent >= CONTEXT_ERROR_PERCENT_THRESHOLD) return colors.error;
|
|
138535
|
+
if (percent >= CONTEXT_WARNING_PERCENT_THRESHOLD) return colors.warning;
|
|
136946
138536
|
return colors.textDim;
|
|
136947
138537
|
}
|
|
136948
138538
|
const BRAND_COLORS = [
|
|
@@ -137089,6 +138679,18 @@ var FooterComponent = class {
|
|
|
137089
138679
|
if (state.permissionMode === "yolo") left.push(chalk.hex(colors.warning).bold("YES"));
|
|
137090
138680
|
if (state.planMode) left.push(chalk.hex(colors.planMode).bold("plan"));
|
|
137091
138681
|
if (state.wolfpackMode) left.push(chalk.hex(colors.primary).bold("wolfpack"));
|
|
138682
|
+
if (state.loopModeEnabled) {
|
|
138683
|
+
const iter = state.loopIteration;
|
|
138684
|
+
const limit = state.loopLimit;
|
|
138685
|
+
let badge = "loop";
|
|
138686
|
+
if (limit?.kind === "iterations") badge = `loop ${iter}/${limit.initial}`;
|
|
138687
|
+
else if (limit?.kind === "duration") {
|
|
138688
|
+
const remainMs = Math.max(0, limit.deadlineMs - Date.now());
|
|
138689
|
+
badge = remainMs >= 6e4 ? `loop ${Math.ceil(remainMs / 6e4)}m` : `loop ${Math.max(1, Math.ceil(remainMs / 1e3))}s`;
|
|
138690
|
+
}
|
|
138691
|
+
if (state.loopLastVerifyPassed === false) badge += " · ✗";
|
|
138692
|
+
left.push(chalk.hex(colors.primary).bold(badge));
|
|
138693
|
+
}
|
|
137092
138694
|
if (state.goalActive) left.push(chalk.hex(colors.primary).bold("goal"));
|
|
137093
138695
|
const model = shortenModel(modelDisplayName(state));
|
|
137094
138696
|
if (model) if (state.streamingPhase === "thinking") left.push(shimmerText(model, colors));
|
|
@@ -137112,7 +138714,7 @@ var FooterComponent = class {
|
|
|
137112
138714
|
else {
|
|
137113
138715
|
const statusLine = buildStatusLine(state.streamingPhase, state.livePaneMode, state.streamingStartTime);
|
|
137114
138716
|
const ccDot = state.ccConnectActive ? chalk.hex(colors.success)("●") : chalk.hex(colors.textDim)("●");
|
|
137115
|
-
const contextColor = pickContextColor(state.contextUsage,
|
|
138717
|
+
const contextColor = pickContextColor(state.contextUsage, colors);
|
|
137116
138718
|
rightText = `${ccDot} ${chalk.hex(contextColor)(formatContextStatus(state.contextUsage, state.contextTokens, state.maxContextTokens))}${chalk.hex(colors.textDim)(` ${statusLine}`)}`;
|
|
137117
138719
|
}
|
|
137118
138720
|
const rightWidth = visibleWidth(rightText);
|
|
@@ -137312,6 +138914,7 @@ var CustomEditor = class extends Editor {
|
|
|
137312
138914
|
onTogglePlanExpand;
|
|
137313
138915
|
onOpenExternalEditor;
|
|
137314
138916
|
onCtrlS;
|
|
138917
|
+
onCtrlW;
|
|
137315
138918
|
/**
|
|
137316
138919
|
* Called when ↑ is pressed in an empty editor. Return `true` to consume
|
|
137317
138920
|
* the key (e.g. recalled a queued message); return `false` to fall
|
|
@@ -137452,6 +139055,10 @@ var CustomEditor = class extends Editor {
|
|
|
137452
139055
|
this.onCtrlS?.();
|
|
137453
139056
|
return;
|
|
137454
139057
|
}
|
|
139058
|
+
if (matchesKey(normalized, Key.ctrl("w"))) {
|
|
139059
|
+
this.onCtrlW?.();
|
|
139060
|
+
return;
|
|
139061
|
+
}
|
|
137455
139062
|
if (matchesKey(normalized, "shift+tab")) {
|
|
137456
139063
|
this.onShiftTab?.();
|
|
137457
139064
|
return;
|
|
@@ -137742,6 +139349,9 @@ function createTUIState(options) {
|
|
|
137742
139349
|
const todoPanelContainer = new GutterContainer(1, 1);
|
|
137743
139350
|
const todoPanel = new TodoPanelComponent(theme.colors);
|
|
137744
139351
|
const queueContainer = new GutterContainer(1, 1);
|
|
139352
|
+
const errorBanner = new ErrorBannerComponent(theme.colors);
|
|
139353
|
+
const errorBannerContainer = new GutterContainer(1, 1);
|
|
139354
|
+
errorBannerContainer.addChild(errorBanner);
|
|
137745
139355
|
const editorContainer = new GutterContainer(1, 1);
|
|
137746
139356
|
const editor = new CustomEditor(ui, theme.colors);
|
|
137747
139357
|
editor.thinking = initialAppState.thinking;
|
|
@@ -137753,6 +139363,8 @@ function createTUIState(options) {
|
|
|
137753
139363
|
todoPanelContainer,
|
|
137754
139364
|
todoPanel,
|
|
137755
139365
|
queueContainer,
|
|
139366
|
+
errorBanner,
|
|
139367
|
+
errorBannerContainer,
|
|
137756
139368
|
editorContainer,
|
|
137757
139369
|
footer: new FooterComponent({ ...initialAppState }, theme.colors, ui, () => {
|
|
137758
139370
|
ui.requestRender();
|
|
@@ -140371,6 +141983,12 @@ function createInitialAppState(input) {
|
|
|
140371
141983
|
goalContinuationCount: 0,
|
|
140372
141984
|
ccConnectActive: false,
|
|
140373
141985
|
wolfpackMode: false,
|
|
141986
|
+
loopModeEnabled: false,
|
|
141987
|
+
loopPrompt: void 0,
|
|
141988
|
+
loopLimit: void 0,
|
|
141989
|
+
loopVerifier: void 0,
|
|
141990
|
+
loopIteration: 0,
|
|
141991
|
+
loopLastVerifyPassed: void 0,
|
|
140374
141992
|
recentSessions: []
|
|
140375
141993
|
};
|
|
140376
141994
|
}
|
|
@@ -140563,8 +142181,7 @@ var ScreamTUI = class {
|
|
|
140563
142181
|
this.reverseRpcDisposers.length = 0;
|
|
140564
142182
|
this.lifecycleController.disposeTerminalTracking();
|
|
140565
142183
|
this.inputController.dispose();
|
|
140566
|
-
this.
|
|
140567
|
-
this.state.ui.requestRender();
|
|
142184
|
+
this.showStatus("正在整理会话记忆...", this.state.theme.colors.textDim);
|
|
140568
142185
|
await new Promise((resolve) => {
|
|
140569
142186
|
setTimeout(resolve, 0);
|
|
140570
142187
|
});
|
|
@@ -140577,7 +142194,9 @@ var ScreamTUI = class {
|
|
|
140577
142194
|
markMemoryExtracted() {
|
|
140578
142195
|
this.lifecycleController.markMemoryExtracted();
|
|
140579
142196
|
}
|
|
140580
|
-
|
|
142197
|
+
sendNormalUserInput(text) {
|
|
142198
|
+
this.inputController.sendNormalUserInput(text);
|
|
142199
|
+
}
|
|
140581
142200
|
onTurnCompleted() {
|
|
140582
142201
|
this.lifecycleController.onTurnCompleted();
|
|
140583
142202
|
}
|
|
@@ -140613,9 +142232,6 @@ var ScreamTUI = class {
|
|
|
140613
142232
|
handlePlanToggle(next) {
|
|
140614
142233
|
this.inputController.handlePlanToggle(next);
|
|
140615
142234
|
}
|
|
140616
|
-
sendNormalUserInput(text) {
|
|
140617
|
-
this.inputController.sendNormalUserInput(text);
|
|
140618
|
-
}
|
|
140619
142235
|
steerMessage(session, input) {
|
|
140620
142236
|
this.inputController.steerMessage(session, input);
|
|
140621
142237
|
}
|
|
@@ -140673,6 +142289,9 @@ var ScreamTUI = class {
|
|
|
140673
142289
|
setExternalEditorRunning(running) {
|
|
140674
142290
|
this.state.externalEditorRunning = running;
|
|
140675
142291
|
}
|
|
142292
|
+
cancelPendingMemoryExtraction() {
|
|
142293
|
+
this.lifecycleController.cancelPendingMemoryExtraction();
|
|
142294
|
+
}
|
|
140676
142295
|
setTasksBrowser(value) {
|
|
140677
142296
|
this.state.tasksBrowser = value;
|
|
140678
142297
|
}
|