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,386 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import type { AgentBeforeSettleEvent, ExtensionAPI, ExtensionContext, MessageEndEvent, SessionStartEvent, SessionShutdownEvent } from '@earendil-works/pi-coding-agent';
3
+ import type { SessionBinding, Binding } from '../runtime/binding.ts';
4
+ import { isQuestion, type Notifications } from '../runtime/notifications.ts';
5
+ import type { StatusPublisher } from '../ui/status.ts';
6
+ import type { AskResult } from '../ask/schema.ts';
7
+ import type { WaitRegistry } from '../runtime/wait.ts';
8
+ import { ToolError } from '../runtime/errors.ts';
9
+ import { GoalActivity, autoStopMessage } from './activity.ts';
10
+ import { GOAL_CONTINUATION } from './context.ts';
11
+ import { importGoal } from './snapshot.ts';
12
+ import { goalStore, type GoalStore } from './store.ts';
13
+ import { goalSummary, requiresExplicitResume, type Goal, type PauseKind, type Schedule } from './state.ts';
14
+ import { GoalWaitResources } from './wait.ts';
15
+
16
+ export class GoalManager {
17
+ goal?: Goal;
18
+ schedule: Schedule = 'detached';
19
+ readonly activity = new GoalActivity();
20
+ private store?: GoalStore;
21
+ private unsubscribe?: () => void;
22
+ private writing = false;
23
+ private fault = false;
24
+ private runGoalId?: string;
25
+ private runRevision?: number;
26
+ private runBinding?: Binding;
27
+ private runAccess?: 'execute' | 'complete';
28
+ private runSignal?: AbortSignal;
29
+ private runningSince?: number;
30
+ private pendingElapsed = 0;
31
+ private lastError?: string;
32
+ private readonly waitResources: GoalWaitResources;
33
+ private completedTimer?: NodeJS.Timeout;
34
+ private clock?: NodeJS.Timeout;
35
+ private controlRevision = 0;
36
+ private runControlRevision = 0;
37
+
38
+ constructor(private pi: ExtensionAPI, private binding: SessionBinding, private notifications: Notifications, private status: StatusPublisher,
39
+ private waits: WaitRegistry) {
40
+ this.waitResources = new GoalWaitResources(binding, waits);
41
+ // A paused or completed goal does not hold results: the woken turn gets access "none",
42
+ // so it handles the notification without resuming. The exception is a pause from a
43
+ // cancelled ask: the user asked the model to stop and wait, so results stay queued and
44
+ // join the user's next message instead of starting a turn behind the user's back.
45
+ // While running, direct child questions and selected monitor/update events can wake an
46
+ // arranged wait; unrelated settlements remain queued until all requested objects settle.
47
+ notifications.setAdmission(ids => {
48
+ const goal = this.goal;
49
+ if (this.fault) return false;
50
+ if (goal?.status === 'paused' && goal.reason?.kind === 'cancelled' && goal.reason.wait?.waiting === 'user') return false;
51
+ if (!goal || goal.status !== 'active' || !goal.automatic) return true;
52
+ return goal.waiting !== 'user' && (!goal.waitFor ||
53
+ ids.some(id => isQuestion(id) || goal.waitFor!.some(waited => id === `job:${waited}:monitor` || id === `job:${waited}:update`)));
54
+ });
55
+ }
56
+ private get requestId(): string { return `goal:${this.goal!.id}`; }
57
+ private get owned(): boolean {
58
+ return Boolean(this.goal && this.runGoalId === this.goal.id && this.runRevision === this.goal.revision && this.runBinding && this.binding.isCurrent(this.runBinding));
59
+ }
60
+ private get executing(): boolean { return this.owned && this.runAccess === 'execute' && this.goal?.status === 'active'; }
61
+ private currentAccess(ctx: ExtensionContext, signal?: AbortSignal): boolean {
62
+ return Boolean(!this.fault && this.owned && this.runAccess && this.runControlRevision === this.controlRevision && !signal?.aborted && !this.runSignal?.aborted &&
63
+ !ctx.signal?.aborted && (!this.runSignal || ctx.signal === this.runSignal) && ctx.sessionManager.getSessionId() === this.binding.current?.sessionId);
64
+ }
65
+ contextView(ctx: ExtensionContext): { goal: Goal; access: 'execute' | 'complete' } | undefined {
66
+ if (!this.currentAccess(ctx)) return;
67
+ return { goal: this.goal!, access: this.executing ? 'execute' : 'complete' };
68
+ }
69
+ get control(): number { return this.controlRevision; }
70
+ private cancelRequest(): void {
71
+ if (this.goal && this.binding.current) this.notifications.cancel(this.binding.current.sessionId, this.requestId);
72
+ }
73
+ private elapsed(): void {
74
+ if (this.runningSince !== undefined) this.pendingElapsed += Math.max(0, performance.now() - this.runningSince);
75
+ this.runningSince = undefined;
76
+ }
77
+ /** Ticks only read the open segment; lifecycle commits fold it into the current file. */
78
+ get elapsedMs(): number {
79
+ return (this.goal?.elapsedMs ?? 0) + this.pendingElapsed + (this.runningSince === undefined ? 0 : Math.max(0, performance.now() - this.runningSince));
80
+ }
81
+ private transition(schedule: Schedule): void {
82
+ this.elapsed(); this.schedule = schedule;
83
+ if (schedule === 'running' && this.goal?.status === 'active') this.runningSince = performance.now();
84
+ if (!this.writing) this.publish();
85
+ }
86
+ private fail(error: unknown): void {
87
+ this.fault = true; this.cancelRequest(); this.disarmWait(); this.runAccess = undefined;
88
+ this.transition('idle');
89
+ this.binding.current?.ctx.ui.notify(String(error), 'error');
90
+ }
91
+ /** Every semantic mutation runs against the locked, latest state, not a cached snapshot.
92
+ * Hold shared delivery until commit: a failed write must never start a new model request. */
93
+ private async change<T>(apply: () => T, signal?: AbortSignal): Promise<T> {
94
+ if (!this.store) await this.restore(this.binding.current!.ctx, 'new');
95
+ const store = this.store!, captured = this.binding.current!, expected = store.current;
96
+ const release = this.notifications.hold();
97
+ let entered = false, applied = false;
98
+ try {
99
+ const result = await store.change(expected, data => {
100
+ if (!this.binding.isCurrent(captured) || this.store !== store) throw new ToolError('STALE_BINDING', 'The session changed during this call; retry in the current session');
101
+ this.writing = true; entered = true; this.goal = data.goal ?? undefined; this.controlRevision = data.control;
102
+ const result = apply(); applied = true;
103
+ this.elapsed();
104
+ if (this.goal) this.goal.elapsedMs += this.pendingElapsed;
105
+ this.pendingElapsed = 0;
106
+ data.goal = this.goal ?? null; data.control = this.controlRevision;
107
+ return result;
108
+ }, signal);
109
+ // An atomic write may finish after a session switch; its result still belongs
110
+ // to the captured store and must not replace the new binding's UI or authority.
111
+ if (!this.binding.isCurrent(captured) || this.store !== store) throw new ToolError('STALE_BINDING', 'The session changed during this call; retry in the current session');
112
+ this.fault = false; this.goal = store.current.goal ?? undefined; this.controlRevision = store.current.control;
113
+ if (this.schedule === 'running' && this.goal?.status === 'active') this.runningSince = performance.now();
114
+ this.publish();
115
+ return result;
116
+ } catch (error) {
117
+ if (this.binding.isCurrent(captured) && this.store === store) {
118
+ this.goal = store.current.goal ?? undefined; this.controlRevision = store.current.control;
119
+ // Domain rejection (wrong goal ID, expired audit, invalid command) is a normal
120
+ // tool/command error. Only storage/binding failures revoke automatic delivery.
121
+ if (!entered || applied) this.fail(error);
122
+ }
123
+ throw error;
124
+ } finally { this.writing = false; release(); }
125
+ }
126
+ private publish(): void {
127
+ this.status.setGoal(goalSummary(this.goal, this.schedule, Date.now(), this.elapsedMs));
128
+ const ticking = this.goal?.status === 'active' && this.schedule === 'running' && this.status.goalVisible && this.binding.current?.ctx.mode === 'tui';
129
+ if (!ticking) { clearInterval(this.clock); this.clock = undefined; }
130
+ else if (!this.clock) {
131
+ const captured = this.binding.current!, goalId = this.goal!.id;
132
+ this.clock = setInterval(() => { if (this.binding.isCurrent(captured) && this.goal?.id === goalId) this.publish(); }, 1000);
133
+ this.clock.unref();
134
+ }
135
+ }
136
+ async restore(ctx: ExtensionContext, reason: SessionStartEvent['reason'] | 'tree'): Promise<void> {
137
+ this.detach();
138
+ const captured = this.binding.current!, store = this.store = goalStore(ctx);
139
+ try {
140
+ await store.initialize(() => reason === 'new' || reason === 'fork' ? undefined : importGoal(ctx));
141
+ await store.snapshot();
142
+ if (!this.binding.isCurrent(captured)) return;
143
+ this.goal = store.current.goal ?? undefined; this.controlRevision = store.current.control; this.fault = false;
144
+ this.unsubscribe = store.subscribe(() => {
145
+ if (!this.binding.isCurrent(captured) || this.store !== store || this.writing) return;
146
+ const next = store.current;
147
+ const changed = this.goal?.id !== next.goal?.id || this.goal?.revision !== next.goal?.revision || this.controlRevision !== next.control;
148
+ if (changed) { this.cancelRequest(); this.disarmWait(); this.runAccess = undefined; this.activity.reset(); this.pendingElapsed = 0; this.runningSince = undefined; }
149
+ this.goal = next.goal ?? undefined; this.controlRevision = next.control;
150
+ if (changed) this.transition('idle'); else this.publish();
151
+ }, error => this.fail(error));
152
+ if (reason === 'startup' && this.goal && this.goal.status !== 'completed') await this.change(() => this.pauseFor('startup'));
153
+ this.transition(this.goal?.waiting === 'user' ? 'waiting_user' : this.goal?.waiting === 'jobs' ? 'waiting_jobs' : 'idle');
154
+ if (this.goal?.status === 'active' && this.goal.automatic) {
155
+ if (this.goal.budget !== undefined && this.goal.usedTokens >= this.goal.budget) await this.change(() => this.pauseFor('budget'));
156
+ else if (!this.goal.waiting) this.request(); else this.armWait();
157
+ }
158
+ this.armCompletion();
159
+ } catch (error) { this.fail(error); throw error; }
160
+ }
161
+ detach(): void {
162
+ this.activity.reset(); this.cancelRequest(); this.elapsed(); this.disarmWait();
163
+ this.unsubscribe?.(); this.unsubscribe = undefined;
164
+ clearTimeout(this.completedTimer); this.completedTimer = undefined;
165
+ clearInterval(this.clock); this.clock = undefined;
166
+ this.runGoalId = undefined; this.runRevision = undefined; this.runBinding = undefined; this.runAccess = undefined; this.runSignal = undefined;
167
+ this.schedule = 'detached'; this.status.setGoal(undefined); this.pendingElapsed = 0;
168
+ }
169
+ async shutdown(reason: SessionShutdownEvent['reason']): Promise<void> {
170
+ try {
171
+ if (this.goal && this.schedule !== 'detached') await this.change(() => { if (reason === 'quit' && this.goal!.status !== 'completed') this.pauseFor('shutdown'); });
172
+ } finally { this.detach(); }
173
+ }
174
+ async start(text: string, ctx: ExtensionContext, budget?: number): Promise<void> {
175
+ await this.change(() => {
176
+ const abortOldRun = this.owned && !ctx.isIdle();
177
+ this.activity.reset(); this.cancelRequest(); this.elapsed(); this.disarmWait(); clearTimeout(this.completedTimer);
178
+ this.pendingElapsed = 0; this.controlRevision++;
179
+ this.goal = { id: randomUUID(), revision: 0, text, budget, status: 'active', automatic: true, usedTokens: 0, elapsedMs: 0, turns: 0, progress: '' };
180
+ this.transition('idle'); if (abortOldRun) ctx.abort(); this.request();
181
+ });
182
+ }
183
+ async edit(text: string | undefined, budget: number | undefined, ctx: ExtensionContext): Promise<void> {
184
+ await this.change(() => {
185
+ if (!this.goal) throw new Error('No goal to edit');
186
+ const abortOldRun = this.owned && text !== undefined && !ctx.isIdle();
187
+ if (text !== undefined) { this.activity.reset(); this.cancelRequest(); this.goal.text = text; this.goal.revision++; if (this.goal.waiting === 'jobs') this.clearWait(); }
188
+ if (budget !== undefined) this.goal.budget = budget;
189
+ if (this.goal.status === 'active' && this.goal.budget !== undefined && this.goal.usedTokens >= this.goal.budget) { this.pauseFor('budget'); if (this.owned) ctx.abort(); }
190
+ if (abortOldRun) ctx.abort();
191
+ if (text !== undefined && this.goal.status === 'active' && this.goal.automatic) this.request();
192
+ });
193
+ }
194
+ async pause(ctx: ExtensionContext): Promise<void> {
195
+ await this.change(() => {
196
+ if (!this.goal) throw new Error('No goal to pause');
197
+ if (this.goal.status === 'completed' || this.goal.status === 'paused' && this.goal.reason?.kind === 'manual') return;
198
+ this.pauseFor('manual'); if (this.owned) ctx.abort();
199
+ });
200
+ }
201
+ captureBinding(ctx: ExtensionContext): Binding | undefined {
202
+ const current = this.binding.current;
203
+ return current?.sessionId === ctx.sessionManager.getSessionId() ? current : undefined;
204
+ }
205
+ isCurrent(captured: Binding): boolean { return this.binding.isCurrent(captured); }
206
+ async resume(): Promise<'running' | 'scheduled' | 'waiting_host'> {
207
+ return this.change(() => {
208
+ if (!this.goal || this.goal.status === 'completed') throw new Error('No unfinished goal to resume');
209
+ if (this.goal.budget !== undefined && this.goal.usedTokens >= this.goal.budget) throw new Error('Raise the token budget above current usage before resuming');
210
+ if (this.owned && this.schedule === 'running' && this.goal.status === 'active' && this.goal.automatic) return 'running';
211
+ this.activity.reset(); this.controlRevision++;
212
+ this.goal.status = 'active'; this.goal.automatic = true; delete this.goal.reason;
213
+ this.clearWait(); delete this.goal.error; this.transition('idle'); this.request();
214
+ return this.binding.current?.ctx.isIdle() ? 'scheduled' : 'waiting_host';
215
+ });
216
+ }
217
+ async clear(ctx: ExtensionContext): Promise<void> {
218
+ await this.change(() => {
219
+ const abortRun = this.owned;
220
+ this.activity.reset(); this.controlRevision++; this.cancelRequest(); this.elapsed(); this.disarmWait(); clearTimeout(this.completedTimer);
221
+ this.goal = undefined; this.pendingElapsed = 0; this.transition('idle'); if (abortRun) ctx.abort();
222
+ });
223
+ }
224
+ private pauseFor(kind: PauseKind, error?: string): void {
225
+ this.activity.reset(); this.cancelRequest(); this.controlRevision++;
226
+ const goal = this.goal!;
227
+ const wait = goal.waiting ? { waiting: goal.waiting, resumeAt: goal.resumeAt, waitFor: goal.waitFor } : goal.reason?.wait;
228
+ const previous = kind === 'shutdown' || kind === 'startup' ? goal.reason?.kind : goal.reason?.previous;
229
+ const automaticStop = goal.reason?.automaticStop;
230
+ goal.status = 'paused'; goal.automatic = false;
231
+ goal.reason = { kind, ...previous ? { previous } : {}, ...automaticStop ? { automaticStop } : {}, ...wait ? { wait } : {} };
232
+ if (error) goal.error = error;
233
+ this.clearWait(); this.transition('idle');
234
+ }
235
+ private request(): void {
236
+ const goal = this.goal, current = this.binding.current;
237
+ if (!goal || !current || goal.status !== 'active' || !goal.automatic || goal.waiting || this.fault) return;
238
+ const revision = goal.revision, control = this.controlRevision;
239
+ this.notifications.enqueue(current.sessionId, this.requestId, GOAL_CONTINUATION, () => {
240
+ if (this.binding.isCurrent(current) && this.goal?.id === goal.id && this.goal.revision === revision && this.controlRevision === control) this.activity.delivered();
241
+ }, 'goal-continuation');
242
+ }
243
+ async beforeStart(userInput: boolean): Promise<boolean> {
244
+ if (!this.store) return false;
245
+ await this.store.snapshot();
246
+ if (!this.store.current.goal) return false;
247
+ return this.change(() => {
248
+ const goal = this.goal;
249
+ if (userInput) {
250
+ this.activity.reset();
251
+ if (goal?.status === 'paused' && !requiresExplicitResume(goal.reason!.kind)) {
252
+ this.controlRevision++;
253
+ goal.status = 'active'; goal.automatic = true; delete goal.reason;
254
+ }
255
+ }
256
+ this.runControlRevision = this.controlRevision;
257
+ this.runAccess = goal?.status === 'active' && goal.automatic ? 'execute' : goal && userInput ? 'complete' : undefined;
258
+ this.runGoalId = this.runAccess ? goal!.id : undefined; this.runRevision = goal?.revision; this.runBinding = this.binding.current;
259
+ if (this.executing) { this.cancelRequest(); this.clearWait(); }
260
+ return this.owned;
261
+ });
262
+ }
263
+ async startRun(ctx?: ExtensionContext): Promise<void> {
264
+ if (!this.owned) return;
265
+ await this.change(() => {
266
+ const nextSignal = ctx?.signal;
267
+ if (nextSignal !== this.runSignal) {
268
+ if (this.runControlRevision !== this.controlRevision && this.goal?.status === 'active' && this.goal.automatic) this.runAccess = 'execute';
269
+ this.runControlRevision = this.controlRevision;
270
+ }
271
+ this.runSignal = nextSignal;
272
+ if (!this.executing) return;
273
+ this.lastError = undefined; this.activity.start(); this.cancelRequest();
274
+ if (this.goal?.waiting === 'jobs') this.clearWait(); this.transition('running');
275
+ });
276
+ }
277
+ endRun(error?: string): void {
278
+ if (!this.executing) return;
279
+ this.lastError = error; if (!this.goal!.waiting) this.transition('waiting_host');
280
+ }
281
+ async messageEnd(event: MessageEndEvent, ctx: ExtensionContext): Promise<void> {
282
+ const id = this.runGoalId, captured = this.runBinding, store = this.store;
283
+ if (!id || !captured || !store || !this.binding.isCurrent(captured) || ctx.sessionManager.getSessionId() !== captured.sessionId || event.message.role !== 'assistant') return;
284
+ this.lastError = event.message.stopReason === 'error' ? event.message.errorMessage ?? 'Model request failed' : undefined;
285
+ try { await store.account(id, event.message.usage.totalTokens, () => this.binding.isCurrent(captured) && this.store === store); }
286
+ catch (error) {
287
+ if (this.binding.isCurrent(captured) && this.store === store) this.fail(error);
288
+ throw error;
289
+ }
290
+ if (!this.binding.isCurrent(captured) || this.store !== store) return;
291
+ if (this.goal?.id === id && this.goal.status === 'active' && this.goal.budget !== undefined && this.goal.usedTokens >= this.goal.budget) {
292
+ await this.change(() => this.pauseFor('budget')); ctx.abort();
293
+ }
294
+ }
295
+ async beforeSettle(event: AgentBeforeSettleEvent): Promise<void> {
296
+ if (!this.executing || this.runControlRevision !== this.controlRevision) return;
297
+ if (event.outcome === 'error' || event.continue || event.context?.pendingMessages.length) { this.cancelRequest(); this.transition('waiting_host'); return; }
298
+ if (event.outcome === 'aborted') return;
299
+ await this.change(() => {
300
+ if (!this.goal!.waiting && this.goal!.automatic) {
301
+ const reason = this.activity.finish();
302
+ if (reason) { this.pauseFor(reason); this.binding.current?.ctx.ui.notify(autoStopMessage[reason], 'warning'); return; }
303
+ this.transition('idle'); this.request();
304
+ }
305
+ });
306
+ }
307
+ async settled(aborted: boolean): Promise<void> {
308
+ if (this.executing) await this.change(() => {
309
+ if (this.runControlRevision === this.controlRevision) {
310
+ if (aborted && !this.goal!.waiting) this.pauseFor('cancelled');
311
+ else if (this.lastError) this.pauseFor('request_failed', this.lastError);
312
+ else if (!this.goal!.waiting) this.transition('idle');
313
+ } else if (!this.goal!.waiting && this.goal!.automatic) { this.transition('idle'); this.request(); }
314
+ });
315
+ this.runGoalId = undefined; this.runRevision = undefined; this.runBinding = undefined; this.runAccess = undefined; this.runSignal = undefined; this.lastError = undefined;
316
+ }
317
+ userPrompt(start: boolean): void {
318
+ if (this.executing) this.transition(start ? 'waiting_user' : this.goal!.waiting === 'user' ? 'waiting_user' : 'running');
319
+ }
320
+ async askResult(status: AskResult['status'], ctx: ExtensionContext): Promise<void> {
321
+ if (!this.executing || ctx.sessionManager.getSessionId() !== this.binding.current?.sessionId) return;
322
+ if (status === 'answered' || status === 'timed_out') this.transition('running');
323
+ else if (status === 'cancelled') await this.change(() => { this.goal!.waiting = 'user'; this.pauseFor('cancelled'); });
324
+ }
325
+ beforeCompact(): void { if (this.goal?.status === 'active') this.transition('waiting_host'); }
326
+ async compacted(willRetry: boolean): Promise<void> {
327
+ if (!this.goal || this.goal.status === 'completed') return;
328
+ await this.change(() => {
329
+ // Compaction can continue active work, but it is not a new user turn.
330
+ if (this.goal?.status !== 'active') return;
331
+ if (this.goal.waiting) { this.transition(this.goal.waiting === 'user' ? 'waiting_user' : 'waiting_jobs'); return; }
332
+ this.activity.reset();
333
+ if (!willRetry) { this.transition('idle'); this.request(); }
334
+ });
335
+ if (!willRetry) this.notifications.afterHostOperation();
336
+ }
337
+ async compactFailed(error?: string): Promise<void> { if (this.goal?.status === 'active') await this.change(() => this.pauseFor('compaction_failed', error)); }
338
+ requireOwned(id: string, ctx: ExtensionContext, access: 'execute' | 'complete' = 'execute', signal?: AbortSignal): Goal {
339
+ if (!this.goal || this.goal.id !== id) throw new ToolError('NOT_FOUND', 'No such goal; use the goalId from the latest Goal instruction', id);
340
+ if (access === 'execute' && (this.goal.status !== 'active' || this.runAccess === 'complete')) throw new ToolError('NOT_RUNNING', `Goal is ${this.goal.status}; goal_wait and goal_blocked only work while it runs automatically. Handle the user's request instead; the user can run /goal resume`, id);
341
+ if (!this.currentAccess(ctx, signal)) throw new ToolError('STALE_BINDING', 'This call belongs to an earlier goal revision or turn; use the goalId from the latest Goal instruction in a new turn', id);
342
+ return this.goal;
343
+ }
344
+ async complete(id: string, summary: string, ctx: ExtensionContext, signal?: AbortSignal): Promise<boolean> {
345
+ const changed = await this.change(() => {
346
+ const goal = this.requireOwned(id, ctx, 'complete', signal);
347
+ if (goal.status === 'completed') return false;
348
+ goal.progress = summary; goal.completedAt = Date.now(); goal.status = 'completed'; goal.automatic = false;
349
+ this.activity.reset(); this.cancelRequest(); this.clearWait(); this.transition('idle'); return true;
350
+ }, signal);
351
+ this.armCompletion(); return changed;
352
+ }
353
+ async block(id: string, reason: string, evidence: string, ctx: ExtensionContext, signal?: AbortSignal): Promise<void> {
354
+ await this.change(() => { this.requireOwned(id, ctx, 'execute', signal); this.goal!.progress = evidence; this.pauseFor('blocked', reason); }, signal);
355
+ }
356
+ async wait(id: string, reason: string, delay: number | undefined, ctx: ExtensionContext, waitFor?: string[], signal?: AbortSignal): Promise<{ waiting: boolean; settled: string[] }> {
357
+ const result = await this.change(() => {
358
+ const goal = this.requireOwned(id, ctx, 'execute', signal), ids = [...new Set(waitFor ?? [])];
359
+ const settled = ids.filter(item => this.waits.settlement(item).settled);
360
+ if (ids.length && settled.length === ids.length) return { waiting: false, settled };
361
+ this.activity.reset(); this.controlRevision++; this.cancelRequest(); goal.waiting = 'jobs'; goal.progress = reason;
362
+ if (ids.length) goal.waitFor = ids.filter(item => !settled.includes(item)); else delete goal.waitFor;
363
+ if (delay !== undefined) goal.resumeAt = Date.now() + delay; else delete goal.resumeAt;
364
+ this.transition('waiting_jobs'); return { waiting: true, settled };
365
+ }, signal);
366
+ if (result.waiting) this.armWait(); return result;
367
+ }
368
+ private disarmWait(): void { this.waitResources.disarm(); }
369
+ private clearWait(): void { this.disarmWait(); if (this.goal) { delete this.goal.waiting; delete this.goal.resumeAt; delete this.goal.waitFor; } }
370
+ private armWait(): void {
371
+ const goal = this.goal, captured = this.binding.current, control = this.controlRevision;
372
+ this.waitResources.arm(goal, () => {
373
+ if (!captured || !this.binding.isCurrent(captured) || this.goal?.id !== goal?.id || this.goal?.revision !== goal?.revision || this.controlRevision !== control || this.goal?.status !== 'active' || !this.goal.automatic) return;
374
+ void this.change(() => {
375
+ if (this.goal?.waiting !== 'jobs') return;
376
+ this.clearWait(); this.transition('idle'); this.request();
377
+ }).catch(error => captured.ctx.ui.notify(String(error), 'error'));
378
+ });
379
+ }
380
+ private armCompletion(): void {
381
+ clearTimeout(this.completedTimer);
382
+ const goal = this.goal, captured = this.binding.current;
383
+ if (goal?.status !== 'completed' || !captured) return;
384
+ this.completedTimer = setTimeout(() => { if (this.binding.isCurrent(captured) && this.goal?.id === goal.id) this.publish(); }, Math.max(0, goal.completedAt! + 5000 - Date.now()));
385
+ }
386
+ }
@@ -0,0 +1,15 @@
1
+ import { goalDuration, goalStateLabels, goalUserState, pauseLabels, type Goal, type Schedule } from './state.ts';
2
+
3
+ export const GOAL_RESUME = 'pi-suite:goal-resume';
4
+ export type ResumeDetails = { resumeVersion: 1; text: string };
5
+ /** Display-only data has no model contract and can be read after the live goal changes. */
6
+ export function goalDetails(goal: Goal, schedule: Schedule, elapsedMs: number): string {
7
+ const reason = goal.reason;
8
+ const wait = goal.waiting ? goal : reason?.wait;
9
+ return `# ${goal.text}\n\nStatus: ${goalStateLabels[goalUserState(goal, schedule)]}` +
10
+ `${reason ? `\n\nReason: ${pauseLabels[reason.kind]}${reason.previous ? ` (${reason.previous})` : ''}` : ''}\n\nID: ${goal.id} · Revision: ${goal.revision}\n\n` +
11
+ `Tokens: ${goal.usedTokens}${goal.budget ? `/${goal.budget}` : ' (no limit)'} · Turns: ${goal.turns} · Active elapsed: ${goalDuration(elapsedMs)}\n\n` +
12
+ `Progress: ${goal.progress || 'not yet recorded'}${goal.error ? `\n\nError: ${goal.error}` : ''}` +
13
+ `${reason?.automaticStop ? `\n\nAutomatic pause: ${pauseLabels[reason.automaticStop]}` : ''}` +
14
+ `${wait?.waiting ? `\n\nWaiting: ${wait.waiting}${wait.waitFor?.length ? ` · ${wait.waitFor.join(', ')}` : ''}${wait.resumeAt ? ` · until ${new Date(wait.resumeAt).toISOString()}` : ''}` : ''}`;
15
+ }
@@ -0,0 +1,36 @@
1
+ import { Text, truncateToWidth } from '@earendil-works/pi-tui';
2
+ import type { ExtensionAPI } from '@earendil-works/pi-coding-agent';
3
+ import { sanitizeText } from '../runtime/text.ts';
4
+ import { GOAL_RESUME, type ResumeDetails } from './presentation.ts';
5
+ import { toolRenderers } from '../ui/tool-render.ts';
6
+
7
+ export const completeRenderers = toolRenderers<unknown, { summary: string }>({
8
+ call: () => ({ icon: '⟳', tone: 'accent', title: 'Goal complete' }),
9
+ collapsed: data => ({ icon: '✔', tone: 'success', title: 'Goal complete', summary: truncateToWidth(data.summary, 60) }),
10
+ expanded: data => [data.summary],
11
+ });
12
+ export const blockedRenderers = toolRenderers<unknown, { reason: string; evidence: string; repeatedTurns: number }>({
13
+ call: () => ({ icon: '⟳', tone: 'accent', title: 'Goal pause' }),
14
+ collapsed: data => ({ icon: '⚠', tone: 'warning', title: 'Goal paused', summary: truncateToWidth(data.reason, 60) }),
15
+ expanded: data => [{ label: 'reason', value: data.reason, tone: 'warning' }, { label: 'evidence', value: data.evidence },
16
+ { label: 'repeatedTurns', value: String(data.repeatedTurns), tone: 'dim' }],
17
+ });
18
+ export const waitRenderers = toolRenderers<unknown, { reason: string; waiting: boolean; settled: string[]; waitFor?: string[]; resumeAfterMs?: number }>({
19
+ call: () => ({ icon: '⟳', tone: 'accent', title: 'Goal wait' }),
20
+ collapsed: data => ({ icon: data.waiting ? '⧗' : '✔', tone: data.waiting ? 'dim' : 'success',
21
+ title: data.waiting ? 'Goal waiting' : 'Goal not waiting', summary: data.waiting ? truncateToWidth(data.reason, 60) : 'all settled' }),
22
+ expanded: data => [{ label: 'reason', value: data.reason }, ...data.waitFor ? [{ label: 'waitFor', value: data.waitFor.join(', ') }] : [],
23
+ ...data.resumeAfterMs ? [{ label: 'resumeAfterMs', value: String(data.resumeAfterMs) }] : [],
24
+ ...data.settled.length ? [{ label: 'settled', value: data.settled.join(', '), tone: 'dim' as const }] : []],
25
+ });
26
+
27
+ /** Factory-safe definitions: no owner, model request, UI reader or resource loader imports. */
28
+ export function registerGoalMessageRenderers(pi: ExtensionAPI): void {
29
+ const receipt = (summary: string, details: ResumeDetails | undefined, expanded: boolean, pad: number) =>
30
+ new Text(sanitizeText(expanded && details?.resumeVersion === 1 ? `${summary}\n\n${details.text}` : summary), pad, 0);
31
+ pi.registerEntryRenderer<ResumeDetails & { summary: string }>(GOAL_RESUME, (entry, options) =>
32
+ receipt(entry.data?.summary ?? 'Goal resumed', entry.data, options.expanded, 1));
33
+ // Persisted message receipts still need their factory renderer when replaying history.
34
+ pi.registerMessageRenderer<ResumeDetails>(GOAL_RESUME, (message, options) =>
35
+ receipt(typeof message.content === 'string' ? message.content : 'Goal resumed', message.details, options.expanded, options.outputPad));
36
+ }
@@ -0,0 +1,78 @@
1
+ import { Type, type Static } from 'typebox';
2
+ import { Value } from 'typebox/value';
3
+ import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
4
+ import type { Goal, PauseKind } from './state.ts';
5
+
6
+ export const GOAL_ENTRY = 'pi-suite:goal';
7
+ const waitFields = {
8
+ waiting: Type.Optional(Type.String({ enum: ['user', 'jobs'] })), resumeAt: Type.Optional(Type.Number()),
9
+ waitFor: Type.Optional(Type.Array(Type.String())),
10
+ };
11
+ const storedFields = {
12
+ id: Type.String(), revision: Type.Integer({ minimum: 0 }), text: Type.String({ minLength: 1, maxLength: 4000 }),
13
+ automatic: Type.Boolean(), resumeRequired: Type.Optional(Type.Boolean()),
14
+ budget: Type.Optional(Type.Integer({ minimum: 1 })), usedTokens: Type.Integer({ minimum: 0 }),
15
+ elapsedMs: Type.Number({ minimum: 0 }), turns: Type.Integer({ minimum: 0 }),
16
+ progress: Type.String(), error: Type.Optional(Type.String()), completedAt: Type.Optional(Type.Number()), ...waitFields,
17
+ };
18
+ const legacySchema = Type.Object({ ...storedFields,
19
+ status: Type.String({ enum: ['active', 'paused', 'blocked', 'failed', 'completed', 'budget_limited', 'stopped'] }),
20
+ stoppedFrom: Type.Optional(Type.String({ enum: ['active', 'paused', 'blocked', 'failed', 'budget_limited'] })),
21
+ autoStopReason: Type.Optional(Type.String({ enum: ['no_tools', 'repeated_tools'] })),
22
+ }, { additionalProperties: false });
23
+ export const storedGoalSchema = Type.Object({ ...storedFields,
24
+ status: Type.String({ enum: ['active', 'paused', 'completed'] }),
25
+ reason: Type.Optional(Type.Object({
26
+ kind: Type.String({ enum: ['manual', 'blocked', 'request_failed', 'budget', 'no_tools', 'repeated_tools', 'shutdown', 'startup', 'cancelled', 'compaction_failed', 'historical_stop', 'permission'] }),
27
+ previous: Type.Optional(Type.String()),
28
+ automaticStop: Type.Optional(Type.String({ enum: ['no_tools', 'repeated_tools'] })),
29
+ wait: Type.Optional(Type.Object({ ...waitFields, waiting: Type.String({ enum: ['user', 'jobs'] }) }, { additionalProperties: false })),
30
+ }, { additionalProperties: false })),
31
+ }, { additionalProperties: false });
32
+ const snapshotSchema = Type.Union([
33
+ Type.Object({ version: Type.Literal(1), goal: Type.Union([legacySchema, Type.Null()]) }, { additionalProperties: false }),
34
+ Type.Object({ version: Type.Literal(2), goal: Type.Union([storedGoalSchema, Type.Null()]) }, { additionalProperties: false }),
35
+ ]);
36
+
37
+ export function normalizeStoredGoal(saved: Static<typeof storedGoalSchema>): Goal {
38
+ // A saved kind is authoritative; old flags can disagree with the current resume policy.
39
+ const { resumeRequired: _obsolete, ...rest } = saved;
40
+ const goal = structuredClone(rest) as Goal;
41
+ if (goal.status === 'active' && (!goal.automatic || goal.reason) ||
42
+ goal.status === 'paused' && (goal.automatic || !goal.reason) ||
43
+ goal.status === 'completed' && goal.automatic) {
44
+ throw new Error('Invalid persisted pi-suite goal permission');
45
+ }
46
+ return goal;
47
+ }
48
+
49
+ /** Parse at the storage boundary without mutating raw JSONL. */
50
+ export function readGoalSnapshot(data: unknown): Goal | undefined {
51
+ if (!Value.Check(snapshotSchema, data)) throw new Error('Invalid persisted pi-suite goal');
52
+ if (!data.goal) return;
53
+ if (data.version === 2) return normalizeStoredGoal(data.goal);
54
+ const { autoStopReason, stoppedFrom, status, resumeRequired, ...rest } = data.goal;
55
+ const goal = structuredClone(rest) as Goal;
56
+ goal.status = status === 'completed' ? 'completed' : 'active';
57
+ const kinds: Record<string, PauseKind> = { paused: 'manual', blocked: 'blocked', failed: 'request_failed', budget_limited: 'budget', stopped: 'historical_stop' };
58
+ const kind = kinds[status] ?? (autoStopReason as PauseKind | undefined) ??
59
+ (resumeRequired ? 'permission' : !rest.automatic ? rest.waiting === 'user' ? 'cancelled' : rest.error ? 'compaction_failed' : 'cancelled' : undefined);
60
+ if (kind && status !== 'completed') {
61
+ goal.status = 'paused'; goal.automatic = false;
62
+ goal.reason = { kind, ...stoppedFrom ? { previous: stoppedFrom } : {},
63
+ ...autoStopReason && kind !== autoStopReason ? { automaticStop: autoStopReason as 'no_tools' | 'repeated_tools' } : {} };
64
+ if (goal.waiting) goal.reason.wait = { waiting: goal.waiting, resumeAt: goal.resumeAt, waitFor: goal.waitFor };
65
+ delete goal.waiting; delete goal.resumeAt; delete goal.waitFor;
66
+ }
67
+ if (goal.status === 'completed') {
68
+ goal.automatic = false;
69
+ if (autoStopReason) goal.reason = { kind: autoStopReason as PauseKind };
70
+ }
71
+ return goal;
72
+ }
73
+ export function importGoal(ctx: ExtensionContext): Goal | undefined {
74
+ // getEntries preserves physical append order across every leaf. A damaged latest
75
+ // record must fail migration rather than reviving an earlier successful goal.
76
+ const entry = ctx.sessionManager.getEntries().findLast(entry => entry.type === 'custom' && entry.customType === GOAL_ENTRY);
77
+ return entry?.type === 'custom' ? readGoalSnapshot(entry.data) : undefined;
78
+ }
@@ -0,0 +1,39 @@
1
+ import type { AutoStopReason } from './activity.ts';
2
+
3
+ export type GoalLifecycle = 'active' | 'paused' | 'completed';
4
+ export type PauseKind = 'manual' | 'blocked' | 'request_failed' | 'budget' | AutoStopReason | 'shutdown' | 'startup' | 'cancelled' | 'compaction_failed' | 'historical_stop' | 'permission';
5
+ const explicitResumeKinds = new Set<PauseKind>(['manual', 'budget', 'shutdown', 'startup', 'historical_stop', 'permission']);
6
+ export function requiresExplicitResume(kind: PauseKind): boolean { return explicitResumeKinds.has(kind); }
7
+ export type GoalWait = { waiting: 'user' | 'jobs'; resumeAt?: number; waitFor?: string[] };
8
+ export type PauseReason = { kind: PauseKind; previous?: string; automaticStop?: AutoStopReason; wait?: GoalWait };
9
+ export interface Goal {
10
+ id: string; revision: number; text: string; status: GoalLifecycle;
11
+ automatic: boolean; reason?: PauseReason;
12
+ budget?: number; usedTokens: number; elapsedMs: number; turns: number;
13
+ progress: string; error?: string; completedAt?: number;
14
+ waiting?: 'user' | 'jobs'; resumeAt?: number; waitFor?: string[];
15
+ }
16
+ export type Schedule = 'running' | 'waiting_user' | 'waiting_jobs' | 'waiting_host' | 'detached' | 'idle';
17
+ export type GoalUserState = 'running' | 'waiting' | 'paused' | 'completed';
18
+ export const goalStateLabels: Record<GoalUserState, string> = { running: '进行中', waiting: '等待中', paused: '已暂停', completed: '已完成' };
19
+ export const pauseLabels: Record<PauseKind, string> = {
20
+ manual: 'Manually paused', blocked: 'External blocker', request_failed: 'Model request failed', budget: 'Token budget reached',
21
+ no_tools: 'No tool activity', repeated_tools: 'Repeated tool activity', shutdown: 'Session ended', startup: 'Session restored',
22
+ cancelled: 'Request cancelled', compaction_failed: 'Compaction failed', historical_stop: 'Historical stop', permission: 'Resume required',
23
+ };
24
+ /** Detached is a binding fact, not a fifth lifecycle. All UI uses this projection. */
25
+ export function goalUserState(goal: Goal, schedule: Schedule): GoalUserState {
26
+ if (goal.status === 'completed') return 'completed';
27
+ if (goal.status === 'paused' || !goal.automatic) return 'paused';
28
+ return goal.waiting || schedule.startsWith('waiting_') ? 'waiting' : 'running';
29
+ }
30
+ export function goalDuration(elapsedMs: number): string {
31
+ const seconds = Math.floor(elapsedMs / 1000), minutes = Math.floor(seconds / 60), hours = Math.floor(minutes / 60);
32
+ const pair = (value: number) => String(value).padStart(2, '0');
33
+ return hours ? `${hours}:${pair(minutes % 60)}:${pair(seconds % 60)}` : `${pair(minutes)}:${pair(seconds % 60)}`;
34
+ }
35
+ export function goalSummary(goal: Goal | undefined, schedule: Schedule, now = Date.now(), elapsedMs = goal?.elapsedMs ?? 0): string | undefined {
36
+ if (!goal || schedule === 'detached' || goal.status === 'completed' && now >= (goal.completedAt ?? 0) + 5000) return;
37
+ const icons: Record<GoalUserState, string> = { running: '🎯', waiting: '⏳', paused: '⏸', completed: '✅' };
38
+ return `${icons[goalUserState(goal, schedule)]} goal ${goalDuration(elapsedMs)}`;
39
+ }
@@ -0,0 +1,59 @@
1
+ import { join } from 'node:path';
2
+ import { getAgentDir, type ExtensionContext } from '@earendil-works/pi-coding-agent';
3
+ import { Type } from 'typebox';
4
+ import { Value } from 'typebox/value';
5
+ import { JsonStore } from '../runtime/json-store.ts';
6
+ import { ToolError } from '../runtime/errors.ts';
7
+ import { normalizeStoredGoal, storedGoalSchema } from './snapshot.ts';
8
+ import type { Goal } from './state.ts';
9
+
10
+ export interface GoalData { version: 1; sessionId: string; control: number; goal: Goal | null }
11
+ const schema = Type.Object({ version: Type.Literal(1), sessionId: Type.String({ minLength: 1 }),
12
+ control: Type.Integer({ minimum: 0 }), goal: Type.Union([storedGoalSchema, Type.Null()]) }, { additionalProperties: false });
13
+ export function goalPath(agentDir: string, sessionId: string): string {
14
+ // SDK IDs are not necessarily UUIDs. Prefix the encoded component so '.'/'..'
15
+ // cannot escape the session directory, without truncating or conflating identities.
16
+ return join(agentDir, 'pi-suite', 'goals', `session-${encodeURIComponent(sessionId)}`, 'state.json');
17
+ }
18
+ const empty = (): GoalData => ({ version: 1, sessionId: '', control: 0, goal: null });
19
+ export class GoalStore extends JsonStore<GoalData> {
20
+ constructor(path: string | undefined, readonly sessionId: string) {
21
+ super(path, empty(), value => {
22
+ if (!Value.Check(schema, value) || value.sessionId !== sessionId) throw new Error('Invalid Goal state or session ownership');
23
+ return { ...value, goal: value.goal ? normalizeStoredGoal(value.goal) : null };
24
+ }, 'GOAL', { missing: empty, skipUnchanged: true });
25
+ }
26
+ initialize(imported: () => Goal | undefined): Promise<void> {
27
+ // Missing check and import share the commit lock with clear and all writers.
28
+ return this.mutate(data => {
29
+ if (data.sessionId) return;
30
+ data.sessionId = this.sessionId; data.goal = imported() ?? null;
31
+ });
32
+ }
33
+ change<T>(expected: GoalData, apply: (data: GoalData) => T, signal?: AbortSignal): Promise<T> {
34
+ return this.mutate(data => {
35
+ if (data.sessionId !== expected.sessionId || data.goal?.id !== expected.goal?.id ||
36
+ data.goal?.revision !== expected.goal?.revision || data.control !== expected.control) {
37
+ throw new ToolError('GOAL_STALE', 'Goal changed; retry against the current state', expected.goal?.id);
38
+ }
39
+ return apply(data);
40
+ }, signal);
41
+ }
42
+ account(id: string, tokens: number, current: () => boolean): Promise<void> {
43
+ return this.mutate(data => {
44
+ // Metering may arrive after pause/edit, but can never write lifecycle fields
45
+ // or charge a replacement goal. Binding cancellation is checked under the lock.
46
+ if (!current() || data.goal?.id !== id) return;
47
+ data.goal.usedTokens += tokens; data.goal.turns++;
48
+ });
49
+ }
50
+ }
51
+ const stores = new Map<string, GoalStore>();
52
+ export function goalStore(ctx: ExtensionContext, agentDir = getAgentDir()): GoalStore {
53
+ const sessionId = ctx.sessionManager.getSessionId();
54
+ const path = ctx.sessionManager.getSessionFile?.() ? goalPath(agentDir, sessionId) : undefined;
55
+ const key = path ?? `memory:${agentDir}:${sessionId}`;
56
+ let store = stores.get(key);
57
+ if (!store) stores.set(key, store = new GoalStore(path, sessionId));
58
+ return store;
59
+ }