@cortex-agent/server 2026.8.3-2 → 2026.8.6

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 (219) hide show
  1. package/defaults/config/thread-templates/agents/benchmark-coder.json +2 -2
  2. package/defaults/config/thread-templates/agents/benchmark-fixer.json +17 -0
  3. package/defaults/config/thread-templates/agents/benchmark-reviewer.json +5 -5
  4. package/defaults/config/thread-templates/templates/benchmark-coder-review-fix.json +21 -0
  5. package/defaults/plugins/cortex-system/skills/thread/SKILL.md +1 -0
  6. package/defaults/prompts/directives/benchmark-coder.md +1 -0
  7. package/defaults/prompts/directives/benchmark-fixer.md +1 -0
  8. package/defaults/prompts/directives/benchmark-reviewer.md +1 -0
  9. package/defaults/prompts/systemPrompts/benchmark-coder.md +1 -0
  10. package/defaults/prompts/systemPrompts/benchmark-fixer.md +1 -0
  11. package/defaults/prompts/systemPrompts/benchmark-reviewer.md +1 -0
  12. package/dist/agent-adapter/capabilities.d.ts +32 -1
  13. package/dist/agent-adapter/capabilities.js +39 -1
  14. package/dist/agent-adapter/claude/adapter.d.ts +15 -0
  15. package/dist/agent-adapter/claude/adapter.js +29 -7
  16. package/dist/agent-adapter/claude/spawn-args.d.ts +5 -2
  17. package/dist/agent-adapter/claude/spawn-args.js +29 -6
  18. package/dist/agent-adapter/index.js +11 -1
  19. package/dist/agent-adapter/normalize/tool-names.d.ts +4 -0
  20. package/dist/agent-adapter/normalize/tool-names.js +10 -0
  21. package/dist/agent-adapter/pi/adapter.d.ts +20 -8
  22. package/dist/agent-adapter/pi/adapter.js +130 -35
  23. package/dist/agent-adapter/pi/agent-dir.d.ts +20 -53
  24. package/dist/agent-adapter/pi/agent-dir.js +48 -89
  25. package/dist/agent-adapter/pi/custom-catalog.d.ts +10 -0
  26. package/dist/agent-adapter/pi/custom-catalog.js +42 -0
  27. package/dist/agent-adapter/pi/defaults.d.ts +9 -0
  28. package/dist/agent-adapter/pi/defaults.js +14 -4
  29. package/dist/agent-adapter/pi/discovery.d.ts +1 -3
  30. package/dist/agent-adapter/pi/discovery.js +3 -15
  31. package/dist/agent-adapter/pi/event-parser.js +8 -0
  32. package/dist/agent-adapter/pi/mcp-bridge.d.ts +13 -0
  33. package/dist/agent-adapter/pi/mcp-bridge.js +31 -6
  34. package/dist/agent-adapter/pi/mcp-duration.d.ts +28 -0
  35. package/dist/agent-adapter/pi/mcp-duration.js +48 -0
  36. package/dist/agent-adapter/pi/policy-guard.d.ts +40 -0
  37. package/dist/agent-adapter/pi/policy-guard.js +111 -0
  38. package/dist/agent-adapter/pi/providers-config.d.ts +62 -0
  39. package/dist/agent-adapter/pi/providers-config.js +101 -0
  40. package/dist/agent-adapter/pi/quota-probe.d.ts +11 -0
  41. package/dist/agent-adapter/pi/quota-probe.js +36 -0
  42. package/dist/agent-adapter/pi/quota-sink.d.ts +25 -0
  43. package/dist/agent-adapter/pi/quota-sink.js +31 -0
  44. package/dist/agent-adapter/pi/session-files.d.ts +2 -0
  45. package/dist/agent-adapter/pi/session-files.js +19 -0
  46. package/dist/agent-adapter/pi/session-support.d.ts +14 -3
  47. package/dist/agent-adapter/pi/session-support.js +8 -0
  48. package/dist/agent-adapter/pi/spawn-args.d.ts +11 -1
  49. package/dist/agent-adapter/pi/spawn-args.js +13 -0
  50. package/dist/agent-adapter/pi/tool-shims.d.ts +2 -2
  51. package/dist/agent-adapter/pi/tool-shims.js +32 -21
  52. package/dist/agent-adapter/pi/web-search.js +36 -8
  53. package/dist/agent-adapter/types.d.ts +14 -0
  54. package/dist/core/locales/en.d.ts +54 -1
  55. package/dist/core/locales/en.js +2 -0
  56. package/dist/core/locales/slices/commands.d.ts +12 -1
  57. package/dist/core/locales/slices/commands.js +24 -2
  58. package/dist/core/locales/slices/providers.d.ts +45 -0
  59. package/dist/core/locales/slices/providers.js +95 -0
  60. package/dist/core/locales/zh.js +2 -0
  61. package/dist/core/resilient-watch.d.ts +28 -0
  62. package/dist/core/resilient-watch.js +110 -0
  63. package/dist/core/settings.js +15 -20
  64. package/dist/core/types/agent-types.d.ts +6 -0
  65. package/dist/core/types/thread-types.d.ts +21 -3
  66. package/dist/domain/agent-run/agent-run-cli.js +3 -1
  67. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +31 -0
  68. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +231 -24
  69. package/dist/domain/agent-run/benchmark-thread-identity.d.ts +15 -2
  70. package/dist/domain/agent-run/benchmark-thread-identity.js +123 -34
  71. package/dist/domain/agent-run/identity.d.ts +5 -0
  72. package/dist/domain/agent-run/identity.js +4 -1
  73. package/dist/domain/agent-run/journal.d.ts +3 -2
  74. package/dist/domain/agent-run/manifest.js +11 -4
  75. package/dist/domain/agent-run/pinned-node-process.d.ts +4 -0
  76. package/dist/domain/agent-run/pinned-node-process.js +9 -0
  77. package/dist/domain/agent-run/role-surface.d.ts +2 -2
  78. package/dist/domain/agent-run/role-surface.js +7 -3
  79. package/dist/domain/agent-run/run-config.d.ts +10 -1
  80. package/dist/domain/agent-run/run-config.js +57 -6
  81. package/dist/domain/agent-run/runner.js +149 -31
  82. package/dist/domain/agents/facade.d.ts +37 -122
  83. package/dist/domain/agents/facade.js +47 -115
  84. package/dist/domain/agents/spawn-config.d.ts +135 -0
  85. package/dist/domain/agents/spawn-config.js +121 -0
  86. package/dist/domain/benchmark/accounting-reconciliation.d.ts +98 -0
  87. package/dist/domain/benchmark/accounting-reconciliation.js +218 -0
  88. package/dist/domain/benchmark/arm-schema.d.ts +43 -0
  89. package/dist/domain/benchmark/arm-schema.js +243 -0
  90. package/dist/domain/benchmark/capabilities.d.ts +4 -0
  91. package/dist/domain/benchmark/capabilities.js +54 -0
  92. package/dist/domain/benchmark/decimal-text.d.ts +27 -0
  93. package/dist/domain/benchmark/decimal-text.js +67 -0
  94. package/dist/domain/benchmark/lease-echo.d.ts +43 -0
  95. package/dist/domain/benchmark/lease-echo.js +56 -0
  96. package/dist/domain/benchmark/policy-backed-runtime-deps.d.ts +14 -0
  97. package/dist/domain/benchmark/policy-backed-runtime-deps.js +47 -0
  98. package/dist/domain/benchmark/policy-compiler.d.ts +68 -0
  99. package/dist/domain/benchmark/policy-compiler.js +680 -0
  100. package/dist/domain/benchmark/resolved-policy.d.ts +110 -0
  101. package/dist/domain/benchmark/resolved-policy.js +195 -0
  102. package/dist/domain/benchmark/trial-adapter-factory.d.ts +38 -0
  103. package/dist/domain/benchmark/trial-adapter-factory.js +165 -0
  104. package/dist/domain/benchmark/trial-thread-adapter.d.ts +25 -0
  105. package/dist/domain/benchmark/trial-thread-adapter.js +106 -0
  106. package/dist/domain/benchmark/variant-proposal.d.ts +45 -0
  107. package/dist/domain/benchmark/variant-proposal.js +42 -0
  108. package/dist/domain/benchmark/workspace-lease.d.ts +99 -0
  109. package/dist/domain/benchmark/workspace-lease.js +272 -0
  110. package/dist/domain/costs/codex-quota.d.ts +29 -0
  111. package/dist/domain/costs/codex-quota.js +102 -0
  112. package/dist/domain/costs/cost-tracker.d.ts +48 -9
  113. package/dist/domain/costs/cost-tracker.js +74 -18
  114. package/dist/domain/costs/rate-limit-throttle.d.ts +23 -1
  115. package/dist/domain/costs/rate-limit-throttle.js +61 -6
  116. package/dist/domain/costs/resume-registry.d.ts +3 -1
  117. package/dist/domain/costs/resume-registry.js +10 -1
  118. package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +26 -2
  119. package/dist/domain/mcp/tools/benchmark-thread-run.js +63 -20
  120. package/dist/domain/mcp/tools/cost.js +15 -6
  121. package/dist/domain/pi-providers/custom-provider-model.d.ts +53 -0
  122. package/dist/domain/pi-providers/custom-provider-model.js +122 -0
  123. package/dist/domain/pi-providers/custom-provider-service.d.ts +59 -0
  124. package/dist/domain/pi-providers/custom-provider-service.js +143 -0
  125. package/dist/domain/pi-providers/gateway-route-store.d.ts +23 -0
  126. package/dist/domain/pi-providers/gateway-route-store.js +78 -0
  127. package/dist/domain/pi-providers/index.d.ts +4 -0
  128. package/dist/domain/pi-providers/index.js +8 -0
  129. package/dist/domain/pi-providers/models-json-store.d.ts +6 -0
  130. package/dist/domain/pi-providers/models-json-store.js +77 -0
  131. package/dist/domain/scheduling/jobs/_shared.d.ts +4 -1
  132. package/dist/domain/scheduling/jobs/_shared.js +11 -2
  133. package/dist/domain/scheduling/jobs/scheduled-task.js +1 -0
  134. package/dist/domain/scheduling/jobs/task-dispatch.js +49 -54
  135. package/dist/domain/sessions/session-lifecycle.d.ts +22 -0
  136. package/dist/domain/sessions/session-lifecycle.js +20 -1
  137. package/dist/domain/system/system-notice.d.ts +4 -1
  138. package/dist/domain/system/system-notice.js +6 -2
  139. package/dist/domain/tasks/dispatch-utils.d.ts +0 -4
  140. package/dist/domain/tasks/dispatch-utils.js +24 -37
  141. package/dist/domain/threads/runner.d.ts +16 -1
  142. package/dist/domain/threads/runner.js +62 -8
  143. package/dist/domain/threads/template-loader.d.ts +5 -0
  144. package/dist/domain/threads/template-loader.js +120 -36
  145. package/dist/domain/threads/template-validate.d.ts +244 -0
  146. package/dist/domain/threads/template-validate.js +574 -0
  147. package/dist/domain/threads/template-validate.parity.d.ts +1 -0
  148. package/dist/domain/threads/template-validate.parity.js +47 -0
  149. package/dist/domain/threads/template-writer.d.ts +55 -0
  150. package/dist/domain/threads/template-writer.js +131 -0
  151. package/dist/domain/ui-service/app-router.d.ts +143 -1
  152. package/dist/domain/ui-service/app-router.js +29 -3
  153. package/dist/domain/ui-service/input-schemas.d.ts +228 -4
  154. package/dist/domain/ui-service/input-schemas.js +132 -1
  155. package/dist/domain/ui-service/mutate/config.d.ts +10 -1
  156. package/dist/domain/ui-service/mutate/config.js +45 -5
  157. package/dist/domain/ui-service/mutate/custom-providers.d.ts +8 -0
  158. package/dist/domain/ui-service/mutate/custom-providers.js +37 -0
  159. package/dist/domain/ui-service/mutate/profiles.d.ts +21 -0
  160. package/dist/domain/ui-service/mutate/profiles.js +156 -0
  161. package/dist/domain/ui-service/mutate/schedules.d.ts +2 -1
  162. package/dist/domain/ui-service/mutate/schedules.js +53 -3
  163. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
  164. package/dist/domain/ui-service/mutate/sessions.js +25 -1
  165. package/dist/domain/ui-service/mutate/system.d.ts +2 -1
  166. package/dist/domain/ui-service/mutate/system.js +17 -3
  167. package/dist/domain/ui-service/mutate/thread-templates.d.ts +4 -0
  168. package/dist/domain/ui-service/mutate/thread-templates.js +71 -0
  169. package/dist/domain/ui-service/query/config.js +30 -0
  170. package/dist/domain/ui-service/query/custom-providers.d.ts +8 -0
  171. package/dist/domain/ui-service/query/custom-providers.js +13 -0
  172. package/dist/domain/ui-service/query/machine-detail.d.ts +2 -0
  173. package/dist/domain/ui-service/query/machine-detail.js +56 -0
  174. package/dist/domain/ui-service/query/machine-probe.d.ts +18 -0
  175. package/dist/domain/ui-service/query/machine-probe.js +136 -0
  176. package/dist/domain/ui-service/query/schedules.js +5 -0
  177. package/dist/domain/ui-service/query/sessions.js +8 -2
  178. package/dist/domain/ui-service/query/thread-template-detail.d.ts +8 -0
  179. package/dist/domain/ui-service/query/thread-template-detail.js +94 -0
  180. package/dist/domain/ui-service/query/thread-templates.d.ts +5 -3
  181. package/dist/domain/ui-service/query/thread-templates.js +44 -7
  182. package/dist/domain/ui-service/types.d.ts +298 -7
  183. package/dist/domain/ui-service/ui-service.js +27 -3
  184. package/dist/entry/app.js +24 -3
  185. package/dist/entry/auth-cli.d.ts +4 -1
  186. package/dist/entry/auth-cli.js +10 -2
  187. package/dist/entry/cli-help.js +6 -2
  188. package/dist/entry/cli.js +2 -1
  189. package/dist/entry/daemon.d.ts +0 -11
  190. package/dist/entry/daemon.js +5 -49
  191. package/dist/entry/provider-cli.d.ts +16 -0
  192. package/dist/entry/provider-cli.js +203 -0
  193. package/dist/events/event-types.d.ts +2 -1
  194. package/dist/orchestration/agent-runner.js +3 -2
  195. package/dist/orchestration/routing/commands/cost.d.ts +8 -0
  196. package/dist/orchestration/routing/commands/cost.js +93 -21
  197. package/dist/orchestration/routing/commands/login-custom.d.ts +26 -0
  198. package/dist/orchestration/routing/commands/login-custom.js +89 -0
  199. package/dist/orchestration/routing/commands/login.d.ts +3 -0
  200. package/dist/orchestration/routing/commands/login.js +7 -0
  201. package/dist/orchestration/routing/message-router.js +48 -33
  202. package/dist/orchestration/routing/webhook.js +1 -1
  203. package/dist/orchestration/session-events.d.ts +2 -1
  204. package/dist/orchestration/session-events.js +1 -0
  205. package/dist/orchestration/thread-callback.js +1 -1
  206. package/dist/store/conversation-history-repo.d.ts +5 -1
  207. package/dist/store/conversation-history-repo.js +2 -1
  208. package/dist/store/cost-repo.d.ts +17 -0
  209. package/dist/store/cost-repo.js +47 -5
  210. package/dist/store/profile-repo.d.ts +0 -10
  211. package/dist/store/profile-repo.js +34 -56
  212. package/dist/store/session-registry-repo.d.ts +12 -0
  213. package/dist/store/session-registry-repo.js +16 -0
  214. package/package.json +1 -1
  215. package/web/dist/assets/index-DYMfaAi4.css +1 -0
  216. package/web/dist/assets/index-uOoZjGKa.js +141 -0
  217. package/web/dist/index.html +2 -2
  218. package/web/dist/assets/index-XqBCYtkw.js +0 -139
  219. package/web/dist/assets/index-zpf3OSKC.css +0 -1
