@yanglaofish/fishtools 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (247) hide show
  1. package/README.md +33 -5
  2. package/bin/fst.js +1 -1
  3. package/manual/README.md +33 -5
  4. package/manual/docs/deployment.md +3 -3
  5. package/manual/docs/examples/script-plugin/LICENSE +21 -0
  6. package/manual/docs/examples/script-plugin/README.md +64 -0
  7. package/manual/docs/examples/script-plugin/index.js +39 -0
  8. package/manual/docs/examples/script-plugin/package.json +9 -0
  9. package/manual/docs/examples/script-plugin/scripts/benchmark.py +23 -0
  10. package/manual/docs/kernel-generation.md +97 -0
  11. package/manual/docs/modules.md +57 -0
  12. package/manual/docs/plugin-development.md +163 -12
  13. package/manual/docs/releases.md +23 -0
  14. package/manual/docs/research/2026-10-11-plugin-kernel-capabilities.md +6 -6
  15. package/manual/docs/roadmap.md +16 -3
  16. package/manual/docs/superpowers/plans/2026-10-09-workflow-mvp.md +5 -5
  17. package/manual/docs/superpowers/plans/2026-10-11-public-plugin-fixes.md +2 -2
  18. package/manual/docs/superpowers/plans/2026-10-12-kernel-generation.md +22 -0
  19. package/manual/docs/superpowers/plans/2026-10-12-modular-kernel.md +40 -0
  20. package/manual/docs/superpowers/plans/2026-10-12-plugin-developer-experience.md +50 -0
  21. package/manual/docs/superpowers/reviews/2026-10-12-kernel-generation-review.md +27 -0
  22. package/manual/docs/superpowers/reviews/2026-10-12-modular-kernel-review.md +32 -0
  23. package/manual/docs/superpowers/reviews/2026-10-12-plugin-release-review.md +20 -0
  24. package/manual/docs/superpowers/reviews/2026-10-13-kernel-runtime-release-review.md +19 -0
  25. package/manual/docs/superpowers/specs/2026-10-12-action-network-policy-design.md +52 -0
  26. package/manual/docs/superpowers/specs/2026-10-12-kernel-generation-design.md +38 -0
  27. package/manual/docs/superpowers/specs/2026-10-12-modular-kernel-design.md +70 -0
  28. package/manual/docs/superpowers/specs/2026-10-12-plugin-developer-experience.md +22 -0
  29. package/manual/docs/superpowers/specs/2026-10-12-plugin-readiness-design.md +21 -0
  30. package/manual/docs/superpowers/specs/2026-10-12-runtime-maintenance-granularity-design.md +35 -0
  31. package/manual/docs/superpowers/specs/2026-10-12-workflow-variation-design.md +19 -0
  32. package/manual/docs/verification.md +58 -1
  33. package/manual/packages/core/README.md +44 -0
  34. package/manual/packages/core/package.json +38 -0
  35. package/manual/packages/core/src/application.js +268 -87
  36. package/manual/packages/core/src/bundle.js +2 -0
  37. package/manual/packages/core/src/development-watch-worker.js +69 -0
  38. package/manual/packages/core/src/development.js +146 -0
  39. package/manual/packages/core/src/environments.js +2 -0
  40. package/manual/packages/core/src/export-snapshot.js +42 -0
  41. package/manual/packages/core/src/plugin-update.js +108 -0
  42. package/manual/packages/core/src/process.js +2 -0
  43. package/manual/packages/core/src/resources.js +31 -0
  44. package/manual/packages/core/src/version.js +2 -0
  45. package/manual/packages/fst-cli/LICENSE +21 -0
  46. package/manual/packages/fst-cli/README.md +54 -0
  47. package/manual/packages/fst-cli/bin/fst.js +124 -0
  48. package/manual/packages/fst-cli/package.json +49 -0
  49. package/manual/packages/fst-cli/src/development.js +53 -0
  50. package/{node_modules/@mytools/core → manual/packages/fst-cli}/src/terminal/model.js +1 -1
  51. package/{node_modules/@mytools/core → manual/packages/fst-cli}/src/terminal/navigation.js +1 -1
  52. package/{node_modules/@mytools/core → manual/packages/fst-cli}/src/terminal/presentation.js +9 -1
  53. package/{node_modules/@mytools/core → manual/packages/fst-cli}/src/terminal/run-feed.js +31 -5
  54. package/{node_modules/@mytools/core → manual/packages/fst-cli}/src/terminal/run-viewer.js +9 -7
  55. package/{node_modules/@mytools/core → manual/packages/fst-cli}/src/terminal/schema.js +1 -1
  56. package/manual/packages/{core → fst-cli}/src/terminal/session.js +137 -9
  57. package/manual/packages/{core → fst-cli}/src/terminal/view.js +20 -3
  58. package/{node_modules/@mytools/core → manual/packages/fst-cli}/src/terminal/workflow-menu.js +17 -2
  59. package/manual/packages/fst-devtools/LICENSE +21 -0
  60. package/manual/packages/fst-devtools/README.md +28 -0
  61. package/manual/packages/fst-devtools/package.json +29 -0
  62. package/{node_modules/@mytools/core → manual/packages/fst-devtools}/src/documentation.js +3 -1
  63. package/manual/packages/fst-devtools/src/plugin-quality.js +136 -0
  64. package/manual/packages/fst-devtools/src/plugin-tools.js +152 -0
  65. package/manual/packages/fst-logs/LICENSE +21 -0
  66. package/manual/packages/fst-logs/README.md +56 -0
  67. package/manual/packages/fst-logs/package.json +24 -0
  68. package/manual/packages/fst-logs/src/log-bounds.js +91 -0
  69. package/manual/packages/fst-logs/src/run-logs.js +239 -0
  70. package/manual/packages/fst-platform/LICENSE +21 -0
  71. package/manual/packages/fst-platform/README.md +67 -0
  72. package/manual/packages/fst-platform/package.json +33 -0
  73. package/manual/packages/fst-platform/src/bundle.js +17 -0
  74. package/manual/packages/fst-platform/src/environments.js +67 -0
  75. package/manual/packages/fst-platform/src/file-probe-engine.js +183 -0
  76. package/manual/packages/fst-platform/src/file-probe-worker.js +43 -0
  77. package/manual/packages/fst-platform/src/file-probe.js +6 -0
  78. package/manual/packages/fst-platform/src/json.js +5 -0
  79. package/manual/packages/fst-platform/src/network.js +199 -0
  80. package/manual/packages/fst-platform/src/npm.js +11 -0
  81. package/manual/packages/fst-platform/src/process.js +110 -0
  82. package/manual/packages/fst-plugin/LICENSE +21 -0
  83. package/manual/packages/fst-plugin/README.md +29 -0
  84. package/manual/packages/fst-plugin/package.json +29 -0
  85. package/manual/packages/fst-plugin/src/contracts.js +86 -0
  86. package/manual/packages/fst-plugin/src/host.js +232 -0
  87. package/manual/packages/fst-plugin/src/loader.js +21 -0
  88. package/manual/packages/fst-plugin/src/privileges.js +91 -0
  89. package/manual/packages/{core → fst-plugin}/src/runtime.js +20 -4
  90. package/manual/packages/fst-workflow/LICENSE +21 -0
  91. package/manual/packages/fst-workflow/README.md +28 -0
  92. package/manual/packages/fst-workflow/package.json +24 -0
  93. package/{node_modules/@mytools/core → manual/packages/fst-workflow}/src/control.js +3 -2
  94. package/manual/packages/{core → fst-workflow}/src/engine.js +2 -2
  95. package/manual/packages/fst-workspace/LICENSE +21 -0
  96. package/manual/packages/fst-workspace/README.md +32 -0
  97. package/manual/packages/fst-workspace/package.json +34 -0
  98. package/{node_modules/@mytools/core → manual/packages/fst-workspace}/src/bundle-workspace.js +1 -1
  99. package/manual/packages/fst-workspace/src/index.js +3 -0
  100. package/manual/packages/fst-workspace/src/plugin-installations.js +84 -0
  101. package/manual/packages/fst-workspace/src/plugins.js +35 -0
  102. package/{node_modules/@mytools/core → manual/packages/fst-workspace}/src/workflows.js +41 -21
  103. package/manual/packages/pack/LICENSE +21 -0
  104. package/manual/packages/pack/README.md +31 -0
  105. package/manual/packages/pack/archive.js +15 -0
  106. package/manual/packages/pack/dependencies.js +105 -0
  107. package/manual/packages/pack/environments.js +50 -0
  108. package/manual/packages/pack/index.js +103 -0
  109. package/manual/packages/pack/package.json +29 -0
  110. package/manual/packages/pack/runtime.js +61 -0
  111. package/manual/packages/sdk/README.md +31 -0
  112. package/manual/packages/sdk/conditions.js +1 -0
  113. package/manual/packages/sdk/package.json +23 -1
  114. package/manual/packages/sdk/schema-path.js +31 -0
  115. package/{node_modules/@mytools/core/src → manual/packages/sdk}/validation.js +22 -9
  116. package/manual/plugins/web/README.md +29 -0
  117. package/manual/tests/application.test.js +6 -4
  118. package/node_modules/@mytools/core/README.md +44 -0
  119. package/node_modules/@mytools/core/package.json +17 -15
  120. package/node_modules/@mytools/core/src/application.js +268 -87
  121. package/node_modules/@mytools/core/src/bundle.js +2 -17
  122. package/node_modules/@mytools/core/src/development-watch-worker.js +69 -0
  123. package/node_modules/@mytools/core/src/development.js +146 -0
  124. package/node_modules/@mytools/core/src/environments.js +2 -29
  125. package/node_modules/@mytools/core/src/export-snapshot.js +42 -0
  126. package/node_modules/@mytools/core/src/plugin-update.js +108 -0
  127. package/node_modules/@mytools/core/src/process.js +2 -71
  128. package/node_modules/@mytools/core/src/version.js +1 -1
  129. package/node_modules/@mytools/fst-cli/LICENSE +21 -0
  130. package/node_modules/@mytools/fst-cli/README.md +54 -0
  131. package/node_modules/@mytools/fst-cli/bin/fst.js +124 -0
  132. package/node_modules/@mytools/fst-cli/package.json +49 -0
  133. package/node_modules/@mytools/fst-cli/src/cli-run.js +12 -0
  134. package/node_modules/@mytools/fst-cli/src/development.js +53 -0
  135. package/node_modules/@mytools/fst-cli/src/terminal/conditions.js +32 -0
  136. package/node_modules/@mytools/fst-cli/src/terminal/log-viewer.js +45 -0
  137. package/node_modules/@mytools/fst-cli/src/terminal/model.js +104 -0
  138. package/node_modules/@mytools/fst-cli/src/terminal/navigation.js +17 -0
  139. package/node_modules/@mytools/fst-cli/src/terminal/presentation.js +50 -0
  140. package/{manual/packages/core → node_modules/@mytools/fst-cli}/src/terminal/run-feed.js +31 -5
  141. package/node_modules/@mytools/fst-cli/src/terminal/run-presentation.js +60 -0
  142. package/node_modules/@mytools/fst-cli/src/terminal/run-viewer.js +106 -0
  143. package/node_modules/@mytools/fst-cli/src/terminal/schema.js +52 -0
  144. package/node_modules/@mytools/{core → fst-cli}/src/terminal/session.js +137 -9
  145. package/node_modules/@mytools/fst-cli/src/terminal/theme.js +29 -0
  146. package/node_modules/@mytools/{core → fst-cli}/src/terminal/view.js +20 -3
  147. package/node_modules/@mytools/fst-cli/src/terminal/workflow-menu.js +65 -0
  148. package/node_modules/@mytools/fst-devtools/LICENSE +21 -0
  149. package/node_modules/@mytools/fst-devtools/README.md +28 -0
  150. package/node_modules/@mytools/fst-devtools/package.json +29 -0
  151. package/node_modules/@mytools/fst-devtools/src/documentation.js +67 -0
  152. package/node_modules/@mytools/fst-devtools/src/plugin-quality.js +136 -0
  153. package/node_modules/@mytools/fst-devtools/src/plugin-tools.js +152 -0
  154. package/node_modules/@mytools/fst-logs/LICENSE +21 -0
  155. package/node_modules/@mytools/fst-logs/README.md +56 -0
  156. package/node_modules/@mytools/fst-logs/package.json +24 -0
  157. package/node_modules/@mytools/fst-logs/src/log-bounds.js +91 -0
  158. package/node_modules/@mytools/fst-logs/src/markdown-log.js +55 -0
  159. package/node_modules/@mytools/fst-logs/src/run-logs.js +239 -0
  160. package/node_modules/@mytools/fst-platform/LICENSE +21 -0
  161. package/node_modules/@mytools/fst-platform/README.md +67 -0
  162. package/node_modules/@mytools/fst-platform/package.json +33 -0
  163. package/node_modules/@mytools/fst-platform/src/bundle.js +17 -0
  164. package/node_modules/@mytools/fst-platform/src/environments.js +67 -0
  165. package/node_modules/@mytools/fst-platform/src/file-probe-engine.js +183 -0
  166. package/node_modules/@mytools/fst-platform/src/file-probe-worker.js +43 -0
  167. package/node_modules/@mytools/fst-platform/src/file-probe.js +6 -0
  168. package/node_modules/@mytools/fst-platform/src/json.js +5 -0
  169. package/node_modules/@mytools/fst-platform/src/network.js +199 -0
  170. package/node_modules/@mytools/fst-platform/src/npm.js +11 -0
  171. package/node_modules/@mytools/fst-platform/src/process.js +110 -0
  172. package/node_modules/@mytools/fst-plugin/LICENSE +21 -0
  173. package/node_modules/@mytools/fst-plugin/README.md +29 -0
  174. package/node_modules/@mytools/fst-plugin/package.json +29 -0
  175. package/node_modules/@mytools/fst-plugin/src/contracts.js +86 -0
  176. package/node_modules/@mytools/fst-plugin/src/host.js +232 -0
  177. package/node_modules/@mytools/fst-plugin/src/loader.js +21 -0
  178. package/node_modules/@mytools/fst-plugin/src/privileges.js +91 -0
  179. package/node_modules/@mytools/{core → fst-plugin}/src/runtime.js +20 -4
  180. package/node_modules/@mytools/fst-workflow/LICENSE +21 -0
  181. package/node_modules/@mytools/fst-workflow/README.md +28 -0
  182. package/node_modules/@mytools/fst-workflow/package.json +24 -0
  183. package/node_modules/@mytools/fst-workflow/src/control.js +64 -0
  184. package/node_modules/@mytools/{core → fst-workflow}/src/engine.js +2 -2
  185. package/node_modules/@mytools/fst-workspace/LICENSE +21 -0
  186. package/node_modules/@mytools/fst-workspace/README.md +32 -0
  187. package/node_modules/@mytools/fst-workspace/package.json +34 -0
  188. package/node_modules/@mytools/fst-workspace/src/bundle-workspace.js +39 -0
  189. package/node_modules/@mytools/fst-workspace/src/index.js +3 -0
  190. package/node_modules/@mytools/fst-workspace/src/plugin-installations.js +84 -0
  191. package/node_modules/@mytools/fst-workspace/src/plugins.js +35 -0
  192. package/node_modules/@mytools/fst-workspace/src/project.js +29 -0
  193. package/node_modules/@mytools/fst-workspace/src/workflows.js +150 -0
  194. package/node_modules/@mytools/fst-workspace/templates/control-demo.yaml +47 -0
  195. package/node_modules/@mytools/fst-workspace/templates/hello.yaml +35 -0
  196. package/node_modules/@mytools/fst-workspace/templates/python-check.yaml +26 -0
  197. package/node_modules/@mytools/fst-workspace/templates/system-check.yaml +11 -0
  198. package/node_modules/@mytools/pack/README.md +31 -0
  199. package/node_modules/@mytools/pack/dependencies.js +15 -3
  200. package/node_modules/@mytools/pack/environments.js +1 -1
  201. package/node_modules/@mytools/pack/index.js +33 -25
  202. package/node_modules/@mytools/pack/package.json +29 -1
  203. package/node_modules/@mytools/sdk/README.md +31 -0
  204. package/node_modules/@mytools/sdk/conditions.js +1 -0
  205. package/node_modules/@mytools/sdk/diagnostics.js +27 -0
  206. package/node_modules/@mytools/sdk/package.json +23 -1
  207. package/node_modules/@mytools/sdk/schema-path.js +31 -0
  208. package/node_modules/@mytools/sdk/validation.js +78 -0
  209. package/node_modules/@mytools/web/README.md +29 -0
  210. package/node_modules/@mytools/web/package.json +7 -0
  211. package/node_modules/@mytools/web/public/THIRD_PARTY_NOTICES.txt +1275 -1076
  212. package/node_modules/@mytools/web/public/assets/index-BaVzHycP.js +70 -0
  213. package/node_modules/@mytools/web/public/assets/index-DA8Ae92t.css +1 -0
  214. package/node_modules/@mytools/web/public/index.html +2 -2
  215. package/node_modules/@mytools/web/server.js +24 -17
  216. package/node_modules/@mytools/web/src/model.js +84 -0
  217. package/node_modules/acorn/CHANGELOG.md +1012 -0
  218. package/node_modules/acorn/LICENSE +21 -0
  219. package/node_modules/acorn/README.md +309 -0
  220. package/node_modules/acorn/bin/acorn +4 -0
  221. package/node_modules/acorn/dist/acorn.d.mts +897 -0
  222. package/node_modules/acorn/dist/acorn.d.ts +897 -0
  223. package/node_modules/acorn/dist/acorn.js +6370 -0
  224. package/node_modules/acorn/dist/acorn.mjs +6341 -0
  225. package/node_modules/acorn/dist/bin.js +90 -0
  226. package/node_modules/acorn/package.json +50 -0
  227. package/package.json +117 -101
  228. package/manual/packages/core/src/host.js +0 -124
  229. package/node_modules/@mytools/core/bin/fst.js +0 -70
  230. package/node_modules/@mytools/core/src/contracts.js +0 -41
  231. package/node_modules/@mytools/core/src/host.js +0 -124
  232. package/node_modules/@mytools/core/src/plugins.js +0 -55
  233. package/node_modules/@mytools/core/src/run-logs.js +0 -63
  234. package/node_modules/@mytools/web/public/assets/index-DT2B4tMV.js +0 -70
  235. package/node_modules/@mytools/web/public/assets/index-vuZvrUTT.css +0 -1
  236. /package/{node_modules/@mytools/core → manual/packages/fst-cli}/src/cli-run.js +0 -0
  237. /package/{node_modules/@mytools/core → manual/packages/fst-cli}/src/terminal/conditions.js +0 -0
  238. /package/{node_modules/@mytools/core → manual/packages/fst-cli}/src/terminal/log-viewer.js +0 -0
  239. /package/{node_modules/@mytools/core → manual/packages/fst-cli}/src/terminal/run-presentation.js +0 -0
  240. /package/{node_modules/@mytools/core → manual/packages/fst-cli}/src/terminal/theme.js +0 -0
  241. /package/{node_modules/@mytools/core → manual/packages/fst-logs}/src/markdown-log.js +0 -0
  242. /package/{node_modules/@mytools/core → manual/packages/fst-workspace}/src/project.js +0 -0
  243. /package/{node_modules/@mytools/core → manual/packages/fst-workspace}/templates/control-demo.yaml +0 -0
  244. /package/{node_modules/@mytools/core → manual/packages/fst-workspace}/templates/hello.yaml +0 -0
  245. /package/{node_modules/@mytools/core → manual/packages/fst-workspace}/templates/python-check.yaml +0 -0
  246. /package/{node_modules/@mytools/core → manual/packages/fst-workspace}/templates/system-check.yaml +0 -0
  247. /package/{node_modules/@mytools/core/src → manual/packages/sdk}/diagnostics.js +0 -0
