@celljs/ta-call 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/host/index.mjs ADDED
@@ -0,0 +1,899 @@
1
+ // web-src/call-host.ts
2
+ import { randomUUID } from "node:crypto";
3
+
4
+ // ../ta-protocol/esm/common/message-protocol.js
5
+ var TaMessageContext;
6
+ (function(TaMessageContext2) {
7
+ const BLOCK = /^<context>\n?[\s\S]*?\n?<\/context>\n?/;
8
+ function wrap(context, message) {
9
+ return `<context>
10
+ ${context}
11
+ </context>
12
+ ${message}`;
13
+ }
14
+ TaMessageContext2.wrap = wrap;
15
+ function strip(message) {
16
+ return message.replace(BLOCK, "");
17
+ }
18
+ TaMessageContext2.strip = strip;
19
+ function read(message) {
20
+ var _a;
21
+ const block = (_a = BLOCK.exec(message)) === null || _a === undefined ? undefined : _a[0];
22
+ return block === null || block === undefined ? undefined : block.replace(/^<context>\n?/, "").replace(/\n?<\/context>\n?$/, "");
23
+ }
24
+ TaMessageContext2.read = read;
25
+ })(TaMessageContext || (TaMessageContext = {}));
26
+ var TaMessageSource;
27
+ (function(TaMessageSource2) {
28
+ TaMessageSource2.DOUBLE = "ta:double";
29
+ const LINE = /^\[ta:from ([^\s\]]+)(?: ([^\]\n]+))?\]$/m;
30
+ function mark(message, from, detail) {
31
+ if (/^[/!]/.test(message) || of(message)) {
32
+ return message;
33
+ }
34
+ const line = `[ta:from ${from}${detail ? ` ${detail.replace(/[\]\n]/g, " ")}` : ""}]`;
35
+ const context = TaMessageContext.read(message);
36
+ return TaMessageContext.wrap(context === undefined ? line : `${context}
37
+ ${line}`, TaMessageContext.strip(message));
38
+ }
39
+ TaMessageSource2.mark = mark;
40
+ function of(message) {
41
+ const context = TaMessageContext.read(message);
42
+ const match = context === undefined ? null : LINE.exec(context);
43
+ return match ? { from: match[1], ...match[2] ? { detail: match[2].trim() } : {} } : undefined;
44
+ }
45
+ TaMessageSource2.of = of;
46
+ })(TaMessageSource || (TaMessageSource = {}));
47
+ var TaImageNote;
48
+ (function(TaImageNote2) {
49
+ 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 [^\]]+\.\]$/;
50
+ function strip(text) {
51
+ const lines = text.split(`
52
+ `);
53
+ const kept = lines.filter((line) => !NOTE.test(line.trim()));
54
+ if (kept.length === lines.length) {
55
+ return text;
56
+ }
57
+ return kept.join(`
58
+ `).replace(/\n+$/, "").replace(/^\n+/, "");
59
+ }
60
+ TaImageNote2.strip = strip;
61
+ })(TaImageNote || (TaImageNote = {}));
62
+ var TaImageSize;
63
+ (function(TaImageSize2) {
64
+ const JPEG_BYTES = 256 * 1024;
65
+ function of(base64) {
66
+ var _a, _b, _c;
67
+ let bytes;
68
+ try {
69
+ const binary = atob(base64.slice(0, Math.ceil(JPEG_BYTES * 4 / 3 / 4) * 4));
70
+ bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
71
+ } catch (_d) {
72
+ return;
73
+ }
74
+ 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);
75
+ return size && size.width > 0 && size.height > 0 ? size : undefined;
76
+ }
77
+ TaImageSize2.of = of;
78
+ function u16be(bytes, at) {
79
+ return bytes[at] << 8 | bytes[at + 1];
80
+ }
81
+ function u16le(bytes, at) {
82
+ return bytes[at] | bytes[at + 1] << 8;
83
+ }
84
+ function u24le(bytes, at) {
85
+ return bytes[at] | bytes[at + 1] << 8 | bytes[at + 2] << 16;
86
+ }
87
+ function u32be(bytes, at) {
88
+ return (bytes[at] << 24 | bytes[at + 1] << 16 | bytes[at + 2] << 8 | bytes[at + 3]) >>> 0;
89
+ }
90
+ function text(bytes, at, length) {
91
+ return String.fromCharCode(...bytes.subarray(at, at + length));
92
+ }
93
+ function png(bytes) {
94
+ return bytes.length >= 24 && bytes[0] === 137 && text(bytes, 1, 3) === "PNG" ? { width: u32be(bytes, 16), height: u32be(bytes, 20) } : undefined;
95
+ }
96
+ function gif(bytes) {
97
+ return bytes.length >= 10 && text(bytes, 0, 3) === "GIF" ? { width: u16le(bytes, 6), height: u16le(bytes, 8) } : undefined;
98
+ }
99
+ function webp(bytes) {
100
+ if (bytes.length < 30 || text(bytes, 0, 4) !== "RIFF" || text(bytes, 8, 4) !== "WEBP") {
101
+ return;
102
+ }
103
+ switch (text(bytes, 12, 4)) {
104
+ case "VP8 ":
105
+ return { width: u16le(bytes, 26) & 16383, height: u16le(bytes, 28) & 16383 };
106
+ case "VP8L": {
107
+ const bits = bytes[21] | bytes[22] << 8 | bytes[23] << 16 | bytes[24] << 24;
108
+ return { width: (bits & 16383) + 1, height: (bits >> 14 & 16383) + 1 };
109
+ }
110
+ case "VP8X":
111
+ return { width: u24le(bytes, 24) + 1, height: u24le(bytes, 27) + 1 };
112
+ default:
113
+ return;
114
+ }
115
+ }
116
+ function jpeg(bytes) {
117
+ if (bytes[0] !== 255 || bytes[1] !== 216) {
118
+ return;
119
+ }
120
+ let at = 2;
121
+ while (at + 9 < bytes.length) {
122
+ if (bytes[at] !== 255) {
123
+ return;
124
+ }
125
+ const marker = bytes[at + 1];
126
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
127
+ return { width: u16be(bytes, at + 7), height: u16be(bytes, at + 5) };
128
+ }
129
+ at += 2 + u16be(bytes, at + 2);
130
+ }
131
+ return;
132
+ }
133
+ })(TaImageSize || (TaImageSize = {}));
134
+ var TaAgentSummary;
135
+ (function(TaAgentSummary2) {
136
+ const START = /^\s*<conversation_history_summary>/;
137
+ const BLOCK = /^\s*<conversation_history_summary>[\s\S]*?(?:<\/conversation_history_summary>\s*|$)/;
138
+ function read(text) {
139
+ if (!START.test(text)) {
140
+ return;
141
+ }
142
+ return text.replace(/<\/?(?:conversation_history_summary|summary)>/g, "").replace(/<\/?\w*$/, "").trim();
143
+ }
144
+ TaAgentSummary2.read = read;
145
+ function strip(text) {
146
+ return text.replace(BLOCK, "");
147
+ }
148
+ TaAgentSummary2.strip = strip;
149
+ })(TaAgentSummary || (TaAgentSummary = {}));
150
+ var TaSkillUse;
151
+ (function(TaSkillUse2) {
152
+ const BLOCK = /^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;
153
+ function parse(message) {
154
+ var _a;
155
+ const match = BLOCK.exec(message);
156
+ if (!match) {
157
+ return;
158
+ }
159
+ return { name: match[1], location: match[2], content: match[3], message: ((_a = match[4]) === null || _a === undefined ? undefined : _a.trim()) || undefined };
160
+ }
161
+ TaSkillUse2.parse = parse;
162
+ function command(use) {
163
+ return use.message ? `/skill:${use.name} ${use.message}` : `/skill:${use.name}`;
164
+ }
165
+ TaSkillUse2.command = command;
166
+ })(TaSkillUse || (TaSkillUse = {}));
167
+ var TaTaskNote;
168
+ (function(TaTaskNote2) {
169
+ const NOTE = /^<task_(update|adopted|renamed) ((?:[^>"\n]|"[^"]*")*)>\n?([\s\S]*?)\n?<\/task_\1>$/;
170
+ const ATTRIBUTE = /(\w+)="([^"]*)"/g;
171
+ function write(note) {
172
+ const attributes = [`id="${quote(note.id)}"`];
173
+ if (note.was !== undefined) {
174
+ attributes.push(`was="${quote(note.was)}"`);
175
+ }
176
+ attributes.push(`title="${quote(note.title)}"`);
177
+ if (note.status !== undefined) {
178
+ attributes.push(`status="${quote(note.status)}"`);
179
+ }
180
+ return `<task_${note.kind} ${attributes.join(" ")}>
181
+ ${note.body}
182
+ </task_${note.kind}>`;
183
+ }
184
+ TaTaskNote2.write = write;
185
+ function parse(text) {
186
+ const match = NOTE.exec(text.trim());
187
+ if (!match) {
188
+ return;
189
+ }
190
+ const attributes = {};
191
+ for (const [, name, value] of match[2].matchAll(ATTRIBUTE)) {
192
+ attributes[name] = unquote(value);
193
+ }
194
+ if (!attributes.id || attributes.title === undefined) {
195
+ return;
196
+ }
197
+ const { id, title, status, was } = attributes;
198
+ return { kind: match[1], id, title, ...status ? { status } : {}, ...was ? { was } : {}, body: match[3] };
199
+ }
200
+ TaTaskNote2.parse = parse;
201
+ function quote(text) {
202
+ return text.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/\n/g, " ");
203
+ }
204
+ function unquote(text) {
205
+ return text.replace(/&quot;/g, '"').replace(/&amp;/g, "&");
206
+ }
207
+ })(TaTaskNote || (TaTaskNote = {}));
208
+
209
+ // ../ta-protocol/esm/common/ta-extension-host.js
210
+ var TA_WEBHOOK_MAX_BYTES = 256 * 1024;
211
+ var TA_HOST_EVENT = "ta:host";
212
+ var TaHostUtil;
213
+ (function(TaHostUtil2) {
214
+ TaHostUtil2.WAIT_MS = 1000;
215
+ function reach(events, name, waitMs = TaHostUtil2.WAIT_MS) {
216
+ return new Promise((resolve) => {
217
+ let heard = false;
218
+ let answered = false;
219
+ const timer = setTimeout(() => resolve(undefined), waitMs);
220
+ const request = {
221
+ name,
222
+ heard: () => {
223
+ heard = true;
224
+ },
225
+ resolve: (answer) => {
226
+ answered = true;
227
+ clearTimeout(timer);
228
+ resolve(answer);
229
+ }
230
+ };
231
+ events.emit(TA_HOST_EVENT, request);
232
+ if (!heard && !answered) {
233
+ clearTimeout(timer);
234
+ resolve(undefined);
235
+ }
236
+ });
237
+ }
238
+ TaHostUtil2.reach = reach;
239
+ function marked(systemPrompt, mark) {
240
+ return role(systemPrompt).includes(mark);
241
+ }
242
+ TaHostUtil2.marked = marked;
243
+ function role(systemPrompt) {
244
+ if (!systemPrompt) {
245
+ return "";
246
+ }
247
+ const open = `<addendum>
248
+ `;
249
+ const start = systemPrompt.indexOf(open);
250
+ const context = systemPrompt.indexOf(`<project_context>
251
+ `);
252
+ if (start < 0 || context >= 0 && context < start) {
253
+ return "";
254
+ }
255
+ const end = systemPrompt.indexOf(`
256
+ </addendum>`, start);
257
+ return systemPrompt.slice(start + open.length, end < 0 ? undefined : end);
258
+ }
259
+ TaHostUtil2.role = role;
260
+ })(TaHostUtil || (TaHostUtil = {}));
261
+ var TA_ASK_ENTRY = "ta-ask";
262
+ var TaAskUtil;
263
+ (function(TaAskUtil2) {
264
+ const LENGTH = 120;
265
+ function entry(question) {
266
+ const line = question.replace(/\s+/g, " ").trim();
267
+ return { question: line.length > LENGTH ? `${line.slice(0, LENGTH - 1)}…` : line };
268
+ }
269
+ TaAskUtil2.entry = entry;
270
+ function asking(entries) {
271
+ var _a;
272
+ for (let i = entries.length - 1;i >= 0; i--) {
273
+ const entry2 = entries[i];
274
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
275
+ return;
276
+ }
277
+ if (entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY) {
278
+ return read(entry2);
279
+ }
280
+ }
281
+ return;
282
+ }
283
+ TaAskUtil2.asking = asking;
284
+ function next(asked, entry2) {
285
+ var _a;
286
+ if (entry2.type === "message" && ((_a = entry2.message) === null || _a === undefined ? undefined : _a.role) === "user") {
287
+ return;
288
+ }
289
+ return entry2.type === "custom" && entry2.customType === TA_ASK_ENTRY ? read(entry2) : asked;
290
+ }
291
+ TaAskUtil2.next = next;
292
+ function read(found) {
293
+ var _a;
294
+ const question = (_a = found.data) === null || _a === undefined ? undefined : _a.question;
295
+ if (typeof question !== "string" || !question.trim()) {
296
+ return;
297
+ }
298
+ const at = found.timestamp ? Date.parse(found.timestamp) : Number.NaN;
299
+ return { question: entry(question).question, at: Number.isNaN(at) ? 0 : at };
300
+ }
301
+ })(TaAskUtil || (TaAskUtil = {}));
302
+
303
+ // web-src/call-protocol.ts
304
+ var NAME = "@celljs/ta-call";
305
+ var CALL_MARK = "[ta-call]";
306
+
307
+ // ../ta-protocol/esm/common/language.js
308
+ var TaLanguageUtil;
309
+ (function(TaLanguageUtil2) {
310
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
311
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
312
+ function of(tag) {
313
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
314
+ if (/^zh(\b|-)/.test(said)) {
315
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
316
+ }
317
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
318
+ }
319
+ TaLanguageUtil2.of = of;
320
+ function server(env = typeof process === "undefined" ? {} : process.env) {
321
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
322
+ }
323
+ TaLanguageUtil2.server = server;
324
+ function pick(language, words) {
325
+ return words[of(language)];
326
+ }
327
+ TaLanguageUtil2.pick = pick;
328
+ function say(words) {
329
+ return words[server()];
330
+ }
331
+ TaLanguageUtil2.say = say;
332
+ function chinese(language) {
333
+ return of(language).startsWith("zh");
334
+ }
335
+ TaLanguageUtil2.chinese = chinese;
336
+ function cjk(language) {
337
+ return of(language) !== "en-US";
338
+ }
339
+ TaLanguageUtil2.cjk = cjk;
340
+ function list(language, items) {
341
+ return items.join(cjk(language) ? "、" : ", ");
342
+ }
343
+ TaLanguageUtil2.list = list;
344
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
345
+
346
+ // web-src/call-util.ts
347
+ var LOOK_CHARS = 1500;
348
+ var ENTRY_CHARS = 600;
349
+ var SEED_CHARS = 1200;
350
+ var ROLE_CHARS = 800;
351
+ var LAST_ENTRIES = 12;
352
+ var NEWS = "[news]";
353
+ var QUIET = "-";
354
+ var FAST = /(mini|flash|haiku|lite|nano|turbo|small|fast|air)\b/i;
355
+ var CallUtil;
356
+ ((CallUtil) => {
357
+ function role(id, target, seed) {
358
+ const work = target.double ? "the user's double, which hands out tasks of its own" : `their conversation${target.cwd ? ` in ${target.cwd}` : ""}`;
359
+ return [
360
+ `${CALL_MARK} ${id}`,
361
+ `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.`,
362
+ "- 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.",
363
+ "- Chat, tell a poem, sing a song (say its words), answer what you know: do it yourself, never through the work.",
364
+ "- 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.",
365
+ "- 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.",
366
+ "- When the user wants what the work or a side conversation does stopped: stop.",
367
+ "- 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.",
368
+ "- 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); never decide for them.",
369
+ "- What only the screen has (what the user looks at, a page of an extension): app_look, app_go, app_do; to show them where something is, with here: true.",
370
+ "- A message that starts with [sent] went to the work already: acknowledge it in a few words.",
371
+ `- A message that starts with ${NEWS} 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.`,
372
+ ...seed ? ["", seedText(seed, target.double)] : []
373
+ ].join(`
374
+ `);
375
+ }
376
+ CallUtil.role = role;
377
+ function seedText(seed, double) {
378
+ const lines = ["<called>"];
379
+ if (seed.name) {
380
+ lines.push(`Conversation: ${flat(seed.name).slice(0, 120)}${seed.cwd ? ` (in ${seed.cwd})` : ""}`);
381
+ }
382
+ const role2 = seed.role && !double ? flat(seed.role).slice(0, ROLE_CHARS) : "";
383
+ if (role2) {
384
+ lines.push(`Its role: speak as it would, with its focus. ${role2}`);
385
+ }
386
+ lines.push(`Now: ${seed.working ? "working" : "idle"}${seed.queued ? `, ${seed.queued} queued` : ""}${seed.waiting ? ", waiting for the user" : ""}.`);
387
+ const recent = [];
388
+ let length = 0;
389
+ const said2 = seed.entries.filter((entry) => entry.role !== "tool");
390
+ for (let i = said2.length - 1;i >= 0; i--) {
391
+ const line = `${said2[i].role}: ${said2[i].text.slice(0, 300)}`;
392
+ if (length + line.length > SEED_CHARS) {
393
+ break;
394
+ }
395
+ recent.unshift(line);
396
+ length += line.length + 1;
397
+ }
398
+ if (recent.length) {
399
+ lines.push("Its last lines (look for more):", ...recent);
400
+ }
401
+ lines.push("</called>");
402
+ return lines.join(`
403
+ `);
404
+ }
405
+ CallUtil.seedText = seedText;
406
+ function side(text, from) {
407
+ const about = from ? ` about the conversation "${flat(from).slice(0, 120)}"` : "";
408
+ 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>
409
+ ${text}`;
410
+ }
411
+ CallUtil.side = side;
412
+ function sideOfDouble(text, title) {
413
+ const named = title ? ` ("${flat(title).slice(0, 80)}")` : "";
414
+ return `The user asked in a call for this as a task of its own${named}: start it with start_task, then go on.
415
+ ${text}`;
416
+ }
417
+ CallUtil.sideOfDouble = sideOfDouble;
418
+ function callOf(role2) {
419
+ const at = role2.indexOf(CALL_MARK);
420
+ return at < 0 ? undefined : role2.slice(at + CALL_MARK.length).trim().split(/\s/)[0] || undefined;
421
+ }
422
+ CallUtil.callOf = callOf;
423
+ function name(language, called) {
424
+ const call = TaLanguageUtil.pick(language, { "zh-CN": "通话", "zh-TW": "通話", "en-US": "Call", "ja-JP": "通話" });
425
+ const other = called ? flat(called).slice(0, 40) : "";
426
+ return other ? `${call} · ${other}` : call;
427
+ }
428
+ CallUtil.name = name;
429
+ function news(lines) {
430
+ return [NEWS, ...lines].join(`
431
+ `);
432
+ }
433
+ CallUtil.news = news;
434
+ function toSay(reply) {
435
+ const said2 = reply?.trim();
436
+ return said2 && said2 !== QUIET && !said2.startsWith(NEWS) ? said2 : undefined;
437
+ }
438
+ CallUtil.toSay = toSay;
439
+ function ended(name2, how) {
440
+ if (how.error) {
441
+ return `${name2} failed: ${how.error.replace(/\s+/g, " ").slice(0, 200)}`;
442
+ }
443
+ if (how.aborted) {
444
+ return `${name2} was stopped.`;
445
+ }
446
+ const last = how.last?.replace(/\s+/g, " ").trim();
447
+ return last ? `${name2} finished. Its last words: ${last.slice(0, 400)}` : `${name2} finished.`;
448
+ }
449
+ CallUtil.ended = ended;
450
+ function waits(name2) {
451
+ return `${name2} waits for the user to decide or confirm, on the screen.`;
452
+ }
453
+ CallUtil.waits = waits;
454
+ function said(text, sent) {
455
+ return sent ? `[sent] ${text}` : text;
456
+ }
457
+ CallUtil.said = said;
458
+ function model(models, chosen, current) {
459
+ if (chosen && models.includes(chosen)) {
460
+ return chosen;
461
+ }
462
+ const provider = current?.split("/")[0];
463
+ const fast = models.filter((model2) => FAST.test(model2.split("/").slice(1).join("/")));
464
+ return fast.find((model2) => model2.split("/")[0] === provider) ?? current;
465
+ }
466
+ CallUtil.model = model;
467
+ function entries(messages) {
468
+ const lines = [];
469
+ for (const raw of messages) {
470
+ const message = raw;
471
+ const parts = typeof message.content === "string" ? [{ type: "text", text: message.content }] : message.content ?? [];
472
+ if (message.role === "user") {
473
+ const text = TaMessageContext.strip(texts(parts)).trim();
474
+ if (text) {
475
+ lines.push({ role: "user", text: short(text) });
476
+ }
477
+ } else if (message.role === "assistant") {
478
+ const text = texts(parts).trim();
479
+ if (text) {
480
+ lines.push({ role: "assistant", text: short(text) });
481
+ }
482
+ for (const call of parts.filter((part) => part.type === "toolCall")) {
483
+ lines.push({ role: "tool", text: short(`${call.name}(${JSON.stringify(call.arguments ?? {})})`) });
484
+ }
485
+ } else if (message.role === "toolResult") {
486
+ const text = texts(parts).trim();
487
+ lines.push({ role: "tool", text: short(`${message.toolName ?? "tool"} → ${text || "(nothing)"}`) });
488
+ }
489
+ }
490
+ return lines;
491
+ }
492
+ CallUtil.entries = entries;
493
+ function look(entries2, question) {
494
+ const words = terms(question);
495
+ let picked;
496
+ if (!words.length) {
497
+ picked = entries2.slice(-LAST_ENTRIES);
498
+ } else {
499
+ const scored = entries2.map((entry, index) => ({ entry, index, score: score(entry.text, words) })).filter((each) => each.score > 0);
500
+ scored.sort((a, b) => b.score - a.score || b.index - a.index);
501
+ picked = scored.slice(0, LAST_ENTRIES).sort((a, b) => a.index - b.index).map((each) => each.entry);
502
+ }
503
+ const lines = [];
504
+ let length = 0;
505
+ for (const entry of picked) {
506
+ const line = `${entry.role}: ${entry.text}`;
507
+ if (length + line.length > LOOK_CHARS) {
508
+ lines.push("…");
509
+ break;
510
+ }
511
+ lines.push(line);
512
+ length += line.length + 1;
513
+ }
514
+ return lines.join(`
515
+ `) || "Nothing about that in the work.";
516
+ }
517
+ CallUtil.look = look;
518
+ function terms(question) {
519
+ const found = new Set;
520
+ for (const word of question.toLowerCase().match(/[a-z0-9_.-]{2,}/g) ?? []) {
521
+ found.add(word);
522
+ }
523
+ for (const run of question.match(/[\u3040-\u30ff\u3400-\u9fff]+/g) ?? []) {
524
+ for (let i = 0;i + 1 < run.length; i++) {
525
+ found.add(run.slice(i, i + 2));
526
+ }
527
+ }
528
+ return [...found];
529
+ }
530
+ CallUtil.terms = terms;
531
+ function score(text, words) {
532
+ const lower = text.toLowerCase();
533
+ return words.filter((word) => lower.includes(word)).length;
534
+ }
535
+ function texts(parts) {
536
+ return parts.filter((part) => part.type === "text" && typeof part.text === "string").map((part) => part.text).join(`
537
+ `);
538
+ }
539
+ function short(text) {
540
+ const line = flat(text);
541
+ return line.length > ENTRY_CHARS ? `${line.slice(0, ENTRY_CHARS)}…` : line;
542
+ }
543
+ function flat(text) {
544
+ return text.replace(/\s+/g, " ").trim();
545
+ }
546
+ })(CallUtil ||= {});
547
+
548
+ // web-src/call-host.ts
549
+ var DEFAULTS = {
550
+ pollMs: 150,
551
+ answerMs: 90000,
552
+ idleMs: 15 * 60000,
553
+ newsMs: 1200,
554
+ watchMs: 2000,
555
+ nextMs: 25000,
556
+ now: () => Date.now()
557
+ };
558
+
559
+ class CallHost {
560
+ host;
561
+ calls = new Map;
562
+ options;
563
+ offEvents;
564
+ watchTimer;
565
+ constructor(host, options = {}) {
566
+ this.host = host;
567
+ this.options = { ...DEFAULTS, ...options };
568
+ }
569
+ async open(target, model) {
570
+ await this.sweep();
571
+ const id = randomUUID().slice(0, 8);
572
+ const caller = this.host.team?.current() ?? "";
573
+ const info = (await this.sessions()).find((session) => session.sessionId === target.sessionId);
574
+ const cwd = target.cwd || info?.cwd || (await this.host.getServerInfo()).cwd;
575
+ const seed = await this.seed(target, info, cwd);
576
+ const { sessionId } = await this.host.openSession({
577
+ cwd,
578
+ appendSystemPrompt: CallUtil.role(id, { ...target, cwd }, seed),
579
+ group: NAME,
580
+ thinkingLevel: "off",
581
+ ...model ? { model } : {}
582
+ });
583
+ await this.host.setSessionName(sessionId, CallUtil.name(target.language, target.double ? undefined : seed.name)).catch(() => {
584
+ return;
585
+ });
586
+ this.calls.set(id, {
587
+ id,
588
+ front: sessionId,
589
+ target: { ...target, cwd },
590
+ caller,
591
+ seed,
592
+ ...info?.model ? { model: info.model } : {},
593
+ sides: new Map,
594
+ used: this.options.now(),
595
+ watched: new Set([target.sessionId]),
596
+ waiting: new Set,
597
+ news: [],
598
+ outbox: [],
599
+ waiters: [],
600
+ turns: Promise.resolve()
601
+ });
602
+ this.watch();
603
+ return { callId: id };
604
+ }
605
+ async say(callId, text, sent = false) {
606
+ const call = this.call(callId);
607
+ call.used = this.options.now();
608
+ const reply = await this.turn(call, CallUtil.said(text, sent));
609
+ call.used = this.options.now();
610
+ return reply;
611
+ }
612
+ next(callId) {
613
+ const call = this.calls.get(callId);
614
+ if (!call) {
615
+ return Promise.resolve(undefined);
616
+ }
617
+ const ready = call.outbox.shift();
618
+ if (ready) {
619
+ return Promise.resolve(ready);
620
+ }
621
+ return new Promise((resolve) => {
622
+ const done = (text) => {
623
+ clearTimeout(timer);
624
+ call.waiters = call.waiters.filter((waiter) => waiter !== done);
625
+ resolve(text);
626
+ };
627
+ const timer = setTimeout(() => done(undefined), this.options.nextMs);
628
+ call.waiters.push(done);
629
+ });
630
+ }
631
+ async close(callId) {
632
+ const call = this.calls.get(callId);
633
+ this.calls.delete(callId);
634
+ if (call) {
635
+ clearTimeout(call.newsTimer);
636
+ for (const waiter of [...call.waiters]) {
637
+ waiter(undefined);
638
+ }
639
+ await this.host.closeSession(call.front).catch(() => {
640
+ return;
641
+ });
642
+ }
643
+ if (!this.calls.size) {
644
+ this.unwatch();
645
+ }
646
+ }
647
+ callOf(systemPrompt) {
648
+ const id = CallUtil.callOf(TaHostUtil.role(systemPrompt));
649
+ return id ? this.calls.get(id) : undefined;
650
+ }
651
+ async tell(call, text, now) {
652
+ const { isStreaming } = await this.host.getState(call.target.sessionId);
653
+ await this.as(call, () => this.host.prompt(call.target.sessionId, {
654
+ clientMessageId: randomUUID(),
655
+ message: TaMessageSource.mark(text, NAME),
656
+ streamingBehavior: now ? "steer" : "followUp"
657
+ }));
658
+ return isStreaming ? now ? "Told the work as it goes." : "Queued after what the work does now." : "The work started on it.";
659
+ }
660
+ async side(call, text, title) {
661
+ if (call.target.double) {
662
+ await this.as(call, () => this.host.prompt(call.target.sessionId, {
663
+ clientMessageId: randomUUID(),
664
+ message: TaMessageSource.mark(CallUtil.sideOfDouble(text, title), NAME),
665
+ streamingBehavior: "followUp"
666
+ }));
667
+ return "Asked the double to start it as a task of its own: news comes when it ends.";
668
+ }
669
+ const name = title?.trim() || text.replace(/\s+/g, " ").trim().slice(0, 40);
670
+ const { sessionId } = await this.as(call, () => this.host.openSession({
671
+ cwd: call.target.cwd || ".",
672
+ ...call.seed.role ? { appendSystemPrompt: call.seed.role } : {},
673
+ ...call.model ? { model: call.model } : {}
674
+ }));
675
+ await this.host.setSessionName(sessionId, name).catch(() => {
676
+ return;
677
+ });
678
+ call.sides.set(sessionId, name);
679
+ call.watched.add(sessionId);
680
+ await this.as(call, () => this.host.prompt(sessionId, { clientMessageId: randomUUID(), message: TaMessageSource.mark(CallUtil.side(text, call.seed.name), NAME) }));
681
+ return `Opened the side conversation "${name}": it works on it now, news comes when it ends.`;
682
+ }
683
+ async stop(call, within) {
684
+ const sessionId = within ? (await this.named(call, within))?.sessionId : call.target.sessionId;
685
+ if (!sessionId) {
686
+ return `No conversation named "${within}".`;
687
+ }
688
+ if (!(await this.host.getState(sessionId)).isStreaming) {
689
+ return "It does nothing now.";
690
+ }
691
+ await this.as(call, () => this.host.abort(sessionId));
692
+ return "Stopped.";
693
+ }
694
+ async status(call) {
695
+ const sessions = await this.host.listSessions();
696
+ const state = await this.host.getState(call.target.sessionId);
697
+ const last = (await this.host.getLastAssistantText(call.target.sessionId)).text?.trim();
698
+ const lines = [
699
+ `The work: ${state.isStreaming ? "working" : "idle"}${state.pendingMessageCount ? `, ${state.pendingMessageCount} queued` : ""}${sessions.find((session) => session.sessionId === call.target.sessionId)?.waiting ? ", waiting for the user" : ""}.`,
700
+ ...last ? [`Its last words: ${last.replace(/\s+/g, " ").slice(0, 300)}`] : []
701
+ ];
702
+ for (const [sessionId, name] of call.sides) {
703
+ const side = sessions.find((session) => session.sessionId === sessionId);
704
+ lines.push(`${name} (a side conversation of this call): ${side?.waiting ? "waiting for the user" : side?.isStreaming ? "working" : "idle"}.`);
705
+ }
706
+ const others = sessions.filter((session) => session.sessionId !== call.target.sessionId && !call.sides.has(session.sessionId) && session.group !== NAME && (session.isStreaming || session.waiting)).slice(0, 8);
707
+ for (const other of others) {
708
+ lines.push(`${other.sessionName || other.firstMessage || other.cwd}: ${other.waiting ? "waiting for the user" : "working"}.`);
709
+ }
710
+ return lines.join(`
711
+ `);
712
+ }
713
+ async look(call, question, within) {
714
+ const file = within ? (await this.named(call, within))?.sessionFile : (await this.host.getState(call.target.sessionId)).sessionFile;
715
+ if (!file) {
716
+ return within ? `No conversation named "${within}".` : "The work has nothing written yet.";
717
+ }
718
+ return CallUtil.look(CallUtil.entries(await this.host.sessionMessages(file)), question);
719
+ }
720
+ dispose() {
721
+ for (const id of [...this.calls.keys()]) {
722
+ this.close(id);
723
+ }
724
+ this.unwatch();
725
+ }
726
+ async event(event) {
727
+ if (event.group === NAME) {
728
+ return;
729
+ }
730
+ for (const call of this.calls.values()) {
731
+ if (event.type === "turn_start") {
732
+ call.watched.add(event.sessionId);
733
+ } else if (call.watched.has(event.sessionId)) {
734
+ const name = await this.nameOf(call, event.sessionId);
735
+ const last = event.error || event.aborted ? undefined : (await this.host.getLastAssistantText(event.sessionId).catch(() => {
736
+ return;
737
+ }))?.text;
738
+ this.report(call, CallUtil.ended(name, { error: event.error, aborted: event.aborted, last: last ?? undefined }));
739
+ }
740
+ }
741
+ }
742
+ async lookWaiting() {
743
+ const sessions = await this.sessions();
744
+ for (const call of this.calls.values()) {
745
+ for (const session of sessions) {
746
+ if (!call.watched.has(session.sessionId)) {
747
+ continue;
748
+ }
749
+ if (session.waiting && !call.waiting.has(session.sessionId)) {
750
+ call.waiting.add(session.sessionId);
751
+ this.report(call, CallUtil.waits(await this.nameOf(call, session.sessionId)));
752
+ } else if (!session.waiting) {
753
+ call.waiting.delete(session.sessionId);
754
+ }
755
+ }
756
+ }
757
+ }
758
+ report(call, line) {
759
+ call.news.push(line);
760
+ clearTimeout(call.newsTimer);
761
+ call.newsTimer = setTimeout(() => {
762
+ const news = call.news.splice(0);
763
+ if (!news.length || !this.calls.has(call.id)) {
764
+ return;
765
+ }
766
+ this.turn(call, CallUtil.news(news)).then((reply) => {
767
+ const said = CallUtil.toSay(reply);
768
+ if (!said || !this.calls.has(call.id)) {
769
+ return;
770
+ }
771
+ const waiter = call.waiters[0];
772
+ if (waiter) {
773
+ waiter(said);
774
+ } else {
775
+ call.outbox.push(said);
776
+ }
777
+ }, () => {
778
+ return;
779
+ });
780
+ }, this.options.newsMs);
781
+ }
782
+ turn(call, message) {
783
+ const next = call.turns.then(async () => {
784
+ const before = await this.host.getState(call.front);
785
+ await this.host.prompt(call.front, { clientMessageId: randomUUID(), message });
786
+ await this.settled(call.front, before.messageCount);
787
+ return (await this.host.getLastAssistantText(call.front)).text?.trim() || undefined;
788
+ });
789
+ call.turns = next.catch(() => {
790
+ return;
791
+ });
792
+ return next;
793
+ }
794
+ sessions() {
795
+ return this.host.listSessions().catch(() => []);
796
+ }
797
+ async nameOf(call, sessionId) {
798
+ if (sessionId === call.target.sessionId) {
799
+ return "The work";
800
+ }
801
+ const side = call.sides.get(sessionId);
802
+ if (side) {
803
+ return `The side conversation "${side}"`;
804
+ }
805
+ const session = (await this.sessions()).find((each) => each.sessionId === sessionId);
806
+ return session?.sessionName || session?.firstMessage || "A task";
807
+ }
808
+ watch() {
809
+ this.offEvents ??= this.host.onSessionEvent((event) => void this.event(event));
810
+ this.watchTimer ??= setInterval(() => void this.lookWaiting(), this.options.watchMs);
811
+ }
812
+ unwatch() {
813
+ this.offEvents?.();
814
+ this.offEvents = undefined;
815
+ clearInterval(this.watchTimer);
816
+ this.watchTimer = undefined;
817
+ }
818
+ call(callId) {
819
+ const call = this.calls.get(callId);
820
+ if (!call) {
821
+ throw new Error("This call is over.");
822
+ }
823
+ return call;
824
+ }
825
+ async named(call, name) {
826
+ const wanted = name.trim().toLowerCase();
827
+ const sessions = (await this.host.listSessions()).filter((session) => session.group !== NAME);
828
+ for (const [sessionId, side] of call.sides) {
829
+ if (side.toLowerCase().includes(wanted)) {
830
+ const sessionFile = sessions.find((session) => session.sessionId === sessionId)?.sessionFile ?? (await this.host.getState(sessionId)).sessionFile;
831
+ return { sessionId, ...sessionFile ? { sessionFile } : {} };
832
+ }
833
+ }
834
+ return sessions.find((session) => (session.sessionName ?? session.firstMessage ?? "").toLowerCase().includes(wanted));
835
+ }
836
+ async seed(target, info, cwd) {
837
+ const state = await this.host.getState(target.sessionId).catch(() => {
838
+ return;
839
+ });
840
+ const file = target.sessionFile || state?.sessionFile;
841
+ const [messages, role] = file ? await Promise.all([
842
+ this.host.sessionMessages(file).catch(() => []),
843
+ target.double ? undefined : this.host.sessionRole?.(file).catch(() => {
844
+ return;
845
+ })
846
+ ]) : [[], undefined];
847
+ const name = info?.sessionName || info?.firstMessage;
848
+ return {
849
+ ...name ? { name } : {},
850
+ cwd,
851
+ ...role ? { role } : {},
852
+ entries: CallUtil.entries(messages),
853
+ working: !!state?.isStreaming,
854
+ queued: state?.pendingMessageCount ?? 0,
855
+ waiting: !!info?.waiting
856
+ };
857
+ }
858
+ as(call, run) {
859
+ const team = this.host.team;
860
+ return team && call.caller ? team.actAs(call.caller, run) : run();
861
+ }
862
+ async sweep() {
863
+ const now = this.options.now();
864
+ for (const call of [...this.calls.values()]) {
865
+ if (now - call.used > this.options.idleMs) {
866
+ await this.close(call.id);
867
+ }
868
+ }
869
+ }
870
+ async settled(sessionId, before) {
871
+ const start = this.options.now();
872
+ for (;; ) {
873
+ const state = await this.host.getState(sessionId);
874
+ if (!state.isStreaming && state.pendingMessageCount === 0 && state.messageCount > before) {
875
+ return;
876
+ }
877
+ if (this.options.now() - start > this.options.answerMs) {
878
+ throw new Error("No answer in time.");
879
+ }
880
+ await new Promise((resolve) => setTimeout(resolve, this.options.pollMs));
881
+ }
882
+ }
883
+ }
884
+
885
+ // web-src/host.ts
886
+ async function activate(host) {
887
+ const calls = new CallHost(host);
888
+ return {
889
+ dispose: () => calls.dispose(),
890
+ open: (target, model) => calls.open(target, model),
891
+ say: (callId, text, sent) => calls.say(callId, text, sent === true),
892
+ next: (callId) => calls.next(callId),
893
+ close: (callId) => calls.close(callId),
894
+ service: calls
895
+ };
896
+ }
897
+ export {
898
+ activate as default
899
+ };