hoi4-agent-tools 4.20.3 → 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 (140) hide show
  1. package/CHANGELOG.md +40 -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/characters/write-operations.js +2 -2
  6. package/dist/hoi4_agent_tools/characters/write-plan.js +21 -205
  7. package/dist/hoi4_agent_tools/common-write/documented-lists.js +62 -0
  8. package/dist/hoi4_agent_tools/common-write/limits.js +35 -0
  9. package/dist/hoi4_agent_tools/common-write/paths.js +17 -0
  10. package/dist/hoi4_agent_tools/common-write/write-job-operations.js +42 -0
  11. package/dist/hoi4_agent_tools/common-write/write-operations.js +360 -0
  12. package/dist/hoi4_agent_tools/common-write/write-plan.js +34 -0
  13. package/dist/hoi4_agent_tools/core/artifacts-engine.js +272 -0
  14. package/dist/hoi4_agent_tools/core/configuration.js +6 -0
  15. package/dist/hoi4_agent_tools/core/domain-tools.js +8 -0
  16. package/dist/hoi4_agent_tools/core/engine.js +67 -21
  17. package/dist/hoi4_agent_tools/core/idle-cache-lifetime.js +7 -0
  18. package/dist/hoi4_agent_tools/core/job-controls.js +12 -2
  19. package/dist/hoi4_agent_tools/core/job-executor.js +8 -7
  20. package/dist/hoi4_agent_tools/core/job-operation-registration.js +4 -0
  21. package/dist/hoi4_agent_tools/core/job-store.js +97 -5
  22. package/dist/hoi4_agent_tools/core/job-worker-host.js +2 -2
  23. package/dist/hoi4_agent_tools/core/operation-result.js +118 -33
  24. package/dist/hoi4_agent_tools/core/operation-tasks.js +4 -2
  25. package/dist/hoi4_agent_tools/core/transactions.js +6 -0
  26. package/dist/hoi4_agent_tools/core/workspace.js +25 -2
  27. package/dist/hoi4_agent_tools/country/job-operations.js +42 -0
  28. package/dist/hoi4_agent_tools/country/write-operations.js +646 -0
  29. package/dist/hoi4_agent_tools/country/write-plan.js +28 -0
  30. package/dist/hoi4_agent_tools/decision/write-operations.js +7 -8
  31. package/dist/hoi4_agent_tools/decision/write-plan.js +25 -245
  32. package/dist/hoi4_agent_tools/doctrine/write-operations.js +2 -2
  33. package/dist/hoi4_agent_tools/doctrine/write-plan.js +21 -180
  34. package/dist/hoi4_agent_tools/event/graph.js +3 -3
  35. package/dist/hoi4_agent_tools/event/job-operations.js +2 -2
  36. package/dist/hoi4_agent_tools/event/write-job-operations.js +2 -2
  37. package/dist/hoi4_agent_tools/event/write-operations.js +9 -10
  38. package/dist/hoi4_agent_tools/event/write-plan.js +28 -278
  39. package/dist/hoi4_agent_tools/focus/job-operations.js +2 -2
  40. package/dist/hoi4_agent_tools/gui/assets.js +3 -13
  41. package/dist/hoi4_agent_tools/gui/job-operations.js +2 -2
  42. package/dist/hoi4_agent_tools/gui/layout.js +2 -4
  43. package/dist/hoi4_agent_tools/gui/renderer.js +2 -1
  44. package/dist/hoi4_agent_tools/gui/source-graph.js +16 -0
  45. package/dist/hoi4_agent_tools/gui/studio.js +31 -0
  46. package/dist/hoi4_agent_tools/ideas/write-operations.js +7 -8
  47. package/dist/hoi4_agent_tools/ideas/write-plan.js +24 -304
  48. package/dist/hoi4_agent_tools/map/engine-validation.js +230 -0
  49. package/dist/hoi4_agent_tools/map/job-operations.js +2 -2
  50. package/dist/hoi4_agent_tools/map/landmass-source.js +42 -0
  51. package/dist/hoi4_agent_tools/map/landmass.js +190 -0
  52. package/dist/hoi4_agent_tools/map/model.js +17 -3
  53. package/dist/hoi4_agent_tools/map/operations.js +20 -6
  54. package/dist/hoi4_agent_tools/map/references.js +6 -3
  55. package/dist/hoi4_agent_tools/map/service.js +88 -8
  56. package/dist/hoi4_agent_tools/map/validation.js +12 -18
  57. package/dist/hoi4_agent_tools/mcp/server/argument-errors.js +2 -0
  58. package/dist/hoi4_agent_tools/mcp/server/create-modern-operations.js +1 -1
  59. package/dist/hoi4_agent_tools/mcp/server/create.js +4 -0
  60. package/dist/hoi4_agent_tools/mcp/server/task-tool-catalog.js +4 -0
  61. package/dist/hoi4_agent_tools/mcp/tools/common-write.js +21 -0
  62. package/dist/hoi4_agent_tools/mcp/tools/country-write.js +21 -0
  63. package/dist/hoi4_agent_tools/mcp/tools/map.js +1 -1
  64. package/dist/hoi4_agent_tools/mcp/transports/http.js +2 -0
  65. package/dist/hoi4_agent_tools/mcp/transports/negotiated-stdio.js +24 -16
  66. package/dist/hoi4_agent_tools/probability/job-operations.js +2 -2
  67. package/dist/hoi4_agent_tools/runtime.js +83 -3
  68. package/dist/hoi4_agent_tools/schemas/character-write.js +5 -1
  69. package/dist/hoi4_agent_tools/schemas/common-write.js +74 -0
  70. package/dist/hoi4_agent_tools/schemas/country-write.js +206 -0
  71. package/dist/hoi4_agent_tools/schemas/decision-write.js +5 -1
  72. package/dist/hoi4_agent_tools/schemas/doctrine-write.js +5 -1
  73. package/dist/hoi4_agent_tools/schemas/event-write.js +5 -1
  74. package/dist/hoi4_agent_tools/schemas/idea-write.js +5 -1
  75. package/dist/hoi4_agent_tools/schemas/landmass.js +129 -0
  76. package/dist/hoi4_agent_tools/schemas/localisation-write.js +10 -1
  77. package/dist/hoi4_agent_tools/schemas/map-requests.js +1 -1
  78. package/dist/hoi4_agent_tools/schemas/map.js +2 -0
  79. package/dist/hoi4_agent_tools/schemas/tech-write.js +5 -1
  80. package/dist/hoi4_agent_tools/script-write/engine-plan.js +45 -0
  81. package/dist/hoi4_agent_tools/technology/engine-graph.js +156 -0
  82. package/dist/hoi4_agent_tools/technology/job-operations.js +2 -2
  83. package/dist/hoi4_agent_tools/technology/operations.js +1 -2
  84. package/dist/hoi4_agent_tools/technology/service.js +30 -59
  85. package/dist/hoi4_agent_tools/technology/write-job-operations.js +2 -2
  86. package/dist/hoi4_agent_tools/technology/write-operations.js +2 -2
  87. package/dist/hoi4_agent_tools/technology/write-plan.js +21 -207
  88. package/dist/hoi4_agent_tools/version.js +1 -1
  89. package/docs/configuration.md +11 -10
  90. package/docs/jobs.md +2 -2
  91. package/docs/setup.md +1 -0
  92. package/docs/tools.md +16 -2
  93. package/docs/troubleshooting.md +11 -11
  94. package/engine/bin/darwin-arm64/hoi4-engine +0 -0
  95. package/engine/bin/linux-arm64/hoi4-engine +0 -0
  96. package/engine/bin/linux-x64/hoi4-engine +0 -0
  97. package/engine/bin/manifest.json +8 -8
  98. package/engine/bin/win32-x64/hoi4-engine.exe +0 -0
  99. package/npm-shrinkwrap.json +43 -19
  100. package/package.json +2 -2
  101. package/schemas/configuration.schema.json +143 -134
  102. package/schemas/continuous-focus-palette.schema.json +1 -1
  103. package/schemas/custom-weighted-pool.schema.json +1 -1
  104. package/schemas/decision-inspect-input.schema.json +1 -1
  105. package/schemas/error-log-input.schema.json +1 -1
  106. package/schemas/event-feature-manifest.schema.json +1 -1
  107. package/schemas/focus-plan.schema.json +1 -1
  108. package/schemas/focus-planning-sidecar.schema.json +1 -1
  109. package/schemas/geography-model.schema.json +1 -1
  110. package/schemas/gui-animation-source.schema.json +1 -1
  111. package/schemas/gui-helper.schema.json +1 -1
  112. package/schemas/gui-scenario.schema.json +1 -1
  113. package/schemas/helper-expansion-request.schema.json +1 -1
  114. package/schemas/helper-expansion-summary.schema.json +1 -1
  115. package/schemas/impact-inspect-input.schema.json +1 -1
  116. package/schemas/map-operation.schema.json +354 -1
  117. package/schemas/mechanic-test-input.schema.json +1 -1
  118. package/schemas/mod-index-input.schema.json +1 -1
  119. package/schemas/operation-result.schema.json +1 -1
  120. package/schemas/package-check-input.schema.json +1 -1
  121. package/schemas/package-manifest.schema.json +1 -1
  122. package/schemas/probability-analysis-result.schema.json +1 -1
  123. package/schemas/probability-compare-input.schema.json +1 -1
  124. package/schemas/probability-evaluate-input.schema.json +1 -1
  125. package/schemas/probability-inspect-input.schema.json +1 -1
  126. package/schemas/probability-render-input.schema.json +1 -1
  127. package/schemas/probability-scenario-set.schema.json +1 -1
  128. package/schemas/probability-sequence-input.schema.json +1 -1
  129. package/schemas/probability-simulate-input.schema.json +1 -1
  130. package/schemas/probability-sweep-input.schema.json +1 -1
  131. package/schemas/reference-context-input.schema.json +1 -1
  132. package/schemas/reference-read-input.schema.json +1 -1
  133. package/schemas/reference-search-input.schema.json +1 -1
  134. package/schemas/reference-sheets.schema.json +1 -1
  135. package/schemas/scenario-suite.schema.json +1 -1
  136. package/schemas/scenario-test-input.schema.json +1 -1
  137. package/schemas/script-validate-input.schema.json +1 -1
  138. package/schemas/shared-scenario.schema.json +1 -1
  139. package/schemas/source-lookup-input.schema.json +1 -1
  140. 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
  ]);
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
1
2
  import { compareCodeUnits, hashCanonical } from './canonical.js';
