hoi4-agent-tools 4.9.0 → 4.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +20 -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/event/graph.js +16 -2
  6. package/dist/hoi4_agent_tools/event/source-analysis.js +35 -16
  7. package/dist/hoi4_agent_tools/impact/service.js +4 -1
  8. package/dist/hoi4_agent_tools/map/gameplay/reachability.js +81 -0
  9. package/dist/hoi4_agent_tools/map/geography/resolve.js +3 -0
  10. package/dist/hoi4_agent_tools/map/operations.js +8 -0
  11. package/dist/hoi4_agent_tools/map/partition-tuning.js +2 -1
  12. package/dist/hoi4_agent_tools/map/reference-world.js +17 -3
  13. package/dist/hoi4_agent_tools/map/relief/painted-relief.js +143 -0
  14. package/dist/hoi4_agent_tools/map/relief/terrain-synthesis.js +13 -0
  15. package/dist/hoi4_agent_tools/map/world.js +108 -23
  16. package/dist/hoi4_agent_tools/mcp/resources/register-modern.js +11 -4
  17. package/dist/hoi4_agent_tools/mcp/resources/register.js +7 -0
  18. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +1 -0
  19. package/dist/hoi4_agent_tools/mcp/tools/analysis.js +12 -0
  20. package/dist/hoi4_agent_tools/mcp/tools/reference.js +12 -3
  21. package/dist/hoi4_agent_tools/package-check/service.js +14 -1
  22. package/dist/hoi4_agent_tools/probability/model.js +4 -4
  23. package/dist/hoi4_agent_tools/probability/operations.js +6 -0
  24. package/dist/hoi4_agent_tools/probability/service.js +23 -0
  25. package/dist/hoi4_agent_tools/reference/operations.js +35 -6
  26. package/dist/hoi4_agent_tools/reference/service.js +118 -14
  27. package/dist/hoi4_agent_tools/reference/skill-resource.js +74 -0
  28. package/dist/hoi4_agent_tools/reference/skills.js +278 -0
  29. package/dist/hoi4_agent_tools/schemas/geography.js +5 -0
  30. package/dist/hoi4_agent_tools/schemas/map.js +29 -0
  31. package/dist/hoi4_agent_tools/schemas/reference.js +34 -2
  32. package/dist/hoi4_agent_tools/schemas/skill.js +72 -0
  33. package/dist/hoi4_agent_tools/version.js +1 -1
  34. package/docs/configuration.md +3 -3
  35. package/docs/map.md +12 -9
  36. package/docs/probability.md +1 -1
  37. package/docs/reference.md +27 -1
  38. package/docs/research/probability-adapter-evidence.md +15 -2
  39. package/docs/tools.md +101 -86
  40. package/engine/bin/manifest.json +1 -1
  41. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  42. package/npm-shrinkwrap.json +2 -2
  43. package/package.json +2 -1
  44. package/schemas/configuration.schema.json +1 -1
  45. package/schemas/continuous-focus-palette.schema.json +1 -1
  46. package/schemas/custom-weighted-pool.schema.json +1 -1
  47. package/schemas/decision-inspect-input.schema.json +1 -1
  48. package/schemas/error-log-input.schema.json +1 -1
  49. package/schemas/event-feature-manifest.schema.json +1 -1
  50. package/schemas/focus-plan.schema.json +1 -1
  51. package/schemas/focus-planning-sidecar.schema.json +1 -1
  52. package/schemas/geography-model.schema.json +4 -1
  53. package/schemas/gui-animation-source.schema.json +1 -1
  54. package/schemas/gui-helper.schema.json +1 -1
  55. package/schemas/gui-scenario.schema.json +1 -1
  56. package/schemas/helper-expansion-request.schema.json +1 -1
  57. package/schemas/helper-expansion-summary.schema.json +1 -1
  58. package/schemas/impact-inspect-input.schema.json +1 -1
  59. package/schemas/map-operation.schema.json +177 -118
  60. package/schemas/mechanic-test-input.schema.json +1 -1
  61. package/schemas/mod-index-input.schema.json +1 -1
  62. package/schemas/operation-result.schema.json +1 -1
  63. package/schemas/package-check-input.schema.json +1 -1
  64. package/schemas/package-manifest.schema.json +1 -1
  65. package/schemas/probability-analysis-result.schema.json +1 -1
  66. package/schemas/probability-compare-input.schema.json +1 -1
  67. package/schemas/probability-evaluate-input.schema.json +1 -1
  68. package/schemas/probability-inspect-input.schema.json +1 -1
  69. package/schemas/probability-render-input.schema.json +1 -1
  70. package/schemas/probability-scenario-set.schema.json +1 -1
  71. package/schemas/probability-sequence-input.schema.json +1 -1
  72. package/schemas/probability-simulate-input.schema.json +1 -1
  73. package/schemas/probability-sweep-input.schema.json +1 -1
  74. package/schemas/reference-context-input.schema.json +1 -1
  75. package/schemas/reference-read-input.schema.json +3 -3
  76. package/schemas/reference-search-input.schema.json +1 -1
  77. package/schemas/reference-sheets.schema.json +1 -1
  78. package/schemas/scenario-suite.schema.json +1 -1
  79. package/schemas/scenario-test-input.schema.json +1 -1
  80. package/schemas/script-validate-input.schema.json +1 -1
  81. package/schemas/shared-scenario.schema.json +1 -1
  82. package/schemas/source-lookup-input.schema.json +1 -1
  83. package/server.json +2 -2