@@ -1,24 +1,22 @@
1
- // Thread template config loading and hot-reload.
2
- // input: DATA_DIR/config/thread-templates/{agents,templates,shells}/ (directory form, preferred) or
3
- // the legacy single file DATA_DIR/config/thread-templates.json (fallback), prompts/ directory
4
- // output: loadConfig / migrateThreadTemplatesToDir / mergeThreadTemplates / startConfigWatcher /
5
- // stopConfigWatcher / getTemplate / getAgent / listTemplates / listAgents / resolvePluginDir
6
- // pos: DR-0017 D6 Phase 2.5 — config is directory-based (one file per agent/template/shell); shell
7
- // transition graphs are pure JSON (shells/*.json) expanded via the generic shell-templates
8
- // engine. A legacy single file is auto-migrated to the directory on startup.
1
+ // input: thread-template config, prompts, shells, resilient watch
2
+ // output: thread config load, migration, lookup, and hot reload APIs
3
+ // pos: Thread template configuration loader and watcher
9
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
10
5
  import { readFileSync, writeFileSync, readdirSync, renameSync, existsSync, mkdirSync, watch } from 'fs';
6
+ import { createHash } from 'node:crypto';
11
7
  import * as path from 'path';
12
8
  import { CONFIG_DIR, DATA_DIR, PROMPTS_DIR } from '../../core/utils.js';
