@cortex-agent/server 2026.6.18 → 2026.6.24

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 (153) hide show
  1. package/defaults/CORTEX.md +5 -0
  2. package/defaults/config/thread-templates.json +12 -6
  3. package/defaults/context/user/CORTEX.md +2 -2
  4. package/defaults/hooks/ask-user-question-hook.mjs +7 -1
  5. package/defaults/hooks/exit-plan-mode-hook.mjs +7 -1
  6. package/defaults/hooks/memory-ref-tracker.mjs +1 -0
  7. package/defaults/hooks/new-session-hook.mjs +1 -0
  8. package/defaults/hooks/post-task-hook.mjs +1 -0
  9. package/defaults/hooks/rules-loader.mjs +1 -0
  10. package/defaults/hooks/sensitive-file-edit.mjs +1 -0
  11. package/defaults/hooks/session-activity-tracker.mjs +1 -0
  12. package/defaults/hooks/task-status-check.mjs +1 -0
  13. package/defaults/hooks/tasks-yaml-guard.mjs +1 -0
  14. package/defaults/plugins/cortex-feishu/.claude-plugin/plugin.json +5 -0
  15. package/defaults/plugins/cortex-feishu/skills/feishu-doc/SKILL.md +163 -0
  16. package/defaults/plugins/cortex-feishu/skills/feishu-doc/scripts/ensure-lark-cli.sh +53 -0
  17. package/defaults/plugins/cortex-system/skills/client-manage/SKILL.md +7 -0
  18. package/defaults/prompts/directives/coder-reviewer.md +6 -6
  19. package/defaults/prompts/directives/coder.md +14 -15
  20. package/defaults/prompts/systemPrompts/coder.md +6 -1
  21. package/defaults/prompts/systemPrompts/direct.md +5 -0
  22. package/defaults/prompts/systemPrompts/web-opus-4-6.md +6 -1
  23. package/defaults/prompts/systemPrompts/web-sonnet-4-6.md +6 -1
  24. package/defaults/prompts/systemPrompts/web.md +6 -1
  25. package/defaults/prompts/systemPrompts/worker.md +6 -1
  26. package/dist/agent-adapter/claude/adapter-tui.d.ts +12 -0
  27. package/dist/agent-adapter/claude/adapter-tui.js +15 -0
  28. package/dist/agent-adapter/claude/adapter.d.ts +110 -1
  29. package/dist/agent-adapter/claude/adapter.js +123 -2
  30. package/dist/agent-adapter/claude/bg-task-tracker.d.ts +45 -0
  31. package/dist/agent-adapter/claude/bg-task-tracker.js +91 -0
  32. package/dist/agent-adapter/normalize/event-types.d.ts +4 -0
  33. package/dist/agent-adapter/pi/event-parser.d.ts +3 -1
  34. package/dist/agent-adapter/pi/event-parser.js +12 -2
  35. package/dist/agent-adapter/types.d.ts +19 -0
  36. package/dist/core/auth.d.ts +36 -0
  37. package/dist/core/auth.js +85 -0
  38. package/dist/core/gateway-generator.js +10 -1
  39. package/dist/core/locales/en.d.ts +12 -0
  40. package/dist/core/locales/slices/interactions.d.ts +6 -0
  41. package/dist/core/locales/slices/interactions.js +14 -0
  42. package/dist/core/locales/slices/status.d.ts +6 -0
  43. package/dist/core/locales/slices/status.js +16 -0
  44. package/dist/core/status-format.d.ts +14 -0
  45. package/dist/core/status-format.js +23 -1
  46. package/dist/core/types/agent-types.d.ts +5 -0
  47. package/dist/core/types/thread-types.d.ts +15 -1
  48. package/dist/core/version.d.ts +3 -0
  49. package/dist/core/version.js +4 -1
  50. package/dist/domain/agents/facade.d.ts +13 -0
  51. package/dist/domain/agents/facade.js +36 -1
  52. package/dist/domain/costs/rate-limit-throttle.d.ts +1 -1
  53. package/dist/domain/costs/rate-limit-throttle.js +23 -2
  54. package/dist/domain/costs/resume-registry.d.ts +30 -0
  55. package/dist/domain/costs/resume-registry.js +68 -0
  56. package/dist/domain/mcp/core-server.js +5 -0
  57. package/dist/domain/mcp/feishu/index.js +5 -51
  58. package/dist/domain/mcp/feishu-server.js +3 -2
  59. package/dist/domain/mcp/tools/manager-qa.d.ts +2 -0
  60. package/dist/domain/mcp/tools/manager-qa.js +72 -0
  61. package/dist/domain/mcp/tools/task-ops.js +4 -2
  62. package/dist/domain/mcp/tools/thread-ops.js +2 -1
  63. package/dist/domain/mcp/tui-server.js +2 -1
  64. package/dist/domain/memory/user-context.d.ts +6 -5
  65. package/dist/domain/memory/user-context.js +12 -7
  66. package/dist/domain/remote/client-bootstrap.js +14 -2
  67. package/dist/domain/remote/client-hot-reload.d.ts +9 -2
  68. package/dist/domain/remote/client-hot-reload.js +77 -6
  69. package/dist/domain/remote/client-manager.d.ts +1 -1
  70. package/dist/domain/remote/client-manager.js +31 -5
  71. package/dist/domain/remote/cortex-client-config.d.ts +32 -0
  72. package/dist/domain/remote/cortex-client-config.js +49 -0
  73. package/dist/domain/remote/cortex-client.js +11 -7
  74. package/dist/domain/scheduling/jobs/scheduled-task.js +17 -1
  75. package/dist/domain/scheduling/jobs/task-dispatch.js +22 -0
  76. package/dist/domain/sessions/session-hooks.d.ts +31 -1
  77. package/dist/domain/sessions/session-hooks.js +69 -17
  78. package/dist/domain/system/doctor.d.ts +63 -0
  79. package/dist/domain/system/doctor.js +362 -0
  80. package/dist/domain/tasks/dispatcher.js +8 -0
  81. package/dist/domain/tasks/system/cortex-run.js +4 -2
  82. package/dist/domain/tasks/system/task-cli.js +7 -4
  83. package/dist/domain/tasks/system/task-state.d.ts +10 -1
  84. package/dist/domain/tasks/system/task-state.js +31 -1
  85. package/dist/domain/threads/prompt-builder.d.ts +7 -4
  86. package/dist/domain/threads/prompt-builder.js +9 -8
  87. package/dist/domain/threads/runner.d.ts +8 -1
  88. package/dist/domain/threads/runner.js +111 -18
  89. package/dist/domain/threads/state-machine.d.ts +5 -0
  90. package/dist/domain/threads/state-machine.js +16 -0
  91. package/dist/entry/app.js +44 -5
  92. package/dist/entry/cli.js +10 -0
  93. package/dist/entry/doctor-cli.d.ts +12 -0
  94. package/dist/entry/doctor-cli.js +76 -0
  95. package/dist/entry/init.js +6 -0
  96. package/dist/hooks/ask-user-question-hook.mjs +7 -1
  97. package/dist/hooks/exit-plan-mode-hook.mjs +7 -1
  98. package/dist/hooks/memory-ref-tracker.mjs +1 -0
  99. package/dist/hooks/new-session-hook.mjs +1 -0
  100. package/dist/hooks/post-task-hook.mjs +1 -0
  101. package/dist/hooks/rules-loader.mjs +1 -0
  102. package/dist/hooks/sensitive-file-edit.mjs +1 -0
  103. package/dist/hooks/session-activity-tracker.mjs +1 -0
  104. package/dist/hooks/task-status-check.mjs +1 -0
  105. package/dist/hooks/tasks-yaml-guard.mjs +1 -0
  106. package/dist/orchestration/agent-runner.js +30 -4
  107. package/dist/orchestration/bg-continuation.d.ts +26 -0
  108. package/dist/orchestration/bg-continuation.js +34 -0
  109. package/dist/orchestration/conversation-runner.d.ts +3 -0
  110. package/dist/orchestration/conversation-runner.js +5 -2
  111. package/dist/orchestration/interactions/interaction-handlers.js +13 -2
  112. package/dist/orchestration/lifecycle.d.ts +5 -2
  113. package/dist/orchestration/lifecycle.js +87 -3
  114. package/dist/orchestration/manager-qa.d.ts +56 -0
  115. package/dist/orchestration/manager-qa.js +223 -0
  116. package/dist/orchestration/resume-dispatcher.d.ts +27 -0
  117. package/dist/orchestration/resume-dispatcher.js +145 -0
  118. package/dist/orchestration/routing/webhook.d.ts +1 -1
  119. package/dist/orchestration/routing/webhook.js +75 -14
  120. package/dist/orchestration/status-helpers.d.ts +3 -0
  121. package/dist/orchestration/status-helpers.js +16 -0
  122. package/dist/orchestration/thread-callback.d.ts +17 -1
  123. package/dist/orchestration/thread-callback.js +57 -36
  124. package/dist/orchestration/turn-notify.d.ts +26 -0
  125. package/dist/orchestration/turn-notify.js +66 -0
  126. package/dist/platform/adapters/feishu.d.ts +16 -0
  127. package/dist/platform/adapters/feishu.js +67 -6
  128. package/dist/store/plugin-sync.d.ts +21 -0
  129. package/dist/store/plugin-sync.js +119 -0
  130. package/dist/store/schedule-repo.d.ts +6 -0
  131. package/dist/store/schedule-repo.js +11 -1
  132. package/dist/store/thread-repo.js +14 -0
  133. package/dist/store/version-migrations.d.ts +23 -4
  134. package/dist/store/version-migrations.js +167 -9
  135. package/dist/tui/App.js +11 -7
  136. package/dist/tui/components/Dashboard.js +26 -11
  137. package/dist/tui/components/InputBox.js +43 -4
  138. package/dist/tui/components/SidePanel.js +1 -1
  139. package/package.json +1 -1
  140. package/dist/domain/mcp/feishu/bitable.d.ts +0 -3
  141. package/dist/domain/mcp/feishu/bitable.js +0 -168
  142. package/dist/domain/mcp/feishu/blocks-to-text.d.ts +0 -19
  143. package/dist/domain/mcp/feishu/blocks-to-text.js +0 -43
  144. package/dist/domain/mcp/feishu/docx.d.ts +0 -3
  145. package/dist/domain/mcp/feishu/docx.js +0 -163
  146. package/dist/domain/mcp/feishu/drive.d.ts +0 -23
  147. package/dist/domain/mcp/feishu/drive.js +0 -66
  148. package/dist/domain/mcp/feishu/markdown-to-blocks.d.ts +0 -40
  149. package/dist/domain/mcp/feishu/markdown-to-blocks.js +0 -191
  150. package/dist/domain/mcp/feishu/sheets.d.ts +0 -3
  151. package/dist/domain/mcp/feishu/sheets.js +0 -119
  152. package/dist/domain/mcp/feishu/wiki.d.ts +0 -3
  153. package/dist/domain/mcp/feishu/wiki.js +0 -77
