hoi4-agent-tools 4.10.0 → 4.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/hoi4_agent_tools/core/operation-result.js +51 -11
  3. package/dist/hoi4_agent_tools/core/workspace.js +22 -7
  4. package/dist/hoi4_agent_tools/decision/service.js +13 -1
  5. package/dist/hoi4_agent_tools/impact/service.js +4 -1
  6. package/dist/hoi4_agent_tools/map/gameplay/crossings.js +55 -16
  7. package/dist/hoi4_agent_tools/map/partition-fields.js +14 -0
  8. package/dist/hoi4_agent_tools/map/partition-geography.js +55 -6
  9. package/dist/hoi4_agent_tools/map/partition-provinces.js +105 -24
  10. package/dist/hoi4_agent_tools/map/relief/hydrology.js +9 -0
  11. package/dist/hoi4_agent_tools/map/relief/macro-relief.js +21 -1
  12. package/dist/hoi4_agent_tools/map/relief/painted-relief.js +8 -5
  13. package/dist/hoi4_agent_tools/map/world-provinces.js +36 -19
  14. package/dist/hoi4_agent_tools/mcp/resources/register-modern.js +11 -4
  15. package/dist/hoi4_agent_tools/mcp/resources/register.js +7 -0
  16. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +1 -0
  17. package/dist/hoi4_agent_tools/mcp/tools/analysis.js +12 -0
  18. package/dist/hoi4_agent_tools/mcp/tools/reference.js +12 -3
  19. package/dist/hoi4_agent_tools/package-check/service.js +14 -1
  20. package/dist/hoi4_agent_tools/reference/operations.js +35 -6
  21. package/dist/hoi4_agent_tools/reference/service.js +118 -14
  22. package/dist/hoi4_agent_tools/reference/skill-resource.js +74 -0
  23. package/dist/hoi4_agent_tools/reference/skills.js +278 -0
  24. package/dist/hoi4_agent_tools/schemas/reference.js +34 -2
  25. package/dist/hoi4_agent_tools/schemas/skill.js +72 -0
  26. package/dist/hoi4_agent_tools/version.js +1 -1
  27. package/docs/configuration.md +3 -3
  28. package/docs/map.md +16 -16
  29. package/docs/reference.md +27 -1
  30. package/docs/tools.md +101 -86
  31. package/engine/bin/manifest.json +1 -1
  32. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  33. package/npm-shrinkwrap.json +2 -2
  34. package/package.json +2 -1
  35. package/schemas/configuration.schema.json +1 -1
  36. package/schemas/continuous-focus-palette.schema.json +1 -1
  37. package/schemas/custom-weighted-pool.schema.json +1 -1
  38. package/schemas/decision-inspect-input.schema.json +1 -1
  39. package/schemas/error-log-input.schema.json +1 -1
  40. package/schemas/event-feature-manifest.schema.json +1 -1
  41. package/schemas/focus-plan.schema.json +1 -1
  42. package/schemas/focus-planning-sidecar.schema.json +1 -1
  43. package/schemas/geography-model.schema.json +1 -1
  44. package/schemas/gui-animation-source.schema.json +1 -1
  45. package/schemas/gui-helper.schema.json +1 -1
  46. package/schemas/gui-scenario.schema.json +1 -1
  47. package/schemas/helper-expansion-request.schema.json +1 -1
  48. package/schemas/helper-expansion-summary.schema.json +1 -1
  49. package/schemas/impact-inspect-input.schema.json +1 -1
  50. package/schemas/map-operation.schema.json +1 -1
  51. package/schemas/mechanic-test-input.schema.json +1 -1
  52. package/schemas/mod-index-input.schema.json +1 -1
  53. package/schemas/operation-result.schema.json +1 -1
  54. package/schemas/package-check-input.schema.json +1 -1
  55. package/schemas/package-manifest.schema.json +1 -1
  56. package/schemas/probability-analysis-result.schema.json +1 -1
  57. package/schemas/probability-compare-input.schema.json +1 -1
  58. package/schemas/probability-evaluate-input.schema.json +1 -1
  59. package/schemas/probability-inspect-input.schema.json +1 -1
  60. package/schemas/probability-render-input.schema.json +1 -1
  61. package/schemas/probability-scenario-set.schema.json +1 -1
  62. package/schemas/probability-sequence-input.schema.json +1 -1
  63. package/schemas/probability-simulate-input.schema.json +1 -1
  64. package/schemas/probability-sweep-input.schema.json +1 -1
  65. package/schemas/reference-context-input.schema.json +1 -1
  66. package/schemas/reference-read-input.schema.json +3 -3
  67. package/schemas/reference-search-input.schema.json +1 -1
  68. package/schemas/reference-sheets.schema.json +1 -1
  69. package/schemas/scenario-suite.schema.json +1 -1
  70. package/schemas/scenario-test-input.schema.json +1 -1
  71. package/schemas/script-validate-input.schema.json +1 -1
  72. package/schemas/shared-scenario.schema.json +1 -1
  73. package/schemas/source-lookup-input.schema.json +1 -1
  74. package/server.json +2 -2
