@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.
Files changed (132) hide show
  1. package/README.md +5 -1
  2. package/defaults/config/thread-templates.json +65 -39
  3. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +4 -4
  4. package/defaults/prompts/directives/coder-reviewer.md +9 -4
  5. package/defaults/prompts/directives/coder.md +10 -2
  6. package/dist/core/log.js +61 -12
  7. package/dist/core/status-format.js +1 -1
  8. package/dist/core/task-parser.d.ts +1 -1
  9. package/dist/core/task-parser.js +13 -6
  10. package/dist/core/types/thread-types.d.ts +4 -2
  11. package/dist/domain/costs/codex-usage-monitor.d.ts +1 -2
  12. package/dist/domain/costs/codex-usage-monitor.js +2 -2
  13. package/dist/domain/costs/cost-tracker.d.ts +2 -0
  14. package/dist/domain/costs/cost-tracker.js +4 -20
  15. package/dist/domain/costs/rate-limit-throttle.js +1 -4
  16. package/dist/domain/mcp/tools/context.d.ts +4 -2
  17. package/dist/domain/mcp/tools/context.js +7 -5
  18. package/dist/domain/mcp/tools/schedule.d.ts +1 -1
  19. package/dist/domain/mcp/tools/schedule.js +24 -20
  20. package/dist/domain/memory/index-regen.js +8 -5
  21. package/dist/domain/monitor/disk-monitor.js +1 -6
  22. package/dist/domain/projects/index.d.ts +2 -0
  23. package/dist/domain/projects/index.js +3 -0
  24. package/dist/domain/projects/project-store.d.ts +54 -0
  25. package/dist/domain/projects/project-store.js +194 -0
  26. package/dist/domain/projects/project-types.d.ts +11 -0
  27. package/dist/domain/projects/project-types.js +5 -0
  28. package/dist/domain/remote/client-hot-reload.d.ts +1 -0
  29. package/dist/domain/remote/client-hot-reload.js +284 -53
  30. package/dist/domain/scheduling/jobs/_shared.d.ts +1 -1
  31. package/dist/domain/scheduling/jobs/_shared.js +6 -5
  32. package/dist/domain/scheduling/jobs/memory-index-regen.js +2 -2
  33. package/dist/domain/scheduling/jobs/scheduled-task.d.ts +2 -2
  34. package/dist/domain/scheduling/jobs/scheduled-task.js +38 -36
  35. package/dist/domain/scheduling/jobs/sync-public.d.ts +1 -0
  36. package/dist/domain/scheduling/jobs/sync-public.js +34 -0
  37. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +3 -7
  38. package/dist/domain/scheduling/jobs/target-dispatch.js +7 -9
  39. package/dist/domain/scheduling/jobs/task-archive.js +2 -2
  40. package/dist/domain/scheduling/jobs/task-dispatch.js +18 -16
  41. package/dist/domain/scheduling/runner.d.ts +1 -0
  42. package/dist/domain/scheduling/runner.js +2 -0
  43. package/dist/domain/scheduling/schedule-cli.d.ts +1 -0
  44. package/dist/domain/scheduling/schedule-cli.js +14 -14
  45. package/dist/domain/scheduling/schedule-command.js +45 -36
  46. package/dist/domain/scheduling/scheduler.d.ts +1 -1
  47. package/dist/domain/scheduling/scheduler.js +12 -11
  48. package/dist/domain/sessions/session-hooks.d.ts +10 -11
  49. package/dist/domain/sessions/session-hooks.js +26 -27
  50. package/dist/domain/sessions/session-registry.d.ts +10 -5
  51. package/dist/domain/sessions/session-registry.js +24 -9
  52. package/dist/domain/tasks/pending-tracker.js +8 -9
  53. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  54. package/dist/domain/tasks/system/task-cli.js +189 -29
  55. package/dist/domain/tasks/system/task-lifecycle-edit.js +3 -3
  56. package/dist/domain/threads/hook-runner.js +12 -7
  57. package/dist/domain/threads/runner.d.ts +3 -3
  58. package/dist/domain/threads/runner.js +30 -28
  59. package/dist/domain/threads/state-machine.d.ts +3 -0
  60. package/dist/domain/threads/state-machine.js +4 -0
  61. package/dist/entry/app.js +30 -9
  62. package/dist/entry/cli.js +19 -4
  63. package/dist/entry/daemon.js +28 -2
  64. package/dist/entry/startup-notify.js +8 -6
  65. package/dist/orchestration/agent-runner.js +19 -13
  66. package/dist/orchestration/durable-helpers.js +3 -2
  67. package/dist/orchestration/interactions/ask-user-question.d.ts +2 -3
  68. package/dist/orchestration/interactions/ask-user-question.js +5 -4
  69. package/dist/orchestration/interactions/interaction-handlers.js +8 -5
  70. package/dist/orchestration/interactions/plan-handler.js +3 -3
  71. package/dist/orchestration/lifecycle.js +43 -38
  72. package/dist/orchestration/routing/commands/cancel.js +9 -8
  73. package/dist/orchestration/routing/commands/channel.js +32 -26
  74. package/dist/orchestration/routing/commands/cost.js +5 -3
  75. package/dist/orchestration/routing/commands/device.js +2 -1
  76. package/dist/orchestration/routing/commands/dispatch.js +8 -7
  77. package/dist/orchestration/routing/commands/index.js +7 -4
  78. package/dist/orchestration/routing/commands/mode.js +24 -18
  79. package/dist/orchestration/routing/commands/nvtop.js +14 -12
  80. package/dist/orchestration/routing/commands/orient.js +2 -1
  81. package/dist/orchestration/routing/commands/schedule.js +2 -1
  82. package/dist/orchestration/routing/commands/sendfile.js +12 -9
  83. package/dist/orchestration/routing/commands/session.js +12 -10
  84. package/dist/orchestration/routing/commands/status.js +2 -2
  85. package/dist/orchestration/routing/commands/tail.js +10 -6
  86. package/dist/orchestration/routing/commands/task.js +5 -4
  87. package/dist/orchestration/routing/commands/thread-handlers.js +19 -12
  88. package/dist/orchestration/routing/hook-bridge-subscribers.js +15 -13
  89. package/dist/orchestration/status-helpers.d.ts +4 -5
  90. package/dist/orchestration/status-helpers.js +7 -8
  91. package/dist/orchestration/thread-executor.js +21 -12
  92. package/dist/platform/adapter.d.ts +13 -9
  93. package/dist/platform/adapter.js +1 -1
  94. package/dist/platform/adapters/feishu-output-stream.d.ts +27 -0
  95. package/dist/platform/adapters/feishu-output-stream.js +114 -0
  96. package/dist/platform/adapters/feishu.d.ts +16 -7
  97. package/dist/platform/adapters/feishu.js +64 -18
  98. package/dist/platform/adapters/index.d.ts +4 -1
  99. package/dist/platform/adapters/index.js +1 -1
  100. package/dist/platform/adapters/slack-output-stream.d.ts +55 -0
  101. package/dist/platform/{virtual-message.js → adapters/slack-output-stream.js} +98 -165
  102. package/dist/platform/adapters/slack-project-conduits.d.ts +9 -0
  103. package/dist/platform/adapters/slack-project-conduits.js +40 -0
  104. package/dist/platform/adapters/slack.d.ts +18 -8
  105. package/dist/platform/adapters/slack.js +82 -24
  106. package/dist/platform/index.d.ts +3 -2
  107. package/dist/platform/index.js +1 -1
  108. package/dist/platform/output-stream-chunk.d.ts +6 -0
  109. package/dist/platform/output-stream-chunk.js +45 -0
  110. package/dist/platform/output-stream-helpers.d.ts +6 -0
  111. package/dist/platform/output-stream-helpers.js +11 -0
  112. package/dist/platform/output-stream.d.ts +28 -0
  113. package/dist/platform/output-stream.js +4 -0
  114. package/dist/platform/testing.d.ts +41 -8
  115. package/dist/platform/testing.js +93 -11
  116. package/dist/platform/tool-trace.d.ts +9 -8
  117. package/dist/platform/tool-trace.js +19 -17
  118. package/dist/platform/types.d.ts +21 -1
  119. package/dist/platform/types.js +17 -1
  120. package/dist/store/channel-repo.d.ts +6 -0
  121. package/dist/store/channel-repo.js +9 -0
  122. package/dist/store/json-repository.js +12 -1
  123. package/dist/store/outbound-queue.d.ts +5 -4
  124. package/dist/store/outbound-queue.js +9 -6
  125. package/dist/store/schedule-repo.d.ts +9 -5
  126. package/dist/store/schedule-repo.js +59 -14
  127. package/dist/store/session-registry-repo.d.ts +36 -7
  128. package/dist/store/session-registry-repo.js +186 -25
  129. package/dist/store/thread-repo.d.ts +1 -0
  130. package/dist/store/thread-repo.js +8 -0
  131. package/package.json +1 -1
  132. 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 { sessionRegistryRepo } from '../store/session-registry-repo.js';
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
- const ch = adapter.getAdminChannel();
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(), sessionRegistryRepo.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
- const adminChannel = adapter.getAdminChannel();
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
- const child = fork(DAEMON_JS, [], {
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
- stdio: 'inherit',
250
+ detached: true,
251
+ stdio: 'ignore',
236
252
  env: { ...process.env },
237
253
  });
