@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
@@ -0,0 +1,49 @@
1
+ // input: process.env-style connection config for cortex-client
2
+ // output: resolved WebSocket server URL + optional Cloudflare Access headers
3
+ // pos: side-effect-free connection-config resolution for cortex-client
4
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ /**
6
+ * Resolve the WebSocket URL the cortex-client dials.
7
+ *
8
+ * A full ``CORTEX_SERVER_URL`` (e.g. ``wss://cortex.fangxm.me``) takes
9
+ * precedence so the client can reach the agent-server through a Cloudflare
10
+ * Tunnel over 443/TLS. Otherwise it falls back to ``ws://<host>:<port>`` for
11
+ * direct/LAN reach.
12
+ */
13
+ export function resolveServerUrl(env) {
14
+ const url = env.CORTEX_SERVER_URL?.trim();
15
+ if (url)
16
+ return url;
17
+ const port = env.CORTEX_SERVER_PORT || '3002';
18
+ return `ws://${env.CORTEX_SERVER_HOST}:${port}`;
19
+ }
20
+ /**
21
+ * Cloudflare Access service-token headers, returned only when both the client
22
+ * id and secret are configured. These let the cortex-client pass a Cloudflare
23
+ * Access policy placed in front of the tunnel (the agent-server WebSocket has
24
+ * no auth of its own, so Access is the gate when it is exposed publicly).
25
+ */
26
+ export function buildAccessHeaders(env) {
27
+ const id = env.CF_ACCESS_CLIENT_ID?.trim();
28
+ const secret = env.CF_ACCESS_CLIENT_SECRET?.trim();
29
+ if (id && secret) {
30
+ return {
31
+ 'CF-Access-Client-Id': id,
32
+ 'CF-Access-Client-Secret': secret,
33
+ };
34
+ }
35
+ return undefined;
36
+ }
37
+ /**
38
+ * Connection headers the cortex-client sends on the WebSocket upgrade. Combines the
39
+ * optional Cloudflare Access service-token headers with the Cortex bearer token
40
+ * (``x-cortex-token`` from ``CORTEX_CLIENT_TOKEN``) that the agent-server's WebSocket
41
+ * gate requires. Returns undefined when neither is configured.
42
+ */
43
+ export function buildAuthHeaders(env) {
44
+ const headers = { ...(buildAccessHeaders(env) ?? {}) };
45
+ const token = env.CORTEX_CLIENT_TOKEN?.trim();
46
+ if (token)
47
+ headers['x-cortex-token'] = token;
48
+ return Object.keys(headers).length > 0 ? headers : undefined;
49
+ }
@@ -8,11 +8,11 @@ import * as path from 'path';
8
8
  import * as os from 'os';
9
9
  import { execFileSync, spawn } from 'child_process';
10
10
  import { scanCortexMDChain } from '../memory/cortex-md-scanner.js';
11
+ import { resolveServerUrl, buildAuthHeaders } from './cortex-client-config.js';
11
12
  import { createLogger } from '../../core/log.js';
12
13
  const log = createLogger('cortex-client');
13
14
  // --- Config ---
14
15
  const SERVER_HOST = process.env.CORTEX_SERVER_HOST;
15
- const SERVER_PORT = process.env.CORTEX_SERVER_PORT || '3002';
16
16
  const DEVICE_NAME = process.env.CORTEX_DEVICE_NAME || os.hostname();
17
17
  const PLATFORM = process.platform;
18
18
  const HEARTBEAT_INTERVAL_MS = 5000;
@@ -20,8 +20,8 @@ const GIT_BASH_PATHS = [
20
20
  'C:\\Program Files\\Git\\bin\\bash.exe',
21
21
  'C:\\Program Files (x86)\\Git\\bin\\bash.exe',
22
22
  ];
