open-multi-agent-kit 0.91.0 → 0.93.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/CHANGELOG.md +32 -1
  2. package/README.md +2 -2
  3. package/dist/core/agent-session.d.ts +29 -0
  4. package/dist/core/agent-session.d.ts.map +1 -1
  5. package/dist/core/agent-session.js +89 -21
  6. package/dist/core/agent-session.js.map +1 -1
  7. package/dist/core/command-safety.d.ts.map +1 -1
  8. package/dist/core/command-safety.js +0 -50
  9. package/dist/core/command-safety.js.map +1 -1
  10. package/dist/core/compaction/branch-summarization.d.ts +5 -1
  11. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  12. package/dist/core/compaction/branch-summarization.js +5 -7
  13. package/dist/core/compaction/branch-summarization.js.map +1 -1
  14. package/dist/core/compaction/compaction.d.ts +12 -3
  15. package/dist/core/compaction/compaction.d.ts.map +1 -1
  16. package/dist/core/compaction/compaction.js +28 -15
  17. package/dist/core/compaction/compaction.js.map +1 -1
  18. package/dist/core/compaction/transaction.d.ts.map +1 -1
  19. package/dist/core/compaction/transaction.js +7 -3
  20. package/dist/core/compaction/transaction.js.map +1 -1
  21. package/dist/core/context-budget-headroom-candidates.d.ts.map +1 -1
  22. package/dist/core/context-budget-headroom-candidates.js +21 -11
  23. package/dist/core/context-budget-headroom-candidates.js.map +1 -1
  24. package/dist/core/context-budget-system-prompt-items.d.ts +1 -0
  25. package/dist/core/context-budget-system-prompt-items.d.ts.map +1 -1
  26. package/dist/core/context-budget-system-prompt-items.js +7 -8
  27. package/dist/core/context-budget-system-prompt-items.js.map +1 -1
  28. package/dist/core/extensions/builtin/command-safety-gate.d.ts +8 -0
  29. package/dist/core/extensions/builtin/command-safety-gate.d.ts.map +1 -1
  30. package/dist/core/extensions/builtin/command-safety-gate.js +23 -0
  31. package/dist/core/extensions/builtin/command-safety-gate.js.map +1 -1
  32. package/dist/core/extensions/runner.d.ts.map +1 -1
  33. package/dist/core/extensions/runner.js +4 -0
  34. package/dist/core/extensions/runner.js.map +1 -1
  35. package/dist/core/extensions/types.d.ts +2 -0
  36. package/dist/core/extensions/types.d.ts.map +1 -1
  37. package/dist/core/extensions/types.js.map +1 -1
  38. package/dist/core/keybindings.d.ts +5 -0
  39. package/dist/core/keybindings.d.ts.map +1 -1
  40. package/dist/core/keybindings.js +5 -0
  41. package/dist/core/keybindings.js.map +1 -1
  42. package/dist/core/loadouts.d.ts.map +1 -1
  43. package/dist/core/loadouts.js +27 -48
  44. package/dist/core/loadouts.js.map +1 -1
  45. package/dist/core/model-resolver.d.ts +41 -3
  46. package/dist/core/model-resolver.d.ts.map +1 -1
  47. package/dist/core/model-resolver.js +17 -9
  48. package/dist/core/model-resolver.js.map +1 -1
  49. package/dist/core/provider-resilience.d.ts.map +1 -1
  50. package/dist/core/provider-resilience.js +3 -1
  51. package/dist/core/provider-resilience.js.map +1 -1
  52. package/dist/core/reasoning-router-v4-weights.d.ts.map +1 -1
  53. package/dist/core/reasoning-router-v4-weights.js +9 -3
  54. package/dist/core/reasoning-router-v4-weights.js.map +1 -1
  55. package/dist/core/reasoning-router-v4.d.ts.map +1 -1
  56. package/dist/core/reasoning-router-v4.js +94 -24
  57. package/dist/core/reasoning-router-v4.js.map +1 -1
  58. package/dist/core/resource-loader.d.ts.map +1 -1
  59. package/dist/core/resource-loader.js +11 -5
  60. package/dist/core/resource-loader.js.map +1 -1
  61. package/dist/core/session-file-compaction.d.ts.map +1 -1
  62. package/dist/core/session-file-compaction.js +39 -5
  63. package/dist/core/session-file-compaction.js.map +1 -1
  64. package/dist/core/session-termination.d.ts.map +1 -1
  65. package/dist/core/session-termination.js +1 -1
  66. package/dist/core/session-termination.js.map +1 -1
  67. package/dist/core/settings-manager.d.ts +3 -0
  68. package/dist/core/settings-manager.d.ts.map +1 -1
  69. package/dist/core/settings-manager.js +8 -0
  70. package/dist/core/settings-manager.js.map +1 -1
  71. package/dist/core/system-prompt.d.ts.map +1 -1
  72. package/dist/core/system-prompt.js +36 -31
  73. package/dist/core/system-prompt.js.map +1 -1
  74. package/dist/core/tools/bash.d.ts +2 -0
  75. package/dist/core/tools/bash.d.ts.map +1 -1
  76. package/dist/core/tools/bash.js +38 -11
  77. package/dist/core/tools/bash.js.map +1 -1
  78. package/dist/main.d.ts.map +1 -1
  79. package/dist/main.js +112 -11
  80. package/dist/main.js.map +1 -1
  81. package/dist/modes/interactive/components/control-panel-box.d.ts +27 -0
  82. package/dist/modes/interactive/components/control-panel-box.d.ts.map +1 -1
  83. package/dist/modes/interactive/components/control-panel-box.js +60 -8
  84. package/dist/modes/interactive/components/control-panel-box.js.map +1 -1
  85. package/dist/modes/interactive/components/control-panel-layout.d.ts.map +1 -1
  86. package/dist/modes/interactive/components/control-panel-layout.js +100 -45
  87. package/dist/modes/interactive/components/control-panel-layout.js.map +1 -1
  88. package/dist/modes/interactive/components/control-panel-runtime-status.d.ts +9 -0
  89. package/dist/modes/interactive/components/control-panel-runtime-status.d.ts.map +1 -1
  90. package/dist/modes/interactive/components/control-panel-runtime-status.js +10 -8
  91. package/dist/modes/interactive/components/control-panel-runtime-status.js.map +1 -1
  92. package/dist/modes/interactive/components/control-panel-sparkles.d.ts +5 -0
  93. package/dist/modes/interactive/components/control-panel-sparkles.d.ts.map +1 -1
  94. package/dist/modes/interactive/components/control-panel-sparkles.js +14 -9
  95. package/dist/modes/interactive/components/control-panel-sparkles.js.map +1 -1
  96. package/dist/modes/interactive/components/footer.d.ts +10 -0
  97. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  98. package/dist/modes/interactive/components/footer.js +3 -3
  99. package/dist/modes/interactive/components/footer.js.map +1 -1
  100. package/dist/modes/interactive/components/status-sidebar.d.ts +49 -0
  101. package/dist/modes/interactive/components/status-sidebar.d.ts.map +1 -0
  102. package/dist/modes/interactive/components/status-sidebar.js +253 -0
  103. package/dist/modes/interactive/components/status-sidebar.js.map +1 -0
  104. package/dist/modes/interactive/interactive-mode.d.ts +9 -0
  105. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  106. package/dist/modes/interactive/interactive-mode.js +94 -20
  107. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  108. package/dist/modes/interactive/theme/omk-neon-control.json +13 -13
  109. package/dist/modes/print-mode.d.ts.map +1 -1
  110. package/dist/modes/print-mode.js +9 -0
  111. package/dist/modes/print-mode.js.map +1 -1
  112. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  113. package/dist/modes/rpc/rpc-mode.js +1 -0
  114. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  115. package/dist/utils/clipboard.d.ts.map +1 -1
  116. package/dist/utils/clipboard.js +19 -8
  117. package/dist/utils/clipboard.js.map +1 -1
  118. package/docs/adaptorch-preview-spec.md +174 -0
  119. package/docs/adaptorch-preview.md +1 -1
  120. package/docs/compaction.md +20 -13
  121. package/docs/correctness-wall.md +13 -5
  122. package/docs/custom-provider.md +8 -8
  123. package/docs/development.md +2 -2
  124. package/docs/docs.json +4 -0
  125. package/docs/environment-variables.md +90 -0
  126. package/docs/extensions.md +8 -8
  127. package/docs/index.md +1 -0
  128. package/docs/json.md +4 -4
  129. package/docs/providers.md +1 -1
  130. package/docs/rpc.md +5 -2
  131. package/docs/session-format.md +5 -5
  132. package/docs/settings.md +1 -0
  133. package/docs/skills.md +2 -0
  134. package/docs/themes.md +2 -2
  135. package/docs/tui.md +4 -4
  136. package/docs/usage.md +4 -0
  137. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  138. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  139. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  140. package/examples/extensions/gondolin/package-lock.json +2 -2
  141. package/examples/extensions/gondolin/package.json +1 -1
  142. package/examples/extensions/sandbox/package-lock.json +2 -2
  143. package/examples/extensions/sandbox/package.json +1 -1
  144. package/examples/extensions/subagent/README.md +35 -10
  145. package/examples/extensions/subagent/adaptive-agent-runtime.test.ts +234 -0
  146. package/examples/extensions/subagent/adaptive-agent-runtime.ts +240 -0
  147. package/examples/extensions/subagent/adaptive-result.ts +112 -0
  148. package/examples/extensions/subagent/agents.test.ts +86 -0
  149. package/examples/extensions/subagent/agents.ts +18 -4
  150. package/examples/extensions/subagent/capabilities.ts +15 -1
  151. package/examples/extensions/subagent/checkpoint-runtime.test.ts +125 -0
  152. package/examples/extensions/subagent/checkpoint-runtime.ts +198 -0
  153. package/examples/extensions/subagent/deadline-budget.test.ts +135 -0
  154. package/examples/extensions/subagent/deadline-budget.ts +242 -0
  155. package/examples/extensions/subagent/deadline-profile-store.test.ts +72 -0
  156. package/examples/extensions/subagent/deadline-profile-store.ts +172 -0
  157. package/examples/extensions/subagent/domain-profiles.ts +272 -0
  158. package/examples/extensions/subagent/fixtures/fake-omk-json.mjs +13 -0
  159. package/examples/extensions/subagent/fixtures/hanging-process-tree.mjs +40 -0
  160. package/examples/extensions/subagent/index.ts +253 -137
  161. package/examples/extensions/subagent/managed-process.test.ts +178 -0
  162. package/examples/extensions/subagent/managed-process.ts +236 -0
  163. package/examples/extensions/subagent/subagent-extension-smoke.test.ts +112 -0
  164. package/examples/extensions/subagent/subagent-runtime-types.ts +76 -0
  165. package/examples/extensions/with-deps/package-lock.json +2 -2
  166. package/examples/extensions/with-deps/package.json +1 -1
  167. package/npm-shrinkwrap.json +21 -21
  168. package/package.json +10 -7
