@cortex-agent/server 2026.5.19-3 → 2026.5.22
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/README.md +5 -1
- package/defaults/config/thread-templates.json +65 -39
- package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +4 -4
- package/defaults/prompts/directives/coder-reviewer.md +9 -4
- package/defaults/prompts/directives/coder.md +10 -2
- package/dist/core/log.js +61 -12
- package/dist/core/status-format.js +1 -1
- package/dist/core/task-parser.d.ts +1 -1
- package/dist/core/task-parser.js +13 -6
- package/dist/core/types/thread-types.d.ts +4 -2
- package/dist/domain/costs/codex-usage-monitor.d.ts +1 -2
- package/dist/domain/costs/codex-usage-monitor.js +2 -2
- package/dist/domain/costs/cost-tracker.d.ts +2 -0
- package/dist/domain/costs/cost-tracker.js +4 -20
- package/dist/domain/costs/rate-limit-throttle.js +1 -4
- package/dist/domain/mcp/tools/context.d.ts +4 -2
- package/dist/domain/mcp/tools/context.js +7 -5
- package/dist/domain/mcp/tools/schedule.d.ts +1 -1
- package/dist/domain/mcp/tools/schedule.js +24 -20
- package/dist/domain/memory/index-regen.js +8 -5
- package/dist/domain/monitor/disk-monitor.js +1 -6
- package/dist/domain/projects/index.d.ts +2 -0
- package/dist/domain/projects/index.js +3 -0
- package/dist/domain/projects/project-store.d.ts +54 -0
- package/dist/domain/projects/project-store.js +194 -0
- package/dist/domain/projects/project-types.d.ts +11 -0
- package/dist/domain/projects/project-types.js +5 -0
- package/dist/domain/remote/client-hot-reload.d.ts +1 -0
- package/dist/domain/remote/client-hot-reload.js +284 -53
- package/dist/domain/scheduling/jobs/_shared.d.ts +1 -1
- package/dist/domain/scheduling/jobs/_shared.js +6 -5
- package/dist/domain/scheduling/jobs/memory-index-regen.js +2 -2
- package/dist/domain/scheduling/jobs/scheduled-task.d.ts +2 -2
- package/dist/domain/scheduling/jobs/scheduled-task.js +38 -36
- package/dist/domain/scheduling/jobs/sync-public.d.ts +1 -0
- package/dist/domain/scheduling/jobs/sync-public.js +34 -0
- package/dist/domain/scheduling/jobs/target-dispatch.d.ts +3 -7
- package/dist/domain/scheduling/jobs/target-dispatch.js +7 -9
- package/dist/domain/scheduling/jobs/task-archive.js +2 -2
- package/dist/domain/scheduling/jobs/task-dispatch.js +18 -16
- package/dist/domain/scheduling/runner.d.ts +1 -0
- package/dist/domain/scheduling/runner.js +2 -0
- package/dist/domain/scheduling/schedule-cli.d.ts +1 -0
- package/dist/domain/scheduling/schedule-cli.js +14 -14
- package/dist/domain/scheduling/schedule-command.js +45 -36
- package/dist/domain/scheduling/scheduler.d.ts +1 -1
- package/dist/domain/scheduling/scheduler.js +12 -11
- package/dist/domain/sessions/session-hooks.d.ts +10 -11
- package/dist/domain/sessions/session-hooks.js +26 -27
- package/dist/domain/sessions/session-registry.d.ts +10 -5
- package/dist/domain/sessions/session-registry.js +24 -9
- package/dist/domain/tasks/pending-tracker.js +8 -9
- package/dist/domain/tasks/system/task-cli.d.ts +2 -0
- package/dist/domain/tasks/system/task-cli.js +189 -29
- package/dist/domain/tasks/system/task-lifecycle-edit.js +3 -3
- package/dist/domain/threads/hook-runner.js +12 -7
- package/dist/domain/threads/runner.d.ts +3 -3
- package/dist/domain/threads/runner.js +30 -28
- package/dist/domain/threads/state-machine.d.ts +3 -0
- package/dist/domain/threads/state-machine.js +4 -0
- package/dist/entry/app.js +30 -9
- package/dist/entry/cli.js +19 -4
- package/dist/entry/daemon.js +28 -2
- package/dist/entry/startup-notify.js +8 -6
- package/dist/orchestration/agent-runner.js +19 -13
- package/dist/orchestration/durable-helpers.js +3 -2
- package/dist/orchestration/interactions/ask-user-question.d.ts +2 -3
- package/dist/orchestration/interactions/ask-user-question.js +5 -4
- package/dist/orchestration/interactions/interaction-handlers.js +8 -5
- package/dist/orchestration/interactions/plan-handler.js +3 -3
- package/dist/orchestration/lifecycle.js +43 -38
- package/dist/orchestration/routing/commands/cancel.js +9 -8
- package/dist/orchestration/routing/commands/channel.js +32 -26
- package/dist/orchestration/routing/commands/cost.js +5 -3
- package/dist/orchestration/routing/commands/device.js +2 -1
- package/dist/orchestration/routing/commands/dispatch.js +8 -7
- package/dist/orchestration/routing/commands/index.js +7 -4
- package/dist/orchestration/routing/commands/mode.js +24 -18
- package/dist/orchestration/routing/commands/nvtop.js +14 -12
- package/dist/orchestration/routing/commands/orient.js +2 -1
- package/dist/orchestration/routing/commands/schedule.js +2 -1
- package/dist/orchestration/routing/commands/sendfile.js +12 -9
- package/dist/orchestration/routing/commands/session.js +12 -10
- package/dist/orchestration/routing/commands/status.js +2 -2
- package/dist/orchestration/routing/commands/tail.js +10 -6
- package/dist/orchestration/routing/commands/task.js +5 -4
- package/dist/orchestration/routing/commands/thread-handlers.js +19 -12
- package/dist/orchestration/routing/hook-bridge-subscribers.js +15 -13
- package/dist/orchestration/status-helpers.d.ts +4 -5
- package/dist/orchestration/status-helpers.js +7 -8
- package/dist/orchestration/thread-executor.js +21 -12
- package/dist/platform/adapter.d.ts +13 -9
- package/dist/platform/adapter.js +1 -1
- package/dist/platform/adapters/feishu-output-stream.d.ts +27 -0
- package/dist/platform/adapters/feishu-output-stream.js +114 -0
- package/dist/platform/adapters/feishu.d.ts +16 -7
- package/dist/platform/adapters/feishu.js +64 -18
- package/dist/platform/adapters/index.d.ts +4 -1
- package/dist/platform/adapters/index.js +1 -1
- package/dist/platform/adapters/slack-output-stream.d.ts +55 -0
- package/dist/platform/{virtual-message.js → adapters/slack-output-stream.js} +98 -165
- package/dist/platform/adapters/slack-project-conduits.d.ts +9 -0
- package/dist/platform/adapters/slack-project-conduits.js +40 -0
- package/dist/platform/adapters/slack.d.ts +18 -8
- package/dist/platform/adapters/slack.js +82 -24
- package/dist/platform/index.d.ts +3 -2
- package/dist/platform/index.js +1 -1
- package/dist/platform/output-stream-chunk.d.ts +6 -0
- package/dist/platform/output-stream-chunk.js +45 -0
- package/dist/platform/output-stream-helpers.d.ts +6 -0
- package/dist/platform/output-stream-helpers.js +11 -0
- package/dist/platform/output-stream.d.ts +28 -0
- package/dist/platform/output-stream.js +4 -0
- package/dist/platform/testing.d.ts +41 -8
- package/dist/platform/testing.js +93 -11
- package/dist/platform/tool-trace.d.ts +9 -8
- package/dist/platform/tool-trace.js +19 -17
- package/dist/platform/types.d.ts +21 -1
- package/dist/platform/types.js +17 -1
- package/dist/store/channel-repo.d.ts +6 -0
- package/dist/store/channel-repo.js +9 -0
- package/dist/store/json-repository.js +12 -1
- package/dist/store/outbound-queue.d.ts +5 -4
- package/dist/store/outbound-queue.js +9 -6
- package/dist/store/schedule-repo.d.ts +9 -5
- package/dist/store/schedule-repo.js +59 -14
- package/dist/store/session-registry-repo.d.ts +36 -7
- package/dist/store/session-registry-repo.js +186 -25
- package/dist/store/thread-repo.d.ts +1 -0
- package/dist/store/thread-repo.js +8 -0
- package/package.json +1 -1
- package/dist/platform/virtual-message.d.ts +0 -68
|
@@ -14,7 +14,7 @@ import { completeTask, uncompleteTask } from './task-completion.js';
|
|
|
14
14
|
import { addTask, batchEdit, decomposeTask } from './task-mutations.js';
|
|
15
15
|
import { stopTask, stopTaskDryRun } from './task-process.js';
|
|
16
16
|
import { acquireLock, assertLockHeld, getOwnerIdentity, readLock, releaseLock, } from './task-lock.js';
|
|
17
|
-
const READ_COMMANDS = new Set(['list', 'all', 'query', 'show', 'deps', 'lint', 'stats']);
|
|
17
|
+
const READ_COMMANDS = new Set(['list', 'all', 'query', 'show', 'deps', 'lint', 'stats', 'tree']);
|
|
18
18
|
const WRITE_COMMANDS = new Set([
|
|
19
19
|
'claim', 'unclaim', 'pause', 'resume', 'pending', 'complete', 'uncomplete',
|
|
20
20
|
'request-approval', 'approve', 'clear-approval',
|
|
@@ -40,11 +40,13 @@ const COMMANDS_NEEDING_PROJECT = new Set([
|
|
|
40
40
|
]);
|
|
41
41
|
const COMMON_FLAGS = new Set(['--base-dir', '--project', '--task-id']);
|
|
42
42
|
const COMMAND_FLAG_ALLOWLIST = {
|
|
43
|
-
list: new Set([...COMMON_FLAGS, '--status', '--priority', '--text', '--has-deps', '--no-deps', '--all', '--json']),
|
|
44
|
-
all: new Set([...COMMON_FLAGS, '--status', '--priority', '--text', '--has-deps', '--no-deps', '--json']),
|
|
45
|
-
query: new Set([...COMMON_FLAGS, '--status', '--priority', '--text', '--has-deps', '--no-deps', '--json']),
|
|
46
|
-
show: new Set([...COMMON_FLAGS, '--json']),
|
|
47
|
-
deps: new Set([...COMMON_FLAGS, '--json']),
|
|
43
|
+
list: new Set([...COMMON_FLAGS, '--status', '--priority', '--text', '--has-deps', '--no-deps', '--all', '--json', '--show-deps']),
|
|
44
|
+
all: new Set([...COMMON_FLAGS, '--status', '--priority', '--text', '--has-deps', '--no-deps', '--json', '--show-deps']),
|
|
45
|
+
query: new Set([...COMMON_FLAGS, '--status', '--priority', '--text', '--has-deps', '--no-deps', '--json', '--show-deps']),
|
|
46
|
+
show: new Set([...COMMON_FLAGS, '--json', '--task-ids']),
|
|
47
|
+
deps: new Set([...COMMON_FLAGS, '--json', '--task-ids']),
|
|
48
|
+
tree: new Set([...COMMON_FLAGS]),
|
|
49
|
+
add: new Set([...COMMON_FLAGS, '--text', '--why', '--done-when', '--plan', '--priority', '--template', '--depends-on', '--auto-lock']),
|
|
48
50
|
lint: new Set([...COMMON_FLAGS, '--json']),
|
|
49
51
|
stats: new Set([...COMMON_FLAGS, '--json']),
|
|
50
52
|
claim: new Set([...COMMON_FLAGS, '--task', '--agent']),
|
|
@@ -59,17 +61,16 @@ const COMMAND_FLAG_ALLOWLIST = {
|
|
|
59
61
|
'clear-approval': new Set([...COMMON_FLAGS, '--task']),
|
|
60
62
|
block: new Set([...COMMON_FLAGS, '--task', '--reason']),
|
|
61
63
|
unblock: new Set([...COMMON_FLAGS, '--task']),
|
|
62
|
-
add: new Set([...COMMON_FLAGS, '--text', '--why', '--done-when', '--plan', '--priority', '--template', '--depends-on']),
|
|
63
64
|
edit: new Set([
|
|
64
65
|
...COMMON_FLAGS, '--task', '--text', '--why', '--done-when', '--plan', '--priority',
|
|
65
|
-
'--depends-on', '--add-depends-on', '--remove-depends-on', '--clear-depends-on',
|
|
66
|
+
'--depends-on', '--add-depends-on', '--remove-depends-on', '--clear-depends-on', '--auto-lock',
|
|
66
67
|
]),
|
|
67
68
|
'batch-edit': new Set([
|
|
68
69
|
...COMMON_FLAGS, '--task-ids', '--text', '--why', '--done-when', '--plan', '--priority',
|
|
69
|
-
'--depends-on', '--add-depends-on', '--remove-depends-on', '--clear-depends-on',
|
|
70
|
+
'--depends-on', '--add-depends-on', '--remove-depends-on', '--clear-depends-on', '--auto-lock',
|
|
70
71
|
]),
|
|
71
|
-
decompose: new Set([...COMMON_FLAGS, '--task', '--subtasks-file', '--dry-run']),
|
|
72
|
-
'assign-ids': new Set([...COMMON_FLAGS]),
|
|
72
|
+
decompose: new Set([...COMMON_FLAGS, '--task', '--subtasks-file', '--dry-run', '--auto-lock']),
|
|
73
|
+
'assign-ids': new Set([...COMMON_FLAGS, '--auto-lock']),
|
|
73
74
|
validate: new Set([...COMMON_FLAGS]),
|
|
74
75
|
stop: new Set([...COMMON_FLAGS, '--dry-run']),
|
|
75
76
|
'lock-acquire': new Set([...COMMON_FLAGS, '--force', '--note', '--json']),
|
|
@@ -87,8 +88,9 @@ const HELP_CONFIG = {
|
|
|
87
88
|
commands: [
|
|
88
89
|
{ name: 'list', description: 'Show actionable tasks (default). Use --all for all tasks' },
|
|
89
90
|
{ name: 'query', description: 'Filter by status, priority, text, task-id' },
|
|
90
|
-
{ name: 'show', description: 'Show detailed info for
|
|
91
|
-
{ name: 'deps', description: 'Show dependency graph for
|
|
91
|
+
{ name: 'show', description: 'Show detailed info for task(s) (--task-id or --task-ids)' },
|
|
92
|
+
{ name: 'deps', description: 'Show dependency graph for task(s) (--task-id or --task-ids)' },
|
|
93
|
+
{ name: 'tree', description: 'Show dependency tree (--project; optionally --task-id for subtree)' },
|
|
92
94
|
{ name: 'lint', description: 'Lint task structure (missing-id, dangling deps, cycles)' },
|
|
93
95
|
{ name: 'stats', description: 'Task supply statistics per project' },
|
|
94
96
|
],
|
|
@@ -151,7 +153,7 @@ const HELP_CONFIG = {
|
|
|
151
153
|
{ flag: '--project <name>', description: 'Project name (required for most write commands; filters reads)' },
|
|
152
154
|
{ flag: '--task-id <id>', description: 'Task hash ID (4-char hex)' },
|
|
153
155
|
{ flag: '--task <text>', description: 'Lookup by task text (fuzzy alternative to --task-id; not for `add`)' },
|
|
154
|
-
{ flag: '--task-ids <ids>', description: 'Comma-separated task IDs (
|
|
156
|
+
{ flag: '--task-ids <ids>', description: 'Comma-separated task IDs (batch-edit, show, deps)' },
|
|
155
157
|
{ flag: '--agent <name>', description: 'Agent identifier for claim', default: 'cortex-local' },
|
|
156
158
|
{ flag: '--note <text>', description: 'Completion note' },
|
|
157
159
|
{ flag: '--reason <text>', description: 'Block reason' },
|
|
@@ -169,10 +171,12 @@ const HELP_CONFIG = {
|
|
|
169
171
|
{ flag: '--status <status>', description: 'Filter by status (read commands)' },
|
|
170
172
|
{ flag: '--has-deps', description: 'Read-only: tasks with dependencies' },
|
|
171
173
|
{ flag: '--no-deps', description: 'Read-only: tasks without dependencies' },
|
|
174
|
+
{ flag: '--show-deps', description: 'Read-only: show dependency IDs after each task line (list/all/query)' },
|
|
172
175
|
{ flag: '--all', description: 'Read-only: include completed tasks (with `list`)' },
|
|
173
176
|
{ flag: '--json', description: 'Output as JSON (read commands)' },
|
|
174
177
|
{ flag: '--base-dir <path>', description: 'Cortex root directory', default: '~/Cortex' },
|
|
175
178
|
{ flag: '--dry-run', description: 'Preview without executing (stop, decompose)' },
|
|
179
|
+
{ flag: '--auto-lock', description: 'Auto-acquire project lock before write (does NOT auto-release)' },
|
|
176
180
|
{ flag: '--skip-verify', description: 'Skip completion evidence check for `complete` (escape hatch)' },
|
|
177
181
|
{ flag: '--skip-verify-reason <text>', description: 'Reason for skipping verification (logged in result)' },
|
|
178
182
|
{ flag: '--help', description: 'Show this help' },
|
|
@@ -249,6 +253,8 @@ function createDefaults() {
|
|
|
249
253
|
skipVerify: false,
|
|
250
254
|
skipVerifyReason: null,
|
|
251
255
|
force: false,
|
|
256
|
+
showDeps: false,
|
|
257
|
+
autoLock: false,
|
|
252
258
|
};
|
|
253
259
|
}
|
|
254
260
|
function splitCommand(argv) {
|
|
@@ -330,6 +336,14 @@ function parseOptions(args, values, seen) {
|
|
|
330
336
|
seen.add(token);
|
|
331
337
|
values.force = true;
|
|
332
338
|
}
|
|
339
|
+
else if (token === '--show-deps') {
|
|
340
|
+
seen.add(token);
|
|
341
|
+
values.showDeps = true;
|
|
342
|
+
}
|
|
343
|
+
else if (token === '--auto-lock') {
|
|
344
|
+
seen.add(token);
|
|
345
|
+
values.autoLock = true;
|
|
346
|
+
}
|
|
333
347
|
else {
|
|
334
348
|
throw cliError(`Unknown argument: ${token}`);
|
|
335
349
|
}
|
|
@@ -350,8 +364,8 @@ function validateCommand(command, values) {
|
|
|
350
364
|
throw cliError(`Unknown command: '${command}'. Available commands: ${[...ALL_COMMANDS].join(', ')}`);
|
|
351
365
|
}
|
|
352
366
|
if (READ_COMMANDS.has(command)) {
|
|
353
|
-
if ((command === 'show' || command === 'deps') && !values.taskId) {
|
|
354
|
-
throw cliError(`--task-id is required for ${command}`);
|
|
367
|
+
if ((command === 'show' || command === 'deps') && !values.taskId && values.taskIds.length === 0) {
|
|
368
|
+
throw cliError(`--task-id or --task-ids is required for ${command}`);
|
|
355
369
|
}
|
|
356
370
|
if (values.status && values.status !== '__all__' && !VALID_STATUSES.has(values.status)) {
|
|
357
371
|
throw cliError(`invalid --status: '${values.status}'. Valid values: ${[...VALID_STATUSES].join(', ')}`);
|
|
@@ -400,8 +414,25 @@ function buildReadFilters(v) {
|
|
|
400
414
|
showAll,
|
|
401
415
|
};
|
|
402
416
|
}
|
|
417
|
+
// ── JSON output helpers ──
|
|
418
|
+
function deepKebabKeys(obj) {
|
|
419
|
+
if (Array.isArray(obj))
|
|
420
|
+
return obj.map(deepKebabKeys);
|
|
421
|
+
if (obj !== null && typeof obj === 'object') {
|
|
422
|
+
const out = {};
|
|
423
|
+
for (const [k, v] of Object.entries(obj)) {
|
|
424
|
+
const key = k.replace(/_/g, '-');
|
|
425
|
+
out[key] = deepKebabKeys(v);
|
|
426
|
+
}
|
|
427
|
+
return out;
|
|
428
|
+
}
|
|
429
|
+
return obj;
|
|
430
|
+
}
|
|
431
|
+
function jsonOutput(payload) {
|
|
432
|
+
return JSON.stringify(deepKebabKeys(payload), null, 2);
|
|
433
|
+
}
|
|
403
434
|
function jsonOrText(json, payload, fallback) {
|
|
404
|
-
return json ?
|
|
435
|
+
return json ? jsonOutput(payload) : fallback;
|
|
405
436
|
}
|
|
406
437
|
function handleList(v) {
|
|
407
438
|
const filters = buildReadFilters(v);
|
|
@@ -410,25 +441,38 @@ function handleList(v) {
|
|
|
410
441
|
const cHashes = completedHashSet(allTasks);
|
|
411
442
|
const scoped = filters.project ? allTasks.filter((t) => t.project === filters.project) : allTasks;
|
|
412
443
|
const tasks = filterTasks(scoped, filters, cHashes);
|
|
413
|
-
return { exitCode: 0, stdout: jsonOrText(v.json, tasks, printTaskListToString(tasks, false)), stderr: '' };
|
|
444
|
+
return { exitCode: 0, stdout: jsonOrText(v.json, tasks, printTaskListToString(tasks, false, v.showDeps)), stderr: '' };
|
|
414
445
|
}
|
|
415
446
|
const tasks = filterTasks(scanAvailableTasks(), filters);
|
|
416
|
-
return { exitCode: 0, stdout: jsonOrText(v.json, tasks, printTaskListToString(tasks, true)), stderr: '' };
|
|
447
|
+
return { exitCode: 0, stdout: jsonOrText(v.json, tasks, printTaskListToString(tasks, true, v.showDeps)), stderr: '' };
|
|
417
448
|
}
|
|
418
449
|
function handleQuery(v) {
|
|
419
450
|
const filters = buildReadFilters(v);
|
|
420
451
|
const allTasks = scanAllTasks();
|
|
421
452
|
const cHashes = completedHashSet(allTasks);
|
|
422
453
|
const tasks = filterTasks(allTasks, filters, cHashes);
|
|
423
|
-
|
|
454
|
+
const textOutput = v.showDeps
|
|
455
|
+
? printTaskListToString(tasks, false, true)
|
|
456
|
+
: tasks.map((t) => t.text).join('\n');
|
|
457
|
+
return { exitCode: 0, stdout: jsonOrText(v.json, tasks, textOutput), stderr: '' };
|
|
424
458
|
}
|
|
425
459
|
function handleShowOrDeps(command, v) {
|
|
426
460
|
const allTasks = scanAllTasks();
|
|
461
|
+
const buildPayload = (task) => command === 'show' ? showPayload(task, allTasks) : depsPayload(task, allTasks);
|
|
462
|
+
if (v.taskIds.length > 0) {
|
|
463
|
+
const results = v.taskIds.map((id) => {
|
|
464
|
+
const task = allTasks.find((t) => t.id === id);
|
|
465
|
+
if (!task)
|
|
466
|
+
throw cliError(`task not found: ${id}`);
|
|
467
|
+
return buildPayload(task);
|
|
468
|
+
});
|
|
469
|
+
return { exitCode: 0, stdout: jsonOrText(v.json, results, JSON.stringify({ tasks: results }, null, 2)), stderr: '' };
|
|
470
|
+
}
|
|
427
471
|
const task = allTasks.find((t) => t.id === v.taskId);
|
|
428
472
|
if (!task)
|
|
429
473
|
throw cliError(`task not found: ${v.taskId}`);
|
|
430
|
-
const payload =
|
|
431
|
-
return { exitCode: 0, stdout: jsonOrText(v.json, payload,
|
|
474
|
+
const payload = buildPayload(task);
|
|
475
|
+
return { exitCode: 0, stdout: jsonOrText(v.json, payload, jsonOutput(payload)), stderr: '' };
|
|
432
476
|
}
|
|
433
477
|
function handleLint(v) {
|
|
434
478
|
const filters = buildReadFilters(v);
|
|
@@ -441,7 +485,88 @@ function handleLint(v) {
|
|
|
441
485
|
catch { /* suppress loadConfig output */ }
|
|
442
486
|
const validTemplateNames = new Set(listTemplateNames());
|
|
443
487
|
const payload = lintTasks(tasks, { validTemplateNames: validTemplateNames.size > 0 ? validTemplateNames : null });
|
|
444
|
-
return { exitCode: 0, stdout: jsonOrText(v.json, payload,
|
|
488
|
+
return { exitCode: 0, stdout: jsonOrText(v.json, payload, jsonOutput(payload)), stderr: '' };
|
|
489
|
+
}
|
|
490
|
+
function buildTree(task, taskMap, visited) {
|
|
491
|
+
if (visited.has(task.id))
|
|
492
|
+
return null;
|
|
493
|
+
visited.add(task.id);
|
|
494
|
+
const children = [];
|
|
495
|
+
for (const t of taskMap.values()) {
|
|
496
|
+
if (t.depends_on?.includes(task.id)) {
|
|
497
|
+
const child = buildTree(t, taskMap, visited);
|
|
498
|
+
if (child)
|
|
499
|
+
children.push(child);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
return { id: task.id, text: task.text, children };
|
|
503
|
+
}
|
|
504
|
+
function printTree(nodes, prefix, shared, completedIds) {
|
|
505
|
+
const lines = [];
|
|
506
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
507
|
+
const node = nodes[i];
|
|
508
|
+
const isLast = i === nodes.length - 1;
|
|
509
|
+
const connector = isLast ? '└── ' : '├── ';
|
|
510
|
+
const childPrefix = isLast ? ' ' : '│ ';
|
|
511
|
+
const marks = [];
|
|
512
|
+
if (completedIds.has(node.id))
|
|
513
|
+
marks.push('done');
|
|
514
|
+
if (shared.has(node.id))
|
|
515
|
+
marks.push('shared');
|
|
516
|
+
const mark = marks.length > 0 ? ` (${marks.join(', ')})` : '';
|
|
517
|
+
lines.push(`${prefix}${connector}${node.id} ${node.text}${mark}`);
|
|
518
|
+
if (node.children.length > 0) {
|
|
519
|
+
const childShared = new Set(shared);
|
|
520
|
+
for (const n of nodes) {
|
|
521
|
+
if (n.id !== node.id)
|
|
522
|
+
childShared.add(n.id);
|
|
523
|
+
}
|
|
524
|
+
lines.push(printTree(node.children, prefix + childPrefix, childShared, completedIds));
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
return lines.join('\n');
|
|
528
|
+
}
|
|
529
|
+
function handleTree(v) {
|
|
530
|
+
const allTasks = scanAllTasks();
|
|
531
|
+
const scoped = v.project ? allTasks.filter((t) => t.project === v.project) : allTasks;
|
|
532
|
+
const entries = [];
|
|
533
|
+
for (const t of scoped) {
|
|
534
|
+
if (t.id)
|
|
535
|
+
entries.push([t.id, t]);
|
|
536
|
+
}
|
|
537
|
+
const taskMap = new Map(entries);
|
|
538
|
+
const completedIds = new Set(completedHashSet(scoped));
|
|
539
|
+
if (v.taskId) {
|
|
540
|
+
// Subtree mode: root is the specified task
|
|
541
|
+
const task = taskMap.get(v.taskId);
|
|
542
|
+
if (!task)
|
|
543
|
+
return { exitCode: 0, stdout: `No task found: ${v.taskId}`, stderr: '' };
|
|
544
|
+
const visited = new Set();
|
|
545
|
+
const node = buildTree(task, taskMap, visited);
|
|
546
|
+
if (!node)
|
|
547
|
+
return { exitCode: 0, stdout: `${v.taskId} ${task.text}`, stderr: '' };
|
|
548
|
+
return { exitCode: 0, stdout: `${node.id} ${node.text}\n${printTree([node], '', new Set(), completedIds)}`, stderr: '' };
|
|
549
|
+
}
|
|
550
|
+
// Full tree: tasks with no open deps are roots (including completed roots)
|
|
551
|
+
const roots = [];
|
|
552
|
+
for (const task of scoped) {
|
|
553
|
+
if (!task.id)
|
|
554
|
+
continue;
|
|
555
|
+
const openDeps = task.depends_on.filter((d) => {
|
|
556
|
+
const dep = taskMap.get(d);
|
|
557
|
+
return dep && !completedIds.has(d);
|
|
558
|
+
});
|
|
559
|
+
if (openDeps.length === 0)
|
|
560
|
+
roots.push(task);
|
|
561
|
+
}
|
|
562
|
+
if (roots.length === 0) {
|
|
563
|
+
return { exitCode: 0, stdout: v.taskId ? `No task found: ${v.taskId}` : 'No open tasks', stderr: '' };
|
|
564
|
+
}
|
|
565
|
+
const visited = new Set();
|
|
566
|
+
const nodes = roots.map((r) => buildTree(r, taskMap, visited)).filter((n) => n !== null);
|
|
567
|
+
const openCount = roots.filter((r) => !completedIds.has(r.id)).length;
|
|
568
|
+
const header = `Dependency tree for ${v.project || 'all projects'} (${roots.length} root(s), ${openCount} open)\n`;
|
|
569
|
+
return { exitCode: 0, stdout: header + printTree(nodes, '', new Set(), completedIds), stderr: '' };
|
|
445
570
|
}
|
|
446
571
|
function handleStats(v) {
|
|
447
572
|
const stats = getTaskStats();
|
|
@@ -581,7 +706,7 @@ function runWrite(command, values) {
|
|
|
581
706
|
if (command === 'lock-status') {
|
|
582
707
|
const result = handleLockStatus(values);
|
|
583
708
|
if (values.json) {
|
|
584
|
-
return { exitCode: 0, stdout:
|
|
709
|
+
return { exitCode: 0, stdout: jsonOutput(result), stderr: '' };
|
|
585
710
|
}
|
|
586
711
|
if (result.projects) {
|
|
587
712
|
const lines = result.projects.map((p) => {
|
|
@@ -599,27 +724,61 @@ function runWrite(command, values) {
|
|
|
599
724
|
const handler = WRITE_HANDLERS[command];
|
|
600
725
|
if (!handler)
|
|
601
726
|
throw cliError(`Unknown command: '${command}'`);
|
|
602
|
-
|
|
727
|
+
// ── Auto-lock ──
|
|
728
|
+
let autoLocked = false;
|
|
729
|
+
if (values.autoLock && (LOCK_GUARD_COMMANDS.has(command) || command === LOCK_GUARD_ASSIGN_IDS)) {
|
|
730
|
+
const owner = getOwnerIdentity();
|
|
731
|
+
const projectsToAutoLock = (command === LOCK_GUARD_ASSIGN_IDS && !values.project)
|
|
732
|
+
? listProjectDirs()
|
|
733
|
+
: [values.project];
|
|
734
|
+
for (const p of projectsToAutoLock) {
|
|
735
|
+
const current = readLock(p);
|
|
736
|
+
if (current) {
|
|
737
|
+
const err = assertLockHeld(p, owner);
|
|
738
|
+
if (err) {
|
|
739
|
+
const result = { success: false, message: `Cannot auto-lock project '${p}': ${err}` };
|
|
740
|
+
return { exitCode: 1, stdout: jsonOutput(result), stderr: '' };
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
else {
|
|
744
|
+
const acq = acquireLock(p, { owner });
|
|
745
|
+
if (!acq.acquired) {
|
|
746
|
+
const result = { success: false, message: `Auto-lock failed for project '${p}': ${acq.message}` };
|
|
747
|
+
return { exitCode: 1, stdout: jsonOutput(result), stderr: '' };
|
|
748
|
+
}
|
|
749
|
+
autoLocked = true;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
if (LOCK_GUARD_COMMANDS.has(command) && !values.autoLock) {
|
|
603
754
|
const owner = getOwnerIdentity();
|
|
604
755
|
const err = assertLockHeld(values.project, owner);
|
|
605
756
|
if (err) {
|
|
606
757
|
const result = { success: false, message: `Lock required: ${err}\nRun: cortex-task lock-acquire --project ${values.project}` };
|
|
607
|
-
return { exitCode: 1, stdout:
|
|
758
|
+
return { exitCode: 1, stdout: jsonOutput(result), stderr: '' };
|
|
608
759
|
}
|
|
609
760
|
}
|
|
610
|
-
if (command === LOCK_GUARD_ASSIGN_IDS) {
|
|
761
|
+
if (command === LOCK_GUARD_ASSIGN_IDS && !values.autoLock) {
|
|
611
762
|
const owner = getOwnerIdentity();
|
|
612
763
|
const projectsToCheck = values.project ? [values.project] : listProjectDirs();
|
|
613
764
|
for (const p of projectsToCheck) {
|
|
614
765
|
const err = assertLockHeld(p, owner);
|
|
615
766
|
if (err) {
|
|
616
767
|
const result = { success: false, message: `Lock required for project '${p}': ${err}\nRun: cortex-task lock-acquire --project ${p}` };
|
|
617
|
-
return { exitCode: 1, stdout:
|
|
768
|
+
return { exitCode: 1, stdout: jsonOutput(result), stderr: '' };
|
|
618
769
|
}
|
|
619
770
|
}
|
|
620
771
|
}
|
|
621
772
|
const result = handler(values);
|
|
622
|
-
|
|
773
|
+
const stderrLines = [];
|
|
774
|
+
if (autoLocked && result.success !== false) {
|
|
775
|
+
stderrLines.push(`Lock acquired automatically. Release with: cortex-task lock-release --project ${values.project}`);
|
|
776
|
+
}
|
|
777
|
+
return {
|
|
778
|
+
exitCode: result.success ? 0 : 1,
|
|
779
|
+
stdout: jsonOutput(result),
|
|
780
|
+
stderr: stderrLines.join('\n'),
|
|
781
|
+
};
|
|
623
782
|
}
|
|
624
783
|
function runRead(command, values) {
|
|
625
784
|
switch (command) {
|
|
@@ -628,6 +787,7 @@ function runRead(command, values) {
|
|
|
628
787
|
case 'query': return handleQuery(values);
|
|
629
788
|
case 'show': return handleShowOrDeps('show', values);
|
|
630
789
|
case 'deps': return handleShowOrDeps('deps', values);
|
|
790
|
+
case 'tree': return handleTree(values);
|
|
631
791
|
case 'lint': return handleLint(values);
|
|
632
792
|
case 'stats': return handleStats(values);
|
|
633
793
|
default: throw cliError(`Unknown read command: ${command}`);
|
|
@@ -180,7 +180,7 @@ function editTask(project, options = {}) {
|
|
|
180
180
|
}
|
|
181
181
|
if (doneWhen != null) {
|
|
182
182
|
task.done_when = doneWhen;
|
|
183
|
-
updatedFields.push('
|
|
183
|
+
updatedFields.push('done-when');
|
|
184
184
|
}
|
|
185
185
|
if (plan != null) {
|
|
186
186
|
task.plan = plan.trim();
|
|
@@ -192,7 +192,7 @@ function editTask(project, options = {}) {
|
|
|
192
192
|
}
|
|
193
193
|
if (clearDependsOn || expandedSetDependsOn != null) {
|
|
194
194
|
task.depends_on = expandedSetDependsOn ?? [];
|
|
195
|
-
updatedFields.push('
|
|
195
|
+
updatedFields.push('depends-on');
|
|
196
196
|
}
|
|
197
197
|
else if (expandedAddDependsOn.length > 0 || expandedRemoveDependsOn.length > 0) {
|
|
198
198
|
task.depends_on = task.depends_on.filter((id) => !expandedRemoveDependsOn.includes(id));
|
|
@@ -200,7 +200,7 @@ function editTask(project, options = {}) {
|
|
|
200
200
|
if (!task.depends_on.includes(id))
|
|
201
201
|
task.depends_on.push(id);
|
|
202
202
|
}
|
|
203
|
-
updatedFields.push('
|
|
203
|
+
updatedFields.push('depends-on');
|
|
204
204
|
}
|
|
205
205
|
writeTasks(project, tasks);
|
|
206
206
|
return { success: true, message: 'Task updated', task_id: taskId, updated_fields: updatedFields };
|
|
@@ -8,7 +8,7 @@ import { threadStore } from '../../store/thread-repo.js';
|
|
|
8
8
|
import { getSessionKey, recordStepResult } from './index.js';
|
|
9
9
|
import { runAgent, getClaudeMode, getActiveBackend, getActiveProfile } from '../agents/index.js';
|
|
10
10
|
import * as executionRegistry from '../executions/registry.js';
|
|
11
|
-
import {
|
|
11
|
+
import { sessionStore } from '../../store/session-registry-repo.js';
|
|
12
12
|
import { DATA_DIR } from '../../core/utils.js';
|
|
13
13
|
import { createLogger } from '../../core/log.js';
|
|
14
14
|
import { runningExecutions } from '../../core/running-executions.js';
|
|
@@ -106,6 +106,10 @@ async function runHookAgent(threadId, hookResult, phase, opts) {
|
|
|
106
106
|
if (!hookResult.prompt)
|
|
107
107
|
return;
|
|
108
108
|
const thread = threadStore.get(threadId);
|
|
109
|
+
if (!thread) {
|
|
110
|
+
log.error(`Thread not found: ${threadId}, skipping hook agent`);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
109
113
|
const isTargetMode = !!hookResult.targetAgent;
|
|
110
114
|
// Determine slotId, sessionKey, sessionId, profile based on mode
|
|
111
115
|
let slotId;
|
|
@@ -148,7 +152,7 @@ async function runHookAgent(threadId, hookResult, phase, opts) {
|
|
|
148
152
|
// Notify Slack
|
|
149
153
|
const slackLabel = isTargetMode ? `→ ${slotId}` : `hook:${phase}`;
|
|
150
154
|
try {
|
|
151
|
-
await opts.adapter.postMessage(opts.
|
|
155
|
+
await opts.adapter.postMessage(opts.destination, {
|
|
152
156
|
text: `:hook: Hook agent (*${slackLabel}*) starting...`,
|
|
153
157
|
}, opts.threadTs ? { threadId: opts.threadTs } : undefined);
|
|
154
158
|
}
|
|
@@ -160,7 +164,7 @@ async function runHookAgent(threadId, hookResult, phase, opts) {
|
|
|
160
164
|
: meta?.trigger === 'scheduled' ? 'scheduled'
|
|
161
165
|
: 'local',
|
|
162
166
|
channel: opts.channel,
|
|
163
|
-
project:
|
|
167
|
+
project: thread.projectId,
|
|
164
168
|
trigger: 'thread-hook',
|
|
165
169
|
backend: getActiveBackend(),
|
|
166
170
|
billingMode: getClaudeMode(),
|
|
@@ -170,7 +174,7 @@ async function runHookAgent(threadId, hookResult, phase, opts) {
|
|
|
170
174
|
threadId,
|
|
171
175
|
agentSlotId: slotId,
|
|
172
176
|
});
|
|
173
|
-
const sessionName = isTargetMode ? null : await
|
|
177
|
+
const sessionName = isTargetMode ? null : await sessionStore.generateSessionName();
|
|
174
178
|
const stepStartTime = new Date().toISOString();
|
|
175
179
|
const handle = runAgent(prompt, {
|
|
176
180
|
channel: opts.channel,
|
|
@@ -178,12 +182,12 @@ async function runHookAgent(threadId, hookResult, phase, opts) {
|
|
|
178
182
|
sessionKey,
|
|
179
183
|
files: [],
|
|
180
184
|
profileName,
|
|
181
|
-
project:
|
|
185
|
+
project: thread.projectId,
|
|
182
186
|
trigger: meta?.trigger || undefined,
|
|
183
187
|
onFallback: null,
|
|
184
188
|
isUserInitiated: false,
|
|
185
189
|
onAssistantMessage: (text) => {
|
|
186
|
-
opts.adapter.postMessage(opts.
|
|
190
|
+
opts.adapter.postMessage(opts.destination, { text }, opts.threadTs ? { threadId: opts.threadTs } : undefined).catch(() => { });
|
|
187
191
|
},
|
|
188
192
|
onProgress: null,
|
|
189
193
|
});
|
|
@@ -218,13 +222,14 @@ async function runHookAgent(threadId, hookResult, phase, opts) {
|
|
|
218
222
|
durationS: stepDurationS,
|
|
219
223
|
});
|
|
220
224
|
if (result?.sessionId && sessionName) {
|
|
221
|
-
await
|
|
225
|
+
await sessionStore.registerSession(sessionName, {
|
|
222
226
|
sessionId: result.sessionId,
|
|
223
227
|
channel: opts.channel,
|
|
224
228
|
backend: getActiveBackend(),
|
|
225
229
|
kind: 'local',
|
|
226
230
|
label: `[${threadId}:${slotId}]`,
|
|
227
231
|
profileName: getActiveProfile(opts.channel),
|
|
232
|
+
projectId: thread.projectId,
|
|
228
233
|
});
|
|
229
234
|
}
|
|
230
235
|
executionRegistry.completeExecution(execution.id, {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { OutputStream } from '../../platform/index.js';
|
|
2
2
|
import type { RunningExecution } from '../../core/running-executions.js';
|
|
3
3
|
import type { ThreadRecord, AgentSlotId, AgentSlotConfig, ThreadTemplate, RunThreadOptions } from '../../core/types/thread-types.js';
|
|
4
4
|
interface ThreadRunResult {
|
|
@@ -22,7 +22,7 @@ interface ThreadContext {
|
|
|
22
22
|
isDefault: boolean;
|
|
23
23
|
template: ThreadTemplate | null;
|
|
24
24
|
meta: ThreadRecord['metadata'];
|
|
25
|
-
|
|
25
|
+
stream: OutputStream | null;
|
|
26
26
|
lastAgentResult: any;
|
|
27
27
|
totalNumTurns: number;
|
|
28
28
|
}
|
|
@@ -53,7 +53,7 @@ interface StepCallbacks {
|
|
|
53
53
|
onToolUse: ((name: string, input: any) => void) | null;
|
|
54
54
|
}
|
|
55
55
|
type StepInfo = Pick<StepContext, 'agentSlotId' | 'agentConfig' | 'isFirstStep' | 'multiAgent' | 'stage'>;
|
|
56
|
-
/** Validate thread, load template/metadata, init the aggregating
|
|
56
|
+
/** Validate thread, load template/metadata, init the aggregating OutputStream. */
|
|
57
57
|
declare function initThreadContext(threadId: string, opts: RunThreadOptions): ThreadContext;
|
|
58
58
|
/** Resolve next step, post boundary notifications, update the status message.
|
|
59
59
|
* Returns null if the loop should break (cancelled, no next step). */
|
|
@@ -7,9 +7,8 @@ import { resolveNextStep, buildStepPrompt, recordStepResult, evaluateTransitions
|
|
|
7
7
|
import { runAgent, getClaudeMode, getActiveBackend, getActiveProfile } from '../agents/index.js';
|
|
8
8
|
import { closeSessionsByPrefix } from '../agents/index.js';
|
|
9
9
|
import * as executionRegistry from '../executions/registry.js';
|
|
10
|
-
import {
|
|
10
|
+
import { sessionStore } from '../../store/session-registry-repo.js';
|
|
11
11
|
import { formatDurationCompact } from '../../core/utils.js';
|
|
12
|
-
import { VirtualMessage } from '../../platform/index.js';
|
|
13
12
|
import { runningExecutions } from '../../core/running-executions.js';
|
|
14
13
|
import { executeLifecycleHook } from './hook-runner.js';
|
|
15
14
|
import { createToolTrace } from '../../platform/index.js';
|
|
@@ -18,17 +17,18 @@ import { createToolTrace } from '../../platform/index.js';
|
|
|
18
17
|
function formatAgentStageLabel(agentSlotId, stage) {
|
|
19
18
|
return stage ? `${agentSlotId}:${stage}` : agentSlotId;
|
|
20
19
|
}
|
|
21
|
-
/** Validate thread, load template/metadata, init the aggregating
|
|
20
|
+
/** Validate thread, load template/metadata, init the aggregating OutputStream. */
|
|
22
21
|
function initThreadContext(threadId, opts) {
|
|
23
22
|
const thread = threadStore.get(threadId);
|
|
24
23
|
if (!thread)
|
|
25
24
|
throw new Error(`Thread not found: ${threadId}`);
|
|
26
25
|
const isDefault = isDefaultThread(threadId);
|
|
27
26
|
const template = thread.templateName ? (getTemplate(thread.templateName) || null) : null;
|
|
28
|
-
// For all non-default threads, aggregate output into
|
|
27
|
+
// For all non-default threads, aggregate output into an OutputStream.
|
|
29
28
|
// Default template passes through opts.onAssistantMessage from app.ts (backward compat).
|
|
30
|
-
|
|
31
|
-
|
|
29
|
+
// The caller supplies the Destination (interactive-reply or project-report).
|
|
30
|
+
const stream = !isDefault ? opts.adapter.openOutputStream(opts.destination, { threadId: opts.threadTs }) : null;
|
|
31
|
+
return { thread, isDefault, template, meta: thread.metadata, stream, lastAgentResult: null, totalNumTurns: 0 };
|
|
32
32
|
}
|
|
33
33
|
/** Resolve next step, post boundary notifications, update the status message.
|
|
34
34
|
* Returns null if the loop should break (cancelled, no next step). */
|
|
@@ -47,14 +47,14 @@ async function resolveAndNotifyStep(threadId, ctx, opts) {
|
|
|
47
47
|
const threadRecord = threadStore.get(threadId);
|
|
48
48
|
const multiAgent = Object.keys(threadRecord.agents).length > 1;
|
|
49
49
|
const label = formatAgentStageLabel(agentSlotId, stage);
|
|
50
|
-
// Post step boundary notification for multi-agent threads via
|
|
51
|
-
if (ctx.
|
|
50
|
+
// Post step boundary notification for multi-agent threads via OutputStream
|
|
51
|
+
if (ctx.stream && multiAgent && !isFirstStep) {
|
|
52
52
|
const prevStep = threadRecord.steps[threadRecord.steps.length - 1];
|
|
53
53
|
const prevLabel = prevStep ? formatAgentStageLabel(prevStep.agentSlotId, prevStep.stage) : '?';
|
|
54
|
-
ctx.
|
|
54
|
+
ctx.stream.emitText(`:arrow_right: Step ${threadRecord.currentStepIndex + 1}: *${label}* starting (prev: ${prevLabel})`);
|
|
55
55
|
}
|
|
56
56
|
// Update status message (multi-agent thread format; skip if caller provides onProgress)
|
|
57
|
-
if (ctx.
|
|
57
|
+
if (ctx.stream && multiAgent && !opts.onProgress) {
|
|
58
58
|
const elapsed = (Date.now() - opts.startTime) / 1000;
|
|
59
59
|
const statusText = `:hourglass_flowing_sand: Thread ${threadRecord.id.substring(0, 12)} | Step ${threadRecord.currentStepIndex + 1}: *${label}* | :stopwatch: ${formatDurationCompact(elapsed)}`;
|
|
60
60
|
try {
|
|
@@ -102,7 +102,7 @@ async function buildStepConfig(threadId, stepInfo, ctx, opts) {
|
|
|
102
102
|
const execution = executionRegistry.startLocalExecution({
|
|
103
103
|
kind: executionKind,
|
|
104
104
|
channel: opts.channel,
|
|
105
|
-
project:
|
|
105
|
+
project: threadStore.get(threadId)?.projectId ?? 'general',
|
|
106
106
|
trigger: executionTrigger,
|
|
107
107
|
backend: getActiveBackend(),
|
|
108
108
|
billingMode: getClaudeMode(),
|
|
@@ -115,7 +115,7 @@ async function buildStepConfig(threadId, stepInfo, ctx, opts) {
|
|
|
115
115
|
return {
|
|
116
116
|
agentSlotId, agentConfig, isFirstStep, multiAgent, stage,
|
|
117
117
|
prompt, sessionId, sessionKey,
|
|
118
|
-
sessionName: (ctx.isDefault && opts.sessionName) ? opts.sessionName : await
|
|
118
|
+
sessionName: (ctx.isDefault && opts.sessionName) ? opts.sessionName : await sessionStore.generateSessionName(),
|
|
119
119
|
profileName, execution,
|
|
120
120
|
stepStartTime: new Date().toISOString(),
|
|
121
121
|
};
|
|
@@ -126,19 +126,19 @@ function setupStepCallbacks(threadId, stepCtx, ctx, opts) {
|
|
|
126
126
|
const { agentSlotId, multiAgent, stage } = stepCtx;
|
|
127
127
|
const threadRecord = threadStore.get(threadId);
|
|
128
128
|
const slot = threadRecord.agents[agentSlotId];
|
|
129
|
-
const
|
|
129
|
+
const stream = ctx.stream;
|
|
130
130
|
const label = formatAgentStageLabel(agentSlotId, stage);
|
|
131
131
|
// Determine callbacks:
|
|
132
|
-
// - default: pass through from opts (app.ts
|
|
133
|
-
// - non-default: aggregate into thread-runner's
|
|
132
|
+
// - default: pass through from opts (app.ts OutputStream)
|
|
133
|
+
// - non-default: aggregate into thread-runner's stream; prefix only for multi-agent
|
|
134
134
|
const slotPrefix = multiAgent ? `*[${label}]*` : null;
|
|
135
|
-
const baseAssistantMessage =
|
|
136
|
-
? (text) => {
|
|
135
|
+
const baseAssistantMessage = stream
|
|
136
|
+
? (text) => { stream.emitText(slotPrefix ? `${slotPrefix} ${text}` : text); }
|
|
137
137
|
: opts.onAssistantMessage;
|
|
138
138
|
// Tool trace (env-gated): caller-supplied onToolUse takes precedence (default-thread path —
|
|
139
|
-
// agent-runner owns the
|
|
139
|
+
// agent-runner owns the stream). Otherwise build one bound to the runner's own stream.
|
|
140
140
|
const callerOnToolUse = opts.onToolUse ?? null;
|
|
141
|
-
const toolTrace = callerOnToolUse ? null : createToolTrace(
|
|
141
|
+
const toolTrace = callerOnToolUse ? null : createToolTrace(stream, { slotPrefix });
|
|
142
142
|
const onAssistantMessage = toolTrace && baseAssistantMessage
|
|
143
143
|
? (text) => { toolTrace.flush(); baseAssistantMessage(text); }
|
|
144
144
|
: baseAssistantMessage;
|
|
@@ -147,7 +147,7 @@ function setupStepCallbacks(threadId, stepCtx, ctx, opts) {
|
|
|
147
147
|
// onProgress: caller override (e.g. scheduler's buildUserProcessingMessage) takes precedence;
|
|
148
148
|
// fallback to thread-specific status format for multi-agent pipelines
|
|
149
149
|
const onProgress = opts.onProgress
|
|
150
|
-
|| (
|
|
150
|
+
|| (stream && multiAgent
|
|
151
151
|
? (progress) => {
|
|
152
152
|
const elapsed = (Date.now() - opts.startTime) / 1000;
|
|
153
153
|
if (opts.statusMsg) {
|
|
@@ -174,7 +174,7 @@ async function executeAndAwaitAgent(threadId, stepCtx, callbacks, ctx, opts) {
|
|
|
174
174
|
sessionKey,
|
|
175
175
|
files: isFirstStep ? (opts.files || []) : [],
|
|
176
176
|
profileName,
|
|
177
|
-
project:
|
|
177
|
+
project: threadStore.get(threadId)?.projectId,
|
|
178
178
|
trigger: meta?.trigger || undefined,
|
|
179
179
|
threadId,
|
|
180
180
|
useCoreMcp: !ctx.isDefault,
|
|
@@ -240,14 +240,16 @@ async function recordStepOutcome(threadId, stepCtx, result, ctx, opts) {
|
|
|
240
240
|
});
|
|
241
241
|
ctx.totalNumTurns += result?.num_turns || 0;
|
|
242
242
|
// Register session
|
|
243
|
-
|
|
244
|
-
|
|
243
|
+
const currentThread = threadStore.get(threadId);
|
|
244
|
+
if (result?.sessionId && sessionName && currentThread) {
|
|
245
|
+
await sessionStore.registerSession(sessionName, {
|
|
245
246
|
sessionId: result.sessionId,
|
|
246
247
|
channel: opts.channel,
|
|
247
248
|
backend: getActiveBackend(),
|
|
248
249
|
kind: 'local',
|
|
249
250
|
label: `[${threadId}:${agentSlotId}]`,
|
|
250
251
|
profileName: getActiveProfile(opts.channel),
|
|
252
|
+
projectId: currentThread.projectId,
|
|
251
253
|
});
|
|
252
254
|
}
|
|
253
255
|
// Finalize execution
|
|
@@ -297,9 +299,9 @@ async function finalizeThread(threadId, ctx) {
|
|
|
297
299
|
// Final output comes from the artifact file
|
|
298
300
|
const artifactContent = readArtifact(threadId);
|
|
299
301
|
const finalOutput = artifactContent || ctx.lastAgentResult?.finalOutput || null;
|
|
300
|
-
if (ctx.
|
|
301
|
-
ctx.
|
|
302
|
-
await ctx.
|
|
302
|
+
if (ctx.stream && finalOutput) {
|
|
303
|
+
ctx.stream.emitText(finalOutput);
|
|
304
|
+
await ctx.stream.flush();
|
|
303
305
|
}
|
|
304
306
|
return {
|
|
305
307
|
thread: finalThread,
|
|
@@ -333,10 +335,10 @@ async function runThread(threadId, opts) {
|
|
|
333
335
|
const abortCheck = detectAbortMarker(threadId);
|
|
334
336
|
if (abortCheck.aborted) {
|
|
335
337
|
await abortThread(threadId, abortCheck.reason);
|
|
336
|
-
if (ctx.
|
|
338
|
+
if (ctx.stream) {
|
|
337
339
|
const reasonStr = abortCheck.reason ? `: ${abortCheck.reason}` : '';
|
|
338
340
|
const abortLabel = formatAgentStageLabel(stepCtx.agentSlotId, stepCtx.stage);
|
|
339
|
-
ctx.
|
|
341
|
+
ctx.stream.emitText(`:octagonal_sign: Thread aborted by *${abortLabel}*${reasonStr}`);
|
|
340
342
|
}
|
|
341
343
|
break;
|
|
342
344
|
}
|