dsh-world 0.7.5 → 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 (115) hide show
  1. package/CHANGELOG.md +541 -446
  2. package/CONTRIBUTING.md +174 -163
  3. package/INSTALL.md +314 -314
  4. package/NOTES.md +98 -5
  5. package/README.md +332 -258
  6. package/client/index.js +1126 -986
  7. package/lib/compaction.d.ts +7 -1
  8. package/lib/compaction.js +8 -3
  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 +8 -1
  56. package/lib/ecosystem/qq-native/images.js +34 -15
  57. package/lib/ecosystem/qq-native/index.js +5 -5
  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 +6 -0
  64. package/lib/ecosystem/wechat/index.js +3 -1
  65. package/lib/ecosystem/wechat/presence.d.ts +5 -1
  66. package/lib/ecosystem/wechat/presence.js +22 -13
  67. package/lib/ecosystem/wechat/reading.d.ts +1 -1
  68. package/lib/ecosystem/wechat/reading.js +2 -2
  69. package/lib/elsewhere.d.ts +34 -0
  70. package/lib/elsewhere.js +40 -0
  71. package/lib/history.d.ts +5 -0
  72. package/lib/history.js +7 -1
  73. package/lib/hostContract.d.ts +6 -0
  74. package/lib/images.d.ts +30 -0
  75. package/lib/images.js +101 -0
  76. package/lib/index.d.ts +4 -0
  77. package/lib/index.js +98 -6
  78. package/lib/life/photoTools.js +4 -15
  79. package/lib/life/runtime.d.ts +12 -2
  80. package/lib/life/runtime.js +93 -12
  81. package/lib/life/toolRegistry.d.ts +9 -3
  82. package/lib/life/toolRegistry.js +46 -27
  83. package/lib/life/turnCost.d.ts +16 -0
  84. package/lib/life/turnCost.js +44 -0
  85. package/lib/life/types.d.ts +17 -0
  86. package/lib/memoryTools.d.ts +4 -2
  87. package/lib/memoryTools.js +25 -5
  88. package/lib/mood.d.ts +5 -1
  89. package/lib/mood.js +25 -8
  90. package/lib/promptSection.d.ts +3 -0
  91. package/lib/promptSection.js +29 -42
  92. package/lib/runtime.js +44 -17
  93. package/lib/sessionNews.d.ts +17 -0
  94. package/lib/sessionNews.js +55 -0
  95. package/lib/store.d.ts +6 -0
  96. package/lib/store.js +17 -3
  97. package/lib/types.d.ts +4 -0
  98. package/lib/worldAdd.d.ts +9 -0
  99. package/lib/worldAdd.js +39 -0
  100. package/lib/worldPrompt.d.ts +3 -2
  101. package/lib/worldPrompt.js +3 -2
  102. package/lib/worldRoutes.d.ts +5 -2
  103. package/lib/worldRoutes.js +29 -4
  104. package/lib/worldSwitch.d.ts +8 -2
  105. package/lib/worldSwitch.js +11 -5
  106. package/package.json +132 -129
  107. package/src/ecosystem/README.md +2 -1
  108. package/src/ecosystem/computer/NOTICE.md +27 -0
  109. package/src/ecosystem/computer/README.md +244 -0
  110. package/src/ecosystem/computer/desktop/win32.ps1 +858 -0
  111. package/src/ecosystem/wechat/windows/README.md +4 -2
  112. package/src/ecosystem/wechat/windows/engine/NOTICE.md +6 -0
  113. package/src/ecosystem/wechat/windows/engine/profiles.json +28 -0
  114. package/templates/world-prompt-memory.md +10 -10
  115. package/templates/world-prompt.md +65 -65
