@dsh-workbench/shared 1.5.2-alpha.4 → 1.5.2-alpha.5

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 (310) hide show
  1. package/dist/components/Activity.css +69 -0
  2. package/dist/components/Activity.d.ts +56 -0
  3. package/dist/components/Activity.js +47 -0
  4. package/dist/components/ApprovalDetail.css +3 -0
  5. package/dist/components/ApprovalDetail.d.ts +42 -0
  6. package/dist/components/ApprovalDetail.js +53 -0
  7. package/dist/components/ApprovalPlan.css +39 -0
  8. package/dist/components/ApprovalPlan.d.ts +27 -0
  9. package/dist/components/ApprovalPlan.js +19 -0
  10. package/dist/components/Card.css +19 -0
  11. package/dist/components/Card.d.ts +26 -0
  12. package/dist/components/Card.js +18 -0
  13. package/dist/components/CardAnchor.d.ts +21 -0
  14. package/dist/components/CardAnchor.js +19 -0
  15. package/dist/components/CardAnchor.module.css +3 -0
  16. package/dist/components/CardBoundary.d.ts +42 -0
  17. package/dist/components/CardBoundary.js +58 -0
  18. package/dist/components/CardBoundary.module.css +5 -0
  19. package/dist/components/CardHead.css +87 -0
  20. package/dist/components/CardHead.d.ts +30 -0
  21. package/dist/components/CardHead.js +27 -0
  22. package/dist/components/ChoiceGroup.css +182 -0
  23. package/dist/components/ChoiceGroup.d.ts +54 -0
  24. package/dist/components/ChoiceGroup.js +63 -0
  25. package/dist/components/ConfirmBar.css +26 -0
  26. package/dist/components/ConfirmBar.d.ts +36 -0
  27. package/dist/components/ConfirmBar.js +26 -0
  28. package/dist/components/EmptyIllustration.d.ts +12 -0
  29. package/dist/components/EmptyIllustration.js +32 -0
  30. package/dist/components/Field.css +20 -0
  31. package/dist/components/Field.d.ts +18 -0
  32. package/dist/components/Field.js +15 -0
  33. package/dist/components/Form.css +6 -0
  34. package/dist/components/Form.d.ts +22 -0
  35. package/dist/components/Form.js +60 -0
  36. package/dist/components/FormActions.css +13 -0
  37. package/dist/components/FormActions.d.ts +29 -0
  38. package/dist/components/FormActions.js +43 -0
  39. package/dist/components/FormNodes.d.ts +107 -0
  40. package/dist/components/FormNodes.js +165 -0
  41. package/dist/components/FormRows.css +107 -0
  42. package/dist/components/FormRows.d.ts +36 -0
  43. package/dist/components/FormRows.js +26 -0
  44. package/dist/components/FormTypes.d.ts +84 -0
  45. package/dist/components/FormTypes.js +1 -0
  46. package/dist/components/Link.css +22 -0
  47. package/dist/components/Link.d.ts +22 -0
  48. package/dist/components/Link.js +17 -0
  49. package/dist/components/LongTaskRow.css +171 -0
  50. package/dist/components/LongTaskRow.d.ts +94 -0
  51. package/dist/components/LongTaskRow.js +103 -0
  52. package/dist/components/Note.css +13 -0
  53. package/dist/components/Note.d.ts +20 -0
  54. package/dist/components/Note.js +14 -0
  55. package/dist/components/ResourceStates.css +114 -0
  56. package/dist/components/ResourceStates.d.ts +44 -0
  57. package/dist/components/ResourceStates.js +41 -0
  58. package/dist/components/Rows.css +42 -0
  59. package/dist/components/Rows.d.ts +28 -0
  60. package/dist/components/Rows.js +21 -0
  61. package/dist/components/SaveBar.d.ts +24 -0
  62. package/dist/components/SaveBar.js +25 -0
  63. package/dist/components/SelectField.css +182 -0
  64. package/dist/components/SelectField.d.ts +89 -0
  65. package/dist/components/SelectField.js +260 -0
  66. package/dist/components/SelectFieldNodes.d.ts +49 -0
  67. package/dist/components/SelectFieldNodes.js +43 -0
  68. package/dist/components/SettingsSection.css +25 -0
  69. package/dist/components/SettingsSection.d.ts +20 -0
  70. package/dist/components/SettingsSection.js +17 -0
  71. package/dist/components/SetupShell.d.ts +93 -0
  72. package/dist/components/SetupShell.js +64 -0
  73. package/dist/components/SetupShell.module.css +81 -0
  74. package/dist/components/Spinner.css +5 -0
  75. package/dist/components/Spinner.d.ts +15 -0
  76. package/dist/components/Spinner.js +13 -0
  77. package/dist/components/Stack.css +6 -0
  78. package/dist/components/Stack.d.ts +14 -0
  79. package/dist/components/Stack.js +10 -0
  80. package/dist/components/StateBlock.css +38 -0
  81. package/dist/components/StateBlock.d.ts +24 -0
  82. package/dist/components/StateBlock.js +22 -0
  83. package/dist/components/TextField.css +32 -0
  84. package/dist/components/TextField.d.ts +14 -0
  85. package/dist/components/TextField.js +10 -0
  86. package/dist/components/board-module.d.ts +307 -0
  87. package/dist/components/board-module.js +1 -0
  88. package/dist/components/card-view-validate.d.ts +5 -0
  89. package/dist/components/card-view-validate.js +256 -0
  90. package/dist/components/icons.d.ts +63 -0
  91. package/dist/components/icons.js +107 -0
  92. package/dist/components/layout/icon-command.d.ts +8 -0
  93. package/dist/components/layout/icon-command.js +21 -0
  94. package/dist/contract/capture.d.ts +16 -0
  95. package/dist/contract/capture.js +1 -0
  96. package/dist/contract/diagnostics.d.ts +34 -0
  97. package/dist/contract/diagnostics.js +124 -0
  98. package/dist/contract/protocol/unit-manager.d.ts +50 -0
  99. package/dist/contract/protocol/unit-manager.js +2 -0
  100. package/dist/host/adapter-contract.d.ts +3 -0
  101. package/dist/host/adapter-contract.js +95 -0
  102. package/dist/host/adapter-set.d.ts +27 -0
  103. package/dist/host/adapter-set.js +258 -0
  104. package/dist/host/adapter-types.d.ts +87 -0
  105. package/dist/host/adapter-types.js +23 -0
  106. package/dist/host/adapters/platform.d.ts +14 -0
  107. package/dist/host/adapters/platform.js +40 -0
  108. package/dist/host/adapters.d.ts +28 -0
  109. package/dist/host/adapters.js +9 -0
  110. package/dist/host/auth-loss.d.ts +33 -0
  111. package/dist/host/auth-loss.js +107 -0
  112. package/dist/host/board-fact.d.ts +8 -0
  113. package/dist/host/board-fact.js +16 -0
  114. package/dist/host/boot-record.d.ts +11 -0
  115. package/dist/host/boot-record.js +31 -0
  116. package/dist/host/browser.d.ts +3 -0
  117. package/dist/host/browser.js +3 -0
  118. package/dist/host/bundle-manager.d.ts +4 -0
  119. package/dist/host/bundle-manager.js +338 -0
  120. package/dist/host/changelog.d.ts +28 -0
  121. package/dist/host/changelog.js +201 -0
  122. package/dist/host/cli-error.d.ts +8 -0
  123. package/dist/host/cli-error.js +70 -0
  124. package/dist/host/cli.d.ts +4 -0
  125. package/dist/host/cli.js +9 -0
  126. package/dist/host/config-sync.d.ts +40 -0
  127. package/dist/host/config-sync.js +267 -0
  128. package/dist/host/context-ref.d.ts +13 -0
  129. package/dist/host/context-ref.js +41 -0
  130. package/dist/host/data-error.d.ts +15 -0
  131. package/dist/host/data-error.js +23 -0
  132. package/dist/host/data-plan-check.d.ts +10 -0
  133. package/dist/host/data-plan-check.js +315 -0
  134. package/dist/host/data-plan.d.ts +15 -0
  135. package/dist/host/data-plan.js +283 -0
  136. package/dist/host/data-root.d.ts +5 -0
  137. package/dist/host/data-root.js +23 -0
  138. package/dist/host/diy-debug.d.ts +80 -0
  139. package/dist/host/diy-debug.js +89 -0
  140. package/dist/host/diy-preset.d.ts +26 -0
  141. package/dist/host/diy-preset.js +115 -0
  142. package/dist/host/diy-record.d.ts +135 -0
  143. package/dist/host/diy-record.js +163 -0
  144. package/dist/host/dsh-compat.d.ts +27 -0
  145. package/dist/host/dsh-compat.js +75 -0
  146. package/dist/host/dsh-plugins.d.ts +5 -0
  147. package/dist/host/dsh-plugins.js +51 -0
  148. package/dist/host/env-policy.d.ts +82 -0
  149. package/dist/host/env-policy.js +181 -0
  150. package/dist/host/extension.d.ts +7 -0
  151. package/dist/host/extension.js +40 -0
  152. package/dist/host/facts.d.ts +31 -0
  153. package/dist/host/facts.js +58 -0
  154. package/dist/host/fs-write.d.ts +96 -0
  155. package/dist/host/fs-write.js +183 -0
  156. package/dist/host/git.d.ts +5 -0
  157. package/dist/host/git.js +1 -0
  158. package/dist/host/host-actions.d.ts +2 -0
  159. package/dist/host/host-actions.js +5 -0
  160. package/dist/host/host-kit.d.ts +37 -0
  161. package/dist/host/host-kit.js +27 -0
  162. package/dist/host/http.d.ts +47 -0
  163. package/dist/host/http.js +289 -0
  164. package/dist/host/install-failure.d.ts +50 -0
  165. package/dist/host/install-failure.js +184 -0
  166. package/dist/host/installed-module.d.ts +25 -0
  167. package/dist/host/installed-module.js +289 -0
  168. package/dist/host/installed-sources.d.ts +10 -0
  169. package/dist/host/installed-sources.js +63 -0
  170. package/dist/host/lease.d.ts +70 -0
  171. package/dist/host/lease.js +264 -0
  172. package/dist/host/lib-capabilities.d.ts +22 -0
  173. package/dist/host/lib-capabilities.js +37 -0
  174. package/dist/host/lib-install.d.ts +19 -0
  175. package/dist/host/lib-install.js +40 -0
  176. package/dist/host/lib-runners.d.ts +18 -0
  177. package/dist/host/lib-runners.js +46 -0
  178. package/dist/host/local-declaration.d.ts +7 -0
  179. package/dist/host/local-declaration.js +33 -0
  180. package/dist/host/long-task.d.ts +97 -0
  181. package/dist/host/long-task.js +297 -0
  182. package/dist/host/market-index-claim.d.ts +19 -0
  183. package/dist/host/market-index-claim.js +87 -0
  184. package/dist/host/market-index-doc.d.ts +12 -0
  185. package/dist/host/market-index-doc.js +1 -0
  186. package/dist/host/market-index-parse.d.ts +28 -0
  187. package/dist/host/market-index-parse.js +413 -0
  188. package/dist/host/market-index.d.ts +13 -0
  189. package/dist/host/market-index.js +105 -0
  190. package/dist/host/module-root.d.ts +1 -0
  191. package/dist/host/module-root.js +5 -0
  192. package/dist/host/needs.d.ts +4 -0
  193. package/dist/host/needs.js +2 -0
  194. package/dist/host/npm-registry.d.ts +10 -0
  195. package/dist/host/npm-registry.js +16 -0
  196. package/dist/host/package-content.d.ts +8 -0
  197. package/dist/host/package-content.js +90 -0
  198. package/dist/host/package-kind.d.ts +13 -0
  199. package/dist/host/package-kind.js +51 -0
  200. package/dist/host/package-route.d.ts +33 -0
  201. package/dist/host/package-route.js +68 -0
  202. package/dist/host/panel-state.d.ts +120 -0
  203. package/dist/host/panel-state.js +177 -0
  204. package/dist/host/patch-blocks.d.ts +13 -0
  205. package/dist/host/patch-blocks.js +52 -0
  206. package/dist/host/patch.d.ts +4 -0
  207. package/dist/host/patch.js +7 -0
  208. package/dist/host/paths.d.ts +12 -0
  209. package/dist/host/paths.js +20 -0
  210. package/dist/host/payload.d.ts +12 -0
  211. package/dist/host/payload.js +16 -0
  212. package/dist/host/plan-results.d.ts +5 -0
  213. package/dist/host/plan-results.js +71 -0
  214. package/dist/host/plan-run.d.ts +41 -0
  215. package/dist/host/plan-run.js +87 -0
  216. package/dist/host/platform.d.ts +14 -0
  217. package/dist/host/platform.js +40 -0
  218. package/dist/host/plugin-ledger.d.ts +32 -0
  219. package/dist/host/plugin-ledger.js +106 -0
  220. package/dist/host/plugin.d.ts +3 -0
  221. package/dist/host/plugin.js +38 -0
  222. package/dist/host/port-types.d.ts +233 -0
  223. package/dist/host/port-types.js +1 -0
  224. package/dist/host/preflight.d.ts +32 -0
  225. package/dist/host/preflight.js +1 -0
  226. package/dist/host/process-alive.d.ts +6 -0
  227. package/dist/host/process-alive.js +16 -0
  228. package/dist/host/profile-bundles.d.ts +20 -0
  229. package/dist/host/profile-bundles.js +48 -0
  230. package/dist/host/profile-create.d.ts +19 -0
  231. package/dist/host/profile-create.js +124 -0
  232. package/dist/host/profile-port.d.ts +4 -0
  233. package/dist/host/profile-port.js +4 -0
  234. package/dist/host/profile-registries.d.ts +10 -0
  235. package/dist/host/profile-registries.js +149 -0
  236. package/dist/host/provision.d.ts +32 -0
  237. package/dist/host/provision.js +105 -0
  238. package/dist/host/read-json.d.ts +1 -0
  239. package/dist/host/read-json.js +11 -0
  240. package/dist/host/recipe-rules.d.ts +5 -0
  241. package/dist/host/recipe-rules.js +412 -0
  242. package/dist/host/recipe.d.ts +14 -0
  243. package/dist/host/recipe.js +332 -0
  244. package/dist/host/registry-declaration.d.ts +21 -0
  245. package/dist/host/registry-declaration.js +42 -0
  246. package/dist/host/reinstall-record.d.ts +16 -0
  247. package/dist/host/reinstall-record.js +54 -0
  248. package/dist/host/release-age.d.ts +24 -0
  249. package/dist/host/release-age.js +92 -0
  250. package/dist/host/release-packages.generated.d.ts +1 -0
  251. package/dist/host/release-packages.generated.js +10 -0
  252. package/dist/host/release-probe.d.ts +37 -0
  253. package/dist/host/release-probe.js +156 -0
  254. package/dist/host/runtime/browser-argv.d.ts +1 -0
  255. package/dist/host/runtime/browser-argv.js +9 -0
  256. package/dist/host/runtime/front-app.d.ts +6 -0
  257. package/dist/host/runtime/front-app.js +70 -0
  258. package/dist/host/shell-render.d.ts +52 -0
  259. package/dist/host/shell-render.js +117 -0
  260. package/dist/host/shell-text.d.ts +30 -0
  261. package/dist/host/shell-text.js +40 -0
  262. package/dist/host/shell.d.ts +25 -0
  263. package/dist/host/shell.js +55 -0
  264. package/dist/host/site.d.ts +45 -0
  265. package/dist/host/site.js +182 -0
  266. package/dist/host/spec.d.ts +8 -0
  267. package/dist/host/spec.js +24 -0
  268. package/dist/host/submit-confirm.d.ts +19 -0
  269. package/dist/host/submit-confirm.js +45 -0
  270. package/dist/host/supply-index.d.ts +38 -0
  271. package/dist/host/supply-index.js +209 -0
  272. package/dist/host/supply-port.d.ts +5 -0
  273. package/dist/host/supply-port.js +50 -0
  274. package/dist/host/time.d.ts +22 -0
  275. package/dist/host/time.js +33 -0
  276. package/dist/host/tokens.d.ts +26 -0
  277. package/dist/host/tokens.js +154 -0
  278. package/dist/host/tool-approval.d.ts +86 -0
  279. package/dist/host/tool-approval.js +118 -0
  280. package/dist/host/tool-kit.d.ts +8 -0
  281. package/dist/host/tool-kit.js +22 -0
  282. package/dist/host/toolbox-port.d.ts +16 -0
  283. package/dist/host/toolbox-port.js +1 -0
  284. package/dist/host/unit-config.d.ts +34 -0
  285. package/dist/host/unit-config.js +28 -0
  286. package/dist/host/unit-data.d.ts +3 -0
  287. package/dist/host/unit-data.js +127 -0
  288. package/dist/host/unit-face.d.ts +95 -0
  289. package/dist/host/unit-face.js +1 -0
  290. package/dist/host/unit-plugin.d.ts +24 -0
  291. package/dist/host/unit-plugin.js +25 -0
  292. package/dist/host/update-journal-manifest.d.ts +19 -0
  293. package/dist/host/update-journal-manifest.js +134 -0
  294. package/dist/host/update-journal-types.d.ts +33 -0
  295. package/dist/host/update-journal-types.js +2 -0
  296. package/dist/host/update-journal.d.ts +43 -0
  297. package/dist/host/update-journal.js +409 -0
  298. package/dist/host/value-handoff.d.ts +16 -0
  299. package/dist/host/value-handoff.js +22 -0
  300. package/dist/host/version-range.d.ts +2 -0
  301. package/dist/host/version-range.js +13 -0
  302. package/dist/host/version.d.ts +4 -0
  303. package/dist/host/version.js +32 -0
  304. package/dist/host/workspace-store.d.ts +19 -0
  305. package/dist/host/workspace-store.js +133 -0
  306. package/dist/host/write-result.d.ts +1 -0
  307. package/dist/host/write-result.js +18 -0
  308. package/dist/lib/dsh-client.d.ts +1 -1
  309. package/package.json +51 -47
  310. package/src/lib/dsh-client.ts +2 -1
