@timmyjl12/pi-subagents 0.20.0 → 0.21.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 (159) hide show
  1. package/CHANGELOG.md +862 -827
  2. package/README.md +1125 -1080
  3. package/dist/active-agents-prompt.d.ts +31 -9
  4. package/dist/active-agents-prompt.js +73 -9
  5. package/dist/agent-color.js +9 -1
  6. package/dist/agent-file-toggle.d.ts +1 -1
  7. package/dist/agent-manager.d.ts +405 -18
  8. package/dist/agent-manager.js +1661 -131
  9. package/dist/agent-runner.d.ts +45 -6
  10. package/dist/agent-runner.js +109 -18
  11. package/dist/agent-types.d.ts +30 -7
  12. package/dist/agent-types.js +38 -9
  13. package/dist/awaited-result.d.ts +37 -0
  14. package/dist/awaited-result.js +150 -0
  15. package/dist/child-session-shutdown.d.ts +19 -1
  16. package/dist/child-session-shutdown.js +60 -11
  17. package/dist/cleanup-plans.d.ts +10 -0
  18. package/dist/cleanup-plans.js +112 -0
  19. package/dist/cross-extension-rpc.d.ts +8 -1
  20. package/dist/cross-extension-rpc.js +59 -5
  21. package/dist/custom-agents.d.ts +34 -9
  22. package/dist/custom-agents.js +308 -111
  23. package/dist/default-agents.d.ts +1 -1
  24. package/dist/env.d.ts +1 -1
  25. package/dist/error-log.d.ts +6 -0
  26. package/dist/error-log.js +8 -0
  27. package/dist/force-main-model.d.ts +21 -0
  28. package/dist/force-main-model.js +28 -0
  29. package/dist/goal-bridge.d.ts +155 -0
  30. package/dist/goal-bridge.js +305 -0
  31. package/dist/group-join.d.ts +5 -1
  32. package/dist/group-join.js +52 -7
  33. package/dist/index.d.ts +5 -5
  34. package/dist/index.js +2827 -333
  35. package/dist/invocation-config.d.ts +30 -3
  36. package/dist/invocation-config.js +30 -1
  37. package/dist/memory.d.ts +1 -1
  38. package/dist/mention-clone.d.ts +1 -1
  39. package/dist/model-scope.d.ts +1 -1
  40. package/dist/nested-tools.d.ts +22 -1
  41. package/dist/nested-tools.js +120 -26
  42. package/dist/output-file.d.ts +15 -4
  43. package/dist/output-file.js +146 -43
  44. package/dist/prompts.d.ts +1 -1
  45. package/dist/recovery.d.ts +1 -1
  46. package/dist/report-cleanup.d.ts +204 -0
  47. package/dist/report-cleanup.js +1632 -0
  48. package/dist/report-store.d.ts +738 -0
  49. package/dist/report-store.js +3612 -0
  50. package/dist/schedule-store.d.ts +14 -6
  51. package/dist/schedule-store.js +88 -58
  52. package/dist/schedule.d.ts +20 -8
  53. package/dist/schedule.js +135 -74
  54. package/dist/settings.d.ts +39 -11
  55. package/dist/settings.js +22 -5
  56. package/dist/status-note.d.ts +1 -1
  57. package/dist/structured-output.d.ts +1 -1
  58. package/dist/types.d.ts +32 -3
  59. package/dist/ui/agent-mention.d.ts +2 -2
  60. package/dist/ui/agent-widget.d.ts +82 -13
  61. package/dist/ui/agent-widget.js +155 -37
  62. package/dist/ui/cleanup-preview.d.ts +59 -0
  63. package/dist/ui/cleanup-preview.js +466 -0
  64. package/dist/ui/conversation-viewer.d.ts +4 -4
  65. package/dist/ui/conversation-viewer.js +10 -6
  66. package/dist/ui/fleet-list.d.ts +3 -3
  67. package/dist/ui/fleet-list.js +3 -3
  68. package/dist/ui/fleet-overlay.d.ts +37 -6
  69. package/dist/ui/fleet-overlay.js +214 -18
  70. package/dist/ui/hub-feed.d.ts +52 -0
  71. package/dist/ui/hub-feed.js +148 -0
  72. package/dist/ui/native-transcript.js +5 -1
  73. package/dist/ui/schedule-menu.d.ts +1 -1
  74. package/dist/ui/schedule-menu.js +1 -1
  75. package/dist/ui/workflow-card.d.ts +4 -4
  76. package/dist/ui/workflow-dialog.d.ts +4 -4
  77. package/dist/ui/workflow-dialog.js +8 -3
  78. package/dist/ui/workflow-menu.d.ts +2 -2
  79. package/dist/usage.d.ts +12 -0
  80. package/dist/usage.js +28 -1
  81. package/dist/workflow/entry.d.ts +3 -3
  82. package/dist/workflow/host.d.ts +7 -4
  83. package/dist/workflow/host.js +162 -48
  84. package/dist/workflow/journal.d.ts +23 -7
  85. package/dist/workflow/journal.js +80 -23
  86. package/dist/workflow/progress.d.ts +1 -1
  87. package/dist/workflow/runtime.d.ts +45 -6
  88. package/dist/workflow/runtime.js +105 -16
  89. package/dist/workflow/task.d.ts +13 -4
  90. package/dist/workflow/task.js +7 -1
  91. package/dist/workflow/tool-description.d.ts +7 -2
  92. package/dist/workflow/tool-description.js +10 -5
  93. package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
  94. package/docs/artifacts.md +93 -0
  95. package/docs/rpc.md +252 -189
  96. package/docs/runtime-performance.md +53 -0
  97. package/docs/workflows.md +48 -18
  98. package/examples/agent-tool-description.md +2 -2
  99. package/examples/workflows/review-panel.js +6 -3
  100. package/package.json +5 -5
  101. package/src/active-agents-prompt.ts +115 -39
  102. package/src/agent-color.ts +10 -2
  103. package/src/agent-file-toggle.ts +2 -2
  104. package/src/agent-manager.ts +3312 -1601
  105. package/src/agent-runner.ts +164 -36
  106. package/src/agent-types.ts +56 -11
  107. package/src/awaited-result.ts +187 -0
  108. package/src/child-session-shutdown.ts +114 -46
  109. package/src/cleanup-plans.ts +112 -0
  110. package/src/cross-extension-rpc.ts +68 -9
  111. package/src/custom-agents.ts +384 -112
  112. package/src/default-agents.ts +1 -1
  113. package/src/enabled-models.ts +1 -1
  114. package/src/env.ts +1 -1
  115. package/src/error-log.ts +10 -1
  116. package/src/force-main-model.ts +29 -0
  117. package/src/goal-bridge.ts +468 -0
  118. package/src/group-join.ts +56 -9
  119. package/src/index.ts +2987 -349
  120. package/src/invocation-config.ts +50 -4
  121. package/src/memory.ts +1 -1
  122. package/src/mention-clone.ts +3 -3
  123. package/src/model-scope.ts +1 -1
  124. package/src/nested-tools.ts +164 -33
  125. package/src/output-file.ts +168 -46
  126. package/src/prompts.ts +1 -1
  127. package/src/recovery.ts +2 -2
  128. package/src/report-cleanup.ts +2044 -0
  129. package/src/report-store.ts +4130 -0
  130. package/src/schedule-store.ts +244 -201
  131. package/src/schedule.ts +144 -80
  132. package/src/settings.ts +61 -16
  133. package/src/skill-loader.ts +1 -1
  134. package/src/standalone-fallback.ts +2 -2
  135. package/src/status-note.ts +1 -1
  136. package/src/structured-output.ts +1 -1
  137. package/src/types.ts +33 -3
  138. package/src/ui/agent-mention.ts +3 -3
  139. package/src/ui/agent-widget.ts +179 -45
  140. package/src/ui/cleanup-preview.ts +518 -0
  141. package/src/ui/conversation-viewer.ts +19 -15
  142. package/src/ui/fleet-list.ts +7 -7
  143. package/src/ui/fleet-overlay.ts +1048 -847
  144. package/src/ui/hub-feed.ts +179 -0
  145. package/src/ui/native-transcript.ts +7 -3
  146. package/src/ui/schedule-menu.ts +4 -4
  147. package/src/ui/workflow-card.ts +4 -4
  148. package/src/ui/workflow-dialog.ts +10 -6
  149. package/src/ui/workflow-menu.ts +4 -4
  150. package/src/usage.ts +53 -3
  151. package/src/workflow/collisions.ts +1 -1
  152. package/src/workflow/entry.ts +3 -3
  153. package/src/workflow/host.ts +174 -54
  154. package/src/workflow/journal.ts +80 -23
  155. package/src/workflow/progress.ts +1 -1
  156. package/src/workflow/runtime.ts +146 -23
  157. package/src/workflow/saved.ts +3 -3
  158. package/src/workflow/task.ts +18 -7
  159. package/src/workflow/tool-description.ts +10 -5
