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,406 @@
1
+ import { getMarkdownTheme, type Theme } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ CURSOR_MARKER, Container, Editor, Input, Key, Markdown, fuzzyFilter, matchesKey, truncateToWidth,
4
+ visibleWidth, type TUI, type TuiMouseEvent, type TuiMouseEventResult,
5
+ } from "@earendil-works/pi-tui";
6
+ import type { SuiteConfig } from "../runtime/config.ts";
7
+ import type { Dock } from "../ui/dock.ts";
8
+ import { ScrollView } from "../ui/scroll.ts";
9
+ import { readingWindow } from '../ui/reading.ts';
10
+ import type { Transcript } from "../ui/transcript.ts";
11
+ import { AskForm } from "./form.ts";
12
+ import type { AskResult, Option } from "./schema.ts";
13
+ import { askKey } from "./keys.ts";
14
+ import { answerText, idleTime, optionRow, questionTabs, type TabRegion } from "./render.ts";
15
+
16
+ import { choiceLines, frame, frameLines, listWindow, questionLines, reviewLines, topBorder, type ListPosition } from './layout.ts';
17
+
18
+ type Focus = "answer" | "search" | "comment" | "actions" | "history" | "details";
19
+ export class AskView extends Container {
20
+ focused = true;
21
+ private focus: Focus = "answer";
22
+ private action = 0;
23
+ private search = new Input({ prompt: "Search: " });
24
+ private editors: Editor[];
25
+ private comments: Input[];
26
+ private history: ScrollView;
27
+ private descriptions = new Map<string, ScrollView>();
28
+ private detailKey = "";
29
+ private historyReturn: Focus = "answer";
30
+ private reading?: "history" | "details";
31
+ private closed = false;
32
+ private timer?: ReturnType<typeof setTimeout>;
33
+ private countdown?: ReturnType<typeof setInterval>;
34
+ private deadline?: number;
35
+ private started = false;
36
+ private height = 3;
37
+ private notice = "";
38
+ private reviewCursor = 0;
39
+ private tabRegions: TabRegion[] = [];
40
+ private listRegion = { y: 0, x: 0, width: 0, indices: [] as number[] };
41
+ private tabY = 0;
42
+ private scrollPosition = { offset: 0, total: 0, height: 0 };
43
+ private expanded = false;
44
+ private collapsible = false;
45
+ private measured = '';
46
+ private inlineHeight = 3;
47
+ private positions = new Map<number, ListPosition>();
48
+ private position(): ListPosition {
49
+ const key = this.form.reviewing ? -1 : this.form.index;
50
+ if (!this.positions.has(key)) this.positions.set(key, { offset: 0, cursor: -1 });
51
+ return this.positions.get(key)!;
52
+ }
53
+ private abort = () => this.finish({ status: "cancelled", responses: [] });
54
+
55
+ constructor(
56
+ readonly form: AskForm, private tui: TUI, private theme: Theme,
57
+ private dock: Dock, private config: SuiteConfig, private transcript: Transcript,
58
+ private done: (result: AskResult) => void, private timeout: number,
59
+ private signal?: AbortSignal, private allowComment = false, private requester = "main", private heading?: string,
60
+ ) {
61
+ super();
62
+ const editorTheme = { borderColor: (text: string) => theme.fg("accent", text), selectList: {
63
+ selectedPrefix: (s: string) => theme.fg("accent", s), selectedText: (s: string) => theme.fg("accent", s),
64
+ description: (s: string) => theme.fg("muted", s), scrollInfo: (s: string) => theme.fg("dim", s), noMatch: (s: string) => theme.fg("warning", s),
65
+ } };
66
+ this.editors = form.drafts.map((draft, index) => {
67
+ const editor = new Editor(tui, editorTheme, { paddingX: 0 });
68
+ // Native submission clears the chat editor. Ask confirms without clearing so
69
+ // revisiting a question retains both its draft and native editing position.
70
+ editor.disableSubmit = true;
71
+ editor.setText(draft.text);
72
+ editor.onChange = text => { form.drafts[index].text = text; };
73
+ return editor;
74
+ });
75
+ this.comments = form.drafts.map(draft => {
76
+ const input = new Input({ prompt: "Comment: " });
77
+ input.onSubmit = () => { draft.comment = input.getValue(); this.focus = "actions"; };
78
+ return input;
79
+ });
80
+ this.search.onSubmit = () => { this.focus = "answer"; };
81
+ this.history = new ScrollView(transcript);
82
+ signal?.addEventListener("abort", this.abort, { once: true });
83
+ }
84
+
85
+ private finish(result: AskResult): void {
86
+ // Input, expiry and abort may reach this boundary in the same event-loop turn.
87
+ if (this.closed) return;
88
+ this.closed = true; this.dispose(); this.done(result);
89
+ }
90
+ dispose(): void {
91
+ clearTimeout(this.timer); clearInterval(this.countdown);
92
+ this.history.dispose(); for (const reader of this.descriptions.values()) reader.dispose();
93
+ this.signal?.removeEventListener("abort", this.abort);
94
+ this.dock.setDetail(false);
95
+ }
96
+ cancel(): void { this.abort(); }
97
+ private skip(): void { this.finish(this.form.skip()); }
98
+ private touch(): void {
99
+ if (!this.started || this.closed || this.timeout === 0) return;
100
+ this.deadline = Date.now() + this.timeout;
101
+ clearTimeout(this.timer);
102
+ this.timer = setTimeout(() => this.finish(this.form.expire()), this.timeout);
103
+ }
104
+ invalidate(): void {
105
+ this.editors.forEach(editor => editor.invalidate());
106
+ this.history.invalidate(); this.descriptions.forEach(view => view.invalidate());
107
+ }
108
+ private options(): Option[] {
109
+ return fuzzyFilter(this.form.question.options, this.form.draft.query, option => `${option.title} ${option.description ?? ""}`);
110
+ }
111
+ private get actions(): string[] {
112
+ if (this.focus === "history" || this.focus === "details") return ["Previous page", "Next page", "Back"];
113
+ const expand = this.expanded ? ["Collapse"] : this.collapsible ? ["Expand"] : [];
114
+ if (this.form.reviewing) return ["Submit", "View details", ...expand, "History", "Skip"];
115
+ return ["View details", ...expand, "History", ...(this.form.question.options.length ? ["Search"] : []),
116
+ ...(this.allowComment ? ["Comment"] : []), "Skip"];
117
+ }
118
+ private advance(): void {
119
+ if (this.form.reviewing) {
120
+ if (this.form.complete) this.finish({ status: "answered", responses: this.form.responses() });
121
+ else this.notice = `${this.form.questions.filter((_, index) => !this.form.answered(index)).length} unanswered`;
122
+ } else if (this.form.response()) {
123
+ if (this.form.questions.length === 1) this.finish({ status: "answered", responses: this.form.responses() });
124
+ else this.changeQuestion(1);
125
+ } else this.notice = this.form.question.allowMultiple && !this.form.draft.editing ? "Space to select" : "Answer required";
126
+ }
127
+ private selectPage(page: number): void {
128
+ this.form.draft.editing = false;
129
+ this.form.reviewing = page === this.form.questions.length;
130
+ if (!this.form.reviewing) this.form.index = page;
131
+ this.search.setValue(this.form.draft.query); this.focus = "answer"; this.action = 0; this.notice = "";
132
+ }
133
+ private changeQuestion(delta: number): void {
134
+ if (this.form.questions.length === 1) return;
135
+ const count = this.form.questions.length + 1;
136
+ const page = this.form.reviewing ? count - 1 : this.form.index;
137
+ this.selectPage((page + delta + count) % count);
138
+ }
139
+ private openHistory(): void {
140
+ this.historyReturn = this.focus; this.reading = "history"; this.focus = "history"; this.action = 0; this.dock.setDetail(true);
141
+ }
142
+ private openDetails(): void {
143
+ const index = this.form.reviewing ? this.reviewCursor : this.form.index;
144
+ const question = this.form.questions[index];
145
+ const option = this.form.reviewing || this.form.draft.editing ? undefined : this.options()[this.form.draft.cursor];
146
+ const response = this.form.reviewing ? this.form.response(index) : undefined;
147
+ const text = [this.requester, this.heading, question.question, option?.title, option?.description,
148
+ ...!this.form.reviewing && !option && this.form.draft.text ? [`✎ ${this.form.draft.text}`] : [],
149
+ response ? answerText(response) : undefined, response?.comment].filter(Boolean).join("\n\n");
150
+ this.detailKey = `details:${index}:${option?.id ?? 'question'}`;
151
+ let reader = this.descriptions.get(this.detailKey);
152
+ if (!reader) { reader = new ScrollView(new Markdown(text, 0, 0, getMarkdownTheme())); this.descriptions.set(this.detailKey, reader); }
153
+ else reader.setContent(new Markdown(text, 0, 0, getMarkdownTheme()));
154
+ this.reading = "details"; this.focus = "details"; this.action = 0; this.dock.setDetail(true);
155
+ }
156
+ private get reader(): ScrollView { return this.reading === "history" ? this.history : this.descriptions.get(this.detailKey)!; }
157
+ private closeReader(): void {
158
+ this.focus = this.reading === "history" ? this.historyReturn : "answer";
159
+ this.reading = undefined;
160
+ this.action = 0; this.dock.setDetail(false);
161
+ }
162
+ private act(): void {
163
+ const action = this.actions[this.action];
164
+ if (action === "Submit") this.advance();
165
+ else if (action === "History") this.openHistory();
166
+ else if (action === "View details") this.openDetails();
167
+ else if (action === "Expand" || action === "Collapse") this.toggleExpanded();
168
+ else if (action === "Search") this.openSearch();
169
+ else if (action === "Comment") this.focus = "comment";
170
+ else if (action === "Skip") this.skip();
171
+ else if (action === "Previous page") this.reader.scroll(-this.height + 3);
172
+ else if (action === "Next page") this.reader.scroll(this.height - 3);
173
+ else if (action === "Back") this.closeReader();
174
+ }
175
+ private openSearch(): void { this.focus = "search"; this.search.setValue(this.form.draft.query); }
176
+ private editText(): void {
177
+ this.form.editText(); this.form.draft.cursor = this.options().length; this.focus = "answer";
178
+ }
179
+ private toggleExpanded(): void { this.expanded = !this.expanded; this.measured = ''; }
180
+ private pageKey(data: string): void {
181
+ if (this.expanded && (matchesKey(data, Key.pageUp) || matchesKey(data, Key.pageDown))) {
182
+ this.position().offset += (matchesKey(data, Key.pageUp) ? -1 : 1) * Math.max(1, this.listRegion.indices.length - 1); return;
183
+ }
184
+ if (this.form.reviewing) {
185
+ if (matchesKey(data, Key.up) || matchesKey(data, Key.pageUp)) this.reviewCursor = Math.max(0, this.reviewCursor - 1);
186
+ else if (matchesKey(data, Key.down) || matchesKey(data, Key.pageDown)) this.reviewCursor = Math.min(this.form.questions.length - 1, this.reviewCursor + 1);
187
+ }
188
+ const action = askKey(data, this.form, this.options(), this.height);
189
+ if (action === "confirm") this.advance();
190
+ else if (action === "previous") this.changeQuestion(-1);
191
+ else if (action === "next") this.changeQuestion(1);
192
+ else if (action === "search") this.openSearch();
193
+ else if (action === "details") this.openDetails();
194
+ else if (action === "expand" && (this.collapsible || this.expanded)) this.toggleExpanded();
195
+ else if (action === "text") this.editText();
196
+ }
197
+ handleInput(data: string): void {
198
+ if (this.closed) return;
199
+ this.touch(); this.notice = "";
200
+ if (this.reading === "history" && matchesKey(data, Key.tab)) {
201
+ this.focus = this.focus === "history" ? "answer" : this.focus === "answer" ? "actions" : "history";
202
+ this.action = 0; this.tui.requestRender(); return;
203
+ }
204
+ if (this.focus === "history" || this.focus === "details") {
205
+ if (this.reader.searching) this.reader.handleInput(data);
206
+ else if (matchesKey(data, Key.escape) || matchesKey(data, this.config.ask.historyKey)) this.closeReader();
207
+ else if (matchesKey(data, Key.left)) this.action = Math.max(0, this.action - 1);
208
+ else if (matchesKey(data, Key.right)) this.action = Math.min(this.actions.length - 1, this.action + 1);
209
+ else if (matchesKey(data, Key.enter)) this.act();
210
+ else if (data === "t" && this.focus === "history") this.transcript.toggleTools();
211
+ else if (data === "i" && this.focus === "history") this.transcript.toggleThinking();
212
+ else this.reader.handleInput(data);
213
+ } else if (matchesKey(data, this.config.ask.historyKey)) {
214
+ if (this.reading) this.closeReader(); else this.openHistory();
215
+ } else if (matchesKey(data, Key.escape)) {
216
+ if (this.focus !== "answer") this.focus = "answer";
217
+ else if (!this.form.reviewing && this.form.draft.editing) this.form.draft.editing = false;
218
+ else this.skip();
219
+ } else if (matchesKey(data, Key.tab)) {
220
+ this.focus = this.focus === "actions" ? "answer" : "actions"; this.action = 0;
221
+ } else if (this.focus === "search") {
222
+ this.search.handleInput(data); this.form.draft.query = this.search.getValue(); this.form.draft.cursor = 0; this.position().offset = 0; this.position().cursor = -1;
223
+ } else if (this.focus === "comment") {
224
+ this.comments[this.form.index].handleInput(data); this.form.draft.comment = this.comments[this.form.index].getValue();
225
+ } else if (this.focus === "actions") {
226
+ if (matchesKey(data, Key.left) || matchesKey(data, Key.up)) this.action = Math.max(0, this.action - 1);
227
+ else if (matchesKey(data, Key.right) || matchesKey(data, Key.down)) this.action = Math.min(this.actions.length - 1, this.action + 1);
228
+ else if (matchesKey(data, Key.enter)) this.act();
229
+ } else if (!this.form.reviewing && this.form.draft.editing) {
230
+ if (matchesKey(data, Key.enter)) this.advance();
231
+ else this.editors[this.form.index].handleInput(data);
232
+ }
233
+ else this.pageKey(data);
234
+ this.tui.requestRender();
235
+ }
236
+ override handleMouse(event: TuiMouseEvent): ReturnType<Container['handleMouse']> {
237
+ if (this.closed) return;
238
+ let result: TuiMouseEventResult | undefined;
239
+ if (!this.reading && event.type === "click" && event.button === "left" && event.y === this.tabY && this.tabRegions.length) {
240
+ const tab = this.tabRegions.find(tab => event.x >= tab.start && event.x < tab.end);
241
+ if (tab) { this.selectPage(tab.page); result = { handled: true }; }
242
+ } else if (!this.reading && event.x >= this.listRegion.x && event.x < this.listRegion.x + this.listRegion.width
243
+ && event.y >= this.listRegion.y && event.y < this.listRegion.y + this.listRegion.indices.length) {
244
+ if (event.type === 'wheel') {
245
+ if (this.form.reviewing) this.reviewCursor = Math.max(0, Math.min(this.form.questions.length - 1, this.reviewCursor + (event.wheelDelta ?? 0)));
246
+ else this.form.draft.cursor = Math.max(0, Math.min(this.options().length, this.form.draft.cursor + (event.wheelDelta ?? 0)));
247
+ result = { handled: true };
248
+ } else if (event.type === 'click' && event.button === 'left') {
249
+ const index = this.listRegion.indices[event.y - this.listRegion.y];
250
+ this.focus = 'answer';
251
+ if (this.form.reviewing) this.reviewCursor = index;
252
+ else { this.form.draft.cursor = index; this.pageKey(' '); }
253
+ result = { handled: true };
254
+ }
255
+ }
256
+ if (result?.handled) { this.touch(); this.notice = ""; this.tui.requestRender(); }
257
+ return result && {target: {component: this, originX: event.screenX - event.x, originY: event.screenY - event.y, width: event.width, height: event.height}, ...result, handled: true};
258
+ }
259
+ private get escapeHint(): string {
260
+ return this.reading || this.focus !== "answer" || (!this.form.reviewing && this.form.draft.editing) ? "Esc back" : "Esc skip";
261
+ }
262
+ private renderActions(width: number): string {
263
+ const active = this.actions[this.action] ?? this.actions[0];
264
+ const listFocus = this.focus === 'answer' && (this.form.reviewing || !this.form.draft.editing);
265
+ const hint = !this.reading && listFocus ? `${this.expanded ? ' · e collapse' : this.collapsible ? ' · e expand' : ''} · d full text` : '';
266
+ const controls = this.theme.fg('accent', `[${active}]`) + ` · ${this.escapeHint} · Tab · ${this.action + 1}/${this.actions.length} ←→ Enter`;
267
+ return truncateToWidth(controls, Math.max(0, width - visibleWidth(hint)), '') + hint;
268
+ }
269
+ private editorLines(width: number, height: number): string[] {
270
+ const editor = this.editors[this.form.index]; editor.focused = this.focus === "answer";
271
+ const rendered = editor.render(Math.max(1, width - 2)).slice(1, -1);
272
+ const cursor = rendered.findIndex(line => line.includes(CURSOR_MARKER));
273
+ const start = Math.max(0, cursor - height + 1);
274
+ return rendered.slice(start, start + height).map(line => this.theme.fg("accent", "✎ ") + line);
275
+ }
276
+ private answerLine(width: number): string {
277
+ if (this.focus === "search") { this.search.focused = true; return this.search.render(width)[0]; }
278
+ if (this.focus === "comment") { this.comments[this.form.index].focused = true; return this.comments[this.form.index].render(width)[0]; }
279
+ if (this.form.reviewing) return reviewLines(this.form, this.theme, width, false)[this.reviewCursor][0];
280
+ if (this.form.draft.editing) return this.editorLines(width, 1)[0] ?? "";
281
+ const options = this.options();
282
+ return truncateToWidth(optionRow(this.theme, this.form.question, this.form.draft, options[this.form.draft.cursor], this.focus === "answer"), width);
283
+ }
284
+ private preview(option: Option): ScrollView {
285
+ const key = `preview:${this.form.index}:${option.id}`;
286
+ if (!this.descriptions.has(key)) this.descriptions.set(key,
287
+ new ScrollView(new Markdown(`${option.title}\n\n${option.description ?? ''}`, 0, 0, getMarkdownTheme())));
288
+ return this.descriptions.get(key)!;
289
+ }
290
+ private optionLines(width: number, height: number, y: number, x: number): string[] {
291
+ const options = this.options(), choices = [...options, undefined];
292
+ this.form.draft.cursor = Math.max(0, Math.min(this.form.draft.cursor, choices.length - 1));
293
+ const wide = this.tui.terminal.columns >= 100, listWidth = wide ? Math.floor(width * 0.5) : width;
294
+ const blocks = choices.map((option, index) => choiceLines(this.theme, this.form.question, this.form.draft, option,
295
+ index === this.form.draft.cursor && this.focus === 'answer', listWidth, this.expanded, wide));
296
+ const list = listWindow(blocks, this.form.draft.cursor, height, this.position());
297
+ this.listRegion = { y, x, width: listWidth, indices: list.indices };
298
+ this.scrollPosition = { offset: this.position().offset, total: list.total, height };
299
+ if (!list.lines.length) return ['No matching options'];
300
+ const option = options[this.form.draft.cursor];
301
+ if (!wide || !option) return list.lines;
302
+ const preview = this.preview(option), previewWidth = width - listWidth - 3;
303
+ const detail = preview.viewport(previewWidth, height, () => this.tui.requestRender());
304
+ return Array.from({ length: height }, (_, index) => {
305
+ const left = list.lines[index] ?? '';
306
+ return left + ' '.repeat(Math.max(0, listWidth - visibleWidth(left))) + ' │ ' + (detail[index] ?? '');
307
+ });
308
+ }
309
+ private measure(width: number, limit: number): number {
310
+ const geometry = frame(width, limit), batch = Number(this.form.questions.length > 1);
311
+ const chrome = 3 + batch + (geometry.separators ? 2 : 0);
312
+ const headerCap = Math.max(0, Math.min(this.expanded ? limit : 4, limit - chrome - 3));
313
+ const wide = this.tui.terminal.columns >= 100, listWidth = wide ? Math.floor(geometry.width * 0.5) : geometry.width;
314
+ const heights = this.form.questions.map((question, index) => {
315
+ const header = questionLines(question, this.theme, geometry.width, headerCap, this.expanded).length;
316
+ const options = [...question.options, undefined].reduce((height, option) => height + choiceLines(this.theme, question, this.form.drafts[index], option,
317
+ false, listWidth, this.expanded, wide).length, 0);
318
+ const preview = wide ? Math.max(0, ...question.options.map(option => this.previewForMeasure(option, geometry.width - listWidth - 3))) : 0;
319
+ return chrome + header + Math.max(1, options, preview);
320
+ });
321
+ if (batch) heights.push(chrome + reviewLines(this.form, this.theme, geometry.width, this.expanded).flat().length);
322
+ return Math.min(limit, Math.max(5, ...heights));
323
+ }
324
+ private previewForMeasure(option: Option, width: number): number {
325
+ return new Markdown(`${option.title}\n\n${option.description ?? ''}`, 0, 0, getMarkdownTheme()).render(width).length;
326
+ }
327
+ private canExpand(width: number, headerCap: number): boolean {
328
+ if (this.form.reviewing) return reviewLines(this.form, this.theme, width, true).some(lines => lines.length > 1);
329
+ const question = this.form.question;
330
+ const full = questionLines(question, this.theme, width, Number.MAX_SAFE_INTEGER, true);
331
+ const wide = this.tui.terminal.columns >= 100, listWidth = wide ? Math.floor(width * 0.5) : width;
332
+ return full.length > headerCap || [...question.options, undefined].some(option =>
333
+ choiceLines(this.theme, question, this.form.draft, option, false, listWidth, true, false).length >
334
+ choiceLines(this.theme, question, this.form.draft, option, false, listWidth, false, wide).length) ||
335
+ visibleWidth(`${this.requester} ${this.heading ?? ''}`) > width - 30;
336
+ }
337
+ /** History and option details scroll and search through the shared ScrollView; the reader takes 80% of terminal rows. */
338
+ private renderReader(width: number): string[] {
339
+ const answer = this.reading === 'history' ? [truncateToWidth(this.form.question.question, width), this.answerLine(width)] : [];
340
+ this.reader.search.focused = this.focused && this.reader.searching;
341
+ const body = this.reader.viewport(width, Math.max(0, this.height - 2 - answer.length), () => this.tui.requestRender());
342
+ return readingWindow([
343
+ truncateToWidth(`${this.reading} ${this.reader.position} · ${idleTime(this.deadline)} · Tab focus · / search`, width),
344
+ ...body, ...answer, ...this.reader.searching ? this.reader.search.render(width) : [this.renderActions(width)],
345
+ ], this.height);
346
+ }
347
+ override render(width: number): string[] {
348
+ if (!this.started) {
349
+ this.started = true;
350
+ if (this.signal?.aborted) this.abort();
351
+ else if (this.timeout > 0) {
352
+ // First render is the display boundary; queued views consume no idle time.
353
+ this.touch(); this.countdown = setInterval(() => this.tui.requestRender(), 1000);
354
+ }
355
+ }
356
+ const limit = this.dock.askBudget(this.tui.terminal.rows);
357
+ const measurement = `${width}:${this.tui.terminal.rows}:${limit}:${this.expanded}`;
358
+ if (this.measured !== measurement) { this.inlineHeight = this.measure(width, limit); this.measured = measurement; }
359
+ this.height = this.reading ? Math.max(4, Math.floor(this.tui.terminal.rows * 0.8)) : this.inlineHeight;
360
+ this.tabRegions = []; this.listRegion = { y: 0, x: 0, width: 0, indices: [] }; this.scrollPosition = { offset: 0, total: 0, height: 0 };
361
+ const time = idleTime(this.deadline);
362
+ if (this.reading) return this.renderReader(width);
363
+ const geometry = frame(width, limit);
364
+ if (!geometry.bordered) {
365
+ this.collapsible = true;
366
+ const answer = this.focus === 'actions' ? this.renderActions(width) : this.answerLine(width);
367
+ this.listRegion = { y: 0, x: 0, width, indices: [this.form.reviewing ? this.reviewCursor : this.form.draft.cursor] };
368
+ return this.height === 1 ? [truncateToWidth(answer, width)] : [truncateToWidth(answer, width), this.renderActions(width)];
369
+ }
370
+ const batch = this.form.questions.length > 1;
371
+ const lines: string[] = [];
372
+ if (batch && this.height >= 6) {
373
+ const tabs = questionTabs(this.form, this.theme, geometry.width);
374
+ this.tabRegions = tabs.regions.map(tab => ({ ...tab, start: tab.start + geometry.inset, end: tab.end + geometry.inset }));
375
+ this.tabY = 1; lines.push(tabs.line);
376
+ }
377
+ const headerCap = Math.max(0, Math.min(this.expanded ? this.height : 4,
378
+ this.height - 3 - lines.length - (geometry.separators ? 2 : 0) - (this.expanded ? 3 : 1)));
379
+ this.collapsible = this.canExpand(geometry.width, headerCap);
380
+ if (!this.form.reviewing) lines.push(...questionLines(this.form.question, this.theme, geometry.width, headerCap, this.expanded));
381
+ if (geometry.separators) lines.push('\0separator');
382
+ const bodyHeight = Math.max(1, this.height - 3 - lines.length - Number(geometry.separators));
383
+ const bodyY = lines.length + 1;
384
+ let body: string[];
385
+ if (this.form.reviewing) {
386
+ const list = listWindow(reviewLines(this.form, this.theme, geometry.width, this.expanded), this.reviewCursor, bodyHeight, this.position());
387
+ body = list.lines.map((line, index) => list.indices[index] === this.reviewCursor ? this.theme.fg('accent', line) : line);
388
+ this.listRegion = { y: bodyY, x: geometry.inset, width: geometry.width, indices: list.indices };
389
+ this.scrollPosition = { offset: this.position().offset, total: list.total, height: bodyHeight };
390
+ } else if (this.focus === 'search' || this.focus === 'comment') body = [this.answerLine(geometry.width)];
391
+ else if (this.form.draft.editing) body = this.editorLines(geometry.width, bodyHeight);
392
+ else body = this.optionLines(geometry.width, bodyHeight, bodyY, geometry.inset);
393
+ lines.push(...body, ...Array(Math.max(0, bodyHeight - body.length)).fill(''));
394
+ const count = this.form.reviewing ? this.form.questions.length : this.options().length + 1;
395
+ const cursor = this.form.reviewing ? this.reviewCursor : this.form.draft.cursor;
396
+ const scroll = this.scrollPosition, scrolling = scroll.total > scroll.height;
397
+ if (geometry.separators) lines.push('\0separator');
398
+ const status = this.notice ? this.theme.fg('warning', this.notice) + ` · ${this.escapeHint}` : this.renderActions(geometry.width);
399
+ lines.push(truncateToWidth((scrolling ? `${cursor + 1}/${count} · ` : '') + status, geometry.width));
400
+ const kind = !this.form.question.options.length ? '✎' : this.form.question.allowMultiple
401
+ ? `☐${this.form.draft.selected.size + Number(this.form.draft.customSelected && Boolean(this.form.draft.text.trim()))}` : '○';
402
+ const page = this.form.reviewing ? 'Review' : `${this.form.index + 1}/${this.form.questions.length} ${kind}`;
403
+ return frameLines(this.theme, geometry, width, topBorder(this.theme, width, this.requester, this.heading, page, time), lines, new Map())
404
+ .map(line => truncateToWidth(line, width));
405
+ }
406
+ }
File without changes
@@ -0,0 +1,50 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { ToolExecutionStartEvent, ToolExecutionEndEvent } from "@earendil-works/pi-coding-agent";
3
+
4
+ export type AutoStopReason = "no_tools" | "repeated_tools";
5
+ export const autoStopMessage: Record<AutoStopReason, string> = {
6
+ no_tools: 'Goal paused · no tool activity',
7
+ repeated_tools: 'Goal paused · repeated tool activity',
8
+ };
9
+ const digest = (value: unknown): string => createHash("sha256").update(JSON.stringify(value)).digest("hex");
10
+
11
+ /** Samples Goal-delivered auto rounds, not provider turns or user work. No output history is retained. */
12
+ export class GoalActivity {
13
+ private pending = false;
14
+ private automatic = false;
15
+ private calls = new Map<string, { call: string; result?: string }>();
16
+ private previous?: string;
17
+ private empty = 0;
18
+ private repeated = 0;
19
+
20
+ reset(): void {
21
+ this.pending = false; this.automatic = false; this.calls.clear();
22
+ this.previous = undefined; this.empty = 0; this.repeated = 0;
23
+ }
24
+ delivered(): void { this.pending = true; }
25
+ start(): void {
26
+ // Host retries/compaction retries without a new Goal delivery stay in the same round.
27
+ if (!this.pending) return;
28
+ this.pending = false; this.automatic = true; this.calls.clear();
29
+ }
30
+ toolStart(event: ToolExecutionStartEvent): void {
31
+ if (this.automatic) this.calls.set(event.toolCallId, { call: digest([event.toolName, event.args]) });
32
+ }
33
+ toolEnd(event: ToolExecutionEndEvent): void {
34
+ const call = this.calls.get(event.toolCallId);
35
+ // Include failed and nested calls, but not call IDs, timings or provider usage.
36
+ if (call) call.result = digest([event.result.content, event.result.details, event.result.structuredContent, event.isError]);
37
+ }
38
+ finish(): AutoStopReason | undefined {
39
+ if (!this.automatic) { this.reset(); return; }
40
+ this.automatic = false;
41
+ const signature = this.calls.size ? digest([...this.calls.values()]) : undefined;
42
+ this.calls.clear();
43
+ // Source insertion order is stable even when tool completions arrive in parallel.
44
+ this.empty = signature === undefined ? this.empty + 1 : 0;
45
+ this.repeated = signature !== undefined ? signature === this.previous ? this.repeated + 1 : 1 : 0;
46
+ this.previous = signature;
47
+ if (this.empty >= 5) return "no_tools";
48
+ if (this.repeated >= 5) return "repeated_tools";
49
+ }
50
+ }
@@ -0,0 +1,75 @@
1
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
+ import type { Notifications } from "../runtime/notifications.ts";
3
+ import type { Dock } from "../ui/dock.ts";
4
+ import { GOAL_RESUME, goalDetails, type ResumeDetails } from './presentation.ts';
5
+
6
+ import type { GoalManager } from './manager.ts';
7
+
8
+ export function parseGoalArgs(args: string): { text?: string; budget?: number } {
9
+ let text = args.trim(); let budget: number | undefined;
10
+ if (text.startsWith("--tokens")) {
11
+ const match = /^--tokens\s+(\d+(?:\.\d+)?)([km]?)\b\s*/i.exec(text);
12
+ if (!match) throw new Error("Use --tokens <positive amount>, e.g. 100k, before the objective");
13
+ budget = Number(match[1]) * ({ k: 1000, m: 1000000 }[match[2].toLowerCase()] ?? 1);
14
+ if (!Number.isSafeInteger(budget) || budget <= 0) throw new Error("Token budget must be a positive whole amount");
15
+ text = text.slice(match[0].length).trim();
16
+ }
17
+ if (text.length > 4000) throw new Error("Goal text must be at most 4000 characters; reference a file for longer instructions");
18
+ return { text: text || undefined, budget };
19
+ }
20
+
21
+ export function registerGoalCommand(pi: ExtensionAPI, manager: GoalManager, dock: Dock, notifications: Notifications): void {
22
+ const details = async (ctx: ExtensionCommandContext) => {
23
+ const goal = manager.goal;
24
+ if (!goal) { ctx.ui.notify("No goal"); return; }
25
+ const captured = manager.captureBinding(ctx);
26
+ if (!captured) return;
27
+ const release = notifications.hold();
28
+ try {
29
+ const { showDetails } = await import('../ui/details.ts');
30
+ // Loading can cross shutdown/tree/reload. Never mount the old page in a new binding.
31
+ if (!manager.isCurrent(captured) || manager.goal !== goal || ctx.signal?.aborted) return;
32
+ await showDetails(ctx, dock, 'Goal', goalDetails(goal, manager.schedule, manager.elapsedMs));
33
+ } finally { release(); }
34
+ };
35
+ pi.registerCommand("goal", {
36
+ description: 'Manage goal: [--tokens 100k] <objective>, status, edit, pause, resume, clear',
37
+ getArgumentCompletions: prefix => ['status', 'edit', 'pause', 'resume', 'clear'].filter(value => value.startsWith(prefix)).map(value => ({ value, label: value })),
38
+ handler: async (args, ctx) => {
39
+ const trimmed = args.trim();
40
+ if (!trimmed || trimmed === "status") { await details(ctx); return; }
41
+ if (trimmed === "pause") { await manager.pause(ctx); return; }
42
+ if (trimmed === 'resume') {
43
+ // Hold control delivery until the explicit result is stored. The display message never
44
+ // triggers execution; the existing requestId queue owns the one continuation.
45
+ const release = notifications.hold();
46
+ try {
47
+ const result = await manager.resume();
48
+ const summary = result === 'running' ? 'Goal already running' : result === 'waiting_host' ? 'Goal resumed · waiting' : 'Goal resumed';
49
+ // A custom message is deferred until turn_end while streaming. This receipt is
50
+ // display-only, so an entry can appear immediately without entering model history.
51
+ pi.appendEntry(GOAL_RESUME, { resumeVersion: 1, summary, text: summary } satisfies ResumeDetails & { summary: string });
52
+ } finally { release(); }
53
+ return;
54
+ }
55
+ // Removed control words must not fall through to objective creation.
56
+ if (/^stop(?:\s|$)/.test(trimmed)) throw new Error('Unknown goal command: stop');
57
+ if (trimmed === "clear") { await manager.clear(ctx); return; }
58
+ if (trimmed === "edit" || trimmed.startsWith("edit ")) {
59
+ const input = parseGoalArgs(trimmed.slice(4));
60
+ if (input.text === undefined && input.budget === undefined) throw new Error("Supply an objective or --tokens budget to edit");
61
+ await manager.edit(input.text, input.budget, ctx); return;
62
+ }
63
+ const input = parseGoalArgs(trimmed);
64
+ if (!input.text) throw new Error("Supply a goal objective");
65
+ const old = manager.goal;
66
+ const captured = manager.captureBinding(ctx);
67
+ if (!captured) return;
68
+ if (old && old.status !== "completed") {
69
+ if (!ctx.hasUI || !await ctx.ui.confirm("Replace unfinished goal?", `${old.text}\n\nNew goal: ${input.text}`)) return;
70
+ if (!manager.isCurrent(captured) || ctx.signal?.aborted) return;
71
+ }
72
+ await manager.start(input.text, ctx, input.budget);
73
+ },
74
+ });
75
+ }
@@ -0,0 +1,36 @@
1
+ import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
2
+ import type { Goal } from './state.ts';
3
+
4
+ export const GOAL_CONTEXT = 'pi-suite:goal-context';
5
+ export const GOAL_CONTROL = 'pi-suite:goal-control';
6
+ export const GOAL_CONTINUATION = 'Continue the current goal.';
7
+ type Access = 'execute' | 'complete' | 'none';
8
+ type Control = { goalId: string | null; revision: number | null; control: number; access: Access; budget: number | null; status: string };
9
+
10
+ // Sent once per goal revision; later changes only append the short control JSON.
11
+ // `access` is what the model must act on. Pausing stops automatic continuation only:
12
+ // a user turn is ordinary work, so the rules must not read as "you may not work now".
13
+ // Evidence and wait rules live in the tool descriptions.
14
+ const rules = 'Work until every original requirement is implemented and verified; do not replace the objective with an easier one. ' +
15
+ 'The latest Goal instruction or control message replaces earlier ones. ' +
16
+ 'access "execute": the goal is running and continues automatically across turns; goal_wait and goal_blocked are available. ' +
17
+ 'access "complete": the goal is paused or completed and does not continue on its own. Handle the user\'s message normally with any tools; ' +
18
+ 'call goal_complete only if every requirement is already verified. If the user wants automatic work to continue, they run /goal resume. ' +
19
+ 'Skipped, timed_out and cancelled ask_user answers are not consent.';
20
+
21
+ /** Derived delivery metadata only: it is never a state or permission recovery source. */
22
+ export function goalInstruction(ctx: ExtensionContext, goal: Goal | undefined, access: Access, control: number) {
23
+ const messages = ctx.sessionManager.buildSessionProjection().messages;
24
+ const anchor = messages.findLast(message => message.role === 'custom' && message.customType === GOAL_CONTEXT);
25
+ const last = messages.findLast(message => message.role === 'custom' && [GOAL_CONTEXT, GOAL_CONTROL].includes(message.customType));
26
+ if (!goal && !last) return;
27
+ const state: Control = { goalId: goal?.id ?? null, revision: goal?.revision ?? null, control, access,
28
+ budget: goal?.budget ?? null, status: goal?.status ?? 'none' };
29
+ const previous = last?.role === 'custom' ? last.details as Control | undefined : undefined;
30
+ if (JSON.stringify(previous) === JSON.stringify(state)) return;
31
+ const anchored = anchor?.role === 'custom' ? anchor.details as Control | undefined : undefined;
32
+ const full = goal && (anchored?.goalId !== goal.id || anchored.revision !== goal.revision);
33
+ return { customType: full ? GOAL_CONTEXT : GOAL_CONTROL, display: false, details: state,
34
+ content: full ? `Current Goal instruction:\n${rules}\n${JSON.stringify({ ...state, objective: goal.text })}` :
35
+ `Current Goal control (replaces earlier ones):\n${JSON.stringify(state)}` };
36
+ }
@@ -0,0 +1,38 @@
1
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
2
+ import type { GoalManager } from './manager.ts';
3
+ import { goalInstruction } from './context.ts';
4
+
5
+ export function registerGoalLifecycle(pi: ExtensionAPI, manager: GoalManager): void {
6
+ pi.on('before_agent_start', async (event, ctx) => {
7
+ await manager.beforeStart(event.messageType === 'user');
8
+ // Stop generating the legacy named section. Existing historical system text
9
+ // stays intact; the latest persistent Goal message supersedes its permission.
10
+ delete event.systemPromptOptions.sections['pi-suite-goal'];
11
+ const message = goalInstruction(ctx, manager.goal, manager.contextView(ctx)?.access ?? 'none', manager.control);
12
+ return message ? { message } : undefined;
13
+ });
14
+ pi.on('input', event => { if (event.source !== 'extension') manager.activity.reset(); });
15
+ pi.on('tool_execution_start', (event, ctx) => { if (manager.contextView(ctx)?.access === 'execute') manager.activity.toolStart(event); });
16
+ pi.on('tool_execution_end', (event, ctx) => { if (manager.contextView(ctx)?.access === 'execute') manager.activity.toolEnd(event); });
17
+ pi.on('agent_start', (_event, ctx) => manager.startRun(ctx));
18
+ pi.on('agent_end', event => {
19
+ const message = event.messages.findLast(message => message.role === 'assistant');
20
+ manager.endRun(message?.role === 'assistant' && message.stopReason === 'error' ? message.errorMessage ?? 'Model request failed' : undefined);
21
+ });
22
+ pi.on('message_end', (event, ctx) => manager.messageEnd(event, ctx));
23
+ pi.on('ui_prompt_start', () => manager.userPrompt(true));
24
+ pi.on('ui_prompt_end', () => manager.userPrompt(false));
25
+ pi.on('session_before_compact', () => manager.beforeCompact());
26
+ pi.on('session_compact', async (event, ctx) => {
27
+ await manager.compacted(event.willRetry);
28
+ // Compaction retries and between-tool turns do not re-enter before_agent_start.
29
+ // Pi polls steering before their already-arranged next request. Never steer an
30
+ // idle completed goal or an arranged wait merely to rebuild its description.
31
+ if (event.willRetry || event.reason === 'threshold' && manager.goal?.status === 'active' && !manager.goal.waiting) {
32
+ const access = manager.goal?.status === 'active' && manager.goal.automatic ? 'execute' : manager.contextView(ctx)?.access ?? 'none';
33
+ const message = goalInstruction(ctx, manager.goal, access, manager.control);
34
+ if (message) pi.sendMessage(message, { deliverAs: 'steer' });
35
+ }
36
+ });
37
+ pi.on('session_compact_failed', event => manager.compactFailed(event.errorMessage));
38
+ }