pi-suite 0.0.0-stage → 0.3.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 (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 +108 -0
  161. package/src/runtime/responses/payload.ts +78 -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,192 @@
1
+ import { getAgentDir, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
2
+ import { loadConfig } from './config.ts';
3
+ import { SessionBinding } from './binding.ts';
4
+ import { Notifications } from './notifications.ts';
5
+ import { Dock } from '../ui/dock.ts';
6
+ import { StatusPublisher } from '../ui/status.ts';
7
+ import { AskManager, registerAsk } from '../ask/index.ts';
8
+ import { WaitRegistry, registerWait } from './wait.ts';
9
+ import { recordsIn } from '../agents/records.ts';
10
+ import { visibleAgent, type AgentType } from '../agents/types.ts';
11
+ import { registerSuiteCommand } from './settings/index.ts';
12
+ import { prepareClipboard } from './clipboard.ts';
13
+ import type { SubagentsDeps } from '../agents/commands.ts';
14
+
15
+ export async function createSuite(pi: ExtensionAPI, initial: ExtensionContext) {
16
+ let config = loadConfig(initial.cwd);
17
+ // Pi uses Jiti with shared dependency graphs: concurrent imports can expose unfinished
18
+ // exports. Load admitted stacks in order and finish registration before session_start returns.
19
+ const [taskApi, goalApi, jobApi, agentApi] = [
20
+ config.modules.tasks ? [await import('../tasks/index.ts'), await import('../tasks/tools.ts'), await import('../tasks/commands.ts')] as const : undefined,
21
+ config.modules.goal ? [await import('../goal/manager.ts'), await import('../goal/tools.ts'), await import('../goal/commands.ts'), await import('../goal/index.ts')] as const : undefined,
22
+ config.modules.jobs || config.modules.agents ? [await import('../jobs/index.ts'), await import('../jobs/tools.ts'), await import('../jobs/commands.ts')] as const : undefined,
23
+ config.modules.agents ? [await import('../agents/index.ts'), await import('../agents/tools.ts'), await import('../agents/commands.ts'),
24
+ await import('../agents/mentions/index.ts'), await import('../agents/schedules/index.ts'), await import('../agents/rpc/index.ts'),
25
+ await import('../agents/workflow/index.ts'), await import('../agents/workflow/tools.ts'), await import('../agents/catalog.ts')] as const : undefined,
26
+ ] as const;
27
+ let cachedTypes: AgentType[] | undefined;
28
+ const catalog = (ctx: ExtensionContext, fresh = false): AgentType[] => {
29
+ if (fresh) cachedTypes = undefined;
30
+ return cachedTypes ??= agentApi![8].agentTypes(ctx.cwd, getAgentDir(), { trusted: ctx.isProjectTrusted(),
31
+ packageGate: config.agents.packageAgents, typeSettings: config.agents.types });
32
+ };
33
+ const binding = new SessionBinding();
34
+ const dock = new Dock();
35
+ const status = new StatusPublisher(dock);
36
+ const notifications = new Notifications(pi, binding);
37
+ // Disabled recovery must not load its protocol classifier or request-state machinery.
38
+ // Enabled registration still completes before binding, so the first request is covered.
39
+ const recovery = config.runtime.openAIResponsesAutoRecovery
40
+ ? (await import('./responses/index.ts')).registerResponsesRecovery(pi, binding, true) : undefined;
41
+ const tasks = config.modules.tasks ? new taskApi![0].TasksModule(binding, dock) : undefined;
42
+ if (tasks) {
43
+ taskApi![1].registerTaskTools(pi, tasks); taskApi![2].registerTasksCommand(pi, tasks, dock, notifications, binding); tasks.registerReminders(pi, () => config, notifications);
44
+ dock.setOpen('tasks', async (rowId, ctx) => {
45
+ const current = binding.current;
46
+ if (!current) return;
47
+ const release = notifications.hold();
48
+ try {
49
+ const { showTask } = await import('../tasks/viewer.ts');
50
+ if (!binding.isCurrent(current) || ctx.signal?.aborted) return;
51
+ await showTask(ctx, tasks, dock, rowId.slice('task:'.length), binding);
52
+ } finally { release(); }
53
+ });
54
+ }
55
+ const waits = new WaitRegistry();
56
+ const goal = config.modules.goal ? new goalApi![0].GoalManager(pi, binding, notifications, status, waits) : undefined;
57
+ const ask = config.modules.ask ? new AskManager(binding, notifications, dock, (status, ctx) => goal?.askResult(status, ctx)) : undefined;
58
+ if (ask) registerAsk(pi, ask, () => config);
59
+ const creatorRoots = () => {
60
+ const ctx = binding.current?.ctx;
61
+ if (!ctx) return [];
62
+ // Module switches remove tools, while saved parent records still identify jobs
63
+ // left by their children. Reading these references does not start an agent runtime.
64
+ return agents ? agents.visibleRunIds(ctx) : recordsIn(ctx.sessionManager.getBranch())
65
+ .filter(record => visibleAgent(record, {ctx})).map(record => record.runId);
66
+ };
67
+ const jobs = config.modules.jobs ? new jobApi![0].JobsModule(pi, binding, notifications, status, creatorRoots) : undefined;
68
+ const jobViewer = jobs ? { jobs, dock, notifications, keys: () => config.jobs } : undefined;
69
+ if (jobs) {
70
+ jobApi![1].registerJobTools(pi, jobs, jobViewer!, { config: () => config, tasks }); jobApi![2].registerJobsCommand(pi, jobViewer!); waits.register(jobs);
71
+ }
72
+ const agents = config.modules.agents ? new agentApi![0].AgentsModule(pi, binding, notifications, status, tasks) : undefined;
73
+ const agentJobViewer = agents ? {pi, viewer: jobViewer ?? {jobs: new jobApi![0].JobsModule(pi, binding, notifications, status, creatorRoots), dock, notifications, keys: () => config.jobs}} : undefined;
74
+ const schedules = agents ? new agentApi![4].AgentScheduler(pi, binding, agents, notifications, () => config) : undefined;
75
+ const agentRpc = agents ? new agentApi![5].AgentRpc(pi, binding, agents, () => config) : undefined;
76
+ const workflows = agents ? new agentApi![6].WorkflowsModule(pi, binding, notifications, dock, agents) : undefined;
77
+ const workflowTool = workflows && agents ? agentApi![7].registerWorkflowTool(pi, workflows, agents, () => config, catalog) : undefined;
78
+ if (workflows) waits.register(workflows);
79
+ let startTool: ReturnType<typeof import("../agents/tools.ts").registerAgentTools> | undefined;
80
+ let mentions: ReturnType<typeof import("../agents/mentions/index.ts").registerAgentMentions> | undefined;
81
+ let subagentsDeps: SubagentsDeps | undefined;
82
+ if (agents) {
83
+ startTool = agentApi![1].registerAgentTools(pi, agents, waits, () => config, schedules, agentJobViewer!.viewer.jobs);
84
+ const reload = (cwd: string) => {
85
+ config = loadConfig(cwd); cachedTypes = undefined; mentions?.refreshTypes();
86
+ if (binding.current) workflowTool?.refreshTypes(binding.current.ctx);
87
+ };
88
+ subagentsDeps = { agents, dock, notices: notifications, config: () => config, reload, scheduler: schedules,
89
+ workflows: workflows && workflowTool ? { available: () => workflowTool.enabled,
90
+ show: async (ctx, page) => { const { showWorkflows } = await import('../agents/workflow/ui/menu.ts');
91
+ await showWorkflows(ctx, { workflows, agents, dock, config: () => config, jobs: agentJobViewer }, page); } } : undefined,
92
+ jobs: agentJobViewer };
93
+ agentApi![2].registerSubagentsCommand(pi, subagentsDeps); waits.register(agents);
94
+ mentions = agentApi![3].registerAgentMentions(pi, agents, binding, () => config, startTool, catalog);
95
+ }
96
+ if (jobs || agents) {
97
+ registerWait(pi, waits);
98
+ // Extension-sent messages (our own notices) are not the user and must not end a wait.
99
+ pi.on("input", event => { if (event.streamingBehavior === "steer" && event.source !== "extension") waits.userSteered(); });
100
+ pi.on("message_start", event => { if (event.message.role === "user") waits.steeringDelivered(); });
101
+ }
102
+ if (goal) {
103
+ goalApi![1].registerGoalTools(pi, goal); goalApi![2].registerGoalCommand(pi, goal, dock, notifications); goalApi![3].registerGoalLifecycle(pi, goal);
104
+ }
105
+
106
+ if (agents) dock.setOpen('agents', async (rowId, ctx) => {
107
+ const current = binding.current!;
108
+ const { showAgent } = await import('../agents/viewer.ts');
109
+ if (!binding.isCurrent(current)) return;
110
+ const runId = rowId.slice('agent:'.length), record = agents.manager.records().find(record => record.runId === runId)!;
111
+ const release = notifications.hold();
112
+ try { await showAgent(ctx, agents, dock, record.id, runId, () => config, false, agentJobViewer); }
113
+ finally { release(); }
114
+ });
115
+ if (workflows && agents) dock.setOpen('workflows', async (id, ctx) => {
116
+ const current = binding.current!;
117
+ const { showWorkflow } = await import('../agents/workflow/ui/menu.ts');
118
+ if (!binding.isCurrent(current)) return;
119
+ const release = notifications.hold();
120
+ try { await showWorkflow(ctx, { workflows, agents, dock, config: () => config, jobs: agentJobViewer }, workflows.manager.get(id)); }
121
+ finally { release(); }
122
+ });
123
+ if (jobs) dock.setOpen('jobs', async (id, ctx) => {
124
+ const current = binding.current!;
125
+ const { jobActions } = await import('../jobs/viewer.ts');
126
+ if (!binding.isCurrent(current)) return;
127
+ await jobActions(pi, ctx, jobViewer!, id, false, jobs.control().peek(id).cwd);
128
+ });
129
+
130
+ let firstBinding = true;
131
+ const bindSession = async (ctx: Parameters<SessionBinding["bind"]>[0], reason: "startup" | "reload" | "new" | "resume" | "fork", previousSessionFile?: string) => {
132
+ // Tree navigation has no shutdown event. Revoke the old readers and timers before
133
+ // rebinding, without appending their state into the branch the host just selected.
134
+ dock.detach(binding.current?.ctx);
135
+ schedules?.stop(); ask?.cancel(); goal?.detach(); jobs?.detach(); workflows?.detach(); agents?.detach(); notifications.detach();
136
+ if (!firstBinding) config = loadConfig(ctx.cwd);
137
+ const goalReason = firstBinding ? reason : "tree";
138
+ firstBinding = false; cachedTypes = undefined;
139
+ await prepareClipboard(pi, ctx);
140
+ binding.bind(ctx);
141
+ recovery?.reset(ctx);
142
+ dock.bind(ctx, config.ui.maxRows);
143
+ status.bind(ctx.ui, { goal: config.goal.display, agents: config.agents.display, jobs: config.jobs.display }, goal !== undefined);
144
+ await goal?.restore(ctx, goalReason);
145
+ await tasks?.bind(ctx, { reason, previousSessionFile });
146
+ agents?.manager.configure(config); agents?.bind();
147
+ jobs?.bind();
148
+ workflows?.bind(); workflowTool?.bind(ctx);
149
+ await schedules?.bind(); startTool?.refreshSchema(); mentions?.bind(ctx);
150
+ agentRpc?.bind();
151
+ notifications.flush();
152
+ };
153
+ pi.on("session_tree", async (_event, ctx) => { await bindSession(ctx, "resume"); notifications.afterHostOperation(); });
154
+ pi.on("session_shutdown", async event => {
155
+ agentRpc?.detach();
156
+ schedules?.stop();
157
+ ask?.cancel(); await goal?.shutdown(event.reason);
158
+ tasks?.detach();
159
+ // Detach before revoking so pending job notices are cancelled under the old session ID.
160
+ (jobs ?? agentJobViewer?.viewer.jobs)?.detach();
161
+ // Module switches change registration, not the lifetime of existing execution owners.
162
+ const agentDir = getAgentDir();
163
+ const { quitExistingRuntime } = await import('../jobs/runtime.ts');
164
+ const { quitExistingAgentRuntime } = await import('../agents/runtime.ts');
165
+ const { quitExistingWorkflowRuntime } = await import('../agents/workflow/manager.ts');
166
+ const quit = event.reason === 'quit' ? quitExistingRuntime(agentDir) : undefined;
167
+ const agentQuit = event.reason === 'quit' ? quitExistingAgentRuntime(agentDir) : undefined;
168
+ const workflowQuit = event.reason === 'quit' ? quitExistingWorkflowRuntime(agentDir) : undefined;
169
+ const scheduleQuit = agentQuit?.then(() => schedules?.drain());
170
+ workflows?.detach(); agents?.detach();
171
+ recovery?.reset();
172
+ notifications.detach(); status.detach(); dock.detach(binding.current?.ctx); binding.revoke();
173
+ return Promise.all([quit, agentQuit, workflowQuit, scheduleQuit]).then(() => { if (agents) pi.events.emit('subagents:disposed', {}); });
174
+ });
175
+ pi.on("agent_before_settle", async event => {
176
+ const repair = recovery?.beforeSettle(event);
177
+ const proposed = repair ? { ...event, ...repair } : event;
178
+ await goal?.beforeSettle(proposed);
179
+ return notifications.beforeSettle(proposed) ?? repair;
180
+ });
181
+ pi.on("agent_settled", async event => {
182
+ recovery?.settled();
183
+ waits.steeringDelivered(); await goal?.settled(event.aborted);
184
+ if (event.aborted) jobs?.pauseWakes();
185
+ notifications.flush();
186
+ });
187
+ registerSuiteCommand(pi, dock, notifications, () => config, subagentsDeps ? async ctx => {
188
+ const { showSubagents } = await import('../agents/ui/index.ts');
189
+ await showSubagents('types', ctx, subagentsDeps!);
190
+ } : undefined);
191
+ return bindSession;
192
+ }
@@ -0,0 +1,6 @@
1
+ import { stripVTControlCharacters } from 'node:util';
2
+
3
+ /** Safe literal program/user text: retain layout, discard terminal transport controls. */
4
+ export function sanitizeText(raw: string): string {
5
+ return stripVTControlCharacters(raw).replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, '');
6
+ }
@@ -0,0 +1,131 @@
1
+ import { Type, type TSchema, type Static } from 'typebox';
2
+ import { Value } from 'typebox/value';
3
+ import type { EntryRenderer, ExtensionAPI, MessageRenderer, ToolDefinition, ToolRenderers } from '@earendil-works/pi-coding-agent';
4
+ import { READ_LIMITS } from './read.ts';
5
+ import { ToolError } from './errors.ts';
6
+
7
+ /**
8
+ * Shared model-tool conventions (doc/current/runtime/tools.md): one shape for IDs, list
9
+ * filters, cursors, reads and stop results. jobs, agents and tasks build their parameters from
10
+ * these pieces so equal meanings keep equal names, units, limits and exclusivity rules.
11
+ */
12
+ /** job_/agent_/run_ use 8 hex digits; workflow run IDs use 12. */
13
+ export const objectId = (prefix: 'job' | 'agent' | 'run' | 'wf', example: string) =>
14
+ Type.String({ pattern: `^${prefix}_[a-f0-9]{${prefix === 'wf' ? 12 : 8}}$`, description: `${prefix} ID, e.g. ${example}` });
15
+ export const WAIT_ID_PATTERN = '^(?:(?:job|agent)_[a-f0-9]{8}|wf_[a-f0-9]{12})$';
16
+
17
+ // Child and main sessions may give the same name different renderers; scope lookup to their API.
18
+ type Renderers = { tools: Map<string, ToolRenderers>; messages: Map<string, MessageRenderer>; entries: Map<string, EntryRenderer> };
19
+ const renderers = new WeakMap<ExtensionAPI, Renderers>();
20
+ function rendererRegistry(pi: ExtensionAPI): Renderers {
21
+ let registry = renderers.get(pi);
22
+ if (!registry) { registry = { tools: new Map(), messages: new Map(), entries: new Map() }; renderers.set(pi, registry); }
23
+ return registry;
24
+ }
25
+ export const toolRenderer = (pi: ExtensionAPI, name: string): ToolRenderers | undefined => renderers.get(pi)?.tools.get(name);
26
+ export function customRendererLookup(pi: ExtensionAPI) {
27
+ return {
28
+ getMessageRenderer: (type: string) => renderers.get(pi)?.messages.get(type),
29
+ getEntryRenderer: (type: string) => renderers.get(pi)?.entries.get(type),
30
+ };
31
+ }
32
+ /** Main-session extensions can register renderers, but only SDK session owners can query Pi's runner.
33
+ * Forward Suite's registrations unchanged and retain those same callbacks for its overlay readers.
34
+ */
35
+ export function captureCustomRenderers(host: ExtensionAPI): ExtensionAPI {
36
+ const pi: ExtensionAPI = { ...host,
37
+ registerMessageRenderer(type, renderer) {
38
+ host.registerMessageRenderer(type, renderer);
39
+ rendererRegistry(pi).messages.set(type, renderer as MessageRenderer);
40
+ },
41
+ registerEntryRenderer(type, renderer) {
42
+ host.registerEntryRenderer(type, renderer);
43
+ rendererRegistry(pi).entries.set(type, renderer as EntryRenderer);
44
+ },
45
+ };
46
+ return pi;
47
+ }
48
+ /** History is rebuilt before session_start; rendering must not wait for module admission. */
49
+ export function registerToolRenderers(pi: ExtensionAPI, defaults: Record<string, ToolRenderers>,
50
+ compose: Record<string, (base: ToolRenderers) => ToolRenderers> = {}): void {
51
+ const lookup = new Map(Object.entries(defaults).map(([name, base]) => [name, compose[name]?.(base) ?? base]));
52
+ rendererRegistry(pi).tools = lookup;
53
+ // Both live resolution and read-only lookup use the same display composition. next() preserves
54
+ // registered/native definitions and other extensions; no execution tool is registered here.
55
+ pi.registerToolRenderer((name, next) => {
56
+ const base = next() ?? defaults[name];
57
+ return base && compose[name] ? compose[name](base) : base;
58
+ });
59
+ }
60
+ /** Initial load has no runtime API yet; late refreshes preserve the active selection. */
61
+ export function registerBoundTool<P extends TSchema>(pi: ExtensionAPI, tool: ToolDefinition<P>, activate: boolean | 'initial' = false): void {
62
+ // Lookup erases the parameter schema; the host supplies this tool's own arguments.
63
+ rendererRegistry(pi).tools.set(tool.name, tool as unknown as ToolRenderers);
64
+ if (activate === 'initial') { pi.registerTool(tool); return; }
65
+ const active = pi.getActiveTools();
66
+ pi.registerTool(tool);
67
+ pi.setActiveTools(activate ? [...new Set([...active, tool.name])] : active);
68
+ }
69
+
70
+ export const LIST_LIMITS = { defaultLimit: 10, maxLimit: 100, defaultBytes: 4096 };
71
+ /** Validate model input without guessing away conflicting fields; return a usable repair. */
72
+ export function checkedArguments<P extends TSchema>(schema: P, hint: string) {
73
+ return (args: unknown): Static<P> => {
74
+ if (!Value.Check(schema, args)) throw new ToolError('INVALID_ARGS', `${Value.Errors(schema, args)[0]?.message ?? 'Invalid arguments'}. ${hint}`);
75
+ return args as Static<P>;
76
+ };
77
+ }
78
+ /** Filters and paging belong to list tools; single-item tools define their own fields. */
79
+ export function listFields<S extends string>(states: readonly S[]) {
80
+ return {
81
+ state: Type.Optional(Type.Unsafe<S>({ type: 'string', enum: [...states], description: `Default ${states[0]}` })),
82
+ scope: Type.Optional(Type.Union([Type.Literal('session'), Type.Literal('workspace')], { description: 'session (default): what this session sees; workspace: every session in this workspace' })),
83
+ cursor: Type.Optional(Type.String({ maxLength: 200, description: 'nextCursor from a previous page' })),
84
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: LIST_LIMITS.maxLimit, description: `Default ${LIST_LIMITS.defaultLimit}` })),
85
+ };
86
+ }
87
+
88
+ type Position = { createdAt: string; id: string };
89
+ /** Newest first; ties broken by ID so pages stay stable while items are added. */
90
+ export function newestFirst(a: Position, b: Position): number {
91
+ return b.createdAt.localeCompare(a.createdAt) || b.id.localeCompare(a.id);
92
+ }
93
+ /** Resume from the last row's position, even if that row has since been removed. */
94
+ export function paginate<T>(items: T[], position: (item: T) => Position, cursor: string | undefined, limit: number,
95
+ options: { oldest?: boolean; size?: (item: T) => number; budgetBytes?: number } = {}): { page: T[]; nextCursor?: string } {
96
+ const compare = (a: Position, b: Position) => newestFirst(a, b) * (options.oldest ? -1 : 1);
97
+ let rows = [...items].sort((a, b) => compare(position(a), position(b)));
98
+ if (cursor) {
99
+ const [createdAt, id] = Buffer.from(cursor, 'base64url').toString().split('|');
100
+ if (!createdAt || !id) throw new ToolError('INVALID_ARGS', 'Invalid cursor. Use nextCursor from the same list or omit cursor.');
101
+ rows = rows.filter(row => compare(position(row), { createdAt, id }) > 0);
102
+ }
103
+ const page: T[] = []; let bytes = 0;
104
+ for (const row of rows) {
105
+ const size = options.size?.(row) ?? 0;
106
+ if (page.length >= limit || page.length && bytes + size > (options.budgetBytes ?? Infinity)) break;
107
+ page.push(row); bytes += size;
108
+ }
109
+ const last = page.at(-1);
110
+ return { page, nextCursor: rows.length > page.length && last ? Buffer.from(`${position(last).createdAt}|${position(last).id}`).toString('base64url') : undefined };
111
+ }
112
+
113
+ /** Byte-offset paging, regex search and default smart truncation; shared by job_read and agent_read. */
114
+ export const readFields = {
115
+ offset: Type.Optional(Type.Integer({ minimum: 0, description: 'Raw byte offset; returns nextOffset' })),
116
+ limitBytes: Type.Optional(Type.Integer({ minimum: 64, maximum: READ_LIMITS.maxBytes, description: `Default ${READ_LIMITS.defaultBytes}` })),
117
+ search: Type.Optional(Type.String({ minLength: 1, maxLength: 500, description: 'Regex, /re/flags; case-insensitive by default' })),
118
+ context: Type.Optional(Type.Integer({ minimum: 0, maximum: READ_LIMITS.maxContext, description: `Lines around matches, default ${READ_LIMITS.defaultContext}` })),
119
+ };
120
+ export function rejectContextWithoutSearch(params: { search?: string; context?: number }): void {
121
+ if (params.context !== undefined && params.search === undefined) throw new ToolError('INVALID_ARGS', 'context requires search. Add search or omit context.');
122
+ }
123
+
124
+ /** stop result shared by job_stop and agent_stop; affected lists every cascaded object's real state. */
125
+ export type StopAffected = { id: string; state: string; cleanup?: string };
126
+ export type StopOutcome = { requested: boolean; state: string; cleanup: string; affected: StopAffected[] };
127
+
128
+ /** First line is the summary and the last line is the next call; undefined lines are dropped. */
129
+ export function textResult<D>(lines: (string | undefined)[], details: D) {
130
+ return { content: [{ type: 'text' as const, text: lines.filter(line => line !== undefined).join('\n') }], details };
131
+ }
@@ -0,0 +1,33 @@
1
+ import { agentDisplayName } from '../agents/registry.ts';
2
+ import { sanitizeText } from './text.ts';
3
+ import { toolRenderers, stateLine } from '../ui/tool-render.ts';
4
+ import { elapsedText } from '../ui/format.ts';
5
+ import type { WaitResult } from './wait.ts';
6
+
7
+ export const waitRenderers = toolRenderers<{ ids: string[] }, WaitResult>({
8
+ call: args => ({ icon: '⟳', tone: 'accent', title: 'Wait', summary: `${args.ids?.length ?? 0} objects` }),
9
+ collapsed: data => {
10
+ const failed = [...data.results, ...data.others].filter(item => item.state === 'failed').length;
11
+ return { icon: failed ? '✘' : '', tone: failed ? 'error' : undefined, title: 'Wait',
12
+ summary: `${data.results.filter(item => item.settled).length}/${data.results.length} settled`,
13
+ meta: [...failed ? [{ text: `${failed} failed`, tone: 'error' as const }] : [],
14
+ ...data.reason !== 'condition' ? [{ text: `returned early: ${data.reason}`, tone: 'warning' as const }] : []] };
15
+ },
16
+ expanded: (data, _args, text) => {
17
+ // Only rewrite the rendered identity; result bodies and read/send arguments keep their IDs.
18
+ let display = text;
19
+ for (const item of [...data.results, ...data.others]) {
20
+ const name = agentDisplayName(item.id, item.runId);
21
+ if (name === item.id) continue;
22
+ const summary = sanitizeText(item.summary);
23
+ display = display.replace(summary, () => summary.replace(item.id, () => sanitizeText(name)));
24
+ }
25
+ if (data.pending.length && data.reason !== 'condition') {
26
+ display = display.replace(`pending: ${data.pending.join(', ')}`,
27
+ () => `pending: ${data.pending.map(id => sanitizeText(agentDisplayName(id))).join(', ')}`);
28
+ }
29
+ return [...[...data.results, ...data.others].map(item => ({ ...stateLine(item.state),
30
+ title: agentDisplayName(item.id, item.runId), meta: [{ text: item.state, tone: stateLine(item.state).tone! }] })),
31
+ ...[...data.results, ...data.others].filter(item => item.state === 'failed').map(item => ({ label: 'error', value: item.summary, tone: 'error' as const })), display];
32
+ },
33
+ }, { timing: elapsedText });
@@ -0,0 +1,134 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
+ import { Type } from 'typebox';
3
+ import { ToolError } from './errors.ts';
4
+ import { WAIT_ID_PATTERN, registerBoundTool } from './tools.ts';
5
+ import { waitRenderers } from './wait-render.ts';
6
+
7
+ /** Separate progress counters let wait consume monitor and hands-free updates without consuming the result. */
8
+ export type Settlement = { id: string; runId?: string; state: string; summary: string; settled: boolean; question?: boolean; event?: number; update?: number };
9
+ export interface Waitable {
10
+ readonly prefix: string;
11
+ settlement(id: string): Settlement;
12
+ /**
13
+ * Entries visible to the current session that the model has not seen yet: settled results not
14
+ * delivered or consumed, open questions from direct children, and undelivered job progress.
15
+ */
16
+ unread(): Settlement[];
17
+ subscribe(listener: () => void): () => void;
18
+ /** Marks a result, question or event batch as seen; it must leave unread() and the notification queue. */
19
+ consume(item: Settlement): void;
20
+ }
21
+ export const WAIT_LIMITS = { maxIds: 50, defaultMs: 300000, maxMs: 3600000 };
22
+
23
+ /** Why a wait returned: its condition, a child question, job progress, another settlement, user input or timeout. */
24
+ export type WaitReason = 'condition' | 'question' | 'event' | 'other' | 'user' | 'timeout';
25
+ export type WaitResult = { results: Settlement[]; others: Settlement[]; pending: string[]; timedOut: boolean; reason: WaitReason };
26
+
27
+ export class WaitRegistry {
28
+ private sources: Record<string, Waitable> = {};
29
+ private interrupts = new Set<() => void>();
30
+ private steerQueued = false;
31
+ register(source: Waitable): void { this.sources[source.prefix] = source; }
32
+ private source(id: string): Waitable {
33
+ const source = this.sources[id.slice(0, id.indexOf('_') + 1)];
34
+ if (!source) throw new ToolError('NOT_FOUND', `No wait source for ${id}. Check the ID and that its module is enabled.`, id);
35
+ return source;
36
+ }
37
+ has(id: string): boolean { return Boolean(this.sources[id.slice(0, id.indexOf('_') + 1)]); }
38
+ settlement(id: string): Settlement { return this.source(id).settlement(id); }
39
+ /** Change signal for every source behind these IDs; goal_wait uses it to resume on its own condition. */
40
+ watch(ids: string[], listener: () => void): () => void {
41
+ const stops = [...new Set(ids.map(id => this.source(id)))].map(source => source.subscribe(listener));
42
+ return () => { for (const stop of stops) stop(); };
43
+ }
44
+ /**
45
+ * Pi reads steering messages only between tool calls, so a blocking wait would hold the
46
+ * user's message until it returns. A steer queued now, or before the wait began, ends it.
47
+ */
48
+ userSteered(): void {
49
+ this.steerQueued = true;
50
+ // The input handler runs just before Pi queues the message; return after it is queued.
51
+ setTimeout(() => { for (const interrupt of this.interrupts) interrupt(); }, 0);
52
+ }
53
+ steeringDelivered(): void { this.steerQueued = false; }
54
+
55
+ /**
56
+ * Resolves when the ids condition holds, when any visible job or agent settles or a direct
57
+ * child asks, when a monitor event or hands-free update arrives (also on a waited job), when the user sends a steering
58
+ * message, at the timeout, or when the signal aborts.
59
+ */
60
+ async wait(ids: string[], mode: 'any' | 'all', timeoutMs: number, signal?: AbortSignal): Promise<WaitResult> {
61
+ signal?.throwIfAborted();
62
+ const unique = [...new Set(ids)];
63
+ const sources = unique.map(id => this.source(id));
64
+ const all = Object.values(this.sources);
65
+ const snapshot = () => unique.map((id, index) => sources[index].settlement(id));
66
+ // A resumed agent shares its ID with older unread runs. Only the exact waited
67
+ // execution is already in results; earlier results and progress remain visible.
68
+ const others = (results: Settlement[]) => all.flatMap(source => source.unread()).filter(item => item.event !== undefined
69
+ || item.update !== undefined || !results.some(result => result.id === item.id && result.runId === item.runId));
70
+ const done = Promise.withResolvers<WaitResult>();
71
+ let finished = false;
72
+ const finish = (reason: WaitReason) => {
73
+ if (finished) return;
74
+ finished = true;
75
+ const results = snapshot(), extra = others(results);
76
+ for (const item of [...results, ...extra]) if (item.settled || item.question || item.event !== undefined || item.update !== undefined) this.source(item.id).consume(item);
77
+ done.resolve({ results, others: extra, pending: results.filter(result => !result.settled).map(result => result.id),
78
+ timedOut: reason === 'timeout', reason });
79
+ };
80
+ const check = () => {
81
+ const results = snapshot();
82
+ if (results.some(result => result.question)) return finish('question');
83
+ if (mode === 'any' ? results.some(result => result.settled) : results.every(result => result.settled)) return finish('condition');
84
+ const extra = others(results);
85
+ if (extra.some(item => item.question)) finish('question');
86
+ else if (extra.some(item => item.event !== undefined || item.update !== undefined)) finish('event');
87
+ else if (extra.length) finish('other');
88
+ };
89
+ const unsubscribe = all.map(source => source.subscribe(check));
90
+ const interrupt = () => finish('user');
91
+ this.interrupts.add(interrupt);
92
+ const timer = setTimeout(() => finish('timeout'), timeoutMs);
93
+ const abort = () => { finished = true; done.reject(signal!.reason ?? new Error('Wait aborted')); };
94
+ signal?.addEventListener('abort', abort, { once: true });
95
+ try {
96
+ if (this.steerQueued) finish('user'); else check();
97
+ return await done.promise;
98
+ } finally {
99
+ clearTimeout(timer); signal?.removeEventListener('abort', abort);
100
+ this.interrupts.delete(interrupt); for (const stop of unsubscribe) stop();
101
+ }
102
+ }
103
+ }
104
+
105
+ const HEADLINE: Record<WaitReason, string> = {
106
+ condition: '', timeout: ' · timed out', other: ' · returned early: another job, agent run or workflow settled',
107
+ question: ' · returned early: an agent asked a question', event: ' · returned early: a monitor event fired',
108
+ user: ' · returned early: the user sent a message',
109
+ };
110
+
111
+ export function registerWait(pi: ExtensionAPI, registry: WaitRegistry): void {
112
+ registerBoundTool(pi, {
113
+ ...waitRenderers,
114
+ name: 'wait', label: 'Wait',
115
+ description: 'Wait for jobs, agents or workflows to settle. Also returns early when any other job, agent run or workflow in this session settles (including earlier runs of a waited agent), a monitor event or hands-free update arrives, a child asks a question, or the user sends a message. Check pending and wait again if needed. Timeout and cancellation stop nothing.',
116
+ parameters: Type.Object({
117
+ ids: Type.Array(Type.String({ pattern: WAIT_ID_PATTERN }), { minItems: 1, maxItems: WAIT_LIMITS.maxIds, description: 'job_, agent_ or wf_ IDs' }),
118
+ mode: Type.Optional(Type.Union([Type.Literal('any'), Type.Literal('all')], { description: 'Wait for any listed ID or all (default).' })),
119
+ timeoutMs: Type.Optional(Type.Integer({ minimum: 1, maximum: WAIT_LIMITS.maxMs, description: `Wait limit in milliseconds; default ${WAIT_LIMITS.defaultMs}.` })),
120
+ }, { additionalProperties: false }),
121
+ async execute(_id, params, signal) {
122
+ const value = await registry.wait(params.ids, params.mode ?? 'all', params.timeoutMs ?? WAIT_LIMITS.defaultMs, signal);
123
+ const settled = value.results.filter(result => result.settled).length;
124
+ const headline = value.reason === 'event' && value.others.some(item => item.update !== undefined)
125
+ ? ' · returned early: a hands-free update arrived' : HEADLINE[value.reason];
126
+ const text = [`wait ${settled}/${value.results.length} settled${headline}`,
127
+ ...value.results.map(result => result.summary),
128
+ ...value.others.length ? ['also:', ...value.others.map(item => item.summary)] : [],
129
+ value.pending.length && value.reason !== 'condition' ? `pending: ${value.pending.join(', ')}` : undefined,
130
+ ].filter(line => line !== undefined).join('\n');
131
+ return { content: [{ type: 'text', text }], details: value };
132
+ },
133
+ }, 'initial');
134
+ }
@@ -0,0 +1,41 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
+ import type { SessionBinding } from '../runtime/binding.ts';
3
+ import type { Notifications } from '../runtime/notifications.ts';
4
+ import type { Dock } from '../ui/dock.ts';
5
+ import type { TasksModule } from './index.ts';
6
+ import { taskViews } from './model.ts';
7
+ import { taskDetails } from './query.ts';
8
+
9
+ /** Register immediately; only an interactive invocation needs the browser stack. */
10
+ export function registerTasksCommand(pi: ExtensionAPI, tasks: TasksModule, dock: Dock, notifications: Notifications,
11
+ binding: SessionBinding): void {
12
+ pi.registerCommand('tasks', {
13
+ description: 'Browse tasks: /tasks [group ID]',
14
+ handler: async (args, ctx) => {
15
+ const current = binding.current;
16
+ if (!current) return;
17
+ const active = () => binding.isCurrent(current) && !ctx.signal?.aborted;
18
+ const words = args.trim().split(/\s+/).filter(Boolean);
19
+ if (words.length > 1 || words.some(word => !/^[1-9][0-9]*$/.test(word))) throw new Error('Expected zero arguments or one numeric group ID. Use /tasks [group ID].');
20
+ const groupId = words[0], state = 'all';
21
+ const generation = (await tasks.scope(ctx).snapshot()).generation;
22
+ if (!active()) return;
23
+ const { data, rows } = await tasks.list(ctx, { parentId: groupId, state }, generation);
24
+ if (!active()) return;
25
+ tasks.selectGroup(groupId);
26
+ if (ctx.mode !== 'tui') {
27
+ const views = new Map(taskViews(data).map(task => [task.id, task]));
28
+ ctx.ui.notify(rows.map(task => taskDetails(task, views).join('\n')).join('\n\n') || 'No tasks'); return;
29
+ }
30
+ const release = notifications.hold();
31
+ try {
32
+ const { showTasks } = await import('./viewer.ts');
33
+ // Imports can outlive reload/tree/new. Do not mount an old reader or
34
+ // clear a replacement binding's Dock when this invocation unwinds.
35
+ if (!active()) return;
36
+ dock.setDetail(true);
37
+ await showTasks(ctx, tasks, groupId, state, binding);
38
+ } finally { if (binding.isCurrent(current)) dock.setDetail(false); release(); }
39
+ },
40
+ });
41
+ }