@cortex-agent/server 2026.6.18 → 2026.6.24

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 (153) hide show
  1. package/defaults/CORTEX.md +5 -0
  2. package/defaults/config/thread-templates.json +12 -6
  3. package/defaults/context/user/CORTEX.md +2 -2
  4. package/defaults/hooks/ask-user-question-hook.mjs +7 -1
  5. package/defaults/hooks/exit-plan-mode-hook.mjs +7 -1
  6. package/defaults/hooks/memory-ref-tracker.mjs +1 -0
  7. package/defaults/hooks/new-session-hook.mjs +1 -0
  8. package/defaults/hooks/post-task-hook.mjs +1 -0
  9. package/defaults/hooks/rules-loader.mjs +1 -0
  10. package/defaults/hooks/sensitive-file-edit.mjs +1 -0
  11. package/defaults/hooks/session-activity-tracker.mjs +1 -0
  12. package/defaults/hooks/task-status-check.mjs +1 -0
  13. package/defaults/hooks/tasks-yaml-guard.mjs +1 -0
  14. package/defaults/plugins/cortex-feishu/.claude-plugin/plugin.json +5 -0
  15. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +163 -0
  16. package/defaults/plugins/cortex-feishu/skills/feishu-doc/scripts/ensure-lark-cli.sh +53 -0
  17. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +7 -0
  18. package/defaults/prompts/directives/coder-reviewer.md +6 -6
  19. package/defaults/prompts/directives/coder.md +14 -15
  20. package/defaults/prompts/systemPrompts/coder.md +6 -1
  21. package/defaults/prompts/systemPrompts/direct.md +5 -0
  22. package/defaults/prompts/systemPrompts/web-opus-4-6.md +6 -1
  23. package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +6 -1
  24. package/defaults/prompts/systemPrompts/web.md +6 -1
  25. package/defaults/prompts/systemPrompts/worker.md +6 -1
  26. package/dist/agent-adapter/claude/adapter-tui.d.ts +12 -0
  27. package/dist/agent-adapter/claude/adapter-tui.js +15 -0
  28. package/dist/agent-adapter/claude/adapter.d.ts +110 -1
  29. package/dist/agent-adapter/claude/adapter.js +123 -2
  30. package/dist/agent-adapter/claude/bg-task-tracker.d.ts +45 -0
  31. package/dist/agent-adapter/claude/bg-task-tracker.js +91 -0
  32. package/dist/agent-adapter/normalize/event-types.d.ts +4 -0
  33. package/dist/agent-adapter/pi/event-parser.d.ts +3 -1
  34. package/dist/agent-adapter/pi/event-parser.js +12 -2
  35. package/dist/agent-adapter/types.d.ts +19 -0
  36. package/dist/core/auth.d.ts +36 -0
  37. package/dist/core/auth.js +85 -0
  38. package/dist/core/gateway-generator.js +10 -1
  39. package/dist/core/locales/en.d.ts +12 -0
  40. package/dist/core/locales/slices/interactions.d.ts +6 -0
  41. package/dist/core/locales/slices/interactions.js +14 -0
  42. package/dist/core/locales/slices/status.d.ts +6 -0
  43. package/dist/core/locales/slices/status.js +16 -0
  44. package/dist/core/status-format.d.ts +14 -0
  45. package/dist/core/status-format.js +23 -1
  46. package/dist/core/types/agent-types.d.ts +5 -0
  47. package/dist/core/types/thread-types.d.ts +15 -1
  48. package/dist/core/version.d.ts +3 -0
  49. package/dist/core/version.js +4 -1
  50. package/dist/domain/agents/facade.d.ts +13 -0
  51. package/dist/domain/agents/facade.js +36 -1
  52. package/dist/domain/costs/rate-limit-throttle.d.ts +1 -1
  53. package/dist/domain/costs/rate-limit-throttle.js +23 -2
  54. package/dist/domain/costs/resume-registry.d.ts +30 -0
  55. package/dist/domain/costs/resume-registry.js +68 -0
  56. package/dist/domain/mcp/core-server.js +5 -0
  57. package/dist/domain/mcp/feishu/index.js +5 -51
  58. package/dist/domain/mcp/feishu-server.js +3 -2
  59. package/dist/domain/mcp/tools/manager-qa.d.ts +2 -0
  60. package/dist/domain/mcp/tools/manager-qa.js +72 -0
  61. package/dist/domain/mcp/tools/task-ops.js +4 -2
  62. package/dist/domain/mcp/tools/thread-ops.js +2 -1
  63. package/dist/domain/mcp/tui-server.js +2 -1
  64. package/dist/domain/memory/user-context.d.ts +6 -5
  65. package/dist/domain/memory/user-context.js +12 -7
  66. package/dist/domain/remote/client-bootstrap.js +14 -2
  67. package/dist/domain/remote/client-hot-reload.d.ts +9 -2
  68. package/dist/domain/remote/client-hot-reload.js +77 -6
  69. package/dist/domain/remote/client-manager.d.ts +1 -1
  70. package/dist/domain/remote/client-manager.js +31 -5
  71. package/dist/domain/remote/cortex-client-config.d.ts +32 -0
  72. package/dist/domain/remote/cortex-client-config.js +49 -0
  73. package/dist/domain/remote/cortex-client.js +11 -7
  74. package/dist/domain/scheduling/jobs/scheduled-task.js +17 -1
  75. package/dist/domain/scheduling/jobs/task-dispatch.js +22 -0
  76. package/dist/domain/sessions/session-hooks.d.ts +31 -1
  77. package/dist/domain/sessions/session-hooks.js +69 -17
  78. package/dist/domain/system/doctor.d.ts +63 -0
  79. package/dist/domain/system/doctor.js +362 -0
  80. package/dist/domain/tasks/dispatcher.js +8 -0
  81. package/dist/domain/tasks/system/cortex-run.js +4 -2
  82. package/dist/domain/tasks/system/task-cli.js +7 -4
  83. package/dist/domain/tasks/system/task-state.d.ts +10 -1
  84. package/dist/domain/tasks/system/task-state.js +31 -1
  85. package/dist/domain/threads/prompt-builder.d.ts +7 -4
  86. package/dist/domain/threads/prompt-builder.js +9 -8
  87. package/dist/domain/threads/runner.d.ts +8 -1
  88. package/dist/domain/threads/runner.js +111 -18
  89. package/dist/domain/threads/state-machine.d.ts +5 -0
  90. package/dist/domain/threads/state-machine.js +16 -0
  91. package/dist/entry/app.js +44 -5
  92. package/dist/entry/cli.js +10 -0
  93. package/dist/entry/doctor-cli.d.ts +12 -0
  94. package/dist/entry/doctor-cli.js +76 -0
  95. package/dist/entry/init.js +6 -0
  96. package/dist/hooks/ask-user-question-hook.mjs +7 -1
  97. package/dist/hooks/exit-plan-mode-hook.mjs +7 -1
  98. package/dist/hooks/memory-ref-tracker.mjs +1 -0
  99. package/dist/hooks/new-session-hook.mjs +1 -0
  100. package/dist/hooks/post-task-hook.mjs +1 -0
  101. package/dist/hooks/rules-loader.mjs +1 -0
  102. package/dist/hooks/sensitive-file-edit.mjs +1 -0
  103. package/dist/hooks/session-activity-tracker.mjs +1 -0
  104. package/dist/hooks/task-status-check.mjs +1 -0
  105. package/dist/hooks/tasks-yaml-guard.mjs +1 -0
  106. package/dist/orchestration/agent-runner.js +30 -4
  107. package/dist/orchestration/bg-continuation.d.ts +26 -0
  108. package/dist/orchestration/bg-continuation.js +34 -0
  109. package/dist/orchestration/conversation-runner.d.ts +3 -0
  110. package/dist/orchestration/conversation-runner.js +5 -2
  111. package/dist/orchestration/interactions/interaction-handlers.js +13 -2
  112. package/dist/orchestration/lifecycle.d.ts +5 -2
  113. package/dist/orchestration/lifecycle.js +87 -3
  114. package/dist/orchestration/manager-qa.d.ts +56 -0
  115. package/dist/orchestration/manager-qa.js +223 -0
  116. package/dist/orchestration/resume-dispatcher.d.ts +27 -0
  117. package/dist/orchestration/resume-dispatcher.js +145 -0
  118. package/dist/orchestration/routing/webhook.d.ts +1 -1
  119. package/dist/orchestration/routing/webhook.js +75 -14
  120. package/dist/orchestration/status-helpers.d.ts +3 -0
  121. package/dist/orchestration/status-helpers.js +16 -0
  122. package/dist/orchestration/thread-callback.d.ts +17 -1
  123. package/dist/orchestration/thread-callback.js +57 -36
  124. package/dist/orchestration/turn-notify.d.ts +26 -0
  125. package/dist/orchestration/turn-notify.js +66 -0
  126. package/dist/platform/adapters/feishu.d.ts +16 -0
  127. package/dist/platform/adapters/feishu.js +67 -6
  128. package/dist/store/plugin-sync.d.ts +21 -0
  129. package/dist/store/plugin-sync.js +119 -0
  130. package/dist/store/schedule-repo.d.ts +6 -0
  131. package/dist/store/schedule-repo.js +11 -1
  132. package/dist/store/thread-repo.js +14 -0
  133. package/dist/store/version-migrations.d.ts +23 -4
  134. package/dist/store/version-migrations.js +167 -9
  135. package/dist/tui/App.js +11 -7
  136. package/dist/tui/components/Dashboard.js +26 -11
  137. package/dist/tui/components/InputBox.js +43 -4
  138. package/dist/tui/components/SidePanel.js +1 -1
  139. package/package.json +1 -1
  140. package/dist/domain/mcp/feishu/bitable.d.ts +0 -3
  141. package/dist/domain/mcp/feishu/bitable.js +0 -168
  142. package/dist/domain/mcp/feishu/blocks-to-text.d.ts +0 -19
  143. package/dist/domain/mcp/feishu/blocks-to-text.js +0 -43
  144. package/dist/domain/mcp/feishu/docx.d.ts +0 -3
  145. package/dist/domain/mcp/feishu/docx.js +0 -163
  146. package/dist/domain/mcp/feishu/drive.d.ts +0 -23
  147. package/dist/domain/mcp/feishu/drive.js +0 -66
  148. package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +0 -40
  149. package/dist/domain/mcp/feishu/markdown-to-blocks.js +0 -191
  150. package/dist/domain/mcp/feishu/sheets.d.ts +0 -3
  151. package/dist/domain/mcp/feishu/sheets.js +0 -119
  152. package/dist/domain/mcp/feishu/wiki.d.ts +0 -3
  153. package/dist/domain/mcp/feishu/wiki.js +0 -77
