@esso0428/pi-subagents 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +638 -0
  2. package/CONTRIBUTING.md +68 -0
  3. package/LICENSE +21 -0
  4. package/README.md +745 -0
  5. package/SECURITY.md +95 -0
  6. package/dist/agent-manager.d.ts +144 -0
  7. package/dist/agent-manager.js +542 -0
  8. package/dist/agent-runner.d.ts +212 -0
  9. package/dist/agent-runner.js +850 -0
  10. package/dist/agent-types.d.ts +67 -0
  11. package/dist/agent-types.js +168 -0
  12. package/dist/context.d.ts +12 -0
  13. package/dist/context.js +56 -0
  14. package/dist/cross-extension-rpc.d.ts +46 -0
  15. package/dist/cross-extension-rpc.js +76 -0
  16. package/dist/custom-agents.d.ts +17 -0
  17. package/dist/custom-agents.js +156 -0
  18. package/dist/default-agents.d.ts +7 -0
  19. package/dist/default-agents.js +122 -0
  20. package/dist/enabled-models.d.ts +49 -0
  21. package/dist/enabled-models.js +145 -0
  22. package/dist/env.d.ts +6 -0
  23. package/dist/env.js +28 -0
  24. package/dist/group-join.d.ts +32 -0
  25. package/dist/group-join.js +116 -0
  26. package/dist/index.d.ts +16 -0
  27. package/dist/index.js +2209 -0
  28. package/dist/invocation-config.d.ts +22 -0
  29. package/dist/invocation-config.js +15 -0
  30. package/dist/memory.d.ts +53 -0
  31. package/dist/memory.js +165 -0
  32. package/dist/model-resolver.d.ts +19 -0
  33. package/dist/model-resolver.js +80 -0
  34. package/dist/nico-overrides.d.ts +53 -0
  35. package/dist/nico-overrides.js +169 -0
  36. package/dist/output-file.d.ts +24 -0
  37. package/dist/output-file.js +101 -0
  38. package/dist/prompts.d.ts +32 -0
  39. package/dist/prompts.js +73 -0
  40. package/dist/schedule-store.d.ts +38 -0
  41. package/dist/schedule-store.js +155 -0
  42. package/dist/schedule.d.ts +109 -0
  43. package/dist/schedule.js +338 -0
  44. package/dist/settings.d.ts +141 -0
  45. package/dist/settings.js +162 -0
  46. package/dist/skill-loader.d.ts +24 -0
  47. package/dist/skill-loader.js +93 -0
  48. package/dist/status-note.d.ts +13 -0
  49. package/dist/status-note.js +24 -0
  50. package/dist/types.d.ts +197 -0
  51. package/dist/types.js +5 -0
  52. package/dist/ui/agent-widget.d.ts +160 -0
  53. package/dist/ui/agent-widget.js +484 -0
  54. package/dist/ui/conversation-viewer.d.ts +57 -0
  55. package/dist/ui/conversation-viewer.js +354 -0
  56. package/dist/ui/fleet-list.d.ts +106 -0
  57. package/dist/ui/fleet-list.js +345 -0
  58. package/dist/ui/schedule-menu.d.ts +16 -0
  59. package/dist/ui/schedule-menu.js +95 -0
  60. package/dist/ui/viewer-keys.d.ts +20 -0
  61. package/dist/ui/viewer-keys.js +17 -0
  62. package/dist/usage.d.ts +50 -0
  63. package/dist/usage.js +49 -0
  64. package/dist/worktree.d.ts +45 -0
  65. package/dist/worktree.js +160 -0
  66. package/examples/agent-tool-description.md +42 -0
  67. package/package.json +56 -0
  68. package/src/agent-manager.ts +631 -0
  69. package/src/agent-runner.ts +1014 -0
  70. package/src/agent-types.ts +202 -0
  71. package/src/context.ts +58 -0
  72. package/src/cross-extension-rpc.ts +122 -0
  73. package/src/custom-agents.ts +167 -0
  74. package/src/default-agents.ts +126 -0
  75. package/src/enabled-models.ts +180 -0
  76. package/src/env.ts +33 -0
  77. package/src/group-join.ts +141 -0
  78. package/src/index.ts +2400 -0
  79. package/src/invocation-config.ts +40 -0
  80. package/src/memory.ts +179 -0
  81. package/src/model-resolver.ts +100 -0
  82. package/src/nico-overrides.ts +235 -0
  83. package/src/output-file.ts +110 -0
  84. package/src/prompts.ts +99 -0
  85. package/src/schedule-store.ts +153 -0
  86. package/src/schedule.ts +365 -0
  87. package/src/settings.ts +288 -0
  88. package/src/skill-loader.ts +102 -0
  89. package/src/status-note.ts +25 -0
  90. package/src/types.ts +208 -0
  91. package/src/ui/agent-widget.ts +566 -0
  92. package/src/ui/conversation-viewer.ts +362 -0
  93. package/src/ui/fleet-list.ts +380 -0
  94. package/src/ui/schedule-menu.ts +104 -0
  95. package/src/ui/viewer-keys.ts +39 -0
  96. package/src/usage.ts +60 -0
  97. package/src/worktree.ts +191 -0
  98. package/vitest.config.ts +18 -0
