@narumitw/pi-goal 0.53.1 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/settings-ui.ts"],
4
+ "sourcesContent": ["import { join } from \"node:path\";\nimport { type ExtensionCommandContext, getAgentDir } from \"@earendil-works/pi-coding-agent\";\nimport { notifyTerminal, safeTerminalText } from \"./errors.js\";\nimport type { GoalRuntime } from \"./runtime.js\";\nimport {\n\tDEFAULT_GOAL_SETTINGS,\n\tGOAL_SETTINGS_FILE,\n\ttype GoalSettings,\n\tsaveGoalSettings,\n} from \"./settings.js\";\n\ninterface GoalSettingsUiOptions {\n\tsettingsPath?: string;\n\tinitialScreen?: \"settings\" | \"automatic\";\n\tsave?: (settings: GoalSettings, settingsPath: string) => void;\n}\n\ninterface GoalSettingsApplyOptions {\n\tsave?: (settings: GoalSettings) => void;\n}\n\ntype LimitField = \"automaticTurns\" | \"noProgressTurns\";\ntype LimitSelection = \"unlimited\" | \"default\" | \"custom\" | \"off\";\nexport async function showGoalSettings(\n\truntime: GoalRuntime,\n\tctx: ExtensionCommandContext,\n\toptions: GoalSettingsUiOptions = {},\n) {\n\tconst settingsPath = options.settingsPath ?? join(getAgentDir(), GOAL_SETTINGS_FILE);\n\tif (ctx.mode !== \"tui\") {\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\n\t\t\t`Edit pi-goal settings manually: ${safeTerminalText(settingsPath)}`,\n\t\t\t\"info\",\n\t\t);\n\t\treturn;\n\t}\n\tconst generation = runtime.menuGeneration;\n\tconst isMenuCurrent = () =>\n\t\tgeneration === runtime.menuGeneration && !runtime.menuController.signal.aborted;\n\tconst { defineMenu, runMenu } = await import(\"@narumitw/pi-tui-kit\");\n\tif (!isMenuCurrent()) return;\n\tconst invalid = runtime.settingsLoadIssue?.kind === \"invalid\";\n\tconst previewGoalIds = new Map<LimitField, string | null>();\n\ttype Screen = \"settings\" | \"automatic\" | \"no-progress\" | \"invalid\";\n\ttype Action =\n\t\t| \"open-automatic\"\n\t\t| \"open-no-progress\"\n\t\t| \"choose-automatic\"\n\t\t| \"choose-no-progress\"\n\t\t| \"set-rpc\";\n\tconst menu = defineMenu<undefined, Screen, Action, ExtensionCommandContext>({\n\t\tstart: invalid ? \"invalid\" : (options.initialScreen ?? \"settings\"),\n\t\tscreens: {\n\t\t\tsettings: () => ({\n\t\t\t\tkind: \"settings\",\n\t\t\t\ttitle: \"Pi Goal Settings\",\n\t\t\t\tlines: [`User settings \u00B7 ${safeTerminalText(settingsPath)}`],\n\t\t\t\titems: [\n\t\t\t\t\t{\n\t\t\t\t\t\tid: \"automaticTurns\",\n\t\t\t\t\t\tlabel: \"Automatic-work limit\",\n\t\t\t\t\t\tdescription: \"Pause automatic Goal work after a visible number of model responses.\",\n\t\t\t\t\t\tcurrentValue: formatAutomaticSettingValue(\n\t\t\t\t\t\t\truntime.settings.continuationLimits.automaticTurns,\n\t\t\t\t\t\t),\n\t\t\t\t\t\taction: \"open-automatic\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tid: \"noProgressTurns\",\n\t\t\t\t\t\tlabel: \"No-progress guard\",\n\t\t\t\t\t\tdescription: \"Pause after repeated or empty tool-free automatic runs.\",\n\t\t\t\t\t\tcurrentValue: formatNoProgressSettingValue(\n\t\t\t\t\t\t\truntime.settings.continuationLimits.noProgressTurns,\n\t\t\t\t\t\t),\n\t\t\t\t\t\taction: \"open-no-progress\",\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tid: \"rpcEnabled\",\n\t\t\t\t\t\tlabel: \"Managed run RPC\",\n\t\t\t\t\t\tdescription:\n\t\t\t\t\t\t\t\"Allow trusted installed extensions to start and cancel Goal runs; this is not an extension sandbox.\",\n\t\t\t\t\t\tcurrentValue: runtime.settings.rpc.enabled ? \"On\" : \"Off\",\n\t\t\t\t\t\tvalues: [\"Off\", \"On\"],\n\t\t\t\t\t\taction: \"set-rpc\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t}),\n\t\t\tautomatic: () => limitChoiceScreen(runtime, \"automaticTurns\", \"choose-automatic\"),\n\t\t\t\"no-progress\": () => limitChoiceScreen(runtime, \"noProgressTurns\", \"choose-no-progress\"),\n\t\t\tinvalid: () => ({\n\t\t\t\tkind: \"detail\",\n\t\t\t\ttitle: \"Pi Goal Settings \u00B7 Read only\",\n\t\t\t\tlines: [\n\t\t\t\t\t`Invalid settings file. Pi-goal is using built-in defaults. Fix ${safeTerminalText(settingsPath)} and run /reload. The file will not be overwritten.`,\n\t\t\t\t\t`Automatic-work limit: ${formatAutomaticWork(runtime.settings.continuationLimits.automaticTurns)}`,\n\t\t\t\t\t`No-progress guard: ${formatNoProgressProtection(runtime.settings.continuationLimits.noProgressTurns)}`,\n\t\t\t\t\t`Managed run RPC: ${runtime.settings.rpc.enabled ? \"On\" : \"Off\"}`,\n\t\t\t\t],\n\t\t\t\thint: \"back\",\n\t\t\t}),\n\t\t},\n\t\tactions: {\n\t\t\t\"open-automatic\": async () => {\n\t\t\t\tpreviewGoalIds.set(\"automaticTurns\", runtime.activeGoal?.id ?? null);\n\t\t\t\treturn { kind: \"to\", screen: \"automatic\" };\n\t\t\t},\n\t\t\t\"open-no-progress\": async () => {\n\t\t\t\tpreviewGoalIds.set(\"noProgressTurns\", runtime.activeGoal?.id ?? null);\n\t\t\t\treturn { kind: \"to\", screen: \"no-progress\" };\n\t\t\t},\n\t\t\t\"choose-automatic\": async ({ itemId }) =>\n\t\t\t\tapplyLimitChoice(\n\t\t\t\t\truntime,\n\t\t\t\t\tctx,\n\t\t\t\t\toptions,\n\t\t\t\t\tsettingsPath,\n\t\t\t\t\t\"automaticTurns\",\n\t\t\t\t\titemId,\n\t\t\t\t\tpreviewGoalIds.get(\"automaticTurns\") ?? null,\n\t\t\t\t\tisMenuCurrent,\n\t\t\t\t),\n\t\t\t\"choose-no-progress\": async ({ itemId }) =>\n\t\t\t\tapplyLimitChoice(\n\t\t\t\t\truntime,\n\t\t\t\t\tctx,\n\t\t\t\t\toptions,\n\t\t\t\t\tsettingsPath,\n\t\t\t\t\t\"noProgressTurns\",\n\t\t\t\t\titemId,\n\t\t\t\t\tpreviewGoalIds.get(\"noProgressTurns\") ?? null,\n\t\t\t\t\tisMenuCurrent,\n\t\t\t\t),\n\t\t\t\"set-rpc\": async ({ value }) => {\n\t\t\t\tconst enabled = value === \"On\";\n\t\t\t\tif (enabled === runtime.settings.rpc.enabled) return { kind: \"stay\" };\n\t\t\t\ttry {\n\t\t\t\t\tconst next = {\n\t\t\t\t\t\t...structuredClone(runtime.settings),\n\t\t\t\t\t\trpc: { enabled },\n\t\t\t\t\t} satisfies GoalSettings;\n\t\t\t\t\tapplyGoalSettings(runtime, next, ctx, {\n\t\t\t\t\t\tsave: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),\n\t\t\t\t\t});\n\t\t\t\t\tnotifyTerminal(ctx.ui, `Managed run RPC: ${enabled ? \"On\" : \"Off\"}.`, \"info\");\n\t\t\t\t\treturn { kind: \"stay\" };\n\t\t\t\t} catch (error) {\n\t\t\t\t\tnotifySettingsFailure(ctx, settingsPath, error);\n\t\t\t\t\treturn { kind: \"rejected\" };\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t});\n\tawait runMenu(ctx, menu, {\n\t\tgetState: () => undefined,\n\t\tsignal: runtime.menuController.signal,\n\t\tisCurrent: isMenuCurrent,\n\t});\n}\n\nfunction limitChoiceScreen(\n\truntime: GoalRuntime,\n\tfield: LimitField,\n\taction: \"choose-automatic\" | \"choose-no-progress\",\n) {\n\tconst value = runtime.settings.continuationLimits[field];\n\tconst goal = runtime.activeGoal;\n\treturn {\n\t\tkind: \"actions\" as const,\n\t\ttitle: field === \"automaticTurns\" ? \"Automatic-work limit\" : \"No-progress guard\",\n\t\tlines: [\n\t\t\tfield === \"automaticTurns\"\n\t\t\t\t? `Current: ${formatAutomaticWork(value)}`\n\t\t\t\t: `Current: ${formatNoProgressProtection(value)}`,\n\t\t\t...(field === \"automaticTurns\"\n\t\t\t\t? [\n\t\t\t\t\t\t`Set a whole-number response limit for each automatic-work epoch. Default: ${DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns}.`,\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t\t\t...(goal\n\t\t\t\t? [\n\t\t\t\t\t\tfield === \"automaticTurns\"\n\t\t\t\t\t\t\t? `Active goal: ${goal.automaticModelTurns} automatic responses used`\n\t\t\t\t\t\t\t: `Active goal: ${goal.toolFreeRepeatCount} repeated or empty runs detected`,\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t\t],\n\t\titems: limitChoices(field, value, goal?.automaticModelTurns).map((item) => ({\n\t\t\tid: item.value,\n\t\t\tlabel: item.label,\n\t\t\tdescription: item.description,\n\t\t\taction,\n\t\t})),\n\t\thint: \"back\" as const,\n\t};\n}\n\nfunction limitChoices(\n\tfield: LimitField,\n\tvalue: number | null,\n\tautomaticTurnsUsed: number | undefined,\n): Array<{ value: LimitSelection; label: string; description: string }> {\n\tif (field === \"automaticTurns\") {\n\t\tconst unlimitedDescription =\n\t\t\tvalue === null\n\t\t\t\t? \"No response-count cap. Completion, manual pause, blockers, provider limits, and other configured guards still apply.\"\n\t\t\t\t: automaticTurnsUsed === undefined\n\t\t\t\t\t? `Remove the current ${value}-response cap. Goal work will have no response-count cap; other configured stop conditions remain.`\n\t\t\t\t\t: `Remove the current ${value}-response cap. The active goal has used ${automaticTurnsUsed} responses; other configured stop conditions remain.`;\n\t\treturn [\n\t\t\t{\n\t\t\t\tvalue: \"custom\",\n\t\t\t\tlabel: \"Set response limit\u2026\",\n\t\t\t\tdescription: `Choose a whole-number response limit for each automatic-work epoch. Default: ${DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns}.`,\n\t\t\t},\n\t\t\t{ value: \"unlimited\", label: \"Unlimited\u2026\", description: unlimitedDescription },\n\t\t];\n\t}\n\tconst defaultLimit = DEFAULT_GOAL_SETTINGS.continuationLimits.noProgressTurns;\n\treturn [\n\t\t{\n\t\t\tvalue: \"default\",\n\t\t\tlabel: `After ${defaultLimit} repeated runs (default)`,\n\t\t\tdescription: \"Pause after the default number of repeated or empty tool-free runs.\",\n\t\t},\n\t\t{\n\t\t\tvalue: \"custom\",\n\t\t\tlabel: \"Set threshold\u2026\",\n\t\t\tdescription: \"Choose a whole number of repeated or empty runs before pausing.\",\n\t\t},\n\t\t{\n\t\t\tvalue: \"off\",\n\t\t\tlabel: \"Off\",\n\t\t\tdescription: \"Do not pause based on repeated or empty tool-free runs.\",\n\t\t},\n\t];\n}\n\nasync function applyLimitChoice(\n\truntime: GoalRuntime,\n\tctx: ExtensionCommandContext,\n\toptions: GoalSettingsUiOptions,\n\tsettingsPath: string,\n\tfield: LimitField,\n\titemId: string,\n\tactiveGoalId: string | null,\n\tisCurrent: () => boolean,\n) {\n\tif (!isCurrent() || !isLimitSelection(itemId)) return { kind: \"rejected\" as const };\n\tif ((runtime.activeGoal?.id ?? null) !== activeGoalId) {\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\n\t\t\t\"The active goal changed while the safety setting was open. No settings were changed.\",\n\t\t\t\"warning\",\n\t\t);\n\t\treturn { kind: \"rejected\" as const };\n\t}\n\tconst previous = runtime.settings.continuationLimits[field];\n\tconst limit = await resolveLimitSelection(field, itemId, previous, ctx, isCurrent);\n\tif (!isCurrent()) return { kind: \"rejected\" as const };\n\tif (limit === undefined || limit === previous) return { kind: \"back\" as const };\n\tif ((runtime.activeGoal?.id ?? null) !== activeGoalId) {\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\n\t\t\t\"The active goal changed while editing the safety setting. No settings were changed.\",\n\t\t\t\"warning\",\n\t\t);\n\t\treturn { kind: \"rejected\" as const };\n\t}\n\tconst confirmation = await confirmLowerActiveLimit(runtime, ctx, field, limit);\n\tif (!isCurrent() || !confirmation.apply) return { kind: \"rejected\" as const };\n\tif (confirmation.goalId !== undefined && runtime.activeGoal?.id !== confirmation.goalId) {\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\n\t\t\t\"The active goal changed while confirming the limit. No settings were changed.\",\n\t\t\t\"warning\",\n\t\t);\n\t\treturn { kind: \"rejected\" as const };\n\t}\n\ttry {\n\t\tapplyGoalSettings(runtime, withLimit(runtime.settings, field, limit), ctx, {\n\t\t\tsave: (settings) => (options.save ?? saveGoalSettings)(settings, settingsPath),\n\t\t});\n\t\tnotifyTerminal(ctx.ui, formatLimitSuccess(field, limit), \"info\");\n\t\treturn { kind: \"back\" as const };\n\t} catch (error) {\n\t\tnotifySettingsFailure(ctx, settingsPath, error);\n\t\treturn { kind: \"rejected\" as const };\n\t}\n}\n\nexport function applyGoalSettings(\n\truntime: GoalRuntime,\n\tnext: GoalSettings,\n\tctx: ExtensionCommandContext,\n\toptions: GoalSettingsApplyOptions = {},\n) {\n\tconst snapshot = runtime.snapshotSettingsApplicationState();\n\tlet fileSaved = false;\n\ttry {\n\t\truntime.settings = structuredClone(next);\n\t\toptions.save?.(next);\n\t\tfileSaved = options.save !== undefined;\n\t\tconst activeGoalId = runtime.activeGoal?.id;\n\t\tconst abortOwnedRun = activeGoalId !== undefined && runtime.agentRunGoalId === activeGoalId;\n\t\tconst pausedByAutomaticLimit = runtime.enforceAutomaticTurnLimit(ctx, abortOwnedRun);\n\t\tif (!pausedByAutomaticLimit) runtime.enforceNoProgressLimit(ctx, abortOwnedRun);\n\t\tif (runtime.activeGoal) {\n\t\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\t}\n\t} catch (error) {\n\t\tconst rollbackErrors: unknown[] = [];\n\t\ttry {\n\t\t\truntime.restoreSettingsApplicationState(snapshot);\n\t\t} catch (rollbackError) {\n\t\t\trollbackErrors.push(rollbackError);\n\t\t}\n\t\tif (fileSaved) {\n\t\t\ttry {\n\t\t\t\toptions.save?.(snapshot.settings);\n\t\t\t} catch (rollbackError) {\n\t\t\t\trollbackErrors.push(rollbackError);\n\t\t\t}\n\t\t\ttry {\n\t\t\t\trestorePersistedRuntime(runtime, ctx);\n\t\t\t} catch (rollbackError) {\n\t\t\t\trollbackErrors.push(rollbackError);\n\t\t\t}\n\t\t}\n\t\tif (rollbackErrors.length > 0) {\n\t\t\tthrow new AggregateError(\n\t\t\t\t[error, ...rollbackErrors],\n\t\t\t\t`pi-goal settings application failed and rollback was incomplete: ${formatError(error)}`,\n\t\t\t);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nexport function parseGoalLimit(value: string): number | undefined {\n\tconst normalized = value.trim();\n\tif (!/^\\d+$/u.test(normalized)) return undefined;\n\tconst parsed = Number(normalized);\n\treturn Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined;\n}\n\nasync function resolveLimitSelection(\n\tfield: LimitField,\n\tselection: LimitSelection,\n\tprevious: number | null,\n\tctx: ExtensionCommandContext,\n\tisCurrent: () => boolean,\n): Promise<number | null | undefined> {\n\tif (selection === \"off\") return null;\n\tif (selection === \"unlimited\") {\n\t\tif (previous === null) return null;\n\t\tconst confirmed = await ctx.ui.confirm(\n\t\t\t\"Allow Unlimited automatic work?\",\n\t\t\t\"Tool loops can continue without a response-count limit and may consume substantial tokens and provider cost. Completion, manual pause, blockers, provider limits, and the no-progress guard still apply.\",\n\t\t);\n\t\treturn isCurrent() && confirmed ? null : undefined;\n\t}\n\tif (selection === \"default\") {\n\t\treturn DEFAULT_GOAL_SETTINGS.continuationLimits[field];\n\t}\n\twhile (true) {\n\t\tconst raw =\n\t\t\tfield === \"automaticTurns\"\n\t\t\t\t? await ctx.ui.editor(\n\t\t\t\t\t\t`Automatic-work response limit (whole number greater than 0) \u00B7 Default: ${DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns}`,\n\t\t\t\t\t\tString(previous ?? DEFAULT_GOAL_SETTINGS.continuationLimits.automaticTurns),\n\t\t\t\t\t)\n\t\t\t\t: await ctx.ui.input(\n\t\t\t\t\t\t\"Repeated-run threshold (whole number greater than 0)\",\n\t\t\t\t\t\tprevious === null ? \"Positive whole number\" : String(previous),\n\t\t\t\t\t);\n\t\tif (!isCurrent() || raw === undefined) return undefined;\n\t\tconst parsed = parseGoalLimit(raw);\n\t\tif (parsed !== undefined) return parsed;\n\t\tnotifyTerminal(\n\t\t\tctx.ui,\n\t\t\t`Enter a whole number greater than 0. Choose ${field === \"automaticTurns\" ? \"Unlimited\" : \"Off\"} from the previous screen if you do not want a limit.`,\n\t\t\t\"warning\",\n\t\t);\n\t}\n}\n\nfunction restorePersistedRuntime(runtime: GoalRuntime, ctx: ExtensionCommandContext) {\n\tif (runtime.activeGoal) {\n\t\truntime.persistGoal(runtime.activeGoal);\n\t\truntime.updateStatus(ctx, runtime.activeGoal);\n\t\truntime.restoreGoalWaitTimer(ctx);\n\t}\n}\n\nasync function confirmLowerActiveLimit(\n\truntime: GoalRuntime,\n\tctx: ExtensionCommandContext,\n\tfield: LimitField,\n\tlimit: number | null,\n) {\n\tconst goal = runtime.activeGoal;\n\tif (goal?.status !== \"active\" || limit === null) return { apply: true };\n\tconst used = field === \"automaticTurns\" ? goal.automaticModelTurns : goal.toolFreeRepeatCount;\n\tif (used < limit) return { apply: true };\n\treturn {\n\t\tapply: await ctx.ui.confirm(\n\t\t\t\"Apply limit and pause now?\",\n\t\t\t`The active goal has already used ${used}. Setting this limit to ${limit} will pause it immediately without deleting progress.`,\n\t\t),\n\t\tgoalId: goal.id,\n\t};\n}\n\nfunction withLimit(settings: GoalSettings, field: LimitField, value: number | null): GoalSettings {\n\treturn {\n\t\t...structuredClone(settings),\n\t\tcontinuationLimits: { ...settings.continuationLimits, [field]: value },\n\t};\n}\n\nfunction formatAutomaticSettingValue(value: number | null) {\n\treturn value === null ? \"Unlimited\" : `${value} responses`;\n}\n\nfunction formatNoProgressSettingValue(value: number | null) {\n\tif (value === null) return \"Off\";\n\treturn `${value} ${value === 1 ? \"run\" : \"runs\"}`;\n}\n\nfunction formatAutomaticWork(value: number | null) {\n\treturn value === null ? \"Unlimited\" : `Up to ${value} responses`;\n}\n\nfunction formatNoProgressProtection(value: number | null) {\n\tif (value === null) return \"Off\";\n\treturn `After ${value} repeated ${value === 1 ? \"run\" : \"runs\"}`;\n}\n\nfunction formatLimitSuccess(field: LimitField, value: number | null) {\n\treturn field === \"automaticTurns\"\n\t\t? `Automatic-work limit: ${formatAutomaticWork(value)}.`\n\t\t: `No-progress guard: ${formatNoProgressProtection(value)}.`;\n}\n\nfunction isLimitSelection(value: string): value is LimitSelection {\n\treturn value === \"unlimited\" || value === \"default\" || value === \"custom\" || value === \"off\";\n}\n\nfunction notifySettingsFailure(ctx: ExtensionCommandContext, settingsPath: string, error: unknown) {\n\tconst path = safeTerminalText(settingsPath);\n\tconst detail = safeTerminalText(formatError(error));\n\tnotifyTerminal(\n\t\tctx.ui,\n\t\terror instanceof AggregateError\n\t\t\t? `Could not apply Goal settings, and rollback was incomplete. Check ${path}, run /reload, and verify the effective settings before retrying: ${detail}`\n\t\t\t: `Could not save Goal settings; the previous value remains. Check ${path} and retry: ${detail}`,\n\t\t\"error\",\n\t);\n}\n\nfunction formatError(error: unknown) {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"],
5
+ "mappings": ";;;;;;;;;;;AAAA,SAAS,YAAY;AACrB,SAAuC,mBAAmB;AAsB1D,eAAsB,iBACrB,SACA,KACA,UAAiC,CAAC,GACjC;AACD,QAAM,eAAe,QAAQ,gBAAgB,KAAK,YAAY,GAAG,kBAAkB;AACnF,MAAI,IAAI,SAAS,OAAO;AACvB;AAAA,MACC,IAAI;AAAA,MACJ,mCAAmC,iBAAiB,YAAY,CAAC;AAAA,MACjE;AAAA,IACD;AACA;AAAA,EACD;AACA,QAAM,aAAa,QAAQ;AAC3B,QAAM,gBAAgB,MACrB,eAAe,QAAQ,kBAAkB,CAAC,QAAQ,eAAe,OAAO;AACzE,QAAM,EAAE,YAAY,QAAQ,IAAI,MAAM,OAAO,sBAAsB;AACnE,MAAI,CAAC,cAAc,EAAG;AACtB,QAAM,UAAU,QAAQ,mB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AA8B,cAAsB,OAAgB;AAClG,QAAM,OAAO,iBAAiB,YAAY;AAC1C,QAAM,SAAS,iBAAiB,YAAY,KAAK,CAAC;AAClD;AAAA,IACC,IAAI;AAAA,IACJ,iBAAiB,iBACd,qEAAqE,IAAI,qEAAqE,MAAM,KACpJ,mEAAmE,IAAI,eAAe,MAAM;AAAA,IAC/F;AAAA,EACD;AACD;AAEA,SAAS,YAAY,OAAgB;AACpC,SAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAC7D;",
6
+ "names": []
7
+ }
package/dist/index.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  // @generated by scripts/build-runtime.mjs; do not edit.
2
- // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
2
+ // @ts-nocheck -- the generated entry uses a .ts extension for Pi's Jiti loader.
3
3
  import {
4
4
  GOAL_BLOCKED_TOOL,
5
5
  GOAL_COMPLETE_TOOL,
6
+ GOAL_CONTRACT_MESSAGE_TYPE,
6
7
  GOAL_WAIT_TOOL,
7
8
  GoalRuntime,
8
9
  MAX_GOAL_ID_LENGTH,
@@ -12,7 +13,6 @@ import {
12
13
  STATUS_KEY,
13
14
  abortCurrentTurn,
14
15
  blocksStaleGoalToolCalls,
15
- buildGoalContextPrompt,
16
16
  buildGoalPrompt,
17
17
  buildObjectiveUpdatedPrompt,
18
18
  buildResumePrompt,
@@ -28,6 +28,7 @@ import {
28
28
  hasAssistantToolCall,
29
29
  incrementGoal,
30
30
  isContradictoryCompletionSummary,
31
+ isGoalContextContract,
31
32
  isRemovedQueueCommand,
32
33
  isResumableGoalStatus,
33
34
  isTerminalGoalStatus,
@@ -35,12 +36,14 @@ import {
35
36
  nextGoalInstance,
36
37
  parseCommand,
37
38
  queueGoalSafetyReset,
39
+ reconcileGoalContextContract,
40
+ reconcileInactiveGoalContextContract,
38
41
  resetGoalSafetyEpoch,
39
42
  resolveGoalWaitDelay,
40
43
  stoppedStatusLabel,
41
44
  transitionGoal,
42
45
  validateObjective
43
- } from "./chunks/chunk-4GOI2LMD.js";
46
+ } from "./chunks/chunk-XHEFHXTF.js";
44
47
  import {
45
48
  DEFAULT_GOAL_SETTINGS,
46
49
  currentTokenTotal,
@@ -55,15 +58,15 @@ import {
55
58
  safeGoalMenuText,
56
59
  safeTerminalText,
57
60
  truncateNotification
58
- } from "./chunks/chunk-UA7LMS63.js";
61
+ } from "./chunks/chunk-UQRRW4CY.js";
59
62
 
60
63
  // src/command-registration.ts
61
64
  function registerGoalCommand(pi, runtime, commands, options = {}) {
62
65
  const loadGoalManager = cachedModuleLoader(
63
- options.loadGoalManager ?? (() => import("./chunks/menu-MMY32N6V.js"))
66
+ options.loadGoalManager ?? (() => import("./chunks/menu-4GLAABLR.js"))
64
67
  );
65
68
  const loadGoalSettings = cachedModuleLoader(
66
- options.loadGoalSettings ?? (() => import("./chunks/settings-ui-NXPYYRGD.js"))
69
+ options.loadGoalSettings ?? (() => import("./chunks/settings-ui-MVYTTBHW.js"))
67
70
  );
68
71
  pi.registerCommand("goal", {
69
72
  description: "Run a goal to completion: /goal [--tokens 100k] <goal_to_complete>",
@@ -198,9 +201,8 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
198
201
  const retainedOwner = this.runtime.ownsWorkflow(existingGoal);
199
202
  if (!this.runtime.acquireWorkflow(ctx.sessionManager)) return this.reportWorkflowBusy(ctx);
200
203
  const acquiredForRequest = !retainedOwner;
201
- const goalToolVisibilityBeforeActivation = this.runtime.toolPolicy.snapshot();
202
204
  try {
203
- this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
205
+ this.runtime.assertGoalToolsAvailable();
204
206
  } catch (error) {
205
207
  notifyTerminal(ctx.ui, `Cannot start /goal: ${formatError(error)}`, "error");
206
208
  if (existingGoal?.status === "active") this.runtime.pauseGoalForUnavailableTools(ctx);
@@ -275,7 +277,6 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
275
277
  }
276
278
  }
277
279
  if (rolledBackStartedGoal) {
278
- this.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);
279
280
  if (acquiredForRequest && !this.runtime.ownsWorkflow(existingGoal)) {
280
281
  this.runtime.releaseWorkflow();
281
282
  }
@@ -340,9 +341,8 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
340
341
  this.reportWorkflowBusy(ctx);
341
342
  return;
342
343
  }
343
- const goalToolVisibilityBeforeActivation = this.runtime.toolPolicy.snapshot();
344
344
  try {
345
- this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
345
+ this.runtime.assertGoalToolsAvailable();
346
346
  } catch (error) {
347
347
  notifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, "error");
348
348
  this.runtime.releaseWorkflow();
@@ -384,7 +384,6 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
384
384
  if (blocksStaleGoalToolCalls(this.runtime.activeGoal.status)) {
385
385
  this.runtime.blockStaleGoalToolCalls();
386
386
  }
387
- this.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);
388
387
  this.runtime.releaseWorkflow();
389
388
  }
390
389
  return;
@@ -406,7 +405,7 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
406
405
  return;
407
406
  }
