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
@@ -27,6 +27,7 @@ import {
27
27
  MODES,
28
28
  RUNTIME,
29
29
  } from "../plugin-api/services.ts";
30
+ import { RUNNER } from "../runner/runner-port.ts";
30
31
  import {
31
32
  BRIDGE_MEMORY_FIX,
32
33
  bridgeMemoryProblem,
@@ -69,6 +70,7 @@ export function agentSessionsSlot(): AgentSessionsSlot {
69
70
  }
70
71
 
71
72
  export interface RuntimePluginOptions {
73
+ imageTool?: NonNullable<PiAgentRuntimeOptions["imageTool"]>;
72
74
  /** Who the conversations serve, as prompts and tool results name them. */
73
75
  owner: OwnerIdentity & { id: string };
74
76
  /** Shared with the rest of the host, so logins refresh in one place. */
@@ -161,6 +163,11 @@ export function runtimePlugin(
161
163
  setup: async (context) => {
162
164
  const { logger, providers, services } = context;
163
165
  identity = services.find(IDENTITY);
166
+ // A configured runner that no plugin provides stops the boot, naming the runner plugin.
167
+ const runner = context.env.runner && {
168
+ settings: context.env.runner,
169
+ port: services.lazy(RUNNER),
170
+ };
164
171
  warn = (message) => logger.warn({}, message);
165
172
  const heldActions = await openHeldActions(context);
166
173
  const prompts = (channel: ChannelKey, scope?: PromptScope | Speaker) =>
@@ -205,7 +212,9 @@ export function runtimePlugin(
205
212
  },
206
213
  ...turnPolicy(options),
207
214
  sessions: context.sessions,
215
+ imageTool: options.imageTool ?? "every-selection",
208
216
  agentTools: context.env.agentTools,
217
+ ...(runner ? { runner } : {}),
209
218
  ...(context.env.shellEnv ? { shellEnv: context.env.shellEnv } : {}),
210
219
  agentDir: options.agentDir,
211
220
  modelRuntime: options.modelRuntime,
@@ -28,6 +28,8 @@ import type { Logger } from "../kernel/log.ts";
28
28
  import type { Autonomy } from "../modes/autonomy.ts";
29
29
  import type { ConversationModes } from "../modes/conversation-modes.ts";
30
30
  import type { AgentTools, LinkedSessions } from "../plugin-api/plugin.ts";
31
+ import type { RunnerSessions } from "../runner/runner-session.ts";
32
+ import type { RunnerBinding } from "../runner/runner-tools.ts";
31
33
  import type { ShellEnv } from "../shared/child-env.ts";
32
34
  import { secretMaskExtension } from "../shared/secret-mask.ts";
33
35
  import type { MemoryDraws } from "./extensions/private-memory.ts";
@@ -81,8 +83,16 @@ export interface PiAgentRuntimeOptions {
81
83
  sessions: () => LinkedSessions;
82
84
  /** The agent server's sessions: their shared workspace, model, and skills. */
83
85
  agents?: AgentSessions;
86
+ /** "selected": only a selection that names `generate_image` offers it; default "every-selection". */
87
+ imageTool?: "every-selection" | "selected";
84
88
  /** "chat-only": no turn carries the shell and file tools, and agent sessions have no workspace; default "full". */
85
89
  agentTools?: AgentTools;
90
+ /**
91
+ * The runner, when the host configures one: every session but the owner's own conversations
92
+ * then runs `bash`, `read`, `edit` and `write` in it, agents' included unless `agentTools` is
93
+ * "chat-only" (see `runnerServes`), and works in its workspace there.
94
+ */
95
+ runner?: RunnerSessions;
86
96
  /** What the sessions' shell gets of the host's environment besides `SHELL_ENV_NAMES`; see `HostEnvironment.shellEnv`. */
87
97
  shellEnv?: ShellEnv;
88
98
  /**
@@ -178,6 +188,8 @@ export interface CoreExtensions {
178
188
  privateMemory: ExtensionFactory;
179
189
  /** The formatting guidance of the surface the turn replies on, appended after the persona. */
180
190
  surfaceFormatting: ExtensionFactory;
191
+ /** Where a session the runner serves has its files and tools, appended after the formatting guidance. */
192
+ runnerPrompt?: ExtensionFactory;
181
193
  activeTools: ExtensionFactory;
182
194
  }
183
195
 
@@ -185,7 +197,8 @@ export interface CoreExtensions {
185
197
  * A session's extensions in load order: the tools phase, the core's attachment, gate, ask-user,
186
198
  * and compact guard, the compactor, the MCP phase, the memory projection, so each request is
187
199
  * projected after every other extension changed it, the surface's formatting guidance, so it follows
188
- * the persona and everything appended before it, the secret mask, and active-tools last, so its
200
+ * the persona and everything appended before it, the runner's line for a session it serves, the
201
+ * secret mask, and active-tools last, so its
189
202
  * before_agent_start handler runs after every other extension's.
190
203
  */
191
204
  export function sessionExtensions(
@@ -216,12 +229,25 @@ export function sessionExtensions(
216
229
  ...contributed(plan.mcp),
217
230
  { name: "private-memory", factory: core.privateMemory },
218
231
  { name: "surface-formatting", factory: core.surfaceFormatting },
232
+ ...(core.runnerPrompt
233
+ ? [{ name: "runner-prompt", factory: core.runnerPrompt }]
234
+ : []),
219
235
  // After every other tool_result handler, so what they add is masked too.
220
236
  { name: "secret-mask", factory: secretMaskExtension() },
221
237
  { name: "active-tools", factory: core.activeTools },
222
238
  ];
223
239
  }
224
240
 
241
+ /**
242
+ * What a worker session keeps of the conversation whose running turn it acts in, rather than
243
+ * taking its own kind's: that turn, the conversation's memory policy, and its place in the runner.
244
+ */
245
+ export interface WorkerScope {
246
+ turn: ChannelKey;
247
+ memory: SessionContext["memory"];
248
+ runner?: RunnerBinding;
249
+ }
250
+
225
251
  export interface ChannelSession {
226
252
  session: AgentSession;
227
253
  /** Read by the active-tools extension at the start of every run. */
@@ -238,4 +264,6 @@ export interface ChannelSession {
238
264
  memory: SessionContext["memory"];
239
265
  /** Its tool calls running now, which a task that reads the reader's memory marks as drawing on it. */
240
266
  draws: MemoryDraws;
267
+ /** Where the runner runs its shell and file tools, for a session the runner serves; a worker beside it keeps the same. */
268
+ runner?: RunnerBinding;
241
269
  }
@@ -23,21 +23,19 @@ import {
23
23
  import { type Speaker, THE_SPEAKER } from "../identity/speakers.ts";
24
24
  import type { LinkedSessions } from "../plugin-api/plugin.ts";
25
25
  import { toolTurn } from "../plugin-api/tool-turn.ts";
26
+ import { runnerPromptExtension } from "../runner/runner-prompt.ts";
27
+ import { runnerPlace } from "../runner/runner-session.ts";
28
+ import { HOST_ONLY_TOOLS, type RunnerBinding } from "../runner/runner-tools.ts";
26
29
  import { activeToolsExtension } from "../shared/active-tools.ts";
27
- import {
28
- ATTACH_FILE_TOOL,
29
- attachFileExtension,
30
- } from "../shared/attach-file-tool.ts";
31
- import { GENERATE_IMAGE_TOOL } from "../shared/generate-image-tool.ts";
30
+ import { attachFileExtension } from "../shared/attach-file-tool.ts";
32
31
  import { packageDir } from "../shared/package-dir.ts";
33
32
  import { readAttachmentExtension } from "../shared/read-attachment-tool.ts";
34
- import { refuseShellTools } from "./chat-only.ts";
35
33
  import {
36
34
  CompactionTiers,
37
35
  compactionEngine,
38
36
  HARD_COMPACT_TOKENS,
39
37
  } from "./compaction-tiers.ts";
40
- import { ASK_USER_TOOL, askUserExtension } from "./extensions/ask-user.ts";
38
+ import { askUserExtension } from "./extensions/ask-user.ts";
41
39
  import {
42
40
  type ConfirmationGate,
43
41
  confirmationGateExtension,
@@ -48,16 +46,14 @@ import {
48
46
  privateCompaction,
49
47
  privateMemoryExtension,
50
48
  } from "./extensions/private-memory.ts";
51
- import {
52
- COMPACT_TOOL,
53
- selfCompactGuardExtension,
54
- } from "./extensions/self-compact-guard.ts";
49
+ import { selfCompactGuardExtension } from "./extensions/self-compact-guard.ts";
55
50
  import { surfaceFormattingExtension } from "./extensions/surface-formatting.ts";
56
51
  import type { PromptSlot } from "./prompt-slot.ts";
57
52
  import type {
58
53
  ChannelSession,
59
54
  CompactionEnd,
60
55
  PiAgentRuntimeOptions,
56
+ WorkerScope,
61
57
  } from "./runtime-types.ts";
62
58
  import {
63
59
  type LoadedSkill,
@@ -71,7 +67,8 @@ import {
71
67
  turnAddressee,
72
68
  } from "./session-conversation.ts";
73
69
  import { imageTools, scratchBash } from "./session-helpers.ts";
74
- import { currentToolNames } from "./tool-tiers.ts";
70
+ import { sessionCustomTools, sessionWorkspace } from "./session-shell.ts";
71
+ import { requiredTools, taskTools, toolsFor } from "./session-tool-names.ts";
75
72
 
76
73
  export { imageTools, scratchBash };
77
74
 
@@ -147,47 +144,46 @@ export class SessionFactory {
147
144
  /**
148
145
  * The tools a selection turns into. A chat-only host refuses a selection that names a shell or
149
146
  * file tool, whatever built it (the agent team, `context.turns`, a plugin), so the turn fails
150
- * closed before any session runs it.
147
+ * closed before any session runs it, unless the runner serves the session (`runnerServed`).
151
148
  */
152
- toolsFor(selection: ToolSelection): string[] {
153
- if (this.chatOnly) refuseShellTools(selection.tools, "a tool selection");
154
- const groups = planOrder(this.plan).flatMap(
155
- (tool) => tool.snapshot().groups ?? [],
149
+ toolsFor(selection: ToolSelection, runnerServed = false): string[] {
150
+ return toolsFor(
151
+ selection,
152
+ this,
153
+ this.#options.logger,
154
+ this.#options.imageTool === "selected",
155
+ runnerServed,
156
156
  );
157
- return [
158
- ...currentToolNames(selection.tools, this.#options.logger),
159
- COMPACT_TOOL,
160
- ASK_USER_TOOL,
161
- // Registered only by a session with a workspace.
162
- ATTACH_FILE_TOOL,
163
- // Registered only with an image provider.
164
- GENERATE_IMAGE_TOOL,
165
- ...groups
166
- .filter((group) => selection.groups.includes(group.name))
167
- .flatMap((group) => group.tools),
168
- ];
169
157
  }
170
158
 
171
159
  /** The tools of a task beside a turn: its selection without what it excludes, and it never asks. */
172
- taskTools(selection: ToolSelection, exclude: readonly string[]): string[] {
173
- const excluded = new Set([
174
- ...currentToolNames(exclude, this.#options.logger),
175
- ASK_USER_TOOL,
176
- ]);
177
- return this.toolsFor(selection).filter((name) => !excluded.has(name));
160
+ taskTools(
161
+ selection: ToolSelection,
162
+ exclude: readonly string[],
163
+ runnerServed = false,
164
+ ): string[] {
165
+ return taskTools(
166
+ () => this.toolsFor(selection, runnerServed),
167
+ exclude,
168
+ this.#options.logger,
169
+ );
170
+ }
171
+
172
+ /** Where the runner runs a session's tools, or undefined; see `runnerPlace`. */
173
+ runnerFor(
174
+ agent: AgentTurnScope | undefined,
175
+ kind: string,
176
+ home: ChannelKey,
177
+ ): RunnerBinding | undefined {
178
+ const { runner, agents } = this.#options;
179
+ return runnerPlace(runner, { agent, kind, home }, this.chatOnly, agents);
178
180
  }
179
181
 
180
182
  /** Every tool startup refuses to run without: the plugins', the core's, and the session tools'. */
181
183
  requiredTools(): string[] {
182
- return currentToolNames(
183
- [
184
- ...this.link().requiredTools,
185
- COMPACT_TOOL,
186
- ASK_USER_TOOL,
187
- ...planOrder(this.plan).flatMap(
188
- (tool) => tool.snapshot().requiredTools ?? [],
189
- ),
190
- ],
184
+ return requiredTools(
185
+ this.link().requiredTools,
186
+ this.plan,
191
187
  this.#options.logger,
192
188
  );
193
189
  }
@@ -293,11 +289,8 @@ export class SessionFactory {
293
289
  kind: string,
294
290
  /** Whom the conversation serves, fixed for the session's life. */
295
291
  conversation: SessionConversation,
296
- /**
297
- * A worker's: the conversation whose running turn it acts in, and that conversation's memory
298
- * policy, which it keeps rather than reading its own kind's.
299
- */
300
- worker?: { turn: ChannelKey; memory: SessionContext["memory"] },
292
+ /** A worker's: the turn it acts in, and that conversation's memory policy and runner place. */
293
+ worker?: WorkerScope,
301
294
  ): Promise<ChannelSession> {
302
295
  const { agentDir, model, thinking, logger } = this.#options;
303
296
  // An agent's prompt is set before each run; the other kinds are refused here, before a session is built.
@@ -314,6 +307,9 @@ export class SessionFactory {
314
307
  // The running turn is the conversation's: an agent's seat in a group, or its own channel; a
315
308
  // worker's is the turn that started it.
316
309
  const turnKey = worker?.turn ?? agent?.session ?? channel;
310
+ const runner = worker
311
+ ? worker.runner
312
+ : this.runnerFor(agent, kind, channel);
317
313
  const deps = this.#deps;
318
314
  const state = {
319
315
  tools: [] as readonly string[],
@@ -326,6 +322,7 @@ export class SessionFactory {
326
322
  return deps.withholdsMemory(turnKey) ? "none" : memory;
327
323
  },
328
324
  draws: new MemoryDraws(),
325
+ ...(runner ? { runner } : {}),
329
326
  };
330
327
  const awaited = planOrder(this.plan).flatMap(
331
328
  (tool) => tool.snapshot().awaitTools ?? [],
@@ -367,15 +364,7 @@ export class SessionFactory {
367
364
  },
368
365
  conversation,
369
366
  addressee,
370
- // A chat-only host's agents work in no workspace.
371
- ...(agents && !this.chatOnly
372
- ? {
373
- workspace: {
374
- workspace: cwd,
375
- ...(agents.scratchDir ? { scratchDir: agents.scratchDir } : {}),
376
- },
377
- }
378
- : {}),
367
+ ...sessionWorkspace(cwd, agents, this.chatOnly, runner),
379
368
  attachmentDir,
380
369
  get memory() {
381
370
  return state.memory;
@@ -451,6 +440,9 @@ export class SessionFactory {
451
440
  // A worker writes a report for the turn, not a reply on its surface.
452
441
  worker ? undefined : deps.formatting(turnKey),
453
442
  ),
443
+ ...(runner
444
+ ? { runnerPrompt: runnerPromptExtension(runner, () => state.tools) }
445
+ : {}),
454
446
  activeTools: activeToolsExtension(() => state.tools),
455
447
  }),
456
448
  ],
@@ -462,10 +454,15 @@ export class SessionFactory {
462
454
  const { session } = await createAgentSession({
463
455
  cwd,
464
456
  agentDir,
465
- // Pi's bash under its own name, with the shell's environment and TMPDIR at the agents' scratch dir.
466
- customTools: this.chatOnly
467
- ? []
468
- : [scratchBash(cwd, agents?.scratchDir, this.#options.shellEnv)],
457
+ customTools: sessionCustomTools(
458
+ cwd,
459
+ agents,
460
+ this.chatOnly,
461
+ this.#options.shellEnv,
462
+ runner,
463
+ ),
464
+ // Pi's own tools that would reach the bot's disk or shell are not there to activate.
465
+ ...(runner ? { excludeTools: [...HOST_ONLY_TOOLS] } : {}),
469
466
  thinkingLevel: thinking,
470
467
  modelRuntime: this.#modelRuntime,
471
468
  resourceLoader,
@@ -0,0 +1,43 @@
1
+ import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
2
+ import type { AgentSessions } from "../contract/runtime.ts";
3
+ import type { SessionContext } from "../domain/sessions.ts";
4
+ import { runnerRoots } from "../runner/runner-session.ts";
5
+ import { type RunnerBinding, runnerTools } from "../runner/runner-tools.ts";
6
+ import type { ShellEnv } from "../shared/child-env.ts";
7
+ import { scratchBash } from "./session-helpers.ts";
8
+
9
+ /**
10
+ * Only a full-tools host's agent sessions expose a workspace on the host; a session the runner
11
+ * serves has its workspace in the runner, reached through the runner alone.
12
+ */
13
+ export function sessionWorkspace(
14
+ cwd: string,
15
+ agents: AgentSessions | undefined,
16
+ chatOnly: boolean,
17
+ runner?: RunnerBinding,
18
+ ): Pick<SessionContext, "workspace"> {
19
+ if (runner) return { workspace: runnerRoots(runner) };
20
+ return agents && !chatOnly
21
+ ? {
22
+ workspace: {
23
+ workspace: cwd,
24
+ ...(agents.scratchDir ? { scratchDir: agents.scratchDir } : {}),
25
+ },
26
+ }
27
+ : {};
28
+ }
29
+
30
+ /**
31
+ * Pi's bash under its own name, with the shell's environment and TMPDIR at the agents' scratch dir;
32
+ * for a session the runner serves, `bash`, `read`, `edit` and `write` that run in the runner.
33
+ */
34
+ export function sessionCustomTools(
35
+ cwd: string,
36
+ agents: AgentSessions | undefined,
37
+ chatOnly: boolean,
38
+ shellEnv: ShellEnv | undefined,
39
+ runner?: RunnerBinding,
40
+ ): ToolDefinition[] {
41
+ if (runner) return runnerTools(runner);
42
+ return chatOnly ? [] : [scratchBash(cwd, agents?.scratchDir, shellEnv)];
43
+ }
@@ -0,0 +1,78 @@
1
+ import {
2
+ planOrder,
3
+ type SessionPlan,
4
+ type ToolSelection,
5
+ } from "../domain/sessions.ts";
6
+ import type { Logger } from "../kernel/log.ts";
7
+ import { refuseHostOnlyTools } from "../runner/runner-tools.ts";
8
+ import { ATTACH_FILE_TOOL } from "../shared/attach-file-tool.ts";
9
+ import { GENERATE_IMAGE_TOOL } from "../shared/generate-image-tool.ts";
10
+ import { refuseShellTools } from "./chat-only.ts";
11
+ import { ASK_USER_TOOL } from "./extensions/ask-user.ts";
12
+ import { COMPACT_TOOL } from "./extensions/self-compact-guard.ts";
13
+ import { currentToolNames } from "./tool-tiers.ts";
14
+
15
+ /**
16
+ * A chat-only host refuses shell and file tools before resolving the session's plan, except for a
17
+ * session the runner serves (`runnerServed`), whose shell and file tools run in the runner; such a
18
+ * session refuses Pi's tools the runner does not run, on any host.
19
+ */
20
+ export function toolsFor(
21
+ selection: ToolSelection,
22
+ source: { readonly chatOnly: boolean; readonly plan: SessionPlan },
23
+ logger: Logger,
24
+ selectedImages: boolean,
25
+ runnerServed = false,
26
+ ): string[] {
27
+ if (source.chatOnly && !runnerServed)
28
+ refuseShellTools(selection.tools, "a tool selection");
29
+ if (runnerServed) refuseHostOnlyTools(selection.tools, "a tool selection");
30
+ const groups = planOrder(source.plan).flatMap(
31
+ (tool) => tool.snapshot().groups ?? [],
32
+ );
33
+ return [
34
+ ...currentToolNames(selection.tools, logger),
35
+ COMPACT_TOOL,
36
+ ASK_USER_TOOL,
37
+ // Registered only by a session with a workspace.
38
+ ATTACH_FILE_TOOL,
39
+ // Registered only with an image provider.
40
+ ...(!selectedImages && !selection.tools.includes(GENERATE_IMAGE_TOOL)
41
+ ? [GENERATE_IMAGE_TOOL]
42
+ : []),
43
+ ...groups
44
+ .filter((group) => selection.groups.includes(group.name))
45
+ .flatMap((group) => group.tools)
46
+ .filter((tool) => !selectedImages || tool !== GENERATE_IMAGE_TOOL),
47
+ ];
48
+ }
49
+
50
+ /** A task excludes the given names and never asks. Resolve its selection after checking aliases. */
51
+ export function taskTools(
52
+ selected: () => string[],
53
+ exclude: readonly string[],
54
+ logger: Logger,
55
+ ): string[] {
56
+ const excluded = new Set([
57
+ ...currentToolNames(exclude, logger),
58
+ ASK_USER_TOOL,
59
+ ]);
60
+ return selected().filter((name) => !excluded.has(name));
61
+ }
62
+
63
+ /** Startup checks the plugins', core's and session tools' required names. */
64
+ export function requiredTools(
65
+ pluginTools: readonly string[],
66
+ plan: SessionPlan,
67
+ logger: Logger,
68
+ ): string[] {
69
+ return currentToolNames(
70
+ [
71
+ ...pluginTools,
72
+ COMPACT_TOOL,
73
+ ASK_USER_TOOL,
74
+ ...planOrder(plan).flatMap((tool) => tool.snapshot().requiredTools ?? []),
75
+ ],
76
+ logger,
77
+ );
78
+ }
@@ -0,0 +1,97 @@
1
+ import type { TurnConversation, TurnRequest } from "../domain/ports.ts";
2
+ import type { OwnerIdentity } from "../identity/owner-identity.ts";
3
+ import type { ConfirmationGate } from "./extensions/confirmation-gate.ts";
4
+ import { loadsMemory } from "./extensions/private-memory.ts";
5
+ import { turnYolo } from "./extensions/yolo.ts";
6
+ import { recordMemoryTurn } from "./reader-history.ts";
7
+ import type { ChannelSession, PiAgentRuntimeOptions } from "./runtime-types.ts";
8
+ import { memoryReader } from "./session-conversation.ts";
9
+ import type { SessionFactory } from "./session-factory.ts";
10
+ import type { ToolTiers } from "./tool-tiers.ts";
11
+ import { turnTools } from "./turn-tools.ts";
12
+
13
+ /** Select at the speaker's tier and record memory use before the runtime publishes the turn. */
14
+ export function selectTurn(
15
+ request: TurnRequest,
16
+ conversation: TurnConversation,
17
+ channelSession: ChannelSession,
18
+ gate: ConfirmationGate,
19
+ factory: SessionFactory,
20
+ tiers: ToolTiers,
21
+ options: PiAgentRuntimeOptions,
22
+ ) {
23
+ const { session } = channelSession;
24
+ // What this turn's message may release: a held call that named approvers is theirs alone.
25
+ const pending = request.confirmed
26
+ ? gate.releasable(request.speaker)
27
+ : gate.pending();
28
+ const registered = new Set(session.getAllTools().map((tool) => tool.name));
29
+ // The speaker's tier limits the tools.
30
+ const { tier } = request.speaker;
31
+ // An approving turn also has the held calls' tools, which a dispatched worker may have used.
32
+ // The agent server may keep a speaker below the owner tier out of memory: no tools, no block.
33
+ const withheld =
34
+ request.agent !== undefined &&
35
+ options.agents?.memory === "owners" &&
36
+ tier !== "owner";
37
+ const wanted = turnTools(
38
+ {
39
+ selected: factory.toolsFor(
40
+ request.selection,
41
+ channelSession.runner !== undefined,
42
+ ),
43
+ held: request.confirmed && pending ? pending.calls : [],
44
+ tier,
45
+ withheld,
46
+ },
47
+ tiers,
48
+ );
49
+ const markPrivateMemory = recordMemoryTurn(
50
+ session.sessionManager,
51
+ request.speaker.principalId,
52
+ !withheld &&
53
+ channelSession.memory !== "none" &&
54
+ memoryReader(conversation, request.speaker) !== undefined &&
55
+ loadsMemory(registered),
56
+ );
57
+ return {
58
+ pending,
59
+ tier,
60
+ withheld,
61
+ markPrivateMemory,
62
+ // Activate only after the running turn and its memory marker are visible to tools.
63
+ activate(who: OwnerIdentity) {
64
+ const missing = wanted.filter((name) => !registered.has(name));
65
+ if (missing.length > 0) {
66
+ options.logger.warn(
67
+ {
68
+ channel: request.channel,
69
+ selection: request.selection.id,
70
+ missing,
71
+ },
72
+ "selected tools missing; running without them",
73
+ );
74
+ }
75
+ channelSession.tools = wanted.filter((name) => registered.has(name));
76
+ session.setActiveToolsByName([...channelSession.tools]);
77
+ gate.beginTurn(
78
+ request.selection.id,
79
+ request.confirmed === true,
80
+ who,
81
+ request.speaker,
82
+ conversation.visibility === "private",
83
+ turnYolo(options, request),
84
+ request.byMessage === true,
85
+ );
86
+ if (request.confirmed && pending && pending.calls.length > 0) {
87
+ options.logger.info(
88
+ {
89
+ channel: request.channel,
90
+ tools: pending.calls.map((call) => call.tool),
91
+ },
92
+ "confirmed actions released",
93
+ );
94
+ }
95
+ },
96
+ };
97
+ }
@@ -1,10 +1,14 @@
1
1
  import { join } from "node:path";
2
- import { wasExpired } from "../attachments/attachment-expiry.ts";
2
+ import {
3
+ wasExpired,
4
+ wasModelImageHidden,
5
+ } from "../attachments/attachment-expiry.ts";
3
6
  import { MAX_ATTACHMENT_BYTES } from "../attachments/attachment-fetcher.ts";
4
7
  import { isAttachmentName, plainText } from "../attachments/attachment-name.ts";
5
8
  import { AttachmentExpiredError } from "../attachments/tool-attachment.ts";
6
9
  import {
7
10
  ATTACHMENT_TEXT_LIMIT,
11
+ AttachmentTextError,
8
12
  readAttachmentText,
9
13
  } from "./attachment-text.ts";
10
14
 
@@ -36,6 +40,11 @@ export async function readAttachment(
36
40
  throw new AttachmentExpiredError(plainText(file));
37
41
  throw new Error(`no attachment named "${file}" in this channel`);
38
42
  }
43
+ if (await wasModelImageHidden(dir, file))
44
+ throw new AttachmentTextError(
45
+ "unsupported",
46
+ `"${plainText(file)}": This image is not shown to you; use a document tool that reads image files.`,
47
+ );
39
48
  // A file a surface took past the default limit is for tools that take files, not for reading whole.
40
49
  if (handle.size > MAX_ATTACHMENT_BYTES)
41
50
  throw new Error(
@@ -1,4 +1,3 @@
1
- import { mkdir, writeFile } from "node:fs/promises";
2
1
  import { join } from "node:path";
3
2
  import type { ExtensionFactory } from "@earendil-works/pi-coding-agent";
4
3
  import { Type } from "typebox";
@@ -14,6 +13,7 @@ import {
14
13
  readWorkspaceFile,
15
14
  WorkspaceFileError,
16
15
  type WorkspaceRoots,
16
+ writeWorkspaceFile,
17
17
  } from "./workspace-files.ts";
18
18
 
19
19
  export const GENERATE_IMAGE_TOOL = "generate_image";
@@ -85,7 +85,8 @@ async function readReferences(
85
85
 
86
86
  /**
87
87
  * Registers `generate_image`, which draws a new picture with the host's image provider, saves it
88
- * under `<scratch dir or workspace>/drawings`, and attaches it to the turn's reply.
88
+ * under `<scratch dir or workspace>/drawings`, and attaches it to the turn's reply. Roots with
89
+ * `files`, such as a runner's workspace, are read and written there alone.
89
90
  */
90
91
  export function generateImageExtension(
91
92
  draw: ImageDrawer,
@@ -148,10 +149,9 @@ export function generateImageExtension(
148
149
  "The image provider returned something that is not a PNG, JPEG, WebP or GIF image.",
149
150
  );
150
151
  const dir = join(roots.scratchDir ?? roots.workspace, "drawings");
151
- await mkdir(dir, { recursive: true });
152
152
  const name = `generated-${new Date().toISOString().replace(/[:.]/g, "-")}.${type.ext}`;
153
153
  const path = join(dir, name);
154
- await writeFile(path, data);
154
+ await writeWorkspaceFile(path, data, roots);
155
155
  try {
156
156
  if (data.byteLength > REPLY_FILE_LIMITS.maxFileBytes)
157
157
  throw new ReplyFileError(
@@ -0,0 +1,14 @@
1
+ import type { BackgroundTarget } from "../contract/channels.ts";
2
+ import { messages } from "../i18n/index.ts";
3
+
4
+ /**
5
+ * The turns that bring a poll's results back to the conversation that posted it, run as the
6
+ * person who started the poll. The polls plugin contributes it; nothing may be scheduled or
7
+ * delegated for it. A claim answers it in its `background` beside its own target: the agent
8
+ * server's does, and a host's own claim adds it the same way. Its label is read when a list is
9
+ * shown, in the host's locale.
10
+ */
11
+ export const POLL_TARGET: BackgroundTarget = {
12
+ name: "poll",
13
+ label: () => messages().scheduleModePoll,
14
+ };