package/src/schedule.ts CHANGED
@@ -18,12 +18,22 @@
18
18
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
19
19
  import { Cron } from "croner";
20
20
  import { nanoid } from "nanoid";
21
- import type { AgentManager } from "./agent-manager.js";
22
- import { normalizeMaxTurns } from "./agent-runner.js";
23
- import { resolveSpawnType } from "./agent-types.js";
24
- import { resolveModel } from "./model-resolver.js";
25
- import type { ScheduleStore } from "./schedule-store.js";
26
- import type { IsolationMode, ScheduledSubagent, SubagentType, ThinkingLevel } from "./types.js";
21
+ import type { AgentManager } from "./agent-manager.ts";
22
+ import { getAllowPerCallTurnLimits, resolveEffectiveMaxTurns } from "./agent-runner.ts";
23
+ import { resolveSpawnType } from "./agent-types.ts";
24
+ import { resolveModel } from "./model-resolver.ts";
25
+ import type { ScheduleStore } from "./schedule-store.ts";
26
+ import type { IsolationMode, ScheduledSubagent, SubagentType, ThinkingLevel } from "./types.ts";
27
+
28
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
29
+
30
+ function timerDelayError(delayMs: number): string {
31
+ return `Schedule delay ${delayMs}ms exceeds Node's maximum timer delay of ${MAX_TIMER_DELAY_MS}ms; use a shorter delay.`;
32
+ }
33
+
34
+ function assertSupportedTimerDelay(delayMs: number): void {
35
+ if (delayMs > MAX_TIMER_DELAY_MS) throw new Error(timerDelayError(delayMs));
36
+ }
27
37
 
28
38
  /** Event emitted on `pi.events` for cross-extension consumers. */
29
39
  export type ScheduleChangeEvent =
@@ -31,6 +41,7 @@ export type ScheduleChangeEvent =
31
41
  | { type: "removed"; jobId: string }
32
42
  | { type: "updated"; job: ScheduledSubagent }
