@cortex-agent/server 2026.8.3 → 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 (224) 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/core/utils.d.ts +21 -1
  67. package/dist/core/utils.js +37 -1
  68. package/dist/domain/agent-run/agent-run-cli.js +3 -1
  69. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.d.ts +31 -0
  70. package/dist/domain/agent-run/benchmark-local-thread-orchestrator.js +231 -24
  71. package/dist/domain/agent-run/benchmark-thread-identity.d.ts +15 -2
  72. package/dist/domain/agent-run/benchmark-thread-identity.js +123 -34
  73. package/dist/domain/agent-run/identity.d.ts +5 -0
  74. package/dist/domain/agent-run/identity.js +4 -1
  75. package/dist/domain/agent-run/journal.d.ts +3 -2
  76. package/dist/domain/agent-run/manifest.js +11 -4
  77. package/dist/domain/agent-run/pinned-node-process.d.ts +4 -0
  78. package/dist/domain/agent-run/pinned-node-process.js +9 -0
  79. package/dist/domain/agent-run/role-surface.d.ts +2 -2
  80. package/dist/domain/agent-run/role-surface.js +7 -3
  81. package/dist/domain/agent-run/run-config.d.ts +10 -1
  82. package/dist/domain/agent-run/run-config.js +57 -6
  83. package/dist/domain/agent-run/runner.js +149 -31
  84. package/dist/domain/agents/facade.d.ts +37 -122
  85. package/dist/domain/agents/facade.js +47 -115
  86. package/dist/domain/agents/spawn-config.d.ts +135 -0
  87. package/dist/domain/agents/spawn-config.js +121 -0
  88. package/dist/domain/benchmark/accounting-reconciliation.d.ts +98 -0
  89. package/dist/domain/benchmark/accounting-reconciliation.js +218 -0
  90. package/dist/domain/benchmark/arm-schema.d.ts +43 -0
  91. package/dist/domain/benchmark/arm-schema.js +243 -0
  92. package/dist/domain/benchmark/capabilities.d.ts +4 -0
  93. package/dist/domain/benchmark/capabilities.js +54 -0
  94. package/dist/domain/benchmark/decimal-text.d.ts +27 -0
  95. package/dist/domain/benchmark/decimal-text.js +67 -0
  96. package/dist/domain/benchmark/lease-echo.d.ts +43 -0
  97. package/dist/domain/benchmark/lease-echo.js +56 -0
  98. package/dist/domain/benchmark/policy-backed-runtime-deps.d.ts +14 -0
  99. package/dist/domain/benchmark/policy-backed-runtime-deps.js +47 -0
  100. package/dist/domain/benchmark/policy-compiler.d.ts +68 -0
  101. package/dist/domain/benchmark/policy-compiler.js +680 -0
  102. package/dist/domain/benchmark/resolved-policy.d.ts +110 -0
  103. package/dist/domain/benchmark/resolved-policy.js +195 -0
  104. package/dist/domain/benchmark/trial-adapter-factory.d.ts +38 -0
  105. package/dist/domain/benchmark/trial-adapter-factory.js +165 -0
  106. package/dist/domain/benchmark/trial-thread-adapter.d.ts +25 -0
  107. package/dist/domain/benchmark/trial-thread-adapter.js +106 -0
  108. package/dist/domain/benchmark/variant-proposal.d.ts +45 -0
  109. package/dist/domain/benchmark/variant-proposal.js +42 -0
  110. package/dist/domain/benchmark/workspace-lease.d.ts +99 -0
  111. package/dist/domain/benchmark/workspace-lease.js +272 -0
  112. package/dist/domain/costs/codex-quota.d.ts +29 -0
  113. package/dist/domain/costs/codex-quota.js +102 -0
  114. package/dist/domain/costs/cost-tracker.d.ts +48 -9
  115. package/dist/domain/costs/cost-tracker.js +74 -18
  116. package/dist/domain/costs/rate-limit-throttle.d.ts +23 -1
  117. package/dist/domain/costs/rate-limit-throttle.js +61 -6
  118. package/dist/domain/costs/resume-registry.d.ts +3 -1
  119. package/dist/domain/costs/resume-registry.js +10 -1
  120. package/dist/domain/mcp/tools/benchmark-thread-run.d.ts +26 -2
  121. package/dist/domain/mcp/tools/benchmark-thread-run.js +63 -20
  122. package/dist/domain/mcp/tools/cost.js +15 -6
  123. package/dist/domain/pi-providers/custom-provider-model.d.ts +53 -0
  124. package/dist/domain/pi-providers/custom-provider-model.js +122 -0
  125. package/dist/domain/pi-providers/custom-provider-service.d.ts +59 -0
  126. package/dist/domain/pi-providers/custom-provider-service.js +143 -0
  127. package/dist/domain/pi-providers/gateway-route-store.d.ts +23 -0
  128. package/dist/domain/pi-providers/gateway-route-store.js +78 -0
  129. package/dist/domain/pi-providers/index.d.ts +4 -0
  130. package/dist/domain/pi-providers/index.js +8 -0
  131. package/dist/domain/pi-providers/models-json-store.d.ts +6 -0
  132. package/dist/domain/pi-providers/models-json-store.js +77 -0
  133. package/dist/domain/remote/client-hot-reload.d.ts +9 -1
  134. package/dist/domain/remote/client-hot-reload.js +60 -12
  135. package/dist/domain/scheduling/jobs/_shared.d.ts +4 -1
  136. package/dist/domain/scheduling/jobs/_shared.js +11 -2
  137. package/dist/domain/scheduling/jobs/scheduled-task.js +1 -0
  138. package/dist/domain/scheduling/jobs/task-dispatch.js +49 -54
  139. package/dist/domain/sessions/session-lifecycle.d.ts +22 -0
  140. package/dist/domain/sessions/session-lifecycle.js +20 -1
  141. package/dist/domain/system/install-cli.js +8 -3
  142. package/dist/domain/system/system-notice.d.ts +4 -1
  143. package/dist/domain/system/system-notice.js +6 -2
  144. package/dist/domain/tasks/dispatch-utils.d.ts +0 -4
  145. package/dist/domain/tasks/dispatch-utils.js +24 -37
  146. package/dist/domain/threads/runner.d.ts +16 -1
  147. package/dist/domain/threads/runner.js +62 -8
  148. package/dist/domain/threads/template-loader.d.ts +5 -0
  149. package/dist/domain/threads/template-loader.js +120 -36
  150. package/dist/domain/threads/template-validate.d.ts +244 -0
  151. package/dist/domain/threads/template-validate.js +574 -0
  152. package/dist/domain/threads/template-validate.parity.d.ts +1 -0
  153. package/dist/domain/threads/template-validate.parity.js +47 -0
  154. package/dist/domain/threads/template-writer.d.ts +55 -0
  155. package/dist/domain/threads/template-writer.js +131 -0
  156. package/dist/domain/ui-service/app-router.d.ts +143 -1
  157. package/dist/domain/ui-service/app-router.js +29 -3
  158. package/dist/domain/ui-service/input-schemas.d.ts +228 -4
  159. package/dist/domain/ui-service/input-schemas.js +132 -1
  160. package/dist/domain/ui-service/mutate/config.d.ts +10 -1
  161. package/dist/domain/ui-service/mutate/config.js +45 -5
  162. package/dist/domain/ui-service/mutate/custom-providers.d.ts +8 -0
  163. package/dist/domain/ui-service/mutate/custom-providers.js +37 -0
  164. package/dist/domain/ui-service/mutate/profiles.d.ts +21 -0
  165. package/dist/domain/ui-service/mutate/profiles.js +156 -0
  166. package/dist/domain/ui-service/mutate/schedules.d.ts +2 -1
  167. package/dist/domain/ui-service/mutate/schedules.js +53 -3
  168. package/dist/domain/ui-service/mutate/sessions.d.ts +2 -1
  169. package/dist/domain/ui-service/mutate/sessions.js +25 -1
  170. package/dist/domain/ui-service/mutate/system.d.ts +2 -1
  171. package/dist/domain/ui-service/mutate/system.js +17 -3
  172. package/dist/domain/ui-service/mutate/thread-templates.d.ts +4 -0
  173. package/dist/domain/ui-service/mutate/thread-templates.js +71 -0
  174. package/dist/domain/ui-service/query/config.js +30 -0
  175. package/dist/domain/ui-service/query/custom-providers.d.ts +8 -0
  176. package/dist/domain/ui-service/query/custom-providers.js +13 -0
  177. package/dist/domain/ui-service/query/machine-detail.d.ts +2 -0
  178. package/dist/domain/ui-service/query/machine-detail.js +56 -0
  179. package/dist/domain/ui-service/query/machine-probe.d.ts +18 -0
  180. package/dist/domain/ui-service/query/machine-probe.js +136 -0
  181. package/dist/domain/ui-service/query/schedules.js +5 -0
  182. package/dist/domain/ui-service/query/sessions.js +8 -2
  183. package/dist/domain/ui-service/query/thread-template-detail.d.ts +8 -0
  184. package/dist/domain/ui-service/query/thread-template-detail.js +94 -0
  185. package/dist/domain/ui-service/query/thread-templates.d.ts +5 -3
  186. package/dist/domain/ui-service/query/thread-templates.js +44 -7
  187. package/dist/domain/ui-service/types.d.ts +298 -7
  188. package/dist/domain/ui-service/ui-service.js +27 -3
  189. package/dist/entry/app.js +24 -3
  190. package/dist/entry/auth-cli.d.ts +4 -1
  191. package/dist/entry/auth-cli.js +10 -2
  192. package/dist/entry/cli-help.js +6 -2
  193. package/dist/entry/cli.js +2 -1
  194. package/dist/entry/daemon.d.ts +0 -11
  195. package/dist/entry/daemon.js +5 -49
  196. package/dist/entry/provider-cli.d.ts +16 -0
  197. package/dist/entry/provider-cli.js +203 -0
  198. package/dist/events/event-types.d.ts +2 -1
  199. package/dist/orchestration/agent-runner.js +3 -2
  200. package/dist/orchestration/routing/commands/cost.d.ts +8 -0
  201. package/dist/orchestration/routing/commands/cost.js +93 -21
  202. package/dist/orchestration/routing/commands/login-custom.d.ts +26 -0
  203. package/dist/orchestration/routing/commands/login-custom.js +89 -0
  204. package/dist/orchestration/routing/commands/login.d.ts +3 -0
  205. package/dist/orchestration/routing/commands/login.js +7 -0
  206. package/dist/orchestration/routing/message-router.js +48 -33
  207. package/dist/orchestration/routing/webhook.js +1 -1
  208. package/dist/orchestration/session-events.d.ts +2 -1
  209. package/dist/orchestration/session-events.js +1 -0
  210. package/dist/orchestration/thread-callback.js +1 -1
  211. package/dist/store/conversation-history-repo.d.ts +5 -1
  212. package/dist/store/conversation-history-repo.js +2 -1
  213. package/dist/store/cost-repo.d.ts +17 -0
  214. package/dist/store/cost-repo.js +47 -5
  215. package/dist/store/profile-repo.d.ts +0 -10
  216. package/dist/store/profile-repo.js +34 -56
  217. package/dist/store/session-registry-repo.d.ts +12 -0
  218. package/dist/store/session-registry-repo.js +16 -0
  219. package/package.json +1 -1
  220. package/web/dist/assets/index-DYMfaAi4.css +1 -0
  221. package/web/dist/assets/index-uOoZjGKa.js +141 -0
  222. package/web/dist/index.html +2 -2
  223. package/web/dist/assets/index-DrNx9R6c.js +0 -139
  224. package/web/dist/assets/index-zpf3OSKC.css +0 -1