408
407
  try {
409
- this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
408
+ this.runtime.assertGoalToolsAvailable();
410
409
  } catch (error) {
411
410
  notifyTerminal(ctx.ui, `Cannot resume /goal: ${formatError(error)}`, "error");
412
411
  return;
@@ -479,10 +478,9 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
479
478
  return;
480
479
  }
481
480
  const acquiredForEdit = intendsActive && !retainedOwner;
482
- const goalToolVisibilityBeforeActivation = intendsActive ? this.runtime.toolPolicy.snapshot() : void 0;
483
481
  if (intendsActive) {
484
482
  try {
485
- this.runtime.toolPolicy.prepareActivation(this.runtime.settings.toolVisibility, ctx);
483
+ this.runtime.assertGoalToolsAvailable();
486
484
  } catch (error) {
487
485
  notifyTerminal(ctx.ui, `Cannot reactivate /goal: ${formatError(error)}`, "error");
488
486
  if (currentGoal.status === "active") this.runtime.pauseGoalForUnavailableTools(ctx);
@@ -545,9 +543,6 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
545
543
  this.runtime.persistGoal(this.runtime.activeGoal);
546
544
  this.runtime.updateStatus(ctx, this.runtime.activeGoal);
547
545
  }
548
- if (goalToolVisibilityBeforeActivation) {
549
- this.runtime.toolPolicy.restore(goalToolVisibilityBeforeActivation);
550
- }
551
546
  if (acquiredForEdit && previousStatus !== "active") {
552
547
  this.runtime.releaseWorkflow();
553
548
  }
@@ -605,52 +600,6 @@ New goal: ${safeGoalMenuText(objective, 4e3)}`
605
600
  }
606
601
  };
607
602
 
608
- // src/goal-contract.ts
609
- var GOAL_CONTRACT_MESSAGE_TYPE = "goal-contract";
610
- var GOAL_CONTRACT_VERSION = 1;
611
- function createGoalContextContract(goal2) {
612
- return {
613
- role: "custom",
614
- customType: GOAL_CONTRACT_MESSAGE_TYPE,
615
- content: buildGoalContextPrompt(goal2),
616
- display: false,
617
- details: { version: GOAL_CONTRACT_VERSION, goalId: goal2.id },
618
- timestamp: 0
619
- };
620
- }
621
- function reconcileGoalContextContract(messages, goal2) {
622
- const summaryBoundary = leadingSummaryBoundary(messages);
623
- const expected = createGoalContextContract(goal2);
624
- const contractIndexes = messages.flatMap(
625
- (message, index) => unwrapMessage(message).customType === GOAL_CONTRACT_MESSAGE_TYPE ? [index] : []
626
- );
627
- if (contractIndexes.length === 1 && contractIndexes[0] === summaryBoundary && unwrapMessage(messages[summaryBoundary]).content === expected.content) {
628
- return messages;
629
- }
630
- const withoutContracts = messages.filter(
631
- (message) => unwrapMessage(message).customType !== GOAL_CONTRACT_MESSAGE_TYPE
632
- );
633
- const insertionIndex = leadingSummaryBoundary(withoutContracts);
634
- return [
635
- ...withoutContracts.slice(0, insertionIndex),
636
- expected,
637
- ...withoutContracts.slice(insertionIndex)
638
- ];
639
- }
640
- function leadingSummaryBoundary(messages) {
641
- let index = 0;
642
- while (index < messages.length) {
643
- const role = unwrapMessage(messages[index]).role;
644
- if (role !== "compactionSummary" && role !== "branchSummary") break;
645
- index += 1;
646
- }
647
- return index;
648
- }
649
- function unwrapMessage(message) {
650
- const entry = message;
651
- return entry?.message ?? message ?? {};
652
- }
653
-
654
603
  // src/lifecycle.ts
655
604
  var REMOVED_QUEUE_SETTING_WARNING = "Ordered goal queue has been removed. Use /goal edit to reprioritize an active objective, or start /goal <objectives> if no active goal exists.";
656
605
  var REMOVED_PERSISTED_QUEUE_WARNING = "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.";
@@ -670,7 +619,6 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
670
619
  runtime.legacyQueueState = void 0;
671
620
  runtime.legacyExperimentalGoalsSetting = false;
672
621
  runtime.clearTerminalDetails();
673
- const previousToolVisibility = runtime.settings.toolVisibility;
674
622
  const settingsResult = readGoalSettings(options.settingsPath);
675
623
  const loaded = loadGoalStateFromSession(ctx);
676
624
  runtime.settings = settingsResult.kind === "loaded" ? settingsResult.settings : DEFAULT_GOAL_SETTINGS;
@@ -693,6 +641,7 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
693
641
  if (!runtime.acquireWorkflow()) {
694
642
  runtime.activeGoal = transitionGoal(loaded.goal, "paused");
695
643
  runtime.persistGoal(runtime.activeGoal);
644
+ runtime.ensureInactiveGoalContextContract(ctx);
696
645
  runtime.updateStatus(ctx, runtime.activeGoal);
697
646
  notifyTerminal(
698
647
  ctx.ui,
@@ -702,18 +651,6 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
702
651
  return;
703
652
  }
704
653
  runtime.activeGoal = loaded.goal;
705
- try {
706
- runtime.toolPolicy.prepareSessionStart(
707
- runtime.settings.toolVisibility,
708
- previousToolVisibility
709
- );
710
- } catch (error) {
711
- notifyTerminal(
712
- ctx.ui,
713
- `Could not restore always-visible goal tools: ${formatError(error)}`,
714
- "error"
715
- );
716
- }
717
654
  if (runtime.activeGoal.safetyResetPending) {
718
655
  runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
719
656
  }
@@ -722,46 +659,22 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
722
659
  if (runtime.enforceAutomaticTurnLimit(ctx, false) || runtime.enforceNoProgressLimit(ctx)) {
723
660
  return;
724
661
  }
725
- runtime.toolPolicy.reconcileRestoredState(runtime.settings.toolVisibility, true);
726
- if (!runtime.toolPolicy.toolsAvailable()) {
662
+ if (!runtime.goalToolsAvailable()) {
727
663
  runtime.pauseGoalForUnavailableTools(ctx, false);
728
664
  return;
729
665
  }
730
666
  runtime.persistGoal(runtime.activeGoal);
731
667
  if (!runtime.ownsWorkflow(runtime.activeGoal)) return;
668
+ const restoredGoalId = runtime.activeGoal.id;
669
+ runtime.ensureGoalContextContract(ctx, runtime.activeGoal);
670
+ if (runtime.activeGoal?.id !== restoredGoalId || runtime.activeGoal.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
671
+ return;
672
+ }
732
673
  runtime.updateStatus(ctx, runtime.activeGoal);
733
674
  runtime.restoreGoalWaitTimer(ctx);
734
675
  return;
735
676
  }
736
677
  runtime.activeGoal = loaded.goal;
737
- let appliedInactivePolicy = false;
738
- let inactivePolicyFailed = false;
739
- try {
740
- appliedInactivePolicy = runtime.withTemporaryWorkflowAccess(() => {
741
- runtime.toolPolicy.prepareSessionStart(
742
- runtime.settings.toolVisibility,
743
- previousToolVisibility
744
- );
745
- runtime.toolPolicy.reconcileRestoredState(
746
- runtime.settings.toolVisibility,
747
- runtime.activeGoal !== void 0 && runtime.legacyQueueState === void 0
748
- );
749
- });
750
- } catch (error) {
751
- inactivePolicyFailed = true;
752
- notifyTerminal(
753
- ctx.ui,
754
- `Could not restore always-visible goal tools: ${formatError(error)}`,
755
- "error"
756
- );
757
- }
758
- if (!appliedInactivePolicy && !inactivePolicyFailed) {
759
- notifyTerminal(
760
- ctx.ui,
761
- "Goal tool visibility was deferred because another workflow is active in this session.",
762
- "warning"
763
- );
764
- }
765
678
  if (runtime.legacyQueueState) {
766
679
  ctx.ui.setStatus(STATUS_KEY, void 0);
767
680
  notifyTerminal(ctx.ui, REMOVED_PERSISTED_QUEUE_WARNING, "warning");
@@ -769,8 +682,10 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
769
682
  }
770
683
  if (runtime.activeGoal) {
771
684
  runtime.persistGoal(runtime.activeGoal);
685
+ runtime.ensureInactiveGoalContextContract(ctx);
772
686
  runtime.updateStatus(ctx, runtime.activeGoal);
773
687
  } else {
688
+ runtime.ensureInactiveGoalContextContract(ctx);
774
689
  ctx.ui.setStatus(STATUS_KEY, void 0);
775
690
  }
776
691
  });
@@ -829,8 +744,13 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
829
744
  runtime.persistGoal(runtime.activeGoal);
830
745
  runtime.updateStatus(ctx, runtime.activeGoal);
831
746
  }
832
- if (!usageRecorded) return;
833
747
  if (runtime.limitActiveGoalForBudget(ctx, false)) return;
748
+ const compactedGoalId = runtime.activeGoal.id;
749
+ runtime.ensureGoalContextContract(ctx, runtime.activeGoal);
750
+ if (runtime.activeGoal?.id !== compactedGoalId || runtime.activeGoal.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
751
+ return;
752
+ }
753
+ if (!usageRecorded) return;
834
754
  const wasPiRetry = runtime.isPiOwnedCompactionRetry(event, runtime.activeGoal.id);
835
755
  if (wasPiRetry) return;
836
756
  runtime.clearGoalRecoveryForGoal(runtime.activeGoal.id);
@@ -872,6 +792,7 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
872
792
  return;
873
793
  }
874
794
  if (message.role === "custom") {
795
+ if (Reflect.get(message, "customType") === GOAL_CONTRACT_MESSAGE_TYPE) return;
875
796
  if (runtime.isActiveBudgetWrapUpMessage(message)) return;
876
797
  if (runtime.activeGoal?.waiting) runtime.clearGoalWait(ctx, runtime.activeGoal.id);
877
798
  if (runtime.guardAbortGoalId === runtime.activeGoal?.id) {
@@ -913,7 +834,8 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
913
834
  const keptMessages = event.messages.filter(
914
835
  (message) => runtime.keepBudgetWrapUpMessage(message)
915
836
  );
916
- const messages = runtime.activeGoal?.status === "active" && runtime.ownsWorkflow(runtime.activeGoal) ? reconcileGoalContextContract(keptMessages, runtime.activeGoal) : keptMessages;
837
+ const hasGoalContractHistory = keptMessages.some(isGoalContextContract) || runtime.hasGoalContextContractHistory(ctx);
838
+ const messages = runtime.activeGoal?.status === "active" && runtime.ownsWorkflow(runtime.activeGoal) ? reconcileGoalContextContract(keptMessages, runtime.activeGoal) : hasGoalContractHistory ? reconcileInactiveGoalContextContract(keptMessages) : keptMessages;
917
839
  if (runtime.activeGoal?.status === "paused" && runtime.guardAbortGoalId === runtime.activeGoal.id) {
918
840
  abortCurrentTurn(ctx);
919
841
  }
@@ -953,7 +875,7 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
953
875
  runtime.persistGoal(runtime.activeGoal);
954
876
  runtime.updateStatus(ctx, runtime.activeGoal);
955
877
  if (runtime.limitActiveGoalForBudget(ctx, true)) return;
956
- if (!runtime.toolPolicy.toolsAvailable()) runtime.pauseGoalForUnavailableTools(ctx);
878
+ if (!runtime.goalToolsAvailable()) runtime.pauseGoalForUnavailableTools(ctx);
957
879
  });
958
880
  pi.on("before_agent_start", (event, ctx) => {
959
881
  runtime.clearAgentRun();
@@ -985,29 +907,30 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
985
907
  const runOrigin = continuationGoalId ? "automatic" : activeGoalRecovery && runtime.goalRecovery?.automaticOwner ? "automatic" : "manual";
986
908
  if (activeBudgetWrapUp && runtime.activeGoal) {
987
909
  runtime.beginAgentRun(runtime.activeGoal.id, "manual");
988
- return;
910
+ return goalContractBoundaryResult(ctx);
989
911
  }
990
912
  if (ownedPromptGoalId && ownedPromptGoalId !== runtime.activeGoal?.id) {
991
913
  runtime.beginAgentRun(ownedPromptGoalId, runOrigin);
992
- if (runtime.activeGoal?.status === "active" && !runtime.toolPolicy.toolsAvailable()) {
914
+ if (runtime.activeGoal?.status === "active" && !runtime.goalToolsAvailable()) {
993
915
  runtime.pauseGoalForUnavailableTools(ctx, false);
994
916
  }
995
917
  abortCurrentTurn(ctx);
996
918
  return;
997
919
  }
998
920
  if (runtime.activeGoal?.status !== "active" || !runtime.ownsWorkflow(runtime.activeGoal)) {
999
- return;
921
+ return goalContractBoundaryResult(ctx);
1000
922
  }
1001
923
  runtime.beginAgentRun(runtime.activeGoal.id, runOrigin);
1002
- if (!runtime.toolPolicy.toolsAvailable()) {
924
+ if (!runtime.goalToolsAvailable()) {
1003
925
  runtime.pauseGoalForUnavailableTools(ctx, ownedPromptGoalId !== void 0);
1004
- return;
926
+ return goalContractBoundaryResult(ctx);
1005
927
  }
1006
928
  if (goalPrompt?.resetSafetyEpoch && goalPromptGoalId === runtime.activeGoal.id) {
1007
929
  runtime.activeGoal = resetGoalSafetyEpoch(runtime.activeGoal);
1008
930
  runtime.persistGoal(runtime.activeGoal);
1009
931
  runtime.updateStatus(ctx, runtime.activeGoal);
1010
932
  }
933
+ return goalContractBoundaryResult(ctx, runtime.activeGoal);
1011
934
  });
1012
935
  pi.on("agent_start", (_event, _ctx) => {
1013
936
  const activeGoal = runtime.activeGoal;
@@ -1054,7 +977,7 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
1054
977
  if (isRetryableGoalInterruption(finalAssistant)) {
1055
978
  if (run.origin === "automatic" && runtime.enforceAutomaticTurnLimit(ctx, true)) return;
1056
979
  if (runtime.limitActiveGoalForBudget(ctx, false)) return;
1057
- if (!runtime.toolPolicy.toolsAvailable()) {
980
+ if (!runtime.goalToolsAvailable()) {
1058
981
  runtime.pauseGoalForUnavailableTools(ctx);
1059
982
  return;
1060
983
  }
@@ -1080,7 +1003,7 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
1080
1003
  }
1081
1004
  runtime.clearGoalRecoveryForGoal(goalId);
1082
1005
  if (runtime.limitActiveGoalForBudget(ctx, false)) return;
1083
- if (!runtime.toolPolicy.toolsAvailable()) {
1006
+ if (!runtime.goalToolsAvailable()) {
1084
1007
  runtime.pauseGoalForUnavailableTools(ctx);
1085
1008
  return;
1086
1009
  }
@@ -1110,6 +1033,10 @@ function registerGoalLifecycle(pi, runtime, runController, options = {}) {
1110
1033
  if (!resumedWait) runtime.dispatchContinuationIfSettled(ctx);
1111
1034
  runtime.clearSettledSafetyTracking();
1112
1035
  });
1036
+ function goalContractBoundaryResult(ctx, goal2) {
1037
+ const message = runtime.goalContextContractForPrompt(ctx, goal2);
1038
+ return message ? { message } : void 0;
1039
+ }
1113
1040
  function beginNonGoalFollowUp(ctx, resetSafetyEpoch) {
1114
1041
  runtime.clearGoalRecovery();
1115
1042
  runtime.clearStaleGoalToolCallBlock();
@@ -1444,14 +1371,7 @@ function registerGoalTools(pi, runtime) {
1444
1371
  const goalCompleteTool = defineTool({
1445
1372
  name: GOAL_COMPLETE_TOOL,
1446
1373
  label: "Goal Complete",
1447
- description: "Mark the active /goal as complete after all required work is done and verified, using the current goal_id stale-turn guard. Do not use for partial progress, blockers, failing, or unverified work.",
1448
- promptSnippet: "Mark the active /goal as complete after fully finishing and verifying it, with the current goal_id",
1449
- promptGuidelines: [
1450
- "When a /goal is active, keep working until the goal is complete; do not stop with only a plan or partial progress.",
1451
- "Before calling goal_complete, audit the active goal requirement by requirement against the current files, command output, tests, or external state.",
1452
- "Pass the exact goal_id shown in the current /goal prompt; never reuse a goal_id from an older, stopped, replaced, or cleared turn.",
1453
- "Call goal_complete only after the requested goal is fully implemented, verified, and no known required work remains; otherwise keep working."
1454
- ],
1374
+ description: "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.",
1455
1375
  parameters: Type.Object({
1456
1376
  goal_id: Type.String({
1457
1377
  minLength: 1,
@@ -1551,14 +1471,7 @@ function registerGoalTools(pi, runtime) {
1551
1471
  const goalBlockedTool = defineTool({
1552
1472
  name: GOAL_BLOCKED_TOOL,
1553
1473
  label: "Goal Blocked",
1554
- description: "Stop the active /goal only at a true impasse after the same blocker recurs for at least three consecutive goal turns, with the current goal_id and concrete evidence that user or external action is required. Do not use for ordinary clarification, uncertainty, or recoverable failures.",
1555
- promptSnippet: "Mark the active /goal blocked only after the same blocker recurs for three consecutive goal turns",
1556
- promptGuidelines: [
1557
- "Use goal_blocked only for a true impasse after the same blocker recurs for at least three consecutive goal turns and concrete evidence shows user or external action is required.",
1558
- "After a blocked goal is resumed, start a fresh three-turn blocker audit before using goal_blocked again.",
1559
- "Do not use goal_blocked for ordinary clarification, incomplete work, uncertainty, difficult tasks, or recoverable tool/provider failures.",
1560
- "Pass goal_blocked the exact current goal_id; never reuse a goal_id from an older, stopped, replaced, or cleared goal turn."
1561
- ],
1474
+ description: "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.",
1562
1475
  parameters: Type.Object({
1563
1476
  goal_id: Type.String({
1564
1477
  minLength: 1,
@@ -1630,15 +1543,7 @@ function registerGoalTools(pi, runtime) {
1630
1543
  const goalWaitTool = defineTool({
1631
1544
  name: GOAL_WAIT_TOOL,
1632
1545
  label: "Goal Wait",
1633
- description: `Keep the active /goal alive but quiet while an external event is expected. Call goal_wait alone after arranging a wake message, or provide resume_after_ms as a safety deadline. Requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms. Do not use it for ordinary unfinished work.`,
1634
- promptSnippet: "Wait quietly for an external event without stopping the active /goal or starting automatic continuations",
1635
- promptGuidelines: [
1636
- "Use goal_wait only when progress depends on a later non-goal message, or when resume_after_ms provides a bounded safety wake-up rather than a polling interval.",
1637
- `Prefer longer waits measured in minutes to avoid busy polling; goal_wait requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms.`,
1638
- "Arrange the external monitor or wake source before calling goal_wait, and call goal_wait alone because parallel sibling tools can prevent immediate turn termination.",
1639
- "Pass the exact current goal_id so a stale turn cannot put a replacement goal into waiting.",
1640
- "Do not use goal_blocked for a recoverable external wait that can be resumed by a message or deadline."
1641
- ],
1546
+ 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.`,
1642
1547
  parameters: Type.Object({
1643
1548
  goal_id: Type.String({
1644
1549
  minLength: 1,