@@ -0,0 +1,264 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, readdirSync, unlinkSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import dayjs from 'dayjs';
5
+ import lockfile from 'proper-lockfile';
6
+ import { writeJsonFile, writeTextFileExclusive } from './fs-write.js';
7
+ import { pidAlive } from './process-alive.js';
8
+ import { now, nowIso } from './time.js';
9
+ export const UPDATE_LEASE_LAUNCH_MS = 120_000;
10
+ /** 有 pid 的更新租约最长认账时间:超过它基本可以断定 pid 被复活进程复用了。 */
11
+ export const UPDATE_LEASE_MAX_MS = 6 * 60 * 60 * 1000;
12
+ const UPDATE_LEASE_CLOCK_SKEW_MS = 60_000;
13
+ export function randomLeaseToken() {
14
+ return randomBytes(8).toString('hex');
15
+ }
16
+ export function hostLeaseDir(profileDir) {
17
+ return join(profileDir, '.dsh-workbench', 'hosts');
18
+ }
19
+ export function hostLeaseFile(profileDir, pid, token) {
20
+ return join(hostLeaseDir(profileDir), `${pid}-${token}.json`);
21
+ }
22
+ export function hostLeaseFiles(profileDir) {
23
+ try {
24
+ return readdirSync(hostLeaseDir(profileDir))
25
+ .filter((name) => name.endsWith('.json'))
26
+ .map((name) => join(hostLeaseDir(profileDir), name));
27
+ }
28
+ catch {
29
+ return [];
30
+ }
31
+ }
32
+ function textOf(value) {
33
+ return typeof value === 'string' && value !== '' ? value : undefined;
34
+ }
35
+ function pidOf(value, minimum) {
36
+ return typeof value === 'number' && Number.isInteger(value) && value >= minimum ? value : undefined;
37
+ }
38
+ function hostRecordOf(file, raw) {
39
+ if (typeof raw !== 'object' || raw === null)
40
+ return undefined;
41
+ const record = raw;
42
+ const pid = pidOf(record['pid'], 1);
43
+ const startedAt = textOf(record['startedAt']);
44
+ const token = textOf(record['token']);
45
+ const profile = record['profile'];
46
+ if (pid === undefined || startedAt === undefined || token === undefined)
47
+ return undefined;
48
+ if (typeof profile !== 'string')
49
+ return undefined;
50
+ const version = record['version'];
51
+ return {
52
+ pid,
53
+ startedAt,
54
+ token,
55
+ profile,
56
+ ...(typeof version === 'string' && version !== '' ? { version } : {}),
57
+ file,
58
+ };
59
+ }
60
+ export function readHostLease(file) {
61
+ try {
62
+ return hostRecordOf(file, JSON.parse(readFileSync(file, 'utf8')));
63
+ }
64
+ catch {
65
+ return undefined;
66
+ }
67
+ }
68
+ export function acquireHostLease(input) {
69
+ const startedAt = input.startedAt ?? nowIso();
70
+ const pid = input.pid ?? process.pid;
71
+ mkdirSync(hostLeaseDir(input.profileDir), { recursive: true });
72
+ for (let attempt = 0; attempt < 3; attempt += 1) {
73
+ const token = input.token === undefined || input.token === '' ? randomLeaseToken() : input.token;
74
+ const file = hostLeaseFile(input.profileDir, pid, token);
75
+ const body = {
76
+ pid,
77
+ startedAt,
78
+ token,
79
+ profile: input.profile,
80
+ ...(input.version === undefined || input.version === '' ? {} : { version: input.version }),
81
+ };
82
+ if (writeTextFileExclusive(file, `${JSON.stringify(body, null, 2)}\n`, { mode: 0o644 })) {
83
+ const record = { ...body, file };
84
+ return {
85
+ record,
86
+ release: () => {
87
+ releaseHostLease({ file, pid, token });
88
+ },
89
+ };
90
+ }
91
+ }
92
+ throw new Error('宿主租约重名,写不进去');
93
+ }
94
+ export function releaseHostLease(input) {
95
+ const record = readHostLease(input.file);
96
+ if (record === undefined)
97
+ return false;
98
+ if (record.pid !== input.pid || record.token !== input.token)
99
+ return false;
100
+ try {
101
+ unlinkSync(input.file);
102
+ return true;
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ }
108
+ export function activeHostLeases(profileDir) {
109
+ const found = [];
110
+ for (const file of hostLeaseFiles(profileDir)) {
111
+ const record = readHostLease(file);
112
+ if (record === undefined)
113
+ continue;
114
+ if (pidAlive(record.pid)) {
115
+ found.push(record);
116
+ continue;
117
+ }
118
+ try {
119
+ unlinkSync(file);
120
+ }
121
+ catch {
122
+ // 别人先清掉了也一样
123
+ }
124
+ }
125
+ return found.sort((left, right) => left.startedAt.localeCompare(right.startedAt));
126
+ }
127
+ export function updateLeaseFile(root) {
128
+ return join(root, 'self-update.lock');
129
+ }
130
+ export function readUpdateLease(root) {
131
+ return leaseRecordAt(updateLeaseFile(root));
132
+ }
133
+ function leaseRecordAt(file) {
134
+ try {
135
+ const raw = JSON.parse(readFileSync(file, 'utf8'));
136
+ if (typeof raw !== 'object' || raw === null)
137
+ return undefined;
138
+ const record = raw;
139
+ const pid = pidOf(record['pid'], 0);
140
+ const startedAt = textOf(record['startedAt']);
141
+ const token = textOf(record['token']);
142
+ if (pid === undefined || startedAt === undefined || token === undefined)
143
+ return undefined;
144
+ const kind = record['kind'];
145
+ return {
146
+ pid,
147
+ startedAt,
148
+ token,
149
+ file,
150
+ ...(kind === 'update' || kind === 'reinstall' ? { kind } : {}),
151
+ };
152
+ }
153
+ catch {
154
+ return undefined;
155
+ }
156
+ }
157
+ export function updateLeaseActive(root, at = now()) {
158
+ const record = readUpdateLease(root);
159
+ if (record === undefined)
160
+ return false;
161
+ const started = dayjs(record.startedAt).valueOf();
162
+ if (!Number.isFinite(started))
163
+ return false;
164
+ const age = at - started;
165
+ if (record.pid > 0) {
166
+ if (!pidAlive(record.pid))
167
+ return false;
168
+ return age < UPDATE_LEASE_MAX_MS;
169
+ }
170
+ if (age < -UPDATE_LEASE_CLOCK_SKEW_MS)
171
+ return false;
172
+ return age < UPDATE_LEASE_LAUNCH_MS;
173
+ }
174
+ export function acquireUpdateLease(input) {
175
+ mkdirSync(input.root, { recursive: true });
176
+ const startedAt = input.startedAt ?? nowIso();
177
+ const pid = input.pid ?? 0;
178
+ const token = input.token === undefined || input.token === '' ? randomLeaseToken() : input.token;
179
+ const file = updateLeaseFile(input.root);
180
+ let unlock;
181
+ try {
182
+ unlock = lockfile.lockSync(file, updateLockOptions(file));
183
+ }
184
+ catch (error) {
185
+ if (error.code === 'ELOCKED')
186
+ return undefined;
187
+ throw error;
188
+ }
189
+ try {
190
+ const body = {
191
+ pid,
192
+ startedAt,
193
+ token,
194
+ ...(input.kind === undefined ? {} : { kind: input.kind }),
195
+ };
196
+ writeJsonFile(file, body, { fsync: true });
197
+ const record = { ...body, file };
198
+ return {
199
+ record,
200
+ release: () => {
201
+ releaseUpdateLease({ root: input.root, token, pid });
202
+ },
203
+ rewrite: (nextPid) => rewriteUpdateLease({ root: input.root, token, pid: nextPid }),
204
+ };
205
+ }
206
+ catch (error) {
207
+ try {
208
+ unlock();
209
+ }
210
+ catch {
211
+ // 已经没了
212
+ }
213
+ throw error;
214
+ }
215
+ }
216
+ const UPDATE_LOCK_STALE_MS = 30_000;
217
+ const UPDATE_LOCK_UPDATE_MS = 5_000;
218
+ function updateLockOptions(file) {
219
+ return {
220
+ realpath: false,
221
+ stale: UPDATE_LOCK_STALE_MS,
222
+ update: UPDATE_LOCK_UPDATE_MS,
223
+ retries: 0,
224
+ lockfilePath: `${file}.d`,
225
+ };
226
+ }
227
+ export function rewriteUpdateLease(input) {
228
+ const record = readUpdateLease(input.root);
229
+ if (record === undefined || record.token !== input.token)
230
+ return false;
231
+ try {
232
+ writeJsonFile(record.file, {
233
+ pid: input.pid,
234
+ startedAt: input.startedAt ?? record.startedAt,
235
+ token: record.token,
236
+ ...(record.kind === undefined ? {} : { kind: record.kind }),
237
+ });
238
+ return true;
239
+ }
240
+ catch {
241
+ return false;
242
+ }
243
+ }
244
+ export function releaseUpdateLease(input) {
245
+ const record = readUpdateLease(input.root);
246
+ if (record === undefined || record.token !== input.token)
247
+ return false;
248
+ if (input.pid !== undefined && record.pid !== 0 && record.pid !== input.pid)
249
+ return false;
250
+ try {
251
+ unlinkSync(record.file);
252
+ }
253
+ catch (error) {
254
+ if (error.code !== 'ENOENT')
255
+ return false;
256
+ }
257
+ try {
258
+ lockfile.unlockSync(record.file, { realpath: false, lockfilePath: `${record.file}.d` });
259
+ }
260
+ catch {
261
+ // 锁目录可能已经被清掉或过期回收
262
+ }
263
+ return true;
264
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * 跨平台库的「能力 → 首选实现」表:外壳 arch 的 S68 与 DIY 模块的 `source` 判据共用这一份,
3
+ * 避免两边各写一张表后漂开。
4
+ *
5
+ * 能力名是「做什么」,`preferred` 是「用什么」;两者不是同一个层级(类似 datetime → dayjs)。
6
+ * 手写轮子的指纹只认最常见的直连写法;`importsPreferred()` 负责判断这个文件是否已经在用首选库。
7
+ */
8
+ export interface LibCapability {
9
+ readonly capability: string;
10
+ readonly preferred: string;
11
+ readonly pattern: RegExp;
12
+ readonly why: string;
13
+ }
14
+ /** 手写轮子的硬指纹;按能力名稳定排序,方便两边报告与测试对照。 */
15
+ export declare const LIB_CAPABILITIES: readonly LibCapability[];
16
+ /**
17
+ * 这个文件是否已经 import 了某个首选库(静态或动态 import 都算)。
18
+ * @param source 文件全文。
19
+ * @param preferred 首选库包名。
20
+ * @returns 有 import 就 `true`。
21
+ */
22
+ export declare function importsPreferred(source: string, preferred: string): boolean;
@@ -0,0 +1,37 @@
1
+ /** 手写轮子的硬指纹;按能力名稳定排序,方便两边报告与测试对照。 */
2
+ export const LIB_CAPABILITIES = [
3
+ {
4
+ capability: 'process-spawn',
5
+ preferred: 'execa',
6
+ pattern: /from\s+['"]node:child_process['"]/,
7
+ why: '自己起进程要用 execa;同步/跨平台差异交给它',
8
+ },
9
+ {
10
+ capability: 'cli-locate',
11
+ preferred: 'which',
12
+ pattern: /\bprocess\.env\.(?:PATH|PATHEXT)\b/,
13
+ why: '自己扫 PATH/PATHEXT 要用 which(它处理 PATHEXT 与 Path 大小写)',
14
+ },
15
+ {
16
+ capability: 'file-lock',
17
+ preferred: 'proper-lockfile',
18
+ pattern: /\bprocess\.kill\([^)]*,\s*0\)|flag:\s*['"]wx['"]/,
19
+ why: '自己抢文件锁要用 proper-lockfile(stale / 重试 / 跨平台)',
20
+ },
21
+ {
22
+ capability: 'atomic-state',
23
+ preferred: 'write-file-atomic',
24
+ pattern: /writeFileSync\([^)]*\.(?:sync\.json|self-update\.json)/,
25
+ why: '自己直写状态文件要用 write-file-atomic(防写一半)',
26
+ },
27
+ ];
28
+ /**
29
+ * 这个文件是否已经 import 了某个首选库(静态或动态 import 都算)。
30
+ * @param source 文件全文。
31
+ * @param preferred 首选库包名。
32
+ * @returns 有 import 就 `true`。
33
+ */
34
+ export function importsPreferred(source, preferred) {
35
+ const escaped = preferred.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
36
+ return new RegExp(`(?:from\\s*|import\\s*\\(\\s*)['"]${escaped}['"]`).test(source);
37
+ }
@@ -0,0 +1,19 @@
1
+ import type { BinNeed, LibNeed, SupplySource } from '../contract/needs.js';
2
+ import type { HostOs } from '../contract/protocol/platform.js';
3
+ export type NpmSource = Extract<SupplySource, {
4
+ kind: 'npm';
5
+ }>;
6
+ export declare function libInstallCommand(options: {
7
+ readonly need: LibNeed;
8
+ readonly source: NpmSource;
9
+ readonly version?: string | undefined;
10
+ readonly env?: NodeJS.ProcessEnv | undefined;
11
+ readonly prefix: string;
12
+ readonly storeDir?: string | undefined;
13
+ readonly pnpm?: string | undefined;
14
+ }): string;
15
+ export declare function binInstallCommand(need: BinNeed, os: HostOs, env: NodeJS.ProcessEnv, prefix: string, storeDir?: string): string | undefined;
16
+ export declare function libUninstallCommand(options: {
17
+ readonly need: LibNeed;
18
+ readonly prefix: string;
19
+ }): string;
@@ -0,0 +1,40 @@
1
+ import { npmRegistryOf } from './npm-registry.js';
2
+ import { quoteShellArg } from './shell-text.js';
3
+ export function libInstallCommand(options) {
4
+ const { need, source, version } = options;
5
+ const pnpm = options.pnpm ?? process.env.DSH_WB_PNPM?.trim() ?? 'pnpm';
6
+ const registry = npmRegistryOf(source, options.env ?? process.env);
7
+ const spec = version ?? need.version ?? 'latest';
8
+ const registryFlag = registry.ok ? ` --registry ${quoteShellArg(registry.value)}` : '';
9
+ const storeFlag = options.storeDir === undefined ? '' : ` --store-dir ${quoteShellArg(options.storeDir)}`;
10
+ return `${pnpm} add --dir ${quoteShellArg(options.prefix)} ${quoteShellArg(`${need.name}@${spec}`)}${registryFlag}${storeFlag} --allow-build=${quoteShellArg(need.name)}`;
11
+ }
12
+ export function binInstallCommand(need, os, env, prefix, storeDir) {
13
+ const install = need.install;
14
+ if (install === undefined)
15
+ return undefined;
16
+ if (install.platforms !== undefined && !install.platforms.includes(os))
17
+ return undefined;
18
+ if (install.kind === 'command') {
19
+ const line = install.line.trim();
20
+ return line === '' ? undefined : line;
21
+ }
22
+ const packageName = install.package.trim();
23
+ if (packageName === '')
24
+ return undefined;
25
+ return libInstallCommand({
26
+ prefix,
27
+ ...(storeDir === undefined ? {} : { storeDir }),
28
+ need: { kind: 'lib', name: packageName, purpose: need.purpose },
29
+ source: {
30
+ kind: 'npm',
31
+ package: packageName,
32
+ ...(install.registryEnv === undefined ? {} : { registryEnv: install.registryEnv }),
33
+ ...(install.registryDefault === undefined ? {} : { registryDefault: install.registryDefault }),
34
+ },
35
+ env,
36
+ });
37
+ }
38
+ export function libUninstallCommand(options) {
39
+ return `pnpm remove --dir ${quoteShellArg(options.prefix)} ${quoteShellArg(options.need.name)}`;
40
+ }
@@ -0,0 +1,18 @@
1
+ import type { LibReader } from '../contract/lib.js';
2
+ import type { LibRunner } from '../contract/runner.js';
3
+ export type LibRuntimes = Readonly<Record<string, LibRunner>>;
4
+ interface Logger {
5
+ warn?(message: string): void;
6
+ }
7
+ /**
8
+ * 给声明了 `runs` 的 lib 注入「跑这个运行时」的执行器:库侧按约定暴露 `set<Runtime>Runner`
9
+ * (运行时名字首字母大写 + `Runner`),外壳在每次 `load` 之后把执行器交给它。
10
+ *
11
+ * 没暴露的(版本旧)就保持它自己的行为(按 PATH 找),只记一条 warn;不熟悉的运行时同样只 warn。
12
+ * @param libs 原来的读库口。
13
+ * @param runtimes 外壳手上有的执行器,按运行时名字给。
14
+ * @param logger 记 warn 的地方(默认不记)。
15
+ * @returns 包好的读库口;`load` 的签名与返回不变。
16
+ */
17
+ export declare function withLibRunners(libs: LibReader, runtimes: LibRuntimes, logger?: Logger): LibReader;
18
+ export {};
@@ -0,0 +1,46 @@
1
+ function runnerOf(runtimes, runtime) {
2
+ return runtimes[runtime];
3
+ }
4
+ function setterNameOf(runtime) {
5
+ return `set${runtime.charAt(0).toUpperCase()}${runtime.slice(1)}Runner`;
6
+ }
7
+ /**
8
+ * 给声明了 `runs` 的 lib 注入「跑这个运行时」的执行器:库侧按约定暴露 `set<Runtime>Runner`
9
+ * (运行时名字首字母大写 + `Runner`),外壳在每次 `load` 之后把执行器交给它。
10
+ *
11
+ * 没暴露的(版本旧)就保持它自己的行为(按 PATH 找),只记一条 warn;不熟悉的运行时同样只 warn。
12
+ * @param libs 原来的读库口。
13
+ * @param runtimes 外壳手上有的执行器,按运行时名字给。
14
+ * @param logger 记 warn 的地方(默认不记)。
15
+ * @returns 包好的读库口;`load` 的签名与返回不变。
16
+ */
17
+ export function withLibRunners(libs, runtimes, logger) {
18
+ const warned = new Set();
19
+ const warnOnce = (key, message) => {
20
+ if (warned.has(key))
21
+ return;
22
+ warned.add(key);
23
+ logger?.warn?.(message);
24
+ };
25
+ return {
26
+ async load(need, entry) {
27
+ const module = await libs.load(need, entry);
28
+ for (const runtime of need.runs ?? []) {
29
+ const runner = runnerOf(runtimes, runtime);
30
+ if (runner === undefined) {
31
+ warnOnce(`${need.name}:${runtime}:unsupported`, `[dsh-workbench] ${need.name} 声明了自己会跑 ${runtime},但工作台没有这个执行器 —— 它会按自己的方式找`);
32
+ continue;
33
+ }
34
+ const setter = typeof module === 'object' && module !== null
35
+ ? module[setterNameOf(runtime)]
36
+ : undefined;
37
+ if (typeof setter !== 'function') {
38
+ warnOnce(`${need.name}:${entry}:${runtime}:missing`, `[dsh-workbench] ${need.name} 声明了自己会跑 ${runtime},但这一版没有 ${setterNameOf(runtime)} —— 它会按 PATH 找`);
39
+ continue;
40
+ }
41
+ setter.call(module, runner);
42
+ }
43
+ return module;
44
+ },
45
+ };
46
+ }
@@ -0,0 +1,7 @@
1
+ import { localDirOf } from './spec.js';
2
+ export { localDirOf };
3
+ export declare function packageManifestOf(dir: string): Readonly<Record<string, unknown>> | undefined;
4
+ export declare function dshRecordOf(dir: string): unknown | undefined;
5
+ export declare function packageNameOf(dir: string): string | undefined;
6
+ export declare function pathDeclarationOf(spec: string): unknown | undefined;
7
+ export declare function declarationRefusalOf(name: string, raw: unknown): readonly string[];
@@ -0,0 +1,33 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { localDirOf } from './spec.js';
4
+ export { localDirOf };
5
+ import { declarationProblemsOf } from '../contract/unit-declaration.js';
6
+ function asRecord(value) {
7
+ return typeof value === 'object' && value !== null ? value : undefined;
8
+ }
9
+ export function packageManifestOf(dir) {
10
+ try {
11
+ const parsed = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
12
+ return asRecord(parsed);
13
+ }
14
+ catch {
15
+ return undefined;
16
+ }
17
+ }
18
+ export function dshRecordOf(dir) {
19
+ return packageManifestOf(dir)?.dsh;
20
+ }
21
+ export function packageNameOf(dir) {
22
+ const name = packageManifestOf(dir)?.name;
23
+ return typeof name === 'string' && name.trim() !== '' ? name.trim() : undefined;
24
+ }
25
+ export function pathDeclarationOf(spec) {
26
+ const dir = localDirOf(spec);
27
+ return dir === undefined ? undefined : asRecord(dshRecordOf(dir))?.workbench;
28
+ }
29
+ export function declarationRefusalOf(name, raw) {
30
+ if (raw === undefined)
31
+ return [];
32
+ return declarationProblemsOf(name, raw);
33
+ }
@@ -0,0 +1,97 @@
1
+ import { type LongTaskIntervention, type LongTaskStatus, type LongTaskStep } from '../contract/long-task.js';
2
+ export interface LongTaskBase {
3
+ readonly id: string;
4
+ readonly workspace: string;
5
+ readonly target: string;
6
+ readonly headline?: string | undefined;
7
+ readonly status: LongTaskStatus;
8
+ readonly step: string;
9
+ readonly steps: readonly string[];
10
+ readonly intervention?: LongTaskIntervention | undefined;
11
+ readonly loginUrl?: string | undefined;
12
+ readonly why?: string | undefined;
13
+ readonly startedAt: string;
14
+ readonly at: string;
15
+ readonly session?: string | undefined;
16
+ }
17
+ export interface LongTaskStart {
18
+ readonly workspace: string;
19
+ readonly target: string;
20
+ readonly payload?: unknown;
21
+ readonly session?: string | undefined;
22
+ }
23
+ export interface LongTaskChange<S extends LongTaskBase> {
24
+ readonly kind: 'start' | 'step' | 'settle';
25
+ readonly snapshot: S;
26
+ readonly step?: LongTaskStep | undefined;
27
+ readonly by?: string | undefined;
28
+ }
29
+ export interface LongTaskDeps<S extends LongTaskBase> {
30
+ readonly run: (options: {
31
+ readonly payload: unknown;
32
+ readonly onStep: (step: LongTaskStep) => void;
33
+ readonly signal: AbortSignal;
34
+ }) => Promise<unknown>;
35
+ readonly step?: ((step: LongTaskStep, current: S) => Partial<S>) | undefined;
36
+ readonly outcome?: ((result: unknown, current: S) => Partial<S>) | undefined;
37
+ readonly stopped?: ((current: S) => Partial<S>) | undefined;
38
+ readonly recheck?: ((current: S) => void) | undefined;
39
+ readonly answer?: ((current: S, values: Readonly<Record<string, string>>) => void) | undefined;
40
+ readonly view: (snapshot: S) => Readonly<Record<string, unknown>>;
41
+ readonly now?: (() => string) | undefined;
42
+ readonly nextId?: (() => string) | undefined;
43
+ readonly facts?: ((change: LongTaskChange<S>) => readonly string[] | undefined) | undefined;
44
+ readonly recentMs?: number | undefined;
45
+ }
46
+ /**
47
+ * 一个单元的长任务注册表:`current(workspace)` 是面板那一行要的投影,`live()` 是外壳侧栏那颗
48
+ * loading 点要的(**不分工作区、不分目标**,把现在活着的每一趟交出来),`stop` 只把中断信号转给生产方。
49
+ */
50
+ export interface LongTaskRegistry<S extends LongTaskBase> {
51
+ readonly resumable: boolean;
52
+ readonly answerable: boolean;
53
+ start(options: LongTaskStart): S;
54
+ snapshot(id: string): S | null;
55
+ active(workspace: string, target: string): S | null;
56
+ current(workspace: string): readonly Readonly<Record<string, unknown>>[];
57
+ live(): readonly S[];
58
+ stop(id: string, by?: string): boolean;
59
+ recheck(id: string): boolean;
60
+ answer(id: string, values: Readonly<Record<string, string>>): boolean;
61
+ onChange(listener: (change: LongTaskChange<S>) => void): () => void;
62
+ rebind?(deps: LongTaskDeps<S>): void;
63
+ }
64
+ export declare function createLongTaskRegistry<S extends LongTaskBase>(deps: LongTaskDeps<S>): LongTaskRegistry<S>;
65
+ /**
66
+ * `withInterventionRetry` 的口径:最多试几次、每轮先等多久(也可按轮次算)、怎么等。
67
+ */
68
+ export interface InterventionRetryOptions {
69
+ readonly attempts?: number | undefined;
70
+ readonly delayMs?: number | ((attempt: number) => number) | undefined;
71
+ readonly sleep?: ((ms: number) => Promise<void>) | undefined;
72
+ }
73
+ /**
74
+ * 把「看一眼接上没有」包成能交给 `longTasks.create({ recheck })` 的 handler:
75
+ * 用户在人工干预节点上按「我处理完了」时先立刻试一次,没接上就有界地再试(第 2 轮起每轮先等)。
76
+ * `check` 返回 true = 已经接上,不用再试;抛错算没接上、继续下一轮。
77
+ * 同一 id 上一轮还在飞时再按直接忽略;成功 / 用尽都清单飞;**永不抛错**(fire-and-forget)。
78
+ * @param check 看一眼接上没有,可同步可异步。
79
+ * @param options 轮次上限(默认 5)、第几次等待等多久(默认 1500ms,可给函数,从第 1 次等待起算)、怎么等(默认真等,测试可注入假的)。
80
+ * @returns 一条同签名的 handler,直接交给 `const longTasks = create({ recheck })`。
81
+ */
82
+ export declare function withInterventionRetry<S extends LongTaskBase>(check: (current: S) => boolean | Promise<boolean>, options?: InterventionRetryOptions): (current: S) => void;
83
+ export declare function sharedLongTaskRegistry<S extends LongTaskBase>(scope: string, key: string, deps: LongTaskDeps<S>): LongTaskRegistry<S>;
84
+ export interface LongTaskHost {
85
+ create<S extends LongTaskBase>(options: {
86
+ readonly key: string;
87
+ } & LongTaskDeps<S>): LongTaskRegistry<S>;
88
+ }
89
+ export declare function createLongTaskHost(options: {
90
+ readonly scope: string;
91
+ readonly unit: string;
92
+ readonly bump: (facts: readonly string[]) => void;
93
+ readonly notify?: ((change: LongTaskChange<LongTaskBase>) => void) | undefined;
94
+ }): {
95
+ readonly host: LongTaskHost;
96
+ dispose(): void;
97
+ };