@@ -15,14 +15,18 @@ import { buildSessionTag, buildUserProcessingMessage, makeFallbackNotifier, make
15
15
  import { readFileSync } from 'fs';
16
16
  import { createLogger } from '../core/log.js';
17
17
  import { Icons } from '../core/icons.js';
18
+ import { t } from '../core/i18n.js';
18
19
  import { getOutboundQueue } from '../store/outbound-queue.js';
19
20
  import { buildDurableHooks } from './durable-helpers.js';
20
21
  const log = createLogger('agent-runner');
21
22
  import { createToolTrace } from '../platform/index.js';
22
23
  import { setStreamingCallback, clearStreamingCallback, publishPlanSubmitted, publishAskUserRequested } from './routing/hook-bridge.js';
23
24
  import { maybeNotifyCodexLowUsage } from '../domain/costs/codex-usage-monitor.js';
25
+ import { recordResume } from '../domain/costs/resume-registry.js';
24
26
  import { getAgent } from '../domain/threads/index.js';
25
27
  import { runConversation } from './conversation-runner.js';
28
+ import { tryAnswerFromHuman } from './manager-qa.js';
29
+ import { isBgContinuationEnabled, isInteractiveChannel } from './bg-continuation.js';
26
30
  import { downloadFiles as downloadPlatformFiles } from './routing/file-handler.js';
27
31
  import { WORKSPACE_DIR } from '../core/utils.js';
28
32
  const TEMP_DIR = WORKSPACE_DIR;
@@ -38,6 +42,14 @@ export class AgentRunner {
38
42
  }
39
43
  async route(ctx) {
40
44
  const { message, channel, adapter } = ctx;
45
+ // DR-0016 top-level fallback: if this channel has a pending human-escalated subtask question,
46
+ // consume this message as the answer and short-circuit normal turn handling. Scope is narrow —
47
+ // tryAnswerFromHuman returns false unless this exact channel is awaiting a human reply.
48
+ if (tryAnswerFromHuman(channel, ctx.userMessage || '')) {
49
+ const dest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
50
+ await adapter.postMessage(dest, { text: `${Icons.ok} ${t('subtask.replyDelivered')}` }).catch(() => { });
51
+ return;
52
+ }
41
53
  if (conduitQueues.has(channel)) {
42
54
  await adapter.markQueued({ conduit: channel, messageId: message.ref.messageId }).catch(() => { });
43
55
  }
@@ -103,12 +115,23 @@ export class AgentRunner {
103
115
  onPlanWritten: interactiveCallbacks.onPlanWritten,
104
116
  onAskUserQuestion: interactiveCallbacks.onAskUserQuestion,
105
117
  });
106
- clearStreamingCallback(channel);
118
+ // Background-task continuation: if the turn left a run_in_background task running and the
119
+ // feature is enabled for this interactive channel, keep the streaming callback alive so the
120
+ // spontaneous continuation turn merges into the same reply (handleAgentSuccess holds the
121
+ // status and registers a sink). Otherwise clear the callback as usual.
122
+ const pendingBg = convResult.result?.pendingBackgroundTasks ?? 0;
123
+ const proc = convResult.agentProcess;
124
+ const holdForBg = isBgContinuationEnabled() && isInteractiveChannel(channel)
125
+ && pendingBg > 0 && !convResult.result?.rateLimited
126
+ && typeof proc?.setContinuationSink === 'function';
127
+ if (!holdForBg)
128
+ clearStreamingCallback(channel);
107
129
  await maybeNotifyCodexLowUsage({ adapter, result: convResult.result });
108
130
  await handleDefaultAgentResult({
109
131
  result: convResult.result, channel, adapter, statusMsg, startTime, userMessage,
110
132
  executionId: convResult.executionId,
111
133
  sessionName, sessionId, threadAnchorId, messageTs, callbacks,
134
+ registerContinuationSink: holdForBg ? (sink) => proc.setContinuationSink(sink) : null,
112
135
  });
113
136
  }
