pi-roundtable 0.22.0 → 0.22.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,18 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.22.2] - 2026-10-21
9
+
10
+ ### Fixed
11
+
12
+ - A skill linked while another was removed no longer vanishes from the registry (`pi-roundtable`). `skill_unlink` reloaded the whole skill cache from the database after its delete, so a `skill_link` running at the same time, as two tool calls of one model message do, could commit its row after the reload had read the table and then be dropped from memory: the skill was missing from `skill_list`, unknown to `agent_skills` and `skill_group_set`, and could be neither unlinked nor linked again until a restart. The skill store now updates its memory from what each write committed and runs its writes one at a time, and a link that meets an existing row says "Already registered" instead of PostgreSQL's duplicate-key error. The agent store's seeding no longer reloads its cache either, and its agent and group writes also run one at a time, so an agent archived while its group is updated cannot come back as a member.
13
+
14
+ ## [0.22.1] - 2026-10-21
15
+
16
+ ### Changed
17
+
18
+ - A turn that reaches its time limit asks before it ends (`pi-roundtable`). When the built-in runtime's 10-minute budget or 30-minute cap fires on a turn that can show the owner a card, the turn keeps working and a card names the limit, the work time, what the turn is doing (the running tool and for how long, waiting on the model, or compacting) and the tools so far, with **Continue** (another full budget from the answer; at the cap the cap moves too) and **Cancel**. No answer within 5 minutes aborts the turn; a turn that finishes first closes the card and replies as usual. A turn that cannot show a card is aborted as before. An aborted turn now fails with `TurnTimeoutError` (an `AgentRunError`, with the reason as `TurnTimeout`: its `TurnLimit`, work time, running tools, tools so far and `TurnTimeoutEnd`), its log warning carries the same fields, and the posted failure says why instead of the generic notice. `ApprovalOptions` gains `wording` (`ApprovalWording`: the buttons' labels and the footers) for a card that is not an approval; the Discord cards honour it. `PiAgentRuntimeOptions` gains `turnTimeoutCardMs`, the card's grace period; the runtime plugin still passes none of the limits, so they stay fixed. See [the turn limits](docs/plugins.md#what-happens-when-the-bot-starts-and-stops).
19
+
8
20
  ## [0.22.0] - 2026-10-21
9
21
 
10
22
  ### Added
package/docs/plugins.md CHANGED
@@ -3526,7 +3526,10 @@ On `SIGTERM` or `SIGINT` the bot takes no new work at once, finishes what runs,
3526
3526
  `shutdown()` returns exit code `0`, or `1` if a listener, service, or pool failed to stop.
3527
3527
  Every call shares the same shutdown.
3528
3528
  Give the service manager a stop timeout longer than the drain limit plus about a minute for the steps after it, such as systemd's `TimeoutStopSec=5min` with the default three-minute drain; a shorter one has the manager kill the process in the middle of the drain.
