@narumitw/pi-goal 0.52.3 → 0.53.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-goal",
3
- "version": "0.52.3",
3
+ "version": "0.53.1",
4
4
  "description": "Pi extension for autonomous single-objective /goal completion.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/commands.ts CHANGED
@@ -76,15 +76,19 @@ export class GoalCommandController {
76
76
  }
77
77
  }
78
78
 
79
- // Unlock lazy visibility only for a real activation. In always mode, a
80
- // missing tool means another policy or allowlist intentionally removed it.
79
+ // Unlock lazy visibility only after final workflow admission. In always mode,
80
+ // a missing tool means another policy or allowlist intentionally removed it.
81
81
  if (isRequestCurrent && !isRequestCurrent()) return;
82
+ const retainedOwner = this.runtime.ownsWorkflow(existingGoal);
83
+ if (!this.runtime.acquireWorkflow(ctx.sessionManager)) return this.reportWorkflowBusy(ctx);
84
+ const acquiredForRequest = !retainedOwner;
82
85
  const goalToolVisibilityBeforeActivation = this.runtime.toolPolicy.snapshot();
83
86
  try {
84
87
  this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
85
88
  } catch (error) {
86
89
  notifyTerminal(ctx.ui, `Cannot start /goal: ${formatError(error)}`, "error");
87
90
  if (existingGoal?.status === "active") this.runtime.pauseGoalForUnavailableTools(ctx);
91
+ else if (acquiredForRequest) this.runtime.releaseWorkflow();
88
92
  return;
89
93
  }
90
94
 
@@ -100,7 +104,7 @@ export class GoalCommandController {
100
104
  if (!legacyQueueBeforeActivation) this.runtime.persistGoal(startedGoal);
101
105
  if (
102
106
  this.runtime.activeGoal?.id !== startedGoal.id ||
103
- this.runtime.activeGoal.status !== "active"
107
+ !this.runtime.ownsWorkflow(this.runtime.activeGoal)
104
108
  ) {
105
109
  return;
106
110
  }
@@ -135,12 +139,12 @@ export class GoalCommandController {
135
139
  this.runtime.updateStatus(ctx, existingGoal);
136
140
  this.runtime.restoreGoalWaitTimer(ctx);
137
141
  } else if (existingGoal.status === "active") {
138
- this.runtime.stopActiveGoal(ctx, {
139
- kind: "activation_rollback",
140
- expectedGoalId: startedGoal.id,
141
- restoreGoal: existingGoal,
142
- abortTurn: true,
143
- });
142
+ this.runtime.activeGoal = existingGoal;
143
+ this.runtime.clearStaleGoalToolCallBlock();
144
+ this.runtime.persistGoal(existingGoal);
145
+ if (this.runtime.activeGoal?.id === existingGoal.id) {
146
+ this.runtime.updateStatus(ctx, existingGoal);
147
+ }
144
148
  } else {
145
149
  this.runtime.activeGoal = existingGoal;
146
150
  if (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {
@@ -160,17 +164,20 @@ export class GoalCommandController {
160
164
  this.runtime.clearStaleGoalToolCallBlock();
161
165
  ctx.ui.setStatus(STATUS_KEY, undefined);
162
166
  } else {
163
- this.runtime.clearActiveGoal(ctx);
167
+ this.runtime.clearActiveGoal(ctx, "goal activation rolled back", false);
164
168
  }
165
169
  }
166
170
  if (rolledBackStartedGoal) {
167
171
  this.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);
172
+ if (acquiredForRequest && !this.runtime.ownsWorkflow(existingGoal)) {
173
+ this.runtime.releaseWorkflow();
174
+ }
168
175
  }
169
176
  return;
170
177
  }
171
178
  if (
172
179
  this.runtime.activeGoal?.id !== startedGoal.id ||
173
- this.runtime.activeGoal.status !== "active"
180
+ !this.runtime.ownsWorkflow(this.runtime.activeGoal)
174
181
  ) {
175
182
  return;
176
183
  }
@@ -238,11 +245,16 @@ export class GoalCommandController {
238
245
  );
239
246
  return;
240
247
  }
248
+ if (!this.runtime.acquireWorkflow(ctx.sessionManager)) {
249
+ this.reportWorkflowBusy(ctx);
250
+ return;
251
+ }
241
252
  const goalToolVisibilityBeforeActivation = this.runtime.toolPolicy.snapshot();
