@cortex-agent/server 2026.6.11 → 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/gateway-generator.js +24 -3
- package/dist/core/i18n.d.ts +19 -0
- package/dist/core/i18n.js +46 -0
- package/dist/core/locales/en.d.ts +438 -0
- package/dist/core/locales/en.js +24 -0
- package/dist/core/locales/slices/commands.d.ts +214 -0
- package/dist/core/locales/slices/commands.js +462 -0
- package/dist/core/locales/slices/init.d.ts +121 -0
- package/dist/core/locales/slices/init.js +380 -0
- package/dist/core/locales/slices/interactions.d.ts +47 -0
- package/dist/core/locales/slices/interactions.js +102 -0
- package/dist/core/locales/slices/lang.d.ts +8 -0
- package/dist/core/locales/slices/lang.js +18 -0
- package/dist/core/locales/slices/scheduling.d.ts +36 -0
- package/dist/core/locales/slices/scheduling.js +74 -0
- package/dist/core/locales/slices/startup.d.ts +6 -0
- package/dist/core/locales/slices/startup.js +14 -0
- package/dist/core/locales/slices/status.d.ts +20 -0
- package/dist/core/locales/slices/status.js +48 -0
- package/dist/core/locales/zh.d.ts +5 -0
- package/dist/core/locales/zh.js +23 -0
- package/dist/core/singleton-lock.d.ts +23 -0
- package/dist/core/singleton-lock.js +53 -0
- package/dist/core/status-format.js +2 -1
- 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/core/utils.d.ts +9 -1
- package/dist/core/utils.js +9 -1
- package/dist/domain/agents/config.d.ts +2 -1
- package/dist/domain/agents/config.js +25 -6
- 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 +18 -16
- package/dist/domain/scheduling/schedule-command.js +38 -37
- package/dist/domain/system/github-release.d.ts +18 -0
- package/dist/domain/system/github-release.js +106 -0
- package/dist/domain/system/preferences.d.ts +12 -0
- package/dist/domain/system/preferences.js +36 -0
- package/dist/domain/tasks/dispatch-utils.d.ts +5 -0
- package/dist/domain/tasks/dispatch-utils.js +9 -1
- package/dist/domain/tasks/dispatcher.d.ts +11 -2
- package/dist/domain/tasks/dispatcher.js +41 -11
- 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.d.ts +6 -0
- package/dist/domain/threads/prompt-builder.js +34 -11
- 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/entry/app.js +36 -3
- package/dist/entry/daemon.js +12 -30
- package/dist/entry/init.d.ts +4 -3
- package/dist/entry/init.js +151 -208
- package/dist/entry/startup-notify.js +6 -3
- package/dist/hooks/task-status-check.mjs +9 -7
- package/dist/orchestration/interactions/interaction-handlers.js +12 -11
- package/dist/orchestration/interactions/update-prompt-slack.js +11 -10
- package/dist/orchestration/interactions/update-prompt.js +66 -11
- package/dist/orchestration/lifecycle.js +13 -12
- package/dist/orchestration/routing/commands/cancel.js +10 -9
- package/dist/orchestration/routing/commands/channel.js +27 -26
- package/dist/orchestration/routing/commands/cost.js +10 -2
- package/dist/orchestration/routing/commands/device.js +11 -9
- package/dist/orchestration/routing/commands/dispatch.js +10 -10
- package/dist/orchestration/routing/commands/index.js +6 -2
- package/dist/orchestration/routing/commands/lang.d.ts +3 -0
- package/dist/orchestration/routing/commands/lang.js +31 -0
- package/dist/orchestration/routing/commands/mode.js +28 -27
- package/dist/orchestration/routing/commands/nvtop.js +13 -12
- package/dist/orchestration/routing/commands/orient.js +2 -1
- package/dist/orchestration/routing/commands/schedule.js +23 -22
- package/dist/orchestration/routing/commands/sendfile.js +8 -7
- package/dist/orchestration/routing/commands/session.js +11 -10
- package/dist/orchestration/routing/commands/status.js +78 -71
- package/dist/orchestration/routing/commands/tail.js +6 -5
- package/dist/orchestration/routing/commands/task.js +23 -22
- package/dist/orchestration/routing/commands/thread-handlers.js +40 -39
- package/dist/orchestration/routing/webhook.js +38 -1
- package/dist/orchestration/status-helpers.js +6 -5
- 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/dist/platform/interactive-builder.js +19 -18
- package/dist/store/version-migrations.d.ts +7 -0
- package/dist/store/version-migrations.js +88 -0
- package/package.json +1 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// Prompt assembly and agent slot config resolution.
|
|
2
2
|
// input: template-loader, artifact-io, thread-store, thread-types
|
|
3
|
-
// output: buildStepPrompt / resolveSystemVars / resolveAgentSlotConfig / resolveTemplateAgents / formatEndpoint / pickStepTemplate
|
|
3
|
+
// output: buildStepPrompt / resolveSystemVars / resolveAgentSlotConfig / resolveTemplateAgents / resolveTemplateProfiles / formatEndpoint / pickStepTemplate
|
|
4
4
|
import { threadStore } from '../../store/thread-repo.js';
|
|
5
|
-
import { getAgent, resolveFileRef } from './template-loader.js';
|
|
5
|
+
import { getAgent, getTemplate, resolveFileRef } from './template-loader.js';
|
|
6
6
|
import { getModifiedFilesFromSession, getSessionFileChanges, renderModifiedFilesWithDiff } from './artifact-io.js';
|
|
7
7
|
import { getDefaultAgent } from '../agents/index.js';
|
|
8
8
|
import { loadUserContext } from '../memory/user-context.js';
|
|
@@ -89,6 +89,23 @@ export function resolveTemplateAgents(template) {
|
|
|
89
89
|
}
|
|
90
90
|
return configs;
|
|
91
91
|
}
|
|
92
|
+
/** Resolve the unique profile names a template's agents will actually run with.
|
|
93
|
+
* Mirrors thread-runner profile resolution (runner.ts): hardcoded agent profiles win;
|
|
94
|
+
* `__active__` slots resolve to `activeProfile` (the dispatch/scheduler profile that
|
|
95
|
+
* would be injected via metadata.profileOverride). Null/empty entries are dropped.
|
|
96
|
+
* Unknown template or no resolvable agents → [] (fail-open; callers decide fallback). */
|
|
97
|
+
export function resolveTemplateProfiles(templateName, activeProfile) {
|
|
98
|
+
const template = getTemplate(templateName);
|
|
99
|
+
if (!template)
|
|
100
|
+
return [];
|
|
101
|
+
const profiles = new Set();
|
|
102
|
+
for (const config of resolveTemplateAgents(template)) {
|
|
103
|
+
const profile = config.profile === '__active__' ? activeProfile : config.profile;
|
|
104
|
+
if (profile)
|
|
105
|
+
profiles.add(profile);
|
|
106
|
+
}
|
|
107
|
+
return [...profiles];
|
|
108
|
+
}
|
|
92
109
|
/** Render an `(agent, stage)` pair as the canonical endpoint string used for iterationCounts keys
|
|
93
110
|
* and transition-rule matching. Stages that are null render as bare agent names. */
|
|
94
111
|
export function formatEndpoint(agent, stage) {
|
|
@@ -106,15 +123,21 @@ export function pickStepTemplate(agentConfig, stage) {
|
|
|
106
123
|
/** System-level protocol preamble injected into every step prompt of threads that own a workspace artifact. */
|
|
107
124
|
export const THREAD_PROTOCOL_PREAMBLE = [
|
|
108
125
|
'[Cortex Thread Protocol]',
|
|
109
|
-
'You are executing inside a Cortex thread.
|
|
110
|
-
'
|
|
111
|
-
'
|
|
112
|
-
'
|
|
113
|
-
'
|
|
114
|
-
'
|
|
115
|
-
'
|
|
116
|
-
'with
|
|
117
|
-
'
|
|
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.',
|
|
118
141
|
].join('\n');
|
|
119
142
|
// --- Prompt assembly ---
|
|
120
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);
|
package/dist/entry/app.js
CHANGED
|
@@ -6,7 +6,8 @@ import * as dotenv from 'dotenv';
|
|
|
6
6
|
import { mkdirSync } from 'fs';
|
|
7
7
|
import * as path from 'path';
|
|
8
8
|
import { createAdapterFromEnv, extractTuiAdapter } from '../platform/index.js';
|
|
9
|
-
import { WORKSPACE_DIR, CONFIG_DIR } from '../core/utils.js';
|
|
9
|
+
import { WORKSPACE_DIR, CONFIG_DIR, DATA_DIR, STORE_DIR } from '../core/utils.js';
|
|
10
|
+
import { tryAcquireSingletonLock, releaseSingletonLock } from '../core/singleton-lock.js';
|
|
10
11
|
import { closeAllSessions, closeSession as closeClaudePooledSession, shutdownCodex } from '../domain/agents/index.js';
|
|
11
12
|
import { closeAllAdapters } from '../agent-adapter/index.js';
|
|
12
13
|
import { recoverTuiOrphans } from '../agent-adapter/claude/adapter.js';
|
|
@@ -30,8 +31,10 @@ import { conversationLedger } from '../store/conversation-ledger-repo.js';
|
|
|
30
31
|
import { executionRepo } from '../store/execution-repo.js';
|
|
31
32
|
import { loadConfig as loadThreadConfig, startConfigWatcher as startThreadConfigWatcher, setAdminNotifier as setConfigNotifier } from '../domain/threads/index.js';
|
|
32
33
|
import { startMemoryWatcher } from '../domain/memory/watcher.js';
|
|
33
|
-
import { getActiveBackend } from '../domain/agents/index.js';
|
|
34
|
+
import { getActiveBackend, configureEnvForMode, loadMode } from '../domain/agents/index.js';
|
|
34
35
|
import { createEditHandler } from '../orchestration/routing/edit-handler.js';
|
|
36
|
+
import { setLocale, normalizeLocale } from '../core/i18n.js';
|
|
37
|
+
import { loadLang } from '../domain/system/preferences.js';
|
|
35
38
|
// Extracted modules
|
|
36
39
|
import { cleanupLogs, ensureMcpConfig } from './startup-helpers.js';
|
|
37
40
|
import { createLogger } from '../core/log.js';
|
|
@@ -50,7 +53,7 @@ import { createUpdatePrompt } from '../orchestration/interactions/update-prompt.
|
|
|
50
53
|
import { registerMessageHandler } from '../orchestration/routing/message-router.js';
|
|
51
54
|
import { initRateLimitThrottle } from '../domain/costs/rate-limit-throttle.js';
|
|
52
55
|
import { scheduleRepo } from '../store/schedule-repo.js';
|
|
53
|
-
import { runMigrations } from '../store/version-migrations.js';
|
|
56
|
+
import { runMigrations, migrateAistatusConfigLocation } from '../store/version-migrations.js';
|
|
54
57
|
import { syncManagedHooks } from '../store/hook-sync.js';
|
|
55
58
|
import { costRepo } from '../store/cost-repo.js';
|
|
56
59
|
import { profileRepo, startProfileWatcher, setAdminNotifier as setProfileNotifier } from '../store/profile-repo.js';
|
|
@@ -68,7 +71,35 @@ import { createTuiSessionService } from '../domain/tui-session/index.js';
|
|
|
68
71
|
import { enqueue, conduitQueues } from '../orchestration/conduit-queue.js';
|
|
69
72
|
import { getCostSummary } from '../domain/costs/cost-tracker.js';
|
|
70
73
|
dotenv.config({ path: path.join(CONFIG_DIR, '.env') });
|
|
74
|
+
// Apply the persisted mode to env now that .env is loaded. This used to be an import-time
|
|
75
|
+
// side effect inside domain/agents/config.ts; it is explicit here so that CLI processes
|
|
76
|
+
// (cortex init / setup-gateway) importing that module don't get their env mutated.
|
|
77
|
+
configureEnvForMode(loadMode());
|
|
78
|
+
// Resolve the UI language for all system-generated user-facing text. Precedence:
|
|
79
|
+
// CORTEX_LANG env (escape hatch, now that .env is loaded) > config/preferences.json > 'en'.
|
|
80
|
+
// The !lang command switches this live at runtime via setLocale().
|
|
81
|
+
setLocale(process.env.CORTEX_LANG ? normalizeLocale(process.env.CORTEX_LANG) : loadLang());
|
|
71
82
|
const log = createLogger('app');
|
|
83
|
+
// --- Singleton lock ---
|
|
84
|
+
// app.js owns ports 3001 (webhook) / 3002 (client-manager); a second instance would
|
|
85
|
+
// crash-loop on EADDRINUSE. The daemon's own daemon.pid lock only guards the supervisor
|
|
86
|
+
// layer and does nothing for `cortex start` (which forks app.js directly, bypassing the
|
|
87
|
+
// daemon). Acquire our own app.pid lock here, as early as possible, to fail fast before
|
|
88
|
+
// any heavy initialization or port binding. Stale locks (previous owner SIGKILL'd / crashed)
|
|
89
|
+
// are reclaimed automatically. Released on process exit (covers SIGTERM→exit(0) and Ctrl+C).
|
|
90
|
+
const APP_PID_FILE = path.join(STORE_DIR, 'app.pid');
|
|
91
|
+
const appLock = tryAcquireSingletonLock(APP_PID_FILE);
|
|
92
|
+
if (appLock.acquired) {
|
|
93
|
+
if (appLock.stale)
|
|
94
|
+
log.info(`Reclaimed stale app.pid lock for PID ${process.pid}`);
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
log.error(`Another Cortex app.js is already running (PID ${appLock.holderPid}, lockfile ${APP_PID_FILE}).\n` +
|
|
98
|
+
` Refusing to start a second instance — it already holds ports 3001/3002; this process would crash on EADDRINUSE.\n` +
|
|
99
|
+
` Inspect with \`cortex daemon status\`, or stop the running instance before retrying.`);
|
|
100
|
+
process.exit(1);
|
|
101
|
+
}
|
|
102
|
+
process.on('exit', () => releaseSingletonLock(APP_PID_FILE));
|
|
72
103
|
// --- Crash safety net ---
|
|
73
104
|
// A single failed outbound post while handling an inbound message must never take
|
|
74
105
|
// down the whole server. Detached per-conduit queue work (conduit-queue.ts) and
|
|
@@ -214,6 +245,8 @@ process.on('SIGTERM', async () => {
|
|
|
214
245
|
cleanupLogs();
|
|
215
246
|
ensureMcpConfig();
|
|
216
247
|
await runMigrations();
|
|
248
|
+
// Migrate old aistatus config from wrong location (CORTEX_HOME/config) to correct location (~/.aistatus)
|
|
249
|
+
await migrateAistatusConfigLocation(DATA_DIR);
|
|
217
250
|
// Refresh version-stamped hooks in DATA_DIR/hooks from the shipped defaults. init's deployHooks
|
|
218
251
|
// only copies-if-missing, so without this an existing install never picks up hook code fixes.
|
|
219
252
|
await syncManagedHooks();
|
package/dist/entry/daemon.js
CHANGED
|
@@ -36,10 +36,11 @@
|
|
|
36
36
|
*/
|
|
37
37
|
import * as dotenv from 'dotenv';
|
|
38
38
|
import { fork, spawn } from 'child_process';
|
|
39
|
-
import { watch, existsSync, unlinkSync, statSync,
|
|
39
|
+
import { watch, existsSync, unlinkSync, statSync, writeFileSync, readdirSync } from 'fs';
|
|
40
40
|
import * as path from 'path';
|
|
41
41
|
import { createLogger } from '../core/log.js';
|
|
42
42
|
import { isMainModule, moduleDir, DATA_DIR, CONFIG_DIR, STORE_DIR } from '../core/utils.js';
|
|
43
|
+
import { tryAcquireSingletonLock, releaseSingletonLock as releaseLock } from '../core/singleton-lock.js';
|
|
43
44
|
// Load .env BEFORE reading any CORTEX_* env vars below. Mirrors app.ts §61 — the
|
|
44
45
|
// daemon needs CORTEX_REPO (and potentially other vars) from .env, not just from
|
|
45
46
|
// the OS shell env. Must be sync and before the `CORTEX_REPO` constant below.
|
|
@@ -479,39 +480,20 @@ function setupShutdown() {
|
|
|
479
480
|
process.on('SIGTERM', () => shutdown('SIGTERM'));
|
|
480
481
|
}
|
|
481
482
|
function acquireSingletonLock() {
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
const otherPid = Number(raw);
|
|
485
|
-
if (Number.isFinite(otherPid) && otherPid > 0) {
|
|
486
|
-
let alive = false;
|
|
487
|
-
try {
|
|
488
|
-
process.kill(otherPid, 0);
|
|
489
|
-
alive = true;
|
|
490
|
-
}
|
|
491
|
-
catch {
|
|
492
|
-
alive = false;
|
|
493
|
-
}
|
|
494
|
-
if (alive) {
|
|
495
|
-
log.error(`Another Cortex daemon is already running (PID ${otherPid}, lockfile ${PID_FILE}).\n` +
|
|
496
|
-
` Refusing to start a second instance — its app.ts already holds ports 3001/3002 and your child would crash-loop on EADDRINUSE.\n` +
|
|
497
|
-
` To restart the running daemon: \`touch agent-server/.restart\` (hot reload), or send SIGTERM to PID ${otherPid} and rerun.`);
|
|
498
|
-
process.exit(1);
|
|
499
|
-
}
|
|
500
|
-
}
|
|
483
|
+
const result = tryAcquireSingletonLock(PID_FILE);
|
|
484
|
+
if (result.acquired) {
|
|
501
485
|
// Stale lock — previous daemon died without cleanup
|
|
502
|
-
|
|
486
|
+
if (result.stale)
|
|
487
|
+
log.info(`Removed stale PID file and reclaimed lock for PID ${process.pid}`);
|
|
488
|
+
return;
|
|
503
489
|
}
|
|
504
|
-
|
|
490
|
+
log.error(`Another Cortex daemon is already running (PID ${result.holderPid}, lockfile ${PID_FILE}).\n` +
|
|
491
|
+
` Refusing to start a second instance — its app.ts already holds ports 3001/3002 and your child would crash-loop on EADDRINUSE.\n` +
|
|
492
|
+
` To restart the running daemon: \`touch agent-server/.restart\` (hot reload), or send SIGTERM to PID ${result.holderPid} and rerun.`);
|
|
493
|
+
process.exit(1);
|
|
505
494
|
}
|
|
506
495
|
function releaseSingletonLock() {
|
|
507
|
-
|
|
508
|
-
if (!existsSync(PID_FILE))
|
|
509
|
-
return;
|
|
510
|
-
const raw = readFileSync(PID_FILE, 'utf8').trim();
|
|
511
|
-
if (Number(raw) === process.pid)
|
|
512
|
-
unlinkSync(PID_FILE);
|
|
513
|
-
}
|
|
514
|
-
catch { }
|
|
496
|
+
releaseLock(PID_FILE);
|
|
515
497
|
try {
|
|
516
498
|
if (existsSync(CHILD_PID_FILE))
|
|
517
499
|
unlinkSync(CHILD_PID_FILE);
|
package/dist/entry/init.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ModelChoice } from '../core/profile-generator.js';
|
|
2
|
+
import { type Locale } from '../core/i18n.js';
|
|
2
3
|
import { cmdFeishu, type CliResult } from './feishu-login.js';
|
|
3
4
|
export interface InitPaths {
|
|
4
5
|
DATA_DIR: string;
|
|
@@ -19,13 +20,10 @@ export interface SlackInitConfig {
|
|
|
19
20
|
botToken: string;
|
|
20
21
|
signingSecret: string;
|
|
21
22
|
appToken: string;
|
|
22
|
-
adminChannel?: string;
|
|
23
23
|
}
|
|
24
24
|
export interface FeishuInitConfig {
|
|
25
25
|
appId: string;
|
|
26
26
|
appSecret: string;
|
|
27
|
-
encryptKey?: string;
|
|
28
|
-
verificationToken?: string;
|
|
29
27
|
domain?: 'feishu' | 'lark';
|
|
30
28
|
/** Identity for MCP document operations: 'bot' (default) or the operator's 'user' account. */
|
|
31
29
|
authMode?: 'bot' | 'user';
|
|
@@ -37,6 +35,8 @@ export interface GatewayUsageConfig {
|
|
|
37
35
|
email?: string;
|
|
38
36
|
}
|
|
39
37
|
export interface InitAnswers {
|
|
38
|
+
/** UI language for system-generated messages. Persisted to config/preferences.json. */
|
|
39
|
+
lang: Locale;
|
|
40
40
|
backends: InitBackend[];
|
|
41
41
|
machineName: string;
|
|
42
42
|
gpuCount: number;
|
|
@@ -107,6 +107,7 @@ export declare function getGitInstallHint(): string;
|
|
|
107
107
|
*/
|
|
108
108
|
export declare function ensureGitInstalled(): boolean;
|
|
109
109
|
export declare function safeCopy(src: string, dst: string, force: boolean, _label: string): boolean;
|
|
110
|
+
export declare function generateConfigs(paths: InitPaths, answers: InitAnswers, force: boolean): void;
|
|
110
111
|
export interface InitOptions {
|
|
111
112
|
homeDir?: string;
|
|
112
113
|
force?: boolean;
|