@cortex-agent/server 2026.6.18-2 → 2026.6.22

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 (82) hide show
  1. package/defaults/CORTEX.md +5 -0
  2. package/defaults/hooks/ask-user-question-hook.mjs +6 -1
  3. package/defaults/hooks/exit-plan-mode-hook.mjs +6 -1
  4. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +7 -0
  5. package/defaults/prompts/systemPrompts/coder.md +6 -1
  6. package/defaults/prompts/systemPrompts/direct.md +5 -0
  7. package/defaults/prompts/systemPrompts/web-opus-4-6.md +6 -1
  8. package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +6 -1
  9. package/defaults/prompts/systemPrompts/web.md +6 -1
  10. package/defaults/prompts/systemPrompts/worker.md +6 -1
  11. package/dist/agent-adapter/claude/adapter.d.ts +110 -1
  12. package/dist/agent-adapter/claude/adapter.js +117 -0
  13. package/dist/agent-adapter/claude/bg-task-tracker.d.ts +37 -0
  14. package/dist/agent-adapter/claude/bg-task-tracker.js +78 -0
  15. package/dist/agent-adapter/normalize/event-types.d.ts +4 -0
  16. package/dist/agent-adapter/pi/event-parser.d.ts +3 -1
  17. package/dist/agent-adapter/pi/event-parser.js +12 -2
  18. package/dist/agent-adapter/types.d.ts +19 -0
  19. package/dist/core/auth.d.ts +36 -0
  20. package/dist/core/auth.js +85 -0
  21. package/dist/core/locales/en.d.ts +6 -0
  22. package/dist/core/locales/slices/status.d.ts +6 -0
  23. package/dist/core/locales/slices/status.js +16 -0
  24. package/dist/core/types/agent-types.d.ts +5 -0
  25. package/dist/core/types/thread-types.d.ts +12 -1
  26. package/dist/core/version.d.ts +3 -0
  27. package/dist/core/version.js +4 -1
  28. package/dist/domain/agents/facade.js +12 -0
  29. package/dist/domain/costs/rate-limit-throttle.d.ts +1 -1
  30. package/dist/domain/costs/rate-limit-throttle.js +23 -2
  31. package/dist/domain/costs/resume-registry.d.ts +30 -0
  32. package/dist/domain/costs/resume-registry.js +68 -0
  33. package/dist/domain/mcp/core-server.js +5 -0
  34. package/dist/domain/mcp/tools/manager-qa.d.ts +2 -0
  35. package/dist/domain/mcp/tools/manager-qa.js +72 -0
  36. package/dist/domain/mcp/tools/task-ops.js +4 -2
  37. package/dist/domain/mcp/tools/thread-ops.js +2 -1
  38. package/dist/domain/mcp/tui-server.js +2 -1
  39. package/dist/domain/remote/client-bootstrap.js +14 -2
  40. package/dist/domain/remote/client-manager.d.ts +1 -1
  41. package/dist/domain/remote/client-manager.js +31 -5
  42. package/dist/domain/remote/cortex-client-config.d.ts +32 -0
  43. package/dist/domain/remote/cortex-client-config.js +49 -0
  44. package/dist/domain/remote/cortex-client.js +11 -7
  45. package/dist/domain/scheduling/jobs/scheduled-task.js +17 -1
  46. package/dist/domain/scheduling/jobs/task-dispatch.js +21 -0
  47. package/dist/domain/tasks/dispatcher.js +8 -0
  48. package/dist/domain/tasks/system/cortex-run.js +4 -2
  49. package/dist/domain/threads/runner.d.ts +8 -1
  50. package/dist/domain/threads/runner.js +81 -11
  51. package/dist/domain/threads/state-machine.d.ts +5 -0
  52. package/dist/domain/threads/state-machine.js +16 -0
  53. package/dist/entry/app.js +19 -4
  54. package/dist/entry/init.js +6 -0
  55. package/dist/hooks/ask-user-question-hook.mjs +6 -1
  56. package/dist/hooks/exit-plan-mode-hook.mjs +6 -1
  57. package/dist/orchestration/agent-runner.js +28 -3
  58. package/dist/orchestration/bg-continuation.d.ts +26 -0
  59. package/dist/orchestration/bg-continuation.js +34 -0
  60. package/dist/orchestration/conversation-runner.d.ts +3 -0
  61. package/dist/orchestration/conversation-runner.js +1 -1
  62. package/dist/orchestration/interactions/interaction-handlers.js +13 -2
  63. package/dist/orchestration/lifecycle.d.ts +3 -1
  64. package/dist/orchestration/lifecycle.js +72 -2
  65. package/dist/orchestration/manager-qa.d.ts +55 -0
  66. package/dist/orchestration/manager-qa.js +218 -0
  67. package/dist/orchestration/resume-dispatcher.d.ts +22 -0
  68. package/dist/orchestration/resume-dispatcher.js +129 -0
  69. package/dist/orchestration/routing/webhook.d.ts +1 -1
  70. package/dist/orchestration/routing/webhook.js +75 -14
  71. package/dist/orchestration/status-helpers.d.ts +3 -0
  72. package/dist/orchestration/status-helpers.js +16 -0
  73. package/dist/orchestration/thread-callback.d.ts +13 -1
  74. package/dist/orchestration/thread-callback.js +18 -1
  75. package/dist/orchestration/turn-notify.d.ts +26 -0
  76. package/dist/orchestration/turn-notify.js +66 -0
  77. package/dist/store/schedule-repo.d.ts +6 -0
  78. package/dist/store/schedule-repo.js +11 -1
  79. package/dist/store/thread-repo.js +14 -0
  80. package/dist/store/version-migrations.d.ts +14 -4
  81. package/dist/store/version-migrations.js +67 -9
  82. package/package.json +1 -1