242
253
  try {
243
254
  this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
244
255
  } catch (error) {
245
256
  notifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, "error");
257
+ this.runtime.releaseWorkflow();
246
258
  return;
247
259
  }
248
260
  const stoppedGoal = this.runtime.activeGoal;
@@ -255,8 +267,9 @@ export class GoalCommandController {
255
267
  transitionGoal(nextGoalInstance(this.runtime.activeGoal), "active"),
256
268
  );
257
269
  this.runtime.persistGoal(this.runtime.activeGoal);
258
- this.runtime.updateStatus(ctx, this.runtime.activeGoal);
259
270
  if (this.runtime.activeGoal.status !== "active") {
271
+ this.runtime.updateStatus(ctx, this.runtime.activeGoal);
272
+ this.runtime.releaseWorkflow();
260
273
  notifyTerminal(
261
274
  ctx.ui,
262
275
  `Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`,
@@ -264,6 +277,8 @@ export class GoalCommandController {
264
277
  );
265
278
  return;
266
279
  }
280
+ if (!this.runtime.ownsWorkflow(this.runtime.activeGoal)) return;
281
+ this.runtime.updateStatus(ctx, this.runtime.activeGoal);
267
282
  const resumedGoal = this.runtime.activeGoal;
268
283
  const sent = await this.runtime.sendOwnedGoalPrompt(
269
284
  ctx,
@@ -282,9 +297,11 @@ export class GoalCommandController {
282
297
  this.runtime.blockStaleGoalToolCalls();
283
298
  }
284
299
  this.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);
300
+ this.runtime.releaseWorkflow();
285
301
  }
286
302
  return;
287
303
  }
304
+ if (!this.runtime.ownsWorkflow(resumedGoal)) return;
288
305
  const automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;