@@ -0,0 +1,574 @@
1
+ // input: a raw thread-template entity (agent / template / shell) + a raw registry snapshot
2
+ // output: validateEntity / validateRegistry / rawRegistryFromDir → { errors, warnings }
3
+ // pos: The validation layer the config never had. The loader is fail-soft (it skips a bad file
4
+ // with a warning) and the executor re-reads templates on EVERY step, so a broken edit does
5
+ // not fail loudly — it makes a running thread stall at `no_matching_transition`. This module
6
+ // is the single place that says what "broken" means, and is consumed by the write path
7
+ // (errors block a save) and by loadConfig (warnings are logged, never enforced).
8
+ // Errors are the confident set: parse failures, name/filename mismatch, missing required
9
+ // fields, broken cross-references, invalid regexes, shell expansion throws. Anything merely
10
+ // unrecognised is a warning, so a schema that has drifted can never lock a user out.
11
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
12
+ import { z } from 'zod';
13
+ import { isShellBinding, expandShell } from './shell-templates.js';
14
+ import { parseTarget } from './utils.js';
15
+ /** `__active__` is the runtime-resolved default agent (prompt-builder.ts:20), not a config entity. */
16
+ export const ACTIVE_AGENT = '__active__';
17
+ const FILE_REF_PREFIX = 'file:';
18
+ const PROMPT_FIELD_DIRS = {
19
+ directive: 'directives',
20
+ promptTemplate: 'promptTemplates',
21
+ systemPrompt: 'systemPrompts',
22
+ };
23
+ // --- Structural schemas (mirror core/types/thread-types.ts) ---
24
+ // Exported for the compile-time parity guard in template-validate.parity.ts, which pins them
25
+ // against the interfaces in core/types/thread-types.ts so the two cannot drift apart silently.
26
+ export const stageSchema = z.object({
27
+ promptTemplate: z.string(),
28
+ continuesSession: z.boolean().optional(),
29
+ description: z.string().optional(),
30
+ });
31
+ export const conditionSchema = z.object({
32
+ type: z.enum(['always', 'convergence', 'output_contains', 'output_not_contains']),
33
+ marker: z.string().optional(),
34
+ pattern: z.string().optional(),
35
+ maxIterations: z.number().int().positive().optional(),
36
+ });
37
+ export const transitionSchema = z.object({
38
+ from: z.string().min(1),
39
+ to: z.string().min(1),
40
+ condition: conditionSchema,
41
+ });
42
+ export const hookConfigSchema = z.object({
43
+ command: z.string().min(1),
44
+ args: z.array(z.string()).optional(),
45
+ timeout: z.number().int().positive().optional(),
46
+ });
47
+ export const hooksSchema = z.object({
48
+ onStart: hookConfigSchema.optional(),
49
+ onTransition: hookConfigSchema.optional(),
50
+ onEnd: hookConfigSchema.optional(),
51
+ });
52
+ export const agentSchema = z.object({
53
+ name: z.string().min(1),
54
+ description: z.string().optional(),
55
+ profile: z.string().min(1),
56
+ persistSession: z.boolean(),
57
+ directive: z.string().optional(),
58
+ systemPrompt: z.string().optional(),
59
+ promptTemplate: z.string().optional(),
60
+ claudeAgent: z.string().optional(),
61
+ outputStyle: z.string().optional(),
62
+ tools: z.string().optional(),
63
+ pluginDirs: z.array(z.string()).optional(),
64
+ mcpComposition: z.enum(['direct', 'thread-control', 'none', 'benchmark-thread-run']).optional(),
65
+ stages: z.record(z.string(), stageSchema).optional(),
66
+ entryStage: z.string().optional(),
67
+ });
68
+ export const agentRefOverrideSchema = z.object({
69
+ ref: z.string().min(1),
70
+ promptTemplate: z.string().optional(),
71
+ directive: z.string().optional(),
72
+ systemPrompt: z.string().optional(),
73
+ persistSession: z.boolean().optional(),
74
+ claudeAgent: z.string().optional(),
75
+ outputStyle: z.string().optional(),
76
+ tools: z.string().optional(),
77
+ pluginDirs: z.array(z.string()).optional(),
78
+ });
79
+ export const agentRefSchema = z.union([z.string().min(1), agentRefOverrideSchema]);
80
+ export const templateSchema = z.object({
81
+ name: z.string().min(1).optional(), // may be omitted in directory form; checked against filename
82
+ description: z.string(),
83
+ agents: z.array(agentRefSchema).min(1),
84
+ transitions: z.array(transitionSchema),
85
+ entryAgent: z.string().min(1),
86
+ entryStage: z.string().optional(),
87
+ maxTotalSteps: z.number().int().positive(),
88
+ maxTotalCostUsd: z.number().positive().optional(),
89
+ disableHooks: z.boolean().optional(),
90
+ hooks: hooksSchema.optional(),
91
+ });
92
+ export const shellBindingSchema = z.object({
93
+ shell: z.string().min(1),
94
+ description: z.string().optional(),
95
+ maxTotalSteps: z.number().int().positive().optional(),
96
+ });
97
+ export const shellSchema = z.object({
98
+ params: z.array(z.string().min(1)),
99
+ agents: z.array(z.string().min(1)),
100
+ transitions: z.array(transitionSchema),
101
+ entryAgent: z.string().min(1),
102
+ entryStage: z.string().optional(),
103
+ maxTotalSteps: z.number().int().positive(),
104
+ maxTotalCostUsd: z.number().positive().optional(),
105
+ hooks: hooksSchema.optional(),
106
+ });
107
+ // Keys the schemas know about. Anything else is a warning, never an error. Shell bindings are
108
+ // excluded on purpose: their parameter values live alongside the reserved keys by design.
109
+ const AGENT_KEYS = new Set(Object.keys(agentSchema.shape));
110
+ const TEMPLATE_KEYS = new Set(Object.keys(templateSchema.shape));
111
+ const SHELL_KEYS = new Set(Object.keys(shellSchema.shape));
112
+ // --- Helpers ---
113
+ function formatPath(segments) {
114
+ let out = '';
115
+ for (const seg of segments) {
116
+ if (typeof seg === 'number')
117
+ out += `[${seg}]`;
118
+ else
119
+ out += out === '' ? String(seg) : `.${String(seg)}`;
120
+ }
121
+ return out;
122
+ }
123
+ function zodIssues(result) {
124
+ if (result.success)
125
+ return [];
126
+ return result.error.issues.map((issue) => ({
127
+ path: formatPath(issue.path) || '(root)',
128
+ message: issue.message,
129
+ }));
130
+ }
131
+ function unknownKeyWarnings(body, known) {
132
+ return Object.keys(body)
133
+ .filter((key) => !known.has(key))
134
+ .map((key) => ({ path: key, message: `Unrecognised field "${key}" — it will be ignored` }));
135
+ }
136
+ function isPlainObject(value) {
137
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
138
+ }
139
+ /** Registry agents as AgentDefinitions, for the shell expander. Non-object entries are dropped. */
140
+ function agentDefs(registry) {
141
+ const out = {};
142
+ for (const [name, body] of Object.entries(registry.agents)) {
143
+ if (isPlainObject(body))
144
+ out[name] = body;
145
+ }
146
+ return out;
147
+ }
148
+ function stagesOf(agent) {
149
+ if (!isPlainObject(agent) || !isPlainObject(agent.stages))
150
+ return null;
151
+ return agent.stages;
152
+ }
153
+ /** Every `{token}` in a string, without the braces. */
154
+ function placeholderTokens(value) {
155
+ return [...value.matchAll(/\{([^}]+)\}/g)].map((m) => m[1]);
156
+ }
157
+ function checkRegex(pattern, path, errors) {
158
+ try {
159
+ new RegExp(pattern);
160
+ }
161
+ catch (error) {
162
+ errors.push({
163
+ path,
164
+ message: `Invalid regex: ${error instanceof Error ? error.message : String(error)} — this transition can never fire`,
165
+ });
166
+ }
167
+ }
168
+ /**
169
+ * Condition sanity. A convergence with no marker degenerates into a plain loop counter and an empty
170
+ * pattern matches everything — both run, so both are warnings; an unparseable regex cannot, so it is
171
+ * an error (`evaluatePatternMatch` catches the throw and the edge is dead — state-machine.ts:456).
172
+ */
173
+ function checkCondition(condition, path, result) {
174
+ if (!isPlainObject(condition))
175
+ return;
176
+ const type = condition.type;
177
+ if (type === 'convergence' && typeof condition.marker !== 'string') {
178
+ result.warnings.push({
179
+ path: `${path}.marker`,
180
+ message: 'convergence without a marker never converges — it only stops at maxIterations',
181
+ });
182
+ }
183
+ if (type === 'output_contains' || type === 'output_not_contains') {
184
+ if (typeof condition.pattern !== 'string' || condition.pattern === '') {
185
+ result.warnings.push({
186
+ path: `${path}.pattern`,
187
+ message: `${String(type)} with an empty pattern matches every output`,
188
+ });
189
+ }
190
+ else {
191
+ checkRegex(condition.pattern, `${path}.pattern`, result.errors);
192
+ }
193
+ }
194
+ }
195
+ // --- Agent validation ---
196
+ function checkPromptFileRef(field, value, path, refs, warnings) {
197
+ if (!refs || typeof value !== 'string' || !value.startsWith(FILE_REF_PREFIX))
198
+ return;
199
+ const subdir = PROMPT_FIELD_DIRS[field];
200
+ if (!subdir)
201
+ return;
202
+ const filename = value.slice(FILE_REF_PREFIX.length);
203
+ if (!refs.exists(refs.join(refs.promptsDir, subdir, filename))) {
204
+ warnings.push({
205
+ path,
206
+ message: `prompts/${subdir}/${filename} does not exist — the literal string "${value}" will be used as the prompt`,
207
+ });
208
+ }
209
+ }
210
+ function validateAgent(name, body, refs) {
211
+ const result = {
212
+ errors: zodIssues(agentSchema.safeParse(body)),
213
+ warnings: unknownKeyWarnings(body, AGENT_KEYS),
214
+ };
215
+ // The map key is the filename basename, and the loader hard-skips a mismatch (template-loader.ts:220).
216
+ if (typeof body.name === 'string' && body.name !== name) {
217
+ result.errors.push({
218
+ path: 'name',
219
+ message: `name "${body.name}" must equal the filename "${name}" — the loader skips the file otherwise`,
220
+ });
221
+ }
222
+ const stages = stagesOf(body);
223
+ if (stages) {
224
+ const stageNames = Object.keys(stages);
225
+ if (stageNames.length === 0) {
226
+ result.warnings.push({ path: 'stages', message: 'stages is empty — the agent has no prompt to run' });
227
+ }
228
+ if (typeof body.entryStage === 'string' && !stageNames.includes(body.entryStage)) {
229
+ result.errors.push({
230
+ path: 'entryStage',
231
+ message: `entryStage "${body.entryStage}" is not one of the declared stages (${stageNames.join(', ')})`,
232
+ });
233
+ }
234
+ if (body.entryStage === undefined && stageNames.length > 1) {
235
+ result.warnings.push({
236
+ path: 'entryStage',
237
+ message: `no entryStage with ${stageNames.length} stages — "${stageNames[0]}" is silently used`,
238
+ });
239
+ }
240
+ if (typeof body.promptTemplate === 'string') {
241
+ result.warnings.push({
242
+ path: 'promptTemplate',
243
+ message: 'promptTemplate is ignored when stages is declared',
244
+ });
245
+ }
246
+ for (const [stageName, stage] of Object.entries(stages)) {
247
+ if (isPlainObject(stage)) {
248
+ checkPromptFileRef('promptTemplate', stage.promptTemplate, `stages.${stageName}.promptTemplate`, refs, result.warnings);
249
+ }
250
+ }
251
+ }
252
+ else if (body.promptTemplate === undefined) {
253
+ result.warnings.push({
254
+ path: 'promptTemplate',
255
+ message: 'agent declares neither promptTemplate nor stages — it has no prompt to run',
256
+ });
257
+ }
258
+ for (const field of ['directive', 'systemPrompt', 'promptTemplate']) {
259
+ checkPromptFileRef(field, body[field], field, refs, result.warnings);
260
+ }
261
+ if (refs && Array.isArray(body.pluginDirs)) {
262
+ body.pluginDirs.forEach((dir, i) => {
263
+ if (typeof dir !== 'string')
264
+ return;
265
+ const abs = refs.isAbsolute(dir) ? dir : refs.join(refs.pluginBaseDir, dir);
266
+ if (!refs.exists(abs)) {
267
+ result.warnings.push({ path: `pluginDirs[${i}]`, message: `plugin directory "${dir}" does not exist` });
268
+ }
269
+ });
270
+ }
271
+ return result;
272
+ }
273
+ // --- Template validation ---
274
+ function agentRefName(ref) {
275
+ if (typeof ref === 'string')
276
+ return ref;
277
+ if (isPlainObject(ref) && typeof ref.ref === 'string')
278
+ return ref.ref;
279
+ return null;
280
+ }
281
+ /**
282
+ * An endpoint is `agent` or `agent:stage`. The agent must be one the template declares — a target
283
+ * outside the slot roster stalls the thread (`resolveTemplateNextStep` finds no slot and returns
284
+ * null, state-machine.ts:270) and a source outside it is an edge that can never match. A pinned
285
+ * stage the agent does not have is the same class of mistake the shell expander already throws on.
286
+ */
287
+ function checkEndpoint(endpoint, path, slots, registry, errors) {
288
+ const { agent, stage } = parseTarget(endpoint);
289
+ if (!slots.has(agent)) {
290
+ errors.push({
291
+ path,
292
+ message: `"${agent}" is not one of this template's agents (${[...slots].join(', ')})`,
293
+ });
294
+ return;
295
+ }
296
+ if (stage === null || agent === ACTIVE_AGENT)
297
+ return;
298
+ const stages = stagesOf(registry.agents[agent]);
299
+ if (!stages) {
300
+ errors.push({ path, message: `agent "${agent}" declares no stages, so ":${stage}" cannot be selected` });
301
+ }
302
+ else if (!(stage in stages)) {
303
+ errors.push({
304
+ path,
305
+ message: `agent "${agent}" has no "${stage}" stage (has: ${Object.keys(stages).join(', ')})`,
306
+ });
307
+ }
308
+ }
309
+ function validateFullTemplate(name, body, registry) {
310
+ const result = {
311
+ errors: zodIssues(templateSchema.safeParse(body)),
312
+ warnings: unknownKeyWarnings(body, TEMPLATE_KEYS),
313
+ };
314
+ if (typeof body.name === 'string' && body.name !== name) {
315
+ result.errors.push({
316
+ path: 'name',
317
+ message: `name "${body.name}" must equal the filename "${name}" — the loader skips the file otherwise`,
318
+ });
319
+ }
320
+ const refs = Array.isArray(body.agents) ? body.agents : [];
321
+ const slots = new Set();
322
+ refs.forEach((ref, i) => {
323
+ const agentName = agentRefName(ref);
324
+ if (agentName === null)
325
+ return; // shape error already reported by zod
326
+ slots.add(agentName);
327
+ if (agentName === ACTIVE_AGENT)
328
+ return;
329
+ if (!(agentName in registry.agents)) {
330
+ result.errors.push({ path: `agents[${i}]`, message: `unknown agent "${agentName}"` });
331
+ }
332
+ });
333
+ if (typeof body.entryAgent === 'string' && !slots.has(body.entryAgent)) {
334
+ result.errors.push({
335
+ path: 'entryAgent',
336
+ message: `entryAgent "${body.entryAgent}" is not in this template's agents list — the thread cannot take its first step`,
337
+ });
338
+ }
339
+ if (typeof body.entryStage === 'string' && typeof body.entryAgent === 'string') {
340
+ const stages = stagesOf(registry.agents[body.entryAgent]);
341
+ if (stages && !(body.entryStage in stages)) {
342
+ result.errors.push({
343
+ path: 'entryStage',
344
+ message: `entryAgent "${body.entryAgent}" has no "${body.entryStage}" stage (has: ${Object.keys(stages).join(', ')})`,
345
+ });
346
+ }
347
+ else if (!stages && body.entryAgent !== ACTIVE_AGENT) {
348
+ result.warnings.push({
349
+ path: 'entryStage',
350
+ message: `entryAgent "${body.entryAgent}" declares no stages — entryStage is ignored`,
351
+ });
352
+ }
353
+ }
354
+ const reached = new Set();
355
+ if (typeof body.entryAgent === 'string')
356
+ reached.add(body.entryAgent);
357
+ const transitions = Array.isArray(body.transitions) ? body.transitions : [];
358
+ transitions.forEach((rule, i) => {
359
+ if (!isPlainObject(rule))
360
+ return;
361
+ if (typeof rule.from === 'string')
362
+ checkEndpoint(rule.from, `transitions[${i}].from`, slots, registry, result.errors);
363
+ if (typeof rule.to === 'string') {
364
+ checkEndpoint(rule.to, `transitions[${i}].to`, slots, registry, result.errors);
365
+ reached.add(parseTarget(rule.to).agent);
366
+ }
367
+ checkCondition(rule.condition, `transitions[${i}].condition`, result);
368
+ });
369
+ for (const slot of slots) {
370
+ if (!reached.has(slot)) {
371
+ result.warnings.push({ path: 'agents', message: `agent "${slot}" is never reached by any transition` });
372
+ }
373
+ }
374
+ return result;
375
+ }
376
+ function validateShellBinding(name, body, registry) {
377
+ const result = {
378
+ errors: zodIssues(shellBindingSchema.safeParse(body)),
379
+ warnings: [],
380
+ };
381
+ const shell = registry.shells[typeof body.shell === 'string' ? body.shell : ''];
382
+ if (!isPlainObject(shell)) {
383
+ result.errors.push({ path: 'shell', message: `unknown shell "${String(body.shell)}"` });
384
+ return result;
385
+ }
386
+ // Dry-run the real expander rather than re-deriving its seven checks (missing param, unknown
387
+ // placeholder, agent not found, missing entryStage, missing stage) and letting them drift.
388
+ try {
389
+ expandShell(name, body, shell, agentDefs(registry));
390
+ }
391
+ catch (error) {
392
+ result.errors.push({ path: '(root)', message: error instanceof Error ? error.message : String(error) });
393
+ }
394
+ // Missing params are already reported by expandShell; the reverse — a binding key the shell
395
+ // does not declare — is silently ignored at load time, so it is worth a warning.
396
+ if (Array.isArray(shell.params)) {
397
+ const declared = new Set(shell.params.filter((p) => typeof p === 'string'));
398
+ for (const key of Object.keys(body)) {
399
+ if (!declared.has(key) && !['shell', 'description', 'maxTotalSteps'].includes(key)) {
400
+ result.warnings.push({
401
+ path: key,
402
+ message: `"${key}" is not a parameter of shell "${String(body.shell)}" (declares: ${[...declared].join(', ')})`,
403
+ });
404
+ }
405
+ }
406
+ }
407
+ return result;
408
+ }
409
+ // --- Shell validation ---
410
+ function validateShell(body) {
411
+ const result = {
412
+ errors: zodIssues(shellSchema.safeParse(body)),
413
+ warnings: unknownKeyWarnings(body, SHELL_KEYS),
414
+ };
415
+ const params = new Set((Array.isArray(body.params) ? body.params : []).filter((p) => typeof p === 'string'));
416
+ const checkTokens = (value, path) => {
417
+ if (typeof value !== 'string')
418
+ return;
419
+ for (const token of placeholderTokens(value)) {
420
+ const dot = token.indexOf('.');
421
+ const param = dot < 0 ? token : token.slice(0, dot);
422
+ const prop = dot < 0 ? '' : token.slice(dot + 1);
423
+ if (!params.has(param)) {
424
+ result.errors.push({ path, message: `unknown placeholder "{${token}}" — "${param}" is not in params` });
425
+ }
426
+ else if (prop !== '' && prop !== 'entryStage') {
427
+ result.errors.push({ path, message: `unknown placeholder property "{${token}}" — only .entryStage is supported` });
428
+ }
429
+ }
430
+ };
431
+ (Array.isArray(body.agents) ? body.agents : []).forEach((a, i) => checkTokens(a, `agents[${i}]`));
432
+ (Array.isArray(body.transitions) ? body.transitions : []).forEach((rule, i) => {
433
+ if (!isPlainObject(rule))
434
+ return;
435
+ checkTokens(rule.from, `transitions[${i}].from`);
436
+ checkTokens(rule.to, `transitions[${i}].to`);
437
+ checkCondition(rule.condition, `transitions[${i}].condition`, result);
438
+ });
439
+ checkTokens(body.entryAgent, 'entryAgent');
440
+ checkTokens(body.entryStage, 'entryStage');
441
+ if (isPlainObject(body.hooks)) {
442
+ for (const [phase, hook] of Object.entries(body.hooks)) {
443
+ if (!isPlainObject(hook))
444
+ continue;
445
+ checkTokens(hook.command, `hooks.${phase}.command`);
446
+ (Array.isArray(hook.args) ? hook.args : []).forEach((arg, i) => checkTokens(arg, `hooks.${phase}.args[${i}]`));
447
+ }
448
+ }
449
+ // A shell with no binding is inert; one with bindings is only as valid as its expansions, which
450
+ // the impact pass re-checks against every dependent template.
451
+ return result;
452
+ }
453
+ // --- Impact: what else breaks if this entity is saved ---
454
+ /** Names of the templates whose definition mentions this agent or shell. */
455
+ export function dependentTemplates(kind, name, registry) {
456
+ if (kind === 'template')
457
+ return [];
458
+ const out = [];
459
+ for (const [templateName, body] of Object.entries(registry.templates)) {
460
+ if (!isPlainObject(body))
461
+ continue;
462
+ if (kind === 'shell') {
463
+ if (body.shell === name)
464
+ out.push(templateName);
465
+ continue;
466
+ }
467
+ if (isShellBinding(body)) {
468
+ if (Object.values(body).some((v) => v === name))
469
+ out.push(templateName);
470
+ continue;
471
+ }
472
+ const refs = Array.isArray(body.agents) ? body.agents : [];
473
+ if (refs.some((ref) => agentRefName(ref) === name) || body.entryAgent === name)
474
+ out.push(templateName);
475
+ }
476
+ return out;
477
+ }
478
+ /**
479
+ * Re-validate every template that depends on this entity, so removing a stage from an agent or
480
+ * editing a shell surfaces the templates it breaks at save time instead of at the next step of a
481
+ * running thread. Reported against the dependent's name, not the edited field.
482
+ */
483
+ function impactIssues(kind, name, registry) {
484
+ const out = [];
485
+ for (const templateName of dependentTemplates(kind, name, registry)) {
486
+ const body = registry.templates[templateName];
487
+ if (!isPlainObject(body))
488
+ continue;
489
+ const { errors } = isShellBinding(body)
490
+ ? validateShellBinding(templateName, body, registry)
491
+ : validateFullTemplate(templateName, body, registry);
492
+ for (const issue of errors) {
493
+ out.push({ path: `template:${templateName}`, message: `${issue.path}: ${issue.message}` });
494
+ }
495
+ }
496
+ return out;
497
+ }
498
+ // --- Entry points ---
499
+ /**
500
+ * Validate one entity against the registry it will live in. The caller is expected to pass a
501
+ * registry with the candidate already swapped in, so cross-entity references resolve against the
502
+ * post-save world rather than the current one.
503
+ */
504
+ export function validateEntity(kind, name, body, registry, refs) {
505
+ if (!isPlainObject(body)) {
506
+ return { errors: [{ path: '(root)', message: 'Body must be a JSON object' }], warnings: [] };
507
+ }
508
+ let result;
509
+ if (kind === 'agent')
510
+ result = validateAgent(name, body, refs);
511
+ else if (kind === 'shell')
512
+ result = validateShell(body);
513
+ else if (isShellBinding(body)) {
514
+ result = validateShellBinding(name, body, registry);
515
+ }
516
+ else
517
+ result = validateFullTemplate(name, body, registry);
518
+ if (kind !== 'template')
519
+ result.errors.push(...impactIssues(kind, name, registry));
520
+ return result;
521
+ }
522
+ /** Validate every entity in a registry. Key format: `<kind>:<name>`. */
523
+ export function validateRegistry(registry, refs) {
524
+ const out = new Map();
525
+ const kinds = [
526
+ ['agent', registry.agents],
527
+ ['template', registry.templates],
528
+ ['shell', registry.shells],
529
+ ];
530
+ for (const [kind, entities] of kinds) {
531
+ for (const [name, body] of Object.entries(entities)) {
532
+ // Skip the impact pass here: validating the whole registry already covers every dependent.
533
+ const result = isPlainObject(body)
534
+ ? kind === 'agent'
535
+ ? validateAgent(name, body, refs)
536
+ : kind === 'shell'
537
+ ? validateShell(body)
538
+ : isShellBinding(body)
539
+ ? validateShellBinding(name, body, registry)
540
+ : validateFullTemplate(name, body, registry)
541
+ : { errors: [{ path: '(root)', message: 'Body must be a JSON object' }], warnings: [] };
542
+ out.set(`${kind}:${name}`, result);
543
+ }
544
+ }
545
+ return out;
546
+ }
547
+ /** The only I/O in this module: read `<dir>/{agents,templates,shells}/*.json` as raw bodies.
548
+ * An unparseable file lands as `null`, which every validator reports as a root-level error. */
549
+ export function rawRegistryFromDir(dir, io) {
550
+ const readKind = (sub) => {
551
+ const full = io.join(dir, sub);
552
+ if (!io.existsSync(full))
553
+ return {};
554
+ const out = {};
555
+ for (const file of io.readdirSync(full)) {
556
+ if (!file.endsWith('.json'))
557
+ continue;
558
+ const name = file.slice(0, -'.json'.length);
559
+ try {
560
+ out[name] = JSON.parse(io.readFileSync(io.join(full, file), 'utf8'));
561
+ }
562
+ catch {
563
+ out[name] = null;
564
+ }
565
+ }
566
+ return out;
567
+ };
568
+ return { agents: readKind('agents'), templates: readKind('templates'), shells: readKind('shells') };
569
+ }
570
+ /** Copy of a registry with one entity replaced — what a save would produce. */
571
+ export function withCandidate(registry, kind, name, body) {
572
+ const key = kind === 'agent' ? 'agents' : kind === 'template' ? 'templates' : 'shells';
573
+ return { ...registry, [key]: { ...registry[key], [name]: body } };
574
+ }
@@ -0,0 +1 @@
1
+ export declare const THREAD_TEMPLATE_SCHEMA_PARITY: readonly [true, true, true, true, true, true, true, true, true, true];
@@ -0,0 +1,47 @@
1
+ // input: the zod schemas in template-validate.ts and the interfaces in core/types/thread-types.ts
2
+ // output: compile-time-only parity assertions (no runtime behaviour)
3
+ // pos: Anti-drift boundary for the thread-template validator. The validator's schemas are a
4
+ // second description of a shape the TS interfaces already describe, so they can drift —
5
+ // a field added to AgentDefinition would silently become an "unrecognised field" warning,
6
+ // and a typo in a schema key would silently stop validating that field. These assertions
7
+ // fail the typecheck instead.
8
+ //
9
+ // Two checks per shape, because either alone has a blind spot under this tsconfig
10
+ // (`strict: false`): assignability misses a RENAMED optional field (both directions still
11
+ // satisfy each other when every differing key is optional), and key-set equality misses a
12
+ // field whose TYPE changed. Together they catch both. Deliberate divergences are narrowed
13
+ // explicitly below with the reason.
14
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
15
+ // ── Exact ─────────────────────────────────────────────────────────
16
+ const _stage = true;
17
+ const _transition = true;
18
+ const _hookConfig = true;
19
+ const _hooks = true;
20
+ const _agent = true;
21
+ const _shell = true;
22
+ // ── Deliberate divergences ────────────────────────────────────────
23
+ /** `TemplateAgentRef` is a union with a bare string; `keyof` over a union collapses to the keys
24
+ * common to both members, so the key check is applied to the object member on its own. */
25
+ const _agentRef = true;
26
+ const _agentRefKeys = true;
27
+ /** `ThreadTemplate.name` is required, but in the directory form the filename is the identity and
28
+ * the field may be omitted (template-loader.ts:233 only checks it when present). The schema makes
29
+ * it optional; every other field must still match exactly. */
30
+ const _template = true;
31
+ /** `ShellTemplateBinding` carries arbitrary parameter values through an index signature, so the
32
+ * schema describes only the reserved keys and the key check cannot apply. Assert the one
33
+ * direction that means anything: everything the schema accepts must be a valid binding. */
34
+ const _shellBinding = true;
35
+ // Referenced so the assertions are not dead code to a linter.
36
+ export const THREAD_TEMPLATE_SCHEMA_PARITY = [
37
+ _stage,
38
+ _transition,
39
+ _hookConfig,
40
+ _hooks,
41
+ _agent,
42
+ _shell,
43
+ _agentRef,
44
+ _agentRefKeys,
45
+ _template,
46
+ _shellBinding,
47
+ ];
@@ -0,0 +1,55 @@
1
+ import { type EntityKind, type Issue, type RefResolver } from './template-validate.js';
2
+ export type WriteErrorCode = 'not-found' | 'invalid-args' | 'conflict';
3
+ /** Carries the validation issues so the UI can anchor them at their fields. */
4
+ export interface TemplateWriteError extends Error {
5
+ code: WriteErrorCode;
6
+ issues?: Issue[];
7
+ }
8
+ export declare function sha256(text: string): string;
9
+ export declare function entityPath(dir: string, kind: EntityKind, name: string): string;
10
+ export interface EntityRead {
11
+ kind: EntityKind;
12
+ name: string;
13
+ filePath: string;
14
+ /** Raw parsed body, or null when the file on disk is not parseable JSON. */
15
+ body: Record<string, unknown> | null;
16
+ /** Hash of the exact bytes on disk — pass back as `baseHash` to save safely. */
17
+ sha256: string;
18
+ }
19
+ export declare function readEntity(dir: string, kind: EntityKind, name: string): EntityRead;
20
+ export interface SaveInput {
21
+ kind: EntityKind;
22
+ name: string;
23
+ body: unknown;
24
+ /** sha256 of the content the editor started from. `null` means "create — must not exist yet". */
25
+ baseHash: string | null;
26
+ }
27
+ export interface SaveResult {
28
+ changed: boolean;
29
+ filePath: string;
30
+ /** Non-blocking issues the caller should surface after the write. */
31
+ warnings: Issue[];
32
+ /** Hash of what is now on disk, so the editor can keep saving without a reload. */
33
+ sha256: string;
34
+ }
35
+ /**
36
+ * Create or replace one entity file. The body is the complete desired state — omitted fields are
37
+ * removed, not merged, because the editor always holds the whole document.
38
+ *
39
+ * Validation runs against the registry with this candidate already swapped in, so a change is
40
+ * judged by the world it produces rather than the one it replaces. Errors block the write.
41
+ */
42
+ export declare function saveEntity(dir: string, input: SaveInput, refs?: RefResolver): SaveResult;
43
+ export interface RemoveResult {
44
+ removed: boolean;
45
+ filePath: string;
46
+ }
47
+ /**
48
+ * Delete one entity file. Refuses while another template still declares this agent or binds this
49
+ * shell — the loader would keep skipping that template, and any thread on it would stall.
50
+ * Templates themselves have no config-level dependents; task and running-thread references are the
51
+ * caller's to check, since they live outside this directory.
52
+ */
53
+ export declare function removeEntity(dir: string, kind: EntityKind, name: string): RemoveResult;
54
+ /** Every entity name present on disk, by kind. */
55
+ export declare function listEntityNames(dir: string, kind: EntityKind): string[];