3529
- The built-in runtime aborts a turn that works 10 minutes, not counting time spent waiting on the owner's cards. Each message steered into the running turn gives it the full 10 minutes again from that moment, up to a cap of 30 minutes of work for the whole turn; once the cap is reached the turn takes no more steering, so a message waits for the next turn, and the turn is aborted as on its timeout. Both limits are fixed: the runtime plugin passes no option for them, so a host cannot change them, and a limit that waiting on an owner's card pushed back can fire up to a second late. The log says `steer renewed the turn's time budget` with `deadlineMs`, the work time left, and the timeout warning names the limit that fired (`limit: "turn"` or `"turnMax"`). Task workers (`task.timeoutMs`), coding workers (`workTimeout`) and sandbox guests (their own `turnTimeoutMs`) keep their own limits, which steering does not renew.
3529
+ The built-in runtime limits a turn to 10 minutes of work, not counting time spent waiting on the owner's cards. Each message steered into the running turn gives it the full 10 minutes again from that moment, up to a cap of 30 minutes of work for the whole turn; once the cap is reached the turn takes no more steering, so a message waits for the next turn.
3530
+ When a limit fires on a turn that can show a card (an owner's turn or a report turn on a surface with cards, the same turns that can ask with `ask_user` or an approval card), the turn is not aborted: it keeps working and a card asks the owner whether to go on. The card names the limit, how long the turn has worked, what it is doing now (the tool running and for how long, or waiting on the model, or compacting the conversation) and the tools it called so far, by name and count, never their inputs. **Continue** gives the turn another full 10 minutes from the answer; at the cap it moves the cap too, to 10 minutes from the answer, so the owner can keep going in steps. **Cancel** aborts the turn. With no answer within 5 minutes of wall time the turn is aborted. The time the card is open counts as work, unlike an `ask_user` or approval card, because the turn keeps working; while it is open the turn takes no steering. If the turn finishes first, the card closes saying so and the reply is posted as usual; a press after that gets the usual "no longer valid" reply. The card's buttons come from `ApprovalOptions.wording` on `Prompts.confirm`, with `supersede` closing it, so a surface that shows approvals shows it; one that ignores `wording` shows its own approve and decline labels.
3531
+ A turn that cannot show a card (a schedule's turn, a member's turn, a turn without a surface) is aborted at once, as before. Either way an aborted turn fails with a `TurnTimeoutError` (an `AgentRunError`) whose `timeout` (`TurnTimeout`) holds the limit, the work time, the running tools, whether it was compacting, the tools so far, and how it ended (`end`: `"timeout"`, `"cancelled"` by the owner, or `"unanswered"`); its message says the same in English, and the failure the conversation posts says it in the host's language instead of the generic failure notice.
3532
+ The limits are fixed: the runtime plugin passes no option for them, nor for the card's grace period (`turnTimeoutMs`, `turnMaxMs` and `turnTimeoutCardMs` of `PiAgentRuntimeOptions`, for a host that builds the runtime itself), and a limit that waiting on an owner's card pushed back can fire up to a second late. The log says `steer renewed the turn's time budget` with `deadlineMs`, the work time left; `turn reached its time limit; asking the owner` when the card is posted; `owner continued the turn past its time limit` on Continue; and the warning `turn timed out; aborting` names the limit that fired (`limit: "turn"` or `"turnMax"`) with `workedMs`, `running`, `compacting`, `tools` and `end`. Task workers (`task.timeoutMs`), coding workers (`workTimeout`) and sandbox guests (their own `turnTimeoutMs`) keep their own limits, which steering does not renew and which post no card.
3530
3533
  A turn whose model ignores its abort (a subprocess that does not exit) is given up on too: a turn that outlives its timeout, or is stopped, gets `turnAbortGraceMs` (15 seconds by default) to end, and then its session is disposed of and the turn is reported failed, so it cannot hold the queue.
3531
3534
  `listen()`, called by the command line and a host's own entry point, exits the process with that code.
3532
3535
 
@@ -3737,6 +3740,7 @@ Import from the entries listed below; source area files are internal.
3737
3740
  | `ApprovalDetails` | `pi-roundtable` | type |
3738
3741
  | `ApprovalFile` | `pi-roundtable` | type |
3739
3742
  | `ApprovalOptions` | `pi-roundtable` | type |
3743
+ | `ApprovalWording` | `pi-roundtable` | type |
3740
3744
  | `ApprovedBy` | `pi-roundtable` | type |
3741
3745
  | `AskOption` | `pi-roundtable` | type |
3742
3746
  | `AskSupport` | `pi-roundtable` | type |
@@ -3963,6 +3967,10 @@ Import from the entries listed below; source area files are internal.
3963
3967
  | `TurnRequest` | `pi-roundtable` | type |
3964
3968
  | `TurnResult` | `pi-roundtable` | type |
3965
3969
  | `TurnSelection` | `pi-roundtable` | type |
3970
+ | `TurnLimit` | `pi-roundtable` | type |
3971
+ | `TurnTimeout` | `pi-roundtable` | type |
3972
+ | `TurnTimeoutEnd` | `pi-roundtable` | type |
3973
+ | `TurnTimeoutError` | `pi-roundtable` | value |
3966
3974
  | `WebSocketAccept` | `pi-roundtable` | type |
3967
3975
  | `WebSocketRoute` | `pi-roundtable` | type |
3968
3976
  | `WebSocketSendResult` | `pi-roundtable` | type |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-roundtable",
3
- "version": "0.22.0",
3
+ "version": "0.22.2",
4
4
  "description": "A plugin-driven Pi agent server for one owner, reached through Discord or the web",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -58,6 +58,8 @@ export class PgAgentStore implements AgentDirectory {
58
58
  readonly #sql: SQL;
59
59
  readonly #agents = new Map<string, Agent>();
60
60
  readonly #groups = new Map<string, AgentGroup>();
61
+ /** The tail of the agent and group writes, which run one at a time so none reads a map another is about to change. */
62
+ #queue: Promise<unknown> = Promise.resolve();
61
63
 
62
64
  readonly #guild: string;
63
65
  readonly #messages: GroupMessages;
@@ -97,18 +99,27 @@ export class PgAgentStore implements AgentDirectory {
97
99
 
98
100
  /** Inserts seed agents that do not exist yet; existing rows, edited or not, are left alone. */
99
101
  async seed(seeds: readonly AgentSeed[]): Promise<string[]> {
100
- const added: string[] = [];
101
- for (const seed of seeds) {
102
- const rows: unknown[] = await this.#sql`
102
+ return this.#serial(async () => {
103
+ const added: string[] = [];
104
+ for (const seed of seeds) {
105
+ const rows: AgentRow[] = await this.#sql`
103
106
  INSERT INTO agents (guild_id, name, display_name, prompt, avatar_prompt, channel_id)
104
107
  VALUES (${this.#guild}, ${seed.name}, ${seed.displayName}, ${seed.prompt}, ${seed.avatarPrompt},
105
108
  ${seed.channelId ?? null})
106
109
  ON CONFLICT DO NOTHING
107
- RETURNING name`;
108
- if (rows.length > 0) added.push(seed.name);
109
- }
110
- await this.#reload();
111
- return added;
110
+ RETURNING *`;
111
+ // Only the inserted rows join the map: reloading it whole would drop a write that
112
+ // committed after its SELECT.
113
+ if (rows[0]) added.push(this.#keepAgent(rows[0]).name);
114
+ }
115
+ return added;
116
+ });
117
+ }
118
+
119
+ #serial<T>(write: () => Promise<T>): Promise<T> {
120
+ const run = this.#queue.then(write);
121
+ this.#queue = run.catch(() => undefined);
122
+ return run;
112
123
  }
113
124
 
114
125
  agents(): Agent[] {
@@ -178,18 +189,20 @@ export class PgAgentStore implements AgentDirectory {
178
189
  avatarPrompt: string;
179
190
  channelId: string;
180
191
  }): Promise<Agent> {
181
- checkAgentName(agent.name);
182
- checkDisplayName(agent.displayName);
183
- checkPrompt(agent.prompt);
184
- // An agent of a host without an image provider has no avatar prompt.
185
- if (agent.avatarPrompt !== "") checkAvatarPrompt(agent.avatarPrompt);
186
- this.#checkFree(agent.name);
187
- const rows: AgentRow[] = await this.#sql`
192
+ return this.#serial(async () => {
193
+ checkAgentName(agent.name);
194
+ checkDisplayName(agent.displayName);
195
+ checkPrompt(agent.prompt);
196
+ // An agent of a host without an image provider has no avatar prompt.
197
+ if (agent.avatarPrompt !== "") checkAvatarPrompt(agent.avatarPrompt);
198
+ this.#checkFree(agent.name);
199
+ const rows: AgentRow[] = await this.#sql`
188
200
  INSERT INTO agents (guild_id, name, display_name, prompt, avatar_prompt, channel_id)
189
201
  VALUES (${this.#guild}, ${agent.name}, ${agent.displayName.trim()}, ${agent.prompt}, ${agent.avatarPrompt},
190
202
  ${agent.channelId})
191
203
  RETURNING *`;
192
- return this.#keepAgent(rows[0]);
204
+ return this.#keepAgent(rows[0]);
205
+ });
193
206
  }
194
207
 
195
208
  /** A name that createAgent would accept, checked before its channel is made. */
@@ -211,20 +224,22 @@ export class PgAgentStore implements AgentDirectory {
211
224
  thinking?: ThinkingLevel | null;
212
225
  },
213
226
  ): Promise<Agent> {
214
- const current = this.activeAgent(name);
215
- if (change.displayName !== undefined) checkDisplayName(change.displayName);
216
- if (change.prompt !== undefined) checkPrompt(change.prompt);
217
- if (change.avatarPrompt !== undefined)
218
- checkAvatarPrompt(change.avatarPrompt);
219
- if (change.model) checkModelRef(change.model);
220
- if (change.thinking) checkThinking(change.thinking);
221
- const model =
222
- change.model === undefined ? (current.model ?? null) : change.model;
223
- const thinking =
224
- change.thinking === undefined
225
- ? (current.thinking ?? null)
226
- : change.thinking;
227
- const rows: AgentRow[] = await this.#sql`
227
+ return this.#serial(async () => {
228
+ const current = this.activeAgent(name);
229
+ if (change.displayName !== undefined)
230
+ checkDisplayName(change.displayName);
231
+ if (change.prompt !== undefined) checkPrompt(change.prompt);
232
+ if (change.avatarPrompt !== undefined)
233
+ checkAvatarPrompt(change.avatarPrompt);
234
+ if (change.model) checkModelRef(change.model);
235
+ if (change.thinking) checkThinking(change.thinking);
236
+ const model =
237
+ change.model === undefined ? (current.model ?? null) : change.model;
238
+ const thinking =
239
+ change.thinking === undefined
240
+ ? (current.thinking ?? null)
241
+ : change.thinking;
242
+ const rows: AgentRow[] = await this.#sql`
228
243
  UPDATE agents SET
229
244
  display_name = ${change.displayName?.trim() ?? current.displayName},
230
245
  prompt = ${change.prompt ?? current.prompt},
@@ -236,29 +251,33 @@ export class PgAgentStore implements AgentDirectory {
236
251
  updated_at = now()
237
252
  WHERE guild_id = ${this.#guild} AND name = ${name}
238
253
  RETURNING *`;
239
- return this.#keepAgent(rows[0]);
254
+ return this.#keepAgent(rows[0]);
255
+ });
240
256
  }
241
257
 
242
258
  /** Archives an agent and takes it out of every group; says which groups it left. */
243
259
  async archiveAgent(name: string): Promise<AgentGroup[]> {
244
- const rows: AgentRow[] = await this.#sql`
260
+ return this.#serial(async () => {
261
+ const rows: AgentRow[] = await this.#sql`
245
262
  UPDATE agents SET status = 'archived', updated_at = now()
246
263
  WHERE guild_id = ${this.#guild} AND name = ${name} RETURNING *`;
247
- this.#keepAgent(rows[0]);
248
- const left: AgentGroup[] = [];
249
- for (const group of this.groups()) {
250
- if (group.status !== "active" || !group.members.includes(name)) continue;
251
- const members = group.members.filter((m) => m !== name);
252
- const host = group.host === name ? (members[0] ?? name) : group.host;
253
- left.push(
254
- await this.#writeGroup(group.name, {
255
- members,
256
- host,
257
- status: members.length < MIN_GROUP_MEMBERS ? "archived" : "active",
258
- }),
259
- );
260
- }
261
- return left;
264
+ this.#keepAgent(rows[0]);
265
+ const left: AgentGroup[] = [];
266
+ for (const group of this.groups()) {
267
+ if (group.status !== "active" || !group.members.includes(name))
268
+ continue;
269
+ const members = group.members.filter((m) => m !== name);
270
+ const host = group.host === name ? (members[0] ?? name) : group.host;
271
+ left.push(
272
+ await this.#writeGroup(group.name, {
273
+ members,
274
+ host,
275
+ status: members.length < MIN_GROUP_MEMBERS ? "archived" : "active",
276
+ }),
277
+ );
278
+ }
279
+ return left;
280
+ });
262
281
  }
263
282
 
264
283
  #keepAgent(row: AgentRow | undefined): Agent {
@@ -296,39 +315,44 @@ export class PgAgentStore implements AgentDirectory {
296
315
  members: string[];
297
316
  host: string;
298
317
  }): Promise<AgentGroup> {
299
- this.checkNewGroup(group.name, group.members, group.host);
300
- checkDisplayName(group.displayName);
301
- const rows: GroupRow[] = await this.#sql`
318
+ return this.#serial(async () => {
319
+ this.checkNewGroup(group.name, group.members, group.host);
320
+ checkDisplayName(group.displayName);
321
+ const rows: GroupRow[] = await this.#sql`
302
322
  INSERT INTO agent_groups (guild_id, name, display_name, channel_id, members, host)
303
323
  VALUES (${this.#guild}, ${group.name}, ${group.displayName.trim()}, ${group.channelId},
304
324
  ${group.members.join(",")}, ${group.host})
305
325
  RETURNING *`;
306
- return this.#keepGroup(rows[0]);
326
+ return this.#keepGroup(rows[0]);
327
+ });
307
328
  }
308
329
 
309
330
  async updateGroup(
310
331
  name: string,
311
332
  change: { displayName?: string; members?: string[]; host?: string },
312
333
  ): Promise<AgentGroup> {
313
- const current = this.#groups.get(name);
314
- if (current?.status !== "active")
315
- throw new AgentError(`There is no active group "${name}".`);
316
- if (change.displayName !== undefined) checkDisplayName(change.displayName);
317
- const members = change.members ?? current.members;
318
- const host =
319
- change.host ??
320
- (members.includes(current.host) ? current.host : (members[0] ?? ""));
321
- this.#checkMembers(members, host);
322
- return this.#writeGroup(name, {
323
- displayName: change.displayName?.trim() ?? current.displayName,
324
- members,
325
- host,
326
- status: "active",
334
+ return this.#serial(async () => {
335
+ const current = this.#groups.get(name);
336
+ if (current?.status !== "active")
337
+ throw new AgentError(`There is no active group "${name}".`);
338
+ if (change.displayName !== undefined)
339
+ checkDisplayName(change.displayName);
340
+ const members = change.members ?? current.members;
341
+ const host =
342
+ change.host ??
343
+ (members.includes(current.host) ? current.host : (members[0] ?? ""));
344
+ this.#checkMembers(members, host);
345
+ return this.#writeGroup(name, {
346
+ displayName: change.displayName?.trim() ?? current.displayName,
347
+ members,
348
+ host,
349
+ status: "active",
350
+ });
327
351
  });
328
352
  }
329
353
 
330
354
  async archiveGroup(name: string): Promise<AgentGroup> {
331
- return this.#writeGroup(name, { status: "archived" });
355
+ return this.#serial(() => this.#writeGroup(name, { status: "archived" }));
332
356
  }
333
357
 
334
358
  async #writeGroup(
@@ -8,7 +8,7 @@ import type {
8
8
  import { AgentError } from "../domain/errors.ts";
9
9
  import type { InterimPosts } from "../domain/interim.ts";
10
10
  import type { AgentTurnScope } from "../domain/ports.ts";
11
- import { messages } from "../i18n/index.ts";
11
+ import { failureNotice } from "../presentation/failure-notice.ts";
12
12
  import { splitReply } from "../presentation/reply-splitter.ts";
13
13
  import { thinkingLine } from "../presentation/thinking-line.ts";
14
14
  import { withReplyFiles } from "../reply-files.ts";
@@ -35,11 +35,6 @@ import {
35
35
 
36
36
  export { MAX_CHAIN_MESSAGES, type TeamTurnsOptions };
37
37
 
38
- /** What a failed turn posts: the stopped notice for a stop, the failure notice otherwise. */
39
- function noticeOf(result: { stopped?: true }): string {
40
- return result.stopped ? messages().stoppedNotice : messages().failureNotice;
41
- }
42
-
43
38
  /**
44
39
  * The agent team's turns: owner messages, background turns, group rounds, and messages between
45
40
  * agents, each posted under the answering agent's name.
@@ -246,7 +241,7 @@ export class TeamTurns {
246
241
  : undefined;
247
242
  await this.#post(postTo, this.#current(agent), {
248
243
  ...(thinking ? { thinking } : {}),
249
- chunks: result.ok ? splitReply(result.text) : [noticeOf(result)],
244
+ chunks: result.ok ? splitReply(result.text) : [failureNotice(result)],
250
245
  ...(result.ok && result.files?.length ? { files: result.files } : {}),
251
246
  });
252
247
  } catch (error) {
@@ -123,23 +123,27 @@ export function answeredLine(answer: OwnerAnswer): string {
123
123
  return messages().cardAnswered(parts);
124
124
  }
125
125
 
126
- /** An approval's controls: run, cancel, and, when the card offers a copy, a copy button that stays usable once it ended. */
126
+ /**
127
+ * An approval's controls: run, cancel, or the labels its wording gives, and, when the card offers
128
+ * a copy, a copy button that stays usable once it ended.
129
+ */
127
130
  export function approvalRows(
128
131
  id: string,
129
132
  disabled: boolean,
130
133
  copy: { label: string } | undefined,
134
+ labels?: { approve: string; decline: string },
131
135
  ): Rows {
132
136
  return [
133
137
  new ActionRowBuilder<ButtonBuilder>().addComponents(
134
138
  new ButtonBuilder()
135
139
  .setCustomId(`${CARD_PREFIX}${id}:yes`)
136
- .setLabel(messages().cardRunLabel)
140
+ .setLabel(labels?.approve ?? messages().cardRunLabel)
137
141
  .setEmoji("✅")
138
142
  .setStyle(ButtonStyle.Success)
139
143
  .setDisabled(disabled),
140
144
  new ButtonBuilder()
141
145
  .setCustomId(`${CARD_PREFIX}${id}:no`)
142
- .setLabel(messages().cardCancelLabel)
146
+ .setLabel(labels?.decline ?? messages().cardCancelLabel)
143
147
  .setEmoji("❌")
144
148
  .setStyle(ButtonStyle.Secondary)
145
149
  .setDisabled(disabled),
@@ -83,6 +83,8 @@ export interface OpenCard {
83
83
  mention?: boolean;
84
84
  /** Who may answer, and what to tell someone else who presses it. */
85
85
  audience: Audience;
86
+ /** An approval card's footers once approved or declined, where its wording gives them. */
87
+ outcomes?: { approved: string; declined: string };
86
88
  }
87
89
 
88
90
  /** What `#post` needs to post one card; `T` is what the card resolves with. */
@@ -101,6 +103,8 @@ export interface CardSpec<T> {
101
103
  build?(id: string, footer: string, disabled: boolean): CardPayload;
102
104
  rows?(id: string, disabled: boolean): Rows;
103
105
  footer: string;
106
+ /** An approval card's footers once approved or declined, where its wording gives them. */
107
+ outcomes?: { approved: string; declined: string };
104
108
  wait?: {
105
109
  pending: T;
106
110
  late(
@@ -175,8 +175,10 @@ export class OwnerCards implements InteractionModule {
175
175
  sections: [message],
176
176
  ...(options?.supersede ? { supersede: options.supersede } : {}),
177
177
  ...(copy ? { copy: copy.text } : {}),
178
- rows: (id, disabled) => approvalRows(id, disabled, copy),
179
- footer: messages().cardApprovalFooter,
178
+ rows: (id, disabled) =>
179
+ approvalRows(id, disabled, copy, options?.wording),
180
+ footer: options?.wording?.footer ?? messages().cardApprovalFooter,
181
+ ...(options?.wording ? { outcomes: options.wording } : {}),
180
182
  },
181
183
  );
182
184
  },
@@ -296,6 +298,7 @@ export class OwnerCards implements InteractionModule {
296
298
  ...(card.question ? { question: card.question } : {}),
297
299
  ...(card.form ? { form: card.form } : {}),
298
300
  ...(card.previews ? { previews: card.previews } : {}),
301
+ ...(card.outcomes ? { outcomes: card.outcomes } : {}),
299
302
  };
300
303
  this.#open.set(id, open);
301
304
  this.#options
@@ -417,7 +420,11 @@ export class OwnerCards implements InteractionModule {
417
420
  return true;
418
421
  }
419
422
  await interaction.update(
420
- card.view(approved ? messages().cardApproved : messages().cardDeclined),
423
+ card.view(
424
+ approved
425
+ ? (card.outcomes?.approved ?? messages().cardApproved)
426
+ : (card.outcomes?.declined ?? messages().cardDeclined),
427
+ ),
421
428
  );
422
429
  return true;
423
430
  }
@@ -0,0 +1,38 @@
1
+ import { AgentRunError } from "./errors.ts";
2
+
3
+ /** Which limit a turn reached: its budget since the start or the last steer, or its cap. */
4
+ export type TurnLimit = "turn" | "turnMax";
5
+
6
+ /**
7
+ * How a timed-out turn ended: at its limit with no card to ask on (`timeout`), cancelled on the
8
+ * timeout card (`cancelled`), or with the card unanswered in its grace period (`unanswered`).
9
+ */
10
+ export type TurnTimeoutEnd = "timeout" | "cancelled" | "unanswered";
11
+
12
+ /** Why a turn hit a time limit, as data: which limit, how long it worked, and what it was doing. */
13
+ export interface TurnTimeout {
14
+ limit: TurnLimit;
15
+ /** The limit's length: the budget, or the cap as the owner's Continues raised it. */
16
+ limitMs: number;
17
+ /** The turn's work so far, not counting time spent waiting on the owner's other cards. */
18
+ workedMs: number;
19
+ /** The tools running, the longest-running first, each with how long it has run. */
20
+ running: { tool: string; ms: number }[];
21
+ compacting: boolean;
22
+ /** Every tool called so far, by name, with how often. */
23
+ tools: [string, number][];
24
+ /** How long the timeout card waits for an answer. */
25
+ graceMs: number;
26
+ end: TurnTimeoutEnd;
27
+ }
28
+
29
+ /** A turn aborted at a time limit; `timeout` says why, and the message says it in English. */
30
+ export class TurnTimeoutError extends AgentRunError {
31
+ override name = "TurnTimeoutError";
32
+ constructor(
33
+ readonly timeout: TurnTimeout,
34
+ message: string,
35
+ ) {
36
+ super(message);
37
+ }
38
+ }
@@ -7,6 +7,7 @@ import { discordEn } from "./discord.ts";
7
7
  import { ownerEn } from "./owner.ts";
8
8
  import { schedulesEn } from "./schedules.ts";
9
9
  import { timeZonesEn } from "./time-zones.ts";
10
+ import { turnTimeoutEn } from "./turn-timeout.ts";
10
11
  import type { CatalogContext } from "./types.ts";
11
12
 
12
13
  export type Messages = ReturnType<typeof createEn>;
@@ -23,5 +24,6 @@ export function createEn(ctx: CatalogContext) {
23
24
  ...dashboardEn(ctx),
24
25
  ...channelsEn(ctx),
25
26
  ...discordEn(ctx),
27
+ ...turnTimeoutEn(),
26
28
  };
27
29
  }
@@ -0,0 +1,131 @@
1
+ import type { TurnTimeout } from "../domain/turn-timeout.ts";
2
+
3
+ /** A duration in whole seconds, as "3 min 12 s", "45 s", or "1 h 5 min". */
4
+ function durationEn(ms: number): string {
5
+ const s = Math.max(0, Math.round(ms / 1000));
6
+ const h = Math.floor(s / 3600);
7
+ const m = Math.floor((s % 3600) / 60);
8
+ const sec = s % 60;
9
+ if (h > 0) return m > 0 ? `${h} h ${m} min` : `${h} h`;
10
+ if (m > 0) return sec > 0 ? `${m} min ${sec} s` : `${m} min`;
11
+ return `${sec} s`;
12
+ }
13
+
14
+ function durationZh(ms: number): string {
15
+ const s = Math.max(0, Math.round(ms / 1000));
16
+ const h = Math.floor(s / 3600);
17
+ const m = Math.floor((s % 3600) / 60);
18
+ const sec = s % 60;
19
+ if (h > 0) return m > 0 ? `${h} 小時 ${m} 分` : `${h} 小時`;
20
+ if (m > 0) return sec > 0 ? `${m} 分 ${sec} 秒` : `${m} 分`;
21
+ return `${sec} 秒`;
22
+ }
23
+
24
+ /** The tools called so far, as the interim tool line shows them. */
25
+ function toolList(tools: TurnTimeout["tools"], separator: string): string {
26
+ return tools
27
+ .map(([name, count]) => (count > 1 ? `${name} ×${count}` : name))
28
+ .join(separator);
29
+ }
30
+
31
+ /** The timeout card and the notice a turn posts when it ends at a time limit. */
32
+ export function turnTimeoutEn() {
33
+ const doing = (t: TurnTimeout) =>
34
+ t.running.length > 0
35
+ ? t.running
36
+ .map(({ tool, ms }) => `${tool}, running for ${durationEn(ms)}`)
37
+ .join("; ")
38
+ : t.compacting
39
+ ? "compacting the conversation"
40
+ : "waiting on the model";
41
+ const limit = (t: TurnTimeout) =>
42
+ t.limit === "turn"
43
+ ? `its time limit of ${durationEn(t.limitMs)} (since it started or since the last message steered into it)`
44
+ : `its cap of ${durationEn(t.limitMs)} of work in all`;
45
+ const tools = (t: TurnTimeout) =>
46
+ t.tools.length > 0 ? `Tools so far: ${toolList(t.tools, " · ")}.` : "";
47
+ return {
48
+ turnTimeoutTitle: "⏱️ This turn is taking long",
49
+ turnTimeoutQuestion: (t: TurnTimeout, budgetMs: number) =>
50
+ [
51
+ `It reached ${limit(t)} and has worked ${durationEn(t.workedMs)}.`,
52
+ `Now: ${doing(t)}.`,
53
+ tools(t),
54
+ `It keeps working while this card is open. Continue gives it another ${durationEn(budgetMs)}; Cancel stops it. With no answer in ${durationEn(t.graceMs)} it stops.`,
55
+ ]
56
+ .filter(Boolean)
57
+ .join("\n"),
58
+ turnTimeoutContinue: "Continue",
59
+ turnTimeoutCancel: "Cancel",
60
+ turnTimeoutFooter:
61
+ "The turn is still working; answer whenever you are ready.",
62
+ turnTimeoutContinued: "▶️ Continued.",
63
+ turnTimeoutCancelled: "❌ Cancelled; the turn stops.",
64
+ turnTimeoutFinished: "✅ The turn finished; nothing to answer.",
65
+ turnTimeoutUnanswered: (t: TurnTimeout) =>
66
+ `⏱️ No answer in ${durationEn(t.graceMs)}; the turn was stopped.`,
67
+ turnTimedOutNotice: (t: TurnTimeout) => {
68
+ const what =
69
+ t.running.length > 0
70
+ ? `while ${t.running.map(({ tool, ms }) => `${tool} was running (${durationEn(ms)})`).join(" and ")}`
71
+ : `while ${doing(t)}`;
72
+ const head =
73
+ t.end === "cancelled"
74
+ ? `⏱️ Cancelled by the owner after ${durationEn(t.workedMs)} ${what}.`
75
+ : t.end === "unanswered"
76
+ ? `⏱️ No answer to the timeout card in ${durationEn(t.graceMs)}, so the turn was stopped after ${durationEn(t.workedMs)} ${what}.`
77
+ : `⏱️ The turn reached ${limit(t)} and was stopped after ${durationEn(t.workedMs)} ${what}.`;
78
+ return [head, tools(t)].filter(Boolean).join(" ");
79
+ },
80
+ };
81
+ }
82
+
83
+ export function turnTimeoutZhTW(): ReturnType<typeof turnTimeoutEn> {
84
+ const doing = (t: TurnTimeout) =>
85
+ t.running.length > 0
86
+ ? t.running
87
+ .map(({ tool, ms }) => `${tool},已執行 ${durationZh(ms)}`)
88
+ .join(";")
89
+ : t.compacting
90
+ ? "正在壓縮對話"
91
+ : "正在等模型回應";
92
+ const limit = (t: TurnTimeout) =>
93
+ t.limit === "turn"
94
+ ? `時間上限 ${durationZh(t.limitMs)}(從開始或最後一則插入的訊息算起)`
95
+ : `總工作時間上限 ${durationZh(t.limitMs)}`;
96
+ const tools = (t: TurnTimeout) =>
97
+ t.tools.length > 0 ? `目前用過的工具:${toolList(t.tools, " · ")}。` : "";
98
+ return {
99
+ turnTimeoutTitle: "⏱️ 這一輪做得比較久",
100
+ turnTimeoutQuestion: (t: TurnTimeout, budgetMs: number) =>
101
+ [
102
+ `已達到${limit(t)},已工作 ${durationZh(t.workedMs)}。`,
103
+ `現在:${doing(t)}。`,
104
+ tools(t),
105
+ `這張卡片開著時它會繼續工作。按「繼續」再給它 ${durationZh(budgetMs)};按「取消」停止。${durationZh(t.graceMs)}內沒有回答就會停止。`,
106
+ ]
107
+ .filter(Boolean)
108
+ .join("\n"),
109
+ turnTimeoutContinue: "繼續",
110
+ turnTimeoutCancel: "取消",
111
+ turnTimeoutFooter: "這一輪仍在工作;準備好再回答即可。",
112
+ turnTimeoutContinued: "▶️ 已繼續。",
113
+ turnTimeoutCancelled: "❌ 已取消,這一輪會停止。",
114
+ turnTimeoutFinished: "✅ 這一輪已完成,不需要回答。",
115
+ turnTimeoutUnanswered: (t: TurnTimeout) =>
116
+ `⏱️ ${durationZh(t.graceMs)}內沒有回答,這一輪已停止。`,
117
+ turnTimedOutNotice: (t: TurnTimeout) => {
118
+ const what =
119
+ t.running.length > 0
120
+ ? `當時 ${t.running.map(({ tool, ms }) => `${tool} 正在執行(${durationZh(ms)})`).join("、")}`
121
+ : `當時${doing(t)}`;
122
+ const head =
123
+ t.end === "cancelled"
124
+ ? `⏱️ 擁有者在工作 ${durationZh(t.workedMs)} 後取消了這一輪,${what}。`
125
+ : t.end === "unanswered"
126
+ ? `⏱️ 逾時卡片在 ${durationZh(t.graceMs)}內沒有回答,這一輪在工作 ${durationZh(t.workedMs)} 後停止,${what}。`
127
+ : `⏱️ 這一輪達到${limit(t)},在工作 ${durationZh(t.workedMs)} 後停止,${what}。`;
128
+ return [head, tools(t)].filter(Boolean).join(" ");
129
+ },
130
+ };
131
+ }
@@ -8,6 +8,7 @@ import type { Messages } from "./en.ts";
8
8
  import { ownerZhTW } from "./owner.ts";
9
9
  import { schedulesZhTW } from "./schedules.ts";
10
10
  import { timeZonesZhTW } from "./time-zones.ts";
11
+ import { turnTimeoutZhTW } from "./turn-timeout.ts";
11
12
  import type { CatalogContext } from "./types.ts";
12
13
 
13
14
  /** The Traditional Chinese catalog. */
@@ -22,5 +23,6 @@ export function createZhTW(ctx: CatalogContext): Messages {
22
23
  ...dashboardZhTW(ctx),
23
24
  ...channelsZhTW(ctx),
24
25
  ...discordZhTW(ctx),
26
+ ...turnTimeoutZhTW(),
25
27
  };
26
28
  }
@@ -128,6 +128,23 @@ export interface ApprovalOptions {
128
128
  * withdrawn call whatever the card answers.
129
129
  */
130
130
  supersede?: AbortSignal;
131
+ /**
132
+ * The card's own words, for a card that asks something other than whether to run an action,
133
+ * such as a turn's timeout card; a surface that cannot show them keeps its own.
134
+ */
135
+ wording?: ApprovalWording;
136
+ }
137
+
138
+ /** A card's words in place of an approval's; see `ApprovalOptions.wording`. */
139
+ export interface ApprovalWording {
140
+ /** The labels of the controls that answer approved and declined. */
141
+ approve: string;
142
+ decline: string;
143
+ /** The footer while the card is open. */
144
+ footer: string;
145
+ /** The footer once it was answered approved, or declined. */
146
+ approved: string;
147
+ declined: string;
131
148
  }
132
149
 
133
150
  /** The longest footer a withdrawn card shows, in characters. */