@polyweave/preston 0.0.0-stage → 1.0.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 (267) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +115 -2
  3. package/assets/logo.png +0 -0
  4. package/assets/logo.webp +0 -0
  5. package/dist/agents/migration.js +29 -0
  6. package/dist/agents/migration.js.map +1 -0
  7. package/dist/agents/updater.js +385 -0
  8. package/dist/agents/updater.js.map +1 -0
  9. package/dist/channels/chat.js +236 -0
  10. package/dist/channels/chat.js.map +1 -0
  11. package/dist/channels/discord/index.js +491 -0
  12. package/dist/channels/discord/index.js.map +1 -0
  13. package/dist/channels/discord/transport.js +130 -0
  14. package/dist/channels/discord/transport.js.map +1 -0
  15. package/dist/channels/fake/index.js +104 -0
  16. package/dist/channels/fake/index.js.map +1 -0
  17. package/dist/channels/hub.js +153 -0
  18. package/dist/channels/hub.js.map +1 -0
  19. package/dist/channels/outbox.js +219 -0
  20. package/dist/channels/outbox.js.map +1 -0
  21. package/dist/channels/registry.js +67 -0
  22. package/dist/channels/registry.js.map +1 -0
  23. package/dist/channels/router.js +50 -0
  24. package/dist/channels/router.js.map +1 -0
  25. package/dist/channels/shared/delivery.js +74 -0
  26. package/dist/channels/shared/delivery.js.map +1 -0
  27. package/dist/channels/shared/files.js +87 -0
  28. package/dist/channels/shared/files.js.map +1 -0
  29. package/dist/channels/shared/pairing.js +99 -0
  30. package/dist/channels/shared/pairing.js.map +1 -0
  31. package/dist/channels/shared/secrets.js +75 -0
  32. package/dist/channels/shared/secrets.js.map +1 -0
  33. package/dist/channels/shared/text.js +68 -0
  34. package/dist/channels/shared/text.js.map +1 -0
  35. package/dist/channels/shared/typing.js +59 -0
  36. package/dist/channels/shared/typing.js.map +1 -0
  37. package/dist/channels/slack/index.js +560 -0
  38. package/dist/channels/slack/index.js.map +1 -0
  39. package/dist/channels/slack/transport.js +184 -0
  40. package/dist/channels/slack/transport.js.map +1 -0
  41. package/dist/channels/terminal.js +67 -0
  42. package/dist/channels/terminal.js.map +1 -0
  43. package/dist/channels/types.js +6 -0
  44. package/dist/channels/types.js.map +1 -0
  45. package/dist/cli-args.js +92 -0
  46. package/dist/cli-args.js.map +1 -0
  47. package/dist/cli.js +120 -0
  48. package/dist/cli.js.map +1 -0
  49. package/dist/clock.js +76 -0
  50. package/dist/clock.js.map +1 -0
  51. package/dist/config/config.js +184 -0
  52. package/dist/config/config.js.map +1 -0
  53. package/dist/config/schema.js +201 -0
  54. package/dist/config/schema.js.map +1 -0
  55. package/dist/coordinator/coordinator.js +491 -0
  56. package/dist/coordinator/coordinator.js.map +1 -0
  57. package/dist/coordinator/inbox.js +64 -0
  58. package/dist/coordinator/inbox.js.map +1 -0
  59. package/dist/coordinator/input.js +71 -0
  60. package/dist/coordinator/input.js.map +1 -0
  61. package/dist/daemon/daemon.js +228 -0
  62. package/dist/daemon/daemon.js.map +1 -0
  63. package/dist/daemon/ensure.js +87 -0
  64. package/dist/daemon/ensure.js.map +1 -0
  65. package/dist/daemon/lock.js +54 -0
  66. package/dist/daemon/lock.js.map +1 -0
  67. package/dist/daemon/start-at-login.js +20 -0
  68. package/dist/daemon/start-at-login.js.map +1 -0
  69. package/dist/daemon/stop.js +51 -0
  70. package/dist/daemon/stop.js.map +1 -0
  71. package/dist/goals/agents.js +36 -0
  72. package/dist/goals/agents.js.map +1 -0
  73. package/dist/goals/brief.js +51 -0
  74. package/dist/goals/brief.js.map +1 -0
  75. package/dist/goals/checks.js +75 -0
  76. package/dist/goals/checks.js.map +1 -0
  77. package/dist/goals/engine.js +1253 -0
  78. package/dist/goals/engine.js.map +1 -0
  79. package/dist/goals/messages.js +110 -0
  80. package/dist/goals/messages.js.map +1 -0
  81. package/dist/goals/status.js +118 -0
  82. package/dist/goals/status.js.map +1 -0
  83. package/dist/goals/store.js +285 -0
  84. package/dist/goals/store.js.map +1 -0
  85. package/dist/home.js +52 -0
  86. package/dist/home.js.map +1 -0
  87. package/dist/i18n/index.js +37 -0
  88. package/dist/i18n/index.js.map +1 -0
  89. package/dist/ipc/client.js +82 -0
  90. package/dist/ipc/client.js.map +1 -0
  91. package/dist/ipc/private-dir.js +23 -0
  92. package/dist/ipc/private-dir.js.map +1 -0
  93. package/dist/ipc/protocol.js +50 -0
  94. package/dist/ipc/protocol.js.map +1 -0
  95. package/dist/ipc/server.js +110 -0
  96. package/dist/ipc/server.js.map +1 -0
  97. package/dist/landing/exec.js +38 -0
  98. package/dist/landing/exec.js.map +1 -0
  99. package/dist/landing/git.js +93 -0
  100. package/dist/landing/git.js.map +1 -0
  101. package/dist/landing/github.js +154 -0
  102. package/dist/landing/github.js.map +1 -0
  103. package/dist/landing/hooks.js +2 -0
  104. package/dist/landing/hooks.js.map +1 -0
  105. package/dist/landing/landing.js +777 -0
  106. package/dist/landing/landing.js.map +1 -0
  107. package/dist/landing/messages.js +157 -0
  108. package/dist/landing/messages.js.map +1 -0
  109. package/dist/landing/migration.js +50 -0
  110. package/dist/landing/migration.js.map +1 -0
  111. package/dist/landing/paths.js +54 -0
  112. package/dist/landing/paths.js.map +1 -0
  113. package/dist/landing/project.js +95 -0
  114. package/dist/landing/project.js.map +1 -0
  115. package/dist/landing/publishing.js +208 -0
  116. package/dist/landing/publishing.js.map +1 -0
  117. package/dist/landing/stage.js +129 -0
  118. package/dist/landing/stage.js.map +1 -0
  119. package/dist/landing/store.js +160 -0
  120. package/dist/landing/store.js.map +1 -0
  121. package/dist/landing/tools.js +38 -0
  122. package/dist/landing/tools.js.map +1 -0
  123. package/dist/landing/workspace.js +349 -0
  124. package/dist/landing/workspace.js.map +1 -0
  125. package/dist/log.js +77 -0
  126. package/dist/log.js.map +1 -0
  127. package/dist/mcp/coordinator-tools.js +492 -0
  128. package/dist/mcp/coordinator-tools.js.map +1 -0
  129. package/dist/mcp/names.js +8 -0
  130. package/dist/mcp/names.js.map +1 -0
  131. package/dist/mcp/owner-turn.js +15 -0
  132. package/dist/mcp/owner-turn.js.map +1 -0
  133. package/dist/mcp/setup-tools.js +243 -0
  134. package/dist/mcp/setup-tools.js.map +1 -0
  135. package/dist/mcp/stdio.js +74 -0
  136. package/dist/mcp/stdio.js.map +1 -0
  137. package/dist/mcp/tools.js +76 -0
  138. package/dist/mcp/tools.js.map +1 -0
  139. package/dist/mcp/worker-tools.js +53 -0
  140. package/dist/mcp/worker-tools.js.map +1 -0
  141. package/dist/memory/files.js +183 -0
  142. package/dist/memory/files.js.map +1 -0
  143. package/dist/memory/index.js +174 -0
  144. package/dist/memory/index.js.map +1 -0
  145. package/dist/memory/service.js +319 -0
  146. package/dist/memory/service.js.map +1 -0
  147. package/dist/memory/tools.js +82 -0
  148. package/dist/memory/tools.js.map +1 -0
  149. package/dist/notify/index.js +122 -0
  150. package/dist/notify/index.js.map +1 -0
  151. package/dist/prompts/coordinator.js +72 -0
  152. package/dist/prompts/coordinator.js.map +1 -0
  153. package/dist/prompts/grilling.js +8 -0
  154. package/dist/prompts/grilling.js.map +1 -0
  155. package/dist/prompts/teaching.js +17 -0
  156. package/dist/prompts/teaching.js.map +1 -0
  157. package/dist/prompts/worker.js +50 -0
  158. package/dist/prompts/worker.js.map +1 -0
  159. package/dist/questions/questions.js +205 -0
  160. package/dist/questions/questions.js.map +1 -0
  161. package/dist/quota/monitor.js +399 -0
  162. package/dist/quota/monitor.js.map +1 -0
  163. package/dist/quota/schedule.js +38 -0
  164. package/dist/quota/schedule.js.map +1 -0
  165. package/dist/quota/store.js +94 -0
  166. package/dist/quota/store.js.map +1 -0
  167. package/dist/quota/time.js +41 -0
  168. package/dist/quota/time.js.map +1 -0
  169. package/dist/runtime.js +438 -0
  170. package/dist/runtime.js.map +1 -0
  171. package/dist/schedule/cron.js +354 -0
  172. package/dist/schedule/cron.js.map +1 -0
  173. package/dist/schedule/service.js +425 -0
  174. package/dist/schedule/service.js.map +1 -0
  175. package/dist/schedule/store.js +210 -0
  176. package/dist/schedule/store.js.map +1 -0
  177. package/dist/schedule/tools.js +246 -0
  178. package/dist/schedule/tools.js.map +1 -0
  179. package/dist/selfupdate/npm.js +114 -0
  180. package/dist/selfupdate/npm.js.map +1 -0
  181. package/dist/selfupdate/start.js +113 -0
  182. package/dist/selfupdate/start.js.map +1 -0
  183. package/dist/selfupdate/state.js +22 -0
  184. package/dist/selfupdate/state.js.map +1 -0
  185. package/dist/selfupdate/updater.js +120 -0
  186. package/dist/selfupdate/updater.js.map +1 -0
  187. package/dist/service/host.js +46 -0
  188. package/dist/service/host.js.map +1 -0
  189. package/dist/service/index.js +142 -0
  190. package/dist/service/index.js.map +1 -0
  191. package/dist/service/launchd.js +88 -0
  192. package/dist/service/launchd.js.map +1 -0
  193. package/dist/service/spec.js +9 -0
  194. package/dist/service/spec.js.map +1 -0
  195. package/dist/service/systemd.js +90 -0
  196. package/dist/service/systemd.js.map +1 -0
  197. package/dist/service/windows.js +122 -0
  198. package/dist/service/windows.js.map +1 -0
  199. package/dist/setup/pairing.js +143 -0
  200. package/dist/setup/pairing.js.map +1 -0
  201. package/dist/setup/setup.js +76 -0
  202. package/dist/setup/setup.js.map +1 -0
  203. package/dist/standing/defaults.js +80 -0
  204. package/dist/standing/defaults.js.map +1 -0
  205. package/dist/standing/model.js +72 -0
  206. package/dist/standing/model.js.map +1 -0
  207. package/dist/standing/service.js +228 -0
  208. package/dist/standing/service.js.map +1 -0
  209. package/dist/standing/tools.js +184 -0
  210. package/dist/standing/tools.js.map +1 -0
  211. package/dist/store/db.js +67 -0
  212. package/dist/store/db.js.map +1 -0
  213. package/dist/store/migrations.js +280 -0
  214. package/dist/store/migrations.js.map +1 -0
  215. package/dist/supervisor/processes.js +128 -0
  216. package/dist/supervisor/processes.js.map +1 -0
  217. package/dist/supervisor/stalls.js +103 -0
  218. package/dist/supervisor/stalls.js.map +1 -0
  219. package/dist/terminal/activity.js +97 -0
  220. package/dist/terminal/activity.js.map +1 -0
  221. package/dist/terminal/conversation.js +231 -0
  222. package/dist/terminal/conversation.js.map +1 -0
  223. package/dist/util/async-queue.js +41 -0
  224. package/dist/util/async-queue.js.map +1 -0
  225. package/dist/util/command.js +29 -0
  226. package/dist/util/command.js.map +1 -0
  227. package/dist/util/ids.js +9 -0
  228. package/dist/util/ids.js.map +1 -0
  229. package/dist/util/process-tree.js +62 -0
  230. package/dist/util/process-tree.js.map +1 -0
  231. package/dist/util/secrets.js +31 -0
  232. package/dist/util/secrets.js.map +1 -0
  233. package/dist/version.js +5 -0
  234. package/dist/version.js.map +1 -0
  235. package/dist/workers/claude/classify.js +172 -0
  236. package/dist/workers/claude/classify.js.map +1 -0
  237. package/dist/workers/claude/index.js +440 -0
  238. package/dist/workers/claude/index.js.map +1 -0
  239. package/dist/workers/claude/process.js +135 -0
  240. package/dist/workers/claude/process.js.map +1 -0
  241. package/dist/workers/claude/quota.js +37 -0
  242. package/dist/workers/claude/quota.js.map +1 -0
  243. package/dist/workers/claude/stream.js +286 -0
  244. package/dist/workers/claude/stream.js.map +1 -0
  245. package/dist/workers/codex/index.js +181 -0
  246. package/dist/workers/codex/index.js.map +1 -0
  247. package/dist/workers/codex/mapping.js +166 -0
  248. package/dist/workers/codex/mapping.js.map +1 -0
  249. package/dist/workers/codex/process.js +124 -0
  250. package/dist/workers/codex/process.js.map +1 -0
  251. package/dist/workers/codex/protocol.js +7 -0
  252. package/dist/workers/codex/protocol.js.map +1 -0
  253. package/dist/workers/codex/rpc.js +145 -0
  254. package/dist/workers/codex/rpc.js.map +1 -0
  255. package/dist/workers/codex/run.js +556 -0
  256. package/dist/workers/codex/run.js.map +1 -0
  257. package/dist/workers/env.js +49 -0
  258. package/dist/workers/env.js.map +1 -0
  259. package/dist/workers/fake/index.js +283 -0
  260. package/dist/workers/fake/index.js.map +1 -0
  261. package/dist/workers/models.js +171 -0
  262. package/dist/workers/models.js.map +1 -0
  263. package/dist/workers/registry.js +63 -0
  264. package/dist/workers/registry.js.map +1 -0
  265. package/dist/workers/types.js +6 -0
  266. package/dist/workers/types.js.map +1 -0
  267. package/package.json +66 -4
