dsh-world 0.7.6 → 0.8.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 (102) hide show
  1. package/CHANGELOG.md +541 -479
  2. package/CONTRIBUTING.md +174 -174
  3. package/INSTALL.md +314 -314
  4. package/NOTES.md +57 -3
  5. package/README.md +332 -259
  6. package/client/index.js +1126 -991
  7. package/lib/compaction.d.ts +1 -0
  8. package/lib/compaction.js +1 -1
  9. package/lib/console/routes.d.ts +11 -3
  10. package/lib/console/routes.js +12 -7
  11. package/lib/console/snapshot.d.ts +2 -0
  12. package/lib/console/snapshot.js +1 -0
  13. package/lib/ecosystem/computer/browser/browser.d.ts +34 -0
  14. package/lib/ecosystem/computer/browser/browser.js +101 -0
  15. package/lib/ecosystem/computer/browser/cdp.d.ts +22 -0
  16. package/lib/ecosystem/computer/browser/cdp.js +91 -0
  17. package/lib/ecosystem/computer/browser/edge.d.ts +15 -0
  18. package/lib/ecosystem/computer/browser/edge.js +80 -0
  19. package/lib/ecosystem/computer/browser/page.d.ts +41 -0
  20. package/lib/ecosystem/computer/browser/page.js +140 -0
  21. package/lib/ecosystem/computer/browser/pageLib.d.ts +7 -0
  22. package/lib/ecosystem/computer/browser/pageLib.js +106 -0
  23. package/lib/ecosystem/computer/desktop/desktop.d.ts +91 -0
  24. package/lib/ecosystem/computer/desktop/desktop.js +322 -0
  25. package/lib/ecosystem/computer/desktop/driver.d.ts +34 -0
  26. package/lib/ecosystem/computer/desktop/driver.js +197 -0
  27. package/lib/ecosystem/computer/desktop/processes.d.ts +5 -0
  28. package/lib/ecosystem/computer/desktop/processes.js +15 -0
  29. package/lib/ecosystem/computer/desktop/recording.d.ts +77 -0
  30. package/lib/ecosystem/computer/desktop/recording.js +187 -0
  31. package/lib/ecosystem/computer/desktop/screen.d.ts +33 -0
  32. package/lib/ecosystem/computer/desktop/screen.js +182 -0
  33. package/lib/ecosystem/computer/desktop/turns.d.ts +58 -0
  34. package/lib/ecosystem/computer/desktop/turns.js +94 -0
  35. package/lib/ecosystem/computer/desktop/watching.d.ts +25 -0
  36. package/lib/ecosystem/computer/desktop/watching.js +81 -0
  37. package/lib/ecosystem/computer/inbox/inbox.d.ts +32 -0
  38. package/lib/ecosystem/computer/inbox/inbox.js +142 -0
  39. package/lib/ecosystem/computer/index.d.ts +82 -0
  40. package/lib/ecosystem/computer/index.js +133 -0
  41. package/lib/ecosystem/computer/procedures/alarm.d.ts +13 -0
  42. package/lib/ecosystem/computer/procedures/alarm.js +46 -0
  43. package/lib/ecosystem/computer/procedures/archive.d.ts +32 -0
  44. package/lib/ecosystem/computer/procedures/archive.js +68 -0
  45. package/lib/ecosystem/computer/procedures/catalog.d.ts +7 -0
  46. package/lib/ecosystem/computer/procedures/catalog.js +75 -0
  47. package/lib/ecosystem/computer/procedures/format.d.ts +167 -0
  48. package/lib/ecosystem/computer/procedures/format.js +332 -0
  49. package/lib/ecosystem/computer/procedures/library.d.ts +53 -0
  50. package/lib/ecosystem/computer/procedures/library.js +178 -0
  51. package/lib/ecosystem/computer/procedures/run.d.ts +80 -0
  52. package/lib/ecosystem/computer/procedures/run.js +245 -0
  53. package/lib/ecosystem/computer/tools.d.ts +21 -0
  54. package/lib/ecosystem/computer/tools.js +197 -0
  55. package/lib/ecosystem/qq-native/images.d.ts +3 -0
  56. package/lib/ecosystem/qq-native/images.js +18 -6
  57. package/lib/ecosystem/qq-native/index.js +2 -2
  58. package/lib/ecosystem/shared/turn.d.ts +3 -0
  59. package/lib/ecosystem/shared/turn.js +13 -3
  60. package/lib/ecosystem/wechat/home.d.ts +1 -0
  61. package/lib/ecosystem/wechat/home.js +9 -3
  62. package/lib/ecosystem/wechat/images.js +3 -5
  63. package/lib/ecosystem/wechat/index.d.ts +1 -0
  64. package/lib/ecosystem/wechat/reading.d.ts +1 -1
  65. package/lib/ecosystem/wechat/reading.js +2 -2
  66. package/lib/history.js +2 -1
  67. package/lib/images.d.ts +30 -0
  68. package/lib/images.js +101 -0
  69. package/lib/index.d.ts +4 -0
  70. package/lib/index.js +90 -5
  71. package/lib/life/photoTools.js +4 -15
  72. package/lib/life/runtime.d.ts +12 -2
  73. package/lib/life/runtime.js +93 -12
  74. package/lib/life/toolRegistry.d.ts +9 -3
  75. package/lib/life/toolRegistry.js +46 -27
  76. package/lib/life/turnCost.d.ts +16 -0
  77. package/lib/life/turnCost.js +44 -0
  78. package/lib/life/types.d.ts +17 -0
  79. package/lib/memoryTools.d.ts +2 -1
  80. package/lib/memoryTools.js +16 -3
  81. package/lib/promptSection.d.ts +1 -0
  82. package/lib/promptSection.js +29 -42
  83. package/lib/runtime.js +1 -1
  84. package/lib/types.d.ts +4 -0
  85. package/lib/worldAdd.d.ts +9 -0
  86. package/lib/worldAdd.js +39 -0
  87. package/lib/worldPrompt.d.ts +3 -2
  88. package/lib/worldPrompt.js +3 -2
  89. package/lib/worldRoutes.d.ts +5 -2
  90. package/lib/worldRoutes.js +29 -4
  91. package/lib/worldSwitch.d.ts +8 -2
  92. package/lib/worldSwitch.js +11 -5
  93. package/package.json +132 -129
  94. package/src/ecosystem/README.md +2 -1
  95. package/src/ecosystem/computer/NOTICE.md +27 -0
  96. package/src/ecosystem/computer/README.md +244 -0
  97. package/src/ecosystem/computer/desktop/win32.ps1 +858 -0
  98. package/src/ecosystem/wechat/windows/README.md +4 -2
  99. package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
  100. package/src/ecosystem/wechat/windows/engine/profiles.json +28 -0
  101. package/templates/world-prompt-memory.md +10 -10
  102. package/templates/world-prompt.md +65 -65
