pi-roundtable 0.53.5 → 0.54.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.
Files changed (97) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +14 -2
  3. package/README.zh-TW.md +14 -2
  4. package/docs/plugins.md +201 -8
  5. package/package.json +3 -1
  6. package/runner/Dockerfile +46 -0
  7. package/runner/Dockerfile.dockerignore +5 -0
  8. package/src/cli/checks/images.ts +3 -2
  9. package/src/cli/checks/preset.ts +20 -0
  10. package/src/cli/checks/runner.ts +45 -0
  11. package/src/cli/doctor.ts +7 -1
  12. package/src/core/agents/agent-claim.ts +7 -4
  13. package/src/core/agents/agent-prompt.ts +11 -2
  14. package/src/core/agents/helper-workspace.ts +72 -0
  15. package/src/core/agents/team-options.ts +2 -0
  16. package/src/core/agents/team-prompt.ts +12 -1
  17. package/src/core/attachments/attachment-expiry.ts +12 -0
  18. package/src/core/attachments/attachment-store.ts +20 -5
  19. package/src/core/attachments/model-images.ts +3 -2
  20. package/src/core/builtin/agent-server.ts +8 -0
  21. package/src/core/builtin/polls.ts +67 -0
  22. package/src/core/builtin/runner.ts +139 -0
  23. package/src/core/config/config-schema.ts +4 -0
  24. package/src/core/config/config.ts +49 -185
  25. package/src/core/config/preset.ts +51 -0
  26. package/src/core/config/resolve-config.ts +175 -0
  27. package/src/core/config/runner-config.ts +80 -0
  28. package/src/core/contract/attachments.ts +2 -0
  29. package/src/core/contract/polls.ts +71 -0
  30. package/src/core/contract/runtime.ts +12 -0
  31. package/src/core/contract/surface.ts +13 -0
  32. package/src/core/discord/discord-polls.ts +156 -0
  33. package/src/core/discord/discord-replies.ts +55 -0
  34. package/src/core/discord/discord-surface.ts +13 -43
  35. package/src/core/domain/client.ts +6 -2
  36. package/src/core/domain/errors.ts +5 -0
  37. package/src/core/domain/sessions.ts +8 -1
  38. package/src/core/host/define-roundtable.ts +8 -0
  39. package/src/core/host/host-registration.ts +7 -0
  40. package/src/core/host/host.ts +8 -0
  41. package/src/core/i18n/schedules.ts +2 -0
  42. package/src/core/modules/polls/poll-result-turns.ts +124 -0
  43. package/src/core/modules/polls/poll-rules.ts +108 -0
  44. package/src/core/modules/polls/poll-service.ts +477 -0
  45. package/src/core/modules/polls/poll-store.ts +336 -0
  46. package/src/core/modules/polls/poll-tools.ts +118 -0
  47. package/src/core/modules/polls/poll-turn-text.ts +60 -0
  48. package/src/core/plugin-api/define.ts +9 -2
  49. package/src/core/plugin-api/holds.ts +2 -0
  50. package/src/core/plugin-api/plugin.ts +8 -0
  51. package/src/core/runner/protocol.ts +456 -0
  52. package/src/core/runner/runner-client.ts +450 -0
  53. package/src/core/runner/runner-drivers.ts +356 -0
  54. package/src/core/runner/runner-files.ts +102 -0
  55. package/src/core/runner/runner-holds.ts +76 -0
  56. package/src/core/runner/runner-port.ts +77 -0
  57. package/src/core/runner/runner-probe.ts +53 -0
  58. package/src/core/runner/runner-prompt.ts +36 -0
  59. package/src/core/runner/runner-session.ts +131 -0
  60. package/src/core/runner/runner-tiers.ts +20 -0
  61. package/src/core/runner/runner-tools.ts +325 -0
  62. package/src/core/runner/settings.ts +108 -0
  63. package/src/core/runtime/conversation-sessions.ts +73 -15
  64. package/src/core/runtime/extensions/approval-card.ts +29 -2
  65. package/src/core/runtime/extensions/confirmation-gate.ts +24 -63
  66. package/src/core/runtime/extensions/gate-card.ts +105 -0
  67. package/src/core/runtime/extensions/yolo.ts +17 -3
  68. package/src/core/runtime/pi-agent-runtime.ts +37 -68
  69. package/src/core/runtime/runtime-plugin.ts +9 -0
  70. package/src/core/runtime/runtime-types.ts +29 -1
  71. package/src/core/runtime/session-factory.ts +59 -62
  72. package/src/core/runtime/session-shell.ts +43 -0
  73. package/src/core/runtime/session-tool-names.ts +78 -0
  74. package/src/core/runtime/turn-selection.ts +97 -0
  75. package/src/core/shared/attachment-reader.ts +10 -1
  76. package/src/core/shared/generate-image-tool.ts +4 -4
  77. package/src/core/shared/poll-target.ts +14 -0
  78. package/src/core/shared/workspace-files.ts +42 -4
  79. package/src/core/testing/fake-polls.ts +131 -0
  80. package/src/core/testing/fake-runner.ts +146 -0
  81. package/src/core/testing/surface-contract-approvals.ts +215 -0
  82. package/src/core/testing/surface-contract-polls.ts +142 -0
  83. package/src/core/testing/surface-contract.ts +32 -208
  84. package/src/core/tool-set.snapshot.json +8 -0
  85. package/src/index.ts +17 -0
  86. package/src/kit/index.ts +6 -0
  87. package/src/kit/polls.ts +8 -0
  88. package/src/runner-server/exec.ts +174 -0
  89. package/src/runner-server/file-helper.ts +208 -0
  90. package/src/runner-server/files.ts +93 -0
  91. package/src/runner-server/host.ts +65 -0
  92. package/src/runner-server/main.ts +89 -0
  93. package/src/runner-server/server.ts +318 -0
  94. package/src/runner-server/shared-dirs.ts +45 -0
  95. package/src/runner-server/state.ts +293 -0
  96. package/src/runner-server/transports.ts +187 -0
  97. package/src/testing.ts +7 -0