@@ -31,10 +31,10 @@ function buildNotice(threadId) {
31
31
  const t = threadStore.get(threadId);
32
32
  const cost = `$${(t.totalCostUsd || 0).toFixed(4)}`;
33
33
  const last = t.steps.length ? t.steps[t.steps.length - 1].output : null;
34
- const tail = t.abortReason || t.error || last || '(无输出)';
34
+ const tail = t.abortReason || t.error || last || '(no output)';
35
35
  const summary = tail.length > 200 ? tail.slice(0, 200) + '…' : tail;
36
36
  const label = t.templateName || t.activeAgent || 'thread';
37
- return `[后台线程完成] 你启动的线程 ${threadId} (${label}) 状态=${t.status} | ${cost}\n摘要: ${summary}\n调用 thread_result("${threadId}") 查看完整产出。`;
37
+ return `[Background thread done] Your thread ${threadId} (${label}) status=${t.status} | ${cost}\nSummary: ${summary}\nCall thread_result("${threadId}") to see the full output.`;
38
38
  }
39
39
  /** Child-result notice delivered into a suspended parent's pendingMessages. Echoes the
40
40
  * delegation contract and demands acceptance verification before the result is trusted
@@ -47,27 +47,27 @@ export function buildChildResultNotice(child) {
47
47
  const childCount = parent?.metadata?.childThreadIds?.length ?? 0;
48
48
  const maxChildren = parseInt(process.env.CORTEX_THREAD_MAX_CHILDREN || '8', 10) || 8;
49
49
  const lines = [
50
- `[子线程完成] ${child.id} (${label}) 状态=${child.status} | ${cost}`,
50
+ `[Child thread done] ${child.id} (${label}) status=${child.status} | ${cost}`,
51
51
  ];
52
52
  if (child.abortReason)
53
- lines.push(`子线程升级/中止原因: ${child.abortReason}`);
53
+ lines.push(`Child escalation/abort reason: ${child.abortReason}`);
54
54
  if (child.error)
55
- lines.push(`子线程错误: ${child.error}`);
55
+ lines.push(`Child error: ${child.error}`);
56
56
  if (contract) {
57
- lines.push(`契约: ${contract.goal}`);
57
+ lines.push(`Contract: ${contract.goal}`);
58
58
  if (contract.doneWhen)
59
59
  lines.push(`Done when: ${contract.doneWhen}`);
60
60
  if (contract.deliverablePath)
61
61
  lines.push(`Deliverable: ${contract.deliverablePath}`);
62
62
  }
63
- lines.push(`完整产出: thread_result("${child.id}")${child.artifactPath ? `;artifact: ${child.artifactPath}` : ''}`);
63
+ lines.push(`Full output: thread_result("${child.id}")${child.artifactPath ? `; artifact: ${child.artifactPath}` : ''}`);
64
64
  lines.push('');
65
- lines.push('验收要求(必须执行,不得凭子线程的汇报文本直接采信):');
66
- lines.push('1. 读取 deliverable 实物,逐条核对 done_when;涉及代码的跑测试验证。');
67
- lines.push('2. 达标 → 蒸馏关键结论进你的 artifact,继续你的计划。');
68
- lines.push('3. 未达标 → 写出 expected/actual 差异与失败假设,用修订后的契约重新 thread_start' +
69
- `(你已使用 ${childCount}/${maxChildren} 个子线程额度;额度耗尽时 thread_start 会被拒绝)。`);
70
- lines.push('4. 无法判断或方向性问题 → 调用 thread_abort 工具(附一行诊断)升级到你的上层。');
65
+ lines.push('Acceptance (mandatory — do NOT trust the child\'s self-reported summary):');
66
+ lines.push('1. Read the actual deliverable; check it against done_when item by item; for code, run the tests.');
67
+ lines.push('2. Passes → distill the key conclusions into your artifact and continue your plan.');
68
+ lines.push('3. Fails → write out the expected/actual gap and your failure hypothesis, then thread_start again with a revised contract' +
69
+ ` (you have used ${childCount}/${maxChildren} child-thread slots; thread_start is rejected once the quota is exhausted).`);
70
+ lines.push('4. Cannot judge, or a directional question → call the thread_abort tool (with a one-line diagnosis) to escalate to your manager.');
71
71
  return lines.join('\n');
72
72
  }
73
73
  /** Durable degraded-path notice to the project-report channel. */
