@cortex-agent/server 2026.5.19 → 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 +188 -0
  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 +15 -8
  132. package/dist/platform/virtual-message.d.ts +0 -68
@@ -1,16 +1,13 @@
1
- // input: PlatformAdapter, MessageRef/RichBlock/ActionElement
2
- // output: VirtualMessage class + append/flush/postStandalone/mutableTail
3
- // pos: Platform-independent continuous message aggregator
1
+ // input: SlackAdapter + output-stream interfaces
2
+ // output: SlackOutputStream — coalescing OutputStream for Slack
3
+ // pos: Slack-specific OutputStream — coalesces segments, uses pendingEdits
4
+ // for chat.update coalescing and rate-limiter sharing.
4
5
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
- import { createLogger } from '../core/log.js';
6
- const log = createLogger('virtual-message');
6
+ import { createLogger } from '../../core/log.js';
7
+ import { needsSplit, chunkText, DEFAULT_MAX_CHUNK } from '../output-stream-chunk.js';
8
+ const log = createLogger('slack-output-stream');
7
9
  const SEPARATOR = '\n';
8
10
  const TAIL_SEPARATOR = '\n';
9
- const DEFAULT_MAX_CHUNK = 3000;
10
- const MAX_HORIZONTAL_RULES = 3;
11
- // Retry delays for transient adapter failures (Slack rate-limits typically last
12
- // 1–5s). Total wall time across all retries: ~6.3s, comfortably under the
13
- // caller-side timeouts but long enough to ride out a typical rate-limit.
14
11
  const DEFAULT_RETRY_DELAYS_MS = [200, 600, 1500, 4000];
15
12
  let retryDelaysMs = DEFAULT_RETRY_DELAYS_MS;
