@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
@@ -271,70 +271,65 @@ async function executeDispatchTask({ selected, selectedTask, channel, scheduleTa
271
271
  }
272
272
  return { success: true, skipped: false, note: `Completed [${selectedTask.project}] ${selectedTask.text.substring(0, 60)}` };
273
273
  }
274
- async function handleDispatchError(error, selectedTask, channel) {
275
- const adapter = ctx.adapter;
276
- log.error(`Error: ${error.message}`);
277
- if (selectedTask) {
278
- const ownership = { generation: selectedTask.dispatch_generation ?? null };
279
- try {
280
- await taskMutator.unclaim(selectedTask.id, { ownership });
281
- }
282
- catch (e) {
283
- log.error(`Failed to unclaim task: ${e.message}`);
274
+ /** Counts this failure and, at the threshold, blocks the task. Runs BEFORE the claim is
275
+ * released: block() clears claimed_by itself, and its ownership check only passes while
276
+ * this dispatch's generation is still the task's own — unclaim() nulls that generation,
277
+ * so quarantining afterwards is refused as stale and the task loops forever. */
278
+ async function quarantineAfterFailure(taskId, ownership, error) {
279
+ const prev = dispatchFailureCounts.get(taskId) || { count: 0, lastError: '' };
280
+ const next = { count: prev.count + 1, lastError: error.message };
281
+ dispatchFailureCounts.set(taskId, next);
282
+ if (next.count < DISPATCH_FAILURE_QUARANTINE_THRESHOLD)
283
+ return false;
284
+ const blockReason = sanitizeBlockReason(`dispatch-failed-${next.count}x: ${error.message}`);
285
+ try {
286
+ const blockResult = await taskMutator.block(taskId, blockReason, { ownership });
287
+ if (blockResult.success) {
288
+ dispatchFailureCounts.delete(taskId);
289
+ return true;
284
290
  }
291
+ log.error(`Failed to auto-block task ${taskId}: ${blockResult.message}`);
285
292
  }
286
- const errChannel = channel;
287
- let blocked = false;
288
- let blockReason = null;
289
- if (selectedTask?.id) {
290
- const taskId = selectedTask.id;
291
- const prev = dispatchFailureCounts.get(taskId) || { count: 0, lastError: '' };
292
- const next = { count: prev.count + 1, lastError: error.message };
293
- dispatchFailureCounts.set(taskId, next);
294
- if (next.count >= DISPATCH_FAILURE_QUARANTINE_THRESHOLD) {
295
- blockReason = sanitizeBlockReason(`dispatch-failed-${next.count}x: ${error.message}`);
296
- try {
297
- const ownership = { generation: selectedTask.dispatch_generation ?? null };
298
- const blockResult = await taskMutator.block(taskId, blockReason, { ownership });
299
- if (blockResult.success) {
300
- blocked = true;
301
- dispatchFailureCounts.delete(taskId);
302
- }
303
- else {
304
- log.error(`Failed to auto-block task ${taskId}: ${blockResult.message}`);
305
- }
306
- }
307
- catch (e) {
308
- log.error(`Failed to auto-block task ${taskId}: ${e.message}`);
309
- }
310
- }
293
+ catch (e) {
294
+ log.error(`Failed to auto-block task ${taskId}: ${e.message}`);
311
295
  }
296
+ return false;
297
+ }
298
+ async function postDispatchErrorNotice(selectedTask, channel, error, blocked) {
299
+ const adapter = ctx.adapter;
300
+ const text = blocked && selectedTask
301
+ ? `${Icons.blocked} Auto-blocked after ${DISPATCH_FAILURE_QUARANTINE_THRESHOLD} consecutive dispatch failures. Reason recorded in TASKS.yaml. Task: [${selectedTask.project}] ${String(selectedTask.text).substring(0, 80)}. Last error: ${error.message}. Unblock with \`cortex-task unblock --task-id ${selectedTask.id}\`.`
302
+ : `${Icons.error} Task dispatch error: ${error.message}`;
303
+ const projDest = { type: 'project-report', projectId: selectedTask?.project || channel, trigger: 'task-dispatch', sessionId: '' };
312
304
  try {
313
305
  const queue = getOutboundQueue();
314
- if (blocked && selectedTask) {
315
- const text = `${Icons.blocked} Auto-blocked after ${DISPATCH_FAILURE_QUARANTINE_THRESHOLD} consecutive dispatch failures. Reason recorded in TASKS.yaml. Task: [${selectedTask.project}] ${String(selectedTask.text).substring(0, 80)}. Last error: ${error.message}. Unblock with \`cortex-task unblock --task-id ${selectedTask.id}\`.`;
316
- const projDest = { type: 'project-report', projectId: selectedTask.project || errChannel, trigger: 'task-dispatch', sessionId: '' };
317
- if (queue) {
318
- await durablePost(queue, adapter, projDest, { text });
319
- }
320
- else {
321
- await adapter.postMessage(projDest, { text });
322
- }
306
+ if (queue) {
307
+ await durablePost(queue, adapter, projDest, { text });
323
308
  }
324
309
  else {
325
- const text = `${Icons.error} Task dispatch error: ${error.message}`;
326
- const projDest = { type: 'project-report', projectId: selectedTask?.project || errChannel, trigger: 'task-dispatch', sessionId: '' };
327
- if (queue) {
328
- await durablePost(queue, adapter, projDest, { text });
329
- }
330
- else {
331
- await adapter.postMessage(projDest, { text });
332
- }
310
+ await adapter.postMessage(projDest, { text });
333
311
  }
334
312
  }
335
313
  catch { }
336
- const noteSuffix = blocked ? ' (blocked)' : '';
337
- return { success: false, skipped: false, note: `Error: ${error.message}${noteSuffix}` };
314
+ }
315
+ async function handleDispatchError(error, selectedTask, channel) {
316
+ log.error(`Error: ${error.message}`);
317
+ const ownership = { generation: selectedTask?.dispatch_generation ?? null };
318
+ const blocked = selectedTask?.id
319
+ ? await quarantineAfterFailure(selectedTask.id, ownership, error)
320
+ : false;
321
+ // A blocked task is already released by block(); only a task going back to the queue
322
+ // needs its claim dropped.
323
+ if (selectedTask && !blocked) {
324
+ try {
325
+ await taskMutator.unclaim(selectedTask.id, { ownership });
326
+ }
327
+ catch (e) {
328
+ log.error(`Failed to unclaim task: ${e.message}`);
329
+ }
330
+ }
331
+ await postDispatchErrorNotice(selectedTask, channel, error, blocked);
332
+ return { success: false, skipped: false, note: `Error: ${error.message}${blocked ? ' (blocked)' : ''}` };
338
333
  }
339
334
  // --- Cancel dispatched task ---
340
335
  export async function cancelDispatchedTask({ taskId, channel }) {
@@ -70,6 +70,28 @@ export interface AttachExistingSessionOpts {
70
70
  /** Attach a channel to an existing session: restore its profile (if any), point sessions.json at it,
71
71
  * and switch the conversation ledger. Mirrors the !resume switch sequence. */
72
72
  export declare function attachExistingSession(channel: string, opts: AttachExistingSessionOpts): Promise<void>;
73
+ export interface AdoptScheduledSessionStore {
74
+ getById(sessionId: string): Promise<{
75
+ name: string;
76
+ channel: string;
77
+ backend: string;
78
+ origin: SessionOrigin;
79
+ profileName: string | null;
80
+ } | null>;
81
+ /** Re-point the registry record: channel → the adopted channel, kind → local, origin → direct. */
82
+ convertToDirect(sessionId: string, opts: {
83
+ channel: string;
84
+ }): Promise<unknown | null>;
85
+ }
86
+ /** Convert a scheduled run's session into a normal direct web session (design 27b: replying adopts
87
+ * the run). Attaches a dedicated `web:<sessionId>` conduit to the existing session — the same
88
+ * switch sequence as !resume, so a later send resumes the run's transcript — then re-points the
89
+ * registry record. `scheduleId` is intentionally KEPT on the record (provenance for the trigger
90
+ * card / schedule grouping). Idempotent: a non-scheduled record just returns its current channel;
91
+ * an unknown id returns null. */
92
+ export declare function adoptScheduledSession(store: AdoptScheduledSessionStore, sessionId: string): Promise<{
93
+ channel: string;
94
+ } | null>;
73
95
  /** Clear a channel's session state: drop sessions.json keys for every backend, clean session
74
96
  * backups, and clear the conversation ledger. Mirrors the store-level half of !new. */
75
97
  export declare function resetChannelSession(channel: string): Promise<void>;
@@ -1,5 +1,5 @@
1
1
  // input: Session stores, conversation ledger, profile state
2
- // output: Session register, attach, create, and reset primitives
2
+ // output: Session register/attach/create/adopt/reset primitives
3
3
  // pos: Central session lifecycle shared by chat and TUI
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import * as crypto from 'node:crypto';
@@ -69,6 +69,25 @@ export async function attachExistingSession(channel, opts) {
69
69
  sessionId: opts.sessionId, sessionName: opts.sessionName, backend: opts.backend, profileName: opts.profileName,
70
70
  });
71
71
  }
72
+ /** Convert a scheduled run's session into a normal direct web session (design 27b: replying adopts
73
+ * the run). Attaches a dedicated `web:<sessionId>` conduit to the existing session — the same
74
+ * switch sequence as !resume, so a later send resumes the run's transcript — then re-points the
75
+ * registry record. `scheduleId` is intentionally KEPT on the record (provenance for the trigger
76
+ * card / schedule grouping). Idempotent: a non-scheduled record just returns its current channel;
77
+ * an unknown id returns null. */
78
+ export async function adoptScheduledSession(store, sessionId) {
79
+ const record = await store.getById(sessionId);
80
+ if (!record)
81
+ return null;
82
+ if (record.origin !== 'scheduled')
83
+ return { channel: record.channel };
84
+ const channel = `web:${sessionId}`;
85
+ await attachExistingSession(channel, {
86
+ sessionId, sessionName: record.name, backend: record.backend, profileName: record.profileName,
87
+ });
88
+ await store.convertToDirect(sessionId, { channel });
89
+ return { channel };
90
+ }
72
91
  /** Clear a channel's session state: drop sessions.json keys for every backend, clean session
73
92
  * backups, and clear the conversation ledger. Mirrors the store-level half of !new. */
74
93
  export async function resetChannelSession(channel) {
@@ -1,4 +1,4 @@
1
- import type { PlatformAdapter, RichBlock } from '../../platform/index.js';
1
+ import type { PlatformAdapter, RichBlock, ActionElement } from '../../platform/index.js';
2
2
  export type SystemNoticeLevel = 'info' | 'warning' | 'error';
3
3
  export interface SystemNoticeInput {
4
4
  /** The notice body (same text that goes to the admin channel). */
@@ -9,6 +9,9 @@ export interface SystemNoticeInput {
9
9
  title?: string;
10
10
  /** Optional platform-native content; Web notices continue to use the secret-free text fields. */
11
11
  richBlocks?: RichBlock[];
12
+ /** Optional action buttons attached to the platform post (Slack/Feishu interactive).
13
+ * When present the notice is delivered via postInteractive; absent keeps postMessage. */
14
+ actions?: ActionElement[];
12
15
  }
13
16
  /** Publish a `system.notice` event on the shared EventBus (the Web notification-toast source).
14
17
  * No-op when no bus is wired (matches publishSessionMessage). */
@@ -1,5 +1,5 @@
1
1
  // input: PlatformAdapter, notice payload, shared job context
2
- // output: Web publication and rich best-effort admin delivery
2
+ // output: Web publication and rich/actionable best-effort admin delivery
3
3
  // pos: Domain seam for admin and system broadcasts
4
4
  // >>> 一旦我被更新,务必更新我的开头注释与所属文件夹 CORTEX.md <<<
5
5
  import { ctx as jobCtx } from '../scheduling/job-registry.js';
@@ -20,7 +20,11 @@ export function publishSystemNotice(p) {
20
20
  export async function emitSystemNotice(adapter, p) {
21
21
  publishSystemNotice(p);
22
22
  try {
23
- const ref = await adapter.postMessage({ type: 'system-notice' }, { text: p.text, ...(p.richBlocks ? { richBlocks: p.richBlocks } : {}) });
23
+ const destination = { type: 'system-notice' };
24
+ const content = { text: p.text, ...(p.richBlocks ? { richBlocks: p.richBlocks } : {}) };
25
+ const ref = p.actions?.length
26
+ ? await adapter.postInteractive(destination, { ...content, actions: p.actions })
27
+ : await adapter.postMessage(destination, content);
24
28
  return ref.conduit.length > 0;
25
29
  }
26
30
  catch {
@@ -41,10 +41,6 @@ declare function getMachineRegistry(): MachineRegistry;
41
41
  * Falls back to 'local' if no machines are registered.
42
42
  */
43
43
  declare function getLocalMachine(): string;
44
- /**
45
- * Start watching machines.json for changes. Reloads on file edit.
46
- * Handles atomic file replacement (rename event) by re-creating the watcher.
47
- */
48
44
  declare function startMachineRegistryWatcher(): void;
49
45
  /**
50
46
  * Stop watching machines.json (for tests / graceful shutdown).
@@ -1,18 +1,19 @@
1
- // input: machine config, task generation ownership
1
+ // input: machine config, resilient watch, task ownership
2
2
  // output: device registry, task IDs, dispatch outcome helpers
3
3
  // pos: Shared task dispatch utilities
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import * as crypto from 'crypto';
6
- import { readFileSync, watch, existsSync } from 'fs';
6
+ import { readFileSync, existsSync } from 'fs';
7
7
  import * as path from 'path';
8
8
  import { CONFIG_DIR } from '../../core/utils.js';
9
9
  import { createLogger } from '../../core/log.js';
10
+ import { createFileWatchMonitor } from '../../core/resilient-watch.js';
10
11
  import { Icons } from '../../core/icons.js';
11
12
  const log = createLogger('machine-registry');
12
13
  const MACHINES_FILE = path.join(CONFIG_DIR, 'machines.json');
13
14
  let _registry = {};
14
15
  let _loaded = false;
15
- let _watcher = null;
16
+ let _watchMonitor = null;
16
17
  let _reloadTimer = null;
17
18
  // --- Admin notification (hot-reload → Slack) ---
18
19
  let _adminNotifier = null;
@@ -75,48 +76,34 @@ function getLocalMachine() {
75
76
  }
76
77
  /**
77
78
  * Start watching machines.json for changes. Reloads on file edit.
78
- * Handles atomic file replacement (rename event) by re-creating the watcher.
79
+ * Watches the parent directory so atomic file replacement keeps monitoring active.
79
80
  */
81
+ function scheduleMachineReload() {
82
+ if (_reloadTimer)
83
+ clearTimeout(_reloadTimer);
84
+ _reloadTimer = setTimeout(() => {
85
+ _reloadTimer = null;
86
+ loadMachinesFromFile(false);
87
+ }, 300);
88
+ }
80
89
  function startMachineRegistryWatcher() {
81
- if (!existsSync(MACHINES_FILE))
82
- return;
83
- const setup = () => {
84
- try {
85
- if (_watcher)
86
- _watcher.close();
87
- _watcher = watch(MACHINES_FILE, (eventType) => {
88
- if (eventType === 'rename') {
89
- // File was atomically replaced — inode changed, watcher is dead.
90
- // Re-create after a short delay to let the new file settle.
91
- setTimeout(() => setup(), 100);
92
- return; // setup() will handle the reload after the new watcher fires
93
- }
94
- if (_reloadTimer)
95
- clearTimeout(_reloadTimer);
96
- _reloadTimer = setTimeout(() => {
97
- _reloadTimer = null;
98
- loadMachinesFromFile(false); // hot-reload: don't crash on error
99
- }, 300);
100
- });
101
- }
102
- catch (e) {
103
- log.error(`Failed to watch machines.json: ${e.message}`);
104
- }
105
- };
106
- setup();
90
+ _watchMonitor?.close();
91
+ _watchMonitor = createFileWatchMonitor({
92
+ label: 'machines.json',
93
+ filePath: MACHINES_FILE,
94
+ onChange: scheduleMachineReload,
95
+ warn: (message) => log.error(message),
96
+ });
107
97
  }
108
98
  /**
109
99
  * Stop watching machines.json (for tests / graceful shutdown).
110
100
  */
111
101
  function stopMachineRegistryWatcher() {
112
- if (_watcher) {
113
- _watcher.close();
114
- _watcher = null;
115
- }
116
- if (_reloadTimer) {
102
+ _watchMonitor?.close();
103
+ _watchMonitor = null;
104
+ if (_reloadTimer)
117
105
  clearTimeout(_reloadTimer);
118
- _reloadTimer = null;
119
- }
106
+ _reloadTimer = null;
120
107
  }
121
108
  // --- Auto-load at import time (equivalent to the old hardcoded constant) ---
122
109
  // This ensures getMachineRegistry() works immediately for all consumers.
@@ -2,7 +2,10 @@ import { type PendingControl } from './index.js';
2
2
  import type { OutputStream } from '../../platform/output-stream.js';
3
3
  import type { RunningExecution } from '../../core/running-executions.js';
4
4
  import { type StepTranscriptRecorder } from './thread-transcript.js';
5
- import type { ThreadRecord, AgentSlotId, AgentSlotConfig, ThreadTemplate, RunThreadOptions } from '../../core/types/thread-types.js';
5
+ import type { ThreadRecord, AgentSlotId, AgentSlotConfig, ThreadTemplate, RunThreadOptions, TransitionResult } from '../../core/types/thread-types.js';
6
+ /** Why the step loop stopped scheduling, in the transition engine's own terms. `transition` is
7
+ * excluded because it is the one verdict that does not stop the loop. */
8
+ export type ThreadStopReason = Exclude<TransitionResult['reason'], 'transition'>;
6
9
  export declare class BenchmarkRateLimitError extends Error {
7
10
  readonly provider: string | null;
8
11
  readonly code = "BENCHMARK_RATE_LIMITED";
@@ -20,6 +23,9 @@ interface ThreadRunResult {
20
23
  lastAgentResult: any;
21
24
  /** The execution ID from the last completed step — used by handleAgentSuccess in the wrapper. */
22
25
  executionId: string | null;
26
+ /** Why the transition engine stopped scheduling steps, in its own typed terms. Null when the
27
+ * loop left for a reason the engine never judged. */
28
+ stopReason: ThreadStopReason | null;
23
29
  }
24
30
  /** Outer-scope state shared across the whole runThread() lifecycle. */
25
31
  interface ThreadContext {
@@ -32,6 +38,9 @@ interface ThreadContext {
32
38
  /** Set when a step was interrupted by a provider throttle.
33
39
  * Pauses the thread (status='rate_limited') instead of completing/failing it. */
34
40
  rateLimited?: boolean;
41
+ /** Why the transition engine stopped scheduling steps. Null when the loop left for a reason the
42
+ * engine never judged — an abort, a wait or a throttle. */
43
+ stopReason: ThreadStopReason | null;
35
44
  }
36
45
  /** Per-step config built once by buildStepConfig — fully populated, no placeholders. */
37
46
  interface StepContext {
@@ -41,6 +50,9 @@ interface StepContext {
41
50
  multiAgent: boolean;
42
51
  /** Stage this step runs. Null for single-stage agents (no `stages` map declared). */
43
52
  stage: string | null;
53
+ /** Index this step occupies in the thread's step list, captured before the step runs (the
54
+ * record advances it once the step's result is recorded). */
55
+ stepIndex: number;
44
56
  prompt: string;
45
57
  /** True when this step re-enters an interrupted attempt's backend session: the prompt is the
46
58
  * continuation reminder, and first-step files are not re-attached. */
@@ -48,6 +60,9 @@ interface StepContext {
48
60
  /** Flipped by the step callbacks on the first streamed assistant/tool event. Gates capturing
49
61
  * the interrupted backend session — an attempt with no activity has nothing worth resuming. */
50
62
  sawActivity: boolean;
63
+ /** The last non-empty assistant message this step emitted, captured off the normalized event
64
+ * channel every backend populates. Stays null when the step emitted none. */
65
+ terminalAssistantText: string | null;
51
66
  /** Backend `--resume` target (slot.backendSessionId via beginStepSession); null → fresh. */
52
67
  resumeSessionId: string | null;
53
68
  /** Stable Cortex track id (slot.sessionId, minted at step start) — the conversation-history /
@@ -47,7 +47,6 @@ const NOOP_STEP_TRANSCRIPT_RECORDER = {
47
47
  recordUser: () => { }, recordAssistant: () => { }, recordTool: () => { },
48
48
  recordToolResult: () => { }, settle: async () => { },
49
49
  };
50
- // --- Result types ---
51
50
  export class BenchmarkRateLimitError extends Error {
52
51
  provider;
53
52
  code = 'BENCHMARK_RATE_LIMITED';
@@ -89,7 +88,10 @@ function initThreadContext(threadId, opts) {
89
88
  // Pass the full statusMsg as anchorRef so CompositeAdapter can resolve a per-platform
90
89
  // thread anchor for each sub-stream (a Slack ts must not be used as a Feishu message_id).
91
90
  const stream = opts.adapter.openOutputStream(opts.destination, { threadId: opts.threadAnchorId, anchorRef: opts.statusMsg });
92
- return { thread, template, meta: thread.metadata, stream, lastAgentResult: null, totalNumTurns: 0 };
91
+ return {
92
+ thread, template, meta: thread.metadata, stream, lastAgentResult: null, totalNumTurns: 0,
93
+ stopReason: null,
94
+ };
93
95
  }
94
96
  async function executeConfiguredLifecycleHooks(ctx, threadId, phase, configs, opts, previousAgent, logSuffix) {
95
97
  if (opts.benchmark || ctx.template?.disableHooks === true)
@@ -241,7 +243,9 @@ async function buildStepConfig(threadId, stepInfo, ctx, opts) {
241
243
  recorder.recordUser(prompt);
242
244
  return {
243
245
  agentSlotId, agentConfig, isFirstStep, multiAgent, stage,
244
- prompt, interruptedResume, sawActivity: false, resumeSessionId, trackSessionId, sessionKey,
246
+ stepIndex: threadStore.get(threadId)?.currentStepIndex ?? 0,
247
+ prompt, interruptedResume, sawActivity: false, terminalAssistantText: null,
248
+ resumeSessionId, trackSessionId, sessionKey,
245
249
  sessionName: await sessionStore.generateSessionName(),
246
250
  profileName, profileBackend, rateLimitProvider, execution,
247
251
  stepStartTime: new Date().toISOString(),
@@ -280,8 +284,10 @@ function setupStepCallbacks(threadId, stepCtx, ctx, opts) {
280
284
  // streaming/tool-trace behaviour is unchanged.
281
285
  const recorder = stepCtx.recorder;
282
286
  const onAssistantMessage = (text) => {
283
- if (text)
287
+ if (text) {
284
288
  stepCtx.sawActivity = true;
289
+ stepCtx.terminalAssistantText = text;
290
+ }
285
291
  streamAssistantMessage(text);
286
292
  if (text)
287
293
  recorder.recordAssistant(text);
@@ -324,7 +330,12 @@ function setupStepCallbacks(threadId, stepCtx, ctx, opts) {
324
330
  function resolveStepSpawnPolicy(stepCtx, ctx, opts) {
325
331
  if (opts.benchmark) {
326
332
  return {
327
- cwd: opts.benchmark.workspaceCwd, processSpawner: opts.benchmark.spawner,
333
+ cwd: opts.benchmark.resolveStepWorkspace?.({
334
+ agentSlotId: stepCtx.agentSlotId, stepIndex: stepCtx.stepIndex,
335
+ }) ?? opts.benchmark.workspaceCwd,
336
+ processSpawner: opts.benchmark.spawner,
337
+ // Names the trial role this step runs as, so a per-step adapter can select it.
338
+ benchmarkAgentSlot: stepCtx.agentSlotId,
328
339
  mcpComposition: 'none', disableHooks: true, loadCortexRules: false,
329
340
  streamDeltas: false, captureTranscriptLogs: false,
330
341
  preserveUnreportedAccounting: true, recordCost: false,
@@ -495,6 +506,33 @@ async function recordStepOutcome(threadId, stepCtx, result, ctx, opts) {
495
506
  });
496
507
  }
497
508
  }
509
+ /** Settle the workspace this step was placed in — the benchmark run appends a snapshot-placed
510
+ * step's terminal message to the thread artifact and discards the snapshot here. Runs at the step
511
+ * boundary: after the step's process exited, before the next transition is evaluated, and on the
512
+ * error path too. A settlement failure is fatal when the step itself succeeded — the appended text
513
+ * is an input to the transition engine, so losing it silently would convert approvals into
514
+ * retries. When the step is already propagating an error, the settlement failure is logged
515
+ * instead: it must not replace the typed failure the caller classifies the run by.
516
+ *
517
+ * The appended text is taken from the step's last normalized assistant message, not from the
518
+ * step result's `finalOutput`: only the message channel is populated on every backend — the PI
519
+ * adapter reports `finalOutput: null` for every turn — and an append that never fires converts
520
+ * each approval into a retry instead of failing loudly. */
521
+ function settleStepWorkspace(stepCtx, opts, stepError) {
522
+ try {
523
+ opts.benchmark?.settleStepWorkspace?.({
524
+ agentSlotId: stepCtx.agentSlotId,
525
+ stepIndex: stepCtx.stepIndex,
526
+ stage: stepCtx.stage,
527
+ terminalText: stepCtx.terminalAssistantText,
528
+ });
529
+ }
530
+ catch (error) {
531
+ if (!stepError)
532
+ throw error;
533
+ log.error(`Step workspace settlement failed after a step error: ${error?.message || error}`);
534
+ }
535
+ }
498
536
  /** Pause the thread for auto-resume after a provider throttle interrupted a step. Records the
499
537
  * thread in the resume registry (drained when its provider window resets) and
500
538
  * flips it to the non-terminal 'rate_limited' status. Sets ctx.rateLimited so the loop breaks
@@ -526,8 +564,12 @@ async function evaluateAndTransition(threadId, stepCtx, ctx, opts) {
526
564
  return false;
527
565
  // Evaluate transitions for template-based multi-agent
528
566
  const transition = evaluateTransitions(threadId);
529
- if (!transition.shouldTransition)
567
+ if (!transition.shouldTransition) {
568
+ // Why the loop ends, in the engine's own typed terms. A caller that re-derived it from the
569
+ // thread record would be inferring what the engine already decided.
570
+ ctx.stopReason = transition.reason === 'transition' ? null : transition.reason;
530
571
  return false;
572
+ }
531
573
  // transition.nextAgent / nextStage are already set on the thread by evaluateTransitions
532
574
  const prevAgent = stepCtx.agentSlotId;
533
575
  const fromLabel = formatAgentStageLabel(prevAgent, stepCtx.stage);
@@ -555,6 +597,7 @@ async function finalizeThread(threadId, ctx) {
555
597
  totalNumTurns: ctx.totalNumTurns,
556
598
  lastAgentResult: ctx.lastAgentResult,
557
599
  executionId: finalThread.steps[finalThread.steps.length - 1]?.executionId ?? null,
600
+ stopReason: ctx.stopReason,
558
601
  };
559
602
  }
560
603
  /** Terminate a thread by agent abort and, BEFORE onEnd hooks run, hand the owning task to the
@@ -651,8 +694,19 @@ async function runThread(threadId, opts) {
651
694
  break;
652
695
  const stepCtx = await buildStepConfig(threadId, stepInfo, ctx, opts);
653
696
  const callbacks = setupStepCallbacks(threadId, stepCtx, ctx, opts);
654
- const result = await executeAndAwaitAgent(threadId, stepCtx, callbacks, ctx, opts);
655
- await recordStepOutcome(threadId, stepCtx, result, ctx, opts);
697
+ let result;
698
+ let stepError = null;
699
+ try {
700
+ result = await executeAndAwaitAgent(threadId, stepCtx, callbacks, ctx, opts);
701
+ await recordStepOutcome(threadId, stepCtx, result, ctx, opts);
702
+ }
703
+ catch (error) {
704
+ stepError = error;
705
+ throw error;
706
+ }
707
+ finally {
708
+ settleStepWorkspace(stepCtx, opts, stepError);
709
+ }
656
710
  // Rate-limit pause (graceful path): recordStepOutcome paused the thread. Break out so the
657
711
  // thread is NOT completed; resume-dispatcher re-enters it when its provider resets.
658
712
  if (ctx.rateLimited)
@@ -1,4 +1,7 @@
1
+ import { type RefResolver } from './template-validate.js';
1
2
  import type { AgentDefinition, ThreadTemplate } from '../../core/types/thread-types.js';
3
+ /** Directory-based config root (preferred). Exported for the write path. */
4
+ export declare const CONFIG_TEMPLATES_DIR: string;
2
5
  export declare const FILE_REF_PREFIX = "file:";
3
6
  export declare function setAdminNotifier(fn: (text: string) => void): void;
4
7
  /** Resolve a "file:<name>" reference for a given field. Returns value unchanged if not a file ref.
@@ -25,6 +28,8 @@ export declare function mergeThreadTemplates(defaultsDir: string, userDir: strin
25
28
  * @returns true if a migration was performed.
26
29
  */
27
30
  export declare function migrateThreadTemplatesToDir(): boolean;
31
+ /** Filesystem probes for the validator's `file:` ref and pluginDirs existence checks. */
32
+ export declare function loaderRefResolver(): RefResolver;
28
33
  export declare function loadConfig(): {
29
34
  agents: Record<string, AgentDefinition>;
30
35
  templates: Record<string, ThreadTemplate>;