pi-roundtable 0.53.6 → 0.54.1

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 +18 -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
@@ -7,9 +7,16 @@ import type {
7
7
  } from "../domain/conversation.ts";
8
8
  import type { ThinkingLevel } from "../domain/models.ts";
9
9
  import type { TurnConversation, TurnRequest } from "../domain/ports.ts";
10
+ import type { HoldContext } from "../plugin-api/holds.ts";
11
+ import { runnerGate } from "../runner/runner-session.ts";
12
+ import type { RunnerBinding } from "../runner/runner-tools.ts";
10
13
  import { ConfirmationGate, unexpired } from "./extensions/confirmation-gate.ts";
11
14
  import { PromptSlot } from "./prompt-slot.ts";
12
- import type { ChannelSession, PiAgentRuntimeOptions } from "./runtime-types.ts";
15
+ import type {
16
+ AgentSessions,
17
+ ChannelSession,
18
+ PiAgentRuntimeOptions,
19
+ } from "./runtime-types.ts";
13
20
  import { revisionsKey, skillsKey } from "./runtime-types.ts";
14
21
  import {
15
22
  conversationChanged,
@@ -92,26 +99,27 @@ export class ConversationSessions {
92
99
 
93
100
  /**
94
101
  * One gate per conversation, restored from the store the first time it is used. An agent's
95
- * gate also judges its shell and file tools against the shared workspace.
102
+ * gate also judges its shell and file tools against the shared workspace; the gate of a
103
+ * conversation the runner serves judges them against its workspace there, at the runner's tiers.
96
104
  */
97
- async gate(key: ChannelKey, agent: boolean): Promise<ConfirmationGate> {
105
+ async gate(
106
+ key: ChannelKey,
107
+ agent: boolean,
108
+ runner?: RunnerBinding,
109
+ ): Promise<ConfirmationGate> {
98
110
  let gate = this.#gates.get(key);
99
111
  if (!gate) {
100
112
  const agents = agent ? this.#options.agents : undefined;
113
+ const inRunner = runner ? runnerGate(runner, this.#tiers) : undefined;
101
114
  gate = new ConfirmationGate(
102
115
  this.#factory.link().holds,
103
116
  this.#options.owner,
104
117
  await this.#options.confirmations.load(key),
105
- // A chat-only host's agents have no shell, so their gate judges no workspace.
106
- agents && this.#options.agentTools !== "chat-only"
107
- ? {
108
- workspace: agents.workDir,
109
- ...(agents.scratchDir ? { scratchDir: agents.scratchDir } : {}),
110
- }
111
- : {},
112
- this.#tiers,
118
+ inRunner?.context ?? this.#hostContext(agents),
119
+ inRunner?.tiers ?? this.#tiers,
113
120
  // Owner sessions have no shell workspace but still send files from their own directory.
114
- agents ? agents.workDir : this.#factory.cwd(undefined),
121
+ runner?.workspace ??
122
+ (agents ? agents.workDir : this.#factory.cwd(undefined)),
115
123
  undefined,
116
124
  // A disabled principal cannot approve, so it is not named as one who can.
117
125
  async (id) => {
@@ -140,6 +148,16 @@ export class ConversationSessions {
140
148
  return gate;
141
149
  }
142
150
 
151
+ /** What an agent's gate judges on the host; a chat-only host's agents have no shell, so none. */
152
+ #hostContext(agents: AgentSessions | undefined): HoldContext {
153
+ return agents && this.#options.agentTools !== "chat-only"
154
+ ? {
155
+ workspace: agents.workDir,
156
+ ...(agents.scratchDir ? { scratchDir: agents.scratchDir } : {}),
157
+ }
158
+ : {};
159
+ }
160
+
143
161
  slot(key: ChannelKey): PromptSlot {
144
162
  let slot = this.#slots.get(key);
145
163
  if (!slot) {
@@ -185,14 +203,20 @@ export class ConversationSessions {
185
203
  this.#restored.delete(key);
186
204
  await this.#options.confirmations.save(key, undefined);
187
205
  }
206
+ const home = agent?.home ?? channel;
207
+ const kind = request?.kind ?? "owner";
188
208
  return this.#factory.create(
189
- agent?.home ?? channel,
209
+ home,
190
210
  history,
191
- await this.gate(key, agent !== undefined),
211
+ await this.gate(
212
+ key,
213
+ agent !== undefined,
214
+ this.#placeOf(key, request),
215
+ ),
192
216
  this.slot(key),
193
217
  ownerAttachmentDir(this.#options.dataDir, channel),
194
218
  agent,
195
- request?.kind ?? "owner",
219
+ kind,
196
220
  conversation,
197
221
  );
198
222
  })();
@@ -244,6 +268,27 @@ export class ConversationSessions {
244
268
  await this.forget(key);
245
269
  return this.session(key, request);
246
270
  }
271
+ // Where the runner runs an agent's tools moved (a temp knight's origin is gone, say): the
272
+ // session and its gate are made anew there, keeping the history; what was held is dropped,
273
+ // as it was judged, and would run, in the place it left. Another kind's place is its kind's,
274
+ // fixed with the session.
275
+ if (
276
+ request.agent !== undefined &&
277
+ channelSession.runner?.conversation !==
278
+ this.#placeOf(key, request)?.conversation
279
+ ) {
280
+ this.#options.logger.info(
281
+ { channel: key },
282
+ "the conversation's place in the runner changed; starting its session there",
283
+ );
284
+ channelSession.session.dispose();
285
+ this.#sessions.delete(key);
286
+ this.#gates.get(key)?.abandon();
287
+ this.#gates.delete(key);
288
+ this.#restored.delete(key);
289
+ await this.#options.confirmations.save(key, undefined);
290
+ return this.session(key, request);
291
+ }
247
292
  const stale = this.#staleReason(channelSession, request);
248
293
  if (!stale) return channelSession;
249
294
  this.#options.logger.info(
@@ -255,6 +300,19 @@ export class ConversationSessions {
255
300
  return this.session(key, request);
256
301
  }
257
302
 
303
+ /** Where the runner runs the tools of the conversation's session for this request; undefined on the host. */
304
+ #placeOf(
305
+ key: ChannelKey,
306
+ request?: Pick<TurnRequest, "channel" | "agent" | "kind">,
307
+ ): RunnerBinding | undefined {
308
+ const agent = request?.agent;
309
+ return this.#factory.runnerFor(
310
+ agent,
311
+ request?.kind ?? "owner",
312
+ agent?.home ?? request?.channel ?? key,
313
+ );
314
+ }
315
+
258
316
  /** Why a cached session must be rebuilt, keeping its history, before this turn; undefined when it is current. */
259
317
  #staleReason(
260
318
  channelSession: ChannelSession,
@@ -17,6 +17,14 @@ const CARD_INPUT_CHARS = 1_500;
17
17
  const CARD_HIDDEN_KEYS = 20;
18
18
  const CARD_KEY_CHARS = 40;
19
19
 
20
+ /** The size of a file a held call sends by path, or undefined when it cannot be told. */
21
+ export type FileSizeOf = (path: string) => number | undefined;
22
+
23
+ /** Sizes read from the host's disk, relative paths against `workspace`. */
24
+ export function hostFileSizes(workspace: string | undefined): FileSizeOf {
25
+ return (path) => fileSize(path, workspace);
26
+ }
27
+
20
28
  /** What an approval card shows of a call's input; see `approvalCard`. */
21
29
  export interface CardLimits {
22
30
  /**
@@ -48,6 +56,16 @@ export function approvalCard(
48
56
  workspace?: string,
49
57
  limits: CardLimits = {},
50
58
  parameters?: unknown,
59
+ ): string {
60
+ return approvalCardSized(call, hostFileSizes(workspace), limits, parameters);
61
+ }
62
+
63
+ /** `approvalCard` with the files' sizes told by `sizeOf`, as the gate of a session the runner serves tells none. */
64
+ export function approvalCardSized(
65
+ call: HeldCall,
66
+ sizeOf: FileSizeOf,
67
+ limits: CardLimits = {},
68
+ parameters?: unknown,
51
69
  ): string {
52
70
  const valueChars = limits.valueChars ?? CARD_VALUE_CHARS;
53
71
  const totalChars = limits.totalChars ?? CARD_INPUT_CHARS;
@@ -56,7 +74,7 @@ export function approvalCard(
56
74
  ? fieldList(fields, { valueChars, totalChars })
57
75
  : `\`\`\`json\n${shownInput(call.input, valueChars, totalChars).replaceAll("```", "`\u200b``")}\n\`\`\``;
58
76
  const files = pathFiles(call.input).map(
59
- (path) => `\n-# ${messages().cardFile(path, fileSize(path, workspace))}`,
77
+ (path) => `\n-# ${messages().cardFile(path, sizeOf(path))}`,
60
78
  );
61
79
  return `**${call.action}**\n-# \`${call.tool}\`\n${body}${files.join("")}`;
62
80
  }
@@ -141,9 +159,18 @@ export function approvalDetails(
141
159
  call: HeldCall,
142
160
  workspace?: string,
143
161
  copy?: ApprovalDetails["copy"],
162
+ ): ApprovalDetails {
163
+ return approvalDetailsSized(call, hostFileSizes(workspace), copy);
164
+ }
165
+
166
+ /** `approvalDetails` with the files' sizes told by `sizeOf`; see `approvalCardSized`. */
167
+ export function approvalDetailsSized(
168
+ call: HeldCall,
169
+ sizeOf: FileSizeOf,
170
+ copy?: ApprovalDetails["copy"],
144
171
  ): ApprovalDetails {
145
172
  const files = pathFiles(call.input).map((path) => {
146
- const bytes = fileSize(path, workspace);
173
+ const bytes = sizeOf(path);
147
174
  return bytes === undefined ? { path } : { path, bytes };
148
175
  });
149
176
  return {
@@ -2,25 +2,21 @@ import type {
2
2
  HeldCall,
3
3
  PendingConfirmation,
4
4
  } from "../../domain/conversation.ts";
5
- import { messages } from "../../i18n/index.ts";
6
5
  import type { OwnerIdentity } from "../../identity/owner-identity.ts";
7
6
  import type { ApprovedBy, Prompts } from "../../interactions/prompts.ts";
8
7
  import {
9
8
  HOLD_DESCRIBE_TIMEOUT_MS,
10
9
  type HoldCheck,
11
10
  type HoldContext,
12
- higherTier,
13
11
  isPromise,
14
12
  } from "../../plugin-api/holds.ts";
15
13
  import type { ToolTiers } from "../tool-tiers.ts";
16
- import { approvalCard, approvalDetails } from "./approval-card.ts";
17
- import { askOnCard } from "./card-ask.ts";
14
+ import { type FileSizeOf, hostFileSizes } from "./approval-card.ts";
15
+ import { gateCardDecision, openGateCard } from "./gate-card.ts";
18
16
  import {
19
17
  type AutoApprover,
20
18
  approverOf,
21
19
  askSpeaker,
22
- awaitingText,
23
- declinedRefusal,
24
20
  type GateDecision,
25
21
  type Needing,
26
22
  namesOf,
@@ -34,7 +30,6 @@ import { type Grant, Grants } from "./grants.ts";
34
30
  import {
35
31
  canonicalJson,
36
32
  mayApproveNamed,
37
- namedApprover,
38
33
  sameCall,
39
34
  spendApproval,
40
35
  unexpired,
@@ -46,7 +41,6 @@ import {
46
41
  type Judgment,
47
42
  STOPPED,
48
43
  } from "./hold-lookups.ts";
49
- import { lateOutcome } from "./late-answer.ts";
50
44
  import { LateReleases } from "./late-releases.ts";
51
45
 
52
46
  export { confirmationGateExtension } from "./confirmation-gate-extension.ts";
@@ -92,7 +86,8 @@ export class ConfirmationGate {
92
86
  readonly #context: HoldContext;
93
87
  readonly #tiers: ToolTiers | undefined;
94
88
  /** Where the session's relative file paths resolve, for the sizes a card shows. */
95
- readonly #fileRoot: string | undefined;
89
+ /** The sizes a card shows of the files a call sends; none for a session the runner serves. */
90
+ readonly #fileSizes: FileSizeOf;
96
91
  /** The name a principal goes by, for telling a speaker who may approve a call; undefined when unknown. */
97
92
  readonly #nameOf:
98
93
  | ((principalId: string) => Promise<string | undefined>)
@@ -113,7 +108,8 @@ export class ConfirmationGate {
113
108
  * `holds` decides which calls wait for the owner. With a workspace, the session has a shell,
114
109
  * and its writes outside the workspace and the context's scratch dir are held too.
115
110
  * `fileRoot` is the session's working directory, where a card resolves relative file paths;
116
- * it defaults to the workspace. A hold that looks things up gets `describeTimeoutMs` to answer
111
+ * it defaults to the workspace. A session the runner serves (`context.runner`) has its files
112
+ * in the runner, so its cards name them without a size. A hold that looks things up gets `describeTimeoutMs` to answer
117
113
  * (`HOLD_DESCRIBE_TIMEOUT_MS` by default) before its call is held under a generic description.
118
114
  * `nameOf` gives the name of a principal a call names as an approver, which the text a speaker
119
115
  * who cannot approve it is given lists.
@@ -131,7 +127,10 @@ export class ConfirmationGate {
131
127
  this.#describer = new HoldDescriber(holds, context, describeTimeoutMs);
132
128
  this.#nameOf = nameOf;
133
129
  this.#tiers = tiers;
134
- this.#fileRoot = fileRoot ?? context.workspace;
130
+ // A session the runner serves has its files in the runner: the host's disk says nothing of them.
131
+ this.#fileSizes = context.runner
132
+ ? () => undefined
133
+ : hostFileSizes(fileRoot ?? context.workspace);
135
134
  this.#holds = holds;
136
135
  this.#owner = owner;
137
136
  this.#addressee = owner;
@@ -331,59 +330,21 @@ export class ConfirmationGate {
331
330
  // In a private conversation only its person answers: a call that names others is not theirs.
332
331
  if (this.#private && !mayApproveNamed(this.#speaker, call))
333
332
  return held("held");
334
- const { answer, approvedBy, approvedPrompt } = await askOnCard(
335
- ask.prompts,
336
- {
337
- title: messages().confirmTitle(ask.asker),
338
- message: approvalCard(call, this.#fileRoot, {}, parameters),
339
- signal: ask.signal,
340
- minTier: higherTier(this.#tiers?.minTier(call.tool), call.minTier),
341
- wait: {
342
- // A late answer on the card: the text of the turn that tells the model, and the release it earned.
343
- late: (late) => {
344
- const outcome = lateOutcome(call, late, watch, needing.onDeclined);
345
- if (outcome?.release) this.#late.add(outcome.release);
346
- return outcome?.text;
347
- },
348
- },
349
- details: approvalDetails(call, this.#fileRoot, needing.copy),
350
- approvers: call.approverIds,
351
- speakerOnly: needing.speakerOnly === true,
352
- watch,
353
- },
333
+ const answer = await openGateCard(
334
+ ask,
335
+ needing,
336
+ watch,
337
+ parameters,
338
+ this.#fileSizes,
339
+ this.#tiers,
340
+ this.#late,
354
341
  );
355
- // Whatever the card then reports, a call the plugin withdrew is refused, never held again.
356
- if (answer === "withdrawn" || (watch?.withdrawn && answer !== "approved"))
357
- return withdrawn(call);
358
- if (answer === "approved") {
359
- // A private conversation's answer to a call that names approvers is its person's, whom a surface need not name.
360
- const by =
361
- approvedBy ??
362
- (this.#private && call.approverIds
363
- ? approverOf(this.#speaker)
364
- : undefined);
365
- // A call that names approvers runs only on the word of one of them, or an owner.
366
- if (!namedApprover(call, by)) return held("held");
367
- watch?.end();
368
- return {
369
- approvedOnCard: true,
370
- ...(by ? { approvedBy: by } : {}),
371
- ...(approvedPrompt ? { approvedPrompt } : {}),
372
- };
373
- }
374
- if (answer === "pending")
375
- return {
376
- reason: awaitingText(this.#addressee, call),
377
- refused: "pending",
378
- };
379
- if (answer === "declined")
380
- return declinedRefusal(this.#addressee, call, watch, needing.onDeclined);
381
- if (answer === "cancelled") {
382
- watch?.end();
383
- return { reason: "The turn was stopped." };
384
- }
385
- // No card was shown, or it went unanswered: the call is held for a message, and stays withdrawable.
386
- return held(answer === "unavailable" ? "held" : "expired");
342
+ return gateCardDecision(answer, needing, watch, {
343
+ isPrivate: this.#private,
344
+ speaker: this.#speaker,
345
+ addressee: this.#addressee,
346
+ held,
347
+ });
387
348
  }
388
349
 
389
350
  /** What a call needs when a rule holds it; undefined when none does. */
@@ -0,0 +1,105 @@
1
+ import type { HeldCall } from "../../domain/conversation.ts";
2
+ import { messages } from "../../i18n/index.ts";
3
+ import type { OwnerIdentity } from "../../identity/owner-identity.ts";
4
+ import type { Prompts } from "../../interactions/prompts.ts";
5
+ import { higherTier } from "../../plugin-api/holds.ts";
6
+ import type { ToolTiers } from "../tool-tiers.ts";
7
+ import {
8
+ approvalCardSized,
9
+ approvalDetailsSized,
10
+ type FileSizeOf,
11
+ } from "./approval-card.ts";
12
+ import { askOnCard, type CardAnswer } from "./card-ask.ts";
13
+ import {
14
+ approverOf,
15
+ awaitingText,
16
+ declinedRefusal,
17
+ type GateDecision,
18
+ type Needing,
19
+ type SpeakerRef,
20
+ withdrawn,
21
+ } from "./gate-refusals.ts";
22
+ import { namedApprover } from "./held-calls.ts";
23
+ import { lateOutcome } from "./late-answer.ts";
24
+ import type { LateReleases } from "./late-releases.ts";
25
+ import type { Watch } from "./withdrawals.ts";
26
+
27
+ type Held = Extract<Needing, { held: HeldCall }>;
28
+
29
+ /** Open the held call's card and record any release that arrives after this turn. */
30
+ export function openGateCard(
31
+ ask: { prompts: Prompts; asker: string; signal?: AbortSignal },
32
+ needing: Held,
33
+ watch: Watch | undefined,
34
+ parameters: unknown,
35
+ sizeOf: FileSizeOf,
36
+ tiers: ToolTiers | undefined,
37
+ releases: LateReleases,
38
+ ): Promise<CardAnswer> {
39
+ const call = needing.held;
40
+ return askOnCard(ask.prompts, {
41
+ title: messages().confirmTitle(ask.asker),
42
+ message: approvalCardSized(call, sizeOf, {}, parameters),
43
+ signal: ask.signal,
44
+ minTier: higherTier(tiers?.minTier(call.tool), call.minTier),
45
+ wait: {
46
+ // A late answer on the card: the text of the turn that tells the model, and the release it earned.
47
+ late: (late) => {
48
+ const outcome = lateOutcome(call, late, watch, needing.onDeclined);
49
+ if (outcome?.release) releases.add(outcome.release);
50
+ return outcome?.text;
51
+ },
52
+ },
53
+ details: approvalDetailsSized(call, sizeOf, needing.copy),
54
+ approvers: call.approverIds,
55
+ speakerOnly: needing.speakerOnly === true,
56
+ watch,
57
+ });
58
+ }
59
+
60
+ /** Interpret the answer against the conversation as it is when the answer arrives. */
61
+ export function gateCardDecision(
62
+ { answer, approvedBy, approvedPrompt }: CardAnswer,
63
+ needing: Held,
64
+ watch: Watch | undefined,
65
+ turn: {
66
+ isPrivate: boolean;
67
+ speaker: SpeakerRef | undefined;
68
+ addressee: OwnerIdentity;
69
+ held(refused: "held" | "expired"): Promise<GateDecision>;
70
+ },
71
+ ): GateDecision | Promise<GateDecision> {
72
+ const call = needing.held;
73
+ // Whatever the card then reports, a call the plugin withdrew is refused, never held again.
74
+ if (answer === "withdrawn" || (watch?.withdrawn && answer !== "approved"))
75
+ return withdrawn(call);
76
+ if (answer === "approved") {
77
+ // A private conversation's answer to a call that names approvers is its person's, whom a surface need not name.
78
+ const by =
79
+ approvedBy ??
80
+ (turn.isPrivate && call.approverIds
81
+ ? approverOf(turn.speaker)
82
+ : undefined);
83
+ // A call that names approvers runs only on the word of one of them, or an owner.
84
+ if (!namedApprover(call, by)) return turn.held("held");
85
+ watch?.end();
86
+ return {
87
+ approvedOnCard: true,
88
+ ...(by ? { approvedBy: by } : {}),
89
+ ...(approvedPrompt ? { approvedPrompt } : {}),
90
+ };
91
+ }
92
+ if (answer === "pending")
93
+ return {
94
+ reason: awaitingText(turn.addressee, call),
95
+ refused: "pending",
96
+ };
97
+ if (answer === "declined")
98
+ return declinedRefusal(turn.addressee, call, watch, needing.onDeclined);
99
+ if (answer === "cancelled") {
100
+ watch?.end();
101
+ return { reason: "The turn was stopped." };
102
+ }
103
+ // No card was shown, or it went unanswered: the call is held for a message, and stays withdrawable.
104
+ return turn.held(answer === "unavailable" ? "held" : "expired");
105
+ }
@@ -7,6 +7,7 @@ import { type Autonomy, DEFAULT_AUTONOMY } from "../../modes/autonomy.ts";
7
7
  import type { ConversationModes } from "../../modes/conversation-modes.ts";
8
8
  import { YOLO_CARDED_SHELL_CLASSES } from "../../modules/host-shell/shell-policy.ts";
9
9
  import { YOLO_NEVER_CLASS } from "../../plugin-api/holds.ts";
10
+ import { shellClassOf } from "../../runner/runner-holds.ts";
10
11
  import type { PiAgentRuntimeOptions } from "../runtime-types.ts";
11
12
  import type { AutoApprover } from "./confirmation-gate.ts";
12
13
  import type { SpeakerRef } from "./gate-refusals.ts";
@@ -31,6 +32,12 @@ function ruleOf(id: string): string {
31
32
  return dot === -1 ? id : id.slice(0, dot);
32
33
  }
33
34
 
35
+ /** The ids a class is judged as: itself, and for a runner-shell class the shell class too. */
36
+ function judgedAs(id: string): string[] {
37
+ const shell = shellClassOf(id);
38
+ return shell === undefined ? [id] : [id, shell];
39
+ }
40
+
34
41
  /**
35
42
  * Whether an id is a rule's bare name, which a call carries when its rule reports no classes for
36
43
  * it: the call is unclassed. Rule names have no dot and every class id has one.
@@ -65,7 +72,9 @@ export function turnYolo(
65
72
  * - the call has classes (a call without them is unknown, so a person decides), and none of them
66
73
  * is carded: not `autonomy.yolo.card`, not one of its rules named there, not a class in
67
74
  * `YOLO_CARDED_SHELL_CLASSES` that `autonomy.yolo.allow` leaves out, and not a rule's bare name
68
- * (its call is unclassed) that `autonomy.yolo.allow` leaves out.
75
+ * (its call is unclassed) that `autonomy.yolo.allow` leaves out. A runner-shell class is also
76
+ * judged as the shell class it stands for, so `runner-shell.rm` is carded as `shell.rm` is, and
77
+ * the config's shell ids and rule name reach it.
69
78
  * It reports who approved as the speaker, marked `auto: "yolo"`, and tells the modes, which log it.
70
79
  */
71
80
  export function yoloApprover(seams: YoloSeams): AutoApprover {
@@ -76,10 +85,15 @@ export function yoloApprover(seams: YoloSeams): AutoApprover {
76
85
  const approves = (id: string) => {
77
86
  // A `yolo: "never"` rule's call, which no configuration lets through.
78
87
  if (id.endsWith(`.${YOLO_NEVER_CLASS}`)) return false;
79
- if (card.has(id) || card.has(ruleOf(id))) return false;
88
+ const ids = judgedAs(id);
89
+ if (ids.some((each) => card.has(each) || card.has(ruleOf(each))))
90
+ return false;
80
91
  // A rule that reports classes has opted in; one that reports none is approved only by name.
81
92
  if (unclassed(id)) return allow.has(id);
82
- return !carded.has(id) || allow.has(id);
93
+ return (
94
+ !ids.some((each) => carded.has(each)) ||
95
+ ids.some((each) => allow.has(each))
96
+ );
83
97
  };
84
98
  return (call: HeldCall, { speakerOnly }): ApprovedBy | undefined => {
85
99
  if (!modes.peek(channel).yolo) return undefined;
@@ -22,6 +22,8 @@ import type { TransientTask } from "../domain/sessions.ts";
22
22
  import { assistantName } from "../i18n/index.ts";
23
23
  import { promptScopeOf } from "../interactions/prompts.ts";
24
24
  import { HostStoppingError } from "../kernel/errors.ts";
25
+ import { removeRunnerWorkspace } from "../runner/runner-session.ts";
26
+ import { runnerTiers } from "../runner/runner-tiers.ts";
25
27
  import { withoutReplyFiles } from "../shared/reply-files.ts";
26
28
  import { AbortGuard } from "./abort-guard.ts";
27
29
  import { bridgeTurnRefusal, chosenAgentModel } from "./bridge-guard.ts";
@@ -29,13 +31,16 @@ import { ConversationSessions } from "./conversation-sessions.ts";
29
31
  import { confirmedTurnText } from "./extensions/confirmation-gate.ts";
30
32
  import { loadsMemory } from "./extensions/private-memory.ts";
31
33
  import { missingToolsError } from "./extensions/self-compact-guard.ts";
32
- import { turnYolo } from "./extensions/yolo.ts";
33
34
  import { interimPoster } from "./interim-text.ts";
34
35
  import { preflightTools } from "./preflight-tools.ts";
35
36
  import { PromptSlot } from "./prompt-slot.ts";
36
- import { carriesMemory, recordMemoryTurn } from "./reader-history.ts";
37
+ import { carriesMemory } from "./reader-history.ts";
37
38
  import { type RunningTurn, runningTurn } from "./running-turn.ts";
38
- import type { PiAgentRuntimeOptions, TurnMessage } from "./runtime-types.ts";
39
+ import type {
40
+ ChannelSession,
41
+ PiAgentRuntimeOptions,
42
+ TurnMessage,
43
+ } from "./runtime-types.ts";
39
44
  import { archiveSessions } from "./session-archive.ts";
40
45
  import {
41
46
  memoryReader,
@@ -51,7 +56,7 @@ import { transcriptOf, turnAnswer, unspokenTurn } from "./turn-answer.ts";
51
56
  import type { TurnBudget } from "./turn-budget.ts";
52
57
  import { promptFailed, turnLimits } from "./turn-limits.ts";
53
58
  import { progressReporter } from "./turn-progress.ts";
54
- import { turnTools } from "./turn-tools.ts";
59
+ import { selectTurn } from "./turn-selection.ts";
55
60
  import { wrapUpTurn } from "./turn-wrapup.ts";
56
61
  import { promptTask, workerReport } from "./worker-task.ts";
57
62
 
@@ -167,66 +172,23 @@ export class PiAgentRuntime implements AgentRuntime {
167
172
  agentModel,
168
173
  );
169
174
  if (session.thinkingLevel !== level) session.setThinkingLevel(level);
170
- const gate = await this.#sessions.gate(key, request.agent !== undefined);
171
- // What this turn's message may release: a held call that named approvers is theirs alone.
172
- const pending = request.confirmed
173
- ? gate.releasable(request.speaker)
174
- : gate.pending();
175
- const registered = new Set(session.getAllTools().map((tool) => tool.name));
176
- // The speaker's tier limits the tools.
177
- const { tier } = request.speaker;
178
- // An approving turn also has the held calls' tools, which a dispatched worker may have used.
179
- // The agent server may keep a speaker below the owner tier out of memory: no tools, no block.
180
- const withheld =
181
- request.agent !== undefined &&
182
- this.#options.agents?.memory === "owners" &&
183
- tier !== "owner";
184
- const wanted = turnTools(
185
- {
186
- selected: this.#factory.toolsFor(request.selection),
187
- held: request.confirmed && pending ? pending.calls : [],
188
- tier,
189
- withheld,
190
- },
191
- this.#tiers,
175
+ const gate = await this.#sessions.gate(
176
+ key,
177
+ request.agent !== undefined,
178
+ channelSession.runner,
192
179
  );
193
- const markPrivateMemory = recordMemoryTurn(
194
- session.sessionManager,
195
- request.speaker.principalId,
196
- !withheld &&
197
- channelSession.memory !== "none" &&
198
- memoryReader(conversation, request.speaker) !== undefined &&
199
- loadsMemory(registered),
180
+ const { pending, tier, withheld, markPrivateMemory, activate } = selectTurn(
181
+ request,
182
+ conversation,
183
+ channelSession,
184
+ gate,
185
+ this.#factory,
186
+ this.#tiersOf(channelSession),
187
+ this.#options,
200
188
  );
201
189
  this.#memoryTurns.set(key, markPrivateMemory);
202
190
  this.#turns.set(key, runningTurn(request, tier, withheld));
203
- const missing = wanted.filter((name) => !registered.has(name));
204
- if (missing.length > 0) {
205
- logger.warn(
206
- { channel: request.channel, selection: request.selection.id, missing },
207
- "selected tools missing; running without them",
208
- );
209
- }
210
- channelSession.tools = wanted.filter((name) => registered.has(name));
211
- session.setActiveToolsByName([...channelSession.tools]);
212
- gate.beginTurn(
213
- request.selection.id,
214
- request.confirmed === true,
215
- who,
216
- request.speaker,
217
- conversation.visibility === "private",
218
- turnYolo(this.#options, request),
219
- request.byMessage === true,
220
- );
221
- if (request.confirmed && pending && pending.calls.length > 0) {
222
- logger.info(
223
- {
224
- channel: request.channel,
225
- tools: pending.calls.map((call) => call.tool),
226
- },
227
- "confirmed actions released",
228
- );
229
- }
191
+ activate(who);
230
192
  // Collected as they end: a compaction during the turn shortens session.messages.
231
193
  const turnMessages: TurnMessage[] = [];
232
194
  const toolCalls: string[] = [];
@@ -394,19 +356,19 @@ export class PiAgentRuntime implements AgentRuntime {
394
356
  throw new AgentRunError(
395
357
  `a task runs beside a turn of its conversation, at that turn's tier, and ${scope.turn} has no turn running`,
396
358
  );
397
- // A worker inherits the starting turn's conversation and memory policy, without asking.
359
+ // A worker inherits the starting turn's conversation, memory policy and runner, without asking.
398
360
  const parent = await this.#sessions.session(scope.turn);
399
- const { conversation, memory } = parent;
361
+ const { conversation, memory, runner } = parent;
400
362
  const worker = await this.#factory.create(
401
363
  scope.home,
402
364
  SessionManager.inMemory(this.#factory.workDir()),
403
- await this.#sessions.gate(scope.home, false),
365
+ await this.#sessions.gate(scope.home, false, runner),
404
366
  new PromptSlot(),
405
367
  ownerAttachmentDir(dataDir, scope.home),
406
368
  undefined,
407
369
  "owner",
408
370
  conversation,
409
- { turn: scope.turn, memory },
371
+ { turn: scope.turn, memory, ...(runner ? { runner } : {}) },
410
372
  );
411
373
  const { session } = worker;
412
374
  const toolCalls: string[] = [];
@@ -428,11 +390,10 @@ export class PiAgentRuntime implements AgentRuntime {
428
390
  this.#memoryTurns.get(scope.turn)?.();
429
391
  }
430
392
  const { tier } = turn;
393
+ const tiers = this.#tiersOf(parent);
431
394
  worker.tools = this.#factory
432
- .taskTools(task.selection, task.exclude)
433
- .filter(
434
- (name) => registered.has(name) && this.#tiers.allows(tier, name),
435
- );
395
+ .taskTools(task.selection, task.exclude, runner !== undefined)
396
+ .filter((name) => registered.has(name) && tiers.allows(tier, name));
436
397
  session.setActiveToolsByName([...worker.tools]);
437
398
  const prompted = withoutReplyFiles(() => promptTask(session, task.text));
438
399
  prompted.catch(() => undefined);
@@ -464,9 +425,17 @@ export class PiAgentRuntime implements AgentRuntime {
464
425
  await this.#sessions.forget(channel);
465
426
  rmSync(this.#factory.sessionDir(channel), { recursive: true, force: true });
466
427
  await discardConversationFiles(this.#options.dataDir, channel);
428
+ await removeRunnerWorkspace(this.#options, channel);
467
429
  this.#options.logger.info({ channel }, "conversation deleted");
468
430
  }
469
431
 
432
+ /** The tiers of a session's tools: the runner's view for one the runner serves. */
433
+ #tiersOf(session: ChannelSession): ToolTiers {
434
+ return session.runner
435
+ ? runnerTiers(this.#tiers, session.runner.settings.minTier)
436
+ : this.#tiers;
437
+ }
438
+
470
439
  /** Undefined until the conversation has run a turn since startup. */
471
440
  // pi-lens-ignore: pass-through-wrappers — AgentRuntime's port method over the private usage map
472
441
  contextUsage(