@cortex-agent/server 2026.6.15 → 2026.6.18
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 +2 -2
- package/defaults/hooks/task-status-check.mjs +9 -7
- package/defaults/plugins/cortex-stage-gate/skills/task/SKILL.md +103 -16
- package/defaults/plugins/cortex-system/skills/orient/SKILL.md +6 -6
- package/defaults/plugins/cortex-system/skills/thread/SKILL.md +29 -35
- package/defaults/prompts/directives/manager.md +21 -11
- package/dist/agent-adapter/claude/spawn-args.d.ts +5 -0
- package/dist/agent-adapter/claude/spawn-args.js +6 -0
- package/dist/agent-adapter/types.d.ts +4 -0
- package/dist/core/task-parser.d.ts +6 -0
- package/dist/core/task-parser.js +10 -0
- package/dist/core/types/thread-types.d.ts +29 -0
- package/dist/domain/agents/facade.d.ts +4 -0
- package/dist/domain/agents/facade.js +3 -1
- package/dist/domain/mcp/core-server.js +15 -9
- package/dist/domain/mcp/tools/task-monitor.d.ts +2 -0
- package/dist/domain/mcp/tools/task-monitor.js +99 -0
- package/dist/domain/mcp/tools/thread-ops.js +50 -85
- package/dist/domain/scheduling/jobs/task-dispatch.js +12 -6
- package/dist/domain/tasks/dispatch-utils.d.ts +5 -0
- package/dist/domain/tasks/dispatch-utils.js +9 -1
- package/dist/domain/tasks/dispatcher.js +4 -4
- package/dist/domain/tasks/system/task-cli.d.ts +1 -0
- package/dist/domain/tasks/system/task-cli.js +82 -6
- package/dist/domain/tasks/system/task-mutations.d.ts +6 -1
- package/dist/domain/tasks/system/task-mutations.js +10 -1
- package/dist/domain/threads/hook-runner.js +1 -0
- package/dist/domain/threads/prompt-builder.js +15 -9
- package/dist/domain/threads/runner.d.ts +5 -0
- package/dist/domain/threads/runner.js +44 -11
- package/dist/domain/threads/state-machine.d.ts +9 -12
- package/dist/domain/threads/state-machine.js +27 -50
- package/dist/hooks/task-status-check.mjs +9 -7
- package/dist/orchestration/routing/webhook.js +38 -1
- package/dist/orchestration/thread-callback.d.ts +11 -1
- package/dist/orchestration/thread-callback.js +66 -30
- package/dist/platform/adapters/feishu.d.ts +11 -0
- package/dist/platform/adapters/feishu.js +74 -3
- package/package.json +1 -1
|
@@ -1,13 +1,16 @@
|
|
|
1
|
-
// input: MCP SDK,
|
|
2
|
-
// output: MCP stdio service, exposing remote_* tools, current_time,
|
|
1
|
+
// input: MCP SDK, remote-ops + time + thread control + task-monitor tool modules
|
|
2
|
+
// output: MCP stdio service, exposing remote_* tools, current_time, thread control tools, task_* tools
|
|
3
3
|
// pos: Core MCP server — thread agents load only this one (no Slack/cost/schedule tools).
|
|
4
|
-
//
|
|
4
|
+
// Delegation is via the task system (cortex-task CLI); thread control tools (abort/split/wait)
|
|
5
|
+
// let an agent steer its own thread; task_* tools monitor tasks. The agent-facing thread
|
|
6
|
+
// spawn/monitor tools (thread_start + status/result/list/list_templates/cancel) were removed.
|
|
5
7
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
6
8
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
7
9
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
8
10
|
import { registerTaskOpsTools } from './tools/task-ops.js';
|
|
9
11
|
import { registerTimeTools } from './tools/time.js';
|
|
10
12
|
import { registerThreadTools } from './tools/thread-ops.js';
|
|
13
|
+
import { registerTaskMonitorTools } from './tools/task-monitor.js';
|
|
11
14
|
import { isMainModule } from '../../core/utils.js';
|
|
12
15
|
import { createLogger } from '../../core/log.js';
|
|
13
16
|
import { CORTEX_VERSION } from '../../core/version.js';
|
|
@@ -17,6 +20,7 @@ const server = new McpServer({ name: 'cortex-core', version: CORTEX_VERSION });
|
|
|
17
20
|
registerTaskOpsTools(server);
|
|
18
21
|
registerTimeTools(server);
|
|
19
22
|
registerThreadTools(server);
|
|
23
|
+
registerTaskMonitorTools(server);
|
|
20
24
|
// --- Exported tool name list (for verification) ---
|
|
21
25
|
export const TOOL_NAMES = [
|
|
22
26
|
'remote_bash',
|
|
@@ -26,12 +30,14 @@ export const TOOL_NAMES = [
|
|
|
26
30
|
'remote_glob',
|
|
27
31
|
'remote_grep',
|
|
28
32
|
'current_time',
|
|
29
|
-
|
|
30
|
-
'
|
|
31
|
-
'
|
|
32
|
-
'
|
|
33
|
-
|
|
34
|
-
'
|
|
33
|
+
// DR-0015 control plane: an agent signals its own thread (abort / split / wait).
|
|
34
|
+
'thread_abort',
|
|
35
|
+
'thread_split',
|
|
36
|
+
'thread_wait',
|
|
37
|
+
// Task monitoring (delegation itself is via the cortex-task CLI).
|
|
38
|
+
'task_status',
|
|
39
|
+
'task_result',
|
|
40
|
+
'task_list',
|
|
35
41
|
];
|
|
36
42
|
// --- Start (called by barrel when run as standalone) ---
|
|
37
43
|
export async function startServer() {
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// input: McpServer, @core/task-parser (reads TASKS.yaml on disk)
|
|
2
|
+
// output: task_status / task_result / task_list read-only tool registrations
|
|
3
|
+
// pos: Agent-facing task monitoring. Delegation is done via the cortex-task CLI (add / spawn);
|
|
4
|
+
// these tools let an agent observe a task it created or depends on without shelling out.
|
|
5
|
+
// Read-only and disk-direct (TASKS.yaml is on the shared filesystem) — no daemon webhook,
|
|
6
|
+
// mirroring tools/context.ts. They replace the removed thread_status / thread_result /
|
|
7
|
+
// thread_list monitoring tools now that a task (not a thread) is the unit of delegation.
|
|
8
|
+
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
9
|
+
import { z } from 'zod';
|
|
10
|
+
import { scanAllTasks, isActionable, completedHashSet, filterTasks, } from '../../../core/task-parser.js';
|
|
11
|
+
/** Default project scope from env so an in-task agent need not re-declare it. null = all projects. */
|
|
12
|
+
function defaultProject(project) {
|
|
13
|
+
return project || process.env.CORTEX_TASK_PROJECT || process.env.CORTEX_PROJECT || null;
|
|
14
|
+
}
|
|
15
|
+
function statusView(task, completed) {
|
|
16
|
+
return {
|
|
17
|
+
id: task.id,
|
|
18
|
+
project: task.project,
|
|
19
|
+
text: task.text,
|
|
20
|
+
status: task.status,
|
|
21
|
+
actionable: isActionable(task, completed),
|
|
22
|
+
priority: task.priority,
|
|
23
|
+
template: task.template,
|
|
24
|
+
parent: task.parent,
|
|
25
|
+
depends_on: task.depends_on,
|
|
26
|
+
claimed_by: task.claimed_by,
|
|
27
|
+
blocked_by: task.blocked_by,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
function jsonResult(payload) {
|
|
31
|
+
return { content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }] };
|
|
32
|
+
}
|
|
33
|
+
export function registerTaskMonitorTools(server) {
|
|
34
|
+
// --- task_status ---
|
|
35
|
+
server.tool('task_status', 'Query a task\'s current lifecycle state: status (open/pending/done), whether it is actionable, who claimed it, what blocks it, its dependencies and parent. Read-only view of TASKS.yaml. Use to poll a child task you created via `cortex-task spawn` (or any task you depend on).', {
|
|
36
|
+
task_id: z.string().describe('Task id (4-char hex).'),
|
|
37
|
+
project: z.string().optional().describe('Project to scope the lookup. Defaults to CORTEX_TASK_PROJECT / CORTEX_PROJECT, else all projects.'),
|
|
38
|
+
}, { readOnlyHint: true }, async ({ task_id, project }) => {
|
|
39
|
+
try {
|
|
40
|
+
const all = scanAllTasks(defaultProject(project));
|
|
41
|
+
const task = all.find((t) => t.id === task_id);
|
|
42
|
+
if (!task)
|
|
43
|
+
return { content: [{ type: 'text', text: `task ${task_id} not found` }], isError: true };
|
|
44
|
+
return jsonResult(statusView(task, completedHashSet(all)));
|
|
45
|
+
}
|
|
46
|
+
catch (e) {
|
|
47
|
+
return { content: [{ type: 'text', text: `task_status error: ${e.message}` }], isError: true };
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
// --- task_result ---
|
|
51
|
+
server.tool('task_result', 'Fetch a task\'s outcome: its done/blocked state, success criteria (done_when), completion note, and block reason. If the task is not yet terminal, the result is partial (a note flags this). Read-only. Use after a child task you depend on turns terminal to inspect what it produced.', {
|
|
52
|
+
task_id: z.string().describe('Task id (4-char hex).'),
|
|
53
|
+
project: z.string().optional().describe('Project to scope the lookup. Defaults to CORTEX_TASK_PROJECT / CORTEX_PROJECT, else all projects.'),
|
|
54
|
+
}, { readOnlyHint: true }, async ({ task_id, project }) => {
|
|
55
|
+
try {
|
|
56
|
+
const all = scanAllTasks(defaultProject(project));
|
|
57
|
+
const task = all.find((t) => t.id === task_id);
|
|
58
|
+
if (!task)
|
|
59
|
+
return { content: [{ type: 'text', text: `task ${task_id} not found` }], isError: true };
|
|
60
|
+
const terminal = task.status === 'done' || !!task.blocked_by;
|
|
61
|
+
return jsonResult({
|
|
62
|
+
id: task.id,
|
|
63
|
+
project: task.project,
|
|
64
|
+
text: task.text,
|
|
65
|
+
status: task.status,
|
|
66
|
+
terminal,
|
|
67
|
+
...(terminal ? {} : { note: 'task not yet terminal — result is partial' }),
|
|
68
|
+
done_when: task.done_when,
|
|
69
|
+
completed_at: task.completed_at,
|
|
70
|
+
completed_note: task.completed_note,
|
|
71
|
+
blocked_by: task.blocked_by,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
catch (e) {
|
|
75
|
+
return { content: [{ type: 'text', text: `task_result error: ${e.message}` }], isError: true };
|
|
76
|
+
}
|
|
77
|
+
});
|
|
78
|
+
// --- task_list ---
|
|
79
|
+
server.tool('task_list', 'List tasks, newest-first by file order, optionally filtered by project and status. Each entry is a compact status view. Use to see the children you spawned under a parent, or the actionable queue of a project.', {
|
|
80
|
+
project: z.string().optional().describe('Project to scope. Defaults to CORTEX_TASK_PROJECT / CORTEX_PROJECT, else all projects.'),
|
|
81
|
+
status: z.string().optional().describe('Filter by status: actionable / open / blocked / in-progress / paused / pending / completed / approval-needed / approved.'),
|
|
82
|
+
parent: z.string().optional().describe('Only tasks whose parent is this task id (the children you spawned).'),
|
|
83
|
+
limit: z.number().optional().describe('Max tasks to return (default 50).'),
|
|
84
|
+
}, { readOnlyHint: true }, async ({ project, status, parent, limit }) => {
|
|
85
|
+
try {
|
|
86
|
+
const proj = defaultProject(project);
|
|
87
|
+
const all = scanAllTasks(proj);
|
|
88
|
+
const completed = completedHashSet(all);
|
|
89
|
+
let tasks = filterTasks(all, { project: proj, status }, completed);
|
|
90
|
+
if (parent)
|
|
91
|
+
tasks = tasks.filter((t) => t.parent === parent);
|
|
92
|
+
const out = tasks.slice(0, limit ?? 50).map((t) => statusView(t, completed));
|
|
93
|
+
return jsonResult({ count: out.length, tasks: out });
|
|
94
|
+
}
|
|
95
|
+
catch (e) {
|
|
96
|
+
return { content: [{ type: 'text', text: `task_list error: ${e.message}` }], isError: true };
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
}
|
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
// input: McpServer, webhook proxy,
|
|
2
|
-
// output:
|
|
3
|
-
// pos:
|
|
4
|
-
//
|
|
5
|
-
//
|
|
1
|
+
// input: McpServer, webhook proxy, CORTEX_THREAD_ID env
|
|
2
|
+
// output: thread_abort / thread_split / thread_wait registrations (DR-0015 control plane)
|
|
3
|
+
// pos: Self-control of the CALLER'S OWN thread, proxied through the daemon webhook. An agent
|
|
4
|
+
// signals its own thread (CORTEX_THREAD_ID) and the runner reads metadata.pendingControl at
|
|
5
|
+
// the step boundary — no artifact string markers. The agent-facing thread spawn/monitor
|
|
6
|
+
// tools (thread_start + thread_status/result/list/list_templates/cancel) were REMOVED:
|
|
7
|
+
// delegation is now done via the task system (cortex-task spawn / add) and monitored via the
|
|
8
|
+
// read-only task_* tools. thread_wait is the suspend primitive paired with cortex-task spawn.
|
|
6
9
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
7
10
|
import { z } from 'zod';
|
|
8
11
|
// Thread operations proxied through the daemon webhook (separate process, no shared memory with
|
|
@@ -20,102 +23,64 @@ async function proxyThreadOp(action, payload) {
|
|
|
20
23
|
return data.data;
|
|
21
24
|
}
|
|
22
25
|
export function registerThreadTools(server) {
|
|
23
|
-
// ---
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
}, async ({
|
|
26
|
+
// --- Control plane (DR-0015): self-control of the CALLER'S OWN thread ---
|
|
27
|
+
// All three target CORTEX_THREAD_ID (the thread you are running inside) — you never pass a
|
|
28
|
+
// threadId. They write a structured intent the runner consumes at the next step boundary, then
|
|
29
|
+
// your step should end. Calling outside a thread (no CORTEX_THREAD_ID) is an error.
|
|
30
|
+
const selfThreadId = () => {
|
|
31
|
+
const id = process.env.CORTEX_THREAD_ID;
|
|
32
|
+
if (!id)
|
|
33
|
+
throw new Error('not running inside a thread (CORTEX_THREAD_ID unset) — control tools only work from within a thread');
|
|
34
|
+
return id;
|
|
35
|
+
};
|
|
36
|
+
// --- thread_abort ---
|
|
37
|
+
server.tool('thread_abort', 'Abort (escalate) YOUR OWN thread when the task cannot be completed as scoped — terminal state `aborted`, distinct from `failed`. Use only when truly blocked: a missing prerequisite, contradictory requirements, or a task far bigger / mis-scoped than its description. A precise diagnosis is the most valuable thing you can produce — it beats a half-done grind. For a dispatch task this blocks the task with your diagnosis and escalates it (its manager, or a human, re-plans). Normal retries, minor issues, or disagreements with the plan are NOT abort cases. After calling, end your step.', {
|
|
38
|
+
kind: z.enum(['too-big', 'mis-scoped', 'blocked-external']).describe('Why you are aborting: "too-big" (needs decomposition into independent units), "mis-scoped" (the task definition is wrong) — both route to a re-planning manager; "blocked-external" (a missing external resource / dependency you cannot obtain) routes to a human.'),
|
|
39
|
+
diagnosis: z.string().min(1).describe('Required one-line diagnosis of the real structure / blocker. Becomes the abort reason and the task block reason.'),
|
|
40
|
+
}, async ({ kind, diagnosis }) => {
|
|
38
41
|
try {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
}
|
|
42
|
-
const projectId = project || process.env.CORTEX_PROJECT || undefined;
|
|
43
|
-
const channel = process.env.SLACK_CHANNEL || undefined;
|
|
44
|
-
const depth = parseInt(process.env.CORTEX_THREAD_DEPTH || '0', 10) || 0;
|
|
45
|
-
const parentSessionId = process.env.CORTEX_SESSION_ID || null;
|
|
46
|
-
const parentThreadId = process.env.CORTEX_THREAD_ID || null;
|
|
47
|
-
const parentChannel = process.env.SLACK_CHANNEL || null;
|
|
48
|
-
const parentProfile = process.env.CORTEX_PROFILE || null;
|
|
49
|
-
const result = await proxyThreadOp('start', {
|
|
50
|
-
template, agent, message, projectId, channel, depth, parentSessionId, parentThreadId, parentChannel, parentProfile,
|
|
51
|
-
goal, done_when, context_files, deliverable_path, budget_usd, wait,
|
|
52
|
-
});
|
|
42
|
+
const threadId = selfThreadId();
|
|
43
|
+
const result = await proxyThreadOp('control', { threadId, control: { action: 'abort', kind, diagnosis } });
|
|
53
44
|
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
54
45
|
}
|
|
55
46
|
catch (e) {
|
|
56
|
-
return { content: [{ type: 'text', text: `
|
|
47
|
+
return { content: [{ type: 'text', text: `thread_abort error: ${e.message}` }], isError: true };
|
|
57
48
|
}
|
|
58
49
|
});
|
|
59
|
-
// ---
|
|
60
|
-
server.tool('
|
|
61
|
-
|
|
62
|
-
|
|
50
|
+
// --- thread_split ---
|
|
51
|
+
server.tool('thread_split', 'Propose a decomposition of YOUR OWN (dispatch) task instead of doing it: the task is decomposed into the given children (keep-parent — your task becomes the join/acceptance node depending on all children), unclaimed, and the children flow through the normal dispatch queue. Use when the task is actually several independently verifiable units. After calling, end your step.', {
|
|
52
|
+
subtasks: z.array(z.object({
|
|
53
|
+
key: z.string().optional().describe('Local key for sibling depends_on references within this batch.'),
|
|
54
|
+
text: z.string().describe('What this child must do (imperative, one unit of work).'),
|
|
55
|
+
template: z.string().optional().describe('Thread template the child runs under (e.g. coder-review). Inherits the parent template when omitted.'),
|
|
56
|
+
why: z.string().optional().describe('Why this child exists.'),
|
|
57
|
+
done_when: z.string().optional().describe('Verifiable completion criteria for this child.'),
|
|
58
|
+
priority: z.string().optional(),
|
|
59
|
+
plan: z.string().optional(),
|
|
60
|
+
depends_on: z.array(z.string()).optional().describe('Sibling keys (from this batch) or existing 4-hex task ids this child depends on.'),
|
|
61
|
+
})).min(1).describe('Non-empty array of child subtasks (decomposeTask shape).'),
|
|
62
|
+
}, async ({ subtasks }) => {
|
|
63
63
|
try {
|
|
64
|
-
const
|
|
64
|
+
const threadId = selfThreadId();
|
|
65
|
+
const result = await proxyThreadOp('control', { threadId, control: { action: 'split', subtasks } });
|
|
65
66
|
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
66
67
|
}
|
|
67
68
|
catch (e) {
|
|
68
|
-
return { content: [{ type: 'text', text: `
|
|
69
|
+
return { content: [{ type: 'text', text: `thread_split error: ${e.message}` }], isError: true };
|
|
69
70
|
}
|
|
70
71
|
});
|
|
71
|
-
// ---
|
|
72
|
-
server.tool('
|
|
73
|
-
|
|
74
|
-
|
|
72
|
+
// --- thread_wait ---
|
|
73
|
+
server.tool('thread_wait', 'Suspend YOUR OWN thread until its awaited children finish (DR-0014 parent suspension). Call this after creating child tasks you depend on (cortex-task spawn) — you are re-entered once ALL awaited children are terminal, with their results injected. If nothing is left to wait on, the thread simply continues. After calling, end your step.', {
|
|
74
|
+
on_tasks: z.array(z.string()).optional().describe('Optional explicit child task ids to wait on (otherwise inferred from the thread / task tree).'),
|
|
75
|
+
on_threads: z.array(z.string()).optional().describe('Optional explicit child thread ids to wait on (otherwise inferred from spawned children).'),
|
|
76
|
+
}, async ({ on_tasks, on_threads }) => {
|
|
75
77
|
try {
|
|
76
|
-
const
|
|
78
|
+
const threadId = selfThreadId();
|
|
79
|
+
const result = await proxyThreadOp('control', { threadId, control: { action: 'wait', on_tasks, on_threads } });
|
|
77
80
|
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
78
81
|
}
|
|
79
82
|
catch (e) {
|
|
80
|
-
return { content: [{ type: 'text', text: `
|
|
81
|
-
}
|
|
82
|
-
});
|
|
83
|
-
// --- thread_list ---
|
|
84
|
-
server.tool('thread_list', 'List threads you started, newest first. scope "mine" (default) returns threads spawned from your current session; "project" returns all threads in the current project. Each entry has threadId, status, template/agent, step count, cost, and timestamps — use thread_status / thread_result for full detail.', {
|
|
85
|
-
scope: z.enum(['mine', 'project']).optional().describe('"mine" (default): threads you started from this session. "project": all threads in the current project (any starter).'),
|
|
86
|
-
limit: z.number().optional().describe('Max threads to return (default 50, newest first).'),
|
|
87
|
-
view: z.enum(['flat', 'tree']).optional().describe('"flat" (default): newest-first list. "tree": nested thread trees (children under parents) with per-root rollups (nodeCount / totalCostUsd / byStatus / maxDepth).'),
|
|
88
|
-
}, { readOnlyHint: true }, async ({ scope, limit, view }) => {
|
|
89
|
-
try {
|
|
90
|
-
const parentSessionId = process.env.CORTEX_SESSION_ID || null;
|
|
91
|
-
const projectId = process.env.CORTEX_PROJECT || undefined;
|
|
92
|
-
const result = await proxyThreadOp('list-threads', { scope: scope || 'mine', parentSessionId, projectId, limit, view });
|
|
93
|
-
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
94
|
-
}
|
|
95
|
-
catch (e) {
|
|
96
|
-
return { content: [{ type: 'text', text: `thread_list error: ${e.message}` }], isError: true };
|
|
97
|
-
}
|
|
98
|
-
});
|
|
99
|
-
// --- thread_list_templates ---
|
|
100
|
-
server.tool('thread_list_templates', 'List available thread templates (multi-agent pipelines) and agents (single ad-hoc roles) with their descriptions. Use to discover what can be passed to thread_start.', {}, { readOnlyHint: true }, async () => {
|
|
101
|
-
try {
|
|
102
|
-
const result = await proxyThreadOp('list', {});
|
|
103
|
-
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
104
|
-
}
|
|
105
|
-
catch (e) {
|
|
106
|
-
return { content: [{ type: 'text', text: `thread_list_templates error: ${e.message}` }], isError: true };
|
|
107
|
-
}
|
|
108
|
-
});
|
|
109
|
-
// --- thread_cancel ---
|
|
110
|
-
server.tool('thread_cancel', 'Cancel a running thread. Returns whether a running thread was found and cancelled.', {
|
|
111
|
-
threadId: z.string().describe('Thread id (thr_XXXX) to cancel'),
|
|
112
|
-
}, async ({ threadId }) => {
|
|
113
|
-
try {
|
|
114
|
-
const result = await proxyThreadOp('cancel', { threadId });
|
|
115
|
-
return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
|
|
116
|
-
}
|
|
117
|
-
catch (e) {
|
|
118
|
-
return { content: [{ type: 'text', text: `thread_cancel error: ${e.message}` }], isError: true };
|
|
83
|
+
return { content: [{ type: 'text', text: `thread_wait error: ${e.message}` }], isError: true };
|
|
119
84
|
}
|
|
120
85
|
});
|
|
121
86
|
}
|
|
@@ -11,9 +11,9 @@ import * as pendingTaskTracker from '../../tasks/pending-tracker.js';
|
|
|
11
11
|
import { sessionStore } from '../../../store/session-registry-repo.js';
|
|
12
12
|
import { selectAndClaimTask, computeNextInterval, updateScheduleInterval } from '../../tasks/dispatcher.js';
|
|
13
13
|
import { taskMutator } from '../../tasks/mutator.js';
|
|
14
|
-
import { createThread,
|
|
14
|
+
import { createThread, detectSplitFromControl, clearPendingControl } from '../../threads/index.js';
|
|
15
15
|
import { runThread as runThreadExec } from '../../threads/runner.js';
|
|
16
|
-
import { processSplitOutcome, processAbortOutcome } from '../../tasks/dispatch-utils.js';
|
|
16
|
+
import { processSplitOutcome, processAbortOutcome, formatWorkerAbortReason } from '../../tasks/dispatch-utils.js';
|
|
17
17
|
import { threadStore } from '../../../store/thread-repo.js';
|
|
18
18
|
import { computeElapsed, buildSessionTag } from '../../../core/status-format.js';
|
|
19
19
|
import { finalizeThreadSuccess } from './_shared.js';
|
|
@@ -133,6 +133,9 @@ async function executeDispatchTask({ selected, selectedTask, channel, scheduleTa
|
|
|
133
133
|
adapter, channel: channel, threadAnchorId: statusMsg?.messageId || null, statusMsg, startTime,
|
|
134
134
|
destination: { type: 'project-report', projectId: selectedTask.project || channel, trigger: 'task-dispatch', sessionId: '' },
|
|
135
135
|
onToolUse: icb?.onToolUse ?? null, onPlanWritten: icb?.onPlanWritten ?? null, onAskUserQuestion: icb?.onAskUserQuestion ?? null,
|
|
136
|
+
// DR-0015 problem 2: block the owning task at abort time, BEFORE the onEnd task-status-check
|
|
137
|
+
// hook runs, so the hook sees a blocked task and does not unclaim it back to actionable.
|
|
138
|
+
onAbort: async ({ taskId, reason }) => { await taskMutator.block(taskId, formatWorkerAbortReason(reason)); },
|
|
136
139
|
extraHooks: {
|
|
137
140
|
onEnd: {
|
|
138
141
|
command: 'node hooks/task-status-check.mjs',
|
|
@@ -193,16 +196,19 @@ async function executeDispatchTask({ selected, selectedTask, channel, scheduleTa
|
|
|
193
196
|
dispatchFailureCounts.delete(selectedTask.id); // abort is judgment, not fault
|
|
194
197
|
return { success: !abortOutcome.error, skipped: false, note: abortOutcome.error ? `abort-block failed: ${abortOutcome.error}` : `[${selectedTask.project}] ${abortOutcome.note}` };
|
|
195
198
|
}
|
|
196
|
-
// DR-0014: the worker proposed a
|
|
197
|
-
//
|
|
198
|
-
//
|
|
199
|
+
// DR-0014: the worker proposed a decomposition (thread_split) instead of doing the task.
|
|
200
|
+
// The signal rides on metadata.pendingControl (DR-0015 problem 1), read via detectSplitFromControl.
|
|
201
|
+
// Decompose keep-parent (task becomes the join/acceptance node) and unclaim; the children flow
|
|
202
|
+
// through the normal dispatch queue.
|
|
199
203
|
const splitOutcome = await processSplitOutcome({ threadId: thread.id, taskId: selectedTask.id ?? null, project: selectedTask.project }, {
|
|
200
|
-
detect:
|
|
204
|
+
detect: detectSplitFromControl,
|
|
201
205
|
// system:true — no agent lock in the dispatch path; defer if a foreign lock exists.
|
|
202
206
|
decompose: (p, t, subs, tid, opts) => taskMutator.decompose(p, t, subs, tid, { ...opts, system: true }),
|
|
203
207
|
unclaim: (tid) => taskMutator.unclaim(tid),
|
|
204
208
|
});
|
|
205
209
|
if (splitOutcome.handled) {
|
|
210
|
+
// Control intent consumed — clear it so a re-read never re-fires.
|
|
211
|
+
await clearPendingControl(thread.id);
|
|
206
212
|
const text = splitOutcome.error
|
|
207
213
|
? `${Icons.error} [${selectedTask.project}] ${selectedTask.text.substring(0, 80)} | [SPLIT] proposal invalid: ${splitOutcome.error} — task unclaimed`
|
|
208
214
|
: `🌿 [${selectedTask.project}] ${selectedTask.text.substring(0, 80)} | ${splitOutcome.note}`;
|
|
@@ -71,6 +71,11 @@ export interface AbortOutcome {
|
|
|
71
71
|
note?: string;
|
|
72
72
|
error?: string;
|
|
73
73
|
}
|
|
74
|
+
/** Canonical block reason for a worker-aborted task. Single source so the runner's
|
|
75
|
+
* pre-onEnd block (DR-0015 problem 2) and processAbortOutcome produce byte-identical
|
|
76
|
+
* reasons — a second block with the same reason is a no-op commit (git porcelain sees no
|
|
77
|
+
* change), so blocking in both places is safe. */
|
|
78
|
+
export declare function formatWorkerAbortReason(raw: string | null): string;
|
|
74
79
|
/** Process an aborted dispatch thread: the worker said "I can't" ([ABORT: <reason>]) —
|
|
75
80
|
* block the task with the abort reason. taskMutator.block publishes task.blocked, which
|
|
76
81
|
* wakes a manager thread waiting on this task (its parent re-plans); with no manager the
|
|
@@ -167,6 +167,14 @@ async function processSplitOutcome(args, deps) {
|
|
|
167
167
|
await deps.unclaim(args.taskId);
|
|
168
168
|
return { handled: true, note: `split into ${detection.subtasks.length} subtask(s) — parent kept as join node` };
|
|
169
169
|
}
|
|
170
|
+
/** Canonical block reason for a worker-aborted task. Single source so the runner's
|
|
171
|
+
* pre-onEnd block (DR-0015 problem 2) and processAbortOutcome produce byte-identical
|
|
172
|
+
* reasons — a second block with the same reason is a no-op commit (git porcelain sees no
|
|
173
|
+
* change), so blocking in both places is safe. */
|
|
174
|
+
export function formatWorkerAbortReason(raw) {
|
|
175
|
+
const r = (raw || 'no reason given').replace(/\s+/g, ' ').trim() || 'no reason given';
|
|
176
|
+
return `worker-abort: ${r}`.slice(0, 280);
|
|
177
|
+
}
|
|
170
178
|
/** Process an aborted dispatch thread: the worker said "I can't" ([ABORT: <reason>]) —
|
|
171
179
|
* block the task with the abort reason. taskMutator.block publishes task.blocked, which
|
|
172
180
|
* wakes a manager thread waiting on this task (its parent re-plans); with no manager the
|
|
@@ -182,7 +190,7 @@ async function processAbortOutcome(args, deps) {
|
|
|
182
190
|
return { handled: false };
|
|
183
191
|
}
|
|
184
192
|
const rawReason = (thread.abortReason || 'no reason given').replace(/\s+/g, ' ').trim();
|
|
185
|
-
const reason =
|
|
193
|
+
const reason = formatWorkerAbortReason(thread.abortReason);
|
|
186
194
|
const result = await deps.block(args.taskId, reason);
|
|
187
195
|
if (!result.success) {
|
|
188
196
|
return { handled: true, error: result.message };
|
|
@@ -260,13 +260,13 @@ function buildDispatchPrompt(task) {
|
|
|
260
260
|
];
|
|
261
261
|
sections.push(isolation.join('\n'));
|
|
262
262
|
const escalation = [
|
|
263
|
-
'## If This Task Is Mis-Scoped (
|
|
263
|
+
'## If This Task Is Mis-Scoped (thread_abort)',
|
|
264
264
|
'',
|
|
265
|
-
'If during execution you discover this task is far bigger than its description suggests, or its scope is wrong (multiple independent work units crammed together, missing prerequisites, contradictory requirements), do NOT grind through it.
|
|
265
|
+
'If during execution you discover this task is far bigger than its description suggests, or its scope is wrong (multiple independent work units crammed together, missing prerequisites, contradictory requirements), do NOT grind through it. Call the `thread_abort` tool:',
|
|
266
266
|
'',
|
|
267
|
-
'
|
|
267
|
+
' thread_abort(kind="too-big", diagnosis="<one-line diagnosis of what the real structure is>")',
|
|
268
268
|
'',
|
|
269
|
-
'The task will be blocked with your diagnosis and escalated: its manager (or a human) re-plans the decomposition with full context. A precise diagnosis is the most valuable thing you can produce here — it beats a half-done grind every time.',
|
|
269
|
+
'The task will be blocked with your diagnosis and escalated: its manager (or a human) re-plans the decomposition with full context. A precise diagnosis is the most valuable thing you can produce here — it beats a half-done grind every time. (Use kind="too-big" or "mis-scoped" for structural problems, "blocked-external" for a missing external resource.) If instead you can already see the right decomposition, call `thread_split` with the subtasks.',
|
|
270
270
|
];
|
|
271
271
|
sections.push(escalation.join('\n'));
|
|
272
272
|
const completion = [
|
|
@@ -19,7 +19,7 @@ const WRITE_COMMANDS = new Set([
|
|
|
19
19
|
'claim', 'unclaim', 'pause', 'resume', 'pending', 'complete', 'uncomplete',
|
|
20
20
|
'request-approval', 'approve', 'clear-approval',
|
|
21
21
|
'block', 'unblock',
|
|
22
|
-
'add', 'edit', 'batch-edit', 'bulk-add', 'decompose',
|
|
22
|
+
'add', 'spawn', 'edit', 'batch-edit', 'bulk-add', 'decompose',
|
|
23
23
|
'assign-ids', 'validate', 'stop',
|
|
24
24
|
'lock-acquire', 'lock-release', 'lock-status', 'lock-force-release',
|
|
25
25
|
]);
|
|
@@ -35,7 +35,7 @@ const COMMANDS_NEEDING_PROJECT = new Set([
|
|
|
35
35
|
'claim', 'unclaim', 'pause', 'resume', 'pending', 'complete', 'uncomplete',
|
|
36
36
|
'request-approval', 'approve', 'clear-approval',
|
|
37
37
|
'block', 'unblock',
|
|
38
|
-
'add', 'edit', 'batch-edit', 'bulk-add', 'decompose',
|
|
38
|
+
'add', 'spawn', 'edit', 'batch-edit', 'bulk-add', 'decompose',
|
|
39
39
|
'lock-acquire', 'lock-release', 'lock-force-release',
|
|
40
40
|
]);
|
|
41
41
|
const COMMON_FLAGS = new Set(['--base-dir', '--project', '--task-id']);
|
|
@@ -46,7 +46,8 @@ const COMMAND_FLAG_ALLOWLIST = {
|
|
|
46
46
|
show: new Set([...COMMON_FLAGS, '--json', '--task-ids']),
|
|
47
47
|
deps: new Set([...COMMON_FLAGS, '--json', '--task-ids']),
|
|
48
48
|
tree: new Set([...COMMON_FLAGS]),
|
|
49
|
-
add: new Set([...COMMON_FLAGS, '--text', '--why', '--done-when', '--plan', '--priority', '--template', '--depends-on', '--auto-lock']),
|
|
49
|
+
add: new Set([...COMMON_FLAGS, '--text', '--why', '--done-when', '--plan', '--priority', '--template', '--depends-on', '--auto-lock', '--no-notify']),
|
|
50
|
+
spawn: new Set([...COMMON_FLAGS, '--text', '--why', '--done-when', '--plan', '--priority', '--template', '--depends-on', '--auto-lock']),
|
|
50
51
|
lint: new Set([...COMMON_FLAGS, '--json']),
|
|
51
52
|
stats: new Set([...COMMON_FLAGS, '--json']),
|
|
52
53
|
claim: new Set([...COMMON_FLAGS, '--task', '--agent']),
|
|
@@ -126,7 +127,8 @@ const HELP_CONFIG = {
|
|
|
126
127
|
{
|
|
127
128
|
heading: 'Mutation',
|
|
128
129
|
commands: [
|
|
129
|
-
{ name: 'add', description: 'Add new task (--text, --why, --done-when, --plan, --template ...)' },
|
|
130
|
+
{ name: 'add', description: 'Add new task (--text, --why, --done-when, --plan, --template ...). Captures origin from env for completion wake.' },
|
|
131
|
+
{ name: 'spawn', description: 'Create a child of the current task (CORTEX_TASK_ID or --task-id); parent becomes a join node. Pair with the thread_wait tool to await it.' },
|
|
130
132
|
{ name: 'bulk-add', description: 'Bulk-add tasks from JSON file (--file, use "key" for intra-batch deps)' },
|
|
131
133
|
{ name: 'edit', description: 'Edit task fields (--text, --why, --done-when, ...)' },
|
|
132
134
|
{ name: 'batch-edit', description: 'Apply same edit to multiple tasks (--task-ids)' },
|
|
@@ -181,6 +183,7 @@ const HELP_CONFIG = {
|
|
|
181
183
|
{ flag: '--dry-run', description: 'Preview without executing (stop, decompose)' },
|
|
182
184
|
{ flag: '--keep-parent', description: 'decompose: keep the original task as a join/acceptance node depending on all subtasks (DR-0014 task tree)' },
|
|
183
185
|
{ flag: '--auto-lock', description: 'Auto-acquire project lock before write (does NOT auto-release)' },
|
|
186
|
+
{ flag: '--no-notify', description: 'add: do not capture origin session/channel (suppresses completion wake)' },
|
|
184
187
|
{ flag: '--skip-verify', description: 'Skip completion evidence check for `complete` (escape hatch)' },
|
|
185
188
|
{ flag: '--skip-verify-reason <text>', description: 'Reason for skipping verification (logged in result)' },
|
|
186
189
|
{ flag: '--help', description: 'Show this help' },
|
|
@@ -263,6 +266,7 @@ function createDefaults() {
|
|
|
263
266
|
force: false,
|
|
264
267
|
showDeps: false,
|
|
265
268
|
autoLock: false,
|
|
269
|
+
noNotify: false,
|
|
266
270
|
};
|
|
267
271
|
}
|
|
268
272
|
function splitCommand(argv) {
|
|
@@ -356,6 +360,10 @@ function parseOptions(args, values, seen) {
|
|
|
356
360
|
seen.add(token);
|
|
357
361
|
values.autoLock = true;
|
|
358
362
|
}
|
|
363
|
+
else if (token === '--no-notify') {
|
|
364
|
+
seen.add(token);
|
|
365
|
+
values.noNotify = true;
|
|
366
|
+
}
|
|
359
367
|
else {
|
|
360
368
|
throw cliError(`Unknown argument: ${token}`);
|
|
361
369
|
}
|
|
@@ -399,6 +407,14 @@ function validateCommand(command, values) {
|
|
|
399
407
|
if (command === 'add' && !values.text) {
|
|
400
408
|
throw cliError('--text is required for add');
|
|
401
409
|
}
|
|
410
|
+
if (command === 'spawn') {
|
|
411
|
+
if (!values.text)
|
|
412
|
+
throw cliError('--text is required for spawn');
|
|
413
|
+
const parent = values.taskId || process.env.CORTEX_TASK_ID;
|
|
414
|
+
if (!parent) {
|
|
415
|
+
throw cliError('spawn needs a current task: run inside a dispatched task (CORTEX_TASK_ID set) or pass --task-id <parent>');
|
|
416
|
+
}
|
|
417
|
+
}
|
|
402
418
|
if (command === 'add' && values.template && (values.template === 'default' || values.template === 'scheduler')) {
|
|
403
419
|
throw cliError(`Template '${values.template}' is forbidden. The 'default' and 'scheduler' templates are single-agent templates with no review pipeline and are not allowed for task dispatch. Use a multi-agent review template instead (run 'cortex-task --help' to see available templates).`);
|
|
404
420
|
}
|
|
@@ -409,6 +425,17 @@ function validateCommand(command, values) {
|
|
|
409
425
|
throw cliError('--project is required');
|
|
410
426
|
}
|
|
411
427
|
}
|
|
428
|
+
/** Context-aware defaults: a running agent already knows its project (and current task) via
|
|
429
|
+
* CORTEX_* env. Fill --project from env for write commands so agents don't re-declare it.
|
|
430
|
+
* `spawn` lives under the current task, so it prefers that task's project. */
|
|
431
|
+
function applyContextDefaults(command, values) {
|
|
432
|
+
if (!values.project && COMMANDS_NEEDING_PROJECT.has(command)) {
|
|
433
|
+
const envProject = (command === 'spawn' ? process.env.CORTEX_TASK_PROJECT : null)
|
|
434
|
+
|| process.env.CORTEX_PROJECT || null;
|
|
435
|
+
if (envProject)
|
|
436
|
+
values.project = envProject;
|
|
437
|
+
}
|
|
438
|
+
}
|
|
412
439
|
function parseArgs(argv) {
|
|
413
440
|
const split = splitCommand(argv);
|
|
414
441
|
const command = split.command ?? 'list';
|
|
@@ -416,6 +443,7 @@ function parseArgs(argv) {
|
|
|
416
443
|
const seen = new Set();
|
|
417
444
|
parseOptions(split.args, values, seen);
|
|
418
445
|
validateFlagsForCommand(command, seen);
|
|
446
|
+
applyContextDefaults(command, values);
|
|
419
447
|
validateCommand(command, values);
|
|
420
448
|
return { command, values };
|
|
421
449
|
}
|
|
@@ -635,6 +663,53 @@ function handleDecompose(v) {
|
|
|
635
663
|
function handleStop(v) {
|
|
636
664
|
return v.dryRun ? stopTaskDryRun(v.taskId) : stopTask(v.taskId);
|
|
637
665
|
}
|
|
666
|
+
/** Capture provenance from env so task.completed can wake the originating session (Problem 1).
|
|
667
|
+
* Suppressed by --no-notify. Returns null when no env context (e.g. a human at a raw shell). */
|
|
668
|
+
function readOriginFromEnv(noNotify) {
|
|
669
|
+
if (noNotify)
|
|
670
|
+
return null;
|
|
671
|
+
const channel = process.env.SLACK_CHANNEL || process.env.FEISHU_CHANNEL || null;
|
|
672
|
+
const sessionId = process.env.CORTEX_SESSION_ID || null;
|
|
673
|
+
const threadId = process.env.CORTEX_THREAD_ID || null;
|
|
674
|
+
if (!channel && !sessionId && !threadId)
|
|
675
|
+
return null;
|
|
676
|
+
return { sessionId, channel, threadId };
|
|
677
|
+
}
|
|
678
|
+
const MAX_SPAWN_DEPTH = 6;
|
|
679
|
+
/** `spawn`: create a single child under the current task (CORTEX_TASK_ID, or --task-id override),
|
|
680
|
+
* reusing decompose's keep-parent join semantics. The child inherits the parent template unless
|
|
681
|
+
* overridden. No origin is captured — an in-task agent resumes via the thread_wait path, not the
|
|
682
|
+
* session-wake path. A parent-chain depth cap bounds runaway recursion (replaces thread tree guard). */
|
|
683
|
+
function handleSpawn(v) {
|
|
684
|
+
const parentId = v.taskId || process.env.CORTEX_TASK_ID || null;
|
|
685
|
+
if (!parentId) {
|
|
686
|
+
return { success: false, message: 'spawn needs a current task (CORTEX_TASK_ID) or --task-id <parent>' };
|
|
687
|
+
}
|
|
688
|
+
// Depth guard: walk the parent chain.
|
|
689
|
+
const tasks = scanAllTasks(v.project);
|
|
690
|
+
const byId = new Map(tasks.filter((t) => t.id).map((t) => [t.id, t]));
|
|
691
|
+
let cur = byId.get(parentId);
|
|
692
|
+
for (let depth = 0; cur && cur.parent; depth++) {
|
|
693
|
+
if (depth >= MAX_SPAWN_DEPTH) {
|
|
694
|
+
return { success: false, message: `spawn refused: task tree deeper than ${MAX_SPAWN_DEPTH} — fold the work in or escalate instead of nesting further` };
|
|
695
|
+
}
|
|
696
|
+
cur = byId.get(cur.parent);
|
|
697
|
+
}
|
|
698
|
+
const subtask = {
|
|
699
|
+
text: v.text,
|
|
700
|
+
why: v.why || undefined,
|
|
701
|
+
done_when: v.doneWhen || undefined,
|
|
702
|
+
template: v.template || undefined,
|
|
703
|
+
priority: v.priority || undefined,
|
|
704
|
+
plan: v.plan || undefined,
|
|
705
|
+
depends_on: v.dependsOn.length > 0 ? v.dependsOn : undefined,
|
|
706
|
+
};
|
|
707
|
+
const result = decomposeTask(v.project, null, [subtask], parentId, { keepParent: true });
|
|
708
|
+
if (result.success && result.child_ids?.length) {
|
|
709
|
+
return { success: true, message: `Spawned child of ${parentId}`, child_id: result.child_ids[0], parent_id: parentId };
|
|
710
|
+
}
|
|
711
|
+
return result;
|
|
712
|
+
}
|
|
638
713
|
// ── Lock helpers ──
|
|
639
714
|
function formatLockResult(project, owner, lock, opts) {
|
|
640
715
|
return {
|
|
@@ -706,7 +781,8 @@ const WRITE_HANDLERS = {
|
|
|
706
781
|
'clear-approval': (v) => clearApprovalTask(v.task, v.project, v.taskId),
|
|
707
782
|
block: (v) => blockTask(v.task, v.project, v.reason, v.taskId),
|
|
708
783
|
unblock: (v) => unblockTask(v.task, v.project, v.taskId),
|
|
709
|
-
add: (v) => addTask(v.project, v.text, v.why, v.doneWhen, v.priority || 'medium', v.template, v.dependsOn.length > 0 ? v.dependsOn : null, v.plan),
|
|
784
|
+
add: (v) => addTask(v.project, v.text, v.why, v.doneWhen, v.priority || 'medium', v.template, v.dependsOn.length > 0 ? v.dependsOn : null, v.plan, readOriginFromEnv(v.noNotify)),
|
|
785
|
+
spawn: handleSpawn,
|
|
710
786
|
edit: handleEdit,
|
|
711
787
|
'batch-edit': handleBatchEdit,
|
|
712
788
|
decompose: handleDecompose,
|
|
@@ -731,7 +807,7 @@ const WRITE_HANDLERS = {
|
|
|
731
807
|
'lock-status': handleLockStatus,
|
|
732
808
|
'lock-force-release': handleLockForceRelease,
|
|
733
809
|
};
|
|
734
|
-
const LOCK_GUARD_COMMANDS = new Set(['add', 'edit', 'batch-edit', 'bulk-add', 'decompose']);
|
|
810
|
+
const LOCK_GUARD_COMMANDS = new Set(['add', 'spawn', 'edit', 'batch-edit', 'bulk-add', 'decompose']);
|
|
735
811
|
const LOCK_GUARD_ASSIGN_IDS = 'assign-ids';
|
|
736
812
|
function runWrite(command, values) {
|
|
737
813
|
if (command === 'lock-status') {
|