@narumitw/pi-goal 0.52.1 → 0.52.2

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.
package/dist/index.ts ADDED
@@ -0,0 +1,1585 @@
1
+ // @generated by scripts/build-runtime.mjs; do not edit.
2
+ // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
+ import {
4
+ GOAL_BLOCKED_TOOL,
5
+ GOAL_COMPLETE_TOOL,
6
+ GOAL_WAIT_TOOL,
7
+ GoalRuntime,
8
+ MAX_GOAL_ID_LENGTH,
9
+ MAX_GOAL_WAIT_DELAY_MS,
10
+ MAX_GOAL_WAIT_REASON_LENGTH,
11
+ MIN_GOAL_WAIT_DELAY_MS,
12
+ STATUS_KEY,
13
+ abortCurrentTurn,
14
+ blocksStaleGoalToolCalls,
15
+ buildGoalPrompt,
16
+ buildGoalSystemPrompt,
17
+ buildObjectiveUpdatedPrompt,
18
+ buildResumePrompt,
19
+ buildWaitingResumePrompt,
20
+ completeGoalArguments,
21
+ createGoal,
22
+ createGoalWait,
23
+ editedGoalStatus,
24
+ formatBudget,
25
+ formatStatus,
26
+ goalIdRejectionReason,
27
+ goalSummary,
28
+ hasAssistantToolCall,
29
+ incrementGoal,
30
+ isContradictoryCompletionSummary,
31
+ isRemovedQueueCommand,
32
+ isResumableGoalStatus,
33
+ isTerminalGoalStatus,
34
+ loadGoalStateFromSession,
35
+ nextGoalInstance,
36
+ parseCommand,
37
+ queueGoalSafetyReset,
38
+ resetGoalSafetyEpoch,
39
+ resolveGoalWaitDelay,
40
+ stoppedStatusLabel,
41
+ transitionGoal,
42
+ validateObjective
43
+ } from "./chunks/chunk-ODVXYZXS.js";
44
+ import {
45
+ DEFAULT_GOAL_SETTINGS,
46
+ currentTokenTotal,
47
+ findFinalAssistantMessage,
48
+ formatError,
49
+ formatTokenCount,
50
+ isGoalContextOverflow,
51
+ isRetryableGoalInterruption,
52
+ isUsageLimitedGoalInterruption,
53
+ notifyTerminal,
54
+ readGoalSettings,
55
+ safeGoalMenuText,
56
+ safeTerminalText,
57
+ truncateNotification
58
+ } from "./chunks/chunk-UA7LMS63.js";
59
+
60
+ // src/command-registration.ts
61
+ function registerGoalCommand(pi, runtime, commands, options = {}) {
62
+ const loadGoalManager = cachedModuleLoader(
63
+ options.loadGoalManager ?? (() => import("./chunks/menu-YILEIJE6.js"))
64
+ );
65
+ const loadGoalSettings = cachedModuleLoader(
66
+ options.loadGoalSettings ?? (() => import("./chunks/settings-ui-HMSJEEZN.js"))
67
+ );
68
+ pi.registerCommand("goal", {
69
+ description: "Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>",
70
+ getArgumentCompletions: (prefix) => completeGoalArguments(prefix),
71
+ handler: async (args, ctx) => {
72
+ if (runtime.hasLegacyQueueInterface() && isRemovedQueueCommand(args)) {
73
+ reportRemovedQueueCommand(ctx, runtime);
74
+ return;
75
+ }
76
+ const result = parseCommand(args);
77
+ if (typeof result === "string") {
78
+ reportCommandError(result, ctx);
79
+ return;
80
+ }
81
+ if (result.kind === "show" && args.trim() === "") {
82
+ const menuIsCurrent = captureMenuOwnership(runtime);
83
+ let managerModule;
84
+ try {
85
+ managerModule = await loadGoalManager();
86
+ } catch (error) {
87
+ if (!menuIsCurrent()) return;
88
+ throw error;
89
+ }
90
+ if (!menuIsCurrent()) return;
91
+ const { showGoalManager } = managerModule;
92
+ await showGoalManager(runtime, commands, ctx, async (menuCtx, target) => {
93
+ const settingsAreCurrent = captureMenuOwnership(runtime);
94
+ let settingsModule;
95
+ try {
96
+ settingsModule = await loadGoalSettings();
97
+ } catch (error) {
98
+ if (!settingsAreCurrent()) return;
99
+ throw error;
100
+ }
101
+ if (!settingsAreCurrent()) return;
102
+ const { showGoalSettings } = settingsModule;
103
+ await showGoalSettings(runtime, menuCtx, {
104
+ settingsPath: options.settingsPath,
105
+ initialScreen: target
106
+ });
107
+ });
108
+ return;
109
+ }
110
+ switch (result.kind) {
111
+ case "show":
112
+ commands.showGoal(ctx);
113
+ return;
114
+ case "pause":
115
+ commands.pauseGoal(ctx);
116
+ return;
117
+ case "resume":
118
+ await commands.resumeGoal(ctx);
119
+ return;
120
+ case "clear":
121
+ commands.clearGoal(ctx);
122
+ return;
123
+ case "edit":
124
+ await commands.editGoal(result.objective ?? "", result.tokenBudget, ctx);
125
+ return;
126
+ case "start":
127
+ await commands.startGoal(result.objective ?? "", result.tokenBudget, ctx);
128
+ return;
129
+ }
130
+ }
131
+ });
132
+ }
133
+ function reportCommandError(message, ctx) {
134
+ const safeMessage = safeTerminalText(message);
135
+ if (ctx.mode === "print" || ctx.mode === "json") throw new Error(safeMessage);
136
+ notifyTerminal(ctx.ui, safeMessage, "warning");
137
+ }
138
+ function reportRemovedQueueCommand(ctx, runtime) {
139
+ const message = runtime.activeGoal ? "Ordered goal queue has been removed. Use /goal edit to reprioritize the active objective instead." : "Ordered goal queue has been removed. Start /goal <objectives> to continue with one merged objective, or use /goal clear to discard the old queue state.";
140
+ if (ctx.mode === "print" || ctx.mode === "json") throw new Error(message);
141
+ notifyTerminal(ctx.ui, message, "warning");
142
+ }
143
+ function captureMenuOwnership(runtime) {
144
+ const generation = runtime.menuGeneration;
145
+ const controller = runtime.menuController;
146
+ return () => runtime.menuGeneration === generation && runtime.menuController === controller && !controller.signal.aborted;
147
+ }
148
+ function cachedModuleLoader(load) {
149
+ let pending;
150
+ return () => {
151
+ if (!pending) {
152
+ pending = load().catch((error) => {
153
+ pending = void 0;
154
+ throw error;
155
+ });
156
+ }
157
+ return pending;
158
+ };
159
+ }
160
+
161
+ // src/commands.ts
162
+ var GoalCommandController = class {
163
+ runtime;
164
+ constructor(runtime) {
165
+ this.runtime = runtime;
166
+ }
167
+ async startGoal(objective, tokenBudget, ctx, onActivated, isActivationCurrent, isRequestCurrent) {
168
+ if (isRequestCurrent && !isRequestCurrent()) return;
169
+ const validationError = validateObjective(objective);
170
+ if (validationError) {
171
+ notifyTerminal(ctx.ui, validationError, "warning");
172
+ return;
173
+ }
174
+ const existingGoal = this.runtime.activeGoal?.status !== "complete" ? this.runtime.activeGoal : void 0;
175
+ const legacyQueueBeforeActivation = existingGoal ? void 0 : this.runtime.legacyQueueState ? structuredClone(this.runtime.legacyQueueState) : void 0;
176
+ if (existingGoal) {
177
+ const shouldReplace = await ctx.ui.confirm(
178
+ "Replace goal?",
179
+ `Current goal: ${safeGoalMenuText(existingGoal.text, 4e3)}
180
+
181
+ New goal: ${safeGoalMenuText(objective, 4e3)}`
182
+ );
183
+ if (!shouldReplace) {
184
+ notifyTerminal(ctx.ui, `Goal kept: ${existingGoal.text}`, "info");
185
+ return;
186
+ }
187
+ if (isRequestCurrent && !isRequestCurrent()) return;
188
+ if (this.runtime.activeGoal?.id !== existingGoal.id) {
189
+ notifyTerminal(
190
+ ctx.ui,
191
+ "The active goal changed while confirmation was open. Try again.",
192
+ "warning"
193
+ );
194
+ return;
195
+ }
196
+ }
197
+ if (isRequestCurrent && !isRequestCurrent()) return;
198
+ const goalToolVisibilityBeforeActivation = this.runtime.toolPolicy.snapshot();
199
+ try {
200
+ this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
201
+ } catch (error) {
202
+ notifyTerminal(ctx.ui, `Cannot start /goal: ${formatError(error)}`, "error");
203
+ if (existingGoal?.status === "active") this.runtime.pauseGoalForUnavailableTools(ctx);
204
+ return;
205
+ }
206
+ this.runtime.clearGoalWaitTimer();
207
+ this.runtime.cancelContinuationWork();
208
+ this.runtime.clearGoalRecovery();
209
+ this.runtime.clearBudgetWrapUp();
210
+ this.runtime.clearStaleGoalToolCallBlock();
211
+ if (!legacyQueueBeforeActivation) this.runtime.legacyQueueState = void 0;
212
+ this.runtime.activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));
213
+ const startedGoal = this.runtime.activeGoal;
214
+ onActivated?.(startedGoal);
215
+ if (!legacyQueueBeforeActivation) this.runtime.persistGoal(startedGoal);
216
+ if (this.runtime.activeGoal?.id !== startedGoal.id || this.runtime.activeGoal.status !== "active") {
217
+ return;
218
+ }
219
+ this.runtime.updateStatus(ctx, startedGoal);
220
+ const sent = await this.runtime.sendOwnedGoalPrompt(
221
+ ctx,
222
+ startedGoal.id,
223
+ buildGoalPrompt(startedGoal),
224
+ true,
225
+ () => (isRequestCurrent?.() ?? true) && (isActivationCurrent?.(startedGoal) ?? true)
226
+ );
227
+ if (sent && legacyQueueBeforeActivation && this.runtime.activeGoal?.id === startedGoal.id && this.runtime.activeGoal.status === "active") {
228
+ this.runtime.legacyQueueState = void 0;
229
+ this.runtime.persistGoal(startedGoal);
230
+ }
231
+ if (isActivationCurrent && !isActivationCurrent(startedGoal)) return;
232
+ if (!sent) {
233
+ let rolledBackStartedGoal = false;
234
+ if (this.runtime.activeGoal?.id === startedGoal.id) {
235
+ rolledBackStartedGoal = true;
236
+ if (existingGoal) {
237
+ this.runtime.recordGoalUsage(existingGoal, ctx);
238
+ if (existingGoal.status === "active" && existingGoal.waiting) {
239
+ this.runtime.activeGoal = existingGoal;
240
+ this.runtime.clearStaleGoalToolCallBlock();
241
+ this.runtime.persistGoal(existingGoal);
242
+ this.runtime.updateStatus(ctx, existingGoal);
243
+ this.runtime.restoreGoalWaitTimer(ctx);
244
+ } else if (existingGoal.status === "active") {
245
+ this.runtime.stopActiveGoal(ctx, {
246
+ kind: "activation_rollback",
247
+ expectedGoalId: startedGoal.id,
248
+ restoreGoal: existingGoal,
249
+ abortTurn: true
250
+ });
251
+ } else {
252
+ this.runtime.activeGoal = existingGoal;
253
+ if (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {
254
+ this.runtime.blockStaleGoalToolCalls();
255
+ } else {
256
+ this.runtime.clearStaleGoalToolCallBlock();
257
+ }
258
+ this.runtime.persistGoal(this.runtime.activeGoal);
259
+ this.runtime.updateStatus(ctx, this.runtime.activeGoal);
260
+ }
261
+ } else if (legacyQueueBeforeActivation) {
262
+ this.runtime.activeGoal = void 0;
263
+ this.runtime.legacyQueueState = legacyQueueBeforeActivation;
264
+ this.runtime.cancelContinuationWork();
265
+ this.runtime.clearGoalRecovery();
266
+ this.runtime.clearBudgetWrapUp();
267
+ this.runtime.clearStaleGoalToolCallBlock();
268
+ ctx.ui.setStatus(STATUS_KEY, void 0);
269
+ } else {
270
+ this.runtime.clearActiveGoal(ctx);
271
+ }
272
+ }
273
+ if (rolledBackStartedGoal) {
274
+ this.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);
275
+ }
276
+ return;
277
+ }
278
+ if (this.runtime.activeGoal?.id !== startedGoal.id || this.runtime.activeGoal.status !== "active") {
279
+ return;
280
+ }
281
+ const automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;
282
+ notifyTerminal(
283
+ ctx.ui,
284
+ `${existingGoal ? "Goal replaced" : "Goal started"}: ${objective}. ${startedGoal.tokenBudget === void 0 ? "" : `Token budget: ${formatTokenCount(startedGoal.tokenBudget)} cumulative; the final model call may exceed it. `}${automaticLimit === null ? "Automatic work is Unlimited; tool loops may consume substantial tokens and provider cost. Open /goal to monitor." : `Automatic work pauses after ${automaticLimit} responses; open /goal to monitor progress.`}`,
285
+ automaticLimit === null ? "warning" : "info"
286
+ );
287
+ }
288
+ pauseGoal(ctx) {
289
+ if (!this.runtime.activeGoal) {
290
+ notifyTerminal(ctx.ui, "No active goal.", "info");
291
+ return;
292
+ }
293
+ if (this.runtime.activeGoal.status !== "active") {
294
+ notifyTerminal(
295
+ ctx.ui,
296
+ `Goal is ${this.runtime.activeGoal.status}; only active goals can be paused.`,
297
+ "warning"
298
+ );
299
+ return;
300
+ }
301
+ const stoppedGoal = this.runtime.stopActiveGoal(ctx, {
302
+ kind: "explicit_pause",
303
+ expectedGoalId: this.runtime.activeGoal.id
304
+ });
305
+ if (stoppedGoal) notifyTerminal(ctx.ui, `Goal paused: ${stoppedGoal.text}`, "info");
306
+ }
307
+ async resumeGoal(ctx) {
308
+ if (!this.runtime.activeGoal) {
309
+ notifyTerminal(ctx.ui, "No active goal.", "info");
310
+ return;
311
+ }
312
+ if (this.runtime.activeGoal.status === "active" && this.runtime.activeGoal.waiting) {
313
+ await this.resumeWaitingGoal(ctx);
314
+ return;
315
+ }
316
+ if (!isResumableGoalStatus(this.runtime.activeGoal.status)) {
317
+ notifyTerminal(
318
+ ctx.ui,
319
+ `Goal is ${this.runtime.activeGoal.status}; only paused, blocked, usage-limited, or budget-limited goals can be resumed.`,
320
+ "warning"
321
+ );
322
+ return;
323
+ }
324
+ if (this.runtime.activeGoal.tokenBudget !== void 0 && this.runtime.activeGoal.tokensUsed >= this.runtime.activeGoal.tokenBudget) {
325
+ notifyTerminal(
326
+ ctx.ui,
327
+ `Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`,
328
+ "warning"
329
+ );
330
+ return;
331
+ }
332
+ const goalToolVisibilityBeforeActivation = this.runtime.toolPolicy.snapshot();
333
+ try {
334
+ this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
335
+ } catch (error) {
336
+ notifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, "error");
337
+ return;
338
+ }
339
+ const stoppedGoal = this.runtime.activeGoal;
340
+ const stoppedStatus = stoppedGoal.status;
341
+ this.runtime.cancelContinuationWork();
342
+ this.runtime.clearGoalRecovery();
343
+ this.runtime.clearBudgetWrapUp();
344
+ this.runtime.clearStaleGoalToolCallBlock();
345
+ this.runtime.activeGoal = queueGoalSafetyReset(
346
+ transitionGoal(nextGoalInstance(this.runtime.activeGoal), "active")
347
+ );
348
+ this.runtime.persistGoal(this.runtime.activeGoal);
349
+ this.runtime.updateStatus(ctx, this.runtime.activeGoal);
350
+ if (this.runtime.activeGoal.status !== "active") {
351
+ notifyTerminal(
352
+ ctx.ui,
353
+ `Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`,
354
+ "warning"
355
+ );
356
+ return;
357
+ }
358
+ const resumedGoal = this.runtime.activeGoal;
359
+ const sent = await this.runtime.sendOwnedGoalPrompt(
360
+ ctx,
361
+ resumedGoal.id,
362
+ buildResumePrompt(resumedGoal, stoppedStatus)
363
+ );
364
+ if (!sent) {
365
+ if (this.runtime.activeGoal?.id === resumedGoal.id && this.runtime.activeGoal.status === "active") {
366
+ this.runtime.activeGoal = stoppedGoal;
367
+ this.runtime.persistGoal(this.runtime.activeGoal);
368
+ this.runtime.updateStatus(ctx, this.runtime.activeGoal);
369
+ if (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {
370
+ this.runtime.blockStaleGoalToolCalls();
371
+ }
372
+ this.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);
373
+ }
374
+ return;
375
+ }
376
+ const automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;
377
+ notifyTerminal(
378
+ ctx.ui,
379
+ `Goal resumed from ${stoppedStatusLabel(stoppedStatus)}: ${resumedGoal.text}. ${automaticLimit === null ? "Automatic work remains Unlimited; goal progress and cumulative usage are preserved." : `The automatic-work counter will reset to 0 of ${automaticLimit} when the resumed prompt starts; goal progress and cumulative usage are preserved.`}`,
380
+ automaticLimit === null ? "warning" : "info"
381
+ );
382
+ }
383
+ async resumeWaitingGoal(ctx) {
384
+ const waitingGoal = this.runtime.activeGoal;
385
+ const waiting = waitingGoal?.waiting;
386
+ if (waitingGoal?.status !== "active" || !waiting) return;
387
+ try {
388
+ this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
389
+ } catch (error) {
390
+ notifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, "error");
391
+ return;
392
+ }
393
+ if (!this.runtime.clearGoalWait(ctx, waitingGoal.id)) return;
394
+ const resumedGoal = this.runtime.activeGoal;
395
+ if (!resumedGoal || resumedGoal.id !== waitingGoal.id || resumedGoal.status !== "active")
396
+ return;
397
+ const sent = await this.runtime.sendOwnedGoalPrompt(
398
+ ctx,
399
+ resumedGoal.id,
400
+ buildWaitingResumePrompt(resumedGoal, waiting.reason),
401
+ false
402
+ );
403
+ if (!sent) {
404
+ if (this.runtime.activeGoal?.id === waitingGoal.id) {
405
+ this.runtime.enterGoalWait(ctx, waitingGoal.id, waiting);
406
+ }
407
+ return;
408
+ }
409
+ notifyTerminal(ctx.ui, `Goal resumed from waiting: ${waitingGoal.text}`, "info");
410
+ }
411
+ clearGoal(ctx) {
412
+ if (!this.runtime.activeGoal) {
413
+ const hadLegacyQueue = this.runtime.legacyQueueState !== void 0;
414
+ this.runtime.legacyQueueState = void 0;
415
+ this.runtime.cancelContinuationWork();
416
+ this.runtime.clearGoalRecovery();
417
+ this.runtime.clearBudgetWrapUp();
418
+ this.runtime.clearStaleGoalToolCallBlock();
419
+ this.runtime.clearPersistedGoal(ctx.cwd);
420
+ ctx.ui.setStatus(STATUS_KEY, void 0);
421
+ notifyTerminal(
422
+ ctx.ui,
423
+ hadLegacyQueue ? "Removed legacy ordered goal queue state." : "No active goal.",
424
+ hadLegacyQueue ? "warning" : "info"
425
+ );
426
+ return;
427
+ }
428
+ const stoppedGoal = this.runtime.activeGoal.text;
429
+ this.runtime.clearActiveGoal(ctx);
430
+ notifyTerminal(ctx.ui, `Goal cleared: ${stoppedGoal}`, "warning");
431
+ }
432
+ async editGoal(objective, tokenBudget, ctx) {
433
+ const validationError = validateObjective(objective);
434
+ if (validationError) {
435
+ notifyTerminal(ctx.ui, validationError, "warning");
436
+ return;
437
+ }
438
+ if (!this.runtime.activeGoal) {
439
+ notifyTerminal(ctx.ui, "No active goal. Use /goal <objective> to start one.", "warning");
440
+ return;
441
+ }
442
+ this.runtime.recordGoalUsage(this.runtime.activeGoal, ctx);
443
+ const previousGoal = { ...this.runtime.activeGoal };
444
+ this.runtime.clearGoalWaitTimer();
445
+ this.runtime.cancelContinuationWork();
446
+ this.runtime.clearGoalRecovery();
447
+ this.runtime.clearBudgetWrapUp();
448
+ const previousStatus = this.runtime.activeGoal.status;
449
+ const rotatedGoal = nextGoalInstance(this.runtime.activeGoal);
450
+ const transitionedGoal = transitionGoal(
451
+ {
452
+ ...rotatedGoal,
453
+ text: objective,
454
+ tokenBudget: tokenBudget ?? this.runtime.activeGoal.tokenBudget,
455
+ waiting: void 0
456
+ },
457
+ editedGoalStatus(previousStatus)
458
+ );
459
+ const nextGoal = transitionedGoal.status === "active" ? queueGoalSafetyReset(transitionedGoal) : transitionedGoal;
460
+ const goalToolVisibilityBeforeActivation = nextGoal.status === "active" ? this.runtime.toolPolicy.snapshot() : void 0;
461
+ if (nextGoal.status === "active") {
462
+ try {
463
+ this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
464
+ } catch (error) {
465
+ notifyTerminal(ctx.ui, `Cannot reactivate /goal: ${formatError(error)}`, "error");
466
+ if (this.runtime.activeGoal?.status === "active") {
467
+ this.runtime.pauseGoalForUnavailableTools(ctx);
468
+ }
469
+ return;
470
+ }
471
+ }
472
+ this.runtime.activeGoal = nextGoal;
473
+ this.runtime.persistGoal(this.runtime.activeGoal);
474
+ this.runtime.updateStatus(ctx, this.runtime.activeGoal);
475
+ const editedGoal = this.runtime.activeGoal;
476
+ if (!editedGoal) return;
477
+ if (editedGoal.status === "active") {
478
+ this.runtime.clearStaleGoalToolCallBlock();
479
+ const sent = await this.runtime.sendOwnedGoalPrompt(
480
+ ctx,
481
+ editedGoal.id,
482
+ buildObjectiveUpdatedPrompt(editedGoal)
483
+ );
484
+ if (!sent) {
485
+ if (this.runtime.activeGoal?.id === editedGoal.id) {
486
+ if (previousStatus === "active" && previousGoal.waiting) {
487
+ this.runtime.activeGoal = previousGoal;
488
+ this.runtime.clearStaleGoalToolCallBlock();
489
+ this.runtime.persistGoal(previousGoal);
490
+ this.runtime.updateStatus(ctx, previousGoal);
491
+ this.runtime.restoreGoalWaitTimer(ctx);
492
+ } else if (previousStatus === "active") {
493
+ this.runtime.stopActiveGoal(ctx, {
494
+ kind: "activation_rollback",
495
+ expectedGoalId: editedGoal.id,
496
+ restoreGoal: previousGoal,
497
+ abortTurn: true
498
+ });
499
+ } else {
500
+ this.runtime.activeGoal = previousGoal;
501
+ if (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {
502
+ this.runtime.blockStaleGoalToolCalls();
503
+ } else {
504
+ this.runtime.clearStaleGoalToolCallBlock();
505
+ }
506
+ this.runtime.persistGoal(this.runtime.activeGoal);
507
+ this.runtime.updateStatus(ctx, this.runtime.activeGoal);
508
+ }
509
+ if (goalToolVisibilityBeforeActivation) {
510
+ this.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);
511
+ }
512
+ }
513
+ return;
514
+ }
515
+ } else if (blocksStaleGoalToolCalls(editedGoal.status)) {
516
+ this.runtime.blockStaleGoalToolCalls();
517
+ } else {
518
+ this.runtime.clearStaleGoalToolCallBlock();
519
+ }
520
+ notifyTerminal(ctx.ui, `Goal updated: ${objective}`, "info");
521
+ }
522
+ showGoal(ctx) {
523
+ if (!this.runtime.activeGoal) {
524
+ ctx.ui.setStatus(STATUS_KEY, void 0);
525
+ this.reportGoalStatus(ctx, this.emptyGoalMessage());
526
+ return;
527
+ }
528
+ this.runtime.recordGoalUsage(this.runtime.activeGoal, ctx);
529
+ this.runtime.persistGoal(this.runtime.activeGoal);
530
+ this.runtime.updateStatus(ctx, this.runtime.activeGoal);
531
+ this.reportGoalStatus(
532
+ ctx,
533
+ goalSummary(this.runtime.activeGoal, this.runtime.settings.continuationLimits.automaticTurns)
534
+ );
535
+ }
536
+ emptyGoalMessage() {
537
+ const legacy = this.runtime.legacyQueueState;
538
+ if (!legacy) return "Usage: /goal <objective>\nNo goal is currently set.";
539
+ return [
540
+ "Ordered goal queue has been removed.",
541
+ `Legacy queue state with ${legacy.retainedGoals} retained ${legacy.retainedGoals === 1 ? "goal" : "goals"} will not run automatically.`,
542
+ "Use /goal edit to reprioritize an active objective, start /goal <objectives>, or use /goal clear to discard the old queue state.",
543
+ 'Example objective: "task b is complete; do task a next, then task c and task d."'
544
+ ].join("\n");
545
+ }
546
+ reportGoalStatus(ctx, message) {
547
+ if (ctx.mode === "print" || ctx.mode === "json") {
548
+ throw new Error(
549
+ `/goal status is unavailable in ${ctx.mode} mode because Pi does not expose an extension-command output channel. Use TUI or RPC mode.`
550
+ );
551
+ }
552
+ notifyTerminal(ctx.ui, message, "info");
553
+ }
554
+ };
555
+
556
+ // src/lifecycle.ts
557
+ var REMOVED_QUEUE_SETTING_WARNING = "Ordered goal queue has been removed. Use /goal edit to reprioritize an active objective, or start /goal <objectives> if no active goal exists.";
558
+ var REMOVED_PERSISTED_QUEUE_WARNING = "Ordered goal queue has been removed. Start /goal <objectives> to continue with one merged objective, or use /goal clear to discard the old queue state.";
559
+ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
560
+ pi.on("session_start", async (_event, ctx) => {
561
+ runtime.replaceMenuSession();
562
+ runtime.clearCompletionStatusTimer();
563
+ runtime.clearContinuationTracking();
564
+ runtime.clearGoalWaitTimer();
565
+ runtime.clearPendingGoalPrompts();
566
+ runtime.clearAgentRun();
567
+ runtime.guardAbortGoalId = void 0;
568
+ runtime.clearGoalRecovery();
569
+ runtime.clearBudgetWrapUp();
570
+ runtime.clearStaleGoalToolCallBlock();
571
+ runtime.legacyQueueState = void 0;
572
+ runtime.legacyExperimentalGoalsSetting = false;
573
+ runtime.clearTerminalDetails();
574
+ const previousToolVisibility = runtime.settings.toolVisibility;
575
+ const settingsResult = readGoalSettings(options.settingsPath);
576
+ runtime.settings = settingsResult.kind === "loaded" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;
577
+ runtime.settingsLoadIssue = settingsResult.kind === "invalid" ? settingsResult : void 0;
578
+ if (settingsResult.kind === "invalid") {
579
+ notifyTerminal(
580
+ ctx.ui,
581
+ `pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`,
582
+ "warning"
583
+ );
584
+ }
585
+ runtime.legacyExperimentalGoalsSetting = settingsResult.kind !== "invalid" && settingsResult.legacyExperimentalGoals;
586
+ try {
587
+ runtime.toolPolicy.prepareSessionStart(
588
+ runtime.settings.toolVisibility,
589
+ previousToolVisibility
590
+ );
591
+ } catch (error) {
592
+ notifyTerminal(
593
+ ctx.ui,
594
+ `Could not restore always-visible goal tools: ${formatError(error)}`,
595
+ "error"
596
+ );
597
+ }
598
+ const loaded = loadGoalStateFromSession(ctx);
599
+ runtime.activeGoal = loaded.goal;
600
+ runtime.legacyQueueState = loaded.legacyQueueState;
601
+ runController.bindSession(ctx);
602
+ if (runtime.legacyQueueState) {
603
+ runtime.toolPolicy.reconcileRestoredState(runtime.settings.toolVisibility, false);
604
+ ctx.ui.setStatus(STATUS_KEY, void 0);
605
+ notifyTerminal(ctx.ui, REMOVED_PERSISTED_QUEUE_WARNING, "warning");
606
+ return;
607
+ }
608
+ if (runtime.legacyExperimentalGoalsSetting) {
609
+ notifyTerminal(ctx.ui, REMOVED_QUEUE_SETTING_WARNING, "warning");
610
+ }
611
+ if (runtime.activeGoal) {
612
+ if (runtime.activeGoal.status === "active" && runtime.activeGoal.safetyResetPending) {
613
+ runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
614
+ }
615
+ if (runtime.activeGoal.status === "active") {
616
+ runtime.recordGoalUsage(runtime.activeGoal, ctx);
617
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
618
+ if (runtime.enforceAutomaticTurnLimit(ctx, false) || runtime.enforceNoProgressLimit(ctx))
619
+ return;
620
+ }
621
+ runtime.toolPolicy.reconcileRestoredState(runtime.settings.toolVisibility, true);
622
+ if (runtime.activeGoal.status === "active" && !runtime.toolPolicy.toolsAvailable()) {
623
+ runtime.pauseGoalForUnavailableTools(ctx, false);
624
+ return;
625
+ }
626
+ runtime.persistGoal(runtime.activeGoal);
627
+ runtime.updateStatus(ctx, runtime.activeGoal);
628
+ runtime.restoreGoalWaitTimer(ctx);
629
+ } else {
630
+ runtime.toolPolicy.reconcileRestoredState(runtime.settings.toolVisibility, false);
631
+ ctx.ui.setStatus(STATUS_KEY, void 0);
632
+ }
633
+ });
634
+ pi.on("session_shutdown", (_event, ctx) => {
635
+ runController.unbindSession();
636
+ runtime.closeMenuSession();
637
+ runtime.clearGoalWaitTimer();
638
+ if (runtime.activeGoal) {
639
+ if (runtime.activeGoal.status === "active") {
640
+ runtime.recordGoalUsage(runtime.activeGoal, ctx, false);
641
+ }
642
+ runtime.persistGoal(runtime.activeGoal);
643
+ }
644
+ runtime.clearContinuationTracking();
645
+ runtime.clearPendingGoalPrompts();
646
+ runtime.clearAgentRun();
647
+ runtime.guardAbortGoalId = void 0;
648
+ runtime.clearGoalRecovery();
649
+ runtime.clearBudgetWrapUp();
650
+ runtime.clearStaleGoalToolCallBlock();
651
+ runtime.activeGoal = void 0;
652
+ runtime.legacyQueueState = void 0;
653
+ runtime.legacyExperimentalGoalsSetting = false;
654
+ ctx.ui.setStatus(STATUS_KEY, void 0);
655
+ runtime.clearCompletionStatusTimer();
656
+ runtime.clearTerminalDetails();
657
+ });
658
+ pi.on("session_before_compact", (event, ctx) => {
659
+ if (runtime.activeGoal?.status === "budget_limited") {
660
+ if (event.willRetry === true) return { cancel: true };
661
+ return;
662
+ }
663
+ if (runtime.activeGoal?.status !== "active") return;
664
+ if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;
665
+ runtime.cancelContinuationWork();
666
+ runtime.persistGoal(runtime.activeGoal);
667
+ runtime.updateStatus(ctx, runtime.activeGoal);
668
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return { cancel: true };
669
+ });
670
+ pi.on("session_compact", async (event, ctx) => {
671
+ if (runtime.activeGoal?.status !== "active") {
672
+ runtime.clearGoalRecovery();
673
+ return;
674
+ }
675
+ const restoredState = loadGoalStateFromSession(ctx);
676
+ if (restoredState.goal?.id === runtime.activeGoal.id) {
677
+ runtime.activeGoal = restoredState.goal;
678
+ }
679
+ const usageRecorded = runtime.recordGoalUsage(runtime.activeGoal, ctx);
680
+ if (usageRecorded) {
681
+ runtime.persistGoal(runtime.activeGoal);
682
+ runtime.updateStatus(ctx, runtime.activeGoal);
683
+ }
684
+ if (!usageRecorded) return;
685
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
686
+ const wasPiRetry = runtime.isPiOwnedCompactionRetry(event, runtime.activeGoal.id);
687
+ if (wasPiRetry) return;
688
+ runtime.clearGoalRecoveryForGoal(runtime.activeGoal.id);
689
+ runtime.requestContinuation(runtime.activeGoal);
690
+ runtime.scheduleContinuationDispatch(ctx, runtime.activeGoal.id);
691
+ });
692
+ pi.on("input", (event, ctx) => {
693
+ if (event.source === "extension") {
694
+ if (runtime.consumeCancelledGoalPrompt(event.text) || runtime.consumeCancelledContinuationPrompt(event.text) || runtime.consumeStaleOwnedGoalPrompt(event.text)) {
695
+ return { action: "handled" };
696
+ }
697
+ if (runtime.acceptOwnedInputBoundary(event.text)) return;
698
+ runtime.supersedeOwnedInputCollision(event.text);
699
+ if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
700
+ if (event.streamingBehavior === "steer" || event.streamingBehavior === "followUp") {
701
+ runtime.noteQueuedNonGoalInput(event.text, event.streamingBehavior);
702
+ }
703
+ runtime.clearGoalRecovery();
704
+ return;
705
+ }
706
+ if (/^\/goal(?:\s|$)/u.test(event.text.trimStart())) return;
707
+ if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
708
+ if (event.streamingBehavior === "followUp") {
709
+ runtime.noteQueuedNonGoalInput(event.text, "followUp", true);
710
+ return;
711
+ }
712
+ if (event.streamingBehavior === "steer") {
713
+ runtime.noteQueuedNonGoalInput(event.text, "steer");
714
+ }
715
+ runtime.clearGoalRecovery();
716
+ runtime.clearBudgetWrapUp();
717
+ runtime.clearStaleGoalToolCallBlock();
718
+ runtime.resetActiveSafetyEpoch(ctx);
719
+ });
720
+ pi.on("message_start", (event, ctx) => {
721
+ const message = event.message;
722
+ if (message.role === "assistant" && runtime.activeGoal?.status === "paused" && runtime.guardAbortGoalId === runtime.activeGoal.id) {
723
+ abortCurrentTurn(ctx);
724
+ return;
725
+ }
726
+ if (message.role === "custom") {
727
+ if (runtime.isActiveBudgetWrapUpMessage(message)) return;
728
+ if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
729
+ if (runtime.guardAbortGoalId === runtime.activeGoal?.id) {
730
+ runtime.guardAbortGoalId = void 0;
731
+ }
732
+ beginNonGoalFollowUp(ctx, false);
733
+ return;
734
+ }
735
+ if (message.role !== "user") return;
736
+ const prompt = Array.isArray(message.content) ? message.content.filter(
737
+ (part) => part && typeof part === "object" && Reflect.get(part, "type") === "text"
738
+ ).map((part) => Reflect.get(part, "text")).filter((text) => typeof text === "string").join("\n") : typeof message.content === "string" ? message.content : "";
739
+ const ownedPrompt = runtime.consumeOwnedGoalPrompt(prompt);
740
+ const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(prompt);
741
+ const queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt, !ownedPromptBoundary);
742
+ if (!ownedPrompt) {
743
+ if (queuedNonGoalInput?.behavior === "followUp") {
744
+ beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
745
+ }
746
+ return;
747
+ }
748
+ if (runtime.activeGoal?.id !== ownedPrompt.goalId || runtime.activeGoal.status !== "active") {
749
+ return;
750
+ }
751
+ if (runtime.agentRunGoalId !== void 0 && runtime.agentRunGoalId !== ownedPrompt.goalId) {
752
+ runtime.activeGoal.baselineTokens = Math.max(
753
+ 0,
754
+ currentTokenTotal(ctx) - runtime.activeGoal.tokensUsed
755
+ );
756
+ }
757
+ runtime.beginAgentRun(ownedPrompt.goalId, "manual");
758
+ if (ownedPrompt.resetSafetyEpoch) {
759
+ runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
760
+ }
761
+ runtime.persistGoal(runtime.activeGoal);
762
+ runtime.updateStatus(ctx, runtime.activeGoal);
763
+ });
764
+ pi.on("context", (event, ctx) => {
765
+ const messages = event.messages.filter((message) => runtime.keepBudgetWrapUpMessage(message));
766
+ if (runtime.activeGoal?.status === "paused" && runtime.guardAbortGoalId === runtime.activeGoal.id) {
767
+ abortCurrentTurn(ctx);
768
+ }
769
+ if (messages.length !== event.messages.length) return { messages };
770
+ });
771
+ pi.on("tool_call", (event, ctx) => {
772
+ runtime.markAgentToolAttempted();
773
+ if (runtime.activeGoal?.status === "budget_limited" && runtime.budgetWrapUp?.goalId === runtime.activeGoal.id && event.toolName !== "goal_complete") {
774
+ abortCurrentTurn(ctx);
775
+ return {
776
+ block: true,
777
+ reason: "Goal token budget is exhausted; only goal_complete is allowed during wrap-up."
778
+ };
779
+ }
780
+ if (!runtime.staleGoalToolCallsBlocked) return;
781
+ if (!runtime.activeGoal || !blocksStaleGoalToolCalls(runtime.activeGoal.status)) {
782
+ runtime.clearStaleGoalToolCallBlock();
783
+ return;
784
+ }
785
+ abortCurrentTurn(ctx);
786
+ return {
787
+ block: true,
788
+ reason: "Blocked stale /goal tool call after the goal stopped or was interrupted."
789
+ };
790
+ });
791
+ pi.on("tool_execution_end", (_event, ctx) => {
792
+ if (runtime.activeGoal?.status === "budget_limited" && runtime.budgetWrapUp?.goalId === runtime.activeGoal.id && !runtime.budgetWrapUp.delivered) {
793
+ runtime.queueBudgetWrapUp(ctx, runtime.activeGoal);
794
+ return;
795
+ }
796
+ if (runtime.activeGoal?.status !== "active") return;
797
+ if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;
798
+ runtime.persistGoal(runtime.activeGoal);
799
+ runtime.updateStatus(ctx, runtime.activeGoal);
800
+ if (runtime.limitActiveGoalForBudget(ctx, true)) return;
801
+ if (!runtime.toolPolicy.toolsAvailable()) runtime.pauseGoalForUnavailableTools(ctx);
802
+ });
803
+ pi.on("before_agent_start", (event, ctx) => {
804
+ runtime.clearAgentRun();
805
+ if (runtime.guardAbortGoalId) runtime.guardAbortGoalId = void 0;
806
+ const goalPrompt = runtime.consumeOwnedGoalPrompt(event.prompt);
807
+ const goalPromptGoalId = goalPrompt?.goalId;
808
+ const continuationGoalId = goalPromptGoalId ? void 0 : runtime.markContinuationStarted(event.prompt);
809
+ const ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;
810
+ const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(event.prompt);
811
+ const activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
812
+ const activeGoalRecovery = runtime.hasActiveGoalRecovery();
813
+ const queuedNonGoalInput = activeBudgetWrapUp ? void 0 : runtime.consumeQueuedNonGoalInput(
814
+ event.prompt,
815
+ !activeGoalRecovery && ownedPromptGoalId === void 0 && !ownedPromptBoundary
816
+ );
817
+ if (queuedNonGoalInput?.behavior === "followUp") {
818
+ beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);
819
+ }
820
+ if (!ownedPromptGoalId && !ownedPromptBoundary) {
821
+ runtime.supersedeOwnedInputCollision(event.prompt);
822
+ if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
823
+ }
824
+ const runOrigin = continuationGoalId ? "automatic" : activeGoalRecovery && runtime.goalRecovery?.automaticOwner ? "automatic" : "manual";
825
+ if (activeBudgetWrapUp && runtime.activeGoal) {
826
+ runtime.beginAgentRun(runtime.activeGoal.id, "manual");
827
+ return;
828
+ }
829
+ if (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {
830
+ runtime.beginAgentRun(ownedPromptGoalId, runOrigin);
831
+ if (runtime.activeGoal?.status === "active" && !runtime.toolPolicy.toolsAvailable()) {
832
+ runtime.pauseGoalForUnavailableTools(ctx, false);
833
+ }
834
+ abortCurrentTurn(ctx);
835
+ return;
836
+ }
837
+ if (runtime.activeGoal?.status !== "active") return;
838
+ runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);
839
+ if (!runtime.toolPolicy.toolsAvailable()) {
840
+ runtime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== void 0);
841
+ return;
842
+ }
843
+ if (goalPrompt?.resetSafetyEpoch && goalPromptGoalId === runtime.activeGoal.id) {
844
+ runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
845
+ runtime.persistGoal(runtime.activeGoal);
846
+ runtime.updateStatus(ctx, runtime.activeGoal);
847
+ }
848
+ return {
849
+ systemPrompt: `${event.systemPrompt}
850
+
851
+ ${buildGoalSystemPrompt(runtime.activeGoal)}`
852
+ };
853
+ });
854
+ pi.on("agent_start", (_event, _ctx) => {
855
+ const activeGoal = runtime.activeGoal;
856
+ if (activeGoal && runtime.guardAbortGoalId === activeGoal.id && activeGoal.status === "paused") {
857
+ if (runtime.consumeQueuedNonGoalFollowUpForAgentStart()) {
858
+ runtime.guardAbortGoalId = void 0;
859
+ runtime.clearStaleGoalToolCallBlock();
860
+ runtime.beginAgentRun(null, void 0);
861
+ }
862
+ return;
863
+ }
864
+ runtime.beginRecoveryRunIfNeeded();
865
+ });
866
+ pi.on("turn_end", (event, ctx) => {
867
+ runtime.recordAutomaticTurn(ctx, event.message);
868
+ });
869
+ pi.on("agent_end", (event, ctx) => {
870
+ const run = runtime.finishAgentRun();
871
+ if (run.goalId === null) return;
872
+ if (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp()) return;
873
+ if (run.goalId && run.goalId !== runtime.activeGoal?.id) return;
874
+ if (!runtime.activeGoal) return;
875
+ if (runtime.activeGoal.status === "budget_limited" && runtime.budgetWrapUp?.goalId === runtime.activeGoal.id) {
876
+ runtime.recordGoalUsage(runtime.activeGoal, ctx);
877
+ runtime.persistGoal(runtime.activeGoal);
878
+ runtime.updateStatus(ctx, runtime.activeGoal);
879
+ runtime.clearBudgetWrapUp();
880
+ return;
881
+ }
882
+ if (runtime.activeGoal.status !== "active") return;
883
+ const goalId = runtime.activeGoal.id;
884
+ const alreadyAwaitingContinuation = runtime.hasContinuationWorkForGoal(goalId);
885
+ const finalAssistant = findFinalAssistantMessage(event.messages);
886
+ if (!alreadyAwaitingContinuation) runtime.activeGoal = incrementGoal(runtime.activeGoal);
887
+ runtime.recordGoalUsage(runtime.activeGoal, ctx);
888
+ if (finalAssistant?.stopReason === "aborted") {
889
+ runtime.clearGoalRecoveryForGoal(goalId);
890
+ stopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, "paused");
891
+ return;
892
+ }
893
+ if (finalAssistant?.stopReason === "error") {
894
+ if (isRetryableGoalInterruption(finalAssistant)) {
895
+ if (run.origin === "automatic" && runtime.enforceAutomaticTurnLimit(ctx, true)) return;
896
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
897
+ if (!runtime.toolPolicy.toolsAvailable()) {
898
+ runtime.pauseGoalForUnavailableTools(ctx);
899
+ return;
900
+ }
901
+ runtime.goalRecovery = {
902
+ goalId,
903
+ kind: isGoalContextOverflow(finalAssistant) ? "compaction_retry" : "provider_retry",
904
+ automaticOwner: run.origin === "automatic",
905
+ errorMessage: finalAssistant.errorMessage
906
+ };
907
+ runtime.cancelContinuationWork();
908
+ runtime.persistGoal(runtime.activeGoal);
909
+ runtime.updateStatus(ctx, runtime.activeGoal);
910
+ return;
911
+ }
912
+ runtime.clearGoalRecoveryForGoal(goalId);
913
+ stopGoalAfterAgentEnd(
914
+ ctx,
915
+ runtime.activeGoal,
916
+ finalAssistant,
917
+ isUsageLimitedGoalInterruption(finalAssistant) ? "usage_limited" : "blocked"
918
+ );
919
+ return;
920
+ }
921
+ runtime.clearGoalRecoveryForGoal(goalId);
922
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
923
+ if (!runtime.toolPolicy.toolsAvailable()) {
924
+ runtime.pauseGoalForUnavailableTools(ctx);
925
+ return;
926
+ }
927
+ if (run.origin === "automatic" && runtime.recordAutomaticRunProgress(
928
+ ctx,
929
+ goalId,
930
+ event.messages,
931
+ run.toolAttempted || hasAssistantToolCall(event.messages)
932
+ )) {
933
+ return;
934
+ }
935
+ runtime.persistGoal(runtime.activeGoal);
936
+ runtime.updateStatus(ctx, runtime.activeGoal);
937
+ const currentGoal = runtime.activeGoal;
938
+ if (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== "active") return;
939
+ runtime.requestContinuation(currentGoal);
940
+ });
941
+ pi.on("agent_settled", (_event, ctx) => {
942
+ runtime.finalizeSettledRecovery(ctx);
943
+ const resumedWait = runtime.dispatchDueGoalWait(ctx);
944
+ if (!resumedWait) runtime.dispatchContinuationIfSettled(ctx);
945
+ runtime.clearSettledSafetyTracking();
946
+ });
947
+ function beginNonGoalFollowUp(ctx, resetSafetyEpoch) {
948
+ runtime.clearGoalRecovery();
949
+ runtime.clearStaleGoalToolCallBlock();
950
+ if (resetSafetyEpoch) runtime.clearBudgetWrapUp();
951
+ const activeGoalId = runtime.activeGoal?.status === "active" ? runtime.activeGoal.id : void 0;
952
+ runtime.beginAgentRun(activeGoalId ?? null, activeGoalId ? "manual" : void 0);
953
+ if (resetSafetyEpoch && activeGoalId) runtime.resetActiveSafetyEpoch(ctx);
954
+ }
955
+ function stopGoalAfterAgentEnd(ctx, goal2, assistant, status) {
956
+ const stoppedGoal = runtime.stopActiveGoal(ctx, {
957
+ kind: "agent_interruption",
958
+ expectedGoalId: goal2.id,
959
+ status,
960
+ reason: assistant.errorMessage ?? `goal ${status} after agent interruption`
961
+ });
962
+ if (!stoppedGoal) return;
963
+ const details = assistant.errorMessage ? ` (${truncateNotification(assistant.errorMessage)})` : "";
964
+ if (status === "paused") {
965
+ notifyTerminal(
966
+ ctx.ui,
967
+ `Goal paused after interruption${details}. Run /goal resume to continue.`,
968
+ "warning"
969
+ );
970
+ return;
971
+ }
972
+ if (status === "usage_limited") {
973
+ notifyTerminal(
974
+ ctx.ui,
975
+ `Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,
976
+ "warning"
977
+ );
978
+ return;
979
+ }
980
+ notifyTerminal(
981
+ ctx.ui,
982
+ `Goal blocked after agent error${details}. Resolve the blocker or run /goal resume to retry.`,
983
+ "warning"
984
+ );
985
+ }
986
+ }
987
+
988
+ // src/run-protocol.ts
989
+ var GOAL_RUN_START_CHANNEL = "pi-goal:start";
990
+ var GOAL_RUN_CANCEL_CHANNEL = "pi-goal:cancel";
991
+ var RUN_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
992
+ var MAX_CANCEL_REASON_LENGTH = 1e3;
993
+ function goalRunEventChannel(runId) {
994
+ return `pi-goal:event:${runId}`;
995
+ }
996
+ function isPayloadRecord(data) {
997
+ if (!data || typeof data !== "object") return false;
998
+ try {
999
+ return !Array.isArray(data);
1000
+ } catch {
1001
+ return false;
1002
+ }
1003
+ }
1004
+ function readPayloadProperty(data, key) {
1005
+ try {
1006
+ return { ok: true, value: Reflect.get(data, key) };
1007
+ } catch {
1008
+ return { ok: false };
1009
+ }
1010
+ }
1011
+ function parseRunId(data) {
1012
+ if (!isPayloadRecord(data)) return void 0;
1013
+ const runId = readPayloadProperty(data, "runId");
1014
+ return runId.ok && typeof runId.value === "string" && RUN_ID_PATTERN.test(runId.value) ? runId.value : void 0;
1015
+ }
1016
+ function currentActiveGoal(runtime) {
1017
+ return runtime.activeGoal;
1018
+ }
1019
+ function parseStartPayload(data) {
1020
+ if (!isPayloadRecord(data)) return "start payload must be an object";
1021
+ const objectiveValue = readPayloadProperty(data, "objective");
1022
+ if (!objectiveValue.ok || typeof objectiveValue.value !== "string") {
1023
+ return "objective must be a string";
1024
+ }
1025
+ const objective = objectiveValue.value.trim();
1026
+ const objectiveError = validateObjective(objective);
1027
+ if (objectiveError) return objectiveError;
1028
+ const tokenBudgetValue = readPayloadProperty(data, "tokenBudget");
1029
+ if (!tokenBudgetValue.ok || tokenBudgetValue.value !== void 0 && (typeof tokenBudgetValue.value !== "number" || !Number.isFinite(tokenBudgetValue.value) || !Number.isSafeInteger(tokenBudgetValue.value) || tokenBudgetValue.value <= 0)) {
1030
+ return "tokenBudget must be a positive integer";
1031
+ }
1032
+ return { objective, tokenBudget: tokenBudgetValue.value };
1033
+ }
1034
+ function parseCancelReason(data) {
1035
+ if (!isPayloadRecord(data)) return { error: "cancel payload must be an object" };
1036
+ const reasonValue = readPayloadProperty(data, "reason");
1037
+ if (!reasonValue.ok || reasonValue.value !== void 0 && typeof reasonValue.value !== "string") {
1038
+ return { error: "reason must be a string" };
1039
+ }
1040
+ if (reasonValue.value === void 0) return void 0;
1041
+ const reason = reasonValue.value.trim();
1042
+ if (reason.length > MAX_CANCEL_REASON_LENGTH) {
1043
+ return { error: `reason must be at most ${MAX_CANCEL_REASON_LENGTH} characters` };
1044
+ }
1045
+ return reason || void 0;
1046
+ }
1047
+ var GoalRunController = class {
1048
+ runtime;
1049
+ commands;
1050
+ generation = 0;
1051
+ session;
1052
+ run;
1053
+ usedRunIds = /* @__PURE__ */ new Set();
1054
+ constructor(runtime, commands) {
1055
+ this.runtime = runtime;
1056
+ this.commands = commands;
1057
+ this.runtime.setGoalStateSink((snapshot) => this.handleGoalState(snapshot));
1058
+ }
1059
+ register(pi) {
1060
+ pi.events.on(GOAL_RUN_START_CHANNEL, (data) => this.handleStart(data));
1061
+ pi.events.on(GOAL_RUN_CANCEL_CHANNEL, (data) => {
1062
+ this.handleCancel(data);
1063
+ });
1064
+ }
1065
+ bindSession(ctx) {
1066
+ this.generation += 1;
1067
+ this.session = { generation: this.generation, ctx };
1068
+ this.closeCurrentRun();
1069
+ this.usedRunIds.clear();
1070
+ }
1071
+ unbindSession() {
1072
+ this.generation += 1;
1073
+ this.session = void 0;
1074
+ this.closeCurrentRun();
1075
+ this.usedRunIds.clear();
1076
+ }
1077
+ async handleStart(data) {
1078
+ const runId = parseRunId(data);
1079
+ if (!runId) return;
1080
+ const session = this.session;
1081
+ if (!session) {
1082
+ this.emitError(runId, "start", "NO_ACTIVE_SESSION", "No active pi-goal session.");
1083
+ return;
1084
+ }
1085
+ if (!this.runtime.settings.rpc.enabled) {
1086
+ this.emitError(runId, "start", "RPC_DISABLED", "Managed run RPC is disabled.");
1087
+ return;
1088
+ }
1089
+ if (this.usedRunIds.has(runId)) {
1090
+ this.emitError(runId, "start", "RUN_ID_IN_USE", "runId was already used in this session.");
1091
+ return;
1092
+ }
1093
+ const parsed = parseStartPayload(data);
1094
+ if (typeof parsed === "string") {
1095
+ this.emitError(runId, "start", "INVALID_REQUEST", parsed);
1096
+ return;
1097
+ }
1098
+ if (this.session !== session || this.generation !== session.generation) {
1099
+ this.emitError(
1100
+ runId,
1101
+ "start",
1102
+ "SUPERSEDED",
1103
+ "The pi-goal session changed while validating the request."
1104
+ );
1105
+ return;
1106
+ }
1107
+ if (this.usedRunIds.has(runId)) {
1108
+ this.emitError(runId, "start", "RUN_ID_IN_USE", "runId was already used in this session.");
1109
+ return;
1110
+ }
1111
+ if (this.runtime.activeGoal || this.run && !this.run.closed) {
1112
+ this.emitError(runId, "start", "GOAL_ALREADY_EXISTS", "A Goal already exists.");
1113
+ return;
1114
+ }
1115
+ const run = {
1116
+ runId,
1117
+ generation: session.generation,
1118
+ closed: false,
1119
+ cancelRequested: false
1120
+ };
1121
+ this.run = run;
1122
+ this.usedRunIds.add(runId);
1123
+ try {
1124
+ await this.commands.startGoal(
1125
+ parsed.objective,
1126
+ parsed.tokenBudget,
1127
+ session.ctx,
1128
+ (goal2) => {
1129
+ if (this.ownsRun(run, session.generation)) run.goalId = goal2.id;
1130
+ },
1131
+ () => this.ownsRun(run, session.generation)
1132
+ );
1133
+ } catch (error) {
1134
+ if (this.ownsRun(run, session.generation)) {
1135
+ this.closeCurrentRun();
1136
+ this.emitError(
1137
+ runId,
1138
+ "start",
1139
+ "ACTIVATION_FAILED",
1140
+ `Goal activation failed: ${formatError(error)}`
1141
+ );
1142
+ }
1143
+ return;
1144
+ }
1145
+ if (!this.ownsRun(run, session.generation)) return;
1146
+ if (!run.goalId) {
1147
+ this.closeCurrentRun();
1148
+ this.emitError(runId, "start", "ACTIVATION_FAILED", "Goal activation did not create a Goal.");
1149
+ return;
1150
+ }
1151
+ if (currentActiveGoal(this.runtime)?.id !== run.goalId) {
1152
+ this.closeCurrentRun();
1153
+ this.emitError(runId, "start", "SUPERSEDED", "The managed Goal was superseded.");
1154
+ return;
1155
+ }
1156
+ if (run.cancelRequested) this.cancelActiveRun(run, session, run.cancelReason);
1157
+ }
1158
+ handleCancel(data) {
1159
+ const runId = parseRunId(data);
1160
+ if (!runId) return;
1161
+ const session = this.session;
1162
+ if (!session) {
1163
+ this.emitError(runId, "cancel", "NO_ACTIVE_SESSION", "No active pi-goal session.");
1164
+ return;
1165
+ }
1166
+ const reason = parseCancelReason(data);
1167
+ if (reason && typeof reason === "object") {
1168
+ this.emitError(runId, "cancel", "INVALID_REQUEST", reason.error);
1169
+ return;
1170
+ }
1171
+ const run = this.run;
1172
+ if (!run || run.closed || run.runId !== runId || run.generation !== session.generation) {
1173
+ this.emitError(runId, "cancel", "RUN_NOT_FOUND", "No active managed run matches runId.");
1174
+ return;
1175
+ }
1176
+ if (!run.goalId) {
1177
+ run.cancelRequested = true;
1178
+ run.cancelReason = reason;
1179
+ return;
1180
+ }
1181
+ this.cancelActiveRun(run, session, reason);
1182
+ }
1183
+ cancelActiveRun(run, session, reason) {
1184
+ if (!this.ownsRun(run, session.generation)) return;
1185
+ const goal2 = this.runtime.activeGoal;
1186
+ if (!goal2 || goal2.id !== run.goalId) {
1187
+ this.closeCurrentRun();
1188
+ this.emitError(run.runId, "cancel", "SUPERSEDED", "The managed Goal was superseded.");
1189
+ return;
1190
+ }
1191
+ if (goal2.status !== "active") {
1192
+ this.closeCurrentRun();
1193
+ this.emitError(run.runId, "cancel", "RUN_NOT_FOUND", "The managed run is no longer active.");
1194
+ return;
1195
+ }
1196
+ this.runtime.setTerminalReason(goal2.id, reason ?? "goal cancelled by managed run");
1197
+ this.commands.pauseGoal(session.ctx);
1198
+ }
1199
+ handleGoalState(snapshot) {
1200
+ const run = this.run;
1201
+ if (!run || run.closed || !run.goalId) return;
1202
+ if (run.goalId !== snapshot.goalId) {
1203
+ if (currentActiveGoal(this.runtime)?.id !== snapshot.goalId) return;
1204
+ this.publishStateEvent(run, {
1205
+ goalId: run.goalId,
1206
+ status: "cleared",
1207
+ reason: "managed Goal superseded by another Goal"
1208
+ });
1209
+ return;
1210
+ }
1211
+ if (snapshot.status === "queued" || run.lastStatus === snapshot.status) return;
1212
+ this.publishStateEvent(run, snapshot);
1213
+ }
1214
+ publishStateEvent(run, snapshot) {
1215
+ const status = snapshot.status;
1216
+ if (status === "queued") return;
1217
+ run.lastStatus = status;
1218
+ const event = {
1219
+ type: "state",
1220
+ runId: run.runId,
1221
+ goalId: snapshot.goalId,
1222
+ status,
1223
+ ...snapshot.summary ? { summary: snapshot.summary } : {},
1224
+ ...snapshot.reason ? { reason: snapshot.reason } : {}
1225
+ };
1226
+ if (!isTerminalGoalStatus(status)) {
1227
+ this.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);
1228
+ return;
1229
+ }
1230
+ run.closed = true;
1231
+ this.run = void 0;
1232
+ const generation = run.generation;
1233
+ queueMicrotask(() => {
1234
+ if (this.generation !== generation) return;
1235
+ this.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);
1236
+ });
1237
+ }
1238
+ emitError(runId, operation, code, message) {
1239
+ this.runtime.pi.events.emit(goalRunEventChannel(runId), {
1240
+ type: "error",
1241
+ runId,
1242
+ operation,
1243
+ error: { code, message }
1244
+ });
1245
+ }
1246
+ ownsRun(run, generation) {
1247
+ return this.session?.generation === generation && this.generation === generation && this.run === run && !run.closed;
1248
+ }
1249
+ closeCurrentRun() {
1250
+ if (this.run) this.run.closed = true;
1251
+ this.run = void 0;
1252
+ }
1253
+ };
1254
+
1255
+ // src/tools.ts
1256
+ import {
1257
+ DEFAULT_MAX_BYTES,
1258
+ DEFAULT_MAX_LINES,
1259
+ defineTool,
1260
+ truncateHead
1261
+ } from "@earendil-works/pi-coding-agent";
1262
+ import { Type } from "typebox";
1263
+ var MAX_GOAL_TEXT_LENGTH = 4e3;
1264
+ var MAX_COMPLETION_SUMMARY_LENGTH = 4e3;
1265
+ var MAX_BLOCKER_REASON_LENGTH = 1e3;
1266
+ var MAX_BLOCKER_EVIDENCE_LENGTH = 4e3;
1267
+ function registerGoalTools(pi, runtime) {
1268
+ const goalCompleteTool = defineTool({
1269
+ name: GOAL_COMPLETE_TOOL,
1270
+ label: "Goal Complete",
1271
+ description: "Mark the active /goal as complete after all required work is done and verified, using the current goal_id stale-turn guard. Do not use for partial progress, blockers, failing, or unverified work.",
1272
+ promptSnippet: "Mark the active /goal as complete after fully finishing and verifying it, with the current goal_id",
1273
+ promptGuidelines: [
1274
+ "When a /goal is active, keep working until the goal is complete; do not stop with only a plan or partial progress.",
1275
+ "Before calling goal_complete, audit the active goal requirement by requirement against the current files, command output, tests, or external state.",
1276
+ "Pass the exact goal_id shown in the current /goal prompt; never reuse a goal_id from an older, stopped, replaced, or cleared turn.",
1277
+ "Call goal_complete only after the requested goal is fully implemented, verified, and no known required work remains; otherwise keep working."
1278
+ ],
1279
+ parameters: Type.Object({
1280
+ goal_id: Type.String({
1281
+ minLength: 1,
1282
+ maxLength: MAX_GOAL_ID_LENGTH,
1283
+ description: "The exact goal_id shown in the current active /goal prompt. Used only to reject stale completion calls from older turns."
1284
+ }),
1285
+ summary: Type.String({
1286
+ minLength: 1,
1287
+ maxLength: MAX_COMPLETION_SUMMARY_LENGTH,
1288
+ description: "State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work."
1289
+ })
1290
+ }),
1291
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1292
+ const completedGoal = runtime.activeGoal;
1293
+ const goal2 = completedGoal?.text ?? "unknown goal";
1294
+ const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
1295
+ const summary = typeof params.summary === "string" ? params.summary.trim() : "";
1296
+ if (!completedGoal) {
1297
+ const rejection = "Goal completion rejected: no active goal.";
1298
+ notifyTerminal(ctx.ui, rejection, "warning");
1299
+ return {
1300
+ content: toolContent(rejection),
1301
+ details: completionDetails(goal2, requestedGoalId, summary)
1302
+ };
1303
+ }
1304
+ const completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();
1305
+ if (!runtime.canRecordGoalUsage() && !completingDuringBudgetWrapUp) {
1306
+ const rejection = "Goal completion rejected: current run does not own the active goal.";
1307
+ notifyTerminal(ctx.ui, rejection, "warning");
1308
+ return {
1309
+ content: toolContent(rejection),
1310
+ details: completionDetails(goal2, requestedGoalId, summary)
1311
+ };
1312
+ }
1313
+ const staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);
1314
+ if (staleGoalRejection) {
1315
+ const rejection = `Goal completion rejected: ${staleGoalRejection}.`;
1316
+ notifyTerminal(ctx.ui, rejection, "warning");
1317
+ if (completingDuringBudgetWrapUp) {
1318
+ runtime.recordGoalUsage(completedGoal, ctx);
1319
+ runtime.persistGoal(completedGoal);
1320
+ runtime.updateStatus(ctx, completedGoal);
1321
+ runtime.clearBudgetWrapUp();
1322
+ }
1323
+ return {
1324
+ content: toolContent(rejection),
1325
+ details: completionDetails(goal2, requestedGoalId, summary),
1326
+ terminate: completingDuringBudgetWrapUp || void 0
1327
+ };
1328
+ }
1329
+ if (completedGoal.status !== "active" && !completingDuringBudgetWrapUp) {
1330
+ const rejection = `Goal completion rejected: goal is ${completedGoal.status}, not active.`;
1331
+ notifyTerminal(ctx.ui, rejection, "warning");
1332
+ return {
1333
+ content: toolContent(rejection),
1334
+ details: completionDetails(goal2, requestedGoalId, summary)
1335
+ };
1336
+ }
1337
+ const rejectionReason = !summary ? "summary is empty" : summary.length > MAX_COMPLETION_SUMMARY_LENGTH ? "summary is too long" : isContradictoryCompletionSummary(summary) ? "summary says the goal is not complete" : void 0;
1338
+ if (rejectionReason) {
1339
+ runtime.recordGoalUsage(completedGoal, ctx);
1340
+ runtime.persistGoal(completedGoal);
1341
+ runtime.updateStatus(ctx, completedGoal);
1342
+ const rejection = `Goal completion rejected: ${rejectionReason}.`;
1343
+ notifyTerminal(ctx.ui, rejection, "warning");
1344
+ if (completingDuringBudgetWrapUp) runtime.clearBudgetWrapUp();
1345
+ return {
1346
+ content: toolContent(rejection),
1347
+ details: completionDetails(goal2, requestedGoalId, summary),
1348
+ terminate: completingDuringBudgetWrapUp || void 0
1349
+ };
1350
+ }
1351
+ runtime.clearGoalWaitTimer();
1352
+ runtime.activeGoal = transitionGoal(completedGoal, "complete");
1353
+ runtime.setCompletionSummary(runtime.activeGoal.id, summary);
1354
+ runtime.recordGoalUsage(runtime.activeGoal, ctx);
1355
+ runtime.persistGoal(runtime.activeGoal);
1356
+ ctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));
1357
+ runtime.clearActiveGoal(ctx);
1358
+ runtime.showCompletionStatus(ctx);
1359
+ notifyTerminal(ctx.ui, `Goal complete: ${goal2}`, "info");
1360
+ return {
1361
+ content: toolContent(`Goal complete: ${summary}`),
1362
+ details: completionDetails(goal2, requestedGoalId, summary),
1363
+ terminate: true
1364
+ };
1365
+ }
1366
+ });
1367
+ const goalBlockedTool = defineTool({
1368
+ name: GOAL_BLOCKED_TOOL,
1369
+ label: "Goal Blocked",
1370
+ description: "Stop the active /goal only at a true impasse after the same blocker recurs for at least three consecutive goal turns, with the current goal_id and concrete evidence that user or external action is required. Do not use for ordinary clarification, uncertainty, or recoverable failures.",
1371
+ promptSnippet: "Mark the active /goal blocked only after the same blocker recurs for three consecutive goal turns",
1372
+ promptGuidelines: [
1373
+ "Use goal_blocked only for a true impasse after the same blocker recurs for at least three consecutive goal turns and concrete evidence shows user or external action is required.",
1374
+ "After a blocked goal is resumed, start a fresh three-turn blocker audit before using goal_blocked again.",
1375
+ "Do not use goal_blocked for ordinary clarification, incomplete work, uncertainty, difficult tasks, or recoverable tool/provider failures.",
1376
+ "Pass goal_blocked the exact current goal_id; never reuse a goal_id from an older, stopped, replaced, or cleared goal turn."
1377
+ ],
1378
+ parameters: Type.Object({
1379
+ goal_id: Type.String({
1380
+ minLength: 1,
1381
+ maxLength: MAX_GOAL_ID_LENGTH,
1382
+ description: "The exact goal_id shown in the current active /goal prompt."
1383
+ }),
1384
+ reason: Type.String({
1385
+ minLength: 1,
1386
+ maxLength: MAX_BLOCKER_REASON_LENGTH,
1387
+ description: "The specific user or external action required to unblock the goal."
1388
+ }),
1389
+ evidence: Type.String({
1390
+ minLength: 1,
1391
+ maxLength: MAX_BLOCKER_EVIDENCE_LENGTH,
1392
+ description: "Concrete evidence from the repeated attempts that proves the impasse."
1393
+ }),
1394
+ repeated_turns: Type.Integer({
1395
+ minimum: 3,
1396
+ description: "Number of separate turns spent trying to resolve this same blocker."
1397
+ })
1398
+ }),
1399
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1400
+ const blockedGoal = runtime.activeGoal;
1401
+ const goal2 = blockedGoal?.text ?? "unknown goal";
1402
+ const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
1403
+ const reason = typeof params.reason === "string" ? params.reason.trim() : "";
1404
+ const evidence = typeof params.evidence === "string" ? params.evidence.trim() : "";
1405
+ const repeatedTurns = typeof params.repeated_turns === "number" ? params.repeated_turns : Number.NaN;
1406
+ const reject = (rejectionReason, terminate = false) => {
1407
+ const rejection = `goal_blocked rejected: ${rejectionReason}.`;
1408
+ notifyTerminal(ctx.ui, rejection, "warning");
1409
+ return {
1410
+ content: toolContent(rejection),
1411
+ details: blockerDetails(goal2, requestedGoalId, reason, evidence, repeatedTurns),
1412
+ ...terminate ? { terminate: true } : {}
1413
+ };
1414
+ };
1415
+ if (!blockedGoal) return reject("no active goal");
1416
+ if (!runtime.canRecordGoalUsage()) {
1417
+ return reject("current run does not own the active goal");
1418
+ }
1419
+ const staleGoalRejection = goalIdRejectionReason(blockedGoal, requestedGoalId);
1420
+ if (staleGoalRejection) return reject(staleGoalRejection);
1421
+ if (blockedGoal.status !== "active") {
1422
+ return reject(`goal is ${blockedGoal.status}, not active`);
1423
+ }
1424
+ if (!reason) return reject("reason is empty");
1425
+ if (reason.length > MAX_BLOCKER_REASON_LENGTH) return reject("reason is too long");
1426
+ if (!evidence) return reject("evidence is empty");
1427
+ if (evidence.length > MAX_BLOCKER_EVIDENCE_LENGTH) return reject("evidence is too long");
1428
+ if (!Number.isInteger(repeatedTurns)) return reject("repeated_turns must be a whole number");
1429
+ if (repeatedTurns < 3) return reject("repeated_turns must be at least 3");
1430
+ const stoppedGoal = runtime.stopActiveGoal(ctx, {
1431
+ kind: "blocker_report",
1432
+ expectedGoalId: blockedGoal.id,
1433
+ reason
1434
+ });
1435
+ if (!stoppedGoal) return reject("active goal changed before blocker transition");
1436
+ notifyTerminal(ctx.ui, `Goal blocked: ${truncateNotification(reason)}`, "warning");
1437
+ return {
1438
+ content: toolContent(`Goal blocked: ${reason}`),
1439
+ details: blockerDetails(goal2, requestedGoalId, reason, evidence, repeatedTurns),
1440
+ terminate: true
1441
+ };
1442
+ }
1443
+ });
1444
+ const goalWaitTool = defineTool({
1445
+ name: GOAL_WAIT_TOOL,
1446
+ label: "Goal Wait",
1447
+ description: `Keep the active /goal alive but quiet while an external event is expected. Call goal_wait alone after arranging a wake message, or provide resume_after_ms as a safety deadline. Requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms. Do not use it for ordinary unfinished work.`,
1448
+ promptSnippet: "Wait quietly for an external event without stopping the active /goal or starting automatic continuations",
1449
+ promptGuidelines: [
1450
+ "Use goal_wait only when progress depends on a later non-goal message, or when resume_after_ms provides a bounded safety wake-up rather than a polling interval.",
1451
+ `Prefer longer waits measured in minutes to avoid busy polling; goal_wait requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms.`,
1452
+ "Arrange the external monitor or wake source before calling goal_wait, and call goal_wait alone because parallel sibling tools can prevent immediate turn termination.",
1453
+ "Pass the exact current goal_id so a stale turn cannot put a replacement goal into waiting.",
1454
+ "Do not use goal_blocked for a recoverable external wait that can be resumed by a message or deadline."
1455
+ ],
1456
+ parameters: Type.Object({
1457
+ goal_id: Type.String({
1458
+ minLength: 1,
1459
+ maxLength: MAX_GOAL_ID_LENGTH,
1460
+ description: "The exact goal_id shown in the current active /goal prompt."
1461
+ }),
1462
+ reason: Type.String({
1463
+ minLength: 1,
1464
+ maxLength: MAX_GOAL_WAIT_REASON_LENGTH,
1465
+ description: "Why the goal is waiting and which external event should wake it."
1466
+ }),
1467
+ resume_after_ms: Type.Optional(
1468
+ Type.Integer({
1469
+ minimum: 1,
1470
+ maximum: MAX_GOAL_WAIT_DELAY_MS,
1471
+ description: `Optional safety deadline in milliseconds that requests one continuation if no wake message arrives. Values below ${MIN_GOAL_WAIT_DELAY_MS} are accepted but clamped to ${MIN_GOAL_WAIT_DELAY_MS}.`
1472
+ })
1473
+ )
1474
+ }),
1475
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1476
+ const activeGoal = runtime.activeGoal;
1477
+ const goal2 = activeGoal?.text ?? "unknown goal";
1478
+ const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
1479
+ const reason = typeof params.reason === "string" ? params.reason.trim() : "";
1480
+ const resumeAfterMs = typeof params.resume_after_ms === "number" ? params.resume_after_ms : void 0;
1481
+ const reject = (rejectionReason) => {
1482
+ const rejection = `goal_wait rejected: ${rejectionReason}.`;
1483
+ notifyTerminal(ctx.ui, rejection, "warning");
1484
+ return {
1485
+ content: toolContent(rejection),
1486
+ details: waitDetails(goal2, requestedGoalId, reason, resumeAfterMs)
1487
+ };
1488
+ };
1489
+ if (!activeGoal) return reject("no active goal");
1490
+ if (!runtime.canRecordGoalUsage()) {
1491
+ return reject("current run does not own the active goal");
1492
+ }
1493
+ const staleGoalRejection = goalIdRejectionReason(activeGoal, requestedGoalId);
1494
+ if (staleGoalRejection) return reject(staleGoalRejection);
1495
+ if (activeGoal.status !== "active") {
1496
+ return reject(`goal is ${activeGoal.status}, not active`);
1497
+ }
1498
+ if (activeGoal.waiting) return reject("goal is already waiting");
1499
+ if (!reason) return reject("reason is empty");
1500
+ if (reason.length > MAX_GOAL_WAIT_REASON_LENGTH) return reject("reason is too long");
1501
+ if (resumeAfterMs !== void 0 && (!Number.isInteger(resumeAfterMs) || resumeAfterMs < 1 || resumeAfterMs > MAX_GOAL_WAIT_DELAY_MS)) {
1502
+ return reject(`resume_after_ms must be a whole number from 1 to ${MAX_GOAL_WAIT_DELAY_MS}`);
1503
+ }
1504
+ const { requestedMs, effectiveMs } = resolveGoalWaitDelay(resumeAfterMs);
1505
+ const waiting = createGoalWait(reason, resumeAfterMs);
1506
+ const waitingGoal = runtime.enterGoalWait(ctx, activeGoal.id, waiting);
1507
+ if (!waitingGoal) return reject("active goal changed before waiting transition");
1508
+ const clamped = requestedMs !== void 0 && effectiveMs !== requestedMs;
1509
+ notifyTerminal(ctx.ui, `Goal waiting: ${truncateNotification(reason)}`, "info");
1510
+ return {
1511
+ content: toolContent(
1512
+ clamped ? `Goal waiting: ${reason}
1513
+ Requested resume_after_ms ${requestedMs} was clamped to ${effectiveMs}.` : `Goal waiting: ${reason}`
1514
+ ),
1515
+ details: waitDetails(
1516
+ goal2,
1517
+ requestedGoalId,
1518
+ reason,
1519
+ effectiveMs,
1520
+ waiting.resumeAt,
1521
+ clamped ? requestedMs : void 0
1522
+ ),
1523
+ terminate: true
1524
+ };
1525
+ }
1526
+ });
1527
+ pi.registerTool(goalCompleteTool);
1528
+ pi.registerTool(goalBlockedTool);
1529
+ pi.registerTool(goalWaitTool);
1530
+ }
1531
+ function toolContent(text) {
1532
+ return [
1533
+ {
1534
+ type: "text",
1535
+ text: truncateHead(safeTerminalText(text), {
1536
+ maxBytes: DEFAULT_MAX_BYTES,
1537
+ maxLines: DEFAULT_MAX_LINES
1538
+ }).content
1539
+ }
1540
+ ];
1541
+ }
1542
+ function completionDetails(goal2, goalId, summary) {
1543
+ return {
1544
+ goal: goal2.slice(0, MAX_GOAL_TEXT_LENGTH),
1545
+ goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),
1546
+ summary: summary.slice(0, MAX_COMPLETION_SUMMARY_LENGTH)
1547
+ };
1548
+ }
1549
+ function blockerDetails(goal2, goalId, reason, evidence, repeatedTurns) {
1550
+ return {
1551
+ goal: goal2.slice(0, MAX_GOAL_TEXT_LENGTH),
1552
+ goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),
1553
+ reason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),
1554
+ evidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),
1555
+ repeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0
1556
+ };
1557
+ }
1558
+ function waitDetails(goal2, goalId, reason, resumeAfterMs, resumeAt, requestedResumeAfterMs) {
1559
+ return {
1560
+ goal: goal2.slice(0, MAX_GOAL_TEXT_LENGTH),
1561
+ goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),
1562
+ reason: reason.slice(0, MAX_GOAL_WAIT_REASON_LENGTH),
1563
+ ...requestedResumeAfterMs === void 0 ? {} : { requested_resume_after_ms: requestedResumeAfterMs },
1564
+ ...resumeAfterMs === void 0 ? {} : { resume_after_ms: resumeAfterMs },
1565
+ ...resumeAt === void 0 ? {} : { resume_at: resumeAt }
1566
+ };
1567
+ }
1568
+
1569
+ // src/goal.ts
1570
+ function registerGoalRuntime(pi, options = {}) {
1571
+ const runtime = new GoalRuntime(pi);
1572
+ const commands = new GoalCommandController(runtime);
1573
+ const runController = new GoalRunController(runtime, commands);
1574
+ runController.register(pi);
1575
+ registerGoalTools(pi, runtime);
1576
+ registerGoalCommand(pi, runtime, commands, options);
1577
+ registerGoalLifecycle(pi, runtime, runController, options);
1578
+ }
1579
+ function goal(pi, options = {}) {
1580
+ registerGoalRuntime(pi, options);
1581
+ }
1582
+ export {
1583
+ goal as default
1584
+ };
1585
+ //# sourceMappingURL=index.ts.map