16
13
  function sleep(ms) {
@@ -48,109 +45,83 @@ export function _testSetRetryDelays(delays) {
48
45
  export function _testResetRetryDelays() {
49
46
  retryDelaysMs = DEFAULT_RETRY_DELAYS_MS;
50
47
  }
51
- function countHorizontalRules(text) {
52
- return text.split('\n').filter(line => /^-{3,}\s*$/.test(line.trim())).length;
53
- }
54
- function countTables(text) {
55
- const lines = text.split('\n');
56
- let count = 0;
57
- let inTable = false;
58
- for (const line of lines) {
59
- const isTableLine = /^\s*\|/.test(line);
60
- if (isTableLine && !inTable) {
61
- count++;
62
- inTable = true;
63
- }
64
- else if (!isTableLine) {
65
- inTable = false;
66
- }
48
+ /**
49
+ * A MutableRegion handle tied to a SlackOutputStream.
50
+ * Stale after the stream opens a new region or emits committed text.
51
+ */
52
+ class SlackMutableRegion {
53
+ _stream;
54
+ _generation;
55
+ constructor(stream, generation) {
56
+ this._stream = stream;
57
+ this._generation = generation;
67
58
  }
68
- return count;
69
- }
70
- function needsSplit(text, maxChunk) {
71
- return countTables(text) > 1
72
- || text.length > maxChunk
73
- || countHorizontalRules(text) >= MAX_HORIZONTAL_RULES;
74
- }
75
- function chunkText(text, maxChunk) {
76
- if (text.length <= maxChunk)
77
- return [text];
78
- const chunks = [];
79
- let remaining = text;
80
- while (remaining.length > maxChunk) {
81
- let splitAt = remaining.lastIndexOf('\n', maxChunk);
82
- if (splitAt <= 0)
83
- splitAt = maxChunk;
84
- chunks.push(remaining.substring(0, splitAt));
85
- remaining = remaining.substring(splitAt).replace(/^\n/, '');
59
+ update(text) {
60
+ if (!text?.trim())
61
+ return;
62
+ this._stream._regionUpdate(this._generation, text);
86
63
  }
87
- if (remaining)
88
- chunks.push(remaining);
89
- return chunks;
90
64
  }
91
- export class VirtualMessage {
65
+ export class SlackOutputStream {
92
66
  adapter;
93
- channel;
67
+ destination;
94
68
  threadId;
95
69
  onMessagePosted;
96
70
  maxChunk;
97
71
  durable;
72
+ /** Readable label for log messages, extracted from the Destination kind. */
73
+ get _logChannel() {
74
+ if (this.destination.type === 'interactive-reply')
75
+ return this.destination.conduit;
76
+ if (this.destination.type === 'project-report')
77
+ return this.destination.projectId;
78
+ return 'system-notice';
79
+ }
98
80
  parentRef = null;
99
81
  currentRef = null;
100
82
  currentContent = '';
101
83
  // Unsealed tail text on the current Slack message. Slack displays
102
84
  // `currentContent + SEPARATOR + mutableTail`. Empty string means no tail open.
103
- // appendMutableTail opens/rotates; editMutableTail replaces; any append() or
104
- // postStandalone() auto-seals by folding mutableTail into currentContent.
85
+ // openMutable opens/rotates; MutableRegion.update replaces;
86
+ // emitText or postInteractive auto-seals by folding mutableTail into currentContent.
105
87
  mutableTail = '';
106
88
  allRefs = [];
107
89
  queue = Promise.resolve();
108
- // Last error from a queued operation. flush() throws and clears this so
109
- // callers can detect that some messages did not reach the platform.
110
90
  lastError = null;
111
- constructor(adapter, channel, opts) {
91
+ /** Generation counter for MutableRegion staleness tracking.
92
+ * Incremented every time openMutable is called or a seal event occurs. */
93
+ _regionGeneration = 0;
94
+ constructor(adapter, destination, opts) {
112
95
  this.adapter = adapter;
113
- this.channel = channel;
96
+ this.destination = destination;
114
97
  this.threadId = opts?.threadId ?? null;
115
98
  this.onMessagePosted = opts?.onMessagePosted ?? null;
116
99
  this.durable = opts?.durable ?? null;
117
100
  this.maxChunk = adapter.capabilities.maxMessageLength || DEFAULT_MAX_CHUNK;
118
101
  }
119
- append(text) {
102
+ emitText(text) {
120
103
  if (!text?.trim())
121
104
  return;
105
+ ++this._regionGeneration; // seal any open mutable region synchronously
122
106
  this.queue = this.queue.then(() => this._processAppend(text)).catch(e => {
123
- // Record the failure so flush() can surface it; swallow here so subsequent
124
- // appends still get a chance to run instead of a poisoned queue.
125
- log.error(`Queue error in channel ${this.channel} (text len=${text.length}):`, e.message);
126
- this.lastError = e instanceof Error ? e : new Error(String(e));
127
- });
128
- }
129
- /** Append `text` as a new mutable tail on the current Slack message.
130
- * Seals any existing mutable tail into `currentContent` first, then writes
131
- * the new tail via updateMessage (or postMessage if no message yet).
132
- * Use this for "start a new tool group" or any ephemeral trailing line. */
133
- appendMutableTail(text) {
134
- if (!text?.trim())
135
- return;
136
- this.queue = this.queue.then(() => this._processAppendMutableTail(text)).catch(e => {
137
- log.error(`Queue error in appendMutableTail (channel ${this.channel}, len=${text.length}):`, e.message);
107
+ log.error(`Queue error in channel ${this._logChannel} (text len=${text.length}):`, e.message);
138
108
  this.lastError = e instanceof Error ? e : new Error(String(e));
139
109
  });
140
110
  }
141
- /** Replace the current mutable tail with `text`. No-op if no tail is open
142
- * (use appendMutableTail to open one). Use this for "update same tool group". */
143
- editMutableTail(text) {
111
+ openMutable(text) {
144
112
  if (!text?.trim())
145
- return;
146
- this.queue = this.queue.then(() => this._processEditMutableTail(text)).catch(e => {
147
- log.error(`Queue error in editMutableTail (channel ${this.channel}, len=${text.length}):`, e.message);
113
+ return this._noopRegion();
114
+ const generation = ++this._regionGeneration;
115
+ this.queue = this.queue.then(() => this._processOpenMutable(text)).catch(e => {
116
+ log.error(`Queue error in openMutable (channel ${this._logChannel}, len=${text.length}):`, e.message);
148
117
  this.lastError = e instanceof Error ? e : new Error(String(e));
149
118
  });
119
+ return new SlackMutableRegion(this, generation);
150
120
  }
151
- postStandalone(text, opts) {
121
+ postInteractive(text, opts) {
152
122
  const richBlocks = opts?.richBlocks;
153
123
  const actions = opts?.actions;
124
+ ++this._regionGeneration; // seal any open mutable region synchronously
154
125
  return new Promise((resolve, reject) => {
155
126
  this.queue = this.queue.then(async () => {
156
127
  this.currentRef = null;
@@ -160,20 +131,20 @@ export class VirtualMessage {
160
131
  let walId = null;
161
132
  try {
162
133
  walId = this.durable
163
- ? await this.durable.beforePost(this.channel, text, { threadId: effectiveThreadId, richBlocks })
134
+ ? await this.durable.beforePost(this.destination, text, { threadId: effectiveThreadId, richBlocks })
164
135
  : null;
165
136
  const ref = await withRetries(async () => {
166
137
  return actions && actions.length > 0
167
- ? await this.adapter.postInteractive(this.channel, {
138
+ ? await this.adapter.postInteractive(this.destination, {
168
139
  text,
169
140
  richBlocks,
170
141
  actions,
171
142
  }, { threadId: effectiveThreadId })
172
- : await this.adapter.postMessage(this.channel, {
143
+ : await this.adapter.postMessage(this.destination, {
173
144
  text,
174
145
  richBlocks,
175
146
  }, { threadId: effectiveThreadId });
176
- }, 'postStandalone');
147
+ }, 'postInteractive');
177
148
  if (walId && this.durable) {
178
149
  await this.durable.afterSent(walId, ref.messageId).catch(e => {
179
150
  log.warn(`afterSent failed for walId=${walId}:`, e.message);
@@ -191,13 +162,12 @@ export class VirtualMessage {
191
162
  this.durable.onSendFailed(walId);
192
163
  }
193
164
  const err = e instanceof Error ? e : new Error(String(e));
194
- log.error(`Standalone post failed after retries in channel ${this.channel}:`, err.message);
165
+ log.error(`postInteractive failed after retries in channel ${this._logChannel}:`, err.message);
195
166
  this.lastError = err;
196
167
  reject(err);
197
- throw err; // also propagate so flush() sees it
168
+ throw err;
198
169
  }
199
170
  }).catch(e => {
200
- // Upstream queue error; surface it to the caller too.
201
171
  const err = e instanceof Error ? e : new Error(String(e));
202
172
  this.lastError = err;
203
173
  reject(err);
@@ -212,26 +182,28 @@ export class VirtualMessage {
212
182
  throw err;
213
183
  }
214
184
  }
215
- static async postOnce(adapter, channel, text, opts) {
216
- const vm = new VirtualMessage(adapter, channel, opts);
217
- vm.append(text);
218
- await vm.flush();
219
- return vm.getParentRef();
220
- }
221
185
  getRefs() {
222
186
  return [...this.allRefs];
223
187
  }
224
188
  getParentRef() {
225
189
  return this.parentRef;
226
190
  }
227
- /** Compatibility: return parentRef's messageId (maps to Slack's ts). */
228
- getParentTs() {
229
- return this.parentRef?.messageId ?? null;
191
+ // --- Internal: MutableRegion staleness ---
192
+ /** Called by SlackMutableRegion.update(). No-op if the generation is stale. */
193
+ _regionUpdate(generation, text) {
194
+ if (generation !== this._regionGeneration)
195
+ return; // stale region — no-op
196
+ this.queue = this.queue.then(() => this._processEditMutableTail(text)).catch(e => {
197
+ log.error(`Queue error in _regionUpdate (channel ${this._logChannel}, len=${text.length}):`, e.message);
198
+ this.lastError = e instanceof Error ? e : new Error(String(e));
199
+ });
200
+ }
201
+ /** Return a no-op region for empty text. */
202
+ _noopRegion() {
203
+ return { update: () => { } };
230
204
  }
205
+ // --- Internal: queue processors ---
231
206
  async _processAppend(text) {
232
- // Seal any open mutable tail into committed content first — plain append()
233
- // is a hard break for tools/trace. After this, mutableTail is empty and
234
- // currentContent includes what Slack already displays as the sealed prefix.
235
207
  this._sealMutableTailNow();
236
208
  if (this.currentRef === null) {
237
209
  await this._postNew(text);
@@ -242,62 +214,28 @@ export class VirtualMessage {
242
214
  await this._postNew(text);
243
215
  return;
244
216
  }
245
- // Only commit currentContent AFTER the update succeeds. If we mutate
246
- // currentContent before the await and the update fails, the next append
247
- // that triggers needsSplit would call _postNew(text) with only the new
248
- // text — silently dropping `text` from anywhere in Slack.
249
217
  const updateResult = await this._updateCurrent(combined);
250
218
  if (updateResult.delivered) {
251
219
  this.currentContent = combined;
252
220
  }
253
221
  else {
254
- // Update permanently failed (after retries). Don't lose `text` — fall
255
- // back to posting it as a new message so it remains visible to the user.
256
- // If THIS also fails, _postNew throws and the queue catch records lastError.
257
- log.error(`Update permanently failed in channel ${this.channel}; falling back to new post`);
222
+ log.error(`Update permanently failed in channel ${this._logChannel}; falling back to new post`);
258
223
  await this._postNew(text);
259
- // After fallback post succeeds, mark the stale update's WAL entry as
260
- // delivered so the drain loop doesn't retry it against the old message
261
- // (which would duplicate content already shown in the new message).
262
224
  if (updateResult.walId) {
263
225
  await this.durable?.afterSent(updateResult.walId).catch(() => { });
264
226
  }
265
227
  }
266
228
  }
267
- /** Combined display = currentContent [+ SEP + mutableTail]. */
268
- _renderWithTail(tail) {
269
- if (!this.currentContent)
270
- return tail;
271
- if (!tail)
272
- return this.currentContent;
273
- return this.currentContent + TAIL_SEPARATOR + tail;
274
- }
275
- /** Synchronously move mutableTail into currentContent. Slack state is
276
- * already up-to-date with the tail displayed; this is pure bookkeeping. */
277
- _sealMutableTailNow() {
278
- if (!this.mutableTail)
279
- return;
280
- this.currentContent = this.currentContent
281
- ? this.currentContent + TAIL_SEPARATOR + this.mutableTail
282
- : this.mutableTail;
283
- this.mutableTail = '';
284
- }
285
- async _processAppendMutableTail(text) {
286
- // Seal any existing tail first, then open a fresh one containing `text`.
229
+ async _processOpenMutable(text) {
287
230
  this._sealMutableTailNow();
288
231
  const combined = this._renderWithTail(text);
289
232
  if (this.currentRef === null) {
290
233
  await this._postNew(combined);
291
- // _postNew leaves currentContent = combined (the whole blob). We want
292
- // committed='' tail=text since the whole freshly-posted blob is, in
293
- // fact, just the tail (currentContent was empty).
294
234
  this.currentContent = '';
295
235
  this.mutableTail = text;
296
236
  return;
297
237
  }
298
238
  if (needsSplit(combined, this.maxChunk)) {
299
- // Too long — commit everything that was already on screen, start a fresh
300
- // message whose content is just the new tail.
301
239
  await this._postNew(text);
302
240
  this.currentContent = '';
303
241
  this.mutableTail = text;
@@ -308,7 +246,7 @@ export class VirtualMessage {
308
246
  this.mutableTail = text;
309
247
  }
310
248
  else {
311
- log.error(`Update failed in appendMutableTail (channel ${this.channel}); falling back to new post`);
249
+ log.error(`Update failed in openMutable (channel ${this._logChannel}); falling back to new post`);
312
250
  await this._postNew(text);
313
251
  this.currentContent = '';
314
252
  this.mutableTail = text;
@@ -319,19 +257,15 @@ export class VirtualMessage {
319
257
  }
320
258
  async _processEditMutableTail(text) {
321
259
  if (!this.mutableTail)
322
- return; // nothing to edit; caller must appendMutableTail first
260
+ return;
323
261
  const combined = this._renderWithTail(text);
324
262
  if (this.currentRef === null) {
325
- // Shouldn't happen if a tail is open (tail implies a message exists),
326
- // but handle defensively: fall back to opening a fresh one.
327
263
  await this._postNew(combined);
328
264
  this.currentContent = '';
329
265
  this.mutableTail = text;
330
266
  return;
331
267
  }
332
268
  if (needsSplit(combined, this.maxChunk)) {
333
- // Overflow during same-group update — commit the old tail into content,
334
- // then open a fresh message carrying the new (larger) tail text.
335
269
  this._sealMutableTailNow();
336
270
  await this._postNew(text);
337
271
  this.currentContent = '';
@@ -343,7 +277,7 @@ export class VirtualMessage {
343
277
  this.mutableTail = text;
344
278
  }
345
279
  else {
346
- log.error(`Update failed in editMutableTail (channel ${this.channel}); falling back to new post`);
280
+ log.error(`Update failed in mutable-tail edit (channel ${this._logChannel}); falling back to new post`);
347
281
  this._sealMutableTailNow();
348
282
  await this._postNew(text);
349
283
  this.currentContent = '';
@@ -353,15 +287,28 @@ export class VirtualMessage {
353
287
  }
354
288
  }
355
289
  }
290
+ /** Combined display = currentContent [+ SEP + mutableTail]. */
291
+ _renderWithTail(tail) {
292
+ if (!this.currentContent)
293
+ return tail;
294
+ if (!tail)
295
+ return this.currentContent;
296
+ return this.currentContent + TAIL_SEPARATOR + tail;
297
+ }
298
+ /** Synchronously move mutableTail into currentContent. */
299
+ _sealMutableTailNow() {
300
+ if (!this.mutableTail)
301
+ return;
302
+ this.currentContent = this.currentContent
303
+ ? this.currentContent + TAIL_SEPARATOR + this.mutableTail
304
+ : this.mutableTail;
305
+ this.mutableTail = '';
306
+ }
356
307
  async _postNew(text) {
357
308
  const chunks = chunkText(text, this.maxChunk);
358
309
  let lastChunkSentIndex = -1;
359
310
  for (let i = 0; i < chunks.length; i++) {
360
311
  const chunk = chunks[i];
361
- // After chunk[0] succeeds, parentRef is set, so subsequent chunks go to
362
- // the thread automatically. If chunk[0] fails permanently, we abort the
363
- // remaining chunks — they would otherwise be posted as orphan top-level
364
- // messages without context.
365
312
  let effectiveThreadId;
366
313
  if (this.threadId) {
367
314
  effectiveThreadId = this.threadId;
@@ -370,8 +317,7 @@ export class VirtualMessage {
370
317
  effectiveThreadId = undefined;
371
318
  }
372
319
  else if (this.parentRef === null) {
373
- // chunk[0] failed and we have no parent — don't orphan subsequent chunks.
374
- throw new Error(`[virtual-message] aborting chunk ${i} — chunk 0 failed to post and would orphan subsequent chunks`);
320
+ throw new Error(`[slack-output-stream] aborting chunk ${i} — chunk 0 failed to post and would orphan subsequent chunks`);
375
321
  }
376
322
  else {
377
323
  effectiveThreadId = this.parentRef.messageId;
@@ -390,26 +336,21 @@ export class VirtualMessage {
390
336
  this.currentContent = chunks[lastChunkSentIndex];
391
337
  }
392
338
  }
393
- /**
394
- * Post a single chunk with rich-text + plain-text fallback wrapped in
395
- * exponential-backoff retries. Throws on permanent failure (after retries).
396
- * When durable hooks are configured, persists intent to WAL before sending.
397
- */
398
339
  async _postOne(chunk, threadId) {
399
340
  const richBlocks = [{ type: 'markdown', text: chunk }];
400
341
  const richContent = { text: chunk, richBlocks };
401
342
  const walId = this.durable
402
- ? await this.durable.beforePost(this.channel, chunk, { threadId, richBlocks })
343
+ ? await this.durable.beforePost(this.destination, chunk, { threadId, richBlocks })
403
344
  : null;
404
345
  try {
405
346
  const ref = await withRetries(async () => {
406
347
  try {
407
- return await this.adapter.postMessage(this.channel, richContent, { threadId });
348
+ return await this.adapter.postMessage(this.destination, richContent, { threadId });
408
349
  }
409
350
  catch {
410
- return await this.adapter.postMessage(this.channel, { text: chunk }, { threadId });
351
+ return await this.adapter.postMessage(this.destination, { text: chunk }, { threadId });
411
352
  }
412
- }, `postMessage(channel=${this.channel}, len=${chunk.length})`);
353
+ }, `postMessage(channel=${this._logChannel}, len=${chunk.length})`);
413
354
  if (walId && this.durable) {
414
355
  await this.durable.afterSent(walId, ref.messageId).catch(e => {
415
356
  log.warn(`afterSent failed for walId=${walId}:`, e.message);
@@ -418,8 +359,6 @@ export class VirtualMessage {
418
359
  return ref;
419
360
  }
420
361
  catch (e) {
421
- // Inline send failed permanently — release the WAL claim so the drain
422
- // loop can retry delivery later.
423
362
  if (walId && this.durable?.onSendFailed) {
424
363
  this.durable.onSendFailed(walId);
425
364
  }
@@ -433,7 +372,7 @@ export class VirtualMessage {
433
372
  const richBlocks = [{ type: 'markdown', text: content }];
434
373
  const richContent = { text: content, richBlocks };
435
374
  const walId = this.durable
436
- ? await this.durable.beforeUpdate(this.channel, ref.messageId, content, { richBlocks })
375
+ ? await this.durable.beforeUpdate(this._logChannel, ref.messageId, content, { richBlocks })
437
376
  : null;
438
377
  try {
439
378
  await withRetries(async () => {
@@ -443,7 +382,7 @@ export class VirtualMessage {
443
382
  catch {
444
383
  await this.adapter.updateMessage(ref, { text: content });
445
384
  }
446
- }, `updateMessage(channel=${this.channel}, len=${content.length})`);
385
+ }, `updateMessage(channel=${this._logChannel}, len=${content.length})`);
447
386
  if (walId && this.durable) {
448
387
  await this.durable.afterSent(walId).catch(e => {
449
388
  log.warn(`afterSent failed for walId=${walId}:`, e.message);
@@ -452,12 +391,6 @@ export class VirtualMessage {
452
391
  return { delivered: true };
453
392
  }
454
393
  catch (e) {
455
- // Don't release the WAL claim yet — let the caller decide whether to
456
- // mark as delivered (after fallback _postNew succeeds) or release
457
- // (after fallback _postNew also fails, so drain loop can retry).
458
- // When no durable hooks are configured, return delivered:false without
459
- // a walId — the caller still needs to fall back to _postNew but
460
- // doesn't need to clean up any WAL entry.
461
394
  return { delivered: false, ...(walId ? { walId } : {}) };
462
395
  }
463
396
  }
@@ -0,0 +1,9 @@
1
+ export declare class SlackProjectConduitsStore {
2
+ private readonly _repo;
3
+ constructor(filePath?: string);
4
+ get(projectId: string): Promise<string | null>;
5
+ set(projectId: string, conduit: string): Promise<void>;
6
+ remove(projectId: string): Promise<void>;
7
+ getAll(): Promise<Record<string, string>>;
8
+ flush(): Promise<void>;
9
+ }
@@ -0,0 +1,40 @@
1
+ // input: JsonRepository + STORE_DIR
2
+ // output: SlackProjectConduitsStore (projectId → conduit file-backed store)
3
+ // pos: File-backed project→conduit mapping, same path as channel-registry.json
4
+ // for backward compatibility with existing bindings.
5
+ import * as path from 'path';
6
+ import { JsonRepository } from '../../store/json-repository.js';
7
+ import { STORE_DIR } from '../../core/paths.js';
8
+ const CHANNEL_REGISTRY_FILE = path.join(STORE_DIR, 'channel-registry.json');
9
+ export class SlackProjectConduitsStore {
10
+ _repo;
11
+ constructor(filePath) {
12
+ this._repo = new JsonRepository({
13
+ filePath: filePath ?? CHANNEL_REGISTRY_FILE,
14
+ defaultValue: () => ({}),
15
+ migrate: (raw) => (typeof raw === 'object' && raw !== null ? raw : ({})),
16
+ });
17
+ }
18
+ async get(projectId) {
19
+ const data = await this._repo.read();
20
+ return data[projectId] ?? null;
21
+ }
22
+ async set(projectId, conduit) {
23
+ await this._repo.mutate((data) => {
24
+ data[projectId] = conduit;
25
+ return { next: data, result: undefined };
26
+ });
27
+ }
28
+ async remove(projectId) {
29
+ await this._repo.mutate((data) => {
30
+ delete data[projectId];
31
+ return { next: data, result: undefined };
32
+ });
33
+ }
34
+ async getAll() {
35
+ return { ...(await this._repo.read()) };
36
+ }
37
+ flush() {
38
+ return this._repo.flush();
39
+ }
40
+ }
@@ -1,7 +1,7 @@
1
- import type { WebClient } from '@slack/web-api';
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';
4
3
  import { TokenBucketRateLimiter } from '../utils/rate-limiter.js';
4
+ import type { OutputStream, OpenOutputStreamOpts } from '../output-stream.js';
5
5
  export interface SlackAdapterConfig {
6
6
  botToken: string;
7
7
  signingSecret: string;
@@ -44,7 +44,7 @@ export declare class SlackAdapter implements PlatformAdapter {
44
44
  * 3. On 429: reports backpressure to the rate limiter, re-throws
45
45
  */
46
46
  private rateLimitedCall;
47
- postMessage(channel: string, content: MessageContent, opts?: PostMessageOpts): Promise<MessageRef>;
47
+ postMessage(destination: Destination, content: MessageContent, opts?: PostMessageOpts): Promise<MessageRef>;
48
48
  /**
49
49
  * Update a message with per-message coalescing.
50
50
  *
@@ -53,7 +53,7 @@ export declare class SlackAdapter implements PlatformAdapter {
53
53
  * shared promise — the intermediate edit is discarded. Once the rate limiter
54
54
  * grants a token, the latest content is sent via chat.update.
55
55
  *
56
- * This eliminates wasted API calls when multiple callers (VirtualMessage
56
+ * This eliminates wasted API calls when multiple callers (OutputStream
57
57
  * streaming, status helpers, lifecycle) concurrently update the same message
58
58
  * while rate-limited.
59
59
  *
@@ -67,21 +67,31 @@ export declare class SlackAdapter implements PlatformAdapter {
67
67
  */
68
68
  private _evictStalePending;
69
69
  deleteMessage(ref: MessageRef): Promise<void>;
70
- postInteractive(channel: string, content: MessageContent & {
70
+ postInteractive(destination: Destination, content: MessageContent & {
71
71
  actions: ActionElement[];
72
72
  }, opts?: PostMessageOpts): Promise<MessageRef>;
73
73
  openModal(triggerId: string, modal: ModalDefinition): Promise<void>;
74
74
  addReaction(ref: MessageRef, emoji: string): Promise<void>;
75
- uploadFile(channel: string, filePath: string, opts?: FileUploadOpts): Promise<void>;
75
+ uploadFile(destination: Destination, filePath: string, opts?: FileUploadOpts): Promise<void>;
76
76
  downloadFile(fileRef: PlatformFileRef, destDir: string): Promise<DownloadedFile>;
77
77
  getPermalink(ref: MessageRef): Promise<string | null>;
78
78
  postEphemeral(channel: string, userId: string, text: string): Promise<void>;
79
- getAdminChannel(): string | null;
80
79
  /** Write CORTEX_ADMIN_CHANNEL to the .env file for persistence across restarts. */
81
80
  private _persistAdminChannel;
82
81
  /** Expose the rate limiter for sharing with MCP tools and testing. */
83
82
  getRateLimiter(): TokenBucketRateLimiter;
84
- getRawClient(): WebClient;
83
+ openOutputStream(destination: Destination, opts?: OpenOutputStreamOpts): OutputStream;
84
+ bindProjectConduit(projectId: string, conduitHint: string): Promise<void>;
85
+ unbindProjectConduit(projectId: string): Promise<void>;
86
+ getProjectConduits(): Promise<Record<string, string>>;
87
+ private _conduitsStore;
88
+ private _getConduitsStore;
89
+ /**
90
+ * Resolve a Destination to a concrete Slack channel + kind label.
91
+ * Returns channel=null for destinations that should be silently dropped
92
+ * (unregistered project, unconfigured admin channel).
93
+ */
94
+ private resolveDestination;
85
95
  private normalizeModalValues;
86
96
  private richBlocksToSlack;
87
97
  private actionElementToSlack;