@ilya-lesikov/pi-pi 0.1.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 (271) hide show
  1. package/3p/pi-ask-user/index.ts +1835 -0
  2. package/3p/pi-ask-user/package.json +50 -0
  3. package/3p/pi-ask-user/single-select-layout.ts +203 -0
  4. package/3p/pi-lsp/extensions/lsp/client.ts +542 -0
  5. package/3p/pi-lsp/extensions/lsp/config.ts +135 -0
  6. package/3p/pi-lsp/extensions/lsp/effects/command.ts +42 -0
  7. package/3p/pi-lsp/extensions/lsp/effects/filesystem.ts +50 -0
  8. package/3p/pi-lsp/extensions/lsp/effects/runtime.ts +21 -0
  9. package/3p/pi-lsp/extensions/lsp/errors.ts +113 -0
  10. package/3p/pi-lsp/extensions/lsp/formatting.ts +315 -0
  11. package/3p/pi-lsp/extensions/lsp/index.ts +231 -0
  12. package/3p/pi-lsp/extensions/lsp/protocol.ts +209 -0
  13. package/3p/pi-lsp/extensions/lsp/retry.ts +39 -0
  14. package/3p/pi-lsp/extensions/lsp/tools/programs.ts +293 -0
  15. package/3p/pi-lsp/extensions/lsp/tools.ts +89 -0
  16. package/3p/pi-lsp/extensions/lsp/types.ts +243 -0
  17. package/3p/pi-lsp/package.json +54 -0
  18. package/3p/pi-plannotator/AGENTS.md +583 -0
  19. package/3p/pi-plannotator/apps/pi-extension/README.md +228 -0
  20. package/3p/pi-plannotator/apps/pi-extension/assistant-message.ts +128 -0
  21. package/3p/pi-plannotator/apps/pi-extension/config.test.ts +166 -0
  22. package/3p/pi-plannotator/apps/pi-extension/config.ts +318 -0
  23. package/3p/pi-plannotator/apps/pi-extension/current-pi-session.ts +147 -0
  24. package/3p/pi-plannotator/apps/pi-extension/index.ts +1279 -0
  25. package/3p/pi-plannotator/apps/pi-extension/package.json +56 -0
  26. package/3p/pi-plannotator/apps/pi-extension/plannotator-browser.test.ts +13 -0
  27. package/3p/pi-plannotator/apps/pi-extension/plannotator-browser.ts +616 -0
  28. package/3p/pi-plannotator/apps/pi-extension/plannotator-events.ts +342 -0
  29. package/3p/pi-plannotator/apps/pi-extension/plannotator.json +12 -0
  30. package/3p/pi-plannotator/apps/pi-extension/server/agent-jobs.ts +515 -0
  31. package/3p/pi-plannotator/apps/pi-extension/server/ai-runtime.ts +169 -0
  32. package/3p/pi-plannotator/apps/pi-extension/server/annotations.ts +85 -0
  33. package/3p/pi-plannotator/apps/pi-extension/server/external-annotations.ts +189 -0
  34. package/3p/pi-plannotator/apps/pi-extension/server/handlers.ts +210 -0
  35. package/3p/pi-plannotator/apps/pi-extension/server/helpers.ts +78 -0
  36. package/3p/pi-plannotator/apps/pi-extension/server/ide.ts +46 -0
  37. package/3p/pi-plannotator/apps/pi-extension/server/integrations.ts +195 -0
  38. package/3p/pi-plannotator/apps/pi-extension/server/network.test.ts +158 -0
  39. package/3p/pi-plannotator/apps/pi-extension/server/network.ts +268 -0
  40. package/3p/pi-plannotator/apps/pi-extension/server/pr.ts +126 -0
  41. package/3p/pi-plannotator/apps/pi-extension/server/project.ts +64 -0
  42. package/3p/pi-plannotator/apps/pi-extension/server/reference.ts +362 -0
  43. package/3p/pi-plannotator/apps/pi-extension/server/serverAnnotate.ts +199 -0
  44. package/3p/pi-plannotator/apps/pi-extension/server/serverPlan.ts +505 -0
  45. package/3p/pi-plannotator/apps/pi-extension/server/serverReview.ts +1229 -0
  46. package/3p/pi-plannotator/apps/pi-extension/server/vcs.ts +121 -0
  47. package/3p/pi-plannotator/apps/pi-extension/server.test.ts +966 -0
  48. package/3p/pi-plannotator/apps/pi-extension/server.ts +44 -0
  49. package/3p/pi-plannotator/apps/pi-extension/tool-scope.test.ts +88 -0
  50. package/3p/pi-plannotator/apps/pi-extension/tool-scope.ts +39 -0
  51. package/3p/pi-plannotator/apps/pi-extension/tsconfig.json +16 -0
  52. package/3p/pi-plannotator/apps/pi-extension/vendor.sh +48 -0
  53. package/3p/pi-plannotator/package.json +53 -0
  54. package/3p/pi-plannotator/packages/ai/ai.test.ts +1407 -0
  55. package/3p/pi-plannotator/packages/ai/base-session.ts +94 -0
  56. package/3p/pi-plannotator/packages/ai/context.ts +250 -0
  57. package/3p/pi-plannotator/packages/ai/endpoints.ts +326 -0
  58. package/3p/pi-plannotator/packages/ai/index.ts +105 -0
  59. package/3p/pi-plannotator/packages/ai/package.json +21 -0
  60. package/3p/pi-plannotator/packages/ai/provider.ts +103 -0
  61. package/3p/pi-plannotator/packages/ai/providers/claude-agent-sdk.ts +447 -0
  62. package/3p/pi-plannotator/packages/ai/providers/codex-sdk.ts +430 -0
  63. package/3p/pi-plannotator/packages/ai/providers/command-path.ts +115 -0
  64. package/3p/pi-plannotator/packages/ai/providers/opencode-sdk.ts +546 -0
  65. package/3p/pi-plannotator/packages/ai/providers/pi-events.ts +110 -0
  66. package/3p/pi-plannotator/packages/ai/providers/pi-sdk-node.ts +425 -0
  67. package/3p/pi-plannotator/packages/ai/providers/pi-sdk.ts +469 -0
  68. package/3p/pi-plannotator/packages/ai/session-manager.ts +195 -0
  69. package/3p/pi-plannotator/packages/ai/tsconfig.json +15 -0
  70. package/3p/pi-plannotator/packages/ai/types.ts +379 -0
  71. package/3p/pi-plannotator/packages/server/agent-jobs.ts +538 -0
  72. package/3p/pi-plannotator/packages/server/agent-review-message.test.ts +135 -0
  73. package/3p/pi-plannotator/packages/server/agent-review-message.ts +243 -0
  74. package/3p/pi-plannotator/packages/server/ai-runtime.ts +108 -0
  75. package/3p/pi-plannotator/packages/server/annotate.ts +401 -0
  76. package/3p/pi-plannotator/packages/server/browser.test.ts +87 -0
  77. package/3p/pi-plannotator/packages/server/browser.ts +245 -0
  78. package/3p/pi-plannotator/packages/server/claude-review.ts +352 -0
  79. package/3p/pi-plannotator/packages/server/code-nav.ts +73 -0
  80. package/3p/pi-plannotator/packages/server/codex-review-schema.json +41 -0
  81. package/3p/pi-plannotator/packages/server/codex-review.ts +330 -0
  82. package/3p/pi-plannotator/packages/server/config.ts +8 -0
  83. package/3p/pi-plannotator/packages/server/draft.ts +1 -0
  84. package/3p/pi-plannotator/packages/server/editor-annotations.ts +76 -0
  85. package/3p/pi-plannotator/packages/server/external-annotations.test.ts +18 -0
  86. package/3p/pi-plannotator/packages/server/external-annotations.ts +207 -0
  87. package/3p/pi-plannotator/packages/server/git.ts +141 -0
  88. package/3p/pi-plannotator/packages/server/goal-setup.test.ts +55 -0
  89. package/3p/pi-plannotator/packages/server/goal-setup.ts +248 -0
  90. package/3p/pi-plannotator/packages/server/ide.ts +43 -0
  91. package/3p/pi-plannotator/packages/server/image.test.ts +63 -0
  92. package/3p/pi-plannotator/packages/server/image.ts +66 -0
  93. package/3p/pi-plannotator/packages/server/index.ts +648 -0
  94. package/3p/pi-plannotator/packages/server/integrations.test.ts +172 -0
  95. package/3p/pi-plannotator/packages/server/integrations.ts +214 -0
  96. package/3p/pi-plannotator/packages/server/jj.test.ts +69 -0
  97. package/3p/pi-plannotator/packages/server/jj.ts +86 -0
  98. package/3p/pi-plannotator/packages/server/p4.ts +417 -0
  99. package/3p/pi-plannotator/packages/server/package.json +40 -0
  100. package/3p/pi-plannotator/packages/server/path-utils.ts +18 -0
  101. package/3p/pi-plannotator/packages/server/pr.ts +146 -0
  102. package/3p/pi-plannotator/packages/server/project.test.ts +115 -0
  103. package/3p/pi-plannotator/packages/server/project.ts +45 -0
  104. package/3p/pi-plannotator/packages/server/reference-handlers.ts +404 -0
  105. package/3p/pi-plannotator/packages/server/remote.test.ts +150 -0
  106. package/3p/pi-plannotator/packages/server/remote.ts +74 -0
  107. package/3p/pi-plannotator/packages/server/repo.ts +80 -0
  108. package/3p/pi-plannotator/packages/server/resolve-file.test.ts +310 -0
  109. package/3p/pi-plannotator/packages/server/review-workspace.test.ts +1032 -0
  110. package/3p/pi-plannotator/packages/server/review-workspace.ts +48 -0
  111. package/3p/pi-plannotator/packages/server/review.ts +1318 -0
  112. package/3p/pi-plannotator/packages/server/sessions.ts +111 -0
  113. package/3p/pi-plannotator/packages/server/share-url.ts +53 -0
  114. package/3p/pi-plannotator/packages/server/shared-handlers.test.ts +43 -0
  115. package/3p/pi-plannotator/packages/server/shared-handlers.ts +177 -0
  116. package/3p/pi-plannotator/packages/server/storage.test.ts +176 -0
  117. package/3p/pi-plannotator/packages/server/storage.ts +17 -0
  118. package/3p/pi-plannotator/packages/server/tour/tour-review.test.ts +146 -0
  119. package/3p/pi-plannotator/packages/server/tour/tour-review.ts +604 -0
  120. package/3p/pi-plannotator/packages/server/tsconfig.json +15 -0
  121. package/3p/pi-plannotator/packages/server/vcs.test.ts +48 -0
  122. package/3p/pi-plannotator/packages/server/vcs.ts +80 -0
  123. package/3p/pi-plannotator/packages/shared/agent-jobs.ts +132 -0
  124. package/3p/pi-plannotator/packages/shared/agents.ts +53 -0
  125. package/3p/pi-plannotator/packages/shared/annotate-args.test.ts +386 -0
  126. package/3p/pi-plannotator/packages/shared/annotate-args.ts +107 -0
  127. package/3p/pi-plannotator/packages/shared/at-reference.test.ts +99 -0
  128. package/3p/pi-plannotator/packages/shared/at-reference.ts +52 -0
  129. package/3p/pi-plannotator/packages/shared/checklist.ts +52 -0
  130. package/3p/pi-plannotator/packages/shared/code-file.test.ts +112 -0
  131. package/3p/pi-plannotator/packages/shared/code-file.ts +41 -0
  132. package/3p/pi-plannotator/packages/shared/code-nav.test.ts +515 -0
  133. package/3p/pi-plannotator/packages/shared/code-nav.ts +436 -0
  134. package/3p/pi-plannotator/packages/shared/compress.ts +51 -0
  135. package/3p/pi-plannotator/packages/shared/config.ts +262 -0
  136. package/3p/pi-plannotator/packages/shared/crypto.test.ts +172 -0
  137. package/3p/pi-plannotator/packages/shared/crypto.ts +97 -0
  138. package/3p/pi-plannotator/packages/shared/data-dir.ts +42 -0
  139. package/3p/pi-plannotator/packages/shared/diff-paths.test.ts +30 -0
  140. package/3p/pi-plannotator/packages/shared/diff-paths.ts +137 -0
  141. package/3p/pi-plannotator/packages/shared/draft.ts +64 -0
  142. package/3p/pi-plannotator/packages/shared/external-annotation.ts +397 -0
  143. package/3p/pi-plannotator/packages/shared/extract-code-paths.test.ts +59 -0
  144. package/3p/pi-plannotator/packages/shared/extract-code-paths.ts +66 -0
  145. package/3p/pi-plannotator/packages/shared/favicon.ts +5 -0
  146. package/3p/pi-plannotator/packages/shared/feedback-templates.test.ts +65 -0
  147. package/3p/pi-plannotator/packages/shared/feedback-templates.ts +29 -0
  148. package/3p/pi-plannotator/packages/shared/goal-setup.test.ts +231 -0
  149. package/3p/pi-plannotator/packages/shared/goal-setup.ts +336 -0
  150. package/3p/pi-plannotator/packages/shared/html-to-markdown.test.ts +62 -0
  151. package/3p/pi-plannotator/packages/shared/html-to-markdown.ts +32 -0
  152. package/3p/pi-plannotator/packages/shared/improvement-hooks.test.ts +135 -0
  153. package/3p/pi-plannotator/packages/shared/improvement-hooks.ts +115 -0
  154. package/3p/pi-plannotator/packages/shared/integrations-common.ts +243 -0
  155. package/3p/pi-plannotator/packages/shared/jj-core.test.ts +236 -0
  156. package/3p/pi-plannotator/packages/shared/jj-core.ts +433 -0
  157. package/3p/pi-plannotator/packages/shared/package.json +55 -0
  158. package/3p/pi-plannotator/packages/shared/pfm-reminder.test.ts +88 -0
  159. package/3p/pi-plannotator/packages/shared/pfm-reminder.ts +80 -0
  160. package/3p/pi-plannotator/packages/shared/pr-github.ts +661 -0
  161. package/3p/pi-plannotator/packages/shared/pr-gitlab.test.ts +202 -0
  162. package/3p/pi-plannotator/packages/shared/pr-gitlab.ts +620 -0
  163. package/3p/pi-plannotator/packages/shared/pr-provider.test.ts +266 -0
  164. package/3p/pi-plannotator/packages/shared/pr-provider.ts +123 -0
  165. package/3p/pi-plannotator/packages/shared/pr-stack.test.ts +104 -0
  166. package/3p/pi-plannotator/packages/shared/pr-stack.ts +194 -0
  167. package/3p/pi-plannotator/packages/shared/pr-types.ts +326 -0
  168. package/3p/pi-plannotator/packages/shared/project.ts +71 -0
  169. package/3p/pi-plannotator/packages/shared/prompts-integration.test.ts +421 -0
  170. package/3p/pi-plannotator/packages/shared/prompts.test.ts +504 -0
  171. package/3p/pi-plannotator/packages/shared/prompts.ts +247 -0
  172. package/3p/pi-plannotator/packages/shared/reference-common.ts +87 -0
  173. package/3p/pi-plannotator/packages/shared/repo.ts +71 -0
  174. package/3p/pi-plannotator/packages/shared/resolve-file.test.ts +113 -0
  175. package/3p/pi-plannotator/packages/shared/resolve-file.ts +509 -0
  176. package/3p/pi-plannotator/packages/shared/review-args.test.ts +64 -0
  177. package/3p/pi-plannotator/packages/shared/review-args.ts +85 -0
  178. package/3p/pi-plannotator/packages/shared/review-core.test.ts +286 -0
  179. package/3p/pi-plannotator/packages/shared/review-core.ts +895 -0
  180. package/3p/pi-plannotator/packages/shared/review-workspace-node.ts +230 -0
  181. package/3p/pi-plannotator/packages/shared/review-workspace.ts +436 -0
  182. package/3p/pi-plannotator/packages/shared/semantic-diff-types.ts +76 -0
  183. package/3p/pi-plannotator/packages/shared/semantic-diff.test.ts +322 -0
  184. package/3p/pi-plannotator/packages/shared/semantic-diff.ts +520 -0
  185. package/3p/pi-plannotator/packages/shared/storage.ts +378 -0
  186. package/3p/pi-plannotator/packages/shared/tour.ts +61 -0
  187. package/3p/pi-plannotator/packages/shared/tsconfig.json +15 -0
  188. package/3p/pi-plannotator/packages/shared/types.ts +29 -0
  189. package/3p/pi-plannotator/packages/shared/url-to-markdown.test.ts +177 -0
  190. package/3p/pi-plannotator/packages/shared/url-to-markdown.ts +351 -0
  191. package/3p/pi-plannotator/packages/shared/vcs-core.test.ts +332 -0
  192. package/3p/pi-plannotator/packages/shared/vcs-core.ts +482 -0
  193. package/3p/pi-plannotator/packages/shared/worktree-pool.test.ts +162 -0
  194. package/3p/pi-plannotator/packages/shared/worktree-pool.ts +103 -0
  195. package/3p/pi-plannotator/packages/shared/worktree.ts +119 -0
  196. package/3p/pi-subagents/package.json +50 -0
  197. package/3p/pi-subagents/src/agent-manager.ts +413 -0
  198. package/3p/pi-subagents/src/agent-runner.ts +502 -0
  199. package/3p/pi-subagents/src/agent-types.ts +248 -0
  200. package/3p/pi-subagents/src/context.ts +58 -0
  201. package/3p/pi-subagents/src/cross-extension-rpc.ts +135 -0
  202. package/3p/pi-subagents/src/custom-agents.ts +137 -0
  203. package/3p/pi-subagents/src/default-agents.ts +144 -0
  204. package/3p/pi-subagents/src/env.ts +33 -0
  205. package/3p/pi-subagents/src/group-join.ts +141 -0
  206. package/3p/pi-subagents/src/index.ts +1811 -0
  207. package/3p/pi-subagents/src/invocation-config.ts +40 -0
  208. package/3p/pi-subagents/src/memory.ts +165 -0
  209. package/3p/pi-subagents/src/model-resolver.ts +81 -0
  210. package/3p/pi-subagents/src/output-file.ts +77 -0
  211. package/3p/pi-subagents/src/prompts.ts +85 -0
  212. package/3p/pi-subagents/src/skill-loader.ts +79 -0
  213. package/3p/pi-subagents/src/types.ts +111 -0
  214. package/3p/pi-subagents/src/ui/agent-widget.ts +496 -0
  215. package/3p/pi-subagents/src/ui/conversation-viewer.ts +250 -0
  216. package/3p/pi-subagents/src/worktree.ts +162 -0
  217. package/3p/pi-tasks/package.json +52 -0
  218. package/3p/pi-tasks/src/auto-clear.ts +91 -0
  219. package/3p/pi-tasks/src/index.ts +1150 -0
  220. package/3p/pi-tasks/src/process-tracker.ts +140 -0
  221. package/3p/pi-tasks/src/reminder-cadence.ts +90 -0
  222. package/3p/pi-tasks/src/task-store.ts +324 -0
  223. package/3p/pi-tasks/src/tasks-config.ts +27 -0
  224. package/3p/pi-tasks/src/types.ts +40 -0
  225. package/3p/pi-tasks/src/ui/settings-menu.ts +152 -0
  226. package/3p/pi-tasks/src/ui/task-widget.ts +296 -0
  227. package/AGENTS.md +28 -0
  228. package/LICENSE +201 -0
  229. package/extensions/orchestrator/agents/brainstorm-reviewer.ts +77 -0
  230. package/extensions/orchestrator/agents/code-reviewer.ts +89 -0
  231. package/extensions/orchestrator/agents/explore.ts +33 -0
  232. package/extensions/orchestrator/agents/librarian.ts +43 -0
  233. package/extensions/orchestrator/agents/plan-reviewer.ts +75 -0
  234. package/extensions/orchestrator/agents/planner.ts +61 -0
  235. package/extensions/orchestrator/agents/registry.ts +156 -0
  236. package/extensions/orchestrator/agents/task.ts +50 -0
  237. package/extensions/orchestrator/agents/tool-routing.ts +84 -0
  238. package/extensions/orchestrator/ast-search.ts +85 -0
  239. package/extensions/orchestrator/cbm.ts +330 -0
  240. package/extensions/orchestrator/command-handlers.test.ts +163 -0
  241. package/extensions/orchestrator/command-handlers.ts +116 -0
  242. package/extensions/orchestrator/commands.test.ts +81 -0
  243. package/extensions/orchestrator/commands.ts +75 -0
  244. package/extensions/orchestrator/config.test.ts +221 -0
  245. package/extensions/orchestrator/config.ts +230 -0
  246. package/extensions/orchestrator/context.test.ts +293 -0
  247. package/extensions/orchestrator/context.ts +206 -0
  248. package/extensions/orchestrator/event-handlers.test.ts +190 -0
  249. package/extensions/orchestrator/event-handlers.ts +1416 -0
  250. package/extensions/orchestrator/exa.ts +104 -0
  251. package/extensions/orchestrator/flant-infra.ts +486 -0
  252. package/extensions/orchestrator/index.ts +80 -0
  253. package/extensions/orchestrator/integration.test.ts +1214 -0
  254. package/extensions/orchestrator/orchestrator.test.ts +252 -0
  255. package/extensions/orchestrator/orchestrator.ts +538 -0
  256. package/extensions/orchestrator/phases/brainstorm.test.ts +15 -0
  257. package/extensions/orchestrator/phases/brainstorm.ts +273 -0
  258. package/extensions/orchestrator/phases/implementation.ts +40 -0
  259. package/extensions/orchestrator/phases/machine.test.ts +293 -0
  260. package/extensions/orchestrator/phases/machine.ts +209 -0
  261. package/extensions/orchestrator/phases/planning.ts +255 -0
  262. package/extensions/orchestrator/phases/review.ts +193 -0
  263. package/extensions/orchestrator/plannotator.ts +56 -0
  264. package/extensions/orchestrator/pp-menu.ts +866 -0
  265. package/extensions/orchestrator/state.test.ts +343 -0
  266. package/extensions/orchestrator/state.ts +237 -0
  267. package/extensions/orchestrator/validate-artifacts.test.ts +88 -0
  268. package/extensions/orchestrator/validate-artifacts.ts +272 -0
  269. package/extensions/orchestrator/vendor.d.ts +26 -0
  270. package/package.json +73 -0
  271. package/scripts/postinstall.sh +18 -0
