@celljs/ta-app-use 0.0.0-stage → 4.17.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/web/index.js ADDED
@@ -0,0 +1,1520 @@
1
+ // ../ta-protocol/esm/common/ta-extension-host.js
2
+ var TA_WEBHOOK_MAX_BYTES = 256 * 1024;
3
+ var TA_HOST_EVENT = "ta:host";
4
+ var TaHostUtil;
5
+ (function(TaHostUtil2) {
6
+ TaHostUtil2.WAIT_MS = 1000;
7
+ function reach(events, name, waitMs = TaHostUtil2.WAIT_MS) {
8
+ return new Promise((resolve) => {
9
+ let heard = false;
10
+ let answered = false;
11
+ const timer = setTimeout(() => resolve(undefined), waitMs);
12
+ const request = {
13
+ name,
14
+ heard: () => {
15
+ heard = true;
16
+ },
17
+ resolve: (answer) => {
18
+ answered = true;
19
+ clearTimeout(timer);
20
+ resolve(answer);
21
+ }
22
+ };
23
+ events.emit(TA_HOST_EVENT, request);
24
+ if (!heard && !answered) {
25
+ clearTimeout(timer);
26
+ resolve(undefined);
27
+ }
28
+ });
29
+ }
30
+ TaHostUtil2.reach = reach;
31
+ function marked(systemPrompt, mark) {
32
+ return role(systemPrompt).includes(mark);
33
+ }
34
+ TaHostUtil2.marked = marked;
35
+ function role(systemPrompt) {
36
+ if (!systemPrompt) {
37
+ return "";
38
+ }
39
+ const open = `<addendum>
40
+ `;
41
+ const start = systemPrompt.indexOf(open);
42
+ const context = systemPrompt.indexOf(`<project_context>
43
+ `);
44
+ if (start < 0 || context >= 0 && context < start) {
45
+ return "";
46
+ }
47
+ const end = systemPrompt.indexOf(`
48
+ </addendum>`, start);
49
+ return systemPrompt.slice(start + open.length, end < 0 ? undefined : end);
50
+ }
51
+ TaHostUtil2.role = role;
52
+ })(TaHostUtil || (TaHostUtil = {}));
53
+ var TA_ASK_ENTRY = "ta-ask";
54
+ var TaAskUtil;
55
+ (function(TaAskUtil2) {
56
+ const LENGTH = 120;
57
+ function entry(question) {
58
+ const line = question.replace(/\s+/g, " ").trim();
59
+ return { question: line.length > LENGTH ? `${line.slice(0, LENGTH - 1)}…` : line };
60
+ }
61
+ TaAskUtil2.entry = entry;
62
+ function asking(entries) {
63
+ var _a;
64
+ for (let i = entries.length - 1;i >= 0; i--) {
65
+ const entry2 = entries[i];
66
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
67
+ return;
68
+ }
69
+ if (entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY) {
70
+ return read(entry2);
71
+ }
72
+ }
73
+ return;
74
+ }
75
+ TaAskUtil2.asking = asking;
76
+ function next(asked, entry2) {
77
+ var _a;
78
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
79
+ return;
80
+ }
81
+ return entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY ? read(entry2) : asked;
82
+ }
83
+ TaAskUtil2.next = next;
84
+ function read(found) {
85
+ var _a;
86
+ const question = (_a = found.data) === null || _a === undefined ? undefined : _a.question;
87
+ if (typeof question !== "string" || !question.trim()) {
88
+ return;
89
+ }
90
+ const at = found.timestamp ? Date.parse(found.timestamp) : Number.NaN;
91
+ return { question: entry(question).question, at: Number.isNaN(at) ? 0 : at };
92
+ }
93
+ })(TaAskUtil || (TaAskUtil = {}));
94
+
95
+ // ../ta-protocol/esm/common/delegate-protocol.js
96
+ var TaDelegateUtil;
97
+ (function(TaDelegateUtil2) {
98
+ TaDelegateUtil2.LEVELS = ["less", "balanced", "more"];
99
+ TaDelegateUtil2.DEFAULT = "balanced";
100
+ TaDelegateUtil2.WORK_TOOLS = ["read", "bash", "powershell", "edit", "write", "grep", "find", "ls"];
101
+ TaDelegateUtil2.CHANGE_TOOLS = ["edit", "write"];
102
+ const LIMITS = {
103
+ less: { noChanges: false },
104
+ balanced: { noChanges: true, steps: 6 },
105
+ more: { noChanges: true, steps: 2 }
106
+ };
107
+ function parse(value) {
108
+ return TaDelegateUtil2.LEVELS.includes(value) ? value : TaDelegateUtil2.DEFAULT;
109
+ }
110
+ TaDelegateUtil2.parse = parse;
111
+ function mark(level) {
112
+ return `(delegate=${level})`;
113
+ }
114
+ TaDelegateUtil2.mark = mark;
115
+ function levelOf(systemPrompt) {
116
+ const role = TaHostUtil.role(systemPrompt);
117
+ return TaDelegateUtil2.LEVELS.find((level) => role.includes(mark(level)));
118
+ }
119
+ TaDelegateUtil2.levelOf = levelOf;
120
+ function limits(level) {
121
+ return LIMITS[level];
122
+ }
123
+ TaDelegateUtil2.limits = limits;
124
+ function refusal(level, tool, steps) {
125
+ if (!TaDelegateUtil2.WORK_TOOLS.includes(tool)) {
126
+ return;
127
+ }
128
+ const limit = LIMITS[level];
129
+ if (limit.noChanges && TaDelegateUtil2.CHANGE_TOOLS.includes(tool)) {
130
+ return "You do not change files yourself: hand this to a task with start_task, with instructions complete enough to do it. The user set how much you hand out in the settings of the double.";
131
+ }
132
+ if (limit.steps !== undefined && steps >= limit.steps) {
133
+ return "You have looked enough for this: hand the work to a task with start_task now, with what you found in its instructions, and tell the user what you started.";
134
+ }
135
+ return;
136
+ }
137
+ TaDelegateUtil2.refusal = refusal;
138
+ })(TaDelegateUtil || (TaDelegateUtil = {}));
139
+
140
+ // ../ta-protocol/esm/common/language.js
141
+ var TaLanguageUtil;
142
+ (function(TaLanguageUtil2) {
143
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
144
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
145
+ function of(tag) {
146
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
147
+ if (/^zh(\b|-)/.test(said)) {
148
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
149
+ }
150
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
151
+ }
152
+ TaLanguageUtil2.of = of;
153
+ function server(env = typeof process === "undefined" ? {} : process.env) {
154
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
155
+ }
156
+ TaLanguageUtil2.server = server;
157
+ function pick(language, words) {
158
+ return words[of(language)];
159
+ }
160
+ TaLanguageUtil2.pick = pick;
161
+ function say(words) {
162
+ return words[server()];
163
+ }
164
+ TaLanguageUtil2.say = say;
165
+ function chinese(language) {
166
+ return of(language).startsWith("zh");
167
+ }
168
+ TaLanguageUtil2.chinese = chinese;
169
+ function cjk(language) {
170
+ return of(language) !== "en-US";
171
+ }
172
+ TaLanguageUtil2.cjk = cjk;
173
+ function list(language, items) {
174
+ return items.join(cjk(language) ? "、" : ", ");
175
+ }
176
+ TaLanguageUtil2.list = list;
177
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
178
+
179
+ // ../ta-protocol/esm/common/app-protocol.js
180
+ var TA_APP_TOOLS = ["app_commands", "app_run", "app_look", "app_go", "app_do"];
181
+ var FONT_SIZES = ["small", "standard", "large", "xlarge"];
182
+ var words = (en, zh, tw, ja) => ({ "en-US": en, "zh-CN": zh, "zh-TW": tw, "ja-JP": ja });
183
+ var SYSTEM = words("as the system", "跟随系统", "跟隨系統", "システムに合わせる");
184
+ var FONT_SHOWN = {
185
+ small: words("small", "小", "小", "小"),
186
+ standard: words("standard", "标准", "標準", "標準"),
187
+ large: words("large", "大", "大", "大"),
188
+ xlarge: words("extra large", "特大", "特大", "特大")
189
+ };
190
+ var TA_WEB_SETTINGS = [
191
+ {
192
+ key: "theme",
193
+ type: "enum",
194
+ values: ["system", "light", "dark"],
195
+ default: "system",
196
+ what: "Light or dark look; system follows the device.",
197
+ title: words("Theme", "外观", "外觀", "外観"),
198
+ shown: { system: SYSTEM, light: words("light", "浅色", "淺色", "ライト"), dark: words("dark", "深色", "深色", "ダーク") }
199
+ },
200
+ {
201
+ key: "language",
202
+ type: "enum",
203
+ values: ["system", ...TaLanguageUtil.ALL],
204
+ default: "system",
205
+ what: "The language of Ta's pages and of what Ta says; system follows the device.",
206
+ title: words("Language", "语言", "語言", "言語"),
207
+ shown: {
208
+ system: SYSTEM,
209
+ ...Object.fromEntries(TaLanguageUtil.ALL.map((language) => [
210
+ language,
211
+ words(TaLanguageUtil.NAMES[language], TaLanguageUtil.NAMES[language], TaLanguageUtil.NAMES[language], TaLanguageUtil.NAMES[language])
212
+ ]))
213
+ }
214
+ },
215
+ {
216
+ key: "fontSize",
217
+ type: "enum",
218
+ values: FONT_SIZES,
219
+ default: "standard",
220
+ what: "The size of the text of the whole page.",
221
+ title: words("Text size", "字体大小", "字型大小", "文字サイズ"),
222
+ shown: FONT_SHOWN
223
+ },
224
+ {
225
+ key: "chatFontSize",
226
+ type: "enum",
227
+ values: FONT_SIZES,
228
+ default: "standard",
229
+ what: "The size of the text of conversations, on top of fontSize.",
230
+ title: words("Text size of conversations", "对话字体大小", "對話字型大小", "会話の文字サイズ"),
231
+ shown: FONT_SHOWN
232
+ },
233
+ {
234
+ key: "speak",
235
+ type: "boolean",
236
+ default: false,
237
+ what: "Read every reply aloud.",
238
+ title: words("Read replies aloud", "朗读回复", "朗讀回覆", "返信を読み上げ")
239
+ },
240
+ {
241
+ key: "speakTalk",
242
+ type: "boolean",
243
+ default: false,
244
+ what: "Read the reply aloud when the user spoke to the double by voice.",
245
+ title: words("Read aloud what was asked by voice", "语音提问时朗读回复", "語音提問時朗讀回覆", "音声で聞いたら読み上げ")
246
+ },
247
+ {
248
+ key: "callCaptions",
249
+ type: "boolean",
250
+ default: false,
251
+ what: "Show captions in a call: what the user says and what Ta reads.",
252
+ title: words("Call captions", "通话字幕", "通話字幕", "通話の字幕")
253
+ },
254
+ {
255
+ key: "voice",
256
+ type: "string",
257
+ default: "",
258
+ what: "The voice replies are read with (a voiceURI of the device's voices); empty for the most natural one.",
259
+ title: words("Voice", "朗读声音", "朗讀聲音", "読み上げの声")
260
+ },
261
+ {
262
+ key: "confirmTasks",
263
+ type: "boolean",
264
+ default: false,
265
+ what: "The double asks before it hands out work.",
266
+ title: words("Ask before handing out work", "派任务前先问我", "派任務前先問我", "作業を割り当てる前に確認")
267
+ },
268
+ {
269
+ key: "maxTasks",
270
+ type: "number",
271
+ values: [0, 2, 4, 8],
272
+ default: 0,
273
+ what: "How many of the double's tasks run at once; 0 for as many as it starts.",
274
+ title: words("Tasks at once", "同时运行的任务", "同時執行的任務", "同時に実行するタスク")
275
+ },
276
+ {
277
+ key: "delegate",
278
+ type: "enum",
279
+ values: TaDelegateUtil.LEVELS,
280
+ default: TaDelegateUtil.DEFAULT,
281
+ what: "How much of the work the double hands out to tasks rather than doing it itself.",
282
+ title: words("Hand out work", "派活多少", "派活多少", "作業の割り当て"),
283
+ shown: { less: words("less", "少", "少", "少なめ"), balanced: words("balanced", "适中", "適中", "ふつう"), more: words("more", "多", "多", "多め") }
284
+ },
285
+ {
286
+ key: "assistantModel",
287
+ type: "model",
288
+ default: "",
289
+ what: "The model of the double, <provider>/<model id>; empty for the default model.",
290
+ title: words("Model of the double", "分身的模型", "分身的模型", "分身のモデル")
291
+ },
292
+ {
293
+ key: "taskModel",
294
+ type: "model",
295
+ default: "",
296
+ what: "The model of the tasks the double starts; empty for the default model.",
297
+ title: words("Model of tasks", "任务的模型", "任務的模型", "タスクのモデル")
298
+ },
299
+ { key: "reduceMotion", type: "boolean", default: false, what: "Fewer animations.", title: words("Reduce motion", "减少动画", "減少動畫", "動きを減らす") },
300
+ {
301
+ key: "keepAliveMinutes",
302
+ type: "number",
303
+ values: [1, 5, 15, 30],
304
+ default: 5,
305
+ what: "How long an extension started on open keeps running once left, in minutes.",
306
+ title: words("Keep extensions running", "扩展离开后保留", "擴充功能離開後保留", "拡張機能を保持")
307
+ },
308
+ {
309
+ key: "chatFoldDays",
310
+ type: "number",
311
+ values: [3, 7, 30, 0],
312
+ default: 7,
313
+ what: "Conversations not updated for these days fold at the end of the list; 0 for none.",
314
+ title: words("Fold old conversations", "折叠旧对话", "摺疊舊對話", "古い会話を折りたたむ")
315
+ },
316
+ {
317
+ key: "chatArchiveDays",
318
+ type: "number",
319
+ values: [30, 90, 365, 0],
320
+ default: 30,
321
+ what: "Conversations not updated for these days are archived (out of the list, found by search); 0 for none.",
322
+ title: words("Archive old conversations", "归档旧对话", "歸檔舊對話", "古い会話をアーカイブ")
323
+ },
324
+ {
325
+ key: "recentShots",
326
+ type: "boolean",
327
+ default: true,
328
+ what: "The screenshot just taken is offered above the message box, once.",
329
+ title: words("Offer recent screenshots", "提示刚截的图", "提示剛截的圖", "撮ったばかりのスクリーンショットを提案")
330
+ }
331
+ ];
332
+ var TaAppUtil;
333
+ (function(TaAppUtil2) {
334
+ function check(spec, value) {
335
+ var _a, _b;
336
+ switch (spec.type) {
337
+ case "boolean":
338
+ return typeof value === "boolean" ? undefined : "true or false";
339
+ case "string":
340
+ return typeof value === "string" ? undefined : "a string";
341
+ case "model":
342
+ return value === "" || typeof value === "string" && /^[^/\s]+\/\S+$/.test(value) ? undefined : "<provider>/<model id>, or empty";
343
+ default:
344
+ return ((_a = spec.values) === null || _a === undefined ? undefined : _a.includes(value)) ? undefined : `one of ${(_b = spec.values) === null || _b === undefined ? undefined : _b.map((one) => JSON.stringify(one)).join(", ")}`;
345
+ }
346
+ }
347
+ TaAppUtil2.check = check;
348
+ function shown(value, language, spec) {
349
+ var _a;
350
+ const named = (_a = spec === null || spec === undefined ? undefined : spec.shown) === null || _a === undefined ? undefined : _a[String(value)];
351
+ if (named) {
352
+ return TaLanguageUtil.pick(language, named);
353
+ }
354
+ if (typeof value === "boolean") {
355
+ return TaLanguageUtil.pick(language, value ? words("on", "开", "開", "オン") : words("off", "关", "關", "オフ"));
356
+ }
357
+ if (value === "" || value === undefined || value === null) {
358
+ return TaLanguageUtil.pick(language, words("default", "默认", "預設", "デフォルト"));
359
+ }
360
+ return String(value);
361
+ }
362
+ TaAppUtil2.shown = shown;
363
+ })(TaAppUtil || (TaAppUtil = {}));
364
+
365
+ // web-src/app-protocol.ts
366
+ var DONE_KEY = "done";
367
+ var DONE_MAX = 20;
368
+
369
+ // web-src/app-util.ts
370
+ var DATA_CHARS = 8000;
371
+ var AppUseUtil;
372
+ ((AppUseUtil) => {
373
+ function find(commands, query) {
374
+ const words2 = (query ?? "").toLowerCase().split(/\s+/).filter(Boolean);
375
+ if (!words2.length) {
376
+ return [...commands];
377
+ }
378
+ return commands.filter((command) => {
379
+ const text = `${command.id} ${command.description}`.toLowerCase();
380
+ return words2.some((word) => text.includes(word));
381
+ });
382
+ }
383
+ AppUseUtil.find = find;
384
+ function listText(commands) {
385
+ if (!commands.length) {
386
+ return "No action matches; app_commands without a query lists them all.";
387
+ }
388
+ return commands.map((command) => {
389
+ const properties = command.input?.properties;
390
+ const required = command.input?.required;
391
+ const input = properties ? ` Input: ${JSON.stringify(properties)}${Array.isArray(required) && required.length ? `, required ${required.join(", ")}` : ""}.` : " No input.";
392
+ return `- ${command.id} (${command.risk}${command.owner ? `, of ${command.owner}` : ""}): ${command.description}${input}`;
393
+ }).join(`
394
+ `);
395
+ }
396
+ AppUseUtil.listText = listText;
397
+ function resultText(result) {
398
+ const lines = [result.text];
399
+ if (result.data !== undefined) {
400
+ const data = JSON.stringify(result.data);
401
+ lines.push(data.length > DATA_CHARS ? `${data.slice(0, DATA_CHARS)}… (cut; narrow it down)` : data);
402
+ }
403
+ if (result.notice) {
404
+ lines.push(`The user's pages show it already, and a notice with Undo.`);
405
+ }
406
+ return lines.join(`
407
+ `);
408
+ }
409
+ AppUseUtil.resultText = resultText;
410
+ function add(done, entry) {
411
+ return [...entries(done), entry].slice(-DONE_MAX);
412
+ }
413
+ AppUseUtil.add = add;
414
+ function entries(done) {
415
+ return Array.isArray(done) ? done.filter((one) => !!one && typeof one === "object" && typeof one.id === "string" && typeof one.notice === "string" && typeof one.at === "number") : [];
416
+ }
417
+ AppUseUtil.entries = entries;
418
+ function fresh(done, since) {
419
+ return entries(done).filter((entry) => entry.at > since && !entry.undone);
420
+ }
421
+ AppUseUtil.fresh = fresh;
422
+ })(AppUseUtil ||= {});
423
+
424
+ // web-src/i18n.ts
425
+ var EN = {
426
+ undo: "Undo",
427
+ commands: "Look up what Ta can do",
428
+ run: "Do in Ta",
429
+ "settings.get": "Read settings",
430
+ "settings.set": "Change settings",
431
+ "chats.list": "Read conversations",
432
+ "chats.pin": "Pin conversation",
433
+ unpin: "Unpin conversation",
434
+ "chats.stop": "Stop conversation",
435
+ "extensions.list": "Read extensions",
436
+ "extensions.set": "Turn extension on or off",
437
+ "asks.list": "Read what waits for you",
438
+ "asks.answer": "Answer for you",
439
+ look: "Look at the screen",
440
+ go: "Go to",
441
+ do: "Do on the screen",
442
+ screen: "Ta's screen",
443
+ operating: "Ta is at work",
444
+ watch: "Watch",
445
+ stop: "Stop",
446
+ bigger: "Larger",
447
+ smaller: "Smaller",
448
+ hide: "Hide",
449
+ settings: "Settings",
450
+ discover: "Discover",
451
+ on: "Turn on",
452
+ off: "Turn off"
453
+ };
454
+ var ZH = {
455
+ undo: "撤销",
456
+ commands: "查看 Ta 能做什么",
457
+ run: "在 Ta 里操作",
458
+ "settings.get": "查看设置",
459
+ "settings.set": "修改设置",
460
+ "chats.list": "查看对话",
461
+ "chats.pin": "置顶对话",
462
+ unpin: "取消置顶",
463
+ "chats.stop": "停止对话",
464
+ "extensions.list": "查看扩展",
465
+ "extensions.set": "开关扩展",
466
+ "asks.list": "查看待你决定",
467
+ "asks.answer": "替你回答",
468
+ look: "看看屏幕",
469
+ go: "打开",
470
+ do: "在屏幕上操作",
471
+ screen: "Ta 的屏幕",
472
+ operating: "Ta 正在操作",
473
+ watch: "看看",
474
+ stop: "停止",
475
+ bigger: "放大",
476
+ smaller: "缩小",
477
+ hide: "收起",
478
+ settings: "设置",
479
+ discover: "发现",
480
+ on: "打开",
481
+ off: "关掉"
482
+ };
483
+ var ZH_TW = {
484
+ undo: "復原",
485
+ commands: "查看 Ta 能做什麼",
486
+ run: "在 Ta 裡操作",
487
+ "settings.get": "查看設定",
488
+ "settings.set": "修改設定",
489
+ "chats.list": "查看對話",
490
+ "chats.pin": "置頂對話",
491
+ unpin: "取消置頂",
492
+ "chats.stop": "停止對話",
493
+ "extensions.list": "查看擴充功能",
494
+ "extensions.set": "開關擴充功能",
495
+ "asks.list": "查看待你決定",
496
+ "asks.answer": "替你回答",
497
+ look: "看看螢幕",
498
+ go: "打開",
499
+ do: "在螢幕上操作",
500
+ screen: "Ta 的螢幕",
501
+ operating: "Ta 正在操作",
502
+ watch: "看看",
503
+ stop: "停止",
504
+ bigger: "放大",
505
+ smaller: "縮小",
506
+ hide: "收起",
507
+ settings: "設定",
508
+ discover: "發現",
509
+ on: "開啟",
510
+ off: "關閉"
511
+ };
512
+ var JA = {
513
+ undo: "元に戻す",
514
+ commands: "Ta にできることを確認",
515
+ run: "Ta で操作",
516
+ "settings.get": "設定を確認",
517
+ "settings.set": "設定を変更",
518
+ "chats.list": "会話を確認",
519
+ "chats.pin": "会話をピン留め",
520
+ unpin: "ピン留めを外す",
521
+ "chats.stop": "会話を停止",
522
+ "extensions.list": "拡張機能を確認",
523
+ "extensions.set": "拡張機能をオン・オフ",
524
+ "asks.list": "あなたの判断待ちを確認",
525
+ "asks.answer": "代わりに回答",
526
+ look: "画面を見る",
527
+ go: "開く",
528
+ do: "画面で操作",
529
+ screen: "Ta の画面",
530
+ operating: "Ta が操作中",
531
+ watch: "見る",
532
+ stop: "停止",
533
+ bigger: "拡大",
534
+ smaller: "縮小",
535
+ hide: "しまう",
536
+ settings: "設定",
537
+ discover: "見つける",
538
+ on: "オンにする",
539
+ off: "オフにする"
540
+ };
541
+ var WORDS = { "zh-CN": ZH, "zh-TW": ZH_TW, "en-US": EN, "ja-JP": JA };
542
+ var AppUseWords;
543
+ ((AppUseWords) => {
544
+ function of(language) {
545
+ return TaLanguageUtil.pick(language, WORDS);
546
+ }
547
+ AppUseWords.of = of;
548
+ })(AppUseWords ||= {});
549
+
550
+ // web-src/screen-cursor.ts
551
+ var STYLE = `
552
+ .ta-agent-layer { position: fixed; inset: 0; pointer-events: none; z-index: 2147483646; }
553
+ .ta-agent-cursor { position: absolute; left: 0; top: 0; transform: translate3d(-40px, -40px, 0); transition: transform 300ms cubic-bezier(.2,.8,.2,1), opacity 200ms; opacity: 0; will-change: transform; }
554
+ .ta-agent-cursor[data-shown] { opacity: 1; }
555
+ .ta-agent-cursor svg { display: block; filter: drop-shadow(0 2px 4px rgba(0,0,0,.25)); transition: transform 120ms; transform-origin: 3px 3px; }
556
+ .ta-agent-cursor[data-press] svg { transform: scale(.86); }
557
+ .ta-agent-caption { position: absolute; left: 22px; top: 20px; max-width: 260px; padding: 4px 9px; border-radius: 9px; background: var(--ta-accent, #07c160); color: #fff; font: 500 12px/1.4 var(--ta-sans, system-ui, sans-serif); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; box-shadow: 0 4px 12px rgba(0,0,0,.18); }
558
+ .ta-agent-caption:empty { display: none; }
559
+ .ta-agent-ring { position: absolute; border-radius: 10px; box-shadow: 0 0 0 2px var(--ta-accent, #07c160), 0 0 0 6px color-mix(in srgb, var(--ta-accent, #07c160) 22%, transparent); opacity: 0; transition: opacity 160ms, left 300ms cubic-bezier(.2,.8,.2,1), top 300ms cubic-bezier(.2,.8,.2,1), width 300ms, height 300ms; }
560
+ .ta-agent-ring[data-shown] { opacity: 1; }
561
+ .ta-agent-ripple { position: absolute; width: 36px; height: 36px; margin: -18px 0 0 -18px; border-radius: 50%; background: color-mix(in srgb, var(--ta-accent, #07c160) 35%, transparent); animation: ta-agent-ripple 420ms ease-out forwards; }
562
+ @keyframes ta-agent-ripple { from { transform: scale(.2); opacity: 1; } to { transform: scale(1.6); opacity: 0; } }
563
+ @media (prefers-reduced-motion: reduce) { .ta-agent-cursor, .ta-agent-ring { transition: none; } .ta-agent-ripple { animation-duration: 1ms; } }
564
+ `;
565
+ var ARROW = '<svg width="22" height="22" viewBox="0 0 22 22"><path d="M3 2.5 L18 11 L11 12.6 L7.6 19.5 Z" fill="var(--ta-accent, #07c160)" stroke="#fff" stroke-width="1.6" stroke-linejoin="round"/></svg>';
566
+ var wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
567
+
568
+ class ScreenCursor {
569
+ document;
570
+ layer;
571
+ pointer;
572
+ caption;
573
+ ring;
574
+ hideTimer;
575
+ at = { x: -40, y: -40 };
576
+ constructor(document2) {
577
+ this.document = document2;
578
+ }
579
+ async point(element, says) {
580
+ this.mount();
581
+ clearTimeout(this.hideTimer);
582
+ const view = this.document.defaultView;
583
+ let rect = element.getBoundingClientRect();
584
+ if (view && (rect.top < 0 || rect.bottom > view.innerHeight || rect.left < 0 || rect.right > view.innerWidth)) {
585
+ element.scrollIntoView({ block: "center", inline: "nearest", behavior: "smooth" });
586
+ await wait(320);
587
+ rect = element.getBoundingClientRect();
588
+ }
589
+ const x = rect.left + Math.min(rect.width / 2, 40);
590
+ const y = rect.top + rect.height / 2;
591
+ const { pointer, caption, ring } = this.parts();
592
+ caption.textContent = says;
593
+ if (this.at.x < 0) {
594
+ pointer.style.transition = "none";
595
+ pointer.style.transform = `translate3d(${x + 60}px, ${y + 50}px, 0)`;
596
+ pointer.getBoundingClientRect();
597
+ pointer.style.transition = "";
598
+ }
599
+ pointer.dataset.shown = "";
600
+ pointer.style.transform = `translate3d(${x}px, ${y}px, 0)`;
601
+ Object.assign(ring.style, { left: `${rect.left - 3}px`, top: `${rect.top - 3}px`, width: `${rect.width + 6}px`, height: `${rect.height + 6}px` });
602
+ ring.dataset.shown = "";
603
+ this.at = { x, y };
604
+ await wait(320);
605
+ }
606
+ async press() {
607
+ const { pointer } = this.parts();
608
+ pointer.dataset.press = "";
609
+ const ripple = this.document.createElement("div");
610
+ ripple.className = "ta-agent-ripple";
611
+ Object.assign(ripple.style, { left: `${this.at.x}px`, top: `${this.at.y}px` });
612
+ this.layer?.appendChild(ripple);
613
+ await wait(140);
614
+ delete pointer.dataset.press;
615
+ setTimeout(() => ripple.remove(), 500);
616
+ }
617
+ async type(text, set) {
618
+ const slow = Math.min(text.length, 32);
619
+ for (let index = 1;index <= slow; index++) {
620
+ set(text.slice(0, index));
621
+ await wait(18);
622
+ }
623
+ if (text.length > slow) {
624
+ set(text);
625
+ }
626
+ }
627
+ rest() {
628
+ clearTimeout(this.hideTimer);
629
+ this.hideTimer = setTimeout(() => {
630
+ if (this.pointer) {
631
+ delete this.pointer.dataset.shown;
632
+ }
633
+ if (this.ring) {
634
+ delete this.ring.dataset.shown;
635
+ }
636
+ this.at = { x: -40, y: -40 };
637
+ }, 1600);
638
+ }
639
+ dispose() {
640
+ clearTimeout(this.hideTimer);
641
+ this.layer?.remove();
642
+ this.layer = undefined;
643
+ }
644
+ parts() {
645
+ this.mount();
646
+ return { pointer: this.pointer, caption: this.caption, ring: this.ring };
647
+ }
648
+ mount() {
649
+ if (this.layer?.isConnected) {
650
+ return;
651
+ }
652
+ const document2 = this.document;
653
+ if (!document2.getElementById("ta-agent-style")) {
654
+ const style = document2.createElement("style");
655
+ style.id = "ta-agent-style";
656
+ style.textContent = STYLE;
657
+ document2.head.appendChild(style);
658
+ }
659
+ const layer = document2.createElement("div");
660
+ layer.className = "ta-agent-layer";
661
+ layer.setAttribute("aria-hidden", "true");
662
+ const ring = document2.createElement("div");
663
+ ring.className = "ta-agent-ring";
664
+ const pointer = document2.createElement("div");
665
+ pointer.className = "ta-agent-cursor";
666
+ pointer.innerHTML = ARROW;
667
+ const caption = document2.createElement("div");
668
+ caption.className = "ta-agent-caption";
669
+ pointer.appendChild(caption);
670
+ layer.append(ring, pointer);
671
+ document2.body.appendChild(layer);
672
+ Object.assign(this, { layer, pointer, caption, ring });
673
+ }
674
+ }
675
+
676
+ // web-src/screen-dom.ts
677
+ var CONTROLS = [
678
+ "button",
679
+ "a[href]",
680
+ "input:not([type=hidden])",
681
+ "textarea",
682
+ "select",
683
+ '[contenteditable="true"]',
684
+ "[role=button]",
685
+ "[role=link]",
686
+ "[role=switch]",
687
+ "[role=checkbox]",
688
+ "[role=tab]",
689
+ "[role=menuitem]",
690
+ "[role=option]",
691
+ "[role=textbox]"
692
+ ].join(",");
693
+ var DIALOGS = "[role=dialog], [role=alertdialog], dialog[open]";
694
+ var ScreenDom;
695
+ ((ScreenDom) => {
696
+ function visible(element) {
697
+ const html = element;
698
+ if (typeof html.checkVisibility === "function" && !html.checkVisibility({ opacityProperty: true, visibilityProperty: true })) {
699
+ return false;
700
+ }
701
+ const rect = html.getBoundingClientRect();
702
+ const view = html.ownerDocument.defaultView;
703
+ return rect.width > 0 && rect.height > 0 && rect.bottom > 0 && rect.right > 0 && rect.top < (view?.innerHeight ?? 0) && rect.left < (view?.innerWidth ?? 0);
704
+ }
705
+ ScreenDom.visible = visible;
706
+ function controls(document2) {
707
+ const dialogs = [...document2.querySelectorAll(DIALOGS)].filter(visible);
708
+ const dialog = dialogs[dialogs.length - 1];
709
+ const root = dialog ?? document2;
710
+ const title = dialog ? labelOf(dialog) || headingOf(dialog) || "" : undefined;
711
+ const controls2 = [];
712
+ const elements = [];
713
+ for (const element of root.querySelectorAll(CONTROLS)) {
714
+ if (element.closest("[data-ta-item], [data-ta-action], .ta-agent-layer, .ta-rail-item") || element.closest('[aria-hidden="true"], [inert]') || !visible(element)) {
715
+ continue;
716
+ }
717
+ const control = read(element);
718
+ if (!control) {
719
+ continue;
720
+ }
721
+ if (title !== undefined) {
722
+ control.dialog = title;
723
+ }
724
+ controls2.push(control);
725
+ elements.push(element);
726
+ }
727
+ return { controls: controls2, elements };
728
+ }
729
+ ScreenDom.controls = controls;
730
+ function headings(document2) {
731
+ const found = [];
732
+ for (const heading of document2.querySelectorAll("h1, h2, [role=heading], .ta-main-head .ta-title, .ta-page-title")) {
733
+ const text = heading.textContent?.replace(/\s+/g, " ").trim();
734
+ if (text && visible(heading) && !found.includes(text)) {
735
+ found.push(text);
736
+ }
737
+ if (found.length >= 8) {
738
+ break;
739
+ }
740
+ }
741
+ return found;
742
+ }
743
+ ScreenDom.headings = headings;
744
+ function read(element) {
745
+ const role = element.getAttribute("role");
746
+ const tag = element.tagName.toLowerCase();
747
+ const type = (element.getAttribute("type") ?? "").toLowerCase();
748
+ const kind = role === "switch" || tag === "input" && type === "checkbox" && element.closest(".ta-switch") ? "switch" : role === "checkbox" || tag === "input" && (type === "checkbox" || type === "radio") ? "checkbox" : tag === "select" ? "select" : tag === "textarea" || tag === "input" && !["button", "submit", "reset", "image", "range", "color", "file"].includes(type) || role === "textbox" || element.isContentEditable ? "textbox" : role === "tab" ? "tab" : role === "menuitem" ? "menuitem" : role === "option" ? "option" : tag === "a" || role === "link" ? "link" : tag === "button" || role === "button" || tag === "input" && ["button", "submit", "reset"].includes(type) ? "button" : undefined;
749
+ if (!kind) {
750
+ return;
751
+ }
752
+ const label = labelOf(element) || (kind === "textbox" ? element.getAttribute("placeholder") || "" : "");
753
+ if (!label) {
754
+ return;
755
+ }
756
+ const control = { kind, label };
757
+ if (kind === "switch" || kind === "checkbox") {
758
+ const aria = element.getAttribute("aria-checked");
759
+ control.checked = aria !== null ? aria === "true" : element.checked === true;
760
+ } else if (kind === "textbox") {
761
+ control.value = element.isContentEditable ? element.textContent ?? "" : element.value ?? "";
762
+ } else if (kind === "select") {
763
+ const select = element;
764
+ control.value = select.selectedOptions[0]?.textContent?.trim() ?? select.value;
765
+ }
766
+ if (element.matches(".ta-danger, .ta-danger *, [data-danger]") || /\bdanger\b/.test(element.className)) {
767
+ control.danger = true;
768
+ }
769
+ return control;
770
+ }
771
+ function labelOf(element) {
772
+ const aria = element.getAttribute("aria-label");
773
+ if (aria?.trim()) {
774
+ return clean(aria);
775
+ }
776
+ const by = element.getAttribute("aria-labelledby");
777
+ if (by) {
778
+ const text = by.split(/\s+/).map((id2) => element.ownerDocument.getElementById(id2)?.textContent ?? "").join(" ");
779
+ if (text.trim()) {
780
+ return clean(text);
781
+ }
782
+ }
783
+ const id = element.getAttribute("id");
784
+ const forLabel = id ? element.ownerDocument.querySelector(`label[for="${CSS.escape(id)}"]`) : null;
785
+ const label = forLabel ?? element.closest("label");
786
+ if (label && label !== element && label.textContent?.trim()) {
787
+ return clean(label.textContent);
788
+ }
789
+ const tag = element.tagName.toLowerCase();
790
+ if (tag !== "input" && tag !== "textarea" && tag !== "select") {
791
+ const words2 = clean(element.textContent ?? "");
792
+ if (words2) {
793
+ return words2;
794
+ }
795
+ }
796
+ const row = element.closest(".ta-setting-row, .ta-list-row, [data-setting]");
797
+ const rowLabel = row?.querySelector(".ta-setting-label, .ta-list-label, label");
798
+ if (rowLabel?.textContent?.trim()) {
799
+ return clean(rowLabel.textContent);
800
+ }
801
+ return clean(element.getAttribute("title") ?? element.querySelector("img")?.getAttribute("alt") ?? "");
802
+ }
803
+ ScreenDom.labelOf = labelOf;
804
+ function headingOf(element) {
805
+ return clean(element.querySelector("h1, h2, h3, [role=heading], .ta-dialog-title")?.textContent ?? "");
806
+ }
807
+ function clean(text) {
808
+ const one = text.replace(/\s+/g, " ").trim();
809
+ return one.length > 80 ? `${one.slice(0, 79)}…` : one;
810
+ }
811
+ })(ScreenDom ||= {});
812
+
813
+ // web-src/screen-protocol.ts
814
+ var LOOK_MAX = 3000;
815
+ var CONTROLS_MAX = 50;
816
+
817
+ // web-src/screen-text.ts
818
+ var ScreenText;
819
+ ((ScreenText) => {
820
+ const cut = (text, length) => text.length > length ? `${text.slice(0, length - 1)}…` : text;
821
+ function look(sight, only) {
822
+ const targets = new Map;
823
+ const lines = [];
824
+ if (!only) {
825
+ lines.push(`${sight.whose === "user" ? "The user's screen" : "Ta's screen"} (${sight.device}): ${sight.where || "starting"}`);
826
+ if (sight.places.length) {
827
+ lines.push(`Places (app_go to): ${sight.places.map((place) => `${place.id} “${place.title}”`).join(" · ")} · chat:<name> a conversation`);
828
+ }
829
+ if (sight.headings.length) {
830
+ lines.push(`Headings: ${sight.headings.map((heading) => cut(heading, 60)).join(" · ")}`);
831
+ }
832
+ }
833
+ sight.parts.forEach((part, index) => {
834
+ const id = `p${index + 1}`;
835
+ targets.set(id, { part: part.id });
836
+ if (only && only !== part.id && only !== id) {
837
+ return;
838
+ }
839
+ lines.push("", `[${id}] ${part.title}${part.state ? ` — ${part.state}` : ""}`);
840
+ part.items.forEach((item, itemIndex) => {
841
+ const itemId = `${id}.${itemIndex + 1}`;
842
+ targets.set(itemId, { part: part.id, item: item.id });
843
+ lines.push(` [${itemId}] ${cut(item.text, 200)}${item.marks?.length ? ` · ${item.marks.map((mark) => cut(mark, 80)).join(" · ")}` : ""}`);
844
+ });
845
+ if (part.actions.length) {
846
+ const actions = part.actions.map((action) => `${action.name}${action.label.toLowerCase() !== action.name ? ` “${action.label}”` : ""}${action.each ? " [a row]" : ""}${action.takes ? ` (${action.takes})` : ""}${action.command ? ` = app_run ${action.command}` : ""}${action.danger ? " !danger" : ""}`);
847
+ lines.push(` does: ${actions.join(" · ")}`);
848
+ }
849
+ });
850
+ const controls = sight.controls.slice(0, CONTROLS_MAX);
851
+ controls.forEach((_control, index) => {
852
+ targets.set(`e${index + 1}`, { control: index });
853
+ });
854
+ if (!only && controls.length) {
855
+ lines.push("", "Also on the screen:");
856
+ let dialog;
857
+ controls.forEach((control, index) => {
858
+ if (control.dialog !== dialog) {
859
+ dialog = control.dialog;
860
+ if (dialog !== undefined) {
861
+ lines.push(` Dialog “${cut(dialog, 80)}”:`);
862
+ }
863
+ }
864
+ const state = control.checked !== undefined ? control.checked ? " on" : " off" : control.value !== undefined ? ` = “${cut(control.value, 80)}”` : "";
865
+ lines.push(` ${control.dialog !== undefined ? " " : ""}[e${index + 1}] ${control.kind} “${cut(control.label, 80)}”${state}${control.danger ? " !danger" : ""}`);
866
+ });
867
+ if (sight.controls.length > controls.length) {
868
+ lines.push(` … ${sight.controls.length - controls.length} more: look at a part, or go elsewhere.`);
869
+ }
870
+ }
871
+ const all = lines.join(`
872
+ `).trim();
873
+ return { text: all.length > LOOK_MAX ? `${all.slice(0, LOOK_MAX - 40)}
874
+ … (more: app_look a part)` : all, targets };
875
+ }
876
+ ScreenText.look = look;
877
+ })(ScreenText ||= {});
878
+
879
+ // web-src/screen-driver.ts
880
+ var wait2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
881
+
882
+ class ScreenDriver {
883
+ window;
884
+ host;
885
+ targets = new Map;
886
+ elements = [];
887
+ cursor;
888
+ constructor(window2, host) {
889
+ this.window = window2;
890
+ this.host = host;
891
+ this.cursor = new ScreenCursor(window2.document);
892
+ }
893
+ async ready(timeoutMs = 20000) {
894
+ const until = Date.now() + timeoutMs;
895
+ while (!this.host.screen.where() && Date.now() < until) {
896
+ await wait2(150);
897
+ }
898
+ await wait2(200);
899
+ }
900
+ look(part) {
901
+ const { controls, elements } = ScreenDom.controls(this.window.document);
902
+ const sight = {
903
+ whose: this.host.user ? "user" : "ta",
904
+ device: this.host.device(),
905
+ where: this.host.screen.where(),
906
+ places: this.host.screen.places(),
907
+ parts: this.host.screen.parts(),
908
+ controls,
909
+ headings: ScreenDom.headings(this.window.document)
910
+ };
911
+ const { text, targets } = ScreenText.look(sight, part);
912
+ this.targets = targets;
913
+ this.elements = elements;
914
+ return text;
915
+ }
916
+ async go(to) {
917
+ const word = to.trim().toLowerCase();
918
+ const place = this.host.screen.places().find((one) => one.id.toLowerCase() === word || one.title.toLowerCase() === word);
919
+ const button = place && this.window.document.querySelector(`[data-ta-place="${CSS.escape(place.id)}"]`);
920
+ if (button && ScreenDom.visible(button) && this.host.watched()) {
921
+ await this.cursor.point(button, place.title);
922
+ await this.cursor.press();
923
+ }
924
+ if (!await this.host.screen.go(to)) {
925
+ throw new Error(`There is no place ${JSON.stringify(to)}: see the places of app_look.`);
926
+ }
927
+ await wait2(450);
928
+ this.cursor.rest();
929
+ return this.look();
930
+ }
931
+ async do(id, action, input = {}, options = {}) {
932
+ if (!this.targets.size) {
933
+ this.look();
934
+ }
935
+ const target = this.targets.get(id.replace(/^\[|\]$/g, ""));
936
+ if (!target) {
937
+ throw new Error(`Nothing on the screen is [${id}] now: app_look again.`);
938
+ }
939
+ const answer = "part" in target ? await this.part(target, action, input, options) : await this.control(target.control, action, input, options);
940
+ this.cursor.rest();
941
+ return answer;
942
+ }
943
+ dispose() {
944
+ this.cursor.dispose();
945
+ }
946
+ async part(target, name, input, options) {
947
+ const part = this.host.screen.parts().find((one) => one.id === target.part);
948
+ const action = part?.actions.find((one) => one.name === name) ?? (target.item ? part?.actions.find((one) => one.name === "open") : undefined);
949
+ if (!part || !action) {
950
+ throw new Error(part ? `Say what to do to it: ${part.actions.map((one) => one.name).join(", ")}.` : "That part is gone: app_look again.");
951
+ }
952
+ const item = target.item ? part.items.find((one) => one.id === target.item) : undefined;
953
+ const says = `${action.label}${item ? ` “${item.text.slice(0, 30)}”` : ""}`;
954
+ if (action.danger && !await this.agree(says, options)) {
955
+ return { text: "The user did not agree: it was not done." };
956
+ }
957
+ const show = options.show === true || !action.command;
958
+ if (show && this.host.watched()) {
959
+ const element = this.host.screen.element(target.part, target.item, action.name);
960
+ if (element) {
961
+ await this.cursor.point(element, says);
962
+ await this.cursor.press();
963
+ }
964
+ }
965
+ const done = await this.host.screen.act(target.part, action.name, target.item, input, show);
966
+ if ("command" in done) {
967
+ return { text: says, command: done.command, input: done.input };
968
+ }
969
+ await wait2(350);
970
+ return { text: `${done.text ?? "Done."}
971
+
972
+ ${this.look(target.part)}` };
973
+ }
974
+ async control(index, action, input, options) {
975
+ const element = this.elements[index];
976
+ if (!element?.isConnected || !ScreenDom.visible(element)) {
977
+ throw new Error("It is not on the screen any more: app_look again.");
978
+ }
979
+ const label = ScreenDom.labelOf(element);
980
+ const text = typeof input.text === "string" ? input.text : typeof input.value === "string" ? input.value : undefined;
981
+ const typing = element.matches('input:not([type=checkbox]):not([type=radio]):not([type=button]):not([type=submit]), textarea, [contenteditable="true"], [role=textbox]');
982
+ const choosing = element.tagName.toLowerCase() === "select";
983
+ if ((typing || choosing) && text === undefined) {
984
+ throw new Error(`Say what to ${choosing ? "choose" : "type"}: input.text.`);
985
+ }
986
+ const danger = element.matches(".ta-danger, .ta-danger *, [data-danger]") || /\bdanger\b/.test(element.className);
987
+ if (danger && !await this.agree(label, options)) {
988
+ return { text: "The user did not agree: it was not done." };
989
+ }
990
+ const watched = this.host.watched();
991
+ if (watched) {
992
+ await this.cursor.point(element, typing ? label : choosing ? `${label}: ${text}` : label);
993
+ await this.cursor.press();
994
+ }
995
+ if (typing) {
996
+ const set = (value) => this.setValue(element, value);
997
+ if (watched) {
998
+ await this.cursor.type(text ?? "", set);
999
+ } else {
1000
+ set(text ?? "");
1001
+ }
1002
+ if (input.submit === true || action === "submit") {
1003
+ for (const type of ["keydown", "keyup"]) {
1004
+ element.dispatchEvent(new KeyboardEvent(type, { key: "Enter", code: "Enter", bubbles: true, cancelable: true }));
1005
+ }
1006
+ }
1007
+ } else if (choosing) {
1008
+ const select = element;
1009
+ const option = [...select.options].find((one) => one.value === text || one.textContent?.trim() === text);
1010
+ if (!option) {
1011
+ throw new Error(`It has no choice ${JSON.stringify(text)}: ${[...select.options].map((one) => one.textContent?.trim()).join(", ")}.`);
1012
+ }
1013
+ this.setValue(element, option.value);
1014
+ } else {
1015
+ element.click();
1016
+ }
1017
+ await wait2(380);
1018
+ return { text: `Done.
1019
+
1020
+ ${this.look()}` };
1021
+ }
1022
+ async agree(what, options) {
1023
+ return options.confirm ? options.confirm(what) : false;
1024
+ }
1025
+ setValue(element, value) {
1026
+ const window2 = this.window;
1027
+ if (element.isContentEditable) {
1028
+ element.textContent = value;
1029
+ element.dispatchEvent(new window2.InputEvent("input", { bubbles: true }));
1030
+ return;
1031
+ }
1032
+ const proto = element instanceof window2.HTMLTextAreaElement ? window2.HTMLTextAreaElement.prototype : element instanceof window2.HTMLSelectElement ? window2.HTMLSelectElement.prototype : window2.HTMLInputElement.prototype;
1033
+ Object.getOwnPropertyDescriptor(proto, "value")?.set?.call(element, value);
1034
+ element.dispatchEvent(new window2.Event(element instanceof window2.HTMLSelectElement ? "change" : "input", { bubbles: true }));
1035
+ }
1036
+ }
1037
+
1038
+ // web-src/screen-window.ts
1039
+ var SCREEN_IDLE_MS = 2 * 60000;
1040
+ var STYLE2 = `
1041
+ .ta-screen-box { position: fixed; z-index: 2147483000; display: flex; flex-direction: column; overflow: hidden; border-radius: 14px; border: 1px solid var(--ta-border, rgba(0,0,0,.12)); background: var(--ta-side, #fff); color: var(--ta-text, #111); box-shadow: var(--ta-shadow-pop, 0 12px 32px rgba(0,0,0,.18)); font: 13px/1.4 var(--ta-sans, system-ui, sans-serif); transition: transform 260ms cubic-bezier(.2,.8,.2,1), opacity 200ms; }
1042
+ .ta-screen-box[data-hidden] { transform: translate3d(0, 24px, 0); opacity: 0; pointer-events: none; }
1043
+ .ta-screen-box[data-away] { left: -300vw !important; top: 0 !important; transition: none; }
1044
+ .ta-screen-head { flex: none; display: flex; align-items: center; gap: 8px; height: 36px; padding: 0 6px 0 12px; border-bottom: 1px solid var(--ta-border-muted, rgba(0,0,0,.08)); cursor: grab; user-select: none; touch-action: none; }
1045
+ .ta-screen-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--ta-muted, #aaa); flex: none; }
1046
+ .ta-screen-box[data-busy] .ta-screen-dot, .ta-screen-pill .ta-screen-dot { background: var(--ta-accent, #07c160); animation: ta-screen-pulse 1.2s ease-in-out infinite; }
1047
+ @keyframes ta-screen-pulse { 50% { opacity: .35; } }
1048
+ .ta-screen-title { flex: 1; min-width: 0; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
1049
+ .ta-screen-title small { margin-left: 6px; font-weight: 400; color: var(--ta-secondary, #666); }
1050
+ .ta-screen-button { flex: none; white-space: nowrap; height: 26px; padding: 0 9px; border: none; border-radius: 7px; background: transparent; color: var(--ta-secondary, #555); font: inherit; font-size: 12px; cursor: pointer; }
1051
+ .ta-screen-button:hover { background: var(--ta-hover, rgba(0,0,0,.06)); color: var(--ta-text, #111); }
1052
+ .ta-screen-button.ta-screen-stop { color: var(--ta-red, #e5484d); }
1053
+ .ta-screen-view { position: relative; flex: 1; overflow: hidden; background: var(--ta-body, #f2f2f2); }
1054
+ .ta-screen-view iframe { position: absolute; left: 0; top: 0; border: 0; transform-origin: 0 0; pointer-events: none; background: var(--ta-main, #fff); }
1055
+ .ta-screen-pill { position: fixed; z-index: 2147483001; left: 50%; top: calc(env(safe-area-inset-top, 0px) + 60px); transform: translate3d(-50%, 0, 0); display: flex; align-items: center; gap: 4px; height: 34px; padding: 0 4px 0 12px; border-radius: 17px; background: var(--ta-side, #fff); color: var(--ta-text, #111); border: 1px solid var(--ta-border, rgba(0,0,0,.12)); box-shadow: var(--ta-shadow-pop, 0 8px 24px rgba(0,0,0,.16)); font: 13px/1 var(--ta-sans, system-ui, sans-serif); transition: opacity 200ms, transform 260ms cubic-bezier(.2,.8,.2,1); }
1056
+ .ta-screen-pill[data-hidden] { opacity: 0; transform: translate3d(-50%, -12px, 0); pointer-events: none; }
1057
+ .ta-screen-pill span { margin: 0 4px 0 2px; font-weight: 600; white-space: nowrap; }
1058
+ @media (prefers-reduced-motion: reduce) { .ta-screen-box, .ta-screen-pill { transition: none; } .ta-screen-dot { animation: none !important; } }
1059
+ `;
1060
+ var wait3 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1061
+
1062
+ class ScreenWindow {
1063
+ pi;
1064
+ words;
1065
+ box;
1066
+ frame;
1067
+ pill;
1068
+ title;
1069
+ sizeButton;
1070
+ size = { width: 1280, height: 800 };
1071
+ big = false;
1072
+ awayFor;
1073
+ shownOnPhone = false;
1074
+ busy = 0;
1075
+ from;
1076
+ idleTimer;
1077
+ restTimer;
1078
+ own;
1079
+ position;
1080
+ constructor(pi, words2) {
1081
+ this.pi = pi;
1082
+ this.words = words2;
1083
+ }
1084
+ async run(ask) {
1085
+ if (ask.here) {
1086
+ return this.runHere(ask);
1087
+ }
1088
+ clearTimeout(this.idleTimer);
1089
+ this.begin(ask.from);
1090
+ const outer = document.activeElement;
1091
+ try {
1092
+ const driver = await this.driver();
1093
+ if (ask.kind === "look") {
1094
+ return { text: driver.look(ask.part) };
1095
+ }
1096
+ if (ask.kind === "go") {
1097
+ return { text: await driver.go(String(ask.to ?? "")) };
1098
+ }
1099
+ return await driver.do(String(ask.id ?? ""), ask.action, ask.input, { show: ask.show === true, confirm: (what) => this.confirm(what, ask) });
1100
+ } finally {
1101
+ if (document.activeElement === this.frame && outer instanceof HTMLElement) {
1102
+ outer.focus({ preventScroll: true });
1103
+ }
1104
+ this.end();
1105
+ }
1106
+ }
1107
+ dispose() {
1108
+ this.close();
1109
+ this.own?.dispose();
1110
+ }
1111
+ async runHere(ask) {
1112
+ const screen = this.pi.ui.screen;
1113
+ this.own ??= new ScreenDriver(window, { screen, watched: () => document.visibilityState === "visible", device: () => this.device(), user: true });
1114
+ if (ask.kind === "look") {
1115
+ return { text: this.own.look(ask.part) };
1116
+ }
1117
+ if (ask.kind === "go") {
1118
+ return { text: await this.own.go(String(ask.to ?? "")) };
1119
+ }
1120
+ return this.own.do(String(ask.id ?? ""), ask.action, ask.input, { show: true, confirm: (what) => this.confirm(what, ask) });
1121
+ }
1122
+ confirm(what, ask) {
1123
+ return this.pi.ui.confirm(`${ask.from?.name ?? "Ta"}: ${what}`, undefined, { danger: true });
1124
+ }
1125
+ device() {
1126
+ return window.innerWidth < 640 ? "phone" : "computer";
1127
+ }
1128
+ async driver() {
1129
+ if (!this.frame?.isConnected) {
1130
+ this.open();
1131
+ }
1132
+ const frame = this.frame;
1133
+ const until = Date.now() + 25000;
1134
+ const found = () => frame.contentWindow?.taScreen;
1135
+ while (!found() && Date.now() < until) {
1136
+ await wait3(150);
1137
+ }
1138
+ const driver = found();
1139
+ if (!driver) {
1140
+ this.close();
1141
+ throw new Error("Ta's screen did not open in time: try again, or do it with app_run.");
1142
+ }
1143
+ frame.contentWindow.taScreenWatched = () => this.watched();
1144
+ await driver.ready();
1145
+ return driver;
1146
+ }
1147
+ watched() {
1148
+ return !!this.box && !this.box.hasAttribute("data-hidden") && !this.box.hasAttribute("data-away") && document.visibilityState === "visible";
1149
+ }
1150
+ open() {
1151
+ this.style();
1152
+ const phone = this.device() === "phone";
1153
+ this.size = phone ? { width: window.innerWidth, height: window.innerHeight } : { width: Math.min(1440, Math.max(1024, window.innerWidth)), height: Math.min(900, Math.max(680, window.innerHeight)) };
1154
+ const box = document.createElement("div");
1155
+ box.className = "ta-screen-box";
1156
+ box.setAttribute("role", "region");
1157
+ box.dataset.hidden = "";
1158
+ const head = document.createElement("div");
1159
+ head.className = "ta-screen-head";
1160
+ const dot = document.createElement("span");
1161
+ dot.className = "ta-screen-dot";
1162
+ const title = document.createElement("div");
1163
+ title.className = "ta-screen-title";
1164
+ const sizeButton = this.button(this.words().bigger, () => this.resize(!this.big));
1165
+ const stop = this.button(this.words().stop, () => this.stop());
1166
+ stop.classList.add("ta-screen-stop");
1167
+ const hide = this.button(this.words().hide, () => this.putAway());
1168
+ head.append(dot, title, ...phone ? [] : [sizeButton], stop, hide);
1169
+ const view = document.createElement("div");
1170
+ view.className = "ta-screen-view";
1171
+ const frame = document.createElement("iframe");
1172
+ frame.title = this.words().screen;
1173
+ frame.tabIndex = -1;
1174
+ frame.setAttribute("aria-hidden", "true");
1175
+ frame.src = `${location.pathname}?ta-screen`;
1176
+ Object.assign(frame.style, { width: `${this.size.width}px`, height: `${this.size.height}px` });
1177
+ view.appendChild(frame);
1178
+ box.append(head, view);
1179
+ box.setAttribute("aria-label", this.words().screen);
1180
+ this.drag(head, box);
1181
+ document.body.appendChild(box);
1182
+ Object.assign(this, { box, frame, title, sizeButton });
1183
+ this.layout();
1184
+ this.away(true);
1185
+ }
1186
+ button(label, run) {
1187
+ const button = document.createElement("button");
1188
+ button.type = "button";
1189
+ button.className = "ta-screen-button";
1190
+ button.textContent = label;
1191
+ button.addEventListener("click", (event) => {
1192
+ event.stopPropagation();
1193
+ run();
1194
+ });
1195
+ button.addEventListener("pointerdown", (event) => event.stopPropagation());
1196
+ return button;
1197
+ }
1198
+ layout() {
1199
+ const box = this.box;
1200
+ const frame = this.frame;
1201
+ if (!box || !frame) {
1202
+ return;
1203
+ }
1204
+ if (this.device() === "phone") {
1205
+ const height = Math.round(window.innerHeight * 0.74);
1206
+ const scale2 = Math.min(1, (height - 36) / this.size.height, window.innerWidth / this.size.width);
1207
+ Object.assign(box.style, {
1208
+ left: "0px",
1209
+ right: "0px",
1210
+ bottom: "0px",
1211
+ top: "auto",
1212
+ width: "auto",
1213
+ height: `${height}px`,
1214
+ borderRadius: "16px 16px 0 0"
1215
+ });
1216
+ Object.assign(frame.style, { transform: `scale(${scale2})`, left: `${Math.max(0, (window.innerWidth - this.size.width * scale2) / 2)}px` });
1217
+ return;
1218
+ }
1219
+ const width = this.big ? Math.min(720, window.innerWidth - 48) : 340;
1220
+ const scale = width / this.size.width;
1221
+ const position = this.position ?? { right: 20, bottom: 20 };
1222
+ Object.assign(box.style, {
1223
+ width: `${width}px`,
1224
+ height: `${Math.round(this.size.height * scale) + 37}px`,
1225
+ right: `${position.right}px`,
1226
+ bottom: `${position.bottom}px`,
1227
+ left: "auto",
1228
+ top: "auto"
1229
+ });
1230
+ frame.style.transform = `scale(${scale})`;
1231
+ }
1232
+ resize(big) {
1233
+ this.big = big;
1234
+ if (this.sizeButton) {
1235
+ this.sizeButton.textContent = big ? this.words().smaller : this.words().bigger;
1236
+ }
1237
+ this.layout();
1238
+ }
1239
+ drag(head, box) {
1240
+ head.addEventListener("pointerdown", (event) => {
1241
+ if (this.device() === "phone") {
1242
+ return;
1243
+ }
1244
+ const start = { x: event.clientX, y: event.clientY, ...this.position ?? { right: 20, bottom: 20 } };
1245
+ head.setPointerCapture(event.pointerId);
1246
+ const move = (moved) => {
1247
+ const right = Math.min(window.innerWidth - 80, Math.max(0, start.right - (moved.clientX - start.x)));
1248
+ const bottom = Math.min(window.innerHeight - 40, Math.max(0, start.bottom - (moved.clientY - start.y)));
1249
+ this.position = { right, bottom };
1250
+ Object.assign(box.style, { right: `${right}px`, bottom: `${bottom}px` });
1251
+ };
1252
+ const up = () => {
1253
+ head.removeEventListener("pointermove", move);
1254
+ head.removeEventListener("pointerup", up);
1255
+ };
1256
+ head.addEventListener("pointermove", move);
1257
+ head.addEventListener("pointerup", up);
1258
+ });
1259
+ }
1260
+ away(away) {
1261
+ if (!this.box) {
1262
+ return;
1263
+ }
1264
+ if (away) {
1265
+ this.box.dataset.hidden = "";
1266
+ setTimeout(() => this.box?.hasAttribute("data-hidden") && this.box.setAttribute("data-away", ""), 240);
1267
+ } else {
1268
+ this.box.removeAttribute("data-away");
1269
+ this.layout();
1270
+ this.box.getBoundingClientRect();
1271
+ this.box.removeAttribute("data-hidden");
1272
+ }
1273
+ }
1274
+ begin(from) {
1275
+ clearTimeout(this.restTimer);
1276
+ this.busy++;
1277
+ if (from?.sessionId !== this.from?.sessionId) {
1278
+ this.awayFor = undefined;
1279
+ }
1280
+ this.from = from;
1281
+ if (!this.frame?.isConnected) {
1282
+ this.open();
1283
+ }
1284
+ this.box?.setAttribute("data-busy", "");
1285
+ this.heading();
1286
+ if (this.device() === "phone") {
1287
+ this.showPill(true);
1288
+ } else if (this.awayFor !== (from?.sessionId ?? "")) {
1289
+ this.away(false);
1290
+ }
1291
+ }
1292
+ end() {
1293
+ this.busy = Math.max(0, this.busy - 1);
1294
+ clearTimeout(this.restTimer);
1295
+ this.restTimer = setTimeout(() => {
1296
+ if (this.busy === 0) {
1297
+ this.box?.removeAttribute("data-busy");
1298
+ this.heading();
1299
+ this.showPill(false);
1300
+ }
1301
+ }, 4000);
1302
+ clearTimeout(this.idleTimer);
1303
+ this.idleTimer = setTimeout(() => this.busy === 0 && this.close(), SCREEN_IDLE_MS);
1304
+ }
1305
+ heading() {
1306
+ if (!this.title) {
1307
+ return;
1308
+ }
1309
+ const busy = this.busy > 0 || this.box?.hasAttribute("data-busy");
1310
+ this.title.textContent = busy ? this.words().operating : this.words().screen;
1311
+ if (busy && this.from?.name) {
1312
+ const small = document.createElement("small");
1313
+ small.textContent = this.from.name;
1314
+ this.title.appendChild(small);
1315
+ }
1316
+ }
1317
+ putAway() {
1318
+ this.awayFor = this.from?.sessionId ?? "";
1319
+ this.shownOnPhone = false;
1320
+ this.away(true);
1321
+ if (this.device() === "phone" && this.busy > 0) {
1322
+ this.showPill(true);
1323
+ }
1324
+ }
1325
+ showPill(show) {
1326
+ if (show && !this.pill) {
1327
+ const pill = document.createElement("div");
1328
+ pill.className = "ta-screen-pill";
1329
+ pill.dataset.hidden = "";
1330
+ const dot = document.createElement("span");
1331
+ dot.className = "ta-screen-dot";
1332
+ const words2 = document.createElement("span");
1333
+ words2.textContent = this.words().operating;
1334
+ const watch = this.button(this.words().watch, () => {
1335
+ this.shownOnPhone = true;
1336
+ this.showPill(false);
1337
+ this.away(false);
1338
+ });
1339
+ const stop = this.button(this.words().stop, () => this.stop());
1340
+ stop.classList.add("ta-screen-stop");
1341
+ pill.append(dot, words2, watch, stop);
1342
+ document.body.appendChild(pill);
1343
+ this.pill = pill;
1344
+ }
1345
+ if (!this.pill) {
1346
+ return;
1347
+ }
1348
+ if (show && !this.shownOnPhone) {
1349
+ this.pill.getBoundingClientRect();
1350
+ this.pill.removeAttribute("data-hidden");
1351
+ } else {
1352
+ this.pill.dataset.hidden = "";
1353
+ }
1354
+ }
1355
+ stop() {
1356
+ const sessionId = this.from?.sessionId;
1357
+ if (sessionId) {
1358
+ this.pi.server.abort(sessionId).catch(() => {
1359
+ return;
1360
+ });
1361
+ }
1362
+ this.busy = 0;
1363
+ this.box?.removeAttribute("data-busy");
1364
+ this.heading();
1365
+ this.putAway();
1366
+ this.showPill(false);
1367
+ }
1368
+ close() {
1369
+ clearTimeout(this.idleTimer);
1370
+ clearTimeout(this.restTimer);
1371
+ this.box?.remove();
1372
+ this.pill?.remove();
1373
+ this.box = undefined;
1374
+ this.frame = undefined;
1375
+ this.pill = undefined;
1376
+ this.busy = 0;
1377
+ this.shownOnPhone = false;
1378
+ }
1379
+ style() {
1380
+ if (!document.getElementById("ta-screen-style")) {
1381
+ const style = document.createElement("style");
1382
+ style.id = "ta-screen-style";
1383
+ style.textContent = STYLE2;
1384
+ document.head.appendChild(style);
1385
+ }
1386
+ }
1387
+ }
1388
+
1389
+ // web-src/tool-line.ts
1390
+ function text(value) {
1391
+ return typeof value === "string" ? value.trim() : "";
1392
+ }
1393
+ var AppToolLine;
1394
+ ((AppToolLine) => {
1395
+ function of(tool, args, words2, language) {
1396
+ if (tool === "app_commands") {
1397
+ return { verb: words2.commands, target: text(args.query) };
1398
+ }
1399
+ if (tool === "app_look") {
1400
+ return { verb: words2.look, target: "" };
1401
+ }
1402
+ if (tool === "app_go") {
1403
+ const to = text(args.to);
1404
+ const [kind, rest = ""] = to.split(/:(.*)/s);
1405
+ const target = kind === "settings" ? rest ? `${words2.settings} · ${rest}` : words2.settings : kind === "discover" ? words2.discover : /^(chat|page|list)$/.test(kind) ? rest.replace(/^.*\//, "") : to;
1406
+ return { verb: words2.go, target };
1407
+ }
1408
+ if (tool === "app_do") {
1409
+ const input2 = args.input && typeof args.input === "object" ? args.input : {};
1410
+ return { verb: words2.do, target: text(input2.text).slice(0, 40) };
1411
+ }
1412
+ if (tool !== "app_run") {
1413
+ return;
1414
+ }
1415
+ const command = text(args.command);
1416
+ const input = args.input && typeof args.input === "object" ? args.input : {};
1417
+ switch (command) {
1418
+ case "settings.set": {
1419
+ const changes = input.changes && typeof input.changes === "object" ? Object.keys(input.changes) : [];
1420
+ const names = changes.map((key) => {
1421
+ const spec = TA_WEB_SETTINGS.find((one) => one.key === key);
1422
+ return spec ? TaLanguageUtil.pick(language, spec.title) : key;
1423
+ });
1424
+ return { verb: words2["settings.set"], target: names.join(TaLanguageUtil.cjk(language) ? "、" : ", ") };
1425
+ }
1426
+ case "chats.pin":
1427
+ return { verb: input.pinned === false ? words2.unpin : words2["chats.pin"], target: "" };
1428
+ case "extensions.set":
1429
+ return { verb: input.enabled === false ? words2.off : input.enabled === true ? words2.on : words2["extensions.set"], target: text(input.name) };
1430
+ case "asks.list":
1431
+ case "asks.answer":
1432
+ return { verb: words2[command], target: "" };
1433
+ case "settings.get":
1434
+ case "chats.list":
1435
+ case "chats.stop":
1436
+ case "extensions.list":
1437
+ return { verb: words2[command], target: text(input.query) };
1438
+ default:
1439
+ return { verb: words2.run, target: command };
1440
+ }
1441
+ }
1442
+ AppToolLine.of = of;
1443
+ })(AppToolLine ||= {});
1444
+
1445
+ // web-src/index.ts
1446
+ function activate(pi) {
1447
+ let since = Number.POSITIVE_INFINITY;
1448
+ let stopped = false;
1449
+ const words2 = () => AppUseWords.of(pi.ui.language);
1450
+ pi.registerToolRenderer?.((name, next) => {
1451
+ if (!TA_APP_TOOLS.includes(name)) {
1452
+ return next();
1453
+ }
1454
+ return { renderCall: (args) => AppToolLine.of(name, args, words2(), pi.ui.language) ?? { verb: name, target: "" } };
1455
+ });
1456
+ if (pi.ui.screen?.agent) {
1457
+ const frame = window;
1458
+ const driver = new ScreenDriver(window, {
1459
+ screen: pi.ui.screen,
1460
+ watched: () => frame.taScreenWatched?.() ?? false,
1461
+ device: () => window.innerWidth < 640 ? "phone" : "computer"
1462
+ });
1463
+ frame.taScreen = driver;
1464
+ return () => {
1465
+ if (frame.taScreen === driver) {
1466
+ frame.taScreen = undefined;
1467
+ }
1468
+ driver.dispose();
1469
+ };
1470
+ }
1471
+ const screens = new ScreenWindow(pi, words2);
1472
+ const stopAnswering = pi.ui.answer?.("screen", (payload) => screens.run(payload));
1473
+ const show = (entry) => {
1474
+ const undo = entry.undo ? {
1475
+ label: words2().undo,
1476
+ run: () => {
1477
+ pi.callHost("undo", entry.id).then(() => entry.command.startsWith("extensions.") ? pi.reloadExtensions() : undefined).catch((error) => pi.ui.notify(error instanceof Error ? error.message : String(error), "error"));
1478
+ }
1479
+ } : undefined;
1480
+ pi.ui.notify(entry.notice, "info", {
1481
+ key: `ta-app-use:${entry.id}`,
1482
+ ta: true,
1483
+ ...entry.changes ? { changes: entry.changes } : {},
1484
+ ...undo ? { action: undo } : {}
1485
+ });
1486
+ };
1487
+ const read = async (tell) => {
1488
+ const done = AppUseUtil.entries(await pi.storage.get(DONE_KEY).catch(() => {
1489
+ return;
1490
+ }));
1491
+ const latest = done.reduce((most, entry) => Math.max(most, entry.at), 0);
1492
+ if (tell && !stopped) {
1493
+ const fresh = AppUseUtil.fresh(done, since);
1494
+ for (const entry of fresh) {
1495
+ show(entry);
1496
+ }
1497
+ if (fresh.some((entry) => entry.command.startsWith("extensions."))) {
1498
+ pi.reloadExtensions().catch(() => {
1499
+ return;
1500
+ });
1501
+ }
1502
+ }
1503
+ since = Math.max(Number.isFinite(since) ? since : 0, latest);
1504
+ };
1505
+ const first = read(false);
1506
+ const off = pi.storage.onChange((keys) => {
1507
+ if (keys.includes(DONE_KEY)) {
1508
+ first.then(() => read(true));
1509
+ }
1510
+ });
1511
+ return () => {
1512
+ stopped = true;
1513
+ off();
1514
+ stopAnswering?.();
1515
+ screens.dispose();
1516
+ };
1517
+ }
1518
+ export {
1519
+ activate as default
1520
+ };