@cortex-agent/server 2026.5.19-3 → 2026.5.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/README.md +5 -1
  2. package/defaults/config/thread-templates.json +65 -39
  3. package/defaults/plugins/cortex-system/skills/schedule/SKILL.md +4 -4
  4. package/defaults/prompts/directives/coder-reviewer.md +9 -4
  5. package/defaults/prompts/directives/coder.md +10 -2
  6. package/dist/core/log.js +61 -12
  7. package/dist/core/status-format.js +1 -1
  8. package/dist/core/task-parser.d.ts +1 -1
  9. package/dist/core/task-parser.js +13 -6
  10. package/dist/core/types/thread-types.d.ts +4 -2
  11. package/dist/domain/costs/codex-usage-monitor.d.ts +1 -2
  12. package/dist/domain/costs/codex-usage-monitor.js +2 -2
  13. package/dist/domain/costs/cost-tracker.d.ts +2 -0
  14. package/dist/domain/costs/cost-tracker.js +4 -20
  15. package/dist/domain/costs/rate-limit-throttle.js +1 -4
  16. package/dist/domain/mcp/tools/context.d.ts +4 -2
  17. package/dist/domain/mcp/tools/context.js +7 -5
  18. package/dist/domain/mcp/tools/schedule.d.ts +1 -1
  19. package/dist/domain/mcp/tools/schedule.js +24 -20
  20. package/dist/domain/memory/index-regen.js +8 -5
  21. package/dist/domain/monitor/disk-monitor.js +1 -6
  22. package/dist/domain/projects/index.d.ts +2 -0
  23. package/dist/domain/projects/index.js +3 -0
  24. package/dist/domain/projects/project-store.d.ts +54 -0
  25. package/dist/domain/projects/project-store.js +194 -0
  26. package/dist/domain/projects/project-types.d.ts +11 -0
  27. package/dist/domain/projects/project-types.js +5 -0
  28. package/dist/domain/remote/client-hot-reload.d.ts +1 -0
  29. package/dist/domain/remote/client-hot-reload.js +284 -53
  30. package/dist/domain/scheduling/jobs/_shared.d.ts +1 -1
  31. package/dist/domain/scheduling/jobs/_shared.js +6 -5
  32. package/dist/domain/scheduling/jobs/memory-index-regen.js +2 -2
  33. package/dist/domain/scheduling/jobs/scheduled-task.d.ts +2 -2
  34. package/dist/domain/scheduling/jobs/scheduled-task.js +38 -36
  35. package/dist/domain/scheduling/jobs/sync-public.d.ts +1 -0
  36. package/dist/domain/scheduling/jobs/sync-public.js +34 -0
  37. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +3 -7
  38. package/dist/domain/scheduling/jobs/target-dispatch.js +7 -9
  39. package/dist/domain/scheduling/jobs/task-archive.js +2 -2
  40. package/dist/domain/scheduling/jobs/task-dispatch.js +18 -16
  41. package/dist/domain/scheduling/runner.d.ts +1 -0
  42. package/dist/domain/scheduling/runner.js +2 -0
  43. package/dist/domain/scheduling/schedule-cli.d.ts +1 -0
  44. package/dist/domain/scheduling/schedule-cli.js +14 -14
  45. package/dist/domain/scheduling/schedule-command.js +45 -36
  46. package/dist/domain/scheduling/scheduler.d.ts +1 -1
  47. package/dist/domain/scheduling/scheduler.js +12 -11
  48. package/dist/domain/sessions/session-hooks.d.ts +10 -11
  49. package/dist/domain/sessions/session-hooks.js +26 -27
  50. package/dist/domain/sessions/session-registry.d.ts +10 -5
  51. package/dist/domain/sessions/session-registry.js +24 -9
  52. package/dist/domain/tasks/pending-tracker.js +8 -9
  53. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  54. package/dist/domain/tasks/system/task-cli.js +189 -29
  55. package/dist/domain/tasks/system/task-lifecycle-edit.js +3 -3
  56. package/dist/domain/threads/hook-runner.js +12 -7
  57. package/dist/domain/threads/runner.d.ts +3 -3
  58. package/dist/domain/threads/runner.js +30 -28
  59. package/dist/domain/threads/state-machine.d.ts +3 -0
  60. package/dist/domain/threads/state-machine.js +4 -0
  61. package/dist/entry/app.js +30 -9
  62. package/dist/entry/cli.js +19 -4
  63. package/dist/entry/daemon.js +28 -2
  64. package/dist/entry/startup-notify.js +8 -6
  65. package/dist/orchestration/agent-runner.js +19 -13
  66. package/dist/orchestration/durable-helpers.js +3 -2
  67. package/dist/orchestration/interactions/ask-user-question.d.ts +2 -3
  68. package/dist/orchestration/interactions/ask-user-question.js +5 -4
  69. package/dist/orchestration/interactions/interaction-handlers.js +8 -5
  70. package/dist/orchestration/interactions/plan-handler.js +3 -3
  71. package/dist/orchestration/lifecycle.js +43 -38
  72. package/dist/orchestration/routing/commands/cancel.js +9 -8
  73. package/dist/orchestration/routing/commands/channel.js +32 -26
  74. package/dist/orchestration/routing/commands/cost.js +5 -3
  75. package/dist/orchestration/routing/commands/device.js +2 -1
  76. package/dist/orchestration/routing/commands/dispatch.js +8 -7
  77. package/dist/orchestration/routing/commands/index.js +7 -4
  78. package/dist/orchestration/routing/commands/mode.js +24 -18
  79. package/dist/orchestration/routing/commands/nvtop.js +14 -12
  80. package/dist/orchestration/routing/commands/orient.js +2 -1
  81. package/dist/orchestration/routing/commands/schedule.js +2 -1
  82. package/dist/orchestration/routing/commands/sendfile.js +12 -9
  83. package/dist/orchestration/routing/commands/session.js +12 -10
  84. package/dist/orchestration/routing/commands/status.js +2 -2
  85. package/dist/orchestration/routing/commands/tail.js +10 -6
  86. package/dist/orchestration/routing/commands/task.js +5 -4
  87. package/dist/orchestration/routing/commands/thread-handlers.js +19 -12
  88. package/dist/orchestration/routing/hook-bridge-subscribers.js +15 -13
  89. package/dist/orchestration/status-helpers.d.ts +4 -5
  90. package/dist/orchestration/status-helpers.js +7 -8
  91. package/dist/orchestration/thread-executor.js +21 -12
  92. package/dist/platform/adapter.d.ts +13 -9
  93. package/dist/platform/adapter.js +1 -1
  94. package/dist/platform/adapters/feishu-output-stream.d.ts +27 -0
  95. package/dist/platform/adapters/feishu-output-stream.js +114 -0
  96. package/dist/platform/adapters/feishu.d.ts +16 -7
  97. package/dist/platform/adapters/feishu.js +64 -18
  98. package/dist/platform/adapters/index.d.ts +4 -1
  99. package/dist/platform/adapters/index.js +1 -1
  100. package/dist/platform/adapters/slack-output-stream.d.ts +55 -0
  101. package/dist/platform/{virtual-message.js → adapters/slack-output-stream.js} +98 -165
  102. package/dist/platform/adapters/slack-project-conduits.d.ts +9 -0
  103. package/dist/platform/adapters/slack-project-conduits.js +40 -0
  104. package/dist/platform/adapters/slack.d.ts +18 -8
  105. package/dist/platform/adapters/slack.js +82 -24
  106. package/dist/platform/index.d.ts +3 -2
  107. package/dist/platform/index.js +1 -1
  108. package/dist/platform/output-stream-chunk.d.ts +6 -0
  109. package/dist/platform/output-stream-chunk.js +45 -0
  110. package/dist/platform/output-stream-helpers.d.ts +6 -0
  111. package/dist/platform/output-stream-helpers.js +11 -0
  112. package/dist/platform/output-stream.d.ts +28 -0
  113. package/dist/platform/output-stream.js +4 -0
  114. package/dist/platform/testing.d.ts +41 -8
  115. package/dist/platform/testing.js +93 -11
  116. package/dist/platform/tool-trace.d.ts +9 -8
  117. package/dist/platform/tool-trace.js +19 -17
  118. package/dist/platform/types.d.ts +21 -1
  119. package/dist/platform/types.js +17 -1
  120. package/dist/store/channel-repo.d.ts +6 -0
  121. package/dist/store/channel-repo.js +9 -0
  122. package/dist/store/json-repository.js +12 -1
  123. package/dist/store/outbound-queue.d.ts +5 -4
  124. package/dist/store/outbound-queue.js +9 -6
  125. package/dist/store/schedule-repo.d.ts +9 -5
  126. package/dist/store/schedule-repo.js +59 -14
  127. package/dist/store/session-registry-repo.d.ts +36 -7
  128. package/dist/store/session-registry-repo.js +186 -25
  129. package/dist/store/thread-repo.d.ts +1 -0
  130. package/dist/store/thread-repo.js +8 -0
  131. package/package.json +1 -1
  132. package/dist/platform/virtual-message.d.ts +0 -68