2
3
  import { installedEffectCommands } from './game-documentation.js';
3
4
  import { SymbolIndex } from './index.js';
@@ -107,7 +108,13 @@ export class CoreEngine {
107
108
  #scanAdmissionQueue = [];
108
109
  #activeScanAdmissions = new Set();
109
110
  #recovery;
111
+ #startupWork;
110
112
  #startup;
113
+ /** Set by {@link recoverOnDemand}: each workspace recovers on its first use. */
114
+ #recoverOnDemand = false;
115
+ #recoveries = new Map();
116
+ /** Marks the work of a recovery, which reads its own workspace and must not wait for itself. */
117
+ #inRecovery = new AsyncLocalStorage();
111
118
  constructor(resolver, services = {}) {
112
119
  this.resolver = resolver;
113
120
  const state = resolver.serverState();
@@ -144,39 +151,78 @@ export class CoreEngine {
144
151
  return recovery;
145
152
  }
146
153
  /**
147
- * Run `work` in the background as part of startup, and hold {@link recovered} until it
148
- * finishes. A stdio server uses this to load the workspaces after it has answered the client
149
- * handshake. The work reports its own failure (for example through
154
+ * Set the work that loads the workspaces, to run when {@link recovered} is first asked for. A
155
+ * stdio server answers its handshake and tool list without it; the transport asks for
156
+ * {@link recovered} when the first request that needs a workspace arrives, so an idle server
157
+ * never loads one. The work reports its own failure (for example through
150
158
  * `resolver.failStartup`); a rejection here only ends the wait.
151
159
  */
152
160
  deferStartup(work) {
153
- this.#startup = work().catch(() => undefined);
161
+ this.#startupWork = work;
162
+ }
163
+ /**
164
+ * Recover each workspace on its first use instead of every workspace at once: before its
165
+ * first file access through the resolver, before its first job is submitted and before its
166
+ * first rewrite is planned or applied. A failed recovery is recorded as with
167
+ * {@link initialize}: reads go on and rewrites are refused with
168
+ * `TRANSACTION_RECOVERY_REQUIRED`.
169
+ */
170
+ recoverOnDemand() {
171
+ this.#recoverOnDemand = true;
172
+ this.resolver.onWorkspaceUse((workspaceId) => this.ensureRecovered(workspaceId));
173
+ this.transactions.setRecoveryGate((workspaceId) => {
174
+ try {
175
+ return this.ensureRecovered(this.resolver.get(workspaceId).id);
176
+ }
177
+ catch {
178
+ // An unknown workspace is refused by the caller's own lookup.
179
+ return Promise.resolve();
180
+ }
181
+ });
182
+ }
183
+ /**
184
+ * Recover `workspaceId` once when {@link recoverOnDemand} is on; otherwise, and for the
185
+ * recovery's own file access, it returns at once. It never rejects.
186
+ */
187
+ ensureRecovered(workspaceId) {
188
+ if (!this.#recoverOnDemand || this.#inRecovery.getStore() === true)
189
+ return Promise.resolve();
190
+ let recovery = this.#recoveries.get(workspaceId);
191
+ if (recovery === undefined) {
192
+ recovery = this.#inRecovery.run(true, () => this.#recoverWorkspace(workspaceId));
193
+ this.#recoveries.set(workspaceId, recovery);
194
+ }
195
+ return recovery;
154
196
  }
155
197
  /**
156
198
  * Settles when the deferred startup and the latest {@link initialize} have finished, at once
157
- * when neither was started.
199
+ * when neither was set. The first call starts the deferred startup.
158
200
  */
159
201
  async recovered() {
202
+ if (this.#startupWork !== undefined)
203
+ this.#startup ??= this.#startupWork().catch(() => undefined);
160
204
  await this.#startup;
161
205
  await this.#recovery;
162
206
  }
163
207
  async #recoverWorkspaces() {
164
- for (const workspace of this.resolver.list()) {
165
- // Recovery repairs an interrupted internal rewrite before the workspace is exposed. A
166
- // journal that cannot be recovered blocks rewrites of its own workspace, not the server.
167
- try {
168
- await this.transactions.recover(workspace.id);
169
- }
170
- catch (error) {
171
- this.transactions.recordRecoveryFailure(workspace.id, error);
172
- process.stderr.write(`${JSON.stringify({
173
- level: 'error',
174
- event: 'transaction_recovery_blocked',
175
- workspaceId: workspace.id,
176
- code: error instanceof ServiceError ? error.code : 'TRANSACTION_RECOVERY_FAILED',
177
- message: error instanceof Error ? error.message : String(error),
178
- })}\n`);
179
- }
208
+ for (const workspace of this.resolver.list())
209
+ await this.#recoverWorkspace(workspace.id);
210
+ }
211
+ async #recoverWorkspace(workspaceId) {
212
+ // Recovery repairs an interrupted internal rewrite before the workspace is exposed. A
213
+ // journal that cannot be recovered blocks rewrites of its own workspace, not the server.
214
+ try {
215
+ await this.transactions.recover(workspaceId);
216
+ }
217
+ catch (error) {
218
+ this.transactions.recordRecoveryFailure(workspaceId, error);
219
+ process.stderr.write(`${JSON.stringify({
220
+ level: 'error',
221
+ event: 'transaction_recovery_blocked',
222
+ workspaceId,
223
+ code: error instanceof ServiceError ? error.code : 'TRANSACTION_RECOVERY_FAILED',
224
+ message: error instanceof Error ? error.message : String(error),
225
+ })}\n`);
180
226
  }
181
227
  }
182
228
  status(workspaceId, principal) {
@@ -96,3 +96,10 @@ export class IdleCacheLifetime {
96
96
  this.release();
97
97
  }
98
98
  }
99
+ /**
100
+ * The cache lifetime of one group of operations on `engine`: its caches are released after the
101
+ * configured `idleCacheReleaseSeconds` without a call (default 30 s).
102
+ */
103
+ export function idleCacheLifetime(engine, releaseCaches) {
104
+ return new IdleCacheLifetime(releaseCaches, engine.resolver.config().idleCacheReleaseSeconds * 1000);
105
+ }
@@ -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,
@@ -131,7 +131,9 @@ export class OperationTaskService {
131
131
  ? validatedArguments.relativePath
132
132
  : undefined, requestSignal)
133
133
  : await resolveOperationWorkspaceId(this.engine, context, requestedWorkspaceId, requestSignal);
134
- this.engine.resolver.get(workspaceId, context.principal);
134
+ // A server that recovers on demand repairs this workspace's interrupted rewrite before
135
+ // the call reads or rewrites it; a failure is recorded and refuses rewrites only.
136
+ await this.engine.ensureRecovered(this.engine.resolver.get(workspaceId, context.principal).id);
135
137
  requestSignal?.throwIfAborted();
136
138
  }
137
139
  catch (error) {
@@ -244,7 +246,7 @@ export class OperationTaskService {
244
246
  if (record.status === 'completed' && record.result !== undefined)
245
247
  return record.result;
246
248
  if (record.status === 'failed')
247
- 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);
248
250
  if (record.status === 'cancelled')
249
251
  return errorResult(new ServiceError('JOB_CANCELLED', 'The background operation was cancelled'), record.scope.workspaceId);
250
252
  throw new ServiceError('TASK_RESULT_PENDING', 'The protocol task has not reached a terminal state');
@@ -212,7 +212,13 @@ export class TransactionManager {
212
212
  recordRecoveryFailure(workspaceId, error) {
213
213
  this.#recoveryFailures.set(workspaceId, error instanceof Error ? error.message : 'Rewrite journal recovery failed');
214
214
  }
215
+ #recoveryGate;
216
+ /** Run `gate` before a rewrite of a workspace is planned or applied; the engine recovers on demand. */
217
+ setRecoveryGate(gate) {
218
+ this.#recoveryGate = gate;
219
+ }
215
220
  async assertRecovered(workspaceId, signal) {
221
+ await this.#recoveryGate?.(workspaceId);
216
222
  if (!this.#recoveryFailures.has(workspaceId))
217
223
  return;
218
224
  try {