@cortex-agent/server 2026.6.18-2 → 2026.6.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 (82) hide show
  1. package/defaults/CORTEX.md +5 -0
  2. package/defaults/hooks/ask-user-question-hook.mjs +6 -1
  3. package/defaults/hooks/exit-plan-mode-hook.mjs +6 -1
  4. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +7 -0
  5. package/defaults/prompts/systemPrompts/coder.md +6 -1
  6. package/defaults/prompts/systemPrompts/direct.md +5 -0
  7. package/defaults/prompts/systemPrompts/web-opus-4-6.md +6 -1
  8. package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +6 -1
  9. package/defaults/prompts/systemPrompts/web.md +6 -1
  10. package/defaults/prompts/systemPrompts/worker.md +6 -1
  11. package/dist/agent-adapter/claude/adapter.d.ts +110 -1
  12. package/dist/agent-adapter/claude/adapter.js +117 -0
  13. package/dist/agent-adapter/claude/bg-task-tracker.d.ts +37 -0
  14. package/dist/agent-adapter/claude/bg-task-tracker.js +78 -0
  15. package/dist/agent-adapter/normalize/event-types.d.ts +4 -0
  16. package/dist/agent-adapter/pi/event-parser.d.ts +3 -1
  17. package/dist/agent-adapter/pi/event-parser.js +12 -2
  18. package/dist/agent-adapter/types.d.ts +19 -0
  19. package/dist/core/auth.d.ts +36 -0
  20. package/dist/core/auth.js +85 -0
  21. package/dist/core/locales/en.d.ts +6 -0
  22. package/dist/core/locales/slices/status.d.ts +6 -0
  23. package/dist/core/locales/slices/status.js +16 -0
  24. package/dist/core/types/agent-types.d.ts +5 -0
  25. package/dist/core/types/thread-types.d.ts +12 -1
  26. package/dist/core/version.d.ts +3 -0
  27. package/dist/core/version.js +4 -1
  28. package/dist/domain/agents/facade.js +12 -0
  29. package/dist/domain/costs/rate-limit-throttle.d.ts +1 -1
  30. package/dist/domain/costs/rate-limit-throttle.js +23 -2
  31. package/dist/domain/costs/resume-registry.d.ts +30 -0
  32. package/dist/domain/costs/resume-registry.js +68 -0
  33. package/dist/domain/mcp/core-server.js +5 -0
  34. package/dist/domain/mcp/tools/manager-qa.d.ts +2 -0
  35. package/dist/domain/mcp/tools/manager-qa.js +72 -0
  36. package/dist/domain/mcp/tools/task-ops.js +4 -2
  37. package/dist/domain/mcp/tools/thread-ops.js +2 -1
  38. package/dist/domain/mcp/tui-server.js +2 -1
  39. package/dist/domain/remote/client-bootstrap.js +14 -2
  40. package/dist/domain/remote/client-manager.d.ts +1 -1
  41. package/dist/domain/remote/client-manager.js +31 -5
  42. package/dist/domain/remote/cortex-client-config.d.ts +32 -0
  43. package/dist/domain/remote/cortex-client-config.js +49 -0
  44. package/dist/domain/remote/cortex-client.js +11 -7
  45. package/dist/domain/scheduling/jobs/scheduled-task.js +17 -1
  46. package/dist/domain/scheduling/jobs/task-dispatch.js +21 -0
  47. package/dist/domain/tasks/dispatcher.js +8 -0
  48. package/dist/domain/tasks/system/cortex-run.js +4 -2
  49. package/dist/domain/threads/runner.d.ts +8 -1
  50. package/dist/domain/threads/runner.js +81 -11
  51. package/dist/domain/threads/state-machine.d.ts +5 -0
  52. package/dist/domain/threads/state-machine.js +16 -0
  53. package/dist/entry/app.js +19 -4
  54. package/dist/entry/init.js +6 -0
  55. package/dist/hooks/ask-user-question-hook.mjs +6 -1
  56. package/dist/hooks/exit-plan-mode-hook.mjs +6 -1
  57. package/dist/orchestration/agent-runner.js +28 -3
  58. package/dist/orchestration/bg-continuation.d.ts +26 -0
  59. package/dist/orchestration/bg-continuation.js +34 -0
  60. package/dist/orchestration/conversation-runner.d.ts +3 -0
  61. package/dist/orchestration/conversation-runner.js +1 -1
  62. package/dist/orchestration/interactions/interaction-handlers.js +13 -2
  63. package/dist/orchestration/lifecycle.d.ts +3 -1
  64. package/dist/orchestration/lifecycle.js +72 -2
  65. package/dist/orchestration/manager-qa.d.ts +55 -0
  66. package/dist/orchestration/manager-qa.js +218 -0
  67. package/dist/orchestration/resume-dispatcher.d.ts +22 -0
  68. package/dist/orchestration/resume-dispatcher.js +129 -0
  69. package/dist/orchestration/routing/webhook.d.ts +1 -1
  70. package/dist/orchestration/routing/webhook.js +75 -14
  71. package/dist/orchestration/status-helpers.d.ts +3 -0
  72. package/dist/orchestration/status-helpers.js +16 -0
  73. package/dist/orchestration/thread-callback.d.ts +13 -1
  74. package/dist/orchestration/thread-callback.js +18 -1
  75. package/dist/orchestration/turn-notify.d.ts +26 -0
  76. package/dist/orchestration/turn-notify.js +66 -0
  77. package/dist/store/schedule-repo.d.ts +6 -0
  78. package/dist/store/schedule-repo.js +11 -1
  79. package/dist/store/thread-repo.js +14 -0
  80. package/dist/store/version-migrations.d.ts +14 -4
  81. package/dist/store/version-migrations.js +67 -9
  82. package/package.json +1 -1