@@ -0,0 +1,1253 @@
1
+ import { existsSync, mkdirSync, statSync, writeFileSync } from "node:fs";
2
+ import { basename, isAbsolute, join, resolve } from "node:path";
3
+ import { isoNow } from "../clock.js";
4
+ import { workerSettings } from "../config/schema.js";
5
+ import { canonicalPath } from "../landing/paths.js";
6
+ import { errorMessage } from "../log.js";
7
+ import { ToolError } from "../mcp/tools.js";
8
+ import { answerPrompt, briefChangedPrompt, failedChecksPrompt, handoverPrompt, QUOTA_RESUME_PROMPT, RATE_LIMIT_RESUME_PROMPT, RECOVERY_PROMPT, REPORT_REMINDER_PROMPT, RESUME_AFTER_PAUSE_PROMPT, SIGNED_IN_RESUME_PROMPT, STALL_RESUME_PROMPT, strategyNotePrompt, WORKER_GUIDANCE, } from "../prompts/worker.js";
9
+ import { formatResetTime } from "../quota/time.js";
10
+ import { recordEvent, transaction } from "../store/db.js";
11
+ import { runHealth, StallWatch } from "../supervisor/stalls.js";
12
+ import { agentLabel } from "../workers/registry.js";
13
+ import { selectAgent } from "./agents.js";
14
+ import { renderBrief } from "./brief.js";
15
+ import { runCheck } from "./checks.js";
16
+ import { blockedMessage, failedChecksEvidence, failedMessage, handoverMessage, quotaWaitMessage, signInHow, signInMessage, spendLimitMessage, unverifiedMessage, verifiedMessage, } from "./messages.js";
17
+ import { TERMINAL_GOAL_STATES, } from "./store.js";
18
+ const PAUSABLE = [
19
+ "queued",
20
+ "running",
21
+ "recovering",
22
+ "waiting_for_quota",
23
+ "waiting_for_login",
24
+ ];
25
+ const MAX_SUGGESTED_CHECKS = 5;
26
+ /** Failures that are really a short burst of rate limiting (Claude reports them as retryable). */
27
+ const TRANSIENT_FAILURE = /\b429\b|\b529\b|rate[ _-]?limit|too many requests|overloaded/i;
28
+ /**
29
+ * The durable Goal and Run state machine. Every transition is a synchronous database write;
30
+ * asynchronous work (agent turns, verification) re-reads state when it finishes, so a Goal
31
+ * cancelled or paused meanwhile is never overwritten.
32
+ */
33
+ export class GoalEngine {
34
+ deps;
35
+ live = new Map();
36
+ tasks = new Set();
37
+ wakeTimers = new Map();
38
+ checkAborts = new Map();
39
+ /** Runs whose live turn Preston interrupted on purpose (pause, cancel). */
40
+ interrupted = new Set();
41
+ /** Runs whose live turn the stall watch interrupted. */
42
+ stalled = new Set();
43
+ watch;
44
+ stopping = false;
45
+ constructor(deps) {
46
+ this.deps = deps;
47
+ deps.questions.onAnswered((question) => this.onAnswered(question));
48
+ deps.questions.onAnswered((question) => this.onLandingAnswered(question));
49
+ this.watch = new StallWatch(deps.clock, () => deps.config.get().supervision, (runId, evidence) => this.onStall(runId, evidence));
50
+ }
51
+ // ---- Commands ----------------------------------------------------------------------------
52
+ createGoal(input) {
53
+ const projectPath = canonicalPath(input.projectPath);
54
+ if (!isAbsolute(input.projectPath)) {
55
+ throw new ToolError("projectPath must be an absolute path to a folder on this computer.");
56
+ }
57
+ if (!existsSync(projectPath) || !statSync(projectPath).isDirectory()) {
58
+ throw new ToolError(`There is no folder at ${projectPath}.`);
59
+ }
60
+ if (input.parentGoalId && !this.deps.store.findGoal(input.parentGoalId)) {
61
+ throw new ToolError(`There is no goal ${input.parentGoalId}.`);
62
+ }
63
+ if (input.sourceKey) {
64
+ const existing = this.deps.store.findGoalBySource(input.sourceKey, input.brief.objective);
65
+ if (existing)
66
+ return existing;
67
+ }
68
+ const agent = input.agent ?? this.chooseAgentNow(projectPath);
69
+ const { store, db, clock } = this.deps;
70
+ const goal = transaction(db, () => {
71
+ const projectId = store.ensureProject(projectPath);
72
+ const created = store.createGoal({
73
+ projectId,
74
+ brief: input.brief,
75
+ parentGoalId: input.parentGoalId,
76
+ origin: input.origin,
77
+ sourceKey: input.sourceKey,
78
+ agentChoice: agent,
79
+ });
80
+ recordEvent(db, clock, "goal_created", { goalId: created.id }, { ...agent });
81
+ input.onCreated?.(created);
82
+ // No acknowledgement of Preston's own: the Coordinator answers the message that made the
83
+ // Goal, and a scheduled Goal says nothing until it has an outcome.
84
+ return created;
85
+ });
86
+ this.startNewRun(goal.id, agent.agent);
87
+ return this.deps.store.goal(goal.id);
88
+ }
89
+ cancelGoal(goalId, detail = "Stopped by you.") {
90
+ const goal = this.requireGoal(goalId);
91
+ if (isTerminal(goal.state))
92
+ throw new ToolError(`Goal ${goalId} has already finished.`);
93
+ const run = this.deps.store.currentRun(goalId);
94
+ transaction(this.deps.db, () => {
95
+ this.deps.store.setGoalState(goalId, "cancelled", { detail });
96
+ if (run)
97
+ this.deps.store.updateRun(run.id, { state: "ended", endReason: "cancelled" });
98
+ this.deps.questions.cancelForGoal(goalId);
99
+ recordEvent(this.deps.db, this.deps.clock, "goal_cancelled", { goalId });
100
+ });
101
+ this.haltWork(goalId, run);
102
+ return this.deps.store.goal(goalId);
103
+ }
104
+ updateBrief(goalId, brief) {
105
+ const goal = this.requireGoal(goalId);
106
+ if (isTerminal(goal.state)) {
107
+ throw new ToolError(`Goal ${goalId} has finished; create a follow-up Goal instead.`);
108
+ }
109
+ this.deps.store.updateBrief(goalId, brief);
110
+ recordEvent(this.deps.db, this.deps.clock, "brief_updated", { goalId });
111
+ return this.deps.store.goal(goalId);
112
+ }
113
+ /** Pauses all work that is running or about to run. Returns the paused Goals. */
114
+ pauseAll() {
115
+ const paused = this.deps.store.activeGoals().filter((g) => PAUSABLE.includes(g.state));
116
+ for (const goal of paused) {
117
+ this.deps.store.setGoalState(goal.id, "paused", { detail: "Paused by you." });
118
+ recordEvent(this.deps.db, this.deps.clock, "goal_paused", { goalId: goal.id });
119
+ this.haltWork(goal.id, this.deps.store.currentRun(goal.id));
120
+ }
121
+ return paused;
122
+ }
123
+ /** Resumes every paused Goal. Returns the resumed Goals. */
124
+ resumeAll() {
125
+ const paused = this.deps.store.activeGoals().filter((g) => g.state === "paused");
126
+ for (const goal of paused) {
127
+ recordEvent(this.deps.db, this.deps.clock, "goal_resumed", { goalId: goal.id });
128
+ const run = this.deps.store.currentRun(goal.id);
129
+ if (!run) {
130
+ this.startNewRun(goal.id, this.pickAgentOr(goal));
131
+ }
132
+ else if (this.live.has(run.id)) {
133
+ // Still winding down from the pause; the turn's end continues it.
134
+ this.deps.store.setGoalState(goal.id, "running");
135
+ }
136
+ else {
137
+ this.nextStep(this.deps.store.goal(goal.id), run, run.sessionId ? RESUME_AFTER_PAUSE_PROMPT : renderBrief(goal.id, goal.brief));
138
+ }
139
+ }
140
+ return paused;
141
+ }
142
+ /**
143
+ * Tries again to merge a finished Goal's verified work that was held back (the user said no
144
+ * to a publishing question) or blocked (an overlap with their own edits, checks that did not
145
+ * finish). It never runs the Worker unless landing itself needs it, and it never merges work
146
+ * Preston did not verify. Safe to repeat: a Goal already being merged is left alone.
147
+ */
148
+ async relandGoal(goalId, options) {
149
+ const { store, db, clock, landing } = this.deps;
150
+ if (!landing)
151
+ throw new ToolError("Merging is not available in this Preston.");
152
+ const goal = this.requireGoal(goalId);
153
+ if (!isTerminal(goal.state)) {
154
+ if (landing.isLanding(goalId))
155
+ return { goal, note: "It is already being merged." };
156
+ throw new ToolError(`Goal ${goalId} has not finished, so there is nothing to merge yet.`);
157
+ }
158
+ const problem = await landing.prepareReland(goal);
159
+ if (problem)
160
+ throw new ToolError(problem);
161
+ const last = store.runsForGoal(goalId).at(-1);
162
+ const started = transaction(db, () => {
163
+ // Another call may have started it while the working copy was being restored.
164
+ if (!isTerminal(store.goal(goalId).state))
165
+ return false;
166
+ landing.resetForReland(goalId, options);
167
+ const run = store.createRun({
168
+ goalId,
169
+ agent: last?.agent ?? this.pickAgentOr(goal),
170
+ workdir: last?.workdir ?? goal.projectPath,
171
+ transcriptDir: (id) => join(this.deps.transcriptsDir, id),
172
+ });
173
+ // Landing may need the Worker (a conflict): it continues the Session that did the work.
174
+ store.updateRun(run.id, {
175
+ ...(last?.sessionId ? { sessionId: last.sessionId } : {}),
176
+ ...(last?.report ? { report: last.report } : {}),
177
+ });
178
+ store.setGoalState(goalId, "verifying", { detail: "Merging the finished work." });
179
+ recordEvent(db, clock, "goal_relanded", { goalId, runId: run.id }, options);
180
+ return true;
181
+ });
182
+ if (!started)
183
+ return { goal: store.goal(goalId), note: "It is already being merged." };
184
+ this.landWork(goalId);
185
+ return { goal: store.goal(goalId), note: "Trying to merge it again." };
186
+ }
187
+ /** Cancels every Goal that has not finished. */
188
+ stopAll() {
189
+ return this.deps.store.activeGoals().map((goal) => this.cancelGoal(goal.id, "Stopped by you."));
190
+ }
191
+ recordReport(runId, report) {
192
+ const run = this.deps.store.run(runId);
193
+ if (run.state === "ended")
194
+ throw new ToolError("This Run has already ended.");
195
+ this.deps.store.updateRun(runId, { report, reportPending: true });
196
+ recordEvent(this.deps.db, this.deps.clock, "worker_reported", { goalId: run.goalId, runId }, {
197
+ blockers: report.blockers.length,
198
+ suggested: report.suggestedVerificationCommands.length,
199
+ });
200
+ }
201
+ /**
202
+ * The Coordinator's decision after a Goal stalled repeatedly. Each decision is recorded on
203
+ * the Goal; after `supervision.maxStrategyChanges` Preston reports Blocked instead of asking.
204
+ */
205
+ changeStrategy(goalId, action, note) {
206
+ const goal = this.requireGoal(goalId);
207
+ const run = this.deps.store.currentRun(goalId);
208
+ if (!run?.strategyPending) {
209
+ throw new ToolError(`Goal ${goalId} is not waiting for a decision on how to continue.`);
210
+ }
211
+ const { store, db } = this.deps;
212
+ const label = agentLabel(run.agent);
213
+ switch (action) {
214
+ case "retry_with_note":
215
+ transaction(db, () => {
216
+ store.updateRun(run.id, { strategyPending: false, stalls: 0 });
217
+ store.addAttempt(goalId, {
218
+ runId: run.id,
219
+ agent: run.agent,
220
+ tactic: action,
221
+ reason: note,
222
+ });
223
+ });
224
+ this.resumeRun(store.run(run.id), run.sessionId ? strategyNotePrompt(note) : renderBrief(goalId, goal.brief));
225
+ break;
226
+ case "fresh_session":
227
+ this.replaceRun(goal, run, run.agent, {
228
+ tactic: action,
229
+ reason: note,
230
+ prompt: (brief) => handoverPrompt({
231
+ brief,
232
+ reason: "it stalled repeatedly",
233
+ previousAgent: `An earlier ${label} session`,
234
+ previousReport: run.report?.summary,
235
+ lastMessage: run.lastMessage ?? undefined,
236
+ note,
237
+ }),
238
+ });
239
+ break;
240
+ case "switch_agent": {
241
+ const target = this.otherAgents(run.agent).find((a) => !this.deps.quota.activeBlock(a));
242
+ if (!target)
243
+ throw new ToolError("No other coding agent is set up with quota to switch to.");
244
+ this.replaceRun(goal, run, target, {
245
+ tactic: action,
246
+ reason: note,
247
+ prompt: (brief) => handoverPrompt({
248
+ brief,
249
+ reason: "it stalled repeatedly",
250
+ previousAgent: label,
251
+ previousReport: run.report?.summary,
252
+ lastMessage: run.lastMessage ?? undefined,
253
+ note,
254
+ }),
255
+ });
256
+ break;
257
+ }
258
+ case "report_blocked":
259
+ store.addAttempt(goalId, { runId: run.id, agent: run.agent, tactic: action, reason: note });
260
+ this.fail(goal, run, "blocked", note);
261
+ break;
262
+ }
263
+ return store.goal(goalId);
264
+ }
265
+ /** Runs a Coordinator decision is still pending for (raised again after a restart). */
266
+ pendingGoalEvents() {
267
+ return this.deps.store.strategyPendingRuns().map((run) => ({
268
+ goalId: run.goalId,
269
+ runId: run.id,
270
+ detail: this.lastAttempt(run.goalId, "strategy_event")?.reason ?? "it stalled repeatedly",
271
+ }));
272
+ }
273
+ /** After the Coordinator handled a Goal event without deciding: report Blocked, never loop. */
274
+ goalEventHandled(event) {
275
+ const run = this.deps.store.findRun(event.runId);
276
+ if (!run?.strategyPending || run.state === "ended")
277
+ return;
278
+ const goal = this.deps.store.goal(run.goalId);
279
+ this.fail(goal, run, "blocked", `The worker stalled repeatedly (${event.detail}) and I couldn't find a different way to continue. Tell me how you'd like to proceed.`);
280
+ }
281
+ /** How a Run looks to the supervisor right now. */
282
+ runHealth(runId) {
283
+ const run = this.deps.store.findRun(runId);
284
+ if (!run)
285
+ return undefined;
286
+ return runHealth({
287
+ goal: this.deps.store.goal(run.goalId),
288
+ run,
289
+ live: this.live.has(runId) ? this.watch.liveness(runId) : undefined,
290
+ now: this.deps.clock.now(),
291
+ settings: this.deps.config.get().supervision,
292
+ });
293
+ }
294
+ /** Reconciles every unfinished Goal with reality. Nothing is assumed to be running. */
295
+ recover() {
296
+ for (const goal of this.deps.store.activeGoals()) {
297
+ const run = this.deps.store.currentRun(goal.id);
298
+ recordEvent(this.deps.db, this.deps.clock, "goal_reconciled", { goalId: goal.id }, { state: goal.state });
299
+ // Still waiting for the Coordinator to decide; it raises the event again when it starts.
300
+ if (run?.strategyPending)
301
+ continue;
302
+ switch (goal.state) {
303
+ case "queued":
304
+ case "running":
305
+ case "recovering":
306
+ if (run)
307
+ this.recoverRun(goal, run, "Preston restarted");
308
+ else
309
+ this.startNewRun(goal.id, this.pickAgentOr(goal));
310
+ break;
311
+ case "verifying":
312
+ if (this.deps.landing?.isLanding(goal.id))
313
+ this.landWork(goal.id);
314
+ else if (run?.reportPending)
315
+ this.verify(goal.id, run.id);
316
+ else if (run)
317
+ this.recoverRun(goal, run, "Preston restarted");
318
+ else
319
+ this.startNewRun(goal.id, this.pickAgentOr(goal));
320
+ break;
321
+ case "waiting_for_user":
322
+ if (!run)
323
+ break;
324
+ if (this.deps.landing?.isLanding(goal.id)) {
325
+ this.landWork(goal.id);
326
+ break;
327
+ }
328
+ for (const q of this.deps.questions.forRun(run.id).open) {
329
+ if (q.state === "pending_coordinator")
330
+ this.deps.raiseWorkerQuestion(q);
331
+ }
332
+ this.nextStep(goal, run, undefined);
333
+ break;
334
+ case "waiting_for_quota":
335
+ // Bucket waits are resumed by the quota monitor; short rate-limit waits by a timer.
336
+ if (!run?.quotaBucket)
337
+ this.scheduleWake(goal.id, goal.wakeAt ?? isoNow(this.deps.clock));
338
+ break;
339
+ case "waiting_for_login":
340
+ case "paused":
341
+ break;
342
+ }
343
+ }
344
+ }
345
+ /** Stops all live work without changing durable state, so the next start recovers it. */
346
+ async stop() {
347
+ this.stopping = true;
348
+ this.watch.stopAll();
349
+ for (const timer of this.wakeTimers.values())
350
+ timer.cancel();
351
+ this.wakeTimers.clear();
352
+ for (const abort of this.checkAborts.values())
353
+ abort.abort();
354
+ this.deps.landing?.abort();
355
+ await Promise.allSettled([...this.live.values()].map((h) => h.interrupt()));
356
+ await Promise.allSettled([...this.tasks]);
357
+ }
358
+ // ---- Quota (called by the quota monitor) -------------------------------------------------
359
+ /** Resumes a Run that waited for quota or a login. False when it no longer waits. */
360
+ resumeFromQuota(runId, probe) {
361
+ if (this.stopping)
362
+ return false;
363
+ const run = this.deps.store.findRun(runId);
364
+ if (run?.state !== "parked" || this.live.has(runId))
365
+ return false;
366
+ const goal = this.deps.store.goal(run.goalId);
367
+ if (goal.state !== "waiting_for_quota" && goal.state !== "waiting_for_login")
368
+ return false;
369
+ const prompt = !run.sessionId
370
+ ? renderBrief(goal.id, goal.brief)
371
+ : goal.state === "waiting_for_login"
372
+ ? SIGNED_IN_RESUME_PROMPT
373
+ : QUOTA_RESUME_PROMPT;
374
+ this.deps.store.updateRun(runId, probe ? { quotaBucket: null } : { quotaBucket: null, waitingSince: null });
375
+ recordEvent(this.deps.db, this.deps.clock, "quota_resume", { goalId: goal.id, runId }, { probe });
376
+ this.nextStep(goal, this.deps.store.run(runId), prompt);
377
+ return true;
378
+ }
379
+ /** A check found a bucket still blocked: tell the user or hand Goals over, if warranted. */
380
+ reviewWaits(bucket) {
381
+ for (const run of this.deps.store.waitingRuns(bucket.bucket)) {
382
+ this.track(this.reviewWait(run.id, bucket));
383
+ }
384
+ }
385
+ // ---- Runs and turns ----------------------------------------------------------------------
386
+ startNewRun(goalId, agent) {
387
+ const goal = this.deps.store.goal(goalId);
388
+ const run = this.deps.store.createRun({
389
+ goalId,
390
+ agent,
391
+ workdir: goal.projectPath,
392
+ transcriptDir: (id) => join(this.deps.transcriptsDir, id),
393
+ });
394
+ this.deps.store.setGoalState(goalId, "running");
395
+ recordEvent(this.deps.db, this.deps.clock, "run_started", { goalId, runId: run.id }, { agent });
396
+ this.spawnTurn(run.id, renderBrief(goalId, goal.brief));
397
+ }
398
+ spawnTurn(runId, prompt) {
399
+ if (this.live.has(runId)) {
400
+ this.deps.log.error("refused to start a second turn for a live Run", { runId });
401
+ return;
402
+ }
403
+ this.track(this.executeTurn(runId, prompt), "turn failed", { runId });
404
+ }
405
+ track(task, what = "background task failed", data = {}) {
406
+ const tracked = task
407
+ .catch((err) => this.deps.log.error(what, { ...data, error: err }))
408
+ .finally(() => this.tasks.delete(tracked));
409
+ this.tasks.add(tracked);
410
+ }
411
+ async executeTurn(runId, prompt) {
412
+ const { store, tokens, config, quota } = this.deps;
413
+ let run = store.run(runId);
414
+ const goal = store.goal(run.goalId);
415
+ // The Goal's own working copy (a worktree), created or reused here, before every turn.
416
+ const workspace = await this.deps.landing?.prepare(goal, run);
417
+ const now = store.goal(goal.id).state;
418
+ if (this.stopping || isTerminal(now))
419
+ return;
420
+ if (now === "paused") {
421
+ // Paused while the working copy was being made: nothing has started yet.
422
+ store.updateRun(runId, { state: "parked" });
423
+ return;
424
+ }
425
+ if (workspace && !workspace.ok) {
426
+ this.fail(goal, run, "blocked", workspace.reason);
427
+ return;
428
+ }
429
+ if (workspace && workspace.workdir !== run.workdir) {
430
+ store.updateRun(runId, { workdir: workspace.workdir });
431
+ run = store.run(runId);
432
+ }
433
+ const adapter = this.deps.adapter(run.agent);
434
+ if (!adapter) {
435
+ this.fail(goal, run, "failed", `${agentLabel(run.agent)} is not available on this computer.`);
436
+ return;
437
+ }
438
+ const turn = run.turns + 1;
439
+ store.updateRun(runId, { state: "active", turns: turn });
440
+ mkdirSync(run.transcriptDir, { recursive: true });
441
+ const token = tokens.mint({ role: "worker", runId, goalId: goal.id });
442
+ const settings = workerSettings(config.get().workers, run.agent);
443
+ let end;
444
+ let trackedPid;
445
+ let tracking = Promise.resolve();
446
+ const resumed = run.sessionId !== null;
447
+ let sessionStarted = false;
448
+ try {
449
+ const handle = adapter.startRun({
450
+ runId,
451
+ workdir: run.workdir,
452
+ prompt,
453
+ resumeSessionId: run.sessionId ?? undefined,
454
+ appendSystemPrompt: withExtra(workspace?.guidance ? `${WORKER_GUIDANCE}\n\n${workspace.guidance}` : WORKER_GUIDANCE, this.deps.workerContext?.(goal)),
455
+ model: settings.model,
456
+ effort: settings.effort,
457
+ mcp: this.deps.mcpLaunch(token),
458
+ access: "full",
459
+ transcriptPath: join(run.transcriptDir, `turn-${turn}.log`),
460
+ });
461
+ this.live.set(runId, handle);
462
+ this.watch.begin(runId);
463
+ const trackPid = () => {
464
+ const pid = handle.processId?.();
465
+ if (pid === undefined || pid === trackedPid)
466
+ return;
467
+ trackedPid = pid;
468
+ tracking = this.deps.processes.track(runId, run.agent, pid);
469
+ this.track(tracking, "could not record the agent process", { runId, pid });
470
+ };
471
+ trackPid();
472
+ for await (const event of handle.events) {
473
+ trackPid();
474
+ this.watch.observe(runId, event);
475
+ if (event.type === "started") {
476
+ sessionStarted = true;
477
+ store.updateRun(runId, { sessionId: event.sessionId });
478
+ store.recordSession(run.agent, event.sessionId, "worker", run.workdir);
479
+ }
480
+ else if (event.type === "message") {
481
+ store.updateRun(runId, { lastMessage: event.text.slice(-2000) });
482
+ }
483
+ if (event.type === "activity" || event.type === "message" || event.type === "completed") {
484
+ quota.progress(runId);
485
+ }
486
+ if (isTurnEnd(event))
487
+ end ??= event;
488
+ }
489
+ }
490
+ catch (err) {
491
+ end ??= {
492
+ type: "failed",
493
+ at: isoNow(this.deps.clock),
494
+ error: errorMessage(err),
495
+ retryable: true,
496
+ };
497
+ }
498
+ finally {
499
+ this.live.delete(runId);
500
+ this.watch.end(runId);
501
+ tokens.revoke(token);
502
+ // On shutdown the record stays: the next start verifies the process really is gone.
503
+ if (!this.stopping) {
504
+ this.track(tracking.then(() => this.deps.processes.untrack(runId)), "could not forget the agent process");
505
+ }
506
+ }
507
+ if (this.stopping)
508
+ return;
509
+ this.afterTurn(runId, end, resumed && !sessionStarted);
510
+ }
511
+ /** `resumeLost`: the turn tried to resume a native Session and never got one back. */
512
+ afterTurn(runId, end, resumeLost = false) {
513
+ const { store } = this.deps;
514
+ const run = store.run(runId);
515
+ const interruptedByPreston = this.interrupted.delete(runId);
516
+ const stalled = this.stalled.delete(runId);
517
+ if (end?.type !== "quota_blocked" && end?.type !== "auth_error") {
518
+ this.deps.quota.turnEnded(runId);
519
+ }
520
+ if (run.state === "ended")
521
+ return;
522
+ const goal = store.goal(run.goalId);
523
+ recordEvent(this.deps.db, this.deps.clock, "turn_ended", { goalId: goal.id, runId }, {
524
+ end: stalled ? "stalled" : (end?.type ?? "exited"),
525
+ });
526
+ if (isTerminal(goal.state)) {
527
+ store.updateRun(runId, { state: "ended", endReason: goal.state });
528
+ return;
529
+ }
530
+ if (goal.state === "paused") {
531
+ store.updateRun(runId, { state: "parked" });
532
+ return;
533
+ }
534
+ if (interruptedByPreston) {
535
+ // Paused, then resumed before the interrupted turn wound down.
536
+ this.nextStep(goal, run, RESUME_AFTER_PAUSE_PROMPT);
537
+ return;
538
+ }
539
+ if (stalled) {
540
+ this.handleStall(goal, run);
541
+ return;
542
+ }
543
+ const waiting = end?.type === "quota_blocked" || end?.type === "auth_error";
544
+ if (!waiting && run.waitingSince)
545
+ store.updateRun(runId, { waitingSince: null });
546
+ if (end?.type === "failed" && end.retryable && TRANSIENT_FAILURE.test(end.error)) {
547
+ this.waitBriefly(goal, store.run(runId), end.error);
548
+ return;
549
+ }
550
+ if (resumeLost && (!end || end.type === "failed")) {
551
+ this.startNewSession(goal, run, end?.type === "failed" ? end.error : undefined);
552
+ return;
553
+ }
554
+ switch (end?.type) {
555
+ case "completed":
556
+ if (run.rateLimitHits || run.stalls)
557
+ store.updateRun(runId, { rateLimitHits: 0, stalls: 0 });
558
+ this.nextStep(goal, store.run(runId), REPORT_REMINDER_PROMPT);
559
+ return;
560
+ case "quota_blocked":
561
+ if (end.kind === "rate_limit")
562
+ this.waitBriefly(goal, run, end.detail);
563
+ else
564
+ this.waitForQuota(goal, run, end);
565
+ return;
566
+ case "auth_error":
567
+ this.waitForLogin(goal, run, end.detail);
568
+ return;
569
+ default: {
570
+ const reason = end?.type === "failed" ? end.error : "the worker exited unexpectedly";
571
+ if (run.stalls > 0) {
572
+ this.raiseStrategy(goal, run, `it failed after Preston resumed it from a stall: ${reason}`);
573
+ return;
574
+ }
575
+ this.recoverRun(goal, run, reason);
576
+ }
577
+ }
578
+ }
579
+ /**
580
+ * Decides what a Run that is between turns does next. `fallback` is the prompt to resume with
581
+ * when nothing else is pending; undefined leaves the Run waiting.
582
+ */
583
+ nextStep(goal, run, fallback) {
584
+ const { store, questions } = this.deps;
585
+ const { open, undelivered } = questions.forRun(run.id);
586
+ if (undelivered.length) {
587
+ questions.markDelivered(undelivered.map((q) => q.id));
588
+ this.resumeRun(run, answerPrompt(undelivered.map((q) => ({ question: q.text, answer: q.answer ?? "" }))));
589
+ return;
590
+ }
591
+ if (open.length) {
592
+ store.updateRun(run.id, { state: "parked" });
593
+ store.setGoalState(goal.id, "waiting_for_user", { detail: "Waiting for an answer." });
594
+ return;
595
+ }
596
+ if (run.briefChanged) {
597
+ store.updateRun(run.id, { briefChanged: false });
598
+ this.resumeRun(run, briefChangedPrompt(renderBrief(goal.id, goal.brief)));
599
+ return;
600
+ }
601
+ if (run.reportPending) {
602
+ this.verify(goal.id, run.id);
603
+ return;
604
+ }
605
+ if (fallback === undefined)
606
+ return;
607
+ if (fallback === REPORT_REMINDER_PROMPT) {
608
+ if (run.recoveries >= this.deps.config.get().recovery.maxAttempts) {
609
+ this.fail(goal, run, "failed", "The worker kept stopping without reporting a result.");
610
+ return;
611
+ }
612
+ store.updateRun(run.id, { recoveries: run.recoveries + 1 });
613
+ }
614
+ this.resumeRun(run, fallback);
615
+ }
616
+ /**
617
+ * The Session cannot be resumed (typically because the agent's CLI was updated and cannot read
618
+ * it). The Goal does not fail: the same agent continues in a new Session from the Brief and a
619
+ * compact checkpoint, like a handover.
620
+ */
621
+ startNewSession(goal, run, error) {
622
+ const label = agentLabel(run.agent);
623
+ this.deps.log.warn("session could not be resumed; starting a new one", {
624
+ runId: run.id,
625
+ agent: run.agent,
626
+ error,
627
+ });
628
+ this.replaceRun(goal, run, run.agent, {
629
+ tactic: "fresh_session",
630
+ reason: `the earlier ${label} session could not be resumed${error ? ` (${error})` : ""}`,
631
+ prompt: (brief) => handoverPrompt({
632
+ brief,
633
+ reason: "its session could not be picked up again, for example after an update",
634
+ previousAgent: `An earlier ${label} session`,
635
+ previousReport: run.report?.summary,
636
+ lastMessage: run.lastMessage ?? undefined,
637
+ }),
638
+ });
639
+ }
640
+ recoverRun(goal, run, reason) {
641
+ const { store } = this.deps;
642
+ if (run.recoveries >= this.deps.config.get().recovery.maxAttempts) {
643
+ this.fail(goal, run, "failed", `The worker kept stopping unexpectedly (${reason}).`);
644
+ return;
645
+ }
646
+ store.updateRun(run.id, { state: "parked", recoveries: run.recoveries + 1 });
647
+ store.setGoalState(goal.id, "recovering", { detail: reason });
648
+ recordEvent(this.deps.db, this.deps.clock, "run_recovering", { goalId: goal.id, runId: run.id }, { reason });
649
+ // Without a native Session there is nothing to resume: start the Run again from the Brief.
650
+ this.resumeRun(run, run.sessionId ? RECOVERY_PROMPT : renderBrief(goal.id, goal.brief));
651
+ }
652
+ resumeRun(run, prompt) {
653
+ if (run.quotaBucket)
654
+ this.deps.store.updateRun(run.id, { quotaBucket: null });
655
+ this.deps.store.setGoalState(run.goalId, "running");
656
+ this.spawnTurn(run.id, prompt);
657
+ }
658
+ onAnswered(question) {
659
+ if (!question.runId || question.answerDelivered || this.stopping)
660
+ return;
661
+ const run = this.deps.store.findRun(question.runId);
662
+ if (!run || run.state === "ended" || this.live.has(run.id))
663
+ return;
664
+ const goal = this.deps.store.goal(run.goalId);
665
+ if (goal.state === "waiting_for_user")
666
+ this.nextStep(goal, run, undefined);
667
+ }
668
+ /** A short, time-based wait after a transient rate limit; no quota monitor, no message. */
669
+ waitBriefly(goal, run, detail) {
670
+ const settings = this.deps.config.get().quota;
671
+ const hits = run.rateLimitHits + 1;
672
+ const delay = Math.min(settings.rateLimitWaitMs * 2 ** (hits - 1), settings.rateLimitMaxWaitMs);
673
+ const wakeAt = new Date(this.deps.clock.now() + delay).toISOString();
674
+ transaction(this.deps.db, () => {
675
+ this.deps.store.updateRun(run.id, { state: "parked", rateLimitHits: hits });
676
+ this.deps.store.setGoalState(goal.id, "waiting_for_quota", {
677
+ detail: `${agentLabel(run.agent)} is briefly rate-limited; retrying shortly.`,
678
+ wakeAt,
679
+ });
680
+ recordEvent(this.deps.db, this.deps.clock, "rate_limited", { goalId: goal.id, runId: run.id }, { hits, delayMs: delay, detail });
681
+ });
682
+ this.scheduleWake(goal.id, wakeAt);
683
+ }
684
+ /** The agent's quota ran out: park the Run on its bucket's monitor. Never a failure. */
685
+ waitForQuota(goal, run, end) {
686
+ const { store, db, clock, quota } = this.deps;
687
+ const label = agentLabel(run.agent);
688
+ const kind = end.kind === "spend_limit" ? "spend_limit" : "usage_limit";
689
+ transaction(db, () => {
690
+ store.updateRun(run.id, {
691
+ state: "parked",
692
+ quotaBucket: end.bucket,
693
+ waitingSince: run.waitingSince ?? isoNow(clock),
694
+ });
695
+ store.setGoalState(goal.id, "waiting_for_quota", {
696
+ detail: kind === "spend_limit"
697
+ ? `${label} has reached its spending limit.`
698
+ : `${label} is out of quota.`,
699
+ wakeAt: end.resetsAt ?? null,
700
+ });
701
+ recordEvent(db, clock, "quota_blocked", { goalId: goal.id, runId: run.id }, { bucket: end.bucket, kind, resetsAt: end.resetsAt, detail: end.detail });
702
+ });
703
+ const bucket = quota.runBlocked({
704
+ owner: run.id,
705
+ agent: run.agent,
706
+ bucket: end.bucket,
707
+ kind,
708
+ resetsAt: end.resetsAt,
709
+ detail: end.detail,
710
+ });
711
+ this.track(this.reviewWait(run.id, bucket));
712
+ }
713
+ /** The agent's login broke: tell the user once, and resume when a check shows it works. */
714
+ waitForLogin(goal, run, detail) {
715
+ const { store, db, clock, quota } = this.deps;
716
+ const label = agentLabel(run.agent);
717
+ const bucket = transaction(db, () => {
718
+ store.updateRun(run.id, {
719
+ state: "parked",
720
+ waitingSince: run.waitingSince ?? isoNow(clock),
721
+ });
722
+ store.setGoalState(goal.id, "waiting_for_login", {
723
+ detail: `${label} needs you to sign in again.`,
724
+ });
725
+ recordEvent(db, clock, "auth_error", { goalId: goal.id, runId: run.id }, { detail });
726
+ const blocked = quota.authBroken({ owner: run.id, agent: run.agent, detail });
727
+ store.updateRun(run.id, { quotaBucket: blocked.bucket });
728
+ return blocked;
729
+ });
730
+ // One message per agent sign-out, however many Goals it holds up.
731
+ this.deps.outbox.broadcast({
732
+ kind: "notice",
733
+ text: signInMessage(goal, label, signInHow(run.agent)),
734
+ goalId: goal.id,
735
+ dedupeKey: `signin:${run.agent}:${bucket.blockedAt}`,
736
+ });
737
+ }
738
+ /**
739
+ * Decides whether a quota wait changes expectations: hand the Goal to another agent with
740
+ * headroom when the wait is long, otherwise tell the user once if it is noticeably long.
741
+ */
742
+ async reviewWait(runId, bucket) {
743
+ const stillWaiting = () => {
744
+ const run = this.deps.store.findRun(runId);
745
+ const goal = run && this.deps.store.findGoal(run.goalId);
746
+ return run?.state === "parked" &&
747
+ run.quotaBucket === bucket.bucket &&
748
+ goal?.state === "waiting_for_quota"
749
+ ? { run, goal }
750
+ : undefined;
751
+ };
752
+ const first = stillWaiting();
753
+ if (!first || this.stopping)
754
+ return;
755
+ const settings = this.deps.config.get().quota;
756
+ const now = this.deps.clock.now();
757
+ const reset = bucket.resetsAt ? Date.parse(bucket.resetsAt) - now : Number.NaN;
758
+ const waited = first.run.waitingSince ? now - Date.parse(first.run.waitingSince) : 0;
759
+ // An unknown reset counts as long only once the wait has actually lasted that long.
760
+ const expected = Number.isFinite(reset) ? Math.max(reset, waited) : waited;
761
+ const until = bucket.resetsAt && reset > 0 ? formatResetTime(bucket.resetsAt, now) : undefined;
762
+ if (expected > settings.switchAfterMs) {
763
+ const target = await this.switchTarget(first.run.agent);
764
+ const current = stillWaiting();
765
+ if (!current || this.stopping)
766
+ return;
767
+ if (target) {
768
+ const from = agentLabel(current.run.agent);
769
+ const to = agentLabel(target);
770
+ this.replaceRun(current.goal, current.run, target, {
771
+ tactic: "quota_handover",
772
+ reason: `${from} is out of quota${until ? ` until ${until}` : ""}`,
773
+ notice: handoverMessage(current.goal, from, to, until),
774
+ prompt: (brief) => handoverPrompt({
775
+ brief,
776
+ reason: "its usage quota ran out",
777
+ previousAgent: from,
778
+ previousReport: current.run.report?.summary,
779
+ lastMessage: current.run.lastMessage ?? undefined,
780
+ }),
781
+ });
782
+ return;
783
+ }
784
+ }
785
+ const { run, goal } = first;
786
+ const label = agentLabel(run.agent);
787
+ const text = bucket.state === "spend_blocked"
788
+ ? spendLimitMessage(goal, label)
789
+ : expected > settings.notifyAfterMs
790
+ ? quotaWaitMessage(goal, label, until)
791
+ : undefined;
792
+ if (!text)
793
+ return;
794
+ this.deps.outbox.broadcast({
795
+ kind: "notice",
796
+ text,
797
+ goalId: goal.id,
798
+ dedupeKey: `quota-wait:${goal.id}:${run.waitingSince}`,
799
+ });
800
+ }
801
+ /** Another configured agent the user allowed, with quota headroom right now. */
802
+ async switchTarget(from) {
803
+ if (!this.deps.config.get().agents.balanceByQuota)
804
+ return undefined;
805
+ for (const agent of this.otherAgents(from)) {
806
+ if (await this.deps.quota.headroom(agent))
807
+ return agent;
808
+ }
809
+ return undefined;
810
+ }
811
+ otherAgents(from) {
812
+ return this.deps.config
813
+ .get()
814
+ .agents.enabled.filter((a) => a !== from && this.deps.adapter(a) !== undefined);
815
+ }
816
+ /**
817
+ * Ends a Run and continues the Goal in a new Session (on the same or another agent), seeded
818
+ * with the Brief and a compact checkpoint. Never claims to continue the old Session exactly.
819
+ */
820
+ replaceRun(goal, run, agent, how) {
821
+ const { store, db, clock, outbox } = this.deps;
822
+ const next = transaction(db, () => {
823
+ store.updateRun(run.id, {
824
+ state: "ended",
825
+ endReason: how.tactic,
826
+ quotaBucket: null,
827
+ strategyPending: false,
828
+ });
829
+ const created = store.createRun({
830
+ goalId: goal.id,
831
+ agent,
832
+ workdir: run.workdir,
833
+ transcriptDir: (id) => join(this.deps.transcriptsDir, id),
834
+ });
835
+ store.setGoalState(goal.id, "running");
836
+ store.addAttempt(goal.id, {
837
+ runId: run.id,
838
+ agent: run.agent,
839
+ tactic: how.tactic,
840
+ reason: how.reason,
841
+ });
842
+ recordEvent(db, clock, "run_replaced", { goalId: goal.id, runId: created.id }, { from: run.id, fromAgent: run.agent, agent, tactic: how.tactic });
843
+ if (how.notice) {
844
+ outbox.broadcast({
845
+ kind: "notice",
846
+ text: how.notice,
847
+ goalId: goal.id,
848
+ dedupeKey: `handover:${run.id}`,
849
+ });
850
+ }
851
+ return created;
852
+ });
853
+ this.spawnTurn(next.id, how.prompt(renderBrief(goal.id, store.goal(goal.id).brief)));
854
+ }
855
+ scheduleWake(goalId, at) {
856
+ this.wakeTimers.get(goalId)?.cancel();
857
+ const delay = Math.max(0, Date.parse(at) - this.deps.clock.now());
858
+ this.wakeTimers.set(goalId, this.deps.clock.setTimeout(() => {
859
+ this.wakeTimers.delete(goalId);
860
+ const goal = this.deps.store.findGoal(goalId);
861
+ const run = this.deps.store.currentRun(goalId);
862
+ if (goal?.state !== "waiting_for_quota" || !run || run.quotaBucket)
863
+ return;
864
+ this.resumeRun(run, run.sessionId ? RATE_LIMIT_RESUME_PROMPT : renderBrief(goalId, goal.brief));
865
+ }, delay));
866
+ }
867
+ // ---- Stalls ------------------------------------------------------------------------------
868
+ /** The stall watch saw a live turn go silent: save evidence and interrupt it. */
869
+ onStall(runId, evidence) {
870
+ const handle = this.live.get(runId);
871
+ if (!handle || this.stopping)
872
+ return;
873
+ const run = this.deps.store.run(runId);
874
+ try {
875
+ writeFileSync(join(run.transcriptDir, `stall-${Date.parse(evidence.at)}.json`), JSON.stringify({ ...evidence, turn: run.turns, sessionId: run.sessionId }, null, 2));
876
+ }
877
+ catch (err) {
878
+ this.deps.log.warn("could not save stall evidence", { runId, error: err });
879
+ }
880
+ recordEvent(this.deps.db, this.deps.clock, "run_stalled", { goalId: run.goalId, runId }, evidence);
881
+ this.deps.log.warn("worker stalled", { runId, quietMs: evidence.quietMs });
882
+ this.stalled.add(runId);
883
+ handle
884
+ .interrupt()
885
+ .catch((err) => this.deps.log.warn("interrupt failed", { runId, error: err }));
886
+ }
887
+ /** First stall: resume the Session once with a note. Again: ask the Coordinator. */
888
+ handleStall(goal, run) {
889
+ const stalls = run.stalls + 1;
890
+ if (stalls > 1) {
891
+ this.raiseStrategy(goal, run, "it stalled again after Preston resumed it");
892
+ return;
893
+ }
894
+ const { store, db } = this.deps;
895
+ transaction(db, () => {
896
+ store.updateRun(run.id, { state: "parked", stalls });
897
+ store.setGoalState(goal.id, "recovering", { detail: "The worker went silent; resuming it." });
898
+ store.addAttempt(goal.id, {
899
+ runId: run.id,
900
+ agent: run.agent,
901
+ tactic: "stall_resume",
902
+ reason: "it went silent",
903
+ });
904
+ });
905
+ this.resumeRun(store.run(run.id), run.sessionId ? STALL_RESUME_PROMPT : renderBrief(goal.id, goal.brief));
906
+ }
907
+ /** Raises one Coordinator event, or reports Blocked once strategy changes are used up. */
908
+ raiseStrategy(goal, run, reason) {
909
+ const { store, db, clock } = this.deps;
910
+ const raised = goal.attempts.filter((a) => a.tactic === "strategy_event").length;
911
+ if (raised >= this.deps.config.get().supervision.maxStrategyChanges) {
912
+ this.fail(goal, run, "blocked", `The worker keeps getting stuck (${reason}), and I've already changed approach ${raised === 1 ? "once" : `${raised} times`}. Tell me how you'd like to proceed.`);
913
+ return;
914
+ }
915
+ transaction(db, () => {
916
+ store.updateRun(run.id, { state: "parked", stalls: run.stalls + 1, strategyPending: true });
917
+ store.setGoalState(goal.id, "recovering", {
918
+ detail: "Deciding how to continue after repeated stalls.",
919
+ });
920
+ store.addAttempt(goal.id, {
921
+ runId: run.id,
922
+ agent: run.agent,
923
+ tactic: "strategy_event",
924
+ reason,
925
+ });
926
+ recordEvent(db, clock, "strategy_needed", { goalId: goal.id, runId: run.id }, { reason });
927
+ });
928
+ this.deps.raiseGoalEvent({ goalId: goal.id, runId: run.id, detail: reason });
929
+ }
930
+ lastAttempt(goalId, tactic) {
931
+ return this.deps.store
932
+ .goal(goalId)
933
+ .attempts.filter((a) => a.tactic === tactic)
934
+ .at(-1);
935
+ }
936
+ // ---- Verification ------------------------------------------------------------------------
937
+ verify(goalId, runId) {
938
+ this.deps.store.setGoalState(goalId, "verifying");
939
+ this.track(this.runVerification(goalId, runId), "verification failed", { goalId });
940
+ }
941
+ async runVerification(goalId, runId) {
942
+ const { store, config, clock, db } = this.deps;
943
+ const goal = store.goal(goalId);
944
+ const run = store.run(runId);
945
+ const report = run.report;
946
+ if (report?.blockers.length) {
947
+ this.fail(goal, run, "blocked", `The worker needs something from you:\n${report.blockers.map((b) => `- ${b}`).join("\n")}`);
948
+ return;
949
+ }
950
+ const checks = [
951
+ ...goal.brief.checks.map((c) => ({ ...c, source: "brief" })),
952
+ ...acceptedSuggestions(report, goal.brief),
953
+ ];
954
+ if (checks.length === 0) {
955
+ this.complete(goal, run, [], report);
956
+ return;
957
+ }
958
+ const settings = config.get().verification;
959
+ const abort = new AbortController();
960
+ this.checkAborts.set(goalId, abort);
961
+ const startedAt = isoNow(clock);
962
+ const results = [];
963
+ try {
964
+ for (const [index, check] of checks.entries()) {
965
+ if (abort.signal.aborted)
966
+ break;
967
+ results.push(await runCheck(check, {
968
+ cwd: run.workdir,
969
+ timeoutMs: settings.checkTimeoutMs,
970
+ clock,
971
+ outputPath: join(run.transcriptDir, `check-${Date.parse(startedAt)}-${index + 1}.log`),
972
+ signal: abort.signal,
973
+ }));
974
+ }
975
+ }
976
+ finally {
977
+ this.checkAborts.delete(goalId);
978
+ }
979
+ if (this.stopping || store.goal(goalId).state !== "verifying")
980
+ return;
981
+ const passed = results.every((r) => r.passed);
982
+ // The verification record and the transition it causes are one write: after a crash the
983
+ // checks are either re-run from scratch or not at all, never recorded twice.
984
+ const record = (patch = {}) => {
985
+ store.addVerification({ goalId, runId, passed, results, startedAt, endedAt: isoNow(clock) });
986
+ store.updateRun(runId, { reportPending: false, ...patch });
987
+ };
988
+ if (passed) {
989
+ transaction(db, () => {
990
+ record();
991
+ this.complete(store.goal(goalId), store.run(runId), results, report);
992
+ });
993
+ return;
994
+ }
995
+ const evidence = failedChecksEvidence(results);
996
+ if (run.fixAttempts < settings.maxFixAttempts) {
997
+ transaction(db, () => {
998
+ record({ fixAttempts: run.fixAttempts + 1 });
999
+ recordEvent(db, clock, "checks_failed_resuming", { goalId, runId });
1000
+ store.setGoalState(goalId, "running");
1001
+ });
1002
+ this.resumeRun(store.run(runId), failedChecksPrompt(evidence));
1003
+ return;
1004
+ }
1005
+ transaction(db, () => {
1006
+ record();
1007
+ this.fail(goal, run, "failed", `My checks still fail after the worker tried to fix them:\n${evidence}`);
1008
+ });
1009
+ }
1010
+ complete(goal, run, results, report) {
1011
+ const verified = results.some((r) => r.source === "brief") && results.every((r) => r.passed);
1012
+ if (verified && this.deps.landing?.usesWorktree(goal.id)) {
1013
+ this.landWork(goal.id);
1014
+ return;
1015
+ }
1016
+ const base = verified
1017
+ ? verifiedMessage(goal, results, report)
1018
+ : unverifiedMessage(goal, report);
1019
+ const note = this.deps.landing?.outcomeNote(goal);
1020
+ this.finish(goal, run, {
1021
+ state: "completed",
1022
+ outcome: verified ? "verified" : "unverified",
1023
+ message: note ? `${base}\n${note}` : base,
1024
+ });
1025
+ }
1026
+ // ---- Landing -----------------------------------------------------------------------------
1027
+ /** Lands the verified work of a Goal that has its own worktree, then finishes the Goal. */
1028
+ landWork(goalId) {
1029
+ const run = this.deps.store.currentRun(goalId);
1030
+ if (!run)
1031
+ return;
1032
+ this.deps.store.setGoalState(goalId, "verifying", { detail: "Merging the finished work." });
1033
+ this.track(this.runLanding(goalId, run.id), "landing failed", { goalId });
1034
+ }
1035
+ async runLanding(goalId, runId) {
1036
+ const { store, landing } = this.deps;
1037
+ if (!landing)
1038
+ return;
1039
+ const result = await landing.land(store.goal(goalId), store.run(runId));
1040
+ if (this.stopping || result.kind === "aborted")
1041
+ return;
1042
+ const goal = store.goal(goalId);
1043
+ const run = store.run(runId);
1044
+ if (goal.state !== "verifying")
1045
+ return;
1046
+ switch (result.kind) {
1047
+ case "landed":
1048
+ case "held": {
1049
+ const results = store
1050
+ .verifications(goalId)
1051
+ .filter((v) => v.passed)
1052
+ .at(-1)?.results ?? [];
1053
+ this.finish(goal, run, {
1054
+ state: "completed",
1055
+ outcome: "verified",
1056
+ message: [verifiedMessage(goal, results, run.report), result.message]
1057
+ .filter(Boolean)
1058
+ .join("\n"),
1059
+ });
1060
+ return;
1061
+ }
1062
+ case "needs_worker":
1063
+ recordEvent(this.deps.db, this.deps.clock, "landing_needs_worker", { goalId, runId });
1064
+ this.resumeRun(run, result.prompt);
1065
+ return;
1066
+ case "waiting_for_user":
1067
+ store.updateRun(runId, { state: "parked" });
1068
+ store.setGoalState(goalId, "waiting_for_user", {
1069
+ detail: "Waiting for your answer before merging.",
1070
+ });
1071
+ return;
1072
+ case "blocked":
1073
+ this.fail(goal, run, "blocked", result.reason);
1074
+ return;
1075
+ }
1076
+ }
1077
+ /** The user answered the question a landing was waiting on: carry on landing. */
1078
+ onLandingAnswered(question) {
1079
+ const goalId = this.deps.landing?.questionGoal(question.id);
1080
+ if (!goalId || this.stopping)
1081
+ return;
1082
+ if (this.deps.store.findGoal(goalId)?.state === "waiting_for_user")
1083
+ this.landWork(goalId);
1084
+ }
1085
+ fail(goal, run, state, reason) {
1086
+ this.finish(goal, run, {
1087
+ state,
1088
+ detail: reason,
1089
+ message: state === "blocked" ? blockedMessage(goal, reason) : failedMessage(goal, reason),
1090
+ });
1091
+ }
1092
+ /** Ends a Goal with an outcome and tells the user once. */
1093
+ finish(goal, run, result) {
1094
+ const { db, store, questions, outbox, clock } = this.deps;
1095
+ const outcome = result.state === "completed" ? result.outcome : undefined;
1096
+ let handoff = false;
1097
+ transaction(db, () => {
1098
+ store.updateRun(run.id, {
1099
+ state: "ended",
1100
+ endReason: result.state,
1101
+ quotaBucket: null,
1102
+ strategyPending: false,
1103
+ });
1104
+ store.setGoalState(goal.id, result.state, {
1105
+ outcome,
1106
+ detail: result.state === "completed" ? null : result.detail.slice(0, 500),
1107
+ });
1108
+ questions.cancelForGoal(goal.id);
1109
+ recordEvent(db, clock, "goal_finished", { goalId: goal.id, runId: run.id }, {
1110
+ state: result.state,
1111
+ outcome,
1112
+ });
1113
+ const files = result.state === "completed" ? deliverableFiles(run.report) : undefined;
1114
+ const waitMs = this.deps.config.get().outcomes.coordinatorWaitMs;
1115
+ handoff = waitMs > 0;
1116
+ outbox.broadcast({
1117
+ kind: "outcome",
1118
+ text: result.message,
1119
+ goalId: goal.id,
1120
+ files,
1121
+ // With the Coordinator asked to speak first, this is only the fallback.
1122
+ holdUntilMs: handoff ? clock.now() + waitMs : undefined,
1123
+ // Per Run: a Goal merged again after being held back reports a new outcome.
1124
+ dedupeKey: `outcome:${goal.id}:${run.id}`,
1125
+ });
1126
+ });
1127
+ if (handoff) {
1128
+ this.deps.raiseGoalOutcome({
1129
+ goalId: goal.id,
1130
+ runId: run.id,
1131
+ state: result.state,
1132
+ outcome,
1133
+ detail: result.state === "completed" ? undefined : result.detail,
1134
+ summary: run.report?.summary,
1135
+ deliverables: (deliverableFiles(run.report) ?? []).map((f) => f.path),
1136
+ standardMessage: result.message,
1137
+ });
1138
+ }
1139
+ this.deps.log.info("goal finished", { goalId: goal.id, state: result.state, outcome });
1140
+ }
1141
+ // ---- Helpers -----------------------------------------------------------------------------
1142
+ haltWork(goalId, run) {
1143
+ this.wakeTimers.get(goalId)?.cancel();
1144
+ this.wakeTimers.delete(goalId);
1145
+ this.checkAborts.get(goalId)?.abort();
1146
+ this.deps.landing?.abort(goalId);
1147
+ const handle = run ? this.live.get(run.id) : undefined;
1148
+ if (!run || !handle)
1149
+ return;
1150
+ this.interrupted.add(run.id);
1151
+ handle
1152
+ .interrupt()
1153
+ .catch((err) => this.deps.log.warn("interrupt failed", { goalId, error: err }));
1154
+ }
1155
+ /**
1156
+ * The agent for a new Goal in a Project, deterministically (see `selectAgent`): with quota
1157
+ * balancing, one with headroom (its own quota read, below `quota.headroomPercent`), the one
1158
+ * used last for the Project when several have it, otherwise the one expected back first. Only
1159
+ * the agents the user enabled are ever considered.
1160
+ */
1161
+ async chooseAgent(projectPath) {
1162
+ const path = canonicalPath(projectPath);
1163
+ const usable = this.usableAgents();
1164
+ const balance = this.deps.config.get().agents.balanceByQuota && usable.length > 1;
1165
+ const infos = await Promise.all(usable.map((agent) => balance ? this.deps.quota.headroomInfo(agent) : this.deps.quota.headroomKnown(agent)));
1166
+ return this.selectFrom(usable, infos, path);
1167
+ }
1168
+ /** The same choice from what Preston already knows, without reading quota (it cannot wait). */
1169
+ chooseAgentNow(path) {
1170
+ const usable = this.usableAgents();
1171
+ return this.selectFrom(usable, usable.map((agent) => this.deps.quota.headroomKnown(agent)), path);
1172
+ }
1173
+ selectFrom(usable, infos, path) {
1174
+ return selectAgent(usable.map((agent, i) => ({
1175
+ agent,
1176
+ label: agentLabel(agent),
1177
+ headroom: infos[i]?.ok ?? false,
1178
+ resetsAt: infos[i]?.resetsAt,
1179
+ })), {
1180
+ balance: this.deps.config.get().agents.balanceByQuota,
1181
+ lastUsed: this.deps.store.lastAgentForProject(path),
1182
+ });
1183
+ }
1184
+ usableAgents() {
1185
+ const usable = this.deps.config.get().agents.enabled.filter((kind) => this.deps.adapter(kind));
1186
+ if (!usable.length) {
1187
+ throw new ToolError("No coding agent is set up yet, so Preston cannot start work.");
1188
+ }
1189
+ return usable;
1190
+ }
1191
+ /** A Goal's agent when it must start again: the one that already worked on it. */
1192
+ pickAgentOr(goal) {
1193
+ const previous = this.deps.store.runsForGoal(goal.id).at(-1)?.agent;
1194
+ if (previous)
1195
+ return previous;
1196
+ const chosen = goal.agentChoice?.agent;
1197
+ return chosen && this.deps.adapter(chosen)
1198
+ ? chosen
1199
+ : this.chooseAgentNow(goal.projectPath).agent;
1200
+ }
1201
+ requireGoal(goalId) {
1202
+ const goal = this.deps.store.findGoal(goalId);
1203
+ if (!goal)
1204
+ throw new ToolError(`There is no goal ${goalId}.`);
1205
+ return goal;
1206
+ }
1207
+ }
1208
+ function withExtra(base, extra) {
1209
+ return extra ? `${base}\n\n${extra}` : base;
1210
+ }
1211
+ function isTerminal(state) {
1212
+ return TERMINAL_GOAL_STATES.includes(state);
1213
+ }
1214
+ function isTurnEnd(event) {
1215
+ return (event.type === "completed" ||
1216
+ event.type === "failed" ||
1217
+ event.type === "quota_blocked" ||
1218
+ event.type === "auth_error");
1219
+ }
1220
+ /** Worker-suggested commands Preston also runs, next to the Brief's checks. */
1221
+ /** The files a Worker handed in for the user that exist, once each, named as the user will see them. */
1222
+ function deliverableFiles(report) {
1223
+ const files = [];
1224
+ const seen = new Set();
1225
+ for (const raw of report?.deliverables ?? []) {
1226
+ const path = resolve(raw);
1227
+ try {
1228
+ if (seen.has(path) || !statSync(path).isFile())
1229
+ continue;
1230
+ }
1231
+ catch {
1232
+ continue;
1233
+ }
1234
+ seen.add(path);
1235
+ files.push({ path, name: basename(path) });
1236
+ }
1237
+ return files.length ? files : undefined;
1238
+ }
1239
+ function acceptedSuggestions(report, brief) {
1240
+ const known = new Set(brief.checks.map((c) => c.command.trim()));
1241
+ const accepted = [];
1242
+ for (const raw of report?.suggestedVerificationCommands ?? []) {
1243
+ const command = raw.trim();
1244
+ if (!command || known.has(command))
1245
+ continue;
1246
+ known.add(command);
1247
+ accepted.push({ name: `suggested: ${command}`, command, source: "suggested" });
1248
+ if (accepted.length >= MAX_SUGGESTED_CHECKS)
1249
+ break;
1250
+ }
1251
+ return accepted;
1252
+ }
1253
+ //# sourceMappingURL=engine.js.map