@@ -666,6 +666,28 @@ function diagnosticsFor(scenarios, surface, extra = {}) {
666
666
  }
667
667
  return diagnostics;
668
668
  }
669
+ /** Reports an installed game the adapters were not checked against (#70). */
670
+ export function gameVersionDiagnostics(verification) {
671
+ if (verification.status !== 'workspace_observed')
672
+ return [];
673
+ return [
674
+ {
675
+ code: 'PROBABILITY_GAME_BUILD_UNVERIFIED',
676
+ severity: 'warning',
677
+ category: 'configuration',
678
+ message: `The installed game is ${verification.observedVersion ?? verification.observedRawVersion ?? 'unknown'}, but the weighting rules were checked against ${verification.adapterTarget}. The documented rules are applied unchanged, so recheck results that depend on rules the new build may have changed.`,
679
+ details: {
680
+ adapterTarget: verification.adapterTarget,
681
+ ...(verification.observedRawVersion === undefined
682
+ ? {}
683
+ : { observedRawVersion: verification.observedRawVersion }),
684
+ ...(verification.observedChecksum === undefined
685
+ ? {}
686
+ : { observedChecksum: verification.observedChecksum }),
687
+ },
688
+ },
689
+ ];
690
+ }
669
691
  function deduplicateUnresolved(values) {
670
692
  const output = new Map();
671
693
  for (const value of values) {
@@ -969,6 +991,7 @@ export class ProbabilityAnalyzer {
969
991
  : { diagnosticThresholds: extra.diagnosticThresholds }),
970
992
  ...(extra.unresolved === undefined ? {} : { unresolved: extra.unresolved }),
971
993
  }),
994
+ ...gameVersionDiagnostics(metadata.gameVersionVerification),
972
995
  ...(extra.diagnostics ?? []),
973
996
  ],
974
997
  unresolved,
@@ -10,6 +10,8 @@ import { scriptValidateDataSchema, scriptValidateRequestSchema, } from '../schem
10
10
  import { identifierArgumentCommands, validateScript, } from './script-validation.js';
11
11
  import { modChangedAfter, readErrorLog } from './error-log.js';
12
12
  import { modIndex } from './mod-index.js';
13
+ import { listSkills, loadSkill } from './skills.js';
14
+ import { skillDataSchema, skillRequestSchema } from '../schemas/skill.js';
13
15
  import { inspectLocalisation } from '../localisation/inspect.js';
14
16
  import { inspectIdeas } from '../ideas/inspect.js';
15
17
  import { ideaInspectDataSchema, ideaInspectRequestSchema } from '../schemas/ideas.js';
@@ -59,6 +61,7 @@ const schemas = {
59
61
  'hoi4.system_inspect': systemInspectRequestSchema,
60
62
  'hoi4.unit_inspect': unitInspectRequestSchema,
61
63
  'hoi4.asset_inspect': assetInspectRequestSchema,
64
+ 'hoi4.skill': skillRequestSchema,
62
65
  };
63
66
  /** Asset findings players would not notice: uneven frames, sprites the game fills itself, hidden pictures and flags one pixel off. */