@@ -1 +1 @@
1
- {"version":3,"file":"context-budget-system-prompt-items.js","sourceRoot":"","sources":["../../src/core/context-budget-system-prompt-items.ts"],"names":[],"mappings":"AAAA,OAAO,EAA4B,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AACrF,OAAO,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAiB/F,MAAM,qBAAqB,GAAG,IAAI,CAAC;AACnC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAC/B,MAAM,mBAAmB,GAAG,EAAE,CAAC;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B,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC;SACvB,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;AAAA,CAC1B","sourcesContent":["import { type ContextBudgetItemV2, fnv1aHex } from \"./context-budget-governor-v2.ts\";\nimport { scoreContextFileRelevance, scoreSkillRelevance } from \"./context-budget-relevance.ts\";\nimport type { ContextFile } from \"./resource-loader.ts\";\nimport type { Skill } from \"./skills.ts\";\n\ninterface SystemPromptBudgetItemInput {\n\treadonly contextFiles: readonly ContextFile[];\n\treadonly skills: readonly Skill[];\n\treadonly includeSkills: boolean;\n\treadonly options: {\n\t\treadonly activeSkillNames?: readonly string[];\n\t\treadonly includeSkillInventory?: boolean;\n\t\treadonly includeFullContextFiles?: boolean;\n\t\treadonly maxInactiveSkills?: number;\n\t\treadonly queryContext?: string;\n\t};\n}\n\nconst CONTEXT_EXCERPT_CHARS = 1200;\nconst MIN_EXCERPT_CHARS = 400;\nconst MAX_EXCERPT_CHARS = 3000;\nconst MAX_INACTIVE_SKILLS = 15;\nconst CONTEXT_FULL_BUDGET_RATIO = 0.5;\n\nexport function createSystemPromptBudgetItems(\n\tinput: SystemPromptBudgetItemInput,\n\tresourceBudget: number,\n): ContextBudgetItemV2[] {\n\tconst items: ContextBudgetItemV2[] = [];\n\tconst contextFullCount = input.options.includeFullContextFiles !== false ? input.contextFiles.length : 0;\n\tconst excerptChars = computeExcerptChars(resourceBudget, contextFullCount);\n\n\tfor (const contextFile of input.contextFiles) {\n\t\tconst queryScore = scoreContextFileRelevance(\n\t\t\t{ path: contextFile.path, content: contextFile.content, isGlobal: contextFile.isGlobal ?? false },\n\t\t\tinput.options.queryContext,\n\t\t);\n\t\tpushContextItems(items, contextFile, queryScore, excerptChars, input.options.includeFullContextFiles !== false);\n\t}\n\n\tconst visibleSkills = input.skills.filter((skill) => !skill.disableModelInvocation);\n\tif (input.includeSkills && input.options.includeSkillInventory !== false && visibleSkills.length > 0) {\n\t\tpushSkillItems(items, visibleSkills, input.options);\n\t}\n\treturn items;\n}\n\nfunction pushContextItems(\n\titems: ContextBudgetItemV2[],\n\tcontextFile: ContextFile,\n\tqueryScore: number,\n\texcerptChars: number,\n\tincludeFullContextFiles: boolean,\n): void {\n\tconst scope = contextFile.isGlobal ? \"parent\" : \"project\";\n\tconst tagName = contextFile.isGlobal ? \"parent_instructions\" : \"project_instructions\";\n\titems.push({\n\t\tid: `context-pointer:${contextFile.path}`,\n\t\ttier: contextFile.isGlobal ? \"system\" : \"current-files\",\n\t\tpriority: contextFile.isGlobal ? \"hard\" : \"high\",\n\t\trelevance: (contextFile.isGlobal ? 1 : 0.8) * 0.4 + queryScore * 0.6,\n\t\ttext: renderContextPointer(contextFile, scope),\n\t});\n\tif (!includeFullContextFiles) return;\n\titems.push({\n\t\tid: `context-full:${contextFile.path}`,\n\t\ttier: contextFile.isGlobal ? \"system\" : \"current-files\",\n\t\tpriority: contextFile.isGlobal ? \"high\" : \"medium\",\n\t\trelevance: (contextFile.isGlobal ? 0.9 : 0.6) * 0.4 + queryScore * 0.6,\n\t\tredundancyKey: contextFile.path,\n\t\tsourceRef: {\n\t\t\turi: `file://${contextFile.path}`,\n\t\t\tcontentHash: fnv1aHex(contextFile.content),\n\t\t\tretrievable: true,\n\t\t},\n\t\ttext: renderContextFull(contextFile, tagName, excerptChars),\n\t});\n}\n\nfunction pushSkillItems(\n\titems: ContextBudgetItemV2[],\n\tvisibleSkills: readonly Skill[],\n\toptions: SystemPromptBudgetItemInput[\"options\"],\n): void {\n\titems.push({ id: \"skill-header\", tier: \"skills\", priority: \"hard\", text: renderSkillHeader() });\n\tconst activeSkillNames = new Set(options.activeSkillNames ?? []);\n\tconst maxInactive = options.maxInactiveSkills ?? MAX_INACTIVE_SKILLS;\n\tfor (const skill of visibleSkills.filter((skill) => activeSkillNames.has(skill.name))) {\n\t\titems.push(renderSkillBudgetItem(skill, \"hard\", 1));\n\t}\n\n\tconst sortedInactive = visibleSkills\n\t\t.filter((skill) => !activeSkillNames.has(skill.name))\n\t\t.sort((a, b) => scoreSkillRelevance(b, options.queryContext) - scoreSkillRelevance(a, options.queryContext));\n\tfor (const skill of sortedInactive.slice(0, maxInactive)) {\n\t\titems.push(renderSkillBudgetItem(skill, \"low\", Math.max(0.25, scoreSkillRelevance(skill, options.queryContext))));\n\t}\n\titems.push({ id: \"skill-footer\", tier: \"skills\", priority: \"hard\", text: \"</available_skills>\" });\n\n\tconst omittedInactiveCount = sortedInactive.length - Math.min(sortedInactive.length, maxInactive);\n\tif (omittedInactiveCount > 0) {\n\t\titems.push({\n\t\t\tid: \"skill-omitted-summary\",\n\t\t\ttier: \"skills\",\n\t\t\tpriority: \"low\",\n\t\t\trelevance: 0.1,\n\t\t\ttext: `<!-- ${omittedInactiveCount} additional skills available. Use 'read' to load a specific skill file when a task matches. -->`,\n\t\t});\n\t}\n}\n\nfunction renderSkillBudgetItem(skill: Skill, priority: \"hard\" | \"low\", relevance: number): ContextBudgetItemV2 {\n\treturn {\n\t\tid: `skill:${skill.name}`,\n\t\ttier: \"skills\",\n\t\tpriority,\n\t\trelevance,\n\t\tredundancyKey: skill.name,\n\t\ttext: renderSkillEntry(skill),\n\t};\n}\n\nfunction computeExcerptChars(resourceBudget: number, contextFullCount: number): number {\n\tif (contextFullCount <= 0) {\n\t\treturn CONTEXT_EXCERPT_CHARS;\n\t}\n\tconst allocatedTokens = Math.floor(resourceBudget * CONTEXT_FULL_BUDGET_RATIO) / contextFullCount;\n\tconst estimatedChars = Math.floor(allocatedTokens * 4);\n\treturn Math.max(MIN_EXCERPT_CHARS, Math.min(MAX_EXCERPT_CHARS, estimatedChars));\n}\n\nfunction renderContextPointer(contextFile: ContextFile, scope: string): string {\n\tconst marker = contextFile.containsJailbreak ? \" sanitized=true\" : \"\";\n\treturn `<context_file_pointer scope=\"${escapeXml(scope)}\" path=\"${escapeXml(contextFile.path)}\"${marker} chars=\"${contextFile.content.length}\" />`;\n}\n\nfunction renderContextFull(contextFile: ContextFile, tagName: string, excerptChars = CONTEXT_EXCERPT_CHARS): string {\n\tconst content =\n\t\tcontextFile.content.length > excerptChars\n\t\t\t? boundedExcerpt(contextFile.content, excerptChars)\n\t\t\t: contextFile.content;\n\tconst truncated = content.length < contextFile.content.length ? \" truncated=true\" : \"\";\n\treturn `<${tagName} path=\"${escapeXml(contextFile.path)}\"${truncated}>\\n${content}\\n</${tagName}>`;\n}\n\nfunction boundedExcerpt(content: string, excerptChars = CONTEXT_EXCERPT_CHARS): string {\n\tconst headChars = Math.floor(excerptChars * 0.7);\n\tconst tailChars = excerptChars - headChars;\n\tlet head = content.slice(0, headChars);\n\tconst lastSpace = head.search(/\\s+\\S*$/);\n\tif (lastSpace > headChars * 0.5) {\n\t\thead = head.slice(0, lastSpace);\n\t}\n\tlet tail = content.slice(-tailChars);\n\tconst firstSpace = tail.search(/\\S+\\s+/);\n\tif (firstSpace > 0 && firstSpace < tailChars * 0.5) {\n\t\ttail = tail.slice(firstSpace).trimStart();\n\t}\n\treturn `${head}\\n\\n[...context-budget excerpt omitted ${content.length - excerptChars} chars...]\\n\\n${tail}`;\n}\n\nfunction renderSkillHeader(): string {\n\treturn [\n\t\t\"\\n\\nThe following skills provide specialized instructions for specific tasks.\",\n\t\t\"Use the read tool to load a skill's file when the task matches its description.\",\n\t\t\"When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\",\n\t\t\"\",\n\t\t\"<available_skills>\",\n\t].join(\"\\n\");\n}\n\nfunction renderSkillEntry(skill: Skill): string {\n\treturn [\n\t\t\" <skill>\",\n\t\t` <name>${escapeXml(skill.name)}</name>`,\n\t\t` <description>${escapeXml(skill.description)}</description>`,\n\t\t` <location>${escapeXml(skill.filePath)}</location>`,\n\t\t\" </skill>\",\n\t].join(\"\\n\");\n}\n\nexport function escapeXml(str: string): string {\n\treturn str\n\t\t.replace(/&/g, \"&amp;\")\n\t\t.replace(/</g, \"&lt;\")\n\t\t.replace(/>/g, \"&gt;\")\n\t\t.replace(/\"/g, \"&quot;\")\n\t\t.replace(/'/g, \"&apos;\");\n}\n"]}
1
+ {"version":3,"file":"context-budget-system-prompt-items.js","sourceRoot":"","sources":["../../src/core/context-budget-system-prompt-items.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAA4B,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AACrF,OAAO,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAiB/F,MAAM,qBAAqB,GAAG,IAAI,CAAC;AACnC,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAC9B,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAC/B,MAAM,mBAAmB,GAAG,EAAE,CAAC;AAC/B,MAAM,yBAAyB,GAAG,GAAG,CAAC;AAEtC,MAAM,UAAU,6BAA6B,CAC5C,KAAkC,EAClC,cAAsB,EACE;IACxB,MAAM,KAAK,GAA0B,EAAE,CAAC;IACxC,MAAM,gBAAgB,GAAG,KAAK,CAAC,OAAO,CAAC,uBAAuB,KAAK,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC;IACzG,MAAM,YAAY,GAAG,mBAAmB,CAAC,cAAc,EAAE,gBAAgB,CAAC,CAAC;IAE3E,KAAK,MAAM,WAAW,IAAI,KAAK,CAAC,YAAY,EAAE,CAAC;QAC9C,MAAM,UAAU,GAAG,yBAAyB,CAC3C,EAAE,IAAI,EAAE,WAAW,CAAC,IAAI,EAAE,OAAO,EAAE,WAAW,CAAC,OAAO,EAAE,QAAQ,EAAE,WAAW,CAAC,QAAQ,IAAI,KAAK,EAAE,EACjG,KAAK,CAAC,OAAO,CAAC,YAAY,CAC1B,CAAC;QACF,gBAAgB,CAAC,KAAK,EAAE,WAAW,EAAE,UAAU,EAAE,YAAY,EAAE,KAAK,CAAC,O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/E,iFAAiF;QACjF,8KAA8K;QAC9K,EAAE;QACF,oBAAoB;KACpB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACb;AAED,SAAS,gBAAgB,CAAC,KAAY,EAAU;IAC/C,OAAO;QACN,WAAW;QACX,aAAa,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,SAAS;QAC3C,oBAAoB,SAAS,CAAC,KAAK,CAAC,WAAW,CAAC,gBAAgB;QAChE,iBAAiB,SAAS,CAAC,KAAK,CAAC,QAAQ,CAAC,aAAa;QACvD,YAAY;KACZ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACb;AAED,MAAM,UAAU,aAAa,CAAC,GAAW,EAAU;IAClD,OAAO,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;AAAA,CAC9E;AAED,MAAM,UAAU,SAAS,CAAC,GAAW,EAAU;IAC9C,OAAO,aAAa,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;AAAA,CAC1E","sourcesContent":["import { pathToFileURL } from \"node:url\";\nimport { type ContextBudgetItemV2, fnv1aHex } from \"./context-budget-governor-v2.ts\";\nimport { scoreContextFileRelevance, scoreSkillRelevance } from \"./context-budget-relevance.ts\";\nimport type { ContextFile } from \"./resource-loader.ts\";\nimport type { Skill } from \"./skills.ts\";\n\ninterface SystemPromptBudgetItemInput {\n\treadonly contextFiles: readonly ContextFile[];\n\treadonly skills: readonly Skill[];\n\treadonly includeSkills: boolean;\n\treadonly options: {\n\t\treadonly activeSkillNames?: readonly string[];\n\t\treadonly includeSkillInventory?: boolean;\n\t\treadonly includeFullContextFiles?: boolean;\n\t\treadonly maxInactiveSkills?: number;\n\t\treadonly queryContext?: string;\n\t};\n}\n\nconst CONTEXT_EXCERPT_CHARS = 1200;\nconst MIN_EXCERPT_CHARS = 400;\nconst MAX_EXCERPT_CHARS = 3000;\nconst MAX_INACTIVE_SKILLS = 15;\nconst CONTEXT_FULL_BUDGET_RATIO = 0.5;\n\nexport function createSystemPromptBudgetItems(\n\tinput: SystemPromptBudgetItemInput,\n\tresourceBudget: number,\n): ContextBudgetItemV2[] {\n\tconst items: ContextBudgetItemV2[] = [];\n\tconst contextFullCount = input.options.includeFullContextFiles !== false ? input.contextFiles.length : 0;\n\tconst excerptChars = computeExcerptChars(resourceBudget, contextFullCount);\n\n\tfor (const contextFile of input.contextFiles) {\n\t\tconst queryScore = scoreContextFileRelevance(\n\t\t\t{ path: contextFile.path, content: contextFile.content, isGlobal: contextFile.isGlobal ?? false },\n\t\t\tinput.options.queryContext,\n\t\t);\n\t\tpushContextItems(items, contextFile, queryScore, excerptChars, input.options.includeFullContextFiles !== false);\n\t}\n\n\tconst visibleSkills = input.skills.filter((skill) => !skill.disableModelInvocation);\n\tif (input.includeSkills && input.options.includeSkillInventory !== false && visibleSkills.length > 0) {\n\t\tpushSkillItems(items, visibleSkills, input.options);\n\t}\n\treturn items;\n}\n\nfunction pushContextItems(\n\titems: ContextBudgetItemV2[],\n\tcontextFile: ContextFile,\n\tqueryScore: number,\n\texcerptChars: number,\n\tincludeFullContextFiles: boolean,\n): void {\n\tconst scope = contextFile.isGlobal ? \"parent\" : \"project\";\n\tconst tagName = contextFile.isGlobal ? \"parent_instructions\" : \"project_instructions\";\n\titems.push({\n\t\tid: `context-pointer:${contextFile.path}`,\n\t\ttier: contextFile.isGlobal ? \"system\" : \"current-files\",\n\t\tpriority: contextFile.isGlobal ? \"hard\" : \"high\",\n\t\trelevance: (contextFile.isGlobal ? 1 : 0.8) * 0.4 + queryScore * 0.6,\n\t\ttext: renderContextPointer(contextFile, scope),\n\t});\n\tif (!includeFullContextFiles) return;\n\titems.push({\n\t\tid: `context-full:${contextFile.path}`,\n\t\ttier: contextFile.isGlobal ? \"system\" : \"current-files\",\n\t\tpriority: contextFile.isGlobal ? \"high\" : \"medium\",\n\t\trelevance: (contextFile.isGlobal ? 0.9 : 0.6) * 0.4 + queryScore * 0.6,\n\t\tredundancyKey: contextFile.path,\n\t\tsourceRef: {\n\t\t\turi: pathToFileURL(contextFile.path).href,\n\t\t\tcontentHash: fnv1aHex(contextFile.content),\n\t\t\tretrievable: true,\n\t\t},\n\t\ttext: renderContextFull(contextFile, tagName, excerptChars),\n\t});\n}\n\nfunction pushSkillItems(\n\titems: ContextBudgetItemV2[],\n\tvisibleSkills: readonly Skill[],\n\toptions: SystemPromptBudgetItemInput[\"options\"],\n): void {\n\titems.push({ id: \"skill-header\", tier: \"skills\", priority: \"hard\", text: renderSkillHeader() });\n\tconst activeSkillNames = new Set(options.activeSkillNames ?? []);\n\tconst maxInactive = options.maxInactiveSkills ?? MAX_INACTIVE_SKILLS;\n\tfor (const skill of visibleSkills.filter((skill) => activeSkillNames.has(skill.name))) {\n\t\titems.push(renderSkillBudgetItem(skill, \"hard\", 1));\n\t}\n\n\tconst sortedInactive = visibleSkills\n\t\t.filter((skill) => !activeSkillNames.has(skill.name))\n\t\t.sort((a, b) => scoreSkillRelevance(b, options.queryContext) - scoreSkillRelevance(a, options.queryContext));\n\tfor (const skill of sortedInactive.slice(0, maxInactive)) {\n\t\titems.push(renderSkillBudgetItem(skill, \"low\", Math.max(0.25, scoreSkillRelevance(skill, options.queryContext))));\n\t}\n\titems.push({ id: \"skill-footer\", tier: \"skills\", priority: \"hard\", text: \"</available_skills>\" });\n\n\tconst omittedInactiveCount = sortedInactive.length - Math.min(sortedInactive.length, maxInactive);\n\tif (omittedInactiveCount > 0) {\n\t\titems.push({\n\t\t\tid: \"skill-omitted-summary\",\n\t\t\ttier: \"skills\",\n\t\t\tpriority: \"low\",\n\t\t\trelevance: 0.1,\n\t\t\ttext: `<!-- ${omittedInactiveCount} additional skills available. Use 'read' to load a specific skill file when a task matches. -->`,\n\t\t});\n\t}\n}\n\nfunction renderSkillBudgetItem(skill: Skill, priority: \"hard\" | \"low\", relevance: number): ContextBudgetItemV2 {\n\treturn {\n\t\tid: `skill:${skill.name}`,\n\t\ttier: \"skills\",\n\t\tpriority,\n\t\trelevance,\n\t\tredundancyKey: skill.name,\n\t\ttext: renderSkillEntry(skill),\n\t};\n}\n\nfunction computeExcerptChars(resourceBudget: number, contextFullCount: number): number {\n\tif (contextFullCount <= 0) {\n\t\treturn CONTEXT_EXCERPT_CHARS;\n\t}\n\tconst allocatedTokens = Math.floor(resourceBudget * CONTEXT_FULL_BUDGET_RATIO) / contextFullCount;\n\tconst estimatedChars = Math.floor(allocatedTokens * 4);\n\treturn Math.max(MIN_EXCERPT_CHARS, Math.min(MAX_EXCERPT_CHARS, estimatedChars));\n}\n\nfunction renderContextPointer(contextFile: ContextFile, scope: string): string {\n\tconst marker = contextFile.containsJailbreak ? \" sanitized=true\" : \"\";\n\treturn `<context_file_pointer scope=\"${escapeXml(scope)}\" path=\"${escapeXml(contextFile.path)}\"${marker} chars=\"${contextFile.content.length}\" />`;\n}\n\nfunction renderContextFull(contextFile: ContextFile, tagName: string, excerptChars = CONTEXT_EXCERPT_CHARS): string {\n\tconst content =\n\t\tcontextFile.content.length > excerptChars\n\t\t\t? boundedExcerpt(contextFile.content, excerptChars)\n\t\t\t: contextFile.content;\n\tconst truncated = content.length < contextFile.content.length ? \" truncated=true\" : \"\";\n\treturn `<${tagName} path=\"${escapeXml(contextFile.path)}\"${truncated}>\\n${escapeXmlText(content)}\\n</${tagName}>`;\n}\n\nfunction boundedExcerpt(content: string, excerptChars = CONTEXT_EXCERPT_CHARS): string {\n\tconst headChars = Math.floor(excerptChars * 0.7);\n\tconst tailChars = excerptChars - headChars;\n\tlet head = content.slice(0, headChars);\n\tconst lastSpace = head.search(/\\s+\\S*$/);\n\tif (lastSpace > headChars * 0.5) {\n\t\thead = head.slice(0, lastSpace);\n\t}\n\tlet tail = content.slice(-tailChars);\n\tconst firstSpace = tail.search(/\\S+\\s+/);\n\tif (firstSpace > 0 && firstSpace < tailChars * 0.5) {\n\t\ttail = tail.slice(firstSpace).trimStart();\n\t}\n\treturn `${head}\\n\\n[...context-budget excerpt omitted ${content.length - excerptChars} chars...]\\n\\n${tail}`;\n}\n\nfunction renderSkillHeader(): string {\n\treturn [\n\t\t\"\\n\\nThe following skills provide specialized instructions for specific tasks.\",\n\t\t\"Use the read tool to load a skill's file when the task matches its description.\",\n\t\t\"When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\",\n\t\t\"\",\n\t\t\"<available_skills>\",\n\t].join(\"\\n\");\n}\n\nfunction renderSkillEntry(skill: Skill): string {\n\treturn [\n\t\t\" <skill>\",\n\t\t` <name>${escapeXml(skill.name)}</name>`,\n\t\t` <description>${escapeXml(skill.description)}</description>`,\n\t\t` <location>${escapeXml(skill.filePath)}</location>`,\n\t\t\" </skill>\",\n\t].join(\"\\n\");\n}\n\nexport function escapeXmlText(str: string): string {\n\treturn str.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n}\n\nexport function escapeXml(str: string): string {\n\treturn escapeXmlText(str).replace(/\"/g, \"&quot;\").replace(/'/g, \"&apos;\");\n}\n"]}
@@ -69,6 +69,14 @@ export declare function evaluateCommandGate(command: string, opts: CommandGateOp
69
69
  /** @deprecated Back-compat alias; prefer {@link evaluateCommandGate}. */
70
70
  export declare const evaluateUserBash: typeof evaluateCommandGate;
71
71
  export declare function isCommandSafetyAssumeYesEnabled(env?: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>>): boolean;
72
+ /**
73
+ * Full disable of the command-safety gate (YOLO mode).
74
+ * Env (any one):
75
+ * OMK_YOLO=1|true
76
+ * OMK_COMMAND_SAFETY=0|false|off|disable
77
+ * OMK_DISABLE_COMMAND_SAFETY=1|true
78
+ */
79
+ export declare function isCommandSafetyDisabled(env?: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>>): boolean;
72
80
  /** Build a synthetic failed `BashResult` surfacing the safety reason. */
73
81
  export declare function buildBlockedBashResult(reason: string): BashResult;
74
82
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"command-safety-gate.d.ts","sourceRoot":"","sources":["../../../../src/core/extensions/builtin/command-safety-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAEzD,OAAO,EAAE,KAAK,YAAY,EAAuB,MAAM,aAAa,CAAC;AAErE,4EAA4E;AAC5E,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;AAE9D,8EAA8E;AAC9E,MAAM,WAAW,kBAAkB;IAClC,iEAAiE;IACjE,KAAK,EAAE,OAAO,CAAC;IACf,mEAAmE;IACnE,OAAO,CAAC,EAAE,SAAS,CAAC;IACpB,uFAAuF;IACvF,wBAAwB,CAAC,EAAE,KAAK,GAAG,OAAO,CAAC;IAC3C,kGAAkG;IAClG,qBAAqB,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC;IACzC,4FAA4F;IAC5F,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC;CACrB;AAED,oEAAoE;AACpE,MAAM,MAAM,uBAAuB,GAAG,kBAAkB,CAAC;AAiCzD;;;;;;;;GAQG;AACH,wBAAgB,oBAAoB,CACnC,OAAO,EAAE,MAAM,EACf,SAAS,CAAC,EAAE,MAAM,EAAE,GAClB;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAM7C;AAED;;;;;;GAMG;AACH,wBAAsB,mBAAmB,CACxC,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,kBAAkB,GACtB,OAAO,CAAC;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAAC,CA2BxD;AAED,yEAAyE;AACzE,eAAO,MAAM,gBAAgB,4BAAsB,CAAC;AAEpD,wBAAgB,+BAA+B,CAC9C,GAAG,GAAE,MAAM,CAAC,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,GACjF,OAAO,CAET;AASD,yEAAyE;AACzE,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,CAOjE;AAED;;;;GAIG;AACH,MAAM,CAAC,OAAO,UAAU,iBAAiB,CAAC,GAAG,EAAE,YAAY,GAAG,IAAI,CAyBjE","sourcesContent":["/**\n * Built-in command-safety gate extension.\n *\n * Wires the pure `classifyShellCommand` verdict engine into the live bash entry\n * points with one shared decision engine (`evaluateCommandGate`):\n * - LLM tool calls (`tool_call` for the `bash` tool) — block-tier verdicts stop\n * execution via `{ block, reason }`. confirm-tier verdicts prompt when a\n * dialog-capable UI is available and otherwise deny headlessly (parity with\n * user bash). `priv.*` is never auto-allowed.\n * - User `!`/`!!` bash (`user_bash`) — block/confirm verdicts produce a synthetic\n * FAILED `BashResult` instead of running the command.\n * - RPC bash routes through `AgentSession.executeBash({ safetyGate: \"headless\" })`\n * which reuses `evaluateCommandGate` and `buildBlockedBashResult` directly.\n *\n * Fail-closed contract:\n * - `user_bash` deny NEVER throws. A thrown `user_bash` handler is logged by the\n * runner and default execution continues (fail-open). Returning a synthetic\n * failed `result` short-circuits execution safely.\n * - `confirm`-tier verdicts deny by default when no interactive UI is available.\n * - `priv.*` verdicts are never headless-allowed.\n *\n * This gate reuses `command-safety.ts` read-only and adds no new classification\n * branches. `extraDeny` patterns can only promote allow/confirm to block; they\n * can never relax a block verdict.\n */\n\nimport type { BashResult } from \"../../bash-executor.ts\";\nimport { type CommandVerdict, classifyShellCommand } from \"../../command-safety.ts\";\nimport { type ExtensionAPI, isToolCallEventType } from \"../types.ts\";\n\n/** Confirmation callback. Returns true when the user approves execution. */\nexport type ConfirmFn = (message: string) => Promise<boolean>;\n\n/** Options controlling how a bash command is evaluated by the shared gate. */\nexport interface CommandGateOptions {\n\t/** Whether a dialog-capable UI is available for confirmation. */\n\thasUI: boolean;\n\t/** Interactive confirmation callback used when `hasUI` is true. */\n\tconfirm?: ConfirmFn;\n\t/** Interactive policy for non-privilege `confirm`-tier verdicts. Defaults to \"ask\". */\n\tinteractiveConfirmPolicy?: \"ask\" | \"allow\";\n\t/** Headless policy for `confirm`-tier verdicts. `priv.*` is never allowed. Defaults to \"deny\". */\n\theadlessConfirmPolicy?: \"deny\" | \"allow\";\n\t/** Extra substrings that promote allow/confirm verdicts to block. Never relaxes a block. */\n\textraDeny?: string[];\n}\n\n/** @deprecated Back-compat alias for {@link CommandGateOptions}. */\nexport type UserBashEvaluateOptions = CommandGateOptions;\n\nfunction formatReason(verdict: CommandVerdict): string {\n\treturn `[${verdict.rule}] ${verdict.reason}`;\n}\n\nfunction matchesExtraDeny(command: string, patterns: string[] | undefined): boolean {\n\tif (!patterns || patterns.length === 0) return false;\n\tfor (const pattern of patterns) {\n\t\tif (pattern.length > 0 && command.includes(pattern)) return true;\n\t}\n\treturn false;\n}\n\n/**\n * Classify a command, applying `extraDeny` promotion.\n *\n * `extraDeny` can only escalate allow/confirm to block; an existing block\n * verdict is returned unchanged.\n */\nfunction classifyWithExtraDeny(command: string, extraDeny?: string[]): CommandVerdict {\n\tconst verdict = classifyShellCommand(command);\n\tif (verdict.risk === \"block\") return verdict;\n\tif (matchesExtraDeny(command, extraDeny)) {\n\t\treturn {\n\t\t\trisk: \"block\",\n\t\t\trule: \"command.extra_deny\",\n\t\t\treason: \"Command matches a configured deny pattern.\",\n\t\t};\n\t}\n\treturn verdict;\n}\n\n/**\n * Pure block-only check for an LLM `bash` tool call.\n *\n * Only block-tier verdicts produce a block here; confirm/allow pass through.\n * Used as a low-level non-negotiable floor (for example by the bash tool's\n * effective-command check after commandPrefix/spawnHook) where no confirm UI\n * or policy context exists. The confirm-deny behavior for the live tool_call\n * gate lives in {@link evaluateCommandGate}.\n */\nexport function evaluateBashToolCall(\n\tcommand: string,\n\textraDeny?: string[],\n): { block: true; reason: string } | undefined {\n\tconst verdict = classifyWithExtraDeny(command, extraDeny);\n\tif (verdict.risk === \"block\") {\n\t\treturn { block: true, reason: formatReason(verdict) };\n\t}\n\treturn undefined;\n}\n\n/**\n * Shared gate decision for any bash command (LLM tool call, user bash, RPC bash).\n *\n * - block => deny.\n * - confirm => hasUI ? (approved ? undefined : deny) : (policy === \"allow\" && !priv ? undefined : deny).\n * - allow => undefined (preserve later extensions / default execution).\n */\nexport async function evaluateCommandGate(\n\tcommand: string,\n\topts: CommandGateOptions,\n): Promise<{ deny: boolean; reason: string } | undefined> {\n\tconst verdict = classifyWithExtraDeny(command, opts.extraDeny);\n\n\tif (verdict.risk === \"allow\") return undefined;\n\tif (verdict.risk === \"block\") {\n\t\treturn { deny: true, reason: formatReason(verdict) };\n\t}\n\n\t// confirm-tier verdict.\n\tconst isPrivilege = verdict.rule.startsWith(\"priv.\");\n\tif (opts.hasUI) {\n\t\tif (!isPrivilege && opts.interactiveConfirmPolicy === \"allow\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (opts.confirm) {\n\t\t\tconst approved = await opts.confirm(formatReason(verdict));\n\t\t\treturn approved ? undefined : { deny: true, reason: formatReason(verdict) };\n\t\t}\n\t\t// UI claimed but no confirm callback: cannot obtain consent => fail-closed.\n\t\treturn { deny: true, reason: formatReason(verdict) };\n\t}\n\n\t// Headless: privilege escalation is never auto-allowed.\n\tif (!isPrivilege && opts.headlessConfirmPolicy === \"allow\") {\n\t\treturn undefined;\n\t}\n\treturn { deny: true, reason: formatReason(verdict) };\n}\n\n/** @deprecated Back-compat alias; prefer {@link evaluateCommandGate}. */\nexport const evaluateUserBash = evaluateCommandGate;\n\nexport function isCommandSafetyAssumeYesEnabled(\n\tenv: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>> = process.env,\n): boolean {\n\treturn env.OMK_COMMAND_SAFETY_ASSUME_YES === \"1\" || env.OMK_COMMAND_SAFETY_ASSUME_YES === \"true\";\n}\n\nfunction getAssumeYesConfirmPolicies(): Pick<CommandGateOptions, \"interactiveConfirmPolicy\" | \"headlessConfirmPolicy\"> {\n\tif (!isCommandSafetyAssumeYesEnabled()) {\n\t\treturn { interactiveConfirmPolicy: \"ask\", headlessConfirmPolicy: \"deny\" };\n\t}\n\treturn { interactiveConfirmPolicy: \"allow\", headlessConfirmPolicy: \"allow\" };\n}\n\n/** Build a synthetic failed `BashResult` surfacing the safety reason. */\nexport function buildBlockedBashResult(reason: string): BashResult {\n\treturn {\n\t\toutput: `command-safety: blocked\\n${reason}`,\n\t\texitCode: 1,\n\t\tcancelled: false,\n\t\ttruncated: false,\n\t};\n}\n\n/**\n * Extension factory. Registered as the first extension so its handlers run\n * before any discovered extension (`tool_call` short-circuits on first block;\n * `user_bash` short-circuits on first truthy result).\n */\nexport default function commandSafetyGate(omk: ExtensionAPI): void {\n\tomk.on(\"tool_call\", async (event, ctx) => {\n\t\tif (!isToolCallEventType(\"bash\", event)) return undefined;\n\t\tconst decision = await evaluateCommandGate(event.input.command, {\n\t\t\thasUI: ctx.hasUI,\n\t\t\tconfirm: ctx.hasUI ? (message) => ctx.ui.confirm(\"Command safety\", message) : undefined,\n\t\t\t...getAssumeYesConfirmPolicies(),\n\t\t});\n\t\tif (decision?.deny) {\n\t\t\treturn { block: true, reason: decision.reason };\n\t\t}\n\t\treturn undefined;\n\t});\n\n\tomk.on(\"user_bash\", async (event, ctx) => {\n\t\tconst decision = await evaluateCommandGate(event.command, {\n\t\t\thasUI: ctx.hasUI,\n\t\t\tconfirm: ctx.hasUI ? (message) => ctx.ui.confirm(\"Command safety\", message) : undefined,\n\t\t\t...getAssumeYesConfirmPolicies(),\n\t\t});\n\t\tif (decision?.deny) {\n\t\t\treturn { result: buildBlockedBashResult(decision.reason) };\n\t\t}\n\t\treturn undefined;\n\t});\n}\n"]}
1
+ {"version":3,"file":"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,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,GACjF,OAAO,CAIT;AAED;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CACtC,GAAG,GAAE,MAAM,CAAC,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAe,GACjF,OAAO,CAOT;AASD,yEAAyE;AACzE,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,CAOjE;AAED;;;;GAIG;AACH,MAAM,CAAC,OAAO,UAAU,iBAAiB,CAAC,GAAG,EAAE,YAAY,GAAG,IAAI,CA4BjE","sourcesContent":["/**\n * Built-in command-safety gate extension.\n *\n * Wires the pure `classifyShellCommand` verdict engine into the live bash entry\n * points with one shared decision engine (`evaluateCommandGate`):\n * - LLM tool calls (`tool_call` for the `bash` tool) — block-tier verdicts stop\n * execution via `{ block, reason }`. confirm-tier verdicts prompt when a\n * dialog-capable UI is available and otherwise deny headlessly (parity with\n * user bash). `priv.*` is never auto-allowed.\n * - User `!`/`!!` bash (`user_bash`) — block/confirm verdicts produce a synthetic\n * FAILED `BashResult` instead of running the command.\n * - RPC bash routes through `AgentSession.executeBash({ safetyGate: \"headless\" })`\n * which reuses `evaluateCommandGate` and `buildBlockedBashResult` directly.\n *\n * Fail-closed contract:\n * - `user_bash` deny NEVER throws. A thrown `user_bash` handler is logged by the\n * runner and default execution continues (fail-open). Returning a synthetic\n * failed `result` short-circuits execution safely.\n * - `confirm`-tier verdicts deny by default when no interactive UI is available.\n * - `priv.*` verdicts are never headless-allowed.\n *\n * This gate reuses `command-safety.ts` read-only and adds no new classification\n * branches. `extraDeny` patterns can only promote allow/confirm to block; they\n * can never relax a block verdict.\n */\n\nimport type { BashResult } from \"../../bash-executor.ts\";\nimport { type CommandVerdict, classifyShellCommand } from \"../../command-safety.ts\";\nimport { type ExtensionAPI, isToolCallEventType } from \"../types.ts\";\n\n/** Confirmation callback. Returns true when the user approves execution. */\nexport type ConfirmFn = (message: string) => Promise<boolean>;\n\n/** Options controlling how a bash command is evaluated by the shared gate. */\nexport interface CommandGateOptions {\n\t/** Whether a dialog-capable UI is available for confirmation. */\n\thasUI: boolean;\n\t/** Interactive confirmation callback used when `hasUI` is true. */\n\tconfirm?: ConfirmFn;\n\t/** Interactive policy for non-privilege `confirm`-tier verdicts. Defaults to \"ask\". */\n\tinteractiveConfirmPolicy?: \"ask\" | \"allow\";\n\t/** Headless policy for `confirm`-tier verdicts. `priv.*` is never allowed. Defaults to \"deny\". */\n\theadlessConfirmPolicy?: \"deny\" | \"allow\";\n\t/** Extra substrings that promote allow/confirm verdicts to block. Never relaxes a block. */\n\textraDeny?: string[];\n}\n\n/** @deprecated Back-compat alias for {@link CommandGateOptions}. */\nexport type UserBashEvaluateOptions = CommandGateOptions;\n\nfunction formatReason(verdict: CommandVerdict): string {\n\treturn `[${verdict.rule}] ${verdict.reason}`;\n}\n\nfunction matchesExtraDeny(command: string, patterns: string[] | undefined): boolean {\n\tif (!patterns || patterns.length === 0) return false;\n\tfor (const pattern of patterns) {\n\t\tif (pattern.length > 0 && command.includes(pattern)) return true;\n\t}\n\treturn false;\n}\n\n/**\n * Classify a command, applying `extraDeny` promotion.\n *\n * `extraDeny` can only escalate allow/confirm to block; an existing block\n * verdict is returned unchanged.\n */\nfunction classifyWithExtraDeny(command: string, extraDeny?: string[]): CommandVerdict {\n\tconst verdict = classifyShellCommand(command);\n\tif (verdict.risk === \"block\") return verdict;\n\tif (matchesExtraDeny(command, extraDeny)) {\n\t\treturn {\n\t\t\trisk: \"block\",\n\t\t\trule: \"command.extra_deny\",\n\t\t\treason: \"Command matches a configured deny pattern.\",\n\t\t};\n\t}\n\treturn verdict;\n}\n\n/**\n * Pure block-only check for an LLM `bash` tool call.\n *\n * Only block-tier verdicts produce a block here; confirm/allow pass through.\n * Used as a low-level non-negotiable floor (for example by the bash tool's\n * effective-command check after commandPrefix/spawnHook) where no confirm UI\n * or policy context exists. The confirm-deny behavior for the live tool_call\n * gate lives in {@link evaluateCommandGate}.\n */\nexport function evaluateBashToolCall(\n\tcommand: string,\n\textraDeny?: string[],\n): { block: true; reason: string } | undefined {\n\tconst verdict = classifyWithExtraDeny(command, extraDeny);\n\tif (verdict.risk === \"block\") {\n\t\treturn { block: true, reason: formatReason(verdict) };\n\t}\n\treturn undefined;\n}\n\n/**\n * Shared gate decision for any bash command (LLM tool call, user bash, RPC bash).\n *\n * - block => deny.\n * - confirm => hasUI ? (approved ? undefined : deny) : (policy === \"allow\" && !priv ? undefined : deny).\n * - allow => undefined (preserve later extensions / default execution).\n */\nexport async function evaluateCommandGate(\n\tcommand: string,\n\topts: CommandGateOptions,\n): Promise<{ deny: boolean; reason: string } | undefined> {\n\tconst verdict = classifyWithExtraDeny(command, opts.extraDeny);\n\n\tif (verdict.risk === \"allow\") return undefined;\n\tif (verdict.risk === \"block\") {\n\t\treturn { deny: true, reason: formatReason(verdict) };\n\t}\n\n\t// confirm-tier verdict.\n\tconst isPrivilege = verdict.rule.startsWith(\"priv.\");\n\tif (opts.hasUI) {\n\t\tif (!isPrivilege && opts.interactiveConfirmPolicy === \"allow\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (opts.confirm) {\n\t\t\tconst approved = await opts.confirm(formatReason(verdict));\n\t\t\treturn approved ? undefined : { deny: true, reason: formatReason(verdict) };\n\t\t}\n\t\t// UI claimed but no confirm callback: cannot obtain consent => fail-closed.\n\t\treturn { deny: true, reason: formatReason(verdict) };\n\t}\n\n\t// Headless: privilege escalation is never auto-allowed.\n\tif (!isPrivilege && opts.headlessConfirmPolicy === \"allow\") {\n\t\treturn undefined;\n\t}\n\treturn { deny: true, reason: formatReason(verdict) };\n}\n\n/** @deprecated Back-compat alias; prefer {@link evaluateCommandGate}. */\nexport const evaluateUserBash = evaluateCommandGate;\n\nexport function isCommandSafetyAssumeYesEnabled(\n\tenv: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>> = process.env,\n): boolean {\n\t// YOLO implies assume-yes for any residual confirm-tier paths.\n\tif (isCommandSafetyDisabled(env)) return true;\n\treturn env.OMK_COMMAND_SAFETY_ASSUME_YES === \"1\" || env.OMK_COMMAND_SAFETY_ASSUME_YES === \"true\";\n}\n\n/**\n * Full disable of the command-safety gate (YOLO mode).\n * Env (any one):\n * OMK_YOLO=1|true\n * OMK_COMMAND_SAFETY=0|false|off|disable\n * OMK_DISABLE_COMMAND_SAFETY=1|true\n */\nexport function isCommandSafetyDisabled(\n\tenv: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>> = process.env,\n): boolean {\n\tconst yolo = env.OMK_YOLO;\n\tif (yolo === \"1\" || yolo === \"true\" || yolo === \"yes\" || yolo === \"on\") return true;\n\tconst cs = String(env.OMK_COMMAND_SAFETY ?? \"\").toLowerCase();\n\tif (cs === \"0\" || cs === \"false\" || cs === \"off\" || cs === \"disable\" || cs === \"disabled\") return true;\n\tconst d = env.OMK_DISABLE_COMMAND_SAFETY;\n\treturn d === \"1\" || d === \"true\" || d === \"yes\" || d === \"on\";\n}\n\nfunction getAssumeYesConfirmPolicies(): Pick<CommandGateOptions, \"interactiveConfirmPolicy\" | \"headlessConfirmPolicy\"> {\n\tif (!isCommandSafetyAssumeYesEnabled()) {\n\t\treturn { interactiveConfirmPolicy: \"ask\", headlessConfirmPolicy: \"deny\" };\n\t}\n\treturn { interactiveConfirmPolicy: \"allow\", headlessConfirmPolicy: \"allow\" };\n}\n\n/** Build a synthetic failed `BashResult` surfacing the safety reason. */\nexport function buildBlockedBashResult(reason: string): BashResult {\n\treturn {\n\t\toutput: `command-safety: blocked\\n${reason}`,\n\t\texitCode: 1,\n\t\tcancelled: false,\n\t\ttruncated: false,\n\t};\n}\n\n/**\n * Extension factory. Registered as the first extension so its handlers run\n * before any discovered extension (`tool_call` short-circuits on first block;\n * `user_bash` short-circuits on first truthy result).\n */\nexport default function commandSafetyGate(omk: ExtensionAPI): void {\n\t// YOLO / disabled: register no handlers — gate is a no-op extension.\n\tif (isCommandSafetyDisabled()) return;\n\n\tomk.on(\"tool_call\", async (event, ctx) => {\n\t\tif (!isToolCallEventType(\"bash\", event)) return undefined;\n\t\tconst decision = await evaluateCommandGate(event.input.command, {\n\t\t\thasUI: ctx.hasUI,\n\t\t\tconfirm: ctx.hasUI ? (message) => ctx.ui.confirm(\"Command safety\", message) : undefined,\n\t\t\t...getAssumeYesConfirmPolicies(),\n\t\t});\n\t\tif (decision?.deny) {\n\t\t\treturn { block: true, reason: decision.reason };\n\t\t}\n\t\treturn undefined;\n\t});\n\n\tomk.on(\"user_bash\", async (event, ctx) => {\n\t\tconst decision = await evaluateCommandGate(event.command, {\n\t\t\thasUI: ctx.hasUI,\n\t\t\tconfirm: ctx.hasUI ? (message) => ctx.ui.confirm(\"Command safety\", message) : undefined,\n\t\t\t...getAssumeYesConfirmPolicies(),\n\t\t});\n\t\tif (decision?.deny) {\n\t\t\treturn { result: buildBlockedBashResult(decision.reason) };\n\t\t}\n\t\treturn undefined;\n\t});\n}\n"]}
@@ -108,8 +108,28 @@ export async function evaluateCommandGate(command, opts) {
108
108
  /** @deprecated Back-compat alias; prefer {@link evaluateCommandGate}. */
109
109
  export const evaluateUserBash = evaluateCommandGate;
110
110
  export function isCommandSafetyAssumeYesEnabled(env = process.env) {
111
+ // YOLO implies assume-yes for any residual confirm-tier paths.
112
+ if (isCommandSafetyDisabled(env))
113
+ return true;
111
114
  return env.OMK_COMMAND_SAFETY_ASSUME_YES === "1" || env.OMK_COMMAND_SAFETY_ASSUME_YES === "true";
112
115
  }
116
+ /**
117
+ * Full disable of the command-safety gate (YOLO mode).
118
+ * Env (any one):
119
+ * OMK_YOLO=1|true
120
+ * OMK_COMMAND_SAFETY=0|false|off|disable
121
+ * OMK_DISABLE_COMMAND_SAFETY=1|true
122
+ */
123
+ export function isCommandSafetyDisabled(env = process.env) {
124
+ const yolo = env.OMK_YOLO;
125
+ if (yolo === "1" || yolo === "true" || yolo === "yes" || yolo === "on")
126
+ return true;
127
+ const cs = String(env.OMK_COMMAND_SAFETY ?? "").toLowerCase();
128
+ if (cs === "0" || cs === "false" || cs === "off" || cs === "disable" || cs === "disabled")
129
+ return true;
130
+ const d = env.OMK_DISABLE_COMMAND_SAFETY;
131
+ return d === "1" || d === "true" || d === "yes" || d === "on";
132
+ }
113
133
  function getAssumeYesConfirmPolicies() {
114
134
  if (!isCommandSafetyAssumeYesEnabled()) {
115
135
  return { interactiveConfirmPolicy: "ask", headlessConfirmPolicy: "deny" };
@@ -131,6 +151,9 @@ export function buildBlockedBashResult(reason) {
131
151
  * `user_bash` short-circuits on first truthy result).
132
152
  */
133
153
  export default function commandSafetyGate(omk) {
154
+ // YOLO / disabled: register no handlers — gate is a no-op extension.
155
+ if (isCommandSafetyDisabled())
156
+ return;
134
157
  omk.on("tool_call", async (event, ctx) => {
135
158
  if (!isToolCallEventType("bash", event))
136
159
  return undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"command-safety-gate.js","sourceRoot":"","sources":["../../../../src/core/extensions/builtin/command-safety-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAGH,OAAO,EAAuB,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACpF,OAAO,EAAqB,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAsBrE,SAAS,YAAY,CAAC,OAAuB,EAAU;IACtD,OAAO,IAAI,OAAO,CAAC,IAAI,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC;AAAA,CAC7C;AAED,SAAS,gBAAgB,CAAC,OAAe,EAAE,QAA8B,EAAW;IACnF,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACrD,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAChC,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC;YAAE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AK,EAAE,GAAG,CAAC,KAAK;YAChB,OAAO,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,OAAO,CAAC,gBAAgB,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS;YACvF,GAAG,2BAA2B,EAAE;SAChC,CAAC,CAAC;QACH,IAAI,QAAQ,EAAE,IAAI,EAAE,CAAC;YACpB,OAAO,EAAE,MAAM,EAAE,sBAAsB,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QAC5D,CAAC;QACD,OAAO,SAAS,CAAC;IAAA,CACjB,CAAC,CAAC;AAAA,CACH","sourcesContent":["/**\n * Built-in command-safety gate extension.\n *\n * Wires the pure `classifyShellCommand` verdict engine into the live bash entry\n * points with one shared decision engine (`evaluateCommandGate`):\n * - LLM tool calls (`tool_call` for the `bash` tool) — block-tier verdicts stop\n * execution via `{ block, reason }`. confirm-tier verdicts prompt when a\n * dialog-capable UI is available and otherwise deny headlessly (parity with\n * user bash). `priv.*` is never auto-allowed.\n * - User `!`/`!!` bash (`user_bash`) — block/confirm verdicts produce a synthetic\n * FAILED `BashResult` instead of running the command.\n * - RPC bash routes through `AgentSession.executeBash({ safetyGate: \"headless\" })`\n * which reuses `evaluateCommandGate` and `buildBlockedBashResult` directly.\n *\n * Fail-closed contract:\n * - `user_bash` deny NEVER throws. A thrown `user_bash` handler is logged by the\n * runner and default execution continues (fail-open). Returning a synthetic\n * failed `result` short-circuits execution safely.\n * - `confirm`-tier verdicts deny by default when no interactive UI is available.\n * - `priv.*` verdicts are never headless-allowed.\n *\n * This gate reuses `command-safety.ts` read-only and adds no new classification\n * branches. `extraDeny` patterns can only promote allow/confirm to block; they\n * can never relax a block verdict.\n */\n\nimport type { BashResult } from \"../../bash-executor.ts\";\nimport { type CommandVerdict, classifyShellCommand } from \"../../command-safety.ts\";\nimport { type ExtensionAPI, isToolCallEventType } from \"../types.ts\";\n\n/** Confirmation callback. Returns true when the user approves execution. */\nexport type ConfirmFn = (message: string) => Promise<boolean>;\n\n/** Options controlling how a bash command is evaluated by the shared gate. */\nexport interface CommandGateOptions {\n\t/** Whether a dialog-capable UI is available for confirmation. */\n\thasUI: boolean;\n\t/** Interactive confirmation callback used when `hasUI` is true. */\n\tconfirm?: ConfirmFn;\n\t/** Interactive policy for non-privilege `confirm`-tier verdicts. Defaults to \"ask\". */\n\tinteractiveConfirmPolicy?: \"ask\" | \"allow\";\n\t/** Headless policy for `confirm`-tier verdicts. `priv.*` is never allowed. Defaults to \"deny\". */\n\theadlessConfirmPolicy?: \"deny\" | \"allow\";\n\t/** Extra substrings that promote allow/confirm verdicts to block. Never relaxes a block. */\n\textraDeny?: string[];\n}\n\n/** @deprecated Back-compat alias for {@link CommandGateOptions}. */\nexport type UserBashEvaluateOptions = CommandGateOptions;\n\nfunction formatReason(verdict: CommandVerdict): string {\n\treturn `[${verdict.rule}] ${verdict.reason}`;\n}\n\nfunction matchesExtraDeny(command: string, patterns: string[] | undefined): boolean {\n\tif (!patterns || patterns.length === 0) return false;\n\tfor (const pattern of patterns) {\n\t\tif (pattern.length > 0 && command.includes(pattern)) return true;\n\t}\n\treturn false;\n}\n\n/**\n * Classify a command, applying `extraDeny` promotion.\n *\n * `extraDeny` can only escalate allow/confirm to block; an existing block\n * verdict is returned unchanged.\n */\nfunction classifyWithExtraDeny(command: string, extraDeny?: string[]): CommandVerdict {\n\tconst verdict = classifyShellCommand(command);\n\tif (verdict.risk === \"block\") return verdict;\n\tif (matchesExtraDeny(command, extraDeny)) {\n\t\treturn {\n\t\t\trisk: \"block\",\n\t\t\trule: \"command.extra_deny\",\n\t\t\treason: \"Command matches a configured deny pattern.\",\n\t\t};\n\t}\n\treturn verdict;\n}\n\n/**\n * Pure block-only check for an LLM `bash` tool call.\n *\n * Only block-tier verdicts produce a block here; confirm/allow pass through.\n * Used as a low-level non-negotiable floor (for example by the bash tool's\n * effective-command check after commandPrefix/spawnHook) where no confirm UI\n * or policy context exists. The confirm-deny behavior for the live tool_call\n * gate lives in {@link evaluateCommandGate}.\n */\nexport function evaluateBashToolCall(\n\tcommand: string,\n\textraDeny?: string[],\n): { block: true; reason: string } | undefined {\n\tconst verdict = classifyWithExtraDeny(command, extraDeny);\n\tif (verdict.risk === \"block\") {\n\t\treturn { block: true, reason: formatReason(verdict) };\n\t}\n\treturn undefined;\n}\n\n/**\n * Shared gate decision for any bash command (LLM tool call, user bash, RPC bash).\n *\n * - block => deny.\n * - confirm => hasUI ? (approved ? undefined : deny) : (policy === \"allow\" && !priv ? undefined : deny).\n * - allow => undefined (preserve later extensions / default execution).\n */\nexport async function evaluateCommandGate(\n\tcommand: string,\n\topts: CommandGateOptions,\n): Promise<{ deny: boolean; reason: string } | undefined> {\n\tconst verdict = classifyWithExtraDeny(command, opts.extraDeny);\n\n\tif (verdict.risk === \"allow\") return undefined;\n\tif (verdict.risk === \"block\") {\n\t\treturn { deny: true, reason: formatReason(verdict) };\n\t}\n\n\t// confirm-tier verdict.\n\tconst isPrivilege = verdict.rule.startsWith(\"priv.\");\n\tif (opts.hasUI) {\n\t\tif (!isPrivilege && opts.interactiveConfirmPolicy === \"allow\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (opts.confirm) {\n\t\t\tconst approved = await opts.confirm(formatReason(verdict));\n\t\t\treturn approved ? undefined : { deny: true, reason: formatReason(verdict) };\n\t\t}\n\t\t// UI claimed but no confirm callback: cannot obtain consent => fail-closed.\n\t\treturn { deny: true, reason: formatReason(verdict) };\n\t}\n\n\t// Headless: privilege escalation is never auto-allowed.\n\tif (!isPrivilege && opts.headlessConfirmPolicy === \"allow\") {\n\t\treturn undefined;\n\t}\n\treturn { deny: true, reason: formatReason(verdict) };\n}\n\n/** @deprecated Back-compat alias; prefer {@link evaluateCommandGate}. */\nexport const evaluateUserBash = evaluateCommandGate;\n\nexport function isCommandSafetyAssumeYesEnabled(\n\tenv: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>> = process.env,\n): boolean {\n\treturn env.OMK_COMMAND_SAFETY_ASSUME_YES === \"1\" || env.OMK_COMMAND_SAFETY_ASSUME_YES === \"true\";\n}\n\nfunction getAssumeYesConfirmPolicies(): Pick<CommandGateOptions, \"interactiveConfirmPolicy\" | \"headlessConfirmPolicy\"> {\n\tif (!isCommandSafetyAssumeYesEnabled()) {\n\t\treturn { interactiveConfirmPolicy: \"ask\", headlessConfirmPolicy: \"deny\" };\n\t}\n\treturn { interactiveConfirmPolicy: \"allow\", headlessConfirmPolicy: \"allow\" };\n}\n\n/** Build a synthetic failed `BashResult` surfacing the safety reason. */\nexport function buildBlockedBashResult(reason: string): BashResult {\n\treturn {\n\t\toutput: `command-safety: blocked\\n${reason}`,\n\t\texitCode: 1,\n\t\tcancelled: false,\n\t\ttruncated: false,\n\t};\n}\n\n/**\n * Extension factory. Registered as the first extension so its handlers run\n * before any discovered extension (`tool_call` short-circuits on first block;\n * `user_bash` short-circuits on first truthy result).\n */\nexport default function commandSafetyGate(omk: ExtensionAPI): void {\n\tomk.on(\"tool_call\", async (event, ctx) => {\n\t\tif (!isToolCallEventType(\"bash\", event)) return undefined;\n\t\tconst decision = await evaluateCommandGate(event.input.command, {\n\t\t\thasUI: ctx.hasUI,\n\t\t\tconfirm: ctx.hasUI ? (message) => ctx.ui.confirm(\"Command safety\", message) : undefined,\n\t\t\t...getAssumeYesConfirmPolicies(),\n\t\t});\n\t\tif (decision?.deny) {\n\t\t\treturn { block: true, reason: decision.reason };\n\t\t}\n\t\treturn undefined;\n\t});\n\n\tomk.on(\"user_bash\", async (event, ctx) => {\n\t\tconst decision = await evaluateCommandGate(event.command, {\n\t\t\thasUI: ctx.hasUI,\n\t\t\tconfirm: ctx.hasUI ? (message) => ctx.ui.confirm(\"Command safety\", message) : undefined,\n\t\t\t...getAssumeYesConfirmPolicies(),\n\t\t});\n\t\tif (decision?.deny) {\n\t\t\treturn { result: buildBlockedBashResult(decision.reason) };\n\t\t}\n\t\treturn undefined;\n\t});\n}\n"]}
1
+ {"version":3,"file":"command-safety-gate.js","sourceRoot":"","sources":["../../../../src/core/extensions/builtin/command-safety-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AAGH,OAAO,EAAuB,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AACpF,OAAO,EAAqB,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAsBrE,SAAS,YAAY,CAAC,OAAuB,EAAU;IACtD,OAAO,IAAI,OAAO,CAAC,IAAI,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC;AAAA,CAC7C;AAED,SAAS,gBAAgB,CAAC,OAAe,EAAE,QAA8B,EAAW;IACnF,IAAI,CAAC,QAAQ,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACrD,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAChC,IAAI,OAAO,CAAC,MAAM,GAAG,CAAC,IAAI,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC;YAAE,OAAO,IAAI,CAAC;IAClE,CAAC;IACD,OAAO,KAAK,CAAC;AAAA,CACb;AAED;;;;;GAKG;AACH,SAAS,qBAAqB,CAAC,OAAe,EAAE,SAAoB,EAAkB;IACrF,MAAM,OAAO,GAAG,oBAAoB,CAAC,OAAO,CAAC,CAAC;IAC9C,IAAI,OAAO,CAAC,IAAI,KAAK,OAAO;QAAE,OAAO,OAAO,CAAC;IAC7C,IAAI,gBAAgB,CAAC,OAAO,EAAE,SAAS,CAAC,EAAE,CAAC;QAC1C,OAAO;YACN,IAAI,EAAE,OAAO;YACb,IAAI,EAAE,oBAAoB;YAC1B,MAAM,EAAE,4CAA4C;SACpD,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AAAA,CACf;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,oBAAoB,CACnC,OAAe,EACf,SAAoB,EAC0B;IAC9C,MAAM,OAAO,GAAG,qBAA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MAAM,EAAE,CAAC;QACjD,CAAC;QACD,OAAO,SAAS,CAAC;IAAA,CACjB,CAAC,CAAC;IAEH,GAAG,CAAC,EAAE,CAAC,WAAW,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,EAAE,CAAC;QACzC,MAAM,QAAQ,GAAG,MAAM,mBAAmB,CAAC,KAAK,CAAC,OAAO,EAAE;YACzD,KAAK,EAAE,GAAG,CAAC,KAAK;YAChB,OAAO,EAAE,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,OAAO,CAAC,gBAAgB,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS;YACvF,GAAG,2BAA2B,EAAE;SAChC,CAAC,CAAC;QACH,IAAI,QAAQ,EAAE,IAAI,EAAE,CAAC;YACpB,OAAO,EAAE,MAAM,EAAE,sBAAsB,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;QAC5D,CAAC;QACD,OAAO,SAAS,CAAC;IAAA,CACjB,CAAC,CAAC;AAAA,CACH","sourcesContent":["/**\n * Built-in command-safety gate extension.\n *\n * Wires the pure `classifyShellCommand` verdict engine into the live bash entry\n * points with one shared decision engine (`evaluateCommandGate`):\n * - LLM tool calls (`tool_call` for the `bash` tool) — block-tier verdicts stop\n * execution via `{ block, reason }`. confirm-tier verdicts prompt when a\n * dialog-capable UI is available and otherwise deny headlessly (parity with\n * user bash). `priv.*` is never auto-allowed.\n * - User `!`/`!!` bash (`user_bash`) — block/confirm verdicts produce a synthetic\n * FAILED `BashResult` instead of running the command.\n * - RPC bash routes through `AgentSession.executeBash({ safetyGate: \"headless\" })`\n * which reuses `evaluateCommandGate` and `buildBlockedBashResult` directly.\n *\n * Fail-closed contract:\n * - `user_bash` deny NEVER throws. A thrown `user_bash` handler is logged by the\n * runner and default execution continues (fail-open). Returning a synthetic\n * failed `result` short-circuits execution safely.\n * - `confirm`-tier verdicts deny by default when no interactive UI is available.\n * - `priv.*` verdicts are never headless-allowed.\n *\n * This gate reuses `command-safety.ts` read-only and adds no new classification\n * branches. `extraDeny` patterns can only promote allow/confirm to block; they\n * can never relax a block verdict.\n */\n\nimport type { BashResult } from \"../../bash-executor.ts\";\nimport { type CommandVerdict, classifyShellCommand } from \"../../command-safety.ts\";\nimport { type ExtensionAPI, isToolCallEventType } from \"../types.ts\";\n\n/** Confirmation callback. Returns true when the user approves execution. */\nexport type ConfirmFn = (message: string) => Promise<boolean>;\n\n/** Options controlling how a bash command is evaluated by the shared gate. */\nexport interface CommandGateOptions {\n\t/** Whether a dialog-capable UI is available for confirmation. */\n\thasUI: boolean;\n\t/** Interactive confirmation callback used when `hasUI` is true. */\n\tconfirm?: ConfirmFn;\n\t/** Interactive policy for non-privilege `confirm`-tier verdicts. Defaults to \"ask\". */\n\tinteractiveConfirmPolicy?: \"ask\" | \"allow\";\n\t/** Headless policy for `confirm`-tier verdicts. `priv.*` is never allowed. Defaults to \"deny\". */\n\theadlessConfirmPolicy?: \"deny\" | \"allow\";\n\t/** Extra substrings that promote allow/confirm verdicts to block. Never relaxes a block. */\n\textraDeny?: string[];\n}\n\n/** @deprecated Back-compat alias for {@link CommandGateOptions}. */\nexport type UserBashEvaluateOptions = CommandGateOptions;\n\nfunction formatReason(verdict: CommandVerdict): string {\n\treturn `[${verdict.rule}] ${verdict.reason}`;\n}\n\nfunction matchesExtraDeny(command: string, patterns: string[] | undefined): boolean {\n\tif (!patterns || patterns.length === 0) return false;\n\tfor (const pattern of patterns) {\n\t\tif (pattern.length > 0 && command.includes(pattern)) return true;\n\t}\n\treturn false;\n}\n\n/**\n * Classify a command, applying `extraDeny` promotion.\n *\n * `extraDeny` can only escalate allow/confirm to block; an existing block\n * verdict is returned unchanged.\n */\nfunction classifyWithExtraDeny(command: string, extraDeny?: string[]): CommandVerdict {\n\tconst verdict = classifyShellCommand(command);\n\tif (verdict.risk === \"block\") return verdict;\n\tif (matchesExtraDeny(command, extraDeny)) {\n\t\treturn {\n\t\t\trisk: \"block\",\n\t\t\trule: \"command.extra_deny\",\n\t\t\treason: \"Command matches a configured deny pattern.\",\n\t\t};\n\t}\n\treturn verdict;\n}\n\n/**\n * Pure block-only check for an LLM `bash` tool call.\n *\n * Only block-tier verdicts produce a block here; confirm/allow pass through.\n * Used as a low-level non-negotiable floor (for example by the bash tool's\n * effective-command check after commandPrefix/spawnHook) where no confirm UI\n * or policy context exists. The confirm-deny behavior for the live tool_call\n * gate lives in {@link evaluateCommandGate}.\n */\nexport function evaluateBashToolCall(\n\tcommand: string,\n\textraDeny?: string[],\n): { block: true; reason: string } | undefined {\n\tconst verdict = classifyWithExtraDeny(command, extraDeny);\n\tif (verdict.risk === \"block\") {\n\t\treturn { block: true, reason: formatReason(verdict) };\n\t}\n\treturn undefined;\n}\n\n/**\n * Shared gate decision for any bash command (LLM tool call, user bash, RPC bash).\n *\n * - block => deny.\n * - confirm => hasUI ? (approved ? undefined : deny) : (policy === \"allow\" && !priv ? undefined : deny).\n * - allow => undefined (preserve later extensions / default execution).\n */\nexport async function evaluateCommandGate(\n\tcommand: string,\n\topts: CommandGateOptions,\n): Promise<{ deny: boolean; reason: string } | undefined> {\n\tconst verdict = classifyWithExtraDeny(command, opts.extraDeny);\n\n\tif (verdict.risk === \"allow\") return undefined;\n\tif (verdict.risk === \"block\") {\n\t\treturn { deny: true, reason: formatReason(verdict) };\n\t}\n\n\t// confirm-tier verdict.\n\tconst isPrivilege = verdict.rule.startsWith(\"priv.\");\n\tif (opts.hasUI) {\n\t\tif (!isPrivilege && opts.interactiveConfirmPolicy === \"allow\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (opts.confirm) {\n\t\t\tconst approved = await opts.confirm(formatReason(verdict));\n\t\t\treturn approved ? undefined : { deny: true, reason: formatReason(verdict) };\n\t\t}\n\t\t// UI claimed but no confirm callback: cannot obtain consent => fail-closed.\n\t\treturn { deny: true, reason: formatReason(verdict) };\n\t}\n\n\t// Headless: privilege escalation is never auto-allowed.\n\tif (!isPrivilege && opts.headlessConfirmPolicy === \"allow\") {\n\t\treturn undefined;\n\t}\n\treturn { deny: true, reason: formatReason(verdict) };\n}\n\n/** @deprecated Back-compat alias; prefer {@link evaluateCommandGate}. */\nexport const evaluateUserBash = evaluateCommandGate;\n\nexport function isCommandSafetyAssumeYesEnabled(\n\tenv: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>> = process.env,\n): boolean {\n\t// YOLO implies assume-yes for any residual confirm-tier paths.\n\tif (isCommandSafetyDisabled(env)) return true;\n\treturn env.OMK_COMMAND_SAFETY_ASSUME_YES === \"1\" || env.OMK_COMMAND_SAFETY_ASSUME_YES === \"true\";\n}\n\n/**\n * Full disable of the command-safety gate (YOLO mode).\n * Env (any one):\n * OMK_YOLO=1|true\n * OMK_COMMAND_SAFETY=0|false|off|disable\n * OMK_DISABLE_COMMAND_SAFETY=1|true\n */\nexport function isCommandSafetyDisabled(\n\tenv: NodeJS.ProcessEnv | Readonly<Record<string, string | undefined>> = process.env,\n): boolean {\n\tconst yolo = env.OMK_YOLO;\n\tif (yolo === \"1\" || yolo === \"true\" || yolo === \"yes\" || yolo === \"on\") return true;\n\tconst cs = String(env.OMK_COMMAND_SAFETY ?? \"\").toLowerCase();\n\tif (cs === \"0\" || cs === \"false\" || cs === \"off\" || cs === \"disable\" || cs === \"disabled\") return true;\n\tconst d = env.OMK_DISABLE_COMMAND_SAFETY;\n\treturn d === \"1\" || d === \"true\" || d === \"yes\" || d === \"on\";\n}\n\nfunction getAssumeYesConfirmPolicies(): Pick<CommandGateOptions, \"interactiveConfirmPolicy\" | \"headlessConfirmPolicy\"> {\n\tif (!isCommandSafetyAssumeYesEnabled()) {\n\t\treturn { interactiveConfirmPolicy: \"ask\", headlessConfirmPolicy: \"deny\" };\n\t}\n\treturn { interactiveConfirmPolicy: \"allow\", headlessConfirmPolicy: \"allow\" };\n}\n\n/** Build a synthetic failed `BashResult` surfacing the safety reason. */\nexport function buildBlockedBashResult(reason: string): BashResult {\n\treturn {\n\t\toutput: `command-safety: blocked\\n${reason}`,\n\t\texitCode: 1,\n\t\tcancelled: false,\n\t\ttruncated: false,\n\t};\n}\n\n/**\n * Extension factory. Registered as the first extension so its handlers run\n * before any discovered extension (`tool_call` short-circuits on first block;\n * `user_bash` short-circuits on first truthy result).\n */\nexport default function commandSafetyGate(omk: ExtensionAPI): void {\n\t// YOLO / disabled: register no handlers — gate is a no-op extension.\n\tif (isCommandSafetyDisabled()) return;\n\n\tomk.on(\"tool_call\", async (event, ctx) => {\n\t\tif (!isToolCallEventType(\"bash\", event)) return undefined;\n\t\tconst decision = await evaluateCommandGate(event.input.command, {\n\t\t\thasUI: ctx.hasUI,\n\t\t\tconfirm: ctx.hasUI ? (message) => ctx.ui.confirm(\"Command safety\", message) : undefined,\n\t\t\t...getAssumeYesConfirmPolicies(),\n\t\t});\n\t\tif (decision?.deny) {\n\t\t\treturn { block: true, reason: decision.reason };\n\t\t}\n\t\treturn undefined;\n\t});\n\n\tomk.on(\"user_bash\", async (event, ctx) => {\n\t\tconst decision = await evaluateCommandGate(event.command, {\n\t\t\thasUI: ctx.hasUI,\n\t\t\tconfirm: ctx.hasUI ? (message) => ctx.ui.confirm(\"Command safety\", message) : undefined,\n\t\t\t...getAssumeYesConfirmPolicies(),\n\t\t});\n\t\tif (decision?.deny) {\n\t\t\treturn { result: buildBlockedBashResult(decision.reason) };\n\t\t}\n\t\treturn undefined;\n\t});\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/runner.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,KAAK,EAAE,YAAY,EAAS,MAAM,QAAQ,CAAC;AAClD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AA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AmB,GAAG,SAAS,CAAC,CA2BjF;IAEK,WAAW,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC,CA8BnE;IAEK,yBAAyB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAgClE;IAEK,oBAAoB,CACzB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,YAAY,EAAE,GAAG,SAAS,EAClC,YAAY,EAAE,MAAM,EACpB,mBAAmB,EAAE,wBAAwB,GAC3C,OAAO,CAAC,8BAA8B,GAAG,SAAS,CAAC,CA2DrD;IAEK,qBAAqB,CAC1B,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,sBAAsB,CAAC,QAAQ,CAAC,GACtC,OAAO,CAAC;QACV,UAAU,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,aAAa,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;QAC3D,WAAW,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,aAAa,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;QAC5D,UAAU,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,aAAa,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;KAC3D,CAAC,CAuCD;IAED,oEAAoE;IAC9D,SAAS,CACd,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,YAAY,EAAE,GAAG,SAAS,EAClC,MAAM,EAAE,WAAW,EACnB,iBAAiB,CAAC,EAAE,OAAO,GAAG,UAAU,GACtC,OAAO,CAAC,gBAAgB,CAAC,CAkC3B;CACD","sourcesContent":["/**\n * Extension runner - executes extensions and manages their lifecycle.\n */\n\nimport type { AgentMessage } from \"omk-agent-core\";\nimport type { ImageContent, Model } from \"omk-ai\";\nimport type { KeyId } from \"omk-tui\";\nimport { type Theme, theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ResourceDiagnostic } from \"../diagnostics.ts\";\nimport type { KeybindingsConfig } from \"../keybindings.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type { SessionManager } from \"../session-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type {\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tBeforeProviderRequestEvent,\n\tCompactOptions,\n\tContextEvent,\n\tContextEventResult,\n\tContextUsage,\n\tExtension,\n\tExtensionActions,\n\tExtensionCommandContext,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionContextActions,\n\tExtensionError,\n\tExtensionEvent,\n\tExtensionFlag,\n\tExtensionMode,\n\tExtensionRuntime,\n\tExtensionShortcut,\n\tExtensionUIContext,\n\tInputEvent,\n\tInputEventResult,\n\tInputSource,\n\tMessageEndEvent,\n\tMessageEndEventResult,\n\tMessageRenderer,\n\tProviderConfig,\n\tRegisteredCommand,\n\tRegisteredTool,\n\tReplacedSessionContext,\n\tResolvedCommand,\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeResult,\n\tSessionShutdownEvent,\n\tToolCallEvent,\n\tToolCallEventResult,\n\tToolResultEvent,\n\tToolResultEventResult,\n\tUserBashEvent,\n\tUserBashEventResult,\n} from \"./types.ts\";\n\n// Extension shortcuts compete with canonical keybinding ids from keybindings.json.\n// Only editor-global shortcuts are reserved here. Picker-specific bindings are not.\nconst RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS = [\n\t\"app.interrupt\",\n\t\"app.clear\",\n\t\"app.exit\",\n\t\"app.suspend\",\n\t\"app.thinking.cycle\",\n\t\"app.model.cycleForward\",\n\t\"app.model.cycleBackward\",\n\t\"app.model.select\",\n\t\"app.tools.expand\",\n\t\"app.thinking.toggle\",\n\t\"app.editor.external\",\n\t\"app.message.followUp\",\n\t\"tui.input.submit\",\n\t\"tui.select.confirm\",\n\t\"tui.select.cancel\",\n\t\"tui.input.copy\",\n\t\"tui.editor.deleteToLineEnd\",\n] as const;\n\ntype BuiltInKeyBindings = Partial<Record<KeyId, { keybinding: string; restrictOverride: boolean }>>;\n\nconst buildBuiltinKeybindings = (resolvedKeybindings: KeybindingsConfig): BuiltInKeyBindings => {\n\tconst builtinKeybindings = {} as BuiltInKeyBindings;\n\tfor (const [keybinding, keys] of Object.entries(resolvedKeybindings)) {\n\t\tif (keys === undefined) continue;\n\t\tconst keyList = Array.isArray(keys) ? keys : [keys];\n\t\tconst restrictOverride = (RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS as readonly string[]).includes(keybinding);\n\t\tfor (const key of keyList) {\n\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\t\t\t// If multiple actions bind the same key, the reserved action wins so extensions\n\t\t\t// remain blocked by reserved shortcuts regardless of iteration order.\n\t\t\tconst existing = builtinKeybindings[normalizedKey];\n\t\t\tif (existing?.restrictOverride && !restrictOverride) continue;\n\t\t\tbuiltinKeybindings[normalizedKey] = {\n\t\t\t\tkeybinding,\n\t\t\t\trestrictOverride,\n\t\t\t};\n\t\t}\n\t}\n\treturn builtinKeybindings;\n};\n\n/** Combined result from all before_agent_start handlers */\ninterface BeforeAgentStartCombinedResult {\n\tmessages?: NonNullable<BeforeAgentStartEventResult[\"message\"]>[];\n\tsystemPrompt?: string;\n}\n\n/**\n * Events handled by the generic emit() method.\n * Events with dedicated emitXxx() methods are excluded for stronger type safety.\n */\ntype RunnerEmitEvent = Exclude<\n\tExtensionEvent,\n\t| ToolCallEvent\n\t| ToolResultEvent\n\t| UserBashEvent\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeAgentStartEvent\n\t| MessageEndEvent\n\t| ResourcesDiscoverEvent\n\t| InputEvent\n>;\n\ntype SessionBeforeEvent = Extract<\n\tRunnerEmitEvent,\n\t{ type: \"session_before_switch\" | \"session_before_fork\" | \"session_before_compact\" | \"session_before_tree\" }\n>;\n\ntype SessionBeforeEventResult =\n\t| SessionBeforeSwitchResult\n\t| SessionBeforeForkResult\n\t| SessionBeforeCompactResult\n\t| SessionBeforeTreeResult;\n\ntype RunnerEmitResult<TEvent extends RunnerEmitEvent> = TEvent extends { type: \"session_before_switch\" }\n\t? SessionBeforeSwitchResult | undefined\n\t: TEvent extends { type: \"session_before_fork\" }\n\t\t? SessionBeforeForkResult | undefined\n\t\t: TEvent extends { type: \"session_before_compact\" }\n\t\t\t? SessionBeforeCompactResult | undefined\n\t\t\t: TEvent extends { type: \"session_before_tree\" }\n\t\t\t\t? SessionBeforeTreeResult | undefined\n\t\t\t\t: undefined;\n\nexport type ExtensionErrorListener = (error: ExtensionError) => void;\n\nexport type NewSessionHandler = (options?: {\n\tparentSession?: string;\n\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n}) => Promise<{ cancelled: boolean }>;\n\nexport type ForkHandler = (\n\tentryId: string,\n\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n) => Promise<{ cancelled: boolean }>;\n\nexport type NavigateTreeHandler = (\n\ttargetId: string,\n\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n) => Promise<{ cancelled: boolean }>;\n\nexport type SwitchSessionHandler = (\n\tsessionPath: string,\n\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n) => Promise<{ cancelled: boolean }>;\n\nexport type ReloadHandler = () => Promise<void>;\n\nexport type ShutdownHandler = () => void;\n\n/**\n * Helper function to emit session_shutdown event to extensions.\n * Returns true if the event was emitted, false if there were no handlers.\n */\nexport async function emitSessionShutdownEvent(\n\textensionRunner: ExtensionRunner,\n\tevent: SessionShutdownEvent,\n): Promise<boolean> {\n\tif (extensionRunner.hasHandlers(\"session_shutdown\")) {\n\t\tawait extensionRunner.emit(event);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nconst noOpUIContext: ExtensionUIContext = {\n\tselect: async () => undefined,\n\tconfirm: async () => false,\n\tinput: async () => undefined,\n\tnotify: () => {},\n\tonTerminalInput: () => () => {},\n\tsetStatus: () => {},\n\tsetWorkingMessage: () => {},\n\tsetWorkingVisible: () => {},\n\tsetWorkingIndicator: () => {},\n\tsetHiddenThinkingLabel: () => {},\n\tsetWidget: () => {},\n\tsetFooter: () => {},\n\tsetHeader: () => {},\n\tsetTitle: () => {},\n\tcustom: async () => undefined as never,\n\tpasteToEditor: () => {},\n\tsetEditorText: () => {},\n\tgetEditorText: () => \"\",\n\teditor: async () => undefined,\n\taddAutocompleteProvider: () => {},\n\tsetEditorComponent: () => {},\n\tgetEditorComponent: () => undefined,\n\tget theme() {\n\t\treturn theme;\n\t},\n\tgetAllThemes: () => [],\n\tgetTheme: () => undefined,\n\tsetTheme: (_theme: string | Theme) => ({ success: false, error: \"UI not available\" }),\n\tgetToolsExpanded: () => false,\n\tsetToolsExpanded: () => {},\n};\n\nexport class ExtensionRunner {\n\tprivate extensions: Extension[];\n\tprivate runtime: ExtensionRuntime;\n\tprivate uiContext: ExtensionUIContext;\n\tprivate mode: ExtensionMode = \"print\";\n\tprivate cwd: string;\n\tprivate sessionManager: SessionManager;\n\tprivate modelRegistry: ModelRegistry;\n\tprivate errorListeners: Set<ExtensionErrorListener> = new Set();\n\tprivate getModel: () => Model<any> | undefined = () => undefined;\n\tprivate isIdleFn: () => boolean = () => true;\n\tprivate getSignalFn: () => AbortSignal | undefined = () => undefined;\n\tprivate waitForIdleFn: () => Promise<void> = async () => {};\n\tprivate abortFn: () => void = () => {};\n\tprivate hasPendingMessagesFn: () => boolean = () => false;\n\tprivate getContextUsageFn: () => ContextUsage | undefined = () => undefined;\n\tprivate compactFn: (options?: CompactOptions) => void = () => {};\n\tprivate getSystemPromptFn: () => string = () => \"\";\n\tprivate getSystemPromptOptionsFn: () => BuildSystemPromptOptions = () => ({ cwd: this.cwd });\n\tprivate newSessionHandler: NewSessionHandler = async () => ({ cancelled: false });\n\tprivate forkHandler: ForkHandler = async () => ({ cancelled: false });\n\tprivate navigateTreeHandler: NavigateTreeHandler = async () => ({ cancelled: false });\n\tprivate switchSessionHandler: SwitchSessionHandler = async () => ({ cancelled: false });\n\tprivate reloadHandler: ReloadHandler = async () => {};\n\tprivate shutdownHandler: ShutdownHandler = () => {};\n\tprivate shortcutDiagnostics: ResourceDiagnostic[] = [];\n\tprivate commandDiagnostics: ResourceDiagnostic[] = [];\n\tprivate staleMessage: string | undefined;\n\n\tconstructor(\n\t\textensions: Extension[],\n\t\truntime: ExtensionRuntime,\n\t\tcwd: string,\n\t\tsessionManager: SessionManager,\n\t\tmodelRegistry: ModelRegistry,\n\t) {\n\t\tthis.extensions = extensions;\n\t\tthis.runtime = runtime;\n\t\tthis.uiContext = noOpUIContext;\n\t\tthis.cwd = cwd;\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.modelRegistry = modelRegistry;\n\t}\n\n\tbindCore(\n\t\tactions: ExtensionActions,\n\t\tcontextActions: ExtensionContextActions,\n\t\tproviderActions?: {\n\t\t\tregisterProvider?: (name: string, config: ProviderConfig) => void;\n\t\t\tunregisterProvider?: (name: string) => void;\n\t\t},\n\t): void {\n\t\t// Copy actions into the shared runtime (all extension APIs reference this)\n\t\tthis.runtime.sendMessage = actions.sendMessage;\n\t\tthis.runtime.sendUserMessage = actions.sendUserMessage;\n\t\tthis.runtime.appendEntry = actions.appendEntry;\n\t\tthis.runtime.setSessionName = actions.setSessionName;\n\t\tthis.runtime.getSessionName = actions.getSessionName;\n\t\tthis.runtime.setLabel = actions.setLabel;\n\t\tthis.runtime.getActiveTools = actions.getActiveTools;\n\t\tthis.runtime.getAllTools = actions.getAllTools;\n\t\tthis.runtime.setActiveTools = actions.setActiveTools;\n\t\tthis.runtime.refreshTools = actions.refreshTools;\n\t\tthis.runtime.getCommands = actions.getCommands;\n\t\tthis.runtime.setModel = actions.setModel;\n\t\tthis.runtime.getThinkingLevel = actions.getThinkingLevel;\n\t\tthis.runtime.setThinkingLevel = actions.setThinkingLevel;\n\t\t// Optional MCP tool bridge for extensions (correctness-wall live OA, etc.).\n\t\t// When undefined, ExtensionAPI.callMcpTool still exists but throws until a handler is bound.\n\t\tthis.runtime.callMcpTool = actions.callMcpTool;\n\n\t\t// Context actions (required)\n\t\tthis.getModel = contextActions.getModel;\n\t\tthis.isIdleFn = contextActions.isIdle;\n\t\tthis.getSignalFn = contextActions.getSignal;\n\t\tthis.abortFn = contextActions.abort;\n\t\tthis.hasPendingMessagesFn = contextActions.hasPendingMessages;\n\t\tthis.shutdownHandler = contextActions.shutdown;\n\t\tthis.getContextUsageFn = contextActions.getContextUsage;\n\t\tthis.compactFn = contextActions.compact;\n\t\tthis.getSystemPromptFn = contextActions.getSystemPrompt;\n\t\tthis.getSystemPromptOptionsFn = contextActions.getSystemPromptOptions ?? (() => ({ cwd: this.cwd }));\n\n\t\t// Flush provider registrations queued during extension loading\n\t\tfor (const { name, config, extensionPath } of this.runtime.pendingProviderRegistrations) {\n\t\t\ttry {\n\t\t\t\tif (providerActions?.registerProvider) {\n\t\t\t\t\tproviderActions.registerProvider(name, config);\n\t\t\t\t} else {\n\t\t\t\t\tthis.modelRegistry.registerProvider(name, config);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthis.emitError({\n\t\t\t\t\textensionPath,\n\t\t\t\t\tevent: \"register_provider\",\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthis.runtime.pendingProviderRegistrations = [];\n\n\t\t// From this point on, provider registration/unregistration takes effect immediately\n\t\t// without requiring a /reload.\n\t\tthis.runtime.registerProvider = (name, config) => {\n\t\t\tif (providerActions?.registerProvider) {\n\t\t\t\tproviderActions.registerProvider(name, config);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.modelRegistry.registerProvider(name, config);\n\t\t};\n\t\tthis.runtime.unregisterProvider = (name) => {\n\t\t\tif (providerActions?.unregisterProvider) {\n\t\t\t\tproviderActions.unregisterProvider(name);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.modelRegistry.unregisterProvider(name);\n\t\t};\n\t}\n\n\tbindCommandContext(actions?: ExtensionCommandContextActions): void {\n\t\tif (actions) {\n\t\t\tthis.waitForIdleFn = actions.waitForIdle;\n\t\t\tthis.newSessionHandler = actions.newSession;\n\t\t\tthis.forkHandler = actions.fork;\n\t\t\tthis.navigateTreeHandler = actions.navigateTree;\n\t\t\tthis.switchSessionHandler = actions.switchSession;\n\t\t\tthis.reloadHandler = actions.reload;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.waitForIdleFn = async () => {};\n\t\tthis.newSessionHandler = async () => ({ cancelled: false });\n\t\tthis.forkHandler = async () => ({ cancelled: false });\n\t\tthis.navigateTreeHandler = async () => ({ cancelled: false });\n\t\tthis.switchSessionHandler = async () => ({ cancelled: false });\n\t\tthis.reloadHandler = async () => {};\n\t}\n\n\tsetUIContext(uiContext?: ExtensionUIContext, mode: ExtensionMode = \"print\"): void {\n\t\tthis.uiContext = uiContext ?? noOpUIContext;\n\t\tthis.mode = mode;\n\t}\n\n\tgetUIContext(): ExtensionUIContext {\n\t\treturn this.uiContext;\n\t}\n\n\thasUI(): boolean {\n\t\treturn this.uiContext !== noOpUIContext;\n\t}\n\n\tgetExtensionPaths(): string[] {\n\t\treturn this.extensions.map((e) => e.path);\n\t}\n\n\t/** Get all registered tools from all extensions (first registration per name wins). */\n\tgetAllRegisteredTools(): RegisteredTool[] {\n\t\tconst toolsByName = new Map<string, RegisteredTool>();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const tool of ext.tools.values()) {\n\t\t\t\tif (!toolsByName.has(tool.definition.name)) {\n\t\t\t\t\ttoolsByName.set(tool.definition.name, tool);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn Array.from(toolsByName.values());\n\t}\n\n\t/** Get a tool definition by name. Returns undefined if not found. */\n\tgetToolDefinition(toolName: string): RegisteredTool[\"definition\"] | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst tool = ext.tools.get(toolName);\n\t\t\tif (tool) {\n\t\t\t\treturn tool.definition;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tgetFlags(): Map<string, ExtensionFlag> {\n\t\tconst allFlags = new Map<string, ExtensionFlag>();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [name, flag] of ext.flags) {\n\t\t\t\tif (!allFlags.has(name)) {\n\t\t\t\t\tallFlags.set(name, flag);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn allFlags;\n\t}\n\n\tsetFlagValue(name: string, value: boolean | string): void {\n\t\tthis.runtime.flagValues.set(name, value);\n\t}\n\n\tgetFlagValues(): Map<string, boolean | string> {\n\t\treturn new Map(this.runtime.flagValues);\n\t}\n\n\tgetShortcuts(resolvedKeybindings: KeybindingsConfig): Map<KeyId, ExtensionShortcut> {\n\t\tthis.shortcutDiagnostics = [];\n\t\tconst builtinKeybindings = buildBuiltinKeybindings(resolvedKeybindings);\n\t\tconst extensionShortcuts = new Map<KeyId, ExtensionShortcut>();\n\n\t\tconst addDiagnostic = (message: string, extensionPath: string) => {\n\t\t\tthis.shortcutDiagnostics.push({ type: \"warning\", message, path: extensionPath });\n\t\t\tif (!this.hasUI()) {\n\t\t\t\tconsole.warn(message);\n\t\t\t}\n\t\t};\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [key, shortcut] of ext.shortcuts) {\n\t\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\n\t\t\t\tconst builtInKeybinding = builtinKeybindings[normalizedKey];\n\t\t\t\tif (builtInKeybinding?.restrictOverride === true) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut '${key}' from ${shortcut.extensionPath} conflicts with built-in shortcut. Skipping.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (builtInKeybinding?.restrictOverride === false) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' is built-in shortcut for ${builtInKeybinding.keybinding} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst existingExtensionShortcut = extensionShortcuts.get(normalizedKey);\n\t\t\t\tif (existingExtensionShortcut) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' registered by both ${existingExtensionShortcut.extensionPath} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\textensionShortcuts.set(normalizedKey, shortcut);\n\t\t\t}\n\t\t}\n\t\treturn extensionShortcuts;\n\t}\n\n\tgetShortcutDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.shortcutDiagnostics;\n\t}\n\n\tinvalidate(\n\t\tmessage = \"This extension ctx is stale after session replacement or reload. Do not use a captured extension API or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\",\n\t): void {\n\t\tif (!this.staleMessage) {\n\t\t\tthis.staleMessage = message;\n\t\t\tthis.runtime.invalidate(message);\n\t\t}\n\t}\n\n\tprivate assertActive(): void {\n\t\tif (this.staleMessage) {\n\t\t\tthrow new Error(this.staleMessage);\n\t\t}\n\t}\n\n\tonError(listener: ExtensionErrorListener): () => void {\n\t\tthis.errorListeners.add(listener);\n\t\treturn () => this.errorListeners.delete(listener);\n\t}\n\n\temitError(error: ExtensionError): void {\n\t\tfor (const listener of this.errorListeners) {\n\t\t\tlistener(error);\n\t\t}\n\t}\n\n\thasHandlers(eventType: string): boolean {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(eventType);\n\t\t\tif (handlers && handlers.length > 0) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tgetMessageRenderer(customType: string): MessageRenderer | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst renderer = ext.messageRenderers.get(customType);\n\t\t\tif (renderer) {\n\t\t\t\treturn renderer;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate resolveRegisteredCommands(): ResolvedCommand[] {\n\t\tconst commands: RegisteredCommand[] = [];\n\t\tconst counts = new Map<string, number>();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const command of ext.commands.values()) {\n\t\t\t\tcommands.push(command);\n\t\t\t\tcounts.set(command.name, (counts.get(command.name) ?? 0) + 1);\n\t\t\t}\n\t\t}\n\n\t\tconst seen = new Map<string, number>();\n\t\tconst takenInvocationNames = new Set<string>();\n\n\t\treturn commands.map((command) => {\n\t\t\tconst occurrence = (seen.get(command.name) ?? 0) + 1;\n\t\t\tseen.set(command.name, occurrence);\n\n\t\t\tlet invocationName = (counts.get(command.name) ?? 0) > 1 ? `${command.name}:${occurrence}` : command.name;\n\n\t\t\tif (takenInvocationNames.has(invocationName)) {\n\t\t\t\tlet suffix = occurrence;\n\t\t\t\tdo {\n\t\t\t\t\tsuffix++;\n\t\t\t\t\tinvocationName = `${command.name}:${suffix}`;\n\t\t\t\t} while (takenInvocationNames.has(invocationName));\n\t\t\t}\n\n\t\t\ttakenInvocationNames.add(invocationName);\n\t\t\treturn {\n\t\t\t\t...command,\n\t\t\t\tinvocationName,\n\t\t\t};\n\t\t});\n\t}\n\n\tgetRegisteredCommands(): ResolvedCommand[] {\n\t\tthis.commandDiagnostics = [];\n\t\treturn this.resolveRegisteredCommands();\n\t}\n\n\tgetCommandDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.commandDiagnostics;\n\t}\n\n\tgetCommand(name: string): ResolvedCommand | undefined {\n\t\treturn this.resolveRegisteredCommands().find((command) => command.invocationName === name);\n\t}\n\n\t/**\n\t * Request a graceful shutdown. Called by extension tools and event handlers.\n\t * The actual shutdown behavior is provided by the mode via bindExtensions().\n\t */\n\tshutdown(): void {\n\t\tthis.shutdownHandler();\n\t}\n\n\t/**\n\t * Create an ExtensionContext for use in event handlers and tool execution.\n\t * Context values are resolved at call time, so changes via bindCore/bindUI are reflected.\n\t */\n\tcreateContext(): ExtensionContext {\n\t\tconst runner = this;\n\t\tconst getModel = this.getModel;\n\t\treturn {\n\t\t\tget ui() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.uiContext;\n\t\t\t},\n\t\t\tget mode() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.mode;\n\t\t\t},\n\t\t\tget hasUI() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.hasUI();\n\t\t\t},\n\t\t\tget cwd() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.cwd;\n\t\t\t},\n\t\t\tget sessionManager() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.sessionManager;\n\t\t\t},\n\t\t\tget modelRegistry() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.modelRegistry;\n\t\t\t},\n\t\t\tget model() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn getModel();\n\t\t\t},\n\t\t\tisIdle: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.isIdleFn();\n\t\t\t},\n\t\t\tget signal() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getSignalFn();\n\t\t\t},\n\t\t\tabort: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.abortFn();\n\t\t\t},\n\t\t\thasPendingMessages: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.hasPendingMessagesFn();\n\t\t\t},\n\t\t\tshutdown: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.shutdownHandler();\n\t\t\t},\n\t\t\tgetContextUsage: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getContextUsageFn();\n\t\t\t},\n\t\t\tcompact: (options) => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.compactFn(options);\n\t\t\t},\n\t\t\tgetSystemPrompt: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getSystemPromptFn();\n\t\t\t},\n\t\t};\n\t}\n\n\tcreateCommandContext(): ExtensionCommandContext {\n\t\t// Use property descriptors instead of object spread so the guarded getters from\n\t\t// createContext() stay lazy. A spread would eagerly read them once and freeze the\n\t\t// old values into the returned object, bypassing stale-instance checks.\n\t\tconst context = Object.defineProperties(\n\t\t\t{},\n\t\t\tObject.getOwnPropertyDescriptors(this.createContext()),\n\t\t) as ExtensionCommandContext;\n\t\tcontext.getSystemPromptOptions = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.getSystemPromptOptionsFn();\n\t\t};\n\t\tcontext.waitForIdle = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.waitForIdleFn();\n\t\t};\n\t\tcontext.newSession = (options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.newSessionHandler(options);\n\t\t};\n\t\tcontext.fork = (entryId, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.forkHandler(entryId, options);\n\t\t};\n\t\tcontext.navigateTree = (targetId, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.navigateTreeHandler(targetId, options);\n\t\t};\n\t\tcontext.switchSession = (sessionPath, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.switchSessionHandler(sessionPath, options);\n\t\t};\n\t\tcontext.reload = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.reloadHandler();\n\t\t};\n\t\treturn context;\n\t}\n\n\tprivate isSessionBeforeEvent(event: RunnerEmitEvent): event is SessionBeforeEvent {\n\t\treturn (\n\t\t\tevent.type === \"session_before_switch\" ||\n\t\t\tevent.type === \"session_before_fork\" ||\n\t\t\tevent.type === \"session_before_compact\" ||\n\t\t\tevent.type === \"session_before_tree\"\n\t\t);\n\t}\n\n\tasync emit<TEvent extends RunnerEmitEvent>(event: TEvent): Promise<RunnerEmitResult<TEvent>> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: SessionBeforeEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(event.type);\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (this.isSessionBeforeEvent(event) && handlerResult) {\n\t\t\t\t\t\tresult = handlerResult as SessionBeforeEventResult;\n\t\t\t\t\t\tif (result.cancel) {\n\t\t\t\t\t\t\treturn result as RunnerEmitResult<TEvent>;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: event.type,\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result as RunnerEmitResult<TEvent>;\n\t}\n\n\tasync emitMessageEnd(event: MessageEndEvent): Promise<AgentMessage | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessage = event.message;\n\t\tlet modified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"message_end\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst currentEvent: MessageEndEvent = { ...event, message: currentMessage };\n\t\t\t\t\tconst handlerResult = (await handler(currentEvent, ctx)) as MessageEndEventResult | undefined;\n\t\t\t\t\tif (!handlerResult?.message) continue;\n\n\t\t\t\t\tif (handlerResult.message.role !== currentMessage.role) {\n\t\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\t\tevent: \"message_end\",\n\t\t\t\t\t\t\terror: \"message_end handlers must return a message with the same role\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentMessage = handlerResult.message;\n\t\t\t\t\tmodified = true;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"message_end\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn modified ? currentMessage : undefined;\n\t}\n\n\tasync emitToolResult(event: ToolResultEvent): Promise<ToolResultEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tconst currentEvent: ToolResultEvent = { ...event };\n\t\tlet modified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_result\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = (await handler(currentEvent, ctx)) as ToolResultEventResult | undefined;\n\t\t\t\t\tif (!handlerResult) continue;\n\n\t\t\t\t\tif (handlerResult.content !== undefined) {\n\t\t\t\t\t\tcurrentEvent.content = handlerResult.content;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.details !== undefined) {\n\t\t\t\t\t\tcurrentEvent.details = handlerResult.details;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.isError !== undefined) {\n\t\t\t\t\t\tcurrentEvent.isError = handlerResult.isError;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"tool_result\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!modified) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: currentEvent.content,\n\t\t\tdetails: currentEvent.details,\n\t\t\tisError: currentEvent.isError,\n\t\t};\n\t}\n\n\tasync emitToolCall(event: ToolCallEvent): Promise<ToolCallEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: ToolCallEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_call\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\tif (handlerResult) {\n\t\t\t\t\tresult = handlerResult as ToolCallEventResult;\n\t\t\t\t\tif (result.block) {\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tasync emitUserBash(event: UserBashEvent): Promise<UserBashEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"user_bash\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\treturn handlerResult as UserBashEventResult;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"user_bash\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitContext(messages: AgentMessage[]): Promise<AgentMessage[]> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessages = structuredClone(messages);\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"context\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ContextEvent = { type: \"context\", messages: currentMessages };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult && (handlerResult as ContextEventResult).messages) {\n\t\t\t\t\t\tcurrentMessages = (handlerResult as ContextEventResult).messages!;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"context\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn currentMessages;\n\t}\n\n\tasync emitBeforeProviderRequest(payload: unknown): Promise<unknown> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentPayload = payload;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_provider_request\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: BeforeProviderRequestEvent = {\n\t\t\t\t\t\ttype: \"before_provider_request\",\n\t\t\t\t\t\tpayload: currentPayload,\n\t\t\t\t\t};\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tif (handlerResult !== undefined) {\n\t\t\t\t\t\tcurrentPayload = handlerResult;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_provider_request\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn currentPayload;\n\t}\n\n\tasync emitBeforeAgentStart(\n\t\tprompt: string,\n\t\timages: ImageContent[] | undefined,\n\t\tsystemPrompt: string,\n\t\tsystemPromptOptions: BuildSystemPromptOptions,\n\t): Promise<BeforeAgentStartCombinedResult | undefined> {\n\t\tlet currentSystemPrompt = systemPrompt;\n\t\tconst ctx = Object.defineProperties(\n\t\t\t{},\n\t\t\tObject.getOwnPropertyDescriptors(this.createContext()),\n\t\t) as ExtensionContext;\n\t\tctx.getSystemPrompt = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn currentSystemPrompt;\n\t\t};\n\t\tconst messages: NonNullable<BeforeAgentStartEventResult[\"message\"]>[] = [];\n\t\tlet systemPromptModified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_agent_start\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: BeforeAgentStartEvent = {\n\t\t\t\t\t\ttype: \"before_agent_start\",\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\timages,\n\t\t\t\t\t\tsystemPrompt: currentSystemPrompt,\n\t\t\t\t\t\tsystemPromptOptions,\n\t\t\t\t\t};\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\tconst result = handlerResult as BeforeAgentStartEventResult;\n\t\t\t\t\t\tif (result.message) {\n\t\t\t\t\t\t\tmessages.push(result.message);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.systemPrompt !== undefined) {\n\t\t\t\t\t\t\tcurrentSystemPrompt = result.systemPrompt;\n\t\t\t\t\t\t\tsystemPromptModified = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_agent_start\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (messages.length > 0 || systemPromptModified) {\n\t\t\treturn {\n\t\t\t\tmessages: messages.length > 0 ? messages : undefined,\n\t\t\t\tsystemPrompt: systemPromptModified ? currentSystemPrompt : undefined,\n\t\t\t};\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitResourcesDiscover(\n\t\tcwd: string,\n\t\treason: ResourcesDiscoverEvent[\"reason\"],\n\t): Promise<{\n\t\tskillPaths: Array<{ path: string; extensionPath: string }>;\n\t\tpromptPaths: Array<{ path: string; extensionPath: string }>;\n\t\tthemePaths: Array<{ path: string; extensionPath: string }>;\n\t}> {\n\t\tconst ctx = this.createContext();\n\t\tconst skillPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst promptPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst themePaths: Array<{ path: string; extensionPath: string }> = [];\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"resources_discover\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ResourcesDiscoverEvent = { type: \"resources_discover\", cwd, reason };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tconst result = handlerResult as ResourcesDiscoverResult | undefined;\n\n\t\t\t\t\tif (result?.skillPaths?.length) {\n\t\t\t\t\t\tskillPaths.push(...result.skillPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.promptPaths?.length) {\n\t\t\t\t\t\tpromptPaths.push(...result.promptPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.themePaths?.length) {\n\t\t\t\t\t\tthemePaths.push(...result.themePaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"resources_discover\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { skillPaths, promptPaths, themePaths };\n\t}\n\n\t/** Emit input event. Transforms chain, \"handled\" short-circuits. */\n\tasync emitInput(\n\t\ttext: string,\n\t\timages: ImageContent[] | undefined,\n\t\tsource: InputSource,\n\t\tstreamingBehavior?: \"steer\" | \"followUp\",\n\t): Promise<InputEventResult> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentText = text;\n\t\tlet currentImages = images;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const handler of ext.handlers.get(\"input\") ?? []) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: InputEvent = {\n\t\t\t\t\t\ttype: \"input\",\n\t\t\t\t\t\ttext: currentText,\n\t\t\t\t\t\timages: currentImages,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tstreamingBehavior,\n\t\t\t\t\t};\n\t\t\t\t\tconst result = (await handler(event, ctx)) as InputEventResult | undefined;\n\t\t\t\t\tif (result?.action === \"handled\") return result;\n\t\t\t\t\tif (result?.action === \"transform\") {\n\t\t\t\t\t\tcurrentText = result.text;\n\t\t\t\t\t\tcurrentImages = result.images ?? currentImages;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"input\",\n\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn currentText !== text || currentImages !== images\n\t\t\t? { action: \"transform\", text: currentText, images: currentImages }\n\t\t\t: { action: \"continue\" };\n\t}\n}\n"]}
1
+ {"version":3,"file":"runner.d.ts","sourceRoot":"","sources":["../../../src/core/extensions/runner.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACnD,OAAO,KAAK,EAAE,YAAY,EAAS,MAAM,QAAQ,CAAC;AAClD,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,KAAK,EAA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,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAgClE;IAEK,oBAAoB,CACzB,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,YAAY,EAAE,GAAG,SAAS,EAClC,YAAY,EAAE,MAAM,EACpB,mBAAmB,EAAE,wBAAwB,GAC3C,OAAO,CAAC,8BAA8B,GAAG,SAAS,CAAC,CA2DrD;IAEK,qBAAqB,CAC1B,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,sBAAsB,CAAC,QAAQ,CAAC,GACtC,OAAO,CAAC;QACV,UAAU,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,aAAa,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;QAC3D,WAAW,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,aAAa,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;QAC5D,UAAU,EAAE,KAAK,CAAC;YAAE,IAAI,EAAE,MAAM,CAAC;YAAC,aAAa,EAAE,MAAM,CAAA;SAAE,CAAC,CAAC;KAC3D,CAAC,CAuCD;IAED,oEAAoE;IAC9D,SAAS,CACd,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,YAAY,EAAE,GAAG,SAAS,EAClC,MAAM,EAAE,WAAW,EACnB,iBAAiB,CAAC,EAAE,OAAO,GAAG,UAAU,GACtC,OAAO,CAAC,gBAAgB,CAAC,CAkC3B;CACD","sourcesContent":["/**\n * Extension runner - executes extensions and manages their lifecycle.\n */\n\nimport type { AgentMessage } from \"omk-agent-core\";\nimport type { ImageContent, Model } from \"omk-ai\";\nimport type { KeyId } from \"omk-tui\";\nimport { type Theme, theme } from \"../../modes/interactive/theme/theme.ts\";\nimport type { ResourceDiagnostic } from \"../diagnostics.ts\";\nimport type { KeybindingsConfig } from \"../keybindings.ts\";\nimport type { ModelRegistry } from \"../model-registry.ts\";\nimport type { SessionManager } from \"../session-manager.ts\";\nimport type { BuildSystemPromptOptions } from \"../system-prompt.ts\";\nimport type {\n\tBeforeAgentStartEvent,\n\tBeforeAgentStartEventResult,\n\tBeforeProviderRequestEvent,\n\tCompactOptions,\n\tContextEvent,\n\tContextEventResult,\n\tContextUsage,\n\tExtension,\n\tExtensionActions,\n\tExtensionCommandContext,\n\tExtensionCommandContextActions,\n\tExtensionContext,\n\tExtensionContextActions,\n\tExtensionError,\n\tExtensionEvent,\n\tExtensionFlag,\n\tExtensionMode,\n\tExtensionRuntime,\n\tExtensionShortcut,\n\tExtensionUIContext,\n\tInputEvent,\n\tInputEventResult,\n\tInputSource,\n\tMessageEndEvent,\n\tMessageEndEventResult,\n\tMessageRenderer,\n\tProviderConfig,\n\tRegisteredCommand,\n\tRegisteredTool,\n\tReplacedSessionContext,\n\tResolvedCommand,\n\tResourcesDiscoverEvent,\n\tResourcesDiscoverResult,\n\tSessionBeforeCompactResult,\n\tSessionBeforeForkResult,\n\tSessionBeforeSwitchResult,\n\tSessionBeforeTreeResult,\n\tSessionShutdownEvent,\n\tToolCallEvent,\n\tToolCallEventResult,\n\tToolResultEvent,\n\tToolResultEventResult,\n\tUserBashEvent,\n\tUserBashEventResult,\n} from \"./types.ts\";\n\n// Extension shortcuts compete with canonical keybinding ids from keybindings.json.\n// Only editor-global shortcuts are reserved here. Picker-specific bindings are not.\nconst RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS = [\n\t\"app.interrupt\",\n\t\"app.clear\",\n\t\"app.exit\",\n\t\"app.suspend\",\n\t\"app.thinking.cycle\",\n\t\"app.model.cycleForward\",\n\t\"app.model.cycleBackward\",\n\t\"app.model.select\",\n\t\"app.tools.expand\",\n\t\"app.thinking.toggle\",\n\t\"app.editor.external\",\n\t\"app.message.followUp\",\n\t\"tui.input.submit\",\n\t\"tui.select.confirm\",\n\t\"tui.select.cancel\",\n\t\"tui.input.copy\",\n\t\"tui.editor.deleteToLineEnd\",\n] as const;\n\ntype BuiltInKeyBindings = Partial<Record<KeyId, { keybinding: string; restrictOverride: boolean }>>;\n\nconst buildBuiltinKeybindings = (resolvedKeybindings: KeybindingsConfig): BuiltInKeyBindings => {\n\tconst builtinKeybindings = {} as BuiltInKeyBindings;\n\tfor (const [keybinding, keys] of Object.entries(resolvedKeybindings)) {\n\t\tif (keys === undefined) continue;\n\t\tconst keyList = Array.isArray(keys) ? keys : [keys];\n\t\tconst restrictOverride = (RESERVED_KEYBINDINGS_FOR_EXTENSION_CONFLICTS as readonly string[]).includes(keybinding);\n\t\tfor (const key of keyList) {\n\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\t\t\t// If multiple actions bind the same key, the reserved action wins so extensions\n\t\t\t// remain blocked by reserved shortcuts regardless of iteration order.\n\t\t\tconst existing = builtinKeybindings[normalizedKey];\n\t\t\tif (existing?.restrictOverride && !restrictOverride) continue;\n\t\t\tbuiltinKeybindings[normalizedKey] = {\n\t\t\t\tkeybinding,\n\t\t\t\trestrictOverride,\n\t\t\t};\n\t\t}\n\t}\n\treturn builtinKeybindings;\n};\n\n/** Combined result from all before_agent_start handlers */\ninterface BeforeAgentStartCombinedResult {\n\tmessages?: NonNullable<BeforeAgentStartEventResult[\"message\"]>[];\n\tsystemPrompt?: string;\n}\n\n/**\n * Events handled by the generic emit() method.\n * Events with dedicated emitXxx() methods are excluded for stronger type safety.\n */\ntype RunnerEmitEvent = Exclude<\n\tExtensionEvent,\n\t| ToolCallEvent\n\t| ToolResultEvent\n\t| UserBashEvent\n\t| ContextEvent\n\t| BeforeProviderRequestEvent\n\t| BeforeAgentStartEvent\n\t| MessageEndEvent\n\t| ResourcesDiscoverEvent\n\t| InputEvent\n>;\n\ntype SessionBeforeEvent = Extract<\n\tRunnerEmitEvent,\n\t{ type: \"session_before_switch\" | \"session_before_fork\" | \"session_before_compact\" | \"session_before_tree\" }\n>;\n\ntype SessionBeforeEventResult =\n\t| SessionBeforeSwitchResult\n\t| SessionBeforeForkResult\n\t| SessionBeforeCompactResult\n\t| SessionBeforeTreeResult;\n\ntype RunnerEmitResult<TEvent extends RunnerEmitEvent> = TEvent extends { type: \"session_before_switch\" }\n\t? SessionBeforeSwitchResult | undefined\n\t: TEvent extends { type: \"session_before_fork\" }\n\t\t? SessionBeforeForkResult | undefined\n\t\t: TEvent extends { type: \"session_before_compact\" }\n\t\t\t? SessionBeforeCompactResult | undefined\n\t\t\t: TEvent extends { type: \"session_before_tree\" }\n\t\t\t\t? SessionBeforeTreeResult | undefined\n\t\t\t\t: undefined;\n\nexport type ExtensionErrorListener = (error: ExtensionError) => void;\n\nexport type NewSessionHandler = (options?: {\n\tparentSession?: string;\n\tsetup?: (sessionManager: SessionManager) => Promise<void>;\n\twithSession?: (ctx: ReplacedSessionContext) => Promise<void>;\n}) => Promise<{ cancelled: boolean }>;\n\nexport type ForkHandler = (\n\tentryId: string,\n\toptions?: { position?: \"before\" | \"at\"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n) => Promise<{ cancelled: boolean }>;\n\nexport type NavigateTreeHandler = (\n\ttargetId: string,\n\toptions?: { summarize?: boolean; customInstructions?: string; replaceInstructions?: boolean; label?: string },\n) => Promise<{ cancelled: boolean }>;\n\nexport type SwitchSessionHandler = (\n\tsessionPath: string,\n\toptions?: { withSession?: (ctx: ReplacedSessionContext) => Promise<void> },\n) => Promise<{ cancelled: boolean }>;\n\nexport type ReloadHandler = () => Promise<void>;\n\nexport type ShutdownHandler = () => void;\n\n/**\n * Helper function to emit session_shutdown event to extensions.\n * Returns true if the event was emitted, false if there were no handlers.\n */\nexport async function emitSessionShutdownEvent(\n\textensionRunner: ExtensionRunner,\n\tevent: SessionShutdownEvent,\n): Promise<boolean> {\n\tif (extensionRunner.hasHandlers(\"session_shutdown\")) {\n\t\tawait extensionRunner.emit(event);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nconst noOpUIContext: ExtensionUIContext = {\n\tselect: async () => undefined,\n\tconfirm: async () => false,\n\tinput: async () => undefined,\n\tnotify: () => {},\n\tonTerminalInput: () => () => {},\n\tsetStatus: () => {},\n\tsetWorkingMessage: () => {},\n\tsetWorkingVisible: () => {},\n\tsetWorkingIndicator: () => {},\n\tsetHiddenThinkingLabel: () => {},\n\tsetWidget: () => {},\n\tsetFooter: () => {},\n\tsetHeader: () => {},\n\tsetTitle: () => {},\n\tcustom: async () => undefined as never,\n\tpasteToEditor: () => {},\n\tsetEditorText: () => {},\n\tgetEditorText: () => \"\",\n\teditor: async () => undefined,\n\taddAutocompleteProvider: () => {},\n\tsetEditorComponent: () => {},\n\tgetEditorComponent: () => undefined,\n\tget theme() {\n\t\treturn theme;\n\t},\n\tgetAllThemes: () => [],\n\tgetTheme: () => undefined,\n\tsetTheme: (_theme: string | Theme) => ({ success: false, error: \"UI not available\" }),\n\tgetToolsExpanded: () => false,\n\tsetToolsExpanded: () => {},\n};\n\nexport class ExtensionRunner {\n\tprivate extensions: Extension[];\n\tprivate runtime: ExtensionRuntime;\n\tprivate uiContext: ExtensionUIContext;\n\tprivate mode: ExtensionMode = \"print\";\n\tprivate cwd: string;\n\tprivate sessionManager: SessionManager;\n\tprivate modelRegistry: ModelRegistry;\n\tprivate errorListeners: Set<ExtensionErrorListener> = new Set();\n\tprivate getModel: () => Model<any> | undefined = () => undefined;\n\tprivate isIdleFn: () => boolean = () => true;\n\tprivate getSignalFn: () => AbortSignal | undefined = () => undefined;\n\tprivate waitForIdleFn: () => Promise<void> = async () => {};\n\tprivate abortFn: () => void = () => {};\n\tprivate hasPendingMessagesFn: () => boolean = () => false;\n\tprivate getContextUsageFn: () => ContextUsage | undefined = () => undefined;\n\tprivate compactFn: (options?: CompactOptions) => void = () => {};\n\tprivate getSystemPromptFn: () => string = () => \"\";\n\tprivate getSystemPromptOptionsFn: () => BuildSystemPromptOptions = () => ({ cwd: this.cwd });\n\tprivate newSessionHandler: NewSessionHandler = async () => ({ cancelled: false });\n\tprivate forkHandler: ForkHandler = async () => ({ cancelled: false });\n\tprivate navigateTreeHandler: NavigateTreeHandler = async () => ({ cancelled: false });\n\tprivate switchSessionHandler: SwitchSessionHandler = async () => ({ cancelled: false });\n\tprivate reloadHandler: ReloadHandler = async () => {};\n\tprivate shutdownHandler: ShutdownHandler = () => {};\n\tprivate shortcutDiagnostics: ResourceDiagnostic[] = [];\n\tprivate commandDiagnostics: ResourceDiagnostic[] = [];\n\tprivate staleMessage: string | undefined;\n\n\tconstructor(\n\t\textensions: Extension[],\n\t\truntime: ExtensionRuntime,\n\t\tcwd: string,\n\t\tsessionManager: SessionManager,\n\t\tmodelRegistry: ModelRegistry,\n\t) {\n\t\tthis.extensions = extensions;\n\t\tthis.runtime = runtime;\n\t\tthis.uiContext = noOpUIContext;\n\t\tthis.cwd = cwd;\n\t\tthis.sessionManager = sessionManager;\n\t\tthis.modelRegistry = modelRegistry;\n\t}\n\n\tbindCore(\n\t\tactions: ExtensionActions,\n\t\tcontextActions: ExtensionContextActions,\n\t\tproviderActions?: {\n\t\t\tregisterProvider?: (name: string, config: ProviderConfig) => void;\n\t\t\tunregisterProvider?: (name: string) => void;\n\t\t},\n\t): void {\n\t\t// Copy actions into the shared runtime (all extension APIs reference this)\n\t\tthis.runtime.sendMessage = actions.sendMessage;\n\t\tthis.runtime.sendUserMessage = actions.sendUserMessage;\n\t\tthis.runtime.appendEntry = actions.appendEntry;\n\t\tthis.runtime.setSessionName = actions.setSessionName;\n\t\tthis.runtime.getSessionName = actions.getSessionName;\n\t\tthis.runtime.setLabel = actions.setLabel;\n\t\tthis.runtime.getActiveTools = actions.getActiveTools;\n\t\tthis.runtime.getAllTools = actions.getAllTools;\n\t\tthis.runtime.setActiveTools = actions.setActiveTools;\n\t\tthis.runtime.refreshTools = actions.refreshTools;\n\t\tthis.runtime.getCommands = actions.getCommands;\n\t\tthis.runtime.setModel = actions.setModel;\n\t\tthis.runtime.getThinkingLevel = actions.getThinkingLevel;\n\t\tthis.runtime.setThinkingLevel = actions.setThinkingLevel;\n\t\t// Optional MCP tool bridge for extensions (correctness-wall live OA, etc.).\n\t\t// When undefined, ExtensionAPI.callMcpTool still exists but throws until a handler is bound.\n\t\tthis.runtime.callMcpTool = actions.callMcpTool;\n\n\t\t// Context actions (required)\n\t\tthis.getModel = contextActions.getModel;\n\t\tthis.isIdleFn = contextActions.isIdle;\n\t\tthis.getSignalFn = contextActions.getSignal;\n\t\tthis.abortFn = contextActions.abort;\n\t\tthis.hasPendingMessagesFn = contextActions.hasPendingMessages;\n\t\tthis.shutdownHandler = contextActions.shutdown;\n\t\tthis.getContextUsageFn = contextActions.getContextUsage;\n\t\tthis.compactFn = contextActions.compact;\n\t\tthis.getSystemPromptFn = contextActions.getSystemPrompt;\n\t\tthis.getSystemPromptOptionsFn = contextActions.getSystemPromptOptions ?? (() => ({ cwd: this.cwd }));\n\n\t\t// Flush provider registrations queued during extension loading\n\t\tfor (const { name, config, extensionPath } of this.runtime.pendingProviderRegistrations) {\n\t\t\ttry {\n\t\t\t\tif (providerActions?.registerProvider) {\n\t\t\t\t\tproviderActions.registerProvider(name, config);\n\t\t\t\t} else {\n\t\t\t\t\tthis.modelRegistry.registerProvider(name, config);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthis.emitError({\n\t\t\t\t\textensionPath,\n\t\t\t\t\tevent: \"register_provider\",\n\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tthis.runtime.pendingProviderRegistrations = [];\n\n\t\t// From this point on, provider registration/unregistration takes effect immediately\n\t\t// without requiring a /reload.\n\t\tthis.runtime.registerProvider = (name, config) => {\n\t\t\tif (providerActions?.registerProvider) {\n\t\t\t\tproviderActions.registerProvider(name, config);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.modelRegistry.registerProvider(name, config);\n\t\t};\n\t\tthis.runtime.unregisterProvider = (name) => {\n\t\t\tif (providerActions?.unregisterProvider) {\n\t\t\t\tproviderActions.unregisterProvider(name);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.modelRegistry.unregisterProvider(name);\n\t\t};\n\t}\n\n\tbindCommandContext(actions?: ExtensionCommandContextActions): void {\n\t\tif (actions) {\n\t\t\tthis.waitForIdleFn = actions.waitForIdle;\n\t\t\tthis.newSessionHandler = actions.newSession;\n\t\t\tthis.forkHandler = actions.fork;\n\t\t\tthis.navigateTreeHandler = actions.navigateTree;\n\t\t\tthis.switchSessionHandler = actions.switchSession;\n\t\t\tthis.reloadHandler = actions.reload;\n\t\t\treturn;\n\t\t}\n\n\t\tthis.waitForIdleFn = async () => {};\n\t\tthis.newSessionHandler = async () => ({ cancelled: false });\n\t\tthis.forkHandler = async () => ({ cancelled: false });\n\t\tthis.navigateTreeHandler = async () => ({ cancelled: false });\n\t\tthis.switchSessionHandler = async () => ({ cancelled: false });\n\t\tthis.reloadHandler = async () => {};\n\t}\n\n\tsetUIContext(uiContext?: ExtensionUIContext, mode: ExtensionMode = \"print\"): void {\n\t\tthis.uiContext = uiContext ?? noOpUIContext;\n\t\tthis.mode = mode;\n\t}\n\n\tgetUIContext(): ExtensionUIContext {\n\t\treturn this.uiContext;\n\t}\n\n\thasUI(): boolean {\n\t\treturn this.uiContext !== noOpUIContext;\n\t}\n\n\tgetExtensionPaths(): string[] {\n\t\treturn this.extensions.map((e) => e.path);\n\t}\n\n\t/** Get all registered tools from all extensions (first registration per name wins). */\n\tgetAllRegisteredTools(): RegisteredTool[] {\n\t\tconst toolsByName = new Map<string, RegisteredTool>();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const tool of ext.tools.values()) {\n\t\t\t\tif (!toolsByName.has(tool.definition.name)) {\n\t\t\t\t\ttoolsByName.set(tool.definition.name, tool);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn Array.from(toolsByName.values());\n\t}\n\n\t/** Get a tool definition by name. Returns undefined if not found. */\n\tgetToolDefinition(toolName: string): RegisteredTool[\"definition\"] | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst tool = ext.tools.get(toolName);\n\t\t\tif (tool) {\n\t\t\t\treturn tool.definition;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tgetFlags(): Map<string, ExtensionFlag> {\n\t\tconst allFlags = new Map<string, ExtensionFlag>();\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [name, flag] of ext.flags) {\n\t\t\t\tif (!allFlags.has(name)) {\n\t\t\t\t\tallFlags.set(name, flag);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn allFlags;\n\t}\n\n\tsetFlagValue(name: string, value: boolean | string): void {\n\t\tthis.runtime.flagValues.set(name, value);\n\t}\n\n\tgetFlagValues(): Map<string, boolean | string> {\n\t\treturn new Map(this.runtime.flagValues);\n\t}\n\n\tgetShortcuts(resolvedKeybindings: KeybindingsConfig): Map<KeyId, ExtensionShortcut> {\n\t\tthis.shortcutDiagnostics = [];\n\t\tconst builtinKeybindings = buildBuiltinKeybindings(resolvedKeybindings);\n\t\tconst extensionShortcuts = new Map<KeyId, ExtensionShortcut>();\n\n\t\tconst addDiagnostic = (message: string, extensionPath: string) => {\n\t\t\tthis.shortcutDiagnostics.push({ type: \"warning\", message, path: extensionPath });\n\t\t\tif (!this.hasUI()) {\n\t\t\t\tconsole.warn(message);\n\t\t\t}\n\t\t};\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const [key, shortcut] of ext.shortcuts) {\n\t\t\t\tconst normalizedKey = key.toLowerCase() as KeyId;\n\n\t\t\t\tconst builtInKeybinding = builtinKeybindings[normalizedKey];\n\t\t\t\tif (builtInKeybinding?.restrictOverride === true) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut '${key}' from ${shortcut.extensionPath} conflicts with built-in shortcut. Skipping.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (builtInKeybinding?.restrictOverride === false) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' is built-in shortcut for ${builtInKeybinding.keybinding} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\n\t\t\t\tconst existingExtensionShortcut = extensionShortcuts.get(normalizedKey);\n\t\t\t\tif (existingExtensionShortcut) {\n\t\t\t\t\taddDiagnostic(\n\t\t\t\t\t\t`Extension shortcut conflict: '${key}' registered by both ${existingExtensionShortcut.extensionPath} and ${shortcut.extensionPath}. Using ${shortcut.extensionPath}.`,\n\t\t\t\t\t\tshortcut.extensionPath,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\textensionShortcuts.set(normalizedKey, shortcut);\n\t\t\t}\n\t\t}\n\t\treturn extensionShortcuts;\n\t}\n\n\tgetShortcutDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.shortcutDiagnostics;\n\t}\n\n\tinvalidate(\n\t\tmessage = \"This extension ctx is stale after session replacement or reload. Do not use a captured extension API or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\",\n\t): void {\n\t\tif (!this.staleMessage) {\n\t\t\tthis.staleMessage = message;\n\t\t\tthis.runtime.invalidate(message);\n\t\t}\n\t}\n\n\tprivate assertActive(): void {\n\t\tif (this.staleMessage) {\n\t\t\tthrow new Error(this.staleMessage);\n\t\t}\n\t}\n\n\tonError(listener: ExtensionErrorListener): () => void {\n\t\tthis.errorListeners.add(listener);\n\t\treturn () => this.errorListeners.delete(listener);\n\t}\n\n\temitError(error: ExtensionError): void {\n\t\tfor (const listener of this.errorListeners) {\n\t\t\tlistener(error);\n\t\t}\n\t}\n\n\thasHandlers(eventType: string): boolean {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(eventType);\n\t\t\tif (handlers && handlers.length > 0) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tgetMessageRenderer(customType: string): MessageRenderer | undefined {\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst renderer = ext.messageRenderers.get(customType);\n\t\t\tif (renderer) {\n\t\t\t\treturn renderer;\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate resolveRegisteredCommands(): ResolvedCommand[] {\n\t\tconst commands: RegisteredCommand[] = [];\n\t\tconst counts = new Map<string, number>();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const command of ext.commands.values()) {\n\t\t\t\tcommands.push(command);\n\t\t\t\tcounts.set(command.name, (counts.get(command.name) ?? 0) + 1);\n\t\t\t}\n\t\t}\n\n\t\tconst seen = new Map<string, number>();\n\t\tconst takenInvocationNames = new Set<string>();\n\n\t\treturn commands.map((command) => {\n\t\t\tconst occurrence = (seen.get(command.name) ?? 0) + 1;\n\t\t\tseen.set(command.name, occurrence);\n\n\t\t\tlet invocationName = (counts.get(command.name) ?? 0) > 1 ? `${command.name}:${occurrence}` : command.name;\n\n\t\t\tif (takenInvocationNames.has(invocationName)) {\n\t\t\t\tlet suffix = occurrence;\n\t\t\t\tdo {\n\t\t\t\t\tsuffix++;\n\t\t\t\t\tinvocationName = `${command.name}:${suffix}`;\n\t\t\t\t} while (takenInvocationNames.has(invocationName));\n\t\t\t}\n\n\t\t\ttakenInvocationNames.add(invocationName);\n\t\t\treturn {\n\t\t\t\t...command,\n\t\t\t\tinvocationName,\n\t\t\t};\n\t\t});\n\t}\n\n\tgetRegisteredCommands(): ResolvedCommand[] {\n\t\tthis.commandDiagnostics = [];\n\t\treturn this.resolveRegisteredCommands();\n\t}\n\n\tgetCommandDiagnostics(): ResourceDiagnostic[] {\n\t\treturn this.commandDiagnostics;\n\t}\n\n\tgetCommand(name: string): ResolvedCommand | undefined {\n\t\treturn this.resolveRegisteredCommands().find((command) => command.invocationName === name);\n\t}\n\n\t/**\n\t * Request a graceful shutdown. Called by extension tools and event handlers.\n\t * The actual shutdown behavior is provided by the mode via bindExtensions().\n\t */\n\tshutdown(): void {\n\t\tthis.shutdownHandler();\n\t}\n\n\t/**\n\t * Create an ExtensionContext for use in event handlers and tool execution.\n\t * Context values are resolved at call time, so changes via bindCore/bindUI are reflected.\n\t */\n\tcreateContext(): ExtensionContext {\n\t\tconst runner = this;\n\t\tconst getModel = this.getModel;\n\t\treturn {\n\t\t\tget ui() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.uiContext;\n\t\t\t},\n\t\t\tget mode() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.mode;\n\t\t\t},\n\t\t\tget hasUI() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.hasUI();\n\t\t\t},\n\t\t\tget cwd() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.cwd;\n\t\t\t},\n\t\t\tget sessionManager() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.sessionManager;\n\t\t\t},\n\t\t\tget modelRegistry() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.modelRegistry;\n\t\t\t},\n\t\t\tget model() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn getModel();\n\t\t\t},\n\t\t\tget thinkingLevel() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.runtime.getThinkingLevel();\n\t\t\t},\n\t\t\tisIdle: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.isIdleFn();\n\t\t\t},\n\t\t\tget signal() {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getSignalFn();\n\t\t\t},\n\t\t\tabort: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.abortFn();\n\t\t\t},\n\t\t\thasPendingMessages: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.hasPendingMessagesFn();\n\t\t\t},\n\t\t\tshutdown: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.shutdownHandler();\n\t\t\t},\n\t\t\tgetContextUsage: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getContextUsageFn();\n\t\t\t},\n\t\t\tcompact: (options) => {\n\t\t\t\trunner.assertActive();\n\t\t\t\trunner.compactFn(options);\n\t\t\t},\n\t\t\tgetSystemPrompt: () => {\n\t\t\t\trunner.assertActive();\n\t\t\t\treturn runner.getSystemPromptFn();\n\t\t\t},\n\t\t};\n\t}\n\n\tcreateCommandContext(): ExtensionCommandContext {\n\t\t// Use property descriptors instead of object spread so the guarded getters from\n\t\t// createContext() stay lazy. A spread would eagerly read them once and freeze the\n\t\t// old values into the returned object, bypassing stale-instance checks.\n\t\tconst context = Object.defineProperties(\n\t\t\t{},\n\t\t\tObject.getOwnPropertyDescriptors(this.createContext()),\n\t\t) as ExtensionCommandContext;\n\t\tcontext.getSystemPromptOptions = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.getSystemPromptOptionsFn();\n\t\t};\n\t\tcontext.waitForIdle = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.waitForIdleFn();\n\t\t};\n\t\tcontext.newSession = (options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.newSessionHandler(options);\n\t\t};\n\t\tcontext.fork = (entryId, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.forkHandler(entryId, options);\n\t\t};\n\t\tcontext.navigateTree = (targetId, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.navigateTreeHandler(targetId, options);\n\t\t};\n\t\tcontext.switchSession = (sessionPath, options) => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.switchSessionHandler(sessionPath, options);\n\t\t};\n\t\tcontext.reload = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn this.reloadHandler();\n\t\t};\n\t\treturn context;\n\t}\n\n\tprivate isSessionBeforeEvent(event: RunnerEmitEvent): event is SessionBeforeEvent {\n\t\treturn (\n\t\t\tevent.type === \"session_before_switch\" ||\n\t\t\tevent.type === \"session_before_fork\" ||\n\t\t\tevent.type === \"session_before_compact\" ||\n\t\t\tevent.type === \"session_before_tree\"\n\t\t);\n\t}\n\n\tasync emit<TEvent extends RunnerEmitEvent>(event: TEvent): Promise<RunnerEmitResult<TEvent>> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: SessionBeforeEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(event.type);\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (this.isSessionBeforeEvent(event) && handlerResult) {\n\t\t\t\t\t\tresult = handlerResult as SessionBeforeEventResult;\n\t\t\t\t\t\tif (result.cancel) {\n\t\t\t\t\t\t\treturn result as RunnerEmitResult<TEvent>;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: event.type,\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result as RunnerEmitResult<TEvent>;\n\t}\n\n\tasync emitMessageEnd(event: MessageEndEvent): Promise<AgentMessage | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessage = event.message;\n\t\tlet modified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"message_end\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst currentEvent: MessageEndEvent = { ...event, message: currentMessage };\n\t\t\t\t\tconst handlerResult = (await handler(currentEvent, ctx)) as MessageEndEventResult | undefined;\n\t\t\t\t\tif (!handlerResult?.message) continue;\n\n\t\t\t\t\tif (handlerResult.message.role !== currentMessage.role) {\n\t\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\t\tevent: \"message_end\",\n\t\t\t\t\t\t\terror: \"message_end handlers must return a message with the same role\",\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\n\t\t\t\t\tcurrentMessage = handlerResult.message;\n\t\t\t\t\tmodified = true;\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"message_end\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn modified ? currentMessage : undefined;\n\t}\n\n\tasync emitToolResult(event: ToolResultEvent): Promise<ToolResultEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tconst currentEvent: ToolResultEvent = { ...event };\n\t\tlet modified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_result\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = (await handler(currentEvent, ctx)) as ToolResultEventResult | undefined;\n\t\t\t\t\tif (!handlerResult) continue;\n\n\t\t\t\t\tif (handlerResult.content !== undefined) {\n\t\t\t\t\t\tcurrentEvent.content = handlerResult.content;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.details !== undefined) {\n\t\t\t\t\t\tcurrentEvent.details = handlerResult.details;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t\tif (handlerResult.isError !== undefined) {\n\t\t\t\t\t\tcurrentEvent.isError = handlerResult.isError;\n\t\t\t\t\t\tmodified = true;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"tool_result\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!modified) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\treturn {\n\t\t\tcontent: currentEvent.content,\n\t\t\tdetails: currentEvent.details,\n\t\t\tisError: currentEvent.isError,\n\t\t};\n\t}\n\n\tasync emitToolCall(event: ToolCallEvent): Promise<ToolCallEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\t\tlet result: ToolCallEventResult | undefined;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"tool_call\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\tif (handlerResult) {\n\t\t\t\t\tresult = handlerResult as ToolCallEventResult;\n\t\t\t\t\tif (result.block) {\n\t\t\t\t\t\treturn result;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tasync emitUserBash(event: UserBashEvent): Promise<UserBashEventResult | undefined> {\n\t\tconst ctx = this.createContext();\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"user_bash\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\treturn handlerResult as UserBashEventResult;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"user_bash\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitContext(messages: AgentMessage[]): Promise<AgentMessage[]> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentMessages = structuredClone(messages);\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"context\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ContextEvent = { type: \"context\", messages: currentMessages };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult && (handlerResult as ContextEventResult).messages) {\n\t\t\t\t\t\tcurrentMessages = (handlerResult as ContextEventResult).messages!;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"context\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn currentMessages;\n\t}\n\n\tasync emitBeforeProviderRequest(payload: unknown): Promise<unknown> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentPayload = payload;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_provider_request\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: BeforeProviderRequestEvent = {\n\t\t\t\t\t\ttype: \"before_provider_request\",\n\t\t\t\t\t\tpayload: currentPayload,\n\t\t\t\t\t};\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tif (handlerResult !== undefined) {\n\t\t\t\t\t\tcurrentPayload = handlerResult;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_provider_request\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn currentPayload;\n\t}\n\n\tasync emitBeforeAgentStart(\n\t\tprompt: string,\n\t\timages: ImageContent[] | undefined,\n\t\tsystemPrompt: string,\n\t\tsystemPromptOptions: BuildSystemPromptOptions,\n\t): Promise<BeforeAgentStartCombinedResult | undefined> {\n\t\tlet currentSystemPrompt = systemPrompt;\n\t\tconst ctx = Object.defineProperties(\n\t\t\t{},\n\t\t\tObject.getOwnPropertyDescriptors(this.createContext()),\n\t\t) as ExtensionContext;\n\t\tctx.getSystemPrompt = () => {\n\t\t\tthis.assertActive();\n\t\t\treturn currentSystemPrompt;\n\t\t};\n\t\tconst messages: NonNullable<BeforeAgentStartEventResult[\"message\"]>[] = [];\n\t\tlet systemPromptModified = false;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"before_agent_start\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: BeforeAgentStartEvent = {\n\t\t\t\t\t\ttype: \"before_agent_start\",\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\timages,\n\t\t\t\t\t\tsystemPrompt: currentSystemPrompt,\n\t\t\t\t\t\tsystemPromptOptions,\n\t\t\t\t\t};\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\n\t\t\t\t\tif (handlerResult) {\n\t\t\t\t\t\tconst result = handlerResult as BeforeAgentStartEventResult;\n\t\t\t\t\t\tif (result.message) {\n\t\t\t\t\t\t\tmessages.push(result.message);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (result.systemPrompt !== undefined) {\n\t\t\t\t\t\t\tcurrentSystemPrompt = result.systemPrompt;\n\t\t\t\t\t\t\tsystemPromptModified = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"before_agent_start\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (messages.length > 0 || systemPromptModified) {\n\t\t\treturn {\n\t\t\t\tmessages: messages.length > 0 ? messages : undefined,\n\t\t\t\tsystemPrompt: systemPromptModified ? currentSystemPrompt : undefined,\n\t\t\t};\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\tasync emitResourcesDiscover(\n\t\tcwd: string,\n\t\treason: ResourcesDiscoverEvent[\"reason\"],\n\t): Promise<{\n\t\tskillPaths: Array<{ path: string; extensionPath: string }>;\n\t\tpromptPaths: Array<{ path: string; extensionPath: string }>;\n\t\tthemePaths: Array<{ path: string; extensionPath: string }>;\n\t}> {\n\t\tconst ctx = this.createContext();\n\t\tconst skillPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst promptPaths: Array<{ path: string; extensionPath: string }> = [];\n\t\tconst themePaths: Array<{ path: string; extensionPath: string }> = [];\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tconst handlers = ext.handlers.get(\"resources_discover\");\n\t\t\tif (!handlers || handlers.length === 0) continue;\n\n\t\t\tfor (const handler of handlers) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: ResourcesDiscoverEvent = { type: \"resources_discover\", cwd, reason };\n\t\t\t\t\tconst handlerResult = await handler(event, ctx);\n\t\t\t\t\tconst result = handlerResult as ResourcesDiscoverResult | undefined;\n\n\t\t\t\t\tif (result?.skillPaths?.length) {\n\t\t\t\t\t\tskillPaths.push(...result.skillPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.promptPaths?.length) {\n\t\t\t\t\t\tpromptPaths.push(...result.promptPaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t\tif (result?.themePaths?.length) {\n\t\t\t\t\t\tthemePaths.push(...result.themePaths.map((path) => ({ path, extensionPath: ext.path })));\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\t\t\tconst stack = err instanceof Error ? err.stack : undefined;\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"resources_discover\",\n\t\t\t\t\t\terror: message,\n\t\t\t\t\t\tstack,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { skillPaths, promptPaths, themePaths };\n\t}\n\n\t/** Emit input event. Transforms chain, \"handled\" short-circuits. */\n\tasync emitInput(\n\t\ttext: string,\n\t\timages: ImageContent[] | undefined,\n\t\tsource: InputSource,\n\t\tstreamingBehavior?: \"steer\" | \"followUp\",\n\t): Promise<InputEventResult> {\n\t\tconst ctx = this.createContext();\n\t\tlet currentText = text;\n\t\tlet currentImages = images;\n\n\t\tfor (const ext of this.extensions) {\n\t\t\tfor (const handler of ext.handlers.get(\"input\") ?? []) {\n\t\t\t\ttry {\n\t\t\t\t\tconst event: InputEvent = {\n\t\t\t\t\t\ttype: \"input\",\n\t\t\t\t\t\ttext: currentText,\n\t\t\t\t\t\timages: currentImages,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tstreamingBehavior,\n\t\t\t\t\t};\n\t\t\t\t\tconst result = (await handler(event, ctx)) as InputEventResult | undefined;\n\t\t\t\t\tif (result?.action === \"handled\") return result;\n\t\t\t\t\tif (result?.action === \"transform\") {\n\t\t\t\t\t\tcurrentText = result.text;\n\t\t\t\t\t\tcurrentImages = result.images ?? currentImages;\n\t\t\t\t\t}\n\t\t\t\t} catch (err) {\n\t\t\t\t\tthis.emitError({\n\t\t\t\t\t\textensionPath: ext.path,\n\t\t\t\t\t\tevent: \"input\",\n\t\t\t\t\t\terror: err instanceof Error ? err.message : String(err),\n\t\t\t\t\t\tstack: err instanceof Error ? err.stack : undefined,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn currentText !== text || currentImages !== images\n\t\t\t? { action: \"transform\", text: currentText, images: currentImages }\n\t\t\t: { action: \"continue\" };\n\t}\n}\n"]}
@@ -413,6 +413,10 @@ export class ExtensionRunner {
413
413
  runner.assertActive();
414
414
  return getModel();
415
415
  },
416
+ get thinkingLevel() {
417
+ runner.assertActive();
418
+ return runner.runtime.getThinkingLevel();
419
+ },
416
420
  isIdle: () => {
417
421
  runner.assertActive();
418
422
  return runner.isIdleFn();