pi-roundtable 0.35.0 → 0.37.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,27 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.37.0] - 2026-11-06
9
+
10
+ ### Added
11
+
12
+ - `AgentTeam.allPresets()` lists every preset of every active knight that is no temp knight, by knight and then name, each with `sharedWith` and `recruits`: the knights that made temp knights from it, each with how many are active and archived and when the latest was made (`last`). `PresetOverview` and `PresetRecruits` are exported.
13
+ - `AgentTeam.transferPreset(agent, name, to)` gives a preset to another active knight, keeping its content and sharing. The new owner leaves the shared list. The old owner joins it when the preset was shared with none or with a list, so the old owner can still recruit from it; the owner removes it from the list to take that away. A preset shared with every knight stays so. The transfer refuses the same knight, a name the new owner already has, a new owner at 20 presets, and an unknown preset. Temp knights made from the preset before keep the name they recorded, so `allPresets` does not count them among the moved preset's recruits.
14
+
15
+ ## [0.36.0] - 2026-11-06
16
+
17
+ ### Added
18
+
19
+ - An owner manages a knight's temp-knight presets outside any agent turn: `AgentTeam.presets(agent)`, `savePreset(agent, preset)` (returns the preset as saved and whether it replaced one) and `deletePreset(agent, name)`. A save runs `helper_preset_set`'s checks at the owner's tier and keeps the cap of 20. All three refuse when temp knights are off, for an unknown or archived agent, and for a temp knight. `HelperTeam.helpersOn()` tells whether the host makes temp knights at all. `HelperPreset` and `MAX_HELPER_PRESETS` are exported.
20
+ - A temp knight made from a preset keeps its name: `Agent.preset`, stored in a new `preset` column of `agents` that the migration `agents-helper-preset` adds.
21
+ - A knight's preset can be shared with other knights, so a preset and the knights recruiting from it are many to many. The owner sets the sharing with `AgentTeam.savePreset(agent, preset, sharedWith)`: `"all"`, a list of knights, or `null` for none; left out, a replaced preset keeps its sharing, which an agent's `helper_preset_set` never changes. The new migration `helper-presets-shared` adds `helper_presets.shared_with`. `AgentTeam.presets(agent)` returns each preset's `sharedWith`, and `AgentTeam.usablePresets(agent)` lists what a knight may recruit from: its own, then those other active knights share with it. `OwnedPreset`, `UsablePreset` and `PresetSharing` are exported.
22
+ - `helper_preset_list` lists a knight's own presets, then those shared with it as `<agent>/<name>`; `helper_create` with `preset` takes its own name, `<agent>/<name>`, or a bare name one shared preset alone has, its own winning, and refuses a bare name several share. A shared preset is checked at the caller's tier against the caller's skills, so sharing never widens what a knight may grant, and only its saving agent or an owner changes or deletes it. A temp knight recruited from a shared preset records the qualified name.
23
+
24
+ ### Changed
25
+
26
+ - `helper_preset_set` and `AgentTeam.savePreset` go through one check, so the tool and the owner's save refuse the same presets.
27
+ - The prompt names no presets: it tells a knight to check `helper_preset_list` for a preset to recruit from before making a temp knight, and to write a new one only when none fits. `helper_create` says the same, and the preset tools speak of recruiting a temp knight from a preset.
28
+
8
29
  ## [0.35.0] - 2026-11-06
9
30
 
10
31
  ### Added
package/docs/plugins.md CHANGED
@@ -4533,6 +4533,12 @@ Import from the entries listed below; source area files are internal.
4533
4533
  | `GroupStatus` | `pi-roundtable` | type |
4534
4534
  | `HeldActionStore` | `pi-roundtable` | type |
4535
4535
  | `HeldCall` | `pi-roundtable` | type |
4536
+ | `HelperPreset` | `pi-roundtable` | type |
4537
+ | `OwnedPreset` | `pi-roundtable` | type |
4538
+ | `PresetOverview` | `pi-roundtable` | type |
4539
+ | `PresetRecruits` | `pi-roundtable` | type |
4540
+ | `PresetSharing` | `pi-roundtable` | type |
4541
+ | `UsablePreset` | `pi-roundtable` | type |
4536
4542
  | `HelperTeam` | `pi-roundtable` | type |
4537
4543
  | `HelpersConfig` | `pi-roundtable` | type |
4538
4544
  | `HelpersEnded` | `pi-roundtable` | type |
@@ -4577,6 +4583,7 @@ Import from the entries listed below; source area files are internal.
4577
4583
  | `LOCAL_TEAM_ID` | `pi-roundtable` | value |
4578
4584
  | `MEMORY` | `pi-roundtable` | value |
4579
4585
  | `MAX_ATTACHMENT_BYTES` | `pi-roundtable` | value |
4586
+ | `MAX_HELPER_PRESETS` | `pi-roundtable` | value |
4580
4587
  | `MODES` | `pi-roundtable` | value |
4581
4588
  | `MEMORY_KINDS` | `pi-roundtable` | value |
4582
4589
  | `MemberJoinedEvent` | `pi-roundtable` | type |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-roundtable",
