@agimon-ai/po-help 0.0.0-alpha.44 → 0.0.0-alpha.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +109 -84
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +108 -83
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -6
package/dist/index.cjs
CHANGED
|
@@ -23,8 +23,8 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
23
23
|
//#endregion
|
|
24
24
|
let _agimon_ai_po_core_help = require("@agimon-ai/po-core/help");
|
|
25
25
|
let node_crypto = require("node:crypto");
|
|
26
|
-
let
|
|
27
|
-
|
|
26
|
+
let node_fs_promises = require("node:fs/promises");
|
|
27
|
+
node_fs_promises = __toESM(node_fs_promises, 1);
|
|
28
28
|
let node_os = require("node:os");
|
|
29
29
|
node_os = __toESM(node_os, 1);
|
|
30
30
|
let node_path = require("node:path");
|
|
@@ -350,37 +350,37 @@ function isContained(root, candidate) {
|
|
|
350
350
|
const relative = node_path.default.relative(root, candidate);
|
|
351
351
|
return relative === "" || !relative.startsWith(`..${node_path.default.sep}`) && relative !== ".." && !node_path.default.isAbsolute(relative);
|
|
352
352
|
}
|
|
353
|
-
function readManifest(filePath) {
|
|
353
|
+
async function readManifest(filePath) {
|
|
354
354
|
let parsed;
|
|
355
355
|
try {
|
|
356
|
-
parsed = JSON.parse(
|
|
356
|
+
parsed = JSON.parse(await node_fs_promises.default.readFile(filePath, "utf8"));
|
|
357
357
|
} catch (error) {
|
|
358
|
+
if (error.code === "ENOENT") return void 0;
|
|
358
359
|
throw new Error(`Cannot read Help package manifest at ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
359
360
|
}
|
|
360
361
|
if (!isRecord$1(parsed)) throw new Error(`Help package manifest at ${filePath} must contain an object.`);
|
|
361
362
|
return parsed;
|
|
362
363
|
}
|
|
363
|
-
function resolveHelpPackageIdentity(moduleUrl, expectedSource) {
|
|
364
|
+
async function resolveHelpPackageIdentity(moduleUrl, expectedSource) {
|
|
364
365
|
if (!NPM_PACKAGE_NAME_PATTERN.test(expectedSource)) throw new Error(`Help source '${expectedSource}' must be a valid lowercase npm package name.`);
|
|
365
366
|
let modulePath;
|
|
366
367
|
try {
|
|
367
368
|
const url = new URL(moduleUrl);
|
|
368
369
|
if (url.protocol !== "file:") throw new Error(`Help module URL must use file:, received ${url.protocol}`);
|
|
369
|
-
modulePath =
|
|
370
|
+
modulePath = await node_fs_promises.default.realpath((0, node_url.fileURLToPath)(url));
|
|
370
371
|
} catch (error) {
|
|
371
372
|
throw new Error(`Invalid Help contributor module URL '${moduleUrl}': ${error instanceof Error ? error.message : String(error)}`);
|
|
372
373
|
}
|
|
373
|
-
if (!
|
|
374
|
+
if (!(await node_fs_promises.default.lstat(modulePath)).isFile()) throw new Error(`Help contributor module is not a regular file: ${modulePath}`);
|
|
374
375
|
let directory = node_path.default.dirname(modulePath);
|
|
375
376
|
while (true) {
|
|
376
|
-
const
|
|
377
|
-
if (
|
|
378
|
-
const manifest = readManifest(manifestPath);
|
|
377
|
+
const manifest = await readManifest(node_path.default.join(directory, PACKAGE_MANIFEST));
|
|
378
|
+
if (manifest !== void 0) {
|
|
379
379
|
const source = manifest.name;
|
|
380
380
|
const version = manifest.version;
|
|
381
381
|
if (source !== expectedSource) throw new Error(`Help source '${expectedSource}' does not match nearest package '${String(source)}'.`);
|
|
382
382
|
if (typeof version !== "string" || !EXACT_SEMVER_PATTERN.test(version)) throw new Error(`Help package '${expectedSource}' must declare an exact semantic version.`);
|
|
383
|
-
const packageRoot =
|
|
383
|
+
const packageRoot = await node_fs_promises.default.realpath(directory);
|
|
384
384
|
if (!isContained(packageRoot, modulePath)) throw new Error("Help contributor module escapes its resolved package root.");
|
|
385
385
|
return {
|
|
386
386
|
source: expectedSource,
|
|
@@ -406,9 +406,21 @@ function parseCacheMetadata(value, identity) {
|
|
|
406
406
|
if (value.schemaVersion !== CACHE_SCHEMA_VERSION || value.source !== identity.source || value.version !== identity.version || value.path !== HELP_INDEX_PATH$1 || typeof value.integrity !== "string" || typeof value.digest !== "string" || typeof value.referenceBase !== "string") return;
|
|
407
407
|
return value;
|
|
408
408
|
}
|
|
409
|
-
|
|
409
|
+
const cacheMutations = /* @__PURE__ */ new Map();
|
|
410
|
+
async function mutateCacheEntry(directory, operation) {
|
|
411
|
+
const key = node_path.default.resolve(directory);
|
|
412
|
+
const result = (cacheMutations.get(key) ?? Promise.resolve()).then(operation);
|
|
413
|
+
const settled = result.then(() => {}, () => {});
|
|
414
|
+
cacheMutations.set(key, settled);
|
|
410
415
|
try {
|
|
411
|
-
|
|
416
|
+
return await result;
|
|
417
|
+
} finally {
|
|
418
|
+
if (cacheMutations.get(key) === settled) cacheMutations.delete(key);
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
async function regularFile(filePath) {
|
|
422
|
+
try {
|
|
423
|
+
const metadata = await node_fs_promises.default.lstat(filePath);
|
|
412
424
|
return metadata.isFile() && !metadata.isSymbolicLink();
|
|
413
425
|
} catch {
|
|
414
426
|
return false;
|
|
@@ -423,24 +435,25 @@ var HelpIndexCache = class {
|
|
|
423
435
|
const key = sha256Hex(`${identity.source}\0${identity.version}\0${HELP_INDEX_PATH$1}`);
|
|
424
436
|
return node_path.default.join(this.root, key);
|
|
425
437
|
}
|
|
426
|
-
discard(identity) {
|
|
427
|
-
|
|
438
|
+
async discard(identity) {
|
|
439
|
+
const directory = this.entryDirectory(identity);
|
|
440
|
+
await mutateCacheEntry(directory, () => node_fs_promises.default.rm(directory, {
|
|
428
441
|
recursive: true,
|
|
429
442
|
force: true
|
|
430
|
-
});
|
|
443
|
+
}));
|
|
431
444
|
}
|
|
432
|
-
read(identity) {
|
|
445
|
+
async read(identity) {
|
|
433
446
|
const directory = this.entryDirectory(identity);
|
|
434
447
|
const completionPath = node_path.default.join(directory, COMPLETION_FILE);
|
|
435
448
|
const indexPath = node_path.default.join(directory, HELP_INDEX_PATH$1);
|
|
436
449
|
const metadataPath = node_path.default.join(directory, CACHE_METADATA_FILE);
|
|
437
|
-
if (!regularFile(completionPath) || !regularFile(indexPath) || !regularFile(metadataPath)) return void 0;
|
|
450
|
+
if (!await regularFile(completionPath) || !await regularFile(indexPath) || !await regularFile(metadataPath)) return void 0;
|
|
438
451
|
try {
|
|
439
|
-
const metadata = parseCacheMetadata(JSON.parse(
|
|
452
|
+
const metadata = parseCacheMetadata(JSON.parse(await node_fs_promises.default.readFile(metadataPath, "utf8")), identity);
|
|
440
453
|
if (!metadata) return void 0;
|
|
441
|
-
const bytes =
|
|
454
|
+
const bytes = await node_fs_promises.default.readFile(indexPath);
|
|
442
455
|
if (sha256Hex(bytes) !== metadata.digest) return void 0;
|
|
443
|
-
if (
|
|
456
|
+
if ((await node_fs_promises.default.readFile(completionPath, "utf8")).trim() !== metadata.digest) return void 0;
|
|
444
457
|
return {
|
|
445
458
|
bytes,
|
|
446
459
|
filePath: indexPath,
|
|
@@ -452,56 +465,58 @@ var HelpIndexCache = class {
|
|
|
452
465
|
return;
|
|
453
466
|
}
|
|
454
467
|
}
|
|
455
|
-
publish(identity, bytes, integrity, referenceBase, signal) {
|
|
456
|
-
assertNotAborted(signal);
|
|
457
|
-
const existing = this.read(identity);
|
|
458
|
-
if (existing) return existing;
|
|
468
|
+
async publish(identity, bytes, integrity, referenceBase, signal) {
|
|
459
469
|
const directory = this.entryDirectory(identity);
|
|
460
|
-
|
|
461
|
-
mode: PRIVATE_DIRECTORY_MODE,
|
|
462
|
-
recursive: true
|
|
463
|
-
});
|
|
464
|
-
if (node_fs.default.existsSync(directory)) node_fs.default.rmSync(directory, {
|
|
465
|
-
recursive: true,
|
|
466
|
-
force: true
|
|
467
|
-
});
|
|
468
|
-
const temporary = `${directory}.${process.pid}.${(0, node_crypto.randomUUID)()}.tmp`;
|
|
469
|
-
const digest = sha256Hex(bytes);
|
|
470
|
-
const metadata = {
|
|
471
|
-
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
472
|
-
source: identity.source,
|
|
473
|
-
version: identity.version,
|
|
474
|
-
path: HELP_INDEX_PATH$1,
|
|
475
|
-
integrity,
|
|
476
|
-
digest,
|
|
477
|
-
referenceBase
|
|
478
|
-
};
|
|
479
|
-
try {
|
|
480
|
-
node_fs.default.mkdirSync(temporary, { mode: PRIVATE_DIRECTORY_MODE });
|
|
481
|
-
node_fs.default.writeFileSync(node_path.default.join(temporary, HELP_INDEX_PATH$1), bytes, { mode: PRIVATE_FILE_MODE });
|
|
482
|
-
node_fs.default.writeFileSync(node_path.default.join(temporary, CACHE_METADATA_FILE), `${JSON.stringify(metadata, null, 2)}\n`, { mode: PRIVATE_FILE_MODE });
|
|
470
|
+
return mutateCacheEntry(directory, async () => {
|
|
483
471
|
assertNotAborted(signal);
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
472
|
+
const existing = await this.read(identity);
|
|
473
|
+
if (existing) return existing;
|
|
474
|
+
await node_fs_promises.default.mkdir(this.root, {
|
|
475
|
+
mode: PRIVATE_DIRECTORY_MODE,
|
|
476
|
+
recursive: true
|
|
477
|
+
});
|
|
478
|
+
await node_fs_promises.default.rm(directory, {
|
|
479
|
+
recursive: true,
|
|
480
|
+
force: true
|
|
481
|
+
});
|
|
482
|
+
const temporary = `${directory}.${process.pid}.${(0, node_crypto.randomUUID)()}.tmp`;
|
|
483
|
+
const digest = sha256Hex(bytes);
|
|
484
|
+
const metadata = {
|
|
485
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
486
|
+
source: identity.source,
|
|
487
|
+
version: identity.version,
|
|
488
|
+
path: HELP_INDEX_PATH$1,
|
|
495
489
|
integrity,
|
|
496
490
|
digest,
|
|
497
491
|
referenceBase
|
|
498
492
|
};
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
493
|
+
try {
|
|
494
|
+
await node_fs_promises.default.mkdir(temporary, { mode: PRIVATE_DIRECTORY_MODE });
|
|
495
|
+
await node_fs_promises.default.writeFile(node_path.default.join(temporary, HELP_INDEX_PATH$1), bytes, { mode: PRIVATE_FILE_MODE });
|
|
496
|
+
await node_fs_promises.default.writeFile(node_path.default.join(temporary, CACHE_METADATA_FILE), `${JSON.stringify(metadata, null, 2)}\n`, { mode: PRIVATE_FILE_MODE });
|
|
497
|
+
assertNotAborted(signal);
|
|
498
|
+
await node_fs_promises.default.writeFile(node_path.default.join(temporary, COMPLETION_FILE), `${digest}\n`, { mode: PRIVATE_FILE_MODE });
|
|
499
|
+
try {
|
|
500
|
+
await node_fs_promises.default.rename(temporary, directory);
|
|
501
|
+
} catch (error) {
|
|
502
|
+
const winner = await this.read(identity);
|
|
503
|
+
if (winner) return winner;
|
|
504
|
+
throw error;
|
|
505
|
+
}
|
|
506
|
+
return {
|
|
507
|
+
bytes: Uint8Array.from(bytes),
|
|
508
|
+
filePath: node_path.default.join(directory, HELP_INDEX_PATH$1),
|
|
509
|
+
integrity,
|
|
510
|
+
digest,
|
|
511
|
+
referenceBase
|
|
512
|
+
};
|
|
513
|
+
} finally {
|
|
514
|
+
await node_fs_promises.default.rm(temporary, {
|
|
515
|
+
recursive: true,
|
|
516
|
+
force: true
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
});
|
|
505
520
|
}
|
|
506
521
|
};
|
|
507
522
|
var DefaultHelpSkillMaterializer = class {
|
|
@@ -517,27 +532,35 @@ var DefaultHelpSkillMaterializer = class {
|
|
|
517
532
|
const directory = node_path.default.join(this.cacheRoot, WRAPPER_DIRECTORY, key);
|
|
518
533
|
const filePath = node_path.default.join(directory, SKILL_FILE);
|
|
519
534
|
const content = renderHelpSkillWrapper(descriptor, index);
|
|
520
|
-
|
|
521
|
-
|
|
535
|
+
const matches = async () => {
|
|
536
|
+
try {
|
|
537
|
+
const metadata = await node_fs_promises.default.lstat(filePath);
|
|
538
|
+
return metadata.isFile() && !metadata.isSymbolicLink() && await node_fs_promises.default.readFile(filePath, "utf8") === content;
|
|
539
|
+
} catch {
|
|
540
|
+
return false;
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
if (!await matches()) {
|
|
544
|
+
await node_fs_promises.default.mkdir(node_path.default.dirname(directory), {
|
|
522
545
|
mode: PRIVATE_DIRECTORY_MODE,
|
|
523
546
|
recursive: true
|
|
524
547
|
});
|
|
525
|
-
|
|
548
|
+
await node_fs_promises.default.rm(directory, {
|
|
526
549
|
recursive: true,
|
|
527
550
|
force: true
|
|
528
551
|
});
|
|
529
552
|
const temporary = `${directory}.${process.pid}.${(0, node_crypto.randomUUID)()}.tmp`;
|
|
530
553
|
try {
|
|
531
|
-
|
|
532
|
-
|
|
554
|
+
await node_fs_promises.default.mkdir(temporary, { mode: PRIVATE_DIRECTORY_MODE });
|
|
555
|
+
await node_fs_promises.default.writeFile(node_path.default.join(temporary, SKILL_FILE), content, { mode: PRIVATE_FILE_MODE });
|
|
533
556
|
assertNotAborted(signal);
|
|
534
557
|
try {
|
|
535
|
-
|
|
558
|
+
await node_fs_promises.default.rename(temporary, directory);
|
|
536
559
|
} catch (error) {
|
|
537
|
-
if (!
|
|
560
|
+
if (!await matches()) throw error;
|
|
538
561
|
}
|
|
539
562
|
} finally {
|
|
540
|
-
|
|
563
|
+
await node_fs_promises.default.rm(temporary, {
|
|
541
564
|
recursive: true,
|
|
542
565
|
force: true
|
|
543
566
|
});
|
|
@@ -568,12 +591,13 @@ function defaultFetch(input, init) {
|
|
|
568
591
|
function isRecord(value) {
|
|
569
592
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
570
593
|
}
|
|
571
|
-
function isRegularFile(filePath) {
|
|
594
|
+
async function isRegularFile(filePath) {
|
|
572
595
|
try {
|
|
573
|
-
const metadata =
|
|
596
|
+
const metadata = await node_fs_promises.default.lstat(filePath);
|
|
574
597
|
return metadata.isFile() && !metadata.isSymbolicLink();
|
|
575
|
-
} catch {
|
|
576
|
-
return
|
|
598
|
+
} catch (error) {
|
|
599
|
+
if (error.code === "ENOENT") return void 0;
|
|
600
|
+
throw error;
|
|
577
601
|
}
|
|
578
602
|
}
|
|
579
603
|
function unpkgPackagePath(source, version) {
|
|
@@ -654,11 +678,12 @@ var DefaultHelpIndexResolver = class {
|
|
|
654
678
|
}
|
|
655
679
|
async resolve(contribution, signal) {
|
|
656
680
|
if (signal.aborted) throw new Error("Help activation was cancelled.");
|
|
657
|
-
const identity = resolveHelpPackageIdentity(contribution.moduleUrl, contribution.source);
|
|
681
|
+
const identity = await resolveHelpPackageIdentity(contribution.moduleUrl, contribution.source);
|
|
658
682
|
const localPath = node_path.default.join(identity.packageRoot, HELP_INDEX_PATH);
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
683
|
+
const regular = await isRegularFile(localPath);
|
|
684
|
+
if (regular !== void 0) {
|
|
685
|
+
if (!regular) throw new Error(`Bundled ${HELP_INDEX_PATH} must be a regular file.`);
|
|
686
|
+
const bytes = await node_fs_promises.default.readFile(localPath);
|
|
662
687
|
validateLlmsBytes(bytes);
|
|
663
688
|
return {
|
|
664
689
|
identity,
|
|
@@ -669,7 +694,7 @@ var DefaultHelpIndexResolver = class {
|
|
|
669
694
|
digest: sha256Hex(bytes)
|
|
670
695
|
};
|
|
671
696
|
}
|
|
672
|
-
const cached = this.cache.read(identity);
|
|
697
|
+
const cached = await this.cache.read(identity);
|
|
673
698
|
if (cached) try {
|
|
674
699
|
validateLlmsBytes(cached.bytes);
|
|
675
700
|
return {
|
|
@@ -681,7 +706,7 @@ var DefaultHelpIndexResolver = class {
|
|
|
681
706
|
digest: cached.digest
|
|
682
707
|
};
|
|
683
708
|
} catch {
|
|
684
|
-
this.cache.discard(identity);
|
|
709
|
+
await this.cache.discard(identity);
|
|
685
710
|
}
|
|
686
711
|
const timed = timeoutSignal(signal, this.timeoutMs);
|
|
687
712
|
try {
|
|
@@ -700,7 +725,7 @@ var DefaultHelpIndexResolver = class {
|
|
|
700
725
|
const bytes = new Uint8Array(await indexResponse.arrayBuffer());
|
|
701
726
|
validateLlmsBytes(bytes);
|
|
702
727
|
verifySri(bytes, metadata.integrity);
|
|
703
|
-
const published = this.cache.publish(identity, bytes, metadata.integrity, referenceBase, timed.signal);
|
|
728
|
+
const published = await this.cache.publish(identity, bytes, metadata.integrity, referenceBase, timed.signal);
|
|
704
729
|
return {
|
|
705
730
|
identity,
|
|
706
731
|
location: "remote",
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["PO_HELP_MAX_DIAGNOSTIC_LENGTH","PO_HELP_MAX_SKILLS","PO_HELP_MAX_DIAGNOSTICS","HELP_INDEX_PATH","isRecord","path","fs","fileURLToPath","os","poHomeDirectory","createHash","randomUUID","fs","createHash","path"],"sources":["../src/services/llmsContent/index.ts","../src/services/helpActivation/index.ts","../src/services/helpStorage/index.ts","../src/services/llmsResolver/index.ts","../src/services/helpRuntime/index.ts"],"sourcesContent":["import type { PoHelpSkillDescriptor } from '@agimon-ai/po-core/help';\n\nimport type { ResolvedHelpIndex } from '../../types/help';\n\nexport const MAX_LLMS_BYTES = 1024 * 1024;\nexport const MAX_AGGREGATE_LLMS_BYTES = 4 * MAX_LLMS_BYTES;\n\nconst MARKDOWN_LINK_PATTERN = /!?\\[[^\\]]*\\]\\(\\s*<?([^\\s)>]+)>?(?:\\s+[^)]*)?\\)/gu;\nconst MARKDOWN_REFERENCE_LINK_PATTERN = /^\\s{0,3}\\[[^\\]\\r\\n]+\\]:\\s*<?([^\\s>]+)>?/gmu;\nconst MARKDOWN_AUTOLINK_PATTERN = /<((?:\\.{0,2}\\/|[A-Za-z][A-Za-z0-9+.-]*:)[^<>\\s]+)>/gu;\nconst HTML_LINK_PATTERN = /\\b(?:href|src)\\s*=\\s*[\"']([^\"']+)[\"']/giu;\nconst URI_SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:/iu;\nconst NESTED_PATH_ENCODING_PATTERN = /%(?:25|2e|2f|3a|5c)/iu;\nconst SAFE_EXTERNAL_SCHEMES = new Set(['http:', 'https:', 'mailto:']);\n\nfunction externalScheme(target: string): string | undefined {\n if (!URI_SCHEME_PATTERN.test(target)) return undefined;\n return target.slice(0, target.indexOf(':') + 1).toLowerCase();\n}\n\nfunction decodeRelativeTarget(rawTarget: string): string {\n let decoded = rawTarget;\n try {\n for (let pass = 0; pass < 2; pass += 1) {\n const next = decodeURIComponent(decoded);\n if (next === decoded) break;\n decoded = next;\n }\n } catch {\n throw new Error(`llms.txt contains an invalid encoded link '${rawTarget}'.`);\n }\n if (NESTED_PATH_ENCODING_PATTERN.test(decoded)) {\n throw new Error(`llms.txt contains an unsafe nested encoding in link '${rawTarget}'.`);\n }\n return decoded;\n}\n\nfunction validateRelativeLink(rawTarget: string): void {\n if (!rawTarget || rawTarget.startsWith('#')) return;\n const rawScheme = externalScheme(rawTarget);\n if (rawScheme) {\n if (!SAFE_EXTERNAL_SCHEMES.has(rawScheme)) {\n throw new Error(`llms.txt contains unsupported link scheme '${rawScheme}'.`);\n }\n return;\n }\n\n const decoded = decodeRelativeTarget(rawTarget);\n const decodedScheme = externalScheme(decoded);\n if (decodedScheme) {\n if (!SAFE_EXTERNAL_SCHEMES.has(decodedScheme)) {\n throw new Error(`llms.txt contains unsupported link scheme '${decodedScheme}'.`);\n }\n return;\n }\n const withoutSuffix = decoded.split(/[?#]/u, 1)[0]?.replaceAll('\\\\', '/') ?? '';\n if (withoutSuffix.startsWith('/') || withoutSuffix.split('/').some((segment) => segment === '..')) {\n throw new Error(`llms.txt link '${rawTarget}' escapes the package root.`);\n }\n}\n\nfunction containsUnsafeControl(text: string): boolean {\n for (const character of text) {\n const code = character.codePointAt(0) ?? 0;\n if ((code >= 0 && code <= 8) || code === 11 || code === 12 || (code >= 14 && code <= 31) || code === 127) {\n return true;\n }\n }\n return false;\n}\n\nexport function validateLlmsBytes(bytes: Uint8Array): string {\n if (bytes.byteLength === 0) throw new Error('llms.txt is empty.');\n if (bytes.byteLength > MAX_LLMS_BYTES) throw new Error(`llms.txt exceeds ${MAX_LLMS_BYTES} bytes.`);\n\n let text: string;\n try {\n text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch {\n throw new Error('llms.txt is not valid UTF-8.');\n }\n if (text.startsWith('\\uFEFF')) text = text.slice(1);\n if (containsUnsafeControl(text)) throw new Error('llms.txt contains unsafe control bytes.');\n\n const firstContentLine = text\n .split(/\\r?\\n/u)\n .find((line) => line.trim().length > 0)\n ?.trim();\n if (!firstContentLine || !/^#\\s+\\S/u.test(firstContentLine)) {\n throw new Error('llms.txt must begin with a Markdown H1 heading.');\n }\n for (const pattern of [\n MARKDOWN_LINK_PATTERN,\n MARKDOWN_REFERENCE_LINK_PATTERN,\n MARKDOWN_AUTOLINK_PATTERN,\n HTML_LINK_PATTERN,\n ]) {\n for (const match of text.matchAll(pattern)) validateRelativeLink(match[1] ?? '');\n }\n return text;\n}\n\nexport function renderHelpSkillWrapper(descriptor: PoHelpSkillDescriptor, index: ResolvedHelpIndex): string {\n const name = JSON.stringify(descriptor.name);\n const description = JSON.stringify(descriptor.description);\n const indexPath = JSON.stringify(index.filePath);\n const referenceBase = JSON.stringify(index.referenceBase);\n return `---\\nname: ${name}\\ndescription: ${description}\\n---\\n\\n# Package Help\\n\\nRead the validated package Help index at ${indexPath}.\\nResolve relative links in that index against ${referenceBase}.\\nOpen only the linked documents relevant to the current request, as needed; do not recursively load the whole reference set.\\n`;\n}\n","import {\n PO_HELP_MAX_DIAGNOSTIC_LENGTH,\n PO_HELP_MAX_DIAGNOSTICS,\n PO_HELP_MAX_SKILLS,\n type PoHelpContribution,\n type PoHelpDiagnostic,\n type PoHelpSkill,\n} from '@agimon-ai/po-core/help';\n\nimport type {\n HelpActivationDependencies,\n HelpActivationService,\n HelpRuntimeState,\n ResolvedHelpIndex,\n} from '../../types/help';\nimport { MAX_AGGREGATE_LLMS_BYTES } from '../llmsContent';\n\nconst MAX_RESOLUTION_CONCURRENCY = 4;\nconst FAILURE_MESSAGE = 'No package Help source could be activated.';\nconst CANCELLATION_MESSAGE = 'Help activation was cancelled.';\n\ninterface LoadedSource {\n contribution: PoHelpContribution;\n index: ResolvedHelpIndex;\n skills: readonly PoHelpSkill[];\n}\n\ninterface SourceOutcome {\n source: string;\n loaded?: LoadedSource;\n error?: unknown;\n}\n\nexport class HelpActivationError extends Error {\n constructor(message = FAILURE_MESSAGE) {\n super(message);\n this.name = 'HelpActivationError';\n }\n}\n\nfunction cloneContribution(contribution: PoHelpContribution): PoHelpContribution {\n return {\n source: contribution.source,\n moduleUrl: contribution.moduleUrl,\n skills: contribution.skills.map((skill) => ({ ...skill })),\n };\n}\n\nfunction cloneState(state: HelpRuntimeState): HelpRuntimeState {\n return {\n activation: state.activation,\n skills: state.skills.map((skill) => ({ ...skill })),\n diagnostics: state.diagnostics.map((diagnostic) => ({ ...diagnostic })),\n };\n}\n\nfunction diagnostic(source: string, code: string, error: unknown): PoHelpDiagnostic {\n const raw = error instanceof Error ? error.message : String(error);\n const message = (raw || 'Unknown Help activation failure.').slice(0, PO_HELP_MAX_DIAGNOSTIC_LENGTH);\n return { source, code, message };\n}\n\nfunction contributionFingerprint(contributions: readonly PoHelpContribution[]): string {\n return JSON.stringify(\n contributions.map((contribution) => ({\n source: contribution.source,\n moduleUrl: contribution.moduleUrl,\n skills: contribution.skills,\n })),\n );\n}\n\nexport class DefaultHelpActivationService implements HelpActivationService {\n private readonly dependencies: HelpActivationDependencies;\n private readonly listeners = new Set<(state: HelpRuntimeState) => void>();\n private contributions: PoHelpContribution[] = [];\n private fingerprint = '[]';\n private state: HelpRuntimeState = { activation: 'inactive', skills: [], diagnostics: [] };\n private settledState: HelpRuntimeState = { activation: 'inactive', skills: [], diagnostics: [] };\n private generation = 0;\n private controller: AbortController | undefined;\n private disposed = false;\n\n constructor(dependencies: HelpActivationDependencies) {\n this.dependencies = dependencies;\n }\n\n getState(): HelpRuntimeState {\n return cloneState(this.state);\n }\n\n replaceContributions(contributions: readonly PoHelpContribution[]): void {\n if (this.disposed) return;\n const next = contributions.map(cloneContribution).sort((left, right) => left.source.localeCompare(right.source));\n const fingerprint = contributionFingerprint(next);\n if (fingerprint === this.fingerprint) return;\n const previous = new Map(this.contributions.map((entry) => [entry.source, contributionFingerprint([entry])]));\n const retained = new Set(\n next\n .filter((entry) => previous.get(entry.source) === contributionFingerprint([entry]))\n .map((entry) => entry.source),\n );\n // A refresh may retain unchanged owners, never withdrawn or replaced ones.\n // Prune the rollback snapshot too, so cancellation cannot resurrect them.\n const skills = this.settledState.skills.filter((entry) => retained.has(entry.source));\n const diagnostics = this.settledState.diagnostics.filter((entry) => !entry.source || retained.has(entry.source));\n this.settledState = {\n activation: skills.length === 0 ? 'inactive' : diagnostics.length > 0 ? 'degraded' : 'active',\n skills,\n diagnostics,\n };\n this.contributions = next;\n this.fingerprint = fingerprint;\n if (this.state.activation !== 'inactive') {\n void this.activate().catch((error: unknown) => {\n // Activation failures publish a bounded settled state before rejecting.\n // Only unexpected implementation failures need an out-of-band report.\n if (error instanceof HelpActivationError) return;\n this.dependencies.onBackgroundError(error);\n });\n }\n }\n\n subscribe(listener: (state: HelpRuntimeState) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n private publish(state: HelpRuntimeState): HelpRuntimeState {\n this.state = cloneState(state);\n if (state.activation !== 'activating') this.settledState = cloneState(state);\n this.dependencies.publisher.publish(this.state);\n for (const listener of this.listeners) listener(cloneState(this.state));\n return this.getState();\n }\n\n private async loadSources(signal: AbortSignal): Promise<SourceOutcome[]> {\n const contributions = this.contributions;\n const outcomes: SourceOutcome[] = Array.from({ length: contributions.length });\n let cursor = 0;\n const worker = async (): Promise<void> => {\n while (cursor < contributions.length) {\n const index = cursor;\n cursor += 1;\n const contribution = contributions[index];\n if (!contribution) return;\n if (signal.aborted) throw new HelpActivationError(CANCELLATION_MESSAGE);\n try {\n const resolved = await this.dependencies.resolver.resolve(contribution, signal);\n if (signal.aborted) throw new HelpActivationError(CANCELLATION_MESSAGE);\n const skills = await this.dependencies.materializer.materialize(contribution, resolved, signal);\n outcomes[index] = { source: contribution.source, loaded: { contribution, index: resolved, skills } };\n } catch (error) {\n if (signal.aborted) throw new HelpActivationError(CANCELLATION_MESSAGE);\n outcomes[index] = { source: contribution.source, error };\n }\n }\n };\n const count = Math.min(MAX_RESOLUTION_CONCURRENCY, contributions.length);\n await Promise.all(Array.from({ length: count }, () => worker()));\n return outcomes;\n }\n\n async activate(externalSignal?: AbortSignal): Promise<HelpRuntimeState> {\n if (this.disposed) throw new HelpActivationError('Help runtime is disposed.');\n this.controller?.abort('Help activation generation replaced.');\n const controller = new AbortController();\n this.controller = controller;\n const generation = ++this.generation;\n const abortFromExternal = () => controller.abort(externalSignal?.reason);\n externalSignal?.addEventListener('abort', abortFromExternal, { once: true });\n if (externalSignal?.aborted) abortFromExternal();\n\n const settledState = cloneState(this.settledState);\n this.publish({ activation: 'activating', skills: settledState.skills, diagnostics: settledState.diagnostics });\n try {\n const outcomes = await this.loadSources(controller.signal);\n if (controller.signal.aborted || generation !== this.generation) {\n throw new HelpActivationError(CANCELLATION_MESSAGE);\n }\n\n const diagnostics: PoHelpDiagnostic[] = [];\n const loaded: LoadedSource[] = [];\n let aggregateBytes = 0;\n for (const outcome of outcomes) {\n if (!outcome) continue;\n if (outcome.error || !outcome.loaded) {\n diagnostics.push(diagnostic(outcome.source, 'HELP_SOURCE_FAILED', outcome.error));\n continue;\n }\n if (aggregateBytes + outcome.loaded.index.byteLength > MAX_AGGREGATE_LLMS_BYTES) {\n diagnostics.push(\n diagnostic(outcome.source, 'HELP_AGGREGATE_LIMIT', 'The aggregate llms.txt byte limit was exceeded.'),\n );\n continue;\n }\n aggregateBytes += outcome.loaded.index.byteLength;\n loaded.push(outcome.loaded);\n }\n\n const skills: PoHelpSkill[] = [];\n const names = new Set<string>();\n for (const source of loaded) {\n for (const skill of source.skills) {\n if (skills.length >= PO_HELP_MAX_SKILLS) {\n diagnostics.push(\n diagnostic(source.contribution.source, 'HELP_SKILL_LIMIT', 'The Help skill limit was reached.'),\n );\n break;\n }\n if (names.has(skill.name)) {\n diagnostics.push(\n diagnostic(\n source.contribution.source,\n 'HELP_SKILL_COLLISION',\n `Help skill '${skill.name}' was already provided by an earlier package source.`,\n ),\n );\n continue;\n }\n names.add(skill.name);\n skills.push({ ...skill });\n }\n }\n\n const boundedDiagnostics = diagnostics.slice(0, PO_HELP_MAX_DIAGNOSTICS);\n if (skills.length === 0) {\n this.publish({ activation: 'inactive', skills: [], diagnostics: boundedDiagnostics });\n throw new HelpActivationError();\n }\n return this.publish({\n activation: boundedDiagnostics.length > 0 ? 'degraded' : 'active',\n skills,\n diagnostics: boundedDiagnostics,\n });\n } catch (error) {\n if (generation === this.generation && this.state.activation === 'activating') this.publish(settledState);\n throw error;\n } finally {\n externalSignal?.removeEventListener('abort', abortFromExternal);\n if (this.controller === controller) this.controller = undefined;\n }\n }\n\n deactivate(): HelpRuntimeState {\n this.generation += 1;\n this.controller?.abort('Help deactivated.');\n this.controller = undefined;\n return this.publish({ activation: 'inactive', skills: [], diagnostics: [] });\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.deactivate();\n this.disposed = true;\n this.listeners.clear();\n }\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { PoHelpContribution, PoHelpSkill } from '@agimon-ai/po-core/help';\nimport { poHomeDirectory } from '@agimon-ai/po-core/piSettings';\n\nimport type { HelpPackageIdentity, HelpSkillMaterializer, ResolvedHelpIndex } from '../../types/help';\nimport { renderHelpSkillWrapper } from '../llmsContent';\n\nconst PACKAGE_MANIFEST = 'package.json';\nconst HELP_INDEX_PATH = 'llms.txt';\nconst CACHE_SCHEMA_VERSION = 1;\nconst PRIVATE_FILE_MODE = 0o600;\nconst PRIVATE_DIRECTORY_MODE = 0o700;\nconst COMPLETION_FILE = '.complete';\nconst CACHE_METADATA_FILE = 'metadata.json';\nconst WRAPPER_DIRECTORY = 'wrappers';\nconst SKILL_FILE = 'SKILL.md';\nconst EXACT_SEMVER_PATTERN =\n /^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/u;\nconst NPM_PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._~-]*\\/)?[a-z0-9][a-z0-9._~-]*$/u;\n\ninterface CacheMetadata {\n schemaVersion: typeof CACHE_SCHEMA_VERSION;\n source: string;\n version: string;\n path: typeof HELP_INDEX_PATH;\n integrity: string;\n digest: string;\n referenceBase: string;\n}\n\nexport interface CachedHelpIndex {\n bytes: Uint8Array;\n filePath: string;\n integrity: string;\n digest: string;\n referenceBase: string;\n}\n\nfunction assertNotAborted(signal: AbortSignal): void {\n if (signal.aborted) throw new Error('Help activation was cancelled.');\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isContained(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));\n}\n\nfunction readManifest(filePath: string): Record<string, unknown> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')) as unknown;\n } catch (error) {\n throw new Error(\n `Cannot read Help package manifest at ${filePath}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (!isRecord(parsed)) throw new Error(`Help package manifest at ${filePath} must contain an object.`);\n return parsed;\n}\n\nexport function resolveHelpPackageIdentity(moduleUrl: string, expectedSource: string): HelpPackageIdentity {\n if (!NPM_PACKAGE_NAME_PATTERN.test(expectedSource)) {\n throw new Error(`Help source '${expectedSource}' must be a valid lowercase npm package name.`);\n }\n let modulePath: string;\n try {\n const url = new URL(moduleUrl);\n if (url.protocol !== 'file:') throw new Error(`Help module URL must use file:, received ${url.protocol}`);\n modulePath = fs.realpathSync(fileURLToPath(url));\n } catch (error) {\n throw new Error(\n `Invalid Help contributor module URL '${moduleUrl}': ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (!fs.lstatSync(modulePath).isFile())\n throw new Error(`Help contributor module is not a regular file: ${modulePath}`);\n\n let directory = path.dirname(modulePath);\n while (true) {\n const manifestPath = path.join(directory, PACKAGE_MANIFEST);\n if (fs.existsSync(manifestPath)) {\n const manifest = readManifest(manifestPath);\n const source = manifest.name;\n const version = manifest.version;\n if (source !== expectedSource) {\n throw new Error(`Help source '${expectedSource}' does not match nearest package '${String(source)}'.`);\n }\n if (typeof version !== 'string' || !EXACT_SEMVER_PATTERN.test(version)) {\n throw new Error(`Help package '${expectedSource}' must declare an exact semantic version.`);\n }\n const packageRoot = fs.realpathSync(directory);\n if (!isContained(packageRoot, modulePath))\n throw new Error('Help contributor module escapes its resolved package root.');\n return { source: expectedSource, version, packageRoot, modulePath };\n }\n const parent = path.dirname(directory);\n if (parent === directory) break;\n directory = parent;\n }\n throw new Error(`Cannot find a package manifest for Help contributor ${modulePath}.`);\n}\n\nexport function defaultHelpCacheRoot(homeDirectory = os.homedir()): string {\n return path.join(poHomeDirectory(homeDirectory), 'llms-cache');\n}\n\nexport function sha256Hex(bytes: Uint8Array | string): string {\n return createHash('sha256').update(bytes).digest('hex');\n}\n\nfunction parseCacheMetadata(value: unknown, identity: HelpPackageIdentity): CacheMetadata | undefined {\n if (!isRecord(value)) return undefined;\n if (\n value.schemaVersion !== CACHE_SCHEMA_VERSION ||\n value.source !== identity.source ||\n value.version !== identity.version ||\n value.path !== HELP_INDEX_PATH ||\n typeof value.integrity !== 'string' ||\n typeof value.digest !== 'string' ||\n typeof value.referenceBase !== 'string'\n ) {\n return undefined;\n }\n return value as unknown as CacheMetadata;\n}\n\nfunction regularFile(filePath: string): boolean {\n try {\n const metadata = fs.lstatSync(filePath);\n return metadata.isFile() && !metadata.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nexport class HelpIndexCache {\n readonly root: string;\n\n constructor(root = defaultHelpCacheRoot()) {\n this.root = root;\n }\n\n entryDirectory(identity: HelpPackageIdentity): string {\n const key = sha256Hex(`${identity.source}\\0${identity.version}\\0${HELP_INDEX_PATH}`);\n return path.join(this.root, key);\n }\n\n discard(identity: HelpPackageIdentity): void {\n fs.rmSync(this.entryDirectory(identity), { recursive: true, force: true });\n }\n\n read(identity: HelpPackageIdentity): CachedHelpIndex | undefined {\n const directory = this.entryDirectory(identity);\n const completionPath = path.join(directory, COMPLETION_FILE);\n const indexPath = path.join(directory, HELP_INDEX_PATH);\n const metadataPath = path.join(directory, CACHE_METADATA_FILE);\n if (!regularFile(completionPath) || !regularFile(indexPath) || !regularFile(metadataPath)) return undefined;\n try {\n const metadata = parseCacheMetadata(JSON.parse(fs.readFileSync(metadataPath, 'utf8')) as unknown, identity);\n if (!metadata) return undefined;\n const bytes = fs.readFileSync(indexPath);\n if (sha256Hex(bytes) !== metadata.digest) return undefined;\n if (fs.readFileSync(completionPath, 'utf8').trim() !== metadata.digest) return undefined;\n return {\n bytes,\n filePath: indexPath,\n integrity: metadata.integrity,\n digest: metadata.digest,\n referenceBase: metadata.referenceBase,\n };\n } catch {\n return undefined;\n }\n }\n\n publish(\n identity: HelpPackageIdentity,\n bytes: Uint8Array,\n integrity: string,\n referenceBase: string,\n signal: AbortSignal,\n ): CachedHelpIndex {\n assertNotAborted(signal);\n const existing = this.read(identity);\n if (existing) return existing;\n const directory = this.entryDirectory(identity);\n fs.mkdirSync(this.root, { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n if (fs.existsSync(directory)) fs.rmSync(directory, { recursive: true, force: true });\n const temporary = `${directory}.${process.pid}.${randomUUID()}.tmp`;\n const digest = sha256Hex(bytes);\n const metadata: CacheMetadata = {\n schemaVersion: CACHE_SCHEMA_VERSION,\n source: identity.source,\n version: identity.version,\n path: HELP_INDEX_PATH,\n integrity,\n digest,\n referenceBase,\n };\n try {\n fs.mkdirSync(temporary, { mode: PRIVATE_DIRECTORY_MODE });\n fs.writeFileSync(path.join(temporary, HELP_INDEX_PATH), bytes, { mode: PRIVATE_FILE_MODE });\n fs.writeFileSync(path.join(temporary, CACHE_METADATA_FILE), `${JSON.stringify(metadata, null, 2)}\\n`, {\n mode: PRIVATE_FILE_MODE,\n });\n assertNotAborted(signal);\n fs.writeFileSync(path.join(temporary, COMPLETION_FILE), `${digest}\\n`, { mode: PRIVATE_FILE_MODE });\n try {\n fs.renameSync(temporary, directory);\n } catch (error) {\n const winner = this.read(identity);\n if (winner) return winner;\n throw error;\n }\n return {\n bytes: Uint8Array.from(bytes),\n filePath: path.join(directory, HELP_INDEX_PATH),\n integrity,\n digest,\n referenceBase,\n };\n } finally {\n fs.rmSync(temporary, { recursive: true, force: true });\n }\n }\n}\n\nexport class DefaultHelpSkillMaterializer implements HelpSkillMaterializer {\n constructor(private readonly cacheRoot = defaultHelpCacheRoot()) {}\n\n async materialize(\n contribution: PoHelpContribution,\n index: ResolvedHelpIndex,\n signal: AbortSignal,\n ): Promise<readonly PoHelpSkill[]> {\n const skills: PoHelpSkill[] = [];\n for (const descriptor of contribution.skills) {\n assertNotAborted(signal);\n const key = sha256Hex(\n `${index.identity.source}\\0${index.identity.version}\\0${descriptor.name}\\0${descriptor.description}\\0${index.digest}`,\n );\n const directory = path.join(this.cacheRoot, WRAPPER_DIRECTORY, key);\n const filePath = path.join(directory, SKILL_FILE);\n const content = renderHelpSkillWrapper(descriptor, index);\n if (!regularFile(filePath) || fs.readFileSync(filePath, 'utf8') !== content) {\n fs.mkdirSync(path.dirname(directory), { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n if (fs.existsSync(directory)) fs.rmSync(directory, { recursive: true, force: true });\n const temporary = `${directory}.${process.pid}.${randomUUID()}.tmp`;\n try {\n fs.mkdirSync(temporary, { mode: PRIVATE_DIRECTORY_MODE });\n fs.writeFileSync(path.join(temporary, SKILL_FILE), content, { mode: PRIVATE_FILE_MODE });\n assertNotAborted(signal);\n try {\n fs.renameSync(temporary, directory);\n } catch (error) {\n if (!regularFile(filePath) || fs.readFileSync(filePath, 'utf8') !== content) throw error;\n }\n } finally {\n fs.rmSync(temporary, { recursive: true, force: true });\n }\n }\n skills.push({\n source: contribution.source,\n name: descriptor.name,\n description: descriptor.description,\n filePath,\n baseDir: directory,\n });\n }\n return skills;\n }\n}\n","import { createHash } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { PoHelpContribution } from '@agimon-ai/po-core/help';\n\nimport type { HelpFetch, HelpFetchResponse, HelpIndexResolver, ResolvedHelpIndex } from '../../types/help';\nimport { HelpIndexCache, resolveHelpPackageIdentity, sha256Hex } from '../helpStorage';\nimport { MAX_LLMS_BYTES, validateLlmsBytes } from '../llmsContent';\n\nconst HELP_INDEX_PATH = 'llms.txt';\nconst UNPKG_ORIGIN = 'https://unpkg.com';\nconst DEFAULT_FETCH_TIMEOUT_MS = 5_000;\nconst MAX_METADATA_BYTES = 512 * 1024;\nconst MAX_REDIRECTS = 3;\nconst SRI_PATTERN = /^sha256-([A-Za-z0-9+/]+={0,2})$/u;\n\ninterface UnpkgMetadataFile {\n path: string;\n size?: number;\n integrity: string;\n}\n\nexport interface DefaultHelpIndexResolverOptions {\n cache?: HelpIndexCache;\n fetch?: HelpFetch;\n timeoutMs?: number;\n}\n\nfunction defaultFetch(input: string, init: { signal: AbortSignal; redirect: 'manual' }): Promise<HelpFetchResponse> {\n return fetch(input, init) as unknown as Promise<HelpFetchResponse>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isRegularFile(filePath: string): boolean {\n try {\n const metadata = fs.lstatSync(filePath);\n return metadata.isFile() && !metadata.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nfunction unpkgPackagePath(source: string, version: string): string {\n const encoded = source\n .split('/')\n .map((segment) =>\n segment.startsWith('@') ? `@${encodeURIComponent(segment.slice(1))}` : encodeURIComponent(segment),\n )\n .join('/');\n return `${encoded}@${encodeURIComponent(version)}`;\n}\n\nfunction exactUnpkgBase(source: string, version: string): string {\n return `${UNPKG_ORIGIN}/${unpkgPackagePath(source, version)}/`;\n}\n\nfunction contentLength(response: HelpFetchResponse): number | undefined {\n const raw = response.headers.get('content-length');\n if (!raw) return undefined;\n const parsed = Number.parseInt(raw, 10);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\nfunction timeoutSignal(parent: AbortSignal, timeoutMs: number): { signal: AbortSignal; dispose(): void } {\n const controller = new AbortController();\n const abort = () => controller.abort(parent.reason);\n parent.addEventListener('abort', abort, { once: true });\n const timer = setTimeout(() => controller.abort(new Error('Help download timed out.')), timeoutMs);\n if (parent.aborted) abort();\n return {\n signal: controller.signal,\n dispose() {\n clearTimeout(timer);\n parent.removeEventListener('abort', abort);\n },\n };\n}\n\nasync function fetchExact(fetcher: HelpFetch, initialUrl: string, signal: AbortSignal): Promise<HelpFetchResponse> {\n let url = initialUrl;\n const expected = new URL(initialUrl);\n for (let redirect = 0; redirect <= MAX_REDIRECTS; redirect += 1) {\n const response = await fetcher(url, { signal, redirect: 'manual' });\n if (response.status < 300 || response.status >= 400) return response;\n const location = response.headers.get('location');\n if (!location) throw new Error(`Unpkg redirected ${url} without a location.`);\n const next = new URL(location, url);\n if (next.origin !== UNPKG_ORIGIN || next.pathname !== expected.pathname || next.search !== expected.search) {\n throw new Error(`Unpkg redirect escaped the exact package/version path: ${next.href}`);\n }\n url = next.href;\n }\n throw new Error(`Unpkg exceeded ${MAX_REDIRECTS} redirects.`);\n}\n\nfunction parseMetadata(text: string): UnpkgMetadataFile {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text) as unknown;\n } catch {\n throw new Error('Unpkg metadata is not valid JSON.');\n }\n if (!isRecord(parsed) || !Array.isArray(parsed.files)) throw new Error('Unpkg metadata has no files list.');\n const match = parsed.files.find((entry) => isRecord(entry) && entry.path === `/${HELP_INDEX_PATH}`);\n if (!isRecord(match) || typeof match.integrity !== 'string') {\n throw new Error(`Unpkg package does not publish /${HELP_INDEX_PATH}.`);\n }\n const size = typeof match.size === 'number' ? match.size : undefined;\n if (size !== undefined && (!Number.isSafeInteger(size) || size < 0 || size > MAX_LLMS_BYTES)) {\n throw new Error(`Unpkg /${HELP_INDEX_PATH} exceeds the Help size limit.`);\n }\n if (!SRI_PATTERN.test(match.integrity)) throw new Error('Unpkg llms.txt metadata does not contain SHA-256 SRI.');\n return { path: match.path as string, ...(size === undefined ? {} : { size }), integrity: match.integrity };\n}\n\nfunction verifySri(bytes: Uint8Array, integrity: string): void {\n const expected = SRI_PATTERN.exec(integrity)?.[1];\n if (!expected) throw new Error('Invalid llms.txt SRI metadata.');\n const actual = createHash('sha256').update(bytes).digest('base64');\n if (actual !== expected) throw new Error('Downloaded llms.txt failed SRI verification.');\n}\n\nexport class DefaultHelpIndexResolver implements HelpIndexResolver {\n private readonly cache: HelpIndexCache;\n private readonly fetcher: HelpFetch;\n private readonly timeoutMs: number;\n\n constructor(options: DefaultHelpIndexResolverOptions = {}) {\n this.cache = options.cache ?? new HelpIndexCache();\n this.fetcher = options.fetch ?? defaultFetch;\n this.timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;\n }\n\n async resolve(contribution: PoHelpContribution, signal: AbortSignal): Promise<ResolvedHelpIndex> {\n if (signal.aborted) throw new Error('Help activation was cancelled.');\n const identity = resolveHelpPackageIdentity(contribution.moduleUrl, contribution.source);\n const localPath = path.join(identity.packageRoot, HELP_INDEX_PATH);\n if (fs.existsSync(localPath)) {\n if (!isRegularFile(localPath)) throw new Error(`Bundled ${HELP_INDEX_PATH} must be a regular file.`);\n const bytes = fs.readFileSync(localPath);\n validateLlmsBytes(bytes);\n return {\n identity,\n location: 'local',\n filePath: localPath,\n referenceBase: identity.packageRoot,\n byteLength: bytes.byteLength,\n digest: sha256Hex(bytes),\n };\n }\n\n const cached = this.cache.read(identity);\n if (cached) {\n try {\n validateLlmsBytes(cached.bytes);\n return {\n identity,\n location: 'cache',\n filePath: cached.filePath,\n referenceBase: cached.referenceBase,\n byteLength: cached.bytes.byteLength,\n digest: cached.digest,\n };\n } catch {\n this.cache.discard(identity);\n }\n }\n\n const timed = timeoutSignal(signal, this.timeoutMs);\n try {\n const referenceBase = exactUnpkgBase(identity.source, identity.version);\n const metadataResponse = await fetchExact(this.fetcher, `${referenceBase}?meta`, timed.signal);\n const metadataLength = contentLength(metadataResponse);\n if (metadataLength !== undefined && metadataLength > MAX_METADATA_BYTES) {\n throw new Error('Unpkg metadata exceeds the Help metadata size limit.');\n }\n if (!metadataResponse.ok) throw new Error(`Unpkg metadata request failed with HTTP ${metadataResponse.status}.`);\n const metadataText = await metadataResponse.text();\n if (Buffer.byteLength(metadataText, 'utf8') > MAX_METADATA_BYTES) {\n throw new Error('Unpkg metadata exceeds the Help metadata size limit.');\n }\n const metadata = parseMetadata(metadataText);\n const indexResponse = await fetchExact(this.fetcher, `${referenceBase}${HELP_INDEX_PATH}`, timed.signal);\n const indexLength = contentLength(indexResponse);\n if (indexLength !== undefined && indexLength > MAX_LLMS_BYTES) {\n throw new Error(`Downloaded ${HELP_INDEX_PATH} exceeds ${MAX_LLMS_BYTES} bytes.`);\n }\n if (!indexResponse.ok) throw new Error(`Unpkg llms.txt request failed with HTTP ${indexResponse.status}.`);\n const bytes = new Uint8Array(await indexResponse.arrayBuffer());\n validateLlmsBytes(bytes);\n verifySri(bytes, metadata.integrity);\n const published = this.cache.publish(identity, bytes, metadata.integrity, referenceBase, timed.signal);\n return {\n identity,\n location: 'remote',\n filePath: published.filePath,\n referenceBase: published.referenceBase,\n byteLength: published.bytes.byteLength,\n digest: published.digest,\n };\n } finally {\n timed.dispose();\n }\n }\n}\n","import type { PoHelpContribution, PoHelpService } from '@agimon-ai/po-core/help';\n\nimport type { HelpFetch } from '../../types/help';\nimport { DefaultHelpActivationService } from '../helpActivation';\nimport { DefaultHelpSkillMaterializer, defaultHelpCacheRoot, HelpIndexCache } from '../helpStorage';\nimport { DefaultHelpIndexResolver } from '../llmsResolver';\n\nexport interface HelpRuntimeOptions {\n cacheRoot?: string;\n fetch?: HelpFetch;\n timeoutMs?: number;\n onBackgroundError?(error: unknown): void;\n}\n\nexport interface HelpRuntimeComposition {\n activation: DefaultHelpActivationService;\n dispose(): void;\n}\n\nfunction reportAsync(error: unknown): void {\n queueMicrotask(() => {\n throw error instanceof Error ? error : new Error(String(error));\n });\n}\n\nexport function createHelpRuntime(service: PoHelpService, options: HelpRuntimeOptions = {}): HelpRuntimeComposition {\n const cacheRoot = options.cacheRoot ?? defaultHelpCacheRoot();\n const cache = new HelpIndexCache(cacheRoot);\n const activation = new DefaultHelpActivationService({\n resolver: new DefaultHelpIndexResolver({ cache, fetch: options.fetch, timeoutMs: options.timeoutMs }),\n materializer: new DefaultHelpSkillMaterializer(cacheRoot),\n publisher: { publish: (snapshot) => service.publish(snapshot) },\n onBackgroundError(error) {\n if (options.onBackgroundError) options.onBackgroundError(error);\n else reportAsync(error);\n },\n });\n const synchronize = (contributions: readonly PoHelpContribution[]): void => {\n activation.replaceContributions(contributions);\n };\n const unsubscribe = service.subscribeContributions((contributions) => synchronize(contributions));\n synchronize(service.listContributions());\n let disposed = false;\n return {\n activation,\n dispose() {\n if (disposed) return;\n disposed = true;\n unsubscribe();\n activation.dispose();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,MAAa,iBAAiB;AAG9B,MAAM,wBAAwB;AAC9B,MAAM,kCAAkC;AACxC,MAAM,4BAA4B;AAClC,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;AAC3B,MAAM,+BAA+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IC_LENGTH","PO_HELP_MAX_SKILLS","PO_HELP_MAX_DIAGNOSTICS","HELP_INDEX_PATH","isRecord","path","fsPromises","fileURLToPath","os","poHomeDirectory","createHash","randomUUID","fs","createHash","path"],"sources":["../src/services/llmsContent/index.ts","../src/services/helpActivation/index.ts","../src/services/helpStorage/index.ts","../src/services/llmsResolver/index.ts","../src/services/helpRuntime/index.ts"],"sourcesContent":["import type { PoHelpSkillDescriptor } from '@agimon-ai/po-core/help';\n\nimport type { ResolvedHelpIndex } from '../../types/help';\n\nexport const MAX_LLMS_BYTES = 1024 * 1024;\nexport const MAX_AGGREGATE_LLMS_BYTES = 4 * MAX_LLMS_BYTES;\n\nconst MARKDOWN_LINK_PATTERN = /!?\\[[^\\]]*\\]\\(\\s*<?([^\\s)>]+)>?(?:\\s+[^)]*)?\\)/gu;\nconst MARKDOWN_REFERENCE_LINK_PATTERN = /^\\s{0,3}\\[[^\\]\\r\\n]+\\]:\\s*<?([^\\s>]+)>?/gmu;\nconst MARKDOWN_AUTOLINK_PATTERN = /<((?:\\.{0,2}\\/|[A-Za-z][A-Za-z0-9+.-]*:)[^<>\\s]+)>/gu;\nconst HTML_LINK_PATTERN = /\\b(?:href|src)\\s*=\\s*[\"']([^\"']+)[\"']/giu;\nconst URI_SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:/iu;\nconst NESTED_PATH_ENCODING_PATTERN = /%(?:25|2e|2f|3a|5c)/iu;\nconst SAFE_EXTERNAL_SCHEMES = new Set(['http:', 'https:', 'mailto:']);\n\nfunction externalScheme(target: string): string | undefined {\n if (!URI_SCHEME_PATTERN.test(target)) return undefined;\n return target.slice(0, target.indexOf(':') + 1).toLowerCase();\n}\n\nfunction decodeRelativeTarget(rawTarget: string): string {\n let decoded = rawTarget;\n try {\n for (let pass = 0; pass < 2; pass += 1) {\n const next = decodeURIComponent(decoded);\n if (next === decoded) break;\n decoded = next;\n }\n } catch {\n throw new Error(`llms.txt contains an invalid encoded link '${rawTarget}'.`);\n }\n if (NESTED_PATH_ENCODING_PATTERN.test(decoded)) {\n throw new Error(`llms.txt contains an unsafe nested encoding in link '${rawTarget}'.`);\n }\n return decoded;\n}\n\nfunction validateRelativeLink(rawTarget: string): void {\n if (!rawTarget || rawTarget.startsWith('#')) return;\n const rawScheme = externalScheme(rawTarget);\n if (rawScheme) {\n if (!SAFE_EXTERNAL_SCHEMES.has(rawScheme)) {\n throw new Error(`llms.txt contains unsupported link scheme '${rawScheme}'.`);\n }\n return;\n }\n\n const decoded = decodeRelativeTarget(rawTarget);\n const decodedScheme = externalScheme(decoded);\n if (decodedScheme) {\n if (!SAFE_EXTERNAL_SCHEMES.has(decodedScheme)) {\n throw new Error(`llms.txt contains unsupported link scheme '${decodedScheme}'.`);\n }\n return;\n }\n const withoutSuffix = decoded.split(/[?#]/u, 1)[0]?.replaceAll('\\\\', '/') ?? '';\n if (withoutSuffix.startsWith('/') || withoutSuffix.split('/').some((segment) => segment === '..')) {\n throw new Error(`llms.txt link '${rawTarget}' escapes the package root.`);\n }\n}\n\nfunction containsUnsafeControl(text: string): boolean {\n for (const character of text) {\n const code = character.codePointAt(0) ?? 0;\n if ((code >= 0 && code <= 8) || code === 11 || code === 12 || (code >= 14 && code <= 31) || code === 127) {\n return true;\n }\n }\n return false;\n}\n\nexport function validateLlmsBytes(bytes: Uint8Array): string {\n if (bytes.byteLength === 0) throw new Error('llms.txt is empty.');\n if (bytes.byteLength > MAX_LLMS_BYTES) throw new Error(`llms.txt exceeds ${MAX_LLMS_BYTES} bytes.`);\n\n let text: string;\n try {\n text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch {\n throw new Error('llms.txt is not valid UTF-8.');\n }\n if (text.startsWith('\\uFEFF')) text = text.slice(1);\n if (containsUnsafeControl(text)) throw new Error('llms.txt contains unsafe control bytes.');\n\n const firstContentLine = text\n .split(/\\r?\\n/u)\n .find((line) => line.trim().length > 0)\n ?.trim();\n if (!firstContentLine || !/^#\\s+\\S/u.test(firstContentLine)) {\n throw new Error('llms.txt must begin with a Markdown H1 heading.');\n }\n for (const pattern of [\n MARKDOWN_LINK_PATTERN,\n MARKDOWN_REFERENCE_LINK_PATTERN,\n MARKDOWN_AUTOLINK_PATTERN,\n HTML_LINK_PATTERN,\n ]) {\n for (const match of text.matchAll(pattern)) validateRelativeLink(match[1] ?? '');\n }\n return text;\n}\n\nexport function renderHelpSkillWrapper(descriptor: PoHelpSkillDescriptor, index: ResolvedHelpIndex): string {\n const name = JSON.stringify(descriptor.name);\n const description = JSON.stringify(descriptor.description);\n const indexPath = JSON.stringify(index.filePath);\n const referenceBase = JSON.stringify(index.referenceBase);\n return `---\\nname: ${name}\\ndescription: ${description}\\n---\\n\\n# Package Help\\n\\nRead the validated package Help index at ${indexPath}.\\nResolve relative links in that index against ${referenceBase}.\\nOpen only the linked documents relevant to the current request, as needed; do not recursively load the whole reference set.\\n`;\n}\n","import {\n PO_HELP_MAX_DIAGNOSTIC_LENGTH,\n PO_HELP_MAX_DIAGNOSTICS,\n PO_HELP_MAX_SKILLS,\n type PoHelpContribution,\n type PoHelpDiagnostic,\n type PoHelpSkill,\n} from '@agimon-ai/po-core/help';\n\nimport type {\n HelpActivationDependencies,\n HelpActivationService,\n HelpRuntimeState,\n ResolvedHelpIndex,\n} from '../../types/help';\nimport { MAX_AGGREGATE_LLMS_BYTES } from '../llmsContent';\n\nconst MAX_RESOLUTION_CONCURRENCY = 4;\nconst FAILURE_MESSAGE = 'No package Help source could be activated.';\nconst CANCELLATION_MESSAGE = 'Help activation was cancelled.';\n\ninterface LoadedSource {\n contribution: PoHelpContribution;\n index: ResolvedHelpIndex;\n skills: readonly PoHelpSkill[];\n}\n\ninterface SourceOutcome {\n source: string;\n loaded?: LoadedSource;\n error?: unknown;\n}\n\nexport class HelpActivationError extends Error {\n constructor(message = FAILURE_MESSAGE) {\n super(message);\n this.name = 'HelpActivationError';\n }\n}\n\nfunction cloneContribution(contribution: PoHelpContribution): PoHelpContribution {\n return {\n source: contribution.source,\n moduleUrl: contribution.moduleUrl,\n skills: contribution.skills.map((skill) => ({ ...skill })),\n };\n}\n\nfunction cloneState(state: HelpRuntimeState): HelpRuntimeState {\n return {\n activation: state.activation,\n skills: state.skills.map((skill) => ({ ...skill })),\n diagnostics: state.diagnostics.map((diagnostic) => ({ ...diagnostic })),\n };\n}\n\nfunction diagnostic(source: string, code: string, error: unknown): PoHelpDiagnostic {\n const raw = error instanceof Error ? error.message : String(error);\n const message = (raw || 'Unknown Help activation failure.').slice(0, PO_HELP_MAX_DIAGNOSTIC_LENGTH);\n return { source, code, message };\n}\n\nfunction contributionFingerprint(contributions: readonly PoHelpContribution[]): string {\n return JSON.stringify(\n contributions.map((contribution) => ({\n source: contribution.source,\n moduleUrl: contribution.moduleUrl,\n skills: contribution.skills,\n })),\n );\n}\n\nexport class DefaultHelpActivationService implements HelpActivationService {\n private readonly dependencies: HelpActivationDependencies;\n private readonly listeners = new Set<(state: HelpRuntimeState) => void>();\n private contributions: PoHelpContribution[] = [];\n private fingerprint = '[]';\n private state: HelpRuntimeState = { activation: 'inactive', skills: [], diagnostics: [] };\n private settledState: HelpRuntimeState = { activation: 'inactive', skills: [], diagnostics: [] };\n private generation = 0;\n private controller: AbortController | undefined;\n private disposed = false;\n\n constructor(dependencies: HelpActivationDependencies) {\n this.dependencies = dependencies;\n }\n\n getState(): HelpRuntimeState {\n return cloneState(this.state);\n }\n\n replaceContributions(contributions: readonly PoHelpContribution[]): void {\n if (this.disposed) return;\n const next = contributions.map(cloneContribution).sort((left, right) => left.source.localeCompare(right.source));\n const fingerprint = contributionFingerprint(next);\n if (fingerprint === this.fingerprint) return;\n const previous = new Map(this.contributions.map((entry) => [entry.source, contributionFingerprint([entry])]));\n const retained = new Set(\n next\n .filter((entry) => previous.get(entry.source) === contributionFingerprint([entry]))\n .map((entry) => entry.source),\n );\n // A refresh may retain unchanged owners, never withdrawn or replaced ones.\n // Prune the rollback snapshot too, so cancellation cannot resurrect them.\n const skills = this.settledState.skills.filter((entry) => retained.has(entry.source));\n const diagnostics = this.settledState.diagnostics.filter((entry) => !entry.source || retained.has(entry.source));\n this.settledState = {\n activation: skills.length === 0 ? 'inactive' : diagnostics.length > 0 ? 'degraded' : 'active',\n skills,\n diagnostics,\n };\n this.contributions = next;\n this.fingerprint = fingerprint;\n if (this.state.activation !== 'inactive') {\n void this.activate().catch((error: unknown) => {\n // Activation failures publish a bounded settled state before rejecting.\n // Only unexpected implementation failures need an out-of-band report.\n if (error instanceof HelpActivationError) return;\n this.dependencies.onBackgroundError(error);\n });\n }\n }\n\n subscribe(listener: (state: HelpRuntimeState) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n private publish(state: HelpRuntimeState): HelpRuntimeState {\n this.state = cloneState(state);\n if (state.activation !== 'activating') this.settledState = cloneState(state);\n this.dependencies.publisher.publish(this.state);\n for (const listener of this.listeners) listener(cloneState(this.state));\n return this.getState();\n }\n\n private async loadSources(signal: AbortSignal): Promise<SourceOutcome[]> {\n const contributions = this.contributions;\n const outcomes: SourceOutcome[] = Array.from({ length: contributions.length });\n let cursor = 0;\n const worker = async (): Promise<void> => {\n while (cursor < contributions.length) {\n const index = cursor;\n cursor += 1;\n const contribution = contributions[index];\n if (!contribution) return;\n if (signal.aborted) throw new HelpActivationError(CANCELLATION_MESSAGE);\n try {\n const resolved = await this.dependencies.resolver.resolve(contribution, signal);\n if (signal.aborted) throw new HelpActivationError(CANCELLATION_MESSAGE);\n const skills = await this.dependencies.materializer.materialize(contribution, resolved, signal);\n outcomes[index] = { source: contribution.source, loaded: { contribution, index: resolved, skills } };\n } catch (error) {\n if (signal.aborted) throw new HelpActivationError(CANCELLATION_MESSAGE);\n outcomes[index] = { source: contribution.source, error };\n }\n }\n };\n const count = Math.min(MAX_RESOLUTION_CONCURRENCY, contributions.length);\n await Promise.all(Array.from({ length: count }, () => worker()));\n return outcomes;\n }\n\n async activate(externalSignal?: AbortSignal): Promise<HelpRuntimeState> {\n if (this.disposed) throw new HelpActivationError('Help runtime is disposed.');\n this.controller?.abort('Help activation generation replaced.');\n const controller = new AbortController();\n this.controller = controller;\n const generation = ++this.generation;\n const abortFromExternal = () => controller.abort(externalSignal?.reason);\n externalSignal?.addEventListener('abort', abortFromExternal, { once: true });\n if (externalSignal?.aborted) abortFromExternal();\n\n const settledState = cloneState(this.settledState);\n this.publish({ activation: 'activating', skills: settledState.skills, diagnostics: settledState.diagnostics });\n try {\n const outcomes = await this.loadSources(controller.signal);\n if (controller.signal.aborted || generation !== this.generation) {\n throw new HelpActivationError(CANCELLATION_MESSAGE);\n }\n\n const diagnostics: PoHelpDiagnostic[] = [];\n const loaded: LoadedSource[] = [];\n let aggregateBytes = 0;\n for (const outcome of outcomes) {\n if (!outcome) continue;\n if (outcome.error || !outcome.loaded) {\n diagnostics.push(diagnostic(outcome.source, 'HELP_SOURCE_FAILED', outcome.error));\n continue;\n }\n if (aggregateBytes + outcome.loaded.index.byteLength > MAX_AGGREGATE_LLMS_BYTES) {\n diagnostics.push(\n diagnostic(outcome.source, 'HELP_AGGREGATE_LIMIT', 'The aggregate llms.txt byte limit was exceeded.'),\n );\n continue;\n }\n aggregateBytes += outcome.loaded.index.byteLength;\n loaded.push(outcome.loaded);\n }\n\n const skills: PoHelpSkill[] = [];\n const names = new Set<string>();\n for (const source of loaded) {\n for (const skill of source.skills) {\n if (skills.length >= PO_HELP_MAX_SKILLS) {\n diagnostics.push(\n diagnostic(source.contribution.source, 'HELP_SKILL_LIMIT', 'The Help skill limit was reached.'),\n );\n break;\n }\n if (names.has(skill.name)) {\n diagnostics.push(\n diagnostic(\n source.contribution.source,\n 'HELP_SKILL_COLLISION',\n `Help skill '${skill.name}' was already provided by an earlier package source.`,\n ),\n );\n continue;\n }\n names.add(skill.name);\n skills.push({ ...skill });\n }\n }\n\n const boundedDiagnostics = diagnostics.slice(0, PO_HELP_MAX_DIAGNOSTICS);\n if (skills.length === 0) {\n this.publish({ activation: 'inactive', skills: [], diagnostics: boundedDiagnostics });\n throw new HelpActivationError();\n }\n return this.publish({\n activation: boundedDiagnostics.length > 0 ? 'degraded' : 'active',\n skills,\n diagnostics: boundedDiagnostics,\n });\n } catch (error) {\n if (generation === this.generation && this.state.activation === 'activating') this.publish(settledState);\n throw error;\n } finally {\n externalSignal?.removeEventListener('abort', abortFromExternal);\n if (this.controller === controller) this.controller = undefined;\n }\n }\n\n deactivate(): HelpRuntimeState {\n this.generation += 1;\n this.controller?.abort('Help deactivated.');\n this.controller = undefined;\n return this.publish({ activation: 'inactive', skills: [], diagnostics: [] });\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.deactivate();\n this.disposed = true;\n this.listeners.clear();\n }\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport fsPromises from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { PoHelpContribution, PoHelpSkill } from '@agimon-ai/po-core/help';\nimport { poHomeDirectory } from '@agimon-ai/po-core/piSettings';\n\nimport type { HelpPackageIdentity, HelpSkillMaterializer, ResolvedHelpIndex } from '../../types/help';\nimport { renderHelpSkillWrapper } from '../llmsContent';\n\nconst PACKAGE_MANIFEST = 'package.json';\nconst HELP_INDEX_PATH = 'llms.txt';\nconst CACHE_SCHEMA_VERSION = 1;\nconst PRIVATE_FILE_MODE = 0o600;\nconst PRIVATE_DIRECTORY_MODE = 0o700;\nconst COMPLETION_FILE = '.complete';\nconst CACHE_METADATA_FILE = 'metadata.json';\nconst WRAPPER_DIRECTORY = 'wrappers';\nconst SKILL_FILE = 'SKILL.md';\nconst EXACT_SEMVER_PATTERN =\n /^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/u;\nconst NPM_PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._~-]*\\/)?[a-z0-9][a-z0-9._~-]*$/u;\n\ninterface CacheMetadata {\n schemaVersion: typeof CACHE_SCHEMA_VERSION;\n source: string;\n version: string;\n path: typeof HELP_INDEX_PATH;\n integrity: string;\n digest: string;\n referenceBase: string;\n}\n\nexport interface CachedHelpIndex {\n bytes: Uint8Array;\n filePath: string;\n integrity: string;\n digest: string;\n referenceBase: string;\n}\n\nfunction assertNotAborted(signal: AbortSignal): void {\n if (signal.aborted) throw new Error('Help activation was cancelled.');\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isContained(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));\n}\n\nasync function readManifest(filePath: string): Promise<Record<string, unknown> | undefined> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(await fsPromises.readFile(filePath, 'utf8')) as unknown;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw new Error(\n `Cannot read Help package manifest at ${filePath}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (!isRecord(parsed)) throw new Error(`Help package manifest at ${filePath} must contain an object.`);\n return parsed;\n}\n\nexport async function resolveHelpPackageIdentity(\n moduleUrl: string,\n expectedSource: string,\n): Promise<HelpPackageIdentity> {\n if (!NPM_PACKAGE_NAME_PATTERN.test(expectedSource)) {\n throw new Error(`Help source '${expectedSource}' must be a valid lowercase npm package name.`);\n }\n let modulePath: string;\n try {\n const url = new URL(moduleUrl);\n if (url.protocol !== 'file:') throw new Error(`Help module URL must use file:, received ${url.protocol}`);\n modulePath = await fsPromises.realpath(fileURLToPath(url));\n } catch (error) {\n throw new Error(\n `Invalid Help contributor module URL '${moduleUrl}': ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (!(await fsPromises.lstat(modulePath)).isFile())\n throw new Error(`Help contributor module is not a regular file: ${modulePath}`);\n\n let directory = path.dirname(modulePath);\n while (true) {\n const manifestPath = path.join(directory, PACKAGE_MANIFEST);\n const manifest = await readManifest(manifestPath);\n if (manifest !== undefined) {\n const source = manifest.name;\n const version = manifest.version;\n if (source !== expectedSource) {\n throw new Error(`Help source '${expectedSource}' does not match nearest package '${String(source)}'.`);\n }\n if (typeof version !== 'string' || !EXACT_SEMVER_PATTERN.test(version)) {\n throw new Error(`Help package '${expectedSource}' must declare an exact semantic version.`);\n }\n const packageRoot = await fsPromises.realpath(directory);\n if (!isContained(packageRoot, modulePath))\n throw new Error('Help contributor module escapes its resolved package root.');\n return { source: expectedSource, version, packageRoot, modulePath };\n }\n const parent = path.dirname(directory);\n if (parent === directory) break;\n directory = parent;\n }\n throw new Error(`Cannot find a package manifest for Help contributor ${modulePath}.`);\n}\n\nexport function defaultHelpCacheRoot(homeDirectory = os.homedir()): string {\n return path.join(poHomeDirectory(homeDirectory), 'llms-cache');\n}\n\nexport function sha256Hex(bytes: Uint8Array | string): string {\n return createHash('sha256').update(bytes).digest('hex');\n}\n\nfunction parseCacheMetadata(value: unknown, identity: HelpPackageIdentity): CacheMetadata | undefined {\n if (!isRecord(value)) return undefined;\n if (\n value.schemaVersion !== CACHE_SCHEMA_VERSION ||\n value.source !== identity.source ||\n value.version !== identity.version ||\n value.path !== HELP_INDEX_PATH ||\n typeof value.integrity !== 'string' ||\n typeof value.digest !== 'string' ||\n typeof value.referenceBase !== 'string'\n ) {\n return undefined;\n }\n return value as unknown as CacheMetadata;\n}\n\n// Share mutation ordering across cache instances targeting the same entry.\nconst cacheMutations = new Map<string, Promise<void>>();\n\nasync function mutateCacheEntry<T>(directory: string, operation: () => Promise<T>): Promise<T> {\n const key = path.resolve(directory);\n const previous = cacheMutations.get(key) ?? Promise.resolve();\n const result = previous.then(operation);\n const settled = result.then(\n () => {},\n () => {},\n );\n cacheMutations.set(key, settled);\n try {\n return await result;\n } finally {\n if (cacheMutations.get(key) === settled) cacheMutations.delete(key);\n }\n}\n\nasync function regularFile(filePath: string): Promise<boolean> {\n try {\n const metadata = await fsPromises.lstat(filePath);\n return metadata.isFile() && !metadata.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nexport class HelpIndexCache {\n readonly root: string;\n\n constructor(root = defaultHelpCacheRoot()) {\n this.root = root;\n }\n\n entryDirectory(identity: HelpPackageIdentity): string {\n const key = sha256Hex(`${identity.source}\\0${identity.version}\\0${HELP_INDEX_PATH}`);\n return path.join(this.root, key);\n }\n\n async discard(identity: HelpPackageIdentity): Promise<void> {\n const directory = this.entryDirectory(identity);\n await mutateCacheEntry(directory, () => fsPromises.rm(directory, { recursive: true, force: true }));\n }\n\n async read(identity: HelpPackageIdentity): Promise<CachedHelpIndex | undefined> {\n const directory = this.entryDirectory(identity);\n const completionPath = path.join(directory, COMPLETION_FILE);\n const indexPath = path.join(directory, HELP_INDEX_PATH);\n const metadataPath = path.join(directory, CACHE_METADATA_FILE);\n if (!(await regularFile(completionPath)) || !(await regularFile(indexPath)) || !(await regularFile(metadataPath)))\n return undefined;\n try {\n const metadata = parseCacheMetadata(\n JSON.parse(await fsPromises.readFile(metadataPath, 'utf8')) as unknown,\n identity,\n );\n if (!metadata) return undefined;\n const bytes = await fsPromises.readFile(indexPath);\n if (sha256Hex(bytes) !== metadata.digest) return undefined;\n if ((await fsPromises.readFile(completionPath, 'utf8')).trim() !== metadata.digest) return undefined;\n return {\n bytes,\n filePath: indexPath,\n integrity: metadata.integrity,\n digest: metadata.digest,\n referenceBase: metadata.referenceBase,\n };\n } catch {\n return undefined;\n }\n }\n\n async publish(\n identity: HelpPackageIdentity,\n bytes: Uint8Array,\n integrity: string,\n referenceBase: string,\n signal: AbortSignal,\n ): Promise<CachedHelpIndex> {\n const directory = this.entryDirectory(identity);\n return mutateCacheEntry(directory, async () => {\n assertNotAborted(signal);\n const existing = await this.read(identity);\n if (existing) return existing;\n await fsPromises.mkdir(this.root, { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n await fsPromises.rm(directory, { recursive: true, force: true });\n const temporary = `${directory}.${process.pid}.${randomUUID()}.tmp`;\n const digest = sha256Hex(bytes);\n const metadata: CacheMetadata = {\n schemaVersion: CACHE_SCHEMA_VERSION,\n source: identity.source,\n version: identity.version,\n path: HELP_INDEX_PATH,\n integrity,\n digest,\n referenceBase,\n };\n try {\n await fsPromises.mkdir(temporary, { mode: PRIVATE_DIRECTORY_MODE });\n await fsPromises.writeFile(path.join(temporary, HELP_INDEX_PATH), bytes, { mode: PRIVATE_FILE_MODE });\n await fsPromises.writeFile(\n path.join(temporary, CACHE_METADATA_FILE),\n `${JSON.stringify(metadata, null, 2)}\\n`,\n {\n mode: PRIVATE_FILE_MODE,\n },\n );\n assertNotAborted(signal);\n await fsPromises.writeFile(path.join(temporary, COMPLETION_FILE), `${digest}\\n`, { mode: PRIVATE_FILE_MODE });\n try {\n await fsPromises.rename(temporary, directory);\n } catch (error) {\n const winner = await this.read(identity);\n if (winner) return winner;\n throw error;\n }\n return {\n bytes: Uint8Array.from(bytes),\n filePath: path.join(directory, HELP_INDEX_PATH),\n integrity,\n digest,\n referenceBase,\n };\n } finally {\n await fsPromises.rm(temporary, { recursive: true, force: true });\n }\n });\n }\n}\n\nexport class DefaultHelpSkillMaterializer implements HelpSkillMaterializer {\n constructor(private readonly cacheRoot = defaultHelpCacheRoot()) {}\n\n async materialize(\n contribution: PoHelpContribution,\n index: ResolvedHelpIndex,\n signal: AbortSignal,\n ): Promise<readonly PoHelpSkill[]> {\n const skills: PoHelpSkill[] = [];\n for (const descriptor of contribution.skills) {\n assertNotAborted(signal);\n const key = sha256Hex(\n `${index.identity.source}\\0${index.identity.version}\\0${descriptor.name}\\0${descriptor.description}\\0${index.digest}`,\n );\n const directory = path.join(this.cacheRoot, WRAPPER_DIRECTORY, key);\n const filePath = path.join(directory, SKILL_FILE);\n const content = renderHelpSkillWrapper(descriptor, index);\n const matches = async (): Promise<boolean> => {\n try {\n const metadata = await fsPromises.lstat(filePath);\n return (\n metadata.isFile() && !metadata.isSymbolicLink() && (await fsPromises.readFile(filePath, 'utf8')) === content\n );\n } catch {\n return false;\n }\n };\n if (!(await matches())) {\n await fsPromises.mkdir(path.dirname(directory), { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n await fsPromises.rm(directory, { recursive: true, force: true });\n const temporary = `${directory}.${process.pid}.${randomUUID()}.tmp`;\n try {\n await fsPromises.mkdir(temporary, { mode: PRIVATE_DIRECTORY_MODE });\n await fsPromises.writeFile(path.join(temporary, SKILL_FILE), content, { mode: PRIVATE_FILE_MODE });\n assertNotAborted(signal);\n try {\n await fsPromises.rename(temporary, directory);\n } catch (error) {\n if (!(await matches())) throw error;\n }\n } finally {\n await fsPromises.rm(temporary, { recursive: true, force: true });\n }\n }\n skills.push({\n source: contribution.source,\n name: descriptor.name,\n description: descriptor.description,\n filePath,\n baseDir: directory,\n });\n }\n return skills;\n }\n}\n","import { createHash } from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type { PoHelpContribution } from '@agimon-ai/po-core/help';\n\nimport type { HelpFetch, HelpFetchResponse, HelpIndexResolver, ResolvedHelpIndex } from '../../types/help';\nimport { HelpIndexCache, resolveHelpPackageIdentity, sha256Hex } from '../helpStorage';\nimport { MAX_LLMS_BYTES, validateLlmsBytes } from '../llmsContent';\n\nconst HELP_INDEX_PATH = 'llms.txt';\nconst UNPKG_ORIGIN = 'https://unpkg.com';\nconst DEFAULT_FETCH_TIMEOUT_MS = 5_000;\nconst MAX_METADATA_BYTES = 512 * 1024;\nconst MAX_REDIRECTS = 3;\nconst SRI_PATTERN = /^sha256-([A-Za-z0-9+/]+={0,2})$/u;\n\ninterface UnpkgMetadataFile {\n path: string;\n size?: number;\n integrity: string;\n}\n\nexport interface DefaultHelpIndexResolverOptions {\n cache?: HelpIndexCache;\n fetch?: HelpFetch;\n timeoutMs?: number;\n}\n\nfunction defaultFetch(input: string, init: { signal: AbortSignal; redirect: 'manual' }): Promise<HelpFetchResponse> {\n return fetch(input, init) as unknown as Promise<HelpFetchResponse>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nasync function isRegularFile(filePath: string): Promise<boolean | undefined> {\n try {\n const metadata = await fs.lstat(filePath);\n return metadata.isFile() && !metadata.isSymbolicLink();\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw error;\n }\n}\n\nfunction unpkgPackagePath(source: string, version: string): string {\n const encoded = source\n .split('/')\n .map((segment) =>\n segment.startsWith('@') ? `@${encodeURIComponent(segment.slice(1))}` : encodeURIComponent(segment),\n )\n .join('/');\n return `${encoded}@${encodeURIComponent(version)}`;\n}\n\nfunction exactUnpkgBase(source: string, version: string): string {\n return `${UNPKG_ORIGIN}/${unpkgPackagePath(source, version)}/`;\n}\n\nfunction contentLength(response: HelpFetchResponse): number | undefined {\n const raw = response.headers.get('content-length');\n if (!raw) return undefined;\n const parsed = Number.parseInt(raw, 10);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\nfunction timeoutSignal(parent: AbortSignal, timeoutMs: number): { signal: AbortSignal; dispose(): void } {\n const controller = new AbortController();\n const abort = () => controller.abort(parent.reason);\n parent.addEventListener('abort', abort, { once: true });\n const timer = setTimeout(() => controller.abort(new Error('Help download timed out.')), timeoutMs);\n if (parent.aborted) abort();\n return {\n signal: controller.signal,\n dispose() {\n clearTimeout(timer);\n parent.removeEventListener('abort', abort);\n },\n };\n}\n\nasync function fetchExact(fetcher: HelpFetch, initialUrl: string, signal: AbortSignal): Promise<HelpFetchResponse> {\n let url = initialUrl;\n const expected = new URL(initialUrl);\n for (let redirect = 0; redirect <= MAX_REDIRECTS; redirect += 1) {\n const response = await fetcher(url, { signal, redirect: 'manual' });\n if (response.status < 300 || response.status >= 400) return response;\n const location = response.headers.get('location');\n if (!location) throw new Error(`Unpkg redirected ${url} without a location.`);\n const next = new URL(location, url);\n if (next.origin !== UNPKG_ORIGIN || next.pathname !== expected.pathname || next.search !== expected.search) {\n throw new Error(`Unpkg redirect escaped the exact package/version path: ${next.href}`);\n }\n url = next.href;\n }\n throw new Error(`Unpkg exceeded ${MAX_REDIRECTS} redirects.`);\n}\n\nfunction parseMetadata(text: string): UnpkgMetadataFile {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text) as unknown;\n } catch {\n throw new Error('Unpkg metadata is not valid JSON.');\n }\n if (!isRecord(parsed) || !Array.isArray(parsed.files)) throw new Error('Unpkg metadata has no files list.');\n const match = parsed.files.find((entry) => isRecord(entry) && entry.path === `/${HELP_INDEX_PATH}`);\n if (!isRecord(match) || typeof match.integrity !== 'string') {\n throw new Error(`Unpkg package does not publish /${HELP_INDEX_PATH}.`);\n }\n const size = typeof match.size === 'number' ? match.size : undefined;\n if (size !== undefined && (!Number.isSafeInteger(size) || size < 0 || size > MAX_LLMS_BYTES)) {\n throw new Error(`Unpkg /${HELP_INDEX_PATH} exceeds the Help size limit.`);\n }\n if (!SRI_PATTERN.test(match.integrity)) throw new Error('Unpkg llms.txt metadata does not contain SHA-256 SRI.');\n return { path: match.path as string, ...(size === undefined ? {} : { size }), integrity: match.integrity };\n}\n\nfunction verifySri(bytes: Uint8Array, integrity: string): void {\n const expected = SRI_PATTERN.exec(integrity)?.[1];\n if (!expected) throw new Error('Invalid llms.txt SRI metadata.');\n const actual = createHash('sha256').update(bytes).digest('base64');\n if (actual !== expected) throw new Error('Downloaded llms.txt failed SRI verification.');\n}\n\nexport class DefaultHelpIndexResolver implements HelpIndexResolver {\n private readonly cache: HelpIndexCache;\n private readonly fetcher: HelpFetch;\n private readonly timeoutMs: number;\n\n constructor(options: DefaultHelpIndexResolverOptions = {}) {\n this.cache = options.cache ?? new HelpIndexCache();\n this.fetcher = options.fetch ?? defaultFetch;\n this.timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;\n }\n\n async resolve(contribution: PoHelpContribution, signal: AbortSignal): Promise<ResolvedHelpIndex> {\n if (signal.aborted) throw new Error('Help activation was cancelled.');\n const identity = await resolveHelpPackageIdentity(contribution.moduleUrl, contribution.source);\n const localPath = path.join(identity.packageRoot, HELP_INDEX_PATH);\n const regular = await isRegularFile(localPath);\n if (regular !== undefined) {\n if (!regular) throw new Error(`Bundled ${HELP_INDEX_PATH} must be a regular file.`);\n const bytes = await fs.readFile(localPath);\n validateLlmsBytes(bytes);\n return {\n identity,\n location: 'local',\n filePath: localPath,\n referenceBase: identity.packageRoot,\n byteLength: bytes.byteLength,\n digest: sha256Hex(bytes),\n };\n }\n\n const cached = await this.cache.read(identity);\n if (cached) {\n try {\n validateLlmsBytes(cached.bytes);\n return {\n identity,\n location: 'cache',\n filePath: cached.filePath,\n referenceBase: cached.referenceBase,\n byteLength: cached.bytes.byteLength,\n digest: cached.digest,\n };\n } catch {\n await this.cache.discard(identity);\n }\n }\n\n const timed = timeoutSignal(signal, this.timeoutMs);\n try {\n const referenceBase = exactUnpkgBase(identity.source, identity.version);\n const metadataResponse = await fetchExact(this.fetcher, `${referenceBase}?meta`, timed.signal);\n const metadataLength = contentLength(metadataResponse);\n if (metadataLength !== undefined && metadataLength > MAX_METADATA_BYTES) {\n throw new Error('Unpkg metadata exceeds the Help metadata size limit.');\n }\n if (!metadataResponse.ok) throw new Error(`Unpkg metadata request failed with HTTP ${metadataResponse.status}.`);\n const metadataText = await metadataResponse.text();\n if (Buffer.byteLength(metadataText, 'utf8') > MAX_METADATA_BYTES) {\n throw new Error('Unpkg metadata exceeds the Help metadata size limit.');\n }\n const metadata = parseMetadata(metadataText);\n const indexResponse = await fetchExact(this.fetcher, `${referenceBase}${HELP_INDEX_PATH}`, timed.signal);\n const indexLength = contentLength(indexResponse);\n if (indexLength !== undefined && indexLength > MAX_LLMS_BYTES) {\n throw new Error(`Downloaded ${HELP_INDEX_PATH} exceeds ${MAX_LLMS_BYTES} bytes.`);\n }\n if (!indexResponse.ok) throw new Error(`Unpkg llms.txt request failed with HTTP ${indexResponse.status}.`);\n const bytes = new Uint8Array(await indexResponse.arrayBuffer());\n validateLlmsBytes(bytes);\n verifySri(bytes, metadata.integrity);\n const published = await this.cache.publish(identity, bytes, metadata.integrity, referenceBase, timed.signal);\n return {\n identity,\n location: 'remote',\n filePath: published.filePath,\n referenceBase: published.referenceBase,\n byteLength: published.bytes.byteLength,\n digest: published.digest,\n };\n } finally {\n timed.dispose();\n }\n }\n}\n","import type { PoHelpContribution, PoHelpService } from '@agimon-ai/po-core/help';\n\nimport type { HelpFetch } from '../../types/help';\nimport { DefaultHelpActivationService } from '../helpActivation';\nimport { DefaultHelpSkillMaterializer, defaultHelpCacheRoot, HelpIndexCache } from '../helpStorage';\nimport { DefaultHelpIndexResolver } from '../llmsResolver';\n\nexport interface HelpRuntimeOptions {\n cacheRoot?: string;\n fetch?: HelpFetch;\n timeoutMs?: number;\n onBackgroundError?(error: unknown): void;\n}\n\nexport interface HelpRuntimeComposition {\n activation: DefaultHelpActivationService;\n dispose(): void;\n}\n\nfunction reportAsync(error: unknown): void {\n queueMicrotask(() => {\n throw error instanceof Error ? error : new Error(String(error));\n });\n}\n\nexport function createHelpRuntime(service: PoHelpService, options: HelpRuntimeOptions = {}): HelpRuntimeComposition {\n const cacheRoot = options.cacheRoot ?? defaultHelpCacheRoot();\n const cache = new HelpIndexCache(cacheRoot);\n const activation = new DefaultHelpActivationService({\n resolver: new DefaultHelpIndexResolver({ cache, fetch: options.fetch, timeoutMs: options.timeoutMs }),\n materializer: new DefaultHelpSkillMaterializer(cacheRoot),\n publisher: { publish: (snapshot) => service.publish(snapshot) },\n onBackgroundError(error) {\n if (options.onBackgroundError) options.onBackgroundError(error);\n else reportAsync(error);\n },\n });\n const synchronize = (contributions: readonly PoHelpContribution[]): void => {\n activation.replaceContributions(contributions);\n };\n const unsubscribe = service.subscribeContributions((contributions) => synchronize(contributions));\n synchronize(service.listContributions());\n let disposed = false;\n return {\n activation,\n dispose() {\n if (disposed) return;\n disposed = true;\n unsubscribe();\n activation.dispose();\n },\n };\n}\n"],"mappings":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U,OAAO,SAAS,WAAW,eAAe,MAAM,MAAM;GAC3G,OAAO;IACL;IACA,UAAU;IACV,UAAU,UAAU;IACpB,eAAe,UAAU;IACzB,YAAY,UAAU,MAAM;IAC5B,QAAQ,UAAU;GACpB;EACF,UAAU;GACR,MAAM,QAAQ;EAChB;CACF;AACF;;;AC/LA,SAAS,YAAY,OAAsB;CACzC,qBAAqB;EACnB,MAAM,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,OAAO,KAAK,CAAC;CAChE,CAAC;AACH;AAEA,SAAgB,kBAAkB,SAAwB,UAA8B,CAAC,GAA2B;CAClH,MAAM,YAAY,QAAQ,aAAa,qBAAqB;CAE5D,MAAM,aAAa,IAAI,6BAA6B;EAClD,UAAU,IAAI,yBAAyB;GAAE,WAFzB,eAAe,SAEU;GAAO,OAAO,QAAQ;GAAO,WAAW,QAAQ;EAAU,CAAC;EACpG,cAAc,IAAI,6BAA6B,SAAS;EACxD,WAAW,EAAE,UAAU,aAAa,QAAQ,QAAQ,QAAQ,EAAE;EAC9D,kBAAkB,OAAO;GACvB,IAAI,QAAQ,mBAAmB,QAAQ,kBAAkB,KAAK;QACzD,YAAY,KAAK;EACxB;CACF,CAAC;CACD,MAAM,eAAe,kBAAuD;EAC1E,WAAW,qBAAqB,aAAa;CAC/C;CACA,MAAM,cAAc,QAAQ,wBAAwB,kBAAkB,YAAY,aAAa,CAAC;CAChG,YAAY,QAAQ,kBAAkB,CAAC;CACvC,IAAI,WAAW;CACf,OAAO;EACL;EACA,UAAU;GACR,IAAI,UAAU;GACd,WAAW;GACX,YAAY;GACZ,WAAW,QAAQ;EACrB;CACF;AACF"}
|
package/dist/index.d.mts
CHANGED
|
@@ -105,9 +105,9 @@ export declare class HelpIndexCache {
|
|
|
105
105
|
readonly root: string;
|
|
106
106
|
constructor(root?: string);
|
|
107
107
|
entryDirectory(identity: HelpPackageIdentity): string;
|
|
108
|
-
discard(identity: HelpPackageIdentity): void
|
|
109
|
-
read(identity: HelpPackageIdentity): CachedHelpIndex | undefined
|
|
110
|
-
publish(identity: HelpPackageIdentity, bytes: Uint8Array, integrity: string, referenceBase: string, signal: AbortSignal): CachedHelpIndex
|
|
108
|
+
discard(identity: HelpPackageIdentity): Promise<void>;
|
|
109
|
+
read(identity: HelpPackageIdentity): Promise<CachedHelpIndex | undefined>;
|
|
110
|
+
publish(identity: HelpPackageIdentity, bytes: Uint8Array, integrity: string, referenceBase: string, signal: AbortSignal): Promise<CachedHelpIndex>;
|
|
111
111
|
}
|
|
112
112
|
export declare class DefaultHelpSkillMaterializer implements HelpSkillMaterializer {
|
|
113
113
|
private readonly cacheRoot;
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types/help.ts","../src/services/helpActivation/index.ts","../src/services/helpRuntime/index.ts","../src/services/helpStorage/index.ts","../src/services/llmsResolver/index.ts"],"mappings":";;UAEiB;EACf;EACA;EACA;EACA;;KAGU;UAEK;EACf,UAAU;EACV,UAAU;EACV;EACA;EACA;EACA;;UAGe;EACf,QAAQ,cAAc,oBAAoB,QAAQ,cAAc,QAAQ;;UAGzD;EACf,YACE,cAAc,oBACd,OAAO,mBACP,QAAQ,cACP,iBAAiB;;UAGL;EACf,YAAY;EACZ,iBAAiB;EACjB,sBAAsB;;UAGP;EACf,QAAQ,UAAU;;UAGH;EACf,UAAU;EACV,cAAc;EACd,WAAW;EACX,kBAAkB;;UAGH;EACf,YAAY;EACZ,qBAAqB,wBAAwB;EAC7C,UAAU,WAAW,OAAO;EAC5B,SAAS,SAAS,cAAc,QAAQ;EACxC,cAAc;EACd;;UAGe;EACf;EACA;EACA;IAAW,IAAI;;EACf,QAAQ;EACR,eAAe,QAAQ;;KAGb,aACV,eACA;EAAQ,QAAQ;EAAa;MAC1B,QAAQ;;;qBCGA,wCAAwC;mBAClC;mBACA;UACT;UACA;UACA;UACA;UACA;UACA;UACA;EAER,YAAY,cAAc;EAI1B,YAAY;EAIZ,qBAAqB,wBAAwB;EAgC7C,UAAU,WAAW,OAAO;UAKpB;UAQM;EA2BR,SAAS,iBAAiB,cAAc,QAAQ;EAiFtD,cAAc;EAOd;;;;UCpPe;EACf;EACA,QAAQ;EACR;EACA,mBAAmB;;UAGJ;EACf,YAAY;EACZ;;wBASc,kBAAkB,SAAS,eAAe,UAAS,qBAA0B;;;UCU5E;EACf,OAAO;EACP;EACA;EACA;EACA;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/types/help.ts","../src/services/helpActivation/index.ts","../src/services/helpRuntime/index.ts","../src/services/helpStorage/index.ts","../src/services/llmsResolver/index.ts"],"mappings":";;UAEiB;EACf;EACA;EACA;EACA;;KAGU;UAEK;EACf,UAAU;EACV,UAAU;EACV;EACA;EACA;EACA;;UAGe;EACf,QAAQ,cAAc,oBAAoB,QAAQ,cAAc,QAAQ;;UAGzD;EACf,YACE,cAAc,oBACd,OAAO,mBACP,QAAQ,cACP,iBAAiB;;UAGL;EACf,YAAY;EACZ,iBAAiB;EACjB,sBAAsB;;UAGP;EACf,QAAQ,UAAU;;UAGH;EACf,UAAU;EACV,cAAc;EACd,WAAW;EACX,kBAAkB;;UAGH;EACf,YAAY;EACZ,qBAAqB,wBAAwB;EAC7C,UAAU,WAAW,OAAO;EAC5B,SAAS,SAAS,cAAc,QAAQ;EACxC,cAAc;EACd;;UAGe;EACf;EACA;EACA;IAAW,IAAI;;EACf,QAAQ;EACR,eAAe,QAAQ;;KAGb,aACV,eACA;EAAQ,QAAQ;EAAa;MAC1B,QAAQ;;;qBCGA,wCAAwC;mBAClC;mBACA;UACT;UACA;UACA;UACA;UACA;UACA;UACA;EAER,YAAY,cAAc;EAI1B,YAAY;EAIZ,qBAAqB,wBAAwB;EAgC7C,UAAU,WAAW,OAAO;UAKpB;UAQM;EA2BR,SAAS,iBAAiB,cAAc,QAAQ;EAiFtD,cAAc;EAOd;;;;UCpPe;EACf;EACA,QAAQ;EACR;EACA,mBAAmB;;UAGJ;EACf,YAAY;EACZ;;wBASc,kBAAkB,SAAS,eAAe,UAAS,qBAA0B;;;UCU5E;EACf,OAAO;EACP;EACA;EACA;EACA;;wBA2Ec,qBAAqB;qBAoDxB;WACF;EAET,YAAY;EAIZ,eAAe,UAAU;EAKnB,QAAQ,UAAU,sBAAsB;EAKxC,KAAK,UAAU,sBAAsB,QAAQ;EA4B7C,QACJ,UAAU,qBACV,OAAO,YACP,mBACA,uBACA,QAAQ,cACP,QAAQ;;qBAoDA,wCAAwC;mBACtB;EAA7B,YAA6B;EAEvB,YACJ,cAAc,oBACd,OAAO,mBACP,QAAQ,cACP,iBAAiB;;;;UC9PL;EACf,QAAQ;EACR,QAAQ;EACR;;qBAqGW,oCAAoC;mBAC9B;mBACA;mBACA;EAEjB,YAAY,UAAS;EAMf,QAAQ,cAAc,oBAAoB,QAAQ,cAAc,QAAQ"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { PO_HELP_MAX_DIAGNOSTICS, PO_HELP_MAX_DIAGNOSTIC_LENGTH, PO_HELP_MAX_SKILLS } from "@agimon-ai/po-core/help";
|
|
2
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
-
import
|
|
3
|
+
import fsPromises from "node:fs/promises";
|
|
4
4
|
import os from "node:os";
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
@@ -324,37 +324,37 @@ function isContained(root, candidate) {
|
|
|
324
324
|
const relative = path.relative(root, candidate);
|
|
325
325
|
return relative === "" || !relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative);
|
|
326
326
|
}
|
|
327
|
-
function readManifest(filePath) {
|
|
327
|
+
async function readManifest(filePath) {
|
|
328
328
|
let parsed;
|
|
329
329
|
try {
|
|
330
|
-
parsed = JSON.parse(
|
|
330
|
+
parsed = JSON.parse(await fsPromises.readFile(filePath, "utf8"));
|
|
331
331
|
} catch (error) {
|
|
332
|
+
if (error.code === "ENOENT") return void 0;
|
|
332
333
|
throw new Error(`Cannot read Help package manifest at ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
|
|
333
334
|
}
|
|
334
335
|
if (!isRecord$1(parsed)) throw new Error(`Help package manifest at ${filePath} must contain an object.`);
|
|
335
336
|
return parsed;
|
|
336
337
|
}
|
|
337
|
-
function resolveHelpPackageIdentity(moduleUrl, expectedSource) {
|
|
338
|
+
async function resolveHelpPackageIdentity(moduleUrl, expectedSource) {
|
|
338
339
|
if (!NPM_PACKAGE_NAME_PATTERN.test(expectedSource)) throw new Error(`Help source '${expectedSource}' must be a valid lowercase npm package name.`);
|
|
339
340
|
let modulePath;
|
|
340
341
|
try {
|
|
341
342
|
const url = new URL(moduleUrl);
|
|
342
343
|
if (url.protocol !== "file:") throw new Error(`Help module URL must use file:, received ${url.protocol}`);
|
|
343
|
-
modulePath =
|
|
344
|
+
modulePath = await fsPromises.realpath(fileURLToPath(url));
|
|
344
345
|
} catch (error) {
|
|
345
346
|
throw new Error(`Invalid Help contributor module URL '${moduleUrl}': ${error instanceof Error ? error.message : String(error)}`);
|
|
346
347
|
}
|
|
347
|
-
if (!
|
|
348
|
+
if (!(await fsPromises.lstat(modulePath)).isFile()) throw new Error(`Help contributor module is not a regular file: ${modulePath}`);
|
|
348
349
|
let directory = path.dirname(modulePath);
|
|
349
350
|
while (true) {
|
|
350
|
-
const
|
|
351
|
-
if (
|
|
352
|
-
const manifest = readManifest(manifestPath);
|
|
351
|
+
const manifest = await readManifest(path.join(directory, PACKAGE_MANIFEST));
|
|
352
|
+
if (manifest !== void 0) {
|
|
353
353
|
const source = manifest.name;
|
|
354
354
|
const version = manifest.version;
|
|
355
355
|
if (source !== expectedSource) throw new Error(`Help source '${expectedSource}' does not match nearest package '${String(source)}'.`);
|
|
356
356
|
if (typeof version !== "string" || !EXACT_SEMVER_PATTERN.test(version)) throw new Error(`Help package '${expectedSource}' must declare an exact semantic version.`);
|
|
357
|
-
const packageRoot =
|
|
357
|
+
const packageRoot = await fsPromises.realpath(directory);
|
|
358
358
|
if (!isContained(packageRoot, modulePath)) throw new Error("Help contributor module escapes its resolved package root.");
|
|
359
359
|
return {
|
|
360
360
|
source: expectedSource,
|
|
@@ -380,9 +380,21 @@ function parseCacheMetadata(value, identity) {
|
|
|
380
380
|
if (value.schemaVersion !== CACHE_SCHEMA_VERSION || value.source !== identity.source || value.version !== identity.version || value.path !== HELP_INDEX_PATH$1 || typeof value.integrity !== "string" || typeof value.digest !== "string" || typeof value.referenceBase !== "string") return;
|
|
381
381
|
return value;
|
|
382
382
|
}
|
|
383
|
-
|
|
383
|
+
const cacheMutations = /* @__PURE__ */ new Map();
|
|
384
|
+
async function mutateCacheEntry(directory, operation) {
|
|
385
|
+
const key = path.resolve(directory);
|
|
386
|
+
const result = (cacheMutations.get(key) ?? Promise.resolve()).then(operation);
|
|
387
|
+
const settled = result.then(() => {}, () => {});
|
|
388
|
+
cacheMutations.set(key, settled);
|
|
384
389
|
try {
|
|
385
|
-
|
|
390
|
+
return await result;
|
|
391
|
+
} finally {
|
|
392
|
+
if (cacheMutations.get(key) === settled) cacheMutations.delete(key);
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
async function regularFile(filePath) {
|
|
396
|
+
try {
|
|
397
|
+
const metadata = await fsPromises.lstat(filePath);
|
|
386
398
|
return metadata.isFile() && !metadata.isSymbolicLink();
|
|
387
399
|
} catch {
|
|
388
400
|
return false;
|
|
@@ -397,24 +409,25 @@ var HelpIndexCache = class {
|
|
|
397
409
|
const key = sha256Hex(`${identity.source}\0${identity.version}\0${HELP_INDEX_PATH$1}`);
|
|
398
410
|
return path.join(this.root, key);
|
|
399
411
|
}
|
|
400
|
-
discard(identity) {
|
|
401
|
-
|
|
412
|
+
async discard(identity) {
|
|
413
|
+
const directory = this.entryDirectory(identity);
|
|
414
|
+
await mutateCacheEntry(directory, () => fsPromises.rm(directory, {
|
|
402
415
|
recursive: true,
|
|
403
416
|
force: true
|
|
404
|
-
});
|
|
417
|
+
}));
|
|
405
418
|
}
|
|
406
|
-
read(identity) {
|
|
419
|
+
async read(identity) {
|
|
407
420
|
const directory = this.entryDirectory(identity);
|
|
408
421
|
const completionPath = path.join(directory, COMPLETION_FILE);
|
|
409
422
|
const indexPath = path.join(directory, HELP_INDEX_PATH$1);
|
|
410
423
|
const metadataPath = path.join(directory, CACHE_METADATA_FILE);
|
|
411
|
-
if (!regularFile(completionPath) || !regularFile(indexPath) || !regularFile(metadataPath)) return void 0;
|
|
424
|
+
if (!await regularFile(completionPath) || !await regularFile(indexPath) || !await regularFile(metadataPath)) return void 0;
|
|
412
425
|
try {
|
|
413
|
-
const metadata = parseCacheMetadata(JSON.parse(
|
|
426
|
+
const metadata = parseCacheMetadata(JSON.parse(await fsPromises.readFile(metadataPath, "utf8")), identity);
|
|
414
427
|
if (!metadata) return void 0;
|
|
415
|
-
const bytes =
|
|
428
|
+
const bytes = await fsPromises.readFile(indexPath);
|
|
416
429
|
if (sha256Hex(bytes) !== metadata.digest) return void 0;
|
|
417
|
-
if (
|
|
430
|
+
if ((await fsPromises.readFile(completionPath, "utf8")).trim() !== metadata.digest) return void 0;
|
|
418
431
|
return {
|
|
419
432
|
bytes,
|
|
420
433
|
filePath: indexPath,
|
|
@@ -426,56 +439,58 @@ var HelpIndexCache = class {
|
|
|
426
439
|
return;
|
|
427
440
|
}
|
|
428
441
|
}
|
|
429
|
-
publish(identity, bytes, integrity, referenceBase, signal) {
|
|
430
|
-
assertNotAborted(signal);
|
|
431
|
-
const existing = this.read(identity);
|
|
432
|
-
if (existing) return existing;
|
|
442
|
+
async publish(identity, bytes, integrity, referenceBase, signal) {
|
|
433
443
|
const directory = this.entryDirectory(identity);
|
|
434
|
-
|
|
435
|
-
mode: PRIVATE_DIRECTORY_MODE,
|
|
436
|
-
recursive: true
|
|
437
|
-
});
|
|
438
|
-
if (fs.existsSync(directory)) fs.rmSync(directory, {
|
|
439
|
-
recursive: true,
|
|
440
|
-
force: true
|
|
441
|
-
});
|
|
442
|
-
const temporary = `${directory}.${process.pid}.${randomUUID()}.tmp`;
|
|
443
|
-
const digest = sha256Hex(bytes);
|
|
444
|
-
const metadata = {
|
|
445
|
-
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
446
|
-
source: identity.source,
|
|
447
|
-
version: identity.version,
|
|
448
|
-
path: HELP_INDEX_PATH$1,
|
|
449
|
-
integrity,
|
|
450
|
-
digest,
|
|
451
|
-
referenceBase
|
|
452
|
-
};
|
|
453
|
-
try {
|
|
454
|
-
fs.mkdirSync(temporary, { mode: PRIVATE_DIRECTORY_MODE });
|
|
455
|
-
fs.writeFileSync(path.join(temporary, HELP_INDEX_PATH$1), bytes, { mode: PRIVATE_FILE_MODE });
|
|
456
|
-
fs.writeFileSync(path.join(temporary, CACHE_METADATA_FILE), `${JSON.stringify(metadata, null, 2)}\n`, { mode: PRIVATE_FILE_MODE });
|
|
444
|
+
return mutateCacheEntry(directory, async () => {
|
|
457
445
|
assertNotAborted(signal);
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
446
|
+
const existing = await this.read(identity);
|
|
447
|
+
if (existing) return existing;
|
|
448
|
+
await fsPromises.mkdir(this.root, {
|
|
449
|
+
mode: PRIVATE_DIRECTORY_MODE,
|
|
450
|
+
recursive: true
|
|
451
|
+
});
|
|
452
|
+
await fsPromises.rm(directory, {
|
|
453
|
+
recursive: true,
|
|
454
|
+
force: true
|
|
455
|
+
});
|
|
456
|
+
const temporary = `${directory}.${process.pid}.${randomUUID()}.tmp`;
|
|
457
|
+
const digest = sha256Hex(bytes);
|
|
458
|
+
const metadata = {
|
|
459
|
+
schemaVersion: CACHE_SCHEMA_VERSION,
|
|
460
|
+
source: identity.source,
|
|
461
|
+
version: identity.version,
|
|
462
|
+
path: HELP_INDEX_PATH$1,
|
|
469
463
|
integrity,
|
|
470
464
|
digest,
|
|
471
465
|
referenceBase
|
|
472
466
|
};
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
467
|
+
try {
|
|
468
|
+
await fsPromises.mkdir(temporary, { mode: PRIVATE_DIRECTORY_MODE });
|
|
469
|
+
await fsPromises.writeFile(path.join(temporary, HELP_INDEX_PATH$1), bytes, { mode: PRIVATE_FILE_MODE });
|
|
470
|
+
await fsPromises.writeFile(path.join(temporary, CACHE_METADATA_FILE), `${JSON.stringify(metadata, null, 2)}\n`, { mode: PRIVATE_FILE_MODE });
|
|
471
|
+
assertNotAborted(signal);
|
|
472
|
+
await fsPromises.writeFile(path.join(temporary, COMPLETION_FILE), `${digest}\n`, { mode: PRIVATE_FILE_MODE });
|
|
473
|
+
try {
|
|
474
|
+
await fsPromises.rename(temporary, directory);
|
|
475
|
+
} catch (error) {
|
|
476
|
+
const winner = await this.read(identity);
|
|
477
|
+
if (winner) return winner;
|
|
478
|
+
throw error;
|
|
479
|
+
}
|
|
480
|
+
return {
|
|
481
|
+
bytes: Uint8Array.from(bytes),
|
|
482
|
+
filePath: path.join(directory, HELP_INDEX_PATH$1),
|
|
483
|
+
integrity,
|
|
484
|
+
digest,
|
|
485
|
+
referenceBase
|
|
486
|
+
};
|
|
487
|
+
} finally {
|
|
488
|
+
await fsPromises.rm(temporary, {
|
|
489
|
+
recursive: true,
|
|
490
|
+
force: true
|
|
491
|
+
});
|
|
492
|
+
}
|
|
493
|
+
});
|
|
479
494
|
}
|
|
480
495
|
};
|
|
481
496
|
var DefaultHelpSkillMaterializer = class {
|
|
@@ -491,27 +506,35 @@ var DefaultHelpSkillMaterializer = class {
|
|
|
491
506
|
const directory = path.join(this.cacheRoot, WRAPPER_DIRECTORY, key);
|
|
492
507
|
const filePath = path.join(directory, SKILL_FILE);
|
|
493
508
|
const content = renderHelpSkillWrapper(descriptor, index);
|
|
494
|
-
|
|
495
|
-
|
|
509
|
+
const matches = async () => {
|
|
510
|
+
try {
|
|
511
|
+
const metadata = await fsPromises.lstat(filePath);
|
|
512
|
+
return metadata.isFile() && !metadata.isSymbolicLink() && await fsPromises.readFile(filePath, "utf8") === content;
|
|
513
|
+
} catch {
|
|
514
|
+
return false;
|
|
515
|
+
}
|
|
516
|
+
};
|
|
517
|
+
if (!await matches()) {
|
|
518
|
+
await fsPromises.mkdir(path.dirname(directory), {
|
|
496
519
|
mode: PRIVATE_DIRECTORY_MODE,
|
|
497
520
|
recursive: true
|
|
498
521
|
});
|
|
499
|
-
|
|
522
|
+
await fsPromises.rm(directory, {
|
|
500
523
|
recursive: true,
|
|
501
524
|
force: true
|
|
502
525
|
});
|
|
503
526
|
const temporary = `${directory}.${process.pid}.${randomUUID()}.tmp`;
|
|
504
527
|
try {
|
|
505
|
-
|
|
506
|
-
|
|
528
|
+
await fsPromises.mkdir(temporary, { mode: PRIVATE_DIRECTORY_MODE });
|
|
529
|
+
await fsPromises.writeFile(path.join(temporary, SKILL_FILE), content, { mode: PRIVATE_FILE_MODE });
|
|
507
530
|
assertNotAborted(signal);
|
|
508
531
|
try {
|
|
509
|
-
|
|
532
|
+
await fsPromises.rename(temporary, directory);
|
|
510
533
|
} catch (error) {
|
|
511
|
-
if (!
|
|
534
|
+
if (!await matches()) throw error;
|
|
512
535
|
}
|
|
513
536
|
} finally {
|
|
514
|
-
|
|
537
|
+
await fsPromises.rm(temporary, {
|
|
515
538
|
recursive: true,
|
|
516
539
|
force: true
|
|
517
540
|
});
|
|
@@ -542,12 +565,13 @@ function defaultFetch(input, init) {
|
|
|
542
565
|
function isRecord(value) {
|
|
543
566
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
544
567
|
}
|
|
545
|
-
function isRegularFile(filePath) {
|
|
568
|
+
async function isRegularFile(filePath) {
|
|
546
569
|
try {
|
|
547
|
-
const metadata =
|
|
570
|
+
const metadata = await fsPromises.lstat(filePath);
|
|
548
571
|
return metadata.isFile() && !metadata.isSymbolicLink();
|
|
549
|
-
} catch {
|
|
550
|
-
return
|
|
572
|
+
} catch (error) {
|
|
573
|
+
if (error.code === "ENOENT") return void 0;
|
|
574
|
+
throw error;
|
|
551
575
|
}
|
|
552
576
|
}
|
|
553
577
|
function unpkgPackagePath(source, version) {
|
|
@@ -628,11 +652,12 @@ var DefaultHelpIndexResolver = class {
|
|
|
628
652
|
}
|
|
629
653
|
async resolve(contribution, signal) {
|
|
630
654
|
if (signal.aborted) throw new Error("Help activation was cancelled.");
|
|
631
|
-
const identity = resolveHelpPackageIdentity(contribution.moduleUrl, contribution.source);
|
|
655
|
+
const identity = await resolveHelpPackageIdentity(contribution.moduleUrl, contribution.source);
|
|
632
656
|
const localPath = path.join(identity.packageRoot, HELP_INDEX_PATH);
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
657
|
+
const regular = await isRegularFile(localPath);
|
|
658
|
+
if (regular !== void 0) {
|
|
659
|
+
if (!regular) throw new Error(`Bundled ${HELP_INDEX_PATH} must be a regular file.`);
|
|
660
|
+
const bytes = await fsPromises.readFile(localPath);
|
|
636
661
|
validateLlmsBytes(bytes);
|
|
637
662
|
return {
|
|
638
663
|
identity,
|
|
@@ -643,7 +668,7 @@ var DefaultHelpIndexResolver = class {
|
|
|
643
668
|
digest: sha256Hex(bytes)
|
|
644
669
|
};
|
|
645
670
|
}
|
|
646
|
-
const cached = this.cache.read(identity);
|
|
671
|
+
const cached = await this.cache.read(identity);
|
|
647
672
|
if (cached) try {
|
|
648
673
|
validateLlmsBytes(cached.bytes);
|
|
649
674
|
return {
|
|
@@ -655,7 +680,7 @@ var DefaultHelpIndexResolver = class {
|
|
|
655
680
|
digest: cached.digest
|
|
656
681
|
};
|
|
657
682
|
} catch {
|
|
658
|
-
this.cache.discard(identity);
|
|
683
|
+
await this.cache.discard(identity);
|
|
659
684
|
}
|
|
660
685
|
const timed = timeoutSignal(signal, this.timeoutMs);
|
|
661
686
|
try {
|
|
@@ -674,7 +699,7 @@ var DefaultHelpIndexResolver = class {
|
|
|
674
699
|
const bytes = new Uint8Array(await indexResponse.arrayBuffer());
|
|
675
700
|
validateLlmsBytes(bytes);
|
|
676
701
|
verifySri(bytes, metadata.integrity);
|
|
677
|
-
const published = this.cache.publish(identity, bytes, metadata.integrity, referenceBase, timed.signal);
|
|
702
|
+
const published = await this.cache.publish(identity, bytes, metadata.integrity, referenceBase, timed.signal);
|
|
678
703
|
return {
|
|
679
704
|
identity,
|
|
680
705
|
location: "remote",
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["HELP_INDEX_PATH","isRecord"],"sources":["../src/services/llmsContent/index.ts","../src/services/helpActivation/index.ts","../src/services/helpStorage/index.ts","../src/services/llmsResolver/index.ts","../src/services/helpRuntime/index.ts"],"sourcesContent":["import type { PoHelpSkillDescriptor } from '@agimon-ai/po-core/help';\n\nimport type { ResolvedHelpIndex } from '../../types/help';\n\nexport const MAX_LLMS_BYTES = 1024 * 1024;\nexport const MAX_AGGREGATE_LLMS_BYTES = 4 * MAX_LLMS_BYTES;\n\nconst MARKDOWN_LINK_PATTERN = /!?\\[[^\\]]*\\]\\(\\s*<?([^\\s)>]+)>?(?:\\s+[^)]*)?\\)/gu;\nconst MARKDOWN_REFERENCE_LINK_PATTERN = /^\\s{0,3}\\[[^\\]\\r\\n]+\\]:\\s*<?([^\\s>]+)>?/gmu;\nconst MARKDOWN_AUTOLINK_PATTERN = /<((?:\\.{0,2}\\/|[A-Za-z][A-Za-z0-9+.-]*:)[^<>\\s]+)>/gu;\nconst HTML_LINK_PATTERN = /\\b(?:href|src)\\s*=\\s*[\"']([^\"']+)[\"']/giu;\nconst URI_SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:/iu;\nconst NESTED_PATH_ENCODING_PATTERN = /%(?:25|2e|2f|3a|5c)/iu;\nconst SAFE_EXTERNAL_SCHEMES = new Set(['http:', 'https:', 'mailto:']);\n\nfunction externalScheme(target: string): string | undefined {\n if (!URI_SCHEME_PATTERN.test(target)) return undefined;\n return target.slice(0, target.indexOf(':') + 1).toLowerCase();\n}\n\nfunction decodeRelativeTarget(rawTarget: string): string {\n let decoded = rawTarget;\n try {\n for (let pass = 0; pass < 2; pass += 1) {\n const next = decodeURIComponent(decoded);\n if (next === decoded) break;\n decoded = next;\n }\n } catch {\n throw new Error(`llms.txt contains an invalid encoded link '${rawTarget}'.`);\n }\n if (NESTED_PATH_ENCODING_PATTERN.test(decoded)) {\n throw new Error(`llms.txt contains an unsafe nested encoding in link '${rawTarget}'.`);\n }\n return decoded;\n}\n\nfunction validateRelativeLink(rawTarget: string): void {\n if (!rawTarget || rawTarget.startsWith('#')) return;\n const rawScheme = externalScheme(rawTarget);\n if (rawScheme) {\n if (!SAFE_EXTERNAL_SCHEMES.has(rawScheme)) {\n throw new Error(`llms.txt contains unsupported link scheme '${rawScheme}'.`);\n }\n return;\n }\n\n const decoded = decodeRelativeTarget(rawTarget);\n const decodedScheme = externalScheme(decoded);\n if (decodedScheme) {\n if (!SAFE_EXTERNAL_SCHEMES.has(decodedScheme)) {\n throw new Error(`llms.txt contains unsupported link scheme '${decodedScheme}'.`);\n }\n return;\n }\n const withoutSuffix = decoded.split(/[?#]/u, 1)[0]?.replaceAll('\\\\', '/') ?? '';\n if (withoutSuffix.startsWith('/') || withoutSuffix.split('/').some((segment) => segment === '..')) {\n throw new Error(`llms.txt link '${rawTarget}' escapes the package root.`);\n }\n}\n\nfunction containsUnsafeControl(text: string): boolean {\n for (const character of text) {\n const code = character.codePointAt(0) ?? 0;\n if ((code >= 0 && code <= 8) || code === 11 || code === 12 || (code >= 14 && code <= 31) || code === 127) {\n return true;\n }\n }\n return false;\n}\n\nexport function validateLlmsBytes(bytes: Uint8Array): string {\n if (bytes.byteLength === 0) throw new Error('llms.txt is empty.');\n if (bytes.byteLength > MAX_LLMS_BYTES) throw new Error(`llms.txt exceeds ${MAX_LLMS_BYTES} bytes.`);\n\n let text: string;\n try {\n text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch {\n throw new Error('llms.txt is not valid UTF-8.');\n }\n if (text.startsWith('\\uFEFF')) text = text.slice(1);\n if (containsUnsafeControl(text)) throw new Error('llms.txt contains unsafe control bytes.');\n\n const firstContentLine = text\n .split(/\\r?\\n/u)\n .find((line) => line.trim().length > 0)\n ?.trim();\n if (!firstContentLine || !/^#\\s+\\S/u.test(firstContentLine)) {\n throw new Error('llms.txt must begin with a Markdown H1 heading.');\n }\n for (const pattern of [\n MARKDOWN_LINK_PATTERN,\n MARKDOWN_REFERENCE_LINK_PATTERN,\n MARKDOWN_AUTOLINK_PATTERN,\n HTML_LINK_PATTERN,\n ]) {\n for (const match of text.matchAll(pattern)) validateRelativeLink(match[1] ?? '');\n }\n return text;\n}\n\nexport function renderHelpSkillWrapper(descriptor: PoHelpSkillDescriptor, index: ResolvedHelpIndex): string {\n const name = JSON.stringify(descriptor.name);\n const description = JSON.stringify(descriptor.description);\n const indexPath = JSON.stringify(index.filePath);\n const referenceBase = JSON.stringify(index.referenceBase);\n return `---\\nname: ${name}\\ndescription: ${description}\\n---\\n\\n# Package Help\\n\\nRead the validated package Help index at ${indexPath}.\\nResolve relative links in that index against ${referenceBase}.\\nOpen only the linked documents relevant to the current request, as needed; do not recursively load the whole reference set.\\n`;\n}\n","import {\n PO_HELP_MAX_DIAGNOSTIC_LENGTH,\n PO_HELP_MAX_DIAGNOSTICS,\n PO_HELP_MAX_SKILLS,\n type PoHelpContribution,\n type PoHelpDiagnostic,\n type PoHelpSkill,\n} from '@agimon-ai/po-core/help';\n\nimport type {\n HelpActivationDependencies,\n HelpActivationService,\n HelpRuntimeState,\n ResolvedHelpIndex,\n} from '../../types/help';\nimport { MAX_AGGREGATE_LLMS_BYTES } from '../llmsContent';\n\nconst MAX_RESOLUTION_CONCURRENCY = 4;\nconst FAILURE_MESSAGE = 'No package Help source could be activated.';\nconst CANCELLATION_MESSAGE = 'Help activation was cancelled.';\n\ninterface LoadedSource {\n contribution: PoHelpContribution;\n index: ResolvedHelpIndex;\n skills: readonly PoHelpSkill[];\n}\n\ninterface SourceOutcome {\n source: string;\n loaded?: LoadedSource;\n error?: unknown;\n}\n\nexport class HelpActivationError extends Error {\n constructor(message = FAILURE_MESSAGE) {\n super(message);\n this.name = 'HelpActivationError';\n }\n}\n\nfunction cloneContribution(contribution: PoHelpContribution): PoHelpContribution {\n return {\n source: contribution.source,\n moduleUrl: contribution.moduleUrl,\n skills: contribution.skills.map((skill) => ({ ...skill })),\n };\n}\n\nfunction cloneState(state: HelpRuntimeState): HelpRuntimeState {\n return {\n activation: state.activation,\n skills: state.skills.map((skill) => ({ ...skill })),\n diagnostics: state.diagnostics.map((diagnostic) => ({ ...diagnostic })),\n };\n}\n\nfunction diagnostic(source: string, code: string, error: unknown): PoHelpDiagnostic {\n const raw = error instanceof Error ? error.message : String(error);\n const message = (raw || 'Unknown Help activation failure.').slice(0, PO_HELP_MAX_DIAGNOSTIC_LENGTH);\n return { source, code, message };\n}\n\nfunction contributionFingerprint(contributions: readonly PoHelpContribution[]): string {\n return JSON.stringify(\n contributions.map((contribution) => ({\n source: contribution.source,\n moduleUrl: contribution.moduleUrl,\n skills: contribution.skills,\n })),\n );\n}\n\nexport class DefaultHelpActivationService implements HelpActivationService {\n private readonly dependencies: HelpActivationDependencies;\n private readonly listeners = new Set<(state: HelpRuntimeState) => void>();\n private contributions: PoHelpContribution[] = [];\n private fingerprint = '[]';\n private state: HelpRuntimeState = { activation: 'inactive', skills: [], diagnostics: [] };\n private settledState: HelpRuntimeState = { activation: 'inactive', skills: [], diagnostics: [] };\n private generation = 0;\n private controller: AbortController | undefined;\n private disposed = false;\n\n constructor(dependencies: HelpActivationDependencies) {\n this.dependencies = dependencies;\n }\n\n getState(): HelpRuntimeState {\n return cloneState(this.state);\n }\n\n replaceContributions(contributions: readonly PoHelpContribution[]): void {\n if (this.disposed) return;\n const next = contributions.map(cloneContribution).sort((left, right) => left.source.localeCompare(right.source));\n const fingerprint = contributionFingerprint(next);\n if (fingerprint === this.fingerprint) return;\n const previous = new Map(this.contributions.map((entry) => [entry.source, contributionFingerprint([entry])]));\n const retained = new Set(\n next\n .filter((entry) => previous.get(entry.source) === contributionFingerprint([entry]))\n .map((entry) => entry.source),\n );\n // A refresh may retain unchanged owners, never withdrawn or replaced ones.\n // Prune the rollback snapshot too, so cancellation cannot resurrect them.\n const skills = this.settledState.skills.filter((entry) => retained.has(entry.source));\n const diagnostics = this.settledState.diagnostics.filter((entry) => !entry.source || retained.has(entry.source));\n this.settledState = {\n activation: skills.length === 0 ? 'inactive' : diagnostics.length > 0 ? 'degraded' : 'active',\n skills,\n diagnostics,\n };\n this.contributions = next;\n this.fingerprint = fingerprint;\n if (this.state.activation !== 'inactive') {\n void this.activate().catch((error: unknown) => {\n // Activation failures publish a bounded settled state before rejecting.\n // Only unexpected implementation failures need an out-of-band report.\n if (error instanceof HelpActivationError) return;\n this.dependencies.onBackgroundError(error);\n });\n }\n }\n\n subscribe(listener: (state: HelpRuntimeState) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n private publish(state: HelpRuntimeState): HelpRuntimeState {\n this.state = cloneState(state);\n if (state.activation !== 'activating') this.settledState = cloneState(state);\n this.dependencies.publisher.publish(this.state);\n for (const listener of this.listeners) listener(cloneState(this.state));\n return this.getState();\n }\n\n private async loadSources(signal: AbortSignal): Promise<SourceOutcome[]> {\n const contributions = this.contributions;\n const outcomes: SourceOutcome[] = Array.from({ length: contributions.length });\n let cursor = 0;\n const worker = async (): Promise<void> => {\n while (cursor < contributions.length) {\n const index = cursor;\n cursor += 1;\n const contribution = contributions[index];\n if (!contribution) return;\n if (signal.aborted) throw new HelpActivationError(CANCELLATION_MESSAGE);\n try {\n const resolved = await this.dependencies.resolver.resolve(contribution, signal);\n if (signal.aborted) throw new HelpActivationError(CANCELLATION_MESSAGE);\n const skills = await this.dependencies.materializer.materialize(contribution, resolved, signal);\n outcomes[index] = { source: contribution.source, loaded: { contribution, index: resolved, skills } };\n } catch (error) {\n if (signal.aborted) throw new HelpActivationError(CANCELLATION_MESSAGE);\n outcomes[index] = { source: contribution.source, error };\n }\n }\n };\n const count = Math.min(MAX_RESOLUTION_CONCURRENCY, contributions.length);\n await Promise.all(Array.from({ length: count }, () => worker()));\n return outcomes;\n }\n\n async activate(externalSignal?: AbortSignal): Promise<HelpRuntimeState> {\n if (this.disposed) throw new HelpActivationError('Help runtime is disposed.');\n this.controller?.abort('Help activation generation replaced.');\n const controller = new AbortController();\n this.controller = controller;\n const generation = ++this.generation;\n const abortFromExternal = () => controller.abort(externalSignal?.reason);\n externalSignal?.addEventListener('abort', abortFromExternal, { once: true });\n if (externalSignal?.aborted) abortFromExternal();\n\n const settledState = cloneState(this.settledState);\n this.publish({ activation: 'activating', skills: settledState.skills, diagnostics: settledState.diagnostics });\n try {\n const outcomes = await this.loadSources(controller.signal);\n if (controller.signal.aborted || generation !== this.generation) {\n throw new HelpActivationError(CANCELLATION_MESSAGE);\n }\n\n const diagnostics: PoHelpDiagnostic[] = [];\n const loaded: LoadedSource[] = [];\n let aggregateBytes = 0;\n for (const outcome of outcomes) {\n if (!outcome) continue;\n if (outcome.error || !outcome.loaded) {\n diagnostics.push(diagnostic(outcome.source, 'HELP_SOURCE_FAILED', outcome.error));\n continue;\n }\n if (aggregateBytes + outcome.loaded.index.byteLength > MAX_AGGREGATE_LLMS_BYTES) {\n diagnostics.push(\n diagnostic(outcome.source, 'HELP_AGGREGATE_LIMIT', 'The aggregate llms.txt byte limit was exceeded.'),\n );\n continue;\n }\n aggregateBytes += outcome.loaded.index.byteLength;\n loaded.push(outcome.loaded);\n }\n\n const skills: PoHelpSkill[] = [];\n const names = new Set<string>();\n for (const source of loaded) {\n for (const skill of source.skills) {\n if (skills.length >= PO_HELP_MAX_SKILLS) {\n diagnostics.push(\n diagnostic(source.contribution.source, 'HELP_SKILL_LIMIT', 'The Help skill limit was reached.'),\n );\n break;\n }\n if (names.has(skill.name)) {\n diagnostics.push(\n diagnostic(\n source.contribution.source,\n 'HELP_SKILL_COLLISION',\n `Help skill '${skill.name}' was already provided by an earlier package source.`,\n ),\n );\n continue;\n }\n names.add(skill.name);\n skills.push({ ...skill });\n }\n }\n\n const boundedDiagnostics = diagnostics.slice(0, PO_HELP_MAX_DIAGNOSTICS);\n if (skills.length === 0) {\n this.publish({ activation: 'inactive', skills: [], diagnostics: boundedDiagnostics });\n throw new HelpActivationError();\n }\n return this.publish({\n activation: boundedDiagnostics.length > 0 ? 'degraded' : 'active',\n skills,\n diagnostics: boundedDiagnostics,\n });\n } catch (error) {\n if (generation === this.generation && this.state.activation === 'activating') this.publish(settledState);\n throw error;\n } finally {\n externalSignal?.removeEventListener('abort', abortFromExternal);\n if (this.controller === controller) this.controller = undefined;\n }\n }\n\n deactivate(): HelpRuntimeState {\n this.generation += 1;\n this.controller?.abort('Help deactivated.');\n this.controller = undefined;\n return this.publish({ activation: 'inactive', skills: [], diagnostics: [] });\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.deactivate();\n this.disposed = true;\n this.listeners.clear();\n }\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { PoHelpContribution, PoHelpSkill } from '@agimon-ai/po-core/help';\nimport { poHomeDirectory } from '@agimon-ai/po-core/piSettings';\n\nimport type { HelpPackageIdentity, HelpSkillMaterializer, ResolvedHelpIndex } from '../../types/help';\nimport { renderHelpSkillWrapper } from '../llmsContent';\n\nconst PACKAGE_MANIFEST = 'package.json';\nconst HELP_INDEX_PATH = 'llms.txt';\nconst CACHE_SCHEMA_VERSION = 1;\nconst PRIVATE_FILE_MODE = 0o600;\nconst PRIVATE_DIRECTORY_MODE = 0o700;\nconst COMPLETION_FILE = '.complete';\nconst CACHE_METADATA_FILE = 'metadata.json';\nconst WRAPPER_DIRECTORY = 'wrappers';\nconst SKILL_FILE = 'SKILL.md';\nconst EXACT_SEMVER_PATTERN =\n /^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/u;\nconst NPM_PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._~-]*\\/)?[a-z0-9][a-z0-9._~-]*$/u;\n\ninterface CacheMetadata {\n schemaVersion: typeof CACHE_SCHEMA_VERSION;\n source: string;\n version: string;\n path: typeof HELP_INDEX_PATH;\n integrity: string;\n digest: string;\n referenceBase: string;\n}\n\nexport interface CachedHelpIndex {\n bytes: Uint8Array;\n filePath: string;\n integrity: string;\n digest: string;\n referenceBase: string;\n}\n\nfunction assertNotAborted(signal: AbortSignal): void {\n if (signal.aborted) throw new Error('Help activation was cancelled.');\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isContained(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));\n}\n\nfunction readManifest(filePath: string): Record<string, unknown> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')) as unknown;\n } catch (error) {\n throw new Error(\n `Cannot read Help package manifest at ${filePath}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (!isRecord(parsed)) throw new Error(`Help package manifest at ${filePath} must contain an object.`);\n return parsed;\n}\n\nexport function resolveHelpPackageIdentity(moduleUrl: string, expectedSource: string): HelpPackageIdentity {\n if (!NPM_PACKAGE_NAME_PATTERN.test(expectedSource)) {\n throw new Error(`Help source '${expectedSource}' must be a valid lowercase npm package name.`);\n }\n let modulePath: string;\n try {\n const url = new URL(moduleUrl);\n if (url.protocol !== 'file:') throw new Error(`Help module URL must use file:, received ${url.protocol}`);\n modulePath = fs.realpathSync(fileURLToPath(url));\n } catch (error) {\n throw new Error(\n `Invalid Help contributor module URL '${moduleUrl}': ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (!fs.lstatSync(modulePath).isFile())\n throw new Error(`Help contributor module is not a regular file: ${modulePath}`);\n\n let directory = path.dirname(modulePath);\n while (true) {\n const manifestPath = path.join(directory, PACKAGE_MANIFEST);\n if (fs.existsSync(manifestPath)) {\n const manifest = readManifest(manifestPath);\n const source = manifest.name;\n const version = manifest.version;\n if (source !== expectedSource) {\n throw new Error(`Help source '${expectedSource}' does not match nearest package '${String(source)}'.`);\n }\n if (typeof version !== 'string' || !EXACT_SEMVER_PATTERN.test(version)) {\n throw new Error(`Help package '${expectedSource}' must declare an exact semantic version.`);\n }\n const packageRoot = fs.realpathSync(directory);\n if (!isContained(packageRoot, modulePath))\n throw new Error('Help contributor module escapes its resolved package root.');\n return { source: expectedSource, version, packageRoot, modulePath };\n }\n const parent = path.dirname(directory);\n if (parent === directory) break;\n directory = parent;\n }\n throw new Error(`Cannot find a package manifest for Help contributor ${modulePath}.`);\n}\n\nexport function defaultHelpCacheRoot(homeDirectory = os.homedir()): string {\n return path.join(poHomeDirectory(homeDirectory), 'llms-cache');\n}\n\nexport function sha256Hex(bytes: Uint8Array | string): string {\n return createHash('sha256').update(bytes).digest('hex');\n}\n\nfunction parseCacheMetadata(value: unknown, identity: HelpPackageIdentity): CacheMetadata | undefined {\n if (!isRecord(value)) return undefined;\n if (\n value.schemaVersion !== CACHE_SCHEMA_VERSION ||\n value.source !== identity.source ||\n value.version !== identity.version ||\n value.path !== HELP_INDEX_PATH ||\n typeof value.integrity !== 'string' ||\n typeof value.digest !== 'string' ||\n typeof value.referenceBase !== 'string'\n ) {\n return undefined;\n }\n return value as unknown as CacheMetadata;\n}\n\nfunction regularFile(filePath: string): boolean {\n try {\n const metadata = fs.lstatSync(filePath);\n return metadata.isFile() && !metadata.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nexport class HelpIndexCache {\n readonly root: string;\n\n constructor(root = defaultHelpCacheRoot()) {\n this.root = root;\n }\n\n entryDirectory(identity: HelpPackageIdentity): string {\n const key = sha256Hex(`${identity.source}\\0${identity.version}\\0${HELP_INDEX_PATH}`);\n return path.join(this.root, key);\n }\n\n discard(identity: HelpPackageIdentity): void {\n fs.rmSync(this.entryDirectory(identity), { recursive: true, force: true });\n }\n\n read(identity: HelpPackageIdentity): CachedHelpIndex | undefined {\n const directory = this.entryDirectory(identity);\n const completionPath = path.join(directory, COMPLETION_FILE);\n const indexPath = path.join(directory, HELP_INDEX_PATH);\n const metadataPath = path.join(directory, CACHE_METADATA_FILE);\n if (!regularFile(completionPath) || !regularFile(indexPath) || !regularFile(metadataPath)) return undefined;\n try {\n const metadata = parseCacheMetadata(JSON.parse(fs.readFileSync(metadataPath, 'utf8')) as unknown, identity);\n if (!metadata) return undefined;\n const bytes = fs.readFileSync(indexPath);\n if (sha256Hex(bytes) !== metadata.digest) return undefined;\n if (fs.readFileSync(completionPath, 'utf8').trim() !== metadata.digest) return undefined;\n return {\n bytes,\n filePath: indexPath,\n integrity: metadata.integrity,\n digest: metadata.digest,\n referenceBase: metadata.referenceBase,\n };\n } catch {\n return undefined;\n }\n }\n\n publish(\n identity: HelpPackageIdentity,\n bytes: Uint8Array,\n integrity: string,\n referenceBase: string,\n signal: AbortSignal,\n ): CachedHelpIndex {\n assertNotAborted(signal);\n const existing = this.read(identity);\n if (existing) return existing;\n const directory = this.entryDirectory(identity);\n fs.mkdirSync(this.root, { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n if (fs.existsSync(directory)) fs.rmSync(directory, { recursive: true, force: true });\n const temporary = `${directory}.${process.pid}.${randomUUID()}.tmp`;\n const digest = sha256Hex(bytes);\n const metadata: CacheMetadata = {\n schemaVersion: CACHE_SCHEMA_VERSION,\n source: identity.source,\n version: identity.version,\n path: HELP_INDEX_PATH,\n integrity,\n digest,\n referenceBase,\n };\n try {\n fs.mkdirSync(temporary, { mode: PRIVATE_DIRECTORY_MODE });\n fs.writeFileSync(path.join(temporary, HELP_INDEX_PATH), bytes, { mode: PRIVATE_FILE_MODE });\n fs.writeFileSync(path.join(temporary, CACHE_METADATA_FILE), `${JSON.stringify(metadata, null, 2)}\\n`, {\n mode: PRIVATE_FILE_MODE,\n });\n assertNotAborted(signal);\n fs.writeFileSync(path.join(temporary, COMPLETION_FILE), `${digest}\\n`, { mode: PRIVATE_FILE_MODE });\n try {\n fs.renameSync(temporary, directory);\n } catch (error) {\n const winner = this.read(identity);\n if (winner) return winner;\n throw error;\n }\n return {\n bytes: Uint8Array.from(bytes),\n filePath: path.join(directory, HELP_INDEX_PATH),\n integrity,\n digest,\n referenceBase,\n };\n } finally {\n fs.rmSync(temporary, { recursive: true, force: true });\n }\n }\n}\n\nexport class DefaultHelpSkillMaterializer implements HelpSkillMaterializer {\n constructor(private readonly cacheRoot = defaultHelpCacheRoot()) {}\n\n async materialize(\n contribution: PoHelpContribution,\n index: ResolvedHelpIndex,\n signal: AbortSignal,\n ): Promise<readonly PoHelpSkill[]> {\n const skills: PoHelpSkill[] = [];\n for (const descriptor of contribution.skills) {\n assertNotAborted(signal);\n const key = sha256Hex(\n `${index.identity.source}\\0${index.identity.version}\\0${descriptor.name}\\0${descriptor.description}\\0${index.digest}`,\n );\n const directory = path.join(this.cacheRoot, WRAPPER_DIRECTORY, key);\n const filePath = path.join(directory, SKILL_FILE);\n const content = renderHelpSkillWrapper(descriptor, index);\n if (!regularFile(filePath) || fs.readFileSync(filePath, 'utf8') !== content) {\n fs.mkdirSync(path.dirname(directory), { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n if (fs.existsSync(directory)) fs.rmSync(directory, { recursive: true, force: true });\n const temporary = `${directory}.${process.pid}.${randomUUID()}.tmp`;\n try {\n fs.mkdirSync(temporary, { mode: PRIVATE_DIRECTORY_MODE });\n fs.writeFileSync(path.join(temporary, SKILL_FILE), content, { mode: PRIVATE_FILE_MODE });\n assertNotAborted(signal);\n try {\n fs.renameSync(temporary, directory);\n } catch (error) {\n if (!regularFile(filePath) || fs.readFileSync(filePath, 'utf8') !== content) throw error;\n }\n } finally {\n fs.rmSync(temporary, { recursive: true, force: true });\n }\n }\n skills.push({\n source: contribution.source,\n name: descriptor.name,\n description: descriptor.description,\n filePath,\n baseDir: directory,\n });\n }\n return skills;\n }\n}\n","import { createHash } from 'node:crypto';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { PoHelpContribution } from '@agimon-ai/po-core/help';\n\nimport type { HelpFetch, HelpFetchResponse, HelpIndexResolver, ResolvedHelpIndex } from '../../types/help';\nimport { HelpIndexCache, resolveHelpPackageIdentity, sha256Hex } from '../helpStorage';\nimport { MAX_LLMS_BYTES, validateLlmsBytes } from '../llmsContent';\n\nconst HELP_INDEX_PATH = 'llms.txt';\nconst UNPKG_ORIGIN = 'https://unpkg.com';\nconst DEFAULT_FETCH_TIMEOUT_MS = 5_000;\nconst MAX_METADATA_BYTES = 512 * 1024;\nconst MAX_REDIRECTS = 3;\nconst SRI_PATTERN = /^sha256-([A-Za-z0-9+/]+={0,2})$/u;\n\ninterface UnpkgMetadataFile {\n path: string;\n size?: number;\n integrity: string;\n}\n\nexport interface DefaultHelpIndexResolverOptions {\n cache?: HelpIndexCache;\n fetch?: HelpFetch;\n timeoutMs?: number;\n}\n\nfunction defaultFetch(input: string, init: { signal: AbortSignal; redirect: 'manual' }): Promise<HelpFetchResponse> {\n return fetch(input, init) as unknown as Promise<HelpFetchResponse>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isRegularFile(filePath: string): boolean {\n try {\n const metadata = fs.lstatSync(filePath);\n return metadata.isFile() && !metadata.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nfunction unpkgPackagePath(source: string, version: string): string {\n const encoded = source\n .split('/')\n .map((segment) =>\n segment.startsWith('@') ? `@${encodeURIComponent(segment.slice(1))}` : encodeURIComponent(segment),\n )\n .join('/');\n return `${encoded}@${encodeURIComponent(version)}`;\n}\n\nfunction exactUnpkgBase(source: string, version: string): string {\n return `${UNPKG_ORIGIN}/${unpkgPackagePath(source, version)}/`;\n}\n\nfunction contentLength(response: HelpFetchResponse): number | undefined {\n const raw = response.headers.get('content-length');\n if (!raw) return undefined;\n const parsed = Number.parseInt(raw, 10);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\nfunction timeoutSignal(parent: AbortSignal, timeoutMs: number): { signal: AbortSignal; dispose(): void } {\n const controller = new AbortController();\n const abort = () => controller.abort(parent.reason);\n parent.addEventListener('abort', abort, { once: true });\n const timer = setTimeout(() => controller.abort(new Error('Help download timed out.')), timeoutMs);\n if (parent.aborted) abort();\n return {\n signal: controller.signal,\n dispose() {\n clearTimeout(timer);\n parent.removeEventListener('abort', abort);\n },\n };\n}\n\nasync function fetchExact(fetcher: HelpFetch, initialUrl: string, signal: AbortSignal): Promise<HelpFetchResponse> {\n let url = initialUrl;\n const expected = new URL(initialUrl);\n for (let redirect = 0; redirect <= MAX_REDIRECTS; redirect += 1) {\n const response = await fetcher(url, { signal, redirect: 'manual' });\n if (response.status < 300 || response.status >= 400) return response;\n const location = response.headers.get('location');\n if (!location) throw new Error(`Unpkg redirected ${url} without a location.`);\n const next = new URL(location, url);\n if (next.origin !== UNPKG_ORIGIN || next.pathname !== expected.pathname || next.search !== expected.search) {\n throw new Error(`Unpkg redirect escaped the exact package/version path: ${next.href}`);\n }\n url = next.href;\n }\n throw new Error(`Unpkg exceeded ${MAX_REDIRECTS} redirects.`);\n}\n\nfunction parseMetadata(text: string): UnpkgMetadataFile {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text) as unknown;\n } catch {\n throw new Error('Unpkg metadata is not valid JSON.');\n }\n if (!isRecord(parsed) || !Array.isArray(parsed.files)) throw new Error('Unpkg metadata has no files list.');\n const match = parsed.files.find((entry) => isRecord(entry) && entry.path === `/${HELP_INDEX_PATH}`);\n if (!isRecord(match) || typeof match.integrity !== 'string') {\n throw new Error(`Unpkg package does not publish /${HELP_INDEX_PATH}.`);\n }\n const size = typeof match.size === 'number' ? match.size : undefined;\n if (size !== undefined && (!Number.isSafeInteger(size) || size < 0 || size > MAX_LLMS_BYTES)) {\n throw new Error(`Unpkg /${HELP_INDEX_PATH} exceeds the Help size limit.`);\n }\n if (!SRI_PATTERN.test(match.integrity)) throw new Error('Unpkg llms.txt metadata does not contain SHA-256 SRI.');\n return { path: match.path as string, ...(size === undefined ? {} : { size }), integrity: match.integrity };\n}\n\nfunction verifySri(bytes: Uint8Array, integrity: string): void {\n const expected = SRI_PATTERN.exec(integrity)?.[1];\n if (!expected) throw new Error('Invalid llms.txt SRI metadata.');\n const actual = createHash('sha256').update(bytes).digest('base64');\n if (actual !== expected) throw new Error('Downloaded llms.txt failed SRI verification.');\n}\n\nexport class DefaultHelpIndexResolver implements HelpIndexResolver {\n private readonly cache: HelpIndexCache;\n private readonly fetcher: HelpFetch;\n private readonly timeoutMs: number;\n\n constructor(options: DefaultHelpIndexResolverOptions = {}) {\n this.cache = options.cache ?? new HelpIndexCache();\n this.fetcher = options.fetch ?? defaultFetch;\n this.timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;\n }\n\n async resolve(contribution: PoHelpContribution, signal: AbortSignal): Promise<ResolvedHelpIndex> {\n if (signal.aborted) throw new Error('Help activation was cancelled.');\n const identity = resolveHelpPackageIdentity(contribution.moduleUrl, contribution.source);\n const localPath = path.join(identity.packageRoot, HELP_INDEX_PATH);\n if (fs.existsSync(localPath)) {\n if (!isRegularFile(localPath)) throw new Error(`Bundled ${HELP_INDEX_PATH} must be a regular file.`);\n const bytes = fs.readFileSync(localPath);\n validateLlmsBytes(bytes);\n return {\n identity,\n location: 'local',\n filePath: localPath,\n referenceBase: identity.packageRoot,\n byteLength: bytes.byteLength,\n digest: sha256Hex(bytes),\n };\n }\n\n const cached = this.cache.read(identity);\n if (cached) {\n try {\n validateLlmsBytes(cached.bytes);\n return {\n identity,\n location: 'cache',\n filePath: cached.filePath,\n referenceBase: cached.referenceBase,\n byteLength: cached.bytes.byteLength,\n digest: cached.digest,\n };\n } catch {\n this.cache.discard(identity);\n }\n }\n\n const timed = timeoutSignal(signal, this.timeoutMs);\n try {\n const referenceBase = exactUnpkgBase(identity.source, identity.version);\n const metadataResponse = await fetchExact(this.fetcher, `${referenceBase}?meta`, timed.signal);\n const metadataLength = contentLength(metadataResponse);\n if (metadataLength !== undefined && metadataLength > MAX_METADATA_BYTES) {\n throw new Error('Unpkg metadata exceeds the Help metadata size limit.');\n }\n if (!metadataResponse.ok) throw new Error(`Unpkg metadata request failed with HTTP ${metadataResponse.status}.`);\n const metadataText = await metadataResponse.text();\n if (Buffer.byteLength(metadataText, 'utf8') > MAX_METADATA_BYTES) {\n throw new Error('Unpkg metadata exceeds the Help metadata size limit.');\n }\n const metadata = parseMetadata(metadataText);\n const indexResponse = await fetchExact(this.fetcher, `${referenceBase}${HELP_INDEX_PATH}`, timed.signal);\n const indexLength = contentLength(indexResponse);\n if (indexLength !== undefined && indexLength > MAX_LLMS_BYTES) {\n throw new Error(`Downloaded ${HELP_INDEX_PATH} exceeds ${MAX_LLMS_BYTES} bytes.`);\n }\n if (!indexResponse.ok) throw new Error(`Unpkg llms.txt request failed with HTTP ${indexResponse.status}.`);\n const bytes = new Uint8Array(await indexResponse.arrayBuffer());\n validateLlmsBytes(bytes);\n verifySri(bytes, metadata.integrity);\n const published = this.cache.publish(identity, bytes, metadata.integrity, referenceBase, timed.signal);\n return {\n identity,\n location: 'remote',\n filePath: published.filePath,\n referenceBase: published.referenceBase,\n byteLength: published.bytes.byteLength,\n digest: published.digest,\n };\n } finally {\n timed.dispose();\n }\n }\n}\n","import type { PoHelpContribution, PoHelpService } from '@agimon-ai/po-core/help';\n\nimport type { HelpFetch } from '../../types/help';\nimport { DefaultHelpActivationService } from '../helpActivation';\nimport { DefaultHelpSkillMaterializer, defaultHelpCacheRoot, HelpIndexCache } from '../helpStorage';\nimport { DefaultHelpIndexResolver } from '../llmsResolver';\n\nexport interface HelpRuntimeOptions {\n cacheRoot?: string;\n fetch?: HelpFetch;\n timeoutMs?: number;\n onBackgroundError?(error: unknown): void;\n}\n\nexport interface HelpRuntimeComposition {\n activation: DefaultHelpActivationService;\n dispose(): void;\n}\n\nfunction reportAsync(error: unknown): void {\n queueMicrotask(() => {\n throw error instanceof Error ? error : new Error(String(error));\n });\n}\n\nexport function createHelpRuntime(service: PoHelpService, options: HelpRuntimeOptions = {}): HelpRuntimeComposition {\n const cacheRoot = options.cacheRoot ?? defaultHelpCacheRoot();\n const cache = new HelpIndexCache(cacheRoot);\n const activation = new DefaultHelpActivationService({\n resolver: new DefaultHelpIndexResolver({ cache, fetch: options.fetch, timeoutMs: options.timeoutMs }),\n materializer: new DefaultHelpSkillMaterializer(cacheRoot),\n publisher: { publish: (snapshot) => service.publish(snapshot) },\n onBackgroundError(error) {\n if (options.onBackgroundError) options.onBackgroundError(error);\n else reportAsync(error);\n },\n });\n const synchronize = (contributions: readonly PoHelpContribution[]): void => {\n activation.replaceContributions(contributions);\n };\n const unsubscribe = service.subscribeContributions((contributions) => synchronize(contributions));\n synchronize(service.listContributions());\n let disposed = false;\n return {\n activation,\n dispose() {\n if (disposed) return;\n disposed = true;\n unsubscribe();\n activation.dispose();\n },\n };\n}\n"],"mappings":";;;;;;;;AAIA,MAAa,iBAAiB;AAG9B,MAAM,wBAAwB;AAC9B,MAAM,kCAAkC;AACxC,MAAM,4BAA4B;AAClC,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;AAC3B,MAAM,+BAA+B;AACrC,MAAM,wCAAwB,IAAI,IAAI;CAAC;CAAS;CAAU;AAAS,CAAC;AAEpE,SAAS,eAAe,QAAoC;CAC1D,IAAI,CAAC,mBAAmB,KAAK,MAAM,GAAG,OAAO,KAAA;CAC7C,OAAO,OAAO,MAAM,GAAG,OAAO,QAAQ,GAAG,IAAI,CAAC,CAAC,CAAC,YAAY;AAC9D;AAEA,S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D,kBAAkB,OAAO;GACvB,IAAI,QAAQ,mBAAmB,QAAQ,kBAAkB,KAAK;QACzD,YAAY,KAAK;EACxB;CACF,CAAC;CACD,MAAM,eAAe,kBAAuD;EAC1E,WAAW,qBAAqB,aAAa;CAC/C;CACA,MAAM,cAAc,QAAQ,wBAAwB,kBAAkB,YAAY,aAAa,CAAC;CAChG,YAAY,QAAQ,kBAAkB,CAAC;CACvC,IAAI,WAAW;CACf,OAAO;EACL;EACA,UAAU;GACR,IAAI,UAAU;GACd,WAAW;GACX,YAAY;GACZ,WAAW,QAAQ;EACrB;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["HELP_INDEX_PATH","isRecord","fs"],"sources":["../src/services/llmsContent/index.ts","../src/services/helpActivation/index.ts","../src/services/helpStorage/index.ts","../src/services/llmsResolver/index.ts","../src/services/helpRuntime/index.ts"],"sourcesContent":["import type { PoHelpSkillDescriptor } from '@agimon-ai/po-core/help';\n\nimport type { ResolvedHelpIndex } from '../../types/help';\n\nexport const MAX_LLMS_BYTES = 1024 * 1024;\nexport const MAX_AGGREGATE_LLMS_BYTES = 4 * MAX_LLMS_BYTES;\n\nconst MARKDOWN_LINK_PATTERN = /!?\\[[^\\]]*\\]\\(\\s*<?([^\\s)>]+)>?(?:\\s+[^)]*)?\\)/gu;\nconst MARKDOWN_REFERENCE_LINK_PATTERN = /^\\s{0,3}\\[[^\\]\\r\\n]+\\]:\\s*<?([^\\s>]+)>?/gmu;\nconst MARKDOWN_AUTOLINK_PATTERN = /<((?:\\.{0,2}\\/|[A-Za-z][A-Za-z0-9+.-]*:)[^<>\\s]+)>/gu;\nconst HTML_LINK_PATTERN = /\\b(?:href|src)\\s*=\\s*[\"']([^\"']+)[\"']/giu;\nconst URI_SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:/iu;\nconst NESTED_PATH_ENCODING_PATTERN = /%(?:25|2e|2f|3a|5c)/iu;\nconst SAFE_EXTERNAL_SCHEMES = new Set(['http:', 'https:', 'mailto:']);\n\nfunction externalScheme(target: string): string | undefined {\n if (!URI_SCHEME_PATTERN.test(target)) return undefined;\n return target.slice(0, target.indexOf(':') + 1).toLowerCase();\n}\n\nfunction decodeRelativeTarget(rawTarget: string): string {\n let decoded = rawTarget;\n try {\n for (let pass = 0; pass < 2; pass += 1) {\n const next = decodeURIComponent(decoded);\n if (next === decoded) break;\n decoded = next;\n }\n } catch {\n throw new Error(`llms.txt contains an invalid encoded link '${rawTarget}'.`);\n }\n if (NESTED_PATH_ENCODING_PATTERN.test(decoded)) {\n throw new Error(`llms.txt contains an unsafe nested encoding in link '${rawTarget}'.`);\n }\n return decoded;\n}\n\nfunction validateRelativeLink(rawTarget: string): void {\n if (!rawTarget || rawTarget.startsWith('#')) return;\n const rawScheme = externalScheme(rawTarget);\n if (rawScheme) {\n if (!SAFE_EXTERNAL_SCHEMES.has(rawScheme)) {\n throw new Error(`llms.txt contains unsupported link scheme '${rawScheme}'.`);\n }\n return;\n }\n\n const decoded = decodeRelativeTarget(rawTarget);\n const decodedScheme = externalScheme(decoded);\n if (decodedScheme) {\n if (!SAFE_EXTERNAL_SCHEMES.has(decodedScheme)) {\n throw new Error(`llms.txt contains unsupported link scheme '${decodedScheme}'.`);\n }\n return;\n }\n const withoutSuffix = decoded.split(/[?#]/u, 1)[0]?.replaceAll('\\\\', '/') ?? '';\n if (withoutSuffix.startsWith('/') || withoutSuffix.split('/').some((segment) => segment === '..')) {\n throw new Error(`llms.txt link '${rawTarget}' escapes the package root.`);\n }\n}\n\nfunction containsUnsafeControl(text: string): boolean {\n for (const character of text) {\n const code = character.codePointAt(0) ?? 0;\n if ((code >= 0 && code <= 8) || code === 11 || code === 12 || (code >= 14 && code <= 31) || code === 127) {\n return true;\n }\n }\n return false;\n}\n\nexport function validateLlmsBytes(bytes: Uint8Array): string {\n if (bytes.byteLength === 0) throw new Error('llms.txt is empty.');\n if (bytes.byteLength > MAX_LLMS_BYTES) throw new Error(`llms.txt exceeds ${MAX_LLMS_BYTES} bytes.`);\n\n let text: string;\n try {\n text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n } catch {\n throw new Error('llms.txt is not valid UTF-8.');\n }\n if (text.startsWith('\\uFEFF')) text = text.slice(1);\n if (containsUnsafeControl(text)) throw new Error('llms.txt contains unsafe control bytes.');\n\n const firstContentLine = text\n .split(/\\r?\\n/u)\n .find((line) => line.trim().length > 0)\n ?.trim();\n if (!firstContentLine || !/^#\\s+\\S/u.test(firstContentLine)) {\n throw new Error('llms.txt must begin with a Markdown H1 heading.');\n }\n for (const pattern of [\n MARKDOWN_LINK_PATTERN,\n MARKDOWN_REFERENCE_LINK_PATTERN,\n MARKDOWN_AUTOLINK_PATTERN,\n HTML_LINK_PATTERN,\n ]) {\n for (const match of text.matchAll(pattern)) validateRelativeLink(match[1] ?? '');\n }\n return text;\n}\n\nexport function renderHelpSkillWrapper(descriptor: PoHelpSkillDescriptor, index: ResolvedHelpIndex): string {\n const name = JSON.stringify(descriptor.name);\n const description = JSON.stringify(descriptor.description);\n const indexPath = JSON.stringify(index.filePath);\n const referenceBase = JSON.stringify(index.referenceBase);\n return `---\\nname: ${name}\\ndescription: ${description}\\n---\\n\\n# Package Help\\n\\nRead the validated package Help index at ${indexPath}.\\nResolve relative links in that index against ${referenceBase}.\\nOpen only the linked documents relevant to the current request, as needed; do not recursively load the whole reference set.\\n`;\n}\n","import {\n PO_HELP_MAX_DIAGNOSTIC_LENGTH,\n PO_HELP_MAX_DIAGNOSTICS,\n PO_HELP_MAX_SKILLS,\n type PoHelpContribution,\n type PoHelpDiagnostic,\n type PoHelpSkill,\n} from '@agimon-ai/po-core/help';\n\nimport type {\n HelpActivationDependencies,\n HelpActivationService,\n HelpRuntimeState,\n ResolvedHelpIndex,\n} from '../../types/help';\nimport { MAX_AGGREGATE_LLMS_BYTES } from '../llmsContent';\n\nconst MAX_RESOLUTION_CONCURRENCY = 4;\nconst FAILURE_MESSAGE = 'No package Help source could be activated.';\nconst CANCELLATION_MESSAGE = 'Help activation was cancelled.';\n\ninterface LoadedSource {\n contribution: PoHelpContribution;\n index: ResolvedHelpIndex;\n skills: readonly PoHelpSkill[];\n}\n\ninterface SourceOutcome {\n source: string;\n loaded?: LoadedSource;\n error?: unknown;\n}\n\nexport class HelpActivationError extends Error {\n constructor(message = FAILURE_MESSAGE) {\n super(message);\n this.name = 'HelpActivationError';\n }\n}\n\nfunction cloneContribution(contribution: PoHelpContribution): PoHelpContribution {\n return {\n source: contribution.source,\n moduleUrl: contribution.moduleUrl,\n skills: contribution.skills.map((skill) => ({ ...skill })),\n };\n}\n\nfunction cloneState(state: HelpRuntimeState): HelpRuntimeState {\n return {\n activation: state.activation,\n skills: state.skills.map((skill) => ({ ...skill })),\n diagnostics: state.diagnostics.map((diagnostic) => ({ ...diagnostic })),\n };\n}\n\nfunction diagnostic(source: string, code: string, error: unknown): PoHelpDiagnostic {\n const raw = error instanceof Error ? error.message : String(error);\n const message = (raw || 'Unknown Help activation failure.').slice(0, PO_HELP_MAX_DIAGNOSTIC_LENGTH);\n return { source, code, message };\n}\n\nfunction contributionFingerprint(contributions: readonly PoHelpContribution[]): string {\n return JSON.stringify(\n contributions.map((contribution) => ({\n source: contribution.source,\n moduleUrl: contribution.moduleUrl,\n skills: contribution.skills,\n })),\n );\n}\n\nexport class DefaultHelpActivationService implements HelpActivationService {\n private readonly dependencies: HelpActivationDependencies;\n private readonly listeners = new Set<(state: HelpRuntimeState) => void>();\n private contributions: PoHelpContribution[] = [];\n private fingerprint = '[]';\n private state: HelpRuntimeState = { activation: 'inactive', skills: [], diagnostics: [] };\n private settledState: HelpRuntimeState = { activation: 'inactive', skills: [], diagnostics: [] };\n private generation = 0;\n private controller: AbortController | undefined;\n private disposed = false;\n\n constructor(dependencies: HelpActivationDependencies) {\n this.dependencies = dependencies;\n }\n\n getState(): HelpRuntimeState {\n return cloneState(this.state);\n }\n\n replaceContributions(contributions: readonly PoHelpContribution[]): void {\n if (this.disposed) return;\n const next = contributions.map(cloneContribution).sort((left, right) => left.source.localeCompare(right.source));\n const fingerprint = contributionFingerprint(next);\n if (fingerprint === this.fingerprint) return;\n const previous = new Map(this.contributions.map((entry) => [entry.source, contributionFingerprint([entry])]));\n const retained = new Set(\n next\n .filter((entry) => previous.get(entry.source) === contributionFingerprint([entry]))\n .map((entry) => entry.source),\n );\n // A refresh may retain unchanged owners, never withdrawn or replaced ones.\n // Prune the rollback snapshot too, so cancellation cannot resurrect them.\n const skills = this.settledState.skills.filter((entry) => retained.has(entry.source));\n const diagnostics = this.settledState.diagnostics.filter((entry) => !entry.source || retained.has(entry.source));\n this.settledState = {\n activation: skills.length === 0 ? 'inactive' : diagnostics.length > 0 ? 'degraded' : 'active',\n skills,\n diagnostics,\n };\n this.contributions = next;\n this.fingerprint = fingerprint;\n if (this.state.activation !== 'inactive') {\n void this.activate().catch((error: unknown) => {\n // Activation failures publish a bounded settled state before rejecting.\n // Only unexpected implementation failures need an out-of-band report.\n if (error instanceof HelpActivationError) return;\n this.dependencies.onBackgroundError(error);\n });\n }\n }\n\n subscribe(listener: (state: HelpRuntimeState) => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n private publish(state: HelpRuntimeState): HelpRuntimeState {\n this.state = cloneState(state);\n if (state.activation !== 'activating') this.settledState = cloneState(state);\n this.dependencies.publisher.publish(this.state);\n for (const listener of this.listeners) listener(cloneState(this.state));\n return this.getState();\n }\n\n private async loadSources(signal: AbortSignal): Promise<SourceOutcome[]> {\n const contributions = this.contributions;\n const outcomes: SourceOutcome[] = Array.from({ length: contributions.length });\n let cursor = 0;\n const worker = async (): Promise<void> => {\n while (cursor < contributions.length) {\n const index = cursor;\n cursor += 1;\n const contribution = contributions[index];\n if (!contribution) return;\n if (signal.aborted) throw new HelpActivationError(CANCELLATION_MESSAGE);\n try {\n const resolved = await this.dependencies.resolver.resolve(contribution, signal);\n if (signal.aborted) throw new HelpActivationError(CANCELLATION_MESSAGE);\n const skills = await this.dependencies.materializer.materialize(contribution, resolved, signal);\n outcomes[index] = { source: contribution.source, loaded: { contribution, index: resolved, skills } };\n } catch (error) {\n if (signal.aborted) throw new HelpActivationError(CANCELLATION_MESSAGE);\n outcomes[index] = { source: contribution.source, error };\n }\n }\n };\n const count = Math.min(MAX_RESOLUTION_CONCURRENCY, contributions.length);\n await Promise.all(Array.from({ length: count }, () => worker()));\n return outcomes;\n }\n\n async activate(externalSignal?: AbortSignal): Promise<HelpRuntimeState> {\n if (this.disposed) throw new HelpActivationError('Help runtime is disposed.');\n this.controller?.abort('Help activation generation replaced.');\n const controller = new AbortController();\n this.controller = controller;\n const generation = ++this.generation;\n const abortFromExternal = () => controller.abort(externalSignal?.reason);\n externalSignal?.addEventListener('abort', abortFromExternal, { once: true });\n if (externalSignal?.aborted) abortFromExternal();\n\n const settledState = cloneState(this.settledState);\n this.publish({ activation: 'activating', skills: settledState.skills, diagnostics: settledState.diagnostics });\n try {\n const outcomes = await this.loadSources(controller.signal);\n if (controller.signal.aborted || generation !== this.generation) {\n throw new HelpActivationError(CANCELLATION_MESSAGE);\n }\n\n const diagnostics: PoHelpDiagnostic[] = [];\n const loaded: LoadedSource[] = [];\n let aggregateBytes = 0;\n for (const outcome of outcomes) {\n if (!outcome) continue;\n if (outcome.error || !outcome.loaded) {\n diagnostics.push(diagnostic(outcome.source, 'HELP_SOURCE_FAILED', outcome.error));\n continue;\n }\n if (aggregateBytes + outcome.loaded.index.byteLength > MAX_AGGREGATE_LLMS_BYTES) {\n diagnostics.push(\n diagnostic(outcome.source, 'HELP_AGGREGATE_LIMIT', 'The aggregate llms.txt byte limit was exceeded.'),\n );\n continue;\n }\n aggregateBytes += outcome.loaded.index.byteLength;\n loaded.push(outcome.loaded);\n }\n\n const skills: PoHelpSkill[] = [];\n const names = new Set<string>();\n for (const source of loaded) {\n for (const skill of source.skills) {\n if (skills.length >= PO_HELP_MAX_SKILLS) {\n diagnostics.push(\n diagnostic(source.contribution.source, 'HELP_SKILL_LIMIT', 'The Help skill limit was reached.'),\n );\n break;\n }\n if (names.has(skill.name)) {\n diagnostics.push(\n diagnostic(\n source.contribution.source,\n 'HELP_SKILL_COLLISION',\n `Help skill '${skill.name}' was already provided by an earlier package source.`,\n ),\n );\n continue;\n }\n names.add(skill.name);\n skills.push({ ...skill });\n }\n }\n\n const boundedDiagnostics = diagnostics.slice(0, PO_HELP_MAX_DIAGNOSTICS);\n if (skills.length === 0) {\n this.publish({ activation: 'inactive', skills: [], diagnostics: boundedDiagnostics });\n throw new HelpActivationError();\n }\n return this.publish({\n activation: boundedDiagnostics.length > 0 ? 'degraded' : 'active',\n skills,\n diagnostics: boundedDiagnostics,\n });\n } catch (error) {\n if (generation === this.generation && this.state.activation === 'activating') this.publish(settledState);\n throw error;\n } finally {\n externalSignal?.removeEventListener('abort', abortFromExternal);\n if (this.controller === controller) this.controller = undefined;\n }\n }\n\n deactivate(): HelpRuntimeState {\n this.generation += 1;\n this.controller?.abort('Help deactivated.');\n this.controller = undefined;\n return this.publish({ activation: 'inactive', skills: [], diagnostics: [] });\n }\n\n dispose(): void {\n if (this.disposed) return;\n this.deactivate();\n this.disposed = true;\n this.listeners.clear();\n }\n}\n","import { createHash, randomUUID } from 'node:crypto';\nimport fsPromises from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport type { PoHelpContribution, PoHelpSkill } from '@agimon-ai/po-core/help';\nimport { poHomeDirectory } from '@agimon-ai/po-core/piSettings';\n\nimport type { HelpPackageIdentity, HelpSkillMaterializer, ResolvedHelpIndex } from '../../types/help';\nimport { renderHelpSkillWrapper } from '../llmsContent';\n\nconst PACKAGE_MANIFEST = 'package.json';\nconst HELP_INDEX_PATH = 'llms.txt';\nconst CACHE_SCHEMA_VERSION = 1;\nconst PRIVATE_FILE_MODE = 0o600;\nconst PRIVATE_DIRECTORY_MODE = 0o700;\nconst COMPLETION_FILE = '.complete';\nconst CACHE_METADATA_FILE = 'metadata.json';\nconst WRAPPER_DIRECTORY = 'wrappers';\nconst SKILL_FILE = 'SKILL.md';\nconst EXACT_SEMVER_PATTERN =\n /^(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)(?:-[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?(?:\\+[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*)?$/u;\nconst NPM_PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9][a-z0-9._~-]*\\/)?[a-z0-9][a-z0-9._~-]*$/u;\n\ninterface CacheMetadata {\n schemaVersion: typeof CACHE_SCHEMA_VERSION;\n source: string;\n version: string;\n path: typeof HELP_INDEX_PATH;\n integrity: string;\n digest: string;\n referenceBase: string;\n}\n\nexport interface CachedHelpIndex {\n bytes: Uint8Array;\n filePath: string;\n integrity: string;\n digest: string;\n referenceBase: string;\n}\n\nfunction assertNotAborted(signal: AbortSignal): void {\n if (signal.aborted) throw new Error('Help activation was cancelled.');\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isContained(root: string, candidate: string): boolean {\n const relative = path.relative(root, candidate);\n return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative));\n}\n\nasync function readManifest(filePath: string): Promise<Record<string, unknown> | undefined> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(await fsPromises.readFile(filePath, 'utf8')) as unknown;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw new Error(\n `Cannot read Help package manifest at ${filePath}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (!isRecord(parsed)) throw new Error(`Help package manifest at ${filePath} must contain an object.`);\n return parsed;\n}\n\nexport async function resolveHelpPackageIdentity(\n moduleUrl: string,\n expectedSource: string,\n): Promise<HelpPackageIdentity> {\n if (!NPM_PACKAGE_NAME_PATTERN.test(expectedSource)) {\n throw new Error(`Help source '${expectedSource}' must be a valid lowercase npm package name.`);\n }\n let modulePath: string;\n try {\n const url = new URL(moduleUrl);\n if (url.protocol !== 'file:') throw new Error(`Help module URL must use file:, received ${url.protocol}`);\n modulePath = await fsPromises.realpath(fileURLToPath(url));\n } catch (error) {\n throw new Error(\n `Invalid Help contributor module URL '${moduleUrl}': ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n if (!(await fsPromises.lstat(modulePath)).isFile())\n throw new Error(`Help contributor module is not a regular file: ${modulePath}`);\n\n let directory = path.dirname(modulePath);\n while (true) {\n const manifestPath = path.join(directory, PACKAGE_MANIFEST);\n const manifest = await readManifest(manifestPath);\n if (manifest !== undefined) {\n const source = manifest.name;\n const version = manifest.version;\n if (source !== expectedSource) {\n throw new Error(`Help source '${expectedSource}' does not match nearest package '${String(source)}'.`);\n }\n if (typeof version !== 'string' || !EXACT_SEMVER_PATTERN.test(version)) {\n throw new Error(`Help package '${expectedSource}' must declare an exact semantic version.`);\n }\n const packageRoot = await fsPromises.realpath(directory);\n if (!isContained(packageRoot, modulePath))\n throw new Error('Help contributor module escapes its resolved package root.');\n return { source: expectedSource, version, packageRoot, modulePath };\n }\n const parent = path.dirname(directory);\n if (parent === directory) break;\n directory = parent;\n }\n throw new Error(`Cannot find a package manifest for Help contributor ${modulePath}.`);\n}\n\nexport function defaultHelpCacheRoot(homeDirectory = os.homedir()): string {\n return path.join(poHomeDirectory(homeDirectory), 'llms-cache');\n}\n\nexport function sha256Hex(bytes: Uint8Array | string): string {\n return createHash('sha256').update(bytes).digest('hex');\n}\n\nfunction parseCacheMetadata(value: unknown, identity: HelpPackageIdentity): CacheMetadata | undefined {\n if (!isRecord(value)) return undefined;\n if (\n value.schemaVersion !== CACHE_SCHEMA_VERSION ||\n value.source !== identity.source ||\n value.version !== identity.version ||\n value.path !== HELP_INDEX_PATH ||\n typeof value.integrity !== 'string' ||\n typeof value.digest !== 'string' ||\n typeof value.referenceBase !== 'string'\n ) {\n return undefined;\n }\n return value as unknown as CacheMetadata;\n}\n\n// Share mutation ordering across cache instances targeting the same entry.\nconst cacheMutations = new Map<string, Promise<void>>();\n\nasync function mutateCacheEntry<T>(directory: string, operation: () => Promise<T>): Promise<T> {\n const key = path.resolve(directory);\n const previous = cacheMutations.get(key) ?? Promise.resolve();\n const result = previous.then(operation);\n const settled = result.then(\n () => {},\n () => {},\n );\n cacheMutations.set(key, settled);\n try {\n return await result;\n } finally {\n if (cacheMutations.get(key) === settled) cacheMutations.delete(key);\n }\n}\n\nasync function regularFile(filePath: string): Promise<boolean> {\n try {\n const metadata = await fsPromises.lstat(filePath);\n return metadata.isFile() && !metadata.isSymbolicLink();\n } catch {\n return false;\n }\n}\n\nexport class HelpIndexCache {\n readonly root: string;\n\n constructor(root = defaultHelpCacheRoot()) {\n this.root = root;\n }\n\n entryDirectory(identity: HelpPackageIdentity): string {\n const key = sha256Hex(`${identity.source}\\0${identity.version}\\0${HELP_INDEX_PATH}`);\n return path.join(this.root, key);\n }\n\n async discard(identity: HelpPackageIdentity): Promise<void> {\n const directory = this.entryDirectory(identity);\n await mutateCacheEntry(directory, () => fsPromises.rm(directory, { recursive: true, force: true }));\n }\n\n async read(identity: HelpPackageIdentity): Promise<CachedHelpIndex | undefined> {\n const directory = this.entryDirectory(identity);\n const completionPath = path.join(directory, COMPLETION_FILE);\n const indexPath = path.join(directory, HELP_INDEX_PATH);\n const metadataPath = path.join(directory, CACHE_METADATA_FILE);\n if (!(await regularFile(completionPath)) || !(await regularFile(indexPath)) || !(await regularFile(metadataPath)))\n return undefined;\n try {\n const metadata = parseCacheMetadata(\n JSON.parse(await fsPromises.readFile(metadataPath, 'utf8')) as unknown,\n identity,\n );\n if (!metadata) return undefined;\n const bytes = await fsPromises.readFile(indexPath);\n if (sha256Hex(bytes) !== metadata.digest) return undefined;\n if ((await fsPromises.readFile(completionPath, 'utf8')).trim() !== metadata.digest) return undefined;\n return {\n bytes,\n filePath: indexPath,\n integrity: metadata.integrity,\n digest: metadata.digest,\n referenceBase: metadata.referenceBase,\n };\n } catch {\n return undefined;\n }\n }\n\n async publish(\n identity: HelpPackageIdentity,\n bytes: Uint8Array,\n integrity: string,\n referenceBase: string,\n signal: AbortSignal,\n ): Promise<CachedHelpIndex> {\n const directory = this.entryDirectory(identity);\n return mutateCacheEntry(directory, async () => {\n assertNotAborted(signal);\n const existing = await this.read(identity);\n if (existing) return existing;\n await fsPromises.mkdir(this.root, { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n await fsPromises.rm(directory, { recursive: true, force: true });\n const temporary = `${directory}.${process.pid}.${randomUUID()}.tmp`;\n const digest = sha256Hex(bytes);\n const metadata: CacheMetadata = {\n schemaVersion: CACHE_SCHEMA_VERSION,\n source: identity.source,\n version: identity.version,\n path: HELP_INDEX_PATH,\n integrity,\n digest,\n referenceBase,\n };\n try {\n await fsPromises.mkdir(temporary, { mode: PRIVATE_DIRECTORY_MODE });\n await fsPromises.writeFile(path.join(temporary, HELP_INDEX_PATH), bytes, { mode: PRIVATE_FILE_MODE });\n await fsPromises.writeFile(\n path.join(temporary, CACHE_METADATA_FILE),\n `${JSON.stringify(metadata, null, 2)}\\n`,\n {\n mode: PRIVATE_FILE_MODE,\n },\n );\n assertNotAborted(signal);\n await fsPromises.writeFile(path.join(temporary, COMPLETION_FILE), `${digest}\\n`, { mode: PRIVATE_FILE_MODE });\n try {\n await fsPromises.rename(temporary, directory);\n } catch (error) {\n const winner = await this.read(identity);\n if (winner) return winner;\n throw error;\n }\n return {\n bytes: Uint8Array.from(bytes),\n filePath: path.join(directory, HELP_INDEX_PATH),\n integrity,\n digest,\n referenceBase,\n };\n } finally {\n await fsPromises.rm(temporary, { recursive: true, force: true });\n }\n });\n }\n}\n\nexport class DefaultHelpSkillMaterializer implements HelpSkillMaterializer {\n constructor(private readonly cacheRoot = defaultHelpCacheRoot()) {}\n\n async materialize(\n contribution: PoHelpContribution,\n index: ResolvedHelpIndex,\n signal: AbortSignal,\n ): Promise<readonly PoHelpSkill[]> {\n const skills: PoHelpSkill[] = [];\n for (const descriptor of contribution.skills) {\n assertNotAborted(signal);\n const key = sha256Hex(\n `${index.identity.source}\\0${index.identity.version}\\0${descriptor.name}\\0${descriptor.description}\\0${index.digest}`,\n );\n const directory = path.join(this.cacheRoot, WRAPPER_DIRECTORY, key);\n const filePath = path.join(directory, SKILL_FILE);\n const content = renderHelpSkillWrapper(descriptor, index);\n const matches = async (): Promise<boolean> => {\n try {\n const metadata = await fsPromises.lstat(filePath);\n return (\n metadata.isFile() && !metadata.isSymbolicLink() && (await fsPromises.readFile(filePath, 'utf8')) === content\n );\n } catch {\n return false;\n }\n };\n if (!(await matches())) {\n await fsPromises.mkdir(path.dirname(directory), { mode: PRIVATE_DIRECTORY_MODE, recursive: true });\n await fsPromises.rm(directory, { recursive: true, force: true });\n const temporary = `${directory}.${process.pid}.${randomUUID()}.tmp`;\n try {\n await fsPromises.mkdir(temporary, { mode: PRIVATE_DIRECTORY_MODE });\n await fsPromises.writeFile(path.join(temporary, SKILL_FILE), content, { mode: PRIVATE_FILE_MODE });\n assertNotAborted(signal);\n try {\n await fsPromises.rename(temporary, directory);\n } catch (error) {\n if (!(await matches())) throw error;\n }\n } finally {\n await fsPromises.rm(temporary, { recursive: true, force: true });\n }\n }\n skills.push({\n source: contribution.source,\n name: descriptor.name,\n description: descriptor.description,\n filePath,\n baseDir: directory,\n });\n }\n return skills;\n }\n}\n","import { createHash } from 'node:crypto';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type { PoHelpContribution } from '@agimon-ai/po-core/help';\n\nimport type { HelpFetch, HelpFetchResponse, HelpIndexResolver, ResolvedHelpIndex } from '../../types/help';\nimport { HelpIndexCache, resolveHelpPackageIdentity, sha256Hex } from '../helpStorage';\nimport { MAX_LLMS_BYTES, validateLlmsBytes } from '../llmsContent';\n\nconst HELP_INDEX_PATH = 'llms.txt';\nconst UNPKG_ORIGIN = 'https://unpkg.com';\nconst DEFAULT_FETCH_TIMEOUT_MS = 5_000;\nconst MAX_METADATA_BYTES = 512 * 1024;\nconst MAX_REDIRECTS = 3;\nconst SRI_PATTERN = /^sha256-([A-Za-z0-9+/]+={0,2})$/u;\n\ninterface UnpkgMetadataFile {\n path: string;\n size?: number;\n integrity: string;\n}\n\nexport interface DefaultHelpIndexResolverOptions {\n cache?: HelpIndexCache;\n fetch?: HelpFetch;\n timeoutMs?: number;\n}\n\nfunction defaultFetch(input: string, init: { signal: AbortSignal; redirect: 'manual' }): Promise<HelpFetchResponse> {\n return fetch(input, init) as unknown as Promise<HelpFetchResponse>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nasync function isRegularFile(filePath: string): Promise<boolean | undefined> {\n try {\n const metadata = await fs.lstat(filePath);\n return metadata.isFile() && !metadata.isSymbolicLink();\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined;\n throw error;\n }\n}\n\nfunction unpkgPackagePath(source: string, version: string): string {\n const encoded = source\n .split('/')\n .map((segment) =>\n segment.startsWith('@') ? `@${encodeURIComponent(segment.slice(1))}` : encodeURIComponent(segment),\n )\n .join('/');\n return `${encoded}@${encodeURIComponent(version)}`;\n}\n\nfunction exactUnpkgBase(source: string, version: string): string {\n return `${UNPKG_ORIGIN}/${unpkgPackagePath(source, version)}/`;\n}\n\nfunction contentLength(response: HelpFetchResponse): number | undefined {\n const raw = response.headers.get('content-length');\n if (!raw) return undefined;\n const parsed = Number.parseInt(raw, 10);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\nfunction timeoutSignal(parent: AbortSignal, timeoutMs: number): { signal: AbortSignal; dispose(): void } {\n const controller = new AbortController();\n const abort = () => controller.abort(parent.reason);\n parent.addEventListener('abort', abort, { once: true });\n const timer = setTimeout(() => controller.abort(new Error('Help download timed out.')), timeoutMs);\n if (parent.aborted) abort();\n return {\n signal: controller.signal,\n dispose() {\n clearTimeout(timer);\n parent.removeEventListener('abort', abort);\n },\n };\n}\n\nasync function fetchExact(fetcher: HelpFetch, initialUrl: string, signal: AbortSignal): Promise<HelpFetchResponse> {\n let url = initialUrl;\n const expected = new URL(initialUrl);\n for (let redirect = 0; redirect <= MAX_REDIRECTS; redirect += 1) {\n const response = await fetcher(url, { signal, redirect: 'manual' });\n if (response.status < 300 || response.status >= 400) return response;\n const location = response.headers.get('location');\n if (!location) throw new Error(`Unpkg redirected ${url} without a location.`);\n const next = new URL(location, url);\n if (next.origin !== UNPKG_ORIGIN || next.pathname !== expected.pathname || next.search !== expected.search) {\n throw new Error(`Unpkg redirect escaped the exact package/version path: ${next.href}`);\n }\n url = next.href;\n }\n throw new Error(`Unpkg exceeded ${MAX_REDIRECTS} redirects.`);\n}\n\nfunction parseMetadata(text: string): UnpkgMetadataFile {\n let parsed: unknown;\n try {\n parsed = JSON.parse(text) as unknown;\n } catch {\n throw new Error('Unpkg metadata is not valid JSON.');\n }\n if (!isRecord(parsed) || !Array.isArray(parsed.files)) throw new Error('Unpkg metadata has no files list.');\n const match = parsed.files.find((entry) => isRecord(entry) && entry.path === `/${HELP_INDEX_PATH}`);\n if (!isRecord(match) || typeof match.integrity !== 'string') {\n throw new Error(`Unpkg package does not publish /${HELP_INDEX_PATH}.`);\n }\n const size = typeof match.size === 'number' ? match.size : undefined;\n if (size !== undefined && (!Number.isSafeInteger(size) || size < 0 || size > MAX_LLMS_BYTES)) {\n throw new Error(`Unpkg /${HELP_INDEX_PATH} exceeds the Help size limit.`);\n }\n if (!SRI_PATTERN.test(match.integrity)) throw new Error('Unpkg llms.txt metadata does not contain SHA-256 SRI.');\n return { path: match.path as string, ...(size === undefined ? {} : { size }), integrity: match.integrity };\n}\n\nfunction verifySri(bytes: Uint8Array, integrity: string): void {\n const expected = SRI_PATTERN.exec(integrity)?.[1];\n if (!expected) throw new Error('Invalid llms.txt SRI metadata.');\n const actual = createHash('sha256').update(bytes).digest('base64');\n if (actual !== expected) throw new Error('Downloaded llms.txt failed SRI verification.');\n}\n\nexport class DefaultHelpIndexResolver implements HelpIndexResolver {\n private readonly cache: HelpIndexCache;\n private readonly fetcher: HelpFetch;\n private readonly timeoutMs: number;\n\n constructor(options: DefaultHelpIndexResolverOptions = {}) {\n this.cache = options.cache ?? new HelpIndexCache();\n this.fetcher = options.fetch ?? defaultFetch;\n this.timeoutMs = options.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;\n }\n\n async resolve(contribution: PoHelpContribution, signal: AbortSignal): Promise<ResolvedHelpIndex> {\n if (signal.aborted) throw new Error('Help activation was cancelled.');\n const identity = await resolveHelpPackageIdentity(contribution.moduleUrl, contribution.source);\n const localPath = path.join(identity.packageRoot, HELP_INDEX_PATH);\n const regular = await isRegularFile(localPath);\n if (regular !== undefined) {\n if (!regular) throw new Error(`Bundled ${HELP_INDEX_PATH} must be a regular file.`);\n const bytes = await fs.readFile(localPath);\n validateLlmsBytes(bytes);\n return {\n identity,\n location: 'local',\n filePath: localPath,\n referenceBase: identity.packageRoot,\n byteLength: bytes.byteLength,\n digest: sha256Hex(bytes),\n };\n }\n\n const cached = await this.cache.read(identity);\n if (cached) {\n try {\n validateLlmsBytes(cached.bytes);\n return {\n identity,\n location: 'cache',\n filePath: cached.filePath,\n referenceBase: cached.referenceBase,\n byteLength: cached.bytes.byteLength,\n digest: cached.digest,\n };\n } catch {\n await this.cache.discard(identity);\n }\n }\n\n const timed = timeoutSignal(signal, this.timeoutMs);\n try {\n const referenceBase = exactUnpkgBase(identity.source, identity.version);\n const metadataResponse = await fetchExact(this.fetcher, `${referenceBase}?meta`, timed.signal);\n const metadataLength = contentLength(metadataResponse);\n if (metadataLength !== undefined && metadataLength > MAX_METADATA_BYTES) {\n throw new Error('Unpkg metadata exceeds the Help metadata size limit.');\n }\n if (!metadataResponse.ok) throw new Error(`Unpkg metadata request failed with HTTP ${metadataResponse.status}.`);\n const metadataText = await metadataResponse.text();\n if (Buffer.byteLength(metadataText, 'utf8') > MAX_METADATA_BYTES) {\n throw new Error('Unpkg metadata exceeds the Help metadata size limit.');\n }\n const metadata = parseMetadata(metadataText);\n const indexResponse = await fetchExact(this.fetcher, `${referenceBase}${HELP_INDEX_PATH}`, timed.signal);\n const indexLength = contentLength(indexResponse);\n if (indexLength !== undefined && indexLength > MAX_LLMS_BYTES) {\n throw new Error(`Downloaded ${HELP_INDEX_PATH} exceeds ${MAX_LLMS_BYTES} bytes.`);\n }\n if (!indexResponse.ok) throw new Error(`Unpkg llms.txt request failed with HTTP ${indexResponse.status}.`);\n const bytes = new Uint8Array(await indexResponse.arrayBuffer());\n validateLlmsBytes(bytes);\n verifySri(bytes, metadata.integrity);\n const published = await this.cache.publish(identity, bytes, metadata.integrity, referenceBase, timed.signal);\n return {\n identity,\n location: 'remote',\n filePath: published.filePath,\n referenceBase: published.referenceBase,\n byteLength: published.bytes.byteLength,\n digest: published.digest,\n };\n } finally {\n timed.dispose();\n }\n }\n}\n","import type { PoHelpContribution, PoHelpService } from '@agimon-ai/po-core/help';\n\nimport type { HelpFetch } from '../../types/help';\nimport { DefaultHelpActivationService } from '../helpActivation';\nimport { DefaultHelpSkillMaterializer, defaultHelpCacheRoot, HelpIndexCache } from '../helpStorage';\nimport { DefaultHelpIndexResolver } from '../llmsResolver';\n\nexport interface HelpRuntimeOptions {\n cacheRoot?: string;\n fetch?: HelpFetch;\n timeoutMs?: number;\n onBackgroundError?(error: unknown): void;\n}\n\nexport interface HelpRuntimeComposition {\n activation: DefaultHelpActivationService;\n dispose(): void;\n}\n\nfunction reportAsync(error: unknown): void {\n queueMicrotask(() => {\n throw error instanceof Error ? error : new Error(String(error));\n });\n}\n\nexport function createHelpRuntime(service: PoHelpService, options: HelpRuntimeOptions = {}): HelpRuntimeComposition {\n const cacheRoot = options.cacheRoot ?? defaultHelpCacheRoot();\n const cache = new HelpIndexCache(cacheRoot);\n const activation = new DefaultHelpActivationService({\n resolver: new DefaultHelpIndexResolver({ cache, fetch: options.fetch, timeoutMs: options.timeoutMs }),\n materializer: new DefaultHelpSkillMaterializer(cacheRoot),\n publisher: { publish: (snapshot) => service.publish(snapshot) },\n onBackgroundError(error) {\n if (options.onBackgroundError) options.onBackgroundError(error);\n else reportAsync(error);\n },\n });\n const synchronize = (contributions: readonly PoHelpContribution[]): void => {\n activation.replaceContributions(contributions);\n };\n const unsubscribe = service.subscribeContributions((contributions) => synchronize(contributions));\n synchronize(service.listContributions());\n let disposed = false;\n return {\n activation,\n dispose() {\n if (disposed) return;\n disposed = true;\n unsubscribe();\n activation.dispose();\n },\n };\n}\n"],"mappings":";;;;;;;;AAIA,MAAa,iBAAiB;AAG9B,MAAM,wBAAwB;AAC9B,MAAM,kCAAkC;AACxC,MAAM,4BAA4B;AAClC,MAAM,oBAAoB;AAC1B,MAAM,qBAAqB;AAC3B,MAAM,+BAA+B;AACrC,MAAM,wCAAwB,IAAI,IAAI;CAAC;CAAS;CAAU;AAAS,CAAC;AAEpE,SAAS,eAAe,QAAoC;CAC1D,IAAI,CAAC,mBAAmB,KAAK,MAAM,GAAG,OAAO,KAAA;CAC7C,OAAO,OAAO,MAAM,GAAG,OAAO,QAAQ,GAAG,IAAI,CAAC,CAAC,CAAC,YAAY;AAC9D;AAEA,SAAS,qBAAqB,WAA2B;CACvD,IAAI,UAAU;CACd,IAAI;EACF,KAAK,IAAI,OAAO,GAAG,OAAO,GAAG,QAAQ,GAAG;GACtC,MAAM,OAAO,mBAAmB,OAAO;GACvC,IAAI,SAAS,SAAS;GACtB,UAAU;EACZ;CACF,QAAQ;EACN,MAAM,IAAI,MAAM,8CAA8C,UAAU,GAAG;CAC7E;CACA,IAAI,6BAA6B,KAAK,OAAO,GAC3C,MAAM,IAAI,MAAM,wDAAwD,UAAU,GAAG;CAEvF,OAAO;AACT;AAEA,SAAS,qBAAqB,WAAyB;CACrD,IAAI,CAAC,aAAa,UAAU,WAAW,GAAG,GAAG;CAC7C,MAAM,YAAY,eAAe,SAAS;CAC1C,IAAI,WAAW;EACb,IAAI,CAAC,sBAAsB,IAAI,SAAS,GACtC,MAAM,IAAI,MAAM,8CAA8C,U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SAAgB,kBAAkB,SAAwB,UAA8B,CAAC,GAA2B;CAClH,MAAM,YAAY,QAAQ,aAAa,qBAAqB;CAE5D,MAAM,aAAa,IAAI,6BAA6B;EAClD,UAAU,IAAI,yBAAyB;GAAE,WAFzB,eAAe,SAEU;GAAO,OAAO,QAAQ;GAAO,WAAW,QAAQ;EAAU,CAAC;EACpG,cAAc,IAAI,6BAA6B,SAAS;EACxD,WAAW,EAAE,UAAU,aAAa,QAAQ,QAAQ,QAAQ,EAAE;EAC9D,kBAAkB,OAAO;GACvB,IAAI,QAAQ,mBAAmB,QAAQ,kBAAkB,KAAK;QACzD,YAAY,KAAK;EACxB;CACF,CAAC;CACD,MAAM,eAAe,kBAAuD;EAC1E,WAAW,qBAAqB,aAAa;CAC/C;CACA,MAAM,cAAc,QAAQ,wBAAwB,kBAAkB,YAAY,aAAa,CAAC;CAChG,YAAY,QAAQ,kBAAkB,CAAC;CACvC,IAAI,WAAW;CACf,OAAO;EACL;EACA,UAAU;GACR,IAAI,UAAU;GACd,WAAW;GACX,YAAY;GACZ,WAAW,QAAQ;EACrB;CACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agimon-ai/po-help",
|
|
3
|
-
"version": "0.0.0-alpha.
|
|
3
|
+
"version": "0.0.0-alpha.46",
|
|
4
4
|
"description": "Activation-gated package guidance and help skills for Po and Pi extensions.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agent-documentation",
|
|
@@ -58,15 +58,15 @@
|
|
|
58
58
|
"access": "public"
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@agimon-ai/po-core": "0.0.0-alpha.
|
|
62
|
-
"@agimon-ai/po-minor-mode": "0.0.0-alpha.
|
|
63
|
-
"@agimon-ai/po-web-components": "0.0.0-alpha.
|
|
61
|
+
"@agimon-ai/po-core": "0.0.0-alpha.46",
|
|
62
|
+
"@agimon-ai/po-minor-mode": "0.0.0-alpha.46",
|
|
63
|
+
"@agimon-ai/po-web-components": "0.0.0-alpha.46",
|
|
64
64
|
"@deepseek-ai/cordis": "4.0.5",
|
|
65
65
|
"typebox": "1.4.2"
|
|
66
66
|
},
|
|
67
67
|
"devDependencies": {
|
|
68
|
-
"@agimon-ai/po-build": "0.0.0-alpha.
|
|
69
|
-
"@agimon-ai/vibe-lint-plugin-po-extension": "0.0.0-alpha.
|
|
68
|
+
"@agimon-ai/po-build": "0.0.0-alpha.46",
|
|
69
|
+
"@agimon-ai/vibe-lint-plugin-po-extension": "0.0.0-alpha.46",
|
|
70
70
|
"@earendil-works/pi-coding-agent": "1.4.0",
|
|
71
71
|
"@types/node": "26.6.5",
|
|
72
72
|
"@types/react": "19.3.0",
|