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,169 @@
1
+ // Background-run lifecycle adapted from @tintinweb/pi-subagents 0.23.0 src/index.ts.
2
+ // Bindings and notifications remain in the suite; this owner never holds an ExtensionAPI.
3
+ import { writeFileSync } from 'node:fs';
4
+ import { getAgentDir } from '@earendil-works/pi-coding-agent';
5
+ import { loadConfig, type SuiteConfig } from '../../runtime/config.ts';
6
+ import { ToolError } from '../../runtime/errors.ts';
7
+ import { acquireRuntime } from '../../jobs/runtime.ts';
8
+ import type { JobManager } from '../../jobs/manager.ts';
9
+ import type { ParentScope } from '../types.ts';
10
+ import { captureParent } from '../parent.ts';
11
+ import { agentRuntime } from '../runtime.ts';
12
+ import { WORKFLOW_OWNER } from '../registry.ts';
13
+ import { acquireOwner, existingOwner, type OwnerHandle } from '../../runtime/owner.ts';
14
+ import type { AgentManager } from '../manager.ts';
15
+ import { appendJournal, readJournal } from './journal.ts';
16
+ import { taskFromEntry, workflowEntryData, type OwnedWorkflowTask, type WorkflowEntryData } from './entry.ts';
17
+ import { createWorkflowFiles, readWorkflowSnapshot, WorkflowStore } from './store.ts';
18
+ import { resolveWorkflowScript } from './saved.ts';
19
+ import { createWorkflowHost } from './host.ts';
20
+ import { createWorkflowTask, completeWorkflowTask, failWorkflowTask, pauseWorkflowTask, resumeWorkflowTask, resolveResumeTarget, updateWorkflowProgressBatch, workflowResultText, workflowRunId } from './task.ts';
21
+
22
+ export type WorkflowParams = {script?: string; scriptPath?: string; name?: string; args?: unknown; resumeFromRunId?: string};
23
+ export const workflowActive = (task: {status: string}) => task.status === 'running' || task.status === 'paused';
24
+ export class WorkflowManager {
25
+ readonly tasks = new Map<string, OwnedWorkflowTask>();
26
+ private runs = new Map<string, {done: Promise<void>; store: WorkflowStore; settled: boolean}>();
27
+ private listeners = new Set<() => void>();
28
+ private runtime?: Promise<typeof import('./runtime/run.ts')>;
29
+ private starting = 0;
30
+ closed = false;
31
+ constructor(readonly agents: AgentManager, private jobs: () => JobManager) {}
32
+ subscribe(listener: () => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener); }
33
+ changed = (): void => { for (const listener of [...this.listeners]) listener(); };
34
+ get(id: string): OwnedWorkflowTask {
35
+ const task = this.tasks.get(id);
36
+ if (!task) throw new ToolError('NOT_FOUND', `No workflow ${id}. Use a wf_ ID from this branch.`, id);
37
+ return task;
38
+ }
39
+ jobManager(): JobManager { return this.jobs(); }
40
+ visible(task: OwnedWorkflowTask, scope: ParentScope): boolean {
41
+ return !scope.run && task.ownerSessionId === scope.ctx.sessionManager.getSessionId()
42
+ && (task.anchorEntryId === null || scope.ctx.sessionManager.getBranch().some(entry => entry.id === task.anchorEntryId));
43
+ }
44
+ restore(entries: WorkflowEntryData[]): void {
45
+ for (const entry of entries) {
46
+ if (this.tasks.has(entry.id)) continue;
47
+ const data = readWorkflowSnapshot(entry.recordPath);
48
+ if (data.id !== entry.id || data.ownerSessionId !== entry.ownerSessionId || data.cwd !== entry.cwd || data.anchorEntryId !== entry.anchorEntryId) {
49
+ throw new ToolError('WORKFLOW_HISTORY', `Workflow snapshot identity mismatch: ${entry.id}. Use another run; this record and its snapshot refer to different owners or runs.`);
50
+ }
51
+ const latest = (entry.endTime ?? 0) >= (data.endTime ?? 0) && !workflowActive(entry) ? entry : data;
52
+ const task = taskFromEntry({...latest, notified: data.notified || entry.notified});
53
+ // A saved running snapshot has no thread in this process; preserve its journal for explicit replay.
54
+ if (workflowActive(task)) { failWorkflowTask(task, 'No live process owns this workflow. Replay its journal from /subagents Workflows or pass resumeFromRunId.'); }
55
+ this.agents.restore(task.children);
56
+ this.tasks.set(task.id, task);
57
+ }
58
+ }
59
+ async start(params: WorkflowParams, scope: ParentScope, config: SuiteConfig, toolCallId?: string): Promise<OwnedWorkflowTask> {
60
+ if (this.closed || this.agents.closed) throw new ToolError('CLOSING', 'Pi is quitting. Start the workflow after reopening Pi.');
61
+ if (scope.run) throw new ToolError('INVALID_ARGS', 'agent_workflow only runs in the main session. Ask the main session to launch it.');
62
+ if (!config.agents.workflows) throw new ToolError('INVALID_ARGS', 'agents.workflows is disabled; use agent_start instead');
63
+ scope = captureParent(scope); this.jobs();
64
+ const source = resolveWorkflowScript(params, scope.ctx.cwd, {trusted: scope.ctx.isProjectTrusted(), packageGate: config.agents.packageWorkflows});
65
+ if (!source.ok) throw new ToolError('INVALID_ARGS', source.message);
66
+ const target = resolveResumeTarget(params.resumeFromRunId, this.tasks);
67
+ if (target && !target.ok) throw new ToolError('INVALID_ARGS', target.message);
68
+ if (target && !this.visible(this.get(target.runId), scope)) throw new ToolError('NOT_OWNER', 'Resume target is outside this session branch; pass a finished wf_ run from the current branch');
69
+ const replay = target ? readJournal(target.journalPath) : undefined;
70
+ const id = workflowRunId(), files = createWorkflowFiles(scope.owner!.ownerSessionId, id, source.script);
71
+ const task = Object.assign(createWorkflowTask({id, script: source.script, ...files, args: params.args,
72
+ toolCallId, replay: replay?.entries, resumedFrom: target?.runId}),
73
+ {cwd: scope.ctx.cwd, ...scope.owner!, recordPath: files.recordPath, resultPath: files.resultPath, notified: false, children: [] as OwnedWorkflowTask['children']});
74
+ if (replay?.truncated) updateWorkflowProgressBatch(task, [{type: 'workflow_log', message: 'Resume journal has an incomplete final append; only its complete prefix is available.'}]);
75
+ const store = new WorkflowStore(workflowEntryData(task));
76
+ this.starting++;
77
+ try { await store.save(workflowEntryData(task)); }
78
+ finally { this.starting--; }
79
+ // Quit can race the initial disk write, before a Worker has been admitted.
80
+ if (this.closed || this.agents.closed) throw new ToolError('CLOSING', 'Pi quit before the workflow could launch. Start it after reopening Pi.');
81
+ this.tasks.set(id, task);
82
+ const host = createWorkflowHost({scope, manager: this.agents, jobs: this.jobs, workflowId: id,
83
+ signal: task.abortController.signal, config: () => loadConfig(task.cwd)});
84
+ const done = this.execute(task, store, host);
85
+ this.runs.set(id, {done, store, settled: false}); this.changed(); return task;
86
+ }
87
+ private async execute(task: OwnedWorkflowTask, store: WorkflowStore, host: ReturnType<typeof createWorkflowHost>): Promise<void> {
88
+ try {
89
+ const { runWorkflow } = await (this.runtime ??= import('./runtime/run.ts'));
90
+ const result = await runWorkflow({script: task.script, args: task.args, host, signal: task.abortController.signal,
91
+ onMeta: meta => { task.meta = meta; task.workflowName = meta.name; },
92
+ journal: {entries: task.replay, append: entry => appendJournal(task.journalPath!, entry)},
93
+ onControl: control => { task.control = control; },
94
+ onProgress: entries => { updateWorkflowProgressBatch(task, entries); this.changed(); }});
95
+ await host.close();
96
+ completeWorkflowTask(task, result);
97
+ } catch (error) {
98
+ task.abortController.abort();
99
+ let message = error instanceof Error ? error.message : String(error);
100
+ try { await host.close(); } catch (cleanup) { message += `; workflow cleanup failed: ${String(cleanup)}`; }
101
+ failWorkflowTask(task, message);
102
+ }
103
+ try {
104
+ writeFileSync(task.resultPath, workflowResultText(task), {flag: 'wx', mode: 0o600});
105
+ await store.save(this.snapshot(task));
106
+ } catch (error) { failWorkflowTask(task, `Workflow result persistence failed: ${String(error)}`); }
107
+ // The only completion signal comes after child/job cleanup and result persistence.
108
+ this.runs.get(task.id)!.settled = true;
109
+ this.changed();
110
+ }
111
+ settled(id: string): boolean { return this.runs.get(id)?.settled ?? !workflowActive(this.get(id)); }
112
+ /** Persist references; the shared SDK session remains the sole source of child transcript/result text. */
113
+ snapshot(task: OwnedWorkflowTask): WorkflowEntryData {
114
+ if (this.runs.has(task.id)) task.children = this.agents.records().filter(record => record.workflowId === task.id).map(record => {
115
+ const {result, structuredJson, ...reference} = record; return reference;
116
+ });
117
+ return workflowEntryData(task);
118
+ }
119
+ finished(id: string): Promise<void> { this.get(id); return this.runs.get(id)?.done ?? Promise.resolve(); }
120
+ async pause(id: string): Promise<boolean> {
121
+ const task = this.get(id), changed = pauseWorkflowTask(task);
122
+ if (changed) { await this.runs.get(id)!.store.save(this.snapshot(task)); this.changed(); }
123
+ return changed;
124
+ }
125
+ async resume(id: string): Promise<boolean> {
126
+ const task = this.get(id), changed = resumeWorkflowTask(task);
127
+ if (changed) { await this.runs.get(id)!.store.save(this.snapshot(task)); this.changed(); }
128
+ return changed;
129
+ }
130
+ async stop(id: string): Promise<boolean> {
131
+ const task = this.get(id), requested = workflowActive(task);
132
+ if (requested) task.abortController.abort();
133
+ await this.finished(id); return requested;
134
+ }
135
+ /** Keep the owner through initial admission and the final result write, as well as Worker execution. */
136
+ busy(): boolean {
137
+ if (this.starting) return true;
138
+ for (const run of this.runs.values()) if (!run.settled) return true;
139
+ return false;
140
+ }
141
+ async shutdown(): Promise<void> {
142
+ this.closed = true;
143
+ for (const task of this.tasks.values()) if (workflowActive(task)) task.abortController.abort();
144
+ await Promise.all([...this.runs.values()].map(run => run.done));
145
+ }
146
+ }
147
+ export function workflowRuntime(agents = agentRuntime()): OwnerHandle<WorkflowManager> {
148
+ const agentDir = getAgentDir();
149
+ const handle = acquireOwner(WORKFLOW_OWNER, 'workflow', agentDir, () => {
150
+ const runtime = acquireRuntime(agentDir);
151
+ return new WorkflowManager(agents.owner, () => {
152
+ if (runtime.mode !== 'active') throw new ToolError('RUNTIME_UNAVAILABLE', runtime.reason);
153
+ return runtime.manager;
154
+ });
155
+ }, { matches: owner => owner.agents === agents.owner });
156
+ // A workflow cannot accept new runs while its agents owner is stale.
157
+ return { owner: handle.owner, stale: handle.stale ?? agents.stale };
158
+ }
159
+
160
+ /** History can observe an existing owner without admitting the workflows module. */
161
+ export function findWorkflowTask(id: string): OwnedWorkflowTask | undefined {
162
+ const owner = existingOwner(WORKFLOW_OWNER, getAgentDir()) as WorkflowManager | undefined;
163
+ return owner?.tasks.get(id);
164
+ }
165
+
166
+ /** Module admission does not own the lifetime of an already running Worker. */
167
+ export function quitExistingWorkflowRuntime(agentDir: string): Promise<void> | undefined {
168
+ return existingOwner(WORKFLOW_OWNER, agentDir)?.shutdown();
169
+ }
@@ -0,0 +1,323 @@
1
+ // Imported/adapted from @tintinweb/pi-subagents 0.23.0 src/workflow/meta.ts (MIT).
2
+ /**
3
+ * meta.ts — extract and validate a workflow script's `meta` block.
4
+ *
5
+ * Workflow scripts open with `export const meta = { ... }`, but the script body
6
+ * runs through `node:vm`, which has no module loader — `export` is a syntax
7
+ * error there. The block also has to be readable *before* execution, because the
8
+ * declared phases seed the progress groups the UI renders from the first frame.
9
+ *
10
+ * `meta` must be a pure literal (no variables, calls, spreads, or template
11
+ * interpolation). Without a JavaScript parser dependency, the scan finds the
12
+ * matching brace, `assertPureLiteral` checks the literal grammar, and only that
13
+ * fragment is evaluated in an empty VM so string escapes and numeric literals
14
+ * keep JavaScript semantics.
15
+ *
16
+ * The scanner is string-, comment-, and regex-aware. That matters: a workflow's
17
+ * `detail` text routinely contains braces, and `phases: [{ title: "a}b" }]` must
18
+ * not terminate the scan early.
19
+ */
20
+
21
+ import { createContext, Script } from "node:vm";
22
+ import { assertPureLiteral } from "./literal.ts";
23
+
24
+ /** A phase declared up front, so the UI can show it before any agent runs. */
25
+ export interface WorkflowPhaseMeta {
26
+ title: string;
27
+ detail?: string;
28
+ /** Display text; does not select the model used by calls in this phase. */
29
+ model?: string;
30
+ }
31
+
32
+ export interface WorkflowMeta {
33
+ name: string;
34
+ description: string;
35
+ /** Optional author guidance; the runtime does not use it for scheduling. */
36
+ whenToUse?: string;
37
+ phases?: WorkflowPhaseMeta[];
38
+ }
39
+
40
+ export interface MetaExtraction {
41
+ meta: WorkflowMeta;
42
+ /**
43
+ * The script with the leading `export ` stripped, so `const meta = {...}`
44
+ * compiles inside the vm. Byte offsets after the keyword are untouched, which
45
+ * keeps stack-trace line numbers aligned with what the author wrote.
46
+ */
47
+ body: string;
48
+ }
49
+
50
+ export class WorkflowMetaError extends Error {}
51
+
52
+ /**
53
+ * Wall-clock bound on evaluating the `meta` fragment. Generous for a literal —
54
+ * this exists only to stop a pathological one from hanging the host thread.
55
+ */
56
+ const META_EVAL_TIMEOUT_MS = 100;
57
+
58
+ const PURE_LITERAL_HINT =
59
+ "The `meta` object must be a PURE LITERAL — no variables, function calls, spreads, or template interpolation.";
60
+
61
+ /** Matches `export const meta =` allowing arbitrary inner whitespace. */
62
+ const META_DECLARATION = /(^|[\r\n])[ \t]*export[ \t\r\n]+const[ \t\r\n]+meta[ \t\r\n]*=/;
63
+
64
+ /**
65
+ * Whether `source` even claims to be a workflow script.
66
+ *
67
+ * The cheap half of {@link extractMeta}, exported so a directory of `.js` files
68
+ * can be told apart from a directory of workflows without evaluating anything.
69
+ * A saved-workflow folder is a normal folder — it may hold a build artifact, a
70
+ * config, someone's scratch script — and those should neither be offered as
71
+ * workflows nor produce a parser error when named.
72
+ */
73
+ export function hasMetaDeclaration(source: string): boolean {
74
+ return META_DECLARATION.test(source);
75
+ }
76
+
77
+ interface ScanResult {
78
+ /** Index of the literal's closing brace, or -1 when braces never balance. */
79
+ end: number;
80
+ /**
81
+ * True when a `${` substitution opened inside a template literal. Reported
82
+ * separately because such a fragment can still *evaluate* — `` `a${1+1}b` ``
83
+ * needs no globals — so the impure-literal check below cannot catch it.
84
+ */
85
+ sawInterpolation: boolean;
86
+ }
87
+
88
+ /**
89
+ * Find the index just past the object literal that starts at `open`.
90
+ *
91
+ * Tracks string, template, comment, and regex context so braces inside them do
92
+ * not move the depth counter.
93
+ */
94
+ function scanObjectLiteral(source: string, open: number): ScanResult {
95
+ let depth = 0;
96
+ let i = open;
97
+ let sawInterpolation = false;
98
+ // What we are currently inside of. "code" means brace counting is live.
99
+ let mode: "code" | "line-comment" | "block-comment" | "single" | "double" | "template" | "regex" = "code";
100
+ // Template literals nest: `${ {a:1} }` re-enters code, and the closing brace
101
+ // of that substitution must not be read as the object's. One depth per level.
102
+ const templateStack: number[] = [];
103
+
104
+ while (i < source.length) {
105
+ const c = source[i];
106
+ const next = source[i + 1];
107
+
108
+ if (mode === "line-comment") {
109
+ if (c === "\n") mode = "code";
110
+ i++;
111
+ continue;
112
+ }
113
+ if (mode === "block-comment") {
114
+ if (c === "*" && next === "/") { mode = "code"; i += 2; continue; }
115
+ i++;
116
+ continue;
117
+ }
118
+ if (mode === "single" || mode === "double" || mode === "regex") {
119
+ if (c === "\\") { i += 2; continue; }
120
+ if (mode === "single" && c === "'") mode = "code";
121
+ else if (mode === "double" && c === '"') mode = "code";
122
+ else if (mode === "regex" && c === "/") mode = "code";
123
+ // An unterminated regex/string can't run past a newline; bail to code so a
124
+ // misdetected regex (see below) cannot swallow the rest of the literal.
125
+ else if (c === "\n" && mode !== "double") mode = "code";
126
+ i++;
127
+ continue;
128
+ }
129
+ if (mode === "template") {
130
+ if (c === "\\") { i += 2; continue; }
131
+ if (c === "`") { mode = "code"; i++; continue; }
132
+ if (c === "$" && next === "{") {
133
+ sawInterpolation = true;
134
+ templateStack.push(depth);
135
+ depth++;
136
+ mode = "code";
137
+ i += 2;
138
+ continue;
139
+ }
140
+ i++;
141
+ continue;
142
+ }
143
+
144
+ // mode === "code"
145
+ if (c === "/" && next === "/") { mode = "line-comment"; i += 2; continue; }
146
+ if (c === "/" && next === "*") { mode = "block-comment"; i += 2; continue; }
147
+ if (c === "'") { mode = "single"; i++; continue; }
148
+ if (c === '"') { mode = "double"; i++; continue; }
149
+ if (c === "`") { mode = "template"; i++; continue; }
150
+ if (c === "/" && isRegexPosition(source, i)) { mode = "regex"; i++; continue; }
151
+ if (c === "{") { depth++; i++; continue; }
152
+ if (c === "}") {
153
+ depth--;
154
+ i++;
155
+ if (templateStack.length > 0 && depth === templateStack[templateStack.length - 1]) {
156
+ templateStack.pop();
157
+ mode = "template";
158
+ continue;
159
+ }
160
+ if (depth === 0) return { end: i, sawInterpolation };
161
+ continue;
162
+ }
163
+ i++;
164
+ }
165
+ return { end: -1, sawInterpolation };
166
+ }
167
+
168
+ /**
169
+ * Decide whether the `/` at `i` opens a regex literal rather than a division.
170
+ *
171
+ * Walks back past whitespace and comments to the previous significant char: a
172
+ * regex can only follow an operator or opener, never a value. This is the usual
173
+ * heuristic and it is sufficient here, because the only thing riding on it is
174
+ * not miscounting braces inside a `meta` literal — and a `meta` literal
175
+ * containing division is already not a pure literal.
176
+ */
177
+ function isRegexPosition(source: string, i: number): boolean {
178
+ let j = i - 1;
179
+ while (j >= 0 && /\s/.test(source[j])) j--;
180
+ if (j < 0) return true;
181
+ const prev = source[j];
182
+ // Identifier/number/closer before `/` means division.
183
+ return !/[\w$)\]]/.test(prev);
184
+ }
185
+
186
+ function fail(message: string): never {
187
+ throw new WorkflowMetaError(message);
188
+ }
189
+
190
+ function assertPhases(value: unknown): WorkflowPhaseMeta[] | undefined {
191
+ if (value === undefined) return undefined;
192
+ if (!Array.isArray(value)) fail("`meta.phases` must be an array of { title, detail?, model? } objects.");
193
+ return value.map((entry, index) => {
194
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
195
+ fail(`\`meta.phases[${index}]\` must be an object with a \`title\`.`);
196
+ }
197
+ const { title, detail, model } = entry as Record<string, unknown>;
198
+ if (typeof title !== "string" || title.trim() === "") {
199
+ fail(`\`meta.phases[${index}].title\` must be a non-empty string.`);
200
+ }
201
+ if (detail !== undefined && typeof detail !== "string") {
202
+ fail(`\`meta.phases[${index}].detail\` must be a string.`);
203
+ }
204
+ if (model !== undefined && typeof model !== "string") {
205
+ fail(`\`meta.phases[${index}].model\` must be a string.`);
206
+ }
207
+ return { title, ...(detail !== undefined ? { detail } : {}), ...(model !== undefined ? { model } : {}) };
208
+ });
209
+ }
210
+
211
+ /**
212
+ * Pull `meta` off the front of a workflow script and hand back the runnable body.
213
+ *
214
+ * Throws {@link WorkflowMetaError} with author-facing guidance for every
215
+ * rejection — these messages are shown verbatim to whoever wrote the script.
216
+ */
217
+ export function extractMeta(source: string): MetaExtraction {
218
+ const declaration = META_DECLARATION.exec(source);
219
+ if (!declaration) {
220
+ fail(
221
+ "A workflow script must begin with `export const meta = { name, description }`.\n" +
222
+ PURE_LITERAL_HINT,
223
+ );
224
+ }
225
+
226
+ const assignedAt = declaration.index + declaration[0].length;
227
+ const trivia = /^(?:\s|\/\/[^\r\n]*(?:\r?\n|$)|\/\*[\s\S]*?\*\/)*/.exec(source.slice(assignedAt))![0];
228
+ const open = assignedAt + trivia.length;
229
+ if (source[open] !== "{") fail("`export const meta` must be assigned an object literal.\n" + PURE_LITERAL_HINT);
230
+
231
+ const { end: close, sawInterpolation } = scanObjectLiteral(source, open);
232
+ if (close === -1) fail("`meta` object literal is never closed — check for an unbalanced `{`.");
233
+
234
+ // Caught here rather than by evaluation: a self-contained substitution such as
235
+ // `` `a${1 + 1}b` `` resolves without touching a single global, so it would
236
+ // sail through the empty-context check below and silently produce "a2b".
237
+ if (sawInterpolation) {
238
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: quoting the syntax being rejected
239
+ fail("`meta` must not use template interpolation (`${...}`).\n" + PURE_LITERAL_HINT);
240
+ }
241
+
242
+ const fragment = source.slice(open, close);
243
+ let value: unknown;
244
+ try {
245
+ assertPureLiteral(fragment);
246
+ // Metadata is evaluated on the host before the Worker exists. Keep the
247
+ // upstream deadline here too: very large literals must not stall the TUI.
248
+ value = new Script(`(${fragment})`, { filename: "workflow-meta.js" })
249
+ .runInContext(createContext({}), { timeout: META_EVAL_TIMEOUT_MS });
250
+ } catch (error) {
251
+ const detail = error instanceof Error ? error.message : String(error);
252
+ if (/timed out|Script execution/i.test(detail)) {
253
+ fail(
254
+ `\`meta\` did not finish evaluating within ${META_EVAL_TIMEOUT_MS}ms — it must be a literal, not a computation.\n` +
255
+ PURE_LITERAL_HINT,
256
+ );
257
+ }
258
+ fail(`\`meta\` could not be evaluated: ${detail}\n${PURE_LITERAL_HINT}`);
259
+ }
260
+
261
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
262
+ fail("`meta` must be an object literal.\n" + PURE_LITERAL_HINT);
263
+ }
264
+ const raw = value as Record<string, unknown>;
265
+
266
+ if (typeof raw.name !== "string" || raw.name.trim() === "") {
267
+ fail("`meta.name` is required and must be a non-empty string.");
268
+ }
269
+ if (typeof raw.description !== "string" || raw.description.trim() === "") {
270
+ fail("`meta.description` is required and must be a non-empty string.");
271
+ }
272
+ if (raw.whenToUse !== undefined && typeof raw.whenToUse !== "string") {
273
+ fail("`meta.whenToUse` must be a string.");
274
+ }
275
+ const phases = assertPhases(raw.phases);
276
+
277
+ const meta: WorkflowMeta = {
278
+ name: raw.name,
279
+ description: raw.description,
280
+ ...(raw.whenToUse !== undefined ? { whenToUse: raw.whenToUse as string } : {}),
281
+ ...(phases !== undefined ? { phases } : {}),
282
+ };
283
+
284
+ // Strip only the `export ` keyword. Replacing it with spaces rather than
285
+ // deleting it keeps every subsequent offset — and therefore every reported
286
+ // line and column — identical to the source the author wrote.
287
+ const exportAt = source.indexOf("export", declaration.index);
288
+ const body = `${source.slice(0, exportAt)}${" ".repeat(6)}${source.slice(exportAt + 6)}`;
289
+
290
+ return { meta, body };
291
+ }
292
+
293
+ /**
294
+ * `meta.name` for a call line, without re-parsing on every frame.
295
+ *
296
+ * `renderCall` runs on every repaint, and extraction evaluates a literal in a
297
+ * vm — cheap, but not free at that cadence. Keyed by the exact source, so an
298
+ * edit-and-rerun cycle re-reads it and a hit is always the answer a fresh parse
299
+ * would give.
300
+ */
301
+ const workflowNames = new Map<string, string>();
302
+
303
+ /** The label an `agent_workflow` call renders under, from whichever field it carries. */
304
+ export function workflowCallName(args: { script?: string; scriptPath?: string; name?: string }): string {
305
+ const source = args.script;
306
+ if (source === undefined || source === "") {
307
+ // A path-only call would need a synchronous file read per repaint to do
308
+ // better than this, and the file name is what the author will recognize.
309
+ if (args.scriptPath !== undefined) return args.scriptPath.split(/[/\\]/).pop() ?? "workflow";
310
+ // A saved workflow is already named by the caller; no read needed at all.
311
+ return args.name !== undefined && args.name !== "" ? args.name : "workflow";
312
+ }
313
+ const cached = workflowNames.get(source);
314
+ if (cached !== undefined) return cached;
315
+ let name = "workflow";
316
+ try {
317
+ name = extractMeta(source).meta.name;
318
+ } catch {
319
+ // An invalid script still gets a call line; `execute` reports why.
320
+ }
321
+ workflowNames.set(source, name);
322
+ return name;
323
+ }
@@ -0,0 +1,184 @@
1
+ // Imported/adapted from @tintinweb/pi-subagents 0.23.0 src/workflow/progress.ts (MIT).
2
+ import type { WorkflowMeta } from "../meta.ts";
3
+ import type { WorkflowRunStatus, PhaseGroup } from "./types.ts";
4
+ import { elapsedMs } from "./model.ts";
5
+
6
+ const plural = (n: number, word: string) => (n === 1 ? word : `${word}s`);
7
+
8
+ /** `1m12s` / `9s` / `340ms`, matching how the rest of the extension reads. */
9
+ export function formatDuration(ms: number): string {
10
+ if (ms < 1000) return `${Math.max(0, Math.round(ms))}ms`;
11
+ const totalSeconds = Math.round(ms / 1000);
12
+ const minutes = Math.floor(totalSeconds / 60);
13
+ const seconds = totalSeconds % 60;
14
+ if (minutes === 0) return `${seconds}s`;
15
+ return `${minutes}m${seconds.toString().padStart(2, "0")}s`;
16
+ }
17
+
18
+ export interface WorkflowHeader {
19
+ name: string;
20
+ subtext: string;
21
+ stats: string;
22
+ state?: 'done' | 'stopped' | 'paused' | 'failed';
23
+ }
24
+
25
+ /**
26
+ * The one-line summary above the tree: `3/7 agents · 1m12s`, plus a terminal
27
+ * suffix once the run stops. Deliberately carries no phase count.
28
+ */
29
+ export function header(
30
+ task: {
31
+ status: WorkflowRunStatus;
32
+ workflowName?: string;
33
+ summary?: string;
34
+ description?: string;
35
+ startTime: number;
36
+ endTime?: number;
37
+ totalPausedMs?: number;
38
+ },
39
+ meta: WorkflowMeta | undefined,
40
+ groups: readonly PhaseGroup[],
41
+ agentCount: number,
42
+ now: number,
43
+ ): WorkflowHeader {
44
+ const state = task.status === 'completed' ? 'done' : task.status === 'killed' ? 'stopped'
45
+ : task.status === 'paused' || task.status === 'failed' ? task.status : undefined;
46
+
47
+ let doneAgents = 0;
48
+ let totalAgents = 0;
49
+ for (const group of groups) {
50
+ doneAgents += group.doneCount;
51
+ totalAgents += group.totalCount;
52
+ }
53
+ totalAgents = Math.max(agentCount, totalAgents, doneAgents);
54
+
55
+ return {
56
+ name: task.workflowName ?? meta?.name ?? task.summary ?? task.description ?? "workflow",
57
+ subtext: meta?.description ?? task.description ?? task.summary ?? "",
58
+ stats: `${doneAgents}/${totalAgents} ${plural(totalAgents, "agent")} · ${formatDuration(elapsedMs(task, now))}`,
59
+ state,
60
+ };
61
+ }
62
+
63
+ /* ------------------------------------------------------------------------- *
64
+ * Size warning
65
+ * ------------------------------------------------------------------------- */
66
+
67
+ export const DEFAULT_AGENT_CAP = 25;
68
+ export const DEFAULT_TOKEN_CAP = 1_500_000;
69
+ /** Assumed spend per agent before any has reported, for the projection. */
70
+ export const ASSUMED_TOKENS_PER_AGENT = 70_000;
71
+
72
+ export interface SizeWarning {
73
+ axis: "agents" | "tokens" | "both";
74
+ scheduledAgents: number;
75
+ totalTokens: number;
76
+ projectedTokens: number;
77
+ agentCap: number;
78
+ tokenCap: number;
79
+ }
80
+
81
+ /**
82
+ * Warn when a run is about to get expensive.
83
+ *
84
+ * The projection matters more than the current total: a 200-agent fan-out is
85
+ * worth flagging at agent 3, not after it has already spent the budget.
86
+ */
87
+ export function sizeWarning(input: {
88
+ scheduledAgents: number;
89
+ startedAgents: number;
90
+ totalTokens: number;
91
+ agentCap?: number;
92
+ tokenCap?: number;
93
+ }): SizeWarning | undefined {
94
+ const agentCap = input.agentCap ?? DEFAULT_AGENT_CAP;
95
+ const tokenCap = input.tokenCap ?? DEFAULT_TOKEN_CAP;
96
+ const perAgent = input.startedAgents > 0 ? input.totalTokens / input.startedAgents : ASSUMED_TOKENS_PER_AGENT;
97
+ const projectedTokens = Math.max(input.totalTokens, Math.round(perAgent * input.scheduledAgents));
98
+
99
+ const overAgents = input.scheduledAgents > agentCap;
100
+ const overTokens = input.totalTokens > tokenCap || projectedTokens > tokenCap;
101
+ if (!overAgents && !overTokens) return undefined;
102
+
103
+ return {
104
+ axis: overAgents && overTokens ? "both" : overAgents ? "agents" : "tokens",
105
+ scheduledAgents: input.scheduledAgents,
106
+ totalTokens: input.totalTokens,
107
+ projectedTokens,
108
+ agentCap,
109
+ tokenCap,
110
+ };
111
+ }
112
+
113
+ /* ------------------------------------------------------------------------- *
114
+ * Footer phase label
115
+ * ------------------------------------------------------------------------- */
116
+
117
+ /** Words whose gerund is irregular, or which read better left alone. */
118
+ const GERUND_OVERRIDES = new Map<string, string | null>([
119
+ ["commit", "committing"],
120
+ ["submit", "submitting"],
121
+ ["format", "formatting"],
122
+ ["setup", null],
123
+ ["cleanup", null],
124
+ ]);
125
+
126
+ const VOWELS = "aeiou";
127
+ const GERUND_CANDIDATE = /^[A-Za-z]{3,12}$/;
128
+
129
+ /**
130
+ * Render a phase title as an activity: `Scan` → `Scanning`.
131
+ *
132
+ * Only applied in the footer, where the line reads as "what is happening now".
133
+ * Anything that is not a plain short word is left untouched.
134
+ */
135
+ export function gerund(word: string): string {
136
+ if (!GERUND_CANDIDATE.test(word)) return word;
137
+ const lower = word.toLowerCase();
138
+
139
+ const override = GERUND_OVERRIDES.get(lower);
140
+ if (override !== undefined) return override === null ? word : word[0] + override.slice(1);
141
+
142
+ if (lower.endsWith("ing")) return word;
143
+ if (lower.endsWith("ie")) return `${word.slice(0, -2)}ying`;
144
+ if (lower.endsWith("e") && !lower.endsWith("ee") && !lower.endsWith("ye")) return `${word.slice(0, -1)}ing`;
145
+
146
+ // Short consonant-vowel-consonant words double the final consonant: run →
147
+ // running. `w`, `x` and `y` never double.
148
+ const last = lower.at(-1) ?? "";
149
+ if (
150
+ lower.length <= 4 &&
151
+ !VOWELS.includes(lower.at(-3) ?? "") &&
152
+ VOWELS.includes(lower.at(-2) ?? "") &&
153
+ !VOWELS.includes(last) &&
154
+ !"wxy".includes(last)
155
+ ) {
156
+ return `${word}${last}ing`;
157
+ }
158
+ return `${word}ing`;
159
+ }
160
+
161
+ /** Truncation width for a footer phase title. */
162
+ const FOOTER_TITLE_WIDTH = 16;
163
+
164
+ const truncate = (text: string, width: number) =>
165
+ text.length <= width ? text : `${text.slice(0, Math.max(1, width - 1))}…`;
166
+
167
+ /**
168
+ * The footer's "what is this run doing" label.
169
+ *
170
+ * One active phase shows its position; two concurrent phases are joined, since
171
+ * a barrier-free pipeline routinely has work in more than one at a time.
172
+ */
173
+ export function footerPhaseLabel(input: {
174
+ titles: readonly string[];
175
+ positionStart: number;
176
+ totalPhases: number;
177
+ }): string {
178
+ const titles = input.titles.map(gerund);
179
+ if (titles.length === 0) return "";
180
+ if (titles.length === 1) {
181
+ return `${truncate(titles[0], FOOTER_TITLE_WIDTH)} (${input.positionStart}/${input.totalPhases})`;
182
+ }
183
+ return titles.map(t => truncate(t, FOOTER_TITLE_WIDTH)).join(" & ");
184
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./types.ts";
2
+ export * from "./model.ts";
3
+ export * from "./format.ts";