pi-suite 0.0.0-stage → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/README.zh-CN.md +101 -0
  4. package/package.json +63 -4
  5. package/skills/pi-suite-jobs/SKILL.md +76 -0
  6. package/skills/pi-suite-workflow/SKILL.md +114 -0
  7. package/src/agents/catalog.ts +80 -0
  8. package/src/agents/child.ts +79 -0
  9. package/src/agents/commands.ts +17 -0
  10. package/src/agents/defaults.ts +78 -0
  11. package/src/agents/history.ts +112 -0
  12. package/src/agents/index.ts +211 -0
  13. package/src/agents/manager.ts +438 -0
  14. package/src/agents/mentions/clone.ts +51 -0
  15. package/src/agents/mentions/grammar.ts +64 -0
  16. package/src/agents/mentions/index.ts +76 -0
  17. package/src/agents/mentions/provider.ts +79 -0
  18. package/src/agents/model-editor.ts +95 -0
  19. package/src/agents/models.ts +43 -0
  20. package/src/agents/output/schema.ts +101 -0
  21. package/src/agents/output/tool.ts +98 -0
  22. package/src/agents/parent.ts +13 -0
  23. package/src/agents/questions.ts +63 -0
  24. package/src/agents/records.ts +90 -0
  25. package/src/agents/registry.ts +20 -0
  26. package/src/agents/render.ts +85 -0
  27. package/src/agents/resources/context.ts +48 -0
  28. package/src/agents/resources/loader.ts +86 -0
  29. package/src/agents/resources/memory.ts +67 -0
  30. package/src/agents/resources/packages.ts +96 -0
  31. package/src/agents/resources/paths.ts +8 -0
  32. package/src/agents/resources/prompts.ts +11 -0
  33. package/src/agents/resources/scope.ts +147 -0
  34. package/src/agents/resources/selectors.ts +186 -0
  35. package/src/agents/retry.ts +20 -0
  36. package/src/agents/rpc/handlers.ts +62 -0
  37. package/src/agents/rpc/index.ts +73 -0
  38. package/src/agents/rpc/options.ts +44 -0
  39. package/src/agents/run-groups.ts +16 -0
  40. package/src/agents/runner.ts +131 -0
  41. package/src/agents/runtime.ts +40 -0
  42. package/src/agents/schedules/index.ts +136 -0
  43. package/src/agents/schedules/menu.ts +38 -0
  44. package/src/agents/schedules/parse.ts +42 -0
  45. package/src/agents/schedules/store.ts +78 -0
  46. package/src/agents/schema.ts +5 -0
  47. package/src/agents/session.ts +29 -0
  48. package/src/agents/tools.ts +177 -0
  49. package/src/agents/types.ts +87 -0
  50. package/src/agents/ui/index.ts +42 -0
  51. package/src/agents/ui/runs.ts +122 -0
  52. package/src/agents/ui/types.ts +91 -0
  53. package/src/agents/viewer-info.ts +36 -0
  54. package/src/agents/viewer.ts +160 -0
  55. package/src/agents/workflow/collisions.ts +124 -0
  56. package/src/agents/workflow/entry.ts +93 -0
  57. package/src/agents/workflow/host.ts +119 -0
  58. package/src/agents/workflow/index.ts +100 -0
  59. package/src/agents/workflow/journal.ts +147 -0
  60. package/src/agents/workflow/literal.ts +57 -0
  61. package/src/agents/workflow/manager.ts +169 -0
  62. package/src/agents/workflow/meta.ts +323 -0
  63. package/src/agents/workflow/progress/format.ts +184 -0
  64. package/src/agents/workflow/progress/index.ts +3 -0
  65. package/src/agents/workflow/progress/model.ts +224 -0
  66. package/src/agents/workflow/progress/types.ts +144 -0
  67. package/src/agents/workflow/render.ts +46 -0
  68. package/src/agents/workflow/runtime/helpers.ts +236 -0
  69. package/src/agents/workflow/runtime/index.ts +3 -0
  70. package/src/agents/workflow/runtime/run.ts +646 -0
  71. package/src/agents/workflow/runtime/types.ts +273 -0
  72. package/src/agents/workflow/saved.ts +74 -0
  73. package/src/agents/workflow/store.ts +23 -0
  74. package/src/agents/workflow/task.ts +277 -0
  75. package/src/agents/workflow/tool-description.ts +32 -0
  76. package/src/agents/workflow/tools.ts +66 -0
  77. package/src/agents/workflow/ui/menu.ts +144 -0
  78. package/src/agents/workflow/ui/progress.ts +91 -0
  79. package/src/agents/workflow/worker/bootstrap.ts +316 -0
  80. package/src/agents/workflow/worker/flow.ts +218 -0
  81. package/src/agents/workflow/worker/index.ts +7 -0
  82. package/src/agents/workflow/worker/scope.ts +215 -0
  83. package/src/ask/.gitkeep +0 -0
  84. package/src/ask/form.ts +67 -0
  85. package/src/ask/index.ts +73 -0
  86. package/src/ask/keys.ts +32 -0
  87. package/src/ask/layout.ts +78 -0
  88. package/src/ask/queue.ts +40 -0
  89. package/src/ask/render.ts +62 -0
  90. package/src/ask/result.ts +56 -0
  91. package/src/ask/schema.ts +67 -0
  92. package/src/ask/tool-render.ts +49 -0
  93. package/src/ask/view.ts +406 -0
  94. package/src/goal/.gitkeep +0 -0
  95. package/src/goal/activity.ts +50 -0
  96. package/src/goal/commands.ts +75 -0
  97. package/src/goal/context.ts +36 -0
  98. package/src/goal/index.ts +38 -0
  99. package/src/goal/manager.ts +386 -0
  100. package/src/goal/presentation.ts +15 -0
  101. package/src/goal/render.ts +36 -0
  102. package/src/goal/snapshot.ts +78 -0
  103. package/src/goal/state.ts +39 -0
  104. package/src/goal/store.ts +59 -0
  105. package/src/goal/tools.ts +59 -0
  106. package/src/goal/wait.ts +39 -0
  107. package/src/index.ts +20 -0
  108. package/src/jobs/backends/linux-tree.ts +87 -0
  109. package/src/jobs/backends/pipe.ts +74 -0
  110. package/src/jobs/backends/process.ts +79 -0
  111. package/src/jobs/backends/pty-job.ts +45 -0
  112. package/src/jobs/backends/pty.ts +502 -0
  113. package/src/jobs/backends/windows-tree.ts +289 -0
  114. package/src/jobs/commands.ts +7 -0
  115. package/src/jobs/control.ts +13 -0
  116. package/src/jobs/index.ts +331 -0
  117. package/src/jobs/launch/config.ts +26 -0
  118. package/src/jobs/launch/name.ts +16 -0
  119. package/src/jobs/launch/presets.ts +61 -0
  120. package/src/jobs/log-viewer.ts +147 -0
  121. package/src/jobs/manager.ts +507 -0
  122. package/src/jobs/monitors/compile.ts +101 -0
  123. package/src/jobs/monitors/hands-free.ts +108 -0
  124. package/src/jobs/monitors/runtime.ts +165 -0
  125. package/src/jobs/output.ts +54 -0
  126. package/src/jobs/query.ts +62 -0
  127. package/src/jobs/render.ts +103 -0
  128. package/src/jobs/runtime.ts +89 -0
  129. package/src/jobs/state.ts +25 -0
  130. package/src/jobs/store.ts +168 -0
  131. package/src/jobs/terminal/keys.ts +292 -0
  132. package/src/jobs/terminal/protocol.ts +37 -0
  133. package/src/jobs/terminal/read.ts +131 -0
  134. package/src/jobs/terminal/render.ts +70 -0
  135. package/src/jobs/terminal/screen.ts +92 -0
  136. package/src/jobs/terminal/session.ts +100 -0
  137. package/src/jobs/terminal/shell.ts +22 -0
  138. package/src/jobs/terminal/snapshot.ts +8 -0
  139. package/src/jobs/terminal/visible-text.ts +53 -0
  140. package/src/jobs/tools.ts +203 -0
  141. package/src/jobs/types.ts +60 -0
  142. package/src/jobs/viewer/component.ts +209 -0
  143. package/src/jobs/viewer/metadata.ts +9 -0
  144. package/src/jobs/viewer.ts +149 -0
  145. package/src/jobs/workspace.ts +31 -0
  146. package/src/runtime/.gitkeep +0 -0
  147. package/src/runtime/binding.ts +26 -0
  148. package/src/runtime/cli-prompt.ts +24 -0
  149. package/src/runtime/clipboard.ts +16 -0
  150. package/src/runtime/config-edit.ts +31 -0
  151. package/src/runtime/config-fields.ts +65 -0
  152. package/src/runtime/config.ts +111 -0
  153. package/src/runtime/errors.ts +11 -0
  154. package/src/runtime/json-store.ts +156 -0
  155. package/src/runtime/notification-render.ts +35 -0
  156. package/src/runtime/notifications.ts +98 -0
  157. package/src/runtime/owner.ts +54 -0
  158. package/src/runtime/read.ts +200 -0
  159. package/src/runtime/renderers.ts +50 -0
  160. package/src/runtime/responses/index.ts +126 -0
  161. package/src/runtime/responses/payload.ts +101 -0
  162. package/src/runtime/settings/index.ts +24 -0
  163. package/src/runtime/settings/view.ts +84 -0
  164. package/src/runtime/suite.ts +192 -0
  165. package/src/runtime/text.ts +6 -0
  166. package/src/runtime/tools.ts +131 -0
  167. package/src/runtime/wait-render.ts +33 -0
  168. package/src/runtime/wait.ts +134 -0
  169. package/src/tasks/commands.ts +41 -0
  170. package/src/tasks/index.ts +305 -0
  171. package/src/tasks/model.ts +152 -0
  172. package/src/tasks/presentation.ts +40 -0
  173. package/src/tasks/query.ts +38 -0
  174. package/src/tasks/render.ts +54 -0
  175. package/src/tasks/schema.ts +25 -0
  176. package/src/tasks/store.ts +164 -0
  177. package/src/tasks/tools.ts +69 -0
  178. package/src/tasks/types.ts +61 -0
  179. package/src/tasks/viewer.ts +68 -0
  180. package/src/ui/.gitkeep +0 -0
  181. package/src/ui/actions.ts +50 -0
  182. package/src/ui/browser-chrome.ts +175 -0
  183. package/src/ui/browser.ts +292 -0
  184. package/src/ui/details.ts +111 -0
  185. package/src/ui/dock/line.ts +14 -0
  186. package/src/ui/dock/rows.ts +78 -0
  187. package/src/ui/dock.ts +224 -0
  188. package/src/ui/format.ts +25 -0
  189. package/src/ui/frame.ts +8 -0
  190. package/src/ui/inline-input.ts +98 -0
  191. package/src/ui/reading.ts +105 -0
  192. package/src/ui/rendering/builtin-command.ts +34 -0
  193. package/src/ui/rendering/command.ts +60 -0
  194. package/src/ui/rendering/read-page.ts +15 -0
  195. package/src/ui/rendering/shell/bash.ts +281 -0
  196. package/src/ui/rendering/shell/index.ts +24 -0
  197. package/src/ui/rendering/shell/powershell.ts +155 -0
  198. package/src/ui/rendering/shell/spans.ts +28 -0
  199. package/src/ui/scroll.ts +111 -0
  200. package/src/ui/select.ts +67 -0
  201. package/src/ui/status.ts +67 -0
  202. package/src/ui/structured-details.ts +41 -0
  203. package/src/ui/terminal.ts +137 -0
  204. package/src/ui/ticker.ts +18 -0
  205. package/src/ui/tool-render.ts +152 -0
  206. package/src/ui/transcript.ts +140 -0
  207. package/src/ui/viewer/agent-information.ts +34 -0
  208. package/src/ui/viewer/editor.ts +18 -0
  209. package/src/ui/viewer/navigation.ts +25 -0
  210. package/themes/oh-my-pi.json +95 -0
  211. package/third-party/UPSTREAM.md +88 -0
  212. package/third-party/licenses/.gitkeep +0 -0
  213. package/third-party/licenses/oh-my-pi.txt +23 -0
  214. package/third-party/licenses/pi-ask-user.txt +21 -0
  215. package/third-party/licenses/pi-background-jobs.txt +21 -0
  216. package/third-party/licenses/pi-goal.txt +21 -0
  217. package/third-party/licenses/pi-interactive-shell.txt +25 -0
  218. package/third-party/licenses/pi-subagents.txt +21 -0
  219. package/third-party/licenses/pi-tasks.txt +21 -0
  220. package/third-party/sources.json +111 -0