114
137
  catch (error) {
@@ -117,7 +140,7 @@ export class AgentRunner {
117
140
  error: error,
118
141
  channel, adapter, statusMsg, startTime,
119
142
  executionId: capturedExecutionId,
120
- sessionName, sessionId, threadAnchorId, userMessageTs: messageTs,
143
+ sessionName, sessionId, threadAnchorId, userMessageTs: messageTs, userMessage,
121
144
  });
122
145
  }
123
146
  }
@@ -144,14 +167,17 @@ export function resolveDefaultAgent(agentMessage, channel) {
144
167
  pluginDirs: defaultAgentDef?.pluginDirs || null,
145
168
  };
146
169
  }
147
- async function handleDefaultAgentResult({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, sessionName, sessionId, threadAnchorId, messageTs, callbacks }) {
170
+ async function handleDefaultAgentResult({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, sessionName, sessionId, threadAnchorId, messageTs, callbacks, registerContinuationSink = null }) {
148
171
  if (result?.rateLimited) {
172
+ // Record the interrupted conversation so it auto-resumes when the rate-limit window
173
+ // resets (rate-limit-throttle onResume → resume-dispatcher).
174
+ recordResume({ kind: 'direct', channel, userMessage, recordedAt: Date.now() });
149
175
  const { elapsedStr } = computeElapsed(startTime);
150
176
  const fallbackText = `${Icons.warning} ${buildSessionTag(sessionName, sessionId)}Rate limited — all fallbacks exhausted (${elapsedStr})`;
151
177
  await sealStatus(adapter, statusMsg, fallbackText, buildSealedStatusActionBlocks(fallbackText, { channel, sessionName, isDm: true }));
152
178
  return;
153
179
  }
154
- await handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger: 'user', sessionName, threadAnchorId, userMessageTs: messageTs, onAssistantMessage: callbacks.onAssistantMsg });
180
+ await handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger: 'user', sessionName, threadAnchorId, userMessageTs: messageTs, onAssistantMessage: callbacks.onAssistantMsg, registerContinuationSink });
155
181
  }
