pi-roundtable 0.53.6 → 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 (91) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +6 -2
  3. package/README.zh-TW.md +6 -2
  4. package/docs/plugins.md +199 -7
  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/builtin/agent-server.ts +8 -0
  18. package/src/core/builtin/polls.ts +67 -0
  19. package/src/core/builtin/runner.ts +139 -0
  20. package/src/core/config/config-schema.ts +4 -0
  21. package/src/core/config/config.ts +49 -185
  22. package/src/core/config/preset.ts +51 -0
  23. package/src/core/config/resolve-config.ts +175 -0
  24. package/src/core/config/runner-config.ts +80 -0
  25. package/src/core/contract/polls.ts +71 -0
  26. package/src/core/contract/runtime.ts +12 -0
  27. package/src/core/contract/surface.ts +13 -0
  28. package/src/core/discord/discord-polls.ts +156 -0
  29. package/src/core/discord/discord-replies.ts +55 -0
  30. package/src/core/discord/discord-surface.ts +13 -43
  31. package/src/core/domain/errors.ts +5 -0
  32. package/src/core/domain/sessions.ts +8 -1
  33. package/src/core/host/define-roundtable.ts +8 -0
  34. package/src/core/host/host-registration.ts +7 -0
  35. package/src/core/host/host.ts +8 -0
  36. package/src/core/i18n/schedules.ts +2 -0
  37. package/src/core/modules/polls/poll-result-turns.ts +124 -0
  38. package/src/core/modules/polls/poll-rules.ts +108 -0
  39. package/src/core/modules/polls/poll-service.ts +477 -0
  40. package/src/core/modules/polls/poll-store.ts +336 -0
  41. package/src/core/modules/polls/poll-tools.ts +118 -0
  42. package/src/core/modules/polls/poll-turn-text.ts +60 -0
  43. package/src/core/plugin-api/define.ts +9 -2
  44. package/src/core/plugin-api/holds.ts +2 -0
  45. package/src/core/plugin-api/plugin.ts +8 -0
  46. package/src/core/runner/protocol.ts +456 -0
  47. package/src/core/runner/runner-client.ts +450 -0
  48. package/src/core/runner/runner-drivers.ts +356 -0
  49. package/src/core/runner/runner-files.ts +102 -0
  50. package/src/core/runner/runner-holds.ts +76 -0
  51. package/src/core/runner/runner-port.ts +77 -0
  52. package/src/core/runner/runner-probe.ts +53 -0
  53. package/src/core/runner/runner-prompt.ts +36 -0
  54. package/src/core/runner/runner-session.ts +131 -0
  55. package/src/core/runner/runner-tiers.ts +20 -0
  56. package/src/core/runner/runner-tools.ts +325 -0
  57. package/src/core/runner/settings.ts +108 -0
  58. package/src/core/runtime/conversation-sessions.ts +73 -15
  59. package/src/core/runtime/extensions/approval-card.ts +29 -2
  60. package/src/core/runtime/extensions/confirmation-gate.ts +24 -63
  61. package/src/core/runtime/extensions/gate-card.ts +105 -0
  62. package/src/core/runtime/extensions/yolo.ts +17 -3
  63. package/src/core/runtime/pi-agent-runtime.ts +37 -68
  64. package/src/core/runtime/runtime-plugin.ts +9 -0
  65. package/src/core/runtime/runtime-types.ts +29 -1
  66. package/src/core/runtime/session-factory.ts +59 -62
  67. package/src/core/runtime/session-shell.ts +43 -0
  68. package/src/core/runtime/session-tool-names.ts +78 -0
  69. package/src/core/runtime/turn-selection.ts +97 -0
  70. package/src/core/shared/generate-image-tool.ts +4 -4
  71. package/src/core/shared/poll-target.ts +14 -0
  72. package/src/core/shared/workspace-files.ts +42 -4
  73. package/src/core/testing/fake-polls.ts +131 -0
  74. package/src/core/testing/fake-runner.ts +146 -0
  75. package/src/core/testing/surface-contract-approvals.ts +215 -0
  76. package/src/core/testing/surface-contract-polls.ts +142 -0
  77. package/src/core/testing/surface-contract.ts +32 -208
  78. package/src/core/tool-set.snapshot.json +8 -0
  79. package/src/index.ts +17 -0
  80. package/src/kit/index.ts +6 -0
  81. package/src/kit/polls.ts +8 -0
  82. package/src/runner-server/exec.ts +174 -0
  83. package/src/runner-server/file-helper.ts +208 -0
  84. package/src/runner-server/files.ts +93 -0
  85. package/src/runner-server/host.ts +65 -0
  86. package/src/runner-server/main.ts +89 -0
  87. package/src/runner-server/server.ts +318 -0
  88. package/src/runner-server/shared-dirs.ts +45 -0
  89. package/src/runner-server/state.ts +293 -0
  90. package/src/runner-server/transports.ts +187 -0
  91. package/src/testing.ts +7 -0
