pi-roundtable-coding 0.38.1 → 0.39.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,18 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.39.1] - 2026-11-08
6
+
7
+ ### Fixed
8
+
9
+ - With `settingsInDatabase: true` the stored worker limit is read when the coding-desk service starts, not during setup, so `Roundtable.check()` (which refuses a database query in setup) passes and the host boots.
10
+
11
+ ## [0.39.0] - 2026-11-08
12
+
13
+ ### Added
14
+
15
+ - The owner sets the coding workers' host-wide limit on the web app's Settings page ("Coding workers", owner only), which shows the running and queued counts; a save applies at once. `CodingDesk.setMaxWorkers(n)` (1 to 64) starts queued tasks in order when raised and lets running workers finish when lowered; `CodingDesk.workers()` reads the counts. With `settingsInDatabase: true` the limit is kept in the `coding_settings` table and wins over `maxWorkers` at setup; `CODING_SETTINGS_MIGRATION` lets a host that wraps `coding()` declare its migration. `maxWorkers` now refuses more than 64. The page ships zh-TW wording, and `presentation.messages` rewords it.
16
+
5
17
  ## [0.38.1] - 2026-11-08
6
18
 
7
19
  - Release in lockstep with pi-roundtable 0.38.1 (a quote in one's own app bubble is readable in every look; a list a model sends as JSON text reaches a tool as the list, so `helper_end` by name works); no package-specific behavior changes.
package/README.md CHANGED
@@ -7,7 +7,7 @@ This package is a reference for the plugin guide's [Helpers for a Pi session of
7
7
  ## Requirements
8
8
 
9
9
  - Bun 1.4.4 or newer on a POSIX host (Linux or macOS).
10
- - pi-roundtable `>=0.38.0 <0.39.0` as a peer dependency; this package uses only its public main, kit and testing entries.
10
+ - pi-roundtable `>=0.39.0 <0.40.0` as a peer dependency; this package uses only its public main, kit and testing entries.
11
11
  - Pi `>=1.0.0 <2`, shared with the host's core dependencies.
12
12
  A core-only host still pinned to Pi 0.99.x must update its Pi dependencies before adding coding, so cross-package extension and session types resolve to one Pi version.
13
13
  - Git, plus GitHub CLI (`gh`) for the default clone implementation.
@@ -107,7 +107,12 @@ A worker that committed nothing leaves no worktree or branch behind.
107
107
  Integrations of one clone run one at a time, and wait for a report or push of it in progress.
108
108
  Reports and pushes refuse a repository only while an integration is changing its clone, not while workers run in their worktrees; the desk also refuses a second concurrent report or push of a repository and new coding tasks for it while one runs.
109
109
 
110
- At most `maxWorkers` workers (default 4) run at once on the host, across repositories and channels.
110
+ At most `maxWorkers` workers (default 4, at most 64) run at once on the host, across repositories and channels.
111
+ The owner can change the limit while the host runs: with the web console registered before this plugin, the owner-only Settings page "Coding workers" (`coding-workers`) shows the limit, the running and queued counts, and saves a new limit at once.
112
+ A higher limit starts queued tasks now, in order; a lower one stops no running worker, and new tasks queue until fewer run.
113
+ With `settingsInDatabase: true` the saved limit is kept in the host database (table `coding_settings`) and wins over `maxWorkers` at the next start; otherwise it lasts until the host stops.
114
+ Hosts call `desk.setMaxWorkers(n)` for the same change in code, and `desk.workers()` reads `{ max, running, queued }`.
115
+ The page has built-in zh-TW wording for a zh-TW host; `presentation.messages`, keyed by the English text, words it otherwise.
111
116
  Past that a task waits in a first-in, first-out queue of at most `maxQueued` tasks (default 16), and `repo_task` answers at once with its queue position; one more is refused.
112
117
  A queued task starts when a worker slot frees.
113
118
  On host stop queued tasks are dropped and each gets a report saying it never ran; the shutdown drain waits only for running workers.
@@ -222,7 +227,8 @@ The `CODING` service exposes `shelf: RepoShelf` and `desk: CodingDesk` for trust
222
227
  | `workerEnv` | `{}` | `{ pass? }`: more host variables the worker process gets for its model, beyond its `models.json` `$VAR`s, `CLAUDE_*` and `ANTHROPIC_*`; the worker's shell never gets them. |
223
228
  | `githubToken` | host `GH_TOKEN`, read at setup | A string, or a function read at each call, given as `GH_TOKEN` to the shelf's git and gh calls only (clone, fetch, push); a function returning undefined leaves gh to its own login. |
224
229
  | `timeoutMs` | `3600000` | Work-time limit in ms, excluding owner wait; 0 < value <= 2147483647. |
225
- | `maxWorkers` | `4` | Workers running at once on the host; a whole number of at least 1. |
230
+ | `maxWorkers` | `4` | Workers running at once on the host; a whole number from 1 to 64. The owner can change it in Settings, and with `settingsInDatabase` a stored value wins over this one. |
231
+ | `settingsInDatabase` | `false` | Keep the owner's worker limit in the host database (table `coding_settings`, migration `coding/settings`); needs a configured database. A host that wraps `coding()` in its own plugin declares `CODING_SETTINGS_MIGRATION` itself. |
226
232
  | `maxQueued` | `16` | Tasks waiting for a worker slot; a whole number of at least 0. |
227
233
  | `modes` | none | The host's conversation modes (`peek`, optional `autoApproved`), for workers to follow their starter's yolo and long-running modes. |
228
234
  | `autonomy` | `{ yolo: { allow: [], card: [] }, longRunningMaxMs: 14400000 }` | The host's resolved autonomy limits those modes follow. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-roundtable-coding",
3
- "version": "0.38.1",
3
+ "version": "0.39.1",
4
4
  "description": "Repository shelves and owner-approved Pi coding workers for pi-roundtable",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -38,13 +38,13 @@
38
38
  "typebox": "1.3.37"
39
39
  },
