@cortex-agent/server 2026.6.11 → 2026.6.18

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 (105) hide show
  1. package/defaults/config/thread-templates.json +2 -2
  2. package/defaults/hooks/task-status-check.mjs +9 -7
  3. package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +103 -16
  4. package/defaults/plugins/cortex-system/skills/orient/SKILL.md +6 -6
  5. package/defaults/plugins/cortex-system/skills/thread/SKILL.md +29 -35
  6. package/defaults/prompts/directives/manager.md +21 -11
  7. package/dist/agent-adapter/claude/spawn-args.d.ts +5 -0
  8. package/dist/agent-adapter/claude/spawn-args.js +6 -0
  9. package/dist/agent-adapter/types.d.ts +4 -0
  10. package/dist/core/gateway-generator.js +24 -3
  11. package/dist/core/i18n.d.ts +19 -0
  12. package/dist/core/i18n.js +46 -0
  13. package/dist/core/locales/en.d.ts +438 -0
  14. package/dist/core/locales/en.js +24 -0
  15. package/dist/core/locales/slices/commands.d.ts +214 -0
  16. package/dist/core/locales/slices/commands.js +462 -0
  17. package/dist/core/locales/slices/init.d.ts +121 -0
  18. package/dist/core/locales/slices/init.js +380 -0
  19. package/dist/core/locales/slices/interactions.d.ts +47 -0
  20. package/dist/core/locales/slices/interactions.js +102 -0
  21. package/dist/core/locales/slices/lang.d.ts +8 -0
  22. package/dist/core/locales/slices/lang.js +18 -0
  23. package/dist/core/locales/slices/scheduling.d.ts +36 -0
  24. package/dist/core/locales/slices/scheduling.js +74 -0
  25. package/dist/core/locales/slices/startup.d.ts +6 -0
  26. package/dist/core/locales/slices/startup.js +14 -0
  27. package/dist/core/locales/slices/status.d.ts +20 -0
  28. package/dist/core/locales/slices/status.js +48 -0
  29. package/dist/core/locales/zh.d.ts +5 -0
  30. package/dist/core/locales/zh.js +23 -0
  31. package/dist/core/singleton-lock.d.ts +23 -0
  32. package/dist/core/singleton-lock.js +53 -0
  33. package/dist/core/status-format.js +2 -1
  34. package/dist/core/task-parser.d.ts +6 -0
  35. package/dist/core/task-parser.js +10 -0
  36. package/dist/core/types/thread-types.d.ts +29 -0
  37. package/dist/core/utils.d.ts +9 -1
  38. package/dist/core/utils.js +9 -1
  39. package/dist/domain/agents/config.d.ts +2 -1
  40. package/dist/domain/agents/config.js +25 -6
  41. package/dist/domain/agents/facade.d.ts +4 -0
  42. package/dist/domain/agents/facade.js +3 -1
  43. package/dist/domain/mcp/core-server.js +15 -9
  44. package/dist/domain/mcp/tools/task-monitor.d.ts +2 -0
  45. package/dist/domain/mcp/tools/task-monitor.js +99 -0
  46. package/dist/domain/mcp/tools/thread-ops.js +50 -85
  47. package/dist/domain/scheduling/jobs/task-dispatch.js +18 -16
  48. package/dist/domain/scheduling/schedule-command.js +38 -37
  49. package/dist/domain/system/github-release.d.ts +18 -0
  50. package/dist/domain/system/github-release.js +106 -0
  51. package/dist/domain/system/preferences.d.ts +12 -0
  52. package/dist/domain/system/preferences.js +36 -0
  53. package/dist/domain/tasks/dispatch-utils.d.ts +5 -0
  54. package/dist/domain/tasks/dispatch-utils.js +9 -1
  55. package/dist/domain/tasks/dispatcher.d.ts +11 -2
  56. package/dist/domain/tasks/dispatcher.js +41 -11
  57. package/dist/domain/tasks/system/task-cli.d.ts +1 -0
  58. package/dist/domain/tasks/system/task-cli.js +82 -6
  59. package/dist/domain/tasks/system/task-mutations.d.ts +6 -1
  60. package/dist/domain/tasks/system/task-mutations.js +10 -1
  61. package/dist/domain/threads/hook-runner.js +1 -0
  62. package/dist/domain/threads/prompt-builder.d.ts +6 -0
  63. package/dist/domain/threads/prompt-builder.js +34 -11
  64. package/dist/domain/threads/runner.d.ts +5 -0
  65. package/dist/domain/threads/runner.js +44 -11
  66. package/dist/domain/threads/state-machine.d.ts +9 -12
  67. package/dist/domain/threads/state-machine.js +27 -50
  68. package/dist/entry/app.js +36 -3
  69. package/dist/entry/daemon.js +12 -30
  70. package/dist/entry/init.d.ts +4 -3
  71. package/dist/entry/init.js +151 -208
  72. package/dist/entry/startup-notify.js +6 -3
  73. package/dist/hooks/task-status-check.mjs +9 -7
  74. package/dist/orchestration/interactions/interaction-handlers.js +12 -11
  75. package/dist/orchestration/interactions/update-prompt-slack.js +11 -10
  76. package/dist/orchestration/interactions/update-prompt.js +66 -11
  77. package/dist/orchestration/lifecycle.js +13 -12
  78. package/dist/orchestration/routing/commands/cancel.js +10 -9
  79. package/dist/orchestration/routing/commands/channel.js +27 -26
  80. package/dist/orchestration/routing/commands/cost.js +10 -2
  81. package/dist/orchestration/routing/commands/device.js +11 -9
  82. package/dist/orchestration/routing/commands/dispatch.js +10 -10
  83. package/dist/orchestration/routing/commands/index.js +6 -2
  84. package/dist/orchestration/routing/commands/lang.d.ts +3 -0
  85. package/dist/orchestration/routing/commands/lang.js +31 -0
  86. package/dist/orchestration/routing/commands/mode.js +28 -27
  87. package/dist/orchestration/routing/commands/nvtop.js +13 -12
  88. package/dist/orchestration/routing/commands/orient.js +2 -1
  89. package/dist/orchestration/routing/commands/schedule.js +23 -22
  90. package/dist/orchestration/routing/commands/sendfile.js +8 -7
  91. package/dist/orchestration/routing/commands/session.js +11 -10
  92. package/dist/orchestration/routing/commands/status.js +78 -71
  93. package/dist/orchestration/routing/commands/tail.js +6 -5
  94. package/dist/orchestration/routing/commands/task.js +23 -22
  95. package/dist/orchestration/routing/commands/thread-handlers.js +40 -39
  96. package/dist/orchestration/routing/webhook.js +38 -1
  97. package/dist/orchestration/status-helpers.js +6 -5
  98. package/dist/orchestration/thread-callback.d.ts +11 -1
  99. package/dist/orchestration/thread-callback.js +66 -30
  100. package/dist/platform/adapters/feishu.d.ts +11 -0
  101. package/dist/platform/adapters/feishu.js +74 -3
  102. package/dist/platform/interactive-builder.js +19 -18
  103. package/dist/store/version-migrations.d.ts +7 -0
  104. package/dist/store/version-migrations.js +88 -0
  105. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import { Icons } from '../../../core/icons.js';