23
- if (!SERVER_HOST) {
24
- log.error('CORTEX_SERVER_HOST is required');
23
+ if (!SERVER_HOST && !process.env.CORTEX_SERVER_URL) {
24
+ log.error('Either CORTEX_SERVER_URL (full ws/wss URL) or CORTEX_SERVER_HOST is required');
25
25
  process.exit(1);
26
26
  }
27
27
  // --- Output accumulator (prevents WS message size explosion) ---
@@ -598,9 +598,13 @@ let heartbeatTimer = null;
598
598
  let reconnectDelay = 1000;
599
599
  const MAX_RECONNECT_DELAY = 30000;
600
600
  function connect() {
601
- const url = `ws://${SERVER_HOST}:${SERVER_PORT}`;
602
- log.info(`Connecting to ${url} as "${DEVICE_NAME}" (${PLATFORM})...`);
603
- ws = new WebSocket(url);
601
+ const url = resolveServerUrl(process.env);
602
+ const headers = buildAuthHeaders(process.env);
603
+ const hasToken = !!process.env.CORTEX_CLIENT_TOKEN?.trim();
604
+ const hasCf = !!(process.env.CF_ACCESS_CLIENT_ID && process.env.CF_ACCESS_CLIENT_SECRET);
605
+ const authTag = hasCf ? (hasToken ? ' [token+CF]' : ' [CF Access]') : (hasToken ? ' [token]' : '');
606
+ log.info(`Connecting to ${url} as "${DEVICE_NAME}" (${PLATFORM})${authTag}...`);
607
+ ws = headers ? new WebSocket(url, { headers }) : new WebSocket(url);
604
608
  ws.on('open', () => {
605
609
  log.info(`Connected to server`);
606
610
  reconnectDelay = 1000;
@@ -700,5 +704,5 @@ function shutdown() {
700
704
  process.on('SIGINT', shutdown);
701
705
  process.on('SIGTERM', shutdown);
702
706
  // --- Start ---
703
- log.info(`Starting: device="${DEVICE_NAME}", platform="${PLATFORM}", server=${SERVER_HOST}:${SERVER_PORT}`);
707
+ log.info(`Starting: device="${DEVICE_NAME}", platform="${PLATFORM}", server=${resolveServerUrl(process.env)}`);
704
708
  connect();
@@ -102,7 +102,23 @@ async function runScheduledTaskAsync({ normalizedMessage, message, projectId, sc
102
102
  const threadResult = await dispatchByPlan({ plan, normalizedMessage, message, scheduleTaskId, effectiveProfile, statusMsg, startTime, sessionName, projectReportDest, projectId });
103
103
  const result = threadResult.lastAgentResult;
104
104
  await maybeNotifyCodexLowUsage({ adapter, result });
105
- if (result?.rateLimited) {
105
+ // Rate-limit pause: the runner already recorded the thread for auto-resume and left it in
106
+ // 'rate_limited'. Don't treat it as a failure — just reflect the paused state.
107
+ if (threadResult.thread?.status === 'rate_limited') {
108
+ const { elapsedStr } = computeElapsed(startTime);
109
+ if (statusMsg) {
110
+ const text = `${Icons.warning} ${buildSessionTag(sessionName, result?.sessionId)}Paused — rate limited, will auto-resume (${elapsedStr})`;
111
+ const queue = getOutboundQueue();
112
+ if (queue) {
113
+ await durableUpdate(queue, adapter, statusMsg, { text });
114
+ }
115
+ else {
116
+ await adapter.updateMessage(statusMsg, { text });
117
+ }
118
+ }
119
+ }
120
+ else if (result?.rateLimited) {
121
+ // Fallback: rate-limited but no active throttle, so the runner did not pause the thread.
106
122
  const { elapsedStr } = computeElapsed(startTime);
107
123
  if (statusMsg) {
108
124
  const text = `${Icons.warning} ${buildSessionTag(sessionName, result?.sessionId)}Rate limited — all fallbacks exhausted (${elapsedStr})`;
@@ -125,6 +125,7 @@ async function executeDispatchTask({ selected, selectedTask, channel, scheduleTa
125
125
  // DR-0014: persisted so a suspended parent's re-entry can rebuild the
126
126
  // task-status-check onEnd hook (extraHooks are not persisted on ThreadRecord).
127
127
  taskId: selectedTask.id ?? null, taskProject: selectedTask.project ?? null,
128
+ taskText: selectedTask.text ?? null,
128
129
  resumeDest: 'project-report',
129
130
  },
130
131
  });
@@ -226,7 +227,28 @@ async function executeDispatchTask({ selected, selectedTask, channel, scheduleTa
226
227
  }
227
228
  return { success: true, skipped: false, note: `[${selectedTask.project}] ${splitOutcome.note}` };
228
229
  }
230
+ // Rate-limit pause: the runner left the thread in 'rate_limited' and recorded it for
231
+ // auto-resume. Keep the task CLAIMED (do not unclaim → no fresh re-dispatch that would race
232
+ // the thread resume), don't publish task.completed, don't finalize. resume-dispatcher re-enters
233
+ // the same thread when the window resets, and its rebuilt onEnd task-status-check hook closes
234
+ // the task loop at true termination — mirrors the DR-0014 suspended-parent branch above.
235
+ if (threadResult.thread?.status === 'rate_limited') {
236
+ if (statusMsg) {
237
+ // Persist the live status message so the post-resume settle can refresh it.
238
+ await threadStore.mutate(thread.id, (t) => { (t.metadata ??= {}).statusMsgRef = statusMsg; });
239
+ const text = `${Icons.warning} [${selectedTask.project}] ${selectedTask.text.substring(0, 80)} | paused — rate limited, will auto-resume`;
240
+ const queue = getOutboundQueue();
241
+ if (queue) {
242
+ await durableUpdate(queue, adapter, statusMsg, { text });
243
+ }
244
+ else {
245
+ await adapter.updateMessage(statusMsg, { text }).catch(() => { });
246
+ }
247
+ }
248
+ return { success: true, skipped: false, note: `Paused [${selectedTask.project}] — rate limited, will auto-resume` };
249
+ }
229
250
  if (result?.rateLimited) {
251
+ // Fallback: rate-limited but no active throttle, so the runner did not pause the thread.
230
252
  const { elapsedStr } = computeElapsed(startTime);
231
253
  await taskMutator.unclaim(selectedTask.id);
232
254
  if (statusMsg) {
@@ -1,4 +1,5 @@
1
1
  import type { PlatformAdapter, OutputStream } from '../../platform/index.js';
2
+ import { runAgent } from '../agents/index.js';
2
3
  export interface SessionHookConfig {
3
4
  command: string;
4
5
  args?: string[];
@@ -38,9 +39,38 @@ export interface SessionHookFormat {
38
39
  export interface SessionHookInject {
39
40
  targetSessionId: string;
40
41
  profileName: string | null;
42
+ /** Session-pool key for the injected turn.
43
+ * - onNew: an ISOLATED key (onNewInjectSessionKey(channel)) so resuming the old session for
44
+ * the pre-close turn never collides with the channel's live pool slot — see the race below.
45
+ * - onMessageEnd: the channel itself, because the injection continues the live conversation. */
46
+ sessionKey: string;
41
47
  /** Forwarded to runAgent as `trigger`, useful for telemetry / cost grouping. */
42
48
  trigger?: string;
43
49
  }
50
+ /** Pool key for the onNew hook's injected "pre-close" turn.
51
+ *
52
+ * MUST be distinct from the channel's live session-pool slot (which is keyed by the channel
53
+ * itself, see ClaudeAdapter / facade `sessionKey: options.channel`). Race it guards against:
54
+ * `!new` fires this hook fire-and-forget, then synchronously closeSession(channel) +
55
+ * resetChannelSession(channel). The hook's memory-write subprocess finishes LATER and injects
56
+ * its stdout as a final turn that RESUMES the old session. If that turn used `channel` as its
57
+ * pool key it would re-create (resurrect) a live session under the channel slot AFTER the reset
58
+ * — so the next message of the brand-new conversation (also keyed by channel) would reuse the
59
+ * resurrected OLD session instead of starting fresh. Routing the pre-close turn to a dedicated
60
+ * key keeps it off the live slot; we close that key once the turn is done. */
61
+ export declare function onNewInjectSessionKey(channel: string): string;
62
+ /** Injected-turn dependencies — seam for unit tests (default binds the real runAgent + a
63
+ * backend-aware session close). */
64
+ export interface InjectDeps {
65
+ runAgent: typeof runAgent;
66
+ /** Close the pooled session created for the injected turn (by sessionKey). */
67
+ closeInjectedSession: (channel: string, sessionKey: string) => void | Promise<void>;
68
+ }
69
+ /** Inject hook stdout as a fresh agent turn against `inject.targetSessionId`, routed through
70
+ * `stream`. Runs on `inject.sessionKey`; for onNew that is an isolated key which we close
71
+ * afterwards (the resurrected old session must not linger on / collide with the channel slot).
72
+ * For onMessageEnd the key IS the channel (live conversation) and is left open. */
73
+ export declare function runHookInjection(output: string, spec: SessionHookSpec, stream: OutputStream, deps?: InjectDeps): Promise<void>;
44
74
  export interface SessionHookSpec {
45
75
  name: HookName;
46
76
  ctx: SessionHookContext;
@@ -56,7 +86,7 @@ export interface SessionHookSpec {
56
86
  * reply chain (no top-level leak).
57
87
  * - onNew: pass a fresh stream anchored at the last assistant message's thread parent
58
88
  * (resolved via resolveSessionThreadTs). */
59
- export declare function runSessionHook(spec: SessionHookSpec, stream: OutputStream): Promise<void>;
89
+ export declare function runSessionHook(spec: SessionHookSpec, stream: OutputStream, deps?: InjectDeps): Promise<void>;
60
90
  /** Resolve the profile name to use when injecting the onNew hook's stdout as a fresh
61
91
  * agent turn. Priority order:
62
92
  * 1. session-registry (per-session truth — correct for thread-spawned sessions whose
@@ -1,5 +1,6 @@
1
1
  // input: agent-server/session-hooks.json (lazy-read), spawn() subprocess, OutputStream
2
2
  // output: runSessionHook() unified pipeline + fireAndForgetPreCloseHook (onNew) + onMessageEnd helpers
3
+ // + runHookInjection / onNewInjectSessionKey (isolated pool key for the onNew pre-close turn)
3
4
  // pos: session-level hook subsystem — config loading, subprocess spawn, unified Slack-display pipeline
4
5
  // (parallel to thread-hook system, scoped to channel/session rather than thread)
5
6
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
@@ -10,6 +11,7 @@ import { DATA_DIR, CONFIG_DIR } from '../../core/paths.js';
10
11
  import { createLogger } from '../../core/log.js';
11
12
  import { Icons } from '../../core/icons.js';
12
13
  import { runAgent, resolveBackendForChannel } from '../agents/index.js';
14
+ import { getAdapter } from '../../agent-adapter/index.js';
13
15
  import { getSessionAsync } from '../sessions/session.js';
14
16
  import { sessionStore } from '../../store/session-registry-repo.js';
15
17
  import { conversationLedger } from '../../store/conversation-ledger-repo.js';
@@ -99,6 +101,63 @@ function spawnHookProcess({ cfg, stdinPayload, env, label }) {
99
101
  }
100
102
  });
101
103
  }
104
+ /** Pool key for the onNew hook's injected "pre-close" turn.
105
+ *
106
+ * MUST be distinct from the channel's live session-pool slot (which is keyed by the channel
107
+ * itself, see ClaudeAdapter / facade `sessionKey: options.channel`). Race it guards against:
108
+ * `!new` fires this hook fire-and-forget, then synchronously closeSession(channel) +
109
+ * resetChannelSession(channel). The hook's memory-write subprocess finishes LATER and injects
110
+ * its stdout as a final turn that RESUMES the old session. If that turn used `channel` as its
111
+ * pool key it would re-create (resurrect) a live session under the channel slot AFTER the reset
112
+ * — so the next message of the brand-new conversation (also keyed by channel) would reuse the
113
+ * resurrected OLD session instead of starting fresh. Routing the pre-close turn to a dedicated
114
+ * key keeps it off the live slot; we close that key once the turn is done. */
115
+ export function onNewInjectSessionKey(channel) {
116
+ return `${channel}::onnew-hook`;
117
+ }
118
+ const defaultInjectDeps = {
119
+ runAgent,
120
+ closeInjectedSession: async (channel, sessionKey) => {
121
+ try {
122
+ await getAdapter(resolveBackendForChannel(channel)).close(sessionKey);
123
+ }
124
+ catch (e) {
125
+ log.warn(`closeInjectedSession failed (${sessionKey}): ${e?.message || e}`);
126
+ }
127
+ },
128
+ };
129
+ /** Inject hook stdout as a fresh agent turn against `inject.targetSessionId`, routed through
130
+ * `stream`. Runs on `inject.sessionKey`; for onNew that is an isolated key which we close
131
+ * afterwards (the resurrected old session must not linger on / collide with the channel slot).
132
+ * For onMessageEnd the key IS the channel (live conversation) and is left open. */
133
+ export async function runHookInjection(output, spec, stream, deps = defaultInjectDeps) {
134
+ const inject = spec.inject;
135
+ if (!inject)
136
+ return;
137
+ try {
138
+ const handle = deps.runAgent(output, {
139
+ channel: spec.ctx.channel,
140
+ sessionId: inject.targetSessionId,
141
+ sessionKey: inject.sessionKey,
142
+ isUserInitiated: false,
143
+ profileName: inject.profileName,
144
+ trigger: inject.trigger ?? `hook:${spec.name}`,
145
+ onAssistantMessage: (text) => stream.emitText(text),
146
+ });
147
+ await handle.promise;
148
+ }
149
+ catch (err) {
150
+ const msg = err?.message || String(err);
151
+ log.error(`hook ${spec.name} injected agent failed: ${msg}`);
152
+ stream.emitText(`${Icons.warning} ${spec.name} hook follow-up failed: ${msg}`);
153
+ }
154
+ finally {
155
+ // Only the isolated (onNew) key is torn down; the channel live slot (onMessageEnd) stays.
156
+ if (inject.sessionKey !== spec.ctx.channel) {
157
+ await deps.closeInjectedSession(spec.ctx.channel, inject.sessionKey);
158
+ }
159
+ }
160
+ }
102
161
  function buildHookEnv(name, ctx) {
103
162
  const env = {
104
163
  ...process.env,
@@ -131,7 +190,7 @@ function buildHookStdin(name, ctx) {
131
190
  * reply chain (no top-level leak).
132
191
  * - onNew: pass a fresh stream anchored at the last assistant message's thread parent
133
192
  * (resolved via resolveSessionThreadTs). */
134
- export async function runSessionHook(spec, stream) {
193
+ export async function runSessionHook(spec, stream, deps = defaultInjectDeps) {
135
194
  const cfg = loadHookConfig(spec.name);
136
195
  if (!cfg)
137
196
  return;
@@ -161,21 +220,7 @@ export async function runSessionHook(spec, stream) {
161
220
  return;
162
221
  }
163
222
  try {
164
- const handle = runAgent(result.stdout, {
165
- channel: spec.ctx.channel,
166
- sessionId: spec.inject.targetSessionId,
167
- sessionKey: spec.ctx.channel,
168
- isUserInitiated: false,
169
- profileName: spec.inject.profileName,
170
- trigger: spec.inject.trigger ?? `hook:${spec.name}`,
171
- onAssistantMessage: (text) => stream.emitText(text),
172
- });
173
- await handle.promise;
174
- }
175
- catch (err) {
176
- const msg = err?.message || String(err);
177
- log.error(`hook ${spec.name} injected agent failed: ${msg}`);
178
- stream.emitText(`${Icons.warning} ${spec.name} hook follow-up failed: ${msg}`);
223
+ await runHookInjection(result.stdout, spec, stream, deps);
179
224
  }
180
225
  finally {
181
226
  await stream.flush().catch((e) => log.warn(`stream.flush after inject failed (${label}): ${e?.message || e}`));
@@ -261,7 +306,12 @@ async function prepareOnNewRun(channel, adapter, threadAnchorId) {
261
306
  name: 'onNew',
262
307
  ctx: { channel, sessionId, sessionName, profile: profileName },
263
308
  format: ONNEW_FORMAT,
264
- inject: { targetSessionId: sessionId, profileName, trigger: 'hook:onNew' },
309
+ inject: {
310
+ targetSessionId: sessionId,
311
+ profileName,
312
+ sessionKey: onNewInjectSessionKey(channel),
313
+ trigger: 'hook:onNew',
314
+ },
265
315
  };
266
316
  return { spec, stream };
267
317
  }
@@ -304,6 +354,8 @@ export async function runMessageEndSessionHook(args) {
304
354
  inject: {
305
355
  targetSessionId: args.sessionId,
306
356
  profileName: args.profile ?? null,
357
+ // onMessageEnd continues the live conversation — keep it on the channel pool slot.
358
+ sessionKey: args.channel,
307
359
  trigger: 'hook:onMessageEnd',
308
360
  },
309
361
  };
@@ -0,0 +1,63 @@
1
+ export type CheckStatus = 'pass' | 'warn' | 'fail' | 'skip';
2
+ export interface CheckResult {
3
+ id: string;
4
+ label: string;
5
+ status: CheckStatus;
6
+ detail: string;
7
+ hint?: string;
8
+ /** Whether `applySafeFixes` can repair this issue idempotently. */
9
+ fixable?: boolean;
10
+ }
11
+ export interface DoctorSection {
12
+ title: string;
13
+ checks: CheckResult[];
14
+ }
15
+ export interface DoctorReport {
16
+ sections: DoctorSection[];
17
+ counts: {
18
+ pass: number;
19
+ warn: number;
20
+ fail: number;
21
+ skip: number;
22
+ };
23
+ /** True when no check failed (warnings/skips do not break ok). */
24
+ ok: boolean;
25
+ }
26
+ export interface DoctorPaths {
27
+ DATA_DIR: string;
28
+ CONFIG_DIR: string;
29
+ STORE_DIR: string;
30
+ }
31
+ /** Read-only environment probes — the diagnostic path never writes. */
32
+ export interface DoctorDeps {
33
+ env: Record<string, string | undefined>;
34
+ paths: DoctorPaths;
35
+ homeDir: string;
36
+ nodeVersion: string;
37
+ requiredNodeMajor: number;
38
+ fileExists(p: string): boolean;
39
+ isWritable(p: string): boolean;
40
+ readText(p: string): string | null;
41
+ parseDotenv(text: string): Record<string, string>;
42
+ commandExists(bin: string): boolean;
43
+ pidAlive(pid: number): boolean;
44
+ probeGateway(): Promise<boolean>;
45
+ }
46
+ /** Write actuators used only by `applySafeFixes` (idempotent, non-destructive). */
47
+ export interface FixActuators {
48
+ mkdirp(p: string): void;
49
+ ensureEnvFile(envPath: string): void;
50
+ /** Generate any missing auth tokens, persist to envPath; return names generated. */
51
+ ensureAuthTokens(envPath: string): string[];
52
+ regenerateMcpConfig(): void;
53
+ }
54
+ export interface FixOutcome {
55
+ id: string;
56
+ label: string;
57
+ applied: boolean;
58
+ detail: string;
59
+ }
60
+ export declare function runDiagnostics(deps: DoctorDeps): Promise<DoctorReport>;
61
+ export declare function applySafeFixes(report: DoctorReport, deps: DoctorDeps, fix: FixActuators): Promise<FixOutcome[]>;
62
+ export declare function createDefaultDoctorDeps(): DoctorDeps;
63
+ export declare function createDefaultFixActuators(): FixActuators;