@kolisachint/hoocode-agent 0.5.25 → 0.5.27

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 (88) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/dist/core/canvas/lifecycle.d.ts +93 -0
  3. package/dist/core/canvas/lifecycle.d.ts.map +1 -0
  4. package/dist/core/canvas/lifecycle.js +165 -0
  5. package/dist/core/canvas/lifecycle.js.map +1 -0
  6. package/dist/core/canvas/registry.d.ts +89 -0
  7. package/dist/core/canvas/registry.d.ts.map +1 -1
  8. package/dist/core/canvas/registry.js +205 -10
  9. package/dist/core/canvas/registry.js.map +1 -1
  10. package/dist/core/canvas/scaffold.d.ts +123 -0
  11. package/dist/core/canvas/scaffold.d.ts.map +1 -0
  12. package/dist/core/canvas/scaffold.js +376 -0
  13. package/dist/core/canvas/scaffold.js.map +1 -0
  14. package/dist/core/canvas/session.d.ts +39 -1
  15. package/dist/core/canvas/session.d.ts.map +1 -1
  16. package/dist/core/canvas/session.js +83 -1
  17. package/dist/core/canvas/session.js.map +1 -1
  18. package/dist/core/capabilities/lexical.d.ts +4 -0
  19. package/dist/core/capabilities/lexical.d.ts.map +1 -1
  20. package/dist/core/capabilities/lexical.js +104 -4
  21. package/dist/core/capabilities/lexical.js.map +1 -1
  22. package/dist/core/capabilities/registry.d.ts +3 -1
  23. package/dist/core/capabilities/registry.d.ts.map +1 -1
  24. package/dist/core/capabilities/registry.js.map +1 -1
  25. package/dist/core/self-docs.d.ts +103 -0
  26. package/dist/core/self-docs.d.ts.map +1 -0
  27. package/dist/core/self-docs.js +351 -0
  28. package/dist/core/self-docs.js.map +1 -0
  29. package/dist/core/system-prompt.d.ts +12 -0
  30. package/dist/core/system-prompt.d.ts.map +1 -1
  31. package/dist/core/system-prompt.js +11 -1
  32. package/dist/core/system-prompt.js.map +1 -1
  33. package/dist/core/tools/canvas.d.ts +23 -3
  34. package/dist/core/tools/canvas.d.ts.map +1 -1
  35. package/dist/core/tools/canvas.js +99 -4
  36. package/dist/core/tools/canvas.js.map +1 -1
  37. package/dist/extensions/core/canvas.d.ts +20 -2
  38. package/dist/extensions/core/canvas.d.ts.map +1 -1
  39. package/dist/extensions/core/canvas.js +279 -36
  40. package/dist/extensions/core/canvas.js.map +1 -1
  41. package/dist/extensions/core/hoo-core.d.ts +1 -0
  42. package/dist/extensions/core/hoo-core.d.ts.map +1 -1
  43. package/dist/extensions/core/hoo-core.js +3 -0
  44. package/dist/extensions/core/hoo-core.js.map +1 -1
  45. package/dist/extensions/core/mcp-loader.d.ts.map +1 -1
  46. package/dist/extensions/core/mcp-loader.js +8 -2
  47. package/dist/extensions/core/mcp-loader.js.map +1 -1
  48. package/dist/extensions/core/scaffold.d.ts +7 -1
  49. package/dist/extensions/core/scaffold.d.ts.map +1 -1
  50. package/dist/extensions/core/scaffold.js +7 -185
  51. package/dist/extensions/core/scaffold.js.map +1 -1
  52. package/dist/extensions/core/self-knowledge.d.ts +28 -0
  53. package/dist/extensions/core/self-knowledge.d.ts.map +1 -0
  54. package/dist/extensions/core/self-knowledge.js +199 -0
  55. package/dist/extensions/core/self-knowledge.js.map +1 -0
  56. package/docs/canvas.md +117 -0
  57. package/docs/compaction.md +4 -4
  58. package/docs/custom-provider.md +1 -1
  59. package/docs/development.md +1 -1
  60. package/docs/docs.json +27 -2
  61. package/docs/extensions.md +12 -12
  62. package/docs/index.md +8 -0
  63. package/docs/keybindings.md +2 -2
  64. package/docs/mcp.md +97 -0
  65. package/docs/models.md +1 -1
  66. package/docs/modes.md +87 -0
  67. package/docs/packages.md +4 -4
  68. package/docs/plugins.md +124 -0
  69. package/docs/prompt-templates.md +1 -1
  70. package/docs/providers.md +2 -2
  71. package/docs/quickstart.md +2 -2
  72. package/docs/rpc.md +5 -5
  73. package/docs/sdk.md +5 -5
  74. package/docs/session-format.md +3 -3
  75. package/docs/sessions.md +1 -1
  76. package/docs/settings.md +3 -3
  77. package/docs/shell-aliases.md +1 -1
  78. package/docs/skills.md +2 -2
  79. package/docs/terminal-setup.md +1 -1
  80. package/docs/termux.md +2 -2
  81. package/docs/themes.md +3 -3
  82. package/docs/usage.md +93 -4
  83. package/docs/windows.md +1 -1
  84. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  85. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  86. package/examples/extensions/sandbox/package.json +1 -1
  87. package/examples/extensions/with-deps/package.json +1 -1
  88. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,KAAK,eAAe,EAAkB,MAAM,wBAAwB,CAAC;AAE9E,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAEhE,MAAM,WAAW,wBAAwB;IACxC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,6FAA6F;IAC7F,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,yBAAyB;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,gCAAgC;IAChC,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxD,yBAAyB;IACzB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;IACjB;;;;OAIG;IACH,MAAM,CAAC,EAAE,eAAe,EAAE,CAAC;CAC3B;AAED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,MAAM,CA8K3E","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { type AgentDefinition, TASK_TOOL_NAME } from \"./agent-frontmatter.js\";\nimport { formatAgentsForPrompt } from \"./agent-registry.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\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, search, grep, find, ls] */\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/**\n\t * Available agents for delegation, emitted as `<available_agents>` XML.\n\t * Only populated when the Task tool is active so the model knows which\n\t * agents exist without re-reading the agent registry each turn.\n\t */\n\tagents?: AgentDefinition[];\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\tagents: providedAgents,\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\tconst agents = providedAgents ?? [];\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 += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst hasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (hasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append agents section (only when Task tool is active)\n\t\tconst hasTask = !selectedTools || selectedTools.includes(TASK_TOOL_NAME);\n\t\tif (hasTask && agents.length > 0) {\n\t\t\tprompt += formatAgentsForPrompt(agents);\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// 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\", \"search\", \"grep\", \"find\", \"ls\"];\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// 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 hasSearch = tools.includes(\"search\");\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. Name only the tools that are actually\n\t// registered (the condition used to OR the three but hardcode all three\n\t// names, advertising tools that might not exist) and map each to its job so\n\t// the model picks the right one instead of defaulting to its bash habit.\n\tconst explore: string[] = [];\n\tif (hasSearch) explore.push(\"search (find where code lives by concept or identifier)\");\n\tif (hasGrep) explore.push(\"grep (exact line/regex search)\");\n\tif (hasFind) explore.push(\"find (locate files by name/glob)\");\n\tif (hasLs) explore.push(\"ls (list directory contents)\");\n\tif (explore.length > 0) {\n\t\taddGuideline(\n\t\t\t`For file exploration use the dedicated tools — ${explore.join(\", \")} — instead of bash; they are faster, and respect .gitignore where applicable`,\n\t\t);\n\t} else if (hasBash) {\n\t\taddGuideline(\"Use bash for file exploration (ls, rg/grep, find)\");\n\t}\n\n\t// Single source of truth for the search↔grep decision. Gated on both tools\n\t// being active so we never reference a tool that isn't registered — grep.ts\n\t// and search.ts intentionally no longer cross-reference each other, since a\n\t// tool factory can't know what else is in the bundle.\n\tif (hasSearch && hasGrep) {\n\t\taddGuideline(\n\t\t\t\"Between search and grep: search finds where code lives by concept, behavior, or half-known name (ranked results); grep enumerates exact matching lines, regexes, and counts (output proportional to matches)\",\n\t\t);\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(\"No preamble or postamble; do not restate the task or summarize what you just did\");\n\taddGuideline('Do not add closers like \"Let me know\" or \"Hope this helps\"');\n\taddGuideline(\n\t\t\"Do not narrate routine tool calls or results — the permission gate already shows them; speak when you have the answer or need a decision\",\n\t);\n\taddGuideline(\n\t\t\"Match the surrounding code's conventions for comments, docstrings, and types — do not add or strip them by default\",\n\t);\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside hoocode, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}`;\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 += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\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 agents section (only when Task tool is active)\n\tconst hasTask = tools.includes(TASK_TOOL_NAME);\n\tif (hasTask && agents.length > 0) {\n\t\tprompt += formatAgentsForPrompt(agents);\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"]}
1
+ {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,KAAK,eAAe,EAAkB,MAAM,wBAAwB,CAAC;AAG9E,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAEhE,MAAM,WAAW,wBAAwB;IACxC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,6FAA6F;IAC7F,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,yBAAyB;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,gCAAgC;IAChC,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxD,yBAAyB;IACzB,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;IACjB;;;;OAIG;IACH,MAAM,CAAC,EAAE,eAAe,EAAE,CAAC;IAC3B;;;;;;;;;;OAUG;IACH,eAAe,CAAC,EAAE,OAAO,CAAC;CAC1B;AAED,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,MAAM,CA0L3E","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { type AgentDefinition, TASK_TOOL_NAME } from \"./agent-frontmatter.js\";\nimport { formatAgentsForPrompt } from \"./agent-registry.js\";\nimport { formatSelfDocsForPrompt } from \"./self-docs.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\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, search, grep, find, ls] */\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/**\n\t * Available agents for delegation, emitted as `<available_agents>` XML.\n\t * Only populated when the Task tool is active so the model knows which\n\t * agents exist without re-reading the agent registry each turn.\n\t */\n\tagents?: AgentDefinition[];\n\t/**\n\t * Point the model at hoocode's own shipped docs so it can answer questions\n\t * about hoocode itself.\n\t *\n\t * Defaults to true for the built-in prompt and false when `customPrompt`\n\t * replaces it. Every other appended section (context files, skills, agents)\n\t * only appears because the caller passed the content in; this one\n\t * materializes on its own, so a caller who has taken over the system prompt\n\t * gets it only by asking. That also keeps it out of light mode, whose whole\n\t * point is a minimal fixed per-turn surface. Needs the read tool either way.\n\t */\n\tincludeSelfDocs?: boolean;\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\tagents: providedAgents,\n\t\tincludeSelfDocs,\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\tconst wantSelfDocs = includeSelfDocs ?? !customPrompt;\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\tconst agents = providedAgents ?? [];\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 += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst hasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (hasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append agents section (only when Task tool is active)\n\t\tconst hasTask = !selectedTools || selectedTools.includes(TASK_TOOL_NAME);\n\t\tif (hasTask && agents.length > 0) {\n\t\t\tprompt += formatAgentsForPrompt(agents);\n\t\t}\n\n\t\t// Append hoocode's own docs (only if read tool is available)\n\t\tif (wantSelfDocs && hasRead) {\n\t\t\tprompt += formatSelfDocsForPrompt();\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// 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\", \"search\", \"grep\", \"find\", \"ls\"];\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// 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 hasSearch = tools.includes(\"search\");\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. Name only the tools that are actually\n\t// registered (the condition used to OR the three but hardcode all three\n\t// names, advertising tools that might not exist) and map each to its job so\n\t// the model picks the right one instead of defaulting to its bash habit.\n\tconst explore: string[] = [];\n\tif (hasSearch) explore.push(\"search (find where code lives by concept or identifier)\");\n\tif (hasGrep) explore.push(\"grep (exact line/regex search)\");\n\tif (hasFind) explore.push(\"find (locate files by name/glob)\");\n\tif (hasLs) explore.push(\"ls (list directory contents)\");\n\tif (explore.length > 0) {\n\t\taddGuideline(\n\t\t\t`For file exploration use the dedicated tools — ${explore.join(\", \")} — instead of bash; they are faster, and respect .gitignore where applicable`,\n\t\t);\n\t} else if (hasBash) {\n\t\taddGuideline(\"Use bash for file exploration (ls, rg/grep, find)\");\n\t}\n\n\t// Single source of truth for the search↔grep decision. Gated on both tools\n\t// being active so we never reference a tool that isn't registered — grep.ts\n\t// and search.ts intentionally no longer cross-reference each other, since a\n\t// tool factory can't know what else is in the bundle.\n\tif (hasSearch && hasGrep) {\n\t\taddGuideline(\n\t\t\t\"Between search and grep: search finds where code lives by concept, behavior, or half-known name (ranked results); grep enumerates exact matching lines, regexes, and counts (output proportional to matches)\",\n\t\t);\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(\"No preamble or postamble; do not restate the task or summarize what you just did\");\n\taddGuideline('Do not add closers like \"Let me know\" or \"Hope this helps\"');\n\taddGuideline(\n\t\t\"Do not narrate routine tool calls or results — the permission gate already shows them; speak when you have the answer or need a decision\",\n\t);\n\taddGuideline(\n\t\t\"Match the surrounding code's conventions for comments, docstrings, and types — do not add or strip them by default\",\n\t);\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside hoocode, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}`;\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 += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\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 agents section (only when Task tool is active)\n\tconst hasTask = tools.includes(TASK_TOOL_NAME);\n\tif (hasTask && agents.length > 0) {\n\t\tprompt += formatAgentsForPrompt(agents);\n\t}\n\n\t// Append hoocode's own docs (only if read tool is available)\n\tif (wantSelfDocs && hasRead) {\n\t\tprompt += formatSelfDocsForPrompt();\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"]}
@@ -3,10 +3,11 @@
3
3
  */
