@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
@@ -0,0 +1,68 @@
1
+ // input: persistence (load/save) + recordResume calls from interruption points
2
+ // output: init/recordResume/takeAllResumes/getResumeCount — pending resume bookkeeping
3
+ // pos: Pure state tracker for sessions/threads interrupted by a rate limit. No
4
+ // orchestration/scheduler coupling — the resume *dispatch* lives in orchestration.
5
+ // Mirrors rate-limit-throttle.ts purity & injected-persistence shape.
6
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
7
+ import { createLogger } from '../../core/log.js';
8
+ const log = createLogger('resume-registry');
9
+ // --- Module state ---
10
+ let _persistence = null;
11
+ // Direct conversations dedupe by channel (pooled per channel — only the latest turn matters).
12
+ const _direct = new Map();
13
+ // Threads dedupe by threadId (each thread is an independent resumable unit).
14
+ const _threads = new Map();
15
+ function snapshot() {
16
+ return [..._direct.values(), ..._threads.values()];
17
+ }
18
+ function persist() {
19
+ _persistence?.save(snapshot()).catch(e => {
20
+ log.error(`Failed to persist resume queue: ${e.message}`);
21
+ });
22
+ }
23
+ // --- Public API ---
24
+ async function initResumeRegistry(persistence) {
25
+ _persistence = persistence;
26
+ try {
27
+ const persisted = await persistence.load();
28
+ for (const entry of persisted ?? []) {
29
+ if (entry.kind === 'direct')
30
+ _direct.set(entry.channel, entry);
31
+ else if (entry.kind === 'thread')
32
+ _threads.set(entry.threadId, entry);
33
+ }
34
+ log.info(`Initialized — ${_direct.size + _threads.size} pending resume(s) restored`);
35
+ }
36
+ catch (e) {
37
+ log.error(`Failed to load resume queue: ${e.message}`);
38
+ }
39
+ }
40
+ /** Record an interrupted session/thread for later resume. Idempotent per key
41
+ * (direct→channel, thread→threadId): a newer record overwrites the older one. */
42
+ function recordResume(entry) {
43
+ if (entry.kind === 'direct')
44
+ _direct.set(entry.channel, entry);
45
+ else if (entry.kind === 'thread')
46
+ _threads.set(entry.threadId, entry);
47
+ persist();
48
+ }
49
+ /** Drain the registry: return all pending entries and clear (persists the empty list).
50
+ * "take + clear" is atomic so each entry is dispatched at most once. */
51
+ function takeAllResumes() {
52
+ const all = snapshot();
53
+ _direct.clear();
54
+ _threads.clear();
55
+ if (all.length > 0)
56
+ persist();
57
+ return all;
58
+ }
59
+ function getResumeCount() {
60
+ return _direct.size + _threads.size;
61
+ }
62
+ // --- Test helpers ---
63
+ function _testReset() {
64
+ _direct.clear();
65
+ _threads.clear();
66
+ _persistence = null;
67
+ }
68
+ export { initResumeRegistry, recordResume, takeAllResumes, getResumeCount, _testReset };
@@ -11,6 +11,7 @@ import { registerTaskOpsTools } from './tools/task-ops.js';
11
11
  import { registerTimeTools } from './tools/time.js';
12
12
  import { registerThreadTools } from './tools/thread-ops.js';
13
13
  import { registerTaskMonitorTools } from './tools/task-monitor.js';
14
+ import { registerManagerQaTools } from './tools/manager-qa.js';
14
15
  import { isMainModule } from '../../core/utils.js';
15
16
  import { createLogger } from '../../core/log.js';
16
17
  import { CORTEX_VERSION } from '../../core/version.js';
@@ -21,6 +22,7 @@ registerTaskOpsTools(server);
21
22
  registerTimeTools(server);
22
23
  registerThreadTools(server);
23
24
  registerTaskMonitorTools(server);
25
+ registerManagerQaTools(server);
24
26
  // --- Exported tool name list (for verification) ---