@@ -0,0 +1,502 @@
1
+ /**
2
+ * agent-runner.ts — Core execution engine: creates sessions, runs agents, collects results.
3
+ */
4
+
5
+ import type { Model } from "@earendil-works/pi-ai";
6
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
7
+ import {
8
+ type AgentSession,
9
+ type AgentSessionEvent,
10
+ createAgentSession,
11
+ DefaultResourceLoader,
12
+ type ExtensionAPI,
13
+ SessionManager,
14
+ SettingsManager,
15
+ } from "@earendil-works/pi-coding-agent";
16
+ import { getAgentConfig, getConfig, getMemoryTools, getReadOnlyMemoryTools, getToolsForType } from "./agent-types.js";
17
+ import { buildParentContext, extractText } from "./context.js";
18
+ import { detectEnv } from "./env.js";
19
+ import { buildMemoryBlock, buildReadOnlyMemoryBlock } from "./memory.js";
20
+ import { buildAgentPrompt, type PromptExtras } from "./prompts.js";
21
+ import { preloadSkills } from "./skill-loader.js";
22
+ import type { SubagentType, ThinkingLevel } from "./types.js";
23
+
24
+ /** Names of tools registered by this extension that subagents must NOT inherit. */
25
+ const EXCLUDED_TOOL_NAMES = ["Agent", "get_subagent_result", "steer_subagent"];
26
+
27
+ /** Default max turns. undefined = unlimited (no turn limit). */
28
+ let defaultMaxTurns: number | undefined;
29
+
30
+ /** Normalize max turns. undefined or 0 = unlimited, otherwise minimum 1. */
31
+ export function normalizeMaxTurns(n: number | undefined): number | undefined {
32
+ if (n == null || n === 0) return undefined;
33
+ return Math.max(1, n);
34
+ }
35
+
36
+ /** Get the default max turns value. undefined = unlimited. */
37
+ export function getDefaultMaxTurns(): number | undefined { return defaultMaxTurns; }
38
+ /** Set the default max turns value. undefined or 0 = unlimited, otherwise minimum 1. */
39
+ export function setDefaultMaxTurns(n: number | undefined): void { defaultMaxTurns = normalizeMaxTurns(n); }
40
+
41
+ /** Additional turns allowed after the soft limit steer message. */
42
+ let graceTurns = 5;
43
+
44
+ /** Get the grace turns value. */
45
+ export function getGraceTurns(): number { return graceTurns; }
46
+ /** Set the grace turns value (minimum 1). */
47
+ export function setGraceTurns(n: number): void { graceTurns = Math.max(1, n); }
48
+
49
+ /**
50
+ * Try to find the right model for an agent type.
51
+ * Priority: explicit option > config.model > parent model.
52
+ */
53
+ function resolveDefaultModel(
54
+ parentModel: Model<any> | undefined,
55
+ registry: { find(provider: string, modelId: string): Model<any> | undefined; getAvailable?(): Model<any>[] },
56
+ configModel?: string,
57
+ ): Model<any> | undefined {
58
+ if (configModel) {
59
+ const slashIdx = configModel.indexOf("/");
60
+ if (slashIdx !== -1) {
61
+ const provider = configModel.slice(0, slashIdx);
62
+ const modelId = configModel.slice(slashIdx + 1);
63
+
64
+ // Build a set of available model keys for fast lookup
65
+ const available = registry.getAvailable?.();
66
+ const availableKeys = available
67
+ ? new Set(available.map((m: any) => `${m.provider}/${m.id}`))
68
+ : undefined;
69
+ const isAvailable = (p: string, id: string) =>
70
+ !availableKeys || availableKeys.has(`${p}/${id}`);
71
+
72
+ const found = registry.find(provider, modelId);
73
+ if (found && isAvailable(provider, modelId)) return found;
74
+ }
75
+ }
76
+
77
+ return parentModel;
78
+ }
79
+
80
+ /** Info about a tool event in the subagent. */
81
+ export interface ToolActivity {
82
+ type: "start" | "end";
83
+ toolName: string;
84
+ }
85
+
86
+ export interface RunOptions {
87
+ /** ExtensionAPI instance — used for pi.exec() instead of execSync. */
88
+ pi: ExtensionAPI;
89
+ model?: Model<any>;
90
+ maxTurns?: number;
91
+ signal?: AbortSignal;
92
+ isolated?: boolean;
93
+ inheritContext?: boolean;
94
+ thinkingLevel?: ThinkingLevel;
95
+ /** Override working directory (e.g. for worktree isolation). */
96
+ cwd?: string;
97
+ /** Called on tool start/end with activity info. */
98
+ onToolActivity?: (activity: ToolActivity) => void;
99
+ /** Called on streaming text deltas from the assistant response. */
100
+ onTextDelta?: (delta: string, fullText: string) => void;
101
+ onSessionCreated?: (session: AgentSession) => void;
102
+ /** Called at the end of each agentic turn with the cumulative count. */
103
+ onTurnEnd?: (turnCount: number) => void;
104
+ /**
105
+ * Called after the agent finishes (session.prompt() returns) but before
106
+ * the run is considered complete. Return a non-empty string to re-prompt
107
+ * the agent with that message. Return undefined/empty to accept completion.
108
+ * Called up to maxValidationRetries times (default: 2).
109
+ */
110
+ validateCompletion?: () => string | undefined;
111
+ maxValidationRetries?: number;
112
+ }
113
+
114
+ export interface RunResult {
115
+ responseText: string;
116
+ session: AgentSession;
117
+ /** True if the agent was hard-aborted (max_turns + grace exceeded). */
118
+ aborted: boolean;
119
+ /** True if the agent was steered to wrap up (hit soft turn limit) but finished in time. */
120
+ steered: boolean;
121
+ }
122
+
123
+ /**
124
+ * Subscribe to a session and collect the last assistant message text.
125
+ * Returns an object with a `getText()` getter and an `unsubscribe` function.
126
+ */
127
+ function collectResponseText(session: AgentSession) {
128
+ let text = "";
129
+ const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
130
+ if (event.type === "message_start") {
131
+ text = "";
132
+ }
133
+ if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
134
+ text += event.assistantMessageEvent.delta;
135
+ }
136
+ });
137
+ return { getText: () => text, unsubscribe };
138
+ }
139
+
140
+ /** Get the last assistant text from the completed session history. */
141
+ function getLastAssistantText(session: AgentSession): string {
142
+ for (let i = session.messages.length - 1; i >= 0; i--) {
143
+ const msg = session.messages[i];
144
+ if (msg.role !== "assistant") continue;
145
+ const text = extractText(msg.content).trim();
146
+ if (text) return text;
147
+ }
148
+ return "";
149
+ }
150
+
151
+ /**
152
+ * Wire an AbortSignal to abort a session.
153
+ * Returns a cleanup function to remove the listener.
154
+ */
155
+ function forwardAbortSignal(session: AgentSession, signal?: AbortSignal): () => void {
156
+ if (!signal) return () => {};
157
+ const onAbort = () => session.abort();
158
+ signal.addEventListener("abort", onAbort, { once: true });
159
+ return () => signal.removeEventListener("abort", onAbort);
160
+ }
161
+
162
+
163
+ export async function runAgent(
164
+ ctx: ExtensionContext,
165
+ type: SubagentType,
166
+ prompt: string,
167
+ options: RunOptions,
168
+ ): Promise<RunResult> {
169
+ const config = getConfig(type);
170
+ const agentConfig = getAgentConfig(type);
171
+
172
+ // Resolve working directory: worktree override > parent cwd
173
+ const effectiveCwd = options.cwd ?? ctx.cwd;
174
+ const subagentSessionKey = Symbol.for("pi-pi:subagent-session");
175
+ const previousSubagentSession = (globalThis as any)[subagentSessionKey];
176
+ const previousDepth = typeof previousSubagentSession === "object" && previousSubagentSession !== null
177
+ ? ((previousSubagentSession as { depth?: number }).depth ?? 0)
178
+ : previousSubagentSession
179
+ ? 1
180
+ : 0;
181
+ const subagentSessionState = { depth: previousDepth + 1 };
182
+ (globalThis as any)[subagentSessionKey] = subagentSessionState;
183
+
184
+ try {
185
+ const env = await detectEnv(options.pi, effectiveCwd);
186
+
187
+ // Get parent system prompt for append-mode agents
188
+ const parentSystemPrompt = ctx.getSystemPrompt();
189
+
190
+ // Build prompt extras (memory, skill preloading)
191
+ const extras: PromptExtras = {};
192
+
193
+ // Resolve extensions/skills: isolated overrides to false
194
+ const extensions = options.isolated ? false : config.extensions;
195
+ const skills = options.isolated ? false : config.skills;
196
+
197
+ // Skill preloading: when skills is string[], preload their content into prompt
198
+ if (Array.isArray(skills)) {
199
+ const loaded = preloadSkills(skills, effectiveCwd);
200
+ if (loaded.length > 0) {
201
+ extras.skillBlocks = loaded;
202
+ }
203
+ }
204
+
205
+ let tools = getToolsForType(type, effectiveCwd);
206
+
207
+ // Persistent memory: detect write capability and branch accordingly.
208
+ // Account for disallowedTools — a tool in the base set but on the denylist is not truly available.
209
+ if (agentConfig?.memory) {
210
+ const existingNames = new Set(tools.map(t => t.name));
211
+ const denied = agentConfig.disallowedTools ? new Set(agentConfig.disallowedTools) : undefined;
212
+ const effectivelyHas = (name: string) => existingNames.has(name) && !denied?.has(name);
213
+ const hasWriteTools = effectivelyHas("write") || effectivelyHas("edit");
214
+
215
+ if (hasWriteTools) {
216
+ const memTools = getMemoryTools(effectiveCwd, existingNames);
217
+ if (memTools.length > 0) tools = [...tools, ...memTools];
218
+ extras.memoryBlock = buildMemoryBlock(agentConfig.name, agentConfig.memory, effectiveCwd);
219
+ } else {
220
+ if (!existingNames.has("read")) {
221
+ const readTools = getReadOnlyMemoryTools(effectiveCwd, existingNames);
222
+ if (readTools.length > 0) tools = [...tools, ...readTools];
223
+ }
224
+ extras.memoryBlock = buildReadOnlyMemoryBlock(agentConfig.name, agentConfig.memory, effectiveCwd);
225
+ }
226
+ }
227
+
228
+ // Build system prompt from agent config
229
+ let systemPrompt: string;
230
+ if (agentConfig) {
231
+ systemPrompt = buildAgentPrompt(agentConfig, effectiveCwd, env, parentSystemPrompt, extras);
232
+ } else {
233
+ systemPrompt = buildAgentPrompt({
234
+ name: type,
235
+ description: "General-purpose agent",
236
+ systemPrompt: "",
237
+ promptMode: "append",
238
+ extensions: true,
239
+ skills: true,
240
+ inheritContext: false,
241
+ runInBackground: false,
242
+ isolated: false,
243
+ }, effectiveCwd, env, parentSystemPrompt, extras);
244
+ }
245
+
246
+ const noSkills = skills === false || Array.isArray(skills);
247
+
248
+ const loader = new DefaultResourceLoader({
249
+ cwd: effectiveCwd,
250
+ agentDir: `${effectiveCwd}/.pi/agents`,
251
+ noExtensions: extensions === false,
252
+ noSkills,
253
+ noPromptTemplates: true,
254
+ noThemes: true,
255
+ systemPromptOverride: () => systemPrompt,
256
+ });
257
+ await loader.reload();
258
+
259
+ const model = options.model ?? resolveDefaultModel(
260
+ ctx.model, ctx.modelRegistry, agentConfig?.model,
261
+ );
262
+
263
+ const thinkingLevel = options.thinkingLevel ?? agentConfig?.thinking;
264
+
265
+ const sessionOpts: Record<string, unknown> = {
266
+ cwd: effectiveCwd,
267
+ sessionManager: SessionManager.inMemory(effectiveCwd),
268
+ settingsManager: SettingsManager.create(effectiveCwd, `${effectiveCwd}/.pi/agents`),
269
+ modelRegistry: ctx.modelRegistry,
270
+ model,
271
+ tools: tools.map((tool) => tool.name),
272
+ customTools: tools,
273
+ resourceLoader: loader,
274
+ };
275
+ if (thinkingLevel) {
276
+ sessionOpts.thinkingLevel = thinkingLevel;
277
+ }
278
+
279
+ let createdSession: Awaited<ReturnType<typeof createAgentSession>> | undefined;
280
+ try {
281
+ createdSession = await createAgentSession(sessionOpts as Parameters<typeof createAgentSession>[0]);
282
+ } catch (error) {
283
+ throw error;
284
+ }
285
+ const { session } = createdSession;
286
+
287
+ const disallowedSet = agentConfig?.disallowedTools
288
+ ? new Set(agentConfig.disallowedTools)
289
+ : undefined;
290
+
291
+ if (extensions !== false) {
292
+ const builtinToolNames = new Set(tools.map(t => t.name));
293
+ const activeTools = session.getActiveToolNames().filter((t) => {
294
+ if (EXCLUDED_TOOL_NAMES.includes(t)) return false;
295
+ if (disallowedSet?.has(t)) return false;
296
+ if (builtinToolNames.has(t)) return true;
297
+ if (Array.isArray(extensions)) {
298
+ return extensions.some(ext => t.startsWith(ext) || t.includes(ext));
299
+ }
300
+ return true;
301
+ });
302
+ session.setActiveToolsByName(activeTools);
303
+ } else if (disallowedSet) {
304
+ const activeTools = session.getActiveToolNames().filter(t => !disallowedSet.has(t));
305
+ session.setActiveToolsByName(activeTools);
306
+ }
307
+
308
+ await session.bindExtensions({
309
+ onError: (err) => {
310
+ options.onToolActivity?.({
311
+ type: "end",
312
+ toolName: `extension-error:${err.extensionPath}`,
313
+ });
314
+ },
315
+ });
316
+
317
+ options.onSessionCreated?.(session);
318
+ try {
319
+ const originalDispose = session.dispose?.bind(session);
320
+ if (originalDispose) {
321
+ session.dispose = (() => {
322
+ return originalDispose();
323
+ }) as typeof session.dispose;
324
+ }
325
+ } catch {}
326
+
327
+ let turnCount = 0;
328
+ const maxTurns = normalizeMaxTurns(options.maxTurns ?? agentConfig?.maxTurns ?? defaultMaxTurns);
329
+ let softLimitReached = false;
330
+ let aborted = false;
331
+ let lastTurnError: string | undefined;
332
+
333
+ let currentMessageText = "";
334
+ const unsubTurns = session.subscribe((event: AgentSessionEvent) => {
335
+ if (event.type === "session_shutdown") {
336
+ }
337
+ if (event.type === "agent_start") {
338
+ }
339
+ if (event.type === "turn_start") {
340
+ }
341
+ if (event.type === "message_start") {
342
+ }
343
+ if (event.type === "tool_execution_start") {
344
+ }
345
+ if (event.type === "turn_end") {
346
+ turnCount++;
347
+ const msg = (event as any).message;
348
+ if (msg?.stopReason === "error") {
349
+ lastTurnError = msg.errorMessage || "Model API error";
350
+ }
351
+ options.onTurnEnd?.(turnCount);
352
+ if (maxTurns != null) {
353
+ if (!softLimitReached && turnCount >= maxTurns) {
354
+ softLimitReached = true;
355
+ session.steer("You have reached your turn limit. Wrap up immediately — provide your final answer now.");
356
+ } else if (softLimitReached && turnCount >= maxTurns + graceTurns) {
357
+ aborted = true;
358
+ session.abort();
359
+ }
360
+ }
361
+ }
362
+ if (event.type === "message_start") {
363
+ currentMessageText = "";
364
+ }
365
+ if (event.type === "message_update" && event.assistantMessageEvent.type === "text_delta") {
366
+ currentMessageText += event.assistantMessageEvent.delta;
367
+ options.onTextDelta?.(event.assistantMessageEvent.delta, currentMessageText);
368
+ }
369
+ if (event.type === "tool_execution_start") {
370
+ options.onToolActivity?.({ type: "start", toolName: event.toolName });
371
+ }
372
+ if (event.type === "tool_execution_end") {
373
+ options.onToolActivity?.({ type: "end", toolName: event.toolName });
374
+ }
375
+ });
376
+
377
+ const collector = collectResponseText(session);
378
+ const cleanupAbort = forwardAbortSignal(session, options.signal);
379
+
380
+ let effectivePrompt = prompt;
381
+ if (options.inheritContext) {
382
+ const parentContext = buildParentContext(ctx);
383
+ if (parentContext) {
384
+ effectivePrompt = parentContext + prompt;
385
+ }
386
+ }
387
+
388
+ try {
389
+ await session.prompt(effectivePrompt);
390
+
391
+ if (options.validateCompletion && !aborted) {
392
+ const maxRetries = options.maxValidationRetries ?? 2;
393
+ for (let attempt = 0; attempt < maxRetries; attempt++) {
394
+ const error = options.validateCompletion();
395
+ if (!error) break;
396
+ await session.prompt(error);
397
+ if (aborted) break;
398
+ }
399
+ }
400
+ } finally {
401
+ unsubTurns();
402
+ collector.unsubscribe();
403
+ cleanupAbort();
404
+ }
405
+
406
+ if (lastTurnError && turnCount <= 1) {
407
+ throw new Error(lastTurnError);
408
+ }
409
+
410
+ const responseText = collector.getText().trim() || getLastAssistantText(session);
411
+ if (lastTurnError) {
412
+ const errorSuffix = `\n\n[Agent error on final turn: ${lastTurnError}]`;
413
+ return { responseText: (responseText || "No output.") + errorSuffix, session, aborted, steered: softLimitReached };
414
+ }
415
+ return { responseText, session, aborted, steered: softLimitReached };
416
+ } finally {
417
+ const currentDepth = typeof (globalThis as any)[subagentSessionKey] === "object" && (globalThis as any)[subagentSessionKey] !== null
418
+ ? ((((globalThis as any)[subagentSessionKey]) as { depth?: number }).depth ?? subagentSessionState.depth)
419
+ : subagentSessionState.depth;
420
+ const nextDepth = Math.max(0, currentDepth - 1);
421
+ if (nextDepth === 0) {
422
+ if (previousSubagentSession === undefined) {
423
+ delete (globalThis as any)[subagentSessionKey];
424
+ } else {
425
+ (globalThis as any)[subagentSessionKey] = previousSubagentSession;
426
+ }
427
+ } else {
428
+ (globalThis as any)[subagentSessionKey] = { depth: nextDepth };
429
+ }
430
+ }
431
+ }
432
+
433
+ /**
434
+ * Send a new prompt to an existing session (resume).
435
+ */
436
+ export async function resumeAgent(
437
+ session: AgentSession,
438
+ prompt: string,
439
+ options: { onToolActivity?: (activity: ToolActivity) => void; signal?: AbortSignal } = {},
440
+ ): Promise<string> {
441
+ const collector = collectResponseText(session);
442
+ const cleanupAbort = forwardAbortSignal(session, options.signal);
443
+
444
+ const unsubToolUse = options.onToolActivity
445
+ ? session.subscribe((event: AgentSessionEvent) => {
446
+ if (event.type === "tool_execution_start") options.onToolActivity!({ type: "start", toolName: event.toolName });
447
+ if (event.type === "tool_execution_end") options.onToolActivity!({ type: "end", toolName: event.toolName });
448
+ })
449
+ : () => {};
450
+
451
+ try {
452
+ await session.prompt(prompt);
453
+ } finally {
454
+ collector.unsubscribe();
455
+ unsubToolUse();
456
+ cleanupAbort();
457
+ }
458
+
459
+ return collector.getText().trim() || getLastAssistantText(session);
460
+ }
461
+
462
+ /**
463
+ * Send a steering message to a running subagent.
464
+ * The message will interrupt the agent after its current tool execution.
465
+ */
466
+ export async function steerAgent(
467
+ session: AgentSession,
468
+ message: string,
469
+ ): Promise<void> {
470
+ await session.steer(message);
471
+ }
472
+
473
+ /**
474
+ * Get the subagent's conversation messages as formatted text.
475
+ */
476
+ export function getAgentConversation(session: AgentSession): string {
477
+ const parts: string[] = [];
478
+
479
+ for (const msg of session.messages) {
480
+ if (msg.role === "user") {
481
+ const text = typeof msg.content === "string"
482
+ ? msg.content
483
+ : extractText(msg.content);
484
+ if (text.trim()) parts.push(`[User]: ${text.trim()}`);
485
+ } else if (msg.role === "assistant") {
486
+ const textParts: string[] = [];
487
+ const toolCalls: string[] = [];
488
+ for (const c of msg.content) {
489
+ if (c.type === "text" && c.text) textParts.push(c.text);
490
+ else if (c.type === "toolCall") toolCalls.push(` Tool: ${(c as any).name ?? (c as any).toolName ?? "unknown"}`);
491
+ }
492
+ if (textParts.length > 0) parts.push(`[Assistant]: ${textParts.join("\n")}`);
493
+ if (toolCalls.length > 0) parts.push(`[Tool Calls]:\n${toolCalls.join("\n")}`);
494
+ } else if (msg.role === "toolResult") {
495
+ const text = extractText(msg.content);
496
+ const truncated = text.length > 200 ? text.slice(0, 200) + "..." : text;
497
+ parts.push(`[Tool Result (${msg.toolName})]: ${truncated}`);
498
+ }
499
+ }
500
+
501
+ return parts.join("\n\n");
502
+ }