hoi4-agent-tools 4.21.0 → 4.22.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 (100) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +2 -0
  3. package/dist/bin/setup.js +1 -0
  4. package/dist/bin/stdio.js +1 -0
  5. package/dist/hoi4_agent_tools/common-write/documented-lists.js +62 -0
  6. package/dist/hoi4_agent_tools/common-write/limits.js +35 -0
  7. package/dist/hoi4_agent_tools/common-write/paths.js +17 -0
  8. package/dist/hoi4_agent_tools/common-write/write-job-operations.js +42 -0
  9. package/dist/hoi4_agent_tools/common-write/write-operations.js +360 -0
  10. package/dist/hoi4_agent_tools/common-write/write-plan.js +34 -0
  11. package/dist/hoi4_agent_tools/core/domain-tools.js +8 -0
  12. package/dist/hoi4_agent_tools/core/job-controls.js +12 -2
  13. package/dist/hoi4_agent_tools/core/job-executor.js +8 -7
  14. package/dist/hoi4_agent_tools/core/job-operation-registration.js +4 -0
  15. package/dist/hoi4_agent_tools/core/job-store.js +97 -5
  16. package/dist/hoi4_agent_tools/core/job-worker-host.js +2 -2
  17. package/dist/hoi4_agent_tools/core/operation-result.js +118 -33
  18. package/dist/hoi4_agent_tools/core/operation-tasks.js +1 -1
  19. package/dist/hoi4_agent_tools/core/workspace.js +11 -1
  20. package/dist/hoi4_agent_tools/country/job-operations.js +42 -0
  21. package/dist/hoi4_agent_tools/country/write-operations.js +646 -0
  22. package/dist/hoi4_agent_tools/country/write-plan.js +28 -0
  23. package/dist/hoi4_agent_tools/map/engine-validation.js +1 -1
  24. package/dist/hoi4_agent_tools/map/landmass-source.js +42 -0
  25. package/dist/hoi4_agent_tools/map/landmass.js +190 -0
  26. package/dist/hoi4_agent_tools/map/operations.js +20 -6
  27. package/dist/hoi4_agent_tools/map/references.js +6 -3
  28. package/dist/hoi4_agent_tools/map/service.js +88 -8
  29. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +2 -0
  30. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
  31. package/dist/hoi4_agent_tools/mcp/server/create.js +4 -0
  32. package/dist/hoi4_agent_tools/mcp/server/task-tool-catalog.js +4 -0
  33. package/dist/hoi4_agent_tools/mcp/tools/common-write.js +21 -0
  34. package/dist/hoi4_agent_tools/mcp/tools/country-write.js +21 -0
  35. package/dist/hoi4_agent_tools/mcp/tools/map.js +1 -1
  36. package/dist/hoi4_agent_tools/mcp/transports/http.js +2 -0
  37. package/dist/hoi4_agent_tools/runtime.js +79 -1
  38. package/dist/hoi4_agent_tools/schemas/character-write.js +5 -1
  39. package/dist/hoi4_agent_tools/schemas/common-write.js +74 -0
  40. package/dist/hoi4_agent_tools/schemas/country-write.js +206 -0
  41. package/dist/hoi4_agent_tools/schemas/decision-write.js +5 -1
  42. package/dist/hoi4_agent_tools/schemas/doctrine-write.js +5 -1
  43. package/dist/hoi4_agent_tools/schemas/event-write.js +5 -1
  44. package/dist/hoi4_agent_tools/schemas/idea-write.js +5 -1
  45. package/dist/hoi4_agent_tools/schemas/landmass.js +129 -0
  46. package/dist/hoi4_agent_tools/schemas/localisation-write.js +10 -1
  47. package/dist/hoi4_agent_tools/schemas/map-requests.js +1 -1
  48. package/dist/hoi4_agent_tools/schemas/map.js +2 -0
  49. package/dist/hoi4_agent_tools/schemas/tech-write.js +5 -1
  50. package/dist/hoi4_agent_tools/version.js +1 -1
  51. package/docs/jobs.md +2 -2
  52. package/docs/setup.md +1 -0
  53. package/docs/tools.md +16 -2
  54. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  55. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  56. package/engine/bin/linux-x64/hoi4-engine +0 -0
  57. package/engine/bin/manifest.json +8 -8
  58. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  59. package/npm-shrinkwrap.json +43 -19
  60. package/package.json +1 -1
  61. package/schemas/configuration.schema.json +1 -1
  62. package/schemas/continuous-focus-palette.schema.json +1 -1
  63. package/schemas/custom-weighted-pool.schema.json +1 -1
  64. package/schemas/decision-inspect-input.schema.json +1 -1
  65. package/schemas/error-log-input.schema.json +1 -1
  66. package/schemas/event-feature-manifest.schema.json +1 -1
  67. package/schemas/focus-plan.schema.json +1 -1
  68. package/schemas/focus-planning-sidecar.schema.json +1 -1
  69. package/schemas/geography-model.schema.json +1 -1
  70. package/schemas/gui-animation-source.schema.json +1 -1
  71. package/schemas/gui-helper.schema.json +1 -1
  72. package/schemas/gui-scenario.schema.json +1 -1
  73. package/schemas/helper-expansion-request.schema.json +1 -1
  74. package/schemas/helper-expansion-summary.schema.json +1 -1
  75. package/schemas/impact-inspect-input.schema.json +1 -1
  76. package/schemas/map-operation.schema.json +354 -1
  77. package/schemas/mechanic-test-input.schema.json +1 -1
  78. package/schemas/mod-index-input.schema.json +1 -1
  79. package/schemas/operation-result.schema.json +1 -1
  80. package/schemas/package-check-input.schema.json +1 -1
  81. package/schemas/package-manifest.schema.json +1 -1
  82. package/schemas/probability-analysis-result.schema.json +1 -1
  83. package/schemas/probability-compare-input.schema.json +1 -1
  84. package/schemas/probability-evaluate-input.schema.json +1 -1
  85. package/schemas/probability-inspect-input.schema.json +1 -1
  86. package/schemas/probability-render-input.schema.json +1 -1
  87. package/schemas/probability-scenario-set.schema.json +1 -1
  88. package/schemas/probability-sequence-input.schema.json +1 -1
  89. package/schemas/probability-simulate-input.schema.json +1 -1
  90. package/schemas/probability-sweep-input.schema.json +1 -1
  91. package/schemas/reference-context-input.schema.json +1 -1
  92. package/schemas/reference-read-input.schema.json +1 -1
  93. package/schemas/reference-search-input.schema.json +1 -1
  94. package/schemas/reference-sheets.schema.json +1 -1
  95. package/schemas/scenario-suite.schema.json +1 -1
  96. package/schemas/scenario-test-input.schema.json +1 -1
  97. package/schemas/script-validate-input.schema.json +1 -1
  98. package/schemas/shared-scenario.schema.json +1 -1
  99. package/schemas/source-lookup-input.schema.json +1 -1
  100. package/server.json +2 -2