@@ -5,6 +5,7 @@ import { globFiles } from '../core/file-glob.js';
5
5
  import { compareCodeUnits, sha256Bytes } from '../core/canonical.js';
6
6
  import { ServiceError } from '../core/result.js';
7
7
  import { isWithin } from '../core/workspace.js';
8
+ import { REFERENCE_HIT_ID_LENGTH, REFERENCE_HIT_REVISION_LENGTH, } from '../schemas/reference.js';
8
9
  import { prepareSource, verifySource, readBoundedFile, } from '../core/scanner.js';
9
10
  import { decodeSource } from '../core/source/encoding.js';
10
11
  import commandPhrases from './command-phrases.json' with { type: 'json' };
@@ -34,9 +35,23 @@ function referenceText(bytes) {
34
35
  }
35
36
  /** The citation fields of a section, without its indexed text or term statistics. */
36
37
  export function publicReferenceSection(section) {
37
- const { lines: _lines, terms: _terms, ...citation } = section;
38
+ const { relativePath: _relativePath, lines: _lines, terms: _terms, ...citation } = section;
38
39
  return citation;
39
40
  }
41
+ /** A section as a search or context hit: short handles, its file under its source's folder. */
42
+ function referenceHit(section) {
43
+ return {
44
+ id: section.id.slice(0, REFERENCE_HIT_ID_LENGTH),
45
+ revision: section.revision.slice(0, REFERENCE_HIT_REVISION_LENGTH),
46
+ source: section.source,
47
+ heading: section.heading,
48
+ ...(section.title === section.heading ? {} : { title: section.title }),
49
+ path: section.relativePath.slice(0, 1024),
50
+ startLine: section.startLine,
51
+ endLine: section.endLine,
52
+ excerpt: section.excerpt,
53
+ };
54
+ }
40
55
  /** An unchanged stamp lets a repeated query reuse the hashed revision without rereading. */