64
67
  const ASSET_INFORMATION = new Set([
@@ -88,11 +91,11 @@ export class ReferenceToolService {
88
91
  const workspaceId = await resolveOperationWorkspaceForSource(this.engine, context, parsed.workspaceId, name === 'hoi4.script_validate' ? scriptValidateRequestSchema.parse(parsed).path : undefined, signal);
89
92
  const workspace = this.engine.resolver.get(workspaceId, context.principal);
90
93
  const data = name === 'hoi4.reference_search'
91
- ? await this.references.search(workspace, referenceSearchRequestSchema.parse(parsed), signal)
94
+ ? await this.references.searchHits(workspace, referenceSearchRequestSchema.parse(parsed), signal)
92
95
  : name === 'hoi4.reference_read'
93
96
  ? await this.references.read(workspace, referenceReadRequestSchema.parse(parsed), signal)
94
97
  : name === 'hoi4.reference_context'
95
- ? await this.references.context(workspace, referenceContextRequestSchema.parse(parsed), signal)
98
+ ? await this.references.contextHits(workspace, referenceContextRequestSchema.parse(parsed), signal)
96
99
  : name === 'hoi4.error_log'
97
100
  ? await readErrorLog(workspace, errorLogRequestSchema.parse(parsed), this.engine.resolver.config().gameUserRoot, signal)
98
101
  : name === 'hoi4.mod_index'
@@ -107,9 +110,11 @@ export class ReferenceToolService {
107
110
  ? await inspectAssets(workspace, assetInspectRequestSchema.parse(parsed), signal)
108
111
  : name === 'hoi4.unit_inspect'
109
112
  ? await inspectUnits(workspace, unitInspectRequestSchema.parse(parsed), signal)
110
- : name === 'hoi4.localisation_inspect'
111
- ? await inspectLocalisation(workspace, localisationInspectRequestSchema.parse(parsed), signal)
112
- : await sourceLookup(this.engine, workspaceId, sourceLookupRequestSchema.parse(parsed), context.principal, signal);
113
+ : name === 'hoi4.skill'
114
+ ? await this.skill(workspace, skillRequestSchema.parse(parsed), signal)
115
+ : name === 'hoi4.localisation_inspect'
116
+ ? await inspectLocalisation(workspace, localisationInspectRequestSchema.parse(parsed), signal)
117
+ : await sourceLookup(this.engine, workspaceId, sourceLookupRequestSchema.parse(parsed), context.principal, signal);
113
118
  const result = emptyServiceResult(workspaceId, data);
114
119
  if (name === 'hoi4.error_log') {
115
120
  const log = errorLogDataSchema.parse(data);
@@ -149,6 +154,25 @@ export class ReferenceToolService {
149
154
  ],
150
155
  };
151
156
  }
157
+ if (name === 'hoi4.skill') {
158
+ const served = skillDataSchema.parse(data);
159
+ result.code = served.skill === undefined ? 'SKILLS_LISTED' : 'SKILL_LOADED';
160
+ // A skill that differs from the kit version the mod pins is not the shared text.
161
+ result.validation = {
162
+ passed: served.drifted === 0,
163
+ checks: [
164
+ {
165
+ id: 'skill-pinned',
166
+ passed: served.drifted === 0,
167
+ message: served.kit === null
168
+ ? 'The mod has no HOI4 Mod Setup lock, so the skills are served unpinned'
169
+ : served.drifted === 0
170
+ ? `Every served file matches kit revision ${served.kit.revision}`
171
+ : `${served.drifted} skills differ from kit revision ${served.kit.revision}`,
172
+ },
173
+ ],
174
+ };
175
+ }
152
176
  if (name === 'hoi4.mod_index') {
153
177
  const index = modIndexDataSchema.parse(data);
154
178
  result.code = index.complete ? 'MOD_INDEXED' : 'MOD_INDEXED_PARTIAL';
@@ -303,12 +327,17 @@ export class ReferenceToolService {
303
327
  result.diagnostics.length > 1)
304
328
  result.diagnostics.pop();
305
329
  }
306
- return toolResult(result);
330
+ return toolResult(result, { compact: true });
307
331
  }
308
332
  #eventPopups = new Map();
309
333
  /** The latest player-text context of each workspace, keyed by its source files' hashes. */
310
334
  #playerText = new Map();
311
335
  /** File mode reads the scanned file and the mod's scripted helper names from one scan. */
336
+ async skill(workspace, request, signal) {
337
+ return request.name === undefined
338
+ ? listSkills(workspace, signal)
339
+ : loadSkill(workspace, { ...request, name: request.name }, signal);
340
+ }
312
341
  async validateScript(workspaceId, workspace, request, principal, signal) {
313
342
  // Every file check of the supported families shares one scan, so checking files across
314
343
  // folders reuses one snapshot and its incremental index; other folders add their own.
@@ -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
+ }