@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,341 @@
1
+ import { randomUUID } from "node:crypto";
2
+ /**
3
+ * Turning one Pi tool call into something a human reads, and nothing more.
4
+ *
5
+ * WHY THIS IS ITS OWN MODULE. Two drain loops need exactly this derivation - the sub-agent supervisor
6
+ * (`subagents.ts`) and the PRIMARY agent's runtime (`runtime.ts`) - and `subagents.ts` already imports
7
+ * `runtime.ts` for `RpcChannel`, so the reverse import would be a cycle. One definition of "what does
8
+ * this call show" therefore has to live below both of them, or the two surfaces would drift: a `read`
9
+ * labelled by its path on a card and by its working directory on a call block is worse than either.
10
+ *
11
+ * The rule the whole module exists to enforce: DERIVED AND BOUNDED, NEVER COPIED. What Pi sends in
12
+ * `args` is an arbitrary object that may hold a file's contents, a multi-kilobyte patch or an entire
13
+ * shell script. What leaves here is short strings with a hard character cap, or a bare type word.
14
+ */
15
+ /**
16
+ * The longest label one tool call may contribute. See `SubagentToolCall.detail` and `ToolCallBlock.detail`
17
+ * for why the argument is summarised rather than carried: the cap is what makes the bound structural
18
+ * instead of aspirational, because nothing downstream can grow past it.
19
+ */
20
+ export const TOOL_DETAIL_CAP = 120;
21
+ /**
22
+ * How many parameters one call block may list.
23
+ *
24
+ * A bound on the COUNT as well as on each value, for the same reason `TOOL_DETAIL_CAP` exists: without
25
+ * it, a tool that Pi sends a dozen arguments to would put twelve rows - and twelve times the cap - into a
26
+ * field that is rewritten on every text delta of the message it belongs to. Six covers every call shape
27
+ * this project has seen (`read`'s path/offset/limit, `bash`'s command/description/timeout) and truncating
28
+ * past it is announced by the caller through the row count rather than silently.
29
+ */
30
+ export const TOOL_ARG_CAP = 6;
31
+ /**
32
+ * The longest tool OUTPUT this module lets through, in characters. Eight kilobytes is a screenful of
33
+ * scroll for one call; a `bash` that prints more is still legible because what it found is usually at the
34
+ * end, which is why the cut keeps the tail.
35
+ */
36
+ export const TOOL_RESULT_CAP = 8 * 1024;
37
+ /**
38
+ * REDUCE PI'S `tool_execution_end.result` TO WHAT A PERSON READS, or `undefined`.
39
+ *
40
+ * This is the ONLY path from a raw Pi result to anything downstream, and that is the whole reason it is
41
+ * safe for the result to be persisted at all: the untrusted object stops here. Four rules, each for a
42
+ * concrete failure it prevents:
43
+ *
44
+ * 1. TEXT BLOCKS ONLY, IMAGES DROPPED. A `read` of a PNG returns base64 megabytes, and the state file it
45
+ * would land in is rewritten on every text delta of the message it belongs to.
46
+ * 2. THE TAIL, CUT ON A LINE BOUNDARY. Cutting mid-line leaves a final row that is half a sentence and
47
+ * reads as corruption. The tail also beats the head: what a tool just found is at the end.
48
+ * 3. `details.truncation` / `details.fullOutputPath` ARE READ, never inferred. "This was cut" is a fact
49
+ * only Pi knows; deriving it from length would claim Pi truncated something it returned in full.
50
+ * 4. IT RETURNS `undefined` AND NEVER THROWS. These records arrive on an open event family, so a shape
51
+ * this function does not recognise is a fact to decline, not a crash to propagate.
52
+ */
53
+ /**
54
+ * Extract text from a Pi tool result, WITHOUT the 8KB tail-cap.
55
+ *
56
+ * Used for `partialResult` in streaming `tool_execution_update` events, where Pi sends the accumulated
57
+ * output so far and truncating it would discard the head of a long-running command's output.
58
+ * The final result still goes through `extractToolResultText` (which applies the cap) because that
59
+ * is what gets persisted into `state.json`.
60
+ */
61
+ export function extractPartialResultText(result) {
62
+ try {
63
+ if (result === undefined || result === null)
64
+ return undefined;
65
+ const content = result.content;
66
+ const chunks = Array.isArray(content)
67
+ ? content
68
+ : [{ type: "text", text: typeof result === "string" ? result : undefined }];
69
+ let text = "";
70
+ for (const raw of chunks) {
71
+ const chunk = raw;
72
+ if (!chunk || chunk.type !== "text" || typeof chunk.text !== "string")
73
+ continue;
74
+ text += (text ? "\n" : "") + chunk.text;
75
+ }
76
+ return text || undefined;
77
+ }
78
+ catch {
79
+ return undefined;
80
+ }
81
+ }
82
+ export function extractToolResultText(result) {
83
+ try {
84
+ if (result === undefined || result === null)
85
+ return undefined;
86
+ const content = result.content;
87
+ const chunks = Array.isArray(content)
88
+ ? content
89
+ : [{ type: "text", text: typeof result === "string" ? result : undefined }];
90
+ let text = "";
91
+ for (const raw of chunks) {
92
+ // An image chunk is dropped WITHOUT being read: its `data` can be megabytes and nothing here wants it.
93
+ const chunk = raw;
94
+ if (!chunk || chunk.type !== "text" || typeof chunk.text !== "string")
95
+ continue;
96
+ text += (text ? "\n" : "") + chunk.text;
97
+ }
98
+ if (!text)
99
+ return undefined;
100
+ const details = result.details;
101
+ const bag = details && typeof details === "object" ? details : {};
102
+ const truncation = bag.truncation;
103
+ const fullOutputPath = typeof bag.fullOutputPath === "string" ? bag.fullOutputPath : undefined;
104
+ let truncated = typeof truncation === "string" && truncation.length > 0;
105
+ let droppedLines;
106
+ if (text.length > TOOL_RESULT_CAP) {
107
+ const lines = text.split("\n");
108
+ const kept = [];
109
+ let used = 0;
110
+ for (let i = lines.length - 1; i >= 0; i--) {
111
+ if (used + lines[i].length > TOOL_RESULT_CAP)
112
+ break;
113
+ used += lines[i].length + 1;
114
+ kept.unshift(lines[i]);
115
+ }
116
+ if (!kept.length)
117
+ kept.push(lines[lines.length - 1].slice(-TOOL_RESULT_CAP));
118
+ droppedLines = lines.length - kept.length;
119
+ text = kept.join("\n");
120
+ truncated = true;
121
+ }
122
+ return {
123
+ text,
124
+ ...(truncated ? { truncated: true } : {}),
125
+ ...(droppedLines ? { droppedLines } : {}),
126
+ ...(fullOutputPath ? { fullOutputPath } : {}),
127
+ };
128
+ }
129
+ catch {
130
+ return undefined;
131
+ }
132
+ }
133
+ /** Argument fields that name a FILE, in the order the tools that read files tend to spell them. */
134
+ const PATH_KEYS = ["path", "file_path", "filePath", "target_file", "filename", "file"];
135
+ /** Argument fields that name a SEARCH, which is the thing a human wants to see on a `grep` row. */
136
+ const PATTERN_KEYS = ["pattern", "query", "regex", "search", "glob"];
137
+ /** Argument fields that name a COMMAND LINE. */
138
+ const COMMAND_KEYS = ["command", "cmd", "script"];
139
+ /**
140
+ * Which argument field names what a given tool was aimed at.
141
+ *
142
+ * A per-tool table rather than one generic scan, because the generic answer is wrong in a way a person
143
+ * would notice: scanning `path` before `command` would label a `bash` row with a working directory, and
144
+ * scanning `pattern` before `path` would label a `read` row with nothing at all. Unknown tools fall
145
+ * back to the union, which is imprecise by construction - and imprecise is acceptable here, because a
146
+ * missing label costs the reader one line and a WRONG one costs them trust in every other label.
147
+ */
148
+ const TARGET_KEYS = {
149
+ read: PATH_KEYS, write: PATH_KEYS, edit: PATH_KEYS, multiedit: PATH_KEYS, notebookread: PATH_KEYS, notebookedit: PATH_KEYS,
150
+ glob: PATTERN_KEYS, grep: PATTERN_KEYS, search: PATTERN_KEYS,
151
+ bash: COMMAND_KEYS, shell: COMMAND_KEYS, run: COMMAND_KEYS,
152
+ };
153
+ const FALLBACK_KEYS = [...COMMAND_KEYS, ...PATH_KEYS, ...PATTERN_KEYS];
154
+ /** One line, whitespace collapsed, hard-capped. The ONLY way a value becomes text in this module. */
155
+ const oneLine = (value) => {
156
+ const collapsed = value.replace(/\s+/g, " ").trim();
157
+ if (!collapsed)
158
+ return "";
159
+ return collapsed.length > TOOL_DETAIL_CAP ? `${collapsed.slice(0, TOOL_DETAIL_CAP - 1)}…` : collapsed;
160
+ };
161
+ /**
162
+ * The one line that tells a reader what a tool call was FOR: the file it opened, the pattern it searched
163
+ * for, the command it ran.
164
+ *
165
+ * Returns `undefined` rather than a placeholder when nothing is recognised, so a row omits the column
166
+ * instead of rendering a column of emptiness.
167
+ *
168
+ * Exported so the mapping can be asserted without spawning a child, which is the only way a table this
169
+ * shape can be regression-tested at all.
170
+ */
171
+ export function describeToolCall(name, args) {
172
+ // A QUESTION NAMES ITSELF. The generic path reads a target-ish string out of the arguments and a
173
+ // question has none, so it fell through to the preparing placeholder - which left every settled
174
+ // question row headed 「正在生成参数…」 above the question itself. The row is the decision; the header
175
+ // should say which one.
176
+ if (name.trim().toLowerCase() === "question") {
177
+ const asked = readQuestionCall(name, args);
178
+ if (asked?.items.length)
179
+ return oneLine(asked.items.length === 1 ? asked.items[0].question : `${asked.items.length} 个问题`);
180
+ }
181
+ if (args === null || typeof args !== "object" || Array.isArray(args))
182
+ return undefined;
183
+ const record = args;
184
+ for (const key of TARGET_KEYS[name.trim().toLowerCase()] ?? FALLBACK_KEYS) {
185
+ const value = record[key];
186
+ if (typeof value !== "string")
187
+ continue;
188
+ const line = oneLine(value);
189
+ if (line)
190
+ return line;
191
+ }
192
+ return undefined;
193
+ }
194
+ /**
195
+ * THE SAME LINE, READ OUT OF A CALL THAT IS STILL BEING WRITTEN.
196
+ *
197
+ * The block for a call appears the instant the model starts writing it, and for an `edit` that is several
198
+ * seconds before the arguments are complete. Showing 「工具 · 正在生成参数…」 through all of it says the
199
+ * reader nothing they can act on - not WHICH tool, and not what it is aimed at, which are the two things
200
+ * the finished block is going to say. So the same `describeToolCall` mapping runs against the fragments
201
+ * that have arrived so far.
202
+ *
203
+ * TWO STEPS, because a partial JSON document almost never parses. The fragments are tried whole first -
204
+ * that is the case where the last one closed the object. Failing that, the FIRST `"key": "value"` pair in
205
+ * the text is read out on its own, and its value does not have to be CLOSED - a fragment usually stops
206
+ * mid-string, and a path that has arrived half-written still says more than a placeholder does. A fragment
207
+ * that has produced neither yet yields `undefined`, and the caller decides what an unknown call says
208
+ * rather than this module inventing a word for it.
209
+ *
210
+ * The pair is read with a pattern rather than by parsing a repaired document: repairing JSON is a parser's
211
+ * job, and a half-repaired document here would risk naming the wrong file - the one thing this line must
212
+ * never do.
213
+ */
214
+ export function describeToolCallInProgress(name, argumentsSoFar) {
215
+ const text = argumentsSoFar.trim();
216
+ if (!text)
217
+ return undefined;
218
+ try {
219
+ const parsed = JSON.parse(text);
220
+ const described = describeToolCall(name, parsed);
221
+ if (described)
222
+ return described;
223
+ }
224
+ catch { /* the document is still being written, which is the normal case here */ }
225
+ const pair = /"([A-Za-z_][A-Za-z0-9_-]*)"\s*:\s*"((?:[^"\\]|\\.)*)/.exec(text);
226
+ if (!pair)
227
+ return undefined;
228
+ // The closing quote is OPTIONAL in the pattern because a fragment almost always stops mid-string, and a
229
+ // path that has arrived half-written is still worth more than the placeholder word. What is captured is
230
+ // unescaped because an escaped quote is part of the VALUE, not the end of it - without this, a file
231
+ // named with a quote in it would be displayed with a backslash the reader never typed.
232
+ return describeToolCall(name, { [pair[1]]: pair[2].replace(/\\(["\\])/g, "$1") });
233
+ }
234
+ /**
235
+ * How one non-string argument value is NAMED without being read.
236
+ *
237
+ * THE MOST IMPORTANT LINE IN THIS FILE. An `edit` tool's arguments routinely carry the replacement text
238
+ * for a whole file, and a `bash` call's arguments can carry anything the model wrote. Rendering such a
239
+ * value - even truncated, even `JSON.stringify`d - would put file contents into a field that is
240
+ * persisted in `state.json` and broadcast to every browser, which is precisely the line
241
+ * `SubagentToolCall.detail` is documented as drawing. So a non-primitive contributes its KIND and
242
+ * nothing else: a reader learns that a patch was applied or an array was passed, and cannot learn what
243
+ * was in it.
244
+ */
245
+ const describeShape = (value) => {
246
+ if (value === null)
247
+ return "null";
248
+ if (Array.isArray(value))
249
+ return `(数组 ${value.length} 项)`;
250
+ switch (typeof value) {
251
+ case "number": return Number.isFinite(value) ? String(value) : undefined;
252
+ case "boolean": return String(value);
253
+ case "object": return "(对象)";
254
+ default: return undefined;
255
+ }
256
+ };
257
+ /**
258
+ * Every parameter of one call, as a bounded list of `key`/`value` pairs a block can show when expanded.
259
+ *
260
+ * THIS IS THE SAME LINE `describeToolCall` DRAWS, APPLIED PER KEY. `describeToolCall` answers "what was
261
+ * this aimed at" with one label; this answers "what was this given" with the whole bounded list, which is
262
+ * the difference between a row that says `bash` and a block that says which command, plus its timeout
263
+ * and description. Both are derived: a string is whitespace-collapsed and capped at `TOOL_DETAIL_CAP`, and
264
+ * anything that is not a string or a number or a boolean becomes a type word (see `describeShape`).
265
+ *
266
+ * Order is Pi's own key order rather than this module's table order, because once every key is listed the
267
+ * per-tool table has said everything it knows - and a reader scanning a list wants the order the caller
268
+ * wrote it in, not one this file invented.
269
+ *
270
+ * Capped at `TOOL_ARG_CAP` ENTRIES, and the cap is applied by taking the first N rather than by sampling
271
+ * across the object: a truncated tail is a prefix of the real argument list, so what is shown is never
272
+ * a selection that implies the omitted keys did not exist.
273
+ *
274
+ * Returns `undefined` when there is nothing readable at all, so a call with no usable arguments renders
275
+ * no parameter section rather than an empty one.
276
+ */
277
+ export function describeToolCallArgs(args) {
278
+ if (args === null || typeof args !== "object" || Array.isArray(args))
279
+ return undefined;
280
+ const listed = [];
281
+ // `Object.keys` rather than `for..in`: a key this file cannot render is skipped rather than emitted
282
+ // with an empty value, and an inherited key is not a parameter Pi sent.
283
+ for (const key of Object.keys(args)) {
284
+ if (listed.length >= TOOL_ARG_CAP)
285
+ break;
286
+ const raw = args[key];
287
+ const value = typeof raw === "string" ? oneLine(raw) : describeShape(raw);
288
+ if (value === undefined || value === "")
289
+ continue;
290
+ listed.push({ key, value });
291
+ }
292
+ return listed.length ? listed : undefined;
293
+ }
294
+ /**
295
+ * READS A `question` CALL'S ARGUMENTS INTO THE SHAPE THE TRANSCRIPT RENDERS, OR NOTHING.
296
+ *
297
+ * Both shapes are accepted because the two references differ and both are in the wild: OpenCode sends
298
+ * `questions: [{ question, header, options: [{label, description}], multiple }]`
299
+ * (`packages/core/src/tool/question.ts:25`) and this project's own extension sends
300
+ * `{ question, options: string[], multiple?, extraNote? }`. A question with no options, or options that
301
+ * are not a list of strings, is not a question - so it returns nothing and the call renders as the
302
+ * ordinary tool call it is, rather than as a card with nothing in it.
303
+ *
304
+ * Ids are MINTED HERE when the caller did not send one, and that is what makes the answer pair by
305
+ * identity rather than by position: a person answering question 2 must not be recorded as answering
306
+ * question 1 because one of them was dropped.
307
+ */
308
+ export function readQuestionCall(name, args) {
309
+ if (name !== "question")
310
+ return undefined;
311
+ const raw = args;
312
+ if (!raw || typeof raw !== "object")
313
+ return undefined;
314
+ const source = Array.isArray(raw.questions) ? raw.questions : [raw];
315
+ const items = [];
316
+ for (const entry of source) {
317
+ if (!entry || typeof entry !== "object")
318
+ return undefined;
319
+ const item = entry;
320
+ if (typeof item.question !== "string" || !item.question.trim())
321
+ return undefined;
322
+ if (!Array.isArray(item.options))
323
+ return undefined;
324
+ const options = item.options.map((option) => (typeof option === "string" ? option : option?.label)).filter((option) => typeof option === "string" && option.trim().length > 0);
325
+ // NO OPTIONS IS NOT A QUESTION. A `question` call with an empty list would render a card the person
326
+ // cannot answer, and the tool would then block for thirty minutes on it.
327
+ if (!options.length)
328
+ return undefined;
329
+ items.push({
330
+ id: typeof item.id === "string" && item.id ? item.id : randomUUID(),
331
+ ...(typeof item.header === "string" && item.header ? { header: item.header } : {}),
332
+ question: item.question,
333
+ options,
334
+ multiple: item.multiple === true,
335
+ // Defaults ON, matching the extension's own schema: a question that asked for an optional note and
336
+ // did not get one should show the field, not silently drop it.
337
+ extraNote: item.extraNote !== false,
338
+ });
339
+ }
340
+ return items.length ? { items, status: "pending" } : undefined;
341
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * A MOUNTED TOOL ASKING THE MODEL A QUESTION - bookkeeping, ceilings and the consent gate's server half.
3
+ *
4
+ * WHY A TOOL GETS THIS AT ALL. A tool author who wants a model in their tool should not be writing a
5
+ * client: no API key to store, no provider endpoint, no retry, no streaming, no cost ceiling. Pi already
6
+ * holds the credentials and the model configuration, so Super Pi owns the call and the tool asks for it
7
+ * over the same relative API it already uses for its Python jobs.
8
+ *
9
+ * WHY IT IS A COMPLETION AND NOT AN AGENT. `askOnce` spawns Pi with `--no-extensions --no-skills
10
+ * --no-mcp --no-context-files --no-prompt-templates`, so the model answering a tool's prompt has no
11
+ * tools, no files and no history. A tool that could make the agent run things would be handing a
12
+ * sandboxed iframe the user's whole machine, and the iframe is exactly the thing that must not have it.
13
+ *
14
+ * WHY EVERY CEILING IS HERE AND NOT IN THE FRAME. The caller is an opaque sandbox on someone else's
15
+ * machine. Prompt size, answer size, duration, and how many calls may be in flight at once are all
16
+ * decided by this file, because "the tool asked nicely" is not a limit.
17
+ */
18
+ /** The slice of the runtime this needs, declared structurally for the same reason `KnowledgeRuntime` is. */
19
+ export type ToolLlmRuntime = {
20
+ /** OPTIONAL, exactly as it is on `AgentRuntime`: a runtime with no Pi behind it has none. */
21
+ askOnce?(input: {
22
+ prompt: string;
23
+ timeoutMs: number;
24
+ cwd: string;
25
+ signal?: AbortSignal;
26
+ }): Promise<string>;
27
+ };
28
+ export type ToolLlmStatus = "running" | "succeeded" | "failed" | "cancelled" | "timed_out";
29
+ export type ToolLlmRun = {
30
+ id: string;
31
+ toolId: string;
32
+ status: ToolLlmStatus;
33
+ startedAt: string;
34
+ finishedAt?: string;
35
+ /** The model's answer. Bounded by MAX_TOOL_LLM_RESPONSE_BYTES, and this is the only copy. */
36
+ text: string;
37
+ promptChars: number;
38
+ elapsedMs?: number;
39
+ error?: string;
40
+ };
41
+ export type ToolLlmRequest = {
42
+ toolId: string;
43
+ prompt: string;
44
+ system?: string;
45
+ timeoutMs?: number;
46
+ ownerId?: string;
47
+ };
48
+ /** 32KB of prompt is a paragraph of a book; more than that is a tool trying to move a transcript. */
49
+ export declare const MAX_TOOL_LLM_PROMPT_BYTES = 32000;
50
+ /** Answers are clipped rather than refused: a truncated answer is still an answer, and the model may be
51
+ * mid-sentence when the ceiling lands. The clip is visible in `chars` being lower than expected. */
52
+ export declare const MAX_TOOL_LLM_RESPONSE_BYTES = 64000;
53
+ export declare const MAX_TOOL_LLM_TIMEOUT_MS: number;
54
+ export declare class ToolLlmService {
55
+ private readonly runtime;
56
+ private readonly cwd;
57
+ private readonly runs;
58
+ constructor(runtime: ToolLlmRuntime | undefined, cwd: string);
59
+ /** WHY A MISSING RUNTIME IS A SENTENCE AND NOT A 500. The welcome runtime has no Pi behind it, and a
60
+ * tool asking a question there should be told the machine cannot answer it. */
61
+ get available(): boolean;
62
+ start(request: ToolLlmRequest): ToolLlmRun;
63
+ list(toolId: string, ownerId: string): {
64
+ id: string;
65
+ status: ToolLlmStatus;
66
+ startedAt: string;
67
+ finishedAt: string | undefined;
68
+ }[];
69
+ get(id: string, toolId: string): ToolLlmRun | undefined;
70
+ cancel(id: string, toolId: string): ToolLlmRun | undefined;
71
+ wait(id: string, toolId: string, signal?: AbortSignal): Promise<ToolLlmRun>;
72
+ }
@@ -0,0 +1,146 @@
1
+ /**
2
+ * A MOUNTED TOOL ASKING THE MODEL A QUESTION - bookkeeping, ceilings and the consent gate's server half.
3
+ *
4
+ * WHY A TOOL GETS THIS AT ALL. A tool author who wants a model in their tool should not be writing a
5
+ * client: no API key to store, no provider endpoint, no retry, no streaming, no cost ceiling. Pi already
6
+ * holds the credentials and the model configuration, so Super Pi owns the call and the tool asks for it
7
+ * over the same relative API it already uses for its Python jobs.
8
+ *
9
+ * WHY IT IS A COMPLETION AND NOT AN AGENT. `askOnce` spawns Pi with `--no-extensions --no-skills
10
+ * --no-mcp --no-context-files --no-prompt-templates`, so the model answering a tool's prompt has no
11
+ * tools, no files and no history. A tool that could make the agent run things would be handing a
12
+ * sandboxed iframe the user's whole machine, and the iframe is exactly the thing that must not have it.
13
+ *
14
+ * WHY EVERY CEILING IS HERE AND NOT IN THE FRAME. The caller is an opaque sandbox on someone else's
15
+ * machine. Prompt size, answer size, duration, and how many calls may be in flight at once are all
16
+ * decided by this file, because "the tool asked nicely" is not a limit.
17
+ */
18
+ /** 32KB of prompt is a paragraph of a book; more than that is a tool trying to move a transcript. */
19
+ export const MAX_TOOL_LLM_PROMPT_BYTES = 32_000;
20
+ /** Answers are clipped rather than refused: a truncated answer is still an answer, and the model may be
21
+ * mid-sentence when the ceiling lands. The clip is visible in `chars` being lower than expected. */
22
+ export const MAX_TOOL_LLM_RESPONSE_BYTES = 64_000;
23
+ export const MAX_TOOL_LLM_TIMEOUT_MS = 5 * 60_000;
24
+ const DEFAULT_TOOL_LLM_TIMEOUT_MS = 60_000;
25
+ /** A tool that fires a hundred calls in a loop gets refused, loudly, instead of quietly costing money. */
26
+ const MAX_IN_FLIGHT_PER_TOOL = 3;
27
+ const MAX_IN_FLIGHT_TOTAL = 8;
28
+ export class ToolLlmService {
29
+ runtime;
30
+ cwd;
31
+ runs = new Map();
32
+ constructor(runtime, cwd) {
33
+ this.runtime = runtime;
34
+ this.cwd = cwd;
35
+ }
36
+ /** WHY A MISSING RUNTIME IS A SENTENCE AND NOT A 500. The welcome runtime has no Pi behind it, and a
37
+ * tool asking a question there should be told the machine cannot answer it. */
38
+ get available() { return typeof this.runtime?.askOnce === "function"; }
39
+ start(request) {
40
+ if (!this.available)
41
+ throw new Error("这台机器上没有可用的 Pi 运行时,工具无法调用模型。");
42
+ const prompt = typeof request.prompt === "string" ? request.prompt.trim() : "";
43
+ if (!prompt)
44
+ throw new Error("请提供要问模型的内容。");
45
+ if (Buffer.byteLength(prompt) > MAX_TOOL_LLM_PROMPT_BYTES)
46
+ throw new Error(`提问太长(上限 ${Math.round(MAX_TOOL_LLM_PROMPT_BYTES / 1024)}KB)。`);
47
+ const system = typeof request.system === "string" ? request.system.trim() : "";
48
+ if (system && Buffer.byteLength(system) > MAX_TOOL_LLM_PROMPT_BYTES)
49
+ throw new Error("系统提示太长。");
50
+ const running = [...this.runs.values()].filter((active) => active.run.status === "running");
51
+ if (running.length >= MAX_IN_FLIGHT_TOTAL)
52
+ throw new Error("已经有太多模型请求在排队,请稍后再试。");
53
+ if (running.filter((active) => active.run.toolId === request.toolId).length >= MAX_IN_FLIGHT_PER_TOOL)
54
+ throw new Error("这个工具同时在等的模型请求已经到上限了。");
55
+ const timeoutMs = Number.isFinite(request.timeoutMs) ? Math.max(1_000, Math.min(MAX_TOOL_LLM_TIMEOUT_MS, Math.floor(request.timeoutMs))) : DEFAULT_TOOL_LLM_TIMEOUT_MS;
56
+ const id = `toolllm_${randomId()}`;
57
+ const run = { id, toolId: request.toolId, status: "running", startedAt: new Date().toISOString(), text: "", promptChars: prompt.length };
58
+ const controller = new AbortController();
59
+ // The deadline is this service's own, not the frame's: a frame that stops polling does not get to keep
60
+ // a Pi process and a model call alive.
61
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
62
+ timer.unref();
63
+ const active = { run, ownerId: request.ownerId, controller, timer };
64
+ this.runs.set(id, active);
65
+ void (async () => {
66
+ try {
67
+ // Narrowed by `available` in `start`, and captured here: the service outlives any single call.
68
+ const ask = this.runtime?.askOnce?.bind(this.runtime);
69
+ if (!ask)
70
+ throw new Error("这台机器上没有可用的 Pi 运行时,工具无法调用模型。");
71
+ const answer = await ask({
72
+ prompt: system ? `${system}\n\n---\n\n${prompt}` : prompt,
73
+ timeoutMs,
74
+ cwd: this.cwd,
75
+ signal: controller.signal,
76
+ });
77
+ if (active.run.status !== "running")
78
+ return;
79
+ active.run.text = clip(answer);
80
+ }
81
+ catch (error) {
82
+ if (active.run.status !== "running")
83
+ return;
84
+ const message = error instanceof Error ? error.message : String(error);
85
+ active.run.status = controller.signal.aborted && active.run.finishedAt === undefined ? "timed_out" : "failed";
86
+ active.run.error = controller.signal.aborted ? `模型在 ${Math.round(timeoutMs / 1000)} 秒内没有返回` : message;
87
+ }
88
+ finally {
89
+ clearTimeout(timer);
90
+ if (active.run.status === "running")
91
+ active.run.status = "succeeded";
92
+ active.run.finishedAt ??= new Date().toISOString();
93
+ active.run.elapsedMs = Date.now() - Date.parse(active.run.startedAt);
94
+ // Bounded memory: a tool that made a thousand calls must not leave a thousand answers in the map.
95
+ if (this.runs.size > 64) {
96
+ const oldest = [...this.runs.entries()].filter(([, entry]) => entry.run.status !== "running").sort((a, b) => Date.parse(a[1].run.finishedAt ?? "") - Date.parse(b[1].run.finishedAt ?? "")).slice(0, this.runs.size - 64);
97
+ for (const [key] of oldest)
98
+ this.runs.delete(key);
99
+ }
100
+ }
101
+ })();
102
+ return copy(run);
103
+ }
104
+ list(toolId, ownerId) {
105
+ return [...this.runs.values()].reverse()
106
+ .filter(entry => entry.run.toolId === toolId && entry.ownerId === ownerId)
107
+ .sort((a, b) => Number(b.run.status === "running") - Number(a.run.status === "running"))
108
+ .slice(0, 16)
109
+ .map(({ run: { id, status, startedAt, finishedAt } }) => ({ id, status, startedAt, finishedAt }));
110
+ }
111
+ get(id, toolId) { const active = this.runs.get(id); return active?.run.toolId === toolId ? copy(active.run) : undefined; }
112
+ cancel(id, toolId) {
113
+ const active = this.runs.get(id);
114
+ if (!active || active.run.toolId !== toolId)
115
+ return undefined;
116
+ if (active.run.status === "running") {
117
+ active.controller.abort();
118
+ active.run.status = "cancelled";
119
+ active.run.error = "已取消";
120
+ }
121
+ return copy(active.run);
122
+ }
123
+ async wait(id, toolId, signal) {
124
+ const deadline = Date.now() + MAX_TOOL_LLM_TIMEOUT_MS + 5_000;
125
+ for (;;) {
126
+ const run = this.get(id, toolId);
127
+ if (!run)
128
+ throw new Error("这次模型请求不存在或已经过期。");
129
+ if (run.status !== "running")
130
+ return run;
131
+ if (signal?.aborted)
132
+ throw new Error("已取消");
133
+ if (Date.now() > deadline)
134
+ throw new Error("等待模型回答超时。");
135
+ await new Promise((resolve) => setTimeout(resolve, 250));
136
+ }
137
+ }
138
+ }
139
+ function clip(text) {
140
+ const buffer = Buffer.from(text, "utf8");
141
+ if (buffer.length <= MAX_TOOL_LLM_RESPONSE_BYTES)
142
+ return text;
143
+ return buffer.subarray(0, MAX_TOOL_LLM_RESPONSE_BYTES).toString("utf8");
144
+ }
145
+ function copy(run) { return { ...run }; }
146
+ function randomId() { return globalThis.crypto?.randomUUID?.() ?? Math.random().toString(36).slice(2); }