@@ -17,20 +17,21 @@ export function registerHookBridgeSubscribers(bus, adapter, planApprovals) {
17
17
  try {
18
18
  const group = askUserQuestion.createHookGroup(ev.requestId, ev.channel, ev.sessionId, ev.questions, ev.extensionUiId, ev.threadId ?? null);
19
19
  askUserQuestion.registerHookResolver(ev.requestId, (data) => resolveHookRequest(ev.requestId, data));
20
- // streamingCb is fetched only to extract the vm reference — not invoked directly for AskUser
20
+ // streamingCb is fetched only to extract the stream reference — not invoked directly for AskUser
21
21
  const streamingCb = getStreamingCallback(ev.channel);
22
- const vm = streamingCb?.vm;
22
+ const stream = streamingCb?.stream;
23
23
  const text = `Questions (${group.questions.length})`;
24
24
  const richBlocks = askUserQuestion.buildQuestionGroupBlocks(group);
25
- // Route through vm when available so standalone post flushes pending appends
26
- // and resets vm state — without this, messages emitted after the form would
25
+ // Route through stream when available so standalone post flushes pending appends
26
+ // and resets stream state — without this, messages emitted after the form would
27
27
  // be merged back into the message that preceded it.
28
- if (vm) {
29
- const ref = await vm.postStandalone(text, { richBlocks });
28
+ const askDest = { type: 'interactive-reply', conduit: ev.channel, sessionId: ev.sessionId ?? '' };
29
+ if (stream) {
30
+ const ref = await stream.postInteractive(text, { richBlocks });
30
31
  group.responseMessageTs = ref?.messageId || null;
31
32
  }
32
33
  else {
33
- const ref = await adapter.postMessage(ev.channel, { text, richBlocks });
34
+ const ref = await adapter.postMessage(askDest, { text, richBlocks });
34
35
  group.responseMessageTs = ref.messageId;
35
36
  }
36
37
  }
@@ -45,7 +46,8 @@ export function registerHookBridgeSubscribers(bus, adapter, planApprovals) {
45
46
  return; // smoke-test: event is journalled, skip Slack post + approval registration
46
47
  try {
47
48
  const streamingCb = getStreamingCallback(ev.channel);
48
- const vm = streamingCb?.vm;
49
+ const stream = streamingCb?.stream;
50
+ const planDest = { type: 'interactive-reply', conduit: ev.channel, sessionId: ev.sessionId ?? '' };
49
51
  if (streamingCb && ev.planContent) {
50
52
  streamingCb(ev.planContent);
51
53
  }
@@ -54,18 +56,18 @@ export function registerHookBridgeSubscribers(bus, adapter, planApprovals) {
54
56
  }
55
57
  planApprovals.register(ev.requestId, { channel: ev.channel, extensionUiId: ev.extensionUiId ?? null, threadId: ev.threadId ?? null });
56
58
  const planApproval = buildPlanApprovalContent(ev.requestId);
57
- // Route approval form through vm so it enqueues behind the plan content append,
58
- // ensuring Slack ordering (plan text first, then button card) and resetting vm
59
+ // Route approval form through stream so it enqueues behind the plan content append,
60
+ // ensuring Slack ordering (plan text first, then button card) and resetting stream
59
61
  // state so subsequent assistant output starts a fresh message instead of
60
62
  // merging back into the message that preceded the form.
61
- if (vm) {
62
- await vm.postStandalone('Plan approval', {
63
+ if (stream) {
64
+ await stream.postInteractive('Plan approval', {
63
65
  richBlocks: planApproval.richBlocks,
64
66
  actions: planApproval.actions,
65
67
  });
66
68
  }
67
69
  else {
68
- await adapter.postInteractive(ev.channel, {
70
+ await adapter.postInteractive(planDest, {
69
71
  text: 'Plan approval',
70
72
  ...planApproval,
71
73
  });
@@ -1,5 +1,4 @@
1
- import type { PlatformAdapter, MessageRef, IncomingAttachment, RichBlock } from '../platform/index.js';
2
- import { VirtualMessage } from '../platform/index.js';
1
+ import type { Destination, PlatformAdapter, MessageRef, IncomingAttachment, RichBlock, OutputStream } from '../platform/index.js';
3
2
  import type { AgentResult } from '../core/types/agent-types.js';
4
3
  import type { ExecutionRecord } from '../domain/executions/registry.js';
5
4
  export { computeElapsed, formatMetricsSuffix, buildSessionTag, buildUserProcessingMessage } from '../core/status-format.js';
@@ -33,9 +32,9 @@ export declare function runAutoCompoundForScheduledTask({ baseResult, channel, p
33
32
  trigger?: string;
34
33
  onAssistantMessage?: ((text: string) => void) | null;
35
34
  }): Promise<AgentResult>;
36
- /** Build a streaming callback that aggregates assistant messages into fewer platform messages via VirtualMessage. */
37
- export declare function makeStreamingMessageCallback(adapter: PlatformAdapter, channel: string, threadTs?: string | null, onMessagePosted?: ((ref: MessageRef) => void) | null, durable?: import('../platform/types.js').DurableHooks | null): ((text: string) => void) & {
38
- vm: VirtualMessage;
35
+ /** Build a streaming callback that aggregates assistant messages via OutputStream. */
36
+ export declare function makeStreamingMessageCallback(adapter: PlatformAdapter, destination: Destination, threadTs?: string | null, onMessagePosted?: ((ref: MessageRef) => void) | null, durable?: import('../platform/types.js').DurableHooks | null): ((text: string) => void) & {
37
+ stream: OutputStream;
39
38
  };
40
39
  /** Extract text content from forwarded messages (attachments marked isForwarded by the platform adapter). */
41
40
  export declare function extractForwardedContent(message: {
@@ -3,18 +3,17 @@
3
3
  // pos: Status message and execution helper functions collection
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  import { createLogger } from '../core/log.js';
6
- import { VirtualMessage } from '../platform/index.js';
7
6
  import * as executionRegistry from '../domain/executions/registry.js';
8
7
  import { runAgent } from '../domain/agents/index.js';
9
8
  import { shouldAutoRunCompound, combineFinalOutputs } from '../domain/threads/auto-thread.js';
10
- import { detectProject } from '../domain/costs/cost-tracker.js';
9
+ import { projectStore } from '../domain/projects/index.js';
11
10
  import { getOutboundQueue } from '../store/outbound-queue.js';
12
11
  import { durableUpdate } from './durable-helpers.js';
13
12
  // Pure formatters live in core/ so the domain layer can consume them without an orch dep.
14
13
  export { computeElapsed, formatMetricsSuffix, buildSessionTag, buildUserProcessingMessage } from '../core/status-format.js';
15
14
  const log = createLogger('status-helpers');
16
15
  export function resolveExecutionProject({ execution, fallbackMessage }) {
17
- return execution?.project || detectProject(fallbackMessage || '');
16
+ return execution?.project || (projectStore.resolveFromMessage(fallbackMessage || '')?.id ?? 'general');
18
17
  }
19
18
  export function buildExecutionStatusReport() {
20
19
  const running = executionRegistry.getRunningExecutions();
@@ -85,11 +84,11 @@ export async function runAutoCompoundForScheduledTask({ baseResult, channel, pro
85
84
  finalOutput: combineFinalOutputs(baseResult?.finalOutput, compoundResult?.finalOutput),
86
85
  };
87
86
  }
88
- /** Build a streaming callback that aggregates assistant messages into fewer platform messages via VirtualMessage. */
89
- export function makeStreamingMessageCallback(adapter, channel, threadTs = null, onMessagePosted = null, durable) {
90
- const vm = new VirtualMessage(adapter, channel, { threadId: threadTs, onMessagePosted, durable: durable ?? null });
91
- const callback = (text) => vm.append(text);
92
- callback.vm = vm;
87
+ /** Build a streaming callback that aggregates assistant messages via OutputStream. */
88
+ export function makeStreamingMessageCallback(adapter, destination, threadTs = null, onMessagePosted = null, durable) {
89
+ const stream = adapter.openOutputStream(destination, { threadId: threadTs, onMessagePosted, durable: durable ?? null });
90
+ const callback = (text) => stream.emitText(text);
91
+ callback.stream = stream;
93
92
  return callback;
94
93
  }
95
94
  /** Extract text content from forwarded messages (attachments marked isForwarded by the platform adapter). */
@@ -46,6 +46,7 @@ export class ThreadExecutor {
46
46
  }
47
47
  async _executeReal(ctx) {
48
48
  const { channel, adapter } = ctx;
49
+ const interactiveDest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
49
50
  const startTime = Date.now();
50
51
  let statusMsg;
51
52
  const downloadedFiles = await downloadFiles(ctx.message.files, ctx.hasFiles, ctx.adapter);
@@ -66,27 +67,27 @@ export class ThreadExecutor {
66
67
  const errorBlocksTemplate = { channel, sessionName: null, isDm: false };
67
68
  if (isCancelled) {
68
69
  if (statusMsg) {
69
- const cancelText = `:octagonal_sign: Cancelled (${elapsedStr}s)`;
70
+ const cancelText = `:octagonal_sign: Cancelled (${elapsedStr})`;
70
71
  await adapter.updateMessage(statusMsg, {
71
72
  text: cancelText,
72
73
  richBlocks: buildSealedStatusActionBlocks(cancelText, errorBlocksTemplate),
73
74
  }).catch(() => { });
74
75
  }
75
76
  else {
76
- await adapter.postMessage(channel, { text: ':octagonal_sign: Cancelled' }, ctx.threadTs ? { threadId: ctx.threadTs } : undefined).catch(() => { });
77
+ await adapter.postMessage(interactiveDest, { text: ':octagonal_sign: Cancelled' }, ctx.threadTs ? { threadId: ctx.threadTs } : undefined).catch(() => { });
77
78
  }
78
79
  }
79
80
  else {
80
81
  const errorMsg = error?.message || 'Unknown error';
81
82
  if (statusMsg) {
82
- const failText = `:x: Thread failed (${elapsedStr}s): ${errorMsg}`;
83
+ const failText = `:x: Thread failed (${elapsedStr}): ${errorMsg}`;
83
84
  await adapter.updateMessage(statusMsg, {
84
85
  text: failText,
85
86
  richBlocks: buildSealedStatusActionBlocks(failText, errorBlocksTemplate),
86
87
  }).catch(() => { });
87
88
  }
88
89
  else {
89
- await adapter.postMessage(channel, { text: `:x: Thread failed: ${errorMsg}` }, ctx.threadTs ? { threadId: ctx.threadTs } : undefined).catch(() => { });
90
+ await adapter.postMessage(interactiveDest, { text: `:x: Thread failed: ${errorMsg}` }, ctx.threadTs ? { threadId: ctx.threadTs } : undefined).catch(() => { });
90
91
  }
91
92
  }
92
93
  }
@@ -95,6 +96,7 @@ export class ThreadExecutor {
95
96
  export const threadExecutor = new ThreadExecutor();
96
97
  // --- Thread sub-handlers ---
97
98
  async function handleThreadAdd({ threadAddMatch, existingThread, channel, adapter, threadTs, startTime, downloadedFiles }) {
99
+ const interactiveDest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
98
100
  const addAgentName = threadAddMatch[1];
99
101
  const addMessage = threadAddMatch[2]?.trim() || null;
100
102
  const targetThread = await validateThreadAddTarget(addAgentName, existingThread, channel, adapter, threadTs);
@@ -104,7 +106,7 @@ async function handleThreadAdd({ threadAddMatch, existingThread, channel, adapte
104
106
  const platformThreadId = targetThread.platformThreadId || threadTs;
105
107
  const threadBlocksTemplate = { channel, sessionName: null, isDm: false, threadId: targetThread.id };
106
108
  const addText = `:heavy_plus_sign: Adding *${addAgentName}* to thread ${targetThread.id.substring(0, 12)}...`;
107
- const statusMsg = await adapter.postMessage(channel, {
109
+ const statusMsg = await adapter.postMessage(interactiveDest, {
108
110
  text: addText,
109
111
  richBlocks: buildStatusActionBlocks(addText, threadBlocksTemplate),
110
112
  }, platformThreadId ? { threadId: platformThreadId } : undefined);
@@ -112,6 +114,7 @@ async function handleThreadAdd({ threadAddMatch, existingThread, channel, adapte
112
114
  const interactiveCallbacks = buildInteractiveCallbacks(channel, null);
113
115
  const threadResult = await runThread(targetThread.id, {
114
116
  adapter, channel, threadTs: platformThreadId, statusMsg, startTime, existingSessionId: null, files: downloadedFiles,
117
+ destination: interactiveDest,
115
118
  onToolUse: interactiveCallbacks.onToolUse, onPlanWritten: interactiveCallbacks.onPlanWritten, onAskUserQuestion: interactiveCallbacks.onAskUserQuestion,
116
119
  });
117
120
  const summaryText = buildThreadSummary(threadResult);
@@ -122,25 +125,27 @@ async function handleThreadAdd({ threadAddMatch, existingThread, channel, adapte
122
125
  return statusMsg;
123
126
  }
124
127
  async function validateThreadAddTarget(addAgentName, existingThread, channel, adapter, threadTs) {
128
+ const interactiveDest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
125
129
  if (!getAgent(addAgentName)) {
126
- await adapter.postMessage(channel, { text: `:x: Unknown agent: \`${addAgentName}\`. Use \`!thread agents\` to see available agents.` }, threadTs ? { threadId: threadTs } : undefined);
130
+ await adapter.postMessage(interactiveDest, { text: `:x: Unknown agent: \`${addAgentName}\`. Use \`!thread agents\` to see available agents.` }, threadTs ? { threadId: threadTs } : undefined);
127
131
  return null;
128
132
  }
129
133
  const targetThread = existingThread || threadStore.findByChannel(channel).find((t) => t.status === 'completed' || t.status === 'waiting');
130
134
  if (!targetThread) {
131
- await adapter.postMessage(channel, { text: `:x: No thread found. Start one first with \`!thread <agent> <message>\`.` }, threadTs ? { threadId: threadTs } : undefined);
135
+ await adapter.postMessage(interactiveDest, { text: `:x: No thread found. Start one first with \`!thread <agent> <message>\`.` }, threadTs ? { threadId: threadTs } : undefined);
132
136
  return null;
133
137
  }
134
138
  if (targetThread.status === 'running' && getActiveHandle(channel)) {
135
- await adapter.postMessage(channel, { text: `:warning: Thread ${targetThread.id.substring(0, 12)} is currently running. Wait for it to finish.` }, threadTs ? { threadId: threadTs } : undefined);
139
+ await adapter.postMessage(interactiveDest, { text: `:warning: Thread ${targetThread.id.substring(0, 12)} is currently running. Wait for it to finish.` }, threadTs ? { threadId: threadTs } : undefined);
136
140
  return null;
137
141
  }
138
142
  return targetThread;
139
143
  }
140
144
  async function handleThreadContinue({ existingThread, agentMessage, channel, adapter, threadTs, startTime, downloadedFiles }) {
145
+ const interactiveDest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
141
146
  const continueBlocksTemplate = { channel, sessionName: null, isDm: false, threadId: existingThread.id };
142
147
  const continueText = `:hourglass_flowing_sand: Continuing thread ${existingThread.id.substring(0, 12)}...`;
143
- const statusMsg = await adapter.postMessage(channel, {
148
+ const statusMsg = await adapter.postMessage(interactiveDest, {
144
149
  text: continueText,
145
150
  richBlocks: buildStatusActionBlocks(continueText, continueBlocksTemplate),
146
151
  }, threadTs ? { threadId: threadTs } : undefined);
@@ -148,6 +153,7 @@ async function handleThreadContinue({ existingThread, agentMessage, channel, ada
148
153
  const interactiveCallbacks = buildInteractiveCallbacks(channel, null);
149
154
  const threadResult = await continueThread(existingThread.id, agentMessage, {
150
155
  adapter, channel, threadTs, statusMsg, startTime, existingSessionId: null, files: downloadedFiles,
156
+ destination: interactiveDest,
151
157
  onToolUse: interactiveCallbacks.onToolUse, onPlanWritten: interactiveCallbacks.onPlanWritten, onAskUserQuestion: interactiveCallbacks.onAskUserQuestion,
152
158
  });
153
159
  const continueSummaryText = buildThreadSummary(threadResult);
@@ -158,16 +164,17 @@ async function handleThreadContinue({ existingThread, agentMessage, channel, ada
158
164
  return statusMsg;
159
165
  }
160
166
  async function handleThreadStart({ threadStartMatch, messageId, channel, adapter, threadTs, startTime, downloadedFiles }) {
167
+ const interactiveDest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
161
168
  const name = threadStartMatch[1];
162
169
  const template = getTemplate(name);
163
170
  const agent = getAgent(name);
164
171
  if (!template && !agent) {
165
- await adapter.postMessage(channel, { text: `:x: Unknown template or agent: \`${name}\`. Use \`!thread templates\` or \`!thread agents\`.` });
172
+ await adapter.postMessage(interactiveDest, { text: `:x: Unknown template or agent: \`${name}\`. Use \`!thread templates\` or \`!thread agents\`.` });
166
173
  return null;
167
174
  }
168
175
  const startBlocksTemplate = { channel, sessionName: null, isDm: false };
169
176
  const startText = `:hourglass_flowing_sand: Starting thread (${template ? name : `agent:${name}`})...`;
170
- const statusMsg = await adapter.postMessage(channel, {
177
+ const statusMsg = await adapter.postMessage(interactiveDest, {
171
178
  text: startText,
172
179
  // No Cancel button initially — threadId needed first
173
180
  }, threadTs ? { threadId: threadTs } : undefined);
@@ -186,6 +193,7 @@ async function handleThreadStart({ threadStartMatch, messageId, channel, adapter
186
193
  const interactiveCallbacks = buildInteractiveCallbacks(channel, null);
187
194
  const threadResult = await runThread(thread.id, {
188
195
  adapter, channel, threadTs: platformThreadId, statusMsg, startTime, existingSessionId: null, files: downloadedFiles,
196
+ destination: interactiveDest,
189
197
  onToolUse: interactiveCallbacks.onToolUse, onPlanWritten: interactiveCallbacks.onPlanWritten, onAskUserQuestion: interactiveCallbacks.onAskUserQuestion,
190
198
  });
191
199
  const startSummaryText = buildThreadSummary(threadResult);
@@ -201,6 +209,7 @@ async function handleThreadStart({ threadStartMatch, messageId, channel, adapter
201
209
  * and we can't safely call continueThread + runThread concurrently. */
202
210
  async function bufferUserMessage(ctx) {
203
211
  const { adapter, channel, threadTs } = ctx;
212
+ const interactiveDest = { type: 'interactive-reply', conduit: channel, sessionId: '' };
204
213
  const thread = ctx.existingThread;
205
214
  const text = ctx.agentMessage || ctx.message.text || '';
206
215
  // Synchronously append to in-memory metadata so the next buildStepPrompt
@@ -222,7 +231,7 @@ async function bufferUserMessage(ctx) {
222
231
  // dropped because the in-memory state is authoritative and will be persisted by
223
232
  // the next conventional mutate() call on this thread.
224
233
  threadStore.set(thread).catch(() => { });
225
- await adapter.postMessage(channel, {
234
+ await adapter.postMessage(interactiveDest, {
226
235
  text: ':inbox_tray: Message buffered — will be included in the next step’s prompt',
227
236
  }, threadTs ? { threadId: threadTs } : undefined);
228
237
  }
@@ -1,4 +1,5 @@
1
- import type { MessageRef, MessageContent, MessageContext, MessageEditContext, ActionContext, ModalSubmitContext, ModalDefinition, PlatformCapabilities, PlatformFileRef, DownloadedFile, PostMessageOpts, FileUploadOpts, ActionElement } from './types.js';
1
+ import type { MessageRef, MessageContent, MessageContext, MessageEditContext, ActionContext, ModalSubmitContext, ModalDefinition, PlatformCapabilities, PlatformFileRef, DownloadedFile, Destination, PostMessageOpts, FileUploadOpts, ActionElement } from './types.js';
2
+ import type { OutputStream, OpenOutputStreamOpts } from './output-stream.js';
2
3
  export interface PlatformAdapter {
3
4
  readonly name: string;
4
5
  readonly capabilities: PlatformCapabilities;
@@ -8,21 +9,24 @@ export interface PlatformAdapter {
8
9
  onMessageEdit(handler: (ctx: MessageEditContext) => Promise<void>): void;
9
10
  onAction(actionId: string, handler: (ctx: ActionContext) => Promise<void>): void;
10
11
  onModalSubmit(callbackId: string, handler: (ctx: ModalSubmitContext) => Promise<void>): void;
11
- postMessage(channel: string, content: MessageContent, opts?: PostMessageOpts): Promise<MessageRef>;
12
+ postMessage(destination: Destination, content: MessageContent, opts?: PostMessageOpts): Promise<MessageRef>;
12
13
  updateMessage(ref: MessageRef, content: MessageContent): Promise<void>;
13
14
  deleteMessage(ref: MessageRef): Promise<void>;
14
- postInteractive(channel: string, content: MessageContent & {
15
+ postInteractive(destination: Destination, content: MessageContent & {
15
16
  actions: ActionElement[];
16
17
  }, opts?: PostMessageOpts): Promise<MessageRef>;
17
18
  openModal(triggerId: string, modal: ModalDefinition): Promise<void>;
18
19
  addReaction(ref: MessageRef, emoji: string): Promise<void>;
19
- uploadFile(channel: string, filePath: string, opts?: FileUploadOpts): Promise<void>;
20
+ uploadFile(destination: Destination, filePath: string, opts?: FileUploadOpts): Promise<void>;
20
21
  downloadFile(fileRef: PlatformFileRef, destDir: string): Promise<DownloadedFile>;
21
22
  getPermalink(ref: MessageRef): Promise<string | null>;
22
23
  postEphemeral(channel: string, userId: string, text: string): Promise<void>;
23
- /** Platform-configured admin/notification channel (replaces hardcoded Slack DM ID). */
24
- getAdminChannel(): string | null;
25
- /** Access to the underlying platform client for edge cases during migration.
26
- * New code should avoid this — it exists to support incremental Phase 2 adoption. */
27
- getRawClient(): unknown;
24
+ /** Open a new OutputStream for streaming agent output to the given destination. */
25
+ openOutputStream(destination: Destination, opts?: OpenOutputStreamOpts): OutputStream;
26
+ /** Register a conduit (channel/chat) for project-report destinations. */
27
+ bindProjectConduit(projectId: string, conduitHint: string): Promise<void>;
28
+ /** Remove a conduit registration. */
29
+ unbindProjectConduit(projectId: string): Promise<void>;
30
+ /** Get all registered project→conduit mappings. */
31
+ getProjectConduits(): Promise<Record<string, string>>;
28
32
  }
@@ -1,5 +1,5 @@
1
1
  // input: ./types.js platform-agnostic message types
2
- // output: PlatformAdapter interface (17 methods)
2
+ // output: PlatformAdapter interface (21 methods: 17 core + openOutputStream + 3 conduit methods)
3
3
  // pos: Single abstraction boundary between core modules and messaging platform
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
5
  export {};
@@ -0,0 +1,27 @@
1
+ import type { FeishuAdapter } from './feishu.js';
2
+ import type { OutputStream, MutableRegion, OpenOutputStreamOpts } from '../output-stream.js';
3
+ import type { MessageRef, Destination, RichBlock, ActionElement } from '../types.js';
4
+ export declare class FeishuOutputStream implements OutputStream {
5
+ private adapter;
6
+ private destination;
7
+ private threadId;
8
+ private onMessagePosted;
9
+ private maxChunk;
10
+ private durable;
11
+ private parentRef;
12
+ private allRefs;
13
+ private queue;
14
+ private lastError;
15
+ constructor(adapter: FeishuAdapter, destination: Destination, opts?: OpenOutputStreamOpts);
16
+ emitText(text: string): void;
17
+ /** Feishu has no messageEdit — return a no-op MutableRegion. */
18
+ openMutable(_text: string): MutableRegion;
19
+ postInteractive(text: string, opts?: {
20
+ richBlocks?: RichBlock[];
21
+ actions?: ActionElement[];
22
+ }): Promise<MessageRef | null>;
23
+ flush(): Promise<void>;
24
+ getRefs(): MessageRef[];
25
+ getParentRef(): MessageRef | null;
26
+ private _postChunks;
27
+ }
@@ -0,0 +1,114 @@
1
+ // input: FeishuAdapter + output-stream interfaces
2
+ // output: FeishuOutputStream
3
+ // pos: Feishu-specific OutputStream — no messageEdit, no coalescing.
4
+ // Each emitText posts a new message; openMutable returns a no-op region.
5
+ // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
6
+ import { createLogger } from '../../core/log.js';
7
+ import { chunkText, DEFAULT_MAX_CHUNK } from '../output-stream-chunk.js';
8
+ const log = createLogger('feishu-output-stream');
9
+ export class FeishuOutputStream {
10
+ adapter;
11
+ destination;
12
+ threadId;
13
+ onMessagePosted;
14
+ maxChunk;
15
+ durable;
16
+ parentRef = null;
17
+ allRefs = [];
18
+ queue = Promise.resolve();
19
+ lastError = null;
20
+ constructor(adapter, destination, opts) {
21
+ this.adapter = adapter;
22
+ this.destination = destination;
23
+ this.threadId = opts?.threadId ?? null;
24
+ this.onMessagePosted = opts?.onMessagePosted ?? null;
25
+ this.durable = opts?.durable ?? null;
26
+ this.maxChunk = adapter.capabilities.maxMessageLength || DEFAULT_MAX_CHUNK;
27
+ }
28
+ emitText(text) {
29
+ if (!text?.trim())
30
+ return;
31
+ this.queue = this.queue.then(() => this._postChunks(text)).catch(e => {
32
+ log.error(`Queue error in emitText (len=${text.length}):`, e.message);
33
+ this.lastError = e instanceof Error ? e : new Error(String(e));
34
+ });
35
+ }
36
+ /** Feishu has no messageEdit — return a no-op MutableRegion. */
37
+ openMutable(_text) {
38
+ return { update: () => { } };
39
+ }
40
+ postInteractive(text, opts) {
41
+ const richBlocks = opts?.richBlocks;
42
+ const actions = opts?.actions;
43
+ return new Promise((resolve, reject) => {
44
+ this.queue = this.queue.then(async () => {
45
+ try {
46
+ const effectiveThreadId = this.threadId || this.parentRef?.messageId || undefined;
47
+ const ref = actions && actions.length > 0
48
+ ? await this.adapter.postInteractive(this.destination, { text, richBlocks, actions }, { threadId: effectiveThreadId })
49
+ : await this.adapter.postMessage(this.destination, { text, richBlocks }, { threadId: effectiveThreadId });
50
+ if (!this.parentRef && !this.threadId)
51
+ this.parentRef = ref;
52
+ this.allRefs.push(ref);
53
+ if (this.onMessagePosted)
54
+ this.onMessagePosted(ref);
55
+ resolve(ref);
56
+ }
57
+ catch (e) {
58
+ const err = e instanceof Error ? e : new Error(String(e));
59
+ log.error(`postInteractive failed:`, err.message);
60
+ this.lastError = err;
61
+ reject(err);
62
+ throw err;
63
+ }
64
+ }).catch(e => {
65
+ const err = e instanceof Error ? e : new Error(String(e));
66
+ this.lastError = err;
67
+ reject(err);
68
+ });
69
+ });
70
+ }
71
+ async flush() {
72
+ await this.queue.catch(() => { });
73
+ if (this.lastError) {
74
+ const err = this.lastError;
75
+ this.lastError = null;
76
+ throw err;
77
+ }
78
+ }
79
+ getRefs() {
80
+ return [...this.allRefs];
81
+ }
82
+ getParentRef() {
83
+ return this.parentRef;
84
+ }
85
+ async _postChunks(text) {
86
+ const chunks = chunkText(text, this.maxChunk);
87
+ for (let i = 0; i < chunks.length; i++) {
88
+ const chunk = chunks[i];
89
+ const effectiveThreadId = this.threadId || this.parentRef?.messageId || undefined;
90
+ let walId = null;
91
+ try {
92
+ walId = this.durable
93
+ ? await this.durable.beforePost(this.destination, chunk, { threadId: effectiveThreadId })
94
+ : null;
95
+ const ref = await this.adapter.postMessage(this.destination, { text: chunk }, { threadId: effectiveThreadId });
96
+ if (walId && this.durable) {
97
+ await this.durable.afterSent(walId, ref.messageId).catch(() => { });
98
+ }
99
+ if (!this.parentRef && !this.threadId && this.allRefs.length === 0 && i === 0) {
100
+ this.parentRef = ref;
101
+ }
102
+ this.allRefs.push(ref);
103
+ if (this.onMessagePosted)
104
+ this.onMessagePosted(ref);
105
+ }
106
+ catch (e) {
107
+ if (walId && this.durable?.onSendFailed) {
108
+ this.durable.onSendFailed(walId);
109
+ }
110
+ throw e;
111
+ }
112
+ }
113
+ }
114
+ }
@@ -1,6 +1,6 @@
1
- import * as lark from '@larksuiteoapi/node-sdk';
2
1
  import type { PlatformAdapter } from '../adapter.js';
3
- import type { MessageRef, MessageContent, MessageContext, MessageEditContext, ActionContext, ModalSubmitContext, ModalDefinition, PlatformCapabilities, PlatformFileRef, DownloadedFile, PostMessageOpts, FileUploadOpts, ActionElement } from '../types.js';
2
+ import type { MessageRef, MessageContent, MessageContext, MessageEditContext, ActionContext, ModalSubmitContext, ModalDefinition, PlatformCapabilities, PlatformFileRef, DownloadedFile, Destination, PostMessageOpts, FileUploadOpts, ActionElement } from '../types.js';
3
+ import type { OutputStream, OpenOutputStreamOpts } from '../output-stream.js';
4
4
  export interface FeishuAdapterConfig {
5
5
  appId: string;
6
6
  appSecret: string;
@@ -26,20 +26,29 @@ export declare class FeishuAdapter implements PlatformAdapter {
26
26
  onMessageEdit(_handler: (ctx: MessageEditContext) => Promise<void>): void;
27
27
  onAction(actionId: string, handler: (ctx: ActionContext) => Promise<void>): void;
28
28
  onModalSubmit(callbackId: string, handler: (ctx: ModalSubmitContext) => Promise<void>): void;
29
- postMessage(channel: string, content: MessageContent, opts?: PostMessageOpts): Promise<MessageRef>;
29
+ postMessage(destination: Destination, content: MessageContent, opts?: PostMessageOpts): Promise<MessageRef>;
30
30
  updateMessage(ref: MessageRef, content: MessageContent): Promise<void>;
31
31
  deleteMessage(ref: MessageRef): Promise<void>;
32
- postInteractive(channel: string, content: MessageContent & {
32
+ postInteractive(destination: Destination, content: MessageContent & {
33
33
  actions: ActionElement[];
34
34
  }, opts?: PostMessageOpts): Promise<MessageRef>;
35
35
  openModal(triggerId: string, modal: ModalDefinition): Promise<void>;
36
36
  addReaction(ref: MessageRef, emoji: string): Promise<void>;
37
- uploadFile(channel: string, filePath: string, opts?: FileUploadOpts): Promise<void>;
37
+ uploadFile(destination: Destination, filePath: string, opts?: FileUploadOpts): Promise<void>;
38
38
  downloadFile(fileRef: PlatformFileRef, destDir: string): Promise<DownloadedFile>;
39
39
  getPermalink(_ref: MessageRef): Promise<string | null>;
40
40
  postEphemeral(_channel: string, _userId: string, _text: string): Promise<void>;
41
- getAdminChannel(): string | null;
42
- getRawClient(): lark.Client;
41
+ openOutputStream(destination: Destination, opts?: OpenOutputStreamOpts): OutputStream;
42
+ private _feishuConduits;
43
+ bindProjectConduit(projectId: string, conduitHint: string): Promise<void>;
44
+ unbindProjectConduit(projectId: string): Promise<void>;
45
+ getProjectConduits(): Promise<Record<string, string>>;
46
+ /**
47
+ * Resolve a Destination to a concrete Feishu chat_id + kind label.
48
+ * Returns channel=null for destinations that should be silently dropped
49
+ * (unconfigured admin channel).
50
+ */
51
+ private resolveDestination;
43
52
  private handleIncomingMessage;
44
53
  private handleCardAction;
45
54
  private buildMessagePayload;