@narumitw/pi-goal 0.53.0 → 0.53.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -2
- package/dist/chunks/{chunk-W7AFYZ6J.ts → chunk-4GOI2LMD.ts} +8 -8
- package/dist/chunks/{chunk-W7AFYZ6J.ts.map → chunk-4GOI2LMD.ts.map} +2 -2
- package/dist/chunks/{menu-73TCS5P6.ts → menu-MMY32N6V.ts} +2 -2
- package/dist/chunks/{settings-ui-Y5LMEFEH.ts → settings-ui-NXPYYRGD.ts} +1 -5
- package/dist/chunks/{settings-ui-Y5LMEFEH.ts.map → settings-ui-NXPYYRGD.ts.map} +2 -2
- package/dist/index.ts +57 -11
- package/dist/index.ts.map +4 -4
- package/package.json +1 -1
- package/src/goal-contract.ts +62 -0
- package/src/lifecycle.ts +11 -7
- package/src/persistence.ts +0 -6
- package/src/prompts.ts +7 -1
- package/src/settings-ui.ts +0 -4
- /package/dist/chunks/{menu-73TCS5P6.ts.map → menu-MMY32N6V.ts.map} +0 -0
package/dist/index.ts.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/command-registration.ts", "../src/commands.ts", "../src/lifecycle.ts", "../src/run-protocol.ts", "../src/tools.ts", "../src/goal.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ExtensionAPI, ExtensionCommandContext } from \"@earendil-works/pi-coding-agent\";\nimport { completeGoalArguments, isRemovedQueueCommand, parseCommand } from \"./command.js\";\nimport type { GoalCommandController } from \"./commands.js\";\nimport { notifyTerminal, safeTerminalText } from \"./errors.js\";\nimport type { GoalRuntime } from \"./runtime.js\";\n\ntype GoalManagerModule = Pick<typeof import(\"./menu.js\"), \"showGoalManager\">;\ntype GoalSettingsModule = Pick<typeof import(\"./settings-ui.js\"), \"showGoalSettings\">;\n\nexport interface GoalCommandRegistrationOptions {\n\tsettingsPath?: string;\n\tloadGoalManager?: () => Promise<GoalManagerModule>;\n\tloadGoalSettings?: () => Promise<GoalSettingsModule>;\n}\n\nexport function registerGoalCommand(\n\tpi: ExtensionAPI,\n\truntime: GoalRuntime,\n\tcommands: GoalCommandController,\n\toptions: GoalCommandRegistrationOptions = {},\n) {\n\tconst loadGoalManager = cachedModuleLoader(\n\t\toptions.loadGoalManager ?? (() => import(\"./menu.js\")),\n\t);\n\tconst loadGoalSettings = cachedModuleLoader(\n\t\toptions.loadGoalSettings ?? (() => import(\"./settings-ui.js\")),\n\t);\n\n\tpi.registerCommand(\"goal\", {\n\t\tdescription: \"Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>\",\n\t\tgetArgumentCompletions: (prefix) => completeGoalArguments(prefix),\n\t\thandler: async (args, ctx) => {\n\t\t\tif (runtime.hasLegacyQueueInterface() && isRemovedQueueCommand(args)) {\n\t\t\t\treportRemovedQueueCommand(ctx, runtime);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst result = parseCommand(args);\n\t\t\tif (typeof result === \"string\") {\n\t\t\t\treportCommandError(result, ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (result.kind === \"show\" && args.trim() === \"\") {\n\t\t\t\tconst menuIsCurrent = captureMenuOwnership(runtime);\n\t\t\t\tlet managerModule: GoalManagerModule;\n\t\t\t\ttry {\n\t\t\t\t\tmanagerModule = await loadGoalManager();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!menuIsCurrent()) return;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tif (!menuIsCurrent()) return;\n\t\t\t\tconst { showGoalManager } = managerModule;\n\t\t\t\tawait showGoalManager(runtime, commands, ctx, async (menuCtx, target) => {\n\t\t\t\t\tconst settingsAreCurrent = captureMenuOwnership(runtime);\n\t\t\t\t\tlet settingsModule: GoalSettingsModule;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsettingsModule = await loadGoalSettings();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!settingsAreCurrent()) return;\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t\tif (!settingsAreCurrent()) return;\n\t\t\t\t\tconst { showGoalSettings } = settingsModule;\n\t\t\t\t\tawait showGoalSettings(runtime, menuCtx, {\n\t\t\t\t\t\tsettingsPath: options.settingsPath,\n\t\t\t\t\t\tinitialScreen: target,\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\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 \"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\nfunction reportCommandError(message: string, ctx: ExtensionCommandContext) {\n\tconst safeMessage = safeTerminalText(message);\n\tif (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(safeMessage);\n\tnotifyTerminal(ctx.ui, safeMessage, \"warning\");\n}\n\nfunction reportRemovedQueueCommand(ctx: ExtensionCommandContext, runtime: GoalRuntime) {\n\tconst message = runtime.activeGoal\n\t\t? \"Ordered goal queue has been removed. Use /goal edit to reprioritize the active objective instead.\"\n\t\t: \"Ordered goal queue has been removed. Start /goal <objectives> to continue with one merged objective, or use /goal clear to discard the old queue state.\";\n\tif (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(message);\n\tnotifyTerminal(ctx.ui, message, \"warning\");\n}\n\nfunction captureMenuOwnership(runtime: GoalRuntime): () => boolean {\n\tconst generation = runtime.menuGeneration;\n\tconst controller = runtime.menuController;\n\treturn () =>\n\t\truntime.menuGeneration === generation &&\n\t\truntime.menuController === controller &&\n\t\t!controller.signal.aborted;\n}\n\nfunction cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {\n\tlet pending: Promise<Module> | undefined;\n\treturn () => {\n\t\tif (!pending) {\n\t\t\tpending = load().catch((error) => {\n\t\t\t\tpending = undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t}\n\t\treturn pending;\n\t};\n}\n", "import { currentTokenTotal, formatTokenCount } from \"./accounting.js\";\nimport { validateObjective } from \"./command.js\";\nimport { notifyTerminal, safeGoalMenuText } from \"./errors.js\";\nimport type { ActiveGoal } from \"./persistence.js\";\nimport {\n\tbuildGoalPrompt,\n\tbuildObjectiveUpdatedPrompt,\n\tbuildResumePrompt,\n\tbuildWaitingResumePrompt,\n} from \"./prompts.js\";\nimport {\n\tblocksStaleGoalToolCalls,\n\tcreateGoal,\n\teditedGoalStatus,\n\tformatBudget,\n\tformatError,\n\ttype GoalRuntime,\n\tgoalSummary,\n\tisResumableGoalStatus,\n\tnextGoalInstance,\n\tqueueGoalSafetyReset,\n\tSTATUS_KEY,\n\ttype StatusContext,\n\tstoppedStatusLabel,\n\ttransitionGoal,\n} from \"./runtime.js\";\n\n// User-command mutations are kept separate from Pi event wiring. Every controller\n// receives exactly one per-factory GoalRuntime, preserving session isolation.\nexport class GoalCommandController {\n\tprivate readonly runtime: GoalRuntime;\n\n\tconstructor(runtime: GoalRuntime) {\n\t\tthis.runtime = runtime;\n\t}\n\n\tasync startGoal(\n\t\tobjective: string,\n\t\ttokenBudget: number | undefined,\n\t\tctx: StatusContext,\n\t\tonActivated?: (goal: ActiveGoal) => void,\n\t\tisActivationCurrent?: (goal: ActiveGoal) => boolean,\n\t\tisRequestCurrent?: () => boolean,\n\t) {\n\t\tif (isRequestCurrent && !isRequestCurrent()) return;\n\t\tconst validationError = validateObjective(objective);\n\t\tif (validationError) {\n\t\t\tnotifyTerminal(ctx.ui, validationError, \"warning\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst existingGoal =\n\t\t\tthis.runtime.activeGoal?.status !== \"complete\" ? this.runtime.activeGoal : undefined;\n\t\tconst legacyQueueBeforeActivation = existingGoal\n\t\t\t? undefined\n\t\t\t: this.runtime.legacyQueueState\n\t\t\t\t? structuredClone(this.runtime.legacyQueueState)\n\t\t\t\t: undefined;\n\t\tif (existingGoal) {\n\t\t\tconst shouldReplace = await ctx.ui.confirm(\n\t\t\t\t\"Replace goal?\",\n\t\t\t\t`Current goal: ${safeGoalMenuText(existingGoal.text, 4_000)}\\n\\nNew goal: ${safeGoalMenuText(objective, 4_000)}`,\n\t\t\t);\n\t\t\tif (!shouldReplace) {\n\t\t\t\tnotifyTerminal(ctx.ui, `Goal kept: ${existingGoal.text}`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isRequestCurrent && !isRequestCurrent()) return;\n\t\t\tif (this.runtime.activeGoal?.id !== existingGoal.id) {\n\t\t\t\tnotifyTerminal(\n\t\t\t\t\tctx.ui,\n\t\t\t\t\t\"The active goal changed while confirmation was open. Try again.\",\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Unlock lazy visibility only after final workflow admission. In always mode,\n\t\t// a missing tool means another policy or allowlist intentionally removed it.\n\t\tif (isRequestCurrent && !isRequestCurrent()) return;\n\t\tconst retainedOwner = this.runtime.ownsWorkflow(existingGoal);\n\t\tif (!this.runtime.acquireWorkflow(ctx.sessionManager)) return this.reportWorkflowBusy(ctx);\n\t\tconst acquiredForRequest = !retainedOwner;\n\t\tconst goalToolVisibilityBeforeActivation = this.runtime.toolPolicy.snapshot();\n\t\ttry {\n\t\t\tthis.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);\n\t\t} catch (error) {\n\t\t\tnotifyTerminal(ctx.ui, `Cannot start /goal: ${formatError(error)}`, \"error\");\n\t\t\tif (existingGoal?.status === \"active\") this.runtime.pauseGoalForUnavailableTools(ctx);\n\t\t\telse if (acquiredForRequest) this.runtime.releaseWorkflow();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.runtime.clearGoalWaitTimer();\n\t\tthis.runtime.cancelContinuationWork();\n\t\tthis.runtime.clearGoalRecovery();\n\t\tthis.runtime.clearBudgetWrapUp();\n\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\tif (!legacyQueueBeforeActivation) this.runtime.legacyQueueState = undefined;\n\t\tthis.runtime.activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));\n\t\tconst startedGoal = this.runtime.activeGoal;\n\t\tonActivated?.(startedGoal);\n\t\tif (!legacyQueueBeforeActivation) this.runtime.persistGoal(startedGoal);\n\t\tif (\n\t\t\tthis.runtime.activeGoal?.id !== startedGoal.id ||\n\t\t\t!this.runtime.ownsWorkflow(this.runtime.activeGoal)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tthis.runtime.updateStatus(ctx, startedGoal);\n\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\tctx,\n\t\t\tstartedGoal.id,\n\t\t\tbuildGoalPrompt(startedGoal),\n\t\t\ttrue,\n\t\t\t() => (isRequestCurrent?.() ?? true) && (isActivationCurrent?.(startedGoal) ?? true),\n\t\t);\n\t\tif (\n\t\t\tsent &&\n\t\t\tlegacyQueueBeforeActivation &&\n\t\t\tthis.runtime.activeGoal?.id === startedGoal.id &&\n\t\t\tthis.runtime.activeGoal.status === \"active\"\n\t\t) {\n\t\t\tthis.runtime.legacyQueueState = undefined;\n\t\t\tthis.runtime.persistGoal(startedGoal);\n\t\t}\n\t\tif (isActivationCurrent && !isActivationCurrent(startedGoal)) return;\n\t\tif (!sent) {\n\t\t\tlet rolledBackStartedGoal = false;\n\t\t\tif (this.runtime.activeGoal?.id === startedGoal.id) {\n\t\t\t\trolledBackStartedGoal = true;\n\t\t\t\tif (existingGoal) {\n\t\t\t\t\tthis.runtime.recordGoalUsage(existingGoal, ctx);\n\t\t\t\t\tif (existingGoal.status === \"active\" && existingGoal.waiting) {\n\t\t\t\t\t\tthis.runtime.activeGoal = existingGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(existingGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, existingGoal);\n\t\t\t\t\t\tthis.runtime.restoreGoalWaitTimer(ctx);\n\t\t\t\t\t} else if (existingGoal.status === \"active\") {\n\t\t\t\t\t\tthis.runtime.activeGoal = existingGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(existingGoal);\n\t\t\t\t\t\tif (this.runtime.activeGoal?.id === existingGoal.id) {\n\t\t\t\t\t\t\tthis.runtime.updateStatus(ctx, existingGoal);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.runtime.activeGoal = existingGoal;\n\t\t\t\t\t\tif (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n\t\t\t\t\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\t\t\t}\n\t\t\t\t} else if (legacyQueueBeforeActivation) {\n\t\t\t\t\tthis.runtime.activeGoal = undefined;\n\t\t\t\t\tthis.runtime.legacyQueueState = legacyQueueBeforeActivation;\n\t\t\t\t\tthis.runtime.cancelContinuationWork();\n\t\t\t\t\tthis.runtime.clearGoalRecovery();\n\t\t\t\t\tthis.runtime.clearBudgetWrapUp();\n\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\t\t} else {\n\t\t\t\t\tthis.runtime.clearActiveGoal(ctx, \"goal activation rolled back\", false);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (rolledBackStartedGoal) {\n\t\t\t\tthis.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);\n\t\t\t\tif (acquiredForRequest && !this.runtime.ownsWorkflow(existingGoal)) {\n\t\t\t\t\tthis.runtime.releaseWorkflow();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\tthis.runtime.activeGoal?.id !== startedGoal.id ||\n\t\t\t!this.runtime.ownsWorkflow(this.runtime.activeGoal)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\n\t\t\t`${existingGoal ? \"Goal replaced\" : \"Goal started\"}: ${objective}. ${\n\t\t\t\tstartedGoal.tokenBudget === undefined\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: `Token budget: ${formatTokenCount(startedGoal.tokenBudget)} cumulative; the final model call may exceed it. `\n\t\t\t}${\n\t\t\t\tautomaticLimit === null\n\t\t\t\t\t? \"Automatic work is Unlimited; tool loops may consume substantial tokens and provider cost. Open /goal to monitor.\"\n\t\t\t\t\t: `Automatic work pauses after ${automaticLimit} responses; open /goal to monitor progress.`\n\t\t\t}`,\n\t\t\tautomaticLimit === null ? \"warning\" : \"info\",\n\t\t);\n\t}\n\n\tpauseGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tnotifyTerminal(ctx.ui, \"No active goal.\", \"info\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.runtime.activeGoal.status !== \"active\") {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal is ${this.runtime.activeGoal.status}; only active goals can be paused.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst stoppedGoal = this.runtime.stopActiveGoal(ctx, {\n\t\t\tkind: \"explicit_pause\",\n\t\t\texpectedGoalId: this.runtime.activeGoal.id,\n\t\t});\n\t\tif (stoppedGoal) notifyTerminal(ctx.ui, `Goal paused: ${stoppedGoal.text}`, \"info\");\n\t}\n\n\tasync resumeGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tnotifyTerminal(ctx.ui, \"No active goal.\", \"info\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.runtime.activeGoal.status === \"active\" && this.runtime.activeGoal.waiting) {\n\t\t\tawait this.resumeWaitingGoal(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (!isResumableGoalStatus(this.runtime.activeGoal.status)) {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal is ${this.runtime.activeGoal.status}; only paused, blocked, usage-limited, or budget-limited goals can be resumed.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\tthis.runtime.activeGoal.tokenBudget !== undefined &&\n\t\t\tthis.runtime.activeGoal.tokensUsed >= this.runtime.activeGoal.tokenBudget\n\t\t) {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.acquireWorkflow(ctx.sessionManager)) {\n\t\t\tthis.reportWorkflowBusy(ctx);\n\t\t\treturn;\n\t\t}\n\t\tconst goalToolVisibilityBeforeActivation = this.runtime.toolPolicy.snapshot();\n\t\ttry {\n\t\t\tthis.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);\n\t\t} catch (error) {\n\t\t\tnotifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, \"error\");\n\t\t\tthis.runtime.releaseWorkflow();\n\t\t\treturn;\n\t\t}\n\t\tconst stoppedGoal = this.runtime.activeGoal;\n\t\tconst stoppedStatus = stoppedGoal.status;\n\t\tthis.runtime.cancelContinuationWork();\n\t\tthis.runtime.clearGoalRecovery();\n\t\tthis.runtime.clearBudgetWrapUp();\n\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\tthis.runtime.activeGoal = queueGoalSafetyReset(\n\t\t\ttransitionGoal(nextGoalInstance(this.runtime.activeGoal), \"active\"),\n\t\t);\n\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\tif (this.runtime.activeGoal.status !== \"active\") {\n\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\tthis.runtime.releaseWorkflow();\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.ownsWorkflow(this.runtime.activeGoal)) return;\n\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\tconst resumedGoal = this.runtime.activeGoal;\n\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\tctx,\n\t\t\tresumedGoal.id,\n\t\t\tbuildResumePrompt(resumedGoal, stoppedStatus),\n\t\t);\n\t\tif (!sent) {\n\t\t\tif (\n\t\t\t\tthis.runtime.activeGoal?.id === resumedGoal.id &&\n\t\t\t\tthis.runtime.activeGoal.status === \"active\"\n\t\t\t) {\n\t\t\t\tthis.runtime.activeGoal = stoppedGoal;\n\t\t\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\t\tif (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n\t\t\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t\t\t}\n\t\t\t\tthis.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);\n\t\t\t\tthis.runtime.releaseWorkflow();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.ownsWorkflow(resumedGoal)) return;\n\t\tconst automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\n\t\t\t`Goal resumed from ${stoppedStatusLabel(stoppedStatus)}: ${resumedGoal.text}. ${\n\t\t\t\tautomaticLimit === null\n\t\t\t\t\t? \"Automatic work remains Unlimited; goal progress and cumulative usage are preserved.\"\n\t\t\t\t\t: `The automatic-work counter will reset to 0 of ${automaticLimit} when the resumed prompt starts; goal progress and cumulative usage are preserved.`\n\t\t\t}`,\n\t\t\tautomaticLimit === null ? \"warning\" : \"info\",\n\t\t);\n\t}\n\n\tprivate async resumeWaitingGoal(ctx: StatusContext) {\n\t\tconst waitingGoal = this.runtime.activeGoal;\n\t\tconst waiting = waitingGoal?.waiting;\n\t\tif (waitingGoal?.status !== \"active\" || !waiting) return;\n\t\tif (!this.runtime.acquireWorkflow(ctx.sessionManager)) {\n\t\t\tthis.reportWorkflowBusy(ctx);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);\n\t\t} catch (error) {\n\t\t\tnotifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, \"error\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.clearGoalWait(ctx, waitingGoal.id)) return;\n\t\tconst resumedGoal = this.runtime.activeGoal;\n\t\tif (!resumedGoal || resumedGoal.id !== waitingGoal.id || resumedGoal.status !== \"active\")\n\t\t\treturn;\n\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\tctx,\n\t\t\tresumedGoal.id,\n\t\t\tbuildWaitingResumePrompt(resumedGoal, waiting.reason),\n\t\t\tfalse,\n\t\t);\n\t\tif (!sent) {\n\t\t\tif (this.runtime.activeGoal?.id === waitingGoal.id) {\n\t\t\t\tthis.runtime.enterGoalWait(ctx, waitingGoal.id, waiting);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.ownsWorkflow(resumedGoal)) return;\n\t\tnotifyTerminal(ctx.ui, `Goal resumed from waiting: ${waitingGoal.text}`, \"info\");\n\t}\n\n\tclearGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tconst hadLegacyQueue = this.runtime.legacyQueueState !== undefined;\n\t\t\tthis.runtime.legacyQueueState = undefined;\n\t\t\tthis.runtime.cancelContinuationWork();\n\t\t\tthis.runtime.clearGoalRecovery();\n\t\t\tthis.runtime.clearBudgetWrapUp();\n\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\tthis.runtime.clearPersistedGoal(ctx.cwd);\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\thadLegacyQueue ? \"Removed legacy ordered goal queue state.\" : \"No active goal.\",\n\t\t\t\thadLegacyQueue ? \"warning\" : \"info\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst stoppedGoal = this.runtime.activeGoal.text;\n\t\tthis.runtime.clearActiveGoal(ctx);\n\t\tnotifyTerminal(ctx.ui, `Goal cleared: ${stoppedGoal}`, \"warning\");\n\t}\n\n\tasync editGoal(objective: string, tokenBudget: number | undefined, ctx: StatusContext) {\n\t\tconst validationError = validateObjective(objective);\n\t\tif (validationError) {\n\t\t\tnotifyTerminal(ctx.ui, validationError, \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tnotifyTerminal(ctx.ui, \"No active goal. Use /goal <objective> to start one.\", \"warning\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst currentGoal = this.runtime.activeGoal;\n\t\tconst effectiveTokenBudget = tokenBudget ?? currentGoal.tokenBudget;\n\t\tif (\n\t\t\tcurrentGoal.status === \"budget_limited\" &&\n\t\t\teffectiveTokenBudget !== undefined &&\n\t\t\teffectiveTokenBudget <= currentGoal.tokensUsed\n\t\t) {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal token budget is still reached: ${formatBudget(currentGoal)}. Raise the budget above current usage before editing.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst previousStatus = currentGoal.status;\n\t\tconst intendsActive = editedGoalStatus(previousStatus) === \"active\";\n\t\tconst retainedOwner = this.runtime.ownsWorkflow(currentGoal);\n\t\tif (intendsActive && !this.runtime.acquireWorkflow(ctx.sessionManager)) {\n\t\t\tthis.reportWorkflowBusy(ctx);\n\t\t\treturn;\n\t\t}\n\t\tconst acquiredForEdit = intendsActive && !retainedOwner;\n\t\tconst goalToolVisibilityBeforeActivation = intendsActive\n\t\t\t? this.runtime.toolPolicy.snapshot()\n\t\t\t: undefined;\n\t\tif (intendsActive) {\n\t\t\ttry {\n\t\t\t\tthis.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);\n\t\t\t} catch (error) {\n\t\t\t\tnotifyTerminal(ctx.ui, `Cannot reactivate /goal: ${formatError(error)}`, \"error\");\n\t\t\t\tif (currentGoal.status === \"active\") this.runtime.pauseGoalForUnavailableTools(ctx);\n\t\t\t\telse if (acquiredForEdit) this.runtime.releaseWorkflow();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tthis.runtime.recordGoalUsage(currentGoal, ctx);\n\t\tconst previousGoal = { ...currentGoal };\n\t\tthis.runtime.clearGoalWaitTimer();\n\t\tthis.runtime.cancelContinuationWork();\n\t\tthis.runtime.clearGoalRecovery();\n\t\tthis.runtime.clearBudgetWrapUp();\n\t\tconst rotatedGoal = nextGoalInstance(currentGoal);\n\t\tconst transitionedGoal = transitionGoal(\n\t\t\t{\n\t\t\t\t...rotatedGoal,\n\t\t\t\ttext: objective,\n\t\t\t\ttokenBudget: effectiveTokenBudget,\n\t\t\t\twaiting: undefined,\n\t\t\t},\n\t\t\teditedGoalStatus(previousStatus),\n\t\t);\n\t\tconst nextGoal =\n\t\t\ttransitionedGoal.status === \"active\"\n\t\t\t\t? queueGoalSafetyReset(transitionedGoal)\n\t\t\t\t: transitionedGoal;\n\t\tthis.runtime.activeGoal = nextGoal;\n\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\tconst editedGoal = this.runtime.activeGoal;\n\t\tif (!editedGoal) return;\n\t\tif (editedGoal.status === \"active\") {\n\t\t\tif (!this.runtime.ownsWorkflow(editedGoal)) return;\n\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\t\tctx,\n\t\t\t\teditedGoal.id,\n\t\t\t\tbuildObjectiveUpdatedPrompt(editedGoal),\n\t\t\t);\n\t\t\tif (!sent) {\n\t\t\t\tif (this.runtime.activeGoal?.id === editedGoal.id) {\n\t\t\t\t\tif (previousStatus === \"active\" && previousGoal.waiting) {\n\t\t\t\t\t\tthis.runtime.activeGoal = previousGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(previousGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, previousGoal);\n\t\t\t\t\t\tthis.runtime.restoreGoalWaitTimer(ctx);\n\t\t\t\t\t} else if (previousStatus === \"active\") {\n\t\t\t\t\t\tthis.runtime.activeGoal = previousGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(previousGoal);\n\t\t\t\t\t\tif (this.runtime.activeGoal?.id === previousGoal.id) {\n\t\t\t\t\t\t\tthis.runtime.updateStatus(ctx, previousGoal);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.runtime.activeGoal = previousGoal;\n\t\t\t\t\t\tif (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n\t\t\t\t\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\t\t\t}\n\t\t\t\t\tif (goalToolVisibilityBeforeActivation) {\n\t\t\t\t\t\tthis.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);\n\t\t\t\t\t}\n\t\t\t\t\tif (acquiredForEdit && previousStatus !== \"active\") {\n\t\t\t\t\t\tthis.runtime.releaseWorkflow();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!this.runtime.ownsWorkflow(editedGoal)) return;\n\t\t} else if (blocksStaleGoalToolCalls(editedGoal.status)) {\n\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t} else {\n\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t}\n\t\tif (editedGoal.status !== \"active\" && (retainedOwner || acquiredForEdit)) {\n\t\t\tthis.runtime.releaseWorkflow();\n\t\t}\n\t\tnotifyTerminal(ctx.ui, `Goal updated: ${objective}`, \"info\");\n\t}\n\n\tprivate reportWorkflowBusy(ctx: StatusContext) {\n\t\tconst message = \"Another workflow is active in this session. End it before starting Goal.\";\n\t\tif (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(message);\n\t\tnotifyTerminal(ctx.ui, message, \"warning\");\n\t\treturn { kind: \"busy\" as const };\n\t}\n\n\tshowGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\tthis.reportGoalStatus(ctx, this.emptyGoalMessage());\n\t\t\treturn;\n\t\t}\n\t\tthis.runtime.recordGoalUsage(this.runtime.activeGoal, ctx);\n\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\tthis.reportGoalStatus(\n\t\t\tctx,\n\t\t\tgoalSummary(this.runtime.activeGoal, this.runtime.settings.continuationLimits.automaticTurns),\n\t\t);\n\t}\n\n\tprivate emptyGoalMessage() {\n\t\tconst legacy = this.runtime.legacyQueueState;\n\t\tif (!legacy) return \"Usage: /goal <objective>\\nNo goal is currently set.\";\n\t\treturn [\n\t\t\t\"Ordered goal queue has been removed.\",\n\t\t\t`Legacy queue state with ${legacy.retainedGoals} retained ${legacy.retainedGoals === 1 ? \"goal\" : \"goals\"} will not run automatically.`,\n\t\t\t\"Use /goal edit to reprioritize an active objective, start /goal <objectives>, or use /goal clear to discard the old queue state.\",\n\t\t\t'Example objective: \"task b is complete; do task a next, then task c and task d.\"',\n\t\t].join(\"\\n\");\n\t}\n\n\tprivate reportGoalStatus(ctx: StatusContext, message: string) {\n\t\tif (ctx.mode === \"print\" || ctx.mode === \"json\") {\n\t\t\tthrow new Error(\n\t\t\t\t`/goal status is unavailable in ${ctx.mode} mode because Pi does not expose an extension-command output channel. Use TUI or RPC mode.`,\n\t\t\t);\n\t\t}\n\t\tnotifyTerminal(ctx.ui, message, \"info\");\n\t}\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { currentTokenTotal } from \"./accounting.js\";\nimport { notifyTerminal } from \"./errors.js\";\nimport { type ActiveGoal, loadGoalStateFromSession } from \"./persistence.js\";\nimport { buildGoalSystemPrompt } from \"./prompts.js\";\nimport type { GoalRunController } from \"./run-protocol.js\";\nimport {\n\ttype AssistantMessageLike,\n\tabortCurrentTurn,\n\tblocksStaleGoalToolCalls,\n\tfindFinalAssistantMessage,\n\tformatError,\n\ttype GoalRuntime,\n\tincrementGoal,\n\tisGoalContextOverflow,\n\tisRetryableGoalInterruption,\n\tisUsageLimitedGoalInterruption,\n\tresetGoalSafetyEpoch,\n\tSTATUS_KEY,\n\ttype StatusContext,\n\ttransitionGoal,\n\ttruncateNotification,\n} from \"./runtime.js\";\nimport { hasAssistantToolCall } from \"./safety.js\";\nimport { DEFAULT_GOAL_SETTINGS, readGoalSettings } from \"./settings.js\";\n\nconst REMOVED_QUEUE_SETTING_WARNING =\n\t\"Ordered goal queue has been removed. Use /goal edit to reprioritize an active objective, or start /goal <objectives> if no active goal exists.\";\nconst REMOVED_PERSISTED_QUEUE_WARNING =\n\t\"Ordered goal queue has been removed. Start /goal <objectives> to continue with one merged objective, or use /goal clear to discard the old queue state.\";\n\ninterface GoalLifecycleOptions {\n\tsettingsPath?: string;\n}\n\nexport function registerGoalLifecycle(\n\tpi: ExtensionAPI,\n\truntime: GoalRuntime,\n\trunController: GoalRunController,\n\toptions: GoalLifecycleOptions = {},\n) {\n\tpi.on(\"session_start\", async (_event, ctx) => {\n\t\truntime.bindWorkflowSession(ctx.sessionManager);\n\t\truntime.replaceMenuSession();\n\t\truntime.clearCompletionStatusTimer();\n\t\truntime.clearContinuationTracking();\n\t\truntime.clearGoalWaitTimer();\n\t\truntime.clearPendingGoalPrompts();\n\t\truntime.clearAgentRun();\n\t\truntime.guardAbortGoalId = undefined;\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearBudgetWrapUp();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\truntime.legacyQueueState = undefined;\n\t\truntime.legacyExperimentalGoalsSetting = false;\n\t\truntime.clearTerminalDetails();\n\t\tconst previousToolVisibility = runtime.settings.toolVisibility;\n\t\tconst settingsResult = readGoalSettings(options.settingsPath);\n\t\tconst loaded = loadGoalStateFromSession(ctx);\n\t\truntime.settings =\n\t\t\tsettingsResult.kind === \"loaded\" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;\n\t\truntime.settingsLoadIssue = settingsResult.kind === \"invalid\" ? settingsResult : undefined;\n\t\truntime.activeGoal = undefined;\n\t\truntime.legacyQueueState = loaded.legacyQueueState;\n\t\truntime.legacyExperimentalGoalsSetting =\n\t\t\tsettingsResult.kind !== \"invalid\" && settingsResult.legacyExperimentalGoals;\n\t\trunController.bindSession(ctx);\n\n\t\tif (settingsResult.kind === \"invalid\") {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\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.legacyExperimentalGoalsSetting && !runtime.legacyQueueState) {\n\t\t\tnotifyTerminal(ctx.ui, REMOVED_QUEUE_SETTING_WARNING, \"warning\");\n\t\t}\n\n\t\tif (loaded.goal?.status === \"active\") {\n\t\t\tif (!runtime.acquireWorkflow()) {\n\t\t\t\truntime.activeGoal = transitionGoal(loaded.goal, \"paused\");\n\t\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\t\tnotifyTerminal(\n\t\t\t\t\tctx.ui,\n\t\t\t\t\t\"Goal was paused during restore because another workflow is active in this session. Resume it after the other workflow ends.\",\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.activeGoal = loaded.goal;\n\t\t\ttry {\n\t\t\t\truntime.toolPolicy.prepareSessionStart(\n\t\t\t\t\truntime.settings.toolVisibility,\n\t\t\t\t\tpreviousToolVisibility,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tnotifyTerminal(\n\t\t\t\t\tctx.ui,\n\t\t\t\t\t`Could not restore always-visible goal tools: ${formatError(error)}`,\n\t\t\t\t\t\"error\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (runtime.activeGoal.safetyResetPending) {\n\t\t\t\t// Resume/edit activation is persisted before its owned prompt starts. A\n\t\t\t\t// reload must commit that promised reset before enforcing the old limits.\n\t\t\t\truntime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n\t\t\t}\n\t\t\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\t\t\tif (runtime.enforceAutomaticTurnLimit(ctx, false) || runtime.enforceNoProgressLimit(ctx)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// On lazy restore, an earlier restrictive session-start policy still wins:\n\t\t\t// reconciliation unlocks ownership without widening the active tool set.\n\t\t\truntime.toolPolicy.reconcileRestoredState(runtime.settings.toolVisibility, true);\n\t\t\tif (!runtime.toolPolicy.toolsAvailable()) {\n\t\t\t\truntime.pauseGoalForUnavailableTools(ctx, false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\tif (!runtime.ownsWorkflow(runtime.activeGoal)) return;\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\truntime.restoreGoalWaitTimer(ctx);\n\t\t\treturn;\n\t\t}\n\n\t\truntime.activeGoal = loaded.goal;\n\t\tlet appliedInactivePolicy = false;\n\t\tlet inactivePolicyFailed = false;\n\t\ttry {\n\t\t\tappliedInactivePolicy = runtime.withTemporaryWorkflowAccess(() => {\n\t\t\t\truntime.toolPolicy.prepareSessionStart(\n\t\t\t\t\truntime.settings.toolVisibility,\n\t\t\t\t\tpreviousToolVisibility,\n\t\t\t\t);\n\t\t\t\truntime.toolPolicy.reconcileRestoredState(\n\t\t\t\t\truntime.settings.toolVisibility,\n\t\t\t\t\truntime.activeGoal !== undefined && runtime.legacyQueueState === undefined,\n\t\t\t\t);\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tinactivePolicyFailed = true;\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Could not restore always-visible goal tools: ${formatError(error)}`,\n\t\t\t\t\"error\",\n\t\t\t);\n\t\t}\n\t\tif (!appliedInactivePolicy && !inactivePolicyFailed) {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t\"Goal tool visibility was deferred because another workflow is active in this session.\",\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t}\n\t\tif (runtime.legacyQueueState) {\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\tnotifyTerminal(ctx.ui, REMOVED_PERSISTED_QUEUE_WARNING, \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal) {\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t} else {\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t}\n\t});\n\n\tpi.on(\"session_shutdown\", (_event, ctx) => {\n\t\tconst shutdownSession = ctx.sessionManager;\n\t\trunController.unbindSession();\n\t\truntime.closeMenuSession();\n\t\truntime.clearGoalWaitTimer();\n\t\tif (runtime.activeGoal) {\n\t\t\tif (runtime.activeGoal.status === \"active\") {\n\t\t\t\truntime.recordGoalUsage(runtime.activeGoal, ctx, false);\n\t\t\t}\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t}\n\t\truntime.clearContinuationTracking();\n\t\truntime.clearPendingGoalPrompts();\n\t\truntime.clearAgentRun();\n\t\truntime.guardAbortGoalId = undefined;\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearBudgetWrapUp();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\truntime.activeGoal = undefined;\n\t\truntime.legacyQueueState = undefined;\n\t\truntime.legacyExperimentalGoalsSetting = false;\n\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\truntime.clearCompletionStatusTimer();\n\t\truntime.clearTerminalDetails();\n\t\truntime.releaseWorkflow();\n\t\truntime.unbindWorkflowSession(shutdownSession);\n\t});\n\n\tpi.on(\"session_before_compact\", (event, ctx) => {\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\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn;\n\t\t}\n\t\tif (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;\n\t\truntime.cancelContinuationWork();\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };\n\t});\n\n\tpi.on(\"session_compact\", async (event, ctx) => {\n\t\tif (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\truntime.clearGoalRecovery();\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}\n\t\tconst usageRecorded = runtime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\tif (usageRecorded) {\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t}\n\t\tif (!usageRecorded) return;\n\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\n\t\tconst wasPiRetry = runtime.isPiOwnedCompactionRetry(event, runtime.activeGoal.id);\n\t\tif (wasPiRetry) return;\n\t\truntime.clearGoalRecoveryForGoal(runtime.activeGoal.id);\n\t\truntime.requestContinuation(runtime.activeGoal);\n\t\t// Pi emits session_compact before it clears its manual-compaction controller,\n\t\t// so sendUserMessage still rejects inside this hook even when ctx reports idle.\n\t\t// Defer one task; threshold compaction retains the intent for agent_settled\n\t\t// when Pi is still busy.\n\t\truntime.scheduleContinuationDispatch(ctx, runtime.activeGoal.id);\n\t});\n\n\tpi.on(\"input\", (event, ctx) => {\n\t\tif (event.source === \"extension\") {\n\t\t\tif (\n\t\t\t\truntime.consumeCancelledGoalPrompt(event.text) ||\n\t\t\t\truntime.consumeCancelledContinuationPrompt(event.text) ||\n\t\t\t\truntime.consumeStaleOwnedGoalPrompt(event.text)\n\t\t\t) {\n\t\t\t\treturn { action: \"handled\" as const };\n\t\t\t}\n\t\t\t// Streaming input is queued before its model work starts. Keep owned\n\t\t\t// markers pending for message_start, and track non-goal delivery mode so a\n\t\t\t// steer cannot consume a later follow-up's cleanup protection.\n\t\t\tif (runtime.acceptOwnedInputBoundary(event.text)) return;\n\t\t\truntime.supersedeOwnedInputCollision(event.text);\n\t\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\t\tif (event.streamingBehavior === \"steer\" || event.streamingBehavior === \"followUp\") {\n\t\t\t\truntime.noteQueuedNonGoalInput(event.text, event.streamingBehavior);\n\t\t\t}\n\t\t\truntime.clearGoalRecovery();\n\t\t\treturn;\n\t\t}\n\t\tif (/^\\/goal(?:\\s|$)/u.test(event.text.trimStart())) return;\n\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\tif (event.streamingBehavior === \"followUp\") {\n\t\t\truntime.noteQueuedNonGoalInput(event.text, \"followUp\", true);\n\t\t\treturn;\n\t\t}\n\t\tif (event.streamingBehavior === \"steer\") {\n\t\t\truntime.noteQueuedNonGoalInput(event.text, \"steer\");\n\t\t}\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearBudgetWrapUp();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\truntime.resetActiveSafetyEpoch(ctx);\n\t});\n\n\tpi.on(\"message_start\", (event, ctx) => {\n\t\tconst message = event.message as { role?: unknown; content?: unknown };\n\t\tif (\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\truntime.activeGoal?.status === \"paused\" &&\n\t\t\truntime.guardAbortGoalId === runtime.activeGoal.id\n\t\t) {\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (message.role === \"custom\") {\n\t\t\tif (runtime.isActiveBudgetWrapUpMessage(message)) return;\n\t\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\t\tif (runtime.guardAbortGoalId === runtime.activeGoal?.id) {\n\t\t\t\truntime.guardAbortGoalId = undefined;\n\t\t\t}\n\t\t\tbeginNonGoalFollowUp(ctx, false);\n\t\t\treturn;\n\t\t}\n\t\tif (message.role !== \"user\") return;\n\t\tconst prompt = Array.isArray(message.content)\n\t\t\t? message.content\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(part) => part && typeof part === \"object\" && Reflect.get(part, \"type\") === \"text\",\n\t\t\t\t\t)\n\t\t\t\t\t.map((part) => Reflect.get(part as object, \"text\"))\n\t\t\t\t\t.filter((text): text is string => typeof text === \"string\")\n\t\t\t\t\t.join(\"\\n\")\n\t\t\t: typeof message.content === \"string\"\n\t\t\t\t? message.content\n\t\t\t\t: \"\";\n\t\tconst ownedPrompt = runtime.consumeOwnedGoalPrompt(prompt);\n\t\tconst ownedPromptBoundary = runtime.hasOwnedPromptBoundary(prompt);\n\t\tconst queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt, !ownedPromptBoundary);\n\t\tif (!ownedPrompt) {\n\t\t\tif (queuedNonGoalInput?.behavior === \"followUp\") {\n\t\t\t\tbeginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\truntime.activeGoal?.id !== ownedPrompt.goalId ||\n\t\t\t!runtime.ownsWorkflow(runtime.activeGoal)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.agentRunGoalId !== undefined && runtime.agentRunGoalId !== ownedPrompt.goalId) {\n\t\t\truntime.activeGoal.baselineTokens = Math.max(\n\t\t\t\t0,\n\t\t\t\tcurrentTokenTotal(ctx) - runtime.activeGoal.tokensUsed,\n\t\t\t);\n\t\t}\n\t\truntime.beginAgentRun(ownedPrompt.goalId, \"manual\");\n\t\tif (ownedPrompt.resetSafetyEpoch) {\n\t\t\truntime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n\t\t}\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t});\n\n\tpi.on(\"context\", (event, ctx) => {\n\t\tconst messages = event.messages.filter((message) => runtime.keepBudgetWrapUpMessage(message));\n\t\tif (\n\t\t\truntime.activeGoal?.status === \"paused\" &&\n\t\t\truntime.guardAbortGoalId === runtime.activeGoal.id\n\t\t) {\n\t\t\t// A current custom follow-up clears the guard at message_start. Otherwise,\n\t\t\t// context transformation aborts before the provider adapter receives the signal.\n\t\t\tabortCurrentTurn(ctx);\n\t\t}\n\t\tif (messages.length !== event.messages.length) return { messages };\n\t});\n\n\tpi.on(\"tool_call\", (event, ctx) => {\n\t\truntime.markAgentToolAttempted();\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\truntime.clearStaleGoalToolCallBlock();\n\t\t\treturn;\n\t\t}\n\t\t// A blocked tool result would normally trigger another model call. Abort the\n\t\t// current turn so a tool-seeking model cannot create an unbounded loop that\n\t\t// burns provider quota while the goal is stopped.\n\t\tabortCurrentTurn(ctx);\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 (\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\truntime.queueBudgetWrapUp(ctx, runtime.activeGoal);\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn;\n\t\t}\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 (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\tif (runtime.limitActiveGoalForBudget(ctx, true)) return;\n\t\tif (!runtime.toolPolicy.toolsAvailable()) runtime.pauseGoalForUnavailableTools(ctx);\n\t});\n\n\tpi.on(\"before_agent_start\", (event, ctx) => {\n\t\truntime.clearAgentRun();\n\t\t// Pi-owned retries emit agent_start directly. Reaching a normal prompt\n\t\t// boundary means cleanup no longer owns the next run, so the hard-cap guard\n\t\t// must not abort it.\n\t\tif (runtime.guardAbortGoalId) runtime.guardAbortGoalId = undefined;\n\t\tconst goalPrompt = runtime.consumeOwnedGoalPrompt(event.prompt);\n\t\tconst goalPromptGoalId = goalPrompt?.goalId;\n\t\tconst continuationGoalId = goalPromptGoalId\n\t\t\t? undefined\n\t\t\t: runtime.markContinuationStarted(event.prompt);\n\t\tconst ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;\n\t\tconst ownedPromptBoundary = runtime.hasOwnedPromptBoundary(event.prompt);\n\t\tconst activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n\t\tconst activeGoalRecovery = runtime.hasActiveGoalRecovery();\n\t\tconst queuedNonGoalInput = activeBudgetWrapUp\n\t\t\t? undefined\n\t\t\t: runtime.consumeQueuedNonGoalInput(\n\t\t\t\t\tevent.prompt,\n\t\t\t\t\t!activeGoalRecovery && ownedPromptGoalId === undefined && !ownedPromptBoundary,\n\t\t\t\t);\n\t\tif (queuedNonGoalInput?.behavior === \"followUp\") {\n\t\t\tbeginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);\n\t\t}\n\t\tif (!ownedPromptGoalId && !ownedPromptBoundary) {\n\t\t\truntime.supersedeOwnedInputCollision(event.prompt);\n\t\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\t}\n\t\tif (runtime.activeGoal?.status === \"active\" && !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\truntime.cancelContinuationWork();\n\t\t\truntime.clearGoalRecovery();\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tconst runOrigin = continuationGoalId\n\t\t\t? \"automatic\"\n\t\t\t: activeGoalRecovery && runtime.goalRecovery?.automaticOwner\n\t\t\t\t? \"automatic\"\n\t\t\t\t: \"manual\";\n\t\tif (activeBudgetWrapUp && runtime.activeGoal) {\n\t\t\truntime.beginAgentRun(runtime.activeGoal.id, \"manual\");\n\t\t\treturn;\n\t\t}\n\t\tif (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {\n\t\t\truntime.beginAgentRun(ownedPromptGoalId, runOrigin);\n\t\t\tif (runtime.activeGoal?.status === \"active\" && !runtime.toolPolicy.toolsAvailable()) {\n\t\t\t\truntime.pauseGoalForUnavailableTools(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\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn;\n\t\t}\n\t\truntime.beginAgentRun(runtime.activeGoal.id, runOrigin);\n\t\tif (!runtime.toolPolicy.toolsAvailable()) {\n\t\t\truntime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);\n\t\t\treturn;\n\t\t}\n\t\tif (goalPrompt?.resetSafetyEpoch && goalPromptGoalId === runtime.activeGoal.id) {\n\t\t\truntime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\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_start\", (_event, _ctx) => {\n\t\tconst activeGoal = runtime.activeGoal;\n\t\tif (\n\t\t\tactiveGoal &&\n\t\t\truntime.guardAbortGoalId === activeGoal.id &&\n\t\t\tactiveGoal.status === \"paused\"\n\t\t) {\n\t\t\tif (runtime.consumeQueuedNonGoalFollowUpForAgentStart()) {\n\t\t\t\truntime.guardAbortGoalId = undefined;\n\t\t\t\truntime.clearStaleGoalToolCallBlock();\n\t\t\t\truntime.beginAgentRun(null, undefined);\n\t\t\t}\n\t\t\t// Unknown runs defer cleanup until their message/context boundary: custom\n\t\t\t// follow-ups have no input event, while bare recovery is aborted pre-provider.\n\t\t\treturn;\n\t\t}\n\t\truntime.beginRecoveryRunIfNeeded();\n\t});\n\n\tpi.on(\"turn_end\", (event, ctx) => {\n\t\truntime.recordAutomaticTurn(ctx, event.message);\n\t});\n\n\tpi.on(\"agent_end\", (event, ctx) => {\n\t\tconst run = runtime.finishAgentRun();\n\t\tif (run.goalId === null) return;\n\t\tif (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp()) return;\n\t\tif (run.goalId && run.goalId !== 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\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\truntime.clearBudgetWrapUp();\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst goalId = runtime.activeGoal.id;\n\t\tconst alreadyAwaitingContinuation = runtime.hasContinuationWorkForGoal(goalId);\n\t\tconst finalAssistant = findFinalAssistantMessage(event.messages);\n\n\t\tif (!alreadyAwaitingContinuation) runtime.activeGoal = incrementGoal(runtime.activeGoal);\n\t\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\n\t\tif (finalAssistant?.stopReason === \"aborted\") {\n\t\t\truntime.clearGoalRecoveryForGoal(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 (run.origin === \"automatic\" && runtime.enforceAutomaticTurnLimit(ctx, true)) return;\n\t\t\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\t\t\t\tif (!runtime.toolPolicy.toolsAvailable()) {\n\t\t\t\t\truntime.pauseGoalForUnavailableTools(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\tautomaticOwner: run.origin === \"automatic\",\n\t\t\t\t\terrorMessage: finalAssistant.errorMessage,\n\t\t\t\t};\n\t\t\t\truntime.cancelContinuationWork();\n\t\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.clearGoalRecoveryForGoal(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\truntime.clearGoalRecoveryForGoal(goalId);\n\n\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\t\tif (!runtime.toolPolicy.toolsAvailable()) {\n\t\t\truntime.pauseGoalForUnavailableTools(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\trun.origin === \"automatic\" &&\n\t\t\truntime.recordAutomaticRunProgress(\n\t\t\t\tctx,\n\t\t\t\tgoalId,\n\t\t\t\tevent.messages,\n\t\t\t\trun.toolAttempted || hasAssistantToolCall(event.messages),\n\t\t\t)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\n\t\tconst currentGoal = runtime.activeGoal;\n\t\tif (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== \"active\") return;\n\t\truntime.requestContinuation(currentGoal);\n\t});\n\n\tpi.on(\"agent_settled\", (_event, ctx) => {\n\t\tif (runtime.activeGoal?.status === \"active\" && !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\truntime.cancelContinuationWork();\n\t\t\truntime.clearGoalRecovery();\n\t\t\truntime.clearSettledSafetyTracking();\n\t\t\treturn;\n\t\t}\n\t\truntime.finalizeSettledRecovery(ctx);\n\t\tconst resumedWait = runtime.dispatchDueGoalWait(ctx);\n\t\tif (!resumedWait) runtime.dispatchContinuationIfSettled(ctx);\n\t\truntime.clearSettledSafetyTracking();\n\t});\n\n\tfunction beginNonGoalFollowUp(ctx: StatusContext, resetSafetyEpoch: boolean) {\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\tif (resetSafetyEpoch) runtime.clearBudgetWrapUp();\n\t\tconst activeGoalId =\n\t\t\truntime.activeGoal?.status === \"active\" ? runtime.activeGoal.id : undefined;\n\t\truntime.beginAgentRun(activeGoalId ?? null, activeGoalId ? \"manual\" : undefined);\n\t\tif (resetSafetyEpoch && activeGoalId) runtime.resetActiveSafetyEpoch(ctx);\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\tconst stoppedGoal = runtime.stopActiveGoal(ctx, {\n\t\t\tkind: \"agent_interruption\",\n\t\t\texpectedGoalId: goal.id,\n\t\t\tstatus,\n\t\t\treason: assistant.errorMessage ?? `goal ${status} after agent interruption`,\n\t\t});\n\t\tif (!stoppedGoal) return;\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\tnotifyTerminal(\n\t\t\t\tctx.ui,\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\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\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", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { validateObjective } from \"./command.js\";\nimport type { GoalCommandController } from \"./commands.js\";\nimport {\n\tformatError,\n\ttype GoalRuntime,\n\ttype GoalStateSnapshot,\n\tisTerminalGoalStatus,\n\ttype StatusContext,\n} from \"./runtime.js\";\n\nexport const GOAL_RUN_START_CHANNEL = \"pi-goal:start\";\nexport const GOAL_RUN_CANCEL_CHANNEL = \"pi-goal:cancel\";\n\nconst RUN_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;\nconst MAX_CANCEL_REASON_LENGTH = 1_000;\n\nexport type GoalRunStatus = Exclude<GoalStateSnapshot[\"status\"], \"queued\">;\nexport type GoalRunErrorCode =\n\t| \"RPC_DISABLED\"\n\t| \"INVALID_REQUEST\"\n\t| \"NO_ACTIVE_SESSION\"\n\t| \"RUN_ID_IN_USE\"\n\t| \"RUN_NOT_FOUND\"\n\t| \"GOAL_ALREADY_EXISTS\"\n\t| \"ACTIVATION_FAILED\"\n\t| \"SUPERSEDED\";\n\nexport type GoalRunEvent =\n\t| {\n\t\t\ttype: \"state\";\n\t\t\trunId: string;\n\t\t\tgoalId: string;\n\t\t\tstatus: GoalRunStatus;\n\t\t\tsummary?: string;\n\t\t\treason?: string;\n\t }\n\t| {\n\t\t\ttype: \"error\";\n\t\t\trunId: string;\n\t\t\toperation: \"start\" | \"cancel\";\n\t\t\terror: { code: GoalRunErrorCode; message: string };\n\t };\n\ninterface GoalRunStartPayload {\n\trunId: string;\n\tobjective: string;\n\ttokenBudget?: number;\n}\n\ninterface BoundSession {\n\tgeneration: number;\n\tctx: StatusContext;\n}\n\ninterface ManagedRun {\n\trunId: string;\n\tgeneration: number;\n\tgoalId?: string;\n\tlastStatus?: GoalRunStatus;\n\tclosed: boolean;\n\tcancelRequested: boolean;\n\tcancelReason?: string;\n}\n\nexport function goalRunEventChannel(runId: string) {\n\treturn `pi-goal:event:${runId}`;\n}\n\nfunction isPayloadRecord(data: unknown): data is object {\n\tif (!data || typeof data !== \"object\") return false;\n\ttry {\n\t\treturn !Array.isArray(data);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction readPayloadProperty(\n\tdata: object,\n\tkey: \"runId\" | \"objective\" | \"tokenBudget\" | \"reason\",\n): { ok: true; value: unknown } | { ok: false } {\n\ttry {\n\t\treturn { ok: true, value: Reflect.get(data, key) };\n\t} catch {\n\t\treturn { ok: false };\n\t}\n}\n\nfunction parseRunId(data: unknown): string | undefined {\n\tif (!isPayloadRecord(data)) return undefined;\n\tconst runId = readPayloadProperty(data, \"runId\");\n\treturn runId.ok && typeof runId.value === \"string\" && RUN_ID_PATTERN.test(runId.value)\n\t\t? runId.value\n\t\t: undefined;\n}\n\nfunction currentActiveGoal(runtime: GoalRuntime) {\n\treturn runtime.activeGoal;\n}\n\nfunction parseStartPayload(data: unknown): string | Omit<GoalRunStartPayload, \"runId\"> {\n\tif (!isPayloadRecord(data)) return \"start payload must be an object\";\n\tconst objectiveValue = readPayloadProperty(data, \"objective\");\n\tif (!objectiveValue.ok || typeof objectiveValue.value !== \"string\") {\n\t\treturn \"objective must be a string\";\n\t}\n\tconst objective = objectiveValue.value.trim();\n\tconst objectiveError = validateObjective(objective);\n\tif (objectiveError) return objectiveError;\n\tconst tokenBudgetValue = readPayloadProperty(data, \"tokenBudget\");\n\tif (\n\t\t!tokenBudgetValue.ok ||\n\t\t(tokenBudgetValue.value !== undefined &&\n\t\t\t(typeof tokenBudgetValue.value !== \"number\" ||\n\t\t\t\t!Number.isFinite(tokenBudgetValue.value) ||\n\t\t\t\t!Number.isSafeInteger(tokenBudgetValue.value) ||\n\t\t\t\ttokenBudgetValue.value <= 0))\n\t) {\n\t\treturn \"tokenBudget must be a positive integer\";\n\t}\n\treturn { objective, tokenBudget: tokenBudgetValue.value as number | undefined };\n}\n\nfunction parseCancelReason(data: unknown): string | undefined | { error: string } {\n\tif (!isPayloadRecord(data)) return { error: \"cancel payload must be an object\" };\n\tconst reasonValue = readPayloadProperty(data, \"reason\");\n\tif (\n\t\t!reasonValue.ok ||\n\t\t(reasonValue.value !== undefined && typeof reasonValue.value !== \"string\")\n\t) {\n\t\treturn { error: \"reason must be a string\" };\n\t}\n\tif (reasonValue.value === undefined) return undefined;\n\tconst reason = reasonValue.value.trim();\n\tif (reason.length > MAX_CANCEL_REASON_LENGTH) {\n\t\treturn { error: `reason must be at most ${MAX_CANCEL_REASON_LENGTH} characters` };\n\t}\n\treturn reason || undefined;\n}\n\nexport class GoalRunController {\n\tprivate readonly runtime: GoalRuntime;\n\tprivate readonly commands: GoalCommandController;\n\tprivate generation = 0;\n\tprivate session?: BoundSession;\n\tprivate run?: ManagedRun;\n\tprivate readonly usedRunIds = new Set<string>();\n\n\tconstructor(runtime: GoalRuntime, commands: GoalCommandController) {\n\t\tthis.runtime = runtime;\n\t\tthis.commands = commands;\n\t\tthis.runtime.setGoalStateSink((snapshot) => this.handleGoalState(snapshot));\n\t}\n\n\tregister(pi: ExtensionAPI) {\n\t\tpi.events.on(GOAL_RUN_START_CHANNEL, (data) => this.handleStart(data));\n\t\tpi.events.on(GOAL_RUN_CANCEL_CHANNEL, (data) => {\n\t\t\tthis.handleCancel(data);\n\t\t});\n\t}\n\n\tbindSession(ctx: StatusContext) {\n\t\tthis.generation += 1;\n\t\tthis.session = { generation: this.generation, ctx };\n\t\tthis.closeCurrentRun();\n\t\tthis.usedRunIds.clear();\n\t}\n\n\tunbindSession() {\n\t\tthis.generation += 1;\n\t\tthis.session = undefined;\n\t\tthis.closeCurrentRun();\n\t\tthis.usedRunIds.clear();\n\t}\n\n\tprivate async handleStart(data: unknown) {\n\t\tconst runId = parseRunId(data);\n\t\tif (!runId) return;\n\t\tconst session = this.session;\n\t\tif (!session) {\n\t\t\tthis.emitError(runId, \"start\", \"NO_ACTIVE_SESSION\", \"No active pi-goal session.\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.settings.rpc.enabled) {\n\t\t\tthis.emitError(runId, \"start\", \"RPC_DISABLED\", \"Managed run RPC is disabled.\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.usedRunIds.has(runId)) {\n\t\t\tthis.emitError(runId, \"start\", \"RUN_ID_IN_USE\", \"runId was already used in this session.\");\n\t\t\treturn;\n\t\t}\n\t\tconst parsed = parseStartPayload(data);\n\t\tif (typeof parsed === \"string\") {\n\t\t\tthis.emitError(runId, \"start\", \"INVALID_REQUEST\", parsed);\n\t\t\treturn;\n\t\t}\n\t\tif (this.session !== session || this.generation !== session.generation) {\n\t\t\tthis.emitError(\n\t\t\t\trunId,\n\t\t\t\t\"start\",\n\t\t\t\t\"SUPERSEDED\",\n\t\t\t\t\"The pi-goal session changed while validating the request.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (this.usedRunIds.has(runId)) {\n\t\t\tthis.emitError(runId, \"start\", \"RUN_ID_IN_USE\", \"runId was already used in this session.\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.runtime.activeGoal || (this.run && !this.run.closed)) {\n\t\t\tthis.emitError(runId, \"start\", \"GOAL_ALREADY_EXISTS\", \"A Goal already exists.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst run: ManagedRun = {\n\t\t\trunId,\n\t\t\tgeneration: session.generation,\n\t\t\tclosed: false,\n\t\t\tcancelRequested: false,\n\t\t};\n\t\tthis.run = run;\n\t\tthis.usedRunIds.add(runId);\n\n\t\ttry {\n\t\t\tconst activation = await this.commands.startGoal(\n\t\t\t\tparsed.objective,\n\t\t\t\tparsed.tokenBudget,\n\t\t\t\tsession.ctx,\n\t\t\t\t(goal) => {\n\t\t\t\t\tif (this.ownsRun(run, session.generation)) run.goalId = goal.id;\n\t\t\t\t},\n\t\t\t\t() => this.ownsRun(run, session.generation),\n\t\t\t);\n\t\t\tif (activation?.kind === \"busy\" && this.ownsRun(run, session.generation)) {\n\t\t\t\tthis.closeCurrentRun();\n\t\t\t\tthis.emitError(\n\t\t\t\t\trunId,\n\t\t\t\t\t\"start\",\n\t\t\t\t\t\"ACTIVATION_FAILED\",\n\t\t\t\t\t\"Another workflow is active in this session. End it before starting Goal.\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (this.ownsRun(run, session.generation)) {\n\t\t\t\tthis.closeCurrentRun();\n\t\t\t\tthis.emitError(\n\t\t\t\t\trunId,\n\t\t\t\t\t\"start\",\n\t\t\t\t\t\"ACTIVATION_FAILED\",\n\t\t\t\t\t`Goal activation failed: ${formatError(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.ownsRun(run, session.generation)) return;\n\t\tif (!run.goalId) {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(runId, \"start\", \"ACTIVATION_FAILED\", \"Goal activation did not create a Goal.\");\n\t\t\treturn;\n\t\t}\n\t\tif (currentActiveGoal(this.runtime)?.id !== run.goalId) {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(runId, \"start\", \"SUPERSEDED\", \"The managed Goal was superseded.\");\n\t\t\treturn;\n\t\t}\n\t\tif (run.cancelRequested) this.cancelActiveRun(run, session, run.cancelReason);\n\t}\n\n\tprivate handleCancel(data: unknown) {\n\t\tconst runId = parseRunId(data);\n\t\tif (!runId) return;\n\t\tconst session = this.session;\n\t\tif (!session) {\n\t\t\tthis.emitError(runId, \"cancel\", \"NO_ACTIVE_SESSION\", \"No active pi-goal session.\");\n\t\t\treturn;\n\t\t}\n\t\tconst reason = parseCancelReason(data);\n\t\tif (reason && typeof reason === \"object\") {\n\t\t\tthis.emitError(runId, \"cancel\", \"INVALID_REQUEST\", reason.error);\n\t\t\treturn;\n\t\t}\n\t\tconst run = this.run;\n\t\tif (!run || run.closed || run.runId !== runId || run.generation !== session.generation) {\n\t\t\tthis.emitError(runId, \"cancel\", \"RUN_NOT_FOUND\", \"No active managed run matches runId.\");\n\t\t\treturn;\n\t\t}\n\t\tif (!run.goalId) {\n\t\t\trun.cancelRequested = true;\n\t\t\trun.cancelReason = reason;\n\t\t\treturn;\n\t\t}\n\t\tthis.cancelActiveRun(run, session, reason);\n\t}\n\n\tprivate cancelActiveRun(run: ManagedRun, session: BoundSession, reason: string | undefined) {\n\t\tif (!this.ownsRun(run, session.generation)) return;\n\t\tconst goal = this.runtime.activeGoal;\n\t\tif (!goal || goal.id !== run.goalId) {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(run.runId, \"cancel\", \"SUPERSEDED\", \"The managed Goal was superseded.\");\n\t\t\treturn;\n\t\t}\n\t\tif (goal.status !== \"active\") {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(run.runId, \"cancel\", \"RUN_NOT_FOUND\", \"The managed run is no longer active.\");\n\t\t\treturn;\n\t\t}\n\t\tthis.runtime.setTerminalReason(goal.id, reason ?? \"goal cancelled by managed run\");\n\t\tthis.commands.pauseGoal(session.ctx);\n\t}\n\n\tprivate handleGoalState(snapshot: GoalStateSnapshot) {\n\t\tconst run = this.run;\n\t\tif (!run || run.closed || !run.goalId) return;\n\t\tif (run.goalId !== snapshot.goalId) {\n\t\t\tif (currentActiveGoal(this.runtime)?.id !== snapshot.goalId) return;\n\t\t\tthis.publishStateEvent(run, {\n\t\t\t\tgoalId: run.goalId,\n\t\t\t\tstatus: \"cleared\",\n\t\t\t\treason: \"managed Goal superseded by another Goal\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (snapshot.status === \"queued\" || run.lastStatus === snapshot.status) return;\n\t\tthis.publishStateEvent(run, snapshot);\n\t}\n\n\tprivate publishStateEvent(\n\t\trun: ManagedRun,\n\t\tsnapshot: Pick<GoalStateSnapshot, \"goalId\" | \"status\" | \"summary\" | \"reason\">,\n\t) {\n\t\tconst status = snapshot.status;\n\t\tif (status === \"queued\") return;\n\t\trun.lastStatus = status;\n\t\tconst event: GoalRunEvent = {\n\t\t\ttype: \"state\",\n\t\t\trunId: run.runId,\n\t\t\tgoalId: snapshot.goalId,\n\t\t\tstatus,\n\t\t\t...(snapshot.summary ? { summary: snapshot.summary } : {}),\n\t\t\t...(snapshot.reason ? { reason: snapshot.reason } : {}),\n\t\t};\n\t\tif (!isTerminalGoalStatus(status)) {\n\t\t\tthis.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);\n\t\t\treturn;\n\t\t}\n\n\t\trun.closed = true;\n\t\tthis.run = undefined;\n\t\tconst generation = run.generation;\n\t\t// Active stays synchronous so a listener can cancel before kickoff. Terminal\n\t\t// publication waits until the transition finishes, preventing listener work\n\t\t// from being overwritten by the old transition's remaining UI or cleanup.\n\t\tqueueMicrotask(() => {\n\t\t\tif (this.generation !== generation) return;\n\t\t\tthis.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);\n\t\t});\n\t}\n\n\tprivate emitError(\n\t\trunId: string,\n\t\toperation: \"start\" | \"cancel\",\n\t\tcode: GoalRunErrorCode,\n\t\tmessage: string,\n\t) {\n\t\tthis.runtime.pi.events.emit(goalRunEventChannel(runId), {\n\t\t\ttype: \"error\",\n\t\t\trunId,\n\t\t\toperation,\n\t\t\terror: { code, message },\n\t\t} satisfies GoalRunEvent);\n\t}\n\n\tprivate ownsRun(run: ManagedRun, generation: number) {\n\t\treturn (\n\t\t\tthis.session?.generation === generation &&\n\t\t\tthis.generation === generation &&\n\t\t\tthis.run === run &&\n\t\t\t!run.closed\n\t\t);\n\t}\n\n\tprivate closeCurrentRun() {\n\t\tif (this.run) this.run.closed = true;\n\t\tthis.run = undefined;\n\t}\n}\n", "import {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tdefineTool,\n\ttype ExtensionAPI,\n\ttruncateHead,\n} from \"@earendil-works/pi-coding-agent\";\nimport { Type } from \"typebox\";\nimport { notifyTerminal, safeTerminalText } from \"./errors.js\";\nimport {\n\tformatStatus,\n\tGOAL_BLOCKED_TOOL,\n\tGOAL_COMPLETE_TOOL,\n\tGOAL_WAIT_TOOL,\n\ttype GoalRuntime,\n\tgoalIdRejectionReason,\n\tisContradictoryCompletionSummary,\n\tMAX_GOAL_ID_LENGTH,\n\tSTATUS_KEY,\n\ttransitionGoal,\n\ttruncateNotification,\n} from \"./runtime.js\";\nimport {\n\tcreateGoalWait,\n\tMAX_GOAL_WAIT_DELAY_MS,\n\tMAX_GOAL_WAIT_REASON_LENGTH,\n\tMIN_GOAL_WAIT_DELAY_MS,\n\tresolveGoalWaitDelay,\n} from \"./wait.js\";\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 GoalWaitDetails {\n\tgoal: string;\n\tgoal_id: string;\n\treason: string;\n\trequested_resume_after_ms?: number;\n\tresume_after_ms?: number;\n\tresume_at?: number;\n}\n\nconst MAX_GOAL_TEXT_LENGTH = 4_000;\nconst MAX_COMPLETION_SUMMARY_LENGTH = 4_000;\nconst MAX_BLOCKER_REASON_LENGTH = 1_000;\nconst MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;\n\nexport function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {\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\tminLength: 1,\n\t\t\t\tmaxLength: MAX_GOAL_ID_LENGTH,\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\tminLength: 1,\n\t\t\t\tmaxLength: MAX_COMPLETION_SUMMARY_LENGTH,\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\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n\t\t\tif (completedGoal.status === \"active\" && !runtime.ownsWorkflow(completedGoal)) {\n\t\t\t\tconst rejection = \"Goal completion rejected: active Goal no longer owns its workflow.\";\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t};\n\t\t\t}\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\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\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\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\tif (completingDuringBudgetWrapUp) {\n\t\t\t\t\truntime.recordGoalUsage(completedGoal, ctx);\n\t\t\t\t\truntime.persistGoal(completedGoal);\n\t\t\t\t\truntime.updateStatus(ctx, completedGoal);\n\t\t\t\t\truntime.clearBudgetWrapUp();\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\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\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\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: summary.length > MAX_COMPLETION_SUMMARY_LENGTH\n\t\t\t\t\t? \"summary is too long\"\n\t\t\t\t\t: isContradictoryCompletionSummary(summary)\n\t\t\t\t\t\t? \"summary says the goal is not complete\"\n\t\t\t\t\t\t: undefined;\n\t\t\tif (rejectionReason) {\n\t\t\t\truntime.recordGoalUsage(completedGoal, ctx);\n\t\t\t\truntime.persistGoal(completedGoal);\n\t\t\t\truntime.updateStatus(ctx, completedGoal);\n\t\t\t\tconst rejection = `Goal completion rejected: ${rejectionReason}.`;\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\tif (completingDuringBudgetWrapUp) runtime.clearBudgetWrapUp();\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t\tterminate: completingDuringBudgetWrapUp || undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\truntime.clearGoalWaitTimer();\n\t\t\truntime.activeGoal = transitionGoal(completedGoal, \"complete\");\n\t\t\truntime.setCompletionSummary(runtime.activeGoal.id, summary);\n\t\t\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\n\t\t\tctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));\n\t\t\truntime.clearActiveGoal(ctx);\n\t\t\truntime.showCompletionStatus(ctx);\n\t\t\tnotifyTerminal(ctx.ui, `Goal complete: ${goal}`, \"info\");\n\n\t\t\treturn {\n\t\t\t\tcontent: toolContent(`Goal complete: ${summary}`),\n\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\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\tminLength: 1,\n\t\t\t\tmaxLength: MAX_GOAL_ID_LENGTH,\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\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),\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\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 (!runtime.ownsWorkflow(blockedGoal))\n\t\t\t\treturn reject(\"active Goal no longer owns its workflow\");\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\tconst stoppedGoal = runtime.stopActiveGoal(ctx, {\n\t\t\t\tkind: \"blocker_report\",\n\t\t\t\texpectedGoalId: blockedGoal.id,\n\t\t\t\treason,\n\t\t\t});\n\t\t\tif (!stoppedGoal) return reject(\"active goal changed before blocker transition\");\n\t\t\tnotifyTerminal(ctx.ui, `Goal blocked: ${truncateNotification(reason)}`, \"warning\");\n\n\t\t\treturn {\n\t\t\t\tcontent: toolContent(`Goal blocked: ${reason}`),\n\t\t\t\tdetails: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),\n\t\t\t\tterminate: true,\n\t\t\t};\n\t\t},\n\t});\n\n\tconst goalWaitTool = defineTool({\n\t\tname: GOAL_WAIT_TOOL,\n\t\tlabel: \"Goal Wait\",\n\t\tdescription: `Keep the active /goal alive but quiet while an external event is expected. Call goal_wait alone after arranging a wake message, or provide resume_after_ms as a safety deadline. Requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms. Do not use it for ordinary unfinished work.`,\n\t\tpromptSnippet:\n\t\t\t\"Wait quietly for an external event without stopping the active /goal or starting automatic continuations\",\n\t\tpromptGuidelines: [\n\t\t\t\"Use goal_wait only when progress depends on a later non-goal message, or when resume_after_ms provides a bounded safety wake-up rather than a polling interval.\",\n\t\t\t`Prefer longer waits measured in minutes to avoid busy polling; goal_wait requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms.`,\n\t\t\t\"Arrange the external monitor or wake source before calling goal_wait, and call goal_wait alone because parallel sibling tools can prevent immediate turn termination.\",\n\t\t\t\"Pass the exact current goal_id so a stale turn cannot put a replacement goal into waiting.\",\n\t\t\t\"Do not use goal_blocked for a recoverable external wait that can be resumed by a message or deadline.\",\n\t\t],\n\t\tparameters: Type.Object({\n\t\t\tgoal_id: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_GOAL_ID_LENGTH,\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_GOAL_WAIT_REASON_LENGTH,\n\t\t\t\tdescription: \"Why the goal is waiting and which external event should wake it.\",\n\t\t\t}),\n\t\t\tresume_after_ms: Type.Optional(\n\t\t\t\tType.Integer({\n\t\t\t\t\tminimum: 1,\n\t\t\t\t\tmaximum: MAX_GOAL_WAIT_DELAY_MS,\n\t\t\t\t\tdescription: `Optional safety deadline in milliseconds that requests one continuation if no wake message arrives. Values below ${MIN_GOAL_WAIT_DELAY_MS} are accepted but clamped to ${MIN_GOAL_WAIT_DELAY_MS}.`,\n\t\t\t\t}),\n\t\t\t),\n\t\t}),\n\t\tasync execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n\t\t\tconst activeGoal = runtime.activeGoal;\n\t\t\tconst goal = activeGoal?.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 resumeAfterMs =\n\t\t\t\ttypeof params.resume_after_ms === \"number\" ? params.resume_after_ms : undefined;\n\t\t\tconst reject = (rejectionReason: string) => {\n\t\t\t\tconst rejection = `goal_wait rejected: ${rejectionReason}.`;\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: waitDetails(goal, requestedGoalId, reason, resumeAfterMs),\n\t\t\t\t};\n\t\t\t};\n\n\t\t\tif (!activeGoal) 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\tconst staleGoalRejection = goalIdRejectionReason(activeGoal, requestedGoalId);\n\t\t\tif (staleGoalRejection) return reject(staleGoalRejection);\n\t\t\tif (activeGoal.status !== \"active\") {\n\t\t\t\treturn reject(`goal is ${activeGoal.status}, not active`);\n\t\t\t}\n\t\t\tif (!runtime.ownsWorkflow(activeGoal))\n\t\t\t\treturn reject(\"active Goal no longer owns its workflow\");\n\t\t\tif (activeGoal.waiting) return reject(\"goal is already waiting\");\n\t\t\tif (!reason) return reject(\"reason is empty\");\n\t\t\tif (reason.length > MAX_GOAL_WAIT_REASON_LENGTH) return reject(\"reason is too long\");\n\t\t\tif (\n\t\t\t\tresumeAfterMs !== undefined &&\n\t\t\t\t(!Number.isInteger(resumeAfterMs) ||\n\t\t\t\t\tresumeAfterMs < 1 ||\n\t\t\t\t\tresumeAfterMs > MAX_GOAL_WAIT_DELAY_MS)\n\t\t\t) {\n\t\t\t\treturn reject(`resume_after_ms must be a whole number from 1 to ${MAX_GOAL_WAIT_DELAY_MS}`);\n\t\t\t}\n\n\t\t\tconst { requestedMs, effectiveMs } = resolveGoalWaitDelay(resumeAfterMs);\n\t\t\tconst waiting = createGoalWait(reason, resumeAfterMs);\n\t\t\tconst waitingGoal = runtime.enterGoalWait(ctx, activeGoal.id, waiting);\n\t\t\tif (!waitingGoal) return reject(\"active goal changed before waiting transition\");\n\t\t\tconst clamped = requestedMs !== undefined && effectiveMs !== requestedMs;\n\t\t\tnotifyTerminal(ctx.ui, `Goal waiting: ${truncateNotification(reason)}`, \"info\");\n\t\t\treturn {\n\t\t\t\tcontent: toolContent(\n\t\t\t\t\tclamped\n\t\t\t\t\t\t? `Goal waiting: ${reason}\\nRequested resume_after_ms ${requestedMs} was clamped to ${effectiveMs}.`\n\t\t\t\t\t\t: `Goal waiting: ${reason}`,\n\t\t\t\t),\n\t\t\t\tdetails: waitDetails(\n\t\t\t\t\tgoal,\n\t\t\t\t\trequestedGoalId,\n\t\t\t\t\treason,\n\t\t\t\t\teffectiveMs,\n\t\t\t\t\twaiting.resumeAt,\n\t\t\t\t\tclamped ? requestedMs : undefined,\n\t\t\t\t),\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\tpi.registerTool(goalWaitTool);\n}\n\nfunction toolContent(text: string) {\n\treturn [\n\t\t{\n\t\t\ttype: \"text\" as const,\n\t\t\ttext: truncateHead(safeTerminalText(text), {\n\t\t\t\tmaxBytes: DEFAULT_MAX_BYTES,\n\t\t\t\tmaxLines: DEFAULT_MAX_LINES,\n\t\t\t}).content,\n\t\t},\n\t];\n}\n\nfunction completionDetails(goal: string, goalId: string, summary: string): GoalCompleteDetails {\n\treturn {\n\t\tgoal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n\t\tgoal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n\t\tsummary: summary.slice(0, MAX_COMPLETION_SUMMARY_LENGTH),\n\t};\n}\n\nfunction blockerDetails(\n\tgoal: string,\n\tgoalId: string,\n\treason: string,\n\tevidence: string,\n\trepeatedTurns: number,\n): GoalBlockedDetails {\n\treturn {\n\t\tgoal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n\t\tgoal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n\t\treason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),\n\t\tevidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),\n\t\trepeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,\n\t};\n}\n\nfunction waitDetails(\n\tgoal: string,\n\tgoalId: string,\n\treason: string,\n\tresumeAfterMs: number | undefined,\n\tresumeAt?: number,\n\trequestedResumeAfterMs?: number,\n): GoalWaitDetails {\n\treturn {\n\t\tgoal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n\t\tgoal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n\t\treason: reason.slice(0, MAX_GOAL_WAIT_REASON_LENGTH),\n\t\t...(requestedResumeAfterMs === undefined\n\t\t\t? {}\n\t\t\t: { requested_resume_after_ms: requestedResumeAfterMs }),\n\t\t...(resumeAfterMs === undefined ? {} : { resume_after_ms: resumeAfterMs }),\n\t\t...(resumeAt === undefined ? {} : { resume_at: resumeAt }),\n\t};\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { registerGoalCommand } from \"./command-registration.js\";\nimport { GoalCommandController } from \"./commands.js\";\nimport { registerGoalLifecycle } from \"./lifecycle.js\";\nimport { GoalRunController } from \"./run-protocol.js\";\nimport { GoalRuntime } from \"./runtime.js\";\nimport { registerGoalTools } from \"./tools.js\";\n\ninterface GoalOptions {\n\tsettingsPath?: string;\n}\n\nfunction registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {\n\tconst runtime = new GoalRuntime(pi);\n\tconst commands = new GoalCommandController(runtime);\n\tconst runController = new GoalRunController(runtime, commands);\n\n\t// Keep registration order explicit: managed-run bus listeners exist before tools,\n\t// command routing, and session lifecycle bind the per-factory runtime.\n\trunController.register(pi);\n\tregisterGoalTools(pi, runtime);\n\tregisterGoalCommand(pi, runtime, commands, options);\n\tregisterGoalLifecycle(pi, runtime, runController, options);\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"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,SAAS,oBACf,IACA,SACA,UACA,UAA0C,CAAC,GAC1C;AACD,QAAM,kBAAkB;AAAA,IACvB,QAAQ,oBAAoB,MAAM,OAAO,2BAAW;AAAA,EACrD;AACA,QAAM,mBAAmB;AAAA,IACxB,QAAQ,qBAAqB,MAAM,OAAO,kCAAkB;AAAA,EAC7D;AAEA,KAAG,gBAAgB,QAAQ;AAAA,IAC1B,aAAa;AAAA,IACb,wBAAwB,CAAC,WAAW,sBAAsB,MAAM;AAAA,IAChE,SAAS,OAAO,MAAM,QAAQ;AAC7B,UAAI,QAAQ,wBAAwB,KAAK,sBAAsB,IAAI,GAAG;AACrE,kCAA0B,KAAK,OAAO;AACtC;AAAA,MACD;AACA,YAAM,SAAS,aAAa,IAAI;AAChC,UAAI,OAAO,WAAW,UAAU;AAC/B,2BAAmB,QAAQ,GAAG;AAC9B;AAAA,MACD;AACA,UAAI,OAAO,SAAS,UAAU,KAAK,KAAK,MAAM,IAAI;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AgB,IAAI,kBAAkB,SAAS,QAAQ;AAI7D,gBAAc,SAAS,EAAE;AACzB,oBAAkB,IAAI,OAAO;AAC7B,sBAAoB,IAAI,SAAS,UAAU,OAAO;AAClD,wBAAsB,IAAI,SAAS,eAAe,OAAO;AAC1D;AAEe,SAAR,KAAsB,IAAkB,UAAuB,CAAC,GAAG;AACzE,sBAAoB,IAAI,OAAO;AAChC;",
|
|
6
|
-
"names": ["goal", "goal", "goal"]
|
|
3
|
+
"sources": ["../src/command-registration.ts", "../src/commands.ts", "../src/goal-contract.ts", "../src/lifecycle.ts", "../src/run-protocol.ts", "../src/tools.ts", "../src/goal.ts"],
|
|
4
|
+
"sourcesContent": ["import type { ExtensionAPI, ExtensionCommandContext } from \"@earendil-works/pi-coding-agent\";\nimport { completeGoalArguments, isRemovedQueueCommand, parseCommand } from \"./command.js\";\nimport type { GoalCommandController } from \"./commands.js\";\nimport { notifyTerminal, safeTerminalText } from \"./errors.js\";\nimport type { GoalRuntime } from \"./runtime.js\";\n\ntype GoalManagerModule = Pick<typeof import(\"./menu.js\"), \"showGoalManager\">;\ntype GoalSettingsModule = Pick<typeof import(\"./settings-ui.js\"), \"showGoalSettings\">;\n\nexport interface GoalCommandRegistrationOptions {\n\tsettingsPath?: string;\n\tloadGoalManager?: () => Promise<GoalManagerModule>;\n\tloadGoalSettings?: () => Promise<GoalSettingsModule>;\n}\n\nexport function registerGoalCommand(\n\tpi: ExtensionAPI,\n\truntime: GoalRuntime,\n\tcommands: GoalCommandController,\n\toptions: GoalCommandRegistrationOptions = {},\n) {\n\tconst loadGoalManager = cachedModuleLoader(\n\t\toptions.loadGoalManager ?? (() => import(\"./menu.js\")),\n\t);\n\tconst loadGoalSettings = cachedModuleLoader(\n\t\toptions.loadGoalSettings ?? (() => import(\"./settings-ui.js\")),\n\t);\n\n\tpi.registerCommand(\"goal\", {\n\t\tdescription: \"Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>\",\n\t\tgetArgumentCompletions: (prefix) => completeGoalArguments(prefix),\n\t\thandler: async (args, ctx) => {\n\t\t\tif (runtime.hasLegacyQueueInterface() && isRemovedQueueCommand(args)) {\n\t\t\t\treportRemovedQueueCommand(ctx, runtime);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst result = parseCommand(args);\n\t\t\tif (typeof result === \"string\") {\n\t\t\t\treportCommandError(result, ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (result.kind === \"show\" && args.trim() === \"\") {\n\t\t\t\tconst menuIsCurrent = captureMenuOwnership(runtime);\n\t\t\t\tlet managerModule: GoalManagerModule;\n\t\t\t\ttry {\n\t\t\t\t\tmanagerModule = await loadGoalManager();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (!menuIsCurrent()) return;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tif (!menuIsCurrent()) return;\n\t\t\t\tconst { showGoalManager } = managerModule;\n\t\t\t\tawait showGoalManager(runtime, commands, ctx, async (menuCtx, target) => {\n\t\t\t\t\tconst settingsAreCurrent = captureMenuOwnership(runtime);\n\t\t\t\t\tlet settingsModule: GoalSettingsModule;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tsettingsModule = await loadGoalSettings();\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tif (!settingsAreCurrent()) return;\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t\tif (!settingsAreCurrent()) return;\n\t\t\t\t\tconst { showGoalSettings } = settingsModule;\n\t\t\t\t\tawait showGoalSettings(runtime, menuCtx, {\n\t\t\t\t\t\tsettingsPath: options.settingsPath,\n\t\t\t\t\t\tinitialScreen: target,\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\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 \"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\nfunction reportCommandError(message: string, ctx: ExtensionCommandContext) {\n\tconst safeMessage = safeTerminalText(message);\n\tif (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(safeMessage);\n\tnotifyTerminal(ctx.ui, safeMessage, \"warning\");\n}\n\nfunction reportRemovedQueueCommand(ctx: ExtensionCommandContext, runtime: GoalRuntime) {\n\tconst message = runtime.activeGoal\n\t\t? \"Ordered goal queue has been removed. Use /goal edit to reprioritize the active objective instead.\"\n\t\t: \"Ordered goal queue has been removed. Start /goal <objectives> to continue with one merged objective, or use /goal clear to discard the old queue state.\";\n\tif (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(message);\n\tnotifyTerminal(ctx.ui, message, \"warning\");\n}\n\nfunction captureMenuOwnership(runtime: GoalRuntime): () => boolean {\n\tconst generation = runtime.menuGeneration;\n\tconst controller = runtime.menuController;\n\treturn () =>\n\t\truntime.menuGeneration === generation &&\n\t\truntime.menuController === controller &&\n\t\t!controller.signal.aborted;\n}\n\nfunction cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {\n\tlet pending: Promise<Module> | undefined;\n\treturn () => {\n\t\tif (!pending) {\n\t\t\tpending = load().catch((error) => {\n\t\t\t\tpending = undefined;\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t}\n\t\treturn pending;\n\t};\n}\n", "import { currentTokenTotal, formatTokenCount } from \"./accounting.js\";\nimport { validateObjective } from \"./command.js\";\nimport { notifyTerminal, safeGoalMenuText } from \"./errors.js\";\nimport type { ActiveGoal } from \"./persistence.js\";\nimport {\n\tbuildGoalPrompt,\n\tbuildObjectiveUpdatedPrompt,\n\tbuildResumePrompt,\n\tbuildWaitingResumePrompt,\n} from \"./prompts.js\";\nimport {\n\tblocksStaleGoalToolCalls,\n\tcreateGoal,\n\teditedGoalStatus,\n\tformatBudget,\n\tformatError,\n\ttype GoalRuntime,\n\tgoalSummary,\n\tisResumableGoalStatus,\n\tnextGoalInstance,\n\tqueueGoalSafetyReset,\n\tSTATUS_KEY,\n\ttype StatusContext,\n\tstoppedStatusLabel,\n\ttransitionGoal,\n} from \"./runtime.js\";\n\n// User-command mutations are kept separate from Pi event wiring. Every controller\n// receives exactly one per-factory GoalRuntime, preserving session isolation.\nexport class GoalCommandController {\n\tprivate readonly runtime: GoalRuntime;\n\n\tconstructor(runtime: GoalRuntime) {\n\t\tthis.runtime = runtime;\n\t}\n\n\tasync startGoal(\n\t\tobjective: string,\n\t\ttokenBudget: number | undefined,\n\t\tctx: StatusContext,\n\t\tonActivated?: (goal: ActiveGoal) => void,\n\t\tisActivationCurrent?: (goal: ActiveGoal) => boolean,\n\t\tisRequestCurrent?: () => boolean,\n\t) {\n\t\tif (isRequestCurrent && !isRequestCurrent()) return;\n\t\tconst validationError = validateObjective(objective);\n\t\tif (validationError) {\n\t\t\tnotifyTerminal(ctx.ui, validationError, \"warning\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst existingGoal =\n\t\t\tthis.runtime.activeGoal?.status !== \"complete\" ? this.runtime.activeGoal : undefined;\n\t\tconst legacyQueueBeforeActivation = existingGoal\n\t\t\t? undefined\n\t\t\t: this.runtime.legacyQueueState\n\t\t\t\t? structuredClone(this.runtime.legacyQueueState)\n\t\t\t\t: undefined;\n\t\tif (existingGoal) {\n\t\t\tconst shouldReplace = await ctx.ui.confirm(\n\t\t\t\t\"Replace goal?\",\n\t\t\t\t`Current goal: ${safeGoalMenuText(existingGoal.text, 4_000)}\\n\\nNew goal: ${safeGoalMenuText(objective, 4_000)}`,\n\t\t\t);\n\t\t\tif (!shouldReplace) {\n\t\t\t\tnotifyTerminal(ctx.ui, `Goal kept: ${existingGoal.text}`, \"info\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isRequestCurrent && !isRequestCurrent()) return;\n\t\t\tif (this.runtime.activeGoal?.id !== existingGoal.id) {\n\t\t\t\tnotifyTerminal(\n\t\t\t\t\tctx.ui,\n\t\t\t\t\t\"The active goal changed while confirmation was open. Try again.\",\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\t// Unlock lazy visibility only after final workflow admission. In always mode,\n\t\t// a missing tool means another policy or allowlist intentionally removed it.\n\t\tif (isRequestCurrent && !isRequestCurrent()) return;\n\t\tconst retainedOwner = this.runtime.ownsWorkflow(existingGoal);\n\t\tif (!this.runtime.acquireWorkflow(ctx.sessionManager)) return this.reportWorkflowBusy(ctx);\n\t\tconst acquiredForRequest = !retainedOwner;\n\t\tconst goalToolVisibilityBeforeActivation = this.runtime.toolPolicy.snapshot();\n\t\ttry {\n\t\t\tthis.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);\n\t\t} catch (error) {\n\t\t\tnotifyTerminal(ctx.ui, `Cannot start /goal: ${formatError(error)}`, \"error\");\n\t\t\tif (existingGoal?.status === \"active\") this.runtime.pauseGoalForUnavailableTools(ctx);\n\t\t\telse if (acquiredForRequest) this.runtime.releaseWorkflow();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.runtime.clearGoalWaitTimer();\n\t\tthis.runtime.cancelContinuationWork();\n\t\tthis.runtime.clearGoalRecovery();\n\t\tthis.runtime.clearBudgetWrapUp();\n\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\tif (!legacyQueueBeforeActivation) this.runtime.legacyQueueState = undefined;\n\t\tthis.runtime.activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));\n\t\tconst startedGoal = this.runtime.activeGoal;\n\t\tonActivated?.(startedGoal);\n\t\tif (!legacyQueueBeforeActivation) this.runtime.persistGoal(startedGoal);\n\t\tif (\n\t\t\tthis.runtime.activeGoal?.id !== startedGoal.id ||\n\t\t\t!this.runtime.ownsWorkflow(this.runtime.activeGoal)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tthis.runtime.updateStatus(ctx, startedGoal);\n\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\tctx,\n\t\t\tstartedGoal.id,\n\t\t\tbuildGoalPrompt(startedGoal),\n\t\t\ttrue,\n\t\t\t() => (isRequestCurrent?.() ?? true) && (isActivationCurrent?.(startedGoal) ?? true),\n\t\t);\n\t\tif (\n\t\t\tsent &&\n\t\t\tlegacyQueueBeforeActivation &&\n\t\t\tthis.runtime.activeGoal?.id === startedGoal.id &&\n\t\t\tthis.runtime.activeGoal.status === \"active\"\n\t\t) {\n\t\t\tthis.runtime.legacyQueueState = undefined;\n\t\t\tthis.runtime.persistGoal(startedGoal);\n\t\t}\n\t\tif (isActivationCurrent && !isActivationCurrent(startedGoal)) return;\n\t\tif (!sent) {\n\t\t\tlet rolledBackStartedGoal = false;\n\t\t\tif (this.runtime.activeGoal?.id === startedGoal.id) {\n\t\t\t\trolledBackStartedGoal = true;\n\t\t\t\tif (existingGoal) {\n\t\t\t\t\tthis.runtime.recordGoalUsage(existingGoal, ctx);\n\t\t\t\t\tif (existingGoal.status === \"active\" && existingGoal.waiting) {\n\t\t\t\t\t\tthis.runtime.activeGoal = existingGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(existingGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, existingGoal);\n\t\t\t\t\t\tthis.runtime.restoreGoalWaitTimer(ctx);\n\t\t\t\t\t} else if (existingGoal.status === \"active\") {\n\t\t\t\t\t\tthis.runtime.activeGoal = existingGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(existingGoal);\n\t\t\t\t\t\tif (this.runtime.activeGoal?.id === existingGoal.id) {\n\t\t\t\t\t\t\tthis.runtime.updateStatus(ctx, existingGoal);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.runtime.activeGoal = existingGoal;\n\t\t\t\t\t\tif (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n\t\t\t\t\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\t\t\t}\n\t\t\t\t} else if (legacyQueueBeforeActivation) {\n\t\t\t\t\tthis.runtime.activeGoal = undefined;\n\t\t\t\t\tthis.runtime.legacyQueueState = legacyQueueBeforeActivation;\n\t\t\t\t\tthis.runtime.cancelContinuationWork();\n\t\t\t\t\tthis.runtime.clearGoalRecovery();\n\t\t\t\t\tthis.runtime.clearBudgetWrapUp();\n\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\t\t} else {\n\t\t\t\t\tthis.runtime.clearActiveGoal(ctx, \"goal activation rolled back\", false);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (rolledBackStartedGoal) {\n\t\t\t\tthis.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);\n\t\t\t\tif (acquiredForRequest && !this.runtime.ownsWorkflow(existingGoal)) {\n\t\t\t\t\tthis.runtime.releaseWorkflow();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\tthis.runtime.activeGoal?.id !== startedGoal.id ||\n\t\t\t!this.runtime.ownsWorkflow(this.runtime.activeGoal)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tconst automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\n\t\t\t`${existingGoal ? \"Goal replaced\" : \"Goal started\"}: ${objective}. ${\n\t\t\t\tstartedGoal.tokenBudget === undefined\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: `Token budget: ${formatTokenCount(startedGoal.tokenBudget)} cumulative; the final model call may exceed it. `\n\t\t\t}${\n\t\t\t\tautomaticLimit === null\n\t\t\t\t\t? \"Automatic work is Unlimited; tool loops may consume substantial tokens and provider cost. Open /goal to monitor.\"\n\t\t\t\t\t: `Automatic work pauses after ${automaticLimit} responses; open /goal to monitor progress.`\n\t\t\t}`,\n\t\t\tautomaticLimit === null ? \"warning\" : \"info\",\n\t\t);\n\t}\n\n\tpauseGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tnotifyTerminal(ctx.ui, \"No active goal.\", \"info\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.runtime.activeGoal.status !== \"active\") {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal is ${this.runtime.activeGoal.status}; only active goals can be paused.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst stoppedGoal = this.runtime.stopActiveGoal(ctx, {\n\t\t\tkind: \"explicit_pause\",\n\t\t\texpectedGoalId: this.runtime.activeGoal.id,\n\t\t});\n\t\tif (stoppedGoal) notifyTerminal(ctx.ui, `Goal paused: ${stoppedGoal.text}`, \"info\");\n\t}\n\n\tasync resumeGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tnotifyTerminal(ctx.ui, \"No active goal.\", \"info\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.runtime.activeGoal.status === \"active\" && this.runtime.activeGoal.waiting) {\n\t\t\tawait this.resumeWaitingGoal(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (!isResumableGoalStatus(this.runtime.activeGoal.status)) {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal is ${this.runtime.activeGoal.status}; only paused, blocked, usage-limited, or budget-limited goals can be resumed.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\tthis.runtime.activeGoal.tokenBudget !== undefined &&\n\t\t\tthis.runtime.activeGoal.tokensUsed >= this.runtime.activeGoal.tokenBudget\n\t\t) {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.acquireWorkflow(ctx.sessionManager)) {\n\t\t\tthis.reportWorkflowBusy(ctx);\n\t\t\treturn;\n\t\t}\n\t\tconst goalToolVisibilityBeforeActivation = this.runtime.toolPolicy.snapshot();\n\t\ttry {\n\t\t\tthis.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);\n\t\t} catch (error) {\n\t\t\tnotifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, \"error\");\n\t\t\tthis.runtime.releaseWorkflow();\n\t\t\treturn;\n\t\t}\n\t\tconst stoppedGoal = this.runtime.activeGoal;\n\t\tconst stoppedStatus = stoppedGoal.status;\n\t\tthis.runtime.cancelContinuationWork();\n\t\tthis.runtime.clearGoalRecovery();\n\t\tthis.runtime.clearBudgetWrapUp();\n\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\tthis.runtime.activeGoal = queueGoalSafetyReset(\n\t\t\ttransitionGoal(nextGoalInstance(this.runtime.activeGoal), \"active\"),\n\t\t);\n\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\tif (this.runtime.activeGoal.status !== \"active\") {\n\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\tthis.runtime.releaseWorkflow();\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.ownsWorkflow(this.runtime.activeGoal)) return;\n\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\tconst resumedGoal = this.runtime.activeGoal;\n\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\tctx,\n\t\t\tresumedGoal.id,\n\t\t\tbuildResumePrompt(resumedGoal, stoppedStatus),\n\t\t);\n\t\tif (!sent) {\n\t\t\tif (\n\t\t\t\tthis.runtime.activeGoal?.id === resumedGoal.id &&\n\t\t\t\tthis.runtime.activeGoal.status === \"active\"\n\t\t\t) {\n\t\t\t\tthis.runtime.activeGoal = stoppedGoal;\n\t\t\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\t\tif (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n\t\t\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t\t\t}\n\t\t\t\tthis.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);\n\t\t\t\tthis.runtime.releaseWorkflow();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.ownsWorkflow(resumedGoal)) return;\n\t\tconst automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\n\t\t\t`Goal resumed from ${stoppedStatusLabel(stoppedStatus)}: ${resumedGoal.text}. ${\n\t\t\t\tautomaticLimit === null\n\t\t\t\t\t? \"Automatic work remains Unlimited; goal progress and cumulative usage are preserved.\"\n\t\t\t\t\t: `The automatic-work counter will reset to 0 of ${automaticLimit} when the resumed prompt starts; goal progress and cumulative usage are preserved.`\n\t\t\t}`,\n\t\t\tautomaticLimit === null ? \"warning\" : \"info\",\n\t\t);\n\t}\n\n\tprivate async resumeWaitingGoal(ctx: StatusContext) {\n\t\tconst waitingGoal = this.runtime.activeGoal;\n\t\tconst waiting = waitingGoal?.waiting;\n\t\tif (waitingGoal?.status !== \"active\" || !waiting) return;\n\t\tif (!this.runtime.acquireWorkflow(ctx.sessionManager)) {\n\t\t\tthis.reportWorkflowBusy(ctx);\n\t\t\treturn;\n\t\t}\n\t\ttry {\n\t\t\tthis.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);\n\t\t} catch (error) {\n\t\t\tnotifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, \"error\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.clearGoalWait(ctx, waitingGoal.id)) return;\n\t\tconst resumedGoal = this.runtime.activeGoal;\n\t\tif (!resumedGoal || resumedGoal.id !== waitingGoal.id || resumedGoal.status !== \"active\")\n\t\t\treturn;\n\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\tctx,\n\t\t\tresumedGoal.id,\n\t\t\tbuildWaitingResumePrompt(resumedGoal, waiting.reason),\n\t\t\tfalse,\n\t\t);\n\t\tif (!sent) {\n\t\t\tif (this.runtime.activeGoal?.id === waitingGoal.id) {\n\t\t\t\tthis.runtime.enterGoalWait(ctx, waitingGoal.id, waiting);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.ownsWorkflow(resumedGoal)) return;\n\t\tnotifyTerminal(ctx.ui, `Goal resumed from waiting: ${waitingGoal.text}`, \"info\");\n\t}\n\n\tclearGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tconst hadLegacyQueue = this.runtime.legacyQueueState !== undefined;\n\t\t\tthis.runtime.legacyQueueState = undefined;\n\t\t\tthis.runtime.cancelContinuationWork();\n\t\t\tthis.runtime.clearGoalRecovery();\n\t\t\tthis.runtime.clearBudgetWrapUp();\n\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\tthis.runtime.clearPersistedGoal(ctx.cwd);\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\thadLegacyQueue ? \"Removed legacy ordered goal queue state.\" : \"No active goal.\",\n\t\t\t\thadLegacyQueue ? \"warning\" : \"info\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tconst stoppedGoal = this.runtime.activeGoal.text;\n\t\tthis.runtime.clearActiveGoal(ctx);\n\t\tnotifyTerminal(ctx.ui, `Goal cleared: ${stoppedGoal}`, \"warning\");\n\t}\n\n\tasync editGoal(objective: string, tokenBudget: number | undefined, ctx: StatusContext) {\n\t\tconst validationError = validateObjective(objective);\n\t\tif (validationError) {\n\t\t\tnotifyTerminal(ctx.ui, validationError, \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tnotifyTerminal(ctx.ui, \"No active goal. Use /goal <objective> to start one.\", \"warning\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst currentGoal = this.runtime.activeGoal;\n\t\tconst effectiveTokenBudget = tokenBudget ?? currentGoal.tokenBudget;\n\t\tif (\n\t\t\tcurrentGoal.status === \"budget_limited\" &&\n\t\t\teffectiveTokenBudget !== undefined &&\n\t\t\teffectiveTokenBudget <= currentGoal.tokensUsed\n\t\t) {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal token budget is still reached: ${formatBudget(currentGoal)}. Raise the budget above current usage before editing.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tconst previousStatus = currentGoal.status;\n\t\tconst intendsActive = editedGoalStatus(previousStatus) === \"active\";\n\t\tconst retainedOwner = this.runtime.ownsWorkflow(currentGoal);\n\t\tif (intendsActive && !this.runtime.acquireWorkflow(ctx.sessionManager)) {\n\t\t\tthis.reportWorkflowBusy(ctx);\n\t\t\treturn;\n\t\t}\n\t\tconst acquiredForEdit = intendsActive && !retainedOwner;\n\t\tconst goalToolVisibilityBeforeActivation = intendsActive\n\t\t\t? this.runtime.toolPolicy.snapshot()\n\t\t\t: undefined;\n\t\tif (intendsActive) {\n\t\t\ttry {\n\t\t\t\tthis.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);\n\t\t\t} catch (error) {\n\t\t\t\tnotifyTerminal(ctx.ui, `Cannot reactivate /goal: ${formatError(error)}`, \"error\");\n\t\t\t\tif (currentGoal.status === \"active\") this.runtime.pauseGoalForUnavailableTools(ctx);\n\t\t\t\telse if (acquiredForEdit) this.runtime.releaseWorkflow();\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\n\t\tthis.runtime.recordGoalUsage(currentGoal, ctx);\n\t\tconst previousGoal = { ...currentGoal };\n\t\tthis.runtime.clearGoalWaitTimer();\n\t\tthis.runtime.cancelContinuationWork();\n\t\tthis.runtime.clearGoalRecovery();\n\t\tthis.runtime.clearBudgetWrapUp();\n\t\tconst rotatedGoal = nextGoalInstance(currentGoal);\n\t\tconst transitionedGoal = transitionGoal(\n\t\t\t{\n\t\t\t\t...rotatedGoal,\n\t\t\t\ttext: objective,\n\t\t\t\ttokenBudget: effectiveTokenBudget,\n\t\t\t\twaiting: undefined,\n\t\t\t},\n\t\t\teditedGoalStatus(previousStatus),\n\t\t);\n\t\tconst nextGoal =\n\t\t\ttransitionedGoal.status === \"active\"\n\t\t\t\t? queueGoalSafetyReset(transitionedGoal)\n\t\t\t\t: transitionedGoal;\n\t\tthis.runtime.activeGoal = nextGoal;\n\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\tconst editedGoal = this.runtime.activeGoal;\n\t\tif (!editedGoal) return;\n\t\tif (editedGoal.status === \"active\") {\n\t\t\tif (!this.runtime.ownsWorkflow(editedGoal)) return;\n\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\tconst sent = await this.runtime.sendOwnedGoalPrompt(\n\t\t\t\tctx,\n\t\t\t\teditedGoal.id,\n\t\t\t\tbuildObjectiveUpdatedPrompt(editedGoal),\n\t\t\t);\n\t\t\tif (!sent) {\n\t\t\t\tif (this.runtime.activeGoal?.id === editedGoal.id) {\n\t\t\t\t\tif (previousStatus === \"active\" && previousGoal.waiting) {\n\t\t\t\t\t\tthis.runtime.activeGoal = previousGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(previousGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, previousGoal);\n\t\t\t\t\t\tthis.runtime.restoreGoalWaitTimer(ctx);\n\t\t\t\t\t} else if (previousStatus === \"active\") {\n\t\t\t\t\t\tthis.runtime.activeGoal = previousGoal;\n\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\tthis.runtime.persistGoal(previousGoal);\n\t\t\t\t\t\tif (this.runtime.activeGoal?.id === previousGoal.id) {\n\t\t\t\t\t\t\tthis.runtime.updateStatus(ctx, previousGoal);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthis.runtime.activeGoal = previousGoal;\n\t\t\t\t\t\tif (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n\t\t\t\t\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t\t\t\t\t}\n\t\t\t\t\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\t\t\t\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\t\t\t\t}\n\t\t\t\t\tif (goalToolVisibilityBeforeActivation) {\n\t\t\t\t\t\tthis.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);\n\t\t\t\t\t}\n\t\t\t\t\tif (acquiredForEdit && previousStatus !== \"active\") {\n\t\t\t\t\t\tthis.runtime.releaseWorkflow();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!this.runtime.ownsWorkflow(editedGoal)) return;\n\t\t} else if (blocksStaleGoalToolCalls(editedGoal.status)) {\n\t\t\tthis.runtime.blockStaleGoalToolCalls();\n\t\t} else {\n\t\t\tthis.runtime.clearStaleGoalToolCallBlock();\n\t\t}\n\t\tif (editedGoal.status !== \"active\" && (retainedOwner || acquiredForEdit)) {\n\t\t\tthis.runtime.releaseWorkflow();\n\t\t}\n\t\tnotifyTerminal(ctx.ui, `Goal updated: ${objective}`, \"info\");\n\t}\n\n\tprivate reportWorkflowBusy(ctx: StatusContext) {\n\t\tconst message = \"Another workflow is active in this session. End it before starting Goal.\";\n\t\tif (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(message);\n\t\tnotifyTerminal(ctx.ui, message, \"warning\");\n\t\treturn { kind: \"busy\" as const };\n\t}\n\n\tshowGoal(ctx: StatusContext) {\n\t\tif (!this.runtime.activeGoal) {\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\tthis.reportGoalStatus(ctx, this.emptyGoalMessage());\n\t\t\treturn;\n\t\t}\n\t\tthis.runtime.recordGoalUsage(this.runtime.activeGoal, ctx);\n\t\tthis.runtime.persistGoal(this.runtime.activeGoal);\n\t\tthis.runtime.updateStatus(ctx, this.runtime.activeGoal);\n\t\tthis.reportGoalStatus(\n\t\t\tctx,\n\t\t\tgoalSummary(this.runtime.activeGoal, this.runtime.settings.continuationLimits.automaticTurns),\n\t\t);\n\t}\n\n\tprivate emptyGoalMessage() {\n\t\tconst legacy = this.runtime.legacyQueueState;\n\t\tif (!legacy) return \"Usage: /goal <objective>\\nNo goal is currently set.\";\n\t\treturn [\n\t\t\t\"Ordered goal queue has been removed.\",\n\t\t\t`Legacy queue state with ${legacy.retainedGoals} retained ${legacy.retainedGoals === 1 ? \"goal\" : \"goals\"} will not run automatically.`,\n\t\t\t\"Use /goal edit to reprioritize an active objective, start /goal <objectives>, or use /goal clear to discard the old queue state.\",\n\t\t\t'Example objective: \"task b is complete; do task a next, then task c and task d.\"',\n\t\t].join(\"\\n\");\n\t}\n\n\tprivate reportGoalStatus(ctx: StatusContext, message: string) {\n\t\tif (ctx.mode === \"print\" || ctx.mode === \"json\") {\n\t\t\tthrow new Error(\n\t\t\t\t`/goal status is unavailable in ${ctx.mode} mode because Pi does not expose an extension-command output channel. Use TUI or RPC mode.`,\n\t\t\t);\n\t\t}\n\t\tnotifyTerminal(ctx.ui, message, \"info\");\n\t}\n}\n", "import type { GoalPromptContext } from \"./prompts.js\";\nimport { buildGoalContextPrompt } from \"./prompts.js\";\n\nexport const GOAL_CONTRACT_MESSAGE_TYPE = \"goal-contract\";\nexport const GOAL_CONTRACT_VERSION = 1;\n\ninterface ContractMessage {\n\trole?: string;\n\tcustomType?: string;\n\tcontent?: unknown;\n}\n\nexport function createGoalContextContract(goal: GoalPromptContext) {\n\treturn {\n\t\trole: \"custom\" as const,\n\t\tcustomType: GOAL_CONTRACT_MESSAGE_TYPE,\n\t\tcontent: buildGoalContextPrompt(goal),\n\t\tdisplay: false,\n\t\tdetails: { version: GOAL_CONTRACT_VERSION, goalId: goal.id },\n\t\ttimestamp: 0,\n\t};\n}\n\nexport function reconcileGoalContextContract(messages: unknown[], goal: GoalPromptContext) {\n\tconst summaryBoundary = leadingSummaryBoundary(messages);\n\tconst expected = createGoalContextContract(goal);\n\tconst contractIndexes = messages.flatMap((message, index) =>\n\t\tunwrapMessage(message).customType === GOAL_CONTRACT_MESSAGE_TYPE ? [index] : [],\n\t);\n\tif (\n\t\tcontractIndexes.length === 1 &&\n\t\tcontractIndexes[0] === summaryBoundary &&\n\t\tunwrapMessage(messages[summaryBoundary]).content === expected.content\n\t) {\n\t\treturn messages;\n\t}\n\n\tconst withoutContracts = messages.filter(\n\t\t(message) => unwrapMessage(message).customType !== GOAL_CONTRACT_MESSAGE_TYPE,\n\t);\n\tconst insertionIndex = leadingSummaryBoundary(withoutContracts);\n\treturn [\n\t\t...withoutContracts.slice(0, insertionIndex),\n\t\texpected,\n\t\t...withoutContracts.slice(insertionIndex),\n\t];\n}\n\nfunction leadingSummaryBoundary(messages: readonly unknown[]) {\n\tlet index = 0;\n\twhile (index < messages.length) {\n\t\tconst role = unwrapMessage(messages[index]).role;\n\t\tif (role !== \"compactionSummary\" && role !== \"branchSummary\") break;\n\t\tindex += 1;\n\t}\n\treturn index;\n}\n\nfunction unwrapMessage(message: unknown): ContractMessage {\n\tconst entry = message as { message?: unknown } | undefined;\n\treturn (entry?.message ?? message ?? {}) as ContractMessage;\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { currentTokenTotal } from \"./accounting.js\";\nimport { notifyTerminal } from \"./errors.js\";\nimport { reconcileGoalContextContract } from \"./goal-contract.js\";\nimport { type ActiveGoal, loadGoalStateFromSession } from \"./persistence.js\";\nimport type { GoalRunController } from \"./run-protocol.js\";\nimport {\n\ttype AssistantMessageLike,\n\tabortCurrentTurn,\n\tblocksStaleGoalToolCalls,\n\tfindFinalAssistantMessage,\n\tformatError,\n\ttype GoalRuntime,\n\tincrementGoal,\n\tisGoalContextOverflow,\n\tisRetryableGoalInterruption,\n\tisUsageLimitedGoalInterruption,\n\tresetGoalSafetyEpoch,\n\tSTATUS_KEY,\n\ttype StatusContext,\n\ttransitionGoal,\n\ttruncateNotification,\n} from \"./runtime.js\";\nimport { hasAssistantToolCall } from \"./safety.js\";\nimport { DEFAULT_GOAL_SETTINGS, readGoalSettings } from \"./settings.js\";\n\nconst REMOVED_QUEUE_SETTING_WARNING =\n\t\"Ordered goal queue has been removed. Use /goal edit to reprioritize an active objective, or start /goal <objectives> if no active goal exists.\";\nconst REMOVED_PERSISTED_QUEUE_WARNING =\n\t\"Ordered goal queue has been removed. Start /goal <objectives> to continue with one merged objective, or use /goal clear to discard the old queue state.\";\n\ninterface GoalLifecycleOptions {\n\tsettingsPath?: string;\n}\n\nexport function registerGoalLifecycle(\n\tpi: ExtensionAPI,\n\truntime: GoalRuntime,\n\trunController: GoalRunController,\n\toptions: GoalLifecycleOptions = {},\n) {\n\tpi.on(\"session_start\", async (_event, ctx) => {\n\t\truntime.bindWorkflowSession(ctx.sessionManager);\n\t\truntime.replaceMenuSession();\n\t\truntime.clearCompletionStatusTimer();\n\t\truntime.clearContinuationTracking();\n\t\truntime.clearGoalWaitTimer();\n\t\truntime.clearPendingGoalPrompts();\n\t\truntime.clearAgentRun();\n\t\truntime.guardAbortGoalId = undefined;\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearBudgetWrapUp();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\truntime.legacyQueueState = undefined;\n\t\truntime.legacyExperimentalGoalsSetting = false;\n\t\truntime.clearTerminalDetails();\n\t\tconst previousToolVisibility = runtime.settings.toolVisibility;\n\t\tconst settingsResult = readGoalSettings(options.settingsPath);\n\t\tconst loaded = loadGoalStateFromSession(ctx);\n\t\truntime.settings =\n\t\t\tsettingsResult.kind === \"loaded\" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;\n\t\truntime.settingsLoadIssue = settingsResult.kind === \"invalid\" ? settingsResult : undefined;\n\t\truntime.activeGoal = undefined;\n\t\truntime.legacyQueueState = loaded.legacyQueueState;\n\t\truntime.legacyExperimentalGoalsSetting =\n\t\t\tsettingsResult.kind !== \"invalid\" && settingsResult.legacyExperimentalGoals;\n\t\trunController.bindSession(ctx);\n\n\t\tif (settingsResult.kind === \"invalid\") {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\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.legacyExperimentalGoalsSetting && !runtime.legacyQueueState) {\n\t\t\tnotifyTerminal(ctx.ui, REMOVED_QUEUE_SETTING_WARNING, \"warning\");\n\t\t}\n\n\t\tif (loaded.goal?.status === \"active\") {\n\t\t\tif (!runtime.acquireWorkflow()) {\n\t\t\t\truntime.activeGoal = transitionGoal(loaded.goal, \"paused\");\n\t\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\t\tnotifyTerminal(\n\t\t\t\t\tctx.ui,\n\t\t\t\t\t\"Goal was paused during restore because another workflow is active in this session. Resume it after the other workflow ends.\",\n\t\t\t\t\t\"warning\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.activeGoal = loaded.goal;\n\t\t\ttry {\n\t\t\t\truntime.toolPolicy.prepareSessionStart(\n\t\t\t\t\truntime.settings.toolVisibility,\n\t\t\t\t\tpreviousToolVisibility,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tnotifyTerminal(\n\t\t\t\t\tctx.ui,\n\t\t\t\t\t`Could not restore always-visible goal tools: ${formatError(error)}`,\n\t\t\t\t\t\"error\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (runtime.activeGoal.safetyResetPending) {\n\t\t\t\t// Resume/edit activation is persisted before its owned prompt starts. A\n\t\t\t\t// reload must commit that promised reset before enforcing the old limits.\n\t\t\t\truntime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n\t\t\t}\n\t\t\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\t\t\tif (runtime.enforceAutomaticTurnLimit(ctx, false) || runtime.enforceNoProgressLimit(ctx)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\t// On lazy restore, an earlier restrictive session-start policy still wins:\n\t\t\t// reconciliation unlocks ownership without widening the active tool set.\n\t\t\truntime.toolPolicy.reconcileRestoredState(runtime.settings.toolVisibility, true);\n\t\t\tif (!runtime.toolPolicy.toolsAvailable()) {\n\t\t\t\truntime.pauseGoalForUnavailableTools(ctx, false);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\tif (!runtime.ownsWorkflow(runtime.activeGoal)) return;\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\truntime.restoreGoalWaitTimer(ctx);\n\t\t\treturn;\n\t\t}\n\n\t\truntime.activeGoal = loaded.goal;\n\t\tlet appliedInactivePolicy = false;\n\t\tlet inactivePolicyFailed = false;\n\t\ttry {\n\t\t\tappliedInactivePolicy = runtime.withTemporaryWorkflowAccess(() => {\n\t\t\t\truntime.toolPolicy.prepareSessionStart(\n\t\t\t\t\truntime.settings.toolVisibility,\n\t\t\t\t\tpreviousToolVisibility,\n\t\t\t\t);\n\t\t\t\truntime.toolPolicy.reconcileRestoredState(\n\t\t\t\t\truntime.settings.toolVisibility,\n\t\t\t\t\truntime.activeGoal !== undefined && runtime.legacyQueueState === undefined,\n\t\t\t\t);\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tinactivePolicyFailed = true;\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Could not restore always-visible goal tools: ${formatError(error)}`,\n\t\t\t\t\"error\",\n\t\t\t);\n\t\t}\n\t\tif (!appliedInactivePolicy && !inactivePolicyFailed) {\n\t\t\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t\"Goal tool visibility was deferred because another workflow is active in this session.\",\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t}\n\t\tif (runtime.legacyQueueState) {\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t\tnotifyTerminal(ctx.ui, REMOVED_PERSISTED_QUEUE_WARNING, \"warning\");\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal) {\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t} else {\n\t\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\t}\n\t});\n\n\tpi.on(\"session_shutdown\", (_event, ctx) => {\n\t\tconst shutdownSession = ctx.sessionManager;\n\t\trunController.unbindSession();\n\t\truntime.closeMenuSession();\n\t\truntime.clearGoalWaitTimer();\n\t\tif (runtime.activeGoal) {\n\t\t\tif (runtime.activeGoal.status === \"active\") {\n\t\t\t\truntime.recordGoalUsage(runtime.activeGoal, ctx, false);\n\t\t\t}\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t}\n\t\truntime.clearContinuationTracking();\n\t\truntime.clearPendingGoalPrompts();\n\t\truntime.clearAgentRun();\n\t\truntime.guardAbortGoalId = undefined;\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearBudgetWrapUp();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\truntime.activeGoal = undefined;\n\t\truntime.legacyQueueState = undefined;\n\t\truntime.legacyExperimentalGoalsSetting = false;\n\t\tctx.ui.setStatus(STATUS_KEY, undefined);\n\t\truntime.clearCompletionStatusTimer();\n\t\truntime.clearTerminalDetails();\n\t\truntime.releaseWorkflow();\n\t\truntime.unbindWorkflowSession(shutdownSession);\n\t});\n\n\tpi.on(\"session_before_compact\", (event, ctx) => {\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\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn;\n\t\t}\n\t\tif (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;\n\t\truntime.cancelContinuationWork();\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };\n\t});\n\n\tpi.on(\"session_compact\", async (event, ctx) => {\n\t\tif (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\truntime.clearGoalRecovery();\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}\n\t\tconst usageRecorded = runtime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\tif (usageRecorded) {\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t}\n\t\tif (!usageRecorded) return;\n\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\n\t\tconst wasPiRetry = runtime.isPiOwnedCompactionRetry(event, runtime.activeGoal.id);\n\t\tif (wasPiRetry) return;\n\t\truntime.clearGoalRecoveryForGoal(runtime.activeGoal.id);\n\t\truntime.requestContinuation(runtime.activeGoal);\n\t\t// Pi emits session_compact before it clears its manual-compaction controller,\n\t\t// so sendUserMessage still rejects inside this hook even when ctx reports idle.\n\t\t// Defer one task; threshold compaction retains the intent for agent_settled\n\t\t// when Pi is still busy.\n\t\truntime.scheduleContinuationDispatch(ctx, runtime.activeGoal.id);\n\t});\n\n\tpi.on(\"input\", (event, ctx) => {\n\t\tif (event.source === \"extension\") {\n\t\t\tif (\n\t\t\t\truntime.consumeCancelledGoalPrompt(event.text) ||\n\t\t\t\truntime.consumeCancelledContinuationPrompt(event.text) ||\n\t\t\t\truntime.consumeStaleOwnedGoalPrompt(event.text)\n\t\t\t) {\n\t\t\t\treturn { action: \"handled\" as const };\n\t\t\t}\n\t\t\t// Streaming input is queued before its model work starts. Keep owned\n\t\t\t// markers pending for message_start, and track non-goal delivery mode so a\n\t\t\t// steer cannot consume a later follow-up's cleanup protection.\n\t\t\tif (runtime.acceptOwnedInputBoundary(event.text)) return;\n\t\t\truntime.supersedeOwnedInputCollision(event.text);\n\t\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\t\tif (event.streamingBehavior === \"steer\" || event.streamingBehavior === \"followUp\") {\n\t\t\t\truntime.noteQueuedNonGoalInput(event.text, event.streamingBehavior);\n\t\t\t}\n\t\t\truntime.clearGoalRecovery();\n\t\t\treturn;\n\t\t}\n\t\tif (/^\\/goal(?:\\s|$)/u.test(event.text.trimStart())) return;\n\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\tif (event.streamingBehavior === \"followUp\") {\n\t\t\truntime.noteQueuedNonGoalInput(event.text, \"followUp\", true);\n\t\t\treturn;\n\t\t}\n\t\tif (event.streamingBehavior === \"steer\") {\n\t\t\truntime.noteQueuedNonGoalInput(event.text, \"steer\");\n\t\t}\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearBudgetWrapUp();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\truntime.resetActiveSafetyEpoch(ctx);\n\t});\n\n\tpi.on(\"message_start\", (event, ctx) => {\n\t\tconst message = event.message as { role?: unknown; content?: unknown };\n\t\tif (\n\t\t\tmessage.role === \"assistant\" &&\n\t\t\truntime.activeGoal?.status === \"paused\" &&\n\t\t\truntime.guardAbortGoalId === runtime.activeGoal.id\n\t\t) {\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (message.role === \"custom\") {\n\t\t\tif (runtime.isActiveBudgetWrapUpMessage(message)) return;\n\t\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\t\tif (runtime.guardAbortGoalId === runtime.activeGoal?.id) {\n\t\t\t\truntime.guardAbortGoalId = undefined;\n\t\t\t}\n\t\t\tbeginNonGoalFollowUp(ctx, false);\n\t\t\treturn;\n\t\t}\n\t\tif (message.role !== \"user\") return;\n\t\tconst prompt = Array.isArray(message.content)\n\t\t\t? message.content\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(part) => part && typeof part === \"object\" && Reflect.get(part, \"type\") === \"text\",\n\t\t\t\t\t)\n\t\t\t\t\t.map((part) => Reflect.get(part as object, \"text\"))\n\t\t\t\t\t.filter((text): text is string => typeof text === \"string\")\n\t\t\t\t\t.join(\"\\n\")\n\t\t\t: typeof message.content === \"string\"\n\t\t\t\t? message.content\n\t\t\t\t: \"\";\n\t\tconst ownedPrompt = runtime.consumeOwnedGoalPrompt(prompt);\n\t\tconst ownedPromptBoundary = runtime.hasOwnedPromptBoundary(prompt);\n\t\tconst queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt, !ownedPromptBoundary);\n\t\tif (!ownedPrompt) {\n\t\t\tif (queuedNonGoalInput?.behavior === \"followUp\") {\n\t\t\t\tbeginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\truntime.activeGoal?.id !== ownedPrompt.goalId ||\n\t\t\t!runtime.ownsWorkflow(runtime.activeGoal)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.agentRunGoalId !== undefined && runtime.agentRunGoalId !== ownedPrompt.goalId) {\n\t\t\truntime.activeGoal.baselineTokens = Math.max(\n\t\t\t\t0,\n\t\t\t\tcurrentTokenTotal(ctx) - runtime.activeGoal.tokensUsed,\n\t\t\t);\n\t\t}\n\t\truntime.beginAgentRun(ownedPrompt.goalId, \"manual\");\n\t\tif (ownedPrompt.resetSafetyEpoch) {\n\t\t\truntime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n\t\t}\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t});\n\n\tpi.on(\"context\", (event, ctx) => {\n\t\tconst keptMessages = event.messages.filter((message) =>\n\t\t\truntime.keepBudgetWrapUpMessage(message),\n\t\t);\n\t\tconst messages =\n\t\t\truntime.activeGoal?.status === \"active\" && runtime.ownsWorkflow(runtime.activeGoal)\n\t\t\t\t? reconcileGoalContextContract(keptMessages, runtime.activeGoal)\n\t\t\t\t: keptMessages;\n\t\tif (\n\t\t\truntime.activeGoal?.status === \"paused\" &&\n\t\t\truntime.guardAbortGoalId === runtime.activeGoal.id\n\t\t) {\n\t\t\t// A current custom follow-up clears the guard at message_start. Otherwise,\n\t\t\t// context transformation aborts before the provider adapter receives the signal.\n\t\t\tabortCurrentTurn(ctx);\n\t\t}\n\t\tif (messages !== keptMessages || keptMessages.length !== event.messages.length) {\n\t\t\treturn { messages: messages as typeof event.messages };\n\t\t}\n\t});\n\n\tpi.on(\"tool_call\", (event, ctx) => {\n\t\truntime.markAgentToolAttempted();\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\truntime.clearStaleGoalToolCallBlock();\n\t\t\treturn;\n\t\t}\n\t\t// A blocked tool result would normally trigger another model call. Abort the\n\t\t// current turn so a tool-seeking model cannot create an unbounded loop that\n\t\t// burns provider quota while the goal is stopped.\n\t\tabortCurrentTurn(ctx);\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 (\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\truntime.queueBudgetWrapUp(ctx, runtime.activeGoal);\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn;\n\t\t}\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 (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\tif (runtime.limitActiveGoalForBudget(ctx, true)) return;\n\t\tif (!runtime.toolPolicy.toolsAvailable()) runtime.pauseGoalForUnavailableTools(ctx);\n\t});\n\n\tpi.on(\"before_agent_start\", (event, ctx) => {\n\t\truntime.clearAgentRun();\n\t\t// Pi-owned retries emit agent_start directly. Reaching a normal prompt\n\t\t// boundary means cleanup no longer owns the next run, so the hard-cap guard\n\t\t// must not abort it.\n\t\tif (runtime.guardAbortGoalId) runtime.guardAbortGoalId = undefined;\n\t\tconst goalPrompt = runtime.consumeOwnedGoalPrompt(event.prompt);\n\t\tconst goalPromptGoalId = goalPrompt?.goalId;\n\t\tconst continuationGoalId = goalPromptGoalId\n\t\t\t? undefined\n\t\t\t: runtime.markContinuationStarted(event.prompt);\n\t\tconst ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;\n\t\tconst ownedPromptBoundary = runtime.hasOwnedPromptBoundary(event.prompt);\n\t\tconst activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n\t\tconst activeGoalRecovery = runtime.hasActiveGoalRecovery();\n\t\tconst queuedNonGoalInput = activeBudgetWrapUp\n\t\t\t? undefined\n\t\t\t: runtime.consumeQueuedNonGoalInput(\n\t\t\t\t\tevent.prompt,\n\t\t\t\t\t!activeGoalRecovery && ownedPromptGoalId === undefined && !ownedPromptBoundary,\n\t\t\t\t);\n\t\tif (queuedNonGoalInput?.behavior === \"followUp\") {\n\t\t\tbeginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);\n\t\t}\n\t\tif (!ownedPromptGoalId && !ownedPromptBoundary) {\n\t\t\truntime.supersedeOwnedInputCollision(event.prompt);\n\t\t\tif (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n\t\t}\n\t\tif (runtime.activeGoal?.status === \"active\" && !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\truntime.cancelContinuationWork();\n\t\t\truntime.clearGoalRecovery();\n\t\t\tabortCurrentTurn(ctx);\n\t\t\treturn;\n\t\t}\n\t\tconst runOrigin = continuationGoalId\n\t\t\t? \"automatic\"\n\t\t\t: activeGoalRecovery && runtime.goalRecovery?.automaticOwner\n\t\t\t\t? \"automatic\"\n\t\t\t\t: \"manual\";\n\t\tif (activeBudgetWrapUp && runtime.activeGoal) {\n\t\t\truntime.beginAgentRun(runtime.activeGoal.id, \"manual\");\n\t\t\treturn;\n\t\t}\n\t\tif (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {\n\t\t\truntime.beginAgentRun(ownedPromptGoalId, runOrigin);\n\t\t\tif (runtime.activeGoal?.status === \"active\" && !runtime.toolPolicy.toolsAvailable()) {\n\t\t\t\truntime.pauseGoalForUnavailableTools(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\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn;\n\t\t}\n\t\truntime.beginAgentRun(runtime.activeGoal.id, runOrigin);\n\t\tif (!runtime.toolPolicy.toolsAvailable()) {\n\t\t\truntime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);\n\t\t\treturn;\n\t\t}\n\t\tif (goalPrompt?.resetSafetyEpoch && goalPromptGoalId === runtime.activeGoal.id) {\n\t\t\truntime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t}\n\t});\n\n\tpi.on(\"agent_start\", (_event, _ctx) => {\n\t\tconst activeGoal = runtime.activeGoal;\n\t\tif (\n\t\t\tactiveGoal &&\n\t\t\truntime.guardAbortGoalId === activeGoal.id &&\n\t\t\tactiveGoal.status === \"paused\"\n\t\t) {\n\t\t\tif (runtime.consumeQueuedNonGoalFollowUpForAgentStart()) {\n\t\t\t\truntime.guardAbortGoalId = undefined;\n\t\t\t\truntime.clearStaleGoalToolCallBlock();\n\t\t\t\truntime.beginAgentRun(null, undefined);\n\t\t\t}\n\t\t\t// Unknown runs defer cleanup until their message/context boundary: custom\n\t\t\t// follow-ups have no input event, while bare recovery is aborted pre-provider.\n\t\t\treturn;\n\t\t}\n\t\truntime.beginRecoveryRunIfNeeded();\n\t});\n\n\tpi.on(\"turn_end\", (event, ctx) => {\n\t\truntime.recordAutomaticTurn(ctx, event.message);\n\t});\n\n\tpi.on(\"agent_end\", (event, ctx) => {\n\t\tconst run = runtime.finishAgentRun();\n\t\tif (run.goalId === null) return;\n\t\tif (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp()) return;\n\t\tif (run.goalId && run.goalId !== 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\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\truntime.clearBudgetWrapUp();\n\t\t\treturn;\n\t\t}\n\t\tif (runtime.activeGoal.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst goalId = runtime.activeGoal.id;\n\t\tconst alreadyAwaitingContinuation = runtime.hasContinuationWorkForGoal(goalId);\n\t\tconst finalAssistant = findFinalAssistantMessage(event.messages);\n\n\t\tif (!alreadyAwaitingContinuation) runtime.activeGoal = incrementGoal(runtime.activeGoal);\n\t\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\n\t\tif (finalAssistant?.stopReason === \"aborted\") {\n\t\t\truntime.clearGoalRecoveryForGoal(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 (run.origin === \"automatic\" && runtime.enforceAutomaticTurnLimit(ctx, true)) return;\n\t\t\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\t\t\t\tif (!runtime.toolPolicy.toolsAvailable()) {\n\t\t\t\t\truntime.pauseGoalForUnavailableTools(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\tautomaticOwner: run.origin === \"automatic\",\n\t\t\t\t\terrorMessage: finalAssistant.errorMessage,\n\t\t\t\t};\n\t\t\t\truntime.cancelContinuationWork();\n\t\t\t\truntime.persistGoal(runtime.activeGoal);\n\t\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\truntime.clearGoalRecoveryForGoal(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\truntime.clearGoalRecoveryForGoal(goalId);\n\n\t\tif (runtime.limitActiveGoalForBudget(ctx, false)) return;\n\t\tif (!runtime.toolPolicy.toolsAvailable()) {\n\t\t\truntime.pauseGoalForUnavailableTools(ctx);\n\t\t\treturn;\n\t\t}\n\t\tif (\n\t\t\trun.origin === \"automatic\" &&\n\t\t\truntime.recordAutomaticRunProgress(\n\t\t\t\tctx,\n\t\t\t\tgoalId,\n\t\t\t\tevent.messages,\n\t\t\t\trun.toolAttempted || hasAssistantToolCall(event.messages),\n\t\t\t)\n\t\t) {\n\t\t\treturn;\n\t\t}\n\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\n\t\tconst currentGoal = runtime.activeGoal;\n\t\tif (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== \"active\") return;\n\t\truntime.requestContinuation(currentGoal);\n\t});\n\n\tpi.on(\"agent_settled\", (_event, ctx) => {\n\t\tif (runtime.activeGoal?.status === \"active\" && !runtime.ownsWorkflow(runtime.activeGoal)) {\n\t\t\truntime.cancelContinuationWork();\n\t\t\truntime.clearGoalRecovery();\n\t\t\truntime.clearSettledSafetyTracking();\n\t\t\treturn;\n\t\t}\n\t\truntime.finalizeSettledRecovery(ctx);\n\t\tconst resumedWait = runtime.dispatchDueGoalWait(ctx);\n\t\tif (!resumedWait) runtime.dispatchContinuationIfSettled(ctx);\n\t\truntime.clearSettledSafetyTracking();\n\t});\n\n\tfunction beginNonGoalFollowUp(ctx: StatusContext, resetSafetyEpoch: boolean) {\n\t\truntime.clearGoalRecovery();\n\t\truntime.clearStaleGoalToolCallBlock();\n\t\tif (resetSafetyEpoch) runtime.clearBudgetWrapUp();\n\t\tconst activeGoalId =\n\t\t\truntime.activeGoal?.status === \"active\" ? runtime.activeGoal.id : undefined;\n\t\truntime.beginAgentRun(activeGoalId ?? null, activeGoalId ? \"manual\" : undefined);\n\t\tif (resetSafetyEpoch && activeGoalId) runtime.resetActiveSafetyEpoch(ctx);\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\tconst stoppedGoal = runtime.stopActiveGoal(ctx, {\n\t\t\tkind: \"agent_interruption\",\n\t\t\texpectedGoalId: goal.id,\n\t\t\tstatus,\n\t\t\treason: assistant.errorMessage ?? `goal ${status} after agent interruption`,\n\t\t});\n\t\tif (!stoppedGoal) return;\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\tnotifyTerminal(\n\t\t\t\tctx.ui,\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\tnotifyTerminal(\n\t\t\t\tctx.ui,\n\t\t\t\t`Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\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", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { validateObjective } from \"./command.js\";\nimport type { GoalCommandController } from \"./commands.js\";\nimport {\n\tformatError,\n\ttype GoalRuntime,\n\ttype GoalStateSnapshot,\n\tisTerminalGoalStatus,\n\ttype StatusContext,\n} from \"./runtime.js\";\n\nexport const GOAL_RUN_START_CHANNEL = \"pi-goal:start\";\nexport const GOAL_RUN_CANCEL_CHANNEL = \"pi-goal:cancel\";\n\nconst RUN_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;\nconst MAX_CANCEL_REASON_LENGTH = 1_000;\n\nexport type GoalRunStatus = Exclude<GoalStateSnapshot[\"status\"], \"queued\">;\nexport type GoalRunErrorCode =\n\t| \"RPC_DISABLED\"\n\t| \"INVALID_REQUEST\"\n\t| \"NO_ACTIVE_SESSION\"\n\t| \"RUN_ID_IN_USE\"\n\t| \"RUN_NOT_FOUND\"\n\t| \"GOAL_ALREADY_EXISTS\"\n\t| \"ACTIVATION_FAILED\"\n\t| \"SUPERSEDED\";\n\nexport type GoalRunEvent =\n\t| {\n\t\t\ttype: \"state\";\n\t\t\trunId: string;\n\t\t\tgoalId: string;\n\t\t\tstatus: GoalRunStatus;\n\t\t\tsummary?: string;\n\t\t\treason?: string;\n\t }\n\t| {\n\t\t\ttype: \"error\";\n\t\t\trunId: string;\n\t\t\toperation: \"start\" | \"cancel\";\n\t\t\terror: { code: GoalRunErrorCode; message: string };\n\t };\n\ninterface GoalRunStartPayload {\n\trunId: string;\n\tobjective: string;\n\ttokenBudget?: number;\n}\n\ninterface BoundSession {\n\tgeneration: number;\n\tctx: StatusContext;\n}\n\ninterface ManagedRun {\n\trunId: string;\n\tgeneration: number;\n\tgoalId?: string;\n\tlastStatus?: GoalRunStatus;\n\tclosed: boolean;\n\tcancelRequested: boolean;\n\tcancelReason?: string;\n}\n\nexport function goalRunEventChannel(runId: string) {\n\treturn `pi-goal:event:${runId}`;\n}\n\nfunction isPayloadRecord(data: unknown): data is object {\n\tif (!data || typeof data !== \"object\") return false;\n\ttry {\n\t\treturn !Array.isArray(data);\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction readPayloadProperty(\n\tdata: object,\n\tkey: \"runId\" | \"objective\" | \"tokenBudget\" | \"reason\",\n): { ok: true; value: unknown } | { ok: false } {\n\ttry {\n\t\treturn { ok: true, value: Reflect.get(data, key) };\n\t} catch {\n\t\treturn { ok: false };\n\t}\n}\n\nfunction parseRunId(data: unknown): string | undefined {\n\tif (!isPayloadRecord(data)) return undefined;\n\tconst runId = readPayloadProperty(data, \"runId\");\n\treturn runId.ok && typeof runId.value === \"string\" && RUN_ID_PATTERN.test(runId.value)\n\t\t? runId.value\n\t\t: undefined;\n}\n\nfunction currentActiveGoal(runtime: GoalRuntime) {\n\treturn runtime.activeGoal;\n}\n\nfunction parseStartPayload(data: unknown): string | Omit<GoalRunStartPayload, \"runId\"> {\n\tif (!isPayloadRecord(data)) return \"start payload must be an object\";\n\tconst objectiveValue = readPayloadProperty(data, \"objective\");\n\tif (!objectiveValue.ok || typeof objectiveValue.value !== \"string\") {\n\t\treturn \"objective must be a string\";\n\t}\n\tconst objective = objectiveValue.value.trim();\n\tconst objectiveError = validateObjective(objective);\n\tif (objectiveError) return objectiveError;\n\tconst tokenBudgetValue = readPayloadProperty(data, \"tokenBudget\");\n\tif (\n\t\t!tokenBudgetValue.ok ||\n\t\t(tokenBudgetValue.value !== undefined &&\n\t\t\t(typeof tokenBudgetValue.value !== \"number\" ||\n\t\t\t\t!Number.isFinite(tokenBudgetValue.value) ||\n\t\t\t\t!Number.isSafeInteger(tokenBudgetValue.value) ||\n\t\t\t\ttokenBudgetValue.value <= 0))\n\t) {\n\t\treturn \"tokenBudget must be a positive integer\";\n\t}\n\treturn { objective, tokenBudget: tokenBudgetValue.value as number | undefined };\n}\n\nfunction parseCancelReason(data: unknown): string | undefined | { error: string } {\n\tif (!isPayloadRecord(data)) return { error: \"cancel payload must be an object\" };\n\tconst reasonValue = readPayloadProperty(data, \"reason\");\n\tif (\n\t\t!reasonValue.ok ||\n\t\t(reasonValue.value !== undefined && typeof reasonValue.value !== \"string\")\n\t) {\n\t\treturn { error: \"reason must be a string\" };\n\t}\n\tif (reasonValue.value === undefined) return undefined;\n\tconst reason = reasonValue.value.trim();\n\tif (reason.length > MAX_CANCEL_REASON_LENGTH) {\n\t\treturn { error: `reason must be at most ${MAX_CANCEL_REASON_LENGTH} characters` };\n\t}\n\treturn reason || undefined;\n}\n\nexport class GoalRunController {\n\tprivate readonly runtime: GoalRuntime;\n\tprivate readonly commands: GoalCommandController;\n\tprivate generation = 0;\n\tprivate session?: BoundSession;\n\tprivate run?: ManagedRun;\n\tprivate readonly usedRunIds = new Set<string>();\n\n\tconstructor(runtime: GoalRuntime, commands: GoalCommandController) {\n\t\tthis.runtime = runtime;\n\t\tthis.commands = commands;\n\t\tthis.runtime.setGoalStateSink((snapshot) => this.handleGoalState(snapshot));\n\t}\n\n\tregister(pi: ExtensionAPI) {\n\t\tpi.events.on(GOAL_RUN_START_CHANNEL, (data) => this.handleStart(data));\n\t\tpi.events.on(GOAL_RUN_CANCEL_CHANNEL, (data) => {\n\t\t\tthis.handleCancel(data);\n\t\t});\n\t}\n\n\tbindSession(ctx: StatusContext) {\n\t\tthis.generation += 1;\n\t\tthis.session = { generation: this.generation, ctx };\n\t\tthis.closeCurrentRun();\n\t\tthis.usedRunIds.clear();\n\t}\n\n\tunbindSession() {\n\t\tthis.generation += 1;\n\t\tthis.session = undefined;\n\t\tthis.closeCurrentRun();\n\t\tthis.usedRunIds.clear();\n\t}\n\n\tprivate async handleStart(data: unknown) {\n\t\tconst runId = parseRunId(data);\n\t\tif (!runId) return;\n\t\tconst session = this.session;\n\t\tif (!session) {\n\t\t\tthis.emitError(runId, \"start\", \"NO_ACTIVE_SESSION\", \"No active pi-goal session.\");\n\t\t\treturn;\n\t\t}\n\t\tif (!this.runtime.settings.rpc.enabled) {\n\t\t\tthis.emitError(runId, \"start\", \"RPC_DISABLED\", \"Managed run RPC is disabled.\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.usedRunIds.has(runId)) {\n\t\t\tthis.emitError(runId, \"start\", \"RUN_ID_IN_USE\", \"runId was already used in this session.\");\n\t\t\treturn;\n\t\t}\n\t\tconst parsed = parseStartPayload(data);\n\t\tif (typeof parsed === \"string\") {\n\t\t\tthis.emitError(runId, \"start\", \"INVALID_REQUEST\", parsed);\n\t\t\treturn;\n\t\t}\n\t\tif (this.session !== session || this.generation !== session.generation) {\n\t\t\tthis.emitError(\n\t\t\t\trunId,\n\t\t\t\t\"start\",\n\t\t\t\t\"SUPERSEDED\",\n\t\t\t\t\"The pi-goal session changed while validating the request.\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\tif (this.usedRunIds.has(runId)) {\n\t\t\tthis.emitError(runId, \"start\", \"RUN_ID_IN_USE\", \"runId was already used in this session.\");\n\t\t\treturn;\n\t\t}\n\t\tif (this.runtime.activeGoal || (this.run && !this.run.closed)) {\n\t\t\tthis.emitError(runId, \"start\", \"GOAL_ALREADY_EXISTS\", \"A Goal already exists.\");\n\t\t\treturn;\n\t\t}\n\n\t\tconst run: ManagedRun = {\n\t\t\trunId,\n\t\t\tgeneration: session.generation,\n\t\t\tclosed: false,\n\t\t\tcancelRequested: false,\n\t\t};\n\t\tthis.run = run;\n\t\tthis.usedRunIds.add(runId);\n\n\t\ttry {\n\t\t\tconst activation = await this.commands.startGoal(\n\t\t\t\tparsed.objective,\n\t\t\t\tparsed.tokenBudget,\n\t\t\t\tsession.ctx,\n\t\t\t\t(goal) => {\n\t\t\t\t\tif (this.ownsRun(run, session.generation)) run.goalId = goal.id;\n\t\t\t\t},\n\t\t\t\t() => this.ownsRun(run, session.generation),\n\t\t\t);\n\t\t\tif (activation?.kind === \"busy\" && this.ownsRun(run, session.generation)) {\n\t\t\t\tthis.closeCurrentRun();\n\t\t\t\tthis.emitError(\n\t\t\t\t\trunId,\n\t\t\t\t\t\"start\",\n\t\t\t\t\t\"ACTIVATION_FAILED\",\n\t\t\t\t\t\"Another workflow is active in this session. End it before starting Goal.\",\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (this.ownsRun(run, session.generation)) {\n\t\t\t\tthis.closeCurrentRun();\n\t\t\t\tthis.emitError(\n\t\t\t\t\trunId,\n\t\t\t\t\t\"start\",\n\t\t\t\t\t\"ACTIVATION_FAILED\",\n\t\t\t\t\t`Goal activation failed: ${formatError(error)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\tif (!this.ownsRun(run, session.generation)) return;\n\t\tif (!run.goalId) {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(runId, \"start\", \"ACTIVATION_FAILED\", \"Goal activation did not create a Goal.\");\n\t\t\treturn;\n\t\t}\n\t\tif (currentActiveGoal(this.runtime)?.id !== run.goalId) {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(runId, \"start\", \"SUPERSEDED\", \"The managed Goal was superseded.\");\n\t\t\treturn;\n\t\t}\n\t\tif (run.cancelRequested) this.cancelActiveRun(run, session, run.cancelReason);\n\t}\n\n\tprivate handleCancel(data: unknown) {\n\t\tconst runId = parseRunId(data);\n\t\tif (!runId) return;\n\t\tconst session = this.session;\n\t\tif (!session) {\n\t\t\tthis.emitError(runId, \"cancel\", \"NO_ACTIVE_SESSION\", \"No active pi-goal session.\");\n\t\t\treturn;\n\t\t}\n\t\tconst reason = parseCancelReason(data);\n\t\tif (reason && typeof reason === \"object\") {\n\t\t\tthis.emitError(runId, \"cancel\", \"INVALID_REQUEST\", reason.error);\n\t\t\treturn;\n\t\t}\n\t\tconst run = this.run;\n\t\tif (!run || run.closed || run.runId !== runId || run.generation !== session.generation) {\n\t\t\tthis.emitError(runId, \"cancel\", \"RUN_NOT_FOUND\", \"No active managed run matches runId.\");\n\t\t\treturn;\n\t\t}\n\t\tif (!run.goalId) {\n\t\t\trun.cancelRequested = true;\n\t\t\trun.cancelReason = reason;\n\t\t\treturn;\n\t\t}\n\t\tthis.cancelActiveRun(run, session, reason);\n\t}\n\n\tprivate cancelActiveRun(run: ManagedRun, session: BoundSession, reason: string | undefined) {\n\t\tif (!this.ownsRun(run, session.generation)) return;\n\t\tconst goal = this.runtime.activeGoal;\n\t\tif (!goal || goal.id !== run.goalId) {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(run.runId, \"cancel\", \"SUPERSEDED\", \"The managed Goal was superseded.\");\n\t\t\treturn;\n\t\t}\n\t\tif (goal.status !== \"active\") {\n\t\t\tthis.closeCurrentRun();\n\t\t\tthis.emitError(run.runId, \"cancel\", \"RUN_NOT_FOUND\", \"The managed run is no longer active.\");\n\t\t\treturn;\n\t\t}\n\t\tthis.runtime.setTerminalReason(goal.id, reason ?? \"goal cancelled by managed run\");\n\t\tthis.commands.pauseGoal(session.ctx);\n\t}\n\n\tprivate handleGoalState(snapshot: GoalStateSnapshot) {\n\t\tconst run = this.run;\n\t\tif (!run || run.closed || !run.goalId) return;\n\t\tif (run.goalId !== snapshot.goalId) {\n\t\t\tif (currentActiveGoal(this.runtime)?.id !== snapshot.goalId) return;\n\t\t\tthis.publishStateEvent(run, {\n\t\t\t\tgoalId: run.goalId,\n\t\t\t\tstatus: \"cleared\",\n\t\t\t\treason: \"managed Goal superseded by another Goal\",\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (snapshot.status === \"queued\" || run.lastStatus === snapshot.status) return;\n\t\tthis.publishStateEvent(run, snapshot);\n\t}\n\n\tprivate publishStateEvent(\n\t\trun: ManagedRun,\n\t\tsnapshot: Pick<GoalStateSnapshot, \"goalId\" | \"status\" | \"summary\" | \"reason\">,\n\t) {\n\t\tconst status = snapshot.status;\n\t\tif (status === \"queued\") return;\n\t\trun.lastStatus = status;\n\t\tconst event: GoalRunEvent = {\n\t\t\ttype: \"state\",\n\t\t\trunId: run.runId,\n\t\t\tgoalId: snapshot.goalId,\n\t\t\tstatus,\n\t\t\t...(snapshot.summary ? { summary: snapshot.summary } : {}),\n\t\t\t...(snapshot.reason ? { reason: snapshot.reason } : {}),\n\t\t};\n\t\tif (!isTerminalGoalStatus(status)) {\n\t\t\tthis.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);\n\t\t\treturn;\n\t\t}\n\n\t\trun.closed = true;\n\t\tthis.run = undefined;\n\t\tconst generation = run.generation;\n\t\t// Active stays synchronous so a listener can cancel before kickoff. Terminal\n\t\t// publication waits until the transition finishes, preventing listener work\n\t\t// from being overwritten by the old transition's remaining UI or cleanup.\n\t\tqueueMicrotask(() => {\n\t\t\tif (this.generation !== generation) return;\n\t\t\tthis.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);\n\t\t});\n\t}\n\n\tprivate emitError(\n\t\trunId: string,\n\t\toperation: \"start\" | \"cancel\",\n\t\tcode: GoalRunErrorCode,\n\t\tmessage: string,\n\t) {\n\t\tthis.runtime.pi.events.emit(goalRunEventChannel(runId), {\n\t\t\ttype: \"error\",\n\t\t\trunId,\n\t\t\toperation,\n\t\t\terror: { code, message },\n\t\t} satisfies GoalRunEvent);\n\t}\n\n\tprivate ownsRun(run: ManagedRun, generation: number) {\n\t\treturn (\n\t\t\tthis.session?.generation === generation &&\n\t\t\tthis.generation === generation &&\n\t\t\tthis.run === run &&\n\t\t\t!run.closed\n\t\t);\n\t}\n\n\tprivate closeCurrentRun() {\n\t\tif (this.run) this.run.closed = true;\n\t\tthis.run = undefined;\n\t}\n}\n", "import {\n\tDEFAULT_MAX_BYTES,\n\tDEFAULT_MAX_LINES,\n\tdefineTool,\n\ttype ExtensionAPI,\n\ttruncateHead,\n} from \"@earendil-works/pi-coding-agent\";\nimport { Type } from \"typebox\";\nimport { notifyTerminal, safeTerminalText } from \"./errors.js\";\nimport {\n\tformatStatus,\n\tGOAL_BLOCKED_TOOL,\n\tGOAL_COMPLETE_TOOL,\n\tGOAL_WAIT_TOOL,\n\ttype GoalRuntime,\n\tgoalIdRejectionReason,\n\tisContradictoryCompletionSummary,\n\tMAX_GOAL_ID_LENGTH,\n\tSTATUS_KEY,\n\ttransitionGoal,\n\ttruncateNotification,\n} from \"./runtime.js\";\nimport {\n\tcreateGoalWait,\n\tMAX_GOAL_WAIT_DELAY_MS,\n\tMAX_GOAL_WAIT_REASON_LENGTH,\n\tMIN_GOAL_WAIT_DELAY_MS,\n\tresolveGoalWaitDelay,\n} from \"./wait.js\";\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 GoalWaitDetails {\n\tgoal: string;\n\tgoal_id: string;\n\treason: string;\n\trequested_resume_after_ms?: number;\n\tresume_after_ms?: number;\n\tresume_at?: number;\n}\n\nconst MAX_GOAL_TEXT_LENGTH = 4_000;\nconst MAX_COMPLETION_SUMMARY_LENGTH = 4_000;\nconst MAX_BLOCKER_REASON_LENGTH = 1_000;\nconst MAX_BLOCKER_EVIDENCE_LENGTH = 4_000;\n\nexport function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {\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\tminLength: 1,\n\t\t\t\tmaxLength: MAX_GOAL_ID_LENGTH,\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\tminLength: 1,\n\t\t\t\tmaxLength: MAX_COMPLETION_SUMMARY_LENGTH,\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\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n\t\t\tif (completedGoal.status === \"active\" && !runtime.ownsWorkflow(completedGoal)) {\n\t\t\t\tconst rejection = \"Goal completion rejected: active Goal no longer owns its workflow.\";\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t};\n\t\t\t}\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\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\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\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\tif (completingDuringBudgetWrapUp) {\n\t\t\t\t\truntime.recordGoalUsage(completedGoal, ctx);\n\t\t\t\t\truntime.persistGoal(completedGoal);\n\t\t\t\t\truntime.updateStatus(ctx, completedGoal);\n\t\t\t\t\truntime.clearBudgetWrapUp();\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\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\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\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: summary.length > MAX_COMPLETION_SUMMARY_LENGTH\n\t\t\t\t\t? \"summary is too long\"\n\t\t\t\t\t: isContradictoryCompletionSummary(summary)\n\t\t\t\t\t\t? \"summary says the goal is not complete\"\n\t\t\t\t\t\t: undefined;\n\t\t\tif (rejectionReason) {\n\t\t\t\truntime.recordGoalUsage(completedGoal, ctx);\n\t\t\t\truntime.persistGoal(completedGoal);\n\t\t\t\truntime.updateStatus(ctx, completedGoal);\n\t\t\t\tconst rejection = `Goal completion rejected: ${rejectionReason}.`;\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\tif (completingDuringBudgetWrapUp) runtime.clearBudgetWrapUp();\n\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\n\t\t\t\t\tterminate: completingDuringBudgetWrapUp || undefined,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\truntime.clearGoalWaitTimer();\n\t\t\truntime.activeGoal = transitionGoal(completedGoal, \"complete\");\n\t\t\truntime.setCompletionSummary(runtime.activeGoal.id, summary);\n\t\t\truntime.recordGoalUsage(runtime.activeGoal, ctx);\n\t\t\truntime.persistGoal(runtime.activeGoal);\n\n\t\t\tctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));\n\t\t\truntime.clearActiveGoal(ctx);\n\t\t\truntime.showCompletionStatus(ctx);\n\t\t\tnotifyTerminal(ctx.ui, `Goal complete: ${goal}`, \"info\");\n\n\t\t\treturn {\n\t\t\t\tcontent: toolContent(`Goal complete: ${summary}`),\n\t\t\t\tdetails: completionDetails(goal, requestedGoalId, summary),\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\tminLength: 1,\n\t\t\t\tmaxLength: MAX_GOAL_ID_LENGTH,\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\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),\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\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 (!runtime.ownsWorkflow(blockedGoal))\n\t\t\t\treturn reject(\"active Goal no longer owns its workflow\");\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\tconst stoppedGoal = runtime.stopActiveGoal(ctx, {\n\t\t\t\tkind: \"blocker_report\",\n\t\t\t\texpectedGoalId: blockedGoal.id,\n\t\t\t\treason,\n\t\t\t});\n\t\t\tif (!stoppedGoal) return reject(\"active goal changed before blocker transition\");\n\t\t\tnotifyTerminal(ctx.ui, `Goal blocked: ${truncateNotification(reason)}`, \"warning\");\n\n\t\t\treturn {\n\t\t\t\tcontent: toolContent(`Goal blocked: ${reason}`),\n\t\t\t\tdetails: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),\n\t\t\t\tterminate: true,\n\t\t\t};\n\t\t},\n\t});\n\n\tconst goalWaitTool = defineTool({\n\t\tname: GOAL_WAIT_TOOL,\n\t\tlabel: \"Goal Wait\",\n\t\tdescription: `Keep the active /goal alive but quiet while an external event is expected. Call goal_wait alone after arranging a wake message, or provide resume_after_ms as a safety deadline. Requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms. Do not use it for ordinary unfinished work.`,\n\t\tpromptSnippet:\n\t\t\t\"Wait quietly for an external event without stopping the active /goal or starting automatic continuations\",\n\t\tpromptGuidelines: [\n\t\t\t\"Use goal_wait only when progress depends on a later non-goal message, or when resume_after_ms provides a bounded safety wake-up rather than a polling interval.\",\n\t\t\t`Prefer longer waits measured in minutes to avoid busy polling; goal_wait requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms.`,\n\t\t\t\"Arrange the external monitor or wake source before calling goal_wait, and call goal_wait alone because parallel sibling tools can prevent immediate turn termination.\",\n\t\t\t\"Pass the exact current goal_id so a stale turn cannot put a replacement goal into waiting.\",\n\t\t\t\"Do not use goal_blocked for a recoverable external wait that can be resumed by a message or deadline.\",\n\t\t],\n\t\tparameters: Type.Object({\n\t\t\tgoal_id: Type.String({\n\t\t\t\tminLength: 1,\n\t\t\t\tmaxLength: MAX_GOAL_ID_LENGTH,\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_GOAL_WAIT_REASON_LENGTH,\n\t\t\t\tdescription: \"Why the goal is waiting and which external event should wake it.\",\n\t\t\t}),\n\t\t\tresume_after_ms: Type.Optional(\n\t\t\t\tType.Integer({\n\t\t\t\t\tminimum: 1,\n\t\t\t\t\tmaximum: MAX_GOAL_WAIT_DELAY_MS,\n\t\t\t\t\tdescription: `Optional safety deadline in milliseconds that requests one continuation if no wake message arrives. Values below ${MIN_GOAL_WAIT_DELAY_MS} are accepted but clamped to ${MIN_GOAL_WAIT_DELAY_MS}.`,\n\t\t\t\t}),\n\t\t\t),\n\t\t}),\n\t\tasync execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n\t\t\tconst activeGoal = runtime.activeGoal;\n\t\t\tconst goal = activeGoal?.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 resumeAfterMs =\n\t\t\t\ttypeof params.resume_after_ms === \"number\" ? params.resume_after_ms : undefined;\n\t\t\tconst reject = (rejectionReason: string) => {\n\t\t\t\tconst rejection = `goal_wait rejected: ${rejectionReason}.`;\n\t\t\t\tnotifyTerminal(ctx.ui, rejection, \"warning\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: toolContent(rejection),\n\t\t\t\t\tdetails: waitDetails(goal, requestedGoalId, reason, resumeAfterMs),\n\t\t\t\t};\n\t\t\t};\n\n\t\t\tif (!activeGoal) 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\tconst staleGoalRejection = goalIdRejectionReason(activeGoal, requestedGoalId);\n\t\t\tif (staleGoalRejection) return reject(staleGoalRejection);\n\t\t\tif (activeGoal.status !== \"active\") {\n\t\t\t\treturn reject(`goal is ${activeGoal.status}, not active`);\n\t\t\t}\n\t\t\tif (!runtime.ownsWorkflow(activeGoal))\n\t\t\t\treturn reject(\"active Goal no longer owns its workflow\");\n\t\t\tif (activeGoal.waiting) return reject(\"goal is already waiting\");\n\t\t\tif (!reason) return reject(\"reason is empty\");\n\t\t\tif (reason.length > MAX_GOAL_WAIT_REASON_LENGTH) return reject(\"reason is too long\");\n\t\t\tif (\n\t\t\t\tresumeAfterMs !== undefined &&\n\t\t\t\t(!Number.isInteger(resumeAfterMs) ||\n\t\t\t\t\tresumeAfterMs < 1 ||\n\t\t\t\t\tresumeAfterMs > MAX_GOAL_WAIT_DELAY_MS)\n\t\t\t) {\n\t\t\t\treturn reject(`resume_after_ms must be a whole number from 1 to ${MAX_GOAL_WAIT_DELAY_MS}`);\n\t\t\t}\n\n\t\t\tconst { requestedMs, effectiveMs } = resolveGoalWaitDelay(resumeAfterMs);\n\t\t\tconst waiting = createGoalWait(reason, resumeAfterMs);\n\t\t\tconst waitingGoal = runtime.enterGoalWait(ctx, activeGoal.id, waiting);\n\t\t\tif (!waitingGoal) return reject(\"active goal changed before waiting transition\");\n\t\t\tconst clamped = requestedMs !== undefined && effectiveMs !== requestedMs;\n\t\t\tnotifyTerminal(ctx.ui, `Goal waiting: ${truncateNotification(reason)}`, \"info\");\n\t\t\treturn {\n\t\t\t\tcontent: toolContent(\n\t\t\t\t\tclamped\n\t\t\t\t\t\t? `Goal waiting: ${reason}\\nRequested resume_after_ms ${requestedMs} was clamped to ${effectiveMs}.`\n\t\t\t\t\t\t: `Goal waiting: ${reason}`,\n\t\t\t\t),\n\t\t\t\tdetails: waitDetails(\n\t\t\t\t\tgoal,\n\t\t\t\t\trequestedGoalId,\n\t\t\t\t\treason,\n\t\t\t\t\teffectiveMs,\n\t\t\t\t\twaiting.resumeAt,\n\t\t\t\t\tclamped ? requestedMs : undefined,\n\t\t\t\t),\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\tpi.registerTool(goalWaitTool);\n}\n\nfunction toolContent(text: string) {\n\treturn [\n\t\t{\n\t\t\ttype: \"text\" as const,\n\t\t\ttext: truncateHead(safeTerminalText(text), {\n\t\t\t\tmaxBytes: DEFAULT_MAX_BYTES,\n\t\t\t\tmaxLines: DEFAULT_MAX_LINES,\n\t\t\t}).content,\n\t\t},\n\t];\n}\n\nfunction completionDetails(goal: string, goalId: string, summary: string): GoalCompleteDetails {\n\treturn {\n\t\tgoal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n\t\tgoal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n\t\tsummary: summary.slice(0, MAX_COMPLETION_SUMMARY_LENGTH),\n\t};\n}\n\nfunction blockerDetails(\n\tgoal: string,\n\tgoalId: string,\n\treason: string,\n\tevidence: string,\n\trepeatedTurns: number,\n): GoalBlockedDetails {\n\treturn {\n\t\tgoal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n\t\tgoal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n\t\treason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),\n\t\tevidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),\n\t\trepeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,\n\t};\n}\n\nfunction waitDetails(\n\tgoal: string,\n\tgoalId: string,\n\treason: string,\n\tresumeAfterMs: number | undefined,\n\tresumeAt?: number,\n\trequestedResumeAfterMs?: number,\n): GoalWaitDetails {\n\treturn {\n\t\tgoal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n\t\tgoal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n\t\treason: reason.slice(0, MAX_GOAL_WAIT_REASON_LENGTH),\n\t\t...(requestedResumeAfterMs === undefined\n\t\t\t? {}\n\t\t\t: { requested_resume_after_ms: requestedResumeAfterMs }),\n\t\t...(resumeAfterMs === undefined ? {} : { resume_after_ms: resumeAfterMs }),\n\t\t...(resumeAt === undefined ? {} : { resume_at: resumeAt }),\n\t};\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { registerGoalCommand } from \"./command-registration.js\";\nimport { GoalCommandController } from \"./commands.js\";\nimport { registerGoalLifecycle } from \"./lifecycle.js\";\nimport { GoalRunController } from \"./run-protocol.js\";\nimport { GoalRuntime } from \"./runtime.js\";\nimport { registerGoalTools } from \"./tools.js\";\n\ninterface GoalOptions {\n\tsettingsPath?: string;\n}\n\nfunction registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {\n\tconst runtime = new GoalRuntime(pi);\n\tconst commands = new GoalCommandController(runtime);\n\tconst runController = new GoalRunController(runtime, commands);\n\n\t// Keep registration order explicit: managed-run bus listeners exist before tools,\n\t// command routing, and session lifecycle bind the per-factory runtime.\n\trunController.register(pi);\n\tregisterGoalTools(pi, runtime);\n\tregisterGoalCommand(pi, runtime, commands, options);\n\tregisterGoalLifecycle(pi, runtime, runController, options);\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"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,SAAS,oBACf,IACA,SACA,UACA,UAA0C,CAAC,GAC1C;AACD,QAAM,kBAAkB;AAAA,IACvB,QAAQ,oBAAoB,MAAM,OAAO,2BAAW;AAAA,EACrD;AACA,QAAM,mBAAmB;AAAA,IACxB,QAAQ,qBAAqB,MAAM,OAAO,kCAAkB;AAAA,EAC7D;AAEA,KAAG,gBAAgB,QAAQ;AAAA,IAC1B,aAAa;AAAA,IACb,wBAAwB,CAAC,WAAW,sBAAsB,MAAM;AAAA,IAChE,SAAS,OAAO,MAAM,QAAQ;AAC7B,UAAI,QAAQ,wBAAwB,KAAK,sBAAsB,IAAI,GAAG;AACrE,kCAA0B,KAAK,OAAO;AACtC;AAAA,MACD;AACA,YAAM,SAAS,aAAa,IAAI;AAChC,UAAI,OAAO,WAAW,UAAU;AAC/B,2BAAmB,QAAQ,GAAG;AAC9B;AAAA,MACD;AACA,UAAI,OAAO,SAAS,UAAU,KAAK,KAAK,MAAM,IAAI;AACjD,cAAM,gBAAgB,qBAAqB,OAAO;AAClD,YAAI;AACJ,YAAI;AACH,0BAAgB,MAAM,gBAAgB;AAAA,QACvC,SAAS,OAAO;AACf,cAAI,CAAC,cAAc,EAAG;AACtB,gBAAM;AAAA,QACP;AACA,YAAI,CAAC,cAAc,EAAG;AACtB,cAAM,EAAE,gBAAgB,IAAI;AAC5B,cAAM,gBAAgB,SAAS,UAAU,KAAK,OAAO,SAAS,WAAW;AACxE,gBAAM,q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