@@ -0,0 +1,239 @@
1
+ import path from 'node:path';
2
+ import {readdir,readFile,lstat,unlink,rmdir,mkdir,writeFile,appendFile,open} from 'node:fs/promises';
3
+ import {FlowError} from '@mytools/sdk';
4
+ import {markdownHeader,markdownEvent,markdownResult} from './markdown-log.js';
5
+ import {logPolicy,jsonSize,preview,eventPreview} from './log-bounds.js';
6
+
7
+ const validId=id=>typeof id==='string'&&/^[a-f0-9-]{36}$/.test(id);
8
+ const logFiles=['run.md','events.jsonl','result.json','run.meta.json'];
9
+ function pageBuffer(buffer,offset,limit,cursor=offset,totalBytes=buffer.length){
10
+ if(offset>buffer.length)throw new FlowError('日志 cursor 超过正文长度',{code:'LOG_CURSOR_INVALID'});
11
+ if(offset<buffer.length&&(buffer[offset]&0xc0)===0x80)throw new FlowError('日志 cursor 必须位于 UTF-8 字符边界',{code:'LOG_CURSOR_INVALID'});
12
+ let end=Math.min(offset+limit,buffer.length);
13
+ if(end<buffer.length)while(end>offset&&(buffer[end]&0xc0)===0x80)end--;
14
+ const text=buffer.subarray(offset,end).toString('utf8'),nextCursor=cursor+end-offset;
15
+ return {text,cursor,nextCursor,hasMore:nextCursor<totalBytes,totalBytes};
16
+ }
17
+ export function validateKeepRuns(value){
18
+ if(value!==null&&(!Number.isSafeInteger(value)||value<1))throw new FlowError('日志保留次数必须为正整数;null 表示不自动清理');
19
+ return value;
20
+ }
21
+
22
+ export function createRunLogs(directory,{projectDir,allowLegacy=false,...options}){
23
+ const root=path.resolve(directory);let cleaning=Promise.resolve();
24
+ const policy=logPolicy(options),metadataLimit=Math.max(2*1024*1024,2*policy.maxMemoryBytes+8*policy.maxEventBytes+65536);
25
+ const owner=process.platform==='win32'?path.resolve(projectDir).toLowerCase():path.resolve(projectDir);
26
+ function location(id){if(!validId(id))throw new FlowError('运行 ID 无效');return path.join(root,id);}
27
+ async function regular(file){try{return (await lstat(file)).isFile();}catch(error){if(error.code==='ENOENT')return false;throw error;}}
28
+ async function safeDirectory(id){
29
+ const stat=await lstat(root);if(!stat.isDirectory()||stat.isSymbolicLink())throw new FlowError('日志根目录无效');
30
+ const dir=location(id),child=await lstat(dir);if(!child.isDirectory()||child.isSymbolicLink())throw new FlowError('日志目录无效');
31
+ return dir;
32
+ }
33
+ async function safeFile(file){
34
+ const before=await lstat(file);if(!before.isFile()||before.isSymbolicLink())throw new FlowError('日志文件无效');
35
+ const handle=await open(file,'r');
36
+ try{const after=await handle.stat();if(!after.isFile()||before.ino!==after.ino||before.dev!==after.dev)throw new FlowError('日志文件无效');return handle;}
37
+ catch(error){await handle.close();throw error;}
38
+ }
39
+ async function read(id){
40
+ const dir=await safeDirectory(id);
41
+ let file=path.join(dir,'result.json');
42
+ try{await lstat(file);}catch(error){if(error.code!=='ENOENT')throw error;file=path.join(dir,'run.meta.json');}
43
+ if(!await regular(file))throw new FlowError('运行记录不存在');
44
+ const handle=await safeFile(file);let result;
45
+ try{
46
+ const stat=await handle.stat();if(stat.size>metadataLimit)throw new FlowError('运行记录元数据超过读取预算',{code:'LOG_METADATA_LIMIT'});
47
+ // 读固定预算,文件在检查后增长也不会形成无限内存读取。
48
+ const buffer=Buffer.alloc(Math.min(stat.size+1,metadataLimit+1)),{bytesRead}=await handle.read(buffer,0,buffer.length,0);
49
+ if(bytesRead>metadataLimit)throw new FlowError('运行记录元数据超过读取预算',{code:'LOG_METADATA_LIMIT'});
50
+ result=JSON.parse(buffer.subarray(0,bytesRead).toString('utf8'));
51
+ }finally{await handle.close();}
52
+ if(result.id!==id)throw new FlowError('运行记录 ID 不匹配');
53
+ if(result.logOwner!==owner&&!(allowLegacy&&result.logOwner===undefined))throw new FlowError('运行记录不属于此项目');
54
+ return result;
55
+ }
56
+ async function list(){
57
+ let entries;try{const stat=await lstat(root);if(!stat.isDirectory()||stat.isSymbolicLink())throw new FlowError('日志根目录无效');entries=await readdir(root,{withFileTypes:true});}catch(error){if(error.code==='ENOENT')return [];throw error;}
58
+ const results=[];
59
+ for(const entry of entries){
60
+ if(!entry.isDirectory()||!validId(entry.name))continue;
61
+ try{
62
+ const record=await read(entry.name);
63
+ if(typeof record.workflowId==='string'&&['succeeded','failed','cancelled','stopped'].includes(record.status)&&Number.isFinite(Date.parse(record.finishedAt)))results.push(record);
64
+ }catch(error){if(error.code==='EACCES'||error.code==='EPERM')throw error;}
65
+ }
66
+ return results.sort((a,b)=>Date.parse(b.finishedAt)-Date.parse(a.finishedAt)||b.id.localeCompare(a.id));
67
+ }
68
+ return {
69
+ list,read,owner,policy:Object.freeze({...policy}),
70
+ async start(initial,{onEvent=()=>{}}={}){
71
+ const directory=location(initial.id),events=[],sizes=[],steps=new Map();
72
+ await mkdir(root,{recursive:true});
73
+ const rootStat=await lstat(root);if(!rootStat.isDirectory()||rootStat.isSymbolicLink())throw new FlowError('日志根目录无效');
74
+ await mkdir(directory,{recursive:true});
75
+ await safeDirectory(initial.id);
76
+ for(const name of logFiles){try{await lstat(path.join(directory,name));throw new FlowError('运行日志已存在,拒绝覆盖');}catch(error){if(error.code!=='ENOENT')throw error;}}
77
+ const markdownFile=path.join(directory,'run.md');
78
+ let writes=Promise.resolve(),failure=null,pendingBytes=0,diskBytes=0,resultBytes=0,eventCount=0,eventBytes=2,eventsTruncated=false,stepSummaryBytes=2,stepsTruncated=false,finished=false;
79
+ const snapshot=state=>structuredClone({...initial,...state,logOwner:owner,events,eventCount,eventBytes,eventsTruncated,stepSummaries:[...steps.values()].map(entry=>entry.event),stepSummaryBytes,stepsTruncated});
80
+ const reject=error=>{failure??=error;const promise=Promise.reject(failure);promise.catch(()=>{});return promise;};
81
+ function diskCheck(extra){if(policy.maxDiskBytes!==null&&diskBytes+extra>policy.maxDiskBytes)throw new FlowError('日志磁盘预算已满',{code:'LOG_DISK_LIMIT',details:{maxDiskBytes:policy.maxDiskBytes}});}
82
+ const queue=(bytes,operation)=>{
83
+ if(failure)return reject(failure);
84
+ if(pendingBytes+bytes>policy.maxPendingBytes)return reject(new FlowError('日志待写队列超过字节预算',{code:'LOG_QUEUE_LIMIT',details:{maxPendingBytes:policy.maxPendingBytes}}));
85
+ pendingBytes+=bytes;
86
+ const job=writes.then(operation).catch(error=>{failure??=error;throw error;}).finally(()=>{pendingBytes-=bytes;});
87
+ writes=job;
88
+ // 调用方仍收到失败;同时防止未 await 的插件日志产生未处理拒绝。
89
+ writes.catch(()=>{});return writes;
90
+ };
91
+ function retain(full){
92
+ const event=eventPreview(full,policy.maxEventBytes),size=Buffer.byteLength(JSON.stringify(event));
93
+ eventCount++;eventsTruncated ||= event.eventTruncated===true;
94
+ events.push(event);sizes.push(size);eventBytes+=size+(events.length>1?1:0);
95
+ while(events.length>policy.maxEvents||eventBytes>policy.maxMemoryBytes){
96
+ const removed=sizes.shift();events.shift();eventBytes-=removed+(events.length?1:0);eventsTruncated=true;
97
+ }
98
+ if(typeof full.type==='string'&&full.type.startsWith('step.')&&(full.callPath!==undefined||full.stepId!==undefined)){
99
+ const lightweight={};
100
+ for(const key of ['type','callPath','stepId','action','time','seq','durationMs','reason','error'])if(full[key]!==undefined)lightweight[key]=full[key];
101
+ const summary=eventPreview(lightweight,policy.maxEventBytes),key=summary.callPath??summary.stepId;
102
+ if(key!==undefined&&summary.callPath===full.callPath&&summary.stepId===full.stepId){
103
+ const previous=steps.get(key);
104
+ if(previous){steps.delete(key);stepSummaryBytes-=previous.bytes+(steps.size?1:0);}
105
+ const bytes=Buffer.byteLength(JSON.stringify(summary));steps.set(key,{event:summary,bytes});stepSummaryBytes+=bytes+(steps.size>1?1:0);
106
+ while(steps.size>policy.maxEvents||stepSummaryBytes>policy.maxMemoryBytes){
107
+ const oldest=steps.keys().next().value,removed=steps.get(oldest);steps.delete(oldest);stepSummaryBytes-=removed.bytes+(steps.size?1:0);stepsTruncated=true;
108
+ }
109
+ }else stepsTruncated=true;
110
+ }
111
+ onEvent(structuredClone(event));
112
+ }
113
+ function metadata(state){
114
+ const run={...initial,...state,logOwner:owner,events,eventCount,eventBytes,eventsTruncated,stepSummaries:[...steps.values()].map(entry=>entry.event),stepSummaryBytes,stepsTruncated};
115
+ for(const key of Object.keys(run)){
116
+ if(['events','stepSummaries','id','workflowId','logOwner','status','startedAt','finishedAt'].includes(key))continue;
117
+ if(run[key]===undefined)continue;
118
+ const bounded=preview(run[key],policy.maxEventBytes);run[key]=bounded.value;if(bounded.truncated)run[`${key}Truncated`]=true;
119
+ }
120
+ const text=JSON.stringify(run);
121
+ if(Buffer.byteLength(text)>metadataLimit)throw new FlowError('运行记录元数据超过写入预算',{code:'LOG_METADATA_LIMIT'});
122
+ return text;
123
+ }
124
+ async function saveText(text){
125
+ const bytes=Buffer.byteLength(text);diskCheck(bytes-resultBytes);
126
+ await rejectLink(path.join(directory,'result.json'));
127
+ await safeDirectory(initial.id);
128
+ await writeFile(path.join(directory,'result.json'),text);diskBytes+=bytes-resultBytes;resultBytes=bytes;
129
+ }
130
+ async function rejectLink(file){try{if((await lstat(file)).isSymbolicLink())throw new FlowError('日志文件无效');}catch(error){if(error.code!=='ENOENT')throw error;}}
131
+ async function appendText(json,markdown){
132
+ const bytes=Buffer.byteLength(json)+Buffer.byteLength(markdown);diskCheck(bytes);
133
+ await safeDirectory(initial.id);await rejectLink(path.join(directory,'events.jsonl'));await rejectLink(markdownFile);
134
+ await appendFile(path.join(directory,'events.jsonl'),json);await appendFile(markdownFile,markdown);diskBytes+=bytes;
135
+ }
136
+ const header=markdownHeader(initial);diskCheck(Buffer.byteLength(header));
137
+ // 独占创建,拒绝覆盖旧日志和文件链接。
138
+ await writeFile(markdownFile,header,{flag:'wx'});diskBytes+=Buffer.byteLength(header);
139
+ const ownership=JSON.stringify({id:initial.id,workflowId:initial.workflowId,startedAt:initial.startedAt,status:'running',logOwner:owner});
140
+ diskCheck(Buffer.byteLength(ownership));await writeFile(path.join(directory,'run.meta.json'),ownership,{flag:'wx'});diskBytes+=Buffer.byteLength(ownership);
141
+ return {
142
+ directory,snapshot,
143
+ markdown:state=>markdownHeader({...initial,...state})+events.map(markdownEvent).join(''),
144
+ append(event){
145
+ if(finished)return reject(new FlowError('日志已经完成',{code:'LOG_CLOSED'}));
146
+ if(failure)return reject(failure);
147
+ try{
148
+ const full={time:new Date().toISOString(),...event,runId:initial.id,seq:eventCount+1};
149
+ if(jsonSize(full,policy.maxPendingBytes)>policy.maxPendingBytes)throw new FlowError('单条日志超过待写字节预算',{code:'LOG_QUEUE_LIMIT'});
150
+ const json=JSON.stringify(full)+'\n',markdown=markdownEvent(full),bytes=Buffer.byteLength(json)+Buffer.byteLength(markdown);
151
+ if(pendingBytes+bytes>policy.maxPendingBytes)throw new FlowError('日志待写队列超过字节预算',{code:'LOG_QUEUE_LIMIT'});
152
+ retain(full);return queue(bytes,()=>appendText(json,markdown));
153
+ }catch(error){return reject(error);}
154
+ },
155
+ finish(state){
156
+ if(failure)return reject(failure);
157
+ if(finished)return reject(new FlowError('日志已经完成',{code:'LOG_CLOSED'}));
158
+ try{
159
+ const full={...state,time:new Date().toISOString(),runId:initial.id,type:'run.result',seq:eventCount+1};
160
+ if(jsonSize(full,policy.maxPendingBytes)>policy.maxPendingBytes)throw new FlowError('最终结果超过待写字节预算',{code:'LOG_QUEUE_LIMIT'});
161
+ const json=JSON.stringify(full)+'\n',markdown=markdownResult({...initial,...state}),bytes=Buffer.byteLength(json)+Buffer.byteLength(markdown);
162
+ if(pendingBytes+bytes>policy.maxPendingBytes)throw new FlowError('日志待写队列超过字节预算',{code:'LOG_QUEUE_LIMIT'});
163
+ // 最终业务结果已由快照提供;JSONL 补充完整记录,不重复广播到插件事件预览。
164
+ eventCount++;finished=true;
165
+ return queue(bytes,async()=>{const text=metadata(state);diskCheck(bytes+Buffer.byteLength(text)-resultBytes);await appendText(json,markdown);await saveText(text);});
166
+ }catch(error){return reject(error);}
167
+ },
168
+ save(state){try{const text=metadata(state);return queue(Buffer.byteLength(text),()=>saveText(text));}catch(error){return reject(error);}},
169
+ };
170
+ },
171
+ async usage(){
172
+ const report={directory:root,bytes:0,files:0,incomplete:false};
173
+ let entries;
174
+ try{
175
+ const stat=await lstat(root);
176
+ if(!stat.isDirectory()||stat.isSymbolicLink()){report.incomplete=true;return report;}
177
+ entries=await readdir(root,{withFileTypes:true});
178
+ }
179
+ catch(error){if(error.code!=='ENOENT')report.incomplete=true;return report;}
180
+ for(const entry of entries){
181
+ if(!entry.isDirectory()||!/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(entry.name))continue;
182
+ const dir=location(entry.name);
183
+ try{
184
+ const stat=await lstat(dir);if(!stat.isDirectory()||stat.isSymbolicLink())continue;
185
+ // 只计约定的日志文件,不读内容、不递归遍历业务目录、不跟随文件链接。
186
+ for(const name of logFiles){
187
+ try{const file=await lstat(path.join(dir,name));if(file.isFile()){report.bytes+=file.size;report.files++;}}
188
+ catch(error){if(error.code!=='ENOENT')report.incomplete=true;}
189
+ }
190
+ }catch(error){if(error.code!=='ENOENT')report.incomplete=true;}
191
+ }
192
+ return report;
193
+ },
194
+ async markdown(id){
195
+ const dir=location(id);const stat=await lstat(dir);if(!stat.isDirectory()||stat.isSymbolicLink())throw new FlowError('日志目录无效');
196
+ const run=await read(id),file=path.join(dir,'run.md');if(await regular(file))return readFile(file,'utf8');
197
+ return markdownHeader(run)+(run.events??[]).map(markdownEvent).join('')+markdownResult(run);
198
+ },
199
+ async page(id,{cursor=0,limit=65536}={}){
200
+ if(!Number.isSafeInteger(cursor)||cursor<0)throw new FlowError('日志 cursor 必须为非负整数字节位置',{code:'LOG_CURSOR_INVALID'});
201
+ if(!Number.isSafeInteger(limit)||limit<4)throw new FlowError('日志 limit 必须为至少 4 的正整数');
202
+ limit=Math.min(limit,256*1024);
203
+ const dir=await safeDirectory(id),run=await read(id),file=path.join(dir,'run.md');
204
+ let handle;
205
+ try{handle=await safeFile(file);}catch(error){
206
+ if(error.code!=='ENOENT')throw error;
207
+ const buffer=Buffer.from(markdownHeader(run)+(run.events??[]).map(markdownEvent).join('')+markdownResult(run));
208
+ return pageBuffer(buffer,cursor,limit);
209
+ }
210
+ try{
211
+ const totalBytes=(await handle.stat()).size;
212
+ if(cursor>totalBytes)throw new FlowError('日志 cursor 超过正文长度',{code:'LOG_CURSOR_INVALID'});
213
+ const buffer=Buffer.alloc(Math.min(limit+1,totalBytes-cursor));
214
+ let offset=0;
215
+ while(offset<buffer.length){const {bytesRead}=await handle.read(buffer,offset,buffer.length-offset,cursor+offset);if(!bytesRead)break;offset+=bytesRead;}
216
+ return pageBuffer(buffer.subarray(0,offset),0,limit,cursor,totalBytes);
217
+ }finally{await handle.close();}
218
+ },
219
+ prune(keepRuns,protectedIds){
220
+ const job=cleaning.then(async()=>{
221
+ if(keepRuns===null)return [];
222
+ validateKeepRuns(keepRuns);
223
+ const ended=await list(),removed=[];
224
+ for(const run of ended.slice(keepRuns)){
225
+ if(protectedIds.has(run.id))continue;
226
+ const dir=location(run.id);
227
+ // 只删除本工具约定的四个日志文件;不递归删除目录或插件生成的业务结果。
228
+ for(const name of logFiles){
229
+ const file=path.join(dir,name);
230
+ if(await regular(file))try{await unlink(file);}catch(error){if(error.code!=='ENOENT')throw error;}
231
+ }
232
+ try{await rmdir(dir);}catch(error){if(!['ENOTEMPTY','EEXIST','ENOENT'].includes(error.code))throw error;}
233
+ removed.push(run.id);
234
+ }
235
+ return removed;
236
+ });cleaning=job.catch(()=>{});return job;
237
+ },
238
+ };
239
+ }
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 mytools contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,67 @@
1
+ # 平台模块
2
+
3
+ 包名:`@mytools/fst-platform`。内部 workspace 包,随 `@yanglaofish/fishtools` 统一交付。
4
+
5
+ ## 职责与边界
6
+
7
+ 进程调用、环境解析、JSON 文件读取、npm 和产物完整性检查。日志留存策略由 logs 负责,项目状态由 workspace 负责。
8
+
9
+ 内部依赖:`@mytools/sdk`。
10
+ ## 公开入口
11
+
12
+ | 导入路径 | 实现位置 |
13
+ | --- | --- |
14
+ | `@mytools/fst-platform` | `./src/process.js` |
15
+ | `@mytools/fst-platform/environments` | `./src/environments.js` |
16
+ | `@mytools/fst-platform/bundle` | `./src/bundle.js` |
17
+ | `@mytools/fst-platform/json` | `./src/json.js` |
18
+ | `@mytools/fst-platform/npm` | `./src/npm.js` |
19
+ | `@mytools/fst-platform/fs` | `./src/file-probe.js` |
20
+ | `@mytools/fst-platform/package.json` | `./package.json` |
21
+
22
+ 仅依赖 exports 声明的入口,禁止消费者跨包读取 src/bin 私有文件。入口路径由本模块维护,修改协议时同步消费方回归。
23
+
24
+ ## 维护与验证
25
+
26
+ 本模块负责上述职责的实现、文档与回归;跨模块接口调整需要同时检查生产者与消费者。具体维护人员尚未指定。
27
+
28
+ 在仓库根目录执行:
29
+
30
+ ```sh
31
+ node --test tests/modules.test.js tests/process.test.js tests/environments.test.js
32
+ ```
33
+
34
+ ## 隔离文件探测
35
+
36
+ `createFileProbe({timeout=2000,maxConcurrent=2,maxPending=16,allowRemote=false})` 创建只读探测器。
37
+ `stat(path,{signal,timeout})` 和 `readDirectory(path,{signal,timeout,limit=1000})` 把实际 I/O 放入独立 Node 子进程。
38
+ 超时从接收请求开始计时,包含排队;并发和排队预算满时返回 `error`,错误码为 `PROBE_BUSY`。
39
+ Windows 子进程使用 `windowsHide`,不会启动可见窗口。
40
+
41
+ 每个结果都有 `status` 和 `incomplete`。状态为 `ok/missing/timedOut/cancelled/skipped/error`;非成功结果附 `reason`,错误结果还附 `{code,message}`。
42
+ `stat` 使用 `lstat`,不追踪符号链接;成功的 `value` 包含 `{type,size,mtimeMs,ctimeMs,birthtimeMs,mode}`,
43
+ 其中 `type` 为 `file/directory/symlink/other`。目录成功的 `value` 为 `[{name,type}]`;顺序取决于文件系统。
44
+ 目录只列一级、不读文件正文;达到条目上限且仍有条目时返回 `incomplete:true,reason:'entryLimit'`。
45
+ `limit` 必须为 1 到 10000 的整数,所有容量和超时参数必须是有限整数。
46
+
47
+ 显式 UNC 和网络设备路径默认返回 `skipped`,原因 `remotePath`;Windows 扩展本地路径仍可探测。
48
+ 普通挂载不根据路径字符串推测位置,由子进程超时约束。允许远端探测时设 `allowRemote:true`。
49
+ 这提供响应时间和资源预算约束,底层内核 I/O 仍可能无法立即回收,不构成安全沙箱。
50
+
51
+ `status()` 返回 `{closed,active,pending,unreaped,maxConcurrent,maxPending}`;超时或取消的 worker 在确认退出前仍计入 `active` 和 `unreaped`。
52
+ `close()` 取消当前和排队请求,尝试终止进程,最多等待 250 ms;返回 `{closed:true,incomplete,unreaped}`。
53
+ 关闭后拒绝新请求;关闭报告中的未回收数为关闭等待结束时的快照,后续实际状态可通过 `status()` 查询。
54
+
55
+ ```js
56
+ import { createFileProbe } from '@mytools/fst-platform/fs';
57
+ const fs = createFileProbe();
58
+ try {
59
+ const result = await fs.readDirectory('.', { limit: 100 });
60
+ if (result.status === 'ok') console.log(result.value, result.incomplete);
61
+ } finally {
62
+ const closed = await fs.close();
63
+ if (closed.incomplete) console.error('仍有未回收探测进程', closed.unreaped);
64
+ }
65
+ ```
66
+
67
+ 定向验证:`node --test tests/file-probe.test.js`。阻塞 fixture 使用真实子进程同步等待,并验证终止失败后预算不会被释放。
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@mytools/fst-platform",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "main": "src/process.js",
7
+ "exports": {
8
+ ".": "./src/process.js",
9
+ "./environments": "./src/environments.js",
10
+ "./bundle": "./src/bundle.js",
11
+ "./json": "./src/json.js",
12
+ "./npm": "./src/npm.js",
13
+ "./fs": "./src/file-probe.js",
14
+ "./network": "./src/network.js",
15
+ "./package.json": "./package.json"
16
+ },
17
+ "files": [
18
+ "src",
19
+ "README.md",
20
+ "LICENSE"
21
+ ],
22
+ "license": "MIT",
23
+ "engines": {
24
+ "node": ">=24.15.0"
25
+ },
26
+ "dependencies": {
27
+ "@mytools/sdk": "0.1.0",
28
+ "execa": "10.1.0",
29
+ "tree-kill": "1.2.2",
30
+ "undici": "^8.4.1",
31
+ "which": "7.0.0"
32
+ }
33
+ }
@@ -0,0 +1,17 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFile, realpath } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+
5
+ export async function verifyBundle(root){
6
+ root=await realpath(root);
7
+ const manifest=JSON.parse(await readFile(path.join(root,'manifest.json'),'utf8'));
8
+ const errors=[];
9
+ for(const [relative,expected] of Object.entries(manifest.files??{})){
10
+ const file=path.resolve(root,relative);
11
+ try{
12
+ if(!file.startsWith(root+path.sep)||!(await realpath(file)).startsWith(root+path.sep))throw new Error('路径越界');
13
+ if(createHash('sha256').update(await readFile(file)).digest('hex')!==expected)errors.push(relative);
14
+ }catch{errors.push(relative);}
15
+ }
16
+ return {ok:errors.length===0,errors};
17
+ }
@@ -0,0 +1,67 @@
1
+ import path from 'node:path';
2
+ import {FlowError} from '@mytools/sdk';
3
+ import which from 'which';
4
+
5
+ export const currentTarget=()=>`${process.platform}-${process.arch}${process.platform==='linux'?'-glibc':''}`;
6
+ export function inside(root,relative){
7
+ if(typeof relative!=='string'||!relative||path.isAbsolute(relative)||/^[A-Za-z]:|\\/.test(relative))throw new FlowError(`资源路径必须是包内相对路径:${relative}`);
8
+ const absolute=path.resolve(root,relative),rel=path.relative(root,absolute);
9
+ if(rel==='..'||rel.startsWith('..'+path.sep)||path.isAbsolute(rel))throw new FlowError(`资源路径越界:${relative}`);
10
+ return absolute;
11
+ }
12
+ export function environmentDeclarations(plugin,action){return {...plugin.environments,...action?.environments};}
13
+ export function resolveEnvironments(plugin,action,overrides={},target=currentTarget()){
14
+ return Object.fromEntries(Object.entries(environmentDeclarations(plugin,action)).map(([id,declaration])=>{
15
+ const selected=overrides[id];
16
+ if(selected!==undefined&&(!selected||typeof selected!=='object'||Array.isArray(selected)||Object.keys(selected).some(k=>!['source','executable'].includes(k))||selected.source!==undefined&&typeof selected.source!=='string'||selected.executable!==undefined&&(typeof selected.executable!=='string'||!selected.executable.trim())))throw new FlowError(`环境来源覆盖无效:${plugin.id}/${id}`);
17
+ const source=selected?.source??declaration.source;
18
+ if(!(declaration.allowedSources??[declaration.source]).includes(source))throw new FlowError(`环境 ${plugin.id}/${id} 不允许来源 ${source}`);
19
+ const e={...declaration,source};delete e.artifacts;
20
+ if(selected?.executable!==undefined){
21
+ if(source!=='host')throw new FlowError(`只有 host 环境允许覆盖解释器:${plugin.id}/${id}`);
22
+ e.executable=selected.executable;
23
+ }
24
+ if(source==='tool'){
25
+ if(id!=='node')throw new FlowError(`工具尚未提供环境:${id}`);
26
+ e.executable=process.execPath;
27
+ }else if(source==='bundled'){
28
+ const artifact=declaration.artifacts?.[target];
29
+ if(!artifact)throw new FlowError(`环境 ${plugin.id}/${id} 未提供 ${target} 的随包资源`);
30
+ e.root=inside(plugin.root,artifact.directory);e.executable=inside(e.root,artifact.executable);
31
+ }
32
+ return [id,e];
33
+ }));
34
+ }
35
+
36
+ // 打包只解析声明;真正调用时才在当前工作区选择候选,避免将开发机路径写入跨平台分发包。
37
+ export async function prepareEnvironments(plugin,action,overrides={}, {cwd=process.cwd()}={}){
38
+ const resolved=resolveEnvironments(plugin,action,overrides);
39
+ for(const [id,environment] of Object.entries(resolved)){
40
+ if(environment.source!=='host'||!Array.isArray(environment.executable)&&overrides[id]?.executable===undefined)continue;
41
+ const candidates=Array.isArray(environment.executable)?environment.executable:[environment.executable];
42
+ const windows=process.platform==='win32',directory=path.resolve(cwd);
43
+ const searchDirectories=[...(windows?[directory]:[]),...(process.env.PATH??'').split(path.delimiter)]
44
+ .map(entry=>path.resolve(directory,entry.replace(/^"(.*)"$/,'$1')));
45
+ let found;
46
+ for(const candidate of candidates){
47
+ const direct=path.isAbsolute(candidate)||candidate.includes('/')||windows&&candidate.includes('\\');
48
+ // 使用绝对候选,防止 which 在 Windows 擅自优先搜索宿主启动目录。
49
+ const paths=direct?[path.resolve(directory,candidate)]:searchDirectories.map(base=>path.resolve(base,candidate));
50
+ for(const executable of paths){
51
+ found=await which(executable,{nothrow:true});
52
+ if(found)break;
53
+ }
54
+ if(found)break;
55
+ }
56
+ if(!found)throw new FlowError(`环境 ${plugin.id}/${id} 未找到程序:${candidates.join('、')}`,{code:'ENOENT',details:{plugin:plugin.id,environment:id,candidates}});
57
+ environment.executable=path.resolve(found);
58
+ }
59
+ return resolved;
60
+ }
61
+
62
+ export function platformWarnings(plugin,platform=process.platform,architecture=process.arch){
63
+ const warnings=[];
64
+ if(plugin.platforms&&!plugin.platforms.includes(platform))warnings.push(`插件 ${plugin.id} 的平台声明不包含当前 ${platform},继续执行;请核实插件支持范围`);
65
+ if(plugin.architectures&&!plugin.architectures.includes(architecture))warnings.push(`插件 ${plugin.id} 的架构声明不包含当前 ${architecture},继续执行;请核实插件支持范围`);
66
+ return warnings;
67
+ }
@@ -0,0 +1,183 @@
1
+ import { fork } from 'node:child_process';
2
+
3
+ const workerPath = new URL('./file-probe-worker.js', import.meta.url);
4
+ const MAX_DIRECTORY_ENTRIES = 10000;
5
+
6
+ function integer(value, name, minimum = 1, maximum = 2147483647) {
7
+ if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
8
+ throw new TypeError(`${name} 必须是 ${minimum} 到 ${maximum} 的整数`);
9
+ }
10
+ return value;
11
+ }
12
+
13
+ function failure(status, reason, error) {
14
+ return { status, incomplete: true, reason, ...(error ? { error: { code: error.code || 'PROBE_ERROR', message: error.message || String(error) } } : {}) };
15
+ }
16
+
17
+ function isRemotePath(value) {
18
+ const normalized = value.replaceAll('/', '\\');
19
+ // Windows 扩展本地路径仍可探测;显式 UNC 和网络设备路径默认跳过。
20
+ if (/^\\\\[?.]\\/u.test(normalized)) {
21
+ return /^\\\\[?.]\\UNC(?:\\|$)/iu.test(normalized)
22
+ || /^\\\\[?.]\\GLOBALROOT\\Device\\(?:Mup|LanmanRedirector|WebDavRedirector)(?:\\|$)/iu.test(normalized);
23
+ }
24
+ return /^\\\\/u.test(normalized)
25
+ || /^\\(?:\?\?\\UNC|Device\\(?:Mup|LanmanRedirector|WebDavRedirector))(?:\\|$)/iu.test(normalized);
26
+ }
27
+
28
+ /** 私有运行时边界:测试可使用真实阻塞 worker 和模拟操作系统终止失败。 */
29
+ export function createFileProbeEngine(options = {}, runtime = {}) {
30
+ const timeout = integer(options.timeout ?? 2000, 'timeout');
31
+ const maxConcurrent = integer(options.maxConcurrent ?? 2, 'maxConcurrent');
32
+ const maxPending = integer(options.maxPending ?? 16, 'maxPending', 0);
33
+ const allowRemote = options.allowRemote ?? false;
34
+ if (typeof allowRemote !== 'boolean') throw new TypeError('allowRemote 必须为布尔值');
35
+ const closeTimeout = runtime.closeTimeout ?? 250;
36
+ const terminate = runtime.terminate ?? (child => child.kill('SIGKILL'));
37
+ const active = new Set();
38
+ const pending = [];
39
+ const closeWaiters = new Set();
40
+ let closed = false;
41
+ let closing;
42
+
43
+ function status() {
44
+ return { closed, active: active.size, pending: pending.length,
45
+ unreaped: [...active].filter(record => record.unreaped).length, maxConcurrent, maxPending };
46
+ }
47
+
48
+ function finish(request, result) {
49
+ if (request.finished) return;
50
+ request.finished = true;
51
+ clearTimeout(request.timer);
52
+ request.signal?.removeEventListener('abort', request.onAbort);
53
+ const index = pending.indexOf(request);
54
+ if (index !== -1) pending.splice(index, 1);
55
+ request.resolve(result);
56
+ }
57
+
58
+ function stop(record) {
59
+ if (!active.has(record)) return;
60
+ record.unreaped = true;
61
+ try { terminate(record.child); } catch { /* 退出事件到达前继续占预算。 */ }
62
+ }
63
+
64
+ function drain() {
65
+ while (!closed && active.size < maxConcurrent && pending.length) {
66
+ start(pending.shift());
67
+ }
68
+ }
69
+
70
+ function release(record) {
71
+ if (!active.delete(record)) return;
72
+ if (!record.request.finished) {
73
+ finish(record.request, failure('error', 'workerExited', { code: 'PROBE_WORKER_EXIT', message: '文件探测进程未返回结果即退出' }));
74
+ }
75
+ drain();
76
+ if (closed && active.size === 0) for (const notify of closeWaiters) notify();
77
+ }
78
+
79
+ function start(request) {
80
+ if (request.finished) return;
81
+ let child;
82
+ try {
83
+ child = fork(runtime.workerPath ?? workerPath, [], {
84
+ execPath: runtime.execPath ?? process.execPath,
85
+ execArgv: [], windowsHide: true,
86
+ stdio: ['ignore', 'ignore', 'ignore', 'ipc'],
87
+ });
88
+ } catch (error) {
89
+ finish(request, failure('error', 'workerStartFailed', error));
90
+ drain();
91
+ return;
92
+ }
93
+ const record = { child, request, unreaped: false };
94
+ request.record = record;
95
+ active.add(record);
96
+ child.once('exit', () => release(record));
97
+ child.once('close', () => release(record));
98
+ child.on('error', error => {
99
+ finish(request, failure('error', 'workerStartFailed', error));
100
+ if (child.pid) stop(record);
101
+ else release(record);
102
+ });
103
+ child.once('message', result => {
104
+ if (request.finished) return;
105
+ if (!result || !['ok', 'missing', 'error'].includes(result.status) || typeof result.incomplete !== 'boolean') {
106
+ finish(request, failure('error', 'workerProtocol', { code: 'PROBE_PROTOCOL', message: '文件探测进程返回非法结果' }));
107
+ stop(record);
108
+ return;
109
+ }
110
+ finish(request, result);
111
+ // 结果已到达也必须收到 exit 后才释放预算,避免新旧进程短暂重叠。
112
+ });
113
+ child.send({ operation: request.operation, path: request.path, limit: request.limit }, error => {
114
+ if (!error || request.finished) return;
115
+ finish(request, failure('error', 'workerStartFailed', error));
116
+ stop(record);
117
+ });
118
+ }
119
+
120
+ function submit(operation, path, requestOptions = {}) {
121
+ if (closed) return Promise.resolve(failure('cancelled', 'closed'));
122
+ let requestTimeout, limit, signal;
123
+ try {
124
+ if (typeof path !== 'string' || !path.length || path.includes('\0')) {
125
+ throw Object.assign(new TypeError('path 必须是非空且不含空字符的字符串'), { code: 'INVALID_PATH' });
126
+ }
127
+ requestTimeout = integer(requestOptions.timeout ?? timeout, 'timeout');
128
+ limit = operation === 'readDirectory' ? integer(requestOptions.limit ?? 1000, 'limit', 1, MAX_DIRECTORY_ENTRIES) : undefined;
129
+ signal = requestOptions.signal;
130
+ if (signal && (typeof signal.addEventListener !== 'function' || typeof signal.removeEventListener !== 'function' || typeof signal.aborted !== 'boolean')) {
131
+ throw new TypeError('signal 必须是 AbortSignal');
132
+ }
133
+ } catch (error) {
134
+ return Promise.resolve(failure('error', 'invalidOptions', error));
135
+ }
136
+ if (signal?.aborted) return Promise.resolve(failure('cancelled', 'signal'));
137
+ if (!allowRemote && isRemotePath(path)) return Promise.resolve(failure('skipped', 'remotePath'));
138
+ if (active.size >= maxConcurrent && pending.length >= maxPending) {
139
+ return Promise.resolve(failure('error', 'queueFull', { code: 'PROBE_BUSY', message: '文件探测并发和排队预算已满' }));
140
+ }
141
+ return new Promise(resolve => {
142
+ const request = { operation, path, limit, signal, resolve, finished: false };
143
+ function cancel(result) {
144
+ finish(request, result);
145
+ if (request.record) stop(request.record);
146
+ }
147
+ request.onAbort = () => cancel(failure('cancelled', 'signal'));
148
+ request.timer = setTimeout(() => cancel(failure('timedOut', 'timeout')), requestTimeout);
149
+ signal?.addEventListener('abort', request.onAbort, { once: true });
150
+ if (active.size < maxConcurrent) start(request);
151
+ else pending.push(request);
152
+ });
153
+ }
154
+
155
+ function close() {
156
+ if (closing) return closing;
157
+ closed = true;
158
+ for (const request of [...pending]) finish(request, failure('cancelled', 'closed'));
159
+ for (const record of active) {
160
+ finish(record.request, failure('cancelled', 'closed'));
161
+ stop(record);
162
+ }
163
+ closing = new Promise(resolve => {
164
+ let timer;
165
+ function done() {
166
+ clearTimeout(timer);
167
+ closeWaiters.delete(done);
168
+ // 不能立即退出的底层 I/O 仍被记录,但不会让宿主关闭无限等待。
169
+ for (const record of active) {
170
+ record.child.unref();
171
+ record.child.channel?.unref();
172
+ }
173
+ resolve({ closed: true, incomplete: active.size > 0, unreaped: active.size });
174
+ }
175
+ if (!active.size) done();
176
+ else { closeWaiters.add(done); timer = setTimeout(done, closeTimeout); }
177
+ });
178
+ return closing;
179
+ }
180
+
181
+ return { stat: (path, options) => submit('stat', path, options),
182
+ readDirectory: (path, options) => submit('readDirectory', path, options), close, status };
183
+ }