pi-roundtable 0.37.0 → 0.38.0

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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,23 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.38.0] - 2026-11-08
9
+
10
+ ### Added
11
+
12
+ - Display blocks (`cards`, `table`, `steps`, `stats`, `mindmap`, `mermaid`, `diff`, GitHub alerts and the interactive kinds of `pi-better-show`) in an agent's reply reach every surface in a form it can show. `ChatSurface.blocks` lists the kinds a surface draws itself; a reply then arrives whole in one chunk, with those fences intact. `ChatSurface.blockText` (`BlockTextFlavor`) picks the text a block reads as on any other surface: `discord` by default, `line`, or `plain`. Discord and LINE never receive a block as YAML any more; a diagram is drawn as Unicode boxes, within 500 ms and from a source of at most 3 KB, otherwise its source is shown; a reply waits 500 ms in all for its diagrams and draws at most three afresh (the text drawing can need a minute for a 250-byte chain of states, so it runs in a worker thread that the host waits on for the deadline at most).
13
+ - `chunksFor(surface, text)` and `BlockSupport` (`pi-roundtable/kit`) cut agent text for a surface; `textFor` does the same conversion without the cut, for a surface that shows a message in one piece, as the web chat does. `InterimPosts` carries the same `blocks` and `blockText`, which the host's surface port fills in from the surface. `ChatSurface.support(channel)` (`ChannelSupport`, `supportOf` in `pi-roundtable/kit`) lets a surface say that one of its channels differs, such as a host's room on the web app, which draws no blocks and whose turns are not told to write them.
14
+ - `describeSurfaceContract` checks that a surface listing `blocks` delivers a long block of a declared kind whole; `describeBlocksContract` (`pi-roundtable/testing`) runs only that check for a surface that cannot run the whole contract.
15
+ - `pi-better-show` 0.2.0 is a dependency.
16
+
17
+ ### Changed
18
+
19
+ - Every path that posts agent text uses `chunksFor` in place of `splitReply`: turn replies, agent-room posts, interim text, messages between agents, dispatch threads, direct messages and the sandbox claim. `splitReply` stays for the host's own notices and error reports. `TurnHost.chunks` is added to the agent team's internals; `replyBody` takes the surface as an optional second argument.
20
+
21
+ ## [0.37.1] - 2026-11-07
22
+
23
+ - Release in lockstep with pi-roundtable-web 0.37.1 (an archived temp knight's or a dismissed thread's unread count leaves the tab title and dot without a reload); no core behavior changes.
24
+
8
25
  ## [0.37.0] - 2026-11-06
9
26
 
10
27
  ### Added