33
43
  | { type: "fired"; jobId: string; agentId: string; name: string }
44
+ | { type: "skipped"; jobId: string; name: string; reason: "overlap" }
34
45
  | { type: "error"; jobId: string; error: string };
35
46
 
36
47
  /** Params accepted at job creation — ID, timestamps, and state are derived. */
@@ -50,6 +61,7 @@ export interface NewJobInput {
50
61
  export class SubagentScheduler {
51
62
  private jobs = new Map<string, Cron>();
52
63
  private intervals = new Map<string, NodeJS.Timeout>();
64
+ private activeRuns = new Set<string>();
53
65
  private store: ScheduleStore | undefined;
54
66
  private pi: ExtensionAPI | undefined;
55
67
  private ctx: ExtensionContext | undefined;
@@ -115,31 +127,29 @@ export class SubagentScheduler {
115
127
  }
116
128
 
117
129
  /** Add a job, persist, and arm if enabled. Returns the stored job. */
118
- addJob(input: NewJobInput): ScheduledSubagent {
130
+ async addJob(input: NewJobInput): Promise<ScheduledSubagent> {
119
131
  const store = this.requireStore();
120
- if (store.hasName(input.name)) {
121
- throw new Error(`A scheduled job named "${input.name}" already exists.`);
122
- }
123
132
  const job = this.buildJob(input);
124
- store.add(job);
133
+ const added = await store.addUnlessNameExists(job);
134
+ if (!added) throw new Error(`A scheduled job named "${input.name}" already exists.`);
125
135
  if (job.enabled) this.scheduleJob(job);
126
136
  this.emit({ type: "added", job });
127
137
  return job;
128
138
  }
129
139
 
130
- removeJob(id: string): boolean {
140
+ async removeJob(id: string): Promise<boolean> {
131
141
  const store = this.requireStore();
132
142
  if (!store.get(id)) return false;
133
143
  this.unscheduleJob(id);
134
- const ok = store.remove(id);
144
+ const ok = await store.remove(id);
135
145
  if (ok) this.emit({ type: "removed", jobId: id });
136
146
  return ok;
137
147
  }
138
148
 
139
149
  /** Toggle / mutate a job. Re-arms based on the new `enabled` state. */
140
- updateJob(id: string, patch: Partial<ScheduledSubagent>): ScheduledSubagent | undefined {
150
+ async updateJob(id: string, patch: Partial<ScheduledSubagent>): Promise<ScheduledSubagent | undefined> {
141
151
  const store = this.requireStore();
142
- const updated = store.update(id, patch);
152
+ const updated = await store.update(id, patch);
143
153
  if (!updated) return undefined;
144
154
  this.unscheduleJob(id);
145
155
  if (updated.enabled) this.scheduleJob(updated);
@@ -171,34 +181,50 @@ export class SubagentScheduler {
171
181
  if (!store) return;
172
182
  try {
173
183
  if (job.scheduleType === "interval" && job.intervalMs) {
174
- const t = setInterval(() => this.executeJob(job.id), job.intervalMs);
184
+ if (job.intervalMs > MAX_TIMER_DELAY_MS) {
185
+ void this.disableJobWithError(job, store, timerDelayError(job.intervalMs)).catch(err => this.reportError(job.id, err));
186
+ return;
187
+ }
188
+ const t = setInterval(() => this.dispatchJob(job.id), job.intervalMs);
175
189
  this.intervals.set(job.id, t);
176
190
  } else if (job.scheduleType === "once") {
177
191
  const target = new Date(job.schedule).getTime();
178
192
  const delay = target - Date.now();
179
- if (delay > 0) {
180
- const t = setTimeout(() => {
181
- this.executeJob(job.id);
182
- // Auto-disable one-shots after they fire (mirrors pi-cron-schedule)
183
- store.update(job.id, { enabled: false });
184
- const updated = store.get(job.id);
185
- if (updated) this.emit({ type: "updated", job: updated });
186
- }, delay);
193
+ if (delay > MAX_TIMER_DELAY_MS) {
194
+ void this.disableJobWithError(job, store, timerDelayError(delay)).catch(err => this.reportError(job.id, err));
195
+ } else if (delay > 0) {
196
+ const t = setTimeout(() => this.executeOnce(job.id, store).catch(err => this.reportError(job.id, err)), delay);
187
197
  this.intervals.set(job.id, t);
188
198
  } else {
189
199
  // Past timestamp — disable, mark error, never fire
190
- store.update(job.id, { enabled: false, lastStatus: "error" });
191
- this.emit({ type: "error", jobId: job.id, error: `Scheduled time ${job.schedule} is in the past` });
200
+ void this.disableJobWithError(job, store, `Scheduled time ${job.schedule} is in the past`).catch(err => this.reportError(job.id, err));
192
201
  }
193
202
  } else {
194
- const cron = new Cron(job.schedule, () => this.executeJob(job.id));
203
+ const cron = new Cron(job.schedule, () => this.dispatchJob(job.id));
195
204
  this.jobs.set(job.id, cron);
196
205
  }
197
206
  } catch (err) {
198
- this.emit({ type: "error", jobId: job.id, error: err instanceof Error ? err.message : String(err) });
207
+ this.reportError(job.id, err);
199
208
  }
200
209
  }
201
210
 
211
+ private dispatchJob(id: string): Promise<void> {
212
+ return this.executeJob(id).catch(err => this.reportError(id, err));
213
+ }
214
+
215
+ private async executeOnce(id: string, store: ScheduleStore): Promise<void> {
216
+ const execution = this.executeJob(id).catch(err => this.reportError(id, err));
217
+ // Auto-disable after dispatch, without waiting for a long-running agent.
218
+ const updated = await store.update(id, { enabled: false });
219
+ if (updated) this.emit({ type: "updated", job: updated });
220
+ await execution;
221
+ }
222
+
223
+ private async disableJobWithError(job: ScheduledSubagent, store: ScheduleStore, error: string): Promise<void> {
224
+ await store.update(job.id, { enabled: false, lastStatus: "error" });
225
+ this.emit({ type: "error", jobId: job.id, error });
226
+ }
227
+
202
228
  private unscheduleJob(id: string): void {
203
229
  const cron = this.jobs.get(id);
204
230
  if (cron) {
@@ -215,10 +241,10 @@ export class SubagentScheduler {
215
241
 
216
242
  /**
217
243
  * Fire a job: persist running state, spawn (bypassing the concurrency
218
- * queue), persist completion. Fire-and-forget: the timer tick returns
219
- * immediately so other jobs keep firing.
244
+ * queue), persist completion. The in-memory guard covers the complete run,
245
+ * so persisted `running` state from a previous process never blocks recovery.
220
246
  */
221
- private executeJob(id: string): void {
247
+ private async executeJob(id: string): Promise<void> {
222
248
  const store = this.store;
223
249
  const pi = this.pi;
224
250
  const ctx = this.ctx;
@@ -226,34 +252,46 @@ export class SubagentScheduler {
226
252
  if (!store || !pi || !ctx || !manager) return;
227
253
  const job = store.get(id);
228
254
  if (!job?.enabled) return;
229
-
230
- store.update(id, { lastStatus: "running" });
231
-
232
- // Resolve model at fire time — registry contents may have changed since the
233
- // job was created (auth added/removed). Fall back silently to spawn-default
234
- // if resolution fails; the spawn path handles undefined model gracefully.
235
- let resolvedModel: any | undefined;
236
- if (job.model) {
237
- const r = resolveModel(job.model, ctx.modelRegistry);
238
- if (typeof r !== "string") resolvedModel = r;
255
+ if (this.activeRuns.has(id)) {
256
+ this.emit({ type: "skipped", jobId: id, name: job.name, reason: "overlap" });
257
+ return;
239
258
  }
259
+ this.activeRuns.add(id);
240
260
 
241
- let agentId: string;
242
261
  try {
262
+ await store.update(id, { lastStatus: "running" });
263
+
264
+ // Resolve model at fire time — registry contents may have changed since the
265
+ // job was created (auth added/removed). Fall back silently to spawn-default
266
+ // if resolution fails; the spawn path handles undefined model gracefully.
267
+ let resolvedModel: any | undefined;
268
+ if (job.model) {
269
+ const r = resolveModel(job.model, ctx.modelRegistry);
270
+ if (typeof r !== "string") resolvedModel = r;
271
+ }
272
+
243
273
  // Re-resolve at fire time against the registry as it stands. This does not
244
274
  // reload from disk (the scheduler has no reason to rebuild process-global
245
275
  // state from a timer), so it catches changes that went through /agents or
246
- // an Agent call — not a file deleted directly from a shell. The catch below turns
247
- // this into lastStatus: "error" plus an error event, like any other
248
- // fire-time failure.
276
+ // an Agent call — not a file deleted directly from a shell.
249
277
  const dispatch = resolveSpawnType(job.subagent_type);
250
278
  if (!dispatch.ok) throw new Error(dispatch.message);
251
- agentId = manager.spawn(pi, ctx, dispatch.type, job.prompt, {
279
+ // Caller caps are a policy opt-in. Re-check at fire time rather than
280
+ // trusting the stored job: the switch can change after creation, and a
281
+ // job persisted while caps were allowed must not keep enforcing its cap
282
+ // after the user turns them off. When off, the runner still applies the
283
+ // agent's own or the project's configured budget (passing undefined).
284
+ const forwardedMaxTurns = getAllowPerCallTurnLimits() ? job.max_turns : undefined;
285
+ // Snapshot the budget that will actually be enforced, not the ignored job
286
+ // field — role/default resolution otherwise lives only in the runner and
287
+ // the conversation viewer would report a cap no longer applied.
288
+ const effectiveMaxTurns = resolveEffectiveMaxTurns(dispatch.type, forwardedMaxTurns);
289
+ const agentId = manager.spawn(pi, ctx, dispatch.type, job.prompt, {
252
290
  description: job.description,
253
291
  isBackground: true,
254
292
  bypassQueue: true,
255
293
  model: resolvedModel,
256
- maxTurns: job.max_turns,
294
+ maxTurns: forwardedMaxTurns,
257
295
  isolated: job.isolated,
258
296
  thinkingLevel: job.thinking,
259
297
  isolation: job.isolation,
@@ -264,47 +302,68 @@ export class SubagentScheduler {
264
302
  // would only be right until then.
265
303
  invocation: {
266
304
  thinking: job.thinking,
267
- // Normalized like the Agent tool's own snapshot: `0` means unlimited,
268
- // and rendering it as "max turns: 0" would read as a limit of none.
269
- maxTurns: normalizeMaxTurns(job.max_turns),
305
+ // Already normalized and resolved for the configured/global fallback;
306
+ // `0` and an ignored stored cap both land as undefined.
307
+ maxTurns: effectiveMaxTurns,
270
308
  isolated: job.isolated,
271
309
  runInBackground: true,
272
310
  isolation: job.isolation,
273
311
  },
274
312
  });
313
+
314
+ this.emit({ type: "fired", jobId: id, agentId, name: job.name });
315
+
316
+ // AgentManager's promise resolves either way (its .catch returns ""), so we
317
+ // can't infer success/failure from the promise — read record.status instead.
318
+ // Terminal states: completed/steered = success; error/aborted/stopped = error.
319
+ // awaitStartup first: with isolation: "worktree" the run promise only exists
320
+ // once the repo copy is made, and a failed copy rejects here.
321
+ let status: "success" | "error";
322
+ try {
323
+ await manager.awaitStartup(agentId);
324
+ await manager.getRecord(agentId)?.promise;
325
+ const r = manager.getRecord(agentId);
326
+ const failed = r?.status === "error" || r?.status === "aborted" || r?.status === "stopped";
327
+ status = failed ? "error" : "success";
328
+ } catch {
329
+ status = "error";
330
+ }
331
+ await this.finalizeRun(store, id, status);
275
332
  } catch (err) {
276
- const error = err instanceof Error ? err.message : String(err);
277
- store.update(id, { lastRun: new Date().toISOString(), lastStatus: "error" });
278
- this.emit({ type: "error", jobId: id, error });
279
- return;
333
+ await this.recordRunError(store, id, err);
334
+ } finally {
335
+ this.activeRuns.delete(id);
280
336
  }
337
+ }
281
338
 
282
- this.emit({ type: "fired", jobId: id, agentId, name: job.name });
339
+ private async finalizeRun(store: ScheduleStore, id: string, status: "success" | "error"): Promise<void> {
340
+ const lastRun = new Date().toISOString();
341
+ const current = store.get(id);
342
+ const next = current?.scheduleType === "interval" && current.intervalMs
343
+ ? new Date(new Date(lastRun).getTime() + current.intervalMs).toISOString()
344
+ : this.getNextRun(id);
345
+ await store.update(id, {
346
+ lastRun,
347
+ lastStatus: status,
348
+ runCount: (current?.runCount ?? 0) + 1,
349
+ nextRun: next,
350
+ });
351
+ }
283
352
 
284
- const finalize = (status: "success" | "error") => {
285
- const next = this.getNextRun(id);
286
- const current = store.get(id);
287
- store.update(id, {
288
- lastRun: new Date().toISOString(),
289
- lastStatus: status,
290
- runCount: (current?.runCount ?? 0) + 1,
291
- nextRun: next,
292
- });
293
- };
353
+ private async recordRunError(store: ScheduleStore, id: string, err: unknown): Promise<void> {
354
+ const error = err instanceof Error ? err.message : String(err);
355
+ try {
356
+ await store.update(id, { lastRun: new Date().toISOString(), lastStatus: "error" });
357
+ } catch (persistErr) {
358
+ const detail = persistErr instanceof Error ? persistErr.message : String(persistErr);
359
+ this.emit({ type: "error", jobId: id, error: `${error}; failed to persist schedule status: ${detail}` });
360
+ return;
361
+ }
362
+ this.emit({ type: "error", jobId: id, error });
363
+ }
294
364
 
295
- // AgentManager's promise resolves either way (its .catch returns ""), so we
296
- // can't infer success/failure from the promise — read record.status instead.
297
- // Terminal states: completed/steered = success; error/aborted/stopped = error.
298
- // awaitStartup first: with isolation: "worktree" the run promise only exists
299
- // once the repo copy is made, and a failed copy rejects here.
300
- manager.awaitStartup(agentId)
301
- .then(() => manager.getRecord(agentId)?.promise)
302
- .then(() => {
303
- const r = manager.getRecord(agentId);
304
- const failed = r?.status === "error" || r?.status === "aborted" || r?.status === "stopped";
305
- finalize(failed ? "error" : "success");
306
- })
307
- .catch(() => finalize("error"));
365
+ private reportError(id: string, err: unknown): void {
366
+ this.emit({ type: "error", jobId: id, error: err instanceof Error ? err.message : String(err) });
308
367
  }
309
368
 
310
369
  private emit(event: ScheduleChangeEvent): void {
@@ -337,9 +396,11 @@ export class SubagentScheduler {
337
396
  if (/^\d{4}-\d{2}-\d{2}T/.test(trimmed)) {
338
397
  const d = new Date(trimmed);
339
398
  if (!Number.isNaN(d.getTime())) {
340
- if (d.getTime() <= Date.now()) {
399
+ const delay = d.getTime() - Date.now();
400
+ if (delay <= 0) {
341
401
  throw new Error(`Scheduled time ${d.toISOString()} is in the past.`);
342
402
  }
403
+ assertSupportedTimerDelay(delay);
343
404
  return { type: "once", normalized: d.toISOString() };
344
405
  }
345
406
  }
@@ -374,6 +435,7 @@ export class SubagentScheduler {
374
435
  const m = s.match(/^\+(\d+)(s|m|h|d)$/);
375
436
  if (!m) return null;
376
437
  const ms = parseInt(m[1], 10) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2] as "s" | "m" | "h" | "d"];
438
+ assertSupportedTimerDelay(ms);
377
439
  return new Date(Date.now() + ms).toISOString();
378
440
  }
379
441
 
@@ -381,6 +443,8 @@ export class SubagentScheduler {
381
443
  static parseInterval(s: string): number | null {
382
444
  const m = s.match(/^(\d+)(s|m|h|d)$/);
383
445
  if (!m) return null;
384
- return parseInt(m[1], 10) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2] as "s" | "m" | "h" | "d"];
446
+ const ms = parseInt(m[1], 10) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2] as "s" | "m" | "h" | "d"];
447
+ assertSupportedTimerDelay(ms);
448
+ return ms;
385
449
  }
386
450
  }
package/src/settings.ts CHANGED
@@ -5,8 +5,8 @@
5
5
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
6
  import { dirname, join } from "node:path";
7
7
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
8
- import { NO_FALLBACK } from "./agent-types.js";
9
- import type { AgentMentionMode, JoinMode, ViewerMarkdownMode, WidgetMode } from "./types.js";
8
+ import { NO_FALLBACK } from "./agent-types.ts";
9
+ import type { AgentMentionMode, JoinMode, ViewerMarkdownMode, WidgetMode, WidgetPlacement } from "./types.ts";
10
10
 
11
11
  export interface SubagentsSettings {
12
12
  maxConcurrent?: number;
@@ -39,6 +39,16 @@ export interface SubagentsSettings {
39
39
  */
40
40
  defaultMaxTurns?: number;
41
41
  graceTurns?: number;
42
+ /**
43
+ * Whether `Agent`/nested `max_turns` parameters (and RPC `maxTurns` options)
44
+ * may impose a per-call turn budget. Defaults to `false`.
45
+ *
46
+ * Off keeps the configured budget authoritative: agent-file `max_turns` and
47
+ * `defaultMaxTurns` apply, the parameter is omitted from both tool schemas,
48
+ * and a runtime call that bypasses schema validation still has its cap
49
+ * dropped. Turn it on to restore the historical caller-cap behaviour.
50
+ */
51
+ allowPerCallTurnLimits?: boolean;
42
52
  defaultJoinMode?: JoinMode;
43
53
  /**
44
54
  * Whether a top-level `Agent` spawn that doesn't say runs detached.
@@ -118,12 +128,6 @@ export interface SubagentsSettings {
118
128
  * next pi session.
119
129
  */
120
130
  toolDescriptionMode?: ToolDescriptionMode;
121
- /**
122
- * Whether the Claude Code-style FleetView (the navigable main+subagents list
123
- * rendered below the editor) is shown. Defaults to `true`. Pure-UI: when off,
124
- * the list never registers and the global key handler never captures input.
125
- */
126
- fleetView?: boolean;
127
131
  /**
128
132
  * Whether `@handle message` typed at the prompt is routed to that subagent
129
133
  * instead of the main model, and whether `@` offers running agents alongside
@@ -153,16 +157,20 @@ export interface SubagentsSettings {
153
157
  */
154
158
  rememberAgents?: boolean;
155
159
  /**
156
- * Display mode for the persistent above-editor agent widget:
160
+ * Display mode for the persistent agent widget:
157
161
  * - `all`: show every agent (foreground + background).
158
162
  * - `background`: hide foreground agents — they already render inline as the
159
163
  * Agent tool result, so the widget would otherwise double-render them
160
164
  * (#118); everything else (background, queued, scheduled, RPC) stays.
161
165
  * - `off`: hide the widget entirely.
162
- * Defaults to `background`. Pure-UI and applied live (toggling refreshes the
166
+ * `background` filtering never gates `←` → Agent Hub (the key follows the
167
+ * Hub's content); `off` stands the key down with the list.
168
+ * Defaults to `all`. Pure-UI and applied live (toggling refreshes the
163
169
  * widget).
164
170
  */
165
171
  widgetMode?: WidgetMode;
172
+ /** Compact list placement relative to the editor. Defaults to `above`; applied live. */
173
+ widgetPlacement?: WidgetPlacement;
166
174
  /**
167
175
  * Project/global default for writing each subagent's `.output` transcript
168
176
  * (a JSON-lines copy of the run, stored under the OS temp dir).
@@ -218,6 +226,24 @@ export interface SubagentsSettings {
218
226
  * fixed once pi has it.
219
227
  */
220
228
  workflowsEnabled?: boolean;
229
+ /**
230
+ * Agent type a workflow's `agent()` call uses when it names no `agentType` of
231
+ * its own. Defaults to `task`, the economical workflow role
232
+ * (`DEFAULT_WORKFLOW_AGENT_TYPE` in workflow/runtime.ts).
233
+ *
234
+ * The precedence is per-run, not global: a `SubagentWorkflow(agentType)` on
235
+ * the call outranks this, a run that resumes another inherits THAT run's
236
+ * frozen choice, and a script's `agent(prompt, { agentType })` outranks all
237
+ * three. Only "unspecified" reads this setting.
238
+ *
239
+ * Kept as a name rather than validated against the registry on load: agent
240
+ * files are added, renamed and disabled mid-session, and a stored name that is
241
+ * temporarily unavailable must survive an unrelated settings save instead of
242
+ * being rewritten to a cheaper-looking role. Resolution stays at spawn time;
243
+ * an unavailable workflow default fails closed instead of using the general
244
+ * fallbackSubagent policy.
245
+ */
246
+ workflowDefaultAgentType?: string;
221
247
  /**
222
248
  * Hard ceiling on nested subagent delegation, counted from the main session:
223
249
  * main = 0, its subagents = 1, their children = 2. Defaults to `2`; `0` or `1`
@@ -266,7 +292,7 @@ export interface SubagentsSettings {
266
292
  reportUsage?: boolean;
267
293
  /**
268
294
  * Whether the subagent surfaces show an estimated dollar cost next to their
269
- * token counts (widget, FleetView, conversation viewer, foreground results,
295
+ * token counts (widget, Agent Hub, conversation viewer, foreground results,
270
296
  * completion notifications). Defaults to `false`. Applied live.
271
297
  *
272
298
  * Rendered as `~$0.0042` — the tilde marks it as pi's reported estimate
@@ -312,6 +338,7 @@ export interface SettingsAppliers {
312
338
  setMaxConcurrentForeground: (n: number) => void;
313
339
  setDefaultMaxTurns: (n: number) => void;
314
340
  setGraceTurns: (n: number) => void;
341
+ setAllowPerCallTurnLimits: (b: boolean) => void;
315
342
  setDefaultJoinMode: (mode: JoinMode) => void;
316
343
  setBackgroundByDefault: (b: boolean) => void;
317
344
  setSchedulingEnabled: (b: boolean) => void;
@@ -319,13 +346,14 @@ export interface SettingsAppliers {
319
346
  setStrictAgentFiles: (b: boolean) => void;
320
347
  setDisableDefaultAgents: (b: boolean) => void;
321
348
  setToolDescriptionMode: (mode: ToolDescriptionMode) => void;
322
- setFleetView: (b: boolean) => void;
349
+ setWidgetPlacement: (placement: WidgetPlacement) => void;
323
350
  setAgentMentions: (mode: AgentMentionMode) => void;
324
351
  setRememberAgents: (b: boolean) => void;
325
352
  setWidgetMode: (mode: WidgetMode) => void;
326
353
  setOutputTranscript: (b: boolean) => void;
327
354
  setWorktreeIsolation: (b: boolean) => void;
328
355
  setWorkflowsEnabled: (b: boolean) => void;
356
+ setWorkflowDefaultAgentType: (agentType: string) => void;
329
357
  setMaxSubagentDepth: (n: number) => void;
330
358
  setFallbackSubagent: (v: string | undefined) => void;
331
359
  setReportUsage: (b: boolean) => void;
@@ -340,6 +368,7 @@ export type SettingsEmit = (event: string, payload: unknown) => void;
340
368
  const VALID_JOIN_MODES: ReadonlySet<string> = new Set<JoinMode>(["async", "group", "smart"]);
341
369
  const VALID_TOOL_DESCRIPTION_MODES: ReadonlySet<string> = new Set<ToolDescriptionMode>(["full", "compact", "custom"]);
342
370
  const VALID_WIDGET_MODES: ReadonlySet<string> = new Set<WidgetMode>(["all", "background", "off"]);
371
+ const VALID_WIDGET_PLACEMENTS: ReadonlySet<string> = new Set<WidgetPlacement>(["above", "below"]);
343
372
  const VALID_VIEWER_MARKDOWN_MODES: ReadonlySet<string> = new Set<ViewerMarkdownMode>(["off", "assistant", "all"]);
344
373
  const VALID_AGENT_MENTION_MODES: ReadonlySet<string> = new Set<AgentMentionMode>(["model", "direct", "off"]);
345
374
 
@@ -386,6 +415,9 @@ function sanitize(raw: unknown): SubagentsSettings {
386
415
  ) {
387
416
  out.graceTurns = r.graceTurns as number;
388
417
  }
418
+ if (typeof r.allowPerCallTurnLimits === "boolean") {
419
+ out.allowPerCallTurnLimits = r.allowPerCallTurnLimits;
420
+ }
389
421
  if (
390
422
  Number.isInteger(r.maxSubagentDepth) &&
391
423
  (r.maxSubagentDepth as number) >= 0 &&
@@ -414,9 +446,6 @@ function sanitize(raw: unknown): SubagentsSettings {
414
446
  if (typeof r.toolDescriptionMode === "string" && VALID_TOOL_DESCRIPTION_MODES.has(r.toolDescriptionMode)) {
415
447
  out.toolDescriptionMode = r.toolDescriptionMode as ToolDescriptionMode;
416
448
  }
417
- if (typeof r.fleetView === "boolean") {
418
- out.fleetView = r.fleetView;
419
- }
420
449
  // Was a boolean before the `model` mode existed. A hand-written or
421
450
  // previously-written `true` means "on", which is now the default `model`.
422
451
  if (typeof r.agentMentions === "boolean") {
@@ -430,6 +459,9 @@ function sanitize(raw: unknown): SubagentsSettings {
430
459
  if (typeof r.widgetMode === "string" && VALID_WIDGET_MODES.has(r.widgetMode)) {
431
460
  out.widgetMode = r.widgetMode as WidgetMode;
432
461
  }
462
+ if (typeof r.widgetPlacement === "string" && VALID_WIDGET_PLACEMENTS.has(r.widgetPlacement)) {
463
+ out.widgetPlacement = r.widgetPlacement as WidgetPlacement;
464
+ }
433
465
  if (typeof r.outputTranscript === "boolean") {
434
466
  out.outputTranscript = r.outputTranscript;
435
467
  }
@@ -451,6 +483,12 @@ function sanitize(raw: unknown): SubagentsSettings {
451
483
  if (typeof r.workflowsEnabled === "boolean") {
452
484
  out.workflowsEnabled = r.workflowsEnabled;
453
485
  }
486
+ if (typeof r.workflowDefaultAgentType === "string" && r.workflowDefaultAgentType.trim()) {
487
+ // Trimmed like `fallbackSubagent` above: a hand-edited file's stray spaces
488
+ // are not part of the role name, and passing them through would turn a
489
+ // valid-looking setting into an unknown-type rejection at spawn.
490
+ out.workflowDefaultAgentType = r.workflowDefaultAgentType.trim();
491
+ }
454
492
  if (r.fallbackSubagent === false) {
455
493
  // The only non-string spelling worth accepting: a boolean would otherwise be
456
494
  // dropped, silently leaving the PERMISSIVE default in place. Every string is
@@ -517,6 +555,10 @@ export function applySettings(s: SubagentsSettings, appliers: SettingsAppliers):
517
555
  }
518
556
  if (typeof s.defaultMaxTurns === "number") appliers.setDefaultMaxTurns(s.defaultMaxTurns);
519
557
  if (typeof s.graceTurns === "number") appliers.setGraceTurns(s.graceTurns);
558
+ // Applied unconditionally, unlike the optional fields around it: caller caps
559
+ // are a policy, not a personal preference, and a different session/project
560
+ // whose file omits the key must not inherit the previous project's `true`.
561
+ appliers.setAllowPerCallTurnLimits(s.allowPerCallTurnLimits ?? false);
520
562
  if (typeof s.maxSubagentDepth === "number") appliers.setMaxSubagentDepth(s.maxSubagentDepth);
521
563
  if (typeof s.fallbackSubagent === "string") appliers.setFallbackSubagent(s.fallbackSubagent);
522
564
  if (s.defaultJoinMode) appliers.setDefaultJoinMode(s.defaultJoinMode);
@@ -526,10 +568,10 @@ export function applySettings(s: SubagentsSettings, appliers: SettingsAppliers):
526
568
  if (typeof s.strictAgentFiles === "boolean") appliers.setStrictAgentFiles(s.strictAgentFiles);
527
569
  if (typeof s.disableDefaultAgents === "boolean") appliers.setDisableDefaultAgents(s.disableDefaultAgents);
528
570
  if (s.toolDescriptionMode) appliers.setToolDescriptionMode(s.toolDescriptionMode);
529
- if (typeof s.fleetView === "boolean") appliers.setFleetView(s.fleetView);
530
571
  if (s.agentMentions) appliers.setAgentMentions(s.agentMentions);
531
572
  if (typeof s.rememberAgents === "boolean") appliers.setRememberAgents(s.rememberAgents);
532
573
  if (s.widgetMode) appliers.setWidgetMode(s.widgetMode);
574
+ if (s.widgetPlacement) appliers.setWidgetPlacement(s.widgetPlacement);
533
575
  if (typeof s.outputTranscript === "boolean") appliers.setOutputTranscript(s.outputTranscript);
534
576
  if (typeof s.worktreeIsolation === "boolean") appliers.setWorktreeIsolation(s.worktreeIsolation);
535
577
  if (typeof s.reportUsage === "boolean") appliers.setReportUsage(s.reportUsage);
@@ -537,6 +579,9 @@ export function applySettings(s: SubagentsSettings, appliers: SettingsAppliers):
537
579
  if (typeof s.showModel === "boolean") appliers.setShowModel(s.showModel);
538
580
  if (s.viewerMarkdown) appliers.setViewerMarkdown(s.viewerMarkdown);
539
581
  if (typeof s.workflowsEnabled === "boolean") appliers.setWorkflowsEnabled(s.workflowsEnabled);
582
+ if (typeof s.workflowDefaultAgentType === "string" && s.workflowDefaultAgentType.trim()) {
583
+ appliers.setWorkflowDefaultAgentType(s.workflowDefaultAgentType.trim());
584
+ }
540
585
  }
541
586
 
542
587
  /**
@@ -23,7 +23,7 @@ import { existsSync, readdirSync } from "node:fs";
23
23
  import { homedir } from "node:os";
24
24
  import { join } from "node:path";
25
25
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
26
- import { isSymlink, isUnsafeName, safeReadFile } from "./memory.js";
26
+ import { isSymlink, isUnsafeName, safeReadFile } from "./memory.ts";
27
27
 
28
28
  export interface PreloadedSkill {
29
29
  name: string;
@@ -4,8 +4,8 @@ import { homedir } from "node:os";
4
4
  import { basename, dirname, join, resolve } from "node:path";
5
5
  import type { Api, AssistantMessage, Model } from "@earendil-works/pi-ai";
6
6
  import type { AgentSession, ExtensionContext, LoadExtensionsResult, SettingsManager } from "@earendil-works/pi-coding-agent";
7
- import { resolveModel } from "./model-resolver.js";
8
- import { checkModelScope } from "./model-scope.js";
7
+ import { resolveModel } from "./model-resolver.ts";
8
+ import { checkModelScope } from "./model-scope.ts";
9
9
 
10
10
  export type RecoveryOwnership = "absent" | "present" | "unknown";
11
11
  export interface StandalonePolicy {
@@ -8,7 +8,7 @@
8
8
  * through agent-runner).
9
9
  */
10
10
 
11
- import type { AgentRecord } from "./types.js";
11
+ import type { AgentRecord } from "./types.ts";
12
12
 
13
13
  /**
14
14
  * Explicit parenthetical note for a non-normal terminal outcome, so the parent
@@ -26,7 +26,7 @@
26
26
  */
27
27
 
28
28
  import { defineTool, type ToolDefinition } from "@earendil-works/pi-coding-agent";
29
- import type { CompiledSchema } from "./workflow/json-schema.js";
29
+ import type { CompiledSchema } from "./workflow/json-schema.ts";
30
30
 
31
31
  /**
32
32
  * Deliberately NOT added to `SUBAGENT_TOOL_NAMES`: that list becomes