@narumitw/pi-goal 0.52.3 → 0.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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);
package/src/lifecycle.ts CHANGED
@@ -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) {
@@ -333,7 +388,9 @@ export function registerGoalLifecycle(
333
388
  runtime.queueBudgetWrapUp(ctx, runtime.activeGoal);
334
389
  return;
335
390
  }
336
- if (runtime.activeGoal?.status !== "active") return;
391
+ if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
392
+ return;
393
+ }
337
394
 
338
395
  // AgentSession persists assistant message_end before tool execution events,
339
396
  // so the completed assistant call's usage is authoritative at this boundary.
@@ -372,6 +429,12 @@ export function registerGoalLifecycle(
372
429
  runtime.supersedeOwnedInputCollision(event.prompt);
373
430
  if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
374
431
  }
432
+ if (runtime.activeGoal?.status === "active" && !runtime.ownsWorkflow(runtime.activeGoal)) {
433
+ runtime.cancelContinuationWork();
434
+ runtime.clearGoalRecovery();
435
+ abortCurrentTurn(ctx);
436
+ return;
437
+ }
375
438
  const runOrigin = continuationGoalId
376
439
  ? "automatic"
377
440
  : activeGoalRecovery && runtime.goalRecovery?.automaticOwner
@@ -389,7 +452,9 @@ export function registerGoalLifecycle(
389
452
  abortCurrentTurn(ctx);
390
453
  return;
391
454
  }
392
- if (runtime.activeGoal?.status !== "active") return;
455
+ if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
456
+ return;
457
+ }
393
458
  runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);
394
459
  if (!runtime.toolPolicy.toolsAvailable()) {
395
460
  runtime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);
@@ -445,7 +510,9 @@ export function registerGoalLifecycle(
445
510
  runtime.clearBudgetWrapUp();
446
511
  return;
447
512
  }
448
- if (runtime.activeGoal.status !== "active") return;
513
+ if (runtime.activeGoal.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
514
+ return;
515
+ }
449
516
 
450
517
  const goalId = runtime.activeGoal.id;
451
518
  const alreadyAwaitingContinuation = runtime.hasContinuationWorkForGoal(goalId);
@@ -517,6 +584,12 @@ export function registerGoalLifecycle(
517
584
  });
518
585
 
519
586
  pi.on("agent_settled", (_event, ctx) => {
587
+ if (runtime.activeGoal?.status === "active" && !runtime.ownsWorkflow(runtime.activeGoal)) {
588
+ runtime.cancelContinuationWork();
589
+ runtime.clearGoalRecovery();
590
+ runtime.clearSettledSafetyTracking();
591
+ return;
592
+ }
520
593
  runtime.finalizeSettledRecovery(ctx);
521
594
  const resumedWait = runtime.dispatchDueGoalWait(ctx);
522
595
  if (!resumedWait) runtime.dispatchContinuationIfSettled(ctx);
@@ -223,7 +223,7 @@ export class GoalRunController {
223
223
  this.usedRunIds.add(runId);
224
224
 
225
225
  try {
226
- await this.commands.startGoal(
226
+ const activation = await this.commands.startGoal(
227
227
  parsed.objective,
228
228
  parsed.tokenBudget,
229
229
  session.ctx,
@@ -232,6 +232,16 @@ export class GoalRunController {
232
232
  },
233
233
  () => this.ownsRun(run, session.generation),
234
234
  );
235
+ if (activation?.kind === "busy" && this.ownsRun(run, session.generation)) {
236
+ this.closeCurrentRun();
237
+ this.emitError(
238
+ runId,
239
+ "start",
240
+ "ACTIVATION_FAILED",
241
+ "Another workflow is active in this session. End it before starting Goal.",
242
+ );
243
+ return;
244
+ }
235
245
  } catch (error) {
236
246
  if (this.ownsRun(run, session.generation)) {
237
247
  this.closeCurrentRun();