@evandu/super-pi-server 0.0.0-stage → 0.1.259

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 (370) hide show
  1. package/README.md +248 -3
  2. package/agents/code-auditor.md +64 -0
  3. package/agents/code-designer.md +64 -0
  4. package/agents/coder.md +24 -0
  5. package/agents/critic.md +24 -0
  6. package/agents/document-organizer.md +48 -0
  7. package/agents/patcher.md +27 -0
  8. package/agents/planner.md +30 -0
  9. package/agents/project-leader.md +28 -0
  10. package/agents/reviewer.md +27 -0
  11. package/agents/scout.md +27 -0
  12. package/agents/solution-designer.md +62 -0
  13. package/agents/super-pi-documents/index.ts +92 -0
  14. package/agents/super-pi-feishu/index.ts +88 -0
  15. package/agents/super-pi-knowledge/index.ts +70 -0
  16. package/agents/super-pi-managed-model/index.ts +9 -0
  17. package/agents/super-pi-memory/index.ts +75 -0
  18. package/agents/super-pi-native-tools/index.ts +1 -0
  19. package/agents/super-pi-task/core.ts +2262 -0
  20. package/agents/super-pi-task/index.ts +814 -0
  21. package/agents/super-pi-task/workflow-schema.ts +34 -0
  22. package/agents/super-pi-web/index.ts +32 -0
  23. package/agents/verifier.md +25 -0
  24. package/assets/fonts/LICENSE +92 -0
  25. package/assets/fonts/NotoSansSC-Bold.otf +0 -0
  26. package/assets/fonts/NotoSansSC-Regular.otf +0 -0
  27. package/assets/knowledge-model/README.md +37 -0
  28. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/config.json +31 -0
  29. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/onnx/model_quantized.onnx +0 -0
  30. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/special_tokens_map.json +7 -0
  31. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer.json +21278 -0
  32. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/tokenizer_config.json +15 -0
  33. package/assets/knowledge-model/Xenova/bge-small-zh-v1.5/vocab.txt +21128 -0
  34. package/bin/npm-prefix.d.ts +1 -0
  35. package/bin/npm-prefix.js +10 -0
  36. package/bin/super-pi.js +349 -0
  37. package/dist/client/.super-pi-client-sources.json +82 -0
  38. package/dist/client/assets/CodeMirrorEditor-mi9rGUce.js +2 -0
  39. package/dist/client/assets/GitDiffEditor-CpoDDQrA.css +1 -0
  40. package/dist/client/assets/GitDiffEditor-FQBfGxOY.js +29 -0
  41. package/dist/client/assets/diff-ChtP43wD.js +1 -0
  42. package/dist/client/assets/dist-AW5lyI3I.js +1 -0
  43. package/dist/client/assets/dist-B3-a6uF0.js +7 -0
  44. package/dist/client/assets/dist-BGxkyh6e.js +1 -0
  45. package/dist/client/assets/dist-BJxfd7yb.js +11 -0
  46. package/dist/client/assets/dist-BRVQKlcp.js +1 -0
  47. package/dist/client/assets/dist-BV64A9Ji.js +1 -0
  48. package/dist/client/assets/dist-BXAOrsjq.js +1 -0
  49. package/dist/client/assets/dist-CKF2Jksy.js +1 -0
  50. package/dist/client/assets/dist-CX_Hm4GS.js +1 -0
  51. package/dist/client/assets/dist-Cus6_oaF.js +2 -0
  52. package/dist/client/assets/dist-Cx00EZKR.js +23 -0
  53. package/dist/client/assets/dist-D71y2EI1.js +1 -0
  54. package/dist/client/assets/dist-D978o95T.js +5 -0
  55. package/dist/client/assets/dist-Dc1MBGAG.js +1 -0
  56. package/dist/client/assets/dist-Dds-qLxY.js +9 -0
  57. package/dist/client/assets/dist-DeD9copn.js +1 -0
  58. package/dist/client/assets/dist-DuvGReu-.js +6 -0
  59. package/dist/client/assets/dist-Dvb0SqcK.js +2 -0
  60. package/dist/client/assets/dist-J6XWqRpB.js +3 -0
  61. package/dist/client/assets/dist-QzbOCAU6.js +1 -0
  62. package/dist/client/assets/dist-moiMRpw_.js +1 -0
  63. package/dist/client/assets/dist-scBkrwv-.js +2 -0
  64. package/dist/client/assets/dockerfile-BDePf5PZ.js +1 -0
  65. package/dist/client/assets/index-Cn7hdrDw.js +350 -0
  66. package/dist/client/assets/index-UfzqdECL.css +1 -0
  67. package/dist/client/assets/powershell-D8WpQPaX.js +1 -0
  68. package/dist/client/assets/properties-C357ku5U.js +1 -0
  69. package/dist/client/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  70. package/dist/client/assets/ruby-ChfNwlCY.js +1 -0
  71. package/dist/client/assets/shell-DwuoZtxw.js +1 -0
  72. package/dist/client/assets/swift-DKB6_1j6.js +1 -0
  73. package/dist/client/assets/toml-BPTmHmyx.js +1 -0
  74. package/dist/client/favicon.ico +0 -0
  75. package/dist/client/favicon.png +0 -0
  76. package/dist/client/favicon.svg +10 -0
  77. package/dist/client/index.html +18 -0
  78. package/dist/extension.d.ts +15 -0
  79. package/dist/extension.js +126 -0
  80. package/dist/server/active-memory.d.ts +247 -0
  81. package/dist/server/active-memory.js +669 -0
  82. package/dist/server/agents.d.ts +245 -0
  83. package/dist/server/agents.js +701 -0
  84. package/dist/server/application/catalog-service.d.ts +98 -0
  85. package/dist/server/application/catalog-service.js +245 -0
  86. package/dist/server/application/conversation-service.d.ts +245 -0
  87. package/dist/server/application/conversation-service.js +654 -0
  88. package/dist/server/application/document-service.d.ts +68 -0
  89. package/dist/server/application/document-service.js +120 -0
  90. package/dist/server/application/extension-ui-service.d.ts +44 -0
  91. package/dist/server/application/extension-ui-service.js +135 -0
  92. package/dist/server/application/feishu-service.d.ts +179 -0
  93. package/dist/server/application/feishu-service.js +358 -0
  94. package/dist/server/application/group-chat-service.d.ts +75 -0
  95. package/dist/server/application/group-chat-service.js +953 -0
  96. package/dist/server/application/group-execution.d.ts +15 -0
  97. package/dist/server/application/group-execution.js +77 -0
  98. package/dist/server/application/project-service.d.ts +464 -0
  99. package/dist/server/application/project-service.js +2523 -0
  100. package/dist/server/application/provider-service.d.ts +174 -0
  101. package/dist/server/application/provider-service.js +510 -0
  102. package/dist/server/application/run-service.d.ts +547 -0
  103. package/dist/server/application/run-service.js +2683 -0
  104. package/dist/server/application/scheduled-task-service.d.ts +184 -0
  105. package/dist/server/application/scheduled-task-service.js +391 -0
  106. package/dist/server/application/session-orchestrator-service.d.ts +388 -0
  107. package/dist/server/application/session-orchestrator-service.js +1146 -0
  108. package/dist/server/application/session-reminder-service.d.ts +59 -0
  109. package/dist/server/application/session-reminder-service.js +141 -0
  110. package/dist/server/application/session-watchdog.d.ts +171 -0
  111. package/dist/server/application/session-watchdog.js +284 -0
  112. package/dist/server/application/workspace-service.d.ts +52 -0
  113. package/dist/server/application/workspace-service.js +186 -0
  114. package/dist/server/application/worktree-service.d.ts +13 -0
  115. package/dist/server/application/worktree-service.js +76 -0
  116. package/dist/server/browser-access.d.ts +34 -0
  117. package/dist/server/browser-access.js +89 -0
  118. package/dist/server/capability.d.ts +105 -0
  119. package/dist/server/capability.js +170 -0
  120. package/dist/server/command-handler.d.ts +93 -0
  121. package/dist/server/command-handler.js +540 -0
  122. package/dist/server/content-search.d.ts +16 -0
  123. package/dist/server/content-search.js +235 -0
  124. package/dist/server/conversation-usage.d.ts +22 -0
  125. package/dist/server/conversation-usage.js +43 -0
  126. package/dist/server/documents.d.ts +152 -0
  127. package/dist/server/documents.js +998 -0
  128. package/dist/server/engineering-learning.d.ts +30 -0
  129. package/dist/server/engineering-learning.js +106 -0
  130. package/dist/server/exec-service.d.ts +45 -0
  131. package/dist/server/exec-service.js +167 -0
  132. package/dist/server/explicit-file-open.d.ts +34 -0
  133. package/dist/server/explicit-file-open.js +105 -0
  134. package/dist/server/failure-text.d.ts +18 -0
  135. package/dist/server/failure-text.js +44 -0
  136. package/dist/server/feishu-cli.d.ts +223 -0
  137. package/dist/server/feishu-cli.js +464 -0
  138. package/dist/server/file-changes.d.ts +119 -0
  139. package/dist/server/file-changes.js +280 -0
  140. package/dist/server/file-diff.d.ts +41 -0
  141. package/dist/server/file-diff.js +97 -0
  142. package/dist/server/file-index.d.ts +100 -0
  143. package/dist/server/file-index.js +296 -0
  144. package/dist/server/file-name-index.d.ts +160 -0
  145. package/dist/server/file-name-index.js +411 -0
  146. package/dist/server/files.d.ts +269 -0
  147. package/dist/server/files.js +748 -0
  148. package/dist/server/git.d.ts +245 -0
  149. package/dist/server/git.js +903 -0
  150. package/dist/server/http-server.d.ts +45 -0
  151. package/dist/server/http-server.js +3830 -0
  152. package/dist/server/index.d.ts +1 -0
  153. package/dist/server/index.js +485 -0
  154. package/dist/server/inline-thinking.d.ts +90 -0
  155. package/dist/server/inline-thinking.js +181 -0
  156. package/dist/server/json-comments.d.ts +14 -0
  157. package/dist/server/json-comments.js +71 -0
  158. package/dist/server/knowledge-embedding-worker.d.ts +1 -0
  159. package/dist/server/knowledge-embedding-worker.js +27 -0
  160. package/dist/server/knowledge-vectors.d.ts +150 -0
  161. package/dist/server/knowledge-vectors.js +385 -0
  162. package/dist/server/knowledge.d.ts +273 -0
  163. package/dist/server/knowledge.js +848 -0
  164. package/dist/server/length-continuation.d.ts +83 -0
  165. package/dist/server/length-continuation.js +118 -0
  166. package/dist/server/logging.d.ts +32 -0
  167. package/dist/server/logging.js +185 -0
  168. package/dist/server/managed-http-tunnel.d.ts +6 -0
  169. package/dist/server/managed-http-tunnel.js +85 -0
  170. package/dist/server/managed-http.d.ts +4 -0
  171. package/dist/server/managed-http.js +85 -0
  172. package/dist/server/managed-model-adapter.d.ts +17 -0
  173. package/dist/server/managed-model-adapter.js +75 -0
  174. package/dist/server/managed-model-gateway.d.ts +49 -0
  175. package/dist/server/managed-model-gateway.js +73 -0
  176. package/dist/server/managed-servers.d.ts +55 -0
  177. package/dist/server/managed-servers.js +392 -0
  178. package/dist/server/managed-ssh.d.ts +26 -0
  179. package/dist/server/managed-ssh.js +73 -0
  180. package/dist/server/manager-vault.d.ts +11 -0
  181. package/dist/server/manager-vault.js +67 -0
  182. package/dist/server/memory-recall.d.ts +25 -0
  183. package/dist/server/memory-recall.js +45 -0
  184. package/dist/server/memory.d.ts +67 -0
  185. package/dist/server/memory.js +216 -0
  186. package/dist/server/message-media.d.ts +7 -0
  187. package/dist/server/message-media.js +54 -0
  188. package/dist/server/model-context-window.d.ts +186 -0
  189. package/dist/server/model-context-window.js +444 -0
  190. package/dist/server/model-filter.d.ts +23 -0
  191. package/dist/server/model-filter.js +48 -0
  192. package/dist/server/models-store.d.ts +36 -0
  193. package/dist/server/models-store.js +132 -0
  194. package/dist/server/native-tool-settings.d.ts +25 -0
  195. package/dist/server/native-tool-settings.js +41 -0
  196. package/dist/server/native-tools-extension.d.ts +2 -0
  197. package/dist/server/native-tools-extension.js +39 -0
  198. package/dist/server/native-tools-service.d.ts +39 -0
  199. package/dist/server/native-tools-service.js +240 -0
  200. package/dist/server/persistence/app-state-repository.d.ts +65 -0
  201. package/dist/server/persistence/app-state-repository.js +1 -0
  202. package/dist/server/persistence/json-state-repository.d.ts +14 -0
  203. package/dist/server/persistence/json-state-repository.js +43 -0
  204. package/dist/server/persistence/open-state-store.d.ts +3 -0
  205. package/dist/server/persistence/open-state-store.js +35 -0
  206. package/dist/server/persistence/rename.d.ts +22 -0
  207. package/dist/server/persistence/rename.js +44 -0
  208. package/dist/server/persistence/sqlite-state-repository.d.ts +12 -0
  209. package/dist/server/persistence/sqlite-state-repository.js +264 -0
  210. package/dist/server/pi-command.d.ts +94 -0
  211. package/dist/server/pi-command.js +265 -0
  212. package/dist/server/pi-native.d.ts +12 -0
  213. package/dist/server/pi-native.js +16 -0
  214. package/dist/server/pi-session-events.d.ts +158 -0
  215. package/dist/server/pi-session-events.js +373 -0
  216. package/dist/server/pi-session-pool.d.ts +233 -0
  217. package/dist/server/pi-session-pool.js +382 -0
  218. package/dist/server/pi-session.d.ts +642 -0
  219. package/dist/server/pi-session.js +655 -0
  220. package/dist/server/presentations/schema.d.ts +120 -0
  221. package/dist/server/presentations/schema.js +128 -0
  222. package/dist/server/provider-network.d.ts +16 -0
  223. package/dist/server/provider-network.js +106 -0
  224. package/dist/server/provider-proxy.d.ts +18 -0
  225. package/dist/server/provider-proxy.js +200 -0
  226. package/dist/server/providers.d.ts +333 -0
  227. package/dist/server/providers.js +989 -0
  228. package/dist/server/remote-bootstrap.d.ts +17 -0
  229. package/dist/server/remote-bootstrap.js +119 -0
  230. package/dist/server/rpc-channel.d.ts +131 -0
  231. package/dist/server/rpc-channel.js +135 -0
  232. package/dist/server/runtime.d.ts +1393 -0
  233. package/dist/server/runtime.js +3286 -0
  234. package/dist/server/scheduled-tasks.d.ts +101 -0
  235. package/dist/server/scheduled-tasks.js +138 -0
  236. package/dist/server/server-context.d.ts +119 -0
  237. package/dist/server/server-context.js +1 -0
  238. package/dist/server/session-cwd.d.ts +19 -0
  239. package/dist/server/session-cwd.js +58 -0
  240. package/dist/server/session-ledger.d.ts +67 -0
  241. package/dist/server/session-ledger.js +76 -0
  242. package/dist/server/session-memory-scope.d.ts +4 -0
  243. package/dist/server/session-memory-scope.js +30 -0
  244. package/dist/server/session-repository.d.ts +100 -0
  245. package/dist/server/session-repository.js +246 -0
  246. package/dist/server/session-tree-scope.d.ts +125 -0
  247. package/dist/server/session-tree-scope.js +337 -0
  248. package/dist/server/skills.d.ts +23 -0
  249. package/dist/server/skills.js +190 -0
  250. package/dist/server/store.d.ts +1062 -0
  251. package/dist/server/store.js +3305 -0
  252. package/dist/server/subagent-runs.d.ts +185 -0
  253. package/dist/server/subagent-runs.js +383 -0
  254. package/dist/server/subagents.d.ts +200 -0
  255. package/dist/server/subagents.js +619 -0
  256. package/dist/server/task-tool.d.ts +282 -0
  257. package/dist/server/task-tool.js +507 -0
  258. package/dist/server/tavily.d.ts +32 -0
  259. package/dist/server/tavily.js +136 -0
  260. package/dist/server/team-context.d.ts +12 -0
  261. package/dist/server/team-context.js +180 -0
  262. package/dist/server/terminal.d.ts +163 -0
  263. package/dist/server/terminal.js +557 -0
  264. package/dist/server/thinking-level-discovery.d.ts +38 -0
  265. package/dist/server/thinking-level-discovery.js +183 -0
  266. package/dist/server/time-zone.d.ts +20 -0
  267. package/dist/server/time-zone.js +32 -0
  268. package/dist/server/tool-calls.d.ts +130 -0
  269. package/dist/server/tool-calls.js +341 -0
  270. package/dist/server/tool-llm.d.ts +72 -0
  271. package/dist/server/tool-llm.js +146 -0
  272. package/dist/server/tool-registry.d.ts +129 -0
  273. package/dist/server/tool-registry.js +249 -0
  274. package/dist/server/tool-runner.d.ts +112 -0
  275. package/dist/server/tool-runner.js +306 -0
  276. package/dist/server/turn-failure.d.ts +48 -0
  277. package/dist/server/turn-failure.js +148 -0
  278. package/dist/server/types.d.ts +2315 -0
  279. package/dist/server/types.js +11 -0
  280. package/dist/server/update-status.d.ts +14 -0
  281. package/dist/server/update-status.js +69 -0
  282. package/dist/server/update.d.ts +46 -0
  283. package/dist/server/update.js +104 -0
  284. package/dist/server/upload.d.ts +35 -0
  285. package/dist/server/upload.js +177 -0
  286. package/dist/server/version.d.ts +33 -0
  287. package/dist/server/version.js +111 -0
  288. package/dist/server/web.d.ts +27 -0
  289. package/dist/server/web.js +183 -0
  290. package/dist/server/workflow-engine.d.ts +47 -0
  291. package/dist/server/workflow-engine.js +255 -0
  292. package/dist/server/workflow.d.ts +329 -0
  293. package/dist/server/workflow.js +469 -0
  294. package/dist/server/workspace-file-indexes.d.ts +2 -0
  295. package/dist/server/workspace-file-indexes.js +61 -0
  296. package/dist/server/workspace-file-operations.d.ts +36 -0
  297. package/dist/server/workspace-file-operations.js +281 -0
  298. package/dist/server/workspace-file-response.d.ts +7 -0
  299. package/dist/server/workspace-file-response.js +79 -0
  300. package/dist/server/ws-server.d.ts +149 -0
  301. package/dist/server/ws-server.js +640 -0
  302. package/dist/shared/agent-order.d.ts +44 -0
  303. package/dist/shared/agent-order.js +50 -0
  304. package/dist/shared/archive-decisions.d.ts +44 -0
  305. package/dist/shared/archive-decisions.js +98 -0
  306. package/dist/shared/background-task.d.ts +25 -0
  307. package/dist/shared/background-task.js +183 -0
  308. package/dist/shared/child-session-lock.d.ts +37 -0
  309. package/dist/shared/child-session-lock.js +59 -0
  310. package/dist/shared/content-search.d.ts +22 -0
  311. package/dist/shared/content-search.js +1 -0
  312. package/dist/shared/conversation-title.d.ts +4 -0
  313. package/dist/shared/conversation-title.js +4 -0
  314. package/dist/shared/file-mentions.d.ts +17 -0
  315. package/dist/shared/file-mentions.js +91 -0
  316. package/dist/shared/git-commit.d.ts +11 -0
  317. package/dist/shared/git-commit.js +1 -0
  318. package/dist/shared/git-graph.d.ts +42 -0
  319. package/dist/shared/git-graph.js +30 -0
  320. package/dist/shared/group-chat.d.ts +132 -0
  321. package/dist/shared/group-chat.js +6 -0
  322. package/dist/shared/managed-servers.d.ts +36 -0
  323. package/dist/shared/managed-servers.js +1 -0
  324. package/dist/shared/message-media.d.ts +12 -0
  325. package/dist/shared/message-media.js +27 -0
  326. package/dist/shared/model-window-label.d.ts +39 -0
  327. package/dist/shared/model-window-label.js +55 -0
  328. package/dist/shared/native-tools.d.ts +43 -0
  329. package/dist/shared/native-tools.js +1 -0
  330. package/dist/shared/pi-cache-warming.d.ts +9 -0
  331. package/dist/shared/pi-cache-warming.js +4 -0
  332. package/dist/shared/project-overview.d.ts +107 -0
  333. package/dist/shared/project-overview.js +92 -0
  334. package/dist/shared/project-presentation.d.ts +55 -0
  335. package/dist/shared/project-presentation.js +111 -0
  336. package/dist/shared/provider-network.d.ts +30 -0
  337. package/dist/shared/provider-network.js +1 -0
  338. package/dist/shared/session-reporting.d.ts +40 -0
  339. package/dist/shared/session-reporting.js +97 -0
  340. package/dist/shared/session-search.d.ts +14 -0
  341. package/dist/shared/session-search.js +1 -0
  342. package/dist/shared/team-context-view.d.ts +33 -0
  343. package/dist/shared/team-context-view.js +49 -0
  344. package/dist/shared/team-context.d.ts +59 -0
  345. package/dist/shared/team-context.js +3 -0
  346. package/dist/shared/terminal-protocol.d.ts +71 -0
  347. package/dist/shared/terminal-protocol.js +1 -0
  348. package/dist/shared/thinking-levels.d.ts +53 -0
  349. package/dist/shared/thinking-levels.js +85 -0
  350. package/dist/shared/tool-glyph.d.ts +7 -0
  351. package/dist/shared/tool-glyph.js +19 -0
  352. package/dist/shared/transcript-order.d.ts +7 -0
  353. package/dist/shared/transcript-order.js +12 -0
  354. package/dist/shared/update-status.d.ts +28 -0
  355. package/dist/shared/update-status.js +1 -0
  356. package/dist/shared/workspace-file-preview.d.ts +4 -0
  357. package/dist/shared/workspace-file-preview.js +28 -0
  358. package/package.json +448 -4
  359. package/scripts/diagnose.mjs +603 -0
  360. package/scripts/patch-brace-expansion.mjs +260 -0
  361. package/scripts/restart-server.mjs +104 -0
  362. package/skills/presentation/SKILL.md +30 -0
  363. package/skills/presentation/references/data.md +10 -0
  364. package/skills/presentation/references/quality.md +12 -0
  365. package/skills/presentation/references/story.md +12 -0
  366. package/skills/presentation/references/templates-and-editing.md +11 -0
  367. package/skills/presentation/references/visual-system.md +10 -0
  368. package/skills/super-pi-agent-development/SKILL.md +25 -0
  369. package/skills/super-pi-development/SKILL.md +31 -0
  370. package/skills/super-pi-tool-development/SKILL.md +39 -0
