@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
|
@@ -5,6 +5,7 @@ export declare function createThread(channel: string, options: {
|
|
|
5
5
|
userMessage: string;
|
|
6
6
|
userMessageTs: string;
|
|
7
7
|
platformThreadId?: string | null;
|
|
8
|
+
projectId?: string;
|
|
8
9
|
metadata?: import('../../core/types/thread-types.js').ThreadMetadata | null;
|
|
9
10
|
}): ThreadRecord;
|
|
10
11
|
/** Create a lightweight completed thread record (no filesystem workspace).
|
|
@@ -14,6 +15,7 @@ export declare function createAutoThreadRecord(channel: string, options: {
|
|
|
14
15
|
userMessage: string;
|
|
15
16
|
userMessageTs: string;
|
|
16
17
|
platformThreadId?: string | null;
|
|
18
|
+
projectId?: string;
|
|
17
19
|
}): ThreadRecord;
|
|
18
20
|
/** Create a thread record that uses the 'default' template (single-step, single-agent with workspace).
|
|
19
21
|
* Used by the agent-runner wrapper to create a thread BEFORE execution, so that isDefaultThread()
|
|
@@ -25,6 +27,7 @@ export declare function createDefaultThread(channel: string, options: {
|
|
|
25
27
|
userMessage: string;
|
|
26
28
|
userMessageTs: string;
|
|
27
29
|
platformThreadId?: string | null;
|
|
30
|
+
projectId?: string;
|
|
28
31
|
}): ThreadRecord;
|
|
29
32
|
export declare function addAgentToThread(threadId: string, agentName: string, userMessage?: string | null): Promise<ThreadRecord>;
|
|
30
33
|
interface NextStepInfo {
|
|
@@ -61,6 +61,7 @@ function makeThreadRecord(init) {
|
|
|
61
61
|
const now = new Date().toISOString();
|
|
62
62
|
return {
|
|
63
63
|
...init,
|
|
64
|
+
projectId: init.projectId ?? 'general',
|
|
64
65
|
status: 'running',
|
|
65
66
|
currentStepIndex: 0,
|
|
66
67
|
steps: [],
|
|
@@ -86,6 +87,7 @@ export function createThread(channel, options) {
|
|
|
86
87
|
const { workspacePath, artifactPath } = createWorkspace(id);
|
|
87
88
|
const thread = makeThreadRecord({
|
|
88
89
|
id, channel,
|
|
90
|
+
projectId: options.projectId,
|
|
89
91
|
templateName: options.templateName || null,
|
|
90
92
|
platformThreadId: options.platformThreadId || null,
|
|
91
93
|
userMessage: options.userMessage,
|
|
@@ -108,6 +110,7 @@ export function createAutoThreadRecord(channel, options) {
|
|
|
108
110
|
const id = threadStore.generateId();
|
|
109
111
|
const thread = makeThreadRecord({
|
|
110
112
|
id, channel,
|
|
113
|
+
projectId: options.projectId,
|
|
111
114
|
templateName: null,
|
|
112
115
|
platformThreadId: options.platformThreadId || null,
|
|
113
116
|
userMessage: options.userMessage,
|
|
@@ -135,6 +138,7 @@ export function createDefaultThread(channel, options) {
|
|
|
135
138
|
const { workspacePath, artifactPath } = createWorkspace(id);
|
|
136
139
|
const thread = makeThreadRecord({
|
|
137
140
|
id, channel,
|
|
141
|
+
projectId: options.projectId,
|
|
138
142
|
templateName: 'default',
|
|
139
143
|
platformThreadId: options.platformThreadId || null,
|
|
140
144
|
userMessage: options.userMessage,
|
package/dist/entry/app.js
CHANGED
|
@@ -18,6 +18,7 @@ import { registerCommands } from '../orchestration/routing/commands/index.js';
|
|
|
18
18
|
import { taskStore } from '../domain/tasks/store.js';
|
|
19
19
|
import { channelRepo } from '../store/channel-repo.js';
|
|
20
20
|
import { projectDirRepo } from '../store/project-dir-repo.js';
|
|
21
|
+
import { projectStore } from '../domain/projects/index.js';
|
|
21
22
|
import { sendStartupDmIfConfigured } from './startup-notify.js';
|
|
22
23
|
import { startGateway, stopGateway } from '../domain/costs/gateway-manager.js';
|
|
23
24
|
import { startClientManager, stopClientManager, startAllRemoteClients } from '../domain/remote/client-manager.js';
|
|
@@ -47,7 +48,8 @@ import { initRateLimitThrottle } from '../domain/costs/rate-limit-throttle.js';
|
|
|
47
48
|
import { scheduleRepo } from '../store/schedule-repo.js';
|
|
48
49
|
import { costRepo } from '../store/cost-repo.js';
|
|
49
50
|
import { profileRepo, startProfileWatcher, setAdminNotifier as setProfileNotifier } from '../store/profile-repo.js';
|
|
50
|
-
import {
|
|
51
|
+
import { sessionStore } from '../store/session-registry-repo.js';
|
|
52
|
+
import { cleanupAllBackups } from '../domain/sessions/session-backup.js';
|
|
51
53
|
import { initDiskMonitor, stopDiskMonitor } from '../domain/monitor/disk-monitor.js';
|
|
52
54
|
import { loadMachinesFromFile, startMachineRegistryWatcher, stopMachineRegistryWatcher, setAdminNotifier as setMachineNotifier } from '../domain/tasks/dispatch-utils.js';
|
|
53
55
|
import { EventBus, createEventLogger } from '../events/index.js';
|
|
@@ -76,9 +78,7 @@ startMachineRegistryWatcher();
|
|
|
76
78
|
const adapter = createAdapterFromEnv();
|
|
77
79
|
// --- Wire hot-reload admin notifiers ---
|
|
78
80
|
const notifyAdmin = (text) => {
|
|
79
|
-
|
|
80
|
-
if (ch)
|
|
81
|
-
adapter.postMessage(ch, { text }).catch(() => { });
|
|
81
|
+
adapter.postMessage({ type: 'system-notice' }, { text }).catch(() => { });
|
|
82
82
|
};
|
|
83
83
|
setProfileNotifier(notifyAdmin);
|
|
84
84
|
setConfigNotifier(notifyAdmin);
|
|
@@ -144,7 +144,7 @@ process.on('SIGTERM', async () => {
|
|
|
144
144
|
// `writeFile(tmp)` and `rename(tmp, target)` in atomic-write.ts leaves orphan .tmp.* siblings.
|
|
145
145
|
// Daemon gives 5s before SIGKILL — well over the time needed to flush a few MB of JSON.
|
|
146
146
|
try {
|
|
147
|
-
await Promise.allSettled([bus.close(), oq.flush(), threadStore.flush(), sessionRepo.flush(), conversationLedger.flush(), taskStore.flush(), executionRepo.flush(), channelRepo.flush(), projectDirRepo.flush(), scheduleRepo.flush(), costRepo.flush(), profileRepo.flush(),
|
|
147
|
+
await Promise.allSettled([bus.close(), oq.flush(), threadStore.flush(), sessionRepo.flush(), conversationLedger.flush(), taskStore.flush(), executionRepo.flush(), channelRepo.flush(), projectDirRepo.flush(), scheduleRepo.flush(), costRepo.flush(), profileRepo.flush(), sessionStore.flush()]);
|
|
148
148
|
}
|
|
149
149
|
catch { }
|
|
150
150
|
await stopGateway();
|
|
@@ -196,6 +196,18 @@ process.on('SIGTERM', async () => {
|
|
|
196
196
|
threadStore.load();
|
|
197
197
|
await threadStore.markRunningAsFailedOnStartup();
|
|
198
198
|
await threadStore.cleanup();
|
|
199
|
+
// GC: prune stale sessions (older than 7 days, unreferenced by running executions or active threads)
|
|
200
|
+
sessionStore.setOnPruneSession(cleanupAllBackups);
|
|
201
|
+
try {
|
|
202
|
+
const pruned = await sessionStore.pruneStale(7 * 24 * 60 * 60 * 1000);
|
|
203
|
+
if (pruned > 0)
|
|
204
|
+
log.info(`Startup GC: pruned ${pruned} stale session(s)`);
|
|
205
|
+
}
|
|
206
|
+
catch (e) {
|
|
207
|
+
log.warn(`Startup GC: pruneStale failed: ${e.message}`);
|
|
208
|
+
}
|
|
209
|
+
// M1: Initialize project registry (scaffolds general/, scans PROJECTS_DIR, starts fs.watch watcher)
|
|
210
|
+
await projectStore.initialize();
|
|
199
211
|
startGateway();
|
|
200
212
|
startClientManager(parseInt(process.env.CORTEX_CLIENT_PORT || '3002', 10));
|
|
201
213
|
setTimeout(async () => {
|
|
@@ -203,10 +215,7 @@ process.on('SIGTERM', async () => {
|
|
|
203
215
|
const updateResult = await checkAndUpdateClients();
|
|
204
216
|
if (updateResult) {
|
|
205
217
|
log.info(`Client hot-reload: ${updateResult.devices.length} devices updated in ${updateResult.duration}ms`);
|
|
206
|
-
|
|
207
|
-
if (adminChannel) {
|
|
208
|
-
await adapter.postMessage(adminChannel, { text: formatUpdateSlackMessage(updateResult) }).catch((e) => log.warn(`Hot-reload DM failed: ${e.message}`));
|
|
209
|
-
}
|
|
218
|
+
await adapter.postMessage({ type: 'system-notice' }, { text: formatUpdateSlackMessage(updateResult) }).catch((e) => log.warn(`Hot-reload DM failed: ${e.message}`));
|
|
210
219
|
}
|
|
211
220
|
}
|
|
212
221
|
catch (e) {
|
|
@@ -225,6 +234,18 @@ process.on('SIGTERM', async () => {
|
|
|
225
234
|
await scheduler.resume(t.id);
|
|
226
235
|
}
|
|
227
236
|
}
|
|
237
|
+
// Periodic GC for stale sessions (every 6 hours)
|
|
238
|
+
const PRUNE_STALE_INTERVAL = 6 * 60 * 60 * 1000;
|
|
239
|
+
setInterval(async () => {
|
|
240
|
+
try {
|
|
241
|
+
const removed = await sessionStore.pruneStale(7 * 24 * 60 * 60 * 1000);
|
|
242
|
+
if (removed > 0)
|
|
243
|
+
log.info(`Periodic GC: pruned ${removed} stale session(s)`);
|
|
244
|
+
}
|
|
245
|
+
catch (e) {
|
|
246
|
+
log.error(`Periodic GC: pruneStale failed: ${e.message}`);
|
|
247
|
+
}
|
|
248
|
+
}, PRUNE_STALE_INTERVAL);
|
|
228
249
|
startWebhookServer();
|
|
229
250
|
// S13: register hook-bridge event subscribers (bodies extracted to orch/routing/hook-bridge-subscribers.ts)
|
|
230
251
|
registerHookBridgeSubscribers(bus, adapter, planApprovals);
|
package/dist/entry/cli.js
CHANGED
|
@@ -209,6 +209,18 @@ function main() {
|
|
|
209
209
|
}
|
|
210
210
|
const cmd = args[0];
|
|
211
211
|
const rest = args.slice(1);
|
|
212
|
+
// Handle --help / -h for subcommands
|
|
213
|
+
if (rest.includes('--help') || rest.includes('-h')) {
|
|
214
|
+
if (cmd === 'daemon') {
|
|
215
|
+
console.log(getCliHelp());
|
|
216
|
+
process.exit(0);
|
|
217
|
+
}
|
|
218
|
+
if (cmd === 'start') {
|
|
219
|
+
console.log(getCliHelp());
|
|
220
|
+
process.exit(0);
|
|
221
|
+
}
|
|
222
|
+
// Other subcommands (init, task, config, setup-gateway) handle --help internally via runCli()
|
|
223
|
+
}
|
|
212
224
|
// ── Subcommands that replace the process (fork + wait) ──
|
|
213
225
|
if (cmd === 'start') {
|
|
214
226
|
if (!existsSync(APP_JS)) {
|
|
@@ -230,13 +242,16 @@ function main() {
|
|
|
230
242
|
log.error('Run `npm run build` first.');
|
|
231
243
|
process.exit(1);
|
|
232
244
|
}
|
|
233
|
-
|
|
245
|
+
// Detach the daemon so it survives parent shell exit (Bug 1: EPIPE cascade).
|
|
246
|
+
// detached: true → new process group leader; stdio: 'ignore' → no pipe to parent.
|
|
247
|
+
// The daemon's own logger writes to files — console output is redundant.
|
|
248
|
+
fork(DAEMON_JS, [], {
|
|
234
249
|
cwd: DATA_DIR,
|
|
235
|
-
|
|
250
|
+
detached: true,
|
|
251
|
+
stdio: 'ignore',
|
|
236
252
|
env: { ...process.env },
|
|
237
253
|
});
|
|
238
|
-
|
|
239
|
-
return; // let the event loop keep the process alive
|
|
254
|
+
process.exit(0);
|
|
240
255
|
}
|
|
241
256
|
// ── Subcommands that return results ──
|
|
242
257
|
runCli(args).then((result) => {
|
package/dist/entry/daemon.js
CHANGED
|
@@ -502,11 +502,37 @@ function releaseSingletonLock() {
|
|
|
502
502
|
catch { }
|
|
503
503
|
}
|
|
504
504
|
function main() {
|
|
505
|
+
// Recursion guard: if log.error() itself throws (e.g. EPIPE on a broken stderr),
|
|
506
|
+
// the uncaughtException handler would be re-entered, causing an infinite loop that
|
|
507
|
+
// fills the log file and the disk. This flag breaks that cycle.
|
|
508
|
+
let inExceptionHandler = false;
|
|
505
509
|
process.on('uncaughtException', (err) => {
|
|
506
|
-
|
|
510
|
+
if (inExceptionHandler)
|
|
511
|
+
return; // already handling an exception — avoid re-entrant loop
|
|
512
|
+
inExceptionHandler = true;
|
|
513
|
+
try {
|
|
514
|
+
log.error(`uncaughtException: ${err?.stack ?? err}`);
|
|
515
|
+
}
|
|
516
|
+
catch {
|
|
517
|
+
// log.error() itself threw (shouldn't happen after log.ts EPIPE fix, but guard anyway)
|
|
518
|
+
}
|
|
519
|
+
finally {
|
|
520
|
+
inExceptionHandler = false;
|
|
521
|
+
}
|
|
507
522
|
});
|
|
508
523
|
process.on('unhandledRejection', (reason) => {
|
|
509
|
-
|
|
524
|
+
if (inExceptionHandler)
|
|
525
|
+
return;
|
|
526
|
+
inExceptionHandler = true;
|
|
527
|
+
try {
|
|
528
|
+
log.error(`unhandledRejection: ${reason instanceof Error ? reason.stack : String(reason)}`);
|
|
529
|
+
}
|
|
530
|
+
catch {
|
|
531
|
+
// log.error() itself threw
|
|
532
|
+
}
|
|
533
|
+
finally {
|
|
534
|
+
inExceptionHandler = false;
|
|
535
|
+
}
|
|
510
536
|
});
|
|
511
537
|
acquireSingletonLock();
|
|
512
538
|
process.on('exit', releaseSingletonLock);
|
|
@@ -9,12 +9,14 @@ function buildStartupMessage({ machine, restartReason }) {
|
|
|
9
9
|
return restartReason ? `${base} Reason: ${restartReason}.` : base;
|
|
10
10
|
}
|
|
11
11
|
async function sendStartupDmIfConfigured(adapter, { machine, restartReason } = {}) {
|
|
12
|
-
|
|
13
|
-
|
|
12
|
+
try {
|
|
13
|
+
await adapter.postMessage({ type: 'system-notice' }, {
|
|
14
|
+
text: buildStartupMessage({ machine, restartReason }),
|
|
15
|
+
});
|
|
16
|
+
return true;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
14
19
|
return false;
|
|
15
|
-
|
|
16
|
-
text: buildStartupMessage({ machine, restartReason }),
|
|
17
|
-
});
|
|
18
|
-
return true;
|
|
20
|
+
}
|
|
19
21
|
}
|
|
20
22
|
export { buildStartupMessage, sendStartupDmIfConfigured };
|
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
// output: AgentRunner — wraps executeDefaultAgent + launchDefaultAgent lifecycle [S8]
|
|
3
3
|
// pos: orch/ — sole default-agent execution path
|
|
4
4
|
// >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
|
|
5
|
+
import { resolveDestinationConduit } from '../platform/types.js';
|
|
5
6
|
import { channelQueues, enqueue } from './channel-queue.js';
|
|
6
7
|
import { trackPendingTask } from './busy-tracker.js';
|
|
7
8
|
import { getSessionAsync } from '../domain/sessions/session.js';
|
|
8
|
-
import {
|
|
9
|
+
import { sessionStore } from '../store/session-registry-repo.js';
|
|
9
10
|
import { conversationLedger } from '../store/conversation-ledger-repo.js';
|
|
10
11
|
import { getActiveProfile, getDefaultAgent, resolveBackendForChannel } from '../domain/agents/index.js';
|
|
11
12
|
import { handleAgentSuccess, handleAgentError, initTurnTracking } from './lifecycle.js';
|
|
@@ -18,6 +19,7 @@ const log = createLogger('agent-runner');
|
|
|
18
19
|
import { createToolTrace } from '../platform/index.js';
|
|
19
20
|
import { setStreamingCallback, clearStreamingCallback, publishPlanSubmitted, publishAskUserRequested } from './routing/hook-bridge.js';
|
|
20
21
|
import { maybeNotifyCodexLowUsage } from '../domain/costs/codex-usage-monitor.js';
|
|
22
|
+
import { projectDirRepo } from '../store/project-dir-repo.js';
|
|
21
23
|
import { getAgent, createDefaultThread } from '../domain/threads/index.js';
|
|
22
24
|
import { runThread } from '../domain/threads/runner.js';
|
|
23
25
|
import { downloadFiles as downloadPlatformFiles } from './routing/file-handler.js';
|
|
@@ -54,12 +56,13 @@ export class AgentRunner {
|
|
|
54
56
|
const startTime = Date.now();
|
|
55
57
|
const sessionId = await getSessionAsync(channel, resolveBackendForChannel(channel));
|
|
56
58
|
const sessionName = await resolveSessionName(sessionId, channel, userMessage);
|
|
59
|
+
const dest = { type: 'interactive-reply', conduit: channel, sessionId: sessionId ?? '' };
|
|
57
60
|
// 1. Orchestration side effects (keep — ledger, status, hook-bridge)
|
|
58
61
|
const statusText = buildUserProcessingMessage({ startTime, profileName: getActiveProfile(channel), sessionName, sessionId });
|
|
59
62
|
const blocksTemplate = { channel, sessionName, isDm: true };
|
|
60
63
|
// Post status message WITHOUT Cancel button initially — Cancel is added after
|
|
61
64
|
// createDefaultThread gives us a threadId (A3: execution-scoped Cancel).
|
|
62
|
-
const statusMsg = await adapter.postMessage(
|
|
65
|
+
const statusMsg = await adapter.postMessage(dest, {
|
|
63
66
|
text: statusText,
|
|
64
67
|
richBlocks: buildSealedStatusActionBlocks(statusText, blocksTemplate),
|
|
65
68
|
}, threadTs ? { threadId: threadTs } : undefined);
|
|
@@ -82,7 +85,7 @@ export class AgentRunner {
|
|
|
82
85
|
}).catch(() => { });
|
|
83
86
|
initStatusBlocks(statusMsg, blocksTemplateWithThread);
|
|
84
87
|
// 4. Build agent callbacks (streaming, fallback, progress — passed to runThread)
|
|
85
|
-
const callbacks = buildAgentCallbacks(adapter,
|
|
88
|
+
const callbacks = buildAgentCallbacks(adapter, dest, statusMsg, threadTs, startTime, sessionName, sessionId, onMessagePosted);
|
|
86
89
|
// 5. Build PI interactive-event callbacks (plan approval / ask-user-question routing)
|
|
87
90
|
const interactiveCallbacks = buildInteractiveCallbacks(channel, sessionId, thread.id);
|
|
88
91
|
// 6. Call runThread instead of runAgent
|
|
@@ -90,6 +93,7 @@ export class AgentRunner {
|
|
|
90
93
|
try {
|
|
91
94
|
const threadResult = await runThread(thread.id, {
|
|
92
95
|
adapter, channel,
|
|
96
|
+
destination: { type: 'interactive-reply', conduit: channel, sessionId: sessionId ?? '' },
|
|
93
97
|
threadTs: threadTs || statusMsg.messageId,
|
|
94
98
|
statusMsg, startTime,
|
|
95
99
|
existingSessionId: sessionId,
|
|
@@ -105,7 +109,7 @@ export class AgentRunner {
|
|
|
105
109
|
});
|
|
106
110
|
result = threadResult.lastAgentResult;
|
|
107
111
|
clearStreamingCallback(channel);
|
|
108
|
-
await maybeNotifyCodexLowUsage({ adapter,
|
|
112
|
+
await maybeNotifyCodexLowUsage({ adapter, result });
|
|
109
113
|
await handleDefaultAgentResult({
|
|
110
114
|
result, channel, adapter, statusMsg, startTime, userMessage,
|
|
111
115
|
executionId: threadResult.executionId,
|
|
@@ -148,7 +152,7 @@ export function resolveDefaultAgent(agentMessage, channel) {
|
|
|
148
152
|
async function handleDefaultAgentResult({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, sessionName, sessionId, threadTs, messageTs, callbacks }) {
|
|
149
153
|
if (result?.rateLimited) {
|
|
150
154
|
const { elapsedStr } = computeElapsed(startTime);
|
|
151
|
-
const fallbackText = `:warning: ${buildSessionTag(sessionName, sessionId)}Rate limited — all fallbacks exhausted (${elapsedStr}
|
|
155
|
+
const fallbackText = `:warning: ${buildSessionTag(sessionName, sessionId)}Rate limited — all fallbacks exhausted (${elapsedStr})`;
|
|
152
156
|
await sealStatus(adapter, statusMsg, fallbackText, buildSealedStatusActionBlocks(fallbackText, { channel, sessionName, isDm: true }));
|
|
153
157
|
return;
|
|
154
158
|
}
|
|
@@ -157,25 +161,27 @@ async function handleDefaultAgentResult({ result, channel, adapter, statusMsg, s
|
|
|
157
161
|
}
|
|
158
162
|
async function resolveSessionName(sessionId, channel, userMessage) {
|
|
159
163
|
if (sessionId) {
|
|
160
|
-
const existing = await
|
|
164
|
+
const existing = await sessionStore.lookupBySessionId(sessionId);
|
|
161
165
|
if (existing)
|
|
162
166
|
return existing;
|
|
163
|
-
const name = await
|
|
164
|
-
|
|
167
|
+
const name = await sessionStore.generateSessionName();
|
|
168
|
+
const channelProject = await projectDirRepo.getChannelProject(channel);
|
|
169
|
+
await sessionStore.registerSession(name, { sessionId, channel, backend: resolveBackendForChannel(channel), kind: 'local', label: userMessage?.substring(0, 60), profileName: getActiveProfile(channel), projectId: channelProject ?? 'general' });
|
|
165
170
|
return name;
|
|
166
171
|
}
|
|
167
|
-
return
|
|
172
|
+
return sessionStore.generateSessionName();
|
|
168
173
|
}
|
|
169
|
-
function buildAgentCallbacks(adapter,
|
|
174
|
+
function buildAgentCallbacks(adapter, destination, statusMsg, threadTs, startTime, sessionName, sessionId, onMessagePosted) {
|
|
175
|
+
const channel = resolveDestinationConduit(destination);
|
|
170
176
|
const onFallback = makeFallbackNotifier(channel, statusMsg, adapter);
|
|
171
177
|
const queue = getOutboundQueue();
|
|
172
178
|
const durable = queue ? buildDurableHooks(queue) : null;
|
|
173
|
-
const baseAssistantMsg = makeStreamingMessageCallback(adapter,
|
|
179
|
+
const baseAssistantMsg = makeStreamingMessageCallback(adapter, destination, threadTs, onMessagePosted, durable);
|
|
174
180
|
// Tool trace: when CORTEX_SHOW_TOOL_CALLS is enabled, emit a compact per-tool Slack line
|
|
175
181
|
// that merges consecutive same-tool calls and splits on different tool / assistant text.
|
|
176
|
-
const toolTrace = createToolTrace(baseAssistantMsg.
|
|
182
|
+
const toolTrace = createToolTrace(baseAssistantMsg.stream);
|
|
177
183
|
const onAssistantMsg = toolTrace
|
|
178
|
-
? Object.assign((text) => { toolTrace.flush(); baseAssistantMsg(text); }, {
|
|
184
|
+
? Object.assign((text) => { toolTrace.flush(); baseAssistantMsg(text); }, { stream: baseAssistantMsg.stream })
|
|
179
185
|
: baseAssistantMsg;
|
|
180
186
|
const onToolUse = toolTrace ? (name, input) => toolTrace.onToolUse(name, input) : null;
|
|
181
187
|
setStreamingCallback(channel, onAssistantMsg);
|
|
@@ -5,10 +5,11 @@
|
|
|
5
5
|
export { durablePost, durableUpdate } from '../store/outbound-queue.js';
|
|
6
6
|
export function buildDurableHooks(queue) {
|
|
7
7
|
return {
|
|
8
|
-
async beforePost(
|
|
8
|
+
async beforePost(destination, text, opts) {
|
|
9
9
|
const walId = await queue.enqueue({
|
|
10
10
|
type: 'post',
|
|
11
|
-
channel,
|
|
11
|
+
channel: '',
|
|
12
|
+
destination,
|
|
12
13
|
text,
|
|
13
14
|
threadId: opts?.threadId,
|
|
14
15
|
richBlocks: opts?.richBlocks,
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import type { PlatformAdapter } from '../../platform/index.js';
|
|
2
|
-
import type { VirtualMessage } from '../../platform/index.js';
|
|
1
|
+
import type { PlatformAdapter, OutputStream } from '../../platform/index.js';
|
|
3
2
|
import { buildQuestionGroupBlocks, buildQuestionModalDefinition } from '../../platform/index.js';
|
|
4
3
|
declare function formatGroupResponse(group: any): string;
|
|
5
4
|
declare function isExpired(record: any): boolean;
|
|
@@ -28,5 +27,5 @@ declare function registerHookResolver(requestId: any, resolver: any): void;
|
|
|
28
27
|
/** If the group is in hook mode and all answers collected, resolve the hook and return true.
|
|
29
28
|
* For PI backend: if a running execution with an agentProcess exists, send extension_ui_response directly. */
|
|
30
29
|
declare function tryResolveHook(group: any): boolean;
|
|
31
|
-
declare function sendMessages(result: any, channel: any, adapter: PlatformAdapter, messageTs: any, threadTs?: any,
|
|
30
|
+
declare function sendMessages(result: any, channel: any, adapter: PlatformAdapter, messageTs: any, threadTs?: any, stream?: OutputStream | null): Promise<number>;
|
|
32
31
|
export { sendMessages, formatGroupResponse, buildQuestionGroupBlocks, buildQuestionModalDefinition, isExpired, getGroup, deleteGroup, getPendingQuestion, createHookGroup, registerHookResolver, tryResolveHook, };
|
|
@@ -137,7 +137,7 @@ function tryResolveHook(group) {
|
|
|
137
137
|
return true;
|
|
138
138
|
}
|
|
139
139
|
// --- Send questions via adapter ---
|
|
140
|
-
async function sendMessages(result, channel, adapter, messageTs, threadTs = null,
|
|
140
|
+
async function sendMessages(result, channel, adapter, messageTs, threadTs = null, stream = null) {
|
|
141
141
|
let sentCount = 0;
|
|
142
142
|
for (const payload of result.askUserQuestions || []) {
|
|
143
143
|
if (!payload.questions?.length)
|
|
@@ -163,12 +163,13 @@ async function sendMessages(result, channel, adapter, messageTs, threadTs = null
|
|
|
163
163
|
};
|
|
164
164
|
const text = `Questions (${group.questions.length})`;
|
|
165
165
|
const richBlocks = buildQuestionGroupBlocks(group);
|
|
166
|
-
if (
|
|
167
|
-
const ref = await
|
|
166
|
+
if (stream) {
|
|
167
|
+
const ref = await stream.postInteractive(text, { richBlocks });
|
|
168
168
|
group.responseMessageTs = ref?.messageId || null;
|
|
169
169
|
}
|
|
170
170
|
else {
|
|
171
|
-
const
|
|
171
|
+
const askMsgDest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
|
|
172
|
+
const ref = await adapter.postMessage(askMsgDest, { text, richBlocks }, threadTs ? { threadId: threadTs } : undefined);
|
|
172
173
|
group.responseMessageTs = ref.messageId;
|
|
173
174
|
}
|
|
174
175
|
for (const q of group.questions) {
|
|
@@ -12,7 +12,7 @@ import { planApprovals } from './plan-approvals.js';
|
|
|
12
12
|
import { runningExecutions } from '../../core/running-executions.js';
|
|
13
13
|
import { channelQueues } from '../channel-queue.js';
|
|
14
14
|
import { setSessionAsync, deleteSessionAsync } from '../../domain/sessions/session.js';
|
|
15
|
-
import {
|
|
15
|
+
import { sessionStore } from '../../store/session-registry-repo.js';
|
|
16
16
|
import { conversationLedger } from '../../store/conversation-ledger-repo.js';
|
|
17
17
|
import { closeSession, getActiveBackend, getActiveProfile, setActiveProfile, resolveBackendForChannel } from '../../domain/agents/index.js';
|
|
18
18
|
import { fireAndForgetPreCloseHook } from '../../domain/sessions/session-hooks.js';
|
|
@@ -190,11 +190,12 @@ function registerExitPlanModeHandlers(adapter) {
|
|
|
190
190
|
}
|
|
191
191
|
const feedbackText = `:pencil2: Plan feedback sent \u2014 Cortex will revise.\n> ${feedback}`;
|
|
192
192
|
const streamingCb = getStreamingCallback(pending.channel);
|
|
193
|
+
const feedbackDest = { type: 'interactive-reply', conduit: pending.channel, sessionId: '' };
|
|
193
194
|
if (streamingCb) {
|
|
194
195
|
streamingCb(feedbackText);
|
|
195
196
|
}
|
|
196
197
|
else {
|
|
197
|
-
await adapter.postMessage(
|
|
198
|
+
await adapter.postMessage(feedbackDest, { text: feedbackText }).catch(() => { });
|
|
198
199
|
}
|
|
199
200
|
});
|
|
200
201
|
}
|
|
@@ -241,7 +242,7 @@ async function handleStatusResume(ctx) {
|
|
|
241
242
|
if (!_adapter)
|
|
242
243
|
return;
|
|
243
244
|
const sessionName = ctx.value;
|
|
244
|
-
const record = await
|
|
245
|
+
const record = await sessionStore.lookupSession(sessionName);
|
|
245
246
|
if (!record)
|
|
246
247
|
return;
|
|
247
248
|
if (record.profileName)
|
|
@@ -251,7 +252,8 @@ async function handleStatusResume(ctx) {
|
|
|
251
252
|
sessionId: record.sessionId, sessionName, backend: record.backend, profileName: record.profileName,
|
|
252
253
|
});
|
|
253
254
|
const profileNote = record.profileName ? ` (profile: ${record.profileName})` : '';
|
|
254
|
-
|
|
255
|
+
const resumeDest = { type: 'interactive-reply', conduit: ctx.channelId, sessionId: record.sessionId ?? '' };
|
|
256
|
+
await _adapter.postMessage(resumeDest, {
|
|
255
257
|
text: `:arrows_counterclockwise: Session \`${sessionName}\` active — send your message below.${profileNote}`,
|
|
256
258
|
}).catch(() => { });
|
|
257
259
|
}
|
|
@@ -273,7 +275,8 @@ async function handleStatusNew(ctx) {
|
|
|
273
275
|
}
|
|
274
276
|
await deleteSessionAsync(channel, resolveBackendForChannel(channel));
|
|
275
277
|
planApprovals.clearByChannel(channel);
|
|
276
|
-
|
|
278
|
+
const newDest = { type: 'interactive-reply', conduit: ctx.channelId, sessionId: '' };
|
|
279
|
+
await _adapter.postMessage(newDest, {
|
|
277
280
|
text: `--- new conversation --- (profile: ${profileName})`,
|
|
278
281
|
}).catch(() => { });
|
|
279
282
|
}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { postOnce } from '../../platform/index.js';
|
|
2
2
|
async function sendPlanToSlack(planContent, channel, adapter, { machine, threadTs } = {}) {
|
|
3
3
|
if (!planContent) {
|
|
4
4
|
const label = machine ? `**[PLAN: ${machine}]**` : '**[PLAN]**';
|
|
5
|
-
await
|
|
5
|
+
await postOnce(adapter, { type: 'interactive-reply', conduit: channel, sessionId: '' }, `:memo: ${label} Plan generated but no content found.`, { threadId: threadTs });
|
|
6
6
|
return;
|
|
7
7
|
}
|
|
8
8
|
const label = '**[PLAN]**';
|
|
9
9
|
const prompt = 'Generated plan — use the buttons below to approve or provide feedback:';
|
|
10
|
-
await
|
|
10
|
+
await postOnce(adapter, { type: 'interactive-reply', conduit: channel, sessionId: '' }, `:memo: ${label} ${prompt}\n${planContent}`, { threadId: threadTs });
|
|
11
11
|
}
|
|
12
12
|
export { sendPlanToSlack };
|