13
9
  import { createLogger } from '../../core/log.js';
10
+ import { createResilientWatchMonitor } from '../../core/resilient-watch.js';
14
11
  import { Icons } from '../../core/icons.js';
15
12
  import { resolveTemplate } from './template-resolver.js';
16
13
  import { isShellBinding, expandShell } from './shell-templates.js';
14
+ import { validateRegistry } from './template-validate.js';
17
15
  const log = createLogger('thread-manager');
18
16
  /** Legacy single-file config (pre-Phase-2.5). Auto-migrated to CONFIG_TEMPLATES_DIR on startup. */
19
17
  const CONFIG_FILE = path.join(CONFIG_DIR, 'thread-templates.json');
20
- /** Directory-based config root (preferred). */
21
- const CONFIG_TEMPLATES_DIR = path.join(CONFIG_DIR, 'thread-templates');
18
+ /** Directory-based config root (preferred). Exported for the write path. */
19
+ export const CONFIG_TEMPLATES_DIR = path.join(CONFIG_DIR, 'thread-templates');
22
20
  const ENTITY_SUBDIRS = ['agents', 'templates', 'shells'];
23
21
  export const FILE_REF_PREFIX = 'file:';
24
22
  const FIELD_DIRS = {
@@ -208,8 +206,10 @@ function readEntityDir(dir) {
208
206
  }
209
207
  /** Load config from the directory form (one file per entity; merged across files). */
210
208
  function loadConfigFromDir(dir) {
209
+ const raw = { agents: {}, templates: {}, shells: {} };
211
210
  const a = {};
212
211
  for (const { name, data } of readEntityDir(path.join(dir, 'agents'))) {
212
+ raw.agents[name] = structuredClone(data);
213
213
  if (!data.name || data.name !== name) {
214
214
  log.warn(`Skipping agent file agents/${name}.json: name field "${data.name}" ≠ filename`);
215
215
  continue;
@@ -218,10 +218,13 @@ function loadConfigFromDir(dir) {
218
218
  a[name] = data;
219
219
  }
220
220
  const shells = {};
221
- for (const { name, data } of readEntityDir(path.join(dir, 'shells')))
221
+ for (const { name, data } of readEntityDir(path.join(dir, 'shells'))) {
222
+ raw.shells[name] = structuredClone(data);
222
223
  shells[name] = data;
224
+ }
223
225
  const t = {};
224
226
  for (const { name, data } of readEntityDir(path.join(dir, 'templates'))) {
227
+ raw.templates[name] = structuredClone(data);
225
228
  if (data.name !== undefined && data.name !== name) {
226
229
  log.warn(`Skipping template file templates/${name}.json: name field "${data.name}" ≠ filename`);
227
230
  continue;
@@ -230,7 +233,39 @@ function loadConfigFromDir(dir) {
230
233
  if (expanded)
231
234
  t[name] = expanded;
232
235
  }
233
- return { agents: a, templates: t };
236
+ return { agents: a, templates: t, raw };
237
+ }
238
+ /** Filesystem probes for the validator's `file:` ref and pluginDirs existence checks. */
239
+ export function loaderRefResolver() {
240
+ return {
241
+ promptsDir: PROMPTS_DIR,
242
+ pluginBaseDir: DATA_DIR,
243
+ join: path.join,
244
+ exists: existsSync,
245
+ isAbsolute: path.isAbsolute,
246
+ };
247
+ }
248
+ /**
249
+ * Report what is wrong with the config as loaded. Diagnostic only — the loader's own fail-soft skip
250
+ * logic still decides what actually loads, so a validator that disagrees with a file that works
251
+ * today can never take it away. The write path is where errors are enforced.
252
+ */
253
+ function logValidation(raw) {
254
+ let errors = 0;
255
+ let warnings = 0;
256
+ for (const [key, result] of validateRegistry(raw, loaderRefResolver())) {
257
+ for (const issue of result.errors) {
258
+ log.error(`thread-template ${key} — ${issue.path}: ${issue.message}`);
259
+ errors++;
260
+ }
261
+ for (const issue of result.warnings) {
262
+ log.warn(`thread-template ${key} — ${issue.path}: ${issue.message}`);
263
+ warnings++;
264
+ }
265
+ }
266
+ if (errors > 0 || warnings > 0) {
267
+ log.warn(`Thread-template validation: ${errors} error(s), ${warnings} warning(s)`);
268
+ }
234
269
  }
235
270
  /** Load config from the legacy single file. Shell bindings here have no shell defs to resolve
236
271
  * against (shells only exist in the directory form) and are fail-soft skipped. */
@@ -256,6 +291,8 @@ export function loadConfig() {
256
291
  agents = loaded.agents;
257
292
  templates = loaded.templates;
258
293
  log.info(`Loaded ${Object.keys(agents).length} agents, ${Object.keys(templates).length} templates`);
294
+ if (loaded.raw)
295
+ logValidation(loaded.raw);
259
296
  }
260
297
  catch (e) {
261
298
  log.error(`Failed to load config: ${e.message}`);
@@ -266,10 +303,9 @@ export function loadConfig() {
266
303
  }
267
304
  // --- Config hot-reload ---
268
305
  // Watches the config dir (or legacy single file) for external changes and reloads on modification.
269
- // Directory form: watch each entity subdir (agents/templates/shells) — flat dirs, so a plain watch
270
- // catches file adds/edits/removes. Single-file form: re-create the watcher on 'rename' events
271
- // because atomic file replacement (temp+rename) changes the inode.
272
- let _watchers = [];
306
+ // Directory form watches each flat entity subdir for adds, edits, and removes. Legacy single-file
307
+ // form watches CONFIG_DIR so atomic replacement does not invalidate the watcher.
308
+ let _configWatchMonitor = null;
273
309
  let _reloadTimer = null;
274
310
  function scheduleConfigReload(label) {
275
311
  if (_reloadTimer)
@@ -281,34 +317,82 @@ function scheduleConfigReload(label) {
281
317
  loadConfig();
282
318
  }, 300);
283
319
  }
284
- function closeConfigWatchers() {
285
- for (const w of _watchers)
286
- w.close();
287
- _watchers = [];
320
+ function pathStamp(filePath) {
321
+ try {
322
+ const digest = createHash('sha256').update(readFileSync(filePath)).digest('hex');
323
+ return `${filePath}:${digest}`;
324
+ }
325
+ catch {
326
+ return `${filePath}:missing`;
327
+ }
288
328
  }
289
- function setupConfigWatch() {
290
- closeConfigWatchers();
329
+ function threadConfigSnapshot() {
330
+ if (!existsSync(CONFIG_TEMPLATES_DIR))
331
+ return pathStamp(CONFIG_FILE);
332
+ const parts = [];
333
+ for (const sub of ENTITY_SUBDIRS) {
334
+ const dir = path.join(CONFIG_TEMPLATES_DIR, sub);
335
+ try {
336
+ const files = readdirSync(dir).filter((file) => file.endsWith('.json')).sort();
337
+ parts.push(`${sub}:${files.map((file) => pathStamp(path.join(dir, file))).join(',')}`);
338
+ }
339
+ catch {
340
+ parts.push(`${sub}:missing`);
341
+ }
342
+ }
343
+ return parts.join('|');
344
+ }
345
+ function startConfigFsWatchers(onChange) {
346
+ const watchers = [];
291
347
  try {
292
348
  if (existsSync(CONFIG_TEMPLATES_DIR)) {
293
349
  for (const sub of ENTITY_SUBDIRS) {
294
350
  const dir = path.join(CONFIG_TEMPLATES_DIR, sub);
295
- if (!existsSync(dir))
296
- continue;
297
- _watchers.push(watch(dir, () => scheduleConfigReload(`thread-templates/${sub}`)));
351
+ if (existsSync(dir))
352
+ watchers.push(watch(dir, () => onChange(`thread-templates/${sub}`)));
298
353
  }
299
354
  }
300
- else if (existsSync(CONFIG_FILE)) {
301
- _watchers.push(watch(CONFIG_FILE, (eventType) => {
302
- if (eventType === 'rename')
303
- setTimeout(() => setupConfigWatch(), 100);
304
- scheduleConfigReload('thread-templates.json');
355
+ else {
356
+ const filename = path.basename(CONFIG_FILE);
357
+ watchers.push(watch(CONFIG_DIR, (_event, changed) => {
358
+ if (changed === null || changed.toString() === filename)
359
+ onChange('thread-templates.json');
305
360
  }));
306
361
  }
362
+ if (watchers.length === 0)
363
+ throw new Error('no thread-template paths exist');
364
+ return watchers;
307
365
  }
308
- catch (e) {
309
- log.error(`Failed to watch thread-templates config: ${e.message}`);
366
+ catch (error) {
367
+ for (const watcher of watchers)
368
+ watcher.close();
369
+ throw error;
310
370
  }
311
371
  }
372
+ function setupConfigWatch() {
373
+ _configWatchMonitor?.close();
374
+ let observedSnapshot = threadConfigSnapshot();
375
+ const handleChange = (label) => {
376
+ const nextSnapshot = threadConfigSnapshot();
377
+ if (nextSnapshot === observedSnapshot)
378
+ return;
379
+ observedSnapshot = nextSnapshot;
380
+ scheduleConfigReload(label);
381
+ };
382
+ const poll = () => {
383
+ const nextSnapshot = threadConfigSnapshot();
384
+ if (nextSnapshot === observedSnapshot)
385
+ return;
386
+ observedSnapshot = nextSnapshot;
387
+ scheduleConfigReload('thread-templates');
388
+ };
389
+ _configWatchMonitor = createResilientWatchMonitor({
390
+ label: 'thread-templates config', poll,
391
+ startWatching: () => startConfigFsWatchers(handleChange),
392
+ warn: (message) => log.error(message),
393
+ });
394
+ poll();
395
+ }
312
396
  // --- Prompts directory hot-reload ---
313
397
  let _promptsWatchers = [];
314
398
  let _promptsReloadTimer = null;
@@ -352,11 +436,11 @@ export function startConfigWatcher() {
352
436
  startPromptsWatcher();
353
437
  }
354
438
  export function stopConfigWatcher() {
355
- closeConfigWatchers();
356
- if (_reloadTimer) {
439
+ _configWatchMonitor?.close();
440
+ _configWatchMonitor = null;
441
+ if (_reloadTimer)
357
442
  clearTimeout(_reloadTimer);
358
- _reloadTimer = null;
359
- }
443
+ _reloadTimer = null;
360
444
  stopPromptsWatcher();
361
445
  }
362
446
  // --- Agent and template lookup ---
@@ -0,0 +1,244 @@
1
+ import { z } from 'zod';
2
+ export type EntityKind = 'agent' | 'template' | 'shell';
3
+ /** `path` anchors the issue at a field (`transitions[2].from`) so the editor can point at it. */
4
+ export interface Issue {
5
+ path: string;
6
+ message: string;
7
+ }
8
+ export interface ValidationResult {
9
+ errors: Issue[];
10
+ warnings: Issue[];
11
+ }
12
+ /** Raw (unexpanded, un-file-ref-resolved) config as it sits on disk: name → parsed JSON. */
13
+ export interface RawRegistry {
14
+ agents: Record<string, unknown>;
15
+ templates: Record<string, unknown>;
16
+ shells: Record<string, unknown>;
17
+ }
18
+ /** Optional filesystem probes. Omitted in unit tests, injected by the API handler. */
19
+ export interface RefResolver {
20
+ promptsDir: string;
21
+ pluginBaseDir: string;
22
+ join: (...parts: string[]) => string;
23
+ exists: (absPath: string) => boolean;
24
+ isAbsolute: (p: string) => boolean;
25
+ }
26
+ /** `__active__` is the runtime-resolved default agent (prompt-builder.ts:20), not a config entity. */
27
+ export declare const ACTIVE_AGENT = "__active__";
28
+ export declare const stageSchema: z.ZodObject<{
29
+ promptTemplate: z.ZodString;
30
+ continuesSession: z.ZodOptional<z.ZodBoolean>;
31
+ description: z.ZodOptional<z.ZodString>;
32
+ }, z.core.$strip>;
33
+ export declare const conditionSchema: z.ZodObject<{
34
+ type: z.ZodEnum<{
35
+ always: "always";
36
+ convergence: "convergence";
37
+ output_contains: "output_contains";
38
+ output_not_contains: "output_not_contains";
39
+ }>;
40
+ marker: z.ZodOptional<z.ZodString>;
41
+ pattern: z.ZodOptional<z.ZodString>;
42
+ maxIterations: z.ZodOptional<z.ZodNumber>;
43
+ }, z.core.$strip>;
44
+ export declare const transitionSchema: z.ZodObject<{
45
+ from: z.ZodString;
46
+ to: z.ZodString;
47
+ condition: z.ZodObject<{
48
+ type: z.ZodEnum<{
49
+ always: "always";
50
+ convergence: "convergence";
51
+ output_contains: "output_contains";
52
+ output_not_contains: "output_not_contains";
53
+ }>;
54
+ marker: z.ZodOptional<z.ZodString>;
55
+ pattern: z.ZodOptional<z.ZodString>;
56
+ maxIterations: z.ZodOptional<z.ZodNumber>;
57
+ }, z.core.$strip>;
58
+ }, z.core.$strip>;
59
+ export declare const hookConfigSchema: z.ZodObject<{
60
+ command: z.ZodString;
61
+ args: z.ZodOptional<z.ZodArray<z.ZodString>>;
62
+ timeout: z.ZodOptional<z.ZodNumber>;
63
+ }, z.core.$strip>;
64
+ export declare const hooksSchema: z.ZodObject<{
65
+ onStart: z.ZodOptional<z.ZodObject<{
66
+ command: z.ZodString;
67
+ args: z.ZodOptional<z.ZodArray<z.ZodString>>;
68
+ timeout: z.ZodOptional<z.ZodNumber>;
69
+ }, z.core.$strip>>;
70
+ onTransition: z.ZodOptional<z.ZodObject<{
71
+ command: z.ZodString;
72
+ args: z.ZodOptional<z.ZodArray<z.ZodString>>;
73
+ timeout: z.ZodOptional<z.ZodNumber>;
74
+ }, z.core.$strip>>;
75
+ onEnd: z.ZodOptional<z.ZodObject<{
76
+ command: z.ZodString;
77
+ args: z.ZodOptional<z.ZodArray<z.ZodString>>;
78
+ timeout: z.ZodOptional<z.ZodNumber>;
79
+ }, z.core.$strip>>;
80
+ }, z.core.$strip>;
81
+ export declare const agentSchema: z.ZodObject<{
82
+ name: z.ZodString;
83
+ description: z.ZodOptional<z.ZodString>;
84
+ profile: z.ZodString;
85
+ persistSession: z.ZodBoolean;
86
+ directive: z.ZodOptional<z.ZodString>;
87
+ systemPrompt: z.ZodOptional<z.ZodString>;
88
+ promptTemplate: z.ZodOptional<z.ZodString>;
89
+ claudeAgent: z.ZodOptional<z.ZodString>;
90
+ outputStyle: z.ZodOptional<z.ZodString>;
91
+ tools: z.ZodOptional<z.ZodString>;
92
+ pluginDirs: z.ZodOptional<z.ZodArray<z.ZodString>>;
93
+ mcpComposition: z.ZodOptional<z.ZodEnum<{
94
+ direct: "direct";
95
+ "thread-control": "thread-control";
96
+ none: "none";
97
+ "benchmark-thread-run": "benchmark-thread-run";
98
+ }>>;
99
+ stages: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
100
+ promptTemplate: z.ZodString;
101
+ continuesSession: z.ZodOptional<z.ZodBoolean>;
102
+ description: z.ZodOptional<z.ZodString>;
103
+ }, z.core.$strip>>>;
104
+ entryStage: z.ZodOptional<z.ZodString>;
105
+ }, z.core.$strip>;
106
+ export declare const agentRefOverrideSchema: z.ZodObject<{
107
+ ref: z.ZodString;
108
+ promptTemplate: z.ZodOptional<z.ZodString>;
109
+ directive: z.ZodOptional<z.ZodString>;
110
+ systemPrompt: z.ZodOptional<z.ZodString>;
111
+ persistSession: z.ZodOptional<z.ZodBoolean>;
112
+ claudeAgent: z.ZodOptional<z.ZodString>;
113
+ outputStyle: z.ZodOptional<z.ZodString>;
114
+ tools: z.ZodOptional<z.ZodString>;
115
+ pluginDirs: z.ZodOptional<z.ZodArray<z.ZodString>>;
116
+ }, z.core.$strip>;
117
+ export declare const agentRefSchema: z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
118
+ ref: z.ZodString;
119
+ promptTemplate: z.ZodOptional<z.ZodString>;
120
+ directive: z.ZodOptional<z.ZodString>;
121
+ systemPrompt: z.ZodOptional<z.ZodString>;
122
+ persistSession: z.ZodOptional<z.ZodBoolean>;
123
+ claudeAgent: z.ZodOptional<z.ZodString>;
124
+ outputStyle: z.ZodOptional<z.ZodString>;
125
+ tools: z.ZodOptional<z.ZodString>;
126
+ pluginDirs: z.ZodOptional<z.ZodArray<z.ZodString>>;
127
+ }, z.core.$strip>]>;
128
+ export declare const templateSchema: z.ZodObject<{
129
+ name: z.ZodOptional<z.ZodString>;
130
+ description: z.ZodString;
131
+ agents: z.ZodArray<z.ZodUnion<readonly [z.ZodString, z.ZodObject<{
132
+ ref: z.ZodString;
133
+ promptTemplate: z.ZodOptional<z.ZodString>;
134
+ directive: z.ZodOptional<z.ZodString>;
135
+ systemPrompt: z.ZodOptional<z.ZodString>;
136
+ persistSession: z.ZodOptional<z.ZodBoolean>;
137
+ claudeAgent: z.ZodOptional<z.ZodString>;
138
+ outputStyle: z.ZodOptional<z.ZodString>;
139
+ tools: z.ZodOptional<z.ZodString>;
140
+ pluginDirs: z.ZodOptional<z.ZodArray<z.ZodString>>;
141
+ }, z.core.$strip>]>>;
142
+ transitions: z.ZodArray<z.ZodObject<{
143
+ from: z.ZodString;
144
+ to: z.ZodString;
145
+ condition: z.ZodObject<{
146
+ type: z.ZodEnum<{
147
+ always: "always";
148
+ convergence: "convergence";
149
+ output_contains: "output_contains";
150
+ output_not_contains: "output_not_contains";
151
+ }>;
152
+ marker: z.ZodOptional<z.ZodString>;
153
+ pattern: z.ZodOptional<z.ZodString>;
154
+ maxIterations: z.ZodOptional<z.ZodNumber>;
155
+ }, z.core.$strip>;
156
+ }, z.core.$strip>>;
157
+ entryAgent: z.ZodString;
158
+ entryStage: z.ZodOptional<z.ZodString>;
159
+ maxTotalSteps: z.ZodNumber;
160
+ maxTotalCostUsd: z.ZodOptional<z.ZodNumber>;
161
+ disableHooks: z.ZodOptional<z.ZodBoolean>;
162
+ hooks: z.ZodOptional<z.ZodObject<{
163
+ onStart: z.ZodOptional<z.ZodObject<{
164
+ command: z.ZodString;
165
+ args: z.ZodOptional<z.ZodArray<z.ZodString>>;
166
+ timeout: z.ZodOptional<z.ZodNumber>;
167
+ }, z.core.$strip>>;
168
+ onTransition: z.ZodOptional<z.ZodObject<{
169
+ command: z.ZodString;
170
+ args: z.ZodOptional<z.ZodArray<z.ZodString>>;
171
+ timeout: z.ZodOptional<z.ZodNumber>;
172
+ }, z.core.$strip>>;
173
+ onEnd: z.ZodOptional<z.ZodObject<{
174
+ command: z.ZodString;
175
+ args: z.ZodOptional<z.ZodArray<z.ZodString>>;
176
+ timeout: z.ZodOptional<z.ZodNumber>;
177
+ }, z.core.$strip>>;
178
+ }, z.core.$strip>>;
179
+ }, z.core.$strip>;
180
+ export declare const shellBindingSchema: z.ZodObject<{
181
+ shell: z.ZodString;
182
+ description: z.ZodOptional<z.ZodString>;
183
+ maxTotalSteps: z.ZodOptional<z.ZodNumber>;
184
+ }, z.core.$strip>;
185
+ export declare const shellSchema: z.ZodObject<{
186
+ params: z.ZodArray<z.ZodString>;
187
+ agents: z.ZodArray<z.ZodString>;
188
+ transitions: z.ZodArray<z.ZodObject<{
189
+ from: z.ZodString;
190
+ to: z.ZodString;
191
+ condition: z.ZodObject<{
192
+ type: z.ZodEnum<{
193
+ always: "always";
194
+ convergence: "convergence";
195
+ output_contains: "output_contains";
196
+ output_not_contains: "output_not_contains";
197
+ }>;
198
+ marker: z.ZodOptional<z.ZodString>;
199
+ pattern: z.ZodOptional<z.ZodString>;
200
+ maxIterations: z.ZodOptional<z.ZodNumber>;
201
+ }, z.core.$strip>;
202
+ }, z.core.$strip>>;
203
+ entryAgent: z.ZodString;
204
+ entryStage: z.ZodOptional<z.ZodString>;
205
+ maxTotalSteps: z.ZodNumber;
206
+ maxTotalCostUsd: z.ZodOptional<z.ZodNumber>;
207
+ hooks: z.ZodOptional<z.ZodObject<{
208
+ onStart: z.ZodOptional<z.ZodObject<{
209
+ command: z.ZodString;
210
+ args: z.ZodOptional<z.ZodArray<z.ZodString>>;
211
+ timeout: z.ZodOptional<z.ZodNumber>;
212
+ }, z.core.$strip>>;
213
+ onTransition: z.ZodOptional<z.ZodObject<{
214
+ command: z.ZodString;
215
+ args: z.ZodOptional<z.ZodArray<z.ZodString>>;
216
+ timeout: z.ZodOptional<z.ZodNumber>;
217
+ }, z.core.$strip>>;
218
+ onEnd: z.ZodOptional<z.ZodObject<{
219
+ command: z.ZodString;
220
+ args: z.ZodOptional<z.ZodArray<z.ZodString>>;
221
+ timeout: z.ZodOptional<z.ZodNumber>;
222
+ }, z.core.$strip>>;
223
+ }, z.core.$strip>>;
224
+ }, z.core.$strip>;
225
+ /** Names of the templates whose definition mentions this agent or shell. */
226
+ export declare function dependentTemplates(kind: EntityKind, name: string, registry: RawRegistry): string[];
227
+ /**
228
+ * Validate one entity against the registry it will live in. The caller is expected to pass a
229
+ * registry with the candidate already swapped in, so cross-entity references resolve against the
230
+ * post-save world rather than the current one.
231
+ */
232
+ export declare function validateEntity(kind: EntityKind, name: string, body: unknown, registry: RawRegistry, refs?: RefResolver): ValidationResult;
233
+ /** Validate every entity in a registry. Key format: `<kind>:<name>`. */
234
+ export declare function validateRegistry(registry: RawRegistry, refs?: RefResolver): Map<string, ValidationResult>;
235
+ /** The only I/O in this module: read `<dir>/{agents,templates,shells}/*.json` as raw bodies.
236
+ * An unparseable file lands as `null`, which every validator reports as a root-level error. */
237
+ export declare function rawRegistryFromDir(dir: string, io: {
238
+ readdirSync: (p: string) => string[];
239
+ readFileSync: (p: string, enc: 'utf8') => string;
240
+ existsSync: (p: string) => boolean;
241
+ join: (...parts: string[]) => string;
242
+ }): RawRegistry;
243
+ /** Copy of a registry with one entity replaced — what a save would produce. */
244
+ export declare function withCandidate(registry: RawRegistry, kind: EntityKind, name: string, body: unknown): RawRegistry;