3
- "version": "0.35.0",
3
+ "version": "0.37.0",
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,7 +58,7 @@ export function agentSystemPrompt(input: {
58
58
  );
59
59
  else if (input.helpers)
60
60
  parts.push(
61
- "A task that stands on its own, such as one of several things to look up or compare, can go to a temp knight: helper_create makes one of yours that works in parallel, its answer comes back to you as a new turn, and helper_end clears the ones you are done with. A temp knight you make often can be saved as a preset (helper_preset_set), then made with helper_create and preset.",
61
+ "A task that stands on its own, such as one of several things to look up or compare, can go to a temp knight: helper_create makes one of yours that works in parallel, its answer comes back to you as a new turn, and helper_end clears the ones you are done with. Before making a temp knight, check helper_preset_list for a preset to recruit it from and recruit with helper_create and preset when one fits; write a new one only otherwise.",
62
62
  );
63
63
  if (group) {
64
64
  const others = group.members
@@ -36,6 +36,8 @@ export interface Agent {
36
36
  finishedAt?: Date;
37
37
  /** The conversation (channel key) a temp knight was made from; only it and the owners may message the temp knight. */
38
38
  origin?: string;
39
+ /** The preset a temp knight was made from, by name; absent when it was made without one. */
40
+ preset?: string;
39
41
  }
40
42
 
41
43
  /** Whether the agent is a temp knight: one a knight made to do a task, which has a parent. */
@@ -23,6 +23,7 @@ export interface AgentRow {
23
23
  parent: string | null;
24
24
  finished_at: Date | null;
25
25
  origin: string | null;
26
+ preset: string | null;
26
27
  }
27
28
 
28
29
  export interface GroupRow {
@@ -50,6 +51,7 @@ export const toAgent = (row: AgentRow): Agent => {
50
51
  ...(row.parent ? { parent: row.parent } : {}),
51
52
  ...(row.finished_at ? { finishedAt: row.finished_at } : {}),
52
53
  ...(row.origin ? { origin: row.origin } : {}),
54
+ ...(row.preset ? { preset: row.preset } : {}),
53
55
  };
54
56
  };
55
57
 
@@ -167,5 +169,14 @@ export function agentMigrations(guildId: string): Migration[] {
167
169
  AgentConversations.migration,
168
170
  // The temp-knight presets each agent saved; kept when the agent is archived.
169
171
  HelperPresets.migration,
172
+ // The preset a temp knight was made from, by name.
173
+ {
174
+ name: "agents-helper-preset",
175
+ up: async (sql) => {
176
+ await sql`ALTER TABLE agents ADD COLUMN IF NOT EXISTS preset text`;
177
+ },
178
+ },
179
+ // Whom a preset is shared with, besides the agent that saved it.
180
+ HelperPresets.sharingMigration,
170
181
  ];
171
182
  }
@@ -44,12 +44,14 @@ export class AgentStatements {
44
44
  parent: string | null;
45
45
  /** The conversation a temp knight was made from. */
46
46
  origin: string | null;
47
+ /** The preset a temp knight was made from. */
48
+ preset: string | null;
47
49
  }): Promise<AgentRow[]> {
48
50
  return this.#sql`
49
- INSERT INTO agents (guild_id, name, display_name, prompt, avatar_prompt, channel_id, avatar_hash, character, parent, origin)
51
+ INSERT INTO agents (guild_id, name, display_name, prompt, avatar_prompt, channel_id, avatar_hash, character, parent, origin, preset)
50
52
  VALUES (${this.#guild}, ${agent.name}, ${agent.displayName}, ${agent.prompt}, ${agent.avatarPrompt},
51
53
  ${agent.channelId}, ${agent.avatarHash},
52
- ${agent.character}::jsonb, ${agent.parent}, ${agent.origin})
54
+ ${agent.character}::jsonb, ${agent.parent}, ${agent.origin}, ${agent.preset})
53
55
  RETURNING *`;
54
56
  }
55
57
 
@@ -1,5 +1,6 @@
1
1
  import type { SQL } from "bun";
2
2
  import type { CharacterSpec } from "../../characters/index.ts";
3
+ import { isCheckDatabase } from "../db/check-database.ts";
3
4
  import type { Migration } from "../db/migrations.ts";
4
5
  import { AgentError } from "../domain/errors.ts";
5
6
  import type { ThinkingLevel } from "../domain/models.ts";
@@ -55,8 +56,6 @@ export {
55
56
  MIN_GROUP_MEMBERS,
56
57
  } from "./agent-rules.ts";
57
58
 
58
- import { isCheckDatabase } from "../db/check-database.ts";
59
-
60
59
  /**
61
60
  * Agents, groups, and group messages, in the database. Agents and groups are also held
62
61
  * in memory, because every inbound message asks and only this process changes them.
@@ -138,8 +137,7 @@ export class PgAgentStore extends AgentBook implements AgentDirectory {
138
137
  avatarPrompt: seed.avatarPrompt ?? "",
139
138
  channelId: seed.channelId ?? null,
140
139
  });
141
- // Only the inserted rows join the map: reloading it whole would drop a write that
142
- // committed after its SELECT.
140
+ // Only inserted rows join the map: a whole reload drops a write committed after its SELECT.
143
141
  if (rows[0]) added.push(this.keepAgent(rows[0]).name);
144
142
  }
145
143
  return added;
@@ -165,6 +163,7 @@ export class PgAgentStore extends AgentBook implements AgentDirectory {
165
163
  /** Makes it a temp knight of this active, permanent knight. */
166
164
  parent?: string;
167
165
  origin?: string; // the conversation a temp knight was made from
166
+ preset?: string; // the preset it was made from
168
167
  }): Promise<Agent> {
169
168
  return this.#serial(async () => {
170
169
  checkAgentName(agent.name);
@@ -184,6 +183,7 @@ export class PgAgentStore extends AgentBook implements AgentDirectory {
184
183
  character: agent.character ?? null,
185
184
  parent: agent.parent ?? null,
186
185
  origin: agent.origin ?? null,
186
+ preset: agent.preset ?? null,
187
187
  });
188
188
  return this.keepAgent(rows[0]);
189
189
  });
@@ -1,5 +1,6 @@
1
1
  import type { ExtensionFactory } from "@earendil-works/pi-coding-agent";
2
2
  import type { CharacterInput } from "../../characters/index.ts";
3
+ import { helpersOf } from "../config/helpers.ts";
3
4
  import type { TurnAttachments } from "../domain/attachment.ts";
4
5
  import type { ChannelKey, TurnResult } from "../domain/conversation.ts";
5
6
  import { AgentError, ScheduleError } from "../domain/errors.ts";
@@ -17,7 +18,8 @@ import {
17
18
  agentToolsExtension,
18
19
  } from "./agent-tools.ts";
19
20
  import type { HelperTeam } from "./helper-ops.ts";
20
- import { type PresetAction, presetAction } from "./helper-preset-ops.ts";
21
+ import { ownerPresets, presetAction } from "./helper-preset-ops.ts";
22
+ import { allPresets, transferPreset } from "./helper-preset-overview.ts";
21
23
  import { type Routes, routesOf } from "./routes.ts";
22
24
  import { TeamEditing } from "./team-editing.ts";
23
25
  import type { TeamHelpers } from "./team-helpers.ts";
@@ -39,9 +41,8 @@ import { teamSelection } from "./team-selection.ts";
39
41
  import { type TeamStatus, teamStatus } from "./team-status.ts";
40
42
  import {
41
43
  agentDetails,
42
- channelIdFromRef,
43
- messageLine,
44
44
  NO_CHANNELS,
45
+ readChannel,
45
46
  teamListText,
46
47
  } from "./team-text.ts";
47
48
  import { TeamTurns } from "./team-turns.ts";
@@ -49,8 +50,6 @@ import { TeamTurns } from "./team-turns.ts";
49
50
  export type { AgentTeamOptions } from "./team-options.ts";
50
51
  export type { AgentStatus, GroupStatus, TeamStatus } from "./team-status.ts";
51
52
 
52
- const READ_LIMIT = 50;
53
-
54
53
  /**
55
54
  * The agent server: every agent is one channel and one conversation with every owner tool.
56
55
  * This team creates, changes, arranges, and archives agents and groups; its TeamTurns runs
@@ -317,21 +316,8 @@ export class DiscordAgentTeam implements AgentOps, AgentTeam {
317
316
  return this.#lifecycle.helpers.reach(...args);
318
317
  }
319
318
 
320
- async read(
321
- channel: string,
322
- around: string | undefined,
323
- limit: number | undefined,
324
- ): Promise<string> {
325
- const { channels } = this.#options;
326
- if (!channels) throw new AgentError(NO_CHANNELS);
327
- const id = channelIdFromRef(channel);
328
- const messages = await channels.read(id, {
329
- limit: Math.min(Math.max(limit ?? 20, 1), READ_LIMIT),
330
- ...(around ? { around } : {}),
331
- });
332
- return messages.length > 0
333
- ? messages.map(messageLine).join("\n")
334
- : `<#${id}> has no messages there.`;
319
+ read(...args: [string, string | undefined, number | undefined]) {
320
+ return readChannel(this.#options.channels, ...args);
335
321
  }
336
322
 
337
323
  // ── AgentOps ───────────────────────────────────────────────────────────
@@ -414,9 +400,26 @@ export class DiscordAgentTeam implements AgentOps, AgentTeam {
414
400
  }
415
401
 
416
402
  /** A knight keeps its own temp-knight presets; see `AgentOps.helperPreset`. */
417
- helperPreset(caller: AgentTurnScope, action: PresetAction): Promise<string> {
418
- return presetAction(this.#context, caller, action);
419
- }
403
+ helperPreset(...args: Parameters<AgentOps["helperPreset"]>) {
404
+ return presetAction(this.#context, ...args);
405
+ }
406
+
407
+ helpersOn(): boolean {
408
+ return helpersOf(this.#options.helpers) !== false;
409
+ }
410
+
411
+ /** An owner manages a knight's presets; see `HelperTeam.presets`. */
412
+ readonly presets: HelperTeam["presets"] = (agent) =>
413
+ ownerPresets(this.#context).list(agent);
414
+ readonly usablePresets: HelperTeam["usablePresets"] = (agent) =>
415
+ ownerPresets(this.#context).usable(agent);
416
+ readonly savePreset: HelperTeam["savePreset"] = (...args) =>
417
+ ownerPresets(this.#context).save(...args);
418
+ readonly deletePreset: HelperTeam["deletePreset"] = (agent, name) =>
419
+ ownerPresets(this.#context).delete(agent, name);
420
+ readonly allPresets = () => allPresets(this.#context);
421
+ readonly transferPreset: HelperTeam["transferPreset"] = (...args) =>
422
+ transferPreset(this.#context, ...args);
420
423
 
421
424
  /** A knight archives its own temp knights; the pages that show the parent are told. */
422
425
  helperEnd(
@@ -22,6 +22,8 @@ export type MakeAgent = (
22
22
  parent: Agent;
23
23
  /** The conversation the temp knight is made from; only it and the owners may message the temp knight. */
24
24
  origin?: string;
25
+ /** The preset it is made from, kept on its record. */
26
+ preset?: string;
25
27
  },
26
28
  fields: {
27
29
  name: string;
@@ -50,20 +52,13 @@ export async function createHelper(
50
52
  const { speaker, parent, limits } = helperMaker(ctx, caller, "helper_create");
51
53
  // A preset saved earlier is checked again now, merged with the call.
52
54
  const merged = await withPreset(ctx, parent, input);
53
- const {
54
- task,
55
- name: given,
56
- model,
57
- thinking,
58
- preset: _preset,
59
- ...rest
60
- } = merged;
55
+ const { task, name: given, model, thinking, preset, ...rest } = merged;
61
56
  const { displayName, prompt } = rest;
62
57
  if (!displayName || !prompt)
63
58
  throw new AgentError(
64
59
  "Give display_name and prompt, or a preset (from helper_preset_list) that has them.",
65
60
  );
66
- checkHelperGrant(ctx, speaker, parent, merged);
61
+ checkHelperGrant(ctx, speaker.tier, parent, merged);
67
62
  const name = given ?? nextName(ctx, parent.name);
68
63
  // Everything that can be refused is checked before anything is made or archived.
69
64
  store.checkNewName(name);
@@ -75,6 +70,7 @@ export async function createHelper(
75
70
  creator: parent,
76
71
  parent,
77
72
  origin: ctx.turns.turnChannel(caller),
73
+ ...(preset ? { preset } : {}),
78
74
  },
79
75
  { ...rest, displayName, prompt, name },
80
76
  { model, thinking },
@@ -1,4 +1,11 @@
1
1
  import type { Agent } from "./agent-rules.ts";
2
+ import type {
3
+ HelperPreset,
4
+ OwnedPreset,
5
+ PresetOverview,
6
+ PresetSharing,
7
+ UsablePreset,
8
+ } from "./helper-presets.ts";
2
9
 
3
10
  /** A knight cleared its own temp knights with `helper_end`. */
4
11
  export interface HelpersEnded {
@@ -30,4 +37,42 @@ export interface HelperTeam {
30
37
  restoreHelpers(names: readonly string[]): Promise<string[]>;
31
38
  /** Called when a knight clears its own temp knights with `helper_end`; not for an owner's or the host's clearing. */
32
39
  onHelpersEnded(listener: (event: HelpersEnded) => void): void;
40
+ /** Whether the host makes temp knights at all: false under `helpers: false`. */
41
+ helpersOn(): boolean;
42
+ /**
43
+ * A knight's temp-knight presets, by name, with whom each is shared, as an owner manages them
44
+ * outside any agent turn. These four throw AgentError when temp knights are off, for an unknown
45
+ * or archived agent, and for a temp knight, which keeps none.
46
+ */
47
+ presets(agent: string): Promise<OwnedPreset[]>;
48
+ /**
49
+ * What a knight may recruit its temp knights from: its own presets, then those other active
50
+ * knights share with it, each with the agent that saved it.
51
+ */
52
+ usablePresets(agent: string): Promise<UsablePreset[]>;
53
+ /**
54
+ * Saves a preset whole under its name, with `helper_preset_set`'s checks at the owner's tier;
55
+ * refuses a new one past 20. `sharedWith` sets who else may recruit from it: every knight,
56
+ * the knights named, or `null` none; left out, a replaced preset keeps its sharing and a new
57
+ * one is shared with none. Returns the preset as saved and whether it replaced one.
58
+ */
59
+ savePreset(
60
+ agent: string,
61
+ preset: HelperPreset,
62
+ sharedWith?: PresetSharing | null,
63
+ ): Promise<{ preset: OwnedPreset; replaced: boolean }>;
64
+ /** Deletes one of a knight's presets; says whether there was one. */
65
+ deletePreset(agent: string, name: string): Promise<boolean>;
66
+ /**
67
+ * Every preset of every active knight, by knight and then name, each with whom it is shared and
68
+ * the knights that recruited temp knights from it. Throws AgentError when temp knights are off.
69
+ */
70
+ allPresets(): Promise<PresetOverview[]>;
71
+ /**
72
+ * Moves a knight's preset to another active knight that is no temp knight, keeping its content
73
+ * and sharing: `to` leaves the shared list, and the old owner joins it unless the preset is
74
+ * shared with every knight. Refuses the same knight, a name `to` already has, `to` at 20
75
+ * presets, and an unknown preset. Temp knights made from it keep the name they recorded.
76
+ */
77
+ transferPreset(agent: string, name: string, to: string): Promise<OwnedPreset>;
33
78
  }
@@ -0,0 +1,131 @@
1
+ import { AgentError } from "../domain/errors.ts";
2
+ import { isHelper } from "./agent-rules.ts";
3
+ import type {
4
+ OwnedPreset,
5
+ PresetSharing,
6
+ UsablePreset,
7
+ } from "./helper-presets.ts";
8
+ import type { TeamContext } from "./team-options.ts";
9
+
10
+ /** A preset found for a knight, with the name its temp knight records: `<agent>/<name>` for a shared one. */
11
+ export interface FoundPreset {
12
+ preset: OwnedPreset;
13
+ ref: string;
14
+ }
15
+
16
+ const refOf = (agent: string, preset: UsablePreset): string =>
17
+ preset.agent === agent ? preset.name : `${preset.agent}/${preset.name}`;
18
+
19
+ /** The presets others share with the knight, of agents still active. */
20
+ export async function sharedPresets(
21
+ ctx: TeamContext,
22
+ agent: string,
23
+ ): Promise<UsablePreset[]> {
24
+ const { store } = ctx.options;
25
+ const shared = await store.presets.sharedWith(agent);
26
+ return shared.filter((p) => store.agent(p.agent)?.status === "active");
27
+ }
28
+
29
+ /** What a knight may recruit from: its own presets first, then those shared with it. */
30
+ export async function usablePresets(
31
+ ctx: TeamContext,
32
+ agent: string,
33
+ ): Promise<UsablePreset[]> {
34
+ const own = await ctx.options.store.presets.list(agent);
35
+ return [
36
+ ...own.map((preset) => ({ ...preset, agent })),
37
+ ...(await sharedPresets(ctx, agent)),
38
+ ];
39
+ }
40
+
41
+ /**
42
+ * The preset a knight names: its own, `<agent>/<name>` shared with it, or a bare name one shared
43
+ * preset alone has. Its own wins over a shared one; a bare name several share is refused with
44
+ * their qualified names, and an unknown one with the names the knight may use.
45
+ */
46
+ export async function findPreset(
47
+ ctx: TeamContext,
48
+ agent: string,
49
+ ref: string,
50
+ ): Promise<FoundPreset> {
51
+ const slash = ref.indexOf("/");
52
+ const owner = slash < 0 ? agent : ref.slice(0, slash);
53
+ const name = slash < 0 ? ref : ref.slice(slash + 1);
54
+ if (owner === agent) {
55
+ const own = await ctx.options.store.presets.get(agent, name);
56
+ if (own) return { preset: own, ref: name };
57
+ }
58
+ const shared = await sharedPresets(ctx, agent);
59
+ const matches = shared.filter(
60
+ (p) => p.name === name && (slash < 0 || p.agent === owner),
61
+ );
62
+ const [only] = matches;
63
+ if (only && matches.length === 1) {
64
+ const { agent: _agent, ...preset } = only;
65
+ return { preset, ref: refOf(agent, only) };
66
+ }
67
+ if (matches.length > 1)
68
+ throw new AgentError(
69
+ `Several knights share a preset "${name}"; name one of ${matches.map((p) => refOf(agent, p)).join(", ")}.`,
70
+ );
71
+ const names = (await usablePresets(ctx, agent)).map((p) => refOf(agent, p));
72
+ throw new AgentError(
73
+ names.length > 0
74
+ ? `You have no preset "${ref}". Your presets: ${names.join(", ")}.`
75
+ : `You have no preset "${ref}", nor any other; save one with helper_preset_set.`,
76
+ );
77
+ }
78
+
79
+ /**
80
+ * The sharing as it is saved, or AgentError: the knights named must be existing knights, not temp
81
+ * knights; the preset's own agent is dropped from the list, and an empty list shares with none.
82
+ */
83
+ export function checkSharing(
84
+ ctx: TeamContext,
85
+ agent: string,
86
+ sharing: PresetSharing | null | undefined,
87
+ ): PresetSharing | null | undefined {
88
+ if (sharing === undefined || sharing === null || sharing === "all")
89
+ return sharing;
90
+ const { store } = ctx.options;
91
+ const names = [...new Set(sharing)].filter((name) => name !== agent);
92
+ const unknown = names.filter((name) => {
93
+ const known = store.agent(name);
94
+ return !known || isHelper(known);
95
+ });
96
+ if (unknown.length > 0)
97
+ throw new AgentError(
98
+ `A preset can be shared only with knights; not one: ${unknown.join(", ")}.`,
99
+ );
100
+ return names.length > 0 ? names : null;
101
+ }
102
+
103
+ /** One line of `helper_preset_list`: a shared preset by its qualified name and its agent. */
104
+ export function presetLine(agent: string, preset: UsablePreset): string {
105
+ const prompt = preset.prompt.replace(/\s+/g, " ").trim();
106
+ const head = prompt.length > 80 ? `${prompt.slice(0, 80)}…` : prompt;
107
+ const extras = [
108
+ preset.skills.length > 0 ? `skills: ${preset.skills.join(", ")}` : "",
109
+ preset.model ? `model: ${preset.model}` : "",
110
+ ].filter(Boolean);
111
+ const by = preset.agent === agent ? "" : ` [shared by ${preset.agent}]`;
112
+ return `${refOf(agent, preset)}${by}: "${preset.displayName}"${extras.length > 0 ? ` (${extras.join("; ")})` : ""}: ${head}`;
113
+ }
114
+
115
+ /** A preset in full, as `helper_preset_list` with a name shows it. */
116
+ export function presetText(found: FoundPreset): string {
117
+ const { preset, ref } = found;
118
+ const slash = ref.indexOf("/");
119
+ return [
120
+ `Preset "${ref}"${slash < 0 ? "" : ` (shared by ${ref.slice(0, slash)})`}`,
121
+ `Display name: ${preset.displayName}`,
122
+ `Skills: ${preset.skills.length > 0 ? preset.skills.join(", ") : "none"}`,
123
+ ...(preset.character?.class ? [`Class: ${preset.character.class}`] : []),
124
+ ...(preset.character?.palette
125
+ ? [`Color: ${preset.character.palette}`]
126
+ : []),
127
+ ...(preset.model ? [`Model: ${preset.model}`] : []),
128
+ ...(preset.thinking ? [`Thinking: ${preset.thinking}`] : []),
129
+ `Prompt:\n${preset.prompt}`,
130
+ ].join("\n");
131
+ }
@@ -3,7 +3,7 @@ import { helpersOf, type ResolvedHelpers } from "../config/helpers.ts";
3
3
  import { AgentError } from "../domain/errors.ts";
4
4
  import { THINKING_LEVELS } from "../domain/models.ts";
5
5
  import type { AgentTurnScope } from "../domain/ports.ts";
6
- import type { Speaker } from "../identity/speakers.ts";
6
+ import type { Speaker, Tier } from "../identity/speakers.ts";
7
7
  import { toolTiers } from "../runtime/tool-tiers.ts";
8
8
  import {
9
9
  type Agent,
@@ -12,7 +12,19 @@ import {
12
12
  checkPrompt,
13
13
  isHelper,
14
14
  } from "./agent-rules.ts";
15
- import type { HelperPreset } from "./helper-presets.ts";
15
+ import {
16
+ checkSharing,
17
+ findPreset,
18
+ presetLine,
19
+ presetText,
20
+ usablePresets,
21
+ } from "./helper-preset-lookup.ts";
22
+ import type {
23
+ HelperPreset,
24
+ OwnedPreset,
25
+ PresetSharing,
26
+ UsablePreset,
27
+ } from "./helper-presets.ts";
16
28
  import type { TeamContext } from "./team-options.ts";
17
29
 
18
30
  /** What the helper_preset tools ask of the team. */
@@ -64,19 +76,16 @@ export function helperMaker(
64
76
  */
65
77
  export function checkHelperGrant(
66
78
  ctx: TeamContext,
67
- speaker: Speaker,
79
+ tier: Tier,
68
80
  parent: Agent,
69
81
  fields: Pick<HelperFields, "model" | "thinking" | "skills">,
70
82
  ): void {
71
83
  const tiers = ctx.options.toolTiers ?? toolTiers();
72
- if (
73
- !tiers.allows(speaker.tier, "agent_update") &&
74
- (fields.model || fields.thinking)
75
- )
84
+ if (!tiers.allows(tier, "agent_update") && (fields.model || fields.thinking))
76
85
  throw new AgentError(
77
86
  "A temp knight runs your model and thinking level; choosing others needs a higher tier.",
78
87
  );
79
- if (fields.skills?.length && !tiers.allows(speaker.tier, "agent_skills")) {
88
+ if (fields.skills?.length && !tiers.allows(tier, "agent_skills")) {
80
89
  const own = new Set(ctx.options.skills?.carriedNames(parent.name) ?? []);
81
90
  const extra = fields.skills.filter((skill) => !own.has(skill));
82
91
  if (extra.length > 0)
@@ -87,8 +96,9 @@ export function checkHelperGrant(
87
96
  }
88
97
 
89
98
  /**
90
- * The call's fields over the named preset: what the call gives replaces the preset's, and its
91
- * skills are added after the preset's. An unknown preset is refused with the caller's names.
99
+ * The call's fields over the named preset (see `findPreset`): what the call gives replaces the
100
+ * preset's, and its skills are added after the preset's. `preset` comes back as its temp knight
101
+ * records it, qualified for a shared one.
92
102
  */
93
103
  export async function withPreset<T extends HelperFields>(
94
104
  ctx: TeamContext,
@@ -97,20 +107,12 @@ export async function withPreset<T extends HelperFields>(
97
107
  ): Promise<T> {
98
108
  const { preset: name, ...given } = input;
99
109
  if (!name) return input;
100
- const presets = ctx.options.store.presets;
101
- const preset = await presets.get(parent.name, name);
102
- if (!preset) {
103
- const names = (await presets.list(parent.name)).map((p) => p.name);
104
- throw new AgentError(
105
- names.length > 0
106
- ? `You have no preset "${name}". Your presets: ${names.join(", ")}.`
107
- : `You have no preset "${name}", nor any other; save one with helper_preset_set.`,
108
- );
109
- }
110
+ const { preset, ref } = await findPreset(ctx, parent.name, name);
110
111
  const skills = [...new Set([...preset.skills, ...(given.skills ?? [])])];
111
112
  const character = { ...preset.character, ...given.character };
112
113
  return {
113
114
  ...given,
115
+ preset: ref,
114
116
  displayName: given.displayName ?? preset.displayName,
115
117
  prompt: given.prompt ?? preset.prompt,
116
118
  ...(Object.keys(character).length > 0 ? { character } : {}),
@@ -124,7 +126,10 @@ export async function withPreset<T extends HelperFields>(
124
126
  } as T;
125
127
  }
126
128
 
127
- /** The helper_preset tools: an agent saves, lists, and deletes its own temp-knight presets. */
129
+ /**
130
+ * The helper_preset tools: an agent saves and deletes its own temp-knight presets, keeping their
131
+ * sharing, and lists its own and those shared with it.
132
+ */
128
133
  export async function presetAction(
129
134
  ctx: TeamContext,
130
135
  caller: AgentTurnScope,
@@ -134,30 +139,41 @@ export async function presetAction(
134
139
  const { speaker, parent } = helperMaker(ctx, caller, tool);
135
140
  const presets = ctx.options.store.presets;
136
141
  if (action.kind === "set") {
137
- const { preset } = action;
138
- checkPreset(ctx, preset);
139
- checkHelperGrant(ctx, speaker, parent, preset);
142
+ const preset = validatePreset(ctx, speaker.tier, parent, action.preset);
140
143
  const done = await presets.set(parent.name, preset);
141
- return `${done === "created" ? "Created" : "Replaced"} the preset "${preset.name}"; make its temp knight with helper_create and preset "${preset.name}".`;
144
+ return `${done === "created" ? "Created" : "Replaced"} the preset "${preset.name}"; recruit its temp knight with helper_create and preset "${preset.name}".`;
142
145
  }
143
146
  if (action.kind === "delete") {
144
- if (!(await presets.delete(parent.name, action.name)))
147
+ const owner = action.name.split("/")[0] ?? "";
148
+ if (action.name.includes("/") && owner !== parent.name)
149
+ throw new AgentError(
150
+ `The preset "${action.name}" is ${owner}'s; only ${owner} or an owner may delete it.`,
151
+ );
152
+ const name = action.name.slice(action.name.indexOf("/") + 1);
153
+ if (!(await presets.delete(parent.name, name)))
145
154
  throw new AgentError(`You have no preset "${action.name}".`);
146
- return `Deleted the preset "${action.name}".`;
147
- }
148
- if (action.name) {
149
- const preset = await presets.get(parent.name, action.name);
150
- if (!preset) throw new AgentError(`You have no preset "${action.name}".`);
151
- return presetText(preset);
155
+ return `Deleted the preset "${name}".`;
152
156
  }
153
- const all = await presets.list(parent.name);
157
+ if (action.name)
158
+ return presetText(await findPreset(ctx, parent.name, action.name));
159
+ const all = await usablePresets(ctx, parent.name);
154
160
  if (all.length === 0)
155
161
  return "You have no presets; save one with helper_preset_set.";
156
- return all.map(presetLine).join("\n");
162
+ return all.map((preset) => presetLine(parent.name, preset)).join("\n");
157
163
  }
158
164
 
159
- /** The checks a temp knight's fields get when it is made, applied when the preset is saved. */
160
- function checkPreset(ctx: TeamContext, preset: HelperPreset): void {
165
+ /**
166
+ * The preset as it is saved, its skills deduplicated, or AgentError: the checks a temp knight's
167
+ * fields get when it is made, and what a speaker of `tier` may grant beyond the parent's own.
168
+ * The store holds the cap of presets as it saves.
169
+ */
170
+ export function validatePreset(
171
+ ctx: TeamContext,
172
+ tier: Tier,
173
+ parent: Agent,
174
+ given: HelperPreset,
175
+ ): HelperPreset {
176
+ const preset = { ...given, skills: [...new Set(given.skills)] };
161
177
  if (!PRESET_NAME.test(preset.name))
162
178
  throw new AgentError(
163
179
  `"${preset.name}" is not a preset name: use 1 to 32 lowercase letters, digits, and dashes.`,
@@ -180,28 +196,43 @@ function checkPreset(ctx: TeamContext, preset: HelperPreset): void {
180
196
  );
181
197
  registry.checkRegistered(preset.skills);
182
198
  }
199
+ checkHelperGrant(ctx, tier, parent, preset);
200
+ return preset;
183
201
  }
184
202
 
185
- const presetLine = (preset: HelperPreset): string => {
186
- const prompt = preset.prompt.replace(/\s+/g, " ").trim();
187
- const head = prompt.length > 80 ? `${prompt.slice(0, 80)}…` : prompt;
188
- const extras = [
189
- preset.skills.length > 0 ? `skills: ${preset.skills.join(", ")}` : "",
190
- preset.model ? `model: ${preset.model}` : "",
191
- ].filter(Boolean);
192
- return `${preset.name}: "${preset.displayName}"${extras.length > 0 ? ` (${extras.join("; ")})` : ""}: ${head}`;
193
- };
203
+ /**
204
+ * The knight whose presets an owner manages from outside any agent turn: refused when temp knights
205
+ * are off, for an unknown or archived agent, and for a temp knight, which keeps none.
206
+ */
207
+ export function presetOwner(ctx: TeamContext, name: string): Agent {
208
+ if (!helpersOf(ctx.options.helpers))
209
+ throw new AgentError("Temp knights are switched off on this host.");
210
+ const agent = ctx.options.store.activeAgent(name);
211
+ if (isHelper(agent))
212
+ throw new AgentError(`"${name}" is a temp knight and keeps no presets.`);
213
+ return agent;
214
+ }
194
215
 
195
- const presetText = (preset: HelperPreset): string =>
196
- [
197
- `Preset "${preset.name}"`,
198
- `Display name: ${preset.displayName}`,
199
- `Skills: ${preset.skills.length > 0 ? preset.skills.join(", ") : "none"}`,
200
- ...(preset.character?.class ? [`Class: ${preset.character.class}`] : []),
201
- ...(preset.character?.palette
202
- ? [`Color: ${preset.character.palette}`]
203
- : []),
204
- ...(preset.model ? [`Model: ${preset.model}`] : []),
205
- ...(preset.thinking ? [`Thinking: ${preset.thinking}`] : []),
206
- `Prompt:\n${preset.prompt}`,
207
- ].join("\n");
216
+ /** An owner's handling of a knight's presets, at the owner's tier; see `HelperTeam.presets`. */
217
+ export const ownerPresets = (ctx: TeamContext) => ({
218
+ list: async (agent: string): Promise<OwnedPreset[]> =>
219
+ ctx.options.store.presets.list(presetOwner(ctx, agent).name),
220
+ usable: async (agent: string): Promise<UsablePreset[]> =>
221
+ usablePresets(ctx, presetOwner(ctx, agent).name),
222
+ save: async (
223
+ agent: string,
224
+ given: HelperPreset,
225
+ sharedWith?: PresetSharing | null,
226
+ ): Promise<{ preset: OwnedPreset; replaced: boolean }> => {
227
+ const parent = presetOwner(ctx, agent);
228
+ const { sharedWith: _ignored, ...content } = given as OwnedPreset;
229
+ const valid = validatePreset(ctx, "owner", parent, content);
230
+ const sharing = checkSharing(ctx, parent.name, sharedWith);
231
+ const { presets } = ctx.options.store;
232
+ const done = await presets.set(parent.name, valid, sharing);
233
+ const preset = (await presets.get(parent.name, valid.name)) ?? valid;
234
+ return { preset, replaced: done === "replaced" };
235
+ },
236
+ delete: async (agent: string, name: string): Promise<boolean> =>
237
+ ctx.options.store.presets.delete(presetOwner(ctx, agent).name, name),
238
+ });
@@ -0,0 +1,80 @@
1
+ import { helpersOf } from "../config/helpers.ts";
2
+ import { AgentError } from "../domain/errors.ts";
3
+ import { isHelper } from "./agent-rules.ts";
4
+ import { presetOwner } from "./helper-preset-ops.ts";
5
+ import type {
6
+ OwnedPreset,
7
+ PresetOverview,
8
+ PresetRecruits,
9
+ } from "./helper-presets.ts";
10
+ import type { TeamContext } from "./team-options.ts";
11
+
12
+ /**
13
+ * Every preset of an active knight, with the knights that recruited from it: a temp knight
14
+ * records its own parent's preset by name and another's as `<agent>/<name>`.
15
+ */
16
+ export async function allPresets(ctx: TeamContext): Promise<PresetOverview[]> {
17
+ if (!helpersOf(ctx.options.helpers))
18
+ throw new AgentError("Temp knights are switched off on this host.");
19
+ const { store } = ctx.options;
20
+ const [presets, rows] = await Promise.all([
21
+ store.presets.all(),
22
+ store.presets.recruits(),
23
+ ]);
24
+ const byPreset = new Map<string, Map<string, PresetRecruits>>();
25
+ for (const row of rows) {
26
+ const slash = row.preset.indexOf("/");
27
+ const key = slash < 0 ? `${row.parent}/${row.preset}` : row.preset;
28
+ const knights = byPreset.get(key) ?? new Map<string, PresetRecruits>();
29
+ byPreset.set(key, knights);
30
+ const seen = knights.get(row.parent) ?? {
31
+ knight: row.parent,
32
+ active: 0,
33
+ archived: 0,
34
+ };
35
+ knights.set(row.parent, seen);
36
+ seen[row.status] += row.count;
37
+ const last = row.last?.toISOString();
38
+ if (last && (!seen.last || last > seen.last)) seen.last = last;
39
+ }
40
+ return presets
41
+ .filter((preset) => {
42
+ const agent = store.agent(preset.agent);
43
+ return agent?.status === "active" && !isHelper(agent);
44
+ })
45
+ .map((preset) => ({
46
+ ...preset,
47
+ recruits: [
48
+ ...(byPreset.get(`${preset.agent}/${preset.name}`)?.values() ?? []),
49
+ ].sort((a, b) => a.knight.localeCompare(b.knight)),
50
+ }));
51
+ }
52
+
53
+ /**
54
+ * Moves a knight's preset to another active knight, keeping its content and sharing: the new
55
+ * agent leaves the shared list, and the old one joins it unless the preset is shared with all.
56
+ */
57
+ export async function transferPreset(
58
+ ctx: TeamContext,
59
+ agent: string,
60
+ name: string,
61
+ to: string,
62
+ ): Promise<OwnedPreset> {
63
+ const from = presetOwner(ctx, agent).name;
64
+ if (to === from)
65
+ throw new AgentError(`The preset "${name}" is already ${from}'s.`);
66
+ const target = ctx.options.store.activeAgent(to);
67
+ if (isHelper(target))
68
+ throw new AgentError(`"${to}" is a temp knight and keeps no presets.`);
69
+ const { presets } = ctx.options.store;
70
+ const preset = await presets.get(from, name);
71
+ if (!preset) throw new AgentError(`${from} has no preset "${name}".`);
72
+ const shared = preset.sharedWith;
73
+ const sharing =
74
+ shared === "all"
75
+ ? ["*"]
76
+ : [...new Set([...(shared ?? []), from])].filter((n) => n !== to);
77
+ if (!(await presets.transfer(from, name, to, sharing)))
78
+ throw new AgentError(`${from} has no preset "${name}".`);
79
+ return (await presets.get(to, name)) ?? preset;
80
+ }
@@ -23,7 +23,7 @@ const PRESET_NAME = Type.String({
23
23
  description: "The preset's name: lowercase letters, digits, and dashes.",
24
24
  });
25
25
 
26
- /** The tools that keep a knight's temp-knight presets, which only it sees and uses. */
26
+ /** The tools that keep a knight's temp-knight presets, which it and the knights they are shared with recruit from. */
27
27
  export function helperPresetToolDefs(
28
28
  ops: Pick<AgentOps, "helperPreset">,
29
29
  scope: AgentTurnScope,
@@ -36,7 +36,7 @@ export function helperPresetToolDefs(
36
36
  name: "helper_preset_set",
37
37
  label: "Save temp knight preset",
38
38
  description:
39
- "Save a temp knight you make often (its role prompt, skills, and look) as a preset, then make it with helper_create and preset instead of writing them again. Saving under a name you have replaces that preset whole. Only you see and use your presets; you may keep 20.",
39
+ "Save a temp knight you make often (its role prompt, skills, and look) as a preset, then recruit it with helper_create and preset instead of writing them again. Saving under a name you have replaces that preset whole and keeps whom it is shared with, which only an owner sets. Only you and the knights an owner shares it with recruit from it, and only you or an owner change it; you may keep 20.",
40
40
  parameters: Type.Object({
41
41
  name: PRESET_NAME,
42
42
  display_name: DISPLAY,
@@ -78,7 +78,7 @@ export function helperPresetToolDefs(
78
78
  name: "helper_preset_list",
79
79
  label: "List temp knight presets",
80
80
  description:
81
- "List your temp knight presets, one line each; with a name, show that preset in full.",
81
+ "List the presets you may recruit temp knights from, one line each: yours, then those other knights share with you as <agent>/<name>. With a name, show that preset in full.",
82
82
  parameters: Type.Object({
83
83
  name: Type.Optional(
84
84
  Type.String({ description: "A preset to show in full." }),
@@ -95,7 +95,8 @@ export function helperPresetToolDefs(
95
95
  {
96
96
  name: "helper_preset_delete",
97
97
  label: "Delete temp knight preset",
98
- description: "Delete one of your temp knight presets.",
98
+ description:
99
+ "Delete one of your own temp knight presets; one shared with you only its knight or an owner deletes.",
99
100
  parameters: Type.Object({
100
101
  name: Type.String({ description: "The preset's name." }),
101
102
  }),
@@ -16,7 +16,21 @@ export interface HelperPreset {
16
16
  thinking?: string;
17
17
  }
18
18
 
19
+ /** Who besides its saving agent may recruit from a preset: every knight, or the ones named. */
20
+ export type PresetSharing = "all" | string[];
21
+
22
+ /** A preset as its saving agent and the owners see it: with whom it is shared, absent for none. */
23
+ export interface OwnedPreset extends HelperPreset {
24
+ sharedWith?: PresetSharing;
25
+ }
26
+
27
+ /** A preset another knight may recruit from, with the agent that saved it. */
28
+ export interface UsablePreset extends OwnedPreset {
29
+ agent: string;
30
+ }
31
+
19
32
  interface Row {
33
+ agent: string;
20
34
  name: string;
21
35
  display_name: string;
22
36
  prompt: string;
@@ -24,9 +38,11 @@ interface Row {
24
38
  character: CharacterInput | null;
25
39
  model: string | null;
26
40
  thinking: string | null;
41
+ shared_with: string[] | null;
27
42
  }
28
43
 
29
- const toPreset = (row: Row): HelperPreset => ({
44
+ const toPreset = (row: Row): UsablePreset => ({
45
+ agent: row.agent,
30
46
  name: row.name,
31
47
  displayName: row.display_name,
32
48
  prompt: row.prompt,
@@ -34,11 +50,47 @@ const toPreset = (row: Row): HelperPreset => ({
34
50
  ...(row.character ? { character: row.character } : {}),
35
51
  ...(row.model ? { model: row.model } : {}),
36
52
  ...(row.thinking ? { thinking: row.thinking } : {}),
53
+ ...(row.shared_with
54
+ ? {
55
+ sharedWith: row.shared_with.includes("*")
56
+ ? ("all" as const)
57
+ : row.shared_with,
58
+ }
59
+ : {}),
37
60
  });
38
61
 
62
+ /** The temp knights one knight recruited from a preset, by their status. */
63
+ export interface PresetRecruits {
64
+ /** The knight that made them. */
65
+ knight: string;
66
+ active: number;
67
+ archived: number;
68
+ /** When the latest of them was made, as an ISO time. */
69
+ last?: string;
70
+ }
71
+
72
+ /** A preset as the presets page lists it: with its agent and who recruited from it. */
73
+ export interface PresetOverview extends UsablePreset {
74
+ /** The knights that made temp knights from it, by name. */
75
+ recruits: PresetRecruits[];
76
+ }
77
+
78
+ /** The temp knights of one parent made from one recorded preset, with one status. */
79
+ export interface RecruitRow {
80
+ parent: string;
81
+ preset: string;
82
+ status: "active" | "archived";
83
+ count: number;
84
+ last: Date | null;
85
+ }
86
+
87
+ const owned = ({ agent: _agent, ...preset }: UsablePreset): OwnedPreset =>
88
+ preset;
89
+
39
90
  /**
40
- * The temp-knight presets, each owned by the agent that saved it; only that agent reads or uses
41
- * them. They outlive an archive, so an agent restored finds its presets.
91
+ * The temp-knight presets, each owned by the agent that saved it: only it and the owners change
92
+ * one, and others recruit from it only when it is shared with them. They outlive an archive, so an
93
+ * agent restored finds its presets.
42
94
  */
43
95
  export class HelperPresets {
44
96
  readonly #sql: SQL;
@@ -70,26 +122,51 @@ export class HelperPresets {
70
122
  },
71
123
  };
72
124
 
125
+ /** Who may recruit from a preset besides its agent: `NULL` none, `["*"]` every knight. */
126
+ static readonly sharingMigration = {
127
+ name: "helper-presets-shared",
128
+ up: async (sql: SQL) => {
129
+ await sql`ALTER TABLE helper_presets ADD COLUMN IF NOT EXISTS shared_with jsonb`;
130
+ },
131
+ };
132
+
73
133
  /** The agent's presets, by name. */
74
- async list(agent: string): Promise<HelperPreset[]> {
134
+ async list(agent: string): Promise<OwnedPreset[]> {
75
135
  const rows: Row[] = await this.#sql`
76
136
  SELECT * FROM helper_presets
77
137
  WHERE guild_id = ${this.#guild} AND agent = ${agent} ORDER BY name`;
138
+ return rows.map((row) => owned(toPreset(row)));
139
+ }
140
+
141
+ /** The presets other agents share with this one, by their agent and then name. */
142
+ async sharedWith(agent: string): Promise<UsablePreset[]> {
143
+ const rows: Row[] = await this.#sql`
144
+ SELECT * FROM helper_presets
145
+ WHERE guild_id = ${this.#guild} AND agent <> ${agent}
146
+ AND (shared_with @> '["*"]'::jsonb
147
+ OR shared_with @> jsonb_build_array(${agent}::text))
148
+ ORDER BY agent, name`;
78
149
  return rows.map(toPreset);
79
150
  }
80
151
 
81
- async get(agent: string, name: string): Promise<HelperPreset | undefined> {
152
+ async get(agent: string, name: string): Promise<OwnedPreset | undefined> {
82
153
  const rows: Row[] = await this.#sql`
83
154
  SELECT * FROM helper_presets
84
155
  WHERE guild_id = ${this.#guild} AND agent = ${agent} AND name = ${name}`;
85
- return rows[0] ? toPreset(rows[0]) : undefined;
156
+ return rows[0] ? owned(toPreset(rows[0])) : undefined;
86
157
  }
87
158
 
88
- /** Saves the preset whole, refusing a new one past the cap; says whether it was new. */
159
+ /**
160
+ * Saves the preset whole, refusing a new one past the cap; says whether it was new. `sharing`
161
+ * left out keeps a replaced preset's and shares a new one with none.
162
+ */
89
163
  async set(
90
164
  agent: string,
91
165
  preset: HelperPreset,
166
+ sharing?: PresetSharing | null,
92
167
  ): Promise<"created" | "replaced"> {
168
+ const shared = sharing === "all" ? ["*"] : sharing?.length ? sharing : null;
169
+ const keep = sharing === undefined;
93
170
  const guild = this.#guild;
94
171
  return this.#sql.begin(async (tx) => {
95
172
  // One save per agent at a time, so two cannot both pass the cap.
@@ -105,18 +182,70 @@ export class HelperPresets {
105
182
  );
106
183
  await tx`
107
184
  INSERT INTO helper_presets
108
- (guild_id, agent, name, display_name, prompt, skills, character, model, thinking)
185
+ (guild_id, agent, name, display_name, prompt, skills, character, model, thinking,
186
+ shared_with)
109
187
  VALUES (${guild}, ${agent}, ${preset.name}, ${preset.displayName}, ${preset.prompt},
110
188
  ${preset.skills}::jsonb, ${preset.character ?? null}::jsonb,
111
- ${preset.model ?? null}, ${preset.thinking ?? null})
189
+ ${preset.model ?? null}, ${preset.thinking ?? null}, ${shared}::jsonb)
112
190
  ON CONFLICT (guild_id, agent, name) DO UPDATE SET
113
191
  display_name = EXCLUDED.display_name, prompt = EXCLUDED.prompt,
114
192
  skills = EXCLUDED.skills, character = EXCLUDED.character,
115
- model = EXCLUDED.model, thinking = EXCLUDED.thinking, updated_at = now()`;
193
+ model = EXCLUDED.model, thinking = EXCLUDED.thinking, updated_at = now(),
194
+ shared_with = CASE WHEN ${keep} THEN helper_presets.shared_with
195
+ ELSE EXCLUDED.shared_with END`;
116
196
  return replaced ? "replaced" : "created";
117
197
  });
118
198
  }
119
199
 
200
+ /** Every agent's presets, by agent and then name. */
201
+ async all(): Promise<UsablePreset[]> {
202
+ const rows: Row[] = await this.#sql`
203
+ SELECT * FROM helper_presets WHERE guild_id = ${this.#guild} ORDER BY agent, name`;
204
+ return rows.map(toPreset);
205
+ }
206
+
207
+ /** The temp knights made from a preset, counted by parent, recorded preset, and status. */
208
+ recruits(): Promise<RecruitRow[]> {
209
+ return this.#sql`
210
+ SELECT parent, preset, status, count(*)::int AS count, max(created_at) AS last
211
+ FROM agents
212
+ WHERE guild_id = ${this.#guild} AND parent IS NOT NULL AND preset IS NOT NULL
213
+ GROUP BY parent, preset, status`;
214
+ }
215
+
216
+ /**
217
+ * Moves a preset to another agent with the sharing given, refusing when that agent has one of
218
+ * the name or the cap of presets; says whether there was a preset to move.
219
+ */
220
+ async transfer(
221
+ from: string,
222
+ name: string,
223
+ to: string,
224
+ sharing: string[],
225
+ ): Promise<boolean> {
226
+ const guild = this.#guild;
227
+ return this.#sql.begin(async (tx) => {
228
+ // The lock `set` takes for the receiving agent, so the cap holds against its saves.
229
+ await tx`SELECT pg_advisory_xact_lock(hashtext(${`helper-presets:${guild}:${to}`}))`;
230
+ const [counted]: { total: number; same: number }[] = await tx`
231
+ SELECT count(*)::int AS total, count(*) FILTER (WHERE name = ${name})::int AS same
232
+ FROM helper_presets WHERE guild_id = ${guild} AND agent = ${to}`;
233
+ if ((counted?.same ?? 0) > 0)
234
+ throw new AgentError(`${to} already has a preset "${name}".`);
235
+ if ((counted?.total ?? 0) >= MAX_HELPER_PRESETS)
236
+ throw new AgentError(
237
+ `${to} has ${MAX_HELPER_PRESETS} presets, the most one may keep; it must delete one first.`,
238
+ );
239
+ const moved = await tx`
240
+ UPDATE helper_presets
241
+ SET agent = ${to}, updated_at = now(),
242
+ shared_with = ${sharing.length > 0 ? sharing : null}::jsonb
243
+ WHERE guild_id = ${guild} AND agent = ${from} AND name = ${name}
244
+ RETURNING name`;
245
+ return moved.length > 0;
246
+ });
247
+ }
248
+
120
249
  /** Deletes one of the agent's presets; says whether there was one. */
121
250
  async delete(agent: string, name: string): Promise<boolean> {
122
251
  const rows = await this.#sql`
@@ -25,12 +25,12 @@ export function helperToolDefs(
25
25
  {
26
26
  name: "helper_create",
27
27
  label: "Create temp knight",
28
- description: `Make a temp knight (a helper knight) for one self-contained task that can run on its own, such as one of several things to look up or compare. It is a real agent with its own picture and place, listed under you; it starts at once and its answer comes back to you here as a new turn, like message_agent's. Make one per task, then end your turn; when the answers are in, merge them and clear the ones that are done with helper_end. It runs your model unless you give one, cannot make knights, temp knights or groups, and has no schedules. You may have a few at once, and when you are at the limit your oldest finished one is archived to make room. A temp knight you make often can be saved as a preset (helper_preset_set) and made by its name: what you give in the call replaces the preset's, and skills you give are added to the preset's.`,
28
+ description: `Make a temp knight (a helper knight) for one self-contained task that can run on its own, such as one of several things to look up or compare. It is a real agent with its own picture and place, listed under you; it starts at once and its answer comes back to you here as a new turn, like message_agent's. Make one per task, then end your turn; when the answers are in, merge them and clear the ones that are done with helper_end. It runs your model unless you give one, cannot make knights, temp knights or groups, and has no schedules. You may have a few at once, and when you are at the limit your oldest finished one is archived to make room. Before making a temp knight, check helper_preset_list for a preset to recruit it from and recruit with helper_create and preset when one fits; write a new one only otherwise. A temp knight recruited from a preset takes what you leave out from it: what you give in the call replaces the preset's, and skills you give are added to the preset's. Save one you make often with helper_preset_set.`,
29
29
  parameters: Type.Object({
30
30
  preset: Type.Optional(
31
31
  Type.String({
32
32
  description:
33
- "A preset of yours, from helper_preset_list, that gives what you leave out here.",
33
+ "The preset to recruit it from, from helper_preset_list: your own by its name, or a shared one as <agent>/<name>; it gives what you leave out here.",
34
34
  }),
35
35
  ),
36
36
  display_name: Type.Optional(
@@ -158,9 +158,8 @@ export class TeamEditing {
158
158
 
159
159
  /**
160
160
  * An owner creates an agent from outside any agent turn (the web app's form; any other tier is
161
- * refused, since the opening task runs as `speaker`): the same checks,
162
- * picture, channel and opening task as `create`, and the model and thinking level the owner
163
- * picked. Without a task the agent only exists, waiting in its room. Returns the new agent.
161
+ * refused, since the opening task runs as `speaker`): the checks, picture, channel and opening
162
+ * task of `create`, and the owner's model and thinking. Without a task it waits in its room.
164
163
  */
165
164
  async createFor(
166
165
  speaker: Speaker,
@@ -224,6 +223,7 @@ export class TeamEditing {
224
223
  parent?: Agent | undefined;
225
224
  /** The conversation a temp knight is made from: made on Discord, it lives in a thread of the parent's channel, made elsewhere in its rooms alone. */
226
225
  origin?: string | undefined;
226
+ preset?: string | undefined;
227
227
  },
228
228
  input: {
229
229
  name: string;
@@ -258,8 +258,7 @@ export class TeamEditing {
258
258
  const categoryName = teamCategory(category, "Agents");
259
259
  store.checkNewName(input.name);
260
260
  skills?.checkRegistered(carried);
261
- // A model or thinking level the host cannot run fails the create, before anything is made.
262
- // A temp knight runs the parent's, as it stands, unless told otherwise.
261
+ // An unusable model or thinking fails the create first; a temp knight runs its parent's unless told otherwise.
263
262
  const model =
264
263
  settings.model === undefined && who.parent
265
264
  ? who.parent.model
@@ -299,6 +298,7 @@ export class TeamEditing {
299
298
  ...(channelId ? { channelId } : {}),
300
299
  ...(who.parent ? { parent: who.parent.name } : {}),
301
300
  ...(who.parent && who.origin ? { origin: who.origin } : {}),
301
+ ...(who.parent && who.preset ? { preset: who.preset } : {}),
302
302
  });
303
303
  } catch (error) {
304
304
  await this.#closeOrphan(channelId);
@@ -4,7 +4,7 @@ import type { ThinkingSetting } from "../domain/models.ts";
4
4
  import { assistantName } from "../i18n/index.ts";
5
5
  import { zonedStamp } from "../kernel/time.ts";
6
6
  import type { AgentDirectory } from "../plugin-api/services.ts";
7
- import type { ChannelMessage } from "./agent-ports.ts";
7
+ import type { AgentChannels, ChannelMessage } from "./agent-ports.ts";
8
8
  import { characterOf, isHelper } from "./agent-rules.ts";
9
9
  import { describeThinking } from "./agent-settings.ts";
10
10
  import type { Agent } from "./agent-store.ts";
@@ -90,3 +90,23 @@ export function agentDetails(
90
90
  `Prompt:\n${agent.prompt}`,
91
91
  ].join("\n");
92
92
  }
93
+
94
+ const READ_LIMIT = 50;
95
+
96
+ /** channel_read: messages of a Discord channel, newest last, around one when given. */
97
+ export async function readChannel(
98
+ channels: AgentChannels | undefined,
99
+ channel: string,
100
+ around: string | undefined,
101
+ limit: number | undefined,
102
+ ): Promise<string> {
103
+ if (!channels) throw new AgentError(NO_CHANNELS);
104
+ const id = channelIdFromRef(channel);
105
+ const messages = await channels.read(id, {
106
+ limit: Math.min(Math.max(limit ?? 20, 1), READ_LIMIT),
107
+ ...(around ? { around } : {}),
108
+ });
109
+ return messages.length > 0
110
+ ? messages.map(messageLine).join("\n")
111
+ : `<#${id}> has no messages there.`;
112
+ }
package/src/index.ts CHANGED
@@ -17,6 +17,15 @@ export type {
17
17
  } from "./core/agents/agent-store.ts";
18
18
  export type { AvatarMode } from "./core/agents/agent-tools.ts";
19
19
  export type { HelpersEnded, HelperTeam } from "./core/agents/helper-ops.ts";
20
+ export {
21
+ type HelperPreset,
22
+ MAX_HELPER_PRESETS,
23
+ type OwnedPreset,
24
+ type PresetOverview,
25
+ type PresetRecruits,
26
+ type PresetSharing,
27
+ type UsablePreset,
28
+ } from "./core/agents/helper-presets.ts";
20
29
  export type { RouteKind, RoutingTable } from "./core/agents/routes.ts";
21
30
  export {
22
31
  agentRoomKey,