@narumitw/pi-goal 0.54.16 → 0.54.17
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/CHANGELOG.md +6 -0
- package/README.md +25 -7
- package/dist/chunks/{chunk-DJULXRA6.ts → chunk-MHW7VEET.ts} +40 -20
- package/dist/chunks/chunk-MHW7VEET.ts.map +7 -0
- package/dist/chunks/{chunk-35Q7SHFA.ts → chunk-ZLKWPYIF.ts} +2 -13
- package/dist/chunks/chunk-ZLKWPYIF.ts.map +7 -0
- package/dist/chunks/{menu-D2YSESU6.ts → menu-3AYWQ637.ts} +3 -3
- package/dist/chunks/{settings-ui-HV4QGJZ2.ts → settings-ui-RVQTWGJ5.ts} +2 -2
- package/dist/index.ts +76 -43
- package/dist/index.ts.map +2 -2
- package/docs/continuation-lifecycle.md +62 -15
- package/package.json +1 -1
- package/src/errors.ts +2 -16
- package/src/lifecycle.ts +91 -41
- package/src/runtime.ts +70 -21
- package/dist/chunks/chunk-35Q7SHFA.ts.map +0 -7
- package/dist/chunks/chunk-DJULXRA6.ts.map +0 -7
- /package/dist/chunks/{menu-D2YSESU6.ts.map → menu-3AYWQ637.ts.map} +0 -0
- /package/dist/chunks/{settings-ui-HV4QGJZ2.ts.map → settings-ui-RVQTWGJ5.ts.map} +0 -0
package/dist/index.ts.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
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 { isStaleContextError, 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 settingsPath?: string;\n loadGoalManager?: () => Promise<GoalManagerModule>;\n loadGoalSettings?: () => Promise<GoalSettingsModule>;\n}\n\nexport function registerGoalCommand(\n pi: ExtensionAPI,\n runtime: GoalRuntime,\n commands: GoalCommandController,\n options: GoalCommandRegistrationOptions = {},\n) {\n const loadGoalManager = cachedModuleLoader(options.loadGoalManager ?? (() => import(\"./menu.js\")));\n const loadGoalSettings = cachedModuleLoader(options.loadGoalSettings ?? (() => import(\"./settings-ui.js\")));\n\n pi.registerCommand(\"goal\", {\n description: \"Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>\",\n getArgumentCompletions: (prefix) => completeGoalArguments(prefix),\n handler: async (args, ctx) => {\n try {\n if (runtime.hasLegacyQueueInterface() && isRemovedQueueCommand(args)) {\n reportRemovedQueueCommand(ctx, runtime);\n return;\n }\n const result = parseCommand(args);\n if (typeof result === \"string\") {\n reportCommandError(result, ctx);\n return;\n }\n if (result.kind === \"show\" && args.trim() === \"\") {\n const menuIsCurrent = captureMenuOwnership(runtime);\n let managerModule: GoalManagerModule;\n try {\n managerModule = await loadGoalManager();\n } catch (error) {\n if (!menuIsCurrent()) return;\n throw error;\n }\n if (!menuIsCurrent()) return;\n const { showGoalManager } = managerModule;\n await showGoalManager(runtime, commands, ctx, async (menuCtx, target) => {\n const settingsAreCurrent = captureMenuOwnership(runtime);\n let settingsModule: GoalSettingsModule;\n try {\n settingsModule = await loadGoalSettings();\n } catch (error) {\n if (!settingsAreCurrent()) return;\n throw error;\n }\n if (!settingsAreCurrent()) return;\n const { showGoalSettings } = settingsModule;\n await showGoalSettings(runtime, menuCtx, {\n settingsPath: options.settingsPath,\n initialScreen: target,\n });\n });\n return;\n }\n switch (result.kind) {\n case \"show\":\n commands.showGoal(ctx);\n return;\n case \"pause\":\n commands.pauseGoal(ctx);\n return;\n case \"resume\":\n await commands.resumeGoal(ctx);\n return;\n case \"clear\":\n commands.clearGoal(ctx);\n return;\n case \"edit\":\n await commands.editGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n return;\n case \"start\":\n await commands.startGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n return;\n }\n } catch (error) {\n // Pi invalidates command ctx when the session is replaced while a\n // confirmation or menu await is still in flight. The dead session's\n // command result is discarded, so a stale context is not an error.\n if (isStaleContextError(error)) return;\n throw error;\n }\n },\n });\n}\n\nfunction reportCommandError(message: string, ctx: ExtensionCommandContext) {\n const safeMessage = safeTerminalText(message);\n if (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(safeMessage);\n notifyTerminal(ctx.ui, safeMessage, \"warning\");\n}\n\nfunction reportRemovedQueueCommand(ctx: ExtensionCommandContext, runtime: GoalRuntime) {\n const message = runtime.activeGoal\n ? \"Ordered goal queue has been removed. Use /goal edit to reprioritize the active objective instead.\"\n : \"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 if (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(message);\n notifyTerminal(ctx.ui, message, \"warning\");\n}\n\nfunction captureMenuOwnership(runtime: GoalRuntime): () => boolean {\n const generation = runtime.menuGeneration;\n const controller = runtime.menuController;\n return () =>\n runtime.menuGeneration === generation && runtime.menuController === controller && !controller.signal.aborted;\n}\n\nfunction cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {\n let pending: Promise<Module> | undefined;\n return () => {\n if (!pending) {\n pending = load().catch((error) => {\n pending = undefined;\n throw error;\n });\n }\n return pending;\n };\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 buildGoalPrompt,\n buildObjectiveUpdatedPrompt,\n buildResumePrompt,\n buildWaitingResumePrompt,\n} from \"./prompts.js\";\nimport {\n blocksStaleGoalToolCalls,\n createGoal,\n editedGoalStatus,\n formatBudget,\n formatError,\n type GoalRuntime,\n goalSummary,\n isResumableGoalStatus,\n nextGoalInstance,\n queueGoalSafetyReset,\n STATUS_KEY,\n type StatusContext,\n stoppedStatusLabel,\n transitionGoal,\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 private readonly runtime: GoalRuntime;\n\n constructor(runtime: GoalRuntime) {\n this.runtime = runtime;\n }\n\n async startGoal(\n objective: string,\n tokenBudget: number | undefined,\n ctx: StatusContext,\n onActivated?: (goal: ActiveGoal) => void,\n isActivationCurrent?: (goal: ActiveGoal) => boolean,\n isRequestCurrent?: () => boolean,\n ) {\n if (isRequestCurrent && !isRequestCurrent()) return;\n const validationError = validateObjective(objective);\n if (validationError) {\n notifyTerminal(ctx.ui, validationError, \"warning\");\n return;\n }\n\n const existingGoal = this.runtime.activeGoal?.status !== \"complete\" ? this.runtime.activeGoal : undefined;\n const legacyQueueBeforeActivation = existingGoal\n ? undefined\n : this.runtime.legacyQueueState\n ? structuredClone(this.runtime.legacyQueueState)\n : undefined;\n if (existingGoal) {\n const shouldReplace = await ctx.ui.confirm(\n \"Replace goal?\",\n `Current goal: ${safeGoalMenuText(existingGoal.text, 4_000)}\\n\\nNew goal: ${safeGoalMenuText(objective, 4_000)}`,\n );\n if (!shouldReplace) {\n notifyTerminal(ctx.ui, `Goal kept: ${existingGoal.text}`, \"info\");\n return;\n }\n if (isRequestCurrent && !isRequestCurrent()) return;\n if (this.runtime.activeGoal?.id !== existingGoal.id) {\n notifyTerminal(ctx.ui, \"The active goal changed while confirmation was open. Try again.\", \"warning\");\n return;\n }\n }\n\n // Tool registration keeps the Goal schema stable. A missing tool means another\n // policy or allowlist intentionally removed it, so activation must not widen it.\n if (isRequestCurrent && !isRequestCurrent()) return;\n const retainedOwner = this.runtime.ownsWorkflow(existingGoal);\n if (!this.runtime.acquireWorkflow(ctx.sessionManager)) return this.reportWorkflowBusy(ctx);\n const acquiredForRequest = !retainedOwner;\n try {\n this.runtime.assertGoalToolsAvailable();\n } catch (error) {\n notifyTerminal(ctx.ui, `Cannot start /goal: ${formatError(error)}`, \"error\");\n if (existingGoal?.status === \"active\") this.runtime.pauseGoalForUnavailableTools(ctx);\n else if (acquiredForRequest) this.runtime.releaseWorkflow();\n return;\n }\n\n this.runtime.clearGoalWaitTimer();\n this.runtime.cancelContinuationWork();\n this.runtime.clearGoalRecovery();\n this.runtime.clearBudgetWrapUp();\n this.runtime.clearStaleGoalToolCallBlock();\n if (!legacyQueueBeforeActivation) this.runtime.legacyQueueState = undefined;\n this.runtime.activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));\n const startedGoal = this.runtime.activeGoal;\n onActivated?.(startedGoal);\n if (!legacyQueueBeforeActivation) this.runtime.persistGoal(startedGoal);\n if (this.runtime.activeGoal?.id !== startedGoal.id || !this.runtime.ownsWorkflow(this.runtime.activeGoal)) {\n return;\n }\n this.runtime.updateStatus(ctx, startedGoal);\n const sent = await this.runtime.sendOwnedGoalPrompt(\n ctx,\n startedGoal.id,\n buildGoalPrompt(startedGoal),\n true,\n () => (isRequestCurrent?.() ?? true) && (isActivationCurrent?.(startedGoal) ?? true),\n );\n if (\n sent &&\n legacyQueueBeforeActivation &&\n this.runtime.activeGoal?.id === startedGoal.id &&\n this.runtime.activeGoal.status === \"active\"\n ) {\n this.runtime.legacyQueueState = undefined;\n this.runtime.persistGoal(startedGoal);\n }\n if (isActivationCurrent && !isActivationCurrent(startedGoal)) return;\n if (!sent) {\n let rolledBackStartedGoal = false;\n if (this.runtime.activeGoal?.id === startedGoal.id) {\n rolledBackStartedGoal = true;\n if (existingGoal) {\n this.runtime.recordGoalUsage(existingGoal, ctx);\n if (existingGoal.status === \"active\" && existingGoal.waiting) {\n this.runtime.activeGoal = existingGoal;\n this.runtime.clearStaleGoalToolCallBlock();\n this.runtime.persistGoal(existingGoal);\n this.runtime.updateStatus(ctx, existingGoal);\n this.runtime.restoreGoalWaitTimer(ctx);\n } else if (existingGoal.status === \"active\") {\n this.runtime.activeGoal = existingGoal;\n this.runtime.clearStaleGoalToolCallBlock();\n this.runtime.persistGoal(existingGoal);\n if (this.runtime.activeGoal?.id === existingGoal.id) {\n this.runtime.updateStatus(ctx, existingGoal);\n }\n } else {\n this.runtime.activeGoal = existingGoal;\n if (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n this.runtime.blockStaleGoalToolCalls();\n } else {\n this.runtime.clearStaleGoalToolCallBlock();\n }\n this.runtime.persistGoal(this.runtime.activeGoal);\n this.runtime.updateStatus(ctx, this.runtime.activeGoal);\n }\n } else if (legacyQueueBeforeActivation) {\n this.runtime.activeGoal = undefined;\n this.runtime.legacyQueueState = legacyQueueBeforeActivation;\n this.runtime.cancelContinuationWork();\n this.runtime.clearGoalRecovery();\n this.runtime.clearBudgetWrapUp();\n this.runtime.clearStaleGoalToolCallBlock();\n ctx.ui.setStatus(STATUS_KEY, undefined);\n } else {\n this.runtime.clearActiveGoal(ctx, \"goal activation rolled back\", false);\n }\n }\n if (rolledBackStartedGoal) {\n if (acquiredForRequest && !this.runtime.ownsWorkflow(existingGoal)) {\n this.runtime.releaseWorkflow();\n }\n }\n return;\n }\n if (this.runtime.activeGoal?.id !== startedGoal.id || !this.runtime.ownsWorkflow(this.runtime.activeGoal)) {\n return;\n }\n const automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;\n notifyTerminal(\n ctx.ui,\n `${existingGoal ? \"Goal replaced\" : \"Goal started\"}: ${objective}. ${\n startedGoal.tokenBudget === undefined\n ? \"\"\n : `Token budget: ${formatTokenCount(startedGoal.tokenBudget)} cumulative; the final model call may exceed it. `\n }${\n automaticLimit === null\n ? \"Automatic work is Unlimited; tool loops may consume substantial tokens and provider cost. Open /goal to monitor.\"\n : `Automatic work pauses after ${automaticLimit} responses; open /goal to monitor progress.`\n }`,\n automaticLimit === null ? \"warning\" : \"info\",\n );\n }\n\n pauseGoal(ctx: StatusContext) {\n if (!this.runtime.activeGoal) {\n notifyTerminal(ctx.ui, \"No active goal.\", \"info\");\n return;\n }\n if (this.runtime.activeGoal.status !== \"active\") {\n notifyTerminal(ctx.ui, `Goal is ${this.runtime.activeGoal.status}; only active goals can be paused.`, \"warning\");\n return;\n }\n const stoppedGoal = this.runtime.stopActiveGoal(ctx, {\n kind: \"explicit_pause\",\n expectedGoalId: this.runtime.activeGoal.id,\n });\n if (stoppedGoal) notifyTerminal(ctx.ui, `Goal paused: ${stoppedGoal.text}`, \"info\");\n }\n\n async resumeGoal(ctx: StatusContext) {\n if (!this.runtime.activeGoal) {\n notifyTerminal(ctx.ui, \"No active goal.\", \"info\");\n return;\n }\n if (this.runtime.activeGoal.status === \"active\" && this.runtime.activeGoal.waiting) {\n await this.resumeWaitingGoal(ctx);\n return;\n }\n if (!isResumableGoalStatus(this.runtime.activeGoal.status)) {\n notifyTerminal(\n ctx.ui,\n `Goal is ${this.runtime.activeGoal.status}; only paused, blocked, usage-limited, or budget-limited goals can be resumed.`,\n \"warning\",\n );\n return;\n }\n if (\n this.runtime.activeGoal.tokenBudget !== undefined &&\n this.runtime.activeGoal.tokensUsed >= this.runtime.activeGoal.tokenBudget\n ) {\n notifyTerminal(ctx.ui, `Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`, \"warning\");\n return;\n }\n if (!this.runtime.acquireWorkflow(ctx.sessionManager)) {\n this.reportWorkflowBusy(ctx);\n return;\n }\n try {\n this.runtime.assertGoalToolsAvailable();\n } catch (error) {\n notifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, \"error\");\n this.runtime.releaseWorkflow();\n return;\n }\n const stoppedGoal = this.runtime.activeGoal;\n const stoppedStatus = stoppedGoal.status;\n this.runtime.cancelContinuationWork();\n this.runtime.clearGoalRecovery();\n this.runtime.clearBudgetWrapUp();\n this.runtime.clearStaleGoalToolCallBlock();\n this.runtime.activeGoal = queueGoalSafetyReset(transitionGoal(nextGoalInstance(this.runtime.activeGoal), \"active\"));\n this.runtime.persistGoal(this.runtime.activeGoal);\n if (this.runtime.activeGoal.status !== \"active\") {\n this.runtime.updateStatus(ctx, this.runtime.activeGoal);\n this.runtime.releaseWorkflow();\n notifyTerminal(ctx.ui, `Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`, \"warning\");\n return;\n }\n if (!this.runtime.ownsWorkflow(this.runtime.activeGoal)) return;\n this.runtime.updateStatus(ctx, this.runtime.activeGoal);\n const resumedGoal = this.runtime.activeGoal;\n const sent = await this.runtime.sendOwnedGoalPrompt(\n ctx,\n resumedGoal.id,\n buildResumePrompt(resumedGoal, stoppedStatus),\n );\n if (!sent) {\n if (this.runtime.activeGoal?.id === resumedGoal.id && this.runtime.activeGoal.status === \"active\") {\n this.runtime.activeGoal = stoppedGoal;\n this.runtime.persistGoal(this.runtime.activeGoal);\n this.runtime.updateStatus(ctx, this.runtime.activeGoal);\n if (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n this.runtime.blockStaleGoalToolCalls();\n }\n this.runtime.releaseWorkflow();\n }\n return;\n }\n if (!this.runtime.ownsWorkflow(resumedGoal)) return;\n const automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;\n notifyTerminal(\n ctx.ui,\n `Goal resumed from ${stoppedStatusLabel(stoppedStatus)}: ${resumedGoal.text}. ${\n automaticLimit === null\n ? \"Automatic work remains Unlimited; goal progress and cumulative usage are preserved.\"\n : `The automatic-work counter will reset to 0 of ${automaticLimit} when the resumed prompt starts; goal progress and cumulative usage are preserved.`\n }`,\n automaticLimit === null ? \"warning\" : \"info\",\n );\n }\n\n private async resumeWaitingGoal(ctx: StatusContext) {\n const waitingGoal = this.runtime.activeGoal;\n const waiting = waitingGoal?.waiting;\n if (waitingGoal?.status !== \"active\" || !waiting) return;\n if (!this.runtime.acquireWorkflow(ctx.sessionManager)) {\n this.reportWorkflowBusy(ctx);\n return;\n }\n try {\n this.runtime.assertGoalToolsAvailable();\n } catch (error) {\n notifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, \"error\");\n return;\n }\n if (!this.runtime.clearGoalWait(ctx, waitingGoal.id)) return;\n const resumedGoal = this.runtime.activeGoal;\n if (!resumedGoal || resumedGoal.id !== waitingGoal.id || resumedGoal.status !== \"active\") return;\n const sent = await this.runtime.sendOwnedGoalPrompt(\n ctx,\n resumedGoal.id,\n buildWaitingResumePrompt(resumedGoal, waiting.reason),\n false,\n );\n if (!sent) {\n if (this.runtime.activeGoal?.id === waitingGoal.id) {\n this.runtime.enterGoalWait(ctx, waitingGoal.id, waiting);\n }\n return;\n }\n if (!this.runtime.ownsWorkflow(resumedGoal)) return;\n notifyTerminal(ctx.ui, `Goal resumed from waiting: ${waitingGoal.text}`, \"info\");\n }\n\n clearGoal(ctx: StatusContext) {\n if (!this.runtime.activeGoal) {\n const hadLegacyQueue = this.runtime.legacyQueueState !== undefined;\n this.runtime.legacyQueueState = undefined;\n this.runtime.cancelContinuationWork();\n this.runtime.clearGoalRecovery();\n this.runtime.clearBudgetWrapUp();\n this.runtime.clearStaleGoalToolCallBlock();\n this.runtime.clearPersistedGoal(ctx.cwd);\n ctx.ui.setStatus(STATUS_KEY, undefined);\n notifyTerminal(\n ctx.ui,\n hadLegacyQueue ? \"Removed legacy ordered goal queue state.\" : \"No active goal.\",\n hadLegacyQueue ? \"warning\" : \"info\",\n );\n return;\n }\n\n const stoppedGoal = this.runtime.activeGoal.text;\n this.runtime.clearActiveGoal(ctx);\n notifyTerminal(ctx.ui, `Goal cleared: ${stoppedGoal}`, \"warning\");\n }\n\n async editGoal(objective: string, tokenBudget: number | undefined, ctx: StatusContext) {\n const validationError = validateObjective(objective);\n if (validationError) {\n notifyTerminal(ctx.ui, validationError, \"warning\");\n return;\n }\n if (!this.runtime.activeGoal) {\n notifyTerminal(ctx.ui, \"No active goal. Use /goal <objective> to start one.\", \"warning\");\n return;\n }\n\n const currentGoal = this.runtime.activeGoal;\n const effectiveTokenBudget = tokenBudget ?? currentGoal.tokenBudget;\n if (\n currentGoal.status === \"budget_limited\" &&\n effectiveTokenBudget !== undefined &&\n effectiveTokenBudget <= currentGoal.tokensUsed\n ) {\n notifyTerminal(\n ctx.ui,\n `Goal token budget is still reached: ${formatBudget(currentGoal)}. Raise the budget above current usage before editing.`,\n \"warning\",\n );\n return;\n }\n const previousStatus = currentGoal.status;\n const intendsActive = editedGoalStatus(previousStatus) === \"active\";\n const retainedOwner = this.runtime.ownsWorkflow(currentGoal);\n if (intendsActive && !this.runtime.acquireWorkflow(ctx.sessionManager)) {\n this.reportWorkflowBusy(ctx);\n return;\n }\n const acquiredForEdit = intendsActive && !retainedOwner;\n if (intendsActive) {\n try {\n this.runtime.assertGoalToolsAvailable();\n } catch (error) {\n notifyTerminal(ctx.ui, `Cannot reactivate /goal: ${formatError(error)}`, \"error\");\n if (currentGoal.status === \"active\") this.runtime.pauseGoalForUnavailableTools(ctx);\n else if (acquiredForEdit) this.runtime.releaseWorkflow();\n return;\n }\n }\n\n this.runtime.recordGoalUsage(currentGoal, ctx);\n const previousGoal = { ...currentGoal };\n this.runtime.clearGoalWaitTimer();\n this.runtime.cancelContinuationWork();\n this.runtime.clearGoalRecovery();\n this.runtime.clearBudgetWrapUp();\n const rotatedGoal = nextGoalInstance(currentGoal);\n const transitionedGoal = transitionGoal(\n {\n ...rotatedGoal,\n text: objective,\n tokenBudget: effectiveTokenBudget,\n waiting: undefined,\n },\n editedGoalStatus(previousStatus),\n );\n const nextGoal = transitionedGoal.status === \"active\" ? queueGoalSafetyReset(transitionedGoal) : transitionedGoal;\n this.runtime.activeGoal = nextGoal;\n this.runtime.persistGoal(this.runtime.activeGoal);\n this.runtime.updateStatus(ctx, this.runtime.activeGoal);\n const editedGoal = this.runtime.activeGoal;\n if (!editedGoal) return;\n if (editedGoal.status === \"active\") {\n if (!this.runtime.ownsWorkflow(editedGoal)) return;\n this.runtime.clearStaleGoalToolCallBlock();\n const sent = await this.runtime.sendOwnedGoalPrompt(ctx, editedGoal.id, buildObjectiveUpdatedPrompt(editedGoal));\n if (!sent) {\n if (this.runtime.activeGoal?.id === editedGoal.id) {\n if (previousStatus === \"active\" && previousGoal.waiting) {\n this.runtime.activeGoal = previousGoal;\n this.runtime.clearStaleGoalToolCallBlock();\n this.runtime.persistGoal(previousGoal);\n this.runtime.updateStatus(ctx, previousGoal);\n this.runtime.restoreGoalWaitTimer(ctx);\n } else if (previousStatus === \"active\") {\n this.runtime.activeGoal = previousGoal;\n this.runtime.clearStaleGoalToolCallBlock();\n this.runtime.persistGoal(previousGoal);\n if (this.runtime.activeGoal?.id === previousGoal.id) {\n this.runtime.updateStatus(ctx, previousGoal);\n }\n } else {\n this.runtime.activeGoal = previousGoal;\n if (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n this.runtime.blockStaleGoalToolCalls();\n } else {\n this.runtime.clearStaleGoalToolCallBlock();\n }\n this.runtime.persistGoal(this.runtime.activeGoal);\n this.runtime.updateStatus(ctx, this.runtime.activeGoal);\n }\n if (acquiredForEdit && previousStatus !== \"active\") {\n this.runtime.releaseWorkflow();\n }\n }\n return;\n }\n if (!this.runtime.ownsWorkflow(editedGoal)) return;\n } else if (blocksStaleGoalToolCalls(editedGoal.status)) {\n this.runtime.blockStaleGoalToolCalls();\n } else {\n this.runtime.clearStaleGoalToolCallBlock();\n }\n if (editedGoal.status !== \"active\" && (retainedOwner || acquiredForEdit)) {\n this.runtime.releaseWorkflow();\n }\n notifyTerminal(ctx.ui, `Goal updated: ${objective}`, \"info\");\n }\n\n private reportWorkflowBusy(ctx: StatusContext) {\n const message = \"Another workflow is active in this session. End it before starting Goal.\";\n if (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(message);\n notifyTerminal(ctx.ui, message, \"warning\");\n return { kind: \"busy\" as const };\n }\n\n showGoal(ctx: StatusContext) {\n if (!this.runtime.activeGoal) {\n ctx.ui.setStatus(STATUS_KEY, undefined);\n this.reportGoalStatus(ctx, this.emptyGoalMessage());\n return;\n }\n this.runtime.recordGoalUsage(this.runtime.activeGoal, ctx);\n this.runtime.persistGoal(this.runtime.activeGoal);\n this.runtime.updateStatus(ctx, this.runtime.activeGoal);\n this.reportGoalStatus(\n ctx,\n goalSummary(this.runtime.activeGoal, this.runtime.settings.continuationLimits.automaticTurns),\n );\n }\n\n private emptyGoalMessage() {\n const legacy = this.runtime.legacyQueueState;\n if (!legacy) return \"Usage: /goal <objective>\\nNo goal is currently set.\";\n return [\n \"Ordered goal queue has been removed.\",\n `Legacy queue state with ${legacy.retainedGoals} retained ${legacy.retainedGoals === 1 ? \"goal\" : \"goals\"} will not run automatically.`,\n \"Use /goal edit to reprioritize an active objective, start /goal <objectives>, or use /goal clear to discard the old queue state.\",\n 'Example objective: \"task b is complete; do task a next, then task c and task d.\"',\n ].join(\"\\n\");\n }\n\n private reportGoalStatus(ctx: StatusContext, message: string) {\n if (ctx.mode === \"print\" || ctx.mode === \"json\") {\n throw new Error(\n `/goal status is unavailable in ${ctx.mode} mode because Pi does not expose an extension-command output channel. Use TUI or RPC mode.`,\n );\n }\n notifyTerminal(ctx.ui, message, \"info\");\n }\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { currentTokenTotal } from \"./accounting.js\";\nimport { notifyTerminal } from \"./errors.js\";\nimport {\n GOAL_CONTRACT_MESSAGE_TYPE,\n isGoalContextContract,\n reconcileGoalContextContract,\n reconcileInactiveGoalContextContract,\n} from \"./goal-contract.js\";\nimport { type ActiveGoal, loadGoalStateFromSession } from \"./persistence.js\";\nimport type { GoalRunController } from \"./run-protocol.js\";\nimport {\n type AssistantMessageLike,\n abortCurrentTurn,\n blocksStaleGoalToolCalls,\n findFinalAssistantMessage,\n type GoalRuntime,\n incrementGoal,\n isGoalContextOverflow,\n isRetryableGoalInterruption,\n isUsageLimitedGoalInterruption,\n resetGoalSafetyEpoch,\n STATUS_KEY,\n type StatusContext,\n transitionGoal,\n truncateNotification,\n} from \"./runtime.js\";\nimport { hasAssistantToolCall } from \"./safety.js\";\nimport { DEFAULT_GOAL_SETTINGS, readGoalSettings } from \"./settings.js\";\n\nconst REMOVED_QUEUE_SETTING_WARNING =\n \"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 \"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 settingsPath?: string;\n}\n\nexport function registerGoalLifecycle(\n pi: ExtensionAPI,\n runtime: GoalRuntime,\n runController: GoalRunController,\n options: GoalLifecycleOptions = {},\n) {\n // Pi invalidates this module's ExtensionContext when the session is replaced\n // or reloaded, but detached prompts and queued emits can still invoke these\n // handlers afterward. After session_shutdown every ctx getter throws a stale\n // context error, so late handlers must return before touching ctx. The flag\n // starts true so handlers keep working on runners where session_start was\n // never emitted (for example late extension loading).\n let sessionActive = true;\n pi.on(\"session_start\", async (_event, ctx) => {\n sessionActive = true;\n runtime.bindWorkflowSession(ctx.sessionManager);\n runtime.replaceMenuSession();\n runtime.clearCompletionStatusTimer();\n runtime.clearContinuationTracking();\n runtime.clearGoalWaitTimer();\n runtime.clearPendingGoalPrompts();\n runtime.clearAgentRun();\n runtime.guardAbortGoalId = undefined;\n runtime.clearGoalRecovery();\n runtime.clearBudgetWrapUp();\n runtime.clearStaleGoalToolCallBlock();\n runtime.legacyQueueState = undefined;\n runtime.legacyExperimentalGoalsSetting = false;\n runtime.clearTerminalDetails();\n const settingsResult = readGoalSettings(options.settingsPath);\n const loaded = loadGoalStateFromSession(ctx);\n runtime.settings = settingsResult.kind === \"loaded\" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;\n runtime.settingsLoadIssue = settingsResult.kind === \"invalid\" ? settingsResult : undefined;\n runtime.activeGoal = undefined;\n runtime.legacyQueueState = loaded.legacyQueueState;\n runtime.legacyExperimentalGoalsSetting =\n settingsResult.kind !== \"invalid\" && settingsResult.legacyExperimentalGoals;\n runController.bindSession(ctx);\n\n if (settingsResult.kind === \"invalid\") {\n notifyTerminal(ctx.ui, `pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`, \"warning\");\n }\n if (runtime.legacyExperimentalGoalsSetting && !runtime.legacyQueueState) {\n notifyTerminal(ctx.ui, REMOVED_QUEUE_SETTING_WARNING, \"warning\");\n }\n\n if (loaded.goal?.status === \"active\") {\n if (!runtime.acquireWorkflow()) {\n runtime.activeGoal = transitionGoal(loaded.goal, \"paused\");\n runtime.persistGoal(runtime.activeGoal);\n runtime.ensureInactiveGoalContextContract(ctx);\n runtime.updateStatus(ctx, runtime.activeGoal);\n notifyTerminal(\n ctx.ui,\n \"Goal was paused during restore because another workflow is active in this session. Resume it after the other workflow ends.\",\n \"warning\",\n );\n return;\n }\n runtime.activeGoal = loaded.goal;\n if (runtime.activeGoal.safetyResetPending) {\n // Resume/edit activation is persisted before its owned prompt starts. A\n // reload must commit that promised reset before enforcing the old limits.\n runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n }\n runtime.recordGoalUsage(runtime.activeGoal, ctx);\n if (runtime.limitActiveGoalForBudget(ctx, false)) return;\n if (runtime.enforceAutomaticTurnLimit(ctx, false) || runtime.enforceNoProgressLimit(ctx)) {\n return;\n }\n if (!runtime.goalToolsAvailable()) {\n runtime.pauseGoalForUnavailableTools(ctx, false);\n return;\n }\n runtime.persistGoal(runtime.activeGoal);\n if (!runtime.ownsWorkflow(runtime.activeGoal)) return;\n const restoredGoalId = runtime.activeGoal.id;\n runtime.ensureGoalContextContract(ctx, runtime.activeGoal);\n if (\n runtime.activeGoal?.id !== restoredGoalId ||\n runtime.activeGoal.status !== \"active\" ||\n !runtime.ownsWorkflow(runtime.activeGoal)\n ) {\n return;\n }\n runtime.updateStatus(ctx, runtime.activeGoal);\n runtime.restoreGoalWaitTimer(ctx);\n return;\n }\n\n runtime.activeGoal = loaded.goal;\n if (runtime.legacyQueueState) {\n ctx.ui.setStatus(STATUS_KEY, undefined);\n notifyTerminal(ctx.ui, REMOVED_PERSISTED_QUEUE_WARNING, \"warning\");\n return;\n }\n if (runtime.activeGoal) {\n runtime.persistGoal(runtime.activeGoal);\n runtime.ensureInactiveGoalContextContract(ctx);\n runtime.updateStatus(ctx, runtime.activeGoal);\n } else {\n runtime.ensureInactiveGoalContextContract(ctx);\n ctx.ui.setStatus(STATUS_KEY, undefined);\n }\n });\n\n pi.on(\"session_shutdown\", (_event, ctx) => {\n sessionActive = false;\n const shutdownSession = ctx.sessionManager;\n runController.unbindSession();\n runtime.closeMenuSession();\n runtime.clearGoalWaitTimer();\n if (runtime.activeGoal) {\n if (runtime.activeGoal.status === \"active\") {\n runtime.recordGoalUsage(runtime.activeGoal, ctx, false);\n }\n runtime.persistGoal(runtime.activeGoal);\n }\n runtime.clearContinuationTracking();\n runtime.clearPendingGoalPrompts();\n runtime.clearAgentRun();\n runtime.guardAbortGoalId = undefined;\n runtime.clearGoalRecovery();\n runtime.clearBudgetWrapUp();\n runtime.clearStaleGoalToolCallBlock();\n runtime.activeGoal = undefined;\n runtime.legacyQueueState = undefined;\n runtime.legacyExperimentalGoalsSetting = false;\n ctx.ui.setStatus(STATUS_KEY, undefined);\n runtime.clearCompletionStatusTimer();\n runtime.clearTerminalDetails();\n runtime.releaseWorkflow();\n runtime.unbindWorkflowSession(shutdownSession);\n });\n\n pi.on(\"session_before_compact\", (event, ctx) => {\n if (!sessionActive) return;\n if (runtime.activeGoal?.status === \"budget_limited\") {\n if ((event as { willRetry?: boolean }).willRetry === true) return { cancel: true as const };\n return;\n }\n if (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n return;\n }\n if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;\n runtime.cancelContinuationWork();\n runtime.persistGoal(runtime.activeGoal);\n runtime.updateStatus(ctx, runtime.activeGoal);\n if (runtime.limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };\n });\n\n pi.on(\"session_compact\", async (event, ctx) => {\n if (!sessionActive) return;\n if (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n runtime.clearGoalRecovery();\n runtime.ensureInactiveGoalContextContract(ctx);\n return;\n }\n\n const restoredState = loadGoalStateFromSession(ctx);\n if (restoredState.goal?.id === runtime.activeGoal.id) {\n runtime.activeGoal = restoredState.goal;\n }\n const usageRecorded = runtime.recordGoalUsage(runtime.activeGoal, ctx);\n if (usageRecorded) {\n runtime.persistGoal(runtime.activeGoal);\n runtime.updateStatus(ctx, runtime.activeGoal);\n }\n if (runtime.limitActiveGoalForBudget(ctx, false)) return;\n const compactedGoalId = runtime.activeGoal.id;\n runtime.ensureGoalContextContract(ctx, runtime.activeGoal);\n if (\n runtime.activeGoal?.id !== compactedGoalId ||\n runtime.activeGoal.status !== \"active\" ||\n !runtime.ownsWorkflow(runtime.activeGoal)\n ) {\n return;\n }\n if (!usageRecorded) return;\n\n const wasPiRetry = runtime.isPiOwnedCompactionRetry(event, runtime.activeGoal.id);\n if (wasPiRetry) return;\n runtime.clearGoalRecoveryForGoal(runtime.activeGoal.id);\n runtime.requestContinuation(runtime.activeGoal);\n // Pi emits session_compact before it clears its manual-compaction controller,\n // so sendUserMessage still rejects inside this hook even when ctx reports idle.\n // Defer one task; threshold compaction retains the intent for agent_settled\n // when Pi is still busy.\n runtime.scheduleContinuationDispatch(ctx, runtime.activeGoal.id);\n });\n\n pi.on(\"input\", (event, ctx) => {\n if (!sessionActive) return;\n if (event.source === \"extension\") {\n if (\n runtime.consumeCancelledGoalPrompt(event.text) ||\n runtime.consumeCancelledContinuationPrompt(event.text) ||\n runtime.consumeStaleOwnedGoalPrompt(event.text)\n ) {\n return { action: \"handled\" as const };\n }\n // Streaming input is queued before its model work starts. Keep owned\n // markers pending for message_start, and track non-goal delivery mode so a\n // steer cannot consume a later follow-up's cleanup protection.\n if (runtime.acceptOwnedInputBoundary(event.text)) return;\n runtime.supersedeOwnedInputCollision(event.text);\n if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n if (event.streamingBehavior === \"steer\" || event.streamingBehavior === \"followUp\") {\n runtime.noteQueuedNonGoalInput(event.text, event.streamingBehavior);\n }\n runtime.clearGoalRecovery();\n return;\n }\n if (/^\\/goal(?:\\s|$)/u.test(event.text.trimStart())) return;\n if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n if (event.streamingBehavior === \"followUp\") {\n runtime.noteQueuedNonGoalInput(event.text, \"followUp\", true);\n return;\n }\n if (event.streamingBehavior === \"steer\") {\n runtime.noteQueuedNonGoalInput(event.text, \"steer\");\n }\n runtime.clearGoalRecovery();\n runtime.clearBudgetWrapUp();\n runtime.clearStaleGoalToolCallBlock();\n runtime.resetActiveSafetyEpoch(ctx);\n });\n\n pi.on(\"message_start\", (event, ctx) => {\n if (!sessionActive) return;\n const message = event.message as { role?: unknown; content?: unknown };\n if (\n message.role === \"assistant\" &&\n runtime.activeGoal?.status === \"paused\" &&\n runtime.guardAbortGoalId === runtime.activeGoal.id\n ) {\n abortCurrentTurn(ctx);\n return;\n }\n if (message.role === \"custom\") {\n if (Reflect.get(message, \"customType\") === GOAL_CONTRACT_MESSAGE_TYPE) return;\n if (runtime.isActiveBudgetWrapUpMessage(message)) return;\n if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n if (runtime.guardAbortGoalId === runtime.activeGoal?.id) {\n runtime.guardAbortGoalId = undefined;\n }\n beginNonGoalFollowUp(ctx, false);\n return;\n }\n if (message.role !== \"user\") return;\n const prompt = Array.isArray(message.content)\n ? message.content\n .filter((part) => part && typeof part === \"object\" && Reflect.get(part, \"type\") === \"text\")\n .map((part) => Reflect.get(part as object, \"text\"))\n .filter((text): text is string => typeof text === \"string\")\n .join(\"\\n\")\n : typeof message.content === \"string\"\n ? message.content\n : \"\";\n const ownedPrompt = runtime.consumeOwnedGoalPrompt(prompt);\n const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(prompt);\n const queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt, !ownedPromptBoundary);\n if (!ownedPrompt) {\n if (queuedNonGoalInput?.behavior === \"followUp\") {\n beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);\n }\n return;\n }\n if (runtime.activeGoal?.id !== ownedPrompt.goalId || !runtime.ownsWorkflow(runtime.activeGoal)) {\n return;\n }\n if (runtime.agentRunGoalId !== undefined && runtime.agentRunGoalId !== ownedPrompt.goalId) {\n runtime.activeGoal.baselineTokens = Math.max(0, currentTokenTotal(ctx) - runtime.activeGoal.tokensUsed);\n }\n runtime.beginAgentRun(ownedPrompt.goalId, \"manual\");\n if (ownedPrompt.resetSafetyEpoch) {\n runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n }\n runtime.persistGoal(runtime.activeGoal);\n runtime.updateStatus(ctx, runtime.activeGoal);\n });\n\n pi.on(\"context\", (event, ctx) => {\n if (!sessionActive) return;\n const keptMessages = event.messages.filter((message) => runtime.keepBudgetWrapUpMessage(message));\n const hasGoalContractHistory =\n keptMessages.some(isGoalContextContract) || runtime.hasGoalContextContractHistory(ctx);\n const messages =\n runtime.activeGoal?.status === \"active\" && runtime.ownsWorkflow(runtime.activeGoal)\n ? reconcileGoalContextContract(keptMessages, runtime.activeGoal)\n : hasGoalContractHistory\n ? reconcileInactiveGoalContextContract(keptMessages)\n : keptMessages;\n if (runtime.activeGoal?.status === \"paused\" && runtime.guardAbortGoalId === runtime.activeGoal.id) {\n // A current custom follow-up clears the guard at message_start. Otherwise,\n // context transformation aborts before the provider adapter receives the signal.\n abortCurrentTurn(ctx);\n }\n if (messages !== keptMessages || keptMessages.length !== event.messages.length) {\n return { messages: messages as typeof event.messages };\n }\n });\n\n pi.on(\"tool_call\", (event, ctx) => {\n if (!sessionActive) return;\n runtime.markAgentToolAttempted();\n if (\n runtime.activeGoal?.status === \"budget_limited\" &&\n runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&\n event.toolName !== \"goal_complete\"\n ) {\n // A blocked tool result would normally trigger another model call. Abort the\n // wrap-up instead so a tool-seeking model cannot create an unbounded loop.\n abortCurrentTurn(ctx);\n return {\n block: true,\n reason: \"Goal token budget is exhausted; only goal_complete is allowed during wrap-up.\",\n };\n }\n if (!runtime.staleGoalToolCallsBlocked) return;\n if (!runtime.activeGoal || !blocksStaleGoalToolCalls(runtime.activeGoal.status)) {\n runtime.clearStaleGoalToolCallBlock();\n return;\n }\n // A blocked tool result would normally trigger another model call. Abort the\n // current turn so a tool-seeking model cannot create an unbounded loop that\n // burns provider quota while the goal is stopped.\n abortCurrentTurn(ctx);\n return {\n block: true,\n reason: \"Blocked stale /goal tool call after the goal stopped or was interrupted.\",\n };\n });\n\n pi.on(\"tool_execution_end\", (_event, ctx) => {\n if (!sessionActive) return;\n if (\n runtime.activeGoal?.status === \"budget_limited\" &&\n runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&\n !runtime.budgetWrapUp.delivered\n ) {\n runtime.queueBudgetWrapUp(ctx, runtime.activeGoal);\n return;\n }\n if (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n return;\n }\n\n // AgentSession persists assistant message_end before tool execution events,\n // so the completed assistant call's usage is authoritative at this boundary.\n if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;\n runtime.persistGoal(runtime.activeGoal);\n runtime.updateStatus(ctx, runtime.activeGoal);\n if (runtime.limitActiveGoalForBudget(ctx, true)) return;\n if (!runtime.goalToolsAvailable()) runtime.pauseGoalForUnavailableTools(ctx);\n });\n\n pi.on(\"before_agent_start\", (event, ctx) => {\n // Custom runs use message_start to establish non-goal ownership.\n if (!sessionActive || event.messageType === \"custom\") return;\n runtime.clearAgentRun();\n // Pi-owned retries emit agent_start directly. Reaching a normal prompt\n // boundary means cleanup no longer owns the next run, so the hard-cap guard\n // must not abort it.\n if (runtime.guardAbortGoalId) runtime.guardAbortGoalId = undefined;\n const goalPrompt = runtime.consumeOwnedGoalPrompt(event.prompt);\n const goalPromptGoalId = goalPrompt?.goalId;\n const continuationGoalId = goalPromptGoalId ? undefined : runtime.markContinuationStarted(event.prompt);\n const ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;\n const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(event.prompt);\n const activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n const activeGoalRecovery = runtime.hasActiveGoalRecovery();\n const queuedNonGoalInput = activeBudgetWrapUp\n ? undefined\n : runtime.consumeQueuedNonGoalInput(\n event.prompt,\n !activeGoalRecovery && ownedPromptGoalId === undefined && !ownedPromptBoundary,\n );\n if (queuedNonGoalInput?.behavior === \"followUp\") {\n beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);\n }\n if (!ownedPromptGoalId && !ownedPromptBoundary) {\n runtime.supersedeOwnedInputCollision(event.prompt);\n if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n }\n if (runtime.activeGoal?.status === \"active\" && !runtime.ownsWorkflow(runtime.activeGoal)) {\n runtime.cancelContinuationWork();\n runtime.clearGoalRecovery();\n abortCurrentTurn(ctx);\n return;\n }\n const runOrigin = continuationGoalId\n ? \"automatic\"\n : activeGoalRecovery && runtime.goalRecovery?.automaticOwner\n ? \"automatic\"\n : \"manual\";\n if (activeBudgetWrapUp && runtime.activeGoal) {\n runtime.beginAgentRun(runtime.activeGoal.id, \"manual\");\n return goalContractBoundaryResult(ctx);\n }\n if (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {\n runtime.beginAgentRun(ownedPromptGoalId, runOrigin);\n if (runtime.activeGoal?.status === \"active\" && !runtime.goalToolsAvailable()) {\n runtime.pauseGoalForUnavailableTools(ctx, false);\n }\n abortCurrentTurn(ctx);\n return;\n }\n if (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n return goalContractBoundaryResult(ctx);\n }\n runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);\n if (!runtime.goalToolsAvailable()) {\n runtime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);\n return goalContractBoundaryResult(ctx);\n }\n if (goalPrompt?.resetSafetyEpoch && goalPromptGoalId === runtime.activeGoal.id) {\n runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n runtime.persistGoal(runtime.activeGoal);\n runtime.updateStatus(ctx, runtime.activeGoal);\n }\n return goalContractBoundaryResult(ctx, runtime.activeGoal);\n });\n\n pi.on(\"agent_start\", (_event, _ctx) => {\n if (!sessionActive) return;\n const activeGoal = runtime.activeGoal;\n if (activeGoal && runtime.guardAbortGoalId === activeGoal.id && activeGoal.status === \"paused\") {\n if (runtime.consumeQueuedNonGoalFollowUpForAgentStart()) {\n runtime.guardAbortGoalId = undefined;\n runtime.clearStaleGoalToolCallBlock();\n runtime.beginAgentRun(null, undefined);\n }\n // Unknown runs defer cleanup until their message/context boundary: custom\n // follow-ups have no input event, while bare recovery is aborted pre-provider.\n return;\n }\n runtime.beginRecoveryRunIfNeeded();\n });\n\n pi.on(\"turn_end\", (event, ctx) => {\n if (!sessionActive) return;\n runtime.recordAutomaticTurn(ctx, event.message);\n // Terminal Goal tools transition state synchronously, but their inactive contract\n // must wait until Pi has persisted the real tool result at this turn boundary.\n if (runtime.activeGoal?.status !== \"active\") {\n runtime.ensureInactiveGoalContextContract(ctx);\n }\n });\n\n pi.on(\"agent_end\", (event, ctx) => {\n if (!sessionActive) return;\n const run = runtime.finishAgentRun();\n if (run.goalId === null) return;\n if (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp()) return;\n if (run.goalId && run.goalId !== runtime.activeGoal?.id) return;\n if (!runtime.activeGoal) return;\n if (runtime.activeGoal.status === \"budget_limited\" && runtime.budgetWrapUp?.goalId === runtime.activeGoal.id) {\n runtime.recordGoalUsage(runtime.activeGoal, ctx);\n runtime.persistGoal(runtime.activeGoal);\n runtime.updateStatus(ctx, runtime.activeGoal);\n runtime.clearBudgetWrapUp();\n return;\n }\n if (runtime.activeGoal.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n return;\n }\n\n const goalId = runtime.activeGoal.id;\n const alreadyAwaitingContinuation = runtime.hasContinuationWorkForGoal(goalId);\n const finalAssistant = findFinalAssistantMessage(event.messages);\n\n if (!alreadyAwaitingContinuation) runtime.activeGoal = incrementGoal(runtime.activeGoal);\n runtime.recordGoalUsage(runtime.activeGoal, ctx);\n\n if (finalAssistant?.stopReason === \"aborted\") {\n runtime.clearGoalRecoveryForGoal(goalId);\n stopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, \"paused\");\n return;\n }\n\n if (finalAssistant?.stopReason === \"error\") {\n if (isRetryableGoalInterruption(finalAssistant)) {\n if (run.origin === \"automatic\" && runtime.enforceAutomaticTurnLimit(ctx, true)) return;\n if (runtime.limitActiveGoalForBudget(ctx, false)) return;\n if (!runtime.goalToolsAvailable()) {\n runtime.pauseGoalForUnavailableTools(ctx);\n return;\n }\n runtime.goalRecovery = {\n goalId,\n kind: isGoalContextOverflow(finalAssistant) ? \"compaction_retry\" : \"provider_retry\",\n automaticOwner: run.origin === \"automatic\",\n errorMessage: finalAssistant.errorMessage,\n };\n runtime.cancelContinuationWork();\n runtime.persistGoal(runtime.activeGoal);\n runtime.updateStatus(ctx, runtime.activeGoal);\n return;\n }\n runtime.clearGoalRecoveryForGoal(goalId);\n stopGoalAfterAgentEnd(\n ctx,\n runtime.activeGoal,\n finalAssistant,\n isUsageLimitedGoalInterruption(finalAssistant) ? \"usage_limited\" : \"blocked\",\n );\n return;\n }\n\n runtime.clearGoalRecoveryForGoal(goalId);\n\n if (runtime.limitActiveGoalForBudget(ctx, false)) return;\n if (!runtime.goalToolsAvailable()) {\n runtime.pauseGoalForUnavailableTools(ctx);\n return;\n }\n if (\n run.origin === \"automatic\" &&\n runtime.recordAutomaticRunProgress(\n ctx,\n goalId,\n event.messages,\n run.toolAttempted || hasAssistantToolCall(event.messages),\n )\n ) {\n return;\n }\n\n runtime.persistGoal(runtime.activeGoal);\n runtime.updateStatus(ctx, runtime.activeGoal);\n\n const currentGoal = runtime.activeGoal;\n if (!currentGoal || currentGoal.id !== goalId || currentGoal.status !== \"active\") return;\n runtime.requestContinuation(currentGoal);\n });\n\n pi.on(\"agent_settled\", (_event, ctx) => {\n if (!sessionActive) return;\n if (runtime.activeGoal?.status === \"active\" && !runtime.ownsWorkflow(runtime.activeGoal)) {\n runtime.cancelContinuationWork();\n runtime.clearGoalRecovery();\n runtime.clearSettledSafetyTracking();\n return;\n }\n runtime.finalizeSettledRecovery(ctx);\n const resumedWait = runtime.dispatchDueGoalWait(ctx);\n if (!resumedWait) runtime.dispatchContinuationIfSettled(ctx);\n runtime.clearSettledSafetyTracking();\n });\n\n function goalContractBoundaryResult(ctx: StatusContext, goal?: ActiveGoal) {\n const message = runtime.goalContextContractForPrompt(ctx, goal);\n return message ? { message } : undefined;\n }\n\n function beginNonGoalFollowUp(ctx: StatusContext, resetSafetyEpoch: boolean) {\n runtime.clearGoalRecovery();\n runtime.clearStaleGoalToolCallBlock();\n if (resetSafetyEpoch) runtime.clearBudgetWrapUp();\n const activeGoalId = runtime.activeGoal?.status === \"active\" ? runtime.activeGoal.id : undefined;\n runtime.beginAgentRun(activeGoalId ?? null, activeGoalId ? \"manual\" : undefined);\n if (resetSafetyEpoch && activeGoalId) runtime.resetActiveSafetyEpoch(ctx);\n }\n\n function stopGoalAfterAgentEnd(\n ctx: StatusContext,\n goal: ActiveGoal,\n assistant: AssistantMessageLike,\n status: \"paused\" | \"blocked\" | \"usage_limited\",\n ) {\n const stoppedGoal = runtime.stopActiveGoal(ctx, {\n kind: \"agent_interruption\",\n expectedGoalId: goal.id,\n status,\n reason: assistant.errorMessage ?? `goal ${status} after agent interruption`,\n });\n if (!stoppedGoal) return;\n\n const details = assistant.errorMessage ? ` (${truncateNotification(assistant.errorMessage)})` : \"\";\n if (status === \"paused\") {\n notifyTerminal(ctx.ui, `Goal paused after interruption${details}. Run /goal resume to continue.`, \"warning\");\n return;\n }\n if (status === \"usage_limited\") {\n notifyTerminal(\n ctx.ui,\n `Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,\n \"warning\",\n );\n return;\n }\n notifyTerminal(\n ctx.ui,\n `Goal blocked after agent error${details}. Resolve the blocker or run /goal resume to retry.`,\n \"warning\",\n );\n }\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { validateObjective } from \"./command.js\";\nimport type { GoalCommandController } from \"./commands.js\";\nimport {\n formatError,\n type GoalRuntime,\n type GoalStateSnapshot,\n isTerminalGoalStatus,\n type 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 = GoalStateSnapshot[\"status\"];\nexport type GoalRunErrorCode =\n | \"RPC_DISABLED\"\n | \"INVALID_REQUEST\"\n | \"NO_ACTIVE_SESSION\"\n | \"RUN_ID_IN_USE\"\n | \"RUN_NOT_FOUND\"\n | \"GOAL_ALREADY_EXISTS\"\n | \"ACTIVATION_FAILED\"\n | \"SUPERSEDED\";\n\nexport type GoalRunEvent =\n | {\n type: \"state\";\n runId: string;\n goalId: string;\n status: GoalRunStatus;\n summary?: string;\n reason?: string;\n }\n | {\n type: \"error\";\n runId: string;\n operation: \"start\" | \"cancel\";\n error: { code: GoalRunErrorCode; message: string };\n };\n\ninterface GoalRunStartPayload {\n runId: string;\n objective: string;\n tokenBudget?: number;\n}\n\ninterface BoundSession {\n generation: number;\n ctx: StatusContext;\n}\n\ninterface ManagedRun {\n runId: string;\n generation: number;\n goalId?: string;\n lastStatus?: GoalRunStatus;\n closed: boolean;\n cancelRequested: boolean;\n cancelReason?: string;\n}\n\nexport function goalRunEventChannel(runId: string) {\n return `pi-goal:event:${runId}`;\n}\n\nfunction isPayloadRecord(data: unknown): data is object {\n if (!data || typeof data !== \"object\") return false;\n try {\n return !Array.isArray(data);\n } catch {\n return false;\n }\n}\n\nfunction readPayloadProperty(\n data: object,\n key: \"runId\" | \"objective\" | \"tokenBudget\" | \"reason\",\n): { ok: true; value: unknown } | { ok: false } {\n try {\n return { ok: true, value: Reflect.get(data, key) };\n } catch {\n return { ok: false };\n }\n}\n\nfunction parseRunId(data: unknown): string | undefined {\n if (!isPayloadRecord(data)) return undefined;\n const runId = readPayloadProperty(data, \"runId\");\n return runId.ok && typeof runId.value === \"string\" && RUN_ID_PATTERN.test(runId.value) ? runId.value : undefined;\n}\n\nfunction currentActiveGoal(runtime: GoalRuntime) {\n return runtime.activeGoal;\n}\n\nfunction parseStartPayload(data: unknown): string | Omit<GoalRunStartPayload, \"runId\"> {\n if (!isPayloadRecord(data)) return \"start payload must be an object\";\n const objectiveValue = readPayloadProperty(data, \"objective\");\n if (!objectiveValue.ok || typeof objectiveValue.value !== \"string\") {\n return \"objective must be a string\";\n }\n const objective = objectiveValue.value.trim();\n const objectiveError = validateObjective(objective);\n if (objectiveError) return objectiveError;\n const tokenBudgetValue = readPayloadProperty(data, \"tokenBudget\");\n if (\n !tokenBudgetValue.ok ||\n (tokenBudgetValue.value !== undefined &&\n (typeof tokenBudgetValue.value !== \"number\" ||\n !Number.isFinite(tokenBudgetValue.value) ||\n !Number.isSafeInteger(tokenBudgetValue.value) ||\n tokenBudgetValue.value <= 0))\n ) {\n return \"tokenBudget must be a positive integer\";\n }\n return { objective, tokenBudget: tokenBudgetValue.value as number | undefined };\n}\n\nfunction parseCancelReason(data: unknown): string | undefined | { error: string } {\n if (!isPayloadRecord(data)) return { error: \"cancel payload must be an object\" };\n const reasonValue = readPayloadProperty(data, \"reason\");\n if (!reasonValue.ok || (reasonValue.value !== undefined && typeof reasonValue.value !== \"string\")) {\n return { error: \"reason must be a string\" };\n }\n if (reasonValue.value === undefined) return undefined;\n const reason = reasonValue.value.trim();\n if (reason.length > MAX_CANCEL_REASON_LENGTH) {\n return { error: `reason must be at most ${MAX_CANCEL_REASON_LENGTH} characters` };\n }\n return reason || undefined;\n}\n\nexport class GoalRunController {\n private readonly runtime: GoalRuntime;\n private readonly commands: GoalCommandController;\n private generation = 0;\n private session?: BoundSession;\n private run?: ManagedRun;\n private readonly usedRunIds = new Set<string>();\n\n constructor(runtime: GoalRuntime, commands: GoalCommandController) {\n this.runtime = runtime;\n this.commands = commands;\n this.runtime.setGoalStateSink((snapshot) => this.handleGoalState(snapshot));\n }\n\n register(pi: ExtensionAPI) {\n pi.events.on(GOAL_RUN_START_CHANNEL, (data) => this.handleStart(data));\n pi.events.on(GOAL_RUN_CANCEL_CHANNEL, (data) => {\n this.handleCancel(data);\n });\n }\n\n bindSession(ctx: StatusContext) {\n this.generation += 1;\n this.session = { generation: this.generation, ctx };\n this.closeCurrentRun();\n this.usedRunIds.clear();\n }\n\n unbindSession() {\n this.generation += 1;\n this.session = undefined;\n this.closeCurrentRun();\n this.usedRunIds.clear();\n }\n\n private async handleStart(data: unknown) {\n const runId = parseRunId(data);\n if (!runId) return;\n const session = this.session;\n if (!session) {\n this.emitError(runId, \"start\", \"NO_ACTIVE_SESSION\", \"No active pi-goal session.\");\n return;\n }\n if (!this.runtime.settings.rpc.enabled) {\n this.emitError(runId, \"start\", \"RPC_DISABLED\", \"Managed run RPC is disabled.\");\n return;\n }\n if (this.usedRunIds.has(runId)) {\n this.emitError(runId, \"start\", \"RUN_ID_IN_USE\", \"runId was already used in this session.\");\n return;\n }\n const parsed = parseStartPayload(data);\n if (typeof parsed === \"string\") {\n this.emitError(runId, \"start\", \"INVALID_REQUEST\", parsed);\n return;\n }\n if (this.session !== session || this.generation !== session.generation) {\n this.emitError(runId, \"start\", \"SUPERSEDED\", \"The pi-goal session changed while validating the request.\");\n return;\n }\n if (this.usedRunIds.has(runId)) {\n this.emitError(runId, \"start\", \"RUN_ID_IN_USE\", \"runId was already used in this session.\");\n return;\n }\n if (this.runtime.activeGoal || (this.run && !this.run.closed)) {\n this.emitError(runId, \"start\", \"GOAL_ALREADY_EXISTS\", \"A Goal already exists.\");\n return;\n }\n\n const run: ManagedRun = {\n runId,\n generation: session.generation,\n closed: false,\n cancelRequested: false,\n };\n this.run = run;\n this.usedRunIds.add(runId);\n\n try {\n const activation = await this.commands.startGoal(\n parsed.objective,\n parsed.tokenBudget,\n session.ctx,\n (goal) => {\n if (this.ownsRun(run, session.generation)) run.goalId = goal.id;\n },\n () => this.ownsRun(run, session.generation),\n );\n if (activation?.kind === \"busy\" && this.ownsRun(run, session.generation)) {\n this.closeCurrentRun();\n this.emitError(\n runId,\n \"start\",\n \"ACTIVATION_FAILED\",\n \"Another workflow is active in this session. End it before starting Goal.\",\n );\n return;\n }\n } catch (error) {\n if (this.ownsRun(run, session.generation)) {\n this.closeCurrentRun();\n this.emitError(runId, \"start\", \"ACTIVATION_FAILED\", `Goal activation failed: ${formatError(error)}`);\n }\n return;\n }\n\n if (!this.ownsRun(run, session.generation)) return;\n if (!run.goalId) {\n this.closeCurrentRun();\n this.emitError(runId, \"start\", \"ACTIVATION_FAILED\", \"Goal activation did not create a Goal.\");\n return;\n }\n if (currentActiveGoal(this.runtime)?.id !== run.goalId) {\n this.closeCurrentRun();\n this.emitError(runId, \"start\", \"SUPERSEDED\", \"The managed Goal was superseded.\");\n return;\n }\n if (run.cancelRequested) this.cancelActiveRun(run, session, run.cancelReason);\n }\n\n private handleCancel(data: unknown) {\n const runId = parseRunId(data);\n if (!runId) return;\n const session = this.session;\n if (!session) {\n this.emitError(runId, \"cancel\", \"NO_ACTIVE_SESSION\", \"No active pi-goal session.\");\n return;\n }\n const reason = parseCancelReason(data);\n if (reason && typeof reason === \"object\") {\n this.emitError(runId, \"cancel\", \"INVALID_REQUEST\", reason.error);\n return;\n }\n const run = this.run;\n if (!run || run.closed || run.runId !== runId || run.generation !== session.generation) {\n this.emitError(runId, \"cancel\", \"RUN_NOT_FOUND\", \"No active managed run matches runId.\");\n return;\n }\n if (!run.goalId) {\n run.cancelRequested = true;\n run.cancelReason = reason;\n return;\n }\n this.cancelActiveRun(run, session, reason);\n }\n\n private cancelActiveRun(run: ManagedRun, session: BoundSession, reason: string | undefined) {\n if (!this.ownsRun(run, session.generation)) return;\n const goal = this.runtime.activeGoal;\n if (!goal || goal.id !== run.goalId) {\n this.closeCurrentRun();\n this.emitError(run.runId, \"cancel\", \"SUPERSEDED\", \"The managed Goal was superseded.\");\n return;\n }\n if (goal.status !== \"active\") {\n this.closeCurrentRun();\n this.emitError(run.runId, \"cancel\", \"RUN_NOT_FOUND\", \"The managed run is no longer active.\");\n return;\n }\n this.runtime.setTerminalReason(goal.id, reason ?? \"goal cancelled by managed run\");\n this.commands.pauseGoal(session.ctx);\n }\n\n private handleGoalState(snapshot: GoalStateSnapshot) {\n const run = this.run;\n if (!run || run.closed || !run.goalId) return;\n if (run.goalId !== snapshot.goalId) {\n if (currentActiveGoal(this.runtime)?.id !== snapshot.goalId) return;\n this.publishStateEvent(run, {\n goalId: run.goalId,\n status: \"cleared\",\n reason: \"managed Goal superseded by another Goal\",\n });\n return;\n }\n if (run.lastStatus === snapshot.status) return;\n this.publishStateEvent(run, snapshot);\n }\n\n private publishStateEvent(\n run: ManagedRun,\n snapshot: Pick<GoalStateSnapshot, \"goalId\" | \"status\" | \"summary\" | \"reason\">,\n ) {\n const status = snapshot.status;\n run.lastStatus = status;\n const event: GoalRunEvent = {\n type: \"state\",\n runId: run.runId,\n goalId: snapshot.goalId,\n status,\n ...(snapshot.summary ? { summary: snapshot.summary } : {}),\n ...(snapshot.reason ? { reason: snapshot.reason } : {}),\n };\n if (!isTerminalGoalStatus(status)) {\n this.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);\n return;\n }\n\n run.closed = true;\n this.run = undefined;\n const generation = run.generation;\n // Active stays synchronous so a listener can cancel before kickoff. Terminal\n // publication waits until the transition finishes, preventing listener work\n // from being overwritten by the old transition's remaining UI or cleanup.\n queueMicrotask(() => {\n if (this.generation !== generation) return;\n this.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);\n });\n }\n\n private emitError(runId: string, operation: \"start\" | \"cancel\", code: GoalRunErrorCode, message: string) {\n this.runtime.pi.events.emit(goalRunEventChannel(runId), {\n type: \"error\",\n runId,\n operation,\n error: { code, message },\n } satisfies GoalRunEvent);\n }\n\n private ownsRun(run: ManagedRun, generation: number) {\n return this.session?.generation === generation && this.generation === generation && this.run === run && !run.closed;\n }\n\n private closeCurrentRun() {\n if (this.run) this.run.closed = true;\n this.run = undefined;\n }\n}\n", "import {\n DEFAULT_MAX_BYTES,\n DEFAULT_MAX_LINES,\n defineTool,\n type ExtensionAPI,\n getMarkdownTheme,\n truncateHead,\n} from \"@earendil-works/pi-coding-agent\";\nimport { Markdown } from \"@earendil-works/pi-tui\";\nimport { Type } from \"typebox\";\nimport { notifyTerminal, safeTerminalText } from \"./errors.js\";\nimport {\n formatStatus,\n GOAL_BLOCKED_TOOL,\n GOAL_COMPLETE_TOOL,\n GOAL_WAIT_TOOL,\n type GoalRuntime,\n goalIdRejectionReason,\n isContradictoryCompletionSummary,\n MAX_GOAL_ID_LENGTH,\n STATUS_KEY,\n transitionGoal,\n truncateNotification,\n} from \"./runtime.js\";\nimport {\n createGoalWait,\n MAX_GOAL_WAIT_DELAY_MS,\n MAX_GOAL_WAIT_REASON_LENGTH,\n MIN_GOAL_WAIT_DELAY_MS,\n resolveGoalWaitDelay,\n} from \"./wait.js\";\n\ninterface GoalCompleteDetails {\n goal: string;\n goal_id: string;\n summary: string;\n}\n\ninterface GoalBlockedDetails {\n goal: string;\n goal_id: string;\n reason: string;\n evidence: string;\n repeated_turns: number;\n}\n\ninterface GoalWaitDetails {\n goal: string;\n goal_id: string;\n reason: string;\n requested_resume_after_ms?: number;\n resume_after_ms?: number;\n resume_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 const goalCompleteTool = defineTool({\n name: GOAL_COMPLETE_TOOL,\n label: \"Goal Complete\",\n description:\n \"Mark an active /goal complete only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and every requirement is verified. Tool visibility alone does not activate Goal mode. Never call for ordinary work, partial progress, blockers, failures, or unverified work.\",\n parameters: Type.Object({\n goal_id: Type.String({\n minLength: 1,\n maxLength: MAX_GOAL_ID_LENGTH,\n description:\n \"The exact goal_id shown in the current active /goal prompt. Used only to reject stale completion calls from older turns.\",\n }),\n summary: Type.String({\n minLength: 1,\n maxLength: MAX_COMPLETION_SUMMARY_LENGTH,\n description:\n \"State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work.\",\n }),\n }),\n renderResult(result) {\n return renderGoalCompletion(result);\n },\n async execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n const completedGoal = runtime.activeGoal;\n const goal = completedGoal?.text ?? \"unknown goal\";\n const requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n const summary = typeof params.summary === \"string\" ? params.summary.trim() : \"\";\n\n if (!completedGoal) {\n const rejection = \"Goal completion rejected: no active goal.\";\n notifyTerminal(ctx.ui, rejection, \"warning\");\n\n return {\n content: toolContent(rejection),\n details: completionDetails(goal, requestedGoalId, summary),\n };\n }\n const completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n if (completedGoal.status === \"active\" && !runtime.ownsWorkflow(completedGoal)) {\n const rejection = \"Goal completion rejected: active Goal no longer owns its workflow.\";\n notifyTerminal(ctx.ui, rejection, \"warning\");\n return {\n content: toolContent(rejection),\n details: completionDetails(goal, requestedGoalId, summary),\n };\n }\n if (!runtime.canRecordGoalUsage() && !completingDuringBudgetWrapUp) {\n const rejection = \"Goal completion rejected: current run does not own the active goal.\";\n notifyTerminal(ctx.ui, rejection, \"warning\");\n return {\n content: toolContent(rejection),\n details: completionDetails(goal, requestedGoalId, summary),\n };\n }\n const staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);\n if (staleGoalRejection) {\n const rejection = `Goal completion rejected: ${staleGoalRejection}.`;\n notifyTerminal(ctx.ui, rejection, \"warning\");\n if (completingDuringBudgetWrapUp) {\n runtime.recordGoalUsage(completedGoal, ctx);\n runtime.persistGoal(completedGoal);\n runtime.updateStatus(ctx, completedGoal);\n runtime.clearBudgetWrapUp();\n }\n\n return {\n content: toolContent(rejection),\n details: completionDetails(goal, requestedGoalId, summary),\n terminate: completingDuringBudgetWrapUp || undefined,\n };\n }\n if (completedGoal.status !== \"active\" && !completingDuringBudgetWrapUp) {\n const rejection = `Goal completion rejected: goal is ${completedGoal.status}, not active.`;\n notifyTerminal(ctx.ui, rejection, \"warning\");\n\n return {\n content: toolContent(rejection),\n details: completionDetails(goal, requestedGoalId, summary),\n };\n }\n\n const rejectionReason = !summary\n ? \"summary is empty\"\n : summary.length > MAX_COMPLETION_SUMMARY_LENGTH\n ? \"summary is too long\"\n : isContradictoryCompletionSummary(summary)\n ? \"summary says the goal is not complete\"\n : undefined;\n if (rejectionReason) {\n runtime.recordGoalUsage(completedGoal, ctx);\n runtime.persistGoal(completedGoal);\n runtime.updateStatus(ctx, completedGoal);\n const rejection = `Goal completion rejected: ${rejectionReason}.`;\n notifyTerminal(ctx.ui, rejection, \"warning\");\n if (completingDuringBudgetWrapUp) runtime.clearBudgetWrapUp();\n\n return {\n content: toolContent(rejection),\n details: completionDetails(goal, requestedGoalId, summary),\n terminate: completingDuringBudgetWrapUp || undefined,\n };\n }\n\n runtime.clearGoalWaitTimer();\n runtime.activeGoal = transitionGoal(completedGoal, \"complete\");\n runtime.setCompletionSummary(runtime.activeGoal.id, summary);\n runtime.recordGoalUsage(runtime.activeGoal, ctx);\n runtime.persistGoal(runtime.activeGoal);\n\n ctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));\n runtime.clearCompletedGoal(ctx);\n runtime.showCompletionStatus(ctx);\n notifyTerminal(ctx.ui, `Goal complete: ${goal}`, \"info\");\n\n return {\n content: toolContent(`Goal complete: ${summary}`),\n details: completionDetails(goal, requestedGoalId, summary),\n terminate: true,\n };\n },\n });\n\n const goalBlockedTool = defineTool({\n name: GOAL_BLOCKED_TOOL,\n label: \"Goal Blocked\",\n description:\n \"Stop an active /goal only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and the same evidenced external blocker recurred for at least three consecutive Goal turns. Tool visibility alone does not activate Goal mode. Never call for ordinary clarification, uncertainty, incomplete work, or recoverable failures.\",\n parameters: Type.Object({\n goal_id: Type.String({\n minLength: 1,\n maxLength: MAX_GOAL_ID_LENGTH,\n description: \"The exact goal_id shown in the current active /goal prompt.\",\n }),\n reason: Type.String({\n minLength: 1,\n maxLength: MAX_BLOCKER_REASON_LENGTH,\n description: \"The specific user or external action required to unblock the goal.\",\n }),\n evidence: Type.String({\n minLength: 1,\n maxLength: MAX_BLOCKER_EVIDENCE_LENGTH,\n description: \"Concrete evidence from the repeated attempts that proves the impasse.\",\n }),\n repeated_turns: Type.Integer({\n minimum: 3,\n description: \"Number of separate turns spent trying to resolve this same blocker.\",\n }),\n }),\n async execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n const blockedGoal = runtime.activeGoal;\n const goal = blockedGoal?.text ?? \"unknown goal\";\n const requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n const reason = typeof params.reason === \"string\" ? params.reason.trim() : \"\";\n const evidence = typeof params.evidence === \"string\" ? params.evidence.trim() : \"\";\n const repeatedTurns = typeof params.repeated_turns === \"number\" ? params.repeated_turns : Number.NaN;\n const reject = (rejectionReason: string, terminate = false) => {\n const rejection = `goal_blocked rejected: ${rejectionReason}.`;\n notifyTerminal(ctx.ui, rejection, \"warning\");\n return {\n content: toolContent(rejection),\n details: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),\n ...(terminate ? { terminate: true as const } : {}),\n };\n };\n\n if (!blockedGoal) return reject(\"no active goal\");\n if (!runtime.canRecordGoalUsage()) {\n return reject(\"current run does not own the active goal\");\n }\n const staleGoalRejection = goalIdRejectionReason(blockedGoal, requestedGoalId);\n if (staleGoalRejection) return reject(staleGoalRejection);\n if (blockedGoal.status !== \"active\") {\n return reject(`goal is ${blockedGoal.status}, not active`);\n }\n if (!runtime.ownsWorkflow(blockedGoal)) return reject(\"active Goal no longer owns its workflow\");\n if (!reason) return reject(\"reason is empty\");\n if (reason.length > MAX_BLOCKER_REASON_LENGTH) return reject(\"reason is too long\");\n if (!evidence) return reject(\"evidence is empty\");\n if (evidence.length > MAX_BLOCKER_EVIDENCE_LENGTH) return reject(\"evidence is too long\");\n if (!Number.isInteger(repeatedTurns)) return reject(\"repeated_turns must be a whole number\");\n if (repeatedTurns < 3) return reject(\"repeated_turns must be at least 3\");\n\n const stoppedGoal = runtime.stopActiveGoal(ctx, {\n kind: \"blocker_report\",\n expectedGoalId: blockedGoal.id,\n reason,\n });\n if (!stoppedGoal) return reject(\"active goal changed before blocker transition\");\n notifyTerminal(ctx.ui, `Goal blocked: ${truncateNotification(reason)}`, \"warning\");\n\n return {\n content: toolContent(`Goal blocked: ${reason}`),\n details: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),\n terminate: true,\n };\n },\n });\n\n const goalWaitTool = defineTool({\n name: GOAL_WAIT_TOOL,\n label: \"Goal Wait\",\n description: `Keep an active /goal quiet only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and progress depends on an arranged external wake event or one safety deadline. Tool visibility alone does not activate Goal mode. Call goal_wait alone. Requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms. Never call for ordinary unfinished work.`,\n parameters: Type.Object({\n goal_id: Type.String({\n minLength: 1,\n maxLength: MAX_GOAL_ID_LENGTH,\n description: \"The exact goal_id shown in the current active /goal prompt.\",\n }),\n reason: Type.String({\n minLength: 1,\n maxLength: MAX_GOAL_WAIT_REASON_LENGTH,\n description: \"Why the goal is waiting and which external event should wake it.\",\n }),\n resume_after_ms: Type.Optional(\n Type.Integer({\n minimum: 1,\n maximum: MAX_GOAL_WAIT_DELAY_MS,\n description: `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 }),\n ),\n }),\n async execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n const activeGoal = runtime.activeGoal;\n const goal = activeGoal?.text ?? \"unknown goal\";\n const requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n const reason = typeof params.reason === \"string\" ? params.reason.trim() : \"\";\n const resumeAfterMs = typeof params.resume_after_ms === \"number\" ? params.resume_after_ms : undefined;\n const reject = (rejectionReason: string) => {\n const rejection = `goal_wait rejected: ${rejectionReason}.`;\n notifyTerminal(ctx.ui, rejection, \"warning\");\n return {\n content: toolContent(rejection),\n details: waitDetails(goal, requestedGoalId, reason, resumeAfterMs),\n };\n };\n\n if (!activeGoal) return reject(\"no active goal\");\n if (!runtime.canRecordGoalUsage()) {\n return reject(\"current run does not own the active goal\");\n }\n const staleGoalRejection = goalIdRejectionReason(activeGoal, requestedGoalId);\n if (staleGoalRejection) return reject(staleGoalRejection);\n if (activeGoal.status !== \"active\") {\n return reject(`goal is ${activeGoal.status}, not active`);\n }\n if (!runtime.ownsWorkflow(activeGoal)) return reject(\"active Goal no longer owns its workflow\");\n if (activeGoal.waiting) return reject(\"goal is already waiting\");\n if (!reason) return reject(\"reason is empty\");\n if (reason.length > MAX_GOAL_WAIT_REASON_LENGTH) return reject(\"reason is too long\");\n if (\n resumeAfterMs !== undefined &&\n (!Number.isInteger(resumeAfterMs) || resumeAfterMs < 1 || resumeAfterMs > MAX_GOAL_WAIT_DELAY_MS)\n ) {\n return reject(`resume_after_ms must be a whole number from 1 to ${MAX_GOAL_WAIT_DELAY_MS}`);\n }\n\n const { requestedMs, effectiveMs } = resolveGoalWaitDelay(resumeAfterMs);\n const waiting = createGoalWait(reason, resumeAfterMs);\n const waitingGoal = runtime.enterGoalWait(ctx, activeGoal.id, waiting);\n if (!waitingGoal) return reject(\"active goal changed before waiting transition\");\n const clamped = requestedMs !== undefined && effectiveMs !== requestedMs;\n notifyTerminal(ctx.ui, `Goal waiting: ${truncateNotification(reason)}`, \"info\");\n return {\n content: toolContent(\n clamped\n ? `Goal waiting: ${reason}\\nRequested resume_after_ms ${requestedMs} was clamped to ${effectiveMs}.`\n : `Goal waiting: ${reason}`,\n ),\n details: waitDetails(\n goal,\n requestedGoalId,\n reason,\n effectiveMs,\n waiting.resumeAt,\n clamped ? requestedMs : undefined,\n ),\n terminate: true,\n };\n },\n });\n\n pi.registerTool(goalCompleteTool);\n pi.registerTool(goalBlockedTool);\n pi.registerTool(goalWaitTool);\n}\n\ninterface GoalCompletionRenderResult {\n content: Array<{ type: string; text?: string }>;\n details?: unknown;\n}\n\nexport function goalCompletionMarkdown(result: GoalCompletionRenderResult) {\n const content = result.content\n .filter((block) => block.type === \"text\" && typeof block.text === \"string\")\n .map((block) => block.text)\n .join(\"\\n\")\n .trim();\n const completionPrefix = \"Goal complete:\";\n if (!content.startsWith(completionPrefix)) return content;\n\n const details = result.details;\n const summary =\n details && typeof details === \"object\" && \"summary\" in details && typeof details.summary === \"string\"\n ? details.summary\n : content.slice(completionPrefix.length);\n const safeSummary = safeTerminalText(summary);\n return safeSummary ? `**Goal complete**\\n\\n${safeSummary}` : \"**Goal complete**\";\n}\n\nexport function renderGoalCompletion(result: GoalCompletionRenderResult) {\n return new Markdown(goalCompletionMarkdown(result), 0, 0, getMarkdownTheme());\n}\n\nfunction toolContent(text: string) {\n return [\n {\n type: \"text\" as const,\n text: truncateHead(safeTerminalText(text), {\n maxBytes: DEFAULT_MAX_BYTES,\n maxLines: DEFAULT_MAX_LINES,\n }).content,\n },\n ];\n}\n\nfunction completionDetails(goal: string, goalId: string, summary: string): GoalCompleteDetails {\n return {\n goal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n summary: summary.slice(0, MAX_COMPLETION_SUMMARY_LENGTH),\n };\n}\n\nfunction blockerDetails(\n goal: string,\n goalId: string,\n reason: string,\n evidence: string,\n repeatedTurns: number,\n): GoalBlockedDetails {\n return {\n goal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n reason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),\n evidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),\n repeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,\n };\n}\n\nfunction waitDetails(\n goal: string,\n goalId: string,\n reason: string,\n resumeAfterMs: number | undefined,\n resumeAt?: number,\n requestedResumeAfterMs?: number,\n): GoalWaitDetails {\n return {\n goal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n reason: reason.slice(0, MAX_GOAL_WAIT_REASON_LENGTH),\n ...(requestedResumeAfterMs === undefined ? {} : { requested_resume_after_ms: requestedResumeAfterMs }),\n ...(resumeAfterMs === undefined ? {} : { resume_after_ms: resumeAfterMs }),\n ...(resumeAt === undefined ? {} : { resume_at: resumeAt }),\n };\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 settingsPath?: string;\n}\n\nfunction registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {\n const runtime = new GoalRuntime(pi);\n const commands = new GoalCommandController(runtime);\n const runController = new GoalRunController(runtime, commands);\n\n // Keep registration order explicit: managed-run bus listeners exist before tools,\n // command routing, and session lifecycle bind the per-factory runtime.\n runController.register(pi);\n registerGoalTools(pi, runtime);\n registerGoalCommand(pi, runtime, commands, options);\n registerGoalLifecycle(pi, runtime, runController, options);\n}\n\nexport default function goal(pi: ExtensionAPI, options: GoalOptions = {}) {\n registerGoalRuntime(pi, options);\n}\n\nexport {\n assistantUsageTokens,\n cumulativeAssistantTokens,\n formatDuration,\n formatTokenCount,\n} from \"./accounting.js\";\n\nexport {\n completeGoalArguments,\n parseCommand,\n parseTokenBudget,\n validateObjective,\n} from \"./command.js\";\n\nexport { buildGoalSystemPrompt } from \"./prompts.js\";\n\nexport {\n findFinalAssistantMessage,\n formatStatus,\n isContradictoryCompletionSummary,\n isRetryableGoalInterruption,\n isUsageLimitedGoalInterruption,\n} from \"./runtime.js\";\n"],
|
|
5
|
-
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,SAAS,oBACd,IACA,SACA,UACA,UAA0C,CAAC,GAC3C;AACA,QAAM,kBAAkB,mBAAmB,QAAQ,oBAAoB,MAAM,OAAO,2BAAW,EAAE;AACjG,QAAM,mBAAmB,mBAAmB,QAAQ,qBAAqB,MAAM,OAAO,kCAAkB,EAAE;AAE1G,KAAG,gBAAgB,QAAQ;AAAA,IACzB,aAAa;AAAA,IACb,wBAAwB,CAAC,WAAW,sBAAsB,MAAM;AAAA,IAChE,SAAS,OAAO,MAAM,QAAQ;AAC5B,UAAI;AACF,YAAI,QAAQ,wBAAwB,KAAK,sBAAsB,IAAI,GAAG;AACpE,oCAA0B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,eACA,UACA,wBACiB;AACjB,SAAO;AAAA,IACL,MAAMA,MAAK,MAAM,GAAG,oBAAoB;AAAA,IACxC,SAAS,OAAO,MAAM,GAAG,kBAAkB;AAAA,IAC3C,QAAQ,OAAO,MAAM,GAAG,2BAA2B;AAAA,IACnD,GAAI,2BAA2B,SAAY,CAAC,IAAI,EAAE,2BAA2B,uBAAuB;AAAA,IACpG,GAAI,kBAAkB,SAAY,CAAC,IAAI,EAAE,iBAAiB,cAAc;AAAA,IACxE,GAAI,aAAa,SAAY,CAAC,IAAI,EAAE,WAAW,SAAS;AAAA,EAC1D;AACF;;;AC9ZA,SAAS,oBAAoB,IAAkB,UAAuB,CAAC,GAAG;AACxE,QAAM,UAAU,IAAI,YAAY,EAAE;AAClC,QAAM,WAAW,IAAI,sBAAsB,OAAO;AAClD,QAAM,gBAAgB,IAAI,kBAAkB,SAAS,QAAQ;AAI7D,gBAAc,SAAS,EAAE;AACzB,oBAAkB,IAAI,OAAO;AAC7B,sBAAoB,IAAI,SAAS,UAAU,OAAO;AAClD,wBAAsB,IAAI,SAAS,eAAe,OAAO;AAC3D;AAEe,SAAR,KAAsB,IAAkB,UAAuB,CAAC,GAAG;AACxE,sBAAoB,IAAI,OAAO;AACjC;",
|
|
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 { isStaleContextError, 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 settingsPath?: string;\n loadGoalManager?: () => Promise<GoalManagerModule>;\n loadGoalSettings?: () => Promise<GoalSettingsModule>;\n}\n\nexport function registerGoalCommand(\n pi: ExtensionAPI,\n runtime: GoalRuntime,\n commands: GoalCommandController,\n options: GoalCommandRegistrationOptions = {},\n) {\n const loadGoalManager = cachedModuleLoader(options.loadGoalManager ?? (() => import(\"./menu.js\")));\n const loadGoalSettings = cachedModuleLoader(options.loadGoalSettings ?? (() => import(\"./settings-ui.js\")));\n\n pi.registerCommand(\"goal\", {\n description: \"Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>\",\n getArgumentCompletions: (prefix) => completeGoalArguments(prefix),\n handler: async (args, ctx) => {\n try {\n if (runtime.hasLegacyQueueInterface() && isRemovedQueueCommand(args)) {\n reportRemovedQueueCommand(ctx, runtime);\n return;\n }\n const result = parseCommand(args);\n if (typeof result === \"string\") {\n reportCommandError(result, ctx);\n return;\n }\n if (result.kind === \"show\" && args.trim() === \"\") {\n const menuIsCurrent = captureMenuOwnership(runtime);\n let managerModule: GoalManagerModule;\n try {\n managerModule = await loadGoalManager();\n } catch (error) {\n if (!menuIsCurrent()) return;\n throw error;\n }\n if (!menuIsCurrent()) return;\n const { showGoalManager } = managerModule;\n await showGoalManager(runtime, commands, ctx, async (menuCtx, target) => {\n const settingsAreCurrent = captureMenuOwnership(runtime);\n let settingsModule: GoalSettingsModule;\n try {\n settingsModule = await loadGoalSettings();\n } catch (error) {\n if (!settingsAreCurrent()) return;\n throw error;\n }\n if (!settingsAreCurrent()) return;\n const { showGoalSettings } = settingsModule;\n await showGoalSettings(runtime, menuCtx, {\n settingsPath: options.settingsPath,\n initialScreen: target,\n });\n });\n return;\n }\n switch (result.kind) {\n case \"show\":\n commands.showGoal(ctx);\n return;\n case \"pause\":\n commands.pauseGoal(ctx);\n return;\n case \"resume\":\n await commands.resumeGoal(ctx);\n return;\n case \"clear\":\n commands.clearGoal(ctx);\n return;\n case \"edit\":\n await commands.editGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n return;\n case \"start\":\n await commands.startGoal(result.objective ?? \"\", result.tokenBudget, ctx);\n return;\n }\n } catch (error) {\n // Pi invalidates command ctx when the session is replaced while a\n // confirmation or menu await is still in flight. The dead session's\n // command result is discarded, so a stale context is not an error.\n if (isStaleContextError(error)) return;\n throw error;\n }\n },\n });\n}\n\nfunction reportCommandError(message: string, ctx: ExtensionCommandContext) {\n const safeMessage = safeTerminalText(message);\n if (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(safeMessage);\n notifyTerminal(ctx.ui, safeMessage, \"warning\");\n}\n\nfunction reportRemovedQueueCommand(ctx: ExtensionCommandContext, runtime: GoalRuntime) {\n const message = runtime.activeGoal\n ? \"Ordered goal queue has been removed. Use /goal edit to reprioritize the active objective instead.\"\n : \"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 if (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(message);\n notifyTerminal(ctx.ui, message, \"warning\");\n}\n\nfunction captureMenuOwnership(runtime: GoalRuntime): () => boolean {\n const generation = runtime.menuGeneration;\n const controller = runtime.menuController;\n return () =>\n runtime.menuGeneration === generation && runtime.menuController === controller && !controller.signal.aborted;\n}\n\nfunction cachedModuleLoader<Module>(load: () => Promise<Module>): () => Promise<Module> {\n let pending: Promise<Module> | undefined;\n return () => {\n if (!pending) {\n pending = load().catch((error) => {\n pending = undefined;\n throw error;\n });\n }\n return pending;\n };\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 buildGoalPrompt,\n buildObjectiveUpdatedPrompt,\n buildResumePrompt,\n buildWaitingResumePrompt,\n} from \"./prompts.js\";\nimport {\n blocksStaleGoalToolCalls,\n createGoal,\n editedGoalStatus,\n formatBudget,\n formatError,\n type GoalRuntime,\n goalSummary,\n isResumableGoalStatus,\n nextGoalInstance,\n queueGoalSafetyReset,\n STATUS_KEY,\n type StatusContext,\n stoppedStatusLabel,\n transitionGoal,\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 private readonly runtime: GoalRuntime;\n\n constructor(runtime: GoalRuntime) {\n this.runtime = runtime;\n }\n\n async startGoal(\n objective: string,\n tokenBudget: number | undefined,\n ctx: StatusContext,\n onActivated?: (goal: ActiveGoal) => void,\n isActivationCurrent?: (goal: ActiveGoal) => boolean,\n isRequestCurrent?: () => boolean,\n ) {\n if (isRequestCurrent && !isRequestCurrent()) return;\n const validationError = validateObjective(objective);\n if (validationError) {\n notifyTerminal(ctx.ui, validationError, \"warning\");\n return;\n }\n\n const existingGoal = this.runtime.activeGoal?.status !== \"complete\" ? this.runtime.activeGoal : undefined;\n const legacyQueueBeforeActivation = existingGoal\n ? undefined\n : this.runtime.legacyQueueState\n ? structuredClone(this.runtime.legacyQueueState)\n : undefined;\n if (existingGoal) {\n const shouldReplace = await ctx.ui.confirm(\n \"Replace goal?\",\n `Current goal: ${safeGoalMenuText(existingGoal.text, 4_000)}\\n\\nNew goal: ${safeGoalMenuText(objective, 4_000)}`,\n );\n if (!shouldReplace) {\n notifyTerminal(ctx.ui, `Goal kept: ${existingGoal.text}`, \"info\");\n return;\n }\n if (isRequestCurrent && !isRequestCurrent()) return;\n if (this.runtime.activeGoal?.id !== existingGoal.id) {\n notifyTerminal(ctx.ui, \"The active goal changed while confirmation was open. Try again.\", \"warning\");\n return;\n }\n }\n\n // Tool registration keeps the Goal schema stable. A missing tool means another\n // policy or allowlist intentionally removed it, so activation must not widen it.\n if (isRequestCurrent && !isRequestCurrent()) return;\n const retainedOwner = this.runtime.ownsWorkflow(existingGoal);\n if (!this.runtime.acquireWorkflow(ctx.sessionManager)) return this.reportWorkflowBusy(ctx);\n const acquiredForRequest = !retainedOwner;\n try {\n this.runtime.assertGoalToolsAvailable();\n } catch (error) {\n notifyTerminal(ctx.ui, `Cannot start /goal: ${formatError(error)}`, \"error\");\n if (existingGoal?.status === \"active\") this.runtime.pauseGoalForUnavailableTools(ctx);\n else if (acquiredForRequest) this.runtime.releaseWorkflow();\n return;\n }\n\n this.runtime.clearGoalWaitTimer();\n this.runtime.cancelContinuationWork();\n this.runtime.clearGoalRecovery();\n this.runtime.clearBudgetWrapUp();\n this.runtime.clearStaleGoalToolCallBlock();\n if (!legacyQueueBeforeActivation) this.runtime.legacyQueueState = undefined;\n this.runtime.activeGoal = createGoal(objective, tokenBudget, currentTokenTotal(ctx));\n const startedGoal = this.runtime.activeGoal;\n onActivated?.(startedGoal);\n if (!legacyQueueBeforeActivation) this.runtime.persistGoal(startedGoal);\n if (this.runtime.activeGoal?.id !== startedGoal.id || !this.runtime.ownsWorkflow(this.runtime.activeGoal)) {\n return;\n }\n this.runtime.updateStatus(ctx, startedGoal);\n const sent = await this.runtime.sendOwnedGoalPrompt(\n ctx,\n startedGoal.id,\n buildGoalPrompt(startedGoal),\n true,\n () => (isRequestCurrent?.() ?? true) && (isActivationCurrent?.(startedGoal) ?? true),\n );\n if (\n sent &&\n legacyQueueBeforeActivation &&\n this.runtime.activeGoal?.id === startedGoal.id &&\n this.runtime.activeGoal.status === \"active\"\n ) {\n this.runtime.legacyQueueState = undefined;\n this.runtime.persistGoal(startedGoal);\n }\n if (isActivationCurrent && !isActivationCurrent(startedGoal)) return;\n if (!sent) {\n let rolledBackStartedGoal = false;\n if (this.runtime.activeGoal?.id === startedGoal.id) {\n rolledBackStartedGoal = true;\n if (existingGoal) {\n this.runtime.recordGoalUsage(existingGoal, ctx);\n if (existingGoal.status === \"active\" && existingGoal.waiting) {\n this.runtime.activeGoal = existingGoal;\n this.runtime.clearStaleGoalToolCallBlock();\n this.runtime.persistGoal(existingGoal);\n this.runtime.updateStatus(ctx, existingGoal);\n this.runtime.restoreGoalWaitTimer(ctx);\n } else if (existingGoal.status === \"active\") {\n this.runtime.activeGoal = existingGoal;\n this.runtime.clearStaleGoalToolCallBlock();\n this.runtime.persistGoal(existingGoal);\n if (this.runtime.activeGoal?.id === existingGoal.id) {\n this.runtime.updateStatus(ctx, existingGoal);\n }\n } else {\n this.runtime.activeGoal = existingGoal;\n if (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n this.runtime.blockStaleGoalToolCalls();\n } else {\n this.runtime.clearStaleGoalToolCallBlock();\n }\n this.runtime.persistGoal(this.runtime.activeGoal);\n this.runtime.updateStatus(ctx, this.runtime.activeGoal);\n }\n } else if (legacyQueueBeforeActivation) {\n this.runtime.activeGoal = undefined;\n this.runtime.legacyQueueState = legacyQueueBeforeActivation;\n this.runtime.cancelContinuationWork();\n this.runtime.clearGoalRecovery();\n this.runtime.clearBudgetWrapUp();\n this.runtime.clearStaleGoalToolCallBlock();\n ctx.ui.setStatus(STATUS_KEY, undefined);\n } else {\n this.runtime.clearActiveGoal(ctx, \"goal activation rolled back\", false);\n }\n }\n if (rolledBackStartedGoal) {\n if (acquiredForRequest && !this.runtime.ownsWorkflow(existingGoal)) {\n this.runtime.releaseWorkflow();\n }\n }\n return;\n }\n if (this.runtime.activeGoal?.id !== startedGoal.id || !this.runtime.ownsWorkflow(this.runtime.activeGoal)) {\n return;\n }\n const automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;\n notifyTerminal(\n ctx.ui,\n `${existingGoal ? \"Goal replaced\" : \"Goal started\"}: ${objective}. ${\n startedGoal.tokenBudget === undefined\n ? \"\"\n : `Token budget: ${formatTokenCount(startedGoal.tokenBudget)} cumulative; the final model call may exceed it. `\n }${\n automaticLimit === null\n ? \"Automatic work is Unlimited; tool loops may consume substantial tokens and provider cost. Open /goal to monitor.\"\n : `Automatic work pauses after ${automaticLimit} responses; open /goal to monitor progress.`\n }`,\n automaticLimit === null ? \"warning\" : \"info\",\n );\n }\n\n pauseGoal(ctx: StatusContext) {\n if (!this.runtime.activeGoal) {\n notifyTerminal(ctx.ui, \"No active goal.\", \"info\");\n return;\n }\n if (this.runtime.activeGoal.status !== \"active\") {\n notifyTerminal(ctx.ui, `Goal is ${this.runtime.activeGoal.status}; only active goals can be paused.`, \"warning\");\n return;\n }\n const stoppedGoal = this.runtime.stopActiveGoal(ctx, {\n kind: \"explicit_pause\",\n expectedGoalId: this.runtime.activeGoal.id,\n });\n if (stoppedGoal) notifyTerminal(ctx.ui, `Goal paused: ${stoppedGoal.text}`, \"info\");\n }\n\n async resumeGoal(ctx: StatusContext) {\n if (!this.runtime.activeGoal) {\n notifyTerminal(ctx.ui, \"No active goal.\", \"info\");\n return;\n }\n if (this.runtime.activeGoal.status === \"active\" && this.runtime.activeGoal.waiting) {\n await this.resumeWaitingGoal(ctx);\n return;\n }\n if (!isResumableGoalStatus(this.runtime.activeGoal.status)) {\n notifyTerminal(\n ctx.ui,\n `Goal is ${this.runtime.activeGoal.status}; only paused, blocked, usage-limited, or budget-limited goals can be resumed.`,\n \"warning\",\n );\n return;\n }\n if (\n this.runtime.activeGoal.tokenBudget !== undefined &&\n this.runtime.activeGoal.tokensUsed >= this.runtime.activeGoal.tokenBudget\n ) {\n notifyTerminal(ctx.ui, `Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`, \"warning\");\n return;\n }\n if (!this.runtime.acquireWorkflow(ctx.sessionManager)) {\n this.reportWorkflowBusy(ctx);\n return;\n }\n try {\n this.runtime.assertGoalToolsAvailable();\n } catch (error) {\n notifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, \"error\");\n this.runtime.releaseWorkflow();\n return;\n }\n const stoppedGoal = this.runtime.activeGoal;\n const stoppedStatus = stoppedGoal.status;\n this.runtime.cancelContinuationWork();\n this.runtime.clearGoalRecovery();\n this.runtime.clearBudgetWrapUp();\n this.runtime.clearStaleGoalToolCallBlock();\n this.runtime.activeGoal = queueGoalSafetyReset(transitionGoal(nextGoalInstance(this.runtime.activeGoal), \"active\"));\n this.runtime.persistGoal(this.runtime.activeGoal);\n if (this.runtime.activeGoal.status !== \"active\") {\n this.runtime.updateStatus(ctx, this.runtime.activeGoal);\n this.runtime.releaseWorkflow();\n notifyTerminal(ctx.ui, `Goal token budget is still reached: ${formatBudget(this.runtime.activeGoal)}`, \"warning\");\n return;\n }\n if (!this.runtime.ownsWorkflow(this.runtime.activeGoal)) return;\n this.runtime.updateStatus(ctx, this.runtime.activeGoal);\n const resumedGoal = this.runtime.activeGoal;\n const sent = await this.runtime.sendOwnedGoalPrompt(\n ctx,\n resumedGoal.id,\n buildResumePrompt(resumedGoal, stoppedStatus),\n );\n if (!sent) {\n if (this.runtime.activeGoal?.id === resumedGoal.id && this.runtime.activeGoal.status === \"active\") {\n this.runtime.activeGoal = stoppedGoal;\n this.runtime.persistGoal(this.runtime.activeGoal);\n this.runtime.updateStatus(ctx, this.runtime.activeGoal);\n if (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n this.runtime.blockStaleGoalToolCalls();\n }\n this.runtime.releaseWorkflow();\n }\n return;\n }\n if (!this.runtime.ownsWorkflow(resumedGoal)) return;\n const automaticLimit = this.runtime.settings.continuationLimits.automaticTurns;\n notifyTerminal(\n ctx.ui,\n `Goal resumed from ${stoppedStatusLabel(stoppedStatus)}: ${resumedGoal.text}. ${\n automaticLimit === null\n ? \"Automatic work remains Unlimited; goal progress and cumulative usage are preserved.\"\n : `The automatic-work counter will reset to 0 of ${automaticLimit} when the resumed prompt starts; goal progress and cumulative usage are preserved.`\n }`,\n automaticLimit === null ? \"warning\" : \"info\",\n );\n }\n\n private async resumeWaitingGoal(ctx: StatusContext) {\n const waitingGoal = this.runtime.activeGoal;\n const waiting = waitingGoal?.waiting;\n if (waitingGoal?.status !== \"active\" || !waiting) return;\n if (!this.runtime.acquireWorkflow(ctx.sessionManager)) {\n this.reportWorkflowBusy(ctx);\n return;\n }\n try {\n this.runtime.assertGoalToolsAvailable();\n } catch (error) {\n notifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, \"error\");\n return;\n }\n if (!this.runtime.clearGoalWait(ctx, waitingGoal.id)) return;\n const resumedGoal = this.runtime.activeGoal;\n if (!resumedGoal || resumedGoal.id !== waitingGoal.id || resumedGoal.status !== \"active\") return;\n const sent = await this.runtime.sendOwnedGoalPrompt(\n ctx,\n resumedGoal.id,\n buildWaitingResumePrompt(resumedGoal, waiting.reason),\n false,\n );\n if (!sent) {\n if (this.runtime.activeGoal?.id === waitingGoal.id) {\n this.runtime.enterGoalWait(ctx, waitingGoal.id, waiting);\n }\n return;\n }\n if (!this.runtime.ownsWorkflow(resumedGoal)) return;\n notifyTerminal(ctx.ui, `Goal resumed from waiting: ${waitingGoal.text}`, \"info\");\n }\n\n clearGoal(ctx: StatusContext) {\n if (!this.runtime.activeGoal) {\n const hadLegacyQueue = this.runtime.legacyQueueState !== undefined;\n this.runtime.legacyQueueState = undefined;\n this.runtime.cancelContinuationWork();\n this.runtime.clearGoalRecovery();\n this.runtime.clearBudgetWrapUp();\n this.runtime.clearStaleGoalToolCallBlock();\n this.runtime.clearPersistedGoal(ctx.cwd);\n ctx.ui.setStatus(STATUS_KEY, undefined);\n notifyTerminal(\n ctx.ui,\n hadLegacyQueue ? \"Removed legacy ordered goal queue state.\" : \"No active goal.\",\n hadLegacyQueue ? \"warning\" : \"info\",\n );\n return;\n }\n\n const stoppedGoal = this.runtime.activeGoal.text;\n this.runtime.clearActiveGoal(ctx);\n notifyTerminal(ctx.ui, `Goal cleared: ${stoppedGoal}`, \"warning\");\n }\n\n async editGoal(objective: string, tokenBudget: number | undefined, ctx: StatusContext) {\n const validationError = validateObjective(objective);\n if (validationError) {\n notifyTerminal(ctx.ui, validationError, \"warning\");\n return;\n }\n if (!this.runtime.activeGoal) {\n notifyTerminal(ctx.ui, \"No active goal. Use /goal <objective> to start one.\", \"warning\");\n return;\n }\n\n const currentGoal = this.runtime.activeGoal;\n const effectiveTokenBudget = tokenBudget ?? currentGoal.tokenBudget;\n if (\n currentGoal.status === \"budget_limited\" &&\n effectiveTokenBudget !== undefined &&\n effectiveTokenBudget <= currentGoal.tokensUsed\n ) {\n notifyTerminal(\n ctx.ui,\n `Goal token budget is still reached: ${formatBudget(currentGoal)}. Raise the budget above current usage before editing.`,\n \"warning\",\n );\n return;\n }\n const previousStatus = currentGoal.status;\n const intendsActive = editedGoalStatus(previousStatus) === \"active\";\n const retainedOwner = this.runtime.ownsWorkflow(currentGoal);\n if (intendsActive && !this.runtime.acquireWorkflow(ctx.sessionManager)) {\n this.reportWorkflowBusy(ctx);\n return;\n }\n const acquiredForEdit = intendsActive && !retainedOwner;\n if (intendsActive) {\n try {\n this.runtime.assertGoalToolsAvailable();\n } catch (error) {\n notifyTerminal(ctx.ui, `Cannot reactivate /goal: ${formatError(error)}`, \"error\");\n if (currentGoal.status === \"active\") this.runtime.pauseGoalForUnavailableTools(ctx);\n else if (acquiredForEdit) this.runtime.releaseWorkflow();\n return;\n }\n }\n\n this.runtime.recordGoalUsage(currentGoal, ctx);\n const previousGoal = { ...currentGoal };\n this.runtime.clearGoalWaitTimer();\n this.runtime.cancelContinuationWork();\n this.runtime.clearGoalRecovery();\n this.runtime.clearBudgetWrapUp();\n const rotatedGoal = nextGoalInstance(currentGoal);\n const transitionedGoal = transitionGoal(\n {\n ...rotatedGoal,\n text: objective,\n tokenBudget: effectiveTokenBudget,\n waiting: undefined,\n },\n editedGoalStatus(previousStatus),\n );\n const nextGoal = transitionedGoal.status === \"active\" ? queueGoalSafetyReset(transitionedGoal) : transitionedGoal;\n this.runtime.activeGoal = nextGoal;\n this.runtime.persistGoal(this.runtime.activeGoal);\n this.runtime.updateStatus(ctx, this.runtime.activeGoal);\n const editedGoal = this.runtime.activeGoal;\n if (!editedGoal) return;\n if (editedGoal.status === \"active\") {\n if (!this.runtime.ownsWorkflow(editedGoal)) return;\n this.runtime.clearStaleGoalToolCallBlock();\n const sent = await this.runtime.sendOwnedGoalPrompt(ctx, editedGoal.id, buildObjectiveUpdatedPrompt(editedGoal));\n if (!sent) {\n if (this.runtime.activeGoal?.id === editedGoal.id) {\n if (previousStatus === \"active\" && previousGoal.waiting) {\n this.runtime.activeGoal = previousGoal;\n this.runtime.clearStaleGoalToolCallBlock();\n this.runtime.persistGoal(previousGoal);\n this.runtime.updateStatus(ctx, previousGoal);\n this.runtime.restoreGoalWaitTimer(ctx);\n } else if (previousStatus === \"active\") {\n this.runtime.activeGoal = previousGoal;\n this.runtime.clearStaleGoalToolCallBlock();\n this.runtime.persistGoal(previousGoal);\n if (this.runtime.activeGoal?.id === previousGoal.id) {\n this.runtime.updateStatus(ctx, previousGoal);\n }\n } else {\n this.runtime.activeGoal = previousGoal;\n if (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {\n this.runtime.blockStaleGoalToolCalls();\n } else {\n this.runtime.clearStaleGoalToolCallBlock();\n }\n this.runtime.persistGoal(this.runtime.activeGoal);\n this.runtime.updateStatus(ctx, this.runtime.activeGoal);\n }\n if (acquiredForEdit && previousStatus !== \"active\") {\n this.runtime.releaseWorkflow();\n }\n }\n return;\n }\n if (!this.runtime.ownsWorkflow(editedGoal)) return;\n } else if (blocksStaleGoalToolCalls(editedGoal.status)) {\n this.runtime.blockStaleGoalToolCalls();\n } else {\n this.runtime.clearStaleGoalToolCallBlock();\n }\n if (editedGoal.status !== \"active\" && (retainedOwner || acquiredForEdit)) {\n this.runtime.releaseWorkflow();\n }\n notifyTerminal(ctx.ui, `Goal updated: ${objective}`, \"info\");\n }\n\n private reportWorkflowBusy(ctx: StatusContext) {\n const message = \"Another workflow is active in this session. End it before starting Goal.\";\n if (ctx.mode === \"print\" || ctx.mode === \"json\") throw new Error(message);\n notifyTerminal(ctx.ui, message, \"warning\");\n return { kind: \"busy\" as const };\n }\n\n showGoal(ctx: StatusContext) {\n if (!this.runtime.activeGoal) {\n ctx.ui.setStatus(STATUS_KEY, undefined);\n this.reportGoalStatus(ctx, this.emptyGoalMessage());\n return;\n }\n this.runtime.recordGoalUsage(this.runtime.activeGoal, ctx);\n this.runtime.persistGoal(this.runtime.activeGoal);\n this.runtime.updateStatus(ctx, this.runtime.activeGoal);\n this.reportGoalStatus(\n ctx,\n goalSummary(this.runtime.activeGoal, this.runtime.settings.continuationLimits.automaticTurns),\n );\n }\n\n private emptyGoalMessage() {\n const legacy = this.runtime.legacyQueueState;\n if (!legacy) return \"Usage: /goal <objective>\\nNo goal is currently set.\";\n return [\n \"Ordered goal queue has been removed.\",\n `Legacy queue state with ${legacy.retainedGoals} retained ${legacy.retainedGoals === 1 ? \"goal\" : \"goals\"} will not run automatically.`,\n \"Use /goal edit to reprioritize an active objective, start /goal <objectives>, or use /goal clear to discard the old queue state.\",\n 'Example objective: \"task b is complete; do task a next, then task c and task d.\"',\n ].join(\"\\n\");\n }\n\n private reportGoalStatus(ctx: StatusContext, message: string) {\n if (ctx.mode === \"print\" || ctx.mode === \"json\") {\n throw new Error(\n `/goal status is unavailable in ${ctx.mode} mode because Pi does not expose an extension-command output channel. Use TUI or RPC mode.`,\n );\n }\n notifyTerminal(ctx.ui, message, \"info\");\n }\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { currentTokenTotal } from \"./accounting.js\";\nimport { notifyTerminal } from \"./errors.js\";\nimport {\n GOAL_CONTRACT_MESSAGE_TYPE,\n isGoalContextContract,\n reconcileGoalContextContract,\n reconcileInactiveGoalContextContract,\n} from \"./goal-contract.js\";\nimport { type ActiveGoal, loadGoalStateFromSession } from \"./persistence.js\";\nimport type { GoalRunController } from \"./run-protocol.js\";\nimport {\n type AssistantMessageLike,\n abortCurrentTurn,\n blocksStaleGoalToolCalls,\n findFinalAssistantMessage,\n type GoalRuntime,\n incrementGoal,\n isGoalContextOverflow,\n isRetryableGoalInterruption,\n isUsageLimitedGoalInterruption,\n resetGoalSafetyEpoch,\n STATUS_KEY,\n type StatusContext,\n transitionGoal,\n truncateNotification,\n} from \"./runtime.js\";\nimport { hasAssistantToolCall } from \"./safety.js\";\nimport { DEFAULT_GOAL_SETTINGS, readGoalSettings } from \"./settings.js\";\n\nconst REMOVED_QUEUE_SETTING_WARNING =\n \"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 \"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 settingsPath?: string;\n}\n\nexport function registerGoalLifecycle(\n pi: ExtensionAPI,\n runtime: GoalRuntime,\n runController: GoalRunController,\n options: GoalLifecycleOptions = {},\n) {\n // Pi invalidates this module's ExtensionContext when the session is replaced\n // or reloaded, but detached prompts and queued emits can still invoke these\n // handlers afterward. After session_shutdown every ctx getter throws a stale\n // context error, so late handlers must return before touching ctx. The flag\n // starts true so handlers keep working on runners where session_start was\n // never emitted (for example late extension loading).\n let sessionActive = true;\n let endedGoalRun: { goalId: string; aborted: boolean } | undefined;\n pi.on(\"session_start\", async (_event, ctx) => {\n sessionActive = true;\n runtime.pendingLengthRecovery = undefined;\n endedGoalRun = undefined;\n runtime.bindWorkflowSession(ctx.sessionManager);\n runtime.replaceMenuSession();\n runtime.clearCompletionStatusTimer();\n runtime.clearContinuationTracking();\n runtime.clearGoalWaitTimer();\n runtime.clearPendingGoalPrompts();\n runtime.clearAgentRun();\n runtime.guardAbortGoalId = undefined;\n runtime.clearGoalRecovery();\n runtime.clearBudgetWrapUp();\n runtime.clearStaleGoalToolCallBlock();\n runtime.legacyQueueState = undefined;\n runtime.legacyExperimentalGoalsSetting = false;\n runtime.clearTerminalDetails();\n const settingsResult = readGoalSettings(options.settingsPath);\n const loaded = loadGoalStateFromSession(ctx);\n runtime.settings = settingsResult.kind === \"loaded\" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;\n runtime.settingsLoadIssue = settingsResult.kind === \"invalid\" ? settingsResult : undefined;\n runtime.activeGoal = undefined;\n runtime.legacyQueueState = loaded.legacyQueueState;\n runtime.legacyExperimentalGoalsSetting =\n settingsResult.kind !== \"invalid\" && settingsResult.legacyExperimentalGoals;\n runController.bindSession(ctx);\n\n if (settingsResult.kind === \"invalid\") {\n notifyTerminal(ctx.ui, `pi-goal settings ignored: ${settingsResult.reason}. Using default settings.`, \"warning\");\n }\n if (runtime.legacyExperimentalGoalsSetting && !runtime.legacyQueueState) {\n notifyTerminal(ctx.ui, REMOVED_QUEUE_SETTING_WARNING, \"warning\");\n }\n\n if (loaded.goal?.status === \"active\") {\n if (!runtime.acquireWorkflow()) {\n runtime.activeGoal = transitionGoal(loaded.goal, \"paused\");\n runtime.persistGoal(runtime.activeGoal);\n runtime.ensureInactiveGoalContextContract(ctx);\n runtime.updateStatus(ctx, runtime.activeGoal);\n notifyTerminal(\n ctx.ui,\n \"Goal was paused during restore because another workflow is active in this session. Resume it after the other workflow ends.\",\n \"warning\",\n );\n return;\n }\n runtime.activeGoal = loaded.goal;\n if (runtime.activeGoal.safetyResetPending) {\n // Resume/edit activation is persisted before its owned prompt starts. A\n // reload must commit that promised reset before enforcing the old limits.\n runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n }\n runtime.recordGoalUsage(runtime.activeGoal, ctx);\n if (runtime.limitActiveGoalForBudget(ctx, false)) return;\n if (runtime.enforceAutomaticTurnLimit(ctx, false) || runtime.enforceNoProgressLimit(ctx)) {\n return;\n }\n if (!runtime.goalToolsAvailable()) {\n runtime.pauseGoalForUnavailableTools(ctx, false);\n return;\n }\n runtime.persistGoal(runtime.activeGoal);\n if (!runtime.ownsWorkflow(runtime.activeGoal)) return;\n const restoredGoalId = runtime.activeGoal.id;\n runtime.ensureGoalContextContract(ctx, runtime.activeGoal);\n if (\n runtime.activeGoal?.id !== restoredGoalId ||\n runtime.activeGoal.status !== \"active\" ||\n !runtime.ownsWorkflow(runtime.activeGoal)\n ) {\n return;\n }\n runtime.updateStatus(ctx, runtime.activeGoal);\n runtime.restoreGoalWaitTimer(ctx);\n return;\n }\n\n runtime.activeGoal = loaded.goal;\n if (runtime.legacyQueueState) {\n ctx.ui.setStatus(STATUS_KEY, undefined);\n notifyTerminal(ctx.ui, REMOVED_PERSISTED_QUEUE_WARNING, \"warning\");\n return;\n }\n if (runtime.activeGoal) {\n runtime.persistGoal(runtime.activeGoal);\n runtime.ensureInactiveGoalContextContract(ctx);\n runtime.updateStatus(ctx, runtime.activeGoal);\n } else {\n runtime.ensureInactiveGoalContextContract(ctx);\n ctx.ui.setStatus(STATUS_KEY, undefined);\n }\n });\n\n pi.on(\"session_shutdown\", (_event, ctx) => {\n sessionActive = false;\n runtime.pendingLengthRecovery = undefined;\n endedGoalRun = undefined;\n const shutdownSession = ctx.sessionManager;\n runController.unbindSession();\n runtime.closeMenuSession();\n runtime.clearGoalWaitTimer();\n if (runtime.activeGoal) {\n if (runtime.activeGoal.status === \"active\") {\n runtime.recordGoalUsage(runtime.activeGoal, ctx, false);\n }\n runtime.persistGoal(runtime.activeGoal);\n }\n runtime.clearContinuationTracking();\n runtime.clearPendingGoalPrompts();\n runtime.clearAgentRun();\n runtime.guardAbortGoalId = undefined;\n runtime.clearGoalRecovery();\n runtime.clearBudgetWrapUp();\n runtime.clearStaleGoalToolCallBlock();\n runtime.activeGoal = undefined;\n runtime.legacyQueueState = undefined;\n runtime.legacyExperimentalGoalsSetting = false;\n ctx.ui.setStatus(STATUS_KEY, undefined);\n runtime.clearCompletionStatusTimer();\n runtime.clearTerminalDetails();\n runtime.releaseWorkflow();\n runtime.unbindWorkflowSession(shutdownSession);\n });\n\n pi.on(\"session_before_compact\", (event, ctx) => {\n if (!sessionActive) return;\n if (runtime.activeGoal?.status === \"budget_limited\") {\n if ((event as { willRetry?: boolean }).willRetry === true) return { cancel: true as const };\n return;\n }\n if (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n return;\n }\n if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;\n if (event.willRetry === true) claimCompactionRecovery(runtime.activeGoal.id);\n runtime.cancelContinuationWork();\n runtime.persistGoal(runtime.activeGoal);\n runtime.updateStatus(ctx, runtime.activeGoal);\n if (runtime.limitActiveGoalForBudget(ctx, false)) return { cancel: true as const };\n });\n\n pi.on(\"session_compact_failed\", (event) => {\n if (!sessionActive || !runtime.ownsWorkflow() || !runtime.activeGoal) return;\n // A repeated length failure ends recovery without another before_compact.\n if (event.reason === \"overflow\") claimCompactionRecovery(runtime.activeGoal.id);\n // Native compaction-only cancellation does not set agent_settled.aborted.\n // An independent manual compaction has no ended run and cannot pause a Goal.\n if (event.aborted && endedGoalRun?.goalId === runtime.activeGoal.id) endedGoalRun.aborted = true;\n });\n\n pi.on(\"session_compact\", async (event, ctx) => {\n if (!sessionActive) return;\n if (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n runtime.clearGoalRecovery();\n runtime.ensureInactiveGoalContextContract(ctx);\n return;\n }\n\n const restoredState = loadGoalStateFromSession(ctx);\n if (restoredState.goal?.id === runtime.activeGoal.id) {\n runtime.activeGoal = restoredState.goal;\n }\n const usageRecorded = runtime.recordGoalUsage(runtime.activeGoal, ctx);\n if (usageRecorded) {\n runtime.persistGoal(runtime.activeGoal);\n runtime.updateStatus(ctx, runtime.activeGoal);\n }\n if (runtime.limitActiveGoalForBudget(ctx, false)) return;\n const compactedGoalId = runtime.activeGoal.id;\n runtime.ensureGoalContextContract(ctx, runtime.activeGoal);\n if (\n runtime.activeGoal?.id !== compactedGoalId ||\n runtime.activeGoal.status !== \"active\" ||\n !runtime.ownsWorkflow(runtime.activeGoal)\n ) {\n return;\n }\n if (!usageRecorded) return;\n\n const wasPiRetry = runtime.isPiOwnedCompactionRetry(event, runtime.activeGoal.id);\n // Threshold compaction can follow a provider error without retrying it.\n // Keep that error pending so settlement waits instead of sending a new turn.\n if (wasPiRetry || runtime.hasActiveGoalRecovery()) return;\n runtime.clearGoalRecoveryForGoal(runtime.activeGoal.id);\n runtime.requestContinuation(runtime.activeGoal);\n // Pi emits session_compact before it clears its manual-compaction controller,\n // so sendUserMessage still rejects inside this hook even when ctx reports idle.\n // Defer one task; threshold compaction retains the intent for agent_settled\n // when Pi is still busy.\n runtime.scheduleContinuationDispatch(ctx, runtime.activeGoal.id);\n });\n\n pi.on(\"input\", (event, ctx) => {\n if (!sessionActive) return;\n if (event.source === \"extension\") {\n if (\n runtime.consumeCancelledGoalPrompt(event.text) ||\n runtime.consumeCancelledContinuationPrompt(event.text) ||\n runtime.consumeStaleOwnedGoalPrompt(event.text)\n ) {\n return { action: \"handled\" as const };\n }\n // Streaming input is queued before its model work starts. Keep owned\n // markers pending for message_start, and track non-goal delivery mode so a\n // steer cannot consume a later follow-up's cleanup protection.\n if (runtime.acceptOwnedInputBoundary(event.text)) return;\n runtime.supersedeOwnedInputCollision(event.text);\n if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n if (event.streamingBehavior === \"steer\" || event.streamingBehavior === \"followUp\") {\n runtime.noteQueuedNonGoalInput(event.text, event.streamingBehavior);\n }\n runtime.pendingLengthRecovery = undefined;\n runtime.clearGoalRecovery();\n return;\n }\n if (/^\\/goal(?:\\s|$)/u.test(event.text.trimStart())) return;\n if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n if (event.streamingBehavior === \"followUp\") {\n runtime.noteQueuedNonGoalInput(event.text, \"followUp\", true);\n return;\n }\n if (event.streamingBehavior === \"steer\") {\n runtime.noteQueuedNonGoalInput(event.text, \"steer\");\n }\n runtime.pendingLengthRecovery = undefined;\n runtime.clearGoalRecovery();\n runtime.clearBudgetWrapUp();\n runtime.clearStaleGoalToolCallBlock();\n runtime.resetActiveSafetyEpoch(ctx);\n });\n\n pi.on(\"message_start\", (event, ctx) => {\n if (!sessionActive) return;\n const message = event.message as { role?: unknown; content?: unknown };\n if (\n message.role === \"assistant\" &&\n runtime.activeGoal?.status === \"paused\" &&\n runtime.guardAbortGoalId === runtime.activeGoal.id\n ) {\n abortCurrentTurn(ctx);\n return;\n }\n if (message.role === \"custom\") {\n if (Reflect.get(message, \"customType\") === GOAL_CONTRACT_MESSAGE_TYPE) return;\n if (runtime.isActiveBudgetWrapUpMessage(message)) return;\n if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n if (runtime.guardAbortGoalId === runtime.activeGoal?.id) {\n runtime.guardAbortGoalId = undefined;\n }\n beginNonGoalFollowUp(ctx, false);\n return;\n }\n if (message.role !== \"user\") return;\n const prompt = Array.isArray(message.content)\n ? message.content\n .filter((part) => part && typeof part === \"object\" && Reflect.get(part, \"type\") === \"text\")\n .map((part) => Reflect.get(part as object, \"text\"))\n .filter((text): text is string => typeof text === \"string\")\n .join(\"\\n\")\n : typeof message.content === \"string\"\n ? message.content\n : \"\";\n const ownedPrompt = runtime.consumeOwnedGoalPrompt(prompt);\n const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(prompt);\n const queuedNonGoalInput = runtime.consumeQueuedNonGoalInput(prompt, !ownedPromptBoundary);\n if (!ownedPrompt) {\n if (queuedNonGoalInput?.behavior === \"followUp\") {\n beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);\n }\n return;\n }\n if (runtime.activeGoal?.id !== ownedPrompt.goalId || !runtime.ownsWorkflow(runtime.activeGoal)) {\n return;\n }\n if (runtime.agentRunGoalId !== undefined && runtime.agentRunGoalId !== ownedPrompt.goalId) {\n runtime.activeGoal.baselineTokens = Math.max(0, currentTokenTotal(ctx) - runtime.activeGoal.tokensUsed);\n }\n runtime.beginAgentRun(ownedPrompt.goalId, \"manual\");\n if (ownedPrompt.resetSafetyEpoch) {\n runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n }\n runtime.persistGoal(runtime.activeGoal);\n runtime.updateStatus(ctx, runtime.activeGoal);\n });\n\n pi.on(\"context\", (event, ctx) => {\n if (!sessionActive) return;\n const keptMessages = event.messages.filter((message) => runtime.keepBudgetWrapUpMessage(message));\n const hasGoalContractHistory =\n keptMessages.some(isGoalContextContract) || runtime.hasGoalContextContractHistory(ctx);\n const messages =\n runtime.activeGoal?.status === \"active\" && runtime.ownsWorkflow(runtime.activeGoal)\n ? reconcileGoalContextContract(keptMessages, runtime.activeGoal)\n : hasGoalContractHistory\n ? reconcileInactiveGoalContextContract(keptMessages)\n : keptMessages;\n if (runtime.activeGoal?.status === \"paused\" && runtime.guardAbortGoalId === runtime.activeGoal.id) {\n // A current custom follow-up clears the guard at message_start. Otherwise,\n // context transformation aborts before the provider adapter receives the signal.\n abortCurrentTurn(ctx);\n }\n if (messages !== keptMessages || keptMessages.length !== event.messages.length) {\n return { messages: messages as typeof event.messages };\n }\n });\n\n pi.on(\"tool_call\", (event, ctx) => {\n if (!sessionActive) return;\n runtime.markAgentToolAttempted();\n if (\n runtime.activeGoal?.status === \"budget_limited\" &&\n runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&\n event.toolName !== \"goal_complete\"\n ) {\n // A blocked tool result would normally trigger another model call. Abort the\n // wrap-up instead so a tool-seeking model cannot create an unbounded loop.\n abortCurrentTurn(ctx);\n return {\n block: true,\n reason: \"Goal token budget is exhausted; only goal_complete is allowed during wrap-up.\",\n };\n }\n if (!runtime.staleGoalToolCallsBlocked) return;\n if (!runtime.activeGoal || !blocksStaleGoalToolCalls(runtime.activeGoal.status)) {\n runtime.clearStaleGoalToolCallBlock();\n return;\n }\n // A blocked tool result would normally trigger another model call. Abort the\n // current turn so a tool-seeking model cannot create an unbounded loop that\n // burns provider quota while the goal is stopped.\n abortCurrentTurn(ctx);\n return {\n block: true,\n reason: \"Blocked stale /goal tool call after the goal stopped or was interrupted.\",\n };\n });\n\n pi.on(\"tool_execution_end\", (_event, ctx) => {\n if (!sessionActive) return;\n if (\n runtime.activeGoal?.status === \"budget_limited\" &&\n runtime.budgetWrapUp?.goalId === runtime.activeGoal.id &&\n !runtime.budgetWrapUp.delivered\n ) {\n runtime.queueBudgetWrapUp(ctx, runtime.activeGoal);\n return;\n }\n if (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n return;\n }\n\n // AgentSession persists assistant message_end before tool execution events,\n // so the completed assistant call's usage is authoritative at this boundary.\n if (!runtime.recordGoalUsage(runtime.activeGoal, ctx)) return;\n runtime.persistGoal(runtime.activeGoal);\n runtime.updateStatus(ctx, runtime.activeGoal);\n if (runtime.limitActiveGoalForBudget(ctx, true)) return;\n if (!runtime.goalToolsAvailable()) runtime.pauseGoalForUnavailableTools(ctx);\n });\n\n pi.on(\"before_agent_start\", (event, ctx) => {\n // Custom runs use message_start to establish non-goal ownership.\n if (!sessionActive || event.messageType === \"custom\") return;\n runtime.pendingLengthRecovery = undefined;\n endedGoalRun = undefined;\n runtime.clearAgentRun();\n // Pi-owned retries emit agent_start directly. Reaching a normal prompt\n // boundary means cleanup no longer owns the next run, so the hard-cap guard\n // must not abort it.\n if (runtime.guardAbortGoalId) runtime.guardAbortGoalId = undefined;\n const goalPrompt = runtime.consumeOwnedGoalPrompt(event.prompt);\n const goalPromptGoalId = goalPrompt?.goalId;\n const continuationGoalId = goalPromptGoalId ? undefined : runtime.markContinuationStarted(event.prompt);\n const ownedPromptGoalId = goalPromptGoalId ?? continuationGoalId;\n const ownedPromptBoundary = runtime.hasOwnedPromptBoundary(event.prompt);\n const activeBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n const activeGoalRecovery = runtime.hasActiveGoalRecovery();\n const queuedNonGoalInput = activeBudgetWrapUp\n ? undefined\n : runtime.consumeQueuedNonGoalInput(\n event.prompt,\n !activeGoalRecovery && ownedPromptGoalId === undefined && !ownedPromptBoundary,\n );\n if (queuedNonGoalInput?.behavior === \"followUp\") {\n beginNonGoalFollowUp(ctx, queuedNonGoalInput.resetSafetyEpoch);\n }\n if (!ownedPromptGoalId && !ownedPromptBoundary) {\n runtime.supersedeOwnedInputCollision(event.prompt);\n if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);\n }\n if (runtime.activeGoal?.status === \"active\" && !runtime.ownsWorkflow(runtime.activeGoal)) {\n runtime.cancelContinuationWork();\n runtime.clearGoalRecovery();\n abortCurrentTurn(ctx);\n return;\n }\n const runOrigin = continuationGoalId\n ? \"automatic\"\n : activeGoalRecovery && runtime.goalRecovery?.automaticOwner\n ? \"automatic\"\n : \"manual\";\n if (activeBudgetWrapUp && runtime.activeGoal) {\n runtime.beginAgentRun(runtime.activeGoal.id, \"manual\");\n return goalContractBoundaryResult(ctx);\n }\n if (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {\n runtime.beginAgentRun(ownedPromptGoalId, runOrigin);\n if (runtime.activeGoal?.status === \"active\" && !runtime.goalToolsAvailable()) {\n runtime.pauseGoalForUnavailableTools(ctx, false);\n }\n abortCurrentTurn(ctx);\n return;\n }\n if (runtime.activeGoal?.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n return goalContractBoundaryResult(ctx);\n }\n runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);\n if (!runtime.goalToolsAvailable()) {\n runtime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== undefined);\n return goalContractBoundaryResult(ctx);\n }\n if (goalPrompt?.resetSafetyEpoch && goalPromptGoalId === runtime.activeGoal.id) {\n runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);\n runtime.persistGoal(runtime.activeGoal);\n runtime.updateStatus(ctx, runtime.activeGoal);\n }\n return goalContractBoundaryResult(ctx, runtime.activeGoal);\n });\n\n pi.on(\"agent_start\", (_event, _ctx) => {\n if (!sessionActive) return;\n runtime.pendingLengthRecovery = undefined;\n endedGoalRun = undefined;\n const activeGoal = runtime.activeGoal;\n if (activeGoal && runtime.guardAbortGoalId === activeGoal.id && activeGoal.status === \"paused\") {\n if (runtime.consumeQueuedNonGoalFollowUpForAgentStart()) {\n runtime.guardAbortGoalId = undefined;\n runtime.clearStaleGoalToolCallBlock();\n runtime.beginAgentRun(null, undefined);\n }\n // Unknown runs defer cleanup until their message/context boundary: custom\n // follow-ups have no input event, while bare recovery is aborted pre-provider.\n return;\n }\n runtime.beginRecoveryRunIfNeeded();\n });\n\n pi.on(\"turn_end\", (event, ctx) => {\n if (!sessionActive) return;\n runtime.recordAutomaticTurn(ctx, event.message);\n // Terminal Goal tools transition state synchronously, but their inactive contract\n // must wait until Pi has persisted the real tool result at this turn boundary.\n if (runtime.activeGoal?.status !== \"active\") {\n runtime.ensureInactiveGoalContextContract(ctx);\n }\n });\n\n pi.on(\"agent_end\", (event, ctx) => {\n if (!sessionActive) return;\n runtime.pendingLengthRecovery = undefined;\n endedGoalRun = undefined;\n const run = runtime.finishAgentRun();\n if (run.goalId === null) return;\n if (!runtime.canRecordGoalUsage() && !runtime.hasActiveBudgetWrapUp()) return;\n if (run.goalId && run.goalId !== runtime.activeGoal?.id) return;\n if (!runtime.activeGoal) return;\n if (runtime.activeGoal.status === \"budget_limited\" && runtime.budgetWrapUp?.goalId === runtime.activeGoal.id) {\n runtime.recordGoalUsage(runtime.activeGoal, ctx);\n runtime.persistGoal(runtime.activeGoal);\n runtime.updateStatus(ctx, runtime.activeGoal);\n runtime.clearBudgetWrapUp();\n return;\n }\n if (runtime.activeGoal.status !== \"active\" || !runtime.ownsWorkflow(runtime.activeGoal)) {\n return;\n }\n\n const goalId = runtime.activeGoal.id;\n endedGoalRun = { goalId, aborted: false };\n const alreadyAwaitingContinuation = runtime.hasContinuationWorkForGoal(goalId);\n const finalAssistant = findFinalAssistantMessage(event.messages);\n\n if (!alreadyAwaitingContinuation) runtime.activeGoal = incrementGoal(runtime.activeGoal);\n runtime.recordGoalUsage(runtime.activeGoal, ctx);\n\n if (finalAssistant?.stopReason === \"aborted\") {\n runtime.clearGoalRecoveryForGoal(goalId);\n stopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, \"paused\");\n return;\n }\n\n if (finalAssistant?.stopReason === \"error\") {\n const nativeRecovery = isRetryableGoalInterruption(finalAssistant);\n if (!nativeRecovery && isUsageLimitedGoalInterruption(finalAssistant)) {\n runtime.clearGoalRecoveryForGoal(goalId);\n stopGoalAfterAgentEnd(ctx, runtime.activeGoal, finalAssistant, \"usage_limited\");\n return;\n }\n if (\n run.origin === \"automatic\" &&\n (runtime.enforceAutomaticTurnLimit(ctx, true) || runtime.enforceNoProgressLimit(ctx, true))\n ) {\n return;\n }\n if (runtime.limitActiveGoalForBudget(ctx, false)) return;\n if (!runtime.goalToolsAvailable()) {\n runtime.pauseGoalForUnavailableTools(ctx);\n return;\n }\n // Waiting does not grant retry eligibility. Pi still owns every attempt.\n runtime.goalRecovery = {\n goalId,\n kind: isGoalContextOverflow(finalAssistant)\n ? \"compaction_retry\"\n : nativeRecovery\n ? \"provider_retry\"\n : \"provider_error\",\n automaticOwner: run.origin === \"automatic\",\n errorMessage: finalAssistant.errorMessage,\n };\n runtime.cancelContinuationWork();\n runtime.persistGoal(runtime.activeGoal);\n if (runtime.activeGoal?.id === goalId && runtime.ownsWorkflow(runtime.activeGoal)) {\n runtime.updateStatus(ctx, runtime.activeGoal);\n }\n return;\n }\n\n runtime.clearGoalRecoveryForGoal(goalId);\n\n if (runtime.limitActiveGoalForBudget(ctx, false)) return;\n if (!runtime.goalToolsAvailable()) {\n runtime.pauseGoalForUnavailableTools(ctx);\n return;\n }\n if (finalAssistant?.stopReason === \"length\") {\n // Reserve before either progress or final-state publication: a reentrant\n // goal_wait invalidates old work, while a later length response is fresh.\n runtime.pendingLengthRecovery = {\n goalId,\n kind: \"compaction_retry\",\n automaticOwner: run.origin === \"automatic\",\n };\n }\n if (\n run.origin === \"automatic\" &&\n runtime.recordAutomaticRunProgress(\n ctx,\n goalId,\n event.messages,\n run.toolAttempted || hasAssistantToolCall(event.messages),\n )\n ) {\n return;\n }\n\n const currentGoal = runtime.activeGoal;\n if (!currentGoal || currentGoal.id !== goalId || !runtime.ownsWorkflow(currentGoal)) return;\n runtime.persistGoal(currentGoal);\n const persistedGoal = runtime.activeGoal;\n if (!persistedGoal || persistedGoal.id !== goalId || !runtime.ownsWorkflow(persistedGoal)) return;\n runtime.updateStatus(ctx, persistedGoal);\n runtime.requestContinuation(persistedGoal);\n });\n\n pi.on(\"agent_settled\", (event, ctx) => {\n if (!sessionActive) return;\n runtime.pendingLengthRecovery = undefined;\n const settledRun = endedGoalRun;\n endedGoalRun = undefined;\n if (runtime.activeGoal?.status === \"active\" && !runtime.ownsWorkflow(runtime.activeGoal)) {\n runtime.cancelContinuationWork();\n runtime.clearGoalRecovery();\n runtime.clearSettledSafetyTracking();\n return;\n }\n runtime.finalizeSettledRecovery(ctx, event.aborted === true || settledRun?.aborted === true, settledRun?.goalId);\n const resumedWait = runtime.dispatchDueGoalWait(ctx);\n if (!resumedWait) runtime.dispatchContinuationIfSettled(ctx);\n runtime.clearSettledSafetyTracking();\n });\n\n function claimCompactionRecovery(goalId: string) {\n const lengthRecovery = runtime.pendingLengthRecovery?.goalId === goalId ? runtime.pendingLengthRecovery : undefined;\n if (lengthRecovery) runtime.pendingLengthRecovery = undefined;\n const recovery = lengthRecovery ?? (runtime.goalRecovery?.goalId === goalId ? runtime.goalRecovery : undefined);\n if (!recovery) return;\n // Pi's public compaction events confirm recovery for this matching run.\n runtime.goalRecovery = { ...recovery, kind: \"compaction_retry\" };\n runtime.cancelContinuationWork();\n }\n\n function goalContractBoundaryResult(ctx: StatusContext, goal?: ActiveGoal) {\n const message = runtime.goalContextContractForPrompt(ctx, goal);\n return message ? { message } : undefined;\n }\n\n function beginNonGoalFollowUp(ctx: StatusContext, resetSafetyEpoch: boolean) {\n runtime.pendingLengthRecovery = undefined;\n runtime.clearGoalRecovery();\n runtime.clearStaleGoalToolCallBlock();\n if (resetSafetyEpoch) runtime.clearBudgetWrapUp();\n const activeGoalId = runtime.activeGoal?.status === \"active\" ? runtime.activeGoal.id : undefined;\n runtime.beginAgentRun(activeGoalId ?? null, activeGoalId ? \"manual\" : undefined);\n if (resetSafetyEpoch && activeGoalId) runtime.resetActiveSafetyEpoch(ctx);\n }\n\n function stopGoalAfterAgentEnd(\n ctx: StatusContext,\n goal: ActiveGoal,\n assistant: AssistantMessageLike,\n status: \"paused\" | \"usage_limited\",\n ) {\n const stoppedGoal = runtime.stopActiveGoal(ctx, {\n kind: \"agent_interruption\",\n expectedGoalId: goal.id,\n status,\n reason: assistant.errorMessage ?? `goal ${status} after agent interruption`,\n });\n if (!stoppedGoal) return;\n\n const details = assistant.errorMessage ? ` (${truncateNotification(assistant.errorMessage)})` : \"\";\n if (status === \"paused\") {\n notifyTerminal(ctx.ui, `Goal paused after interruption${details}. Run /goal resume to continue.`, \"warning\");\n return;\n }\n notifyTerminal(\n ctx.ui,\n `Goal stopped after provider usage limit${details}. Run /goal resume when usage is available.`,\n \"warning\",\n );\n }\n}\n", "import type { ExtensionAPI } from \"@earendil-works/pi-coding-agent\";\nimport { validateObjective } from \"./command.js\";\nimport type { GoalCommandController } from \"./commands.js\";\nimport {\n formatError,\n type GoalRuntime,\n type GoalStateSnapshot,\n isTerminalGoalStatus,\n type 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 = GoalStateSnapshot[\"status\"];\nexport type GoalRunErrorCode =\n | \"RPC_DISABLED\"\n | \"INVALID_REQUEST\"\n | \"NO_ACTIVE_SESSION\"\n | \"RUN_ID_IN_USE\"\n | \"RUN_NOT_FOUND\"\n | \"GOAL_ALREADY_EXISTS\"\n | \"ACTIVATION_FAILED\"\n | \"SUPERSEDED\";\n\nexport type GoalRunEvent =\n | {\n type: \"state\";\n runId: string;\n goalId: string;\n status: GoalRunStatus;\n summary?: string;\n reason?: string;\n }\n | {\n type: \"error\";\n runId: string;\n operation: \"start\" | \"cancel\";\n error: { code: GoalRunErrorCode; message: string };\n };\n\ninterface GoalRunStartPayload {\n runId: string;\n objective: string;\n tokenBudget?: number;\n}\n\ninterface BoundSession {\n generation: number;\n ctx: StatusContext;\n}\n\ninterface ManagedRun {\n runId: string;\n generation: number;\n goalId?: string;\n lastStatus?: GoalRunStatus;\n closed: boolean;\n cancelRequested: boolean;\n cancelReason?: string;\n}\n\nexport function goalRunEventChannel(runId: string) {\n return `pi-goal:event:${runId}`;\n}\n\nfunction isPayloadRecord(data: unknown): data is object {\n if (!data || typeof data !== \"object\") return false;\n try {\n return !Array.isArray(data);\n } catch {\n return false;\n }\n}\n\nfunction readPayloadProperty(\n data: object,\n key: \"runId\" | \"objective\" | \"tokenBudget\" | \"reason\",\n): { ok: true; value: unknown } | { ok: false } {\n try {\n return { ok: true, value: Reflect.get(data, key) };\n } catch {\n return { ok: false };\n }\n}\n\nfunction parseRunId(data: unknown): string | undefined {\n if (!isPayloadRecord(data)) return undefined;\n const runId = readPayloadProperty(data, \"runId\");\n return runId.ok && typeof runId.value === \"string\" && RUN_ID_PATTERN.test(runId.value) ? runId.value : undefined;\n}\n\nfunction currentActiveGoal(runtime: GoalRuntime) {\n return runtime.activeGoal;\n}\n\nfunction parseStartPayload(data: unknown): string | Omit<GoalRunStartPayload, \"runId\"> {\n if (!isPayloadRecord(data)) return \"start payload must be an object\";\n const objectiveValue = readPayloadProperty(data, \"objective\");\n if (!objectiveValue.ok || typeof objectiveValue.value !== \"string\") {\n return \"objective must be a string\";\n }\n const objective = objectiveValue.value.trim();\n const objectiveError = validateObjective(objective);\n if (objectiveError) return objectiveError;\n const tokenBudgetValue = readPayloadProperty(data, \"tokenBudget\");\n if (\n !tokenBudgetValue.ok ||\n (tokenBudgetValue.value !== undefined &&\n (typeof tokenBudgetValue.value !== \"number\" ||\n !Number.isFinite(tokenBudgetValue.value) ||\n !Number.isSafeInteger(tokenBudgetValue.value) ||\n tokenBudgetValue.value <= 0))\n ) {\n return \"tokenBudget must be a positive integer\";\n }\n return { objective, tokenBudget: tokenBudgetValue.value as number | undefined };\n}\n\nfunction parseCancelReason(data: unknown): string | undefined | { error: string } {\n if (!isPayloadRecord(data)) return { error: \"cancel payload must be an object\" };\n const reasonValue = readPayloadProperty(data, \"reason\");\n if (!reasonValue.ok || (reasonValue.value !== undefined && typeof reasonValue.value !== \"string\")) {\n return { error: \"reason must be a string\" };\n }\n if (reasonValue.value === undefined) return undefined;\n const reason = reasonValue.value.trim();\n if (reason.length > MAX_CANCEL_REASON_LENGTH) {\n return { error: `reason must be at most ${MAX_CANCEL_REASON_LENGTH} characters` };\n }\n return reason || undefined;\n}\n\nexport class GoalRunController {\n private readonly runtime: GoalRuntime;\n private readonly commands: GoalCommandController;\n private generation = 0;\n private session?: BoundSession;\n private run?: ManagedRun;\n private readonly usedRunIds = new Set<string>();\n\n constructor(runtime: GoalRuntime, commands: GoalCommandController) {\n this.runtime = runtime;\n this.commands = commands;\n this.runtime.setGoalStateSink((snapshot) => this.handleGoalState(snapshot));\n }\n\n register(pi: ExtensionAPI) {\n pi.events.on(GOAL_RUN_START_CHANNEL, (data) => this.handleStart(data));\n pi.events.on(GOAL_RUN_CANCEL_CHANNEL, (data) => {\n this.handleCancel(data);\n });\n }\n\n bindSession(ctx: StatusContext) {\n this.generation += 1;\n this.session = { generation: this.generation, ctx };\n this.closeCurrentRun();\n this.usedRunIds.clear();\n }\n\n unbindSession() {\n this.generation += 1;\n this.session = undefined;\n this.closeCurrentRun();\n this.usedRunIds.clear();\n }\n\n private async handleStart(data: unknown) {\n const runId = parseRunId(data);\n if (!runId) return;\n const session = this.session;\n if (!session) {\n this.emitError(runId, \"start\", \"NO_ACTIVE_SESSION\", \"No active pi-goal session.\");\n return;\n }\n if (!this.runtime.settings.rpc.enabled) {\n this.emitError(runId, \"start\", \"RPC_DISABLED\", \"Managed run RPC is disabled.\");\n return;\n }\n if (this.usedRunIds.has(runId)) {\n this.emitError(runId, \"start\", \"RUN_ID_IN_USE\", \"runId was already used in this session.\");\n return;\n }\n const parsed = parseStartPayload(data);\n if (typeof parsed === \"string\") {\n this.emitError(runId, \"start\", \"INVALID_REQUEST\", parsed);\n return;\n }\n if (this.session !== session || this.generation !== session.generation) {\n this.emitError(runId, \"start\", \"SUPERSEDED\", \"The pi-goal session changed while validating the request.\");\n return;\n }\n if (this.usedRunIds.has(runId)) {\n this.emitError(runId, \"start\", \"RUN_ID_IN_USE\", \"runId was already used in this session.\");\n return;\n }\n if (this.runtime.activeGoal || (this.run && !this.run.closed)) {\n this.emitError(runId, \"start\", \"GOAL_ALREADY_EXISTS\", \"A Goal already exists.\");\n return;\n }\n\n const run: ManagedRun = {\n runId,\n generation: session.generation,\n closed: false,\n cancelRequested: false,\n };\n this.run = run;\n this.usedRunIds.add(runId);\n\n try {\n const activation = await this.commands.startGoal(\n parsed.objective,\n parsed.tokenBudget,\n session.ctx,\n (goal) => {\n if (this.ownsRun(run, session.generation)) run.goalId = goal.id;\n },\n () => this.ownsRun(run, session.generation),\n );\n if (activation?.kind === \"busy\" && this.ownsRun(run, session.generation)) {\n this.closeCurrentRun();\n this.emitError(\n runId,\n \"start\",\n \"ACTIVATION_FAILED\",\n \"Another workflow is active in this session. End it before starting Goal.\",\n );\n return;\n }\n } catch (error) {\n if (this.ownsRun(run, session.generation)) {\n this.closeCurrentRun();\n this.emitError(runId, \"start\", \"ACTIVATION_FAILED\", `Goal activation failed: ${formatError(error)}`);\n }\n return;\n }\n\n if (!this.ownsRun(run, session.generation)) return;\n if (!run.goalId) {\n this.closeCurrentRun();\n this.emitError(runId, \"start\", \"ACTIVATION_FAILED\", \"Goal activation did not create a Goal.\");\n return;\n }\n if (currentActiveGoal(this.runtime)?.id !== run.goalId) {\n this.closeCurrentRun();\n this.emitError(runId, \"start\", \"SUPERSEDED\", \"The managed Goal was superseded.\");\n return;\n }\n if (run.cancelRequested) this.cancelActiveRun(run, session, run.cancelReason);\n }\n\n private handleCancel(data: unknown) {\n const runId = parseRunId(data);\n if (!runId) return;\n const session = this.session;\n if (!session) {\n this.emitError(runId, \"cancel\", \"NO_ACTIVE_SESSION\", \"No active pi-goal session.\");\n return;\n }\n const reason = parseCancelReason(data);\n if (reason && typeof reason === \"object\") {\n this.emitError(runId, \"cancel\", \"INVALID_REQUEST\", reason.error);\n return;\n }\n const run = this.run;\n if (!run || run.closed || run.runId !== runId || run.generation !== session.generation) {\n this.emitError(runId, \"cancel\", \"RUN_NOT_FOUND\", \"No active managed run matches runId.\");\n return;\n }\n if (!run.goalId) {\n run.cancelRequested = true;\n run.cancelReason = reason;\n return;\n }\n this.cancelActiveRun(run, session, reason);\n }\n\n private cancelActiveRun(run: ManagedRun, session: BoundSession, reason: string | undefined) {\n if (!this.ownsRun(run, session.generation)) return;\n const goal = this.runtime.activeGoal;\n if (!goal || goal.id !== run.goalId) {\n this.closeCurrentRun();\n this.emitError(run.runId, \"cancel\", \"SUPERSEDED\", \"The managed Goal was superseded.\");\n return;\n }\n if (goal.status !== \"active\") {\n this.closeCurrentRun();\n this.emitError(run.runId, \"cancel\", \"RUN_NOT_FOUND\", \"The managed run is no longer active.\");\n return;\n }\n this.runtime.setTerminalReason(goal.id, reason ?? \"goal cancelled by managed run\");\n this.commands.pauseGoal(session.ctx);\n }\n\n private handleGoalState(snapshot: GoalStateSnapshot) {\n const run = this.run;\n if (!run || run.closed || !run.goalId) return;\n if (run.goalId !== snapshot.goalId) {\n if (currentActiveGoal(this.runtime)?.id !== snapshot.goalId) return;\n this.publishStateEvent(run, {\n goalId: run.goalId,\n status: \"cleared\",\n reason: \"managed Goal superseded by another Goal\",\n });\n return;\n }\n if (run.lastStatus === snapshot.status) return;\n this.publishStateEvent(run, snapshot);\n }\n\n private publishStateEvent(\n run: ManagedRun,\n snapshot: Pick<GoalStateSnapshot, \"goalId\" | \"status\" | \"summary\" | \"reason\">,\n ) {\n const status = snapshot.status;\n run.lastStatus = status;\n const event: GoalRunEvent = {\n type: \"state\",\n runId: run.runId,\n goalId: snapshot.goalId,\n status,\n ...(snapshot.summary ? { summary: snapshot.summary } : {}),\n ...(snapshot.reason ? { reason: snapshot.reason } : {}),\n };\n if (!isTerminalGoalStatus(status)) {\n this.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);\n return;\n }\n\n run.closed = true;\n this.run = undefined;\n const generation = run.generation;\n // Active stays synchronous so a listener can cancel before kickoff. Terminal\n // publication waits until the transition finishes, preventing listener work\n // from being overwritten by the old transition's remaining UI or cleanup.\n queueMicrotask(() => {\n if (this.generation !== generation) return;\n this.runtime.pi.events.emit(goalRunEventChannel(run.runId), event);\n });\n }\n\n private emitError(runId: string, operation: \"start\" | \"cancel\", code: GoalRunErrorCode, message: string) {\n this.runtime.pi.events.emit(goalRunEventChannel(runId), {\n type: \"error\",\n runId,\n operation,\n error: { code, message },\n } satisfies GoalRunEvent);\n }\n\n private ownsRun(run: ManagedRun, generation: number) {\n return this.session?.generation === generation && this.generation === generation && this.run === run && !run.closed;\n }\n\n private closeCurrentRun() {\n if (this.run) this.run.closed = true;\n this.run = undefined;\n }\n}\n", "import {\n DEFAULT_MAX_BYTES,\n DEFAULT_MAX_LINES,\n defineTool,\n type ExtensionAPI,\n getMarkdownTheme,\n truncateHead,\n} from \"@earendil-works/pi-coding-agent\";\nimport { Markdown } from \"@earendil-works/pi-tui\";\nimport { Type } from \"typebox\";\nimport { notifyTerminal, safeTerminalText } from \"./errors.js\";\nimport {\n formatStatus,\n GOAL_BLOCKED_TOOL,\n GOAL_COMPLETE_TOOL,\n GOAL_WAIT_TOOL,\n type GoalRuntime,\n goalIdRejectionReason,\n isContradictoryCompletionSummary,\n MAX_GOAL_ID_LENGTH,\n STATUS_KEY,\n transitionGoal,\n truncateNotification,\n} from \"./runtime.js\";\nimport {\n createGoalWait,\n MAX_GOAL_WAIT_DELAY_MS,\n MAX_GOAL_WAIT_REASON_LENGTH,\n MIN_GOAL_WAIT_DELAY_MS,\n resolveGoalWaitDelay,\n} from \"./wait.js\";\n\ninterface GoalCompleteDetails {\n goal: string;\n goal_id: string;\n summary: string;\n}\n\ninterface GoalBlockedDetails {\n goal: string;\n goal_id: string;\n reason: string;\n evidence: string;\n repeated_turns: number;\n}\n\ninterface GoalWaitDetails {\n goal: string;\n goal_id: string;\n reason: string;\n requested_resume_after_ms?: number;\n resume_after_ms?: number;\n resume_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 const goalCompleteTool = defineTool({\n name: GOAL_COMPLETE_TOOL,\n label: \"Goal Complete\",\n description:\n \"Mark an active /goal complete only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and every requirement is verified. Tool visibility alone does not activate Goal mode. Never call for ordinary work, partial progress, blockers, failures, or unverified work.\",\n parameters: Type.Object({\n goal_id: Type.String({\n minLength: 1,\n maxLength: MAX_GOAL_ID_LENGTH,\n description:\n \"The exact goal_id shown in the current active /goal prompt. Used only to reject stale completion calls from older turns.\",\n }),\n summary: Type.String({\n minLength: 1,\n maxLength: MAX_COMPLETION_SUMMARY_LENGTH,\n description:\n \"State what was completed and what evidence verified it. Do not use this tool to report partial progress, blockers, failures, or remaining work.\",\n }),\n }),\n renderResult(result) {\n return renderGoalCompletion(result);\n },\n async execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n const completedGoal = runtime.activeGoal;\n const goal = completedGoal?.text ?? \"unknown goal\";\n const requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n const summary = typeof params.summary === \"string\" ? params.summary.trim() : \"\";\n\n if (!completedGoal) {\n const rejection = \"Goal completion rejected: no active goal.\";\n notifyTerminal(ctx.ui, rejection, \"warning\");\n\n return {\n content: toolContent(rejection),\n details: completionDetails(goal, requestedGoalId, summary),\n };\n }\n const completingDuringBudgetWrapUp = runtime.hasActiveBudgetWrapUp();\n if (completedGoal.status === \"active\" && !runtime.ownsWorkflow(completedGoal)) {\n const rejection = \"Goal completion rejected: active Goal no longer owns its workflow.\";\n notifyTerminal(ctx.ui, rejection, \"warning\");\n return {\n content: toolContent(rejection),\n details: completionDetails(goal, requestedGoalId, summary),\n };\n }\n if (!runtime.canRecordGoalUsage() && !completingDuringBudgetWrapUp) {\n const rejection = \"Goal completion rejected: current run does not own the active goal.\";\n notifyTerminal(ctx.ui, rejection, \"warning\");\n return {\n content: toolContent(rejection),\n details: completionDetails(goal, requestedGoalId, summary),\n };\n }\n const staleGoalRejection = goalIdRejectionReason(completedGoal, requestedGoalId);\n if (staleGoalRejection) {\n const rejection = `Goal completion rejected: ${staleGoalRejection}.`;\n notifyTerminal(ctx.ui, rejection, \"warning\");\n if (completingDuringBudgetWrapUp) {\n runtime.recordGoalUsage(completedGoal, ctx);\n runtime.persistGoal(completedGoal);\n runtime.updateStatus(ctx, completedGoal);\n runtime.clearBudgetWrapUp();\n }\n\n return {\n content: toolContent(rejection),\n details: completionDetails(goal, requestedGoalId, summary),\n terminate: completingDuringBudgetWrapUp || undefined,\n };\n }\n if (completedGoal.status !== \"active\" && !completingDuringBudgetWrapUp) {\n const rejection = `Goal completion rejected: goal is ${completedGoal.status}, not active.`;\n notifyTerminal(ctx.ui, rejection, \"warning\");\n\n return {\n content: toolContent(rejection),\n details: completionDetails(goal, requestedGoalId, summary),\n };\n }\n\n const rejectionReason = !summary\n ? \"summary is empty\"\n : summary.length > MAX_COMPLETION_SUMMARY_LENGTH\n ? \"summary is too long\"\n : isContradictoryCompletionSummary(summary)\n ? \"summary says the goal is not complete\"\n : undefined;\n if (rejectionReason) {\n runtime.recordGoalUsage(completedGoal, ctx);\n runtime.persistGoal(completedGoal);\n runtime.updateStatus(ctx, completedGoal);\n const rejection = `Goal completion rejected: ${rejectionReason}.`;\n notifyTerminal(ctx.ui, rejection, \"warning\");\n if (completingDuringBudgetWrapUp) runtime.clearBudgetWrapUp();\n\n return {\n content: toolContent(rejection),\n details: completionDetails(goal, requestedGoalId, summary),\n terminate: completingDuringBudgetWrapUp || undefined,\n };\n }\n\n runtime.clearGoalWaitTimer();\n runtime.activeGoal = transitionGoal(completedGoal, \"complete\");\n runtime.setCompletionSummary(runtime.activeGoal.id, summary);\n runtime.recordGoalUsage(runtime.activeGoal, ctx);\n runtime.persistGoal(runtime.activeGoal);\n\n ctx.ui.setStatus(STATUS_KEY, formatStatus(runtime.activeGoal));\n runtime.clearCompletedGoal(ctx);\n runtime.showCompletionStatus(ctx);\n notifyTerminal(ctx.ui, `Goal complete: ${goal}`, \"info\");\n\n return {\n content: toolContent(`Goal complete: ${summary}`),\n details: completionDetails(goal, requestedGoalId, summary),\n terminate: true,\n };\n },\n });\n\n const goalBlockedTool = defineTool({\n name: GOAL_BLOCKED_TOOL,\n label: \"Goal Blocked\",\n description:\n \"Stop an active /goal only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and the same evidenced external blocker recurred for at least three consecutive Goal turns. Tool visibility alone does not activate Goal mode. Never call for ordinary clarification, uncertainty, incomplete work, or recoverable failures.\",\n parameters: Type.Object({\n goal_id: Type.String({\n minLength: 1,\n maxLength: MAX_GOAL_ID_LENGTH,\n description: \"The exact goal_id shown in the current active /goal prompt.\",\n }),\n reason: Type.String({\n minLength: 1,\n maxLength: MAX_BLOCKER_REASON_LENGTH,\n description: \"The specific user or external action required to unblock the goal.\",\n }),\n evidence: Type.String({\n minLength: 1,\n maxLength: MAX_BLOCKER_EVIDENCE_LENGTH,\n description: \"Concrete evidence from the repeated attempts that proves the impasse.\",\n }),\n repeated_turns: Type.Integer({\n minimum: 3,\n description: \"Number of separate turns spent trying to resolve this same blocker.\",\n }),\n }),\n async execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n const blockedGoal = runtime.activeGoal;\n const goal = blockedGoal?.text ?? \"unknown goal\";\n const requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n const reason = typeof params.reason === \"string\" ? params.reason.trim() : \"\";\n const evidence = typeof params.evidence === \"string\" ? params.evidence.trim() : \"\";\n const repeatedTurns = typeof params.repeated_turns === \"number\" ? params.repeated_turns : Number.NaN;\n const reject = (rejectionReason: string, terminate = false) => {\n const rejection = `goal_blocked rejected: ${rejectionReason}.`;\n notifyTerminal(ctx.ui, rejection, \"warning\");\n return {\n content: toolContent(rejection),\n details: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),\n ...(terminate ? { terminate: true as const } : {}),\n };\n };\n\n if (!blockedGoal) return reject(\"no active goal\");\n if (!runtime.canRecordGoalUsage()) {\n return reject(\"current run does not own the active goal\");\n }\n const staleGoalRejection = goalIdRejectionReason(blockedGoal, requestedGoalId);\n if (staleGoalRejection) return reject(staleGoalRejection);\n if (blockedGoal.status !== \"active\") {\n return reject(`goal is ${blockedGoal.status}, not active`);\n }\n if (!runtime.ownsWorkflow(blockedGoal)) return reject(\"active Goal no longer owns its workflow\");\n if (!reason) return reject(\"reason is empty\");\n if (reason.length > MAX_BLOCKER_REASON_LENGTH) return reject(\"reason is too long\");\n if (!evidence) return reject(\"evidence is empty\");\n if (evidence.length > MAX_BLOCKER_EVIDENCE_LENGTH) return reject(\"evidence is too long\");\n if (!Number.isInteger(repeatedTurns)) return reject(\"repeated_turns must be a whole number\");\n if (repeatedTurns < 3) return reject(\"repeated_turns must be at least 3\");\n\n const stoppedGoal = runtime.stopActiveGoal(ctx, {\n kind: \"blocker_report\",\n expectedGoalId: blockedGoal.id,\n reason,\n });\n if (!stoppedGoal) return reject(\"active goal changed before blocker transition\");\n notifyTerminal(ctx.ui, `Goal blocked: ${truncateNotification(reason)}`, \"warning\");\n\n return {\n content: toolContent(`Goal blocked: ${reason}`),\n details: blockerDetails(goal, requestedGoalId, reason, evidence, repeatedTurns),\n terminate: true,\n };\n },\n });\n\n const goalWaitTool = defineTool({\n name: GOAL_WAIT_TOOL,\n label: \"Goal Wait\",\n description: `Keep an active /goal quiet only when the latest effective Goal contract explicitly says Goal mode is active, supplies the matching current goal_id, and progress depends on an arranged external wake event or one safety deadline. Tool visibility alone does not activate Goal mode. Call goal_wait alone. Requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms. Never call for ordinary unfinished work.`,\n parameters: Type.Object({\n goal_id: Type.String({\n minLength: 1,\n maxLength: MAX_GOAL_ID_LENGTH,\n description: \"The exact goal_id shown in the current active /goal prompt.\",\n }),\n reason: Type.String({\n minLength: 1,\n maxLength: MAX_GOAL_WAIT_REASON_LENGTH,\n description: \"Why the goal is waiting and which external event should wake it.\",\n }),\n resume_after_ms: Type.Optional(\n Type.Integer({\n minimum: 1,\n maximum: MAX_GOAL_WAIT_DELAY_MS,\n description: `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 }),\n ),\n }),\n async execute(_toolCallId, params, _signal, _onUpdate, ctx) {\n const activeGoal = runtime.activeGoal;\n const goal = activeGoal?.text ?? \"unknown goal\";\n const requestedGoalId = typeof params.goal_id === \"string\" ? params.goal_id.trim() : \"\";\n const reason = typeof params.reason === \"string\" ? params.reason.trim() : \"\";\n const resumeAfterMs = typeof params.resume_after_ms === \"number\" ? params.resume_after_ms : undefined;\n const reject = (rejectionReason: string) => {\n const rejection = `goal_wait rejected: ${rejectionReason}.`;\n notifyTerminal(ctx.ui, rejection, \"warning\");\n return {\n content: toolContent(rejection),\n details: waitDetails(goal, requestedGoalId, reason, resumeAfterMs),\n };\n };\n\n if (!activeGoal) return reject(\"no active goal\");\n if (!runtime.canRecordGoalUsage()) {\n return reject(\"current run does not own the active goal\");\n }\n const staleGoalRejection = goalIdRejectionReason(activeGoal, requestedGoalId);\n if (staleGoalRejection) return reject(staleGoalRejection);\n if (activeGoal.status !== \"active\") {\n return reject(`goal is ${activeGoal.status}, not active`);\n }\n if (!runtime.ownsWorkflow(activeGoal)) return reject(\"active Goal no longer owns its workflow\");\n if (activeGoal.waiting) return reject(\"goal is already waiting\");\n if (!reason) return reject(\"reason is empty\");\n if (reason.length > MAX_GOAL_WAIT_REASON_LENGTH) return reject(\"reason is too long\");\n if (\n resumeAfterMs !== undefined &&\n (!Number.isInteger(resumeAfterMs) || resumeAfterMs < 1 || resumeAfterMs > MAX_GOAL_WAIT_DELAY_MS)\n ) {\n return reject(`resume_after_ms must be a whole number from 1 to ${MAX_GOAL_WAIT_DELAY_MS}`);\n }\n\n const { requestedMs, effectiveMs } = resolveGoalWaitDelay(resumeAfterMs);\n const waiting = createGoalWait(reason, resumeAfterMs);\n const waitingGoal = runtime.enterGoalWait(ctx, activeGoal.id, waiting);\n if (!waitingGoal) return reject(\"active goal changed before waiting transition\");\n const clamped = requestedMs !== undefined && effectiveMs !== requestedMs;\n notifyTerminal(ctx.ui, `Goal waiting: ${truncateNotification(reason)}`, \"info\");\n return {\n content: toolContent(\n clamped\n ? `Goal waiting: ${reason}\\nRequested resume_after_ms ${requestedMs} was clamped to ${effectiveMs}.`\n : `Goal waiting: ${reason}`,\n ),\n details: waitDetails(\n goal,\n requestedGoalId,\n reason,\n effectiveMs,\n waiting.resumeAt,\n clamped ? requestedMs : undefined,\n ),\n terminate: true,\n };\n },\n });\n\n pi.registerTool(goalCompleteTool);\n pi.registerTool(goalBlockedTool);\n pi.registerTool(goalWaitTool);\n}\n\ninterface GoalCompletionRenderResult {\n content: Array<{ type: string; text?: string }>;\n details?: unknown;\n}\n\nexport function goalCompletionMarkdown(result: GoalCompletionRenderResult) {\n const content = result.content\n .filter((block) => block.type === \"text\" && typeof block.text === \"string\")\n .map((block) => block.text)\n .join(\"\\n\")\n .trim();\n const completionPrefix = \"Goal complete:\";\n if (!content.startsWith(completionPrefix)) return content;\n\n const details = result.details;\n const summary =\n details && typeof details === \"object\" && \"summary\" in details && typeof details.summary === \"string\"\n ? details.summary\n : content.slice(completionPrefix.length);\n const safeSummary = safeTerminalText(summary);\n return safeSummary ? `**Goal complete**\\n\\n${safeSummary}` : \"**Goal complete**\";\n}\n\nexport function renderGoalCompletion(result: GoalCompletionRenderResult) {\n return new Markdown(goalCompletionMarkdown(result), 0, 0, getMarkdownTheme());\n}\n\nfunction toolContent(text: string) {\n return [\n {\n type: \"text\" as const,\n text: truncateHead(safeTerminalText(text), {\n maxBytes: DEFAULT_MAX_BYTES,\n maxLines: DEFAULT_MAX_LINES,\n }).content,\n },\n ];\n}\n\nfunction completionDetails(goal: string, goalId: string, summary: string): GoalCompleteDetails {\n return {\n goal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n summary: summary.slice(0, MAX_COMPLETION_SUMMARY_LENGTH),\n };\n}\n\nfunction blockerDetails(\n goal: string,\n goalId: string,\n reason: string,\n evidence: string,\n repeatedTurns: number,\n): GoalBlockedDetails {\n return {\n goal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n reason: reason.slice(0, MAX_BLOCKER_REASON_LENGTH),\n evidence: evidence.slice(0, MAX_BLOCKER_EVIDENCE_LENGTH),\n repeated_turns: Number.isFinite(repeatedTurns) ? repeatedTurns : 0,\n };\n}\n\nfunction waitDetails(\n goal: string,\n goalId: string,\n reason: string,\n resumeAfterMs: number | undefined,\n resumeAt?: number,\n requestedResumeAfterMs?: number,\n): GoalWaitDetails {\n return {\n goal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),\n goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),\n reason: reason.slice(0, MAX_GOAL_WAIT_REASON_LENGTH),\n ...(requestedResumeAfterMs === undefined ? {} : { requested_resume_after_ms: requestedResumeAfterMs }),\n ...(resumeAfterMs === undefined ? {} : { resume_after_ms: resumeAfterMs }),\n ...(resumeAt === undefined ? {} : { resume_at: resumeAt }),\n };\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 settingsPath?: string;\n}\n\nfunction registerGoalRuntime(pi: ExtensionAPI, options: GoalOptions = {}) {\n const runtime = new GoalRuntime(pi);\n const commands = new GoalCommandController(runtime);\n const runController = new GoalRunController(runtime, commands);\n\n // Keep registration order explicit: managed-run bus listeners exist before tools,\n // command routing, and session lifecycle bind the per-factory runtime.\n runController.register(pi);\n registerGoalTools(pi, runtime);\n registerGoalCommand(pi, runtime, commands, options);\n registerGoalLifecycle(pi, runtime, runController, options);\n}\n\nexport default function goal(pi: ExtensionAPI, options: GoalOptions = {}) {\n registerGoalRuntime(pi, options);\n}\n\nexport {\n assistantUsageTokens,\n cumulativeAssistantTokens,\n formatDuration,\n formatTokenCount,\n} from \"./accounting.js\";\n\nexport {\n completeGoalArguments,\n parseCommand,\n parseTokenBudget,\n validateObjective,\n} from \"./command.js\";\n\nexport { buildGoalSystemPrompt } from \"./prompts.js\";\n\nexport {\n findFinalAssistantMessage,\n formatStatus,\n isContradictoryCompletionSummary,\n isRetryableGoalInterruption,\n isUsageLimitedGoalInterruption,\n} from \"./runtime.js\";\n"],
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,SAAS,oBACd,IACA,SACA,UACA,UAA0C,CAAC,GAC3C;AACA,QAAM,kBAAkB,mBAAmB,QAAQ,oBAAoB,MAAM,OAAO,2BAAW,EAAE;AACjG,QAAM,mBAAmB,mBAAmB,QAAQ,qBAAqB,MAAM,OAAO,kCAAkB,EAAE;AAE1G,KAAG,gBAAgB,QAAQ;AAAA,IACzB,aAAa;AAAA,IACb,wBAAwB,CAAC,WAAW,sBAAsB,MAAM;AAAA,IAChE,SAAS,OAAO,MAAM,QAAQ;AAC5B,UAAI;AACF,YAAI,QAAQ,wBAAwB,KAAK,sBAAsB,IAAI,GAAG;AACpE,oCAA0B,KAAK,OAAO;AACtC;A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