@@ -3,6 +3,8 @@ import { eventInspectRequestSchema, eventRenderRequestSchema } from '../schemas/
3
3
  import { focusInspectRequestSchema, focusRenderRequestSchema, focusRewriteRequestSchema, } from '../schemas/focus-requests.js';
4
4
  import { guiInspectRequestSchema, guiRenderRequestSchema, guiRewriteRequestSchema, } from '../schemas/gui-requests.js';
5
5
  import { characterWriteRequestSchema } from '../schemas/character-write.js';
6
+ import { commonWriteRequestSchema } from '../schemas/common-write.js';
7
+ import { countryWriteRequestSchema } from '../schemas/country-write.js';
6
8
  import { decisionWriteRequestSchema } from '../schemas/decision-write.js';
7
9
  import { doctrineWriteRequestSchema } from '../schemas/doctrine-write.js';
8
10
  import { techWriteRequestSchema } from '../schemas/tech-write.js';
@@ -35,10 +37,12 @@ export const DOMAIN_TOOL_NAMES = [
35
37
  'hoi4.localisation_write',
36
38
  'hoi4.idea_write',
37
39
  'hoi4.character_write',
40
+ 'hoi4.country_write',
38
41
  'hoi4.event_write',
39
42
  'hoi4.decision_write',
40
43
  'hoi4.tech_write',
41
44
  'hoi4.doctrine_write',
45
+ 'hoi4.common_write',
42
46
  'hoi4.gui_inspect',
43
47
  'hoi4.gui_render',
44
48
  'hoi4.gui_rewrite',
@@ -63,10 +67,12 @@ export const DOMAIN_TOOL_ARGUMENT_SCHEMAS = {
63
67
  'hoi4.localisation_write': localisationWriteRequestSchema,
64
68
  'hoi4.idea_write': ideaWriteRequestSchema,
65
69
  'hoi4.character_write': characterWriteRequestSchema,
70
+ 'hoi4.country_write': countryWriteRequestSchema,
66
71
  'hoi4.event_write': eventWriteRequestSchema,
67
72
  'hoi4.decision_write': decisionWriteRequestSchema,
68
73
  'hoi4.tech_write': techWriteRequestSchema,
69
74
  'hoi4.doctrine_write': doctrineWriteRequestSchema,
75
+ 'hoi4.common_write': commonWriteRequestSchema,
70
76
  'hoi4.gui_inspect': guiInspectRequestSchema,
71
77
  'hoi4.gui_render': guiRenderRequestSchema,
72
78
  'hoi4.gui_rewrite': guiRewriteRequestSchema,
@@ -85,9 +91,11 @@ export const MUTATION_TOOL_NAMES = new Set([
85
91
  'hoi4.localisation_write',
86
92
  'hoi4.idea_write',
87
93
  'hoi4.character_write',
94
+ 'hoi4.country_write',
88
95
  'hoi4.event_write',
89
96
  'hoi4.decision_write',
90
97
  'hoi4.tech_write',
91
98
  'hoi4.doctrine_write',
99
+ 'hoi4.common_write',
92
100
  'hoi4.focus_rewrite',
93
101
  ]);
@@ -27,7 +27,16 @@ const jobStatusDataSchema = z
27
27
  .strict()
28
28
  .optional(),
29
29
  failure: z
30
- .object({ code: z.string().max(256), message: z.string().max(4096) })
30
+ .object({
31
+ code: z.string().max(256),
32
+ message: z.string().max(4096),
33
+ /**
34
+ * The refusal's public details, unchanged. Details over 64 KiB of canonical JSON are
35
+ * replaced by `{ truncated: true, originalBytes, maximumBytes, omittedKeyCount,
36
+ * omittedKeys, details }`. Absent when the refusal carried none.
37
+ */
38
+ details: z.record(z.string().max(256), z.unknown()).optional(),
39
+ })
31
40
  .strict()
32
41
  .optional(),
33
42
  })