41
56
  function fileStamp(metadata) {
42
57
  return `${metadata.size}:${metadata.mtimeMs}:${metadata.ctimeMs}:${metadata.ino}:${metadata.dev}`;
@@ -61,9 +76,77 @@ function fenceMarker(line) {
61
76
  const marker = match[1];
62
77
  return { character: marker[0], length: marker.length, info: match[2].trim() };
63
78
  }
64
- function sectionize(root, filePath, content, revision) {
65
- const lines = content.replace(/^\uFEFF/u, '').split(/\r?\n/u);
79
+ /** Inline code spans and the text between them, so a comment is never matched inside code. */
80
+ const inlineCode = /(`+)[\s\S]*?\1/gu;
81
+ const inlineComment = /<!--[\s\S]*?-->/gu;
82
+ /**
83
+ * Markdown lines with every HTML comment outside code blanked and every line kept, so a
84
+ * section's line numbers still match the file. A reader never sees a comment, and older
85
+ * kit wiki pages carry `<!-- kit:begin ... -->` maintenance markers that would otherwise
86
+ * open search excerpts. A line that starts a comment hides everything up to the line that
87
+ * closes it, as Markdown does; a comment inside a line is cut out of that line only.
88
+ */
89
+ export function withoutComments(lines) {
90
+ const out = [];
91
+ let fence;
92
+ let comment = false;
93
+ for (const line of lines) {
94
+ if (comment) {
95
+ out.push('');
96
+ comment = !line.includes('-->');
97
+ continue;
98
+ }
99
+ const marker = fenceMarker(line);
100
+ if (fence !== undefined || marker !== undefined) {
101
+ if (fence === undefined)
102
+ fence = marker;
103
+ else if (marker?.character === fence.character &&
104
+ marker.length >= fence.length &&
105
+ marker.info === '')
106
+ fence = undefined;
107
+ out.push(line);
108
+ continue;
109
+ }
110
+ if (/^ {0,3}<!--/u.test(line)) {
111
+ out.push('');
112
+ comment = !line.includes('-->', line.indexOf('<!--') + 4);
113
+ continue;
114
+ }
115
+ if (!line.includes('<!--')) {
116
+ out.push(line);
117
+ continue;
118
+ }
119
+ let cleaned = '';
120
+ let cursor = 0;
121
+ for (const code of line.matchAll(inlineCode)) {
122
+ cleaned += line.slice(cursor, code.index).replace(inlineComment, '') + code[0];
123
+ cursor = code.index + code[0].length;
124
+ }
125
+ out.push((cleaned + line.slice(cursor).replace(inlineComment, '')).trimEnd());
126
+ }
127
+ return out;
128
+ }
129
+ /**
130
+ * Files of the kit's wiki folder that hold no modding text: the license, the attribution
131
+ * list of source pages and the maintenance manifest. The index never serves them, whatever
132
+ * their extension, so a reference answer never spends a reader's context on them.
133
+ */
134
+ const WIKI_META_FILES = new Set([
135
+ 'license.txt',
136
+ 'license.md',
137
+ 'sources.json',
138
+ 'sources.md',
139
+ 'manifest.json',
140
+ 'manifest.md',
141
+ ]);
142
+ function isWikiMetaFile(root, name) {
143
+ return root.kind === 'wiki' && WIKI_META_FILES.has(path.basename(name).toLowerCase());
144
+ }
145
+ function sectionize(root, canonicalRoot, filePath, content, revision) {
146
+ const raw = content.replace(/^\uFEFF/u, '').split(/\r?\n/u);
147
+ const lines = /\.md$/iu.test(filePath) ? withoutComments(raw) : raw;
66
148
  const relative = path.relative(root.root, filePath).replaceAll('\\', '/');
149
+ const relativePath = path.relative(canonicalRoot, filePath).replaceAll('\\', '/');
67
150
  const title = path
68
151
  .basename(filePath)
69
152
  .replace(/\.(md|log)$/iu, '')
@@ -112,6 +195,7 @@ function sectionize(root, filePath, content, revision) {
112
195
  title,
113
196
  heading: heading.slice(0, 512),
114
197
  path: filePath,
198
+ relativePath,
115
199
  startLine: start + 1,
116
200
  endLine: end,
117
201
  excerpt: snippet(sectionLines),
@@ -347,11 +431,11 @@ export class ReferenceService {
347
431
  throw new ServiceError('REFERENCE_ROOT_ESCAPE', 'Reference root resolves outside its configured workspace');
348
432
  }
349
433
  coverage[root.kind].unavailable = false;
350
- const names = await globFiles(root.patterns, {
434
+ const names = (await globFiles(root.patterns, {
351
435
  cwd: canonicalRoot,
352
436
  caseSensitive: false,
353
437
  ...(signal === undefined ? {} : { signal }),
354
- });
438
+ })).filter((name) => !isWikiMetaFile(root, name));
355
439
  names.sort(compareCodeUnits);
356
440
  for (let offset = 0; offset < names.length; offset += 8) {
357
441
  signal?.throwIfAborted();
@@ -421,7 +505,7 @@ export class ReferenceService {
421
505
  revision,
422
506
  bytes: content.length,
423
507
  stamp: fileStamp(source.metadata),
424
- sections: sectionize(root, canonical, referenceText(content), revision),
508
+ sections: sectionize(root, canonicalRoot, canonical, referenceText(content), revision),
425
509
  };
426
510
  }
427
511
  else
@@ -442,11 +526,18 @@ export class ReferenceService {
442
526
  return { sections, coverage, skipped };
443
527
  }
444
528
  async search(workspace, input, signal) {
529
+ return this.searchAs(workspace, input, signal, (section) => this.publicSection(section));
530
+ }
531
+ /** {@link search} with compact hits, as `hoi4.reference_search` returns them. */
532
+ async searchHits(workspace, input, signal) {
533
+ return this.searchAs(workspace, input, signal, referenceHit);
534
+ }
535
+ async searchAs(workspace, input, signal, present) {
445
536
  const inventory = await this.inventory(workspace, signal, input.sources);
446
537
  const { ranked: matches, describe } = this.rank(inventory.sections, input.query, await this.gameText(workspace));
447
538
  const results = matches.slice(0, input.limit).map((match) => {
448
539
  const { section, score, excerpt, matchLine } = describe(match);
449
- return { ...this.publicSection(section), score, excerpt, matchLine };
540
+ return { ...present(section), score, excerpt, matchLine };
450
541
  });
451
542
  const requested = results.length;
452
543
  while (Buffer.byteLength(JSON.stringify(results), 'utf8') > MAX_REFERENCE_METADATA_BYTES &&
@@ -550,10 +641,11 @@ export class ReferenceService {
550
641
  };
551
642
  }
552
643
  async read(workspace, input, signal) {
644
+ // A hit carries a prefix of the section id; a full id is its own prefix.
553
645
  let source = input.source;
554
646
  if (source === undefined) {
555
647
  for (const cached of this.#cache.values()) {
556
- const section = cached.sections.find(({ id }) => id === input.id);
648
+ const section = cached.sections.find(({ id }) => id.startsWith(input.id));
557
649
  if (section !== undefined) {
558
650
  source = section.source;
559
651
  break;
@@ -561,10 +653,13 @@ export class ReferenceService {
561
653
  }
562
654
  }
563
655
  const inventory = await this.inventory(workspace, signal, source === undefined ? undefined : [source]);
564
- const section = inventory.sections.find(({ id }) => id === input.id);
656
+ const matching = inventory.sections.filter(({ id }) => id.startsWith(input.id));
657
+ const section = matching[0];
565
658
  if (section === undefined)
566
659
  throw new ServiceError('REFERENCE_SECTION_UNKNOWN', 'Reference section is not in this workspace');
567
- if (section.revision !== input.revision)
660
+ if (matching.some(({ id }) => id !== section.id))
661
+ throw new ServiceError('REFERENCE_SECTION_AMBIGUOUS', 'More than one section starts with this id; pass the full id');
662
+ if (!section.revision.startsWith(input.revision))
568
663
  throw new ServiceError('REFERENCE_REVISION_STALE', 'Reference source changed; search again', {
569
664
  currentRevision: section.revision,
570
665
  });
@@ -580,6 +675,13 @@ export class ReferenceService {
580
675
  };
581
676
  }
582
677
  async context(workspace, input, signal) {
678
+ return this.contextAs(workspace, input, signal, (section) => this.publicSection(section));
679
+ }
680
+ /** {@link context} with compact hits, as `hoi4.reference_context` returns them. */
681
+ async contextHits(workspace, input, signal) {
682
+ return this.contextAs(workspace, input, signal, referenceHit);
683
+ }
684
+ async contextAs(workspace, input, signal, present) {
583
685
  const inventory = await this.inventory(workspace, signal);
584
686
  const wanted = surfaceNames[input.surface];
585
687
  const ranking = input.question === undefined
@@ -622,19 +724,21 @@ export class ReferenceService {
622
724
  });
623
725
  const selected = prioritized.slice(0, input.limit);
624
726
  const requestedCount = selected.length;
625
- while (Buffer.byteLength(JSON.stringify(selected.map((section) => this.publicSection(section))), 'utf8') > MAX_REFERENCE_METADATA_BYTES &&
727
+ while (Buffer.byteLength(JSON.stringify(selected.map((section) => present(section))), 'utf8') >
728
+ MAX_REFERENCE_METADATA_BYTES &&
626
729
  selected.length > 1)
627
730
  selected.pop();
628
- if (Buffer.byteLength(JSON.stringify(selected.map((section) => this.publicSection(section))), 'utf8') > MAX_REFERENCE_METADATA_BYTES)
731
+ if (Buffer.byteLength(JSON.stringify(selected.map((section) => present(section))), 'utf8') >
732
+ MAX_REFERENCE_METADATA_BYTES)
629
733
  throw new ServiceError('REFERENCE_RESPONSE_TOO_LARGE', 'Reference metadata exceeds the bounded reply');
630
734
  return {
631
735
  surface: input.surface,
632
736
  sections: selected.map((section) => {
633
737
  const match = ranked.find((entry) => entry.section.id === section.id);
634
738
  if (match === undefined || ranking === undefined)
635
- return this.publicSection(section);
739
+ return present(section);
636
740
  const { excerpt, matchLine } = ranking.describe(match);
637
- return { ...this.publicSection(section), excerpt, matchLine };
741
+ return { ...present(section), excerpt, matchLine };
638
742
  }),
639
743
  omitted: Math.max(0, prioritized.length - selected.length),
640
744
  limitedByBytes: selected.length < requestedCount,
@@ -0,0 +1,74 @@
1
+ import { requireOperationScope, resolveOperationWorkspaceId, } from '../core/operation-context.js';
2
+ import { ServiceError } from '../core/result.js';
3
+ import { SKILL_NAME_PATTERN } from '../schemas/skill.js';
4
+ import { readSkillText, skillNames } from './skills.js';
5
+ /** The same skill text hoi4.skill serves, as one resource per skill: its SKILL.md. */
6
+ export const skillResourceDefinition = {
7
+ name: 'skill',
8
+ uriTemplate: 'hoi4-agent://workspace/{workspaceId}/skill/{name}',
9
+ title: 'HOI4 modding skill',
10
+ description: "A skill's SKILL.md at the kit version HOI4 Mod Setup pinned for the mod; _meta carries its sha256 and kit revision. An edited file is refused; read it with hoi4.skill and acceptLocalEdits. Use workspace current for the client's mod.",
11
+ mimeType: 'text/markdown',
12
+ };
13
+ const skillUri = (workspaceId, name) => `hoi4-agent://workspace/${encodeURIComponent(workspaceId)}/skill/${name}`;
14
+ /** The current workspace's skills, for resources/list. A mod without skills lists none. */
15
+ export async function listSkillResources(engine, context, signal) {
16
+ requireOperationScope(context, 'hoi4:read');
17
+ try {
18
+ const workspaceId = await resolveOperationWorkspaceId(engine, context, 'current', signal);
19
+ const workspace = engine.resolver.get(workspaceId, context.principal);
20
+ return (await skillNames(workspace, signal)).map((name) => ({
21
+ uri: skillUri('current', name),
22
+ name: `skill:${name}`,
23
+ title: name,
24
+ mimeType: 'text/markdown',
25
+ }));
26
+ }
27
+ catch (error) {
28
+ if (signal?.aborted)
29
+ throw error;
30
+ // No current mod (several configured, none chosen) is an empty list, not a failure.
31
+ return [];
32
+ }
33
+ }
34
+ export async function readSkillResource(engine, uriInput, context, signal) {
35
+ requireOperationScope(context, 'hoi4:read');
36
+ let workspaceId;
37
+ let name;
38
+ try {
39
+ const uri = new URL(uriInput);
40
+ const segments = uri.pathname.split('/');
41
+ if (uri.protocol !== 'hoi4-agent:' ||
42
+ uri.hostname !== 'workspace' ||
43
+ uri.search !== '' ||
44
+ segments.length !== 4 ||
45
+ segments[0] !== '' ||
46
+ segments[2] !== 'skill')
47
+ throw new Error('Invalid skill resource path');
48
+ workspaceId = decodeURIComponent(segments[1]);
49
+ name = segments[3];
50
+ if (!SKILL_NAME_PATTERN.test(name))
51
+ throw new Error('Invalid skill name');
52
+ }
53
+ catch {
54
+ throw new ServiceError('RESOURCE_URI_INVALID', 'Resource URI is invalid');
55
+ }
56
+ const resolved = await resolveOperationWorkspaceId(engine, context, workspaceId, signal);
57
+ const workspace = engine.resolver.get(resolved, context.principal);
58
+ const skill = await readSkillText(workspace, name, 'SKILL.md', signal);
59
+ return {
60
+ contents: [
61
+ {
62
+ uri: uriInput,
63
+ mimeType: 'text/markdown',
64
+ text: skill.text,
65
+ _meta: {
66
+ sha256: skill.sha256,
67
+ state: skill.state,
68
+ kitRevision: skill.kit?.revision ?? null,
69
+ kitRelease: skill.kit?.release ?? null,
70
+ },
71
+ },
72
+ ],
73
+ };
74
+ }
@@ -0,0 +1,278 @@
1
+ import { lstat, readdir, readFile, realpath } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { sha256Bytes } from '../core/canonical.js';
4
+ import { ServiceError } from '../core/result.js';
5
+ import { SKILL_FILE_PATTERN, SKILL_NAME_PATTERN, SKILL_TEXT_BYTES, } from '../schemas/skill.js';
6
+ // Skills are served from the mod, as HOI4 Mod Setup installed them. Its lock records the kit
7
+ // revision and the hash of every installed file, so a file whose bytes differ is reported as
8
+ // edited and not served unless the caller accepts local edits. A mod without a lock gets its
9
+ // installed skills marked unpinned.
10
+ export const SETUP_LOCK_PATH = '.hoi4-mod-setup/install.lock.json';
11
+ const LOCK_BYTES = 8 * 1024 * 1024;
12
+ const SKILL_FILE_BYTES = 4 * 1024 * 1024;
13
+ /** Setup installs one copy per client; the agent-neutral copy wins. */
14
+ const SKILL_ROOTS = ['.agents/skills', '.claude/skills'];
15
+ const FILES_PER_SKILL = 64;
16
+ export async function listSkills(workspace, signal) {
17
+ const inventory = await readInventory(workspace.modRoot, signal);
18
+ const skills = [];
19
+ let drifted = 0;
20
+ for (const [name, files] of [...inventory.skills].sort(([a], [b]) => a.localeCompare(b))) {
21
+ signal?.throwIfAborted();
22
+ const states = await Promise.all(files.map(async (entry) => (await readSkillFile(workspace.modRoot, entry)).state));
23
+ const state = worst(states);
24
+ if (state === 'edited' || state === 'missing')
25
+ drifted += 1;
26
+ const main = files.find(({ file }) => file === 'SKILL.md');
27
+ const description = main === undefined ? '' : await frontmatterDescription(workspace.modRoot, main);
28
+ skills.push({ name, description, files: files.length, state });
29
+ }
30
+ return { kit: inventory.kit, skills: skills.slice(0, 128), drifted };
31
+ }
32
+ export async function loadSkill(workspace, request, signal) {
33
+ const inventory = await readInventory(workspace.modRoot, signal);
34
+ const files = inventory.skills.get(request.name);
35
+ if (files === undefined)
36
+ throw new ServiceError('SKILL_NOT_FOUND', `The mod has no skill named ${request.name}; call hoi4.skill without a name to list them`, { name: request.name });
37
+ const entry = files.find(({ file }) => file === request.file);
38
+ if (entry === undefined)
39
+ throw new ServiceError('SKILL_FILE_NOT_FOUND', `The skill ${request.name} has no file ${request.file}`, { name: request.name, files: files.map(({ file }) => file).slice(0, 32) });
40
+ const read = await readSkillFile(workspace.modRoot, entry);
41
+ if (read.bytes === undefined)
42
+ throw new ServiceError('SKILL_FILE_MISSING', `The Setup lock names ${entry.path}, but the file is not in the mod; rerun HOI4 Mod Setup to restore it`, { path: entry.path });
43
+ if (read.state === 'edited' && !request.acceptLocalEdits)
44
+ throw new ServiceError('SKILL_TEXT_DRIFTED', `${entry.path} differs from the kit revision ${inventory.kit?.revision ?? ''} the mod pins (sha256 ${read.sha256} instead of ${entry.pinnedSha256 ?? ''}); rerun HOI4 Mod Setup to restore it, or pass acceptLocalEdits to read the edited text`, { path: entry.path, sha256: read.sha256, pinnedSha256: entry.pinnedSha256 });
45
+ if (request.offset > read.bytes.length)
46
+ throw new ServiceError('SKILL_OFFSET_INVALID', `offset ${request.offset} is past the end of ${entry.path} (${read.bytes.length} bytes)`);
47
+ const end = pageEnd(read.bytes, request.offset);
48
+ return {
49
+ kit: inventory.kit,
50
+ skill: {
51
+ name: request.name,
52
+ file: entry.file,
53
+ path: entry.path,
54
+ state: read.state,
55
+ sha256: read.sha256,
56
+ pinnedSha256: entry.pinnedSha256,
57
+ bytes: read.bytes.length,
58
+ offset: request.offset,
59
+ nextOffset: end < read.bytes.length ? end : null,
60
+ text: read.bytes.subarray(request.offset, end).toString('utf8'),
61
+ otherFiles: files
62
+ .map(({ file }) => file)
63
+ .filter((file) => file !== entry.file)
64
+ .slice(0, 64),
65
+ },
66
+ drifted: read.state === 'edited' ? 1 : 0,
67
+ };
68
+ }
69
+ /** The whole text of one skill file for a resource read, with the same drift rule. */
70
+ export async function readSkillText(workspace, name, file, signal) {
71
+ const inventory = await readInventory(workspace.modRoot, signal);
72
+ const entry = inventory.skills.get(name)?.find((candidate) => candidate.file === file);
73
+ if (entry === undefined)
74
+ throw new ServiceError('SKILL_NOT_FOUND', `The mod has no skill file ${name}/${file}`);
75
+ const read = await readSkillFile(workspace.modRoot, entry);
76
+ if (read.bytes === undefined)
77
+ throw new ServiceError('SKILL_FILE_MISSING', `${entry.path} is not in the mod`);
78
+ if (read.state === 'edited')
79
+ throw new ServiceError('SKILL_TEXT_DRIFTED', `${entry.path} differs from the kit revision the mod pins; read it with hoi4.skill and acceptLocalEdits`);
80
+ return {
81
+ text: read.bytes.toString('utf8'),
82
+ sha256: read.sha256,
83
+ state: read.state,
84
+ kit: inventory.kit,
85
+ };
86
+ }
87
+ /** Skill names the mod has, for resource listing. */
88
+ export async function skillNames(workspace, signal) {
89
+ return [...(await readInventory(workspace.modRoot, signal)).skills.keys()].sort();
90
+ }
91
+ async function readInventory(modRoot, signal) {
92
+ const lock = await readLock(modRoot);
93
+ signal?.throwIfAborted();
94
+ return lock === undefined ? installedInventory(modRoot, signal) : lockedInventory(lock);
95
+ }
96
+ async function readLock(modRoot) {
97
+ const lockPath = path.join(modRoot, SETUP_LOCK_PATH);
98
+ let bytes;
99
+ try {
100
+ const info = await lstat(lockPath);
101
+ if (!info.isFile())
102
+ return undefined;
103
+ if (info.size > LOCK_BYTES)
104
+ throw new ServiceError('SKILL_LOCK_INVALID', `${SETUP_LOCK_PATH} is larger than 8 MB`);
105
+ bytes = await readFile(lockPath);
106
+ }
107
+ catch (error) {
108
+ if (error.code === 'ENOENT')
109
+ return undefined;
110
+ throw error;
111
+ }
112
+ let parsed;
113
+ try {
114
+ parsed = JSON.parse(bytes.toString('utf8'));
115
+ }
116
+ catch {
117
+ throw new ServiceError('SKILL_LOCK_INVALID', `${SETUP_LOCK_PATH} is not valid JSON`);
118
+ }
119
+ const lock = parsed;
120
+ const source = lock?.source;
121
+ if (lock === null ||
122
+ typeof source?.repository !== 'string' ||
123
+ typeof source.revision !== 'string' ||
124
+ typeof source.manifest_sha256 !== 'string' ||
125
+ !/^[a-f0-9]{64}$/u.test(source.manifest_sha256) ||
126
+ !Array.isArray(lock.files))
127
+ throw new ServiceError('SKILL_LOCK_INVALID', `${SETUP_LOCK_PATH} lacks the source revision, manifest hash or file list`);
128
+ return lock;
129
+ }
130
+ function lockedInventory(lock) {
131
+ const byRoot = new Map();
132
+ for (const raw of lock.files) {
133
+ const entry = raw;
134
+ if (typeof entry?.path !== 'string' ||
135
+ typeof entry.installed_sha256 !== 'string' ||
136
+ !/^[a-f0-9]{64}$/u.test(entry.installed_sha256))
137
+ continue;
138
+ const located = locate(entry.path);
139
+ if (located === undefined)
140
+ continue;
141
+ const skills = byRoot.get(located.root) ?? new Map();
142
+ byRoot.set(located.root, skills);
143
+ const files = skills.get(located.name) ?? [];
144
+ skills.set(located.name, files);
145
+ if (files.length < FILES_PER_SKILL)
146
+ files.push({ file: located.file, path: entry.path, pinnedSha256: entry.installed_sha256 });
147
+ }
148
+ return {
149
+ kit: {
150
+ repository: lock.source.repository.slice(0, 200),
151
+ revision: lock.source.revision.slice(0, 64),
152
+ release: typeof lock.source.release === 'string' ? lock.source.release.slice(0, 64) : null,
153
+ manifestSha256: lock.source.manifest_sha256,
154
+ },
155
+ skills: merged(byRoot),
156
+ };
157
+ }
158
+ async function installedInventory(modRoot, signal) {
159
+ const byRoot = new Map();
160
+ for (const root of SKILL_ROOTS) {
161
+ let names;
162
+ try {
163
+ names = await readdir(path.join(modRoot, root));
164
+ }
165
+ catch {
166
+ continue;
167
+ }
168
+ const skills = new Map();
169
+ byRoot.set(root, skills);
170
+ for (const name of names.filter((candidate) => SKILL_NAME_PATTERN.test(candidate))) {
171
+ signal?.throwIfAborted();
172
+ const files = (await filesBelow(path.join(modRoot, root, name)))
173
+ .filter((file) => SKILL_FILE_PATTERN.test(file))
174
+ .sort((a, b) => (a === 'SKILL.md' ? -1 : b === 'SKILL.md' ? 1 : a.localeCompare(b)))
175
+ .slice(0, FILES_PER_SKILL);
176
+ if (!files.includes('SKILL.md'))
177
+ continue;
178
+ skills.set(name, files.map((file) => ({ file, path: `${root}/${name}/${file}`, pinnedSha256: null })));
179
+ }
180
+ }
181
+ return { kit: null, skills: merged(byRoot) };
182
+ }
183
+ async function filesBelow(directory, prefix = '', depth = 0) {
184
+ if (depth > 3)
185
+ return [];
186
+ let entries;
187
+ try {
188
+ entries = await readdir(directory, { withFileTypes: true });
189
+ }
190
+ catch {
191
+ return [];
192
+ }
193
+ const found = [];
194
+ for (const entry of entries) {
195
+ const relative = `${prefix}${entry.name}`;
196
+ if (entry.isFile())
197
+ found.push(relative);
198
+ else if (entry.isDirectory())
199
+ found.push(...(await filesBelow(path.join(directory, entry.name), `${relative}/`, depth + 1)));
200
+ }
201
+ return found;
202
+ }
203
+ /** Every skill once, taken from the first root in SKILL_ROOTS that has it. */
204
+ function merged(byRoot) {
205
+ const skills = new Map();
206
+ for (const root of SKILL_ROOTS)
207
+ for (const [name, files] of byRoot.get(root) ?? [])
208
+ if (!skills.has(name) && files.some(({ file }) => file === 'SKILL.md'))
209
+ skills.set(name, files);
210
+ return skills;
211
+ }
212
+ function locate(lockPath) {
213
+ for (const root of SKILL_ROOTS) {
214
+ if (!lockPath.startsWith(`${root}/`))
215
+ continue;
216
+ const rest = lockPath.slice(root.length + 1);
217
+ const slash = rest.indexOf('/');
218
+ if (slash < 0)
219
+ return undefined;
220
+ const name = rest.slice(0, slash);
221
+ const file = rest.slice(slash + 1);
222
+ if (SKILL_NAME_PATTERN.test(name) && SKILL_FILE_PATTERN.test(file))
223
+ return { root, name, file };
224
+ }
225
+ return undefined;
226
+ }
227
+ async function readSkillFile(modRoot, entry) {
228
+ const absolute = path.join(modRoot, ...entry.path.split('/'));
229
+ let bytes;
230
+ try {
231
+ // A link could point outside the mod, so the real path must stay inside it.
232
+ const [real, root] = await Promise.all([realpath(absolute), realpath(modRoot)]);
233
+ const relative = path.relative(root, real);
234
+ if (relative.startsWith('..') || path.isAbsolute(relative))
235
+ throw new ServiceError('SKILL_PATH_OUTSIDE_MOD', `${entry.path} resolves outside the mod`);
236
+ const info = await lstat(real);
237
+ if (!info.isFile() || info.size > SKILL_FILE_BYTES)
238
+ return { state: 'missing' };
239
+ bytes = await readFile(real);
240
+ }
241
+ catch (error) {
242
+ if (error instanceof ServiceError)
243
+ throw error;
244
+ return { state: 'missing' };
245
+ }
246
+ const sha256 = sha256Bytes(bytes);
247
+ const state = entry.pinnedSha256 === null ? 'unpinned' : sha256 === entry.pinnedSha256 ? 'pinned' : 'edited';
248
+ return { state, bytes, sha256 };
249
+ }
250
+ async function frontmatterDescription(modRoot, entry) {
251
+ const read = await readSkillFile(modRoot, entry);
252
+ if (read.bytes === undefined)
253
+ return '';
254
+ const head = read.bytes.subarray(0, 4096).toString('utf8');
255
+ const match = /^---\r?\n[\s\S]*?^description:\s*(.+?)\s*$/mu.exec(head);
256
+ const text = (match?.[1] ?? '').replace(/^["']|["']$/gu, '');
257
+ return text.length > 300 ? `${text.slice(0, 297)}...` : text;
258
+ }
259
+ function worst(states) {
260
+ for (const state of ['missing', 'edited', 'unpinned'])
261
+ if (states.includes(state))
262
+ return state;
263
+ return 'pinned';
264
+ }
265
+ /** The end of one page: at most SKILL_TEXT_BYTES, cut after a line break when one fits. */
266
+ function pageEnd(bytes, offset) {
267
+ const limit = offset + SKILL_TEXT_BYTES;
268
+ if (limit >= bytes.length)
269
+ return bytes.length;
270
+ const newline = bytes.lastIndexOf(0x0a, limit - 1);
271
+ if (newline >= offset)
272
+ return newline + 1;
273
+ // No line break in the page: back off to the start of a UTF-8 character.
274
+ let end = limit;
275
+ while (end > offset && (bytes[end] & 0xc0) === 0x80)
276
+ end -= 1;
277
+ return end;
278
+ }
@@ -24,8 +24,10 @@ export const referenceSearchRequestSchema = z
24
24
  export const referenceReadRequestSchema = z
25
25
  .object({
26
26
  workspaceId: workspaceIdSchema,
27
- id: z.string().regex(/^[a-f0-9]{64}$/u),
28
- revision: z.string().regex(/^[a-f0-9]{64}$/u),
27
+ /** A hit's short id, or the full SHA-256 section id. */
28
+ id: z.string().regex(/^[a-f0-9]{16,64}$/u),
29
+ /** A hit's short revision, or the full SHA-256 file revision. */
30
+ revision: z.string().regex(/^[a-f0-9]{12,64}$/u),
29
31
  source: referenceSourceSchema.optional(),
30
32
  startLine: z.number().int().min(1).optional(),
31
33
  startColumn: z.number().int().min(1).optional(),
@@ -151,6 +153,33 @@ export const referenceSearchDataSchema = z
151
153
  skipped: count,
152
154
  })
153
155
  .strict();
156
+ /** Characters of a section id and a file revision that a search or context hit carries. */
157
+ export const REFERENCE_HIT_ID_LENGTH = 16;
158
+ export const REFERENCE_HIT_REVISION_LENGTH = 12;
159
+ /**
160
+ * One search or context hit as a tool returns it. Every session reads many hits, so a hit names
161
+ * its file under its source's folder instead of an absolute path, carries short id and revision
162
+ * prefixes that `hoi4.reference_read` accepts, and leaves out the source's authority line.
163
+ */
164
+ export const referenceHitSchema = z
165
+ .object({
166
+ id: z.string().regex(/^[a-f0-9]{16}$/u),
167
+ revision: z.string().regex(/^[a-f0-9]{12}$/u),
168
+ source: referenceSourceSchema,
169
+ heading: z.string().max(512),
170
+ /** The page, when it is not the heading itself. */
171
+ title: z.string().max(512).optional(),
172
+ /** The file under its source's folder, such as `effects.md`. */
173
+ path: z.string().max(1024),
174
+ startLine: line,
175
+ endLine: line,
176
+ excerpt: z.string().max(300),
177
+ matchLine: line.optional(),
178
+ })
179
+ .strict();
180
+ export const referenceSearchToolDataSchema = referenceSearchDataSchema
181
+ .extend({ results: z.array(referenceHitSchema.extend({ score: z.number() })).max(12) })
182
+ .strict();
154
183
  export const referenceReadDataSchema = referenceSectionSchema
155
184
  .extend({
156
185
  sectionStartLine: line,
@@ -186,6 +215,9 @@ export const referenceContextDataSchema = z
186
215
  .max(16),
187
216
  })
188
217
  .strict();
218
+ export const referenceContextToolDataSchema = referenceContextDataSchema
219
+ .extend({ sections: z.array(referenceHitSchema).max(24) })
220
+ .strict();
189
221
  export const sourceLookupDataSchema = z
190
222
  .object({
191
223
  sourceScope: z.enum([