@celljs/ta-reflex 0.0.0-stage → 4.37.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.
- package/README.en.md +28 -0
- package/README.md +27 -2
- package/extension/index.mjs +976 -0
- package/host/index.mjs +1942 -0
- package/package.json +72 -4
- package/web/index.js +2232 -0
package/web/index.js
ADDED
|
@@ -0,0 +1,2232 @@
|
|
|
1
|
+
// ../ta-protocol/esm/common/language.js
|
|
2
|
+
var TaLanguageUtil;
|
|
3
|
+
(function(TaLanguageUtil2) {
|
|
4
|
+
TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
|
|
5
|
+
TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
|
|
6
|
+
function of(tag) {
|
|
7
|
+
const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
|
|
8
|
+
if (/^zh(\b|-)/.test(said)) {
|
|
9
|
+
return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
|
|
10
|
+
}
|
|
11
|
+
return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
|
|
12
|
+
}
|
|
13
|
+
TaLanguageUtil2.of = of;
|
|
14
|
+
function server(env = typeof process === "undefined" ? {} : process.env) {
|
|
15
|
+
return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
|
|
16
|
+
}
|
|
17
|
+
TaLanguageUtil2.server = server;
|
|
18
|
+
function pick(language, words) {
|
|
19
|
+
return words[of(language)];
|
|
20
|
+
}
|
|
21
|
+
TaLanguageUtil2.pick = pick;
|
|
22
|
+
function say(words) {
|
|
23
|
+
return words[server()];
|
|
24
|
+
}
|
|
25
|
+
TaLanguageUtil2.say = say;
|
|
26
|
+
function chinese(language) {
|
|
27
|
+
return of(language).startsWith("zh");
|
|
28
|
+
}
|
|
29
|
+
TaLanguageUtil2.chinese = chinese;
|
|
30
|
+
function cjk(language) {
|
|
31
|
+
return of(language) !== "en-US";
|
|
32
|
+
}
|
|
33
|
+
TaLanguageUtil2.cjk = cjk;
|
|
34
|
+
function list(language, items) {
|
|
35
|
+
return items.join(cjk(language) ? "、" : ", ");
|
|
36
|
+
}
|
|
37
|
+
TaLanguageUtil2.list = list;
|
|
38
|
+
})(TaLanguageUtil || (TaLanguageUtil = {}));
|
|
39
|
+
|
|
40
|
+
// web-src/i18n.ts
|
|
41
|
+
var EN = {
|
|
42
|
+
section: "Live hands",
|
|
43
|
+
aim: "Aim",
|
|
44
|
+
aimHint: "Ta may point at what moves and press on it by itself, in a game and elsewhere. Off: it only follows and watches.",
|
|
45
|
+
code: "Ta's own programs",
|
|
46
|
+
codeHint: "Ta may write a little program for what it works live; it runs on this page with no network. Off: only those that come with Ta.",
|
|
47
|
+
decide: "Decision models",
|
|
48
|
+
decideHint: "Small steps (which button, is it done) are chosen by a decision model, in a fraction of a second; Ta is asked only when it is unsure. First one of yours on this computer (Ollama, LM Studio), then the one of Settings → Local models, then those added below. Off: Ta decides each step.",
|
|
49
|
+
decideOnline: "Decision models not on this computer",
|
|
50
|
+
decideOnlineHint: "Those added below that are on the internet or another computer may be asked too; they read what the page shows. Off: only those on this computer.",
|
|
51
|
+
remotes: "Decision models added",
|
|
52
|
+
remotesHint: "By address: a service of the Decisions API (Jev), or any OpenAI-compatible one (vLLM, llama.cpp on another computer). Its key is kept in the vault.",
|
|
53
|
+
remoteUrl: "Address, https://…/v1",
|
|
54
|
+
remoteKey: "Key (if it needs one)",
|
|
55
|
+
remoteModel: "Model (if it needs one)",
|
|
56
|
+
remoteAdd: "Add",
|
|
57
|
+
remoteRemove: "Remove",
|
|
58
|
+
remoteNone: "None added yet.",
|
|
59
|
+
remoteHere: "this computer",
|
|
60
|
+
remoteOff: "not asked while the switch above is off",
|
|
61
|
+
reflex_targets: "Look for what can be worked live",
|
|
62
|
+
reflex_do: "Do it live",
|
|
63
|
+
reflex_start: "Work live",
|
|
64
|
+
reflex_intent: "Steer the live run",
|
|
65
|
+
reflex_program: "Change the live program",
|
|
66
|
+
reflex_batch: "Do steps at once",
|
|
67
|
+
reflex_stop: "Stop working live",
|
|
68
|
+
working: "Ta is working {title} live",
|
|
69
|
+
workingFor: "{who} is working {title} live",
|
|
70
|
+
stop: "Stop",
|
|
71
|
+
told: "{title}: {what}",
|
|
72
|
+
round_over: "the round is over",
|
|
73
|
+
intent_expired: "waits for what to do next",
|
|
74
|
+
program_failed: "its program failed",
|
|
75
|
+
target_gone: "it is gone",
|
|
76
|
+
stopped: "stopped",
|
|
77
|
+
seen: "what it watched for showed",
|
|
78
|
+
gone: "what it watched went",
|
|
79
|
+
lost: "lost what it followed"
|
|
80
|
+
};
|
|
81
|
+
var ZH = {
|
|
82
|
+
section: "实时操作",
|
|
83
|
+
aim: "瞄准",
|
|
84
|
+
aimHint: "Ta 可以自己对准移动的目标并按下,游戏里或别处都可以。关掉后只跟随和等待。",
|
|
85
|
+
code: "Ta 自己写的程序",
|
|
86
|
+
codeHint: "Ta 可以为实时操作写一个小程序,在本页运行、不能联网。关掉后只用 Ta 自带的程序。",
|
|
87
|
+
decide: "决策模型",
|
|
88
|
+
decideHint: "点哪个按钮、做完没有这类小判断交给决策模型,零点几秒就答;拿不准时才问 Ta。先用这台电脑上已有的(Ollama、LM Studio),再用「本机模型」里下载的,最后是下面添加的。关掉后每一步都由 Ta 决定。",
|
|
89
|
+
decideOnline: "不在本机的决策模型",
|
|
90
|
+
decideOnlineHint: "下面添加的、在网上或另一台电脑上的决策模型也可以问,它们会读到页面上的内容。关掉后只用本机的。",
|
|
91
|
+
remotes: "添加的决策模型",
|
|
92
|
+
remotesHint: "按地址添加:决策接口(Jev)的服务,或任何 OpenAI 兼容的服务(vLLM、另一台电脑上的 llama.cpp)。密钥存在保险箱里。",
|
|
93
|
+
remoteUrl: "地址,https://…/v1",
|
|
94
|
+
remoteKey: "密钥(需要时填)",
|
|
95
|
+
remoteModel: "模型(需要时填)",
|
|
96
|
+
remoteAdd: "添加",
|
|
97
|
+
remoteRemove: "移除",
|
|
98
|
+
remoteNone: "还没有添加。",
|
|
99
|
+
remoteHere: "本机",
|
|
100
|
+
remoteOff: "上面的开关关着,不会用它",
|
|
101
|
+
reflex_targets: "查看能实时操作的对象",
|
|
102
|
+
reflex_do: "实时完成任务",
|
|
103
|
+
reflex_start: "开始实时操作",
|
|
104
|
+
reflex_intent: "调整实时操作",
|
|
105
|
+
reflex_program: "更换实时操作的程序",
|
|
106
|
+
reflex_batch: "连续操作",
|
|
107
|
+
reflex_stop: "停止实时操作",
|
|
108
|
+
working: "Ta 正在实时操作 {title}",
|
|
109
|
+
workingFor: "{who} 正在实时操作 {title}",
|
|
110
|
+
stop: "停止",
|
|
111
|
+
told: "{title}:{what}",
|
|
112
|
+
round_over: "一局结束",
|
|
113
|
+
intent_expired: "等 Ta 给下一步",
|
|
114
|
+
program_failed: "程序出错",
|
|
115
|
+
target_gone: "对象不见了",
|
|
116
|
+
stopped: "已停止",
|
|
117
|
+
seen: "等的东西出现了",
|
|
118
|
+
gone: "等的东西不见了",
|
|
119
|
+
lost: "跟丢了"
|
|
120
|
+
};
|
|
121
|
+
var ZH_TW = {
|
|
122
|
+
section: "即時操作",
|
|
123
|
+
aim: "瞄準",
|
|
124
|
+
aimHint: "Ta 可以自己對準移動的目標並按下,遊戲裡或別處都可以。關掉後只跟隨和等待。",
|
|
125
|
+
code: "Ta 自己寫的程式",
|
|
126
|
+
codeHint: "Ta 可以為即時操作寫一個小程式,在本頁執行、不能連網。關掉後只用 Ta 內建的程式。",
|
|
127
|
+
decide: "決策模型",
|
|
128
|
+
decideHint: "點哪個按鈕、做完沒有這類小判斷交給決策模型,零點幾秒就答;拿不準時才問 Ta。先用這台電腦上已有的(Ollama、LM Studio),再用「本機模型」裡下載的,最後是下面新增的。關掉後每一步都由 Ta 決定。",
|
|
129
|
+
decideOnline: "不在本機的決策模型",
|
|
130
|
+
decideOnlineHint: "下面新增的、在網路上或另一台電腦上的決策模型也可以問,它們會讀到頁面上的內容。關掉後只用本機的。",
|
|
131
|
+
remotes: "新增的決策模型",
|
|
132
|
+
remotesHint: "按位址新增:決策介面(Jev)的服務,或任何 OpenAI 相容的服務(vLLM、另一台電腦上的 llama.cpp)。金鑰存在保險箱裡。",
|
|
133
|
+
remoteUrl: "位址,https://…/v1",
|
|
134
|
+
remoteKey: "金鑰(需要時填)",
|
|
135
|
+
remoteModel: "模型(需要時填)",
|
|
136
|
+
remoteAdd: "新增",
|
|
137
|
+
remoteRemove: "移除",
|
|
138
|
+
remoteNone: "還沒有新增。",
|
|
139
|
+
remoteHere: "本機",
|
|
140
|
+
remoteOff: "上面的開關關著,不會用它",
|
|
141
|
+
reflex_targets: "查看能即時操作的對象",
|
|
142
|
+
reflex_do: "即時完成任務",
|
|
143
|
+
reflex_start: "開始即時操作",
|
|
144
|
+
reflex_intent: "調整即時操作",
|
|
145
|
+
reflex_program: "更換即時操作的程式",
|
|
146
|
+
reflex_batch: "連續操作",
|
|
147
|
+
reflex_stop: "停止即時操作",
|
|
148
|
+
working: "Ta 正在即時操作 {title}",
|
|
149
|
+
workingFor: "{who} 正在即時操作 {title}",
|
|
150
|
+
stop: "停止",
|
|
151
|
+
told: "{title}:{what}",
|
|
152
|
+
round_over: "一局結束",
|
|
153
|
+
intent_expired: "等 Ta 給下一步",
|
|
154
|
+
program_failed: "程式出錯",
|
|
155
|
+
target_gone: "對象不見了",
|
|
156
|
+
stopped: "已停止",
|
|
157
|
+
seen: "等的東西出現了",
|
|
158
|
+
gone: "等的東西不見了",
|
|
159
|
+
lost: "跟丟了"
|
|
160
|
+
};
|
|
161
|
+
var JA = {
|
|
162
|
+
section: "リアルタイム操作",
|
|
163
|
+
aim: "エイム",
|
|
164
|
+
aimHint: "ゲームなどで、動く対象に Ta が自分で狙いを合わせて押します。オフにすると追従と待機だけになります。",
|
|
165
|
+
code: "Ta が書くプログラム",
|
|
166
|
+
codeHint: "リアルタイム操作のために Ta が小さなプログラムを書けます。このページ内で動き、ネットワークは使えません。オフにすると Ta 付属のプログラムだけを使います。",
|
|
167
|
+
decide: "判断モデル",
|
|
168
|
+
decideHint: "どのボタンを押すか、終わったかといった小さな判断は判断モデルが一瞬で答え、迷ったときだけ Ta に聞きます。まずこのコンピューターにあるもの(Ollama、LM Studio)、次に「ローカルモデル」でダウンロードしたもの、最後に下で追加したものを使います。オフにすると毎回 Ta が判断します。",
|
|
169
|
+
decideOnline: "このコンピューター以外の判断モデル",
|
|
170
|
+
decideOnlineHint: "下で追加した、インターネットや別のコンピューターにある判断モデルにも聞けます。ページの内容が送られます。オフにするとこのコンピューターのものだけを使います。",
|
|
171
|
+
remotes: "追加した判断モデル",
|
|
172
|
+
remotesHint: "アドレスで追加します:判断 API(Jev)のサービス、または OpenAI 互換のサービス(vLLM、別のコンピューターの llama.cpp)。キーは保管庫に保存します。",
|
|
173
|
+
remoteUrl: "アドレス、https://…/v1",
|
|
174
|
+
remoteKey: "キー(必要なら)",
|
|
175
|
+
remoteModel: "モデル(必要なら)",
|
|
176
|
+
remoteAdd: "追加",
|
|
177
|
+
remoteRemove: "削除",
|
|
178
|
+
remoteNone: "まだありません。",
|
|
179
|
+
remoteHere: "このコンピューター",
|
|
180
|
+
remoteOff: "上のスイッチがオフのあいだは使いません",
|
|
181
|
+
reflex_targets: "リアルタイム操作できる対象を確認",
|
|
182
|
+
reflex_do: "リアルタイムで完了",
|
|
183
|
+
reflex_start: "リアルタイム操作を開始",
|
|
184
|
+
reflex_intent: "リアルタイム操作を調整",
|
|
185
|
+
reflex_program: "リアルタイム操作のプログラムを変更",
|
|
186
|
+
reflex_batch: "連続して操作",
|
|
187
|
+
reflex_stop: "リアルタイム操作を停止",
|
|
188
|
+
working: "Ta が {title} をリアルタイム操作中",
|
|
189
|
+
workingFor: "{who} が {title} をリアルタイム操作中",
|
|
190
|
+
stop: "停止",
|
|
191
|
+
told: "{title}:{what}",
|
|
192
|
+
round_over: "ラウンド終了",
|
|
193
|
+
intent_expired: "Ta の次の指示待ち",
|
|
194
|
+
program_failed: "プログラムのエラー",
|
|
195
|
+
target_gone: "対象が見えなくなりました",
|
|
196
|
+
stopped: "停止しました",
|
|
197
|
+
seen: "待っていたものが現れました",
|
|
198
|
+
gone: "待っていたものが消えました",
|
|
199
|
+
lost: "見失いました"
|
|
200
|
+
};
|
|
201
|
+
var WORDS = { "zh-CN": ZH, "zh-TW": ZH_TW, "en-US": EN, "ja-JP": JA };
|
|
202
|
+
var ReflexWords;
|
|
203
|
+
((ReflexWords) => {
|
|
204
|
+
function of(language) {
|
|
205
|
+
return TaLanguageUtil.pick(language, WORDS);
|
|
206
|
+
}
|
|
207
|
+
ReflexWords.of = of;
|
|
208
|
+
function fill(text, values) {
|
|
209
|
+
return text.replace(/\{(\w+)\}/g, (all, key) => values[key] ?? all);
|
|
210
|
+
}
|
|
211
|
+
ReflexWords.fill = fill;
|
|
212
|
+
})(ReflexWords ||= {});
|
|
213
|
+
|
|
214
|
+
// web-src/program-lib.ts
|
|
215
|
+
var clamp = (value) => Math.min(1, Math.max(0, value));
|
|
216
|
+
var ProgramLib;
|
|
217
|
+
((ProgramLib) => {
|
|
218
|
+
function center(box) {
|
|
219
|
+
return { x: box.x + box.w / 2, y: box.y + box.h / 2 };
|
|
220
|
+
}
|
|
221
|
+
ProgramLib.center = center;
|
|
222
|
+
function inside(point, box, margin = 0) {
|
|
223
|
+
const mx = box.w * margin;
|
|
224
|
+
const my = box.h * margin;
|
|
225
|
+
return point.x >= box.x + mx && point.x <= box.x + box.w - mx && point.y >= box.y + my && point.y <= box.y + box.h - my;
|
|
226
|
+
}
|
|
227
|
+
ProgramLib.inside = inside;
|
|
228
|
+
function matching(entities, filter = {}) {
|
|
229
|
+
return entities.filter((entity) => (!filter.types?.length || filter.types.includes(entity.type)) && (!filter.tags?.length || filter.tags.every((tag) => entity.tags?.includes(tag))) && !filter.skip?.some((tag) => entity.tags?.includes(tag) || entity.type === tag));
|
|
230
|
+
}
|
|
231
|
+
ProgramLib.matching = matching;
|
|
232
|
+
|
|
233
|
+
class Tracker {
|
|
234
|
+
known = new Map;
|
|
235
|
+
update(observation) {
|
|
236
|
+
const seen = [];
|
|
237
|
+
const now = new Set;
|
|
238
|
+
for (const entity of observation.entities ?? []) {
|
|
239
|
+
if (!entity.box) {
|
|
240
|
+
continue;
|
|
241
|
+
}
|
|
242
|
+
const { x, y } = center(entity.box);
|
|
243
|
+
const before = this.known.get(entity.id);
|
|
244
|
+
const dt = before ? (observation.t - before.t) / 1000 : 0;
|
|
245
|
+
const k = 0.5;
|
|
246
|
+
const vx = before && dt > 0 ? before.vx + k * ((x - before.x) / dt - before.vx) : 0;
|
|
247
|
+
const vy = before && dt > 0 ? before.vy + k * ((y - before.y) / dt - before.vy) : 0;
|
|
248
|
+
const tracked = { id: entity.id, entity, x, y, vx, vy, t: observation.t };
|
|
249
|
+
this.known.set(entity.id, tracked);
|
|
250
|
+
now.add(entity.id);
|
|
251
|
+
seen.push({ id: entity.id, entity, x, y, vx, vy });
|
|
252
|
+
}
|
|
253
|
+
for (const id of [...this.known.keys()]) {
|
|
254
|
+
if (!now.has(id)) {
|
|
255
|
+
this.known.delete(id);
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return seen;
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
ProgramLib.Tracker = Tracker;
|
|
262
|
+
function lead(tracked, ms) {
|
|
263
|
+
return { x: clamp(tracked.x + tracked.vx * ms / 1000), y: clamp(tracked.y + tracked.vy * ms / 1000) };
|
|
264
|
+
}
|
|
265
|
+
ProgramLib.lead = lead;
|
|
266
|
+
function pick(tracked, prefer = "nearest", from = { x: 0.5, y: 0.5 }) {
|
|
267
|
+
if (prefer === "first") {
|
|
268
|
+
return tracked[0];
|
|
269
|
+
}
|
|
270
|
+
let best;
|
|
271
|
+
let score = Number.POSITIVE_INFINITY;
|
|
272
|
+
for (const one of tracked) {
|
|
273
|
+
const size = one.entity.box ? one.entity.box.w * one.entity.box.h : 0;
|
|
274
|
+
const value = prefer === "largest" ? -size : (one.x - from.x) ** 2 + (one.y - from.y) ** 2;
|
|
275
|
+
if (value < score) {
|
|
276
|
+
score = value;
|
|
277
|
+
best = one;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return best;
|
|
281
|
+
}
|
|
282
|
+
ProgramLib.pick = pick;
|
|
283
|
+
function approach(from, to, smooth) {
|
|
284
|
+
const keep = Math.min(0.95, Math.max(0, smooth));
|
|
285
|
+
return { x: from.x + (to.x - from.x) * (1 - keep), y: from.y + (to.y - from.y) * (1 - keep) };
|
|
286
|
+
}
|
|
287
|
+
ProgramLib.approach = approach;
|
|
288
|
+
function click(at) {
|
|
289
|
+
return { kind: "pointer", x: at.x, y: at.y };
|
|
290
|
+
}
|
|
291
|
+
ProgramLib.click = click;
|
|
292
|
+
function move(at) {
|
|
293
|
+
return { kind: "pointer", x: at.x, y: at.y, press: "move" };
|
|
294
|
+
}
|
|
295
|
+
ProgramLib.move = move;
|
|
296
|
+
function turn(at, sensitivity, smooth) {
|
|
297
|
+
const towards = approach({ x: 0.5, y: 0.5 }, at, smooth);
|
|
298
|
+
return { kind: "pointer", dx: Math.round((towards.x - 0.5) * sensitivity), dy: Math.round((towards.y - 0.5) * sensitivity) };
|
|
299
|
+
}
|
|
300
|
+
ProgramLib.turn = turn;
|
|
301
|
+
const median = (values) => {
|
|
302
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
303
|
+
const middle = sorted.length >> 1;
|
|
304
|
+
return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
class TurnAxis {
|
|
308
|
+
perPixel;
|
|
309
|
+
lag = 0;
|
|
310
|
+
sent = [];
|
|
311
|
+
moved = [];
|
|
312
|
+
constructor(sensitivity) {
|
|
313
|
+
this.perPixel = 1 / sensitivity;
|
|
314
|
+
}
|
|
315
|
+
see(moved) {
|
|
316
|
+
this.moved.push(moved);
|
|
317
|
+
if (this.moved.length > TurnAxis.KEPT) {
|
|
318
|
+
this.moved.shift();
|
|
319
|
+
}
|
|
320
|
+
this.learn();
|
|
321
|
+
}
|
|
322
|
+
send(pixels) {
|
|
323
|
+
this.sent.push(pixels);
|
|
324
|
+
if (this.sent.length > TurnAxis.KEPT) {
|
|
325
|
+
this.sent.shift();
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
coming() {
|
|
329
|
+
const late = this.lag ? this.sent.slice(-this.lag) : [];
|
|
330
|
+
return -this.perPixel * late.reduce((sum, one) => sum + one, 0);
|
|
331
|
+
}
|
|
332
|
+
learn() {
|
|
333
|
+
let best;
|
|
334
|
+
for (let lag = 0;lag <= TurnAxis.LAG_MAX; lag++) {
|
|
335
|
+
let product = 0;
|
|
336
|
+
let squares = 0;
|
|
337
|
+
const pairs = [];
|
|
338
|
+
for (let i = 0;i + lag < this.moved.length && i < this.sent.length; i++) {
|
|
339
|
+
const moved = this.moved[i + lag + (this.moved.length - this.sent.length)];
|
|
340
|
+
if (moved === undefined || Number.isNaN(moved)) {
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
product += moved * this.sent[i];
|
|
344
|
+
squares += this.sent[i] ** 2;
|
|
345
|
+
pairs.push([this.sent[i], moved]);
|
|
346
|
+
}
|
|
347
|
+
if (squares < TurnAxis.LEARN_PX ** 2) {
|
|
348
|
+
continue;
|
|
349
|
+
}
|
|
350
|
+
const perPixel = -product / squares;
|
|
351
|
+
const error = pairs.reduce((sum, [sent, moved]) => sum + (moved + perPixel * sent) ** 2, 0) / pairs.length;
|
|
352
|
+
if (perPixel > 0 && (!best || error < best.error)) {
|
|
353
|
+
best = { lag, perPixel, error };
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
if (best) {
|
|
357
|
+
this.lag = best.lag;
|
|
358
|
+
this.perPixel = Math.min(TurnAxis.MAX, Math.max(TurnAxis.MIN, this.perPixel + (best.perPixel - this.perPixel) * 0.5));
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
static KEPT = 40;
|
|
362
|
+
static LAG_MAX = 3;
|
|
363
|
+
static LEARN_PX = 30;
|
|
364
|
+
static MIN = 1 / 20000;
|
|
365
|
+
static MAX = 1 / 20;
|
|
366
|
+
}
|
|
367
|
+
ProgramLib.TurnAxis = TurnAxis;
|
|
368
|
+
|
|
369
|
+
class ViewTurner {
|
|
370
|
+
gain;
|
|
371
|
+
across;
|
|
372
|
+
down;
|
|
373
|
+
vx = 0;
|
|
374
|
+
vy = 0;
|
|
375
|
+
last = new Map;
|
|
376
|
+
t;
|
|
377
|
+
turned = true;
|
|
378
|
+
constructor(sensitivity = 800, gain = 0.5) {
|
|
379
|
+
this.gain = gain;
|
|
380
|
+
this.across = new TurnAxis(sensitivity);
|
|
381
|
+
this.down = new TurnAxis(sensitivity);
|
|
382
|
+
}
|
|
383
|
+
see(tracked, t) {
|
|
384
|
+
if (!this.turned) {
|
|
385
|
+
this.across.send(0);
|
|
386
|
+
this.down.send(0);
|
|
387
|
+
}
|
|
388
|
+
this.turned = false;
|
|
389
|
+
const shifts = tracked.flatMap((one) => {
|
|
390
|
+
const before = this.last.get(one.id);
|
|
391
|
+
return before ? [{ x: one.x - before.x, y: one.y - before.y }] : [];
|
|
392
|
+
});
|
|
393
|
+
const dt = this.t === undefined ? 0 : (t - this.t) / 1000;
|
|
394
|
+
this.t = t;
|
|
395
|
+
this.last = new Map(tracked.map((one) => [one.id, { x: one.x, y: one.y }]));
|
|
396
|
+
const x = shifts.length ? median(shifts.map((shift) => shift.x)) : Number.NaN;
|
|
397
|
+
const y = shifts.length ? median(shifts.map((shift) => shift.y)) : Number.NaN;
|
|
398
|
+
this.vx = dt > 0 && shifts.length ? x / dt : 0;
|
|
399
|
+
this.vy = dt > 0 && shifts.length ? y / dt : 0;
|
|
400
|
+
this.across.see(x);
|
|
401
|
+
this.down.see(y);
|
|
402
|
+
}
|
|
403
|
+
turn(at) {
|
|
404
|
+
const x = at.x + this.across.coming() - 0.5;
|
|
405
|
+
const y = at.y + this.down.coming() - 0.5;
|
|
406
|
+
return this.by(x * this.gain / this.across.perPixel, y * this.gain / this.down.perPixel);
|
|
407
|
+
}
|
|
408
|
+
sweep(widths) {
|
|
409
|
+
return this.by(widths / this.across.perPixel, 0);
|
|
410
|
+
}
|
|
411
|
+
own(tracked) {
|
|
412
|
+
return { ...tracked, vx: tracked.vx - this.vx, vy: tracked.vy - this.vy };
|
|
413
|
+
}
|
|
414
|
+
by(dx, dy) {
|
|
415
|
+
const action = { kind: "pointer", dx: Math.round(dx), dy: Math.round(dy) };
|
|
416
|
+
this.across.send(action.dx);
|
|
417
|
+
this.down.send(action.dy);
|
|
418
|
+
this.turned = true;
|
|
419
|
+
return action;
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
ProgramLib.ViewTurner = ViewTurner;
|
|
423
|
+
function shows(observation, look) {
|
|
424
|
+
if (look.data && !Object.entries(look.data).every(([key, value]) => observation.data?.[key] === value)) {
|
|
425
|
+
return false;
|
|
426
|
+
}
|
|
427
|
+
if (look.type === undefined && look.text === undefined) {
|
|
428
|
+
return !!look.data;
|
|
429
|
+
}
|
|
430
|
+
const text = look.text?.toLowerCase();
|
|
431
|
+
return (observation.entities ?? []).some((entity) => (look.type === undefined || entity.type === look.type) && (text === undefined || (entity.text ?? "").toLowerCase().includes(text)));
|
|
432
|
+
}
|
|
433
|
+
ProgramLib.shows = shows;
|
|
434
|
+
})(ProgramLib ||= {});
|
|
435
|
+
|
|
436
|
+
// web-src/programs.ts
|
|
437
|
+
var num = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
438
|
+
var strings = (value) => Array.isArray(value) ? value.filter((one) => typeof one === "string") : undefined;
|
|
439
|
+
var MIDDLE = { x: 0.5, y: 0.5 };
|
|
440
|
+
var AIM = {
|
|
441
|
+
step(observation, intent, memory, ctx) {
|
|
442
|
+
const params = intent.params ?? {};
|
|
443
|
+
memory.tracker ??= new ctx.lib.Tracker;
|
|
444
|
+
const tracker = memory.tracker;
|
|
445
|
+
const skip = strings(params.skip) ?? ["friend"];
|
|
446
|
+
const filter = { types: strings(params.types), tags: strings(params.tags), skip };
|
|
447
|
+
const all = tracker.update(observation);
|
|
448
|
+
const tracked = all.filter((one) => ctx.lib.matching([one.entity], filter).length > 0);
|
|
449
|
+
const view = params.mode === "view";
|
|
450
|
+
const turner = view ? viewTurner(memory, ctx, params) : undefined;
|
|
451
|
+
turner?.see(all, observation.t);
|
|
452
|
+
const dt = memory.t === undefined ? 0 : (observation.t - memory.t) / 1000;
|
|
453
|
+
memory.t = observation.t;
|
|
454
|
+
if (observation.data?.over === true) {
|
|
455
|
+
if (!memory.over) {
|
|
456
|
+
memory.over = true;
|
|
457
|
+
ctx.escalate("round_over", { score: observation.data.score });
|
|
458
|
+
}
|
|
459
|
+
return [];
|
|
460
|
+
}
|
|
461
|
+
memory.over = false;
|
|
462
|
+
if (!tracked.length) {
|
|
463
|
+
if (!memory.empty) {
|
|
464
|
+
memory.empty = true;
|
|
465
|
+
ctx.emit("no_target");
|
|
466
|
+
}
|
|
467
|
+
const sweep = num(params.sweep, 0.6);
|
|
468
|
+
return turner && sweep && dt > 0 ? [turner.sweep(sweep * dt)] : [];
|
|
469
|
+
}
|
|
470
|
+
memory.empty = false;
|
|
471
|
+
const from = view ? MIDDLE : memory.at ?? MIDDLE;
|
|
472
|
+
const target = ctx.lib.pick(tracked, params.prefer === "largest" || params.prefer === "first" ? params.prefer : "nearest", from);
|
|
473
|
+
if (!target?.entity.box) {
|
|
474
|
+
return [];
|
|
475
|
+
}
|
|
476
|
+
const at = ctx.lib.lead(turner ? turner.own(target) : target, num(params.leadMs, 40));
|
|
477
|
+
const smooth = num(params.smooth, 0);
|
|
478
|
+
const blocked = (point) => all.some((one) => one.entity.box && ctx.lib.matching([one.entity], { skip }).length === 0 && ctx.lib.inside(point, one.entity.box));
|
|
479
|
+
const ready = params.fire !== false && (memory.fired === undefined || observation.t - memory.fired >= num(params.cooldownMs, 120));
|
|
480
|
+
const actions = [];
|
|
481
|
+
if (turner) {
|
|
482
|
+
actions.push(turner.turn(at));
|
|
483
|
+
if (ready && ctx.lib.inside(MIDDLE, target.entity.box, 0.1) && !blocked(MIDDLE)) {
|
|
484
|
+
actions.push(ctx.lib.click(MIDDLE));
|
|
485
|
+
memory.fired = observation.t;
|
|
486
|
+
}
|
|
487
|
+
return actions;
|
|
488
|
+
}
|
|
489
|
+
const next = ctx.lib.approach(from, at, smooth);
|
|
490
|
+
memory.at = next;
|
|
491
|
+
const box = target.entity.box;
|
|
492
|
+
if (ready && !blocked(next) && (smooth === 0 || ctx.lib.inside(next, { ...box, x: at.x - box.w / 2, y: at.y - box.h / 2 }, 0.1))) {
|
|
493
|
+
memory.fired = observation.t;
|
|
494
|
+
return [ctx.lib.click(next)];
|
|
495
|
+
}
|
|
496
|
+
return [ctx.lib.move(next)];
|
|
497
|
+
}
|
|
498
|
+
};
|
|
499
|
+
function viewTurner(memory, ctx, params) {
|
|
500
|
+
memory.turner ??= new ctx.lib.ViewTurner(num(params.sensitivity, 800), Math.min(1, Math.max(0.05, num(params.gain, 0.5))));
|
|
501
|
+
return memory.turner;
|
|
502
|
+
}
|
|
503
|
+
var WATCH = {
|
|
504
|
+
step(observation, intent, memory, ctx) {
|
|
505
|
+
const params = intent.params ?? {};
|
|
506
|
+
const look = {
|
|
507
|
+
...typeof params.type === "string" ? { type: params.type } : {},
|
|
508
|
+
...typeof params.text === "string" ? { text: params.text } : {},
|
|
509
|
+
...params.data && typeof params.data === "object" ? { data: params.data } : {}
|
|
510
|
+
};
|
|
511
|
+
const shown = ctx.lib.shows(observation, look);
|
|
512
|
+
const wanted = params.gone === true ? !shown : shown;
|
|
513
|
+
if (wanted && !memory.told) {
|
|
514
|
+
memory.told = true;
|
|
515
|
+
ctx.escalate(params.gone === true ? "gone" : "seen", { ...look });
|
|
516
|
+
} else if (!wanted) {
|
|
517
|
+
memory.told = false;
|
|
518
|
+
}
|
|
519
|
+
return [];
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
var TRACK = {
|
|
523
|
+
step(observation, intent, memory, ctx) {
|
|
524
|
+
const params = intent.params ?? {};
|
|
525
|
+
memory.tracker ??= new ctx.lib.Tracker;
|
|
526
|
+
const tracker = memory.tracker;
|
|
527
|
+
const filter = { types: strings(params.types), tags: strings(params.tags), skip: strings(params.skip) };
|
|
528
|
+
const all = tracker.update(observation);
|
|
529
|
+
const tracked = all.filter((one) => ctx.lib.matching([one.entity], filter).length > 0);
|
|
530
|
+
const view = params.mode === "view";
|
|
531
|
+
const turner = view ? viewTurner(memory, ctx, params) : undefined;
|
|
532
|
+
turner?.see(all, observation.t);
|
|
533
|
+
const from = view ? MIDDLE : memory.at ?? MIDDLE;
|
|
534
|
+
const followed = tracked.find((one) => one.id === memory.id) ?? ctx.lib.pick(tracked, params.prefer === "largest" || params.prefer === "first" ? params.prefer : "nearest", from);
|
|
535
|
+
if (!followed) {
|
|
536
|
+
memory.lostAt ??= observation.t;
|
|
537
|
+
if (!memory.lost && observation.t - memory.lostAt >= num(params.lostMs, 1000)) {
|
|
538
|
+
memory.lost = true;
|
|
539
|
+
ctx.escalate("lost", memory.id ? { id: memory.id } : undefined);
|
|
540
|
+
}
|
|
541
|
+
return [];
|
|
542
|
+
}
|
|
543
|
+
memory.id = followed.id;
|
|
544
|
+
memory.lostAt = undefined;
|
|
545
|
+
memory.lost = false;
|
|
546
|
+
const lead = ctx.lib.lead(turner ? turner.own(followed) : followed, num(params.leadMs, 40));
|
|
547
|
+
const at = { x: params.axis === "y" ? from.x : lead.x, y: params.axis === "x" ? from.y : lead.y };
|
|
548
|
+
if (turner) {
|
|
549
|
+
return [turner.turn(at)];
|
|
550
|
+
}
|
|
551
|
+
const next = ctx.lib.approach(from, at, num(params.smooth, 0));
|
|
552
|
+
memory.at = next;
|
|
553
|
+
return [ctx.lib.move(next)];
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
var ACTIONABLE = new Set([
|
|
557
|
+
"button",
|
|
558
|
+
"link",
|
|
559
|
+
"textbox",
|
|
560
|
+
"searchbox",
|
|
561
|
+
"textarea",
|
|
562
|
+
"textfield",
|
|
563
|
+
"combobox",
|
|
564
|
+
"checkbox",
|
|
565
|
+
"radio",
|
|
566
|
+
"switch",
|
|
567
|
+
"tab",
|
|
568
|
+
"menuitem",
|
|
569
|
+
"option",
|
|
570
|
+
"cell",
|
|
571
|
+
"row",
|
|
572
|
+
"treeitem",
|
|
573
|
+
"slider",
|
|
574
|
+
"spinbutton",
|
|
575
|
+
"listitem",
|
|
576
|
+
"image"
|
|
577
|
+
]);
|
|
578
|
+
var FIELDS = new Set(["textbox", "searchbox", "textarea", "textfield", "combobox", "spinbutton"]);
|
|
579
|
+
var DIALOGS = new Set(["dialog", "alertdialog", "sheet"]);
|
|
580
|
+
var NAV_OPTIONS = 24;
|
|
581
|
+
var NAV_DONE = "The goal is reached: nothing more to do";
|
|
582
|
+
var NAV_DONE_MEANS = "The goal is already reached on this screen: nothing more needs doing.";
|
|
583
|
+
var TOGGLES = new Set(["checkbox", "switch", "radio", "menuitemcheckbox", "menuitemradio"]);
|
|
584
|
+
var label = (entity) => [entity.type, entity.text ? JSON.stringify(entity.text.slice(0, 80)) : "", entity.value ? `= ${JSON.stringify(entity.value.slice(0, 40))}` : ""].filter(Boolean).join(" ");
|
|
585
|
+
var means = (entity, fill) => {
|
|
586
|
+
const type = entity.type.toLowerCase();
|
|
587
|
+
const text = JSON.stringify((entity.text ?? "").slice(0, 80));
|
|
588
|
+
if (TOGGLES.has(type) && (entity.value === "on" || entity.value === "off")) {
|
|
589
|
+
return `Turning the ${type} ${text} ${entity.value === "on" ? "off" : "on"} (it is ${entity.value} now) is the right next step toward the goal.`;
|
|
590
|
+
}
|
|
591
|
+
if (FIELDS.has(type)) {
|
|
592
|
+
const key = Object.keys(fill).find((name) => (entity.text ?? "").toLowerCase().includes(name.toLowerCase()));
|
|
593
|
+
const typed = key === undefined ? "" : `${JSON.stringify(String(fill[key]).slice(0, 40))} `;
|
|
594
|
+
const holds = entity.value ? ` (it holds ${JSON.stringify(entity.value.slice(0, 40))})` : "";
|
|
595
|
+
return `Typing ${typed}into the field ${text}${holds} is the right next step toward the goal.`;
|
|
596
|
+
}
|
|
597
|
+
return `Clicking the ${type} ${text} is the right next step toward the goal.`;
|
|
598
|
+
};
|
|
599
|
+
var reached = (memory, params, goal) => {
|
|
600
|
+
const key = JSON.stringify([goal, params.plan ?? null, params.fill ?? null]);
|
|
601
|
+
if (memory.doneKey !== key) {
|
|
602
|
+
memory.doneKey = key;
|
|
603
|
+
memory.donePath = [...memory.path];
|
|
604
|
+
}
|
|
605
|
+
return memory.donePath;
|
|
606
|
+
};
|
|
607
|
+
var signature = (observation) => (observation.entities ?? []).map((entity) => `${entity.id}:${entity.text ?? ""}:${entity.value ?? ""}`).join("|");
|
|
608
|
+
var named = (entities, step) => {
|
|
609
|
+
const want = step.trim().toLowerCase();
|
|
610
|
+
return entities.find((entity) => entity.id === step || (entity.text ?? "").trim().toLowerCase() === want) ?? entities.find((entity) => !!want && (entity.text ?? "").toLowerCase().includes(want));
|
|
611
|
+
};
|
|
612
|
+
var words = (text) => {
|
|
613
|
+
const lower = text.toLowerCase();
|
|
614
|
+
const latin = lower.match(/[a-z0-9]+/g) ?? [];
|
|
615
|
+
const han = [...lower].filter((char) => char.charCodeAt(0) > 127);
|
|
616
|
+
return new Set([...latin, ...han.slice(0, -1).map((one, i) => one + han[i + 1])]);
|
|
617
|
+
};
|
|
618
|
+
var NAV = {
|
|
619
|
+
step(observation, intent, memory, ctx) {
|
|
620
|
+
const params = intent.params ?? {};
|
|
621
|
+
const goal = typeof intent.goal === "string" && intent.goal.trim() ? intent.goal.trim() : typeof params.goal === "string" ? params.goal : "";
|
|
622
|
+
const fill = params.fill && typeof params.fill === "object" ? params.fill : {};
|
|
623
|
+
const given = JSON.stringify(intent);
|
|
624
|
+
if (memory.given !== given) {
|
|
625
|
+
memory.given = given;
|
|
626
|
+
memory.paused = false;
|
|
627
|
+
memory.stale = 0;
|
|
628
|
+
memory.steps ??= [];
|
|
629
|
+
memory.path ??= [];
|
|
630
|
+
memory.task ??= goal;
|
|
631
|
+
memory.next = typeof params.next === "string" ? params.next : undefined;
|
|
632
|
+
const plan2 = JSON.stringify(params.plan ?? null);
|
|
633
|
+
if (memory.plan !== plan2) {
|
|
634
|
+
memory.plan = plan2;
|
|
635
|
+
memory.at = 0;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
if (!goal) {
|
|
639
|
+
if (!memory.paused) {
|
|
640
|
+
memory.paused = true;
|
|
641
|
+
ctx.escalate("no_goal");
|
|
642
|
+
}
|
|
643
|
+
return [];
|
|
644
|
+
}
|
|
645
|
+
const steps = memory.steps;
|
|
646
|
+
const sign = signature(observation);
|
|
647
|
+
if (memory.actedAt !== undefined) {
|
|
648
|
+
const changed = sign !== memory.actedSign;
|
|
649
|
+
if (!changed && observation.t - memory.actedAt < num(params.settleMs, 1500)) {
|
|
650
|
+
return [];
|
|
651
|
+
}
|
|
652
|
+
memory.actedAt = undefined;
|
|
653
|
+
if (memory.by) {
|
|
654
|
+
ctx.emit("decision", { by: memory.by, missed: !changed });
|
|
655
|
+
memory.by = undefined;
|
|
656
|
+
}
|
|
657
|
+
memory.stale = changed ? 0 : memory.stale + 1;
|
|
658
|
+
if (memory.stale >= 2) {
|
|
659
|
+
memory.paused = true;
|
|
660
|
+
ctx.escalate("stuck", { steps: steps.slice(-3) });
|
|
661
|
+
return [];
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
if (memory.paused) {
|
|
665
|
+
return [];
|
|
666
|
+
}
|
|
667
|
+
const pause = (type, data) => {
|
|
668
|
+
memory.paused = true;
|
|
669
|
+
ctx.escalate(type, data);
|
|
670
|
+
return [];
|
|
671
|
+
};
|
|
672
|
+
if (steps.length >= num(params.maxSteps, 20)) {
|
|
673
|
+
return pause("max_steps", { steps: steps.length });
|
|
674
|
+
}
|
|
675
|
+
const all = (observation.entities ?? []).filter((entity) => ACTIONABLE.has(entity.type.toLowerCase()) && (entity.text || entity.value || FIELDS.has(entity.type.toLowerCase())));
|
|
676
|
+
const act = (entity, by) => {
|
|
677
|
+
if (FIELDS.has(entity.type.toLowerCase())) {
|
|
678
|
+
const key = Object.keys(fill).find((name) => (entity.text ?? "").toLowerCase().includes(name.toLowerCase()));
|
|
679
|
+
if (key === undefined) {
|
|
680
|
+
pause("needs_text", { field: label(entity), id: entity.id });
|
|
681
|
+
return;
|
|
682
|
+
}
|
|
683
|
+
if (entity.value === String(fill[key])) {
|
|
684
|
+
pause("unsure", { why: "that field already holds it", field: label(entity) });
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
steps.push(`typed into ${label(entity)}`);
|
|
688
|
+
memory.path.push(entity.text ?? entity.id);
|
|
689
|
+
memory.actedAt = observation.t;
|
|
690
|
+
memory.seenSign = undefined;
|
|
691
|
+
memory.actedSign = sign;
|
|
692
|
+
memory.by = by;
|
|
693
|
+
return [{ kind: "text", ref: entity.id, text: String(fill[key]) }];
|
|
694
|
+
}
|
|
695
|
+
steps.push(`clicked ${label(entity)}`);
|
|
696
|
+
memory.path.push(entity.text ?? entity.id);
|
|
697
|
+
memory.actedAt = observation.t;
|
|
698
|
+
memory.seenSign = undefined;
|
|
699
|
+
memory.actedSign = sign;
|
|
700
|
+
memory.by = by;
|
|
701
|
+
return [{ kind: "pointer", ref: entity.id }];
|
|
702
|
+
};
|
|
703
|
+
if (memory.next) {
|
|
704
|
+
const named2 = all.find((entity) => entity.id === memory.next) ?? (observation.entities ?? []).find((entity) => entity.id === memory.next);
|
|
705
|
+
memory.next = undefined;
|
|
706
|
+
return named2 ? act(named2) ?? [] : pause("unsure", { why: "params.next names no element now" });
|
|
707
|
+
}
|
|
708
|
+
const entities = observation.entities ?? [];
|
|
709
|
+
const dialog = entities.findIndex((entity) => DIALOGS.has(entity.type.toLowerCase()));
|
|
710
|
+
const pool = dialog < 0 ? all : all.filter((entity) => entities.indexOf(entity) > dialog);
|
|
711
|
+
const plan = Array.isArray(params.plan) ? params.plan.map(String) : [];
|
|
712
|
+
const planned = plan[memory.at];
|
|
713
|
+
if (plan.length) {
|
|
714
|
+
const unfilled = pool.find((entity) => {
|
|
715
|
+
if (!FIELDS.has(entity.type.toLowerCase())) {
|
|
716
|
+
return false;
|
|
717
|
+
}
|
|
718
|
+
const key = Object.keys(fill).find((name) => (entity.text ?? "").toLowerCase().includes(name.toLowerCase()));
|
|
719
|
+
return key !== undefined && entity.value !== String(fill[key]) && !steps.includes(`typed into ${label(entity)}`);
|
|
720
|
+
});
|
|
721
|
+
if (unfilled) {
|
|
722
|
+
if (named([unfilled], planned ?? "")) {
|
|
723
|
+
memory.at = memory.at + 1;
|
|
724
|
+
}
|
|
725
|
+
return act(unfilled) ?? [];
|
|
726
|
+
}
|
|
727
|
+
if (planned === undefined) {
|
|
728
|
+
return pause("done", { steps: steps.length, plan: plan.length, goal: memory.task || goal, path: reached(memory, params, goal) });
|
|
729
|
+
}
|
|
730
|
+
const found = named(pool, planned);
|
|
731
|
+
if (found) {
|
|
732
|
+
const actions = act(found);
|
|
733
|
+
if (actions) {
|
|
734
|
+
memory.at = memory.at + 1;
|
|
735
|
+
}
|
|
736
|
+
return actions ?? [];
|
|
737
|
+
}
|
|
738
|
+
if (sign !== memory.seenSign) {
|
|
739
|
+
memory.seenSign = sign;
|
|
740
|
+
memory.seenAt = observation.t;
|
|
741
|
+
}
|
|
742
|
+
if (dialog < 0 && observation.t - memory.seenAt < num(params.settleMs, 1500)) {
|
|
743
|
+
return [];
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
const wanted = words([goal, planned ?? "", ...Object.keys(fill)].join(" "));
|
|
747
|
+
const offered = pool.length <= NAV_OPTIONS ? pool : pool.map((entity, at) => ({ entity, at, score: [...words(label(entity))].filter((word) => wanted.has(word)).length })).sort((a, b) => b.score - a.score || a.at - b.at).slice(0, NAV_OPTIONS).sort((a, b) => a.at - b.at).map((one) => one.entity);
|
|
748
|
+
const likeliest = (probs) => Object.entries(probs ?? {}).sort((a, b) => b[1] - a[1]).slice(0, 3).map(([option, p]) => ({ option, p: Math.round(p * 100) / 100, id: offered.find((entity) => label(entity) === option)?.id }));
|
|
749
|
+
if (!ctx.has("decide")) {
|
|
750
|
+
const why = planned !== undefined ? dialog < 0 ? `the planned step does not show: ${planned}` : `a dialog opened: ${entities[dialog].text ?? ""}` : "no decision model here (L2): pick the next element";
|
|
751
|
+
return pause("unsure", { why, decider: "none", options: offered.map((entity) => ({ id: entity.id, label: label(entity) })) });
|
|
752
|
+
}
|
|
753
|
+
const lines = (observation.entities ?? []).slice(0, 60).map(label);
|
|
754
|
+
const state = (observation.data?.title ? `Title: ${String(observation.data.title)}
|
|
755
|
+
` : "") + lines.join("; ") + (steps.length ? `
|
|
756
|
+
Done so far: ${steps.slice(-5).join("; ")}` : "");
|
|
757
|
+
const options = [...offered.map(label), NAV_DONE];
|
|
758
|
+
const asked = "Goal: " + goal + (planned !== undefined ? `. The next planned step: ${planned}` : "") + (dialog >= 0 ? `. A dialog is open: ${entities[dialog].text ?? ""}` : "") + ". What should be done next on this screen?";
|
|
759
|
+
const decided = ctx.decide(`nav:${steps.length}:${sign}`, state, [
|
|
760
|
+
{ choice: asked, options, means: [...offered.map((entity) => means(entity, fill)), NAV_DONE_MEANS] }
|
|
761
|
+
]);
|
|
762
|
+
if (decided === undefined) {
|
|
763
|
+
return [];
|
|
764
|
+
}
|
|
765
|
+
if (decided === null) {
|
|
766
|
+
return pause("unsure", { why: "the decision model did not answer", options: offered.map((entity) => ({ id: entity.id, label: label(entity) })) });
|
|
767
|
+
}
|
|
768
|
+
const [answer] = decided.answers;
|
|
769
|
+
if (!answer || answer.confidence < num(params.decideMin, ctx.decideMin)) {
|
|
770
|
+
return pause("unsure", { likeliest: likeliest(answer?.probs), confidence: Math.round((answer?.confidence ?? 0) * 100) / 100 });
|
|
771
|
+
}
|
|
772
|
+
if (answer.answer === NAV_DONE) {
|
|
773
|
+
return pause("done", { steps: steps.length, goal: memory.task || goal, path: reached(memory, params, goal) });
|
|
774
|
+
}
|
|
775
|
+
const picked = offered[options.indexOf(String(answer.answer))];
|
|
776
|
+
if (!picked) {
|
|
777
|
+
return pause("unsure", { likeliest: likeliest(answer.probs) });
|
|
778
|
+
}
|
|
779
|
+
return act(picked, decided.by) ?? [];
|
|
780
|
+
}
|
|
781
|
+
};
|
|
782
|
+
var PROGRAMS = { aim: AIM, track: TRACK, watch: WATCH, nav: NAV };
|
|
783
|
+
|
|
784
|
+
// web-src/reflex-util.ts
|
|
785
|
+
var ACTIONS_MAX = 32;
|
|
786
|
+
var CODE_MAX = 20000;
|
|
787
|
+
var PRESSES = { pointer: ["click", "move", "down", "up"], key: ["tap", "down", "up"] };
|
|
788
|
+
function finite(value, name, min = Number.NEGATIVE_INFINITY, max = Number.POSITIVE_INFINITY) {
|
|
789
|
+
if (value === undefined) {
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {
|
|
793
|
+
throw new Error(`${name} is a number${min > Number.NEGATIVE_INFINITY ? ` from ${min} to ${max}` : ""}, not ${JSON.stringify(value)}.`);
|
|
794
|
+
}
|
|
795
|
+
return value;
|
|
796
|
+
}
|
|
797
|
+
function text(value, name) {
|
|
798
|
+
if (typeof value !== "string" || !value) {
|
|
799
|
+
throw new Error(`${name} is a string, not ${JSON.stringify(value)}.`);
|
|
800
|
+
}
|
|
801
|
+
return value;
|
|
802
|
+
}
|
|
803
|
+
var ReflexUtil;
|
|
804
|
+
((ReflexUtil) => {
|
|
805
|
+
function actions(value) {
|
|
806
|
+
if (value === undefined || value === null) {
|
|
807
|
+
return [];
|
|
808
|
+
}
|
|
809
|
+
const list = Array.isArray(value) ? value : [value];
|
|
810
|
+
if (list.length > ACTIONS_MAX) {
|
|
811
|
+
throw new Error(`A step gives at most ${ACTIONS_MAX} actions, not ${list.length}.`);
|
|
812
|
+
}
|
|
813
|
+
return list.map((one, at) => action(one, `actions[${at}]`));
|
|
814
|
+
}
|
|
815
|
+
ReflexUtil.actions = actions;
|
|
816
|
+
function action(value, name = "action") {
|
|
817
|
+
const one = value ?? {};
|
|
818
|
+
switch (one.kind) {
|
|
819
|
+
case "pointer": {
|
|
820
|
+
const press = one.press ?? "click";
|
|
821
|
+
if (!PRESSES.pointer.includes(press)) {
|
|
822
|
+
throw new Error(`${name}.press is one of ${PRESSES.pointer.join(", ")}.`);
|
|
823
|
+
}
|
|
824
|
+
const x = finite(one.x, `${name}.x`, 0, 1);
|
|
825
|
+
const y = finite(one.y, `${name}.y`, 0, 1);
|
|
826
|
+
const dx = finite(one.dx, `${name}.dx`, -1e4, 1e4);
|
|
827
|
+
const dy = finite(one.dy, `${name}.dy`, -1e4, 1e4);
|
|
828
|
+
return {
|
|
829
|
+
kind: "pointer",
|
|
830
|
+
...x !== undefined ? { x } : {},
|
|
831
|
+
...y !== undefined ? { y } : {},
|
|
832
|
+
...typeof one.ref === "string" ? { ref: one.ref } : {},
|
|
833
|
+
...dx !== undefined ? { dx } : {},
|
|
834
|
+
...dy !== undefined ? { dy } : {},
|
|
835
|
+
...one.press !== undefined ? { press } : {}
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
case "key": {
|
|
839
|
+
const press = one.press ?? "tap";
|
|
840
|
+
if (!PRESSES.key.includes(press)) {
|
|
841
|
+
throw new Error(`${name}.press is one of ${PRESSES.key.join(", ")}.`);
|
|
842
|
+
}
|
|
843
|
+
const ms = finite(one.ms, `${name}.ms`, 10, 5000);
|
|
844
|
+
return {
|
|
845
|
+
kind: "key",
|
|
846
|
+
key: text(one.key, `${name}.key`),
|
|
847
|
+
...one.press !== undefined ? { press } : {},
|
|
848
|
+
...ms !== undefined ? { ms } : {}
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
case "text":
|
|
852
|
+
return { kind: "text", text: String(one.text ?? ""), ...typeof one.ref === "string" ? { ref: one.ref } : {} };
|
|
853
|
+
case "scroll": {
|
|
854
|
+
const dx = finite(one.dx, `${name}.dx`);
|
|
855
|
+
const dy = finite(one.dy, `${name}.dy`);
|
|
856
|
+
return {
|
|
857
|
+
kind: "scroll",
|
|
858
|
+
...dx !== undefined ? { dx } : {},
|
|
859
|
+
...dy !== undefined ? { dy } : {},
|
|
860
|
+
...typeof one.ref === "string" ? { ref: one.ref } : {}
|
|
861
|
+
};
|
|
862
|
+
}
|
|
863
|
+
case "verb":
|
|
864
|
+
return {
|
|
865
|
+
kind: "verb",
|
|
866
|
+
name: text(one.name, `${name}.name`),
|
|
867
|
+
...one.input && typeof one.input === "object" ? { input: one.input } : {}
|
|
868
|
+
};
|
|
869
|
+
default:
|
|
870
|
+
throw new Error(`${name}.kind is pointer, key, text, scroll or verb, not ${JSON.stringify(one.kind)}.`);
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
ReflexUtil.action = action;
|
|
874
|
+
function intent(value) {
|
|
875
|
+
const one = value && typeof value === "object" ? value : {};
|
|
876
|
+
const ttl = finite(one.ttl, "intent.ttl", 0.1, 86400);
|
|
877
|
+
return {
|
|
878
|
+
...typeof one.goal === "string" ? { goal: one.goal } : {},
|
|
879
|
+
...one.params && typeof one.params === "object" && !Array.isArray(one.params) ? { params: one.params } : {},
|
|
880
|
+
...ttl !== undefined ? { ttl } : {},
|
|
881
|
+
...Array.isArray(one.reportOn) ? { reportOn: one.reportOn.filter((type) => typeof type === "string") } : {}
|
|
882
|
+
};
|
|
883
|
+
}
|
|
884
|
+
ReflexUtil.intent = intent;
|
|
885
|
+
function percentile(values, p) {
|
|
886
|
+
if (!values.length) {
|
|
887
|
+
return 0;
|
|
888
|
+
}
|
|
889
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
890
|
+
return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * p))];
|
|
891
|
+
}
|
|
892
|
+
ReflexUtil.percentile = percentile;
|
|
893
|
+
})(ReflexUtil ||= {});
|
|
894
|
+
|
|
895
|
+
// web-src/program-sandbox.ts
|
|
896
|
+
class ProgramSandbox {
|
|
897
|
+
now;
|
|
898
|
+
program;
|
|
899
|
+
memory = {};
|
|
900
|
+
constructor(now = () => Date.now()) {
|
|
901
|
+
this.now = now;
|
|
902
|
+
}
|
|
903
|
+
load(source) {
|
|
904
|
+
const program = ProgramSandbox.compile(source);
|
|
905
|
+
const memory = {};
|
|
906
|
+
program.init?.(memory, this.context([], {}, []));
|
|
907
|
+
this.program = program;
|
|
908
|
+
this.memory = memory;
|
|
909
|
+
return source.use ?? "code";
|
|
910
|
+
}
|
|
911
|
+
step(observation, intent, extra = {}) {
|
|
912
|
+
const events = [];
|
|
913
|
+
const decides = [];
|
|
914
|
+
if (!this.program) {
|
|
915
|
+
return { actions: [], events, error: "No program is loaded." };
|
|
916
|
+
}
|
|
917
|
+
const done = (result) => decides.length ? { ...result, decides } : result;
|
|
918
|
+
try {
|
|
919
|
+
const given = this.program.step(observation, intent, this.memory, this.context(events, extra, decides));
|
|
920
|
+
const shaped = given && typeof given === "object" && !Array.isArray(given) && !("kind" in given) ? given : { actions: given };
|
|
921
|
+
for (const event of Array.isArray(shaped.events) ? shaped.events : []) {
|
|
922
|
+
if (event && typeof event.type === "string") {
|
|
923
|
+
events.push({
|
|
924
|
+
type: event.type,
|
|
925
|
+
at: this.now(),
|
|
926
|
+
...event.data ? { data: event.data } : {},
|
|
927
|
+
...event.escalate ? { escalate: true } : {}
|
|
928
|
+
});
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
return done({ actions: ReflexUtil.actions(shaped.actions), events });
|
|
932
|
+
} catch (failure) {
|
|
933
|
+
return done({ actions: [], events, error: failure instanceof Error ? failure.message : String(failure) });
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
context(events, extra, decides) {
|
|
937
|
+
const add = (escalate) => (type, data) => void events.push({ type: String(type), at: this.now(), ...data ? { data } : {}, ...escalate ? { escalate: true } : {} });
|
|
938
|
+
const can = extra.decideMin !== undefined;
|
|
939
|
+
return {
|
|
940
|
+
lib: ProgramLib,
|
|
941
|
+
emit: add(false),
|
|
942
|
+
escalate: add(true),
|
|
943
|
+
has: (what) => what === "decide" && can,
|
|
944
|
+
decideMin: extra.decideMin ?? 1,
|
|
945
|
+
decide: (key, state, questions) => {
|
|
946
|
+
if (!can) {
|
|
947
|
+
return null;
|
|
948
|
+
}
|
|
949
|
+
const outcome = extra.decided?.[String(key)];
|
|
950
|
+
if (outcome) {
|
|
951
|
+
return "error" in outcome ? null : outcome;
|
|
952
|
+
}
|
|
953
|
+
if (!decides.some((each) => each.key === String(key))) {
|
|
954
|
+
decides.push({ key: String(key), ask: { state: String(state), questions } });
|
|
955
|
+
}
|
|
956
|
+
return;
|
|
957
|
+
}
|
|
958
|
+
};
|
|
959
|
+
}
|
|
960
|
+
static compile(source) {
|
|
961
|
+
if (source.use !== undefined) {
|
|
962
|
+
const program = PROGRAMS[source.use];
|
|
963
|
+
if (!program) {
|
|
964
|
+
throw new Error(`The library has no program ${JSON.stringify(source.use)}: it has ${Object.keys(PROGRAMS).join(", ")}.`);
|
|
965
|
+
}
|
|
966
|
+
return program;
|
|
967
|
+
}
|
|
968
|
+
const code = source.code ?? "";
|
|
969
|
+
if (!code.trim()) {
|
|
970
|
+
throw new Error("A program is one of the library (use) or code that defines function step(observation, intent, memory, ctx).");
|
|
971
|
+
}
|
|
972
|
+
if (code.length > CODE_MAX) {
|
|
973
|
+
throw new Error(`A program is at most ${CODE_MAX} characters.`);
|
|
974
|
+
}
|
|
975
|
+
const made = new Function(`"use strict";
|
|
976
|
+
${code}
|
|
977
|
+
;return { step: typeof step === 'function' ? step : undefined, init: typeof init === 'function' ? init : undefined };`)();
|
|
978
|
+
if (!made.step) {
|
|
979
|
+
throw new Error("The program defines no function step(observation, intent, memory, ctx).");
|
|
980
|
+
}
|
|
981
|
+
return { step: made.step, ...made.init ? { init: made.init } : {} };
|
|
982
|
+
}
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
// web-src/program-host.ts
|
|
986
|
+
var STEP_TIMEOUT_MS = 250;
|
|
987
|
+
|
|
988
|
+
class InlineProgramHost {
|
|
989
|
+
sandbox = new ProgramSandbox;
|
|
990
|
+
async load(source) {
|
|
991
|
+
if (source.use === undefined) {
|
|
992
|
+
throw new Error("Only a program of the library runs on the page.");
|
|
993
|
+
}
|
|
994
|
+
return this.sandbox.load(source);
|
|
995
|
+
}
|
|
996
|
+
async step(observation, intent, extra) {
|
|
997
|
+
return this.sandbox.step(observation, intent, extra);
|
|
998
|
+
}
|
|
999
|
+
alive() {
|
|
1000
|
+
return true;
|
|
1001
|
+
}
|
|
1002
|
+
dispose() {}
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
class WorkerProgramHost {
|
|
1006
|
+
worker;
|
|
1007
|
+
timeoutMs;
|
|
1008
|
+
release;
|
|
1009
|
+
pending = new Map;
|
|
1010
|
+
count = 0;
|
|
1011
|
+
ended;
|
|
1012
|
+
constructor(worker, timeoutMs = STEP_TIMEOUT_MS, release) {
|
|
1013
|
+
this.worker = worker;
|
|
1014
|
+
this.timeoutMs = timeoutMs;
|
|
1015
|
+
this.release = release;
|
|
1016
|
+
worker.onmessage = (event) => this.received(event.data);
|
|
1017
|
+
worker.onerror = () => this.end("The worker of the program failed.");
|
|
1018
|
+
}
|
|
1019
|
+
static create(script) {
|
|
1020
|
+
if (!WorkerProgramHost.available()) {
|
|
1021
|
+
return;
|
|
1022
|
+
}
|
|
1023
|
+
const url = URL.createObjectURL(new Blob([script], { type: "text/javascript" }));
|
|
1024
|
+
try {
|
|
1025
|
+
return new WorkerProgramHost(new Worker(url), STEP_TIMEOUT_MS, () => URL.revokeObjectURL(url));
|
|
1026
|
+
} catch {
|
|
1027
|
+
URL.revokeObjectURL(url);
|
|
1028
|
+
return;
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
static available() {
|
|
1032
|
+
return typeof Worker === "function" && typeof Blob === "function" && typeof URL?.createObjectURL === "function";
|
|
1033
|
+
}
|
|
1034
|
+
async load(source) {
|
|
1035
|
+
return await this.send({ type: "load", source }, this.timeoutMs * 8);
|
|
1036
|
+
}
|
|
1037
|
+
async step(observation, intent, extra) {
|
|
1038
|
+
return await this.send({ type: "step", observation, intent, ...extra ? { extra } : {} }, this.timeoutMs);
|
|
1039
|
+
}
|
|
1040
|
+
alive() {
|
|
1041
|
+
return this.ended === undefined;
|
|
1042
|
+
}
|
|
1043
|
+
dispose() {
|
|
1044
|
+
this.end("The program was stopped.");
|
|
1045
|
+
}
|
|
1046
|
+
send(message, timeoutMs) {
|
|
1047
|
+
if (this.ended !== undefined) {
|
|
1048
|
+
return Promise.reject(new Error(this.ended));
|
|
1049
|
+
}
|
|
1050
|
+
const id = ++this.count;
|
|
1051
|
+
return new Promise((resolve, reject) => {
|
|
1052
|
+
const pending = { resolve, reject };
|
|
1053
|
+
pending.timer = setTimeout(() => this.end(`A step of the program took longer than ${timeoutMs} ms: it was stopped.`), timeoutMs);
|
|
1054
|
+
this.pending.set(id, pending);
|
|
1055
|
+
this.worker.postMessage({ ...message, id });
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
received(data) {
|
|
1059
|
+
const pending = this.pending.get(data.id);
|
|
1060
|
+
if (!pending) {
|
|
1061
|
+
return;
|
|
1062
|
+
}
|
|
1063
|
+
this.pending.delete(data.id);
|
|
1064
|
+
clearTimeout(pending.timer);
|
|
1065
|
+
if (data.error !== undefined) {
|
|
1066
|
+
pending.reject(new Error(data.error));
|
|
1067
|
+
} else {
|
|
1068
|
+
pending.resolve(data.value);
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
end(why) {
|
|
1072
|
+
if (this.ended !== undefined) {
|
|
1073
|
+
return;
|
|
1074
|
+
}
|
|
1075
|
+
this.ended = why;
|
|
1076
|
+
this.worker.terminate();
|
|
1077
|
+
this.release?.();
|
|
1078
|
+
for (const pending of this.pending.values()) {
|
|
1079
|
+
clearTimeout(pending.timer);
|
|
1080
|
+
pending.reject(new Error(why));
|
|
1081
|
+
}
|
|
1082
|
+
this.pending.clear();
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
// web-src/program-worker-source.ts
|
|
1087
|
+
var PROGRAM_WORKER_SOURCE = '(()=>{var s=(J)=>Math.min(1,Math.max(0,J)),v;((Xj)=>{function J(Q){return{x:Q.x+Q.w/2,y:Q.y+Q.h/2}}Xj.center=J;function B(Q,Z,X=0){let U=Z.w*X,M=Z.h*X;return Q.x>=Z.x+U&&Q.x<=Z.x+Z.w-U&&Q.y>=Z.y+M&&Q.y<=Z.y+Z.h-M}Xj.inside=B;function j(Q,Z={}){return Q.filter((X)=>(!Z.types?.length||Z.types.includes(X.type))&&(!Z.tags?.length||Z.tags.every((U)=>X.tags?.includes(U)))&&!Z.skip?.some((U)=>X.tags?.includes(U)||X.type===U))}Xj.matching=j;class z{known=new Map;update(Q){let Z=[],X=new Set;for(let U of Q.entities??[]){if(!U.box)continue;let{x:M,y:G}=J(U.box),q=this.known.get(U.id),V=q?(Q.t-q.t)/1000:0,O=0.5,T=q&&V>0?q.vx+O*((M-q.x)/V-q.vx):0,f=q&&V>0?q.vy+O*((G-q.y)/V-q.vy):0,h={id:U.id,entity:U,x:M,y:G,vx:T,vy:f,t:Q.t};this.known.set(U.id,h),X.add(U.id),Z.push({id:U.id,entity:U,x:M,y:G,vx:T,vy:f})}for(let U of[...this.known.keys()])if(!X.has(U))this.known.delete(U);return Z}}Xj.Tracker=z;function Y(Q,Z){return{x:s(Q.x+Q.vx*Z/1000),y:s(Q.y+Q.vy*Z/1000)}}Xj.lead=Y;function H(Q,Z="nearest",X={x:0.5,y:0.5}){if(Z==="first")return Q[0];let U,M=Number.POSITIVE_INFINITY;for(let G of Q){let q=G.entity.box?G.entity.box.w*G.entity.box.h:0,V=Z==="largest"?-q:(G.x-X.x)**2+(G.y-X.y)**2;if(V<M)M=V,U=G}return U}Xj.pick=H;function $(Q,Z,X){let U=Math.min(0.95,Math.max(0,X));return{x:Q.x+(Z.x-Q.x)*(1-U),y:Q.y+(Z.y-Q.y)*(1-U)}}Xj.approach=$;function F(Q){return{kind:"pointer",x:Q.x,y:Q.y}}Xj.click=F;function W(Q){return{kind:"pointer",x:Q.x,y:Q.y,press:"move"}}Xj.move=W;function N(Q,Z,X){let U=$({x:0.5,y:0.5},Q,X);return{kind:"pointer",dx:Math.round((U.x-0.5)*Z),dy:Math.round((U.y-0.5)*Z)}}Xj.turn=N;let R=(Q)=>{let Z=[...Q].sort((U,M)=>U-M),X=Z.length>>1;return Z.length%2?Z[X]:(Z[X-1]+Z[X])/2};class C{perPixel;lag=0;sent=[];moved=[];constructor(Q){this.perPixel=1/Q}see(Q){if(this.moved.push(Q),this.moved.length>C.KEPT)this.moved.shift();this.learn()}send(Q){if(this.sent.push(Q),this.sent.length>C.KEPT)this.sent.shift()}coming(){let Q=this.lag?this.sent.slice(-this.lag):[];return-this.perPixel*Q.reduce((Z,X)=>Z+X,0)}learn(){let Q;for(let Z=0;Z<=C.LAG_MAX;Z++){let X=0,U=0,M=[];for(let V=0;V+Z<this.moved.length&&V<this.sent.length;V++){let O=this.moved[V+Z+(this.moved.length-this.sent.length)];if(O===void 0||Number.isNaN(O))continue;X+=O*this.sent[V],U+=this.sent[V]**2,M.push([this.sent[V],O])}if(U<C.LEARN_PX**2)continue;let G=-X/U,q=M.reduce((V,[O,T])=>V+(T+G*O)**2,0)/M.length;if(G>0&&(!Q||q<Q.error))Q={lag:Z,perPixel:G,error:q}}if(Q)this.lag=Q.lag,this.perPixel=Math.min(C.MAX,Math.max(C.MIN,this.perPixel+(Q.perPixel-this.perPixel)*0.5))}static KEPT=40;static LAG_MAX=3;static LEARN_PX=30;static MIN=0.00005;static MAX=0.05}Xj.TurnAxis=C;class P{gain;across;down;vx=0;vy=0;last=new Map;t;turned=!0;constructor(Q=800,Z=0.5){this.gain=Z;this.across=new C(Q),this.down=new C(Q)}see(Q,Z){if(!this.turned)this.across.send(0),this.down.send(0);this.turned=!1;let X=Q.flatMap((q)=>{let V=this.last.get(q.id);return V?[{x:q.x-V.x,y:q.y-V.y}]:[]}),U=this.t===void 0?0:(Z-this.t)/1000;this.t=Z,this.last=new Map(Q.map((q)=>[q.id,{x:q.x,y:q.y}]));let M=X.length?R(X.map((q)=>q.x)):Number.NaN,G=X.length?R(X.map((q)=>q.y)):Number.NaN;this.vx=U>0&&X.length?M/U:0,this.vy=U>0&&X.length?G/U:0,this.across.see(M),this.down.see(G)}turn(Q){let Z=Q.x+this.across.coming()-0.5,X=Q.y+this.down.coming()-0.5;return this.by(Z*this.gain/this.across.perPixel,X*this.gain/this.down.perPixel)}sweep(Q){return this.by(Q/this.across.perPixel,0)}own(Q){return{...Q,vx:Q.vx-this.vx,vy:Q.vy-this.vy}}by(Q,Z){let X={kind:"pointer",dx:Math.round(Q),dy:Math.round(Z)};return this.across.send(X.dx),this.down.send(X.dy),this.turned=!0,X}}Xj.ViewTurner=P;function D(Q,Z){if(Z.data&&!Object.entries(Z.data).every(([U,M])=>Q.data?.[U]===M))return!1;if(Z.type===void 0&&Z.text===void 0)return!!Z.data;let X=Z.text?.toLowerCase();return(Q.entities??[]).some((U)=>(Z.type===void 0||U.type===Z.type)&&(X===void 0||(U.text??"").toLowerCase().includes(X)))}Xj.shows=D})(v||={});var L=(J,B)=>typeof J==="number"&&Number.isFinite(J)?J:B,g=(J)=>Array.isArray(J)?J.filter((B)=>typeof B==="string"):void 0,w={x:0.5,y:0.5},Jj={step(J,B,j,z){let Y=B.params??{};j.tracker??=new z.lib.Tracker;let H=j.tracker,$=g(Y.skip)??["friend"],F={types:g(Y.types),tags:g(Y.tags),skip:$},W=H.update(J),N=W.filter((O)=>z.lib.matching([O.entity],F).length>0),R=Y.mode==="view",C=R?o(j,z,Y):void 0;C?.see(W,J.t);let P=j.t===void 0?0:(J.t-j.t)/1000;if(j.t=J.t,J.data?.over===!0){if(!j.over)j.over=!0,z.escalate("round_over",{score:J.data.score});return[]}if(j.over=!1,!N.length){if(!j.empty)j.empty=!0,z.emit("no_target");let O=L(Y.sweep,0.6);return C&&O&&P>0?[C.sweep(O*P)]:[]}j.empty=!1;let D=R?w:j.at??w,Q=z.lib.pick(N,Y.prefer==="largest"||Y.prefer==="first"?Y.prefer:"nearest",D);if(!Q?.entity.box)return[];let Z=z.lib.lead(C?C.own(Q):Q,L(Y.leadMs,40)),X=L(Y.smooth,0),U=(O)=>W.some((T)=>T.entity.box&&z.lib.matching([T.entity],{skip:$}).length===0&&z.lib.inside(O,T.entity.box)),M=Y.fire!==!1&&(j.fired===void 0||J.t-j.fired>=L(Y.cooldownMs,120)),G=[];if(C){if(G.push(C.turn(Z)),M&&z.lib.inside(w,Q.entity.box,0.1)&&!U(w))G.push(z.lib.click(w)),j.fired=J.t;return G}let q=z.lib.approach(D,Z,X);j.at=q;let V=Q.entity.box;if(M&&!U(q)&&(X===0||z.lib.inside(q,{...V,x:Z.x-V.w/2,y:Z.y-V.h/2},0.1)))return j.fired=J.t,[z.lib.click(q)];return[z.lib.move(q)]}};function o(J,B,j){return J.turner??=new B.lib.ViewTurner(L(j.sensitivity,800),Math.min(1,Math.max(0.05,L(j.gain,0.5)))),J.turner}var Qj={step(J,B,j,z){let Y=B.params??{},H={...typeof Y.type==="string"?{type:Y.type}:{},...typeof Y.text==="string"?{text:Y.text}:{},...Y.data&&typeof Y.data==="object"?{data:Y.data}:{}},$=z.lib.shows(J,H),F=Y.gone===!0?!$:$;if(F&&!j.told)j.told=!0,z.escalate(Y.gone===!0?"gone":"seen",{...H});else if(!F)j.told=!1;return[]}},Yj={step(J,B,j,z){let Y=B.params??{};j.tracker??=new z.lib.Tracker;let H=j.tracker,$={types:g(Y.types),tags:g(Y.tags),skip:g(Y.skip)},F=H.update(J),W=F.filter((X)=>z.lib.matching([X.entity],$).length>0),N=Y.mode==="view",R=N?o(j,z,Y):void 0;R?.see(F,J.t);let C=N?w:j.at??w,P=W.find((X)=>X.id===j.id)??z.lib.pick(W,Y.prefer==="largest"||Y.prefer==="first"?Y.prefer:"nearest",C);if(!P){if(j.lostAt??=J.t,!j.lost&&J.t-j.lostAt>=L(Y.lostMs,1000))j.lost=!0,z.escalate("lost",j.id?{id:j.id}:void 0);return[]}j.id=P.id,j.lostAt=void 0,j.lost=!1;let D=z.lib.lead(R?R.own(P):P,L(Y.leadMs,40)),Q={x:Y.axis==="y"?C.x:D.x,y:Y.axis==="x"?C.y:D.y};if(R)return[R.turn(Q)];let Z=z.lib.approach(C,Q,L(Y.smooth,0));return j.at=Z,[z.lib.move(Z)]}},Zj=new Set(["button","link","textbox","searchbox","textarea","textfield","combobox","checkbox","radio","switch","tab","menuitem","option","cell","row","treeitem","slider","spinbutton","listitem","image"]),b=new Set(["textbox","searchbox","textarea","textfield","combobox","spinbutton"]),$j=new Set(["dialog","alertdialog","sheet"]),i=24,n="The goal is reached: nothing more to do",zj="The goal is already reached on this screen: nothing more needs doing.",Bj=new Set(["checkbox","switch","radio","menuitemcheckbox","menuitemradio"]),S=(J)=>[J.type,J.text?JSON.stringify(J.text.slice(0,80)):"",J.value?`= ${JSON.stringify(J.value.slice(0,40))}`:""].filter(Boolean).join(" "),Hj=(J,B)=>{let j=J.type.toLowerCase(),z=JSON.stringify((J.text??"").slice(0,80));if(Bj.has(j)&&(J.value==="on"||J.value==="off"))return`Turning the ${j} ${z} ${J.value==="on"?"off":"on"} (it is ${J.value} now) is the right next step toward the goal.`;if(b.has(j)){let Y=Object.keys(B).find((F)=>(J.text??"").toLowerCase().includes(F.toLowerCase())),H=Y===void 0?"":`${JSON.stringify(String(B[Y]).slice(0,40))} `,$=J.value?` (it holds ${JSON.stringify(J.value.slice(0,40))})`:"";return`Typing ${H}into the field ${z}${$} is the right next step toward the goal.`}return`Clicking the ${j} ${z} is the right next step toward the goal.`},a=(J,B,j)=>{let z=JSON.stringify([j,B.plan??null,B.fill??null]);if(J.doneKey!==z)J.doneKey=z,J.donePath=[...J.path];return J.donePath},Kj=(J)=>(J.entities??[]).map((B)=>`${B.id}:${B.text??""}:${B.value??""}`).join("|"),r=(J,B)=>{let j=B.trim().toLowerCase();return J.find((z)=>z.id===B||(z.text??"").trim().toLowerCase()===j)??J.find((z)=>!!j&&(z.text??"").toLowerCase().includes(j))},m=(J)=>{let B=J.toLowerCase(),j=B.match(/[a-z0-9]+/g)??[],z=[...B].filter((Y)=>Y.charCodeAt(0)>127);return new Set([...j,...z.slice(0,-1).map((Y,H)=>Y+z[H+1])])},Uj={step(J,B,j,z){let Y=B.params??{},H=typeof B.goal==="string"&&B.goal.trim()?B.goal.trim():typeof Y.goal==="string"?Y.goal:"",$=Y.fill&&typeof Y.fill==="object"?Y.fill:{},F=JSON.stringify(B);if(j.given!==F){j.given=F,j.paused=!1,j.stale=0,j.steps??=[],j.path??=[],j.task??=H,j.next=typeof Y.next==="string"?Y.next:void 0;let K=JSON.stringify(Y.plan??null);if(j.plan!==K)j.plan=K,j.at=0}if(!H){if(!j.paused)j.paused=!0,z.escalate("no_goal");return[]}let W=j.steps,N=Kj(J);if(j.actedAt!==void 0){let K=N!==j.actedSign;if(!K&&J.t-j.actedAt<L(Y.settleMs,1500))return[];if(j.actedAt=void 0,j.by)z.emit("decision",{by:j.by,missed:!K}),j.by=void 0;if(j.stale=K?0:j.stale+1,j.stale>=2)return j.paused=!0,z.escalate("stuck",{steps:W.slice(-3)}),[]}if(j.paused)return[];let R=(K,_)=>{return j.paused=!0,z.escalate(K,_),[]};if(W.length>=L(Y.maxSteps,20))return R("max_steps",{steps:W.length});let C=(J.entities??[]).filter((K)=>Zj.has(K.type.toLowerCase())&&(K.text||K.value||b.has(K.type.toLowerCase()))),P=(K,_)=>{if(b.has(K.type.toLowerCase())){let I=Object.keys($).find((k)=>(K.text??"").toLowerCase().includes(k.toLowerCase()));if(I===void 0){R("needs_text",{field:S(K),id:K.id});return}if(K.value===String($[I])){R("unsure",{why:"that field already holds it",field:S(K)});return}return W.push(`typed into ${S(K)}`),j.path.push(K.text??K.id),j.actedAt=J.t,j.seenSign=void 0,j.actedSign=N,j.by=_,[{kind:"text",ref:K.id,text:String($[I])}]}return W.push(`clicked ${S(K)}`),j.path.push(K.text??K.id),j.actedAt=J.t,j.seenSign=void 0,j.actedSign=N,j.by=_,[{kind:"pointer",ref:K.id}]};if(j.next){let K=C.find((_)=>_.id===j.next)??(J.entities??[]).find((_)=>_.id===j.next);return j.next=void 0,K?P(K)??[]:R("unsure",{why:"params.next names no element now"})}let D=J.entities??[],Q=D.findIndex((K)=>$j.has(K.type.toLowerCase())),Z=Q<0?C:C.filter((K)=>D.indexOf(K)>Q),X=Array.isArray(Y.plan)?Y.plan.map(String):[],U=X[j.at];if(X.length){let K=Z.find((I)=>{if(!b.has(I.type.toLowerCase()))return!1;let k=Object.keys($).find((jj)=>(I.text??"").toLowerCase().includes(jj.toLowerCase()));return k!==void 0&&I.value!==String($[k])&&!W.includes(`typed into ${S(I)}`)});if(K){if(r([K],U??""))j.at=j.at+1;return P(K)??[]}if(U===void 0)return R("done",{steps:W.length,plan:X.length,goal:j.task||H,path:a(j,Y,H)});let _=r(Z,U);if(_){let I=P(_);if(I)j.at=j.at+1;return I??[]}if(N!==j.seenSign)j.seenSign=N,j.seenAt=J.t;if(Q<0&&J.t-j.seenAt<L(Y.settleMs,1500))return[]}let M=m([H,U??"",...Object.keys($)].join(" ")),G=Z.length<=i?Z:Z.map((K,_)=>({entity:K,at:_,score:[...m(S(K))].filter((I)=>M.has(I)).length})).sort((K,_)=>_.score-K.score||K.at-_.at).slice(0,i).sort((K,_)=>K.at-_.at).map((K)=>K.entity),q=(K)=>Object.entries(K??{}).sort((_,I)=>I[1]-_[1]).slice(0,3).map(([_,I])=>({option:_,p:Math.round(I*100)/100,id:G.find((k)=>S(k)===_)?.id}));if(!z.has("decide")){let K=U!==void 0?Q<0?`the planned step does not show: ${U}`:`a dialog opened: ${D[Q].text??""}`:"no decision model here (L2): pick the next element";return R("unsure",{why:K,decider:"none",options:G.map((_)=>({id:_.id,label:S(_)}))})}let V=(J.entities??[]).slice(0,60).map(S),O=(J.data?.title?`Title: ${String(J.data.title)}\n`:"")+V.join("; ")+(W.length?`\nDone so far: ${W.slice(-5).join("; ")}`:""),T=[...G.map(S),n],f="Goal: "+H+(U!==void 0?`. The next planned step: ${U}`:"")+(Q>=0?`. A dialog is open: ${D[Q].text??""}`:"")+". What should be done next on this screen?",h=z.decide(`nav:${W.length}:${N}`,O,[{choice:f,options:T,means:[...G.map((K)=>Hj(K,$)),zj]}]);if(h===void 0)return[];if(h===null)return R("unsure",{why:"the decision model did not answer",options:G.map((K)=>({id:K.id,label:S(K)}))});let[A]=h.answers;if(!A||A.confidence<L(Y.decideMin,z.decideMin))return R("unsure",{likeliest:q(A?.probs),confidence:Math.round((A?.confidence??0)*100)/100});if(A.answer===n)return R("done",{steps:W.length,goal:j.task||H,path:a(j,Y,H)});let y=G[T.indexOf(String(A.answer))];if(!y)return R("unsure",{likeliest:q(A.probs)});return P(y,h.by)??[]}},p={aim:Jj,track:Yj,watch:Qj,nav:Uj};var d=20000,u={pointer:["click","move","down","up"],key:["tap","down","up"]};function E(J,B,j=Number.NEGATIVE_INFINITY,z=Number.POSITIVE_INFINITY){if(J===void 0)return;if(typeof J!=="number"||!Number.isFinite(J)||J<j||J>z)throw Error(`${B} is a number${j>Number.NEGATIVE_INFINITY?` from ${j} to ${z}`:""}, not ${JSON.stringify(J)}.`);return J}function t(J,B){if(typeof J!=="string"||!J)throw Error(`${B} is a string, not ${JSON.stringify(J)}.`);return J}var l;((qj)=>{function J(Y){if(Y===void 0||Y===null)return[];let H=Array.isArray(Y)?Y:[Y];if(H.length>32)throw Error(`A step gives at most 32 actions, not ${H.length}.`);return H.map(($,F)=>B($,`actions[${F}]`))}qj.actions=J;function B(Y,H="action"){let $=Y??{};switch($.kind){case"pointer":{let F=$.press??"click";if(!u.pointer.includes(F))throw Error(`${H}.press is one of ${u.pointer.join(", ")}.`);let W=E($.x,`${H}.x`,0,1),N=E($.y,`${H}.y`,0,1),R=E($.dx,`${H}.dx`,-1e4,1e4),C=E($.dy,`${H}.dy`,-1e4,1e4);return{kind:"pointer",...W!==void 0?{x:W}:{},...N!==void 0?{y:N}:{},...typeof $.ref==="string"?{ref:$.ref}:{},...R!==void 0?{dx:R}:{},...C!==void 0?{dy:C}:{},...$.press!==void 0?{press:F}:{}}}case"key":{let F=$.press??"tap";if(!u.key.includes(F))throw Error(`${H}.press is one of ${u.key.join(", ")}.`);let W=E($.ms,`${H}.ms`,10,5000);return{kind:"key",key:t($.key,`${H}.key`),...$.press!==void 0?{press:F}:{},...W!==void 0?{ms:W}:{}}}case"text":return{kind:"text",text:String($.text??""),...typeof $.ref==="string"?{ref:$.ref}:{}};case"scroll":{let F=E($.dx,`${H}.dx`),W=E($.dy,`${H}.dy`);return{kind:"scroll",...F!==void 0?{dx:F}:{},...W!==void 0?{dy:W}:{},...typeof $.ref==="string"?{ref:$.ref}:{}}}case"verb":return{kind:"verb",name:t($.name,`${H}.name`),...$.input&&typeof $.input==="object"?{input:$.input}:{}};default:throw Error(`${H}.kind is pointer, key, text, scroll or verb, not ${JSON.stringify($.kind)}.`)}}qj.action=B;function j(Y){let H=Y&&typeof Y==="object"?Y:{},$=E(H.ttl,"intent.ttl",0.1,86400);return{...typeof H.goal==="string"?{goal:H.goal}:{},...H.params&&typeof H.params==="object"&&!Array.isArray(H.params)?{params:H.params}:{},...$!==void 0?{ttl:$}:{},...Array.isArray(H.reportOn)?{reportOn:H.reportOn.filter((F)=>typeof F==="string")}:{}}}qj.intent=j;function z(Y,H){if(!Y.length)return 0;let $=[...Y].sort((F,W)=>F-W);return $[Math.min($.length-1,Math.floor($.length*H))]}qj.percentile=z})(l||={});class x{now;program;memory={};constructor(J=()=>Date.now()){this.now=J}load(J){let B=x.compile(J),j={};return B.init?.(j,this.context([],{},[])),this.program=B,this.memory=j,J.use??"code"}step(J,B,j={}){let z=[],Y=[];if(!this.program)return{actions:[],events:z,error:"No program is loaded."};let H=($)=>Y.length?{...$,decides:Y}:$;try{let $=this.program.step(J,B,this.memory,this.context(z,j,Y)),F=$&&typeof $==="object"&&!Array.isArray($)&&!("kind"in $)?$:{actions:$};for(let W of Array.isArray(F.events)?F.events:[])if(W&&typeof W.type==="string")z.push({type:W.type,at:this.now(),...W.data?{data:W.data}:{},...W.escalate?{escalate:!0}:{}});return H({actions:l.actions(F.actions),events:z})}catch($){return H({actions:[],events:z,error:$ instanceof Error?$.message:String($)})}}context(J,B,j){let z=(H)=>($,F)=>void J.push({type:String($),at:this.now(),...F?{data:F}:{},...H?{escalate:!0}:{}}),Y=B.decideMin!==void 0;return{lib:v,emit:z(!1),escalate:z(!0),has:(H)=>H==="decide"&&Y,decideMin:B.decideMin??1,decide:(H,$,F)=>{if(!Y)return null;let W=B.decided?.[String(H)];if(W)return"error"in W?null:W;if(!j.some((N)=>N.key===String(H)))j.push({key:String(H),ask:{state:String($),questions:F}});return}}}static compile(J){if(J.use!==void 0){let z=p[J.use];if(!z)throw Error(`The library has no program ${JSON.stringify(J.use)}: it has ${Object.keys(p).join(", ")}.`);return z}let B=J.code??"";if(!B.trim())throw Error("A program is one of the library (use) or code that defines function step(observation, intent, memory, ctx).");if(B.length>d)throw Error(`A program is at most ${d} characters.`);let j=Function(`"use strict";\n${B}\n;return { step: typeof step === \'function\' ? step : undefined, init: typeof init === \'function\' ? init : undefined };`)();if(!j.step)throw Error("The program defines no function step(observation, intent, memory, ctx).");return{step:j.step,...j.init?{init:j.init}:{}}}}var c=globalThis;for(let J of["fetch","XMLHttpRequest","WebSocket","EventSource","importScripts","indexedDB","caches","BroadcastChannel","Request","navigator"])try{Object.defineProperty(c,J,{value:void 0,configurable:!1,writable:!1})}catch{}var e=new x;c.onmessage=(J)=>{let B=J.data;try{let j=B.type==="load"?e.load(B.source??{}):e.step(B.observation,B.intent??{},B.extra);c.postMessage({id:B.id,value:j})}catch(j){c.postMessage({id:B.id,error:j instanceof Error?j.message:String(j)})}};})();\n';
|
|
1088
|
+
|
|
1089
|
+
// web-src/desktop-target.ts
|
|
1090
|
+
var ROLES = {
|
|
1091
|
+
AXButton: "button",
|
|
1092
|
+
AXLink: "link",
|
|
1093
|
+
AXTextField: "textfield",
|
|
1094
|
+
AXTextArea: "textarea",
|
|
1095
|
+
AXSearchField: "searchbox",
|
|
1096
|
+
AXComboBox: "combobox",
|
|
1097
|
+
AXCheckBox: "checkbox",
|
|
1098
|
+
AXRadioButton: "radio",
|
|
1099
|
+
AXSwitch: "switch",
|
|
1100
|
+
AXTab: "tab",
|
|
1101
|
+
AXTabGroup: "tablist",
|
|
1102
|
+
AXSheet: "dialog",
|
|
1103
|
+
AXMenuItem: "menuitem",
|
|
1104
|
+
AXMenuBarItem: "menuitem",
|
|
1105
|
+
AXPopUpButton: "combobox",
|
|
1106
|
+
AXMenuButton: "button",
|
|
1107
|
+
AXCell: "cell",
|
|
1108
|
+
AXRow: "row",
|
|
1109
|
+
AXOutlineRow: "treeitem",
|
|
1110
|
+
AXSlider: "slider",
|
|
1111
|
+
AXIncrementor: "spinbutton",
|
|
1112
|
+
AXStaticText: "text",
|
|
1113
|
+
AXImage: "image",
|
|
1114
|
+
AXHeading: "heading",
|
|
1115
|
+
AXDisclosureTriangle: "button"
|
|
1116
|
+
};
|
|
1117
|
+
var LEFT_OUT = new Set([
|
|
1118
|
+
"AXMenu",
|
|
1119
|
+
"AXMenuBar",
|
|
1120
|
+
"AXApplication",
|
|
1121
|
+
"AXWindow",
|
|
1122
|
+
"AXGroup",
|
|
1123
|
+
"AXSplitGroup",
|
|
1124
|
+
"AXScrollArea",
|
|
1125
|
+
"AXLayoutArea",
|
|
1126
|
+
"AXUnknown",
|
|
1127
|
+
"AXToolbar"
|
|
1128
|
+
]);
|
|
1129
|
+
var ELEMENTS_MAX = 300;
|
|
1130
|
+
var DesktopTarget;
|
|
1131
|
+
((DesktopTarget) => {
|
|
1132
|
+
DesktopTarget.PREFIX = "app:";
|
|
1133
|
+
DesktopTarget.HZ = 3;
|
|
1134
|
+
function id(window) {
|
|
1135
|
+
return `${DesktopTarget.PREFIX}${window.pid}:${window.window_id}`;
|
|
1136
|
+
}
|
|
1137
|
+
DesktopTarget.id = id;
|
|
1138
|
+
function parse(id2) {
|
|
1139
|
+
const match = /^app:(\d+):(\d+)$/.exec(id2);
|
|
1140
|
+
return match ? { pid: Number(match[1]), window: Number(match[2]) } : undefined;
|
|
1141
|
+
}
|
|
1142
|
+
DesktopTarget.parse = parse;
|
|
1143
|
+
function title(window) {
|
|
1144
|
+
return window.title && window.title !== window.app_name ? `${window.app_name} · ${window.title}` : window.app_name;
|
|
1145
|
+
}
|
|
1146
|
+
DesktopTarget.title = title;
|
|
1147
|
+
const NOT_APPS = new Set(["Cua Driver"]);
|
|
1148
|
+
function windows(listed, own = []) {
|
|
1149
|
+
const kept = listed.filter((window) => window.is_on_screen !== false && !NOT_APPS.has(window.app_name) && (window.layer ?? 0) === 0 && !own.includes(window.pid) && (window.bounds?.width ?? 100) >= 80 && (window.bounds?.height ?? 100) >= 60);
|
|
1150
|
+
const titled = new Set(kept.filter((window) => window.title).map((window) => window.pid));
|
|
1151
|
+
return kept.filter((window) => window.title || !titled.has(window.pid));
|
|
1152
|
+
}
|
|
1153
|
+
DesktopTarget.windows = windows;
|
|
1154
|
+
const SHOWN_ROW = /^\s*- (AX\w+)(?: = "((?:[^"\\]|\\.)*)")?(?: \(([^)]*)\))?/;
|
|
1155
|
+
const MARKS = /[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
|
|
1156
|
+
function shown(markdown) {
|
|
1157
|
+
const out = [];
|
|
1158
|
+
for (const line of (markdown ?? "").split(`
|
|
1159
|
+
`)) {
|
|
1160
|
+
if (/^\s*- \[\d+\]/.test(line)) {
|
|
1161
|
+
continue;
|
|
1162
|
+
}
|
|
1163
|
+
const match = SHOWN_ROW.exec(line);
|
|
1164
|
+
const role = match?.[1];
|
|
1165
|
+
const text2 = (match?.[2] || match?.[3] || "").replace(MARKS, "").trim();
|
|
1166
|
+
if (role && text2 && !LEFT_OUT.has(role)) {
|
|
1167
|
+
out.push({ type: ROLES[role] ?? role.replace(/^AX/, "").toLowerCase(), text: text2 });
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
return out;
|
|
1171
|
+
}
|
|
1172
|
+
DesktopTarget.shown = shown;
|
|
1173
|
+
function observation(elements, window, markdown) {
|
|
1174
|
+
const entities = shown(markdown).map((one, i) => ({ id: `shown:${i + 1}`, type: one.type, text: one.text }));
|
|
1175
|
+
const tokens = new Map;
|
|
1176
|
+
const seen = new Map;
|
|
1177
|
+
for (const element of elements) {
|
|
1178
|
+
if (LEFT_OUT.has(element.role) || entities.length >= ELEMENTS_MAX) {
|
|
1179
|
+
continue;
|
|
1180
|
+
}
|
|
1181
|
+
const type = ROLES[element.role] ?? element.role.replace(/^AX/, "").toLowerCase();
|
|
1182
|
+
const label2 = (element.label ?? "").trim();
|
|
1183
|
+
const value = element.value === undefined || element.value === null ? "" : String(element.value).trim();
|
|
1184
|
+
if (!label2 && !value && type === "text") {
|
|
1185
|
+
continue;
|
|
1186
|
+
}
|
|
1187
|
+
const base = `${type}:${label2 || value}`;
|
|
1188
|
+
const nth = seen.get(base) ?? 0;
|
|
1189
|
+
seen.set(base, nth + 1);
|
|
1190
|
+
const id2 = nth ? `${base}#${nth + 1}` : base;
|
|
1191
|
+
if (element.element_token) {
|
|
1192
|
+
tokens.set(id2, element.element_token);
|
|
1193
|
+
}
|
|
1194
|
+
const box = element.frame && window && window.width > 0 && window.height > 0 ? {
|
|
1195
|
+
x: (element.frame.x - window.x) / window.width,
|
|
1196
|
+
y: (element.frame.y - window.y) / window.height,
|
|
1197
|
+
w: element.frame.w / window.width,
|
|
1198
|
+
h: element.frame.h / window.height
|
|
1199
|
+
} : undefined;
|
|
1200
|
+
entities.push({ id: id2, type, ...label2 ? { text: label2 } : {}, ...value && value !== label2 ? { value } : {}, ...box ? { box } : {} });
|
|
1201
|
+
}
|
|
1202
|
+
return { observation: { entities }, tokens };
|
|
1203
|
+
}
|
|
1204
|
+
DesktopTarget.observation = observation;
|
|
1205
|
+
function call(action, at, tokens) {
|
|
1206
|
+
const token = (ref) => {
|
|
1207
|
+
if (ref === undefined) {
|
|
1208
|
+
return;
|
|
1209
|
+
}
|
|
1210
|
+
const found = tokens.get(ref);
|
|
1211
|
+
if (found === undefined) {
|
|
1212
|
+
throw new Error(`No element ${JSON.stringify(ref)} in the window now: read it again.`);
|
|
1213
|
+
}
|
|
1214
|
+
return found;
|
|
1215
|
+
};
|
|
1216
|
+
const on = { pid: at.pid, window_id: at.window };
|
|
1217
|
+
switch (action.kind) {
|
|
1218
|
+
case "pointer": {
|
|
1219
|
+
const element = token(action.ref);
|
|
1220
|
+
if (element === undefined) {
|
|
1221
|
+
throw new Error('A desktop app takes a click on an entity: {kind: "pointer", ref}.');
|
|
1222
|
+
}
|
|
1223
|
+
return { tool: "click", args: { element_token: element } };
|
|
1224
|
+
}
|
|
1225
|
+
case "text": {
|
|
1226
|
+
const element = token(action.ref);
|
|
1227
|
+
return { tool: "type_text", args: element !== undefined ? { element_token: element, text: action.text } : { ...on, text: action.text } };
|
|
1228
|
+
}
|
|
1229
|
+
case "key": {
|
|
1230
|
+
const parts = action.key.split("+");
|
|
1231
|
+
const key = parts.pop().toLowerCase();
|
|
1232
|
+
const named2 = key === "enter" ? "return" : key;
|
|
1233
|
+
return parts.length ? { tool: "hotkey", args: { ...on, keys: [...parts.map((part) => part.toLowerCase() === "meta" ? "cmd" : part.toLowerCase()), named2] } } : { tool: "press_key", args: { ...on, key: named2 } };
|
|
1234
|
+
}
|
|
1235
|
+
case "scroll": {
|
|
1236
|
+
const element = token(action.ref);
|
|
1237
|
+
const dy = action.dy ?? 0;
|
|
1238
|
+
return {
|
|
1239
|
+
tool: "scroll",
|
|
1240
|
+
args: {
|
|
1241
|
+
...element !== undefined ? { element_token: element } : on,
|
|
1242
|
+
direction: dy < 0 ? "up" : "down",
|
|
1243
|
+
amount: Math.max(1, Math.round(Math.abs(dy) / 100) || 3)
|
|
1244
|
+
}
|
|
1245
|
+
};
|
|
1246
|
+
}
|
|
1247
|
+
case "verb":
|
|
1248
|
+
throw new Error("A desktop app has no verbs: use pointer, text, key and scroll.");
|
|
1249
|
+
}
|
|
1250
|
+
}
|
|
1251
|
+
DesktopTarget.call = call;
|
|
1252
|
+
})(DesktopTarget ||= {});
|
|
1253
|
+
|
|
1254
|
+
// web-src/reflex-apps-page.ts
|
|
1255
|
+
class ReflexAppsPage {
|
|
1256
|
+
targets;
|
|
1257
|
+
callHost;
|
|
1258
|
+
now;
|
|
1259
|
+
apps = [];
|
|
1260
|
+
constructor(targets, callHost, now = () => Date.now()) {
|
|
1261
|
+
this.targets = targets;
|
|
1262
|
+
this.callHost = callHost;
|
|
1263
|
+
this.now = now;
|
|
1264
|
+
}
|
|
1265
|
+
async refresh() {
|
|
1266
|
+
this.apps = await this.callHost("apps").catch(() => []) ?? [];
|
|
1267
|
+
}
|
|
1268
|
+
list() {
|
|
1269
|
+
return [...this.targets.list(), ...this.apps];
|
|
1270
|
+
}
|
|
1271
|
+
get(id) {
|
|
1272
|
+
return this.targets.get(id) ?? (DesktopTarget.parse(id) ? this.app(id) : undefined);
|
|
1273
|
+
}
|
|
1274
|
+
async observe(id) {
|
|
1275
|
+
if (this.targets.get(id)) {
|
|
1276
|
+
return this.targets.observe(id);
|
|
1277
|
+
}
|
|
1278
|
+
const seen = await this.callHost("appObserve", id);
|
|
1279
|
+
return seen ? { ...seen, t: this.now() } : undefined;
|
|
1280
|
+
}
|
|
1281
|
+
app(id) {
|
|
1282
|
+
const info = this.apps.find((one) => one.id === id) ?? {
|
|
1283
|
+
id,
|
|
1284
|
+
kind: "app",
|
|
1285
|
+
title: id,
|
|
1286
|
+
tier: "tree",
|
|
1287
|
+
actions: ["pointer", "text", "key", "scroll"],
|
|
1288
|
+
hz: DesktopTarget.HZ
|
|
1289
|
+
};
|
|
1290
|
+
return {
|
|
1291
|
+
...info,
|
|
1292
|
+
title: () => info.title,
|
|
1293
|
+
observe: async () => await this.observe(id) ?? {},
|
|
1294
|
+
act: async (actions) => void await this.callHost("appAct", id, actions)
|
|
1295
|
+
};
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
// web-src/reflex-decide-page.ts
|
|
1300
|
+
var INFO_MS = 30000;
|
|
1301
|
+
|
|
1302
|
+
class ReflexDecidePage {
|
|
1303
|
+
callHost;
|
|
1304
|
+
allowed;
|
|
1305
|
+
info;
|
|
1306
|
+
timer;
|
|
1307
|
+
constructor(callHost, allowed) {
|
|
1308
|
+
this.callHost = callHost;
|
|
1309
|
+
this.allowed = allowed;
|
|
1310
|
+
this.refresh();
|
|
1311
|
+
this.timer = setInterval(() => void this.refresh(), INFO_MS);
|
|
1312
|
+
}
|
|
1313
|
+
deps = {
|
|
1314
|
+
min: () => this.allowed() && this.info?.by ? this.info.min : undefined,
|
|
1315
|
+
ask: async (ask) => {
|
|
1316
|
+
try {
|
|
1317
|
+
return await this.callHost("decide", ask);
|
|
1318
|
+
} catch (failure) {
|
|
1319
|
+
this.refresh();
|
|
1320
|
+
return { error: failure instanceof Error ? failure.message : String(failure) };
|
|
1321
|
+
}
|
|
1322
|
+
},
|
|
1323
|
+
report: (by, missed) => void this.callHost("decided", by, missed).catch(() => {
|
|
1324
|
+
return;
|
|
1325
|
+
}),
|
|
1326
|
+
warm: () => void this.callHost("warm").catch(() => {
|
|
1327
|
+
return;
|
|
1328
|
+
})
|
|
1329
|
+
};
|
|
1330
|
+
async refresh() {
|
|
1331
|
+
this.info = await this.callHost("deciders").catch(() => {
|
|
1332
|
+
return;
|
|
1333
|
+
});
|
|
1334
|
+
}
|
|
1335
|
+
dispose() {
|
|
1336
|
+
clearInterval(this.timer);
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
// web-src/reflex-gate.ts
|
|
1341
|
+
var BrowserClock = {
|
|
1342
|
+
now: () => Date.now(),
|
|
1343
|
+
after: (run, ms) => {
|
|
1344
|
+
const timer = setTimeout(run, ms);
|
|
1345
|
+
return () => clearTimeout(timer);
|
|
1346
|
+
}
|
|
1347
|
+
};
|
|
1348
|
+
var GATE_EVENTS = 8;
|
|
1349
|
+
|
|
1350
|
+
class ReflexGate {
|
|
1351
|
+
send;
|
|
1352
|
+
clock;
|
|
1353
|
+
min;
|
|
1354
|
+
max;
|
|
1355
|
+
queue = [];
|
|
1356
|
+
skipped = 0;
|
|
1357
|
+
last = Number.NEGATIVE_INFINITY;
|
|
1358
|
+
cancel;
|
|
1359
|
+
current;
|
|
1360
|
+
constructor(send, clock, min = 2000, max = 1e4) {
|
|
1361
|
+
this.send = send;
|
|
1362
|
+
this.clock = clock;
|
|
1363
|
+
this.min = min;
|
|
1364
|
+
this.max = max;
|
|
1365
|
+
this.current = min;
|
|
1366
|
+
}
|
|
1367
|
+
get interval() {
|
|
1368
|
+
return this.current;
|
|
1369
|
+
}
|
|
1370
|
+
add(event) {
|
|
1371
|
+
this.queue.push(event);
|
|
1372
|
+
if (this.queue.length > GATE_EVENTS) {
|
|
1373
|
+
this.queue.shift();
|
|
1374
|
+
this.skipped++;
|
|
1375
|
+
}
|
|
1376
|
+
if (this.cancel) {
|
|
1377
|
+
return;
|
|
1378
|
+
}
|
|
1379
|
+
const now = this.clock.now();
|
|
1380
|
+
const wait = this.last + this.current - now;
|
|
1381
|
+
if (wait <= 0) {
|
|
1382
|
+
this.flush();
|
|
1383
|
+
} else {
|
|
1384
|
+
this.cancel = this.clock.after(() => {
|
|
1385
|
+
this.cancel = undefined;
|
|
1386
|
+
this.flush();
|
|
1387
|
+
}, wait);
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
flush() {
|
|
1391
|
+
this.cancel?.();
|
|
1392
|
+
this.cancel = undefined;
|
|
1393
|
+
if (!this.queue.length) {
|
|
1394
|
+
return;
|
|
1395
|
+
}
|
|
1396
|
+
const now = this.clock.now();
|
|
1397
|
+
const since = now - this.last;
|
|
1398
|
+
if (since <= this.current * 1.5) {
|
|
1399
|
+
this.current = Math.min(this.max, this.current * 2);
|
|
1400
|
+
} else if (since >= this.current * 15) {
|
|
1401
|
+
this.current = Math.max(this.min, this.current / 2);
|
|
1402
|
+
}
|
|
1403
|
+
const events = this.skipped ? [{ type: "skipped", at: now, data: { count: this.skipped } }, ...this.queue] : this.queue;
|
|
1404
|
+
this.queue = [];
|
|
1405
|
+
this.skipped = 0;
|
|
1406
|
+
this.last = now;
|
|
1407
|
+
this.send(events);
|
|
1408
|
+
}
|
|
1409
|
+
dispose() {
|
|
1410
|
+
this.cancel?.();
|
|
1411
|
+
this.cancel = undefined;
|
|
1412
|
+
this.queue = [];
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
// web-src/reflex-remotes-settings.ts
|
|
1417
|
+
var STYLE = `
|
|
1418
|
+
.ta-reflex-remotes { display: flex; flex-direction: column; gap: 8px; width: 100%; }
|
|
1419
|
+
.ta-reflex-remote { display: flex; align-items: center; gap: 10px; padding: 8px 12px; border: 1px solid var(--ta-border); border-radius: 10px; }
|
|
1420
|
+
.ta-reflex-remote-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
1421
|
+
.ta-reflex-remote-tag { flex: none; color: var(--ta-secondary); font-size: calc(12px * var(--ta-font-scale)); }
|
|
1422
|
+
.ta-reflex-remote-form { display: grid; grid-template-columns: 1fr; gap: 8px; }
|
|
1423
|
+
.ta-reflex-remote-form .ta-reflex-remote-actions { display: flex; align-items: center; gap: 8px; }
|
|
1424
|
+
.ta-reflex-remote-note { margin: 0; color: var(--ta-secondary); font-size: calc(13px * var(--ta-font-scale)); }
|
|
1425
|
+
.ta-reflex-remote-error { margin: 0; color: var(--ta-danger, #e5484d); font-size: calc(13px * var(--ta-font-scale)); overflow-wrap: anywhere; }
|
|
1426
|
+
`;
|
|
1427
|
+
function injectRemotesStyle() {
|
|
1428
|
+
const element = document.createElement("style");
|
|
1429
|
+
element.dataset.taPackage = "ta-reflex";
|
|
1430
|
+
element.textContent = STYLE;
|
|
1431
|
+
document.head.appendChild(element);
|
|
1432
|
+
return () => element.remove();
|
|
1433
|
+
}
|
|
1434
|
+
function RemotesControl({ pi, options }) {
|
|
1435
|
+
const h = pi.React.createElement;
|
|
1436
|
+
const words2 = ReflexWords.of(pi.ui.language);
|
|
1437
|
+
const [list, setList] = pi.React.useState();
|
|
1438
|
+
const [form, setForm] = pi.React.useState({ baseUrl: "", key: "", model: "" });
|
|
1439
|
+
const [error, setError] = pi.React.useState();
|
|
1440
|
+
const [busy, run] = pi.ui.useBusy();
|
|
1441
|
+
pi.React.useEffect(() => {
|
|
1442
|
+
pi.callHost("remotes").then(setList, () => setList([]));
|
|
1443
|
+
}, [pi]);
|
|
1444
|
+
const add = () => run(() => pi.callHost("addRemote", {
|
|
1445
|
+
baseUrl: form.baseUrl,
|
|
1446
|
+
...form.key ? { key: form.key } : {},
|
|
1447
|
+
...form.model ? { model: form.model } : {}
|
|
1448
|
+
}).then((next) => {
|
|
1449
|
+
setList(next);
|
|
1450
|
+
setForm({ baseUrl: "", key: "", model: "" });
|
|
1451
|
+
setError(undefined);
|
|
1452
|
+
}, (failure) => setError(String(failure?.message ?? failure))));
|
|
1453
|
+
const remove = (id) => run(() => pi.callHost("removeRemote", id).then(setList, (failure) => setError(String(failure?.message ?? failure))));
|
|
1454
|
+
const field = (key, placeholder, type = "text") => h("input", {
|
|
1455
|
+
className: "ta-input",
|
|
1456
|
+
type,
|
|
1457
|
+
value: form[key],
|
|
1458
|
+
placeholder,
|
|
1459
|
+
"aria-label": placeholder,
|
|
1460
|
+
autoComplete: "off",
|
|
1461
|
+
spellCheck: false,
|
|
1462
|
+
onChange: (event) => setForm({ ...form, [key]: event.target.value })
|
|
1463
|
+
});
|
|
1464
|
+
const online = options.on("decideOnline");
|
|
1465
|
+
return h("div", { className: "ta-reflex-remotes" }, list?.length ? list.map((one) => h("div", { key: one.id, className: "ta-reflex-remote" }, h("span", { className: "ta-reflex-remote-name", title: one.baseUrl }, one.name), h("span", { className: "ta-reflex-remote-tag" }, one.online ? online ? one.api : words2.remoteOff : words2.remoteHere), h("button", { type: "button", className: "ta-button", disabled: busy, onClick: () => remove(one.id) }, words2.remoteRemove))) : list && h("p", { className: "ta-reflex-remote-note" }, words2.remoteNone), h("div", { className: "ta-reflex-remote-form" }, field("baseUrl", words2.remoteUrl, "url"), field("key", words2.remoteKey, "password"), field("model", words2.remoteModel), h("div", { className: "ta-reflex-remote-actions" }, h("button", { type: "button", className: `ta-button ta-primary${busy ? " ta-busy" : ""}`, disabled: busy || !form.baseUrl.trim(), onClick: add }, words2.remoteAdd)), error && h("p", { className: "ta-reflex-remote-error", role: "alert" }, error)));
|
|
1466
|
+
}
|
|
1467
|
+
|
|
1468
|
+
// web-src/reflex-options.ts
|
|
1469
|
+
var OPTION_KEYS = { aim: "aim", code: "code", decide: "decide", decideOnline: "decideOnline" };
|
|
1470
|
+
var OFF_BY_DEFAULT = new Set(["decideOnline"]);
|
|
1471
|
+
|
|
1472
|
+
class ReflexOptions {
|
|
1473
|
+
storage;
|
|
1474
|
+
off = new Set(OFF_BY_DEFAULT);
|
|
1475
|
+
stop;
|
|
1476
|
+
changes = 0;
|
|
1477
|
+
constructor(storage) {
|
|
1478
|
+
this.storage = storage;
|
|
1479
|
+
const read = () => {
|
|
1480
|
+
const at = this.changes;
|
|
1481
|
+
for (const option of Object.keys(OPTION_KEYS)) {
|
|
1482
|
+
storage.get(OPTION_KEYS[option]).then((value) => {
|
|
1483
|
+
if (at === this.changes) {
|
|
1484
|
+
if (OFF_BY_DEFAULT.has(option) ? value !== true : value === false) {
|
|
1485
|
+
this.off.add(option);
|
|
1486
|
+
} else {
|
|
1487
|
+
this.off.delete(option);
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
});
|
|
1491
|
+
}
|
|
1492
|
+
};
|
|
1493
|
+
read();
|
|
1494
|
+
this.stop = storage.onChange((keys) => {
|
|
1495
|
+
if (keys.some((key) => Object.values(OPTION_KEYS).includes(key))) {
|
|
1496
|
+
read();
|
|
1497
|
+
}
|
|
1498
|
+
});
|
|
1499
|
+
}
|
|
1500
|
+
on(option) {
|
|
1501
|
+
return !this.off.has(option);
|
|
1502
|
+
}
|
|
1503
|
+
set(option, on) {
|
|
1504
|
+
this.changes++;
|
|
1505
|
+
if (on) {
|
|
1506
|
+
this.off.delete(option);
|
|
1507
|
+
} else {
|
|
1508
|
+
this.off.add(option);
|
|
1509
|
+
}
|
|
1510
|
+
return this.storage.set(OPTION_KEYS[option], OFF_BY_DEFAULT.has(option) ? on ? true : null : on ? null : false);
|
|
1511
|
+
}
|
|
1512
|
+
refuses(source) {
|
|
1513
|
+
if (source.use === "aim" && !this.on("aim")) {
|
|
1514
|
+
return "The user turned aiming off (Settings → Live hands): use track or watch, or work it yourself.";
|
|
1515
|
+
}
|
|
1516
|
+
if (source.code !== undefined && !this.on("code")) {
|
|
1517
|
+
return "The user turned programs of yours off (Settings → Live hands): use a program of the library, or reflex_batch.";
|
|
1518
|
+
}
|
|
1519
|
+
return;
|
|
1520
|
+
}
|
|
1521
|
+
dispose() {
|
|
1522
|
+
this.stop();
|
|
1523
|
+
}
|
|
1524
|
+
}
|
|
1525
|
+
function registerOptionSettings(pi, options) {
|
|
1526
|
+
const words2 = () => ReflexWords.of(pi.ui.language);
|
|
1527
|
+
const row = (option, label2, hint) => ({
|
|
1528
|
+
key: option,
|
|
1529
|
+
label: label2,
|
|
1530
|
+
description: hint,
|
|
1531
|
+
render: () => {
|
|
1532
|
+
const [on, setOn] = pi.React.useState(options.on(option));
|
|
1533
|
+
const change = (next) => {
|
|
1534
|
+
setOn(next);
|
|
1535
|
+
return options.set(option, next);
|
|
1536
|
+
};
|
|
1537
|
+
const Switch = pi.ui.Switch;
|
|
1538
|
+
return Switch ? pi.React.createElement(Switch, { checked: on, label: label2(), onChange: change }) : pi.React.createElement("input", {
|
|
1539
|
+
type: "checkbox",
|
|
1540
|
+
role: "switch",
|
|
1541
|
+
className: "ta-switch",
|
|
1542
|
+
checked: on,
|
|
1543
|
+
"aria-checked": on,
|
|
1544
|
+
"aria-label": label2(),
|
|
1545
|
+
onChange: (event) => void change(event.target.checked)
|
|
1546
|
+
});
|
|
1547
|
+
}
|
|
1548
|
+
});
|
|
1549
|
+
pi.registerSettings({
|
|
1550
|
+
title: () => words2().section,
|
|
1551
|
+
icon: pi.ui.icons.Zap ?? pi.ui.icons.Sparkles,
|
|
1552
|
+
group: "ta",
|
|
1553
|
+
rows: [
|
|
1554
|
+
row("aim", () => words2().aim, () => words2().aimHint),
|
|
1555
|
+
row("code", () => words2().code, () => words2().codeHint),
|
|
1556
|
+
row("decide", () => words2().decide, () => words2().decideHint),
|
|
1557
|
+
row("decideOnline", () => words2().decideOnline, () => words2().decideOnlineHint),
|
|
1558
|
+
{
|
|
1559
|
+
key: "remotes",
|
|
1560
|
+
label: () => words2().remotes,
|
|
1561
|
+
description: () => words2().remotesHint,
|
|
1562
|
+
stacked: true,
|
|
1563
|
+
render: () => pi.React.createElement(RemotesControl, { pi, options })
|
|
1564
|
+
}
|
|
1565
|
+
]
|
|
1566
|
+
});
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
// web-src/reflex-batch.ts
|
|
1570
|
+
var BATCH_STEPS_MAX = 50;
|
|
1571
|
+
var BATCH_WAIT_MAX = 1e4;
|
|
1572
|
+
var BATCH_MS_MAX = 30000;
|
|
1573
|
+
var UNTIL_EVERY_MS = 50;
|
|
1574
|
+
var ReflexBatch;
|
|
1575
|
+
((ReflexBatch) => {
|
|
1576
|
+
function steps(value) {
|
|
1577
|
+
if (!Array.isArray(value) || !value.length) {
|
|
1578
|
+
throw new Error("steps is a list of {action}, {wait: ms} or {until: {type?, text?, data?, gone?}, timeoutMs?}.");
|
|
1579
|
+
}
|
|
1580
|
+
if (value.length > BATCH_STEPS_MAX) {
|
|
1581
|
+
throw new Error(`A batch is at most ${BATCH_STEPS_MAX} steps, not ${value.length}.`);
|
|
1582
|
+
}
|
|
1583
|
+
return value.map((one, at) => {
|
|
1584
|
+
if (one && typeof one === "object" && "action" in one) {
|
|
1585
|
+
return { action: ReflexUtil.action(one.action, `steps[${at}].action`) };
|
|
1586
|
+
}
|
|
1587
|
+
if (one && typeof one.wait === "number" && one.wait >= 0 && one.wait <= BATCH_WAIT_MAX) {
|
|
1588
|
+
return { wait: one.wait };
|
|
1589
|
+
}
|
|
1590
|
+
if (one?.until && typeof one.until === "object") {
|
|
1591
|
+
const timeoutMs = typeof one.timeoutMs === "number" ? Math.min(BATCH_WAIT_MAX, Math.max(0, one.timeoutMs)) : 5000;
|
|
1592
|
+
return { until: look(one.until), timeoutMs };
|
|
1593
|
+
}
|
|
1594
|
+
throw new Error(`steps[${at}] is {action}, {wait: 0 to ${BATCH_WAIT_MAX}} or {until, timeoutMs?}.`);
|
|
1595
|
+
});
|
|
1596
|
+
}
|
|
1597
|
+
ReflexBatch.steps = steps;
|
|
1598
|
+
function look(value) {
|
|
1599
|
+
return {
|
|
1600
|
+
...typeof value.type === "string" ? { type: value.type } : {},
|
|
1601
|
+
...typeof value.text === "string" ? { text: value.text } : {},
|
|
1602
|
+
...value.data && typeof value.data === "object" ? { data: value.data } : {},
|
|
1603
|
+
...value.gone === true ? { gone: true } : {}
|
|
1604
|
+
};
|
|
1605
|
+
}
|
|
1606
|
+
ReflexBatch.look = look;
|
|
1607
|
+
function seen(observation, until) {
|
|
1608
|
+
const shown = !!observation && ProgramLib.shows(observation, until);
|
|
1609
|
+
return until.gone ? !shown : shown;
|
|
1610
|
+
}
|
|
1611
|
+
ReflexBatch.seen = seen;
|
|
1612
|
+
async function run(target, observe, steps2, clock) {
|
|
1613
|
+
const started = clock.now();
|
|
1614
|
+
const sleep = (ms) => new Promise((resolve) => clock.after(resolve, ms));
|
|
1615
|
+
let done = 0;
|
|
1616
|
+
for (const [at, step] of steps2.entries()) {
|
|
1617
|
+
const left = BATCH_MS_MAX - (clock.now() - started);
|
|
1618
|
+
try {
|
|
1619
|
+
if ("action" in step) {
|
|
1620
|
+
if (!target.actions.includes(step.action.kind)) {
|
|
1621
|
+
throw new Error(`The target takes ${target.actions.join(", ")} actions only.`);
|
|
1622
|
+
}
|
|
1623
|
+
await target.act([step.action]);
|
|
1624
|
+
} else if ("wait" in step) {
|
|
1625
|
+
await sleep(Math.min(step.wait, Math.max(0, left)));
|
|
1626
|
+
} else {
|
|
1627
|
+
const until = started + Math.min(BATCH_MS_MAX, clock.now() - started + (step.timeoutMs ?? 5000));
|
|
1628
|
+
while (!seen(await observe(), step.until)) {
|
|
1629
|
+
if (clock.now() >= until) {
|
|
1630
|
+
throw new Error(`What it waited for did not ${step.until.gone ? "go" : "show"} in time.`);
|
|
1631
|
+
}
|
|
1632
|
+
await sleep(UNTIL_EVERY_MS);
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
done++;
|
|
1636
|
+
} catch (failure) {
|
|
1637
|
+
return { done, failed: { at, error: failure instanceof Error ? failure.message : String(failure) }, ms: clock.now() - started };
|
|
1638
|
+
}
|
|
1639
|
+
if (clock.now() - started >= BATCH_MS_MAX && at < steps2.length - 1) {
|
|
1640
|
+
return { done, failed: { at: at + 1, error: `A batch takes ${BATCH_MS_MAX / 1000} s at most.` }, ms: clock.now() - started };
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
return { done, ms: clock.now() - started };
|
|
1644
|
+
}
|
|
1645
|
+
ReflexBatch.run = run;
|
|
1646
|
+
})(ReflexBatch ||= {});
|
|
1647
|
+
|
|
1648
|
+
// web-src/reflex-run.ts
|
|
1649
|
+
var FAILURES_MAX = 5;
|
|
1650
|
+
var HZ_MAX = 60;
|
|
1651
|
+
var DEFAULT_HZ = 30;
|
|
1652
|
+
var TIMES_KEPT = 512;
|
|
1653
|
+
var DECIDED_KEPT = 64;
|
|
1654
|
+
|
|
1655
|
+
class ReflexRun {
|
|
1656
|
+
id;
|
|
1657
|
+
info;
|
|
1658
|
+
deps;
|
|
1659
|
+
program;
|
|
1660
|
+
programName;
|
|
1661
|
+
intent = {};
|
|
1662
|
+
intentAt;
|
|
1663
|
+
state = "waiting";
|
|
1664
|
+
why;
|
|
1665
|
+
busy = false;
|
|
1666
|
+
paused = false;
|
|
1667
|
+
cancel;
|
|
1668
|
+
started;
|
|
1669
|
+
gate;
|
|
1670
|
+
times = [];
|
|
1671
|
+
steps = 0;
|
|
1672
|
+
ran = 0;
|
|
1673
|
+
runningSince;
|
|
1674
|
+
actions = 0;
|
|
1675
|
+
dropped = 0;
|
|
1676
|
+
errors = 0;
|
|
1677
|
+
failures = 0;
|
|
1678
|
+
error;
|
|
1679
|
+
events = 0;
|
|
1680
|
+
escalations = 0;
|
|
1681
|
+
last;
|
|
1682
|
+
decided = new Map;
|
|
1683
|
+
asking = new Set;
|
|
1684
|
+
decisions = 0;
|
|
1685
|
+
constructor(id, info, deps) {
|
|
1686
|
+
this.id = id;
|
|
1687
|
+
this.info = info;
|
|
1688
|
+
this.deps = deps;
|
|
1689
|
+
this.started = deps.clock.now();
|
|
1690
|
+
this.intentAt = this.started;
|
|
1691
|
+
this.gate = new ReflexGate((events) => deps.tell(events, this.summary()), deps.clock);
|
|
1692
|
+
}
|
|
1693
|
+
get period() {
|
|
1694
|
+
return 1000 / Math.min(HZ_MAX, this.info.hz ?? DEFAULT_HZ);
|
|
1695
|
+
}
|
|
1696
|
+
get level() {
|
|
1697
|
+
return !this.program ? "L1" : this.deps.decide?.min() !== undefined ? "L3" : "L2";
|
|
1698
|
+
}
|
|
1699
|
+
get observation() {
|
|
1700
|
+
return this.last;
|
|
1701
|
+
}
|
|
1702
|
+
async start(program, intent) {
|
|
1703
|
+
this.setIntent(intent ?? {});
|
|
1704
|
+
if (program) {
|
|
1705
|
+
if (this.deps.decide?.min() !== undefined) {
|
|
1706
|
+
this.deps.decide.warm?.();
|
|
1707
|
+
}
|
|
1708
|
+
await this.setProgram(program);
|
|
1709
|
+
} else {
|
|
1710
|
+
this.wait("no_program");
|
|
1711
|
+
this.last = await this.deps.observe();
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
setIntent(intent) {
|
|
1715
|
+
this.intent = intent;
|
|
1716
|
+
this.intentAt = this.deps.clock.now();
|
|
1717
|
+
if (this.program && this.state === "waiting") {
|
|
1718
|
+
this.go();
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
async setProgram(source) {
|
|
1722
|
+
const host = this.deps.host(source);
|
|
1723
|
+
try {
|
|
1724
|
+
this.programName = await host.load(source);
|
|
1725
|
+
} catch (failure) {
|
|
1726
|
+
host.dispose();
|
|
1727
|
+
throw failure;
|
|
1728
|
+
}
|
|
1729
|
+
this.program?.dispose();
|
|
1730
|
+
this.program = host;
|
|
1731
|
+
this.failures = 0;
|
|
1732
|
+
this.error = undefined;
|
|
1733
|
+
this.go();
|
|
1734
|
+
}
|
|
1735
|
+
stop(why) {
|
|
1736
|
+
if (this.state !== "stopped") {
|
|
1737
|
+
this.ranUntilNow();
|
|
1738
|
+
this.halt();
|
|
1739
|
+
this.program?.dispose();
|
|
1740
|
+
this.program = undefined;
|
|
1741
|
+
this.state = "stopped";
|
|
1742
|
+
this.why = why;
|
|
1743
|
+
this.resume();
|
|
1744
|
+
this.gate.flush();
|
|
1745
|
+
this.gate.dispose();
|
|
1746
|
+
}
|
|
1747
|
+
return this.summary();
|
|
1748
|
+
}
|
|
1749
|
+
summary() {
|
|
1750
|
+
const ms = this.deps.clock.now() - this.started;
|
|
1751
|
+
return {
|
|
1752
|
+
target: this.info.id,
|
|
1753
|
+
level: this.level,
|
|
1754
|
+
state: this.state,
|
|
1755
|
+
...this.why ? { why: this.why } : {},
|
|
1756
|
+
...this.programName ? { program: this.programName } : {},
|
|
1757
|
+
ms,
|
|
1758
|
+
hz: this.running() > 0 ? Math.round(this.steps * 1e4 / this.running()) / 10 : 0,
|
|
1759
|
+
steps: this.steps,
|
|
1760
|
+
actions: this.actions,
|
|
1761
|
+
dropped: this.dropped,
|
|
1762
|
+
errors: this.errors,
|
|
1763
|
+
...this.error ? { error: this.error } : {},
|
|
1764
|
+
...this.decisions ? { decisions: this.decisions } : {},
|
|
1765
|
+
events: this.events,
|
|
1766
|
+
escalations: this.escalations,
|
|
1767
|
+
gateMs: this.gate.interval,
|
|
1768
|
+
...this.times.length ? { stepMs: { p50: ReflexUtil.percentile(this.times, 0.5), p95: ReflexUtil.percentile(this.times, 0.95) } } : {}
|
|
1769
|
+
};
|
|
1770
|
+
}
|
|
1771
|
+
async tick() {
|
|
1772
|
+
if (this.busy) {
|
|
1773
|
+
this.dropped++;
|
|
1774
|
+
return;
|
|
1775
|
+
}
|
|
1776
|
+
const program = this.program;
|
|
1777
|
+
if (this.state !== "running" || !program) {
|
|
1778
|
+
return;
|
|
1779
|
+
}
|
|
1780
|
+
const now = this.deps.clock.now();
|
|
1781
|
+
if (this.intent.ttl !== undefined && now - this.intentAt > this.intent.ttl * 1000) {
|
|
1782
|
+
this.wait("intent_expired");
|
|
1783
|
+
this.escalate({ type: "intent_expired", at: now, data: { ttl: this.intent.ttl } });
|
|
1784
|
+
return;
|
|
1785
|
+
}
|
|
1786
|
+
this.busy = true;
|
|
1787
|
+
try {
|
|
1788
|
+
const observation = await this.deps.observe();
|
|
1789
|
+
const target = this.deps.target();
|
|
1790
|
+
if (!observation || !target) {
|
|
1791
|
+
this.escalate({ type: "target_gone", at: this.deps.clock.now() });
|
|
1792
|
+
this.stop("target_gone");
|
|
1793
|
+
return;
|
|
1794
|
+
}
|
|
1795
|
+
this.last = observation;
|
|
1796
|
+
const result = await program.step(observation, this.intent, this.extra());
|
|
1797
|
+
if (this.state !== "running" || program !== this.program) {
|
|
1798
|
+
return;
|
|
1799
|
+
}
|
|
1800
|
+
this.steps++;
|
|
1801
|
+
const allowed = result.actions.filter((action) => this.info.actions.includes(action.kind));
|
|
1802
|
+
if (allowed.length < result.actions.length) {
|
|
1803
|
+
result.error ??= `The target takes ${this.info.actions.join(", ")} actions only.`;
|
|
1804
|
+
}
|
|
1805
|
+
if (allowed.length) {
|
|
1806
|
+
await target.act(allowed);
|
|
1807
|
+
this.actions += allowed.length;
|
|
1808
|
+
}
|
|
1809
|
+
this.time(this.deps.clock.now() - observation.t);
|
|
1810
|
+
for (const event of result.events) {
|
|
1811
|
+
this.event(event);
|
|
1812
|
+
}
|
|
1813
|
+
for (const asked of result.decides ?? []) {
|
|
1814
|
+
this.ask(asked.key, asked.ask);
|
|
1815
|
+
}
|
|
1816
|
+
if (result.error) {
|
|
1817
|
+
this.failed(result.error, program);
|
|
1818
|
+
} else {
|
|
1819
|
+
this.failures = 0;
|
|
1820
|
+
}
|
|
1821
|
+
} catch (failure) {
|
|
1822
|
+
this.failed(failure instanceof Error ? failure.message : String(failure), program);
|
|
1823
|
+
} finally {
|
|
1824
|
+
this.busy = false;
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
extra() {
|
|
1828
|
+
const min = this.deps.decide?.min();
|
|
1829
|
+
return min === undefined ? {} : { decideMin: min, ...this.decided.size ? { decided: Object.fromEntries(this.decided) } : {} };
|
|
1830
|
+
}
|
|
1831
|
+
ask(key, ask) {
|
|
1832
|
+
const decide = this.deps.decide;
|
|
1833
|
+
if (!decide || this.decided.has(key) || this.asking.has(key)) {
|
|
1834
|
+
return;
|
|
1835
|
+
}
|
|
1836
|
+
this.asking.add(key);
|
|
1837
|
+
this.decisions++;
|
|
1838
|
+
decide.ask(ask).catch((failure) => ({ error: failure instanceof Error ? failure.message : String(failure) })).then((outcome) => {
|
|
1839
|
+
this.asking.delete(key);
|
|
1840
|
+
this.decided.set(key, outcome);
|
|
1841
|
+
if (this.decided.size > DECIDED_KEPT) {
|
|
1842
|
+
this.decided.delete(this.decided.keys().next().value);
|
|
1843
|
+
}
|
|
1844
|
+
});
|
|
1845
|
+
}
|
|
1846
|
+
event(event) {
|
|
1847
|
+
if (event.type === "decision" && typeof event.data?.by === "string") {
|
|
1848
|
+
this.deps.decide?.report(event.data.by, event.data.missed === true);
|
|
1849
|
+
}
|
|
1850
|
+
this.events++;
|
|
1851
|
+
if (event.escalate || this.intent.reportOn?.includes(event.type)) {
|
|
1852
|
+
this.escalate(event);
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
escalate(event) {
|
|
1856
|
+
this.escalations++;
|
|
1857
|
+
this.gate.add({ ...event, escalate: true });
|
|
1858
|
+
}
|
|
1859
|
+
failed(error, program) {
|
|
1860
|
+
this.errors++;
|
|
1861
|
+
this.failures++;
|
|
1862
|
+
this.error = error;
|
|
1863
|
+
if (this.failures >= FAILURES_MAX || !program.alive()) {
|
|
1864
|
+
program.dispose();
|
|
1865
|
+
if (this.program === program) {
|
|
1866
|
+
this.program = undefined;
|
|
1867
|
+
}
|
|
1868
|
+
this.wait("program_failed");
|
|
1869
|
+
this.escalate({ type: "program_failed", at: this.deps.clock.now(), data: { error, level: this.level } });
|
|
1870
|
+
}
|
|
1871
|
+
}
|
|
1872
|
+
running() {
|
|
1873
|
+
return this.ran + (this.runningSince === undefined ? 0 : this.deps.clock.now() - this.runningSince);
|
|
1874
|
+
}
|
|
1875
|
+
ranUntilNow() {
|
|
1876
|
+
if (this.runningSince !== undefined) {
|
|
1877
|
+
this.ran += this.deps.clock.now() - this.runningSince;
|
|
1878
|
+
this.runningSince = undefined;
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
wait(why) {
|
|
1882
|
+
this.ranUntilNow();
|
|
1883
|
+
this.halt();
|
|
1884
|
+
this.state = "waiting";
|
|
1885
|
+
this.why = why;
|
|
1886
|
+
if (!this.paused && this.info.pausable) {
|
|
1887
|
+
this.paused = true;
|
|
1888
|
+
this.deps.target()?.pause?.();
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
go() {
|
|
1892
|
+
if (this.state === "stopped") {
|
|
1893
|
+
return;
|
|
1894
|
+
}
|
|
1895
|
+
this.runningSince ??= this.deps.clock.now();
|
|
1896
|
+
this.state = "running";
|
|
1897
|
+
this.why = undefined;
|
|
1898
|
+
this.resume();
|
|
1899
|
+
if (!this.cancel) {
|
|
1900
|
+
this.loop();
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
loop() {
|
|
1904
|
+
this.cancel = this.deps.clock.after(() => {
|
|
1905
|
+
this.cancel = undefined;
|
|
1906
|
+
if (this.state === "running") {
|
|
1907
|
+
this.tick();
|
|
1908
|
+
this.loop();
|
|
1909
|
+
}
|
|
1910
|
+
}, this.period);
|
|
1911
|
+
}
|
|
1912
|
+
halt() {
|
|
1913
|
+
this.cancel?.();
|
|
1914
|
+
this.cancel = undefined;
|
|
1915
|
+
}
|
|
1916
|
+
resume() {
|
|
1917
|
+
if (this.paused) {
|
|
1918
|
+
this.paused = false;
|
|
1919
|
+
this.deps.target()?.resume?.();
|
|
1920
|
+
}
|
|
1921
|
+
}
|
|
1922
|
+
time(ms) {
|
|
1923
|
+
this.times.push(ms);
|
|
1924
|
+
if (this.times.length > TIMES_KEPT) {
|
|
1925
|
+
this.times.shift();
|
|
1926
|
+
}
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
// web-src/reflex-page.ts
|
|
1931
|
+
var RUNS_MAX = 8;
|
|
1932
|
+
|
|
1933
|
+
class ReflexPage {
|
|
1934
|
+
deps;
|
|
1935
|
+
runs = new Map;
|
|
1936
|
+
constructor(deps) {
|
|
1937
|
+
this.deps = deps;
|
|
1938
|
+
}
|
|
1939
|
+
reach() {
|
|
1940
|
+
return this.deps.workers ? { level: "L2" } : { level: "L2", why: "Only programs of the library run here: this page cannot start a worker for code." };
|
|
1941
|
+
}
|
|
1942
|
+
async answer(ask) {
|
|
1943
|
+
switch (ask.kind) {
|
|
1944
|
+
case "targets":
|
|
1945
|
+
await this.deps.refresh?.();
|
|
1946
|
+
return { kind: "targets", reach: this.reach(), targets: this.deps.targets.list() };
|
|
1947
|
+
case "start":
|
|
1948
|
+
return this.start(ask.run, ask.target, ask.program, ask.intent, ask.who);
|
|
1949
|
+
case "batch":
|
|
1950
|
+
return this.batch(ask.target, ask.steps);
|
|
1951
|
+
default:
|
|
1952
|
+
return this.steer(ask);
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
stopByUser(id) {
|
|
1956
|
+
const run = this.runs.get(id);
|
|
1957
|
+
if (run) {
|
|
1958
|
+
this.end(run, run.stop("user"), [{ type: "stopped", at: this.deps.clock.now(), data: { by: "user" }, escalate: true }]);
|
|
1959
|
+
}
|
|
1960
|
+
}
|
|
1961
|
+
dispose() {
|
|
1962
|
+
for (const run of [...this.runs.values()]) {
|
|
1963
|
+
this.end(run, run.stop("page_closed"), [{ type: "stopped", at: this.deps.clock.now(), data: { by: "page" }, escalate: true }]);
|
|
1964
|
+
}
|
|
1965
|
+
}
|
|
1966
|
+
async start(id, target, program, intent, who) {
|
|
1967
|
+
let spec = this.deps.targets.get(target);
|
|
1968
|
+
if (!spec && this.deps.refresh) {
|
|
1969
|
+
await this.deps.refresh();
|
|
1970
|
+
spec = this.deps.targets.get(target);
|
|
1971
|
+
}
|
|
1972
|
+
if (!spec) {
|
|
1973
|
+
return { kind: "missing", reach: this.reach(), what: `target ${target}` };
|
|
1974
|
+
}
|
|
1975
|
+
if (this.runs.size >= RUNS_MAX) {
|
|
1976
|
+
throw new Error(`A page keeps ${RUNS_MAX} runs at most: stop one first.`);
|
|
1977
|
+
}
|
|
1978
|
+
const info = this.deps.targets.list().find((one) => one.id === target) ?? infoOf(spec);
|
|
1979
|
+
const run = new ReflexRun(id, info, {
|
|
1980
|
+
target: () => this.deps.targets.get(target),
|
|
1981
|
+
observe: () => this.deps.targets.observe(target).then((seen) => seen ?? undefined),
|
|
1982
|
+
host: (source) => this.host(source),
|
|
1983
|
+
tell: (events, summary) => this.told(run, events, summary),
|
|
1984
|
+
clock: this.deps.clock,
|
|
1985
|
+
...this.deps.decide ? { decide: this.deps.decide } : {}
|
|
1986
|
+
});
|
|
1987
|
+
await run.start(program, ReflexUtil.intent(intent));
|
|
1988
|
+
this.runs.set(id, run);
|
|
1989
|
+
this.deps.shown?.({ id, info, ...who ? { who } : {} }, true);
|
|
1990
|
+
return this.runAnswer(run);
|
|
1991
|
+
}
|
|
1992
|
+
async steer(ask) {
|
|
1993
|
+
const run = this.runs.get(ask.run);
|
|
1994
|
+
if (!run) {
|
|
1995
|
+
return { kind: "missing", reach: this.reach(), what: `run ${ask.run}` };
|
|
1996
|
+
}
|
|
1997
|
+
if (ask.kind === "stop") {
|
|
1998
|
+
const summary = run.stop();
|
|
1999
|
+
this.end(run, summary, []);
|
|
2000
|
+
return { kind: "run", reach: this.reach(), info: run.info, ...run.observation ? { observation: run.observation } : {}, summary };
|
|
2001
|
+
}
|
|
2002
|
+
if (ask.kind === "program") {
|
|
2003
|
+
await run.setProgram(ask.program);
|
|
2004
|
+
} else if (ask.kind === "intent" && ask.intent) {
|
|
2005
|
+
run.setIntent(ReflexUtil.intent(ask.intent));
|
|
2006
|
+
}
|
|
2007
|
+
return this.runAnswer(run);
|
|
2008
|
+
}
|
|
2009
|
+
async batch(target, given) {
|
|
2010
|
+
if (!this.deps.targets.get(target)) {
|
|
2011
|
+
await this.deps.refresh?.();
|
|
2012
|
+
}
|
|
2013
|
+
const spec = this.deps.targets.get(target);
|
|
2014
|
+
if (!spec) {
|
|
2015
|
+
return { kind: "missing", reach: this.reach(), what: `target ${target}` };
|
|
2016
|
+
}
|
|
2017
|
+
const observe = () => this.deps.targets.observe(target);
|
|
2018
|
+
const result = await ReflexBatch.run(spec, observe, ReflexBatch.steps(given), this.deps.clock);
|
|
2019
|
+
const info = this.deps.targets.list().find((one) => one.id === target) ?? infoOf(spec);
|
|
2020
|
+
const observation = await observe();
|
|
2021
|
+
return { kind: "batch", reach: { level: "L1" }, info, result, ...observation ? { observation } : {} };
|
|
2022
|
+
}
|
|
2023
|
+
runAnswer(run) {
|
|
2024
|
+
return { kind: "run", reach: this.reach(), info: run.info, ...run.observation ? { observation: run.observation } : {}, summary: run.summary() };
|
|
2025
|
+
}
|
|
2026
|
+
host(source) {
|
|
2027
|
+
const refused = this.deps.refuses?.(source);
|
|
2028
|
+
if (refused) {
|
|
2029
|
+
throw new Error(refused);
|
|
2030
|
+
}
|
|
2031
|
+
if (source.use !== undefined) {
|
|
2032
|
+
return new InlineProgramHost;
|
|
2033
|
+
}
|
|
2034
|
+
const worker = this.deps.worker();
|
|
2035
|
+
if (!worker) {
|
|
2036
|
+
throw new Error("This page cannot start a worker, so code cannot run here: use a program of the library, or reflex_batch.");
|
|
2037
|
+
}
|
|
2038
|
+
return worker;
|
|
2039
|
+
}
|
|
2040
|
+
told(run, events, summary) {
|
|
2041
|
+
this.deps.tell({ run: run.id, target: run.info.id, title: run.info.title, events, summary });
|
|
2042
|
+
if (summary.state === "stopped" && this.runs.get(run.id) === run) {
|
|
2043
|
+
this.runs.delete(run.id);
|
|
2044
|
+
this.deps.shown?.({ id: run.id, info: run.info }, false);
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
end(run, summary, events) {
|
|
2048
|
+
const had = this.runs.get(run.id) === run;
|
|
2049
|
+
if (had) {
|
|
2050
|
+
this.runs.delete(run.id);
|
|
2051
|
+
this.deps.shown?.({ id: run.id, info: run.info }, false);
|
|
2052
|
+
}
|
|
2053
|
+
if (had || events.length) {
|
|
2054
|
+
this.deps.tell({ run: run.id, target: run.info.id, title: run.info.title, events, summary });
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
}
|
|
2058
|
+
function infoOf(spec) {
|
|
2059
|
+
return {
|
|
2060
|
+
id: spec.id,
|
|
2061
|
+
kind: spec.kind,
|
|
2062
|
+
title: typeof spec.title === "function" ? spec.title() : spec.title,
|
|
2063
|
+
tier: spec.tier,
|
|
2064
|
+
actions: spec.actions,
|
|
2065
|
+
...spec.hz ? { hz: spec.hz } : {},
|
|
2066
|
+
...spec.pause ? { pausable: true } : {}
|
|
2067
|
+
};
|
|
2068
|
+
}
|
|
2069
|
+
|
|
2070
|
+
// web-src/reflex-protocol.ts
|
|
2071
|
+
var EVENT_TYPE = "ta-reflex";
|
|
2072
|
+
var REFLEX_TOOLS = ["reflex_targets", "reflex_do", "reflex_start", "reflex_intent", "reflex_program", "reflex_batch", "reflex_stop"];
|
|
2073
|
+
|
|
2074
|
+
// web-src/run-bar.ts
|
|
2075
|
+
class RunBar {
|
|
2076
|
+
pi;
|
|
2077
|
+
runs = new Map;
|
|
2078
|
+
listeners = new Set;
|
|
2079
|
+
shown = false;
|
|
2080
|
+
constructor(pi) {
|
|
2081
|
+
this.pi = pi;
|
|
2082
|
+
}
|
|
2083
|
+
add(run) {
|
|
2084
|
+
this.runs.set(run.id, run);
|
|
2085
|
+
this.changed();
|
|
2086
|
+
}
|
|
2087
|
+
remove(id) {
|
|
2088
|
+
if (this.runs.delete(id)) {
|
|
2089
|
+
this.changed();
|
|
2090
|
+
}
|
|
2091
|
+
}
|
|
2092
|
+
dispose() {
|
|
2093
|
+
this.runs.clear();
|
|
2094
|
+
this.changed();
|
|
2095
|
+
}
|
|
2096
|
+
changed() {
|
|
2097
|
+
if (this.runs.size && !this.shown) {
|
|
2098
|
+
this.shown = true;
|
|
2099
|
+
this.pi.ui.setWidget("ta-reflex", this.view());
|
|
2100
|
+
} else if (!this.runs.size && this.shown) {
|
|
2101
|
+
this.shown = false;
|
|
2102
|
+
this.pi.ui.setWidget("ta-reflex", undefined);
|
|
2103
|
+
}
|
|
2104
|
+
for (const listener of this.listeners) {
|
|
2105
|
+
listener();
|
|
2106
|
+
}
|
|
2107
|
+
}
|
|
2108
|
+
view() {
|
|
2109
|
+
const { React, ui } = this.pi;
|
|
2110
|
+
const h = React.createElement;
|
|
2111
|
+
return () => {
|
|
2112
|
+
const [, render] = React.useState(0);
|
|
2113
|
+
React.useEffect(() => {
|
|
2114
|
+
const listener = () => render((count) => count + 1);
|
|
2115
|
+
this.listeners.add(listener);
|
|
2116
|
+
return () => void this.listeners.delete(listener);
|
|
2117
|
+
}, []);
|
|
2118
|
+
const words2 = ReflexWords.of(ui.language);
|
|
2119
|
+
return h("div", { style: { display: "flex", flexDirection: "column", gap: 4 } }, [...this.runs.values()].map((run) => h("div", { key: run.id, style: { display: "flex", alignItems: "center", gap: 8, fontSize: 13 } }, h("span", {
|
|
2120
|
+
"aria-hidden": true,
|
|
2121
|
+
style: { width: 7, height: 7, borderRadius: 4, background: "var(--ta-accent, #22c55e)", flex: "none" }
|
|
2122
|
+
}), h("span", { style: { flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, ReflexWords.fill(run.who ? words2.workingFor : words2.working, { title: run.title, who: run.who ?? "" })), h("button", {
|
|
2123
|
+
type: "button",
|
|
2124
|
+
onClick: () => run.stop(),
|
|
2125
|
+
style: { border: "none", background: "none", color: "inherit", textDecoration: "underline", cursor: "pointer", padding: 0 }
|
|
2126
|
+
}, words2.stop))));
|
|
2127
|
+
};
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
|
|
2131
|
+
// web-src/told-line.ts
|
|
2132
|
+
var SAID = ["round_over", "intent_expired", "program_failed", "target_gone", "stopped", "seen", "gone", "lost"];
|
|
2133
|
+
var ToldLine;
|
|
2134
|
+
((ToldLine) => {
|
|
2135
|
+
function text2(told, words2) {
|
|
2136
|
+
const what = [...new Set(told.events.map((event) => event.type))].map((type) => SAID.includes(type) ? words2[type] : type).join(words2 === ReflexWords.of("en-US") ? ", " : ",");
|
|
2137
|
+
return ReflexWords.fill(words2.told, { title: told.title ?? told.target, what });
|
|
2138
|
+
}
|
|
2139
|
+
ToldLine.text = text2;
|
|
2140
|
+
function register(pi, type) {
|
|
2141
|
+
const h = pi.React.createElement;
|
|
2142
|
+
pi.registerMessageRenderer(type, ({ message }) => {
|
|
2143
|
+
const told = message.details;
|
|
2144
|
+
if (!told?.events?.length) {
|
|
2145
|
+
return null;
|
|
2146
|
+
}
|
|
2147
|
+
return h("div", {
|
|
2148
|
+
style: {
|
|
2149
|
+
display: "flex",
|
|
2150
|
+
alignItems: "baseline",
|
|
2151
|
+
gap: 8,
|
|
2152
|
+
minWidth: 0,
|
|
2153
|
+
margin: "2px 0",
|
|
2154
|
+
color: "var(--ta-muted)",
|
|
2155
|
+
fontSize: "calc(13px * var(--ta-font-scale))",
|
|
2156
|
+
lineHeight: 1.6
|
|
2157
|
+
}
|
|
2158
|
+
}, h("i", { style: { flex: "none", width: 6, height: 6, borderRadius: "50%", background: "currentColor", transform: "translateY(-1px)" } }), h("span", { style: { minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } }, text2(told, ReflexWords.of(pi.ui.language))));
|
|
2159
|
+
});
|
|
2160
|
+
}
|
|
2161
|
+
ToldLine.register = register;
|
|
2162
|
+
})(ToldLine ||= {});
|
|
2163
|
+
|
|
2164
|
+
// web-src/tool-line.ts
|
|
2165
|
+
var text2 = (value) => typeof value === "string" ? value.trim() : "";
|
|
2166
|
+
var ReflexToolLine;
|
|
2167
|
+
((ReflexToolLine) => {
|
|
2168
|
+
function of(tool, args, words2) {
|
|
2169
|
+
if (!REFLEX_TOOLS.includes(tool)) {
|
|
2170
|
+
return;
|
|
2171
|
+
}
|
|
2172
|
+
const verb = words2[tool];
|
|
2173
|
+
const intent = args.intent && typeof args.intent === "object" ? text2(args.intent.goal) : text2(args.goal);
|
|
2174
|
+
const program = text2(args.use) || (text2(args.code) ? "code" : "");
|
|
2175
|
+
const target = [text2(args.target) || text2(args.run), program, intent].filter(Boolean).join(" · ");
|
|
2176
|
+
return { verb, target: target.slice(0, 60) };
|
|
2177
|
+
}
|
|
2178
|
+
ReflexToolLine.of = of;
|
|
2179
|
+
})(ReflexToolLine ||= {});
|
|
2180
|
+
|
|
2181
|
+
// web-src/index.ts
|
|
2182
|
+
function activate(pi) {
|
|
2183
|
+
const words2 = () => ReflexWords.of(pi.ui.language);
|
|
2184
|
+
pi.registerToolRenderer?.((name, next) => {
|
|
2185
|
+
const line = ReflexToolLine.of(name, {}, words2());
|
|
2186
|
+
return line ? { renderCall: (args) => ReflexToolLine.of(name, args, words2()) ?? line } : next();
|
|
2187
|
+
});
|
|
2188
|
+
ToldLine.register(pi, EVENT_TYPE);
|
|
2189
|
+
const targets = pi.targets;
|
|
2190
|
+
if (!targets) {
|
|
2191
|
+
return () => {
|
|
2192
|
+
return;
|
|
2193
|
+
};
|
|
2194
|
+
}
|
|
2195
|
+
const options = new ReflexOptions(pi.storage);
|
|
2196
|
+
const removeStyle = injectRemotesStyle();
|
|
2197
|
+
registerOptionSettings(pi, options);
|
|
2198
|
+
const bar = new RunBar(pi);
|
|
2199
|
+
const decide = new ReflexDecidePage((method, ...params) => pi.callHost(method, ...params), () => options.on("decide"));
|
|
2200
|
+
const all = new ReflexAppsPage(targets, (method, ...params) => pi.callHost(method, ...params));
|
|
2201
|
+
const page = new ReflexPage({
|
|
2202
|
+
targets: all,
|
|
2203
|
+
refresh: () => all.refresh(),
|
|
2204
|
+
workers: WorkerProgramHost.available(),
|
|
2205
|
+
worker: () => WorkerProgramHost.create(PROGRAM_WORKER_SOURCE),
|
|
2206
|
+
refuses: (source) => options.refuses(source),
|
|
2207
|
+
decide: decide.deps,
|
|
2208
|
+
tell: (told) => void pi.callHost("told", told).catch(() => {
|
|
2209
|
+
return;
|
|
2210
|
+
}),
|
|
2211
|
+
shown: (run, running) => {
|
|
2212
|
+
if (running) {
|
|
2213
|
+
bar.add({ id: run.id, title: run.info.title, ...run.who ? { who: run.who } : {}, stop: () => page.stopByUser(run.id) });
|
|
2214
|
+
} else {
|
|
2215
|
+
bar.remove(run.id);
|
|
2216
|
+
}
|
|
2217
|
+
},
|
|
2218
|
+
clock: BrowserClock
|
|
2219
|
+
});
|
|
2220
|
+
const stopAnswering = pi.ui.answer?.("reflex", (payload) => page.answer(payload));
|
|
2221
|
+
return () => {
|
|
2222
|
+
stopAnswering?.();
|
|
2223
|
+
page.dispose();
|
|
2224
|
+
decide.dispose();
|
|
2225
|
+
bar.dispose();
|
|
2226
|
+
options.dispose();
|
|
2227
|
+
removeStyle();
|
|
2228
|
+
};
|
|
2229
|
+
}
|
|
2230
|
+
export {
|
|
2231
|
+
activate as default
|
|
2232
|
+
};
|