@cortex-agent/server 2026.6.22 → 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/config/thread-templates.json +12 -6
- package/defaults/context/user/CORTEX.md +2 -2
- package/defaults/hooks/ask-user-question-hook.mjs +1 -0
- package/defaults/hooks/exit-plan-mode-hook.mjs +1 -0
- 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/prompts/directives/coder-reviewer.md +6 -6
- package/defaults/prompts/directives/coder.md +14 -15
- 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.js +6 -2
- package/dist/agent-adapter/claude/bg-task-tracker.d.ts +8 -0
- package/dist/agent-adapter/claude/bg-task-tracker.js +18 -5
- package/dist/core/gateway-generator.js +10 -1
- package/dist/core/locales/en.d.ts +6 -0
- package/dist/core/locales/slices/interactions.d.ts +6 -0
- package/dist/core/locales/slices/interactions.js +14 -0
- package/dist/core/status-format.d.ts +14 -0
- package/dist/core/status-format.js +23 -1
- package/dist/core/types/thread-types.d.ts +3 -0
- package/dist/domain/agents/facade.d.ts +13 -0
- package/dist/domain/agents/facade.js +24 -1
- package/dist/domain/mcp/feishu/index.js +5 -51
- package/dist/domain/mcp/feishu-server.js +3 -2
- package/dist/domain/memory/user-context.d.ts +6 -5
- package/dist/domain/memory/user-context.js +12 -7
- package/dist/domain/remote/client-hot-reload.d.ts +9 -2
- package/dist/domain/remote/client-hot-reload.js +77 -6
- package/dist/domain/scheduling/jobs/task-dispatch.js +1 -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/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.js +30 -7
- package/dist/entry/app.js +38 -14
- 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/hooks/ask-user-question-hook.mjs +1 -0
- package/dist/hooks/exit-plan-mode-hook.mjs +1 -0
- 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 +3 -2
- package/dist/orchestration/conversation-runner.js +4 -1
- package/dist/orchestration/lifecycle.d.ts +2 -1
- package/dist/orchestration/lifecycle.js +15 -1
- package/dist/orchestration/manager-qa.d.ts +3 -2
- package/dist/orchestration/manager-qa.js +17 -12
- package/dist/orchestration/resume-dispatcher.d.ts +5 -0
- package/dist/orchestration/resume-dispatcher.js +38 -22
- package/dist/orchestration/thread-callback.d.ts +7 -3
- package/dist/orchestration/thread-callback.js +39 -35
- package/dist/store/plugin-sync.d.ts +21 -0
- package/dist/store/plugin-sync.js +119 -0
- package/dist/store/version-migrations.d.ts +9 -0
- package/dist/store/version-migrations.js +100 -0
- 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
|
@@ -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
|
-
|
|
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
|
|
41
|
-
*
|
|
42
|
-
*
|
|
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
|
|
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
|
-
|
|
176
|
-
|
|
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
|
|
214
|
-
*
|
|
215
|
-
*
|
|
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(
|
|
231
|
+
const userCtx = includeUserContext ? loadUserContext() : null;
|
|
231
232
|
if (userCtx)
|
|
232
233
|
prefixes.push(userCtx);
|
|
233
234
|
if (agentConfig.directive)
|
|
@@ -13,6 +13,7 @@ import { closeSessionsByPrefix } from '../agents/index.js';
|
|
|
13
13
|
import * as executionRegistry from '../executions/registry.js';
|
|
14
14
|
import { sessionStore } from '../../store/session-registry-repo.js';
|
|
15
15
|
import { formatDurationCompact } from '../../core/utils.js';
|
|
16
|
+
import { buildThreadStatusMessage } from '../../core/status-format.js';
|
|
16
17
|
import { runningExecutions } from '../../core/running-executions.js';
|
|
17
18
|
import { executeLifecycleHook } from './hook-runner.js';
|
|
18
19
|
import { createToolTrace } from '../../platform/index.js';
|
|
@@ -60,7 +61,15 @@ async function resolveAndNotifyStep(threadId, ctx, opts) {
|
|
|
60
61
|
// Update status message (multi-agent thread format; skip if caller provides onProgress)
|
|
61
62
|
if (ctx.stream && multiAgent && !opts.onProgress) {
|
|
62
63
|
const elapsed = (Date.now() - opts.startTime) / 1000;
|
|
63
|
-
const statusText =
|
|
64
|
+
const statusText = buildThreadStatusMessage({
|
|
65
|
+
threadId: threadRecord.id,
|
|
66
|
+
stepNumber: threadRecord.currentStepIndex + 1,
|
|
67
|
+
label,
|
|
68
|
+
elapsedS: elapsed,
|
|
69
|
+
taskProject: threadRecord.metadata?.taskProject ?? null,
|
|
70
|
+
taskId: threadRecord.metadata?.taskId ?? null,
|
|
71
|
+
taskText: threadRecord.metadata?.taskText ?? null,
|
|
72
|
+
});
|
|
64
73
|
try {
|
|
65
74
|
if (opts.statusMsg) {
|
|
66
75
|
await opts.adapter.updateMessage(opts.statusMsg, { text: statusText });
|
|
@@ -125,15 +134,20 @@ function setupStepCallbacks(threadId, stepCtx, ctx, opts) {
|
|
|
125
134
|
// Aggregate assistant output into the thread-runner's OutputStream; prefix only for multi-agent.
|
|
126
135
|
const slotPrefix = multiAgent ? `*[${label}]*` : null;
|
|
127
136
|
const baseAssistantMessage = (text) => { stream.emitText(slotPrefix ? `${slotPrefix} ${text}` : text); };
|
|
128
|
-
// Tool trace (env-gated):
|
|
129
|
-
//
|
|
137
|
+
// Tool trace (env-gated): emit a compact per-tool line to the runner's stream when
|
|
138
|
+
// CORTEX_SHOW_TOOL_CALLS is on, while STILL firing any caller-supplied onToolUse
|
|
139
|
+
// (interactive plan/ask capture). Both must run — compose, don't choose — so dispatch /
|
|
140
|
+
// scheduled / webhook threads stream tool calls like a direct session. The trace fires
|
|
141
|
+
// first; the caller (interactive) fires after, preserving the onToolUse-before-ask ordering.
|
|
130
142
|
const callerOnToolUse = opts.onToolUse ?? null;
|
|
131
|
-
const toolTrace =
|
|
143
|
+
const toolTrace = createToolTrace(stream, { slotPrefix });
|
|
132
144
|
const onAssistantMessage = toolTrace
|
|
133
145
|
? (text) => { toolTrace.flush(); baseAssistantMessage(text); }
|
|
134
146
|
: baseAssistantMessage;
|
|
135
|
-
const
|
|
136
|
-
|
|
147
|
+
const traceToolUse = toolTrace ? (name, input) => toolTrace.onToolUse(name, input) : null;
|
|
148
|
+
const onToolUse = traceToolUse && callerOnToolUse
|
|
149
|
+
? (name, input) => { traceToolUse(name, input); callerOnToolUse(name, input); }
|
|
150
|
+
: (traceToolUse ?? callerOnToolUse);
|
|
137
151
|
// onProgress: caller override (e.g. scheduler's buildUserProcessingMessage) takes precedence;
|
|
138
152
|
// fallback to thread-specific status format for multi-agent pipelines
|
|
139
153
|
const onProgress = opts.onProgress
|
|
@@ -142,7 +156,16 @@ function setupStepCallbacks(threadId, stepCtx, ctx, opts) {
|
|
|
142
156
|
const elapsed = (Date.now() - opts.startTime) / 1000;
|
|
143
157
|
if (opts.statusMsg) {
|
|
144
158
|
opts.adapter.updateMessage(opts.statusMsg, {
|
|
145
|
-
text:
|
|
159
|
+
text: buildThreadStatusMessage({
|
|
160
|
+
threadId: threadRecord.id,
|
|
161
|
+
stepNumber: threadRecord.currentStepIndex + 1,
|
|
162
|
+
label,
|
|
163
|
+
elapsedS: elapsed,
|
|
164
|
+
numTurns: progress?.num_turns ?? null,
|
|
165
|
+
taskProject: threadRecord.metadata?.taskProject ?? null,
|
|
166
|
+
taskId: threadRecord.metadata?.taskId ?? null,
|
|
167
|
+
taskText: threadRecord.metadata?.taskText ?? null,
|
|
168
|
+
}),
|
|
146
169
|
}).catch(() => { });
|
|
147
170
|
}
|
|
148
171
|
}
|
package/dist/entry/app.js
CHANGED
|
@@ -52,12 +52,13 @@ import { registerInteractionHandlers, initInteractionHandlers } from '../orchest
|
|
|
52
52
|
import { CommandActionRouter } from '../orchestration/interactions/command-action-router.js';
|
|
53
53
|
import { createUpdatePrompt } from '../orchestration/interactions/update-prompt.js';
|
|
54
54
|
import { registerMessageHandler } from '../orchestration/routing/message-router.js';
|
|
55
|
-
import { initRateLimitThrottle } from '../domain/costs/rate-limit-throttle.js';
|
|
56
|
-
import { initResumeRegistry } from '../domain/costs/resume-registry.js';
|
|
55
|
+
import { initRateLimitThrottle, isThrottled } from '../domain/costs/rate-limit-throttle.js';
|
|
56
|
+
import { initResumeRegistry, getResumeCount, recordResume } from '../domain/costs/resume-registry.js';
|
|
57
57
|
import { dispatchPendingResumes } from '../orchestration/resume-dispatcher.js';
|
|
58
58
|
import { scheduleRepo } from '../store/schedule-repo.js';
|
|
59
59
|
import { runMigrations, migrateAistatusConfigLocation } from '../store/version-migrations.js';
|
|
60
60
|
import { syncManagedHooks } from '../store/hook-sync.js';
|
|
61
|
+
import { syncManagedPlugins } from '../store/plugin-sync.js';
|
|
61
62
|
import { costRepo } from '../store/cost-repo.js';
|
|
62
63
|
import { profileRepo, startProfileWatcher, setAdminNotifier as setProfileNotifier } from '../store/profile-repo.js';
|
|
63
64
|
import { sessionStore } from '../store/session-registry-repo.js';
|
|
@@ -187,18 +188,9 @@ setInteractiveCallbacksFactory(buildInteractiveCallbacks);
|
|
|
187
188
|
const scheduler = createScheduler();
|
|
188
189
|
scheduler.setAdminNotifier(notifyAdmin);
|
|
189
190
|
setSchedulerRef(scheduler);
|
|
190
|
-
//
|
|
191
|
-
//
|
|
192
|
-
//
|
|
193
|
-
initResumeRegistry({
|
|
194
|
-
save: (entries) => scheduleRepo.setResumeQueue(entries),
|
|
195
|
-
load: () => scheduleRepo.getResumeQueue(),
|
|
196
|
-
}).catch(e => log.error(`initResumeRegistry failed: ${e.message}`)).finally(() => {
|
|
197
|
-
initRateLimitThrottle(adapter, {
|
|
198
|
-
save: (state) => scheduleRepo.setRateLimitThrottle(state),
|
|
199
|
-
load: () => scheduleRepo.getRateLimitThrottle(),
|
|
200
|
-
}, () => { void dispatchPendingResumes(adapter); }).catch(e => log.error(`initRateLimitThrottle failed: ${e.message}`));
|
|
201
|
-
});
|
|
191
|
+
// Rate-limit resume registry + throttle are initialized later, inside main(), as one ordered
|
|
192
|
+
// awaited sequence (initRateLimitRecovery) — it must run AFTER threadStore.load() so it can
|
|
193
|
+
// reconcile orphaned rate-limited threads back into the resume queue.
|
|
202
194
|
initDiskMonitor(adapter);
|
|
203
195
|
const commandRouter = new CommandActionRouter();
|
|
204
196
|
const dispatchCommand = registerCommands({
|
|
@@ -265,6 +257,10 @@ process.on('SIGTERM', async () => {
|
|
|
265
257
|
// Refresh version-stamped hooks in DATA_DIR/hooks from the shipped defaults. init's deployHooks
|
|
266
258
|
// only copies-if-missing, so without this an existing install never picks up hook code fixes.
|
|
267
259
|
await syncManagedHooks();
|
|
260
|
+
// Deploy new plugins and refresh updated skills in DATA_DIR/plugins from the shipped defaults.
|
|
261
|
+
// init's copyDefaults (copy-if-missing, only on `cortex init`) never reaches an existing install,
|
|
262
|
+
// so without this a new plugin or an updated skill never propagates on upgrade.
|
|
263
|
+
await syncManagedPlugins();
|
|
268
264
|
// DR-0012 §3.6: clean up orphan TUI tmux sessions from a previous agent-server lifetime.
|
|
269
265
|
// We can't re-adopt them (sessionKey↔tmux mapping was never persisted) so the honest move
|
|
270
266
|
// is to kill any leftovers — otherwise a later session that reuses the same sessionId will
|
|
@@ -328,6 +324,34 @@ process.on('SIGTERM', async () => {
|
|
|
328
324
|
threadStore.load();
|
|
329
325
|
await threadStore.markRunningAsFailedOnStartup();
|
|
330
326
|
await threadStore.cleanup();
|
|
327
|
+
// --- Rate-limit recovery (ordered; must run after threadStore.load) ---
|
|
328
|
+
// 1) hydrate the persisted resume queue. 2) Reconcile orphaned rate-limited threads: any thread
|
|
329
|
+
// left in 'rate_limited' (markRunningAsFailedOnStartup deliberately spares them) that is not
|
|
330
|
+
// represented in the queue — dropped by a prior dispatcher skip, or a queue/throttle desync
|
|
331
|
+
// across restart — is re-queued (idempotent, dedupe by threadId). 3) Arm the throttle; its
|
|
332
|
+
// restart-recovery may fire onResume synchronously, draining the (already-reconciled) queue.
|
|
333
|
+
// 4) If nothing is throttled and entries remain, drain now so a clean window resumes them.
|
|
334
|
+
await initResumeRegistry({
|
|
335
|
+
save: (entries) => scheduleRepo.setResumeQueue(entries),
|
|
336
|
+
load: () => scheduleRepo.getResumeQueue(),
|
|
337
|
+
});
|
|
338
|
+
let reQueuedRateLimited = 0;
|
|
339
|
+
for (const t of threadStore.getAll()) {
|
|
340
|
+
if (t.status === 'rate_limited') {
|
|
341
|
+
recordResume({ kind: 'thread', threadId: t.id, channel: t.channel, userMessage: t.userMessage ?? '', recordedAt: Date.now() });
|
|
342
|
+
reQueuedRateLimited++;
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
if (reQueuedRateLimited > 0)
|
|
346
|
+
log.info(`Reconciled ${reQueuedRateLimited} rate-limited thread(s) into the resume queue`);
|
|
347
|
+
await initRateLimitThrottle(adapter, {
|
|
348
|
+
save: (state) => scheduleRepo.setRateLimitThrottle(state),
|
|
349
|
+
load: () => scheduleRepo.getRateLimitThrottle(),
|
|
350
|
+
}, () => { void dispatchPendingResumes(adapter); });
|
|
351
|
+
if (!isThrottled() && getResumeCount() > 0) {
|
|
352
|
+
log.info(`Startup: ${getResumeCount()} pending resume(s), no active throttle — draining`);
|
|
353
|
+
void dispatchPendingResumes(adapter);
|
|
354
|
+
}
|
|
331
355
|
// GC: prune stale sessions (older than 7 days, unreferenced by running executions or active threads)
|
|
332
356
|
sessionStore.setOnPruneSession(cleanupAllBackups);
|
|
333
357
|
try {
|
package/dist/entry/cli.js
CHANGED
|
@@ -29,6 +29,7 @@ import { runCli as taskRunCli } from '../domain/tasks/system/task-cli.js';
|
|
|
29
29
|
import { runCli as installRunCli, getInstallHelp } from '../domain/system/install-cli.js';
|
|
30
30
|
import { getResolvedPaths, formatConfigOutput, runInit, } from './init.js';
|
|
31
31
|
import { cmdFeishu } from './feishu-login.js';
|
|
32
|
+
import { cmdDoctor, getDoctorHelp } from './doctor-cli.js';
|
|
32
33
|
import { discoverEndpoints, writeMergedGatewayYaml, validateProfilesAgainstGateway, dryRunGatewayYaml } from '../core/gateway-generator.js';
|
|
33
34
|
import { generateProfiles, writeProfilesJson } from '../core/profile-generator.js';
|
|
34
35
|
import { CORTEX_VERSION } from '../core/version.js';
|
|
@@ -165,6 +166,7 @@ export function getCliHelp() {
|
|
|
165
166
|
{ name: 'task', description: 'Task system CLI (delegate to cortex-task)' },
|
|
166
167
|
{ name: 'install latest', description: 'Install the latest version of Cortex from npm' },
|
|
167
168
|
{ name: 'config', description: 'Show resolved paths and initialization status' },
|
|
169
|
+
{ name: 'doctor', description: 'Health-check the install (runtime, login, platform, gateway); --fix to repair' },
|
|
168
170
|
{ name: 'feishu', description: 'Manage Feishu user-identity login (login / status / logout)' },
|
|
169
171
|
{ name: 'setup-gateway', description: 'Auto-detect Claude/PI configs and generate gateway.yaml + profiles.json' },
|
|
170
172
|
{ name: 'tui', description: 'Start the Terminal UI (TUI) client for local interaction' },
|
|
@@ -176,6 +178,8 @@ export function getCliHelp() {
|
|
|
176
178
|
{ description: 'Interactive init', command: 'cortex init' },
|
|
177
179
|
{ description: 'Init to custom directory', command: 'cortex init --home /tmp/my-cortex' },
|
|
178
180
|
{ description: 'Show resolved paths', command: 'cortex config' },
|
|
181
|
+
{ description: 'Health-check the install', command: 'cortex doctor' },
|
|
182
|
+
{ description: 'Diagnose and auto-repair', command: 'cortex doctor --fix' },
|
|
179
183
|
{ description: 'Re-generate gateway config', command: 'cortex setup-gateway' },
|
|
180
184
|
{ description: 'Start the server', command: 'cortex start' },
|
|
181
185
|
{ description: 'Stop the daemon', command: 'cortex daemon stop' },
|
|
@@ -551,6 +555,12 @@ export async function runCli(argv) {
|
|
|
551
555
|
}
|
|
552
556
|
case 'config':
|
|
553
557
|
return { exitCode: 0, stdout: getConfigOutput(), stderr: '' };
|
|
558
|
+
case 'doctor': {
|
|
559
|
+
if (rest.includes('--help') || rest.includes('-h')) {
|
|
560
|
+
return { exitCode: 0, stdout: getDoctorHelp(), stderr: '' };
|
|
561
|
+
}
|
|
562
|
+
return cmdDoctor(rest);
|
|
563
|
+
}
|
|
554
564
|
case 'feishu':
|
|
555
565
|
return cmdFeishu(rest);
|
|
556
566
|
case 'restart': {
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { type DoctorDeps, type FixActuators } from '../domain/system/doctor.js';
|
|
2
|
+
export interface CliResult {
|
|
3
|
+
exitCode: number;
|
|
4
|
+
stdout: string;
|
|
5
|
+
stderr: string;
|
|
6
|
+
}
|
|
7
|
+
export interface CmdDoctorDeps {
|
|
8
|
+
diag: DoctorDeps;
|
|
9
|
+
fix: FixActuators;
|
|
10
|
+
}
|
|
11
|
+
export declare function getDoctorHelp(): string;
|
|
12
|
+
export declare function cmdDoctor(args: string[], override?: Partial<CmdDoctorDeps>): Promise<CliResult>;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// input: argv (cortex doctor [--json] [--fix] [--help]) + optional injected deps
|
|
2
|
+
// output: cmdDoctor(args) → CliResult; getDoctorHelp() → help string
|
|
3
|
+
// pos: CLI wrapper for `cortex doctor`. Runs the diagnostic engine, optionally
|
|
4
|
+
// applies safe idempotent fixes, and renders a plain-text or JSON report.
|
|
5
|
+
// Exit code 1 when any check fails, else 0 (CLI Rule ④/exit-code).
|
|
6
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
7
|
+
import { formatHelp } from '../core/cli-utils.js';
|
|
8
|
+
import { runDiagnostics, applySafeFixes, createDefaultDoctorDeps, createDefaultFixActuators, } from '../domain/system/doctor.js';
|
|
9
|
+
export function getDoctorHelp() {
|
|
10
|
+
return formatHelp({
|
|
11
|
+
name: 'cortex doctor',
|
|
12
|
+
description: 'Health-check the Cortex installation — runtime, backend/login, messaging platform, gateway.',
|
|
13
|
+
usage: 'cortex doctor [options]',
|
|
14
|
+
options: [
|
|
15
|
+
{ flag: '--fix', description: 'Apply safe, idempotent repairs (generate missing tokens, create dirs, rebuild mcp-config)' },
|
|
16
|
+
{ flag: '--json', description: 'Emit the report as JSON' },
|
|
17
|
+
{ flag: '--help, -h', description: 'Show this help' },
|
|
18
|
+
],
|
|
19
|
+
examples: [
|
|
20
|
+
{ description: 'Run a read-only diagnosis', command: 'cortex doctor' },
|
|
21
|
+
{ description: 'Diagnose and auto-repair fixable issues', command: 'cortex doctor --fix' },
|
|
22
|
+
{ description: 'Machine-readable output', command: 'cortex doctor --json' },
|
|
23
|
+
],
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
const MARKER = {
|
|
27
|
+
pass: '[OK] ',
|
|
28
|
+
warn: '[WARN]',
|
|
29
|
+
fail: '[FAIL]',
|
|
30
|
+
skip: '[--] ',
|
|
31
|
+
};
|
|
32
|
+
function renderText(report, fixes) {
|
|
33
|
+
const lines = ['Cortex Doctor', ''];
|
|
34
|
+
for (const section of report.sections) {
|
|
35
|
+
lines.push(section.title);
|
|
36
|
+
for (const c of section.checks) {
|
|
37
|
+
lines.push(` ${MARKER[c.status]} ${c.label} — ${c.detail}`);
|
|
38
|
+
if (c.hint && (c.status === 'fail' || c.status === 'warn'))
|
|
39
|
+
lines.push(` ↳ ${c.hint}`);
|
|
40
|
+
}
|
|
41
|
+
lines.push('');
|
|
42
|
+
}
|
|
43
|
+
if (fixes.length > 0) {
|
|
44
|
+
lines.push('Fixes applied:');
|
|
45
|
+
for (const f of fixes)
|
|
46
|
+
lines.push(` ${f.applied ? '[OK] ' : '[--] '} ${f.label} — ${f.detail}`);
|
|
47
|
+
lines.push('');
|
|
48
|
+
}
|
|
49
|
+
const { pass, warn, fail } = report.counts;
|
|
50
|
+
lines.push(`Summary: ${pass} passed, ${warn} warning${warn === 1 ? '' : 's'}, ${fail} failed`);
|
|
51
|
+
if (fail > 0 || warn > 0) {
|
|
52
|
+
const anyFixable = report.sections.some(s => s.checks.some(c => c.fixable && (c.status === 'fail' || c.status === 'warn')));
|
|
53
|
+
if (anyFixable)
|
|
54
|
+
lines.push('Run `cortex doctor --fix` to auto-repair fixable issues.');
|
|
55
|
+
}
|
|
56
|
+
return lines.join('\n').trimEnd() + '\n';
|
|
57
|
+
}
|
|
58
|
+
export async function cmdDoctor(args, override) {
|
|
59
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
60
|
+
return { exitCode: 0, stdout: getDoctorHelp(), stderr: '' };
|
|
61
|
+
}
|
|
62
|
+
const asJson = args.includes('--json');
|
|
63
|
+
const doFix = args.includes('--fix');
|
|
64
|
+
const diag = override?.diag ?? createDefaultDoctorDeps();
|
|
65
|
+
const fix = override?.fix ?? createDefaultFixActuators();
|
|
66
|
+
let report = await runDiagnostics(diag);
|
|
67
|
+
let fixes = [];
|
|
68
|
+
if (doFix) {
|
|
69
|
+
fixes = await applySafeFixes(report, diag, fix);
|
|
70
|
+
report = await runDiagnostics(diag);
|
|
71
|
+
}
|
|
72
|
+
const stdout = asJson
|
|
73
|
+
? JSON.stringify({ ...report, fixes: doFix ? fixes : undefined }, null, 2) + '\n'
|
|
74
|
+
: renderText(report, fixes);
|
|
75
|
+
return { exitCode: report.ok ? 0 : 1, stdout, stderr: '' };
|
|
76
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
// @cortex-hook-version 2026.6.22-2
|
|
2
3
|
// input: stdin Claude Code PreToolUse event, node:http
|
|
3
4
|
// output: stdout updatedInput containing user answers received from Slack
|
|
4
5
|
// pos: PreToolUse hook: intercept AskUserQuestion and forward to Slack to collect answers
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
// @cortex-hook-version 2026.6.22-2
|
|
2
3
|
// input: stdin Claude Code PreToolUse event, node:http
|
|
3
4
|
// output: stdout permissionDecision (plan injected back after Slack approval)
|
|
4
5
|
// pos: PreToolUse hook: intercept ExitPlanMode and forward plan to Slack for approval
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
// @cortex-hook-version 2026.6.22-2
|
|
2
3
|
// input: stdin { channel, sessionId, sessionName, trigger, timestampIso } + env CORTEX_HOOK_*
|
|
3
4
|
// output: stdout — prompt to inject into the closing session (empty stdout = skip)
|
|
4
5
|
// pos: !new pre-close memory flush hook — recall valuable user and project info from the session, write to corresponding context files
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
// @cortex-hook-version 2026.6.22-2
|
|
2
3
|
// input: stdin JSON — Claude Code PostToolUse event or PI hook-bridge payload
|
|
3
4
|
// output: { matched: [...], hookSpecificOutput: { additionalContext: "..." } }
|
|
4
5
|
// pos: Read/Grep hook — check if file path matches scoped rules in ~/.cortex/rules/
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
// @cortex-hook-version 2026.6.22-2
|
|
2
3
|
// input: stdin Claude Code PreToolUse event, node:fs
|
|
3
4
|
// output: Direct-write target file + deny to prevent Claude from re-running built-in Edit/Write
|
|
4
5
|
// pos: PreToolUse hook: bypass Claude Code's hardcoded protection on .claude/ paths
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
// @cortex-hook-version 2026.6.22-2
|
|
2
3
|
// input: stdin JSON — Claude Code PreToolUse event payload
|
|
3
4
|
// output: stdout JSON — { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision, permissionDecisionReason } }
|
|
4
5
|
// pos: PreToolUse hook — intercepts Edit/Write on **/TASKS.yaml, checks project lock
|
|
@@ -15,6 +15,7 @@ import { buildSessionTag, buildUserProcessingMessage, makeFallbackNotifier, make
|
|
|
15
15
|
import { readFileSync } from 'fs';
|
|
16
16
|
import { createLogger } from '../core/log.js';
|
|
17
17
|
import { Icons } from '../core/icons.js';
|
|
18
|
+
import { t } from '../core/i18n.js';
|
|
18
19
|
import { getOutboundQueue } from '../store/outbound-queue.js';
|
|
19
20
|
import { buildDurableHooks } from './durable-helpers.js';
|
|
20
21
|
const log = createLogger('agent-runner');
|
|
@@ -46,7 +47,7 @@ export class AgentRunner {
|
|
|
46
47
|
// tryAnswerFromHuman returns false unless this exact channel is awaiting a human reply.
|
|
47
48
|
if (tryAnswerFromHuman(channel, ctx.userMessage || '')) {
|
|
48
49
|
const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
|
|
49
|
-
await adapter.postMessage(dest, { text: `${Icons.ok}
|
|
50
|
+
await adapter.postMessage(dest, { text: `${Icons.ok} ${t('subtask.replyDelivered')}` }).catch(() => { });
|
|
50
51
|
return;
|
|
51
52
|
}
|
|
52
53
|
if (conduitQueues.has(channel)) {
|
|
@@ -139,7 +140,7 @@ export class AgentRunner {
|
|
|
139
140
|
error: error,
|
|
140
141
|
channel, adapter, statusMsg, startTime,
|
|
141
142
|
executionId: capturedExecutionId,
|
|
142
|
-
sessionName, sessionId, threadAnchorId, userMessageTs: messageTs,
|
|
143
|
+
sessionName, sessionId, threadAnchorId, userMessageTs: messageTs, userMessage,
|
|
143
144
|
});
|
|
144
145
|
}
|
|
145
146
|
}
|
|
@@ -32,7 +32,10 @@ export async function runConversation(opts) {
|
|
|
32
32
|
const agentConfig = resolveAgentSlotConfigByName(defaultAgentName);
|
|
33
33
|
if (!agentConfig)
|
|
34
34
|
throw new Error(`Unknown default agent: ${defaultAgentName}`);
|
|
35
|
-
|
|
35
|
+
// USER.md profile is injected only on a session's FIRST turn (existingSessionId === null).
|
|
36
|
+
// Session resume keeps it in history thereafter, so re-sending it every turn just wastes tokens.
|
|
37
|
+
const isFreshSession = opts.existingSessionId === null;
|
|
38
|
+
const prompt = buildConversationPrompt(agentConfig, opts.userMessage, { includeUserContext: isFreshSession });
|
|
36
39
|
const project = projectStore.resolveFromMessage(opts.userMessage)?.id ?? 'general';
|
|
37
40
|
// Resolve profile: hardcoded agent profiles win; __active__ honors the optional override
|
|
38
41
|
// (scheduler) then the channel's active profile.
|
|
@@ -16,7 +16,7 @@ export declare function handleAgentSuccess({ result, channel, adapter, statusMsg
|
|
|
16
16
|
onAssistantMessage?: ((text: string) => void) | null;
|
|
17
17
|
registerContinuationSink?: ((sink: ContinuationSink) => void) | null;
|
|
18
18
|
}): Promise<void>;
|
|
19
|
-
export declare function handleAgentError({ error, channel, adapter, statusMsg, startTime, executionId, sessionName, sessionId, effectiveSessionId, threadAnchorId, userMessageTs }: {
|
|
19
|
+
export declare function handleAgentError({ error, channel, adapter, statusMsg, startTime, executionId, sessionName, sessionId, effectiveSessionId, threadAnchorId, userMessageTs, userMessage }: {
|
|
20
20
|
error: {
|
|
21
21
|
message: string;
|
|
22
22
|
cancelled?: boolean;
|
|
@@ -31,6 +31,7 @@ export declare function handleAgentError({ error, channel, adapter, statusMsg, s
|
|
|
31
31
|
effectiveSessionId?: string | null;
|
|
32
32
|
threadAnchorId?: string | null;
|
|
33
33
|
userMessageTs?: string | null;
|
|
34
|
+
userMessage?: string | null;
|
|
34
35
|
}): Promise<void>;
|
|
35
36
|
export declare function resumeAskUserQuestionGroup({ adapter, group, responseText }: {
|
|
36
37
|
adapter: PlatformAdapter;
|
|
@@ -25,6 +25,8 @@ import { buildContinuationSink } from './bg-continuation.js';
|
|
|
25
25
|
import { recordCost } from '../domain/costs/cost-tracker.js';
|
|
26
26
|
import { maybeNotifyCodexLowUsage } from '../domain/costs/codex-usage-monitor.js';
|
|
27
27
|
import { recordResume } from '../domain/costs/resume-registry.js';
|
|
28
|
+
import { isApiRateLimitError } from '../domain/agents/config.js';
|
|
29
|
+
import { isThrottled } from '../domain/costs/rate-limit-throttle.js';
|
|
28
30
|
import { normalizeSkillCommandPrefix } from '../domain/memory/skill-scanner.js';
|
|
29
31
|
import { getOutboundQueue } from '../store/outbound-queue.js';
|
|
30
32
|
import { buildDurableHooks, durablePost } from './durable-helpers.js';
|
|
@@ -169,7 +171,7 @@ async function backfillLedgerSessionId(result, channel) {
|
|
|
169
171
|
}
|
|
170
172
|
}
|
|
171
173
|
// --- Agent error handler ---
|
|
172
|
-
export async function handleAgentError({ error, channel, adapter, statusMsg, startTime, executionId, sessionName = null, sessionId = null, effectiveSessionId = null, threadAnchorId = null, userMessageTs = null }) {
|
|
174
|
+
export async function handleAgentError({ error, channel, adapter, statusMsg, startTime, executionId, sessionName = null, sessionId = null, effectiveSessionId = null, threadAnchorId = null, userMessageTs = null, userMessage = null }) {
|
|
173
175
|
if (executionId)
|
|
174
176
|
runningExecutions.fail(executionId, error.message);
|
|
175
177
|
const resolvedSessionId = effectiveSessionId || sessionId;
|
|
@@ -191,6 +193,18 @@ export async function handleAgentError({ error, channel, adapter, statusMsg, sta
|
|
|
191
193
|
await sealStatus(adapter, statusMsg, cancelledText, buildSealedStatusActionBlocks(cancelledText, { channel, sessionName, isDm: true }));
|
|
192
194
|
return;
|
|
193
195
|
}
|
|
196
|
+
// Thrown rate-limit error while the five-hour throttle is active: pause-and-resume instead of
|
|
197
|
+
// failing, mirroring the thread thrown path (domain/threads/runner.ts) and the graceful direct
|
|
198
|
+
// path (agent-runner handleDefaultAgentResult / edit-retry below). runningExecutions.fail already
|
|
199
|
+
// ran at the top. Only when a userMessage is available (direct/TUI turns) — manager-qa / edit
|
|
200
|
+
// callers without it fall through to the normal error path.
|
|
201
|
+
if (userMessage && isApiRateLimitError(error.message) && isThrottled()) {
|
|
202
|
+
finalizeLocalExecution({ executionId, status: 'failed', error: { message: 'Rate limited' }, durationS: elapsedS });
|
|
203
|
+
recordResume({ kind: 'direct', channel, userMessage, recordedAt: Date.now() });
|
|
204
|
+
const rateLimitText = `${Icons.warning} ${sessionTag}${t('status.rateLimitedExhausted')} (${elapsedStr})`;
|
|
205
|
+
await sealStatus(adapter, statusMsg, rateLimitText, buildSealedStatusActionBlocks(rateLimitText, { channel, sessionName, isDm: true }));
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
194
208
|
log.error('Agent error:', error.message);
|
|
195
209
|
finalizeLocalExecution({ executionId, status: 'failed', error, durationS: elapsedS });
|
|
196
210
|
const errorText = `${Icons.error} ${sessionTag}${t('status.error')} (${elapsedStr})`;
|
|
@@ -13,8 +13,9 @@ export interface ManagerQaDeps {
|
|
|
13
13
|
/** Post the question to a human-escalation channel (defaults to the platform adapter). */
|
|
14
14
|
postToChannel?: (channel: string, text: string) => void | Promise<void>;
|
|
15
15
|
}
|
|
16
|
-
/** Notice injected into the manager's pendingMessages
|
|
17
|
-
* Mirrors buildChildResultNotice's shape: states
|
|
16
|
+
/** Notice injected into the manager's pendingMessages — an AGENT-facing prompt (English, not i18n;
|
|
17
|
+
* mirrors the directives, which are not localized). Mirrors buildChildResultNotice's shape: states
|
|
18
|
+
* what is asked and how to respond. */
|
|
18
19
|
export declare function buildQuestionNotice(q: {
|
|
19
20
|
questionId: string;
|
|
20
21
|
fromTaskId: string | null;
|
|
@@ -14,6 +14,7 @@ import { resumeManagerForQuestion } from './thread-callback.js';
|
|
|
14
14
|
import { ctx as jobCtx } from '../domain/scheduling/job-registry.js';
|
|
15
15
|
import { getOutboundQueue, durablePost } from '../store/outbound-queue.js';
|
|
16
16
|
import { createLogger } from '../core/log.js';
|
|
17
|
+
import { t } from '../core/i18n.js';
|
|
17
18
|
const log = createLogger('manager-qa');
|
|
18
19
|
/** Central in-memory question store (daemon process). questionId → question. */
|
|
19
20
|
const questions = new Map();
|
|
@@ -46,28 +47,32 @@ async function defaultPostToChannel(channel, text) {
|
|
|
46
47
|
else
|
|
47
48
|
await adapter.postMessage(dest, { text });
|
|
48
49
|
}
|
|
49
|
-
/** Notice injected into the manager's pendingMessages
|
|
50
|
-
* Mirrors buildChildResultNotice's shape: states
|
|
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. */
|
|
51
53
|
export function buildQuestionNotice(q) {
|
|
52
|
-
const from = q.fromTaskId ?
|
|
54
|
+
const from = q.fromTaskId ? `subtask #${q.fromTaskId}` : 'a subtask';
|
|
53
55
|
return [
|
|
54
|
-
`[
|
|
56
|
+
`[Subtask question] ${from} hit something unclear/contradictory while executing and is checking your planning intent (you are its manager):`,
|
|
55
57
|
'',
|
|
56
|
-
|
|
58
|
+
`Question: ${q.question}`,
|
|
57
59
|
'',
|
|
58
|
-
'
|
|
59
|
-
` answer_subtask(question_id="${q.questionId}", answer="
|
|
60
|
-
'
|
|
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.',
|
|
61
63
|
].join('\n');
|
|
62
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). */
|
|
63
68
|
function buildHumanEscalationNotice(q) {
|
|
64
|
-
const from = q.fromTaskId ?
|
|
69
|
+
const from = q.fromTaskId ? t('subtask.fromTask', { taskId: q.fromTaskId }) : t('subtask.fromUnknown');
|
|
65
70
|
return [
|
|
66
|
-
|
|
71
|
+
`❓ ${t('subtask.escalateHeader', { from })}`,
|
|
67
72
|
'',
|
|
68
|
-
|
|
73
|
+
t('subtask.questionLabel', { question: q.question }),
|
|
69
74
|
'',
|
|
70
|
-
'
|
|
75
|
+
t('subtask.escalateReply'),
|
|
71
76
|
].join('\n');
|
|
72
77
|
}
|
|
73
78
|
/** Resolve the manager thread to ask: prefer an explicit thread parent; otherwise walk the task
|