@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,362 @@
1
+ // input: injected DoctorDeps (env, paths, fs probes, gateway probe) + FixActuators
2
+ // output: runDiagnostics(deps) → DoctorReport; applySafeFixes(report, deps, fix) → FixOutcome[]
3
+ // createDefaultDoctorDeps / createDefaultFixActuators — real-environment wiring
4
+ // pos: Pure diagnostic engine for `cortex doctor`. Health-checks the whole install
5
+ // (runtime, backend/login, messaging platform, gateway). No side effects in the
6
+ // diagnostic path; all writes go through injected FixActuators (--fix only).
7
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
8
+ import * as fs from 'node:fs';
9
+ import * as os from 'node:os';
10
+ import * as path from 'node:path';
11
+ import * as http from 'node:http';
12
+ import { parse as parseDotenvLib } from 'dotenv';
13
+ import { DATA_DIR, CONFIG_DIR, STORE_DIR, GATEWAY_MANAGED_KEY_PLACEHOLDER } from '../../core/utils.js';
14
+ import { ensureAuthTokens, CLIENT_TOKEN_ENV, WEBHOOK_TOKEN_ENV } from '../../core/auth.js';
15
+ import { generateMcpConfig } from '../../core/config-generator.js';
16
+ // ─── Helpers ──────────────────────────────────────────────────────
17
+ const GW_HOST = '127.0.0.1';
18
+ const GW_PORT = 9880;
19
+ function normalize(v) {
20
+ if (typeof v !== 'string')
21
+ return undefined;
22
+ const t = v.trim();
23
+ if (!t || t === 'null' || t === 'undefined')
24
+ return undefined;
25
+ return t;
26
+ }
27
+ function nodeMajor(version) {
28
+ const m = version.match(/^v?(\d+)/);
29
+ return m ? Number(m[1]) : 0;
30
+ }
31
+ /** Merge process env over the .env file, normalizing blanks/null/undefined away. */
32
+ function buildEnvReader(deps) {
33
+ const envPath = path.join(deps.paths.CONFIG_DIR, '.env');
34
+ let fileEnv = {};
35
+ const text = deps.readText(envPath);
36
+ if (text != null) {
37
+ try {
38
+ fileEnv = deps.parseDotenv(text);
39
+ }
40
+ catch {
41
+ fileEnv = {};
42
+ }
43
+ }
44
+ return (name) => normalize(deps.env[name] ?? fileEnv[name]);
45
+ }
46
+ // ─── Section: Runtime & Process ───────────────────────────────────
47
+ function sectionRuntime(deps) {
48
+ const checks = [];
49
+ const major = nodeMajor(deps.nodeVersion);
50
+ checks.push(major >= deps.requiredNodeMajor
51
+ ? { id: 'node-version', label: 'Node version', status: 'pass', detail: `${deps.nodeVersion} (>=${deps.requiredNodeMajor})` }
52
+ : { id: 'node-version', label: 'Node version', status: 'warn', detail: `${deps.nodeVersion} — Cortex requires Node >=${deps.requiredNodeMajor}`, hint: 'Upgrade Node.js' });
53
+ checks.push(deps.commandExists('git')
54
+ ? { id: 'git', label: 'git', status: 'pass', detail: 'found on PATH' }
55
+ : { id: 'git', label: 'git', status: 'fail', detail: 'not found on PATH', hint: 'Install git — required for context sync' });
56
+ // Backend binary, per mode.json backend selection.
57
+ const modeText = deps.readText(path.join(deps.paths.STORE_DIR, 'mode.json'));
58
+ let backend = 'claude';
59
+ try {
60
+ if (modeText) {
61
+ const m = JSON.parse(modeText);
62
+ if (typeof m.backend === 'string')
63
+ backend = m.backend;
64
+ }
65
+ }
66
+ catch { /* fall back to claude */ }
67
+ const bin = backend === 'pi' ? 'pi' : backend === 'codex' ? 'codex' : 'claude';
68
+ checks.push(deps.commandExists(bin)
69
+ ? { id: 'backend-binary', label: 'Backend binary', status: 'pass', detail: `${bin} found on PATH (backend: ${backend})` }
70
+ : { id: 'backend-binary', label: 'Backend binary', status: 'warn', detail: `${bin} not on PATH (backend: ${backend})`, hint: `Install/login the ${bin} CLI` });
71
+ // Daemon — informational only.
72
+ const pidPath = path.join(deps.paths.STORE_DIR, 'daemon.pid');
73
+ const pidText = deps.fileExists(pidPath) ? deps.readText(pidPath) : null;
74
+ const pid = pidText ? Number(pidText.trim()) : NaN;
75
+ if (Number.isFinite(pid) && deps.pidAlive(pid)) {
76
+ checks.push({ id: 'daemon', label: 'Daemon', status: 'pass', detail: `running (pid ${pid})` });
77
+ }
78
+ else {
79
+ checks.push({ id: 'daemon', label: 'Daemon', status: 'skip', detail: 'not running', hint: 'Start with `cortex daemon`' });
80
+ }
81
+ return { title: 'Runtime & Process', checks };
82
+ }
83
+ // ─── Section: Backend Install / Login ─────────────────────────────
84
+ function sectionBackend(deps, getEnv) {
85
+ const checks = [];
86
+ const { DATA_DIR: data, CONFIG_DIR: config, STORE_DIR: store } = deps.paths;
87
+ // Directories exist + writable.
88
+ const dirProblems = [];
89
+ for (const [name, p] of [['DATA_DIR', data], ['CONFIG_DIR', config], ['STORE_DIR', store]]) {
90
+ if (!deps.fileExists(p))
91
+ dirProblems.push(`${name} missing (${p})`);
92
+ else if (!deps.isWritable(p))
93
+ dirProblems.push(`${name} not writable (${p})`);
94
+ }
95
+ checks.push(dirProblems.length === 0
96
+ ? { id: 'dirs', label: 'Data directories', status: 'pass', detail: 'present and writable' }
97
+ : { id: 'dirs', label: 'Data directories', status: 'fail', detail: dirProblems.join('; '), hint: 'run `cortex doctor --fix` or `cortex init`', fixable: true });
98
+ // .env file.
99
+ const envPath = path.join(config, '.env');
100
+ checks.push(deps.fileExists(envPath)
101
+ ? { id: 'env-file', label: '.env file', status: 'pass', detail: envPath }
102
+ : { id: 'env-file', label: '.env file', status: 'fail', detail: `missing (${envPath})`, hint: 'run `cortex init`' });
103
+ // Auth tokens.
104
+ const missingTokens = [CLIENT_TOKEN_ENV, WEBHOOK_TOKEN_ENV].filter(n => !getEnv(n));
105
+ checks.push(missingTokens.length === 0
106
+ ? { id: 'auth-tokens', label: 'Auth tokens', status: 'pass', detail: 'client + webhook tokens set' }
107
+ : { id: 'auth-tokens', label: 'Auth tokens', status: 'fail', detail: `missing: ${missingTokens.join(', ')}`, hint: 'run `cortex doctor --fix` to generate', fixable: true });
108
+ // Anthropic API key — warn (plan/subscription mode does not need it).
109
+ const apiKey = getEnv('ANTHROPIC_API_KEY');
110
+ if (apiKey === GATEWAY_MANAGED_KEY_PLACEHOLDER) {
111
+ checks.push({ id: 'anthropic-key', label: 'Anthropic API key', status: 'pass', detail: 'managed by gateway' });
112
+ }
113
+ else if (apiKey) {
114
+ checks.push({ id: 'anthropic-key', label: 'Anthropic API key', status: 'pass', detail: 'set' });
115
+ }
116
+ else {
117
+ checks.push({ id: 'anthropic-key', label: 'Anthropic API key', status: 'warn', detail: 'not set — required for API mode (plan/subscription mode can ignore)', hint: 'set ANTHROPIC_API_KEY in .env or run `cortex init`' });
118
+ }
119
+ // mode.json
120
+ pushJsonCheck(checks, deps, path.join(store, 'mode.json'), 'mode-json', 'mode.json', 'warn');
121
+ // profiles.json (schema-lite)
122
+ checks.push(checkProfiles(deps, path.join(config, 'profiles.json')));
123
+ // mcp-config.json
124
+ const mcpPath = path.join(config, 'mcp-config.json');
125
+ if (!deps.fileExists(mcpPath)) {
126
+ checks.push({ id: 'mcp-config', label: 'mcp-config.json', status: 'warn', detail: `missing (${mcpPath})`, hint: 'run `cortex doctor --fix` to regenerate', fixable: true });
127
+ }
128
+ else if (!isValidJson(deps.readText(mcpPath))) {
129
+ checks.push({ id: 'mcp-config', label: 'mcp-config.json', status: 'warn', detail: 'invalid JSON', hint: 'run `cortex doctor --fix` to regenerate', fixable: true });
130
+ }
131
+ else {
132
+ checks.push({ id: 'mcp-config', label: 'mcp-config.json', status: 'pass', detail: 'valid' });
133
+ }
134
+ return { title: 'Backend Install / Login', checks };
135
+ }
136
+ function isValidJson(text) {
137
+ if (text == null)
138
+ return false;
139
+ try {
140
+ JSON.parse(text);
141
+ return true;
142
+ }
143
+ catch {
144
+ return false;
145
+ }
146
+ }
147
+ function pushJsonCheck(checks, deps, p, id, label, missingStatus) {
148
+ if (!deps.fileExists(p)) {
149
+ checks.push({ id, label, status: missingStatus, detail: `missing (${p})` });
150
+ return;
151
+ }
152
+ checks.push(isValidJson(deps.readText(p))
153
+ ? { id, label, status: 'pass', detail: 'valid' }
154
+ : { id, label, status: missingStatus, detail: 'invalid JSON' });
155
+ }
156
+ function checkProfiles(deps, p) {
157
+ if (!deps.fileExists(p)) {
158
+ return { id: 'profiles', label: 'profiles.json', status: 'warn', detail: `missing (${p})`, hint: 'run `cortex setup-gateway`' };
159
+ }
160
+ const text = deps.readText(p);
161
+ let parsed;
162
+ try {
163
+ parsed = JSON.parse(text ?? '');
164
+ }
165
+ catch {
166
+ return { id: 'profiles', label: 'profiles.json', status: 'fail', detail: 'invalid JSON', hint: 're-run `cortex setup-gateway`' };
167
+ }
168
+ if (!parsed || typeof parsed !== 'object' || typeof parsed.profiles !== 'object' || parsed.profiles == null) {
169
+ return { id: 'profiles', label: 'profiles.json', status: 'fail', detail: 'missing `profiles` object' };
170
+ }
171
+ if (parsed.defaultProfile && !(parsed.defaultProfile in parsed.profiles)) {
172
+ return { id: 'profiles', label: 'profiles.json', status: 'fail', detail: `defaultProfile "${parsed.defaultProfile}" not found in profiles` };
173
+ }
174
+ const names = Object.keys(parsed.profiles).join(', ');
175
+ return { id: 'profiles', label: 'profiles.json', status: 'pass', detail: `profiles: ${names || '(none)'}` };
176
+ }
177
+ // ─── Section: Messaging Platform ──────────────────────────────────
178
+ function sectionPlatform(deps, getEnv) {
179
+ const checks = [];
180
+ const raw = getEnv('CORTEX_PLATFORM') ?? 'slack';
181
+ const names = raw.split(',').map(s => s.trim().toLowerCase()).filter(Boolean);
182
+ checks.push({ id: 'platform', label: 'Platform', status: 'pass', detail: `configured: ${names.join(', ') || '(none)'}` });
183
+ for (const name of names) {
184
+ if (name === 'slack') {
185
+ const problems = [];
186
+ const bot = getEnv('SLACK_BOT_TOKEN');
187
+ const sign = getEnv('SLACK_SIGNING_SECRET');
188
+ const app = getEnv('SLACK_APP_TOKEN');
189
+ if (!bot)
190
+ problems.push('SLACK_BOT_TOKEN missing');
191
+ else if (!bot.startsWith('xoxb-'))
192
+ problems.push('SLACK_BOT_TOKEN should start with xoxb-');
193
+ if (!sign)
194
+ problems.push('SLACK_SIGNING_SECRET missing');
195
+ if (!app)
196
+ problems.push('SLACK_APP_TOKEN missing');
197
+ else if (!app.startsWith('xapp-'))
198
+ problems.push('SLACK_APP_TOKEN should start with xapp-');
199
+ checks.push(problems.length === 0
200
+ ? { id: 'slack-creds', label: 'Slack credentials', status: 'pass', detail: 'bot / signing / app tokens present' }
201
+ : { id: 'slack-creds', label: 'Slack credentials', status: 'fail', detail: problems.join('; '), hint: 'set Slack tokens in .env (see `cortex init`)' });
202
+ }
203
+ else if (name === 'feishu') {
204
+ const problems = [];
205
+ if (!getEnv('FEISHU_APP_ID'))
206
+ problems.push('FEISHU_APP_ID missing');
207
+ if (!getEnv('FEISHU_APP_SECRET'))
208
+ problems.push('FEISHU_APP_SECRET missing');
209
+ checks.push(problems.length === 0
210
+ ? { id: 'feishu-creds', label: 'Feishu credentials', status: 'pass', detail: 'app id / secret present' }
211
+ : { id: 'feishu-creds', label: 'Feishu credentials', status: 'fail', detail: problems.join('; '), hint: 'set FEISHU_APP_ID / FEISHU_APP_SECRET in .env' });
212
+ }
213
+ else if (name === 'test') {
214
+ checks.push({ id: 'test-platform', label: 'Test platform', status: 'skip', detail: 'mock adapter (test only)' });
215
+ }
216
+ else {
217
+ checks.push({ id: `platform-${name}`, label: `Platform: ${name}`, status: 'warn', detail: 'unknown platform name' });
218
+ }
219
+ }
220
+ return { title: 'Messaging Platform', checks };
221
+ }
222
+ // ─── Section: Gateway ─────────────────────────────────────────────
223
+ async function sectionGateway(deps, getEnv) {
224
+ const checks = [];
225
+ const gwYaml = path.join(deps.homeDir, '.aistatus', 'gateway.yaml');
226
+ const gwConfigured = deps.fileExists(gwYaml);
227
+ checks.push(gwConfigured
228
+ ? { id: 'gateway-config', label: 'Gateway config', status: 'pass', detail: gwYaml }
229
+ : { id: 'gateway-config', label: 'Gateway config', status: 'skip', detail: 'not configured (no ~/.aistatus/gateway.yaml)', hint: 'run `cortex setup-gateway` if you use the gateway' });
230
+ const healthy = await deps.probeGateway();
231
+ const gatewayInUse = getEnv('ANTHROPIC_API_KEY') === GATEWAY_MANAGED_KEY_PLACEHOLDER || gwConfigured;
232
+ if (healthy) {
233
+ checks.push({ id: 'gateway-health', label: 'Gateway health', status: 'pass', detail: `responding at ${GW_HOST}:${GW_PORT}` });
234
+ }
235
+ else if (gatewayInUse) {
236
+ checks.push({ id: 'gateway-health', label: 'Gateway health', status: 'fail', detail: `no response at ${GW_HOST}:${GW_PORT}/status`, hint: 'check gateway.log or restart Cortex (the server auto-starts the gateway)' });
237
+ }
238
+ else {
239
+ checks.push({ id: 'gateway-health', label: 'Gateway health', status: 'skip', detail: 'not running (not required for current backend)' });
240
+ }
241
+ return { title: 'Gateway', checks };
242
+ }
243
+ // ─── Engine ───────────────────────────────────────────────────────
244
+ export async function runDiagnostics(deps) {
245
+ const getEnv = buildEnvReader(deps);
246
+ const sections = [
247
+ sectionRuntime(deps),
248
+ sectionBackend(deps, getEnv),
249
+ sectionPlatform(deps, getEnv),
250
+ await sectionGateway(deps, getEnv),
251
+ ];
252
+ const counts = { pass: 0, warn: 0, fail: 0, skip: 0 };
253
+ for (const s of sections)
254
+ for (const c of s.checks)
255
+ counts[c.status]++;
256
+ return { sections, counts, ok: counts.fail === 0 };
257
+ }
258
+ // ─── Safe fixes ───────────────────────────────────────────────────
259
+ export async function applySafeFixes(report, deps, fix) {
260
+ const fixable = new Map();
261
+ for (const s of report.sections)
262
+ for (const c of s.checks) {
263
+ if (c.fixable && (c.status === 'fail' || c.status === 'warn'))
264
+ fixable.set(c.id, c);
265
+ }
266
+ const outcomes = [];
267
+ const envPath = path.join(deps.paths.CONFIG_DIR, '.env');
268
+ if (fixable.has('dirs')) {
269
+ for (const p of [deps.paths.DATA_DIR, deps.paths.CONFIG_DIR, deps.paths.STORE_DIR])
270
+ fix.mkdirp(p);
271
+ outcomes.push({ id: 'dirs', label: 'Data directories', applied: true, detail: 'created missing directories' });
272
+ }
273
+ if (fixable.has('auth-tokens')) {
274
+ fix.ensureEnvFile(envPath);
275
+ const generated = fix.ensureAuthTokens(envPath);
276
+ outcomes.push({ id: 'auth-tokens', label: 'Auth tokens', applied: generated.length > 0, detail: generated.length > 0 ? `generated: ${generated.join(', ')}` : 'already present' });
277
+ }
278
+ if (fixable.has('mcp-config')) {
279
+ fix.regenerateMcpConfig();
280
+ outcomes.push({ id: 'mcp-config', label: 'mcp-config.json', applied: true, detail: 'regenerated' });
281
+ }
282
+ return outcomes;
283
+ }
284
+ // ─── Default real-environment wiring ──────────────────────────────
285
+ function commandExistsOnPath(bin) {
286
+ const pathVar = process.env.PATH || '';
287
+ const exts = process.platform === 'win32' ? (process.env.PATHEXT || '.EXE;.CMD;.BAT').split(';') : [''];
288
+ for (const dir of pathVar.split(path.delimiter)) {
289
+ if (!dir)
290
+ continue;
291
+ for (const ext of exts) {
292
+ const candidate = path.join(dir, bin + ext);
293
+ try {
294
+ if (fs.existsSync(candidate))
295
+ return true;
296
+ }
297
+ catch { /* ignore */ }
298
+ }
299
+ }
300
+ return false;
301
+ }
302
+ function probeGatewayHttp() {
303
+ return new Promise((resolve) => {
304
+ const req = http.get(`http://${GW_HOST}:${GW_PORT}/status`, { timeout: 5000 }, (res) => {
305
+ res.resume();
306
+ resolve(res.statusCode === 200);
307
+ });
308
+ req.on('error', () => resolve(false));
309
+ req.on('timeout', () => { req.destroy(); resolve(false); });
310
+ });
311
+ }
312
+ export function createDefaultDoctorDeps() {
313
+ return {
314
+ env: process.env,
315
+ paths: { DATA_DIR, CONFIG_DIR, STORE_DIR },
316
+ homeDir: os.homedir(),
317
+ nodeVersion: process.version,
318
+ requiredNodeMajor: 20,
319
+ fileExists: (p) => { try {
320
+ return fs.existsSync(p);
321
+ }
322
+ catch {
323
+ return false;
324
+ } },
325
+ isWritable: (p) => { try {
326
+ fs.accessSync(p, fs.constants.W_OK);
327
+ return true;
328
+ }
329
+ catch {
330
+ return false;
331
+ } },
332
+ readText: (p) => { try {
333
+ return fs.readFileSync(p, 'utf8');
334
+ }
335
+ catch {
336
+ return null;
337
+ } },
338
+ parseDotenv: (t) => parseDotenvLib(t),
339
+ commandExists: commandExistsOnPath,
340
+ pidAlive: (pid) => { try {
341
+ process.kill(pid, 0);
342
+ return true;
343
+ }
344
+ catch {
345
+ return false;
346
+ } },
347
+ probeGateway: probeGatewayHttp,
348
+ };
349
+ }
350
+ export function createDefaultFixActuators() {
351
+ return {
352
+ mkdirp: (p) => { fs.mkdirSync(p, { recursive: true }); },
353
+ ensureEnvFile: (envPath) => {
354
+ if (!fs.existsSync(envPath)) {
355
+ fs.mkdirSync(path.dirname(envPath), { recursive: true });
356
+ fs.writeFileSync(envPath, '');
357
+ }
358
+ },
359
+ ensureAuthTokens: (envPath) => ensureAuthTokens({ envPath }).generated,
360
+ regenerateMcpConfig: () => generateMcpConfig(),
361
+ };
362
+ }
@@ -267,6 +267,14 @@ function buildDispatchPrompt(task) {
267
267
  ' thread_abort(kind="too-big", diagnosis="<one-line diagnosis of what the real structure is>")',
268
268
  '',
269
269
  'The task will be blocked with your diagnosis and escalated: its manager (or a human) re-plans the decomposition with full context. A precise diagnosis is the most valuable thing you can produce here — it beats a half-done grind every time. (Use kind="too-big" or "mis-scoped" for structural problems, "blocked-external" for a missing external resource.) If instead you can already see the right decomposition, call `thread_split` with the subtasks.',
270
+ '',
271
+ '## If The Planning Intent Is Unclear (ask_manager)',
272
+ '',
273
+ 'If during execution you hit confusion, a contradiction, or an ambiguous/under-specified intent — and you cannot settle it by reading the deliverable, code, or task spec yourself — do NOT guess and do NOT abort. Ask the manager who planned this task:',
274
+ '',
275
+ ' ask_manager(question="<a specific, self-contained question about the planning intent>")',
276
+ '',
277
+ 'This is lighter than thread_abort: it does not give up the task. The call blocks until the manager (or, at the top of the tree, a human) replies, then returns their answer so you can continue. Use it for genuine planning questions ("did you mean approach A or B?", "two done_when conditions conflict — which wins?"), not for things you can verify yourself.',
270
278
  ];
