@cortex-agent/server 2026.6.11 → 2026.6.18-2

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 +27 -0
  101. package/dist/platform/adapters/feishu.js +136 -4
  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
@@ -0,0 +1,74 @@
1
+ // input: nothing (leaf data slice)
2
+ // output: schedulingEn / schedulingZh — message slice (filled by i18n extraction)
3
+ // pos: one locale slice; aggregated by core/locales/en.ts & zh.ts barrels
4
+ // >>> Keep en and zh keys in lockstep (zh typed against keyof typeof schedulingEn) <<<
5
+ export const schedulingEn = {
6
+ 'schedule.help.title': '*Schedule commands:*',
7
+ 'schedule.help.addInterval': '`!schedule add interval <duration> [--profile <name>] <message>` — repeat every duration (e.g. `30m`, `2h`, `1d`)',
8
+ 'schedule.help.addDaily': '`!schedule add daily <HH:MM> [--profile <name>] <message>` — run every day at a fixed time (24-hour)',
9
+ 'schedule.help.addWeekly': '`!schedule add weekly <day> <HH:MM> [--profile <name>] <message>` — run every week (day: mon,tue,wed,thu,fri,sat,sun)',
10
+ 'schedule.help.addOnce': '`!schedule add once <duration> [--profile <name>] <message>` — run once after a delay',
11
+ 'schedule.help.list': '`!schedule list` — show all scheduled tasks',
12
+ 'schedule.help.pause': '`!schedule pause <id>` — pause a recurring task',
13
+ 'schedule.help.resume': '`!schedule resume <id>` — resume a paused recurring task',
14
+ 'schedule.help.remove': '`!schedule remove <id>` — remove a task by id',
15
+ 'schedule.help.availableProfiles': 'Available profiles: ${profileNames}',
16
+ 'schedule.list.empty': 'No scheduled tasks.',
17
+ 'schedule.list.header': '*Scheduled tasks (${count}):*\n${lines}',
18
+ 'schedule.remove.usage': 'Usage: `!schedule remove <id>`',
19
+ 'schedule.remove.ok': 'Removed task `${id}`.',
20
+ 'schedule.taskNotFound': 'Task not found: `${id}`',
21
+ 'schedule.pause.usage': 'Usage: `!schedule pause <id>`',
22
+ 'schedule.pause.ok': 'Paused task `${id}`.',
23
+ 'schedule.resume.usage': 'Usage: `!schedule resume <id>`',
24
+ 'schedule.resume.ok': 'Resumed task `${id}`.${nextAt}',
25
+ 'schedule.resume.nextRun': ' Next run: ${time}.',
26
+ 'schedule.invalidDuration': 'Invalid duration: `${duration}`. Use e.g. `30s`, `5m`, `2h`, `1d`',
27
+ 'schedule.invalidTime': 'Invalid time: `${time}`. Use 24-hour HH:MM, e.g. `${example}`',
28
+ 'schedule.invalidDay': 'Invalid day: `${day}`. Use: mon, tue, wed, thu, fri, sat, sun',
29
+ 'schedule.add.intervalUsage': 'Usage: `!schedule add interval <duration> [--profile <name>] <message>`',
30
+ 'schedule.add.dailyUsage': 'Usage: `!schedule add daily <HH:MM> [--profile <name>] <message>`',
31
+ 'schedule.add.weeklyUsage': 'Usage: `!schedule add weekly <day> <HH:MM> [--profile <name>] <message>`',
32
+ 'schedule.add.onceUsage': 'Usage: `!schedule add once <duration> [--profile <name>] <message>`',
33
+ 'schedule.add.scheduledInterval': 'Scheduled every *${duration}*: "${message}"',
34
+ 'schedule.add.scheduledDaily': 'Scheduled daily at *${time}*: "${message}"',
35
+ 'schedule.add.scheduledWeekly': 'Scheduled weekly *${day} ${time}*: "${message}"',
36
+ 'schedule.add.scheduledOnce': 'Scheduled once in *${duration}*: "${message}"',
37
+ 'schedule.add.unknownType': 'Unknown type: `${type}`. Use `interval`, `daily`, `weekly`, or `once`',
38
+ 'schedule.profileUsage': 'Usage: ${usage}',
39
+ };
40
+ export const schedulingZh = {
41
+ 'schedule.help.title': '*定时任务命令:*',
42
+ 'schedule.help.addInterval': '`!schedule add interval <duration> [--profile <name>] <message>` — 每隔指定时长重复(例如 `30m`、`2h`、`1d`)',
43
+ 'schedule.help.addDaily': '`!schedule add daily <HH:MM> [--profile <name>] <message>` — 每天在固定时间运行(24 小时制)',
44
+ 'schedule.help.addWeekly': '`!schedule add weekly <day> <HH:MM> [--profile <name>] <message>` — 每周运行(day:mon,tue,wed,thu,fri,sat,sun)',
45
+ 'schedule.help.addOnce': '`!schedule add once <duration> [--profile <name>] <message>` — 延迟一段时间后运行一次',
46
+ 'schedule.help.list': '`!schedule list` — 显示所有定时任务',
47
+ 'schedule.help.pause': '`!schedule pause <id>` — 暂停一个周期任务',
48
+ 'schedule.help.resume': '`!schedule resume <id>` — 恢复一个已暂停的周期任务',
49
+ 'schedule.help.remove': '`!schedule remove <id>` — 按 id 删除任务',
50
+ 'schedule.help.availableProfiles': '可用的 profile:${profileNames}',
51
+ 'schedule.list.empty': '没有定时任务。',
52
+ 'schedule.list.header': '*定时任务(${count}):*\n${lines}',
53
+ 'schedule.remove.usage': '用法:`!schedule remove <id>`',
54
+ 'schedule.remove.ok': '已删除任务 `${id}`。',
55
+ 'schedule.taskNotFound': '未找到任务:`${id}`',
56
+ 'schedule.pause.usage': '用法:`!schedule pause <id>`',
57
+ 'schedule.pause.ok': '已暂停任务 `${id}`。',
58
+ 'schedule.resume.usage': '用法:`!schedule resume <id>`',
59
+ 'schedule.resume.ok': '已恢复任务 `${id}`。${nextAt}',
60
+ 'schedule.resume.nextRun': ' 下次运行:${time}。',
61
+ 'schedule.invalidDuration': '无效的时长:`${duration}`。请使用例如 `30s`、`5m`、`2h`、`1d`',
62
+ 'schedule.invalidTime': '无效的时间:`${time}`。请使用 24 小时制 HH:MM,例如 `${example}`',
63
+ 'schedule.invalidDay': '无效的星期:`${day}`。请使用:mon, tue, wed, thu, fri, sat, sun',
64
+ 'schedule.add.intervalUsage': '用法:`!schedule add interval <duration> [--profile <name>] <message>`',
65
+ 'schedule.add.dailyUsage': '用法:`!schedule add daily <HH:MM> [--profile <name>] <message>`',
66
+ 'schedule.add.weeklyUsage': '用法:`!schedule add weekly <day> <HH:MM> [--profile <name>] <message>`',
67
+ 'schedule.add.onceUsage': '用法:`!schedule add once <duration> [--profile <name>] <message>`',
68
+ 'schedule.add.scheduledInterval': '已设定每 *${duration}* 运行一次:"${message}"',
69
+ 'schedule.add.scheduledDaily': '已设定每天 *${time}* 运行:"${message}"',
70
+ 'schedule.add.scheduledWeekly': '已设定每周 *${day} ${time}* 运行:"${message}"',
71
+ 'schedule.add.scheduledOnce': '已设定 *${duration}* 后运行一次:"${message}"',
72
+ 'schedule.add.unknownType': '未知的类型:`${type}`。请使用 `interval`、`daily`、`weekly` 或 `once`',
73
+ 'schedule.profileUsage': '用法:${usage}',
74
+ };
@@ -0,0 +1,6 @@
1
+ export declare const startupEn: {
2
+ readonly 'startup.started': "Cortex agent v${version} started on ${machine}.";
3
+ readonly 'startup.restarted': "Cortex agent v${version} restarted on ${machine}.";
4
+ readonly 'startup.reason': " Reason: ${reason}.";
5
+ };
6
+ export declare const startupZh: Record<keyof typeof startupEn, string>;
@@ -0,0 +1,14 @@
1
+ // input: nothing (leaf data slice)
2
+ // output: startupEn / startupZh — message slice (filled by i18n extraction)
3
+ // pos: one locale slice; aggregated by core/locales/en.ts & zh.ts barrels
4
+ // >>> Keep en and zh keys in lockstep (zh typed against keyof typeof startupEn) <<<
5
+ export const startupEn = {
6
+ 'startup.started': 'Cortex agent v${version} started on ${machine}.',
7
+ 'startup.restarted': 'Cortex agent v${version} restarted on ${machine}.',
8
+ 'startup.reason': ' Reason: ${reason}.',
9
+ };
10
+ export const startupZh = {
11
+ 'startup.started': 'Cortex 代理 v${version} 已在 ${machine} 上启动。',
12
+ 'startup.restarted': 'Cortex 代理 v${version} 已在 ${machine} 上重启。',
13
+ 'startup.reason': ' 原因:${reason}。',
14
+ };
@@ -0,0 +1,20 @@
1
+ export declare const statusEn: {
2
+ readonly 'status.processing': "Processing";
3
+ readonly 'status.done': "Done";
4
+ readonly 'status.waitingForUserInput': "Waiting for user input";
5
+ readonly 'status.cancelled': "Cancelled";
6
+ readonly 'status.error': "Error";
7
+ readonly 'status.supersededByEdit': "Superseded by edit";
8
+ readonly 'status.retryEdited': "edited";
9
+ readonly 'status.retry': "Retry";
10
+ readonly 'status.rateLimitedExhausted': "Rate limited — all fallbacks exhausted";
11
+ readonly 'status.supersededSeeNewReply': "see new reply";
12
+ readonly 'status.processingAskResponse': "Processing AskUserQuestion response...";
13
+ readonly 'status.errorBody': "Error: ${message}";
14
+ readonly 'status.noRunningExecutions': "No running executions.";
15
+ readonly 'status.runningExecutions': "Running executions: ${count}";
16
+ readonly 'btn.cancel': "Cancel";
17
+ readonly 'btn.resume': "Resume";
18
+ readonly 'btn.new': "New";
19
+ };
20
+ export declare const statusZh: Record<keyof typeof statusEn, string>;
@@ -0,0 +1,48 @@
1
+ // input: nothing (leaf data slice)
2
+ // output: statusEn / statusZh — message slice (filled by i18n extraction)
3
+ // pos: one locale slice; aggregated by core/locales/en.ts & zh.ts barrels
4
+ // >>> Keep en and zh keys in lockstep (zh typed against keyof typeof statusEn) <<<
5
+ export const statusEn = {
6
+ // --- Status / lifecycle phrases ---
7
+ 'status.processing': 'Processing',
8
+ 'status.done': 'Done',
9
+ 'status.waitingForUserInput': 'Waiting for user input',
10
+ 'status.cancelled': 'Cancelled',
11
+ 'status.error': 'Error',
12
+ 'status.supersededByEdit': 'Superseded by edit',
13
+ 'status.retryEdited': 'edited',
14
+ 'status.retry': 'Retry',
15
+ 'status.rateLimitedExhausted': 'Rate limited — all fallbacks exhausted',
16
+ 'status.supersededSeeNewReply': 'see new reply',
17
+ 'status.processingAskResponse': 'Processing AskUserQuestion response...',
18
+ 'status.errorBody': 'Error: ${message}',
19
+ // --- Execution report ---
20
+ 'status.noRunningExecutions': 'No running executions.',
21
+ 'status.runningExecutions': 'Running executions: ${count}',
22
+ // --- Button labels ---
23
+ 'btn.cancel': 'Cancel',
24
+ 'btn.resume': 'Resume',
25
+ 'btn.new': 'New',
26
+ };
27
+ export const statusZh = {
28
+ // --- Status / lifecycle phrases ---
29
+ 'status.processing': '处理中',
30
+ 'status.done': '完成',
31
+ 'status.waitingForUserInput': '等待用户输入',
32
+ 'status.cancelled': '已取消',
33
+ 'status.error': '错误',
34
+ 'status.supersededByEdit': '已被编辑取代',
35
+ 'status.retryEdited': '已编辑',
36
+ 'status.retry': '重试',
37
+ 'status.rateLimitedExhausted': '触发限流 — 所有回退已用尽',
38
+ 'status.supersededSeeNewReply': '查看新回复',
39
+ 'status.processingAskResponse': '正在处理 AskUserQuestion 回复……',
40
+ 'status.errorBody': '错误:${message}',
41
+ // --- Execution report ---
42
+ 'status.noRunningExecutions': '没有正在运行的执行。',
43
+ 'status.runningExecutions': '正在运行的执行:${count}',
44
+ // --- Button labels ---
45
+ 'btn.cancel': '取消',
46
+ 'btn.resume': '恢复',
47
+ 'btn.new': '新建',
48
+ };
@@ -0,0 +1,5 @@
1
+ import type { MessageKey } from './en.js';
2
+ /** Simplified-Chinese translations, aggregated from per-cluster slices. Must provide every
3
+ * MessageKey (compiler-enforced via Record<MessageKey,string>) and add none. ${param}
4
+ * placeholders and `code`/*bold* markdown are preserved verbatim from the en slices. */
5
+ export declare const zh: Record<MessageKey, string>;
@@ -0,0 +1,23 @@
1
+ // input: per-cluster Simplified-Chinese slices (./slices/*) + MessageKey from en.ts
2
+ // output: `zh` — aggregated zh table, typed Record<MessageKey, string>
3
+ // pos: L0 locale barrel; the Record<MessageKey,...> type forces parity with en.ts at compile time
4
+ // >>> Keep slice keys in lockstep with their en counterparts <<<
5
+ import { langZh } from './slices/lang.js';
6
+ import { statusZh } from './slices/status.js';
7
+ import { commandsZh } from './slices/commands.js';
8
+ import { schedulingZh } from './slices/scheduling.js';
9
+ import { interactionsZh } from './slices/interactions.js';
10
+ import { startupZh } from './slices/startup.js';
11
+ import { initZh } from './slices/init.js';
12
+ /** Simplified-Chinese translations, aggregated from per-cluster slices. Must provide every
13
+ * MessageKey (compiler-enforced via Record<MessageKey,string>) and add none. ${param}
14
+ * placeholders and `code`/*bold* markdown are preserved verbatim from the en slices. */
15
+ export const zh = {
16
+ ...langZh,
17
+ ...statusZh,
18
+ ...commandsZh,
19
+ ...schedulingZh,
20
+ ...interactionsZh,
21
+ ...startupZh,
22
+ ...initZh,
23
+ };
@@ -0,0 +1,23 @@
1
+ /** Probe whether a PID is alive. Signal 0 performs the permission/existence check
2
+ * without actually delivering a signal; a throw (ESRCH/EPERM-as-dead handled by caller)
3
+ * means the process is not addressable as a live, signalable target. */
4
+ export declare function isProcessAlive(pid: number): boolean;
5
+ export interface AcquireResult {
6
+ acquired: boolean;
7
+ /** Set when acquired === true: whether a stale/corrupt lock was reclaimed. */
8
+ stale?: boolean;
9
+ /** Set when acquired === false: the PID currently holding the lock. */
10
+ holderPid?: number;
11
+ }
12
+ /**
13
+ * Attempt to take a PID-file singleton lock.
14
+ * - File missing → write own pid, { acquired: true, stale: false }
15
+ * - File holds a live, valid pid → { acquired: false, holderPid }
16
+ * - File holds a dead/corrupt pid → overwrite with own pid, { acquired: true, stale: true }
17
+ *
18
+ * This function never exits the process or logs — the caller decides how to react to a
19
+ * conflict (typically: log a message and process.exit(1)).
20
+ */
21
+ export declare function tryAcquireSingletonLock(pidFile: string): AcquireResult;
22
+ /** Release the lock iff it is still owned by the current process. Best-effort; swallows errors. */
23
+ export declare function releaseSingletonLock(pidFile: string): void;
@@ -0,0 +1,53 @@
1
+ // input: a pidfile path
2
+ // output: tryAcquireSingletonLock / releaseSingletonLock / isProcessAlive
3
+ // pos: L0 zero-dependency singleton-lock primitive, shared by daemon.ts and app.ts
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { existsSync, readFileSync, writeFileSync, unlinkSync } from 'fs';
6
+ /** Probe whether a PID is alive. Signal 0 performs the permission/existence check
7
+ * without actually delivering a signal; a throw (ESRCH/EPERM-as-dead handled by caller)
8
+ * means the process is not addressable as a live, signalable target. */
9
+ export function isProcessAlive(pid) {
10
+ try {
11
+ process.kill(pid, 0);
12
+ return true;
13
+ }
14
+ catch {
15
+ return false;
16
+ }
17
+ }
18
+ /**
19
+ * Attempt to take a PID-file singleton lock.
20
+ * - File missing → write own pid, { acquired: true, stale: false }
21
+ * - File holds a live, valid pid → { acquired: false, holderPid }
22
+ * - File holds a dead/corrupt pid → overwrite with own pid, { acquired: true, stale: true }
23
+ *
24
+ * This function never exits the process or logs — the caller decides how to react to a
25
+ * conflict (typically: log a message and process.exit(1)).
26
+ */
27
+ export function tryAcquireSingletonLock(pidFile) {
28
+ if (existsSync(pidFile)) {
29
+ const raw = readFileSync(pidFile, 'utf8').trim();
30
+ const holderPid = Number(raw);
31
+ if (Number.isFinite(holderPid) && holderPid > 0 && isProcessAlive(holderPid)) {
32
+ return { acquired: false, holderPid };
33
+ }
34
+ // Stale (previous owner died without cleanup) or corrupt content — reclaim it.
35
+ writeFileSync(pidFile, String(process.pid), 'utf8');
36
+ return { acquired: true, stale: true };
37
+ }
38
+ writeFileSync(pidFile, String(process.pid), 'utf8');
39
+ return { acquired: true, stale: false };
40
+ }
41
+ /** Release the lock iff it is still owned by the current process. Best-effort; swallows errors. */
42
+ export function releaseSingletonLock(pidFile) {
43
+ try {
44
+ if (!existsSync(pidFile))
45
+ return;
46
+ const raw = readFileSync(pidFile, 'utf8').trim();
47
+ if (Number(raw) === process.pid)
48
+ unlinkSync(pidFile);
49
+ }
50
+ catch {
51
+ /* best-effort cleanup */
52
+ }
53
+ }
@@ -4,6 +4,7 @@
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { formatDurationCompact } from './utils.js';
6
6
  import { Icons } from './icons.js';