@@ -0,0 +1,218 @@
1
+ // input: webhook /webhook/manager-qa (ask/poll/answer), agent-runner human-reply interception
2
+ // output: askManager / submitAnswer / getAnswer / tryAnswerFromHuman / buildQuestionNotice
3
+ // pos: DR-0016 up-ask channel — a subtask asks its manager (or, at the top, a human) a clarifying
4
+ // question and blocks (synchronously, via the ask_manager MCP tool's poll loop) until
5
+ // answered. A suspended manager is woken to answer (resumeManagerForQuestion) and re-suspends
6
+ // via pendingControl='wait' after answer_subtask. Central question state is an in-memory Map
7
+ // in the daemon (synchronous model: a daemon restart fails the in-flight ask, consistent with
8
+ // running threads failing on restart — no persistence in v1).
9
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
10
+ import { threadStore } from '../store/thread-repo.js';
11
+ import { scanAllTasks } from '../core/task-parser.js';
12
+ import { isTerminalStatus } from '../domain/threads/tree.js';
13
+ import { resumeManagerForQuestion } from './thread-callback.js';
14
+ import { ctx as jobCtx } from '../domain/scheduling/job-registry.js';
15
+ import { getOutboundQueue, durablePost } from '../store/outbound-queue.js';
16
+ import { createLogger } from '../core/log.js';
17
+ const log = createLogger('manager-qa');
18
+ /** Central in-memory question store (daemon process). questionId → question. */
19
+ const questions = new Map();
20
+ /** channel → questionId, for routing a human's free-text reply back to the right pending ask. */
21
+ const channelIndex = new Map();
22
+ /** Test hook: clear all in-memory Q&A state. */
23
+ export function _testResetManagerQa() {
24
+ questions.clear();
25
+ channelIndex.clear();
26
+ }
27
+ function defaultReadTask(project, taskId) {
28
+ try {
29
+ const t = scanAllTasks(project ?? undefined).find((x) => x.id === taskId);
30
+ return t ? { parent: t.parent ?? null, origin_channel: t.origin_channel ?? null } : null;
31
+ }
32
+ catch {
33
+ return null;
34
+ }
35
+ }
36
+ async function defaultPostToChannel(channel, text) {
37
+ const adapter = jobCtx.adapter;
38
+ if (!adapter) {
39
+ log.error(`no adapter; cannot escalate question to ${channel}`);
40
+ return;
41
+ }
42
+ const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
43
+ const queue = getOutboundQueue();
44
+ if (queue)
45
+ await durablePost(queue, adapter, dest, { text });
46
+ else
47
+ await adapter.postMessage(dest, { text });
48
+ }
49
+ /** Notice injected into the manager's pendingMessages (and, lightly adapted, posted to a human).
50
+ * Mirrors buildChildResultNotice's shape: states what is asked and how to respond. */
51
+ export function buildQuestionNotice(q) {
52
+ const from = q.fromTaskId ? `子任务 #${q.fromTaskId}` : '一个子任务';
53
+ return [
54
+ `[子任务提问] ${from} 在执行中遇到不清楚/矛盾之处,向你(manager)确认规划意图:`,
55
+ '',
56
+ `问题: ${q.question}`,
57
+ '',
58
+ '请用 answer_subtask 工具回答(回答后你会自动回到等待子任务的状态):',
59
+ ` answer_subtask(question_id="${q.questionId}", answer="<你的答复>")`,
60
+ '若你自己也不确定(属于更上层的规划意图),可调用 ask_manager 向你的上级继续提问,拿到答复后再回答这个子任务。',
61
+ ].join('\n');
62
+ }
63
+ function buildHumanEscalationNotice(q) {
64
+ const from = q.fromTaskId ? `子任务 #${q.fromTaskId}` : '一个子任务';
65
+ return [
66
+ `${'❓'} [子任务提问 — 已升级到你] ${from} 在执行中遇到不清楚/矛盾之处,没有上级 manager,转而向你确认:`,
67
+ '',
68
+ `问题: ${q.question}`,
69
+ '',
70
+ '直接在本频道回复即可——你的下一条消息会作为答复返回给该子任务。',
71
+ ].join('\n');
72
+ }
73
+ /** Resolve the manager thread to ask: prefer an explicit thread parent; otherwise walk the task
74
+ * tree (child task.parent → the live thread that owns that manager task). Returns null when no
75
+ * live manager exists (→ human escalation). */
76
+ function resolveManagerThread(thread, deps) {
77
+ const ptid = thread.metadata?.parentThreadId;
78
+ if (ptid) {
79
+ const p = threadStore.get(ptid);
80
+ if (p && !isTerminalStatus(p.status))
81
+ return ptid;
82
+ }
83
+ const taskId = thread.metadata?.taskId;
84
+ if (!taskId)
85
+ return null;
86
+ const project = thread.metadata?.taskProject ?? null;
87
+ const childTask = (deps.readTask ?? defaultReadTask)(project, taskId);
88
+ const managerTaskId = childTask?.parent ?? null;
89
+ if (!managerTaskId)
90
+ return null;
91
+ const mgr = threadStore.getAll().find((t) => t.metadata?.taskId === managerTaskId && !isTerminalStatus(t.status));
92
+ return mgr?.id ?? null;
93
+ }
94
+ /** Walk up the task tree from the asking thread's task to the nearest ancestor that carries an
95
+ * origin_channel — the human who set the work in motion. Used only when no manager thread exists. */
96
+ function findEscalationChannel(thread, deps) {
97
+ const read = deps.readTask ?? defaultReadTask;
98
+ const project = thread.metadata?.taskProject ?? null;
99
+ let taskId = thread.metadata?.taskId ?? null;
100
+ let hops = 0;
101
+ while (taskId && hops < 16) {
102
+ const t = read(project, taskId);
103
+ if (!t)
104
+ break;
105
+ if (t.origin_channel)
106
+ return t.origin_channel;
107
+ taskId = t.parent;
108
+ hops++;
109
+ }
110
+ // No human conduit captured anywhere up the tree → nothing to escalate to. We deliberately do
111
+ // NOT fall back to thread.channel: a dispatch thread's channel is often an unattended
112
+ // project-report conduit, and silently posting a question there would block the subtask on an
113
+ // answer that never comes.
114
+ return null;
115
+ }
116
+ async function deliverToManager(managerThreadId, q, deps) {
117
+ await threadStore.mutate(managerThreadId, (t) => {
118
+ const m = (t.metadata ??= {});
119
+ if (!Array.isArray(m.pendingMessages))
120
+ m.pendingMessages = [];
121
+ if (m.pendingMessages.length >= 10)
122
+ m.pendingMessages.shift();
123
+ m.pendingMessages.push(buildQuestionNotice(q));
124
+ if (!Array.isArray(m.pendingQuestions))
125
+ m.pendingQuestions = [];
126
+ m.pendingQuestions.push({ questionId: q.questionId, fromTaskId: q.fromTaskId, question: q.question });
127
+ });
128
+ // Only a suspended manager needs waking; a running one will see the question in its own loop.
129
+ const mgr = threadStore.get(managerThreadId);
130
+ if (mgr?.status === 'waiting')
131
+ (deps.resume ?? resumeManagerForQuestion)(managerThreadId);
132
+ }
133
+ function newQuestionId() {
134
+ return `q_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
135
+ }
136
+ /** Register a subtask's question and route it: to its manager (woken to answer), or — at the top of
137
+ * the tree — to a human via the origin channel. Returns a questionId the caller polls via getAnswer. */
138
+ export async function askManager(threadId, question, deps = {}) {
139
+ const thread = threadStore.get(threadId);
140
+ if (!thread)
141
+ return { ok: false, error: 'calling thread not found (CORTEX_THREAD_ID stale?)' };
142
+ const q = (question ?? '').trim();
143
+ if (!q)
144
+ return { ok: false, error: 'question must not be empty' };
145
+ const managerThreadId = resolveManagerThread(thread, deps);
146
+ const questionId = newQuestionId();
147
+ if (managerThreadId) {
148
+ const rec = {
149
+ questionId, fromThreadId: threadId, fromTaskId: thread.metadata?.taskId ?? null,
150
+ managerThreadId, channel: null, awaitingHuman: false, question: q, answer: null, createdAt: Date.now(),
151
+ };
152
+ questions.set(questionId, rec);
153
+ await deliverToManager(managerThreadId, rec, deps);
154
+ log.info(`ask_manager: ${threadId} → manager ${managerThreadId} (${questionId})`);
155
+ return { ok: true, questionId, target: 'manager', managerThreadId };
156
+ }
157
+ const channel = findEscalationChannel(thread, deps);
158
+ if (!channel) {
159
+ return { ok: false, error: 'no manager and no origin channel to escalate to — use your best judgment, record the assumption, or call thread_abort with a diagnosis' };
160
+ }
161
+ const rec = {
162
+ questionId, fromThreadId: threadId, fromTaskId: thread.metadata?.taskId ?? null,
163
+ managerThreadId: null, channel, awaitingHuman: true, question: q, answer: null, createdAt: Date.now(),
164
+ };
165
+ questions.set(questionId, rec);
166
+ channelIndex.set(channel, questionId);
167
+ await (deps.postToChannel ?? defaultPostToChannel)(channel, buildHumanEscalationNotice(rec));
168
+ log.info(`ask_manager: ${threadId} → human escalation on ${channel} (${questionId})`);
169
+ return { ok: true, questionId, target: 'human', channel };
170
+ }
171
+ /** Manager answers a subtask question. Records the answer and forces the manager back to waiting
172
+ * (pendingControl='wait') so it re-suspends on its still-live children at the next step boundary. */
173
+ export async function submitAnswer(questionId, answer) {
174
+ const rec = questions.get(questionId);
175
+ if (!rec)
176
+ return { ok: false, error: `unknown question ${questionId} (expired, already consumed, or lost on restart)` };
177
+ rec.answer = answer ?? '';
178
+ if (rec.managerThreadId) {
179
+ await threadStore.mutate(rec.managerThreadId, (t) => {
180
+ const m = (t.metadata ??= {});
181
+ if (Array.isArray(m.pendingQuestions))
182
+ m.pendingQuestions = m.pendingQuestions.filter((x) => x.questionId !== questionId);
183
+ // Re-suspend after answering — unless a control intent is already queued (don't clobber it).
184
+ if (!m.pendingControl)
185
+ m.pendingControl = { action: 'wait' };
186
+ });
187
+ }
188
+ log.info(`answer_subtask: ${questionId} answered`);
189
+ return { ok: true };
190
+ }
191
+ /** Poll for an answer. Consumes the entry once an answer is present (one-shot read by the poller). */
192
+ export function getAnswer(questionId) {
193
+ const rec = questions.get(questionId);
194
+ if (!rec)
195
+ return { found: false, answered: false, answer: null };
196
+ if (rec.answer !== null) {
197
+ questions.delete(questionId);
198
+ if (rec.channel)
199
+ channelIndex.delete(rec.channel);
200
+ return { found: true, answered: true, answer: rec.answer };
201
+ }
202
+ return { found: true, answered: false, answer: null };
203
+ }
204
+ /** Interactive hook: if `channel` has a pending human-escalated question, consume this message as
205
+ * its answer and return true (the caller should then short-circuit normal turn handling). */
206
+ export function tryAnswerFromHuman(channel, text) {
207
+ const qid = channelIndex.get(channel);
208
+ if (!qid)
209
+ return false;
210
+ const rec = questions.get(qid);
211
+ if (!rec || !rec.awaitingHuman) {
212
+ channelIndex.delete(channel);
213
+ return false;
214
+ }
215
+ rec.answer = text ?? '';
216
+ log.info(`ask_manager: human answered ${qid} on ${channel}`);
217
+ return true;
218
+ }
@@ -0,0 +1,22 @@
1
+ import type { PlatformAdapter } from '../platform/index.js';
2
+ import type { ThreadRecord, RunThreadOptions } from '../core/types/thread-types.js';
3
+ import { type ResumeEntry } from '../domain/costs/resume-registry.js';
4
+ import { agentRunner } from './agent-runner.js';
5
+ /** Auto-resume is on by default; disable with CORTEX_AUTO_RESUME=0 (or "false"). */
6
+ export declare function isAutoResumeEnabled(): boolean;
7
+ /** The continuation prompt injected into a resumed session/thread. Self-contained — the
8
+ * prior turn's content is already in the resumed session/thread history. */
9
+ export declare function buildResumeReminder(): string;
10
+ export interface ResumeDeps {
11
+ takeAll: () => ResumeEntry[];
12
+ route: (ctx: Parameters<typeof agentRunner.route>[0]) => Promise<void>;
13
+ resumeThread: (threadId: string, opts: RunThreadOptions) => Promise<unknown>;
14
+ buildResumeOptions: (thread: ThreadRecord) => RunThreadOptions | null;
15
+ getThread: (threadId: string) => ThreadRecord | null;
16
+ channelBusy: (channel: string) => boolean;
17
+ now: () => number;
18
+ delay: (ms: number) => Promise<void>;
19
+ }
20
+ /** Drain the resume registry and re-enter each interrupted target. Called by the
21
+ * rate-limit-throttle onResume hook when the window resets. Never throws. */
22
+ export declare function dispatchPendingResumes(adapter: PlatformAdapter, overrides?: Partial<ResumeDeps>): Promise<void>;
@@ -0,0 +1,129 @@
1
+ // input: rate-limit-throttle onResume → resume-registry (takeAllResumes) + agentRunner / resumeRateLimitedThread
2
+ // output: dispatchPendingResumes — wakes sessions/threads interrupted by a rate limit
3
+ // pos: orch/ — runs when the rate-limit window resets. Direct sessions are re-entered with a
4
+ // <system-reminder>; threads (status 'rate_limited') are re-run from the interrupted step
5
+ // via resumeRateLimitedThread with options rebuilt by buildResumeOptions (dispatch onEnd
6
+ // hook + destination). All deps injectable for tests.
7
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
8
+ import { takeAllResumes } from '../domain/costs/resume-registry.js';
9
+ import { agentRunner } from './agent-runner.js';
10
+ import { resumeRateLimitedThread } from '../domain/threads/runner.js';
11
+ import { buildResumeOptions } from './thread-callback.js';
12
+ import { threadStore } from '../store/thread-repo.js';
13
+ import { runningExecutions } from '../core/running-executions.js';
14
+ import { createLogger } from '../core/log.js';
15
+ const log = createLogger('resume-dispatcher');
16
+ /** Entries older than this are considered obsolete (user moved on / thread finished).
17
+ * 6h = the 5-hour window plus restart slack. */
18
+ const MAX_RESUME_AGE_MS = 6 * 60 * 60 * 1000;
19
+ /** Gap between consecutive resumes so we don't instantly re-trip the limit. */
20
+ const RESUME_STAGGER_MS = 3_000;
21
+ /** Auto-resume is on by default; disable with CORTEX_AUTO_RESUME=0 (or "false"). */
22
+ export function isAutoResumeEnabled() {
23
+ const v = process.env.CORTEX_AUTO_RESUME;
24
+ return v !== '0' && v !== 'false';
25
+ }
26
+ /** The continuation prompt injected into a resumed session/thread. Self-contained — the
27
+ * prior turn's content is already in the resumed session/thread history. */
28
+ export function buildResumeReminder() {
29
+ return [
30
+ '<system-reminder>',
31
+ '上一轮因命中 API 限流(五小时窗口)被中断。该窗口现已重置,你可以继续。',
32
+ '请从中断处接着做:回顾上方最近的对话上下文,判断还有什么没完成并完成它。',
33
+ '不要从头重启任务、也不要重复询问用户已提供的信息。若上一轮其实已经完成,简短确认后停止。',
34
+ '本条消息仅为恢复信号,不应改变你原本的任务。',
35
+ '</system-reminder>',
36
+ ].join('\n');
37
+ }
38
+ function defaultDeps() {
39
+ return {
40
+ takeAll: takeAllResumes,
41
+ route: (ctx) => agentRunner.route(ctx),
42
+ resumeThread: (id, opts) => resumeRateLimitedThread(id, opts),
43
+ buildResumeOptions: (thread) => buildResumeOptions(thread),
44
+ getThread: (id) => threadStore.get(id),
45
+ channelBusy: (ch) => runningExecutions.hasChannel(ch),
46
+ now: () => Date.now(),
47
+ delay: (ms) => new Promise((r) => setTimeout(r, ms)),
48
+ };
49
+ }
50
+ function entryKey(e) {
51
+ return e.kind === 'thread' ? `thread ${e.threadId}` : `direct ${e.channel}`;
52
+ }
53
+ /** Drain the resume registry and re-enter each interrupted target. Called by the
54
+ * rate-limit-throttle onResume hook when the window resets. Never throws. */
55
+ export async function dispatchPendingResumes(adapter, overrides = {}) {
56
+ const deps = { ...defaultDeps(), ...overrides };
57
+ if (!isAutoResumeEnabled()) {
58
+ const drained = deps.takeAll(); // drain so stale entries don't pile up across windows
59
+ if (drained.length > 0)
60
+ log.info(`Auto-resume disabled — dropped ${drained.length} pending entry(ies)`);
61
+ return;
62
+ }
63
+ const entries = deps.takeAll();
64
+ if (entries.length === 0)
65
+ return;
66
+ log.info(`Rate-limit window reset — resuming ${entries.length} interrupted target(s)`);
67
+ let dispatched = 0;
68
+ for (const entry of entries) {
69
+ const skip = guardSkipReason(entry, deps);
70
+ if (skip) {
71
+ log.info(`Resume skip (${entryKey(entry)}): ${skip}`);
72
+ continue;
73
+ }
74
+ try {
75
+ if (dispatched > 0)
76
+ await deps.delay(RESUME_STAGGER_MS); // stagger between actual dispatches
77
+ if (entry.kind === 'direct')
78
+ await resumeDirect(entry, adapter, deps);
79
+ else
80
+ await resumeThread(entry, deps.getThread(entry.threadId), adapter, deps);
81
+ dispatched++;
82
+ }
83
+ catch (e) {
84
+ log.error(`Resume failed (${entryKey(entry)}): ${e.message}`);
85
+ }
86
+ }
87
+ log.info(`Resume complete — dispatched ${dispatched}/${entries.length}`);
88
+ }
89
+ /** Returns a human reason to skip, or null to proceed. */
90
+ function guardSkipReason(entry, deps) {
91
+ if (deps.now() - entry.recordedAt > MAX_RESUME_AGE_MS)
92
+ return 'stale';
93
+ if (deps.channelBusy(entry.channel))
94
+ return 'channel already has a running execution';
95
+ if (entry.kind === 'thread') {
96
+ const thread = deps.getThread(entry.threadId);
97
+ if (!thread)
98
+ return 'thread no longer exists';
99
+ if (thread.status !== 'rate_limited')
100
+ return `thread is ${thread.status}`;
101
+ }
102
+ return null;
103
+ }
104
+ async function resumeDirect(entry, adapter, deps) {
105
+ const notice = buildResumeReminder();
106
+ const message = {
107
+ ref: { conduit: entry.channel, messageId: `resume_${Date.now()}` },
108
+ text: notice,
109
+ senderId: 'cortex-rate-limit-resume',
110
+ isBot: false,
111
+ kind: 'user',
112
+ raw: { source: 'rate-limit-resume', originalMessage: entry.userMessage },
113
+ };
114
+ log.info(`Resuming direct session on ${entry.channel}`);
115
+ await deps.route({ message, channel: entry.channel, adapter, threadAnchorId: null, hasFiles: false, userMessage: notice, agentMessage: notice });
116
+ }
117
+ async function resumeThread(entry, thread, _adapter, deps) {
118
+ // Rebuild RunThreadOptions (destination + dispatch task-status-check onEnd hook) from the
119
+ // thread's persisted metadata — same machinery DR-0014 uses to re-enter suspended parents.
120
+ // Unlike a direct session, a thread re-runs its interrupted step from the original prompt, so
121
+ // no <system-reminder> / userMessage overwrite is injected.
122
+ const opts = deps.buildResumeOptions(thread);
123
+ if (!opts) {
124
+ log.error(`Resume skip (thread ${entry.threadId}): could not rebuild run options (no adapter?)`);
125
+ return;
126
+ }
127
+ log.info(`Resuming thread ${entry.threadId} on ${entry.channel}`);
128
+ await deps.resumeThread(entry.threadId, opts);
129
+ }
@@ -1,5 +1,5 @@
1
1
  import * as http from 'http';
2
- declare function createWebhookHandler({ secret, }?: {
2
+ declare function createWebhookHandler(_options?: {
3
3
  secret?: string;
4
4
  }): (req: any, res: any) => void;
5
5
  declare function startWebhookServer(options?: {
@@ -1,8 +1,9 @@
1
- // input: GitHub push, task-op, thread-op, remote cmd, hook HTTP events
1
+ // input: GitHub push, task-op, thread-op, manager-qa, remote cmd, hook HTTP events
2
2
  // output: startWebhookServer
3
- // pos: GitHub/task-op/thread-op/hook webhook HTTP entry point
3
+ // pos: GitHub/task-op/thread-op/manager-qa/hook webhook HTTP entry point
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { createLogger } from '../../core/log.js';
6
+ import { AUTH_HEADER, getWebhookToken, timingSafeEqualStr } from '../../core/auth.js';
6
7
  import * as http from 'http';
7
8
  import * as crypto from 'crypto';
8
9
  import { readFileSync } from 'fs';
@@ -18,6 +19,7 @@ import { Icons } from '../../core/icons.js';
18
19
  import { buildStatusActionBlocks, buildSealedStatusActionBlocks, initStatusBlocks } from '../status-helpers.js';
19
20
  import { threadStore } from '../../store/thread-repo.js';
20
21
  import { fireThreadCallback } from '../thread-callback.js';
22
+ import { askManager, getAnswer, submitAnswer } from '../manager-qa.js';
21
23
  const log = createLogger('webhook');
22
24
  const PORT = parseInt(process.env.WEBHOOK_PORT || '3001', 10);
23
25
  // Read at call time, not import time — dotenv.config() in app.ts runs AFTER ESM imports
@@ -36,12 +38,16 @@ function verifySignature(body, signature) {
36
38
  return false;
37
39
  }
38
40
  }
39
- function hasValidSecret(secret, providedSecret) {
40
- const secretBuf = Buffer.from(secret || '');
41
- const providedBuf = Buffer.from(providedSecret || '');
42
- return !(secretBuf.length === 0
43
- || providedBuf.length !== secretBuf.length
44
- || !crypto.timingSafeEqual(providedBuf, secretBuf));
41
+ /**
42
+ * Bearer-token gate for every webhook route EXCEPT /webhook/github (which authenticates
43
+ * via its own HMAC signature). Reads the call-time CORTEX_WEBHOOK_TOKEN and compares it
44
+ * timing-safely against the `x-cortex-token` request header. Fail-closed: an unset token
45
+ * or a missing/mismatched header is rejected.
46
+ */
47
+ function isWebhookAuthorized(req) {
48
+ const provided = (req.headers || {})[AUTH_HEADER];
49
+ const headerVal = Array.isArray(provided) ? provided[0] : provided;
50
+ return timingSafeEqualStr(getWebhookToken(), headerVal);
45
51
  }
46
52
  function readJsonBody(req, callback) {
47
53
  let body = '';
@@ -67,8 +73,16 @@ const TASK_OP_HANDLERS = {
67
73
  pause: (data) => taskMutator.pause(data.task_id),
68
74
  resume: (data) => taskMutator.resume(data.task_id),
69
75
  };
70
- function createWebhookHandler({ secret = getSecret(), } = {}) {
76
+ function createWebhookHandler(_options = {}) {
71
77
  return (req, res) => {
78
+ // --- Auth gate: every route requires the webhook bearer token, except /webhook/github
79
+ // which authenticates via its own HMAC signature (GitHub cannot send our header). ---
80
+ if (req.url !== '/webhook/github' && !isWebhookAuthorized(req)) {
81
+ log.warn(`webhook auth rejected: ${req.method} ${req.url}`);
82
+ res.writeHead(401);
83
+ res.end('Unauthorized');
84
+ return;
85
+ }
72
86
  // --- Device list query (from MCP sidecar) ---
73
87
  if (req.method === 'GET' && req.url === '/webhook/devices') {
74
88
  const devices = getOnlineDevices().map(d => d.device);
@@ -116,11 +130,7 @@ function createWebhookHandler({ secret = getSecret(), } = {}) {
116
130
  res.end('Bad JSON');
117
131
  return;
118
132
  }
119
- if (!hasValidSecret(secret, data.secret)) {
120
- res.writeHead(401);
121
- res.end('Unauthorized');
122
- return;
123
- }
133
+ // Auth handled by the global token gate above (was: body-secret check).
124
134
  const handler = TASK_OP_HANDLERS[data.op];
125
135
  if (!handler) {
126
136
  res.writeHead(400);
@@ -401,6 +411,57 @@ function createWebhookHandler({ secret = getSecret(), } = {}) {
401
411
  });
402
412
  return;
403
413
  }
414
+ // --- Manager Q&A (DR-0016 up-ask channel, from cortex-core MCP sidecar) ---
415
+ // ask: a subtask registers a clarifying question → routed to its manager (woken) or a human.
416
+ // poll: the ask_manager tool polls this until the answer is present (synchronous block).
417
+ // answer: the manager's answer_subtask tool (or a human reply) records the answer.
418
+ if (req.method === 'POST' && req.url === '/webhook/manager-qa') {
419
+ readJsonBody(req, async (error, _body, data) => {
420
+ if (error) {
421
+ res.writeHead(400);
422
+ res.end('Bad JSON');
423
+ return;
424
+ }
425
+ const reply = (obj) => {
426
+ res.writeHead(200, { 'Content-Type': 'application/json' });
427
+ res.end(JSON.stringify(obj));
428
+ };
429
+ try {
430
+ const action = data.action;
431
+ if (action === 'ask') {
432
+ if (!data.threadId || !data.question) {
433
+ return reply({ success: false, error: 'ask requires threadId and question' });
434
+ }
435
+ const result = await askManager(String(data.threadId), String(data.question));
436
+ if (result.ok === false)
437
+ return reply({ success: false, error: result.error });
438
+ const { ok: _ok, ...payload } = result;
439
+ return reply({ success: true, data: payload });
440
+ }
441
+ if (action === 'poll') {
442
+ if (!data.questionId)
443
+ return reply({ success: false, error: 'poll requires questionId' });
444
+ const r = getAnswer(String(data.questionId));
445
+ return reply({ success: true, data: { answered: r.answered, answer: r.answer } });
446
+ }
447
+ if (action === 'answer') {
448
+ const questionId = data.question_id ?? data.questionId;
449
+ if (!questionId)
450
+ return reply({ success: false, error: 'answer requires question_id' });
451
+ const r = await submitAnswer(String(questionId), String(data.answer ?? ''));
452
+ if (!r.ok)
453
+ return reply({ success: false, error: r.error });
454
+ return reply({ success: true, data: { answered: true } });
455
+ }
456
+ return reply({ success: false, error: `unknown action: ${action}` });
457
+ }
458
+ catch (e) {
459
+ log.error(`manager-qa error: ${e.message}`);
460
+ reply({ success: false, error: e.message });
461
+ }
462
+ });
463
+ return;
464
+ }
404
465
  // --- PreToolUse hook: AskUserQuestion ---
405
466
  if (req.method === 'POST' && req.url === '/hook/ask-user-question') {
406
467
  readJsonBody(req, async (error, _body, data) => {
@@ -2,6 +2,9 @@ import type { Destination, PlatformAdapter, MessageRef, IncomingAttachment, Rich
2
2
  import type { AgentResult } from '../core/types/agent-types.js';
3
3
  import type { ExecutionRecord } from '../domain/executions/registry.js';
4
4
  export { computeElapsed, formatMetricsSuffix, buildSessionTag, buildUserProcessingMessage } from '../core/status-format.js';
5
+ /** Feature gate: the "New (quiet)" status button (=!newq, skips the pre-close hook)
6
+ * is OFF by default. Opt in with CORTEX_STATUS_NEWQ_BUTTON = 1/true/on/yes. */
7
+ export declare function isStatusNewqButtonEnabled(): boolean;
5
8
  export declare function resolveExecutionProject({ execution, fallbackMessage }: {
6
9
  execution: ExecutionRecord | null;
7
10
  fallbackMessage: string;
@@ -14,6 +14,14 @@ import { durableUpdate } from './durable-helpers.js';
14
14
  // Pure formatters live in core/ so the domain layer can consume them without an orch dep.
15
15
  export { computeElapsed, formatMetricsSuffix, buildSessionTag, buildUserProcessingMessage } from '../core/status-format.js';
16
16
  const log = createLogger('status-helpers');
17
+ /** Feature gate: the "New (quiet)" status button (=!newq, skips the pre-close hook)
18
+ * is OFF by default. Opt in with CORTEX_STATUS_NEWQ_BUTTON = 1/true/on/yes. */
19
+ export function isStatusNewqButtonEnabled() {
20
+ const v = process.env.CORTEX_STATUS_NEWQ_BUTTON;
21
+ if (v === undefined)
22
+ return false;
23
+ return ['1', 'true', 'on', 'yes'].includes(v.trim().toLowerCase());
24
+ }
17
25
  export function resolveExecutionProject({ execution, fallbackMessage }) {
18
26
  return execution?.project || (projectStore.resolveFromMessage(fallbackMessage || '')?.id ?? 'general');
19
27
  }
@@ -136,6 +144,14 @@ function buildActionElements({ channel, sessionName, isDm, includeCancel, thread
136
144
  value: channel,
137
145
  });
138
146
  }
147
+ if (isDm && isStatusNewqButtonEnabled()) {
148
+ elements.push({
149
+ type: 'button',
150
+ text: t('btn.newq'),
151
+ actionId: 'status_newq',
152
+ value: channel,
153
+ });
154
+ }
139
155
  return elements;
140
156
  }
141
157
  /** Build richBlocks for the initial "Processing" message (Cancel button included). */
@@ -1,5 +1,5 @@
1
1
  import { type Task } from '../core/task-parser.js';
2
- import type { ThreadRecord } from '../core/types/thread-types.js';
2
+ import type { ThreadRecord, RunThreadOptions } from '../core/types/thread-types.js';
3
3
  import type { PlatformAdapter } from '../platform/index.js';
4
4
  /** Test hook: clear in-memory dedup state to simulate a server restart. */
5
5
  export declare function _testResetCallbackState(): void;
@@ -7,12 +7,24 @@ export declare function _testResetCallbackState(): void;
7
7
  * delegation contract and demands acceptance verification before the result is trusted
8
8
  * (DR-0014 L1 纠偏: verify the deliverable, never the child's self-report). */
9
9
  export declare function buildChildResultNotice(child: ThreadRecord): string;
10
+ /** Rebuild RunThreadOptions for re-entering a suspended parent. extraHooks are not
11
+ * persisted on ThreadRecord, so the dispatch task-status-check hook is reconstructed
12
+ * from metadata.taskId/taskProject (the reason dispatch threads must store them). */
13
+ export declare function buildResumeOptions(parent: ThreadRecord): RunThreadOptions | null;
10
14
  /** Refresh the status message persisted at suspension (metadata.statusMsgRef): a resumed
11
15
  * thread's terminal summary, or the new suspension count if it suspended again. Without
12
16
  * this, the dispatch/webhook status message reads "suspended — waiting on children"
13
17
  * forever after the thread has finished (2026-06-11 verification finding). */
14
18
  export declare function sealSuspendedStatusMsg(threadId: string, adapter?: PlatformAdapter | null): Promise<void>;
15
19
  export type ResumeFn = (parentThreadId: string) => void;
20
+ /** Resume a suspended manager thread to answer a subtask's question (ask_manager / DR-0016).
21
+ * Unlike maybeResumeParent, this does NOT require the manager's child sets to be empty — the
22
+ * manager is woken to answer, not because its children finished. It answers via answer_subtask,
23
+ * whose handler sets pendingControl='wait', so the manager re-suspends on its still-live children
24
+ * at the next step boundary. Shares the `resuming` guard so it never collides with a concurrent
25
+ * completion-driven resume (whichever wins, the question + any child results both sit in
26
+ * pendingMessages). No-op unless the manager is currently 'waiting'. */
27
+ export declare function resumeManagerForQuestion(managerThreadId: string, resume?: ResumeFn): void;
16
28
  /** Deliver a terminal child's result to its thread parent: remove the child from waitingOn,
17
29
  * queue the result notice into pendingMessages (persistent idempotency via
18
30
  * deliveredChildResults), and resume the parent when nothing is left to wait on.
@@ -89,7 +89,7 @@ async function postProjectNotice(t, text) {
89
89
  /** Rebuild RunThreadOptions for re-entering a suspended parent. extraHooks are not
90
90
  * persisted on ThreadRecord, so the dispatch task-status-check hook is reconstructed
91
91
  * from metadata.taskId/taskProject (the reason dispatch threads must store them). */
92
- function buildResumeOptions(parent) {
92
+ export function buildResumeOptions(parent) {
93
93
  const adapter = jobCtx.adapter;
94
94
  if (!adapter)
95
95
  return null;
@@ -153,6 +153,23 @@ const defaultResume = (parentId) => {
153
153
  },
154
154
  });
155
155
  };
156
+ /** Resume a suspended manager thread to answer a subtask's question (ask_manager / DR-0016).
157
+ * Unlike maybeResumeParent, this does NOT require the manager's child sets to be empty — the
158
+ * manager is woken to answer, not because its children finished. It answers via answer_subtask,
159
+ * whose handler sets pendingControl='wait', so the manager re-suspends on its still-live children
160
+ * at the next step boundary. Shares the `resuming` guard so it never collides with a concurrent
161
+ * completion-driven resume (whichever wins, the question + any child results both sit in
162
+ * pendingMessages). No-op unless the manager is currently 'waiting'. */
163
+ export function resumeManagerForQuestion(managerThreadId, resume) {
164
+ if (resuming.has(managerThreadId))
165
+ return;
166
+ const mgr = threadStore.get(managerThreadId);
167
+ if (!mgr || mgr.status !== 'waiting')
168
+ return;
169
+ resuming.add(managerThreadId);
170
+ log.info(`resuming manager ${managerThreadId} to answer a subtask question`);
171
+ (resume ?? defaultResume)(managerThreadId);
172
+ }
156
173
  /** Resume `parentId` if (and only if) it is suspended with nothing left to wait on —
157
174
  * both thread children (waitingOn) and task children (waitingOnTasks, DR-0014 §8). */
158
175
  function maybeResumeParent(parentId, resume) {
@@ -0,0 +1,26 @@
1
+ import type { PlatformAdapter } from '../platform/index.js';
2
+ /** Feature gate: turn-completion notification is ON by default. Opt out by setting
3
+ * CORTEX_TURN_NOTIFY to a falsy value (0 / false / off / no). */
4
+ export declare function isTurnNotifyEnabled(): boolean;
5
+ /** Minimum turn duration (seconds) before a completion notification is pushed.
6
+ * Configurable via CORTEX_TURN_NOTIFY_THRESHOLD_S; defaults to 60s. A non-positive
7
+ * or unparseable value falls back to the default. */
8
+ export declare function getTurnNotifyThresholdS(): number;
9
+ /** Push a NEW message to the conversation's channel when a long-running, user-initiated
10
+ * turn finishes — so the user gets an actual push notification (editing the status
11
+ * message to "✓ Done" does not notify on Slack or Feishu). Works for both Slack and
12
+ * Feishu through the PlatformAdapter abstraction (Composite fans out to both).
13
+ *
14
+ * Gated by: feature flag, interactive-channel scope, and a duration threshold.
15
+ * Never throws — a failed notification must not affect the main turn. */
16
+ export declare function maybeNotifyTurnComplete(params: {
17
+ adapter: PlatformAdapter;
18
+ channel: string;
19
+ threadAnchorId: string | null;
20
+ sessionName: string | null;
21
+ sessionId: string | null;
22
+ elapsedS: number;
23
+ elapsedStr: string;
24
+ status: 'completed' | 'failed';
25
+ metricsSuffix?: string;
26
+ }): Promise<void>;