289
306
  notifyTerminal(
290
307
  ctx.ui,
@@ -301,6 +318,10 @@ export class GoalCommandController {
301
318
  const waitingGoal = this.runtime.activeGoal;
302
319
  const waiting = waitingGoal?.waiting;
303
320
  if (waitingGoal?.status !== "active" || !waiting) return;
321
+ if (!this.runtime.acquireWorkflow(ctx.sessionManager)) {
322
+ this.reportWorkflowBusy(ctx);
323
+ return;
324
+ }
304
325
  try {
305
326
  this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
306
327
  } catch (error) {
@@ -323,6 +344,7 @@ export class GoalCommandController {
323
344
  }
324
345
  return;
325
346
  }
347
+ if (!this.runtime.ownsWorkflow(resumedGoal)) return;
326
348
  notifyTerminal(ctx.ui, `Goal resumed from waiting: ${waitingGoal.text}`, "info");
327
349
  }
328
350
 
@@ -360,19 +382,54 @@ export class GoalCommandController {
360
382
  return;
361
383
  }
362
384
 
363
- this.runtime.recordGoalUsage(this.runtime.activeGoal, ctx);
364
- const previousGoal = { ...this.runtime.activeGoal };
385
+ const currentGoal = this.runtime.activeGoal;
386
+ const effectiveTokenBudget = tokenBudget ?? currentGoal.tokenBudget;
387
+ if (
388
+ currentGoal.status === "budget_limited" &&
389
+ effectiveTokenBudget !== undefined &&
390
+ effectiveTokenBudget <= currentGoal.tokensUsed
391
+ ) {
392
+ notifyTerminal(
393
+ ctx.ui,
394
+ `Goal token budget is still reached: ${formatBudget(currentGoal)}. Raise the budget above current usage before editing.`,
395
+ "warning",
396
+ );
397
+ return;
398
+ }
399
+ const previousStatus = currentGoal.status;
400
+ const intendsActive = editedGoalStatus(previousStatus) === "active";
401
+ const retainedOwner = this.runtime.ownsWorkflow(currentGoal);
402
+ if (intendsActive && !this.runtime.acquireWorkflow(ctx.sessionManager)) {
403
+ this.reportWorkflowBusy(ctx);
404
+ return;
405
+ }
406
+ const acquiredForEdit = intendsActive && !retainedOwner;
407
+ const goalToolVisibilityBeforeActivation = intendsActive
408
+ ? this.runtime.toolPolicy.snapshot()
409
+ : undefined;
410
+ if (intendsActive) {
411
+ try {
412
+ this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
413
+ } catch (error) {
414
+ notifyTerminal(ctx.ui, `Cannot reactivate /goal: ${formatError(error)}`, "error");
415
+ if (currentGoal.status === "active") this.runtime.pauseGoalForUnavailableTools(ctx);
416
+ else if (acquiredForEdit) this.runtime.releaseWorkflow();
417
+ return;
418
+ }
419
+ }
420
+
421
+ this.runtime.recordGoalUsage(currentGoal, ctx);
422
+ const previousGoal = { ...currentGoal };
365
423
  this.runtime.clearGoalWaitTimer();
366
424
  this.runtime.cancelContinuationWork();
367
425
  this.runtime.clearGoalRecovery();
368
426
  this.runtime.clearBudgetWrapUp();
369
- const previousStatus = this.runtime.activeGoal.status;
370
- const rotatedGoal = nextGoalInstance(this.runtime.activeGoal);
427
+ const rotatedGoal = nextGoalInstance(currentGoal);
371
428
  const transitionedGoal = transitionGoal(
372
429
  {
373
430
  ...rotatedGoal,
374
431
  text: objective,
375
- tokenBudget: tokenBudget ?? this.runtime.activeGoal.tokenBudget,
432
+ tokenBudget: effectiveTokenBudget,
376
433
  waiting: undefined,
377
434
  },
378
435
  editedGoalStatus(previousStatus),
@@ -381,25 +438,13 @@ export class GoalCommandController {
381
438
  transitionedGoal.status === "active"
382
439
  ? queueGoalSafetyReset(transitionedGoal)
383
440
  : transitionedGoal;
384
- const goalToolVisibilityBeforeActivation =
385
- nextGoal.status === "active" ? this.runtime.toolPolicy.snapshot() : undefined;
386
- if (nextGoal.status === "active") {
387
- try {
388
- this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
389
- } catch (error) {
390
- notifyTerminal(ctx.ui, `Cannot reactivate /goal: ${formatError(error)}`, "error");
391
- if (this.runtime.activeGoal?.status === "active") {
392
- this.runtime.pauseGoalForUnavailableTools(ctx);
393
- }
394
- return;
395
- }
396
- }
397
441
  this.runtime.activeGoal = nextGoal;
398
442
  this.runtime.persistGoal(this.runtime.activeGoal);
399
443
  this.runtime.updateStatus(ctx, this.runtime.activeGoal);
400
444
  const editedGoal = this.runtime.activeGoal;
401
445
  if (!editedGoal) return;
402
446
  if (editedGoal.status === "active") {
447
+ if (!this.runtime.ownsWorkflow(editedGoal)) return;
403
448
  this.runtime.clearStaleGoalToolCallBlock();
404
449
  const sent = await this.runtime.sendOwnedGoalPrompt(
405
450
  ctx,
@@ -415,12 +460,12 @@ export class GoalCommandController {
415
460
  this.runtime.updateStatus(ctx, previousGoal);
416
461
  this.runtime.restoreGoalWaitTimer(ctx);
417
462
  } else if (previousStatus === "active") {
418
- this.runtime.stopActiveGoal(ctx, {
419
- kind: "activation_rollback",
420
- expectedGoalId: editedGoal.id,
421
- restoreGoal: previousGoal,
422
- abortTurn: true,
423
- });
463
+ this.runtime.activeGoal = previousGoal;
464
+ this.runtime.clearStaleGoalToolCallBlock();
465
+ this.runtime.persistGoal(previousGoal);
466
+ if (this.runtime.activeGoal?.id === previousGoal.id) {
467
+ this.runtime.updateStatus(ctx, previousGoal);
468
+ }
424
469
  } else {
425
470
  this.runtime.activeGoal = previousGoal;
426
471
  if (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {
@@ -434,17 +479,31 @@ export class GoalCommandController {
434
479
  if (goalToolVisibilityBeforeActivation) {
435
480
  this.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);
436
481
  }
482
+ if (acquiredForEdit && previousStatus !== "active") {
483
+ this.runtime.releaseWorkflow();
484
+ }
437
485
  }
438
486
  return;
439
487
  }
488
+ if (!this.runtime.ownsWorkflow(editedGoal)) return;
440
489
  } else if (blocksStaleGoalToolCalls(editedGoal.status)) {
441
490
  this.runtime.blockStaleGoalToolCalls();
442
491
  } else {
443
492
  this.runtime.clearStaleGoalToolCallBlock();
444
493
  }
494
+ if (editedGoal.status !== "active" && (retainedOwner || acquiredForEdit)) {
495
+ this.runtime.releaseWorkflow();
496
+ }
445
497
  notifyTerminal(ctx.ui, `Goal updated: ${objective}`, "info");
446
498
  }
447
499
 
500
+ private reportWorkflowBusy(ctx: StatusContext) {
501
+ const message = "Another workflow is active in this session. End it before starting Goal.";
502
+ if (ctx.mode === "print" || ctx.mode === "json") throw new Error(message);
503
+ notifyTerminal(ctx.ui, message, "warning");
504
+ return { kind: "busy" as const };
505
+ }
506
+
448
507
  showGoal(ctx: StatusContext) {
449
508
  if (!this.runtime.activeGoal) {
450
509
  ctx.ui.setStatus(STATUS_KEY, undefined);
@@ -0,0 +1,62 @@
1
+ import type { GoalPromptContext } from "./prompts.js";
2
+ import { buildGoalContextPrompt } from "./prompts.js";
3
+
4
+ export const GOAL_CONTRACT_MESSAGE_TYPE = "goal-contract";
5
+ export const GOAL_CONTRACT_VERSION = 1;
6
+
7
+ interface ContractMessage {
8
+ role?: string;
9
+ customType?: string;
10
+ content?: unknown;
11
+ }
12
+
13
+ export function createGoalContextContract(goal: GoalPromptContext) {
14
+ return {
15
+ role: "custom" as const,
16
+ customType: GOAL_CONTRACT_MESSAGE_TYPE,
17
+ content: buildGoalContextPrompt(goal),
18
+ display: false,
19
+ details: { version: GOAL_CONTRACT_VERSION, goalId: goal.id },
20
+ timestamp: 0,
21
+ };
22
+ }
23
+
24
+ export function reconcileGoalContextContract(messages: unknown[], goal: GoalPromptContext) {
25
+ const summaryBoundary = leadingSummaryBoundary(messages);
26
+ const expected = createGoalContextContract(goal);
27
+ const contractIndexes = messages.flatMap((message, index) =>
28
+ unwrapMessage(message).customType === GOAL_CONTRACT_MESSAGE_TYPE ? [index] : [],
29
+ );
30
+ if (
31
+ contractIndexes.length === 1 &&
32
+ contractIndexes[0] === summaryBoundary &&
33
+ unwrapMessage(messages[summaryBoundary]).content === expected.content
34
+ ) {
35
+ return messages;
36
+ }
37
+
38
+ const withoutContracts = messages.filter(
39
+ (message) => unwrapMessage(message).customType !== GOAL_CONTRACT_MESSAGE_TYPE,
40
+ );
41
+ const insertionIndex = leadingSummaryBoundary(withoutContracts);
42
+ return [
43
+ ...withoutContracts.slice(0, insertionIndex),
44
+ expected,
45
+ ...withoutContracts.slice(insertionIndex),
46
+ ];
47
+ }
48
+
49
+ function leadingSummaryBoundary(messages: readonly unknown[]) {
50
+ let index = 0;
51
+ while (index < messages.length) {
52
+ const role = unwrapMessage(messages[index]).role;
53
+ if (role !== "compactionSummary" && role !== "branchSummary") break;
54
+ index += 1;
55
+ }
56
+ return index;
57
+ }
58
+
59
+ function unwrapMessage(message: unknown): ContractMessage {
60
+ const entry = message as { message?: unknown } | undefined;
61
+ return (entry?.message ?? message ?? {}) as ContractMessage;
62
+ }
package/src/lifecycle.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { currentTokenTotal } from "./accounting.js";
3
3
  import { notifyTerminal } from "./errors.js";
4
+ import { reconcileGoalContextContract } from "./goal-contract.js";
4
5
  import { type ActiveGoal, loadGoalStateFromSession } from "./persistence.js";
5
- import { buildGoalSystemPrompt } from "./prompts.js";
6
6
  import type { GoalRunController } from "./run-protocol.js";
7
7
  import {
8
8
  type AssistantMessageLike,
@@ -18,6 +18,7 @@ import {
18
18
  resetGoalSafetyEpoch,
19
19
  STATUS_KEY,
20
20
  type StatusContext,
21
+ transitionGoal,
21
22
  truncateNotification,
22
23
  } from "./runtime.js";
23
24
  import { hasAssistantToolCall } from "./safety.js";
@@ -39,6 +40,7 @@ export function registerGoalLifecycle(
39
40
  options: GoalLifecycleOptions = {},
40
41
  ) {
41
42
  pi.on("session_start", async (_event, ctx) => {
43
+ runtime.bindWorkflowSession(ctx.sessionManager);
42
44
  runtime.replaceMenuSession();
43
45
  runtime.clearCompletionStatusTimer();
44
46
  runtime.clearContinuationTracking();
@@ -54,9 +56,16 @@ export function registerGoalLifecycle(
54
56
  runtime.clearTerminalDetails();
55
57
  const previousToolVisibility = runtime.settings.toolVisibility;
56
58
  const settingsResult = readGoalSettings(options.settingsPath);
59
+ const loaded = loadGoalStateFromSession(ctx);
57
60
  runtime.settings =
58
61
  settingsResult.kind === "loaded" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;
59
62
  runtime.settingsLoadIssue = settingsResult.kind === "invalid" ? settingsResult : undefined;
63
+ runtime.activeGoal = undefined;
64
+ runtime.legacyQueueState = loaded.legacyQueueState;
65
+ runtime.legacyExperimentalGoalsSetting =
66
+ settingsResult.kind !== "invalid" && settingsResult.legacyExperimentalGoals;
67
+ runController.bindSession(ctx);
68
+
60
69
  if (settingsResult.kind === "invalid") {
61
70
  notifyTerminal(
62
71
  ctx.ui,
@@ -64,64 +73,103 @@ export function registerGoalLifecycle(
64
73
  "warning",
65
74
  );
66
75
  }
67
- runtime.legacyExperimentalGoalsSetting =
68
- settingsResult.kind !== "invalid" && settingsResult.legacyExperimentalGoals;
69
- try {
70
- runtime.toolPolicy.prepareSessionStart(
71
- runtime.settings.toolVisibility,
72
- previousToolVisibility,
73
- );
74
- } catch (error) {
75
- notifyTerminal(
76
- ctx.ui,
77
- `Could not restore always-visible goal tools: ${formatError(error)}`,
78
- "error",
79
- );
80
- }
81
-
82
- const loaded = loadGoalStateFromSession(ctx);
83
- runtime.activeGoal = loaded.goal;
84
- runtime.legacyQueueState = loaded.legacyQueueState;
85
- runController.bindSession(ctx);
86
- if (runtime.legacyQueueState) {
87
- runtime.toolPolicy.reconcileRestoredState(runtime.settings.toolVisibility, false);
88
- ctx.ui.setStatus(STATUS_KEY, undefined);
89
- notifyTerminal(ctx.ui, REMOVED_PERSISTED_QUEUE_WARNING, "warning");
90
- return;
91
- }
92
- if (runtime.legacyExperimentalGoalsSetting) {
76
+ if (runtime.legacyExperimentalGoalsSetting && !runtime.legacyQueueState) {
93
77
  notifyTerminal(ctx.ui, REMOVED_QUEUE_SETTING_WARNING, "warning");
94
78
  }
95
79
 
96
- if (runtime.activeGoal) {
97
- if (runtime.activeGoal.status === "active" && runtime.activeGoal.safetyResetPending) {
80
+ if (loaded.goal?.status === "active") {
81
+ if (!runtime.acquireWorkflow()) {
82
+ runtime.activeGoal = transitionGoal(loaded.goal, "paused");
83
+ runtime.persistGoal(runtime.activeGoal);
84
+ runtime.updateStatus(ctx, runtime.activeGoal);
85
+ notifyTerminal(
86
+ ctx.ui,
87
+ "Goal was paused during restore because another workflow is active in this session. Resume it after the other workflow ends.",
88
+ "warning",
89
+ );
90
+ return;
91
+ }
92
+ runtime.activeGoal = loaded.goal;
93
+ try {
94
+ runtime.toolPolicy.prepareSessionStart(
95
+ runtime.settings.toolVisibility,
96
+ previousToolVisibility,
97
+ );
98
+ } catch (error) {
99
+ notifyTerminal(
100
+ ctx.ui,
101
+ `Could not restore always-visible goal tools: ${formatError(error)}`,
102
+ "error",
103
+ );
104
+ }
105
+ if (runtime.activeGoal.safetyResetPending) {
98
106
  // Resume/edit activation is persisted before its owned prompt starts. A
99
107
  // reload must commit that promised reset before enforcing the old limits.
100
108
  runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
101
109
  }
102
- if (runtime.activeGoal.status === "active") {
103
- runtime.recordGoalUsage(runtime.activeGoal, ctx);
104
- if (runtime.limitActiveGoalForBudget(ctx, false)) return;
105
- if (runtime.enforceAutomaticTurnLimit(ctx, false) || runtime.enforceNoProgressLimit(ctx))
106
- return;
110
+ runtime.recordGoalUsage(runtime.activeGoal, ctx);
111
+ if (runtime.limitActiveGoalForBudget(ctx, false)) return;
112
+ if (runtime.enforceAutomaticTurnLimit(ctx, false) || runtime.enforceNoProgressLimit(ctx)) {
113
+ return;
107
114
  }
108
115
  // On lazy restore, an earlier restrictive session-start policy still wins:
109
116
  // reconciliation unlocks ownership without widening the active tool set.
110
117
  runtime.toolPolicy.reconcileRestoredState(runtime.settings.toolVisibility, true);
111
- if (runtime.activeGoal.status === "active" && !runtime.toolPolicy.toolsAvailable()) {
118
+ if (!runtime.toolPolicy.toolsAvailable()) {
112
119
  runtime.pauseGoalForUnavailableTools(ctx, false);
113
120
  return;
114
121
  }
115
122
  runtime.persistGoal(runtime.activeGoal);
123
+ if (!runtime.ownsWorkflow(runtime.activeGoal)) return;
116
124
  runtime.updateStatus(ctx, runtime.activeGoal);
117
125
  runtime.restoreGoalWaitTimer(ctx);
126
+ return;
127
+ }
128
+
129
+ runtime.activeGoal = loaded.goal;
130
+ let appliedInactivePolicy = false;
131
+ let inactivePolicyFailed = false;
132
+ try {
133
+ appliedInactivePolicy = runtime.withTemporaryWorkflowAccess(() => {
134
+ runtime.toolPolicy.prepareSessionStart(
135
+ runtime.settings.toolVisibility,
136
+ previousToolVisibility,
137
+ );
138
+ runtime.toolPolicy.reconcileRestoredState(
139
+ runtime.settings.toolVisibility,
140
+ runtime.activeGoal !== undefined && runtime.legacyQueueState === undefined,
141
+ );
142
+ });
143
+ } catch (error) {
144
+ inactivePolicyFailed = true;
145
+ notifyTerminal(
146
+ ctx.ui,
147
+ `Could not restore always-visible goal tools: ${formatError(error)}`,
148
+ "error",
149
+ );
150
+ }
151
+ if (!appliedInactivePolicy && !inactivePolicyFailed) {
152
+ notifyTerminal(
153
+ ctx.ui,
154
+ "Goal tool visibility was deferred because another workflow is active in this session.",
155
+ "warning",
156
+ );
157
+ }
158
+ if (runtime.legacyQueueState) {
159
+ ctx.ui.setStatus(STATUS_KEY, undefined);
160
+ notifyTerminal(ctx.ui, REMOVED_PERSISTED_QUEUE_WARNING, "warning");
161
+ return;
162
+ }
163
+ if (runtime.activeGoal) {
164
+ runtime.persistGoal(runtime.activeGoal);
165
+ runtime.updateStatus(ctx, runtime.activeGoal);
118
166
  } else {
119
- runtime.toolPolicy.reconcileRestoredState(runtime.settings.toolVisibility, false);
120
167
  ctx.ui.setStatus(STATUS_KEY, undefined);
121
168
  }
122
169
  });
123
170
 
124
171
  pi.on("session_shutdown", (_event, ctx) => {
172
+ const shutdownSession = ctx.sessionManager;
125
173
  runController.unbindSession();
126
174
  runtime.closeMenuSession();
127
175
  runtime.clearGoalWaitTimer();
@@ -144,6 +192,8 @@ export function registerGoalLifecycle(
144
192
  ctx.ui.setStatus(STATUS_KEY, undefined);
145
193
  runtime.clearCompletionStatusTimer();
146
194
  runtime.clearTerminalDetails();
195
+ runtime.releaseWorkflow();
196
+ runtime.unbindWorkflowSession(shutdownSession);
147
197
  });
148
198
 
149
199
  pi.on("session_before_compact", (event, ctx) => {
@@ -151,7 +201,9 @@ export function registerGoalLifecycle(
151
201
  if ((event as { willRetry?: boolean }).willRetry === true) return { cancel: true as const };
152
202
  return;
153
203
  }
154
- if (runtime.activeGoal?.status !== "active") return;
204
+ if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
205
+ return;
206
+ }
155
207
  if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;
156
208
  runtime.cancelContinuationWork();
157
209
  runtime.persistGoal(runtime.activeGoal);
@@ -160,7 +212,7 @@ export function registerGoalLifecycle(
160
212
  });
161
213
 
162
214
  pi.on("session_compact", async (event, ctx) => {
163
- if (runtime.activeGoal?.status !== "active") {
215
+ if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
164
216
  runtime.clearGoalRecovery();
165
217
  return;
166
218
  }
@@ -264,7 +316,10 @@ export function registerGoalLifecycle(
264
316
  }
265
317
  return;
266
318
  }
267
- if (runtime.activeGoal?.id !== ownedPrompt.goalId || runtime.activeGoal.status !== "active") {
319
+ if (
320
+ runtime.activeGoal?.id !== ownedPrompt.goalId ||
321
+ !runtime.ownsWorkflow(runtime.activeGoal)
322
+ ) {
268
323
  return;
269
324
  }
270
325
  if (runtime.agentRunGoalId !== undefined && runtime.agentRunGoalId !== ownedPrompt.goalId) {
@@ -282,7 +337,13 @@ export function registerGoalLifecycle(
282
337
  });
283
338
 
284
339
  pi.on("context", (event, ctx) => {
285
- const messages = event.messages.filter((message) => runtime.keepBudgetWrapUpMessage(message));
340
+ const keptMessages = event.messages.filter((message) =>
341
+ runtime.keepBudgetWrapUpMessage(message),
342
+ );
343
+ const messages =
344
+ runtime.activeGoal?.status === "active" && runtime.ownsWorkflow(runtime.activeGoal)
345
+ ? reconcileGoalContextContract(keptMessages, runtime.activeGoal)
346
+ : keptMessages;
286
347
  if (
287
348
  runtime.activeGoal?.status === "paused" &&
288
349
  runtime.guardAbortGoalId === runtime.activeGoal.id
@@ -291,7 +352,9 @@ export function registerGoalLifecycle(
291
352
  // context transformation aborts before the provider adapter receives the signal.
292
353
  abortCurrentTurn(ctx);
293
354
  }
294
- if (messages.length !== event.messages.length) return { messages };
355
+ if (messages !== keptMessages || keptMessages.length !== event.messages.length) {
356
+ return { messages: messages as typeof event.messages };
357
+ }
295
358
  });
296
359
 
297
360
  pi.on("tool_call", (event, ctx) => {
@@ -333,7 +396,9 @@ export function registerGoalLifecycle(
333
396
  runtime.queueBudgetWrapUp(ctx, runtime.activeGoal);
334
397
  return;
335
398
  }
336
- if (runtime.activeGoal?.status !== "active") return;
399
+ if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
400
+ return;
401
+ }
337
402
 
338
403
  // AgentSession persists assistant message_end before tool execution events,
339
404
  // so the completed assistant call's usage is authoritative at this boundary.
@@ -372,6 +437,12 @@ export function registerGoalLifecycle(
372
437
  runtime.supersedeOwnedInputCollision(event.prompt);
373
438
  if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
374
439
  }
440
+ if (runtime.activeGoal?.status === "active" && !runtime.ownsWorkflow(runtime.activeGoal)) {
441
+ runtime.cancelContinuationWork();
442
+ runtime.clearGoalRecovery();
443
+ abortCurrentTurn(ctx);
444
+ return;
445
+ }
375
446
  const runOrigin = continuationGoalId
376
447
  ? "automatic"
377
448
  : activeGoalRecovery && runtime.goalRecovery?.automaticOwner
@@ -389,7 +460,9 @@ export function registerGoalLifecycle(
389
460
  abortCurrentTurn(ctx);
390
461
  return;
391
462
  }
392
- if (runtime.activeGoal?.status !== "active") return;
463
+ if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
464
+ return;
465
+ }
393
466
  runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);
394
467
  if (!runtime.toolPolicy.toolsAvailable()) {
395
468
  runtime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);
@@ -400,10 +473,6 @@ export function registerGoalLifecycle(
400
473
  runtime.persistGoal(runtime.activeGoal);
401
474
  runtime.updateStatus(ctx, runtime.activeGoal);
402
475
  }
403
-
404
- return {
405
- systemPrompt: `${event.systemPrompt}\n\n${buildGoalSystemPrompt(runtime.activeGoal)}`,
406
- };
407
476
  });
408
477
 
409
478
  pi.on("agent_start", (_event, _ctx) => {
@@ -445,7 +514,9 @@ export function registerGoalLifecycle(
445
514
  runtime.clearBudgetWrapUp();
446
515
  return;
447
516
  }
448
- if (runtime.activeGoal.status !== "active") return;
517
+ if (runtime.activeGoal.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
518
+ return;
519
+ }
449
520
 
450
521
  const goalId = runtime.activeGoal.id;
451
522
  const alreadyAwaitingContinuation = runtime.hasContinuationWorkForGoal(goalId);
@@ -517,6 +588,12 @@ export function registerGoalLifecycle(
517
588
  });
518
589
 
519
590
  pi.on("agent_settled", (_event, ctx) => {
591
+ if (runtime.activeGoal?.status === "active" && !runtime.ownsWorkflow(runtime.activeGoal)) {
592
+ runtime.cancelContinuationWork();
593
+ runtime.clearGoalRecovery();
594
+ runtime.clearSettledSafetyTracking();
595
+ return;
596
+ }
520
597
  runtime.finalizeSettledRecovery(ctx);
521
598
  const resumedWait = runtime.dispatchDueGoalWait(ctx);
522
599
  if (!resumedWait) runtime.dispatchContinuationIfSettled(ctx);
@@ -82,12 +82,6 @@ export function loadGoalStateFromSession(ctx: SessionContext): LoadedGoalState {
82
82
  return legacyEntry ? loadLegacyGoalsState(legacyEntry.data) : emptyGoalState("none");
83
83
  }
84
84
 
85
- export function loadGoalFromSession(ctx: SessionContext): ActiveGoal | undefined {
86
- const loaded = loadGoalStateFromSession(ctx);
87
- if (loaded.legacyQueueState || loaded.goal?.status === "complete") return undefined;
88
- return loaded.goal;
89
- }
90
-
91
85
  function loadCanonicalGoalState(data: unknown): LoadedGoalState {
92
86
  if (!isRecord(data)) return emptyGoalState("canonical");
93
87
  const rawGoal = data.goal;
package/src/prompts.ts CHANGED
@@ -56,8 +56,14 @@ export function buildGoalSystemPrompt(goal: GoalPromptContext) {
56
56
  return `Active /goal:\n${goalContextBlock(goal)}\n\n${goalModeRules("the active goal")}${budgetLine}`;
57
57
  }
58
58
 
59
+ export function buildGoalContextPrompt(goal: GoalPromptContext) {
60
+ return `Active /goal context:\n${goalContextBlock(goal)}\n\n${goalModeRules("the active goal")}`;
61
+ }
62
+
59
63
  export function buildContinuePrompt(goal: GoalPromptContext, marker: string) {
60
- return `Continue the active /goal until it is complete:\n\n${goalContextBlock(goal)}\n\nThis is automatic continuation #${goal.iteration}. The full objective persists across turns; continue from the authoritative current state.\n\n${goalModeRules("this goal")}\n\n${continuationMarkerComment(marker)}`;
64
+ const budgetLine =
65
+ goal.tokenBudget === undefined ? "" : `\nToken budget: ${formatBudget(goal)} used.`;
66
+ return `Continue the active /goal until it is complete:\n\n${goalContextBlock(goal)}${budgetLine}\n\nThis is automatic continuation #${goal.iteration}. The full objective persists across turns; continue from the authoritative current state.\n\n${goalModeRules("this goal")}\n\n${continuationMarkerComment(marker)}`;
61
67
  }
62
68
 
63
69
  function goalContextBlock(goal: GoalPromptContext) {