@narumitw/pi-goal 0.49.6 → 0.50.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/runtime.ts CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  formatTokenCount,
7
7
  updateGoalUsage,
8
8
  } from "./accounting.js";
9
- import { formatError, notifyTerminal, truncateNotification } from "./errors.js";
9
+ import { formatError, notifyTerminal, safeGoalMenuText, truncateNotification } from "./errors.js";
10
10
  import {
11
11
  appendGoalPromptMarker,
12
12
  extractContinuationMarker,
@@ -30,8 +30,14 @@ import {
30
30
  type GoalSettingsLoadIssue,
31
31
  } from "./settings.js";
32
32
  import { GoalToolPolicy, type GoalToolVisibilitySnapshot } from "./tool-policy.js";
33
+ import { type GoalWait, GoalWaitTimer } from "./wait.js";
33
34
 
34
- export { GOAL_BLOCKED_TOOL, GOAL_COMPLETE_TOOL, GOAL_TOOL_NAMES } from "./tool-policy.js";
35
+ export {
36
+ GOAL_BLOCKED_TOOL,
37
+ GOAL_COMPLETE_TOOL,
38
+ GOAL_TOOL_NAMES,
39
+ GOAL_WAIT_TOOL,
40
+ } from "./tool-policy.js";
35
41
 
36
42
  export interface ContinuationTicket {
37
43
  goalId: string;
@@ -158,7 +164,7 @@ export interface GoalSettingsRuntimeSnapshot {
158
164
  budgetWrapUp?: BudgetWrapUp;
159
165
  guardAbortGoalId?: string;
160
166
  staleGoalToolCallsBlocked: boolean;
161
- cancelledContinuationMarkers: string[];
167
+ cancelledContinuationMarkers: Array<[string, string]>;
162
168
  terminalDetails?: GoalTerminalDetails;
163
169
  toolVisibility: GoalToolVisibilitySnapshot;
164
170
  }
@@ -166,6 +172,8 @@ export interface GoalSettingsRuntimeSnapshot {
166
172
  interface PendingGoalPrompt {
167
173
  goalId: string;
168
174
  resetSafetyEpoch: boolean;
175
+ fingerprint: string;
176
+ prompt: string;
169
177
  }
170
178
 
171
179
  interface PendingNonGoalInput {
@@ -188,11 +196,11 @@ const CONTRADICTORY_COMPLETION_PATTERNS = [
188
196
  // One instance belongs to one extension factory. It owns all mutable session state
189
197
  // and the cross-cutting invariants used by command and lifecycle orchestration.
190
198
  // Keep this state machine cohesive despite its size: prompt ownership, continuation,
191
- // budget, safety, and queue transitions share ordering-sensitive invariants. Tool visibility is
192
- // delegated to GoalToolPolicy.
193
- // Cohesion justification: Goal transitions, continuation ownership, queue state, and budget/retry
194
- // recovery share one generation-guarded runtime; separating them further would duplicate stale-turn
195
- // and persistence invariants across modules.
199
+ // budget, safety, external-wait, and queue transitions share ordering-sensitive invariants.
200
+ // Tool visibility and generic wait-timer mechanics are delegated to focused collaborators.
201
+ // Cohesion justification: Goal transitions, continuation and wait ownership, queue state, and
202
+ // budget/retry recovery share one generation-guarded runtime; separating them further would
203
+ // duplicate stale-turn, timer, and persistence invariants across modules.
196
204
  export class GoalRuntime {
197
205
  settings: GoalSettings = DEFAULT_GOAL_SETTINGS;
198
206
  settingsLoadIssue?: GoalSettingsLoadIssue;
@@ -206,6 +214,13 @@ export class GoalRuntime {
206
214
  queueFreezeAwaitingSettle = false;
207
215
  completionStatusTimer?: NodeJS.Timeout;
208
216
  private continuationDispatchTimer?: NodeJS.Timeout;
217
+ private readonly goalWaitTimer = new GoalWaitTimer();
218
+ private goalWaitDeadlineRetry?: {
219
+ goalId: string;
220
+ resumeAt: number;
221
+ retryAt?: number;
222
+ exhausted: boolean;
223
+ };
209
224
  continuationIntent?: ContinuationTicket;
210
225
  continuationDelivery?: ContinuationTicket;
211
226
  goalRecovery?: GoalRecovery;
@@ -218,9 +233,10 @@ export class GoalRuntime {
218
233
  staleGoalToolCallsBlocked = false;
219
234
  readonly toolPolicy: GoalToolPolicy;
220
235
  pendingGoalPromptMarkers = new Map<string, PendingGoalPrompt>();
221
- claimedGoalPromptMarkers = new Set<string>();
222
- cancelledContinuationMarkers = new Set<string>();
223
- claimedContinuationMarkers = new Set<string>();
236
+ claimedGoalPromptMarkers = new Map<string, string>();
237
+ cancelledGoalPromptMarkers = new Map<string, string>();
238
+ cancelledContinuationMarkers = new Map<string, string>();
239
+ claimedContinuationMarkers = new Map<string, string>();
224
240
  pendingNonGoalInputs: PendingNonGoalInput[] = [];
225
241
  menuGeneration = 0;
226
242
  menuController = new AbortController();
@@ -324,7 +340,7 @@ export class GoalRuntime {
324
340
  recordGoalUsage(
325
341
  goal: ActiveGoal,
326
342
  ctx: StatusContext,
327
- checkpointActiveTime = goal.status === "active",
343
+ checkpointActiveTime = goal.status === "active" && !goal.waiting,
328
344
  ) {
329
345
  if (!this.canRecordGoalUsage(goal.id)) return false;
330
346
  updateGoalUsage(goal, ctx, checkpointActiveTime);
@@ -332,7 +348,7 @@ export class GoalRuntime {
332
348
  }
333
349
 
334
350
  requestContinuation(goal: ActiveGoal) {
335
- if (this.hasContinuationWorkForGoal(goal.id)) return false;
351
+ if (goal.waiting || this.hasContinuationWorkForGoal(goal.id)) return false;
336
352
  const marker = continuationMarker(goal);
337
353
  this.continuationIntent = {
338
354
  goalId: goal.id,
@@ -353,7 +369,8 @@ export class GoalRuntime {
353
369
  if (
354
370
  !this.activeGoal ||
355
371
  this.activeGoal.id !== intent.goalId ||
356
- this.activeGoal.status !== "active"
372
+ this.activeGoal.status !== "active" ||
373
+ this.activeGoal.waiting
357
374
  ) {
358
375
  this.continuationIntent = undefined;
359
376
  return false;
@@ -387,6 +404,128 @@ export class GoalRuntime {
387
404
  );
388
405
  }
389
406
 
407
+ enterGoalWait(ctx: StatusContext, goalId: string, waiting: GoalWait) {
408
+ const goal = this.activeGoal;
409
+ if (!goal || goal.id !== goalId || goal.status !== "active") return undefined;
410
+ this.recordGoalUsage(goal, ctx, false);
411
+ this.cancelContinuationWork();
412
+ this.clearGoalRecoveryForGoal(goal.id);
413
+ this.clearGoalWaitTimer();
414
+ this.activeGoal = {
415
+ ...goal,
416
+ waiting,
417
+ activeStartedAt: undefined,
418
+ updatedAt: Date.now(),
419
+ };
420
+ this.persistGoal(this.activeGoal);
421
+ this.updateStatus(ctx, this.activeGoal);
422
+ this.restoreGoalWaitTimer(ctx);
423
+ return this.activeGoal;
424
+ }
425
+
426
+ clearGoalWait(ctx: StatusContext, goalId: string) {
427
+ const goal = this.activeGoal;
428
+ if (!goal || goal.id !== goalId || goal.status !== "active" || !goal.waiting) return false;
429
+ this.clearGoalWaitTimer();
430
+ const { waiting: _waiting, ...nextGoal } = goal;
431
+ const now = Date.now();
432
+ checkpointGoalActiveTime(nextGoal, now, true);
433
+ nextGoal.updatedAt = now;
434
+ this.activeGoal = nextGoal;
435
+ this.persistGoal(this.activeGoal);
436
+ this.updateStatus(ctx, this.activeGoal);
437
+ return true;
438
+ }
439
+
440
+ restoreGoalWaitTimer(ctx: StatusContext) {
441
+ this.clearGoalWaitTimer();
442
+ if (this.queueFrozen || this.pendingQueueAction) return false;
443
+ const goal = this.activeGoal;
444
+ const resumeAt = goal?.status === "active" ? goal.waiting?.resumeAt : undefined;
445
+ if (!goal || resumeAt === undefined) return false;
446
+ this.scheduleGoalWaitTimer(ctx, goal.id, resumeAt);
447
+ return true;
448
+ }
449
+
450
+ dispatchDueGoalWait(ctx: StatusContext) {
451
+ if (this.queueFrozen || this.pendingQueueAction) return false;
452
+ const goal = this.activeGoal;
453
+ const waiting = goal?.status === "active" ? goal.waiting : undefined;
454
+ const resumeAt = waiting?.resumeAt;
455
+ if (!goal || !waiting || resumeAt === undefined) return false;
456
+ const retry = this.goalWaitDeadlineRetry;
457
+ const matchingRetry =
458
+ retry?.goalId === goal.id && retry.resumeAt === resumeAt ? retry : undefined;
459
+ if (matchingRetry?.exhausted) return false;
460
+ const wakeAt = matchingRetry?.retryAt ?? resumeAt;
461
+ if (Date.now() < wakeAt) return false;
462
+ const retryAttempt = matchingRetry?.retryAt !== undefined;
463
+ if (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;
464
+ if (retryAttempt) this.goalWaitDeadlineRetry = undefined;
465
+ if (!this.clearGoalWait(ctx, goal.id)) return false;
466
+ const resumedGoal = this.activeGoal;
467
+ if (!resumedGoal || resumedGoal.id !== goal.id || resumedGoal.status !== "active") return false;
468
+ this.requestContinuation(resumedGoal);
469
+ const dispatched = this.dispatchContinuationIfSettled(ctx);
470
+ if (dispatched) return true;
471
+ if (
472
+ this.activeGoal?.id === goal.id &&
473
+ this.activeGoal.status === "active" &&
474
+ this.continuationIntent?.goalId === goal.id
475
+ ) {
476
+ this.restoreGoalWaitAfterDeadlineFailure(ctx, goal.id, waiting, !retryAttempt);
477
+ }
478
+ return false;
479
+ }
480
+
481
+ clearGoalWaitTimer() {
482
+ this.goalWaitTimer.clear();
483
+ this.goalWaitDeadlineRetry = undefined;
484
+ }
485
+
486
+ private scheduleGoalWaitTimer(ctx: StatusContext, goalId: string, wakeAt: number) {
487
+ const generation = this.menuGeneration;
488
+ this.goalWaitTimer.schedule(wakeAt, () => {
489
+ if (generation !== this.menuGeneration || this.activeGoal?.id !== goalId) return;
490
+ try {
491
+ this.dispatchDueGoalWait(ctx);
492
+ } catch (error) {
493
+ notifyTerminal(ctx.ui, `Goal wait deadline failed: ${formatError(error)}`, "error");
494
+ }
495
+ });
496
+ }
497
+
498
+ private restoreGoalWaitAfterDeadlineFailure(
499
+ ctx: StatusContext,
500
+ goalId: string,
501
+ waiting: GoalWait,
502
+ allowRetry: boolean,
503
+ ) {
504
+ const goal = this.activeGoal;
505
+ if (!goal || goal.id !== goalId || goal.status !== "active" || waiting.resumeAt === undefined) {
506
+ return;
507
+ }
508
+ this.cancelContinuationWork();
509
+ this.recordGoalUsage(goal, ctx, false);
510
+ this.goalWaitTimer.clear();
511
+ this.activeGoal = {
512
+ ...goal,
513
+ waiting,
514
+ activeStartedAt: undefined,
515
+ updatedAt: Date.now(),
516
+ };
517
+ const retryAt = allowRetry ? Date.now() + 1_000 : undefined;
518
+ this.goalWaitDeadlineRetry = {
519
+ goalId,
520
+ resumeAt: waiting.resumeAt,
521
+ retryAt,
522
+ exhausted: !allowRetry,
523
+ };
524
+ this.persistGoal(this.activeGoal);
525
+ this.updateStatus(ctx, this.activeGoal);
526
+ if (retryAt !== undefined) this.scheduleGoalWaitTimer(ctx, goalId, retryAt);
527
+ }
528
+
390
529
  updateStatus(ctx: StatusContext, goal: ActiveGoal) {
391
530
  this.clearCompletionStatusTimer();
392
531
  ctx.ui.setStatus(
@@ -399,6 +538,7 @@ export class GoalRuntime {
399
538
  const currentGoal = this.activeGoal;
400
539
  if (!currentGoal || currentGoal.id !== request.expectedGoalId) return undefined;
401
540
 
541
+ this.clearGoalWaitTimer();
402
542
  let goal = currentGoal;
403
543
  let status: StoppedGoalStatus;
404
544
  let terminalReason: string | undefined;
@@ -727,6 +867,7 @@ export class GoalRuntime {
727
867
  clearPendingGoalPrompts() {
728
868
  this.pendingGoalPromptMarkers.clear();
729
869
  this.claimedGoalPromptMarkers.clear();
870
+ this.cancelledGoalPromptMarkers.clear();
730
871
  this.pendingNonGoalInputs = [];
731
872
  }
732
873
 
@@ -749,7 +890,7 @@ export class GoalRuntime {
749
890
  cancelContinuationWork() {
750
891
  this.clearContinuationDispatchTimer();
751
892
  if (this.continuationDelivery) {
752
- this.rememberCancelledContinuationMarker(this.continuationDelivery.marker);
893
+ this.rememberCancelledContinuationMarker(this.continuationDelivery);
753
894
  }
754
895
  this.continuationIntent = undefined;
755
896
  this.continuationDelivery = undefined;
@@ -777,30 +918,88 @@ export class GoalRuntime {
777
918
  this.continuationDispatchTimer = undefined;
778
919
  }
779
920
 
921
+ consumeCancelledGoalPrompt(prompt: string) {
922
+ const marker = extractGoalPromptMarker(prompt);
923
+ if (!marker) return false;
924
+ const cancelledPrompt = this.cancelledGoalPromptMarkers.get(marker);
925
+ if (!cancelledPrompt || !preservesOwnedPromptAtTerminalBoundary(prompt, cancelledPrompt)) {
926
+ return false;
927
+ }
928
+ this.cancelledGoalPromptMarkers.delete(marker);
929
+ return true;
930
+ }
931
+
780
932
  consumeCancelledContinuationPrompt(prompt: string) {
781
933
  const marker = extractContinuationMarker(prompt);
782
- return marker ? this.cancelledContinuationMarkers.delete(marker) : false;
934
+ if (!marker) return false;
935
+ const cancelledPrompt = this.cancelledContinuationMarkers.get(marker);
936
+ if (!cancelledPrompt || !preservesOwnedPromptAtTerminalBoundary(prompt, cancelledPrompt)) {
937
+ return false;
938
+ }
939
+ this.cancelledContinuationMarkers.delete(marker);
940
+ return true;
783
941
  }
784
942
 
785
- hasPendingOwnedGoalPrompt(prompt: string) {
786
- const marker = extractGoalPromptMarker(prompt);
787
- return marker ? this.pendingGoalPromptMarkers.has(marker) : false;
943
+ acceptOwnedInputBoundary(prompt: string) {
944
+ const fingerprint = inputFingerprint(prompt);
945
+ const goalMarker = extractGoalPromptMarker(prompt);
946
+ if (goalMarker) {
947
+ const pending = this.pendingGoalPromptMarkers.get(goalMarker);
948
+ if (pending && preservesOwnedPromptAtTerminalBoundary(prompt, pending.prompt)) return true;
949
+ if (this.claimedGoalPromptMarkers.get(goalMarker) === fingerprint) return true;
950
+ }
951
+ const continuationMarker = extractContinuationMarker(prompt);
952
+ if (!continuationMarker) return false;
953
+ if (
954
+ this.continuationDelivery?.marker === continuationMarker &&
955
+ preservesOwnedPromptAtTerminalBoundary(prompt, this.continuationDelivery.prompt)
956
+ ) {
957
+ return true;
958
+ }
959
+ return this.claimedContinuationMarkers.get(continuationMarker) === fingerprint;
788
960
  }
789
961
 
790
- hasOwnedPromptBoundary(prompt: string) {
962
+ supersedeOwnedInputCollision(prompt: string) {
963
+ const fingerprint = inputFingerprint(prompt);
791
964
  const goalMarker = extractGoalPromptMarker(prompt);
965
+ if (goalMarker) {
966
+ const pending = this.pendingGoalPromptMarkers.get(goalMarker);
967
+ if (pending && pending.fingerprint !== fingerprint) {
968
+ this.pendingGoalPromptMarkers.delete(goalMarker);
969
+ this.rememberCancelledGoalPromptMarker(goalMarker, pending.prompt);
970
+ }
971
+ this.claimedGoalPromptMarkers.delete(goalMarker);
972
+ }
973
+ const continuationMarker = extractContinuationMarker(prompt);
974
+ if (!continuationMarker) return;
792
975
  if (
793
- goalMarker &&
794
- (this.pendingGoalPromptMarkers.has(goalMarker) ||
795
- this.claimedGoalPromptMarkers.has(goalMarker))
976
+ (this.continuationDelivery?.marker === continuationMarker &&
977
+ !preservesOwnedPromptAtTerminalBoundary(prompt, this.continuationDelivery.prompt)) ||
978
+ this.continuationIntent?.marker === continuationMarker
796
979
  ) {
797
- return true;
980
+ this.cancelContinuationWork();
981
+ }
982
+ this.claimedContinuationMarkers.delete(continuationMarker);
983
+ }
984
+
985
+ hasOwnedPromptBoundary(prompt: string) {
986
+ const fingerprint = inputFingerprint(prompt);
987
+ const goalMarker = extractGoalPromptMarker(prompt);
988
+ if (goalMarker) {
989
+ const pending = this.pendingGoalPromptMarkers.get(goalMarker);
990
+ if (
991
+ (pending && preservesOwnedPromptAtTerminalBoundary(prompt, pending.prompt)) ||
992
+ this.claimedGoalPromptMarkers.get(goalMarker) === fingerprint
993
+ ) {
994
+ return true;
995
+ }
798
996
  }
799
997
  const continuationMarker = extractContinuationMarker(prompt);
800
- return Boolean(
801
- continuationMarker &&
802
- (this.continuationDelivery?.marker === continuationMarker ||
803
- this.claimedContinuationMarkers.has(continuationMarker)),
998
+ if (!continuationMarker) return false;
999
+ return (
1000
+ (this.continuationDelivery?.marker === continuationMarker &&
1001
+ preservesOwnedPromptAtTerminalBoundary(prompt, this.continuationDelivery.prompt)) ||
1002
+ this.claimedContinuationMarkers.get(continuationMarker) === fingerprint
804
1003
  );
805
1004
  }
806
1005
 
@@ -808,7 +1007,7 @@ export class GoalRuntime {
808
1007
  const marker = extractGoalPromptMarker(prompt);
809
1008
  if (!marker) return false;
810
1009
  const pending = this.pendingGoalPromptMarkers.get(marker);
811
- if (!pending) return false;
1010
+ if (!pending || !preservesOwnedPromptAtTerminalBoundary(prompt, pending.prompt)) return false;
812
1011
  if (
813
1012
  !this.queueFrozen &&
814
1013
  !this.pendingQueueAction &&
@@ -882,11 +1081,24 @@ export class GoalRuntime {
882
1081
  this.cancelContinuationWork();
883
1082
  return undefined;
884
1083
  }
1084
+ const fingerprint = inputFingerprint(prompt);
885
1085
  if (this.continuationDelivery?.marker === marker) {
886
- this.continuationDelivery = undefined;
887
- this.rememberClaimedContinuationMarker(marker);
1086
+ const delivery = this.continuationDelivery;
1087
+ if (preservesOwnedPromptAtTerminalBoundary(prompt, delivery.prompt)) {
1088
+ this.continuationDelivery = undefined;
1089
+ this.rememberClaimedContinuationMarker(marker, prompt);
1090
+ return marker.split(":", 1)[0];
1091
+ }
1092
+ }
1093
+ const cancelledPrompt = this.cancelledContinuationMarkers.get(marker);
1094
+ if (
1095
+ this.claimedContinuationMarkers.get(marker) === fingerprint ||
1096
+ (cancelledPrompt && preservesOwnedPromptAtTerminalBoundary(prompt, cancelledPrompt))
1097
+ ) {
1098
+ return marker.split(":", 1)[0];
888
1099
  }
889
- return marker.split(":", 1)[0];
1100
+ this.cancelContinuationWork();
1101
+ return undefined;
890
1102
  }
891
1103
 
892
1104
  persistGoal(goal: ActiveGoal) {
@@ -917,6 +1129,7 @@ export class GoalRuntime {
917
1129
 
918
1130
  clearActiveGoal(ctx: StatusContext, reason = "goal cleared") {
919
1131
  const clearedGoal = this.activeGoal;
1132
+ this.clearGoalWaitTimer();
920
1133
  this.cancelContinuationWork();
921
1134
  this.clearGoalRecovery();
922
1135
  this.clearBudgetWrapUp();
@@ -969,7 +1182,7 @@ export class GoalRuntime {
969
1182
  this.budgetWrapUp = snapshot.budgetWrapUp ? structuredClone(snapshot.budgetWrapUp) : undefined;
970
1183
  this.guardAbortGoalId = snapshot.guardAbortGoalId;
971
1184
  this.staleGoalToolCallsBlocked = snapshot.staleGoalToolCallsBlocked;
972
- this.cancelledContinuationMarkers = new Set(snapshot.cancelledContinuationMarkers);
1185
+ this.cancelledContinuationMarkers = new Map(snapshot.cancelledContinuationMarkers);
973
1186
  this.terminalDetails = snapshot.terminalDetails
974
1187
  ? structuredClone(snapshot.terminalDetails)
975
1188
  : undefined;
@@ -1016,34 +1229,50 @@ export class GoalRuntime {
1016
1229
 
1017
1230
  private rememberPendingGoalPrompt(goalId: string, prompt: string, resetSafetyEpoch: boolean) {
1018
1231
  const marker = randomUUID();
1019
- this.pendingGoalPromptMarkers.set(marker, { goalId, resetSafetyEpoch });
1232
+ const ownedPrompt = appendGoalPromptMarker(prompt, marker);
1233
+ this.pendingGoalPromptMarkers.set(marker, {
1234
+ goalId,
1235
+ resetSafetyEpoch,
1236
+ fingerprint: inputFingerprint(ownedPrompt),
1237
+ prompt: ownedPrompt,
1238
+ });
1020
1239
  if (this.pendingGoalPromptMarkers.size > MAX_PENDING_GOAL_PROMPTS) {
1021
1240
  const oldest = this.pendingGoalPromptMarkers.keys().next().value;
1022
1241
  if (oldest) this.pendingGoalPromptMarkers.delete(oldest);
1023
1242
  }
1024
- return { marker, prompt: appendGoalPromptMarker(prompt, marker) };
1243
+ return { marker, prompt: ownedPrompt };
1025
1244
  }
1026
1245
 
1027
1246
  private consumePendingGoalPrompt(prompt: string) {
1028
1247
  const marker = extractGoalPromptMarker(prompt);
1029
1248
  if (!marker) return undefined;
1030
1249
  const pending = this.pendingGoalPromptMarkers.get(marker);
1250
+ if (!pending || !preservesOwnedPromptAtTerminalBoundary(prompt, pending.prompt)) {
1251
+ return undefined;
1252
+ }
1031
1253
  this.pendingGoalPromptMarkers.delete(marker);
1032
- if (pending) this.rememberClaimedGoalPromptMarker(marker);
1254
+ this.rememberClaimedGoalPromptMarker(marker, inputFingerprint(prompt));
1033
1255
  return pending;
1034
1256
  }
1035
1257
 
1036
- private rememberClaimedGoalPromptMarker(marker: string) {
1037
- this.claimedGoalPromptMarkers.add(marker);
1258
+ private rememberCancelledGoalPromptMarker(marker: string, prompt: string) {
1259
+ this.cancelledGoalPromptMarkers.set(marker, prompt);
1260
+ if (this.cancelledGoalPromptMarkers.size <= MAX_PENDING_GOAL_PROMPTS) return;
1261
+ const oldest = this.cancelledGoalPromptMarkers.keys().next().value;
1262
+ if (oldest) this.cancelledGoalPromptMarkers.delete(oldest);
1263
+ }
1264
+
1265
+ private rememberClaimedGoalPromptMarker(marker: string, fingerprint: string) {
1266
+ this.claimedGoalPromptMarkers.set(marker, fingerprint);
1038
1267
  if (this.claimedGoalPromptMarkers.size <= MAX_PENDING_GOAL_PROMPTS) return;
1039
- const oldest = this.claimedGoalPromptMarkers.values().next().value;
1268
+ const oldest = this.claimedGoalPromptMarkers.keys().next().value;
1040
1269
  if (oldest) this.claimedGoalPromptMarkers.delete(oldest);
1041
1270
  }
1042
1271
 
1043
- private rememberClaimedContinuationMarker(marker: string) {
1044
- this.claimedContinuationMarkers.add(marker);
1272
+ private rememberClaimedContinuationMarker(marker: string, prompt: string) {
1273
+ this.claimedContinuationMarkers.set(marker, inputFingerprint(prompt));
1045
1274
  if (this.claimedContinuationMarkers.size <= MAX_CANCELLED_CONTINUATION_PROMPTS) return;
1046
- const oldest = this.claimedContinuationMarkers.values().next().value;
1275
+ const oldest = this.claimedContinuationMarkers.keys().next().value;
1047
1276
  if (oldest) this.claimedContinuationMarkers.delete(oldest);
1048
1277
  }
1049
1278
 
@@ -1051,10 +1280,10 @@ export class GoalRuntime {
1051
1280
  return this.consumePendingGoalPrompt(prompt);
1052
1281
  }
1053
1282
 
1054
- private rememberCancelledContinuationMarker(marker: string) {
1055
- this.cancelledContinuationMarkers.add(marker);
1283
+ private rememberCancelledContinuationMarker(ticket: ContinuationTicket) {
1284
+ this.cancelledContinuationMarkers.set(ticket.marker, ticket.prompt);
1056
1285
  if (this.cancelledContinuationMarkers.size <= MAX_CANCELLED_CONTINUATION_PROMPTS) return;
1057
- const oldest = this.cancelledContinuationMarkers.values().next().value;
1286
+ const oldest = this.cancelledContinuationMarkers.keys().next().value;
1058
1287
  if (oldest) this.cancelledContinuationMarkers.delete(oldest);
1059
1288
  }
1060
1289
  }
@@ -1090,8 +1319,13 @@ export function transitionGoal(goal: ActiveGoal, requestedStatus: GoalStatus): A
1090
1319
  goal.tokensUsed >= goal.tokenBudget
1091
1320
  ? "budget_limited"
1092
1321
  : requestedStatus;
1093
- const next = { ...goal, status, updatedAt: now };
1094
- checkpointGoalActiveTime(next, now, status === "active");
1322
+ const next = {
1323
+ ...goal,
1324
+ status,
1325
+ updatedAt: now,
1326
+ ...(status === "active" ? {} : { waiting: undefined }),
1327
+ };
1328
+ checkpointGoalActiveTime(next, now, status === "active" && !next.waiting);
1095
1329
  return next;
1096
1330
  }
1097
1331
 
@@ -1119,6 +1353,9 @@ export function formatStatus(
1119
1353
  ? "automatic Unlimited"
1120
1354
  : `automatic ${goal.automaticModelTurns}/${automaticTurnLimit}`;
1121
1355
  if (goal.status === "queued") return `queued · ${automatic}`;
1356
+ if (goal.waiting) {
1357
+ return `waiting ${safeGoalMenuText(goal.waiting.reason)} · ${automatic}`;
1358
+ }
1122
1359
  if (goal.status === "paused" && goal.safetyPauseCause === "continuation_limit") {
1123
1360
  if (automaticTurnLimit === null) {
1124
1361
  return `paused · previous automatic limit at ${goal.automaticModelTurns}`;
@@ -1150,7 +1387,15 @@ export function goalSummary(
1150
1387
  ) {
1151
1388
  const summary = [
1152
1389
  `Goal: ${goal.text}`,
1153
- `Status: ${queueFrozen ? "queue off" : goal.status}`,
1390
+ `Status: ${queueFrozen ? "queue off" : goal.waiting ? "waiting" : goal.status}`,
1391
+ ...(goal.waiting
1392
+ ? [
1393
+ `Waiting: ${safeGoalMenuText(goal.waiting.reason, 1_000)}`,
1394
+ ...(goal.waiting.resumeAt === undefined
1395
+ ? []
1396
+ : [`Resume deadline: ${new Date(goal.waiting.resumeAt).toISOString()}`]),
1397
+ ]
1398
+ : []),
1154
1399
  `Iteration: ${goal.iteration}`,
1155
1400
  automaticTurnLimit === null
1156
1401
  ? `Automatic work: ${goal.automaticModelTurns} responses · Unlimited`
@@ -1187,7 +1432,7 @@ export function goalSummary(
1187
1432
  "Commands: /goal, /goal clear",
1188
1433
  );
1189
1434
  } else {
1190
- summary.push(`Commands: ${goalCommandHint(goal.status, experimentalGoals)}`);
1435
+ summary.push(`Commands: ${goalCommandHint(goal, experimentalGoals)}`);
1191
1436
  }
1192
1437
  return summary.join("\n");
1193
1438
  }
@@ -1229,8 +1474,17 @@ export function goalIdRejectionReason(goal: ActiveGoal, requestedGoalId: string)
1229
1474
  return undefined;
1230
1475
  }
1231
1476
 
1232
- function inputFingerprint(prompt: string) {
1233
- return createHash("sha256").update(prompt, "utf8").digest("hex");
1477
+ function preservesOwnedPromptAtTerminalBoundary(prompt: string, ownedPrompt: string) {
1478
+ // Earlier input handlers may prefix a live pi-goal message before this runtime
1479
+ // can fingerprint it. Require the complete generated prompt as the terminal
1480
+ // boundary so a quoted marker or text appended by an external sender is not owned.
1481
+ return prompt === ownedPrompt || prompt.endsWith(ownedPrompt);
1482
+ }
1483
+
1484
+ function inputFingerprint(prompt: unknown) {
1485
+ return createHash("sha256")
1486
+ .update(typeof prompt === "string" ? prompt : "", "utf8")
1487
+ .digest("hex");
1234
1488
  }
1235
1489
 
1236
1490
  async function sendPrompt(
@@ -1250,14 +1504,17 @@ async function sendPrompt(
1250
1504
  }
1251
1505
  }
1252
1506
 
1253
- function goalCommandHint(status: GoalStatus, experimentalGoals = false) {
1507
+ function goalCommandHint(goal: ActiveGoal, experimentalGoals = false) {
1254
1508
  const queueCommands = experimentalGoals
1255
1509
  ? ", /goal add <objective>, /goal prioritize <objective>, /goal drop-last, /goal skip"
1256
1510
  : "";
1257
- if (status === "active") {
1511
+ if (goal.waiting) {
1512
+ return `/goal resume, /goal edit <objective>, /goal pause, /goal clear${queueCommands}`;
1513
+ }
1514
+ if (goal.status === "active") {
1258
1515
  return `/goal edit <objective>, /goal pause, /goal clear${queueCommands}`;
1259
1516
  }
1260
- if (isResumableGoalStatus(status)) {
1517
+ if (isResumableGoalStatus(goal.status)) {
1261
1518
  return `/goal edit <objective>, /goal resume, /goal clear${queueCommands}`;
1262
1519
  }
1263
1520
  return `/goal edit <objective>, /goal clear${queueCommands}`;
@@ -530,6 +530,7 @@ function applyQueueSetting(runtime: GoalRuntime, ctx: ExtensionCommandContext) {
530
530
  else ctx.ui.setStatus(STATUS_KEY, undefined);
531
531
  if (!shouldFreeze) return;
532
532
 
533
+ runtime.clearGoalWaitTimer();
533
534
  runtime.cancelContinuationWork();
534
535
  runtime.clearGoalRecovery();
535
536
  runtime.clearBudgetWrapUp();
@@ -547,6 +548,7 @@ function restorePersistedRuntime(runtime: GoalRuntime, ctx: ExtensionCommandCont
547
548
  runtime.persistGoal(runtime.activeGoal);
548
549
  if (runtime.queueFrozen) ctx.ui.setStatus(STATUS_KEY, "queue off");
549
550
  else runtime.updateStatus(ctx, runtime.activeGoal);
551
+ runtime.restoreGoalWaitTimer(ctx);
550
552
  return;
551
553
  }
552
554
  ctx.ui.setStatus(STATUS_KEY, undefined);
@@ -3,7 +3,9 @@ import type { GoalToolVisibility } from "./settings.js";
3
3
 
4
4
  export const GOAL_COMPLETE_TOOL = "goal_complete";
5
5
  export const GOAL_BLOCKED_TOOL = "goal_blocked";
6
- export const GOAL_TOOL_NAMES = [GOAL_COMPLETE_TOOL, GOAL_BLOCKED_TOOL] as const;
6
+ export const GOAL_WAIT_TOOL = "goal_wait";
7
+ export const GOAL_TOOL_NAMES = [GOAL_COMPLETE_TOOL, GOAL_BLOCKED_TOOL, GOAL_WAIT_TOOL] as const;
8
+ const REQUIRED_GOAL_TOOL_NAMES = [GOAL_COMPLETE_TOOL, GOAL_BLOCKED_TOOL] as const;
7
9
 
8
10
  export interface GoalToolVisibilitySnapshot {
9
11
  activeTools: string[];
@@ -38,7 +40,7 @@ export class GoalToolPolicy {
38
40
 
39
41
  toolsAvailable() {
40
42
  const active = new Set(this.pi.getActiveTools());
41
- return GOAL_TOOL_NAMES.every((name) => active.has(name));
43
+ return REQUIRED_GOAL_TOOL_NAMES.every((name) => active.has(name));
42
44
  }
43
45
 
44
46
  lock() {