@cortex-agent/server 2026.5.19-3 → 2026.5.22-2

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 (134) 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/gateway-generator.js +26 -4
  7. package/dist/core/log.js +61 -12
  8. package/dist/core/profile-generator.js +4 -3
  9. package/dist/core/status-format.js +1 -1
  10. package/dist/core/task-parser.d.ts +1 -1
  11. package/dist/core/task-parser.js +13 -6
  12. package/dist/core/types/thread-types.d.ts +4 -2
  13. package/dist/domain/costs/codex-usage-monitor.d.ts +1 -2
  14. package/dist/domain/costs/codex-usage-monitor.js +2 -2
  15. package/dist/domain/costs/cost-tracker.d.ts +2 -0
  16. package/dist/domain/costs/cost-tracker.js +4 -20
  17. package/dist/domain/costs/rate-limit-throttle.js +1 -4
  18. package/dist/domain/mcp/tools/context.d.ts +4 -2
  19. package/dist/domain/mcp/tools/context.js +7 -5
  20. package/dist/domain/mcp/tools/schedule.d.ts +1 -1
  21. package/dist/domain/mcp/tools/schedule.js +24 -20
  22. package/dist/domain/memory/index-regen.js +8 -5
  23. package/dist/domain/monitor/disk-monitor.js +1 -6
  24. package/dist/domain/projects/index.d.ts +2 -0
  25. package/dist/domain/projects/index.js +3 -0
  26. package/dist/domain/projects/project-store.d.ts +54 -0
  27. package/dist/domain/projects/project-store.js +194 -0
  28. package/dist/domain/projects/project-types.d.ts +11 -0
  29. package/dist/domain/projects/project-types.js +5 -0
  30. package/dist/domain/remote/client-hot-reload.d.ts +1 -0
  31. package/dist/domain/remote/client-hot-reload.js +284 -53
  32. package/dist/domain/scheduling/jobs/_shared.d.ts +1 -1
  33. package/dist/domain/scheduling/jobs/_shared.js +6 -5
  34. package/dist/domain/scheduling/jobs/memory-index-regen.js +2 -2
  35. package/dist/domain/scheduling/jobs/scheduled-task.d.ts +2 -2
  36. package/dist/domain/scheduling/jobs/scheduled-task.js +38 -36
  37. package/dist/domain/scheduling/jobs/sync-public.d.ts +1 -0
  38. package/dist/domain/scheduling/jobs/sync-public.js +34 -0
  39. package/dist/domain/scheduling/jobs/target-dispatch.d.ts +3 -7
  40. package/dist/domain/scheduling/jobs/target-dispatch.js +7 -9
  41. package/dist/domain/scheduling/jobs/task-archive.js +2 -2
  42. package/dist/domain/scheduling/jobs/task-dispatch.js +18 -16
  43. package/dist/domain/scheduling/runner.d.ts +1 -0
  44. package/dist/domain/scheduling/runner.js +2 -0
  45. package/dist/domain/scheduling/schedule-cli.d.ts +1 -0
  46. package/dist/domain/scheduling/schedule-cli.js +14 -14
  47. package/dist/domain/scheduling/schedule-command.js +45 -36
  48. package/dist/domain/scheduling/scheduler.d.ts +1 -1
  49. package/dist/domain/scheduling/scheduler.js +12 -11
  50. package/dist/domain/sessions/session-hooks.d.ts +10 -11
  51. package/dist/domain/sessions/session-hooks.js +26 -27
  52. package/dist/domain/sessions/session-registry.d.ts +10 -5
  53. package/dist/domain/sessions/session-registry.js +24 -9
  54. package/dist/domain/tasks/pending-tracker.js +8 -9
  55. package/dist/domain/tasks/system/task-cli.d.ts +2 -0
  56. package/dist/domain/tasks/system/task-cli.js +189 -29
  57. package/dist/domain/tasks/system/task-lifecycle-edit.js +3 -3
  58. package/dist/domain/threads/hook-runner.js +12 -7
  59. package/dist/domain/threads/runner.d.ts +3 -3
  60. package/dist/domain/threads/runner.js +30 -28
  61. package/dist/domain/threads/state-machine.d.ts +3 -0
  62. package/dist/domain/threads/state-machine.js +4 -0
  63. package/dist/entry/app.js +30 -9
  64. package/dist/entry/cli.js +19 -4
  65. package/dist/entry/daemon.js +28 -2
  66. package/dist/entry/startup-notify.js +8 -6
  67. package/dist/orchestration/agent-runner.js +19 -13
  68. package/dist/orchestration/durable-helpers.js +3 -2
  69. package/dist/orchestration/interactions/ask-user-question.d.ts +2 -3
  70. package/dist/orchestration/interactions/ask-user-question.js +5 -4
  71. package/dist/orchestration/interactions/interaction-handlers.js +8 -5
  72. package/dist/orchestration/interactions/plan-handler.js +3 -3
  73. package/dist/orchestration/lifecycle.js +43 -38
  74. package/dist/orchestration/routing/commands/cancel.js +9 -8
  75. package/dist/orchestration/routing/commands/channel.js +32 -26
  76. package/dist/orchestration/routing/commands/cost.js +5 -3
  77. package/dist/orchestration/routing/commands/device.js +2 -1
  78. package/dist/orchestration/routing/commands/dispatch.js +8 -7
  79. package/dist/orchestration/routing/commands/index.js +7 -4
  80. package/dist/orchestration/routing/commands/mode.js +24 -18
  81. package/dist/orchestration/routing/commands/nvtop.js +14 -12
  82. package/dist/orchestration/routing/commands/orient.js +2 -1
  83. package/dist/orchestration/routing/commands/schedule.js +2 -1
  84. package/dist/orchestration/routing/commands/sendfile.js +12 -9
  85. package/dist/orchestration/routing/commands/session.js +12 -10
  86. package/dist/orchestration/routing/commands/status.js +2 -2
  87. package/dist/orchestration/routing/commands/tail.js +10 -6
  88. package/dist/orchestration/routing/commands/task.js +5 -4
  89. package/dist/orchestration/routing/commands/thread-handlers.js +19 -12
  90. package/dist/orchestration/routing/hook-bridge-subscribers.js +15 -13
  91. package/dist/orchestration/status-helpers.d.ts +4 -5
  92. package/dist/orchestration/status-helpers.js +7 -8
  93. package/dist/orchestration/thread-executor.js +21 -12
  94. package/dist/platform/adapter.d.ts +13 -9
  95. package/dist/platform/adapter.js +1 -1
  96. package/dist/platform/adapters/feishu-output-stream.d.ts +27 -0
  97. package/dist/platform/adapters/feishu-output-stream.js +114 -0
  98. package/dist/platform/adapters/feishu.d.ts +16 -7
  99. package/dist/platform/adapters/feishu.js +64 -18
  100. package/dist/platform/adapters/index.d.ts +4 -1
  101. package/dist/platform/adapters/index.js +1 -1
  102. package/dist/platform/adapters/slack-output-stream.d.ts +55 -0
  103. package/dist/platform/{virtual-message.js → adapters/slack-output-stream.js} +98 -165
  104. package/dist/platform/adapters/slack-project-conduits.d.ts +9 -0
  105. package/dist/platform/adapters/slack-project-conduits.js +40 -0
  106. package/dist/platform/adapters/slack.d.ts +18 -8
  107. package/dist/platform/adapters/slack.js +82 -24
  108. package/dist/platform/index.d.ts +3 -2
  109. package/dist/platform/index.js +1 -1
  110. package/dist/platform/output-stream-chunk.d.ts +6 -0
  111. package/dist/platform/output-stream-chunk.js +45 -0
  112. package/dist/platform/output-stream-helpers.d.ts +6 -0
  113. package/dist/platform/output-stream-helpers.js +11 -0
  114. package/dist/platform/output-stream.d.ts +28 -0
  115. package/dist/platform/output-stream.js +4 -0
  116. package/dist/platform/testing.d.ts +41 -8
  117. package/dist/platform/testing.js +93 -11
  118. package/dist/platform/tool-trace.d.ts +9 -8
  119. package/dist/platform/tool-trace.js +19 -17
  120. package/dist/platform/types.d.ts +21 -1
  121. package/dist/platform/types.js +17 -1
  122. package/dist/store/channel-repo.d.ts +6 -0
  123. package/dist/store/channel-repo.js +9 -0
  124. package/dist/store/json-repository.js +12 -1
  125. package/dist/store/outbound-queue.d.ts +5 -4
  126. package/dist/store/outbound-queue.js +9 -6
  127. package/dist/store/schedule-repo.d.ts +9 -5
  128. package/dist/store/schedule-repo.js +59 -14
  129. package/dist/store/session-registry-repo.d.ts +36 -7
  130. package/dist/store/session-registry-repo.js +186 -25
  131. package/dist/store/thread-repo.d.ts +1 -0
  132. package/dist/store/thread-repo.js +8 -0
  133. package/package.json +1 -1
  134. package/dist/platform/virtual-message.d.ts +0 -68
