@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
@@ -0,0 +1,136 @@
1
+ // input: raw stdout of the machines.detail shell probe
2
+ // output: buildProbeCommand + parseMachineProbe (pure) → { vitals, gpus }
3
+ // pos: probe command text and its parser for the machines.detail handler
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ /** Probe budget: one bash round trip. Above the client's own spawn latency, below a stuck device. */
6
+ export const PROBE_TIMEOUT_MS = 15_000;
7
+ const KIB_PER_GIB = 1024 * 1024;
8
+ /** Single-quote a value for POSIX sh so registry-sourced paths cannot break out of the command. */
9
+ function shellQuote(value) {
10
+ return `'${value.replace(/'/g, `'\\''`)}'`;
11
+ }
12
+ /**
13
+ * One command, one round trip. Every stage is individually failure-tolerant (`2>/dev/null`) so a
14
+ * host without nvidia-smi, /proc or `free` still returns the sections it can fill — the parser maps
15
+ * the missing ones to null rather than to zero. `df -kP` forces POSIX single-line output.
16
+ */
17
+ export function buildProbeCommand(cortexPath) {
18
+ const diskTarget = shellQuote(cortexPath && cortexPath.length > 0 ? cortexPath : '/');
19
+ return [
20
+ `echo '##GPU'`,
21
+ 'nvidia-smi --query-gpu=index,uuid,name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw --format=csv,noheader,nounits 2>/dev/null',
22
+ `echo '##PROC'`,
23
+ 'nvidia-smi --query-compute-apps=pid,process_name,used_memory,gpu_uuid --format=csv,noheader,nounits 2>/dev/null',
24
+ `echo '##SYS'`,
25
+ 'echo "cores=$(nproc 2>/dev/null)"',
26
+ `echo "load1=$(cut -d' ' -f1 /proc/loadavg 2>/dev/null)"`,
27
+ `free -m 2>/dev/null | awk '/^Mem:/{printf "memTotalMb=%s\\nmemUsedMb=%s\\n", $2, $3}'`,
28
+ `df -kP ${diskTarget} 2>/dev/null | awk 'NR==2{printf "diskTotalKb=%s\\ndiskFreeKb=%s\\n", $2, $4}'`,
29
+ `echo "uptimeSec=$(cut -d' ' -f1 /proc/uptime 2>/dev/null)"`,
30
+ ].join('\n');
31
+ }
32
+ /** Parse a numeric field; empty, absent and non-numeric all collapse to null (never 0). */
33
+ function num(value) {
34
+ if (value === undefined)
35
+ return null;
36
+ const trimmed = value.trim();
37
+ if (trimmed === '')
38
+ return null;
39
+ const parsed = Number(trimmed);
40
+ return Number.isFinite(parsed) ? parsed : null;
41
+ }
42
+ function parseGpuLine(line) {
43
+ const parts = line.split(',').map((part) => part.trim());
44
+ if (parts.length < 8)
45
+ return null;
46
+ const index = num(parts[0]);
47
+ if (index === null)
48
+ return null;
49
+ return {
50
+ uuid: parts[1],
51
+ gpu: {
52
+ index,
53
+ name: parts[2],
54
+ utilPercent: num(parts[3]) ?? 0,
55
+ memUsedMb: num(parts[4]) ?? 0,
56
+ memTotalMb: num(parts[5]) ?? 0,
57
+ tempC: num(parts[6]) ?? 0,
58
+ powerW: Math.round(num(parts[7]) ?? 0),
59
+ processes: [],
60
+ },
61
+ };
62
+ }
63
+ /**
64
+ * Windows hosts list every desktop app here with used_memory `[N/A]` — those are graphics clients,
65
+ * not compute processes, and hold no memory we can attribute. Unparseable memory ⇒ drop the row.
66
+ */
67
+ function parseProcLine(line) {
68
+ const parts = line.split(',').map((part) => part.trim());
69
+ if (parts.length < 4)
70
+ return null;
71
+ const memoryMb = num(parts[2]);
72
+ if (memoryMb === null)
73
+ return null;
74
+ return { uuid: parts[3], proc: { pid: parts[0], name: parts[1], memoryMb } };
75
+ }
76
+ function toVitals(sys) {
77
+ const diskTotalKb = num(sys.get('diskTotalKb'));
78
+ const diskFreeKb = num(sys.get('diskFreeKb'));
79
+ const uptimeSec = num(sys.get('uptimeSec'));
80
+ return {
81
+ cpuCores: num(sys.get('cores')),
82
+ loadAvg1: num(sys.get('load1')),
83
+ memUsedMb: num(sys.get('memUsedMb')),
84
+ memTotalMb: num(sys.get('memTotalMb')),
85
+ diskFreeGb: diskFreeKb === null ? null : diskFreeKb / KIB_PER_GIB,
86
+ diskTotalGb: diskTotalKb === null ? null : diskTotalKb / KIB_PER_GIB,
87
+ uptimeSec: uptimeSec === null ? null : Math.floor(uptimeSec),
88
+ };
89
+ }
90
+ const SECTION_MARKERS = {
91
+ '##GPU': 'GPU',
92
+ '##PROC': 'PROC',
93
+ '##SYS': 'SYS',
94
+ };
95
+ /**
96
+ * Split the probe stdout on its `##SECTION` markers, then join compute processes onto their GPU by
97
+ * uuid. The uuid is a join key only — it stays out of the DTO. Malformed lines are dropped silently
98
+ * because a partially-degraded host is the normal case, not an error worth failing the whole probe.
99
+ */
100
+ export function parseMachineProbe(raw) {
101
+ const gpuByUuid = new Map();
102
+ const gpus = [];
103
+ const procs = [];
104
+ const sys = new Map();
105
+ let section = null;
106
+ for (const line of raw.split('\n')) {
107
+ const trimmed = line.trim();
108
+ if (trimmed === '')
109
+ continue;
110
+ const marker = SECTION_MARKERS[trimmed];
111
+ if (marker) {
112
+ section = marker;
113
+ continue;
114
+ }
115
+ if (section === 'GPU') {
116
+ const parsed = parseGpuLine(trimmed);
117
+ if (parsed) {
118
+ gpuByUuid.set(parsed.uuid, parsed.gpu);
119
+ gpus.push(parsed.gpu);
120
+ }
121
+ }
122
+ else if (section === 'PROC') {
123
+ const parsed = parseProcLine(trimmed);
124
+ if (parsed)
125
+ procs.push(parsed);
126
+ }
127
+ else if (section === 'SYS') {
128
+ const eq = trimmed.indexOf('=');
129
+ if (eq > 0)
130
+ sys.set(trimmed.slice(0, eq), trimmed.slice(eq + 1));
131
+ }
132
+ }
133
+ for (const { uuid, proc } of procs)
134
+ gpuByUuid.get(uuid)?.processes.push(proc);
135
+ return { vitals: toVitals(sys), gpus };
136
+ }
@@ -20,5 +20,10 @@ export async function handleSchedulesList(deps, params) {
20
20
  lastRun: s.lastRun != null ? new Date(s.lastRun).toISOString() : null,
21
21
  paused: s.isPaused ?? false,
22
22
  pausedBy: s.pausedBy ?? null,
23
+ intervalMs: s.intervalMs ?? null,
24
+ time: s.time ?? null,
25
+ dayOfWeek: s.dayOfWeek ?? null,
26
+ target: s.target ?? null,
27
+ fallback: s.fallback ?? null,
23
28
  }));