package/dist/entry/app.js CHANGED
@@ -38,6 +38,7 @@ import { loadLang } from '../domain/system/preferences.js';
38
38
  // Extracted modules
39
39
  import { cleanupLogs, ensureMcpConfig } from './startup-helpers.js';
40
40
  import { createLogger } from '../core/log.js';
41
+ import { ensureAuthTokens } from '../core/auth.js';
41
42
  import { runningExecutions } from '../core/running-executions.js';
42
43
  import { planApprovals } from '../orchestration/interactions/plan-approvals.js';
43
44
  import { busyTracker } from '../orchestration/busy-tracker.js';
@@ -52,6 +53,8 @@ import { CommandActionRouter } from '../orchestration/interactions/command-actio
52
53
  import { createUpdatePrompt } from '../orchestration/interactions/update-prompt.js';
53
54
  import { registerMessageHandler } from '../orchestration/routing/message-router.js';
54
55
  import { initRateLimitThrottle } from '../domain/costs/rate-limit-throttle.js';
56
+ import { initResumeRegistry } from '../domain/costs/resume-registry.js';
57
+ import { dispatchPendingResumes } from '../orchestration/resume-dispatcher.js';
55
58
  import { scheduleRepo } from '../store/schedule-repo.js';
56
59
  import { runMigrations, migrateAistatusConfigLocation } from '../store/version-migrations.js';
57
60
  import { syncManagedHooks } from '../store/hook-sync.js';
@@ -71,6 +74,10 @@ import { createTuiSessionService } from '../domain/tui-session/index.js';
71
74
  import { enqueue, conduitQueues } from '../orchestration/conduit-queue.js';
72
75
  import { getCostSummary } from '../domain/costs/cost-tracker.js';
73
76
  dotenv.config({ path: path.join(CONFIG_DIR, '.env') });
77
+ // Ensure the WebSocket + webhook bearer tokens exist before either server starts. Generates
78
+ // and persists them to .env on first run (fail-closed auth — see core/auth.ts). Must run after
79
+ // dotenv.config() so pre-existing tokens are honored, and before startClientManager/startWebhookServer.
80
+ ensureAuthTokens();
74
81
  // Apply the persisted mode to env now that .env is loaded. This used to be an import-time
75
82
  // side effect inside domain/agents/config.ts; it is explicit here so that CLI processes
76
83
  // (cortex init / setup-gateway) importing that module don't get their env mutated.
@@ -180,10 +187,18 @@ setInteractiveCallbacksFactory(buildInteractiveCallbacks);
180
187
  const scheduler = createScheduler();
181
188
  scheduler.setAdminNotifier(notifyAdmin);
182
189
  setSchedulerRef(scheduler);
183
- initRateLimitThrottle(adapter, {
184
- save: (state) => scheduleRepo.setRateLimitThrottle(state),
185
- load: () => scheduleRepo.getRateLimitThrottle(),
186
- }).catch(e => log.error(`initRateLimitThrottle failed: ${e.message}`));
190
+ // Resume registry must hydrate BEFORE the throttle: the throttle's restart-recovery path
191
+ // may synchronously fire onResume → dispatchPendingResumes → takeAllResumes. Chain the two
192
+ // inits so the registry is ready before any resume can fire (avoids a load race on restart).
193
+ initResumeRegistry({
194
+ save: (entries) => scheduleRepo.setResumeQueue(entries),
195
+ load: () => scheduleRepo.getResumeQueue(),
196
+ }).catch(e => log.error(`initResumeRegistry failed: ${e.message}`)).finally(() => {
197
+ initRateLimitThrottle(adapter, {
198
+ save: (state) => scheduleRepo.setRateLimitThrottle(state),
199
+ load: () => scheduleRepo.getRateLimitThrottle(),
200
+ }, () => { void dispatchPendingResumes(adapter); }).catch(e => log.error(`initRateLimitThrottle failed: ${e.message}`));
201
+ });
187
202
  initDiskMonitor(adapter);