@@ -5,6 +5,8 @@
5
5
  import { App } from '@slack/bolt';
6
6
  import { TokenBucketRateLimiter } from '../utils/rate-limiter.js';
7
7
  import { createLogger } from '../../core/log.js';
8
+ import { SlackOutputStream } from './slack-output-stream.js';
9
+ import { SlackProjectConduitsStore } from './slack-project-conduits.js';
8
10
  import * as fs from 'fs';
9
11
  import * as path from 'path';
10
12
  import { writeFile, readFile, mkdir } from 'fs/promises';
@@ -115,7 +117,7 @@ export class SlackAdapter {
115
117
  log.info(`Admin channel auto-detected from DM: ${msg.channel}`);
116
118
  // Persist to .env and notify (fire-and-forget, non-blocking)
117
119
  this._persistAdminChannel(msg.channel).catch(e => log.warn(`Failed to persist CORTEX_ADMIN_CHANNEL to .env: ${e.message}`));
118
- this.postMessage(msg.channel, {
120
+ this.postMessage({ type: 'system-notice' }, {
119
121
  text: `:wave: This DM channel has been auto-registered as the Cortex admin channel. \`CORTEX_ADMIN_CHANNEL=${msg.channel}\` has been written to \`.env\`. System notifications (startup, rate-limit, disk alerts) will be sent here.`,
120
122
  }).catch(e => log.warn(`Failed to send admin auto-detect notification: ${e.message}`));
121
123
  }
@@ -151,7 +153,7 @@ export class SlackAdapter {
151
153
  await handler({
152
154
  message: incoming,
153
155
  async reply(content, opts) {
154
- return adapter.postMessage(ref.channel, content, {
156
+ return adapter.postMessage({ type: 'interactive-reply', conduit: ref.channel, sessionId: '' }, content, {
155
157
  threadId: opts?.threadId || ref.threadId,
156
158
  });
157
159
  },
@@ -221,17 +223,21 @@ export class SlackAdapter {
221
223
  throw e;
222
224
  }
223
225
  }
224
- async postMessage(channel, content, opts) {
226
+ async postMessage(destination, content, opts) {
227
+ const resolved = await this.resolveDestination(destination);
228
+ if (!resolved.channel) {
229
+ return { channel: '', messageId: '' };
230
+ }
225
231
  const blocks = content.richBlocks ? this.richBlocksToSlack(content.richBlocks) : undefined;
226
232
  const payload = {
227
- channel,
233
+ channel: resolved.channel,
228
234
  text: content.text,
229
235
  ...(blocks && { blocks }),
230
236
  ...(opts?.threadId && { thread_ts: opts.threadId }),
231
237
  };
232
- const result = await this.rateLimitedCall('chat.postMessage', channel, () => this.client.chat.postMessage(payload));
238
+ const result = await this.rateLimitedCall('chat.postMessage', resolved.channel, () => this.client.chat.postMessage(payload));
233
239
  return {
234
- channel,
240
+ channel: resolved.channel,
235
241
  messageId: result.ts,
236
242
  threadId: opts?.threadId,
237
243
  };
@@ -244,7 +250,7 @@ export class SlackAdapter {
244
250
  * shared promise — the intermediate edit is discarded. Once the rate limiter
245
251
  * grants a token, the latest content is sent via chat.update.
246
252
  *
247
- * This eliminates wasted API calls when multiple callers (VirtualMessage
253
+ * This eliminates wasted API calls when multiple callers (OutputStream
248
254
  * streaming, status helpers, lifecycle) concurrently update the same message
249
255
  * while rate-limited.
250
256
  *
@@ -305,7 +311,7 @@ export class SlackAdapter {
305
311
  continue;
306
312
  }
307
313
  // Non-429 error: resolve to avoid hanging callers, but re-throw so the
308
- // caller (e.g. VirtualMessage) can fall back to posting a new message.
314
+ // caller (e.g. OutputStream) can fall back to posting a new message.
309
315
  this.pendingEdits.delete(key);
310
316
  resolve();
311
317
  throw e;
@@ -341,7 +347,11 @@ export class SlackAdapter {
341
347
  }));
342
348
  }
343
349
  // --- Interactive messages ---
344
- async postInteractive(channel, content, opts) {
350
+ async postInteractive(destination, content, opts) {
351
+ const resolved = await this.resolveDestination(destination);
352
+ if (!resolved.channel) {
353
+ return { channel: '', messageId: '' };
354
+ }
345
355
  const blocks = [
346
356
  ...(content.richBlocks ? this.richBlocksToSlack(content.richBlocks) : []),
347
357
  {
@@ -349,14 +359,14 @@ export class SlackAdapter {
349
359
  elements: content.actions.map(a => this.actionElementToSlack(a)),
350
360
  },
351
361
  ];
352
- const result = await this.rateLimitedCall('chat.postMessage', channel, () => this.client.chat.postMessage({
353
- channel,
362
+ const result = await this.rateLimitedCall('chat.postMessage', resolved.channel, () => this.client.chat.postMessage({
363
+ channel: resolved.channel,
354
364
  text: content.text,
355
365
  blocks,
356
366
  ...(opts?.threadId && { thread_ts: opts.threadId }),
357
367
  }));
358
368
  return {
359
- channel,
369
+ channel: resolved.channel,
360
370
  messageId: result.ts,
361
371
  threadId: opts?.threadId,
362
372
  };
@@ -377,11 +387,15 @@ export class SlackAdapter {
377
387
  }));
378
388
  }
379
389
  // --- Files ---
380
- async uploadFile(channel, filePath, opts) {
381
- const { resolved, size } = this.resolveFilePath(filePath);
382
- const body = fs.readFileSync(resolved);
383
- const uploadName = opts?.filename || path.basename(resolved);
384
- const uploadInit = await this.rateLimitedCall('files.getUploadURLExternal', channel, () => this.client.files.getUploadURLExternal({
390
+ async uploadFile(destination, filePath, opts) {
391
+ const resolved = await this.resolveDestination(destination);
392
+ if (!resolved.channel) {
393
+ return;
394
+ }
395
+ const { resolved: fileResolved, size } = this.resolveFilePath(filePath);
396
+ const body = fs.readFileSync(fileResolved);
397
+ const uploadName = opts?.filename || path.basename(fileResolved);
398
+ const uploadInit = await this.rateLimitedCall('files.getUploadURLExternal', resolved.channel, () => this.client.files.getUploadURLExternal({
385
399
  filename: uploadName,
386
400
  length: size,
387
401
  }));
@@ -396,9 +410,9 @@ export class SlackAdapter {
396
410
  if (!uploadRes.ok) {
397
411
  throw new Error(`Slack file upload failed (${uploadRes.status})`);
398
412
  }
399
- await this.rateLimitedCall('files.completeUploadExternal', channel, () => this.client.files.completeUploadExternal({
413
+ await this.rateLimitedCall('files.completeUploadExternal', resolved.channel, () => this.client.files.completeUploadExternal({
400
414
  files: [{ id: uploadInit.file_id, title: uploadName }],
401
- channel_id: channel,
415
+ channel_id: resolved.channel,
402
416
  }));
403
417
  }
404
418
  async downloadFile(fileRef, destDir) {
@@ -451,9 +465,6 @@ export class SlackAdapter {
451
465
  async postEphemeral(channel, userId, text) {
452
466
  await this.rateLimitedCall('chat.postEphemeral', channel, () => this.client.chat.postEphemeral({ channel, user: userId, text }));
453
467
  }
454
- getAdminChannel() {
455
- return this.config.adminChannel || null;
456
- }
457
468
  /** Write CORTEX_ADMIN_CHANNEL to the .env file for persistence across restarts. */
458
469
  async _persistAdminChannel(channel) {
459
470
  const envPath = path.join(CONFIG_DIR, '.env');
@@ -484,8 +495,55 @@ export class SlackAdapter {
484
495
  getRateLimiter() {
485
496
  return this.rateLimiter;
486
497
  }
487
- getRawClient() {
488
- return this.client;
498
+ // --- Output stream ---
499
+ openOutputStream(destination, opts) {
500
+ return new SlackOutputStream(this, destination, opts);
501
+ }
502
+ // --- Project conduit mapping ---
503
+ async bindProjectConduit(projectId, conduitHint) {
504
+ await this._getConduitsStore().set(projectId, conduitHint);
505
+ }
506
+ async unbindProjectConduit(projectId) {
507
+ await this._getConduitsStore().remove(projectId);
508
+ }
509
+ async getProjectConduits() {
510
+ return this._getConduitsStore().getAll();
511
+ }
512
+ _conduitsStore = null;
513
+ _getConduitsStore() {
514
+ if (!this._conduitsStore) {
515
+ this._conduitsStore = new SlackProjectConduitsStore();
516
+ }
517
+ return this._conduitsStore;
518
+ }
519
+ /**
520
+ * Resolve a Destination to a concrete Slack channel + kind label.
521
+ * Returns channel=null for destinations that should be silently dropped
522
+ * (unregistered project, unconfigured admin channel).
523
+ */
524
+ async resolveDestination(dest) {
525
+ switch (dest.type) {
526
+ case 'interactive-reply':
527
+ return { channel: dest.conduit, kind: 'interactive-reply' };
528
+ case 'project-report': {
529
+ const conduits = await this.getProjectConduits();
530
+ const channel = conduits[dest.projectId];
531
+ if (!channel) {
532
+ log.warn(`No conduit registered for project "${dest.projectId}"; dropping project-report`);
533
+ return { channel: null, kind: 'project-report-noop' };
534
+ }
535
+ return { channel, kind: 'project-report' };
536
+ }
537
+ case 'system-notice':
538
+ if (!this.config.adminChannel) {
539
+ log.warn('No admin channel configured; dropping system-notice');
540
+ return { channel: null, kind: 'system-notice-noop' };
541
+ }
542
+ return { channel: this.config.adminChannel, kind: 'system-notice' };
543
+ default:
544
+ // Pre-existing: callers passing raw strings (strict:false compat)
545
+ return { channel: null, kind: 'unknown' };
546
+ }
489
547
  }
490
548
  // --- Slack-specific converters ---
491
549
  normalizeModalValues(rawValues) {
@@ -1,6 +1,7 @@
1
1
  export type { PlatformAdapter } from './adapter.js';
2
- export type { MessageRef, MessageContent, MessageContext, MessageEditContext, ActionContext, ModalSubmitContext, ModalDefinition, ModalField, ModalSelectField, ModalMultiSelectField, ModalTextInputField, ModalSectionField, SelectOption, ModalFieldValue, PlatformCapabilities, PlatformFileRef, DownloadedFile, IncomingMessage, IncomingAttachment, PostMessageOpts, FileUploadOpts, RichBlock, ActionElement, ButtonElement, } from './types.js';
3
- export { VirtualMessage } from './virtual-message.js';
2
+ export type { MessageRef, MessageContent, MessageContext, MessageEditContext, ActionContext, ModalSubmitContext, ModalDefinition, ModalField, ModalSelectField, ModalMultiSelectField, ModalTextInputField, ModalSectionField, SelectOption, ModalFieldValue, PlatformCapabilities, PlatformFileRef, DownloadedFile, IncomingMessage, IncomingAttachment, PostMessageOpts, FileUploadOpts, RichBlock, ActionElement, ButtonElement, Destination, } from './types.js';
3
+ export type { OutputStream, MutableRegion, OpenOutputStreamOpts } from './output-stream.js';
4
+ export { postOnce } from './output-stream-helpers.js';
4
5
  export { ToolTrace, createToolTrace, isToolTraceEnabled } from './tool-trace.js';
5
6
  export { buildQuestionGroupBlocks, buildQuestionModalDefinition, buildPlanApprovalContent, buildPlanFeedbackModal, } from './interactive-builder.js';
6
7
  export type { QuestionOption, QuestionRecord, QuestionGroup } from './interactive-builder.js';
@@ -2,7 +2,7 @@
2
2
  // output: Re-export full family of PlatformAdapter public APIs
3
3
  // pos: Public API export of the Platform abstraction
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
- export { VirtualMessage } from './virtual-message.js';
5
+ export { postOnce } from './output-stream-helpers.js';
6
6
  export { ToolTrace, createToolTrace, isToolTraceEnabled } from './tool-trace.js';
7
7
  export { buildQuestionGroupBlocks, buildQuestionModalDefinition, buildPlanApprovalContent, buildPlanFeedbackModal, } from './interactive-builder.js';
8
8
  export { createAdapter, createAdapterFromEnv } from './adapters/index.js';
@@ -0,0 +1,6 @@
1
+ export declare const DEFAULT_MAX_CHUNK = 3000;
2
+ export declare const MAX_HORIZONTAL_RULES = 3;
3
+ export declare function countHorizontalRules(text: string): number;
4
+ export declare function countTables(text: string): number;
5
+ export declare function needsSplit(text: string, maxChunk: number): boolean;
6
+ export declare function chunkText(text: string, maxChunk: number): string[];
@@ -0,0 +1,45 @@
1
+ // input: nothing (pure functions)
2
+ // output: shared length-based chunking utilities
3
+ // pos: Used by SlackOutputStream and FeishuOutputStream for message splitting
4
+ export const DEFAULT_MAX_CHUNK = 3000;
5
+ export const MAX_HORIZONTAL_RULES = 3;
6
+ export function countHorizontalRules(text) {
7
+ return text.split('\n').filter(line => /^-{3,}\s*$/.test(line.trim())).length;
8
+ }
9
+ export function countTables(text) {
10
+ const lines = text.split('\n');
11
+ let count = 0;
12
+ let inTable = false;
13
+ for (const line of lines) {
14
+ const isTableLine = /^\s*\|/.test(line);
15
+ if (isTableLine && !inTable) {
16
+ count++;
17
+ inTable = true;
18
+ }
19
+ else if (!isTableLine) {
20
+ inTable = false;
21
+ }
22
+ }
23
+ return count;
24
+ }
25
+ export function needsSplit(text, maxChunk) {
26
+ return countTables(text) > 1
27
+ || text.length > maxChunk
28
+ || countHorizontalRules(text) >= MAX_HORIZONTAL_RULES;
29
+ }
30
+ export function chunkText(text, maxChunk) {
31
+ if (text.length <= maxChunk)
32
+ return [text];
33
+ const chunks = [];
34
+ let remaining = text;
35
+ while (remaining.length > maxChunk) {
36
+ let splitAt = remaining.lastIndexOf('\n', maxChunk);
37
+ if (splitAt <= 0)
38
+ splitAt = maxChunk;
39
+ chunks.push(remaining.substring(0, splitAt));
40
+ remaining = remaining.substring(splitAt).replace(/^\n/, '');
41
+ }
42
+ if (remaining)
43
+ chunks.push(remaining);
44
+ return chunks;
45
+ }
@@ -0,0 +1,6 @@
1
+ import type { PlatformAdapter } from './adapter.js';
2
+ import type { Destination, MessageRef } from './types.js';
3
+ import type { OpenOutputStreamOpts } from './output-stream.js';
4
+ /** Post a single text message and return its parent MessageRef.
5
+ * Creates a transient OutputStream, emits, flushes, and disposes. */
6
+ export declare function postOnce(adapter: PlatformAdapter, destination: Destination, text: string, opts?: OpenOutputStreamOpts): Promise<MessageRef | null>;
@@ -0,0 +1,11 @@
1
+ // input: PlatformAdapter + Destination
2
+ // output: postOnce free helper
3
+ // pos: One-shot message post via transient OutputStream
4
+ /** Post a single text message and return its parent MessageRef.
5
+ * Creates a transient OutputStream, emits, flushes, and disposes. */
6
+ export async function postOnce(adapter, destination, text, opts) {
7
+ const stream = adapter.openOutputStream(destination, opts);
8
+ stream.emitText(text);
9
+ await stream.flush();
10
+ return stream.getParentRef();
11
+ }
@@ -0,0 +1,28 @@
1
+ import type { MessageRef, RichBlock, ActionElement, DurableHooks } from './types.js';
2
+ export interface MutableRegion {
3
+ /** Replace the region's content. No-op once the stream commits past this region. */
4
+ update(text: string): void;
5
+ }
6
+ export interface OutputStream {
7
+ /** Emit committed assistant text — a hard boundary for aggregation. */
8
+ emitText(text: string): void;
9
+ /** Open a fresh mutable region, returning a handle for updates.
10
+ * The region is sealed when emitText, openMutable, or postInteractive is called next. */
11
+ openMutable(text: string): MutableRegion;
12
+ /** Post an independent interactive message (buttons, actions). Resets the internal cursor. */
13
+ postInteractive(text: string, opts?: {
14
+ richBlocks?: RichBlock[];
15
+ actions?: ActionElement[];
16
+ }): Promise<MessageRef | null>;
17
+ /** Await all queued operations and surface any captured errors. */
18
+ flush(): Promise<void>;
19
+ /** All MessageRefs posted by this stream, in order. */
20
+ getRefs(): MessageRef[];
21
+ /** The first MessageRef posted (the parent / root of the thread). */
22
+ getParentRef(): MessageRef | null;
23
+ }
24
+ export interface OpenOutputStreamOpts {
25
+ threadId?: string | null;
26
+ onMessagePosted?: ((ref: MessageRef) => void) | null;
27
+ durable?: DurableHooks | null;
28
+ }
@@ -0,0 +1,4 @@
1
+ // input: nothing (pure types module)
2
+ // output: OutputStream / MutableRegion / OpenOutputStreamOpts types
3
+ // pos: Platform-neutral output streaming interface
4
+ export {};
@@ -1,7 +1,8 @@
1
1
  import type { PlatformAdapter } from './adapter.js';
2
- import type { MessageRef, MessageContent, MessageContext, MessageEditContext, ActionContext, ModalSubmitContext, ModalDefinition, ModalFieldValue, PlatformCapabilities, PlatformFileRef, DownloadedFile, PostMessageOpts, FileUploadOpts, ActionElement } from './types.js';
2
+ import type { MessageRef, MessageContent, MessageContext, MessageEditContext, ActionContext, ModalSubmitContext, ModalDefinition, ModalFieldValue, PlatformCapabilities, PlatformFileRef, DownloadedFile, Destination, PostMessageOpts, FileUploadOpts, ActionElement, RichBlock } from './types.js';
3
+ import type { OutputStream, MutableRegion, OpenOutputStreamOpts } from './output-stream.js';
3
4
  export interface PostedMessage {
4
- channel: string;
5
+ destination: Destination;
5
6
  content: MessageContent;
6
7
  threadId?: string;
7
8
  actions?: ActionElement[];
@@ -18,7 +19,7 @@ export interface AddedReaction {
18
19
  emoji: string;
19
20
  }
20
21
  export interface UploadedFile {
21
- channel: string;
22
+ destination: Destination;
22
23
  filePath: string;
23
24
  opts?: FileUploadOpts;
24
25
  }
@@ -31,6 +32,35 @@ export interface EphemeralMessage {
31
32
  userId: string;
32
33
  text: string;
33
34
  }
35
+ export interface MockSegmentRecord {
36
+ kind: 'text' | 'mutable-open' | 'mutable-update' | 'interactive';
37
+ text: string;
38
+ actions?: ActionElement[];
39
+ }
40
+ /** Mock OutputStream that records a typed segment trail.
41
+ * Routes real posts through MockAdapter.postMessage/postInteractive
42
+ * so existing posted[] assertions keep working. Does no coalescing,
43
+ * mirroring TUI behavior. */
44
+ export declare class MockOutputStream implements OutputStream {
45
+ private adapter;
46
+ private destination;
47
+ private _parentRef;
48
+ readonly segments: MockSegmentRecord[];
49
+ readonly refs: MessageRef[];
50
+ constructor(adapter: MockAdapter, destination: Destination, _opts?: OpenOutputStreamOpts);
51
+ emitText(text: string): void;
52
+ openMutable(text: string): MutableRegion;
53
+ postInteractive(text: string, opts?: {
54
+ richBlocks?: RichBlock[];
55
+ actions?: ActionElement[];
56
+ }): Promise<MessageRef | null>;
57
+ flush(): Promise<void>;
58
+ getRefs(): MessageRef[];
59
+ getParentRef(): MessageRef | null;
60
+ private _genCounter;
61
+ private _nextGen;
62
+ private _mutableUpdate;
63
+ }
34
64
  export declare class MockAdapter implements PlatformAdapter {
35
65
  readonly name = "mock";
36
66
  readonly capabilities: PlatformCapabilities;
@@ -61,20 +91,23 @@ export declare class MockAdapter implements PlatformAdapter {
61
91
  onMessageEdit(handler: (ctx: MessageEditContext) => Promise<void>): void;
62
92
  onAction(actionId: string, handler: (ctx: ActionContext) => Promise<void>): void;
63
93
  onModalSubmit(callbackId: string, handler: (ctx: ModalSubmitContext) => Promise<void>): void;
64
- postMessage(channel: string, content: MessageContent, opts?: PostMessageOpts): Promise<MessageRef>;
94
+ postMessage(destination: Destination, content: MessageContent, opts?: PostMessageOpts): Promise<MessageRef>;
65
95
  updateMessage(ref: MessageRef, content: MessageContent): Promise<void>;
66
96
  deleteMessage(ref: MessageRef): Promise<void>;
67
- postInteractive(channel: string, content: MessageContent & {
97
+ postInteractive(destination: Destination, content: MessageContent & {
68
98
  actions: ActionElement[];
69
99
  }, opts?: PostMessageOpts): Promise<MessageRef>;
70
100
  openModal(triggerId: string, modal: ModalDefinition): Promise<void>;
71
101
  addReaction(ref: MessageRef, emoji: string): Promise<void>;
72
- uploadFile(channel: string, filePath: string, opts?: FileUploadOpts): Promise<void>;
102
+ uploadFile(destination: Destination, filePath: string, opts?: FileUploadOpts): Promise<void>;
73
103
  downloadFile(fileRef: PlatformFileRef, destDir: string): Promise<DownloadedFile>;
74
104
  getPermalink(ref: MessageRef): Promise<string | null>;
75
105
  postEphemeral(channel: string, userId: string, text: string): Promise<void>;
76
- getAdminChannel(): string | null;
77
- getRawClient(): null;
106
+ openOutputStream(destination: Destination, opts?: OpenOutputStreamOpts): OutputStream;
107
+ private _projectConduits;
108
+ bindProjectConduit(projectId: string, conduitHint: string): Promise<void>;
109
+ unbindProjectConduit(projectId: string): Promise<void>;
110
+ getProjectConduits(): Promise<Record<string, string>>;
78
111
  /** Simulate an inbound message for testing event handlers. */
79
112
  simulateMessage(channel: string, text: string, opts?: {
80
113
  senderId?: string;
@@ -2,6 +2,76 @@
2
2
  // output: MockAdapter + recorded message/modal types
3
3
  // pos: In-memory mock adapter for unit tests
4
4
  // >>> If I am updated, update my header comment and the parent folder's CORTEX.md <<<
5
+ import { resolveDestinationConduit } from './types.js';
6
+ /** Mock OutputStream that records a typed segment trail.
7
+ * Routes real posts through MockAdapter.postMessage/postInteractive
8
+ * so existing posted[] assertions keep working. Does no coalescing,
9
+ * mirroring TUI behavior. */
10
+ export class MockOutputStream {
11
+ adapter;
12
+ destination;
13
+ _parentRef = null;
14
+ segments = [];
15
+ refs = [];
16
+ constructor(adapter, destination, _opts) {
17
+ this.adapter = adapter;
18
+ this.destination = destination;
19
+ }
20
+ emitText(text) {
21
+ if (!text?.trim())
22
+ return;
23
+ this.segments.push({ kind: 'text', text });
24
+ this.adapter.postMessage(this.destination, { text }).then(ref => {
25
+ this.refs.push(ref);
26
+ if (!this._parentRef)
27
+ this._parentRef = ref;
28
+ });
29
+ }
30
+ openMutable(text) {
31
+ if (!text?.trim())
32
+ return { update: () => { } };
33
+ const generation = this._nextGen();
34
+ this.segments.push({ kind: 'mutable-open', text });
35
+ this.adapter.postMessage(this.destination, { text }).then(ref => {
36
+ this.refs.push(ref);
37
+ if (!this._parentRef)
38
+ this._parentRef = ref;
39
+ });
40
+ return { update: (t) => this._mutableUpdate(t, generation) };
41
+ }
42
+ postInteractive(text, opts) {
43
+ const actions = opts?.actions;
44
+ this.segments.push({ kind: 'interactive', text, actions });
45
+ const method = actions && actions.length > 0
46
+ ? this.adapter.postInteractive(this.destination, { text, richBlocks: opts?.richBlocks, actions })
47
+ : this.adapter.postMessage(this.destination, { text, richBlocks: opts?.richBlocks });
48
+ return method.then(ref => {
49
+ this.refs.push(ref);
50
+ if (!this._parentRef)
51
+ this._parentRef = ref;
52
+ return ref;
53
+ });
54
+ }
55
+ async flush() {
56
+ // All operations are synchronous behind MockAdapter;
57
+ // nothing to await.
58
+ }
59
+ getRefs() {
60
+ return [...this.refs];
61
+ }
62
+ getParentRef() {
63
+ return this._parentRef;
64
+ }
65
+ _genCounter = 0;
66
+ _nextGen() {
67
+ return ++this._genCounter;
68
+ }
69
+ _mutableUpdate(text, _generation) {
70
+ if (!text?.trim())
71
+ return;
72
+ this.segments.push({ kind: 'mutable-update', text });
73
+ }
74
+ }
5
75
  export class MockAdapter {
6
76
  name = 'mock';
7
77
  capabilities;
@@ -53,13 +123,14 @@ export class MockAdapter {
53
123
  onModalSubmit(callbackId, handler) {
54
124
  this.modalHandlers.set(callbackId, handler);
55
125
  }
56
- async postMessage(channel, content, opts) {
126
+ async postMessage(destination, content, opts) {
57
127
  if (this.failPostMessageCount > 0) {
58
128
  this.failPostMessageCount--;
59
129
  throw new Error('mock: postMessage transient failure');
60
130
  }
131
+ const channel = resolveDestinationConduit(destination, this._adminChannel);
61
132
  const messageId = String(this.nextId++);
62
- this.posted.push({ channel, content, threadId: opts?.threadId });
133
+ this.posted.push({ destination, content, threadId: opts?.threadId });
63
134
  return { channel, messageId, threadId: opts?.threadId };
64
135
  }
65
136
  async updateMessage(ref, content) {
@@ -72,13 +143,14 @@ export class MockAdapter {
72
143
  async deleteMessage(ref) {
73
144
  this.deleted.push({ ref });
74
145
  }
75
- async postInteractive(channel, content, opts) {
146
+ async postInteractive(destination, content, opts) {
76
147
  if (this.failPostInteractiveCount > 0) {
77
148
  this.failPostInteractiveCount--;
78
149
  throw new Error('mock: postInteractive transient failure');
79
150
  }
151
+ const channel = resolveDestinationConduit(destination, this._adminChannel);
80
152
  const messageId = String(this.nextId++);
81
- this.posted.push({ channel, content, threadId: opts?.threadId, actions: content.actions });
153
+ this.posted.push({ destination, content, threadId: opts?.threadId, actions: content.actions });
82
154
  return { channel, messageId, threadId: opts?.threadId };
83
155
  }
84
156
  async openModal(triggerId, modal) {
@@ -87,8 +159,8 @@ export class MockAdapter {
87
159
  async addReaction(ref, emoji) {
88
160
  this.reactions.push({ ref, emoji });
89
161
  }
90
- async uploadFile(channel, filePath, opts) {
91
- this.uploads.push({ channel, filePath, opts });
162
+ async uploadFile(destination, filePath, opts) {
163
+ this.uploads.push({ destination, filePath, opts });
92
164
  }
93
165
  async downloadFile(fileRef, destDir) {
94
166
  return { localPath: `${destDir}/${fileRef.id}`, mimetype: fileRef.mimetype, name: fileRef.name };
@@ -99,11 +171,20 @@ export class MockAdapter {
99
171
  async postEphemeral(channel, userId, text) {
100
172
  this.ephemeralMessages.push({ channel, userId, text });
101
173
  }
102
- getAdminChannel() {
103
- return this._adminChannel;
174
+ // --- Output stream ---
175
+ openOutputStream(destination, opts) {
176
+ return new MockOutputStream(this, destination, opts);
177
+ }
178
+ // --- Project conduit mapping ---
179
+ _projectConduits = new Map();
180
+ async bindProjectConduit(projectId, conduitHint) {
181
+ this._projectConduits.set(projectId, conduitHint);
182
+ }
183
+ async unbindProjectConduit(projectId) {
184
+ this._projectConduits.delete(projectId);
104
185
  }
105
- getRawClient() {
106
- return null;
186
+ async getProjectConduits() {
187
+ return Object.fromEntries(this._projectConduits);
107
188
  }
108
189
  // --- Test helpers ---
109
190
  /** Simulate an inbound message for testing event handlers. */
@@ -123,7 +204,7 @@ export class MockAdapter {
123
204
  raw: {},
124
205
  },
125
206
  async reply(content, replyOpts) {
126
- return adapter.postMessage(channel, content, {
207
+ return adapter.postMessage({ type: 'interactive-reply', conduit: channel, sessionId: '' }, content, {
127
208
  threadId: replyOpts?.threadId || ref.threadId,
128
209
  });
129
210
  },
@@ -186,5 +267,6 @@ export class MockAdapter {
186
267
  this.failPostMessageCount = 0;
187
268
  this.failUpdateMessageCount = 0;
188
269
  this.failPostInteractiveCount = 0;
270
+ this._projectConduits.clear();
189
271
  }
190
272
  }
@@ -1,4 +1,4 @@
1
- import type { VirtualMessage } from './index.js';
1
+ import type { OutputStream } from './index.js';
2
2
  export declare function isToolTraceEnabled(): boolean;
3
3
  /** One-line summary of a single tool invocation's params — short enough to chain. */
4
4
  declare function summarizeToolInput(name: string, input: any): string;
@@ -11,21 +11,22 @@ export interface ToolTraceOptions {
11
11
  slotPrefix?: string | null;
12
12
  }
13
13
  export declare class ToolTrace {
14
- private vm;
14
+ private stream;
15
+ private region;
15
16
  private prefix;
16
17
  /** Name of the currently-open group (null if no open group). */
17
18
  private groupName;
18
19
  /** Accumulated summaries for the open group; rendered on every update. */
19
20
  private groupSummaries;
20
- constructor(vm: VirtualMessage, opts?: ToolTraceOptions);
21
+ constructor(stream: OutputStream, opts?: ToolTraceOptions);
21
22
  onToolUse(name: string, input: any): void;
22
- /** Seal the current group on the tool-trace side. VM's tail is not touched
23
- * here — the next `vm.append(text)` or `vm.appendMutableTail(...)` will
24
- * seal it naturally. */
23
+ /** Seal the current group on the tool-trace side. The stream's mutable region
24
+ * is not touched here — the next `stream.emitText(text)` or
25
+ * `stream.openMutable(...)` will seal it naturally. */
25
26
  flush(): void;
26
27
  }
27
- /** Factory: returns a ToolTrace wired to the given VM, or null if the feature is disabled or VM is missing. */
28
- export declare function createToolTrace(vm: VirtualMessage | null | undefined, opts?: ToolTraceOptions): ToolTrace | null;
28
+ /** Factory: returns a ToolTrace wired to the given OutputStream, or null if the feature is disabled or stream is missing. */
29
+ export declare function createToolTrace(stream: OutputStream | null | undefined, opts?: ToolTraceOptions): ToolTrace | null;
29
30
  export declare const _test: {
30
31
  summarizeToolInput: typeof summarizeToolInput;
31
32
  renderToolLine: typeof renderToolLine;