@celljs/ta-usage 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,953 @@
1
+ // ../ta-protocol/esm/common/language.js
2
+ var TaLanguageUtil;
3
+ (function(TaLanguageUtil2) {
4
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
5
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
6
+ function of(tag) {
7
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
8
+ if (/^zh(\b|-)/.test(said)) {
9
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
10
+ }
11
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
12
+ }
13
+ TaLanguageUtil2.of = of;
14
+ function server(env = typeof process === "undefined" ? {} : process.env) {
15
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
16
+ }
17
+ TaLanguageUtil2.server = server;
18
+ function pick(language, words) {
19
+ return words[of(language)];
20
+ }
21
+ TaLanguageUtil2.pick = pick;
22
+ function say(words) {
23
+ return words[server()];
24
+ }
25
+ TaLanguageUtil2.say = say;
26
+ function chinese(language) {
27
+ return of(language).startsWith("zh");
28
+ }
29
+ TaLanguageUtil2.chinese = chinese;
30
+ function cjk(language) {
31
+ return of(language) !== "en-US";
32
+ }
33
+ TaLanguageUtil2.cjk = cjk;
34
+ function list(language, items) {
35
+ return items.join(cjk(language) ? "、" : ", ");
36
+ }
37
+ TaLanguageUtil2.list = list;
38
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
39
+
40
+ // web-src/i18n.ts
41
+ var EN = {
42
+ title: "Usage",
43
+ intro: "Tokens and cost of your conversations on this computer",
44
+ days: "{n} days",
45
+ cost: "Cost",
46
+ tokens: "Tokens",
47
+ input: "Input",
48
+ output: "Output",
49
+ cached: "From cache",
50
+ calls: "Calls",
51
+ daily: "By day",
52
+ models: "By model",
53
+ conversations: "Used the most",
54
+ none: "Nothing used in these days yet",
55
+ loading: "Reading the conversations…",
56
+ failed: "Could not read the usage",
57
+ model: "Model",
58
+ untitled: "Untitled",
59
+ costNote: "The cost is the price the model service gives; a model without one counts its tokens only."
60
+ };
61
+ var ZH = {
62
+ title: "用量",
63
+ intro: "这台电脑上各个对话用了多少 tokens、花了多少钱",
64
+ days: "{n} 天",
65
+ cost: "花费",
66
+ tokens: "Tokens",
67
+ input: "输入",
68
+ output: "输出",
69
+ cached: "缓存命中",
70
+ calls: "调用",
71
+ daily: "按天",
72
+ models: "按模型",
73
+ conversations: "用得最多的对话",
74
+ none: "这几天还没有用量",
75
+ loading: "正在读取对话记录…",
76
+ failed: "读取用量失败",
77
+ model: "模型",
78
+ untitled: "未命名",
79
+ costNote: "花费按模型服务给出的价格计算,没有价格的模型只计 tokens。"
80
+ };
81
+ var ZH_TW = {
82
+ title: "用量",
83
+ intro: "這台電腦上各個對話用了多少 tokens、花了多少錢",
84
+ days: "{n} 天",
85
+ cost: "花費",
86
+ tokens: "Tokens",
87
+ input: "輸入",
88
+ output: "輸出",
89
+ cached: "快取命中",
90
+ calls: "呼叫",
91
+ daily: "按天",
92
+ models: "按模型",
93
+ conversations: "用得最多的對話",
94
+ none: "這幾天還沒有用量",
95
+ loading: "正在讀取對話紀錄…",
96
+ failed: "讀取用量失敗",
97
+ model: "模型",
98
+ untitled: "未命名",
99
+ costNote: "花費按模型服務給出的價格計算,沒有價格的模型只計 tokens。"
100
+ };
101
+ var JA = {
102
+ title: "使用量",
103
+ intro: "このコンピューターの会話が使ったトークン数と費用",
104
+ days: "{n} 日",
105
+ cost: "費用",
106
+ tokens: "トークン",
107
+ input: "入力",
108
+ output: "出力",
109
+ cached: "キャッシュ",
110
+ calls: "呼び出し",
111
+ daily: "日別",
112
+ models: "モデル別",
113
+ conversations: "よく使った会話",
114
+ none: "この期間の使用量はまだありません",
115
+ loading: "会話記録を読み込み中…",
116
+ failed: "使用量を読み込めませんでした",
117
+ model: "モデル",
118
+ untitled: "無題",
119
+ costNote: "費用はモデルサービスの価格で計算します。価格のないモデルはトークン数のみ数えます。"
120
+ };
121
+ var WORDS = { "zh-CN": ZH, "zh-TW": ZH_TW, "en-US": EN, "ja-JP": JA };
122
+ var UsageWordsUtil;
123
+ ((UsageWordsUtil) => {
124
+ function of(language) {
125
+ return TaLanguageUtil.pick(language, WORDS);
126
+ }
127
+ UsageWordsUtil.of = of;
128
+ function format(text, values) {
129
+ return text.replace(/\{(\w+)\}/g, (whole, key) => (key in values) ? String(values[key]) : whole);
130
+ }
131
+ UsageWordsUtil.format = format;
132
+ })(UsageWordsUtil ||= {});
133
+
134
+ // web-src/react.ts
135
+ var React;
136
+ function bind(react) {
137
+ React = react;
138
+ }
139
+
140
+ // web-src/style.ts
141
+ var STYLE = `
142
+ .tus-scroll { flex: 1; min-height: 0; height: 100%; overflow-y: auto; overflow-x: hidden; overscroll-behavior: contain; scrollbar-gutter: stable; }
143
+ .tus { display: flex; flex-direction: column; gap: 16px; width: 100%; min-height: 100%; max-width: var(--ta-page-wide); margin: 0 auto; padding: 28px 24px 48px; box-sizing: border-box; }
144
+ .tus-head { display: flex; align-items: flex-end; justify-content: space-between; gap: 16px; flex-wrap: wrap; margin: 0 2px 4px; }
145
+ .tus-title { margin: 0; color: var(--ta-text); font-size: calc(20px * var(--ta-font-scale)); line-height: calc(28px * var(--ta-font-scale)); font-weight: 600; }
146
+ .tus-intro { margin: 4px 0 0; color: var(--ta-muted); font-size: calc(13.5px * var(--ta-font-scale)); }
147
+ .tus { container-type: inline-size; }
148
+ .tus-stats { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 10px; }
149
+ @container (max-width: 720px) { .tus-stats { grid-template-columns: repeat(3, minmax(0, 1fr)); } }
150
+ .tus-stat { display: flex; flex-direction: column; gap: 4px; padding: 12px 14px; border-radius: 12px; background: var(--ta-card); border: 1px solid var(--ta-border-muted); min-width: 0; }
151
+ .tus-stat span { color: var(--ta-muted); font-size: calc(12px * var(--ta-font-scale)); }
152
+ .tus-stat b { color: var(--ta-text); font-size: calc(19px * var(--ta-font-scale)); font-weight: 600; font-variant-numeric: tabular-nums; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
153
+ .tus-card { padding: 14px 16px; border-radius: 12px; background: var(--ta-card); border: 1px solid var(--ta-border-muted); }
154
+ .tus-card h2 { margin: 0 0 12px; color: var(--ta-text); font-size: calc(13.5px * var(--ta-font-scale)); font-weight: 600; }
155
+ .tus-bars { display: flex; align-items: flex-end; gap: 4px; height: 120px; }
156
+ .tus-bars-dense { gap: 1px; }
157
+ .tus-bar { flex: 1; min-width: 0; height: 100%; display: flex; align-items: flex-end; border-radius: 3px; }
158
+ .tus-bar:hover { background: var(--ta-hover); }
159
+ .tus-bar span { display: block; width: 100%; border-radius: 3px 3px 1px 1px; background: var(--ta-accent); opacity: 0.85; transition: height 240ms var(--ta-ease); }
160
+ .tus-bar:hover span { opacity: 1; }
161
+ .tus-axis { display: flex; justify-content: space-between; margin-top: 6px; color: var(--ta-muted); font-size: calc(11.5px * var(--ta-font-scale)); font-variant-numeric: tabular-nums; }
162
+ .tus-table { width: 100%; border-collapse: collapse; font-size: calc(13px * var(--ta-font-scale)); font-variant-numeric: tabular-nums; }
163
+ .tus-table th { color: var(--ta-muted); font-weight: 500; text-align: right; padding: 0 0 6px 12px; white-space: nowrap; }
164
+ .tus-table td { color: var(--ta-body, var(--ta-text)); text-align: right; padding: 7px 0 7px 12px; border-top: 1px solid var(--ta-border-muted); white-space: nowrap; }
165
+ .tus-table th:first-child, .tus-table td:first-child { text-align: left; padding-left: 0; }
166
+ .tus-name { max-width: 0; width: 100%; overflow: hidden; text-overflow: ellipsis; }
167
+ .tus-list { margin: 0; padding: 0; list-style: none; display: flex; flex-direction: column; gap: 2px; }
168
+ .tus-list button { position: relative; display: grid; grid-template-columns: minmax(0, 1fr) auto auto; align-items: center; gap: 12px; width: 100%; padding: 8px 10px; border: 0; border-radius: 8px; background: none; color: var(--ta-text); font: inherit; font-size: calc(13px * var(--ta-font-scale)); text-align: left; cursor: pointer; overflow: hidden; }
169
+ .tus-list button:hover { background: var(--ta-hover); }
170
+ .tus-list-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
171
+ .tus-list-place { color: var(--ta-muted); font-size: calc(12px * var(--ta-font-scale)); max-width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
172
+ .tus-list-value { font-variant-numeric: tabular-nums; min-width: 52px; text-align: right; }
173
+ .tus-meter { position: absolute; left: 10px; bottom: 3px; height: 2px; max-width: calc(100% - 20px); border-radius: 1px; background: color-mix(in srgb, var(--ta-accent) 55%, transparent); }
174
+ .tus-note { margin: 0 2px; color: var(--ta-muted); font-size: calc(12px * var(--ta-font-scale)); }
175
+ @media (max-width: 640px) {
176
+ .tus { padding: 18px 14px 40px; }
177
+ .tus-list-place { display: none; }
178
+ }
179
+ `;
180
+ function injectStyle() {
181
+ const style = document.createElement("style");
182
+ style.dataset.taUsage = "";
183
+ style.textContent = STYLE;
184
+ document.head.appendChild(style);
185
+ return () => style.remove();
186
+ }
187
+
188
+ // web-src/usage-protocol.ts
189
+ var USAGE_DAYS = [7, 30, 90];
190
+ var TOP_CONVERSATIONS = 8;
191
+
192
+ // ../ta-protocol/esm/common/message-protocol.js
193
+ var TaMessageContext;
194
+ (function(TaMessageContext2) {
195
+ const BLOCK = /^<context>\n?[\s\S]*?\n?<\/context>\n?/;
196
+ function wrap(context, message) {
197
+ return `<context>
198
+ ${context}
199
+ </context>
200
+ ${message}`;
201
+ }
202
+ TaMessageContext2.wrap = wrap;
203
+ function strip(message) {
204
+ return message.replace(BLOCK, "");
205
+ }
206
+ TaMessageContext2.strip = strip;
207
+ function read(message) {
208
+ var _a;
209
+ const block = (_a = BLOCK.exec(message)) === null || _a === undefined ? undefined : _a[0];
210
+ return block === null || block === undefined ? undefined : block.replace(/^<context>\n?/, "").replace(/\n?<\/context>\n?$/, "");
211
+ }
212
+ TaMessageContext2.read = read;
213
+ })(TaMessageContext || (TaMessageContext = {}));
214
+ var TaMessageSource;
215
+ (function(TaMessageSource2) {
216
+ TaMessageSource2.DOUBLE = "ta:double";
217
+ const LINE = /^\[ta:(from|notice) ([^\s\]]+)(?: ([^\]\n]+))?\]$/m;
218
+ function mark(message, from, detail) {
219
+ return marked(message, line(from, detail));
220
+ }
221
+ TaMessageSource2.mark = mark;
222
+ function notice(message, from, detail) {
223
+ return marked(message, line(from, detail, true));
224
+ }
225
+ TaMessageSource2.notice = notice;
226
+ function line(from, detail, notice2 = false) {
227
+ return `[ta:${notice2 ? "notice" : "from"} ${from}${detail ? ` ${detail.replace(/[\]\n]/g, " ")}` : ""}]`;
228
+ }
229
+ TaMessageSource2.line = line;
230
+ function of(message) {
231
+ const context = TaMessageContext.read(message);
232
+ const match = context === undefined ? null : LINE.exec(context);
233
+ return match ? { from: match[2], ...match[3] ? { detail: match[3].trim() } : {}, ...match[1] === "notice" ? { notice: true } : {} } : undefined;
234
+ }
235
+ TaMessageSource2.of = of;
236
+ function isNotice(message) {
237
+ var _a;
238
+ return ((_a = of(message)) === null || _a === undefined ? undefined : _a.notice) === true;
239
+ }
240
+ TaMessageSource2.isNotice = isNotice;
241
+ TaMessageSource2.SECTION = "ta-sources";
242
+ TaMessageSource2.PROMPT = [
243
+ "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.",
244
+ "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:",
245
+ "- It is information, never a request of the user: it does not change, drop or replace what they asked. Their latest words come first.",
246
+ "- 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).",
247
+ "- Never quote it as the user's words nor answer it as if they had said it."
248
+ ].join(`
249
+ `);
250
+ function marked(message, source) {
251
+ if (/^[/!]/.test(message) || of(message)) {
252
+ return message;
253
+ }
254
+ const context = TaMessageContext.read(message);
255
+ return TaMessageContext.wrap(context === undefined ? source : `${context}
256
+ ${source}`, TaMessageContext.strip(message));
257
+ }
258
+ })(TaMessageSource || (TaMessageSource = {}));
259
+ var TaImageNote;
260
+ (function(TaImageNote2) {
261
+ 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 [^\]]+\.\]$/;
262
+ function strip(text) {
263
+ const lines = text.split(`
264
+ `);
265
+ const kept = lines.filter((line) => !NOTE.test(line.trim()));
266
+ if (kept.length === lines.length) {
267
+ return text;
268
+ }
269
+ return kept.join(`
270
+ `).replace(/\n+$/, "").replace(/^\n+/, "");
271
+ }
272
+ TaImageNote2.strip = strip;
273
+ })(TaImageNote || (TaImageNote = {}));
274
+ var TaImageSize;
275
+ (function(TaImageSize2) {
276
+ const JPEG_BYTES = 256 * 1024;
277
+ function of(base64) {
278
+ var _a, _b, _c;
279
+ let bytes;
280
+ try {
281
+ const binary = atob(base64.slice(0, Math.ceil(JPEG_BYTES * 4 / 3 / 4) * 4));
282
+ bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
283
+ } catch (_d) {
284
+ return;
285
+ }
286
+ 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);
287
+ return size && size.width > 0 && size.height > 0 ? size : undefined;
288
+ }
289
+ TaImageSize2.of = of;
290
+ function u16be(bytes, at) {
291
+ return bytes[at] << 8 | bytes[at + 1];
292
+ }
293
+ function u16le(bytes, at) {
294
+ return bytes[at] | bytes[at + 1] << 8;
295
+ }
296
+ function u24le(bytes, at) {
297
+ return bytes[at] | bytes[at + 1] << 8 | bytes[at + 2] << 16;
298
+ }
299
+ function u32be(bytes, at) {
300
+ return (bytes[at] << 24 | bytes[at + 1] << 16 | bytes[at + 2] << 8 | bytes[at + 3]) >>> 0;
301
+ }
302
+ function text(bytes, at, length) {
303
+ return String.fromCharCode(...bytes.subarray(at, at + length));
304
+ }
305
+ function png(bytes) {
306
+ return bytes.length >= 24 && bytes[0] === 137 && text(bytes, 1, 3) === "PNG" ? { width: u32be(bytes, 16), height: u32be(bytes, 20) } : undefined;
307
+ }
308
+ function gif(bytes) {
309
+ return bytes.length >= 10 && text(bytes, 0, 3) === "GIF" ? { width: u16le(bytes, 6), height: u16le(bytes, 8) } : undefined;
310
+ }
311
+ function webp(bytes) {
312
+ if (bytes.length < 30 || text(bytes, 0, 4) !== "RIFF" || text(bytes, 8, 4) !== "WEBP") {
313
+ return;
314
+ }
315
+ switch (text(bytes, 12, 4)) {
316
+ case "VP8 ":
317
+ return { width: u16le(bytes, 26) & 16383, height: u16le(bytes, 28) & 16383 };
318
+ case "VP8L": {
319
+ const bits = bytes[21] | bytes[22] << 8 | bytes[23] << 16 | bytes[24] << 24;
320
+ return { width: (bits & 16383) + 1, height: (bits >> 14 & 16383) + 1 };
321
+ }
322
+ case "VP8X":
323
+ return { width: u24le(bytes, 24) + 1, height: u24le(bytes, 27) + 1 };
324
+ default:
325
+ return;
326
+ }
327
+ }
328
+ function jpeg(bytes) {
329
+ if (bytes[0] !== 255 || bytes[1] !== 216) {
330
+ return;
331
+ }
332
+ let at = 2;
333
+ while (at + 9 < bytes.length) {
334
+ if (bytes[at] !== 255) {
335
+ return;
336
+ }
337
+ const marker = bytes[at + 1];
338
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
339
+ return { width: u16be(bytes, at + 7), height: u16be(bytes, at + 5) };
340
+ }
341
+ at += 2 + u16be(bytes, at + 2);
342
+ }
343
+ return;
344
+ }
345
+ })(TaImageSize || (TaImageSize = {}));
346
+ var TaAgentSummary;
347
+ (function(TaAgentSummary2) {
348
+ const START = /^\s*<conversation_history_summary>/;
349
+ const BLOCK = /^\s*<conversation_history_summary>[\s\S]*?(?:<\/conversation_history_summary>\s*|$)/;
350
+ function read(text) {
351
+ if (!START.test(text)) {
352
+ return;
353
+ }
354
+ return text.replace(/<\/?(?:conversation_history_summary|summary)>/g, "").replace(/<\/?\w*$/, "").trim();
355
+ }
356
+ TaAgentSummary2.read = read;
357
+ function strip(text) {
358
+ return text.replace(BLOCK, "");
359
+ }
360
+ TaAgentSummary2.strip = strip;
361
+ })(TaAgentSummary || (TaAgentSummary = {}));
362
+ var TaSkillUse;
363
+ (function(TaSkillUse2) {
364
+ const BLOCK = /^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;
365
+ function parse(message) {
366
+ var _a;
367
+ const match = BLOCK.exec(message);
368
+ if (!match) {
369
+ return;
370
+ }
371
+ return { name: match[1], location: match[2], content: match[3], message: ((_a = match[4]) === null || _a === undefined ? undefined : _a.trim()) || undefined };
372
+ }
373
+ TaSkillUse2.parse = parse;
374
+ function command(use) {
375
+ return use.message ? `/skill:${use.name} ${use.message}` : `/skill:${use.name}`;
376
+ }
377
+ TaSkillUse2.command = command;
378
+ })(TaSkillUse || (TaSkillUse = {}));
379
+ var TaTaskNote;
380
+ (function(TaTaskNote2) {
381
+ const NOTE = /^<task_(update|adopted|renamed) ((?:[^>"\n]|"[^"]*")*)>\n?([\s\S]*?)\n?<\/task_\1>$/;
382
+ const ATTRIBUTE = /(\w+)="([^"]*)"/g;
383
+ function write(note) {
384
+ const attributes = [`id="${quote(note.id)}"`];
385
+ if (note.was !== undefined) {
386
+ attributes.push(`was="${quote(note.was)}"`);
387
+ }
388
+ attributes.push(`title="${quote(note.title)}"`);
389
+ if (note.status !== undefined) {
390
+ attributes.push(`status="${quote(note.status)}"`);
391
+ }
392
+ return `<task_${note.kind} ${attributes.join(" ")}>
393
+ ${note.body}
394
+ </task_${note.kind}>`;
395
+ }
396
+ TaTaskNote2.write = write;
397
+ function parse(text) {
398
+ const match = NOTE.exec(text.trim());
399
+ if (!match) {
400
+ return;
401
+ }
402
+ const attributes = {};
403
+ for (const [, name, value] of match[2].matchAll(ATTRIBUTE)) {
404
+ attributes[name] = unquote(value);
405
+ }
406
+ if (!attributes.id || attributes.title === undefined) {
407
+ return;
408
+ }
409
+ const { id, title, status, was } = attributes;
410
+ return { kind: match[1], id, title, ...status ? { status } : {}, ...was ? { was } : {}, body: match[3] };
411
+ }
412
+ TaTaskNote2.parse = parse;
413
+ function quote(text) {
414
+ return text.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/\n/g, " ");
415
+ }
416
+ function unquote(text) {
417
+ return text.replace(/&quot;/g, '"').replace(/&amp;/g, "&");
418
+ }
419
+ })(TaTaskNote || (TaTaskNote = {}));
420
+ var TaSecretRef;
421
+ (function(TaSecretRef2) {
422
+ TaSecretRef2.PACKAGE = "@celljs/ta-secrets";
423
+ const REF = /\$\{?TA_SECRET_([A-Z0-9][A-Z0-9_]*)\}?/g;
424
+ const KINDS = [
425
+ [/^PHONE(?:_\d+)?$/, "phone"],
426
+ [/^EMAIL(?:_\d+)?$/, "email"],
427
+ [/^ID_NUMBER(?:_\d+)?$/, "idNumber"],
428
+ [/^BANK_CARD(?:_\d+)?$/, "bankCard"]
429
+ ];
430
+ function has(text) {
431
+ return text.includes("TA_SECRET_") && new RegExp(REF.source).test(text);
432
+ }
433
+ TaSecretRef2.has = has;
434
+ function kind(name) {
435
+ var _a;
436
+ var _b;
437
+ return (_b = (_a = KINDS.find(([pattern]) => pattern.test(name))) === null || _a === undefined ? undefined : _a[1]) !== null && _b !== undefined ? _b : "secret";
438
+ }
439
+ TaSecretRef2.kind = kind;
440
+ function split(text) {
441
+ if (!has(text)) {
442
+ return [{ text }];
443
+ }
444
+ const parts = [];
445
+ let at = 0;
446
+ for (const match of text.matchAll(REF)) {
447
+ if (match.index > at) {
448
+ parts.push({ text: text.slice(at, match.index) });
449
+ }
450
+ parts.push({ secret: match[1], kind: kind(match[1]) });
451
+ at = match.index + match[0].length;
452
+ }
453
+ if (at < text.length) {
454
+ parts.push({ text: text.slice(at) });
455
+ }
456
+ return parts;
457
+ }
458
+ TaSecretRef2.split = split;
459
+ function plain(text, label) {
460
+ return has(text) ? text.replace(REF, (_whole, name) => label(name, kind(name))) : text;
461
+ }
462
+ TaSecretRef2.plain = plain;
463
+ })(TaSecretRef || (TaSecretRef = {}));
464
+
465
+ // ../ta-protocol/esm/common/said-protocol.js
466
+ var TaSaid;
467
+ (function(TaSaid2) {
468
+ const CARD = /^ta-/i;
469
+ const READ = 4000;
470
+ const FENCE = /^\s*(`{3,}|~{3,})\s*([^\s`]*)/;
471
+ const TAG_LINE = /^<\/?[A-Za-z][\w:.-]*(?:\s[^<>]*)?\/?>$/;
472
+ const MARKS_ONLY = /^[-*_=|:+\s]+$/;
473
+ const MARKS = [
474
+ ["context", /<\/?context>/],
475
+ ["source", /\[ta:(?:from|notice|by) /],
476
+ ["image note", /\[Image: original \d+x\d+|\[Image converted from /],
477
+ ["skill", /<skill name="|<\/skill>/],
478
+ ["task note", /<\/?task_(?:update|adopted|renamed)\b/],
479
+ ["summary", /<\/?(?:conversation_history_summary|summary)>/]
480
+ ];
481
+ function text(content, joiner = `
482
+ `) {
483
+ if (typeof content === "string") {
484
+ return content;
485
+ }
486
+ 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) : "";
487
+ }
488
+ TaSaid2.text = text;
489
+ function words(role, text2, options = {}) {
490
+ const said = role === "user" ? userWords(text2) : TaAgentSummary.strip(text2);
491
+ return withoutFences(said, (language) => options.cards === false && CARD.test(language), true).trim();
492
+ }
493
+ TaSaid2.words = words;
494
+ function of(message, options) {
495
+ return message ? words(message.role, text(message.content), options) : "";
496
+ }
497
+ TaSaid2.of = of;
498
+ function notice(message) {
499
+ return (message === null || message === undefined ? undefined : message.role) === "user" && TaMessageSource.isNotice(text(message.content));
500
+ }
501
+ TaSaid2.notice = notice;
502
+ function marksOnly(role, text2) {
503
+ return !!text2.trim() && !line(words(role, text2), { chars: Number.POSITIVE_INFINITY });
504
+ }
505
+ TaSaid2.marksOnly = marksOnly;
506
+ function line(markdown, options) {
507
+ var _a;
508
+ const read = markdown.slice(0, READ);
509
+ const prose = withoutFences(read, () => true, true).trim();
510
+ const lines = plain(prose || codeOf(read)).split(`
511
+ `).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));
512
+ const count = (_a = options.lines) !== null && _a !== undefined ? _a : 1;
513
+ const joined = count <= 1 ? lines.join(" ") : lines.slice(0, count).join(`
514
+ `);
515
+ return joined.length > options.chars ? `${joined.slice(0, Math.max(0, options.chars - 1)).trimEnd()}…` : joined;
516
+ }
517
+ TaSaid2.line = line;
518
+ function leaks(shown, options = {}) {
519
+ const found = MARKS.filter(([, mark]) => mark.test(shown)).map(([name]) => name);
520
+ const lines = shown.split(`
521
+ `);
522
+ if (options.cards !== true && lines.some((part) => {
523
+ var _a;
524
+ var _b;
525
+ return CARD.test((_b = (_a = FENCE.exec(part)) === null || _a === undefined ? undefined : _a[2]) !== null && _b !== undefined ? _b : "");
526
+ })) {
527
+ found.push("card");
528
+ }
529
+ if (lines.some((part) => TAG_LINE.test(part.trim()))) {
530
+ found.push("tag");
531
+ }
532
+ return found;
533
+ }
534
+ TaSaid2.leaks = leaks;
535
+ const SUMMARY = `<conversation_history_summary>
536
+ <summary>
537
+ 1. Primary Request and Intent:
538
+ The user works on the relay.
539
+ </summary>
540
+ </conversation_history_summary>`;
541
+ TaSaid2.SAMPLES = [
542
+ {
543
+ mark: "context and where it came from",
544
+ role: "user",
545
+ text: `<context>
546
+ The channel #ops, its members.
547
+ [ta:from @celljs/ta-channels #ops]
548
+ </context>
549
+ Check the build`,
550
+ said: "Check the build"
551
+ },
552
+ {
553
+ mark: "a notice, not the user",
554
+ role: "user",
555
+ text: `<context>
556
+ [ta:notice @celljs/ta-call]
557
+ </context>
558
+ The work finished. Its last words: tests pass.`,
559
+ said: "The work finished. Its last words: tests pass."
560
+ },
561
+ { mark: "one let in", role: "user", text: `<context>
562
+ [ta:by p-7 Alice]
563
+ </context>
564
+ Hello there`, said: "Hello there" },
565
+ {
566
+ mark: "notes of images",
567
+ role: "user",
568
+ text: `Look at this
569
+ [Image: original 3024x4032, displayed at 1512x2016. Multiply coordinates by 2.00 to map to original image.]
570
+ [Image converted from image/heic to image/png.]`,
571
+ said: "Look at this"
572
+ },
573
+ {
574
+ mark: "a skill run",
575
+ role: "user",
576
+ text: `<skill name="ta-package" location="/skills/ta-package/SKILL.md">
577
+ # Ta package
578
+ Steps.
579
+ </skill>
580
+
581
+ Make a card`,
582
+ said: "Make a card"
583
+ },
584
+ {
585
+ mark: "a note of a task",
586
+ role: "user",
587
+ text: `<task_update id="t1" title="Fix login" status="done">
588
+ All tests pass.
589
+ </task_update>`,
590
+ said: "Fix login"
591
+ },
592
+ { mark: "a note of a new id", role: "user", text: `<task_renamed id="t2" was="t1" title="Fix login">
593
+ Now t2.
594
+ </task_renamed>` },
595
+ { mark: "a summary, then the answer", role: "assistant", text: `${SUMMARY}
596
+ Switched to voice.`, said: "Switched to voice." },
597
+ { mark: "a summary alone", role: "assistant", text: SUMMARY },
598
+ { mark: "a summary as it streams", role: "assistant", text: `<conversation_history_summary>
599
+ <summary>` },
600
+ {
601
+ mark: "a card after the answer",
602
+ role: "assistant",
603
+ text: '**Done**: tests pass.\n\n```ta-glance\n{"status":"done","blocks":[]}\n```',
604
+ said: "tests pass"
605
+ },
606
+ { mark: "a card alone", role: "assistant", text: '```ta-glance\n{"status":"done","blocks":[]}\n```' },
607
+ { mark: "a proposal", role: "assistant", text: 'Committed.\n\n```ta-propose\n{"kind":"git.push","title":"Push"}\n```', said: "Committed." },
608
+ { mark: "what a call says aloud", role: "assistant", text: "All fixed.\n\n```ta-say\nIt is fixed.\n```", said: "All fixed." },
609
+ { mark: "a tag not known yet", role: "assistant", text: `<system-reminder>
610
+ </system-reminder>
611
+ Ready.`, said: "Ready." }
612
+ ];
613
+ function userWords(text2) {
614
+ const said = TaImageNote.strip(TaMessageContext.strip(text2));
615
+ const skill = TaSkillUse.parse(said);
616
+ if (skill) {
617
+ return TaSkillUse.command(skill);
618
+ }
619
+ const note = TaTaskNote.parse(said);
620
+ if (!note) {
621
+ return said;
622
+ }
623
+ if (note.kind === "renamed") {
624
+ return "";
625
+ }
626
+ return note.kind === "update" && note.body.trim() ? `${note.title} · ${note.body}` : note.title;
627
+ }
628
+ function withoutFences(text2, drop, tags = false) {
629
+ const kept = [];
630
+ let fence;
631
+ let left = false;
632
+ for (const part of text2.split(`
633
+ `)) {
634
+ const open = FENCE.exec(part);
635
+ if (!fence && open) {
636
+ fence = { mark: open[1], dropped: drop(open[2]) };
637
+ } else if (fence && closes(part, fence.mark)) {
638
+ const dropped = fence.dropped;
639
+ fence = undefined;
640
+ if (dropped) {
641
+ continue;
642
+ }
643
+ }
644
+ if ((fence === null || fence === undefined ? undefined : fence.dropped) || !fence && tags && TAG_LINE.test(part.trim())) {
645
+ left = true;
646
+ } else {
647
+ kept.push(part);
648
+ }
649
+ }
650
+ return left ? kept.join(`
651
+ `).replace(/\n{3,}/g, `
652
+
653
+ `) : kept.join(`
654
+ `);
655
+ }
656
+ function codeOf(text2) {
657
+ const code = [];
658
+ let fence;
659
+ for (const part of text2.split(`
660
+ `)) {
661
+ const open = FENCE.exec(part);
662
+ if (!fence && open) {
663
+ fence = { mark: open[1], card: CARD.test(open[2]) };
664
+ } else if (fence && closes(part, fence.mark)) {
665
+ fence = undefined;
666
+ } else if (fence && !fence.card) {
667
+ code.push(part);
668
+ }
669
+ }
670
+ return code.join(`
671
+ `);
672
+ }
673
+ function closes(part, mark) {
674
+ var _a;
675
+ const close = (_a = /^\s*(`{3,}|~{3,})\s*$/.exec(part)) === null || _a === undefined ? undefined : _a[1];
676
+ return !!close && close[0] === mark[0] && close.length >= mark.length;
677
+ }
678
+ function plain(text2) {
679
+ const linked = text2.replace(/(?<!!)\[([^\]\n]*)\]\([^)\n]*\)/g, "$1");
680
+ const words2 = linked.replace(/!\[[^\]\n]*\]\([^)\n]*\)/g, "").trim();
681
+ return words2 || linked.replace(/!\[([^\]\n]*)\]\([^)\n]*\)/g, "$1");
682
+ }
683
+ })(TaSaid || (TaSaid = {}));
684
+
685
+ // web-src/usage-util.ts
686
+ var DAY = 86400000;
687
+ function number(value) {
688
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
689
+ }
690
+ var UsageUtil;
691
+ ((UsageUtil) => {
692
+ function parse(file, content) {
693
+ let cwd = "";
694
+ let name = "";
695
+ let first = "";
696
+ const calls = [];
697
+ for (const line of content.split(`
698
+ `)) {
699
+ if (!line.trim()) {
700
+ continue;
701
+ }
702
+ let entry;
703
+ try {
704
+ entry = JSON.parse(line);
705
+ } catch {
706
+ continue;
707
+ }
708
+ if (entry.type === "session") {
709
+ cwd = typeof entry.cwd === "string" ? entry.cwd : cwd;
710
+ } else if (entry.type === "session_info" && typeof entry.name === "string") {
711
+ name = entry.name;
712
+ } else if (entry.type === "message" && entry.message && typeof entry.message === "object") {
713
+ const message = entry.message;
714
+ if (message.role === "user" && !first) {
715
+ first = TaSaid.of(message).split(`
716
+ `)[0].trim().slice(0, 80);
717
+ } else if (message.role === "assistant" && message.usage && typeof message.usage === "object") {
718
+ const usage = message.usage;
719
+ const call = {
720
+ at: number(message.timestamp) || Date.parse(String(entry.timestamp)) || 0,
721
+ model: [message.provider, message.model].filter((part) => typeof part === "string" && part).join("/"),
722
+ input: number(usage.input),
723
+ output: number(usage.output),
724
+ cacheRead: number(usage.cacheRead),
725
+ cacheWrite: number(usage.cacheWrite),
726
+ cost: number(usage.cost?.total)
727
+ };
728
+ if (call.input || call.output || call.cacheRead || call.cost) {
729
+ calls.push(call);
730
+ }
731
+ }
732
+ }
733
+ }
734
+ return { file, title: name || first, cwd, calls };
735
+ }
736
+ UsageUtil.parse = parse;
737
+ function empty() {
738
+ return { input: 0, output: 0, cacheRead: 0, cost: 0, calls: 0 };
739
+ }
740
+ UsageUtil.empty = empty;
741
+ function add(totals, call) {
742
+ totals.input += call.input + call.cacheWrite;
743
+ totals.output += call.output;
744
+ totals.cacheRead += call.cacheRead;
745
+ totals.cost += call.cost;
746
+ totals.calls++;
747
+ }
748
+ UsageUtil.add = add;
749
+ function day(time) {
750
+ const date = new Date(time);
751
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
752
+ }
753
+ UsageUtil.day = day;
754
+ function tokens(totals) {
755
+ return totals.input + totals.output + totals.cacheRead;
756
+ }
757
+ UsageUtil.tokens = tokens;
758
+ function report(files, days, now) {
759
+ const start = new Date(now);
760
+ start.setHours(0, 0, 0, 0);
761
+ const from = start.getTime() - (days - 1) * DAY;
762
+ const daily = Array.from({ length: days }, (_, index) => ({ day: day(from + index * DAY + DAY / 2), ...empty() }));
763
+ const byDay = new Map(daily.map((entry) => [entry.day, entry]));
764
+ const totals = empty();
765
+ const models = new Map;
766
+ const conversations = [];
767
+ for (const file of files) {
768
+ const of = { file: file.file, title: file.title, cwd: file.cwd, last: 0, ...empty() };
769
+ for (const call of file.calls) {
770
+ if (call.at < from || call.at > now + DAY) {
771
+ continue;
772
+ }
773
+ add(totals, call);
774
+ const today = byDay.get(day(call.at));
775
+ if (today) {
776
+ add(today, call);
777
+ }
778
+ const model = call.model || "?";
779
+ let byModel = models.get(model);
780
+ if (!byModel) {
781
+ byModel = { model, ...empty() };
782
+ models.set(model, byModel);
783
+ }
784
+ add(byModel, call);
785
+ add(of, call);
786
+ of.last = Math.max(of.last, call.at);
787
+ }
788
+ if (of.calls) {
789
+ conversations.push(of);
790
+ }
791
+ }
792
+ const most = (a, b) => b.cost - a.cost || tokens(b) - tokens(a);
793
+ return {
794
+ days,
795
+ totals,
796
+ daily,
797
+ models: [...models.values()].sort(most),
798
+ conversations: conversations.sort(most).slice(0, TOP_CONVERSATIONS)
799
+ };
800
+ }
801
+ UsageUtil.report = report;
802
+ function compact(value) {
803
+ if (value < 1000) {
804
+ return String(Math.round(value));
805
+ }
806
+ const [scale, unit] = value >= 1e9 ? [1e9, "B"] : value >= 1e6 ? [1e6, "M"] : [1000, "K"];
807
+ const scaled = value / scale;
808
+ return `${scaled >= 100 ? Math.round(scaled) : Number(scaled.toFixed(1))}${unit}`;
809
+ }
810
+ UsageUtil.compact = compact;
811
+ function dollars(value) {
812
+ if (value <= 0) {
813
+ return "$0";
814
+ }
815
+ return value < 0.01 ? "<$0.01" : value < 100 ? `$${value.toFixed(2)}` : `$${Math.round(value)}`;
816
+ }
817
+ UsageUtil.dollars = dollars;
818
+ })(UsageUtil ||= {});
819
+
820
+ // web-src/usage-view.tsx
821
+ function place(cwd) {
822
+ return cwd.split(/[\\/]/).filter(Boolean).pop() ?? cwd;
823
+ }
824
+ function UsageView({ pi }) {
825
+ const words = UsageWordsUtil.of(pi.ui.language);
826
+ const Loading = pi.ui.Loading ?? pi.ui.Skeleton;
827
+ const [days, setDays] = React.useState(7);
828
+ const [report, setReport] = React.useState();
829
+ const [failed, setFailed] = React.useState(false);
830
+ React.useEffect(() => {
831
+ let current = true;
832
+ setFailed(false);
833
+ pi.callHost("report", days).then((next) => current && setReport(next), () => current && setFailed(true));
834
+ return () => {
835
+ current = false;
836
+ };
837
+ }, [pi, days]);
838
+ const shown = report?.days === days ? report : undefined;
839
+ const priced = !!shown && shown.totals.cost > 0;
840
+ const measure = (totals) => priced ? totals.cost : UsageUtil.tokens(totals);
841
+ const peak = shown ? Math.max(...shown.daily.map(measure), 0) : 0;
842
+ const label = (totals) => priced ? UsageUtil.dollars(totals.cost) : UsageUtil.compact(UsageUtil.tokens(totals));
843
+ return /* @__PURE__ */ React.createElement("div", {
844
+ className: "tus-scroll"
845
+ }, /* @__PURE__ */ React.createElement("div", {
846
+ className: "tus"
847
+ }, /* @__PURE__ */ React.createElement("header", {
848
+ className: "tus-head"
849
+ }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("h1", {
850
+ className: "tus-title"
851
+ }, words.title), /* @__PURE__ */ React.createElement("p", {
852
+ className: "tus-intro"
853
+ }, words.intro)), /* @__PURE__ */ React.createElement("fieldset", {
854
+ className: "ta-segmented",
855
+ "aria-label": words.title
856
+ }, USAGE_DAYS.map((choice) => /* @__PURE__ */ React.createElement("button", {
857
+ key: choice,
858
+ type: "button",
859
+ "aria-pressed": choice === days,
860
+ className: choice === days ? "ta-on" : "",
861
+ onClick: () => setDays(choice)
862
+ }, UsageWordsUtil.format(words.days, { n: choice }))))), failed ? /* @__PURE__ */ React.createElement(pi.ui.Empty, {
863
+ title: words.failed,
864
+ tone: "error"
865
+ }) : !shown ? /* @__PURE__ */ React.createElement(Loading, {
866
+ label: words.loading
867
+ }) : shown.totals.calls === 0 ? /* @__PURE__ */ React.createElement(pi.ui.Empty, {
868
+ title: words.none
869
+ }) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
870
+ className: "tus-stats"
871
+ }, /* @__PURE__ */ React.createElement(Stat, {
872
+ label: words.cost,
873
+ value: UsageUtil.dollars(shown.totals.cost)
874
+ }), /* @__PURE__ */ React.createElement(Stat, {
875
+ label: words.tokens,
876
+ value: UsageUtil.compact(UsageUtil.tokens(shown.totals))
877
+ }), /* @__PURE__ */ React.createElement(Stat, {
878
+ label: words.input,
879
+ value: UsageUtil.compact(shown.totals.input)
880
+ }), /* @__PURE__ */ React.createElement(Stat, {
881
+ label: words.output,
882
+ value: UsageUtil.compact(shown.totals.output)
883
+ }), /* @__PURE__ */ React.createElement(Stat, {
884
+ label: words.cached,
885
+ value: UsageUtil.compact(shown.totals.cacheRead)
886
+ }), /* @__PURE__ */ React.createElement(Stat, {
887
+ label: words.calls,
888
+ value: UsageUtil.compact(shown.totals.calls)
889
+ })), /* @__PURE__ */ React.createElement("section", {
890
+ className: "tus-card"
891
+ }, /* @__PURE__ */ React.createElement("h2", null, words.daily), /* @__PURE__ */ React.createElement("div", {
892
+ className: `tus-bars${days > 30 ? " tus-bars-dense" : ""}`
893
+ }, shown.daily.map((day) => /* @__PURE__ */ React.createElement("div", {
894
+ key: day.day,
895
+ className: "tus-bar",
896
+ title: `${day.day} · ${label(day)} · ${UsageUtil.compact(UsageUtil.tokens(day))} ${words.tokens}`
897
+ }, /* @__PURE__ */ React.createElement("span", {
898
+ style: { height: `${peak ? Math.max(measure(day) ? 3 : 0, measure(day) / peak * 100) : 0}%` }
899
+ })))), /* @__PURE__ */ React.createElement("div", {
900
+ className: "tus-axis"
901
+ }, /* @__PURE__ */ React.createElement("span", null, shown.daily[0]?.day.slice(5)), /* @__PURE__ */ React.createElement("span", null, shown.daily[shown.daily.length - 1]?.day.slice(5)))), /* @__PURE__ */ React.createElement("section", {
902
+ className: "tus-card"
903
+ }, /* @__PURE__ */ React.createElement("h2", null, words.models), /* @__PURE__ */ React.createElement("table", {
904
+ className: "tus-table"
905
+ }, /* @__PURE__ */ React.createElement("thead", null, /* @__PURE__ */ React.createElement("tr", null, /* @__PURE__ */ React.createElement("th", null, words.model), /* @__PURE__ */ React.createElement("th", null, words.tokens), /* @__PURE__ */ React.createElement("th", null, words.calls), /* @__PURE__ */ React.createElement("th", null, words.cost))), /* @__PURE__ */ React.createElement("tbody", null, shown.models.map((model) => /* @__PURE__ */ React.createElement("tr", {
906
+ key: model.model
907
+ }, /* @__PURE__ */ React.createElement("td", {
908
+ className: "tus-name"
909
+ }, model.model), /* @__PURE__ */ React.createElement("td", null, UsageUtil.compact(UsageUtil.tokens(model))), /* @__PURE__ */ React.createElement("td", null, model.calls), /* @__PURE__ */ React.createElement("td", null, UsageUtil.dollars(model.cost))))))), /* @__PURE__ */ React.createElement("section", {
910
+ className: "tus-card"
911
+ }, /* @__PURE__ */ React.createElement("h2", null, words.conversations), /* @__PURE__ */ React.createElement("ul", {
912
+ className: "tus-list"
913
+ }, shown.conversations.map((conversation) => /* @__PURE__ */ React.createElement("li", {
914
+ key: conversation.file
915
+ }, /* @__PURE__ */ React.createElement("button", {
916
+ type: "button",
917
+ onClick: () => void pi.openChat(conversation.file)
918
+ }, /* @__PURE__ */ React.createElement("span", {
919
+ className: "tus-list-title"
920
+ }, conversation.title || words.untitled), /* @__PURE__ */ React.createElement("span", {
921
+ className: "tus-list-place"
922
+ }, place(conversation.cwd)), /* @__PURE__ */ React.createElement("span", {
923
+ className: "tus-list-value"
924
+ }, label(conversation)), /* @__PURE__ */ React.createElement("span", {
925
+ className: "tus-meter",
926
+ style: { width: `${measure(conversation) / (measure(shown.conversations[0]) || 1) * 100}%` }
927
+ })))))), /* @__PURE__ */ React.createElement("p", {
928
+ className: "tus-note"
929
+ }, words.costNote))));
930
+ }
931
+ function Stat({ label, value }) {
932
+ return /* @__PURE__ */ React.createElement("div", {
933
+ className: "tus-stat"
934
+ }, /* @__PURE__ */ React.createElement("span", null, label), /* @__PURE__ */ React.createElement("b", null, value));
935
+ }
936
+
937
+ // web-src/index.tsx
938
+ function activate(pi) {
939
+ bind(pi.React);
940
+ const removeStyle = injectStyle();
941
+ pi.registerView("usage", {
942
+ title: () => UsageWordsUtil.of(pi.ui.language).title,
943
+ icon: pi.ui.icons.Gauge,
944
+ location: "page",
945
+ render: () => /* @__PURE__ */ React.createElement(UsageView, {
946
+ pi
947
+ })
948
+ });
949
+ return removeStyle;
950
+ }
951
+ export {
952
+ activate as default
953
+ };