188
203
  const commandRouter = new CommandActionRouter();
189
204
  const dispatchCommand = registerCommands({
@@ -9,6 +9,7 @@
9
9
  // DATA_DIR is resolved via the --home arg, $CORTEX_HOME env, or ~/.cortex/ default.
10
10
  // Run with: node dist/entry/cli.js init [--home <path>] [--force]
11
11
  import { mkdirSync, writeFileSync, copyFileSync, existsSync, readFileSync, readdirSync } from 'fs';
12
+ import { randomBytes } from 'crypto';
12
13
  import { execSync } from 'child_process';
13
14
  import * as path from 'path';
14
15
  import * as os from 'os';
@@ -87,6 +88,11 @@ export function generateDotEnvContent(answers) {
87
88
  '# Generated by `cortex init`',
88
89
  '',
89
90
  `CORTEX_MACHINE=${answers.machineName}`,
91
+ '',
92
+ '# Auth tokens — WS client (cortex-client ↔ server) + webhook bearer. Required (fail-closed).',
93
+ '# Remote cortex-client machines must share CORTEX_CLIENT_TOKEN. Rotate by editing here + restart.',
94
+ `CORTEX_CLIENT_TOKEN=${randomBytes(32).toString('hex')}`,
95
+ `CORTEX_WEBHOOK_TOKEN=${randomBytes(32).toString('hex')}`,
90
96
  ];
91
97
  // CORTEX_PLATFORM is a comma-separated list (runtime composes adapters via CompositeAdapter).
92
98
  // Each platform's token block is emitted independently when its config is present, so a
@@ -30,7 +30,12 @@ async function main() {
30
30
  port,
31
31
  path: '/hook/ask-user-question',
32
32
  method: 'POST',
33
- headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
33
+ headers: {
34
+ 'Content-Type': 'application/json',
35
+ 'Content-Length': Buffer.byteLength(body),
36
+ // Bearer token for the webhook auth gate (inherited from the session env).
37
+ 'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '',
38
+ },
34
39
  timeout: 60 * 60 * 1000, // 60 minutes — user may take time to respond
35
40
  }, (res) => {
36
41
  let data = '';
@@ -36,7 +36,12 @@ async function main() {
36
36
  port,
37
37
  path: '/hook/exit-plan-mode',
38
38
  method: 'POST',
39
- headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
39
+ headers: {
40
+ 'Content-Type': 'application/json',
41
+ 'Content-Length': Buffer.byteLength(body),
42
+ // Bearer token for the webhook auth gate (inherited from the session env).
43
+ 'x-cortex-token': process.env.CORTEX_WEBHOOK_TOKEN || '',
44
+ },
40
45
  timeout: 60 * 60 * 1000, // 60 minutes — user may take time to respond
41
46
  }, (res) => {
42
47
  let data = '';
@@ -21,8 +21,11 @@ const log = createLogger('agent-runner');
21
21
  import { createToolTrace } from '../platform/index.js';
22
22
  import { setStreamingCallback, clearStreamingCallback, publishPlanSubmitted, publishAskUserRequested } from './routing/hook-bridge.js';
23
23
  import { maybeNotifyCodexLowUsage } from '../domain/costs/codex-usage-monitor.js';
24
+ import { recordResume } from '../domain/costs/resume-registry.js';
24
25
  import { getAgent } from '../domain/threads/index.js';
25
26
  import { runConversation } from './conversation-runner.js';
27
+ import { tryAnswerFromHuman } from './manager-qa.js';
28
+ import { isBgContinuationEnabled, isInteractiveChannel } from './bg-continuation.js';
26
29
  import { downloadFiles as downloadPlatformFiles } from './routing/file-handler.js';
27
30
  import { WORKSPACE_DIR } from '../core/utils.js';
28
31
  const TEMP_DIR = WORKSPACE_DIR;
@@ -38,6 +41,14 @@ export class AgentRunner {
38
41
  }
39
42
  async route(ctx) {
40
43
  const { message, channel, adapter } = ctx;
44
+ // DR-0016 top-level fallback: if this channel has a pending human-escalated subtask question,
45
+ // consume this message as the answer and short-circuit normal turn handling. Scope is narrow —
46
+ // tryAnswerFromHuman returns false unless this exact channel is awaiting a human reply.
47
+ if (tryAnswerFromHuman(channel, ctx.userMessage || '')) {
48
+ const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
49
+ await adapter.postMessage(dest, { text: `${Icons.ok} 已把你的回复作为答复返回给提问的子任务。` }).catch(() => { });
50
+ return;
51
+ }
41
52
  if (conduitQueues.has(channel)) {
42
53
  await adapter.markQueued({ conduit: channel, messageId: message.ref.messageId }).catch(() => { });
43
54
  }
@@ -103,12 +114,23 @@ export class AgentRunner {
103
114
  onPlanWritten: interactiveCallbacks.onPlanWritten,
104
115
  onAskUserQuestion: interactiveCallbacks.onAskUserQuestion,
105
116
  });
106
- clearStreamingCallback(channel);
117
+ // Background-task continuation: if the turn left a run_in_background task running and the
118
+ // feature is enabled for this interactive channel, keep the streaming callback alive so the
119
+ // spontaneous continuation turn merges into the same reply (handleAgentSuccess holds the
120
+ // status and registers a sink). Otherwise clear the callback as usual.
121
+ const pendingBg = convResult.result?.pendingBackgroundTasks ?? 0;
122
+ const proc = convResult.agentProcess;
123
+ const holdForBg = isBgContinuationEnabled() && isInteractiveChannel(channel)
124
+ && pendingBg > 0 && !convResult.result?.rateLimited
125
+ && typeof proc?.setContinuationSink === 'function';
126
+ if (!holdForBg)
127
+ clearStreamingCallback(channel);
107
128
  await maybeNotifyCodexLowUsage({ adapter, result: convResult.result });
108
129
  await handleDefaultAgentResult({
109
130
  result: convResult.result, channel, adapter, statusMsg, startTime, userMessage,
110
131
  executionId: convResult.executionId,
111
132
  sessionName, sessionId, threadAnchorId, messageTs, callbacks,
133
+ registerContinuationSink: holdForBg ? (sink) => proc.setContinuationSink(sink) : null,
112
134
  });
113
135
  }
114
136
  catch (error) {
@@ -144,14 +166,17 @@ export function resolveDefaultAgent(agentMessage, channel) {
144
166
  pluginDirs: defaultAgentDef?.pluginDirs || null,
145
167
  };
146
168
  }
147
- async function handleDefaultAgentResult({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, sessionName, sessionId, threadAnchorId, messageTs, callbacks }) {
169
+ async function handleDefaultAgentResult({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, sessionName, sessionId, threadAnchorId, messageTs, callbacks, registerContinuationSink = null }) {
148
170
  if (result?.rateLimited) {
171
+ // Record the interrupted conversation so it auto-resumes when the rate-limit window
172
+ // resets (rate-limit-throttle onResume → resume-dispatcher).
173
+ recordResume({ kind: 'direct', channel, userMessage, recordedAt: Date.now() });
149
174
  const { elapsedStr } = computeElapsed(startTime);
150
175
  const fallbackText = `${Icons.warning} ${buildSessionTag(sessionName, sessionId)}Rate limited — all fallbacks exhausted (${elapsedStr})`;
151
176
  await sealStatus(adapter, statusMsg, fallbackText, buildSealedStatusActionBlocks(fallbackText, { channel, sessionName, isDm: true }));
152
177
  return;
153
178
  }
154
- await handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger: 'user', sessionName, threadAnchorId, userMessageTs: messageTs, onAssistantMessage: callbacks.onAssistantMsg });
179
+ await handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger: 'user', sessionName, threadAnchorId, userMessageTs: messageTs, onAssistantMessage: callbacks.onAssistantMsg, registerContinuationSink });
155
180
  }