40
40
  "peerDependencies": {
41
- "pi-roundtable": ">=0.38.0 <0.39.0"
41
+ "pi-roundtable": ">=0.39.0 <0.40.0"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@earendil-works/pi-ai": ">=1.0.0 <2",
45
45
  "@biomejs/biome": "2.5.15",
46
46
  "@types/bun": "1.4.3",
47
- "pi-roundtable": "0.38.1",
47
+ "pi-roundtable": "0.39.1",
48
48
  "typescript": "7.0.2"
49
49
  }
50
50
  }
@@ -21,6 +21,7 @@ import {
21
21
  workTimeout,
22
22
  YOLO_CARDED_SHELL_CLASSES,
23
23
  } from "pi-roundtable/kit";
24
+ import { checkCount, checkMaxWorkers, checkTime } from "./limits.ts";
24
25
  import type {
25
26
  Integration,
26
27
  RepoShelf,
@@ -29,6 +30,8 @@ import type {
29
30
  } from "./repo-shelf.ts";
30
31
  import { CodingWorkerFailure } from "./worker-failure.ts";
31
32
 
33
+ export { checkLimit } from "./limits.ts";
34
+
32
35
  export type HeldCallAnswer = "approved" | "declined" | "held";
33
36
  /** Who spoke the turn that started a job, as yolo and long-running modes need to know. */
34
37
  export interface CodingSpeaker {
@@ -167,16 +170,6 @@ export interface CodingLimits {
167
170
  /** Longest held-action entry; default 1,000 characters. */
168
171
  heldChars?: number;
169
172
  }
170
- export function checkLimit(name: string, value: number | undefined): void {
171
- if (
172
- value !== undefined &&
173
- value !== Number.POSITIVE_INFINITY &&
174
- (!Number.isSafeInteger(value) || value < 1)
175
- )
176
- throw new Error(
177
- `${name} must be a whole number of at least 1, or Infinity; got ${value}.`,
178
- );
179
- }
180
173
  export const MAX_CODING_TASK_CHARS = 8_000;
181
174
  const MAX_REPORT_CHARS = 20_000;
182
175
  const MAX_HELD_ENTRIES = 10;
@@ -193,23 +186,9 @@ const DEFAULT_TIMEOUT_MS = 3_600_000;
193
186
  const DEFAULT_LONG_RUNNING_MS = 4 * 60 * 60_000;
194
187
  /** How often a run past its own limit looks again at the starter's long-running mode. */
195
188
  const LONG_RUNNING_STEP_MS = 60_000;
196
- const MAX_TIMER_MS = 2_147_483_647;
197
189
  const DEFAULT_MAX_WORKERS = 4;
198
190
  const DEFAULT_MAX_QUEUED = 16;
199
191
 
200
- function checkTime(name: string, value: number): void {
201
- if (!Number.isFinite(value) || value <= 0 || value > MAX_TIMER_MS)
202
- throw new AgentError(
203
- `${name} must be positive, finite and at most ${MAX_TIMER_MS}.`,
204
- );
205
- }
206
- function checkCount(name: string, value: number, least: number): void {
207
- if (!Number.isSafeInteger(value) || value < least)
208
- throw new AgentError(
209
- `${name} must be a whole number of at least ${least}; got ${value}.`,
210
- );
211
- }
212
-
213
192
  /** The rule a class belongs to: the part before its first dot, or a rule's bare name. */
214
193
  function ruleOf(id: string): string {
215
194
  const dot = id.indexOf(".");
@@ -229,7 +208,7 @@ interface Running {
229
208
  */
230
209
  export class CodingDesk {
231
210
  readonly #options: CodingDeskOptions;
232
- readonly #maxWorkers: number;
211
+ #maxWorkers: number;
233
212
  readonly #maxQueued: number;
234
213
  readonly #longRunningMs: number;
235
214
  readonly #yoloApproves: (id: string) => boolean;
@@ -252,7 +231,7 @@ export class CodingDesk {
252
231
  checkTime("autonomy.longRunningMaxMs", longRunning);
253
232
  this.#maxWorkers = options.maxWorkers ?? DEFAULT_MAX_WORKERS;
254
233
  this.#maxQueued = options.maxQueued ?? DEFAULT_MAX_QUEUED;
255
- checkCount("maxWorkers", this.#maxWorkers, 1);
234
+ checkMaxWorkers(this.#maxWorkers);
256
235
  checkCount("maxQueued", this.#maxQueued, 0);
257
236
  this.#longRunningMs = longRunning;
258
237
  const allow = new Set(options.autonomy?.yolo?.allow ?? []);
@@ -274,6 +253,20 @@ export class CodingDesk {
274
253
  queuedChannels(): ChannelKey[] {
275
254
  return this.#queue.map((job) => job.channel);
276
255
  }
256
+ /** Workers allowed at once, and how many run and wait now. */
257
+ workers(): { max: number; running: number; queued: number } {
258
+ const { size: running } = this.#running;
259
+ return { max: this.#maxWorkers, running, queued: this.#queue.length };
260
+ }
261
+ /**
262
+ * Changes how many workers run at once, 1 to 64. A higher limit starts queued tasks now, in
263
+ * order; a lower one stops no running worker, and new tasks queue until fewer run.
264
+ */
265
+ setMaxWorkers(max: number): void {
266
+ checkMaxWorkers(max);
267
+ this.#maxWorkers = max;
268
+ this.#fill();
269
+ }
277
270
  busy(): string[] {
278
271
  return [
279
272
  ...[...this.#running.values()].map(
@@ -382,6 +375,9 @@ export class CodingDesk {
382
375
  /** Frees the job's slot and starts the next queued tasks. */
383
376
  #free(job: CodingJob): void {
384
377
  this.#running.delete(job.id);
378
+ this.#fill();
379
+ }
380
+ #fill(): void {
385
381
  while (
386
382
  !this.#stopped &&
387
383
  this.#running.size < this.#maxWorkers &&
@@ -0,0 +1,151 @@
1
+ import type {
2
+ ChannelKey,
3
+ HoldCheck,
4
+ InterimTextMode,
5
+ ThinkingLevel,
6
+ ToolTurn,
7
+ } from "pi-roundtable";
8
+ import type { DispatchThreads } from "pi-roundtable/kit";
9
+ import type {
10
+ CodingAutonomy,
11
+ CodingJob,
12
+ CodingLimits,
13
+ CodingModes,
14
+ CodingResult,
15
+ CodingThreadText,
16
+ CodingWorker,
17
+ } from "./coding-desk.ts";
18
+ import type { WorkerEnv } from "./pi-coding-worker.ts";
19
+ import type {
20
+ ChangeReport,
21
+ CloneCommand,
22
+ GithubToken,
23
+ RepoSummary,
24
+ } from "./repo-shelf.ts";
25
+
26
+ export interface CodingRun {
27
+ model: string;
28
+ thinking: ThinkingLevel;
29
+ channel: ChannelKey;
30
+ origin?: ChannelKey;
31
+ }
32
+ export type RepoToolName =
33
+ | "repo_list"
34
+ | "repo_add"
35
+ | "repo_change_report"
36
+ | "repo_push"
37
+ | "repo_task";
38
+ /** Trusted wording of one repository tool, as the model reads it; unset fields keep the defaults. */
39
+ export interface CodingToolText {
40
+ description?: string;
41
+ /** Argument descriptions by argument name. */
42
+ parameters?: Record<string, string>;
43
+ }
44
+ export interface CodingPresentation {
45
+ /** The repo_list result; unset: the managed clones as JSON. */
46
+ list?(
47
+ repos: (RepoSummary & { skills: string[] })[],
48
+ context: { shelfDir: string; fetched: boolean },
49
+ ): string;
50
+ /** Separate the owner's posted record from the model's shipping instructions. */
51
+ changeReport?(
52
+ report: ChangeReport,
53
+ direct: boolean,
54
+ ): { post: string; result: string };
55
+ taskStarted?(job: CodingJob, skippedSkills: string[]): string;
56
+ /** The repo_task result for a task waiting for a worker slot, at `position` (from 1) in the queue. */
57
+ /**
58
+ * Wording of the Settings page, keyed by its English text, such as
59
+ * `{ "Coding workers": "..." }`; it wins over the built-in zh-TW wording, key by key.
60
+ */
61
+ messages?: Readonly<Record<string, string>>;
62
+ taskQueued?(
63
+ job: CodingJob,
64
+ position: number,
65
+ skippedSkills: string[],
66
+ ): string;
67
+ }
68
+ export interface CodingOptions {
69
+ shelfDir: string;
70
+ /** Provider/model-id, resolved with the worker's Pi host login. */
71
+ model: string;
72
+ thinking?: ThinkingLevel;
73
+ /** Exact owner/repo names allowed to use repo_push without a hold. Default: none. */
74
+ ownerRepos?: string[];
75
+ /** Trusted host policy for additional owner-owned repositories, including future clones.
76
+ * Only literal true grants an exemption. This never bypasses linked host hold rules. */
77
+ isOwnerRepo?: (repo: string) => boolean;
78
+ /** Trusted wording for the approval card of a held `repo_push`. Default: names the repository, sha, target and branch. */
79
+ pushHoldText?: (repo: string, sha: string) => string;
80
+ /** Moves legacy standalone clones before the host reads shelf-linked skills. */
81
+ adoptClones?: { from: string; repo: string }[];
82
+ /** Resolve the calling agent/owner's run identity, independently of report posting. */
83
+ resolveRun?: (turn: ToolTurn) => CodingRun | Promise<CodingRun>;
84
+ /** Post change reports in the caller's identity/channel rather than the default surface. */
85
+ postChangeReport?: (turn: ToolTurn, text: string) => Promise<void>;
86
+ presentation?: CodingPresentation;
87
+ /** Trusted wording of the repository tools' descriptions and arguments. */
88
+ toolText?: Partial<Record<RepoToolName, CodingToolText>>;
89
+ threads?: Pick<DispatchThreads, "open">;
90
+ threadText?: CodingThreadText;
91
+ /**
92
+ * Whether a worker posts its progress into its thread as it goes: longer text as messages, short
93
+ * narration and its tools in one edited small-text message. Default "on"; "off" posts only the
94
+ * task and the report. Pass the host config's `interimText` to follow it.
95
+ */
96
+ interimText?: InterimTextMode;
97
+ /** Length from which a worker's intermediate text is its own message; default 400. */
98
+ interimPrimaryChars?: number;
99
+ workerWorkspace?: string;
100
+ workerPrompt?: (dir: string) => string;
101
+ /** How much of a long run a report keeps; see `CodingLimits`. */
102
+ limits?: CodingLimits;
103
+ /** Longest git, gh and worker error text kept in a failure, in characters; default 600. */
104
+ diagnosticChars?: number;
105
+ /** Trusted wording of what the worker reads when a call is declined or held; see `PiCodingWorkerOptions.blockText`. */
106
+ workerBlockText?: (answer: "declined" | "held", action: string) => string;
107
+ /** Opt in to skipping unavailable implicit skills; explicit requests always fail closed. */
108
+ skipUnavailableCarriedSkills?: boolean;
109
+ /** Absolute installed extension package paths. Default: none. */
110
+ workerPackages?: string[];
111
+ agentDir?: string;
112
+ /**
113
+ * More host variables the worker process gets for its model, by name; its shell never gets them.
114
+ * Without it the worker already gets the shell's whitelist, `PI_CODING_AGENT_DIR`, the `$VAR`s
115
+ * its agent dir's `models.json` names, and `CLAUDE_*` and `ANTHROPIC_*`.
116
+ */
117
+ workerEnv?: WorkerEnv;
118
+ /**
119
+ * The token git and gh calls of the shelf (clone, fetch, push) get as GH_TOKEN, or a function
120
+ * read at each call; no other host secret reaches them. Default: the host's GH_TOKEN, read when
121
+ * the plugin sets up.
122
+ */
123
+ githubToken?: GithubToken;
124
+ timeoutMs?: number;
125
+ /** Workers running at once on the host, 1 to 64; default 4. More tasks wait in a queue. */
126
+ maxWorkers?: number;
127
+ /**
128
+ * Keep the owner's worker limit, set on the web app's Settings page, in the host database
129
+ * (table `coding_settings`), where it wins over `maxWorkers` at the next start; needs a
130
+ * database. Default false: a change lasts until the host stops.
131
+ */
132
+ settingsInDatabase?: boolean;
133
+ /** Tasks waiting for a worker slot, first in first out; one more is refused. Default 16. */
134
+ maxQueued?: number;
135
+ /**
136
+ * The conversations' modes, such as `context.services.find(MODES)`: a worker then follows the
137
+ * yolo and long-running modes of the conversation whose owner turn started it, read live.
138
+ * Without them a worker asks a card for every held call and stops at `timeoutMs`.
139
+ */
140
+ modes?: CodingModes;
141
+ /** The host's resolved `autonomy` limits, which the worker's yolo and long-running modes follow. */
142
+ autonomy?: CodingAutonomy;
143
+ /** Optional additional worker rules; linked host rules also apply. */
144
+ holds?: HoldCheck;
145
+ /** A different Git host or an offline clone implementation. */
146
+ clone?: CloneCommand;
147
+ /** Replace the process runner for deterministic tests. */
148
+ worker?: CodingWorker;
149
+ /** Override report delivery, for example to schedule a background conversation turn. */
150
+ onResult?: (result: CodingResult) => Promise<void>;
151
+ }
@@ -2,197 +2,52 @@ import {
2
2
  type ChannelKey,
3
3
  definePlugin,
4
4
  defineTool,
5
- type HoldCheck,
6
5
  IDENTITY,
7
- type InterimTextMode,
8
6
  PluginError,
9
7
  SKILLS,
10
8
  SYSTEM_PRINCIPAL,
11
9
  serviceKey,
12
- type ThinkingLevel,
13
10
  ToolRefusal,
14
- type ToolTurn,
15
11
  } from "pi-roundtable";
16
12
  import {
17
13
  AgentError,
18
14
  checkRepoName,
19
- type DispatchThreads,
20
15
  skillListExtension,
21
16
  zonedStamp,
22
17
  } from "pi-roundtable/kit";
23
18
  import { Type } from "typebox";
24
19
  import {
25
- type CodingAutonomy,
26
20
  CodingDesk,
27
- type CodingJob,
28
- type CodingLimits,
29
- type CodingModes,
30
- type CodingResult,
31
- type CodingThreadText,
32
- type CodingWorker,
33
21
  checkLimit,
34
22
  codingReport,
35
23
  MAX_CODING_TASK_CHARS,
36
24
  } from "./coding-desk.ts";
37
- import { PiCodingWorker, type WorkerEnv } from "./pi-coding-worker.ts";
25
+ import type { CodingOptions, RepoToolName } from "./coding-options.ts";
38
26
  import {
39
- type ChangeReport,
40
- type CloneCommand,
41
- type GithubToken,
42
- RepoShelf,
43
- type RepoSummary,
44
- reportPost,
45
- } from "./repo-shelf.ts";
27
+ applyStoredLimit,
28
+ CODING_SETTINGS_MIGRATION,
29
+ databaseSettings,
30
+ memorySettings,
31
+ registerSettingsPage,
32
+ } from "./coding-settings.ts";
33
+ import { checkCount, checkMaxWorkers } from "./limits.ts";
34
+ import { PiCodingWorker } from "./pi-coding-worker.ts";
35
+ import { RepoShelf, reportPost } from "./repo-shelf.ts";
36
+ import { workerHolds } from "./worker-holds.ts";
37
+
38
+ export type {
39
+ CodingOptions,
40
+ CodingPresentation,
41
+ CodingRun,
42
+ CodingToolText,
43
+ RepoToolName,
44
+ } from "./coding-options.ts";
46
45
 
47
46
  export interface CodingService {
48
47
  readonly shelf: RepoShelf;
49
48
  readonly desk: CodingDesk;
50
49
  }
51
50
  export const CODING = serviceKey<CodingService>("coding.workbench");
52
- export interface CodingRun {
53
- model: string;
54
- thinking: ThinkingLevel;
55
- channel: ChannelKey;
56
- origin?: ChannelKey;
57
- }
58
- export type RepoToolName =
59
- | "repo_list"
60
- | "repo_add"
61
- | "repo_change_report"
62
- | "repo_push"
63
- | "repo_task";
64
- /** Trusted wording of one repository tool, as the model reads it; unset fields keep the defaults. */
65
- export interface CodingToolText {
66
- description?: string;
67
- /** Argument descriptions by argument name. */
68
- parameters?: Record<string, string>;
69
- }
70
- export interface CodingPresentation {
71
- /** The repo_list result; unset: the managed clones as JSON. */
72
- list?(
73
- repos: (RepoSummary & { skills: string[] })[],
74
- context: { shelfDir: string; fetched: boolean },
75
- ): string;
76
- /** Separate the owner's posted record from the model's shipping instructions. */
77
- changeReport?(
78
- report: ChangeReport,
79
- direct: boolean,
80
- ): { post: string; result: string };
81
- taskStarted?(job: CodingJob, skippedSkills: string[]): string;
82
- /** The repo_task result for a task waiting for a worker slot, at `position` (from 1) in the queue. */
83
- taskQueued?(
84
- job: CodingJob,
85
- position: number,
86
- skippedSkills: string[],
87
- ): string;
88
- }
89
- export interface CodingOptions {
90
- shelfDir: string;
91
- /** Provider/model-id, resolved with the worker's Pi host login. */
92
- model: string;
93
- thinking?: ThinkingLevel;
94
- /** Exact owner/repo names allowed to use repo_push without a hold. Default: none. */
95
- ownerRepos?: string[];
96
- /** Trusted host policy for additional owner-owned repositories, including future clones.
97
- * Only literal true grants an exemption. This never bypasses linked host hold rules. */
98
- isOwnerRepo?: (repo: string) => boolean;
99
- /** Trusted wording for the approval card of a held `repo_push`. Default: names the repository, sha, target and branch. */
100
- pushHoldText?: (repo: string, sha: string) => string;
101
- /** Moves legacy standalone clones before the host reads shelf-linked skills. */
102
- adoptClones?: { from: string; repo: string }[];
103
- /** Resolve the calling agent/owner's run identity, independently of report posting. */
104
- resolveRun?: (turn: ToolTurn) => CodingRun | Promise<CodingRun>;
105
- /** Post change reports in the caller's identity/channel rather than the default surface. */
106
- postChangeReport?: (turn: ToolTurn, text: string) => Promise<void>;
107
- presentation?: CodingPresentation;
108
- /** Trusted wording of the repository tools' descriptions and arguments. */
109
- toolText?: Partial<Record<RepoToolName, CodingToolText>>;
110
- threads?: Pick<DispatchThreads, "open">;
111
- threadText?: CodingThreadText;
112
- /**
113
- * Whether a worker posts its progress into its thread as it goes: longer text as messages, short
114
- * narration and its tools in one edited small-text message. Default "on"; "off" posts only the
115
- * task and the report. Pass the host config's `interimText` to follow it.
116
- */
117
- interimText?: InterimTextMode;
118
- /** Length from which a worker's intermediate text is its own message; default 400. */
119
- interimPrimaryChars?: number;
120
- workerWorkspace?: string;
121
- workerPrompt?: (dir: string) => string;
122
- /** How much of a long run a report keeps; see `CodingLimits`. */
123
- limits?: CodingLimits;
124
- /** Longest git, gh and worker error text kept in a failure, in characters; default 600. */
125
- diagnosticChars?: number;
126
- /** Trusted wording of what the worker reads when a call is declined or held; see `PiCodingWorkerOptions.blockText`. */
127
- workerBlockText?: (answer: "declined" | "held", action: string) => string;
128
- /** Opt in to skipping unavailable implicit skills; explicit requests always fail closed. */
129
- skipUnavailableCarriedSkills?: boolean;
130
- /** Absolute installed extension package paths. Default: none. */
131
- workerPackages?: string[];
132
- agentDir?: string;
133
- /**
134
- * More host variables the worker process gets for its model, by name; its shell never gets them.
135
- * Without it the worker already gets the shell's whitelist, `PI_CODING_AGENT_DIR`, the `$VAR`s
136
- * its agent dir's `models.json` names, and `CLAUDE_*` and `ANTHROPIC_*`.
137
- */
138
- workerEnv?: WorkerEnv;
139
- /**
140
- * The token git and gh calls of the shelf (clone, fetch, push) get as GH_TOKEN, or a function
141
- * read at each call; no other host secret reaches them. Default: the host's GH_TOKEN, read when
142
- * the plugin sets up.
143
- */
144
- githubToken?: GithubToken;
145
- timeoutMs?: number;
146
- /** Workers running at once on the host; default 4. More tasks wait in a queue. */
147
- maxWorkers?: number;
148
- /** Tasks waiting for a worker slot, first in first out; one more is refused. Default 16. */
149
- maxQueued?: number;
150
- /**
151
- * The conversations' modes, such as `context.services.find(MODES)`: a worker then follows the
152
- * yolo and long-running modes of the conversation whose owner turn started it, read live.
153
- * Without them a worker asks a card for every held call and stops at `timeoutMs`.
154
- */
155
- modes?: CodingModes;
156
- /** The host's resolved `autonomy` limits, which the worker's yolo and long-running modes follow. */
157
- autonomy?: CodingAutonomy;
158
- /** Optional additional worker rules; linked host rules also apply. */
159
- holds?: HoldCheck;
160
- /** A different Git host or an offline clone implementation. */
161
- clone?: CloneCommand;
162
- /** Replace the process runner for deterministic tests. */
163
- worker?: CodingWorker;
164
- /** Override report delivery, for example to schedule a background conversation turn. */
165
- onResult?: (result: CodingResult) => Promise<void>;
166
- }
167
- /**
168
- * The worker's host hold check: the plugin's extra rules, else the linked host rules, with the
169
- * classes of every check that holds a call so yolo mode can judge it; a check that holds a call
170
- * without telling its classes leaves the call unclassed.
171
- */
172
- function workerHolds(
173
- extra: HoldCheck | undefined,
174
- linked: () => HoldCheck,
175
- ): HoldCheck {
176
- const check: HoldCheck = (tool, input, scope) =>
177
- extra?.(tool, input, scope) ?? linked()(tool, input, scope);
178
- check.classesOf = (tool, input, scope) => {
179
- const found: string[] = [];
180
- for (const holds of extra ? [extra, linked()] : [linked()]) {
181
- if (holds(tool, input, scope) === undefined) continue;
182
- const classes = holds.classesOf?.(tool, input, scope);
183
- if (!classes?.length) return undefined;
184
- found.push(...classes);
185
- }
186
- return found.length ? [...new Set(found)] : undefined;
187
- };
188
- return check;
189
- }
190
- function checkCount(name: string, value: number | undefined, least: number) {
191
- if (value !== undefined && (!Number.isSafeInteger(value) || value < least))
192
- throw new Error(
193
- `${name} must be a whole number of at least ${least}; got ${value}.`,
194
- );
195
- }
196
51
  async function refusal<T>(operation: () => Promise<T>): Promise<T> {
197
52
  try {
198
53
  return await operation();
@@ -212,8 +67,9 @@ export function coding(options: CodingOptions) {
212
67
  checkLimit("limits.heldEntries", options.limits?.heldEntries);
213
68
  checkLimit("limits.heldChars", options.limits?.heldChars);
214
69
  checkLimit("diagnosticChars", options.diagnosticChars);
215
- checkCount("maxWorkers", options.maxWorkers, 1);
216
- checkCount("maxQueued", options.maxQueued, 0);
70
+ if (options.maxWorkers !== undefined) checkMaxWorkers(options.maxWorkers);
71
+ if (options.maxQueued !== undefined)
72
+ checkCount("maxQueued", options.maxQueued, 0);
217
73
  const longRunning = options.autonomy?.longRunningMaxMs;
218
74
  if (
219
75
  longRunning !== undefined &&
@@ -240,7 +96,10 @@ export function coding(options: CodingOptions) {
240
96
  // Its workers run shells and edit files on the host's machine.
241
97
  hostAccess: true,
242
98
  provides: [CODING],
243
- setup(context) {
99
+ ...(options.settingsInDatabase
100
+ ? { migrations: [CODING_SETTINGS_MIGRATION] }
101
+ : {}),
102
+ async setup(context) {
244
103
  const shelf = new RepoShelf(options.shelfDir, options.clone, {
245
104
  diagnosticChars: options.diagnosticChars,
246
105
  ...(options.githubToken !== undefined
@@ -303,6 +162,15 @@ export function coding(options: CodingOptions) {
303
162
  const ship = <T>(repo: string, operation: () => Promise<T>) =>
304
163
  desk.ship(repo, operation);
305
164
  context.services.provide(CODING, { shelf, desk });
165
+ const store = options.settingsInDatabase
166
+ ? databaseSettings(context.database())
167
+ : memorySettings();
168
+ registerSettingsPage(
169
+ context,
170
+ desk,
171
+ store,
172
+ options.presentation?.messages,
173
+ );
306
174
  // Whether the principal holds the owner role; no identity service, or a failed lookup,
307
175
  // tells of no one holding it.
308
176
  const holdsOwnerRole = async (
@@ -333,6 +201,8 @@ export function coding(options: CodingOptions) {
333
201
  services: [
334
202
  {
335
203
  name: "coding-desk",
204
+ // The stored limit is read at start: setup must not query the database.
205
+ start: () => applyStoredLimit(store, desk, context.logger),
336
206
  // The host names the channels whose work a shutdown waits for or aborts.
337
207
  busy: () => desk.runningChannels(),
338
208
  stop: () => desk.stop(),
@@ -0,0 +1,242 @@
1
+ import type { SQL } from "bun";
2
+ import {
3
+ type Locale,
4
+ type Logger,
5
+ type Migration,
6
+ type PluginContext,
7
+ type ServiceKey,
8
+ serviceKey,
9
+ type Tier,
10
+ } from "pi-roundtable";
11
+ import type { CodingDesk } from "./coding-desk.ts";
12
+ import { ZH_TW } from "./i18n/zh-tw.ts";
13
+ import { checkMaxWorkers, MAX_WORKERS_LIMIT } from "./limits.ts";
14
+
15
+ /** The owner's coding settings, one row per key; this migration is never edited once released. */
16
+ export const CODING_SETTINGS_MIGRATION: Migration = {
17
+ name: "settings",
18
+ up: async (sql) => {
19
+ await sql`CREATE TABLE IF NOT EXISTS coding_settings (
20
+ key TEXT PRIMARY KEY,
21
+ value TEXT NOT NULL,
22
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
23
+ )`;
24
+ },
25
+ };
26
+
27
+ /** Where the owner's worker limit is kept: the host database, or memory for one run. */
28
+ export interface CodingSettingsStore {
29
+ maxWorkers(): Promise<number | undefined>;
30
+ setMaxWorkers(max: number): Promise<void>;
31
+ }
32
+ export function databaseSettings(sql: SQL): CodingSettingsStore {
33
+ return {
34
+ async maxWorkers() {
35
+ const rows: { value: string }[] =
36
+ await sql`SELECT value FROM coding_settings WHERE key = 'max_workers'`;
37
+ return rows[0] ? Number(rows[0].value) : undefined;
38
+ },
39
+ async setMaxWorkers(max) {
40
+ await sql`INSERT INTO coding_settings (key, value) VALUES ('max_workers', ${String(max)})
41
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()`;
42
+ },
43
+ };
44
+ }
45
+ export function memorySettings(): CodingSettingsStore {
46
+ let stored: number | undefined;
47
+ return {
48
+ maxWorkers: async () => stored,
49
+ setMaxWorkers: async (max) => {
50
+ stored = max;
51
+ },
52
+ };
53
+ }
54
+
55
+ /** Applies a stored limit to the desk; one out of range is logged and the option's stays. */
56
+ export async function applyStoredLimit(
57
+ store: CodingSettingsStore,
58
+ desk: CodingDesk,
59
+ logger: Logger,
60
+ ): Promise<void> {
61
+ const stored = await store.maxWorkers();
62
+ if (stored === undefined) return;
63
+ try {
64
+ desk.setMaxWorkers(stored);
65
+ } catch (error) {
66
+ logger.warn(
67
+ { err: error },
68
+ "the stored coding worker limit is not 1 to 64; the configured one applies",
69
+ );
70
+ }
71
+ }
72
+
73
+ /** The part of the web app's `WEB_APP` service the settings page uses, matched by the service's id. */
74
+ export interface SettingsWebApp {
75
+ registerPage(page: SettingsPage): void;
76
+ readonly pages: { changed(id?: string): void };
77
+ }
78
+ interface SettingsViewer {
79
+ tier: Tier;
80
+ }
81
+ type SettingsResult =
82
+ | { ok: true; notice?: string }
83
+ | { ok: false; error: string; field?: string };
84
+ export interface SettingsPage {
85
+ id: string;
86
+ label: string;
87
+ place: "settings";
88
+ visible(viewer: SettingsViewer): boolean;
89
+ view(viewer: SettingsViewer): Promise<{
90
+ title: string;
91
+ sections: readonly (
92
+ | { kind: "markdown"; text: string }
93
+ | {
94
+ kind: "form";
95
+ action: string;
96
+ form: {
97
+ title: string;
98
+ submit: string;
99
+ fields: {
100
+ name: string;
101
+ label: string;
102
+ type: "text";
103
+ required: boolean;
104
+ max: number;
105
+ initial: string;
106
+ hint: string;
107
+ }[];
108
+ };
109
+ }
110
+ )[];
111
+ }>;
112
+ act(
113
+ viewer: SettingsViewer,
114
+ action: string,
115
+ input: Readonly<Record<string, string | readonly string[]>>,
116
+ ): Promise<SettingsResult>;
117
+ }
118
+ export const WEB_APP: ServiceKey<SettingsWebApp> =
119
+ serviceKey<SettingsWebApp>("roundtable.web.app");
120
+ export const SETTINGS_PAGE_ID = "coding-workers";
121
+
122
+ /** The wording of a locale: zh-TW's catalog, then the host's own entries, both keyed by the English text. */
123
+ export function settingsWording(
124
+ locale: Locale,
125
+ messages: Readonly<Record<string, string>> = {},
126
+ ): (text: string, values?: Record<string, number>) => string {
127
+ const catalog = { ...(locale === "zh-TW" ? ZH_TW : {}), ...messages };
128
+ return (text, values = {}) =>
129
+ (catalog[text] ?? text).replace(/\{(\w+)\}/g, (whole, name: string) =>
130
+ name in values ? String(values[name]) : whole,
131
+ );
132
+ }
133
+
134
+ /** The owner's settings page: how many coding workers run at once, applied and stored on save. */
135
+ export function settingsPage(
136
+ desk: CodingDesk,
137
+ store: CodingSettingsStore,
138
+ t: ReturnType<typeof settingsWording>,
139
+ changed: () => void,
140
+ ): SettingsPage {
141
+ const owner = (viewer: SettingsViewer) => viewer.tier === "owner";
142
+ return {
143
+ id: SETTINGS_PAGE_ID,
144
+ label: t("Coding workers"),
145
+ place: "settings",
146
+ visible: owner,
147
+ view: async () => {
148
+ const { max, running, queued } = desk.workers();
149
+ return {
150
+ title: t("Coding workers"),
151
+ sections: [
152
+ {
153
+ kind: "markdown",
154
+ text: t(
155
+ "At most {max} at once. Running now: {running}. Waiting in the queue: {queued}.",
156
+ { max, running, queued },
157
+ ),
158
+ },
159
+ {
160
+ kind: "form",
161
+ action: "save",
162
+ form: {
163
+ title: t("Worker limit"),
164
+ submit: t("Save"),
165
+ fields: [
166
+ {
167
+ name: "maxWorkers",
168
+ label: t("Coding workers at once"),
169
+ type: "text",
170
+ required: true,
171
+ max: 2,
172
+ initial: String(max),
173
+ hint: t(
174
+ "Shared by every agent and repository, 1 to {most}. Extra tasks wait in a queue. Lowering it lets running workers finish.",
175
+ { most: MAX_WORKERS_LIMIT },
176
+ ),
177
+ },
178
+ ],
179
+ },
180
+ },
181
+ ],
182
+ };
183
+ },
184
+ act: async (viewer, action, input) => {
185
+ if (!owner(viewer))
186
+ return { ok: false, error: t("Only an owner changes this.") };
187
+ if (action !== "save")
188
+ return { ok: false, error: t("This page has no such action.") };
189
+ const text = input.maxWorkers;
190
+ const max =
191
+ typeof text === "string" && /^\d{1,2}$/.test(text.trim())
192
+ ? Number(text.trim())
193
+ : Number.NaN;
194
+ try {
195
+ checkMaxWorkers(max);
196
+ } catch {
197
+ return {
198
+ ok: false,
199
+ field: "maxWorkers",
200
+ error: t("Give a whole number from 1 to {most}.", {
201
+ most: MAX_WORKERS_LIMIT,
202
+ }),
203
+ };
204
+ }
205
+ await store.setMaxWorkers(max);
206
+ desk.setMaxWorkers(max);
207
+ changed();
208
+ return {
209
+ ok: true,
210
+ notice: t("Up to {max} coding workers now run at once.", { max }),
211
+ };
212
+ },
213
+ };
214
+ }
215
+
216
+ /** Registers the settings page when the web app is there; the web app must be registered first. */
217
+ export function registerSettingsPage(
218
+ context: Pick<PluginContext, "services" | "logger" | "env">,
219
+ desk: CodingDesk,
220
+ store: CodingSettingsStore,
221
+ messages?: Readonly<Record<string, string>>,
222
+ ): void {
223
+ let web: SettingsWebApp | undefined;
224
+ try {
225
+ web = context.services.find(WEB_APP);
226
+ } catch (error) {
227
+ context.logger.warn(
228
+ { err: error },
229
+ "register the coding plugin after web-console to get its Settings page",
230
+ );
231
+ }
232
+ if (!web) return;
233
+ const app = web;
234
+ app.registerPage(
235
+ settingsPage(
236
+ desk,
237
+ store,
238
+ settingsWording(context.env.locale, messages),
239
+ () => app.pages.changed(SETTINGS_PAGE_ID),
240
+ ),
241
+ );
242
+ }
@@ -0,0 +1,16 @@
1
+ /** The coding plugin's Traditional Chinese (Taiwan) wording, keyed by the English text; a host's `presentation.messages` wins, key by key. */
2
+ export const ZH_TW: Readonly<Record<string, string>> = {
3
+ "Coding workers": "程式工作者",
4
+ "At most {max} at once. Running now: {running}. Waiting in the queue: {queued}.":
5
+ "同時最多 {max} 個。執行中:{running}。排隊等候:{queued}。",
6
+ "Worker limit": "工作者上限",
7
+ Save: "儲存",
8
+ "Coding workers at once": "同時執行的程式工作者",
9
+ "Shared by every agent and repository, 1 to {most}. Extra tasks wait in a queue. Lowering it lets running workers finish.":
10
+ "所有代理與儲存庫共用,可設 1 到 {most}。超出的任務會排隊等候。調低時,執行中的工作者會先做完。",
11
+ "Only an owner changes this.": "只有擁有者能變更這項設定。",
12
+ "This page has no such action.": "這個頁面沒有這個動作。",
13
+ "Give a whole number from 1 to {most}.": "請輸入 1 到 {most} 的整數。",
14
+ "Up to {max} coding workers now run at once.":
15
+ "現在同時最多執行 {max} 個程式工作者。",
16
+ };
package/src/index.ts CHANGED
@@ -18,11 +18,12 @@ export type {
18
18
  CodingOptions,
19
19
  CodingPresentation,
20
20
  CodingRun,
21
- CodingService,
22
21
  CodingToolText,
23
22
  RepoToolName,
24
- } from "./coding-plugin.ts";
23
+ } from "./coding-options.ts";
24
+ export type { CodingService } from "./coding-plugin.ts";
25
25
  export { CODING, coding } from "./coding-plugin.ts";
26
+ export { CODING_SETTINGS_MIGRATION } from "./coding-settings.ts";
26
27
  export type { PiCodingWorkerOptions, WorkerEnv } from "./pi-coding-worker.ts";
27
28
  export { modelEnvNames, PiCodingWorker } from "./pi-coding-worker.ts";
28
29
  export type {
package/src/limits.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { AgentError } from "pi-roundtable/kit";
2
+
3
+ const MAX_TIMER_MS = 2_147_483_647;
4
+ /** The most coding workers a host may run at once. */
5
+ export const MAX_WORKERS_LIMIT = 64;
6
+
7
+ export function checkLimit(name: string, value: number | undefined): void {
8
+ if (
9
+ value !== undefined &&
10
+ value !== Number.POSITIVE_INFINITY &&
11
+ (!Number.isSafeInteger(value) || value < 1)
12
+ )
13
+ throw new Error(
14
+ `${name} must be a whole number of at least 1, or Infinity; got ${value}.`,
15
+ );
16
+ }
17
+ export function checkTime(name: string, value: number): void {
18
+ if (!Number.isFinite(value) || value <= 0 || value > MAX_TIMER_MS)
19
+ throw new AgentError(
20
+ `${name} must be positive, finite and at most ${MAX_TIMER_MS}.`,
21
+ );
22
+ }
23
+ export function checkCount(
24
+ name: string,
25
+ value: number,
26
+ least: number,
27
+ most = Number.MAX_SAFE_INTEGER,
28
+ ): void {
29
+ if (!Number.isSafeInteger(value) || value < least || value > most)
30
+ throw new AgentError(
31
+ most === Number.MAX_SAFE_INTEGER
32
+ ? `${name} must be a whole number of at least ${least}; got ${value}.`
33
+ : `${name} must be a whole number from ${least} to ${most}; got ${value}.`,
34
+ );
35
+ }
36
+ /** Throws unless `value` is a worker limit: a whole number from 1 to 64. */
37
+ export function checkMaxWorkers(value: number): void {
38
+ checkCount("maxWorkers", value, 1, MAX_WORKERS_LIMIT);
39
+ }
@@ -0,0 +1,25 @@
1
+ import type { HoldCheck } from "pi-roundtable";
2
+
3
+ /**
4
+ * The worker's host hold check: the plugin's extra rules, else the linked host rules, with the
5
+ * classes of every check that holds a call so yolo mode can judge it; a check that holds a call
6
+ * without telling its classes leaves the call unclassed.
7
+ */
8
+ export function workerHolds(
9
+ extra: HoldCheck | undefined,
10
+ linked: () => HoldCheck,
11
+ ): HoldCheck {
12
+ const check: HoldCheck = (tool, input, scope) =>
13
+ extra?.(tool, input, scope) ?? linked()(tool, input, scope);
14
+ check.classesOf = (tool, input, scope) => {
15
+ const found: string[] = [];
16
+ for (const holds of extra ? [extra, linked()] : [linked()]) {
17
+ if (holds(tool, input, scope) === undefined) continue;
18
+ const classes = holds.classesOf?.(tool, input, scope);
19
+ if (!classes?.length) return undefined;
20
+ found.push(...classes);
21
+ }
22
+ return found.length ? [...new Set(found)] : undefined;
23
+ };
24
+ return check;
25
+ }