2
+ import { t } from '../../../core/i18n.js';
2
3
  import { scanAllTasks, completedHashSet, isActionable } from '../../../domain/tasks/parser.js';
3
4
  import { PROJECTS_DIR } from '../../../core/utils.js';
4
5
  import * as path from 'path';
@@ -13,8 +14,8 @@ function formatTaskList(tasks, filter, project) {
13
14
  default: return true;
14
15
  }
15
16
  });
16
- const filterLabel = filter === 'all' ? '' : ` — ${filter}`;
17
- const lines = [`*Tasks for \`${project}\`* (${filtered.length}/${tasks.length})${filterLabel}\n`];
17
+ const filterLabel = filter === 'all' ? '' : t('cmd.task.filterLabel', { filter });
18
+ const lines = [`${t('cmd.task.header', { project, shown: filtered.length, total: tasks.length, filterLabel })}\n`];
18
19
  for (const task of filtered) {
19
20
  const status = task.status === 'done' ? Icons.ok : (task.blocked_by ? Icons.blocked : (task.claimed_by ? Icons.refresh : (task.paused ? Icons.paused : Icons.pending)));
20
21
  const id = task.id ? `\`${task.id}\`` : '—';
@@ -23,27 +24,27 @@ function formatTaskList(tasks, filter, project) {
23
24
  tags.push(task.priority);
24
25
  if (task.gpu)
25
26
  tags.push(`gpu:${task.gpu}`);
26
- const statusLabel = task.status === 'done' ? 'completed'
27
- : task.blocked_by ? `blocked: ${task.blocked_by}`
28
- : task.claimed_by ? `in-progress: ${task.claimed_by}`
29
- : task.paused ? 'paused'
30
- : (task.approval_needed && !task.approved_at) ? 'approval-needed'
31
- : isActionable(task, completed) ? 'actionable'
32
- : 'open';
27
+ const statusLabel = task.status === 'done' ? t('cmd.task.statusCompleted')
28
+ : task.blocked_by ? t('cmd.task.statusBlocked', { by: task.blocked_by })
29
+ : task.claimed_by ? t('cmd.task.statusInProgress', { by: task.claimed_by })
30
+ : task.paused ? t('cmd.task.statusPaused')
31
+ : (task.approval_needed && !task.approved_at) ? t('cmd.task.statusApprovalNeeded')
32
+ : isActionable(task, completed) ? t('cmd.task.statusActionable')
33
+ : t('cmd.task.statusOpen');
33
34
  lines.push(`${status} ${id} *${task.text}*`);
34
- lines.push(` Status: ${statusLabel} · Priority: ${task.priority}`);
35
+ lines.push(t('cmd.task.statusLine', { status: statusLabel, priority: task.priority }));
35
36
  if (tags.length)
36
- lines.push(` Tags: ${tags.join(', ')}`);
37
+ lines.push(t('cmd.task.tagsLine', { tags: tags.join(', ') }));
37
38
  if (task.why)
38
- lines.push(` Why: ${task.why}`);
39
+ lines.push(t('cmd.task.whyLine', { why: task.why }));
39
40
  if (task.done_when)
40
- lines.push(` Done when: ${task.done_when}`);
41
+ lines.push(t('cmd.task.doneWhenLine', { doneWhen: task.done_when }));
41
42
  if (task.depends_on.length)
42
- lines.push(` Depends on: ${task.depends_on.join(', ')}`);
43
+ lines.push(t('cmd.task.dependsLine', { depends: task.depends_on.join(', ') }));
43
44
  lines.push('');
44
45
  }
45
46
  if (filtered.length === 0) {
46
- lines.push(`No ${filter} tasks found.`);
47
+ lines.push(t('cmd.task.noneFound', { filter }));
47
48
  }
48
49
  return lines.join('\n');
49
50
  }