4
4
  import { TASK_TOOL_NAME } from "./agent-frontmatter.js";
5
5
  import { formatAgentsForPrompt } from "./agent-registry.js";
6
+ import { formatSelfDocsForPrompt } from "./self-docs.js";
6
7
  import { formatSkillsForPrompt } from "./skills.js";
7
8
  /** Build the system prompt with tools, guidelines, and context */
8
9
  export function buildSystemPrompt(options) {
9
- const { customPrompt, selectedTools, toolSnippets, promptGuidelines, appendSystemPrompt, cwd, contextFiles: providedContextFiles, skills: providedSkills, agents: providedAgents, } = options;
10
+ const { customPrompt, selectedTools, toolSnippets, promptGuidelines, appendSystemPrompt, cwd, contextFiles: providedContextFiles, skills: providedSkills, agents: providedAgents, includeSelfDocs, } = options;
10
11
  const resolvedCwd = cwd;
11
12
  const promptCwd = resolvedCwd.replace(/\\/g, "/");
12
13
  const now = new Date();
@@ -15,6 +16,7 @@ export function buildSystemPrompt(options) {
15
16
  const day = String(now.getDate()).padStart(2, "0");
16
17
  const date = `${year}-${month}-${day}`;
17
18
  const appendSection = appendSystemPrompt ? `\n\n${appendSystemPrompt}` : "";
19
+ const wantSelfDocs = includeSelfDocs ?? !customPrompt;
18
20
  const contextFiles = providedContextFiles ?? [];
19
21
  const skills = providedSkills ?? [];
20
22
  const agents = providedAgents ?? [];
@@ -41,6 +43,10 @@ export function buildSystemPrompt(options) {
41
43
  if (hasTask && agents.length > 0) {
42
44
  prompt += formatAgentsForPrompt(agents);
43
45
  }
46
+ // Append hoocode's own docs (only if read tool is available)
47
+ if (wantSelfDocs && hasRead) {
48
+ prompt += formatSelfDocsForPrompt();
49
+ }
44
50
  // Add date and working directory last
45
51
  prompt += `\nCurrent date: ${date}`;
46
52
  prompt += `\nCurrent working directory: ${promptCwd}`;
@@ -136,6 +142,10 @@ ${guidelines}`;
136
142
  if (hasTask && agents.length > 0) {
137
143
  prompt += formatAgentsForPrompt(agents);
138
144
  }
145
+ // Append hoocode's own docs (only if read tool is available)
146
+ if (wantSelfDocs && hasRead) {
147
+ prompt += formatSelfDocsForPrompt();
148
+ }
139
149
  // Add date and working directory last
140
150
  prompt += `\nCurrent date: ${date}`;
141
151
  prompt += `\nCurrent working directory: ${promptCwd}`;
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAwB,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AA2BhE,kEAAkE;AAClE,MAAM,UAAU,iBAAiB,CAAC,OAAiC,EAAU;I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QACtC,MAAM,IAAI,mDAAmD,CAAC;QAC9D,KAAK,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,YAAY,EAAE,CAAC;YACxD,MAAM,IAAI,MAAM,QAAQ,OAAO,OAAO,MAAM,CAAC;QAC9C,CAAC;IACF,CAAC;IAED,yDAAyD;IACzD,IAAI,OAAO,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAClC,MAAM,IAAI,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACzC,CAAC;IAED,wDAAwD;IACxD,MAAM,OAAO,GAAG,KAAK,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;IAC/C,IAAI,OAAO,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAClC,MAAM,IAAI,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACzC,CAAC;IAED,sCAAsC;IACtC,MAAM,IAAI,mBAAmB,IAAI,EAAE,CAAC;IACpC,MAAM,IAAI,gCAAgC,SAAS,EAAE,CAAC;IAEtD,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { type AgentDefinition, TASK_TOOL_NAME } from \"./agent-frontmatter.js\";\nimport { formatAgentsForPrompt } from \"./agent-registry.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\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, search, grep, find, ls] */\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/**\n\t * Available agents for delegation, emitted as `<available_agents>` XML.\n\t * Only populated when the Task tool is active so the model knows which\n\t * agents exist without re-reading the agent registry each turn.\n\t */\n\tagents?: AgentDefinition[];\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\tagents: providedAgents,\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\tconst agents = providedAgents ?? [];\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 += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst hasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (hasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append agents section (only when Task tool is active)\n\t\tconst hasTask = !selectedTools || selectedTools.includes(TASK_TOOL_NAME);\n\t\tif (hasTask && agents.length > 0) {\n\t\t\tprompt += formatAgentsForPrompt(agents);\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// 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\", \"search\", \"grep\", \"find\", \"ls\"];\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// 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 hasSearch = tools.includes(\"search\");\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. Name only the tools that are actually\n\t// registered (the condition used to OR the three but hardcode all three\n\t// names, advertising tools that might not exist) and map each to its job so\n\t// the model picks the right one instead of defaulting to its bash habit.\n\tconst explore: string[] = [];\n\tif (hasSearch) explore.push(\"search (find where code lives by concept or identifier)\");\n\tif (hasGrep) explore.push(\"grep (exact line/regex search)\");\n\tif (hasFind) explore.push(\"find (locate files by name/glob)\");\n\tif (hasLs) explore.push(\"ls (list directory contents)\");\n\tif (explore.length > 0) {\n\t\taddGuideline(\n\t\t\t`For file exploration use the dedicated tools — ${explore.join(\", \")} — instead of bash; they are faster, and respect .gitignore where applicable`,\n\t\t);\n\t} else if (hasBash) {\n\t\taddGuideline(\"Use bash for file exploration (ls, rg/grep, find)\");\n\t}\n\n\t// Single source of truth for the search↔grep decision. Gated on both tools\n\t// being active so we never reference a tool that isn't registered — grep.ts\n\t// and search.ts intentionally no longer cross-reference each other, since a\n\t// tool factory can't know what else is in the bundle.\n\tif (hasSearch && hasGrep) {\n\t\taddGuideline(\n\t\t\t\"Between search and grep: search finds where code lives by concept, behavior, or half-known name (ranked results); grep enumerates exact matching lines, regexes, and counts (output proportional to matches)\",\n\t\t);\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(\"No preamble or postamble; do not restate the task or summarize what you just did\");\n\taddGuideline('Do not add closers like \"Let me know\" or \"Hope this helps\"');\n\taddGuideline(\n\t\t\"Do not narrate routine tool calls or results — the permission gate already shows them; speak when you have the answer or need a decision\",\n\t);\n\taddGuideline(\n\t\t\"Match the surrounding code's conventions for comments, docstrings, and types — do not add or strip them by default\",\n\t);\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside hoocode, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}`;\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 += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\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 agents section (only when Task tool is active)\n\tconst hasTask = tools.includes(TASK_TOOL_NAME);\n\tif (hasTask && agents.length > 0) {\n\t\tprompt += formatAgentsForPrompt(agents);\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"]}
1
+ {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAwB,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC9E,OAAO,EAAE,qBAAqB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAuChE,kEAAkE;AAClE,MAAM,UAAU,iBAAiB,CAAC,OAAiC,EAAU;IAC5E,MAAM,EACL,YAAY,EACZ,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,kBAAkB,EAClB,GAAG,EACH,YAAY,EAAE,oBAAoB,EAClC,MAAM,EAAE,cAAc,EACtB,MAAM,EAAE,cAAc,EACtB,eAAe,GACf,GAAG,OAAO,CAAC;IACZ,MAAM,WAAW,GAAG,GAAG,CAAC;IACxB,MAAM,SAAS,GAAG,WAAW,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IAElD,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC;IACvB,MAAM,IAAI,GAAG,GAAG,CAAC,WAAW,EAAE,CAAC;IAC/B,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;IAC1D,MAAM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AAK,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;IAC/C,IAAI,OAAO,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAClC,MAAM,IAAI,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACzC,CAAC;IAED,6DAA6D;IAC7D,IAAI,YAAY,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,IAAI,uBAAuB,EAAE,CAAC;IACrC,CAAC;IAED,sCAAsC;IACtC,MAAM,IAAI,mBAAmB,IAAI,EAAE,CAAC;IACpC,MAAM,IAAI,gCAAgC,SAAS,EAAE,CAAC;IAEtD,OAAO,MAAM,CAAC;AAAA,CACd","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { type AgentDefinition, TASK_TOOL_NAME } from \"./agent-frontmatter.js\";\nimport { formatAgentsForPrompt } from \"./agent-registry.js\";\nimport { formatSelfDocsForPrompt } from \"./self-docs.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.js\";\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, search, grep, find, ls] */\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/**\n\t * Available agents for delegation, emitted as `<available_agents>` XML.\n\t * Only populated when the Task tool is active so the model knows which\n\t * agents exist without re-reading the agent registry each turn.\n\t */\n\tagents?: AgentDefinition[];\n\t/**\n\t * Point the model at hoocode's own shipped docs so it can answer questions\n\t * about hoocode itself.\n\t *\n\t * Defaults to true for the built-in prompt and false when `customPrompt`\n\t * replaces it. Every other appended section (context files, skills, agents)\n\t * only appears because the caller passed the content in; this one\n\t * materializes on its own, so a caller who has taken over the system prompt\n\t * gets it only by asking. That also keeps it out of light mode, whose whole\n\t * point is a minimal fixed per-turn surface. Needs the read tool either way.\n\t */\n\tincludeSelfDocs?: boolean;\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\tagents: providedAgents,\n\t\tincludeSelfDocs,\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\tconst wantSelfDocs = includeSelfDocs ?? !customPrompt;\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\tconst agents = providedAgents ?? [];\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 += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t\t}\n\t\t}\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst hasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (hasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append agents section (only when Task tool is active)\n\t\tconst hasTask = !selectedTools || selectedTools.includes(TASK_TOOL_NAME);\n\t\tif (hasTask && agents.length > 0) {\n\t\t\tprompt += formatAgentsForPrompt(agents);\n\t\t}\n\n\t\t// Append hoocode's own docs (only if read tool is available)\n\t\tif (wantSelfDocs && hasRead) {\n\t\t\tprompt += formatSelfDocsForPrompt();\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// 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\", \"search\", \"grep\", \"find\", \"ls\"];\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// 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 hasSearch = tools.includes(\"search\");\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. Name only the tools that are actually\n\t// registered (the condition used to OR the three but hardcode all three\n\t// names, advertising tools that might not exist) and map each to its job so\n\t// the model picks the right one instead of defaulting to its bash habit.\n\tconst explore: string[] = [];\n\tif (hasSearch) explore.push(\"search (find where code lives by concept or identifier)\");\n\tif (hasGrep) explore.push(\"grep (exact line/regex search)\");\n\tif (hasFind) explore.push(\"find (locate files by name/glob)\");\n\tif (hasLs) explore.push(\"ls (list directory contents)\");\n\tif (explore.length > 0) {\n\t\taddGuideline(\n\t\t\t`For file exploration use the dedicated tools — ${explore.join(\", \")} — instead of bash; they are faster, and respect .gitignore where applicable`,\n\t\t);\n\t} else if (hasBash) {\n\t\taddGuideline(\"Use bash for file exploration (ls, rg/grep, find)\");\n\t}\n\n\t// Single source of truth for the search↔grep decision. Gated on both tools\n\t// being active so we never reference a tool that isn't registered — grep.ts\n\t// and search.ts intentionally no longer cross-reference each other, since a\n\t// tool factory can't know what else is in the bundle.\n\tif (hasSearch && hasGrep) {\n\t\taddGuideline(\n\t\t\t\"Between search and grep: search finds where code lives by concept, behavior, or half-known name (ranked results); grep enumerates exact matching lines, regexes, and counts (output proportional to matches)\",\n\t\t);\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(\"No preamble or postamble; do not restate the task or summarize what you just did\");\n\taddGuideline('Do not add closers like \"Let me know\" or \"Hope this helps\"');\n\taddGuideline(\n\t\t\"Do not narrate routine tool calls or results — the permission gate already shows them; speak when you have the answer or need a decision\",\n\t);\n\taddGuideline(\n\t\t\"Match the surrounding code's conventions for comments, docstrings, and types — do not add or strip them by default\",\n\t);\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside hoocode, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.\n\nGuidelines:\n${guidelines}`;\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 += `## ${filePath}\\n\\n${content}\\n\\n`;\n\t\t}\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 agents section (only when Task tool is active)\n\tconst hasTask = tools.includes(TASK_TOOL_NAME);\n\tif (hasTask && agents.length > 0) {\n\t\tprompt += formatAgentsForPrompt(agents);\n\t}\n\n\t// Append hoocode's own docs (only if read tool is available)\n\tif (wantSelfDocs && hasRead) {\n\t\tprompt += formatSelfDocsForPrompt();\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"]}
@@ -1,13 +1,19 @@
1
1
  /**
2
- * The two agent-facing canvas tools.
2
+ * The three agent-facing canvas tools.
3
3
  *
4
4
  * Design: `docs/canvas-extensions-design.md` §11.5. Copilot names its own shape in
5
5
  * the SDK types — `list_canvas_capabilities` to discover, `invoke_canvas_action` to
6
6
  * invoke — and hoocode mirrors it, for its own reason as well as fidelity:
7
7
  * `AGENTS.md` budgets the prompt at ~4,140 tokens with ~2,710 of it tool schemas,
8
8
  * and every active tool's schema is re-sent on every request. One tool per open
9
- * action would make that surface grow with how many canvases are open. Two fixed
10
- * tools keep it flat.
9
+ * action would make that surface grow with how many canvases are open. Fixed tools
10
+ * keep it flat.
11
+ *
12
+ * `reload_canvas` is hoocode's, not Copilot's, and it is what makes a canvas
13
+ * something the agent can *iterate on* rather than only drive: an edit to
14
+ * `extension.mjs` is invisible until the child forked from the old bytes is
15
+ * replaced. See {@link createReloadTool} for why reloading is the agent's to do
16
+ * while opening is not.
11
17
  *
12
18
  * **There is deliberately no "open a canvas" tool.** Opening forks a process and
13
19
  * binds a listening socket; that is a person's decision, gated by workspace trust
@@ -24,6 +30,11 @@ import { type ToolDefinition } from "../extensions/types.js";
24
30
  export declare const LIST_CANVAS_CAPABILITIES_TOOL_NAME = "list_canvas_capabilities";
25
31
  /** Tool name for action invocation, matching Copilot's. */
26
32
  export declare const INVOKE_CANVAS_ACTION_TOOL_NAME = "invoke_canvas_action";
33
+ /**
34
+ * Tool name for re-forking an edited extension. hoocode's own — Copilot has no
35
+ * equivalent because its `/create-canvas` flow reloads the panel itself.
36
+ */
37
+ export declare const RELOAD_CANVAS_TOOL_NAME = "reload_canvas";
27
38
  /**
28
39
  * Ceiling on a serialized action result, in characters.
29
40
  *
@@ -37,6 +48,15 @@ export interface CanvasCapabilitiesDetails {
37
48
  instances: number;
38
49
  actions: number;
39
50
  }
51
+ /** What `reload_canvas` reports. */
52
+ export interface CanvasReloadDetails {
53
+ extensionId: string;
54
+ reopened: number;
55
+ dropped: number;
56
+ actionsAdded: number;
57
+ actionsRemoved: number;
58
+ actionsChanged: number;
59
+ }
40
60
  /** What `invoke_canvas_action` reports. */
41
61
  export interface CanvasInvokeDetails {
42
62
  instanceId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"canvas.d.ts","sourceRoot":"","sources":["../../../src/core/tools/canvas.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAc,KAAK,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAEzE,8DAA8D;AAC9D,eAAO,MAAM,kCAAkC,6BAA6B,CAAC;AAC7E,2DAA2D;AAC3D,eAAO,MAAM,8BAA8B,yBAAyB,CAAC;AAErE;;;;;;GAMG;AACH,eAAO,MAAM,uBAAuB,OAAQ,CAAC;AAe7C,+CAA+C;AAC/C,MAAM,WAAW,yBAAyB;IACzC,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,2CAA2C;AAC3C,MAAM,WAAW,mBAAmB;IACnC,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,OAAO,CAAC;CACnB;AAkHD;;;;;;;GAOG;AACH,wBAAgB,2BAA2B,CAAC,QAAQ,EAAE,cAAc,GAAG,cAAc,EAAE,CAGtF","sourcesContent":["/**\n * The two agent-facing canvas tools.\n *\n * Design: `docs/canvas-extensions-design.md` §11.5. Copilot names its own shape in\n * the SDK types — `list_canvas_capabilities` to discover, `invoke_canvas_action` to\n * invoke — and hoocode mirrors it, for its own reason as well as fidelity:\n * `AGENTS.md` budgets the prompt at ~4,140 tokens with ~2,710 of it tool schemas,\n * and every active tool's schema is re-sent on every request. One tool per open\n * action would make that surface grow with how many canvases are open. Two fixed\n * tools keep it flat.\n *\n * **There is deliberately no \"open a canvas\" tool.** Opening forks a process and\n * binds a listening socket; that is a person's decision, gated by workspace trust\n * (§5). The agent drives a surface a human has already opened. This also keeps the\n * injection surface flat: a poisoned issue title rendered into a canvas can at most\n * cause an action on an instance the person chose to open.\n *\n * These are optional tools, created only when canvas support is available and at\n * least one canvas is open — so a repository without canvases pays nothing.\n */\n\nimport { type Static, Type } from \"typebox\";\nimport type { CanvasRegistry } from \"../canvas/registry.js\";\nimport { defineTool, type ToolDefinition } from \"../extensions/types.js\";\n\n/** Tool name for capability discovery, matching Copilot's. */\nexport const LIST_CANVAS_CAPABILITIES_TOOL_NAME = \"list_canvas_capabilities\";\n/** Tool name for action invocation, matching Copilot's. */\nexport const INVOKE_CANVAS_ACTION_TOOL_NAME = \"invoke_canvas_action\";\n\n/**\n * Ceiling on a serialized action result, in characters.\n *\n * Whatever an action returns lands in the model's context window.\n * `pr-artifact-explorer` truncates its own payloads (`entries.slice(0, 200)`), but\n * nothing in the contract obliges a canvas to, so the host caps it too.\n */\nexport const CANVAS_RESULT_MAX_CHARS = 8_000;\n\nconst listParams = Type.Object({}, { additionalProperties: false });\n\nconst invokeParams = Type.Object(\n\t{\n\t\tinstanceId: Type.String({ description: \"From list_canvas_capabilities.\" }),\n\t\taction: Type.String({ description: \"Action name declared by that instance's canvas.\" }),\n\t\tinput: Type.Optional(Type.Unknown({ description: \"Action input, matching the action's declared schema.\" })),\n\t},\n\t{ additionalProperties: false },\n);\n\ntype InvokeParams = Static<typeof invokeParams>;\n\n/** What `list_canvas_capabilities` reports. */\nexport interface CanvasCapabilitiesDetails {\n\tinstances: number;\n\tactions: number;\n}\n\n/** What `invoke_canvas_action` reports. */\nexport interface CanvasInvokeDetails {\n\tinstanceId: string;\n\taction: string;\n\ttruncated: boolean;\n}\n\nfunction textResult(text: string) {\n\treturn { content: [{ type: \"text\" as const, text }] };\n}\n\n/** Serialize an action result, capped so a chatty canvas cannot flood the context. */\nfunction renderResult(value: unknown): { text: string; truncated: boolean } {\n\tconst serialized = value === undefined ? \"null\" : JSON.stringify(value, null, 1);\n\tif (serialized.length <= CANVAS_RESULT_MAX_CHARS) return { text: serialized, truncated: false };\n\treturn {\n\t\ttext: `${serialized.slice(0, CANVAS_RESULT_MAX_CHARS)}\\n… truncated at ${CANVAS_RESULT_MAX_CHARS} characters.`,\n\t\ttruncated: true,\n\t};\n}\n\n/**\n * Discovery: every open instance, its canvas, and the actions it declares with\n * their input schemas.\n *\n * Takes no parameters. A filter would add schema bytes on every request to save\n * bytes in a response the model reads once.\n */\nfunction createListCapabilitiesTool(registry: CanvasRegistry): ToolDefinition {\n\treturn defineTool<typeof listParams, CanvasCapabilitiesDetails>({\n\t\tname: LIST_CANVAS_CAPABILITIES_TOOL_NAME,\n\t\tlabel: LIST_CANVAS_CAPABILITIES_TOOL_NAME,\n\t\tdescription:\n\t\t\t\"List the open canvases and the actions each one accepts, with their input schemas. Call this before invoke_canvas_action to learn the instanceId and the action's schema.\",\n\t\tpromptSnippet: \"Discover open canvases and the actions they accept\",\n\t\tparameters: listParams,\n\t\tasync execute() {\n\t\t\tconst instances = registry.listInstances();\n\t\t\tconst bindings = registry.activeActions();\n\t\t\tif (instances.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\t...textResult(\"No canvas is open. A person opens a canvas; you can then drive it.\"),\n\t\t\t\t\tdetails: { instances: 0, actions: 0 },\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst report = instances.map((instance) => ({\n\t\t\t\tinstanceId: instance.instanceId,\n\t\t\t\tcanvas: instance.canvasId,\n\t\t\t\textension: instance.extensionId,\n\t\t\t\ttitle: instance.title,\n\t\t\t\tstatus: instance.status,\n\t\t\t\tactions: bindings\n\t\t\t\t\t.filter((binding) => binding.instanceId === instance.instanceId)\n\t\t\t\t\t.map((binding) => binding.action),\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\t...textResult(JSON.stringify(report, null, 1)),\n\t\t\t\tdetails: { instances: instances.length, actions: bindings.length },\n\t\t\t};\n\t\t},\n\t});\n}\n\n/** Invocation: run one declared action against one open instance. */\nfunction createInvokeActionTool(registry: CanvasRegistry): ToolDefinition {\n\treturn defineTool<typeof invokeParams, CanvasInvokeDetails>({\n\t\tname: INVOKE_CANVAS_ACTION_TOOL_NAME,\n\t\tlabel: INVOKE_CANVAS_ACTION_TOOL_NAME,\n\t\t// The description deliberately makes no safety claim. An earlier version said\n\t\t// actions \"cannot edit files or run commands\", which is false: a canvas\n\t\t// extension is arbitrary Node code running with the user's privileges, and\n\t\t// `pr-artifact-explorer` really does download artifacts to disk and call the\n\t\t// GitHub API. Those side effects never pass hoocode's permission gate, because\n\t\t// the gate sits in front of hoocode's own tools, not inside a forked\n\t\t// extension — the workspace-trust gate (canvas/trust.ts) is the control here,\n\t\t// not a sentence in a tool schema. Never tell the model a safety property the\n\t\t// runtime does not enforce.\n\t\tdescription:\n\t\t\t\"Invoke an action on an open canvas. Actions are implemented by the canvas extension itself: an action may change what the person is looking at and can have side effects of its own, so read the action's description before calling it.\",\n\t\tpromptSnippet: \"Act on an open canvas the user is looking at\",\n\t\tparameters: invokeParams,\n\t\tasync execute(_toolCallId, params: InvokeParams, signal) {\n\t\t\t// instanceId is a UUID and unique across every canvas, so the model does not\n\t\t\t// have to carry the extension and canvas ids too — the registry already knows\n\t\t\t// which instance a given id belongs to.\n\t\t\tconst instance = registry.listInstances().find((open) => open.instanceId === params.instanceId);\n\t\t\tif (!instance) {\n\t\t\t\t// Tools report failure by throwing here, as the built-ins do; the loop turns\n\t\t\t\t// a rejection into the model's tool result.\n\t\t\t\tconst open = registry.listInstances().map((other) => other.instanceId);\n\t\t\t\tthrow new Error(\n\t\t\t\t\topen.length === 0\n\t\t\t\t\t\t? \"No canvas is open, so there is nothing to act on.\"\n\t\t\t\t\t\t: `No open canvas instance \"${params.instanceId}\". Open instances: ${open.join(\", \")}.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Honour the turn's abort signal: without this, aborting a turn leaves the\n\t\t\t\t// request running and its answer arriving for a turn nobody awaits.\n\t\t\t\tconst result = await registry.invokeAction(instance, params.action, params.input as never, { signal });\n\t\t\t\tconst { text, truncated } = renderResult(result);\n\t\t\t\treturn {\n\t\t\t\t\t...textResult(text),\n\t\t\t\t\tdetails: { instanceId: params.instanceId, action: params.action, truncated },\n\t\t\t\t};\n\t\t\t} catch (cause) {\n\t\t\t\t// Canvas handlers throw CanvasError with a machine-readable code, which the\n\t\t\t\t// runner preserves across the process boundary as CanvasCallError.code. Only\n\t\t\t\t// the message is rendered to the model, so fold the code into it rather than\n\t\t\t\t// letting the typed-error intent (§8) stop at the tool boundary.\n\t\t\t\tconst code = cause instanceof Error && \"code\" in cause ? String(cause.code) : undefined;\n\t\t\t\tconst message = cause instanceof Error ? cause.message : String(cause);\n\t\t\t\tthrow new Error(code ? `${code}: ${message}` : message);\n\t\t\t}\n\t\t},\n\t});\n}\n\n/**\n * The canvas tools, or none.\n *\n * Returns an empty array while nothing is open, so the two schemas are absent from\n * the prompt in the overwhelmingly common case of a repository with no canvases —\n * the same reason `registry.activeActions()` is empty until an instance exists\n * (§7). Callers re-derive this when the open set changes.\n */\nexport function createCanvasToolDefinitions(registry: CanvasRegistry): ToolDefinition[] {\n\tif (registry.listInstances().length === 0) return [];\n\treturn [createListCapabilitiesTool(registry), createInvokeActionTool(registry)];\n}\n"]}
1
+ {"version":3,"file":"canvas.d.ts","sourceRoot":"","sources":["../../../src/core/tools/canvas.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAGH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAc,KAAK,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAEzE,8DAA8D;AAC9D,eAAO,MAAM,kCAAkC,6BAA6B,CAAC;AAC7E,2DAA2D;AAC3D,eAAO,MAAM,8BAA8B,yBAAyB,CAAC;AACrE;;;GAGG;AACH,eAAO,MAAM,uBAAuB,kBAAkB,CAAC;AAEvD;;;;;;GAMG;AACH,eAAO,MAAM,uBAAuB,OAAQ,CAAC;AA0B7C,+CAA+C;AAC/C,MAAM,WAAW,yBAAyB;IACzC,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,oCAAoC;AACpC,MAAM,WAAW,mBAAmB;IACnC,WAAW,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;IACvB,cAAc,EAAE,MAAM,CAAC;CACvB;AAED,2CAA2C;AAC3C,MAAM,WAAW,mBAAmB;IACnC,UAAU,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,OAAO,CAAC;CACnB;AAgND;;;;;;;GAOG;AACH,wBAAgB,2BAA2B,CAAC,QAAQ,EAAE,cAAc,GAAG,cAAc,EAAE,CAGtF","sourcesContent":["/**\n * The three agent-facing canvas tools.\n *\n * Design: `docs/canvas-extensions-design.md` §11.5. Copilot names its own shape in\n * the SDK types — `list_canvas_capabilities` to discover, `invoke_canvas_action` to\n * invoke — and hoocode mirrors it, for its own reason as well as fidelity:\n * `AGENTS.md` budgets the prompt at ~4,140 tokens with ~2,710 of it tool schemas,\n * and every active tool's schema is re-sent on every request. One tool per open\n * action would make that surface grow with how many canvases are open. Fixed tools\n * keep it flat.\n *\n * `reload_canvas` is hoocode's, not Copilot's, and it is what makes a canvas\n * something the agent can *iterate on* rather than only drive: an edit to\n * `extension.mjs` is invisible until the child forked from the old bytes is\n * replaced. See {@link createReloadTool} for why reloading is the agent's to do\n * while opening is not.\n *\n * **There is deliberately no \"open a canvas\" tool.** Opening forks a process and\n * binds a listening socket; that is a person's decision, gated by workspace trust\n * (§5). The agent drives a surface a human has already opened. This also keeps the\n * injection surface flat: a poisoned issue title rendered into a canvas can at most\n * cause an action on an instance the person chose to open.\n *\n * These are optional tools, created only when canvas support is available and at\n * least one canvas is open — so a repository without canvases pays nothing.\n */\n\nimport { type Static, Type } from \"typebox\";\nimport type { CanvasRegistry } from \"../canvas/registry.js\";\nimport { defineTool, type ToolDefinition } from \"../extensions/types.js\";\n\n/** Tool name for capability discovery, matching Copilot's. */\nexport const LIST_CANVAS_CAPABILITIES_TOOL_NAME = \"list_canvas_capabilities\";\n/** Tool name for action invocation, matching Copilot's. */\nexport const INVOKE_CANVAS_ACTION_TOOL_NAME = \"invoke_canvas_action\";\n/**\n * Tool name for re-forking an edited extension. hoocode's own — Copilot has no\n * equivalent because its `/create-canvas` flow reloads the panel itself.\n */\nexport const RELOAD_CANVAS_TOOL_NAME = \"reload_canvas\";\n\n/**\n * Ceiling on a serialized action result, in characters.\n *\n * Whatever an action returns lands in the model's context window.\n * `pr-artifact-explorer` truncates its own payloads (`entries.slice(0, 200)`), but\n * nothing in the contract obliges a canvas to, so the host caps it too.\n */\nexport const CANVAS_RESULT_MAX_CHARS = 8_000;\n\nconst listParams = Type.Object({}, { additionalProperties: false });\n\nconst reloadParams = Type.Object(\n\t{\n\t\textensionId: Type.String({\n\t\t\tdescription: \"The extension whose code changed. From list_canvas_capabilities (the `extension` field).\",\n\t\t}),\n\t},\n\t{ additionalProperties: false },\n);\n\ntype ReloadParams = Static<typeof reloadParams>;\n\nconst invokeParams = Type.Object(\n\t{\n\t\tinstanceId: Type.String({ description: \"From list_canvas_capabilities.\" }),\n\t\taction: Type.String({ description: \"Action name declared by that instance's canvas.\" }),\n\t\tinput: Type.Optional(Type.Unknown({ description: \"Action input, matching the action's declared schema.\" })),\n\t},\n\t{ additionalProperties: false },\n);\n\ntype InvokeParams = Static<typeof invokeParams>;\n\n/** What `list_canvas_capabilities` reports. */\nexport interface CanvasCapabilitiesDetails {\n\tinstances: number;\n\tactions: number;\n}\n\n/** What `reload_canvas` reports. */\nexport interface CanvasReloadDetails {\n\textensionId: string;\n\treopened: number;\n\tdropped: number;\n\tactionsAdded: number;\n\tactionsRemoved: number;\n\tactionsChanged: number;\n}\n\n/** What `invoke_canvas_action` reports. */\nexport interface CanvasInvokeDetails {\n\tinstanceId: string;\n\taction: string;\n\ttruncated: boolean;\n}\n\nfunction textResult(text: string) {\n\treturn { content: [{ type: \"text\" as const, text }] };\n}\n\n/** Serialize an action result, capped so a chatty canvas cannot flood the context. */\nfunction renderResult(value: unknown): { text: string; truncated: boolean } {\n\tconst serialized = value === undefined ? \"null\" : JSON.stringify(value, null, 1);\n\tif (serialized.length <= CANVAS_RESULT_MAX_CHARS) return { text: serialized, truncated: false };\n\treturn {\n\t\ttext: `${serialized.slice(0, CANVAS_RESULT_MAX_CHARS)}\\n… truncated at ${CANVAS_RESULT_MAX_CHARS} characters.`,\n\t\ttruncated: true,\n\t};\n}\n\n/**\n * Discovery: every open instance, its canvas, and the actions it declares with\n * their input schemas.\n *\n * Takes no parameters. A filter would add schema bytes on every request to save\n * bytes in a response the model reads once.\n */\nfunction createListCapabilitiesTool(registry: CanvasRegistry): ToolDefinition {\n\treturn defineTool<typeof listParams, CanvasCapabilitiesDetails>({\n\t\tname: LIST_CANVAS_CAPABILITIES_TOOL_NAME,\n\t\tlabel: LIST_CANVAS_CAPABILITIES_TOOL_NAME,\n\t\tdescription:\n\t\t\t\"List the open canvases and the actions each one accepts, with their input schemas. Call this before invoke_canvas_action to learn the instanceId and the action's schema.\",\n\t\tpromptSnippet: \"Discover open canvases and the actions they accept\",\n\t\tparameters: listParams,\n\t\tasync execute() {\n\t\t\tconst instances = registry.listInstances();\n\t\t\tconst bindings = registry.activeActions();\n\t\t\tif (instances.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\t...textResult(\"No canvas is open. A person opens a canvas; you can then drive it.\"),\n\t\t\t\t\tdetails: { instances: 0, actions: 0 },\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst report = instances.map((instance) => ({\n\t\t\t\tinstanceId: instance.instanceId,\n\t\t\t\tcanvas: instance.canvasId,\n\t\t\t\textension: instance.extensionId,\n\t\t\t\ttitle: instance.title,\n\t\t\t\tstatus: instance.status,\n\t\t\t\tactions: bindings\n\t\t\t\t\t.filter((binding) => binding.instanceId === instance.instanceId)\n\t\t\t\t\t.map((binding) => binding.action),\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\t...textResult(JSON.stringify(report, null, 1)),\n\t\t\t\tdetails: { instances: instances.length, actions: bindings.length },\n\t\t\t};\n\t\t},\n\t});\n}\n\n/** Invocation: run one declared action against one open instance. */\nfunction createInvokeActionTool(registry: CanvasRegistry): ToolDefinition {\n\treturn defineTool<typeof invokeParams, CanvasInvokeDetails>({\n\t\tname: INVOKE_CANVAS_ACTION_TOOL_NAME,\n\t\tlabel: INVOKE_CANVAS_ACTION_TOOL_NAME,\n\t\t// The description deliberately makes no safety claim. An earlier version said\n\t\t// actions \"cannot edit files or run commands\", which is false: a canvas\n\t\t// extension is arbitrary Node code running with the user's privileges, and\n\t\t// `pr-artifact-explorer` really does download artifacts to disk and call the\n\t\t// GitHub API. Those side effects never pass hoocode's permission gate, because\n\t\t// the gate sits in front of hoocode's own tools, not inside a forked\n\t\t// extension — the workspace-trust gate (canvas/trust.ts) is the control here,\n\t\t// not a sentence in a tool schema. Never tell the model a safety property the\n\t\t// runtime does not enforce.\n\t\tdescription:\n\t\t\t\"Invoke an action on an open canvas. Actions are implemented by the canvas extension itself: an action may change what the person is looking at and can have side effects of its own, so read the action's description before calling it.\",\n\t\tpromptSnippet: \"Act on an open canvas the user is looking at\",\n\t\tparameters: invokeParams,\n\t\tasync execute(_toolCallId, params: InvokeParams, signal) {\n\t\t\t// instanceId is a UUID and unique across every canvas, so the model does not\n\t\t\t// have to carry the extension and canvas ids too — the registry already knows\n\t\t\t// which instance a given id belongs to.\n\t\t\tconst instance = registry.listInstances().find((open) => open.instanceId === params.instanceId);\n\t\t\tif (!instance) {\n\t\t\t\t// Tools report failure by throwing here, as the built-ins do; the loop turns\n\t\t\t\t// a rejection into the model's tool result.\n\t\t\t\tconst open = registry.listInstances().map((other) => other.instanceId);\n\t\t\t\tthrow new Error(\n\t\t\t\t\topen.length === 0\n\t\t\t\t\t\t? \"No canvas is open, so there is nothing to act on.\"\n\t\t\t\t\t\t: `No open canvas instance \"${params.instanceId}\". Open instances: ${open.join(\", \")}.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Honour the turn's abort signal: without this, aborting a turn leaves the\n\t\t\t\t// request running and its answer arriving for a turn nobody awaits.\n\t\t\t\tconst result = await registry.invokeAction(instance, params.action, params.input as never, { signal });\n\t\t\t\tconst { text, truncated } = renderResult(result);\n\t\t\t\treturn {\n\t\t\t\t\t...textResult(text),\n\t\t\t\t\tdetails: { instanceId: params.instanceId, action: params.action, truncated },\n\t\t\t\t};\n\t\t\t} catch (cause) {\n\t\t\t\t// Canvas handlers throw CanvasError with a machine-readable code, which the\n\t\t\t\t// runner preserves across the process boundary as CanvasCallError.code. Only\n\t\t\t\t// the message is rendered to the model, so fold the code into it rather than\n\t\t\t\t// letting the typed-error intent (§8) stop at the tool boundary.\n\t\t\t\tconst code = cause instanceof Error && \"code\" in cause ? String(cause.code) : undefined;\n\t\t\t\tconst message = cause instanceof Error ? cause.message : String(cause);\n\t\t\t\tthrow new Error(code ? `${code}: ${message}` : message);\n\t\t\t}\n\t\t},\n\t});\n}\n\n/**\n * Reload: re-fork an extension whose source changed, carrying its open instances.\n *\n * This is the tool that makes a canvas *iterable* by the agent — \"add a column\",\n * \"make the header sticky\" — which is the whole point of authoring one in a\n * session. Editing `extension.mjs` alone changes nothing: the child forked from\n * the old bytes keeps serving until it is replaced.\n *\n * It reloads; it does not open. That distinction is what keeps §11.5's reasoning\n * intact. Opening is a person's decision because it starts a process from a\n * directory nobody has vouched for; reloading only restarts an extension the\n * person already opened, in a workspace they already trusted, from a path the\n * host already resolved. The model cannot reach a new extension through it, and\n * a poisoned string in some canvas's data still cannot cause one to start.\n *\n * It is not a safety boundary on the *contents* of the file, and must not be\n * described as one: whatever wrote `extension.mjs` — the model's own edit,\n * through the permission gate — is what runs.\n */\nfunction createReloadTool(registry: CanvasRegistry): ToolDefinition {\n\treturn defineTool<typeof reloadParams, CanvasReloadDetails>({\n\t\tname: RELOAD_CANVAS_TOOL_NAME,\n\t\tlabel: RELOAD_CANVAS_TOOL_NAME,\n\t\tdescription:\n\t\t\t\"Restart an open canvas extension so your edits to its source take effect. Editing the extension's file does nothing on its own — the running process was forked from the old code. Call this after every edit. It reports which actions you added, removed or changed, so use it to confirm an action you just wrote is really callable. Open instances are carried across and keep their instanceId, but each gets a NEW url: tell the person the new url, because the tab they have open is now dead.\",\n\t\tpromptSnippet: \"Restart an edited canvas so the change is live\",\n\t\tparameters: reloadParams,\n\t\tasync execute(_toolCallId, params: ReloadParams, signal) {\n\t\t\tconst running = [...new Set(registry.listInstances().map((instance) => instance.extensionId))];\n\t\t\tif (!running.includes(params.extensionId)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\trunning.length === 0\n\t\t\t\t\t\t? \"No canvas is open, so there is nothing to reload.\"\n\t\t\t\t\t\t: `Canvas extension \"${params.extensionId}\" has nothing open. Running: ${running.join(\", \")}.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// A failed reload is the common case while iterating — the edit did not\n\t\t\t// parse, or threw at module scope. The registry leaves the old child\n\t\t\t// serving in that case, so this reads as \"your edit is broken and the\n\t\t\t// canvas is untouched\", which is what the model needs to hear to fix it.\n\t\t\tconst result = await registry.reload(params.extensionId, { signal });\n\n\t\t\tconst lines = [`Reloaded ${params.extensionId}. It declares: ${result.canvases.join(\", \") || \"no canvases\"}.`];\n\n\t\t\t// The capability delta is the answer to the question an author actually has\n\t\t\t// after an edit — did the host see the action I just wrote? Silence would read\n\t\t\t// as success, so \"nothing changed\" is said out loud too.\n\t\t\tconst { added, removed, changed, current } = result.actions;\n\t\t\tif (added.length + removed.length + changed.length === 0) {\n\t\t\t\tlines.push(`Actions unchanged: ${current.join(\", \") || \"none\"}.`);\n\t\t\t} else {\n\t\t\t\tif (added.length > 0) lines.push(`Actions added: ${added.join(\", \")}.`);\n\t\t\t\tif (removed.length > 0) lines.push(`Actions removed: ${removed.join(\", \")}.`);\n\t\t\t\tif (changed.length > 0) {\n\t\t\t\t\tlines.push(\n\t\t\t\t\t\t`Actions changed (description or inputSchema): ${changed.join(\", \")}. Any schema you were holding for these is stale.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlines.push(`Now callable: ${current.join(\", \") || \"none\"}.`);\n\t\t\t}\n\t\t\tif (result.reopened.length > 0) {\n\t\t\t\tlines.push(\n\t\t\t\t\t\"Re-opened (give the person the new url — their old tab points at a closed port):\",\n\t\t\t\t\t...result.reopened.map(\n\t\t\t\t\t\t(instance) =>\n\t\t\t\t\t\t\t` ${instance.canvasId} (${instance.instanceId})${instance.url ? ` — ${instance.url}` : \"\"}`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (result.dropped.length > 0) {\n\t\t\t\tlines.push(\n\t\t\t\t\t\"Did not come back:\",\n\t\t\t\t\t...result.dropped.map((drop) => ` ${drop.canvasId} (${drop.instanceId}): ${drop.reason}`),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (result.reopened.length === 0 && result.dropped.length === 0) {\n\t\t\t\tlines.push(\"Nothing was open, so nothing was re-opened.\");\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...textResult(lines.join(\"\\n\")),\n\t\t\t\tdetails: {\n\t\t\t\t\textensionId: params.extensionId,\n\t\t\t\t\treopened: result.reopened.length,\n\t\t\t\t\tdropped: result.dropped.length,\n\t\t\t\t\tactionsAdded: added.length,\n\t\t\t\t\tactionsRemoved: removed.length,\n\t\t\t\t\tactionsChanged: changed.length,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t});\n}\n\n/**\n * The canvas tools, or none.\n *\n * Returns an empty array while nothing is open, so the two schemas are absent from\n * the prompt in the overwhelmingly common case of a repository with no canvases —\n * the same reason `registry.activeActions()` is empty until an instance exists\n * (§7). Callers re-derive this when the open set changes.\n */\nexport function createCanvasToolDefinitions(registry: CanvasRegistry): ToolDefinition[] {\n\tif (registry.listInstances().length === 0) return [];\n\treturn [createListCapabilitiesTool(registry), createInvokeActionTool(registry), createReloadTool(registry)];\n}\n"]}
@@ -1,13 +1,19 @@
1
1
  /**
2
- * The two agent-facing canvas tools.
2
+ * The three agent-facing canvas tools.
3
3
  *
4
4
  * Design: `docs/canvas-extensions-design.md` §11.5. Copilot names its own shape in
5
5
  * the SDK types — `list_canvas_capabilities` to discover, `invoke_canvas_action` to
6
6
  * invoke — and hoocode mirrors it, for its own reason as well as fidelity:
7
7
  * `AGENTS.md` budgets the prompt at ~4,140 tokens with ~2,710 of it tool schemas,
8
8
  * and every active tool's schema is re-sent on every request. One tool per open
9
- * action would make that surface grow with how many canvases are open. Two fixed
10
- * tools keep it flat.
9
+ * action would make that surface grow with how many canvases are open. Fixed tools
10
+ * keep it flat.
11
+ *
12
+ * `reload_canvas` is hoocode's, not Copilot's, and it is what makes a canvas
13
+ * something the agent can *iterate on* rather than only drive: an edit to
14
+ * `extension.mjs` is invisible until the child forked from the old bytes is
15
+ * replaced. See {@link createReloadTool} for why reloading is the agent's to do
16
+ * while opening is not.
11
17
  *
12
18
  * **There is deliberately no "open a canvas" tool.** Opening forks a process and
13
19
  * binds a listening socket; that is a person's decision, gated by workspace trust
@@ -24,6 +30,11 @@ import { defineTool } from "../extensions/types.js";
24
30
  export const LIST_CANVAS_CAPABILITIES_TOOL_NAME = "list_canvas_capabilities";
25
31
  /** Tool name for action invocation, matching Copilot's. */
26
32
  export const INVOKE_CANVAS_ACTION_TOOL_NAME = "invoke_canvas_action";
33
+ /**
34
+ * Tool name for re-forking an edited extension. hoocode's own — Copilot has no
35
+ * equivalent because its `/create-canvas` flow reloads the panel itself.
36
+ */
37
+ export const RELOAD_CANVAS_TOOL_NAME = "reload_canvas";
27
38
  /**
28
39
  * Ceiling on a serialized action result, in characters.
29
40
  *
@@ -33,6 +44,11 @@ export const INVOKE_CANVAS_ACTION_TOOL_NAME = "invoke_canvas_action";
33
44
  */
34
45
  export const CANVAS_RESULT_MAX_CHARS = 8_000;
35
46
  const listParams = Type.Object({}, { additionalProperties: false });
47
+ const reloadParams = Type.Object({
48
+ extensionId: Type.String({
49
+ description: "The extension whose code changed. From list_canvas_capabilities (the `extension` field).",
50
+ }),
51
+ }, { additionalProperties: false });
36
52
  const invokeParams = Type.Object({
37
53
  instanceId: Type.String({ description: "From list_canvas_capabilities." }),
38
54
  action: Type.String({ description: "Action name declared by that instance's canvas." }),
@@ -143,6 +159,85 @@ function createInvokeActionTool(registry) {
143
159
  },
144
160
  });
145
161
  }
162
+ /**
163
+ * Reload: re-fork an extension whose source changed, carrying its open instances.
164
+ *
165
+ * This is the tool that makes a canvas *iterable* by the agent — "add a column",
166
+ * "make the header sticky" — which is the whole point of authoring one in a
167
+ * session. Editing `extension.mjs` alone changes nothing: the child forked from
168
+ * the old bytes keeps serving until it is replaced.
169
+ *
170
+ * It reloads; it does not open. That distinction is what keeps §11.5's reasoning
171
+ * intact. Opening is a person's decision because it starts a process from a
172
+ * directory nobody has vouched for; reloading only restarts an extension the
173
+ * person already opened, in a workspace they already trusted, from a path the
174
+ * host already resolved. The model cannot reach a new extension through it, and
175
+ * a poisoned string in some canvas's data still cannot cause one to start.
176
+ *
177
+ * It is not a safety boundary on the *contents* of the file, and must not be
178
+ * described as one: whatever wrote `extension.mjs` — the model's own edit,
179
+ * through the permission gate — is what runs.
180
+ */
181
+ function createReloadTool(registry) {
182
+ return defineTool({
183
+ name: RELOAD_CANVAS_TOOL_NAME,
184
+ label: RELOAD_CANVAS_TOOL_NAME,
185
+ description: "Restart an open canvas extension so your edits to its source take effect. Editing the extension's file does nothing on its own — the running process was forked from the old code. Call this after every edit. It reports which actions you added, removed or changed, so use it to confirm an action you just wrote is really callable. Open instances are carried across and keep their instanceId, but each gets a NEW url: tell the person the new url, because the tab they have open is now dead.",
186
+ promptSnippet: "Restart an edited canvas so the change is live",
187
+ parameters: reloadParams,
188
+ async execute(_toolCallId, params, signal) {
189
+ const running = [...new Set(registry.listInstances().map((instance) => instance.extensionId))];
190
+ if (!running.includes(params.extensionId)) {
191
+ throw new Error(running.length === 0
192
+ ? "No canvas is open, so there is nothing to reload."
193
+ : `Canvas extension "${params.extensionId}" has nothing open. Running: ${running.join(", ")}.`);
194
+ }
195
+ // A failed reload is the common case while iterating — the edit did not
196
+ // parse, or threw at module scope. The registry leaves the old child
197
+ // serving in that case, so this reads as "your edit is broken and the
198
+ // canvas is untouched", which is what the model needs to hear to fix it.
199
+ const result = await registry.reload(params.extensionId, { signal });
200
+ const lines = [`Reloaded ${params.extensionId}. It declares: ${result.canvases.join(", ") || "no canvases"}.`];
201
+ // The capability delta is the answer to the question an author actually has
202
+ // after an edit — did the host see the action I just wrote? Silence would read
203
+ // as success, so "nothing changed" is said out loud too.
204
+ const { added, removed, changed, current } = result.actions;
205
+ if (added.length + removed.length + changed.length === 0) {
206
+ lines.push(`Actions unchanged: ${current.join(", ") || "none"}.`);
207
+ }
208
+ else {
209
+ if (added.length > 0)
210
+ lines.push(`Actions added: ${added.join(", ")}.`);
211
+ if (removed.length > 0)
212
+ lines.push(`Actions removed: ${removed.join(", ")}.`);
213
+ if (changed.length > 0) {
214
+ lines.push(`Actions changed (description or inputSchema): ${changed.join(", ")}. Any schema you were holding for these is stale.`);
215
+ }
216
+ lines.push(`Now callable: ${current.join(", ") || "none"}.`);
217
+ }
218
+ if (result.reopened.length > 0) {
219
+ lines.push("Re-opened (give the person the new url — their old tab points at a closed port):", ...result.reopened.map((instance) => ` ${instance.canvasId} (${instance.instanceId})${instance.url ? ` — ${instance.url}` : ""}`));
220
+ }
221
+ if (result.dropped.length > 0) {
222
+ lines.push("Did not come back:", ...result.dropped.map((drop) => ` ${drop.canvasId} (${drop.instanceId}): ${drop.reason}`));
223
+ }
224
+ if (result.reopened.length === 0 && result.dropped.length === 0) {
225
+ lines.push("Nothing was open, so nothing was re-opened.");
226
+ }
227
+ return {
228
+ ...textResult(lines.join("\n")),
229
+ details: {
230
+ extensionId: params.extensionId,
231
+ reopened: result.reopened.length,
232
+ dropped: result.dropped.length,
233
+ actionsAdded: added.length,
234
+ actionsRemoved: removed.length,
235
+ actionsChanged: changed.length,
236
+ },
237
+ };
238
+ },
239
+ });
240
+ }
146
241
  /**
147
242
  * The canvas tools, or none.
148
243
  *
@@ -154,6 +249,6 @@ function createInvokeActionTool(registry) {
154
249
  export function createCanvasToolDefinitions(registry) {
155
250
  if (registry.listInstances().length === 0)
156
251
  return [];
157
- return [createListCapabilitiesTool(registry), createInvokeActionTool(registry)];
252
+ return [createListCapabilitiesTool(registry), createInvokeActionTool(registry), createReloadTool(registry)];
158
253
  }
159
254
  //# sourceMappingURL=canvas.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"canvas.js","sourceRoot":"","sources":["../../../src/core/tools/canvas.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAEH,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AA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QAAQ,CAAC,CAAC,CAAC;AAAA,CAChF","sourcesContent":["/**\n * The two agent-facing canvas tools.\n *\n * Design: `docs/canvas-extensions-design.md` §11.5. Copilot names its own shape in\n * the SDK types — `list_canvas_capabilities` to discover, `invoke_canvas_action` to\n * invoke — and hoocode mirrors it, for its own reason as well as fidelity:\n * `AGENTS.md` budgets the prompt at ~4,140 tokens with ~2,710 of it tool schemas,\n * and every active tool's schema is re-sent on every request. One tool per open\n * action would make that surface grow with how many canvases are open. Two fixed\n * tools keep it flat.\n *\n * **There is deliberately no \"open a canvas\" tool.** Opening forks a process and\n * binds a listening socket; that is a person's decision, gated by workspace trust\n * (§5). The agent drives a surface a human has already opened. This also keeps the\n * injection surface flat: a poisoned issue title rendered into a canvas can at most\n * cause an action on an instance the person chose to open.\n *\n * These are optional tools, created only when canvas support is available and at\n * least one canvas is open — so a repository without canvases pays nothing.\n */\n\nimport { type Static, Type } from \"typebox\";\nimport type { CanvasRegistry } from \"../canvas/registry.js\";\nimport { defineTool, type ToolDefinition } from \"../extensions/types.js\";\n\n/** Tool name for capability discovery, matching Copilot's. */\nexport const LIST_CANVAS_CAPABILITIES_TOOL_NAME = \"list_canvas_capabilities\";\n/** Tool name for action invocation, matching Copilot's. */\nexport const INVOKE_CANVAS_ACTION_TOOL_NAME = \"invoke_canvas_action\";\n\n/**\n * Ceiling on a serialized action result, in characters.\n *\n * Whatever an action returns lands in the model's context window.\n * `pr-artifact-explorer` truncates its own payloads (`entries.slice(0, 200)`), but\n * nothing in the contract obliges a canvas to, so the host caps it too.\n */\nexport const CANVAS_RESULT_MAX_CHARS = 8_000;\n\nconst listParams = Type.Object({}, { additionalProperties: false });\n\nconst invokeParams = Type.Object(\n\t{\n\t\tinstanceId: Type.String({ description: \"From list_canvas_capabilities.\" }),\n\t\taction: Type.String({ description: \"Action name declared by that instance's canvas.\" }),\n\t\tinput: Type.Optional(Type.Unknown({ description: \"Action input, matching the action's declared schema.\" })),\n\t},\n\t{ additionalProperties: false },\n);\n\ntype InvokeParams = Static<typeof invokeParams>;\n\n/** What `list_canvas_capabilities` reports. */\nexport interface CanvasCapabilitiesDetails {\n\tinstances: number;\n\tactions: number;\n}\n\n/** What `invoke_canvas_action` reports. */\nexport interface CanvasInvokeDetails {\n\tinstanceId: string;\n\taction: string;\n\ttruncated: boolean;\n}\n\nfunction textResult(text: string) {\n\treturn { content: [{ type: \"text\" as const, text }] };\n}\n\n/** Serialize an action result, capped so a chatty canvas cannot flood the context. */\nfunction renderResult(value: unknown): { text: string; truncated: boolean } {\n\tconst serialized = value === undefined ? \"null\" : JSON.stringify(value, null, 1);\n\tif (serialized.length <= CANVAS_RESULT_MAX_CHARS) return { text: serialized, truncated: false };\n\treturn {\n\t\ttext: `${serialized.slice(0, CANVAS_RESULT_MAX_CHARS)}\\n… truncated at ${CANVAS_RESULT_MAX_CHARS} characters.`,\n\t\ttruncated: true,\n\t};\n}\n\n/**\n * Discovery: every open instance, its canvas, and the actions it declares with\n * their input schemas.\n *\n * Takes no parameters. A filter would add schema bytes on every request to save\n * bytes in a response the model reads once.\n */\nfunction createListCapabilitiesTool(registry: CanvasRegistry): ToolDefinition {\n\treturn defineTool<typeof listParams, CanvasCapabilitiesDetails>({\n\t\tname: LIST_CANVAS_CAPABILITIES_TOOL_NAME,\n\t\tlabel: LIST_CANVAS_CAPABILITIES_TOOL_NAME,\n\t\tdescription:\n\t\t\t\"List the open canvases and the actions each one accepts, with their input schemas. Call this before invoke_canvas_action to learn the instanceId and the action's schema.\",\n\t\tpromptSnippet: \"Discover open canvases and the actions they accept\",\n\t\tparameters: listParams,\n\t\tasync execute() {\n\t\t\tconst instances = registry.listInstances();\n\t\t\tconst bindings = registry.activeActions();\n\t\t\tif (instances.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\t...textResult(\"No canvas is open. A person opens a canvas; you can then drive it.\"),\n\t\t\t\t\tdetails: { instances: 0, actions: 0 },\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst report = instances.map((instance) => ({\n\t\t\t\tinstanceId: instance.instanceId,\n\t\t\t\tcanvas: instance.canvasId,\n\t\t\t\textension: instance.extensionId,\n\t\t\t\ttitle: instance.title,\n\t\t\t\tstatus: instance.status,\n\t\t\t\tactions: bindings\n\t\t\t\t\t.filter((binding) => binding.instanceId === instance.instanceId)\n\t\t\t\t\t.map((binding) => binding.action),\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\t...textResult(JSON.stringify(report, null, 1)),\n\t\t\t\tdetails: { instances: instances.length, actions: bindings.length },\n\t\t\t};\n\t\t},\n\t});\n}\n\n/** Invocation: run one declared action against one open instance. */\nfunction createInvokeActionTool(registry: CanvasRegistry): ToolDefinition {\n\treturn defineTool<typeof invokeParams, CanvasInvokeDetails>({\n\t\tname: INVOKE_CANVAS_ACTION_TOOL_NAME,\n\t\tlabel: INVOKE_CANVAS_ACTION_TOOL_NAME,\n\t\t// The description deliberately makes no safety claim. An earlier version said\n\t\t// actions \"cannot edit files or run commands\", which is false: a canvas\n\t\t// extension is arbitrary Node code running with the user's privileges, and\n\t\t// `pr-artifact-explorer` really does download artifacts to disk and call the\n\t\t// GitHub API. Those side effects never pass hoocode's permission gate, because\n\t\t// the gate sits in front of hoocode's own tools, not inside a forked\n\t\t// extension — the workspace-trust gate (canvas/trust.ts) is the control here,\n\t\t// not a sentence in a tool schema. Never tell the model a safety property the\n\t\t// runtime does not enforce.\n\t\tdescription:\n\t\t\t\"Invoke an action on an open canvas. Actions are implemented by the canvas extension itself: an action may change what the person is looking at and can have side effects of its own, so read the action's description before calling it.\",\n\t\tpromptSnippet: \"Act on an open canvas the user is looking at\",\n\t\tparameters: invokeParams,\n\t\tasync execute(_toolCallId, params: InvokeParams, signal) {\n\t\t\t// instanceId is a UUID and unique across every canvas, so the model does not\n\t\t\t// have to carry the extension and canvas ids too — the registry already knows\n\t\t\t// which instance a given id belongs to.\n\t\t\tconst instance = registry.listInstances().find((open) => open.instanceId === params.instanceId);\n\t\t\tif (!instance) {\n\t\t\t\t// Tools report failure by throwing here, as the built-ins do; the loop turns\n\t\t\t\t// a rejection into the model's tool result.\n\t\t\t\tconst open = registry.listInstances().map((other) => other.instanceId);\n\t\t\t\tthrow new Error(\n\t\t\t\t\topen.length === 0\n\t\t\t\t\t\t? \"No canvas is open, so there is nothing to act on.\"\n\t\t\t\t\t\t: `No open canvas instance \"${params.instanceId}\". Open instances: ${open.join(\", \")}.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Honour the turn's abort signal: without this, aborting a turn leaves the\n\t\t\t\t// request running and its answer arriving for a turn nobody awaits.\n\t\t\t\tconst result = await registry.invokeAction(instance, params.action, params.input as never, { signal });\n\t\t\t\tconst { text, truncated } = renderResult(result);\n\t\t\t\treturn {\n\t\t\t\t\t...textResult(text),\n\t\t\t\t\tdetails: { instanceId: params.instanceId, action: params.action, truncated },\n\t\t\t\t};\n\t\t\t} catch (cause) {\n\t\t\t\t// Canvas handlers throw CanvasError with a machine-readable code, which the\n\t\t\t\t// runner preserves across the process boundary as CanvasCallError.code. Only\n\t\t\t\t// the message is rendered to the model, so fold the code into it rather than\n\t\t\t\t// letting the typed-error intent (§8) stop at the tool boundary.\n\t\t\t\tconst code = cause instanceof Error && \"code\" in cause ? String(cause.code) : undefined;\n\t\t\t\tconst message = cause instanceof Error ? cause.message : String(cause);\n\t\t\t\tthrow new Error(code ? `${code}: ${message}` : message);\n\t\t\t}\n\t\t},\n\t});\n}\n\n/**\n * The canvas tools, or none.\n *\n * Returns an empty array while nothing is open, so the two schemas are absent from\n * the prompt in the overwhelmingly common case of a repository with no canvases —\n * the same reason `registry.activeActions()` is empty until an instance exists\n * (§7). Callers re-derive this when the open set changes.\n */\nexport function createCanvasToolDefinitions(registry: CanvasRegistry): ToolDefinition[] {\n\tif (registry.listInstances().length === 0) return [];\n\treturn [createListCapabilitiesTool(registry), createInvokeActionTool(registry)];\n}\n"]}
1
+ {"version":3,"file":"canvas.js","sourceRoot":"","sources":["../../../src/core/tools/canvas.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**\n * The three agent-facing canvas tools.\n *\n * Design: `docs/canvas-extensions-design.md` §11.5. Copilot names its own shape in\n * the SDK types — `list_canvas_capabilities` to discover, `invoke_canvas_action` to\n * invoke — and hoocode mirrors it, for its own reason as well as fidelity:\n * `AGENTS.md` budgets the prompt at ~4,140 tokens with ~2,710 of it tool schemas,\n * and every active tool's schema is re-sent on every request. One tool per open\n * action would make that surface grow with how many canvases are open. Fixed tools\n * keep it flat.\n *\n * `reload_canvas` is hoocode's, not Copilot's, and it is what makes a canvas\n * something the agent can *iterate on* rather than only drive: an edit to\n * `extension.mjs` is invisible until the child forked from the old bytes is\n * replaced. See {@link createReloadTool} for why reloading is the agent's to do\n * while opening is not.\n *\n * **There is deliberately no \"open a canvas\" tool.** Opening forks a process and\n * binds a listening socket; that is a person's decision, gated by workspace trust\n * (§5). The agent drives a surface a human has already opened. This also keeps the\n * injection surface flat: a poisoned issue title rendered into a canvas can at most\n * cause an action on an instance the person chose to open.\n *\n * These are optional tools, created only when canvas support is available and at\n * least one canvas is open — so a repository without canvases pays nothing.\n */\n\nimport { type Static, Type } from \"typebox\";\nimport type { CanvasRegistry } from \"../canvas/registry.js\";\nimport { defineTool, type ToolDefinition } from \"../extensions/types.js\";\n\n/** Tool name for capability discovery, matching Copilot's. */\nexport const LIST_CANVAS_CAPABILITIES_TOOL_NAME = \"list_canvas_capabilities\";\n/** Tool name for action invocation, matching Copilot's. */\nexport const INVOKE_CANVAS_ACTION_TOOL_NAME = \"invoke_canvas_action\";\n/**\n * Tool name for re-forking an edited extension. hoocode's own — Copilot has no\n * equivalent because its `/create-canvas` flow reloads the panel itself.\n */\nexport const RELOAD_CANVAS_TOOL_NAME = \"reload_canvas\";\n\n/**\n * Ceiling on a serialized action result, in characters.\n *\n * Whatever an action returns lands in the model's context window.\n * `pr-artifact-explorer` truncates its own payloads (`entries.slice(0, 200)`), but\n * nothing in the contract obliges a canvas to, so the host caps it too.\n */\nexport const CANVAS_RESULT_MAX_CHARS = 8_000;\n\nconst listParams = Type.Object({}, { additionalProperties: false });\n\nconst reloadParams = Type.Object(\n\t{\n\t\textensionId: Type.String({\n\t\t\tdescription: \"The extension whose code changed. From list_canvas_capabilities (the `extension` field).\",\n\t\t}),\n\t},\n\t{ additionalProperties: false },\n);\n\ntype ReloadParams = Static<typeof reloadParams>;\n\nconst invokeParams = Type.Object(\n\t{\n\t\tinstanceId: Type.String({ description: \"From list_canvas_capabilities.\" }),\n\t\taction: Type.String({ description: \"Action name declared by that instance's canvas.\" }),\n\t\tinput: Type.Optional(Type.Unknown({ description: \"Action input, matching the action's declared schema.\" })),\n\t},\n\t{ additionalProperties: false },\n);\n\ntype InvokeParams = Static<typeof invokeParams>;\n\n/** What `list_canvas_capabilities` reports. */\nexport interface CanvasCapabilitiesDetails {\n\tinstances: number;\n\tactions: number;\n}\n\n/** What `reload_canvas` reports. */\nexport interface CanvasReloadDetails {\n\textensionId: string;\n\treopened: number;\n\tdropped: number;\n\tactionsAdded: number;\n\tactionsRemoved: number;\n\tactionsChanged: number;\n}\n\n/** What `invoke_canvas_action` reports. */\nexport interface CanvasInvokeDetails {\n\tinstanceId: string;\n\taction: string;\n\ttruncated: boolean;\n}\n\nfunction textResult(text: string) {\n\treturn { content: [{ type: \"text\" as const, text }] };\n}\n\n/** Serialize an action result, capped so a chatty canvas cannot flood the context. */\nfunction renderResult(value: unknown): { text: string; truncated: boolean } {\n\tconst serialized = value === undefined ? \"null\" : JSON.stringify(value, null, 1);\n\tif (serialized.length <= CANVAS_RESULT_MAX_CHARS) return { text: serialized, truncated: false };\n\treturn {\n\t\ttext: `${serialized.slice(0, CANVAS_RESULT_MAX_CHARS)}\\n… truncated at ${CANVAS_RESULT_MAX_CHARS} characters.`,\n\t\ttruncated: true,\n\t};\n}\n\n/**\n * Discovery: every open instance, its canvas, and the actions it declares with\n * their input schemas.\n *\n * Takes no parameters. A filter would add schema bytes on every request to save\n * bytes in a response the model reads once.\n */\nfunction createListCapabilitiesTool(registry: CanvasRegistry): ToolDefinition {\n\treturn defineTool<typeof listParams, CanvasCapabilitiesDetails>({\n\t\tname: LIST_CANVAS_CAPABILITIES_TOOL_NAME,\n\t\tlabel: LIST_CANVAS_CAPABILITIES_TOOL_NAME,\n\t\tdescription:\n\t\t\t\"List the open canvases and the actions each one accepts, with their input schemas. Call this before invoke_canvas_action to learn the instanceId and the action's schema.\",\n\t\tpromptSnippet: \"Discover open canvases and the actions they accept\",\n\t\tparameters: listParams,\n\t\tasync execute() {\n\t\t\tconst instances = registry.listInstances();\n\t\t\tconst bindings = registry.activeActions();\n\t\t\tif (instances.length === 0) {\n\t\t\t\treturn {\n\t\t\t\t\t...textResult(\"No canvas is open. A person opens a canvas; you can then drive it.\"),\n\t\t\t\t\tdetails: { instances: 0, actions: 0 },\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst report = instances.map((instance) => ({\n\t\t\t\tinstanceId: instance.instanceId,\n\t\t\t\tcanvas: instance.canvasId,\n\t\t\t\textension: instance.extensionId,\n\t\t\t\ttitle: instance.title,\n\t\t\t\tstatus: instance.status,\n\t\t\t\tactions: bindings\n\t\t\t\t\t.filter((binding) => binding.instanceId === instance.instanceId)\n\t\t\t\t\t.map((binding) => binding.action),\n\t\t\t}));\n\t\t\treturn {\n\t\t\t\t...textResult(JSON.stringify(report, null, 1)),\n\t\t\t\tdetails: { instances: instances.length, actions: bindings.length },\n\t\t\t};\n\t\t},\n\t});\n}\n\n/** Invocation: run one declared action against one open instance. */\nfunction createInvokeActionTool(registry: CanvasRegistry): ToolDefinition {\n\treturn defineTool<typeof invokeParams, CanvasInvokeDetails>({\n\t\tname: INVOKE_CANVAS_ACTION_TOOL_NAME,\n\t\tlabel: INVOKE_CANVAS_ACTION_TOOL_NAME,\n\t\t// The description deliberately makes no safety claim. An earlier version said\n\t\t// actions \"cannot edit files or run commands\", which is false: a canvas\n\t\t// extension is arbitrary Node code running with the user's privileges, and\n\t\t// `pr-artifact-explorer` really does download artifacts to disk and call the\n\t\t// GitHub API. Those side effects never pass hoocode's permission gate, because\n\t\t// the gate sits in front of hoocode's own tools, not inside a forked\n\t\t// extension — the workspace-trust gate (canvas/trust.ts) is the control here,\n\t\t// not a sentence in a tool schema. Never tell the model a safety property the\n\t\t// runtime does not enforce.\n\t\tdescription:\n\t\t\t\"Invoke an action on an open canvas. Actions are implemented by the canvas extension itself: an action may change what the person is looking at and can have side effects of its own, so read the action's description before calling it.\",\n\t\tpromptSnippet: \"Act on an open canvas the user is looking at\",\n\t\tparameters: invokeParams,\n\t\tasync execute(_toolCallId, params: InvokeParams, signal) {\n\t\t\t// instanceId is a UUID and unique across every canvas, so the model does not\n\t\t\t// have to carry the extension and canvas ids too — the registry already knows\n\t\t\t// which instance a given id belongs to.\n\t\t\tconst instance = registry.listInstances().find((open) => open.instanceId === params.instanceId);\n\t\t\tif (!instance) {\n\t\t\t\t// Tools report failure by throwing here, as the built-ins do; the loop turns\n\t\t\t\t// a rejection into the model's tool result.\n\t\t\t\tconst open = registry.listInstances().map((other) => other.instanceId);\n\t\t\t\tthrow new Error(\n\t\t\t\t\topen.length === 0\n\t\t\t\t\t\t? \"No canvas is open, so there is nothing to act on.\"\n\t\t\t\t\t\t: `No open canvas instance \"${params.instanceId}\". Open instances: ${open.join(\", \")}.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\t// Honour the turn's abort signal: without this, aborting a turn leaves the\n\t\t\t\t// request running and its answer arriving for a turn nobody awaits.\n\t\t\t\tconst result = await registry.invokeAction(instance, params.action, params.input as never, { signal });\n\t\t\t\tconst { text, truncated } = renderResult(result);\n\t\t\t\treturn {\n\t\t\t\t\t...textResult(text),\n\t\t\t\t\tdetails: { instanceId: params.instanceId, action: params.action, truncated },\n\t\t\t\t};\n\t\t\t} catch (cause) {\n\t\t\t\t// Canvas handlers throw CanvasError with a machine-readable code, which the\n\t\t\t\t// runner preserves across the process boundary as CanvasCallError.code. Only\n\t\t\t\t// the message is rendered to the model, so fold the code into it rather than\n\t\t\t\t// letting the typed-error intent (§8) stop at the tool boundary.\n\t\t\t\tconst code = cause instanceof Error && \"code\" in cause ? String(cause.code) : undefined;\n\t\t\t\tconst message = cause instanceof Error ? cause.message : String(cause);\n\t\t\t\tthrow new Error(code ? `${code}: ${message}` : message);\n\t\t\t}\n\t\t},\n\t});\n}\n\n/**\n * Reload: re-fork an extension whose source changed, carrying its open instances.\n *\n * This is the tool that makes a canvas *iterable* by the agent — \"add a column\",\n * \"make the header sticky\" — which is the whole point of authoring one in a\n * session. Editing `extension.mjs` alone changes nothing: the child forked from\n * the old bytes keeps serving until it is replaced.\n *\n * It reloads; it does not open. That distinction is what keeps §11.5's reasoning\n * intact. Opening is a person's decision because it starts a process from a\n * directory nobody has vouched for; reloading only restarts an extension the\n * person already opened, in a workspace they already trusted, from a path the\n * host already resolved. The model cannot reach a new extension through it, and\n * a poisoned string in some canvas's data still cannot cause one to start.\n *\n * It is not a safety boundary on the *contents* of the file, and must not be\n * described as one: whatever wrote `extension.mjs` — the model's own edit,\n * through the permission gate — is what runs.\n */\nfunction createReloadTool(registry: CanvasRegistry): ToolDefinition {\n\treturn defineTool<typeof reloadParams, CanvasReloadDetails>({\n\t\tname: RELOAD_CANVAS_TOOL_NAME,\n\t\tlabel: RELOAD_CANVAS_TOOL_NAME,\n\t\tdescription:\n\t\t\t\"Restart an open canvas extension so your edits to its source take effect. Editing the extension's file does nothing on its own — the running process was forked from the old code. Call this after every edit. It reports which actions you added, removed or changed, so use it to confirm an action you just wrote is really callable. Open instances are carried across and keep their instanceId, but each gets a NEW url: tell the person the new url, because the tab they have open is now dead.\",\n\t\tpromptSnippet: \"Restart an edited canvas so the change is live\",\n\t\tparameters: reloadParams,\n\t\tasync execute(_toolCallId, params: ReloadParams, signal) {\n\t\t\tconst running = [...new Set(registry.listInstances().map((instance) => instance.extensionId))];\n\t\t\tif (!running.includes(params.extensionId)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\trunning.length === 0\n\t\t\t\t\t\t? \"No canvas is open, so there is nothing to reload.\"\n\t\t\t\t\t\t: `Canvas extension \"${params.extensionId}\" has nothing open. Running: ${running.join(\", \")}.`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// A failed reload is the common case while iterating — the edit did not\n\t\t\t// parse, or threw at module scope. The registry leaves the old child\n\t\t\t// serving in that case, so this reads as \"your edit is broken and the\n\t\t\t// canvas is untouched\", which is what the model needs to hear to fix it.\n\t\t\tconst result = await registry.reload(params.extensionId, { signal });\n\n\t\t\tconst lines = [`Reloaded ${params.extensionId}. It declares: ${result.canvases.join(\", \") || \"no canvases\"}.`];\n\n\t\t\t// The capability delta is the answer to the question an author actually has\n\t\t\t// after an edit — did the host see the action I just wrote? Silence would read\n\t\t\t// as success, so \"nothing changed\" is said out loud too.\n\t\t\tconst { added, removed, changed, current } = result.actions;\n\t\t\tif (added.length + removed.length + changed.length === 0) {\n\t\t\t\tlines.push(`Actions unchanged: ${current.join(\", \") || \"none\"}.`);\n\t\t\t} else {\n\t\t\t\tif (added.length > 0) lines.push(`Actions added: ${added.join(\", \")}.`);\n\t\t\t\tif (removed.length > 0) lines.push(`Actions removed: ${removed.join(\", \")}.`);\n\t\t\t\tif (changed.length > 0) {\n\t\t\t\t\tlines.push(\n\t\t\t\t\t\t`Actions changed (description or inputSchema): ${changed.join(\", \")}. Any schema you were holding for these is stale.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tlines.push(`Now callable: ${current.join(\", \") || \"none\"}.`);\n\t\t\t}\n\t\t\tif (result.reopened.length > 0) {\n\t\t\t\tlines.push(\n\t\t\t\t\t\"Re-opened (give the person the new url — their old tab points at a closed port):\",\n\t\t\t\t\t...result.reopened.map(\n\t\t\t\t\t\t(instance) =>\n\t\t\t\t\t\t\t` ${instance.canvasId} (${instance.instanceId})${instance.url ? ` — ${instance.url}` : \"\"}`,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (result.dropped.length > 0) {\n\t\t\t\tlines.push(\n\t\t\t\t\t\"Did not come back:\",\n\t\t\t\t\t...result.dropped.map((drop) => ` ${drop.canvasId} (${drop.instanceId}): ${drop.reason}`),\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (result.reopened.length === 0 && result.dropped.length === 0) {\n\t\t\t\tlines.push(\"Nothing was open, so nothing was re-opened.\");\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...textResult(lines.join(\"\\n\")),\n\t\t\t\tdetails: {\n\t\t\t\t\textensionId: params.extensionId,\n\t\t\t\t\treopened: result.reopened.length,\n\t\t\t\t\tdropped: result.dropped.length,\n\t\t\t\t\tactionsAdded: added.length,\n\t\t\t\t\tactionsRemoved: removed.length,\n\t\t\t\t\tactionsChanged: changed.length,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t});\n}\n\n/**\n * The canvas tools, or none.\n *\n * Returns an empty array while nothing is open, so the two schemas are absent from\n * the prompt in the overwhelmingly common case of a repository with no canvases —\n * the same reason `registry.activeActions()` is empty until an instance exists\n * (§7). Callers re-derive this when the open set changes.\n */\nexport function createCanvasToolDefinitions(registry: CanvasRegistry): ToolDefinition[] {\n\tif (registry.listInstances().length === 0) return [];\n\treturn [createListCapabilitiesTool(registry), createInvokeActionTool(registry), createReloadTool(registry)];\n}\n"]}
@@ -10,11 +10,29 @@
10
10
  * reaches the abandon path (§11.6) and the extension is told to release the port it
11
11
  * may already have bound, rather than the spinner merely disappearing.
12
12
  *
13
- * The two agent tools register on the first successful open and stay for the session:
13
+ * `/new-canvas` is registered here rather than beside `/new-skill` and friends
14
+ * because it is not a file-writing command any more: it opens what it scaffolds
15
+ * and hands the agent a brief to build it, which needs this file's session and
16
+ * `pi.sendUserMessage`. Its decisions live in `core/canvas/scaffold.ts`.
17
+ *
18
+ * The agent tools register on the first successful open and stay for the session:
14
19
  * `registerTool` has no counterpart to remove a tool. So a session that never opens a
15
20
  * canvas pays nothing for them, which is the case that matters (§11.5); after the
16
21
  * first open they cost ~235 tokens and answer honestly when nothing is open.
17
22
  */
23
+ import { type CanvasSessionOptions } from "../../core/canvas/session.js";
18
24
  import type { ExtensionAPI } from "../../core/extensions/types.js";
19
- export declare function setupCanvas(pi: ExtensionAPI): void;
25
+ /**
26
+ * Test seams, and only that.
27
+ *
28
+ * `/new-canvas` opens what it writes, so driving it without a terminal needs a
29
+ * runtime that does not depend on hoocode having been built, and a home
30
+ * directory that is not the developer's. Everything else this file does is
31
+ * decided in `core/canvas/`, where it is testable without any of this.
32
+ */
33
+ export interface CanvasSetupOverrides {
34
+ homeDir?: string;
35
+ resolveRuntime?: CanvasSessionOptions["resolveRuntime"];
36
+ }
37
+ export declare function setupCanvas(pi: ExtensionAPI, overrides?: CanvasSetupOverrides): void;
20
38
  //# sourceMappingURL=canvas.d.ts.map