156
182
  export async function resolveSessionName(sessionId, channel, userMessage, adapter) {
157
183
  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,
@@ -32,7 +32,10 @@ export async function runConversation(opts) {
32
32
  const agentConfig = resolveAgentSlotConfigByName(defaultAgentName);
33
33
  if (!agentConfig)
34
34
  throw new Error(`Unknown default agent: ${defaultAgentName}`);
35
- const prompt = buildConversationPrompt(agentConfig, opts.userMessage);
35
+ // USER.md profile is injected only on a session's FIRST turn (existingSessionId === null).
36
+ // Session resume keeps it in history thereafter, so re-sending it every turn just wastes tokens.
37
+ const isFreshSession = opts.existingSessionId === null;
38
+ const prompt = buildConversationPrompt(agentConfig, opts.userMessage, { includeUserContext: isFreshSession });
36
39
  const project = projectStore.resolveFromMessage(opts.userMessage)?.id ?? 'general';
37
40
  // Resolve profile: hardcoded agent profiles win; __active__ honors the optional override
38
41
  // (scheduler) then the channel's active profile.
@@ -105,5 +108,5 @@ export async function runConversation(opts) {
105
108
  else {
106
109
  executionRegistry.teardownExecution({ executionId: execution.id, status: 'completed', durationS, result });
107
110
  }
108
- return { result, executionId: execution.id };
111
+ return { result, executionId: execution.id, agentProcess: handle.agentProcess };
109
112
  }
@@ -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,8 +14,9 @@ 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
- export declare function handleAgentError({ error, channel, adapter, statusMsg, startTime, executionId, sessionName, sessionId, effectiveSessionId, threadAnchorId, userMessageTs }: {
19
+ export declare function handleAgentError({ error, channel, adapter, statusMsg, startTime, executionId, sessionName, sessionId, effectiveSessionId, threadAnchorId, userMessageTs, userMessage }: {
18
20
  error: {
19
21
  message: string;
20
22
  cancelled?: boolean;
@@ -29,6 +31,7 @@ export declare function handleAgentError({ error, channel, adapter, statusMsg, s
29
31
  effectiveSessionId?: string | null;
30
32
  threadAnchorId?: string | null;
31
33
  userMessageTs?: string | null;
34
+ userMessage?: string | null;
32
35
  }): Promise<void>;
33
36
  export declare function resumeAskUserQuestionGroup({ adapter, group, responseText }: {
34
37
  adapter: PlatformAdapter;
@@ -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,19 @@ 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';
28
+ import { isApiRateLimitError } from '../domain/agents/config.js';
29
+ import { isThrottled } from '../domain/costs/rate-limit-throttle.js';
24
30
  import { normalizeSkillCommandPrefix } from '../domain/memory/skill-scanner.js';
25
31
  import { getOutboundQueue } from '../store/outbound-queue.js';
26
32
  import { buildDurableHooks, durablePost } from './durable-helpers.js';
27
33
  const log = createLogger('lifecycle');
28
34
  // --- 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 }) {
35
+ export async function handleAgentSuccess({ result, channel, adapter, statusMsg, startTime, userMessage, executionId, trigger = 'user', sessionName = null, threadAnchorId = null, userMessageTs = null, onAssistantMessage = null, registerContinuationSink = null }) {
30
36
  if (result?.sessionId)
31
37
  await setSessionAsync(channel, result.sessionId, resolveBackendForChannel(channel));
32
38
  await registerOrUpdateSession(result, sessionName, channel, trigger, projectStore.resolveFromMessage(userMessage)?.id ?? 'general');
@@ -37,10 +43,43 @@ export async function handleAgentSuccess({ result, channel, adapter, statusMsg,
37
43
  const sessionTag = buildSessionTag(sessionName, result?.sessionId);
38
44
  const stream = onAssistantMessage?.stream ?? null;
39
45
  const askCount = await askUserQuestion.sendMessages(result, channel, adapter, statusMsg.messageId, threadAnchorId, stream);
46
+ // Background-task continuation: a run_in_background task is still running. Hold the status
47
+ // in a "waiting" state (don't seal) and register a sink so the spontaneous continuation turn
48
+ // the CLI emits on completion merges into this reply and seals the status then. Only when
49
+ // there are no pending user questions and the assistant reply stream is available to merge into.
50
+ const pendingBg = result?.pendingBackgroundTasks ?? 0;
51
+ if (registerContinuationSink && stream && askCount === 0 && pendingBg > 0) {
52
+ const projectId = projectStore.resolveFromMessage(userMessage)?.id ?? 'general';
53
+ const backend = resolveBackendForChannel(channel);
54
+ const waitingText = (pending) => `${Icons.waiting} ${sessionTag}${t('status.backgroundRunning')} (${pending}) (${elapsedStr}${metrics})`;
55
+ await writeStatus(adapter, statusMsg, waitingText(pendingBg));
56
+ let finalized = false;
57
+ const sink = buildContinuationSink({
58
+ stream,
59
+ onWaiting: (pending) => { void writeStatus(adapter, statusMsg, waitingText(pending)); },
60
+ onComplete: (contResult) => {
61
+ if (finalized)
62
+ return;
63
+ finalized = true;
64
+ void finalizeBackgroundContinuation({
65
+ adapter, statusMsg, channel, sessionName, sessionId: result?.sessionId ?? null,
66
+ startTime, baseResult: result, contResult, userMessageTs, executionId, trigger, projectId, backend,
67
+ }).catch((e) => log.error('finalizeBackgroundContinuation failed:', e?.message ?? e));
68
+ },
69
+ });
70
+ registerContinuationSink(sink);
71
+ return; // status held; finalization deferred to the continuation turn
72
+ }
40
73
  const statusText = askCount > 0
41
74
  ? `${Icons.waiting} ${sessionTag}${t('status.waitingForUserInput')} (${elapsedStr}${metrics})`
42
75
  : `${Icons.ok} ${t('status.done')} | ${sessionTag}(${elapsedStr}${metrics})`;
43
76
  await sealStatus(adapter, statusMsg, statusText, buildSealedStatusActionBlocks(statusText, { channel, sessionName, isDm: true }));
77
+ // Push a NEW message when a long-running user turn finishes (the sealed status above is an
78
+ // edit, which does not notify on Slack/Feishu). Only fires when no ask-user questions are
79
+ // pending — those already prompt the user.
80
+ if (askCount === 0) {
81
+ await maybeNotifyTurnComplete({ adapter, channel, threadAnchorId, sessionName, sessionId: result?.sessionId ?? null, elapsedS, elapsedStr, status: 'completed', metricsSuffix: metrics });
82
+ }
44
83
  if (userMessageTs) {
45
84
  await conversationLedger.completeTurn(channel, userMessageTs, { executionId });
46
85
  }
@@ -75,6 +114,36 @@ export async function handleAgentSuccess({ result, channel, adapter, statusMsg,
75
114
  }
76
115
  }
77
116
  }
117
+ /** Finalize a turn that was held in "waiting" state once its background-task continuation
118
+ * completes: seal the status (combined metrics), complete the conversation turn, release the
119
+ * streaming callback, and record the continuation's cost. Idempotency is guarded by the
120
+ * caller (the sink fires onComplete once). */
121
+ async function finalizeBackgroundContinuation({ adapter, statusMsg, channel, sessionName, sessionId, startTime, baseResult, contResult, userMessageTs, executionId, trigger, projectId, backend }) {
122
+ const { elapsedStr } = computeElapsed(startTime);
123
+ const totalCost = (baseResult?.total_cost_usd ?? 0) + (contResult?.total_cost_usd ?? 0);
124
+ const totalTurns = (baseResult?.num_turns ?? 0) + (contResult?.num_turns ?? 0);
125
+ const metrics = formatMetricsSuffix({ costUsd: totalCost, numTurns: totalTurns });
126
+ const sessionTag = buildSessionTag(sessionName, sessionId);
127
+ const statusText = `${Icons.ok} ${t('status.done')} | ${sessionTag}(${elapsedStr}${metrics})`;
128
+ await sealStatus(adapter, statusMsg, statusText, buildSealedStatusActionBlocks(statusText, { channel, sessionName, isDm: true }));
129
+ await maybeNotifyTurnComplete({ adapter, channel, threadAnchorId: null, sessionName, sessionId, elapsedS: computeElapsed(startTime).elapsedS, elapsedStr, status: 'completed', metricsSuffix: metrics });
130
+ if (userMessageTs) {
131
+ await conversationLedger.completeTurn(channel, userMessageTs, { executionId }).catch((e) => log.error('completeTurn failed:', e.message));
132
+ }
133
+ clearStreamingCallback(channel);
134
+ if (contResult?.total_cost_usd != null) {
135
+ await recordCost({
136
+ project: projectId,
137
+ trigger: trigger ? `${trigger}:bg-continuation` : 'bg-continuation',
138
+ cost_usd: contResult.total_cost_usd,
139
+ backend: backend,
140
+ mode: getClaudeMode(),
141
+ source: 'estimate',
142
+ input_tokens: 0,
143
+ output_tokens: 0,
144
+ }).catch((e) => log.warn('recordCost (bg-continuation) failed:', e.message));
145
+ }
146
+ }
78
147
  async function registerOrUpdateSession(result, sessionName, channel, trigger, projectId = 'general') {
79
148
  if (!result?.sessionId || !sessionName)
80
149
  return;
@@ -102,7 +171,7 @@ async function backfillLedgerSessionId(result, channel) {
102
171
  }
103
172
  }
104
173
  // --- Agent error handler ---
105
- export async function handleAgentError({ error, channel, adapter, statusMsg, startTime, executionId, sessionName = null, sessionId = null, effectiveSessionId = null, threadAnchorId = null, userMessageTs = null }) {
174
+ export async function handleAgentError({ error, channel, adapter, statusMsg, startTime, executionId, sessionName = null, sessionId = null, effectiveSessionId = null, threadAnchorId = null, userMessageTs = null, userMessage = null }) {
106
175
  if (executionId)
107
176
  runningExecutions.fail(executionId, error.message);
108
177
  const resolvedSessionId = effectiveSessionId || sessionId;
@@ -124,10 +193,23 @@ export async function handleAgentError({ error, channel, adapter, statusMsg, sta
124
193
  await sealStatus(adapter, statusMsg, cancelledText, buildSealedStatusActionBlocks(cancelledText, { channel, sessionName, isDm: true }));
125
194
  return;
126
195
  }
196
+ // Thrown rate-limit error while the five-hour throttle is active: pause-and-resume instead of
197
+ // failing, mirroring the thread thrown path (domain/threads/runner.ts) and the graceful direct
198
+ // path (agent-runner handleDefaultAgentResult / edit-retry below). runningExecutions.fail already
199
+ // ran at the top. Only when a userMessage is available (direct/TUI turns) — manager-qa / edit
200
+ // callers without it fall through to the normal error path.
201
+ if (userMessage && isApiRateLimitError(error.message) && isThrottled()) {
202
+ finalizeLocalExecution({ executionId, status: 'failed', error: { message: 'Rate limited' }, durationS: elapsedS });
203
+ recordResume({ kind: 'direct', channel, userMessage, recordedAt: Date.now() });
204
+ const rateLimitText = `${Icons.warning} ${sessionTag}${t('status.rateLimitedExhausted')} (${elapsedStr})`;
205
+ await sealStatus(adapter, statusMsg, rateLimitText, buildSealedStatusActionBlocks(rateLimitText, { channel, sessionName, isDm: true }));
206
+ return;
207
+ }
127
208
  log.error('Agent error:', error.message);
128
209
  finalizeLocalExecution({ executionId, status: 'failed', error, durationS: elapsedS });
129
210
  const errorText = `${Icons.error} ${sessionTag}${t('status.error')} (${elapsedStr})`;
130
211
  await sealStatus(adapter, statusMsg, errorText, buildSealedStatusActionBlocks(errorText, { channel, sessionName, isDm: true }));
212
+ await maybeNotifyTurnComplete({ adapter, channel, threadAnchorId, sessionName, sessionId: resolvedSessionId, elapsedS, elapsedStr, status: 'failed' });
131
213
  const errorDest = { type: 'interactive-reply', conduit: channel, sessionId: resolvedSessionId ?? '' };
132
214
  const queue = getOutboundQueue();
133
215
  if (queue) {
@@ -242,6 +324,8 @@ async function runRetryAgent({ channel, text, adapter, statusMsg, startTime, ses
242
324
  clearStreamingCallback(channel);
243
325
  await maybeNotifyCodexLowUsage({ adapter, result });
244
326
  if (result?.rateLimited) {
327
+ // Record the interrupted edit-retry conversation for auto-resume when the window resets.
328
+ recordResume({ kind: 'direct', channel, userMessage: text, recordedAt: Date.now() });
245
329
  const { elapsedStr } = computeElapsed(startTime);
246
330
  const rateLimitText = `${Icons.warning} ${buildSessionTag(sessionName, sessionId)}${t('status.rateLimitedExhausted')} (${elapsedStr})`;
247
331
  await sealStatus(adapter, statusMsg, rateLimitText, buildSealedStatusActionBlocks(rateLimitText, { channel, sessionName, isDm: true }));
@@ -0,0 +1,56 @@
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 — an AGENT-facing prompt (English, not i18n;
17
+ * mirrors the directives, which are not localized). Mirrors buildChildResultNotice's shape: states
18
+ * what is asked and how to respond. */
19
+ export declare function buildQuestionNotice(q: {
20
+ questionId: string;
21
+ fromTaskId: string | null;
22
+ question: string;
23
+ }): string;
24
+ export type AskResult = {
25
+ ok: true;
26
+ questionId: string;
27
+ target: 'manager';
28
+ managerThreadId: string;
29
+ } | {
30
+ ok: true;
31
+ questionId: string;
32
+ target: 'human';
33
+ channel: string;
34
+ } | {
35
+ ok: false;
36
+ error: string;
37
+ };
38
+ /** Register a subtask's question and route it: to its manager (woken to answer), or — at the top of
39
+ * the tree — to a human via the origin channel. Returns a questionId the caller polls via getAnswer. */
40
+ export declare function askManager(threadId: string, question: string, deps?: ManagerQaDeps): Promise<AskResult>;
41
+ /** Manager answers a subtask question. Records the answer and forces the manager back to waiting
42
+ * (pendingControl='wait') so it re-suspends on its still-live children at the next step boundary. */
43
+ export declare function submitAnswer(questionId: string, answer: string): Promise<{
44
+ ok: boolean;
45
+ error?: string;
46
+ }>;
47
+ /** Poll for an answer. Consumes the entry once an answer is present (one-shot read by the poller). */
48
+ export declare function getAnswer(questionId: string): {
49
+ found: boolean;
50
+ answered: boolean;
51
+ answer: string | null;
52
+ };
53
+ /** Interactive hook: if `channel` has a pending human-escalated question, consume this message as
54
+ * its answer and return true (the caller should then short-circuit normal turn handling). */
55
+ export declare function tryAnswerFromHuman(channel: string, text: string): boolean;
56
+ export {};