@@ -68,10 +69,10 @@ function textToSectionBlocks(text) {
68
69
  }
69
70
  function buildFilterButtons(project) {
70
71
  const TASK_FILTERS = [
71
- { label: 'All', value: 'all' },
72
- { label: 'Actionable', value: 'actionable' },
73
- { label: 'In Progress', value: 'in-progress' },
74
- { label: 'Blocked', value: 'blocked' },
72
+ { label: t('cmd.task.filterAll'), value: 'all' },
73
+ { label: t('cmd.task.filterActionable'), value: 'actionable' },
74
+ { label: t('cmd.task.filterInProgress'), value: 'in-progress' },
75
+ { label: t('cmd.task.filterBlocked'), value: 'blocked' },
75
76
  ];
76
77
  return TASK_FILTERS.map(f => ({
77
78
  type: 'button',
@@ -111,18 +112,18 @@ export function createTasksHandler(router) {
111
112
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
112
113
  const args = trimmedMessage.split(/\s+/).slice(1);
113
114
  if (args.length === 0) {
114
- await adapter.postMessage(dest, { text: `${Icons.error} Usage: \`!tasks <project>\`` });
115
+ await adapter.postMessage(dest, { text: `${Icons.error} ${t('cmd.task.usage')}` });
115
116
  return;
116
117
  }
117
118
  const project = args[0];
118
119
  const projectDir = path.join(PROJECTS_DIR, project);
119
120
  if (!existsSync(projectDir)) {
120
- await adapter.postMessage(dest, { text: `${Icons.error} Project not found: \`${project}\`` });
121
+ await adapter.postMessage(dest, { text: `${Icons.error} ${t('cmd.task.projectNotFound', { project })}` });
121
122
  return;
122
123
  }
123
124
  const tasks = scanAllTasks(project);
124
125
  if (tasks.length === 0) {
125
- await adapter.postMessage(dest, { text: `No tasks found for \`${project}\`.` });
126
+ await adapter.postMessage(dest, { text: t('cmd.task.noTasks', { project }) });
126
127
  return;
127
128
  }
128
129
  const text = formatTaskList(tasks, 'all', project);
@@ -4,6 +4,7 @@
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { createLogger } from '../../../core/log.js';
6
6
  import { Icons } from '../../../core/icons.js';
7
+ import { t } from '../../../core/i18n.js';
7
8
  import { threadStore } from '../../../store/thread-repo.js';
8
9
  import { listTemplates, listAgents } from '../../../domain/threads/index.js';
9
10
  import { runningExecutions } from '../../../core/running-executions.js';
@@ -14,19 +15,19 @@ async function handleThreadStatus(channel, adapter) {
14
15
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
15
16
  const active = threadStore.findActive(channel);
16
17
  if (!active) {
17
- await adapter.postMessage(dest, { text: 'No active thread in this channel.' });
18
+ await adapter.postMessage(dest, { text: t('cmd.thread.noActive') });
18
19
  return;
19
20
  }
20
21
  const agents = Object.keys(active.agents).join(', ');
21
- const modeLabel = active.templateName ? active.templateName : 'ad-hoc';
22
+ const modeLabel = active.templateName ? active.templateName : t('cmd.thread.adHoc');
22
23
  const lines = [
23
- `*Active Thread* \`${active.id}\` (${modeLabel})`,
24
- `Status: ${active.status} | Active agent: ${active.activeAgent}`,
25
- `Steps: ${active.steps.length} | Cost: $${active.totalCostUsd.toFixed(4)}`,
26
- `Agents: ${agents}`,
24
+ t('cmd.thread.activeHeader', { id: active.id, mode: modeLabel }),
25
+ t('cmd.thread.statusLine', { status: active.status, agent: active.activeAgent }),
26
+ t('cmd.thread.stepsLine', { steps: active.steps.length, cost: active.totalCostUsd.toFixed(4) }),
27
+ t('cmd.thread.agentsLine', { agents }),
27
28
  ];
28
29
  if (active.status === 'aborted' && active.abortReason) {
29
- lines.push(`Abort reason: ${active.abortReason}`);
30
+ lines.push(t('cmd.thread.abortLine', { reason: active.abortReason }));
30
31
  }
31
32
  await adapter.postMessage(dest, { text: lines.join('\n') });
32
33
  }
@@ -34,13 +35,13 @@ async function handleThreadTemplates(channel, adapter) {
34
35
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
35
36
  const templates = listTemplates();
36
37
  if (templates.length === 0) {
37
- await adapter.postMessage(dest, { text: 'No thread templates configured.' });
38
+ await adapter.postMessage(dest, { text: t('cmd.thread.noTemplates') });
38
39
  return;
39
40
  }
40
- const lines = ['*Available Thread Templates*'];
41
- for (const t of templates) {
42
- const agentList = t.agents.map(a => typeof a === 'string' ? a : a.ref).join(', ');
43
- lines.push(`• \`${t.name}\` — ${t.description} [agents: ${agentList}]`);
41
+ const lines = [t('cmd.thread.templatesHeader')];
42
+ for (const tpl of templates) {
43
+ const agentList = tpl.agents.map(a => typeof a === 'string' ? a : a.ref).join(', ');
44
+ lines.push(`• ${t('cmd.thread.templateLine', { name: tpl.name, description: tpl.description, agents: agentList })}`);
44
45
  }
45
46
  await adapter.postMessage(dest, { text: lines.join('\n') });
46
47
  }
@@ -49,22 +50,22 @@ async function handleThreadAgents(channel, adapter) {
49
50
  const agentDefs = listAgents();
50
51
  const lines = [];
51
52
  if (agentDefs.length > 0) {
52
- lines.push('*Available Agents*');
53
+ lines.push(t('cmd.thread.agentsTitle'));
53
54
  for (const a of agentDefs) {
54
- lines.push(`• \`${a.name}\` (${a.profile}) — ${a.description || ''}`);
55
+ lines.push(`• ${t('cmd.thread.agentLine', { name: a.name, profile: a.profile, description: a.description || '' })}`);
55
56
  }
56
57
  }
57
58
  else {
58
- lines.push('No agents configured.');
59
+ lines.push(t('cmd.thread.noAgents'));
59
60
  }
60
61
  const active = threadStore.findActive(channel);
61
62
  if (active) {
62
63
  lines.push('');
63
- lines.push(`*Active Thread* \`${active.id}\``);
64
+ lines.push(t('cmd.thread.activeThreadHeader', { id: active.id }));
64
65
  for (const [slotId, slot] of Object.entries(active.agents)) {
65
66
  const isActiveAgent = slotId === active.activeAgent ? ` ${Icons.arrowLeft}` : '';
66
- const sessionStr = slot.sessionName || 'no session';
67
- lines.push(` • *${slotId}* (${slot.profile}) — ${slot.status} | ${sessionStr}${isActiveAgent}`);
67
+ const sessionStr = slot.sessionName || t('cmd.thread.noSession');
68
+ lines.push(` • ${t('cmd.thread.slotLine', { slotId, profile: slot.profile, status: slot.status, session: sessionStr })}${isActiveAgent}`);
68
69
  }
69
70
  }
70
71
  await adapter.postMessage(dest, { text: lines.join('\n') });
@@ -83,23 +84,23 @@ async function handleThreadCancelAlias(channel, adapter) {
83
84
  if (execs.length > 0) {
84
85
  log.info('Cancel requested for channel:', channel);
85
86
  conduitQueues.delete(channel);
86
- await adapter.postMessage(dest, { text: `${Icons.stopped} Cancelled. Session preserved — next message will resume.` });
87
+ await adapter.postMessage(dest, { text: `${Icons.stopped} ${t('cmd.thread.cancelledSessionPreserved')}` });
87
88
  }
88
89
  else {
89
- await adapter.postMessage(dest, { text: 'Nothing running to cancel.' });
90
+ await adapter.postMessage(dest, { text: t('cmd.thread.nothingRunning') });
90
91
  }
91
92
  }
92
93
  async function handleThreadList(channel, adapter) {
93
94
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
94
95
  const threads = threadStore.findByChannel(channel).slice(0, 10);
95
96
  if (threads.length === 0) {
96
- await adapter.postMessage(dest, { text: 'No threads found for this channel.' });
97
+ await adapter.postMessage(dest, { text: t('cmd.thread.noThreadsChannel') });
97
98
  return;
98
99
  }
99
- const lines = ['*Recent Threads*'];
100
- for (const t of threads) {
101
- const modeLabel = t.templateName || 'ad-hoc';
102
- lines.push(`• \`${t.id}\` ${modeLabel} — ${t.status} | ${t.steps.length} steps | $${t.totalCostUsd.toFixed(4)}`);
100
+ const lines = [t('cmd.thread.recentHeader')];
101
+ for (const thr of threads) {
102
+ const modeLabel = thr.templateName || t('cmd.thread.adHoc');
103
+ lines.push(`• ${t('cmd.thread.recentLine', { id: thr.id, mode: modeLabel, status: thr.status, steps: thr.steps.length, cost: thr.totalCostUsd.toFixed(4) })}`);
103
104
  }
104
105
  await adapter.postMessage(dest, { text: lines.join('\n') });
105
106
  }
@@ -107,16 +108,16 @@ async function handleThreadListRunning(channel, adapter) {
107
108
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
108
109
  const executions = runningExecutions.getAll().filter(e => e.threadId);
109
110
  if (executions.length === 0) {
110
- await adapter.postMessage(dest, { text: 'No running threads.' });
111
+ await adapter.postMessage(dest, { text: t('cmd.thread.noRunning') });
111
112
  return;
112
113
  }
113
- const lines = ['*Running Threads*'];
114
+ const lines = [t('cmd.thread.runningHeader')];
114
115
  for (const exec of executions) {
115
116
  const thread = exec.threadId ? threadStore.get(exec.threadId) : null;
116
- const modeLabel = thread?.templateName || 'ad-hoc';
117
+ const modeLabel = thread?.templateName || t('cmd.thread.adHoc');
117
118
  const stepCount = thread?.steps.length ?? 0;
118
119
  const cost = thread?.totalCostUsd ?? 0;
119
- lines.push(`• \`${exec.threadId}\` — ${exec.channel || '?'} | ${modeLabel} | ${stepCount} step(s) | $${cost.toFixed(4)}`);
120
+ lines.push(`• ${t('cmd.thread.runningLine', { id: exec.threadId ?? '', channel: exec.channel || '?', mode: modeLabel, steps: stepCount, cost: cost.toFixed(4) })}`);
120
121
  }
121
122
  await adapter.postMessage(dest, { text: lines.join('\n') });
122
123
  }
@@ -124,16 +125,16 @@ async function sendThreadUsage(channel, adapter) {
124
125
  const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
125
126
  await adapter.postMessage(dest, {
126
127
  text: [
127
- '*Thread Commands*',
128
- '`!thread` — show active thread status',
129
- '`!thread agents` — list available agents',
130
- '`!thread templates` — list available templates',
131
- '`!thread <agent> <message>` — start ad-hoc thread with one agent',
132
- '`!thread <template> <message>` — start template-based thread',
133
- '`!thread add <agent> [message]` — add agent to current thread',
134
- '`!cancel` — cancel active thread (also `!thread cancel`)',
135
- '`!thread list` — list recent threads',
136
- '`!thread list --running` — list running threads across channels',
128
+ t('cmd.thread.usageHeader'),
129
+ t('cmd.thread.usageStatus'),
130
+ t('cmd.thread.usageAgents'),
131
+ t('cmd.thread.usageTemplates'),
132
+ t('cmd.thread.usageAdHoc'),
133
+ t('cmd.thread.usageTemplate'),
134
+ t('cmd.thread.usageAdd'),
135
+ t('cmd.thread.usageCancel'),
136
+ t('cmd.thread.usageList'),
137
+ t('cmd.thread.usageListRunning'),
137
138
  ].join('\n'),
138
139
  });
139
140
  }
@@ -177,7 +177,7 @@ function createWebhookHandler({ secret = getSecret(), } = {}) {
177
177
  const parentThread = data.parentThreadId ? threadStore.get(String(data.parentThreadId)) : null;
178
178
  const guard = checkSpawnGuards(parentThread);
179
179
  if (guard.ok === false) {
180
- return reply({ success: false, error: `${guard.reason}. Do NOT retry this spawn — fold the remaining work into your own step, or escalate via [ABORT: <diagnosis>].` });
180
+ return reply({ success: false, error: `${guard.reason}. Do NOT retry this spawn — fold the remaining work into your own step, or escalate by calling the thread_abort tool with a diagnosis.` });
181
181
  }
182
182
  const projectId = data.projectId || 'general';
183
183
  // The originating conduit (the starter agent's SLACK_CHANNEL, forwarded by thread-ops.ts).
@@ -351,6 +351,43 @@ function createWebhookHandler({ secret = getSecret(), } = {}) {
351
351
  }));
352
352
  return reply({ success: true, data: { scope, count: out.length, threads: out } });
353
353
  }
354
+ if (action === 'control') {
355
+ // DR-0015 problem 1: out-of-band control plane. The agent's own thread_abort /
356
+ // thread_split / thread_wait tool POSTs { threadId, control:{ action, ... } } here.
357
+ // Validate the thread exists and is not terminal; reject a second concurrent control;
358
+ // then persist metadata.pendingControl for the runner to read at the step boundary.
359
+ const threadId = data.threadId;
360
+ const control = data.control;
361
+ if (!threadId || !control || typeof control.action !== 'string') {
362
+ return reply({ success: false, error: 'control requires threadId and control.action' });
363
+ }
364
+ if (!['abort', 'split', 'wait'].includes(control.action)) {
365
+ return reply({ success: false, error: `unknown control action: ${control.action}` });
366
+ }
367
+ const t = threadStore.get(threadId);
368
+ if (!t)
369
+ return reply({ success: false, error: 'thread not found' });
370
+ if (['completed', 'failed', 'cancelled', 'aborted'].includes(t.status)) {
371
+ return reply({ success: false, error: `thread is ${t.status} (terminal) — cannot accept control` });
372
+ }
373
+ if (t.metadata?.pendingControl) {
374
+ return reply({ success: false, error: `thread already has a pending ${t.metadata.pendingControl.action} control — only one control intent at a time` });
375
+ }
376
+ const requestedAtStep = t.currentStepIndex;
377
+ await threadStore.mutate(threadId, (r) => {
378
+ (r.metadata ??= {}).pendingControl = {
379
+ action: control.action,
380
+ kind: control.kind ?? null,
381
+ diagnosis: control.diagnosis ?? null,
382
+ subtasks: Array.isArray(control.subtasks) ? control.subtasks : null,
383
+ onTasks: Array.isArray(control.on_tasks) ? control.on_tasks : null,
384
+ onThreads: Array.isArray(control.on_threads) ? control.on_threads : null,
385
+ requestedAtStep,
386
+ };
387
+ });
388
+ log.info(`thread-op control ${threadId}: ${control.action}${control.kind ? ` (${control.kind})` : ''}`);
389
+ return reply({ success: true, data: { threadId, action: control.action, requestedAtStep, accepted: true } });
390
+ }
354
391
  if (action === 'cancel') {
355
392
  const cancelled = await cancelThread(data.threadId);
356
393
  return reply({ success: true, data: { cancelled } });
@@ -4,6 +4,7 @@
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { createLogger } from '../core/log.js';
6
6
  import { Icons } from '../core/icons.js';
7
+ import { t } from '../core/i18n.js';
7
8
  import * as executionRegistry from '../domain/executions/registry.js';
8
9
  import { runAgent } from '../domain/agents/index.js';
9
10
  import { shouldAutoRunCompound, combineFinalOutputs } from '../domain/threads/auto-thread.js';
@@ -19,8 +20,8 @@ export function resolveExecutionProject({ execution, fallbackMessage }) {
19
20
  export function buildExecutionStatusReport() {
20
21
  const running = executionRegistry.getRunningExecutions();
21
22
  if (running.length === 0)
22
- return 'No running executions.';
23
- const lines = [`Running executions: ${running.length}`];
23
+ return t('status.noRunningExecutions');
24
+ const lines = [t('status.runningExecutions', { count: running.length })];
24
25
  for (const record of running) {
25
26
  const location = record.kind === 'dispatch'
26
27
  ? `${record.dispatch?.machine || '?'}:${record.dispatch?.taskId || record.id}`
@@ -113,7 +114,7 @@ function buildActionElements({ channel, sessionName, isDm, includeCancel, thread
113
114
  if (includeCancel) {
114
115
  elements.push({
115
116
  type: 'button',
116
- text: 'Cancel',
117
+ text: t('btn.cancel'),
117
118
  actionId: 'status_cancel',
118
119
  value: JSON.stringify({ channel, threadId: threadId ?? null, executionId: executionId ?? null }),
119
120
  style: 'danger',
@@ -122,7 +123,7 @@ function buildActionElements({ channel, sessionName, isDm, includeCancel, thread
122
123
  if (sessionName) {
123
124
  elements.push({
124
125
  type: 'button',
125
- text: 'Resume',
126
+ text: t('btn.resume'),
126
127
  actionId: 'status_resume',
127
128
  value: sessionName,
128
129
  });
@@ -130,7 +131,7 @@ function buildActionElements({ channel, sessionName, isDm, includeCancel, thread
130
131
  if (isDm) {
131
132
  elements.push({
132
133
  type: 'button',
133
- text: 'New',
134
+ text: t('btn.new'),
134
135
  actionId: 'status_new',
135
136
  value: channel,
136
137
  });
@@ -32,6 +32,15 @@ export declare function buildTaskResultNotice(task: Task, kind: 'completed' | 'b
32
32
  export declare function notifyTaskParentThreads(taskId: string, kind: 'completed' | 'blocked', deps?: {
33
33
  resume?: ResumeFn;
34
34
  }): Promise<void>;
35
+ type WakeFn = (channel: string, notice: string) => void | Promise<void>;
36
+ /** Session→task wake (Problem 1): when a task created by an interactive session/agent turns
37
+ * terminal, route a notice back to its origin channel. Default-on, no fallback — if origin_channel
38
+ * is set we always wake it. Mutually exclusive with the thread-parent path: if any thread is
39
+ * currently waiting on this task (waitingOnTasks), that path owns the result and we defer.
40
+ * `wake` is injectable for testing (mirrors the `resume` injection on notifyTaskParentThreads). */
41
+ export declare function notifyTaskOriginSession(taskId: string, kind: 'completed' | 'blocked', deps?: {
42
+ wake?: WakeFn;
43
+ }): Promise<void>;
35
44
  /** Sweep one waiting thread's waitingOnTasks against disk state: deliver already-done and
36
45
  * already-blocked children, drop missing ones, keep open ones. Closes the race window
37
46
  * where a child task turns terminal between the suspension snapshot and the waiting
@@ -56,7 +65,7 @@ export declare function recoverWaitingThreads(deps?: {
56
65
  }): Promise<number>;
57
66
  /**
58
67
  * Fire the completion callback for an MCP-spawned thread once it is terminal.
59
- * - Non-terminal statuses (e.g. a parent that suspended via [WAIT_CHILDREN] and returned
68
+ * - Non-terminal statuses (e.g. a parent that suspended via thread_wait and returned
60
69
  * from runThread in 'waiting') are ignored — suspension is not completion.
61
70
  * - Interactive parent (no parentThreadId): wake the parent by routing a synthetic turn onto
62
71
  * its channel via agentRunner.route.
@@ -65,3 +74,4 @@ export declare function recoverWaitingThreads(deps?: {
65
74
  * Threads not spawned via thread_start (no parentSessionId) are ignored.
66
75
  */
67
76
  export declare function fireThreadCallback(threadId: string): Promise<void>;
77
+ export {};
@@ -67,7 +67,7 @@ export function buildChildResultNotice(child) {
67
67
  lines.push('2. 达标 → 蒸馏关键结论进你的 artifact,继续你的计划。');
68
68
  lines.push('3. 未达标 → 写出 expected/actual 差异与失败假设,用修订后的契约重新 thread_start' +
69
69
  `(你已使用 ${childCount}/${maxChildren} 个子线程额度;额度耗尽时 thread_start 会被拒绝)。`);
70
- lines.push('4. 无法判断或方向性问题 → 在 artifact 写 [ABORT: <诊断>] 升级到你的上层。');
70
+ lines.push('4. 无法判断或方向性问题 → 调用 thread_abort 工具(附一行诊断)升级到你的上层。');
71
71
  return lines.join('\n');
72
72
  }
73
73
  /** Durable degraded-path notice to the project-report channel. */
@@ -229,8 +229,8 @@ export function buildTaskResultNotice(task, kind) {
229
229
  lines.push('验收要求(必须执行,不得凭完成备注直接采信):');
230
230
  lines.push('1. 读取实际产出(代码/文档/实验记录),逐条核对 done_when;涉及代码的跑测试验证。');
231
231
  lines.push('2. 达标 → 蒸馏关键结论进你的 artifact,继续你的计划。');
232
- lines.push(`3. 未达标 → cortex-task uncomplete 后修订该任务,或用 decompose --keep-parent 增加修订子任务,再 [WAIT_CHILDREN]。`);
233
- lines.push('4. 方向性问题 → 在 artifact 写 [ABORT: <诊断>] 升级。');
232
+ lines.push(`3. 未达标 → cortex-task uncomplete 后修订该任务,或用 decompose --keep-parent 增加修订子任务,再调用 thread_wait。`);
233
+ lines.push('4. 方向性问题 → 调用 thread_abort 工具(附一行诊断)升级。');
234
234
  }
235
235
  else {
236
236
  lines.push(`[子任务被阻塞 — 升级信号] #${task.id} ${task.text}`);
@@ -238,8 +238,8 @@ export function buildTaskResultNotice(task, kind) {
238
238
  lines.push('');
239
239
  lines.push('这是子任务的升级:它无法自行完成。你必须处理:');
240
240
  lines.push('1. 诊断原因(读它的产出/日志;too-big 类原因 = 你当初的分解需要修订)。');
241
- lines.push('2. 可修复 → cortex-task unblock 并修订任务描述/done_when,或重建修订后的子任务(decompose --keep-parent),再 [WAIT_CHILDREN]。');
242
- lines.push('3. 超出你的职权或方向性问题 → 在 artifact 写 [ABORT: <诊断>] 向上升级。');
241
+ lines.push('2. 可修复 → cortex-task unblock 并修订任务描述/done_when,或重建修订后的子任务(decompose --keep-parent),再调用 thread_wait。');
242
+ lines.push('3. 超出你的职权或方向性问题 → 调用 thread_abort 工具(附一行诊断)向上升级。');
243
243
  }
244
244
  return lines.join('\n');
245
245
  }
@@ -308,6 +308,63 @@ export async function notifyTaskParentThreads(taskId, kind, deps = {}) {
308
308
  await deliverTaskResult(parent.id, task, kind, deps);
309
309
  }
310
310
  }
311
+ /** Wake (or create) the session on a channel by routing a synthetic user message — the same
312
+ * mechanism the interactive thread-parent path uses. Shared by thread completion (fireThreadCallback)
313
+ * and task completion (notifyTaskOriginSession). agentRunner.route find-or-creates the channel's
314
+ * session, so this works whether or not a live session still exists. */
315
+ async function wakeSession(channel, notice, tag) {
316
+ const adapter = jobCtx.adapter;
317
+ if (!adapter) {
318
+ log.error(`no adapter; cannot wake session on ${channel} (${tag})`);
319
+ return;
320
+ }
321
+ const message = {
322
+ ref: { conduit: channel, messageId: `cb_${tag}_${Date.now()}` },
323
+ text: notice,
324
+ senderId: 'cortex-thread-callback',
325
+ isBot: false,
326
+ kind: 'user',
327
+ raw: { source: 'task-callback', tag },
328
+ };
329
+ log.info(`waking session on ${channel} for ${tag}`);
330
+ await agentRunner.route({
331
+ message, channel, adapter, threadAnchorId: null, hasFiles: false, userMessage: notice, agentMessage: notice,
332
+ });
333
+ }
334
+ /** Origin-session notice: a task created by an interactive session/agent finished — concise,
335
+ * no manager-style verification ceremony (the recipient is the requester, not a join node). */
336
+ function buildTaskOriginNotice(task, kind) {
337
+ 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} 查看详情。`;
340
+ }
341
+ return `[任务受阻] 你布置的任务 #${task.id} (${task.project})「${task.text}」被阻塞。\n阻塞原因: ${task.blocked_by || '(未记录)'}\n用 cortex-task show --task-id ${task.id} 查看详情,处理后可 cortex-task unblock。`;
342
+ }
343
+ /** Session→task wake (Problem 1): when a task created by an interactive session/agent turns
344
+ * terminal, route a notice back to its origin channel. Default-on, no fallback — if origin_channel
345
+ * is set we always wake it. Mutually exclusive with the thread-parent path: if any thread is
346
+ * currently waiting on this task (waitingOnTasks), that path owns the result and we defer.
347
+ * `wake` is injectable for testing (mirrors the `resume` injection on notifyTaskParentThreads). */
348
+ export async function notifyTaskOriginSession(taskId, kind, deps = {}) {
349
+ for (const t of threadStore.getAll()) {
350
+ if (t.status === 'waiting' && t.metadata?.waitingOnTasks?.includes(taskId))
351
+ return;
352
+ }
353
+ const key = `task_${taskId}_${kind}`;
354
+ if (fired.has(key))
355
+ return;
356
+ // The event carries only the id; origin fields live on the task — scan disk to find it.
357
+ const task = scanAllTasks().find((t) => t.id === taskId);
358
+ if (!task || !task.origin_channel)
359
+ return;
360
+ if (kind === 'completed' && task.status !== 'done')
361
+ return; // dispatch publishes loosely
362
+ if (kind === 'blocked' && !task.blocked_by)
363
+ return;
364
+ fired.add(key);
365
+ const wake = deps.wake ?? ((ch, n) => wakeSession(ch, n, `task_${taskId}`));
366
+ await wake(task.origin_channel, buildTaskOriginNotice(task, kind));
367
+ }
311
368
  /** Sweep one waiting thread's waitingOnTasks against disk state: deliver already-done and
312
369
  * already-blocked children, drop missing ones, keep open ones. Closes the race window
313
370
  * where a child task turns terminal between the suspension snapshot and the waiting
@@ -350,9 +407,11 @@ export async function reconcileWaitingTasks(threadId, deps = {}) {
350
407
  export function registerTaskTreeSubscribers(bus) {
351
408
  bus.subscribe('task.completed', (e) => {
352
409
  void notifyTaskParentThreads(e.taskId, 'completed').catch((err) => log.error(`task.completed bridge: ${err.message}`));
410
+ void notifyTaskOriginSession(e.taskId, 'completed').catch((err) => log.error(`task.completed origin-wake: ${err.message}`));
353
411
  });
354
412
  bus.subscribe('task.blocked', (e) => {
355
413
  void notifyTaskParentThreads(e.taskId, 'blocked').catch((err) => log.error(`task.blocked bridge: ${err.message}`));
414
+ void notifyTaskOriginSession(e.taskId, 'blocked').catch((err) => log.error(`task.blocked origin-wake: ${err.message}`));
356
415
  });
357
416
  }
358
417
  /** Startup recovery: re-deliver results that completed while the server was down.
@@ -398,7 +457,7 @@ export async function recoverWaitingThreads(deps = {}) {
398
457
  }
399
458
  /**
400
459
  * Fire the completion callback for an MCP-spawned thread once it is terminal.
401
- * - Non-terminal statuses (e.g. a parent that suspended via [WAIT_CHILDREN] and returned
460
+ * - Non-terminal statuses (e.g. a parent that suspended via thread_wait and returned
402
461
  * from runThread in 'waiting') are ignored — suspension is not completion.
403
462
  * - Interactive parent (no parentThreadId): wake the parent by routing a synthetic turn onto
404
463
  * its channel via agentRunner.route.
@@ -433,31 +492,8 @@ export async function fireThreadCallback(threadId) {
433
492
  return;
434
493
  fired.add(threadId);
435
494
  const notice = buildNotice(threadId);
436
- const adapter = jobCtx.adapter;
437
495
  if (m.parentChannel) {
438
- if (!adapter) {
439
- log.error(`no adapter; cannot wake parent for ${threadId}`);
440
- return;
441
- }
442
- const channel = m.parentChannel;
443
- const message = {
444
- ref: { conduit: channel, messageId: `cb_${threadId}_${Date.now()}` },
445
- text: notice,
446
- senderId: 'cortex-thread-callback',
447
- isBot: false,
448
- kind: 'user',
449
- raw: { source: 'thread-callback', threadId },
450
- };
451
- log.info(`waking parent session on ${channel} for thread ${threadId}`);
452
- await agentRunner.route({
453
- message,
454
- channel,
455
- adapter,
456
- threadAnchorId: null,
457
- hasFiles: false,
458
- userMessage: notice,
459
- agentMessage: notice,
460
- });
496
+ await wakeSession(m.parentChannel, notice, `thr_${threadId}`);
461
497
  return;
462
498
  }
463
499
  // No channel → durable notice to the project-report channel.
@@ -76,6 +76,17 @@ export declare class FeishuAdapter implements PlatformAdapter {
76
76
  * im.v1.messageResource.get (which requires both message_id and a type param).
77
77
  */
78
78
  private extractInboundFiles;
79
+ /**
80
+ * Parse a Feishu `post` (富文本/rich-text) message content payload. Feishu wraps
81
+ * a single message that mixes text and images as a post, whose `content` is a 2D
82
+ * array of paragraphs, each a run of element nodes:
83
+ * { title?, content: [ [ {tag:'text',text}, {tag:'a',text,href}, {tag:'at',user_name},
84
+ * {tag:'img',image_key} ], ... ] }
85
+ * Returns the concatenated text (paragraphs joined by '\n', non-empty title
86
+ * prefixed) and the list of inline image_keys, so callers recover BOTH the text
87
+ * and the images from one mixed message.
88
+ */
89
+ private parsePostContent;
79
90
  private handleCardAction;
80
91
  private buildMessagePayload;
81
92
  private buildCardJson;