@@ -0,0 +1,80 @@
1
+ import { isAbsolute } from "node:path";
2
+ import { ConfigError } from "../domain/errors.ts";
3
+ import { TIERS } from "../identity/speakers.ts";
4
+ import { RUNNER_CEILINGS } from "../runner/protocol.ts";
5
+ import type { RunnerConfig } from "../runner/settings.ts";
6
+ import {
7
+ type Field,
8
+ guarded,
9
+ integer,
10
+ number,
11
+ oneOf,
12
+ optional,
13
+ shape,
14
+ } from "./schema.ts";
15
+
16
+ /** What every driver's `runner` setting may say of the limits. */
17
+ const limits = {
18
+ commandTimeoutMs: optional(integer(1_000, RUNNER_CEILINGS.commandTimeoutMs)),
19
+ maxOutputBytes: optional(integer(1_024, RUNNER_CEILINGS.maxOutputBytes)),
20
+ maxFileBytes: optional(integer(1_024, RUNNER_CEILINGS.maxFileBytes)),
21
+ keepDays: optional(integer(1, 3_650)),
22
+ minTier: optional(oneOf(...TIERS)),
23
+ };
24
+
25
+ /** An image reference docker takes as one argument; never one that reads as an option. */
26
+ const image = guarded(
27
+ "an image name, such as pi-roundtable-runner or registry/name:tag",
28
+ (value): value is string =>
29
+ typeof value === "string" && /^[A-Za-z0-9][\w./:@-]*$/.test(value),
30
+ );
31
+
32
+ /** A container name as docker accepts it. */
33
+ const containerName = guarded(
34
+ "a container name of letters, digits, _ . and -",
35
+ (value): value is string =>
36
+ typeof value === "string" && /^[A-Za-z0-9][\w.-]{0,127}$/.test(value),
37
+ );
38
+
39
+ const absolutePath = guarded(
40
+ "an absolute path",
41
+ (value): value is string =>
42
+ typeof value === "string" && value !== "" && isAbsolute(value),
43
+ );
44
+
45
+ const docker = shape({
46
+ driver: oneOf("docker" as const),
47
+ image,
48
+ name: optional(containerName),
49
+ memoryMb: optional(integer(64, 1_048_576)),
50
+ cpus: optional(number(0.1, 1_024)),
51
+ pids: optional(integer(16, 4_194_304)),
52
+ ...limits,
53
+ });
54
+
55
+ const socket = shape({
56
+ driver: oneOf("socket" as const),
57
+ socket: absolutePath,
58
+ ...limits,
59
+ });
60
+
61
+ const DESCRIBE =
62
+ '{ driver: "docker", image } or { driver: "socket", socket }, with optional limits';
63
+
64
+ /** The `runner` setting: a container the host runs, or a sidecar's socket; see `RunnerConfig`. */
65
+ export const runnerField: Field<RunnerConfig> = {
66
+ describe: DESCRIBE,
67
+ check: (value, path) => {
68
+ const driver =
69
+ typeof value === "object" && value !== null && !Array.isArray(value)
70
+ ? (value as { driver?: unknown }).driver
71
+ : undefined;
72
+ if (driver === "docker") return docker.check(value, path);
73
+ if (driver === "socket") return socket.check(value, path);
74
+ if (driver === undefined && (typeof value !== "object" || value === null))
75
+ return guarded(DESCRIBE, (_): _ is never => false).check(value, path);
76
+ throw new ConfigError(
77
+ `config ${path}.driver: expected "docker" or "socket", got ${JSON.stringify(driver) ?? "nothing"}. Fix the value in roundtable.config.ts.`,
78
+ );
79
+ },
80
+ };
@@ -36,6 +36,8 @@ export class AttachmentRefusal extends Error {
36
36
 
37
37
  /** What a plugin asks of `turnAttachments` besides the files. */
38
38
  export interface TurnAttachmentOptions {
39
+ /** Number of images to prepare for the model (0–4; default 4). Every file is still listed and readable. */
40
+ modelImages?: number;
39
41
  /**
40
42
  * The most bytes the principal may have used in turns across all their conversations, these
41
43
  * files included. A call that would pass it is refused with `quota_exceeded` and moves nothing.
@@ -0,0 +1,71 @@
1
+ import type { ChannelKey } from "../domain/sessions.ts";
2
+
3
+ /** What a surface's native polls hold: the most answers, characters, and time it takes. */
4
+ export interface PollLimits {
5
+ /** The most answers one poll offers; at least 2. */
6
+ answers: number;
7
+ /** The most characters of the question. */
8
+ questionChars: number;
9
+ /** The most characters of one answer. */
10
+ answerChars: number;
11
+ /** The longest a poll may stay open, in ms. */
12
+ maxDurationMs: number;
13
+ }
14
+
15
+ /** A poll to post: its question, its answers in order, and when it closes. */
16
+ export interface SurfacePoll {
17
+ question: string;
18
+ answers: readonly string[];
19
+ /** Whether a voter may pick more than one answer. */
20
+ multi: boolean;
21
+ /**
22
+ * When the poll should close. A surface that counts its time more coarsely, such as Discord in
23
+ * whole hours, keeps it open at least this long; the host ends it at this time with `end`.
24
+ */
25
+ closesAt: Date;
26
+ }
27
+
28
+ /** One person who voted, as the surface shows them: their id on the network and their display name. */
29
+ export interface PollVoter {
30
+ id: string;
31
+ name: string;
32
+ }
33
+
34
+ /** A poll's count once it ended, one entry per answer in the order the answers were posted. */
35
+ export interface PollResults {
36
+ answers: {
37
+ text: string;
38
+ votes: number;
39
+ /** Who chose it, as many as the surface lists (Discord lists at most 100). */
40
+ voters: PollVoter[];
41
+ /** True when `voters` lists fewer people than `votes` counts. */
42
+ votersCut: boolean;
43
+ }[];
44
+ /**
45
+ * How many people voted: the sum of the votes of a single-choice poll, and the distinct voters
46
+ * listed of a multiple-choice one, which undercounts when a list was cut.
47
+ */
48
+ totalVoters: number;
49
+ }
50
+
51
+ /**
52
+ * A surface's native polls, which an agent posts with `poll_create`: anyone who can see the channel
53
+ * votes, and the host reads the results once it ends. A surface without them makes the poll tools
54
+ * refuse.
55
+ */
56
+ export interface SurfacePolls {
57
+ readonly limits: PollLimits;
58
+ /**
59
+ * Posts the poll in the channel; resolves to the surface's own id of it, which `end` and
60
+ * `results` take. Rejects with a plain message when the surface refuses, such as for a missing
61
+ * permission.
62
+ */
63
+ post(channel: ChannelKey, poll: SurfacePoll): Promise<{ pollId: string }>;
64
+ /** Closes the poll to new votes; a poll already ended, or deleted, resolves as well. */
65
+ end(channel: ChannelKey, pollId: string): Promise<void>;
66
+ /**
67
+ * The poll's count, read after `end`; `"gone"` when its message was deleted or its channel is no
68
+ * longer there. Rejects when it cannot be read now, so the host tries again later.
69
+ */
70
+ results(channel: ChannelKey, pollId: string): Promise<PollResults | "gone">;
71
+ }
@@ -103,6 +103,18 @@ export interface AgentSessions {
103
103
  modelOf(name: string): { model: string; thinking: ThinkingSetting };
104
104
  /** The channel the scope's turns run in: the group's for a seat in one, else the agent's own. */
105
105
  turnChannel(scope: AgentTurnScope): ChannelKey;
106
+ /**
107
+ * The home whose workspace the scope's turns use when the runner serves them: a temp knight's
108
+ * origin's, so it shares its parent's files as it shares the workspace on the host; left out,
109
+ * the scope's own home.
110
+ */
111
+ runnerHome?(scope: AgentTurnScope): ChannelKey;
112
+ /**
113
+ * Whether only the owners reach the agent's conversation, such as its room on the web app, so
114
+ * its turns keep the host's shell and files on a host with a runner, as the owner's own
115
+ * conversations do. Left out, none is: every agent conversation the runner may serve, it serves.
116
+ */
117
+ ownersOnly?(scope: AgentTurnScope): boolean;
106
118
  /**
107
119
  * Whose turns in an agent's conversation load memory: `"everyone"` (the default) lets each
108
120
  * speaker read their own, `"owners"` only the owners, so a speaker below the owner tier gets no
@@ -20,6 +20,7 @@ import type {
20
20
  AttachmentRef,
21
21
  InboundMessage,
22
22
  } from "./channels.ts";
23
+ import type { SurfacePolls } from "./polls.ts";
23
24
 
24
25
  /**
25
26
  * Splits a channel key, `<surface>:<id>`, at its first colon: the surface names the chat network
@@ -111,12 +112,24 @@ export interface ChatSurface {
111
112
  * room through `sendReply` with `OutboundReply.author`. Absent or false = no rooms.
112
113
  */
113
114
  readonly agentRooms?: boolean;
115
+ /**
116
+ * Only the owners enter this surface's agent and group rooms: it serves them, their messages and
117
+ * their cards to owners alone and refuses anyone else, as the web app does. Declared, an agent's
118
+ * own room here is a conversation only the owners reach, which keeps the host's shell on a host
119
+ * with a runner. Absent or false = others may be there too, and the runner serves those rooms.
120
+ */
121
+ readonly agentRoomsOwnersOnly?: boolean;
114
122
  /**
115
123
  * Hosts dispatch threads: a background dispatch started in one of this surface's channels
116
124
  * opens its thread here, and the thread is the conversation `<surface>:<id>`. Absent = the
117
125
  * dispatch posts in the channel as before.
118
126
  */
119
127
  readonly threads?: SurfaceThreads;
128
+ /**
129
+ * Native polls an agent may post in this surface's channels (`poll_create`); their results come
130
+ * back to the agent in a turn of its own once they end. Absent = the poll tools refuse here.
131
+ */
132
+ readonly polls?: SurfacePolls;
120
133
  /**
121
134
  * What was said in the message's channel since the assistant last posted there, before the
122
135
  * message that addressed it: public text around the message, for a claim to append to its turn
@@ -0,0 +1,156 @@
1
+ import {
2
+ type Client,
3
+ DiscordAPIError,
4
+ type Message,
5
+ RESTJSONErrorCodes,
6
+ } from "discord.js";
7
+ import type {
8
+ PollLimits,
9
+ PollResults,
10
+ SurfacePolls,
11
+ } from "../contract/polls.ts";
12
+ import type { ChannelKey } from "../domain/conversation.ts";
13
+ import { sendableChannel } from "./discord-replies.ts";
14
+
15
+ const HOUR_MS = 3_600_000;
16
+
17
+ /** Discord counts a poll's duration in whole hours, from 1 to 32 days. */
18
+ const MAX_HOURS = 768;
19
+
20
+ /** The most voters Discord lists of one answer in one request. */
21
+ export const DISCORD_VOTERS_LISTED = 100;
22
+
23
+ /** Discord's own limits on a poll. */
24
+ export const DISCORD_POLL_LIMITS: PollLimits = {
25
+ answers: 10,
26
+ questionChars: 300,
27
+ answerChars: 55,
28
+ maxDurationMs: MAX_HOURS * HOUR_MS,
29
+ };
30
+
31
+ export interface DiscordPollsOptions {
32
+ /** How often the results are read again while Discord has not finalized them; default 3. */
33
+ finalizeTries?: number;
34
+ /** The wait between those reads; default 1 s. */
35
+ finalizeWaitMs?: number;
36
+ /** Replaceable in tests. */
37
+ now?: () => Date;
38
+ }
39
+
40
+ const codeOf = (error: unknown) =>
41
+ error instanceof DiscordAPIError ? error.code : undefined;
42
+
43
+ /** The poll's channel or message is no longer there. */
44
+ const isGone = (error: unknown) =>
45
+ codeOf(error) === RESTJSONErrorCodes.UnknownMessage ||
46
+ codeOf(error) === RESTJSONErrorCodes.UnknownChannel;
47
+
48
+ /** The whole hours Discord keeps a poll open so that it is still open at `closesAt`, within 1 to 768. */
49
+ export function discordPollHours(closesAt: Date, now: Date): number {
50
+ const hours = Math.ceil((closesAt.getTime() - now.getTime()) / HOUR_MS);
51
+ return Math.min(MAX_HOURS, Math.max(1, hours));
52
+ }
53
+
54
+ /** A message's poll as results: each answer in order, with its count and at most 100 voters. */
55
+ async function resultsOf(message: Message): Promise<PollResults> {
56
+ const poll = message.poll;
57
+ if (!poll) throw new Error(`message ${message.id} holds no poll`);
58
+ const answers = await Promise.all(
59
+ [...poll.answers.values()]
60
+ .sort((a, b) => a.id - b.id)
61
+ .map(async (answer) => {
62
+ const users = await answer.voters.fetch({
63
+ limit: DISCORD_VOTERS_LISTED,
64
+ });
65
+ const voters = [...users.values()].map((user) => ({
66
+ id: user.id,
67
+ name: user.globalName ?? user.username,
68
+ }));
69
+ const votes = Math.max(answer.voteCount, voters.length);
70
+ return {
71
+ text: answer.text ?? "",
72
+ votes,
73
+ voters,
74
+ votersCut: votes > voters.length,
75
+ };
76
+ }),
77
+ );
78
+ const totalVoters = poll.allowMultiselect
79
+ ? new Set(answers.flatMap((answer) => answer.voters.map((v) => v.id))).size
80
+ : answers.reduce((sum, answer) => sum + answer.votes, 0);
81
+ return { answers, totalVoters };
82
+ }
83
+
84
+ /**
85
+ * Discord's native polls, through the client as it is when each call is made: a poll is a message
86
+ * in the channel, and its id is the message's. The bot needs Send Polls to post and Read Message
87
+ * History to read the count.
88
+ */
89
+ export function discordPolls(
90
+ client: () => Client,
91
+ options: DiscordPollsOptions = {},
92
+ ): SurfacePolls {
93
+ const now = options.now ?? (() => new Date());
94
+ const tries = options.finalizeTries ?? 3;
95
+ const wait = options.finalizeWaitMs ?? 1_000;
96
+ return {
97
+ limits: DISCORD_POLL_LIMITS,
98
+ post: async (channel: ChannelKey, poll) => {
99
+ const target = await sendableChannel(client(), channel);
100
+ try {
101
+ const message = await target.send({
102
+ poll: {
103
+ question: { text: poll.question },
104
+ answers: poll.answers.map((text) => ({ text })),
105
+ duration: discordPollHours(poll.closesAt, now()),
106
+ allowMultiselect: poll.multi,
107
+ },
108
+ });
109
+ return { pollId: message.id };
110
+ } catch (error) {
111
+ if (codeOf(error) === RESTJSONErrorCodes.MissingPermissions)
112
+ throw new Error(
113
+ "the bot may not post polls in this channel: it needs the Send Polls permission there",
114
+ );
115
+ if (
116
+ codeOf(error) === RESTJSONErrorCodes.InvalidChannelTypeForPollCreation
117
+ )
118
+ throw new Error("Discord takes no polls in this kind of channel");
119
+ throw error;
120
+ }
121
+ },
122
+ end: async (channel, pollId) => {
123
+ try {
124
+ const target = await sendableChannel(client(), channel);
125
+ await target.messages.endPoll(pollId);
126
+ } catch (error) {
127
+ // Ended already, at its own time or by someone, or gone: there is nothing left to end.
128
+ if (codeOf(error) === RESTJSONErrorCodes.PollExpired || isGone(error))
129
+ return;
130
+ throw error;
131
+ }
132
+ },
133
+ results: async (channel, pollId) => {
134
+ try {
135
+ const target = await sendableChannel(client(), channel);
136
+ let message = await target.messages.fetch({
137
+ message: pollId,
138
+ force: true,
139
+ });
140
+ // Discord counts the votes once more after the end; read again until it says it has.
141
+ for (let tried = 1; tried < tries; tried += 1) {
142
+ if (message.poll?.resultsFinalized !== false) break;
143
+ await Bun.sleep(wait);
144
+ message = await target.messages.fetch({
145
+ message: pollId,
146
+ force: true,
147
+ });
148
+ }
149
+ return await resultsOf(message);
150
+ } catch (error) {
151
+ if (isGone(error)) return "gone";
152
+ throw error;
153
+ }
154
+ },
155
+ };
156
+ }
@@ -0,0 +1,55 @@
1
+ import { AttachmentBuilder, type Client } from "discord.js";
2
+ import type { ChannelKey, OutboundReply } from "../domain/conversation.ts";
3
+ import type { Logger } from "../kernel/log.ts";
4
+
5
+ export const DISCORD_PREFIX = "discord:";
6
+
7
+ export async function sendableChannel(client: Client, channel: ChannelKey) {
8
+ if (!channel.startsWith(DISCORD_PREFIX))
9
+ throw new Error(`not a Discord channel: ${channel}`);
10
+ const target = await client.channels.fetch(
11
+ channel.slice(DISCORD_PREFIX.length),
12
+ );
13
+ if (!target?.isSendable())
14
+ throw new Error(`channel ${channel} cannot receive messages`);
15
+ return target;
16
+ }
17
+
18
+ /**
19
+ * Discord draws attachments below a message's text, so the card goes out as its own message
20
+ * first and produced files last, each on its own. Replies may mention people but never everyone or a role. A card
21
+ * Discord refuses (a channel without Attach Files) is logged, and the text still goes out. */
22
+ export async function sendDiscordReply(
23
+ client: Client,
24
+ channel: ChannelKey,
25
+ reply: OutboundReply,
26
+ logger: Logger,
27
+ ): Promise<void> {
28
+ const target = await sendableChannel(client, channel);
29
+ const allowedMentions = { parse: ["users" as const] };
30
+ if (reply.thinking) {
31
+ await target.send({ content: reply.thinking, allowedMentions });
32
+ }
33
+ if (reply.card) {
34
+ const card = new AttachmentBuilder(Buffer.from(reply.card), {
35
+ name: "card.png",
36
+ });
37
+ await target.send({ files: [card] }).catch((err: unknown) => {
38
+ logger.warn(
39
+ { channel, err },
40
+ "reply card not posted; sending the text alone",
41
+ );
42
+ });
43
+ }
44
+ for (const chunk of reply.chunks) {
45
+ await target.send({ content: chunk, allowedMentions });
46
+ }
47
+ // One file per message: Discord crops several images in one message into a grid.
48
+ for (const file of reply.files ?? []) {
49
+ await target.send({
50
+ files: [
51
+ new AttachmentBuilder(Buffer.from(file.data), { name: file.name }),
52
+ ],
53
+ });
54
+ }
55
+ }
@@ -1,5 +1,4 @@
1
1
  import {
2
- AttachmentBuilder,
3
2
  Client,
4
3
  Events,
5
4
  GatewayIntentBits,
@@ -16,6 +15,7 @@ import type {
16
15
  ChannelContext,
17
16
  ChannelContextOptions,
18
17
  } from "../contract/channel-context.ts";
18
+ import type { SurfacePolls } from "../contract/polls.ts";
19
19
  import type {
20
20
  ChatSurface,
21
21
  SurfaceMessageEvents,
@@ -43,6 +43,12 @@ import type { ChannelExecutor } from "./channel-operations.ts";
43
43
  import type { ComposedCommands } from "./compose-commands.ts";
44
44
  import type { ChannelInfo, DiscordConnection } from "./connection.ts";
45
45
  import { readMessagesBefore, readThreadStarter } from "./context-reading.ts";
46
+ import { discordPolls } from "./discord-polls.ts";
47
+ import {
48
+ DISCORD_PREFIX as PREFIX,
49
+ sendableChannel,
50
+ sendDiscordReply,
51
+ } from "./discord-replies.ts";
46
52
  import { DiscordThreadHost } from "./dispatch-thread-host.ts";
47
53
  import { DISCORD_FORMATTING, pickFormatting } from "./formatting.ts";
48
54
  import { DEFAULT_FRESH_MARKER, postFreshMarker } from "./fresh-marker.ts";
@@ -63,7 +69,6 @@ import { DiscordOwnerOps } from "./owner-discord.ts";
63
69
  import { showStopPanel } from "./stop-button.ts";
64
70
  import { voiceIntents } from "./voice/voice-discord.ts";
65
71
 
66
- const PREFIX = "discord:";
67
72
  const TYPING_REFRESH_MS = 8_000;
68
73
 
69
74
  export interface DiscordSurfaceOptions {
@@ -116,6 +121,8 @@ export class DiscordSurface
116
121
  send: (threadId, text) => this.threadHost().send(threadId, text),
117
122
  close: (threadId) => this.threadHost().close(threadId),
118
123
  });
124
+ /** Native polls in its channels; the bot needs Send Polls and Read Message History. */
125
+ readonly polls: SurfacePolls = discordPolls(() => this.#client);
119
126
  readonly #options: DiscordSurfaceOptions;
120
127
  readonly #client: Client;
121
128
 
@@ -312,38 +319,8 @@ export class DiscordSurface
312
319
  );
313
320
  }
314
321
 
315
- /**
316
- * Discord draws attachments below a message's text, so the card goes out as its own message
317
- * first and produced files last, each on its own. Replies may mention people but never everyone or a role. A card
318
- * Discord refuses (a channel without Attach Files) is logged, and the text still goes out. */
319
- async sendReply(channel: ChannelKey, reply: OutboundReply): Promise<void> {
320
- const target = await this.#sendable(channel);
321
- const allowedMentions = { parse: ["users" as const] };
322
- if (reply.thinking) {
323
- await target.send({ content: reply.thinking, allowedMentions });
324
- }
325
- if (reply.card) {
326
- const card = new AttachmentBuilder(Buffer.from(reply.card), {
327
- name: "card.png",
328
- });
329
- await target.send({ files: [card] }).catch((err: unknown) => {
330
- this.#options.logger.warn(
331
- { channel, err },
332
- "reply card not posted; sending the text alone",
333
- );
334
- });
335
- }
336
- for (const chunk of reply.chunks) {
337
- await target.send({ content: chunk, allowedMentions });
338
- }
339
- // One file per message: Discord crops several images in one message into a grid.
340
- for (const file of reply.files ?? []) {
341
- await target.send({
342
- files: [
343
- new AttachmentBuilder(Buffer.from(file.data), { name: file.name }),
344
- ],
345
- });
346
- }
322
+ sendReply(channel: ChannelKey, reply: OutboundReply): Promise<void> {
323
+ return sendDiscordReply(this.#client, channel, reply, this.#options.logger);
347
324
  }
348
325
 
349
326
  /** The divider that ends channel context's window; see `postFreshMarker`. */
@@ -486,14 +463,7 @@ export class DiscordSurface
486
463
  }
487
464
  }
488
465
 
489
- async #sendable(channel: ChannelKey) {
490
- if (!channel.startsWith(PREFIX))
491
- throw new Error(`not a Discord channel: ${channel}`);
492
- const target = await this.#client.channels.fetch(
493
- channel.slice(PREFIX.length),
494
- );
495
- if (!target?.isSendable())
496
- throw new Error(`channel ${channel} cannot receive messages`);
497
- return target;
466
+ #sendable(channel: ChannelKey) {
467
+ return sendableChannel(this.#client, channel);
498
468
  }
499
469
  }