@@ -0,0 +1,136 @@
1
+ // Timer dispatch and lifecycle adapted from @tintinweb/pi-subagents 0.23.0
2
+ // src/schedule.ts/index.ts (MIT).
3
+ import { randomBytes } from 'node:crypto';
4
+ import { getAgentDir, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
5
+ import type { Binding, SessionBinding } from '../../runtime/binding.ts';
6
+ import type { Notifications } from '../../runtime/notifications.ts';
7
+ import type { SuiteConfig } from '../../runtime/config.ts';
8
+ import { ToolError } from '../../runtime/errors.ts';
9
+ import type { AgentsModule } from '../index.ts';
10
+ import type { StartAgent } from '../types.ts';
11
+ import { resolveType } from '../catalog.ts';
12
+ import { parseSchedule, nextOccurrence } from './parse.ts';
13
+ import { ScheduleStore, schedulePath, type ScheduledAgent } from './store.ts';
14
+
15
+ type Activation = { binding: Binding; store: ScheduleStore; controller: AbortController };
16
+ export class AgentScheduler {
17
+ private timers = new Map<string, NodeJS.Timeout>();
18
+ private pending = new Set<Promise<void>>();
19
+ private activation?: Activation;
20
+ constructor(private pi: ExtensionAPI, private binding: SessionBinding, private agents: AgentsModule,
21
+ private notices: Notifications, private config: () => SuiteConfig) {}
22
+ get isActive(): boolean { return Boolean(this.activation); }
23
+ list(): ScheduledAgent[] { return this.activation?.store.current.jobs ?? []; }
24
+ async bind(): Promise<void> {
25
+ this.stop();
26
+ if (!this.config().agents.scheduling || !this.binding.current) return;
27
+ const binding = this.binding.current;
28
+ const activation = { binding, store: new ScheduleStore(schedulePath(getAgentDir(), binding.sessionId)), controller: new AbortController() };
29
+ this.activation = activation;
30
+ try {
31
+ const { jobs } = await activation.store.snapshot();
32
+ if (!this.current(activation)) return;
33
+ for (const job of jobs) {
34
+ if (!job.enabled) continue;
35
+ if (Date.parse(job.nextRun!) <= Date.now()) {
36
+ // Downtime has no dispatch context: skip missed recurring occurrences and report
37
+ // expired one-shots instead of replaying model work when a session is reopened.
38
+ const nextRun = nextOccurrence(job, Date.now(), Date.parse(job.nextRun!));
39
+ await activation.store.update(job.id, { nextRun, enabled: Boolean(nextRun),
40
+ ...nextRun ? {} : { lastStatus: 'error', lastError: 'Scheduled time passed while the session was inactive. Schedule a future time.' } }, activation.controller.signal);
41
+ if (!nextRun) this.error(activation, job.id, job.nextRun!, 'Scheduled time passed while the session was inactive. Schedule a future time.');
42
+ }
43
+ }
44
+ for (const job of activation.store.current.jobs) this.arm(activation, job);
45
+ this.pi.events.emit('subagents:scheduler_ready', { sessionId: binding.sessionId, jobCount: activation.store.current.jobs.length });
46
+ } catch (error) { if (!activation.controller.signal.aborted) { this.stop(); throw error; } }
47
+ }
48
+ stop(): void {
49
+ this.activation?.controller.abort(); this.activation = undefined;
50
+ for (const timer of this.timers.values()) clearTimeout(timer); this.timers.clear();
51
+ }
52
+ /** Quit stops admitted children first, then joins their captured schedule-file updates. */
53
+ async drain(): Promise<void> { await Promise.all([...this.pending]); }
54
+ private current(activation: Activation): boolean {
55
+ return this.activation === activation && this.binding.isCurrent(activation.binding) && !activation.controller.signal.aborted;
56
+ }
57
+ async add(request: StartAgent, schedule: string, ctx: ExtensionContext, signal?: AbortSignal): Promise<ScheduledAgent> {
58
+ const activation = this.activation;
59
+ if (!activation || !this.current(activation) || ctx.sessionManager.getSessionId() !== activation.binding.sessionId) throw new ToolError('STALE_BINDING', 'Scheduler is not bound to this session. Retry in the active session with scheduling enabled.');
60
+ if (request.background === false || request.inheritContext !== undefined) throw new ToolError('INVALID_ARGS', 'Scheduled runs are background-only and cannot inherit context. Omit background:false and inheritContext.');
61
+ const config = this.config();
62
+ const type = resolveType(ctx.cwd, request.type ?? 'general-purpose', { trusted: ctx.isProjectTrusted(),
63
+ packageGate: config.agents.packageAgents, typeSettings: config.agents.types });
64
+ const spec = parseSchedule(schedule), now = Date.now();
65
+ const { background: _background, inheritContext: _context, ...options } = request;
66
+ const job: ScheduledAgent = { id: `schedule_${randomBytes(4).toString('hex')}`, name: request.name?.trim() || `${type.name}: ${request.prompt.replace(/\s+/g, ' ').slice(0, 40)}`.slice(0, 80),
67
+ ...spec, request: { ...options, type: type.name }, enabled: true, createdAt: new Date(now).toISOString(), runCount: 0,
68
+ nextRun: spec.scheduleType === 'once' ? spec.schedule : nextOccurrence(spec, now) };
69
+ const combined = signal ? AbortSignal.any([signal, activation.controller.signal]) : activation.controller.signal;
70
+ await activation.store.add(job, combined);
71
+ if (this.current(activation)) this.arm(activation, job);
72
+ this.pi.events.emit('subagents:scheduled', { type: 'added', job }); return job;
73
+ }
74
+ async remove(id: string): Promise<void> {
75
+ const activation = this.activation;
76
+ if (!activation || !this.current(activation)) throw new ToolError('STALE_BINDING', 'Scheduler is inactive. Open the owning session with scheduling enabled and retry.');
77
+ await activation.store.remove(id, activation.controller.signal); this.unschedule(id);
78
+ this.pi.events.emit('subagents:scheduled', { type: 'removed', jobId: id });
79
+ }
80
+ private unschedule(id: string): void {
81
+ clearTimeout(this.timers.get(id)); this.timers.delete(id);
82
+ }
83
+ private arm(activation: Activation, job: ScheduledAgent): void {
84
+ if (!this.current(activation) || !job.enabled) return;
85
+ this.unschedule(job.id);
86
+ // Persisted UTC deadlines drive every schedule. A second local-time cron timer
87
+ // can fire before a restored deadline after a timezone change, fail its claim,
88
+ // and silently disarm the still-enabled schedule. Croner computes deadlines only.
89
+ // Node converts delays above 2^31-1 to 1ms. Re-arm toward the same absolute deadline
90
+ // so long one-shots/intervals retain their requested time without a hot loop.
91
+ const delay = Math.max(1, Math.min(2_147_483_647, Date.parse(job.nextRun!) - Date.now()));
92
+ this.timers.set(job.id, setTimeout(() => {
93
+ this.timers.delete(job.id);
94
+ if (Date.now() < Date.parse(job.nextRun!)) this.arm(activation, job);
95
+ else this.dispatch(activation, job.id, job.nextRun!);
96
+ }, delay).unref());
97
+ }
98
+ private error(activation: Activation, id: string, occurrence: string, error: string): void {
99
+ this.pi.events.emit('subagents:scheduled', { type: 'error', jobId: id, error });
100
+ this.notices.enqueue(activation.binding.sessionId, `schedule:${id}:${occurrence}`, `Schedule ${id} failed: ${error}\n/subagents schedules`,
101
+ undefined, 'event', { title: 'Schedule failed', state: 'failed', meta: [id], body: `${error}\n/subagents schedules` });
102
+ }
103
+ private dispatch(activation: Activation, id: string, deadline: string): void {
104
+ const work = this.fire(activation, id, deadline).catch(error => this.error(activation, id, deadline, String(error)))
105
+ .finally(() => { this.pending.delete(work); });
106
+ this.pending.add(work);
107
+ }
108
+ private async fire(activation: Activation, id: string, deadline: string): Promise<void> {
109
+ if (!this.current(activation)) return;
110
+ let occurrence: string | undefined;
111
+ try {
112
+ const now = Date.now(), job = await activation.store.claim(id, deadline, now, activation.controller.signal);
113
+ if (!job) { this.unschedule(id); return; }
114
+ occurrence = new Date(now).toISOString();
115
+ const updated = activation.store.current.jobs.find(item => item.id === id)!;
116
+ this.arm(activation, updated);
117
+ const run = await this.agents.admit().start(job.request, this.agents.scope(activation.binding.ctx), this.config(), undefined,
118
+ { scheduleId: id, bypassQueue: true, signal: activation.controller.signal });
119
+ await activation.store.setRun(id, occurrence, run.record.id, run.record.runId);
120
+ this.pi.events.emit('subagents:scheduled', { type: 'fired', jobId: id, agentId: run.record.id, name: job.name });
121
+ let current = run, result = await current.done.promise;
122
+ // Automatic resumes are runs of this occurrence, not additional dispatches.
123
+ while (current.replacement) {
124
+ current = current.replacement;
125
+ await activation.store.setRun(id, occurrence, current.record.id, current.record.runId);
126
+ result = await current.done.promise;
127
+ }
128
+ const success = result.state === 'completed';
129
+ await activation.store.finish(id, occurrence, success, result.error ?? (success ? undefined : result.state));
130
+ } catch (error) {
131
+ // File/dispatch failures are visible. An aborted, uncommitted claim is simply cancelled.
132
+ if (occurrence) await activation.store.finish(id, occurrence, false, String(error));
133
+ if (!activation.controller.signal.aborted) this.error(activation, id, deadline, String(error));
134
+ }
135
+ }
136
+ }
@@ -0,0 +1,38 @@
1
+ // Schedule details/cancellation adapted from pi-subagents 0.23.0 (MIT).
2
+ import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
3
+ import { browse, type BrowsePage } from '../../ui/browser.ts';
4
+ import { showDetails } from '../../ui/details.ts';
5
+ import type { Dock } from '../../ui/dock.ts';
6
+ import type { AgentScheduler } from './index.ts';
7
+ import type { ScheduledAgent } from './store.ts';
8
+ import { field, part, plainDetailLines, section, statePart, type StructuredDetails } from '../../ui/structured-details.ts';
9
+
10
+ const details = (job: ScheduledAgent): StructuredDetails => ({rows: [
11
+ [part(job.name, 'heading')], field('ID:', part(job.id, 'id')), field('Type:', job.request.type),
12
+ field('Schedule:', job.schedule, part(` (${job.scheduleType})`, 'meta')),
13
+ field('Enabled:', statePart(job.enabled, job.enabled ? 'enabled' : 'disabled')), null,
14
+ field('Next:', part(job.nextRun ?? '—', 'meta')),
15
+ field('Last:', part(job.lastRun ?? '—', 'meta'), part(' ('), statePart(job.lastStatus ?? '—'), part(')')),
16
+ field('Runs:', part(job.runCount, 'number')), field('Agent:', part(job.lastAgentId ?? '—', 'id')),
17
+ ...(job.lastError !== undefined ? [null, [part(job.lastError, 'error')]] : []), section('Input'), job.request.prompt,
18
+ ]});
19
+
20
+ export async function showSchedules(ctx: ExtensionContext, scheduler: AgentScheduler, dock: Dock, page: BrowsePage): Promise<void> {
21
+ for (; !page.navigation?.closed;) {
22
+ let action = 'details';
23
+ const id = await browse(ctx, dock, { title: 'Subagents', state: page.state, pages: page.pages, navigation: page.navigation,
24
+ selection: item => { const job = scheduler.list().find(job => job.id === item.value)!; return {name: job.name, id: job.id}; },
25
+ ticking: () => scheduler.list().some(job => job.enabled || job.lastStatus === 'running'),
26
+ items: () => scheduler.list().map(job => ({ value: job.id, status: job.lastStatus, label: `${job.name} · ${job.schedule}`, description: job.request.type,
27
+ search: `${job.id} ${job.name} ${job.schedule} ${job.request.type} ${job.request.prompt}`, details: () => details(job) })),
28
+ actions: (item, done) => [{ key: 'x', label: 'Cancel schedule', run: () => { action = 'cancel'; done(item.value); } }],
29
+ });
30
+ if (id === undefined || page.navigation?.closed) return;
31
+ const job = scheduler.list().find(job => job.id === id);
32
+ if (!job) continue;
33
+ if (action === 'details') await showDetails(ctx, dock, job.name, details(job), 'text', page.navigation);
34
+ else if (await ctx.ui.confirm(`Cancel "${job.name}"?`, plainDetailLines(details(job)).join('\n'))) {
35
+ await scheduler.remove(job.id); ctx.ui.notify(`Cancelled: ${job.name}`);
36
+ }
37
+ }
38
+ }
@@ -0,0 +1,42 @@
1
+ // Format detection/parsers adapted from @tintinweb/pi-subagents 0.23.0 src/schedule.ts (MIT).
2
+ import { Cron } from 'croner';
3
+ import { ToolError } from '../../runtime/errors.ts';
4
+
5
+ export type ScheduleSpec = { schedule: string; scheduleType: 'cron' | 'once' | 'interval'; intervalMs?: number };
6
+ const units = { s: 1000, m: 60_000, h: 3_600_000, d: 86_400_000 };
7
+ export function nextCron(schedule: string, after: number): string | undefined {
8
+ // Croner computes deadlines only; a separate callback could race the persisted timer.
9
+ const cron = new Cron(schedule, { paused: true, unref: true });
10
+ try { return cron.nextRun(new Date(after))?.toISOString(); } finally { cron.stop(); }
11
+ }
12
+ export function parseSchedule(input: string, now = Date.now(), allowPast = false): ScheduleSpec {
13
+ const schedule = input.trim(), match = /^(\+?)(\d+)(s|m|h|d)$/.exec(schedule);
14
+ if (match) {
15
+ const intervalMs = Number(match[2]) * units[match[3] as keyof typeof units];
16
+ if (!Number.isSafeInteger(intervalMs) || intervalMs <= 0 || !Number.isFinite(new Date(now + intervalMs).getTime())) {
17
+ throw new ToolError('INVALID_ARGS', 'Schedule duration is zero or out of range. Use a positive integer with s, m, h, or d (e.g. 5m).');
18
+ }
19
+ return match[1] ? { scheduleType: 'once', schedule: new Date(now + intervalMs).toISOString() }
20
+ : { scheduleType: 'interval', schedule, intervalMs };
21
+ }
22
+ if (/^\d{4}-\d{2}-\d{2}T/.test(schedule)) {
23
+ const time = new Date(schedule).getTime();
24
+ if (Number.isFinite(time)) {
25
+ if (!allowPast && time <= now) throw new ToolError('INVALID_ARGS', `Scheduled time ${schedule} has passed. Use a future time.`);
26
+ return { scheduleType: 'once', schedule: new Date(time).toISOString() };
27
+ }
28
+ }
29
+ if (schedule.split(/\s+/).length === 6) {
30
+ try {
31
+ if (nextCron(schedule, now)) return { scheduleType: 'cron', schedule };
32
+ } catch (error) { throw new ToolError('INVALID_ARGS', `Invalid cron schedule: ${String(error)}. Correct the six cron fields and retry.`); }
33
+ }
34
+ throw new ToolError('INVALID_ARGS', `Invalid schedule "${input}"; use six-field cron, an interval (5m/1h), or a one-shot (+10m/ISO timestamp)`);
35
+ }
36
+ export function nextOccurrence(spec: ScheduleSpec, after: number, deadline = after): string | undefined {
37
+ if (spec.scheduleType === 'once') return;
38
+ // Claim and inactive-session recovery share the same cadence; skip missed
39
+ // intervals from the committed deadline rather than restarting their phase.
40
+ const base = spec.scheduleType === 'interval' ? deadline + Math.floor((after - deadline) / spec.intervalMs!) * spec.intervalMs! : after;
41
+ return spec.scheduleType === 'cron' ? nextCron(spec.schedule, after) : new Date(base + spec.intervalMs!).toISOString();
42
+ }
@@ -0,0 +1,78 @@
1
+ // Session scope and reload-under-lock adapted from @tintinweb/pi-subagents 0.23.0
2
+ // src/schedule-store.ts (MIT). Tasks and schedules share the same JSON file protocol.
3
+ import { join } from 'node:path';
4
+ import { Type, type Static } from 'typebox';
5
+ import { Value } from 'typebox/value';
6
+ import { JsonStore } from '../../runtime/json-store.ts';
7
+ import { ToolError } from '../../runtime/errors.ts';
8
+ import { taskId, generationSchema } from '../../tasks/types.ts';
9
+ import { thinkingSchema } from '../schema.ts';
10
+ import { parseSchedule, nextOccurrence } from './parse.ts';
11
+
12
+ const iso = Type.String({ format: 'date-time' });
13
+ export const scheduleSchema = Type.Object({
14
+ id: Type.String({ pattern: '^schedule_[a-f0-9]{8}$' }), name: Type.String({ minLength: 1, maxLength: 80 }),
15
+ schedule: Type.String({ minLength: 1 }), scheduleType: Type.Union([Type.Literal('once'), Type.Literal('cron'), Type.Literal('interval')]),
16
+ intervalMs: Type.Optional(Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER })),
17
+ request: Type.Object({ prompt: Type.String({ minLength: 1 }), type: Type.String({ minLength: 1 }), name: Type.Optional(Type.String({ maxLength: 80 })),
18
+ model: Type.Optional(Type.String({ minLength: 1 })), thinking: Type.Optional(thinkingSchema),
19
+ maxTurns: Type.Optional(Type.Integer({ minimum: 0 })), isolated: Type.Optional(Type.Boolean()), taskId: Type.Optional(taskId), taskGeneration: Type.Optional(generationSchema) }, { additionalProperties: false }),
20
+ enabled: Type.Boolean(), createdAt: iso, nextRun: Type.Optional(iso), runCount: Type.Integer({ minimum: 0 }),
21
+ lastRun: Type.Optional(iso), lastStatus: Type.Optional(Type.Union([Type.Literal('running'), Type.Literal('success'), Type.Literal('error')])),
22
+ lastError: Type.Optional(Type.String()), lastAgentId: Type.Optional(Type.String()), lastRunId: Type.Optional(Type.String()),
23
+ }, { additionalProperties: false });
24
+ const dataSchema = Type.Object({ version: Type.Literal(1), jobs: Type.Array(scheduleSchema) }, { additionalProperties: false });
25
+ export type ScheduledAgent = Static<typeof scheduleSchema>;
26
+ type ScheduleData = Static<typeof dataSchema>;
27
+ export function schedulePath(agentDir: string, sessionId: string): string {
28
+ return join(agentDir, 'pi-suite', 'agents', 'schedules', `${sessionId}.json`);
29
+ }
30
+ export class ScheduleStore extends JsonStore<ScheduleData> {
31
+ constructor(path: string) {
32
+ super(path, { version: 1, jobs: [] }, value => {
33
+ if (!Value.Check(dataSchema, value)) throw new Error('Invalid schedule version or data');
34
+ if (new Set(value.jobs.map(job => job.id)).size !== value.jobs.length || new Set(value.jobs.map(job => job.name)).size !== value.jobs.length) throw new Error('Duplicate schedule IDs or names');
35
+ for (const job of value.jobs) {
36
+ const spec = parseSchedule(job.schedule, Date.now(), true);
37
+ if (spec.scheduleType !== job.scheduleType || spec.intervalMs !== job.intervalMs || job.enabled && !job.nextRun) throw new Error(`Schedule ${job.id} has a mismatched rule or no deadline while enabled`);
38
+ }
39
+ return value;
40
+ }, 'SCHEDULE');
41
+ }
42
+ add(job: ScheduledAgent, signal?: AbortSignal): Promise<void> {
43
+ return this.mutate(data => {
44
+ if (data.jobs.some(item => item.id === job.id || item.name === job.name)) throw new ToolError('INVALID_ARGS', `Schedule ID or name already exists: ${job.id} (${job.name}). Retry with a unique name.`);
45
+ data.jobs.push(job);
46
+ }, signal);
47
+ }
48
+ update(id: string, patch: Partial<ScheduledAgent>, signal?: AbortSignal): Promise<void> {
49
+ return this.mutate(data => { const job = data.jobs.find(item => item.id === id); if (job) Object.assign(job, patch); }, signal);
50
+ }
51
+ remove(id: string, signal?: AbortSignal): Promise<void> { return this.mutate(data => { data.jobs = data.jobs.filter(job => job.id !== id); }, signal); }
52
+ setRun(id: string, occurrence: string, agentId: string, runId: string): Promise<void> {
53
+ return this.mutate(data => {
54
+ const job = data.jobs.find(item => item.id === id);
55
+ if (job?.lastRun === occurrence) { job.lastAgentId = agentId; job.lastRunId = runId; }
56
+ });
57
+ }
58
+ /** Commit the next occurrence before dispatch: two hosts observing one deadline cannot both launch it. */
59
+ claim(id: string, expected: string, now: number, signal?: AbortSignal): Promise<ScheduledAgent | undefined> {
60
+ return this.mutate(data => {
61
+ const job = data.jobs.find(item => item.id === id);
62
+ if (!job?.enabled || job.nextRun !== expected || Date.parse(expected) > now) return;
63
+ const occurrence = structuredClone(job);
64
+ job.nextRun = nextOccurrence(job, now, Date.parse(expected)); job.enabled = Boolean(job.nextRun);
65
+ job.lastRun = new Date(now).toISOString(); job.lastStatus = 'running'; job.lastError = undefined;
66
+ return occurrence;
67
+ }, signal);
68
+ }
69
+ finish(id: string, occurrence: string, success: boolean, error?: string): Promise<void> {
70
+ return this.mutate(data => {
71
+ const job = data.jobs.find(item => item.id === id);
72
+ if (!job) return;
73
+ job.runCount++;
74
+ // Intervals may overlap. An older completion cannot replace a newer run's status.
75
+ if (job.lastRun === occurrence) { job.lastStatus = success ? 'success' : 'error'; job.lastError = error; }
76
+ });
77
+ }
78
+ }
@@ -0,0 +1,5 @@
1
+ import { Type } from 'typebox';
2
+
3
+ // Shared configuration must not import catalog discovery just to validate a thinking value.
4
+ export const thinkingSchema = Type.Union([Type.Literal('off'), Type.Literal('minimal'), Type.Literal('low'),
5
+ Type.Literal('medium'), Type.Literal('high'), Type.Literal('xhigh'), Type.Literal('max')]);
@@ -0,0 +1,29 @@
1
+ import { basename, dirname, join } from 'node:path';
2
+ import { SessionManager } from '@earendil-works/pi-coding-agent';
3
+ import type { Execution } from './types.ts';
4
+ import { AGENT_ENTRY, resultText } from './records.ts';
5
+
6
+ /** All persistent child launches share this location; resume opens its recorded file instead. */
7
+ export function createChildSession(cwd: string, parentSession?: string, sessionDir?: string): SessionManager {
8
+ if (sessionDir !== undefined) return SessionManager.create(cwd, sessionDir, { parentSession });
9
+ // Pi's cwd encoding is not a public helper. create() computes it without writing a
10
+ // session file until conversation messages arrive, so a memory parent leaves no stray file.
11
+ const parentDir = parentSession ? dirname(parentSession) : SessionManager.create(cwd).getSessionDir();
12
+ // Flatten nested children: Pi's non-recursive resume lists must never see these files.
13
+ return SessionManager.create(cwd, basename(parentDir) === 'subagents' ? parentDir : join(parentDir, 'subagents'), { parentSession });
14
+ }
15
+
16
+ /** Closing retained sessions must stay available without loading a new child execution stack. */
17
+ export async function closeAgent(run: Execution): Promise<void> {
18
+ const session = run.session;
19
+ if (!session) return;
20
+ try {
21
+ await session.extensionRunner.emit({ type: 'session_shutdown', reason: 'quit' });
22
+ run.record.sessionFile = session.sessionManager.getSessionFile();
23
+ run.record.endLeafId = session.sessionManager.getLeafId();
24
+ run.record.result ??= resultText(session.sessionManager.getBranch());
25
+ run.record.contextUsage = session.getContextUsage();
26
+ session.sessionManager.appendCustomEntry(AGENT_ENTRY, { ...run.record });
27
+ run.entries = session.sessionManager.getBranch(run.record.endLeafId ?? undefined);
28
+ } finally { session.dispose(); run.session = undefined; }
29
+ }
@@ -0,0 +1,177 @@
1
+ import type { ExtensionAPI, ToolDefinition } from '@earendil-works/pi-coding-agent';
2
+ import { Type } from 'typebox';
3
+ import type { SuiteConfig } from '../runtime/config.ts';
4
+ import { ToolError } from '../runtime/errors.ts';
5
+ import { readBounded, readContinuation, textSource } from '../runtime/read.ts';
6
+ import { sanitizeText } from '../runtime/text.ts';
7
+ import { checkedArguments, LIST_LIMITS, listFields, objectId, paginate, readFields, registerBoundTool, rejectContextWithoutSearch, textResult as text } from '../runtime/tools.ts';
8
+ import type { WaitRegistry } from '../runtime/wait.ts';
9
+ import { childId, generationSchema } from '../tasks/types.ts';
10
+ import { thinkingSchema } from './schema.ts';
11
+ import { questionText } from './questions.ts';
12
+ import { AgentsModule, agentSummary, summaryLine, usageText } from './index.ts';
13
+ import { active, executing, recordWorkspace } from './types.ts';
14
+ import { transcript, transcriptText } from './records.ts';
15
+ import type { AgentScheduler } from './schedules/index.ts';
16
+ import type { JobsModule } from '../jobs/index.ts';
17
+ import type { JobSummary } from '../jobs/types.ts';
18
+ import { isActive as jobActive } from '../jobs/state.ts';
19
+
20
+ import { startRenderers, listRenderers, getRenderers, readRenderers, sendRenderers, stopRenderers } from './render.ts';
21
+
22
+ const id = objectId('agent', 'agent_3fa1c2d0'), runId = objectId('run', 'run_3fa1c2d0');
23
+ const listSchema = Type.Object({ agentId: Type.Optional(id), ...listFields(['active', 'queued', 'finished', 'all'] as const) }, { additionalProperties: false });
24
+ const getSchema = Type.Object({ id, runId: Type.Optional(runId), detail: Type.Optional(Type.Boolean()) }, { additionalProperties: false });
25
+ const queryHint = 'Use agent_list({agentId, state:"all"}) for history or agent_get({id, runId}) for one run.';
26
+ export function registerAgentTools(pi: ExtensionAPI, agents: AgentsModule, waits: WaitRegistry, config: () => SuiteConfig, scheduler: AgentScheduler | undefined, jobs: Pick<JobsModule, 'createdBy'>) {
27
+ let scheduling = Boolean(scheduler && config().agents.scheduling);
28
+ const startFields = { prompt: Type.String({ minLength: 1 }), type: Type.Optional(Type.String({ minLength: 1 })),
29
+ name: Type.Optional(Type.String({ maxLength: 80 })), background: Type.Optional(Type.Boolean()),
30
+ model: Type.Optional(Type.String({ minLength: 1 })), thinking: Type.Optional(thinkingSchema),
31
+ maxTurns: Type.Optional(Type.Integer({ minimum: 0 })), taskId: Type.Optional(childId), taskGeneration: Type.Optional(generationSchema),
32
+ inheritContext: Type.Optional(Type.Boolean()), isolated: Type.Optional(Type.Boolean()), schedule: Type.Optional(Type.String({ minLength: 1 })) };
33
+ const buildStartSchema = () => {
34
+ const fields = { ...startFields };
35
+ if (!scheduling) Reflect.deleteProperty(fields, 'schedule');
36
+ return Type.Object(fields, { additionalProperties: false });
37
+ };
38
+ const startSchema = buildStartSchema();
39
+ const description = 'Start a child agent with a task prompt. Set type to general-purpose (default), Explore, Plan, or a configured type. ' +
40
+ 'Background is the default and returns an ID; foreground waits for the result or a child question. The type can override background. ' +
41
+ 'Use agent_read for output, agent_send to reply or resume, and agent_stop to stop. If you pass taskId, copy taskGeneration from task_list.';
42
+ const scheduleDescription = ' To schedule instead, pass schedule: six-field cron, an interval (5m), or a time (+10m or ISO). Omit inheritContext and do not set background:false. Manage in /subagents schedules.';
43
+ const startTool: ToolDefinition<typeof startSchema> = { name: 'agent_start', ...startRenderers, label: 'Start agent',
44
+ description: description + (scheduling ? scheduleDescription : ''),
45
+ parameters: startSchema,
46
+ async execute(_id, params, signal, _update, ctx) {
47
+ if (signal?.aborted) throw signal.reason;
48
+ const manager = agents.admit();
49
+ const { schedule, ...request } = params;
50
+ if (schedule !== undefined) {
51
+ if (!scheduler || !config().agents.scheduling) throw new ToolError('INVALID_ARGS', 'Scheduling is disabled. Omit schedule to start now.');
52
+ const job = await scheduler.add(request, schedule, ctx, signal);
53
+ return text([`${job.id} ${job.scheduleType} · next ${job.nextRun}`], { schedule: job });
54
+ }
55
+ const run = await manager.start(request, agents.scope(ctx), config());
56
+ // A mention clone cannot deliver a foreground result to the parent.
57
+ if (!_id) { run.notifyResult = true; agents.manager.changed(); }
58
+ if (run.record.background || !_id) return text([summaryLine(agents.manager.view(run)), run.record.error], { agent: agentSummary(agents.manager.view(run)) });
59
+ // Bind Esc only while this tool call is waiting, so an early return leaves the child running.
60
+ let current = run;
61
+ const latest = () => { while (current.replacement) current = current.replacement; return current; };
62
+ const abort = () => {
63
+ const { record } = latest();
64
+ if (!record.background) void agents.manager.stop(record.id, record.runId);
65
+ };
66
+ const waiter = new AbortController();
67
+ const foreground = run.foreground = Promise.withResolvers<undefined>();
68
+ const waitSignal = signal ? AbortSignal.any([signal, waiter.signal]) : waiter.signal;
69
+ signal?.addEventListener('abort', abort, { once: true });
70
+ try {
71
+ if (signal?.aborted) { await agents.manager.stop(run.record.id, latest().record.runId); throw signal.reason; }
72
+ let waiting;
73
+ do {
74
+ waiting = await Promise.race([waits.wait([run.record.id], 'all', 3600000, waitSignal), foreground.promise]);
75
+ if (!waiting) {
76
+ const record = agents.manager.view(latest());
77
+ return text([summaryLine(record), 'Continuing in background; the result will be notified.',
78
+ `read: agent_read({"id":"${record.id}"})`], { agent: agentSummary(record), backgrounded: true });
79
+ }
80
+ }
81
+ while ((waiting.reason === 'other' || waiting.reason === 'event') && active(latest().record.state));
82
+ const record = agents.manager.view(latest());
83
+ if (!active(record.state)) agents.consume({ ...agents.settlement(record.id), runId: record.runId });
84
+ else { latest().notifyResult = true; agents.manager.changed(); }
85
+ return text([...waiting.reason !== 'condition' ? [`wait: ${waiting.reason}${waiting.pending.length ? ` · pending ${waiting.pending.join(', ')}` : ''}`] : [],
86
+ ...waiting.results.map(item => item.summary), ...waiting.others.map(item => item.summary)], { agent: agentSummary(record), wait: waiting });
87
+ } finally {
88
+ latest().foreground = undefined;
89
+ waiter.abort(new Error('Foreground caller released its wait'));
90
+ signal?.removeEventListener('abort', abort);
91
+ }
92
+ } };
93
+ registerBoundTool(pi, startTool, 'initial');
94
+ registerBoundTool(pi, { name: 'agent_list', ...listRenderers, label: 'List agents',
95
+ description: 'List child runs. state: active (default, excludes queued), queued, finished, or all. scope: session (direct children, default) or workspace (includes saved runs). Pass agentId to filter history; pass runId to agent_get to inspect one run.',
96
+ parameters: listSchema, prepareArguments: checkedArguments(listSchema, queryHint),
97
+ async execute(_id, params, signal, _update, ctx) {
98
+ const scope = agents.scope(ctx);
99
+ if (params.scope === 'workspace') await agents.manager.discover(scope, config(), signal);
100
+ const state = params.state ?? 'active';
101
+ const rows = agents.manager.records().filter(record => recordWorkspace(record) === (scope.run?.configCwd ?? ctx.cwd)
102
+ && (scope.run || record.workflowId === undefined) && (params.scope === 'workspace' || agents.manager.visible(record, scope)))
103
+ .filter(record => (!params.agentId || record.id === params.agentId) && (state === 'all' || state === 'active' && executing(record.state)
104
+ || state === 'queued' && record.state === 'queued' || state === 'finished' && !active(record.state)));
105
+ const label = (record: typeof rows[number]) => `${summaryLine(record)}${agents.manager.runs.get(record.runId)?.question ? ' · waiting(parent)' : ''}${record.error ? ` · error: ${record.error}` : ''}${!agents.manager.visible(record, scope) ? ' · read-only' : ''}`;
106
+ const { page, nextCursor } = paginate(rows, record => ({ createdAt: record.createdAt, id: record.runId }), params.cursor, params.limit ?? LIST_LIMITS.defaultLimit,
107
+ { budgetBytes: LIST_LIMITS.defaultBytes - 512, size: record => Buffer.byteLength(label(record)) + 1 });
108
+ return text([`${page.length} ${state} agents (${params.scope ?? 'session'})`, ...page.map(label),
109
+ nextCursor ? `more: agent_list(${JSON.stringify({ ...params, cursor: nextCursor })})` : undefined], { agents: page.map(agentSummary), nextCursor });
110
+ } }, 'initial');
111
+ registerBoundTool(pi, { name: 'agent_get', ...getRenderers, label: 'Agent',
112
+ description: 'Inspect the current run or a specific runId, including pending questions. Set detail:true for model sources, context, usage, and active jobs. Find run IDs with agent_list; read output with agent_read.',
113
+ parameters: getSchema, prepareArguments: checkedArguments(getSchema, queryHint),
114
+ async execute(_id, params, signal, _update, ctx) {
115
+ const scope = agents.scope(ctx), { record, run } = await agents.manager.lookup(params.id, scope, config(), params.runId, signal);
116
+ const lines = [summaryLine(record) + (!agents.manager.visible(record, scope) ? ' · read-only' : ''),
117
+ `model: ${record.model} · thinking: ${record.thinking} · turns ${record.turns ?? 0} · tools ${record.toolUses ?? 0}${record.taskId ? ` · task ${record.taskId} @ ${record.taskGeneration ?? 'unavailable (assignment expired)'}` : ''}`,
118
+ record.activity ? `activity: ${record.activity}` : undefined, record.error,
119
+ run?.question ? questionText(run) : undefined];
120
+ let created: JobSummary[] = [], jobsUnavailable: string | undefined;
121
+ if (params.detail) {
122
+ lines.push(`sources: model ${record.modelSource} · thinking ${record.thinkingSource}`, usageText(record),
123
+ record.contextUsage ? `context: ${record.contextUsage.tokens ?? 'unknown'}/${record.contextUsage.contextWindow} tokens${record.contextUsage.percent === null ? '' : ` · ${record.contextUsage.percent.toFixed(1)}%`}` : undefined,
124
+ record.lastUpdateAt ? `lastUpdateAt: ${record.lastUpdateAt}` : undefined);
125
+ // Explicit runId scopes ownership to that execution; an agent-level detail
126
+ // must also reveal jobs left by earlier executions of this same agent.
127
+ const roots = params.runId ? [record.runId] : agents.manager.records().filter(item => item.id === record.id).map(item => item.runId);
128
+ try { created = (await jobs.createdBy(roots)).filter(jobActive); }
129
+ catch (error) { if (!(error instanceof ToolError) || error.code !== 'RUNTIME_UNAVAILABLE') throw error; jobsUnavailable = error.message; }
130
+ lines.push(jobsUnavailable ? `jobs unavailable: ${jobsUnavailable}` : `jobs: ${created.length} active`,
131
+ ...created.map(job => `${job.id} ${job.state} · cleanup ${job.cleanup.state}${job.cleanup.error ? ` · ${job.cleanup.error}` : ''}`));
132
+ }
133
+ return text(lines, { agent: agentSummary(record), jobs: created, jobsUnavailable, question: run?.question?.params,
134
+ waitingFor: run?.question ? 'parent' : undefined });
135
+ } }, 'initial');
136
+ registerBoundTool(pi, { name: 'agent_read', ...readRenderers, label: 'Read agent',
137
+ description: 'Read output without resuming. stream defaults to transcript until the run ends, then result. Pass runId for an earlier run. Byte paging and regex search work like job_read.',
138
+ parameters: Type.Object({ id, runId: Type.Optional(runId), stream: Type.Optional(Type.Union([Type.Literal('result'), Type.Literal('transcript')])), ...readFields }, { additionalProperties: false }),
139
+ async execute(_id, params, signal, _update, ctx) {
140
+ rejectContextWithoutSearch(params);
141
+ const { record, run } = await agents.manager.lookup(params.id, agents.scope(ctx), config(), params.runId, signal), stream = params.stream ?? (active(record.state) ? 'transcript' : 'result');
142
+ const output = stream === 'transcript' ? transcriptText(transcript(record, run)) : [record.error, record.result].filter(Boolean).join('\n');
143
+ const page = await readBounded(textSource(output), params, sanitizeText);
144
+ if (!active(record.state)) agents.consume({ id: record.id, runId: record.runId, state: record.state, summary: summaryLine(record), settled: true });
145
+ return text([`${summaryLine(record)} · ${stream} bytes ${page.offset}-${page.nextOffset} of ${page.totalBytes}`, page.text,
146
+ page.truncated ? `full: agent_read(${JSON.stringify({ id: record.id, runId: record.runId, stream, ...readContinuation(params, 0) })})` : undefined,
147
+ page.endOfStream ? undefined : `more: agent_read(${JSON.stringify({ id: record.id, runId: record.runId, stream, ...readContinuation(params, page.nextOffset) })})`], { ...page, stream, agent: agentSummary(record) });
148
+ } }, 'initial');
149
+ registerBoundTool(pi, { name: 'agent_send', ...sendRenderers, label: 'Send to agent',
150
+ description: 'Send to a direct child: answer, steer, queue a message, or resume a finished session. Answer with text or an exact option ID/title. For multiple selections use a JSON array of IDs/titles; for a batch use a JSON array with one answer per question.',
151
+ parameters: Type.Object({ id, message: Type.String({ minLength: 1 }) }, { additionalProperties: false }),
152
+ async execute(_id, params, signal, _update, ctx) {
153
+ const scope = agents.scope(ctx);
154
+ await agents.manager.lookup(params.id, scope, config(), undefined, signal);
155
+ const result = await agents.admitSend(params.id).send(params.id, params.message, scope, config());
156
+ return text([summaryLine(agents.manager.view(result.run)), `action: ${result.action}`], { agent: agentSummary(agents.manager.view(result.run)), action: result.action });
157
+ } }, 'initial');
158
+ registerBoundTool(pi, { name: 'agent_stop', ...stopRenderers, label: 'Stop agent',
159
+ description: 'Stop an agent and its descendants, and clean up their active jobs, including jobs left by earlier runs. Pass runId to limit cleanup to that run and its descendants. Waits for abort and cleanup, then reports both states.',
160
+ parameters: Type.Object({ id, runId: Type.Optional(runId) }, { additionalProperties: false }),
161
+ async execute(_id, params, signal, _update, ctx) {
162
+ const scope = agents.scope(ctx);
163
+ const { record } = await agents.manager.lookup(params.id, scope, config(), params.runId, signal);
164
+ if (scope.run && !agents.manager.visible(record, scope)) throw new ToolError('NOT_OWNER', `${params.id} is not your direct child. Pick a child from agent_list.`);
165
+ const outcome = await agents.manager.stop(params.id, params.runId);
166
+ return text([`${params.id} ${outcome.state} · cleanup ${outcome.cleanup} · ${record.runId} · requested ${outcome.requested}`,
167
+ ...outcome.affected.map(item => `${item.id} ${item.state}${item.cleanup ? ` · ${item.cleanup}` : ''}`)], { ...outcome, runId: record.runId, name: record.name });
168
+ } }, 'initial');
169
+ return Object.assign(startTool, { refreshSchema() {
170
+ const next = Boolean(scheduler && config().agents.scheduling);
171
+ if (next === scheduling) return;
172
+ scheduling = next; startTool.parameters = buildStartSchema();
173
+ startTool.description = description + (scheduling ? scheduleDescription : '');
174
+ // Late registration updates Pi's single tool registry after a new project's config loads.
175
+ registerBoundTool(pi, startTool);
176
+ } });
177
+ }
@@ -0,0 +1,87 @@
1
+ import type { AgentSession, ContextUsage, ExtensionContext, ExtensionRunner, SessionEntry, SessionManager, SessionStats, ToolRenderers } from '@earendil-works/pi-coding-agent';
2
+ import type { Model } from '@earendil-works/pi-ai';
3
+ import type { AskParams, AskResult, Question } from '../ask/schema.ts';
4
+ import type { TaskStore } from '../tasks/store.ts';
5
+ import type { SuiteConfig } from '../runtime/config.ts';
6
+ import type { CompiledSchema } from './output/schema.ts';
7
+ export type ResourceChoice = boolean | string[];
8
+ export type MemoryScope = 'user' | 'project' | 'local';
9
+
10
+ export type Thinking = 'off' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';
11
+ export type AgentState = 'queued' | 'starting' | 'running' | 'waiting' | 'stopping' | 'completed' | 'failed' | 'stopped' | 'limited';
12
+ export const active = (state: AgentState): boolean => ['queued', 'starting', 'running', 'waiting', 'stopping'].includes(state);
13
+ export const executing = (state: AgentState): boolean => state !== 'queued' && active(state);
14
+ export type Pool = 'background' | 'foreground';
15
+ export interface AgentType {
16
+ name: string; displayName?: string; description: string; systemPrompt: string; promptMode: 'append' | 'replace';
17
+ tools?: string[]; excludeTools?: string[]; model?: string; thinking?: Thinking;
18
+ maxTurns?: number; persistSession?: boolean; allowedSubagents?: 'all' | string[];
19
+ enabled?: boolean; sourcePath?: string; packageName?: string; color?: string;
20
+ extensions?: ResourceChoice; excludeExtensions?: string[]; skills?: ResourceChoice;
21
+ sessionDir?: string; inheritContext?: boolean; runInBackground?: boolean; isolated?: boolean; memory?: MemoryScope;
22
+ }
23
+ export type ModelSource = 'parameter' | 'type' | 'frontmatter' | 'default' | 'inherited' | 'individual';
24
+ export type ModelOverrides = { model?: string; thinking?: Thinking };
25
+ export type AgentTypeSettings = ModelOverrides & { enabled?: boolean };
26
+ export interface AgentRecord {
27
+ version: 1; id: string; runId: string; type: string; name: string; prompt: string; cwd: string; configCwd?: string;
28
+ ownerSessionId: string; anchorEntryId: string | null; parentAgentId?: string; parentRunId?: string;
29
+ ancestors: string[]; background: boolean; state: AgentState;
30
+ createdAt: string; startedAt?: string; endedAt?: string; elapsedMs?: number;
31
+ model: string; modelSource: ModelSource; thinking: Thinking; thinkingSource: ModelSource;
32
+ sessionFile?: string; endLeafId?: string | null; persisted: boolean;
33
+ result?: string; error?: string; usage?: Pick<SessionStats, 'tokens' | 'cost'>;
34
+ /** Last SDK context estimate for this run; null tokens mean usage is unknown. */
35
+ contextUsage?: ContextUsage;
36
+ taskId?: string; taskGeneration?: string; handle?: string; alias?: string; scheduleId?: string; workflowId?: string; description?: string;
37
+ structuredJson?: string; structuredRetried?: boolean; compactionCount?: number;
38
+ turns?: number; toolUses?: number; activity?: string; lastUpdateAt?: string;
39
+ individual?: ModelOverrides;
40
+ }
41
+ export type StartAgent = {
42
+ type?: string; prompt: string; name?: string; background?: boolean; model?: string; thinking?: Thinking;
43
+ maxTurns?: number; taskId?: string; taskGeneration?: string; inheritContext?: boolean; isolated?: boolean;
44
+ };
45
+ export type ParentContext = Pick<ExtensionContext, 'cwd' | 'model' | 'modelRegistry' | 'thinkingLevel' | 'sessionManager' | 'isProjectTrusted' | 'getSystemPrompt'>;
46
+ export interface ParentScope {
47
+ ctx: ParentContext; run?: Execution;
48
+ /** The direct parent's own list, never the task that was assigned to that parent. */
49
+ taskStore?: TaskStore;
50
+ owner?: Pick<AgentRecord, 'ownerSessionId' | 'anchorEntryId'>;
51
+ }
52
+ export const isTopLevelAgent = (record: Pick<AgentRecord, 'parentAgentId' | 'workflowId'>): boolean =>
53
+ record.parentAgentId === undefined && record.workflowId === undefined;
54
+ export function visibleAgent(record: AgentRecord, scope: ParentScope): boolean {
55
+ if (scope.run) return record.parentRunId === scope.run.record.runId;
56
+ return isTopLevelAgent(record) && record.ownerSessionId === scope.ctx.sessionManager.getSessionId()
57
+ && (record.anchorEntryId === null || scope.ctx.sessionManager.getBranch().some(entry => entry.id === record.anchorEntryId));
58
+ }
59
+ export const recordWorkspace = (record: AgentRecord): string => record.configCwd ?? record.cwd;
60
+ export type AgentEventKind = 'created' | 'started' | 'completed' | 'failed' | 'steered' | 'compacted' | 'usage';
61
+ export type StartOptions = {
62
+ scheduleId?: string; workflowId?: string; bypassQueue?: boolean; signal?: AbortSignal;
63
+ cwd?: string; description?: string; structuredOutput?: CompiledSchema; detached?: boolean;
64
+ onSpawned?: (id: string) => void; onQueued?: (id: string, ahead: number) => void;
65
+ onCompaction?: (info: { reason: string; tokensBefore: number; compactionCount: number }) => void;
66
+ };
67
+ export type PendingQuestion = {
68
+ params: AskParams; questions: Question[]; seen: boolean; finish: (result: AskResult) => void;
69
+ };
70
+ /** Runtime handles belong to one run, never to the stable agent ID. */
71
+ export interface Execution {
72
+ record: AgentRecord; type: AgentType; model: Model<any>; parent: ParentScope;
73
+ /** The child's private task list, used when it starts a nested agent. */
74
+ taskStore?: TaskStore;
75
+ controller: AbortController; done: PromiseWithResolvers<AgentRecord>; chargedPool?: Pool;
76
+ startedMonotonic?: number; session?: AgentSession; sessionManager?: SessionManager; entries?: SessionEntry[]; question?: PendingQuestion;
77
+ settled?: boolean; terminated?: boolean; streamingEntry?: SessionEntry;
78
+ liveResults?: Map<string, SessionEntry>; renderers?: Map<string, ToolRenderers>;
79
+ customRenderers?: Pick<ExtensionRunner, 'getMessageRenderer' | 'getEntryRenderer'>;
80
+ pendingMessages: string[]; consumed: boolean; notifyResult?: boolean; maxTurns?: number;
81
+ request: StartAgent; config: SuiteConfig; isolated?: boolean; inheritedContext?: string; bypassQueue?: boolean;
82
+ configCwd: string; configTrusted: boolean; options: StartOptions; startup?: PromiseWithResolvers<string | undefined>; detachAbort?: () => void;
83
+ foreground?: PromiseWithResolvers<undefined>;
84
+ autoResumes?: number;
85
+ retry?: { attempt: number; max: number; timer?: NodeJS.Timeout };
86
+ replacement?: Execution;
87
+ }