@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/dist/schedule.js CHANGED
@@ -16,12 +16,21 @@
16
16
  */
17
17
  import { Cron } from "croner";
18
18
  import { nanoid } from "nanoid";
19
- import { normalizeMaxTurns } from "./agent-runner.js";
19
+ import { getAllowPerCallTurnLimits, resolveEffectiveMaxTurns } from "./agent-runner.js";
20
20
  import { resolveSpawnType } from "./agent-types.js";
21
21
  import { resolveModel } from "./model-resolver.js";
22
+ const MAX_TIMER_DELAY_MS = 2_147_483_647;
23
+ function timerDelayError(delayMs) {
24
+ return `Schedule delay ${delayMs}ms exceeds Node's maximum timer delay of ${MAX_TIMER_DELAY_MS}ms; use a shorter delay.`;
25
+ }
26
+ function assertSupportedTimerDelay(delayMs) {
27
+ if (delayMs > MAX_TIMER_DELAY_MS)
28
+ throw new Error(timerDelayError(delayMs));
29
+ }
22
30
  export class SubagentScheduler {
23
31
  jobs = new Map();
24
32
  intervals = new Map();
33
+ activeRuns = new Set();
25
34
  store;
26
35
  pi;
27
36
  ctx;
@@ -83,32 +92,31 @@ export class SubagentScheduler {
83
92
  };
84
93
  }
85
94
  /** Add a job, persist, and arm if enabled. Returns the stored job. */