24
29
  }
@@ -93,6 +93,7 @@ export async function handleSessionsList(deps, params) {
93
93
  backend: s.backend,
94
94
  kind: s.kind,
95
95
  origin: s.origin ?? 'direct',
96
+ scheduleId: s.scheduleId ?? null,
96
97
  createdAt: s.createdAt,
97
98
  lastUsedAt: s.lastUsedAt,
98
99
  resumable: s.kind !== 'scheduled',
@@ -106,8 +107,12 @@ export async function handleSessionsList(deps, params) {
106
107
  numTurns: resolveNumTurns(s.channel, inTurn),
107
108
  costUsd: resolveCost(s.channel, inTurn),
108
109
  // Unread = activity (lastUsedAt, bumped at turn end) after the user's last view
109
- // (sessions.markRead → lastReadAt). Legacy records without lastReadAt → read.
110
- unread: !!s.lastReadAt && s.lastUsedAt > s.lastReadAt,
110
+ // (sessions.markRead → lastReadAt). Legacy DIRECT records without lastReadAt → read
111
+ // (no unread flood on first deploy). SCHEDULED runs invert the default: a run the user
112
+ // never opened IS the unread state (27c result → blue dot until opened).
113
+ unread: s.origin === 'scheduled'
114
+ ? (!s.lastReadAt || s.lastUsedAt > s.lastReadAt)
115
+ : (!!s.lastReadAt && s.lastUsedAt > s.lastReadAt),
111
116
  };
112
117
  });
