@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.
- package/defaults/CORTEX.md +5 -0
- package/defaults/config/thread-templates.json +12 -6
- package/defaults/context/user/CORTEX.md +2 -2
- package/defaults/hooks/ask-user-question-hook.mjs +7 -1
- package/defaults/hooks/exit-plan-mode-hook.mjs +7 -1
- package/defaults/hooks/memory-ref-tracker.mjs +1 -0
- package/defaults/hooks/new-session-hook.mjs +1 -0
- package/defaults/hooks/post-task-hook.mjs +1 -0
- package/defaults/hooks/rules-loader.mjs +1 -0
- package/defaults/hooks/sensitive-file-edit.mjs +1 -0
- package/defaults/hooks/session-activity-tracker.mjs +1 -0
- package/defaults/hooks/task-status-check.mjs +1 -0
- package/defaults/hooks/tasks-yaml-guard.mjs +1 -0
- package/defaults/plugins/cortex-feishu/.claude-plugin/plugin.json +5 -0
- package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +163 -0
- package/defaults/plugins/cortex-feishu/skills/feishu-doc/scripts/ensure-lark-cli.sh +53 -0
- package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +7 -0
- package/defaults/prompts/directives/coder-reviewer.md +6 -6
- package/defaults/prompts/directives/coder.md +14 -15
- package/defaults/prompts/systemPrompts/coder.md +6 -1
- package/defaults/prompts/systemPrompts/direct.md +5 -0
- package/defaults/prompts/systemPrompts/web-opus-4-6.md +6 -1
- package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +6 -1
- package/defaults/prompts/systemPrompts/web.md +6 -1
- package/defaults/prompts/systemPrompts/worker.md +6 -1
- package/dist/agent-adapter/claude/adapter-tui.d.ts +12 -0
- package/dist/agent-adapter/claude/adapter-tui.js +15 -0
- package/dist/agent-adapter/claude/adapter.d.ts +110 -1
- package/dist/agent-adapter/claude/adapter.js +123 -2
- package/dist/agent-adapter/claude/bg-task-tracker.d.ts +45 -0
- package/dist/agent-adapter/claude/bg-task-tracker.js +91 -0
- package/dist/agent-adapter/normalize/event-types.d.ts +4 -0
- package/dist/agent-adapter/pi/event-parser.d.ts +3 -1
- package/dist/agent-adapter/pi/event-parser.js +12 -2
- package/dist/agent-adapter/types.d.ts +19 -0
- package/dist/core/auth.d.ts +36 -0
- package/dist/core/auth.js +85 -0
- package/dist/core/gateway-generator.js +10 -1
- package/dist/core/locales/en.d.ts +12 -0
- package/dist/core/locales/slices/interactions.d.ts +6 -0
- package/dist/core/locales/slices/interactions.js +14 -0
- package/dist/core/locales/slices/status.d.ts +6 -0
- package/dist/core/locales/slices/status.js +16 -0
- package/dist/core/status-format.d.ts +14 -0
- package/dist/core/status-format.js +23 -1
- package/dist/core/types/agent-types.d.ts +5 -0
- package/dist/core/types/thread-types.d.ts +15 -1
- package/dist/core/version.d.ts +3 -0
- package/dist/core/version.js +4 -1
- package/dist/domain/agents/facade.d.ts +13 -0
- package/dist/domain/agents/facade.js +36 -1
- package/dist/domain/costs/rate-limit-throttle.d.ts +1 -1
- package/dist/domain/costs/rate-limit-throttle.js +23 -2
- package/dist/domain/costs/resume-registry.d.ts +30 -0
- package/dist/domain/costs/resume-registry.js +68 -0
- package/dist/domain/mcp/core-server.js +5 -0
- package/dist/domain/mcp/feishu/index.js +5 -51
- package/dist/domain/mcp/feishu-server.js +3 -2
- package/dist/domain/mcp/tools/manager-qa.d.ts +2 -0
- package/dist/domain/mcp/tools/manager-qa.js +72 -0
- package/dist/domain/mcp/tools/task-ops.js +4 -2
- package/dist/domain/mcp/tools/thread-ops.js +2 -1
- package/dist/domain/mcp/tui-server.js +2 -1
- package/dist/domain/memory/user-context.d.ts +6 -5
- package/dist/domain/memory/user-context.js +12 -7
- package/dist/domain/remote/client-bootstrap.js +14 -2
- package/dist/domain/remote/client-hot-reload.d.ts +9 -2
- package/dist/domain/remote/client-hot-reload.js +77 -6
- package/dist/domain/remote/client-manager.d.ts +1 -1
- package/dist/domain/remote/client-manager.js +31 -5
- package/dist/domain/remote/cortex-client-config.d.ts +32 -0
- package/dist/domain/remote/cortex-client-config.js +49 -0
- package/dist/domain/remote/cortex-client.js +11 -7
- package/dist/domain/scheduling/jobs/scheduled-task.js +17 -1
- package/dist/domain/scheduling/jobs/task-dispatch.js +22 -0
- package/dist/domain/sessions/session-hooks.d.ts +31 -1
- package/dist/domain/sessions/session-hooks.js +69 -17
- package/dist/domain/system/doctor.d.ts +63 -0
- package/dist/domain/system/doctor.js +362 -0
- package/dist/domain/tasks/dispatcher.js +8 -0
- package/dist/domain/tasks/system/cortex-run.js +4 -2
- package/dist/domain/tasks/system/task-cli.js +7 -4
- package/dist/domain/tasks/system/task-state.d.ts +10 -1
- package/dist/domain/tasks/system/task-state.js +31 -1
- package/dist/domain/threads/prompt-builder.d.ts +7 -4
- package/dist/domain/threads/prompt-builder.js +9 -8
- package/dist/domain/threads/runner.d.ts +8 -1
- package/dist/domain/threads/runner.js +111 -18
- package/dist/domain/threads/state-machine.d.ts +5 -0
- package/dist/domain/threads/state-machine.js +16 -0
- package/dist/entry/app.js +44 -5
- package/dist/entry/cli.js +10 -0
- package/dist/entry/doctor-cli.d.ts +12 -0
- package/dist/entry/doctor-cli.js +76 -0
- package/dist/entry/init.js +6 -0
- package/dist/hooks/ask-user-question-hook.mjs +7 -1
- package/dist/hooks/exit-plan-mode-hook.mjs +7 -1
- package/dist/hooks/memory-ref-tracker.mjs +1 -0
- package/dist/hooks/new-session-hook.mjs +1 -0
- package/dist/hooks/post-task-hook.mjs +1 -0
- package/dist/hooks/rules-loader.mjs +1 -0
- package/dist/hooks/sensitive-file-edit.mjs +1 -0
- package/dist/hooks/session-activity-tracker.mjs +1 -0
- package/dist/hooks/task-status-check.mjs +1 -0
- package/dist/hooks/tasks-yaml-guard.mjs +1 -0
- package/dist/orchestration/agent-runner.js +30 -4
- package/dist/orchestration/bg-continuation.d.ts +26 -0
- package/dist/orchestration/bg-continuation.js +34 -0
- package/dist/orchestration/conversation-runner.d.ts +3 -0
- package/dist/orchestration/conversation-runner.js +5 -2
- package/dist/orchestration/interactions/interaction-handlers.js +13 -2
- package/dist/orchestration/lifecycle.d.ts +5 -2
- package/dist/orchestration/lifecycle.js +87 -3
- package/dist/orchestration/manager-qa.d.ts +56 -0
- package/dist/orchestration/manager-qa.js +223 -0
- package/dist/orchestration/resume-dispatcher.d.ts +27 -0
- package/dist/orchestration/resume-dispatcher.js +145 -0
- package/dist/orchestration/routing/webhook.d.ts +1 -1
- package/dist/orchestration/routing/webhook.js +75 -14
- package/dist/orchestration/status-helpers.d.ts +3 -0
- package/dist/orchestration/status-helpers.js +16 -0
- package/dist/orchestration/thread-callback.d.ts +17 -1
- package/dist/orchestration/thread-callback.js +57 -36
- package/dist/orchestration/turn-notify.d.ts +26 -0
- package/dist/orchestration/turn-notify.js +66 -0
- package/dist/platform/adapters/feishu.d.ts +16 -0
- package/dist/platform/adapters/feishu.js +67 -6
- package/dist/store/plugin-sync.d.ts +21 -0
- package/dist/store/plugin-sync.js +119 -0
- package/dist/store/schedule-repo.d.ts +6 -0
- package/dist/store/schedule-repo.js +11 -1
- package/dist/store/thread-repo.js +14 -0
- package/dist/store/version-migrations.d.ts +23 -4
- package/dist/store/version-migrations.js +167 -9
- package/dist/tui/App.js +11 -7
- package/dist/tui/components/Dashboard.js +26 -11
- package/dist/tui/components/InputBox.js +43 -4
- package/dist/tui/components/SidePanel.js +1 -1
- package/package.json +1 -1
- package/dist/domain/mcp/feishu/bitable.d.ts +0 -3
- package/dist/domain/mcp/feishu/bitable.js +0 -168
- package/dist/domain/mcp/feishu/blocks-to-text.d.ts +0 -19
- package/dist/domain/mcp/feishu/blocks-to-text.js +0 -43
- package/dist/domain/mcp/feishu/docx.d.ts +0 -3
- package/dist/domain/mcp/feishu/docx.js +0 -163
- package/dist/domain/mcp/feishu/drive.d.ts +0 -23
- package/dist/domain/mcp/feishu/drive.js +0 -66
- package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +0 -40
- package/dist/domain/mcp/feishu/markdown-to-blocks.js +0 -191
- package/dist/domain/mcp/feishu/sheets.d.ts +0 -3
- package/dist/domain/mcp/feishu/sheets.js +0 -119
- package/dist/domain/mcp/feishu/wiki.d.ts +0 -3
- package/dist/domain/mcp/feishu/wiki.js +0 -77
|
@@ -0,0 +1,223 @@
|
|
|
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
|
+
import { t } from '../core/i18n.js';
|
|
18
|
+
const log = createLogger('manager-qa');
|
|
19
|
+
/** Central in-memory question store (daemon process). questionId → question. */
|
|
20
|
+
const questions = new Map();
|
|
21
|
+
/** channel → questionId, for routing a human's free-text reply back to the right pending ask. */
|
|
22
|
+
const channelIndex = new Map();
|
|
23
|
+
/** Test hook: clear all in-memory Q&A state. */
|
|
24
|
+
export function _testResetManagerQa() {
|
|
25
|
+
questions.clear();
|
|
26
|
+
channelIndex.clear();
|
|
27
|
+
}
|
|
28
|
+
function defaultReadTask(project, taskId) {
|
|
29
|
+
try {
|
|
30
|
+
const t = scanAllTasks(project ?? undefined).find((x) => x.id === taskId);
|
|
31
|
+
return t ? { parent: t.parent ?? null, origin_channel: t.origin_channel ?? null } : null;
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
async function defaultPostToChannel(channel, text) {
|
|
38
|
+
const adapter = jobCtx.adapter;
|
|
39
|
+
if (!adapter) {
|
|
40
|
+
log.error(`no adapter; cannot escalate question to ${channel}`);
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
|
|
44
|
+
const queue = getOutboundQueue();
|
|
45
|
+
if (queue)
|
|
46
|
+
await durablePost(queue, adapter, dest, { text });
|
|
47
|
+
else
|
|
48
|
+
await adapter.postMessage(dest, { text });
|
|
49
|
+
}
|
|
50
|
+
/** Notice injected into the manager's pendingMessages — an AGENT-facing prompt (English, not i18n;
|
|
51
|
+
* mirrors the directives, which are not localized). Mirrors buildChildResultNotice's shape: states
|
|
52
|
+
* what is asked and how to respond. */
|
|
53
|
+
export function buildQuestionNotice(q) {
|
|
54
|
+
const from = q.fromTaskId ? `subtask #${q.fromTaskId}` : 'a subtask';
|
|
55
|
+
return [
|
|
56
|
+
`[Subtask question] ${from} hit something unclear/contradictory while executing and is checking your planning intent (you are its manager):`,
|
|
57
|
+
'',
|
|
58
|
+
`Question: ${q.question}`,
|
|
59
|
+
'',
|
|
60
|
+
'Answer with the answer_subtask tool (after answering you automatically return to waiting on your subtasks):',
|
|
61
|
+
` answer_subtask(question_id="${q.questionId}", answer="<your answer>")`,
|
|
62
|
+
'If you are also unsure (it concerns a higher-level planning intent), call ask_manager to ask your own manager, then answer this subtask once you have their reply.',
|
|
63
|
+
].join('\n');
|
|
64
|
+
}
|
|
65
|
+
/** Notice posted to a human's chat channel when a subtask escalates to the top of the tree — a
|
|
66
|
+
* USER-facing platform message, so it is localized via i18n.t() (CORTEX_LANG). The ❓ icon stays
|
|
67
|
+
* in code per the locales convention (icons never live in the message tables). */
|
|
68
|
+
function buildHumanEscalationNotice(q) {
|
|
69
|
+
const from = q.fromTaskId ? t('subtask.fromTask', { taskId: q.fromTaskId }) : t('subtask.fromUnknown');
|
|
70
|
+
return [
|
|
71
|
+
`❓ ${t('subtask.escalateHeader', { from })}`,
|
|
72
|
+
'',
|
|
73
|
+
t('subtask.questionLabel', { question: q.question }),
|
|
74
|
+
'',
|
|
75
|
+
t('subtask.escalateReply'),
|
|
76
|
+
].join('\n');
|
|
77
|
+
}
|
|
78
|
+
/** Resolve the manager thread to ask: prefer an explicit thread parent; otherwise walk the task
|
|
79
|
+
* tree (child task.parent → the live thread that owns that manager task). Returns null when no
|
|
80
|
+
* live manager exists (→ human escalation). */
|
|
81
|
+
function resolveManagerThread(thread, deps) {
|
|
82
|
+
const ptid = thread.metadata?.parentThreadId;
|
|
83
|
+
if (ptid) {
|
|
84
|
+
const p = threadStore.get(ptid);
|
|
85
|
+
if (p && !isTerminalStatus(p.status))
|
|
86
|
+
return ptid;
|
|
87
|
+
}
|
|
88
|
+
const taskId = thread.metadata?.taskId;
|
|
89
|
+
if (!taskId)
|
|
90
|
+
return null;
|
|
91
|
+
const project = thread.metadata?.taskProject ?? null;
|
|
92
|
+
const childTask = (deps.readTask ?? defaultReadTask)(project, taskId);
|
|
93
|
+
const managerTaskId = childTask?.parent ?? null;
|
|
94
|
+
if (!managerTaskId)
|
|
95
|
+
return null;
|
|
96
|
+
const mgr = threadStore.getAll().find((t) => t.metadata?.taskId === managerTaskId && !isTerminalStatus(t.status));
|
|
97
|
+
return mgr?.id ?? null;
|
|
98
|
+
}
|
|
99
|
+
/** Walk up the task tree from the asking thread's task to the nearest ancestor that carries an
|
|
100
|
+
* origin_channel — the human who set the work in motion. Used only when no manager thread exists. */
|
|
101
|
+
function findEscalationChannel(thread, deps) {
|
|
102
|
+
const read = deps.readTask ?? defaultReadTask;
|
|
103
|
+
const project = thread.metadata?.taskProject ?? null;
|
|
104
|
+
let taskId = thread.metadata?.taskId ?? null;
|
|
105
|
+
let hops = 0;
|
|
106
|
+
while (taskId && hops < 16) {
|
|
107
|
+
const t = read(project, taskId);
|
|
108
|
+
if (!t)
|
|
109
|
+
break;
|
|
110
|
+
if (t.origin_channel)
|
|
111
|
+
return t.origin_channel;
|
|
112
|
+
taskId = t.parent;
|
|
113
|
+
hops++;
|
|
114
|
+
}
|
|
115
|
+
// No human conduit captured anywhere up the tree → nothing to escalate to. We deliberately do
|
|
116
|
+
// NOT fall back to thread.channel: a dispatch thread's channel is often an unattended
|
|
117
|
+
// project-report conduit, and silently posting a question there would block the subtask on an
|
|
118
|
+
// answer that never comes.
|
|
119
|
+
return null;
|
|
120
|
+
}
|
|
121
|
+
async function deliverToManager(managerThreadId, q, deps) {
|
|
122
|
+
await threadStore.mutate(managerThreadId, (t) => {
|
|
123
|
+
const m = (t.metadata ??= {});
|
|
124
|
+
if (!Array.isArray(m.pendingMessages))
|
|
125
|
+
m.pendingMessages = [];
|
|
126
|
+
if (m.pendingMessages.length >= 10)
|
|
127
|
+
m.pendingMessages.shift();
|
|
128
|
+
m.pendingMessages.push(buildQuestionNotice(q));
|
|
129
|
+
if (!Array.isArray(m.pendingQuestions))
|
|
130
|
+
m.pendingQuestions = [];
|
|
131
|
+
m.pendingQuestions.push({ questionId: q.questionId, fromTaskId: q.fromTaskId, question: q.question });
|
|
132
|
+
});
|
|
133
|
+
// Only a suspended manager needs waking; a running one will see the question in its own loop.
|
|
134
|
+
const mgr = threadStore.get(managerThreadId);
|
|
135
|
+
if (mgr?.status === 'waiting')
|
|
136
|
+
(deps.resume ?? resumeManagerForQuestion)(managerThreadId);
|
|
137
|
+
}
|
|
138
|
+
function newQuestionId() {
|
|
139
|
+
return `q_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
|
140
|
+
}
|
|
141
|
+
/** Register a subtask's question and route it: to its manager (woken to answer), or — at the top of
|
|
142
|
+
* the tree — to a human via the origin channel. Returns a questionId the caller polls via getAnswer. */
|
|
143
|
+
export async function askManager(threadId, question, deps = {}) {
|
|
144
|
+
const thread = threadStore.get(threadId);
|
|
145
|
+
if (!thread)
|
|
146
|
+
return { ok: false, error: 'calling thread not found (CORTEX_THREAD_ID stale?)' };
|
|
147
|
+
const q = (question ?? '').trim();
|
|
148
|
+
if (!q)
|
|
149
|
+
return { ok: false, error: 'question must not be empty' };
|
|
150
|
+
const managerThreadId = resolveManagerThread(thread, deps);
|
|
151
|
+
const questionId = newQuestionId();
|
|
152
|
+
if (managerThreadId) {
|
|
153
|
+
const rec = {
|
|
154
|
+
questionId, fromThreadId: threadId, fromTaskId: thread.metadata?.taskId ?? null,
|
|
155
|
+
managerThreadId, channel: null, awaitingHuman: false, question: q, answer: null, createdAt: Date.now(),
|
|
156
|
+
};
|
|
157
|
+
questions.set(questionId, rec);
|
|
158
|
+
await deliverToManager(managerThreadId, rec, deps);
|
|
159
|
+
log.info(`ask_manager: ${threadId} → manager ${managerThreadId} (${questionId})`);
|
|
160
|
+
return { ok: true, questionId, target: 'manager', managerThreadId };
|
|
161
|
+
}
|
|
162
|
+
const channel = findEscalationChannel(thread, deps);
|
|
163
|
+
if (!channel) {
|
|
164
|
+
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' };
|
|
165
|
+
}
|
|
166
|
+
const rec = {
|
|
167
|
+
questionId, fromThreadId: threadId, fromTaskId: thread.metadata?.taskId ?? null,
|
|
168
|
+
managerThreadId: null, channel, awaitingHuman: true, question: q, answer: null, createdAt: Date.now(),
|
|
169
|
+
};
|
|
170
|
+
questions.set(questionId, rec);
|
|
171
|
+
channelIndex.set(channel, questionId);
|
|
172
|
+
await (deps.postToChannel ?? defaultPostToChannel)(channel, buildHumanEscalationNotice(rec));
|
|
173
|
+
log.info(`ask_manager: ${threadId} → human escalation on ${channel} (${questionId})`);
|
|
174
|
+
return { ok: true, questionId, target: 'human', channel };
|
|
175
|
+
}
|
|
176
|
+
/** Manager answers a subtask question. Records the answer and forces the manager back to waiting
|
|
177
|
+
* (pendingControl='wait') so it re-suspends on its still-live children at the next step boundary. */
|
|
178
|
+
export async function submitAnswer(questionId, answer) {
|
|
179
|
+
const rec = questions.get(questionId);
|
|
180
|
+
if (!rec)
|
|
181
|
+
return { ok: false, error: `unknown question ${questionId} (expired, already consumed, or lost on restart)` };
|
|
182
|
+
rec.answer = answer ?? '';
|
|
183
|
+
if (rec.managerThreadId) {
|
|
184
|
+
await threadStore.mutate(rec.managerThreadId, (t) => {
|
|
185
|
+
const m = (t.metadata ??= {});
|
|
186
|
+
if (Array.isArray(m.pendingQuestions))
|
|
187
|
+
m.pendingQuestions = m.pendingQuestions.filter((x) => x.questionId !== questionId);
|
|
188
|
+
// Re-suspend after answering — unless a control intent is already queued (don't clobber it).
|
|
189
|
+
if (!m.pendingControl)
|
|
190
|
+
m.pendingControl = { action: 'wait' };
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
log.info(`answer_subtask: ${questionId} answered`);
|
|
194
|
+
return { ok: true };
|
|
195
|
+
}
|
|
196
|
+
/** Poll for an answer. Consumes the entry once an answer is present (one-shot read by the poller). */
|
|
197
|
+
export function getAnswer(questionId) {
|
|
198
|
+
const rec = questions.get(questionId);
|
|
199
|
+
if (!rec)
|
|
200
|
+
return { found: false, answered: false, answer: null };
|
|
201
|
+
if (rec.answer !== null) {
|
|
202
|
+
questions.delete(questionId);
|
|
203
|
+
if (rec.channel)
|
|
204
|
+
channelIndex.delete(rec.channel);
|
|
205
|
+
return { found: true, answered: true, answer: rec.answer };
|
|
206
|
+
}
|
|
207
|
+
return { found: true, answered: false, answer: null };
|
|
208
|
+
}
|
|
209
|
+
/** Interactive hook: if `channel` has a pending human-escalated question, consume this message as
|
|
210
|
+
* its answer and return true (the caller should then short-circuit normal turn handling). */
|
|
211
|
+
export function tryAnswerFromHuman(channel, text) {
|
|
212
|
+
const qid = channelIndex.get(channel);
|
|
213
|
+
if (!qid)
|
|
214
|
+
return false;
|
|
215
|
+
const rec = questions.get(qid);
|
|
216
|
+
if (!rec || !rec.awaitingHuman) {
|
|
217
|
+
channelIndex.delete(channel);
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
rec.answer = text ?? '';
|
|
221
|
+
log.info(`ask_manager: human answered ${qid} on ${channel}`);
|
|
222
|
+
return true;
|
|
223
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
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
|
+
/** True if a DIRECT (interactive) session is live on the channel — i.e. an execution with no
|
|
18
|
+
* threadId. Only direct sessions force a channel to serialize (a Slack conversation cannot
|
|
19
|
+
* interleave two assistant turns). Threads are channel-parallel-safe, so a rate-limited thread
|
|
20
|
+
* only needs to avoid a live direct session, not other threads. */
|
|
21
|
+
directSessionBusy: (channel: string) => boolean;
|
|
22
|
+
now: () => number;
|
|
23
|
+
delay: (ms: number) => Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
/** Drain the resume registry and re-enter each interrupted target. Called by the
|
|
26
|
+
* rate-limit-throttle onResume hook when the window resets. Never throws. */
|
|
27
|
+
export declare function dispatchPendingResumes(adapter: PlatformAdapter, overrides?: Partial<ResumeDeps>): Promise<void>;
|
|
@@ -0,0 +1,145 @@
|
|
|
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 (or on startup if the queue has orphans
|
|
4
|
+
// and no throttle is active). Direct sessions are re-entered with a <system-reminder> and
|
|
5
|
+
// serialized per channel; threads (status 'rate_limited') are re-run from the interrupted
|
|
6
|
+
// step via resumeRateLimitedThread, fired concurrently (channel-parallel-safe) and only
|
|
7
|
+
// skipped if a live direct session holds the channel. Options rebuilt by buildResumeOptions
|
|
8
|
+
// (dispatch onEnd hook + destination). All deps injectable for tests.
|
|
9
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
10
|
+
import { takeAllResumes } from '../domain/costs/resume-registry.js';
|
|
11
|
+
import { agentRunner } from './agent-runner.js';
|
|
12
|
+
import { resumeRateLimitedThread } from '../domain/threads/runner.js';
|
|
13
|
+
import { buildResumeOptions } from './thread-callback.js';
|
|
14
|
+
import { threadStore } from '../store/thread-repo.js';
|
|
15
|
+
import { runningExecutions } from '../core/running-executions.js';
|
|
16
|
+
import { createLogger } from '../core/log.js';
|
|
17
|
+
const log = createLogger('resume-dispatcher');
|
|
18
|
+
/** Entries older than this are considered obsolete (user moved on / thread finished).
|
|
19
|
+
* 6h = the 5-hour window plus restart slack. */
|
|
20
|
+
const MAX_RESUME_AGE_MS = 6 * 60 * 60 * 1000;
|
|
21
|
+
/** Gap between consecutive resume starts so we don't re-trip the limit / overload the API right
|
|
22
|
+
* after a window reset. Resumes begin one every 30s. */
|
|
23
|
+
const RESUME_STAGGER_MS = 30_000;
|
|
24
|
+
/** Auto-resume is on by default; disable with CORTEX_AUTO_RESUME=0 (or "false"). */
|
|
25
|
+
export function isAutoResumeEnabled() {
|
|
26
|
+
const v = process.env.CORTEX_AUTO_RESUME;
|
|
27
|
+
return v !== '0' && v !== 'false';
|
|
28
|
+
}
|
|
29
|
+
/** The continuation prompt injected into a resumed session/thread. Self-contained — the
|
|
30
|
+
* prior turn's content is already in the resumed session/thread history. */
|
|
31
|
+
export function buildResumeReminder() {
|
|
32
|
+
return [
|
|
33
|
+
'<system-reminder>',
|
|
34
|
+
'The previous turn was interrupted by an API rate limit (the 5-hour window). That window has now reset; you may continue.',
|
|
35
|
+
'Resume from where you left off: review the recent conversation context above, work out what is still unfinished, and finish it.',
|
|
36
|
+
'Do not restart the task from scratch, and do not re-ask for information the user already provided. If the previous turn was in fact already complete, briefly confirm and stop.',
|
|
37
|
+
'This message is only a resume signal; it should not change your original task.',
|
|
38
|
+
'</system-reminder>',
|
|
39
|
+
].join('\n');
|
|
40
|
+
}
|
|
41
|
+
function defaultDeps() {
|
|
42
|
+
return {
|
|
43
|
+
takeAll: takeAllResumes,
|
|
44
|
+
route: (ctx) => agentRunner.route(ctx),
|
|
45
|
+
resumeThread: (id, opts) => resumeRateLimitedThread(id, opts),
|
|
46
|
+
buildResumeOptions: (thread) => buildResumeOptions(thread),
|
|
47
|
+
getThread: (id) => threadStore.get(id),
|
|
48
|
+
channelBusy: (ch) => runningExecutions.hasChannel(ch),
|
|
49
|
+
directSessionBusy: (ch) => runningExecutions.getByChannel(ch).some(e => !e.threadId),
|
|
50
|
+
now: () => Date.now(),
|
|
51
|
+
delay: (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function entryKey(e) {
|
|
55
|
+
return e.kind === 'thread' ? `thread ${e.threadId}` : `direct ${e.channel}`;
|
|
56
|
+
}
|
|
57
|
+
/** Drain the resume registry and re-enter each interrupted target. Called by the
|
|
58
|
+
* rate-limit-throttle onResume hook when the window resets. Never throws. */
|
|
59
|
+
export async function dispatchPendingResumes(adapter, overrides = {}) {
|
|
60
|
+
const deps = { ...defaultDeps(), ...overrides };
|
|
61
|
+
if (!isAutoResumeEnabled()) {
|
|
62
|
+
const drained = deps.takeAll(); // drain so stale entries don't pile up across windows
|
|
63
|
+
if (drained.length > 0)
|
|
64
|
+
log.info(`Auto-resume disabled — dropped ${drained.length} pending entry(ies)`);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
const entries = deps.takeAll();
|
|
68
|
+
if (entries.length === 0)
|
|
69
|
+
return;
|
|
70
|
+
log.info(`Rate-limit window reset — resuming ${entries.length} interrupted target(s)`);
|
|
71
|
+
let dispatched = 0;
|
|
72
|
+
for (const entry of entries) {
|
|
73
|
+
const skip = guardSkipReason(entry, deps);
|
|
74
|
+
if (skip) {
|
|
75
|
+
log.info(`Resume skip (${entryKey(entry)}): ${skip}`);
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
if (dispatched > 0)
|
|
80
|
+
await deps.delay(RESUME_STAGGER_MS); // stagger START times, not completion
|
|
81
|
+
if (entry.kind === 'direct') {
|
|
82
|
+
// Direct sessions are serial per channel — await so the next dispatch sees it as busy.
|
|
83
|
+
await resumeDirect(entry, adapter, deps);
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
// Threads are channel-parallel-safe: fire-and-forget so multiple rate-limited threads on
|
|
87
|
+
// the same channel resume concurrently instead of serializing behind the first one.
|
|
88
|
+
void resumeThread(entry, deps.getThread(entry.threadId), adapter, deps)
|
|
89
|
+
.catch(e => log.error(`Resume failed (${entryKey(entry)}): ${e.message}`));
|
|
90
|
+
}
|
|
91
|
+
dispatched++;
|
|
92
|
+
}
|
|
93
|
+
catch (e) {
|
|
94
|
+
log.error(`Resume failed (${entryKey(entry)}): ${e.message}`);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
log.info(`Resume complete — dispatched ${dispatched}/${entries.length}`);
|
|
98
|
+
}
|
|
99
|
+
/** Returns a human reason to skip, or null to proceed. */
|
|
100
|
+
function guardSkipReason(entry, deps) {
|
|
101
|
+
if (deps.now() - entry.recordedAt > MAX_RESUME_AGE_MS)
|
|
102
|
+
return 'stale';
|
|
103
|
+
if (entry.kind === 'direct') {
|
|
104
|
+
// A direct session is a live conversation — serialize per channel (no interleaved turns).
|
|
105
|
+
if (deps.channelBusy(entry.channel))
|
|
106
|
+
return 'channel already has a running execution';
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
// Thread: channel-parallel-safe. Only avoid a live direct session (interactive turn) on the
|
|
110
|
+
// channel; concurrent threads on the same channel are fine and must not skip each other.
|
|
111
|
+
if (deps.directSessionBusy(entry.channel))
|
|
112
|
+
return 'direct session active on channel';
|
|
113
|
+
const thread = deps.getThread(entry.threadId);
|
|
114
|
+
if (!thread)
|
|
115
|
+
return 'thread no longer exists';
|
|
116
|
+
if (thread.status !== 'rate_limited')
|
|
117
|
+
return `thread is ${thread.status}`;
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
async function resumeDirect(entry, adapter, deps) {
|
|
121
|
+
const notice = buildResumeReminder();
|
|
122
|
+
const message = {
|
|
123
|
+
ref: { conduit: entry.channel, messageId: `resume_${Date.now()}` },
|
|
124
|
+
text: notice,
|
|
125
|
+
senderId: 'cortex-rate-limit-resume',
|
|
126
|
+
isBot: false,
|
|
127
|
+
kind: 'user',
|
|
128
|
+
raw: { source: 'rate-limit-resume', originalMessage: entry.userMessage },
|
|
129
|
+
};
|
|
130
|
+
log.info(`Resuming direct session on ${entry.channel}`);
|
|
131
|
+
await deps.route({ message, channel: entry.channel, adapter, threadAnchorId: null, hasFiles: false, userMessage: notice, agentMessage: notice });
|
|
132
|
+
}
|
|
133
|
+
async function resumeThread(entry, thread, _adapter, deps) {
|
|
134
|
+
// Rebuild RunThreadOptions (destination + dispatch task-status-check onEnd hook) from the
|
|
135
|
+
// thread's persisted metadata — same machinery DR-0014 uses to re-enter suspended parents.
|
|
136
|
+
// Unlike a direct session, a thread re-runs its interrupted step from the original prompt, so
|
|
137
|
+
// no <system-reminder> / userMessage overwrite is injected.
|
|
138
|
+
const opts = deps.buildResumeOptions(thread);
|
|
139
|
+
if (!opts) {
|
|
140
|
+
log.error(`Resume skip (thread ${entry.threadId}): could not rebuild run options (no adapter?)`);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
log.info(`Resuming thread ${entry.threadId} on ${entry.channel}`);
|
|
144
|
+
await deps.resumeThread(entry.threadId, opts);
|
|
145
|
+
}
|
|
@@ -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
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
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(
|
|
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
|
-
|
|
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,28 @@ 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 OR a rate-limit-paused thread.
|
|
11
|
+
* extraHooks are not persisted on ThreadRecord, so the dispatch task-status-check hook is
|
|
12
|
+
* reconstructed from metadata.taskId/taskProject (the reason dispatch threads must store them).
|
|
13
|
+
* statusMsg is restored from metadata.statusMsgRef (persisted at dispatch by task-dispatch /
|
|
14
|
+
* webhook) so the resumed run keeps updating the SAME live status message — without it the run
|
|
15
|
+
* carries statusMsg=null and the message freezes at "Paused — rate limited" forever even though
|
|
16
|
+
* the thread runs to completion (2026-06-23 finding: rate-limit resume status-message freeze). */
|
|
17
|
+
export declare function buildResumeOptions(parent: ThreadRecord): RunThreadOptions | null;
|
|
10
18
|
/** Refresh the status message persisted at suspension (metadata.statusMsgRef): a resumed
|
|
11
19
|
* thread's terminal summary, or the new suspension count if it suspended again. Without
|
|
12
20
|
* this, the dispatch/webhook status message reads "suspended — waiting on children"
|
|
13
21
|
* forever after the thread has finished (2026-06-11 verification finding). */
|
|
14
22
|
export declare function sealSuspendedStatusMsg(threadId: string, adapter?: PlatformAdapter | null): Promise<void>;
|
|
15
23
|
export type ResumeFn = (parentThreadId: string) => void;
|
|
24
|
+
/** Resume a suspended manager thread to answer a subtask's question (ask_manager / DR-0016).
|
|
25
|
+
* Unlike maybeResumeParent, this does NOT require the manager's child sets to be empty — the
|
|
26
|
+
* manager is woken to answer, not because its children finished. It answers via answer_subtask,
|
|
27
|
+
* whose handler sets pendingControl='wait', so the manager re-suspends on its still-live children
|
|
28
|
+
* at the next step boundary. Shares the `resuming` guard so it never collides with a concurrent
|
|
29
|
+
* completion-driven resume (whichever wins, the question + any child results both sit in
|
|
30
|
+
* pendingMessages). No-op unless the manager is currently 'waiting'. */
|
|
31
|
+
export declare function resumeManagerForQuestion(managerThreadId: string, resume?: ResumeFn): void;
|
|
16
32
|
/** Deliver a terminal child's result to its thread parent: remove the child from waitingOn,
|
|
17
33
|
* queue the result notice into pendingMessages (persistent idempotency via
|
|
18
34
|
* deliveredChildResults), and resume the parent when nothing is left to wait on.
|