86
- addJob(input) {
95
+ async addJob(input) {
87
96
  const store = this.requireStore();
88
- if (store.hasName(input.name)) {
89
- throw new Error(`A scheduled job named "${input.name}" already exists.`);
90
- }
91
97
  const job = this.buildJob(input);
92
- store.add(job);
98
+ const added = await store.addUnlessNameExists(job);
99
+ if (!added)
100
+ throw new Error(`A scheduled job named "${input.name}" already exists.`);
93
101
  if (job.enabled)
94
102
  this.scheduleJob(job);
95
103
  this.emit({ type: "added", job });
96
104
  return job;
97
105
  }
98
- removeJob(id) {
106
+ async removeJob(id) {
99
107
  const store = this.requireStore();
100
108
  if (!store.get(id))
101
109
  return false;
102
110
  this.unscheduleJob(id);
103
- const ok = store.remove(id);
111
+ const ok = await store.remove(id);
104
112
  if (ok)
105
113
  this.emit({ type: "removed", jobId: id });
106
114
  return ok;
107
115
  }
108
116
  /** Toggle / mutate a job. Re-arms based on the new `enabled` state. */
109
- updateJob(id, patch) {
117
+ async updateJob(id, patch) {
110
118
  const store = this.requireStore();
111
- const updated = store.update(id, patch);
119
+ const updated = await store.update(id, patch);
112
120
  if (!updated)
113
121
  return undefined;
114
122
  this.unscheduleJob(id);
@@ -143,38 +151,52 @@ export class SubagentScheduler {
143
151
  return;
144
152
  try {
145
153
  if (job.scheduleType === "interval" && job.intervalMs) {
146
- const t = setInterval(() => this.executeJob(job.id), job.intervalMs);
154
+ if (job.intervalMs > MAX_TIMER_DELAY_MS) {
155
+ void this.disableJobWithError(job, store, timerDelayError(job.intervalMs)).catch(err => this.reportError(job.id, err));
156
+ return;
157
+ }
158
+ const t = setInterval(() => this.dispatchJob(job.id), job.intervalMs);
147
159
  this.intervals.set(job.id, t);
148
160
  }
149
161
  else if (job.scheduleType === "once") {
150
162
  const target = new Date(job.schedule).getTime();
151
163
  const delay = target - Date.now();
152
- if (delay > 0) {
153
- const t = setTimeout(() => {
154
- this.executeJob(job.id);
155
- // Auto-disable one-shots after they fire (mirrors pi-cron-schedule)
156
- store.update(job.id, { enabled: false });
157
- const updated = store.get(job.id);
158
- if (updated)
159
- this.emit({ type: "updated", job: updated });
160
- }, delay);
164
+ if (delay > MAX_TIMER_DELAY_MS) {
165
+ void this.disableJobWithError(job, store, timerDelayError(delay)).catch(err => this.reportError(job.id, err));
166
+ }
167
+ else if (delay > 0) {
168
+ const t = setTimeout(() => this.executeOnce(job.id, store).catch(err => this.reportError(job.id, err)), delay);
161
169
  this.intervals.set(job.id, t);
162
170
  }
163
171
  else {
164
172
  // Past timestamp — disable, mark error, never fire
165
- store.update(job.id, { enabled: false, lastStatus: "error" });
166
- this.emit({ type: "error", jobId: job.id, error: `Scheduled time ${job.schedule} is in the past` });
173
+ void this.disableJobWithError(job, store, `Scheduled time ${job.schedule} is in the past`).catch(err => this.reportError(job.id, err));
167
174
  }
168
175
  }
169
176
  else {
170
- const cron = new Cron(job.schedule, () => this.executeJob(job.id));
177
+ const cron = new Cron(job.schedule, () => this.dispatchJob(job.id));
171
178
  this.jobs.set(job.id, cron);
172
179
  }
173
180
  }
174
181
  catch (err) {
175
- this.emit({ type: "error", jobId: job.id, error: err instanceof Error ? err.message : String(err) });
182
+ this.reportError(job.id, err);
176
183
  }
177
184
  }
185
+ dispatchJob(id) {
186
+ return this.executeJob(id).catch(err => this.reportError(id, err));
187
+ }
188
+ async executeOnce(id, store) {
189
+ const execution = this.executeJob(id).catch(err => this.reportError(id, err));
190
+ // Auto-disable after dispatch, without waiting for a long-running agent.
191
+ const updated = await store.update(id, { enabled: false });
192
+ if (updated)
193
+ this.emit({ type: "updated", job: updated });
194
+ await execution;
195
+ }
196
+ async disableJobWithError(job, store, error) {
197
+ await store.update(job.id, { enabled: false, lastStatus: "error" });
198
+ this.emit({ type: "error", jobId: job.id, error });
199
+ }
178
200
  unscheduleJob(id) {
179
201
  const cron = this.jobs.get(id);
180
202
  if (cron) {
@@ -190,10 +212,10 @@ export class SubagentScheduler {
190
212
  }
191
213
  /**
192
214
  * Fire a job: persist running state, spawn (bypassing the concurrency
193
- * queue), persist completion. Fire-and-forget: the timer tick returns
194
- * immediately so other jobs keep firing.
215
+ * queue), persist completion. The in-memory guard covers the complete run,
216
+ * so persisted `running` state from a previous process never blocks recovery.
195
217
  */
196
- executeJob(id) {
218
+ async executeJob(id) {
197
219
  const store = this.store;
198
220
  const pi = this.pi;
199
221
  const ctx = this.ctx;
@@ -203,33 +225,45 @@ export class SubagentScheduler {
203
225
  const job = store.get(id);
204
226
  if (!job?.enabled)
205
227
  return;
206
- store.update(id, { lastStatus: "running" });
207
- // Resolve model at fire time — registry contents may have changed since the
208
- // job was created (auth added/removed). Fall back silently to spawn-default
209
- // if resolution fails; the spawn path handles undefined model gracefully.
210
- let resolvedModel;
211
- if (job.model) {
212
- const r = resolveModel(job.model, ctx.modelRegistry);
213
- if (typeof r !== "string")
214
- resolvedModel = r;
228
+ if (this.activeRuns.has(id)) {
229
+ this.emit({ type: "skipped", jobId: id, name: job.name, reason: "overlap" });
230
+ return;
215
231
  }
216
- let agentId;
232
+ this.activeRuns.add(id);
217
233
  try {
234
+ await store.update(id, { lastStatus: "running" });
235
+ // Resolve model at fire time — registry contents may have changed since the
236
+ // job was created (auth added/removed). Fall back silently to spawn-default
237
+ // if resolution fails; the spawn path handles undefined model gracefully.
238
+ let resolvedModel;
239
+ if (job.model) {
240
+ const r = resolveModel(job.model, ctx.modelRegistry);
241
+ if (typeof r !== "string")
242
+ resolvedModel = r;
243
+ }
218
244
  // Re-resolve at fire time against the registry as it stands. This does not
219
245
  // reload from disk (the scheduler has no reason to rebuild process-global
220
246
  // state from a timer), so it catches changes that went through /agents or
221
- // an Agent call — not a file deleted directly from a shell. The catch below turns
222
- // this into lastStatus: "error" plus an error event, like any other
223
- // fire-time failure.
247
+ // an Agent call — not a file deleted directly from a shell.
224
248
  const dispatch = resolveSpawnType(job.subagent_type);
225
249
  if (!dispatch.ok)
226
250
  throw new Error(dispatch.message);
227
- agentId = manager.spawn(pi, ctx, dispatch.type, job.prompt, {
251
+ // Caller caps are a policy opt-in. Re-check at fire time rather than
252
+ // trusting the stored job: the switch can change after creation, and a
253
+ // job persisted while caps were allowed must not keep enforcing its cap
254
+ // after the user turns them off. When off, the runner still applies the
255
+ // agent's own or the project's configured budget (passing undefined).
256
+ const forwardedMaxTurns = getAllowPerCallTurnLimits() ? job.max_turns : undefined;
257
+ // Snapshot the budget that will actually be enforced, not the ignored job
258
+ // field — role/default resolution otherwise lives only in the runner and
259
+ // the conversation viewer would report a cap no longer applied.
260
+ const effectiveMaxTurns = resolveEffectiveMaxTurns(dispatch.type, forwardedMaxTurns);
261
+ const agentId = manager.spawn(pi, ctx, dispatch.type, job.prompt, {
228
262
  description: job.description,
229
263
  isBackground: true,
230
264
  bypassQueue: true,
231
265
  model: resolvedModel,
232
- maxTurns: job.max_turns,
266
+ maxTurns: forwardedMaxTurns,
233
267
  isolated: job.isolated,
234
268
  thinkingLevel: job.thinking,
235
269
  isolation: job.isolation,
@@ -240,45 +274,67 @@ export class SubagentScheduler {
240
274
  // would only be right until then.
241
275
  invocation: {
242
276
  thinking: job.thinking,
243
- // Normalized like the Agent tool's own snapshot: `0` means unlimited,
244
- // and rendering it as "max turns: 0" would read as a limit of none.
245
- maxTurns: normalizeMaxTurns(job.max_turns),
277
+ // Already normalized and resolved for the configured/global fallback;
278
+ // `0` and an ignored stored cap both land as undefined.
279
+ maxTurns: effectiveMaxTurns,
246
280
  isolated: job.isolated,
247
281
  runInBackground: true,
248
282
  isolation: job.isolation,
249
283
  },
250
284
  });
285
+ this.emit({ type: "fired", jobId: id, agentId, name: job.name });
286
+ // AgentManager's promise resolves either way (its .catch returns ""), so we
287
+ // can't infer success/failure from the promise — read record.status instead.
288
+ // Terminal states: completed/steered = success; error/aborted/stopped = error.
289
+ // awaitStartup first: with isolation: "worktree" the run promise only exists
290
+ // once the repo copy is made, and a failed copy rejects here.
291
+ let status;
292
+ try {
293
+ await manager.awaitStartup(agentId);
294
+ await manager.getRecord(agentId)?.promise;
295
+ const r = manager.getRecord(agentId);
296
+ const failed = r?.status === "error" || r?.status === "aborted" || r?.status === "stopped";
297
+ status = failed ? "error" : "success";
298
+ }
299
+ catch {
300
+ status = "error";
301
+ }
302
+ await this.finalizeRun(store, id, status);
251
303
  }
252
304
  catch (err) {
253
- const error = err instanceof Error ? err.message : String(err);
254
- store.update(id, { lastRun: new Date().toISOString(), lastStatus: "error" });
255
- this.emit({ type: "error", jobId: id, error });
305
+ await this.recordRunError(store, id, err);
306
+ }
307
+ finally {
308
+ this.activeRuns.delete(id);
309
+ }
310
+ }
311
+ async finalizeRun(store, id, status) {
312
+ const lastRun = new Date().toISOString();
313
+ const current = store.get(id);
314
+ const next = current?.scheduleType === "interval" && current.intervalMs
315
+ ? new Date(new Date(lastRun).getTime() + current.intervalMs).toISOString()
316
+ : this.getNextRun(id);
317
+ await store.update(id, {
318
+ lastRun,
319
+ lastStatus: status,
320
+ runCount: (current?.runCount ?? 0) + 1,
321
+ nextRun: next,
322
+ });
323
+ }
324
+ async recordRunError(store, id, err) {
325
+ const error = err instanceof Error ? err.message : String(err);
326
+ try {
327
+ await store.update(id, { lastRun: new Date().toISOString(), lastStatus: "error" });
328
+ }
329
+ catch (persistErr) {
330
+ const detail = persistErr instanceof Error ? persistErr.message : String(persistErr);
331
+ this.emit({ type: "error", jobId: id, error: `${error}; failed to persist schedule status: ${detail}` });
256
332
  return;
257
333
  }
258
- this.emit({ type: "fired", jobId: id, agentId, name: job.name });
259
- const finalize = (status) => {
260
- const next = this.getNextRun(id);
261
- const current = store.get(id);
262
- store.update(id, {
263
- lastRun: new Date().toISOString(),
264
- lastStatus: status,
265
- runCount: (current?.runCount ?? 0) + 1,
266
- nextRun: next,
267
- });
268
- };
269
- // AgentManager's promise resolves either way (its .catch returns ""), so we
270
- // can't infer success/failure from the promise — read record.status instead.
271
- // Terminal states: completed/steered = success; error/aborted/stopped = error.
272
- // awaitStartup first: with isolation: "worktree" the run promise only exists
273
- // once the repo copy is made, and a failed copy rejects here.
274
- manager.awaitStartup(agentId)
275
- .then(() => manager.getRecord(agentId)?.promise)
276
- .then(() => {
277
- const r = manager.getRecord(agentId);
278
- const failed = r?.status === "error" || r?.status === "aborted" || r?.status === "stopped";
279
- finalize(failed ? "error" : "success");
280
- })
281
- .catch(() => finalize("error"));
334
+ this.emit({ type: "error", jobId: id, error });
335
+ }
336
+ reportError(id, err) {
337
+ this.emit({ type: "error", jobId: id, error: err instanceof Error ? err.message : String(err) });
282
338
  }
283
339
  emit(event) {
284
340
  if (this.pi)
@@ -311,9 +367,11 @@ export class SubagentScheduler {
311
367
  if (/^\d{4}-\d{2}-\d{2}T/.test(trimmed)) {
312
368
  const d = new Date(trimmed);
313
369
  if (!Number.isNaN(d.getTime())) {
314
- if (d.getTime() <= Date.now()) {
370
+ const delay = d.getTime() - Date.now();
371
+ if (delay <= 0) {
315
372
  throw new Error(`Scheduled time ${d.toISOString()} is in the past.`);
316
373
  }
374
+ assertSupportedTimerDelay(delay);
317
375
  return { type: "once", normalized: d.toISOString() };
318
376
  }
319
377
  }
@@ -347,6 +405,7 @@ export class SubagentScheduler {
347
405
  if (!m)
348
406
  return null;
349
407
  const ms = parseInt(m[1], 10) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2]];
408
+ assertSupportedTimerDelay(ms);
350
409
  return new Date(Date.now() + ms).toISOString();
351
410
  }
352
411
  /** "10s"/"5m"/"1h"/"2d" → milliseconds. */
@@ -354,6 +413,8 @@ export class SubagentScheduler {
354
413
  const m = s.match(/^(\d+)(s|m|h|d)$/);
355
414
  if (!m)
356
415
  return null;
357
- return parseInt(m[1], 10) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2]];
416
+ const ms = parseInt(m[1], 10) * { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 }[m[2]];
417
+ assertSupportedTimerDelay(ms);
418
+ return ms;
358
419
  }
359
420
  }
@@ -1,4 +1,4 @@
1
- import type { AgentMentionMode, JoinMode, ViewerMarkdownMode, WidgetMode } from "./types.js";
1
+ import type { AgentMentionMode, JoinMode, ViewerMarkdownMode, WidgetMode, WidgetPlacement } from "./types.ts";
2
2
  export interface SubagentsSettings {
3
3
  maxConcurrent?: number;
4
4
  /**
@@ -30,6 +30,16 @@ export interface SubagentsSettings {
30
30
  */
31
31
  defaultMaxTurns?: number;
32
32
  graceTurns?: number;
33
+ /**
34
+ * Whether `Agent`/nested `max_turns` parameters (and RPC `maxTurns` options)
35
+ * may impose a per-call turn budget. Defaults to `false`.
36
+ *
37
+ * Off keeps the configured budget authoritative: agent-file `max_turns` and
38
+ * `defaultMaxTurns` apply, the parameter is omitted from both tool schemas,
39
+ * and a runtime call that bypasses schema validation still has its cap
40
+ * dropped. Turn it on to restore the historical caller-cap behaviour.
41
+ */
42
+ allowPerCallTurnLimits?: boolean;
33
43
  defaultJoinMode?: JoinMode;
34
44
  /**
35
45
  * Whether a top-level `Agent` spawn that doesn't say runs detached.
@@ -109,12 +119,6 @@ export interface SubagentsSettings {
109
119
  * next pi session.
110
120
  */
111
121
  toolDescriptionMode?: ToolDescriptionMode;
112
- /**
113
- * Whether the Claude Code-style FleetView (the navigable main+subagents list
114
- * rendered below the editor) is shown. Defaults to `true`. Pure-UI: when off,
115
- * the list never registers and the global key handler never captures input.
116
- */
117
- fleetView?: boolean;
118
122
  /**
119
123
  * Whether `@handle message` typed at the prompt is routed to that subagent
120
124
  * instead of the main model, and whether `@` offers running agents alongside
@@ -144,16 +148,20 @@ export interface SubagentsSettings {
144
148
  */
145
149
  rememberAgents?: boolean;
146
150
  /**
147
- * Display mode for the persistent above-editor agent widget:
151
+ * Display mode for the persistent agent widget:
148
152
  * - `all`: show every agent (foreground + background).
149
153
  * - `background`: hide foreground agents — they already render inline as the
150
154
  * Agent tool result, so the widget would otherwise double-render them
151
155
  * (#118); everything else (background, queued, scheduled, RPC) stays.
152
156
  * - `off`: hide the widget entirely.
153
- * Defaults to `background`. Pure-UI and applied live (toggling refreshes the
157
+ * `background` filtering never gates `←` → Agent Hub (the key follows the
158
+ * Hub's content); `off` stands the key down with the list.
159
+ * Defaults to `all`. Pure-UI and applied live (toggling refreshes the
154
160
  * widget).
155
161
  */
156
162
  widgetMode?: WidgetMode;
163
+ /** Compact list placement relative to the editor. Defaults to `above`; applied live. */
164
+ widgetPlacement?: WidgetPlacement;
157
165
  /**
158
166
  * Project/global default for writing each subagent's `.output` transcript
159
167
  * (a JSON-lines copy of the run, stored under the OS temp dir).
@@ -209,6 +217,24 @@ export interface SubagentsSettings {
209
217
  * fixed once pi has it.
210
218
  */
211
219
  workflowsEnabled?: boolean;
220
+ /**
221
+ * Agent type a workflow's `agent()` call uses when it names no `agentType` of
222
+ * its own. Defaults to `task`, the economical workflow role
223
+ * (`DEFAULT_WORKFLOW_AGENT_TYPE` in workflow/runtime.ts).
224
+ *
225
+ * The precedence is per-run, not global: a `SubagentWorkflow(agentType)` on
226
+ * the call outranks this, a run that resumes another inherits THAT run's
227
+ * frozen choice, and a script's `agent(prompt, { agentType })` outranks all
228
+ * three. Only "unspecified" reads this setting.
229
+ *
230
+ * Kept as a name rather than validated against the registry on load: agent
231
+ * files are added, renamed and disabled mid-session, and a stored name that is
232
+ * temporarily unavailable must survive an unrelated settings save instead of
233
+ * being rewritten to a cheaper-looking role. Resolution stays at spawn time;
234
+ * an unavailable workflow default fails closed instead of using the general
235
+ * fallbackSubagent policy.
236
+ */
237
+ workflowDefaultAgentType?: string;
212
238
  /**
213
239
  * Hard ceiling on nested subagent delegation, counted from the main session:
214
240
  * main = 0, its subagents = 1, their children = 2. Defaults to `2`; `0` or `1`
@@ -257,7 +283,7 @@ export interface SubagentsSettings {
257
283
  reportUsage?: boolean;
258
284
  /**
259
285
  * Whether the subagent surfaces show an estimated dollar cost next to their
260
- * token counts (widget, FleetView, conversation viewer, foreground results,
286
+ * token counts (widget, Agent Hub, conversation viewer, foreground results,
261
287
  * completion notifications). Defaults to `false`. Applied live.
262
288
  *
263
289
  * Rendered as `~$0.0042` — the tilde marks it as pi's reported estimate
@@ -300,6 +326,7 @@ export interface SettingsAppliers {
300
326
  setMaxConcurrentForeground: (n: number) => void;
301
327
  setDefaultMaxTurns: (n: number) => void;
302
328
  setGraceTurns: (n: number) => void;
329
+ setAllowPerCallTurnLimits: (b: boolean) => void;
303
330
  setDefaultJoinMode: (mode: JoinMode) => void;
304
331
  setBackgroundByDefault: (b: boolean) => void;
305
332
  setSchedulingEnabled: (b: boolean) => void;
@@ -307,13 +334,14 @@ export interface SettingsAppliers {
307
334
  setStrictAgentFiles: (b: boolean) => void;
308
335
  setDisableDefaultAgents: (b: boolean) => void;
309
336
  setToolDescriptionMode: (mode: ToolDescriptionMode) => void;
310
- setFleetView: (b: boolean) => void;
337
+ setWidgetPlacement: (placement: WidgetPlacement) => void;
311
338
  setAgentMentions: (mode: AgentMentionMode) => void;
312
339
  setRememberAgents: (b: boolean) => void;
313
340
  setWidgetMode: (mode: WidgetMode) => void;
314
341
  setOutputTranscript: (b: boolean) => void;
315
342
  setWorktreeIsolation: (b: boolean) => void;
316
343
  setWorkflowsEnabled: (b: boolean) => void;
344
+ setWorkflowDefaultAgentType: (agentType: string) => void;
317
345
  setMaxSubagentDepth: (n: number) => void;
318
346
  setFallbackSubagent: (v: string | undefined) => void;
319
347
  setReportUsage: (b: boolean) => void;
package/dist/settings.js CHANGED
@@ -8,6 +8,7 @@ import { NO_FALLBACK } from "./agent-types.js";
8
8
  const VALID_JOIN_MODES = new Set(["async", "group", "smart"]);
9
9
  const VALID_TOOL_DESCRIPTION_MODES = new Set(["full", "compact", "custom"]);
10
10
  const VALID_WIDGET_MODES = new Set(["all", "background", "off"]);
11
+ const VALID_WIDGET_PLACEMENTS = new Set(["above", "below"]);
11
12
  const VALID_VIEWER_MARKDOWN_MODES = new Set(["off", "assistant", "all"]);
12
13
  const VALID_AGENT_MENTION_MODES = new Set(["model", "direct", "off"]);
13
14
  // Sanity ceilings — prevent hand-edited configs from asking for values that
@@ -45,6 +46,9 @@ function sanitize(raw) {
45
46
  r.graceTurns <= GRACE_TURNS_CEILING) {
46
47
  out.graceTurns = r.graceTurns;
47
48
  }
49
+ if (typeof r.allowPerCallTurnLimits === "boolean") {
50
+ out.allowPerCallTurnLimits = r.allowPerCallTurnLimits;
51
+ }
48
52
  if (Number.isInteger(r.maxSubagentDepth) &&
49
53
  r.maxSubagentDepth >= 0 &&
50
54
  r.maxSubagentDepth <= SUBAGENT_DEPTH_CEILING) {
@@ -71,9 +75,6 @@ function sanitize(raw) {
71
75
  if (typeof r.toolDescriptionMode === "string" && VALID_TOOL_DESCRIPTION_MODES.has(r.toolDescriptionMode)) {
72
76
  out.toolDescriptionMode = r.toolDescriptionMode;
73
77
  }
74
- if (typeof r.fleetView === "boolean") {
75
- out.fleetView = r.fleetView;
76
- }
77
78
  // Was a boolean before the `model` mode existed. A hand-written or
78
79
  // previously-written `true` means "on", which is now the default `model`.
79
80
  if (typeof r.agentMentions === "boolean") {
@@ -88,6 +89,9 @@ function sanitize(raw) {
88
89
  if (typeof r.widgetMode === "string" && VALID_WIDGET_MODES.has(r.widgetMode)) {
89
90
  out.widgetMode = r.widgetMode;
90
91
  }
92
+ if (typeof r.widgetPlacement === "string" && VALID_WIDGET_PLACEMENTS.has(r.widgetPlacement)) {
93
+ out.widgetPlacement = r.widgetPlacement;
94
+ }
91
95
  if (typeof r.outputTranscript === "boolean") {
92
96
  out.outputTranscript = r.outputTranscript;
93
97
  }
@@ -109,6 +113,12 @@ function sanitize(raw) {
109
113
  if (typeof r.workflowsEnabled === "boolean") {
110
114
  out.workflowsEnabled = r.workflowsEnabled;
111
115
  }
116
+ if (typeof r.workflowDefaultAgentType === "string" && r.workflowDefaultAgentType.trim()) {
117
+ // Trimmed like `fallbackSubagent` above: a hand-edited file's stray spaces
118
+ // are not part of the role name, and passing them through would turn a
119
+ // valid-looking setting into an unknown-type rejection at spawn.
120
+ out.workflowDefaultAgentType = r.workflowDefaultAgentType.trim();
121
+ }
112
122
  if (r.fallbackSubagent === false) {
113
123
  // The only non-string spelling worth accepting: a boolean would otherwise be
114
124
  // dropped, silently leaving the PERMISSIVE default in place. Every string is
@@ -176,6 +186,10 @@ export function applySettings(s, appliers) {
176
186
  appliers.setDefaultMaxTurns(s.defaultMaxTurns);
177
187
  if (typeof s.graceTurns === "number")
178
188
  appliers.setGraceTurns(s.graceTurns);
189
+ // Applied unconditionally, unlike the optional fields around it: caller caps
190
+ // are a policy, not a personal preference, and a different session/project
191
+ // whose file omits the key must not inherit the previous project's `true`.
192
+ appliers.setAllowPerCallTurnLimits(s.allowPerCallTurnLimits ?? false);
179
193
  if (typeof s.maxSubagentDepth === "number")
180
194
  appliers.setMaxSubagentDepth(s.maxSubagentDepth);
181
195
  if (typeof s.fallbackSubagent === "string")
@@ -194,14 +208,14 @@ export function applySettings(s, appliers) {
194
208
  appliers.setDisableDefaultAgents(s.disableDefaultAgents);
195
209
  if (s.toolDescriptionMode)
196
210
  appliers.setToolDescriptionMode(s.toolDescriptionMode);
197
- if (typeof s.fleetView === "boolean")
198
- appliers.setFleetView(s.fleetView);
199
211
  if (s.agentMentions)
200
212
  appliers.setAgentMentions(s.agentMentions);
201
213
  if (typeof s.rememberAgents === "boolean")
202
214
  appliers.setRememberAgents(s.rememberAgents);
203
215
  if (s.widgetMode)
204
216
  appliers.setWidgetMode(s.widgetMode);
217
+ if (s.widgetPlacement)
218
+ appliers.setWidgetPlacement(s.widgetPlacement);
205
219
  if (typeof s.outputTranscript === "boolean")
206
220
  appliers.setOutputTranscript(s.outputTranscript);
207
221
  if (typeof s.worktreeIsolation === "boolean")
@@ -216,6 +230,9 @@ export function applySettings(s, appliers) {
216
230
  appliers.setViewerMarkdown(s.viewerMarkdown);
217
231
  if (typeof s.workflowsEnabled === "boolean")
218
232
  appliers.setWorkflowsEnabled(s.workflowsEnabled);
233
+ if (typeof s.workflowDefaultAgentType === "string" && s.workflowDefaultAgentType.trim()) {
234
+ appliers.setWorkflowDefaultAgentType(s.workflowDefaultAgentType.trim());
235
+ }
219
236
  }
220
237
  /**
221
238
  * Format the user-facing toast for a settings mutation. Pure function —
@@ -7,7 +7,7 @@
7
7
  * from index.ts (that is the extension entry, and it already reaches these tools
8
8
  * through agent-runner).
9
9
  */
10
- import type { AgentRecord } from "./types.js";
10
+ import type { AgentRecord } from "./types.ts";
11
11
  /**
12
12
  * Explicit parenthetical note for a non-normal terminal outcome, so the parent
13
13
  * agent can't mistake partial output for a completed result. Empty string for a
@@ -25,7 +25,7 @@
25
25
  * `StructuredOutput` is still telling the truth.
26
26
  */
27
27
  import { type ToolDefinition } from "@earendil-works/pi-coding-agent";
28
- import type { CompiledSchema } from "./workflow/json-schema.js";
28
+ import type { CompiledSchema } from "./workflow/json-schema.ts";
29
29
  /**
30
30
  * Deliberately NOT added to `SUBAGENT_TOOL_NAMES`: that list becomes
31
31
  * `EXCLUDED_TOOL_NAMES`, which is exactly the denial this tool has to avoid.
package/dist/types.d.ts CHANGED
@@ -2,8 +2,8 @@
2
2
  * types.ts — Type definitions for the subagent system.
3
3
  */
4
4
  import type { AgentSession } from "@earendil-works/pi-coding-agent";
5
- import type { AdvisorStatus } from "./advisor-status.js";
6
- import type { LifetimeUsage } from "./usage.js";
5
+ import type { AdvisorStatus } from "./advisor-status.ts";
6
+ import type { LifetimeUsage } from "./usage.ts";
7
7
  /** Use the session's full control surface, including the explicit "off" level. */
8
8
  export type ThinkingLevel = AgentSession["thinkingLevel"];
9
9
  /** Agent type: any string name (built-in defaults or user-defined). */
@@ -96,13 +96,15 @@ export interface AgentConfig {
96
96
  }
97
97
  export type JoinMode = 'async' | 'group' | 'smart';
98
98
  /**
99
- * Display mode for the persistent above-editor agent widget.
99
+ * Display mode for the persistent agent widget.
100
100
  * - `all`: show every agent (foreground + background).
101
101
  * - `background`: hide foreground agents (they already render inline as the
102
102
  * Agent tool result, #118); show background/queued/scheduled/RPC.
103
103
  * - `off`: hide the widget entirely.
104
104
  */
105
105
  export type WidgetMode = 'all' | 'background' | 'off';
106
+ /** Placement of the compact agent widget relative to the prompt editor. */
107
+ export type WidgetPlacement = 'above' | 'below';
106
108
  /**
107
109
  * How much of the conversation viewer's transcript is rendered as Markdown.
108
110
  * - `off`: every line wraps as literal text, as it did before the mode existed.
@@ -200,6 +202,13 @@ export interface AgentRecord {
200
202
  startGate?: Promise<void>;
201
203
  groupId?: string;
202
204
  joinMode?: JoinMode;
205
+ /**
206
+ * Run identity within one record: incremented once when a resume starts a new
207
+ * run. Completions, group holds and held nudges captured under an older
208
+ * generation are superseded and must not deliver against this run.
209
+ * Undefined (0) is the initial run.
210
+ */
211
+ runGeneration?: number;
203
212
  /** Set when result was already consumed via get_subagent_result — suppresses completion notification. */
204
213
  resultConsumed?: boolean;
205
214
  /** Steering messages queued before the session was ready. */
@@ -226,6 +235,16 @@ export interface AgentRecord {
226
235
  toolCallId?: string;
227
236
  /** Path to the streaming output transcript file. */
228
237
  outputFile?: string;
238
+ /**
239
+ * Every ancestor agent that owns this record, nearest first, captured at
240
+ * spawn time from the live parent chain.
241
+ *
242
+ * This exists so ownership survives the eviction of an intermediate parent:
243
+ * a grandchild archived after Parent2 is gone still names Parent1, which is
244
+ * what an active cleanup uses to protect the descendant's files. A workflow
245
+ * owner stays on `workflowId`; this list is the agent lineage only.
246
+ */
247
+ ownerIds?: string[];
229
248
  /**
230
249
  * The agent's pi session file, when it was persisted (`persist_session`, or
231
250
  * the `rememberAgents` default). Captured so a mention can reopen the
@@ -288,8 +307,18 @@ export interface AgentRecord {
288
307
  * Session id of the root (main) session this branch descends from. Nested
289
308
  * spawns inherit it so their transcripts file under the same session
290
309
  * directory as their ancestors' instead of the child session's own id.
310
+ *
311
+ * Also pinned for spawns that enter outside the Agent tool (mentions,
312
+ * schedules, RPC) from the session context that started them, so child
313
+ * sessions and their archived provenance share one stable root.
291
314
  */
292
315
  rootSessionId?: string;
316
+ /** Stable root project directory; never a worktree copy's cwd. */
317
+ rootCwd?: string;
318
+ /** The root session's pi JSONL file, when it has one. */
319
+ rootSessionFile?: string;
320
+ /** The child session id, once a session exists. Plain string, never a session. */
321
+ sessionId?: string;
293
322
  }
294
323
  /** Actual session level after SDK model-capability clamping. */
295
324
  export type EffectiveThinkingLevel = ThinkingLevel;
@@ -42,8 +42,8 @@
42
42
  * unaddressable.
43
43
  */
44
44
  import type { AutocompleteProvider } from "@earendil-works/pi-tui";
45
- import type { AgentManager } from "../agent-manager.js";
46
- import type { AgentRecord, AgentTombstone } from "../types.js";
45
+ import type { AgentManager } from "../agent-manager.ts";
46
+ import type { AgentRecord, AgentTombstone } from "../types.ts";
47
47
  /**
48
48
  * One thing `@` can address, and what sending to it will do. `typeLabel` is the
49
49
  * agent's `display_name`, resolved by the caller: this module stays independent