@@ -53,7 +62,8 @@ function statusResult(record) {
53
62
  if (record.status === 'failed') {
54
63
  result.status = 'error';
55
64
  result.validation.passed = false;
56
- result.blockers = [record.failure];
65
+ const { code, message, details } = record.failure;
66
+ result.blockers = [{ code, message, ...(details === undefined ? {} : { details }) }];
57
67
  }
58
68
  else if (record.status === 'cancelled') {
59
69
  result.status = 'blocked';
@@ -1,6 +1,6 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
2
  import { z } from 'zod/v4';
3
- import { currentJobOwner } from './job-store.js';
3
+ import { currentJobOwner, jobFailureFromError } from './job-store.js';
4
4
  import { JobTransactions } from './job-transactions.js';
5
5
  import { ServiceError } from './result.js';
6
6
  import { PACKAGE_VERSION } from '../version.js';
@@ -232,12 +232,13 @@ export class JobExecutor {
232
232
  const cause = watchFailure ?? error;
233
233
  return await this.jobs.store.updateOwned(scope, id, owner.token, {
234
234
  status: 'failed',
235
- failure: {
236
- code: cause instanceof ServiceError ? cause.code : 'JOB_EXECUTION_FAILED',
237
- message: cause instanceof ServiceError
238
- ? cause.message
239
- : 'The typed operation failed; no completed result was recorded',
240
- },
235
+ // A refusal keeps its bounded public details so every answer can return them (#327).
236
+ failure: cause instanceof ServiceError
237
+ ? jobFailureFromError(cause)
238
+ : {
239
+ code: 'JOB_EXECUTION_FAILED',
240
+ message: 'The typed operation failed; no completed result was recorded',
241
+ },
241
242
  });
242
243
  }
243
244
  finally {
@@ -39,10 +39,14 @@ export async function registerWorkerOperations(engine, toolName) {
39
39
  (await import('../ideas/job-operations.js')).registerIdeaWriteJobs(operations, engine);
40
40
  else if (toolName === 'hoi4.decision_write')
41
41
  (await import('../decision/write-job-operations.js')).registerDecisionWriteJobs(operations, engine);
42
+ else if (toolName === 'hoi4.common_write')
43
+ (await import('../common-write/write-job-operations.js')).registerCommonWriteJobs(operations, engine);
42
44
  else if (toolName === 'hoi4.doctrine_write')
43
45
  (await import('../doctrine/write-job-operations.js')).registerDoctrineWriteJobs(operations, engine);
44
46
  else if (toolName === 'hoi4.character_write')
45
47
  (await import('../characters/job-operations.js')).registerCharacterWriteJobs(operations, engine);
48
+ else if (toolName === 'hoi4.country_write')
49
+ (await import('../country/job-operations.js')).registerCountryWriteJobs(operations, engine);
46
50
  else if (toolName.startsWith('hoi4.map_'))
47
51
  (await import('../map/job-operations.js')).registerMapJobs(operations, engine);
48
52
  else if (toolName.startsWith('hoi4.probability_'))
@@ -2,13 +2,108 @@ import { lstat, mkdir, open, opendir, rename, unlink } from 'node:fs/promises';
2
2
  import path from 'node:path';
3
3
  import { hostname } from 'node:os';
4
4
  import { z } from 'zod/v4';
5
- import { canonicalJson, hashCanonical, secureId } from './canonical.js';
5
+ import { canonicalize, canonicalJson, canonicalJsonByteLength, compareCodeUnits, hashCanonical, secureId, } from './canonical.js';
6
+ import { publicDetailText, publicServiceErrorDetails } from './operation-result.js';
6
7
  import { ServiceError } from './result.js';
7
8
  import { retryWindowsSharing } from './windows-sharing.js';
8
9
  import { SharedRequestCapacity } from './shared-request-capacity.js';
9
10
  import { containedGeneratedPath } from './workspace.js';
10
11
  import { PACKAGE_VERSION } from '../version.js';
11
12
  const digest = z.string().regex(/^[a-f0-9]{64}$/u);
13
+ /** Largest canonical JSON, in UTF-8 bytes, of the refusal details a failed job keeps. */
14
+ export const JOB_FAILURE_DETAILS_MAX_BYTES = 64 * 1024;
15
+ /** How many omitted top-level detail names a truncation marker lists. */
16
+ const JOB_FAILURE_OMITTED_KEYS_LISTED = 64;
17
+ /** Room the truncation marker's own fields keep free inside the limit. */
18
+ const JOB_FAILURE_MARKER_RESERVE_BYTES = 8 * 1024;
19
+ function defineMember(target, key, value) {
20
+ Object.defineProperty(target, key, {
21
+ value,
22
+ enumerable: true,
23
+ writable: true,
24
+ configurable: true,
25
+ });
26
+ }
27
+ /**
28
+ * Bound a refusal's public details for a job record (issue 327). Details whose canonical JSON fits
29
+ * in {@link JOB_FAILURE_DETAILS_MAX_BYTES} are kept unchanged. Larger details are replaced by a
30
+ * deterministic marker:
31
+ *
32
+ * `{ truncated: true, originalBytes, maximumBytes, omittedKeyCount, omittedKeys, details }`
33
+ *
34
+ * where `details` keeps whole top-level members in code-unit key order while they fit, and
35
+ * `omittedKeys` lists the first omitted names (at most 64) in the same order. Empty or
36
+ * non-serializable details give `undefined`, so a failure without details shows none.
37
+ */
38
+ export function boundedJobFailureDetails(details) {
39
+ let value;
40
+ try {
41
+ value = canonicalize(JSON.parse(JSON.stringify(details)));
42
+ }
43
+ catch {
44
+ return undefined;
45
+ }
46
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
47
+ return undefined;
48
+ const keys = Object.keys(value).sort(compareCodeUnits);
49
+ if (keys.length === 0)
50
+ return undefined;
51
+ const originalBytes = Buffer.byteLength(JSON.stringify(value));
52
+ if (originalBytes <= JOB_FAILURE_DETAILS_MAX_BYTES)
53
+ return value;
54
+ const budget = JOB_FAILURE_DETAILS_MAX_BYTES - JOB_FAILURE_MARKER_RESERVE_BYTES;
55
+ const kept = {};
56
+ const omitted = [];
57
+ let keptBytes = 2;
58
+ for (const key of keys) {
59
+ const member = value[key];
60
+ const separator = keptBytes > 2 ? 1 : 0;
61
+ const memberBytes = canonicalJsonByteLength(member, budget);
62
+ const entryBytes = memberBytes === undefined
63
+ ? undefined
64
+ : separator + Buffer.byteLength(JSON.stringify(key)) + 1 + memberBytes;
65
+ if (entryBytes !== undefined && keptBytes + entryBytes <= budget) {
66
+ defineMember(kept, key, member);
67
+ keptBytes += entryBytes;
68
+ }
69
+ else
70
+ omitted.push(key);
71
+ }
72
+ const marker = (listed, retained) => ({
73
+ truncated: true,
74
+ originalBytes,
75
+ maximumBytes: JOB_FAILURE_DETAILS_MAX_BYTES,
76
+ omittedKeyCount: omitted.length,
77
+ omittedKeys: listed,
78
+ details: retained,
79
+ });
80
+ const listed = omitted.slice(0, JOB_FAILURE_OMITTED_KEYS_LISTED);
81
+ for (const candidate of [marker(listed, kept), marker([], kept), marker([], {})]) {
82
+ if (canonicalJsonByteLength(candidate, JOB_FAILURE_DETAILS_MAX_BYTES) !== undefined)
83
+ return canonicalize(candidate);
84
+ }
85
+ return undefined;
86
+ }
87
+ /** The stored failure for a refusal: its code, message and bounded public details. */
88
+ export function jobFailureFromError(error) {
89
+ const details = boundedJobFailureDetails(publicServiceErrorDetails(error));
90
+ return {
91
+ code: error.code,
92
+ message: publicDetailText(error.message),
93
+ ...(details === undefined ? {} : { details }),
94
+ };
95
+ }
96
+ const failureDetailsSchema = z
97
+ .record(z.string(), z.json())
98
+ .refine((value) => canonicalJsonByteLength(value, JOB_FAILURE_DETAILS_MAX_BYTES) !== undefined, 'Job failure details exceed the stored size limit');
99
+ const failureSchema = z
100
+ .object({
101
+ code: z.string().min(1),
102
+ message: z.string().max(4096),
103
+ /** Optional: records written before issue 327 carry no details. */
104
+ details: failureDetailsSchema.optional(),
105
+ })
106
+ .strict();
12
107
  const jobId = z.string().regex(/^job_[a-f0-9]{64}$/u);
13
108
  const scopeSchema = z
14
109
  .object({
@@ -103,10 +198,7 @@ const recordBaseSchema = z
103
198
  * ends (ADR 0087). The task answers with it; the job's final result follows in `result`.
104
199
  */
105
200
  earlyResult: z.record(z.string(), z.json()).optional(),
106
- failure: z
107
- .object({ code: z.string().min(1), message: z.string().max(4096) })
108
- .strict()
109
- .optional(),
201
+ failure: failureSchema.optional(),
110
202
  })
111
203
  .strict();
112
204
  const recordSchema = recordBaseSchema.superRefine((value, context) => {
@@ -5,7 +5,7 @@ import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { setTimeout as delay } from 'node:timers/promises';
7
7
  import { JobService } from './job-service.js';
8
- import { jobOwnerLiveness, readCheckpointIdentity } from './job-store.js';
8
+ import { jobFailureFromError, jobOwnerLiveness, readCheckpointIdentity, } from './job-store.js';
9
9
  import { RequestScheduler } from './request-scheduler.js';
10
10
  import { SharedRequestCapacity } from './shared-request-capacity.js';
11
11
  import { containedGeneratedPath } from './workspace.js';
@@ -61,7 +61,7 @@ function nativeFailureCode(error) {
61
61
  /** Map a launcher failure to a stable, path-free job failure. */
62
62
  export function workerFailure(error, stage) {
63
63
  if (error instanceof ServiceError)
64
- return { code: error.code, message: error.message };
64
+ return jobFailureFromError(error);
65
65
  const nativeCode = nativeFailureCode(error);
66
66
  return nativeCode === undefined
67
67
  ? {
@@ -592,6 +592,122 @@ export function internalServiceError(error) {
592
592
  const message = error instanceof Error ? withoutDirectories(error.message) : '';
593
593
  return new ServiceError('INTERNAL_ERROR', `Unexpected ${kind}${message.length > 0 ? `: ${message}` : ''}. Retry once with a narrower selector; if it repeats, report this message with the tool name and arguments.`);
594
594
  }
595
+ /**
596
+ * The refusal details a tool result may carry for this error: internal write details are reduced
597
+ * to their public limits and path, stack and transaction fields are dropped. Applying it twice
598
+ * gives the same details, so a job can store them and rebuild the same error envelope.
599
+ */
600
+ export function publicServiceErrorDetails(serviceError) {
601
+ return serviceError.code.startsWith('TRANSACTION_')
602
+ ? ['TRANSACTION_STRUCTURE_LIMIT', 'TRANSACTION_JOURNAL_LIMIT'].includes(serviceError.code)
603
+ ? Object.fromEntries(Object.entries(serviceError.details).filter(([key, value]) => (key === 'remedy' && typeof value === 'string' && value.length <= 400) ||
604
+ ([
605
+ 'files',
606
+ 'filesLimit',
607
+ 'operations',
608
+ 'operationsLimit',
609
+ 'readDependencies',
610
+ 'readDependenciesLimit',
611
+ 'artifacts',
612
+ 'artifactsLimit',
613
+ 'diagnostics',
614
+ 'diagnosticsLimit',
615
+ 'checks',
616
+ 'checksLimit',
617
+ 'requestedWorkBytes',
618
+ 'plannedJournalBytes',
619
+ 'retainedBytes',
620
+ 'maximumBytes',
621
+ ].includes(key) &&
622
+ typeof value === 'number' &&
623
+ Number.isSafeInteger(value) &&
624
+ value >= 0)))
625
+ : {}
626
+ : publicDetailValue(serviceError.details, 0, new WeakSet());
627
+ }
628
+ /** Key names compare lower-case without `_` or `-`, so `Absolute_Path` and `plan-hash` match. */
629
+ const DENIED_DETAIL_KEYS = new Set([
630
+ 'cause',
631
+ 'stack',
632
+ 'stacktrace',
633
+ 'absolutepath',
634
+ 'transactionid',
635
+ 'planhash',
636
+ 'rollbackstatus',
637
+ 'snippet',
638
+ 'sourcetext',
639
+ ]);
640
+ const DETAIL_MAX_DEPTH = 8;
641
+ const DETAIL_CYCLE_MARKER = '[details omitted: cyclic]';
642
+ const DETAIL_DEEP_MARKER = '[details omitted: nested too deeply]';
643
+ /**
644
+ * An absolute host path inside text: a drive path, a UNC (`\\server\share`) or `\\?\` path, a
645
+ * `file://` URL, a `~/` path or a rooted path. A folder name may hold one space ("John Smith"); a path ends at `,` `;` `(` `)`, at a space followed by a word without a slash, and its last name ends at
646
+ * whitespace. A relative path with a slash in it never matches, because the match must start at a
647
+ * boundary.
648
+ */
649
+ const ABSOLUTE_PATH_IN_TEXT = /(?<![A-Za-z0-9_.\-/\\~:])(?:file:\/\/\/?|\\\\\?\\|\\\\|~[\\/]|[A-Za-z]:[\\/]|[\\/])(?=\S)(?:[A-Za-z]:[\\/])?(?:[^\s\\/'"`<>|*?:,;()]+(?: [^\s\\/'"`<>|*?:,;()]+)?[\\/])*[^\s\\/'"`<>|*?:,;()]*/gu;
650
+ /** Text with every absolute host path reduced to its last name (or a marker when it has none). */
651
+ export function publicDetailText(value) {
652
+ return value.replace(ABSOLUTE_PATH_IN_TEXT, (match) => {
653
+ const name = /[^\\/]+$/u.exec(match)?.[0] ?? '';
654
+ return name.length === 0 || name.endsWith(':') ? '[host path]' : name;
655
+ });
656
+ }
657
+ function denied(key) {
658
+ return DENIED_DETAIL_KEYS.has(key.toLowerCase().replace(/[_-]/gu, ''));
659
+ }
660
+ /**
661
+ * The public form of one refusal detail value at any depth: denied keys (in any case or
662
+ * spelling) are removed from every nested object, key names and text lose absolute host paths,
663
+ * and a cyclic or too deep value becomes a marker, so nothing is dropped without a trace. A
664
+ * `Date` becomes its ISO text, a `Map` an object, a `Set` an array and an `Error` its name and
665
+ * path-free message. A cut at the depth limit keeps only the marker, not the data below it.
666
+ */
667
+ function publicDetailValue(value, depth, seen) {
668
+ if (typeof value === 'string')
669
+ return publicDetailText(value);
670
+ if (value === null || typeof value !== 'object')
671
+ return value;
672
+ if (value instanceof Date)
673
+ return Number.isNaN(value.getTime()) ? null : value.toISOString();
674
+ if (value instanceof Error)
675
+ return `${value.name}: ${publicDetailText(value.message)}`.slice(0, 300);
676
+ if (seen.has(value))
677
+ return DETAIL_CYCLE_MARKER;
678
+ if (depth >= DETAIL_MAX_DEPTH)
679
+ return DETAIL_DEEP_MARKER;
680
+ seen.add(value);
681
+ try {
682
+ if (Array.isArray(value) || value instanceof Set)
683
+ return [...value].map((member) => publicDetailValue(member, depth + 1, seen));
684
+ const entries = value instanceof Map
685
+ ? [...value.entries()].map(([key, member]) => [String(key), member])
686
+ : Object.entries(value);
687
+ const result = {};
688
+ for (const [key, member] of entries) {
689
+ if (denied(key))
690
+ continue;
691
+ // Two keys can collapse to the same text once their paths are reduced.
692
+ const base = publicDetailText(key);
693
+ let name = base;
694
+ for (let suffix = 2; Object.hasOwn(result, name); suffix += 1)
695
+ name = `${base}_${suffix}`;
696
+ // defineProperty, so a `__proto__` key stays data instead of changing the prototype.
697
+ Object.defineProperty(result, name, {
698
+ value: publicDetailValue(member, depth + 1, seen),
699
+ enumerable: true,
700
+ writable: true,
701
+ configurable: true,
702
+ });
703
+ }
704
+ return result;
705
+ }
706
+ finally {
707
+ // A shared (not cyclic) object may appear twice, so only the current path counts.
708
+ seen.delete(value);
709
+ }
710
+ }
595
711
  export function errorResult(error, workspaceId = '', context = {}) {
596
712
  const serviceError = error instanceof ServiceError ? error : internalServiceError(error);
597
713
  const internalWriteError = serviceError.code.startsWith('TRANSACTION_');
@@ -604,39 +720,8 @@ export function errorResult(error, workspaceId = '', context = {}) {
604
720
  : serviceError.code === 'TRANSACTION_JOURNAL_LIMIT'
605
721
  ? 'The requested rewrite exceeds the bounded rollback storage allowance'
606
722
  : 'Rewrite could not be completed'
607
- : serviceError.message;
608
- const publicDetails = internalWriteError
609
- ? ['TRANSACTION_STRUCTURE_LIMIT', 'TRANSACTION_JOURNAL_LIMIT'].includes(serviceError.code)
610
- ? Object.fromEntries(Object.entries(serviceError.details).filter(([key, value]) => [
611
- 'files',
612
- 'filesLimit',
613
- 'operations',
614
- 'operationsLimit',
615
- 'readDependencies',
616
- 'readDependenciesLimit',
617
- 'artifacts',
618
- 'artifactsLimit',
619
- 'diagnostics',
620
- 'diagnosticsLimit',
621
- 'checks',
622
- 'checksLimit',
623
- 'requestedWorkBytes',
624
- 'plannedJournalBytes',
625
- 'retainedBytes',
626
- 'maximumBytes',
627
- ].includes(key) &&
628
- typeof value === 'number' &&
629
- Number.isSafeInteger(value) &&
630
- value >= 0))
631
- : {}
632
- : Object.fromEntries(Object.entries(serviceError.details).filter(([key]) => ![
633
- 'cause',
634
- 'stack',
635
- 'absolutePath',
636
- 'transactionId',
637
- 'planHash',
638
- 'rollbackStatus',
639
- ].includes(key)));
723
+ : publicDetailText(serviceError.message);
724
+ const publicDetails = publicServiceErrorDetails(serviceError);
640
725
  return toolResult({
641
726
  status: publicCode.includes('BLOCKED') ? 'blocked' : 'error',
642
727
  code: publicCode,
@@ -246,7 +246,7 @@ export class OperationTaskService {
246
246
  if (record.status === 'completed' && record.result !== undefined)
247
247
  return record.result;
248
248
  if (record.status === 'failed')
249
- return errorResult(new ServiceError(record.failure?.code ?? 'JOB_FAILED', record.failure?.message ?? 'The background operation failed'), record.scope.workspaceId);
249
+ return errorResult(new ServiceError(record.failure?.code ?? 'JOB_FAILED', record.failure?.message ?? 'The background operation failed', record.failure?.details ?? {}), record.scope.workspaceId);
250
250
  if (record.status === 'cancelled')
251
251
  return errorResult(new ServiceError('JOB_CANCELLED', 'The background operation was cancelled'), record.scope.workspaceId);
252
252
  throw new ServiceError('TASK_RESULT_PENDING', 'The protocol task has not reached a terminal state');
@@ -1,3 +1,4 @@
1
+ import { realpathSync } from 'node:fs';
1
2
  import { lstat, mkdir, opendir, readFile, readdir, realpath } from 'node:fs/promises';
2
3
  import path from 'node:path';
3
4
  import { WORKSPACE_MAX_REGISTRATIONS, workspaceRegistrationSchema, } from './configuration.js';
@@ -560,7 +561,16 @@ export class WorkspaceResolver {
560
561
  throw new ServiceError('WORKSPACE_CONTEXT_NOT_FOUND', 'No writable mod workspace is configured for the MCP server', workspaceCandidates(workspaces));
561
562
  }
562
563
  const currentDirectory = path.normalize(process.cwd());
563
- const containing = workspaces.filter((workspace) => isWithin(workspace.modRoot, currentDirectory));
564
+ // Workspace roots are canonical, so a symlink, junction or 8.3 name must be resolved too.
565
+ let canonicalDirectory = currentDirectory;
566
+ try {
567
+ canonicalDirectory = path.normalize(realpathSync.native(currentDirectory));
568
+ }
569
+ catch {
570
+ // A vanished working folder keeps its lexical form.
571
+ }
572
+ const containing = workspaces.filter((workspace) => isWithin(workspace.modRoot, currentDirectory) ||
573
+ isWithin(workspace.modRoot, canonicalDirectory));
564
574
  if (containing.length === 1)
565
575
  return containing[0].id;
566
576
  if (containing.length > 1) {
@@ -0,0 +1,42 @@
1
+ import { z } from 'zod/v4';
2
+ import { toolResult } from '../core/operation-result.js';
3
+ import { ServiceError } from '../core/result.js';
4
+ import { countryWriteRequestSchema } from '../schemas/country-write.js';
5
+ import { completeCountryWrite, prepareCountryWrite, previewCountryWrite, } from './write-operations.js';
6
+ const wireResult = z.record(z.string(), z.json());
7
+ function wire(result) {
8
+ return wireResult.parse(JSON.parse(JSON.stringify(toolResult(result))));
9
+ }
10
+ /** Registers `hoi4.country_write`: a read-only preview, or one journaled transaction. */
11
+ export function registerCountryWriteJobs(operations, engine) {
12
+ operations.registerWrite('hoi4.country_write', countryWriteRequestSchema, async (input, context) => {
13
+ if (input.workspaceId !== 'current' && input.workspaceId !== context.workspaceId)
14
+ throw new ServiceError('JOB_ARGUMENT_SCOPE_MISMATCH', 'The request workspace does not match the authorized job workspace');
15
+ const operationContext = {
16
+ workspaceId: context.workspaceId,
17
+ ...(context.principal === undefined ? {} : { principal: context.principal }),
18
+ signal: context.signal,
19
+ progress: (completed, total, message) => context.progress({ completed, total, message }),
20
+ };
21
+ if (!input.apply)
22
+ return {
23
+ readOnlyPreview: wire(await previewCountryWrite(engine, input, operationContext)),
24
+ };
25
+ const prepared = await prepareCountryWrite(engine, input, operationContext);
26
+ if ('readOnlyPreview' in prepared)
27
+ return { readOnlyPreview: wire(prepared.readOnlyPreview) };
28
+ return { transaction: prepared.transaction, recipe: { ...prepared.recipe } };
29
+ }, async (_input, execution, _reconciled, recipe, context) => {
30
+ const result = completeCountryWrite(context.workspaceId, execution, recipe);
31
+ await context.progress({
32
+ completed: 3,
33
+ total: 3,
34
+ message: execution.outcome === 'applied'
35
+ ? 'Country change complete'
36
+ : execution.outcome === 'unchanged'
37
+ ? 'The country already matched the request'
38
+ : 'Country change blocked',
39
+ });
40
+ return wire(result);
41
+ });
42
+ }