271
279
  sections.push(escalation.join('\n'));
272
280
  const completion = [
@@ -22,9 +22,11 @@ import { isMainModule } from '../../../core/utils.js';
22
22
  // the daemon process, so we proxy sendCommand/isDeviceOnline through HTTP.
23
23
  const WEBHOOK_PORT = parseInt(process.env.WEBHOOK_PORT || '3001', 10);
24
24
  const WEBHOOK_BASE = `http://127.0.0.1:${WEBHOOK_PORT}`;
25
+ // Bearer token for the webhook auth gate. Inherited from the daemon/dispatcher env (see core/auth.ts).
26
+ const webhookAuthHeader = () => ({ 'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '' });
25
27
  async function httpIsDeviceOnline(device) {
26
28
  try {
27
- const res = await fetch(`${WEBHOOK_BASE}/webhook/devices`);
29
+ const res = await fetch(`${WEBHOOK_BASE}/webhook/devices`, { headers: webhookAuthHeader() });
28
30
  if (!res.ok)
29
31
  return false;
30
32
  const data = (await res.json());
@@ -49,7 +51,7 @@ async function httpSendCommand(device, command) {
49
51
  try {
50
52
  const res = await fetch(`${WEBHOOK_BASE}/webhook/remote-command`, {
51
53
  method: 'POST',
52
- headers: { 'Content-Type': 'application/json' },
54
+ headers: { 'Content-Type': 'application/json', ...webhookAuthHeader() },
53
55
  body: JSON.stringify({
54
56
  device,
55
57
  action: command.action,
@@ -9,14 +9,14 @@ import { lintTasks } from '../lint.js';
9
9
  import { loadConfig, listTemplateNames } from '../../threads/template-loader.js';
10
10
  import { editTask } from './task-lifecycle-edit.js';
11
11
  import { assignIds, validateIds } from './task-id-utils.js';
12
- import { approveTask, blockTask, claimTask, clearApprovalTask, pauseTask, pendingTask, requestApprovalTask, resumeTask, unblockTask, unclaimTask, } from './task-state.js';
12
+ import { approveTask, blockTask, claimTask, clearApprovalTask, pauseTask, pendingTask, reopenTask, requestApprovalTask, resumeTask, unblockTask, unclaimTask, } from './task-state.js';
13
13
  import { completeTask, uncompleteTask } from './task-completion.js';
14
14
  import { addTask, batchEdit, bulkAddTasks, decomposeTask } from './task-mutations.js';
15
15
  import { stopTask, stopTaskDryRun } from './task-process.js';
16
16
  import { acquireLock, assertLockHeld, getOwnerIdentity, readLock, releaseLock, } from './task-lock.js';
17
17
  const READ_COMMANDS = new Set(['list', 'all', 'query', 'show', 'deps', 'lint', 'stats', 'tree']);
18
18
  const WRITE_COMMANDS = new Set([
19
- 'claim', 'unclaim', 'pause', 'resume', 'pending', 'complete', 'uncomplete',
19
+ 'claim', 'unclaim', 'pause', 'resume', 'pending', 'reopen', 'complete', 'uncomplete',
20
20
  'request-approval', 'approve', 'clear-approval',
21
21
  'block', 'unblock',
22
22
  'add', 'spawn', 'edit', 'batch-edit', 'bulk-add', 'decompose',
@@ -25,14 +25,14 @@ const WRITE_COMMANDS = new Set([
25
25
  ]);
26
26
  const ALL_COMMANDS = new Set([...READ_COMMANDS, ...WRITE_COMMANDS]);
27
27
  const COMMANDS_NEEDING_TASK = new Set([
28
- 'claim', 'unclaim', 'pause', 'resume', 'pending', 'complete', 'uncomplete',
28
+ 'claim', 'unclaim', 'pause', 'resume', 'pending', 'reopen', 'complete', 'uncomplete',
29
29
  'request-approval', 'approve', 'clear-approval',
30
30
  'block', 'unblock',
31
31
  'edit', 'decompose',
32
32
  ]);
33
33
  const COMMANDS_NEEDING_REASON = new Set(['block']);
34
34
  const COMMANDS_NEEDING_PROJECT = new Set([
35
- 'claim', 'unclaim', 'pause', 'resume', 'pending', 'complete', 'uncomplete',
35
+ 'claim', 'unclaim', 'pause', 'resume', 'pending', 'reopen', 'complete', 'uncomplete',
36
36
  'request-approval', 'approve', 'clear-approval',
37
37
  'block', 'unblock',
38
38
  'add', 'spawn', 'edit', 'batch-edit', 'bulk-add', 'decompose',
@@ -55,6 +55,7 @@ const COMMAND_FLAG_ALLOWLIST = {
55
55
  pause: new Set([...COMMON_FLAGS, '--task']),
56
56
  resume: new Set([...COMMON_FLAGS, '--task']),
57
57
  pending: new Set([...COMMON_FLAGS, '--task']),
58
+ reopen: new Set([...COMMON_FLAGS, '--task']),
58
59
  complete: new Set([...COMMON_FLAGS, '--task', '--note', '--skip-verify', '--skip-verify-reason']),
59
60
  uncomplete: new Set([...COMMON_FLAGS, '--task']),
60
61
  'request-approval': new Set([...COMMON_FLAGS, '--task']),
@@ -105,6 +106,7 @@ const HELP_CONFIG = {
105
106
  { name: 'pause', description: 'Pause' },
106
107
  { name: 'resume', description: 'Resume a paused task' },
107
108
  { name: 'pending', description: 'Mark pending (waiting for cortex-run)' },
109
+ { name: 'reopen', description: 'Restore a stuck pending task back to open (e.g. after a lost cortex-run callback)' },
108
110
  { name: 'complete', description: 'Mark complete (--note)' },
109
111
  { name: 'uncomplete', description: 'Reverse a completed task' },
110
112
  ],
@@ -774,6 +776,7 @@ const WRITE_HANDLERS = {
774
776
  pause: (v) => pauseTask(v.task, v.project, v.taskId),
775
777
  resume: (v) => resumeTask(v.task, v.project, v.taskId),
776
778
  pending: (v) => pendingTask(v.task, v.project, v.taskId),
779
+ reopen: (v) => reopenTask(v.task, v.project, v.taskId),
777
780
  complete: (v) => completeTask(v.task, v.project, v.note, v.taskId, v.skipVerify, v.skipVerifyReason),
778
781
  uncomplete: (v) => uncompleteTask(v.task, v.project, v.taskId),
779
782
  'request-approval': (v) => requestApprovalTask(v.task, v.project, v.taskId),
@@ -67,4 +67,13 @@ declare function unblockTask(taskText: string | null, project: string, taskId?:
67
67
  message: string;
68
68
  task_id: string;
69
69
  };
70
- export { approveTask, blockTask, claimTask, clearApprovalTask, pauseTask, pendingTask, requestApprovalTask, resumeTask, unblockTask, unclaimTask, };
70
+ declare function reopenTask(taskText: string | null, project: string, taskId?: string | null): {
71
+ success: boolean;
72
+ message: string;
73
+ task_id?: undefined;
74
+ } | {
75
+ success: boolean;
76
+ message: string;
77
+ task_id: string;
78
+ };
79
+ export { approveTask, blockTask, claimTask, clearApprovalTask, pauseTask, pendingTask, reopenTask, requestApprovalTask, resumeTask, unblockTask, unclaimTask, };
@@ -135,6 +135,12 @@ function blockTask(taskText, project, reason, taskId = null) {
135
135
  task.claimed_at = null;
136
136
  task.pending_at = null;
137
137
  task.blocked_by = reason;
138
+ // Normalize a 'pending' (mid cortex-run) task back to 'open'. `status === 'pending'`
139
+ // is an independent dispatch-exclusion gate (task-parser isActionable), so leaving it
140
+ // here would make the task invisible to the dispatcher even after it is unblocked.
141
+ // blocked_by still gates dispatch, so this is safe. Never resurrect a done task.
142
+ if (task.status !== 'done')
143
+ task.status = 'open';
138
144
  writeTasks(project, tasks);
139
145
  return { success: true, message: `Task blocked: ${reason}`, task_id: task.id };
140
146
  }
@@ -170,7 +176,31 @@ function unblockTask(taskText, project, taskId = null) {
170
176
  return { success: false, message: found.error };
171
177
  const task = found.task;
172
178
  task.blocked_by = null;
179
+ // Defensively restore legacy stuck tasks (status=pending + blocked_by, produced before
180
+ // blockTask normalized status) so they become dispatchable again on unblock.
181
+ if (task.status === 'pending') {
182
+ task.status = 'open';
183
+ task.pending_at = null;
184
+ }
173
185
  writeTasks(project, tasks);
174
186
  return { success: true, message: 'Task unblocked', task_id: task.id };
175
187
  }
176
- export { approveTask, blockTask, claimTask, clearApprovalTask, pauseTask, pendingTask, requestApprovalTask, resumeTask, unblockTask, unclaimTask, };
188
+ function reopenTask(taskText, project, taskId = null) {
189
+ const tasks = readTasks(project);
190
+ if (tasks.length === 0 && !fs.existsSync(getTasksPath(project))) {
191
+ return { success: false, message: `TASKS.yaml not found for project ${project}` };
192
+ }
193
+ const found = findTask(tasks, taskText, taskId);
194
+ if ('error' in found)
195
+ return { success: false, message: found.error };
196
+ const task = found.task;
197
+ if (task.status === 'done')
198
+ return { success: false, message: 'Cannot reopen a completed task — use uncomplete' };
199
+ if (task.status !== 'pending')
200
+ return { success: true, message: 'Task is already open (idempotent)', task_id: task.id };
201
+ task.status = 'open';
202
+ task.pending_at = null;
203
+ writeTasks(project, tasks);
204
+ return { success: true, message: 'Task reopened', task_id: task.id };
205
+ }
206
+ export { approveTask, blockTask, claimTask, clearApprovalTask, pauseTask, pendingTask, reopenTask, requestApprovalTask, resumeTask, unblockTask, unclaimTask, };
@@ -37,9 +37,12 @@ export declare function buildStepPrompt(threadId: string, agentConfig: AgentSlot
37
37
  * Fidelity with the legacy default-thread path (templateName='default', isUserInitiated=true):
38
38
  * - applies the default agent's promptTemplate (typically `{{input}}`) with empty thread vars;
39
39
  * - prepends the agent directive (resolved for {{systemVar}});
40
- * - prepends user context ONLY under the same gate the default thread used —
41
- * loadUserContext({templateName:'default'}) returns null unless CORTEX_INJECT_USER_CONTEXT=1
42
- * AND the template is a direct-* template, so 'default' yields null today (behavior preserved);
40
+ * - prepends the user profile (loadUserContext) — plain conversation is the ONLY path that
41
+ * injects USER.md; it is on by default unless CORTEX_DISABLE_USER_CONTEXT=1. Thread steps
42
+ * (buildStepPrompt) never inject it. The caller gates it via opts.includeUserContext so the
43
+ * profile is sent only on a session's FIRST turn (session resume keeps it in history thereafter);
43
44
  * - NEVER injects THREAD_PROTOCOL_PREAMBLE (no artifact, no [ABORT] protocol for conversations).
44
45
  */
45
- export declare function buildConversationPrompt(agentConfig: AgentSlotConfig, input: string): string;
46
+ export declare function buildConversationPrompt(agentConfig: AgentSlotConfig, input: string, opts?: {
47
+ includeUserContext?: boolean;
48
+ }): string;
@@ -172,9 +172,8 @@ export function buildStepPrompt(threadId, agentConfig, stage = null) {
172
172
  }
173
173
  if (!resumingPersistentSession) {
174
174
  const prefixes = [];
175
- const userCtx = loadUserContext(thread);
176
- if (userCtx)
177
- prefixes.push(userCtx);
175
+ // Thread steps never carry the user profile — only thread-free conversation turns do
176
+ // (see buildConversationPrompt). This keeps multi-agent pipelines profile-agnostic.
178
177
  if (agentConfig.directive)
179
178
  prefixes.push(resolveSystemVars(agentConfig.directive));
180
179
  if (thread.artifactPath)
@@ -210,12 +209,14 @@ export function buildStepPrompt(threadId, agentConfig, stage = null) {
210
209
  * Fidelity with the legacy default-thread path (templateName='default', isUserInitiated=true):
211
210
  * - applies the default agent's promptTemplate (typically `{{input}}`) with empty thread vars;
212
211
  * - prepends the agent directive (resolved for {{systemVar}});
213
- * - prepends user context ONLY under the same gate the default thread used —
214
- * loadUserContext({templateName:'default'}) returns null unless CORTEX_INJECT_USER_CONTEXT=1
215
- * AND the template is a direct-* template, so 'default' yields null today (behavior preserved);
212
+ * - prepends the user profile (loadUserContext) — plain conversation is the ONLY path that
213
+ * injects USER.md; it is on by default unless CORTEX_DISABLE_USER_CONTEXT=1. Thread steps
214
+ * (buildStepPrompt) never inject it. The caller gates it via opts.includeUserContext so the
215
+ * profile is sent only on a session's FIRST turn (session resume keeps it in history thereafter);
216
216
  * - NEVER injects THREAD_PROTOCOL_PREAMBLE (no artifact, no [ABORT] protocol for conversations).
217
217
  */
218
- export function buildConversationPrompt(agentConfig, input) {
218
+ export function buildConversationPrompt(agentConfig, input, opts = {}) {
219
+ const { includeUserContext = true } = opts;
219
220
  const { template: templateStr } = pickStepTemplate(agentConfig, null);
220
221
  const vars = {
221
222
  input,
@@ -227,7 +228,7 @@ export function buildConversationPrompt(agentConfig, input) {
227
228
  };
228
229
  let prompt = applyPromptTemplate(templateStr, vars);
229
230
  const prefixes = [];
230
- const userCtx = loadUserContext({ templateName: 'default' });
231
+ const userCtx = includeUserContext ? loadUserContext() : null;
231
232
  if (userCtx)
232
233
  prefixes.push(userCtx);
233
234
  if (agentConfig.directive)
@@ -22,6 +22,9 @@ interface ThreadContext {
22
22
  stream: OutputStream;
23
23
  lastAgentResult: any;
24
24
  totalNumTurns: number;
25
+ /** Set when a step was interrupted by an API rate limit while the throttle is active.
26
+ * Pauses the thread (status='rate_limited') instead of completing/failing it. */
27
+ rateLimited?: boolean;
25
28
  }
26
29
  /** Per-step config built once by buildStepConfig — fully populated, no placeholders. */
27
30
  interface StepContext {
@@ -78,6 +81,10 @@ declare function finalizeThread(threadId: string, ctx: ThreadContext): Promise<T
78
81
  export declare function finalizeAbortedThread(threadId: string, meta: ThreadRecord['metadata'], reason: string | null, opts: Pick<RunThreadOptions, 'onAbort'>): Promise<void>;
79
82
  declare function runThread(threadId: string, opts: RunThreadOptions): Promise<ThreadRunResult>;
80
83
  declare function continueThread(threadId: string, userMessage: string, opts: RunThreadOptions): Promise<ThreadRunResult>;
84
+ /** Re-enter a thread paused by an API rate limit (status==='rate_limited'). Like resumeThread,
85
+ * the userMessage is NOT overwritten — the thread re-runs its interrupted step from the original
86
+ * prompt/contract. Called by resume-dispatcher when the rate-limit window resets. */
87
+ declare function resumeRateLimitedThread(threadId: string, opts: RunThreadOptions): Promise<ThreadRunResult>;
81
88
  /** Re-enter a parent thread that was suspended via [WAIT_CHILDREN]. Unlike continueThread,
82
89
  * the userMessage is NOT overwritten — the original contract stays in {{input}}; the child
83
90
  * results arrive through metadata.pendingMessages (injected by the prompt builder). */
@@ -85,5 +92,5 @@ declare function resumeThread(threadId: string, opts: RunThreadOptions): Promise
85
92
  declare function buildThreadSummary(result: ThreadRunResult): string;
86
93
  declare function cancelActiveThread(channel: string): boolean;
87
94
  declare function getActiveHandle(channel: string): RunningExecution | null;
88
- export { runThread, continueThread, resumeThread, buildThreadSummary, cancelActiveThread, getActiveHandle, initThreadContext, resolveAndNotifyStep, buildStepConfig, setupStepCallbacks, executeAndAwaitAgent, recordStepOutcome, evaluateAndTransition, finalizeThread, };
95
+ export { runThread, continueThread, resumeThread, resumeRateLimitedThread, buildThreadSummary, cancelActiveThread, getActiveHandle, initThreadContext, resolveAndNotifyStep, buildStepConfig, setupStepCallbacks, executeAndAwaitAgent, recordStepOutcome, evaluateAndTransition, finalizeThread, };
89
96
  export type { ThreadRunResult, ThreadContext, StepContext, StepCallbacks, StepInfo };