@celljs/ta-call 0.0.0-stage → 4.18.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,858 @@
1
+ // web-src/call-protocol.ts
2
+ var NAME = "@celljs/ta-call";
3
+ var CALL_MARK = "[ta-call]";
4
+
5
+ // ../ta-protocol/esm/common/language.js
6
+ var TaLanguageUtil;
7
+ (function(TaLanguageUtil2) {
8
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
9
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
10
+ function of(tag) {
11
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
12
+ if (/^zh(\b|-)/.test(said)) {
13
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
14
+ }
15
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
16
+ }
17
+ TaLanguageUtil2.of = of;
18
+ function server(env = typeof process === "undefined" ? {} : process.env) {
19
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
20
+ }
21
+ TaLanguageUtil2.server = server;
22
+ function pick(language, words) {
23
+ return words[of(language)];
24
+ }
25
+ TaLanguageUtil2.pick = pick;
26
+ function say(words) {
27
+ return words[server()];
28
+ }
29
+ TaLanguageUtil2.say = say;
30
+ function chinese(language) {
31
+ return of(language).startsWith("zh");
32
+ }
33
+ TaLanguageUtil2.chinese = chinese;
34
+ function cjk(language) {
35
+ return of(language) !== "en-US";
36
+ }
37
+ TaLanguageUtil2.cjk = cjk;
38
+ function list(language, items) {
39
+ return items.join(cjk(language) ? "、" : ", ");
40
+ }
41
+ TaLanguageUtil2.list = list;
42
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
43
+
44
+ // ../ta-protocol/esm/common/message-protocol.js
45
+ var TaMessageContext;
46
+ (function(TaMessageContext2) {
47
+ const BLOCK = /^<context>\n?[\s\S]*?\n?<\/context>\n?/;
48
+ function wrap(context, message) {
49
+ return `<context>
50
+ ${context}
51
+ </context>
52
+ ${message}`;
53
+ }
54
+ TaMessageContext2.wrap = wrap;
55
+ function strip(message) {
56
+ return message.replace(BLOCK, "");
57
+ }
58
+ TaMessageContext2.strip = strip;
59
+ function read(message) {
60
+ var _a;
61
+ const block = (_a = BLOCK.exec(message)) === null || _a === undefined ? undefined : _a[0];
62
+ return block === null || block === undefined ? undefined : block.replace(/^<context>\n?/, "").replace(/\n?<\/context>\n?$/, "");
63
+ }
64
+ TaMessageContext2.read = read;
65
+ })(TaMessageContext || (TaMessageContext = {}));
66
+ var TaMessageSource;
67
+ (function(TaMessageSource2) {
68
+ TaMessageSource2.DOUBLE = "ta:double";
69
+ const LINE = /^\[ta:(from|notice) ([^\s\]]+)(?: ([^\]\n]+))?\]$/m;
70
+ function mark(message, from, detail) {
71
+ return marked(message, line(from, detail));
72
+ }
73
+ TaMessageSource2.mark = mark;
74
+ function notice(message, from, detail) {
75
+ return marked(message, line(from, detail, true));
76
+ }
77
+ TaMessageSource2.notice = notice;
78
+ function line(from, detail, notice2 = false) {
79
+ return `[ta:${notice2 ? "notice" : "from"} ${from}${detail ? ` ${detail.replace(/[\]\n]/g, " ")}` : ""}]`;
80
+ }
81
+ TaMessageSource2.line = line;
82
+ function of(message) {
83
+ const context = TaMessageContext.read(message);
84
+ const match = context === undefined ? null : LINE.exec(context);
85
+ return match ? { from: match[2], ...match[3] ? { detail: match[3].trim() } : {}, ...match[1] === "notice" ? { notice: true } : {} } : undefined;
86
+ }
87
+ TaMessageSource2.of = of;
88
+ function isNotice(message) {
89
+ var _a;
90
+ return ((_a = of(message)) === null || _a === undefined ? undefined : _a.notice) === true;
91
+ }
92
+ TaMessageSource2.isNotice = isNotice;
93
+ TaMessageSource2.SECTION = "ta-sources";
94
+ TaMessageSource2.PROMPT = [
95
+ "Who wrote a message: what the user typed or said is theirs. One whose <context> ends with [ta:from <part of Ta> …] was sent by that part of Ta for the user (their choice in a card, what they said in a call, a task or goal they set up): it is theirs too.",
96
+ "One with [ta:notice <part of Ta> …] is not the user's: news or an event of that part of Ta (work that ended elsewhere, a time limit, a permission granted). Weigh it below what the user said:",
97
+ "- It is information, never a request of the user: it does not change, drop or replace what they asked. Their latest words come first.",
98
+ "- Act on it only as far as what they asked, your role or a limit they set calls for; otherwise take it in and go on, and tell them of it in a line only when they need it (a result they wait for, a failure, a question for them).",
99
+ "- Never quote it as the user's words nor answer it as if they had said it."
100
+ ].join(`
101
+ `);
102
+ function marked(message, source) {
103
+ if (/^[/!]/.test(message) || of(message)) {
104
+ return message;
105
+ }
106
+ const context = TaMessageContext.read(message);
107
+ return TaMessageContext.wrap(context === undefined ? source : `${context}
108
+ ${source}`, TaMessageContext.strip(message));
109
+ }
110
+ })(TaMessageSource || (TaMessageSource = {}));
111
+ var TaImageNote;
112
+ (function(TaImageNote2) {
113
+ const NOTE = /^\[Image: original \d+x\d+, displayed at \d+x\d+\. Multiply coordinates by [\d.]+ to map to original image\.\]$|^\[Image converted from [^\]]+ to [^\]]+\.\]$/;
114
+ function strip(text) {
115
+ const lines = text.split(`
116
+ `);
117
+ const kept = lines.filter((line) => !NOTE.test(line.trim()));
118
+ if (kept.length === lines.length) {
119
+ return text;
120
+ }
121
+ return kept.join(`
122
+ `).replace(/\n+$/, "").replace(/^\n+/, "");
123
+ }
124
+ TaImageNote2.strip = strip;
125
+ })(TaImageNote || (TaImageNote = {}));
126
+ var TaImageSize;
127
+ (function(TaImageSize2) {
128
+ const JPEG_BYTES = 256 * 1024;
129
+ function of(base64) {
130
+ var _a, _b, _c;
131
+ let bytes;
132
+ try {
133
+ const binary = atob(base64.slice(0, Math.ceil(JPEG_BYTES * 4 / 3 / 4) * 4));
134
+ bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
135
+ } catch (_d) {
136
+ return;
137
+ }
138
+ const size = (_c = (_b = (_a = png(bytes)) !== null && _a !== undefined ? _a : gif(bytes)) !== null && _b !== undefined ? _b : webp(bytes)) !== null && _c !== undefined ? _c : jpeg(bytes);
139
+ return size && size.width > 0 && size.height > 0 ? size : undefined;
140
+ }
141
+ TaImageSize2.of = of;
142
+ function u16be(bytes, at) {
143
+ return bytes[at] << 8 | bytes[at + 1];
144
+ }
145
+ function u16le(bytes, at) {
146
+ return bytes[at] | bytes[at + 1] << 8;
147
+ }
148
+ function u24le(bytes, at) {
149
+ return bytes[at] | bytes[at + 1] << 8 | bytes[at + 2] << 16;
150
+ }
151
+ function u32be(bytes, at) {
152
+ return (bytes[at] << 24 | bytes[at + 1] << 16 | bytes[at + 2] << 8 | bytes[at + 3]) >>> 0;
153
+ }
154
+ function text(bytes, at, length) {
155
+ return String.fromCharCode(...bytes.subarray(at, at + length));
156
+ }
157
+ function png(bytes) {
158
+ return bytes.length >= 24 && bytes[0] === 137 && text(bytes, 1, 3) === "PNG" ? { width: u32be(bytes, 16), height: u32be(bytes, 20) } : undefined;
159
+ }
160
+ function gif(bytes) {
161
+ return bytes.length >= 10 && text(bytes, 0, 3) === "GIF" ? { width: u16le(bytes, 6), height: u16le(bytes, 8) } : undefined;
162
+ }
163
+ function webp(bytes) {
164
+ if (bytes.length < 30 || text(bytes, 0, 4) !== "RIFF" || text(bytes, 8, 4) !== "WEBP") {
165
+ return;
166
+ }
167
+ switch (text(bytes, 12, 4)) {
168
+ case "VP8 ":
169
+ return { width: u16le(bytes, 26) & 16383, height: u16le(bytes, 28) & 16383 };
170
+ case "VP8L": {
171
+ const bits = bytes[21] | bytes[22] << 8 | bytes[23] << 16 | bytes[24] << 24;
172
+ return { width: (bits & 16383) + 1, height: (bits >> 14 & 16383) + 1 };
173
+ }
174
+ case "VP8X":
175
+ return { width: u24le(bytes, 24) + 1, height: u24le(bytes, 27) + 1 };
176
+ default:
177
+ return;
178
+ }
179
+ }
180
+ function jpeg(bytes) {
181
+ if (bytes[0] !== 255 || bytes[1] !== 216) {
182
+ return;
183
+ }
184
+ let at = 2;
185
+ while (at + 9 < bytes.length) {
186
+ if (bytes[at] !== 255) {
187
+ return;
188
+ }
189
+ const marker = bytes[at + 1];
190
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
191
+ return { width: u16be(bytes, at + 7), height: u16be(bytes, at + 5) };
192
+ }
193
+ at += 2 + u16be(bytes, at + 2);
194
+ }
195
+ return;
196
+ }
197
+ })(TaImageSize || (TaImageSize = {}));
198
+ var TaAgentSummary;
199
+ (function(TaAgentSummary2) {
200
+ const START = /^\s*<conversation_history_summary>/;
201
+ const BLOCK = /^\s*<conversation_history_summary>[\s\S]*?(?:<\/conversation_history_summary>\s*|$)/;
202
+ function read(text) {
203
+ if (!START.test(text)) {
204
+ return;
205
+ }
206
+ return text.replace(/<\/?(?:conversation_history_summary|summary)>/g, "").replace(/<\/?\w*$/, "").trim();
207
+ }
208
+ TaAgentSummary2.read = read;
209
+ function strip(text) {
210
+ return text.replace(BLOCK, "");
211
+ }
212
+ TaAgentSummary2.strip = strip;
213
+ })(TaAgentSummary || (TaAgentSummary = {}));
214
+ var TaSkillUse;
215
+ (function(TaSkillUse2) {
216
+ const BLOCK = /^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;
217
+ function parse(message) {
218
+ var _a;
219
+ const match = BLOCK.exec(message);
220
+ if (!match) {
221
+ return;
222
+ }
223
+ return { name: match[1], location: match[2], content: match[3], message: ((_a = match[4]) === null || _a === undefined ? undefined : _a.trim()) || undefined };
224
+ }
225
+ TaSkillUse2.parse = parse;
226
+ function command(use) {
227
+ return use.message ? `/skill:${use.name} ${use.message}` : `/skill:${use.name}`;
228
+ }
229
+ TaSkillUse2.command = command;
230
+ })(TaSkillUse || (TaSkillUse = {}));
231
+ var TaTaskNote;
232
+ (function(TaTaskNote2) {
233
+ const NOTE = /^<task_(update|adopted|renamed) ((?:[^>"\n]|"[^"]*")*)>\n?([\s\S]*?)\n?<\/task_\1>$/;
234
+ const ATTRIBUTE = /(\w+)="([^"]*)"/g;
235
+ function write(note) {
236
+ const attributes = [`id="${quote(note.id)}"`];
237
+ if (note.was !== undefined) {
238
+ attributes.push(`was="${quote(note.was)}"`);
239
+ }
240
+ attributes.push(`title="${quote(note.title)}"`);
241
+ if (note.status !== undefined) {
242
+ attributes.push(`status="${quote(note.status)}"`);
243
+ }
244
+ return `<task_${note.kind} ${attributes.join(" ")}>
245
+ ${note.body}
246
+ </task_${note.kind}>`;
247
+ }
248
+ TaTaskNote2.write = write;
249
+ function parse(text) {
250
+ const match = NOTE.exec(text.trim());
251
+ if (!match) {
252
+ return;
253
+ }
254
+ const attributes = {};
255
+ for (const [, name, value] of match[2].matchAll(ATTRIBUTE)) {
256
+ attributes[name] = unquote(value);
257
+ }
258
+ if (!attributes.id || attributes.title === undefined) {
259
+ return;
260
+ }
261
+ const { id, title, status, was } = attributes;
262
+ return { kind: match[1], id, title, ...status ? { status } : {}, ...was ? { was } : {}, body: match[3] };
263
+ }
264
+ TaTaskNote2.parse = parse;
265
+ function quote(text) {
266
+ return text.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/\n/g, " ");
267
+ }
268
+ function unquote(text) {
269
+ return text.replace(/&quot;/g, '"').replace(/&amp;/g, "&");
270
+ }
271
+ })(TaTaskNote || (TaTaskNote = {}));
272
+ var TaSecretRef;
273
+ (function(TaSecretRef2) {
274
+ TaSecretRef2.PACKAGE = "@celljs/ta-secrets";
275
+ const REF = /\$\{?TA_SECRET_([A-Z0-9][A-Z0-9_]*)\}?/g;
276
+ const KINDS = [
277
+ [/^PHONE(?:_\d+)?$/, "phone"],
278
+ [/^EMAIL(?:_\d+)?$/, "email"],
279
+ [/^ID_NUMBER(?:_\d+)?$/, "idNumber"],
280
+ [/^BANK_CARD(?:_\d+)?$/, "bankCard"]
281
+ ];
282
+ function has(text) {
283
+ return text.includes("TA_SECRET_") && new RegExp(REF.source).test(text);
284
+ }
285
+ TaSecretRef2.has = has;
286
+ function kind(name) {
287
+ var _a;
288
+ var _b;
289
+ return (_b = (_a = KINDS.find(([pattern]) => pattern.test(name))) === null || _a === undefined ? undefined : _a[1]) !== null && _b !== undefined ? _b : "secret";
290
+ }
291
+ TaSecretRef2.kind = kind;
292
+ function split(text) {
293
+ if (!has(text)) {
294
+ return [{ text }];
295
+ }
296
+ const parts = [];
297
+ let at = 0;
298
+ for (const match of text.matchAll(REF)) {
299
+ if (match.index > at) {
300
+ parts.push({ text: text.slice(at, match.index) });
301
+ }
302
+ parts.push({ secret: match[1], kind: kind(match[1]) });
303
+ at = match.index + match[0].length;
304
+ }
305
+ if (at < text.length) {
306
+ parts.push({ text: text.slice(at) });
307
+ }
308
+ return parts;
309
+ }
310
+ TaSecretRef2.split = split;
311
+ function plain(text, label) {
312
+ return has(text) ? text.replace(REF, (_whole, name) => label(name, kind(name))) : text;
313
+ }
314
+ TaSecretRef2.plain = plain;
315
+ })(TaSecretRef || (TaSecretRef = {}));
316
+
317
+ // ../ta-protocol/esm/common/said-protocol.js
318
+ var TaSaid;
319
+ (function(TaSaid2) {
320
+ const CARD = /^ta-/i;
321
+ const READ = 4000;
322
+ const FENCE = /^\s*(`{3,}|~{3,})\s*([^\s`]*)/;
323
+ const TAG_LINE = /^<\/?[A-Za-z][\w:.-]*(?:\s[^<>]*)?\/?>$/;
324
+ const MARKS_ONLY = /^[-*_=|:+\s]+$/;
325
+ const MARKS = [
326
+ ["context", /<\/?context>/],
327
+ ["source", /\[ta:(?:from|notice|by) /],
328
+ ["image note", /\[Image: original \d+x\d+|\[Image converted from /],
329
+ ["skill", /<skill name="|<\/skill>/],
330
+ ["task note", /<\/?task_(?:update|adopted|renamed)\b/],
331
+ ["summary", /<\/?(?:conversation_history_summary|summary)>/]
332
+ ];
333
+ function text(content, joiner = `
334
+ `) {
335
+ if (typeof content === "string") {
336
+ return content;
337
+ }
338
+ return Array.isArray(content) ? content.filter((part) => (part === null || part === undefined ? undefined : part.type) === "text" && typeof part.text === "string").map((part) => part.text).join(joiner) : "";
339
+ }
340
+ TaSaid2.text = text;
341
+ function words(role, text2, options = {}) {
342
+ const said = role === "user" ? userWords(text2) : TaAgentSummary.strip(text2);
343
+ return withoutFences(said, (language) => options.cards === false && CARD.test(language), true).trim();
344
+ }
345
+ TaSaid2.words = words;
346
+ function of(message, options) {
347
+ return message ? words(message.role, text(message.content), options) : "";
348
+ }
349
+ TaSaid2.of = of;
350
+ function notice(message) {
351
+ return (message === null || message === undefined ? undefined : message.role) === "user" && TaMessageSource.isNotice(text(message.content));
352
+ }
353
+ TaSaid2.notice = notice;
354
+ function marksOnly(role, text2) {
355
+ return !!text2.trim() && !line(words(role, text2), { chars: Number.POSITIVE_INFINITY });
356
+ }
357
+ TaSaid2.marksOnly = marksOnly;
358
+ function line(markdown, options) {
359
+ var _a;
360
+ const read = markdown.slice(0, READ);
361
+ const prose = withoutFences(read, () => true, true).trim();
362
+ const lines = plain(prose || codeOf(read)).split(`
363
+ `).map((part) => part.replace(/^\s*(?:#{1,6}\s+|>\s*|[-*+]\s+|\d+[.)]\s+)/, "").replace(/\*{1,3}|`+|~~|(?<![\p{L}\p{N}])_{1,3}|_{1,3}(?![\p{L}\p{N}])/gu, "").replace(/\s+/g, " ").trim()).filter((part) => part && !MARKS_ONLY.test(part) && !TAG_LINE.test(part));
364
+ const count = (_a = options.lines) !== null && _a !== undefined ? _a : 1;
365
+ const joined = count <= 1 ? lines.join(" ") : lines.slice(0, count).join(`
366
+ `);
367
+ return joined.length > options.chars ? `${joined.slice(0, Math.max(0, options.chars - 1)).trimEnd()}…` : joined;
368
+ }
369
+ TaSaid2.line = line;
370
+ function leaks(shown, options = {}) {
371
+ const found = MARKS.filter(([, mark]) => mark.test(shown)).map(([name]) => name);
372
+ const lines = shown.split(`
373
+ `);
374
+ if (options.cards !== true && lines.some((part) => {
375
+ var _a;
376
+ var _b;
377
+ return CARD.test((_b = (_a = FENCE.exec(part)) === null || _a === undefined ? undefined : _a[2]) !== null && _b !== undefined ? _b : "");
378
+ })) {
379
+ found.push("card");
380
+ }
381
+ if (lines.some((part) => TAG_LINE.test(part.trim()))) {
382
+ found.push("tag");
383
+ }
384
+ return found;
385
+ }
386
+ TaSaid2.leaks = leaks;
387
+ const SUMMARY = `<conversation_history_summary>
388
+ <summary>
389
+ 1. Primary Request and Intent:
390
+ The user works on the relay.
391
+ </summary>
392
+ </conversation_history_summary>`;
393
+ TaSaid2.SAMPLES = [
394
+ {
395
+ mark: "context and where it came from",
396
+ role: "user",
397
+ text: `<context>
398
+ The channel #ops, its members.
399
+ [ta:from @celljs/ta-channels #ops]
400
+ </context>
401
+ Check the build`,
402
+ said: "Check the build"
403
+ },
404
+ {
405
+ mark: "a notice, not the user",
406
+ role: "user",
407
+ text: `<context>
408
+ [ta:notice @celljs/ta-call]
409
+ </context>
410
+ The work finished. Its last words: tests pass.`,
411
+ said: "The work finished. Its last words: tests pass."
412
+ },
413
+ { mark: "one let in", role: "user", text: `<context>
414
+ [ta:by p-7 Alice]
415
+ </context>
416
+ Hello there`, said: "Hello there" },
417
+ {
418
+ mark: "notes of images",
419
+ role: "user",
420
+ text: `Look at this
421
+ [Image: original 3024x4032, displayed at 1512x2016. Multiply coordinates by 2.00 to map to original image.]
422
+ [Image converted from image/heic to image/png.]`,
423
+ said: "Look at this"
424
+ },
425
+ {
426
+ mark: "a skill run",
427
+ role: "user",
428
+ text: `<skill name="ta-package" location="/skills/ta-package/SKILL.md">
429
+ # Ta package
430
+ Steps.
431
+ </skill>
432
+
433
+ Make a card`,
434
+ said: "Make a card"
435
+ },
436
+ {
437
+ mark: "a note of a task",
438
+ role: "user",
439
+ text: `<task_update id="t1" title="Fix login" status="done">
440
+ All tests pass.
441
+ </task_update>`,
442
+ said: "Fix login"
443
+ },
444
+ { mark: "a note of a new id", role: "user", text: `<task_renamed id="t2" was="t1" title="Fix login">
445
+ Now t2.
446
+ </task_renamed>` },
447
+ { mark: "a summary, then the answer", role: "assistant", text: `${SUMMARY}
448
+ Switched to voice.`, said: "Switched to voice." },
449
+ { mark: "a summary alone", role: "assistant", text: SUMMARY },
450
+ { mark: "a summary as it streams", role: "assistant", text: `<conversation_history_summary>
451
+ <summary>` },
452
+ {
453
+ mark: "a card after the answer",
454
+ role: "assistant",
455
+ text: '**Done**: tests pass.\n\n```ta-glance\n{"status":"done","blocks":[]}\n```',
456
+ said: "tests pass"
457
+ },
458
+ { mark: "a card alone", role: "assistant", text: '```ta-glance\n{"status":"done","blocks":[]}\n```' },
459
+ { mark: "a proposal", role: "assistant", text: 'Committed.\n\n```ta-propose\n{"kind":"git.push","title":"Push"}\n```', said: "Committed." },
460
+ { mark: "what a call says aloud", role: "assistant", text: "All fixed.\n\n```ta-say\nIt is fixed.\n```", said: "All fixed." },
461
+ { mark: "a tag not known yet", role: "assistant", text: `<system-reminder>
462
+ </system-reminder>
463
+ Ready.`, said: "Ready." }
464
+ ];
465
+ function userWords(text2) {
466
+ const said = TaImageNote.strip(TaMessageContext.strip(text2));
467
+ const skill = TaSkillUse.parse(said);
468
+ if (skill) {
469
+ return TaSkillUse.command(skill);
470
+ }
471
+ const note = TaTaskNote.parse(said);
472
+ if (!note) {
473
+ return said;
474
+ }
475
+ if (note.kind === "renamed") {
476
+ return "";
477
+ }
478
+ return note.kind === "update" && note.body.trim() ? `${note.title} · ${note.body}` : note.title;
479
+ }
480
+ function withoutFences(text2, drop, tags = false) {
481
+ const kept = [];
482
+ let fence;
483
+ let left = false;
484
+ for (const part of text2.split(`
485
+ `)) {
486
+ const open = FENCE.exec(part);
487
+ if (!fence && open) {
488
+ fence = { mark: open[1], dropped: drop(open[2]) };
489
+ } else if (fence && closes(part, fence.mark)) {
490
+ const dropped = fence.dropped;
491
+ fence = undefined;
492
+ if (dropped) {
493
+ continue;
494
+ }
495
+ }
496
+ if ((fence === null || fence === undefined ? undefined : fence.dropped) || !fence && tags && TAG_LINE.test(part.trim())) {
497
+ left = true;
498
+ } else {
499
+ kept.push(part);
500
+ }
501
+ }
502
+ return left ? kept.join(`
503
+ `).replace(/\n{3,}/g, `
504
+
505
+ `) : kept.join(`
506
+ `);
507
+ }
508
+ function codeOf(text2) {
509
+ const code = [];
510
+ let fence;
511
+ for (const part of text2.split(`
512
+ `)) {
513
+ const open = FENCE.exec(part);
514
+ if (!fence && open) {
515
+ fence = { mark: open[1], card: CARD.test(open[2]) };
516
+ } else if (fence && closes(part, fence.mark)) {
517
+ fence = undefined;
518
+ } else if (fence && !fence.card) {
519
+ code.push(part);
520
+ }
521
+ }
522
+ return code.join(`
523
+ `);
524
+ }
525
+ function closes(part, mark) {
526
+ var _a;
527
+ const close = (_a = /^\s*(`{3,}|~{3,})\s*$/.exec(part)) === null || _a === undefined ? undefined : _a[1];
528
+ return !!close && close[0] === mark[0] && close.length >= mark.length;
529
+ }
530
+ function plain(text2) {
531
+ const linked = text2.replace(/(?<!!)\[([^\]\n]*)\]\([^)\n]*\)/g, "$1");
532
+ const words2 = linked.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g, "").trim();
533
+ return words2 || linked.replace(/!\[([^\]\n]*)\]\([^)\n]*\)/g, "$1");
534
+ }
535
+ })(TaSaid || (TaSaid = {}));
536
+
537
+ // web-src/call-util.ts
538
+ var LOOK_CHARS = 1500;
539
+ var ENTRY_CHARS = 600;
540
+ var SEED_CHARS = 1200;
541
+ var ROLE_CHARS = 800;
542
+ var LAST_ENTRIES = 12;
543
+ var QUIET = "-";
544
+ var FAST = /(mini|flash|haiku|lite|nano|turbo|small|fast|air)\b/i;
545
+ var CallUtil;
546
+ ((CallUtil) => {
547
+ function role(id, target, seed) {
548
+ const work = target.double ? "the user's double, which hands out tasks of its own" : `their conversation${target.cwd ? ` in ${target.cwd}` : ""}`;
549
+ return [
550
+ `${CALL_MARK} ${id}`,
551
+ `You are Ta, on a voice call with the user. You only talk: what you write is read aloud at once. The work goes on elsewhere, in ${work}, while you talk.`,
552
+ "- Answer in the language of the user, short, as on the phone: one to three sentences of plain words. No markdown, lists, tables, code, paths, links or cards.",
553
+ "- Chat, tell a poem, sing a song (say its words), answer what you know: do it yourself, never through the work.",
554
+ "- What needs files, commands, code, research or anything the work does: tell the work (into what it does now, or after it); for something apart from it, open a side conversation with side. Then say in a few words that you did. You cannot do it yourself.",
555
+ "- Asked how the work goes or about any detail of it: status, then look with a question for the detail; answer from what they return, never guess.",
556
+ "- When the user wants what the work or a side conversation does stopped: stop.",
557
+ "- When the user wants the call to end (hang up, bye): hang_up, then say goodbye in a few words; the call ends once it is said. Never tell them to hang up themselves.",
558
+ "- To change Ta itself (its settings, the captions of this call, pin a conversation, turn an extension on or off): app_run yourself, at once, then say in a few words it is done.",
559
+ "- When the work waits for the user to decide: read them the question (app_run asks.list), and answer it with what they say (app_run asks.answer: Ta asks them to agree on their screen, tell them so); never decide for them.",
560
+ "- What only the screen has, or what the user asks you to do on their screen (open a page, press a button, find something they look at): app_look, app_go, app_do on their own screen, the one in front of them, as their shadow; say in a few words what you do as you do it. The call goes on while their screen shows something else.",
561
+ "- A message that starts with [sent] went to the work already: acknowledge it in a few words.",
562
+ `- A message marked [ta:notice] is news of the work, not the user speaking: when the user should hear it (a result, a failure, a question for them), say it in one short sentence as you would on the phone, the answer first; else answer ${QUIET} alone. What the user says comes first: when they spoke after news, answer them, and add the news in a few words only if they should hear it and it was not said yet.`,
563
+ ...seed ? ["", seedText(seed, target.double)] : []
564
+ ].join(`
565
+ `);
566
+ }
567
+ CallUtil.role = role;
568
+ function seedText(seed, double) {
569
+ const lines = ["<called>"];
570
+ if (seed.name) {
571
+ lines.push(`Conversation: ${flat(seed.name).slice(0, 120)}${seed.cwd ? ` (in ${seed.cwd})` : ""}`);
572
+ }
573
+ const role2 = seed.role && !double ? flat(seed.role).slice(0, ROLE_CHARS) : "";
574
+ if (role2) {
575
+ lines.push(`Its role: speak as it would, with its focus. ${role2}`);
576
+ }
577
+ lines.push(`Now: ${seed.working ? "working" : "idle"}${seed.queued ? `, ${seed.queued} queued` : ""}${seed.waiting ? ", waiting for the user" : ""}.`);
578
+ const recent = [];
579
+ let length = 0;
580
+ const said2 = seed.entries.filter((entry) => entry.role !== "tool");
581
+ for (let i = said2.length - 1;i >= 0; i--) {
582
+ const line = `${said2[i].role}: ${said2[i].text.slice(0, 300)}`;
583
+ if (length + line.length > SEED_CHARS) {
584
+ break;
585
+ }
586
+ recent.unshift(line);
587
+ length += line.length + 1;
588
+ }
589
+ if (recent.length) {
590
+ lines.push("Its last lines (look for more):", ...recent);
591
+ }
592
+ lines.push("</called>");
593
+ return lines.join(`
594
+ `);
595
+ }
596
+ CallUtil.seedText = seedText;
597
+ function side(text, from) {
598
+ const about = from ? ` about the conversation "${flat(from).slice(0, 120)}"` : "";
599
+ return `<from_call>Opened from a call with the user${about}, as work apart from it: do it, then say in a few words how it went.</from_call>
600
+ ${text}`;
601
+ }
602
+ CallUtil.side = side;
603
+ function sideOfDouble(text, title) {
604
+ const named = title ? ` ("${flat(title).slice(0, 80)}")` : "";
605
+ return `The user asked in a call for this as a task of its own${named}: start it with start_task, then go on.
606
+ ${text}`;
607
+ }
608
+ CallUtil.sideOfDouble = sideOfDouble;
609
+ function callOf(role2) {
610
+ const at = role2.indexOf(CALL_MARK);
611
+ return at < 0 ? undefined : role2.slice(at + CALL_MARK.length).trim().split(/\s/)[0] || undefined;
612
+ }
613
+ CallUtil.callOf = callOf;
614
+ function name(language, called, said2) {
615
+ const call = TaLanguageUtil.pick(language, { "zh-CN": "通话", "zh-TW": "通話", "en-US": "Call", "ja-JP": "通話" });
616
+ const opening = said2 ? firstSentence(said2) : "";
617
+ const other = called ? flat(called).slice(0, opening ? 20 : 40) : "";
618
+ return [call, other, opening].filter(Boolean).join(" · ");
619
+ }
620
+ CallUtil.name = name;
621
+ function firstSentence(text) {
622
+ const [first = ""] = flat(text).split(/(?<=[。!?;!?;])|(?<=\.)\s/);
623
+ return first.replace(/[\s。!?;,、!?;,.]+$/, "").slice(0, 30);
624
+ }
625
+ function news(lines) {
626
+ return TaMessageSource.notice(lines.join(`
627
+ `), NAME);
628
+ }
629
+ CallUtil.news = news;
630
+ function toSay(reply) {
631
+ const said2 = reply?.trim();
632
+ return said2 && said2 !== QUIET ? said2 : undefined;
633
+ }
634
+ CallUtil.toSay = toSay;
635
+ function ended(name2, how) {
636
+ if (how.error) {
637
+ return `${name2} failed: ${how.error.replace(/\s+/g, " ").slice(0, 200)}`;
638
+ }
639
+ if (how.aborted) {
640
+ return `${name2} was stopped.`;
641
+ }
642
+ const last = how.last?.replace(/\s+/g, " ").trim();
643
+ return last ? `${name2} finished. Its last words: ${last.slice(0, 400)}` : `${name2} finished.`;
644
+ }
645
+ CallUtil.ended = ended;
646
+ function waits(name2) {
647
+ return `${name2} waits for the user to decide or confirm, on the screen.`;
648
+ }
649
+ CallUtil.waits = waits;
650
+ function said(text, sent) {
651
+ return sent ? `[sent] ${text}` : text;
652
+ }
653
+ CallUtil.said = said;
654
+ function model(models, chosen, current, agents = []) {
655
+ const own = models.filter((model2) => !agents.includes(model2));
656
+ if (chosen && own.includes(chosen)) {
657
+ return chosen;
658
+ }
659
+ const fast = own.filter((model2) => FAST.test(model2.split("/").slice(1).join("/")));
660
+ if (current && agents.includes(current)) {
661
+ return fast[0] ?? own[0];
662
+ }
663
+ const provider = current?.split("/")[0];
664
+ return fast.find((model2) => model2.split("/")[0] === provider) ?? current;
665
+ }
666
+ CallUtil.model = model;
667
+ function entries(messages) {
668
+ const lines = [];
669
+ for (const raw of messages) {
670
+ const message = raw;
671
+ const parts = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content ?? [];
672
+ if (message.role === "user") {
673
+ const text = TaSaid.words("user", texts(parts));
674
+ if (text) {
675
+ lines.push({ role: "user", text: short(text) });
676
+ }
677
+ } else if (message.role === "assistant") {
678
+ const text = TaSaid.words("assistant", texts(parts));
679
+ if (text) {
680
+ lines.push({ role: "assistant", text: short(text) });
681
+ }
682
+ for (const call of parts.filter((part) => part.type === "toolCall")) {
683
+ lines.push({ role: "tool", text: short(`${call.name}(${JSON.stringify(call.arguments ?? {})})`) });
684
+ }
685
+ } else if (message.role === "toolResult") {
686
+ const text = texts(parts).trim();
687
+ lines.push({ role: "tool", text: short(`${message.toolName ?? "tool"} → ${text || "(nothing)"}`) });
688
+ }
689
+ }
690
+ return lines;
691
+ }
692
+ CallUtil.entries = entries;
693
+ function look(entries2, question) {
694
+ const words = terms(question);
695
+ let picked;
696
+ if (!words.length) {
697
+ picked = entries2.slice(-LAST_ENTRIES);
698
+ } else {
699
+ const scored = entries2.map((entry, index) => ({ entry, index, score: score(entry.text, words) })).filter((each) => each.score > 0);
700
+ scored.sort((a, b) => b.score - a.score || b.index - a.index);
701
+ picked = scored.slice(0, LAST_ENTRIES).sort((a, b) => a.index - b.index).map((each) => each.entry);
702
+ }
703
+ const lines = [];
704
+ let length = 0;
705
+ for (const entry of picked) {
706
+ const line = `${entry.role}: ${entry.text}`;
707
+ if (length + line.length > LOOK_CHARS) {
708
+ lines.push("…");
709
+ break;
710
+ }
711
+ lines.push(line);
712
+ length += line.length + 1;
713
+ }
714
+ return lines.join(`
715
+ `) || "Nothing about that in the work.";
716
+ }
717
+ CallUtil.look = look;
718
+ function terms(question) {
719
+ const found = new Set;
720
+ for (const word of question.toLowerCase().match(/[a-z0-9_.-]{2,}/g) ?? []) {
721
+ found.add(word);
722
+ }
723
+ for (const run of question.match(/[\u3040-\u30ff\u3400-\u9fff]+/g) ?? []) {
724
+ for (let i = 0;i + 1 < run.length; i++) {
725
+ found.add(run.slice(i, i + 2));
726
+ }
727
+ }
728
+ return [...found];
729
+ }
730
+ CallUtil.terms = terms;
731
+ function score(text, words) {
732
+ const lower = text.toLowerCase();
733
+ return words.filter((word) => lower.includes(word)).length;
734
+ }
735
+ function texts(parts) {
736
+ return parts.filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join(`
737
+ `);
738
+ }
739
+ function short(text) {
740
+ const line = flat(text);
741
+ return line.length > ENTRY_CHARS ? `${line.slice(0, ENTRY_CHARS)}…` : line;
742
+ }
743
+ function flat(text) {
744
+ return text.replace(/\s+/g, " ").trim();
745
+ }
746
+ })(CallUtil ||= {});
747
+
748
+ // web-src/i18n.ts
749
+ var EN = {
750
+ settings: "Calls",
751
+ model: "Model of calls",
752
+ modelHint: "Who talks with you in a call while the work goes on. A fast one answers at once and costs little; the work keeps its own model.",
753
+ fast: "A fast one of the same provider"
754
+ };
755
+ var ZH = {
756
+ settings: "通话",
757
+ model: "通话用的模型",
758
+ modelHint: "通话时陪你说话的模型,任务照常在后台跑。用快的模型回应更及时、也更省钱;干活仍用对话自己的模型。",
759
+ fast: "同一提供商里快的那个"
760
+ };
761
+ var ZH_TW = {
762
+ settings: "通話",
763
+ model: "通話用的模型",
764
+ modelHint: "通話時陪你說話的模型,任務照常在後台跑。用快的模型回應更及時、也更省錢;幹活仍用對話自己的模型。",
765
+ fast: "同一供應商裡快的那個"
766
+ };
767
+ var JA = {
768
+ settings: "通話",
769
+ model: "通話のモデル",
770
+ modelHint: "通話中に話し相手になるモデルです。作業は裏で続きます。速いモデルなら即座に応え、コストも抑えられます。作業には会話自身のモデルを使います。",
771
+ fast: "同じプロバイダーの速いモデル"
772
+ };
773
+ var WORDS = { "zh-CN": ZH, "zh-TW": ZH_TW, "en-US": EN, "ja-JP": JA };
774
+ var CallWords;
775
+ ((CallWords) => {
776
+ function of(language) {
777
+ return TaLanguageUtil.pick(language, WORDS);
778
+ }
779
+ CallWords.of = of;
780
+ })(CallWords ||= {});
781
+
782
+ // web-src/react.ts
783
+ var React;
784
+ function bind(react) {
785
+ React = react;
786
+ }
787
+
788
+ // web-src/index.tsx
789
+ var MODEL = "model";
790
+ function activate(pi) {
791
+ bind(pi.React);
792
+ if (!pi.registerCallPartner) {
793
+ return () => {
794
+ return;
795
+ };
796
+ }
797
+ pi.registerCallPartner({
798
+ open: async (target) => {
799
+ const model = await modelFor(pi, target.cwd);
800
+ const { callId } = await pi.callHost("open", target, model);
801
+ let ending = false;
802
+ return {
803
+ say: async (text, options) => {
804
+ const reply = await pi.callHost("say", callId, text, options?.sent === true);
805
+ ending ||= reply.end === true;
806
+ return reply.text;
807
+ },
808
+ ending: () => ending,
809
+ next: () => pi.callHost("next", callId),
810
+ close: () => void pi.callHost("close", callId).catch(() => {
811
+ return;
812
+ })
813
+ };
814
+ }
815
+ });
816
+ const words = () => CallWords.of(pi.ui.language);
817
+ pi.registerChatIcon?.({
818
+ icon: (chat) => chat.group === NAME ? { icon: pi.ui.icons.Phone, folder: words().settings, quiet: true } : undefined
819
+ });
820
+ pi.registerSettings({
821
+ title: () => words().settings,
822
+ icon: pi.ui.icons.Phone,
823
+ group: "ta",
824
+ rows: [{ key: "model", label: () => words().model, description: () => words().modelHint, stacked: true, render: () => /* @__PURE__ */ React.createElement(ModelRow, {
825
+ pi
826
+ }) }]
827
+ });
828
+ return () => {
829
+ return;
830
+ };
831
+ }
832
+ async function modelFor(pi, cwd) {
833
+ const [chosen, settings] = await Promise.all([pi.storage.get(MODEL), pi.settings.getSettings(cwd).catch(() => {
834
+ return;
835
+ })]);
836
+ const current = settings?.project.model ?? settings?.user.model;
837
+ return CallUtil.model(settings?.models ?? [], chosen ?? "", current, settings?.agents);
838
+ }
839
+ function ModelRow({ pi }) {
840
+ const [value, setValue] = React.useState("");
841
+ React.useEffect(() => {
842
+ pi.storage.get(MODEL).then((chosen) => setValue(chosen ?? ""));
843
+ }, [pi]);
844
+ const { ModelPicker } = pi.ui;
845
+ return /* @__PURE__ */ React.createElement(ModelPicker, {
846
+ value,
847
+ defaultLabel: CallWords.of(pi.ui.language).fast,
848
+ label: CallWords.of(pi.ui.language).model,
849
+ noAgents: true,
850
+ onChange: (next) => {
851
+ setValue(next);
852
+ pi.storage.set(MODEL, next || null);
853
+ }
854
+ });
855
+ }
856
+ export {
857
+ activate as default
858
+ };