@@ -0,0 +1,75 @@
1
+ // src/ecosystem/computer/procedures/catalog.ts
2
+ import { dirname, join } from 'node:path';
3
+ import { cut } from "./run.js";
4
+ const GUIDE_SHOWN = 500;
5
+ const START_HINT = '用 page_* 自己摸索,走通了用 procedure_save 存进一个分类,再用 procedure_note 写这一类的说明。';
6
+ /** Two-letter overlap a misspelt word still needs, so bilbili finds bilibili but a stray shared letter finds nothing. */
7
+ const SIMILAR = 0.6;
8
+ /**
9
+ * The words in a text, lower-cased; one letter alone names nothing. Chinese runs stay whole: a word like 微信 has no
10
+ * spaces around it, so a run of hers is matched by containment below, not split.
11
+ */
12
+ const words = (text) => text.toLowerCase().split(/[\s,,、。.;;::/|()()「」【】!!??]+/u).filter(word => [...word].length > 1);
13
+ const pairs = (word) => { const chars = [...word]; return new Set(chars.slice(1).map((ch, i) => chars[i] + ch)); };
14
+ /** How much of `a` and `b` is the same: the shorter one's length when one holds the other, else by shared letter pairs. */
15
+ function closeness(a, b) {
16
+ const shorter = Math.min([...a].length, [...b].length);
17
+ if (a.includes(b) || b.includes(a))
18
+ return shorter;
19
+ const x = pairs(a), y = pairs(b);
20
+ const dice = 2 * [...x].filter(pair => y.has(pair)).length / (x.size + y.size);
21
+ return dice >= SIMILAR ? dice * shorter : 0;
22
+ }
23
+ /**
24
+ * How well `target` names the object `haystack` describes: each word of hers counts by its closest word there.
25
+ * Word against word, never letters scattered through her note, or 消息 in 消息框 would pull in 发送消息.
26
+ */
27
+ function score(target, haystack) {
28
+ const hay = words(haystack);
29
+ return words(target).reduce((sum, word) => sum + Math.max(0, ...hay.map(other => closeness(word, other))), 0);
30
+ }
31
+ function groups(library) {
32
+ const all = library.list();
33
+ // Newest first: what she saved or fixed last is likeliest what she is doing now.
34
+ const newest = (a, b) => b.modified - a.modified;
35
+ return library.categories().map(({ name, guide }) => ({ name, guide, operations: all.filter(entry => entry.procedure.category === name).sort(newest) }));
36
+ }
37
+ /**
38
+ * A category as she needs it to pick an operation: her note, the operation names and the folder. The names are short
39
+ * and say what each does; parameters and steps are in the files, which she reads only for the one she picks.
40
+ */
41
+ function section(library, group) {
42
+ const lines = [group.name];
43
+ if (group.guide.trim())
44
+ lines.push(cut(group.guide.trim(), GUIDE_SHOWN));
45
+ lines.push(group.operations.length ? `操作:${group.operations.map(({ procedure }) => procedure.name).join('、')}` : '(这一类还没有操作)');
46
+ // Files the development build left flat sit in the root, not in the 未分类 folder.
47
+ const folders = group.operations.length ? [...new Set(group.operations.map(({ file }) => dirname(file)))] : [join(library.dir, group.name)];
48
+ lines.push(`文件在 ${folders.join('、')},一个操作一个 <名字>.json;要看参数和步骤就读它。`);
49
+ return `${lines.join('\n')}\n\n用 procedure_run("${group.name}/操作名", 参数) 直接跑;没有合适的就用 page_* 自己做,走通了 procedure_save 存进来。`;
50
+ }
51
+ /**
52
+ * What `computer_use` answers. A target names the thing she is about to use, a program or a site, so it is matched
53
+ * against the category name and her note only: operations are named by what they do, and the same 发送消息 under
54
+ * several categories would pull in the lists of things she is not using. One category comes back, never a mix.
55
+ */
56
+ export function catalogText(library, target) {
57
+ const all = groups(library);
58
+ if (!target?.trim()) {
59
+ if (!all.length)
60
+ return `还没有学会的操作。${START_HINT}`;
61
+ return `学会的操作:${all.map(group => `${group.name}(${group.operations.length} 个)`).join('、')}。要用某一类,用 computer_use 说出它的名字。`;
62
+ }
63
+ const named = target.trim();
64
+ const ranked = all.map(group => ({ group, score: score(named, `${group.name} ${group.guide}`) })).filter(entry => entry.score > 0)
65
+ .sort((a, b) => b.score - a.score);
66
+ if (!ranked.length) {
67
+ if (!all.length)
68
+ return `还没有学会的操作。${START_HINT}`;
69
+ return `没有对得上「${named}」的分类(已有:${all.map(group => group.name).join('、')})。是其中一类的话,用 procedure_note 在它的说明里写上这个叫法;不是就${START_HINT}`;
70
+ }
71
+ const best = ranked.filter(entry => entry.score === ranked[0].score);
72
+ if (best.length > 1)
73
+ return `「${named}」对得上不止一类:${best.map(({ group }) => group.name).join('、')}。用 computer_use 说出其中一类的名字。`;
74
+ return section(library, ranked[0].group);
75
+ }
@@ -0,0 +1,167 @@
1
+ /** Finds an element by what a person sees: its role and name, text it shows, or a CSS selector; `nth` picks among several. */
2
+ export interface Anchor {
3
+ role?: string;
4
+ name?: string;
5
+ text?: string;
6
+ css?: string;
7
+ nth?: number;
8
+ }
9
+ export interface Condition {
10
+ text?: string;
11
+ anchor?: Anchor;
12
+ url?: string;
13
+ }
14
+ export interface ExtractSpec {
15
+ list: Anchor;
16
+ fields: Record<string, Anchor & {
17
+ attr?: string;
18
+ }>;
19
+ limit?: number;
20
+ }
21
+ export type Target = {
22
+ ref: number;
23
+ } | {
24
+ anchor: Anchor;
25
+ };
26
+ export type Step = {
27
+ open: string;
28
+ } | {
29
+ click: Anchor;
30
+ outward?: boolean;
31
+ } | {
32
+ type: {
33
+ into: Anchor;
34
+ text: string;
35
+ };
36
+ outward?: boolean;
37
+ } | {
38
+ press: string;
39
+ outward?: boolean;
40
+ } | {
41
+ wait: Condition & {
42
+ seconds?: number;
43
+ };
44
+ } | {
45
+ check: Condition;
46
+ } | {
47
+ extract: ExtractSpec;
48
+ allowEmpty?: boolean;
49
+ } | {
50
+ script: string;
51
+ as?: string;
52
+ outward?: boolean;
53
+ allowEmpty?: boolean;
54
+ };
55
+ export interface Param {
56
+ type: 'string' | 'number' | 'boolean';
57
+ required?: boolean;
58
+ description?: string;
59
+ }
60
+ /** How the rows of the last `extract` become archive records; every value is a template over the row and the arguments. */
61
+ export interface MessageMap {
62
+ channel: string;
63
+ accountId: string;
64
+ conversationType: 'private' | 'group';
65
+ conversationId: string;
66
+ messageId: string;
67
+ speakerId: string;
68
+ speakerName?: string;
69
+ conversationName?: string;
70
+ content: string;
71
+ occurredAt?: string;
72
+ /** Evaluates to `true` for her own messages. */
73
+ outgoing?: string;
74
+ }
75
+ /** A pixel on the screenshot `desktop` gives of the current window (long edge about 1280), so it follows the window's size. */
76
+ export interface Point {
77
+ x: number;
78
+ y: number;
79
+ }
80
+ export type Direction = 'up' | 'down' | 'left' | 'right';
81
+ /** Steps on the partner's computer, the `desktop` actions written down: nothing to read there, only pictures. */
82
+ export type DesktopStep = {
83
+ open: string;
84
+ } | {
85
+ click: Point & {
86
+ double?: boolean;
87
+ right?: boolean;
88
+ hold?: number;
89
+ };
90
+ outward?: boolean;
91
+ } | {
92
+ drag: Point & {
93
+ x2: number;
94
+ y2: number;
95
+ right?: boolean;
96
+ hold?: number;
97
+ };
98
+ outward?: boolean;
99
+ } | {
100
+ type: {
101
+ text: string;
102
+ } & Partial<Point>;
103
+ outward?: boolean;
104
+ } | {
105
+ press: string;
106
+ hold?: number;
107
+ outward?: boolean;
108
+ } | {
109
+ scroll: {
110
+ direction: Direction;
111
+ } & Partial<Point>;
112
+ } | {
113
+ wait: {
114
+ seconds: number;
115
+ };
116
+ };
117
+ interface Common {
118
+ name: string;
119
+ category: string;
120
+ description: string;
121
+ params: Record<string, Param>;
122
+ }
123
+ export interface PageProcedure extends Common {
124
+ where?: undefined;
125
+ steps: Step[];
126
+ onAlarm?: boolean;
127
+ summary?: string;
128
+ messages?: MessageMap;
129
+ }
130
+ /** `desktop` is replayed in background mode (one window), `screen` in foreground mode (the whole screen, real input). */
131
+ export type Computer = 'desktop' | 'screen';
132
+ export interface DesktopProcedure extends Common {
133
+ where: Computer;
134
+ steps: DesktopStep[];
135
+ onAlarm?: undefined;
136
+ summary?: undefined;
137
+ messages?: undefined;
138
+ }
139
+ export type Procedure = PageProcedure | DesktopProcedure;
140
+ export declare class ProcedureError extends Error {
141
+ name: string;
142
+ }
143
+ /** A category or operation name is also a folder or file name, so it holds no path characters. */
144
+ export declare const ENTRY_NAME: RegExp;
145
+ /** Her own notes for a category live in `<category>/目录.md`, so no operation may take that name. */
146
+ export declare const GUIDE_NAME = "\u76EE\u5F55";
147
+ /** Where files the development build left flat in `procedures/` belong. */
148
+ export declare const UNSORTED = "\u672A\u5206\u7C7B";
149
+ export declare const substitute: (text: string, values: Record<string, unknown>) => string;
150
+ /** Her browser reads the web, not the computer: no file:, chrome:, edge:, javascript: or data: pages. */
151
+ export declare const WEB_ONLY = "\u53EA\u80FD\u6253\u5F00 http \u6216 https \u5730\u5740";
152
+ export declare const isWebAddress: (url: string) => boolean;
153
+ export declare const procedurePath: (procedure: Pick<Procedure, "category" | "name">) => string;
154
+ /** A desktop step right after input that opens the window it needs: by hand there was time between them, in a replay none. */
155
+ export declare const isOpenTooSoon: (steps: DesktopStep[], index: number) => boolean;
156
+ /**
157
+ * What a saved desktop operation is likely to trip on, said when she saves it rather than refused: she may know
158
+ * better, and she learns it either way. A page operation has its own waits and checks.
159
+ */
160
+ export declare function desktopAdvice(procedure: Procedure): string[];
161
+ export declare function entryName(value: unknown, path: string): string;
162
+ /**
163
+ * Her tool file, checked through: a mistake is refused with where it is, so nothing half-valid is ever saved or run.
164
+ * `category` is the folder the file sits in, used when the file does not say.
165
+ */
166
+ export declare function parseProcedure(value: unknown, category?: string): Procedure;
167
+ export {};
@@ -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
+ };