@ashx-j/lunr 0.1.6 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/dist/builtin-extensions/index.d.ts.map +1 -1
  2. package/dist/builtin-extensions/index.js +3 -6
  3. package/dist/builtin-extensions/index.js.map +1 -1
  4. package/dist/builtin-extensions/lunr-todos.d.ts +7 -6
  5. package/dist/builtin-extensions/lunr-todos.d.ts.map +1 -1
  6. package/dist/builtin-extensions/lunr-todos.js +24 -11
  7. package/dist/builtin-extensions/lunr-todos.js.map +1 -1
  8. package/dist/builtin-extensions/narumiruna-pi-goal/src/commands.d.ts.map +1 -1
  9. package/dist/builtin-extensions/narumiruna-pi-goal/src/commands.js +9 -5
  10. package/dist/builtin-extensions/narumiruna-pi-goal/src/commands.js.map +1 -1
  11. package/dist/builtin-extensions/narumiruna-pi-goal/src/goal.d.ts.map +1 -1
  12. package/dist/builtin-extensions/narumiruna-pi-goal/src/goal.js +31 -3
  13. package/dist/builtin-extensions/narumiruna-pi-goal/src/goal.js.map +1 -1
  14. package/dist/builtin-extensions/narumiruna-pi-goal/src/runtime.d.ts +1 -0
  15. package/dist/builtin-extensions/narumiruna-pi-goal/src/runtime.d.ts.map +1 -1
  16. package/dist/builtin-extensions/narumiruna-pi-goal/src/runtime.js +14 -4
  17. package/dist/builtin-extensions/narumiruna-pi-goal/src/runtime.js.map +1 -1
  18. package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts.map +1 -1
  19. package/dist/builtin-extensions/pi-subagents/src/extension/index.js +4 -3
  20. package/dist/builtin-extensions/pi-subagents/src/extension/index.js.map +1 -1
  21. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.d.ts.map +1 -1
  22. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js +12 -1
  23. package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js.map +1 -1
  24. package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts +3 -0
  25. package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts.map +1 -1
  26. package/dist/builtin-extensions/pi-subagents/src/shared/types.js.map +1 -1
  27. package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts +8 -0
  28. package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts.map +1 -1
  29. package/dist/builtin-extensions/pi-subagents/src/tui/render.js +22 -2
  30. package/dist/builtin-extensions/pi-subagents/src/tui/render.js.map +1 -1
  31. package/dist/builtin-extensions/pi-web-access/index.d.ts.map +1 -1
  32. package/dist/builtin-extensions/pi-web-access/index.js +38 -230
  33. package/dist/builtin-extensions/pi-web-access/index.js.map +1 -1
  34. package/dist/builtin-extensions/pi-web-access/render-search-chrome.d.ts +35 -0
  35. package/dist/builtin-extensions/pi-web-access/render-search-chrome.d.ts.map +1 -0
  36. package/dist/builtin-extensions/pi-web-access/render-search-chrome.js +93 -0
  37. package/dist/builtin-extensions/pi-web-access/render-search-chrome.js.map +1 -0
  38. package/dist/bun/cli.d.ts.map +1 -1
  39. package/dist/bun/cli.js +1 -0
  40. package/dist/bun/cli.js.map +1 -1
  41. package/dist/catalog/models.json +1 -1
  42. package/dist/catalog/providers/cerebras.json +1 -1
  43. package/dist/catalog/providers/cloudflare-ai-gateway.json +1 -1
  44. package/dist/catalog/providers/cloudflare-workers-ai.json +1 -1
  45. package/dist/catalog/providers/huggingface.json +1 -1
  46. package/dist/catalog/providers/opencode-go.json +1 -1
  47. package/dist/catalog/providers/openrouter.json +1 -1
  48. package/dist/catalog/providers/vercel-ai-gateway.json +1 -1
  49. package/dist/catalog/publication.json +3 -3
  50. package/dist/cli.d.ts.map +1 -1
  51. package/dist/cli.js +4 -1
  52. package/dist/cli.js.map +1 -1
  53. package/dist/core/context-breakdown.d.ts +21 -1
  54. package/dist/core/context-breakdown.d.ts.map +1 -1
  55. package/dist/core/context-breakdown.js +58 -2
  56. package/dist/core/context-breakdown.js.map +1 -1
  57. package/dist/core/extensions/host-static.d.ts +2 -0
  58. package/dist/core/extensions/host-static.d.ts.map +1 -0
  59. package/dist/core/extensions/host-static.js +15 -0
  60. package/dist/core/extensions/host-static.js.map +1 -0
  61. package/dist/core/extensions/loader.d.ts +10 -0
  62. package/dist/core/extensions/loader.d.ts.map +1 -1
  63. package/dist/core/extensions/loader.js +75 -34
  64. package/dist/core/extensions/loader.js.map +1 -1
  65. package/dist/core/official-catalog.d.ts.map +1 -1
  66. package/dist/core/official-catalog.js +11 -4
  67. package/dist/core/official-catalog.js.map +1 -1
  68. package/dist/core/package-manager.d.ts +3 -0
  69. package/dist/core/package-manager.d.ts.map +1 -1
  70. package/dist/core/package-manager.js +11 -5
  71. package/dist/core/package-manager.js.map +1 -1
  72. package/dist/core/permission-mode-control.d.ts +27 -0
  73. package/dist/core/permission-mode-control.d.ts.map +1 -0
  74. package/dist/core/permission-mode-control.js +39 -0
  75. package/dist/core/permission-mode-control.js.map +1 -0
  76. package/dist/core/resource-loader.d.ts +4 -1
  77. package/dist/core/resource-loader.d.ts.map +1 -1
  78. package/dist/core/resource-loader.js +13 -5
  79. package/dist/core/resource-loader.js.map +1 -1
  80. package/dist/core/settings-manager.d.ts.map +1 -1
  81. package/dist/core/settings-manager.js.map +1 -1
  82. package/dist/core/slash-commands.d.ts.map +1 -1
  83. package/dist/core/slash-commands.js +0 -1
  84. package/dist/core/slash-commands.js.map +1 -1
  85. package/dist/core/timings.d.ts +1 -0
  86. package/dist/core/timings.d.ts.map +1 -1
  87. package/dist/core/timings.js +6 -1
  88. package/dist/core/timings.js.map +1 -1
  89. package/dist/core/tools/read.d.ts.map +1 -1
  90. package/dist/core/tools/read.js +14 -20
  91. package/dist/core/tools/read.js.map +1 -1
  92. package/dist/core/tools/render-utils.d.ts +2 -0
  93. package/dist/core/tools/render-utils.d.ts.map +1 -1
  94. package/dist/core/tools/render-utils.js +10 -0
  95. package/dist/core/tools/render-utils.js.map +1 -1
  96. package/dist/main.d.ts +8 -0
  97. package/dist/main.d.ts.map +1 -1
  98. package/dist/main.js +63 -16
  99. package/dist/main.js.map +1 -1
  100. package/dist/migrations.d.ts.map +1 -1
  101. package/dist/migrations.js +3 -0
  102. package/dist/migrations.js.map +1 -1
  103. package/dist/modes/interactive/components/assistant-message.d.ts +1 -0
  104. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  105. package/dist/modes/interactive/components/assistant-message.js +1 -0
  106. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  107. package/dist/modes/interactive/components/context-view.d.ts.map +1 -1
  108. package/dist/modes/interactive/components/context-view.js +3 -1
  109. package/dist/modes/interactive/components/context-view.js.map +1 -1
  110. package/dist/modes/interactive/components/plan-message.d.ts +17 -0
  111. package/dist/modes/interactive/components/plan-message.d.ts.map +1 -0
  112. package/dist/modes/interactive/components/plan-message.js +43 -0
  113. package/dist/modes/interactive/components/plan-message.js.map +1 -0
  114. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  115. package/dist/modes/interactive/components/settings-selector.js +1 -1
  116. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  117. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  118. package/dist/modes/interactive/components/tool-execution.js +3 -1
  119. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  120. package/dist/modes/interactive/components/usage-view.d.ts +4 -25
  121. package/dist/modes/interactive/components/usage-view.d.ts.map +1 -1
  122. package/dist/modes/interactive/components/usage-view.js +17 -69
  123. package/dist/modes/interactive/components/usage-view.js.map +1 -1
  124. package/dist/modes/interactive/components/user-message.d.ts +1 -0
  125. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  126. package/dist/modes/interactive/components/user-message.js +1 -0
  127. package/dist/modes/interactive/components/user-message.js.map +1 -1
  128. package/dist/modes/interactive/interactive-mode.d.ts +23 -6
  129. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  130. package/dist/modes/interactive/interactive-mode.js +267 -148
  131. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  132. package/dist/modes/interactive/smooth-streaming.d.ts +39 -6
  133. package/dist/modes/interactive/smooth-streaming.d.ts.map +1 -1
  134. package/dist/modes/interactive/smooth-streaming.js +160 -73
  135. package/dist/modes/interactive/smooth-streaming.js.map +1 -1
  136. package/dist/utils/clipboard-image.d.ts.map +1 -1
  137. package/dist/utils/clipboard-image.js +7 -3
  138. package/dist/utils/clipboard-image.js.map +1 -1
  139. package/docs/terminal-setup.md +13 -0
  140. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  141. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  142. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  143. package/examples/extensions/gondolin/package-lock.json +2 -2
  144. package/examples/extensions/gondolin/package.json +1 -1
  145. package/examples/extensions/sandbox/package-lock.json +2 -2
  146. package/examples/extensions/sandbox/package.json +1 -1
  147. package/examples/extensions/with-deps/package-lock.json +2 -2
  148. package/examples/extensions/with-deps/package.json +1 -1
  149. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"goal.js","sourceRoot":"","sources":["../../../../src/builtin-extensions/narumiruna-pi-goal/src/goal.ts"],"names":[],"mappings":"AAAA,cAAc;AACd,iFAA+E;AAC/E,sEAAsE;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAC;AAC/D,OAAO,EAAE,UAAU,EAAE,MAAM,kCAAkC,CAAC;AAE9D,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACpD,OAAO,EAAE,qBAAqB,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AACnE,OAAO,EAAE,qBAAqB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAmB,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC7E,OAAO,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AACtE,OAAO,EAAE,kBAAkB,EAAE,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AC;YACzB,GAAG,CAAC,EAAE,CAAC,MAAM,CACZ,iCAAiC,OAAO,iCAAiC,EACzE,SAAS,CACT,CAAC;YACF,OAAO;QACR,CAAC;QACD,IAAI,MAAM,KAAK,eAAe,EAAE,CAAC;YAChC,MAAM,IAAI,GAAG,WAAW,KAAK,SAAS,CAAC,CAAC,CAAC,8BAA8B,IAAI,IAAI,CAAC,WAAW,CAAC,CAAC,cAAc,EAAE,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC;YACtH,GAAG,CAAC,EAAE,CAAC,MAAM,CACZ,qBAAqB,OAAO,IAAI,IAAI,mHAAmH,EACvJ,SAAS,CACT,CAAC;YACF,OAAO;QACR,CAAC;QACD,GAAG,CAAC,EAAE,CAAC,MAAM,CACZ,iCAAiC,OAAO,qDAAqD,EAC7F,SAAS,CACT,CAAC;IAAA,CACF;AAAA,CACD;AAED,MAAM,CAAC,OAAO,UAAU,IAAI,CAAC,EAAgB,EAAE,OAAO,GAAgB,EAAE,EAAE;IACzE,mBAAmB,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;AAAA,CACjC;AAED,OAAO,EACN,oBAAoB,EACpB,yBAAyB,EACzB,cAAc,EACd,gBAAgB,GAChB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EACN,qBAAqB,EACrB,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,GACjB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAErD,OAAO,EACN,yBAAyB,EACzB,YAAY,EACZ,gCAAgC,EAChC,2BAA2B,EAC3B,8BAA8B,GAC9B,MAAM,cAAc,CAAC","sourcesContent":["// @ts-nocheck\n// lunr: defineTool imported from the concrete module, NOT the package barrel —\n// the barrel re-exports main.ts which imports this extension (cycle).\nimport { defineTool } from \"../../../core/extensions/types.js\";\nimport { isCronFire } from \"../../../core/cron/fire-guard.js\";\nimport type { ExtensionAPI } from \"@ashx-j/lunr\";\nimport { Type } from \"typebox\";\nimport { currentTokenTotal } from \"./accounting.js\";\nimport { completeGoalArguments, parseCommand } from \"./command.js\";\nimport { GoalCommandController } from \"./commands.js\";\nimport { type ActiveGoal, loadGoalStateFromSession } from \"./persistence.js\";\nimport { buildGoalPrompt, buildGoalSystemPrompt } from \"./prompts.js\";\nimport { activateQueuedGoal } from \"./queue.js\";\nimport {\n\ttype AssistantMessageLike,\n\tabortCurrentTurn,\n\tblocksStaleGoalToolCalls,\n\tfindFinalAssistantMessage,\n\tformatError,\n\tformatStatus,\n\tGOAL_BLOCKED_TOOL,\n\tGOAL_COMPLETE_TOOL,\n\tGoalRuntime,\n\tgoalIdRejectionReason,\n\tincrementGoal,\n\tisContradictoryCompletionSummary,\n\tisGoalContextOverflow,\n\tisRetryableGoalInterruption,\n\tisUsageLimitedGoalInterruption,\n\tparseUsageResetTimeMs,\n\tSTATUS_KEY,\n\ttype StatusContext,\n\ttransitionGoal,\n\ttruncateNotification,\n} from \"./runtime.js\";\nimport { DEFAULT_GOAL_SETTINGS, readGoalSettings } from \"./settings.js\";\n\n// goal.ts is the Pi-facing composition root: it keeps tool contracts and event\n// ordering together. Per-session mechanisms live in runtime.ts, while user command\n// transitions live in commands.ts. Each factory constructs isolated instances.\n\ninterface GoalCompleteDetails {\n\tgoal: string;\n\tgoal_id: string;\n\tsummary: string;\n}\n\ninterface GoalBlockedDetails {\n\tgoal: string;\n\tgoal_id: string;\n\treason: string;\n\tevidence: string;\n\trepeated_turns: number;\n}\n\ninterface GoalOptions {\n\tsettingsPath?: string;\n}\n\nconst EXPERIMENTAL_GOALS_WARNING =\n\t\"Experimental ordered goals are enabled for pi-goal. Queue behavior and persisted state may change.\";\nconst MAX_BLOCKER_REASON_LENGTH = 1_000;\nconst MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;\n\nfunction registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {\n\tconst runtime = new GoalRuntime(pi);\n\tconst commands = new GoalCommandController(runtime);\n\n\t// Bind per-factory runtime operations once so event orchestration stays concise\n\t// without reintroducing module-global mutable state.\n\tconst clearCompletionStatusTimer = runtime.clearCompletionStatusTimer.bind(runtime);\n\t// lunr: footer refresh timer cleanup\n\tconst clearStatusRefreshTimer = runtime.clearStatusRefreshTimer.bind(runtime);\n\tconst clearContinuationTracking = runtime.clearContinuationTracking.bind(runtime);\n\tconst clearPendingGoalPrompts = runtime.clearPendingGoalPrompts.bind(runtime);\n\tconst clearGoalRecovery = runtime.clearGoalRecovery.bind(runtime);\n\tconst clearBudgetWrapUp = runtime.clearBudgetWrapUp.bind(runtime);\n\tconst clearStaleGoalToolCallBlock = runtime.clearStaleGoalToolCallBlock.bind(runtime);\n\tconst persistGoal = runtime.persistGoal.bind(runtime);\n\tconst updateGoalUsage = runtime.recordGoalUsage.bind(runtime);\n\tconst updateStatus = runtime.updateStatus.bind(runtime);\n\tconst limitActiveGoalForBudget = runtime.limitActiveGoalForBudget.bind(runtime);\n\tconst hideGoalToolsIfLocked = runtime.hideGoalToolsIfLocked.bind(runtime);\n\tconst goalToolsAvailable = runtime.goalToolsAvailable.bind(runtime);\n\tconst pauseGoalForUnavailableTools = runtime.pauseGoalForUnavailableTools.bind(runtime);\n\tconst isPiOwnedCompactionRetry = runtime.isPiOwnedCompactionRetry.bind(runtime);\n\tconst requestContinuation = runtime.requestContinuation.bind(runtime);\n\tconst dispatchContinuationIfSettled = runtime.dispatchContinuationIfSettled.bind(runtime);\n\tconst isGoalToolName = runtime.isGoalToolName.bind(runtime);\n\tconst queueBudgetWrapUp = runtime.queueBudgetWrapUp.bind(runtime);\n\tconst clearGoalRecoveryForGoal = runtime.clearGoalRecoveryForGoal.bind(runtime);\n\tconst blockStaleGoalToolCalls = runtime.blockStaleGoalToolCalls.bind(runtime);\n\tconst cancelContinuationWork = runtime.cancelContinuationWork.bind(runtime);\n\tconst consumeCancelledContinuationPrompt =\n\t\truntime.consumeCancelledContinuationPrompt.bind(runtime);\n\tconst consumeStaleOwnedGoalPrompt = runtime.consumeStaleOwnedGoalPrompt.bind(runtime);\n\tconst consumePendingGoalPrompt = runtime.consumeOwnedGoalPrompt.bind(runtime);\n\tconst markContinuationStarted = runtime.markContinuationStarted.bind(runtime);\n\tconst hasContinuationWorkForGoal = runtime.hasContinuationWorkForGoal.bind(runtime);\n\tconst clearActiveGoal = runtime.clearActiveGoal.bind(runtime);\n\tconst showCompletionStatus = runtime.showCompletionStatus.bind(runtime);\n\tconst restoreGoalToolsHiddenByPolicy = runtime.restoreGoalToolsHiddenByPolicy.bind(runtime);\n\tconst sendOwnedGoalPrompt = (\n\t\t_pi: ExtensionAPI,\n\t\tctx: StatusContext,\n\t\tgoalId: string,\n\t\tprompt: string,\n\t) => runtime.sendOwnedGoalPrompt(ctx, goalId, prompt);\n\tconst dispatchPendingQueueActionIfSettled =\n\t\tcommands.dispatchPendingQueueActionIfSettled.bind(commands);\n\n\tconst goalCompleteTool = defineTool({\n\t\tname: GOAL_COMPLETE_TOOL,\n\t\tlabel: \"Goal Complete\",\n\t\tdescription:\n\t\t\t\"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.\",\n\t\tpromptSnippet:\n\t\t\t\"Mark the active /goal as complete after fully finishing and verifying it, with the current goal_id\",\n\t\tpromptGuidelines: [\n\t\t\t\"When a /goal is active, keep working until the goal is complete; do not stop with only a plan or partial progress.\",\n\t\t\t\"Before calling goal_complete, audit the active goal requirement by requirement against the current files, command output, tests, or external state.\",\n\t\t\t\"Pass the exact goal_id shown in the current /goal prompt; never reuse a goal_id from an older, stopped, replaced, or cleared turn.\",\n\t\t\t\"Call goal_complete only after the requested goal is fully implemented, verified, and no known required work remains; otherwise keep working.\",\n\t\t],\n\t\tparameters: Type.Object({\n\t\t\tgoal_id: Type.String({\n\t\t\t\tdescription:\n\t\t\t\t\t\"The exact goal_id shown in the current active /goal prompt. Used only to reject stale completion calls from older turns.\",\n\t\t\t}),\n\t\t\tsummary: Type.String({\n\t\t\t\tdescription:\n\t\t\t\t\t\"State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work.\",\n\t\t\t}),\n\t\t}),\n\t\tasync execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n\t\t\tconst completedGoal = runtime.activeGoal;\n\t\t\tconst goal = completedGoal?.text ?? \"unknown goal\";\n\t\t\tconst requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n\t\t\tconst summary = typeof params.summary === \"string\" ? params.summary.trim() : \"\";\n\n\t\t\tif (!completedGoal) {\n\t\t\t\tconst rejection = \"Goal completion rejected: no active goal.\";\n\t\t\t\tctx.ui.notify(rejection, \"warning\");\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: rejection }],\n\t\t\t\t\tdetails: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n\t\t\tif (!runtime.canRecordGoalUsage() && !completingDuringBudgetWrapUp) {\n\t\t\t\tconst rejection = \"Goal completion rejected: current run does not own the active goal.\";\n\t\t\t\tctx.ui.notify(rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: rejection }],\n\t\t\t\t\tdetails: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (hasPendingSkipForGoal(completedGoal.id)) {\n\t\t\t\tupdateGoalUsage(completedGoal, ctx);\n\t\t\t\tpersistGoal(completedGoal);\n\t\t\t\tupdateStatus(ctx, completedGoal);\n\t\t\t\tclearBudgetWrapUp();\n\t\t\t\tconst rejection = \"Goal completion rejected: goal is queued to be skipped.\";\n\t\t\t\tctx.ui.notify(rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: rejection }],\n\t\t\t\t\tdetails: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,\n\t\t\t\t\tterminate: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);\n\t\t\tif (staleGoalRejection) {\n\t\t\t\tconst rejection = `Goal completion rejected: ${staleGoalRejection}.`;\n\t\t\t\tctx.ui.notify(rejection, \"warning\");\n\t\t\t\tif (completingDuringBudgetWrapUp) {\n\t\t\t\t\tupdateGoalUsage(completedGoal, ctx);\n\t\t\t\t\tpersistGoal(completedGoal);\n\t\t\t\t\tupdateStatus(ctx, completedGoal);\n\t\t\t\t\tclearBudgetWrapUp();\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: rejection }],\n\t\t\t\t\tdetails: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,\n\t\t\t\t\tterminate: completingDuringBudgetWrapUp || undefined,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (completedGoal.status !== \"active\" && !completingDuringBudgetWrapUp) {\n\t\t\t\tconst rejection = `Goal completion rejected: goal is ${completedGoal.status}, not active.`;\n\t\t\t\tctx.ui.notify(rejection, \"warning\");\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: rejection }],\n\t\t\t\t\tdetails: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst rejectionReason = !summary\n\t\t\t\t? \"summary is empty\"\n\t\t\t\t: isContradictoryCompletionSummary(summary)\n\t\t\t\t\t? \"summary says the goal is not complete\"\n\t\t\t\t\t: undefined;\n\t\t\tif (rejectionReason) {\n\t\t\t\tupdateGoalUsage(completedGoal, ctx);\n\t\t\t\tpersistGoal(completedGoal);\n\t\t\t\tupdateStatus(ctx, completedGoal);\n\t\t\t\tconst rejection = `Goal completion rejected: ${rejectionReason}.`;\n\t\t\t\tctx.ui.notify(rejection, \"warning\");\n\t\t\t\tif (completingDuringBudgetWrapUp) clearBudgetWrapUp();\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: rejection,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,\n\t\t\t\t\tterminate: completingDuringBudgetWrapUp || undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\truntime.activeGoal = transitionGoal(completedGoal, \"complete\");\n\t\t\tupdateGoalUsage(runtime.activeGoal, ctx);\n\t\t\tif (runtime.pendingQueueAction?.kind === \"prioritize\") {\n\t\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\t\tctx.ui.setStatus(STATUS_KEY, \"complete\");\n\t\t\t\tctx.ui.notify(`Goal complete: ${goal}. Priority goal waits for Pi to settle.`, \"info\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Goal complete: ${summary}` }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tgoal,\n\t\t\t\t\t\tgoal_id: requestedGoalId,\n\t\t\t\t\t\tsummary,\n\t\t\t\t\t} satisfies GoalCompleteDetails,\n\t\t\t\t\tterminate: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (runtime.queuedGoals.length > 0) {\n\t\t\t\truntime.pendingQueueAction = {\n\t\t\t\t\tkind: \"advance\",\n\t\t\t\t\tgoalId: runtime.activeGoal.id,\n\t\t\t\t\treason: \"complete\",\n\t\t\t\t\tcompletedText: goal,\n\t\t\t\t};\n\t\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\t\tctx.ui.setStatus(STATUS_KEY, \"complete\");\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t`Goal complete: ${goal}. Next goal queued: ${runtime.queuedGoals[0]?.text}`,\n\t\t\t\t\t\"info\",\n\t\t\t\t);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Goal complete: ${summary}\\nNext goal queued: ${runtime.queuedGoals[0]?.text}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tgoal,\n\t\t\t\t\t\tgoal_id: requestedGoalId,\n\t\t\t\t\t\tsummary,\n\t\t\t\t\t} satisfies GoalCompleteDetails,\n\t\t\t\t\tterminate: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\tpersistGoal(runtime.activeGoal);\n\n\t\t\tctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));\n\t\t\tclearActiveGoal(ctx);\n\t\t\tshowCompletionStatus(ctx);\n\t\t\tctx.ui.notify(`Goal complete: ${goal}`, \"info\");\n\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: `Goal complete: ${summary}` }],\n\t\t\t\tdetails: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,\n\t\t\t\tterminate: true,\n\t\t\t};\n\t\t},\n\t});\n\n\tconst goalBlockedTool = defineTool({\n\t\tname: GOAL_BLOCKED_TOOL,\n\t\tlabel: \"Goal Blocked\",\n\t\tdescription:\n\t\t\t\"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.\",\n\t\tpromptSnippet:\n\t\t\t\"Mark the active /goal blocked only after the same blocker recurs for three consecutive goal turns\",\n\t\tpromptGuidelines: [\n\t\t\t\"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.\",\n\t\t\t\"After a blocked goal is resumed, start a fresh three-turn blocker audit before using goal_blocked again.\",\n\t\t\t\"Do not use goal_blocked for ordinary clarification, incomplete work, uncertainty, difficult tasks, or recoverable tool/provider failures.\",\n\t\t\t\"Pass goal_blocked the exact current goal_id; never reuse a goal_id from an older, stopped, replaced, or cleared goal turn.\",\n\t\t],\n\t\tparameters: Type.Object({\n\t\t\tgoal_id: Type.String({\n\t\t\t\tdescription: \"The exact goal_id shown in the current active /goal prompt.\",\n\t\t\t}),\n\t\t\treason: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_BLOCKER_REASON_LENGTH,\n\t\t\t\tdescription: \"The specific user or external action required to unblock the goal.\",\n\t\t\t}),\n\t\t\tevidence: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_BLOCKER_EVIDENCE_LENGTH,\n\t\t\t\tdescription: \"Concrete evidence from the repeated attempts that proves the impasse.\",\n\t\t\t}),\n\t\t\trepeated_turns: Type.Integer({\n\t\t\t\tminimum: 3,\n\t\t\t\tdescription: \"Number of separate turns spent trying to resolve this same blocker.\",\n\t\t\t}),\n\t\t}),\n\t\tasync execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n\t\t\tconst blockedGoal = runtime.activeGoal;\n\t\t\tconst goal = blockedGoal?.text ?? \"unknown goal\";\n\t\t\tconst requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n\t\t\tconst reason = typeof params.reason === \"string\" ? params.reason.trim() : \"\";\n\t\t\tconst evidence = typeof params.evidence === \"string\" ? params.evidence.trim() : \"\";\n\t\t\tconst repeatedTurns =\n\t\t\t\ttypeof params.repeated_turns === \"number\" ? params.repeated_turns : Number.NaN;\n\t\t\tconst reject = (rejectionReason: string, terminate = false) => {\n\t\t\t\tconst rejection = `goal_blocked rejected: ${rejectionReason}.`;\n\t\t\t\tctx.ui.notify(rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\" as const, text: rejection }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tgoal,\n\t\t\t\t\t\tgoal_id: requestedGoalId,\n\t\t\t\t\t\treason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),\n\t\t\t\t\t\tevidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),\n\t\t\t\t\t\trepeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,\n\t\t\t\t\t} satisfies GoalBlockedDetails,\n\t\t\t\t\t...(terminate ? { terminate: true as const } : {}),\n\t\t\t\t};\n\t\t\t};\n\n\t\t\tif (!blockedGoal) return reject(\"no active goal\");\n\t\t\tif (!runtime.canRecordGoalUsage()) {\n\t\t\t\treturn reject(\"current run does not own the active goal\");\n\t\t\t}\n\t\t\tif (hasPendingSkipForGoal(blockedGoal.id)) {\n\t\t\t\tupdateGoalUsage(blockedGoal, ctx);\n\t\t\t\tpersistGoal(blockedGoal);\n\t\t\t\tupdateStatus(ctx, blockedGoal);\n\t\t\t\tclearBudgetWrapUp();\n\t\t\t\treturn reject(\"goal is queued to be skipped\", true);\n\t\t\t}\n\t\t\tconst staleGoalRejection = goalIdRejectionReason(blockedGoal, requestedGoalId);\n\t\t\tif (staleGoalRejection) return reject(staleGoalRejection);\n\t\t\tif (blockedGoal.status !== \"active\") {\n\t\t\t\treturn reject(`goal is ${blockedGoal.status}, not active`);\n\t\t\t}\n\t\t\tif (!reason) return reject(\"reason is empty\");\n\t\t\tif (reason.length > MAX_BLOCKER_REASON_LENGTH) return reject(\"reason is too long\");\n\t\t\tif (!evidence) return reject(\"evidence is empty\");\n\t\t\tif (evidence.length > MAX_BLOCKER_EVIDENCE_LENGTH) return reject(\"evidence is too long\");\n\t\t\tif (!Number.isInteger(repeatedTurns)) return reject(\"repeated_turns must be a whole number\");\n\t\t\tif (repeatedTurns < 3) return reject(\"repeated_turns must be at least 3\");\n\n\t\t\tupdateGoalUsage(blockedGoal, ctx);\n\t\t\tcancelContinuationWork();\n\t\t\tclearBudgetWrapUp();\n\t\t\tclearGoalRecoveryForGoal(blockedGoal.id);\n\t\t\tblockStaleGoalToolCalls();\n\t\t\truntime.activeGoal = transitionGoal(blockedGoal, \"blocked\");\n\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t\tctx.ui.notify(`Goal blocked: ${truncateNotification(reason)}`, \"warning\");\n\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: `Goal blocked: ${reason}` }],\n\t\t\t\tdetails: {\n\t\t\t\t\tgoal,\n\t\t\t\t\tgoal_id: requestedGoalId,\n\t\t\t\t\treason,\n\t\t\t\t\tevidence,\n\t\t\t\t\trepeated_turns: repeatedTurns,\n\t\t\t\t} satisfies GoalBlockedDetails,\n\t\t\t\tterminate: true,\n\t\t\t};\n\t\t},\n\t});\n\n\tpi.registerTool(goalCompleteTool);\n\tpi.registerTool(goalBlockedTool);\n\t// Do not touch the active tool set during factory registration: ExtensionAPI\n\t// actions are unbound until the session binds the runtime. session_start applies\n\t// baseline visibility once actions work; later hooks only enforce goal safety.\n\n\tpi.registerCommand(\"goal\", {\n\t\tdescription: \"Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>\",\n\t\tgetArgumentCompletions: (prefix) =>\n\t\t\tcompleteGoalArguments(prefix, {\n\t\t\t\texperimentalGoals: runtime.settings.experimental.goals,\n\t\t\t}),\n\t\thandler: async (args, ctx) => {\n\t\t\tconst result = parseCommand(args, {\n\t\t\t\texperimentalGoals: runtime.settings.experimental.goals,\n\t\t\t});\n\t\t\tif (typeof result === \"string\") {\n\t\t\t\tctx.ui.notify(result, \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (runtime.queueFrozen) {\n\t\t\t\tif (result.kind === \"show\") commands.showGoal(ctx);\n\t\t\t\telse if (result.kind === \"clear\") commands.clearGoal(ctx);\n\t\t\t\telse commands.notifyFrozenQueue(ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (runtime.pendingQueueAction && result.kind !== \"show\" && result.kind !== \"clear\") {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\"A queued goal change is waiting for Pi to settle. Retry after it finishes.\",\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tswitch (result.kind) {\n\t\t\t\tcase \"show\":\n\t\t\t\t\tcommands.showGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"pause\":\n\t\t\t\t\tcommands.pauseGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"resume\":\n\t\t\t\t\tawait commands.resumeGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"clear\":\n\t\t\t\t\tcommands.clearGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"edit\":\n\t\t\t\t\tawait commands.editGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"add\":\n\t\t\t\t\tawait commands.addGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"prioritize\":\n\t\t\t\t\tawait commands.prioritizeGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"drop-last\":\n\t\t\t\t\tcommands.dropLastGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"skip\":\n\t\t\t\t\tawait commands.skipGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"start\":\n\t\t\t\t\tawait commands.startGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t},\n\t});\n\n\tpi.on(\"session_start\", async (_event, ctx) => {\n\t\tclearCompletionStatusTimer();\n\t\tclearStatusRefreshTimer(); // lunr\n\t\tclearContinuationTracking();\n\t\tclearPendingGoalPrompts();\n\t\truntime.agentRunGoalId = undefined;\n\t\tclearGoalRecovery();\n\t\tclearBudgetWrapUp();\n\t\tclearStaleGoalToolCallBlock();\n\t\truntime.queuedGoals = [];\n\t\truntime.pendingQueueAction = undefined;\n\t\truntime.queueFrozen = false;\n\t\tconst previousToolVisibility = runtime.settings.toolVisibility;\n\t\tconst settingsResult = readGoalSettings(options.settingsPath);\n\t\truntime.settings =\n\t\t\tsettingsResult.kind === \"loaded\" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;\n\t\tif (settingsResult.kind === \"invalid\") {\n\t\t\tctx.ui.notify(\n\t\t\t\t`pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t}\n\t\tif (runtime.settings.experimental.goals) {\n\t\t\tctx.ui.notify(EXPERIMENTAL_GOALS_WARNING, \"warning\");\n\t\t}\n\t\tif (\n\t\t\truntime.settings.toolVisibility === \"after-first-goal\" &&\n\t\t\tpreviousToolVisibility === \"always\"\n\t\t) {\n\t\t\truntime.goalToolsUnlocked = false;\n\t\t}\n\t\tif (runtime.settings.toolVisibility === \"always\") {\n\t\t\tif (runtime.goalToolsHiddenByPolicy.size > 0) {\n\t\t\t\ttry {\n\t\t\t\t\trestoreGoalToolsHiddenByPolicy();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\t`Could not restore always-visible goal tools: ${formatError(error)}`,\n\t\t\t\t\t\t\"error\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\truntime.goalToolsUnlocked = true;\n\t\t}\n\n\t\tconst loaded = loadGoalStateFromSession(ctx);\n\t\truntime.activeGoal = loaded.goal;\n\t\truntime.queuedGoals = loaded.queue;\n\t\truntime.pendingQueueAction = loaded.pendingAction;\n\t\truntime.queueFrozen = loaded.hasExperimentalQueueState && !runtime.settings.experimental.goals;\n\t\tif (runtime.queueFrozen) {\n\t\t\tif (runtime.activeGoal) persistGoal(runtime.activeGoal);\n\t\t\tctx.ui.setStatus(STATUS_KEY, \"queue off\");\n\t\t\tctx.ui.notify(\n\t\t\t\t\"An experimental goal queue is frozen because experimental.goals is disabled. Re-enable it and run /reload to continue, or use /goal clear.\",\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tlet startRestoredQueuedGoal = false;\n\t\tif (runtime.activeGoal?.status === \"queued\" && !runtime.pendingQueueAction) {\n\t\t\truntime.activeGoal = activateQueuedGoal(runtime.activeGoal, currentTokenTotal(ctx));\n\t\t\tstartRestoredQueuedGoal = runtime.activeGoal.status === \"active\";\n\t\t}\n\t\tif (runtime.pendingQueueAction) await dispatchPendingQueueActionIfSettled(ctx);\n\t\tif (runtime.activeGoal) {\n\t\t\tif (runtime.activeGoal.status === \"active\") {\n\t\t\t\tupdateGoalUsage(runtime.activeGoal, ctx);\n\t\t\t\tif (limitActiveGoalForBudget(ctx, false)) return;\n\t\t\t}\n\t\t\tif (runtime.settings.toolVisibility === \"after-first-goal\") {\n\t\t\t\t// Registered tools are already active on an unrestricted fresh runtime.\n\t\t\t\t// If an earlier session_start handler removed them, that restrictive\n\t\t\t\t// policy wins: mark lazy visibility unlocked without widening its set.\n\t\t\t\truntime.goalToolsUnlocked = true;\n\t\t\t\truntime.goalToolsHiddenByPolicy.clear();\n\t\t\t}\n\t\t\tif (runtime.activeGoal.status === \"active\" && !goalToolsAvailable()) {\n\t\t\t\tpauseGoalForUnavailableTools(ctx, false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t\tif (startRestoredQueuedGoal) {\n\t\t\t\tconst restoredGoal = runtime.activeGoal;\n\t\t\t\tconst sent = await sendOwnedGoalPrompt(\n\t\t\t\t\truntime.pi,\n\t\t\t\t\tctx,\n\t\t\t\t\trestoredGoal.id,\n\t\t\t\t\tbuildGoalPrompt(restoredGoal),\n\t\t\t\t);\n\t\t\t\tif (!sent && runtime.activeGoal?.id === restoredGoal.id) {\n\t\t\t\t\truntime.activeGoal = transitionGoal(restoredGoal, \"paused\");\n\t\t\t\t\tblockStaleGoalToolCalls();\n\t\t\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (runtime.settings.toolVisibility === \"after-first-goal\" && !runtime.goalToolsUnlocked) {\n\t\t\t\thideGoalToolsIfLocked();\n\t\t\t}\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t}\n\t});\n\n\tpi.on(\"session_shutdown\", (_event, ctx) => {\n\t\tif (runtime.activeGoal) {\n\t\t\tif (!runtime.queueFrozen && runtime.activeGoal.status === \"active\") {\n\t\t\t\tupdateGoalUsage(runtime.activeGoal, ctx, false);\n\t\t\t}\n\t\t\tpersistGoal(runtime.activeGoal);\n\t\t}\n\t\tclearContinuationTracking();\n\t\tclearPendingGoalPrompts();\n\t\truntime.agentRunGoalId = undefined;\n\t\tclearGoalRecovery();\n\t\tclearBudgetWrapUp();\n\t\tclearStaleGoalToolCallBlock();\n\t\truntime.activeGoal = undefined;\n\t\truntime.queuedGoals = [];\n\t\truntime.pendingQueueAction = undefined;\n\t\truntime.queueFrozen = false;\n\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\tclearCompletionStatusTimer();\n\t\tclearStatusRefreshTimer(); // lunr\n\t});\n\n\tpi.on(\"session_before_compact\", (event, ctx) => {\n\t\tif (runtime.queueFrozen) return;\n\t\tif (runtime.activeGoal?.status === \"budget_limited\") {\n\t\t\tif ((event as { willRetry?: boolean }).willRetry === true) return { cancel: true as const };\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal?.status !== \"active\") return;\n\t\tif (!updateGoalUsage(runtime.activeGoal, ctx)) return;\n\t\tcancelContinuationWork();\n\t\tpersistGoal(runtime.activeGoal);\n\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\tif (runtime.pendingQueueAction) return;\n\t\tif (limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };\n\t});\n\n\tpi.on(\"session_compact\", async (event, ctx) => {\n\t\tif (runtime.queueFrozen) return;\n\t\tif (runtime.activeGoal?.status !== \"active\") {\n\t\t\tclearGoalRecovery();\n\t\t\tif (runtime.pendingQueueAction) await dispatchPendingQueueActionIfSettled(ctx);\n\t\t\treturn;\n\t\t}\n\n\t\tconst restoredState = loadGoalStateFromSession(ctx);\n\t\tif (restoredState.goal?.id === runtime.activeGoal.id) {\n\t\t\truntime.activeGoal = restoredState.goal;\n\t\t\truntime.queuedGoals = restoredState.queue;\n\t\t\truntime.pendingQueueAction = restoredState.pendingAction;\n\t\t}\n\t\tconst usageRecorded = updateGoalUsage(runtime.activeGoal, ctx);\n\t\tif (usageRecorded) {\n\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t}\n\t\tif (runtime.pendingQueueAction) {\n\t\t\tawait dispatchPendingQueueActionIfSettled(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (!usageRecorded) return;\n\t\tif (limitActiveGoalForBudget(ctx, false)) return;\n\n\t\tconst wasPiRetry = isPiOwnedCompactionRetry(event, runtime.activeGoal.id);\n\t\tclearGoalRecoveryForGoal(runtime.activeGoal.id);\n\t\tif (wasPiRetry) return;\n\t\trequestContinuation(runtime.activeGoal);\n\t\t// Manual compaction does not emit agent_settled. This common dispatcher is\n\t\t// therefore the narrow fallback; threshold compaction leaves the intent for\n\t\t// agent_settled when Pi is still busy.\n\t\tdispatchContinuationIfSettled(ctx);\n\t});\n\n\tpi.on(\"input\", (event) => {\n\t\tif (event.source === \"extension\") {\n\t\t\tif (\n\t\t\t\tconsumeCancelledContinuationPrompt(event.text) ||\n\t\t\t\tconsumeStaleOwnedGoalPrompt(event.text)\n\t\t\t) {\n\t\t\t\treturn { action: \"handled\" as const };\n\t\t\t}\n\t\t\tif (runtime.queueFrozen) return;\n\t\t\tclearGoalRecovery();\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.queueFrozen) return;\n\t\tif (/^\\/goal(?:\\s|$)/u.test(event.text.trimStart())) return;\n\t\tclearGoalRecovery();\n\t\tclearBudgetWrapUp();\n\t\tclearStaleGoalToolCallBlock();\n\t});\n\n\t// lunr: the previous context-event filter dropped superseded budget\n\t// wrap-up messages from request context. That breaks Anthropic prefix\n\t// continuity (full cache miss from the cut). The wrap-up custom message\n\t// is small; keeping history unfiltered is cheaper than a cache rewrite.\n\t// keepBudgetWrapUpMessage remains on the runtime if a future token-saving\n\t// path can prove the wrap-up was never sent.\n\n\tpi.on(\"tool_call\", (event, ctx) => {\n\t\tif (runtime.queueFrozen) {\n\t\t\tif (!isGoalToolName(event.toolName)) return;\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason:\n\t\t\t\t\t\"The experimental goal queue is frozen. Re-enable experimental.goals and run /reload, or use /goal clear.\",\n\t\t\t};\n\t\t}\n\t\t// lunr: mask locked goal tools instead of removing them from the active\n\t\t// list (setActiveTools churn busts the tools+system cache prefix).\n\t\tif (isGoalToolName(event.toolName) && runtime.areGoalToolsLocked()) {\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: \"Goal tools are locked until a /goal is activated.\",\n\t\t\t};\n\t\t}\n\t\tif (\n\t\t\truntime.activeGoal?.status === \"budget_limited\" &&\n\t\t\truntime.budgetWrapUp?.goalId === runtime.activeGoal.id &&\n\t\t\tevent.toolName !== \"goal_complete\"\n\t\t) {\n\t\t\t// A blocked tool result would normally trigger another model call. Abort the\n\t\t\t// wrap-up instead so a tool-seeking model cannot create an unbounded loop.\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: \"Goal token budget is exhausted; only goal_complete is allowed during wrap-up.\",\n\t\t\t};\n\t\t}\n\t\tif (!runtime.staleGoalToolCallsBlocked) return;\n\t\tif (!runtime.activeGoal || !blocksStaleGoalToolCalls(runtime.activeGoal.status)) {\n\t\t\tclearStaleGoalToolCallBlock();\n\t\t\treturn;\n\t\t}\n\t\treturn {\n\t\t\tblock: true,\n\t\t\treason: \"Blocked stale /goal tool call after the goal stopped or was interrupted.\",\n\t\t};\n\t});\n\n\tpi.on(\"tool_execution_end\", (_event, ctx) => {\n\t\tif (runtime.queueFrozen) return;\n\t\tif (\n\t\t\truntime.activeGoal?.status === \"budget_limited\" &&\n\t\t\truntime.budgetWrapUp?.goalId === runtime.activeGoal.id &&\n\t\t\t!runtime.budgetWrapUp.delivered\n\t\t) {\n\t\t\tqueueBudgetWrapUp(ctx, runtime.activeGoal);\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal?.status !== \"active\") return;\n\n\t\t// AgentSession persists assistant message_end before tool execution events,\n\t\t// so the completed assistant call's usage is authoritative at this boundary.\n\t\tif (!updateGoalUsage(runtime.activeGoal, ctx)) return;\n\t\tpersistGoal(runtime.activeGoal);\n\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\tif (limitActiveGoalForBudget(ctx, true)) return;\n\t\tif (!goalToolsAvailable()) pauseGoalForUnavailableTools(ctx);\n\t});\n\n\tpi.on(\"before_agent_start\", (event, ctx) => {\n\t\tif (runtime.queueFrozen) {\n\t\t\truntime.agentRunGoalId = undefined;\n\t\t\treturn;\n\t\t}\n\t\tconst goalPromptGoalId = consumePendingGoalPrompt(event.prompt);\n\t\tconst continuationGoalId = goalPromptGoalId ? undefined : markContinuationStarted(event.prompt);\n\t\tconst ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;\n\t\tconst activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n\t\tconst activeGoalRecovery = runtime.hasActiveGoalRecovery();\n\t\t// lunr: auto-resume a usage_limited goal on a wake-up turn. Two triggers:\n\t\t// - resumeAfter was parsed from the provider error and has elapsed (any turn\n\t\t// resumes — the reset time is known, so the goal should not stay parked);\n\t\t// - no reset time was parseable: only a cron-fired turn resumes (the user\n\t\t// scheduled the wake-up explicitly; ordinary manual turns don't hijack —\n\t\t// /goal resume stays the manual path).\n\t\t// Gateway cron fires are headless and cannot see this session's goal.\n\t\tconst resumeAfter = runtime.activeGoal?.resumeAfter;\n\t\tconst resumeDue = resumeAfter !== undefined && Date.now() >= resumeAfter;\n\t\tconst cronWakeUp = resumeAfter === undefined && isCronFire();\n\t\tif (\n\t\t\truntime.activeGoal?.status === \"usage_limited\" &&\n\t\t\t(resumeDue || cronWakeUp) &&\n\t\t\t!ownedPromptGoalId &&\n\t\t\t!activeBudgetWrapUp &&\n\t\t\t!activeGoalRecovery\n\t\t) {\n\t\t\tconst resumed = runtime.reactivateGoalForResume(ctx);\n\t\t\tif (resumed) {\n\t\t\t\truntime.agentRunGoalId = resumed.id;\n\t\t\t\tif (!goalToolsAvailable()) {\n\t\t\t\t\tpauseGoalForUnavailableTools(ctx, false);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tsystemPrompt: event.systemPrompt + \"\\n\\n\" + buildGoalSystemPrompt(runtime.activeGoal),\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\truntime.pendingQueueAction?.kind === \"prioritize\" &&\n\t\t\t!activeBudgetWrapUp &&\n\t\t\t!activeGoalRecovery\n\t\t) {\n\t\t\t// A turn that starts after priority intent is committed belongs to neither\n\t\t\t// the displaced goal nor the not-yet-activated urgent goal. Persist the\n\t\t\t// displaced goal's final accounting boundary so reload cannot absorb this run.\n\t\t\tif (!runtime.pendingQueueAction.displacedUsageFinalized) {\n\t\t\t\tif (runtime.activeGoal?.status === \"active\") {\n\t\t\t\t\tupdateGoalUsage(runtime.activeGoal, ctx, false);\n\t\t\t\t}\n\t\t\t\truntime.pendingQueueAction.displacedUsageFinalized = true;\n\t\t\t\tif (runtime.activeGoal) {\n\t\t\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t\t\t}\n\t\t\t}\n\t\t\truntime.agentRunGoalId = null;\n\t\t\tif (ownedPromptGoalId) abortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (activeBudgetWrapUp && runtime.activeGoal) {\n\t\t\truntime.agentRunGoalId = runtime.activeGoal.id;\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\truntime.pendingQueueAction?.kind === \"advance\" &&\n\t\t\truntime.pendingQueueAction.goalId === runtime.activeGoal?.id\n\t\t) {\n\t\t\truntime.agentRunGoalId = ownedPromptGoalId ?? runtime.activeGoal.id;\n\t\t\tif (ownedPromptGoalId) abortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {\n\t\t\truntime.agentRunGoalId = ownedPromptGoalId;\n\t\t\tif (runtime.activeGoal?.status === \"active\" && !goalToolsAvailable()) {\n\t\t\t\tpauseGoalForUnavailableTools(ctx, false);\n\t\t\t}\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal?.status !== \"active\") {\n\t\t\truntime.agentRunGoalId = undefined;\n\t\t\treturn;\n\t\t}\n\t\truntime.agentRunGoalId = runtime.activeGoal.id;\n\t\tif (!goalToolsAvailable()) {\n\t\t\tpauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);\n\t\t\treturn;\n\t\t}\n\n\t\treturn {\n\t\t\tsystemPrompt: `${event.systemPrompt}\\n\\n${buildGoalSystemPrompt(runtime.activeGoal)}`,\n\t\t};\n\t});\n\n\tpi.on(\"agent_end\", (event, ctx) => {\n\t\tif (runtime.queueFrozen) return;\n\t\tconst agentRunGoalId = runtime.agentRunGoalId;\n\t\truntime.agentRunGoalId = undefined;\n\t\tif (\n\t\t\tagentRunGoalId === null ||\n\t\t\t(!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp())\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tif (agentRunGoalId && agentRunGoalId !== runtime.activeGoal?.id) return;\n\t\tif (!runtime.activeGoal) return;\n\t\tif (\n\t\t\truntime.activeGoal.status === \"budget_limited\" &&\n\t\t\truntime.budgetWrapUp?.goalId === runtime.activeGoal.id\n\t\t) {\n\t\t\tupdateGoalUsage(runtime.activeGoal, ctx);\n\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t\tclearBudgetWrapUp();\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal.status !== \"active\") return;\n\t\tif (\n\t\t\truntime.pendingQueueAction?.kind === \"advance\" &&\n\t\t\truntime.pendingQueueAction.goalId === runtime.activeGoal.id\n\t\t) {\n\t\t\tupdateGoalUsage(runtime.activeGoal, ctx);\n\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t\treturn;\n\t\t}\n\n\t\tconst goalId = runtime.activeGoal.id;\n\t\tconst alreadyAwaitingContinuation = hasContinuationWorkForGoal(goalId);\n\t\tconst finalAssistant = findFinalAssistantMessage(event.messages);\n\n\t\tif (!alreadyAwaitingContinuation) runtime.activeGoal = incrementGoal(runtime.activeGoal);\n\t\tupdateGoalUsage(runtime.activeGoal, ctx);\n\n\t\tif (finalAssistant?.stopReason === \"aborted\") {\n\t\t\tclearGoalRecoveryForGoal(goalId);\n\t\t\tstopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, \"paused\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (finalAssistant?.stopReason === \"error\") {\n\t\t\tif (isRetryableGoalInterruption(finalAssistant)) {\n\t\t\t\tif (limitActiveGoalForBudget(ctx, false)) return;\n\t\t\t\tif (!goalToolsAvailable()) {\n\t\t\t\t\tpauseGoalForUnavailableTools(ctx);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\truntime.goalRecovery = {\n\t\t\t\t\tgoalId,\n\t\t\t\t\tkind: isGoalContextOverflow(finalAssistant) ? \"compaction_retry\" : \"provider_retry\",\n\t\t\t\t};\n\t\t\t\tcancelContinuationWork();\n\t\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tclearGoalRecoveryForGoal(goalId);\n\t\t\tstopGoalAfterAgentEnd(\n\t\t\t\tctx,\n\t\t\t\truntime.activeGoal,\n\t\t\t\tfinalAssistant,\n\t\t\t\tisUsageLimitedGoalInterruption(finalAssistant) ? \"usage_limited\" : \"blocked\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tclearGoalRecoveryForGoal(goalId);\n\n\t\tif (limitActiveGoalForBudget(ctx, false)) return;\n\t\tif (!goalToolsAvailable()) {\n\t\t\tpauseGoalForUnavailableTools(ctx);\n\t\t\treturn;\n\t\t}\n\n\t\tpersistGoal(runtime.activeGoal);\n\t\tupdateStatus(ctx, runtime.activeGoal);\n\n\t\tconst currentGoal = runtime.activeGoal;\n\t\tif (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== \"active\") return;\n\t\tif (runtime.pendingQueueAction?.kind === \"prioritize\") return;\n\t\trequestContinuation(currentGoal);\n\t});\n\n\tpi.on(\"agent_settled\", (_event, ctx) => {\n\t\tif (runtime.queueFrozen) return;\n\t\tif (!runtime.pendingQueueAction) {\n\t\t\tdispatchContinuationIfSettled(ctx);\n\t\t\treturn;\n\t\t}\n\t\treturn dispatchPendingQueueActionIfSettled(ctx).then((dispatched) => {\n\t\t\tif (!dispatched) dispatchContinuationIfSettled(ctx);\n\t\t});\n\t});\n\n\tfunction hasPendingSkipForGoal(goalId: string) {\n\t\treturn (\n\t\t\truntime.pendingQueueAction?.kind === \"advance\" &&\n\t\t\truntime.pendingQueueAction.reason === \"skip\" &&\n\t\t\truntime.pendingQueueAction.goalId === goalId\n\t\t);\n\t}\n\n\tfunction stopGoalAfterAgentEnd(\n\t\tctx: StatusContext,\n\t\tgoal: ActiveGoal,\n\t\tassistant: AssistantMessageLike,\n\t\tstatus: \"paused\" | \"blocked\" | \"usage_limited\",\n\t) {\n\t\tcancelContinuationWork();\n\t\tclearBudgetWrapUp();\n\t\tblockStaleGoalToolCalls();\n\t\tabortCurrentTurn(ctx);\n\t\t// lunr: if the provider error carries a reset time, pre-fill resumeAfter so a\n\t\t// one-shot /cron wake-up auto-resumes the goal without a manual /goal resume.\n\t\tconst resumeAfter = status === \"usage_limited\" ? parseUsageResetTimeMs(assistant.errorMessage) : undefined;\n\t\tconst goalWithResume = resumeAfter !== undefined ? { ...goal, resumeAfter } : goal;\n\t\truntime.activeGoal = transitionGoal(goalWithResume, status);\n\t\tpersistGoal(runtime.activeGoal);\n\t\tupdateStatus(ctx, runtime.activeGoal);\n\n\t\tconst details = assistant.errorMessage\n\t\t\t? ` (${truncateNotification(assistant.errorMessage)})`\n\t\t\t: \"\";\n\t\tif (status === \"paused\") {\n\t\t\tctx.ui.notify(\n\t\t\t\t`Goal paused after interruption${details}. Run /goal resume to continue.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (status === \"usage_limited\") {\n\t\t\tconst when = resumeAfter !== undefined ? ` Auto-resume scheduled for ${new Date(resumeAfter).toLocaleString()}.` : \"\";\n\t\t\tctx.ui.notify(\n\t\t\t\t`Goal usage-limited${details}.${when} Run /goal resume when usage resets, or schedule a one-shot /cron firing \"continue\" into this session to wake it.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tctx.ui.notify(\n\t\t\t`Goal blocked after agent error${details}. Resolve the blocker or run /goal resume to retry.`,\n\t\t\t\"warning\",\n\t\t);\n\t}\n}\n\nexport default function goal(pi: ExtensionAPI, options: GoalOptions = {}) {\n\tregisterGoalRuntime(pi, options);\n}\n\nexport {\n\tassistantUsageTokens,\n\tcumulativeAssistantTokens,\n\tformatDuration,\n\tformatTokenCount,\n} from \"./accounting.js\";\n\nexport {\n\tcompleteGoalArguments,\n\tparseCommand,\n\tparseTokenBudget,\n\tvalidateObjective,\n} from \"./command.js\";\n\nexport { buildGoalSystemPrompt } from \"./prompts.js\";\n\nexport {\n\tfindFinalAssistantMessage,\n\tformatStatus,\n\tisContradictoryCompletionSummary,\n\tisRetryableGoalInterruption,\n\tisUsageLimitedGoalInterruption,\n} from \"./runtime.js\";\n"]}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AE,CAAC,MAAM,CACZ,iCAAiC,OAAO,qDAAqD,EAC7F,SAAS,CACT,CAAC;IAAA,CACF;AAAA,CACD;AAED,MAAM,CAAC,OAAO,UAAU,IAAI,CAAC,EAAgB,EAAE,OAAO,GAAgB,EAAE,EAAE;IACzE,mBAAmB,CAAC,EAAE,EAAE,OAAO,CAAC,CAAC;AAAA,CACjC;AAED,OAAO,EACN,oBAAoB,EACpB,yBAAyB,EACzB,cAAc,EACd,gBAAgB,GAChB,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EACN,qBAAqB,EACrB,YAAY,EACZ,gBAAgB,EAChB,iBAAiB,GACjB,MAAM,cAAc,CAAC;AAEtB,OAAO,EAAE,qBAAqB,EAAE,MAAM,cAAc,CAAC;AAErD,OAAO,EACN,yBAAyB,EACzB,YAAY,EACZ,gCAAgC,EAChC,2BAA2B,EAC3B,8BAA8B,GAC9B,MAAM,cAAc,CAAC","sourcesContent":["// @ts-nocheck\n// lunr: defineTool imported from the concrete module, NOT the package barrel —\n// the barrel re-exports main.ts which imports this extension (cycle).\nimport { defineTool } from \"../../../core/extensions/types.js\";\nimport { isCronFire } from \"../../../core/cron/fire-guard.js\";\nimport type { ExtensionAPI } from \"@ashx-j/lunr\";\nimport { Type } from \"typebox\";\nimport { Container, Markdown, Text } from \"@ashx-j/lunr-tui\";\nimport { currentTokenTotal } from \"./accounting.js\";\nimport { completeGoalArguments, parseCommand } from \"./command.js\";\nimport { GoalCommandController } from \"./commands.js\";\nimport { type ActiveGoal, loadGoalStateFromSession } from \"./persistence.js\";\nimport { buildGoalPrompt, buildGoalSystemPrompt } from \"./prompts.js\";\nimport { activateQueuedGoal } from \"./queue.js\";\nimport {\n\ttype AssistantMessageLike,\n\tabortCurrentTurn,\n\tblocksStaleGoalToolCalls,\n\tfindFinalAssistantMessage,\n\tformatError,\n\tformatStatus,\n\tGOAL_BLOCKED_TOOL,\n\tGOAL_COMPLETE_TOOL,\n\tGoalRuntime,\n\tgoalIdRejectionReason,\n\tincrementGoal,\n\tisContradictoryCompletionSummary,\n\tisGoalContextOverflow,\n\tisRetryableGoalInterruption,\n\tisUsageLimitedGoalInterruption,\n\tparseUsageResetTimeMs,\n\tSTATUS_KEY,\n\ttype StatusContext,\n\ttransitionGoal,\n\ttruncateNotification,\n} from \"./runtime.js\";\nimport { DEFAULT_GOAL_SETTINGS, readGoalSettings } from \"./settings.js\";\n\n// goal.ts is the Pi-facing composition root: it keeps tool contracts and event\n// ordering together. Per-session mechanisms live in runtime.ts, while user command\n// transitions live in commands.ts. Each factory constructs isolated instances.\n\ninterface GoalCompleteDetails {\n\tgoal: string;\n\tgoal_id: string;\n\tsummary: string;\n}\n\ninterface GoalBlockedDetails {\n\tgoal: string;\n\tgoal_id: string;\n\treason: string;\n\tevidence: string;\n\trepeated_turns: number;\n}\n\ninterface GoalOptions {\n\tsettingsPath?: string;\n}\n\nconst GOAL_COMPLETE_MESSAGE_TYPE = \"goal-complete\";\nconst EXPERIMENTAL_GOALS_WARNING =\n\t\"Experimental ordered goals are enabled for pi-goal. Queue behavior and persisted state may change.\";\nconst MAX_BLOCKER_REASON_LENGTH = 1_000;\nconst MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;\n\nfunction registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {\n\tconst runtime = new GoalRuntime(pi);\n\tconst commands = new GoalCommandController(runtime);\n\n\t// Bind per-factory runtime operations once so event orchestration stays concise\n\t// without reintroducing module-global mutable state.\n\tconst clearCompletionStatusTimer = runtime.clearCompletionStatusTimer.bind(runtime);\n\t// lunr: footer refresh timer cleanup\n\tconst clearStatusRefreshTimer = runtime.clearStatusRefreshTimer.bind(runtime);\n\tconst clearContinuationTracking = runtime.clearContinuationTracking.bind(runtime);\n\tconst clearPendingGoalPrompts = runtime.clearPendingGoalPrompts.bind(runtime);\n\tconst clearGoalRecovery = runtime.clearGoalRecovery.bind(runtime);\n\tconst clearBudgetWrapUp = runtime.clearBudgetWrapUp.bind(runtime);\n\tconst clearStaleGoalToolCallBlock = runtime.clearStaleGoalToolCallBlock.bind(runtime);\n\tconst persistGoal = runtime.persistGoal.bind(runtime);\n\tconst updateGoalUsage = runtime.recordGoalUsage.bind(runtime);\n\tconst updateStatus = runtime.updateStatus.bind(runtime);\n\tconst limitActiveGoalForBudget = runtime.limitActiveGoalForBudget.bind(runtime);\n\tconst hideGoalToolsIfLocked = runtime.hideGoalToolsIfLocked.bind(runtime);\n\tconst goalToolsAvailable = runtime.goalToolsAvailable.bind(runtime);\n\tconst pauseGoalForUnavailableTools = runtime.pauseGoalForUnavailableTools.bind(runtime);\n\tconst isPiOwnedCompactionRetry = runtime.isPiOwnedCompactionRetry.bind(runtime);\n\tconst requestContinuation = runtime.requestContinuation.bind(runtime);\n\tconst dispatchContinuationIfSettled = runtime.dispatchContinuationIfSettled.bind(runtime);\n\tconst isGoalToolName = runtime.isGoalToolName.bind(runtime);\n\tconst queueBudgetWrapUp = runtime.queueBudgetWrapUp.bind(runtime);\n\tconst clearGoalRecoveryForGoal = runtime.clearGoalRecoveryForGoal.bind(runtime);\n\tconst blockStaleGoalToolCalls = runtime.blockStaleGoalToolCalls.bind(runtime);\n\tconst cancelContinuationWork = runtime.cancelContinuationWork.bind(runtime);\n\tconst consumeCancelledContinuationPrompt =\n\t\truntime.consumeCancelledContinuationPrompt.bind(runtime);\n\tconst consumeStaleOwnedGoalPrompt = runtime.consumeStaleOwnedGoalPrompt.bind(runtime);\n\tconst consumePendingGoalPrompt = runtime.consumeOwnedGoalPrompt.bind(runtime);\n\tconst markContinuationStarted = runtime.markContinuationStarted.bind(runtime);\n\tconst hasContinuationWorkForGoal = runtime.hasContinuationWorkForGoal.bind(runtime);\n\tconst clearActiveGoal = runtime.clearActiveGoal.bind(runtime);\n\tconst showCompletionStatus = runtime.showCompletionStatus.bind(runtime);\n\tconst restoreGoalToolsHiddenByPolicy = runtime.restoreGoalToolsHiddenByPolicy.bind(runtime);\n\tconst sendOwnedGoalPrompt = (\n\t\t_pi: ExtensionAPI,\n\t\tctx: StatusContext,\n\t\tgoalId: string,\n\t\tprompt: string,\n\t) => runtime.sendOwnedGoalPrompt(ctx, goalId, prompt);\n\tconst dispatchPendingQueueActionIfSettled =\n\t\tcommands.dispatchPendingQueueActionIfSettled.bind(commands);\n\n\tconst emitGoalCompleteMessage = (summary: string) => {\n\t\tconst text = summary.startsWith(\"Goal complete\") ? summary : summary;\n\t\tpi.sendMessage({\n\t\t\tcustomType: GOAL_COMPLETE_MESSAGE_TYPE,\n\t\t\tcontent: [{ type: \"text\", text }],\n\t\t\tdisplay: true,\n\t\t});\n\t};\n\n\tpi.registerMessageRenderer(GOAL_COMPLETE_MESSAGE_TYPE, (message, _options, theme) => {\n\t\tconst raw =\n\t\t\ttypeof message.content === \"string\"\n\t\t\t\t? message.content\n\t\t\t\t: message.content\n\t\t\t\t\t\t.filter((block) => block.type === \"text\")\n\t\t\t\t\t\t.map((block) => (\"text\" in block ? block.text : \"\"))\n\t\t\t\t\t\t.join(\"\\n\");\n\t\tconst c = new Container();\n\t\tc.addChild(new Markdown(`● ${raw}`, 1, 0, undefined, {\n\t\t\tcolor: (content) => theme.fg(\"text\", content),\n\t\t}));\n\t\treturn c;\n\t});\n\n\tconst goalCompleteTool = defineTool({\n\t\tname: GOAL_COMPLETE_TOOL,\n\t\tlabel: \"Goal Complete\",\n\t\tdescription:\n\t\t\t\"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.\",\n\t\tpromptSnippet:\n\t\t\t\"Mark the active /goal as complete after fully finishing and verifying it, with the current goal_id\",\n\t\tpromptGuidelines: [\n\t\t\t\"When a /goal is active, keep working until the goal is complete; do not stop with only a plan or partial progress.\",\n\t\t\t\"Before calling goal_complete, audit the active goal requirement by requirement against the current files, command output, tests, or external state.\",\n\t\t\t\"Pass the exact goal_id shown in the current /goal prompt; never reuse a goal_id from an older, stopped, replaced, or cleared turn.\",\n\t\t\t\"Call goal_complete only after the requested goal is fully implemented, verified, and no known required work remains; otherwise keep working.\",\n\t\t],\n\t\tparameters: Type.Object({\n\t\t\tgoal_id: Type.String({\n\t\t\t\tdescription:\n\t\t\t\t\t\"The exact goal_id shown in the current active /goal prompt. Used only to reject stale completion calls from older turns.\",\n\t\t\t}),\n\t\t\tsummary: Type.String({\n\t\t\t\tdescription:\n\t\t\t\t\t\"State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work.\",\n\t\t\t}),\n\t\t}),\n\t\tasync execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n\t\t\tconst completedGoal = runtime.activeGoal;\n\t\t\tconst goal = completedGoal?.text ?? \"unknown goal\";\n\t\t\tconst requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n\t\t\tconst summary = typeof params.summary === \"string\" ? params.summary.trim() : \"\";\n\n\t\t\tif (!completedGoal) {\n\t\t\t\tconst rejection = \"Goal completion rejected: no active goal.\";\n\t\t\t\tctx.ui.notify(rejection, \"warning\");\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: rejection }],\n\t\t\t\t\tdetails: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n\t\t\tif (!runtime.canRecordGoalUsage() && !completingDuringBudgetWrapUp) {\n\t\t\t\tconst rejection = \"Goal completion rejected: current run does not own the active goal.\";\n\t\t\t\tctx.ui.notify(rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: rejection }],\n\t\t\t\t\tdetails: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (hasPendingSkipForGoal(completedGoal.id)) {\n\t\t\t\tupdateGoalUsage(completedGoal, ctx);\n\t\t\t\tpersistGoal(completedGoal);\n\t\t\t\tupdateStatus(ctx, completedGoal);\n\t\t\t\tclearBudgetWrapUp();\n\t\t\t\tconst rejection = \"Goal completion rejected: goal is queued to be skipped.\";\n\t\t\t\tctx.ui.notify(rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: rejection }],\n\t\t\t\t\tdetails: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,\n\t\t\t\t\tterminate: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);\n\t\t\tif (staleGoalRejection) {\n\t\t\t\tconst rejection = `Goal completion rejected: ${staleGoalRejection}.`;\n\t\t\t\tctx.ui.notify(rejection, \"warning\");\n\t\t\t\tif (completingDuringBudgetWrapUp) {\n\t\t\t\t\tupdateGoalUsage(completedGoal, ctx);\n\t\t\t\t\tpersistGoal(completedGoal);\n\t\t\t\t\tupdateStatus(ctx, completedGoal);\n\t\t\t\t\tclearBudgetWrapUp();\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: rejection }],\n\t\t\t\t\tdetails: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,\n\t\t\t\t\tterminate: completingDuringBudgetWrapUp || undefined,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (completedGoal.status !== \"active\" && !completingDuringBudgetWrapUp) {\n\t\t\t\tconst rejection = `Goal completion rejected: goal is ${completedGoal.status}, not active.`;\n\t\t\t\tctx.ui.notify(rejection, \"warning\");\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: rejection }],\n\t\t\t\t\tdetails: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst rejectionReason = !summary\n\t\t\t\t? \"summary is empty\"\n\t\t\t\t: isContradictoryCompletionSummary(summary)\n\t\t\t\t\t? \"summary says the goal is not complete\"\n\t\t\t\t\t: undefined;\n\t\t\tif (rejectionReason) {\n\t\t\t\tupdateGoalUsage(completedGoal, ctx);\n\t\t\t\tpersistGoal(completedGoal);\n\t\t\t\tupdateStatus(ctx, completedGoal);\n\t\t\t\tconst rejection = `Goal completion rejected: ${rejectionReason}.`;\n\t\t\t\tctx.ui.notify(rejection, \"warning\");\n\t\t\t\tif (completingDuringBudgetWrapUp) clearBudgetWrapUp();\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: rejection,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,\n\t\t\t\t\tterminate: completingDuringBudgetWrapUp || undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\truntime.activeGoal = transitionGoal(completedGoal, \"complete\");\n\t\t\tupdateGoalUsage(runtime.activeGoal, ctx);\n\t\t\tif (runtime.pendingQueueAction?.kind === \"prioritize\") {\n\t\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\t\tctx.ui.setStatus(STATUS_KEY, \"complete\");\n\t\t\t\temitGoalCompleteMessage(summary);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\", text: `Goal complete: ${summary}` }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tgoal,\n\t\t\t\t\t\tgoal_id: requestedGoalId,\n\t\t\t\t\t\tsummary,\n\t\t\t\t\t} satisfies GoalCompleteDetails,\n\t\t\t\t\tterminate: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (runtime.queuedGoals.length > 0) {\n\t\t\t\truntime.pendingQueueAction = {\n\t\t\t\t\tkind: \"advance\",\n\t\t\t\t\tgoalId: runtime.activeGoal.id,\n\t\t\t\t\treason: \"complete\",\n\t\t\t\t\tcompletedText: goal,\n\t\t\t\t};\n\t\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\t\tctx.ui.setStatus(STATUS_KEY, \"complete\");\n\t\t\t\temitGoalCompleteMessage(summary);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Goal complete: ${summary}\\nNext goal queued: ${runtime.queuedGoals[0]?.text}`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tgoal,\n\t\t\t\t\t\tgoal_id: requestedGoalId,\n\t\t\t\t\t\tsummary,\n\t\t\t\t\t} satisfies GoalCompleteDetails,\n\t\t\t\t\tterminate: true,\n\t\t\t\t};\n\t\t\t}\n\t\t\tpersistGoal(runtime.activeGoal);\n\n\t\t\tctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));\n\t\t\tclearActiveGoal(ctx);\n\t\t\tshowCompletionStatus(ctx);\n\t\t\temitGoalCompleteMessage(summary);\n\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: `Goal complete: ${summary}` }],\n\t\t\t\tdetails: { goal, goal_id: requestedGoalId, summary } satisfies GoalCompleteDetails,\n\t\t\t\tterminate: true,\n\t\t\t};\n\t\t},\n\t\trenderResult(_result, { isPartial }, theme) {\n\t\t\tif (isPartial) return new Text(theme.fg(\"warning\", \"Completing goal...\"), 0, 0);\n\t\t\treturn { render: () => [], invalidate() {} };\n\t\t},\n\t});\n\n\tconst goalBlockedTool = defineTool({\n\t\tname: GOAL_BLOCKED_TOOL,\n\t\tlabel: \"Goal Blocked\",\n\t\tdescription:\n\t\t\t\"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.\",\n\t\tpromptSnippet:\n\t\t\t\"Mark the active /goal blocked only after the same blocker recurs for three consecutive goal turns\",\n\t\tpromptGuidelines: [\n\t\t\t\"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.\",\n\t\t\t\"After a blocked goal is resumed, start a fresh three-turn blocker audit before using goal_blocked again.\",\n\t\t\t\"Do not use goal_blocked for ordinary clarification, incomplete work, uncertainty, difficult tasks, or recoverable tool/provider failures.\",\n\t\t\t\"Pass goal_blocked the exact current goal_id; never reuse a goal_id from an older, stopped, replaced, or cleared goal turn.\",\n\t\t],\n\t\tparameters: Type.Object({\n\t\t\tgoal_id: Type.String({\n\t\t\t\tdescription: \"The exact goal_id shown in the current active /goal prompt.\",\n\t\t\t}),\n\t\t\treason: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_BLOCKER_REASON_LENGTH,\n\t\t\t\tdescription: \"The specific user or external action required to unblock the goal.\",\n\t\t\t}),\n\t\t\tevidence: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_BLOCKER_EVIDENCE_LENGTH,\n\t\t\t\tdescription: \"Concrete evidence from the repeated attempts that proves the impasse.\",\n\t\t\t}),\n\t\t\trepeated_turns: Type.Integer({\n\t\t\t\tminimum: 3,\n\t\t\t\tdescription: \"Number of separate turns spent trying to resolve this same blocker.\",\n\t\t\t}),\n\t\t}),\n\t\tasync execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n\t\t\tconst blockedGoal = runtime.activeGoal;\n\t\t\tconst goal = blockedGoal?.text ?? \"unknown goal\";\n\t\t\tconst requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n\t\t\tconst reason = typeof params.reason === \"string\" ? params.reason.trim() : \"\";\n\t\t\tconst evidence = typeof params.evidence === \"string\" ? params.evidence.trim() : \"\";\n\t\t\tconst repeatedTurns =\n\t\t\t\ttypeof params.repeated_turns === \"number\" ? params.repeated_turns : Number.NaN;\n\t\t\tconst reject = (rejectionReason: string, terminate = false) => {\n\t\t\t\tconst rejection = `goal_blocked rejected: ${rejectionReason}.`;\n\t\t\t\tctx.ui.notify(rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [{ type: \"text\" as const, text: rejection }],\n\t\t\t\t\tdetails: {\n\t\t\t\t\t\tgoal,\n\t\t\t\t\t\tgoal_id: requestedGoalId,\n\t\t\t\t\t\treason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),\n\t\t\t\t\t\tevidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),\n\t\t\t\t\t\trepeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,\n\t\t\t\t\t} satisfies GoalBlockedDetails,\n\t\t\t\t\t...(terminate ? { terminate: true as const } : {}),\n\t\t\t\t};\n\t\t\t};\n\n\t\t\tif (!blockedGoal) return reject(\"no active goal\");\n\t\t\tif (!runtime.canRecordGoalUsage()) {\n\t\t\t\treturn reject(\"current run does not own the active goal\");\n\t\t\t}\n\t\t\tif (hasPendingSkipForGoal(blockedGoal.id)) {\n\t\t\t\tupdateGoalUsage(blockedGoal, ctx);\n\t\t\t\tpersistGoal(blockedGoal);\n\t\t\t\tupdateStatus(ctx, blockedGoal);\n\t\t\t\tclearBudgetWrapUp();\n\t\t\t\treturn reject(\"goal is queued to be skipped\", true);\n\t\t\t}\n\t\t\tconst staleGoalRejection = goalIdRejectionReason(blockedGoal, requestedGoalId);\n\t\t\tif (staleGoalRejection) return reject(staleGoalRejection);\n\t\t\tif (blockedGoal.status !== \"active\") {\n\t\t\t\treturn reject(`goal is ${blockedGoal.status}, not active`);\n\t\t\t}\n\t\t\tif (!reason) return reject(\"reason is empty\");\n\t\t\tif (reason.length > MAX_BLOCKER_REASON_LENGTH) return reject(\"reason is too long\");\n\t\t\tif (!evidence) return reject(\"evidence is empty\");\n\t\t\tif (evidence.length > MAX_BLOCKER_EVIDENCE_LENGTH) return reject(\"evidence is too long\");\n\t\t\tif (!Number.isInteger(repeatedTurns)) return reject(\"repeated_turns must be a whole number\");\n\t\t\tif (repeatedTurns < 3) return reject(\"repeated_turns must be at least 3\");\n\n\t\t\tupdateGoalUsage(blockedGoal, ctx);\n\t\t\tcancelContinuationWork();\n\t\t\tclearBudgetWrapUp();\n\t\t\tclearGoalRecoveryForGoal(blockedGoal.id);\n\t\t\tblockStaleGoalToolCalls();\n\t\t\truntime.activeGoal = transitionGoal(blockedGoal, \"blocked\");\n\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t\tctx.ui.notify(`Goal blocked: ${truncateNotification(reason)}`, \"warning\");\n\n\t\t\treturn {\n\t\t\t\tcontent: [{ type: \"text\", text: `Goal blocked: ${reason}` }],\n\t\t\t\tdetails: {\n\t\t\t\t\tgoal,\n\t\t\t\t\tgoal_id: requestedGoalId,\n\t\t\t\t\treason,\n\t\t\t\t\tevidence,\n\t\t\t\t\trepeated_turns: repeatedTurns,\n\t\t\t\t} satisfies GoalBlockedDetails,\n\t\t\t\tterminate: true,\n\t\t\t};\n\t\t},\n\t});\n\n\tpi.registerTool(goalCompleteTool);\n\tpi.registerTool(goalBlockedTool);\n\t// Do not touch the active tool set during factory registration: ExtensionAPI\n\t// actions are unbound until the session binds the runtime. session_start applies\n\t// baseline visibility once actions work; later hooks only enforce goal safety.\n\n\tpi.registerCommand(\"goal\", {\n\t\tdescription: \"Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>\",\n\t\tgetArgumentCompletions: (prefix) =>\n\t\t\tcompleteGoalArguments(prefix, {\n\t\t\t\texperimentalGoals: runtime.settings.experimental.goals,\n\t\t\t}),\n\t\thandler: async (args, ctx) => {\n\t\t\tconst result = parseCommand(args, {\n\t\t\t\texperimentalGoals: runtime.settings.experimental.goals,\n\t\t\t});\n\t\t\tif (typeof result === \"string\") {\n\t\t\t\tctx.ui.notify(result, \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (runtime.queueFrozen) {\n\t\t\t\tif (result.kind === \"show\") commands.showGoal(ctx);\n\t\t\t\telse if (result.kind === \"clear\") commands.clearGoal(ctx);\n\t\t\t\telse commands.notifyFrozenQueue(ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (runtime.pendingQueueAction && result.kind !== \"show\" && result.kind !== \"clear\") {\n\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\"A queued goal change is waiting for Pi to settle. Retry after it finishes.\",\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tswitch (result.kind) {\n\t\t\t\tcase \"show\":\n\t\t\t\t\tcommands.showGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"pause\":\n\t\t\t\t\tcommands.pauseGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"resume\":\n\t\t\t\t\tawait commands.resumeGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"clear\":\n\t\t\t\t\tcommands.clearGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"edit\":\n\t\t\t\t\tawait commands.editGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"add\":\n\t\t\t\t\tawait commands.addGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"prioritize\":\n\t\t\t\t\tawait commands.prioritizeGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"drop-last\":\n\t\t\t\t\tcommands.dropLastGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"skip\":\n\t\t\t\t\tawait commands.skipGoal(ctx);\n\t\t\t\t\treturn;\n\t\t\t\tcase \"start\":\n\t\t\t\t\tawait commands.startGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t},\n\t});\n\n\tpi.on(\"session_start\", async (_event, ctx) => {\n\t\tclearCompletionStatusTimer();\n\t\tclearStatusRefreshTimer(); // lunr\n\t\tclearContinuationTracking();\n\t\tclearPendingGoalPrompts();\n\t\truntime.agentRunGoalId = undefined;\n\t\tclearGoalRecovery();\n\t\tclearBudgetWrapUp();\n\t\tclearStaleGoalToolCallBlock();\n\t\truntime.queuedGoals = [];\n\t\truntime.pendingQueueAction = undefined;\n\t\truntime.queueFrozen = false;\n\t\tconst previousToolVisibility = runtime.settings.toolVisibility;\n\t\tconst settingsResult = readGoalSettings(options.settingsPath);\n\t\truntime.settings =\n\t\t\tsettingsResult.kind === \"loaded\" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;\n\t\tif (settingsResult.kind === \"invalid\") {\n\t\t\tctx.ui.notify(\n\t\t\t\t`pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t}\n\t\tif (runtime.settings.experimental.goals) {\n\t\t\tctx.ui.notify(EXPERIMENTAL_GOALS_WARNING, \"warning\");\n\t\t}\n\t\tif (\n\t\t\truntime.settings.toolVisibility === \"after-first-goal\" &&\n\t\t\tpreviousToolVisibility === \"always\"\n\t\t) {\n\t\t\truntime.goalToolsUnlocked = false;\n\t\t}\n\t\tif (runtime.settings.toolVisibility === \"always\") {\n\t\t\tif (runtime.goalToolsHiddenByPolicy.size > 0) {\n\t\t\t\ttry {\n\t\t\t\t\trestoreGoalToolsHiddenByPolicy();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tctx.ui.notify(\n\t\t\t\t\t\t`Could not restore always-visible goal tools: ${formatError(error)}`,\n\t\t\t\t\t\t\"error\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\truntime.goalToolsUnlocked = true;\n\t\t}\n\n\t\tconst loaded = loadGoalStateFromSession(ctx);\n\t\truntime.activeGoal = loaded.goal;\n\t\truntime.queuedGoals = loaded.queue;\n\t\truntime.pendingQueueAction = loaded.pendingAction;\n\t\truntime.queueFrozen = loaded.hasExperimentalQueueState && !runtime.settings.experimental.goals;\n\t\tif (runtime.queueFrozen) {\n\t\t\tif (runtime.activeGoal) persistGoal(runtime.activeGoal);\n\t\t\tctx.ui.setStatus(STATUS_KEY, \"queue off\");\n\t\t\tctx.ui.notify(\n\t\t\t\t\"An experimental goal queue is frozen because experimental.goals is disabled. Re-enable it and run /reload to continue, or use /goal clear.\",\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tlet startRestoredQueuedGoal = false;\n\t\tif (runtime.activeGoal?.status === \"queued\" && !runtime.pendingQueueAction) {\n\t\t\truntime.activeGoal = activateQueuedGoal(runtime.activeGoal, currentTokenTotal(ctx));\n\t\t\tstartRestoredQueuedGoal = runtime.activeGoal.status === \"active\";\n\t\t}\n\t\tif (runtime.pendingQueueAction) await dispatchPendingQueueActionIfSettled(ctx);\n\t\tif (runtime.activeGoal) {\n\t\t\tif (runtime.activeGoal.status === \"active\") {\n\t\t\t\tupdateGoalUsage(runtime.activeGoal, ctx);\n\t\t\t\tif (limitActiveGoalForBudget(ctx, false)) return;\n\t\t\t}\n\t\t\tif (runtime.settings.toolVisibility === \"after-first-goal\") {\n\t\t\t\t// Registered tools are already active on an unrestricted fresh runtime.\n\t\t\t\t// If an earlier session_start handler removed them, that restrictive\n\t\t\t\t// policy wins: mark lazy visibility unlocked without widening its set.\n\t\t\t\truntime.goalToolsUnlocked = true;\n\t\t\t\truntime.goalToolsHiddenByPolicy.clear();\n\t\t\t}\n\t\t\tif (runtime.activeGoal.status === \"active\" && !goalToolsAvailable()) {\n\t\t\t\tpauseGoalForUnavailableTools(ctx, false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t\tif (startRestoredQueuedGoal) {\n\t\t\t\tconst restoredGoal = runtime.activeGoal;\n\t\t\t\tconst sent = await sendOwnedGoalPrompt(\n\t\t\t\t\truntime.pi,\n\t\t\t\t\tctx,\n\t\t\t\t\trestoredGoal.id,\n\t\t\t\t\tbuildGoalPrompt(restoredGoal),\n\t\t\t\t);\n\t\t\t\tif (!sent && runtime.activeGoal?.id === restoredGoal.id) {\n\t\t\t\t\truntime.activeGoal = transitionGoal(restoredGoal, \"paused\");\n\t\t\t\t\tblockStaleGoalToolCalls();\n\t\t\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif (runtime.settings.toolVisibility === \"after-first-goal\" && !runtime.goalToolsUnlocked) {\n\t\t\t\thideGoalToolsIfLocked();\n\t\t\t}\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t}\n\t});\n\n\tpi.on(\"session_shutdown\", (_event, ctx) => {\n\t\tif (runtime.activeGoal) {\n\t\t\tif (!runtime.queueFrozen && runtime.activeGoal.status === \"active\") {\n\t\t\t\tupdateGoalUsage(runtime.activeGoal, ctx, false);\n\t\t\t}\n\t\t\tpersistGoal(runtime.activeGoal);\n\t\t}\n\t\tclearContinuationTracking();\n\t\tclearPendingGoalPrompts();\n\t\truntime.agentRunGoalId = undefined;\n\t\tclearGoalRecovery();\n\t\tclearBudgetWrapUp();\n\t\tclearStaleGoalToolCallBlock();\n\t\truntime.activeGoal = undefined;\n\t\truntime.queuedGoals = [];\n\t\truntime.pendingQueueAction = undefined;\n\t\truntime.queueFrozen = false;\n\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\tclearCompletionStatusTimer();\n\t\tclearStatusRefreshTimer(); // lunr\n\t});\n\n\tpi.on(\"session_before_compact\", (event, ctx) => {\n\t\tif (runtime.queueFrozen) return;\n\t\tif (runtime.activeGoal?.status === \"budget_limited\") {\n\t\t\tif ((event as { willRetry?: boolean }).willRetry === true) return { cancel: true as const };\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal?.status !== \"active\") return;\n\t\tif (!updateGoalUsage(runtime.activeGoal, ctx)) return;\n\t\tcancelContinuationWork();\n\t\tpersistGoal(runtime.activeGoal);\n\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\tif (runtime.pendingQueueAction) return;\n\t\tif (limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };\n\t});\n\n\tpi.on(\"session_compact\", async (event, ctx) => {\n\t\tif (runtime.queueFrozen) return;\n\t\tif (runtime.activeGoal?.status !== \"active\") {\n\t\t\tclearGoalRecovery();\n\t\t\tif (runtime.pendingQueueAction) await dispatchPendingQueueActionIfSettled(ctx);\n\t\t\treturn;\n\t\t}\n\n\t\tconst restoredState = loadGoalStateFromSession(ctx);\n\t\tif (restoredState.goal?.id === runtime.activeGoal.id) {\n\t\t\truntime.activeGoal = restoredState.goal;\n\t\t\truntime.queuedGoals = restoredState.queue;\n\t\t\truntime.pendingQueueAction = restoredState.pendingAction;\n\t\t}\n\t\tconst usageRecorded = updateGoalUsage(runtime.activeGoal, ctx);\n\t\tif (usageRecorded) {\n\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t}\n\t\tif (runtime.pendingQueueAction) {\n\t\t\tawait dispatchPendingQueueActionIfSettled(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (!usageRecorded) return;\n\t\tif (limitActiveGoalForBudget(ctx, false)) return;\n\n\t\tconst wasPiRetry = isPiOwnedCompactionRetry(event, runtime.activeGoal.id);\n\t\tclearGoalRecoveryForGoal(runtime.activeGoal.id);\n\t\tif (wasPiRetry) return;\n\t\trequestContinuation(runtime.activeGoal);\n\t\t// Manual compaction does not emit agent_settled. This common dispatcher is\n\t\t// therefore the narrow fallback; threshold compaction leaves the intent for\n\t\t// agent_settled when Pi is still busy.\n\t\tdispatchContinuationIfSettled(ctx);\n\t});\n\n\tpi.on(\"input\", (event) => {\n\t\tif (event.source === \"extension\") {\n\t\t\tif (\n\t\t\t\tconsumeCancelledContinuationPrompt(event.text) ||\n\t\t\t\tconsumeStaleOwnedGoalPrompt(event.text)\n\t\t\t) {\n\t\t\t\treturn { action: \"handled\" as const };\n\t\t\t}\n\t\t\tif (runtime.queueFrozen) return;\n\t\t\tclearGoalRecovery();\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.queueFrozen) return;\n\t\tif (/^\\/goal(?:\\s|$)/u.test(event.text.trimStart())) return;\n\t\tclearGoalRecovery();\n\t\tclearBudgetWrapUp();\n\t\tclearStaleGoalToolCallBlock();\n\t});\n\n\t// lunr: the previous context-event filter dropped superseded budget\n\t// wrap-up messages from request context. That breaks Anthropic prefix\n\t// continuity (full cache miss from the cut). The wrap-up custom message\n\t// is small; keeping history unfiltered is cheaper than a cache rewrite.\n\t// keepBudgetWrapUpMessage remains on the runtime if a future token-saving\n\t// path can prove the wrap-up was never sent.\n\n\tpi.on(\"tool_call\", (event, ctx) => {\n\t\tif (runtime.queueFrozen) {\n\t\t\tif (!isGoalToolName(event.toolName)) return;\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason:\n\t\t\t\t\t\"The experimental goal queue is frozen. Re-enable experimental.goals and run /reload, or use /goal clear.\",\n\t\t\t};\n\t\t}\n\t\t// lunr: mask locked goal tools instead of removing them from the active\n\t\t// list (setActiveTools churn busts the tools+system cache prefix).\n\t\tif (isGoalToolName(event.toolName) && runtime.areGoalToolsLocked()) {\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: \"Goal tools are locked until a /goal is activated.\",\n\t\t\t};\n\t\t}\n\t\tif (\n\t\t\truntime.activeGoal?.status === \"budget_limited\" &&\n\t\t\truntime.budgetWrapUp?.goalId === runtime.activeGoal.id &&\n\t\t\tevent.toolName !== \"goal_complete\"\n\t\t) {\n\t\t\t// A blocked tool result would normally trigger another model call. Abort the\n\t\t\t// wrap-up instead so a tool-seeking model cannot create an unbounded loop.\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: \"Goal token budget is exhausted; only goal_complete is allowed during wrap-up.\",\n\t\t\t};\n\t\t}\n\t\tif (!runtime.staleGoalToolCallsBlocked) return;\n\t\tif (!runtime.activeGoal || !blocksStaleGoalToolCalls(runtime.activeGoal.status)) {\n\t\t\tclearStaleGoalToolCallBlock();\n\t\t\treturn;\n\t\t}\n\t\treturn {\n\t\t\tblock: true,\n\t\t\treason: \"Blocked stale /goal tool call after the goal stopped or was interrupted.\",\n\t\t};\n\t});\n\n\tpi.on(\"tool_execution_end\", (_event, ctx) => {\n\t\tif (runtime.queueFrozen) return;\n\t\tif (\n\t\t\truntime.activeGoal?.status === \"budget_limited\" &&\n\t\t\truntime.budgetWrapUp?.goalId === runtime.activeGoal.id &&\n\t\t\t!runtime.budgetWrapUp.delivered\n\t\t) {\n\t\t\tqueueBudgetWrapUp(ctx, runtime.activeGoal);\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal?.status !== \"active\") return;\n\n\t\t// AgentSession persists assistant message_end before tool execution events,\n\t\t// so the completed assistant call's usage is authoritative at this boundary.\n\t\tif (!updateGoalUsage(runtime.activeGoal, ctx)) return;\n\t\tpersistGoal(runtime.activeGoal);\n\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\tif (limitActiveGoalForBudget(ctx, true)) return;\n\t\tif (!goalToolsAvailable()) pauseGoalForUnavailableTools(ctx);\n\t});\n\n\tpi.on(\"before_agent_start\", (event, ctx) => {\n\t\tif (runtime.queueFrozen) {\n\t\t\truntime.agentRunGoalId = undefined;\n\t\t\treturn;\n\t\t}\n\t\tconst goalPromptGoalId = consumePendingGoalPrompt(event.prompt);\n\t\tconst continuationGoalId = goalPromptGoalId ? undefined : markContinuationStarted(event.prompt);\n\t\tconst ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;\n\t\tconst activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n\t\tconst activeGoalRecovery = runtime.hasActiveGoalRecovery();\n\t\t// lunr: auto-resume a usage_limited goal on a wake-up turn. Two triggers:\n\t\t// - resumeAfter was parsed from the provider error and has elapsed (any turn\n\t\t// resumes — the reset time is known, so the goal should not stay parked);\n\t\t// - no reset time was parseable: only a cron-fired turn resumes (the user\n\t\t// scheduled the wake-up explicitly; ordinary manual turns don't hijack —\n\t\t// /goal resume stays the manual path).\n\t\t// Gateway cron fires are headless and cannot see this session's goal.\n\t\tconst resumeAfter = runtime.activeGoal?.resumeAfter;\n\t\tconst resumeDue = resumeAfter !== undefined && Date.now() >= resumeAfter;\n\t\tconst cronWakeUp = resumeAfter === undefined && isCronFire();\n\t\tif (\n\t\t\truntime.activeGoal?.status === \"usage_limited\" &&\n\t\t\t(resumeDue || cronWakeUp) &&\n\t\t\t!ownedPromptGoalId &&\n\t\t\t!activeBudgetWrapUp &&\n\t\t\t!activeGoalRecovery\n\t\t) {\n\t\t\tconst resumed = runtime.reactivateGoalForResume(ctx);\n\t\t\tif (resumed) {\n\t\t\t\truntime.agentRunGoalId = resumed.id;\n\t\t\t\tif (!goalToolsAvailable()) {\n\t\t\t\t\tpauseGoalForUnavailableTools(ctx, false);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tsystemPrompt: event.systemPrompt + \"\\n\\n\" + buildGoalSystemPrompt(runtime.activeGoal),\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t\tif (\n\t\t\truntime.pendingQueueAction?.kind === \"prioritize\" &&\n\t\t\t!activeBudgetWrapUp &&\n\t\t\t!activeGoalRecovery\n\t\t) {\n\t\t\t// A turn that starts after priority intent is committed belongs to neither\n\t\t\t// the displaced goal nor the not-yet-activated urgent goal. Persist the\n\t\t\t// displaced goal's final accounting boundary so reload cannot absorb this run.\n\t\t\tif (!runtime.pendingQueueAction.displacedUsageFinalized) {\n\t\t\t\tif (runtime.activeGoal?.status === \"active\") {\n\t\t\t\t\tupdateGoalUsage(runtime.activeGoal, ctx, false);\n\t\t\t\t}\n\t\t\t\truntime.pendingQueueAction.displacedUsageFinalized = true;\n\t\t\t\tif (runtime.activeGoal) {\n\t\t\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t\t\t}\n\t\t\t}\n\t\t\truntime.agentRunGoalId = null;\n\t\t\tif (ownedPromptGoalId) abortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (activeBudgetWrapUp && runtime.activeGoal) {\n\t\t\truntime.agentRunGoalId = runtime.activeGoal.id;\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\truntime.pendingQueueAction?.kind === \"advance\" &&\n\t\t\truntime.pendingQueueAction.goalId === runtime.activeGoal?.id\n\t\t) {\n\t\t\truntime.agentRunGoalId = ownedPromptGoalId ?? runtime.activeGoal.id;\n\t\t\tif (ownedPromptGoalId) abortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {\n\t\t\truntime.agentRunGoalId = ownedPromptGoalId;\n\t\t\tif (runtime.activeGoal?.status === \"active\" && !goalToolsAvailable()) {\n\t\t\t\tpauseGoalForUnavailableTools(ctx, false);\n\t\t\t}\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal?.status !== \"active\") {\n\t\t\truntime.agentRunGoalId = undefined;\n\t\t\treturn;\n\t\t}\n\t\truntime.agentRunGoalId = runtime.activeGoal.id;\n\t\tif (!goalToolsAvailable()) {\n\t\t\tpauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);\n\t\t\treturn;\n\t\t}\n\n\t\treturn {\n\t\t\tsystemPrompt: `${event.systemPrompt}\\n\\n${buildGoalSystemPrompt(runtime.activeGoal)}`,\n\t\t};\n\t});\n\n\tpi.on(\"agent_end\", (event, ctx) => {\n\t\tif (runtime.queueFrozen) return;\n\t\tconst agentRunGoalId = runtime.agentRunGoalId;\n\t\truntime.agentRunGoalId = undefined;\n\t\tif (\n\t\t\tagentRunGoalId === null ||\n\t\t\t(!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp())\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tif (agentRunGoalId && agentRunGoalId !== runtime.activeGoal?.id) return;\n\t\tif (!runtime.activeGoal) return;\n\t\tif (\n\t\t\truntime.activeGoal.status === \"budget_limited\" &&\n\t\t\truntime.budgetWrapUp?.goalId === runtime.activeGoal.id\n\t\t) {\n\t\t\tupdateGoalUsage(runtime.activeGoal, ctx);\n\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t\tclearBudgetWrapUp();\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal.status !== \"active\") return;\n\t\tif (\n\t\t\truntime.pendingQueueAction?.kind === \"advance\" &&\n\t\t\truntime.pendingQueueAction.goalId === runtime.activeGoal.id\n\t\t) {\n\t\t\tupdateGoalUsage(runtime.activeGoal, ctx);\n\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t\treturn;\n\t\t}\n\n\t\tconst goalId = runtime.activeGoal.id;\n\t\tconst alreadyAwaitingContinuation = hasContinuationWorkForGoal(goalId);\n\t\tconst finalAssistant = findFinalAssistantMessage(event.messages);\n\n\t\tif (!alreadyAwaitingContinuation) runtime.activeGoal = incrementGoal(runtime.activeGoal);\n\t\tupdateGoalUsage(runtime.activeGoal, ctx);\n\n\t\tif (finalAssistant?.stopReason === \"aborted\") {\n\t\t\tclearGoalRecoveryForGoal(goalId);\n\t\t\tstopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, \"paused\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (finalAssistant?.stopReason === \"error\") {\n\t\t\tif (isRetryableGoalInterruption(finalAssistant)) {\n\t\t\t\tif (limitActiveGoalForBudget(ctx, false)) return;\n\t\t\t\tif (!goalToolsAvailable()) {\n\t\t\t\t\tpauseGoalForUnavailableTools(ctx);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\truntime.goalRecovery = {\n\t\t\t\t\tgoalId,\n\t\t\t\t\tkind: isGoalContextOverflow(finalAssistant) ? \"compaction_retry\" : \"provider_retry\",\n\t\t\t\t};\n\t\t\t\tcancelContinuationWork();\n\t\t\t\tpersistGoal(runtime.activeGoal);\n\t\t\t\tupdateStatus(ctx, runtime.activeGoal);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tclearGoalRecoveryForGoal(goalId);\n\t\t\tstopGoalAfterAgentEnd(\n\t\t\t\tctx,\n\t\t\t\truntime.activeGoal,\n\t\t\t\tfinalAssistant,\n\t\t\t\tisUsageLimitedGoalInterruption(finalAssistant) ? \"usage_limited\" : \"blocked\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tclearGoalRecoveryForGoal(goalId);\n\n\t\tif (limitActiveGoalForBudget(ctx, false)) return;\n\t\tif (!goalToolsAvailable()) {\n\t\t\tpauseGoalForUnavailableTools(ctx);\n\t\t\treturn;\n\t\t}\n\n\t\tpersistGoal(runtime.activeGoal);\n\t\tupdateStatus(ctx, runtime.activeGoal);\n\n\t\tconst currentGoal = runtime.activeGoal;\n\t\tif (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== \"active\") return;\n\t\tif (runtime.pendingQueueAction?.kind === \"prioritize\") return;\n\t\trequestContinuation(currentGoal);\n\t});\n\n\tpi.on(\"agent_settled\", (_event, ctx) => {\n\t\tif (runtime.queueFrozen) return;\n\t\tif (!runtime.pendingQueueAction) {\n\t\t\tdispatchContinuationIfSettled(ctx);\n\t\t\treturn;\n\t\t}\n\t\treturn dispatchPendingQueueActionIfSettled(ctx).then((dispatched) => {\n\t\t\tif (!dispatched) dispatchContinuationIfSettled(ctx);\n\t\t});\n\t});\n\n\tfunction hasPendingSkipForGoal(goalId: string) {\n\t\treturn (\n\t\t\truntime.pendingQueueAction?.kind === \"advance\" &&\n\t\t\truntime.pendingQueueAction.reason === \"skip\" &&\n\t\t\truntime.pendingQueueAction.goalId === goalId\n\t\t);\n\t}\n\n\tfunction stopGoalAfterAgentEnd(\n\t\tctx: StatusContext,\n\t\tgoal: ActiveGoal,\n\t\tassistant: AssistantMessageLike,\n\t\tstatus: \"paused\" | \"blocked\" | \"usage_limited\",\n\t) {\n\t\tcancelContinuationWork();\n\t\tclearBudgetWrapUp();\n\t\tblockStaleGoalToolCalls();\n\t\tabortCurrentTurn(ctx);\n\t\t// lunr: if the provider error carries a reset time, pre-fill resumeAfter so a\n\t\t// one-shot /cron wake-up auto-resumes the goal without a manual /goal resume.\n\t\tconst resumeAfter = status === \"usage_limited\" ? parseUsageResetTimeMs(assistant.errorMessage) : undefined;\n\t\tconst goalWithResume = resumeAfter !== undefined ? { ...goal, resumeAfter } : goal;\n\t\truntime.activeGoal = transitionGoal(goalWithResume, status);\n\t\tpersistGoal(runtime.activeGoal);\n\t\tupdateStatus(ctx, runtime.activeGoal);\n\n\t\tconst details = assistant.errorMessage\n\t\t\t? ` (${truncateNotification(assistant.errorMessage)})`\n\t\t\t: \"\";\n\t\tif (status === \"paused\") {\n\t\t\tctx.ui.notify(\n\t\t\t\t`Goal paused after interruption${details}. Run /goal resume to continue.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (status === \"usage_limited\") {\n\t\t\tconst when = resumeAfter !== undefined ? ` Auto-resume scheduled for ${new Date(resumeAfter).toLocaleString()}.` : \"\";\n\t\t\tctx.ui.notify(\n\t\t\t\t`Goal usage-limited${details}.${when} Run /goal resume when usage resets, or schedule a one-shot /cron firing \"continue\" into this session to wake it.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tctx.ui.notify(\n\t\t\t`Goal blocked after agent error${details}. Resolve the blocker or run /goal resume to retry.`,\n\t\t\t\"warning\",\n\t\t);\n\t}\n}\n\nexport default function goal(pi: ExtensionAPI, options: GoalOptions = {}) {\n\tregisterGoalRuntime(pi, options);\n}\n\nexport {\n\tassistantUsageTokens,\n\tcumulativeAssistantTokens,\n\tformatDuration,\n\tformatTokenCount,\n} from \"./accounting.js\";\n\nexport {\n\tcompleteGoalArguments,\n\tparseCommand,\n\tparseTokenBudget,\n\tvalidateObjective,\n} from \"./command.js\";\n\nexport { buildGoalSystemPrompt } from \"./prompts.js\";\n\nexport {\n\tfindFinalAssistantMessage,\n\tformatStatus,\n\tisContradictoryCompletionSummary,\n\tisRetryableGoalInterruption,\n\tisUsageLimitedGoalInterruption,\n} from \"./runtime.js\";\n"]}
