@cortex-agent/server 2026.6.15 → 2026.6.18-2
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 +27 -0
- package/dist/platform/adapters/feishu.js +136 -4
- package/package.json +1 -1
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
export interface TaskOrigin {
|
|
2
|
+
sessionId?: string | null;
|
|
3
|
+
channel?: string | null;
|
|
4
|
+
threadId?: string | null;
|
|
5
|
+
}
|
|
1
6
|
interface BulkTaskInput {
|
|
2
7
|
key: string;
|
|
3
8
|
text: string;
|
|
@@ -10,7 +15,7 @@ interface BulkTaskInput {
|
|
|
10
15
|
gpu?: string;
|
|
11
16
|
'gpu-count'?: number;
|
|
12
17
|
}
|
|
13
|
-
declare function addTask(project: string, text: string | null, why: string | null, doneWhen: string | null, priority?: string, template?: string | null, dependsOn?: string[] | null, plan?: string | null): {
|
|
18
|
+
declare function addTask(project: string, text: string | null, why: string | null, doneWhen: string | null, priority?: string, template?: string | null, dependsOn?: string[] | null, plan?: string | null, origin?: TaskOrigin | null): {
|
|
14
19
|
success: boolean;
|
|
15
20
|
message: string;
|
|
16
21
|
task_id?: undefined;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as fs from 'node:fs';
|
|
2
2
|
import { collectAllExistingHashes, generateHash } from './task-id-utils.js';
|
|
3
3
|
import { editTask, findTask, getTasksPath, readTasks, VALID_PRIORITIES, validateTemplateName, writeTasks } from './task-lifecycle-edit.js';
|
|
4
|
-
function addTask(project, text, why, doneWhen, priority = 'medium', template = null, dependsOn = null, plan = null) {
|
|
4
|
+
function addTask(project, text, why, doneWhen, priority = 'medium', template = null, dependsOn = null, plan = null, origin = null) {
|
|
5
5
|
if (!text || text === 'null') {
|
|
6
6
|
return { success: false, message: '--text is required and must not be empty' };
|
|
7
7
|
}
|
|
@@ -45,6 +45,9 @@ function addTask(project, text, why, doneWhen, priority = 'medium', template = n
|
|
|
45
45
|
completed_at: null,
|
|
46
46
|
completed_note: null,
|
|
47
47
|
pending_at: null,
|
|
48
|
+
origin_session_id: origin?.sessionId ?? null,
|
|
49
|
+
origin_channel: origin?.channel ?? null,
|
|
50
|
+
origin_thread_id: origin?.threadId ?? null,
|
|
48
51
|
};
|
|
49
52
|
tasks.push(newTask);
|
|
50
53
|
writeTasks(project, tasks);
|
|
@@ -128,6 +131,9 @@ function decomposeTask(project, originalText, subtasks, taskId = null, options =
|
|
|
128
131
|
completed_at: null,
|
|
129
132
|
completed_note: null,
|
|
130
133
|
pending_at: null,
|
|
134
|
+
origin_session_id: null,
|
|
135
|
+
origin_channel: null,
|
|
136
|
+
origin_thread_id: null,
|
|
131
137
|
});
|
|
132
138
|
}
|
|
133
139
|
if (keepParent) {
|
|
@@ -254,6 +260,9 @@ function bulkAddTasks(project, inputs) {
|
|
|
254
260
|
completed_at: null,
|
|
255
261
|
completed_note: null,
|
|
256
262
|
pending_at: null,
|
|
263
|
+
origin_session_id: null,
|
|
264
|
+
origin_channel: null,
|
|
265
|
+
origin_thread_id: null,
|
|
257
266
|
};
|
|
258
267
|
tasks.push(newTask);
|
|
259
268
|
created.push({ key: inp.key.trim(), id: taskId, text: inp.text });
|
|
@@ -34,6 +34,7 @@ function buildHookContext(threadId, phase, previousAgent) {
|
|
|
34
34
|
artifactContent,
|
|
35
35
|
userMessage: thread.userMessage,
|
|
36
36
|
totalCostUsd: thread.totalCostUsd,
|
|
37
|
+
pendingControlAction: thread.metadata?.pendingControl?.action ?? null,
|
|
37
38
|
};
|
|
38
39
|
}
|
|
39
40
|
/** Execute a hook script and parse its JSON result. Returns { insertAgent: false } on any error.
|
|
@@ -123,15 +123,21 @@ export function pickStepTemplate(agentConfig, stage) {
|
|
|
123
123
|
/** System-level protocol preamble injected into every step prompt of threads that own a workspace artifact. */
|
|
124
124
|
export const THREAD_PROTOCOL_PREAMBLE = [
|
|
125
125
|
'[Cortex Thread Protocol]',
|
|
126
|
-
'You are executing inside a Cortex thread.
|
|
127
|
-
'
|
|
128
|
-
'
|
|
129
|
-
'
|
|
130
|
-
'
|
|
131
|
-
'
|
|
132
|
-
'
|
|
133
|
-
'with
|
|
134
|
-
'
|
|
126
|
+
'You are executing inside a Cortex thread. Control of the thread is done by calling tools, NOT by',
|
|
127
|
+
'writing markers in the artifact — the artifact is plain prose and mentioning a control keyword in',
|
|
128
|
+
'it does nothing.',
|
|
129
|
+
'If the task cannot be completed (missing dependencies, contradictory requirements, or repeated',
|
|
130
|
+
'unrecoverable failures), call the `thread_abort` tool with a kind (too-big | mis-scoped |',
|
|
131
|
+
'blocked-external) and a one-line diagnosis to terminate the thread — terminal state `aborted`,',
|
|
132
|
+
'distinct from `failed`. Use this only when truly blocked: normal retries, minor issues, or',
|
|
133
|
+
'disagreements with the plan are not abort cases.',
|
|
134
|
+
'Decomposition: if your task is actually several independently verifiable units, call the',
|
|
135
|
+
'`thread_split` tool with the subtasks instead of grinding through it.',
|
|
136
|
+
'Delegation (DR-0014): you may spawn child threads via the `thread_start` tool (pass a contract:',
|
|
137
|
+
'goal / done_when / deliverable_path / budget_usd). After spawning awaited children, call the',
|
|
138
|
+
'`thread_wait` tool to suspend; you are re-entered once ALL awaited children finish, with their',
|
|
139
|
+
'results injected. Acceptance before trust: verify each child deliverable against its done_when',
|
|
140
|
+
'yourself (read files, run tests) — never accept a child\'s self-report as evidence.',
|
|
135
141
|
].join('\n');
|
|
136
142
|
// --- Prompt assembly ---
|
|
137
143
|
function buildPromptVars(thread, lastStep) {
|
|
@@ -71,6 +71,11 @@ declare function recordStepOutcome(threadId: string, stepCtx: StepContext, resul
|
|
|
71
71
|
declare function evaluateAndTransition(threadId: string, stepCtx: StepContext, ctx: ThreadContext, opts: RunThreadOptions): Promise<boolean>;
|
|
72
72
|
/** Read final artifact, flush VM, build the run result. */
|
|
73
73
|
declare function finalizeThread(threadId: string, ctx: ThreadContext): Promise<ThreadRunResult>;
|
|
74
|
+
/** Terminate a thread by agent abort and, BEFORE onEnd hooks run, hand the owning task to the
|
|
75
|
+
* caller's onAbort so it can reach a terminal (blocked) state in time (DR-0015 problem 2).
|
|
76
|
+
* No-op on the task side for non-dispatch threads (metadata has no taskId) or when the caller
|
|
77
|
+
* did not inject onAbort. Exported for unit testing. */
|
|
78
|
+
export declare function finalizeAbortedThread(threadId: string, meta: ThreadRecord['metadata'], reason: string | null, opts: Pick<RunThreadOptions, 'onAbort'>): Promise<void>;
|
|
74
79
|
declare function runThread(threadId: string, opts: RunThreadOptions): Promise<ThreadRunResult>;
|
|
75
80
|
declare function continueThread(threadId: string, userMessage: string, opts: RunThreadOptions): Promise<ThreadRunResult>;
|
|
76
81
|
/** Re-enter a parent thread that was suspended via [WAIT_CHILDREN]. Unlike continueThread,
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// pos: runtime execution engine for the Thread system
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
5
|
import { threadStore } from '../../store/thread-repo.js';
|
|
6
|
-
import { resolveNextStep, buildStepPrompt, recordStepResult, evaluateTransitions, completeThread, failThread, abortThread,
|
|
6
|
+
import { resolveNextStep, buildStepPrompt, recordStepResult, evaluateTransitions, completeThread, failThread, abortThread, peekPendingControl, clearPendingControl, tryEnterWaiting, checkContractBudget, isAdHocThread, getSessionKey, getTemplate, readArtifact, resolveSystemVars, } from './index.js';
|
|
7
7
|
import { runAgent, getClaudeMode, getActiveBackend, getActiveProfile } from '../agents/index.js';
|
|
8
8
|
import { Icons } from '../../core/icons.js';
|
|
9
9
|
import { closeSessionsByPrefix } from '../agents/index.js';
|
|
@@ -165,6 +165,8 @@ async function executeAndAwaitAgent(threadId, stepCtx, callbacks, ctx, opts) {
|
|
|
165
165
|
trigger: meta?.trigger || undefined,
|
|
166
166
|
threadId,
|
|
167
167
|
threadDepth: meta?.depth ?? 0,
|
|
168
|
+
taskId: meta?.taskId ?? null,
|
|
169
|
+
taskProject: meta?.taskProject ?? null,
|
|
168
170
|
useCoreMcp: true,
|
|
169
171
|
sessionName: stepCtx.sessionName,
|
|
170
172
|
claudeAgent: agentConfig.claudeAgent || null,
|
|
@@ -297,6 +299,17 @@ async function finalizeThread(threadId, ctx) {
|
|
|
297
299
|
executionId: finalThread.steps[finalThread.steps.length - 1]?.executionId ?? null,
|
|
298
300
|
};
|
|
299
301
|
}
|
|
302
|
+
/** Terminate a thread by agent abort and, BEFORE onEnd hooks run, hand the owning task to the
|
|
303
|
+
* caller's onAbort so it can reach a terminal (blocked) state in time (DR-0015 problem 2).
|
|
304
|
+
* No-op on the task side for non-dispatch threads (metadata has no taskId) or when the caller
|
|
305
|
+
* did not inject onAbort. Exported for unit testing. */
|
|
306
|
+
export async function finalizeAbortedThread(threadId, meta, reason, opts) {
|
|
307
|
+
await abortThread(threadId, reason);
|
|
308
|
+
const taskId = meta?.taskId ?? null;
|
|
309
|
+
if (taskId && opts.onAbort) {
|
|
310
|
+
await opts.onAbort({ taskId, project: meta?.taskProject ?? null, reason });
|
|
311
|
+
}
|
|
312
|
+
}
|
|
300
313
|
async function runThread(threadId, opts) {
|
|
301
314
|
const ctx = initThreadContext(threadId, opts);
|
|
302
315
|
let enteredWaiting = false;
|
|
@@ -313,26 +326,46 @@ async function runThread(threadId, opts) {
|
|
|
313
326
|
const callbacks = setupStepCallbacks(threadId, stepCtx, ctx, opts);
|
|
314
327
|
const result = await executeAndAwaitAgent(threadId, stepCtx, callbacks, ctx, opts);
|
|
315
328
|
await recordStepOutcome(threadId, stepCtx, result, ctx, opts);
|
|
316
|
-
//
|
|
317
|
-
//
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
329
|
+
// Out-of-band control plane (DR-0015 problem 1): the agent signals abort / split / wait by
|
|
330
|
+
// calling the thread_abort / thread_split / thread_wait MCP tools, which write a typed
|
|
331
|
+
// metadata.pendingControl on this thread. Read it here at the step boundary — never scan the
|
|
332
|
+
// artifact (prose mentioning "[ABORT]" no longer triggers anything). Higher precedence than
|
|
333
|
+
// transitions.
|
|
334
|
+
const control = peekPendingControl(threadId);
|
|
335
|
+
// Agent-initiated abort. Global check. Loop exits → onEnd hook still fires.
|
|
336
|
+
if (control?.action === 'abort') {
|
|
337
|
+
await clearPendingControl(threadId);
|
|
338
|
+
const reason = control.diagnosis ?? null;
|
|
339
|
+
// DR-0015 problem 2: abort the thread AND block the owning task here, BEFORE the onEnd
|
|
340
|
+
// hook runs below — otherwise task-status-check sees a still-claimed task and unclaims it.
|
|
341
|
+
await finalizeAbortedThread(threadId, ctx.meta, reason, opts);
|
|
321
342
|
if (ctx.stream) {
|
|
322
|
-
const reasonStr =
|
|
343
|
+
const reasonStr = reason ? `: ${reason}` : '';
|
|
323
344
|
const abortLabel = formatAgentStageLabel(stepCtx.agentSlotId, stepCtx.stage);
|
|
324
345
|
ctx.stream.emitText(`${Icons.stopped} Thread aborted by *${abortLabel}*${reasonStr}`);
|
|
325
346
|
}
|
|
326
347
|
break;
|
|
327
348
|
}
|
|
328
|
-
//
|
|
329
|
-
//
|
|
349
|
+
// Split proposal (DR-0014): the worker called thread_split with a typed subtask array. Leave
|
|
350
|
+
// metadata.pendingControl IN PLACE (do NOT clear) and break — the thread terminates and the
|
|
351
|
+
// dispatch path (processSplitOutcome) consumes control.subtasks to decompose keep-parent.
|
|
352
|
+
if (control?.action === 'split') {
|
|
353
|
+
if (ctx.stream) {
|
|
354
|
+
const splitLabel = formatAgentStageLabel(stepCtx.agentSlotId, stepCtx.stage);
|
|
355
|
+
const n = Array.isArray(control.subtasks) ? control.subtasks.length : 0;
|
|
356
|
+
ctx.stream.emitText(`${Icons.arrowRight} Thread split by *${splitLabel}* into ${n} subtask(s)`);
|
|
357
|
+
}
|
|
358
|
+
break;
|
|
359
|
+
}
|
|
360
|
+
// Parent suspension (DR-0014): the agent called thread_wait. Checked after abort/split,
|
|
361
|
+
// before transitions. Three outcomes:
|
|
330
362
|
// - live awaited children remain → thread enters 'waiting' (resumed by thread-callback
|
|
331
363
|
// when the last child turns terminal); skip onEnd — it fires once, at true termination.
|
|
332
364
|
// - all awaited children already terminal (callback won the race) and their results sit
|
|
333
365
|
// in pendingMessages → re-enter the loop immediately so the same agent processes them.
|
|
334
|
-
// -
|
|
335
|
-
if (
|
|
366
|
+
// - signal but nothing to wait on or process → fall through to normal transitions.
|
|
367
|
+
if (control?.action === 'wait') {
|
|
368
|
+
await clearPendingControl(threadId);
|
|
336
369
|
if (await tryEnterWaiting(threadId)) {
|
|
337
370
|
enteredWaiting = true;
|
|
338
371
|
const n = threadStore.get(threadId)?.metadata?.waitingOn?.length ?? 0;
|
|
@@ -31,14 +31,15 @@ interface StepResultInput {
|
|
|
31
31
|
export declare function recordStepResult(threadId: string, agentSlotId: AgentSlotId, result: StepResultInput): Promise<AgentStep>;
|
|
32
32
|
export declare function evaluateTransitions(threadId: string): TransitionResult;
|
|
33
33
|
export declare function cancelThread(threadId: string): Promise<boolean>;
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
/**
|
|
40
|
-
*
|
|
41
|
-
|
|
34
|
+
export type PendingControl = NonNullable<ThreadRecord['metadata']>['pendingControl'];
|
|
35
|
+
/** Peek the thread's pending control signal (does NOT clear it). Returns null when none set. */
|
|
36
|
+
export declare function peekPendingControl(threadId: string): PendingControl | null;
|
|
37
|
+
/** Clear the thread's pending control signal so an intent fires exactly once. */
|
|
38
|
+
export declare function clearPendingControl(threadId: string): Promise<void>;
|
|
39
|
+
/** Derive a split detection from a thread's pending control signal — the dispatch path's
|
|
40
|
+
* injected `detect` (replaces the old artifact-scanning detectSplitMarker). The subtask array
|
|
41
|
+
* was validated as a typed tool argument, so the only "error" case is an empty array. */
|
|
42
|
+
export declare function detectSplitFromControl(threadId: string): SplitDetection;
|
|
42
43
|
/** Try to suspend the thread until its waited-on children finish. Inside a single mutate
|
|
43
44
|
* (serialized with the callback side via the store mutex), filter waitingOn down to
|
|
44
45
|
* children that still exist and are non-terminal; additionally (DR-0014 §8) snapshot live
|
|
@@ -55,10 +56,6 @@ export interface SplitDetection {
|
|
|
55
56
|
subtasks: any[] | null;
|
|
56
57
|
error: string | null;
|
|
57
58
|
}
|
|
58
|
-
/** Detect a `[SPLIT]` decomposition proposal in the artifact: the marker followed by a
|
|
59
|
-
* ```json fenced block containing `{ "subtasks": [...] }`. Parse failures are surfaced
|
|
60
|
-
* (not swallowed) so the dispatch path can report them instead of silently dropping. */
|
|
61
|
-
export declare function detectSplitMarker(threadId: string): SplitDetection;
|
|
62
59
|
/** Terminate the thread with status='aborted'. Idempotent — returns false if thread is already terminal. */
|
|
63
60
|
export declare function abortThread(threadId: string, reason: string | null): Promise<boolean>;
|
|
64
61
|
export declare function completeThread(threadId: string): Promise<boolean>;
|
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
// input: thread-store, template-loader, prompt-builder, utils, artifact-io
|
|
3
3
|
// output: createThread / addAgentToThread /
|
|
4
4
|
// resolveNextStep / evaluateTransitions / recordStepResult / completeThread /
|
|
5
|
-
// failThread / cancelThread / abortThread /
|
|
6
|
-
//
|
|
5
|
+
// failThread / cancelThread / abortThread / tryEnterWaiting /
|
|
6
|
+
// peekPendingControl / clearPendingControl / detectSplitFromControl (DR-0015 control plane)
|
|
7
7
|
import { mkdirSync, writeFileSync, readFileSync } from 'fs';
|
|
8
8
|
import * as path from 'path';
|
|
9
9
|
import { WORKSPACE_DIR } from '../../core/utils.js';
|
|
@@ -13,7 +13,6 @@ const log = createLogger('state-machine');
|
|
|
13
13
|
import { getTemplate, getAgent } from './template-loader.js';
|
|
14
14
|
import { resolveAgentSlotConfigByName, resolveTemplateAgents, resolveActiveAgentName } from './prompt-builder.js';
|
|
15
15
|
import { resolveStageName, parseTarget } from './utils.js';
|
|
16
|
-
import { readArtifact } from './artifact-io.js';
|
|
17
16
|
import { checkContractBudget } from './contract.js';
|
|
18
17
|
import { scanAllTasks } from '../../core/task-parser.js';
|
|
19
18
|
// --- Agent slot helpers ---
|
|
@@ -346,31 +345,32 @@ export async function cancelThread(threadId) {
|
|
|
346
345
|
log.info(`Cancelled thread ${threadId}`);
|
|
347
346
|
return true;
|
|
348
347
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
const m = ABORT_MARKER_RE.exec(content);
|
|
356
|
-
if (!m)
|
|
357
|
-
return { aborted: false, reason: null };
|
|
358
|
-
const raw = m[1] != null ? m[1].trim() : '';
|
|
359
|
-
return { aborted: true, reason: raw.length > 0 ? raw : null };
|
|
360
|
-
}
|
|
361
|
-
// --- Wait-on-children + split markers (DR-0014) ---
|
|
362
|
-
const WAIT_MARKER_RE = /\[WAIT_CHILDREN\]/;
|
|
363
|
-
/** Detect `[WAIT_CHILDREN]` in the last step's output or in the artifact. The marker alone
|
|
364
|
-
* does not suspend the thread — tryEnterWaiting() additionally requires live children. */
|
|
365
|
-
export function detectWaitMarker(threadId) {
|
|
348
|
+
/** Peek the thread's pending control signal (does NOT clear it). Returns null when none set. */
|
|
349
|
+
export function peekPendingControl(threadId) {
|
|
350
|
+
return threadStore.get(threadId)?.metadata?.pendingControl ?? null;
|
|
351
|
+
}
|
|
352
|
+
/** Clear the thread's pending control signal so an intent fires exactly once. */
|
|
353
|
+
export async function clearPendingControl(threadId) {
|
|
366
354
|
const thread = threadStore.get(threadId);
|
|
367
|
-
if (!thread)
|
|
368
|
-
return
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
355
|
+
if (!thread?.metadata?.pendingControl)
|
|
356
|
+
return;
|
|
357
|
+
await threadStore.mutate(threadId, (t) => {
|
|
358
|
+
if (t.metadata)
|
|
359
|
+
t.metadata.pendingControl = null;
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
/** Derive a split detection from a thread's pending control signal — the dispatch path's
|
|
363
|
+
* injected `detect` (replaces the old artifact-scanning detectSplitMarker). The subtask array
|
|
364
|
+
* was validated as a typed tool argument, so the only "error" case is an empty array. */
|
|
365
|
+
export function detectSplitFromControl(threadId) {
|
|
366
|
+
const control = peekPendingControl(threadId);
|
|
367
|
+
if (!control || control.action !== 'split')
|
|
368
|
+
return { split: false, subtasks: null, error: null };
|
|
369
|
+
const subtasks = control.subtasks;
|
|
370
|
+
if (!Array.isArray(subtasks) || subtasks.length === 0) {
|
|
371
|
+
return { split: true, subtasks: null, error: 'thread_split called with an empty subtasks array' };
|
|
372
|
+
}
|
|
373
|
+
return { split: true, subtasks, error: null };
|
|
374
374
|
}
|
|
375
375
|
function isTerminal(status) {
|
|
376
376
|
return status === 'completed' || status === 'failed' || status === 'cancelled' || status === 'aborted';
|
|
@@ -438,29 +438,6 @@ export async function tryEnterWaiting(threadId) {
|
|
|
438
438
|
}
|
|
439
439
|
return entered;
|
|
440
440
|
}
|
|
441
|
-
const SPLIT_MARKER_RE = /\[SPLIT\]/;
|
|
442
|
-
const SPLIT_JSON_FENCE_RE = /\[SPLIT\][\s\S]*?```json\s*\n([\s\S]*?)\n\s*```/;
|
|
443
|
-
/** Detect a `[SPLIT]` decomposition proposal in the artifact: the marker followed by a
|
|
444
|
-
* ```json fenced block containing `{ "subtasks": [...] }`. Parse failures are surfaced
|
|
445
|
-
* (not swallowed) so the dispatch path can report them instead of silently dropping. */
|
|
446
|
-
export function detectSplitMarker(threadId) {
|
|
447
|
-
const content = readArtifact(threadId) || '';
|
|
448
|
-
if (!SPLIT_MARKER_RE.test(content))
|
|
449
|
-
return { split: false, subtasks: null, error: null };
|
|
450
|
-
const fence = SPLIT_JSON_FENCE_RE.exec(content);
|
|
451
|
-
if (!fence)
|
|
452
|
-
return { split: true, subtasks: null, error: '[SPLIT] marker present but no ```json fenced block follows' };
|
|
453
|
-
try {
|
|
454
|
-
const parsed = JSON.parse(fence[1]);
|
|
455
|
-
if (!parsed || !Array.isArray(parsed.subtasks) || parsed.subtasks.length === 0) {
|
|
456
|
-
return { split: true, subtasks: null, error: '[SPLIT] JSON must be an object with a non-empty "subtasks" array' };
|
|
457
|
-
}
|
|
458
|
-
return { split: true, subtasks: parsed.subtasks, error: null };
|
|
459
|
-
}
|
|
460
|
-
catch (e) {
|
|
461
|
-
return { split: true, subtasks: null, error: `[SPLIT] JSON parse failed: ${e?.message || e}` };
|
|
462
|
-
}
|
|
463
|
-
}
|
|
464
441
|
/** Terminate the thread with status='aborted'. Idempotent — returns false if thread is already terminal. */
|
|
465
442
|
export async function abortThread(threadId, reason) {
|
|
466
443
|
const thread = threadStore.get(threadId);
|
|
@@ -119,13 +119,15 @@ async function main() {
|
|
|
119
119
|
|
|
120
120
|
if (!project || !taskId) { noop(); return; }
|
|
121
121
|
|
|
122
|
-
//
|
|
123
|
-
//
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
//
|
|
127
|
-
//
|
|
128
|
-
|
|
122
|
+
// Out-of-band control intent (DR-0015): the agent signalled abort/split/wait via a tool, not
|
|
123
|
+
// by writing a marker into the artifact. Read the typed signal — never scan the artifact (prose
|
|
124
|
+
// mentioning "[ABORT]"/"[SPLIT]" must not trip this).
|
|
125
|
+
// - split: the task is INTENTIONALLY not done — the dispatcher decomposes it keep-parent and
|
|
126
|
+
// unclaims right after this hook returns. Don't burn an agent turn nagging. (The runner
|
|
127
|
+
// leaves pendingControl set for the dispatch path, so it is still present here.)
|
|
128
|
+
// - abort: the runner already blocked the task BEFORE this hook (DR-0015 problem 2) and cleared
|
|
129
|
+
// the control, so the blocked-by guard below covers it; this is belt-and-suspenders.
|
|
130
|
+
if (ctx.pendingControlAction === 'split' || ctx.pendingControlAction === 'abort') { noop(); return; }
|
|
129
131
|
|
|
130
132
|
const tasksPath = path.join(PROJECTS_DIR, project, 'TASKS.yaml');
|
|
131
133
|
if (!existsSync(tasksPath)) { noop(); return; }
|
|
@@ -177,7 +177,7 @@ function createWebhookHandler({ secret = getSecret(), } = {}) {
|
|
|
177
177
|
const parentThread = data.parentThreadId ? threadStore.get(String(data.parentThreadId)) : null;
|
|
178
178
|
const guard = checkSpawnGuards(parentThread);
|
|
179
179
|
if (guard.ok === false) {
|
|
180
|
-
return reply({ success: false, error: `${guard.reason}. Do NOT retry this spawn — fold the remaining work into your own step, or escalate
|
|
180
|
+
return reply({ success: false, error: `${guard.reason}. Do NOT retry this spawn — fold the remaining work into your own step, or escalate by calling the thread_abort tool with a diagnosis.` });
|
|
181
181
|
}
|
|
182
182
|
const projectId = data.projectId || 'general';
|
|
183
183
|
// The originating conduit (the starter agent's SLACK_CHANNEL, forwarded by thread-ops.ts).
|
|
@@ -351,6 +351,43 @@ function createWebhookHandler({ secret = getSecret(), } = {}) {
|
|
|
351
351
|
}));
|
|
352
352
|
return reply({ success: true, data: { scope, count: out.length, threads: out } });
|
|
353
353
|
}
|
|
354
|
+
if (action === 'control') {
|
|
355
|
+
// DR-0015 problem 1: out-of-band control plane. The agent's own thread_abort /
|
|
356
|
+
// thread_split / thread_wait tool POSTs { threadId, control:{ action, ... } } here.
|
|
357
|
+
// Validate the thread exists and is not terminal; reject a second concurrent control;
|
|
358
|
+
// then persist metadata.pendingControl for the runner to read at the step boundary.
|
|
359
|
+
const threadId = data.threadId;
|
|
360
|
+
const control = data.control;
|
|
361
|
+
if (!threadId || !control || typeof control.action !== 'string') {
|
|
362
|
+
return reply({ success: false, error: 'control requires threadId and control.action' });
|
|
363
|
+
}
|
|
364
|
+
if (!['abort', 'split', 'wait'].includes(control.action)) {
|
|
365
|
+
return reply({ success: false, error: `unknown control action: ${control.action}` });
|
|
366
|
+
}
|
|
367
|
+
const t = threadStore.get(threadId);
|
|
368
|
+
if (!t)
|
|
369
|
+
return reply({ success: false, error: 'thread not found' });
|
|
370
|
+
if (['completed', 'failed', 'cancelled', 'aborted'].includes(t.status)) {
|
|
371
|
+
return reply({ success: false, error: `thread is ${t.status} (terminal) — cannot accept control` });
|
|
372
|
+
}
|
|
373
|
+
if (t.metadata?.pendingControl) {
|
|
374
|
+
return reply({ success: false, error: `thread already has a pending ${t.metadata.pendingControl.action} control — only one control intent at a time` });
|
|
375
|
+
}
|
|
376
|
+
const requestedAtStep = t.currentStepIndex;
|
|
377
|
+
await threadStore.mutate(threadId, (r) => {
|
|
378
|
+
(r.metadata ??= {}).pendingControl = {
|
|
379
|
+
action: control.action,
|
|
380
|
+
kind: control.kind ?? null,
|
|
381
|
+
diagnosis: control.diagnosis ?? null,
|
|
382
|
+
subtasks: Array.isArray(control.subtasks) ? control.subtasks : null,
|
|
383
|
+
onTasks: Array.isArray(control.on_tasks) ? control.on_tasks : null,
|
|
384
|
+
onThreads: Array.isArray(control.on_threads) ? control.on_threads : null,
|
|
385
|
+
requestedAtStep,
|
|
386
|
+
};
|
|
387
|
+
});
|
|
388
|
+
log.info(`thread-op control ${threadId}: ${control.action}${control.kind ? ` (${control.kind})` : ''}`);
|
|
389
|
+
return reply({ success: true, data: { threadId, action: control.action, requestedAtStep, accepted: true } });
|
|
390
|
+
}
|
|
354
391
|
if (action === 'cancel') {
|
|
355
392
|
const cancelled = await cancelThread(data.threadId);
|
|
356
393
|
return reply({ success: true, data: { cancelled } });
|
|
@@ -32,6 +32,15 @@ export declare function buildTaskResultNotice(task: Task, kind: 'completed' | 'b
|
|
|
32
32
|
export declare function notifyTaskParentThreads(taskId: string, kind: 'completed' | 'blocked', deps?: {
|
|
33
33
|
resume?: ResumeFn;
|
|
34
34
|
}): Promise<void>;
|
|
35
|
+
type WakeFn = (channel: string, notice: string) => void | Promise<void>;
|
|
36
|
+
/** Session→task wake (Problem 1): when a task created by an interactive session/agent turns
|
|
37
|
+
* terminal, route a notice back to its origin channel. Default-on, no fallback — if origin_channel
|
|
38
|
+
* is set we always wake it. Mutually exclusive with the thread-parent path: if any thread is
|
|
39
|
+
* currently waiting on this task (waitingOnTasks), that path owns the result and we defer.
|
|
40
|
+
* `wake` is injectable for testing (mirrors the `resume` injection on notifyTaskParentThreads). */
|
|
41
|
+
export declare function notifyTaskOriginSession(taskId: string, kind: 'completed' | 'blocked', deps?: {
|
|
42
|
+
wake?: WakeFn;
|
|
43
|
+
}): Promise<void>;
|
|
35
44
|
/** Sweep one waiting thread's waitingOnTasks against disk state: deliver already-done and
|
|
36
45
|
* already-blocked children, drop missing ones, keep open ones. Closes the race window
|
|
37
46
|
* where a child task turns terminal between the suspension snapshot and the waiting
|
|
@@ -56,7 +65,7 @@ export declare function recoverWaitingThreads(deps?: {
|
|
|
56
65
|
}): Promise<number>;
|
|
57
66
|
/**
|
|
58
67
|
* Fire the completion callback for an MCP-spawned thread once it is terminal.
|
|
59
|
-
* - Non-terminal statuses (e.g. a parent that suspended via
|
|
68
|
+
* - Non-terminal statuses (e.g. a parent that suspended via thread_wait and returned
|
|
60
69
|
* from runThread in 'waiting') are ignored — suspension is not completion.
|
|
61
70
|
* - Interactive parent (no parentThreadId): wake the parent by routing a synthetic turn onto
|
|
62
71
|
* its channel via agentRunner.route.
|
|
@@ -65,3 +74,4 @@ export declare function recoverWaitingThreads(deps?: {
|
|
|
65
74
|
* Threads not spawned via thread_start (no parentSessionId) are ignored.
|
|
66
75
|
*/
|
|
67
76
|
export declare function fireThreadCallback(threadId: string): Promise<void>;
|
|
77
|
+
export {};
|
|
@@ -67,7 +67,7 @@ export function buildChildResultNotice(child) {
|
|
|
67
67
|
lines.push('2. 达标 → 蒸馏关键结论进你的 artifact,继续你的计划。');
|
|
68
68
|
lines.push('3. 未达标 → 写出 expected/actual 差异与失败假设,用修订后的契约重新 thread_start' +
|
|
69
69
|
`(你已使用 ${childCount}/${maxChildren} 个子线程额度;额度耗尽时 thread_start 会被拒绝)。`);
|
|
70
|
-
lines.push('4. 无法判断或方向性问题 →
|
|
70
|
+
lines.push('4. 无法判断或方向性问题 → 调用 thread_abort 工具(附一行诊断)升级到你的上层。');
|
|
71
71
|
return lines.join('\n');
|
|
72
72
|
}
|
|
73
73
|
/** Durable degraded-path notice to the project-report channel. */
|
|
@@ -229,8 +229,8 @@ export function buildTaskResultNotice(task, kind) {
|
|
|
229
229
|
lines.push('验收要求(必须执行,不得凭完成备注直接采信):');
|
|
230
230
|
lines.push('1. 读取实际产出(代码/文档/实验记录),逐条核对 done_when;涉及代码的跑测试验证。');
|
|
231
231
|
lines.push('2. 达标 → 蒸馏关键结论进你的 artifact,继续你的计划。');
|
|
232
|
-
lines.push(`3. 未达标 → cortex-task uncomplete 后修订该任务,或用 decompose --keep-parent
|
|
233
|
-
lines.push('4. 方向性问题 →
|
|
232
|
+
lines.push(`3. 未达标 → cortex-task uncomplete 后修订该任务,或用 decompose --keep-parent 增加修订子任务,再调用 thread_wait。`);
|
|
233
|
+
lines.push('4. 方向性问题 → 调用 thread_abort 工具(附一行诊断)升级。');
|
|
234
234
|
}
|
|
235
235
|
else {
|
|
236
236
|
lines.push(`[子任务被阻塞 — 升级信号] #${task.id} ${task.text}`);
|
|
@@ -238,8 +238,8 @@ export function buildTaskResultNotice(task, kind) {
|
|
|
238
238
|
lines.push('');
|
|
239
239
|
lines.push('这是子任务的升级:它无法自行完成。你必须处理:');
|
|
240
240
|
lines.push('1. 诊断原因(读它的产出/日志;too-big 类原因 = 你当初的分解需要修订)。');
|
|
241
|
-
lines.push('2. 可修复 → cortex-task unblock 并修订任务描述/done_when,或重建修订后的子任务(decompose --keep-parent
|
|
242
|
-
lines.push('3. 超出你的职权或方向性问题 →
|
|
241
|
+
lines.push('2. 可修复 → cortex-task unblock 并修订任务描述/done_when,或重建修订后的子任务(decompose --keep-parent),再调用 thread_wait。');
|
|
242
|
+
lines.push('3. 超出你的职权或方向性问题 → 调用 thread_abort 工具(附一行诊断)向上升级。');
|
|
243
243
|
}
|
|
244
244
|
return lines.join('\n');
|
|
245
245
|
}
|
|
@@ -308,6 +308,63 @@ export async function notifyTaskParentThreads(taskId, kind, deps = {}) {
|
|
|
308
308
|
await deliverTaskResult(parent.id, task, kind, deps);
|
|
309
309
|
}
|
|
310
310
|
}
|
|
311
|
+
/** Wake (or create) the session on a channel by routing a synthetic user message — the same
|
|
312
|
+
* mechanism the interactive thread-parent path uses. Shared by thread completion (fireThreadCallback)
|
|
313
|
+
* and task completion (notifyTaskOriginSession). agentRunner.route find-or-creates the channel's
|
|
314
|
+
* session, so this works whether or not a live session still exists. */
|
|
315
|
+
async function wakeSession(channel, notice, tag) {
|
|
316
|
+
const adapter = jobCtx.adapter;
|
|
317
|
+
if (!adapter) {
|
|
318
|
+
log.error(`no adapter; cannot wake session on ${channel} (${tag})`);
|
|
319
|
+
return;
|
|
320
|
+
}
|
|
321
|
+
const message = {
|
|
322
|
+
ref: { conduit: channel, messageId: `cb_${tag}_${Date.now()}` },
|
|
323
|
+
text: notice,
|
|
324
|
+
senderId: 'cortex-thread-callback',
|
|
325
|
+
isBot: false,
|
|
326
|
+
kind: 'user',
|
|
327
|
+
raw: { source: 'task-callback', tag },
|
|
328
|
+
};
|
|
329
|
+
log.info(`waking session on ${channel} for ${tag}`);
|
|
330
|
+
await agentRunner.route({
|
|
331
|
+
message, channel, adapter, threadAnchorId: null, hasFiles: false, userMessage: notice, agentMessage: notice,
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
/** Origin-session notice: a task created by an interactive session/agent finished — concise,
|
|
335
|
+
* no manager-style verification ceremony (the recipient is the requester, not a join node). */
|
|
336
|
+
function buildTaskOriginNotice(task, kind) {
|
|
337
|
+
if (kind === 'completed') {
|
|
338
|
+
const note = task.completed_note ? `\n备注: ${task.completed_note}` : '';
|
|
339
|
+
return `[任务完成] 你布置的任务 #${task.id} (${task.project})「${task.text}」已完成。${note}\n用 cortex-task show --task-id ${task.id} 查看详情。`;
|
|
340
|
+
}
|
|
341
|
+
return `[任务受阻] 你布置的任务 #${task.id} (${task.project})「${task.text}」被阻塞。\n阻塞原因: ${task.blocked_by || '(未记录)'}\n用 cortex-task show --task-id ${task.id} 查看详情,处理后可 cortex-task unblock。`;
|
|
342
|
+
}
|
|
343
|
+
/** Session→task wake (Problem 1): when a task created by an interactive session/agent turns
|
|
344
|
+
* terminal, route a notice back to its origin channel. Default-on, no fallback — if origin_channel
|
|
345
|
+
* is set we always wake it. Mutually exclusive with the thread-parent path: if any thread is
|
|
346
|
+
* currently waiting on this task (waitingOnTasks), that path owns the result and we defer.
|
|
347
|
+
* `wake` is injectable for testing (mirrors the `resume` injection on notifyTaskParentThreads). */
|
|
348
|
+
export async function notifyTaskOriginSession(taskId, kind, deps = {}) {
|
|
349
|
+
for (const t of threadStore.getAll()) {
|
|
350
|
+
if (t.status === 'waiting' && t.metadata?.waitingOnTasks?.includes(taskId))
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
const key = `task_${taskId}_${kind}`;
|
|
354
|
+
if (fired.has(key))
|
|
355
|
+
return;
|
|
356
|
+
// The event carries only the id; origin fields live on the task — scan disk to find it.
|
|
357
|
+
const task = scanAllTasks().find((t) => t.id === taskId);
|
|
358
|
+
if (!task || !task.origin_channel)
|
|
359
|
+
return;
|
|
360
|
+
if (kind === 'completed' && task.status !== 'done')
|
|
361
|
+
return; // dispatch publishes loosely
|
|
362
|
+
if (kind === 'blocked' && !task.blocked_by)
|
|
363
|
+
return;
|
|
364
|
+
fired.add(key);
|
|
365
|
+
const wake = deps.wake ?? ((ch, n) => wakeSession(ch, n, `task_${taskId}`));
|
|
366
|
+
await wake(task.origin_channel, buildTaskOriginNotice(task, kind));
|
|
367
|
+
}
|
|
311
368
|
/** Sweep one waiting thread's waitingOnTasks against disk state: deliver already-done and
|
|
312
369
|
* already-blocked children, drop missing ones, keep open ones. Closes the race window
|
|
313
370
|
* where a child task turns terminal between the suspension snapshot and the waiting
|
|
@@ -350,9 +407,11 @@ export async function reconcileWaitingTasks(threadId, deps = {}) {
|
|
|
350
407
|
export function registerTaskTreeSubscribers(bus) {
|
|
351
408
|
bus.subscribe('task.completed', (e) => {
|
|
352
409
|
void notifyTaskParentThreads(e.taskId, 'completed').catch((err) => log.error(`task.completed bridge: ${err.message}`));
|
|
410
|
+
void notifyTaskOriginSession(e.taskId, 'completed').catch((err) => log.error(`task.completed origin-wake: ${err.message}`));
|
|
353
411
|
});
|
|
354
412
|
bus.subscribe('task.blocked', (e) => {
|
|
355
413
|
void notifyTaskParentThreads(e.taskId, 'blocked').catch((err) => log.error(`task.blocked bridge: ${err.message}`));
|
|
414
|
+
void notifyTaskOriginSession(e.taskId, 'blocked').catch((err) => log.error(`task.blocked origin-wake: ${err.message}`));
|
|
356
415
|
});
|
|
357
416
|
}
|
|
358
417
|
/** Startup recovery: re-deliver results that completed while the server was down.
|
|
@@ -398,7 +457,7 @@ export async function recoverWaitingThreads(deps = {}) {
|
|
|
398
457
|
}
|
|
399
458
|
/**
|
|
400
459
|
* Fire the completion callback for an MCP-spawned thread once it is terminal.
|
|
401
|
-
* - Non-terminal statuses (e.g. a parent that suspended via
|
|
460
|
+
* - Non-terminal statuses (e.g. a parent that suspended via thread_wait and returned
|
|
402
461
|
* from runThread in 'waiting') are ignored — suspension is not completion.
|
|
403
462
|
* - Interactive parent (no parentThreadId): wake the parent by routing a synthetic turn onto
|
|
404
463
|
* its channel via agentRunner.route.
|
|
@@ -433,31 +492,8 @@ export async function fireThreadCallback(threadId) {
|
|
|
433
492
|
return;
|
|
434
493
|
fired.add(threadId);
|
|
435
494
|
const notice = buildNotice(threadId);
|
|
436
|
-
const adapter = jobCtx.adapter;
|
|
437
495
|
if (m.parentChannel) {
|
|
438
|
-
|
|
439
|
-
log.error(`no adapter; cannot wake parent for ${threadId}`);
|
|
440
|
-
return;
|
|
441
|
-
}
|
|
442
|
-
const channel = m.parentChannel;
|
|
443
|
-
const message = {
|
|
444
|
-
ref: { conduit: channel, messageId: `cb_${threadId}_${Date.now()}` },
|
|
445
|
-
text: notice,
|
|
446
|
-
senderId: 'cortex-thread-callback',
|
|
447
|
-
isBot: false,
|
|
448
|
-
kind: 'user',
|
|
449
|
-
raw: { source: 'thread-callback', threadId },
|
|
450
|
-
};
|
|
451
|
-
log.info(`waking parent session on ${channel} for thread ${threadId}`);
|
|
452
|
-
await agentRunner.route({
|
|
453
|
-
message,
|
|
454
|
-
channel,
|
|
455
|
-
adapter,
|
|
456
|
-
threadAnchorId: null,
|
|
457
|
-
hasFiles: false,
|
|
458
|
-
userMessage: notice,
|
|
459
|
-
agentMessage: notice,
|
|
460
|
-
});
|
|
496
|
+
await wakeSession(m.parentChannel, notice, `thr_${threadId}`);
|
|
461
497
|
return;
|
|
462
498
|
}
|
|
463
499
|
// No channel → durable notice to the project-report channel.
|