@@ -0,0 +1,332 @@
1
+ // src/ecosystem/computer/procedures/format.ts
2
+ import { PAGE_KEYS } from "../browser/page.js";
3
+ import { desktopKey, holdMs } from "../desktop/desktop.js";
4
+ export class ProcedureError extends Error {
5
+ name = 'ProcedureError';
6
+ }
7
+ const fail = (path, why) => { throw new ProcedureError(`${path}:${why}`); };
8
+ /** A category or operation name is also a folder or file name, so it holds no path characters. */
9
+ export const ENTRY_NAME = /^[\p{L}\p{N}_-]{1,40}$/u;
10
+ /** Her own notes for a category live in `<category>/目录.md`, so no operation may take that name. */
11
+ export const GUIDE_NAME = '目录';
12
+ /** Where files the development build left flat in `procedures/` belong. */
13
+ export const UNSORTED = '未分类';
14
+ const FIELD_NAME = /^[a-zA-Z_][a-zA-Z0-9_]{0,30}$/;
15
+ const TEMPLATE = /\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}/g;
16
+ const ACTIONS = ['open', 'click', 'type', 'press', 'wait', 'check', 'extract', 'script'];
17
+ const EXTRAS = { open: [], click: ['outward'], type: ['outward'], press: ['outward'], wait: [], check: [], extract: ['allowEmpty'], script: ['as', 'outward', 'allowEmpty'] };
18
+ const RESERVED = new Set(['__proto__', 'constructor', 'prototype']);
19
+ const ANCHOR_KEYS = ['role', 'name', 'text', 'css', 'nth'];
20
+ const MAX_STEPS = 40, MAX_SCRIPT = 4000, MAX_TEXT = 500;
21
+ export const substitute = (text, values) => text.replace(TEMPLATE, (_all, key) => Object.hasOwn(values, key) ? String(values[key] ?? '') : '');
22
+ /** Her browser reads the web, not the computer: no file:, chrome:, edge:, javascript: or data: pages. */
23
+ export const WEB_ONLY = '只能打开 http 或 https 地址';
24
+ export const isWebAddress = (url) => /^https?:\/\//i.test(url.trim()) || url.trim() === 'about:blank';
25
+ const names = (text) => [...text.matchAll(TEMPLATE)].map(match => match[1]);
26
+ const record = (value, path) => value && typeof value === 'object' && !Array.isArray(value) ? value : fail(path, '应该是一个对象');
27
+ /** A typo like `nmae` must not quietly turn an anchor into "any link". */
28
+ function only(input, keys, path) {
29
+ for (const key of Object.keys(input))
30
+ if (input[key] !== undefined && !keys.includes(key))
31
+ fail(path, `不认识 ${key}`);
32
+ }
33
+ function identifier(value, path, what) {
34
+ if (!FIELD_NAME.test(value) || RESERVED.has(value))
35
+ fail(path, `${what} ${value} 只能用字母、数字和下划线,且不能是 ${[...RESERVED].join('、')}`);
36
+ return value;
37
+ }
38
+ function text(value, path, max = MAX_TEXT, known) {
39
+ if (typeof value !== 'string' || !value.trim() || value.length > max)
40
+ return fail(path, `应该是 1 到 ${max} 字的文字`);
41
+ if (known)
42
+ for (const name of names(value))
43
+ if (!known.has(name))
44
+ fail(path, `{{${name}}} 不是已声明的参数或字段`);
45
+ return value;
46
+ }
47
+ const optionalText = (value, path, known) => value === undefined ? undefined : text(value, path, MAX_TEXT, known);
48
+ const flag = (value, path) => value === undefined ? undefined : typeof value === 'boolean' ? value : fail(path, '应该是 true 或 false');
49
+ /** `bare` is for an extract field that names only an attribute: it reads the list item itself. */
50
+ function anchor(value, path, known, extra = [], bare = false) {
51
+ const input = record(value, path);
52
+ only(input, [...ANCHOR_KEYS, ...extra], path);
53
+ const out = {};
54
+ for (const key of ['role', 'name', 'text', 'css']) {
55
+ const field = optionalText(input[key], `${path}.${key}`, known);
56
+ if (field !== undefined)
57
+ out[key] = field;
58
+ }
59
+ if (!bare && !out.role && !out.name && !out.text && !out.css)
60
+ fail(path, '至少要有 role、name、text、css 中的一个');
61
+ if (input.nth !== undefined) {
62
+ if (!Number.isSafeInteger(input.nth) || input.nth < 0 || input.nth > 50)
63
+ fail(`${path}.nth`, '应该是 0 到 50 的整数');
64
+ out.nth = input.nth;
65
+ }
66
+ return out;
67
+ }
68
+ function condition(value, path, known, extra = []) {
69
+ const input = record(value, path);
70
+ only(input, ['text', 'url', 'anchor', ...extra], path);
71
+ const out = {};
72
+ const textValue = optionalText(input.text, `${path}.text`, known), urlValue = optionalText(input.url, `${path}.url`, known);
73
+ if (textValue !== undefined)
74
+ out.text = textValue;
75
+ if (urlValue !== undefined)
76
+ out.url = urlValue;
77
+ if (input.anchor !== undefined)
78
+ out.anchor = anchor(input.anchor, `${path}.anchor`, known);
79
+ if (!out.text && !out.url && !out.anchor)
80
+ fail(path, '至少要有 text、url、anchor 中的一个');
81
+ return out;
82
+ }
83
+ function extract(value, path, known) {
84
+ const input = record(value, path);
85
+ only(input, ['list', 'fields', 'limit'], path);
86
+ const fields = record(input.fields, `${path}.fields`);
87
+ const entries = Object.entries(fields);
88
+ if (!entries.length || entries.length > 12)
89
+ fail(`${path}.fields`, '要有 1 到 12 个字段');
90
+ const out = { list: anchor(input.list, `${path}.list`, known), fields: {} };
91
+ for (const [name, field] of entries) {
92
+ identifier(name, `${path}.fields`, '字段名');
93
+ const attr = optionalText(record(field, `${path}.fields.${name}`).attr, `${path}.fields.${name}.attr`);
94
+ out.fields[name] = { ...anchor(field, `${path}.fields.${name}`, known, ['attr'], attr !== undefined), ...(attr === undefined ? {} : { attr }) };
95
+ }
96
+ if (input.limit !== undefined) {
97
+ if (!Number.isSafeInteger(input.limit) || input.limit < 1 || input.limit > 20)
98
+ fail(`${path}.limit`, '应该是 1 到 20 的整数');
99
+ out.limit = input.limit;
100
+ }
101
+ return out;
102
+ }
103
+ /** `taken` holds the names a `script` result may not reuse; a step that names a result adds it. */
104
+ function step(value, path, known, taken) {
105
+ const input = record(value, path);
106
+ const actions = ACTIONS.filter(action => action in input);
107
+ if (actions.length !== 1)
108
+ return fail(path, `每一步只能有一个动作(${ACTIONS.join('、')})`);
109
+ const action = actions[0];
110
+ for (const key of Object.keys(input))
111
+ if (key !== action && !EXTRAS[action].includes(key))
112
+ fail(path, `${action} 这一步不认识 ${key}`);
113
+ const outward = flag(input.outward, `${path}.outward`), allowEmpty = flag(input.allowEmpty, `${path}.allowEmpty`);
114
+ const extra = outward === undefined ? {} : { outward }, empty = allowEmpty === undefined ? {} : { allowEmpty };
115
+ switch (action) {
116
+ case 'open': {
117
+ const address = text(input.open, `${path}.open`, 2000, known);
118
+ // An address that starts with a parameter can only be checked once it is filled in, when the step runs.
119
+ if (!address.trimStart().startsWith('{{') && !isWebAddress(address))
120
+ fail(`${path}.open`, WEB_ONLY);
121
+ return { open: address };
122
+ }
123
+ case 'click': return { click: anchor(input.click, `${path}.click`, known), ...extra };
124
+ case 'type': {
125
+ const body = record(input.type, `${path}.type`);
126
+ only(body, ['into', 'text'], `${path}.type`);
127
+ return { type: { into: anchor(body.into, `${path}.type.into`, known), text: text(body.text, `${path}.type.text`, 2000, known) }, ...extra };
128
+ }
129
+ case 'press': {
130
+ const key = text(input.press, `${path}.press`, 40);
131
+ if (!PAGE_KEYS.includes(key))
132
+ fail(`${path}.press`, `不认识按键 ${key},可用:${PAGE_KEYS.join('、')}`);
133
+ return { press: key, ...extra };
134
+ }
135
+ case 'wait': {
136
+ const seconds = record(input.wait, `${path}.wait`).seconds;
137
+ if (seconds !== undefined && (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds <= 0 || seconds > 60))
138
+ fail(`${path}.wait.seconds`, '应该是大于 0、不超过 60 的秒数');
139
+ return { wait: { ...condition(input.wait, `${path}.wait`, known, ['seconds']), ...(seconds === undefined ? {} : { seconds: seconds }) } };
140
+ }
141
+ case 'check': return { check: condition(input.check, `${path}.check`, known) };
142
+ case 'extract': return { extract: extract(input.extract, `${path}.extract`, known), ...empty };
143
+ case 'script': {
144
+ const as = input.as === undefined ? undefined : identifier(String(input.as), `${path}.as`, '结果名');
145
+ if (as !== undefined) {
146
+ if (taken.has(as))
147
+ fail(`${path}.as`, `${as} 已经被参数、count 或前面的步骤用了`);
148
+ taken.add(as);
149
+ }
150
+ // Only a kept value is checked for emptiness, so the flag means nothing without `as`.
151
+ if (allowEmpty !== undefined && as === undefined)
152
+ fail(`${path}.allowEmpty`, '只用在带 as 的脚本上');
153
+ return { script: text(input.script, `${path}.script`, MAX_SCRIPT), ...(as === undefined ? {} : { as }), ...extra, ...empty };
154
+ }
155
+ }
156
+ }
157
+ const DESKTOP_ACTIONS = ['open', 'click', 'drag', 'type', 'press', 'scroll', 'wait'];
158
+ const DIRECTIONS = ['up', 'down', 'left', 'right'];
159
+ function coordinate(value, path) {
160
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 4000 ? value : fail(path, '应该是截图上的像素(0 到 4000 的数)');
161
+ }
162
+ /** Seconds held, checked as her `desktop` checks them; absent for a plain press. */
163
+ function held(value, path) {
164
+ if (value === undefined)
165
+ return {};
166
+ try {
167
+ holdMs(value);
168
+ }
169
+ catch (error) {
170
+ fail(path, error instanceof Error ? error.message : String(error));
171
+ }
172
+ return { hold: value };
173
+ }
174
+ /** Both x and y or neither: half a point would land somewhere she never chose. */
175
+ function optionalPoint(input, path) {
176
+ if (input.x === undefined && input.y === undefined)
177
+ return {};
178
+ return { x: coordinate(input.x, `${path}.x`), y: coordinate(input.y, `${path}.y`) };
179
+ }
180
+ function desktopStep(value, path, known) {
181
+ const input = record(value, path);
182
+ const actions = DESKTOP_ACTIONS.filter(action => action in input);
183
+ if (actions.length !== 1)
184
+ return fail(path, `每一步只能有一个动作(${DESKTOP_ACTIONS.join('、')})`);
185
+ const action = actions[0];
186
+ const canGoOut = action === 'click' || action === 'drag' || action === 'type' || action === 'press';
187
+ for (const key of Object.keys(input))
188
+ if (key !== action && !(canGoOut && key === 'outward') && !(action === 'press' && key === 'hold'))
189
+ fail(path, `${action} 这一步不认识 ${key}`);
190
+ const outward = flag(input.outward, `${path}.outward`), extra = outward === undefined ? {} : { outward };
191
+ switch (action) {
192
+ case 'open': return { open: text(input.open, `${path}.open`, 200, known) };
193
+ case 'click': {
194
+ const body = record(input.click, `${path}.click`);
195
+ only(body, ['x', 'y', 'double', 'right', 'hold'], `${path}.click`);
196
+ const double = flag(body.double, `${path}.click.double`), right = flag(body.right, `${path}.click.right`);
197
+ return { click: { x: coordinate(body.x, `${path}.click.x`), y: coordinate(body.y, `${path}.click.y`), ...(double ? { double } : {}), ...(right ? { right } : {}), ...held(body.hold, `${path}.click.hold`) }, ...extra };
198
+ }
199
+ case 'drag': {
200
+ const body = record(input.drag, `${path}.drag`);
201
+ only(body, ['x', 'y', 'x2', 'y2', 'right', 'hold'], `${path}.drag`);
202
+ const right = flag(body.right, `${path}.drag.right`);
203
+ return { drag: { x: coordinate(body.x, `${path}.drag.x`), y: coordinate(body.y, `${path}.drag.y`), x2: coordinate(body.x2, `${path}.drag.x2`), y2: coordinate(body.y2, `${path}.drag.y2`), ...(right ? { right } : {}), ...held(body.hold, `${path}.drag.hold`) }, ...extra };
204
+ }
205
+ case 'type': {
206
+ const body = record(input.type, `${path}.type`);
207
+ only(body, ['text', 'x', 'y'], `${path}.type`);
208
+ return { type: { text: text(body.text, `${path}.type.text`, 2000, known), ...optionalPoint(body, `${path}.type`) }, ...extra };
209
+ }
210
+ case 'press': {
211
+ const key = text(input.press, `${path}.press`, 40);
212
+ try {
213
+ desktopKey(key);
214
+ }
215
+ catch (error) {
216
+ fail(`${path}.press`, error instanceof Error ? error.message : String(error));
217
+ }
218
+ return { press: key, ...held(input.hold, `${path}.hold`), ...extra };
219
+ }
220
+ case 'scroll': {
221
+ const body = record(input.scroll, `${path}.scroll`);
222
+ only(body, ['direction', 'x', 'y'], `${path}.scroll`);
223
+ if (!DIRECTIONS.includes(body.direction))
224
+ fail(`${path}.scroll.direction`, `应该是 ${DIRECTIONS.join('、')}`);
225
+ return { scroll: { direction: body.direction, ...optionalPoint(body, `${path}.scroll`) } };
226
+ }
227
+ case 'wait': {
228
+ const body = record(input.wait, `${path}.wait`);
229
+ only(body, ['seconds'], `${path}.wait`);
230
+ if (typeof body.seconds !== 'number' || !Number.isFinite(body.seconds) || body.seconds <= 0 || body.seconds > 60)
231
+ fail(`${path}.wait.seconds`, '桌面上只能等几秒:大于 0、不超过 60');
232
+ return { wait: { seconds: body.seconds } };
233
+ }
234
+ }
235
+ }
236
+ function params(value) {
237
+ const input = record(value ?? {}, 'params');
238
+ const out = {};
239
+ for (const [name, raw] of Object.entries(input)) {
240
+ identifier(name, 'params', '参数名');
241
+ const param = record(raw, `params.${name}`);
242
+ only(param, ['type', 'required', 'description'], `params.${name}`);
243
+ if (!['string', 'number', 'boolean'].includes(param.type))
244
+ fail(`params.${name}.type`, '应该是 string、number 或 boolean');
245
+ const required = flag(param.required, `params.${name}.required`), description = optionalText(param.description, `params.${name}.description`);
246
+ out[name] = { type: param.type, ...(required === undefined ? {} : { required }), ...(description === undefined ? {} : { description }) };
247
+ }
248
+ return out;
249
+ }
250
+ function messages(value, known) {
251
+ const input = record(value, 'messages');
252
+ only(input, ['channel', 'accountId', 'conversationType', 'conversationId', 'messageId', 'speakerId', 'speakerName', 'conversationName', 'content', 'occurredAt', 'outgoing'], 'messages');
253
+ const channel = text(input.channel, 'messages.channel', 40);
254
+ if (!/^[a-z][a-z0-9-]*$/.test(channel))
255
+ fail('messages.channel', '只能用小写字母、数字和连字符,例如 bilibili');
256
+ if (input.conversationType !== 'private' && input.conversationType !== 'group')
257
+ fail('messages.conversationType', '应该是 private 或 group');
258
+ const out = {
259
+ channel, conversationType: input.conversationType,
260
+ accountId: text(input.accountId, 'messages.accountId', MAX_TEXT, known), conversationId: text(input.conversationId, 'messages.conversationId', MAX_TEXT, known),
261
+ messageId: text(input.messageId, 'messages.messageId', MAX_TEXT, known), speakerId: text(input.speakerId, 'messages.speakerId', MAX_TEXT, known),
262
+ content: text(input.content, 'messages.content', MAX_TEXT, known),
263
+ };
264
+ for (const key of ['speakerName', 'conversationName', 'occurredAt', 'outgoing']) {
265
+ const field = optionalText(input[key], `messages.${key}`, known);
266
+ if (field !== undefined)
267
+ out[key] = field;
268
+ }
269
+ return out;
270
+ }
271
+ export const procedurePath = (procedure) => `${procedure.category}/${procedure.name}`;
272
+ /** A desktop step right after input that opens the window it needs: by hand there was time between them, in a replay none. */
273
+ export const isOpenTooSoon = (steps, index) => index > 0 && 'open' in steps[index] && !('wait' in steps[index - 1]) && !('open' in steps[index - 1]);
274
+ /**
275
+ * What a saved desktop operation is likely to trip on, said when she saves it rather than refused: she may know
276
+ * better, and she learns it either way. A page operation has its own waits and checks.
277
+ */
278
+ export function desktopAdvice(procedure) {
279
+ if (procedure.where === undefined)
280
+ return [];
281
+ const advice = procedure.steps.flatMap((step, index) => isOpenTooSoon(procedure.steps, index) && 'open' in step
282
+ ? [`第 ${index + 1} 步 open「${step.open}」紧跟在上一步后面,回放时中间不停;手动做时这个窗口是过一会儿才出来的,要的话在中间加 {"wait":{"seconds":1}}。`] : []);
283
+ if (!procedure.steps.some(step => 'outward' in step && step.outward))
284
+ advice.push('没有一步标 outward:会把东西发出去的那一步(发送、发表)要标 "outward": true,没跑通时才知道可能已经发出去了。');
285
+ return advice;
286
+ }
287
+ export function entryName(value, path) {
288
+ if (typeof value !== 'string' || !ENTRY_NAME.test(value) || value === GUIDE_NAME)
289
+ return fail(path, `只能用文字、数字、下划线和连字符,1 到 40 个字,不能是「${GUIDE_NAME}」`);
290
+ return value;
291
+ }
292
+ /**
293
+ * Her tool file, checked through: a mistake is refused with where it is, so nothing half-valid is ever saved or run.
294
+ * `category` is the folder the file sits in, used when the file does not say.
295
+ */
296
+ export function parseProcedure(value, category = UNSORTED) {
297
+ const input = record(value, '工具');
298
+ only(input, ['name', 'category', 'description', 'params', 'where', 'steps', 'onAlarm', 'summary', 'messages'], '工具');
299
+ const name = entryName(input.name, 'name');
300
+ const own = input.category === undefined ? category : entryName(input.category, 'category');
301
+ const declared = params(input.params);
302
+ const known = new Set(Object.keys(declared));
303
+ if (!Array.isArray(input.steps) || !input.steps.length || input.steps.length > MAX_STEPS)
304
+ fail('steps', `要有 1 到 ${MAX_STEPS} 步`);
305
+ if (input.where !== undefined && input.where !== 'desktop' && input.where !== 'screen')
306
+ fail('where', '只能是 desktop(后台模式走通的)或 screen(前台模式走通的);网页上的不写');
307
+ if (input.where === 'desktop' || input.where === 'screen') {
308
+ // Nothing on the desktop can be read back, and nothing there may run unseen before an alarm.
309
+ for (const key of ['onAlarm', 'summary', 'messages'])
310
+ if (input[key] !== undefined)
311
+ fail(key, '桌面上的操作不能用');
312
+ const steps = input.steps.map((item, index) => desktopStep(item, `steps[${index}]`, known));
313
+ return { name, category: own, description: text(input.description, 'description'), params: declared, where: input.where, steps };
314
+ }
315
+ const taken = new Set([...known, 'count']);
316
+ const steps = input.steps.map((item, index) => step(item, `steps[${index}]`, known, taken));
317
+ const onAlarm = flag(input.onAlarm, 'onAlarm');
318
+ if (onAlarm && Object.values(declared).some(param => param.required))
319
+ fail('onAlarm', '闹钟前自动跑的工具不能有必填参数');
320
+ if (onAlarm && steps.some(item => 'outward' in item && item.outward))
321
+ fail('onAlarm', '闹钟前自动跑的工具不能有向外发出的步骤');
322
+ const fields = new Set([...known, ...steps.flatMap(item => 'extract' in item ? Object.keys(item.extract.fields) : [])]);
323
+ const values = new Set([...known, 'count', ...steps.flatMap(item => 'script' in item && item.as ? [item.as] : [])]);
324
+ if (input.messages !== undefined && !steps.some(item => 'extract' in item))
325
+ fail('messages', '只有带 extract 的工具才能声明消息');
326
+ const summary = optionalText(input.summary, 'summary', values);
327
+ return {
328
+ name, category: own, description: text(input.description, 'description'), params: declared, steps,
329
+ ...(onAlarm === undefined ? {} : { onAlarm }), ...(summary === undefined ? {} : { summary }),
330
+ ...(input.messages === undefined ? {} : { messages: messages(input.messages, fields) }),
331
+ };
332
+ }
@@ -0,0 +1,53 @@
1
+ import { type Faults } from '../../../faults.ts';
2
+ import { type Procedure } from './format.ts';
3
+ import { type KeptVersion } from './run.ts';
4
+ /** `modified` is the file's time: when she last saved it or edited it by hand. */
5
+ export interface StoredProcedure {
6
+ procedure: Procedure;
7
+ path: string;
8
+ file: string;
9
+ modified: number;
10
+ }
11
+ export interface Category {
12
+ name: string;
13
+ guide: string;
14
+ }
15
+ export interface RunNote {
16
+ at: string;
17
+ ok: boolean;
18
+ detail?: string;
19
+ }
20
+ export type ProcedureLibrary = ReturnType<typeof createProcedureLibrary>;
21
+ /**
22
+ * Her operations, one file each in `<world>/procedures/<category>/`, with her own `目录.md` per category. They are hers:
23
+ * the plugin writes a file only when she saves, and keeps what it replaces as `<name>.v<n>.json` (`目录.v<n>.md`), the
24
+ * newest two of them: a run never tries more, and mending often would otherwise fill the folder. She may
25
+ * also edit them by hand; the revision follows the files. Files the development build left flat in `procedures/` are
26
+ * read in place as the category 未分类 and never moved.
27
+ */
28
+ export declare function createProcedureLibrary(dir: string, deps?: {
29
+ faults?: Faults;
30
+ }): {
31
+ dir: string;
32
+ list: () => StoredProcedure[];
33
+ get: (path: string) => Procedure | undefined;
34
+ /** Categories with an operation or a note of hers, by name; `guide` is her `目录.md`, or empty. */
35
+ categories(): Category[];
36
+ /**
37
+ * The versions her operation replaced, newest first, for when the newest fails. One that no longer parses or repeats
38
+ * a newer one is left out: they are fallbacks, and the files stay hers either way.
39
+ */
40
+ kept(path: string): KeptVersion[];
41
+ /** Checks and writes one operation into its category folder; what it replaces stays as the next `.v<n>.json`. */
42
+ save(json: string): {
43
+ procedure: Procedure;
44
+ path: string;
45
+ version: number;
46
+ };
47
+ /** Her note for a category, whole; the one it replaces stays as `目录.v<n>.md`. Returns the new version number. */
48
+ saveGuide(category: string, text: string): number;
49
+ /** For when the module stops: its load faults would otherwise outlive the operations they describe. */
50
+ clearFaults(): void;
51
+ note(path: string, ok: boolean, detail?: string): void;
52
+ lastRun: (path: string) => RunNote | undefined;
53
+ };
@@ -0,0 +1,178 @@
1
+ // src/ecosystem/computer/procedures/library.ts
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { errorText } from "../../../faults.js";
5
+ import { durableWrite } from "../../../life/lifeStore.js";
6
+ import { ENTRY_NAME, entryName, GUIDE_NAME, parseProcedure, procedurePath, ProcedureError, UNSORTED } from "./format.js";
7
+ import { MAX_FALLBACK } from "./run.js";
8
+ const OWN_FILE = /^([^.]+)\.json$/;
9
+ const MAX_GUIDE = 1000;
10
+ const GUIDE_FILE = `${GUIDE_NAME}.md`;
11
+ /** A folder counts as a category only if its name could have been saved as one. */
12
+ const ENTRY_OK = (name) => name !== GUIDE_NAME && ENTRY_NAME.test(name);
13
+ /**
14
+ * Her operations, one file each in `<world>/procedures/<category>/`, with her own `目录.md` per category. They are hers:
15
+ * the plugin writes a file only when she saves, and keeps what it replaces as `<name>.v<n>.json` (`目录.v<n>.md`), the
16
+ * newest two of them: a run never tries more, and mending often would otherwise fill the folder. She may
17
+ * also edit them by hand; the revision follows the files. Files the development build left flat in `procedures/` are
18
+ * read in place as the category 未分类 and never moved.
19
+ */
20
+ export function createProcedureLibrary(dir, deps = {}) {
21
+ const runs = new Map();
22
+ const faulted = new Set();
23
+ let cache;
24
+ // Sorted, so the catalog and the console list her operations the same way on every disk.
25
+ const entries = (at) => { try {
26
+ return readdirSync(at, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
27
+ }
28
+ catch {
29
+ return [];
30
+ } };
31
+ const folders = () => entries(dir).filter(entry => entry.isDirectory() && ENTRY_OK(entry.name)).map(entry => entry.name).sort();
32
+ /** Every operation file with its category; folders first, then the flat files, so a saved one shadows a flat one. */
33
+ const files = () => [
34
+ ...folders().flatMap(category => entries(join(dir, category)).filter(entry => entry.isFile() && OWN_FILE.test(entry.name)).map(entry => ({ category, base: entry.name, file: join(dir, category, entry.name), label: `${category}/${entry.name}` }))),
35
+ ...entries(dir).filter(entry => entry.isFile() && OWN_FILE.test(entry.name)).map(entry => ({ category: UNSORTED, base: entry.name, file: join(dir, entry.name), label: entry.name })),
36
+ ];
37
+ const revision = () => files().flatMap(({ file }) => {
38
+ try {
39
+ const { mtimeMs, size } = statSync(file);
40
+ return [`${file}:${mtimeMs}:${size}`];
41
+ }
42
+ catch {
43
+ return [];
44
+ } // deleted between listing and stat
45
+ }).join('|');
46
+ /** The `<name>.v<n>.<ext>` numbers in a folder, highest first. */
47
+ const keptNumbers = (folder, name, ext) => {
48
+ const pattern = new RegExp(`^${name}\\.v(\\d+)\\.${ext}$`, 'u');
49
+ return entries(folder).map(entry => Number(pattern.exec(entry.name)?.[1] ?? 0)).filter(Boolean).sort((a, b) => b - a);
50
+ };
51
+ /** Writes `file`, first keeping what it replaces as the next version in its folder. Returns the new version number. */
52
+ function replace(folder, name, ext, content) {
53
+ mkdirSync(folder, { recursive: true });
54
+ const file = join(folder, `${name}.${ext}`);
55
+ // Numbering continues after the highest kept version, so a gap or a deleted file never makes a save overwrite one.
56
+ const highest = keptNumbers(folder, name, ext)[0] ?? 0;
57
+ const replaced = existsSync(file);
58
+ if (replaced)
59
+ durableWrite(join(folder, `${name}.v${highest + 1}.${ext}`), readFileSync(file, 'utf8'));
60
+ durableWrite(file, content);
61
+ // Only on a save, and only this name: nothing is tidied that she did not just replace.
62
+ for (const old of keptNumbers(folder, name, ext).slice(MAX_FALLBACK)) {
63
+ const key = `procedure-old:${name}.v${old}.${ext}`;
64
+ try {
65
+ rmSync(join(folder, `${name}.v${old}.${ext}`));
66
+ deps.faults?.clear(key);
67
+ }
68
+ catch (error) {
69
+ deps.faults?.set(key, `旧版本 ${name}.v${old}.${ext} 没能删掉:${errorText(error)}`);
70
+ }
71
+ }
72
+ cache = undefined;
73
+ return highest + (replaced ? 2 : 1);
74
+ }
75
+ function list() {
76
+ const current = revision();
77
+ if (cache?.revision === current)
78
+ return cache.list;
79
+ const out = [], seen = new Set(), paths = new Set();
80
+ for (const { category, base, file, label } of files()) {
81
+ const key = `procedure:${label}`;
82
+ seen.add(key);
83
+ try {
84
+ const procedure = parseProcedure(JSON.parse(readFileSync(file, 'utf8')), category);
85
+ if (`${procedure.name}.json` !== base)
86
+ throw new ProcedureError(`文件名应该是 ${procedure.name}.json`);
87
+ if (procedure.category !== category)
88
+ throw new ProcedureError(`分类应该是 ${category},或者把文件挪进 ${procedure.category} 文件夹`);
89
+ const path = procedurePath(procedure);
90
+ if (!paths.has(path)) {
91
+ paths.add(path);
92
+ out.push({ procedure, path, file, modified: statSync(file).mtimeMs });
93
+ }
94
+ deps.faults?.clear(key);
95
+ faulted.delete(key);
96
+ }
97
+ catch (error) {
98
+ deps.faults?.set(key, `她的操作 ${label} 没能载入:${errorText(error)}`);
99
+ faulted.add(key);
100
+ }
101
+ }
102
+ for (const key of [...faulted])
103
+ if (!seen.has(key)) {
104
+ deps.faults?.clear(key);
105
+ faulted.delete(key);
106
+ }
107
+ cache = { revision: current, list: out };
108
+ return out;
109
+ }
110
+ const find = (path) => list().find(entry => entry.path === path);
111
+ return {
112
+ dir,
113
+ list,
114
+ get: (path) => find(path)?.procedure,
115
+ /** Categories with an operation or a note of hers, by name; `guide` is her `目录.md`, or empty. */
116
+ categories() {
117
+ const names = new Set([...list().map(entry => entry.procedure.category), ...folders().filter(name => existsSync(join(dir, name, GUIDE_FILE)))]);
118
+ return [...names].sort().map(name => {
119
+ const file = join(dir, name, GUIDE_FILE);
120
+ let guide = '';
121
+ try {
122
+ guide = existsSync(file) ? readFileSync(file, 'utf8') : '';
123
+ }
124
+ catch { /* unreadable: shown as no note */ }
125
+ return { name, guide };
126
+ });
127
+ },
128
+ /**
129
+ * The versions her operation replaced, newest first, for when the newest fails. One that no longer parses or repeats
130
+ * a newer one is left out: they are fallbacks, and the files stay hers either way.
131
+ */
132
+ kept(path) {
133
+ const stored = find(path);
134
+ if (!stored)
135
+ return [];
136
+ const folder = dirname(stored.file), name = stored.procedure.name;
137
+ const seen = new Set([JSON.stringify(stored.procedure)]);
138
+ return keptNumbers(folder, name, 'json').flatMap(version => {
139
+ try {
140
+ const procedure = parseProcedure(JSON.parse(readFileSync(join(folder, `${name}.v${version}.json`), 'utf8')), stored.procedure.category);
141
+ const key = JSON.stringify(procedure);
142
+ if (seen.has(key))
143
+ return [];
144
+ seen.add(key);
145
+ return [{ procedure, version }];
146
+ }
147
+ catch {
148
+ return [];
149
+ }
150
+ });
151
+ },
152
+ /** Checks and writes one operation into its category folder; what it replaces stays as the next `.v<n>.json`. */
153
+ save(json) {
154
+ let value;
155
+ try {
156
+ value = JSON.parse(json);
157
+ }
158
+ catch (error) {
159
+ throw new ProcedureError(`JSON 格式不对:${errorText(error)}`);
160
+ }
161
+ const procedure = parseProcedure(value);
162
+ const version = replace(join(dir, procedure.category), procedure.name, 'json', JSON.stringify(procedure, null, 2) + '\n');
163
+ return { procedure, path: procedurePath(procedure), version };
164
+ },
165
+ /** Her note for a category, whole; the one it replaces stays as `目录.v<n>.md`. Returns the new version number. */
166
+ saveGuide(category, text) {
167
+ entryName(category, 'category');
168
+ if (typeof text !== 'string' || !text.trim() || [...text].length > MAX_GUIDE)
169
+ throw new ProcedureError(`说明应该是 1 到 ${MAX_GUIDE} 字`);
170
+ return replace(join(dir, category), GUIDE_NAME, 'md', text);
171
+ },
172
+ /** For when the module stops: its load faults would otherwise outlive the operations they describe. */
173
+ clearFaults() { for (const key of faulted)
174
+ deps.faults?.clear(key); faulted.clear(); cache = undefined; },
175
+ note(path, ok, detail) { runs.set(path, { at: new Date().toISOString(), ok, ...(detail === undefined ? {} : { detail }) }); },
176
+ lastRun: (path) => runs.get(path),
177
+ };
178
+ }
@@ -0,0 +1,80 @@
1
+ import { type Row } from '../browser/page.ts';
2
+ import type { ProcedureLibrary } from './library.ts';
3
+ import type { DesktopInput, DesktopResult } from '../desktop/desktop.ts';
4
+ import { type Condition, type DesktopStep, type ExtractSpec, type Procedure, type Step, type Target } from './format.ts';
5
+ /** What replaying needs from a page; her browser's `Page` is one. */
6
+ export interface Driver {
7
+ open(url: string): Promise<void>;
8
+ click(target: Target): Promise<void>;
9
+ type(target: Target, text: string): Promise<void>;
10
+ press(key: string): Promise<void>;
11
+ wait(condition: Condition, timeoutMs: number, signal?: AbortSignal): Promise<void>;
12
+ has(condition: Condition): Promise<boolean>;
13
+ extract(spec: ExtractSpec): Promise<Row[]>;
14
+ evaluate(script: string, args: Record<string, unknown>): Promise<unknown>;
15
+ brief(): Promise<string>;
16
+ }
17
+ /** What replaying a desktop operation needs: her `desktop` hands, each action answered with a fresh picture. */
18
+ export interface Hands {
19
+ act(input: DesktopInput): Promise<DesktopResult>;
20
+ }
21
+ export type Args = Record<string, string | number | boolean>;
22
+ export type Failure = {
23
+ ok: false;
24
+ step: number;
25
+ action: string;
26
+ error: string;
27
+ outwardDone: boolean;
28
+ page: string;
29
+ };
30
+ export type RunResult = {
31
+ ok: true;
32
+ rows: Row[];
33
+ values: Record<string, unknown>;
34
+ } | Failure;
35
+ /** One of the versions she replaced, kept as `<name>.v<n>.json`. */
36
+ export interface KeptVersion {
37
+ procedure: Procedure;
38
+ version: number;
39
+ }
40
+ /** Which version a run ended on: the newest unless it failed before anything went out and a kept one worked. */
41
+ export interface VersionedRun {
42
+ result: RunResult;
43
+ ran: Procedure;
44
+ fallback?: {
45
+ version: number;
46
+ newest: Failure;
47
+ };
48
+ }
49
+ /** Kept versions tried after the newest fails, so a long repair history cannot make one call run for minutes. */
50
+ export declare const MAX_FALLBACK = 2;
51
+ export declare function checkArgs(procedure: Procedure, input: Record<string, unknown>): Args;
52
+ export declare function describeStep(step: Step | DesktopStep): string;
53
+ /**
54
+ * Replays her steps without the model: the first one that fails stops the run and says where, never retried. Coming up
55
+ * empty is failing too, unless the step allows it, so a broken tool is never read as "nothing new".
56
+ */
57
+ export declare function runProcedure(procedure: Procedure, args: Args, driver: Driver | Hands, signal?: AbortSignal): Promise<RunResult>;
58
+ /**
59
+ * Runs her newest version; when it fails before anything went out, her kept versions newest first, since a site may
60
+ * serve its old and new page side by side and a repair for one must not lose the other. The newest's failure is the
61
+ * one reported when none works. A kept version whose parameters no longer fit the call is skipped.
62
+ */
63
+ export declare function runVersions(newest: Procedure, kept: KeptVersion[], input: Record<string, unknown>, driver: Driver | Hands, signal?: AbortSignal): Promise<VersionedRun>;
64
+ /** Told after a result that came from a kept version, so she knows her newest one is broken. */
65
+ export declare const fallbackText: ({ version, newest }: NonNullable<VersionedRun["fallback"]>) => string;
66
+ /** Said at the moment it breaks, when the task is still in front of her: doing it by hand is how the new version gets made. */
67
+ export declare const REPAIR_NOW = "\u73B0\u5728\u5C31\u4FEE\uFF1A\u5148\u7528 page_* \u6216 desktop \u628A\u8FD9\u4EF6\u4E8B\u505A\u5B8C\uFF0C\u518D\u628A\u8D70\u901A\u7684\u6B65\u9AA4\u7528\u539F\u6765\u7684\u540D\u5B57 procedure_save \u6210\u65B0\u7248\uFF08\u4E0D\u53E6\u8D77\u4E00\u4E2A\u65B0\u7684\uFF09\uFF0C\u5B58\u5B8C\u8DD1\u4E00\u6B21\u786E\u8BA4\u3002";
68
+ export declare function failureText(path: string, result: Failure): string;
69
+ /** Cuts by characters, not UTF-16 units, so an emoji is never split. */
70
+ export declare const cut: (text: string, max: number) => string;
71
+ /** What her tool hands back: the rows of its last extract and the values its scripts kept, cut to 2000 characters. */
72
+ export declare function resultText(result: Extract<RunResult, {
73
+ ok: true;
74
+ }>): string;
75
+ /** One line after her alarm: the tool's own summary, or its result; a failure is said as a failure, never as nothing. */
76
+ export declare function summaryLine(procedure: Procedure, result: RunResult): string;
77
+ /** The one place a run, or the error that cut it off, becomes the note the catalog and the console show. */
78
+ export declare function noteRun(library: Pick<ProcedureLibrary, 'note'>, path: string, outcome: VersionedRun | {
79
+ thrown: unknown;
80
+ }): void;