@fro.bot/systematic 3.27.2 → 3.28.0
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/ATTRIBUTIONS.md +2 -2
- package/HARNESSES.md +22 -9
- package/agents/research/learnings-researcher.md +49 -9
- package/dist/claude-code-search.d.ts +30 -0
- package/dist/claude-code-validator-bin.d.ts +17 -0
- package/dist/cli.d.ts +18 -0
- package/dist/cli.js +335 -108
- package/dist/{index-608preny.js → index-9chxhh5j.js} +1120 -72
- package/dist/index.js +117 -3
- package/dist/lib/agent-resolver.d.ts +8 -2
- package/dist/lib/config-protected-fields.d.ts +1 -1
- package/dist/lib/config-schema.d.ts +6 -0
- package/dist/lib/config.d.ts +13 -0
- package/dist/lib/main-module.d.ts +30 -0
- package/dist/lib/opencode-v2-skills.d.ts +12 -2
- package/dist/lib/opencode-v2.d.ts +1 -0
- package/dist/lib/pi-delegate-session.d.ts +3 -1
- package/dist/lib/pi-delegate-tool.d.ts +12 -1
- package/dist/lib/search-cli.d.ts +52 -0
- package/dist/lib/search-core.d.ts +128 -0
- package/dist/lib/search-corpus.d.ts +105 -0
- package/dist/lib/search-lexical.d.ts +136 -0
- package/dist/lib/search-render.d.ts +69 -0
- package/dist/lib/search-tool.d.ts +53 -0
- package/dist/lib/search-user-config.d.ts +96 -0
- package/dist/pi.js +1155 -77
- package/package.json +3 -3
- package/skills/ce-review/SKILL.md +1 -1
- package/skills/ce-review/references/review-output-template.md +1 -1
- package/skills/ce-review/scripts/validate-review.mjs +1 -3
- package/skills/using-systematic/references/claude-code-profile.md +1 -0
- package/skills/using-systematic/references/opencode-profile.md +1 -0
- package/skills/using-systematic/references/opencode-v2-profile.md +1 -0
- package/skills/using-systematic/references/pi-profile.md +1 -0
package/dist/pi.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// src/pi.ts
|
|
2
|
-
import
|
|
2
|
+
import path9 from "node:path";
|
|
3
3
|
import { fileURLToPath } from "node:url";
|
|
4
4
|
import { Type as Type3 } from "typebox";
|
|
5
5
|
|
|
6
6
|
// src/lib/agent-resolver.ts
|
|
7
|
-
import
|
|
7
|
+
import fs3 from "node:fs";
|
|
8
8
|
|
|
9
9
|
// node_modules/.bun/js-yaml@4.3.2/node_modules/js-yaml/dist/js-yaml.mjs
|
|
10
10
|
function getDefaultExportFromCjs(x) {
|
|
@@ -3141,7 +3141,7 @@ var {
|
|
|
3141
3141
|
|
|
3142
3142
|
// src/lib/frontmatter.ts
|
|
3143
3143
|
function parseFrontmatter(content) {
|
|
3144
|
-
const frontmatterRegex = /^---\r?\n([\s\S]
|
|
3144
|
+
const frontmatterRegex = /^---\r?\n((?:[\s\S]*?\r?\n)?)---\r?\n([\s\S]*)$/;
|
|
3145
3145
|
const match = content.match(frontmatterRegex);
|
|
3146
3146
|
if (!match) {
|
|
3147
3147
|
return {
|
|
@@ -3239,13 +3239,902 @@ function findAgentsInDir(dir, maxDepth = 2) {
|
|
|
3239
3239
|
}));
|
|
3240
3240
|
}
|
|
3241
3241
|
|
|
3242
|
+
// src/lib/search-corpus.ts
|
|
3243
|
+
import fs2 from "node:fs";
|
|
3244
|
+
import path2 from "node:path";
|
|
3245
|
+
var MAX_FILE_BYTES = 256 * 1024;
|
|
3246
|
+
var MAX_FILES = 2000;
|
|
3247
|
+
var MAX_DEPTH = 6;
|
|
3248
|
+
var MAX_TOTAL_BYTES = 16 * 1024 * 1024;
|
|
3249
|
+
var MAX_DISCOVERED_FILES = MAX_FILES * 4;
|
|
3250
|
+
var MAX_WARNING_LENGTH = 200;
|
|
3251
|
+
var KIND_TABLE = {
|
|
3252
|
+
solution: {
|
|
3253
|
+
dir: "docs/solutions",
|
|
3254
|
+
excludedFiles: ["readme.md", "critical-patterns.md"],
|
|
3255
|
+
excludedDirs: ["_archived"],
|
|
3256
|
+
lifecycle: true
|
|
3257
|
+
}
|
|
3258
|
+
};
|
|
3259
|
+
function isDocumentKind(value) {
|
|
3260
|
+
return typeof value === "string" && Object.hasOwn(KIND_TABLE, value);
|
|
3261
|
+
}
|
|
3262
|
+
var ANSI_SEQUENCE = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|[@-Z\\-_])/g;
|
|
3263
|
+
var CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]/g;
|
|
3264
|
+
function cleanForWarning(text) {
|
|
3265
|
+
const clean = text.replace(ANSI_SEQUENCE, "").replace(CONTROL_CHARACTERS, "");
|
|
3266
|
+
return clean.length > MAX_WARNING_LENGTH ? `${clean.slice(0, MAX_WARNING_LENGTH)}…` : clean;
|
|
3267
|
+
}
|
|
3268
|
+
function compareCodeUnits(a, b) {
|
|
3269
|
+
if (a < b)
|
|
3270
|
+
return -1;
|
|
3271
|
+
return a > b ? 1 : 0;
|
|
3272
|
+
}
|
|
3273
|
+
function safeLstat(target) {
|
|
3274
|
+
try {
|
|
3275
|
+
return fs2.lstatSync(target, { throwIfNoEntry: false }) ?? null;
|
|
3276
|
+
} catch {
|
|
3277
|
+
return null;
|
|
3278
|
+
}
|
|
3279
|
+
}
|
|
3280
|
+
function safeRealpath(target) {
|
|
3281
|
+
try {
|
|
3282
|
+
return fs2.realpathSync(target);
|
|
3283
|
+
} catch {
|
|
3284
|
+
return null;
|
|
3285
|
+
}
|
|
3286
|
+
}
|
|
3287
|
+
function isAbsence(error) {
|
|
3288
|
+
const code = typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
|
|
3289
|
+
return code === "ENOENT" || code === "ENOTDIR";
|
|
3290
|
+
}
|
|
3291
|
+
function probeRealpath(target) {
|
|
3292
|
+
try {
|
|
3293
|
+
return { kind: "ok", value: fs2.realpathSync(target) };
|
|
3294
|
+
} catch (error) {
|
|
3295
|
+
return { kind: isAbsence(error) ? "absent" : "failed" };
|
|
3296
|
+
}
|
|
3297
|
+
}
|
|
3298
|
+
function probeLstat(target) {
|
|
3299
|
+
try {
|
|
3300
|
+
const stat = fs2.lstatSync(target, { throwIfNoEntry: false });
|
|
3301
|
+
return stat === undefined ? { kind: "absent" } : { kind: "ok", value: stat };
|
|
3302
|
+
} catch (error) {
|
|
3303
|
+
return { kind: isAbsence(error) ? "absent" : "failed" };
|
|
3304
|
+
}
|
|
3305
|
+
}
|
|
3306
|
+
function safeReaddir(target) {
|
|
3307
|
+
try {
|
|
3308
|
+
return fs2.readdirSync(target);
|
|
3309
|
+
} catch {
|
|
3310
|
+
return null;
|
|
3311
|
+
}
|
|
3312
|
+
}
|
|
3313
|
+
function resolveSearchRoot(startDir) {
|
|
3314
|
+
const resolved = path2.resolve(startDir);
|
|
3315
|
+
const start = safeRealpath(resolved) ?? resolved;
|
|
3316
|
+
let current = start;
|
|
3317
|
+
while (true) {
|
|
3318
|
+
try {
|
|
3319
|
+
if (fs2.lstatSync(path2.join(current, ".git"), { throwIfNoEntry: false })) {
|
|
3320
|
+
return current;
|
|
3321
|
+
}
|
|
3322
|
+
} catch {
|
|
3323
|
+
return start;
|
|
3324
|
+
}
|
|
3325
|
+
const parent = path2.dirname(current);
|
|
3326
|
+
if (parent === current)
|
|
3327
|
+
return start;
|
|
3328
|
+
current = parent;
|
|
3329
|
+
}
|
|
3330
|
+
}
|
|
3331
|
+
function isInside(root, candidate) {
|
|
3332
|
+
const relative = path2.relative(root, candidate);
|
|
3333
|
+
return relative !== "" && relative !== ".." && !relative.startsWith(`..${path2.sep}`) && !path2.isAbsolute(relative);
|
|
3334
|
+
}
|
|
3335
|
+
function classifyEntry(spec, name, stat) {
|
|
3336
|
+
if (stat === null || stat.isSymbolicLink())
|
|
3337
|
+
return "ignored";
|
|
3338
|
+
if (stat.isDirectory()) {
|
|
3339
|
+
return spec.excludedDirs.includes(name) ? "ignored" : "directory";
|
|
3340
|
+
}
|
|
3341
|
+
if (!stat.isFile())
|
|
3342
|
+
return "ignored";
|
|
3343
|
+
const lower = name.toLowerCase();
|
|
3344
|
+
const indexable = lower.endsWith(".md") && !spec.excludedFiles.includes(lower);
|
|
3345
|
+
return indexable ? "file" : "ignored";
|
|
3346
|
+
}
|
|
3347
|
+
function discoverFiles(spec, directory, prefix, depth, found, warnings) {
|
|
3348
|
+
const names = safeReaddir(directory);
|
|
3349
|
+
if (names === null) {
|
|
3350
|
+
const shown = prefix === "" ? spec.dir : `${spec.dir}/${prefix.slice(0, -1)}`;
|
|
3351
|
+
warnings.push(cleanForWarning(`could not read directory ${shown}`));
|
|
3352
|
+
return;
|
|
3353
|
+
}
|
|
3354
|
+
names.sort(compareCodeUnits);
|
|
3355
|
+
for (const name of names) {
|
|
3356
|
+
if (found.truncated)
|
|
3357
|
+
return;
|
|
3358
|
+
const absolute = path2.join(directory, name);
|
|
3359
|
+
const stat = safeLstat(absolute);
|
|
3360
|
+
const entryKind = classifyEntry(spec, name, stat);
|
|
3361
|
+
if (entryKind === "directory" && depth + 1 <= MAX_DEPTH) {
|
|
3362
|
+
const child = `${prefix}${name}/`;
|
|
3363
|
+
discoverFiles(spec, absolute, child, depth + 1, found, warnings);
|
|
3364
|
+
} else if (entryKind === "file" && stat !== null) {
|
|
3365
|
+
if (found.candidates.length >= MAX_DISCOVERED_FILES) {
|
|
3366
|
+
found.truncated = true;
|
|
3367
|
+
return;
|
|
3368
|
+
}
|
|
3369
|
+
found.candidates.push({
|
|
3370
|
+
relative: `${prefix}${name}`,
|
|
3371
|
+
absolute,
|
|
3372
|
+
size: stat.size
|
|
3373
|
+
});
|
|
3374
|
+
}
|
|
3375
|
+
}
|
|
3376
|
+
}
|
|
3377
|
+
function narrowString(value) {
|
|
3378
|
+
return typeof value === "string" ? value : undefined;
|
|
3379
|
+
}
|
|
3380
|
+
function narrowStringList(value) {
|
|
3381
|
+
const items = Array.isArray(value) ? value : [value];
|
|
3382
|
+
const result = [];
|
|
3383
|
+
for (const item of items) {
|
|
3384
|
+
if (typeof item === "string")
|
|
3385
|
+
result.push(item);
|
|
3386
|
+
else if (typeof item === "number" && Number.isFinite(item))
|
|
3387
|
+
result.push(String(item));
|
|
3388
|
+
}
|
|
3389
|
+
return result;
|
|
3390
|
+
}
|
|
3391
|
+
function narrowSupersededBy(value) {
|
|
3392
|
+
if (value === undefined || value === null)
|
|
3393
|
+
return { state: "none" };
|
|
3394
|
+
if (typeof value === "string")
|
|
3395
|
+
return { state: "value", value };
|
|
3396
|
+
return { state: "invalid" };
|
|
3397
|
+
}
|
|
3398
|
+
function parseCorpusDocument(kind, relativePath, content) {
|
|
3399
|
+
let text = content.charCodeAt(0) === 65279 ? content.slice(1) : content;
|
|
3400
|
+
if (!text.endsWith(`
|
|
3401
|
+
`))
|
|
3402
|
+
text += `
|
|
3403
|
+
`;
|
|
3404
|
+
const parsed = parseFrontmatter(text);
|
|
3405
|
+
if (parsed.parseError)
|
|
3406
|
+
return { ok: false, reason: "invalid frontmatter" };
|
|
3407
|
+
if (parsed.hadFrontmatter && !isRecord(parsed.data)) {
|
|
3408
|
+
return { ok: false, reason: "frontmatter is not a mapping" };
|
|
3409
|
+
}
|
|
3410
|
+
const data = isRecord(parsed.data) ? parsed.data : {};
|
|
3411
|
+
const fileName = relativePath.slice(relativePath.lastIndexOf("/") + 1);
|
|
3412
|
+
const title = narrowString(data.title)?.trim();
|
|
3413
|
+
return {
|
|
3414
|
+
ok: true,
|
|
3415
|
+
document: {
|
|
3416
|
+
path: relativePath,
|
|
3417
|
+
kind,
|
|
3418
|
+
title: title ? title : fileName.replace(/\.md$/i, ""),
|
|
3419
|
+
tags: narrowStringList(data.tags),
|
|
3420
|
+
module: narrowString(data.module),
|
|
3421
|
+
component: narrowString(data.component),
|
|
3422
|
+
problemType: narrowString(data.problem_type),
|
|
3423
|
+
symptoms: narrowStringList(data.symptoms),
|
|
3424
|
+
appliesWhen: narrowStringList(data.applies_when),
|
|
3425
|
+
status: narrowString(data.status),
|
|
3426
|
+
supersededBy: narrowSupersededBy(data.superseded_by),
|
|
3427
|
+
staleReason: narrowString(data.stale_reason),
|
|
3428
|
+
body: parsed.body
|
|
3429
|
+
}
|
|
3430
|
+
};
|
|
3431
|
+
}
|
|
3432
|
+
function readCandidates(spec, kind, candidates, considered, warnings) {
|
|
3433
|
+
const documents = [];
|
|
3434
|
+
let totalBytes = 0;
|
|
3435
|
+
for (let index = 0;index < considered; index++) {
|
|
3436
|
+
const candidate = candidates[index];
|
|
3437
|
+
if (candidate === undefined)
|
|
3438
|
+
break;
|
|
3439
|
+
const logicalPath = `${spec.dir}/${candidate.relative}`;
|
|
3440
|
+
const display = cleanForWarning(logicalPath);
|
|
3441
|
+
if (candidate.size > MAX_FILE_BYTES) {
|
|
3442
|
+
warnings.push(`skipped ${display}: larger than ${MAX_FILE_BYTES} bytes`);
|
|
3443
|
+
continue;
|
|
3444
|
+
}
|
|
3445
|
+
if (totalBytes + candidate.size > MAX_TOTAL_BYTES) {
|
|
3446
|
+
return { documents, budgetSkipped: considered - index };
|
|
3447
|
+
}
|
|
3448
|
+
totalBytes += candidate.size;
|
|
3449
|
+
let bytes;
|
|
3450
|
+
try {
|
|
3451
|
+
bytes = fs2.readFileSync(candidate.absolute);
|
|
3452
|
+
} catch {
|
|
3453
|
+
warnings.push(`skipped ${display}: could not be read`);
|
|
3454
|
+
continue;
|
|
3455
|
+
}
|
|
3456
|
+
if (bytes.byteLength > MAX_FILE_BYTES) {
|
|
3457
|
+
warnings.push(`skipped ${display}: larger than ${MAX_FILE_BYTES} bytes`);
|
|
3458
|
+
continue;
|
|
3459
|
+
}
|
|
3460
|
+
const parsed = parseCorpusDocument(kind, logicalPath, bytes.toString("utf8"));
|
|
3461
|
+
if (parsed.ok)
|
|
3462
|
+
documents.push(parsed.document);
|
|
3463
|
+
else
|
|
3464
|
+
warnings.push(`skipped ${display}: ${parsed.reason}`);
|
|
3465
|
+
}
|
|
3466
|
+
return { documents, budgetSkipped: 0 };
|
|
3467
|
+
}
|
|
3468
|
+
function loadCorpus(root, kind = "solution") {
|
|
3469
|
+
const spec = KIND_TABLE[kind];
|
|
3470
|
+
const warnings = [];
|
|
3471
|
+
const none = { state: "none", documents: [], warnings };
|
|
3472
|
+
const unreadable = () => {
|
|
3473
|
+
warnings.push(`could not read ${spec.dir}; not loaded`);
|
|
3474
|
+
return none;
|
|
3475
|
+
};
|
|
3476
|
+
const rootProbe = probeRealpath(root);
|
|
3477
|
+
const directoryProbe = probeRealpath(path2.join(root, ...spec.dir.split("/")));
|
|
3478
|
+
if (rootProbe.kind === "failed" || directoryProbe.kind === "failed") {
|
|
3479
|
+
return unreadable();
|
|
3480
|
+
}
|
|
3481
|
+
if (rootProbe.kind !== "ok" || directoryProbe.kind !== "ok")
|
|
3482
|
+
return none;
|
|
3483
|
+
const rootReal = rootProbe.value;
|
|
3484
|
+
const directoryReal = directoryProbe.value;
|
|
3485
|
+
const statProbe = probeLstat(directoryReal);
|
|
3486
|
+
if (statProbe.kind === "failed")
|
|
3487
|
+
return unreadable();
|
|
3488
|
+
if (statProbe.kind !== "ok" || !statProbe.value.isDirectory())
|
|
3489
|
+
return none;
|
|
3490
|
+
if (!isInside(rootReal, directoryReal)) {
|
|
3491
|
+
warnings.push(`${spec.dir} resolves outside the project root; not loaded`);
|
|
3492
|
+
return none;
|
|
3493
|
+
}
|
|
3494
|
+
const found = { candidates: [], truncated: false };
|
|
3495
|
+
discoverFiles(spec, directoryReal, "", 0, found, warnings);
|
|
3496
|
+
const candidates = found.candidates.sort((a, b) => compareCodeUnits(a.relative, b.relative));
|
|
3497
|
+
const considered = Math.min(candidates.length, MAX_FILES);
|
|
3498
|
+
const { documents, budgetSkipped } = readCandidates(spec, kind, candidates, considered, warnings);
|
|
3499
|
+
const capSkipped = candidates.length - considered;
|
|
3500
|
+
if (capSkipped > 0) {
|
|
3501
|
+
const atLeast = found.truncated ? "at least " : "";
|
|
3502
|
+
warnings.push(`file limit of ${MAX_FILES} reached; skipped ${atLeast}${capSkipped} files`);
|
|
3503
|
+
}
|
|
3504
|
+
if (budgetSkipped > 0) {
|
|
3505
|
+
warnings.push(`text budget of ${MAX_TOTAL_BYTES} bytes reached; skipped ${budgetSkipped} files`);
|
|
3506
|
+
}
|
|
3507
|
+
return { state: "loaded", documents, warnings };
|
|
3508
|
+
}
|
|
3509
|
+
|
|
3510
|
+
// src/lib/search-lexical.ts
|
|
3511
|
+
var LEXICAL_FIELDS = [
|
|
3512
|
+
"title",
|
|
3513
|
+
"tags",
|
|
3514
|
+
"module",
|
|
3515
|
+
"symptoms",
|
|
3516
|
+
"applies_when",
|
|
3517
|
+
"component",
|
|
3518
|
+
"problem_type",
|
|
3519
|
+
"body"
|
|
3520
|
+
];
|
|
3521
|
+
var BM25F_PARAMS = {
|
|
3522
|
+
k1: 1.2,
|
|
3523
|
+
fields: {
|
|
3524
|
+
title: { weight: 3, b: 0 },
|
|
3525
|
+
tags: { weight: 2.5, b: 0 },
|
|
3526
|
+
module: { weight: 2, b: 0 },
|
|
3527
|
+
symptoms: { weight: 3, b: 0 },
|
|
3528
|
+
applies_when: { weight: 2, b: 0 },
|
|
3529
|
+
component: { weight: 1.5, b: 0 },
|
|
3530
|
+
problem_type: { weight: 1.5, b: 0 },
|
|
3531
|
+
body: { weight: 1, b: 0.75 }
|
|
3532
|
+
}
|
|
3533
|
+
};
|
|
3534
|
+
var MAX_QUERY_TERMS = 64;
|
|
3535
|
+
var IDENTIFIER_RUN = /[a-z0-9]+(?:[_-]+[a-z0-9]+)*/g;
|
|
3536
|
+
var WORD = /[a-z0-9]+/g;
|
|
3537
|
+
function tokenize(text) {
|
|
3538
|
+
const tokens = [];
|
|
3539
|
+
for (const match of text.toLowerCase().matchAll(IDENTIFIER_RUN)) {
|
|
3540
|
+
const run = match[0];
|
|
3541
|
+
const words = run.match(WORD);
|
|
3542
|
+
if (words === null)
|
|
3543
|
+
continue;
|
|
3544
|
+
if (words.length === 1) {
|
|
3545
|
+
tokens.push(run);
|
|
3546
|
+
continue;
|
|
3547
|
+
}
|
|
3548
|
+
tokens.push(run, ...words);
|
|
3549
|
+
}
|
|
3550
|
+
return tokens;
|
|
3551
|
+
}
|
|
3552
|
+
function uniqueQueryTerms(query, max = MAX_QUERY_TERMS) {
|
|
3553
|
+
const seen = new Set;
|
|
3554
|
+
for (const token of tokenize(query))
|
|
3555
|
+
seen.add(token);
|
|
3556
|
+
const all = [...seen];
|
|
3557
|
+
const truncated = all.length > max;
|
|
3558
|
+
const terms = (truncated ? all.slice(0, max) : all).sort(compareCodeUnits2);
|
|
3559
|
+
return { terms, truncated };
|
|
3560
|
+
}
|
|
3561
|
+
function compareCodeUnits2(a, b) {
|
|
3562
|
+
if (a < b)
|
|
3563
|
+
return -1;
|
|
3564
|
+
if (a > b)
|
|
3565
|
+
return 1;
|
|
3566
|
+
return 0;
|
|
3567
|
+
}
|
|
3568
|
+
var LN2_HI = 0.6931471803691238;
|
|
3569
|
+
var LN2_LO = 0.00000000019082149292705877;
|
|
3570
|
+
var SQRT2 = Math.SQRT2;
|
|
3571
|
+
var SQRT_HALF = Math.SQRT1_2;
|
|
3572
|
+
function ln(x) {
|
|
3573
|
+
if (Number.isNaN(x) || x < 0)
|
|
3574
|
+
return Number.NaN;
|
|
3575
|
+
if (x === 0)
|
|
3576
|
+
return Number.NEGATIVE_INFINITY;
|
|
3577
|
+
if (x === Number.POSITIVE_INFINITY)
|
|
3578
|
+
return x;
|
|
3579
|
+
let m = x;
|
|
3580
|
+
let k = 0;
|
|
3581
|
+
while (m >= SQRT2) {
|
|
3582
|
+
m /= 2;
|
|
3583
|
+
k += 1;
|
|
3584
|
+
}
|
|
3585
|
+
while (m < SQRT_HALF) {
|
|
3586
|
+
m *= 2;
|
|
3587
|
+
k -= 1;
|
|
3588
|
+
}
|
|
3589
|
+
const s = (m - 1) / (m + 1);
|
|
3590
|
+
const s2 = s * s;
|
|
3591
|
+
let series = 1 / 25;
|
|
3592
|
+
for (let d = 23;d >= 1; d -= 2)
|
|
3593
|
+
series = series * s2 + 1 / d;
|
|
3594
|
+
const small = 2 * s * series;
|
|
3595
|
+
return k * LN2_HI + (k * LN2_LO + small);
|
|
3596
|
+
}
|
|
3597
|
+
function buildLexicalIndex(documents, params = BM25F_PARAMS) {
|
|
3598
|
+
const documentFrequency = new Map;
|
|
3599
|
+
const totals = LEXICAL_FIELDS.map(() => 0);
|
|
3600
|
+
const docs = [];
|
|
3601
|
+
for (const document of documents) {
|
|
3602
|
+
const seenInDocument = new Set;
|
|
3603
|
+
const fields = LEXICAL_FIELDS.map((field, fieldIndex) => {
|
|
3604
|
+
const tokens = tokenize(document.fields[field] ?? "");
|
|
3605
|
+
const tf = new Map;
|
|
3606
|
+
for (const token of tokens) {
|
|
3607
|
+
tf.set(token, (tf.get(token) ?? 0) + 1);
|
|
3608
|
+
seenInDocument.add(token);
|
|
3609
|
+
}
|
|
3610
|
+
totals[fieldIndex] = (totals[fieldIndex] ?? 0) + tokens.length;
|
|
3611
|
+
return { tf, length: tokens.length };
|
|
3612
|
+
});
|
|
3613
|
+
for (const term of seenInDocument) {
|
|
3614
|
+
documentFrequency.set(term, (documentFrequency.get(term) ?? 0) + 1);
|
|
3615
|
+
}
|
|
3616
|
+
docs.push({ id: document.id, fields });
|
|
3617
|
+
}
|
|
3618
|
+
const count = docs.length;
|
|
3619
|
+
const averageLength = totals.map((total) => count === 0 ? 0 : total / count);
|
|
3620
|
+
return { params, docs, documentFrequency, averageLength };
|
|
3621
|
+
}
|
|
3622
|
+
function weightedFrequency(index, document, term) {
|
|
3623
|
+
let total = 0;
|
|
3624
|
+
for (let i = 0;i < LEXICAL_FIELDS.length; i++) {
|
|
3625
|
+
const field = LEXICAL_FIELDS[i];
|
|
3626
|
+
const stats = document.fields[i];
|
|
3627
|
+
const tf = stats?.tf.get(term);
|
|
3628
|
+
if (field === undefined || stats === undefined || tf === undefined)
|
|
3629
|
+
continue;
|
|
3630
|
+
const { weight, b } = index.params.fields[field];
|
|
3631
|
+
const average = index.averageLength[i] ?? 0;
|
|
3632
|
+
const normalisation = 1 - b + b * (stats.length / average);
|
|
3633
|
+
total += weight * tf / normalisation;
|
|
3634
|
+
}
|
|
3635
|
+
return total;
|
|
3636
|
+
}
|
|
3637
|
+
function searchLexical(index, terms) {
|
|
3638
|
+
const total = index.docs.length;
|
|
3639
|
+
const weighted = [];
|
|
3640
|
+
for (const term of [...new Set(terms)].sort(compareCodeUnits2)) {
|
|
3641
|
+
const df = index.documentFrequency.get(term);
|
|
3642
|
+
if (df === undefined)
|
|
3643
|
+
continue;
|
|
3644
|
+
weighted.push({ term, idf: ln(1 + (total - df + 0.5) / (df + 0.5)) });
|
|
3645
|
+
}
|
|
3646
|
+
const { k1 } = index.params;
|
|
3647
|
+
const hits = [];
|
|
3648
|
+
for (const document of index.docs) {
|
|
3649
|
+
let score = 0;
|
|
3650
|
+
for (const { term, idf } of weighted) {
|
|
3651
|
+
const wtf = weightedFrequency(index, document, term);
|
|
3652
|
+
if (wtf === 0)
|
|
3653
|
+
continue;
|
|
3654
|
+
score += idf * wtf / (k1 + wtf);
|
|
3655
|
+
}
|
|
3656
|
+
if (score > 0)
|
|
3657
|
+
hits.push({ id: document.id, score });
|
|
3658
|
+
}
|
|
3659
|
+
return hits.sort((a, b) => b.score - a.score || compareCodeUnits2(a.id, b.id));
|
|
3660
|
+
}
|
|
3661
|
+
|
|
3662
|
+
// src/lib/search-render.ts
|
|
3663
|
+
var MAX_OUTPUT_BYTES = 16 * 1024;
|
|
3664
|
+
var TRUNCATION_MARKER = "[Systematic: search output truncated at 16 KB]";
|
|
3665
|
+
var MAX_TITLE_CHARS = 160;
|
|
3666
|
+
var MAX_TAGS = 8;
|
|
3667
|
+
var MAX_SNIPPET_CHARS = 240;
|
|
3668
|
+
var MAX_WARNINGS = 5;
|
|
3669
|
+
var SUPERSEDES_LABEL = "Supersedes:";
|
|
3670
|
+
var MAX_TAG_CHARS = 64;
|
|
3671
|
+
var MAX_MODULE_CHARS = 120;
|
|
3672
|
+
var MAX_QUERY_ECHO_CHARS = 200;
|
|
3673
|
+
var MAX_WARNING_CHARS = 200;
|
|
3674
|
+
var MAX_NOTE_CHARS = 200;
|
|
3675
|
+
var MAX_LIFECYCLE_LINE_CHARS = 400;
|
|
3676
|
+
var MAX_PATH_CHARS = 400;
|
|
3677
|
+
var MAX_LABEL_CHARS = 40;
|
|
3678
|
+
var ELLIPSIS = "…";
|
|
3679
|
+
var ANSI_SEQUENCE2 = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|[@-Z\\-_])/g;
|
|
3680
|
+
var LINE_BREAKS = /[\t\n\r\u000b\u000c\u0085\u2028\u2029]+/g;
|
|
3681
|
+
var CONTROL_CHARACTERS2 = /[\u0000-\u001f\u007f-\u009f]/g;
|
|
3682
|
+
var INVISIBLE_FORMATTING = /[\u200b-\u200f\u202a-\u202e\u2060-\u2064\u2066-\u2069\ufeff]/g;
|
|
3683
|
+
function isHighSurrogate(code) {
|
|
3684
|
+
return code >= 55296 && code <= 56319;
|
|
3685
|
+
}
|
|
3686
|
+
function isLowSurrogate(code) {
|
|
3687
|
+
return code >= 56320 && code <= 57343;
|
|
3688
|
+
}
|
|
3689
|
+
function clip(text, max) {
|
|
3690
|
+
if (text.length <= max)
|
|
3691
|
+
return text;
|
|
3692
|
+
let cut = Math.max(0, max - ELLIPSIS.length);
|
|
3693
|
+
if (cut > 0 && isHighSurrogate(text.charCodeAt(cut - 1)))
|
|
3694
|
+
cut -= 1;
|
|
3695
|
+
return `${text.slice(0, cut)}${ELLIPSIS}`;
|
|
3696
|
+
}
|
|
3697
|
+
function sanitizeInline(text, max = Number.POSITIVE_INFINITY) {
|
|
3698
|
+
const clean = text.replace(ANSI_SEQUENCE2, "").replace(LINE_BREAKS, " ").replace(CONTROL_CHARACTERS2, "").replace(INVISIBLE_FORMATTING, "").replace(/ {2,}/g, " ").trim();
|
|
3699
|
+
return clip(clean, max);
|
|
3700
|
+
}
|
|
3701
|
+
function truncateUtf8(text, maxBytes, marker) {
|
|
3702
|
+
const encoder = new TextEncoder;
|
|
3703
|
+
const bytes = encoder.encode(text);
|
|
3704
|
+
if (bytes.byteLength <= maxBytes)
|
|
3705
|
+
return text;
|
|
3706
|
+
const tail = `
|
|
3707
|
+
${marker}`;
|
|
3708
|
+
const budget = Math.max(0, maxBytes - encoder.encode(tail).byteLength);
|
|
3709
|
+
let cut = budget;
|
|
3710
|
+
while (cut > 0 && ((bytes[cut] ?? 0) & 192) === 128)
|
|
3711
|
+
cut -= 1;
|
|
3712
|
+
let kept = new TextDecoder("utf-8").decode(bytes.subarray(0, cut));
|
|
3713
|
+
const lastBreak = kept.lastIndexOf(`
|
|
3714
|
+
`);
|
|
3715
|
+
if (lastBreak > 0)
|
|
3716
|
+
kept = kept.slice(0, lastBreak);
|
|
3717
|
+
return `${kept}${tail}`;
|
|
3718
|
+
}
|
|
3719
|
+
var IDENTIFIER_RUN2 = /[a-z0-9]+(?:[_-]+[a-z0-9]+)*/gi;
|
|
3720
|
+
var WORD2 = /[a-z0-9]+/g;
|
|
3721
|
+
function matchedTerms(run, wanted) {
|
|
3722
|
+
const lower = run.toLowerCase();
|
|
3723
|
+
const matched = [];
|
|
3724
|
+
if (wanted.has(lower))
|
|
3725
|
+
matched.push(lower);
|
|
3726
|
+
if (lower.includes("_") || lower.includes("-")) {
|
|
3727
|
+
for (const part of lower.match(WORD2) ?? []) {
|
|
3728
|
+
if (wanted.has(part) && !matched.includes(part))
|
|
3729
|
+
matched.push(part);
|
|
3730
|
+
}
|
|
3731
|
+
}
|
|
3732
|
+
return matched;
|
|
3733
|
+
}
|
|
3734
|
+
function findOccurrences(text, wanted) {
|
|
3735
|
+
const found = [];
|
|
3736
|
+
for (const match of text.matchAll(IDENTIFIER_RUN2)) {
|
|
3737
|
+
const run = match[0];
|
|
3738
|
+
const terms = matchedTerms(run, wanted);
|
|
3739
|
+
if (terms.length === 0)
|
|
3740
|
+
continue;
|
|
3741
|
+
const start = match.index ?? 0;
|
|
3742
|
+
found.push({ start, end: start + run.length, terms });
|
|
3743
|
+
}
|
|
3744
|
+
return found;
|
|
3745
|
+
}
|
|
3746
|
+
function addTerms(counts, terms) {
|
|
3747
|
+
for (const term of terms)
|
|
3748
|
+
counts.set(term, (counts.get(term) ?? 0) + 1);
|
|
3749
|
+
}
|
|
3750
|
+
function removeTerms(counts, terms) {
|
|
3751
|
+
for (const term of terms) {
|
|
3752
|
+
const remaining = (counts.get(term) ?? 1) - 1;
|
|
3753
|
+
if (remaining <= 0)
|
|
3754
|
+
counts.delete(term);
|
|
3755
|
+
else
|
|
3756
|
+
counts.set(term, remaining);
|
|
3757
|
+
}
|
|
3758
|
+
}
|
|
3759
|
+
function densestWindow(occurrences, width) {
|
|
3760
|
+
const counts = new Map;
|
|
3761
|
+
let best;
|
|
3762
|
+
let bestDistinct = 0;
|
|
3763
|
+
let next = 0;
|
|
3764
|
+
for (let first = 0;first < occurrences.length; first++) {
|
|
3765
|
+
const head = occurrences[first];
|
|
3766
|
+
if (head === undefined)
|
|
3767
|
+
break;
|
|
3768
|
+
for (let candidate = occurrences[next];candidate !== undefined && candidate.end - head.start <= width; candidate = occurrences[next]) {
|
|
3769
|
+
addTerms(counts, candidate.terms);
|
|
3770
|
+
next += 1;
|
|
3771
|
+
}
|
|
3772
|
+
if (next === first) {
|
|
3773
|
+
next = first + 1;
|
|
3774
|
+
continue;
|
|
3775
|
+
}
|
|
3776
|
+
if (counts.size > bestDistinct) {
|
|
3777
|
+
bestDistinct = counts.size;
|
|
3778
|
+
best = { first, last: next - 1 };
|
|
3779
|
+
}
|
|
3780
|
+
removeTerms(counts, head.terms);
|
|
3781
|
+
}
|
|
3782
|
+
return best;
|
|
3783
|
+
}
|
|
3784
|
+
function cutAround(text, spanStart, spanEnd, inner) {
|
|
3785
|
+
const middle = Math.floor((spanStart + spanEnd) / 2);
|
|
3786
|
+
let begin = Math.max(0, middle - Math.floor(inner / 2));
|
|
3787
|
+
const end0 = Math.min(text.length, begin + inner);
|
|
3788
|
+
begin = Math.max(0, end0 - inner);
|
|
3789
|
+
let end = end0;
|
|
3790
|
+
if (begin > 0 && text.charAt(begin - 1) !== " ") {
|
|
3791
|
+
const space = text.indexOf(" ", begin);
|
|
3792
|
+
if (space !== -1 && space + 1 <= spanStart)
|
|
3793
|
+
begin = space + 1;
|
|
3794
|
+
}
|
|
3795
|
+
if (end < text.length && text.charAt(end) !== " ") {
|
|
3796
|
+
const space = text.lastIndexOf(" ", end);
|
|
3797
|
+
if (space >= spanEnd)
|
|
3798
|
+
end = space;
|
|
3799
|
+
}
|
|
3800
|
+
if (begin > 0 && isLowSurrogate(text.charCodeAt(begin)))
|
|
3801
|
+
begin += 1;
|
|
3802
|
+
if (end < text.length && isHighSurrogate(text.charCodeAt(end - 1)))
|
|
3803
|
+
end -= 1;
|
|
3804
|
+
const body = text.slice(begin, end).trim();
|
|
3805
|
+
return `${begin > 0 ? ELLIPSIS : ""}${body}${end < text.length ? ELLIPSIS : ""}`;
|
|
3806
|
+
}
|
|
3807
|
+
function bodySnippet(text, queryTerms) {
|
|
3808
|
+
if (text === "" || queryTerms.length === 0)
|
|
3809
|
+
return;
|
|
3810
|
+
const occurrences = findOccurrences(text, new Set(queryTerms));
|
|
3811
|
+
const head = occurrences[0];
|
|
3812
|
+
if (head === undefined)
|
|
3813
|
+
return;
|
|
3814
|
+
const inner = MAX_SNIPPET_CHARS - 2 * ELLIPSIS.length;
|
|
3815
|
+
const window = densestWindow(occurrences, inner);
|
|
3816
|
+
const first = window === undefined ? head : occurrences[window.first];
|
|
3817
|
+
const last = window === undefined ? head : occurrences[window.last];
|
|
3818
|
+
if (first === undefined || last === undefined)
|
|
3819
|
+
return;
|
|
3820
|
+
const snippet = window === undefined ? clip(text.slice(first.start), MAX_SNIPPET_CHARS) : cutAround(text, first.start, last.end, inner);
|
|
3821
|
+
return snippet === "" ? undefined : snippet;
|
|
3822
|
+
}
|
|
3823
|
+
function extractSnippet(document, queryTerms) {
|
|
3824
|
+
const fromBody = bodySnippet(sanitizeInline(document.body), queryTerms);
|
|
3825
|
+
if (fromBody !== undefined)
|
|
3826
|
+
return fromBody;
|
|
3827
|
+
const symptoms = sanitizeInline(document.symptoms.join("; "), MAX_SNIPPET_CHARS);
|
|
3828
|
+
if (symptoms !== "")
|
|
3829
|
+
return symptoms;
|
|
3830
|
+
return sanitizeInline(document.title, MAX_SNIPPET_CHARS);
|
|
3831
|
+
}
|
|
3832
|
+
function plural(count, singular) {
|
|
3833
|
+
return `${count} ${singular}${count === 1 ? "" : "s"}`;
|
|
3834
|
+
}
|
|
3835
|
+
function renderHeader(result) {
|
|
3836
|
+
const query = sanitizeInline(result.query, MAX_QUERY_ECHO_CHARS);
|
|
3837
|
+
const prefix = `Search "${query}":`;
|
|
3838
|
+
switch (result.corpus.state) {
|
|
3839
|
+
case "none":
|
|
3840
|
+
return `${prefix} corpus: none (no docs/solutions/ directory under the project root).`;
|
|
3841
|
+
case "empty":
|
|
3842
|
+
return `${prefix} corpus: empty (docs/solutions/ holds no indexable docs).`;
|
|
3843
|
+
case "docs":
|
|
3844
|
+
return `${prefix} ${plural(result.corpus.docCount, "doc")}, ${plural(result.hits.length, "hit")}. Corpus: docs/solutions.`;
|
|
3845
|
+
}
|
|
3846
|
+
}
|
|
3847
|
+
function renderLifecycleLine(line) {
|
|
3848
|
+
const prefix = `${SUPERSEDES_LABEL} `;
|
|
3849
|
+
if (!line.startsWith(prefix)) {
|
|
3850
|
+
return sanitizeInline(line, MAX_LIFECYCLE_LINE_CHARS);
|
|
3851
|
+
}
|
|
3852
|
+
const paths = line.slice(prefix.length).split(", ").map((path) => sanitizeInline(path, MAX_PATH_CHARS)).filter((path) => path !== "");
|
|
3853
|
+
return `${prefix}${paths.join(", ")}`;
|
|
3854
|
+
}
|
|
3855
|
+
function renderHit(hit, queryTerms) {
|
|
3856
|
+
const { document } = hit;
|
|
3857
|
+
const lines = [`${hit.rank}. ${sanitizeInline(document.path)}`];
|
|
3858
|
+
lines.push(` ${[
|
|
3859
|
+
`Title: ${sanitizeInline(document.title, MAX_TITLE_CHARS)}`,
|
|
3860
|
+
`Kind: ${sanitizeInline(document.kind, MAX_LABEL_CHARS)}`,
|
|
3861
|
+
`Status: ${sanitizeInline(hit.status, MAX_LABEL_CHARS)}`
|
|
3862
|
+
].join(" | ")}`);
|
|
3863
|
+
const module = document.module === undefined ? "" : sanitizeInline(document.module, MAX_MODULE_CHARS);
|
|
3864
|
+
const tags = document.tags.map((tag) => sanitizeInline(tag, MAX_TAG_CHARS)).filter((tag) => tag !== "").slice(0, MAX_TAGS);
|
|
3865
|
+
const meta = [];
|
|
3866
|
+
if (module !== "")
|
|
3867
|
+
meta.push(`Module: ${module}`);
|
|
3868
|
+
if (tags.length > 0)
|
|
3869
|
+
meta.push(`Tags: ${tags.join(", ")}`);
|
|
3870
|
+
if (meta.length > 0)
|
|
3871
|
+
lines.push(` ${meta.join(" | ")}`);
|
|
3872
|
+
lines.push(` Snippet: ${extractSnippet(document, queryTerms)}`);
|
|
3873
|
+
for (const line of hit.lifecycle)
|
|
3874
|
+
lines.push(` ${renderLifecycleLine(line)}`);
|
|
3875
|
+
return lines;
|
|
3876
|
+
}
|
|
3877
|
+
function renderSearchResult(result) {
|
|
3878
|
+
const lines = [renderHeader(result)];
|
|
3879
|
+
if (result.notes.length > 0) {
|
|
3880
|
+
lines.push(`Notes: ${result.notes.map((note) => sanitizeInline(note, MAX_NOTE_CHARS)).join("; ")}`);
|
|
3881
|
+
}
|
|
3882
|
+
if (result.warnings.length > 0) {
|
|
3883
|
+
lines.push("Warnings:");
|
|
3884
|
+
for (const warning of result.warnings.slice(0, MAX_WARNINGS)) {
|
|
3885
|
+
lines.push(`- ${sanitizeInline(warning, MAX_WARNING_CHARS)}`);
|
|
3886
|
+
}
|
|
3887
|
+
const hidden = result.warnings.length - MAX_WARNINGS;
|
|
3888
|
+
if (hidden > 0)
|
|
3889
|
+
lines.push(`- +${hidden} more`);
|
|
3890
|
+
}
|
|
3891
|
+
for (const hit of result.hits) {
|
|
3892
|
+
lines.push("", ...renderHit(hit, result.queryTerms));
|
|
3893
|
+
}
|
|
3894
|
+
return truncateUtf8(lines.join(`
|
|
3895
|
+
`), MAX_OUTPUT_BYTES, TRUNCATION_MARKER);
|
|
3896
|
+
}
|
|
3897
|
+
|
|
3898
|
+
// src/lib/search-core.ts
|
|
3899
|
+
var SEARCH_TOOL_NAME = "systematic_search";
|
|
3900
|
+
var SEARCH_ARGS = {
|
|
3901
|
+
query: "query",
|
|
3902
|
+
kind: "kind",
|
|
3903
|
+
limit: "limit"
|
|
3904
|
+
};
|
|
3905
|
+
var DEFAULT_LIMIT = 8;
|
|
3906
|
+
var MIN_LIMIT = 1;
|
|
3907
|
+
var MAX_LIMIT = 20;
|
|
3908
|
+
var MAX_QUERY_CHARS = 2000;
|
|
3909
|
+
var SEARCH_TOOL_DESCRIPTION = "Search this project's durable outputs (the docs/solutions learnings) by symptom, error text, module or topic. Returns ranked hits with path, title, snippet, tags and status. A superseded learning is replaced by its successor, and a stale one carries a caution. Read a hit's path for the full text. Use it before debugging a failure or planning work a past learning may already cover.";
|
|
3910
|
+
var SEARCH_ARG_DESCRIPTIONS = {
|
|
3911
|
+
query: `What to look for: a symptom, error message, module or topic, in plain words. At most ${MAX_QUERY_CHARS} characters.`,
|
|
3912
|
+
kind: 'Optional. The kind of durable output to search. Only "solution" (docs/solutions/) exists today, and it is the default.',
|
|
3913
|
+
limit: `Optional. How many hits to return, an integer from ${MIN_LIMIT} to ${MAX_LIMIT}. Defaults to ${DEFAULT_LIMIT}.`
|
|
3914
|
+
};
|
|
3915
|
+
var SEARCH_NOTICES = {
|
|
3916
|
+
failed: "Error: search failed.",
|
|
3917
|
+
noProject: "No project directory is available for this session, so there is nothing to search."
|
|
3918
|
+
};
|
|
3919
|
+
var SEARCH_CONFIG_UNREADABLE_NOTE = "config unreadable";
|
|
3920
|
+
var MAX_SUCCESSOR_HOPS = 5;
|
|
3921
|
+
var SUCCESSOR_PATH_PREFIX = `${KIND_TABLE.solution.dir}/`;
|
|
3922
|
+
var CAUTION_LABEL = "Caution:";
|
|
3923
|
+
var SUCCESSOR_UNRESOLVED_TEXT = "successor unresolved";
|
|
3924
|
+
var STALE_CAUTION_TEXT = "marked stale";
|
|
3925
|
+
var MAX_STALE_REASON_CHARS = 200;
|
|
3926
|
+
var SEARCH_ERRORS = {
|
|
3927
|
+
queryEmpty: "Error: query must be a non-empty string.",
|
|
3928
|
+
queryTooLong: `Error: query must be at most ${MAX_QUERY_CHARS} characters.`,
|
|
3929
|
+
kindUnknown: `Error: kind must be one of: ${Object.keys(KIND_TABLE).join(", ")}.`,
|
|
3930
|
+
limitInvalid: `Error: limit must be an integer from ${MIN_LIMIT} to ${MAX_LIMIT}.`
|
|
3931
|
+
};
|
|
3932
|
+
function isSuccessorPathForm(value) {
|
|
3933
|
+
if (!value.startsWith(SUCCESSOR_PATH_PREFIX))
|
|
3934
|
+
return false;
|
|
3935
|
+
if (!value.endsWith(".md"))
|
|
3936
|
+
return false;
|
|
3937
|
+
const segments = value.split("/");
|
|
3938
|
+
if (segments.includes(".."))
|
|
3939
|
+
return false;
|
|
3940
|
+
const name = segments[segments.length - 1]?.toLowerCase();
|
|
3941
|
+
if (name === "readme.md")
|
|
3942
|
+
return false;
|
|
3943
|
+
if (segments.includes("_archived"))
|
|
3944
|
+
return false;
|
|
3945
|
+
return true;
|
|
3946
|
+
}
|
|
3947
|
+
function resolveSuccessor(candidate, byPath) {
|
|
3948
|
+
const visited = new Set([candidate.path]);
|
|
3949
|
+
let current = candidate;
|
|
3950
|
+
for (let hop = 1;hop <= MAX_SUCCESSOR_HOPS; hop++) {
|
|
3951
|
+
const link = current.supersededBy;
|
|
3952
|
+
if (link.state !== "value" || !isSuccessorPathForm(link.value)) {
|
|
3953
|
+
return;
|
|
3954
|
+
}
|
|
3955
|
+
if (visited.has(link.value))
|
|
3956
|
+
return;
|
|
3957
|
+
const target = byPath.get(link.value);
|
|
3958
|
+
if (target === undefined)
|
|
3959
|
+
return;
|
|
3960
|
+
visited.add(target.path);
|
|
3961
|
+
if (target.status !== "superseded")
|
|
3962
|
+
return target;
|
|
3963
|
+
current = target;
|
|
3964
|
+
}
|
|
3965
|
+
return;
|
|
3966
|
+
}
|
|
3967
|
+
function compareCodeUnits3(a, b) {
|
|
3968
|
+
if (a < b)
|
|
3969
|
+
return -1;
|
|
3970
|
+
return a > b ? 1 : 0;
|
|
3971
|
+
}
|
|
3972
|
+
function resolveLifecycle(ranked, documents) {
|
|
3973
|
+
const byPath = new Map(documents.map((doc) => [doc.path, doc]));
|
|
3974
|
+
const order = [];
|
|
3975
|
+
const entries = new Map;
|
|
3976
|
+
for (const candidate of ranked) {
|
|
3977
|
+
let target = candidate;
|
|
3978
|
+
let replaces;
|
|
3979
|
+
let unresolved = false;
|
|
3980
|
+
if (candidate.status === "superseded") {
|
|
3981
|
+
const successor = resolveSuccessor(candidate, byPath);
|
|
3982
|
+
if (successor === undefined)
|
|
3983
|
+
unresolved = true;
|
|
3984
|
+
else {
|
|
3985
|
+
target = successor;
|
|
3986
|
+
replaces = candidate.path;
|
|
3987
|
+
}
|
|
3988
|
+
}
|
|
3989
|
+
let entry = entries.get(target.path);
|
|
3990
|
+
if (entry === undefined) {
|
|
3991
|
+
entry = { document: target, replaced: new Set, unresolved };
|
|
3992
|
+
entries.set(target.path, entry);
|
|
3993
|
+
order.push(target.path);
|
|
3994
|
+
}
|
|
3995
|
+
if (replaces !== undefined)
|
|
3996
|
+
entry.replaced.add(replaces);
|
|
3997
|
+
}
|
|
3998
|
+
return order.flatMap((path) => {
|
|
3999
|
+
const entry = entries.get(path);
|
|
4000
|
+
if (entry === undefined)
|
|
4001
|
+
return [];
|
|
4002
|
+
return [
|
|
4003
|
+
{
|
|
4004
|
+
document: entry.document,
|
|
4005
|
+
supersedes: [...entry.replaced].sort(compareCodeUnits3),
|
|
4006
|
+
unresolved: entry.unresolved
|
|
4007
|
+
}
|
|
4008
|
+
];
|
|
4009
|
+
});
|
|
4010
|
+
}
|
|
4011
|
+
function entryStatus(entry) {
|
|
4012
|
+
if (entry.unresolved)
|
|
4013
|
+
return "superseded";
|
|
4014
|
+
return entry.document.status === "stale" ? "stale" : "active";
|
|
4015
|
+
}
|
|
4016
|
+
function lifecycleLines(entry) {
|
|
4017
|
+
const lines = [];
|
|
4018
|
+
if (entry.supersedes.length > 0) {
|
|
4019
|
+
lines.push(`${SUPERSEDES_LABEL} ${entry.supersedes.join(", ")}`);
|
|
4020
|
+
}
|
|
4021
|
+
if (entry.unresolved) {
|
|
4022
|
+
lines.push(`${CAUTION_LABEL} ${SUCCESSOR_UNRESOLVED_TEXT}`);
|
|
4023
|
+
} else if (entry.document.status === "stale") {
|
|
4024
|
+
const reason = sanitizeInline(entry.document.staleReason ?? "", MAX_STALE_REASON_CHARS);
|
|
4025
|
+
lines.push(reason === "" ? `${CAUTION_LABEL} ${STALE_CAUTION_TEXT}` : `${CAUTION_LABEL} ${STALE_CAUTION_TEXT}: ${reason}`);
|
|
4026
|
+
}
|
|
4027
|
+
return lines;
|
|
4028
|
+
}
|
|
4029
|
+
function toLexicalDocument(document) {
|
|
4030
|
+
return {
|
|
4031
|
+
id: document.path,
|
|
4032
|
+
fields: {
|
|
4033
|
+
title: document.title,
|
|
4034
|
+
tags: document.tags.join(" "),
|
|
4035
|
+
module: document.module ?? "",
|
|
4036
|
+
symptoms: document.symptoms.join(`
|
|
4037
|
+
`),
|
|
4038
|
+
applies_when: document.appliesWhen.join(`
|
|
4039
|
+
`),
|
|
4040
|
+
component: document.component ?? "",
|
|
4041
|
+
problem_type: document.problemType ?? "",
|
|
4042
|
+
body: document.body
|
|
4043
|
+
}
|
|
4044
|
+
};
|
|
4045
|
+
}
|
|
4046
|
+
function validate(request) {
|
|
4047
|
+
const { query } = request;
|
|
4048
|
+
if (typeof query !== "string" || query.trim() === "") {
|
|
4049
|
+
return { ok: false, error: SEARCH_ERRORS.queryEmpty };
|
|
4050
|
+
}
|
|
4051
|
+
if (query.length > MAX_QUERY_CHARS) {
|
|
4052
|
+
return { ok: false, error: SEARCH_ERRORS.queryTooLong };
|
|
4053
|
+
}
|
|
4054
|
+
let kind = "solution";
|
|
4055
|
+
if (request.kind !== undefined) {
|
|
4056
|
+
if (!isDocumentKind(request.kind)) {
|
|
4057
|
+
return { ok: false, error: SEARCH_ERRORS.kindUnknown };
|
|
4058
|
+
}
|
|
4059
|
+
kind = request.kind;
|
|
4060
|
+
}
|
|
4061
|
+
let limit = DEFAULT_LIMIT;
|
|
4062
|
+
if (request.limit !== undefined) {
|
|
4063
|
+
const value = request.limit;
|
|
4064
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < MIN_LIMIT || value > MAX_LIMIT) {
|
|
4065
|
+
return { ok: false, error: SEARCH_ERRORS.limitInvalid };
|
|
4066
|
+
}
|
|
4067
|
+
limit = value;
|
|
4068
|
+
}
|
|
4069
|
+
return { ok: true, query, kind, limit };
|
|
4070
|
+
}
|
|
4071
|
+
async function runSearch(request, options) {
|
|
4072
|
+
const checked = validate(request);
|
|
4073
|
+
if (!checked.ok)
|
|
4074
|
+
return { ok: false, text: checked.error };
|
|
4075
|
+
const { query, kind, limit } = checked;
|
|
4076
|
+
const root = resolveSearchRoot(options.startDir);
|
|
4077
|
+
const load = (options.corpusLoader ?? loadCorpus)(root, kind);
|
|
4078
|
+
const { terms, truncated } = uniqueQueryTerms(query);
|
|
4079
|
+
const base = {
|
|
4080
|
+
query,
|
|
4081
|
+
queryTerms: terms,
|
|
4082
|
+
warnings: load.warnings
|
|
4083
|
+
};
|
|
4084
|
+
const noteList = [...options.notes ?? []];
|
|
4085
|
+
if (truncated)
|
|
4086
|
+
noteList.push("query cut to its first 64 distinct terms");
|
|
4087
|
+
const finish = (result) => ({
|
|
4088
|
+
ok: true,
|
|
4089
|
+
text: renderSearchResult(result),
|
|
4090
|
+
result
|
|
4091
|
+
});
|
|
4092
|
+
if (load.state === "none") {
|
|
4093
|
+
return finish({
|
|
4094
|
+
...base,
|
|
4095
|
+
corpus: { state: "none", docCount: 0 },
|
|
4096
|
+
hits: [],
|
|
4097
|
+
notes: noteList
|
|
4098
|
+
});
|
|
4099
|
+
}
|
|
4100
|
+
if (load.documents.length === 0) {
|
|
4101
|
+
return finish({
|
|
4102
|
+
...base,
|
|
4103
|
+
corpus: { state: "empty", docCount: 0 },
|
|
4104
|
+
hits: [],
|
|
4105
|
+
notes: noteList
|
|
4106
|
+
});
|
|
4107
|
+
}
|
|
4108
|
+
const index = buildLexicalIndex(load.documents.map(toLexicalDocument), options.lexicalParams ?? BM25F_PARAMS);
|
|
4109
|
+
const lexical = searchLexical(index, terms);
|
|
4110
|
+
const byPath = new Map(load.documents.map((doc) => [doc.path, doc]));
|
|
4111
|
+
const candidates = [];
|
|
4112
|
+
for (const hit of lexical) {
|
|
4113
|
+
const document = byPath.get(hit.id);
|
|
4114
|
+
if (document !== undefined)
|
|
4115
|
+
candidates.push(document);
|
|
4116
|
+
}
|
|
4117
|
+
const hits = resolveLifecycle(candidates, load.documents).slice(0, limit).map((entry, position) => ({
|
|
4118
|
+
rank: position + 1,
|
|
4119
|
+
document: entry.document,
|
|
4120
|
+
status: entryStatus(entry),
|
|
4121
|
+
lifecycle: lifecycleLines(entry)
|
|
4122
|
+
}));
|
|
4123
|
+
return finish({
|
|
4124
|
+
...base,
|
|
4125
|
+
corpus: { state: "docs", docCount: load.documents.length },
|
|
4126
|
+
hits,
|
|
4127
|
+
notes: noteList
|
|
4128
|
+
});
|
|
4129
|
+
}
|
|
4130
|
+
|
|
3242
4131
|
// src/lib/agent-resolver.ts
|
|
3243
4132
|
function buildAgentCatalog(agentsDir) {
|
|
3244
4133
|
const infos = findAgentsInDir(agentsDir);
|
|
3245
4134
|
const byName = new Map;
|
|
3246
4135
|
const entries = [];
|
|
3247
4136
|
for (const info of infos) {
|
|
3248
|
-
const content =
|
|
4137
|
+
const content = fs3.readFileSync(info.file, "utf8");
|
|
3249
4138
|
const parsed = parseValidatedAgentEntry(content, info.file);
|
|
3250
4139
|
const category = info.category ?? "";
|
|
3251
4140
|
const key = info.name;
|
|
@@ -3316,14 +4205,21 @@ function extractRawToolsSource(data, sourceFile) {
|
|
|
3316
4205
|
function resolveAgent(catalog, name) {
|
|
3317
4206
|
return catalog.find((entry) => entry.name === name);
|
|
3318
4207
|
}
|
|
3319
|
-
var DEFAULT_READONLY_TOOLS = [
|
|
4208
|
+
var DEFAULT_READONLY_TOOLS = [
|
|
4209
|
+
"read",
|
|
4210
|
+
"grep",
|
|
4211
|
+
"find",
|
|
4212
|
+
"ls",
|
|
4213
|
+
SEARCH_TOOL_NAME
|
|
4214
|
+
];
|
|
3320
4215
|
var OPENCODE_TO_PI_TOOL = {
|
|
3321
4216
|
Read: "read",
|
|
3322
4217
|
Grep: "grep",
|
|
3323
4218
|
Glob: "find",
|
|
3324
4219
|
Bash: "bash",
|
|
3325
4220
|
Edit: "edit",
|
|
3326
|
-
Write: "write"
|
|
4221
|
+
Write: "write",
|
|
4222
|
+
[SEARCH_TOOL_NAME]: SEARCH_TOOL_NAME
|
|
3327
4223
|
};
|
|
3328
4224
|
function unknownDeclaredToolError(toolName) {
|
|
3329
4225
|
const error = new Error(`Unknown declared tool "${toolName}" in persona frontmatter; refusing to map ` + "to a Pi built-in (fail-closed). Known tools: " + `${Object.keys(OPENCODE_TO_PI_TOOL).join(", ")}.`);
|
|
@@ -3350,22 +4246,22 @@ function resolveToolAllowlist(toolsSource) {
|
|
|
3350
4246
|
}
|
|
3351
4247
|
|
|
3352
4248
|
// src/lib/bootstrap.ts
|
|
3353
|
-
import
|
|
4249
|
+
import fs4 from "node:fs";
|
|
3354
4250
|
import os from "node:os";
|
|
3355
|
-
import
|
|
4251
|
+
import path3 from "node:path";
|
|
3356
4252
|
function readHarnessProfile(bundledSkillsDir, name) {
|
|
3357
|
-
const profilePath =
|
|
4253
|
+
const profilePath = path3.join(bundledSkillsDir, "using-systematic/references", `${name}-profile.md`);
|
|
3358
4254
|
try {
|
|
3359
|
-
return
|
|
4255
|
+
return fs4.readFileSync(profilePath, "utf8");
|
|
3360
4256
|
} catch (error) {
|
|
3361
4257
|
console.error(`Failed to read harness profile ${profilePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
3362
4258
|
return null;
|
|
3363
4259
|
}
|
|
3364
4260
|
}
|
|
3365
4261
|
function readWorktreePlacementRule(bundledSkillsDir) {
|
|
3366
|
-
const rulePath =
|
|
4262
|
+
const rulePath = path3.join(bundledSkillsDir, "using-systematic/references/worktree-placement.md");
|
|
3367
4263
|
try {
|
|
3368
|
-
return
|
|
4264
|
+
return fs4.readFileSync(rulePath, "utf8").trim();
|
|
3369
4265
|
} catch (error) {
|
|
3370
4266
|
console.error(`Failed to read worktree placement rule ${rulePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
3371
4267
|
return null;
|
|
@@ -3422,15 +4318,15 @@ function getBootstrapContent(config, deps) {
|
|
|
3422
4318
|
if (!config.bootstrap.enabled)
|
|
3423
4319
|
return null;
|
|
3424
4320
|
if (config.bootstrap.file) {
|
|
3425
|
-
const customPath = config.bootstrap.file.startsWith("~/") ?
|
|
3426
|
-
if (
|
|
3427
|
-
return
|
|
4321
|
+
const customPath = config.bootstrap.file.startsWith("~/") ? path3.join(os.homedir(), config.bootstrap.file.slice(2)) : config.bootstrap.file;
|
|
4322
|
+
if (fs4.existsSync(customPath)) {
|
|
4323
|
+
return fs4.readFileSync(customPath, "utf8");
|
|
3428
4324
|
}
|
|
3429
4325
|
}
|
|
3430
|
-
const usingSystematicPath =
|
|
3431
|
-
if (!
|
|
4326
|
+
const usingSystematicPath = path3.join(bundledSkillsDir, "using-systematic/SKILL.md");
|
|
4327
|
+
if (!fs4.existsSync(usingSystematicPath))
|
|
3432
4328
|
return null;
|
|
3433
|
-
const fullContent =
|
|
4329
|
+
const fullContent = fs4.readFileSync(usingSystematicPath, "utf8");
|
|
3434
4330
|
const { body } = parseFrontmatter(fullContent);
|
|
3435
4331
|
const content = body.trim();
|
|
3436
4332
|
const skillUsage = usageTemplate ?? getSkillUsageTemplate();
|
|
@@ -3452,12 +4348,11 @@ ${skillUsage}${ruleSection}${profileSection}
|
|
|
3452
4348
|
}
|
|
3453
4349
|
|
|
3454
4350
|
// src/lib/config.ts
|
|
3455
|
-
import
|
|
3456
|
-
import
|
|
3457
|
-
import path3 from "node:path";
|
|
4351
|
+
import fs6 from "node:fs";
|
|
4352
|
+
import path5 from "node:path";
|
|
3458
4353
|
import {
|
|
3459
|
-
parse as
|
|
3460
|
-
printParseErrorCode
|
|
4354
|
+
parse as parseJsonc2,
|
|
4355
|
+
printParseErrorCode as printParseErrorCode2
|
|
3461
4356
|
} from "jsonc-parser";
|
|
3462
4357
|
|
|
3463
4358
|
// src/lib/bundled-names.ts
|
|
@@ -4434,7 +5329,7 @@ var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
|
|
|
4434
5329
|
};
|
|
4435
5330
|
var COMPILE_INVALID = /* @__PURE__ */ Symbol.for("zod.compile.invalid");
|
|
4436
5331
|
var COMPILE_FALLBACK = /* @__PURE__ */ Symbol.for("zod.compile.fallback");
|
|
4437
|
-
var
|
|
5332
|
+
var validate2 = (schema, value, _ctx) => {
|
|
4438
5333
|
const validator = schema._zod.bag.validator;
|
|
4439
5334
|
if (validator !== undefined) {
|
|
4440
5335
|
if (validator(value) !== COMPILE_INVALID)
|
|
@@ -8620,7 +9515,7 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
|
|
|
8620
9515
|
own(this, "spa", value);
|
|
8621
9516
|
},
|
|
8622
9517
|
validate(data, params) {
|
|
8623
|
-
return
|
|
9518
|
+
return validate2(this, data, params);
|
|
8624
9519
|
},
|
|
8625
9520
|
validateAsync(data, params) {
|
|
8626
9521
|
return validateAsync(this, data, params);
|
|
@@ -9436,6 +10331,79 @@ var REMOVED_CONFIG_KEYS = [
|
|
|
9436
10331
|
"workflow_guard"
|
|
9437
10332
|
];
|
|
9438
10333
|
|
|
10334
|
+
// src/lib/search-user-config.ts
|
|
10335
|
+
import fs5 from "node:fs";
|
|
10336
|
+
import os2 from "node:os";
|
|
10337
|
+
import path4 from "node:path";
|
|
10338
|
+
import {
|
|
10339
|
+
parse as parseJsonc,
|
|
10340
|
+
printParseErrorCode
|
|
10341
|
+
} from "jsonc-parser";
|
|
10342
|
+
var SearchSettingsSchema = object({
|
|
10343
|
+
enabled: boolean2().optional().meta({
|
|
10344
|
+
description: "Set to false to remove the search tool. Defaults to true when unset.",
|
|
10345
|
+
examples: [false]
|
|
10346
|
+
})
|
|
10347
|
+
}).strict().meta({
|
|
10348
|
+
description: "Durable-output search settings. Only user config and OPENCODE_CONFIG_DIR config may set this field; a project config that sets it has the whole field ignored with a warning, so a repository cannot switch search off. An invalid block is dropped with a warning; the rest of the file still loads.",
|
|
10349
|
+
examples: [{ enabled: false }]
|
|
10350
|
+
});
|
|
10351
|
+
function validateSearchBlock(value) {
|
|
10352
|
+
const parsed = SearchSettingsSchema.safeParse(value);
|
|
10353
|
+
if (parsed.success)
|
|
10354
|
+
return { ok: true, settings: parsed.data };
|
|
10355
|
+
const fields = [];
|
|
10356
|
+
for (const issue of parsed.error.issues) {
|
|
10357
|
+
const field = ["search", ...issue.path.map(String)].join(".");
|
|
10358
|
+
if (!fields.includes(field))
|
|
10359
|
+
fields.push(field);
|
|
10360
|
+
}
|
|
10361
|
+
return { ok: false, fields };
|
|
10362
|
+
}
|
|
10363
|
+
var MAX_WARNING_FIELDS = 5;
|
|
10364
|
+
var MAX_PATH_CHARS2 = 200;
|
|
10365
|
+
function displaySafe(text) {
|
|
10366
|
+
let out = "";
|
|
10367
|
+
for (const char of text) {
|
|
10368
|
+
if (out.length >= MAX_PATH_CHARS2)
|
|
10369
|
+
return `${out}…`;
|
|
10370
|
+
const code = char.codePointAt(0) ?? 0;
|
|
10371
|
+
const isControl = code <= 31 || code === 127 || code >= 128 && code <= 159 || code === 8232 || code === 8233;
|
|
10372
|
+
out += isControl ? `\\u${code.toString(16).padStart(4, "0")}` : char;
|
|
10373
|
+
}
|
|
10374
|
+
return out;
|
|
10375
|
+
}
|
|
10376
|
+
function formatSearchBlockWarning(sourcePath, fields) {
|
|
10377
|
+
const shown = fields.slice(0, MAX_WARNING_FIELDS).join(", ");
|
|
10378
|
+
const more = fields.length > MAX_WARNING_FIELDS ? ` and ${fields.length - MAX_WARNING_FIELDS} more` : "";
|
|
10379
|
+
return `[systematic] \`search\` in ${displaySafe(sourcePath)} is invalid (${shown}${more}) and has been ignored; search still runs and its results carry a \`config unreadable\` note. The rest of the file still loads.`;
|
|
10380
|
+
}
|
|
10381
|
+
function mergeSearchSettings(sources) {
|
|
10382
|
+
let enabled;
|
|
10383
|
+
let unreadable = false;
|
|
10384
|
+
for (const source of sources) {
|
|
10385
|
+
if (source.unreadable)
|
|
10386
|
+
unreadable = true;
|
|
10387
|
+
if (source.settings?.enabled !== undefined)
|
|
10388
|
+
enabled = source.settings.enabled;
|
|
10389
|
+
}
|
|
10390
|
+
if (enabled === undefined)
|
|
10391
|
+
return { settings: undefined, unreadable };
|
|
10392
|
+
return { settings: { enabled }, unreadable };
|
|
10393
|
+
}
|
|
10394
|
+
function selectConfigFile(dir, basename) {
|
|
10395
|
+
const jsoncPath = path4.join(dir, `${basename}.jsonc`);
|
|
10396
|
+
if (fs5.existsSync(jsoncPath))
|
|
10397
|
+
return jsoncPath;
|
|
10398
|
+
return path4.join(dir, `${basename}.json`);
|
|
10399
|
+
}
|
|
10400
|
+
function resolveUserLevelConfigDirs(options) {
|
|
10401
|
+
const homeDir = options?.homeDir ?? os2.homedir();
|
|
10402
|
+
const userConfigDir = options?.userConfigDir ?? path4.join(homeDir, ".config/opencode");
|
|
10403
|
+
const rawCustom = options !== undefined && Object.hasOwn(options, "customConfigDir") ? options.customConfigDir?.trim() : process.env.OPENCODE_CONFIG_DIR?.trim();
|
|
10404
|
+
return { homeDir, userConfigDir, customConfigDir: rawCustom || undefined };
|
|
10405
|
+
}
|
|
10406
|
+
|
|
9439
10407
|
// src/lib/config-schema.ts
|
|
9440
10408
|
var permissionSettingSchema = _enum(["ask", "allow", "deny"]);
|
|
9441
10409
|
var permissionRuleSchema = union([
|
|
@@ -9725,6 +10693,7 @@ function createSystematicConfigSchema(opts) {
|
|
|
9725
10693
|
description: "Allow a repository's project config to define its own `profiles` map. User-owned only — only valid in user config or OPENCODE_CONFIG_DIR config; a project config setting this field has it ignored (a project cannot grant itself a permission it does not already have). Defaults to false.",
|
|
9726
10694
|
examples: [true, false]
|
|
9727
10695
|
})).default(false),
|
|
10696
|
+
search: trustProtected(SearchSettingsSchema).optional(),
|
|
9728
10697
|
disabled_skills: array(_enum([...skillNames, ...removedSkillNames])).default([]).meta({
|
|
9729
10698
|
description: "Array of bundled skill names to disable globally. Unknown skill names are rejected at parse time.",
|
|
9730
10699
|
examples: [["ce:plan", "ce:review"]]
|
|
@@ -10049,7 +11018,10 @@ var PROTECTED_OVERLAY_FIELD_PATHS = {
|
|
|
10049
11018
|
pi: "categories.*.pi"
|
|
10050
11019
|
}
|
|
10051
11020
|
};
|
|
10052
|
-
var PROJECT_ALWAYS_PROTECTED_FIELDS = new Set([
|
|
11021
|
+
var PROJECT_ALWAYS_PROTECTED_FIELDS = new Set([
|
|
11022
|
+
"allow_project_profiles",
|
|
11023
|
+
"search"
|
|
11024
|
+
]);
|
|
10053
11025
|
var MAX_DIAGNOSTIC_TEXT = 200;
|
|
10054
11026
|
var MAX_STRIP_WARNINGS = 20;
|
|
10055
11027
|
var DIAGNOSTIC_ELLIPSIS = "…";
|
|
@@ -10126,29 +11098,23 @@ function warnDroppedNames(dropped, field, warned, removalVersion, warningSink =
|
|
|
10126
11098
|
warningSink(`[systematic] "${displayName}" in \`${field}\` is no longer a bundled name and will be ignored.${removalNote} Remove it from your config to silence this warning. See ${MIGRATION_DOCS_URL} for migration guidance.`);
|
|
10127
11099
|
}
|
|
10128
11100
|
}
|
|
10129
|
-
function resolveConfigPath(dir, basename) {
|
|
10130
|
-
const jsoncPath = path3.join(dir, `${basename}.jsonc`);
|
|
10131
|
-
if (fs4.existsSync(jsoncPath))
|
|
10132
|
-
return jsoncPath;
|
|
10133
|
-
return path3.join(dir, `${basename}.json`);
|
|
10134
|
-
}
|
|
10135
11101
|
function isErrorWithCode(error) {
|
|
10136
11102
|
return error instanceof Error && "code" in error;
|
|
10137
11103
|
}
|
|
10138
11104
|
function loadJsoncFile(filePath) {
|
|
10139
11105
|
let content;
|
|
10140
11106
|
try {
|
|
10141
|
-
content =
|
|
11107
|
+
content = fs6.readFileSync(filePath, "utf-8");
|
|
10142
11108
|
} catch (error) {
|
|
10143
11109
|
if (isErrorWithCode(error) && error.code === "ENOENT")
|
|
10144
11110
|
return null;
|
|
10145
11111
|
throw new Error(`Invalid Systematic config in ${filePath}: unable to read file`, { cause: error });
|
|
10146
11112
|
}
|
|
10147
11113
|
const errors = [];
|
|
10148
|
-
const parsed =
|
|
11114
|
+
const parsed = parseJsonc2(content, errors);
|
|
10149
11115
|
if (errors.length > 0) {
|
|
10150
11116
|
const error = errors[0];
|
|
10151
|
-
const message = error ? `${
|
|
11117
|
+
const message = error ? `${printParseErrorCode2(error.error)} at offset ${error.offset}` : "unknown parse error";
|
|
10152
11118
|
throw new Error(`Invalid Systematic config in ${filePath}: JSONC parse error: ${message}`);
|
|
10153
11119
|
}
|
|
10154
11120
|
if (!isRecord2(parsed)) {
|
|
@@ -10254,19 +11220,21 @@ function loadConfigSource(filePath, trust, invalidSource, warningSink, allowProj
|
|
|
10254
11220
|
const protectedFields = collectProjectProtectedFields(rawConfig, trust, allowProjectProfiles);
|
|
10255
11221
|
const topLevelStripped = trust === "project" ? stripProjectProtectedFields(rawConfig, allowProjectProfiles) : rawConfig;
|
|
10256
11222
|
const config = trust === "project" ? stripProjectSecurityOverlayFields(topLevelStripped, filePath, warningSink) : topLevelStripped;
|
|
10257
|
-
const
|
|
11223
|
+
const { config: configWithoutSearch, search } = splitSearchBlock(config, filePath, warningSink);
|
|
11224
|
+
const result = SystematicConfigSchema.safeParse(configWithoutSearch);
|
|
10258
11225
|
if (!result.success) {
|
|
10259
|
-
throwTopLevelConfigSchemaError(filePath, trust, result.error.issues,
|
|
11226
|
+
throwTopLevelConfigSchemaError(filePath, trust, result.error.issues, configWithoutSearch);
|
|
10260
11227
|
}
|
|
10261
11228
|
return {
|
|
10262
11229
|
metadata: { kind: trust, presence: "present" },
|
|
10263
11230
|
source: {
|
|
10264
11231
|
kind: "file",
|
|
10265
11232
|
canonicalPath: resolveConfigSourcePath(filePath),
|
|
10266
|
-
config,
|
|
11233
|
+
config: configWithoutSearch,
|
|
10267
11234
|
path: filePath,
|
|
10268
11235
|
protectedFields,
|
|
10269
11236
|
removedKeys: REMOVED_CONFIG_KEYS.filter((key) => Object.hasOwn(rawConfig, key)),
|
|
11237
|
+
...search && { search },
|
|
10270
11238
|
trust
|
|
10271
11239
|
}
|
|
10272
11240
|
};
|
|
@@ -10283,6 +11251,23 @@ function loadConfigSource(filePath, trust, invalidSource, warningSink, allowProj
|
|
|
10283
11251
|
};
|
|
10284
11252
|
}
|
|
10285
11253
|
}
|
|
11254
|
+
function splitSearchBlock(config, filePath, warningSink) {
|
|
11255
|
+
if (!Object.hasOwn(config, "search"))
|
|
11256
|
+
return { config, search: undefined };
|
|
11257
|
+
const { search: rawSearch, ...rest } = config;
|
|
11258
|
+
const validation = validateSearchBlock(rawSearch);
|
|
11259
|
+
if (validation.ok) {
|
|
11260
|
+
return {
|
|
11261
|
+
config: rest,
|
|
11262
|
+
search: { settings: validation.settings, unreadable: false }
|
|
11263
|
+
};
|
|
11264
|
+
}
|
|
11265
|
+
warningSink(formatSearchBlockWarning(filePath, validation.fields));
|
|
11266
|
+
return {
|
|
11267
|
+
config: rest,
|
|
11268
|
+
search: { unreadable: true }
|
|
11269
|
+
};
|
|
11270
|
+
}
|
|
10286
11271
|
function classifyConfigSourceError(error) {
|
|
10287
11272
|
if (isConfigSchemaError(error))
|
|
10288
11273
|
return "schema-invalid";
|
|
@@ -10299,9 +11284,9 @@ function isConfigSchemaError(error) {
|
|
|
10299
11284
|
}
|
|
10300
11285
|
function resolveConfigSourcePath(filePath) {
|
|
10301
11286
|
try {
|
|
10302
|
-
return
|
|
11287
|
+
return fs6.realpathSync(filePath);
|
|
10303
11288
|
} catch {
|
|
10304
|
-
return
|
|
11289
|
+
return path5.resolve(filePath);
|
|
10305
11290
|
}
|
|
10306
11291
|
}
|
|
10307
11292
|
function emitTopLevelProtectedFieldWarning(projectSource, fieldPath, messageTemplate, sink) {
|
|
@@ -10329,6 +11314,13 @@ function collectProjectProtectedFields(rawConfig, trust, allowProjectProfiles) {
|
|
|
10329
11314
|
sourceKind: "project"
|
|
10330
11315
|
}
|
|
10331
11316
|
] : [],
|
|
11317
|
+
...Object.hasOwn(rawConfig, "search") ? [
|
|
11318
|
+
{
|
|
11319
|
+
fieldPath: "search",
|
|
11320
|
+
outcome: "blocked",
|
|
11321
|
+
sourceKind: "project"
|
|
11322
|
+
}
|
|
11323
|
+
] : [],
|
|
10332
11324
|
...collectOverlayProtectedFields(rawConfig.agents, "agents"),
|
|
10333
11325
|
...collectOverlayProtectedFields(rawConfig.categories, "categories")
|
|
10334
11326
|
];
|
|
@@ -10592,6 +11584,7 @@ function loadConfigWithSources(projectDir, options) {
|
|
|
10592
11584
|
const projectSource = project.source;
|
|
10593
11585
|
emitTopLevelProtectedFieldWarning(projectSource, "profiles", `\`profiles\` in project config (%PATH%) is only valid in user config or OPENCODE_CONFIG_DIR config and has been ignored. Its bundles are not selectable even if this project also sets \`profile\`.`, boundedProjectStrip.sink);
|
|
10594
11586
|
emitTopLevelProtectedFieldWarning(projectSource, "allow_project_profiles", `\`allow_project_profiles\` in project config (%PATH%) is only valid in user config or OPENCODE_CONFIG_DIR config and has been ignored.`, boundedProjectStrip.sink);
|
|
11587
|
+
emitTopLevelProtectedFieldWarning(projectSource, "search", `\`search\` in project config (%PATH%) is only valid in user config or OPENCODE_CONFIG_DIR config and has been ignored.`, boundedProjectStrip.sink);
|
|
10595
11588
|
const suppressedStripCount = boundedProjectStrip.suppressedCount();
|
|
10596
11589
|
if (suppressedStripCount > 0) {
|
|
10597
11590
|
projectStrip.sink(`[systematic] ${suppressedStripCount} additional project-config protected-field warning(s) in (${sanitizeDiagnosticText(paths.projectConfig)}) were suppressed.`);
|
|
@@ -10617,6 +11610,7 @@ function loadConfigWithSources(projectDir, options) {
|
|
|
10617
11610
|
const projectConfig = projectSource?.config;
|
|
10618
11611
|
const customConfig = customSource?.config;
|
|
10619
11612
|
const warned = new Set;
|
|
11613
|
+
const mergedSearch = mergeSearchSettings([userSource?.search, customSource?.search].filter((source) => source !== undefined));
|
|
10620
11614
|
assertAllProfileBundlesAreValid(userConfig, customConfig, projectConfig);
|
|
10621
11615
|
const profileSelection = resolveActiveProfile({
|
|
10622
11616
|
userConfig,
|
|
@@ -10669,7 +11663,9 @@ function loadConfigWithSources(projectDir, options) {
|
|
|
10669
11663
|
agents: overlayValues(mergedPiSubagentsOverlays.agents)
|
|
10670
11664
|
},
|
|
10671
11665
|
skills_as_commands: customConfig?.skills_as_commands ?? projectConfig?.skills_as_commands ?? userConfig?.skills_as_commands ?? DEFAULT_CONFIG.skills_as_commands,
|
|
10672
|
-
allow_project_profiles: customConfig?.allow_project_profiles ?? userConfig?.allow_project_profiles ?? DEFAULT_CONFIG.allow_project_profiles
|
|
11666
|
+
allow_project_profiles: customConfig?.allow_project_profiles ?? userConfig?.allow_project_profiles ?? DEFAULT_CONFIG.allow_project_profiles,
|
|
11667
|
+
...mergedSearch.settings && { search: mergedSearch.settings },
|
|
11668
|
+
...mergedSearch.unreadable && { searchUnreadable: true }
|
|
10673
11669
|
};
|
|
10674
11670
|
const droppedSkills = computeDroppedNames(result.disabled_skills, CURRENT_SKILL_NAMES_SET);
|
|
10675
11671
|
warnDroppedNames(droppedSkills, "disabled_skills", warned, undefined, warningSink);
|
|
@@ -11009,17 +12005,15 @@ function throwInvalidOverlay(sourcePath, keyPath) {
|
|
|
11009
12005
|
throw new Error(`Invalid Systematic config in ${sourcePath}: ${keyPath} must be an object`);
|
|
11010
12006
|
}
|
|
11011
12007
|
function getConfigPaths(projectDir, options) {
|
|
11012
|
-
const homeDir
|
|
11013
|
-
const userConfigDir = options?.userConfigDir ?? path3.join(homeDir, ".config/opencode");
|
|
11014
|
-
const customConfigDir = options !== undefined && Object.hasOwn(options, "customConfigDir") ? options.customConfigDir?.trim() : process.env.OPENCODE_CONFIG_DIR?.trim();
|
|
12008
|
+
const { homeDir, userConfigDir, customConfigDir } = resolveUserLevelConfigDirs(options);
|
|
11015
12009
|
const result = {
|
|
11016
|
-
userConfig:
|
|
11017
|
-
projectConfig:
|
|
11018
|
-
userDir:
|
|
11019
|
-
projectDir:
|
|
12010
|
+
userConfig: selectConfigFile(userConfigDir, "systematic"),
|
|
12011
|
+
projectConfig: selectConfigFile(path5.join(projectDir, ".opencode"), "systematic"),
|
|
12012
|
+
userDir: path5.join(homeDir, ".config/opencode/systematic"),
|
|
12013
|
+
projectDir: path5.join(projectDir, ".opencode/systematic"),
|
|
11020
12014
|
...customConfigDir && {
|
|
11021
|
-
customConfig:
|
|
11022
|
-
customDir:
|
|
12015
|
+
customConfig: selectConfigFile(customConfigDir, "systematic"),
|
|
12016
|
+
customDir: path5.join(customConfigDir, "systematic")
|
|
11023
12017
|
}
|
|
11024
12018
|
};
|
|
11025
12019
|
return result;
|
|
@@ -11098,7 +12092,7 @@ function renderDelegateCatalogCompact(catalog, budget) {
|
|
|
11098
12092
|
`);
|
|
11099
12093
|
}
|
|
11100
12094
|
function createPiDelegateTool(deps) {
|
|
11101
|
-
const { catalog, createDelegateSession } = deps;
|
|
12095
|
+
const { catalog, createDelegateSession, customTools } = deps;
|
|
11102
12096
|
const routing = {
|
|
11103
12097
|
overlays: deps.overlays ?? EMPTY_ROUTING_OVERLAYS,
|
|
11104
12098
|
piSubagentsOverlays: toSourcedPiSubagentsOverlays(deps.piSubagentsOverlays),
|
|
@@ -11113,7 +12107,7 @@ function createPiDelegateTool(deps) {
|
|
|
11113
12107
|
parameters: buildDelegateParametersSchema(catalog),
|
|
11114
12108
|
executionMode: DELEGATE_EXECUTION_MODE,
|
|
11115
12109
|
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
11116
|
-
return runDelegateTool({ catalog, createDelegateSession }, routing, params, signal, ctx);
|
|
12110
|
+
return runDelegateTool({ catalog, createDelegateSession, customTools }, routing, params, signal, ctx);
|
|
11117
12111
|
}
|
|
11118
12112
|
};
|
|
11119
12113
|
}
|
|
@@ -11296,7 +12290,7 @@ function cleanUpLateSession(session) {
|
|
|
11296
12290
|
} catch {}
|
|
11297
12291
|
});
|
|
11298
12292
|
}
|
|
11299
|
-
async function runValidatedDelegateSession(createDelegateSession, request, signal, cwd) {
|
|
12293
|
+
async function runValidatedDelegateSession(createDelegateSession, request, signal, cwd, customTools) {
|
|
11300
12294
|
const {
|
|
11301
12295
|
agentName,
|
|
11302
12296
|
task,
|
|
@@ -11326,7 +12320,8 @@ async function runValidatedDelegateSession(createDelegateSession, request, signa
|
|
|
11326
12320
|
thinkingLevel,
|
|
11327
12321
|
cwd,
|
|
11328
12322
|
systemPromptOverride: personaBody,
|
|
11329
|
-
allowedToolNames
|
|
12323
|
+
allowedToolNames,
|
|
12324
|
+
...customTools !== undefined && { customTools }
|
|
11330
12325
|
});
|
|
11331
12326
|
sessionPromise.then((session) => {
|
|
11332
12327
|
if (signal?.aborted || state.abortReason !== undefined) {
|
|
@@ -11385,7 +12380,7 @@ async function runValidatedDelegateSession(createDelegateSession, request, signa
|
|
|
11385
12380
|
}
|
|
11386
12381
|
async function runDelegateTool(deps, routing, params, signal, ctx) {
|
|
11387
12382
|
const request = validateDelegateRequest(deps.catalog, params, ctx, routing);
|
|
11388
|
-
return runValidatedDelegateSession(deps.createDelegateSession, request, signal, ctx.cwd);
|
|
12383
|
+
return runValidatedDelegateSession(deps.createDelegateSession, request, signal, ctx.cwd, deps.customTools);
|
|
11389
12384
|
}
|
|
11390
12385
|
|
|
11391
12386
|
// src/lib/pi-delegate-session.ts
|
|
@@ -11416,6 +12411,7 @@ function buildDelegateAgentSessionOptions(options) {
|
|
|
11416
12411
|
model,
|
|
11417
12412
|
thinkingLevel,
|
|
11418
12413
|
allowedToolNames,
|
|
12414
|
+
customTools,
|
|
11419
12415
|
resourceLoader,
|
|
11420
12416
|
sessionManager
|
|
11421
12417
|
} = options;
|
|
@@ -11425,7 +12421,7 @@ function buildDelegateAgentSessionOptions(options) {
|
|
|
11425
12421
|
model,
|
|
11426
12422
|
...thinkingLevel !== undefined && { thinkingLevel },
|
|
11427
12423
|
tools: allowedToolNames,
|
|
11428
|
-
customTools
|
|
12424
|
+
customTools,
|
|
11429
12425
|
resourceLoader,
|
|
11430
12426
|
sessionManager
|
|
11431
12427
|
};
|
|
@@ -11437,11 +12433,15 @@ function createDelegateSessionWith(runtime) {
|
|
|
11437
12433
|
thinkingLevel,
|
|
11438
12434
|
cwd,
|
|
11439
12435
|
systemPromptOverride,
|
|
11440
|
-
allowedToolNames
|
|
12436
|
+
allowedToolNames,
|
|
12437
|
+
customTools = []
|
|
11441
12438
|
} = options;
|
|
11442
12439
|
if (allowedToolNames.includes(DELEGATE_TOOL_NAME)) {
|
|
11443
12440
|
throw new Error(`Refusing to construct delegate child session: allowedToolNames included ${DELEGATE_TOOL_NAME} (fail-closed re-entry guard).`);
|
|
11444
12441
|
}
|
|
12442
|
+
if (customTools.some((tool) => tool.name === DELEGATE_TOOL_NAME)) {
|
|
12443
|
+
throw new Error(`Refusing to construct delegate child session: customTools included ${DELEGATE_TOOL_NAME} (fail-closed re-entry guard).`);
|
|
12444
|
+
}
|
|
11445
12445
|
const agentDir = runtime.getAgentDir();
|
|
11446
12446
|
const resourceLoader = runtime.createResourceLoader(buildDelegateResourceLoaderOptions({
|
|
11447
12447
|
cwd,
|
|
@@ -11456,6 +12456,7 @@ function createDelegateSessionWith(runtime) {
|
|
|
11456
12456
|
model,
|
|
11457
12457
|
thinkingLevel,
|
|
11458
12458
|
allowedToolNames,
|
|
12459
|
+
customTools,
|
|
11459
12460
|
resourceLoader,
|
|
11460
12461
|
sessionManager
|
|
11461
12462
|
}));
|
|
@@ -11596,14 +12597,83 @@ function parseSourceCategoryAndKey(sourceRelPath) {
|
|
|
11596
12597
|
return { category: undefined, agentKey: fileName.replace(/\.md$/, "") };
|
|
11597
12598
|
}
|
|
11598
12599
|
|
|
12600
|
+
// src/lib/search-tool.ts
|
|
12601
|
+
function isSearchEnabled(settings) {
|
|
12602
|
+
return settings?.enabled !== false;
|
|
12603
|
+
}
|
|
12604
|
+
async function executeSearch(args, startDir, settings, unreadable) {
|
|
12605
|
+
try {
|
|
12606
|
+
if (startDir === undefined)
|
|
12607
|
+
return SEARCH_NOTICES.noProject;
|
|
12608
|
+
const record = isRecord(args) ? args : {};
|
|
12609
|
+
const response = await runSearch({
|
|
12610
|
+
query: record[SEARCH_ARGS.query],
|
|
12611
|
+
kind: record[SEARCH_ARGS.kind],
|
|
12612
|
+
limit: record[SEARCH_ARGS.limit]
|
|
12613
|
+
}, {
|
|
12614
|
+
startDir,
|
|
12615
|
+
settings,
|
|
12616
|
+
...unreadable === true && { notes: [SEARCH_CONFIG_UNREADABLE_NOTE] }
|
|
12617
|
+
});
|
|
12618
|
+
return response.text;
|
|
12619
|
+
} catch {
|
|
12620
|
+
return SEARCH_NOTICES.failed;
|
|
12621
|
+
}
|
|
12622
|
+
}
|
|
12623
|
+
function usableDirectory(value) {
|
|
12624
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
12625
|
+
}
|
|
12626
|
+
var V2_INPUT_SCHEMA = {
|
|
12627
|
+
type: "object",
|
|
12628
|
+
properties: {
|
|
12629
|
+
[SEARCH_ARGS.query]: {
|
|
12630
|
+
type: "string",
|
|
12631
|
+
description: SEARCH_ARG_DESCRIPTIONS.query
|
|
12632
|
+
},
|
|
12633
|
+
[SEARCH_ARGS.kind]: {
|
|
12634
|
+
type: "string",
|
|
12635
|
+
description: SEARCH_ARG_DESCRIPTIONS.kind
|
|
12636
|
+
},
|
|
12637
|
+
[SEARCH_ARGS.limit]: {
|
|
12638
|
+
type: "integer",
|
|
12639
|
+
description: SEARCH_ARG_DESCRIPTIONS.limit
|
|
12640
|
+
}
|
|
12641
|
+
},
|
|
12642
|
+
required: [SEARCH_ARGS.query],
|
|
12643
|
+
additionalProperties: false
|
|
12644
|
+
};
|
|
12645
|
+
function buildPiParameters(Type) {
|
|
12646
|
+
return Type.Object({
|
|
12647
|
+
[SEARCH_ARGS.query]: Type.String({
|
|
12648
|
+
description: SEARCH_ARG_DESCRIPTIONS.query
|
|
12649
|
+
}),
|
|
12650
|
+
[SEARCH_ARGS.kind]: Type.Optional(Type.String({ description: SEARCH_ARG_DESCRIPTIONS.kind })),
|
|
12651
|
+
[SEARCH_ARGS.limit]: Type.Optional(Type.Integer({ description: SEARCH_ARG_DESCRIPTIONS.limit }))
|
|
12652
|
+
});
|
|
12653
|
+
}
|
|
12654
|
+
function createPiSearchTool(options) {
|
|
12655
|
+
const { settings, unreadable, Type } = options;
|
|
12656
|
+
return {
|
|
12657
|
+
name: SEARCH_TOOL_NAME,
|
|
12658
|
+
label: "Systematic Search",
|
|
12659
|
+
description: SEARCH_TOOL_DESCRIPTION,
|
|
12660
|
+
promptSnippet: "Use `systematic_search` to find past learnings in docs/solutions.",
|
|
12661
|
+
parameters: buildPiParameters(Type),
|
|
12662
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
12663
|
+
const text = await executeSearch(params, usableDirectory(ctx.cwd), settings, unreadable);
|
|
12664
|
+
return { content: [{ type: "text", text }], details: undefined };
|
|
12665
|
+
}
|
|
12666
|
+
};
|
|
12667
|
+
}
|
|
12668
|
+
|
|
11599
12669
|
// src/lib/skill-resolver.ts
|
|
11600
|
-
import
|
|
11601
|
-
import
|
|
12670
|
+
import fs9 from "node:fs";
|
|
12671
|
+
import path8 from "node:path";
|
|
11602
12672
|
import { pathToFileURL } from "node:url";
|
|
11603
12673
|
|
|
11604
12674
|
// src/lib/skill-loader.ts
|
|
11605
|
-
import
|
|
11606
|
-
import
|
|
12675
|
+
import fs7 from "node:fs";
|
|
12676
|
+
import path6 from "node:path";
|
|
11607
12677
|
var SKILL_PREFIX = "systematic:";
|
|
11608
12678
|
var SKILL_DESCRIPTION_PREFIX = "(Systematic) ";
|
|
11609
12679
|
function formatSkillCommandName(name) {
|
|
@@ -11620,7 +12690,7 @@ function formatSkillDescription(description, fallbackName) {
|
|
|
11620
12690
|
return `${SKILL_DESCRIPTION_PREFIX}${desc}`;
|
|
11621
12691
|
}
|
|
11622
12692
|
function wrapSkillTemplate(skillPath, body) {
|
|
11623
|
-
const skillDir =
|
|
12693
|
+
const skillDir = path6.dirname(skillPath);
|
|
11624
12694
|
return `<skill-instruction>
|
|
11625
12695
|
Base directory for this skill: ${skillDir}/
|
|
11626
12696
|
File references (@path) in this skill are relative to this directory.
|
|
@@ -11639,7 +12709,7 @@ function extractSkillBody(wrappedTemplate) {
|
|
|
11639
12709
|
}
|
|
11640
12710
|
function loadSkill(skillInfo) {
|
|
11641
12711
|
try {
|
|
11642
|
-
const content =
|
|
12712
|
+
const content = fs7.readFileSync(skillInfo.skillFile, "utf8");
|
|
11643
12713
|
const { body } = parseFrontmatter(content);
|
|
11644
12714
|
const wrappedTemplate = wrapSkillTemplate(skillInfo.skillFile, body);
|
|
11645
12715
|
return {
|
|
@@ -11662,8 +12732,8 @@ function loadSkill(skillInfo) {
|
|
|
11662
12732
|
}
|
|
11663
12733
|
|
|
11664
12734
|
// src/lib/skills.ts
|
|
11665
|
-
import
|
|
11666
|
-
import
|
|
12735
|
+
import fs8 from "node:fs";
|
|
12736
|
+
import path7 from "node:path";
|
|
11667
12737
|
function parseMetadata(data) {
|
|
11668
12738
|
const metadataRaw = data.metadata;
|
|
11669
12739
|
if (!isRecord(metadataRaw)) {
|
|
@@ -11700,7 +12770,7 @@ function extractFrontmatterFromContent(content) {
|
|
|
11700
12770
|
}
|
|
11701
12771
|
function extractFrontmatter(filePath) {
|
|
11702
12772
|
try {
|
|
11703
|
-
const content =
|
|
12773
|
+
const content = fs8.readFileSync(filePath, "utf8");
|
|
11704
12774
|
return extractFrontmatterFromContent(content);
|
|
11705
12775
|
} catch {
|
|
11706
12776
|
return { name: "", description: "" };
|
|
@@ -11713,8 +12783,8 @@ function findSkillsInDir(dir, maxDepth = 3) {
|
|
|
11713
12783
|
filter: (e) => e.isDirectory
|
|
11714
12784
|
});
|
|
11715
12785
|
for (const entry of entries) {
|
|
11716
|
-
const skillFile =
|
|
11717
|
-
if (
|
|
12786
|
+
const skillFile = path7.join(entry.path, "SKILL.md");
|
|
12787
|
+
if (fs8.existsSync(skillFile)) {
|
|
11718
12788
|
const frontmatter = extractFrontmatter(skillFile);
|
|
11719
12789
|
skills.push({
|
|
11720
12790
|
path: entry.path,
|
|
@@ -11828,7 +12898,7 @@ ${raw}`;
|
|
|
11828
12898
|
function buildSkillContentOutput(matchedSkill, argument) {
|
|
11829
12899
|
const trimmedBody = extractSkillBody(matchedSkill.wrappedTemplate).trim();
|
|
11830
12900
|
const body = argument === undefined ? trimmedBody : substituteSkillArguments(trimmedBody, argument);
|
|
11831
|
-
const dir =
|
|
12901
|
+
const dir = path8.dirname(matchedSkill.skillFile);
|
|
11832
12902
|
const base = pathToFileURL(dir).href;
|
|
11833
12903
|
const files = discoverSkillFiles(dir);
|
|
11834
12904
|
const lines = [
|
|
@@ -11859,17 +12929,17 @@ function discoverSkillFiles(dir, limit = 10) {
|
|
|
11859
12929
|
function handleEntry(entry, currentDir) {
|
|
11860
12930
|
if (entry.isDirectory()) {
|
|
11861
12931
|
if (!shouldSkipDirectory(entry.name)) {
|
|
11862
|
-
recurse(
|
|
12932
|
+
recurse(path8.resolve(currentDir, entry.name));
|
|
11863
12933
|
}
|
|
11864
12934
|
} else if (shouldIncludeFile(entry.name)) {
|
|
11865
|
-
files.push(
|
|
12935
|
+
files.push(path8.resolve(currentDir, entry.name));
|
|
11866
12936
|
}
|
|
11867
12937
|
}
|
|
11868
12938
|
function recurse(currentDir) {
|
|
11869
12939
|
if (files.length >= limit)
|
|
11870
12940
|
return;
|
|
11871
12941
|
try {
|
|
11872
|
-
const entries =
|
|
12942
|
+
const entries = fs9.readdirSync(currentDir, { withFileTypes: true });
|
|
11873
12943
|
for (const entry of entries) {
|
|
11874
12944
|
if (files.length >= limit)
|
|
11875
12945
|
break;
|
|
@@ -11883,10 +12953,10 @@ function discoverSkillFiles(dir, limit = 10) {
|
|
|
11883
12953
|
}
|
|
11884
12954
|
|
|
11885
12955
|
// src/pi.ts
|
|
11886
|
-
var __dirname2 =
|
|
11887
|
-
var packageRoot =
|
|
11888
|
-
var bundledSkillsDir =
|
|
11889
|
-
var bundledAgentsDir =
|
|
12956
|
+
var __dirname2 = path9.dirname(fileURLToPath(import.meta.url));
|
|
12957
|
+
var packageRoot = path9.resolve(__dirname2, "..");
|
|
12958
|
+
var bundledSkillsDir = path9.join(packageRoot, "skills");
|
|
12959
|
+
var bundledAgentsDir = path9.join(packageRoot, "agents");
|
|
11890
12960
|
var PI_BOOTSTRAP_USAGE_TEMPLATE = `**Skills usage:**
|
|
11891
12961
|
- Use \`systematic_skill\` for Systematic skills.
|
|
11892
12962
|
- For non-Systematic skills, follow Pi's native skill instructions and read the listed SKILL.md path.`;
|
|
@@ -11984,6 +13054,13 @@ async function systematicPiExtension(pi, deps = defaultPiExtensionDependencies)
|
|
|
11984
13054
|
};
|
|
11985
13055
|
}
|
|
11986
13056
|
});
|
|
13057
|
+
const searchTool = isSearchEnabled(piConfig.search) ? createPiSearchTool({
|
|
13058
|
+
settings: piConfig.search,
|
|
13059
|
+
unreadable: piConfig.searchUnreadable,
|
|
13060
|
+
Type: Type3
|
|
13061
|
+
}) : undefined;
|
|
13062
|
+
if (searchTool !== undefined)
|
|
13063
|
+
pi.registerTool(searchTool);
|
|
11987
13064
|
try {
|
|
11988
13065
|
const disabledAgents = new Set(piConfig.disabled_agents);
|
|
11989
13066
|
const catalog = buildAgentCatalogFn(bundledAgentsDir).filter((entry) => !isAgentDisabled(disabledAgents, piRoutingOverlays.agents, entry.category, entry.key));
|
|
@@ -11992,7 +13069,8 @@ async function systematicPiExtension(pi, deps = defaultPiExtensionDependencies)
|
|
|
11992
13069
|
createDelegateSession: createRealPiDelegateSession,
|
|
11993
13070
|
overlays: piRoutingOverlays,
|
|
11994
13071
|
piSubagentsOverlays: piConfig.pi_subagents,
|
|
11995
|
-
activeProfile: piConfigMetadata.activeProfile
|
|
13072
|
+
activeProfile: piConfigMetadata.activeProfile,
|
|
13073
|
+
...searchTool !== undefined && { customTools: [searchTool] }
|
|
11996
13074
|
}));
|
|
11997
13075
|
} catch (error) {
|
|
11998
13076
|
reportPiDelegateCatalogFailure(error);
|