238
- child.on('exit', (code) => process.exit(code ?? 0));
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) => {
@@ -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
- log.error(`uncaughtException: ${err?.stack ?? err}`);
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
- log.error(`unhandledRejection: ${reason instanceof Error ? reason.stack : String(reason)}`);
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
- const adminChannel = adapter.getAdminChannel();
13
- if (!adminChannel)
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
- await adapter.postMessage(adminChannel, {
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 { sessionRegistryRepo } from '../store/session-registry-repo.js';
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(channel, {
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, channel, statusMsg, threadTs, startTime, sessionName, sessionId, onMessagePosted);
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, channel, result });
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}s)`;
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 sessionRegistryRepo.lookupBySessionId(sessionId);
164
+ const existing = await sessionStore.lookupBySessionId(sessionId);
161
165
  if (existing)
162
166
  return existing;
163
- const name = await sessionRegistryRepo.generateSessionName();
164
- await sessionRegistryRepo.registerSession(name, { sessionId, channel, backend: resolveBackendForChannel(channel), kind: 'local', label: userMessage?.substring(0, 60), profileName: getActiveProfile(channel) });
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 sessionRegistryRepo.generateSessionName();
172
+ return sessionStore.generateSessionName();
168
173
  }
169
- function buildAgentCallbacks(adapter, channel, statusMsg, threadTs, startTime, sessionName, sessionId, onMessagePosted) {
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, channel, threadTs, onMessagePosted, durable);
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.vm);
182
+ const toolTrace = createToolTrace(baseAssistantMsg.stream);
177
183
  const onAssistantMsg = toolTrace
178
- ? Object.assign((text) => { toolTrace.flush(); baseAssistantMsg(text); }, { vm: baseAssistantMsg.vm })
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(channel, text, opts) {
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, vm?: VirtualMessage | null): Promise<number>;
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, vm = 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 (vm) {
167
- const ref = await vm.postStandalone(text, { richBlocks });
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 ref = await adapter.postMessage(channel, { text, richBlocks }, threadTs ? { threadId: threadTs } : undefined);
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 { sessionRegistryRepo } from '../../store/session-registry-repo.js';
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(pending.channel, { text: feedbackText }).catch(() => { });
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 sessionRegistryRepo.lookupSession(sessionName);
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
- await _adapter.postMessage(ctx.channelId, {
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
- await _adapter.postMessage(ctx.channelId, {
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 { VirtualMessage } from '../../platform/index.js';
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 VirtualMessage.postOnce(adapter, channel, `:memo: ${label} Plan generated but no content found.`, { threadId: threadTs });
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 VirtualMessage.postOnce(adapter, channel, `:memo: ${label} ${prompt}\n${planContent}`, { threadId: threadTs });
10
+ await postOnce(adapter, { type: 'interactive-reply', conduit: channel, sessionId: '' }, `:memo: ${label} ${prompt}\n${planContent}`, { threadId: threadTs });
11
11
  }
12
12
  export { sendPlanToSlack };