@openeryc/pi-coding-agent 0.75.58 → 0.75.59

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/core/agent-session.d.ts +11 -1
  3. package/dist/core/agent-session.d.ts.map +1 -1
  4. package/dist/core/agent-session.js +32 -0
  5. package/dist/core/agent-session.js.map +1 -1
  6. package/dist/core/session-manager.d.ts +4 -0
  7. package/dist/core/session-manager.d.ts.map +1 -1
  8. package/dist/core/session-manager.js +19 -2
  9. package/dist/core/session-manager.js.map +1 -1
  10. package/dist/core/system-prompt.d.ts +2 -0
  11. package/dist/core/system-prompt.d.ts.map +1 -1
  12. package/dist/core/system-prompt.js +8 -1
  13. package/dist/core/system-prompt.js.map +1 -1
  14. package/dist/modes/interactive/goal-evaluator.d.ts +23 -0
  15. package/dist/modes/interactive/goal-evaluator.d.ts.map +1 -0
  16. package/dist/modes/interactive/goal-evaluator.js +68 -0
  17. package/dist/modes/interactive/goal-evaluator.js.map +1 -0
  18. package/dist/modes/interactive/interactive-mode.d.ts +6 -6
  19. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  20. package/dist/modes/interactive/interactive-mode.js +133 -79
  21. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  22. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  23. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  24. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  25. package/examples/extensions/sandbox/package-lock.json +2 -2
  26. package/examples/extensions/sandbox/package.json +1 -1
  27. package/examples/extensions/with-deps/package-lock.json +2 -2
  28. package/examples/extensions/with-deps/package.json +1 -1
  29. package/npm-shrinkwrap.json +12 -12
  30. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAA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AS,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;QAChE,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;YACjC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YACvB,KAAK,CAAC,IAAI,CAAC,aAAa,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YACvD,KAAK,CAAC,IAAI,CAAC,oBAAoB,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC;YAC5E,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACzB,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACzB,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACxB","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n\t/** MCP tools grouped by server name. */\n\tmcpTools?: Array<{ serverName: string; tools: Array<{ name: string; description: string }> }>;\n\t/** Project memory content (MEMORY.md). */\n\tmemory?: string;\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t\tmcpTools: providedMcpTools,\n\t\tmemory,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n<project_context>\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `<project_instructions path=\"${filePath}\">\\n${content}\\n</project_instructions>\\n\\n`;\n\t\t\t}\n\t\t\tprompt += \"</project_context>\\n\";\n\t\t}\n\n\t\t// Append project memory (AI-learned across sessions)\n\t\tif (memory) {\n\t\t\tprompt += `\\n<project_memory>\\n${memory}\\n</project_memory>\\n`;\n\t\t}\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst customPromptHasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (customPromptHasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append MCP tools section — explicitly note these are callable function tools\n\t\tif (providedMcpTools && providedMcpTools.length > 0) {\n\t\t\tprompt +=\n\t\t\t\t\"\\n\\nThe MCP (Model Context Protocol) tools below are regular callable tools — use them just like any other tool listed above. Each accepts an optional `_timeoutMs` parameter to override the timeout for that specific call.\";\n\t\t\tprompt += formatMcpToolsForPrompt(providedMcpTools);\n\t\t}\n\n\t\t// Add date and working directory last\n\t\tprompt += `\\nCurrent date: ${date}`;\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst tools = selectedTools || [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Determine if any visible tool is an MCP tool\n\tconst hasMcpTools = visibleTools.some((name) => name.startsWith(\"mcp_\"));\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRead = tools.includes(\"read\");\n\n\t// File exploration guidelines\n\tif (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t} else if (hasBash && (hasGrep || hasFind || hasLs)) {\n\t\taddGuideline(\"Prefer grep/find/ls tools over bash for file exploration (faster, respects .gitignore)\");\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\taddGuideline(\n\t\t\"Save important project learnings (build commands, debugging insights, architecture notes, code style preferences) to .pi/memory/MEMORY.md so they persist across sessions. Read MEMORY.md first when starting new work.\",\n\t);\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tconst additionalToolsNote = hasMcpTools\n\t\t? `\nMCP (Model Context Protocol) tools are regular callable tools with the mcp_ prefix — use them just like any other tool. Each accepts an optional _timeoutMs parameter (in milliseconds) to override the timeout for that specific call (e.g. _timeoutMs: 300000 for 5 minutes).`\n\t\t: \"\\nIn addition to the tools above, you may have access to other custom tools depending on the project.\";\n\n\tlet prompt = `You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}${additionalToolsNote}\n\nGuidelines:\n${guidelines}\n\nPi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md)\n- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n<project_context>\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `<project_instructions path=\"${filePath}\">\\n${content}\\n</project_instructions>\\n\\n`;\n\t\t}\n\t\tprompt += \"</project_context>\\n\";\n\t}\n\n\t// Append project memory (AI-learned across sessions)\n\tif (memory) {\n\t\tprompt += `\\n<project_memory>\\n${memory}\\n</project_memory>\\n`;\n\t}\n\n\t// Append skills section (only if read tool is available)\n\tif (hasRead && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Append MCP tools section\n\tif (providedMcpTools && providedMcpTools.length > 0) {\n\t\tprompt +=\n\t\t\t\"\\n\\nMCP tool details (each tool accepts an optional `_timeoutMs` param to override timeout per-call, e.g. `_timeoutMs: 300000` for 5 min):\";\n\t\tprompt += formatMcpToolsForPrompt(providedMcpTools);\n\t}\n\n\t// Add date and working directory last\n\tprompt += `\\nCurrent date: ${date}`;\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\treturn prompt;\n}\n\nfunction xmlEscape(str: string): string {\n\treturn str\n\t\t.replace(/&/g, \"&amp;\")\n\t\t.replace(/</g, \"&lt;\")\n\t\t.replace(/>/g, \"&gt;\")\n\t\t.replace(/\"/g, \"&quot;\")\n\t\t.replace(/'/g, \"&apos;\");\n}\n\nfunction formatMcpToolsForPrompt(\n\tservers: Array<{ serverName: string; tools: Array<{ name: string; description: string }> }>,\n): string {\n\tconst lines: string[] = [];\n\n\tfor (const server of servers) {\n\t\tlines.push(`\\n<server name=\"${xmlEscape(server.serverName)}\">`);\n\t\tfor (const tool of server.tools) {\n\t\t\tlines.push(\" <tool>\");\n\t\t\tlines.push(` <name>${xmlEscape(tool.name)}</name>`);\n\t\t\tlines.push(` <description>${xmlEscape(tool.description)}</description>`);\n\t\t\tlines.push(\" </tool>\");\n\t\t}\n\t\tlines.push(\"</server>\");\n\t}\n\n\treturn lines.join(\"\\n\");\n}\n"]}