@@ -0,0 +1,655 @@
1
+ /**
2
+ * THE SESSION LAYER: one Pi session per Super Pi conversation, alive across turns.
3
+ *
4
+ * WHY THIS FILE EXISTS. Super Pi used to spawn a fresh `pi --mode rpc` process for every turn and kill
5
+ * it when the turn ended. That cost ~400ms of spawn plus ~380ms of handshake plus a full replay of the
6
+ * transcript on EVERY message, and it is why an interrupt had to kill a process and start another one:
7
+ * the turn and the process were the same thing. Pi's own `abort` takes 147ms and leaves the session
8
+ * usable, so the process churn was Super Pi's choice, not a property of interrupting.
9
+ *
10
+ * Pi's SDK (`@earendil-works/pi-coding-agent`) is the supported way to embed it - Pi's own RPC docs
11
+ * recommend it for Node applications. A session here is a Pi `AgentSession`: it keeps the conversation
12
+ * context in memory across turns, and `abort()` returns as soon as the agent is idle.
13
+ *
14
+ * WHAT THIS FILE IS NOT. It is not a second runtime. The one-shot paths (memory review, knowledge
15
+ * rerank, autotitle, tool LLM, catalog probe) keep spawning their own throwaway children, because their
16
+ * identity, tool set and lifecycle are deliberately different from the primary agent's and sharing a
17
+ * session with them would be a correctness bug, not an optimization. See `runtime.ts`.
18
+ *
19
+ * THE ONE HARD CONSTRAINT. Pi's agent prompt, its tool allowlist and the extensions it mounts are all
20
+ * decided when the session is CREATED. None of them can be changed on a live session. So a session carries
21
+ * a FINGERPRINT of everything that was decided at creation, and the caller compares fingerprints: a
22
+ * change means the session is stale and must be replaced. `revert` is the sharpest case - it truncates
23
+ * the transcript on disk while the live session still holds the old context in memory, and nothing in Pi
24
+ * would notice the difference.
25
+ */
26
+ import { existsSync, readdirSync, statSync } from "node:fs";
27
+ import { open, readdir } from "node:fs/promises";
28
+ import { StringDecoder } from "node:string_decoder";
29
+ import { dirname, join, resolve } from "node:path";
30
+ import { createModelResolver } from "./model-context-window.js";
31
+ import { installProviderProxy, proxyCredentialStore } from "./provider-proxy.js";
32
+ import { fileURLToPath, pathToFileURL } from "node:url";
33
+ import { nativeToolEnv, nativeToolPolicy, nativeToolSettingsPath, readNativeToolSettings } from "./native-tool-settings.js";
34
+ const traceSession = (conversationId, phase, startedAt, extra = "") => {
35
+ if (process.env.SUPER_PI_TRACE_LATENCY !== "1")
36
+ return;
37
+ console.warn(`[super-pi latency] conversation=${conversationId} phase=${phase} elapsedMs=${Math.round(performance.now() - startedAt)}${extra ? ` ${extra}` : ""}`);
38
+ };
39
+ /**
40
+ * Loads Pi's SDK while the server is still starting.
41
+ *
42
+ * Importing Pi costs about 1.5 seconds once and is free afterwards, and it used to be paid by whatever
43
+ * user action needed it FIRST - which for most people was opening the model picker and watching it stay
44
+ * grey. Paying it here, during startup, moves it off the path a person can see.
45
+ *
46
+ * Safe to call more than once, and safe to call on a server that never needs the SDK: it loads the
47
+ * module and returns, and the caller decides what to do with a failure.
48
+ */
49
+ export async function warmPiSdk() {
50
+ try {
51
+ await loadSdk();
52
+ return true;
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ }
58
+ let sdkPromise;
59
+ let sdkFailure;
60
+ export async function piCacheWarmingMode(mode) {
61
+ const sdk = await loadSdk();
62
+ const settings = sdk.SettingsManager.create(process.cwd(), defaultAgentDir());
63
+ if (mode !== undefined) {
64
+ settings.setCacheWarmingMode(mode);
65
+ await settings.flush();
66
+ }
67
+ const errors = settings.drainErrors();
68
+ if (errors.length)
69
+ throw new Error("Pi 设置读写失败,请检查服务端设置文件和目录权限。");
70
+ return settings.getCacheWarmingMode();
71
+ }
72
+ async function loadSdk() {
73
+ if (sdkFailure)
74
+ throw new Error(sdkFailure);
75
+ if (!sdkPromise) {
76
+ // The specifier is assembled at runtime on purpose: a static `import("...")` would be resolved by
77
+ // the compiler, which would turn a BROKEN INSTALL into a COMPILE ERROR - and the compiler runs
78
+ // before anything can report the real reason. The name is written out in full here so a reader
79
+ // can see exactly which package is being loaded.
80
+ const specifier = ["@earendil-works", "pi-coding-agent"].join("/");
81
+ sdkPromise = import(/* @vite-ignore */ specifier).then(async (mod) => {
82
+ // Pi 0.86.1 accepts a CredentialStore but exports its file-store constructor only from core.
83
+ const storageUrl = new URL("./core/auth-storage.js", import.meta.resolve(specifier)).href;
84
+ const storage = await import(/* @vite-ignore */ storageUrl);
85
+ return { ...mod, AuthStorage: storage.AuthStorage };
86
+ }, (error) => {
87
+ const reason = error instanceof Error ? error.message : String(error);
88
+ sdkFailure = `Super Pi could not load Pi's SDK (@earendil-works/pi-coding-agent): ${reason}. Reinstall Super Pi (npm i -g @evandu/super-pi) so that Pi comes with it, or install it next to Super Pi with \`npm install @earendil-works/pi-coding-agent\`.`;
89
+ throw new Error(sdkFailure);
90
+ });
91
+ }
92
+ return sdkPromise;
93
+ }
94
+ /**
95
+ * Builds a zero-process catalog reader.
96
+ *
97
+ * The ModelRuntime and the SettingsManager are created ONCE and reused: both read the auth store and
98
+ * the model store from disk, so a fresh one per call would put the same I/O back that this is here to
99
+ * remove. They are safe to share - they are read-mostly views of the same files.
100
+ *
101
+ * The MODEL LIST is read once, at build time, and the LEVELS are cached per model - both because
102
+ * re-reading them is the cost this exists to remove, and because the answer cannot change while the
103
+ * process runs: a person who edits `auth.json` or adds a model restarts Super Pi, exactly as they
104
+ * would for anything else in Pi's own configuration.
105
+ */
106
+ export async function createSdkCatalog(cwd) {
107
+ const sdk = await loadSdk();
108
+ const agentDir = defaultAgentDir();
109
+ const credentials = sdk.AuthStorage ? proxyCredentialStore(sdk.AuthStorage.create(join(agentDir, "auth.json"))) : undefined;
110
+ const modelRuntime = await sdk.ModelRuntime.create(credentials ? { credentials } : undefined);
111
+ await installProviderProxy(modelRuntime, agentDir);
112
+ const settingsManager = sdk.SettingsManager.create(cwd, agentDir);
113
+ const models = (await modelRuntime.getAvailable?.()) ?? modelRuntime.getModels?.() ?? [];
114
+ const levelsByModel = new Map();
115
+ // THE DEFAULT MODEL IS PI'S TO DECIDE, SO PI IS ASKED. Not read out of the settings and not guessed:
116
+ // the settings say what the person WANTS, and Pi decides what will actually run.
117
+ const resolved = await resolveDefaultModel(sdk, { cwd, agentDir, modelRuntime, settingsManager });
118
+ // The default's own levels come from the session that resolved it, so the level list is not paid
119
+ // for twice: the next question about that model is a cache hit.
120
+ if (resolved)
121
+ levelsByModel.set(`${resolved.model.provider}/${resolved.model.modelId}`, resolved.thinking);
122
+ return {
123
+ models,
124
+ configError: () => modelRuntime.getError?.(),
125
+ oauthProviders: async () => Promise.all((modelRuntime.getProviders?.() ?? []).flatMap((provider) => provider.auth?.oauth
126
+ ? [Promise.resolve(modelRuntime.checkAuth?.(provider.id)).then((auth) => ({ id: provider.id, name: provider.auth.oauth.name ?? provider.name ?? provider.id,
127
+ isSubscription: provider.auth.oauth.isSubscription === true,
128
+ ...(provider.auth.oauth.loginLabel ? { loginLabel: provider.auth.oauth.loginLabel } : {}), authenticated: auth?.type === "oauth" }))]
129
+ : [])),
130
+ loginOAuth: async (providerId, interaction) => {
131
+ if (!modelRuntime.login)
132
+ throw new Error("当前 Pi SDK 不支持供应商登录。");
133
+ await modelRuntime.login(providerId, "oauth", interaction, { agentName: "Super Pi" });
134
+ await modelRuntime.refresh?.();
135
+ },
136
+ logoutOAuth: async (providerId) => {
137
+ if (!modelRuntime.logout)
138
+ throw new Error("当前 Pi SDK 不支持供应商退出登录。");
139
+ await modelRuntime.logout(providerId);
140
+ },
141
+ ...(resolved ? { defaultModel: resolved.model } : {}),
142
+ thinkingLevelsFor: async (model) => {
143
+ const key = `${model.provider}/${model.modelId}`;
144
+ const cached = levelsByModel.get(key);
145
+ if (cached)
146
+ return cached;
147
+ // THE MODEL HAS TO BE FOUND FIRST, and the reason it has to be found is that a session created
148
+ // WITHOUT one runs on Pi's DEFAULT model - and then it answers with the DEFAULT MODEL'S LEVELS.
149
+ // That is a silent wrong answer: the picker would offer the levels of a model the person is not
150
+ // using, and hide the ones they are. A model this runtime does not know is not a model with no
151
+ // levels; it is a model whose levels have to be asked of whoever does know it.
152
+ const whole = modelRuntime.getModel?.(model.provider, model.modelId);
153
+ if (!whole)
154
+ return undefined;
155
+ // A model that is not running has no levels of its own, so a short-lived in-memory session is
156
+ // built to ask Pi. It costs a session - measured at ~30ms warm, and no process at all - and it is
157
+ // paid once per model rather than once per picker open.
158
+ const { session } = await sdk.createAgentSession({
159
+ cwd,
160
+ agentDir,
161
+ modelRuntime,
162
+ settingsManager,
163
+ sessionManager: sdk.SessionManager.inMemory(cwd, { id: "catalog-levels" }),
164
+ model: whole,
165
+ });
166
+ try {
167
+ const value = sessionThinking(session);
168
+ levelsByModel.set(key, value);
169
+ return value;
170
+ }
171
+ finally {
172
+ session.dispose?.();
173
+ }
174
+ },
175
+ };
176
+ }
177
+ /**
178
+ * THE MODEL PI WOULD RUN, AND WHAT IT CAN THINK - asked of Pi.
179
+ *
180
+ * THE SESSION IS BUILT WITH NO MODEL ON PURPOSE. That is the one way to make Pi do its own default
181
+ * resolution instead of Super Pi guessing at it: Pi's resolver prefers the settings' default, but
182
+ * only when that model still exists AND its provider has a credential, and otherwise it picks a
183
+ * model it can actually run - a preference Super Pi cannot read, because the table of "the default
184
+ * model per provider" is Pi's own and is not exported.
185
+ *
186
+ * The session that comes back is RUNNING ON the model Pi picked, so its levels and its thinking
187
+ * level are that model's - read from the same place Pi reads them from.
188
+ *
189
+ * NO INFERENCE IS SENT. A session that has not been prompted does not talk to the provider; it only
190
+ * resolves its configuration. And a session with NO MODEL reports every thinking level there is,
191
+ * which is Pi's way of saying "I have no model to level" - so a session without a model is not an
192
+ * answer at all, and the honest one is "Pi has no model to run".
193
+ */
194
+ async function resolveDefaultModel(sdk, options) {
195
+ let session;
196
+ try {
197
+ const created = await sdk.createAgentSession({
198
+ cwd: options.cwd,
199
+ agentDir: options.agentDir,
200
+ modelRuntime: options.modelRuntime,
201
+ settingsManager: options.settingsManager,
202
+ sessionManager: sdk.SessionManager.inMemory(options.cwd, { id: "catalog-default" }),
203
+ // NO MODEL: THAT IS THE POINT. Pi resolves the one it would run.
204
+ });
205
+ session = created.session;
206
+ const model = session.model;
207
+ if (typeof model?.provider !== "string" || !model.provider || typeof model.id !== "string" || !model.id)
208
+ return undefined;
209
+ return { model: { provider: model.provider, modelId: model.id }, thinking: sessionThinking(session) };
210
+ }
211
+ catch (error) {
212
+ console.warn(`Pi's SDK could not resolve the default model: ${error instanceof Error ? error.message : String(error)}. The catalog will report no default model rather than a wrong one.`);
213
+ return undefined;
214
+ }
215
+ finally {
216
+ session?.dispose?.();
217
+ }
218
+ }
219
+ /** Reads the thinking levels off a session, tolerating a session that does not implement the call. */
220
+ function sessionLevels(session) {
221
+ const levels = session.getAvailableThinkingLevels?.();
222
+ return Array.isArray(levels) ? levels.filter((level) => typeof level === "string") : [];
223
+ }
224
+ /**
225
+ * The levels a session's model offers, AND the level in force on it.
226
+ *
227
+ * The level is read off the session because that is where Pi clamped it: the per-model override,
228
+ * else the global default, brought down to a level this model actually has.
229
+ */
230
+ function sessionThinking(session) {
231
+ const levels = sessionLevels(session);
232
+ const level = session.thinkingLevel;
233
+ return { levels, ...(typeof level === "string" && level ? { level } : {}) };
234
+ }
235
+ /**
236
+ * The transcript file a conversation's session writes to, found WITHOUT starting a Pi process.
237
+ *
238
+ * THIS REPLACES A SPAWN. Revert and fork need to know which file holds a conversation's history, and
239
+ * they used to start a child purely to be told. Pi's SDK answers it from the session
240
+ * manager's own state - and it answers it the same way Pi's RPC mode does, which is the only reason
241
+ * this is safe: Pi looks a session up BY ID and by WORKING DIRECTORY, so asking the library that
242
+ * resolves the session gives the same file the child would have named.
243
+ *
244
+ * Returns undefined when there is no such session, which is the caller's cue to fall back rather than
245
+ * to guess: a wrong path here would truncate somebody else's conversation.
246
+ */
247
+ export async function resolveTranscriptFile(cwd, conversationId, sessionDir) {
248
+ // The caller still falls back to RPC when the SDK is unavailable. Discovery itself is async so
249
+ // a cold directory on a cloud filesystem does not block stop/send handling on the event loop.
250
+ await loadSdk();
251
+ return transcriptFiles.find(cwd, conversationId, sessionDir);
252
+ }
253
+ /** Whether the SDK could be loaded. Used by the server to report the reason instead of failing a turn. */
254
+ export async function piSdkAvailable() {
255
+ try {
256
+ await loadSdk();
257
+ return { available: true };
258
+ }
259
+ catch (error) {
260
+ return { available: false, reason: error instanceof Error ? error.message : String(error) };
261
+ }
262
+ }
263
+ /**
264
+ * Fingerprints are compared by VALUE, and this is where that comparison is spelled out.
265
+ *
266
+ * The array fields are compared as SETS, not sequences: the tool allowlist is a set of names, and a
267
+ * caller that happens to list them in a different order is asking for the same session, not a new one.
268
+ * Getting this wrong in the strict direction would throw away a perfectly good session on every turn
269
+ * (a latency bug that looks like nothing at all), and getting it wrong in the loose direction would keep
270
+ * a session whose allowlist had genuinely changed (a permission bug). So: order-insensitive, and every
271
+ * element compared exactly.
272
+ */
273
+ export function sameFingerprint(a, b) {
274
+ if (a.cwd !== b.cwd)
275
+ return false;
276
+ if (a.agentId !== b.agentId)
277
+ return false;
278
+ if (!sameSet(a.tools, b.tools))
279
+ return false;
280
+ if (!sameSet(a.excludeTools, b.excludeTools))
281
+ return false;
282
+ if (!sameSet(a.extensions, b.extensions))
283
+ return false;
284
+ if (a.modelEpoch !== b.modelEpoch)
285
+ return false;
286
+ return true;
287
+ }
288
+ function sameSet(a, b) {
289
+ if (a === undefined || b === undefined)
290
+ return a === b;
291
+ if (a.length !== b.length)
292
+ return false;
293
+ const left = [...a].sort();
294
+ const right = [...b].sort();
295
+ return left.every((item, index) => item === right[index]);
296
+ }
297
+ /**
298
+ * Runs `work` with the given environment applied, and restores the previous values afterwards.
299
+ *
300
+ * The values are applied SYNCHRONOUSLY and the whole of `work` is awaited inside the window, because
301
+ * the extension factory runs during the loader's reload and reads the environment at that moment. A
302
+ * concurrent session's environment would otherwise land in the middle of this one.
303
+ */
304
+ export async function withEnvironment(values, work) {
305
+ const previous = new Map();
306
+ for (const [key, value] of Object.entries(values)) {
307
+ previous.set(key, process.env[key]);
308
+ process.env[key] = value;
309
+ }
310
+ try {
311
+ return await work();
312
+ }
313
+ finally {
314
+ for (const [key, value] of previous) {
315
+ if (value === undefined)
316
+ delete process.env[key];
317
+ else
318
+ process.env[key] = value;
319
+ }
320
+ }
321
+ }
322
+ /**
323
+ * The env window of the session currently being built, so the next one queues behind it.
324
+ *
325
+ * `withEnvironment` alone is not safe here: its window is process-global, and two sessions created
326
+ * concurrently would interleave - A applies its capability, B applies its own, and A's extension
327
+ * factory captures B's credential. Chaining the windows means a concurrent creation waits for the
328
+ * other's `reload()` - milliseconds - instead of silently wearing its capability.
329
+ */
330
+ let extensionEnvWindow = Promise.resolve();
331
+ /**
332
+ * `withEnvironment` for one session's extension load, serialized across all session creations.
333
+ *
334
+ * The extension factories run inside `work` and capture the values into their closures; after the
335
+ * window closes they never read `process.env` again, so only the WINDOW needs to be exclusive.
336
+ */
337
+ export function withIsolatedSessionEnv(values, work) {
338
+ const run = extensionEnvWindow.then(() => withEnvironment(values, work));
339
+ extensionEnvWindow = run.then(() => undefined, () => undefined);
340
+ return run;
341
+ }
342
+ export async function createPiSession(creation) {
343
+ const startedAt = performance.now();
344
+ traceSession(creation.sessionId, "sdk.load.begin", startedAt);
345
+ const sdk = await loadSdk();
346
+ traceSession(creation.sessionId, "sdk.load.end", startedAt);
347
+ const agentDir = creation.agentDir ?? defaultAgentDir();
348
+ // THE EXTENSIONS ARE PI'S TO LOAD. Every path goes to Pi's own resource loader, which imports them
349
+ // through its jiti transpiler with its virtual modules - and both of those are load-bearing:
350
+ // `@sinclair/typebox` is a Pi virtual module that NO node_modules anywhere can resolve, and Node's
351
+ // type stripping refuses .ts under any `node_modules` segment (which is where a published package
352
+ // lives). A native `import()` here survived neither - it broke every installed layout the moment it
353
+ // shipped, invisibly, because nothing in `npm run check` runs from an installed layout.
354
+ // `scripts/installed-layout.test.mjs` exists to keep that class of breakage visible.
355
+ return (async () => {
356
+ // THE AGENT'S PROMPT. Pi's loader takes the same two shapes the command line took: a `systemPrompt`
357
+ // that REPLACES Pi's own, and an `appendSystemPrompt` list of files that are ADDED to it. An agent
358
+ // that says `promptMode: replace` gets the first, and one that says nothing gets the second - the
359
+ // same two meanings the `--system-prompt` and `--append-system-prompt` flags carried, and the same
360
+ // distinction: an append keeps Pi's own coding-agent baseline (its tool guidance, its environment
361
+ // facts) and adds the role on top.
362
+ const loader = new sdk.DefaultResourceLoader({
363
+ cwd: creation.cwd,
364
+ agentDir,
365
+ ...(creation.extensionPaths.length ? { additionalExtensionPaths: creation.extensionPaths } : {}),
366
+ ...(creation.skillPaths?.length ? { additionalSkillPaths: creation.skillPaths } : {}),
367
+ ...(creation.systemPromptFile && creation.systemPromptMode === "replace"
368
+ ? { systemPrompt: creation.systemPromptFile }
369
+ : creation.systemPromptFile
370
+ ? { appendSystemPrompt: [creation.systemPromptFile] }
371
+ : {}),
372
+ });
373
+ // The extension factories run inside `reload()` and capture this session's env values into their
374
+ // closures; the window is serialized (`withIsolatedSessionEnv`) so a concurrent creation cannot
375
+ // land its own capability in the middle.
376
+ const nativePolicy = nativeToolPolicy(creation, readNativeToolSettings(nativeToolSettingsPath(creation.sessionDir)));
377
+ await withIsolatedSessionEnv({ ...creation.extensionEnv, ...nativeToolEnv(creation.sessionDir, nativePolicy), SUPER_PI_NATIVE_AGENT_DIR: agentDir }, () => loader.reload());
378
+ traceSession(creation.sessionId, "sdk.loader.reload", startedAt, `extensions=${creation.extensionPaths.length}`);
379
+ const sessionManager = creation.persist === false
380
+ ? sdk.SessionManager.inMemory(creation.cwd, { id: creation.sessionId })
381
+ : await resolveSessionManager(sdk, creation);
382
+ traceSession(creation.sessionId, "sdk.transcript.ready", startedAt, `bytes=${transcriptBytes(sessionManager)}`);
383
+ const credentials = sdk.AuthStorage ? proxyCredentialStore(sdk.AuthStorage.create(join(agentDir, "auth.json"))) : undefined;
384
+ const modelRuntime = await sdk.ModelRuntime.create(credentials ? { credentials } : undefined);
385
+ await installProviderProxy(modelRuntime, agentDir);
386
+ traceSession(creation.sessionId, "sdk.model-runtime", startedAt);
387
+ // THE MODEL IS RESOLVED, NOT PASSED THROUGH. Pi's SDK takes a whole Model object - the provider's
388
+ // configuration, the endpoint, the capability list - and Super Pi only knows the pair
389
+ // (provider, modelId) that the picker shows. The runtime is what turns that pair into the object
390
+ // Pi needs, and it is the same runtime the catalog probe uses, so the model the session runs on is
391
+ // the model the picker listed.
392
+ //
393
+ // A model that cannot be resolved is NOT a reason to fail the session: Pi falls back to its own
394
+ // default, and the turn still runs. Failing here would turn "the picker showed a model this Pi no
395
+ // longer has" into a conversation that cannot be sent at all.
396
+ const model = creation.model
397
+ ? modelRuntime.getModel?.(creation.model.provider, creation.model.modelId)
398
+ : undefined;
399
+ const options = {
400
+ cwd: creation.cwd,
401
+ agentDir,
402
+ modelRuntime,
403
+ resourceLoader: loader,
404
+ sessionManager,
405
+ ...(nativePolicy.tools ? { tools: nativePolicy.tools } : {}),
406
+ ...(nativePolicy.excludeTools ? { excludeTools: nativePolicy.excludeTools } : {}),
407
+ ...(model ? { model } : {}),
408
+ ...(creation.thinkingLevel ? { thinkingLevel: creation.thinkingLevel } : {}),
409
+ };
410
+ const { session } = await sdk.createAgentSession(options);
411
+ traceSession(creation.sessionId, "sdk.session.created", startedAt);
412
+ const live = session;
413
+ // THE WHOLE MODEL, LOOKED UP THE WAY PI LOOKS IT UP. Pi's `setModel` puts the model it is given
414
+ // straight into the agent's state, so what it needs is the WHOLE model - the one with an `api`, a
415
+ // `contextWindow` and a `maxTokens` - and not the `{provider, id}` pair the picker holds. The only
416
+ // thing that has a whole model is the model runtime this session was built with, and Pi's own RPC
417
+ // `set_model` does exactly this lookup before it calls `setModel` (`rpc-mode.ts:470-477`).
418
+ //
419
+ // It is attached to the session rather than kept beside it because the session is what outlives a
420
+ // turn: a model change applies to a LIVE session, and the live session is the thing that has to be
421
+ // able to answer "give me this model whole".
422
+ //
423
+ // The window the model REALLY has is arbitrated inside the resolver - see
424
+ // `model-context-window.ts` for the whole reasoning and for the tests that hold it in place.
425
+ live.resolveModel = createModelResolver({ agentDir, modelRuntime });
426
+ return live;
427
+ })();
428
+ }
429
+ function transcriptBytes(sessionManager) {
430
+ const file = sessionManager.getSessionFile?.();
431
+ if (!file)
432
+ return 0;
433
+ try {
434
+ return existsSync(file) ? statSync(file).size : 0;
435
+ }
436
+ catch {
437
+ return 0;
438
+ }
439
+ }
440
+ /**
441
+ * Resolves the session manager for a conversation: the EXISTING transcript if there is one, a new one
442
+ * otherwise.
443
+ *
444
+ * WHY THIS IS NOT JUST `SessionManager.create`. A conversation's transcript outlives its session - Pi
445
+ * writes it to a file, and a session that was evicted (idle, or thrown away by a revert) is rebuilt from
446
+ * that file. So building a session is "reopen the conversation's transcript", and the id is what says
447
+ * which transcript: Super Pi's conversation id IS the session id, which is what makes `revert` and
448
+ * `fork` able to find the file without guessing at a filename.
449
+ *
450
+ * The recorded locator avoids directory discovery altogether. Both paths verify the actual header's
451
+ * exact id and cwd; a stale path or a workspace change must never reopen somebody else's transcript.
452
+ */
453
+ export async function resolveSessionManager(sdk, creation) {
454
+ const cachedHeader = creation.sessionFile ? await readTranscriptHeader(creation.sessionFile) : undefined;
455
+ const cachedMatches = transcriptMatches(cachedHeader, creation.cwd, creation.sessionId);
456
+ const existing = cachedMatches ? creation.sessionFile
457
+ : await transcriptFiles.find(creation.cwd, creation.sessionId, creation.sessionDir);
458
+ if (existing) {
459
+ try {
460
+ const manager = sdk.SessionManager.open(existing, creation.sessionDir, creation.cwd);
461
+ // Check Pi's loaded header too: the file may have changed between async discovery and open.
462
+ const header = manager.getHeader?.();
463
+ if (transcriptMatches(header ?? undefined, creation.cwd, creation.sessionId))
464
+ return manager;
465
+ }
466
+ catch {
467
+ // A file that exists but cannot be opened is not a reason to fail the turn: falling through
468
+ // creates a fresh session, and the reader sees an empty conversation rather than an error. The
469
+ // alternative - refusing - would make a corrupt file permanently break the conversation.
470
+ }
471
+ }
472
+ return sdk.SessionManager.create(creation.cwd, creation.sessionDir, { id: creation.sessionId });
473
+ }
474
+ function transcriptMatches(header, cwd, id) {
475
+ return header?.id === id && typeof header.cwd === "string" && header.cwd !== "" && resolve(header.cwd) === resolve(cwd);
476
+ }
477
+ /** Pi's bounded header discovery contract, using async reads instead of synchronous disk I/O. */
478
+ export async function readTranscriptHeader(path) {
479
+ const file = await open(path, "r").catch(() => undefined);
480
+ if (!file)
481
+ return undefined;
482
+ try {
483
+ const decoder = new StringDecoder("utf8");
484
+ const buffer = Buffer.allocUnsafe(4096);
485
+ let pending = "";
486
+ const parse = (line) => {
487
+ if (!line.trim())
488
+ return undefined;
489
+ let value;
490
+ try {
491
+ value = JSON.parse(line);
492
+ }
493
+ catch {
494
+ return undefined;
495
+ }
496
+ if (value && typeof value === "object" && value.type === "session"
497
+ && typeof value.id === "string")
498
+ return value;
499
+ return null;
500
+ };
501
+ let scanned = 0;
502
+ while (scanned < 1024 * 1024) {
503
+ const { bytesRead } = await file.read(buffer, 0, Math.min(buffer.length, 1024 * 1024 - scanned), null);
504
+ if (!bytesRead)
505
+ return parse(pending + decoder.end()) ?? undefined;
506
+ scanned += bytesRead;
507
+ pending += decoder.write(buffer.subarray(0, bytesRead));
508
+ let newline;
509
+ while ((newline = pending.indexOf("\n")) !== -1) {
510
+ const header = parse(pending.slice(0, newline));
511
+ if (header !== undefined)
512
+ return header ?? undefined;
513
+ pending = pending.slice(newline + 1);
514
+ }
515
+ }
516
+ // Match Pi's exact-boundary EOF case without reading an unbounded prefix or transcript body.
517
+ const probe = await file.read(buffer, 0, 1, null);
518
+ return probe.bytesRead ? undefined : parse(pending + decoder.end()) ?? undefined;
519
+ }
520
+ catch {
521
+ // Discovery is best-effort, like Pi's own readSessionHeaderForDiscovery.
522
+ return undefined;
523
+ }
524
+ finally {
525
+ await file.close();
526
+ }
527
+ }
528
+ /**
529
+ * Session headers are immutable under Pi's append/rewrite contract. Cache their identities, refresh
530
+ * filenames every lookup, and recheck the selected header before opening. A newly created file is
531
+ * discovered even if stopping/crashing prevented Super Pi from persisting its locator. Arbitrary
532
+ * legacy filenames still work; filenames are never treated as proof of session identity.
533
+ */
534
+ export class TranscriptFileIndex {
535
+ readHeader;
536
+ directories = new Map();
537
+ constructor(readHeader = readTranscriptHeader) {
538
+ this.readHeader = readHeader;
539
+ }
540
+ async find(cwd, id, sessionDir) {
541
+ const dir = resolve(sessionDir);
542
+ let state = this.directories.get(dir);
543
+ if (!state) {
544
+ state = { headers: new Map(), lane: Promise.resolve() };
545
+ this.directories.set(dir, state);
546
+ }
547
+ const current = state;
548
+ let found;
549
+ const lookup = async () => {
550
+ const names = (await readdir(dir).catch(() => [])).filter(name => name.endsWith(".jsonl"));
551
+ const paths = new Set(names.map(name => join(dir, name)));
552
+ for (const path of current.headers.keys())
553
+ if (!paths.has(path))
554
+ current.headers.delete(path);
555
+ const pending = [...paths].filter(path => !current.headers.has(path));
556
+ let next = 0;
557
+ await Promise.all(Array.from({ length: Math.min(8, pending.length) }, async () => {
558
+ while (next < pending.length) {
559
+ const path = pending[next++];
560
+ const header = await this.readHeader(path);
561
+ // Empty/unreadable files may be in the middle of their first write; retry next time.
562
+ if (header)
563
+ current.headers.set(path, header);
564
+ }
565
+ }));
566
+ for (const path of paths) {
567
+ if (!transcriptMatches(current.headers.get(path), cwd, id))
568
+ continue;
569
+ const header = await this.readHeader(path);
570
+ if (header)
571
+ current.headers.set(path, header);
572
+ else
573
+ current.headers.delete(path);
574
+ if (transcriptMatches(header, cwd, id)) {
575
+ found = path;
576
+ break;
577
+ }
578
+ }
579
+ };
580
+ const run = current.lane.then(lookup, lookup);
581
+ current.lane = run.then(() => { }, () => { });
582
+ await run;
583
+ return found;
584
+ }
585
+ }
586
+ const transcriptFiles = new TranscriptFileIndex();
587
+ /**
588
+ * Pi's own global configuration directory, when it can be worked out without importing the SDK.
589
+ *
590
+ * The SDK's `getAgentDir()` is the authority, but asking it would mean importing the SDK - which this
591
+ * file goes out of its way not to do for a path it can derive. The derivation is Pi's own default:
592
+ * `~/.pi/agent`, with the home directory taken from the environment rather than from `os.homedir()`,
593
+ * because on Windows the two disagree often enough to matter.
594
+ *
595
+ * `PI_CODING_AGENT_DIR` WINS, exactly as it wins in Pi (`core/config.ts:getAgentDir`). A person who
596
+ * set it expects Pi to read its whole configuration from there, and this function used to disagree
597
+ * with Pi about it: Pi's model runtime read `models.json` from that directory while the session's
598
+ * resource loader read the skills from `~/.pi/agent`. Two halves of one Pi pointed at two
599
+ * directories, and only one of them was the one the person had configured.
600
+ */
601
+ export function defaultAgentDir() {
602
+ const configured = process.env.PI_CODING_AGENT_DIR?.trim();
603
+ if (configured)
604
+ return configured;
605
+ const home = process.env.HOME ?? process.env.USERPROFILE ?? "";
606
+ return home ? join(home, ".pi", "agent") : join(".pi", "agent");
607
+ }
608
+ let promptTemplateLoader;
609
+ /** Reads Pi's own prompt-template loader rather than duplicating its discovery rules. */
610
+ async function loadPromptTemplateLoader() {
611
+ if (!promptTemplateLoader) {
612
+ const packageRoot = dirname(fileURLToPath(await import.meta.resolve("@earendil-works/pi-coding-agent")));
613
+ promptTemplateLoader = import(pathToFileURL(join(packageRoot, "core", "prompt-templates.js")).href)
614
+ .then((module) => module.loadPromptTemplates);
615
+ }
616
+ return promptTemplateLoader;
617
+ }
618
+ export async function loadPromptTemplateSummaries(cwd) {
619
+ const loadPromptTemplates = await loadPromptTemplateLoader();
620
+ const { templates } = loadPromptTemplates({ cwd, agentDir: defaultAgentDir(), promptPaths: [], includeDefaults: true });
621
+ return templates
622
+ .filter((template) => template.sourceInfo.scope === "user" || template.sourceInfo.scope === "project")
623
+ .map((template) => ({ name: template.name, description: template.description, ...(template.argumentHint ? { argumentHint: template.argumentHint } : {}), scope: template.sourceInfo.scope }));
624
+ }
625
+ export function superPiExtensionPaths(repositoryRoot) {
626
+ const paths = [
627
+ join(repositoryRoot, "agents", "super-pi-native-tools", "index.ts"),
628
+ join(repositoryRoot, "agents", "super-pi-task", "index.ts"),
629
+ join(repositoryRoot, "agents", "super-pi-memory", "index.ts"),
630
+ join(repositoryRoot, "agents", "super-pi-knowledge", "index.ts"),
631
+ join(repositoryRoot, "agents", "super-pi-web", "index.ts"),
632
+ // The document tools. They are mounted for every session, and the extension itself decides
633
+ // whether to register anything: with no endpoint in its environment it returns without
634
+ // registering a tool, so a runtime without a document endpoint mounts nothing harmful.
635
+ join(repositoryRoot, "agents", "super-pi-documents", "index.ts"),
636
+ // The Feishu tools, mounted for every session on the same terms: the extension registers
637
+ // nothing without an endpoint in its environment.
638
+ join(repositoryRoot, "agents", "super-pi-feishu", "index.ts"),
639
+ ];
640
+ return paths.filter((path) => existsSync(path));
641
+ }
642
+ /** Skills shipped by Super Pi itself. Paths are explicit so installed and development layouts agree. */
643
+ export function superPiSkillPaths(repositoryRoot) {
644
+ const root = join(repositoryRoot, "skills");
645
+ if (!existsSync(root))
646
+ return [];
647
+ try {
648
+ return readdirSync(root, { withFileTypes: true }).filter((entry) => entry.isDirectory())
649
+ .map((entry) => join(root, entry.name)).filter((path) => existsSync(join(path, "SKILL.md")))
650
+ .sort((a, b) => (a.endsWith("presentation") ? -1 : b.endsWith("presentation") ? 1 : a.localeCompare(b)));
651
+ }
652
+ catch {
653
+ return [];
654
+ }
655
+ }