156
181
  export async function resolveSessionName(sessionId, channel, userMessage, adapter) {
157
182
  if (sessionId) {
@@ -0,0 +1,26 @@
1
+ import type { OutputStream } from '../platform/index.js';
2
+ import type { AgentResult } from '../core/types/agent-types.js';
3
+ import type { ContinuationSink } from '../agent-adapter/types.js';
4
+ export interface ContinuationSinkDeps {
5
+ /** The originating turn's OutputStream — continuation text is appended here so the
6
+ * follow-up merges into the same reply (looks like one turn). */
7
+ stream: OutputStream;
8
+ /** Called when the continuation result still has background tasks pending (chained
9
+ * tasks): keep the status in a waiting state with the remaining count. */
10
+ onWaiting: (pendingCount: number) => void;
11
+ /** Called when no background tasks remain: seal the status as complete, record the
12
+ * continuation's cost, and clear the streaming callback + sink. */
13
+ onComplete: (result: AgentResult) => void;
14
+ }
15
+ /**
16
+ * Build the session-level continuation sink. Pure dispatch: assistant text is merged
17
+ * into the originating reply via the shared OutputStream; the terminating result either
18
+ * holds the waiting status (tasks still pending) or completes the turn (none remain).
19
+ * Heavy side effects (seal / cost / clear) are injected via onWaiting / onComplete.
20
+ */
21
+ export declare function buildContinuationSink(deps: ContinuationSinkDeps): ContinuationSink;
22
+ /** Feature gate: background-task continuation is ON by default. Opt out by setting
23
+ * CORTEX_BG_CONTINUATION to a falsy value (0 / false / off / no). */
24
+ export declare function isBgContinuationEnabled(): boolean;
25
+ /** Scope gate: only interactive user conduits (Slack / Feishu), never thread/dispatch. */
26
+ export declare function isInteractiveChannel(channel: string): boolean;
@@ -0,0 +1,34 @@
1
+ // input: ContinuationSink contract (agent-adapter) + OutputStream + AgentResult
2
+ // output: buildContinuationSink + scope/feature gating helpers
3
+ // pos: CC background-task continuation orchestration (merge into reply + waiting status)
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ /**
6
+ * Build the session-level continuation sink. Pure dispatch: assistant text is merged
7
+ * into the originating reply via the shared OutputStream; the terminating result either
8
+ * holds the waiting status (tasks still pending) or completes the turn (none remain).
9
+ * Heavy side effects (seal / cost / clear) are injected via onWaiting / onComplete.
10
+ */
11
+ export function buildContinuationSink(deps) {
12
+ return {
13
+ onAssistantText: (text) => deps.stream.emitText(text),
14
+ onResult: (result) => {
15
+ const pending = result.pendingBackgroundTasks ?? 0;
16
+ if (pending > 0)
17
+ deps.onWaiting(pending);
18
+ else
19
+ deps.onComplete(result);
20
+ },
21
+ };
22
+ }
23
+ /** Feature gate: background-task continuation is ON by default. Opt out by setting
24
+ * CORTEX_BG_CONTINUATION to a falsy value (0 / false / off / no). */
25
+ export function isBgContinuationEnabled() {
26
+ const v = process.env.CORTEX_BG_CONTINUATION;
27
+ if (v === undefined)
28
+ return true;
29
+ return !['0', 'false', 'off', 'no'].includes(v.trim().toLowerCase());
30
+ }
31
+ /** Scope gate: only interactive user conduits (Slack / Feishu), never thread/dispatch. */
32
+ export function isInteractiveChannel(channel) {
33
+ return !!channel && (channel.startsWith('slack:') || channel.startsWith('feishu:'));
34
+ }
@@ -33,6 +33,9 @@ export interface RunConversationOptions {
33
33
  export interface ConversationResult {
34
34
  result: AgentResult;
35
35
  executionId: string;
36
+ /** Underlying agent process for the turn. Used by the background-task continuation path to
37
+ * register a ContinuationSink on the (Claude) session. Opaque to other consumers. */
38
+ agentProcess?: unknown;
36
39
  }
37
40
  /**
38
41
  * Execute a single plain user-conversation turn against the active default agent — no thread,
@@ -105,5 +105,5 @@ export async function runConversation(opts) {
105
105
  else {
106
106
  executionRegistry.teardownExecution({ executionId: execution.id, status: 'completed', durationS, result });
107
107
  }
108
- return { result, executionId: execution.id };
108
+ return { result, executionId: execution.id, agentProcess: handle.agentProcess };
109
109
  }
@@ -229,6 +229,7 @@ function registerStatusActionHandlers(adapter) {
229
229
  adapter.onAction('status_cancel', handleStatusCancel);
230
230
  adapter.onAction('status_resume', handleStatusResume);
231
231
  adapter.onAction('status_new', handleStatusNew);
232
+ adapter.onAction('status_newq', handleStatusNewq);
232
233
  }
233
234
  async function handleStatusCancel(ctx) {
234
235
  if (!_adapter)
@@ -310,15 +311,25 @@ async function handleStatusResume(ctx) {
310
311
  text: `${Icons.refresh} ${t('interaction.sessionActive', { sessionName, profileNote })}`,
311
312
  }).catch(() => { });
312
313
  }
314
+ // "New" button (=!new): close the session and run the pre-close hook.
313
315
  async function handleStatusNew(ctx) {
316
+ await resetChannelFromStatusButton(ctx, { skipHook: false });
317
+ }
318
+ // "New (quiet)" button (=!newq): close the session WITHOUT running the pre-close hook.
319
+ async function handleStatusNewq(ctx) {
320
+ await resetChannelFromStatusButton(ctx, { skipHook: true });
321
+ }
322
+ async function resetChannelFromStatusButton(ctx, opts) {
314
323
  if (!_adapter)
315
324
  return;
316
325
  const channel = ctx.value;
317
326
  // Status message IS the thread parent (no thread_ts on it) — use its messageId
318
327
  // as the thread context so hook messages land in the session's thread.
319
328
  const threadAnchorId = ctx.messageRef?.threadId || ctx.messageRef?.messageId;
320
- // Fire-and-forget: hook starts, session closes immediately without waiting
321
- void fireAndForgetPreCloseHook(channel, _adapter, threadAnchorId);
329
+ // Fire-and-forget: hook starts, session closes immediately without waiting.
330
+ // The quiet variant (!newq) skips the hook entirely.
331
+ if (!opts.skipHook)
332
+ void fireAndForgetPreCloseHook(channel, _adapter, threadAnchorId);
322
333
  closeSession(channel);
323
334
  const conv = await conversationLedger.getConversation(channel);
324
335
  const profileName = getActiveProfile(channel) || 'default';
@@ -1,6 +1,7 @@
1
1
  import type { PlatformAdapter, MessageRef } from '../platform/index.js';
2
2
  import type { AgentResult } from '../core/types/agent-types.js';
3
- export declare function handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger, sessionName, threadAnchorId, userMessageTs, onAssistantMessage }: {
3
+ import type { ContinuationSink } from '../agent-adapter/types.js';
4
+ export declare function handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger, sessionName, threadAnchorId, userMessageTs, onAssistantMessage, registerContinuationSink }: {
4
5
  result: AgentResult;
5
6
  channel: string;
6
7
  adapter: PlatformAdapter;
@@ -13,6 +14,7 @@ export declare function handleAgentSuccess({ result, channel, adapter, statusMsg
13
14
  threadAnchorId?: string | null;
14
15
  userMessageTs?: string | null;
15
16
  onAssistantMessage?: ((text: string) => void) | null;
17
+ registerContinuationSink?: ((sink: ContinuationSink) => void) | null;
16
18
  }): Promise<void>;
17
19
  export declare function handleAgentError({ error, channel, adapter, statusMsg, startTime, executionId, sessionName, sessionId, effectiveSessionId, threadAnchorId, userMessageTs }: {
18
20
  error: {
@@ -1,4 +1,4 @@
1
- // input: orch/busy-tracker(trackPendingTask), orch/channel-queue, orch/superseded-edits, orch/active-agents, orch/interactions/plan-approvals, status-helpers
1
+ // input: orch/busy-tracker(trackPendingTask), orch/channel-queue, orch/superseded-edits, orch/active-agents, orch/interactions/plan-approvals, orch/turn-notify, status-helpers
2
2
  // output: handleAgentSuccess/Error, reprocessMessage
3
3
  // pos: Agent runtime lifecycle handling (success/failure/approval/resume)
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
@@ -20,13 +20,17 @@ import * as askUserQuestion from './interactions/ask-user-question.js';
20
20
  import { runAgent, getClaudeMode, getActiveProfile, resolveBackendForChannel } from '../domain/agents/index.js';
21
21
  import { projectStore } from '../domain/projects/index.js';
22
22
  import { setStreamingCallback, clearStreamingCallback } from './routing/hook-bridge.js';
23
+ import { maybeNotifyTurnComplete } from './turn-notify.js';
24
+ import { buildContinuationSink } from './bg-continuation.js';
25
+ import { recordCost } from '../domain/costs/cost-tracker.js';
23
26
  import { maybeNotifyCodexLowUsage } from '../domain/costs/codex-usage-monitor.js';
27
+ import { recordResume } from '../domain/costs/resume-registry.js';
24
28
  import { normalizeSkillCommandPrefix } from '../domain/memory/skill-scanner.js';
25
29
  import { getOutboundQueue } from '../store/outbound-queue.js';
26
30
  import { buildDurableHooks, durablePost } from './durable-helpers.js';
27
31
  const log = createLogger('lifecycle');
28
32
  // --- Agent success handler ---
29
- export async function handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger = 'user', sessionName = null, threadAnchorId = null, userMessageTs = null, onAssistantMessage = null }) {
33
+ export async function handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger = 'user', sessionName = null, threadAnchorId = null, userMessageTs = null, onAssistantMessage = null, registerContinuationSink = null }) {
30
34
  if (result?.sessionId)
31
35
  await setSessionAsync(channel, result.sessionId, resolveBackendForChannel(channel));
32
36
  await registerOrUpdateSession(result, sessionName, channel, trigger, projectStore.resolveFromMessage(userMessage)?.id ?? 'general');
@@ -37,10 +41,43 @@ export async function handleAgentSuccess({ result, channel, adapter, statusMsg,
37
41
  const sessionTag = buildSessionTag(sessionName, result?.sessionId);
38
42
  const stream = onAssistantMessage?.stream ?? null;
39
43
  const askCount = await askUserQuestion.sendMessages(result, channel, adapter, statusMsg.messageId, threadAnchorId, stream);
44
+ // Background-task continuation: a run_in_background task is still running. Hold the status
45
+ // in a "waiting" state (don't seal) and register a sink so the spontaneous continuation turn
46
+ // the CLI emits on completion merges into this reply and seals the status then. Only when
47
+ // there are no pending user questions and the assistant reply stream is available to merge into.
48
+ const pendingBg = result?.pendingBackgroundTasks ?? 0;
49
+ if (registerContinuationSink && stream && askCount === 0 && pendingBg > 0) {
50
+ const projectId = projectStore.resolveFromMessage(userMessage)?.id ?? 'general';
51
+ const backend = resolveBackendForChannel(channel);
52
+ const waitingText = (pending) => `${Icons.waiting} ${sessionTag}${t('status.backgroundRunning')} (${pending}) (${elapsedStr}${metrics})`;
53
+ await writeStatus(adapter, statusMsg, waitingText(pendingBg));
54
+ let finalized = false;
55
+ const sink = buildContinuationSink({
56
+ stream,
57
+ onWaiting: (pending) => { void writeStatus(adapter, statusMsg, waitingText(pending)); },
58
+ onComplete: (contResult) => {
59
+ if (finalized)
60
+ return;
61
+ finalized = true;
62
+ void finalizeBackgroundContinuation({
63
+ adapter, statusMsg, channel, sessionName, sessionId: result?.sessionId ?? null,
64
+ startTime, baseResult: result, contResult, userMessageTs, executionId, trigger, projectId, backend,
65
+ }).catch((e) => log.error('finalizeBackgroundContinuation failed:', e?.message ?? e));
66
+ },
67
+ });
68
+ registerContinuationSink(sink);
69
+ return; // status held; finalization deferred to the continuation turn
70
+ }
40
71
  const statusText = askCount > 0
41
72
  ? `${Icons.waiting} ${sessionTag}${t('status.waitingForUserInput')} (${elapsedStr}${metrics})`
42
73
  : `${Icons.ok} ${t('status.done')} | ${sessionTag}(${elapsedStr}${metrics})`;
43
74
  await sealStatus(adapter, statusMsg, statusText, buildSealedStatusActionBlocks(statusText, { channel, sessionName, isDm: true }));
75
+ // Push a NEW message when a long-running user turn finishes (the sealed status above is an
76
+ // edit, which does not notify on Slack/Feishu). Only fires when no ask-user questions are
77
+ // pending — those already prompt the user.
78
+ if (askCount === 0) {
79
+ await maybeNotifyTurnComplete({ adapter, channel, threadAnchorId, sessionName, sessionId: result?.sessionId ?? null, elapsedS, elapsedStr, status: 'completed', metricsSuffix: metrics });
80
+ }
44
81
  if (userMessageTs) {
45
82
  await conversationLedger.completeTurn(channel, userMessageTs, { executionId });
46
83
  }
@@ -75,6 +112,36 @@ export async function handleAgentSuccess({ result, channel, adapter, statusMsg,
75
112
  }
76
113
  }
77
114
  }
115
+ /** Finalize a turn that was held in "waiting" state once its background-task continuation
116
+ * completes: seal the status (combined metrics), complete the conversation turn, release the
117
+ * streaming callback, and record the continuation's cost. Idempotency is guarded by the
118
+ * caller (the sink fires onComplete once). */
119
+ async function finalizeBackgroundContinuation({ adapter, statusMsg, channel, sessionName, sessionId, startTime, baseResult, contResult, userMessageTs, executionId, trigger, projectId, backend }) {
120
+ const { elapsedStr } = computeElapsed(startTime);
121
+ const totalCost = (baseResult?.total_cost_usd ?? 0) + (contResult?.total_cost_usd ?? 0);
122
+ const totalTurns = (baseResult?.num_turns ?? 0) + (contResult?.num_turns ?? 0);
123
+ const metrics = formatMetricsSuffix({ costUsd: totalCost, numTurns: totalTurns });
124
+ const sessionTag = buildSessionTag(sessionName, sessionId);
125
+ const statusText = `${Icons.ok} ${t('status.done')} | ${sessionTag}(${elapsedStr}${metrics})`;
126
+ await sealStatus(adapter, statusMsg, statusText, buildSealedStatusActionBlocks(statusText, { channel, sessionName, isDm: true }));
127
+ await maybeNotifyTurnComplete({ adapter, channel, threadAnchorId: null, sessionName, sessionId, elapsedS: computeElapsed(startTime).elapsedS, elapsedStr, status: 'completed', metricsSuffix: metrics });
128
+ if (userMessageTs) {
129
+ await conversationLedger.completeTurn(channel, userMessageTs, { executionId }).catch((e) => log.error('completeTurn failed:', e.message));
130
+ }
131
+ clearStreamingCallback(channel);
132
+ if (contResult?.total_cost_usd != null) {
133
+ await recordCost({
134
+ project: projectId,
135
+ trigger: trigger ? `${trigger}:bg-continuation` : 'bg-continuation',
136
+ cost_usd: contResult.total_cost_usd,
137
+ backend: backend,
138
+ mode: getClaudeMode(),
139
+ source: 'estimate',
140
+ input_tokens: 0,
141
+ output_tokens: 0,
142
+ }).catch((e) => log.warn('recordCost (bg-continuation) failed:', e.message));
143
+ }
144
+ }
78
145
  async function registerOrUpdateSession(result, sessionName, channel, trigger, projectId = 'general') {
79
146
  if (!result?.sessionId || !sessionName)
80
147
  return;
@@ -128,6 +195,7 @@ export async function handleAgentError({ error, channel, adapter, statusMsg, sta
128
195
  finalizeLocalExecution({ executionId, status: 'failed', error, durationS: elapsedS });
129
196
  const errorText = `${Icons.error} ${sessionTag}${t('status.error')} (${elapsedStr})`;
130
197
  await sealStatus(adapter, statusMsg, errorText, buildSealedStatusActionBlocks(errorText, { channel, sessionName, isDm: true }));
198
+ await maybeNotifyTurnComplete({ adapter, channel, threadAnchorId, sessionName, sessionId: resolvedSessionId, elapsedS, elapsedStr, status: 'failed' });
131
199
  const errorDest = { type: 'interactive-reply', conduit: channel, sessionId: resolvedSessionId ?? '' };
132
200
  const queue = getOutboundQueue();
133
201
  if (queue) {
@@ -242,6 +310,8 @@ async function runRetryAgent({ channel, text, adapter, statusMsg, startTime, ses
242
310
  clearStreamingCallback(channel);
243
311
  await maybeNotifyCodexLowUsage({ adapter, result });
244
312
  if (result?.rateLimited) {
313
+ // Record the interrupted edit-retry conversation for auto-resume when the window resets.
314
+ recordResume({ kind: 'direct', channel, userMessage: text, recordedAt: Date.now() });
245
315
  const { elapsedStr } = computeElapsed(startTime);
246
316
  const rateLimitText = `${Icons.warning} ${buildSessionTag(sessionName, sessionId)}${t('status.rateLimitedExhausted')} (${elapsedStr})`;
247
317
  await sealStatus(adapter, statusMsg, rateLimitText, buildSealedStatusActionBlocks(rateLimitText, { channel, sessionName, isDm: true }));
@@ -0,0 +1,55 @@
1
+ /** Test hook: clear all in-memory Q&A state. */
2
+ export declare function _testResetManagerQa(): void;
3
+ /** Minimal task shape the resolver needs (kept tiny so callers/tests can inject a reader). */
4
+ interface TaskLite {
5
+ parent: string | null;
6
+ origin_channel: string | null;
7
+ }
8
+ export interface ManagerQaDeps {
9
+ /** Disk-fresh task lookup (defaults to scanAllTasks). Injected in tests to avoid disk. */
10
+ readTask?: (project: string | null, taskId: string) => TaskLite | null;
11
+ /** Resume a waiting manager so it can answer (defaults to resumeManagerForQuestion). */
12
+ resume?: (managerThreadId: string) => void;
13
+ /** Post the question to a human-escalation channel (defaults to the platform adapter). */
14
+ postToChannel?: (channel: string, text: string) => void | Promise<void>;
15
+ }
16
+ /** Notice injected into the manager's pendingMessages (and, lightly adapted, posted to a human).
17
+ * Mirrors buildChildResultNotice's shape: states what is asked and how to respond. */
18
+ export declare function buildQuestionNotice(q: {
19
+ questionId: string;
20
+ fromTaskId: string | null;
21
+ question: string;
22
+ }): string;
23
+ export type AskResult = {
24
+ ok: true;
25
+ questionId: string;
26
+ target: 'manager';
27
+ managerThreadId: string;
28
+ } | {
29
+ ok: true;
30
+ questionId: string;
31
+ target: 'human';
32
+ channel: string;
33
+ } | {
34
+ ok: false;
35
+ error: string;
36
+ };
37
+ /** Register a subtask's question and route it: to its manager (woken to answer), or — at the top of
38
+ * the tree — to a human via the origin channel. Returns a questionId the caller polls via getAnswer. */
39
+ export declare function askManager(threadId: string, question: string, deps?: ManagerQaDeps): Promise<AskResult>;
40
+ /** Manager answers a subtask question. Records the answer and forces the manager back to waiting
41
+ * (pendingControl='wait') so it re-suspends on its still-live children at the next step boundary. */
42
+ export declare function submitAnswer(questionId: string, answer: string): Promise<{
43
+ ok: boolean;
44
+ error?: string;
45
+ }>;
46
+ /** Poll for an answer. Consumes the entry once an answer is present (one-shot read by the poller). */
47
+ export declare function getAnswer(questionId: string): {
48
+ found: boolean;
49
+ answered: boolean;
50
+ answer: string | null;
51
+ };
52
+ /** Interactive hook: if `channel` has a pending human-escalated question, consume this message as
53
+ * its answer and return true (the caller should then short-circuit normal turn handling). */
54
+ export declare function tryAnswerFromHuman(channel: string, text: string): boolean;
55
+ export {};