@@ -24,9 +24,13 @@ export type ClientCallError =
24
24
  | "failed";
25
25
 
26
26
  /** What a client call comes to: the value the client answered with and its binary parts, or why not. */
27
- export type ClientCallResult =
27
+ export type ClientCallResult = (
28
28
  | { ok: true; value: unknown; parts: readonly ClientPart[] }
29
- | { ok: false; error: ClientCallError; message: string };
29
+ | { ok: false; error: ClientCallError; message: string }
30
+ ) & {
31
+ /** Transport id of the dispatched call, if available. Absent when the call was never sent. */
32
+ readonly callId?: string;
33
+ };
30
34
 
31
35
  /** How one client call is bounded. */
32
36
  export interface ClientCallOptions {
@@ -25,6 +25,11 @@ export class DelegationError extends Error {
25
25
  override name = "DelegationError";
26
26
  }
27
27
 
28
+ /** A poll that cannot be posted or ended; its message is the tool's answer to the model. */
29
+ export class PollError extends Error {
30
+ override name = "PollError";
31
+ }
32
+
28
33
  /** A request about agents or groups that cannot be met; its message is shown to whoever asked. */
29
34
  export class AgentError extends Error {
30
35
  override name = "AgentError";
@@ -4,6 +4,7 @@ import type { Principal } from "../identity/principal-store.ts";
4
4
  import type { Speaker } from "../identity/speakers.ts";
5
5
  import type { ApprovedBy } from "../interactions/prompts.ts";
6
6
  import { PluginError } from "../kernel/errors.ts";
7
+ import type { WorkspaceFiles } from "../shared/workspace-files.ts";
7
8
  import type { ClientPort } from "./client.ts";
8
9
 
9
10
  /** `<surface>:<channel id>`, for example `discord:1234`. A DM is one channel. */
@@ -88,8 +89,14 @@ export interface SessionContext {
88
89
  /**
89
90
  * The shared workspace of a session with a shell, and its scratch dir: the roots its shell writes
90
91
  * in without a hold, and where its tools may read a file by path. Absent for a session without one.
92
+ * In a session the runner serves they are the runner's paths, not the host's, and `files` reaches
93
+ * them: a tool reads and writes a file there through it, never through the host's disk.
91
94
  */
92
- workspace?: { workspace: string; scratchDir?: string };
95
+ workspace?: {
96
+ workspace: string;
97
+ scratchDir?: string;
98
+ files?: WorkspaceFiles;
99
+ };
93
100
  /** Where the session's conversation keeps the files people attached; absent when the session keeps none. */
94
101
  attachmentDir?: string;
95
102
  /** The person the session's running turn is for; undefined between turns. */
@@ -8,7 +8,9 @@ import { discordFormerChannelOps, discordPlugin } from "../builtin/discord.ts";
8
8
  import { discordAdminPlugin } from "../builtin/discord-admin.ts";
9
9
  import { identityPlugin } from "../builtin/identity.ts";
10
10
  import { modulesPlugin, schedulerPlugin } from "../builtin/modules.ts";
11
+ import { pollsPlugin } from "../builtin/polls.ts";
11
12
  import { promptsPlugin } from "../builtin/prompts.ts";
13
+ import { runnerPlugin } from "../builtin/runner.ts";
12
14
  import { seedsPlugin } from "../builtin/seeds.ts";
13
15
  import { skillsPlugin } from "../builtin/skills.ts";
14
16
  import {
@@ -347,6 +349,7 @@ export async function defineRoundtable(
347
349
  ...(input.shellEnv ? { shellEnv: input.shellEnv } : {}),
348
350
  characterSkins: config.characters.skins,
349
351
  agentTools: config.agentTools,
352
+ ...(config.runner ? { runner: config.runner } : {}),
350
353
  },
351
354
  database: { url: config.databaseUrl },
352
355
  dataDir: config.dataDir,
@@ -410,7 +413,10 @@ export async function defineRoundtable(
410
413
  config.conversations.keep,
411
414
  ),
412
415
  modesPlugin(),
416
+ // Before the runtime and the agent server, whose sessions run their shells in it.
417
+ ...(config.runner ? [runnerPlugin({ dataDir: config.dataDir })] : []),
413
418
  runtimePlugin({
419
+ imageTool: config.imageTool,
414
420
  owner,
415
421
  modelRuntime,
416
422
  agentDir: config.agentDir,
@@ -434,6 +440,8 @@ export async function defineRoundtable(
434
440
  : []),
435
441
  ...config.plugins,
436
442
  schedulerPlugin(),
443
+ // After everything a poll's result turn reaches, as the scheduler is.
444
+ pollsPlugin(),
437
445
  ],
438
446
  };
439
447
  }
@@ -7,6 +7,7 @@ import {
7
7
  } from "../../characters/index.ts";
8
8
  import { attachmentPort } from "../attachments/attachment-port.ts";
9
9
  import { retentionServices } from "../attachments/attachment-retention.ts";
10
+ import { runnerField } from "../config/runner-config.ts";
10
11
  import type { AttachmentPort } from "../contract/attachments.ts";
11
12
  import type { ConversationPort } from "../contract/channels.ts";
12
13
  import type { ResolvedProviders } from "../contract/providers.ts";
@@ -43,6 +44,7 @@ import {
43
44
  import { MessageObservers } from "../routing/message-observers.ts";
44
45
  import { PeerBots } from "../routing/peer-bots.ts";
45
46
  import { surfacePort } from "../routing/surface-port.ts";
47
+ import { runnerSettings } from "../runner/settings.ts";
46
48
  import { refuseHostAccess } from "../runtime/chat-only.ts";
47
49
  import { type ToolTierTable, toolTiers } from "../runtime/tool-tiers.ts";
48
50
  import { frozenShellEnv } from "../shared/child-env.ts";
@@ -136,9 +138,13 @@ export class Linkage {
136
138
  characterSkins,
137
139
  agentTools = "full",
138
140
  shellEnv,
141
+ runner,
139
142
  } = this.#options.environment ?? {};
140
143
  // Checked before anything is applied, so a bad set stops the start with the process untouched.
141
144
  const skins = characterSkinsOf(characterSkins);
145
+ const settings = runner
146
+ ? runnerSettings(runnerField.check(runner, "runner"))
147
+ : undefined;
142
148
  setLocale(locale, { assistant, root: rootCommand });
143
149
  setTimeZone(timeZone);
144
150
  // Pi packages such as pi-web-access read their config from the Pi agent directory.
@@ -151,6 +157,7 @@ export class Linkage {
151
157
  characterSkins: skins,
152
158
  agentTools,
153
159
  ...(shellEnv ? { shellEnv: frozenShellEnv(shellEnv) } : {}),
160
+ ...(settings ? { runner: settings } : {}),
154
161
  };
155
162
  }
156
163
 
@@ -18,6 +18,7 @@ import type {
18
18
  Service,
19
19
  } from "../plugin-api/plugin.ts";
20
20
  import { RUNTIME } from "../plugin-api/services.ts";
21
+ import type { RunnerConfig } from "../runner/settings.ts";
21
22
  import type { ToolTierTable } from "../runtime/tool-tiers.ts";
22
23
  import type { ShellEnvConfig } from "../shared/child-env.ts";
23
24
  import {
@@ -52,6 +53,13 @@ export interface HostEnvironment extends ShellEnvConfig {
52
53
  characterSkins?: readonly Hex[];
53
54
  /** What the agents' turns may use of the machine, which plugins read as `env.agentTools`; default "full". */
54
55
  agentTools?: AgentTools;
56
+ /**
57
+ * The runner where every conversation but the owner's own runs its shell and file tools (what
58
+ * the configuration's `runner` sets), which plugins read, with its defaults, as `env.runner`. A
59
+ * host composed by hand also adds the runner plugin, which `defineRoundtable` does. Checked as
60
+ * the configuration is; a bad value stops the start.
61
+ */
62
+ runner?: RunnerConfig;
55
63
  }
56
64
 
57
65
  export interface RoundtableOptions {