package/docs/plugins.md CHANGED
@@ -3125,6 +3125,9 @@ The agent server claims `discord:` keys, and, only on a surface that declares `a
3125
3125
  | `readAttachment(channel, ref)` | Returns the content of an attachment this surface made, such as an upload to a room, as `Promise<AttachmentContent>`: the bytes, `{ path }` of a file on the host, or a stream, the last two stored without holding them whole; the agent server's claim reads the refs of the surface's messages here and never fetches them over the network, and a rejection fails that file. A claim of your own passes the same function as `read` to `attachmentsOf`, or its refs are downloaded | the refs' URLs are downloaded, up to 25 MB each |
3126
3126
  | `maxAttachmentBytes` | The most bytes of one attachment a turn takes from this surface, for a ref, a file, a stream or a download alike; a positive integer, so a surface that keeps large uploads can raise it past 25 MiB. See [files from outside a turn](#contextattachments-files-from-outside-a-turn) | 25 MiB, as Discord's |
3127
3127
  | `formatting` | A short English text on how a reply renders here, such as "no Markdown tables"; the runtime appends it to the system prompt of every turn that replies on this surface, after the persona | nothing is appended |
3128
+ | `blocks` | The [display-block](#display-blocks-in-a-reply) kinds the surface draws itself, such as `["table", "mermaid"]` (`BlockKind` of `pi-better-show`); a reply reaches `sendReply` whole, with the fences of those kinds intact. Every other block arrives as text | none: every block arrives as text |
3129
+ | `blockText` | How a block the surface does not draw reads as text: `"discord"` (Markdown, with Discord's native `diff` fence), `"line"` (plain text without Markdown markup) or `"plain"` | `"discord"` |
3130
+ | `support(channel)` | What differs in one channel of the surface: a `formatting`, `blocks` or `blockText` that replaces the surface's own for a turn that replies there, such as a host's room on a surface that draws blocks only in its own rooms. Return `undefined` for a channel that is like the rest | every channel is like the surface |
3128
3131
  | `startTyping(channel)` | Shows a typing indicator until the returned function is called | none is shown |
3129
3132
  | `showStop(channel)` | Shows the owner a stop control until the returned function is called; using it calls `conversations.stop(channel)`. A group's round shows it for the whole round, and stopping ends the round: the member speaking is stopped and the members still waiting do not speak | none is shown |
3130
3133
  | `react`, `unreact` | Adds or removes the bot's reaction on a message | no marks on queued or steered messages |
@@ -3231,6 +3234,11 @@ The built-in values: Discord says that Markdown renders except tables, which sho
3231
3234
  A host overrides or removes a built-in value through that surface's options (`discord.formatting`, `line({ formatting })`, `webChat({ formatting })`): a text replaces it, and `false` tells the model nothing.
3232
3235
  A custom runtime provider reads the same lookup as `RuntimeDeps.formatting(channel)`.
3233
3236
 
3237
+ ### Display blocks in a reply
3238
+
3239
+ An agent may write a *display block* in a reply: a fenced block whose first word is a kind (`cards`, `table`, `steps`, `stats`, `mindmap`, `mermaid`, `diff`, `options`, `form`, ...) or a GitHub alert (`> [!NOTE]`), as `pi-better-show` defines. A block is YAML or source that only a surface that draws it should show, so the host cuts agent text with `chunksFor(surface, text)` (from `pi-roundtable/kit`), never `splitReply` alone: a block whose kind the surface does not list in `blocks` becomes text first (Discord's flavor by default, `blockText: "line"` for plain text; a diagram is drawn as Unicode boxes, unless its source is over 3 KB or the drawing, which runs in a worker the host waits on for at most 500 ms, is not done by then, and then the source is shown), and the result is split into messages within Discord's limit. A surface that lists any kind in `blocks` gets the text whole in one chunk, because cutting a fence breaks the block. `textFor(surface, text)` does the conversion alone, for a surface that shows a message of any length in one piece (the web chat's replies and inbox notices) and so needs no cutting. A block that is not closed at the end of the reply is still a block: a text surface gets it as text, and a surface that draws it gets it as written. A block that does not parse becomes a plain code block. The same applies to interim posts: the host's surface port copies the surface's `blocks` and `blockText` onto the `InterimPosts` it returns, so the poster cuts for the right surface. A surface whose channels differ (a host's room, read on a page that does not draw blocks) answers `support(channel)` with what is different, and `supportOf(surface, channel)` (from `pi-roundtable/kit`) reads the result; the formatting guidance a turn gets follows it too. Host notices and error reports are the host's own text and keep `splitReply`.
3240
+ `describeSurfaceContract` checks that a surface listing `blocks` delivers a block of a declared kind longer than a message whole; `describeBlocksContract(name, make)` registers only that check, for a surface that cannot run the whole contract (the subject needs `surface`, `channel` and `observations()` of the replies its person has seen).
3241
+
3234
3242
  Each message a surface delivers says who wrote it in `actor`, the `ActorFacts` the identity service resolves: `provider` and `subject`, such as `discord` and the user id, `name`, `roles` written `<surface>:role:<name>` (left out where the surface does not know them, such as a Discord DM, which is not the same as none), and `legacyId`, the speaker id 0.8 gave the person, so someone carried over keeps their principal.
3235
3243
  A surface that leaves `actor` out has it read from `authorId`, `authorName`, and `authorRoleIds` with its prefix as the provider, and the host warns once that this goes away in 1.0.
3236
3244
 
@@ -4491,6 +4499,7 @@ Import from the entries listed below; source area files are internal.
4491
4499
  | `ChannelClaim` | `pi-roundtable` | type |
4492
4500
  | `ChannelKey` | `pi-roundtable` | type |
4493
4501
  | `ChatCommand` | `pi-roundtable` | type |
4502
+ | `BlockTextFlavor` | `pi-roundtable` | type |
4494
4503
  | `ChatSurface` | `pi-roundtable` | type |
4495
4504
  | `ClassedHold` | `pi-roundtable` | type |
4496
4505
  | `ClientCallError` | `pi-roundtable` | type |
@@ -4804,6 +4813,7 @@ Import from the entries listed below; source area files are internal.
4804
4813
  | `TestStore` | `pi-roundtable/testing` | type |
4805
4814
  | `UsePostgresOptions` | `pi-roundtable/testing` | type |
4806
4815
  | `describeDb` | `pi-roundtable/testing` | value |
4816
+ | `describeBlocksContract` | `pi-roundtable/testing` | value |
4807
4817
  | `describeSurfaceContract` | `pi-roundtable/testing` | value |
4808
4818
  | `checkSurfaceContract` | `pi-roundtable/testing` | value |
4809
4819
  | `SurfaceContractFailure` | `pi-roundtable/testing` | type |
@@ -4850,9 +4860,11 @@ Import from the entries listed below; source area files are internal.
4850
4860
  | `AgentTurnRunner` | `pi-roundtable/kit` | type |
4851
4861
  | `AssistantLike` | `pi-roundtable/kit` | type |
4852
4862
  | `Backlog` | `pi-roundtable/kit` | type |
4863
+ | `BlockSupport` | `pi-roundtable/kit` | type |
4853
4864
  | `CODEX_IMAGES_PROVIDER` | `pi-roundtable/kit` | value |
4854
4865
  | `CODEX_IMAGE_MODEL` | `pi-roundtable/kit` | value |
4855
4866
  | `CardLimits` | `pi-roundtable/kit` | type |
4867
+ | `ChannelSupport` | `pi-roundtable/kit` | type |
4856
4868
  | `CategoryLayout` | `pi-roundtable/kit` | type |
4857
4869
  | `ChannelMessage` | `pi-roundtable/kit` | type |
4858
4870
  | `ChannelQueue` | `pi-roundtable/kit` | type |
@@ -4998,7 +5010,10 @@ Import from the entries listed below; source area files are internal.
4998
5010
  | `maskSecrets` | `pi-roundtable/kit` | value |
4999
5011
  | `secretMaskExtension` | `pi-roundtable/kit` | value |
5000
5012
  | `skillListExtension` | `pi-roundtable/kit` | value |
5013
+ | `chunksFor` | `pi-roundtable/kit` | value |
5001
5014
  | `splitReply` | `pi-roundtable/kit` | value |
5015
+ | `supportOf` | `pi-roundtable/kit` | value |
5016
+ | `textFor` | `pi-roundtable/kit` | value |
5002
5017
  | `stringList` | `pi-roundtable/kit` | value |
5003
5018
  | `textOf` | `pi-roundtable/kit` | value |
5004
5019
  | `textToolsExtension` | `pi-roundtable/kit` | value |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-roundtable",
3
- "version": "0.37.0",
3
+ "version": "0.38.0",
4
4
  "description": "A plugin-driven Pi agent server for one owner, reached through Discord or the web",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -71,6 +71,7 @@
71
71
  "canvas": "3.2.3",
72
72
  "discord.js": "14.27.0",
73
73
  "pi-jev-compaction": "1.0.0",
74
+ "pi-better-show": "0.2.0",
74
75
  "pi-mcp-adapter": "5.3.0",
75
76
  "pino": "10.4.0",
76
77
  "typebox": "1.3.37",
@@ -6,7 +6,6 @@ import { addressee, type Speaker } from "../identity/speakers.ts";
6
6
  import { HostStoppingError } from "../kernel/errors.ts";
7
7
  import { intercomPlain } from "../presentation/intercom.ts";
8
8
  import { isQuiet } from "../presentation/reply-body.ts";
9
- import { splitReply } from "../presentation/reply-splitter.ts";
10
9
  import type { OutboxEntry, StoredOutboxEntry } from "./agent-outbox.ts";
11
10
  import {
12
11
  agentFailureText,
@@ -141,7 +140,7 @@ export class AgentMessages {
141
140
  #card(channel: ChannelKey, as: Agent, card: IntercomCard): Promise<void> {
142
141
  return this.#host
143
142
  .post(channel, this.#host.current(as), {
144
- chunks: splitReply(intercomPlain(card)),
143
+ chunks: this.#host.chunks(channel, intercomPlain(card)),
145
144
  intercom: card,
146
145
  })
147
146
  .catch((error: unknown) =>
@@ -163,7 +162,8 @@ export class AgentMessages {
163
162
  ): Promise<void> {
164
163
  const { queue, logger } = this.#host.options;
165
164
  await this.#host.post(targetChannel, this.#host.current(sender), {
166
- chunks: splitReply(
165
+ chunks: this.#host.chunks(
166
+ targetChannel,
167
167
  deliveredMessagePost(this.#host.current(target), text),
168
168
  ),
169
169
  });
@@ -0,0 +1,24 @@
1
+ import type { ChannelKey } from "../domain/conversation.ts";
2
+ import type { TurnProgress } from "../domain/progress.ts";
3
+ import { discordIdOf } from "./team-keys.ts";
4
+ import type { TeamTurnsOptions } from "./team-turn-types.ts";
5
+
6
+ /**
7
+ * What a turn in a room shows as it goes, through the room's surface; none in a Discord
8
+ * channel, which shows only the final reply, or on a surface that shows no progress.
9
+ */
10
+ export function roomProgress(
11
+ { surfaces, logger }: Pick<TeamTurnsOptions, "surfaces" | "logger">,
12
+ channel: ChannelKey,
13
+ ): ((event: TurnProgress) => void) | undefined {
14
+ if (discordIdOf(channel) !== undefined || !surfaces?.progress)
15
+ return undefined;
16
+ return (event) => {
17
+ // pi-lens-ignore: no-unknown-parameters — a rejection reason is unknown; it only reaches the logger
18
+ surfaces
19
+ .progress?.(channel, event)
20
+ .catch((error: unknown) =>
21
+ logger.warn({ channel, err: error }, "progress not shown"),
22
+ );
23
+ };
24
+ }
@@ -146,6 +146,8 @@ export interface TurnHost {
146
146
  intercom?: IntercomCard;
147
147
  },
148
148
  ): Promise<void>;
149
+ /** The messages that carry an agent's text to the channel, cut for the surface that serves it. */
150
+ chunks(channel: ChannelKey, text: string): string[];
149
151
  /** The agent's latest row. */
150
152
  current(agent: Agent): Agent;
151
153
  /** Whether the speaker's tier holds every tool of the held actions. */
@@ -1,5 +1,6 @@
1
1
  import { channelKey, parseChannelKey } from "../contract/surface.ts";
2
2
  import type { TurnAttachments } from "../domain/attachment.ts";
3
+ import { supportOf } from "../domain/block-support.ts";
3
4
  import type {
4
5
  ChannelKey,
5
6
  IntercomCard,
@@ -14,7 +15,7 @@ import type { AgentTurnScope } from "../domain/ports.ts";
14
15
  import type { TurnProgress } from "../domain/progress.ts";
15
16
  import type { Speaker } from "../identity/speakers.ts";
16
17
  import { isQuiet, replyBody } from "../presentation/reply-body.ts";
17
- import { splitReply } from "../presentation/reply-splitter.ts";
18
+ import { chunksFor } from "../presentation/reply-chunks.ts";
18
19
  import { endOf, settleTurn } from "../routing/settle-turn.ts";
19
20
  import { toolTiers } from "../runtime/tool-tiers.ts";
20
21
  import { withReplyFiles } from "../shared/reply-files.ts";
@@ -22,6 +23,7 @@ import { AgentMessages } from "./agent-messages.ts";
22
23
  import type { Agent } from "./agent-store.ts";
23
24
  import { GroupTurns } from "./group-turns.ts";
24
25
  import { HelperWork } from "./helper-work.ts";
26
+ import { roomProgress } from "./room-progress.ts";
25
27
  import { type Routes, routesOf } from "./routes.ts";
26
28
  import { mayApprove } from "./team-approval.ts";
27
29
  import {
@@ -88,6 +90,7 @@ export class TeamTurns {
88
90
  current: (agent) => this.#current(agent),
89
91
  mayApprove: (speaker, pending) => this.#mayApprove(speaker, pending),
90
92
  turnChannel: (scope) => this.turnChannel(scope),
93
+ chunks: (channel, text) => this.#chunks(channel, text),
91
94
  };
92
95
  this.#messages = new AgentMessages(host);
93
96
  this.#groups = new GroupTurns(host);
@@ -222,7 +225,7 @@ export class TeamTurns {
222
225
  };
223
226
  this.#options.events?.turnStarted(turn);
224
227
  const interim = this.#interim(postTo, agent);
225
- const progress = this.#progress(postTo);
228
+ const progress = roomProgress(this.#options, postTo);
226
229
  let result: TurnResult;
227
230
  try {
228
231
  result = await settleTurn(
@@ -265,7 +268,10 @@ export class TeamTurns {
265
268
  { agent: agent.name, channel: postTo },
266
269
  "unattended turn had nothing to say; nothing posted",
267
270
  );
268
- else await this.#post(postTo, this.#current(agent), replyBody(result));
271
+ else {
272
+ const body = replyBody(result, this.#support(postTo));
273
+ await this.#post(postTo, this.#current(agent), body);
274
+ }
269
275
  } catch (error) {
270
276
  logger.error({ agent: agent.name, err: error }, "agent reply not posted");
271
277
  } finally {
@@ -297,22 +303,14 @@ export class TeamTurns {
297
303
  return this.#options.store.agent(agent.name) ?? agent;
298
304
  }
299
305
 
300
- /**
301
- * What a turn in a room shows as it goes, through the room's surface; none in a Discord
302
- * channel, which shows only the final reply, or on a surface that shows no progress.
303
- */
304
- #progress(channel: ChannelKey): ((event: TurnProgress) => void) | undefined {
305
- const { surfaces, logger } = this.#options;
306
- if (discordIdOf(channel) !== undefined || !surfaces?.progress)
307
- return undefined;
308
- return (event) => {
309
- // pi-lens-ignore: no-unknown-parameters — a rejection reason is unknown; it only reaches the logger
310
- surfaces
311
- .progress?.(channel, event)
312
- .catch((error: unknown) =>
313
- logger.warn({ channel, err: error }, "progress not shown"),
314
- );
315
- };
306
+ /** What the surface that serves the channel does there (see `supportOf`). */
307
+ #support(channel: ChannelKey) {
308
+ return supportOf(this.#options.surfaces?.of(channel), channel);
309
+ }
310
+
311
+ /** The messages that carry an agent's text to the channel, cut for the surface that serves it. */
312
+ #chunks(channel: ChannelKey, text: string): string[] {
313
+ return chunksFor(this.#support(channel), text);
316
314
  }
317
315
 
318
316
  /**
@@ -327,6 +325,9 @@ export class TeamTurns {
327
325
  if (!surfaces || !first) return undefined;
328
326
  return {
329
327
  ...(first.tools === false ? { tools: false } : {}),
328
+ // The poster cuts text for the surface the posts go to.
329
+ ...(first.blocks ? { blocks: first.blocks } : {}),
330
+ ...(first.blockText ? { blockText: first.blockText } : {}),
330
331
  post: async (text) => {
331
332
  if (!channelOwner(store, channel, this.#rooms(channel)))
332
333
  throw new AgentError(`${channel} is archived`);
@@ -418,9 +419,9 @@ export class TeamTurns {
418
419
  */
419
420
  async postAs(caller: AgentTurnScope, text: string): Promise<void> {
420
421
  const agent = this.#options.store.activeAgent(caller.name);
421
- await this.#post(this.turnChannel(caller), this.#current(agent), {
422
- chunks: splitReply(text),
423
- });
422
+ const channel = this.turnChannel(caller);
423
+ const chunks = this.#chunks(channel, text);
424
+ await this.#post(channel, this.#current(agent), { chunks });
424
425
  }
425
426
 
426
427
  /** The channel the scope's turns run in: the group's in a group round, otherwise its own. */
@@ -452,7 +453,7 @@ export class TeamTurns {
452
453
  : this.routes.primary(coordinator.name);
453
454
  if (!home)
454
455
  throw new AgentError(`${coordinator.name} has no room to post in`);
455
- await this.#post(home, coordinator, { chunks: splitReply(text) });
456
+ await this.#post(home, coordinator, { chunks: this.#chunks(home, text) });
456
457
  }
457
458
 
458
459
  message(...args: Parameters<AgentMessages["message"]>): string {
@@ -1,3 +1,8 @@
1
+ import type { BlockKind } from "pi-better-show";
2
+ import type {
3
+ BlockTextFlavor,
4
+ ChannelSupport,
5
+ } from "../domain/block-support.ts";
1
6
  import type { OutboundReply, PostAuthor } from "../domain/conversation.ts";
2
7
  import type { InterimMessage, InterimPosts } from "../domain/interim.ts";
3
8
  import type { TurnProgress } from "../domain/progress.ts";
@@ -131,6 +136,24 @@ export interface ChatSurface {
131
136
  * appended; a turn whose channel has no surface gets none either.
132
137
  */
133
138
  readonly formatting?: string;
139
+ /**
140
+ * The display-block kinds this surface draws itself, such as `table` or `mermaid` (see
141
+ * pi-better-show). A reply reaches `sendReply` whole, with the fences of those kinds intact; a
142
+ * block of any other kind arrives as text, and a surface that lists none gets every block as
143
+ * text. Absent = none.
144
+ */
145
+ readonly blocks?: readonly BlockKind[];
146
+ /**
147
+ * How a block this surface does not draw reads as text: `discord` (Markdown with a native
148
+ * `diff` fence), `line` (plain text without Markdown markup), or `plain`. Absent = `discord`.
149
+ */
150
+ readonly blockText?: BlockTextFlavor;
151
+ /**
152
+ * What differs in one channel of this surface: its `formatting`, `blocks` or `blockText`
153
+ * replace the surface's for a turn that replies there, such as a host's room on a surface that
154
+ * draws blocks only in its own. Absent, or undefined for a channel = the surface's own.
155
+ */
156
+ support?(channel: ChannelKey): ChannelSupport | undefined;
134
157
  /**
135
158
  * Connects and delivers every incoming message; the host passes its conversation router. A
136
159
  * message whose channel key has another prefix is logged and dropped.
@@ -30,7 +30,7 @@ import type { PromptScope, Prompts } from "../interactions/prompts.ts";
30
30
  import type { Logger } from "../kernel/log.ts";
31
31
  import type { OwnerOperations } from "../modules/discord-admin/discord-admin.ts";
32
32
  import type { MemberJoinedEvent } from "../plugin-api/event-types.ts";
33
- import { splitReply } from "../presentation/reply-splitter.ts";
33
+ import { chunksFor } from "../presentation/reply-chunks.ts";
34
34
  import { threadsOfHost } from "../threads/host-threads.ts";
35
35
  import { DiscordAgentChannels, DiscordDashboard } from "./agent-discord.ts";
36
36
  import {
@@ -418,7 +418,8 @@ export class DiscordSurface
418
418
  /** Sends a Discord user a direct message, split as a reply is. */
419
419
  async sendDirect(userId: string, text: string): Promise<void> {
420
420
  const user = await this.#client.users.fetch(userId);
421
- for (const chunk of splitReply(text)) await user.send({ content: chunk });
421
+ for (const chunk of chunksFor(undefined, text))
422
+ await user.send({ content: chunk });
422
423
  }
423
424
 
424
425
  /** @deprecated The primary owner's direct-message channel; see `DiscordConnection.ownerChannel`. */
@@ -5,7 +5,7 @@ import {
5
5
  ThreadAutoArchiveDuration,
6
6
  } from "discord.js";
7
7
  import type { InterimMessage } from "../domain/interim.ts";
8
- import { splitReply } from "../presentation/reply-splitter.ts";
8
+ import { chunksFor } from "../presentation/reply-chunks.ts";
9
9
  import type { ThreadHost } from "../threads/dispatch-threads.ts";
10
10
 
11
11
  /** Parents a dispatch thread may start in; DMs, threads, forums, and voice chats keep posting in place. */
@@ -51,7 +51,8 @@ export class DiscordThreadHost implements ThreadHost {
51
51
 
52
52
  async post(threadId: string, text: string): Promise<void> {
53
53
  const thread = await this.#thread(threadId);
54
- for (const chunk of splitReply(text)) await thread.send({ content: chunk });
54
+ for (const chunk of chunksFor(undefined, text))
55
+ await thread.send({ content: chunk });
55
56
  }
56
57
 
57
58
  async send(threadId: string, text: string): Promise<InterimMessage> {
@@ -13,7 +13,7 @@ import {
13
13
  intercomHeading,
14
14
  intercomSummary,
15
15
  } from "../presentation/intercom.ts";
16
- import { splitReply } from "../presentation/reply-splitter.ts";
16
+ import { chunksFor } from "../presentation/reply-chunks.ts";
17
17
  import type { InteractionModule } from "./interaction-module.ts";
18
18
 
19
19
  /** The custom id of a card's open button starts with this; the text's id follows. */
@@ -70,7 +70,7 @@ export function intercomPost(card: IntercomCard, texts: IntercomTexts) {
70
70
  export function intercomReplies(text: string) {
71
71
  const flags = MessageFlags.Ephemeral as const;
72
72
  const allowedMentions = { parse: [] as never[] };
73
- const parts = splitReply(text);
73
+ const parts = chunksFor(undefined, text);
74
74
  if (parts.length <= MAX_PARTS)
75
75
  return parts.map((content) => ({ content, flags, allowedMentions }));
76
76
  return [
@@ -0,0 +1,41 @@
1
+ import type { BlockKind } from "pi-better-show";
2
+
3
+ /** How a block that a surface does not draw reads as text. */
4
+ export type BlockTextFlavor = "discord" | "line" | "plain";
5
+
6
+ /** What a surface says about display blocks (see pi-better-show): the kinds it draws and the text it reads the rest as. */
7
+ export interface BlockSupport {
8
+ /** The kinds drawn by the surface itself; absent = none. */
9
+ readonly blocks?: readonly BlockKind[];
10
+ /** The flavor of text for the other kinds; absent = `discord`. */
11
+ readonly blockText?: BlockTextFlavor;
12
+ }
13
+
14
+ /** What a surface says about one channel where it differs from the surface's own; a field that is absent changes nothing. */
15
+ export interface ChannelSupport extends BlockSupport {
16
+ /** The formatting guidance given to a turn that replies in the channel. */
17
+ readonly formatting?: string;
18
+ }
19
+
20
+ /**
21
+ * What a surface does in `channel`: its own `formatting`, `blocks` and `blockText`, over which the
22
+ * channel's `support` lays what differs (a host's room on an app, which draws no blocks).
23
+ */
24
+ export function supportOf(
25
+ surface:
26
+ | (ChannelSupport & {
27
+ support?(channel: string): ChannelSupport | undefined;
28
+ })
29
+ | undefined,
30
+ channel: string,
31
+ ): ChannelSupport {
32
+ if (!surface) return {};
33
+ const own = {
34
+ ...(surface.formatting === undefined
35
+ ? {}
36
+ : { formatting: surface.formatting }),
37
+ ...(surface.blocks ? { blocks: surface.blocks } : {}),
38
+ ...(surface.blockText ? { blockText: surface.blockText } : {}),
39
+ };
40
+ return { ...own, ...surface.support?.(channel) };
41
+ }
@@ -1,3 +1,5 @@
1
+ import type { BlockSupport } from "./block-support.ts";
2
+
1
3
  /** A message an interim post made, which the turn edits in place as it goes. */
2
4
  export interface InterimMessage {
3
5
  edit(text: string): Promise<void>;
@@ -6,9 +8,10 @@ export interface InterimMessage {
6
8
  /**
7
9
  * Where a running turn posts the text it writes before its final answer: the channel the
8
10
  * final reply goes to, under the same name. Each call posts one ordinary message of at most
9
- * Discord's 2000 characters.
11
+ * Discord's 2000 characters. The surface's block support (`blocks`, `blockText`) says how the text
12
+ * is cut: the host's surface port fills it in from the surface that serves the channel.
10
13
  */
11
- export interface InterimPosts {
14
+ export interface InterimPosts extends BlockSupport {
12
15
  post(text: string): Promise<InterimMessage>;
13
16
  /**
14
17
  * Whether the turn's progress message names the tools it called, on a line of its own; true
@@ -1,8 +1,9 @@
1
1
  import type { SurfacePort } from "../contract/surface.ts";
2
2
  import { parseChannelKey } from "../contract/surface.ts";
3
+ import { supportOf } from "../domain/block-support.ts";
3
4
  import type { ChannelKey } from "../domain/conversation.ts";
4
5
  import type { Logger } from "../kernel/log.ts";
5
- import { splitReply } from "../presentation/reply-splitter.ts";
6
+ import { chunksFor } from "../presentation/reply-chunks.ts";
6
7
  import type {
7
8
  DirectChannelProvider,
8
9
  DirectChannels,
@@ -49,7 +50,7 @@ export interface DeliveryRouter {
49
50
 
50
51
  export function deliveryRouter(
51
52
  providers: () => readonly DirectChannelProvider[],
52
- surfaces: Pick<SurfacePort, "sendReply">,
53
+ surfaces: Pick<SurfacePort, "sendReply"> & Partial<Pick<SurfacePort, "of">>,
53
54
  logger?: Pick<Logger, "warn">,
54
55
  ): DeliveryRouter {
55
56
  const order = (origin: Origin): readonly DirectChannelProvider[] => {
@@ -124,7 +125,11 @@ export function deliveryRouter(
124
125
  await reached.provider.deliver(principalId, text);
125
126
  else
126
127
  await surfaces.sendReply(reached.channel, {
127
- chunks: splitReply(text),
128
+ // The text of a notice may be an agent's (the notify tool's), block fences included.
129
+ chunks: chunksFor(
130
+ supportOf(surfaces.of?.(reached.channel), reached.channel),
131
+ text,
132
+ ),
128
133
  });
129
134
  await mirrored(reached.provider, principalId, text);
130
135
  return true;
@@ -92,7 +92,7 @@ export interface DirectChannels {
92
92
  /** The direct channels over the providers the host linked, posting through its surfaces where a provider does not deliver itself. */
93
93
  export function directChannelsPort(
94
94
  providers: () => readonly DirectChannelProvider[],
95
- surfaces: Pick<SurfacePort, "sendReply">,
95
+ surfaces: Pick<SurfacePort, "sendReply"> & Partial<Pick<SurfacePort, "of">>,
96
96
  logger?: Pick<Logger, "warn">,
97
97
  ): DirectChannels {
98
98
  const router = deliveryRouter(providers, surfaces, logger);
@@ -0,0 +1,29 @@
1
+ import { parentPort, workerData } from "node:worker_threads";
2
+ import { mermaidText } from "pi-better-show/server";
3
+
4
+ /**
5
+ * Draws Mermaid sources as text off the host's thread (see `diagram-text.ts`). The result goes back
6
+ * through shared memory, since the host waits on it without running its event loop: word 0 is the
7
+ * state (1 = working, 2 = answered), word 1 the byte length of the text, or -1 for none. Loaded
8
+ * outside a worker, which is what importing every module of the core does, it does nothing.
9
+ */
10
+ const shared = (workerData as { shared?: SharedArrayBuffer } | null)?.shared;
11
+
12
+ if (shared && parentPort) {
13
+ const head = new Int32Array(shared, 0, 4);
14
+ const body = new Uint8Array(shared, 16);
15
+ parentPort.on("message", (source: string) => {
16
+ const text = mermaidText(source);
17
+ const bytes =
18
+ text === undefined ? undefined : new TextEncoder().encode(text);
19
+ if (!bytes || bytes.length > body.length) head[1] = -1;
20
+ else {
21
+ body.set(bytes);
22
+ head[1] = bytes.length;
23
+ }
24
+ Atomics.store(head, 0, 2);
25
+ Atomics.notify(head, 0);
26
+ });
27
+ Atomics.store(head, 0, 1);
28
+ Atomics.notify(head, 0);
29
+ }
@@ -0,0 +1,130 @@
1
+ import { Worker } from "node:worker_threads";
2
+
3
+ /** The most source a diagram may have to be drawn as text; a longer one is shown as its source. */
4
+ export const MAX_DIAGRAM_TEXT_BYTES = 3 * 1024;
5
+ /** The longest the host waits for the drawings of one reply. The drawing is not bounded by the size of its source. */
6
+ export const DIAGRAM_TEXT_DEADLINE_MS = 500;
7
+ /** The most diagrams drawn afresh for one reply; the others are shown as their source. */
8
+ export const MAX_DRAWN_PER_REPLY = 3;
9
+ /** How long the first drawing of a worker may take to start, with the drawing library loading. */
10
+ const START_MS = 5_000;
11
+ const KEPT = 200;
12
+ /** How long a source that overran stays undrawn before it is tried again: on a loaded host an overrun is no verdict on the source. */
13
+ const OVERRUN_KEPT_MS = 10 * 60_000;
14
+ const RESULT_BYTES = 256 * 1024;
15
+
16
+ interface Drawer {
17
+ worker: Worker;
18
+ head: Int32Array;
19
+ body: Uint8Array;
20
+ }
21
+
22
+ let drawer: Drawer | undefined;
23
+ /** Set once a worker could not be started: the host does not try again for the life of the process. */
24
+ let unavailable = false;
25
+ /** What was drawn, by source; `null` for one that could not be, so it is not tried again. */
26
+ const drawn = new Map<string, string | null>();
27
+ /** When each source that overran may be tried again. */
28
+ const overran = new Map<string, number>();
29
+
30
+ function start(): Drawer | undefined {
31
+ const shared = new SharedArrayBuffer(16 + RESULT_BYTES);
32
+ const head = new Int32Array(shared, 0, 4);
33
+ const worker = new Worker(
34
+ new URL("./diagram-text-worker.ts", import.meta.url),
35
+ { workerData: { shared } },
36
+ );
37
+ // An idle drawer does not keep the host running.
38
+ worker.unref();
39
+ worker.on("error", () => {
40
+ if (drawer?.worker === worker) drawer = undefined;
41
+ });
42
+ if (Atomics.wait(head, 0, 0, START_MS) === "timed-out") {
43
+ void worker.terminate();
44
+ unavailable = true;
45
+ return undefined;
46
+ }
47
+ return { worker, head, body: new Uint8Array(shared, 16) };
48
+ }
49
+
50
+ function stop(current: Drawer): void {
51
+ void current.worker.terminate();
52
+ if (drawer === current) drawer = undefined;
53
+ }
54
+
55
+ /**
56
+ * A drawer of Mermaid diagrams as Unicode box drawing for one reply: it gives undefined for a source
57
+ * that cannot be shown right (see `mermaidText` of `pi-better-show/server`), is longer than
58
+ * `MAX_DIAGRAM_TEXT_BYTES`, or does not fit the reply's budget. The text drawing grows with the shape
59
+ * of the diagram, not its size (a 250-byte chain of states needs about a minute), so it runs in a
60
+ * worker the host waits on, and the worker is dropped when it overruns. The host's thread is held for
61
+ * `DIAGRAM_TEXT_DEADLINE_MS` in all across the reply's sources, and at most `MAX_DRAWN_PER_REPLY` are
62
+ * drawn afresh; a source seen before answers from memory. Callers fall back to the source.
63
+ *
64
+ * What is remembered: a source the worker refused, and for ten minutes one that overran a whole deadline; a source
65
+ * left undrawn for the budget, or because no worker could be started, is no verdict and is tried
66
+ * again in a later reply.
67
+ */
68
+ export function diagramDrawer(): (source: string) => string | undefined {
69
+ let left = DIAGRAM_TEXT_DEADLINE_MS;
70
+ let fresh = 0;
71
+ return (source) => {
72
+ if (Buffer.byteLength(source) > MAX_DIAGRAM_TEXT_BYTES) return undefined;
73
+ const known = drawn.get(source);
74
+ if (known === null && (overran.get(source) ?? Infinity) <= Date.now()) {
75
+ drawn.delete(source);
76
+ overran.delete(source);
77
+ } else if (known !== undefined) {
78
+ drawn.delete(source);
79
+ drawn.set(source, known);
80
+ return known ?? undefined;
81
+ }
82
+ if (fresh >= MAX_DRAWN_PER_REPLY || left <= 0) return undefined;
83
+ fresh += 1;
84
+ const waitMs = left;
85
+ const started = performance.now();
86
+ const result = draw(source, waitMs);
87
+ left -= performance.now() - started;
88
+ if (typeof result === "object") remember(source, result.text);
89
+ else if (result === "refused") remember(source, null);
90
+ else if (result === "slow" && waitMs >= DIAGRAM_TEXT_DEADLINE_MS) {
91
+ remember(source, null);
92
+ overran.set(source, Date.now() + OVERRUN_KEPT_MS);
93
+ }
94
+ return typeof result === "object" ? result.text : undefined;
95
+ };
96
+ }
97
+
98
+ /** One source on its own, with a whole reply's budget. */
99
+ export function diagramText(source: string): string | undefined {
100
+ return diagramDrawer()(source);
101
+ }
102
+
103
+ function remember(source: string, text: string | null): void {
104
+ drawn.set(source, text);
105
+ if (drawn.size > KEPT)
106
+ for (const oldest of drawn.keys()) {
107
+ drawn.delete(oldest);
108
+ overran.delete(oldest);
109
+ break;
110
+ }
111
+ }
112
+
113
+ function draw(
114
+ source: string,
115
+ waitMs: number,
116
+ ): { text: string } | "refused" | "slow" | "unavailable" {
117
+ if (unavailable) return "unavailable";
118
+ drawer ??= start();
119
+ const current = drawer;
120
+ if (!current) return "unavailable";
121
+ Atomics.store(current.head, 0, 1);
122
+ current.worker.postMessage(source);
123
+ if (Atomics.wait(current.head, 0, 1, waitMs) === "timed-out") {
124
+ stop(current);
125
+ return "slow";
126
+ }
127
+ const length = current.head[1] ?? -1;
128
+ if (length < 0) return "refused";
129
+ return { text: new TextDecoder().decode(current.body.slice(0, length)) };
130
+ }
@@ -1,10 +1,17 @@
1
+ import type { BlockSupport } from "../domain/block-support.ts";
1
2
  import type { ReplyFile, TurnResult } from "../domain/conversation.ts";
2
3
  import { failureNotice } from "./failure-notice.ts";
3
- import { splitReply } from "./reply-splitter.ts";
4
+ import { chunksFor } from "./reply-chunks.ts";
4
5
  import { thinkingLine } from "./thinking-line.ts";
5
6
 
6
- /** What a turn posts: its answer with a thinking line, or the failure or stopped notice. */
7
- export function replyBody(result: TurnResult): {
7
+ /**
8
+ * What a turn posts: its answer with a thinking line, or the failure or stopped notice. The
9
+ * answer is cut for `surface`, the one it is posted on (see `chunksFor`); none = as for Discord.
10
+ */
11
+ export function replyBody(
12
+ result: TurnResult,
13
+ surface?: BlockSupport,
14
+ ): {
8
15
  thinking?: string;
9
16
  chunks: string[];
10
17
  files?: ReplyFile[];
@@ -19,7 +26,7 @@ export function replyBody(result: TurnResult): {
19
26
  const thinking = result.thinking ? thinkingLine(result.thinking) : undefined;
20
27
  return {
21
28
  ...(thinking ? { thinking } : {}),
22
- chunks: splitReply(result.text),
29
+ chunks: chunksFor(surface, result.text),
23
30
  ...(result.files?.length ? { files: result.files } : {}),
24
31
  };
25
32
  }
@@ -0,0 +1,46 @@
1
+ import { type BlockKind, parse, toText } from "pi-better-show";
2
+ import type { BlockSupport, BlockTextFlavor } from "../domain/block-support.ts";
3
+ import { diagramDrawer } from "./diagram-text.ts";
4
+ import { splitReply } from "./reply-splitter.ts";
5
+
6
+ /**
7
+ * The messages that carry agent-written text to a surface. A display block (a fence such as
8
+ * `table` or `mermaid`, or a GitHub alert) is YAML that only a surface that draws it should
9
+ * see, so a block of a kind the surface does not list in `blocks` is turned into text first.
10
+ * A surface that draws any block gets the result whole, since cutting a fence breaks the block;
11
+ * any other surface gets it split into messages within Discord's limit. A block left open at the end
12
+ * of the text is still a block; one that does not parse becomes a plain code block.
13
+ */
14
+ export function chunksFor(
15
+ surface: BlockSupport | undefined,
16
+ text: string,
17
+ ): string[] {
18
+ const converted = textFor(surface, text);
19
+ if ((surface?.blocks ?? []).length === 0) return splitReply(converted);
20
+ return converted.trim() ? [converted] : [];
21
+ }
22
+
23
+ /**
24
+ * The text as `chunksFor` would send it, in one piece: a block of a kind the surface does not draw
25
+ * is text, and nothing is cut. For a surface that shows a message however long it is, such as a
26
+ * web chat's, where cutting would split a code fence.
27
+ */
28
+ export function textFor(
29
+ surface: BlockSupport | undefined,
30
+ text: string,
31
+ ): string {
32
+ return convert(text, surface?.blocks ?? [], surface?.blockText ?? "discord");
33
+ }
34
+
35
+ function convert(
36
+ text: string,
37
+ draws: readonly BlockKind[],
38
+ flavor: BlockTextFlavor,
39
+ ): string {
40
+ const segments = parse(text);
41
+ const blocks = segments.filter((segment) => segment.type !== "markdown");
42
+ // Toward a surface that draws all of them the text is already right, and rejoining the
43
+ // segments would only change its spacing.
44
+ if (blocks.every((block) => draws.includes(block.kind))) return text;
45
+ return toText(segments, { flavor, mermaid: diagramDrawer(), keep: draws });
46
+ }
@@ -5,6 +5,7 @@ import type {
5
5
  ConversationVisibility,
6
6
  } from "../conversations/conversation-registry.ts";
7
7
  import type { TurnAttachments } from "../domain/attachment.ts";
8
+ import { supportOf } from "../domain/block-support.ts";
8
9
  import type { ClientPort } from "../domain/client.ts";
9
10
  import type { TurnResult } from "../domain/conversation.ts";
10
11
  import type { TurnConversation } from "../domain/ports.ts";
@@ -247,7 +248,11 @@ export function conversationTurns(
247
248
  "unattended turn had nothing to say; nothing posted",
248
249
  );
249
250
  else if (input.reply) await input.reply(result);
250
- else await surfaces.sendReply(channel, replyBody(result));
251
+ else
252
+ await surfaces.sendReply(
253
+ channel,
254
+ replyBody(result, supportOf(surfaces.of(channel), channel)),
255
+ );
251
256
  } catch (error) {
252
257
  logger.error({ channel, kind, err: error }, "reply not posted");
253
258
  } finally {
@@ -1,5 +1,6 @@
1
1
  import type { ChatSurface, SurfacePort } from "../contract/surface.ts";
2
2
  import { parseChannelKey } from "../contract/surface.ts";
3
+ import { supportOf } from "../domain/block-support.ts";
3
4
  import type { ChannelKey } from "../domain/sessions.ts";
4
5
  import type { Speaker } from "../identity/speakers.ts";
5
6
  import {
@@ -61,7 +62,19 @@ export function surfacePort(
61
62
  .filter((surface) => surface.agentRooms === true)
62
63
  .map((surface) => surface.surface),
63
64
  names: () => linked().map((surface) => surface.surface),
64
- interim: (channel, as) => of(channel)?.interim?.(channel, as),
65
+ interim: (channel, as) => {
66
+ const surface = of(channel);
67
+ const posts = surface?.interim?.(channel, as);
68
+ if (!surface || !posts) return posts;
69
+ // The poster cuts text for the surface it posts on, which only the port knows.
70
+ const { blocks, blockText } = supportOf(surface, channel);
71
+ return {
72
+ ...(posts.tools === undefined ? {} : { tools: posts.tools }),
73
+ ...(blocks ? { blocks } : {}),
74
+ ...(blockText ? { blockText } : {}),
75
+ post: (text) => posts.post(text),
76
+ };
77
+ },
65
78
  progress: async (channel, event) => {
66
79
  await of(channel)?.progress?.(channel, event);
67
80
  },
@@ -1,10 +1,8 @@
1
1
  import type { InterimMessage, InterimPosts } from "../domain/interim.ts";
2
2
  import type { TurnRequest } from "../domain/ports.ts";
3
3
  import type { Logger } from "../kernel/log.ts";
4
- import {
5
- DISCORD_MESSAGE_LIMIT,
6
- splitReply,
7
- } from "../presentation/reply-splitter.ts";
4
+ import { chunksFor } from "../presentation/reply-chunks.ts";
5
+ import { DISCORD_MESSAGE_LIMIT } from "../presentation/reply-splitter.ts";
8
6
  import { textOf } from "../shared/session-messages.ts";
9
7
  import type { PiAgentRuntimeOptions } from "./runtime-types.ts";
10
8
 
@@ -13,11 +11,12 @@ export const PRIMARY_CHARS = 400;
13
11
  /** The progress message is edited at most this often; its last state always lands. */
14
12
  export const PROGRESS_EDIT_MS = 1_500;
15
13
 
16
- const STRUCTURE = /^\s{0,3}(#{1,6}\s|```|~~~|[-*+]\s|\d+[.)]\s|\|.*\|)/m;
14
+ const STRUCTURE =
15
+ /^\s{0,3}(#{1,6}\s|```|~~~|[-*+]\s|\d+[.)]\s|\|.*\|)|^\s{0,3}>\s*\[![A-Z]+\]/m;
17
16
 
18
17
  /**
19
18
  * Whether an intermediate text is content the owner must read, such as a proposal or findings:
20
- * long, or written with a Markdown heading, list, table, or code fence. Shorter narration
19
+ * long, or written with a Markdown heading, list, table, code fence, or GitHub alert. Shorter narration
21
20
  * between tool calls goes to the progress message instead.
22
21
  */
23
22
  export function isPrimaryText(
@@ -113,7 +112,7 @@ export class InterimPoster {
113
112
  if (!text) return;
114
113
  if (isPrimaryText(text, this.#options.primaryChars)) {
115
114
  this.#endRun();
116
- for (const chunk of splitReply(text))
115
+ for (const chunk of chunksFor(this.#posts, text))
117
116
  this.#enqueue(async () => {
118
117
  await this.#posts.post(chunk);
119
118
  }, "interim text not posted");
@@ -5,6 +5,7 @@ import type {
5
5
  HeldActionStore,
6
6
  RuntimeDeps,
7
7
  } from "../contract/runtime.ts";
8
+ import { supportOf } from "../domain/block-support.ts";
8
9
  import type { ChannelKey } from "../domain/conversation.ts";
9
10
  import type { InterimTextMode } from "../domain/interim.ts";
10
11
  import {
@@ -166,7 +167,7 @@ export function runtimePlugin(
166
167
  context.surfaces.prompts(channel, scope);
167
168
  const agents = () => options.agents?.current();
168
169
  const formatting = (channel: ChannelKey) =>
169
- context.surfaces.of(channel)?.formatting;
170
+ supportOf(context.surfaces.of(channel), channel).formatting;
170
171
  const running: AgentRuntime = providers.filled.has("runtime")
171
172
  ? providers.runtime(
172
173
  runtimeDeps({
@@ -0,0 +1,59 @@
1
+ import { describe, test } from "bun:test";
2
+ import type { SurfaceContractSubject } from "./surface-contract.ts";
3
+ import {
4
+ expectThat,
5
+ type Running,
6
+ runCheck,
7
+ seen,
8
+ until,
9
+ } from "./surface-contract-support.ts";
10
+
11
+ /** The contract of a surface that lists `ChatSurface.blocks`: what it says it draws arrives whole. */
12
+ export const BLOCK_CHECKS: readonly {
13
+ name: string;
14
+ applies(subject: SurfaceContractSubject): boolean;
15
+ run(running: Running): Promise<void>;
16
+ }[] = [
17
+ {
18
+ name: "shows a block of a kind it draws whole, longer than a message",
19
+ applies: (subject) => (subject.surface.blocks?.length ?? 0) > 0,
20
+ run: async (running) => {
21
+ const { surface, channel } = running.subject;
22
+ const kind = surface.blocks?.[0] ?? "table";
23
+ // What the block holds is the kind's to read; the surface must not cut or reflow it.
24
+ const block = [
25
+ `\`\`\`${kind}`,
26
+ ...Array.from({ length: 120 }, (_, i) => `row ${i}: ${"x".repeat(30)}`),
27
+ "```",
28
+ ].join("\n");
29
+ expectThat(block.length > 2000, "the block is longer than a message");
30
+ await surface.sendReply(channel, { chunks: [`Here it is.\n\n${block}`] });
31
+ await until(
32
+ () => seen(running, "reply").length > 0,
33
+ "the person sees the reply",
34
+ );
35
+ const reply = seen(running, "reply")[0];
36
+ expectThat(
37
+ reply?.kind === "reply" && reply.text.includes(block),
38
+ `the ${kind} block did not arrive whole`,
39
+ );
40
+ },
41
+ },
42
+ ];
43
+
44
+ /**
45
+ * Registers only the display-block part of the contract, for a surface that cannot run the whole
46
+ * chat contract (its person writes through a browser, say). The subject needs `surface`,
47
+ * `channel` and `observations()` showing the replies its person has seen; `write` is never called.
48
+ */
49
+ export function describeBlocksContract(
50
+ name: string,
51
+ make: () => Promise<SurfaceContractSubject>,
52
+ ): void {
53
+ describe(`${name} keeps the display-block contract`, () => {
54
+ for (const check of BLOCK_CHECKS)
55
+ test(check.name, async () => {
56
+ await runCheck(check, make);
57
+ });
58
+ });
59
+ }
@@ -9,6 +9,10 @@ import type {
9
9
  Questionnaire,
10
10
  QuestionnaireAnswer,
11
11
  } from "../interactions/questionnaire.ts";
12
+ import { BLOCK_CHECKS } from "./surface-contract-blocks.ts";
13
+
14
+ export { describeBlocksContract } from "./surface-contract-blocks.ts";
15
+
12
16
  import { QUESTIONNAIRE_CHECKS } from "./surface-contract-questionnaire.ts";
13
17
  import {
14
18
  answeredOnlyByThem,
@@ -442,6 +446,7 @@ const CHECKS: readonly Check[] = [
442
446
  );
443
447
  },
444
448
  },
449
+ ...BLOCK_CHECKS,
445
450
  ...QUESTIONNAIRE_CHECKS,
446
451
  ];
447
452
 
@@ -12,6 +12,7 @@ import {
12
12
  type SurfacePort,
13
13
  type SurfaceThreads,
14
14
  } from "../contract/surface.ts";
15
+ import { supportOf } from "../domain/block-support.ts";
15
16
  import type { ChannelKey } from "../domain/conversation.ts";
16
17
  import type { InterimMessage, InterimPosts } from "../domain/interim.ts";
17
18
  import { messages } from "../i18n/index.ts";
@@ -247,6 +248,10 @@ export class DispatchThreads {
247
248
  const { id } = parseChannelKey(channel);
248
249
  let closed = false;
249
250
  const send = threads.send?.bind(threads);
251
+ const { blocks, blockText } = supportOf(
252
+ this.#options.surfaces?.of(channel),
253
+ channel,
254
+ );
250
255
  const post = async (text: string) => {
251
256
  try {
252
257
  await threads.post(id, text);
@@ -262,7 +267,16 @@ export class DispatchThreads {
262
267
  channel,
263
268
  mention,
264
269
  post,
265
- ...(send ? { interim: { post: (text: string) => send(id, text) } } : {}),
270
+ ...(send
271
+ ? {
272
+ interim: {
273
+ // The poster cuts text for the surface the thread is on.
274
+ ...(blocks ? { blocks } : {}),
275
+ ...(blockText ? { blockText } : {}),
276
+ post: (text: string) => send(id, text),
277
+ },
278
+ }
279
+ : {}),
266
280
  close: async (report) => {
267
281
  if (closed) return;
268
282
  closed = true;
package/src/index.ts CHANGED
@@ -154,6 +154,7 @@ export type {
154
154
  TurnAttachments,
155
155
  } from "./core/domain/attachment.ts";
156
156
  export { NO_ATTACHMENTS } from "./core/domain/attachment.ts";
157
+ export type { BlockTextFlavor } from "./core/domain/block-support.ts";
157
158
  export type {
158
159
  ClientCallError,
159
160
  ClientCallOptions,
package/src/kit/index.ts CHANGED
@@ -129,9 +129,14 @@ export type {
129
129
  } from "./ops-alerts.ts";
130
130
  export { OpsAlerts } from "./ops-alerts.ts";
131
131
  export {
132
+ type BlockSupport,
133
+ type ChannelSupport,
134
+ chunksFor,
132
135
  headline,
133
136
  quietLinks,
134
137
  splitReply,
138
+ supportOf,
139
+ textFor,
135
140
  thinkingLine,
136
141
  zonedStamp,
137
142
  } from "./presentation.ts";
@@ -1,7 +1,13 @@
1
1
  // Plugin helpers, versioned like the main entry; see the plugin guide.
2
2
 
3
+ export {
4
+ type BlockSupport,
5
+ type ChannelSupport,
6
+ supportOf,
7
+ } from "../core/domain/block-support.ts";
3
8
  export { zonedStampIn as zonedStamp } from "../core/kernel/time.ts";
4
9
  export { headline } from "../core/presentation/headline.ts";
5
10
  export { quietLinks } from "../core/presentation/quiet-links.ts";
11
+ export { chunksFor, textFor } from "../core/presentation/reply-chunks.ts";
6
12
  export { splitReply } from "../core/presentation/reply-splitter.ts";
7
13
  export { thinkingLine } from "../core/presentation/thinking-line.ts";
package/src/testing.ts CHANGED
@@ -32,6 +32,7 @@ import {
32
32
  ownerRootCommand,
33
33
  } from "./core/discord/owner-command.ts";
34
34
  import type { DiscordPoster } from "./core/discord/poster/poster.ts";
35
+ import { supportOf } from "./core/domain/block-support.ts";
35
36
  import type { ClientPart, ClientPort } from "./core/domain/client.ts";
36
37
  import type {
37
38
  PendingConfirmation,
@@ -140,6 +141,7 @@ export type {
140
141
  } from "./core/testing/surface-contract.ts";
141
142
  export {
142
143
  checkSurfaceContract,
144
+ describeBlocksContract,
143
145
  describeSurfaceContract,
144
146
  } from "./core/testing/surface-contract.ts";
145
147
  export type { TestHost, TestHostOptions } from "./core/testing/test-host.ts";
@@ -148,9 +150,8 @@ export type { FakeThreadHost } from "./core/testing/thread-host.ts";
148
150
  export { fakeThreads } from "./core/testing/thread-host.ts";
149
151
 
150
152
  /**
151
- * A service the plugin under test reads, with the members the test gives it, made by
152
- * `servicePair(KEY, { ... })`. Reading a member the test did not give throws a PluginError that
153
- * names it.
153
+ * A service the plugin under test reads, with the members the test gives it, made by `servicePair(KEY,
154
+ * { ... })`. Reading a member the test did not give throws a PluginError that names it.
154
155
  */
155
156
  export interface ServicePair {
156
157
  readonly key: ServiceKey<unknown>;
@@ -256,10 +257,7 @@ export interface TestPluginOptions {
256
257
  conversations?: Partial<ConversationPort>;
257
258
  /** Replaces `context.turns`, which by default runs turns over the runtime and the surfaces. */
258
259
  turns?: ConversationTurns;
259
- /**
260
- * The credentials `context.apiKey` returns, by provider name; a provider not listed reads as
261
- * having none, as on a host that is not logged in to it.
262
- */
260
+ /** The credentials `context.apiKey` returns, by provider name; a provider not listed reads as having none, as on a host not logged in to it. */
263
261
  apiKeys?: Readonly<Record<string, string>>;
264
262
  /** How long the router holds a bare forward for the message that follows it; the host option `conversations.forwardJoinMs`. */
265
263
  forwardJoinMs?: number;
@@ -482,7 +480,7 @@ export async function testPlugin(
482
480
  sessions: () => linked ?? unlinked("sessions"),
483
481
  toolTiers: tiers,
484
482
  prompts: (channel, speaker) => surfaces.prompts(channel, speaker),
485
- formatting: (channel) => surfaces.of(channel)?.formatting,
483
+ formatting: (c) => supportOf(surfaces.of(c), c).formatting,
486
484
  agents: {
487
485
  workDir: tmpdir(),
488
486
  skills: () => [],