1
+ {"version":3,"file":"system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AC,IAAI,EAAE,QAAQ,CAAC;SACvB,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;AAAA,CAC1B;AAED,SAAS,uBAAuB,CAC/B,OAA2F,EAClF;IACT,MAAM,KAAK,GAAa,EAAE,CAAC;IAE3B,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC9B,KAAK,CAAC,IAAI,CAAC,mBAAmB,SAAS,CAAC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;QAChE,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;YACjC,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;YACvB,KAAK,CAAC,IAAI,CAAC,aAAa,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;YACvD,KAAK,CAAC,IAAI,CAAC,oBAAoB,SAAS,CAAC,IAAI,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC;YAC5E,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACzB,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACzB,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACxB","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n\t/** MCP tools grouped by server name. */\n\tmcpTools?: Array<{ serverName: string; tools: Array<{ name: string; description: string }> }>;\n\t/** Project memory content (MEMORY.md). */\n\tmemory?: string;\n\t/** Session goal, if set via /goal. Injected into system prompt so model is always aware of it. */\n\tsessionGoal?: string;\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t\tmcpTools: providedMcpTools,\n\t\tmemory,\n\t\tsessionGoal,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\t// Append project context files\n\t\tif (contextFiles.length > 0) {\n\t\t\tprompt += \"\\n\\n<project_context>\\n\\n\";\n\t\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\t\tprompt += `<project_instructions path=\"${filePath}\">\\n${content}\\n</project_instructions>\\n\\n`;\n\t\t\t}\n\t\t\tprompt += \"</project_context>\\n\";\n\t\t}\n\n\t\t// Append project memory (AI-learned across sessions)\n\t\tif (memory) {\n\t\t\tprompt += `\\n<project_memory>\\n${memory}\\n</project_memory>\\n`;\n\t\t}\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst customPromptHasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (customPromptHasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append MCP tools section — explicitly note these are callable function tools\n\t\tif (providedMcpTools && providedMcpTools.length > 0) {\n\t\t\tprompt +=\n\t\t\t\t\"\\n\\nThe MCP (Model Context Protocol) tools below are regular callable tools — use them just like any other tool listed above. Each accepts an optional `_timeoutMs` parameter to override the timeout for that specific call.\";\n\t\t\tprompt += formatMcpToolsForPrompt(providedMcpTools);\n\t\t}\n\n\t\t// Add date and working directory last\n\t\tprompt += `\\nCurrent date: ${date}`;\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst tools = selectedTools || [\"read\", \"bash\", \"edit\", \"write\"];\n\tconst visibleTools = tools.filter((name) => !!toolSnippets?.[name]);\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Determine if any visible tool is an MCP tool\n\tconst hasMcpTools = visibleTools.some((name) => name.startsWith(\"mcp_\"));\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasGrep = tools.includes(\"grep\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst hasRead = tools.includes(\"read\");\n\n\t// File exploration guidelines\n\tif (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t} else if (hasBash && (hasGrep || hasFind || hasLs)) {\n\t\taddGuideline(\"Prefer grep/find/ls tools over bash for file exploration (faster, respects .gitignore)\");\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\taddGuideline(\n\t\t\"Save important project learnings (build commands, debugging insights, architecture notes, code style preferences) to .pi/memory/MEMORY.md so they persist across sessions. Read MEMORY.md first when starting new work.\",\n\t);\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tconst additionalToolsNote = hasMcpTools\n\t\t? `\nMCP (Model Context Protocol) tools are regular callable tools with the mcp_ prefix — use them just like any other tool. Each accepts an optional _timeoutMs parameter (in milliseconds) to override the timeout for that specific call (e.g. _timeoutMs: 300000 for 5 minutes).`\n\t\t: \"\\nIn addition to the tools above, you may have access to other custom tools depending on the project.\";\n\n\tlet prompt = `You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}${additionalToolsNote}\n\nGuidelines:\n${guidelines}\n\nPi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md)\n- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\t// Append project context files\n\tif (contextFiles.length > 0) {\n\t\tprompt += \"\\n\\n<project_context>\\n\\n\";\n\t\tprompt += \"Project-specific instructions and guidelines:\\n\\n\";\n\t\tfor (const { path: filePath, content } of contextFiles) {\n\t\t\tprompt += `<project_instructions path=\"${filePath}\">\\n${content}\\n</project_instructions>\\n\\n`;\n\t\t}\n\t\tprompt += \"</project_context>\\n\";\n\t}\n\n\t// Append project memory (AI-learned across sessions)\n\tif (memory) {\n\t\tprompt += `\\n<project_memory>\\n${memory}\\n</project_memory>\\n`;\n\t}\n\n\t// Inject session goal prominently when set (like Claude Code's goal mechanism)\n\t// The goal appears before project context and skills so it gets high attention.\n\t// Tells the model to keep working toward it autonomously, not to stop easily.\n\tif (sessionGoal) {\n\t\tprompt += `\\n<session_goal>\\n${sessionGoal}\\n</session_goal>\\n`;\n\t\tprompt += `\\nYou have an active session goal set via /goal. This goal is your primary objective across turns. Continue working toward it autonomously. Do not treat the goal as optional or stop making progress unless every aspect is demonstrably complete. If you encounter obstacles, work through them — do not abandon the goal.\\n`;\n\t}\n\n\t// Append skills section (only if read tool is available)\n\tif (hasRead && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Append MCP tools section\n\tif (providedMcpTools && providedMcpTools.length > 0) {\n\t\tprompt +=\n\t\t\t\"\\n\\nMCP tool details (each tool accepts an optional `_timeoutMs` param to override timeout per-call, e.g. `_timeoutMs: 300000` for 5 min):\";\n\t\tprompt += formatMcpToolsForPrompt(providedMcpTools);\n\t}\n\n\t// Add date and working directory last\n\tprompt += `\\nCurrent date: ${date}`;\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\treturn prompt;\n}\n\nfunction xmlEscape(str: string): string {\n\treturn str\n\t\t.replace(/&/g, \"&amp;\")\n\t\t.replace(/</g, \"&lt;\")\n\t\t.replace(/>/g, \"&gt;\")\n\t\t.replace(/\"/g, \"&quot;\")\n\t\t.replace(/'/g, \"&apos;\");\n}\n\nfunction formatMcpToolsForPrompt(\n\tservers: Array<{ serverName: string; tools: Array<{ name: string; description: string }> }>,\n): string {\n\tconst lines: string[] = [];\n\n\tfor (const server of servers) {\n\t\tlines.push(`\\n<server name=\"${xmlEscape(server.serverName)}\">`);\n\t\tfor (const tool of server.tools) {\n\t\t\tlines.push(\" <tool>\");\n\t\t\tlines.push(` <name>${xmlEscape(tool.name)}</name>`);\n\t\t\tlines.push(` <description>${xmlEscape(tool.description)}</description>`);\n\t\t\tlines.push(\" </tool>\");\n\t\t}\n\t\tlines.push(\"</server>\");\n\t}\n\n\treturn lines.join(\"\\n\");\n}\n"]}
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Goal evaluator — a lightweight LLM call that checks whether a session goal
3
+ * condition is met based on the conversation so far.
4
+ *
5
+ * Inspired by Claude Code's /goal evaluator: it reads what the assistant has
6
+ * produced (test output, git status, etc.) and judges the condition.
7
+ *
8
+ * When the condition is NOT met, it also provides a nextDirection to guide
9
+ * the assistant's next turn.
10
+ */
11
+ import type { Model, SimpleStreamOptions } from "@openeryc/pi-ai";
12
+ export interface GoalEvaluation {
13
+ met: boolean;
14
+ reason: string;
15
+ /** Concrete next-step instruction when the goal is not yet met. */
16
+ nextDirection?: string;
17
+ }
18
+ /**
19
+ * Evaluate whether a goal condition is met based on recent conversation.
20
+ * When not met, returns a nextDirection to guide the next turn.
21
+ */
22
+ export declare function evaluateGoalCondition(condition: string, lastAssistantText: string | undefined, model: Model<any>, options: SimpleStreamOptions): Promise<GoalEvaluation>;
23
+ //# sourceMappingURL=goal-evaluator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"goal-evaluator.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/goal-evaluator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,mBAAmB,EAAE,MAAM,iBAAiB,CAAC;AAmBlE,MAAM,WAAW,cAAc;IAC9B,GAAG,EAAE,OAAO,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,mEAAmE;IACnE,aAAa,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;GAGG;AACH,wBAAsB,qBAAqB,CAC1C,SAAS,EAAE,MAAM,EACjB,iBAAiB,EAAE,MAAM,GAAG,SAAS,EACrC,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EACjB,OAAO,EAAE,mBAAmB,GAC1B,OAAO,CAAC,cAAc,CAAC,CA4CzB","sourcesContent":["/**\n * Goal evaluator — a lightweight LLM call that checks whether a session goal\n * condition is met based on the conversation so far.\n *\n * Inspired by Claude Code's /goal evaluator: it reads what the assistant has\n * produced (test output, git status, etc.) and judges the condition.\n *\n * When the condition is NOT met, it also provides a nextDirection to guide\n * the assistant's next turn.\n */\n\nimport type { Model, SimpleStreamOptions } from \"@openeryc/pi-ai\";\nimport { completeSimple } from \"@openeryc/pi-ai\";\n\nconst EVALUATOR_PROMPT = `You are a goal evaluator. Your job is to determine whether a session goal condition is satisfied based on the conversation, and if not, suggest a concrete next step.\n\nRead the <session-goal> condition and the latest assistant output, then decide:\n\n### If the condition is clearly met:\nReturn {\"met\": true, \"reason\": \"...\"} with a short explanation of what evidence proves it.\n\n### If the condition is NOT met:\nReturn {\"met\": false, \"reason\": \"...\", \"nextDirection\": \"...\"}\n- reason: what's still missing or what went wrong\n- nextDirection: a specific, actionable instruction for the assistant's very next turn. Tell it exactly what to do next — which file to edit, which command to run, what to check, etc. Do NOT say \"continue working\" — be concrete.\n\nBe strict: the condition must be unambiguously satisfied. If the assistant claims success but the evidence (test output, command results) doesn't back it up, return false.\n\nRespond ONLY with a single JSON object on one line. No other text.`;\n\nexport interface GoalEvaluation {\n\tmet: boolean;\n\treason: string;\n\t/** Concrete next-step instruction when the goal is not yet met. */\n\tnextDirection?: string;\n}\n\n/**\n * Evaluate whether a goal condition is met based on recent conversation.\n * When not met, returns a nextDirection to guide the next turn.\n */\nexport async function evaluateGoalCondition(\n\tcondition: string,\n\tlastAssistantText: string | undefined,\n\tmodel: Model<any>,\n\toptions: SimpleStreamOptions,\n): Promise<GoalEvaluation> {\n\tif (!lastAssistantText) {\n\t\treturn {\n\t\t\tmet: false,\n\t\t\treason: \"No assistant output to evaluate yet.\",\n\t\t\tnextDirection: `Work toward: \"${condition}\". Start by exploring the codebase and understanding what needs to be done.`,\n\t\t};\n\t}\n\n\tconst userPrompt = `<session-goal>\\n${condition}\\n</session-goal>\\n\\n<latest-assistant-output>\\n${lastAssistantText.slice(0, 8000)}\\n</latest-assistant-output>\\n\\nDoes the assistant output demonstrate that the goal condition is met? If not, what should the assistant do next? Respond with JSON.`;\n\n\ttry {\n\t\tconst response = await completeSimple(\n\t\t\tmodel,\n\t\t\t{\n\t\t\t\tsystemPrompt: EVALUATOR_PROMPT,\n\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t},\n\t\t\t{ ...options, maxTokens: 500 },\n\t\t);\n\n\t\tconst textContent = response.content\n\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t.map((c) => c.text)\n\t\t\t.join(\"\");\n\n\t\tconst jsonMatch = textContent.match(/\\{.*\\}/s);\n\t\tif (jsonMatch) {\n\t\t\treturn JSON.parse(jsonMatch[0]) as GoalEvaluation;\n\t\t}\n\n\t\treturn {\n\t\t\tmet: false,\n\t\t\treason: \"Evaluator returned unparseable response.\",\n\t\t\tnextDirection: `Keep working on: ${condition}`,\n\t\t};\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"Unknown evaluator error\";\n\t\treturn {\n\t\t\tmet: false,\n\t\t\treason: `Evaluation failed: ${errorMessage}`,\n\t\t\tnextDirection: `Keep working on: ${condition}`,\n\t\t};\n\t}\n}\n"]}
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Goal evaluator — a lightweight LLM call that checks whether a session goal
3
+ * condition is met based on the conversation so far.
4
+ *
5
+ * Inspired by Claude Code's /goal evaluator: it reads what the assistant has
6
+ * produced (test output, git status, etc.) and judges the condition.
7
+ *
8
+ * When the condition is NOT met, it also provides a nextDirection to guide
9
+ * the assistant's next turn.
10
+ */
11
+ import { completeSimple } from "@openeryc/pi-ai";
12
+ const EVALUATOR_PROMPT = `You are a goal evaluator. Your job is to determine whether a session goal condition is satisfied based on the conversation, and if not, suggest a concrete next step.
13
+
14
+ Read the <session-goal> condition and the latest assistant output, then decide:
15
+
16
+ ### If the condition is clearly met:
17
+ Return {"met": true, "reason": "..."} with a short explanation of what evidence proves it.
18
+
19
+ ### If the condition is NOT met:
20
+ Return {"met": false, "reason": "...", "nextDirection": "..."}
21
+ - reason: what's still missing or what went wrong
22
+ - nextDirection: a specific, actionable instruction for the assistant's very next turn. Tell it exactly what to do next — which file to edit, which command to run, what to check, etc. Do NOT say "continue working" — be concrete.
23
+
24
+ Be strict: the condition must be unambiguously satisfied. If the assistant claims success but the evidence (test output, command results) doesn't back it up, return false.
25
+
26
+ Respond ONLY with a single JSON object on one line. No other text.`;
27
+ /**
28
+ * Evaluate whether a goal condition is met based on recent conversation.
29
+ * When not met, returns a nextDirection to guide the next turn.
30
+ */
31
+ export async function evaluateGoalCondition(condition, lastAssistantText, model, options) {
32
+ if (!lastAssistantText) {
33
+ return {
34
+ met: false,
35
+ reason: "No assistant output to evaluate yet.",
36
+ nextDirection: `Work toward: "${condition}". Start by exploring the codebase and understanding what needs to be done.`,
37
+ };
38
+ }
39
+ const userPrompt = `<session-goal>\n${condition}\n</session-goal>\n\n<latest-assistant-output>\n${lastAssistantText.slice(0, 8000)}\n</latest-assistant-output>\n\nDoes the assistant output demonstrate that the goal condition is met? If not, what should the assistant do next? Respond with JSON.`;
40
+ try {
41
+ const response = await completeSimple(model, {
42
+ systemPrompt: EVALUATOR_PROMPT,
43
+ messages: [{ role: "user", content: [{ type: "text", text: userPrompt }], timestamp: Date.now() }],
44
+ }, { ...options, maxTokens: 500 });
45
+ const textContent = response.content
46
+ .filter((c) => c.type === "text")
47
+ .map((c) => c.text)
48
+ .join("");
49
+ const jsonMatch = textContent.match(/\{.*\}/s);
50
+ if (jsonMatch) {
51
+ return JSON.parse(jsonMatch[0]);
52
+ }
53
+ return {
54
+ met: false,
55
+ reason: "Evaluator returned unparseable response.",
56
+ nextDirection: `Keep working on: ${condition}`,
57
+ };
58
+ }
59
+ catch (error) {
60
+ const errorMessage = error instanceof Error ? error.message : "Unknown evaluator error";
61
+ return {
62
+ met: false,
63
+ reason: `Evaluation failed: ${errorMessage}`,
64
+ nextDirection: `Keep working on: ${condition}`,
65
+ };
66
+ }
67
+ }
68
+ //# sourceMappingURL=goal-evaluator.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"goal-evaluator.js","sourceRoot":"","sources":["../../../src/modes/interactive/goal-evaluator.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAGH,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEjD,MAAM,gBAAgB,GAAG;;;;;;;;;;;;;;mEAc0C,CAAC;AASpE;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CAC1C,SAAiB,EACjB,iBAAqC,EACrC,KAAiB,EACjB,OAA4B,EACF;IAC1B,IAAI,CAAC,iBAAiB,EAAE,CAAC;QACxB,OAAO;YACN,GAAG,EAAE,KAAK;YACV,MAAM,EAAE,sCAAsC;YAC9C,aAAa,EAAE,iBAAiB,SAAS,6EAA6E;SACtH,CAAC;IACH,CAAC;IAED,MAAM,UAAU,GAAG,mBAAmB,SAAS,mDAAmD,iBAAiB,CAAC,KAAK,CAAC,CAAC,EA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Goal evaluator — a lightweight LLM call that checks whether a session goal\n * condition is met based on the conversation so far.\n *\n * Inspired by Claude Code's /goal evaluator: it reads what the assistant has\n * produced (test output, git status, etc.) and judges the condition.\n *\n * When the condition is NOT met, it also provides a nextDirection to guide\n * the assistant's next turn.\n */\n\nimport type { Model, SimpleStreamOptions } from \"@openeryc/pi-ai\";\nimport { completeSimple } from \"@openeryc/pi-ai\";\n\nconst EVALUATOR_PROMPT = `You are a goal evaluator. Your job is to determine whether a session goal condition is satisfied based on the conversation, and if not, suggest a concrete next step.\n\nRead the <session-goal> condition and the latest assistant output, then decide:\n\n### If the condition is clearly met:\nReturn {\"met\": true, \"reason\": \"...\"} with a short explanation of what evidence proves it.\n\n### If the condition is NOT met:\nReturn {\"met\": false, \"reason\": \"...\", \"nextDirection\": \"...\"}\n- reason: what's still missing or what went wrong\n- nextDirection: a specific, actionable instruction for the assistant's very next turn. Tell it exactly what to do next — which file to edit, which command to run, what to check, etc. Do NOT say \"continue working\" — be concrete.\n\nBe strict: the condition must be unambiguously satisfied. If the assistant claims success but the evidence (test output, command results) doesn't back it up, return false.\n\nRespond ONLY with a single JSON object on one line. No other text.`;\n\nexport interface GoalEvaluation {\n\tmet: boolean;\n\treason: string;\n\t/** Concrete next-step instruction when the goal is not yet met. */\n\tnextDirection?: string;\n}\n\n/**\n * Evaluate whether a goal condition is met based on recent conversation.\n * When not met, returns a nextDirection to guide the next turn.\n */\nexport async function evaluateGoalCondition(\n\tcondition: string,\n\tlastAssistantText: string | undefined,\n\tmodel: Model<any>,\n\toptions: SimpleStreamOptions,\n): Promise<GoalEvaluation> {\n\tif (!lastAssistantText) {\n\t\treturn {\n\t\t\tmet: false,\n\t\t\treason: \"No assistant output to evaluate yet.\",\n\t\t\tnextDirection: `Work toward: \"${condition}\". Start by exploring the codebase and understanding what needs to be done.`,\n\t\t};\n\t}\n\n\tconst userPrompt = `<session-goal>\\n${condition}\\n</session-goal>\\n\\n<latest-assistant-output>\\n${lastAssistantText.slice(0, 8000)}\\n</latest-assistant-output>\\n\\nDoes the assistant output demonstrate that the goal condition is met? If not, what should the assistant do next? Respond with JSON.`;\n\n\ttry {\n\t\tconst response = await completeSimple(\n\t\t\tmodel,\n\t\t\t{\n\t\t\t\tsystemPrompt: EVALUATOR_PROMPT,\n\t\t\t\tmessages: [{ role: \"user\", content: [{ type: \"text\", text: userPrompt }], timestamp: Date.now() }],\n\t\t\t},\n\t\t\t{ ...options, maxTokens: 500 },\n\t\t);\n\n\t\tconst textContent = response.content\n\t\t\t.filter((c): c is { type: \"text\"; text: string } => c.type === \"text\")\n\t\t\t.map((c) => c.text)\n\t\t\t.join(\"\");\n\n\t\tconst jsonMatch = textContent.match(/\\{.*\\}/s);\n\t\tif (jsonMatch) {\n\t\t\treturn JSON.parse(jsonMatch[0]) as GoalEvaluation;\n\t\t}\n\n\t\treturn {\n\t\t\tmet: false,\n\t\t\treason: \"Evaluator returned unparseable response.\",\n\t\t\tnextDirection: `Keep working on: ${condition}`,\n\t\t};\n\t} catch (error) {\n\t\tconst errorMessage = error instanceof Error ? error.message : \"Unknown evaluator error\";\n\t\treturn {\n\t\t\tmet: false,\n\t\t\treason: `Evaluation failed: ${errorMessage}`,\n\t\t\tnextDirection: `Keep working on: ${condition}`,\n\t\t};\n\t}\n}\n"]}
@@ -80,13 +80,12 @@ export declare class InteractiveMode {
80
80
  private goalRunnerAbortController;
81
81
  private goalRunnerRetryAttempt;
82
82
  private goalRunnerStatusDisplayed;
83
- /** Normalized assistant texts from recent goal turns (for duplicate detection). */
84
- private goalRunnerRecentOutputs;
85
- private readonly GOAL_RUNNER_MAX_RETRIES;
86
- private readonly GOAL_RUNNER_BASE_DELAY_MS;
83
+ private goalRunnerTurnCount;
84
+ private goalRunnerStartTime;
85
+ private goalRunnerTokenSpend;
86
+ private goalRunnerLastEvalReason;
87
87
  private readonly GOAL_RUNNER_TURN_DELAY_MS;
88
- /** Pause when this many consecutive turns look like near-duplicates. */
89
- private readonly GOAL_RUNNER_MAX_DUPLICATE_STREAK;
88
+ private readonly GOAL_RUNNER_RETRY_DELAY_MS;
90
89
  private extensionSelector;
91
90
  private extensionInput;
92
91
  private extensionEditor;
@@ -379,6 +378,7 @@ export declare class InteractiveMode {
379
378
  private handleCopyCommand;
380
379
  private handleNameCommand;
381
380
  private handleGoalCommand;
381
+ private formatDuration;
382
382
  private goalRunnerContinuationLoop;
383
383
  private handleSessionCommand;
384
384
  private showMcpSelector;