@@ -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
  }
@@ -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 {
@@ -37,6 +37,7 @@ export function schedulesEn(ctx: CatalogContext) {
37
37
  target: string,
38
38
  ) => `**#${id} ${title}** · ${channel} · ${target}`,
39
39
  scheduleModeOwner: ctx.assistant,
40
+ scheduleModePoll: "Poll results",
40
41
  scheduleFooter: `Schedules are created and edited by the bot in conversation; here you can review and cancel them. \`/${ctx.root} schedule cancel\` cancels one.`,
41
42
  scheduleGroupDescription: "Schedules",
42
43
  scheduleListDescription: "List the schedules of every channel",
@@ -88,6 +89,7 @@ export function schedulesZhTW(
88
89
  target: string,
89
90
  ) => `**#${id} ${title}** ${channel} ${target}`,
90
91
  scheduleModeOwner: ctx.assistant,
92
+ scheduleModePoll: "投票結果",
91
93
  scheduleFooter: `排程由 bot 在對話中建立與修改;這裡可以總覽與取消。\`/${ctx.root} schedule cancel\` 取消。`,
92
94
  scheduleGroupDescription: "排程",
93
95
  scheduleListDescription: "列出所有頻道的排程",
@@ -0,0 +1,124 @@
1
+ import type {
2
+ BackgroundTurn,
3
+ ScheduledOutcome,
4
+ } from "../../contract/channels.ts";
5
+ import type { ConversationRegistry } from "../../conversations/conversation-registry.ts";
6
+ import type { ChannelKey, TurnSelection } from "../../domain/sessions.ts";
7
+ import type { Speaker } from "../../identity/speakers.ts";
8
+ import type { ConversationTurns } from "../../routing/conversation-turns.ts";
9
+ import { POLL_TARGET } from "../../shared/poll-target.ts";
10
+
11
+ /** How a claim answers a poll's results in one of its conversations. */
12
+ export interface PollResultAnswer {
13
+ /** The conversation's kind, whose persona answers. */
14
+ kind: string;
15
+ /** The tools of the result turn, such as the ones the conversation's own turns carry. */
16
+ selection: TurnSelection;
17
+ /** Where the turn comes from, as the claim's own turns there say it; left out, none. */
18
+ origin?: string;
19
+ }
20
+
21
+ export interface PollResultTurnsOptions {
22
+ /** Runs the turn: the plugin's `context.turns`. */
23
+ turns: Pick<ConversationTurns, "run">;
24
+ /**
25
+ * The host's conversation registry (`CONVERSATIONS`), read at each turn; undefined on a host
26
+ * that records none, where every result turn is skipped, since whose conversation it is
27
+ * cannot be checked.
28
+ */
29
+ conversations: () => Pick<ConversationRegistry, "get"> | undefined;
30
+ /** How the claim answers a poll's results in a channel; undefined skips the turn. */
31
+ answer(channel: ChannelKey): PollResultAnswer | undefined;
32
+ }
33
+
34
+ /** What a claim spreads into itself to answer poll results: `background` and its `backgroundRefusal`. */
35
+ export interface PollResultTurns {
36
+ background(turn: BackgroundTurn): Promise<ScheduledOutcome>;
37
+ backgroundRefusal(
38
+ turn: BackgroundTurn & { speaker: Speaker },
39
+ ): string | undefined;
40
+ }
41
+
42
+ /**
43
+ * A claim's `background` for `POLL_TARGET` alone, so a plugin's claim hears the results of the
44
+ * polls its turns started: `...pollResultTurns({ turns, conversations, answer })`. Each result
45
+ * turn runs as the poll's starter, as the router checked them, with the selection `answer` gives
46
+ * for the channel; it is never a message (no `byMessage`, no `confirmed`), so it approves no held
47
+ * action, and nobody waits on it. It skips every other target, a turn the router did not run as
48
+ * the starter, a channel `answer` leaves out, and a conversation that is gone or now private to
49
+ * someone else.
50
+ */
51
+ export function pollResultTurns(
52
+ options: PollResultTurnsOptions,
53
+ ): PollResultTurns {
54
+ /** Why the turn is skipped, or how it is answered. */
55
+ const check = (
56
+ turn: BackgroundTurn & { speaker: Speaker },
57
+ ): { reason: string } | { answer: PollResultAnswer } => {
58
+ if (turn.target !== POLL_TARGET.name)
59
+ return {
60
+ reason: `this claim answers only "${POLL_TARGET.name}" background turns`,
61
+ };
62
+ if (turn.speaker.principalId !== turn.author.principalId)
63
+ return {
64
+ reason: "a poll's results run only as the person who started it",
65
+ };
66
+ const answer = options.answer(turn.channel);
67
+ return answer
68
+ ? { answer }
69
+ : { reason: "this conversation takes no poll results" };
70
+ };
71
+ return {
72
+ backgroundRefusal: (turn) => {
73
+ const checked = check(turn);
74
+ return "reason" in checked ? checked.reason : undefined;
75
+ },
76
+ background: async (turn) => {
77
+ const { speaker } = turn;
78
+ if (!speaker)
79
+ return {
80
+ status: "skipped",
81
+ reason:
82
+ "a poll's results reach a claim through the router, which says whom they run as",
83
+ };
84
+ const checked = check({ ...turn, speaker });
85
+ if ("reason" in checked)
86
+ return { status: "skipped", reason: checked.reason };
87
+ const { answer } = checked;
88
+ const registry = options.conversations();
89
+ if (!registry)
90
+ return {
91
+ status: "skipped",
92
+ reason:
93
+ "the host records no conversations, so whose this one is cannot be checked",
94
+ };
95
+ const kept = await registry.get(turn.channel);
96
+ if (!kept)
97
+ return { status: "skipped", reason: "the conversation is gone" };
98
+ if (
99
+ kept.visibility === "private" &&
100
+ kept.principalId !== speaker.principalId
101
+ )
102
+ return {
103
+ status: "skipped",
104
+ reason:
105
+ "the conversation now belongs to someone other than the poll's starter",
106
+ };
107
+ const result = await options.turns.run({
108
+ channel: turn.channel,
109
+ kind: answer.kind,
110
+ text: turn.text,
111
+ speaker,
112
+ selection: answer.selection,
113
+ ...(answer.origin === undefined ? {} : { origin: answer.origin }),
114
+ unattended: true,
115
+ ...(turn.timeLimitMs === undefined
116
+ ? {}
117
+ : { timeLimitMs: turn.timeLimitMs }),
118
+ });
119
+ return result.ok
120
+ ? { status: "ran" }
121
+ : { status: "failed", error: "a poll's result turn failed" };
122
+ },
123
+ };
124
+ }