@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
|
@@ -0,0 +1,976 @@
|
|
|
1
|
+
// ../ta-protocol/esm/common/ta-extension-host.js
|
|
2
|
+
var TA_CLOUD_OUTPUT_BYTES = 1024 * 1024;
|
|
3
|
+
var TA_WEBHOOK_MAX_BYTES = 256 * 1024;
|
|
4
|
+
var TA_HOST_EVENT = "ta:host";
|
|
5
|
+
var TaHostUtil;
|
|
6
|
+
(function(TaHostUtil2) {
|
|
7
|
+
TaHostUtil2.WAIT_MS = 1000;
|
|
8
|
+
function reach(events, name, waitMs = TaHostUtil2.WAIT_MS) {
|
|
9
|
+
return new Promise((resolve) => {
|
|
10
|
+
let heard = false;
|
|
11
|
+
let answered = false;
|
|
12
|
+
const timer = setTimeout(() => resolve(undefined), waitMs);
|
|
13
|
+
const request = {
|
|
14
|
+
name,
|
|
15
|
+
heard: () => {
|
|
16
|
+
heard = true;
|
|
17
|
+
},
|
|
18
|
+
resolve: (answer) => {
|
|
19
|
+
answered = true;
|
|
20
|
+
clearTimeout(timer);
|
|
21
|
+
resolve(answer);
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
events.emit(TA_HOST_EVENT, request);
|
|
25
|
+
if (!heard && !answered) {
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
resolve(undefined);
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
TaHostUtil2.reach = reach;
|
|
32
|
+
function marked(systemPrompt, mark) {
|
|
33
|
+
return role(systemPrompt).includes(mark);
|
|
34
|
+
}
|
|
35
|
+
TaHostUtil2.marked = marked;
|
|
36
|
+
function role(systemPrompt) {
|
|
37
|
+
if (!systemPrompt) {
|
|
38
|
+
return "";
|
|
39
|
+
}
|
|
40
|
+
const open = `<addendum>
|
|
41
|
+
`;
|
|
42
|
+
const start = systemPrompt.indexOf(open);
|
|
43
|
+
const context = systemPrompt.indexOf(`<project_context>
|
|
44
|
+
`);
|
|
45
|
+
if (start < 0 || context >= 0 && context < start) {
|
|
46
|
+
return "";
|
|
47
|
+
}
|
|
48
|
+
const end = systemPrompt.indexOf(`
|
|
49
|
+
</addendum>`, start);
|
|
50
|
+
return systemPrompt.slice(start + open.length, end < 0 ? undefined : end);
|
|
51
|
+
}
|
|
52
|
+
TaHostUtil2.role = role;
|
|
53
|
+
})(TaHostUtil || (TaHostUtil = {}));
|
|
54
|
+
var TA_DOUBLE_LOOK = {
|
|
55
|
+
name: "@celljs/ta-web",
|
|
56
|
+
key: "assistant.species",
|
|
57
|
+
given: ["trex", "triceratops", "stegosaurus", "brachiosaurus", "velociraptor", "ankylosaurus", "pteranodon", "parasaurolophus"]
|
|
58
|
+
};
|
|
59
|
+
var TaDoubleLookUtil;
|
|
60
|
+
(function(TaDoubleLookUtil2) {
|
|
61
|
+
function given(id) {
|
|
62
|
+
let hash = 2166136261;
|
|
63
|
+
for (let i = 0;i < id.length; i++) {
|
|
64
|
+
hash = Math.imul(hash ^ id.charCodeAt(i), 16777619);
|
|
65
|
+
}
|
|
66
|
+
return TA_DOUBLE_LOOK.given[(hash >>> 0) % TA_DOUBLE_LOOK.given.length];
|
|
67
|
+
}
|
|
68
|
+
TaDoubleLookUtil2.given = given;
|
|
69
|
+
})(TaDoubleLookUtil || (TaDoubleLookUtil = {}));
|
|
70
|
+
var TA_WITH_OTHERS_MARK = "[ta:speaks-with-others]";
|
|
71
|
+
|
|
72
|
+
// web-src/program-lib.ts
|
|
73
|
+
var clamp = (value) => Math.min(1, Math.max(0, value));
|
|
74
|
+
var ProgramLib;
|
|
75
|
+
((ProgramLib) => {
|
|
76
|
+
function center(box) {
|
|
77
|
+
return { x: box.x + box.w / 2, y: box.y + box.h / 2 };
|
|
78
|
+
}
|
|
79
|
+
ProgramLib.center = center;
|
|
80
|
+
function inside(point, box, margin = 0) {
|
|
81
|
+
const mx = box.w * margin;
|
|
82
|
+
const my = box.h * margin;
|
|
83
|
+
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;
|
|
84
|
+
}
|
|
85
|
+
ProgramLib.inside = inside;
|
|
86
|
+
function matching(entities, filter = {}) {
|
|
87
|
+
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));
|
|
88
|
+
}
|
|
89
|
+
ProgramLib.matching = matching;
|
|
90
|
+
|
|
91
|
+
class Tracker {
|
|
92
|
+
known = new Map;
|
|
93
|
+
update(observation) {
|
|
94
|
+
const seen = [];
|
|
95
|
+
const now = new Set;
|
|
96
|
+
for (const entity of observation.entities ?? []) {
|
|
97
|
+
if (!entity.box) {
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const { x, y } = center(entity.box);
|
|
101
|
+
const before = this.known.get(entity.id);
|
|
102
|
+
const dt = before ? (observation.t - before.t) / 1000 : 0;
|
|
103
|
+
const k = 0.5;
|
|
104
|
+
const vx = before && dt > 0 ? before.vx + k * ((x - before.x) / dt - before.vx) : 0;
|
|
105
|
+
const vy = before && dt > 0 ? before.vy + k * ((y - before.y) / dt - before.vy) : 0;
|
|
106
|
+
const tracked = { id: entity.id, entity, x, y, vx, vy, t: observation.t };
|
|
107
|
+
this.known.set(entity.id, tracked);
|
|
108
|
+
now.add(entity.id);
|
|
109
|
+
seen.push({ id: entity.id, entity, x, y, vx, vy });
|
|
110
|
+
}
|
|
111
|
+
for (const id of [...this.known.keys()]) {
|
|
112
|
+
if (!now.has(id)) {
|
|
113
|
+
this.known.delete(id);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return seen;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
ProgramLib.Tracker = Tracker;
|
|
120
|
+
function lead(tracked, ms) {
|
|
121
|
+
return { x: clamp(tracked.x + tracked.vx * ms / 1000), y: clamp(tracked.y + tracked.vy * ms / 1000) };
|
|
122
|
+
}
|
|
123
|
+
ProgramLib.lead = lead;
|
|
124
|
+
function pick(tracked, prefer = "nearest", from = { x: 0.5, y: 0.5 }) {
|
|
125
|
+
if (prefer === "first") {
|
|
126
|
+
return tracked[0];
|
|
127
|
+
}
|
|
128
|
+
let best;
|
|
129
|
+
let score = Number.POSITIVE_INFINITY;
|
|
130
|
+
for (const one of tracked) {
|
|
131
|
+
const size = one.entity.box ? one.entity.box.w * one.entity.box.h : 0;
|
|
132
|
+
const value = prefer === "largest" ? -size : (one.x - from.x) ** 2 + (one.y - from.y) ** 2;
|
|
133
|
+
if (value < score) {
|
|
134
|
+
score = value;
|
|
135
|
+
best = one;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return best;
|
|
139
|
+
}
|
|
140
|
+
ProgramLib.pick = pick;
|
|
141
|
+
function approach(from, to, smooth) {
|
|
142
|
+
const keep = Math.min(0.95, Math.max(0, smooth));
|
|
143
|
+
return { x: from.x + (to.x - from.x) * (1 - keep), y: from.y + (to.y - from.y) * (1 - keep) };
|
|
144
|
+
}
|
|
145
|
+
ProgramLib.approach = approach;
|
|
146
|
+
function click(at) {
|
|
147
|
+
return { kind: "pointer", x: at.x, y: at.y };
|
|
148
|
+
}
|
|
149
|
+
ProgramLib.click = click;
|
|
150
|
+
function move(at) {
|
|
151
|
+
return { kind: "pointer", x: at.x, y: at.y, press: "move" };
|
|
152
|
+
}
|
|
153
|
+
ProgramLib.move = move;
|
|
154
|
+
function turn(at, sensitivity, smooth) {
|
|
155
|
+
const towards = approach({ x: 0.5, y: 0.5 }, at, smooth);
|
|
156
|
+
return { kind: "pointer", dx: Math.round((towards.x - 0.5) * sensitivity), dy: Math.round((towards.y - 0.5) * sensitivity) };
|
|
157
|
+
}
|
|
158
|
+
ProgramLib.turn = turn;
|
|
159
|
+
const median = (values) => {
|
|
160
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
161
|
+
const middle = sorted.length >> 1;
|
|
162
|
+
return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
class TurnAxis {
|
|
166
|
+
perPixel;
|
|
167
|
+
lag = 0;
|
|
168
|
+
sent = [];
|
|
169
|
+
moved = [];
|
|
170
|
+
constructor(sensitivity) {
|
|
171
|
+
this.perPixel = 1 / sensitivity;
|
|
172
|
+
}
|
|
173
|
+
see(moved) {
|
|
174
|
+
this.moved.push(moved);
|
|
175
|
+
if (this.moved.length > TurnAxis.KEPT) {
|
|
176
|
+
this.moved.shift();
|
|
177
|
+
}
|
|
178
|
+
this.learn();
|
|
179
|
+
}
|
|
180
|
+
send(pixels) {
|
|
181
|
+
this.sent.push(pixels);
|
|
182
|
+
if (this.sent.length > TurnAxis.KEPT) {
|
|
183
|
+
this.sent.shift();
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
coming() {
|
|
187
|
+
const late = this.lag ? this.sent.slice(-this.lag) : [];
|
|
188
|
+
return -this.perPixel * late.reduce((sum, one) => sum + one, 0);
|
|
189
|
+
}
|
|
190
|
+
learn() {
|
|
191
|
+
let best;
|
|
192
|
+
for (let lag = 0;lag <= TurnAxis.LAG_MAX; lag++) {
|
|
193
|
+
let product = 0;
|
|
194
|
+
let squares = 0;
|
|
195
|
+
const pairs = [];
|
|
196
|
+
for (let i = 0;i + lag < this.moved.length && i < this.sent.length; i++) {
|
|
197
|
+
const moved = this.moved[i + lag + (this.moved.length - this.sent.length)];
|
|
198
|
+
if (moved === undefined || Number.isNaN(moved)) {
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
product += moved * this.sent[i];
|
|
202
|
+
squares += this.sent[i] ** 2;
|
|
203
|
+
pairs.push([this.sent[i], moved]);
|
|
204
|
+
}
|
|
205
|
+
if (squares < TurnAxis.LEARN_PX ** 2) {
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
const perPixel = -product / squares;
|
|
209
|
+
const error = pairs.reduce((sum, [sent, moved]) => sum + (moved + perPixel * sent) ** 2, 0) / pairs.length;
|
|
210
|
+
if (perPixel > 0 && (!best || error < best.error)) {
|
|
211
|
+
best = { lag, perPixel, error };
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
if (best) {
|
|
215
|
+
this.lag = best.lag;
|
|
216
|
+
this.perPixel = Math.min(TurnAxis.MAX, Math.max(TurnAxis.MIN, this.perPixel + (best.perPixel - this.perPixel) * 0.5));
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
static KEPT = 40;
|
|
220
|
+
static LAG_MAX = 3;
|
|
221
|
+
static LEARN_PX = 30;
|
|
222
|
+
static MIN = 1 / 20000;
|
|
223
|
+
static MAX = 1 / 20;
|
|
224
|
+
}
|
|
225
|
+
ProgramLib.TurnAxis = TurnAxis;
|
|
226
|
+
|
|
227
|
+
class ViewTurner {
|
|
228
|
+
gain;
|
|
229
|
+
across;
|
|
230
|
+
down;
|
|
231
|
+
vx = 0;
|
|
232
|
+
vy = 0;
|
|
233
|
+
last = new Map;
|
|
234
|
+
t;
|
|
235
|
+
turned = true;
|
|
236
|
+
constructor(sensitivity = 800, gain = 0.5) {
|
|
237
|
+
this.gain = gain;
|
|
238
|
+
this.across = new TurnAxis(sensitivity);
|
|
239
|
+
this.down = new TurnAxis(sensitivity);
|
|
240
|
+
}
|
|
241
|
+
see(tracked, t) {
|
|
242
|
+
if (!this.turned) {
|
|
243
|
+
this.across.send(0);
|
|
244
|
+
this.down.send(0);
|
|
245
|
+
}
|
|
246
|
+
this.turned = false;
|
|
247
|
+
const shifts = tracked.flatMap((one) => {
|
|
248
|
+
const before = this.last.get(one.id);
|
|
249
|
+
return before ? [{ x: one.x - before.x, y: one.y - before.y }] : [];
|
|
250
|
+
});
|
|
251
|
+
const dt = this.t === undefined ? 0 : (t - this.t) / 1000;
|
|
252
|
+
this.t = t;
|
|
253
|
+
this.last = new Map(tracked.map((one) => [one.id, { x: one.x, y: one.y }]));
|
|
254
|
+
const x = shifts.length ? median(shifts.map((shift) => shift.x)) : Number.NaN;
|
|
255
|
+
const y = shifts.length ? median(shifts.map((shift) => shift.y)) : Number.NaN;
|
|
256
|
+
this.vx = dt > 0 && shifts.length ? x / dt : 0;
|
|
257
|
+
this.vy = dt > 0 && shifts.length ? y / dt : 0;
|
|
258
|
+
this.across.see(x);
|
|
259
|
+
this.down.see(y);
|
|
260
|
+
}
|
|
261
|
+
turn(at) {
|
|
262
|
+
const x = at.x + this.across.coming() - 0.5;
|
|
263
|
+
const y = at.y + this.down.coming() - 0.5;
|
|
264
|
+
return this.by(x * this.gain / this.across.perPixel, y * this.gain / this.down.perPixel);
|
|
265
|
+
}
|
|
266
|
+
sweep(widths) {
|
|
267
|
+
return this.by(widths / this.across.perPixel, 0);
|
|
268
|
+
}
|
|
269
|
+
own(tracked) {
|
|
270
|
+
return { ...tracked, vx: tracked.vx - this.vx, vy: tracked.vy - this.vy };
|
|
271
|
+
}
|
|
272
|
+
by(dx, dy) {
|
|
273
|
+
const action = { kind: "pointer", dx: Math.round(dx), dy: Math.round(dy) };
|
|
274
|
+
this.across.send(action.dx);
|
|
275
|
+
this.down.send(action.dy);
|
|
276
|
+
this.turned = true;
|
|
277
|
+
return action;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
ProgramLib.ViewTurner = ViewTurner;
|
|
281
|
+
function shows(observation, look) {
|
|
282
|
+
if (look.data && !Object.entries(look.data).every(([key, value]) => observation.data?.[key] === value)) {
|
|
283
|
+
return false;
|
|
284
|
+
}
|
|
285
|
+
if (look.type === undefined && look.text === undefined) {
|
|
286
|
+
return !!look.data;
|
|
287
|
+
}
|
|
288
|
+
const text = look.text?.toLowerCase();
|
|
289
|
+
return (observation.entities ?? []).some((entity) => (look.type === undefined || entity.type === look.type) && (text === undefined || (entity.text ?? "").toLowerCase().includes(text)));
|
|
290
|
+
}
|
|
291
|
+
ProgramLib.shows = shows;
|
|
292
|
+
})(ProgramLib ||= {});
|
|
293
|
+
|
|
294
|
+
// web-src/reflex-util.ts
|
|
295
|
+
var ACTIONS_MAX = 32;
|
|
296
|
+
var CODE_MAX = 20000;
|
|
297
|
+
var PRESSES = { pointer: ["click", "move", "down", "up"], key: ["tap", "down", "up"] };
|
|
298
|
+
function finite(value, name, min = Number.NEGATIVE_INFINITY, max = Number.POSITIVE_INFINITY) {
|
|
299
|
+
if (value === undefined) {
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < min || value > max) {
|
|
303
|
+
throw new Error(`${name} is a number${min > Number.NEGATIVE_INFINITY ? ` from ${min} to ${max}` : ""}, not ${JSON.stringify(value)}.`);
|
|
304
|
+
}
|
|
305
|
+
return value;
|
|
306
|
+
}
|
|
307
|
+
function text(value, name) {
|
|
308
|
+
if (typeof value !== "string" || !value) {
|
|
309
|
+
throw new Error(`${name} is a string, not ${JSON.stringify(value)}.`);
|
|
310
|
+
}
|
|
311
|
+
return value;
|
|
312
|
+
}
|
|
313
|
+
var ReflexUtil;
|
|
314
|
+
((ReflexUtil) => {
|
|
315
|
+
function actions(value) {
|
|
316
|
+
if (value === undefined || value === null) {
|
|
317
|
+
return [];
|
|
318
|
+
}
|
|
319
|
+
const list = Array.isArray(value) ? value : [value];
|
|
320
|
+
if (list.length > ACTIONS_MAX) {
|
|
321
|
+
throw new Error(`A step gives at most ${ACTIONS_MAX} actions, not ${list.length}.`);
|
|
322
|
+
}
|
|
323
|
+
return list.map((one, at) => action(one, `actions[${at}]`));
|
|
324
|
+
}
|
|
325
|
+
ReflexUtil.actions = actions;
|
|
326
|
+
function action(value, name = "action") {
|
|
327
|
+
const one = value ?? {};
|
|
328
|
+
switch (one.kind) {
|
|
329
|
+
case "pointer": {
|
|
330
|
+
const press = one.press ?? "click";
|
|
331
|
+
if (!PRESSES.pointer.includes(press)) {
|
|
332
|
+
throw new Error(`${name}.press is one of ${PRESSES.pointer.join(", ")}.`);
|
|
333
|
+
}
|
|
334
|
+
const x = finite(one.x, `${name}.x`, 0, 1);
|
|
335
|
+
const y = finite(one.y, `${name}.y`, 0, 1);
|
|
336
|
+
const dx = finite(one.dx, `${name}.dx`, -1e4, 1e4);
|
|
337
|
+
const dy = finite(one.dy, `${name}.dy`, -1e4, 1e4);
|
|
338
|
+
return {
|
|
339
|
+
kind: "pointer",
|
|
340
|
+
...x !== undefined ? { x } : {},
|
|
341
|
+
...y !== undefined ? { y } : {},
|
|
342
|
+
...typeof one.ref === "string" ? { ref: one.ref } : {},
|
|
343
|
+
...dx !== undefined ? { dx } : {},
|
|
344
|
+
...dy !== undefined ? { dy } : {},
|
|
345
|
+
...one.press !== undefined ? { press } : {}
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
case "key": {
|
|
349
|
+
const press = one.press ?? "tap";
|
|
350
|
+
if (!PRESSES.key.includes(press)) {
|
|
351
|
+
throw new Error(`${name}.press is one of ${PRESSES.key.join(", ")}.`);
|
|
352
|
+
}
|
|
353
|
+
const ms = finite(one.ms, `${name}.ms`, 10, 5000);
|
|
354
|
+
return {
|
|
355
|
+
kind: "key",
|
|
356
|
+
key: text(one.key, `${name}.key`),
|
|
357
|
+
...one.press !== undefined ? { press } : {},
|
|
358
|
+
...ms !== undefined ? { ms } : {}
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
case "text":
|
|
362
|
+
return { kind: "text", text: String(one.text ?? ""), ...typeof one.ref === "string" ? { ref: one.ref } : {} };
|
|
363
|
+
case "scroll": {
|
|
364
|
+
const dx = finite(one.dx, `${name}.dx`);
|
|
365
|
+
const dy = finite(one.dy, `${name}.dy`);
|
|
366
|
+
return {
|
|
367
|
+
kind: "scroll",
|
|
368
|
+
...dx !== undefined ? { dx } : {},
|
|
369
|
+
...dy !== undefined ? { dy } : {},
|
|
370
|
+
...typeof one.ref === "string" ? { ref: one.ref } : {}
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
case "verb":
|
|
374
|
+
return {
|
|
375
|
+
kind: "verb",
|
|
376
|
+
name: text(one.name, `${name}.name`),
|
|
377
|
+
...one.input && typeof one.input === "object" ? { input: one.input } : {}
|
|
378
|
+
};
|
|
379
|
+
default:
|
|
380
|
+
throw new Error(`${name}.kind is pointer, key, text, scroll or verb, not ${JSON.stringify(one.kind)}.`);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
ReflexUtil.action = action;
|
|
384
|
+
function intent(value) {
|
|
385
|
+
const one = value && typeof value === "object" ? value : {};
|
|
386
|
+
const ttl = finite(one.ttl, "intent.ttl", 0.1, 86400);
|
|
387
|
+
return {
|
|
388
|
+
...typeof one.goal === "string" ? { goal: one.goal } : {},
|
|
389
|
+
...one.params && typeof one.params === "object" && !Array.isArray(one.params) ? { params: one.params } : {},
|
|
390
|
+
...ttl !== undefined ? { ttl } : {},
|
|
391
|
+
...Array.isArray(one.reportOn) ? { reportOn: one.reportOn.filter((type) => typeof type === "string") } : {}
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
ReflexUtil.intent = intent;
|
|
395
|
+
function percentile(values, p) {
|
|
396
|
+
if (!values.length) {
|
|
397
|
+
return 0;
|
|
398
|
+
}
|
|
399
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
400
|
+
return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * p))];
|
|
401
|
+
}
|
|
402
|
+
ReflexUtil.percentile = percentile;
|
|
403
|
+
})(ReflexUtil ||= {});
|
|
404
|
+
|
|
405
|
+
// web-src/reflex-batch.ts
|
|
406
|
+
var BATCH_STEPS_MAX = 50;
|
|
407
|
+
var BATCH_WAIT_MAX = 1e4;
|
|
408
|
+
var BATCH_MS_MAX = 30000;
|
|
409
|
+
var UNTIL_EVERY_MS = 50;
|
|
410
|
+
var ReflexBatch;
|
|
411
|
+
((ReflexBatch) => {
|
|
412
|
+
function steps(value) {
|
|
413
|
+
if (!Array.isArray(value) || !value.length) {
|
|
414
|
+
throw new Error("steps is a list of {action}, {wait: ms} or {until: {type?, text?, data?, gone?}, timeoutMs?}.");
|
|
415
|
+
}
|
|
416
|
+
if (value.length > BATCH_STEPS_MAX) {
|
|
417
|
+
throw new Error(`A batch is at most ${BATCH_STEPS_MAX} steps, not ${value.length}.`);
|
|
418
|
+
}
|
|
419
|
+
return value.map((one, at) => {
|
|
420
|
+
if (one && typeof one === "object" && "action" in one) {
|
|
421
|
+
return { action: ReflexUtil.action(one.action, `steps[${at}].action`) };
|
|
422
|
+
}
|
|
423
|
+
if (one && typeof one.wait === "number" && one.wait >= 0 && one.wait <= BATCH_WAIT_MAX) {
|
|
424
|
+
return { wait: one.wait };
|
|
425
|
+
}
|
|
426
|
+
if (one?.until && typeof one.until === "object") {
|
|
427
|
+
const timeoutMs = typeof one.timeoutMs === "number" ? Math.min(BATCH_WAIT_MAX, Math.max(0, one.timeoutMs)) : 5000;
|
|
428
|
+
return { until: look(one.until), timeoutMs };
|
|
429
|
+
}
|
|
430
|
+
throw new Error(`steps[${at}] is {action}, {wait: 0 to ${BATCH_WAIT_MAX}} or {until, timeoutMs?}.`);
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
ReflexBatch.steps = steps;
|
|
434
|
+
function look(value) {
|
|
435
|
+
return {
|
|
436
|
+
...typeof value.type === "string" ? { type: value.type } : {},
|
|
437
|
+
...typeof value.text === "string" ? { text: value.text } : {},
|
|
438
|
+
...value.data && typeof value.data === "object" ? { data: value.data } : {},
|
|
439
|
+
...value.gone === true ? { gone: true } : {}
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
ReflexBatch.look = look;
|
|
443
|
+
function seen(observation, until) {
|
|
444
|
+
const shown = !!observation && ProgramLib.shows(observation, until);
|
|
445
|
+
return until.gone ? !shown : shown;
|
|
446
|
+
}
|
|
447
|
+
ReflexBatch.seen = seen;
|
|
448
|
+
async function run(target, observe, steps2, clock) {
|
|
449
|
+
const started = clock.now();
|
|
450
|
+
const sleep = (ms) => new Promise((resolve) => clock.after(resolve, ms));
|
|
451
|
+
let done = 0;
|
|
452
|
+
for (const [at, step] of steps2.entries()) {
|
|
453
|
+
const left = BATCH_MS_MAX - (clock.now() - started);
|
|
454
|
+
try {
|
|
455
|
+
if ("action" in step) {
|
|
456
|
+
if (!target.actions.includes(step.action.kind)) {
|
|
457
|
+
throw new Error(`The target takes ${target.actions.join(", ")} actions only.`);
|
|
458
|
+
}
|
|
459
|
+
await target.act([step.action]);
|
|
460
|
+
} else if ("wait" in step) {
|
|
461
|
+
await sleep(Math.min(step.wait, Math.max(0, left)));
|
|
462
|
+
} else {
|
|
463
|
+
const until = started + Math.min(BATCH_MS_MAX, clock.now() - started + (step.timeoutMs ?? 5000));
|
|
464
|
+
while (!seen(await observe(), step.until)) {
|
|
465
|
+
if (clock.now() >= until) {
|
|
466
|
+
throw new Error(`What it waited for did not ${step.until.gone ? "go" : "show"} in time.`);
|
|
467
|
+
}
|
|
468
|
+
await sleep(UNTIL_EVERY_MS);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
done++;
|
|
472
|
+
} catch (failure) {
|
|
473
|
+
return { done, failed: { at, error: failure instanceof Error ? failure.message : String(failure) }, ms: clock.now() - started };
|
|
474
|
+
}
|
|
475
|
+
if (clock.now() - started >= BATCH_MS_MAX && at < steps2.length - 1) {
|
|
476
|
+
return { done, failed: { at: at + 1, error: `A batch takes ${BATCH_MS_MAX / 1000} s at most.` }, ms: clock.now() - started };
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return { done, ms: clock.now() - started };
|
|
480
|
+
}
|
|
481
|
+
ReflexBatch.run = run;
|
|
482
|
+
})(ReflexBatch ||= {});
|
|
483
|
+
|
|
484
|
+
// web-src/reflex-inbox.ts
|
|
485
|
+
class ReflexInbox {
|
|
486
|
+
send;
|
|
487
|
+
now;
|
|
488
|
+
held = [];
|
|
489
|
+
seen = new Map;
|
|
490
|
+
busy = false;
|
|
491
|
+
constructor(send, now = () => Date.now()) {
|
|
492
|
+
this.send = send;
|
|
493
|
+
this.now = now;
|
|
494
|
+
}
|
|
495
|
+
told(told) {
|
|
496
|
+
if (this.busy) {
|
|
497
|
+
this.held.push({ told, at: this.now() });
|
|
498
|
+
} else {
|
|
499
|
+
this.send(told);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
saw(run) {
|
|
503
|
+
this.seen.set(run, this.now());
|
|
504
|
+
}
|
|
505
|
+
take(run) {
|
|
506
|
+
let taken;
|
|
507
|
+
const seen = this.seen.get(run) ?? Number.NEGATIVE_INFINITY;
|
|
508
|
+
for (let i = 0;i < this.held.length; ) {
|
|
509
|
+
const { told, at } = this.held[i];
|
|
510
|
+
if (told.run !== run) {
|
|
511
|
+
i++;
|
|
512
|
+
continue;
|
|
513
|
+
}
|
|
514
|
+
this.held.splice(i, 1);
|
|
515
|
+
if (at > seen) {
|
|
516
|
+
taken = taken ? { ...told, events: [...taken.events, ...told.events] } : told;
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
return taken;
|
|
520
|
+
}
|
|
521
|
+
working() {
|
|
522
|
+
this.busy = true;
|
|
523
|
+
}
|
|
524
|
+
ended() {
|
|
525
|
+
this.busy = false;
|
|
526
|
+
const runs = new Map;
|
|
527
|
+
for (const { told, at } of this.held.splice(0)) {
|
|
528
|
+
if ((this.seen.get(told.run) ?? Number.NEGATIVE_INFINITY) >= at) {
|
|
529
|
+
continue;
|
|
530
|
+
}
|
|
531
|
+
const before = runs.get(told.run);
|
|
532
|
+
runs.set(told.run, before ? { ...told, events: [...before.events, ...told.events] } : told);
|
|
533
|
+
}
|
|
534
|
+
for (const told of runs.values()) {
|
|
535
|
+
this.send(told);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
dispose() {
|
|
539
|
+
this.held.length = 0;
|
|
540
|
+
this.seen.clear();
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// web-src/reflex-protocol.ts
|
|
545
|
+
var NAME = "@celljs/ta-reflex";
|
|
546
|
+
var EVENT_TYPE = "ta-reflex";
|
|
547
|
+
var REFLEX_TOOLS = ["reflex_targets", "reflex_do", "reflex_start", "reflex_intent", "reflex_program", "reflex_batch", "reflex_stop"];
|
|
548
|
+
|
|
549
|
+
// web-src/programs.ts
|
|
550
|
+
var ACTIONABLE = new Set([
|
|
551
|
+
"button",
|
|
552
|
+
"link",
|
|
553
|
+
"textbox",
|
|
554
|
+
"searchbox",
|
|
555
|
+
"textarea",
|
|
556
|
+
"textfield",
|
|
557
|
+
"combobox",
|
|
558
|
+
"checkbox",
|
|
559
|
+
"radio",
|
|
560
|
+
"switch",
|
|
561
|
+
"tab",
|
|
562
|
+
"menuitem",
|
|
563
|
+
"option",
|
|
564
|
+
"cell",
|
|
565
|
+
"row",
|
|
566
|
+
"treeitem",
|
|
567
|
+
"slider",
|
|
568
|
+
"spinbutton",
|
|
569
|
+
"listitem",
|
|
570
|
+
"image"
|
|
571
|
+
]);
|
|
572
|
+
var FIELDS = new Set(["textbox", "searchbox", "textarea", "textfield", "combobox", "spinbutton"]);
|
|
573
|
+
var DIALOGS = new Set(["dialog", "alertdialog", "sheet"]);
|
|
574
|
+
var TOGGLES = new Set(["checkbox", "switch", "radio", "menuitemcheckbox", "menuitemradio"]);
|
|
575
|
+
var PROGRAM_HELP = {
|
|
576
|
+
aim: 'points at what moves and presses on it, where it will be: params {types?, tags?, skip? (default ["friend"]), prefer? nearest|largest|first, mode? pointer|view (the first person: it turns the view, learning the sensitivity of the game as it goes, and looks round while nothing is in sight), leadMs? 40, smooth? 0 to 0.95 (pointer), cooldownMs? 120, fire? true, sensitivity? 800 (pixels for a turn across the view, a first guess), gain? 0.5 (of the way a frame turns), sweep? 0.6 (view widths a second looking round; 0 not)}; never presses where something it skips is; tells round_over',
|
|
577
|
+
track: "keeps the pointer (or the view) on what moves, without pressing: params {types?, tags?, skip?, prefer?, axis? x|y, mode?, leadMs?, smooth?, sensitivity?, gain?, lostMs? 1000}; tells lost",
|
|
578
|
+
watch: "waits for something to show, then tells once: params {type?, text?, data?, gone?}; tells seen (or gone)",
|
|
579
|
+
nav: "works a page or an app toward intent.goal step by step without your turns. Give params.plan, the texts of the elements to click or fill in order, as far as you can foresee them (screens it has not seen yet too): it does each as soon as it shows and asks no one; a decision model (L3) settles only what the plan did not foresee (a dialog that opens, a step that does not show), and you only when it is unsure. Without a plan the model picks every step. params {plan? [texts], fill? {field name: text to type}, next? (an element id to act on now), maxSteps? 20, settleMs? 1500, decideMin?}; tells unsure (with the likeliest), needs_text, done (check it), stuck, max_steps, then waits for a new intent"
|
|
580
|
+
};
|
|
581
|
+
|
|
582
|
+
// web-src/reflex-text.ts
|
|
583
|
+
var ENTITIES_SHOWN = 30;
|
|
584
|
+
var DATA_SHOWN = 600;
|
|
585
|
+
var round = (value) => Math.round(value * 1000) / 1000;
|
|
586
|
+
var json = (value, max = DATA_SHOWN) => {
|
|
587
|
+
const text2 = JSON.stringify(value) ?? "";
|
|
588
|
+
return text2.length > max ? `${text2.slice(0, max)}…` : text2;
|
|
589
|
+
};
|
|
590
|
+
var ReflexText;
|
|
591
|
+
((ReflexText) => {
|
|
592
|
+
ReflexText.NO_PAGE = "Level L0 here: no page of Ta that runs programs is open for you (or ta-reflex is off on it), so work it step by step with the tools you have (app_do, the browser, the desktop).";
|
|
593
|
+
ReflexText.WAIT_HINT = "To hear what it tells, call reflex_intent with {run, wait: seconds} (up to 120): it answers as soon as the run tells something. Do not sleep to wait.";
|
|
594
|
+
function reach(reach2) {
|
|
595
|
+
return `Level ${reach2.level} here${reach2.why ? ` (${reach2.why})` : ""}.`;
|
|
596
|
+
}
|
|
597
|
+
ReflexText.reach = reach;
|
|
598
|
+
function target(info) {
|
|
599
|
+
const traits = [info.kind, info.tier, info.hz ? `${info.hz} Hz` : "", info.pausable ? "waits for you" : ""].filter(Boolean).join(", ");
|
|
600
|
+
const verbs = info.verbs ? `; verbs: ${Object.entries(info.verbs).map(([name, what]) => `${name} (${what})`).join(", ")}` : "";
|
|
601
|
+
return `- ${info.id} (${traits}): ${info.title}; actions: ${info.actions.join(", ")}${verbs}${info.describe ? `; observation: ${info.describe}` : ""}`;
|
|
602
|
+
}
|
|
603
|
+
ReflexText.target = target;
|
|
604
|
+
function decide(info) {
|
|
605
|
+
if (!info) {
|
|
606
|
+
return "";
|
|
607
|
+
}
|
|
608
|
+
if (!info.by) {
|
|
609
|
+
return `Decisions (ctx.decide, nav): none here, L2: ${info.why ?? "no decision model answers"} Programs ask you instead.`;
|
|
610
|
+
}
|
|
611
|
+
const how = [info.online ? "online" : "on this computer", info.api, info.ms !== undefined ? `about ${info.ms} ms` : ""].filter(Boolean).join(", ");
|
|
612
|
+
return `Decisions (ctx.decide, nav): L3, by ${info.by} (${how}); an answer is acted on at confidence ${round(info.min)} or more, else you are asked.`;
|
|
613
|
+
}
|
|
614
|
+
ReflexText.decide = decide;
|
|
615
|
+
function targets(reached, decided, learned = {}) {
|
|
616
|
+
if (reached?.kind !== "targets") {
|
|
617
|
+
return ReflexText.NO_PAGE;
|
|
618
|
+
}
|
|
619
|
+
const list = reached.targets.length ? reached.targets.map(target).join(`
|
|
620
|
+
`) : "(none now: a game, or what an extension offers, shows here while it is open on the page)";
|
|
621
|
+
const ways = Object.entries(learned).map(([title, paths]) => paths.map((one) => `- ${title}: ${json(one.goal, 120)} by ${json(one.path, 600)}`).join(`
|
|
622
|
+
`)).join(`
|
|
623
|
+
`);
|
|
624
|
+
const library = Object.entries(PROGRAM_HELP).map(([name, what]) => `- ${name}: ${what}`).join(`
|
|
625
|
+
`);
|
|
626
|
+
const decide2 = ReflexText.decide(decided);
|
|
627
|
+
return `${reach(reached.reach)}${decide2 ? `
|
|
628
|
+
${decide2}` : ""}
|
|
629
|
+
For a task of steps on a page or an app (settings, a form, an export), call reflex_do {target, goal, plan?, fill?} once: it answers when done or when it needs you.
|
|
630
|
+
Targets on the user's page:
|
|
631
|
+
${list}${ways ? `
|
|
632
|
+
Ways nav took before to reach a goal (reflex_do uses the one for a goal like yours by itself):
|
|
633
|
+
${ways}` : ""}
|
|
634
|
+
Programs of the library (program {use}):
|
|
635
|
+
${library}`;
|
|
636
|
+
}
|
|
637
|
+
ReflexText.targets = targets;
|
|
638
|
+
function observation(observation2) {
|
|
639
|
+
if (!observation2) {
|
|
640
|
+
return "Nothing read yet.";
|
|
641
|
+
}
|
|
642
|
+
const entities = observation2.entities ?? [];
|
|
643
|
+
const lines = entities.slice(0, ENTITIES_SHOWN).map((entity) => {
|
|
644
|
+
const box = entity.box ? ` at ${round(entity.box.x)},${round(entity.box.y)} ${round(entity.box.w)}×${round(entity.box.h)}` : "";
|
|
645
|
+
const text2 = entity.text ? ` ${json(entity.text, 80)}` : "";
|
|
646
|
+
const value = entity.value !== undefined ? ` = ${json(entity.value, 40)}` : "";
|
|
647
|
+
const tags = entity.tags?.length ? ` [${entity.tags.join(", ")}]` : "";
|
|
648
|
+
return ` ${entity.id} ${entity.type}${text2}${value}${box}${tags}`;
|
|
649
|
+
});
|
|
650
|
+
const more = entities.length > ENTITIES_SHOWN ? [` … ${entities.length - ENTITIES_SHOWN} more`] : [];
|
|
651
|
+
const data = observation2.data && Object.keys(observation2.data).length ? `data: ${json(observation2.data)}
|
|
652
|
+
` : "";
|
|
653
|
+
return `${data}entities (${entities.length}):${lines.length ? `
|
|
654
|
+
${[...lines, ...more].join(`
|
|
655
|
+
`)}` : " none"}`;
|
|
656
|
+
}
|
|
657
|
+
ReflexText.observation = observation;
|
|
658
|
+
function summary(summary2) {
|
|
659
|
+
const parts = [
|
|
660
|
+
`${round(summary2.ms / 1000)} s`,
|
|
661
|
+
`${summary2.steps} steps (${summary2.hz}/s)`,
|
|
662
|
+
`${summary2.actions} actions`,
|
|
663
|
+
summary2.stepMs ? `step ${round(summary2.stepMs.p50)} ms p50, ${round(summary2.stepMs.p95)} ms p95` : "",
|
|
664
|
+
summary2.dropped ? `${summary2.dropped} frames left out` : "",
|
|
665
|
+
summary2.errors ? `${summary2.errors} errors (last: ${summary2.error})` : "",
|
|
666
|
+
summary2.decisions ? `${summary2.decisions} decisions asked` : "",
|
|
667
|
+
`${summary2.escalations} of ${summary2.events} events woke you`,
|
|
668
|
+
`at most once in ${round(summary2.gateMs / 1000)} s now`
|
|
669
|
+
];
|
|
670
|
+
const what = summary2.state === "running" ? `running ${summary2.program}` : summary2.state === "waiting" ? `waiting${summary2.why ? ` (${summary2.why})` : ""}` : `stopped${summary2.why ? ` (${summary2.why})` : ""}`;
|
|
671
|
+
return `${what}, ${summary2.level}: ${parts.filter(Boolean).join(", ")}`;
|
|
672
|
+
}
|
|
673
|
+
ReflexText.summary = summary;
|
|
674
|
+
function run(id, answer) {
|
|
675
|
+
if (!answer) {
|
|
676
|
+
return ReflexText.NO_PAGE;
|
|
677
|
+
}
|
|
678
|
+
if (answer.kind === "missing") {
|
|
679
|
+
return `The page in front of the user has no ${answer.what}: it is on another page of theirs, or it went. reflex_targets says what there is.`;
|
|
680
|
+
}
|
|
681
|
+
if (answer.kind !== "run") {
|
|
682
|
+
return "";
|
|
683
|
+
}
|
|
684
|
+
return `Run ${id} on ${answer.summary.target}: ${summary(answer.summary)}.
|
|
685
|
+
Now:
|
|
686
|
+
${observation(answer.observation)}`;
|
|
687
|
+
}
|
|
688
|
+
ReflexText.run = run;
|
|
689
|
+
function batch(answer) {
|
|
690
|
+
if (!answer) {
|
|
691
|
+
return ReflexText.NO_PAGE;
|
|
692
|
+
}
|
|
693
|
+
if (answer.kind === "missing") {
|
|
694
|
+
return `The page in front of the user has no ${answer.what}. reflex_targets says what there is.`;
|
|
695
|
+
}
|
|
696
|
+
if (answer.kind !== "batch") {
|
|
697
|
+
return "";
|
|
698
|
+
}
|
|
699
|
+
return `${result(answer.result)}
|
|
700
|
+
Now:
|
|
701
|
+
${observation(answer.observation)}`;
|
|
702
|
+
}
|
|
703
|
+
ReflexText.batch = batch;
|
|
704
|
+
function result(result2) {
|
|
705
|
+
const failed = result2.failed ? `, stopped at step ${result2.failed.at}: ${result2.failed.error}` : "";
|
|
706
|
+
return `${result2.done} steps done in ${round(result2.ms / 1000)} s${failed}.`;
|
|
707
|
+
}
|
|
708
|
+
ReflexText.result = result;
|
|
709
|
+
function event(event2) {
|
|
710
|
+
return `${event2.type}${event2.data && Object.keys(event2.data).length ? ` ${json(event2.data, 200)}` : ""}`;
|
|
711
|
+
}
|
|
712
|
+
ReflexText.event = event;
|
|
713
|
+
function told(told2) {
|
|
714
|
+
const events = told2.events.map(event).join("; ");
|
|
715
|
+
const next = told2.summary.state === "stopped" ? "It ended." : "Steer it with reflex_intent or reflex_program, or end it with reflex_stop; say nothing to the user unless it matters to them.";
|
|
716
|
+
return `Run ${told2.run} on ${told2.target}: ${events}.
|
|
717
|
+
${summary(told2.summary)}.
|
|
718
|
+
${next}`;
|
|
719
|
+
}
|
|
720
|
+
ReflexText.told = told;
|
|
721
|
+
})(ReflexText ||= {});
|
|
722
|
+
|
|
723
|
+
// web-src/extension.ts
|
|
724
|
+
var NO_SERVER = "Working targets needs the Ta service: start it with `ta serve`.";
|
|
725
|
+
var NEEDS_YOU = new Set(["unsure", "needs_text", "stuck", "max_steps", "no_goal"]);
|
|
726
|
+
var WAIT_MAX = 120;
|
|
727
|
+
var object = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
|
|
728
|
+
var text2 = (value, name) => {
|
|
729
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
730
|
+
throw new Error(`${name} is required.`);
|
|
731
|
+
}
|
|
732
|
+
return value.trim();
|
|
733
|
+
};
|
|
734
|
+
function program(params) {
|
|
735
|
+
const use = typeof params.use === "string" && params.use.trim() ? params.use.trim() : undefined;
|
|
736
|
+
const code = typeof params.code === "string" && params.code.trim() ? params.code : undefined;
|
|
737
|
+
if (use && code) {
|
|
738
|
+
throw new Error("A program is use (of the library) or code, not both.");
|
|
739
|
+
}
|
|
740
|
+
return use ? { use } : code ? { code } : undefined;
|
|
741
|
+
}
|
|
742
|
+
var INTENT = {
|
|
743
|
+
type: "object",
|
|
744
|
+
description: "What the program is to do now: {goal?, params? (what the program reads: which entities, how fast, how), ttl? (seconds it holds: past it the run waits for you), reportOn? (event types that wake you besides what the program escalates)}."
|
|
745
|
+
};
|
|
746
|
+
var PROGRAM = {
|
|
747
|
+
use: { type: "string", description: "A program of the library: aim, track, watch (reflex_targets says what each takes)." },
|
|
748
|
+
code: {
|
|
749
|
+
type: "string",
|
|
750
|
+
description: `Or a program of yours (at most ${CODE_MAX} characters): JavaScript defining function step(observation, intent, memory, ctx) that returns the actions of this frame (or {actions, events}), and may define init(memory, ctx). observation is {t, entities: [{id, type, text?, box?: {x, y, w, h} 0 to 1, tags?}], data}; memory is kept between frames; ctx.lib has center, inside, matching, Tracker, lead, pick, approach, click, move, turn, shows; ctx.emit(type, data) counts an event, ctx.escalate(type, data) wakes you. An action: {kind: "pointer", x, y, press?: click|move|down|up} or {kind: "pointer", dx, dy} (turn a view), {kind: "key", key, press?: tap|down|up, ms?}, {kind: "text", text}, {kind: "scroll", dx?, dy?}, {kind: "verb", name, input?}. It runs in a worker with no network, every frame: keep it quick, no loops that wait.`
|
|
751
|
+
}
|
|
752
|
+
};
|
|
753
|
+
var TOOLS = [
|
|
754
|
+
{
|
|
755
|
+
name: "reflex_targets",
|
|
756
|
+
label: "Find what can be worked live",
|
|
757
|
+
description: "What on the user's page can be worked live, frame by frame by a program, faster than you can step it (a game, a canvas, what an extension offers): each with its id, what it is seen as, the actions it takes, and how far this device can go (L2 programs, L1 batches only, L0 none: step it yourself). Use it before reflex_start or reflex_batch.",
|
|
758
|
+
parameters: { type: "object", properties: {} },
|
|
759
|
+
run: async (reflex, _params, file) => {
|
|
760
|
+
const [targets, decide] = await Promise.all([reflex.targets(file), reflex.decide()]);
|
|
761
|
+
const learned = targets?.kind === "targets" ? await reflex.learned(targets.targets.map((one) => one.title)) : {};
|
|
762
|
+
return ReflexText.targets(targets, decide, learned);
|
|
763
|
+
}
|
|
764
|
+
},
|
|
765
|
+
{
|
|
766
|
+
name: "reflex_start",
|
|
767
|
+
label: "Start working live",
|
|
768
|
+
description: "Starts a run on a target: a program steps it every frame on the page, by your intent, while you think on; what it escalates (and the events of intent.reportOn) wakes you in this conversation, at most once every few seconds. Answers the run id, its level and what the target shows now. Without a program the run waits for you, a target that can wait (a game alone on this device) waiting too. Aim at what you see, not at people: what a game says is a friend is skipped. Stop it with reflex_stop when done.",
|
|
769
|
+
parameters: {
|
|
770
|
+
type: "object",
|
|
771
|
+
properties: { target: { type: "string", description: "Its id, from reflex_targets." }, ...PROGRAM, intent: INTENT },
|
|
772
|
+
required: ["target"]
|
|
773
|
+
},
|
|
774
|
+
run: async (reflex, params, file) => {
|
|
775
|
+
const intent = params.intent === undefined ? undefined : ReflexUtil.intent(params.intent);
|
|
776
|
+
const { run, answer } = await reflex.start(file, text2(params.target, "target"), program(params), intent);
|
|
777
|
+
const going = answer?.kind === "run" && answer.summary.state !== "stopped";
|
|
778
|
+
return { text: `${ReflexText.run(run, answer)}${going ? `
|
|
779
|
+
${ReflexText.WAIT_HINT}` : ""}`, ...going ? { run } : {} };
|
|
780
|
+
}
|
|
781
|
+
},
|
|
782
|
+
{
|
|
783
|
+
name: "reflex_intent",
|
|
784
|
+
label: "Steer the live run",
|
|
785
|
+
description: `Gives a run a new intent, at once (a run that waited for one goes on), and answers how it is and what the target shows. Without intent it only answers that: look before you steer. With wait (seconds, at most ${WAIT_MAX}) it answers when the run next tells you something (what it escalates, the events of reportOn, its end) or when that time is up: wait so rather than sleeping, and you hear at once.`,
|
|
786
|
+
parameters: {
|
|
787
|
+
type: "object",
|
|
788
|
+
properties: {
|
|
789
|
+
run: { type: "string" },
|
|
790
|
+
intent: INTENT,
|
|
791
|
+
wait: { type: "number", description: `Seconds to wait for what the run tells next, at most ${WAIT_MAX}.` }
|
|
792
|
+
},
|
|
793
|
+
required: ["run"]
|
|
794
|
+
},
|
|
795
|
+
run: async (reflex, params, file, signal, inbox) => {
|
|
796
|
+
const run = text2(params.run, "run");
|
|
797
|
+
const intent = params.intent === undefined ? undefined : ReflexUtil.intent(params.intent);
|
|
798
|
+
const answer = await reflex.intent(file, run, intent);
|
|
799
|
+
const wait = typeof params.wait === "number" && params.wait > 0 ? Math.min(WAIT_MAX, params.wait) : 0;
|
|
800
|
+
if (!wait || answer?.kind !== "run" || answer.summary.state === "stopped") {
|
|
801
|
+
return { text: ReflexText.run(run, answer), run };
|
|
802
|
+
}
|
|
803
|
+
const held = intent === undefined ? inbox?.take(run) : undefined;
|
|
804
|
+
const told = held ?? await reflex.next(file, run, wait * 1000, signal);
|
|
805
|
+
const now = told?.summary.state === "stopped" ? undefined : await reflex.intent(file, run, undefined).catch(() => {
|
|
806
|
+
return;
|
|
807
|
+
});
|
|
808
|
+
const said = told ? `${ReflexText.told(told)}${now ? `
|
|
809
|
+
${ReflexText.run(run, now)}` : ""}` : `Nothing came in ${wait} s.
|
|
810
|
+
${ReflexText.run(run, now)}`;
|
|
811
|
+
return { text: said, run };
|
|
812
|
+
}
|
|
813
|
+
},
|
|
814
|
+
{
|
|
815
|
+
name: "reflex_program",
|
|
816
|
+
label: "Change the live program",
|
|
817
|
+
description: "Puts another program in a run, in place of the one there (with a memory of its own), after loading it: one that does not load leaves the old going and says why. When a program failed and the run waits, this is how it goes on.",
|
|
818
|
+
parameters: { type: "object", properties: { run: { type: "string" }, ...PROGRAM }, required: ["run"] },
|
|
819
|
+
run: async (reflex, params, file) => {
|
|
820
|
+
const run = text2(params.run, "run");
|
|
821
|
+
const given = program(params);
|
|
822
|
+
if (!given) {
|
|
823
|
+
throw new Error("Give the program: use or code.");
|
|
824
|
+
}
|
|
825
|
+
return { text: ReflexText.run(run, await reflex.program(file, run, given)), run };
|
|
826
|
+
}
|
|
827
|
+
},
|
|
828
|
+
{
|
|
829
|
+
name: "reflex_batch",
|
|
830
|
+
label: "Do steps at once",
|
|
831
|
+
description: "Does many steps on a target in one call, in order, with no turn of yours between them (L1, where no program is needed or none can run): {action} as reflex_start's actions, {wait: ms}, or {until: {type?, text?, data?, gone?}, timeoutMs?} waiting till the target shows (or no longer shows) it. Stops at the first that fails. Answers what was done and what the target shows after.",
|
|
832
|
+
parameters: {
|
|
833
|
+
type: "object",
|
|
834
|
+
properties: { target: { type: "string" }, steps: { type: "array", items: { type: "object" } } },
|
|
835
|
+
required: ["target", "steps"]
|
|
836
|
+
},
|
|
837
|
+
run: async (reflex, params, file) => ReflexText.batch(await reflex.batch(file, text2(params.target, "target"), ReflexBatch.steps(params.steps)))
|
|
838
|
+
},
|
|
839
|
+
{
|
|
840
|
+
name: "reflex_do",
|
|
841
|
+
label: "Do a task live",
|
|
842
|
+
description: `Does a task on a target of a tree (a page, an app, the browser) in one call: nav works it toward goal on the page, by the way it learned for this same goal when there is one (else by plan, your guess of the texts to click in order), filling fill; it answers once the goal is reached, with what the target shows then, or as soon as it needs you (unsure, needs_text, stuck), leaving the run going for you to steer with reflex_intent. Use it in place of reflex_start + reflex_intent + reflex_stop for a task of steps.`,
|
|
843
|
+
parameters: {
|
|
844
|
+
type: "object",
|
|
845
|
+
properties: {
|
|
846
|
+
target: { type: "string", description: "Its id, from reflex_targets." },
|
|
847
|
+
goal: { type: "string", description: "The whole task, as the user said it." },
|
|
848
|
+
plan: {
|
|
849
|
+
type: "array",
|
|
850
|
+
items: { type: "string" },
|
|
851
|
+
description: "The texts of what to click or fill, in order, as far as you can foresee them; a way learned for the very same goal is used before it."
|
|
852
|
+
},
|
|
853
|
+
fill: { type: "object", description: "What to type into a field, by the name of the field." },
|
|
854
|
+
wait: { type: "number", description: `Seconds to wait at most, ${WAIT_MAX} by default.` }
|
|
855
|
+
},
|
|
856
|
+
required: ["target", "goal"]
|
|
857
|
+
},
|
|
858
|
+
run: async (reflex, params, file, signal, inbox) => {
|
|
859
|
+
const target = text2(params.target, "target");
|
|
860
|
+
const goal = text2(params.goal, "goal");
|
|
861
|
+
const listed = await reflex.targets(file);
|
|
862
|
+
const info = listed?.kind === "targets" ? listed.targets.find((one) => one.id === target) : undefined;
|
|
863
|
+
if (!info) {
|
|
864
|
+
return listed?.kind === "targets" ? `No target ${target} on the page: ${listed.targets.map((one) => one.id).join(", ") || "none"}.` : ReflexText.NO_PAGE;
|
|
865
|
+
}
|
|
866
|
+
const way = await reflex.wayFor(info.title, goal);
|
|
867
|
+
const given = Array.isArray(params.plan) ? params.plan.map(String) : undefined;
|
|
868
|
+
const plan = way?.path ?? given;
|
|
869
|
+
const fill = params.fill && typeof params.fill === "object" ? params.fill : undefined;
|
|
870
|
+
const { run, answer } = await reflex.start(file, target, { use: "nav" }, { goal, params: { ...plan ? { plan } : {}, ...fill ? { fill } : {} } });
|
|
871
|
+
if (answer?.kind !== "run" || answer.summary.state === "stopped") {
|
|
872
|
+
return ReflexText.run(run, answer);
|
|
873
|
+
}
|
|
874
|
+
const how = way ? "by the way learned for it" : given ? "by your plan" : "step by step";
|
|
875
|
+
const until = Date.now() + (typeof params.wait === "number" && params.wait > 0 ? Math.min(WAIT_MAX, params.wait) : WAIT_MAX) * 1000;
|
|
876
|
+
for (;; ) {
|
|
877
|
+
const left = until - Date.now();
|
|
878
|
+
const told = inbox?.take(run) ?? (left > 0 ? await reflex.next(file, run, left, signal) : undefined);
|
|
879
|
+
if (!told) {
|
|
880
|
+
return {
|
|
881
|
+
text: `Not done in time (${how}).
|
|
882
|
+
${ReflexText.run(run, await reflex.intent(file, run, undefined).catch(() => {
|
|
883
|
+
return;
|
|
884
|
+
}))}
|
|
885
|
+
Steer it with reflex_intent, or stop it.`,
|
|
886
|
+
run
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
const done = told.events.find((event) => event.type === "done");
|
|
890
|
+
if (done) {
|
|
891
|
+
const ended = await reflex.stop(file, run);
|
|
892
|
+
const end = ended?.kind === "run" ? ended : undefined;
|
|
893
|
+
return `Done ${how}: ${ReflexText.event(done)}. ${end ? `${ReflexText.summary(end.summary)}.
|
|
894
|
+
Now:
|
|
895
|
+
${ReflexText.observation(end.observation)}` : ""}`;
|
|
896
|
+
}
|
|
897
|
+
if (told.events.some((event) => NEEDS_YOU.has(event.type)) || told.summary.state !== "running") {
|
|
898
|
+
return { text: `${ReflexText.told(told)}
|
|
899
|
+
The run goes on (${how}): steer it with reflex_intent {run: "${run}", intent, wait}.`, run };
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
},
|
|
904
|
+
{
|
|
905
|
+
name: "reflex_stop",
|
|
906
|
+
label: "Stop working live",
|
|
907
|
+
description: "Stops a run and answers its summary: how long, steps and actions, step times, events, errors. A target it paused goes on.",
|
|
908
|
+
parameters: { type: "object", properties: { run: { type: "string" } }, required: ["run"] },
|
|
909
|
+
run: async (reflex, params, file) => {
|
|
910
|
+
const run = text2(params.run, "run");
|
|
911
|
+
return { text: ReflexText.run(run, await reflex.stop(file, run)), run };
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
];
|
|
915
|
+
function activate(pi) {
|
|
916
|
+
let reached;
|
|
917
|
+
const reach = () => reached ??= TaHostUtil.reach(pi.events, NAME).then((answer) => ({
|
|
918
|
+
answered: !!answer,
|
|
919
|
+
reflex: answer?.service?.service
|
|
920
|
+
}));
|
|
921
|
+
const others = (ctx) => TaHostUtil.marked(ctx.getSystemPrompt(), TA_WITH_OTHERS_MARK);
|
|
922
|
+
const ours = (name) => REFLEX_TOOLS.includes(name);
|
|
923
|
+
const inbox = new ReflexInbox((told) => pi.sendMessage({ customType: EVENT_TYPE, content: ReflexText.told(told), display: true, details: told }, { triggerTurn: true, deliverAs: "steer" }));
|
|
924
|
+
let detach;
|
|
925
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
926
|
+
detach?.();
|
|
927
|
+
detach = undefined;
|
|
928
|
+
inbox.dispose();
|
|
929
|
+
const file = ctx.sessionManager?.getSessionFile();
|
|
930
|
+
const { reflex } = await reach();
|
|
931
|
+
if (reflex && file && !others(ctx)) {
|
|
932
|
+
detach = reflex.attach(file, (told) => inbox.told(told));
|
|
933
|
+
}
|
|
934
|
+
});
|
|
935
|
+
pi.on("session_shutdown", () => {
|
|
936
|
+
detach?.();
|
|
937
|
+
detach = undefined;
|
|
938
|
+
inbox.dispose();
|
|
939
|
+
});
|
|
940
|
+
pi.on("agent_start", () => inbox.working());
|
|
941
|
+
pi.on("agent_end", () => inbox.ended());
|
|
942
|
+
pi.on("before_agent_start", (_event, ctx) => {
|
|
943
|
+
if (others(ctx)) {
|
|
944
|
+
const active = pi.getActiveTools();
|
|
945
|
+
if (active.some(ours)) {
|
|
946
|
+
pi.setActiveTools(active.filter((name) => !ours(name)));
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
});
|
|
950
|
+
pi.on("tool_call", (event, ctx) => others(ctx) && ours(event.toolName) ? { block: true, reason: "Here you speak with other people: what is on the user's page is not yours to work." } : undefined);
|
|
951
|
+
for (const tool of TOOLS) {
|
|
952
|
+
pi.registerTool({
|
|
953
|
+
name: tool.name,
|
|
954
|
+
label: tool.label,
|
|
955
|
+
description: tool.description,
|
|
956
|
+
parameters: tool.parameters,
|
|
957
|
+
execute: async (_id, params, signal, _update, ctx) => {
|
|
958
|
+
const { answered, reflex } = await reach();
|
|
959
|
+
if (!reflex) {
|
|
960
|
+
throw new Error(answered ? "ta-reflex did not start in the Ta service; its log says why." : NO_SERVER);
|
|
961
|
+
}
|
|
962
|
+
const told = await tool.run(reflex, object(params) ?? {}, ctx.sessionManager?.getSessionFile(), signal, inbox);
|
|
963
|
+
const { text: content, run } = typeof told === "string" ? { text: told, run: undefined } : told;
|
|
964
|
+
if (run) {
|
|
965
|
+
inbox.saw(run);
|
|
966
|
+
}
|
|
967
|
+
return { content: [{ type: "text", text: content }], details: undefined };
|
|
968
|
+
}
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
export {
|
|
973
|
+
activate as default,
|
|
974
|
+
WAIT_MAX,
|
|
975
|
+
TOOLS
|
|
976
|
+
};
|