@astralyn/pi 0.82.5 → 0.82.7
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 +55 -0
- package/README.md +1 -1
- package/dist/cli/project-trust.d.ts.map +1 -1
- package/dist/cli/project-trust.js +4 -1
- package/dist/cli/project-trust.js.map +1 -1
- package/dist/cli/session-picker.d.ts.map +1 -1
- package/dist/cli/session-picker.js +11 -13
- package/dist/cli/session-picker.js.map +1 -1
- package/dist/core/bash-executor.d.ts.map +1 -1
- package/dist/core/bash-executor.js +4 -22
- package/dist/core/bash-executor.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/types.d.ts +32 -5
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +2 -2
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/tools/bash.d.ts +1 -5
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +16 -41
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +42 -11
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +6 -7
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +17 -8
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js +3 -3
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/output-accumulator.d.ts +3 -13
- package/dist/core/tools/output-accumulator.d.ts.map +1 -1
- package/dist/core/tools/output-accumulator.js +6 -36
- package/dist/core/tools/output-accumulator.js.map +1 -1
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js +4 -4
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/render-utils.d.ts +7 -0
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js +11 -0
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js +2 -3
- package/dist/core/tools/write.js.map +1 -1
- package/dist/extensions/deepwiki/render.d.ts.map +1 -1
- package/dist/extensions/deepwiki/render.js +34 -22
- package/dist/extensions/deepwiki/render.js.map +1 -1
- package/dist/extensions/plan/constants.d.ts +43 -6
- package/dist/extensions/plan/constants.d.ts.map +1 -1
- package/dist/extensions/plan/constants.js +51 -8
- package/dist/extensions/plan/constants.js.map +1 -1
- package/dist/extensions/plan/index.d.ts +12 -3
- package/dist/extensions/plan/index.d.ts.map +1 -1
- package/dist/extensions/plan/index.js +173 -35
- package/dist/extensions/plan/index.js.map +1 -1
- package/dist/extensions/plan/schema.d.ts +5 -0
- package/dist/extensions/plan/schema.d.ts.map +1 -1
- package/dist/extensions/plan/schema.js.map +1 -1
- package/dist/extensions/plan/state.d.ts +11 -2
- package/dist/extensions/plan/state.d.ts.map +1 -1
- package/dist/extensions/plan/state.js +31 -9
- package/dist/extensions/plan/state.js.map +1 -1
- package/dist/extensions/plan/storage.d.ts +11 -3
- package/dist/extensions/plan/storage.d.ts.map +1 -1
- package/dist/extensions/plan/storage.js +45 -20
- package/dist/extensions/plan/storage.js.map +1 -1
- package/dist/extensions/plan/view.d.ts +44 -0
- package/dist/extensions/plan/view.d.ts.map +1 -0
- package/dist/extensions/plan/view.js +149 -0
- package/dist/extensions/plan/view.js.map +1 -0
- package/dist/extensions/question/dialog.d.ts.map +1 -1
- package/dist/extensions/question/dialog.js +29 -10
- package/dist/extensions/question/dialog.js.map +1 -1
- package/dist/extensions/question/index.d.ts.map +1 -1
- package/dist/extensions/question/index.js +7 -2
- package/dist/extensions/question/index.js.map +1 -1
- package/dist/extensions/question/render.d.ts +4 -8
- package/dist/extensions/question/render.d.ts.map +1 -1
- package/dist/extensions/question/render.js +202 -29
- package/dist/extensions/question/render.js.map +1 -1
- package/dist/extensions/question/results.d.ts.map +1 -1
- package/dist/extensions/question/results.js +1 -0
- package/dist/extensions/question/results.js.map +1 -1
- package/dist/extensions/question/schema.d.ts.map +1 -1
- package/dist/extensions/question/schema.js +2 -2
- package/dist/extensions/question/schema.js.map +1 -1
- package/dist/extensions/question/types.d.ts +1 -0
- package/dist/extensions/question/types.d.ts.map +1 -1
- package/dist/extensions/question/types.js +1 -1
- package/dist/extensions/question/types.js.map +1 -1
- package/dist/extensions/router/stream.d.ts +1 -0
- package/dist/extensions/router/stream.d.ts.map +1 -1
- package/dist/extensions/router/stream.js +75 -0
- package/dist/extensions/router/stream.js.map +1 -1
- package/dist/extensions/subagent/activity.d.ts.map +1 -1
- package/dist/extensions/subagent/activity.js +25 -4
- package/dist/extensions/subagent/activity.js.map +1 -1
- package/dist/extensions/subagent/constants.d.ts +1 -0
- package/dist/extensions/subagent/constants.d.ts.map +1 -1
- package/dist/extensions/subagent/constants.js +1 -0
- package/dist/extensions/subagent/constants.js.map +1 -1
- package/dist/extensions/subagent/index.d.ts.map +1 -1
- package/dist/extensions/subagent/index.js +16 -0
- package/dist/extensions/subagent/index.js.map +1 -1
- package/dist/extensions/subagent/render.d.ts.map +1 -1
- package/dist/extensions/subagent/render.js +352 -152
- package/dist/extensions/subagent/render.js.map +1 -1
- package/dist/extensions/subagent/resolve.d.ts.map +1 -1
- package/dist/extensions/subagent/resolve.js +13 -9
- package/dist/extensions/subagent/resolve.js.map +1 -1
- package/dist/extensions/subagent/retry.d.ts +17 -0
- package/dist/extensions/subagent/retry.d.ts.map +1 -0
- package/dist/extensions/subagent/retry.js +41 -0
- package/dist/extensions/subagent/retry.js.map +1 -0
- package/dist/extensions/subagent/runner.d.ts.map +1 -1
- package/dist/extensions/subagent/runner.js +37 -7
- package/dist/extensions/subagent/runner.js.map +1 -1
- package/dist/extensions/subagent/schema.d.ts.map +1 -1
- package/dist/extensions/subagent/schema.js +2 -2
- package/dist/extensions/subagent/schema.js.map +1 -1
- package/dist/extensions/subagent/sdk-runner.d.ts +6 -0
- package/dist/extensions/subagent/sdk-runner.d.ts.map +1 -1
- package/dist/extensions/subagent/sdk-runner.js +46 -24
- package/dist/extensions/subagent/sdk-runner.js.map +1 -1
- package/dist/extensions/subagent/types.d.ts +7 -0
- package/dist/extensions/subagent/types.d.ts.map +1 -1
- package/dist/extensions/subagent/types.js.map +1 -1
- package/dist/extensions/todo/constants.d.ts +17 -6
- package/dist/extensions/todo/constants.d.ts.map +1 -1
- package/dist/extensions/todo/constants.js +22 -9
- package/dist/extensions/todo/constants.js.map +1 -1
- package/dist/extensions/todo/index.d.ts +0 -14
- package/dist/extensions/todo/index.d.ts.map +1 -1
- package/dist/extensions/todo/index.js +13 -1
- package/dist/extensions/todo/index.js.map +1 -1
- package/dist/extensions/todo/schema.d.ts +53 -2
- package/dist/extensions/todo/schema.d.ts.map +1 -1
- package/dist/extensions/todo/schema.js +57 -8
- package/dist/extensions/todo/schema.js.map +1 -1
- package/dist/extensions/todo/state.d.ts +16 -5
- package/dist/extensions/todo/state.d.ts.map +1 -1
- package/dist/extensions/todo/state.js +874 -130
- package/dist/extensions/todo/state.js.map +1 -1
- package/dist/extensions/todo/view.d.ts +16 -1
- package/dist/extensions/todo/view.d.ts.map +1 -1
- package/dist/extensions/todo/view.js +428 -1
- package/dist/extensions/todo/view.js.map +1 -1
- package/dist/migrations.d.ts.map +1 -1
- package/dist/migrations.js +2 -1
- package/dist/migrations.js.map +1 -1
- package/dist/modes/interactive/components/armin.d.ts.map +1 -1
- package/dist/modes/interactive/components/armin.js +5 -0
- package/dist/modes/interactive/components/armin.js.map +1 -1
- package/dist/modes/interactive/components/bash-execution.d.ts +1 -0
- package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js +4 -2
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/countdown-timer.d.ts +13 -6
- package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -1
- package/dist/modes/interactive/components/countdown-timer.js +54 -17
- package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
- package/dist/modes/interactive/components/extension-selector.d.ts +6 -1
- package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-selector.js +23 -11
- package/dist/modes/interactive/components/extension-selector.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts +11 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +56 -0
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +3 -0
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +52 -2
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +10 -0
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +139 -18
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tool-group.d.ts +1 -0
- package/dist/modes/interactive/components/tool-group.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-group.js +5 -0
- package/dist/modes/interactive/components/tool-group.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts +10 -1
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.js +55 -2
- package/dist/modes/interactive/components/tree-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +5 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +79 -19
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +3 -2
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-mode.js +8 -1
- package/dist/modes/rpc/rpc-mode.js.map +1 -1
- package/dist/utils/paths.d.ts +6 -0
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +8 -0
- package/dist/utils/paths.js.map +1 -1
- package/docs/bundled/README.md +1 -0
- package/docs/bundled/extensions/deepwiki.md +1 -1
- package/docs/bundled/extensions/plan.md +13 -10
- package/docs/bundled/extensions/question.md +7 -5
- package/docs/bundled/extensions/router.md +3 -4
- package/docs/bundled/extensions/statusline.md +0 -1
- package/docs/bundled/extensions/subagent.md +5 -4
- package/docs/bundled/extensions/todo.md +9 -7
- package/docs/bundled/tool-presentation.md +17 -16
- package/docs/extensions.md +34 -5
- package/docs/rpc.md +1 -1
- package/docs/usage.md +1 -1
- package/npm-shrinkwrap.json +6 -6
- package/package.json +1 -1
- package/dist/utils/output-decoder.d.ts +0 -52
- package/dist/utils/output-decoder.d.ts.map +0 -1
- package/dist/utils/output-decoder.js +0 -134
- package/dist/utils/output-decoder.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render.d.ts","sourceRoot":"","sources":["../../../src/extensions/deepwiki/render.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,KAAK,SAAS,EAAqC,MAAM,wBAAwB,CAAC;AAC3F,OAAO,KAAK,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAE/F,OAAO,EAAoB,KAAK,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAItF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"render.d.ts","sourceRoot":"","sources":["../../../src/extensions/deepwiki/render.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,KAAK,SAAS,EAAqC,MAAM,wBAAwB,CAAC;AAC3F,OAAO,KAAK,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAE/F,OAAO,EAAoB,KAAK,KAAK,EAAE,MAAM,wCAAwC,CAAC;AAItF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAgIlD,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,cAAc,EAAE,KAAK,EAAE,KAAK,GAAG,SAAS,CAUhF;AASD,wBAAgB,oBAAoB,CACnC,MAAM,EAAE,eAAe,CAAC,eAAe,CAAC,EACxC,OAAO,EAAE,uBAAuB,EAChC,KAAK,EAAE,KAAK,EACZ,OAAO,EAAE,OAAO,GACd,SAAS,CAqBX","sourcesContent":["/**\n * TUI rendering for the deepwiki tool (collapse / expand).\n *\n * Pi's fallback renderer dumps full `content` text and ignores `expanded`; this\n * extension returns large wiki payloads, so a private renderer stays local here.\n */\nimport { type Component, Container, Markdown, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { AgentToolResult, ToolRenderResultOptions } from \"../../core/extensions/types.ts\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getMarkdownTheme, type Theme } from \"../../modes/interactive/theme/theme.ts\";\n\nimport { extractContentPages, extractStructureSections } from \"./client.ts\";\nimport { DEEPWIKI_LABEL } from \"./constants.ts\";\nimport type { DeepWikiDetails } from \"./execute.ts\";\nimport type { DeepWikiParams } from \"./schema.ts\";\n\nfunction truncateText(text: string, maxLength: number, options?: { word?: boolean }): string {\n\tif (text.length <= maxLength) return text;\n\tif (options?.word) {\n\t\tconst prefix = text.slice(0, maxLength - 3);\n\t\tconst lastSpace = prefix.lastIndexOf(\" \");\n\t\tif (lastSpace >= 40) return `${prefix.slice(0, lastSpace)}...`;\n\t}\n\treturn `${text.slice(0, maxLength - 3)}...`;\n}\n\nfunction singleLine(text: unknown): string {\n\treturn typeof text === \"string\" ? text.replace(/\\s+/g, \" \").trim() : \"\";\n}\n\nfunction firstText(result: AgentToolResult<DeepWikiDetails>): string {\n\tfor (const part of result.content ?? []) {\n\t\tif (part.type === \"text\" && typeof part.text === \"string\") return part.text;\n\t}\n\treturn \"\";\n}\n\nfunction firstContentLine(text: string): string {\n\treturn (\n\t\ttext\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trim())\n\t\t\t.find((line) => line.length > 0) ?? \"DeepWiki response\"\n\t);\n}\n\nfunction formatPageList(pages: string[], maxItems = 4): string {\n\tconst shown = pages.slice(0, maxItems).map(singleLine).join(\", \");\n\treturn pages.length > maxItems ? `${shown}...` : shown;\n}\n\nfunction pageTitlesFromResult(text: string, details: DeepWikiDetails | undefined): string[] {\n\tif (Array.isArray(details?.pageTitles)) {\n\t\tconst titles = details.pageTitles.filter((title) => typeof title === \"string\");\n\t\tif (titles.length) return titles;\n\t}\n\tif (Array.isArray(details?.sectionTitles)) {\n\t\tconst titles = details.sectionTitles.filter((title) => typeof title === \"string\");\n\t\tif (titles.length) return titles;\n\t}\n\tconst fromContent = extractContentPages(text);\n\tif (fromContent.length) return fromContent;\n\treturn extractStructureSections(text);\n}\n\nfunction summarizeStructure(text: string, details: DeepWikiDetails | undefined): string {\n\tconst pages = pageTitlesFromResult(text, details);\n\tif (pages.length === 0) return truncateText(firstContentLine(text), 120);\n\tconst count = details?.pageCount ?? pages.length;\n\treturn `${count} pages · ${formatPageList(pages)}`;\n}\n\nfunction summarizeContents(text: string, details: DeepWikiDetails | undefined): string {\n\tif (typeof details?.requestedPage === \"string\" && details.requestedPage.trim()) {\n\t\tconst position =\n\t\t\tdetails.pageIndex !== undefined && details.pageCount ? `${details.pageIndex}/${details.pageCount} · ` : \"\";\n\t\tconst cut = details.truncatedChars ? \" (truncated)\" : \"\";\n\t\treturn `Page ${position}${singleLine(details.requestedPage)}${cut}`;\n\t}\n\tconst pages = pageTitlesFromResult(text, details);\n\tif (details?.shownPages !== undefined) {\n\t\tconst total = details.pageCount ?? pages.length;\n\t\tconst pagesPart = total > 0 ? `${details.shownPages}/${total} pages` : \"partial\";\n\t\treturn `Wiki · ${pagesPart} shown (truncated)`;\n\t}\n\tif (pages.length === 0) return \"Wiki loaded\";\n\treturn `Wiki · ${details?.pageCount ?? pages.length} pages`;\n}\n\nfunction stripDeepWikiTail(text: string): string {\n\tconst tailIndex = text.search(/\\n(?:#+\\s*)?(?:Wiki pages you might want to explore|View this search)/i);\n\tif (tailIndex < 0) return text;\n\treturn text.slice(0, tailIndex);\n}\n\nfunction summarizeQuestion(text: string): string {\n\tconst cleaned = stripDeepWikiTail(text)\n\t\t.replace(/\\[([^\\]]+)\\]\\([^)]+\\)/g, \"$1\")\n\t\t.replace(/[`*_]/g, \"\")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n\tif (!cleaned) return \"Answer ready\";\n\tconst sentenceMatch = cleaned.match(/^.{40,}?[.!?](?=\\s|$)/);\n\treturn truncateText(sentenceMatch?.[0] ?? cleaned, 140, { word: true });\n}\n\nfunction summarizeCollapsed(text: string, details: DeepWikiDetails | undefined): string {\n\tlet summary: string;\n\tif (details?.action === \"structure\") summary = summarizeStructure(text, details);\n\telse if (details?.action === \"contents\") summary = summarizeContents(text, details);\n\telse if (details?.action === \"question\") summary = summarizeQuestion(text);\n\telse summary = truncateText(firstContentLine(text), 120);\n\treturn truncateText(singleLine(summary), 180, { word: true });\n}\n\nfunction repoLabel(repoName: DeepWikiParams[\"repoName\"] | undefined): string {\n\tif (Array.isArray(repoName)) {\n\t\tif (repoName.length === 0) return \"repo\";\n\t\tif (repoName.length === 1) return repoName[0];\n\t\treturn `${repoName.length} repos: ${repoName.slice(0, 2).join(\", \")}${repoName.length > 2 ? \"...\" : \"\"}`;\n\t}\n\treturn repoName ?? \"repo\";\n}\n\n/** renderCall sees raw tool args; normalize JSON-array strings for display. */\nfunction repoLabelForCall(repoName: unknown): string {\n\tif (Array.isArray(repoName)) return repoLabel(repoName as DeepWikiParams[\"repoName\"]);\n\tif (typeof repoName === \"string\") {\n\t\tconst trimmed = repoName.trim();\n\t\tif (trimmed.startsWith(\"[\")) {\n\t\t\ttry {\n\t\t\t\tconst parsed: unknown = JSON.parse(trimmed);\n\t\t\t\tif (Array.isArray(parsed)) return repoLabel(parsed as string[]);\n\t\t\t} catch {\n\t\t\t\t/* fall through */\n\t\t\t}\n\t\t}\n\t\treturn repoLabel(repoName);\n\t}\n\treturn repoLabel(undefined);\n}\n\nexport function renderDeepWikiCall(args: DeepWikiParams, theme: Theme): Component {\n\tlet line = theme.fg(\"toolTitle\", theme.bold(`${DEEPWIKI_LABEL} `));\n\tline += theme.fg(\"muted\", args.action);\n\tline += ` ${theme.fg(\"accent\", repoLabelForCall(args.repoName))}`;\n\tif (args.action === \"question\" && args.question) {\n\t\tline += ` ${theme.fg(\"dim\", truncateText(singleLine(args.question), 64))}`;\n\t} else if (args.action === \"contents\" && args.page !== undefined) {\n\t\tline += ` ${theme.fg(\"dim\", truncateText(singleLine(String(args.page)), 40))}`;\n\t}\n\treturn new Text(line, 0, 0);\n}\n\nfunction markdownBlock(text: string): Component {\n\tconst container = new Container();\n\tcontainer.addChild(new Spacer(1));\n\tcontainer.addChild(new Markdown(text, 1, 0, getMarkdownTheme()));\n\treturn container;\n}\n\nexport function renderDeepWikiResult(\n\tresult: AgentToolResult<DeepWikiDetails>,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tisError: boolean,\n): Component {\n\tif (options.isPartial) {\n\t\tconst repo = typeof result.details?.repoName === \"string\" ? singleLine(result.details.repoName) : \"\";\n\t\tconst label = repo ? `Querying ${repo}...` : \"Querying...\";\n\t\treturn new Text(theme.fg(\"warning\", label), 0, 0);\n\t}\n\n\tconst text = firstText(result);\n\tconst errorMessage = typeof result.details?.errorMessage === \"string\" ? result.details.errorMessage : undefined;\n\tif (isError || errorMessage) {\n\t\tconst line = truncateText(errorMessage ?? firstContentLine(text), 200);\n\t\treturn new Text(theme.fg(\"error\", `failed · ${line}`), 0, 0);\n\t}\n\n\tif (!options.expanded) {\n\t\tconst summary = theme.fg(\"toolOutput\", summarizeCollapsed(text, result.details));\n\t\tconst hint = `${theme.fg(\"muted\", \" (\")}${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\treturn new Text(`${summary}${hint}`, 0, 0);\n\t}\n\n\treturn markdownBlock(text);\n}\n"]}
|
|
@@ -20,6 +20,9 @@ function truncateText(text, maxLength, options) {
|
|
|
20
20
|
}
|
|
21
21
|
return `${text.slice(0, maxLength - 3)}...`;
|
|
22
22
|
}
|
|
23
|
+
function singleLine(text) {
|
|
24
|
+
return typeof text === "string" ? text.replace(/\s+/g, " ").trim() : "";
|
|
25
|
+
}
|
|
23
26
|
function firstText(result) {
|
|
24
27
|
for (const part of result.content ?? []) {
|
|
25
28
|
if (part.type === "text" && typeof part.text === "string")
|
|
@@ -34,14 +37,20 @@ function firstContentLine(text) {
|
|
|
34
37
|
.find((line) => line.length > 0) ?? "DeepWiki response");
|
|
35
38
|
}
|
|
36
39
|
function formatPageList(pages, maxItems = 4) {
|
|
37
|
-
const shown = pages.slice(0, maxItems).join(", ");
|
|
40
|
+
const shown = pages.slice(0, maxItems).map(singleLine).join(", ");
|
|
38
41
|
return pages.length > maxItems ? `${shown}...` : shown;
|
|
39
42
|
}
|
|
40
43
|
function pageTitlesFromResult(text, details) {
|
|
41
|
-
if (details?.pageTitles
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
44
|
+
if (Array.isArray(details?.pageTitles)) {
|
|
45
|
+
const titles = details.pageTitles.filter((title) => typeof title === "string");
|
|
46
|
+
if (titles.length)
|
|
47
|
+
return titles;
|
|
48
|
+
}
|
|
49
|
+
if (Array.isArray(details?.sectionTitles)) {
|
|
50
|
+
const titles = details.sectionTitles.filter((title) => typeof title === "string");
|
|
51
|
+
if (titles.length)
|
|
52
|
+
return titles;
|
|
53
|
+
}
|
|
45
54
|
const fromContent = extractContentPages(text);
|
|
46
55
|
if (fromContent.length)
|
|
47
56
|
return fromContent;
|
|
@@ -55,10 +64,10 @@ function summarizeStructure(text, details) {
|
|
|
55
64
|
return `${count} pages · ${formatPageList(pages)}`;
|
|
56
65
|
}
|
|
57
66
|
function summarizeContents(text, details) {
|
|
58
|
-
if (details?.requestedPage) {
|
|
67
|
+
if (typeof details?.requestedPage === "string" && details.requestedPage.trim()) {
|
|
59
68
|
const position = details.pageIndex !== undefined && details.pageCount ? `${details.pageIndex}/${details.pageCount} · ` : "";
|
|
60
69
|
const cut = details.truncatedChars ? " (truncated)" : "";
|
|
61
|
-
return `Page ${position}${details.requestedPage}${cut}`;
|
|
70
|
+
return `Page ${position}${singleLine(details.requestedPage)}${cut}`;
|
|
62
71
|
}
|
|
63
72
|
const pages = pageTitlesFromResult(text, details);
|
|
64
73
|
if (details?.shownPages !== undefined) {
|
|
@@ -88,13 +97,16 @@ function summarizeQuestion(text) {
|
|
|
88
97
|
return truncateText(sentenceMatch?.[0] ?? cleaned, 140, { word: true });
|
|
89
98
|
}
|
|
90
99
|
function summarizeCollapsed(text, details) {
|
|
100
|
+
let summary;
|
|
91
101
|
if (details?.action === "structure")
|
|
92
|
-
|
|
93
|
-
if (details?.action === "contents")
|
|
94
|
-
|
|
95
|
-
if (details?.action === "question")
|
|
96
|
-
|
|
97
|
-
|
|
102
|
+
summary = summarizeStructure(text, details);
|
|
103
|
+
else if (details?.action === "contents")
|
|
104
|
+
summary = summarizeContents(text, details);
|
|
105
|
+
else if (details?.action === "question")
|
|
106
|
+
summary = summarizeQuestion(text);
|
|
107
|
+
else
|
|
108
|
+
summary = truncateText(firstContentLine(text), 120);
|
|
109
|
+
return truncateText(singleLine(summary), 180, { word: true });
|
|
98
110
|
}
|
|
99
111
|
function repoLabel(repoName) {
|
|
100
112
|
if (Array.isArray(repoName)) {
|
|
@@ -131,10 +143,10 @@ export function renderDeepWikiCall(args, theme) {
|
|
|
131
143
|
line += theme.fg("muted", args.action);
|
|
132
144
|
line += ` ${theme.fg("accent", repoLabelForCall(args.repoName))}`;
|
|
133
145
|
if (args.action === "question" && args.question) {
|
|
134
|
-
line += ` ${theme.fg("dim", truncateText(args.question, 64))}`;
|
|
146
|
+
line += ` ${theme.fg("dim", truncateText(singleLine(args.question), 64))}`;
|
|
135
147
|
}
|
|
136
148
|
else if (args.action === "contents" && args.page !== undefined) {
|
|
137
|
-
line += ` ${theme.fg("dim", truncateText(String(args.page), 40))}`;
|
|
149
|
+
line += ` ${theme.fg("dim", truncateText(singleLine(String(args.page)), 40))}`;
|
|
138
150
|
}
|
|
139
151
|
return new Text(line, 0, 0);
|
|
140
152
|
}
|
|
@@ -146,20 +158,20 @@ function markdownBlock(text) {
|
|
|
146
158
|
}
|
|
147
159
|
export function renderDeepWikiResult(result, options, theme, isError) {
|
|
148
160
|
if (options.isPartial) {
|
|
149
|
-
const repo = result.details?.repoName;
|
|
161
|
+
const repo = typeof result.details?.repoName === "string" ? singleLine(result.details.repoName) : "";
|
|
150
162
|
const label = repo ? `Querying ${repo}...` : "Querying...";
|
|
151
163
|
return new Text(theme.fg("warning", label), 0, 0);
|
|
152
164
|
}
|
|
153
165
|
const text = firstText(result);
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
const line = truncateText(
|
|
166
|
+
const errorMessage = typeof result.details?.errorMessage === "string" ? result.details.errorMessage : undefined;
|
|
167
|
+
if (isError || errorMessage) {
|
|
168
|
+
const line = truncateText(errorMessage ?? firstContentLine(text), 200);
|
|
157
169
|
return new Text(theme.fg("error", `failed · ${line}`), 0, 0);
|
|
158
170
|
}
|
|
159
171
|
if (!options.expanded) {
|
|
160
|
-
const summary = theme.fg("
|
|
161
|
-
const hint = `${theme.fg("muted", "(")}${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`;
|
|
162
|
-
return new Text(`${summary}
|
|
172
|
+
const summary = theme.fg("toolOutput", summarizeCollapsed(text, result.details));
|
|
173
|
+
const hint = `${theme.fg("muted", " (")}${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`;
|
|
174
|
+
return new Text(`${summary}${hint}`, 0, 0);
|
|
163
175
|
}
|
|
164
176
|
return markdownBlock(text);
|
|
165
177
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render.js","sourceRoot":"","sources":["../../../src/extensions/deepwiki/render.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAkB,SAAS,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAE3F,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAc,MAAM,wCAAwC,CAAC;AAEtF,OAAO,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAIhD,SAAS,YAAY,CAAC,IAAY,EAAE,SAAiB,EAAE,OAA4B,EAAU;IAC5F,IAAI,IAAI,CAAC,MAAM,IAAI,SAAS;QAAE,OAAO,IAAI,CAAC;IAC1C,IAAI,OAAO,EAAE,IAAI,EAAE,CAAC;QACnB,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,GAAG,CAAC,CAAC,CAAC;QAC5C,MAAM,SAAS,GAAG,MAAM,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;QAC1C,IAAI,SAAS,IAAI,EAAE;YAAE,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,CAAC,KAAK,CAAC;IAChE,CAAC;IACD,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC;AAAA,CAC5C;A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GAAG,CAAC,EAAE,CAAC;QAC7G,OAAO,IAAI,IAAI,CAAC,GAAG,OAAO,KAAK,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC9C,CAAC;IAED,OAAO,aAAa,CAAC,IAAI,CAAC,CAAC;AAAA,CAC3B","sourcesContent":["/**\n * TUI rendering for the deepwiki tool (collapse / expand).\n *\n * Pi's fallback renderer dumps full `content` text and ignores `expanded`; this\n * extension returns large wiki payloads, so a private renderer stays local here.\n */\nimport { type Component, Container, Markdown, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { AgentToolResult, ToolRenderResultOptions } from \"../../core/extensions/types.ts\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getMarkdownTheme, type Theme } from \"../../modes/interactive/theme/theme.ts\";\n\nimport { extractContentPages, extractStructureSections } from \"./client.ts\";\nimport { DEEPWIKI_LABEL } from \"./constants.ts\";\nimport type { DeepWikiDetails } from \"./execute.ts\";\nimport type { DeepWikiParams } from \"./schema.ts\";\n\nfunction truncateText(text: string, maxLength: number, options?: { word?: boolean }): string {\n\tif (text.length <= maxLength) return text;\n\tif (options?.word) {\n\t\tconst prefix = text.slice(0, maxLength - 3);\n\t\tconst lastSpace = prefix.lastIndexOf(\" \");\n\t\tif (lastSpace >= 40) return `${prefix.slice(0, lastSpace)}...`;\n\t}\n\treturn `${text.slice(0, maxLength - 3)}...`;\n}\n\nfunction firstText(result: AgentToolResult<DeepWikiDetails>): string {\n\tfor (const part of result.content ?? []) {\n\t\tif (part.type === \"text\" && typeof part.text === \"string\") return part.text;\n\t}\n\treturn \"\";\n}\n\nfunction firstContentLine(text: string): string {\n\treturn (\n\t\ttext\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trim())\n\t\t\t.find((line) => line.length > 0) ?? \"DeepWiki response\"\n\t);\n}\n\nfunction formatPageList(pages: string[], maxItems = 4): string {\n\tconst shown = pages.slice(0, maxItems).join(\", \");\n\treturn pages.length > maxItems ? `${shown}...` : shown;\n}\n\nfunction pageTitlesFromResult(text: string, details: DeepWikiDetails | undefined): string[] {\n\tif (details?.pageTitles?.length) return details.pageTitles;\n\tif (details?.sectionTitles?.length) return details.sectionTitles;\n\tconst fromContent = extractContentPages(text);\n\tif (fromContent.length) return fromContent;\n\treturn extractStructureSections(text);\n}\n\nfunction summarizeStructure(text: string, details: DeepWikiDetails | undefined): string {\n\tconst pages = pageTitlesFromResult(text, details);\n\tif (pages.length === 0) return truncateText(firstContentLine(text), 120);\n\tconst count = details?.pageCount ?? pages.length;\n\treturn `${count} pages · ${formatPageList(pages)}`;\n}\n\nfunction summarizeContents(text: string, details: DeepWikiDetails | undefined): string {\n\tif (details?.requestedPage) {\n\t\tconst position =\n\t\t\tdetails.pageIndex !== undefined && details.pageCount ? `${details.pageIndex}/${details.pageCount} · ` : \"\";\n\t\tconst cut = details.truncatedChars ? \" (truncated)\" : \"\";\n\t\treturn `Page ${position}${details.requestedPage}${cut}`;\n\t}\n\tconst pages = pageTitlesFromResult(text, details);\n\tif (details?.shownPages !== undefined) {\n\t\tconst total = details.pageCount ?? pages.length;\n\t\tconst pagesPart = total > 0 ? `${details.shownPages}/${total} pages` : \"partial\";\n\t\treturn `Wiki · ${pagesPart} shown (truncated)`;\n\t}\n\tif (pages.length === 0) return \"Wiki loaded\";\n\treturn `Wiki · ${details?.pageCount ?? pages.length} pages`;\n}\n\nfunction stripDeepWikiTail(text: string): string {\n\tconst tailIndex = text.search(/\\n(?:#+\\s*)?(?:Wiki pages you might want to explore|View this search)/i);\n\tif (tailIndex < 0) return text;\n\treturn text.slice(0, tailIndex);\n}\n\nfunction summarizeQuestion(text: string): string {\n\tconst cleaned = stripDeepWikiTail(text)\n\t\t.replace(/\\[([^\\]]+)\\]\\([^)]+\\)/g, \"$1\")\n\t\t.replace(/[`*_]/g, \"\")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n\tif (!cleaned) return \"Answer ready\";\n\tconst sentenceMatch = cleaned.match(/^.{40,}?[.!?](?=\\s|$)/);\n\treturn truncateText(sentenceMatch?.[0] ?? cleaned, 140, { word: true });\n}\n\nfunction summarizeCollapsed(text: string, details: DeepWikiDetails | undefined): string {\n\tif (details?.action === \"structure\") return summarizeStructure(text, details);\n\tif (details?.action === \"contents\") return summarizeContents(text, details);\n\tif (details?.action === \"question\") return summarizeQuestion(text);\n\treturn truncateText(firstContentLine(text), 120);\n}\n\nfunction repoLabel(repoName: DeepWikiParams[\"repoName\"] | undefined): string {\n\tif (Array.isArray(repoName)) {\n\t\tif (repoName.length === 0) return \"repo\";\n\t\tif (repoName.length === 1) return repoName[0];\n\t\treturn `${repoName.length} repos: ${repoName.slice(0, 2).join(\", \")}${repoName.length > 2 ? \"...\" : \"\"}`;\n\t}\n\treturn repoName ?? \"repo\";\n}\n\n/** renderCall sees raw tool args; normalize JSON-array strings for display. */\nfunction repoLabelForCall(repoName: unknown): string {\n\tif (Array.isArray(repoName)) return repoLabel(repoName as DeepWikiParams[\"repoName\"]);\n\tif (typeof repoName === \"string\") {\n\t\tconst trimmed = repoName.trim();\n\t\tif (trimmed.startsWith(\"[\")) {\n\t\t\ttry {\n\t\t\t\tconst parsed: unknown = JSON.parse(trimmed);\n\t\t\t\tif (Array.isArray(parsed)) return repoLabel(parsed as string[]);\n\t\t\t} catch {\n\t\t\t\t/* fall through */\n\t\t\t}\n\t\t}\n\t\treturn repoLabel(repoName);\n\t}\n\treturn repoLabel(undefined);\n}\n\nexport function renderDeepWikiCall(args: DeepWikiParams, theme: Theme): Component {\n\tlet line = theme.fg(\"toolTitle\", theme.bold(`${DEEPWIKI_LABEL} `));\n\tline += theme.fg(\"muted\", args.action);\n\tline += ` ${theme.fg(\"accent\", repoLabelForCall(args.repoName))}`;\n\tif (args.action === \"question\" && args.question) {\n\t\tline += ` ${theme.fg(\"dim\", truncateText(args.question, 64))}`;\n\t} else if (args.action === \"contents\" && args.page !== undefined) {\n\t\tline += ` ${theme.fg(\"dim\", truncateText(String(args.page), 40))}`;\n\t}\n\treturn new Text(line, 0, 0);\n}\n\nfunction markdownBlock(text: string): Component {\n\tconst container = new Container();\n\tcontainer.addChild(new Spacer(1));\n\tcontainer.addChild(new Markdown(text, 1, 0, getMarkdownTheme()));\n\treturn container;\n}\n\nexport function renderDeepWikiResult(\n\tresult: AgentToolResult<DeepWikiDetails>,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tisError: boolean,\n): Component {\n\tif (options.isPartial) {\n\t\tconst repo = result.details?.repoName;\n\t\tconst label = repo ? `Querying ${repo}...` : \"Querying...\";\n\t\treturn new Text(theme.fg(\"warning\", label), 0, 0);\n\t}\n\n\tconst text = firstText(result);\n\tif (isError || result.details?.errorMessage) {\n\t\tconst msg = result.details?.errorMessage ?? firstContentLine(text);\n\t\tconst line = truncateText(msg, 200);\n\t\treturn new Text(theme.fg(\"error\", `failed · ${line}`), 0, 0);\n\t}\n\n\tif (!options.expanded) {\n\t\tconst summary = theme.fg(\"accent\", summarizeCollapsed(text, result.details));\n\t\tconst hint = `${theme.fg(\"muted\", \"(\")}${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\treturn new Text(`${summary}\\n${hint}`, 0, 0);\n\t}\n\n\treturn markdownBlock(text);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"render.js","sourceRoot":"","sources":["../../../src/extensions/deepwiki/render.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAkB,SAAS,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,wBAAwB,CAAC;AAE3F,OAAO,EAAE,OAAO,EAAE,MAAM,wDAAwD,CAAC;AACjF,OAAO,EAAE,gBAAgB,EAAc,MAAM,wCAAwC,CAAC;AAEtF,OAAO,EAAE,mBAAmB,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAC5E,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAIhD,SAAS,YAAY,CAA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,CAAC;IAC9D,CAAC;IAED,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC;QACvB,MAAM,OAAO,GAAG,KAAK,CAAC,EAAE,CAAC,YAAY,EAAE,kBAAkB,CAAC,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC;QACjF,MAAM,IAAI,GAAG,GAAG,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,IAAI,CAAC,GAAG,OAAO,CAAC,kBAAkB,EAAE,WAAW,CAAC,GAAG,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC;QAC9G,OAAO,IAAI,IAAI,CAAC,GAAG,OAAO,GAAG,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC5C,CAAC;IAED,OAAO,aAAa,CAAC,IAAI,CAAC,CAAC;AAAA,CAC3B","sourcesContent":["/**\n * TUI rendering for the deepwiki tool (collapse / expand).\n *\n * Pi's fallback renderer dumps full `content` text and ignores `expanded`; this\n * extension returns large wiki payloads, so a private renderer stays local here.\n */\nimport { type Component, Container, Markdown, Spacer, Text } from \"@earendil-works/pi-tui\";\nimport type { AgentToolResult, ToolRenderResultOptions } from \"../../core/extensions/types.ts\";\nimport { keyHint } from \"../../modes/interactive/components/keybinding-hints.ts\";\nimport { getMarkdownTheme, type Theme } from \"../../modes/interactive/theme/theme.ts\";\n\nimport { extractContentPages, extractStructureSections } from \"./client.ts\";\nimport { DEEPWIKI_LABEL } from \"./constants.ts\";\nimport type { DeepWikiDetails } from \"./execute.ts\";\nimport type { DeepWikiParams } from \"./schema.ts\";\n\nfunction truncateText(text: string, maxLength: number, options?: { word?: boolean }): string {\n\tif (text.length <= maxLength) return text;\n\tif (options?.word) {\n\t\tconst prefix = text.slice(0, maxLength - 3);\n\t\tconst lastSpace = prefix.lastIndexOf(\" \");\n\t\tif (lastSpace >= 40) return `${prefix.slice(0, lastSpace)}...`;\n\t}\n\treturn `${text.slice(0, maxLength - 3)}...`;\n}\n\nfunction singleLine(text: unknown): string {\n\treturn typeof text === \"string\" ? text.replace(/\\s+/g, \" \").trim() : \"\";\n}\n\nfunction firstText(result: AgentToolResult<DeepWikiDetails>): string {\n\tfor (const part of result.content ?? []) {\n\t\tif (part.type === \"text\" && typeof part.text === \"string\") return part.text;\n\t}\n\treturn \"\";\n}\n\nfunction firstContentLine(text: string): string {\n\treturn (\n\t\ttext\n\t\t\t.split(\"\\n\")\n\t\t\t.map((line) => line.trim())\n\t\t\t.find((line) => line.length > 0) ?? \"DeepWiki response\"\n\t);\n}\n\nfunction formatPageList(pages: string[], maxItems = 4): string {\n\tconst shown = pages.slice(0, maxItems).map(singleLine).join(\", \");\n\treturn pages.length > maxItems ? `${shown}...` : shown;\n}\n\nfunction pageTitlesFromResult(text: string, details: DeepWikiDetails | undefined): string[] {\n\tif (Array.isArray(details?.pageTitles)) {\n\t\tconst titles = details.pageTitles.filter((title) => typeof title === \"string\");\n\t\tif (titles.length) return titles;\n\t}\n\tif (Array.isArray(details?.sectionTitles)) {\n\t\tconst titles = details.sectionTitles.filter((title) => typeof title === \"string\");\n\t\tif (titles.length) return titles;\n\t}\n\tconst fromContent = extractContentPages(text);\n\tif (fromContent.length) return fromContent;\n\treturn extractStructureSections(text);\n}\n\nfunction summarizeStructure(text: string, details: DeepWikiDetails | undefined): string {\n\tconst pages = pageTitlesFromResult(text, details);\n\tif (pages.length === 0) return truncateText(firstContentLine(text), 120);\n\tconst count = details?.pageCount ?? pages.length;\n\treturn `${count} pages · ${formatPageList(pages)}`;\n}\n\nfunction summarizeContents(text: string, details: DeepWikiDetails | undefined): string {\n\tif (typeof details?.requestedPage === \"string\" && details.requestedPage.trim()) {\n\t\tconst position =\n\t\t\tdetails.pageIndex !== undefined && details.pageCount ? `${details.pageIndex}/${details.pageCount} · ` : \"\";\n\t\tconst cut = details.truncatedChars ? \" (truncated)\" : \"\";\n\t\treturn `Page ${position}${singleLine(details.requestedPage)}${cut}`;\n\t}\n\tconst pages = pageTitlesFromResult(text, details);\n\tif (details?.shownPages !== undefined) {\n\t\tconst total = details.pageCount ?? pages.length;\n\t\tconst pagesPart = total > 0 ? `${details.shownPages}/${total} pages` : \"partial\";\n\t\treturn `Wiki · ${pagesPart} shown (truncated)`;\n\t}\n\tif (pages.length === 0) return \"Wiki loaded\";\n\treturn `Wiki · ${details?.pageCount ?? pages.length} pages`;\n}\n\nfunction stripDeepWikiTail(text: string): string {\n\tconst tailIndex = text.search(/\\n(?:#+\\s*)?(?:Wiki pages you might want to explore|View this search)/i);\n\tif (tailIndex < 0) return text;\n\treturn text.slice(0, tailIndex);\n}\n\nfunction summarizeQuestion(text: string): string {\n\tconst cleaned = stripDeepWikiTail(text)\n\t\t.replace(/\\[([^\\]]+)\\]\\([^)]+\\)/g, \"$1\")\n\t\t.replace(/[`*_]/g, \"\")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n\tif (!cleaned) return \"Answer ready\";\n\tconst sentenceMatch = cleaned.match(/^.{40,}?[.!?](?=\\s|$)/);\n\treturn truncateText(sentenceMatch?.[0] ?? cleaned, 140, { word: true });\n}\n\nfunction summarizeCollapsed(text: string, details: DeepWikiDetails | undefined): string {\n\tlet summary: string;\n\tif (details?.action === \"structure\") summary = summarizeStructure(text, details);\n\telse if (details?.action === \"contents\") summary = summarizeContents(text, details);\n\telse if (details?.action === \"question\") summary = summarizeQuestion(text);\n\telse summary = truncateText(firstContentLine(text), 120);\n\treturn truncateText(singleLine(summary), 180, { word: true });\n}\n\nfunction repoLabel(repoName: DeepWikiParams[\"repoName\"] | undefined): string {\n\tif (Array.isArray(repoName)) {\n\t\tif (repoName.length === 0) return \"repo\";\n\t\tif (repoName.length === 1) return repoName[0];\n\t\treturn `${repoName.length} repos: ${repoName.slice(0, 2).join(\", \")}${repoName.length > 2 ? \"...\" : \"\"}`;\n\t}\n\treturn repoName ?? \"repo\";\n}\n\n/** renderCall sees raw tool args; normalize JSON-array strings for display. */\nfunction repoLabelForCall(repoName: unknown): string {\n\tif (Array.isArray(repoName)) return repoLabel(repoName as DeepWikiParams[\"repoName\"]);\n\tif (typeof repoName === \"string\") {\n\t\tconst trimmed = repoName.trim();\n\t\tif (trimmed.startsWith(\"[\")) {\n\t\t\ttry {\n\t\t\t\tconst parsed: unknown = JSON.parse(trimmed);\n\t\t\t\tif (Array.isArray(parsed)) return repoLabel(parsed as string[]);\n\t\t\t} catch {\n\t\t\t\t/* fall through */\n\t\t\t}\n\t\t}\n\t\treturn repoLabel(repoName);\n\t}\n\treturn repoLabel(undefined);\n}\n\nexport function renderDeepWikiCall(args: DeepWikiParams, theme: Theme): Component {\n\tlet line = theme.fg(\"toolTitle\", theme.bold(`${DEEPWIKI_LABEL} `));\n\tline += theme.fg(\"muted\", args.action);\n\tline += ` ${theme.fg(\"accent\", repoLabelForCall(args.repoName))}`;\n\tif (args.action === \"question\" && args.question) {\n\t\tline += ` ${theme.fg(\"dim\", truncateText(singleLine(args.question), 64))}`;\n\t} else if (args.action === \"contents\" && args.page !== undefined) {\n\t\tline += ` ${theme.fg(\"dim\", truncateText(singleLine(String(args.page)), 40))}`;\n\t}\n\treturn new Text(line, 0, 0);\n}\n\nfunction markdownBlock(text: string): Component {\n\tconst container = new Container();\n\tcontainer.addChild(new Spacer(1));\n\tcontainer.addChild(new Markdown(text, 1, 0, getMarkdownTheme()));\n\treturn container;\n}\n\nexport function renderDeepWikiResult(\n\tresult: AgentToolResult<DeepWikiDetails>,\n\toptions: ToolRenderResultOptions,\n\ttheme: Theme,\n\tisError: boolean,\n): Component {\n\tif (options.isPartial) {\n\t\tconst repo = typeof result.details?.repoName === \"string\" ? singleLine(result.details.repoName) : \"\";\n\t\tconst label = repo ? `Querying ${repo}...` : \"Querying...\";\n\t\treturn new Text(theme.fg(\"warning\", label), 0, 0);\n\t}\n\n\tconst text = firstText(result);\n\tconst errorMessage = typeof result.details?.errorMessage === \"string\" ? result.details.errorMessage : undefined;\n\tif (isError || errorMessage) {\n\t\tconst line = truncateText(errorMessage ?? firstContentLine(text), 200);\n\t\treturn new Text(theme.fg(\"error\", `failed · ${line}`), 0, 0);\n\t}\n\n\tif (!options.expanded) {\n\t\tconst summary = theme.fg(\"toolOutput\", summarizeCollapsed(text, result.details));\n\t\tconst hint = `${theme.fg(\"muted\", \" (\")}${keyHint(\"app.tools.expand\", \"to expand\")}${theme.fg(\"muted\", \")\")}`;\n\t\treturn new Text(`${summary}${hint}`, 0, 0);\n\t}\n\n\treturn markdownBlock(text);\n}\n"]}
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* matching the todo/question constants.ts pattern. Prompt copy is the
|
|
6
6
|
* model-facing contract; keep it stable.
|
|
7
7
|
*/
|
|
8
|
+
import type { SelectOption } from "../../core/extensions/types.ts";
|
|
8
9
|
export declare const EXIT_PLAN_TOOL_NAME = "exit_plan";
|
|
9
10
|
export declare const EXIT_PLAN_TOOL_LABEL = "Exit Plan";
|
|
10
11
|
export declare const PLAN_COMMAND_NAME = "plan";
|
|
@@ -12,17 +13,53 @@ export declare const PLAN_FLAG_NAME = "plan";
|
|
|
12
13
|
export declare const PLAN_ENTRY_TYPE = "plan-mode";
|
|
13
14
|
export declare const PLAN_STATUS_KEY = "plan-mode";
|
|
14
15
|
/**
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
|
|
18
|
-
|
|
16
|
+
* customType of the post-compaction kickoff message. Sent via sendMessage so
|
|
17
|
+
* the LLM receives the full plan while the TUI renders a collapsed card.
|
|
18
|
+
*/
|
|
19
|
+
export declare const PLAN_KICKOFF_MESSAGE_TYPE = "plan-kickoff";
|
|
20
|
+
/**
|
|
21
|
+
* Tools blocked while planning: edit/write grant write access directly.
|
|
22
|
+
* bash stays available and is constrained to read-only inspection via the
|
|
23
|
+
* plan-mode system prompt (same contract as the explorer subagent), and
|
|
24
|
+
* subagent stays available but is limited to the built-in explorer profile
|
|
25
|
+
* by the tool_call guard. Other extension tools (question, todo, deepwiki,
|
|
26
|
+
* ...) stay available.
|
|
19
27
|
*/
|
|
20
28
|
export declare const PLAN_BLOCKED_TOOLS: ReadonlySet<string>;
|
|
29
|
+
/**
|
|
30
|
+
* Exploration tools activated on entry. Mirrors the explorer subagent's
|
|
31
|
+
* EXPLORER_TOOLS (kept as a separate constant so plan does not depend on the
|
|
32
|
+
* subagent extension): the standalone search tools plus bash for read-only
|
|
33
|
+
* inspection. grep/find/ls are registered but not active in the default
|
|
34
|
+
* session tool set, so plan mode must activate them explicitly.
|
|
35
|
+
*/
|
|
36
|
+
export declare const PLAN_EXPLORE_TOOLS: readonly string[];
|
|
37
|
+
/** Only subagent profile allowed while planning (read-only exploration). */
|
|
38
|
+
export declare const PLAN_ALLOWED_SUBAGENT = "explorer";
|
|
39
|
+
/** Name of the subagent extension tool, for the plan-mode tool_call guard. */
|
|
40
|
+
export declare const PLAN_SUBAGENT_TOOL_NAME = "subagent";
|
|
21
41
|
/** Max characters of plan markdown echoed into the post-compaction kickoff message. */
|
|
22
42
|
export declare const PLAN_EMBED_MAX_CHARS = 24000;
|
|
23
|
-
export declare const MENU_EXECUTE = "Start executing
|
|
24
|
-
export declare const MENU_COMPACT_EXECUTE = "Compact context, then execute
|
|
43
|
+
export declare const MENU_EXECUTE = "Start executing";
|
|
44
|
+
export declare const MENU_COMPACT_EXECUTE = "Compact context, then execute";
|
|
25
45
|
export declare const MENU_KEEP_PLANNING = "Keep planning";
|
|
46
|
+
/**
|
|
47
|
+
* Approval choices. The label is the decision, the description is the
|
|
48
|
+
* trade-off, so the three options can be told apart without reading to the
|
|
49
|
+
* end of a sentence. select() resolves to the label.
|
|
50
|
+
*/
|
|
51
|
+
export declare const EXIT_PLAN_MENU_OPTIONS: readonly SelectOption[];
|
|
52
|
+
/** Esc maps to "keep planning", so the dismiss hint must not read as "discard". */
|
|
53
|
+
export declare const EXIT_PLAN_CANCEL_HINT = "keep planning";
|
|
54
|
+
/**
|
|
55
|
+
* /plan panel (shown when the command runs while planning): exit is the first
|
|
56
|
+
* option, saved plans follow. Esc keeps planning with no side effects.
|
|
57
|
+
*/
|
|
58
|
+
export declare const PLAN_PANEL_TITLE = "Plan mode";
|
|
59
|
+
export declare const PLAN_PANEL_EXIT = "Exit plan mode";
|
|
60
|
+
export declare const PLAN_PANEL_EXIT_DESCRIPTION = "restore full tool access";
|
|
61
|
+
export declare const PLAN_PANEL_CANCEL_HINT = "keep planning";
|
|
62
|
+
export declare const PLAN_PANEL_MAX_FILES = 20;
|
|
26
63
|
export declare const EXIT_PLAN_TOOL_DESCRIPTION = "Submit the finished plan and ask the user to approve leaving plan mode. Present the complete plan as normal response text first, then call this tool with a short title and the same plan markdown; on approval the plan is saved to disk. The user chooses between executing with full context, compacting the context before executing, or continuing to plan. Only available while plan mode is active.";
|
|
27
64
|
export declare const EXIT_PLAN_PROMPT_SNIPPET = "Submit the finished plan for user approval and leave plan mode";
|
|
28
65
|
export declare const EXIT_PLAN_PROMPT_GUIDELINES: string[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/extensions/plan/constants.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,eAAO,MAAM,mBAAmB,cAAc,CAAC;AAC/C,eAAO,MAAM,oBAAoB,cAAc,CAAC;AAChD,eAAO,MAAM,iBAAiB,SAAS,CAAC;AACxC,eAAO,MAAM,cAAc,SAAS,CAAC;AACrC,eAAO,MAAM,eAAe,cAAc,CAAC;AAC3C,eAAO,MAAM,eAAe,cAAc,CAAC;AAE3C
|
|
1
|
+
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/extensions/plan/constants.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAEnE,eAAO,MAAM,mBAAmB,cAAc,CAAC;AAC/C,eAAO,MAAM,oBAAoB,cAAc,CAAC;AAChD,eAAO,MAAM,iBAAiB,SAAS,CAAC;AACxC,eAAO,MAAM,cAAc,SAAS,CAAC;AACrC,eAAO,MAAM,eAAe,cAAc,CAAC;AAC3C,eAAO,MAAM,eAAe,cAAc,CAAC;AAE3C;;;GAGG;AACH,eAAO,MAAM,yBAAyB,iBAAiB,CAAC;AAExD;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB,EAAE,WAAW,CAAC,MAAM,CAA8B,CAAC;AAElF;;;;;;GAMG;AACH,eAAO,MAAM,kBAAkB,EAAE,SAAS,MAAM,EAA2C,CAAC;AAE5F,4EAA4E;AAC5E,eAAO,MAAM,qBAAqB,aAAa,CAAC;AAEhD,8EAA8E;AAC9E,eAAO,MAAM,uBAAuB,aAAa,CAAC;AAElD,uFAAuF;AACvF,eAAO,MAAM,oBAAoB,QAAS,CAAC;AAE3C,eAAO,MAAM,YAAY,oBAAoB,CAAC;AAC9C,eAAO,MAAM,oBAAoB,kCAAkC,CAAC;AACpE,eAAO,MAAM,kBAAkB,kBAAkB,CAAC;AAElD;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,EAAE,SAAS,YAAY,EAIzD,CAAC;AAEF,mFAAmF;AACnF,eAAO,MAAM,qBAAqB,kBAAkB,CAAC;AAErD;;;GAGG;AACH,eAAO,MAAM,gBAAgB,cAAc,CAAC;AAC5C,eAAO,MAAM,eAAe,mBAAmB,CAAC;AAChD,eAAO,MAAM,2BAA2B,6BAA6B,CAAC;AACtE,eAAO,MAAM,sBAAsB,kBAAkB,CAAC;AACtD,eAAO,MAAM,oBAAoB,KAAK,CAAC;AAEvC,eAAO,MAAM,0BAA0B,+YACsW,CAAC;AAE9Y,eAAO,MAAM,wBAAwB,mEAAmE,CAAC;AAEzG,eAAO,MAAM,2BAA2B,UAGvC,CAAC;AAoBF,4FAA4F;AAC5F,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,CAQ/D","sourcesContent":["/**\n * plan/constants.ts — tool identity, command names, and prompt copy.\n *\n * Name/label/command live here so `index.ts` only assembles the extension,\n * matching the todo/question constants.ts pattern. Prompt copy is the\n * model-facing contract; keep it stable.\n */\n\nimport type { SelectOption } from \"../../core/extensions/types.ts\";\n\nexport const EXIT_PLAN_TOOL_NAME = \"exit_plan\";\nexport const EXIT_PLAN_TOOL_LABEL = \"Exit Plan\";\nexport const PLAN_COMMAND_NAME = \"plan\";\nexport const PLAN_FLAG_NAME = \"plan\";\nexport const PLAN_ENTRY_TYPE = \"plan-mode\";\nexport const PLAN_STATUS_KEY = \"plan-mode\";\n\n/**\n * customType of the post-compaction kickoff message. Sent via sendMessage so\n * the LLM receives the full plan while the TUI renders a collapsed card.\n */\nexport const PLAN_KICKOFF_MESSAGE_TYPE = \"plan-kickoff\";\n\n/**\n * Tools blocked while planning: edit/write grant write access directly.\n * bash stays available and is constrained to read-only inspection via the\n * plan-mode system prompt (same contract as the explorer subagent), and\n * subagent stays available but is limited to the built-in explorer profile\n * by the tool_call guard. Other extension tools (question, todo, deepwiki,\n * ...) stay available.\n */\nexport const PLAN_BLOCKED_TOOLS: ReadonlySet<string> = new Set([\"edit\", \"write\"]);\n\n/**\n * Exploration tools activated on entry. Mirrors the explorer subagent's\n * EXPLORER_TOOLS (kept as a separate constant so plan does not depend on the\n * subagent extension): the standalone search tools plus bash for read-only\n * inspection. grep/find/ls are registered but not active in the default\n * session tool set, so plan mode must activate them explicitly.\n */\nexport const PLAN_EXPLORE_TOOLS: readonly string[] = [\"read\", \"grep\", \"find\", \"ls\", \"bash\"];\n\n/** Only subagent profile allowed while planning (read-only exploration). */\nexport const PLAN_ALLOWED_SUBAGENT = \"explorer\";\n\n/** Name of the subagent extension tool, for the plan-mode tool_call guard. */\nexport const PLAN_SUBAGENT_TOOL_NAME = \"subagent\";\n\n/** Max characters of plan markdown echoed into the post-compaction kickoff message. */\nexport const PLAN_EMBED_MAX_CHARS = 24_000;\n\nexport const MENU_EXECUTE = \"Start executing\";\nexport const MENU_COMPACT_EXECUTE = \"Compact context, then execute\";\nexport const MENU_KEEP_PLANNING = \"Keep planning\";\n\n/**\n * Approval choices. The label is the decision, the description is the\n * trade-off, so the three options can be told apart without reading to the\n * end of a sentence. select() resolves to the label.\n */\nexport const EXIT_PLAN_MENU_OPTIONS: readonly SelectOption[] = [\n\t{ label: MENU_EXECUTE, description: \"keep full context\" },\n\t{ label: MENU_COMPACT_EXECUTE, description: \"best for long tasks\" },\n\t{ label: MENU_KEEP_PLANNING, description: \"refine before running\" },\n];\n\n/** Esc maps to \"keep planning\", so the dismiss hint must not read as \"discard\". */\nexport const EXIT_PLAN_CANCEL_HINT = \"keep planning\";\n\n/**\n * /plan panel (shown when the command runs while planning): exit is the first\n * option, saved plans follow. Esc keeps planning with no side effects.\n */\nexport const PLAN_PANEL_TITLE = \"Plan mode\";\nexport const PLAN_PANEL_EXIT = \"Exit plan mode\";\nexport const PLAN_PANEL_EXIT_DESCRIPTION = \"restore full tool access\";\nexport const PLAN_PANEL_CANCEL_HINT = \"keep planning\";\nexport const PLAN_PANEL_MAX_FILES = 20;\n\nexport const EXIT_PLAN_TOOL_DESCRIPTION =\n\t\"Submit the finished plan and ask the user to approve leaving plan mode. Present the complete plan as normal response text first, then call this tool with a short title and the same plan markdown; on approval the plan is saved to disk. The user chooses between executing with full context, compacting the context before executing, or continuing to plan. Only available while plan mode is active.\";\n\nexport const EXIT_PLAN_PROMPT_SNIPPET = \"Submit the finished plan for user approval and leave plan mode\";\n\nexport const EXIT_PLAN_PROMPT_GUIDELINES = [\n\t\"Call `exit_plan` only after presenting the complete plan as response text; make it the only tool call in that step and stop after it returns.\",\n\t\"`exit_plan` results are authoritative for plan-mode state: follow them even when the plan-mode system prompt block is still present later in the run.\",\n];\n\nconst PLAN_MODE_PROMPT = `[PLAN MODE]\nYou are in plan mode: a read-only phase for exploring the codebase and agreeing on a plan with the user before any changes are made.\n\nRestrictions:\n- edit and write are unavailable; do not attempt changes or workarounds.\n- bash is for read-only inspection only: git log/diff/blame/show/status, ls, wc, head, tail, cat, and similar. Never run anything that modifies state: no file creation or deletion, no redirect (>, >>) or heredoc writes, no temp files, no git commands that write (add, commit, checkout, restore, stash, clean), no installs, no network access.\n- subagent is limited to the read-only explorer profile: always pass agent: \"${PLAN_ALLOWED_SUBAGENT}\"; other profiles are blocked while planning.\n- Explore with read, grep, find, ls, read-only bash, and explorer subagents.\n\nWorking style:\n- Answer questions from the code, not from the user: explore before asking.\n- When product intent, scope, or risk tolerance is unclear, interview the user with the question tool. Focus on one decision per exchange (batch only tightly coupled decisions) and always include your recommendation and the trade-offs.\n- Skip the interview for small, clear tasks. Pick sensible defaults for low-risk details and state them in the plan.\n\nDelivering the plan:\n- When the plan is ready, present it in full as normal response text (goal, steps, verification criteria) so the user can read it, then call exit_plan with a short title and the same markdown as the plan parameter.\n- The exit_plan tool result is authoritative for mode state: this block can outlive plan mode within a run, so if the result says plan mode has ended, it has ended.`;\n\n/** Build the plan-mode system prompt block, listing plans already saved for this branch. */\nexport function buildPlanModePrompt(planFiles: string[]): string {\n\tif (!planFiles.length) return PLAN_MODE_PROMPT;\n\tconst listing = planFiles.map((path) => `- ${path}`).join(\"\\n\");\n\treturn `${PLAN_MODE_PROMPT}\n\nPlans already saved for this session (read them with the read tool):\n${listing}\nWhen revising a saved plan, read the latest one first, account for work already completed, and produce a revision that states what changed and why; set the revises parameter to the file name of the plan being revised.`;\n}\n"]}
|
|
@@ -12,17 +12,57 @@ export const PLAN_FLAG_NAME = "plan";
|
|
|
12
12
|
export const PLAN_ENTRY_TYPE = "plan-mode";
|
|
13
13
|
export const PLAN_STATUS_KEY = "plan-mode";
|
|
14
14
|
/**
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* so leaving it active would let the model write through a child agent.
|
|
18
|
-
* Other extension tools (question, todo, deepwiki, ...) stay available.
|
|
15
|
+
* customType of the post-compaction kickoff message. Sent via sendMessage so
|
|
16
|
+
* the LLM receives the full plan while the TUI renders a collapsed card.
|
|
19
17
|
*/
|
|
20
|
-
export const
|
|
18
|
+
export const PLAN_KICKOFF_MESSAGE_TYPE = "plan-kickoff";
|
|
19
|
+
/**
|
|
20
|
+
* Tools blocked while planning: edit/write grant write access directly.
|
|
21
|
+
* bash stays available and is constrained to read-only inspection via the
|
|
22
|
+
* plan-mode system prompt (same contract as the explorer subagent), and
|
|
23
|
+
* subagent stays available but is limited to the built-in explorer profile
|
|
24
|
+
* by the tool_call guard. Other extension tools (question, todo, deepwiki,
|
|
25
|
+
* ...) stay available.
|
|
26
|
+
*/
|
|
27
|
+
export const PLAN_BLOCKED_TOOLS = new Set(["edit", "write"]);
|
|
28
|
+
/**
|
|
29
|
+
* Exploration tools activated on entry. Mirrors the explorer subagent's
|
|
30
|
+
* EXPLORER_TOOLS (kept as a separate constant so plan does not depend on the
|
|
31
|
+
* subagent extension): the standalone search tools plus bash for read-only
|
|
32
|
+
* inspection. grep/find/ls are registered but not active in the default
|
|
33
|
+
* session tool set, so plan mode must activate them explicitly.
|
|
34
|
+
*/
|
|
35
|
+
export const PLAN_EXPLORE_TOOLS = ["read", "grep", "find", "ls", "bash"];
|
|
36
|
+
/** Only subagent profile allowed while planning (read-only exploration). */
|
|
37
|
+
export const PLAN_ALLOWED_SUBAGENT = "explorer";
|
|
38
|
+
/** Name of the subagent extension tool, for the plan-mode tool_call guard. */
|
|
39
|
+
export const PLAN_SUBAGENT_TOOL_NAME = "subagent";
|
|
21
40
|
/** Max characters of plan markdown echoed into the post-compaction kickoff message. */
|
|
22
41
|
export const PLAN_EMBED_MAX_CHARS = 24_000;
|
|
23
|
-
export const MENU_EXECUTE = "Start executing
|
|
24
|
-
export const MENU_COMPACT_EXECUTE = "Compact context, then execute
|
|
42
|
+
export const MENU_EXECUTE = "Start executing";
|
|
43
|
+
export const MENU_COMPACT_EXECUTE = "Compact context, then execute";
|
|
25
44
|
export const MENU_KEEP_PLANNING = "Keep planning";
|
|
45
|
+
/**
|
|
46
|
+
* Approval choices. The label is the decision, the description is the
|
|
47
|
+
* trade-off, so the three options can be told apart without reading to the
|
|
48
|
+
* end of a sentence. select() resolves to the label.
|
|
49
|
+
*/
|
|
50
|
+
export const EXIT_PLAN_MENU_OPTIONS = [
|
|
51
|
+
{ label: MENU_EXECUTE, description: "keep full context" },
|
|
52
|
+
{ label: MENU_COMPACT_EXECUTE, description: "best for long tasks" },
|
|
53
|
+
{ label: MENU_KEEP_PLANNING, description: "refine before running" },
|
|
54
|
+
];
|
|
55
|
+
/** Esc maps to "keep planning", so the dismiss hint must not read as "discard". */
|
|
56
|
+
export const EXIT_PLAN_CANCEL_HINT = "keep planning";
|
|
57
|
+
/**
|
|
58
|
+
* /plan panel (shown when the command runs while planning): exit is the first
|
|
59
|
+
* option, saved plans follow. Esc keeps planning with no side effects.
|
|
60
|
+
*/
|
|
61
|
+
export const PLAN_PANEL_TITLE = "Plan mode";
|
|
62
|
+
export const PLAN_PANEL_EXIT = "Exit plan mode";
|
|
63
|
+
export const PLAN_PANEL_EXIT_DESCRIPTION = "restore full tool access";
|
|
64
|
+
export const PLAN_PANEL_CANCEL_HINT = "keep planning";
|
|
65
|
+
export const PLAN_PANEL_MAX_FILES = 20;
|
|
26
66
|
export const EXIT_PLAN_TOOL_DESCRIPTION = "Submit the finished plan and ask the user to approve leaving plan mode. Present the complete plan as normal response text first, then call this tool with a short title and the same plan markdown; on approval the plan is saved to disk. The user chooses between executing with full context, compacting the context before executing, or continuing to plan. Only available while plan mode is active.";
|
|
27
67
|
export const EXIT_PLAN_PROMPT_SNIPPET = "Submit the finished plan for user approval and leave plan mode";
|
|
28
68
|
export const EXIT_PLAN_PROMPT_GUIDELINES = [
|
|
@@ -33,7 +73,10 @@ const PLAN_MODE_PROMPT = `[PLAN MODE]
|
|
|
33
73
|
You are in plan mode: a read-only phase for exploring the codebase and agreeing on a plan with the user before any changes are made.
|
|
34
74
|
|
|
35
75
|
Restrictions:
|
|
36
|
-
- edit
|
|
76
|
+
- edit and write are unavailable; do not attempt changes or workarounds.
|
|
77
|
+
- bash is for read-only inspection only: git log/diff/blame/show/status, ls, wc, head, tail, cat, and similar. Never run anything that modifies state: no file creation or deletion, no redirect (>, >>) or heredoc writes, no temp files, no git commands that write (add, commit, checkout, restore, stash, clean), no installs, no network access.
|
|
78
|
+
- subagent is limited to the read-only explorer profile: always pass agent: "${PLAN_ALLOWED_SUBAGENT}"; other profiles are blocked while planning.
|
|
79
|
+
- Explore with read, grep, find, ls, read-only bash, and explorer subagents.
|
|
37
80
|
|
|
38
81
|
Working style:
|
|
39
82
|
- Answer questions from the code, not from the user: explore before asking.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/extensions/plan/constants.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;
|
|
1
|
+
{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/extensions/plan/constants.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH,MAAM,CAAC,MAAM,mBAAmB,GAAG,WAAW,CAAC;AAC/C,MAAM,CAAC,MAAM,oBAAoB,GAAG,WAAW,CAAC;AAChD,MAAM,CAAC,MAAM,iBAAiB,GAAG,MAAM,CAAC;AACxC,MAAM,CAAC,MAAM,cAAc,GAAG,MAAM,CAAC;AACrC,MAAM,CAAC,MAAM,eAAe,GAAG,WAAW,CAAC;AAC3C,MAAM,CAAC,MAAM,eAAe,GAAG,WAAW,CAAC;AAE3C;;;GAGG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,cAAc,CAAC;AAExD;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAwB,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;AAElF;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAsB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAE5F,4EAA4E;AAC5E,MAAM,CAAC,MAAM,qBAAqB,GAAG,UAAU,CAAC;AAEhD,8EAA8E;AAC9E,MAAM,CAAC,MAAM,uBAAuB,GAAG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MAAM,OAAO,GAAG,SAAS,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAChE,OAAO,GAAG,gBAAgB;;;EAGzB,OAAO;0NACiN,CAAC;AAAA,CAC1N","sourcesContent":["/**\n * plan/constants.ts — tool identity, command names, and prompt copy.\n *\n * Name/label/command live here so `index.ts` only assembles the extension,\n * matching the todo/question constants.ts pattern. Prompt copy is the\n * model-facing contract; keep it stable.\n */\n\nimport type { SelectOption } from \"../../core/extensions/types.ts\";\n\nexport const EXIT_PLAN_TOOL_NAME = \"exit_plan\";\nexport const EXIT_PLAN_TOOL_LABEL = \"Exit Plan\";\nexport const PLAN_COMMAND_NAME = \"plan\";\nexport const PLAN_FLAG_NAME = \"plan\";\nexport const PLAN_ENTRY_TYPE = \"plan-mode\";\nexport const PLAN_STATUS_KEY = \"plan-mode\";\n\n/**\n * customType of the post-compaction kickoff message. Sent via sendMessage so\n * the LLM receives the full plan while the TUI renders a collapsed card.\n */\nexport const PLAN_KICKOFF_MESSAGE_TYPE = \"plan-kickoff\";\n\n/**\n * Tools blocked while planning: edit/write grant write access directly.\n * bash stays available and is constrained to read-only inspection via the\n * plan-mode system prompt (same contract as the explorer subagent), and\n * subagent stays available but is limited to the built-in explorer profile\n * by the tool_call guard. Other extension tools (question, todo, deepwiki,\n * ...) stay available.\n */\nexport const PLAN_BLOCKED_TOOLS: ReadonlySet<string> = new Set([\"edit\", \"write\"]);\n\n/**\n * Exploration tools activated on entry. Mirrors the explorer subagent's\n * EXPLORER_TOOLS (kept as a separate constant so plan does not depend on the\n * subagent extension): the standalone search tools plus bash for read-only\n * inspection. grep/find/ls are registered but not active in the default\n * session tool set, so plan mode must activate them explicitly.\n */\nexport const PLAN_EXPLORE_TOOLS: readonly string[] = [\"read\", \"grep\", \"find\", \"ls\", \"bash\"];\n\n/** Only subagent profile allowed while planning (read-only exploration). */\nexport const PLAN_ALLOWED_SUBAGENT = \"explorer\";\n\n/** Name of the subagent extension tool, for the plan-mode tool_call guard. */\nexport const PLAN_SUBAGENT_TOOL_NAME = \"subagent\";\n\n/** Max characters of plan markdown echoed into the post-compaction kickoff message. */\nexport const PLAN_EMBED_MAX_CHARS = 24_000;\n\nexport const MENU_EXECUTE = \"Start executing\";\nexport const MENU_COMPACT_EXECUTE = \"Compact context, then execute\";\nexport const MENU_KEEP_PLANNING = \"Keep planning\";\n\n/**\n * Approval choices. The label is the decision, the description is the\n * trade-off, so the three options can be told apart without reading to the\n * end of a sentence. select() resolves to the label.\n */\nexport const EXIT_PLAN_MENU_OPTIONS: readonly SelectOption[] = [\n\t{ label: MENU_EXECUTE, description: \"keep full context\" },\n\t{ label: MENU_COMPACT_EXECUTE, description: \"best for long tasks\" },\n\t{ label: MENU_KEEP_PLANNING, description: \"refine before running\" },\n];\n\n/** Esc maps to \"keep planning\", so the dismiss hint must not read as \"discard\". */\nexport const EXIT_PLAN_CANCEL_HINT = \"keep planning\";\n\n/**\n * /plan panel (shown when the command runs while planning): exit is the first\n * option, saved plans follow. Esc keeps planning with no side effects.\n */\nexport const PLAN_PANEL_TITLE = \"Plan mode\";\nexport const PLAN_PANEL_EXIT = \"Exit plan mode\";\nexport const PLAN_PANEL_EXIT_DESCRIPTION = \"restore full tool access\";\nexport const PLAN_PANEL_CANCEL_HINT = \"keep planning\";\nexport const PLAN_PANEL_MAX_FILES = 20;\n\nexport const EXIT_PLAN_TOOL_DESCRIPTION =\n\t\"Submit the finished plan and ask the user to approve leaving plan mode. Present the complete plan as normal response text first, then call this tool with a short title and the same plan markdown; on approval the plan is saved to disk. The user chooses between executing with full context, compacting the context before executing, or continuing to plan. Only available while plan mode is active.\";\n\nexport const EXIT_PLAN_PROMPT_SNIPPET = \"Submit the finished plan for user approval and leave plan mode\";\n\nexport const EXIT_PLAN_PROMPT_GUIDELINES = [\n\t\"Call `exit_plan` only after presenting the complete plan as response text; make it the only tool call in that step and stop after it returns.\",\n\t\"`exit_plan` results are authoritative for plan-mode state: follow them even when the plan-mode system prompt block is still present later in the run.\",\n];\n\nconst PLAN_MODE_PROMPT = `[PLAN MODE]\nYou are in plan mode: a read-only phase for exploring the codebase and agreeing on a plan with the user before any changes are made.\n\nRestrictions:\n- edit and write are unavailable; do not attempt changes or workarounds.\n- bash is for read-only inspection only: git log/diff/blame/show/status, ls, wc, head, tail, cat, and similar. Never run anything that modifies state: no file creation or deletion, no redirect (>, >>) or heredoc writes, no temp files, no git commands that write (add, commit, checkout, restore, stash, clean), no installs, no network access.\n- subagent is limited to the read-only explorer profile: always pass agent: \"${PLAN_ALLOWED_SUBAGENT}\"; other profiles are blocked while planning.\n- Explore with read, grep, find, ls, read-only bash, and explorer subagents.\n\nWorking style:\n- Answer questions from the code, not from the user: explore before asking.\n- When product intent, scope, or risk tolerance is unclear, interview the user with the question tool. Focus on one decision per exchange (batch only tightly coupled decisions) and always include your recommendation and the trade-offs.\n- Skip the interview for small, clear tasks. Pick sensible defaults for low-risk details and state them in the plan.\n\nDelivering the plan:\n- When the plan is ready, present it in full as normal response text (goal, steps, verification criteria) so the user can read it, then call exit_plan with a short title and the same markdown as the plan parameter.\n- The exit_plan tool result is authoritative for mode state: this block can outlive plan mode within a run, so if the result says plan mode has ended, it has ended.`;\n\n/** Build the plan-mode system prompt block, listing plans already saved for this branch. */\nexport function buildPlanModePrompt(planFiles: string[]): string {\n\tif (!planFiles.length) return PLAN_MODE_PROMPT;\n\tconst listing = planFiles.map((path) => `- ${path}`).join(\"\\n\");\n\treturn `${PLAN_MODE_PROMPT}\n\nPlans already saved for this session (read them with the read tool):\n${listing}\nWhen revising a saved plan, read the latest one first, account for work already completed, and produce a revision that states what changed and why; set the revises parameter to the file name of the plan being revised.`;\n}\n"]}
|
|
@@ -3,9 +3,11 @@
|
|
|
3
3
|
* then a user-approved exit that saves the plan and optionally compacts.
|
|
4
4
|
*
|
|
5
5
|
* Shape:
|
|
6
|
-
* - Entry (/plan or --plan)
|
|
7
|
-
*
|
|
8
|
-
*
|
|
6
|
+
* - Entry (/plan or --plan) snapshots the active tool set and swaps to the
|
|
7
|
+
* exploration set (read/grep/find/ls/bash + exit_plan; edit/write removed,
|
|
8
|
+
* bash prompt-constrained to read-only, subagent guarded to the explorer
|
|
9
|
+
* profile); a tool_call guard covers requests already in flight before the
|
|
10
|
+
* tool-set change lands.
|
|
9
11
|
* - The plan text travels as an exit_plan parameter, so the model needs no
|
|
10
12
|
* write access to produce the plan file.
|
|
11
13
|
* - "Compact, then execute" keeps plan mode active until compaction completes
|
|
@@ -17,5 +19,12 @@
|
|
|
17
19
|
* pattern as todo): /reload, /tree, resume, and fork all restore.
|
|
18
20
|
*/
|
|
19
21
|
import type { ExtensionAPI } from "../../core/extensions/types.ts";
|
|
22
|
+
/**
|
|
23
|
+
* First subagent profile in the call that is not allowed in plan mode, or
|
|
24
|
+
* undefined when every profile is the read-only explorer. An omitted or null
|
|
25
|
+
* agent resolves to the default "general" profile, so it is disallowed too.
|
|
26
|
+
* Args arrive off the wire, so every field is read defensively.
|
|
27
|
+
*/
|
|
28
|
+
export declare function findDisallowedSubagentProfile(input: unknown): string | undefined;
|
|
20
29
|
export default function plan(pi: ExtensionAPI): void;
|
|
21
30
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extensions/plan/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,KAAK,EAEX,YAAY,EAGZ,MAAM,gCAAgC,CAAC;AAgDxC,MAAM,CAAC,OAAO,UAAU,IAAI,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CAySnD","sourcesContent":["/**\n * plan — Claude-Code-style plan mode: read-only exploration and interview,\n * then a user-approved exit that saves the plan and optionally compacts.\n *\n * Shape:\n * - Entry (/plan or --plan) removes write-capable tools (edit/write/bash/\n * subagent) and activates exit_plan; a tool_call guard covers requests\n * already in flight before the tool-set change lands.\n * - The plan text travels as an exit_plan parameter, so the model needs no\n * write access to produce the plan file.\n * - \"Compact, then execute\" keeps plan mode active until compaction completes\n * (tools are restored in onComplete) and terminates the run via the tool\n * result, so there is no window where the model holds full context plus\n * write tools. The kickoff message embeds the plan itself — continuation\n * never depends on the compaction summary preserving a path.\n * - State is conversation-backed via custom entries and branch replay (same\n * pattern as todo): /reload, /tree, resume, and fork all restore.\n */\nimport type {\n\tAgentToolResult,\n\tExtensionAPI,\n\tExtensionContext,\n\tToolExecutionMode,\n} from \"../../core/extensions/types.ts\";\nimport {\n\tbuildPlanModePrompt,\n\tEXIT_PLAN_PROMPT_GUIDELINES,\n\tEXIT_PLAN_PROMPT_SNIPPET,\n\tEXIT_PLAN_TOOL_DESCRIPTION,\n\tEXIT_PLAN_TOOL_LABEL,\n\tEXIT_PLAN_TOOL_NAME,\n\tMENU_COMPACT_EXECUTE,\n\tMENU_EXECUTE,\n\tMENU_KEEP_PLANNING,\n\tPLAN_BLOCKED_TOOLS,\n\tPLAN_COMMAND_NAME,\n\tPLAN_EMBED_MAX_CHARS,\n\tPLAN_ENTRY_TYPE,\n\tPLAN_FLAG_NAME,\n\tPLAN_STATUS_KEY,\n} from \"./constants.ts\";\nimport { type ExitPlanDetails, type ExitPlanParams, ExitPlanParamsSchema } from \"./schema.ts\";\nimport {\n\tclonePlanState,\n\tdisposePlanSession,\n\tEMPTY_PLAN_STATE,\n\tgetPlanState,\n\treplacePlanState,\n\treplayPlanFromBranch,\n\tsetActivePlanSession,\n} from \"./state.ts\";\nimport { savePlanFile } from \"./storage.ts\";\n\ninterface PendingCompact {\n\ttitle: string;\n\tplan: string;\n\tplanPath: string;\n}\n\nfunction buildKickoffMessage(pending: PendingCompact): string {\n\tconst truncated = pending.plan.length > PLAN_EMBED_MAX_CHARS;\n\tconst body = truncated\n\t\t? `${pending.plan.slice(0, PLAN_EMBED_MAX_CHARS)}\\n\\n[Plan truncated — read the full plan at ${pending.planPath}]`\n\t\t: pending.plan;\n\treturn `Execute the approved plan \"${pending.title}\" (saved at ${pending.planPath}).\n\n${body}\n\nStart now. Track multi-step work with the todo tool, and report back instead of improvising if the plan turns out to need revision.`;\n}\n\nexport default function plan(pi: ExtensionAPI): void {\n\tlet menuOpen = false;\n\tlet pendingCompact: PendingCompact | undefined;\n\n\tpi.registerFlag(PLAN_FLAG_NAME, {\n\t\tdescription: \"Start in plan mode (read-only planning)\",\n\t\ttype: \"boolean\",\n\t\tdefault: false,\n\t});\n\n\t/** Remove blocked tools, activate exit_plan, and return what was actually removed. */\n\tfunction applyPlanTools(): string[] {\n\t\tconst active = pi.getActiveTools();\n\t\tconst removed = active.filter((name) => PLAN_BLOCKED_TOOLS.has(name));\n\t\tpi.setActiveTools([...new Set([...active.filter((name) => !PLAN_BLOCKED_TOOLS.has(name)), EXIT_PLAN_TOOL_NAME])]);\n\t\treturn removed;\n\t}\n\n\t/** Inverse of applyPlanTools: drop exit_plan, re-add exactly what was removed. */\n\tfunction restoreTools(removedTools: string[]): void {\n\t\tconst active = pi.getActiveTools().filter((name) => name !== EXIT_PLAN_TOOL_NAME);\n\t\tpi.setActiveTools([...new Set([...active, ...removedTools])]);\n\t}\n\n\tfunction persist(): void {\n\t\tpi.appendEntry(PLAN_ENTRY_TYPE, getPlanState());\n\t}\n\n\tfunction updateStatus(ctx: ExtensionContext): void {\n\t\tconst state = getPlanState();\n\t\tctx.ui.setStatus(PLAN_STATUS_KEY, state.planning ? ctx.ui.theme.fg(\"warning\", \"plan\") : undefined);\n\t}\n\n\tfunction enterPlanMode(ctx: ExtensionContext): void {\n\t\tconst state = getPlanState();\n\t\tif (state.planning) return;\n\t\tconst removedTools = applyPlanTools();\n\t\treplacePlanState({ planning: true, removedTools, awaitingCompact: false, planFiles: state.planFiles });\n\t\tpersist();\n\t\tupdateStatus(ctx);\n\t\tctx.ui.notify(\"Plan mode enabled: edit, write, bash, and subagent are disabled.\", \"info\");\n\t}\n\n\tfunction exitPlanMode(ctx: ExtensionContext, notifyText?: string): void {\n\t\tconst state = getPlanState();\n\t\trestoreTools(state.removedTools);\n\t\treplacePlanState({ ...state, planning: false, awaitingCompact: false, removedTools: [] });\n\t\tpersist();\n\t\tupdateStatus(ctx);\n\t\tif (notifyText) ctx.ui.notify(notifyText, \"info\");\n\t}\n\n\t/** Save the approved plan, index it in state, and name the session if unnamed. */\n\tfunction saveApprovedPlan(ctx: ExtensionContext, params: ExitPlanParams, title: string): string {\n\t\tconst planPath = savePlanFile({\n\t\t\tsessionId: ctx.sessionManager.getSessionId(),\n\t\t\ttitle,\n\t\t\tplan: params.plan,\n\t\t\tcwd: ctx.cwd,\n\t\t\trevises: params.revises,\n\t\t});\n\t\tconst state = getPlanState();\n\t\treplacePlanState({ ...state, planFiles: [...state.planFiles, planPath] });\n\t\tif (!pi.getSessionName()) pi.setSessionName(title);\n\t\treturn planPath;\n\t}\n\n\t/**\n\t * Rebuild state from the current branch and reconcile the live tool set.\n\t * An interrupted compact-and-execute approval (restart, resume, branch\n\t * switch) degrades to the keep-context exit so the approval is honored.\n\t */\n\tfunction syncFromBranch(ctx: ExtensionContext, options?: { applyFlag?: boolean }): void {\n\t\tsetActivePlanSession(ctx.sessionManager.getSessionId());\n\t\tconst before = getPlanState();\n\t\tconst replayed = replayPlanFromBranch(ctx);\n\t\tconst next = replayed ?? clonePlanState(EMPTY_PLAN_STATE);\n\t\tif (!replayed && options?.applyFlag && pi.getFlag(PLAN_FLAG_NAME) === true) {\n\t\t\tnext.planning = true;\n\t\t}\n\n\t\tlet interruptedCompact = false;\n\t\tif (next.awaitingCompact) {\n\t\t\tnext.planning = false;\n\t\t\tnext.awaitingCompact = false;\n\t\t\tinterruptedCompact = true;\n\t\t\tpendingCompact = undefined;\n\t\t}\n\n\t\tif (next.planning) {\n\t\t\t// The fresh removal set is authoritative for the eventual restore:\n\t\t\t// the live tool set may differ from what the entry recorded.\n\t\t\tnext.removedTools = applyPlanTools();\n\t\t} else {\n\t\t\tif (pi.getActiveTools().includes(EXIT_PLAN_TOOL_NAME)) {\n\t\t\t\trestoreTools(before.planning ? before.removedTools : next.removedTools);\n\t\t\t}\n\t\t\tnext.removedTools = [];\n\t\t}\n\n\t\treplacePlanState(next);\n\t\tif (interruptedCompact) {\n\t\t\tpersist();\n\t\t\tctx.ui.notify(\"Pending compaction was interrupted; plan mode exited with context kept.\", \"warning\");\n\t\t}\n\t\tupdateStatus(ctx);\n\t}\n\n\tpi.registerTool({\n\t\tname: EXIT_PLAN_TOOL_NAME,\n\t\tlabel: EXIT_PLAN_TOOL_LABEL,\n\t\tdescription: EXIT_PLAN_TOOL_DESCRIPTION,\n\t\tpromptSnippet: EXIT_PLAN_PROMPT_SNIPPET,\n\t\tpromptGuidelines: EXIT_PLAN_PROMPT_GUIDELINES,\n\t\tparameters: ExitPlanParamsSchema,\n\t\texecutionMode: \"sequential\" as ToolExecutionMode,\n\n\t\tasync execute(_toolCallId, params, signal, _onUpdate, ctx): Promise<AgentToolResult<ExitPlanDetails>> {\n\t\t\tsetActivePlanSession(ctx.sessionManager.getSessionId());\n\t\t\tconst state = getPlanState();\n\t\t\tconst title = params.title.trim() || \"plan\";\n\n\t\t\tif (!state.planning || state.awaitingCompact) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{ type: \"text\", text: \"Plan mode is not awaiting an exit; continue with your current instructions.\" },\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { decision: \"cancelled\", title },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (!ctx.hasUI) {\n\t\t\t\t// json/print: no way to ask, so honor the least surprising default —\n\t\t\t\t// exit with context kept. Documented as a headless-mode semantic.\n\t\t\t\tconst planPath = saveApprovedPlan(ctx, params, title);\n\t\t\t\texitPlanMode(ctx);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Plan saved to ${planPath}. No interactive UI, so plan mode exited with context kept (authoritative: write tools are restored). Begin executing the plan now.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { decision: \"execute\", title, planPath },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlet choice: string | undefined;\n\t\t\tmenuOpen = true;\n\t\t\ttry {\n\t\t\t\tchoice = await ctx.ui.select(\n\t\t\t\t\t`Approve plan \"${title}\"?`,\n\t\t\t\t\t[MENU_EXECUTE, MENU_COMPACT_EXECUTE, MENU_KEEP_PLANNING],\n\t\t\t\t\t{\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t} finally {\n\t\t\t\tmenuOpen = false;\n\t\t\t}\n\n\t\t\tif (signal?.aborted) {\n\t\t\t\t// Throwing lets Pi mark the result as an error, matching the todo convention.\n\t\t\t\tthrow new Error(\"Plan approval was interrupted; plan mode is still active.\");\n\t\t\t}\n\n\t\t\tif (choice === MENU_EXECUTE) {\n\t\t\t\tconst planPath = saveApprovedPlan(ctx, params, title);\n\t\t\t\texitPlanMode(ctx, \"Plan approved: executing with full context.\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Plan approved and saved to ${planPath}. Plan mode has ended and write tools are restored (authoritative — overrides the plan-mode system prompt block). Begin executing the plan now; track multi-step work with the todo tool.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { decision: \"execute\", title, planPath },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (choice === MENU_COMPACT_EXECUTE) {\n\t\t\t\tconst planPath = saveApprovedPlan(ctx, params, title);\n\t\t\t\t// Stay in plan mode (tools restricted) until compaction completes;\n\t\t\t\t// terminate ends the run so agent_settled can start the compaction.\n\t\t\t\treplacePlanState({ ...getPlanState(), awaitingCompact: true });\n\t\t\t\tpersist();\n\t\t\t\tpendingCompact = { title, plan: params.plan, planPath };\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Plan approved and saved to ${planPath}. The context will now be compacted; stop here — execution restarts automatically after compaction.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { decision: \"compactAndExecute\", title, planPath },\n\t\t\t\t\tterminate: true,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Explicit \"Keep planning\", Esc, or timeout: the only side-effect-free\n\t\t\t// choice, so any dismissal maps here.\n\t\t\tlet feedback: string | undefined;\n\t\t\tif (choice === MENU_KEEP_PLANNING) {\n\t\t\t\tfeedback =\n\t\t\t\t\tctx.mode === \"tui\"\n\t\t\t\t\t\t? await ctx.ui.editor(\"Feedback for the plan (optional):\", \"\")\n\t\t\t\t\t\t: await ctx.ui.input(\"Feedback for the plan (optional):\");\n\t\t\t}\n\t\t\tconst trimmedFeedback = feedback?.trim();\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: trimmedFeedback\n\t\t\t\t\t\t\t? `The user wants to keep planning. Feedback:\\n${trimmedFeedback}`\n\t\t\t\t\t\t\t: \"The user wants to keep planning. Ask what should change, or keep refining the open points.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails: { decision: \"keepPlanning\", title },\n\t\t\t};\n\t\t},\n\t});\n\n\tpi.registerCommand(PLAN_COMMAND_NAME, {\n\t\tdescription: \"Toggle plan mode (read-only planning with user-approved exit)\",\n\t\thandler: async (_args, ctx) => {\n\t\t\tsetActivePlanSession(ctx.sessionManager.getSessionId());\n\t\t\tconst state = getPlanState();\n\t\t\tif (menuOpen) {\n\t\t\t\tctx.ui.notify(\"The exit_plan approval menu is open — answer it first.\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (state.awaitingCompact) {\n\t\t\t\tctx.ui.notify(\"Waiting for compaction to finish before leaving plan mode.\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (state.planning) {\n\t\t\t\texitPlanMode(ctx, \"Plan mode disabled: full tool access restored.\");\n\t\t\t} else {\n\t\t\t\tenterPlanMode(ctx);\n\t\t\t}\n\t\t},\n\t});\n\n\t// Defense in depth: the active-tools change lands on the next LLM request,\n\t// so a request already in flight when plan mode toggled can still carry\n\t// blocked tool calls.\n\tpi.on(\"tool_call\", async (event, ctx) => {\n\t\tsetActivePlanSession(ctx.sessionManager.getSessionId());\n\t\tconst state = getPlanState();\n\t\tif (!state.planning || !PLAN_BLOCKED_TOOLS.has(event.toolName)) return;\n\t\treturn {\n\t\t\tblock: true,\n\t\t\treason: `Plan mode: ${event.toolName} is disabled. Keep exploring with read-only tools, or call ${EXIT_PLAN_TOOL_NAME} to submit the plan for approval.`,\n\t\t};\n\t});\n\n\tpi.on(\"before_agent_start\", async (event, ctx) => {\n\t\tsetActivePlanSession(ctx.sessionManager.getSessionId());\n\t\tconst state = getPlanState();\n\t\tif (!state.planning) return;\n\t\treturn { systemPrompt: `${event.systemPrompt}\\n\\n${buildPlanModePrompt(state.planFiles)}` };\n\t});\n\n\t// agent_settled fires once per fully settled run (agent_end can repeat on\n\t// retries and queued continuations), so the approved compaction starts here.\n\tpi.on(\"agent_settled\", async (_event, ctx) => {\n\t\tsetActivePlanSession(ctx.sessionManager.getSessionId());\n\t\tif (!getPlanState().awaitingCompact || !pendingCompact) return;\n\t\tconst pending = pendingCompact;\n\t\tpendingCompact = undefined;\n\t\tctx.compact({\n\t\t\tcustomInstructions: `The user approved an implementation plan saved at ${pending.planPath}. Preserve decisions, constraints, and rejected alternatives from the planning discussion that are not already written in the plan file.`,\n\t\t\tonComplete: () => {\n\t\t\t\texitPlanMode(ctx, \"Context compacted; executing the plan.\");\n\t\t\t\tpi.sendUserMessage(buildKickoffMessage(pending));\n\t\t\t},\n\t\t\tonError: (error) => {\n\t\t\t\t// Never leave the user stuck read-only: degrade to keep-context execution.\n\t\t\t\texitPlanMode(ctx, `Compaction failed (${error.message}); executing with full context instead.`);\n\t\t\t\tpi.sendUserMessage(buildKickoffMessage(pending));\n\t\t\t},\n\t\t});\n\t});\n\n\tpi.on(\"session_start\", async (_event, ctx) => {\n\t\tsyncFromBranch(ctx, { applyFlag: true });\n\t});\n\n\tpi.on(\"session_tree\", async (_event, ctx) => {\n\t\tsyncFromBranch(ctx);\n\t});\n\n\tpi.on(\"session_shutdown\", async (_event, ctx) => {\n\t\tpendingCompact = undefined;\n\t\tdisposePlanSession(ctx.sessionManager.getSessionId());\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/extensions/plan/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAIH,OAAO,KAAK,EAEX,YAAY,EAGZ,MAAM,gCAAgC,CAAC;AAkExC;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAYhF;AAED,MAAM,CAAC,OAAO,UAAU,IAAI,CAAC,EAAE,EAAE,YAAY,GAAG,IAAI,CA+YnD","sourcesContent":["/**\n * plan — Claude-Code-style plan mode: read-only exploration and interview,\n * then a user-approved exit that saves the plan and optionally compacts.\n *\n * Shape:\n * - Entry (/plan or --plan) snapshots the active tool set and swaps to the\n * exploration set (read/grep/find/ls/bash + exit_plan; edit/write removed,\n * bash prompt-constrained to read-only, subagent guarded to the explorer\n * profile); a tool_call guard covers requests already in flight before the\n * tool-set change lands.\n * - The plan text travels as an exit_plan parameter, so the model needs no\n * write access to produce the plan file.\n * - \"Compact, then execute\" keeps plan mode active until compaction completes\n * (tools are restored in onComplete) and terminates the run via the tool\n * result, so there is no window where the model holds full context plus\n * write tools. The kickoff message embeds the plan itself — continuation\n * never depends on the compaction summary preserving a path.\n * - State is conversation-backed via custom entries and branch replay (same\n * pattern as todo): /reload, /tree, resume, and fork all restore.\n */\n\nimport { basename } from \"node:path\";\nimport { Text } from \"@earendil-works/pi-tui\";\nimport type {\n\tAgentToolResult,\n\tExtensionAPI,\n\tExtensionContext,\n\tToolExecutionMode,\n} from \"../../core/extensions/types.ts\";\nimport {\n\tbuildPlanModePrompt,\n\tEXIT_PLAN_CANCEL_HINT,\n\tEXIT_PLAN_MENU_OPTIONS,\n\tEXIT_PLAN_PROMPT_GUIDELINES,\n\tEXIT_PLAN_PROMPT_SNIPPET,\n\tEXIT_PLAN_TOOL_DESCRIPTION,\n\tEXIT_PLAN_TOOL_LABEL,\n\tEXIT_PLAN_TOOL_NAME,\n\tMENU_COMPACT_EXECUTE,\n\tMENU_EXECUTE,\n\tMENU_KEEP_PLANNING,\n\tPLAN_ALLOWED_SUBAGENT,\n\tPLAN_BLOCKED_TOOLS,\n\tPLAN_COMMAND_NAME,\n\tPLAN_EMBED_MAX_CHARS,\n\tPLAN_ENTRY_TYPE,\n\tPLAN_EXPLORE_TOOLS,\n\tPLAN_FLAG_NAME,\n\tPLAN_KICKOFF_MESSAGE_TYPE,\n\tPLAN_PANEL_CANCEL_HINT,\n\tPLAN_PANEL_EXIT,\n\tPLAN_PANEL_EXIT_DESCRIPTION,\n\tPLAN_PANEL_MAX_FILES,\n\tPLAN_PANEL_TITLE,\n\tPLAN_STATUS_KEY,\n\tPLAN_SUBAGENT_TOOL_NAME,\n} from \"./constants.ts\";\nimport { type ExitPlanDetails, type ExitPlanParams, ExitPlanParamsSchema, type PlanKickoffDetails } from \"./schema.ts\";\nimport {\n\tclonePlanState,\n\tdisposePlanSession,\n\tEMPTY_PLAN_STATE,\n\tgetPlanState,\n\treplacePlanState,\n\treplayPlanFromBranch,\n\tsetActivePlanSession,\n} from \"./state.ts\";\nimport { listProjectPlanFiles, savePlanFile } from \"./storage.ts\";\nimport {\n\tformatApprovalSubtitle,\n\tformatExitPlanResult,\n\trenderExitPlanCall,\n\trenderPlanKickoffMessage,\n\tshortenPlanPath,\n} from \"./view.ts\";\n\ninterface PendingCompact {\n\ttitle: string;\n\tplan: string;\n\tplanPath: string;\n}\n\nfunction buildKickoffMessage(pending: PendingCompact): string {\n\tconst truncated = pending.plan.length > PLAN_EMBED_MAX_CHARS;\n\tconst body = truncated\n\t\t? `${pending.plan.slice(0, PLAN_EMBED_MAX_CHARS)}\\n\\n[Plan truncated — read the full plan at ${pending.planPath}]`\n\t\t: pending.plan;\n\treturn `Execute the approved plan \"${pending.title}\" (saved at ${pending.planPath}).\n\n${body}\n\nStart now. Track multi-step work with the todo tool, and report back instead of improvising if the plan turns out to need revision.`;\n}\n\n/**\n * First subagent profile in the call that is not allowed in plan mode, or\n * undefined when every profile is the read-only explorer. An omitted or null\n * agent resolves to the default \"general\" profile, so it is disallowed too.\n * Args arrive off the wire, so every field is read defensively.\n */\nexport function findDisallowedSubagentProfile(input: unknown): string | undefined {\n\tconst record = input && typeof input === \"object\" ? (input as Record<string, unknown>) : {};\n\tconst requested: unknown[] = Array.isArray(record.tasks)\n\t\t? record.tasks.map((task) =>\n\t\t\t\ttask && typeof task === \"object\" ? (task as Record<string, unknown>).agent : undefined,\n\t\t\t)\n\t\t: [record.agent];\n\tfor (const profile of requested) {\n\t\tconst name = typeof profile === \"string\" && profile.trim() ? profile.trim() : \"general\";\n\t\tif (name !== PLAN_ALLOWED_SUBAGENT) return name;\n\t}\n\treturn undefined;\n}\n\nexport default function plan(pi: ExtensionAPI): void {\n\tlet menuOpen = false;\n\tlet pendingCompact: PendingCompact | undefined;\n\n\tpi.registerMessageRenderer<PlanKickoffDetails>(PLAN_KICKOFF_MESSAGE_TYPE, renderPlanKickoffMessage);\n\n\t/**\n\t * Kickoff as a custom message, not a user message: the LLM still receives\n\t * the full kickoff text (custom messages convert to user-role context),\n\t * while the TUI renders the registered collapsed card instead of echoing\n\t * the whole plan again.\n\t */\n\tfunction sendKickoff(pending: PendingCompact): void {\n\t\tpi.sendMessage(\n\t\t\t{\n\t\t\t\tcustomType: PLAN_KICKOFF_MESSAGE_TYPE,\n\t\t\t\tcontent: buildKickoffMessage(pending),\n\t\t\t\tdisplay: true,\n\t\t\t\tdetails: { title: pending.title, planPath: pending.planPath },\n\t\t\t},\n\t\t\t{ triggerTurn: true },\n\t\t);\n\t}\n\n\tpi.registerFlag(PLAN_FLAG_NAME, {\n\t\tdescription: \"Start in plan mode (read-only planning)\",\n\t\ttype: \"boolean\",\n\t\tdefault: false,\n\t});\n\n\t/**\n\t * Swap to the exploration tool set and return the pre-entry snapshot.\n\t * Snapshot + delta rather than a fixed allowlist: edit/write are dropped,\n\t * the explore tools (grep/find/ls are registered but not active by\n\t * default) and exit_plan are added, and every other active tool — question,\n\t * todo, deepwiki, subagent, ... — stays active.\n\t */\n\tfunction applyPlanTools(): string[] {\n\t\tconst snapshot = pi.getActiveTools();\n\t\tpi.setActiveTools([\n\t\t\t...new Set([\n\t\t\t\t...snapshot.filter((name) => !PLAN_BLOCKED_TOOLS.has(name)),\n\t\t\t\t...PLAN_EXPLORE_TOOLS,\n\t\t\t\tEXIT_PLAN_TOOL_NAME,\n\t\t\t]),\n\t\t]);\n\t\treturn snapshot;\n\t}\n\n\t/**\n\t * Inverse of applyPlanTools: restore the snapshot verbatim. An empty\n\t * snapshot (legacy entries) only drops exit_plan — there is nothing\n\t * recorded to restore to.\n\t */\n\tfunction restoreTools(toolSnapshot: string[]): void {\n\t\tif (toolSnapshot.length > 0) {\n\t\t\tpi.setActiveTools([...new Set(toolSnapshot)].filter((name) => name !== EXIT_PLAN_TOOL_NAME));\n\t\t\treturn;\n\t\t}\n\t\tpi.setActiveTools(pi.getActiveTools().filter((name) => name !== EXIT_PLAN_TOOL_NAME));\n\t}\n\n\tfunction persist(): void {\n\t\tpi.appendEntry(PLAN_ENTRY_TYPE, getPlanState());\n\t}\n\n\tfunction updateStatus(ctx: ExtensionContext): void {\n\t\tconst state = getPlanState();\n\t\tctx.ui.setStatus(PLAN_STATUS_KEY, state.planning ? ctx.ui.theme.fg(\"accent\", \"Plan Mode\") : undefined);\n\t}\n\n\tfunction enterPlanMode(ctx: ExtensionContext): void {\n\t\tconst state = getPlanState();\n\t\tif (state.planning) return;\n\t\tconst toolSnapshot = applyPlanTools();\n\t\treplacePlanState({ planning: true, toolSnapshot, awaitingCompact: false, planFiles: state.planFiles });\n\t\tpersist();\n\t\tupdateStatus(ctx);\n\t\tctx.ui.notify(\n\t\t\t\"Plan mode: read-only exploration — edit/write disabled, bash constrained to read-only, subagent limited to explorer.\",\n\t\t\t\"info\",\n\t\t);\n\t}\n\n\tfunction exitPlanMode(ctx: ExtensionContext, notifyText?: string): void {\n\t\tconst state = getPlanState();\n\t\trestoreTools(state.toolSnapshot);\n\t\treplacePlanState({ ...state, planning: false, awaitingCompact: false, toolSnapshot: [] });\n\t\tpersist();\n\t\tupdateStatus(ctx);\n\t\tif (notifyText) ctx.ui.notify(notifyText, \"info\");\n\t}\n\n\t/** Save the approved plan, index it in state, and name the session if unnamed. */\n\tfunction saveApprovedPlan(ctx: ExtensionContext, params: ExitPlanParams, title: string): string {\n\t\tconst planPath = savePlanFile({\n\t\t\tsessionId: ctx.sessionManager.getSessionId(),\n\t\t\ttitle,\n\t\t\tplan: params.plan,\n\t\t\tcwd: ctx.cwd,\n\t\t\trevises: params.revises,\n\t\t});\n\t\tconst state = getPlanState();\n\t\treplacePlanState({ ...state, planFiles: [...state.planFiles, planPath] });\n\t\tif (!pi.getSessionName()) pi.setSessionName(title);\n\t\treturn planPath;\n\t}\n\n\t/**\n\t * Rebuild state from the current branch and reconcile the live tool set.\n\t * An interrupted compact-and-execute approval (restart, resume, branch\n\t * switch) degrades to the keep-context exit so the approval is honored.\n\t */\n\tfunction syncFromBranch(ctx: ExtensionContext, options?: { applyFlag?: boolean }): void {\n\t\tsetActivePlanSession(ctx.sessionManager.getSessionId());\n\t\tconst before = getPlanState();\n\t\tconst replayed = replayPlanFromBranch(ctx);\n\t\tconst next = replayed ?? clonePlanState(EMPTY_PLAN_STATE);\n\t\tif (!replayed && options?.applyFlag && pi.getFlag(PLAN_FLAG_NAME) === true) {\n\t\t\tnext.planning = true;\n\t\t}\n\n\t\tlet interruptedCompact = false;\n\t\tif (next.awaitingCompact) {\n\t\t\tnext.planning = false;\n\t\t\tnext.awaitingCompact = false;\n\t\t\tinterruptedCompact = true;\n\t\t\tpendingCompact = undefined;\n\t\t}\n\n\t\tif (next.planning) {\n\t\t\t// Re-applying is idempotent, but the returned live snapshot is only\n\t\t\t// authoritative when the live set was NOT already restricted: on a\n\t\t\t// branch switch while planning, re-snapshotting would capture the\n\t\t\t// plan-mode set, so the in-memory snapshot wins there.\n\t\t\tconst liveSnapshot = applyPlanTools();\n\t\t\tnext.toolSnapshot =\n\t\t\t\tbefore.planning && before.toolSnapshot.length > 0 ? [...before.toolSnapshot] : liveSnapshot;\n\t\t} else {\n\t\t\tif (pi.getActiveTools().includes(EXIT_PLAN_TOOL_NAME)) {\n\t\t\t\trestoreTools(before.planning ? before.toolSnapshot : next.toolSnapshot);\n\t\t\t}\n\t\t\tnext.toolSnapshot = [];\n\t\t}\n\n\t\treplacePlanState(next);\n\t\tif (interruptedCompact) {\n\t\t\tpersist();\n\t\t\tctx.ui.notify(\"Pending compaction was interrupted; plan mode exited with context kept.\", \"warning\");\n\t\t}\n\t\tupdateStatus(ctx);\n\t}\n\n\tpi.registerTool<typeof ExitPlanParamsSchema, ExitPlanDetails>({\n\t\tname: EXIT_PLAN_TOOL_NAME,\n\t\tlabel: EXIT_PLAN_TOOL_LABEL,\n\t\tdescription: EXIT_PLAN_TOOL_DESCRIPTION,\n\t\tpromptSnippet: EXIT_PLAN_PROMPT_SNIPPET,\n\t\tpromptGuidelines: EXIT_PLAN_PROMPT_GUIDELINES,\n\t\tparameters: ExitPlanParamsSchema,\n\t\texecutionMode: \"sequential\" as ToolExecutionMode,\n\t\trendersOwnProgress: true,\n\n\t\tasync execute(_toolCallId, params, signal, _onUpdate, ctx): Promise<AgentToolResult<ExitPlanDetails>> {\n\t\t\tsetActivePlanSession(ctx.sessionManager.getSessionId());\n\t\t\tconst state = getPlanState();\n\t\t\tconst title = params.title.trim() || \"plan\";\n\n\t\t\tif (!state.planning || state.awaitingCompact) {\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{ type: \"text\", text: \"Plan mode is not awaiting an exit; continue with your current instructions.\" },\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { decision: \"cancelled\", title },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (!ctx.hasUI) {\n\t\t\t\t// json/print: no way to ask, so honor the least surprising default —\n\t\t\t\t// exit with context kept. Documented as a headless-mode semantic.\n\t\t\t\tconst planPath = saveApprovedPlan(ctx, params, title);\n\t\t\t\texitPlanMode(ctx);\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Plan saved to ${planPath}. No interactive UI, so plan mode exited with context kept (authoritative: write tools are restored). Begin executing the plan now.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { decision: \"execute\", title, planPath },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tlet choice: string | undefined;\n\t\t\tmenuOpen = true;\n\t\t\ttry {\n\t\t\t\tchoice = await ctx.ui.select(`Approve plan \"${title}\"?`, EXIT_PLAN_MENU_OPTIONS, {\n\t\t\t\t\tsignal,\n\t\t\t\t\tsubtitle: formatApprovalSubtitle(ctx),\n\t\t\t\t\tcancelHint: EXIT_PLAN_CANCEL_HINT,\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tmenuOpen = false;\n\t\t\t}\n\n\t\t\tif (signal?.aborted) {\n\t\t\t\t// Throwing lets Pi mark the result as an error, matching the todo convention.\n\t\t\t\tthrow new Error(\"Plan approval was interrupted; plan mode is still active.\");\n\t\t\t}\n\n\t\t\tif (choice === MENU_EXECUTE) {\n\t\t\t\tconst planPath = saveApprovedPlan(ctx, params, title);\n\t\t\t\texitPlanMode(ctx, \"Plan approved: executing with full context.\");\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Plan approved and saved to ${planPath}. Plan mode has ended and write tools are restored (authoritative — overrides the plan-mode system prompt block). Begin executing the plan now; track multi-step work with the todo tool.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { decision: \"execute\", title, planPath },\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (choice === MENU_COMPACT_EXECUTE) {\n\t\t\t\tconst planPath = saveApprovedPlan(ctx, params, title);\n\t\t\t\t// Stay in plan mode (tools restricted) until compaction completes;\n\t\t\t\t// terminate ends the run so agent_settled can start the compaction.\n\t\t\t\treplacePlanState({ ...getPlanState(), awaitingCompact: true });\n\t\t\t\tpersist();\n\t\t\t\tpendingCompact = { title, plan: params.plan, planPath };\n\t\t\t\treturn {\n\t\t\t\t\tcontent: [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: `Plan approved and saved to ${planPath}. The context will now be compacted; stop here — execution restarts automatically after compaction.`,\n\t\t\t\t\t\t},\n\t\t\t\t\t],\n\t\t\t\t\tdetails: { decision: \"compactAndExecute\", title, planPath },\n\t\t\t\t\tterminate: true,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\t// Explicit \"Keep planning\", Esc, or timeout: the only side-effect-free\n\t\t\t// choice, so any dismissal maps here.\n\t\t\tlet feedback: string | undefined;\n\t\t\tif (choice === MENU_KEEP_PLANNING) {\n\t\t\t\tfeedback =\n\t\t\t\t\tctx.mode === \"tui\"\n\t\t\t\t\t\t? await ctx.ui.editor(\"Feedback for the plan (optional):\", \"\")\n\t\t\t\t\t\t: await ctx.ui.input(\"Feedback for the plan (optional):\");\n\t\t\t}\n\t\t\tconst trimmedFeedback = feedback?.trim();\n\t\t\treturn {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: trimmedFeedback\n\t\t\t\t\t\t\t? `The user wants to keep planning. Feedback:\\n${trimmedFeedback}`\n\t\t\t\t\t\t\t: \"The user wants to keep planning. Ask what should change, or keep refining the open points.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails: { decision: \"keepPlanning\", title },\n\t\t\t};\n\t\t},\n\n\t\trenderCall(args, theme, context) {\n\t\t\treturn renderExitPlanCall(args, theme, context.expanded);\n\t\t},\n\n\t\trenderResult(result, _options, theme) {\n\t\t\treturn new Text(formatExitPlanResult(result, theme), 0, 0);\n\t\t},\n\t});\n\n\t/**\n\t * Plans offered in the /plan panel: this branch's plans first (newest\n\t * first), then the rest of the project's, deduped, bounded. Legacy plans\n\t * from other sessions' directories only appear via planFiles entries.\n\t */\n\tfunction collectPanelPlanFiles(ctx: ExtensionContext): string[] {\n\t\tconst state = getPlanState();\n\t\tconst seen = new Set<string>();\n\t\tconst files: string[] = [];\n\t\tfor (const path of [...[...state.planFiles].reverse(), ...listProjectPlanFiles(ctx.cwd)]) {\n\t\t\tconst key = path.replace(/\\\\/g, \"/\").toLowerCase();\n\t\t\tif (seen.has(key)) continue;\n\t\t\tseen.add(key);\n\t\t\tfiles.push(path);\n\t\t\tif (files.length >= PLAN_PANEL_MAX_FILES) break;\n\t\t}\n\t\treturn files;\n\t}\n\n\t/** Panel behind /plan while planning: pick a plan file or exit the mode. */\n\tasync function openPlanPanel(ctx: ExtensionContext): Promise<void> {\n\t\tconst files = collectPanelPlanFiles(ctx);\n\t\tconst fileOptions = files.map((path) => ({ label: basename(path), description: shortenPlanPath(path) }));\n\t\tconst options = [{ label: PLAN_PANEL_EXIT, description: PLAN_PANEL_EXIT_DESCRIPTION }, ...fileOptions];\n\t\tconst choice = await ctx.ui.select(PLAN_PANEL_TITLE, options, { cancelHint: PLAN_PANEL_CANCEL_HINT });\n\t\tif (choice === PLAN_PANEL_EXIT) {\n\t\t\texitPlanMode(ctx, \"Plan mode disabled: full tool access restored.\");\n\t\t\treturn;\n\t\t}\n\t\tif (!choice) return; // Esc: keep planning, no side effects.\n\t\tconst selected = files.find((path) => basename(path) === choice);\n\t\tif (selected) ctx.ui.pasteToEditor(selected);\n\t}\n\n\tpi.registerCommand(PLAN_COMMAND_NAME, {\n\t\tdescription: \"Enter plan mode; while planning, open the plan panel (pick a plan file or exit)\",\n\t\thandler: async (_args, ctx) => {\n\t\t\tsetActivePlanSession(ctx.sessionManager.getSessionId());\n\t\t\tconst state = getPlanState();\n\t\t\tif (menuOpen) {\n\t\t\t\tctx.ui.notify(\"The exit_plan approval menu is open — answer it first.\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (state.awaitingCompact) {\n\t\t\t\tctx.ui.notify(\"Waiting for compaction to finish before leaving plan mode.\", \"warning\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!state.planning) {\n\t\t\t\tenterPlanMode(ctx);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (ctx.mode !== \"tui\") {\n\t\t\t\t// No panel affordances outside the TUI: keep the toggle semantic.\n\t\t\t\texitPlanMode(ctx, \"Plan mode disabled: full tool access restored.\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait openPlanPanel(ctx);\n\t\t},\n\t});\n\n\t// Defense in depth: the active-tools change lands on the next LLM request,\n\t// so a request already in flight when plan mode toggled can still carry\n\t// blocked tool calls.\n\tpi.on(\"tool_call\", async (event, ctx) => {\n\t\tsetActivePlanSession(ctx.sessionManager.getSessionId());\n\t\tconst state = getPlanState();\n\t\tif (!state.planning) return;\n\t\tif (PLAN_BLOCKED_TOOLS.has(event.toolName)) {\n\t\t\treturn {\n\t\t\t\tblock: true,\n\t\t\t\treason: `Plan mode: ${event.toolName} is disabled. Keep exploring with read-only tools, or call ${EXIT_PLAN_TOOL_NAME} to submit the plan for approval.`,\n\t\t\t};\n\t\t}\n\t\tif (event.toolName === PLAN_SUBAGENT_TOOL_NAME) {\n\t\t\tconst disallowed = findDisallowedSubagentProfile(event.input);\n\t\t\tif (disallowed !== undefined) {\n\t\t\t\treturn {\n\t\t\t\t\tblock: true,\n\t\t\t\t\treason: `Plan mode: subagent profile \"${disallowed}\" is blocked while planning. Delegate read-only exploration with agent: \"${PLAN_ALLOWED_SUBAGENT}\" (set it on every task in tasks mode).`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t});\n\n\tpi.on(\"before_agent_start\", async (event, ctx) => {\n\t\tsetActivePlanSession(ctx.sessionManager.getSessionId());\n\t\tconst state = getPlanState();\n\t\tif (!state.planning) return;\n\t\treturn { systemPrompt: `${event.systemPrompt}\\n\\n${buildPlanModePrompt(state.planFiles)}` };\n\t});\n\n\t// agent_settled fires once per fully settled run (agent_end can repeat on\n\t// retries and queued continuations), so the approved compaction starts here.\n\tpi.on(\"agent_settled\", async (_event, ctx) => {\n\t\tsetActivePlanSession(ctx.sessionManager.getSessionId());\n\t\tif (!getPlanState().awaitingCompact || !pendingCompact) return;\n\t\tconst pending = pendingCompact;\n\t\tpendingCompact = undefined;\n\t\tctx.compact({\n\t\t\tcustomInstructions: `The user approved an implementation plan saved at ${pending.planPath}. Preserve decisions, constraints, and rejected alternatives from the planning discussion that are not already written in the plan file.`,\n\t\t\tonComplete: () => {\n\t\t\t\texitPlanMode(ctx, \"Context compacted; executing the plan.\");\n\t\t\t\tsendKickoff(pending);\n\t\t\t},\n\t\t\tonError: (error) => {\n\t\t\t\t// Never leave the user stuck read-only: degrade to keep-context execution.\n\t\t\t\texitPlanMode(ctx, `Compaction failed (${error.message}); executing with full context instead.`);\n\t\t\t\tsendKickoff(pending);\n\t\t\t},\n\t\t});\n\t});\n\n\tpi.on(\"session_start\", async (_event, ctx) => {\n\t\tsyncFromBranch(ctx, { applyFlag: true });\n\t});\n\n\tpi.on(\"session_tree\", async (_event, ctx) => {\n\t\tsyncFromBranch(ctx);\n\t});\n\n\tpi.on(\"session_shutdown\", async (_event, ctx) => {\n\t\tpendingCompact = undefined;\n\t\tdisposePlanSession(ctx.sessionManager.getSessionId());\n\t});\n}\n"]}
|