@@ -86,10 +86,14 @@ async function postProjectNotice(t, text) {
86
86
  await adapter.postMessage(dest, { text });
87
87
  }
88
88
  }
89
- /** Rebuild RunThreadOptions for re-entering a suspended parent. extraHooks are not
90
- * persisted on ThreadRecord, so the dispatch task-status-check hook is reconstructed
91
- * from metadata.taskId/taskProject (the reason dispatch threads must store them). */
92
- function buildResumeOptions(parent) {
89
+ /** Rebuild RunThreadOptions for re-entering a suspended parent OR a rate-limit-paused thread.
90
+ * extraHooks are not persisted on ThreadRecord, so the dispatch task-status-check hook is
91
+ * reconstructed from metadata.taskId/taskProject (the reason dispatch threads must store them).
92
+ * statusMsg is restored from metadata.statusMsgRef (persisted at dispatch by task-dispatch /
93
+ * webhook) so the resumed run keeps updating the SAME live status message — without it the run
94
+ * carries statusMsg=null and the message freezes at "Paused — rate limited" forever even though
95
+ * the thread runs to completion (2026-06-23 finding: rate-limit resume status-message freeze). */
96
+ export function buildResumeOptions(parent) {
93
97
  const adapter = jobCtx.adapter;
94
98
  if (!adapter)
95
99
  return null;
@@ -105,7 +109,7 @@ function buildResumeOptions(parent) {
105
109
  channel: parent.channel,
106
110
  destination: dest,
107
111
  threadAnchorId: parent.platformThreadId ?? null,
108
- statusMsg: null,
112
+ statusMsg: m?.statusMsgRef ?? null,
109
113
  startTime: Date.now(),
110
114
  onProgress: null,
111
115
  onToolUse: null,
@@ -153,6 +157,23 @@ const defaultResume = (parentId) => {
153
157
  },
154
158
  });
155
159
  };
160
+ /** Resume a suspended manager thread to answer a subtask's question (ask_manager / DR-0016).
161
+ * Unlike maybeResumeParent, this does NOT require the manager's child sets to be empty — the
162
+ * manager is woken to answer, not because its children finished. It answers via answer_subtask,
163
+ * whose handler sets pendingControl='wait', so the manager re-suspends on its still-live children
164
+ * at the next step boundary. Shares the `resuming` guard so it never collides with a concurrent
165
+ * completion-driven resume (whichever wins, the question + any child results both sit in
166
+ * pendingMessages). No-op unless the manager is currently 'waiting'. */
167
+ export function resumeManagerForQuestion(managerThreadId, resume) {
168
+ if (resuming.has(managerThreadId))
169
+ return;
170
+ const mgr = threadStore.get(managerThreadId);
171
+ if (!mgr || mgr.status !== 'waiting')
172
+ return;
173
+ resuming.add(managerThreadId);
174
+ log.info(`resuming manager ${managerThreadId} to answer a subtask question`);
175
+ (resume ?? defaultResume)(managerThreadId);
176
+ }
156
177
  /** Resume `parentId` if (and only if) it is suspended with nothing left to wait on —
157
178
  * both thread children (waitingOn) and task children (waitingOnTasks, DR-0014 §8). */