7
+ import { t } from './i18n.js';
7
8
  export function computeElapsed(startTime) {
8
9
  const elapsedS = (Date.now() - startTime) / 1000;
9
10
  return { elapsedStr: formatDurationCompact(elapsedS), elapsedS };
@@ -28,5 +29,5 @@ export function buildUserProcessingMessage({ startTime, elapsed_s = null, num_tu
28
29
  const elapsed = elapsed_s ?? ((Date.now() - startTime) / 1000);
29
30
  const sessionTag = buildSessionTag(sessionName, sessionId);
30
31
  const turnsStr = num_turns != null ? ` | ${Icons.repeat} ${num_turns} turns` : '';
31
- return `${Icons.processing} Processing | ${sessionTag}${profileName || 'default'} | ${Icons.stopwatch} ${formatDurationCompact(elapsed || 0)}${turnsStr}`;
32
+ return `${Icons.processing} ${t('status.processing')} | ${sessionTag}${profileName || 'default'} | ${Icons.stopwatch} ${formatDurationCompact(elapsed || 0)}${turnsStr}`;
32
33
  }
@@ -24,6 +24,12 @@ export interface Task {
24
24
  completed_at: string | null;
25
25
  completed_note: string | null;
26
26
  pending_at: string | null;
27
+ /** Provenance for session→task wake (Problem 1). Captured from CORTEX_* / channel env when a
28
+ * task is created from within a running session or agent. On task.completed, if origin_channel
29
+ * is set (and no thread is waiting on this task), the originating session is woken. */
30
+ origin_session_id: string | null;
31
+ origin_channel: string | null;
32
+ origin_thread_id: string | null;
27
33
  }
28
34
  export interface LockState {
29
35
  owner: string;
@@ -17,6 +17,9 @@ const YAML_TO_TS = {
17
17
  'completed-at': 'completed_at',
18
18
  'completed-note': 'completed_note',
19
19
  'pending-at': 'pending_at',
20
+ 'origin-session-id': 'origin_session_id',
21
+ 'origin-channel': 'origin_channel',
22
+ 'origin-thread-id': 'origin_thread_id',
20
23
  };
21
24
  const TS_TO_YAML = Object.fromEntries(Object.entries(YAML_TO_TS).map(([k, v]) => [v, k]));
22
25
  function yamlKeyToTs(key) {
@@ -47,6 +50,9 @@ const TASK_DEFAULTS = {
47
50
  completed_at: null,
48
51
  completed_note: null,
49
52
  pending_at: null,
53
+ origin_session_id: null,
54
+ origin_channel: null,
55
+ origin_thread_id: null,
50
56
  };
51
57
  // ── Parsing ──
52
58
  function rawToTask(raw, project) {
@@ -78,6 +84,9 @@ function rawToTask(raw, project) {
78
84
  completed_at: mapped.completed_at != null ? String(mapped.completed_at) : null,
79
85
  completed_note: mapped.completed_note != null ? String(mapped.completed_note) : null,
80
86
  pending_at: mapped.pending_at != null ? String(mapped.pending_at) : null,
87
+ origin_session_id: mapped.origin_session_id != null ? String(mapped.origin_session_id) : null,
88
+ origin_channel: mapped.origin_channel != null ? String(mapped.origin_channel) : null,
89
+ origin_thread_id: mapped.origin_thread_id != null ? String(mapped.origin_thread_id) : null,
81
90
  };
82
91
  }
83
92
  function parseTasksFile(content, project) {
@@ -126,6 +135,7 @@ const REQUIRED_KEYS = ['id', 'text', 'why', 'done_when', 'priority', 'status', '
126
135
  const OPTIONAL_KEY_ORDER = [
127
136
  'parent', 'depends_on', 'gpu', 'gpu_count', 'blocked_by', 'claimed_by', 'claimed_at',
128
137
  'paused', 'approval_needed', 'approved_at', 'not_before', 'pending_at', 'completed_at', 'completed_note',
138
+ 'origin_session_id', 'origin_channel', 'origin_thread_id',
129
139
  ];
130
140
  function isDefault(key, value) {
131
141
  const def = TASK_DEFAULTS[key];
@@ -117,6 +117,10 @@ export interface HookContext {
117
117
  artifactContent: string;
118
118
  userMessage: string;
119
119
  totalCostUsd: number;
120
+ /** Out-of-band control intent on this thread (DR-0015): 'abort' | 'split' | 'wait' | null.
121
+ * Hooks (e.g. task-status-check) use this — NOT artifact scanning — to tell an intentional
122
+ * non-completion (abort/split) from a stuck task. */
123
+ pendingControlAction?: 'abort' | 'split' | 'wait' | null;
120
124
  }
121
125
  /** Lifecycle hooks for thread templates */
122
126
  export interface ThreadHooks {
@@ -257,6 +261,21 @@ export interface ThreadMetadata {
257
261
  /** Live status message persisted at suspension so the post-resume settle can refresh it
258
262
  * (otherwise it reads "suspended — waiting on children" forever — 2026-06-11 finding). */
259
263
  statusMsgRef?: MessageRef | null;
264
+ /** Out-of-band control signal written by the agent's own thread_abort / thread_split /
265
+ * thread_wait MCP tool (DR-0015 problem 1). The runner reads this at the step boundary and
266
+ * CLEARS it after consuming, so a control intent fires exactly once. Replaces the old in-band
267
+ * artifact string markers ([ABORT]/[SPLIT]/[WAIT_CHILDREN]) — agent prose that merely mentions
268
+ * those tokens can no longer trigger a control action. Set only via the webhook `control`
269
+ * action, which rejects a second concurrent control on the same thread. */
270
+ pendingControl?: {
271
+ action: 'abort' | 'split' | 'wait';
272
+ kind?: string | null;
273
+ diagnosis?: string | null;
274
+ subtasks?: any[] | null;
275
+ onTasks?: string[] | null;
276
+ onThreads?: string[] | null;
277
+ requestedAtStep?: number;
278
+ } | null;
260
279
  }
261
280
  export interface StepResult {
262
281
  done: boolean;
@@ -297,6 +316,16 @@ export interface RunThreadOptions {
297
316
  multi?: boolean;
298
317
  }>;
299
318
  }) => void) | null;
319
+ /** Invoked when the thread terminates via agent abort, BEFORE onEnd hooks run, so the
320
+ * dispatch path can block the owning task in time (DR-0015 problem 2: otherwise the onEnd
321
+ * task-status-check sees a still-claimed task and "recovers" it by unclaiming, which lets the
322
+ * dispatcher re-grab the task before the abort→block lands). Injected by task-dispatch; absent
323
+ * for non-dispatch threads (no owning task). */
324
+ onAbort?: ((info: {
325
+ taskId: string;
326
+ project: string | null;
327
+ reason: string | null;
328
+ }) => Promise<void> | void) | null;
300
329
  /** Per-call lifecycle hooks injected by the caller (task-dispatcher / scheduled-runner / etc.).
301
330
  * Executed AFTER the template's hook at the same phase (template first, extra second) and share
302
331
  * the same execution semantics (HookContext via stdin, insertAgent / targetAgent result).
@@ -26,4 +26,12 @@ declare function todayISO(): string;
26
26
  * `cortex-task lock-status`, `stats`, id-assignment, etc.).
27
27
  */
28
28
  declare function listProjectDirs(projectsDir?: string): string[];
29
- export { INSTALL_ROOT, DEFAULTS_DIR, PACKAGE_ROOT, SERVER_ROOT, REPO_ROOT, DATA_DIR, CONFIG_DIR, STORE_DIR, CONTEXT_DIR, PROJECTS_DIR, WORKSPACE_DIR, PLUGINS_DIR, PROMPTS_DIR, HOOKS_DIR, SKIP_DIRS, moduleDir, isMainModule, readableTimestamp, chunkText, formatDurationCompact, todayISO, listProjectDirs };
29
+ /**
30
+ * Sentinel ANTHROPIC_API_KEY value set when the gateway is healthy but no real key exists.
31
+ * Its only purpose is to satisfy Claude Code's startup credential check on machines without
32
+ * OAuth login — upstream auth is handled by the gateway's own configured keys. Anything that
33
+ * treats ANTHROPIC_API_KEY as a real credential (gateway-generator discovery, saved-env
34
+ * snapshots) must ignore this value.
35
+ */
36
+ declare const GATEWAY_MANAGED_KEY_PLACEHOLDER = "cortex-gateway-managed";
37
+ export { INSTALL_ROOT, DEFAULTS_DIR, PACKAGE_ROOT, SERVER_ROOT, REPO_ROOT, DATA_DIR, CONFIG_DIR, STORE_DIR, CONTEXT_DIR, PROJECTS_DIR, WORKSPACE_DIR, PLUGINS_DIR, PROMPTS_DIR, HOOKS_DIR, SKIP_DIRS, GATEWAY_MANAGED_KEY_PLACEHOLDER, moduleDir, isMainModule, readableTimestamp, chunkText, formatDurationCompact, todayISO, listProjectDirs };
@@ -95,4 +95,12 @@ function listProjectDirs(projectsDir = PROJECTS_DIR) {
95
95
  return [];
96
96
  }
97
97
  }
98
- export { INSTALL_ROOT, DEFAULTS_DIR, PACKAGE_ROOT, SERVER_ROOT, REPO_ROOT, DATA_DIR, CONFIG_DIR, STORE_DIR, CONTEXT_DIR, PROJECTS_DIR, WORKSPACE_DIR, PLUGINS_DIR, PROMPTS_DIR, HOOKS_DIR, SKIP_DIRS, moduleDir, isMainModule, readableTimestamp, chunkText, formatDurationCompact, todayISO, listProjectDirs };
98
+ /**
99
+ * Sentinel ANTHROPIC_API_KEY value set when the gateway is healthy but no real key exists.
100
+ * Its only purpose is to satisfy Claude Code's startup credential check on machines without
101
+ * OAuth login — upstream auth is handled by the gateway's own configured keys. Anything that
102
+ * treats ANTHROPIC_API_KEY as a real credential (gateway-generator discovery, saved-env
103
+ * snapshots) must ignore this value.
104
+ */
105
+ const GATEWAY_MANAGED_KEY_PLACEHOLDER = 'cortex-gateway-managed';
106
+ export { INSTALL_ROOT, DEFAULTS_DIR, PACKAGE_ROOT, SERVER_ROOT, REPO_ROOT, DATA_DIR, CONFIG_DIR, STORE_DIR, CONTEXT_DIR, PROJECTS_DIR, WORKSPACE_DIR, PLUGINS_DIR, PROMPTS_DIR, HOOKS_DIR, SKIP_DIRS, GATEWAY_MANAGED_KEY_PLACEHOLDER, moduleDir, isMainModule, readableTimestamp, chunkText, formatDurationCompact, todayISO, listProjectDirs };
@@ -1,3 +1,4 @@
1
+ import { GATEWAY_MANAGED_KEY_PLACEHOLDER } from '../../core/utils.js';
1
2
  export interface ModeFileData {
2
3
  mode?: string;
3
4
  claudeMode?: string;
@@ -55,4 +56,4 @@ export declare function resolveAgentModel({ profileName, modelOverride }?: {
55
56
  modelOverride?: string | null;
56
57
  }): string;
57
58
  export declare function detectBillingMode(): string;
58
- export { GATEWAY_ANTHROPIC_URL, saveModeFile, loadModeFile, };
59
+ export { GATEWAY_ANTHROPIC_URL, GATEWAY_MANAGED_KEY_PLACEHOLDER, saveModeFile, loadModeFile, };
@@ -5,7 +5,7 @@ import { readFileSync, writeFileSync } from 'fs';
5
5
  import { parse as parseDotenv } from 'dotenv';
6
6
  import * as path from 'path';
7
7
  import * as http from 'http';
8
- import { STORE_DIR, CONFIG_DIR } from '../../core/utils.js';
8
+ import { STORE_DIR, CONFIG_DIR, GATEWAY_MANAGED_KEY_PLACEHOLDER } from '../../core/utils.js';
9
9
  import { getProfileModel, resolveProfileConfig } from './profile-manager.js';
10
10
  import { GATEWAY_URL, isGatewayHealthy } from '../costs/gateway-manager.js';
11
11
  import { createLogger } from '../../core/log.js';
@@ -52,8 +52,12 @@ function readApiEnvFromDotenvFile() {
52
52
  }
53
53
  function captureApiEnvSnapshot() {
54
54
  const fileEnv = readApiEnvFromDotenvFile();
55
+ // The gateway-managed placeholder is not a real credential — never let it
56
+ // pollute the saved env used for direct (gateway-down) connections.
57
+ const liveKey = normalizeEnvValue(process.env.ANTHROPIC_API_KEY);
58
+ const realLiveKey = liveKey === GATEWAY_MANAGED_KEY_PLACEHOLDER ? undefined : liveKey;
55
59
  return {
56
- ANTHROPIC_API_KEY: normalizeEnvValue(process.env.ANTHROPIC_API_KEY) || fileEnv.ANTHROPIC_API_KEY,
60
+ ANTHROPIC_API_KEY: realLiveKey || fileEnv.ANTHROPIC_API_KEY,
57
61
  ANTHROPIC_BASE_URL: normalizeEnvValue(process.env.ANTHROPIC_BASE_URL) || fileEnv.ANTHROPIC_BASE_URL,
58
62
  };
59
63
  }
@@ -234,7 +238,18 @@ export function configureEnvForMode(mode, metadata) {
234
238
  if (isGatewayHealthy()) {
235
239
  const url = gatewayModeUrl(mode, metadata);
236
240
  process.env.ANTHROPIC_BASE_URL = url;
237
- delete process.env.ANTHROPIC_API_KEY;
241
+ if (mode === 'plan') {
242
+ // Plan mode rides the gateway's passthrough: Claude Code must send its own OAuth
243
+ // bearer token, and an env API key would take precedence over OAuth — delete it.
244
+ delete process.env.ANTHROPIC_API_KEY;
245
+ }
246
+ else {
247
+ // Non-plan modes: upstream auth is the gateway's job (it injects its own configured
248
+ // keys). Keep a key in env purely so Claude Code passes its startup credential check
249
+ // on machines without OAuth login (otherwise it exits with "Please run /login").
250
+ const saved = getSavedApiEnv();
251
+ process.env.ANTHROPIC_API_KEY = saved.ANTHROPIC_API_KEY || GATEWAY_MANAGED_KEY_PLACEHOLDER;
252
+ }
238
253
  return url;
239
254
  }
240
255
  // Gateway unhealthy — fallback to direct connection
@@ -308,6 +323,10 @@ export function detectBillingMode() {
308
323
  catch { }
309
324
  return 'api';
310
325
  }
311
- // Apply persisted mode on startup — route through gateway if healthy, else direct
312
- configureEnvForMode(claudeMode);
313
- export { GATEWAY_ANTHROPIC_URL, saveModeFile, loadModeFile, };
326
+ // NOTE: deliberately NO configureEnvForMode() call at module scope. This module is imported
327
+ // transitively by CLI processes (cortex init / setup-gateway via domain/threads), where the
328
+ // gateway is always unhealthy — an import-time call would delete ANTHROPIC_API_KEY (plan mode)
329
+ // before gateway-generator discovery runs, breaking api endpoint generation. The server entry
330
+ // (app.ts) applies the persisted mode explicitly after dotenv loads; every agent spawn also
331
+ // calls configureEnvForMode() per-request (facade.runAgentOnce).
332
+ export { GATEWAY_ANTHROPIC_URL, GATEWAY_MANAGED_KEY_PLACEHOLDER, saveModeFile, loadModeFile, };
@@ -35,6 +35,10 @@ export interface RunAgentOptions {
35
35
  /** Recursion depth of the owning thread, surfaced to the spawned agent as CORTEX_THREAD_DEPTH
36
36
  * so the thread_start MCP tool can forward it for the depth guard. */
37
37
  threadDepth?: number | null;
38
+ /** Owning dispatch task id/project, surfaced as CORTEX_TASK_ID / CORTEX_TASK_PROJECT so
39
+ * `cortex-task spawn` can infer the current task as the parent of a child task. */
40
+ taskId?: string | null;
41
+ taskProject?: string | null;
38
42
  onProgress?: ((progress: any) => void) | null;
39
43
  onAssistantMessage?: ((msg: string) => void) | null;
40
44
  onToolUse?: ((name: string, input: any) => void) | null;
@@ -40,8 +40,10 @@ function buildSpawnConfig(options, config, anthropicBaseUrl) {
40
40
  executionId: options.executionId ?? null,
41
41
  useCoreMcp: options.useCoreMcp ?? undefined,
42
42
  threadDepth: options.threadDepth ?? null,
43
+ taskId: options.taskId ?? null,
44
+ taskProject: options.taskProject ?? null,
43
45
  };
44
- const hasContext = !!(ctx.threadId || ctx.profile || ctx.project || ctx.sessionName || ctx.executionId || ctx.useCoreMcp || ctx.threadDepth != null);
46
+ const hasContext = !!(ctx.threadId || ctx.profile || ctx.project || ctx.sessionName || ctx.executionId || ctx.useCoreMcp || ctx.threadDepth != null || ctx.taskId || ctx.taskProject);
45
47
  // Load global rules (no paths frontmatter) and inject as appendSystemPrompt.
46
48
  // Scoped rules (with paths) are handled by the Read/Grep PostToolUse hook.
47
49
  const rules = loadCortexRules();
@@ -1,13 +1,16 @@
1
- // input: MCP SDK, task-ops + time + thread-ops tool modules
2
- // output: MCP stdio service, exposing remote_* tools, current_time, and thread_* tools
1
+ // input: MCP SDK, remote-ops + time + thread control + task-monitor tool modules
2
+ // output: MCP stdio service, exposing remote_* tools, current_time, thread control tools, task_* tools
3
3
  // pos: Core MCP server — thread agents load only this one (no Slack/cost/schedule tools).
4
- // thread_* tools let any agent drive the Thread system via the daemon webhook.
4
+ // Delegation is via the task system (cortex-task CLI); thread control tools (abort/split/wait)
5
+ // let an agent steer its own thread; task_* tools monitor tasks. The agent-facing thread
6
+ // spawn/monitor tools (thread_start + status/result/list/list_templates/cancel) were removed.
5
7
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
6
8
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
7
9
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
8
10
  import { registerTaskOpsTools } from './tools/task-ops.js';
9
11
  import { registerTimeTools } from './tools/time.js';
10
12
  import { registerThreadTools } from './tools/thread-ops.js';
13
+ import { registerTaskMonitorTools } from './tools/task-monitor.js';
11
14
  import { isMainModule } from '../../core/utils.js';
12
15
  import { createLogger } from '../../core/log.js';
13
16
  import { CORTEX_VERSION } from '../../core/version.js';
@@ -17,6 +20,7 @@ const server = new McpServer({ name: 'cortex-core', version: CORTEX_VERSION });
17
20
  registerTaskOpsTools(server);
18
21
  registerTimeTools(server);
19
22
  registerThreadTools(server);
23
+ registerTaskMonitorTools(server);
20
24
  // --- Exported tool name list (for verification) ---
21
25
  export const TOOL_NAMES = [
22
26
  'remote_bash',
@@ -26,12 +30,14 @@ export const TOOL_NAMES = [
26
30
  'remote_glob',
27
31
  'remote_grep',
28
32
  'current_time',
29
- 'thread_start',
30
- 'thread_status',
31
- 'thread_result',
32
- 'thread_list',
33
- 'thread_list_templates',
34
- 'thread_cancel',
33
+ // DR-0015 control plane: an agent signals its own thread (abort / split / wait).
34
+ 'thread_abort',
35
+ 'thread_split',
36
+ 'thread_wait',
37
+ // Task monitoring (delegation itself is via the cortex-task CLI).
38
+ 'task_status',
39
+ 'task_result',
40
+ 'task_list',
35
41
  ];
36
42
  // --- Start (called by barrel when run as standalone) ---
37
43
  export async function startServer() {
@@ -0,0 +1,2 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ export declare function registerTaskMonitorTools(server: McpServer): void;