@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,40 @@
1
+ import type { AgentConfig, IsolationMode, JoinMode, ThinkingLevel } from "./types.js";
2
+
3
+ interface AgentInvocationParams {
4
+ model?: string;
5
+ thinking?: string;
6
+ max_turns?: number;
7
+ run_in_background?: boolean;
8
+ inherit_context?: boolean;
9
+ isolated?: boolean;
10
+ isolation?: IsolationMode;
11
+ }
12
+
13
+ export function resolveAgentInvocationConfig(
14
+ agentConfig: AgentConfig | undefined,
15
+ params: AgentInvocationParams,
16
+ ): {
17
+ modelInput?: string;
18
+ modelFromParams: boolean;
19
+ thinking?: ThinkingLevel;
20
+ maxTurns?: number;
21
+ inheritContext: boolean;
22
+ runInBackground: boolean;
23
+ isolated: boolean;
24
+ isolation?: IsolationMode;
25
+ } {
26
+ return {
27
+ modelInput: agentConfig?.model ?? params.model,
28
+ modelFromParams: agentConfig?.model == null && params.model != null,
29
+ thinking: (agentConfig?.thinking ?? params.thinking) as ThinkingLevel | undefined,
30
+ maxTurns: agentConfig?.maxTurns ?? params.max_turns,
31
+ inheritContext: agentConfig?.inheritContext ?? params.inherit_context ?? false,
32
+ runInBackground: agentConfig?.runInBackground ?? params.run_in_background ?? false,
33
+ isolated: agentConfig?.isolated ?? params.isolated ?? false,
34
+ isolation: agentConfig?.isolation ?? params.isolation,
35
+ };
36
+ }
37
+
38
+ export function resolveJoinMode(defaultJoinMode: JoinMode, runInBackground: boolean): JoinMode | undefined {
39
+ return runInBackground ? defaultJoinMode : undefined;
40
+ }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * memory.ts — Persistent agent memory: per-agent memory directories that persist across sessions.
3
+ *
4
+ * Memory scopes:
5
+ * - "user" → ~/.pi/agent-memory/{agent-name}/
6
+ * - "project" → .pi/agent-memory/{agent-name}/
7
+ * - "local" → .pi/agent-memory-local/{agent-name}/
8
+ */
9
+
10
+ import { existsSync, lstatSync, mkdirSync, readFileSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { join, } from "node:path";
13
+ import type { MemoryScope } from "./types.js";
14
+
15
+ /** Maximum lines to read from MEMORY.md */
16
+ const MAX_MEMORY_LINES = 200;
17
+
18
+ /**
19
+ * Returns true if a name contains characters not allowed in agent/skill names.
20
+ * Uses a whitelist: only alphanumeric, hyphens, underscores, and dots (no leading dot).
21
+ */
22
+ export function isUnsafeName(name: string): boolean {
23
+ if (!name || name.length > 128) return true;
24
+ return !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name);
25
+ }
26
+
27
+ /**
28
+ * Returns true if the given path is a symlink (defense against symlink attacks).
29
+ */
30
+ export function isSymlink(filePath: string): boolean {
31
+ try {
32
+ return lstatSync(filePath).isSymbolicLink();
33
+ } catch {
34
+ return false;
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Safely read a file, rejecting symlinks.
40
+ * Returns undefined if the file doesn't exist, is a symlink, or can't be read.
41
+ */
42
+ export function safeReadFile(filePath: string): string | undefined {
43
+ if (!existsSync(filePath)) return undefined;
44
+ if (isSymlink(filePath)) return undefined;
45
+ try {
46
+ return readFileSync(filePath, "utf-8");
47
+ } catch {
48
+ return undefined;
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Resolve the memory directory path for a given agent + scope + cwd.
54
+ * Throws if agentName contains path traversal characters.
55
+ */
56
+ export function resolveMemoryDir(agentName: string, scope: MemoryScope, cwd: string): string {
57
+ if (isUnsafeName(agentName)) {
58
+ throw new Error(`Unsafe agent name for memory directory: "${agentName}"`);
59
+ }
60
+ switch (scope) {
61
+ case "user":
62
+ return join(homedir(), ".pi", "agent-memory", agentName);
63
+ case "project":
64
+ return join(cwd, ".pi", "agent-memory", agentName);
65
+ case "local":
66
+ return join(cwd, ".pi", "agent-memory-local", agentName);
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Ensure the memory directory exists, creating it if needed.
72
+ * Refuses to create directories if any component in the path is a symlink
73
+ * to prevent symlink-based directory traversal attacks.
74
+ */
75
+ export function ensureMemoryDir(memoryDir: string): void {
76
+ // If the directory already exists, verify it's not a symlink
77
+ if (existsSync(memoryDir)) {
78
+ if (isSymlink(memoryDir)) {
79
+ throw new Error(`Refusing to use symlinked memory directory: ${memoryDir}`);
80
+ }
81
+ return;
82
+ }
83
+ mkdirSync(memoryDir, { recursive: true });
84
+ }
85
+
86
+ /**
87
+ * Read the first N lines of MEMORY.md from the memory directory, if it exists.
88
+ * Returns undefined if no MEMORY.md exists or if the path is a symlink.
89
+ */
90
+ export function readMemoryIndex(memoryDir: string): string | undefined {
91
+ // Reject symlinked memory directories
92
+ if (isSymlink(memoryDir)) return undefined;
93
+
94
+ const memoryFile = join(memoryDir, "MEMORY.md");
95
+ const content = safeReadFile(memoryFile);
96
+ if (content === undefined) return undefined;
97
+
98
+ const lines = content.split("\n");
99
+ if (lines.length > MAX_MEMORY_LINES) {
100
+ return lines.slice(0, MAX_MEMORY_LINES).join("\n") + "\n... (truncated at 200 lines)";
101
+ }
102
+ return content;
103
+ }
104
+
105
+ /**
106
+ * Build the memory block to inject into the agent's system prompt.
107
+ * Also ensures the memory directory exists (creates it if needed).
108
+ */
109
+ export function buildMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string {
110
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
111
+ // Create the memory directory so the agent can immediately write to it
112
+ ensureMemoryDir(memoryDir);
113
+
114
+ const existingMemory = readMemoryIndex(memoryDir);
115
+
116
+ const header = `# Agent Memory
117
+
118
+ You have a persistent memory directory at: ${memoryDir}/
119
+ Memory scope: ${scope}
120
+
121
+ This memory persists across sessions. Use it to build up knowledge over time.`;
122
+
123
+ const memoryContent = existingMemory
124
+ ? `\n\n## Current MEMORY.md\n${existingMemory}`
125
+ : `\n\nNo MEMORY.md exists yet. Create one at ${join(memoryDir, "MEMORY.md")} to start building persistent memory.`;
126
+
127
+ const instructions = `
128
+
129
+ ## Memory Instructions
130
+ - MEMORY.md is an index file — keep it concise (under 200 lines). Lines after 200 are truncated.
131
+ - Store detailed memories in separate files within ${memoryDir}/ and link to them from MEMORY.md.
132
+ - Each memory file should use this frontmatter format:
133
+ \`\`\`markdown
134
+ ---
135
+ name: <memory name>
136
+ description: <one-line description>
137
+ type: <user|feedback|project|reference>
138
+ ---
139
+ <memory content>
140
+ \`\`\`
141
+ - Update or remove memories that become outdated. Check for existing memories before creating duplicates.
142
+ - You have Read, Write, and Edit tools available for managing memory files.`;
143
+
144
+ return header + memoryContent + instructions;
145
+ }
146
+
147
+ /**
148
+ * Build a read-only memory block for agents that lack write/edit tools.
149
+ * Does NOT create the memory directory — agents can only consume existing memory.
150
+ */
151
+ export function buildReadOnlyMemoryBlock(agentName: string, scope: MemoryScope, cwd: string): string {
152
+ const memoryDir = resolveMemoryDir(agentName, scope, cwd);
153
+ const existingMemory = readMemoryIndex(memoryDir);
154
+
155
+ const header = `# Agent Memory (read-only)
156
+
157
+ Memory scope: ${scope}
158
+ You have read-only access to memory. You can reference existing memories but cannot create or modify them.`;
159
+
160
+ const memoryContent = existingMemory
161
+ ? `\n\n## Current MEMORY.md\n${existingMemory}`
162
+ : `\n\nNo memory is available yet. Other agents or sessions with write access can create memories for you to consume.`;
163
+
164
+ return header + memoryContent;
165
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Model resolution: exact match ("provider/modelId") with fuzzy fallback.
3
+ */
4
+
5
+ export interface ModelEntry {
6
+ id: string;
7
+ name: string;
8
+ provider: string;
9
+ }
10
+
11
+ export interface ModelRegistry {
12
+ find(provider: string, modelId: string): any;
13
+ getAll(): any[];
14
+ getAvailable?(): any[];
15
+ }
16
+
17
+ /**
18
+ * Resolve a model string to a Model instance.
19
+ * Tries exact match first ("provider/modelId"), then fuzzy match against all available models.
20
+ * Returns the Model on success, or an error message string on failure.
21
+ */
22
+ export function resolveModel(
23
+ input: string,
24
+ registry: ModelRegistry,
25
+ ): any | string {
26
+ // Available models (those with auth configured)
27
+ const all = (registry.getAvailable?.() ?? registry.getAll()) as ModelEntry[];
28
+ const availableSet = new Set(all.map(m => `${m.provider}/${m.id}`.toLowerCase()));
29
+
30
+ // 1. Exact match: "provider/modelId" — only if available (has auth)
31
+ const slashIdx = input.indexOf("/");
32
+ if (slashIdx !== -1) {
33
+ const provider = input.slice(0, slashIdx);
34
+ const modelId = input.slice(slashIdx + 1);
35
+ if (availableSet.has(input.toLowerCase())) {
36
+ const found = registry.find(provider, modelId);
37
+ if (found) return found;
38
+ }
39
+ }
40
+
41
+ // 2. Fuzzy match against available models
42
+ const query = input.toLowerCase();
43
+
44
+ // Score each model: prefer exact id match > id contains > name contains > provider+id contains
45
+ let bestMatch: ModelEntry | undefined;
46
+ let bestScore = 0;
47
+
48
+ for (const m of all) {
49
+ const id = m.id.toLowerCase();
50
+ const name = m.name.toLowerCase();
51
+ const full = `${m.provider}/${m.id}`.toLowerCase();
52
+
53
+ let score = 0;
54
+ if (id === query || full === query) {
55
+ score = 100; // exact
56
+ } else if (id.includes(query) || full.includes(query)) {
57
+ score = 60 + (query.length / id.length) * 30; // substring, prefer tighter matches
58
+ } else if (name.includes(query)) {
59
+ score = 40 + (query.length / name.length) * 20;
60
+ } else if (query.split(/[\s\-/]+/).every(part => id.includes(part) || name.includes(part) || m.provider.toLowerCase().includes(part))) {
61
+ score = 20; // all parts present somewhere
62
+ }
63
+
64
+ if (score > bestScore) {
65
+ bestScore = score;
66
+ bestMatch = m;
67
+ }
68
+ }
69
+
70
+ if (bestMatch && bestScore >= 20) {
71
+ const found = registry.find(bestMatch.provider, bestMatch.id);
72
+ if (found) return found;
73
+ }
74
+
75
+ // 3. No match — list available models
76
+ const modelList = all
77
+ .map(m => ` ${m.provider}/${m.id}`)
78
+ .sort()
79
+ .join("\n");
80
+ return `Model not found: "${input}".\n\nAvailable models:\n${modelList}`;
81
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * output-file.ts — Streaming JSONL output file for agent transcripts.
3
+ *
4
+ * Creates a per-agent output file that streams conversation turns as JSONL,
5
+ * matching Claude Code's task output file format.
6
+ */
7
+
8
+ import { appendFileSync, chmodSync, mkdirSync, writeFileSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+ import type { AgentSession, AgentSessionEvent } from "@earendil-works/pi-coding-agent";
12
+
13
+ /** Create the output file path, ensuring the directory exists.
14
+ * Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks/{agentId}.output */
15
+ export function createOutputFilePath(cwd: string, agentId: string, sessionId: string): string {
16
+ const encoded = cwd.replace(/\//g, "-").replace(/^-/, "");
17
+ const root = join(tmpdir(), `pi-subagents-${process.getuid?.() ?? 0}`);
18
+ mkdirSync(root, { recursive: true, mode: 0o700 });
19
+ chmodSync(root, 0o700);
20
+ const dir = join(root, encoded, sessionId, "tasks");
21
+ mkdirSync(dir, { recursive: true });
22
+ return join(dir, `${agentId}.output`);
23
+ }
24
+
25
+ /** Write the initial user prompt entry. */
26
+ export function writeInitialEntry(path: string, agentId: string, prompt: string, cwd: string): void {
27
+ const entry = {
28
+ isSidechain: true,
29
+ agentId,
30
+ type: "user",
31
+ message: { role: "user", content: prompt },
32
+ timestamp: new Date().toISOString(),
33
+ cwd,
34
+ };
35
+ writeFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
36
+ }
37
+
38
+ /**
39
+ * Subscribe to session events and flush new messages to the output file on each turn_end.
40
+ * Returns a cleanup function that does a final flush and unsubscribes.
41
+ */
42
+ export function streamToOutputFile(
43
+ session: AgentSession,
44
+ path: string,
45
+ agentId: string,
46
+ cwd: string,
47
+ ): () => void {
48
+ let writtenCount = 1; // initial user prompt already written
49
+
50
+ const flush = () => {
51
+ const messages = session.messages;
52
+ while (writtenCount < messages.length) {
53
+ const msg = messages[writtenCount];
54
+ const entry = {
55
+ isSidechain: true,
56
+ agentId,
57
+ type: msg.role === "assistant" ? "assistant" : msg.role === "user" ? "user" : "toolResult",
58
+ message: msg,
59
+ timestamp: new Date().toISOString(),
60
+ cwd,
61
+ };
62
+ try {
63
+ appendFileSync(path, JSON.stringify(entry) + "\n", "utf-8");
64
+ } catch { /* ignore write errors */ }
65
+ writtenCount++;
66
+ }
67
+ };
68
+
69
+ const unsubscribe = session.subscribe((event: AgentSessionEvent) => {
70
+ if (event.type === "turn_end") flush();
71
+ });
72
+
73
+ return () => {
74
+ flush();
75
+ unsubscribe();
76
+ };
77
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * prompts.ts — System prompt builder for agents.
3
+ */
4
+
5
+ import type { AgentConfig, EnvInfo } from "./types.js";
6
+
7
+ /** Extra sections to inject into the system prompt (memory, skills, etc.). */
8
+ export interface PromptExtras {
9
+ /** Persistent memory content to inject (first 200 lines of MEMORY.md + instructions). */
10
+ memoryBlock?: string;
11
+ /** Preloaded skill contents to inject. */
12
+ skillBlocks?: { name: string; content: string }[];
13
+ }
14
+
15
+ /**
16
+ * Build the system prompt for an agent from its config.
17
+ *
18
+ * - "replace" mode: env header + config.systemPrompt (full control, no parent identity)
19
+ * - "append" mode: env header + parent system prompt + sub-agent context + config.systemPrompt
20
+ * - "append" with empty systemPrompt: pure parent clone
21
+ *
22
+ * @param parentSystemPrompt The parent agent's effective system prompt (for append mode).
23
+ * @param extras Optional extra sections to inject (memory, preloaded skills).
24
+ */
25
+ export function buildAgentPrompt(
26
+ config: AgentConfig,
27
+ cwd: string,
28
+ env: EnvInfo,
29
+ parentSystemPrompt?: string,
30
+ extras?: PromptExtras,
31
+ ): string {
32
+ const envBlock = `# Environment
33
+ Working directory: ${cwd}
34
+ ${env.isGitRepo ? `Git repository: yes\nBranch: ${env.branch}` : "Not a git repository"}
35
+ Platform: ${env.platform}`;
36
+
37
+ // Build optional extras suffix
38
+ const extraSections: string[] = [];
39
+ if (extras?.memoryBlock) {
40
+ extraSections.push(extras.memoryBlock);
41
+ }
42
+ if (extras?.skillBlocks?.length) {
43
+ for (const skill of extras.skillBlocks) {
44
+ extraSections.push(`\n# Preloaded Skill: ${skill.name}\n${skill.content}`);
45
+ }
46
+ }
47
+ const extrasSuffix = extraSections.length > 0 ? "\n\n" + extraSections.join("\n") : "";
48
+
49
+ if (config.promptMode === "append") {
50
+ const identity = parentSystemPrompt || genericBase;
51
+
52
+ const bridge = `<sub_agent_context>
53
+ You are operating as a sub-agent invoked to handle a specific task.
54
+ - Use the read tool instead of cat/head/tail
55
+ - Use the edit tool instead of sed/awk
56
+ - Use the write tool instead of echo/heredoc
57
+ - Use the find tool instead of bash find/ls for file search
58
+ - Use the grep tool instead of bash grep/rg for content search
59
+ - Make independent tool calls in parallel
60
+ - Use absolute file paths
61
+ - Do not use emojis
62
+ - Be concise but complete
63
+ </sub_agent_context>`;
64
+
65
+ const customSection = config.systemPrompt?.trim()
66
+ ? `\n\n<agent_instructions>\n${config.systemPrompt}\n</agent_instructions>`
67
+ : "";
68
+
69
+ return envBlock + "\n\n<inherited_system_prompt>\n" + identity + "\n</inherited_system_prompt>\n\n" + bridge + customSection + extrasSuffix;
70
+ }
71
+
72
+ // "replace" mode — env header + the config's full system prompt
73
+ const replaceHeader = `You are a pi coding agent sub-agent.
74
+ You have been invoked to handle a specific task autonomously.
75
+
76
+ ${envBlock}`;
77
+
78
+ return replaceHeader + "\n\n" + config.systemPrompt + extrasSuffix;
79
+ }
80
+
81
+ /** Fallback base prompt when parent system prompt is unavailable in append mode. */
82
+ const genericBase = `# Role
83
+ You are a general-purpose coding agent for complex, multi-step tasks.
84
+ You have full access to read, write, edit files, and execute commands.
85
+ Do what has been asked; nothing more, nothing less.`;
@@ -0,0 +1,79 @@
1
+ /**
2
+ * skill-loader.ts — Preload specific skill files and inject their content into the system prompt.
3
+ *
4
+ * When skills is a string[], reads each named skill from .pi/skills/ or ~/.pi/skills/
5
+ * and returns their content for injection into the agent's system prompt.
6
+ */
7
+
8
+ import { homedir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { isUnsafeName, safeReadFile } from "./memory.js";
11
+
12
+ export interface PreloadedSkill {
13
+ name: string;
14
+ content: string;
15
+ }
16
+
17
+ /**
18
+ * Attempt to load named skills from project and global skill directories.
19
+ * Looks for: <dir>/<name>.md, <dir>/<name>.txt, <dir>/<name>
20
+ *
21
+ * @param skillNames List of skill names to preload.
22
+ * @param cwd Working directory for project-level skills.
23
+ * @returns Array of loaded skills (missing skills are skipped with a warning comment).
24
+ */
25
+ export function preloadSkills(skillNames: string[], cwd: string): PreloadedSkill[] {
26
+ const results: PreloadedSkill[] = [];
27
+
28
+ for (const name of skillNames) {
29
+ // Unlike memory (which throws on unsafe names because it's part of agent setup),
30
+ // skills are optional — skip gracefully to avoid blocking agent startup.
31
+ if (isUnsafeName(name)) {
32
+ results.push({ name, content: `(Skill "${name}" skipped: name contains path traversal characters)` });
33
+ continue;
34
+ }
35
+ const content = findAndReadSkill(name, cwd);
36
+ if (content !== undefined) {
37
+ results.push({ name, content });
38
+ } else {
39
+ // Include a note about missing skills so the agent knows it was requested but not found
40
+ results.push({ name, content: `(Skill "${name}" not found in .pi/skills/ or ~/.pi/skills/)` });
41
+ }
42
+ }
43
+
44
+ return results;
45
+ }
46
+
47
+ /**
48
+ * Search for a skill file in project and global directories.
49
+ * Project-level takes priority over global.
50
+ */
51
+ function findAndReadSkill(name: string, cwd: string): string | undefined {
52
+ const projectDir = join(cwd, ".pi", "skills");
53
+ const globalDir = join(homedir(), ".pi", "skills");
54
+
55
+ // Try project first, then global
56
+ for (const dir of [projectDir, globalDir]) {
57
+ const content = tryReadSkillFile(dir, name);
58
+ if (content !== undefined) return content;
59
+ }
60
+
61
+ return undefined;
62
+ }
63
+
64
+ /**
65
+ * Try to read a skill file from a directory.
66
+ * Tries extensions in order: .md, .txt, (no extension)
67
+ */
68
+ function tryReadSkillFile(dir: string, name: string): string | undefined {
69
+ const extensions = [".md", ".txt", ""];
70
+
71
+ for (const ext of extensions) {
72
+ const path = join(dir, name + ext);
73
+ // safeReadFile rejects symlinks to prevent reading arbitrary files
74
+ const content = safeReadFile(path);
75
+ if (content !== undefined) return content.trim();
76
+ }
77
+
78
+ return undefined;
79
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * types.ts — Type definitions for the subagent system.
3
+ */
4
+
5
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
6
+ import type { AgentSession } from "@earendil-works/pi-coding-agent";
7
+
8
+ export type { ThinkingLevel };
9
+
10
+ /** Agent type: any string name (built-in defaults or user-defined). */
11
+ export type SubagentType = string;
12
+
13
+ /** Names of the three embedded default agents. */
14
+ export const DEFAULT_AGENT_NAMES = ["general-purpose", "Explore", "Plan"] as const;
15
+
16
+ /** Memory scope for persistent agent memory. */
17
+ export type MemoryScope = "user" | "project" | "local";
18
+
19
+ /** Isolation mode for agent execution. */
20
+ export type IsolationMode = "worktree";
21
+
22
+ /** Unified agent configuration — used for both default and user-defined agents. */
23
+ export interface AgentConfig {
24
+ name: string;
25
+ displayName?: string;
26
+ description: string;
27
+ builtinToolNames?: string[];
28
+ /** Tool denylist — these tools are removed even if `builtinToolNames` or extensions include them. */
29
+ disallowedTools?: string[];
30
+ /** true = inherit all, string[] = only listed, false = none */
31
+ extensions: true | string[] | false;
32
+ /** true = inherit all, string[] = only listed, false = none */
33
+ skills: true | string[] | false;
34
+ model?: string;
35
+ thinking?: ThinkingLevel;
36
+ maxTurns?: number;
37
+ systemPrompt: string;
38
+ promptMode: "replace" | "append";
39
+ /** Default for spawn: fork parent conversation. undefined = caller decides. */
40
+ inheritContext?: boolean;
41
+ /** Default for spawn: run in background. undefined = caller decides. */
42
+ runInBackground?: boolean;
43
+ /** Default for spawn: no extension tools. undefined = caller decides. */
44
+ isolated?: boolean;
45
+ /** Persistent memory scope — agents with memory get a persistent directory and MEMORY.md */
46
+ memory?: MemoryScope;
47
+ /** Isolation mode — "worktree" runs the agent in a temporary git worktree */
48
+ isolation?: IsolationMode;
49
+ /** true = this is an embedded default agent (informational) */
50
+ isDefault?: boolean;
51
+ /** false = agent is hidden from the registry */
52
+ enabled?: boolean;
53
+ /** Where this agent was loaded from */
54
+ source?: "default" | "project" | "global";
55
+ }
56
+
57
+ export type JoinMode = 'async' | 'group' | 'smart';
58
+
59
+ export interface AgentRecord {
60
+ id: string;
61
+ type: SubagentType;
62
+ description: string;
63
+ status: "queued" | "running" | "completed" | "steered" | "aborted" | "stopped" | "error";
64
+ result?: string;
65
+ error?: string;
66
+ toolUses: number;
67
+ startedAt: number;
68
+ completedAt?: number;
69
+ session?: AgentSession;
70
+ abortController?: AbortController;
71
+ promise?: Promise<string>;
72
+ groupId?: string;
73
+ joinMode?: JoinMode;
74
+ /** Set when result was already consumed via get_subagent_result — suppresses completion notification. */
75
+ resultConsumed?: boolean;
76
+ /** Steering messages queued before the session was ready. */
77
+ pendingSteers?: string[];
78
+ /** Worktree info if the agent is running in an isolated worktree. */
79
+ worktree?: { path: string; branch: string };
80
+ /** Worktree cleanup result after agent completion. */
81
+ worktreeResult?: { hasChanges: boolean; branch?: string };
82
+ /** The tool_use_id from the original Agent tool call. */
83
+ toolCallId?: string;
84
+ /** Path to the streaming output transcript file. */
85
+ outputFile?: string;
86
+ /** Cleanup function for the output file stream subscription. */
87
+ outputCleanup?: () => void;
88
+ }
89
+
90
+ /** Details attached to custom notification messages for visual rendering. */
91
+ export interface NotificationDetails {
92
+ id: string;
93
+ description: string;
94
+ status: string;
95
+ toolUses: number;
96
+ turnCount: number;
97
+ maxTurns?: number;
98
+ totalTokens: number;
99
+ durationMs: number;
100
+ outputFile?: string;
101
+ error?: string;
102
+ resultPreview: string;
103
+ /** Additional agents in a group notification. */
104
+ others?: NotificationDetails[];
105
+ }
106
+
107
+ export interface EnvInfo {
108
+ isGitRepo: boolean;
109
+ branch: string;
110
+ platform: string;
111
+ }