158
179
  function maybeResumeParent(parentId, resume) {
@@ -220,26 +241,26 @@ export async function notifyThreadParent(childId, deps = {}) {
220
241
  export function buildTaskResultNotice(task, kind) {
221
242
  const lines = [];
222
243
  if (kind === 'completed') {
223
- lines.push(`[子任务完成] #${task.id} ${task.text}`);
244
+ lines.push(`[Subtask done] #${task.id} ${task.text}`);
224
245
  if (task.done_when)
225
246
  lines.push(`Done when: ${task.done_when}`);
226
247
  if (task.completed_note)
227
- lines.push(`完成备注: ${task.completed_note}`);
248
+ lines.push(`Completion note: ${task.completed_note}`);
228
249
  lines.push('');
229
- lines.push('验收要求(必须执行,不得凭完成备注直接采信):');
230
- lines.push('1. 读取实际产出(代码/文档/实验记录),逐条核对 done_when;涉及代码的跑测试验证。');
231
- lines.push('2. 达标 → 蒸馏关键结论进你的 artifact,继续你的计划。');
232
- lines.push(`3. 未达标 → cortex-task uncomplete 后修订该任务,或用 decompose --keep-parent 增加修订子任务,再调用 thread_wait。`);
233
- lines.push('4. 方向性问题 → 调用 thread_abort 工具(附一行诊断)升级。');
250
+ lines.push('Acceptance (mandatory — do NOT trust the completion note at face value):');
251
+ lines.push('1. Read the actual output (code/docs/experiment records); check it against done_when item by item; for code, run the tests.');
252
+ lines.push('2. Passes → distill the key conclusions into your artifact and continue your plan.');
253
+ lines.push(`3. Fails → cortex-task uncomplete then revise the task, or add a revision subtask with decompose --keep-parent, then call thread_wait.`);
254
+ lines.push('4. Directional question → call the thread_abort tool (with a one-line diagnosis) to escalate.');
234
255
  }
235
256
  else {
236
- lines.push(`[子任务被阻塞 — 升级信号] #${task.id} ${task.text}`);
237
- lines.push(`阻塞原因: ${task.blocked_by || '(未记录)'}`);
257
+ lines.push(`[Subtask blocked — escalation signal] #${task.id} ${task.text}`);
258
+ lines.push(`Blocked by: ${task.blocked_by || '(unrecorded)'}`);
238
259
  lines.push('');
239
- lines.push('这是子任务的升级:它无法自行完成。你必须处理:');
240
- lines.push('1. 诊断原因(读它的产出/日志;too-big 类原因 = 你当初的分解需要修订)。');
241
- lines.push('2. 可修复 → cortex-task unblock 并修订任务描述/done_when,或重建修订后的子任务(decompose --keep-parent),再调用 thread_wait。');
242
- lines.push('3. 超出你的职权或方向性问题 → 调用 thread_abort 工具(附一行诊断)向上升级。');
260
+ lines.push('This is the subtask escalating: it cannot finish on its own. You must handle it:');
261
+ lines.push('1. Diagnose the cause (read its output/logs; a too-big cause = your original decomposition needs revising).');
262
+ lines.push('2. Fixable → cortex-task unblock and revise the task description/done_when, or rebuild a revised subtask (decompose --keep-parent), then call thread_wait.');
263
+ lines.push('3. Beyond your authority or a directional question → call the thread_abort tool (with a one-line diagnosis) to escalate upward.');
243
264
  }
244
265
  return lines.join('\n');
245
266
  }
@@ -335,10 +356,10 @@ async function wakeSession(channel, notice, tag) {
335
356
  * no manager-style verification ceremony (the recipient is the requester, not a join node). */
336
357
  function buildTaskOriginNotice(task, kind) {
337
358
  if (kind === 'completed') {
338
- const note = task.completed_note ? `\n备注: ${task.completed_note}` : '';
339
- return `[任务完成] 你布置的任务 #${task.id} (${task.project})「${task.text}」已完成。${note}\n用 cortex-task show --task-id ${task.id} 查看详情。`;
359
+ const note = task.completed_note ? `\nNote: ${task.completed_note}` : '';
360
+ return `[Task done] The task you dispatched #${task.id} (${task.project}) "${task.text}" is complete.${note}\nRun cortex-task show --task-id ${task.id} for details.`;
340
361
  }
341
- return `[任务受阻] 你布置的任务 #${task.id} (${task.project})「${task.text}」被阻塞。\n阻塞原因: ${task.blocked_by || '(未记录)'}\n用 cortex-task show --task-id ${task.id} 查看详情,处理后可 cortex-task unblock。`;
362
+ return `[Task blocked] The task you dispatched #${task.id} (${task.project}) "${task.text}" is blocked.\nBlocked by: ${task.blocked_by || '(unrecorded)'}\nRun cortex-task show --task-id ${task.id} for details; once handled, cortex-task unblock.`;
342
363
  }
343
364
  /** Session→task wake (Problem 1): when a task created by an interactive session/agent turns
344
365
  * terminal, route a notice back to its origin channel. Default-on, no fallback — if origin_channel
@@ -388,7 +409,7 @@ export async function reconcileWaitingTasks(threadId, deps = {}) {
388
409
  m.waitingOnTasks = (m.waitingOnTasks ?? []).filter((id) => id !== taskId);
389
410
  if (!Array.isArray(m.pendingMessages))
390
411
  m.pendingMessages = [];
391
- m.pendingMessages.push(`[子任务丢失] #${taskId} 已不在 TASKS.yaml(可能被归档或删除),按失败处理。`);
412
+ m.pendingMessages.push(`[Subtask lost] #${taskId} is no longer in TASKS.yaml (likely archived or deleted); treating as failed.`);
392
413
  });
393
414
  log.warn(`reconcile: dropped missing task ${taskId} from waiting thread ${threadId}`);
394
415
  }
@@ -437,7 +458,7 @@ export async function recoverWaitingThreads(deps = {}) {
437
458
  meta.waitingOn = (meta.waitingOn ?? []).filter((id) => id !== childId);
438
459
  if (!Array.isArray(meta.pendingMessages))
439
460
  meta.pendingMessages = [];
440
- meta.pendingMessages.push(`[子线程丢失] ${childId} 的记录已不存在(可能被清理),按失败处理。`);
461
+ meta.pendingMessages.push(`[Child thread lost] the record for ${childId} no longer exists (likely cleaned up); treating as failed.`);
441
462
  });
442
463
  log.warn(`recover: dropped missing child ${childId} from waiting parent ${parent.id}`);
443
464
  }
@@ -0,0 +1,26 @@
1
+ import type { PlatformAdapter } from '../platform/index.js';
2
+ /** Feature gate: turn-completion notification is ON by default. Opt out by setting
3
+ * CORTEX_TURN_NOTIFY to a falsy value (0 / false / off / no). */
4
+ export declare function isTurnNotifyEnabled(): boolean;
5
+ /** Minimum turn duration (seconds) before a completion notification is pushed.
6
+ * Configurable via CORTEX_TURN_NOTIFY_THRESHOLD_S; defaults to 60s. A non-positive
7
+ * or unparseable value falls back to the default. */
8
+ export declare function getTurnNotifyThresholdS(): number;
9
+ /** Push a NEW message to the conversation's channel when a long-running, user-initiated
10
+ * turn finishes — so the user gets an actual push notification (editing the status
11
+ * message to "✓ Done" does not notify on Slack or Feishu). Works for both Slack and
12
+ * Feishu through the PlatformAdapter abstraction (Composite fans out to both).
13
+ *
14
+ * Gated by: feature flag, interactive-channel scope, and a duration threshold.
15
+ * Never throws — a failed notification must not affect the main turn. */
16
+ export declare function maybeNotifyTurnComplete(params: {
17
+ adapter: PlatformAdapter;
18
+ channel: string;
19
+ threadAnchorId: string | null;
20
+ sessionName: string | null;
21
+ sessionId: string | null;
22
+ elapsedS: number;
23
+ elapsedStr: string;
24
+ status: 'completed' | 'failed';
25
+ metricsSuffix?: string;
26
+ }): Promise<void>;
@@ -0,0 +1,66 @@
1
+ // input: orch/bg-continuation(isInteractiveChannel), store/outbound-queue(durablePost,getOutboundQueue), core/status-format(buildSessionTag), core/icons, core/i18n
2
+ // output: isTurnNotifyEnabled / getTurnNotifyThresholdS / maybeNotifyTurnComplete
3
+ // pos: orch layer — push a NEW message (Slack + Feishu) when a long-running user turn finishes
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { createLogger } from '../core/log.js';
6
+ import { Icons } from '../core/icons.js';
7
+ import { t } from '../core/i18n.js';
8
+ import { buildSessionTag } from '../core/status-format.js';
9
+ import { getOutboundQueue, durablePost } from '../store/outbound-queue.js';
10
+ import { isInteractiveChannel } from './bg-continuation.js';
11
+ const log = createLogger('turn-notify');
12
+ const DEFAULT_THRESHOLD_S = 60;
13
+ /** Feature gate: turn-completion notification is ON by default. Opt out by setting
14
+ * CORTEX_TURN_NOTIFY to a falsy value (0 / false / off / no). */
15
+ export function isTurnNotifyEnabled() {
16
+ const v = process.env.CORTEX_TURN_NOTIFY;
17
+ if (v === undefined)
18
+ return true;
19
+ return !['0', 'false', 'off', 'no'].includes(v.trim().toLowerCase());
20
+ }
21
+ /** Minimum turn duration (seconds) before a completion notification is pushed.
22
+ * Configurable via CORTEX_TURN_NOTIFY_THRESHOLD_S; defaults to 60s. A non-positive
23
+ * or unparseable value falls back to the default. */
24
+ export function getTurnNotifyThresholdS() {
25
+ const raw = process.env.CORTEX_TURN_NOTIFY_THRESHOLD_S;
26
+ if (raw === undefined)
27
+ return DEFAULT_THRESHOLD_S;
28
+ const n = Number(raw.trim());
29
+ if (!Number.isFinite(n) || n <= 0)
30
+ return DEFAULT_THRESHOLD_S;
31
+ return n;
32
+ }
33
+ /** Push a NEW message to the conversation's channel when a long-running, user-initiated
34
+ * turn finishes — so the user gets an actual push notification (editing the status
35
+ * message to "✓ Done" does not notify on Slack or Feishu). Works for both Slack and
36
+ * Feishu through the PlatformAdapter abstraction (Composite fans out to both).
37
+ *
38
+ * Gated by: feature flag, interactive-channel scope, and a duration threshold.
39
+ * Never throws — a failed notification must not affect the main turn. */
40
+ export async function maybeNotifyTurnComplete(params) {
41
+ const { adapter, channel, threadAnchorId, sessionName, sessionId, elapsedS, elapsedStr, status, metricsSuffix } = params;
42
+ try {
43
+ if (!isTurnNotifyEnabled())
44
+ return;
45
+ if (!isInteractiveChannel(channel))
46
+ return;
47
+ if (elapsedS < getTurnNotifyThresholdS())
48
+ return;
49
+ const sessionTag = buildSessionTag(sessionName, sessionId);
50
+ const text = status === 'completed'
51
+ ? `${Icons.ok} ${t('notify.turnComplete')} | ${sessionTag}(${elapsedStr}${metricsSuffix ?? ''})`
52
+ : `${Icons.error} ${t('notify.turnFailed')} | ${sessionTag}(${elapsedStr})`;
53
+ const dest = { type: 'interactive-reply', conduit: channel, sessionId: sessionId ?? '' };
54
+ const opts = threadAnchorId ? { threadId: threadAnchorId } : undefined;
55
+ const queue = getOutboundQueue();
56
+ if (queue) {
57
+ await durablePost(queue, adapter, dest, { text }, opts);
58
+ }
59
+ else {
60
+ await adapter.postMessage(dest, { text }, opts);
61
+ }
62
+ }
63
+ catch (err) {
64
+ log.warn('turn-complete notification failed:', err?.message ?? err);
65
+ }
66
+ }
@@ -87,6 +87,22 @@ export declare class FeishuAdapter implements PlatformAdapter {
87
87
  * and the images from one mixed message.
88
88
  */
89
89
  private parsePostContent;
90
+ /**
91
+ * Resolve a Feishu message's human-readable text from its type + parsed content.
92
+ * `post` (rich text) buries text in a 2D run array; plain text lives in
93
+ * parsed.text; a few legacy payloads ship a bare non-JSON string as content.
94
+ * Shared by both inbound messages and quoted-parent enrichment.
95
+ */
96
+ private extractMessageText;
97
+ /**
98
+ * Fetch the directly-quoted parent message (one level) and project it to the same
99
+ * { text, files } shape an inbound message produces, so a reply can be enriched
100
+ * with what it quotes — notably files, since a Feishu file message carries no text
101
+ * and thus cannot @ the bot. Returns null on any failure (best-effort).
102
+ * NOTE: im.v1.message.get returns content under data.items[].body.content (a JSON
103
+ * string), NOT the top-level `content` field the receive_v1 event uses.
104
+ */
105
+ private fetchQuotedParent;
90
106
  private handleCardAction;
91
107
  private buildMessagePayload;
92
108
  private buildCardJson;
@@ -468,11 +468,7 @@ export class FeishuAdapter {
468
468
  // images — the text is NOT a top-level `parsed.text` but buried in a 2D array
469
469
  // of paragraph element-runs, so the simple text/raw-string path below would
470
470
  // yield '' and drop the user's message. Parse post specially.
471
- const text = messageType === 'post'
472
- ? this.parsePostContent(parsed).text
473
- : (typeof parsed.text === 'string'
474
- ? parsed.text
475
- : (typeof message.content === 'string' && !message.content.startsWith('{') ? message.content : ''));
471
+ let text = this.extractMessageText(messageType, parsed, message.content || '');
476
472
  const ref = {
477
473
  conduit: this._wrap(chatId),
478
474
  messageId,
@@ -480,7 +476,24 @@ export class FeishuAdapter {
480
476
  };
481
477
  // Extract file references from the parsed content. The id (file_key/image_key)
482
478
  // plus message_id + resourceType are needed by downloadFile (messageResource.get).
483
- const files = this.extractInboundFiles(messageType, parsed, messageId, chatId);
479
+ let files = this.extractInboundFiles(messageType, parsed, messageId, chatId);
480
+ // Quote/reply enrichment. When a message replies to another (parent_id set),
481
+ // Feishu delivers ONLY the reply — the quoted message's text/files are not
482
+ // inlined. A user sharing a file cannot @ the bot on the file message itself
483
+ // (file messages carry no text), so they reply-and-@ instead; without this the
484
+ // file would be lost. Fetch the direct parent (one level) unconditionally —
485
+ // including bot-authored parents — and merge its text + files into this message.
486
+ // Best-effort: a fetch failure must never drop the user's own message.
487
+ if (parentId) {
488
+ const quoted = await this.fetchQuotedParent(parentId, chatId);
489
+ if (quoted) {
490
+ if (quoted.text)
491
+ text = text ? `${text}\n\n[引用消息]\n${quoted.text}` : quoted.text;
492
+ if (quoted.files && quoted.files.length) {
493
+ files = files ? [...files, ...quoted.files] : quoted.files;
494
+ }
495
+ }
496
+ }
484
497
  // TODO: Parse Feishu forwarded/merged messages (merge_forward msg type) into
485
498
  // IncomingAttachment[]. Feishu's format differs from Slack's msg.attachments.
486
499
  const kind = files ? 'file_share' : 'user';
@@ -602,6 +615,54 @@ export class FeishuAdapter {
602
615
  }
603
616
  return { text, imageKeys };
604
617
  }
618
+ /**
619
+ * Resolve a Feishu message's human-readable text from its type + parsed content.
620
+ * `post` (rich text) buries text in a 2D run array; plain text lives in
621
+ * parsed.text; a few legacy payloads ship a bare non-JSON string as content.
622
+ * Shared by both inbound messages and quoted-parent enrichment.
623
+ */
624
+ extractMessageText(messageType, parsed, rawContent) {
625
+ if (messageType === 'post')
626
+ return this.parsePostContent(parsed).text;
627
+ if (typeof parsed?.text === 'string')
628
+ return parsed.text;
629
+ if (typeof rawContent === 'string' && rawContent && !rawContent.startsWith('{'))
630
+ return rawContent;
631
+ return '';
632
+ }
633
+ /**
634
+ * Fetch the directly-quoted parent message (one level) and project it to the same
635
+ * { text, files } shape an inbound message produces, so a reply can be enriched
636
+ * with what it quotes — notably files, since a Feishu file message carries no text
637
+ * and thus cannot @ the bot. Returns null on any failure (best-effort).
638
+ * NOTE: im.v1.message.get returns content under data.items[].body.content (a JSON
639
+ * string), NOT the top-level `content` field the receive_v1 event uses.
640
+ */
641
+ async fetchQuotedParent(parentId, chatId) {
642
+ try {
643
+ const resp = await this.client.im.v1.message.get({ path: { message_id: parentId } });
644
+ const item = resp?.data?.items?.[0];
645
+ if (!item)
646
+ return null;
647
+ const messageType = item.msg_type || '';
648
+ const rawContent = item.body?.content || '';
649
+ let parsed = {};
650
+ try {
651
+ parsed = JSON.parse(rawContent || '{}');
652
+ }
653
+ catch {
654
+ parsed = {};
655
+ }
656
+ const text = this.extractMessageText(messageType, parsed, rawContent);
657
+ // Files of the parent must download against the PARENT's message_id.
658
+ const files = this.extractInboundFiles(messageType, parsed, item.message_id || parentId, chatId);
659
+ return { text, files };
660
+ }
661
+ catch (e) {
662
+ log.warn(`Failed to fetch quoted parent ${parentId}: ${e.message}`);
663
+ return null;
664
+ }
665
+ }
605
666
  async handleCardAction(data) {
606
667
  const event = data.event || data;
607
668
  const action = event.action || {};
@@ -0,0 +1,21 @@
1
+ /** Parse the `version` field from a plugin.json manifest string, or null if absent/malformed.
2
+ * compareCalVer is a generic numeric dotted-version comparator, so plain semver ("0.1.0") works. */
3
+ export declare function parsePluginVersion(manifestJson: string): string | null;
4
+ /**
5
+ * Keep version-managed plugins in PLUGINS_DIR in sync with the shipped defaults.
6
+ *
7
+ * A default plugin that declares a `version` in `.claude-plugin/plugin.json` is deployed when
8
+ * missing, and refreshed (all its shipped files rewritten) whenever the shipped version is newer
9
+ * than the deployed one. A missing or unversioned deployed copy counts as oldest, so legacy installs
10
+ * are brought under management on first run. Unversioned default plugins (no manifest version) are
11
+ * left to init's copy-if-missing and never touched here. User-added files inside a managed plugin are
12
+ * preserved (only shipped files are written, nothing is deleted). Idempotent and crash-safe via
13
+ * atomicWrite.
14
+ *
15
+ * `opts` exists for tests; production calls it with no args (real DEFAULTS_DIR/plugins + PLUGINS_DIR).
16
+ * Returns the list of plugin names that were deployed or refreshed.
17
+ */
18
+ export declare function syncManagedPlugins(opts?: {
19
+ srcDir?: string;
20
+ dstDir?: string;
21
+ }): Promise<string[]>;
@@ -0,0 +1,119 @@
1
+ // input: DEFAULTS_DIR/plugins/<plugin> (each with .claude-plugin/plugin.json `version`) + PLUGINS_DIR (DATA_DIR/plugins)
2
+ // output: syncManagedPlugins() — deploys a new plugin, or refreshes a deployed one when the shipped version is newer
3
+ // pos: Startup asset-sync sibling to runMigrations / syncManagedHooks; keeps DATA_DIR/plugins in sync
4
+ // with defaults. init.ts copyDefaults() uses safeCopyDir (copy-if-missing) and only runs on
5
+ // `cortex init`, so an existing install never gets a NEW plugin or an UPDATED skill on upgrade.
6
+ // This closes that gap, keyed on each plugin's .claude-plugin/plugin.json `version`.
7
+ //
8
+ // CONVENTION: whenever you change ANY file inside a plugin (a skill's SKILL.md, a script, the
9
+ // manifest), bump that plugin's `version` in .claude-plugin/plugin.json — the analog of bumping
10
+ // @cortex-hook-version on a hook. Without a bump the change will NOT propagate to existing installs.
11
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
12
+ import * as fs from 'node:fs/promises';
13
+ import { existsSync } from 'node:fs';
14
+ import * as path from 'node:path';
15
+ import { DEFAULTS_DIR, PLUGINS_DIR } from '../core/paths.js';
16
+ import { atomicWrite } from '../core/atomic-write.js';
17
+ import { compareCalVer } from './version-migrations.js';
18
+ import { createLogger } from '../core/log.js';
19
+ const log = createLogger('plugin-sync');
20
+ const MANIFEST_REL = path.join('.claude-plugin', 'plugin.json');
21
+ /** Parse the `version` field from a plugin.json manifest string, or null if absent/malformed.
22
+ * compareCalVer is a generic numeric dotted-version comparator, so plain semver ("0.1.0") works. */
23
+ export function parsePluginVersion(manifestJson) {
24
+ try {
25
+ const parsed = JSON.parse(manifestJson);
26
+ if (parsed && typeof parsed === 'object' && typeof parsed.version === 'string') {
27
+ const v = parsed.version.trim();
28
+ return v.length > 0 ? v : null;
29
+ }
30
+ }
31
+ catch {
32
+ // malformed JSON → treat as unversioned
33
+ }
34
+ return null;
35
+ }
36
+ /** Read a plugin's manifest version from `<pluginDir>/.claude-plugin/plugin.json`, or null. */
37
+ async function readPluginVersion(pluginDir) {
38
+ try {
39
+ return parsePluginVersion(await fs.readFile(path.join(pluginDir, MANIFEST_REL), 'utf8'));
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ /** Recursively walk every file under `src` and atomicWrite it into `dst` at the same relative
46
+ * path, creating parent dirs as needed. Overwrites shipped files; never deletes anything already
47
+ * in `dst` (so user-added skills/files inside a managed plugin are preserved). */
48
+ async function copyPluginTree(src, dst) {
49
+ const entries = await fs.readdir(src, { withFileTypes: true });
50
+ for (const entry of entries) {
51
+ const srcPath = path.join(src, entry.name);
52
+ const dstPath = path.join(dst, entry.name);
53
+ if (entry.isDirectory()) {
54
+ await copyPluginTree(srcPath, dstPath);
55
+ }
56
+ else if (entry.isFile()) {
57
+ await fs.mkdir(path.dirname(dstPath), { recursive: true });
58
+ await atomicWrite(dstPath, await fs.readFile(srcPath, 'utf8'));
59
+ }
60
+ }
61
+ }
62
+ /**
63
+ * Keep version-managed plugins in PLUGINS_DIR in sync with the shipped defaults.
64
+ *
65
+ * A default plugin that declares a `version` in `.claude-plugin/plugin.json` is deployed when
66
+ * missing, and refreshed (all its shipped files rewritten) whenever the shipped version is newer
67
+ * than the deployed one. A missing or unversioned deployed copy counts as oldest, so legacy installs
68
+ * are brought under management on first run. Unversioned default plugins (no manifest version) are
69
+ * left to init's copy-if-missing and never touched here. User-added files inside a managed plugin are
70
+ * preserved (only shipped files are written, nothing is deleted). Idempotent and crash-safe via
71
+ * atomicWrite.
72
+ *
73
+ * `opts` exists for tests; production calls it with no args (real DEFAULTS_DIR/plugins + PLUGINS_DIR).
74
+ * Returns the list of plugin names that were deployed or refreshed.
75
+ */
76
+ export async function syncManagedPlugins(opts = {}) {
77
+ const srcDir = opts.srcDir ?? path.join(DEFAULTS_DIR, 'plugins');
78
+ const dstDir = opts.dstDir ?? PLUGINS_DIR;
79
+ if (!existsSync(srcDir))
80
+ return [];
81
+ let entries;
82
+ try {
83
+ entries = await fs.readdir(srcDir, { withFileTypes: true });
84
+ }
85
+ catch {
86
+ return [];
87
+ }
88
+ await fs.mkdir(dstDir, { recursive: true });
89
+ const updated = [];
90
+ for (const entry of entries) {
91
+ if (!entry.isDirectory())
92
+ continue;
93
+ const name = entry.name;
94
+ const srcPlugin = path.join(srcDir, name);
95
+ const srcVer = await readPluginVersion(srcPlugin);
96
+ if (!srcVer)
97
+ continue; // unversioned default → leave to init's copy-if-missing
98
+ const dstPlugin = path.join(dstDir, name);
99
+ if (existsSync(dstPlugin)) {
100
+ const dstVer = await readPluginVersion(dstPlugin);
101
+ // Deployed copy already at or ahead of the shipped version → current; skip.
102
+ // A missing/unparseable deployed version (dstVer === null) counts as oldest → refresh.
103
+ if (dstVer && compareCalVer(dstVer, srcVer) >= 0)
104
+ continue;
105
+ }
106
+ try {
107
+ await copyPluginTree(srcPlugin, dstPlugin);
108
+ updated.push(name);
109
+ log.info(`synced plugin ${name} → ${srcVer}`);
110
+ }
111
+ catch (e) {
112
+ log.error(`failed to sync plugin ${name}: ${e.message}`);
113
+ }
114
+ }
115
+ if (updated.length === 0) {
116
+ log.info('managed plugins up to date');
117
+ }
118
+ return updated;
119
+ }
@@ -1,3 +1,4 @@
1
+ import type { ResumeEntry } from '../domain/costs/resume-registry.js';
1
2
  export declare const SCHEDULES_FILE: string;
2
3
  export declare const CHANNEL_REGISTRY_FILE: string;
3
4
  /** Where a fired scheduled-task should land. Resolved by the cortex_schedule_add MCP tool
@@ -54,6 +55,9 @@ export interface SchedulesData {
54
55
  activatedAt: number;
55
56
  modes?: string[];
56
57
  } | null;
58
+ /** Sessions/threads interrupted by a rate limit, awaiting auto-resume when the
59
+ * window resets. Owned by domain/costs/resume-registry.ts. */
60
+ resumeQueue?: ResumeEntry[] | null;
57
61
  }
58
62
  /** Convenience: reverse-lookup projectId from a Slack channel via channel-registry.json. */
59
63
  export declare function channelToProjectId(channel: string): string | null;
@@ -76,6 +80,8 @@ export declare class ScheduleRepo {
76
80
  activatedAt: number;
77
81
  modes?: string[];
78
82
  } | null>;
83
+ setResumeQueue(entries: ResumeEntry[] | null): Promise<void>;
84
+ getResumeQueue(): Promise<ResumeEntry[]>;
79
85
  /** Generic mutate passthrough for composite operations. */
80
86
  mutate<R>(fn: (data: SchedulesData) => {
81
87
  next: SchedulesData;
@@ -1,5 +1,5 @@
1
1
  // input: schedules.json + channel-registry.json + JsonRepository
2
- // output: ScheduleRepo (read / addTask / removeTask / updateTask / rateLimitThrottle) + migration helpers
2
+ // output: ScheduleRepo (read / addTask / removeTask / updateTask / rateLimitThrottle / resumeQueue) + migration helpers
3
3
  // pos: Schedule persistence layer. Based on JsonRepository abstraction (Pattern A), AsyncMutex serializes reads/writes of schedules.json.
4
4
  // Migration from channel→projectId reads channel-registry.json synchronously for reverse lookup.
5
5
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
@@ -117,6 +117,16 @@ export class ScheduleRepo {
117
117
  const data = await this._repo.read();
118
118
  return data.rateLimitThrottle || null;
119
119
  }
120
+ async setResumeQueue(entries) {
121
+ await this._repo.mutate((data) => {
122
+ data.resumeQueue = entries;
123
+ return { next: data, result: undefined };
124
+ });
125
+ }
126
+ async getResumeQueue() {
127
+ const data = await this._repo.read();
128
+ return data.resumeQueue ?? [];
129
+ }
120
130
  /** Generic mutate passthrough for composite operations. */
121
131
  async mutate(fn) {
122
132
  return this._repo.mutate(fn);
@@ -155,6 +155,10 @@ class ThreadRepo {
155
155
  || record.metadata?.waitingOnTasks?.length);
156
156
  if (isSuspendedParent)
157
157
  continue;
158
+ // Rate-limit-paused threads survive restarts: the throttle re-arms its resume timer (or
159
+ // fires immediately if the window already passed) and resume-dispatcher re-enters them.
160
+ if (record.status === 'rate_limited')
161
+ continue;
158
162
  if (record.status === 'running' || record.status === 'waiting') {
159
163
  record.status = 'failed';
160
164
  record.error = 'Interrupted by server restart';
@@ -196,6 +200,16 @@ class ThreadRepo {
196
200
  record.updatedAt = new Date().toISOString();
197
201
  staleWaiting++;
198
202
  }
203
+ // Limbo safety net: a rate-limit-paused thread that never got resumed (auto-resume
204
+ // disabled, or the window-reset resume was dropped) is failed once past maxAge so it
205
+ // does not linger forever.
206
+ if (record.status === 'rate_limited' && record.updatedAt < cutoff) {
207
+ record.status = 'failed';
208
+ record.error = 'rate-limit-paused thread never resumed';
209
+ record.endedAt = new Date().toISOString();
210
+ record.updatedAt = new Date().toISOString();
211
+ staleWaiting++;
212
+ }
199
213
  }
200
214
  if (staleWaiting > 0)
201
215
  log.info(`Failed ${staleWaiting} stale waiting threads (leak safety net)`);