25
27
  export const TOOL_NAMES = [
26
28
  'remote_bash',
@@ -38,6 +40,9 @@ export const TOOL_NAMES = [
38
40
  'task_status',
39
41
  'task_result',
40
42
  'task_list',
43
+ // DR-0016 up-ask channel: a subtask asks its manager (or a human) a clarifying question.
44
+ 'ask_manager',
45
+ 'answer_subtask',
41
46
  ];
42
47
  // --- Start (called by barrel when run as standalone) ---
43
48
  export async function startServer() {
@@ -1,61 +1,15 @@
1
- // input: MCP SDK, register*Tools modules, FeishuToolDeps
2
- // output: registerFeishuTools — aggregate all feishu_* doc/wiki/bitable/sheets tools onto a server
3
- // pos: Single entry the cortex-feishu MCP server calls to wire all Feishu tools
1
+ // input: MCP SDK, registerFileTools, FeishuToolDeps
2
+ // output: registerFeishuTools — wire the feishu_send_file tool onto a server
3
+ // pos: Single entry the cortex-feishu MCP server calls to wire all Feishu tools.
4
+ // Document/table/wiki tooling was removed in favor of the official lark-cli
5
+ // (see the feishu-doc skill); this MCP now only exposes file sending.
4
6
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
- import { registerDocxTools } from './docx.js';
6
- import { registerWikiTools } from './wiki.js';
7
- import { registerBitableTools } from './bitable.js';
8
- import { registerSheetsTools } from './sheets.js';
9
- import { registerDriveTools } from './drive.js';
10
7
  import { registerFileTools } from './file.js';
11
8
  /** Tool names exposed by the cortex-feishu MCP server (kept in sync for verification). */
12
9
  export const FEISHU_TOOL_NAMES = [
13
10
  // file — send files to chats
14
11
  'feishu_send_file',
15
- // docx — cloud documents
16
- 'feishu_docx_create',
17
- 'feishu_docx_get_content',
18
- 'feishu_docx_list_blocks',
19
- 'feishu_docx_append',
20
- 'feishu_docx_insert',
21
- 'feishu_docx_update_block',
22
- 'feishu_docx_delete_blocks',
23
- 'feishu_docx_delete',
24
- // wiki — knowledge base
25
- 'feishu_wiki_list_spaces',
26
- 'feishu_wiki_list_nodes',
27
- 'feishu_wiki_get_node',
28
- 'feishu_wiki_create_node',
29
- 'feishu_wiki_update_node_title',
30
- // bitable — 多维表格
31
- 'feishu_bitable_create_app',
32
- 'feishu_bitable_delete_app',
33
- 'feishu_bitable_list_tables',
34
- 'feishu_bitable_create_table',
35
- 'feishu_bitable_delete_table',
36
- 'feishu_bitable_list_fields',
37
- 'feishu_bitable_create_field',
38
- 'feishu_bitable_list_records',
39
- 'feishu_bitable_create_records',
40
- 'feishu_bitable_update_records',
41
- 'feishu_bitable_delete_records',
42
- // sheets — 电子表格
43
- 'feishu_sheets_create',
44
- 'feishu_sheets_delete',
45
- 'feishu_sheets_get',
46
- 'feishu_sheets_read_range',
47
- 'feishu_sheets_write_range',
48
- 'feishu_sheets_append_rows',
49
- 'feishu_sheets_add_sheet',
50
- 'feishu_sheets_delete_sheet',
51
- // drive — sharing & permissions
52
- 'feishu_drive_set_link_share',
53
12
  ];
54
13
  export function registerFeishuTools(server, deps) {
55
14
  registerFileTools(server, deps);
56
- registerDocxTools(server, deps);
57
- registerWikiTools(server, deps);
58
- registerBitableTools(server, deps);
59
- registerSheetsTools(server, deps);
60
- registerDriveTools(server, deps);
61
15
  }
@@ -1,5 +1,6 @@
1
1
  // input: MCP SDK, feishu/ tool registration, lark client builder
2
- // output: cortex-feishu MCP stdio server — Feishu tools (docx/wiki/bitable/sheets + drive sharing)
2
+ // output: cortex-feishu MCP stdio server — Feishu file sending (feishu_send_file).
3
+ // Document/table/wiki tooling moved to the official lark-cli (see feishu-doc skill).
3
4
  // pos: Standalone MCP server (peer of core-server.ts & server.ts); loaded only for Feishu-originated
4
5
  // sessions (channel carries the `feishu:` prefix) — Claude via mcp-config-feishu.json layering,
5
6
  // PI via the mcp-bridge feishu handle. Not loaded for thread/core sessions.
@@ -20,7 +21,7 @@ registerFeishuTools(server, { client });
20
21
  export const TOOL_NAMES = FEISHU_TOOL_NAMES;
21
22
  export async function startServer() {
22
23
  if (!client) {
23
- log.warn('FEISHU_APP_ID / FEISHU_APP_SECRET not set — Feishu document tools will return a not-configured error');
24
+ log.warn('FEISHU_APP_ID / FEISHU_APP_SECRET not set — feishu_send_file will return a not-configured error');
24
25
  }
25
26
  const transport = new StdioServerTransport();
26
27
  await server.connect(transport);
@@ -0,0 +1,2 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ export declare function registerManagerQaTools(server: McpServer): void;
@@ -0,0 +1,72 @@
1
+ // input: McpServer, webhook proxy (/webhook/manager-qa), CORTEX_THREAD_ID env
2
+ // output: ask_manager / answer_subtask registrations (DR-0016 up-ask channel)
3
+ // pos: A subtask asks its manager (or, at the top of the tree, a human) a clarifying question and
4
+ // BLOCKS synchronously — ask_manager registers the question, then polls until answered and
5
+ // returns the answer as the tool result. The manager answers with answer_subtask. Managers
6
+ // nest: a manager that is itself unsure can ask_manager upward. Proxied through the daemon
7
+ // webhook (separate process; no shared memory with the thread store / runner).
8
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
9
+ import { z } from 'zod';
10
+ const WEBHOOK_BASE = `http://127.0.0.1:${process.env.WEBHOOK_PORT || '3001'}`;
11
+ const POLL_INTERVAL_MS = 3000;
12
+ const TIMEOUT_MS = parseInt(process.env.CORTEX_ASK_MANAGER_TIMEOUT_MS || '1800000', 10) || 1800000; // 30 min
13
+ async function proxyQa(action, payload) {
14
+ const res = await fetch(`${WEBHOOK_BASE}/webhook/manager-qa`, {
15
+ method: 'POST',
16
+ headers: { 'Content-Type': 'application/json', 'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '' },
17
+ body: JSON.stringify({ action, ...payload }),
18
+ });
19
+ const data = await res.json();
20
+ if (!data.success)
21
+ throw new Error(data.error || 'manager-qa failed');
22
+ return data.data;
23
+ }
24
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
25
+ export function registerManagerQaTools(server) {
26
+ const selfThreadId = () => {
27
+ const id = process.env.CORTEX_THREAD_ID;
28
+ if (!id)
29
+ throw new Error('not running inside a thread (CORTEX_THREAD_ID unset) — ask_manager only works from within a dispatched task/thread');
30
+ return id;
31
+ };
32
+ // --- ask_manager ---
33
+ server.tool('ask_manager', 'Ask the manager who planned your task a clarifying question when you hit confusion, a contradiction, or an ambiguous/under-specified intent — instead of guessing or aborting. This is LIGHTER than thread_abort: it does not give up the task; it resolves the uncertainty and lets you continue. The call BLOCKS until the manager replies, then returns their answer. Managers nest: if your manager is itself unsure it may ask its own manager upward; at the top of the tree the question goes to a human. Use for genuine planning/intent questions (e.g. "did you mean approach A or B?", "two done_when conditions conflict — which wins?"), not for things you can settle by reading the deliverable, code, or task spec yourself.', {
34
+ question: z.string().min(1).describe('A specific, self-contained question about the planning intent. Include the conflict/ambiguity and the options you see so the manager can answer crisply.'),
35
+ }, async ({ question }) => {
36
+ try {
37
+ const threadId = selfThreadId();
38
+ const reg = await proxyQa('ask', { threadId, question });
39
+ const questionId = reg.questionId;
40
+ const target = reg.target;
41
+ const deadline = Date.now() + TIMEOUT_MS;
42
+ while (Date.now() < deadline) {
43
+ await sleep(POLL_INTERVAL_MS);
44
+ const poll = await proxyQa('poll', { questionId });
45
+ if (poll.answered) {
46
+ const who = target === 'human' ? 'human' : 'manager';
47
+ return { content: [{ type: 'text', text: `Answer from your ${who}:\n\n${poll.answer}` }] };
48
+ }
49
+ }
50
+ return {
51
+ content: [{ type: 'text', text: `ask_manager timed out after ${Math.round(TIMEOUT_MS / 60000)} min with no reply (${target}). Proceed with your best judgment and record the assumption explicitly, or call thread_abort with a diagnosis if you cannot.` }],
52
+ isError: true,
53
+ };
54
+ }
55
+ catch (e) {
56
+ return { content: [{ type: 'text', text: `ask_manager error: ${e.message}` }], isError: true };
57
+ }
58
+ });
59
+ // --- answer_subtask ---
60
+ server.tool('answer_subtask', 'Answer a question a subtask asked you via ask_manager (the question, with its question_id, arrives in your context while you are waiting on your children). Give a concrete, actionable answer about your planning intent. After you answer, your thread automatically returns to waiting for your children — end your step. If the question is really about a HIGHER-level intent you are unsure of, call ask_manager to ask your own manager first, then answer the subtask with what you learn.', {
61
+ question_id: z.string().min(1).describe('The question_id from the subtask question notice.'),
62
+ answer: z.string().min(1).describe('Your answer / clarification for the subtask.'),
63
+ }, async ({ question_id, answer }) => {
64
+ try {
65
+ const result = await proxyQa('answer', { question_id, answer });
66
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
67
+ }
68
+ catch (e) {
69
+ return { content: [{ type: 'text', text: `answer_subtask error: ${e.message}` }], isError: true };
70
+ }
71
+ });
72
+ }
@@ -12,15 +12,17 @@ import { WORKSPACE_DIR } from '../../../core/utils.js';
12
12
  import { cortexMDContentBlocks } from './cortex-md.js';
13
13
  // Remote device commands proxied through app.ts webhook (separate process, no shared memory with client-manager)
14
14
  const WEBHOOK_BASE = `http://127.0.0.1:${process.env.WEBHOOK_PORT || '3001'}`;
15
+ // Bearer token for the webhook auth gate. Inherited from the daemon's env (see core/auth.ts).
16
+ const webhookAuthHeader = () => ({ 'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '' });
15
17
  async function proxyGetOnlineDevices() {
16
- const res = await fetch(`${WEBHOOK_BASE}/webhook/devices`);
18
+ const res = await fetch(`${WEBHOOK_BASE}/webhook/devices`, { headers: webhookAuthHeader() });
17
19
  const data = await res.json();
18
20
  return data.devices || [];
19
21
  }
20
22
  async function proxySendCommand(device, action, params, timeout) {
21
23
  const res = await fetch(`${WEBHOOK_BASE}/webhook/remote-command`, {
22
24
  method: 'POST',
23
- headers: { 'Content-Type': 'application/json' },
25
+ headers: { 'Content-Type': 'application/json', ...webhookAuthHeader() },
24
26
  body: JSON.stringify({ device, action, params, timeout }),
25
27
  });
26
28
  const data = await res.json();
@@ -14,7 +14,8 @@ const WEBHOOK_BASE = `http://127.0.0.1:${process.env.WEBHOOK_PORT || '3001'}`;
14
14
  async function proxyThreadOp(action, payload) {
15
15
  const res = await fetch(`${WEBHOOK_BASE}/webhook/thread-op`, {
16
16
  method: 'POST',
17
- headers: { 'Content-Type': 'application/json' },
17
+ // Bearer token for the webhook auth gate. Inherited from the daemon's env (see core/auth.ts).
18
+ headers: { 'Content-Type': 'application/json', 'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '' },
18
19
  body: JSON.stringify({ action, ...payload }),
19
20
  });
20
21
  const data = await res.json();
@@ -21,7 +21,8 @@ const webhookBaseUrl = `http://127.0.0.1:${webhookPort}`;
21
21
  async function defaultHttpPost(url, body) {
22
22
  const r = await fetch(url, {
23
23
  method: 'POST',
24
- headers: { 'Content-Type': 'application/json' },
24
+ // Bearer token for the webhook auth gate. Inherited from the session's env (see core/auth.ts).
25
+ headers: { 'Content-Type': 'application/json', 'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '' },
25
26
  body: JSON.stringify(body),
26
27
  });
27
28
  let parsed = null;
@@ -1,5 +1,6 @@
1
- interface ThreadLike {
2
- templateName: string | null;
3
- }
4
- export declare function loadUserContext(thread: ThreadLike): string | null;
5
- export {};
1
+ /**
2
+ * The user profile for plain, thread-free conversation turns. Injected by default;
3
+ * set CORTEX_DISABLE_USER_CONTEXT=1 to opt out. Multi-agent thread steps deliberately
4
+ * do NOT inject this — only the direct conversation path calls it.
5
+ */
6
+ export declare function loadUserContext(): string | null;
@@ -1,12 +1,14 @@
1
- // input: REPO_ROOT, fs, thread record
1
+ // input: CONTEXT_DIR, fs
2
2
  // output: loadUserContext()
3
- // pos: user profile injection — reads USER.md and injects in direct conversation threads
3
+ // pos: user profile injection — reads USER.md and injects into thread-free conversation
4
+ // turns only (buildConversationPrompt), and only on a session's FIRST turn (the caller
5
+ // gates via includeUserContext; session resume keeps it in history thereafter).
6
+ // Thread steps never carry the user profile.
4
7
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
8
  import { readFileSync, statSync } from 'fs';
6
9
  import * as path from 'path';
7
10
  import { CONTEXT_DIR } from '../../core/utils.js';
8
11
  const USER_MD_PATH = path.join(CONTEXT_DIR, 'user', 'USER.md');
9
- const DIRECT_TEMPLATES = new Set(['direct', 'direct-web', 'direct-review']);
10
12
  let cachedContent = null;
11
13
  let cachedMtimeMs = 0;
12
14
  function readUserMd() {
@@ -22,10 +24,13 @@ function readUserMd() {
22
24
  return null;
23
25
  }
24
26
  }
25
- export function loadUserContext(thread) {
26
- if (process.env.CORTEX_INJECT_USER_CONTEXT !== '1')
27
- return null;
28
- if (thread.templateName && !DIRECT_TEMPLATES.has(thread.templateName))
27
+ /**
28
+ * The user profile for plain, thread-free conversation turns. Injected by default;
29
+ * set CORTEX_DISABLE_USER_CONTEXT=1 to opt out. Multi-agent thread steps deliberately
30
+ * do NOT inject this — only the direct conversation path calls it.
31
+ */
32
+ export function loadUserContext() {
33
+ if (process.env.CORTEX_DISABLE_USER_CONTEXT === '1')
29
34
  return null;
30
35
  const content = readUserMd();
31
36
  if (!content)
@@ -18,6 +18,10 @@ if (!serverHost) {
18
18
  process.exit(1);
19
19
  }
20
20
  const serverPort = getArg('--server-port') || '3002';
21
+ // The WS auth token the remote client must present. Falls back to the server's own env so a
22
+ // bootstrap run on the server host picks it up automatically. Empty means the client cannot
23
+ // authenticate — we warn loudly below.
24
+ const clientToken = getArg('--client-token') || process.env.CORTEX_CLIENT_TOKEN || '';
21
25
  if (!sshHost) {
22
26
  log.error(`Usage: node --import tsx src/client-bootstrap.ts --host user@host --device-name NAME [options]
23
27
 
@@ -26,6 +30,7 @@ Options:
26
30
  --device-name <name> Device name for cortex-client (required)
27
31
  --server-host <host> Cortex server IP (required)
28
32
  --server-port <port> Cortex server WS port (default: 3002)
33
+ --client-token <token> WS auth token (default: \$CORTEX_CLIENT_TOKEN from server env)
29
34
  `);
30
35
  process.exit(1);
31
36
  }
@@ -99,7 +104,13 @@ async function main() {
99
104
  }
100
105
  // Step 5: Create systemd service
101
106
  console.log('[5/5] Setting up auto-start...');
107
+ if (!clientToken) {
108
+ log.warn('No client token available (pass --client-token or set CORTEX_CLIENT_TOKEN). The');
109
+ log.warn('client will be REJECTED by the server WS auth gate until a token is configured.');
110
+ }
102
111
  const platform = await sshExec('uname -s').catch(() => 'unknown');
112
+ // Token is hex (no systemd-special chars), so it is safe to embed directly.
113
+ const tokenEnvLine = clientToken ? `Environment=CORTEX_CLIENT_TOKEN=${clientToken}\n` : '';
103
114
  if (platform === 'Linux') {
104
115
  const serviceContent = `[Unit]
105
116
  Description=Cortex Client (${deviceName})
@@ -107,7 +118,7 @@ After=network.target
107
118
 
108
119
  [Service]
109
120
  Type=simple
110
- ExecStart=/usr/bin/env cortex-client
121
+ ${tokenEnvLine}ExecStart=/usr/bin/env cortex-client
111
122
  Restart=always
112
123
  RestartSec=5
113
124
 
@@ -124,7 +135,8 @@ WantedBy=default.target
124
135
  }
125
136
  else {
126
137
  // Non-Linux: just create a wrapper script
127
- const startScript = '#!/bin/bash\nexec cortex-client\n';
138
+ const tokenExport = clientToken ? `export CORTEX_CLIENT_TOKEN=${clientToken}\n` : '';
139
+ const startScript = `#!/bin/bash\n${tokenExport}exec cortex-client\n`;
128
140
  await sshExec(`mkdir -p ~/.cortex/bin`);
129
141
  await sshExec(`cat > ~/.cortex/bin/start-client.sh << 'SHEOF'\n${startScript}\nSHEOF`);
130
142
  await sshExec(`chmod +x ~/.cortex/bin/start-client.sh`);
@@ -13,7 +13,14 @@ interface ClientUpdateResult {
13
13
  devices: DeviceResult[];
14
14
  duration: number;
15
15
  }
16
+ interface LocalUpdateDeps {
17
+ getInstalledVersion: () => string | null;
18
+ kill: () => Promise<boolean>;
19
+ npmUpdate: () => Promise<string>;
20
+ restart: () => Promise<boolean>;
21
+ }
22
+ declare function updateClientReleaseLocal(device: string, latestVersion: string, deps: LocalUpdateDeps): Promise<DeviceResult>;
16
23
  declare function checkAndUpdateClients(): Promise<ClientUpdateResult | null>;
17
24
  declare function formatUpdateSlackMessage(result: ClientUpdateResult): string;
18
- export { checkAndUpdateClients, formatUpdateSlackMessage };
19
- export type { ClientUpdateResult, DeviceResult };
25
+ export { checkAndUpdateClients, formatUpdateSlackMessage, updateClientReleaseLocal };
26
+ export type { ClientUpdateResult, DeviceResult, LocalUpdateDeps };
@@ -1,11 +1,13 @@
1
1
  // Client hot-reload — two modes:
2
2
  // Dev mode (CORTEX_REPO set): build client from source, check tgz mtime,
3
3
  // SCP to remotes + npm install -g + restart.
4
- // Release mode (CORTEX_REPO unset): check npm registry vs remote installed
5
- // version, npm update -g + restart.
4
+ // Release mode (CORTEX_REPO unset): check npm registry vs installed version,
5
+ // npm update -g + restart. Covers remote devices
6
+ // (over SSH) AND the local same-machine client
7
+ // (local npm + process.kill + detached respawn).
6
8
  import * as fs from 'fs';
7
9
  import * as path from 'path';
8
- import { execSync, execFile } from 'child_process';
10
+ import { execSync, execFile, spawn } from 'child_process';
9
11
  import { getMachineRegistry } from '../tasks/dispatch-utils.js';
10
12
  import { sshExec, clientPids, buildRemoteSpawnCommand } from './client-manager.js';
11
13
  import { STORE_DIR } from '../../core/utils.js';
@@ -140,6 +142,30 @@ function getNpmRegistryVersion() {
140
142
  return null;
141
143
  }
142
144
  }
145
+ function getLocalInstalledVersion() {
146
+ try {
147
+ const result = execSync('npm ls -g @cortex-agent/client --json 2>/dev/null || true', {
148
+ encoding: 'utf8',
149
+ timeout: 15000,
150
+ stdio: 'pipe',
151
+ }).trim();
152
+ const parsed = JSON.parse(result);
153
+ return parsed?.dependencies?.['@cortex-agent/client']?.version || null;
154
+ }
155
+ catch {
156
+ return null;
157
+ }
158
+ }
159
+ function npmUpdateLocal() {
160
+ return new Promise((resolve, reject) => {
161
+ execFile('npm', ['update', '-g', '@cortex-agent/client'], { timeout: 120000 }, (err, stdout, stderr) => {
162
+ if (err)
163
+ reject(new Error(`npm update error: ${err.message}\n${stderr}`));
164
+ else
165
+ resolve(stdout.trim());
166
+ });
167
+ });
168
+ }
143
169
  async function getRemoteInstalledVersion(host) {
144
170
  try {
145
171
  const cmd = 'npm ls -g @cortex-agent/client --json 2>/dev/null || true';
@@ -183,6 +209,22 @@ async function killClientOnDevice(device, reg) {
183
209
  }
184
210
  async function restartClientOnDevice(device, reg) {
185
211
  try {
212
+ if (!reg.ssh) {
213
+ // Local device: spawn a detached cortex-client (mirrors client-manager
214
+ // startRemoteClient local branch). PATH now resolves to the just-updated
215
+ // global binary. Env (incl. CORTEX_CLIENT_TOKEN) is inherited from the server.
216
+ const child = spawn('cortex-client', [], { detached: true, stdio: 'ignore' });
217
+ child.on('error', (err) => {
218
+ log.warn(`Local client respawn error on ${device}: ${err.message}`);
219
+ });
220
+ child.unref();
221
+ if (child.pid) {
222
+ clientPids.set(device, child.pid);
223
+ log.info(`Restarted local client on ${device} (PID ${child.pid})`);
224
+ return true;
225
+ }
226
+ return false;
227
+ }
186
228
  if (reg.win) {
187
229
  const wmiArg = 'cmd.exe /c cortex-client';
188
230
  await sshExec(reg.ssh, `powershell -Command "(Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList '${wmiArg}').ProcessId"`, 30000);
@@ -230,12 +272,41 @@ async function updateClientDev(device, reg, tgzPath, tgzName) {
230
272
  }
231
273
  return res;
232
274
  }
275
+ async function updateClientReleaseLocal(device, latestVersion, deps) {
276
+ const res = { device, updated: false, restarted: false, oldVersion: '?', newVersion: latestVersion };
277
+ try {
278
+ const localVer = deps.getInstalledVersion();
279
+ res.oldVersion = localVer || '?';
280
+ if (localVer === latestVersion) {
281
+ log.info(` ${device}: already at latest (${latestVersion})`);
282
+ return res;
283
+ }
284
+ // 1. Kill the running local client (frees the device name for reconnect)
285
+ await deps.kill();
286
+ // 2. npm update -g locally
287
+ const updateOutput = await deps.npmUpdate();
288
+ res.updated = true;
289
+ log.info(` ${device}: local npm update output: ${updateOutput.slice(0, 200)}`);
290
+ // 3. Respawn the local client on the new binary
291
+ res.restarted = await deps.restart();
292
+ }
293
+ catch (err) {
294
+ res.error = err.message;
295
+ log.warn(` ${device}: local release update failed — ${res.error}`);
296
+ }
297
+ return res;
298
+ }
233
299
  // --- Release mode: full per-device update ---
234
300
  async function updateClientRelease(device, reg, latestVersion) {
235
301
  const res = { device, updated: false, restarted: false, oldVersion: '?', newVersion: latestVersion };
236
302
  if (!reg.ssh) {
237
- res.error = 'Local client update not yet supported (use npm update -g @cortex-agent/client manually)';
238
- return res;
303
+ // Local same-machine client: update via local npm + process.kill + detached respawn.
304
+ return updateClientReleaseLocal(device, latestVersion, {
305
+ getInstalledVersion: getLocalInstalledVersion,
306
+ kill: () => killClientOnDevice(device, reg),
307
+ npmUpdate: npmUpdateLocal,
308
+ restart: () => restartClientOnDevice(device, reg),
309
+ });
239
310
  }
240
311
  try {
241
312
  // 1. Check remote installed version
@@ -371,4 +442,4 @@ function formatUpdateSlackMessage(result) {
371
442
  }
372
443
  return lines.join('\n');
373
444
  }
374
- export { checkAndUpdateClients, formatUpdateSlackMessage };
445
+ export { checkAndUpdateClients, formatUpdateSlackMessage, updateClientReleaseLocal };
@@ -39,7 +39,7 @@ type SshExec = (host: string, command: string, timeout?: number) => Promise<stri
39
39
  * Linux note: the shell handles PATH lookup; `nohup` detaches and `echo $!`
40
40
  * returns the child PID on stdout.
41
41
  */
42
- declare function buildRemoteSpawnCommand(reg: MachineEntry): string;
42
+ declare function buildRemoteSpawnCommand(reg: MachineEntry, clientToken?: string): string;
43
43
  declare function startRemoteClient(device: string): Promise<void>;
44
44
  /** Start clients on all registered devices */
45
45
  declare function startAllRemoteClients(): Promise<void>;
@@ -10,6 +10,7 @@ import * as path from 'path';
10
10
  import { execFile, spawn } from 'child_process';
11
11
  import { getMachineRegistry } from '../tasks/dispatch-utils.js';
12
12
  import { STORE_DIR } from '../../core/utils.js';
13
+ import { AUTH_HEADER, getClientToken, timingSafeEqualStr } from '../../core/auth.js';
13
14
  import { createLogger } from '../../core/log.js';
14
15
  import { readTasks, findTask } from '../tasks/system/task-lifecycle-edit.js';
15
16
  import { taskMutator } from '../tasks/mutator.js';
@@ -28,7 +29,24 @@ function startClientManager(port) {
28
29
  log.warn('Already running');
29
30
  return;
30
31
  }
31
- wss = new WebSocketServer({ port });
32
+ // Authenticate at the HTTP upgrade (before the WS is established): the client must send a
33
+ // valid bearer token in the `x-cortex-token` header. Fail-closed — an unset server token or
34
+ // a missing/mismatched header rejects the upgrade with 401. This is the no-Cloudflare gate.
35
+ wss = new WebSocketServer({
36
+ port,
37
+ verifyClient: (info, cb) => {
38
+ const provided = info.req.headers[AUTH_HEADER];
39
+ const headerVal = Array.isArray(provided) ? provided[0] : provided;
40
+ if (timingSafeEqualStr(getClientToken(), headerVal)) {
41
+ cb(true);
42
+ }
43
+ else {
44
+ const from = info.req.socket?.remoteAddress || 'unknown';
45
+ log.warn(`WS auth rejected from ${from}: ${headerVal ? 'invalid token' : 'missing token'}`);
46
+ cb(false, 401, 'Unauthorized');
47
+ }
48
+ },
49
+ });
32
50
  log.info(`WebSocket server started on port ${port}`);
33
51
  wss.on('connection', (ws) => {
34
52
  let deviceName = null;
@@ -271,11 +289,19 @@ let _getRegistryImpl = getMachineRegistry;
271
289
  * Linux note: the shell handles PATH lookup; `nohup` detaches and `echo $!`
272
290
  * returns the child PID on stdout.
273
291
  */
274
- function buildRemoteSpawnCommand(reg) {
292
+ function buildRemoteSpawnCommand(reg, clientToken) {
293
+ const token = clientToken?.trim();
275
294
  if (reg.win) {
276
- return `powershell -Command "(Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList 'cmd.exe /c cortex-client').ProcessId"`;
295
+ // Inject the token via `cmd.exe /c set ... && cortex-client` so the WMI-spawned process
296
+ // sees CORTEX_CLIENT_TOKEN. Tokens are hex (no shell metacharacters), so no escaping needed.
297
+ const inner = token
298
+ ? `cmd.exe /c set CORTEX_CLIENT_TOKEN=${token} && cortex-client`
299
+ : `cmd.exe /c cortex-client`;
300
+ return `powershell -Command "(Invoke-WmiMethod -Class Win32_Process -Name Create -ArgumentList '${inner}').ProcessId"`;
277
301
  }
278
- return `nohup cortex-client > /dev/null 2>&1 & echo $!`;
302
+ // Single-quote the token for the remote shell (hex value has no quotes to escape).
303
+ const envPrefix = token ? `CORTEX_CLIENT_TOKEN='${token}' ` : '';
304
+ return `${envPrefix}nohup cortex-client > /dev/null 2>&1 & echo $!`;
279
305
  }
280
306
  async function isRemotePidAlive(device) {
281
307
  const reg = _getRegistryImpl()[device];
@@ -340,7 +366,7 @@ async function startRemoteClient(device) {
340
366
  // restart, because scheduleRestart() is otherwise only triggered by disconnect or
341
367
  // heartbeat-timeout of an already-connected device.
342
368
  try {
343
- const pidStr = await _sshExecImpl(reg.ssh, buildRemoteSpawnCommand(reg), 30000);
369
+ const pidStr = await _sshExecImpl(reg.ssh, buildRemoteSpawnCommand(reg, getClientToken()), 30000);
344
370
  const pid = parseInt(pidStr);
345
371
  if (!isNaN(pid) && pid > 0) {
346
372
  clientPids.set(device, pid);
@@ -0,0 +1,32 @@
1
+ export interface ClientConnectEnv {
2
+ CORTEX_SERVER_URL?: string;
3
+ CORTEX_SERVER_HOST?: string;
4
+ CORTEX_SERVER_PORT?: string;
5
+ CF_ACCESS_CLIENT_ID?: string;
6
+ CF_ACCESS_CLIENT_SECRET?: string;
7
+ CORTEX_CLIENT_TOKEN?: string;
8
+ [key: string]: string | undefined;
9
+ }
10
+ /**
11
+ * Resolve the WebSocket URL the cortex-client dials.
12
+ *
13
+ * A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.fangxm.me``) takes
14
+ * precedence so the client can reach the agent-server through a Cloudflare
15
+ * Tunnel over 443/TLS. Otherwise it falls back to ``ws://<host>:<port>`` for
16
+ * direct/LAN reach.
17
+ */
18
+ export declare function resolveServerUrl(env: ClientConnectEnv): string;
19
+ /**
20
+ * Cloudflare Access service-token headers, returned only when both the client
21
+ * id and secret are configured. These let the cortex-client pass a Cloudflare
22
+ * Access policy placed in front of the tunnel (the agent-server WebSocket has
23
+ * no auth of its own, so Access is the gate when it is exposed publicly).
24
+ */
25
+ export declare function buildAccessHeaders(env: ClientConnectEnv): Record<string, string> | undefined;
26
+ /**
27
+ * Connection headers the cortex-client sends on the WebSocket upgrade. Combines the
28
+ * optional Cloudflare Access service-token headers with the Cortex bearer token
29
+ * (``x-cortex-token`` from ``CORTEX_CLIENT_TOKEN``) that the agent-server's WebSocket
30
+ * gate requires. Returns undefined when neither is configured.
31
+ */
32
+ export declare function buildAuthHeaders(env: ClientConnectEnv): Record<string, string> | undefined;