113
118
  // Title label-less sessions from their first user message so the left rail shows the conversation's
@@ -219,6 +224,7 @@ export async function handleSessionsTranscript(deps, params) {
219
224
  // uploads (15a) and agent-sent files (20a, assistant events) carry attachments.
220
225
  ...((ev.type === 'user' || ev.type === 'assistant') && ev.attachments !== undefined ? { attachments: ev.attachments } : {}),
221
226
  ...(ev.type === 'assistant' && ev.noticeLevel !== undefined ? { noticeLevel: ev.noticeLevel } : {}),
227
+ ...(ev.type === 'assistant' && ev.noticeAction !== undefined ? { noticeAction: ev.noticeAction } : {}),
222
228
  // Edit+rewind marker (sessions.rewind): backs the「已编辑」badge + original-message card.
223
229
  ...(ev.type === 'user' && ev.edited !== undefined ? { edited: ev.edited } : {}),
224
230
  // Defense in depth: persisted debug records stay hidden when DEBUG is off. Large-tool
@@ -0,0 +1,8 @@
1
+ import type { UiServiceDeps, ThreadTemplateDetailParams, ThreadTemplateDetail, ThreadTemplateOrigin } from '../types.js';
2
+ /**
3
+ * Compare against the shipped defaults. `mergeThreadTemplates` is copy-if-missing and never
4
+ * overwrites, so a user file that differs from its default has forked permanently — it will not
5
+ * receive upstream changes. Worth knowing before editing.
6
+ */
7
+ export declare function classifyOrigin(defaultsRoot: string, kind: ThreadTemplateDetailParams['kind'], name: string, userContent: string | null): ThreadTemplateOrigin;
8
+ export declare function handleThreadTemplatesDetail(deps: UiServiceDeps, params: ThreadTemplateDetailParams): Promise<ThreadTemplateDetail>;
@@ -0,0 +1,94 @@
1
+ // input: UiServiceDeps + ThreadTemplateDetailParams { kind, name }
2
+ // output: threadTemplates.detail handler → ThreadTemplateDetail
3
+ // pos: The drill-in the templates panel never had. Beyond the raw body it answers the three
4
+ // questions the editor needs before it lets anyone type: is this entity currently valid,
5
+ // what else depends on it, and is anything running on it right now — because transitions
6
+ // are re-read on every step, so a save can reroute or stall a live thread.
7
+ // For a shell-binding template it also returns the expanded graph, which is otherwise
8
+ // impossible to see: `execute-review.json` is four lines that bind a shell.
9
+ // >>> If I am updated, update CORTEX.md <<<
10
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
11
+ import * as path from 'node:path';
12
+ import { DEFAULTS_DIR } from '../../../core/paths.js';
13
+ import { validateEntity, rawRegistryFromDir, dependentTemplates, } from '../../threads/template-validate.js';
14
+ import { readEntity } from '../../threads/template-writer.js';
15
+ import { loaderRefResolver, CONFIG_TEMPLATES_DIR } from '../../threads/template-loader.js';
16
+ import { isShellBinding, expandShell } from '../../threads/shell-templates.js';
17
+ const IO = {
18
+ readdirSync: (p) => readdirSync(p),
19
+ readFileSync: (p, enc) => readFileSync(p, enc),
20
+ existsSync,
21
+ join: path.join,
22
+ };
23
+ const SUBDIR = {
24
+ template: 'templates',
25
+ agent: 'agents',
26
+ shell: 'shells',
27
+ };
28
+ const TERMINAL_THREAD_STATUSES = new Set(['completed', 'failed', 'cancelled', 'aborted']);
29
+ /**
30
+ * Compare against the shipped defaults. `mergeThreadTemplates` is copy-if-missing and never
31
+ * overwrites, so a user file that differs from its default has forked permanently — it will not
32
+ * receive upstream changes. Worth knowing before editing.
33
+ */
34
+ export function classifyOrigin(defaultsRoot, kind, name, userContent) {
35
+ const shipped = path.join(defaultsRoot, 'config', 'thread-templates', SUBDIR[kind], `${name}.json`);
36
+ if (!existsSync(shipped))
37
+ return 'custom';
38
+ try {
39
+ return readFileSync(shipped, 'utf8') === userContent ? 'stock' : 'modified';
40
+ }
41
+ catch {
42
+ return 'custom';
43
+ }
44
+ }
45
+ /** Expand a shell-binding template so the editor can show the graph it actually runs. */
46
+ function expandBinding(name, body, registry) {
47
+ if (!isShellBinding(body))
48
+ return null;
49
+ const shell = registry.shells[body.shell];
50
+ if (!shell || typeof shell !== 'object')
51
+ return null;
52
+ const agents = {};
53
+ for (const [agentName, agentBody] of Object.entries(registry.agents)) {
54
+ if (agentBody && typeof agentBody === 'object')
55
+ agents[agentName] = agentBody;
56
+ }
57
+ try {
58
+ return expandShell(name, body, shell, agents);
59
+ }
60
+ catch {
61
+ return null; // the validator already reports why
62
+ }
63
+ }
64
+ export async function handleThreadTemplatesDetail(deps, params) {
65
+ const { kind, name } = params;
66
+ const entity = readEntity(CONFIG_TEMPLATES_DIR, kind, name);
67
+ const registry = rawRegistryFromDir(CONFIG_TEMPLATES_DIR, IO);
68
+ const { errors, warnings } = validateEntity(kind, name, entity.body, registry, loaderRefResolver());
69
+ const rawContent = existsSync(entity.filePath) ? readFileSync(entity.filePath, 'utf8') : null;
70
+ // Transitions are re-read every step, so a live thread on this template is the thing a user most
71
+ // needs to know about before saving.
72
+ const runningThreads = kind === 'template'
73
+ ? deps.threadStore.getAll().filter((thread) => thread.templateName === name && !TERMINAL_THREAD_STATUSES.has(String(thread.status))).length
74
+ : 0;
75
+ const referencingTasks = kind === 'template'
76
+ ? deps.taskStore.getAll().filter((task) => task.template === name && task.status !== 'done').length
77
+ : 0;
78
+ const description = entity.body && typeof entity.body.description === 'string' ? entity.body.description : null;
79
+ return {
80
+ kind,
81
+ name,
82
+ description,
83
+ body: entity.body,
84
+ filePath: entity.filePath,
85
+ origin: classifyOrigin(DEFAULTS_DIR, kind, name, rawContent),
86
+ sha256: entity.sha256,
87
+ errors,
88
+ warnings,
89
+ usedByTemplates: dependentTemplates(kind, name, registry),
90
+ runningThreads,
91
+ referencingTasks,
92
+ expanded: kind === 'template' ? expandBinding(name, entity.body, registry) : null,
93
+ };
94
+ }
@@ -1,8 +1,10 @@
1
1
  import type { UiServiceDeps, ThreadTemplatesGetParams, ThreadTemplateEntry } from '../types.js';
2
2
  /**
3
3
  * Read all thread-template entries from config/thread-templates/{templates,agents,shells}/*.json.
4
- * Pure over configDir (hermetically testable). Returns templates first, then agents, then shells,
5
- * each group sorted alphabetically by basename. body is null when the file cannot be parsed.
4
+ * Pure over configDir + defaultsRoot (hermetically testable). Returns templates first, then agents,
5
+ * then shells, each group sorted alphabetically by basename. body is null when the file cannot be
6
+ * parsed. Each entry carries its validation verdict so the list can flag a broken entity without a
7
+ * round trip per row.
6
8
  */
7
- export declare function readThreadTemplates(configDir: string): Promise<ThreadTemplateEntry[]>;
9
+ export declare function readThreadTemplates(configDir: string, defaultsRoot?: string): Promise<ThreadTemplateEntry[]>;
8
10
  export declare function handleThreadTemplatesGet(_deps: UiServiceDeps, _params: ThreadTemplatesGetParams): Promise<ThreadTemplateEntry[]>;
@@ -8,7 +8,9 @@
8
8
  // >>> If I am updated, update CORTEX.md <<<
9
9
  import fs from 'node:fs/promises';
10
10
  import path from 'node:path';
11
- import { CONFIG_DIR } from '../../../core/paths.js';
11
+ import { CONFIG_DIR, DEFAULTS_DIR } from '../../../core/paths.js';
12
+ import { validateRegistry } from '../../threads/template-validate.js';
13
+ import { loaderRefResolver } from '../../threads/template-loader.js';
12
14
  async function readJson(file) {
13
15
  try {
14
16
  const raw = JSON.parse(await fs.readFile(file, 'utf8'));
@@ -20,34 +22,69 @@ async function readJson(file) {
20
22
  return null;
21
23
  }
22
24
  }
25
+ const SUBDIR = {
26
+ template: 'templates',
27
+ agent: 'agents',
28
+ shell: 'shells',
29
+ };
23
30
  async function readEntriesForKind(dir, kind) {
24
31
  try {
25
32
  const files = await fs.readdir(dir);
26
33
  const jsonFiles = files.filter((f) => f.endsWith('.json')).sort();
27
34
  return Promise.all(jsonFiles.map(async (f) => {
28
35
  const name = f.slice(0, -'.json'.length);
29
- const body = await readJson(path.join(dir, f));
36
+ const filePath = path.join(dir, f);
37
+ const content = await fs.readFile(filePath, 'utf8').catch(() => null);
38
+ const body = await readJson(filePath);
30
39
  const description = body && typeof body.description === 'string' ? body.description : null;
31
- return { kind, name, description, body };
40
+ return { kind, name, description, body, content };
32
41
  }));
33
42
  }
34
43
  catch {
35
44
  return [];
36
45
  }
37
46
  }
47
+ /**
48
+ * Relationship to the shipped default of the same name. `mergeThreadTemplates` is copy-if-missing
49
+ * and never overwrites, so a user file that differs has forked from upstream permanently.
50
+ */
51
+ async function classifyOrigin(defaultsRoot, kind, name, content) {
52
+ const shipped = path.join(defaultsRoot, 'config', 'thread-templates', SUBDIR[kind], `${name}.json`);
53
+ const stock = await fs.readFile(shipped, 'utf8').catch(() => null);
54
+ if (stock === null)
55
+ return 'custom';
56
+ return stock === content ? 'stock' : 'modified';
57
+ }
38
58
  /**
39
59
  * Read all thread-template entries from config/thread-templates/{templates,agents,shells}/*.json.
40
- * Pure over configDir (hermetically testable). Returns templates first, then agents, then shells,
41
- * each group sorted alphabetically by basename. body is null when the file cannot be parsed.
60
+ * Pure over configDir + defaultsRoot (hermetically testable). Returns templates first, then agents,
61
+ * then shells, each group sorted alphabetically by basename. body is null when the file cannot be
62
+ * parsed. Each entry carries its validation verdict so the list can flag a broken entity without a
63
+ * round trip per row.
42
64
  */
43
- export async function readThreadTemplates(configDir) {
65
+ export async function readThreadTemplates(configDir, defaultsRoot = DEFAULTS_DIR) {
44
66
  const tt = path.join(configDir, 'thread-templates');
45
67
  const [templates, agents, shells] = await Promise.all([
46
68
  readEntriesForKind(path.join(tt, 'templates'), 'template'),
47
69
  readEntriesForKind(path.join(tt, 'agents'), 'agent'),
48
70
  readEntriesForKind(path.join(tt, 'shells'), 'shell'),
49
71
  ]);
50
- return [...templates, ...agents, ...shells];
72
+ const raw = [...templates, ...agents, ...shells];
73
+ const registry = { agents: {}, templates: {}, shells: {} };
74
+ for (const entry of raw) {
75
+ const bucket = entry.kind === 'agent' ? registry.agents : entry.kind === 'template' ? registry.templates : registry.shells;
76
+ bucket[entry.name] = entry.body;
77
+ }
78
+ const verdicts = validateRegistry(registry, loaderRefResolver());
79
+ return Promise.all(raw.map(async ({ content, ...entry }) => {
80
+ const errorCount = verdicts.get(`${entry.kind}:${entry.name}`)?.errors.length ?? 0;
81
+ return {
82
+ ...entry,
83
+ valid: errorCount === 0,
84
+ errorCount,
85
+ origin: await classifyOrigin(defaultsRoot, entry.kind, entry.name, content),
86
+ };
87
+ }));
51
88
  }
52
89
  export async function handleThreadTemplatesGet(_deps, _params) {
53
90
  return readThreadTemplates(CONFIG_DIR);