@@ -83,6 +83,7 @@ export declare class GoalRuntime {
83
83
  requestContinuation(goal: ActiveGoal): boolean;
84
84
  dispatchContinuationIfSettled(ctx: StatusContext): boolean;
85
85
  hasContinuationWorkForGoal(goalId: string): boolean;
86
+ syncGoalPermissionMode(goal?: ActiveGoal): void;
86
87
  updateStatus(ctx: StatusContext, goal: ActiveGoal): void;
87
88
  clearStatusRefreshTimer(): void;
88
89
  blockStaleGoalToolCalls(): void;
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../../../src/builtin-extensions/narumiruna-pi-goal/src/runtime.ts"],"names":[],"mappings":"AAEA,OAAO,EAEN,KAAK,gBAAgB,IAAI,kBAAkB,EAC3C,KAAK,KAAK,EACV,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AASpE,OAAO,EACN,KAAK,UAAU,EAEf,KAAK,kBAAkB,EAEvB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAuB,KAAK,UAAU,EAAE,MAAM,cAAc,CAAC;AACpE,OAAO,EAAyB,KAAK,YAAY,EAAE,MAAM,eAAe,CAAC;AAEzE,MAAM,MAAM,eAAe,GAAG,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,CAAC;AAElF,MAAM,WAAW,kBAAkB;IAClC,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;CACf;AAED,MAAM,WAAW,YAAY;IAC5B,MAAM,EAAE,MAAM,CAAC;IACf,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AE1D;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,UAAU,uEAEvD;AAED,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,UAAU,gGAIpD;AAED,wBAAgB,gCAAgC,CAAC,OAAO,EAAE,MAAM,WAE/D;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,4EAI9E;AAED,wBAAgB,8BAA8B,CAAC,SAAS,EAAE,oBAAoB,WAO7E;AAED,wBAAgB,2BAA2B,CAAC,SAAS,EAAE,oBAAoB,WAa1E;AAED,wBAAgB,qBAAqB,CAAC,SAAS,EAAE,oBAAoB,WAEpE;AAiBD,wBAAgB,qBAAqB,CAAC,YAAY,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAkB1F;AAED,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,oBAAoB,GAAG,SAAS,CAuB/F;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,UAEzC;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,UAEjD","sourcesContent":["// @ts-nocheck\nimport { randomUUID } from \"node:crypto\";\nimport {\n\tisContextOverflow,\n\ttype AssistantMessage as PiAssistantMessage,\n\ttype Usage,\n} from \"@ashx-j/lunr-ai\";\nimport type { ExtensionAPI } from \"@ashx-j/lunr\";\nimport {\n\tassistantUsageTokens,\n\tcheckpointGoalActiveTime,\n\tformatDuration,\n\tformatTokenCount,\n\tnonNegativeFiniteNumber,\n\tupdateGoalUsage,\n} from \"./accounting.js\";\nimport {\n\ttype ActiveGoal,\n\tclearLegacyPersistedGoal,\n\ttype PendingQueueAction,\n\tserializeGoalState,\n} from \"./persistence.js\";\nimport { buildContinuePrompt, type GoalStatus } from \"./prompts.js\";\nimport { DEFAULT_GOAL_SETTINGS, type GoalSettings } from \"./settings.js\";\n\nexport type AgentStopReason = \"stop\" | \"length\" | \"toolUse\" | \"error\" | \"aborted\";\n\nexport interface ContinuationTicket {\n\tgoalId: string;\n\titeration: number;\n\tmarker: string;\n\tprompt: string;\n}\n\nexport interface BudgetWrapUp {\n\tgoalId: string;\n\tdelivered: boolean;\n}\n\nexport type GoalRecoveryKind = \"provider_retry\" | \"compaction_retry\";\n\nexport interface GoalRecovery {\n\tgoalId: string;\n\tkind: GoalRecoveryKind;\n}\n\nexport interface AssistantMessageLike {\n\trole: \"assistant\";\n\tstopReason?: AgentStopReason;\n\terrorMessage?: string;\n\tcontent?: PiAssistantMessage[\"content\"];\n\tapi?: PiAssistantMessage[\"api\"];\n\tprovider?: PiAssistantMessage[\"provider\"];\n\tmodel?: string;\n\tusage?: Usage;\n\ttimestamp?: number;\n}\n\nexport interface StatusContext {\n\tcwd: string;\n\tui: {\n\t\tconfirm: (title: string, message: string) => Promise<boolean>;\n\t\tnotify: (message: string, level?: \"info\" | \"warning\" | \"error\") => void;\n\t\tsetStatus: (key: string, value: string | undefined) => void;\n\t};\n\tisIdle?: () => boolean;\n\thasPendingMessages?: () => boolean;\n\tabort?: () => void;\n\tsessionManager?: unknown;\n}\n\nexport interface GoalToolVisibilitySnapshot {\n\tactiveTools: string[];\n\tgoalToolsUnlocked: boolean;\n\tgoalToolsHiddenByPolicy: string[];\n}\n\nexport const STATUS_KEY = \"goal\";\nexport const GOAL_STATE_ENTRY_TYPE = \"goal-state\";\nexport const GOAL_COMPLETE_TOOL = \"goal_complete\";\nexport const GOAL_BLOCKED_TOOL = \"goal_blocked\";\nexport const GOAL_TOOL_NAMES = [GOAL_COMPLETE_TOOL, GOAL_BLOCKED_TOOL] as const;\n\nconst MAX_CANCELLED_CONTINUATION_PROMPTS = 20;\nconst MAX_PENDING_GOAL_PROMPTS = 20;\nconst GOAL_PROMPT_MARKER_PREFIX = \"pi-goal-prompt:\";\nconst CONTINUATION_MARKER_PREFIX = \"pi-goal-continuation:\";\nconst BUDGET_WRAP_UP_MESSAGE_TYPE = \"goal-budget-wrap-up\";\nconst BUDGET_WRAP_UP_PROMPT =\n\t\"The active /goal token budget is exhausted. Stop substantive work and do not call substantive tools. Summarize progress, verified results, remaining work, and blockers concisely. Treat completion as unproven. Do not call goal_complete unless authoritative, requirement-by-requirement evidence already proves every requirement is complete. Weak, indirect, or missing evidence is not enough. Budget exhaustion is not completion.\";\nconst CONTRADICTORY_COMPLETION_PATTERNS = [\n\t/(?<!could\\s)\\bnot\\s+(?:yet\\s+)?(?:complete|completed|done|finished)\\b/i,\n\t/\\bstill\\s+(?:incomplete|failing|failing\\s+tests?|fails?)\\b/i,\n\t/\\btests?\\s+(?:still\\s+)?fail(?:ing)?\\b/i,\n] as const;\nconst USAGE_LIMIT_GOAL_ERROR_PATTERNS = [\n\t/usage[_\\s-]*(?:limit|cap)|chatgpt.{0,32}usage/i,\n\t/quota.{0,32}(?:reached|exceeded|exhausted|depleted)|(?:reached|exceeded|exhausted|depleted).{0,32}quota/i,\n\t/insufficient[_\\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,\n\t/(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,\n] as const;\nconst NON_RETRYABLE_GOAL_ERROR_RE =\n\t/multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;\n// Pi 0.79 does not export its assistant-error retry classifier. Keep this\n// compatibility mirror aligned with Pi's public retry utility in newer versions.\nconst RETRYABLE_GOAL_ERROR_PATTERNS = [\n\t/overloaded|rate.?limit|too many requests|\\b(?:429|500|502|503|504)\\b|service.?unavailable|server.?error|internal.?error/i,\n\t/provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,\n\t/network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,\n\t/timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream ended before message_stop|http2 request did not get a response|retry delay/i,\n\t/context[_\\s-]*length[_\\s-]*exceeded|input exceeds the context window/i,\n] as const;\n\n// One instance belongs to one extension factory. It owns all mutable session state\n// and the cross-cutting invariants used by command and lifecycle orchestration.\nexport class GoalRuntime {\n\tsettings: GoalSettings = DEFAULT_GOAL_SETTINGS;\n\tactiveGoal?: ActiveGoal;\n\tqueuedGoals: ActiveGoal[] = [];\n\tpendingQueueAction?: PendingQueueAction;\n\tqueueFrozen = false;\n\tcompletionStatusTimer?: NodeJS.Timeout;\n\t// lunr: 30s footer refresh timer so the goal indicator's elapsed minutes tick while active\n\tstatusRefreshTimer?: NodeJS.Timeout;\n\tstatusRefreshCtx?: StatusContext;\n\tcontinuationIntent?: ContinuationTicket;\n\tcontinuationDelivery?: ContinuationTicket;\n\tgoalRecovery?: GoalRecovery;\n\tbudgetWrapUp?: BudgetWrapUp;\n\t/** `null` marks a run that must not be charged to the active goal. */\n\tagentRunGoalId?: string | null;\n\tstaleGoalToolCallsBlocked = false;\n\t/** Once true, goal tools stay in the active set for this runtime (prompt-cache stable). */\n\tgoalToolsUnlocked = false;\n\t/** Exact lazy goal tools this runtime removed and may restore on a mode change. */\n\tgoalToolsHiddenByPolicy = new Set<string>();\n\tpendingGoalPromptMarkers = new Map<string, string>();\n\tcancelledContinuationMarkers = new Set<string>();\n\n\treadonly pi: ExtensionAPI;\n\n\tconstructor(pi: ExtensionAPI) {\n\t\tthis.pi = pi;\n\t}\n\n\tcanRecordGoalUsage() {\n\t\treturn (\n\t\t\tthis.agentRunGoalId !== null &&\n\t\t\t!(\n\t\t\t\tthis.pendingQueueAction?.kind === \"prioritize\" &&\n\t\t\t\tthis.pendingQueueAction.displacedUsageFinalized === true\n\t\t\t)\n\t\t);\n\t}\n\n\thasActiveBudgetWrapUp() {\n\t\treturn (\n\t\t\tthis.activeGoal?.status === \"budget_limited\" &&\n\t\t\tthis.budgetWrapUp?.goalId === this.activeGoal.id &&\n\t\t\tthis.budgetWrapUp.delivered\n\t\t);\n\t}\n\n\thasActiveGoalRecovery() {\n\t\treturn Boolean(this.activeGoal && this.goalRecovery?.goalId === this.activeGoal.id);\n\t}\n\n\trecordGoalUsage(\n\t\tgoal: ActiveGoal,\n\t\tctx: StatusContext,\n\t\tcheckpointActiveTime = goal.status === \"active\",\n\t) {\n\t\tif (!this.canRecordGoalUsage()) return false;\n\t\tupdateGoalUsage(goal, ctx, checkpointActiveTime);\n\t\treturn true;\n\t}\n\n\trequestContinuation(goal: ActiveGoal) {\n\t\tif (this.hasContinuationWorkForGoal(goal.id)) return false;\n\t\tconst marker = continuationMarker(goal);\n\t\tthis.continuationIntent = {\n\t\t\tgoalId: goal.id,\n\t\t\titeration: goal.iteration,\n\t\t\tmarker,\n\t\t\tprompt: buildContinuePrompt(goal, marker),\n\t\t};\n\t\treturn true;\n\t}\n\n\tdispatchContinuationIfSettled(ctx: StatusContext) {\n\t\tconst intent = this.continuationIntent;\n\t\tif (!intent) return false;\n\t\tif (this.activeGoal?.status === \"active\" && !this.goalToolsAvailable()) {\n\t\t\tthis.pauseGoalForUnavailableTools(ctx);\n\t\t\treturn false;\n\t\t}\n\t\tif (\n\t\t\t!this.activeGoal ||\n\t\t\tthis.activeGoal.id !== intent.goalId ||\n\t\t\tthis.activeGoal.status !== \"active\"\n\t\t) {\n\t\t\tthis.continuationIntent = undefined;\n\t\t\treturn false;\n\t\t}\n\t\tif (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;\n\n\t\tthis.continuationIntent = undefined;\n\t\tthis.continuationDelivery = intent;\n\t\ttry {\n\t\t\tthis.pi.sendUserMessage(intent.prompt, { deliverAs: \"followUp\" });\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (this.continuationDelivery?.marker === intent.marker) {\n\t\t\t\tthis.continuationDelivery = undefined;\n\t\t\t}\n\t\t\tif (this.activeGoal?.id === intent.goalId && this.activeGoal.status === \"active\") {\n\t\t\t\tthis.continuationIntent = intent;\n\t\t\t}\n\t\t\tctx.ui.notify(`Goal prompt failed: ${formatError(error)}`, \"error\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\thasContinuationWorkForGoal(goalId: string) {\n\t\treturn (\n\t\t\tthis.continuationIntent?.goalId === goalId || this.continuationDelivery?.goalId === goalId\n\t\t);\n\t}\n\n\tupdateStatus(ctx: StatusContext, goal: ActiveGoal) {\n\t\tthis.clearCompletionStatusTimer();\n\t\tctx.ui.setStatus(STATUS_KEY, formatStatus(goal));\n\t\t// lunr: refresh the footer every 30s while a goal is active so the elapsed time ticks\n\t\tthis.clearStatusRefreshTimer();\n\t\tif (goal.status === \"active\") {\n\t\t\tthis.statusRefreshCtx = ctx;\n\t\t\tthis.statusRefreshTimer = setInterval(() => {\n\t\t\t\tconst currentGoal = this.activeGoal;\n\t\t\t\tconst refreshCtx = this.statusRefreshCtx;\n\t\t\t\tif (!currentGoal || currentGoal.status !== \"active\" || !refreshCtx) {\n\t\t\t\t\tthis.clearStatusRefreshTimer();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\trefreshCtx.ui.setStatus(STATUS_KEY, formatStatus(currentGoal));\n\t\t\t\t} catch {\n\t\t\t\t\t// The captured ctx may be stale after session replacement or reload.\n\t\t\t\t\tthis.clearStatusRefreshTimer();\n\t\t\t\t}\n\t\t\t}, 30_000);\n\t\t\tthis.statusRefreshTimer.unref?.();\n\t\t}\n\t}\n\n\t// lunr: paired with the status refresh interval started in updateStatus()\n\tclearStatusRefreshTimer() {\n\t\tif (!this.statusRefreshTimer) return;\n\t\tclearInterval(this.statusRefreshTimer);\n\t\tthis.statusRefreshTimer = undefined;\n\t\tthis.statusRefreshCtx = undefined;\n\t}\n\n\tblockStaleGoalToolCalls() {\n\t\tthis.staleGoalToolCallsBlocked = true;\n\t}\n\n\tclearStaleGoalToolCallBlock() {\n\t\tthis.staleGoalToolCallsBlocked = false;\n\t}\n\n\tclearGoalRecovery() {\n\t\tthis.goalRecovery = undefined;\n\t}\n\n\tclearBudgetWrapUp() {\n\t\tthis.budgetWrapUp = undefined;\n\t}\n\n\tkeepBudgetWrapUpMessage(message: unknown) {\n\t\tif (!message || typeof message !== \"object\") return true;\n\t\tconst candidate = message as {\n\t\t\trole?: unknown;\n\t\t\tcustomType?: unknown;\n\t\t\tdetails?: { goalId?: unknown };\n\t\t};\n\t\tif (candidate.role !== \"custom\" || candidate.customType !== BUDGET_WRAP_UP_MESSAGE_TYPE) {\n\t\t\treturn true;\n\t\t}\n\t\treturn (\n\t\t\ttypeof candidate.details?.goalId === \"string\" &&\n\t\t\tcandidate.details.goalId === this.budgetWrapUp?.goalId &&\n\t\t\tcandidate.details.goalId === this.activeGoal?.id\n\t\t);\n\t}\n\n\tqueueBudgetWrapUp(ctx: StatusContext, goal: ActiveGoal) {\n\t\tif (!this.budgetWrapUp || this.budgetWrapUp.goalId !== goal.id) {\n\t\t\tthis.budgetWrapUp = { goalId: goal.id, delivered: false };\n\t\t}\n\t\tif (this.budgetWrapUp.delivered) return true;\n\t\tthis.budgetWrapUp.delivered = true;\n\t\ttry {\n\t\t\tthis.pi.sendMessage(\n\t\t\t\t{\n\t\t\t\t\tcustomType: BUDGET_WRAP_UP_MESSAGE_TYPE,\n\t\t\t\t\tcontent: BUDGET_WRAP_UP_PROMPT,\n\t\t\t\t\tdisplay: true,\n\t\t\t\t\tdetails: { goalId: goal.id },\n\t\t\t\t},\n\t\t\t\t{ deliverAs: \"steer\" },\n\t\t\t);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tthis.budgetWrapUp.delivered = false;\n\t\t\tctx.ui.notify(`Goal budget wrap-up failed: ${formatError(error)}`, \"error\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tlimitActiveGoalForBudget(ctx: StatusContext, sendWrapUp: boolean) {\n\t\tconst goal = this.activeGoal;\n\t\tif (\n\t\t\tgoal?.status !== \"active\" ||\n\t\t\tgoal.tokenBudget === undefined ||\n\t\t\tgoal.tokensUsed < goal.tokenBudget\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\n\t\tthis.cancelContinuationWork();\n\t\tthis.clearGoalRecoveryForGoal(goal.id);\n\t\tthis.clearBudgetWrapUp();\n\t\tthis.activeGoal = transitionGoal(goal, \"budget_limited\");\n\t\tthis.persistGoal(this.activeGoal);\n\t\tthis.updateStatus(ctx, this.activeGoal);\n\t\tctx.ui.notify(`Goal token budget reached: ${formatBudget(this.activeGoal)}`, \"warning\");\n\t\tif (sendWrapUp) this.queueBudgetWrapUp(ctx, this.activeGoal);\n\t\treturn true;\n\t}\n\n\tclearGoalRecoveryForGoal(goalId: string) {\n\t\tif (this.goalRecovery?.goalId === goalId) this.goalRecovery = undefined;\n\t}\n\n\tisPiOwnedCompactionRetry(event: unknown, goalId: string) {\n\t\tconst compaction = event as { reason?: unknown; willRetry?: unknown };\n\t\tif (compaction.willRetry === true) return true;\n\t\treturn (\n\t\t\tthis.goalRecovery?.goalId === goalId &&\n\t\t\tthis.goalRecovery.kind === \"compaction_retry\" &&\n\t\t\t(compaction.reason === undefined || compaction.reason === \"overflow\")\n\t\t);\n\t}\n\n\tclearContinuationTracking() {\n\t\tthis.continuationIntent = undefined;\n\t\tthis.continuationDelivery = undefined;\n\t\tthis.cancelledContinuationMarkers.clear();\n\t}\n\n\tclearPendingGoalPrompts() {\n\t\tthis.pendingGoalPromptMarkers.clear();\n\t}\n\n\tasync sendOwnedGoalPrompt(ctx: StatusContext, goalId: string, prompt: string) {\n\t\tconst pending = this.rememberPendingGoalPrompt(goalId, prompt);\n\t\tconst sent = await sendPrompt(this.pi, ctx, pending.prompt);\n\t\tif (!sent) this.pendingGoalPromptMarkers.delete(pending.marker);\n\t\treturn sent;\n\t}\n\n\tcancelContinuationWork() {\n\t\tif (this.continuationDelivery) {\n\t\t\tthis.rememberCancelledContinuationMarker(this.continuationDelivery.marker);\n\t\t}\n\t\tthis.continuationIntent = undefined;\n\t\tthis.continuationDelivery = undefined;\n\t}\n\n\tconsumeCancelledContinuationPrompt(prompt: string) {\n\t\tconst marker = extractContinuationMarker(prompt);\n\t\treturn marker ? this.cancelledContinuationMarkers.delete(marker) : false;\n\t}\n\n\tconsumeStaleOwnedGoalPrompt(prompt: string) {\n\t\tconst marker = extractGoalPromptMarker(prompt);\n\t\tif (!marker) return false;\n\t\tconst goalId = this.pendingGoalPromptMarkers.get(marker);\n\t\tif (!goalId) return false;\n\t\tif (\n\t\t\t!this.queueFrozen &&\n\t\t\t!this.pendingQueueAction &&\n\t\t\tthis.activeGoal?.id === goalId &&\n\t\t\tthis.activeGoal.status === \"active\"\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tthis.pendingGoalPromptMarkers.delete(marker);\n\t\treturn true;\n\t}\n\n\tmarkContinuationStarted(prompt: string) {\n\t\tconst marker = extractContinuationMarker(prompt);\n\t\tif (!marker) {\n\t\t\t// A user, retry, or another extension started newer work. Cancel both an\n\t\t\t// unsent intent and a delivery that may have lost the non-atomic idle race;\n\t\t\t// the newer work's agent_end will record a fresh intent.\n\t\t\tthis.cancelContinuationWork();\n\t\t\treturn undefined;\n\t\t}\n\t\tif (this.continuationDelivery?.marker === marker) this.continuationDelivery = undefined;\n\t\treturn marker.split(\":\", 1)[0];\n\t}\n\n\tpersistGoal(goal: ActiveGoal) {\n\t\tthis.pi.appendEntry(\n\t\t\tGOAL_STATE_ENTRY_TYPE,\n\t\t\tserializeGoalState(goal, this.queuedGoals, this.pendingQueueAction),\n\t\t);\n\t}\n\n\tclearPersistedGoal(cwd: string) {\n\t\tthis.pi.appendEntry(GOAL_STATE_ENTRY_TYPE, serializeGoalState(undefined, [], undefined));\n\t\tclearLegacyPersistedGoal(cwd);\n\t}\n\n\tclearActiveGoal(ctx: StatusContext) {\n\t\tthis.clearStatusRefreshTimer(); // lunr: stop the footer refresh when the goal is cleared\n\t\tthis.cancelContinuationWork();\n\t\tthis.clearGoalRecovery();\n\t\tthis.clearBudgetWrapUp();\n\t\tthis.clearStaleGoalToolCallBlock();\n\t\tthis.activeGoal = undefined;\n\t\tthis.queuedGoals = [];\n\t\tthis.pendingQueueAction = undefined;\n\t\tthis.queueFrozen = false;\n\t\tthis.clearPersistedGoal(ctx.cwd);\n\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t// Do not clear goalToolsUnlocked: after first activation, keep tools visible\n\t\t// for the rest of this extension runtime to avoid repeated goal-tool schema\n\t\t// churn within the same runtime.\n\t}\n\n\tisGoalToolName(name: string) {\n\t\treturn (GOAL_TOOL_NAMES as readonly string[]).includes(name);\n\t}\n\n\tgoalToolsAvailable() {\n\t\tconst active = new Set(this.pi.getActiveTools());\n\t\treturn GOAL_TOOL_NAMES.every((name) => active.has(name));\n\t}\n\n\thideGoalToolsIfLocked() {\n\t\tif (this.goalToolsUnlocked) return;\n\t\tconst active = this.pi.getActiveTools();\n\t\tconst hidden = active.filter((name) => this.isGoalToolName(name));\n\t\tif (hidden.length === 0) return;\n\t\t// lunr: do not mutate the active tool list (Anthropic tools sit at the\n\t\t// front of the cache prefix). Locked goal tools stay registered; the\n\t\t// tool_call gate rejects them until a /goal is activated.\n\t\tfor (const name of hidden) this.goalToolsHiddenByPolicy.add(name);\n\t}\n\n\trestoreGoalToolsHiddenByPolicy() {\n\t\t// lunr: flags only — the tool list is never rewritten at runtime.\n\t\tthis.goalToolsHiddenByPolicy.clear();\n\t}\n\n\tassertGoalToolsAvailable() {\n\t\tif (this.goalToolsAvailable()) return;\n\t\tthrow new Error(\n\t\t\t\"goal_complete and goal_blocked are unavailable; include them in the active tool allowlist or leave the restrictive tool mode first.\",\n\t\t);\n\t}\n\n\tensureGoalToolsVisible() {\n\t\t// lunr: never add/remove tools mid-session. Assert they were already\n\t\t// registered at session start so the wire bytes stay stable.\n\t\tthis.assertGoalToolsAvailable();\n\t}\n\n\tprepareGoalToolsForActivation(ctx: StatusContext) {\n\t\tif (this.settings.toolVisibility === \"after-first-goal\") {\n\t\t\tif (!this.goalToolsAvailable() && ctx.isIdle?.() !== true) {\n\t\t\t\tthrow new Error(\"wait until Pi is idle before revealing the goal tools\");\n\t\t\t}\n\t\t\tthis.revealGoalTools();\n\t\t\treturn;\n\t\t}\n\t\tthis.assertGoalToolsAvailable();\n\t}\n\n\t/** Mark lazy tools permanently desired for this runtime and make them active now. */\n\trevealGoalTools() {\n\t\tconst wasUnlocked = this.goalToolsUnlocked;\n\t\ttry {\n\t\t\tthis.ensureGoalToolsVisible();\n\t\t\tthis.goalToolsUnlocked = true;\n\t\t\tthis.goalToolsHiddenByPolicy.clear();\n\t\t} catch (error) {\n\t\t\tthis.goalToolsUnlocked = wasUnlocked;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tsnapshotGoalToolVisibility(): GoalToolVisibilitySnapshot {\n\t\treturn {\n\t\t\tactiveTools: this.pi.getActiveTools(),\n\t\t\tgoalToolsUnlocked: this.goalToolsUnlocked,\n\t\t\tgoalToolsHiddenByPolicy: [...this.goalToolsHiddenByPolicy],\n\t\t};\n\t}\n\n\t/**\n\t * lunr: reactivate a stopped (usage_limited / paused / blocked / budget_limited)\n\t * goal back to active WITHOUT sending a prompt. Shared by the /goal resume\n\t * command and the auto-resume hook (cron wake-up). Returns the reactivated goal\n\t * or undefined if reactivation was rejected (tools unavailable, budget reached).\n\t * Consumes resumeAfter so a single schedule only fires once.\n\t */\n\treactivateGoalForResume(ctx: StatusContext): ActiveGoal | undefined {\n\t\tif (!this.activeGoal) return undefined;\n\t\tif (!isResumableGoalStatus(this.activeGoal.status)) return undefined;\n\t\tif (\n\t\t\tthis.activeGoal.tokenBudget !== undefined &&\n\t\t\tthis.activeGoal.tokensUsed >= this.activeGoal.tokenBudget\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\ttry {\n\t\t\tthis.prepareGoalToolsForActivation(ctx);\n\t\t} catch (error) {\n\t\t\tctx.ui.notify(`Cannot resume /goal: ${formatError(error)}`, \"error\");\n\t\t\treturn undefined;\n\t\t}\n\t\tthis.cancelContinuationWork();\n\t\tthis.clearGoalRecovery();\n\t\tthis.clearBudgetWrapUp();\n\t\tthis.clearStaleGoalToolCallBlock();\n\t\tconst next = transitionGoal(nextGoalInstance(this.activeGoal), \"active\");\n\t\tthis.activeGoal = { ...next, resumeAfter: undefined };\n\t\tthis.persistGoal(this.activeGoal);\n\t\tthis.updateStatus(ctx, this.activeGoal);\n\t\tif (this.activeGoal.status !== \"active\") return undefined;\n\t\treturn this.activeGoal;\n\t}\n\n\trestoreGoalToolVisibility(snapshot: GoalToolVisibilitySnapshot) {\n\t\t// lunr: restore unlock/hidden flags only — never rewrite the tool list.\n\t\tthis.goalToolsUnlocked = snapshot.goalToolsUnlocked;\n\t\tthis.goalToolsHiddenByPolicy.clear();\n\t\tfor (const name of snapshot.goalToolsHiddenByPolicy) {\n\t\t\tthis.goalToolsHiddenByPolicy.add(name);\n\t\t}\n\t}\n\n\tareGoalToolsLocked() {\n\t\treturn !this.goalToolsUnlocked && this.settings.toolVisibility === \"after-first-goal\";\n\t}\n\n\tpauseGoalForUnavailableTools(ctx: StatusContext, abortTurn = true, recordUsage = true) {\n\t\tconst goal = this.activeGoal;\n\t\tif (goal?.status !== \"active\") return false;\n\t\tif (recordUsage) this.recordGoalUsage(goal, ctx);\n\t\tthis.cancelContinuationWork();\n\t\tthis.clearGoalRecoveryForGoal(goal.id);\n\t\tthis.clearBudgetWrapUp();\n\t\tif (abortTurn) {\n\t\t\tthis.blockStaleGoalToolCalls();\n\t\t\tabortCurrentTurn(ctx);\n\t\t} else {\n\t\t\tthis.clearStaleGoalToolCallBlock();\n\t\t}\n\t\tthis.activeGoal = transitionGoal(goal, \"paused\");\n\t\tthis.persistGoal(this.activeGoal);\n\t\tthis.updateStatus(ctx, this.activeGoal);\n\t\tctx.ui.notify(\n\t\t\t\"Goal tools are unavailable, so the active goal was paused. Restore the tools and run /goal resume.\",\n\t\t\t\"warning\",\n\t\t);\n\t\treturn true;\n\t}\n\n\tshowCompletionStatus(ctx: StatusContext) {\n\t\tthis.clearCompletionStatusTimer();\n\t\tthis.clearStatusRefreshTimer(); // lunr: stop the footer refresh on completion\n\t\t// lunr: enriched footer status format\n\t\tctx.ui.setStatus(STATUS_KEY, \"goal ✓ complete\");\n\t\tthis.completionStatusTimer = setTimeout(() => {\n\t\t\tthis.completionStatusTimer = undefined;\n\t\t\ttry {\n\t\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\t} catch {\n\t\t\t\t// The completion status is best-effort; the captured ctx may be stale after\n\t\t\t\t// session replacement or reload before this timer fires.\n\t\t\t}\n\t\t}, 8_000);\n\t}\n\n\tclearCompletionStatusTimer() {\n\t\tif (!this.completionStatusTimer) return;\n\t\tclearTimeout(this.completionStatusTimer);\n\t\tthis.completionStatusTimer = undefined;\n\t}\n\n\tprivate rememberPendingGoalPrompt(goalId: string, prompt: string) {\n\t\tconst marker = randomUUID();\n\t\tthis.pendingGoalPromptMarkers.set(marker, goalId);\n\t\tif (this.pendingGoalPromptMarkers.size > MAX_PENDING_GOAL_PROMPTS) {\n\t\t\tconst oldest = this.pendingGoalPromptMarkers.keys().next().value;\n\t\t\tif (oldest) this.pendingGoalPromptMarkers.delete(oldest);\n\t\t}\n\t\treturn { marker, prompt: `${prompt}\\n\\n<!-- ${GOAL_PROMPT_MARKER_PREFIX}${marker} -->` };\n\t}\n\n\tprivate consumePendingGoalPrompt(prompt: string) {\n\t\tconst marker = extractGoalPromptMarker(prompt);\n\t\tif (!marker) return undefined;\n\t\tconst goalId = this.pendingGoalPromptMarkers.get(marker);\n\t\tthis.pendingGoalPromptMarkers.delete(marker);\n\t\treturn goalId;\n\t}\n\n\tconsumeOwnedGoalPrompt(prompt: string) {\n\t\treturn this.consumePendingGoalPrompt(prompt);\n\t}\n\n\tprivate rememberCancelledContinuationMarker(marker: string) {\n\t\tthis.cancelledContinuationMarkers.add(marker);\n\t\tif (this.cancelledContinuationMarkers.size <= MAX_CANCELLED_CONTINUATION_PROMPTS) return;\n\t\tconst oldest = this.cancelledContinuationMarkers.values().next().value;\n\t\tif (oldest) this.cancelledContinuationMarkers.delete(oldest);\n\t}\n}\n\nexport function createGoal(\n\ttext: string,\n\ttokenBudget: number | undefined,\n\tbaselineTokens: number,\n): ActiveGoal {\n\tconst now = Date.now();\n\treturn {\n\t\tid: randomUUID(),\n\t\ttext,\n\t\tstatus: \"active\",\n\t\tstartedAt: now,\n\t\tupdatedAt: now,\n\t\titeration: 0,\n\t\ttokenBudget,\n\t\ttokensUsed: 0,\n\t\ttimeUsedSeconds: 0,\n\t\tbaselineTokens,\n\t\tactiveStartedAt: now,\n\t};\n}\n\nexport function transitionGoal(goal: ActiveGoal, requestedStatus: GoalStatus): ActiveGoal {\n\tconst now = Date.now();\n\tconst status =\n\t\trequestedStatus === \"active\" &&\n\t\tgoal.tokenBudget !== undefined &&\n\t\tgoal.tokensUsed >= goal.tokenBudget\n\t\t\t? \"budget_limited\"\n\t\t\t: requestedStatus;\n\tconst next = { ...goal, status, updatedAt: now };\n\tcheckpointGoalActiveTime(next, now, status === \"active\");\n\treturn next;\n}\n\nexport function nextGoalInstance(goal: ActiveGoal): ActiveGoal {\n\treturn { ...goal, id: randomUUID(), updatedAt: Date.now() };\n}\n\nexport function editedGoalStatus(status: GoalStatus): GoalStatus {\n\tif (status === \"paused\" || status === \"blocked\" || status === \"usage_limited\") return status;\n\treturn \"active\";\n}\n\nexport function incrementGoal(goal: ActiveGoal): ActiveGoal {\n\treturn { ...goal, iteration: goal.iteration + 1, updatedAt: Date.now() };\n}\n\n// lunr: enriched footer status — `goal ● active · 3m · 2 turns` (rendered by ashxj-tui)\nexport function formatStatus(goal: ActiveGoal | undefined) {\n\tif (!goal) return undefined;\n\tif (goal.status === \"complete\") return \"goal ✓ complete\";\n\tif (goal.status === \"queued\") return \"goal queued\";\n\tif (goal.status === \"paused\") {\n\t\treturn `goal ◌ paused · ${formatGoalElapsed(goal)} · ${formatGoalTurns(goal)}`;\n\t}\n\tif (goal.status === \"blocked\") return \"goal ✗ blocked\";\n\tif (goal.status === \"usage_limited\") return \"goal usage-limited\";\n\tif (goal.status === \"budget_limited\") return `goal budget ${formatBudget(goal)}`;\n\tconst status = `goal ● active · ${formatGoalElapsed(goal)} · ${formatGoalTurns(goal)}`;\n\tif (goal.tokenBudget !== undefined) return `${status} · ${formatBudget(goal)}`;\n\treturn status;\n}\n\n// lunr: live elapsed = accumulated active time + the in-progress active segment\nfunction goalElapsedSeconds(goal: ActiveGoal) {\n\tlet seconds = nonNegativeFiniteNumber(goal.timeUsedSeconds);\n\tif (typeof goal.activeStartedAt === \"number\" && Number.isFinite(goal.activeStartedAt)) {\n\t\tseconds += Math.max(0, Date.now() - goal.activeStartedAt) / 1000;\n\t}\n\treturn seconds;\n}\n\n// lunr: footer elapsed format — `Xm` under 1h, `XhYm` after\nfunction formatGoalElapsed(goal: ActiveGoal) {\n\tconst totalMinutes = Math.floor(goalElapsedSeconds(goal) / 60);\n\tif (totalMinutes < 60) return `${totalMinutes}m`;\n\treturn `${Math.floor(totalMinutes / 60)}h${totalMinutes % 60}m`;\n}\n\n// lunr: footer turn count, singular at 1\nfunction formatGoalTurns(goal: ActiveGoal) {\n\treturn goal.iteration === 1 ? \"1 turn\" : `${goal.iteration} turns`;\n}\n\nexport function formatBudget(goal: ActiveGoal) {\n\treturn `${formatTokenCount(goal.tokensUsed)}/${formatTokenCount(goal.tokenBudget ?? 0)}`;\n}\n\nexport function goalSummary(\n\tgoal: ActiveGoal,\n\tqueuedGoals: readonly ActiveGoal[] = [],\n\texperimentalGoals = false,\n\tqueueFrozen = false,\n) {\n\tconst summary = [\n\t\t`Goal: ${goal.text}`,\n\t\t`Status: ${queueFrozen ? \"queue off\" : goal.status}`,\n\t\t`Iteration: ${goal.iteration}`,\n\t\t`Active elapsed: ${formatDuration(goal.timeUsedSeconds)}`,\n\t\t`Tokens: ${goal.tokenBudget === undefined ? formatTokenCount(goal.tokensUsed) : formatBudget(goal)}`,\n\t];\n\tif (experimentalGoals || queuedGoals.length > 0 || queueFrozen) {\n\t\tsummary.push(\n\t\t\t`Goals (${queuedGoals.length + 1}):`,\n\t\t\t...[goal, ...queuedGoals].map(\n\t\t\t\t(queuedGoal, index) => `${index + 1}. [${queuedGoal.status}] ${queuedGoal.text}`,\n\t\t\t),\n\t\t);\n\t}\n\tif (queueFrozen) {\n\t\tsummary.push(\n\t\t\t\"Queue is frozen. Re-enable experimental.goals and run /reload, or use /goal clear.\",\n\t\t\t\"Commands: /goal, /goal clear\",\n\t\t);\n\t} else {\n\t\tsummary.push(`Commands: ${goalCommandHint(goal.status, experimentalGoals)}`);\n\t}\n\treturn summary.join(\"\\n\");\n}\n\nexport function hasPendingMessages(ctx: StatusContext) {\n\treturn ctx.hasPendingMessages?.() ?? false;\n}\n\nexport function abortCurrentTurn(ctx: StatusContext) {\n\ttry {\n\t\tctx.abort?.();\n\t} catch {\n\t\t// Best effort: stale goal guards still prevent follow-on tool calls.\n\t}\n}\n\nexport function blocksStaleGoalToolCalls(status: GoalStatus) {\n\treturn status === \"paused\" || status === \"blocked\" || status === \"usage_limited\";\n}\n\nexport function isResumableGoalStatus(status: GoalStatus) {\n\treturn blocksStaleGoalToolCalls(status) || status === \"budget_limited\";\n}\n\nexport function stoppedStatusLabel(status: GoalStatus) {\n\tif (status === \"usage_limited\") return \"usage-limited\";\n\tif (status === \"budget_limited\") return \"budget-limited\";\n\treturn status;\n}\n\nexport function isContradictoryCompletionSummary(summary: string) {\n\treturn CONTRADICTORY_COMPLETION_PATTERNS.some((pattern) => pattern.test(summary));\n}\n\nexport function goalIdRejectionReason(goal: ActiveGoal, requestedGoalId: string) {\n\tif (!requestedGoalId) return \"missing goal_id\";\n\tif (requestedGoalId !== goal.id) return \"goal_id does not match the active goal\";\n\treturn undefined;\n}\n\nexport function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {\n\tconst errorMessage = assistant.errorMessage;\n\treturn (\n\t\tassistant.stopReason === \"error\" &&\n\t\ttypeof errorMessage === \"string\" &&\n\t\tUSAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))\n\t);\n}\n\nexport function isRetryableGoalInterruption(assistant: AssistantMessageLike) {\n\tif (assistant.stopReason !== \"error\") return false;\n\tif (!assistant.errorMessage) return false;\n\tif (\n\t\tisUsageLimitedGoalInterruption(assistant) ||\n\t\tNON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)\n\t) {\n\t\treturn false;\n\t}\n\treturn (\n\t\tisGoalContextOverflow(assistant) ||\n\t\tRETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? \"\"))\n\t);\n}\n\nexport function isGoalContextOverflow(assistant: AssistantMessageLike) {\n\treturn isContextOverflow(toPiAssistantMessage(assistant));\n}\n\n/**\n * lunr: best-effort extraction of a usage-limit reset time from a provider error\n * message. Returns an absolute epoch ms to resume after, or undefined. Handles\n * relative delays (\"reset in 2h\", \"try again in 30m\", \"available in 3600s\") and\n * ISO-8601 timestamps. Most provider errors omit this, so undefined is the norm.\n */\nconst USAGE_RESET_TIME_PATTERNS = [\n\t/reset(?:s|ting)?\\s*(?:in|after|at)?\\s*(\\d+)\\s*s(ec)?/i,\n\t/reset(?:s|ting)?\\s*(?:in|after|at)?\\s*(\\d+)\\s*m(in)?/i,\n\t/reset(?:s|ting)?\\s*(?:in|after|at)?\\s*(\\d+)\\s*h(our|r)?/i,\n\t/(?:retry|try(?:\\s+again)?|available)\\s+(?:in|after|at)\\s*(\\d+)\\s*s(ec)?/i,\n\t/(?:retry|try(?:\\s+again)?|available)\\s+(?:in|after|at)\\s*(\\d+)\\s*m(in)?/i,\n\t/(?:retry|try(?:\\s+again)?|available)\\s+(?:in|after|at)\\s*(\\d+)\\s*h(our|r)?/i,\n] as const;\n\nexport function parseUsageResetTimeMs(errorMessage: string | undefined): number | undefined {\n\tif (!errorMessage) return undefined;\n\tconst now = Date.now();\n\tfor (const pattern of USAGE_RESET_TIME_PATTERNS) {\n\t\tconst match = errorMessage.match(pattern);\n\t\tif (!match) continue;\n\t\tconst value = Number.parseInt(match[1] ?? \"\", 10);\n\t\tif (!Number.isFinite(value) || value <= 0) continue;\n\t\tconst unit = pattern.source.includes(\"\\\\s*h\") ? 3600_000 : pattern.source.includes(\"\\\\s*m\") ? 60_000 : 1_000;\n\t\treturn now + value * unit;\n\t}\n\t// ISO-8601 timestamp fallback (e.g. \"reset at 2026-08-01T09:00:00Z\").\n\tconst isoMatch = errorMessage.match(/(?:reset|available).{0,12}(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2})?(?:Z|[+-]\\d{2}:?\\d{2})?)/i);\n\tif (isoMatch?.[1]) {\n\t\tconst parsed = Date.parse(isoMatch[1]);\n\t\tif (Number.isFinite(parsed) && parsed > now) return parsed;\n\t}\n\treturn undefined;\n}\n\nexport function findFinalAssistantMessage(messages: unknown[]): AssistantMessageLike | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (!message || typeof message !== \"object\") continue;\n\t\tconst candidate = message as Record<string, unknown>;\n\t\tif (candidate.role !== \"assistant\") continue;\n\t\tconst assistant: AssistantMessageLike = {\n\t\t\trole: \"assistant\",\n\t\t\tstopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,\n\t\t\terrorMessage: typeof candidate.errorMessage === \"string\" ? candidate.errorMessage : undefined,\n\t\t};\n\t\tif (Array.isArray(candidate.content)) {\n\t\t\tassistant.content = candidate.content as PiAssistantMessage[\"content\"];\n\t\t}\n\t\tif (typeof candidate.api === \"string\") assistant.api = candidate.api;\n\t\tif (typeof candidate.provider === \"string\") assistant.provider = candidate.provider;\n\t\tif (typeof candidate.model === \"string\") assistant.model = candidate.model;\n\t\tif (typeof candidate.timestamp === \"number\") assistant.timestamp = candidate.timestamp;\n\t\tconst usage = normalizeUsage(candidate.usage);\n\t\tif (usage) assistant.usage = usage;\n\t\treturn assistant;\n\t}\n\treturn undefined;\n}\n\nexport function formatError(error: unknown) {\n\treturn truncateNotification(error instanceof Error ? error.message : String(error));\n}\n\nexport function truncateNotification(value: string) {\n\treturn value.length > 160 ? `${value.slice(0, 157)}...` : value;\n}\n\nasync function sendPrompt(pi: ExtensionAPI, ctx: StatusContext, prompt: string) {\n\ttry {\n\t\tawait pi.sendUserMessage(prompt, { deliverAs: \"followUp\" });\n\t\treturn true;\n\t} catch (error) {\n\t\tctx.ui.notify(`Goal prompt failed: ${formatError(error)}`, \"error\");\n\t\treturn false;\n\t}\n}\n\nfunction goalCommandHint(status: GoalStatus, experimentalGoals = false) {\n\tconst queueCommands = experimentalGoals\n\t\t? \", /goal add <objective>, /goal prioritize <objective>, /goal drop-last, /goal skip\"\n\t\t: \"\";\n\tif (status === \"active\") {\n\t\treturn `/goal edit <objective>, /goal pause, /goal clear${queueCommands}`;\n\t}\n\tif (isResumableGoalStatus(status)) {\n\t\treturn `/goal edit <objective>, /goal resume, /goal clear${queueCommands}`;\n\t}\n\treturn `/goal edit <objective>, /goal clear${queueCommands}`;\n}\n\nfunction toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: assistant.content ?? [],\n\t\tapi: assistant.api ?? \"openai-responses\",\n\t\tprovider: assistant.provider ?? \"unknown\",\n\t\tmodel: assistant.model ?? \"unknown\",\n\t\tusage: assistant.usage ?? zeroUsage(),\n\t\tstopReason: assistant.stopReason ?? \"error\",\n\t\terrorMessage: assistant.errorMessage,\n\t\ttimestamp: assistant.timestamp ?? Date.now(),\n\t};\n}\n\nfunction zeroUsage(): Usage {\n\treturn {\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tcost: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotal: 0,\n\t\t},\n\t};\n}\n\nfunction continuationMarker(goal: ActiveGoal) {\n\treturn `${goal.id}:${goal.iteration}:${randomUUID()}`;\n}\n\nfunction escapeRegExpText(value: string) {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nconst GOAL_PROMPT_MARKER_PATTERN = new RegExp(\n\t`<!--\\\\s*${escapeRegExpText(GOAL_PROMPT_MARKER_PREFIX)}([^\\\\s>]+)\\\\s*-->`,\n);\nconst CONTINUATION_MARKER_PATTERN = new RegExp(\n\t`<!--\\\\s*${escapeRegExpText(CONTINUATION_MARKER_PREFIX)}([^\\\\s>]+)\\\\s*-->`,\n);\n\nfunction extractGoalPromptMarker(prompt: string) {\n\treturn GOAL_PROMPT_MARKER_PATTERN.exec(prompt)?.[1];\n}\n\nfunction extractContinuationMarker(prompt: string) {\n\treturn CONTINUATION_MARKER_PATTERN.exec(prompt)?.[1];\n}\n\nfunction isAgentStopReason(value: unknown): value is AgentStopReason {\n\treturn [\"stop\", \"length\", \"toolUse\", \"error\", \"aborted\"].includes(String(value));\n}\n\nfunction normalizeUsage(value: unknown): Usage | undefined {\n\tif (!value || typeof value !== \"object\") return undefined;\n\tconst usage = value as Partial<Usage>;\n\tif (typeof usage.input !== \"number\" || typeof usage.output !== \"number\") return undefined;\n\treturn {\n\t\tinput: nonNegativeFiniteNumber(usage.input),\n\t\toutput: nonNegativeFiniteNumber(usage.output),\n\t\tcacheRead: nonNegativeFiniteNumber(usage.cacheRead),\n\t\tcacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),\n\t\ttotalTokens: assistantUsageTokens(usage),\n\t\tcost: {\n\t\t\tinput: usage.cost?.input ?? 0,\n\t\t\toutput: usage.cost?.output ?? 0,\n\t\t\tcacheRead: usage.cost?.cacheRead ?? 0,\n\t\t\tcacheWrite: usage.cost?.cacheWrite ?? 0,\n\t\t\ttotal: usage.cost?.total ?? 0,\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"runtime.d.ts","sourceRoot":"","sources":["../../../../src/builtin-extensions/narumiruna-pi-goal/src/runtime.ts"],"names":[],"mappings":"AAEA,OAAO,EAEN,KAAK,gBAAgB,IAAI,kBAAkB,EAC3C,KAAK,KAAK,EACV,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iCAAiC,C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AAM,UAEjD","sourcesContent":["// @ts-nocheck\nimport { randomUUID } from \"node:crypto\";\nimport {\n\tisContextOverflow,\n\ttype AssistantMessage as PiAssistantMessage,\n\ttype Usage,\n} from \"@ashx-j/lunr-ai\";\nimport type { ExtensionAPI } from \"@ashx-j/lunr\";\nimport {\n\tassistantUsageTokens,\n\tcheckpointGoalActiveTime,\n\tformatDuration,\n\tformatTokenCount,\n\tnonNegativeFiniteNumber,\n\tupdateGoalUsage,\n} from \"./accounting.js\";\nimport {\n\ttype ActiveGoal,\n\tclearLegacyPersistedGoal,\n\ttype PendingQueueAction,\n\tserializeGoalState,\n} from \"./persistence.js\";\nimport { buildContinuePrompt, type GoalStatus } from \"./prompts.js\";\nimport { DEFAULT_GOAL_SETTINGS, type GoalSettings } from \"./settings.js\";\nimport { enterGoalAuto, leaveGoalAuto } from \"../../../core/permission-mode-control.js\";\n\nexport type AgentStopReason = \"stop\" | \"length\" | \"toolUse\" | \"error\" | \"aborted\";\n\nexport interface ContinuationTicket {\n\tgoalId: string;\n\titeration: number;\n\tmarker: string;\n\tprompt: string;\n}\n\nexport interface BudgetWrapUp {\n\tgoalId: string;\n\tdelivered: boolean;\n}\n\nexport type GoalRecoveryKind = \"provider_retry\" | \"compaction_retry\";\n\nexport interface GoalRecovery {\n\tgoalId: string;\n\tkind: GoalRecoveryKind;\n}\n\nexport interface AssistantMessageLike {\n\trole: \"assistant\";\n\tstopReason?: AgentStopReason;\n\terrorMessage?: string;\n\tcontent?: PiAssistantMessage[\"content\"];\n\tapi?: PiAssistantMessage[\"api\"];\n\tprovider?: PiAssistantMessage[\"provider\"];\n\tmodel?: string;\n\tusage?: Usage;\n\ttimestamp?: number;\n}\n\nexport interface StatusContext {\n\tcwd: string;\n\tui: {\n\t\tconfirm: (title: string, message: string) => Promise<boolean>;\n\t\tnotify: (message: string, level?: \"info\" | \"warning\" | \"error\") => void;\n\t\tsetStatus: (key: string, value: string | undefined) => void;\n\t};\n\tisIdle?: () => boolean;\n\thasPendingMessages?: () => boolean;\n\tabort?: () => void;\n\tsessionManager?: unknown;\n}\n\nexport interface GoalToolVisibilitySnapshot {\n\tactiveTools: string[];\n\tgoalToolsUnlocked: boolean;\n\tgoalToolsHiddenByPolicy: string[];\n}\n\nexport const STATUS_KEY = \"goal\";\nexport const GOAL_STATE_ENTRY_TYPE = \"goal-state\";\nexport const GOAL_COMPLETE_TOOL = \"goal_complete\";\nexport const GOAL_BLOCKED_TOOL = \"goal_blocked\";\nexport const GOAL_TOOL_NAMES = [GOAL_COMPLETE_TOOL, GOAL_BLOCKED_TOOL] as const;\n\nconst MAX_CANCELLED_CONTINUATION_PROMPTS = 20;\nconst MAX_PENDING_GOAL_PROMPTS = 20;\nconst GOAL_PROMPT_MARKER_PREFIX = \"pi-goal-prompt:\";\nconst CONTINUATION_MARKER_PREFIX = \"pi-goal-continuation:\";\nconst BUDGET_WRAP_UP_MESSAGE_TYPE = \"goal-budget-wrap-up\";\nconst BUDGET_WRAP_UP_PROMPT =\n\t\"The active /goal token budget is exhausted. Stop substantive work and do not call substantive tools. Summarize progress, verified results, remaining work, and blockers concisely. Treat completion as unproven. Do not call goal_complete unless authoritative, requirement-by-requirement evidence already proves every requirement is complete. Weak, indirect, or missing evidence is not enough. Budget exhaustion is not completion.\";\nconst CONTRADICTORY_COMPLETION_PATTERNS = [\n\t/(?<!could\\s)\\bnot\\s+(?:yet\\s+)?(?:complete|completed|done|finished)\\b/i,\n\t/\\bstill\\s+(?:incomplete|failing|failing\\s+tests?|fails?)\\b/i,\n\t/\\btests?\\s+(?:still\\s+)?fail(?:ing)?\\b/i,\n] as const;\nconst USAGE_LIMIT_GOAL_ERROR_PATTERNS = [\n\t/usage[_\\s-]*(?:limit|cap)|chatgpt.{0,32}usage/i,\n\t/quota.{0,32}(?:reached|exceeded|exhausted|depleted)|(?:reached|exceeded|exhausted|depleted).{0,32}quota/i,\n\t/insufficient[_\\s-]*(?:quota|credits?)|out of credits|out of budget|available balance|payment required/i,\n\t/(?:credit|balance).{0,32}(?:low|exhausted|depleted)|billing/i,\n] as const;\nconst NON_RETRYABLE_GOAL_ERROR_RE =\n\t/multi-auth rotation failed|credentials tried|unauthori[sz]ed|invalid api key/i;\n// Pi 0.79 does not export its assistant-error retry classifier. Keep this\n// compatibility mirror aligned with Pi's public retry utility in newer versions.\nconst RETRYABLE_GOAL_ERROR_PATTERNS = [\n\t/overloaded|rate.?limit|too many requests|\\b(?:429|500|502|503|504)\\b|service.?unavailable|server.?error|internal.?error/i,\n\t/provider.?returned.?error|you can retry your request|try your request again|please retry your request/i,\n\t/network.?error|connection.?(?:error|refused|lost)|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up/i,\n\t/timed? out|timeout|terminated|websocket.?(?:closed|error)|ended without|stream ended before message_stop|http2 request did not get a response|retry delay/i,\n\t/context[_\\s-]*length[_\\s-]*exceeded|input exceeds the context window/i,\n] as const;\n\n// One instance belongs to one extension factory. It owns all mutable session state\n// and the cross-cutting invariants used by command and lifecycle orchestration.\nexport class GoalRuntime {\n\tsettings: GoalSettings = DEFAULT_GOAL_SETTINGS;\n\tactiveGoal?: ActiveGoal;\n\tqueuedGoals: ActiveGoal[] = [];\n\tpendingQueueAction?: PendingQueueAction;\n\tqueueFrozen = false;\n\tcompletionStatusTimer?: NodeJS.Timeout;\n\t// lunr: 30s footer refresh timer so the goal indicator's elapsed minutes tick while active\n\tstatusRefreshTimer?: NodeJS.Timeout;\n\tstatusRefreshCtx?: StatusContext;\n\tcontinuationIntent?: ContinuationTicket;\n\tcontinuationDelivery?: ContinuationTicket;\n\tgoalRecovery?: GoalRecovery;\n\tbudgetWrapUp?: BudgetWrapUp;\n\t/** `null` marks a run that must not be charged to the active goal. */\n\tagentRunGoalId?: string | null;\n\tstaleGoalToolCallsBlocked = false;\n\t/** Once true, goal tools stay in the active set for this runtime (prompt-cache stable). */\n\tgoalToolsUnlocked = false;\n\t/** Exact lazy goal tools this runtime removed and may restore on a mode change. */\n\tgoalToolsHiddenByPolicy = new Set<string>();\n\tpendingGoalPromptMarkers = new Map<string, string>();\n\tcancelledContinuationMarkers = new Set<string>();\n\n\treadonly pi: ExtensionAPI;\n\n\tconstructor(pi: ExtensionAPI) {\n\t\tthis.pi = pi;\n\t}\n\n\tcanRecordGoalUsage() {\n\t\treturn (\n\t\t\tthis.agentRunGoalId !== null &&\n\t\t\t!(\n\t\t\t\tthis.pendingQueueAction?.kind === \"prioritize\" &&\n\t\t\t\tthis.pendingQueueAction.displacedUsageFinalized === true\n\t\t\t)\n\t\t);\n\t}\n\n\thasActiveBudgetWrapUp() {\n\t\treturn (\n\t\t\tthis.activeGoal?.status === \"budget_limited\" &&\n\t\t\tthis.budgetWrapUp?.goalId === this.activeGoal.id &&\n\t\t\tthis.budgetWrapUp.delivered\n\t\t);\n\t}\n\n\thasActiveGoalRecovery() {\n\t\treturn Boolean(this.activeGoal && this.goalRecovery?.goalId === this.activeGoal.id);\n\t}\n\n\trecordGoalUsage(\n\t\tgoal: ActiveGoal,\n\t\tctx: StatusContext,\n\t\tcheckpointActiveTime = goal.status === \"active\",\n\t) {\n\t\tif (!this.canRecordGoalUsage()) return false;\n\t\tupdateGoalUsage(goal, ctx, checkpointActiveTime);\n\t\treturn true;\n\t}\n\n\trequestContinuation(goal: ActiveGoal) {\n\t\tif (this.hasContinuationWorkForGoal(goal.id)) return false;\n\t\tconst marker = continuationMarker(goal);\n\t\tthis.continuationIntent = {\n\t\t\tgoalId: goal.id,\n\t\t\titeration: goal.iteration,\n\t\t\tmarker,\n\t\t\tprompt: buildContinuePrompt(goal, marker),\n\t\t};\n\t\treturn true;\n\t}\n\n\tdispatchContinuationIfSettled(ctx: StatusContext) {\n\t\tconst intent = this.continuationIntent;\n\t\tif (!intent) return false;\n\t\tif (this.activeGoal?.status === \"active\" && !this.goalToolsAvailable()) {\n\t\t\tthis.pauseGoalForUnavailableTools(ctx);\n\t\t\treturn false;\n\t\t}\n\t\tif (\n\t\t\t!this.activeGoal ||\n\t\t\tthis.activeGoal.id !== intent.goalId ||\n\t\t\tthis.activeGoal.status !== \"active\"\n\t\t) {\n\t\t\tthis.continuationIntent = undefined;\n\t\t\treturn false;\n\t\t}\n\t\tif (ctx.isIdle?.() !== true || hasPendingMessages(ctx)) return false;\n\n\t\tthis.continuationIntent = undefined;\n\t\tthis.continuationDelivery = intent;\n\t\ttry {\n\t\t\tthis.pi.sendUserMessage(intent.prompt, { deliverAs: \"followUp\" });\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (this.continuationDelivery?.marker === intent.marker) {\n\t\t\t\tthis.continuationDelivery = undefined;\n\t\t\t}\n\t\t\tif (this.activeGoal?.id === intent.goalId && this.activeGoal.status === \"active\") {\n\t\t\t\tthis.continuationIntent = intent;\n\t\t\t}\n\t\t\tctx.ui.notify(`Goal prompt failed: ${formatError(error)}`, \"error\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\thasContinuationWorkForGoal(goalId: string) {\n\t\treturn (\n\t\t\tthis.continuationIntent?.goalId === goalId || this.continuationDelivery?.goalId === goalId\n\t\t);\n\t}\n\n\tsyncGoalPermissionMode(goal?: ActiveGoal) {\n\t\tif (goal?.status === \"active\") enterGoalAuto();\n\t\telse leaveGoalAuto();\n\t}\n\n\tupdateStatus(ctx: StatusContext, goal: ActiveGoal) {\n\t\tthis.clearCompletionStatusTimer();\n\t\tthis.syncGoalPermissionMode(goal);\n\t\tctx.ui.setStatus(STATUS_KEY, formatStatus(goal));\n\t\t// lunr: refresh the footer every 30s while a goal is active so the elapsed time ticks\n\t\tthis.clearStatusRefreshTimer();\n\t\tif (goal.status === \"active\") {\n\t\t\tthis.statusRefreshCtx = ctx;\n\t\t\tthis.statusRefreshTimer = setInterval(() => {\n\t\t\t\tconst currentGoal = this.activeGoal;\n\t\t\t\tconst refreshCtx = this.statusRefreshCtx;\n\t\t\t\tif (!currentGoal || currentGoal.status !== \"active\" || !refreshCtx) {\n\t\t\t\t\tthis.clearStatusRefreshTimer();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\trefreshCtx.ui.setStatus(STATUS_KEY, formatStatus(currentGoal));\n\t\t\t\t} catch {\n\t\t\t\t\t// The captured ctx may be stale after session replacement or reload.\n\t\t\t\t\tthis.clearStatusRefreshTimer();\n\t\t\t\t}\n\t\t\t}, 30_000);\n\t\t\tthis.statusRefreshTimer.unref?.();\n\t\t}\n\t}\n\n\t// lunr: paired with the status refresh interval started in updateStatus()\n\tclearStatusRefreshTimer() {\n\t\tif (!this.statusRefreshTimer) return;\n\t\tclearInterval(this.statusRefreshTimer);\n\t\tthis.statusRefreshTimer = undefined;\n\t\tthis.statusRefreshCtx = undefined;\n\t}\n\n\tblockStaleGoalToolCalls() {\n\t\tthis.staleGoalToolCallsBlocked = true;\n\t}\n\n\tclearStaleGoalToolCallBlock() {\n\t\tthis.staleGoalToolCallsBlocked = false;\n\t}\n\n\tclearGoalRecovery() {\n\t\tthis.goalRecovery = undefined;\n\t}\n\n\tclearBudgetWrapUp() {\n\t\tthis.budgetWrapUp = undefined;\n\t}\n\n\tkeepBudgetWrapUpMessage(message: unknown) {\n\t\tif (!message || typeof message !== \"object\") return true;\n\t\tconst candidate = message as {\n\t\t\trole?: unknown;\n\t\t\tcustomType?: unknown;\n\t\t\tdetails?: { goalId?: unknown };\n\t\t};\n\t\tif (candidate.role !== \"custom\" || candidate.customType !== BUDGET_WRAP_UP_MESSAGE_TYPE) {\n\t\t\treturn true;\n\t\t}\n\t\treturn (\n\t\t\ttypeof candidate.details?.goalId === \"string\" &&\n\t\t\tcandidate.details.goalId === this.budgetWrapUp?.goalId &&\n\t\t\tcandidate.details.goalId === this.activeGoal?.id\n\t\t);\n\t}\n\n\tqueueBudgetWrapUp(ctx: StatusContext, goal: ActiveGoal) {\n\t\tif (!this.budgetWrapUp || this.budgetWrapUp.goalId !== goal.id) {\n\t\t\tthis.budgetWrapUp = { goalId: goal.id, delivered: false };\n\t\t}\n\t\tif (this.budgetWrapUp.delivered) return true;\n\t\tthis.budgetWrapUp.delivered = true;\n\t\ttry {\n\t\t\tthis.pi.sendMessage(\n\t\t\t\t{\n\t\t\t\t\tcustomType: BUDGET_WRAP_UP_MESSAGE_TYPE,\n\t\t\t\t\tcontent: BUDGET_WRAP_UP_PROMPT,\n\t\t\t\t\tdisplay: true,\n\t\t\t\t\tdetails: { goalId: goal.id },\n\t\t\t\t},\n\t\t\t\t{ deliverAs: \"steer\" },\n\t\t\t);\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tthis.budgetWrapUp.delivered = false;\n\t\t\tctx.ui.notify(`Goal budget wrap-up failed: ${formatError(error)}`, \"error\");\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tlimitActiveGoalForBudget(ctx: StatusContext, sendWrapUp: boolean) {\n\t\tconst goal = this.activeGoal;\n\t\tif (\n\t\t\tgoal?.status !== \"active\" ||\n\t\t\tgoal.tokenBudget === undefined ||\n\t\t\tgoal.tokensUsed < goal.tokenBudget\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\n\t\tthis.cancelContinuationWork();\n\t\tthis.clearGoalRecoveryForGoal(goal.id);\n\t\tthis.clearBudgetWrapUp();\n\t\tthis.activeGoal = transitionGoal(goal, \"budget_limited\");\n\t\tthis.persistGoal(this.activeGoal);\n\t\tthis.updateStatus(ctx, this.activeGoal);\n\t\tctx.ui.notify(`Goal token budget reached: ${formatBudget(this.activeGoal)}`, \"warning\");\n\t\tif (sendWrapUp) this.queueBudgetWrapUp(ctx, this.activeGoal);\n\t\treturn true;\n\t}\n\n\tclearGoalRecoveryForGoal(goalId: string) {\n\t\tif (this.goalRecovery?.goalId === goalId) this.goalRecovery = undefined;\n\t}\n\n\tisPiOwnedCompactionRetry(event: unknown, goalId: string) {\n\t\tconst compaction = event as { reason?: unknown; willRetry?: unknown };\n\t\tif (compaction.willRetry === true) return true;\n\t\treturn (\n\t\t\tthis.goalRecovery?.goalId === goalId &&\n\t\t\tthis.goalRecovery.kind === \"compaction_retry\" &&\n\t\t\t(compaction.reason === undefined || compaction.reason === \"overflow\")\n\t\t);\n\t}\n\n\tclearContinuationTracking() {\n\t\tthis.continuationIntent = undefined;\n\t\tthis.continuationDelivery = undefined;\n\t\tthis.cancelledContinuationMarkers.clear();\n\t}\n\n\tclearPendingGoalPrompts() {\n\t\tthis.pendingGoalPromptMarkers.clear();\n\t}\n\n\tasync sendOwnedGoalPrompt(ctx: StatusContext, goalId: string, prompt: string) {\n\t\tconst pending = this.rememberPendingGoalPrompt(goalId, prompt);\n\t\tconst sent = await sendPrompt(this.pi, ctx, pending.prompt);\n\t\tif (!sent) this.pendingGoalPromptMarkers.delete(pending.marker);\n\t\treturn sent;\n\t}\n\n\tcancelContinuationWork() {\n\t\tif (this.continuationDelivery) {\n\t\t\tthis.rememberCancelledContinuationMarker(this.continuationDelivery.marker);\n\t\t}\n\t\tthis.continuationIntent = undefined;\n\t\tthis.continuationDelivery = undefined;\n\t}\n\n\tconsumeCancelledContinuationPrompt(prompt: string) {\n\t\tconst marker = extractContinuationMarker(prompt);\n\t\treturn marker ? this.cancelledContinuationMarkers.delete(marker) : false;\n\t}\n\n\tconsumeStaleOwnedGoalPrompt(prompt: string) {\n\t\tconst marker = extractGoalPromptMarker(prompt);\n\t\tif (!marker) return false;\n\t\tconst goalId = this.pendingGoalPromptMarkers.get(marker);\n\t\tif (!goalId) return false;\n\t\tif (\n\t\t\t!this.queueFrozen &&\n\t\t\t!this.pendingQueueAction &&\n\t\t\tthis.activeGoal?.id === goalId &&\n\t\t\tthis.activeGoal.status === \"active\"\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tthis.pendingGoalPromptMarkers.delete(marker);\n\t\treturn true;\n\t}\n\n\tmarkContinuationStarted(prompt: string) {\n\t\tconst marker = extractContinuationMarker(prompt);\n\t\tif (!marker) {\n\t\t\t// A user, retry, or another extension started newer work. Cancel both an\n\t\t\t// unsent intent and a delivery that may have lost the non-atomic idle race;\n\t\t\t// the newer work's agent_end will record a fresh intent.\n\t\t\tthis.cancelContinuationWork();\n\t\t\treturn undefined;\n\t\t}\n\t\tif (this.continuationDelivery?.marker === marker) this.continuationDelivery = undefined;\n\t\treturn marker.split(\":\", 1)[0];\n\t}\n\n\tpersistGoal(goal: ActiveGoal) {\n\t\tthis.pi.appendEntry(\n\t\t\tGOAL_STATE_ENTRY_TYPE,\n\t\t\tserializeGoalState(goal, this.queuedGoals, this.pendingQueueAction),\n\t\t);\n\t}\n\n\tclearPersistedGoal(cwd: string) {\n\t\tthis.pi.appendEntry(GOAL_STATE_ENTRY_TYPE, serializeGoalState(undefined, [], undefined));\n\t\tclearLegacyPersistedGoal(cwd);\n\t}\n\n\tclearActiveGoal(ctx: StatusContext) {\n\t\tthis.clearStatusRefreshTimer(); // lunr: stop the footer refresh when the goal is cleared\n\t\tthis.syncGoalPermissionMode(undefined);\n\t\tthis.cancelContinuationWork();\n\t\tthis.clearGoalRecovery();\n\t\tthis.clearBudgetWrapUp();\n\t\tthis.clearStaleGoalToolCallBlock();\n\t\tthis.activeGoal = undefined;\n\t\tthis.queuedGoals = [];\n\t\tthis.pendingQueueAction = undefined;\n\t\tthis.queueFrozen = false;\n\t\tthis.clearPersistedGoal(ctx.cwd);\n\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t// Do not clear goalToolsUnlocked: after first activation, keep tools visible\n\t\t// for the rest of this extension runtime to avoid repeated goal-tool schema\n\t\t// churn within the same runtime.\n\t}\n\n\tisGoalToolName(name: string) {\n\t\treturn (GOAL_TOOL_NAMES as readonly string[]).includes(name);\n\t}\n\n\tgoalToolsAvailable() {\n\t\tconst active = new Set(this.pi.getActiveTools());\n\t\treturn GOAL_TOOL_NAMES.every((name) => active.has(name));\n\t}\n\n\thideGoalToolsIfLocked() {\n\t\tif (this.goalToolsUnlocked) return;\n\t\tconst active = this.pi.getActiveTools();\n\t\tconst hidden = active.filter((name) => this.isGoalToolName(name));\n\t\tif (hidden.length === 0) return;\n\t\t// lunr: do not mutate the active tool list (Anthropic tools sit at the\n\t\t// front of the cache prefix). Locked goal tools stay registered; the\n\t\t// tool_call gate rejects them until a /goal is activated.\n\t\tfor (const name of hidden) this.goalToolsHiddenByPolicy.add(name);\n\t}\n\n\trestoreGoalToolsHiddenByPolicy() {\n\t\t// lunr: flags only — the tool list is never rewritten at runtime.\n\t\tthis.goalToolsHiddenByPolicy.clear();\n\t}\n\n\tassertGoalToolsAvailable() {\n\t\tif (this.goalToolsAvailable()) return;\n\t\tthrow new Error(\n\t\t\t\"goal_complete and goal_blocked are unavailable; include them in the active tool allowlist or leave the restrictive tool mode first.\",\n\t\t);\n\t}\n\n\tensureGoalToolsVisible() {\n\t\t// lunr: never add/remove tools mid-session. Assert they were already\n\t\t// registered at session start so the wire bytes stay stable.\n\t\tthis.assertGoalToolsAvailable();\n\t}\n\n\tprepareGoalToolsForActivation(ctx: StatusContext) {\n\t\tif (this.settings.toolVisibility === \"after-first-goal\") {\n\t\t\tif (!this.goalToolsAvailable() && ctx.isIdle?.() !== true) {\n\t\t\t\tthrow new Error(\"wait until Pi is idle before revealing the goal tools\");\n\t\t\t}\n\t\t\tthis.revealGoalTools();\n\t\t\treturn;\n\t\t}\n\t\tthis.assertGoalToolsAvailable();\n\t}\n\n\t/** Mark lazy tools permanently desired for this runtime and make them active now. */\n\trevealGoalTools() {\n\t\tconst wasUnlocked = this.goalToolsUnlocked;\n\t\ttry {\n\t\t\tthis.ensureGoalToolsVisible();\n\t\t\tthis.goalToolsUnlocked = true;\n\t\t\tthis.goalToolsHiddenByPolicy.clear();\n\t\t} catch (error) {\n\t\t\tthis.goalToolsUnlocked = wasUnlocked;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tsnapshotGoalToolVisibility(): GoalToolVisibilitySnapshot {\n\t\treturn {\n\t\t\tactiveTools: this.pi.getActiveTools(),\n\t\t\tgoalToolsUnlocked: this.goalToolsUnlocked,\n\t\t\tgoalToolsHiddenByPolicy: [...this.goalToolsHiddenByPolicy],\n\t\t};\n\t}\n\n\t/**\n\t * lunr: reactivate a stopped (usage_limited / paused / blocked / budget_limited)\n\t * goal back to active WITHOUT sending a prompt. Shared by the /goal resume\n\t * command and the auto-resume hook (cron wake-up). Returns the reactivated goal\n\t * or undefined if reactivation was rejected (tools unavailable, budget reached).\n\t * Consumes resumeAfter so a single schedule only fires once.\n\t */\n\treactivateGoalForResume(ctx: StatusContext): ActiveGoal | undefined {\n\t\tif (!this.activeGoal) return undefined;\n\t\tif (!isResumableGoalStatus(this.activeGoal.status)) return undefined;\n\t\tif (\n\t\t\tthis.activeGoal.tokenBudget !== undefined &&\n\t\t\tthis.activeGoal.tokensUsed >= this.activeGoal.tokenBudget\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\ttry {\n\t\t\tthis.prepareGoalToolsForActivation(ctx);\n\t\t} catch (error) {\n\t\t\tctx.ui.notify(`Cannot resume /goal: ${formatError(error)}`, \"error\");\n\t\t\treturn undefined;\n\t\t}\n\t\tthis.cancelContinuationWork();\n\t\tthis.clearGoalRecovery();\n\t\tthis.clearBudgetWrapUp();\n\t\tthis.clearStaleGoalToolCallBlock();\n\t\tconst next = transitionGoal(nextGoalInstance(this.activeGoal), \"active\");\n\t\tthis.activeGoal = { ...next, resumeAfter: undefined };\n\t\tthis.persistGoal(this.activeGoal);\n\t\tthis.updateStatus(ctx, this.activeGoal);\n\t\tif (this.activeGoal.status !== \"active\") return undefined;\n\t\treturn this.activeGoal;\n\t}\n\n\trestoreGoalToolVisibility(snapshot: GoalToolVisibilitySnapshot) {\n\t\t// lunr: restore unlock/hidden flags only — never rewrite the tool list.\n\t\tthis.goalToolsUnlocked = snapshot.goalToolsUnlocked;\n\t\tthis.goalToolsHiddenByPolicy.clear();\n\t\tfor (const name of snapshot.goalToolsHiddenByPolicy) {\n\t\t\tthis.goalToolsHiddenByPolicy.add(name);\n\t\t}\n\t}\n\n\tareGoalToolsLocked() {\n\t\treturn !this.goalToolsUnlocked && this.settings.toolVisibility === \"after-first-goal\";\n\t}\n\n\tpauseGoalForUnavailableTools(ctx: StatusContext, abortTurn = true, recordUsage = true) {\n\t\tconst goal = this.activeGoal;\n\t\tif (goal?.status !== \"active\") return false;\n\t\tif (recordUsage) this.recordGoalUsage(goal, ctx);\n\t\tthis.cancelContinuationWork();\n\t\tthis.clearGoalRecoveryForGoal(goal.id);\n\t\tthis.clearBudgetWrapUp();\n\t\tif (abortTurn) {\n\t\t\tthis.blockStaleGoalToolCalls();\n\t\t\tabortCurrentTurn(ctx);\n\t\t} else {\n\t\t\tthis.clearStaleGoalToolCallBlock();\n\t\t}\n\t\tthis.activeGoal = transitionGoal(goal, \"paused\");\n\t\tthis.persistGoal(this.activeGoal);\n\t\tthis.updateStatus(ctx, this.activeGoal);\n\t\tctx.ui.notify(\n\t\t\t\"Goal tools are unavailable, so the active goal was paused. Restore the tools and run /goal resume.\",\n\t\t\t\"warning\",\n\t\t);\n\t\treturn true;\n\t}\n\n\tshowCompletionStatus(ctx: StatusContext) {\n\t\tthis.clearCompletionStatusTimer();\n\t\tthis.clearStatusRefreshTimer(); // lunr: stop the footer refresh on completion\n\t\tthis.syncGoalPermissionMode(undefined);\n\t\t// lunr: enriched footer status format\n\t\tctx.ui.setStatus(STATUS_KEY, \"goal ✓ complete\");\n\t\tthis.completionStatusTimer = setTimeout(() => {\n\t\t\tthis.completionStatusTimer = undefined;\n\t\t\ttry {\n\t\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\t} catch {\n\t\t\t\t// The completion status is best-effort; the captured ctx may be stale after\n\t\t\t\t// session replacement or reload before this timer fires.\n\t\t\t}\n\t\t}, 8_000);\n\t}\n\n\tclearCompletionStatusTimer() {\n\t\tif (!this.completionStatusTimer) return;\n\t\tclearTimeout(this.completionStatusTimer);\n\t\tthis.completionStatusTimer = undefined;\n\t}\n\n\tprivate rememberPendingGoalPrompt(goalId: string, prompt: string) {\n\t\tconst marker = randomUUID();\n\t\tthis.pendingGoalPromptMarkers.set(marker, goalId);\n\t\tif (this.pendingGoalPromptMarkers.size > MAX_PENDING_GOAL_PROMPTS) {\n\t\t\tconst oldest = this.pendingGoalPromptMarkers.keys().next().value;\n\t\t\tif (oldest) this.pendingGoalPromptMarkers.delete(oldest);\n\t\t}\n\t\treturn { marker, prompt: `${prompt}\\n\\n<!-- ${GOAL_PROMPT_MARKER_PREFIX}${marker} -->` };\n\t}\n\n\tprivate consumePendingGoalPrompt(prompt: string) {\n\t\tconst marker = extractGoalPromptMarker(prompt);\n\t\tif (!marker) return undefined;\n\t\tconst goalId = this.pendingGoalPromptMarkers.get(marker);\n\t\tthis.pendingGoalPromptMarkers.delete(marker);\n\t\treturn goalId;\n\t}\n\n\tconsumeOwnedGoalPrompt(prompt: string) {\n\t\treturn this.consumePendingGoalPrompt(prompt);\n\t}\n\n\tprivate rememberCancelledContinuationMarker(marker: string) {\n\t\tthis.cancelledContinuationMarkers.add(marker);\n\t\tif (this.cancelledContinuationMarkers.size <= MAX_CANCELLED_CONTINUATION_PROMPTS) return;\n\t\tconst oldest = this.cancelledContinuationMarkers.values().next().value;\n\t\tif (oldest) this.cancelledContinuationMarkers.delete(oldest);\n\t}\n}\n\nexport function createGoal(\n\ttext: string,\n\ttokenBudget: number | undefined,\n\tbaselineTokens: number,\n): ActiveGoal {\n\tconst now = Date.now();\n\treturn {\n\t\tid: randomUUID(),\n\t\ttext,\n\t\tstatus: \"active\",\n\t\tstartedAt: now,\n\t\tupdatedAt: now,\n\t\titeration: 0,\n\t\ttokenBudget,\n\t\ttokensUsed: 0,\n\t\ttimeUsedSeconds: 0,\n\t\tbaselineTokens,\n\t\tactiveStartedAt: now,\n\t};\n}\n\nexport function transitionGoal(goal: ActiveGoal, requestedStatus: GoalStatus): ActiveGoal {\n\tconst now = Date.now();\n\tconst status =\n\t\trequestedStatus === \"active\" &&\n\t\tgoal.tokenBudget !== undefined &&\n\t\tgoal.tokensUsed >= goal.tokenBudget\n\t\t\t? \"budget_limited\"\n\t\t\t: requestedStatus;\n\tconst next = { ...goal, status, updatedAt: now };\n\tcheckpointGoalActiveTime(next, now, status === \"active\");\n\treturn next;\n}\n\nexport function nextGoalInstance(goal: ActiveGoal): ActiveGoal {\n\treturn { ...goal, id: randomUUID(), updatedAt: Date.now() };\n}\n\nexport function editedGoalStatus(status: GoalStatus): GoalStatus {\n\tif (status === \"paused\" || status === \"blocked\" || status === \"usage_limited\") return status;\n\treturn \"active\";\n}\n\nexport function incrementGoal(goal: ActiveGoal): ActiveGoal {\n\treturn { ...goal, iteration: goal.iteration + 1, updatedAt: Date.now() };\n}\n\n// lunr: footer status — active is just `goal` (elapsed/turns stay on paused)\nexport function formatStatus(goal: ActiveGoal | undefined) {\n\tif (!goal) return undefined;\n\tif (goal.status === \"complete\") return \"goal ✓ complete\";\n\tif (goal.status === \"queued\") return \"goal queued\";\n\tif (goal.status === \"paused\") {\n\t\treturn `goal ◌ paused · ${formatGoalElapsed(goal)} · ${formatGoalTurns(goal)}`;\n\t}\n\tif (goal.status === \"blocked\") return \"goal ✗ blocked\";\n\tif (goal.status === \"usage_limited\") return \"goal usage-limited\";\n\tif (goal.status === \"budget_limited\") return `goal budget ${formatBudget(goal)}`;\n\t// lunr: active (and budget-suffixed active) display text is exactly `goal`\n\tif (goal.tokenBudget !== undefined) return `goal · ${formatBudget(goal)}`;\n\treturn \"goal\";\n}\n\n// lunr: live elapsed = accumulated active time + the in-progress active segment\nfunction goalElapsedSeconds(goal: ActiveGoal) {\n\tlet seconds = nonNegativeFiniteNumber(goal.timeUsedSeconds);\n\tif (typeof goal.activeStartedAt === \"number\" && Number.isFinite(goal.activeStartedAt)) {\n\t\tseconds += Math.max(0, Date.now() - goal.activeStartedAt) / 1000;\n\t}\n\treturn seconds;\n}\n\n// lunr: footer elapsed format — `Xm` under 1h, `XhYm` after\nfunction formatGoalElapsed(goal: ActiveGoal) {\n\tconst totalMinutes = Math.floor(goalElapsedSeconds(goal) / 60);\n\tif (totalMinutes < 60) return `${totalMinutes}m`;\n\treturn `${Math.floor(totalMinutes / 60)}h${totalMinutes % 60}m`;\n}\n\n// lunr: footer turn count, singular at 1\nfunction formatGoalTurns(goal: ActiveGoal) {\n\treturn goal.iteration === 1 ? \"1 turn\" : `${goal.iteration} turns`;\n}\n\nexport function formatBudget(goal: ActiveGoal) {\n\treturn `${formatTokenCount(goal.tokensUsed)}/${formatTokenCount(goal.tokenBudget ?? 0)}`;\n}\n\nexport function goalSummary(\n\tgoal: ActiveGoal,\n\tqueuedGoals: readonly ActiveGoal[] = [],\n\texperimentalGoals = false,\n\tqueueFrozen = false,\n) {\n\tconst summary = [\n\t\t`Goal: ${goal.text}`,\n\t\t`Status: ${queueFrozen ? \"queue off\" : goal.status}`,\n\t\t`Iteration: ${goal.iteration}`,\n\t\t`Active elapsed: ${formatDuration(goal.timeUsedSeconds)}`,\n\t\t`Tokens: ${goal.tokenBudget === undefined ? formatTokenCount(goal.tokensUsed) : formatBudget(goal)}`,\n\t];\n\tif (experimentalGoals || queuedGoals.length > 0 || queueFrozen) {\n\t\tsummary.push(\n\t\t\t`Goals (${queuedGoals.length + 1}):`,\n\t\t\t...[goal, ...queuedGoals].map(\n\t\t\t\t(queuedGoal, index) => `${index + 1}. [${queuedGoal.status}] ${queuedGoal.text}`,\n\t\t\t),\n\t\t);\n\t}\n\tif (queueFrozen) {\n\t\tsummary.push(\n\t\t\t\"Queue is frozen. Re-enable experimental.goals and run /reload, or use /goal clear.\",\n\t\t\t\"Commands: /goal, /goal clear\",\n\t\t);\n\t} else {\n\t\tsummary.push(`Commands: ${goalCommandHint(goal.status, experimentalGoals)}`);\n\t}\n\treturn summary.join(\"\\n\");\n}\n\nexport function hasPendingMessages(ctx: StatusContext) {\n\treturn ctx.hasPendingMessages?.() ?? false;\n}\n\nexport function abortCurrentTurn(ctx: StatusContext) {\n\ttry {\n\t\tctx.abort?.();\n\t} catch {\n\t\t// Best effort: stale goal guards still prevent follow-on tool calls.\n\t}\n}\n\nexport function blocksStaleGoalToolCalls(status: GoalStatus) {\n\treturn status === \"paused\" || status === \"blocked\" || status === \"usage_limited\";\n}\n\nexport function isResumableGoalStatus(status: GoalStatus) {\n\treturn blocksStaleGoalToolCalls(status) || status === \"budget_limited\";\n}\n\nexport function stoppedStatusLabel(status: GoalStatus) {\n\tif (status === \"usage_limited\") return \"usage-limited\";\n\tif (status === \"budget_limited\") return \"budget-limited\";\n\treturn status;\n}\n\nexport function isContradictoryCompletionSummary(summary: string) {\n\treturn CONTRADICTORY_COMPLETION_PATTERNS.some((pattern) => pattern.test(summary));\n}\n\nexport function goalIdRejectionReason(goal: ActiveGoal, requestedGoalId: string) {\n\tif (!requestedGoalId) return \"missing goal_id\";\n\tif (requestedGoalId !== goal.id) return \"goal_id does not match the active goal\";\n\treturn undefined;\n}\n\nexport function isUsageLimitedGoalInterruption(assistant: AssistantMessageLike) {\n\tconst errorMessage = assistant.errorMessage;\n\treturn (\n\t\tassistant.stopReason === \"error\" &&\n\t\ttypeof errorMessage === \"string\" &&\n\t\tUSAGE_LIMIT_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(errorMessage))\n\t);\n}\n\nexport function isRetryableGoalInterruption(assistant: AssistantMessageLike) {\n\tif (assistant.stopReason !== \"error\") return false;\n\tif (!assistant.errorMessage) return false;\n\tif (\n\t\tisUsageLimitedGoalInterruption(assistant) ||\n\t\tNON_RETRYABLE_GOAL_ERROR_RE.test(assistant.errorMessage)\n\t) {\n\t\treturn false;\n\t}\n\treturn (\n\t\tisGoalContextOverflow(assistant) ||\n\t\tRETRYABLE_GOAL_ERROR_PATTERNS.some((pattern) => pattern.test(assistant.errorMessage ?? \"\"))\n\t);\n}\n\nexport function isGoalContextOverflow(assistant: AssistantMessageLike) {\n\treturn isContextOverflow(toPiAssistantMessage(assistant));\n}\n\n/**\n * lunr: best-effort extraction of a usage-limit reset time from a provider error\n * message. Returns an absolute epoch ms to resume after, or undefined. Handles\n * relative delays (\"reset in 2h\", \"try again in 30m\", \"available in 3600s\") and\n * ISO-8601 timestamps. Most provider errors omit this, so undefined is the norm.\n */\nconst USAGE_RESET_TIME_PATTERNS = [\n\t/reset(?:s|ting)?\\s*(?:in|after|at)?\\s*(\\d+)\\s*s(ec)?/i,\n\t/reset(?:s|ting)?\\s*(?:in|after|at)?\\s*(\\d+)\\s*m(in)?/i,\n\t/reset(?:s|ting)?\\s*(?:in|after|at)?\\s*(\\d+)\\s*h(our|r)?/i,\n\t/(?:retry|try(?:\\s+again)?|available)\\s+(?:in|after|at)\\s*(\\d+)\\s*s(ec)?/i,\n\t/(?:retry|try(?:\\s+again)?|available)\\s+(?:in|after|at)\\s*(\\d+)\\s*m(in)?/i,\n\t/(?:retry|try(?:\\s+again)?|available)\\s+(?:in|after|at)\\s*(\\d+)\\s*h(our|r)?/i,\n] as const;\n\nexport function parseUsageResetTimeMs(errorMessage: string | undefined): number | undefined {\n\tif (!errorMessage) return undefined;\n\tconst now = Date.now();\n\tfor (const pattern of USAGE_RESET_TIME_PATTERNS) {\n\t\tconst match = errorMessage.match(pattern);\n\t\tif (!match) continue;\n\t\tconst value = Number.parseInt(match[1] ?? \"\", 10);\n\t\tif (!Number.isFinite(value) || value <= 0) continue;\n\t\tconst unit = pattern.source.includes(\"\\\\s*h\") ? 3600_000 : pattern.source.includes(\"\\\\s*m\") ? 60_000 : 1_000;\n\t\treturn now + value * unit;\n\t}\n\t// ISO-8601 timestamp fallback (e.g. \"reset at 2026-08-01T09:00:00Z\").\n\tconst isoMatch = errorMessage.match(/(?:reset|available).{0,12}(\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2})?(?:Z|[+-]\\d{2}:?\\d{2})?)/i);\n\tif (isoMatch?.[1]) {\n\t\tconst parsed = Date.parse(isoMatch[1]);\n\t\tif (Number.isFinite(parsed) && parsed > now) return parsed;\n\t}\n\treturn undefined;\n}\n\nexport function findFinalAssistantMessage(messages: unknown[]): AssistantMessageLike | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (!message || typeof message !== \"object\") continue;\n\t\tconst candidate = message as Record<string, unknown>;\n\t\tif (candidate.role !== \"assistant\") continue;\n\t\tconst assistant: AssistantMessageLike = {\n\t\t\trole: \"assistant\",\n\t\t\tstopReason: isAgentStopReason(candidate.stopReason) ? candidate.stopReason : undefined,\n\t\t\terrorMessage: typeof candidate.errorMessage === \"string\" ? candidate.errorMessage : undefined,\n\t\t};\n\t\tif (Array.isArray(candidate.content)) {\n\t\t\tassistant.content = candidate.content as PiAssistantMessage[\"content\"];\n\t\t}\n\t\tif (typeof candidate.api === \"string\") assistant.api = candidate.api;\n\t\tif (typeof candidate.provider === \"string\") assistant.provider = candidate.provider;\n\t\tif (typeof candidate.model === \"string\") assistant.model = candidate.model;\n\t\tif (typeof candidate.timestamp === \"number\") assistant.timestamp = candidate.timestamp;\n\t\tconst usage = normalizeUsage(candidate.usage);\n\t\tif (usage) assistant.usage = usage;\n\t\treturn assistant;\n\t}\n\treturn undefined;\n}\n\nexport function formatError(error: unknown) {\n\treturn truncateNotification(error instanceof Error ? error.message : String(error));\n}\n\nexport function truncateNotification(value: string) {\n\treturn value.length > 160 ? `${value.slice(0, 157)}...` : value;\n}\n\nasync function sendPrompt(pi: ExtensionAPI, ctx: StatusContext, prompt: string) {\n\ttry {\n\t\tawait pi.sendUserMessage(prompt, { deliverAs: \"followUp\" });\n\t\treturn true;\n\t} catch (error) {\n\t\tctx.ui.notify(`Goal prompt failed: ${formatError(error)}`, \"error\");\n\t\treturn false;\n\t}\n}\n\nfunction goalCommandHint(status: GoalStatus, experimentalGoals = false) {\n\tconst queueCommands = experimentalGoals\n\t\t? \", /goal add <objective>, /goal prioritize <objective>, /goal drop-last, /goal skip\"\n\t\t: \"\";\n\tif (status === \"active\") {\n\t\treturn `/goal edit <objective>, /goal pause, /goal clear${queueCommands}`;\n\t}\n\tif (isResumableGoalStatus(status)) {\n\t\treturn `/goal edit <objective>, /goal resume, /goal clear${queueCommands}`;\n\t}\n\treturn `/goal edit <objective>, /goal clear${queueCommands}`;\n}\n\nfunction toPiAssistantMessage(assistant: AssistantMessageLike): PiAssistantMessage {\n\treturn {\n\t\trole: \"assistant\",\n\t\tcontent: assistant.content ?? [],\n\t\tapi: assistant.api ?? \"openai-responses\",\n\t\tprovider: assistant.provider ?? \"unknown\",\n\t\tmodel: assistant.model ?? \"unknown\",\n\t\tusage: assistant.usage ?? zeroUsage(),\n\t\tstopReason: assistant.stopReason ?? \"error\",\n\t\terrorMessage: assistant.errorMessage,\n\t\ttimestamp: assistant.timestamp ?? Date.now(),\n\t};\n}\n\nfunction zeroUsage(): Usage {\n\treturn {\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: 0,\n\t\tcost: {\n\t\t\tinput: 0,\n\t\t\toutput: 0,\n\t\t\tcacheRead: 0,\n\t\t\tcacheWrite: 0,\n\t\t\ttotal: 0,\n\t\t},\n\t};\n}\n\nfunction continuationMarker(goal: ActiveGoal) {\n\treturn `${goal.id}:${goal.iteration}:${randomUUID()}`;\n}\n\nfunction escapeRegExpText(value: string) {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nconst GOAL_PROMPT_MARKER_PATTERN = new RegExp(\n\t`<!--\\\\s*${escapeRegExpText(GOAL_PROMPT_MARKER_PREFIX)}([^\\\\s>]+)\\\\s*-->`,\n);\nconst CONTINUATION_MARKER_PATTERN = new RegExp(\n\t`<!--\\\\s*${escapeRegExpText(CONTINUATION_MARKER_PREFIX)}([^\\\\s>]+)\\\\s*-->`,\n);\n\nfunction extractGoalPromptMarker(prompt: string) {\n\treturn GOAL_PROMPT_MARKER_PATTERN.exec(prompt)?.[1];\n}\n\nfunction extractContinuationMarker(prompt: string) {\n\treturn CONTINUATION_MARKER_PATTERN.exec(prompt)?.[1];\n}\n\nfunction isAgentStopReason(value: unknown): value is AgentStopReason {\n\treturn [\"stop\", \"length\", \"toolUse\", \"error\", \"aborted\"].includes(String(value));\n}\n\nfunction normalizeUsage(value: unknown): Usage | undefined {\n\tif (!value || typeof value !== \"object\") return undefined;\n\tconst usage = value as Partial<Usage>;\n\tif (typeof usage.input !== \"number\" || typeof usage.output !== \"number\") return undefined;\n\treturn {\n\t\tinput: nonNegativeFiniteNumber(usage.input),\n\t\toutput: nonNegativeFiniteNumber(usage.output),\n\t\tcacheRead: nonNegativeFiniteNumber(usage.cacheRead),\n\t\tcacheWrite: nonNegativeFiniteNumber(usage.cacheWrite),\n\t\ttotalTokens: assistantUsageTokens(usage),\n\t\tcost: {\n\t\t\tinput: usage.cost?.input ?? 0,\n\t\t\toutput: usage.cost?.output ?? 0,\n\t\t\tcacheRead: usage.cost?.cacheRead ?? 0,\n\t\t\tcacheWrite: usage.cost?.cacheWrite ?? 0,\n\t\t\ttotal: usage.cost?.total ?? 0,\n\t\t},\n\t};\n}\n"]}