@@ -0,0 +1,338 @@
1
+ /**
2
+ * schedule.ts — `SubagentScheduler`: timer-driven dispatcher of scheduled subagents.
3
+ *
4
+ * Mirrors the engine shape of pi-cron-schedule/src/scheduler.ts:
5
+ * - two-Map split (jobs = croner Cron, intervals = setInterval/setTimeout)
6
+ * - addJob/removeJob/updateJob/scheduleJob/unscheduleJob/executeJob
7
+ * - static parsers for cron / "+10m" / "5m" / ISO formats
8
+ *
9
+ * Differences vs pi-cron-schedule:
10
+ * - Persistence is via ScheduleStore (PID-locked, session-scoped, atomic).
11
+ * - `executeJob` calls `manager.spawn(..., { bypassQueue: true })` instead
12
+ * of dispatching a user message — schedule fires bypass maxConcurrent so
13
+ * a 5-minute interval can't be deferred behind 4 long-running agents.
14
+ * - Result delivery is implicit: spawn → background completion → existing
15
+ * `subagent-notification` followUp path. No new delivery code.
16
+ */
17
+ import { Cron } from "croner";
18
+ import { nanoid } from "nanoid";
19
+ import { resolveModel } from "./model-resolver.js";
20
+ export class SubagentScheduler {
21
+ jobs = new Map();
22
+ intervals = new Map();
23
+ store;
24
+ pi;
25
+ ctx;
26
+ manager;
27
+ /** Start the scheduler: bind to a session's store and arm enabled jobs. */
28
+ start(pi, ctx, manager, store) {
29
+ this.pi = pi;
30
+ this.ctx = ctx;
31
+ this.manager = manager;
32
+ this.store = store;
33
+ for (const job of store.list()) {
34
+ if (job.enabled)
35
+ this.scheduleJob(job);
36
+ }
37
+ }
38
+ /** Stop all timers; drop refs. Safe to call repeatedly. */
39
+ stop() {
40
+ for (const cron of this.jobs.values())
41
+ cron.stop();
42
+ this.jobs.clear();
43
+ for (const t of this.intervals.values())
44
+ clearTimeout(t);
45
+ this.intervals.clear();
46
+ this.store = undefined;
47
+ this.pi = undefined;
48
+ this.ctx = undefined;
49
+ this.manager = undefined;
50
+ }
51
+ /** True if start() has bound a store and the scheduler is active. */
52
+ isActive() {
53
+ return this.store !== undefined;
54
+ }
55
+ list() {
56
+ return this.store?.list() ?? [];
57
+ }
58
+ /**
59
+ * Build a `ScheduledSubagent` from user input. Validates the schedule
60
+ * format and tags `scheduleType`. Throws on invalid input.
61
+ */
62
+ buildJob(input) {
63
+ const detected = SubagentScheduler.detectSchedule(input.schedule);
64
+ return {
65
+ id: nanoid(10),
66
+ name: input.name,
67
+ description: input.description,
68
+ schedule: detected.normalized,
69
+ scheduleType: detected.type,
70
+ intervalMs: detected.intervalMs,
71
+ subagent_type: input.subagent_type,
72
+ prompt: input.prompt,
73
+ model: input.model,
74
+ thinking: input.thinking,
75
+ max_turns: input.max_turns,
76
+ isolated: input.isolated,
77
+ isolation: input.isolation,
78
+ enabled: true,
79
+ createdAt: new Date().toISOString(),
80
+ runCount: 0,
81
+ };
82
+ }
83
+ /** Add a job, persist, and arm if enabled. Returns the stored job. */
84
+ addJob(input) {
85
+ const store = this.requireStore();
86
+ if (store.hasName(input.name)) {
87
+ throw new Error(`A scheduled job named "${input.name}" already exists.`);
88
+ }
89
+ const job = this.buildJob(input);
90
+ store.add(job);
91
+ if (job.enabled)
92
+ this.scheduleJob(job);
93
+ this.emit({ type: "added", job });
94
+ return job;
95
+ }
96
+ removeJob(id) {
97
+ const store = this.requireStore();
98
+ if (!store.get(id))
99
+ return false;
100
+ this.unscheduleJob(id);
101
+ const ok = store.remove(id);
102
+ if (ok)
103
+ this.emit({ type: "removed", jobId: id });
104
+ return ok;
105
+ }
106
+ /** Toggle / mutate a job. Re-arms based on the new `enabled` state. */
107
+ updateJob(id, patch) {
108
+ const store = this.requireStore();
109
+ const updated = store.update(id, patch);
110
+ if (!updated)
111
+ return undefined;
112
+ this.unscheduleJob(id);
113
+ if (updated.enabled)
114
+ this.scheduleJob(updated);
115
+ this.emit({ type: "updated", job: updated });
116
+ return updated;
117
+ }
118
+ /** Next-run time as ISO, or undefined if not currently armed. */
119
+ getNextRun(jobId) {
120
+ const cron = this.jobs.get(jobId);
121
+ if (cron)
122
+ return cron.nextRun()?.toISOString();
123
+ const job = this.store?.get(jobId);
124
+ if (!job?.enabled)
125
+ return undefined;
126
+ if (job.scheduleType === "once")
127
+ return job.schedule;
128
+ if (job.scheduleType === "interval" && job.intervalMs) {
129
+ // Before the first fire there's no `lastRun`, so fall back to "now" —
130
+ // accurate at create time (setInterval was just armed) and within
131
+ // intervalMs of correct in any pre-first-fire view.
132
+ const base = job.lastRun ? new Date(job.lastRun).getTime() : Date.now();
133
+ return new Date(base + job.intervalMs).toISOString();
134
+ }
135
+ return undefined;
136
+ }
137
+ // ── Scheduling primitives ────────────────────────────────────────────
138
+ scheduleJob(job) {
139
+ const store = this.store;
140
+ if (!store)
141
+ return;
142
+ try {
143
+ if (job.scheduleType === "interval" && job.intervalMs) {
144
+ const t = setInterval(() => this.executeJob(job.id), job.intervalMs);
145
+ this.intervals.set(job.id, t);
146
+ }
147
+ else if (job.scheduleType === "once") {
148
+ const target = new Date(job.schedule).getTime();
149
+ const delay = target - Date.now();
150
+ if (delay > 0) {
151
+ const t = setTimeout(() => {
152
+ this.executeJob(job.id);
153
+ // Auto-disable one-shots after they fire (mirrors pi-cron-schedule)
154
+ store.update(job.id, { enabled: false });
155
+ const updated = store.get(job.id);
156
+ if (updated)
157
+ this.emit({ type: "updated", job: updated });
158
+ }, delay);
159
+ this.intervals.set(job.id, t);
160
+ }
161
+ else {
162
+ // Past timestamp — disable, mark error, never fire
163
+ store.update(job.id, { enabled: false, lastStatus: "error" });
164
+ this.emit({ type: "error", jobId: job.id, error: `Scheduled time ${job.schedule} is in the past` });
165
+ }
166
+ }
167
+ else {
168
+ const cron = new Cron(job.schedule, () => this.executeJob(job.id));
169
+ this.jobs.set(job.id, cron);
170
+ }
171
+ }
172
+ catch (err) {
173
+ this.emit({ type: "error", jobId: job.id, error: err instanceof Error ? err.message : String(err) });
174
+ }
175
+ }
176
+ unscheduleJob(id) {
177
+ const cron = this.jobs.get(id);
178
+ if (cron) {
179
+ cron.stop();
180
+ this.jobs.delete(id);
181
+ }
182
+ const t = this.intervals.get(id);
183
+ if (t) {
184
+ clearTimeout(t);
185
+ clearInterval(t);
186
+ this.intervals.delete(id);
187
+ }
188
+ }
189
+ /**
190
+ * Fire a job: persist running state, spawn (bypassing the concurrency
191
+ * queue), persist completion. Fire-and-forget: the timer tick returns
192
+ * immediately so other jobs keep firing.
193
+ */
194
+ executeJob(id) {
195
+ const store = this.store;
196
+ const pi = this.pi;
197
+ const ctx = this.ctx;
198
+ const manager = this.manager;
199
+ if (!store || !pi || !ctx || !manager)
200
+ return;
201
+ const job = store.get(id);
202
+ if (!job?.enabled)
203
+ return;
204
+ store.update(id, { lastStatus: "running" });
205
+ // Resolve model at fire time — registry contents may have changed since the
206
+ // job was created (auth added/removed). Fall back silently to spawn-default
207
+ // if resolution fails; the spawn path handles undefined model gracefully.
208
+ let resolvedModel;
209
+ if (job.model) {
210
+ const r = resolveModel(job.model, ctx.modelRegistry);
211
+ if (typeof r !== "string")
212
+ resolvedModel = r;
213
+ }
214
+ let agentId;
215
+ try {
216
+ agentId = manager.spawn(pi, ctx, job.subagent_type, job.prompt, {
217
+ description: job.description,
218
+ isBackground: true,
219
+ bypassQueue: true,
220
+ model: resolvedModel,
221
+ maxTurns: job.max_turns,
222
+ isolated: job.isolated,
223
+ thinkingLevel: job.thinking,
224
+ isolation: job.isolation,
225
+ });
226
+ }
227
+ catch (err) {
228
+ const error = err instanceof Error ? err.message : String(err);
229
+ store.update(id, { lastRun: new Date().toISOString(), lastStatus: "error" });
230
+ this.emit({ type: "error", jobId: id, error });
231
+ return;
232
+ }
233
+ this.emit({ type: "fired", jobId: id, agentId, name: job.name });
234
+ const record = manager.getRecord(agentId);
235
+ const finalize = (status) => {
236
+ const next = this.getNextRun(id);
237
+ const current = store.get(id);
238
+ store.update(id, {
239
+ lastRun: new Date().toISOString(),
240
+ lastStatus: status,
241
+ runCount: (current?.runCount ?? 0) + 1,
242
+ nextRun: next,
243
+ });
244
+ };
245
+ // AgentManager's promise resolves either way (its .catch returns ""), so we
246
+ // can't infer success/failure from the promise — read record.status instead.
247
+ // Terminal states: completed/steered = success; error/aborted/stopped = error.
248
+ if (record?.promise) {
249
+ record.promise
250
+ .then(() => {
251
+ const r = manager.getRecord(agentId);
252
+ const failed = r?.status === "error" || r?.status === "aborted" || r?.status === "stopped";
253
+ finalize(failed ? "error" : "success");
254
+ })
255
+ .catch(() => finalize("error"));
256
+ }
257
+ else {
258
+ // Spawn returned without a promise (defensive — bypassQueue path always sets one).
259
+ finalize("success");
260
+ }
261
+ }
262
+ emit(event) {
263
+ if (this.pi)
264
+ this.pi.events.emit("subagents:scheduled", event);
265
+ }
266
+ requireStore() {
267
+ if (!this.store)
268
+ throw new Error("Scheduler not started — no active session.");
269
+ return this.store;
270
+ }
271
+ // ── Format detection / parsers (statics — pure) ──────────────────────
272
+ /**
273
+ * Sniff a schedule string and tag its type. Throws on invalid input.
274
+ * Order matters: relative ("+10m") and interval ("5m") both match digit+unit;
275
+ * relative requires the leading "+" to disambiguate.
276
+ */
277
+ static detectSchedule(s) {
278
+ const trimmed = s.trim();
279
+ // "+10m" — relative one-shot
280
+ const rel = SubagentScheduler.parseRelativeTime(trimmed);
281
+ if (rel !== null)
282
+ return { type: "once", normalized: rel };
283
+ // "5m" — interval
284
+ const ivl = SubagentScheduler.parseInterval(trimmed);
285
+ if (ivl !== null)
286
+ return { type: "interval", intervalMs: ivl, normalized: trimmed };
287
+ // ISO timestamp — one-shot. Reject past timestamps upfront so we never
288
+ // create a dead-on-arrival record (scheduleJob's safety net still catches
289
+ // micro-races from `+0s`-style relatives).
290
+ if (/^\d{4}-\d{2}-\d{2}T/.test(trimmed)) {
291
+ const d = new Date(trimmed);
292
+ if (!Number.isNaN(d.getTime())) {
293
+ if (d.getTime() <= Date.now()) {
294
+ throw new Error(`Scheduled time ${d.toISOString()} is in the past.`);
295
+ }
296
+ return { type: "once", normalized: d.toISOString() };
297
+ }
298
+ }
299
+ // Cron — 6-field
300
+ const cronCheck = SubagentScheduler.validateCronExpression(trimmed);
301
+ if (cronCheck.valid)
302
+ return { type: "cron", normalized: trimmed };
303
+ throw new Error(`Invalid schedule "${s}". Use 6-field cron (e.g. "0 0 9 * * 1" — 9am every Monday), interval ("5m"/"1h"), or one-shot ("+10m" / ISO).`);
304
+ }
305
+ /** 6-field cron — 'second minute hour dom month dow'. */
306
+ static validateCronExpression(expr) {
307
+ const fields = expr.trim().split(/\s+/);
308
+ if (fields.length !== 6) {
309
+ return {
310
+ valid: false,
311
+ error: `Cron must have 6 fields (second minute hour dom month dow), got ${fields.length}. Example: "0 0 9 * * 1" for 9am every Monday.`,
312
+ };
313
+ }
314
+ try {
315
+ // Croner validates by construction.
316
+ new Cron(expr, () => { });
317
+ return { valid: true };
318
+ }
319
+ catch (e) {
320
+ return { valid: false, error: e instanceof Error ? e.message : "Invalid cron expression" };
321
+ }
322
+ }
323
+ /** "+10s"/"+5m"/"+1h"/"+2d" → ISO timestamp. */
324
+ static parseRelativeTime(s) {
325
+ const m = s.match(/^\+(\d+)(s|m|h|d)$/);
326
+ if (!m)
327
+ return null;
328
+ const ms = parseInt(m[1], 10) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2]];
329
+ return new Date(Date.now() + ms).toISOString();
330
+ }
331
+ /** "10s"/"5m"/"1h"/"2d" → milliseconds. */
332
+ static parseInterval(s) {
333
+ const m = s.match(/^(\d+)(s|m|h|d)$/);
334
+ if (!m)
335
+ return null;
336
+ return parseInt(m[1], 10) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2]];
337
+ }
338
+ }
@@ -0,0 +1,141 @@
1
+ import type { JoinMode, WidgetMode } from "./types.js";
2
+ export interface SubagentsSettings {
3
+ maxConcurrent?: number;
4
+ /**
5
+ * 0 = unlimited — the extension's single source of truth for that convention:
6
+ * `normalizeMaxTurns()` in agent-runner.ts treats 0 → `undefined`, and the
7
+ * `/agents` → Settings input prompt explicitly says "0 = unlimited".
8
+ */
9
+ defaultMaxTurns?: number;
10
+ graceTurns?: number;
11
+ defaultJoinMode?: JoinMode;
12
+ /**
13
+ * Master switch for the schedule subagent feature. Defaults to `true`.
14
+ * When `false`: the `Agent` tool's `schedule` param + its guideline are
15
+ * stripped from the tool spec at registration (zero LLM-context cost), the
16
+ * scheduler doesn't bind to the session, and the `/agents → Scheduled jobs`
17
+ * menu entry is hidden. Schema-level removal applies at extension load
18
+ * (next pi session); runtime menu/runtime-fire short-circuit is immediate.
19
+ */
20
+ schedulingEnabled?: boolean;
21
+ /**
22
+ * When true, the effective model of each subagent spawn is validated
23
+ * against `enabledModels` from pi's settings — both global
24
+ * (`<agentDir>/settings.json`) and project-local (`<cwd>/.pi/settings.json`),
25
+ * with project overriding global (mirrors pi's SettingsManager deep-merge).
26
+ *
27
+ * scopeModels guards against runtime LLM choices, not user-level config.
28
+ * Out-of-scope handling reflects this:
29
+ * - Caller-supplied via `Agent({ model: "..." })` (only when frontmatter
30
+ * has no `model:`, since frontmatter is authoritative): hard error
31
+ * returned to the orchestrator, listing the allowed models. The LLM
32
+ * made an explicit out-of-scope choice and gets explicit feedback.
33
+ * - Frontmatter-pinned: warning toast + the pinned model runs. The
34
+ * agent's author/installer chose this; trust it.
35
+ * - Parent-inherited (neither caller nor frontmatter sets a model):
36
+ * warning toast + parent's model runs. The user chose the parent's
37
+ * model when starting the session; trust it.
38
+ *
39
+ * No-op when pi's `enabledModels` is empty or absent — nothing to validate
40
+ * against. Defaults to false: subagents may use any model.
41
+ */
42
+ scopeModels?: boolean;
43
+ /**
44
+ * When true, the three built-in default agents (general-purpose, Explore, Plan)
45
+ * are not registered at startup. User-defined agents from project/global custom
46
+ * agent dirs are completely unaffected — only the hardcoded DEFAULT_AGENTS are suppressed.
47
+ * Defaults to false.
48
+ */
49
+ disableDefaultAgents?: boolean;
50
+ /**
51
+ * Which Agent tool description the LLM sees. "full" (default) is the rich
52
+ * Claude Code-style prompt; "compact" is a ~75% smaller version (one-line
53
+ * agent type list, terse usage notes) for small/local models where tool-spec
54
+ * tokens are expensive; "custom" reads `.pi/agent-tool-description.md`
55
+ * (project, falling back to `<agentDir>/agent-tool-description.md`) with
56
+ * `{{placeholder}}` substitution — a missing/empty file falls back to "full".
57
+ * The mode is read once at tool registration — changing it applies on the
58
+ * next pi session.
59
+ */
60
+ toolDescriptionMode?: ToolDescriptionMode;
61
+ /**
62
+ * Whether the Claude Code-style FleetView (the navigable main+subagents list
63
+ * rendered below the editor) is shown. Defaults to `true`. Pure-UI: when off,
64
+ * the list never registers and the global key handler never captures input.
65
+ */
66
+ fleetView?: boolean;
67
+ /**
68
+ * Display mode for the persistent above-editor agent widget:
69
+ * - `all`: show every agent (foreground + background).
70
+ * - `background`: hide foreground agents — they already render inline as the
71
+ * Agent tool result, so the widget would otherwise double-render them
72
+ * (#118); everything else (background, queued, scheduled, RPC) stays.
73
+ * - `off`: hide the widget entirely.
74
+ * Defaults to `background`. Pure-UI and applied live (toggling refreshes the
75
+ * widget).
76
+ */
77
+ widgetMode?: WidgetMode;
78
+ /**
79
+ * Project/global default for writing each subagent's `.output` transcript
80
+ * (a JSON-lines copy of the run, stored under the OS temp dir).
81
+ * Defaults to `true`. Set `false` to make transcripts opt-in for the whole
82
+ * project (e.g. a repo that shouldn't leave run transcripts on disk for backup
83
+ * or DLP tooling to ingest). A custom agent's `output_transcript` frontmatter
84
+ * overrides this per agent. This governs only the transcript — it does NOT
85
+ * affect the persisted pi session (`persist_session`), worktree commits
86
+ * (`isolation: worktree`), or memory files.
87
+ */
88
+ outputTranscript?: boolean;
89
+ }
90
+ export type ToolDescriptionMode = "full" | "compact" | "custom";
91
+ /** Setter hooks used by applySettings to wire persisted values into in-memory state. */
92
+ export interface SettingsAppliers {
93
+ setMaxConcurrent: (n: number) => void;
94
+ setDefaultMaxTurns: (n: number) => void;
95
+ setGraceTurns: (n: number) => void;
96
+ setDefaultJoinMode: (mode: JoinMode) => void;
97
+ setSchedulingEnabled: (b: boolean) => void;
98
+ setScopeModels: (enabled: boolean) => void;
99
+ setDisableDefaultAgents: (b: boolean) => void;
100
+ setToolDescriptionMode: (mode: ToolDescriptionMode) => void;
101
+ setFleetView: (b: boolean) => void;
102
+ setWidgetMode: (mode: WidgetMode) => void;
103
+ setOutputTranscript: (b: boolean) => void;
104
+ }
105
+ /** Emit callback — a subset of `pi.events.emit` to keep helpers testable. */
106
+ export type SettingsEmit = (event: string, payload: unknown) => void;
107
+ /** Load merged settings: global provides defaults, project overrides. */
108
+ export declare function loadSettings(cwd?: string): SubagentsSettings;
109
+ /**
110
+ * Write project-local settings. Global is never touched from code.
111
+ * Returns `true` on success, `false` if the write (or mkdir) failed so the
112
+ * caller can surface a warning — persistence isn't fatal but isn't silent.
113
+ */
114
+ export declare function saveSettings(s: SubagentsSettings, cwd?: string): boolean;
115
+ /** Apply persisted settings to the in-memory state via caller-supplied setters. */
116
+ export declare function applySettings(s: SubagentsSettings, appliers: SettingsAppliers): void;
117
+ /**
118
+ * Format the user-facing toast for a settings mutation. Pure function —
119
+ * routes the success/failure of `saveSettings` into the right message + level
120
+ * so the UI layer (index.ts) stays a thin wire between input and notification.
121
+ */
122
+ export declare function persistToastFor(successMsg: string, persisted: boolean): {
123
+ message: string;
124
+ level: "info" | "warning";
125
+ };
126
+ /**
127
+ * Load merged settings, apply them to in-memory state, and emit the
128
+ * `subagents:settings_loaded` lifecycle event. Returns the loaded settings so
129
+ * callers can log/inspect. Extension init wires this once.
130
+ */
131
+ export declare function applyAndEmitLoaded(appliers: SettingsAppliers, emit: SettingsEmit, cwd?: string): SubagentsSettings;
132
+ /**
133
+ * Persist a settings snapshot, emit the `subagents:settings_changed` event
134
+ * (regardless of persist outcome so listeners see the in-memory change), and
135
+ * return the toast the UI should display. Event payload carries the `persisted`
136
+ * flag so listeners can react to write failures.
137
+ */
138
+ export declare function saveAndEmitChanged(snapshot: SubagentsSettings, successMsg: string, emit: SettingsEmit, cwd?: string): {
139
+ message: string;
140
+ level: "info" | "warning";
141
+ };
@@ -0,0 +1,162 @@
1
+ // Persistence for pi-subagents operational settings.
2
+ // - Global: ~/.pi/agent/subagents.json (via getAgentDir()) — manual defaults, never written here
3
+ // - Project: <cwd>/.pi/subagents.json — written by /agents → Settings; overrides global on load
4
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
6
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
7
+ const VALID_JOIN_MODES = new Set(["async", "group", "smart"]);
8
+ const VALID_TOOL_DESCRIPTION_MODES = new Set(["full", "compact", "custom"]);
9
+ const VALID_WIDGET_MODES = new Set(["all", "background", "off"]);
10
+ // Sanity ceilings — prevent hand-edited configs from asking for values that
11
+ // make no operational sense (e.g. 1e6 concurrent subagents). Permissive enough
12
+ // that any realistic power-user setting passes through.
13
+ const MAX_CONCURRENT_CEILING = 1024;
14
+ const MAX_TURNS_CEILING = 10_000;
15
+ const GRACE_TURNS_CEILING = 1_000;
16
+ /** Drop fields that don't match the expected shape. Silent — garbage becomes absent. */
17
+ function sanitize(raw) {
18
+ if (!raw || typeof raw !== "object")
19
+ return {};
20
+ const r = raw;
21
+ const out = {};
22
+ if (Number.isInteger(r.maxConcurrent) &&
23
+ r.maxConcurrent >= 1 &&
24
+ r.maxConcurrent <= MAX_CONCURRENT_CEILING) {
25
+ out.maxConcurrent = r.maxConcurrent;
26
+ }
27
+ if (Number.isInteger(r.defaultMaxTurns) &&
28
+ r.defaultMaxTurns >= 0 &&
29
+ r.defaultMaxTurns <= MAX_TURNS_CEILING) {
30
+ out.defaultMaxTurns = r.defaultMaxTurns;
31
+ }
32
+ if (Number.isInteger(r.graceTurns) &&
33
+ r.graceTurns >= 1 &&
34
+ r.graceTurns <= GRACE_TURNS_CEILING) {
35
+ out.graceTurns = r.graceTurns;
36
+ }
37
+ if (typeof r.defaultJoinMode === "string" && VALID_JOIN_MODES.has(r.defaultJoinMode)) {
38
+ out.defaultJoinMode = r.defaultJoinMode;
39
+ }
40
+ if (typeof r.schedulingEnabled === "boolean") {
41
+ out.schedulingEnabled = r.schedulingEnabled;
42
+ }
43
+ if (typeof r.scopeModels === "boolean") {
44
+ out.scopeModels = r.scopeModels;
45
+ }
46
+ if (typeof r.disableDefaultAgents === "boolean") {
47
+ out.disableDefaultAgents = r.disableDefaultAgents;
48
+ }
49
+ if (typeof r.toolDescriptionMode === "string" && VALID_TOOL_DESCRIPTION_MODES.has(r.toolDescriptionMode)) {
50
+ out.toolDescriptionMode = r.toolDescriptionMode;
51
+ }
52
+ if (typeof r.fleetView === "boolean") {
53
+ out.fleetView = r.fleetView;
54
+ }
55
+ if (typeof r.widgetMode === "string" && VALID_WIDGET_MODES.has(r.widgetMode)) {
56
+ out.widgetMode = r.widgetMode;
57
+ }
58
+ if (typeof r.outputTranscript === "boolean") {
59
+ out.outputTranscript = r.outputTranscript;
60
+ }
61
+ return out;
62
+ }
63
+ function globalPath() {
64
+ return join(getAgentDir(), "subagents.json");
65
+ }
66
+ function projectPath(cwd) {
67
+ return join(cwd, ".pi", "subagents.json");
68
+ }
69
+ /**
70
+ * Read a settings file. Missing file is silent (returns `{}`). A file that
71
+ * exists but can't be parsed emits a warning to stderr so users aren't
72
+ * silently reverted to defaults — and still returns `{}` so startup proceeds.
73
+ */
74
+ function readSettingsFile(path) {
75
+ if (!existsSync(path))
76
+ return {};
77
+ try {
78
+ return sanitize(JSON.parse(readFileSync(path, "utf-8")));
79
+ }
80
+ catch (err) {
81
+ const reason = err instanceof Error ? err.message : String(err);
82
+ console.warn(`[pi-subagents] Ignoring malformed settings at ${path}: ${reason}`);
83
+ return {};
84
+ }
85
+ }
86
+ /** Load merged settings: global provides defaults, project overrides. */
87
+ export function loadSettings(cwd = process.cwd()) {
88
+ return { ...readSettingsFile(globalPath()), ...readSettingsFile(projectPath(cwd)) };
89
+ }
90
+ /**
91
+ * Write project-local settings. Global is never touched from code.
92
+ * Returns `true` on success, `false` if the write (or mkdir) failed so the
93
+ * caller can surface a warning — persistence isn't fatal but isn't silent.
94
+ */
95
+ export function saveSettings(s, cwd = process.cwd()) {
96
+ const path = projectPath(cwd);
97
+ try {
98
+ mkdirSync(dirname(path), { recursive: true });
99
+ writeFileSync(path, JSON.stringify(s, null, 2), "utf-8");
100
+ return true;
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ }
106
+ /** Apply persisted settings to the in-memory state via caller-supplied setters. */
107
+ export function applySettings(s, appliers) {
108
+ if (typeof s.maxConcurrent === "number")
109
+ appliers.setMaxConcurrent(s.maxConcurrent);
110
+ if (typeof s.defaultMaxTurns === "number")
111
+ appliers.setDefaultMaxTurns(s.defaultMaxTurns);
112
+ if (typeof s.graceTurns === "number")
113
+ appliers.setGraceTurns(s.graceTurns);
114
+ if (s.defaultJoinMode)
115
+ appliers.setDefaultJoinMode(s.defaultJoinMode);
116
+ if (typeof s.schedulingEnabled === "boolean")
117
+ appliers.setSchedulingEnabled(s.schedulingEnabled);
118
+ if (typeof s.scopeModels === "boolean")
119
+ appliers.setScopeModels(s.scopeModels);
120
+ if (typeof s.disableDefaultAgents === "boolean")
121
+ appliers.setDisableDefaultAgents(s.disableDefaultAgents);
122
+ if (s.toolDescriptionMode)
123
+ appliers.setToolDescriptionMode(s.toolDescriptionMode);
124
+ if (typeof s.fleetView === "boolean")
125
+ appliers.setFleetView(s.fleetView);
126
+ if (s.widgetMode)
127
+ appliers.setWidgetMode(s.widgetMode);
128
+ if (typeof s.outputTranscript === "boolean")
129
+ appliers.setOutputTranscript(s.outputTranscript);
130
+ }
131
+ /**
132
+ * Format the user-facing toast for a settings mutation. Pure function —
133
+ * routes the success/failure of `saveSettings` into the right message + level
134
+ * so the UI layer (index.ts) stays a thin wire between input and notification.
135
+ */
136
+ export function persistToastFor(successMsg, persisted) {
137
+ return persisted
138
+ ? { message: successMsg, level: "info" }
139
+ : { message: `${successMsg} (session only; failed to persist)`, level: "warning" };
140
+ }
141
+ /**
142
+ * Load merged settings, apply them to in-memory state, and emit the
143
+ * `subagents:settings_loaded` lifecycle event. Returns the loaded settings so
144
+ * callers can log/inspect. Extension init wires this once.
145
+ */
146
+ export function applyAndEmitLoaded(appliers, emit, cwd = process.cwd()) {
147
+ const settings = loadSettings(cwd);
148
+ applySettings(settings, appliers);
149
+ emit("subagents:settings_loaded", { settings });
150
+ return settings;
151
+ }
152
+ /**
153
+ * Persist a settings snapshot, emit the `subagents:settings_changed` event
154
+ * (regardless of persist outcome so listeners see the in-memory change), and
155
+ * return the toast the UI should display. Event payload carries the `persisted`
156
+ * flag so listeners can react to write failures.
157
+ */
158
+ export function saveAndEmitChanged(snapshot, successMsg, emit, cwd = process.cwd()) {
159
+ const persisted = saveSettings(snapshot, cwd);
160
+ emit("subagents:settings_changed", { settings: snapshot, persisted });
161
+ return persistToastFor(successMsg, persisted);
162
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * skill-loader.ts — Preload named skills.
3
+ *
4
+ * Roots, in precedence order:
5
+ * - <cwd>/.pi/skills (project, Pi's standard)
6
+ * - <cwd>/.agents/skills (project, cross-tool Agent Skills spec — https://agentskills.io)
7
+ * - getAgentDir()/skills (user, default ~/.pi/agent/skills — Pi's standard)
8
+ * - ~/.agents/skills (user, cross-tool Agent Skills spec)
9
+ * - ~/.pi/skills (legacy global, pre-Pi)
10
+ *
11
+ * Layout per root:
12
+ * - <root>/<name>.md (flat file at the top level)
13
+ * - <root>/.../<name>/SKILL.md (directory skill, may be nested — Pi's standard)
14
+ *
15
+ * Recursion skips dotfile entries and node_modules. A directory that itself contains
16
+ * SKILL.md is a skill — we don't descend into it (Pi: skills don't nest).
17
+ *
18
+ * Symlinks are rejected for security (deviation from Pi, which follows them).
19
+ */
20
+ export interface PreloadedSkill {
21
+ name: string;
22
+ content: string;
23
+ }
24
+ export declare function preloadSkills(skillNames: string[], cwd: string): PreloadedSkill[];