@celljs/ta-offer 0.0.0-stage → 4.39.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,3123 @@
1
+ // ../ta-protocol/esm/common/http-protocol.js
2
+ var TA_WEBHOOK_MAX_BYTES = 256 * 1024;
3
+ var TA_RELAY_HTTP_PATH = "/a/";
4
+ var TA_HTTP_MAX_BYTES = 4 * 1024 * 1024;
5
+ var TaHttpUtil;
6
+ (function(TaHttpUtil2) {
7
+ function base(relay, host, packageName) {
8
+ return `${relay.replace(/\/+$/, "")}${TA_RELAY_HTTP_PATH}${host}/${packageName.slice(packageName.lastIndexOf("/") + 1)}`;
9
+ }
10
+ TaHttpUtil2.base = base;
11
+ function json(status, value, headers = {}) {
12
+ return { status, headers: { "content-type": "application/json; charset=utf-8", ...headers }, body: JSON.stringify(value) };
13
+ }
14
+ TaHttpUtil2.json = json;
15
+ })(TaHttpUtil || (TaHttpUtil = {}));
16
+
17
+ // ../ta-protocol/esm/common/message-protocol.js
18
+ var TaMessageContext;
19
+ (function(TaMessageContext2) {
20
+ const BLOCK = /^<context>\n?[\s\S]*?\n?<\/context>\n?/;
21
+ function wrap(context, message) {
22
+ return `<context>
23
+ ${context}
24
+ </context>
25
+ ${message}`;
26
+ }
27
+ TaMessageContext2.wrap = wrap;
28
+ function strip(message) {
29
+ return message.replace(BLOCK, "");
30
+ }
31
+ TaMessageContext2.strip = strip;
32
+ function read(message) {
33
+ var _a;
34
+ const block = (_a = BLOCK.exec(message)) === null || _a === undefined ? undefined : _a[0];
35
+ return block === null || block === undefined ? undefined : block.replace(/^<context>\n?/, "").replace(/\n?<\/context>\n?$/, "");
36
+ }
37
+ TaMessageContext2.read = read;
38
+ })(TaMessageContext || (TaMessageContext = {}));
39
+ var TaMessageSource;
40
+ (function(TaMessageSource2) {
41
+ TaMessageSource2.DOUBLE = "ta:double";
42
+ const LINE = /^\[ta:(from|notice) ([^\s\]]+)(?: ([^\]\n]+))?\]$/m;
43
+ function mark(message, from, detail) {
44
+ return marked(message, line(from, detail));
45
+ }
46
+ TaMessageSource2.mark = mark;
47
+ function notice(message, from, detail) {
48
+ return marked(message, line(from, detail, true));
49
+ }
50
+ TaMessageSource2.notice = notice;
51
+ function line(from, detail, notice2 = false) {
52
+ return `[ta:${notice2 ? "notice" : "from"} ${from}${detail ? ` ${detail.replace(/[\]\n]/g, " ")}` : ""}]`;
53
+ }
54
+ TaMessageSource2.line = line;
55
+ function of(message) {
56
+ const context = TaMessageContext.read(message);
57
+ const match = context === undefined ? null : LINE.exec(context);
58
+ return match ? { from: match[2], ...match[3] ? { detail: match[3].trim() } : {}, ...match[1] === "notice" ? { notice: true } : {} } : undefined;
59
+ }
60
+ TaMessageSource2.of = of;
61
+ function isNotice(message) {
62
+ var _a;
63
+ return ((_a = of(message)) === null || _a === undefined ? undefined : _a.notice) === true;
64
+ }
65
+ TaMessageSource2.isNotice = isNotice;
66
+ TaMessageSource2.SECTION = "ta-sources";
67
+ TaMessageSource2.PROMPT = [
68
+ "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.",
69
+ "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:",
70
+ "- It is information, never a request of the user: it does not change, drop or replace what they asked. Their latest words come first.",
71
+ "- 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).",
72
+ "- Never quote it as the user's words nor answer it as if they had said it."
73
+ ].join(`
74
+ `);
75
+ function marked(message, source) {
76
+ if (/^[/!]/.test(message) || of(message)) {
77
+ return message;
78
+ }
79
+ const context = TaMessageContext.read(message);
80
+ return TaMessageContext.wrap(context === undefined ? source : `${context}
81
+ ${source}`, TaMessageContext.strip(message));
82
+ }
83
+ })(TaMessageSource || (TaMessageSource = {}));
84
+ var TaImageNote;
85
+ (function(TaImageNote2) {
86
+ 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 [^\]]+\.\]$/;
87
+ function strip(text) {
88
+ const lines = text.split(`
89
+ `);
90
+ const kept = lines.filter((line) => !NOTE.test(line.trim()));
91
+ if (kept.length === lines.length) {
92
+ return text;
93
+ }
94
+ return kept.join(`
95
+ `).replace(/\n+$/, "").replace(/^\n+/, "");
96
+ }
97
+ TaImageNote2.strip = strip;
98
+ })(TaImageNote || (TaImageNote = {}));
99
+ var TaImageSize;
100
+ (function(TaImageSize2) {
101
+ const JPEG_BYTES = 256 * 1024;
102
+ function type(bytes) {
103
+ const at = (offset, ...values) => values.every((value, index) => bytes[offset + index] === value);
104
+ return at(0, 255, 216, 255) ? "image/jpeg" : at(0, 137, 80, 78, 71) ? "image/png" : at(0, 71, 73, 70, 56) ? "image/gif" : at(0, 82, 73, 70, 70) && at(8, 87, 69, 66, 80) ? "image/webp" : undefined;
105
+ }
106
+ TaImageSize2.type = type;
107
+ function of(base64) {
108
+ var _a, _b, _c;
109
+ let bytes;
110
+ try {
111
+ const binary = atob(base64.slice(0, Math.ceil(JPEG_BYTES * 4 / 3 / 4) * 4));
112
+ bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
113
+ } catch (_d) {
114
+ return;
115
+ }
116
+ 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);
117
+ return size && size.width > 0 && size.height > 0 ? size : undefined;
118
+ }
119
+ TaImageSize2.of = of;
120
+ function u16be(bytes, at) {
121
+ return bytes[at] << 8 | bytes[at + 1];
122
+ }
123
+ function u16le(bytes, at) {
124
+ return bytes[at] | bytes[at + 1] << 8;
125
+ }
126
+ function u24le(bytes, at) {
127
+ return bytes[at] | bytes[at + 1] << 8 | bytes[at + 2] << 16;
128
+ }
129
+ function u32be(bytes, at) {
130
+ return (bytes[at] << 24 | bytes[at + 1] << 16 | bytes[at + 2] << 8 | bytes[at + 3]) >>> 0;
131
+ }
132
+ function text(bytes, at, length) {
133
+ return String.fromCharCode(...bytes.subarray(at, at + length));
134
+ }
135
+ function png(bytes) {
136
+ return bytes.length >= 24 && bytes[0] === 137 && text(bytes, 1, 3) === "PNG" ? { width: u32be(bytes, 16), height: u32be(bytes, 20) } : undefined;
137
+ }
138
+ function gif(bytes) {
139
+ return bytes.length >= 10 && text(bytes, 0, 3) === "GIF" ? { width: u16le(bytes, 6), height: u16le(bytes, 8) } : undefined;
140
+ }
141
+ function webp(bytes) {
142
+ if (bytes.length < 30 || text(bytes, 0, 4) !== "RIFF" || text(bytes, 8, 4) !== "WEBP") {
143
+ return;
144
+ }
145
+ switch (text(bytes, 12, 4)) {
146
+ case "VP8 ":
147
+ return { width: u16le(bytes, 26) & 16383, height: u16le(bytes, 28) & 16383 };
148
+ case "VP8L": {
149
+ const bits = bytes[21] | bytes[22] << 8 | bytes[23] << 16 | bytes[24] << 24;
150
+ return { width: (bits & 16383) + 1, height: (bits >> 14 & 16383) + 1 };
151
+ }
152
+ case "VP8X":
153
+ return { width: u24le(bytes, 24) + 1, height: u24le(bytes, 27) + 1 };
154
+ default:
155
+ return;
156
+ }
157
+ }
158
+ function jpeg(bytes) {
159
+ if (bytes[0] !== 255 || bytes[1] !== 216) {
160
+ return;
161
+ }
162
+ let at = 2;
163
+ while (at + 9 < bytes.length) {
164
+ if (bytes[at] !== 255) {
165
+ return;
166
+ }
167
+ const marker = bytes[at + 1];
168
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
169
+ return { width: u16be(bytes, at + 7), height: u16be(bytes, at + 5) };
170
+ }
171
+ at += 2 + u16be(bytes, at + 2);
172
+ }
173
+ return;
174
+ }
175
+ })(TaImageSize || (TaImageSize = {}));
176
+ var TaAgentSummary;
177
+ (function(TaAgentSummary2) {
178
+ const START = /^\s*<conversation_history_summary>/;
179
+ const BLOCK = /^\s*<conversation_history_summary>[\s\S]*?(?:<\/conversation_history_summary>\s*|$)/;
180
+ function read(text) {
181
+ if (!START.test(text)) {
182
+ return;
183
+ }
184
+ return text.replace(/<\/?(?:conversation_history_summary|summary)>/g, "").replace(/<\/?\w*$/, "").trim();
185
+ }
186
+ TaAgentSummary2.read = read;
187
+ function strip(text) {
188
+ return text.replace(BLOCK, "");
189
+ }
190
+ TaAgentSummary2.strip = strip;
191
+ })(TaAgentSummary || (TaAgentSummary = {}));
192
+ var TaPictureNote;
193
+ (function(TaPictureNote2) {
194
+ TaPictureNote2.OPEN = "<pictures>";
195
+ TaPictureNote2.CLOSE = "</pictures>";
196
+ const BLOCK = /[ \t]*<pictures>([\s\S]*?)(?:<\/pictures>|$)|<p(?:i(?:c(?:t(?:u(?:r(?:es?)?)?)?)?)?)?$/gi;
197
+ const ROW = /(?:^|\s)[-*]?\s*p(\d+)\s*[::]\s*/gi;
198
+ function take(text) {
199
+ const told = new Map;
200
+ if (!/<p/i.test(text)) {
201
+ return { said: text, told };
202
+ }
203
+ const said = text.replace(BLOCK, (_all, body) => {
204
+ const rows = [...(body !== null && body !== undefined ? body : "").matchAll(ROW)];
205
+ rows.forEach((row, index) => {
206
+ var _a;
207
+ var _b, _c;
208
+ const end = (_b = (_a = rows[index + 1]) === null || _a === undefined ? undefined : _a.index) !== null && _b !== undefined ? _b : body === null || body === undefined ? undefined : body.length;
209
+ const what = body === null || body === undefined ? undefined : body.slice(((_c = row.index) !== null && _c !== undefined ? _c : 0) + row[0].length, end).trim();
210
+ if (what) {
211
+ told.set(Number(row[1]), what);
212
+ }
213
+ });
214
+ return "";
215
+ });
216
+ return { said: said === text ? text : said.replace(/\n{3,}/g, `
217
+
218
+ `).trim(), told };
219
+ }
220
+ TaPictureNote2.take = take;
221
+ function strip(text) {
222
+ return take(text).said;
223
+ }
224
+ TaPictureNote2.strip = strip;
225
+ })(TaPictureNote || (TaPictureNote = {}));
226
+ var TaSkillUse;
227
+ (function(TaSkillUse2) {
228
+ const BLOCK = /^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;
229
+ function parse(message) {
230
+ var _a;
231
+ const match = BLOCK.exec(message);
232
+ if (!match) {
233
+ return;
234
+ }
235
+ return { name: match[1], location: match[2], content: match[3], message: ((_a = match[4]) === null || _a === undefined ? undefined : _a.trim()) || undefined };
236
+ }
237
+ TaSkillUse2.parse = parse;
238
+ function command(use) {
239
+ return use.message ? `/skill:${use.name} ${use.message}` : `/skill:${use.name}`;
240
+ }
241
+ TaSkillUse2.command = command;
242
+ })(TaSkillUse || (TaSkillUse = {}));
243
+ var TaTaskNote;
244
+ (function(TaTaskNote2) {
245
+ const NOTE = /^<task_(update|adopted|renamed) ((?:[^>"\n]|"[^"]*")*)>\n?([\s\S]*?)\n?<\/task_\1>$/;
246
+ const ATTRIBUTE = /(\w+)="([^"]*)"/g;
247
+ function write(note) {
248
+ const attributes = [`id="${quote(note.id)}"`];
249
+ if (note.was !== undefined) {
250
+ attributes.push(`was="${quote(note.was)}"`);
251
+ }
252
+ attributes.push(`title="${quote(note.title)}"`);
253
+ if (note.status !== undefined) {
254
+ attributes.push(`status="${quote(note.status)}"`);
255
+ }
256
+ return `<task_${note.kind} ${attributes.join(" ")}>
257
+ ${note.body}
258
+ </task_${note.kind}>`;
259
+ }
260
+ TaTaskNote2.write = write;
261
+ function parse(text) {
262
+ const match = NOTE.exec(text.trim());
263
+ if (!match) {
264
+ return;
265
+ }
266
+ const attributes = {};
267
+ for (const [, name, value] of match[2].matchAll(ATTRIBUTE)) {
268
+ attributes[name] = unquote(value);
269
+ }
270
+ if (!attributes.id || attributes.title === undefined) {
271
+ return;
272
+ }
273
+ const { id, title, status, was } = attributes;
274
+ return { kind: match[1], id, title, ...status ? { status } : {}, ...was ? { was } : {}, body: match[3] };
275
+ }
276
+ TaTaskNote2.parse = parse;
277
+ function quote(text) {
278
+ return text.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/\n/g, " ");
279
+ }
280
+ function unquote(text) {
281
+ return text.replace(/&quot;/g, '"').replace(/&amp;/g, "&");
282
+ }
283
+ })(TaTaskNote || (TaTaskNote = {}));
284
+ var TaSecretRef;
285
+ (function(TaSecretRef2) {
286
+ TaSecretRef2.PACKAGE = "@celljs/ta-secrets";
287
+ const REF = /\$\{?TA_SECRET_([A-Z0-9][A-Z0-9_]*)\}?/g;
288
+ const KINDS = [
289
+ [/^PHONE(?:_\d+)?$/, "phone"],
290
+ [/^EMAIL(?:_\d+)?$/, "email"],
291
+ [/^ID_NUMBER(?:_\d+)?$/, "idNumber"],
292
+ [/^BANK_CARD(?:_\d+)?$/, "bankCard"]
293
+ ];
294
+ function has(text) {
295
+ return text.includes("TA_SECRET_") && new RegExp(REF.source).test(text);
296
+ }
297
+ TaSecretRef2.has = has;
298
+ function kind(name) {
299
+ var _a;
300
+ var _b;
301
+ return (_b = (_a = KINDS.find(([pattern]) => pattern.test(name))) === null || _a === undefined ? undefined : _a[1]) !== null && _b !== undefined ? _b : "secret";
302
+ }
303
+ TaSecretRef2.kind = kind;
304
+ function split(text) {
305
+ if (!has(text)) {
306
+ return [{ text }];
307
+ }
308
+ const parts = [];
309
+ let at = 0;
310
+ for (const match of text.matchAll(REF)) {
311
+ if (match.index > at) {
312
+ parts.push({ text: text.slice(at, match.index) });
313
+ }
314
+ parts.push({ secret: match[1], kind: kind(match[1]) });
315
+ at = match.index + match[0].length;
316
+ }
317
+ if (at < text.length) {
318
+ parts.push({ text: text.slice(at) });
319
+ }
320
+ return parts;
321
+ }
322
+ TaSecretRef2.split = split;
323
+ function plain(text, label) {
324
+ return has(text) ? text.replace(REF, (_whole, name) => label(name, kind(name))) : text;
325
+ }
326
+ TaSecretRef2.plain = plain;
327
+ })(TaSecretRef || (TaSecretRef = {}));
328
+
329
+ // web-src/offer-keys.ts
330
+ import { createHash, randomBytes } from "node:crypto";
331
+ var KEY_PREFIX = "ta_sk_";
332
+ var TOKEN_PREFIX = { access: "ta_at_", refresh: "ta_rt_", code: "ta_ac_" };
333
+ var OfferKeys;
334
+ ((OfferKeys) => {
335
+ function make() {
336
+ const key = `${KEY_PREFIX}${randomBytes(32).toString("base64url")}`;
337
+ return { key, hash: hashOf(key), hint: `${key.slice(0, KEY_PREFIX.length + 4)}…${key.slice(-4)}` };
338
+ }
339
+ OfferKeys.make = make;
340
+ function secret(prefix) {
341
+ const value = `${prefix}${randomBytes(32).toString("base64url")}`;
342
+ return { value, hash: hashOf(value) };
343
+ }
344
+ OfferKeys.secret = secret;
345
+ function hashOf(key) {
346
+ return createHash("sha256").update(key).digest("hex");
347
+ }
348
+ OfferKeys.hashOf = hashOf;
349
+ function bearer(headers) {
350
+ const match = /^Bearer\s+(\S+)\s*$/i.exec(headers.authorization ?? "");
351
+ const key = match?.[1];
352
+ return key && (key.startsWith(KEY_PREFIX) || key.startsWith(TOKEN_PREFIX.access)) && key.length <= 128 ? key : undefined;
353
+ }
354
+ OfferKeys.bearer = bearer;
355
+ function conversation() {
356
+ return `c${randomBytes(12).toString("hex")}`;
357
+ }
358
+ OfferKeys.conversation = conversation;
359
+ })(OfferKeys ||= {});
360
+
361
+ // ../ta-protocol/esm/common/language.js
362
+ var TaLanguageUtil;
363
+ (function(TaLanguageUtil2) {
364
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
365
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
366
+ function of(tag) {
367
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
368
+ if (/^zh(\b|-)/.test(said)) {
369
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
370
+ }
371
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
372
+ }
373
+ TaLanguageUtil2.of = of;
374
+ function server(env = typeof process === "undefined" ? {} : process.env) {
375
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
376
+ }
377
+ TaLanguageUtil2.server = server;
378
+ function pick(language, words) {
379
+ return words[of(language)];
380
+ }
381
+ TaLanguageUtil2.pick = pick;
382
+ function say(words) {
383
+ return words[server()];
384
+ }
385
+ TaLanguageUtil2.say = say;
386
+ function chinese(language) {
387
+ return of(language).startsWith("zh");
388
+ }
389
+ TaLanguageUtil2.chinese = chinese;
390
+ function cjk(language) {
391
+ return of(language) !== "en-US";
392
+ }
393
+ TaLanguageUtil2.cjk = cjk;
394
+ function list(language, items) {
395
+ return items.join(cjk(language) ? "、" : ", ");
396
+ }
397
+ TaLanguageUtil2.list = list;
398
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
399
+
400
+ // web-src/offer-texts.ts
401
+ function yuan(fen) {
402
+ return (fen / 100).toFixed(fen % 100 === 0 ? 0 : 2);
403
+ }
404
+ var OfferTexts;
405
+ ((OfferTexts) => {
406
+ function paidTitle() {
407
+ return TaLanguageUtil.say({ "zh-CN": "有人要付款开通", "zh-TW": "有人要付款開通", "en-US": "Someone is paying", "ja-JP": "支払いの申し出があります" });
408
+ }
409
+ OfferTexts.paidTitle = paidTitle;
410
+ function paid(name, offer, amount, code) {
411
+ const price = yuan(amount);
412
+ return TaLanguageUtil.say({
413
+ "zh-CN": `${name} 要付 ¥${price} 开通${offer},付款备注核对码 ${code}。收到钱后再确认开通。`,
414
+ "zh-TW": `${name} 要付 ¥${price} 開通${offer},付款備註核對碼 ${code}。收到錢後再確認開通。`,
415
+ "en-US": `${name} is paying ¥${price} for ${offer}, with the code ${code} in the note. Confirm once it came in.`,
416
+ "ja-JP": `${name} さんが ¥${price} で${offer}を開通しようとしています。備考の照合コードは ${code}。入金を確認してから開通してください。`
417
+ });
418
+ }
419
+ OfferTexts.paid = paid;
420
+ function blocked(block) {
421
+ switch (block) {
422
+ case "daily":
423
+ return TaLanguageUtil.say({
424
+ "zh-CN": "今天的额度用完了,明天 0 点恢复。也可以在“开放给我的”里换个方案。",
425
+ "zh-TW": "今天的額度用完了,明天 0 點恢復。也可以在「開放給我的」裡換個方案。",
426
+ "en-US": "Today’s allowance is used up; it comes back at midnight. Or pick another plan in Opened to me.",
427
+ "ja-JP": "今日の利用枠を使い切りました。午前 0 時に戻ります。「公開されたもの」でプランを変えることもできます。"
428
+ });
429
+ case "paused":
430
+ case "closed":
431
+ return TaLanguageUtil.say({
432
+ "zh-CN": "提供者暂停了这个智能体,恢复后就能接着用。",
433
+ "zh-TW": "提供者暫停了這個智慧體,恢復後就能接著用。",
434
+ "en-US": "Its owner paused this agent for now; you can go on once they open it again.",
435
+ "ja-JP": "提供者がこのエージェントを一時停止しました。再開されれば続けられます。"
436
+ });
437
+ default:
438
+ return TaLanguageUtil.say({
439
+ "zh-CN": "额度用完了。在“开放给我的”里选个方案,付款后提供者确认就能接着用。",
440
+ "zh-TW": "額度用完了。在「開放給我的」裡選個方案,付款後提供者確認就能接著用。",
441
+ "en-US": "Your allowance is used up. Pick a plan in Opened to me; once its owner confirms your payment, go on.",
442
+ "ja-JP": "利用枠を使い切りました。「公開されたもの」でプランを選び、支払いが確認されれば続けられます。"
443
+ });
444
+ }
445
+ }
446
+ OfferTexts.blocked = blocked;
447
+ })(OfferTexts ||= {});
448
+
449
+ // web-src/offer-calls.ts
450
+ var RUNNING_MAX = 4;
451
+ var CALLS_MAX = 200;
452
+ var SEEN_MS = 60000;
453
+ var refusal = (status, code, message, headers) => ({
454
+ refused: true,
455
+ status,
456
+ code,
457
+ message,
458
+ ...headers ? { headers } : {}
459
+ });
460
+
461
+ class OfferCalls {
462
+ ctx;
463
+ constructor(ctx) {
464
+ this.ctx = ctx;
465
+ }
466
+ static refusal = refusal;
467
+ caller(headers, door, now = Date.now()) {
468
+ const token = OfferKeys.bearer(headers);
469
+ const hash = token && OfferKeys.hashOf(token);
470
+ let user;
471
+ let by;
472
+ for (const one of hash ? this.ctx.data.users : []) {
473
+ by = token?.startsWith(KEY_PREFIX) ? one.keys?.find((key) => key.hash === hash) : door === "mcp" && token?.startsWith(TOKEN_PREFIX.access) ? one.clients?.find((client) => client.access === hash && client.accessUntil > now) : undefined;
474
+ if (by) {
475
+ user = one;
476
+ break;
477
+ }
478
+ }
479
+ const offer = user && this.ctx.data.offers.find((one) => one.id === user.offer);
480
+ const member = user && this.ctx.links.who(user.member);
481
+ if (!user || !by || !offer || !member) {
482
+ return refusal(401, "invalid_api_key", door === "api" ? "Incorrect API key provided." : "The key or token is not valid; sign in again.");
483
+ }
484
+ if (offer.api === false) {
485
+ return refusal(403, "api_off", "The owner turned off the API of this agent.");
486
+ }
487
+ if (!by.lastAt || now - by.lastAt > SEEN_MS) {
488
+ by.lastAt = now;
489
+ this.ctx.commit();
490
+ }
491
+ return { user, offer, member, by };
492
+ }
493
+ async ask({ user, offer, member }, input, signal) {
494
+ const state = this.ctx.state(user);
495
+ if (state.block !== "none") {
496
+ return refusal(429, "insufficient_quota", OfferTexts.blocked(state.block));
497
+ }
498
+ if (this.ctx.turns.running(user.member) >= RUNNING_MAX) {
499
+ return refusal(429, "rate_limit_exceeded", `At most ${RUNNING_MAX} requests at once; wait for one to end.`, { "retry-after": "5" });
500
+ }
501
+ const calls = user.calls ?? {};
502
+ user.calls = calls;
503
+ const held = input.conversation ? calls[input.conversation] : undefined;
504
+ if (input.conversation && (!held || !user.sessions.includes(held))) {
505
+ return refusal(404, "conversation_not_found", "No such conversation.");
506
+ }
507
+ if (held && this.ctx.turns.busy(held)) {
508
+ return refusal(409, "conversation_busy", "This conversation is answering another message; send it once that ends.");
509
+ }
510
+ let conversation;
511
+ let file;
512
+ let sessionId;
513
+ if (input.conversation && held) {
514
+ conversation = input.conversation;
515
+ file = held;
516
+ sessionId = await this.ctx.conversations.resume(member, file);
517
+ } else {
518
+ const agent = await this.ctx.conversations.agent(offer.agent);
519
+ if (!agent) {
520
+ return refusal(503, "unavailable", OfferTexts.blocked("closed"));
521
+ }
522
+ const started = await this.ctx.conversations.start(member, offer, agent);
523
+ if (!started.sessionFile) {
524
+ return refusal(500, "server_error", "The conversation could not be started.");
525
+ }
526
+ file = started.sessionFile;
527
+ sessionId = started.sessionId;
528
+ conversation = OfferKeys.conversation();
529
+ if (!user.sessions.includes(file)) {
530
+ user.sessions = [...user.sessions, file];
531
+ }
532
+ calls[conversation] = file;
533
+ const ids = Object.keys(calls);
534
+ for (const old of ids.slice(0, Math.max(0, ids.length - CALLS_MAX))) {
535
+ delete calls[old];
536
+ }
537
+ }
538
+ user.lastAt = Date.now();
539
+ await this.ctx.commit();
540
+ const message = input.context ? TaMessageContext.wrap(input.context, input.text) : input.text;
541
+ return { conversation, turn: await this.ctx.turns.run(user.member, sessionId, file, message, signal) };
542
+ }
543
+ static failure(end) {
544
+ switch (end.error) {
545
+ case "refused":
546
+ return refusal(429, "insufficient_quota", end.why ?? "Your plan is used up.");
547
+ case "failed":
548
+ return refusal(502, "server_error", end.why ?? "The agent failed to answer.");
549
+ case "timeout":
550
+ return refusal(504, "timeout", "The agent took too long to answer.");
551
+ case "aborted":
552
+ return refusal(499, "aborted", "Stopped.");
553
+ default:
554
+ return;
555
+ }
556
+ }
557
+ }
558
+
559
+ // web-src/offer-openai.ts
560
+ var OFFER_MODEL = "agent";
561
+ var CONTEXT_MAX = 24000;
562
+ var CONVERSATION = /^c[0-9a-f]{24}$/;
563
+ var OfferOpenAi;
564
+ ((OfferOpenAi) => {
565
+ function textOf(content) {
566
+ if (typeof content === "string") {
567
+ return content;
568
+ }
569
+ if (!Array.isArray(content)) {
570
+ return "";
571
+ }
572
+ return content.map((part) => {
573
+ const { type, text } = part ?? {};
574
+ return (type === "text" || type === "input_text" || type === "output_text") && typeof text === "string" ? text : "";
575
+ }).filter(Boolean).join(`
576
+ `);
577
+ }
578
+ OfferOpenAi.textOf = textOf;
579
+ function conversationOf(value) {
580
+ const id = typeof value === "string" ? value : value && typeof value === "object" ? value.id : undefined;
581
+ if (id === undefined || id === null || id === "") {
582
+ return;
583
+ }
584
+ return typeof id === "string" && CONVERSATION.test(id) ? id : "bad";
585
+ }
586
+ OfferOpenAi.conversationOf = conversationOf;
587
+ function conversationOfResponse(id) {
588
+ if (id === undefined || id === null || id === "") {
589
+ return;
590
+ }
591
+ const match = typeof id === "string" ? /^resp_(c[0-9a-f]{24})_[0-9a-z]+$/.exec(id) : null;
592
+ return match ? match[1] : "bad";
593
+ }
594
+ OfferOpenAi.conversationOfResponse = conversationOfResponse;
595
+ function responseId(conversation, at = Date.now()) {
596
+ return `resp_${conversation}_${at.toString(36)}`;
597
+ }
598
+ OfferOpenAi.responseId = responseId;
599
+ function context(instructions, before, held) {
600
+ const parts = [
601
+ "Sent through the API by the one using this offer.",
602
+ ...instructions.length ? ["Their instructions, within your role:", ...instructions] : [],
603
+ ...before.length && !held ? ["What was said before, as they sent it:", ...before] : []
604
+ ];
605
+ if (parts.length === 1) {
606
+ return;
607
+ }
608
+ const text = parts.join(`
609
+ `);
610
+ return text.length > CONTEXT_MAX ? `…${text.slice(text.length - CONTEXT_MAX)}` : text;
611
+ }
612
+ function read(items, instructions, kind, body, conversation) {
613
+ const said = items.filter((item) => item.role === "user" || item.role === "assistant");
614
+ for (const item of items) {
615
+ if (item.role === "system" || item.role === "developer") {
616
+ const text2 = textOf(item.content).trim();
617
+ if (text2) {
618
+ instructions.push(text2);
619
+ }
620
+ }
621
+ }
622
+ const last = said.at(-1);
623
+ const text = last?.role === "user" ? textOf(last.content).trim() : "";
624
+ if (!text) {
625
+ return "The last message must be of the user, with text.";
626
+ }
627
+ const before = said.slice(0, -1).map((item) => `${item.role}: ${textOf(item.content).trim()}`);
628
+ const ctx = context(instructions, before, !!conversation);
629
+ const options = body.stream_options;
630
+ return {
631
+ kind,
632
+ text,
633
+ ...ctx ? { context: ctx } : {},
634
+ stream: body.stream === true,
635
+ usage: options?.include_usage === true,
636
+ ...conversation ? { conversation } : {}
637
+ };
638
+ }
639
+ function chat(body, header) {
640
+ const value = body ?? {};
641
+ if (!Array.isArray(value.messages) || !value.messages.length) {
642
+ return "`messages` is required.";
643
+ }
644
+ const conversation = conversationOf(header);
645
+ if (conversation === "bad") {
646
+ return "No such conversation.";
647
+ }
648
+ return read(value.messages, [], "chat", value, conversation);
649
+ }
650
+ OfferOpenAi.chat = chat;
651
+ function responses(body, header) {
652
+ const value = body ?? {};
653
+ const items = typeof value.input === "string" ? [{ role: "user", content: value.input }] : Array.isArray(value.input) ? value.input.filter((item) => item && (item.type === undefined || item.type === "message")) : [];
654
+ if (!items.length) {
655
+ return "`input` is required.";
656
+ }
657
+ const conversation = [conversationOfResponse(value.previous_response_id), conversationOf(value.conversation), conversationOf(header)].find((one) => one !== undefined);
658
+ if (conversation === "bad") {
659
+ return "No such conversation.";
660
+ }
661
+ const instructions = typeof value.instructions === "string" && value.instructions.trim() ? [value.instructions.trim()] : [];
662
+ return read(items, instructions, "responses", value, conversation);
663
+ }
664
+ OfferOpenAi.responses = responses;
665
+ function chatUsage(used) {
666
+ const prompt = used.input + used.cacheRead + used.cacheWrite;
667
+ return {
668
+ prompt_tokens: prompt,
669
+ completion_tokens: used.output,
670
+ total_tokens: prompt + used.output,
671
+ prompt_tokens_details: { cached_tokens: used.cacheRead }
672
+ };
673
+ }
674
+ OfferOpenAi.chatUsage = chatUsage;
675
+ function responseUsage(used) {
676
+ const input = used.input + used.cacheRead + used.cacheWrite;
677
+ return { input_tokens: input, input_tokens_details: { cached_tokens: used.cacheRead }, output_tokens: used.output, total_tokens: input + used.output };
678
+ }
679
+ OfferOpenAi.responseUsage = responseUsage;
680
+ function chatAnswer(id, created, text, used) {
681
+ return {
682
+ id,
683
+ object: "chat.completion",
684
+ created,
685
+ model: OFFER_MODEL,
686
+ choices: [{ index: 0, message: { role: "assistant", content: text }, finish_reason: "stop" }],
687
+ usage: chatUsage(used)
688
+ };
689
+ }
690
+ OfferOpenAi.chatAnswer = chatAnswer;
691
+ function chatChunk(id, created, delta, finish, used) {
692
+ return {
693
+ id,
694
+ object: "chat.completion.chunk",
695
+ created,
696
+ model: OFFER_MODEL,
697
+ choices: used ? [] : [{ index: 0, delta, finish_reason: finish }],
698
+ ...used ? { usage: chatUsage(used) } : {}
699
+ };
700
+ }
701
+ OfferOpenAi.chatChunk = chatChunk;
702
+ function response(id, created, status, text, conversation, used) {
703
+ const done = status !== "in_progress";
704
+ return {
705
+ id,
706
+ object: "response",
707
+ created_at: created,
708
+ status,
709
+ model: OFFER_MODEL,
710
+ conversation: { id: conversation },
711
+ output: done ? [
712
+ {
713
+ type: "message",
714
+ id: `msg_${id.slice(5)}`,
715
+ status: "completed",
716
+ role: "assistant",
717
+ content: [{ type: "output_text", text, annotations: [] }]
718
+ }
719
+ ] : [],
720
+ ...done ? { output_text: text } : {},
721
+ ...used ? { usage: responseUsage(used) } : {}
722
+ };
723
+ }
724
+ OfferOpenAi.response = response;
725
+ function event(data, name) {
726
+ return `${name ? `event: ${name}
727
+ ` : ""}data: ${typeof data === "string" ? data : JSON.stringify(data)}
728
+
729
+ `;
730
+ }
731
+ OfferOpenAi.event = event;
732
+ function error(status, message, code, headers = {}) {
733
+ const type = status === 401 ? "authentication_error" : status === 429 ? code === "insufficient_quota" ? "insufficient_quota" : "rate_limit_error" : status >= 500 ? "server_error" : "invalid_request_error";
734
+ return TaHttpUtil.json(status, { error: { message, type, code, param: null } }, headers);
735
+ }
736
+ OfferOpenAi.error = error;
737
+ })(OfferOpenAi ||= {});
738
+
739
+ class OfferResponseEvents {
740
+ id;
741
+ created;
742
+ conversation;
743
+ sequence = 0;
744
+ item;
745
+ constructor(id, created, conversation) {
746
+ this.id = id;
747
+ this.created = created;
748
+ this.conversation = conversation;
749
+ this.item = `msg_${id.slice(5)}`;
750
+ }
751
+ next(type, data) {
752
+ return OfferOpenAi.event({ type, sequence_number: this.sequence++, ...data }, type);
753
+ }
754
+ start() {
755
+ const response = OfferOpenAi.response(this.id, this.created, "in_progress", "", this.conversation);
756
+ return [
757
+ this.next("response.created", { response }),
758
+ this.next("response.in_progress", { response }),
759
+ this.next("response.output_item.added", {
760
+ output_index: 0,
761
+ item: { type: "message", id: this.item, status: "in_progress", role: "assistant", content: [] }
762
+ }),
763
+ this.next("response.content_part.added", {
764
+ item_id: this.item,
765
+ output_index: 0,
766
+ content_index: 0,
767
+ part: { type: "output_text", text: "", annotations: [] }
768
+ })
769
+ ].join("");
770
+ }
771
+ delta(text) {
772
+ return this.next("response.output_text.delta", { item_id: this.item, output_index: 0, content_index: 0, delta: text, logprobs: [] });
773
+ }
774
+ end(text, used) {
775
+ const part = { type: "output_text", text, annotations: [] };
776
+ return [
777
+ this.next("response.output_text.done", { item_id: this.item, output_index: 0, content_index: 0, text, logprobs: [] }),
778
+ this.next("response.content_part.done", { item_id: this.item, output_index: 0, content_index: 0, part }),
779
+ this.next("response.output_item.done", {
780
+ output_index: 0,
781
+ item: { type: "message", id: this.item, status: "completed", role: "assistant", content: [part] }
782
+ }),
783
+ this.next("response.completed", { response: OfferOpenAi.response(this.id, this.created, "completed", text, this.conversation, used) })
784
+ ].join("");
785
+ }
786
+ failed(message) {
787
+ return this.next("response.failed", {
788
+ response: { ...OfferOpenAi.response(this.id, this.created, "failed", "", this.conversation), error: { code: "server_error", message } }
789
+ });
790
+ }
791
+ }
792
+
793
+ // web-src/offer-api.ts
794
+ var SSE = { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache" };
795
+
796
+ class OfferApi {
797
+ ctx;
798
+ constructor(ctx) {
799
+ this.ctx = ctx;
800
+ }
801
+ async http(request) {
802
+ const caller = this.ctx.calls.caller(request.headers, "api");
803
+ if ("refused" in caller) {
804
+ return OfferApi.error(caller);
805
+ }
806
+ const route = `${request.method.toUpperCase()} ${request.path.replace(/\/+$/, "")}`;
807
+ if (route === "GET v1/models") {
808
+ return TaHttpUtil.json(200, {
809
+ object: "list",
810
+ data: [{ id: OFFER_MODEL, object: "model", created: Math.floor(caller.offer.createdAt / 1000), owned_by: caller.member.owner }]
811
+ });
812
+ }
813
+ if (route !== "POST v1/chat/completions" && route !== "POST v1/responses") {
814
+ return OfferOpenAi.error(404, "No such endpoint: this API has /v1/models, /v1/chat/completions and /v1/responses.", "not_found");
815
+ }
816
+ let body;
817
+ try {
818
+ body = JSON.parse(request.body || "{}");
819
+ } catch {
820
+ return OfferOpenAi.error(400, "The body is not JSON.", "invalid_json");
821
+ }
822
+ const header = request.headers["ta-conversation"];
823
+ const ask = route === "POST v1/chat/completions" ? OfferOpenAi.chat(body, header) : OfferOpenAi.responses(body, header);
824
+ return typeof ask === "string" ? OfferOpenAi.error(400, ask, "invalid_request") : this.ask(caller, ask, request.signal);
825
+ }
826
+ async ask(caller, ask, signal) {
827
+ const input = {
828
+ text: ask.text,
829
+ ...ask.context ? { context: ask.context } : {},
830
+ ...ask.conversation ? { conversation: ask.conversation } : {}
831
+ };
832
+ const call = await this.ctx.calls.ask(caller, input, signal);
833
+ if ("refused" in call) {
834
+ return OfferApi.error(call);
835
+ }
836
+ const { conversation, turn } = call;
837
+ const headers = { "ta-conversation": conversation };
838
+ const created = Math.floor(Date.now() / 1000);
839
+ if (!ask.stream) {
840
+ const end = await turn.done;
841
+ const failed = OfferCalls.failure(end);
842
+ if (failed) {
843
+ return OfferApi.error(failed);
844
+ }
845
+ return ask.kind === "chat" ? TaHttpUtil.json(200, OfferOpenAi.chatAnswer(`chatcmpl-${conversation}-${created.toString(36)}`, created, end.text, end.used), headers) : TaHttpUtil.json(200, OfferOpenAi.response(OfferOpenAi.responseId(conversation), created, "completed", end.text, conversation, end.used), headers);
846
+ }
847
+ return {
848
+ status: 200,
849
+ headers: { ...SSE, ...headers },
850
+ body: ask.kind === "chat" ? OfferApi.chatStream(turn, conversation, created, ask.usage) : OfferApi.responseStream(turn, conversation, created)
851
+ };
852
+ }
853
+ static error(refusal2) {
854
+ return OfferOpenAi.error(refusal2.status, refusal2.message, refusal2.code, refusal2.headers);
855
+ }
856
+ static async* chatStream(turn, conversation, created, usage) {
857
+ const id = `chatcmpl-${conversation}-${created.toString(36)}`;
858
+ yield OfferOpenAi.event(OfferOpenAi.chatChunk(id, created, { role: "assistant", content: "" }, null));
859
+ for await (const part of turn.parts) {
860
+ yield OfferOpenAi.event(OfferOpenAi.chatChunk(id, created, { content: part }, null));
861
+ }
862
+ const end = await turn.done;
863
+ const failed = OfferCalls.failure(end);
864
+ if (failed) {
865
+ yield OfferOpenAi.event(OfferApi.error(failed).body);
866
+ } else {
867
+ yield OfferOpenAi.event(OfferOpenAi.chatChunk(id, created, {}, "stop"));
868
+ if (usage) {
869
+ yield OfferOpenAi.event(OfferOpenAi.chatChunk(id, created, {}, null, end.used));
870
+ }
871
+ }
872
+ yield OfferOpenAi.event("[DONE]");
873
+ }
874
+ static async* responseStream(turn, conversation, created) {
875
+ const events = new OfferResponseEvents(OfferOpenAi.responseId(conversation, created * 1000), created, conversation);
876
+ yield events.start();
877
+ let text = "";
878
+ for await (const part of turn.parts) {
879
+ text += part;
880
+ yield events.delta(part);
881
+ }
882
+ const end = await turn.done;
883
+ const failed = OfferCalls.failure(end);
884
+ yield failed ? events.failed(end.why ?? end.error ?? "failed") : events.end(text, end.used);
885
+ }
886
+ }
887
+
888
+ // ../ta-protocol/esm/common/team-protocol.js
889
+ var TA_OWNER = "owner";
890
+ var TA_UNDECLARED = "extensions.install";
891
+ var TaPermissionUtil;
892
+ (function(TaPermissionUtil2) {
893
+ function read(pi) {
894
+ const given = pi === null || pi === undefined ? undefined : pi.permissions;
895
+ const map = (value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string")) : undefined;
896
+ const host2 = map(given === null || given === undefined ? undefined : given.host);
897
+ const tools = map(given === null || given === undefined ? undefined : given.tools);
898
+ return { ...host2 ? { host: host2 } : {}, ...tools ? { tools } : {} };
899
+ }
900
+ TaPermissionUtil2.read = read;
901
+ function host(manifest, method, kind) {
902
+ var _a, _b, _c, _d;
903
+ const host2 = (_a = manifest === null || manifest === undefined ? undefined : manifest.host) !== null && _a !== undefined ? _a : {};
904
+ const own = (key) => {
905
+ var _a2;
906
+ return (_a2 = Object.getOwnPropertyDescriptor(host2, key)) === null || _a2 === undefined ? undefined : _a2.value;
907
+ };
908
+ return (_d = (_c = (_b = kind ? own(`${method}:${kind}`) : undefined) !== null && _b !== undefined ? _b : own(method)) !== null && _c !== undefined ? _c : own("*")) !== null && _d !== undefined ? _d : TA_UNDECLARED;
909
+ }
910
+ TaPermissionUtil2.host = host;
911
+ })(TaPermissionUtil || (TaPermissionUtil = {}));
912
+ var action = (id, en, zh, tw, ja, more = {}) => ({
913
+ id,
914
+ area: id.split(".")[0],
915
+ title: { en, "zh-CN": zh, ...tw ? { "zh-TW": tw } : {}, ...ja ? { "ja-JP": ja } : {} },
916
+ ...more
917
+ });
918
+ var TA_ACTIONS = [
919
+ action("chat.view", "See conversations", "查看对话", "檢視對話", "会話を確認"),
920
+ action("chat.send", "Send in conversations", "在对话里发消息", "在對話裡發訊息", "会話にメッセージを送信"),
921
+ action("chat.create", "Start conversations", "新建对话", "新建對話", "新しい会話を開始"),
922
+ action("chat.stop", "Stop a reply", "停止回复", "停止回覆", "返信を停止"),
923
+ action("chat.manage", "Rename, archive and close conversations", "改名、归档、关闭对话", "改名、歸檔、關閉對話", "会話の名前変更、アーカイブ、クローズ"),
924
+ action("chat.share", "Share by a link", "生成分享链接", "生成分享連結", "共有リンクで共有"),
925
+ action("agent.view", "See agents", "查看智能体", "檢視智慧體", "エージェントを確認"),
926
+ action("agent.use", "Talk with agents", "和智能体对话", "和智慧體對話", "エージェントと対話"),
927
+ action("agent.edit", "Create, change and remove agents", "新建、修改、删除智能体", "新建、修改、刪除智慧體", "エージェントを作成・変更・削除"),
928
+ action("channel.view", "See channels", "查看频道", "檢視頻道", "チャネルを確認"),
929
+ action("channel.post", "Post in channels", "在频道里发言", "在頻道里發言", "チャネルに投稿"),
930
+ action("channel.manage", "Create and change channels", "新建、管理频道", "新建、管理頻道", "チャネルを作成・管理"),
931
+ action("task.view", "See tasks", "查看任务", "檢視任務", "タスクを確認"),
932
+ action("task.create", "Hand out tasks", "派任务", "派任務", "タスクを割り当て"),
933
+ action("task.manage", "Take over and stop tasks", "接管、停止任务", "接管、停止任務", "タスクを引き継ぎ・停止"),
934
+ action("files.read", "Read files", "读文件", "讀檔案", "ファイルを読取", { scoped: true }),
935
+ action("files.write", "Change files", "改文件", "改檔案", "ファイルを変更", { scoped: true }),
936
+ action("commands.run", "Let Ta run commands", "让 Ta 运行命令", "讓 Ta 執行命令", "Ta にコマンド実行を許可", { scoped: true, risky: true }),
937
+ action("commands.terminal", "Open terminals", "打开终端", "開啟終端機", "ターミナルを開く", { scoped: true, risky: true }),
938
+ action("hosts.use", "Use remote hosts", "使用远程主机", "使用遠端主機", "リモートホストを使用", { risky: true }),
939
+ action("models.use", "Use the models", "使用模型", "使用模型", "モデルを使用"),
940
+ action("models.manage", "Sign in to models", "登录和更换模型账号", "登入和更換模型帳號", "モデルアカウントにサインイン・変更", { grant: "single" }),
941
+ action("cron.view", "See scheduled tasks", "查看定时任务", "檢視定時任務", "スケジュールタスクを確認"),
942
+ action("cron.manage", "Change scheduled tasks", "管理定时任务", "管理定時任務", "スケジュールタスクを管理"),
943
+ action("extensions.use", "Use extensions", "使用扩展", "使用擴充功能", "拡張機能を使用"),
944
+ action("extensions.install", "Install and turn off extensions", "安装、停用扩展", "安裝、停用擴充功能", "拡張機能をインストール・無効化"),
945
+ action("extensions.trust", "Decide how far others' extensions reach", "决定别人的扩展能用到哪一步", "決定別人的擴充功能能用到哪一步", "他の人の拡張機能に許す範囲を決める", { risky: true }),
946
+ action("settings.view", "See settings", "查看设置", "檢視設定", "設定を確認"),
947
+ action("settings.manage", "Change settings", "修改设置", "修改設定", "設定を変更"),
948
+ action("members.view", "See members", "查看成员", "檢視成員", "メンバーを確認"),
949
+ action("members.invite", "Invite people", "邀请别人", "邀請別人", "メンバーを招待"),
950
+ action("members.approve", "Answer requests", "处理申请", "處理申請", "リクエストに対応"),
951
+ action("members.roles", "Change roles and members", "管理角色和成员", "管理角色和成員", "ロールとメンバーを管理"),
952
+ action("audit.view", "See the record", "查看记录", "檢視記錄", "レコードを確認")
953
+ ];
954
+ var TA_OWNER_ACTIONS = [
955
+ action("desktop.view", "See remote desktops", "查看远程桌面", "檢視遠端桌面", "リモートデスクトップを見る", { risky: true }),
956
+ action("desktop.control", "Work remote desktops", "操作远程桌面", "操作遠端桌面", "リモートデスクトップを操作", { risky: true }),
957
+ action("models.owner", "Ask models on the owner's keys", "用你的密钥和本机模型做判断", "用你的金鑰和本機模型做判斷", "あなたのキーとローカルモデルで判断", {
958
+ risky: true
959
+ })
960
+ ];
961
+ var OWNER_AREAS = ["desktop"];
962
+ var TaActionUtil;
963
+ (function(TaActionUtil2) {
964
+ const byId = new Map(TA_ACTIONS.map((one) => [one.id, one]));
965
+ const titled = new Map([...TA_ACTIONS, ...TA_OWNER_ACTIONS].map((one) => [one.id, one]));
966
+ function info(id) {
967
+ return byId.get(id);
968
+ }
969
+ TaActionUtil2.info = info;
970
+ function title(id, language) {
971
+ var _a;
972
+ var _b, _c;
973
+ const title2 = (_a = titled.get(id)) === null || _a === undefined ? undefined : _a.title;
974
+ if (!title2) {
975
+ return id;
976
+ }
977
+ return TaLanguageUtil.pick(language, {
978
+ "zh-CN": title2["zh-CN"],
979
+ "zh-TW": (_b = title2["zh-TW"]) !== null && _b !== undefined ? _b : title2["zh-CN"],
980
+ "en-US": title2.en,
981
+ "ja-JP": (_c = title2["ja-JP"]) !== null && _c !== undefined ? _c : title2.en
982
+ });
983
+ }
984
+ TaActionUtil2.title = title;
985
+ function grantable(id) {
986
+ const info2 = byId.get(id);
987
+ return !!info2 && !OWNER_AREAS.includes(info2.area);
988
+ }
989
+ TaActionUtil2.grantable = grantable;
990
+ function inRoles(id) {
991
+ var _a;
992
+ return grantable(id) && ((_a = byId.get(id)) === null || _a === undefined ? undefined : _a.grant) !== "single";
993
+ }
994
+ TaActionUtil2.inRoles = inRoles;
995
+ function inside(dir, path) {
996
+ const base = dir.replace(/\/+$/, "");
997
+ return path === base || path.startsWith(`${base}/`) || base === "";
998
+ }
999
+ TaActionUtil2.inside = inside;
1000
+ })(TaActionUtil || (TaActionUtil = {}));
1001
+
1002
+ // web-src/offer-connects.ts
1003
+ import { createHash as createHash2, randomBytes as randomBytes2 } from "node:crypto";
1004
+ var CONNECT_MS = 10 * 60000;
1005
+ var TRIES = 10;
1006
+ var TRIES_MS = 10 * 60000;
1007
+ var ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
1008
+ var hashOf = (code) => createHash2("sha256").update(code).digest("hex");
1009
+
1010
+ class OfferConnects {
1011
+ codes = new Map;
1012
+ fails = new Map;
1013
+ make(user, now = Date.now()) {
1014
+ for (const [hash, held] of this.codes) {
1015
+ if (held.user === user || held.until <= now) {
1016
+ this.codes.delete(hash);
1017
+ }
1018
+ }
1019
+ const code = [...randomBytes2(10)].map((byte) => ALPHABET[byte & 31]).join("");
1020
+ const expiresAt = now + CONNECT_MS;
1021
+ this.codes.set(hashOf(code), { user, until: expiresAt });
1022
+ return { code: `${code.slice(0, 5)}-${code.slice(5)}`, expiresAt };
1023
+ }
1024
+ take(code, client, now = Date.now()) {
1025
+ const fails = (this.fails.get(client) ?? []).filter((at) => now - at < TRIES_MS);
1026
+ if (fails.length >= TRIES) {
1027
+ return "blocked";
1028
+ }
1029
+ const typed = String(code ?? "").toUpperCase().replace(/[\s-]/g, "").replace(/O/g, "0").replace(/[IL]/g, "1");
1030
+ const hash = hashOf(typed);
1031
+ const held = this.codes.get(hash);
1032
+ if (held && held.until > now) {
1033
+ this.codes.delete(hash);
1034
+ return held.user;
1035
+ }
1036
+ this.fails.set(client, [...fails, now]);
1037
+ for (const [other, times] of this.fails) {
1038
+ if (!times.some((at) => now - at < TRIES_MS)) {
1039
+ this.fails.delete(other);
1040
+ }
1041
+ }
1042
+ return "wrong";
1043
+ }
1044
+ }
1045
+
1046
+ // ../ta-protocol/esm/common/redactor.js
1047
+ var REDACTED = "[redacted]";
1048
+ var WHOLE = [
1049
+ ["PRIVATE_KEY", /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g],
1050
+ ["API_KEY", /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}/g],
1051
+ ["GITHUB_TOKEN", /\bgh[pousr]_[A-Za-z0-9]{30,}\b/g],
1052
+ ["GITHUB_TOKEN", /\bgithub_pat_[A-Za-z0-9_]{40,}\b/g],
1053
+ ["GITLAB_TOKEN", /\bglpat-[A-Za-z0-9_-]{20,}\b/g],
1054
+ ["SLACK_TOKEN", /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g],
1055
+ ["AWS_ACCESS_KEY_ID", /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g],
1056
+ ["GOOGLE_API_KEY", /\bAIza[0-9A-Za-z_-]{35}\b/g],
1057
+ ["JWT", /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g]
1058
+ ];
1059
+ var NAMED = [
1060
+ /(\bBearer\s+)[A-Za-z0-9._~+/-]{16,}=*/gi,
1061
+ /(\b[A-Za-z0-9_.-]*(?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key)[A-Za-z0-9_.-]*["']?\s*[:=]\s*["']?)([^\s"'`,;]{6,})/gi,
1062
+ /(:\/\/[^\s:/@]+:)([^\s@/]{3,})(@)/g
1063
+ ];
1064
+
1065
+ class Redactor {
1066
+ constructor() {
1067
+ this.count = 0;
1068
+ }
1069
+ text(text) {
1070
+ let out = text;
1071
+ for (const [, pattern] of WHOLE) {
1072
+ out = out.replace(pattern, () => this.hide());
1073
+ }
1074
+ out = out.replace(NAMED[0], (_match, before) => before + this.hide());
1075
+ out = out.replace(NAMED[1], (match, before, value) => Redactor.placeholder(value) ? match : before + this.hide());
1076
+ out = out.replace(NAMED[2], (_match, before, _value, after) => before + this.hide() + after);
1077
+ return out;
1078
+ }
1079
+ value(value, max) {
1080
+ if (typeof value === "string") {
1081
+ return Redactor.cut(this.text(value), max);
1082
+ }
1083
+ if (Array.isArray(value)) {
1084
+ return value.map((item) => this.value(item, max));
1085
+ }
1086
+ if (value && typeof value === "object") {
1087
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, this.value(item, max)]));
1088
+ }
1089
+ return value;
1090
+ }
1091
+ static spans(text) {
1092
+ var _a;
1093
+ var _b;
1094
+ const found = [];
1095
+ for (const [kind, pattern] of WHOLE) {
1096
+ for (const match of text.matchAll(pattern)) {
1097
+ found.push({ start: match.index, end: match.index + match[0].length, kind });
1098
+ }
1099
+ }
1100
+ for (const match of text.matchAll(NAMED[0])) {
1101
+ found.push({ start: match.index + match[1].length, end: match.index + match[0].length, kind: "BEARER_TOKEN" });
1102
+ }
1103
+ for (const match of text.matchAll(NAMED[1])) {
1104
+ if (!Redactor.placeholder(match[2])) {
1105
+ const start = match.index + match[1].length;
1106
+ const name = (_b = (_a = /[A-Za-z0-9_.-]+/.exec(match[1])) === null || _a === undefined ? undefined : _a[0]) !== null && _b !== undefined ? _b : "SECRET";
1107
+ found.push({ start, end: start + match[2].length, kind: name.replace(/[^A-Za-z0-9]+/g, "_").toUpperCase() });
1108
+ }
1109
+ }
1110
+ for (const match of text.matchAll(NAMED[2])) {
1111
+ const start = match.index + match[1].length;
1112
+ found.push({ start, end: start + match[2].length, kind: "URL_PASSWORD" });
1113
+ }
1114
+ found.sort((a, b) => a.start - b.start || b.end - a.end);
1115
+ const spans = [];
1116
+ for (const span of found) {
1117
+ const last = spans.at(-1);
1118
+ if (!last || span.start >= last.end) {
1119
+ spans.push(span);
1120
+ }
1121
+ }
1122
+ return spans;
1123
+ }
1124
+ static cut(text, max) {
1125
+ return text.length > max ? `${text.slice(0, max)}…` : text;
1126
+ }
1127
+ hide() {
1128
+ this.count++;
1129
+ return REDACTED;
1130
+ }
1131
+ static placeholder(value) {
1132
+ return /^(?:\$|<|\{|\[redacted|process\.env|os\.environ|xxx|\*{3})/i.test(value) || /^(?:true|false|null|undefined|none|string|number)$/i.test(value);
1133
+ }
1134
+ }
1135
+
1136
+ // web-src/offer-protocol.ts
1137
+ var NAME = "@celljs/ta-offer";
1138
+ var OFFERS_VIEW = `${NAME}/offers`;
1139
+ var OFFER_MARK = "[ta:offer]";
1140
+ var DATA_KEY = "data";
1141
+ var PAYEE_KEY = "payee";
1142
+ var EMPTY_DATA = { v: 1, offers: [], users: [], payments: [] };
1143
+ var LIMITS = { name: 40, intro: 300, plans: 6, planName: 20, note: 300, picture: 400000, keys: 5, keyName: 30, clients: 10 };
1144
+
1145
+ // web-src/offer-conversations.ts
1146
+ var CHANNELS = "@celljs/ta-channels";
1147
+ var OfferRole;
1148
+ ((OfferRole) => {
1149
+ function of(agent, offer) {
1150
+ return [
1151
+ OFFER_MARK,
1152
+ `You are ${offer.name}, which the owner of this Ta opened for others to use. The one you talk with uses you within a plan of theirs: help them as your role says.`,
1153
+ new Redactor().text(agent.role.trim())
1154
+ ].join(`
1155
+ `);
1156
+ }
1157
+ OfferRole.of = of;
1158
+ })(OfferRole ||= {});
1159
+
1160
+ class OfferConversations {
1161
+ host;
1162
+ constructor(host) {
1163
+ this.host = host;
1164
+ }
1165
+ async agents() {
1166
+ const listed = await this.host.callPackageHost(CHANNELS, "listAgents").catch(() => []);
1167
+ return Array.isArray(listed) ? listed : [];
1168
+ }
1169
+ async agent(id) {
1170
+ return (await this.agents()).find((agent) => agent.id === id);
1171
+ }
1172
+ async start(member, offer, agent) {
1173
+ if (!member.home) {
1174
+ throw new Error("One using an offer works in a home of their own; this member has none.");
1175
+ }
1176
+ const home = member.home;
1177
+ return this.host.team.actAs(member.id, async () => {
1178
+ const { sessionId } = await this.host.openSession({
1179
+ cwd: home,
1180
+ appendSystemPrompt: OfferRole.of(agent, offer),
1181
+ ...agent.model ? { model: agent.model } : {}
1182
+ });
1183
+ await this.host.setSessionName(sessionId, offer.name).catch(() => {
1184
+ return;
1185
+ });
1186
+ const { sessionFile } = await this.host.getState(sessionId);
1187
+ return { sessionId, ...sessionFile ? { sessionFile } : {} };
1188
+ });
1189
+ }
1190
+ async resume(member, sessionFile) {
1191
+ const open = (await this.host.listSessions()).find((session) => session.sessionFile === sessionFile);
1192
+ if (open) {
1193
+ return open.sessionId;
1194
+ }
1195
+ if (!member.home) {
1196
+ throw new Error("One using an offer works in a home of their own; this member has none.");
1197
+ }
1198
+ const home = member.home;
1199
+ return this.host.team.actAs(member.id, async () => (await this.host.openSession({ cwd: home, sessionFile })).sessionId);
1200
+ }
1201
+ }
1202
+
1203
+ // web-src/offer-links.ts
1204
+ var TEAM = "@celljs/ta-team";
1205
+ var USER_ROLE = "user";
1206
+ var LINK_DAYS = 365;
1207
+
1208
+ class OfferLinks {
1209
+ host;
1210
+ constructor(host) {
1211
+ this.host = host;
1212
+ }
1213
+ call(method, ...params) {
1214
+ return this.host.callPackageHost(TEAM, method, params);
1215
+ }
1216
+ async create(what, approve, language) {
1217
+ const invite = await this.call("createInvite", {
1218
+ role: USER_ROLE,
1219
+ days: LINK_DAYS,
1220
+ approve,
1221
+ what,
1222
+ ...language ? { language } : {}
1223
+ });
1224
+ return { id: invite.id, link: invite.link, expiresAt: invite.expiresAt };
1225
+ }
1226
+ async setApprove(invite, approve) {
1227
+ await this.call("setInviteApprove", invite, approve);
1228
+ }
1229
+ async stop(invite) {
1230
+ await this.call("stopInvite", invite).catch(() => {
1231
+ return;
1232
+ });
1233
+ }
1234
+ async waiting(invites) {
1235
+ if (!invites.size) {
1236
+ return [];
1237
+ }
1238
+ const overview = await this.call("overview").catch(() => {
1239
+ return;
1240
+ });
1241
+ return (overview?.joins ?? []).filter((join) => join.status === "waiting" && invites.has(join.invite));
1242
+ }
1243
+ async answer(join, accept) {
1244
+ await this.call("answerJoin", join, accept, USER_ROLE);
1245
+ }
1246
+ async remove(member) {
1247
+ this.host.team.disconnect(member);
1248
+ await this.call("removeMember", member).catch(() => {
1249
+ return;
1250
+ });
1251
+ }
1252
+ who(principal) {
1253
+ const info = this.host.team.describe(principal);
1254
+ return info?.role === USER_ROLE ? info : undefined;
1255
+ }
1256
+ apiBase(link, name) {
1257
+ try {
1258
+ const url = new URL(link ?? "");
1259
+ const host = new URLSearchParams(url.hash.slice(1)).get("h");
1260
+ return host ? TaHttpUtil.base(url.origin, host, name) : undefined;
1261
+ } catch {
1262
+ return;
1263
+ }
1264
+ }
1265
+ online(member) {
1266
+ return (this.host.team.connected()[member] ?? 0) > 0;
1267
+ }
1268
+ }
1269
+
1270
+ // web-src/offer-payments.ts
1271
+ import { randomInt, randomUUID } from "node:crypto";
1272
+
1273
+ // web-src/offer-quota.ts
1274
+ var DAY_MS = 86400000;
1275
+ var OfferQuota;
1276
+ ((OfferQuota) => {
1277
+ function day(now) {
1278
+ const date = new Date(now);
1279
+ const pad = (n) => String(n).padStart(2, "0");
1280
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
1281
+ }
1282
+ OfferQuota.day = day;
1283
+ function nextDay(now) {
1284
+ const date = new Date(now);
1285
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).getTime();
1286
+ }
1287
+ OfferQuota.nextDay = nextDay;
1288
+ function emptyMeter(now) {
1289
+ return { total: 0, day: day(now), today: 0, cost: 0 };
1290
+ }
1291
+ OfferQuota.emptyMeter = emptyMeter;
1292
+ function tokensOf(usage) {
1293
+ const n = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
1294
+ return Math.ceil(n(usage?.input) + n(usage?.output) + n(usage?.cacheWrite) + n(usage?.cacheRead) / 10);
1295
+ }
1296
+ OfferQuota.tokensOf = tokensOf;
1297
+ function add(meter, tokens, cost, now) {
1298
+ const today = day(now);
1299
+ const same = meter.day === today;
1300
+ return {
1301
+ total: meter.total + tokens,
1302
+ day: today,
1303
+ today: (same ? meter.today : 0) + tokens,
1304
+ cost: meter.cost + (Number.isFinite(cost) && cost > 0 ? cost : 0)
1305
+ };
1306
+ }
1307
+ OfferQuota.add = add;
1308
+ function grant(plan, by, now, before) {
1309
+ const old = before?.grant;
1310
+ const total = before?.used.total ?? 0;
1311
+ const carried = old && !old.days && !plan.days && old.tokens !== undefined && plan.tokens !== undefined && !(old.endsAt !== undefined && old.endsAt <= now) ? Math.max(0, old.tokens - (total - (old.from ?? 0))) : 0;
1312
+ return {
1313
+ plan: plan.id,
1314
+ name: plan.name,
1315
+ price: plan.price,
1316
+ ...plan.tokens !== undefined ? { tokens: plan.tokens + carried } : {},
1317
+ ...plan.daily !== undefined ? { daily: plan.daily } : {},
1318
+ ...plan.days ? { days: plan.days } : {},
1319
+ ...total ? { from: total } : {},
1320
+ startsAt: now,
1321
+ ...plan.days ? { endsAt: now + plan.days * DAY_MS } : {},
1322
+ by
1323
+ };
1324
+ }
1325
+ OfferQuota.grant = grant;
1326
+ function state(grant2, meter, now, stopped) {
1327
+ if (!grant2) {
1328
+ return { block: "expired" };
1329
+ }
1330
+ const today = meter.day === day(now) ? meter.today : 0;
1331
+ const left = grant2.tokens !== undefined ? Math.max(0, grant2.tokens - (meter.total - (grant2.from ?? 0))) : undefined;
1332
+ const todayLeft = grant2.daily !== undefined ? Math.max(0, grant2.daily - today) : undefined;
1333
+ const state2 = {
1334
+ block: "none",
1335
+ ...left !== undefined ? { left } : {},
1336
+ ...todayLeft !== undefined ? { todayLeft, resetsAt: nextDay(now) } : {},
1337
+ ...grant2.endsAt !== undefined ? { endsAt: grant2.endsAt } : {}
1338
+ };
1339
+ if (stopped) {
1340
+ return { ...state2, block: stopped };
1341
+ }
1342
+ if (grant2.endsAt !== undefined && grant2.endsAt <= now) {
1343
+ return { ...state2, block: "expired" };
1344
+ }
1345
+ if (left === 0) {
1346
+ return { ...state2, block: "total" };
1347
+ }
1348
+ if (todayLeft === 0) {
1349
+ return { ...state2, block: "daily" };
1350
+ }
1351
+ return state2;
1352
+ }
1353
+ OfferQuota.state = state;
1354
+ function clean(plans, limits) {
1355
+ const whole = (value, min, max) => {
1356
+ const n = Math.floor(Number(value));
1357
+ return Number.isFinite(n) && n >= min ? Math.min(n, max) : undefined;
1358
+ };
1359
+ const seen = new Set;
1360
+ const out = [];
1361
+ for (const one of Array.isArray(plans) ? plans : []) {
1362
+ const given = one;
1363
+ const id = typeof given?.id === "string" && /^[A-Za-z0-9_-]{1,24}$/.test(given.id) ? given.id : undefined;
1364
+ const name = typeof given?.name === "string" ? given.name.trim().slice(0, limits.planName) : "";
1365
+ if (!id || !name || seen.has(id) || out.length >= limits.plans) {
1366
+ continue;
1367
+ }
1368
+ seen.add(id);
1369
+ const tokens = whole(given.tokens, 1, 1000000000000);
1370
+ const daily = whole(given.daily, 1, 1000000000000);
1371
+ const days = whole(given.days, 1, 3660);
1372
+ out.push({
1373
+ id,
1374
+ name,
1375
+ price: whole(given.price, 0, 1e9) ?? 0,
1376
+ ...tokens !== undefined ? { tokens } : {},
1377
+ ...daily !== undefined ? { daily } : {},
1378
+ ...days !== undefined ? { days } : {}
1379
+ });
1380
+ }
1381
+ return out;
1382
+ }
1383
+ OfferQuota.clean = clean;
1384
+ })(OfferQuota ||= {});
1385
+
1386
+ // web-src/offer-payments.ts
1387
+ var MAX_WAITING = 1;
1388
+ var WAIT_DAYS = 14;
1389
+ var DAY_MS2 = 86400000;
1390
+ var KEEP = 500;
1391
+
1392
+ class OfferPayments {
1393
+ store;
1394
+ constructor(store) {
1395
+ this.store = store;
1396
+ }
1397
+ waitingOf(user) {
1398
+ return this.store.data.payments.find((one) => one.user === user && one.status === "waiting");
1399
+ }
1400
+ claim(user, offer, planId, now = Date.now()) {
1401
+ const plan = offer.plans.find((one) => one.id === planId);
1402
+ if (!plan || plan.price <= 0) {
1403
+ throw new Error("No such plan to pay for.");
1404
+ }
1405
+ const waiting = this.store.data.payments.filter((one) => one.user === user.id && one.status === "waiting");
1406
+ for (const old of waiting.slice(0, Math.max(0, waiting.length + 1 - MAX_WAITING))) {
1407
+ old.status = "refused";
1408
+ old.answeredAt = now;
1409
+ }
1410
+ const payment = {
1411
+ id: randomUUID(),
1412
+ user: user.id,
1413
+ offer: offer.id,
1414
+ plan: plan.id,
1415
+ amount: plan.price,
1416
+ code: String(randomInt(1000, 1e4)),
1417
+ at: now,
1418
+ status: "waiting",
1419
+ way: "code"
1420
+ };
1421
+ this.store.data.payments.push(payment);
1422
+ return payment;
1423
+ }
1424
+ cancel(user, id, now = Date.now()) {
1425
+ const payment = this.store.data.payments.find((one) => one.id === id && one.user === user.id && one.status === "waiting");
1426
+ if (payment) {
1427
+ payment.status = "refused";
1428
+ payment.answeredAt = now;
1429
+ }
1430
+ }
1431
+ answer(id, accept, by, now = Date.now()) {
1432
+ const payment = this.store.data.payments.find((one) => one.id === id && one.status === "waiting");
1433
+ if (!payment) {
1434
+ throw new Error("No such payment waiting.");
1435
+ }
1436
+ payment.status = accept ? "confirmed" : "refused";
1437
+ payment.answeredAt = now;
1438
+ const user = accept ? this.give(payment.user, payment.offer, payment.plan, by, now) : undefined;
1439
+ return { payment, ...user ? { user } : {} };
1440
+ }
1441
+ offline(user, offer, planId, amount, by, now = Date.now()) {
1442
+ const plan = offer.plans.find((one) => one.id === planId);
1443
+ if (!plan) {
1444
+ throw new Error("No such plan.");
1445
+ }
1446
+ const fen = Number.isFinite(Number(amount)) && Number(amount) >= 0 ? Math.floor(Number(amount)) : plan.price;
1447
+ const payment = {
1448
+ id: randomUUID(),
1449
+ user: user.id,
1450
+ offer: offer.id,
1451
+ plan: plan.id,
1452
+ amount: fen,
1453
+ code: "",
1454
+ at: now,
1455
+ status: "confirmed",
1456
+ answeredAt: now,
1457
+ way: "offline"
1458
+ };
1459
+ this.store.data.payments.push(payment);
1460
+ this.give(user.id, offer.id, plan.id, by, now);
1461
+ return payment;
1462
+ }
1463
+ tidy(now = Date.now()) {
1464
+ for (const one of this.store.data.payments) {
1465
+ if (one.status === "waiting" && now - one.at > WAIT_DAYS * DAY_MS2) {
1466
+ one.status = "refused";
1467
+ one.answeredAt = now;
1468
+ }
1469
+ }
1470
+ const answered = this.store.data.payments.filter((one) => one.status !== "waiting");
1471
+ if (answered.length > KEEP) {
1472
+ const drop = new Set(answered.slice(0, answered.length - KEEP));
1473
+ this.store.data.payments = this.store.data.payments.filter((one) => !drop.has(one));
1474
+ }
1475
+ }
1476
+ give(userId, offerId, planId, by, now) {
1477
+ const user = this.store.data.users.find((one) => one.id === userId);
1478
+ const plan = this.store.data.offers.find((one) => one.id === offerId)?.plans.find((one) => one.id === planId);
1479
+ if (!user || !plan) {
1480
+ return;
1481
+ }
1482
+ user.grant = OfferQuota.grant(plan, by, now, user);
1483
+ return user;
1484
+ }
1485
+ }
1486
+
1487
+ // web-src/offer-store.ts
1488
+ import { appendFile, mkdir } from "node:fs/promises";
1489
+ import { join } from "node:path";
1490
+ class OfferStore {
1491
+ host;
1492
+ data = structuredClone(EMPTY_DATA);
1493
+ writing = Promise.resolve();
1494
+ constructor(host) {
1495
+ this.host = host;
1496
+ }
1497
+ async load() {
1498
+ const kept = await this.host.getExtensionData(NAME, DATA_KEY).catch(() => {
1499
+ return;
1500
+ });
1501
+ this.data = {
1502
+ v: 1,
1503
+ offers: Array.isArray(kept?.offers) ? kept.offers : [],
1504
+ users: Array.isArray(kept?.users) ? kept.users : [],
1505
+ payments: Array.isArray(kept?.payments) ? kept.payments : []
1506
+ };
1507
+ }
1508
+ save() {
1509
+ const value = structuredClone(this.data);
1510
+ this.writing = this.writing.then(() => this.host.setExtensionData(NAME, DATA_KEY, value)).catch(() => {
1511
+ return;
1512
+ });
1513
+ return this.writing;
1514
+ }
1515
+ async payee() {
1516
+ const kept = await this.host.getExtensionData(NAME, PAYEE_KEY).catch(() => {
1517
+ return;
1518
+ });
1519
+ return {
1520
+ ...typeof kept?.picture === "string" ? { picture: kept.picture } : {},
1521
+ ...typeof kept?.note === "string" ? { note: kept.note } : {}
1522
+ };
1523
+ }
1524
+ setPayee(payee) {
1525
+ return this.host.setExtensionData(NAME, PAYEE_KEY, payee);
1526
+ }
1527
+ async record(line) {
1528
+ const dir = join(this.host.agentDir, "offer");
1529
+ await mkdir(dir, { recursive: true, mode: 448 }).catch(() => {
1530
+ return;
1531
+ });
1532
+ await appendFile(join(dir, "ledger.jsonl"), `${JSON.stringify(line)}
1533
+ `, { mode: 384 }).catch(() => {
1534
+ return;
1535
+ });
1536
+ }
1537
+ }
1538
+
1539
+ // web-src/offer-turns.ts
1540
+ import { randomUUID as randomUUID2 } from "node:crypto";
1541
+ var TURN_MS = 10 * 60000;
1542
+ var n = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
1543
+
1544
+ class Live {
1545
+ member;
1546
+ sessionId;
1547
+ queue = [];
1548
+ wake;
1549
+ current = "";
1550
+ last = "";
1551
+ apart = false;
1552
+ used = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
1553
+ ended;
1554
+ finish;
1555
+ done = new Promise((resolve) => {
1556
+ this.finish = resolve;
1557
+ });
1558
+ timer;
1559
+ constructor(member, sessionId) {
1560
+ this.member = member;
1561
+ this.sessionId = sessionId;
1562
+ }
1563
+ push(text) {
1564
+ this.queue.push(text);
1565
+ this.wake?.();
1566
+ }
1567
+ end(end) {
1568
+ if (this.ended) {
1569
+ return;
1570
+ }
1571
+ clearTimeout(this.timer);
1572
+ this.ended = { text: this.current || this.last, used: this.used, ...end };
1573
+ this.finish(this.ended);
1574
+ this.wake?.();
1575
+ }
1576
+ async* parts() {
1577
+ for (;; ) {
1578
+ const text = this.queue.shift();
1579
+ if (text !== undefined) {
1580
+ yield text;
1581
+ continue;
1582
+ }
1583
+ if (this.ended) {
1584
+ return;
1585
+ }
1586
+ await new Promise((resolve) => {
1587
+ this.wake = resolve;
1588
+ });
1589
+ this.wake = undefined;
1590
+ }
1591
+ }
1592
+ }
1593
+
1594
+ class OfferTurns {
1595
+ host;
1596
+ live = new Map;
1597
+ stopEvents;
1598
+ constructor(host) {
1599
+ this.host = host;
1600
+ }
1601
+ start() {
1602
+ this.stopEvents = this.host.onSessionEvent((event) => {
1603
+ if (event.type === "turn_end" && event.sessionFile) {
1604
+ this.live.get(event.sessionFile)?.end(event.aborted ? { error: "aborted" } : event.error ? { error: "failed", why: event.error } : {});
1605
+ this.live.delete(event.sessionFile);
1606
+ }
1607
+ });
1608
+ }
1609
+ dispose() {
1610
+ this.stopEvents?.();
1611
+ for (const live of this.live.values()) {
1612
+ live.end({ error: "aborted" });
1613
+ }
1614
+ this.live.clear();
1615
+ }
1616
+ busy(sessionFile) {
1617
+ return this.live.has(sessionFile);
1618
+ }
1619
+ running(member) {
1620
+ return [...this.live.values()].filter((live) => live.member === member).length;
1621
+ }
1622
+ delta(sessionFile, text) {
1623
+ const live = sessionFile ? this.live.get(sessionFile) : undefined;
1624
+ if (!live || !text) {
1625
+ return;
1626
+ }
1627
+ const apart = live.apart && !live.current;
1628
+ live.apart = false;
1629
+ live.current += text;
1630
+ live.push(apart ? `
1631
+
1632
+ ${text}` : text);
1633
+ }
1634
+ message(sessionFile, usage) {
1635
+ const live = sessionFile ? this.live.get(sessionFile) : undefined;
1636
+ if (!live) {
1637
+ return;
1638
+ }
1639
+ live.used.input += n(usage?.input);
1640
+ live.used.output += n(usage?.output);
1641
+ live.used.cacheRead += n(usage?.cacheRead);
1642
+ live.used.cacheWrite += n(usage?.cacheWrite);
1643
+ if (live.current) {
1644
+ live.last = live.current;
1645
+ live.current = "";
1646
+ live.apart = true;
1647
+ }
1648
+ }
1649
+ refused(sessionFile, why) {
1650
+ const live = sessionFile ? this.live.get(sessionFile) : undefined;
1651
+ if (live && sessionFile) {
1652
+ live.end({ error: "refused", why });
1653
+ this.live.delete(sessionFile);
1654
+ }
1655
+ }
1656
+ async run(member, sessionId, sessionFile, message, signal) {
1657
+ const live = new Live(member, sessionId);
1658
+ this.live.set(sessionFile, live);
1659
+ const stop = () => {
1660
+ if (!live.ended) {
1661
+ this.host.abort(sessionId).catch(() => {
1662
+ return;
1663
+ });
1664
+ }
1665
+ };
1666
+ live.timer = setTimeout(() => {
1667
+ stop();
1668
+ live.end({ error: "timeout" });
1669
+ this.live.delete(sessionFile);
1670
+ }, TURN_MS);
1671
+ live.timer.unref?.();
1672
+ signal?.addEventListener("abort", stop, { once: true });
1673
+ try {
1674
+ await this.host.team.actAs(member, () => this.host.prompt(sessionId, { message, clientMessageId: randomUUID2() }));
1675
+ } catch (error) {
1676
+ live.end({ error: "failed", why: error instanceof Error ? error.message : String(error) });
1677
+ this.live.delete(sessionFile);
1678
+ }
1679
+ return { parts: live.parts(), done: live.done };
1680
+ }
1681
+ }
1682
+
1683
+ // web-src/offer-context.ts
1684
+ class OfferError extends Error {
1685
+ }
1686
+
1687
+ class OfferContext {
1688
+ host;
1689
+ store;
1690
+ links;
1691
+ conversations;
1692
+ payments;
1693
+ turns;
1694
+ calls;
1695
+ connects = new OfferConnects;
1696
+ constructor(host) {
1697
+ this.host = host;
1698
+ this.store = new OfferStore(host);
1699
+ this.links = new OfferLinks(host);
1700
+ this.conversations = new OfferConversations(host);
1701
+ this.payments = new OfferPayments(this.store);
1702
+ this.turns = new OfferTurns(host);
1703
+ this.calls = new OfferCalls(this);
1704
+ }
1705
+ get data() {
1706
+ return this.store.data;
1707
+ }
1708
+ requireOwner() {
1709
+ if (this.host.team.current() !== TA_OWNER) {
1710
+ throw new OfferError("Only the owner of this Ta does this.");
1711
+ }
1712
+ }
1713
+ caller() {
1714
+ const principal = this.host.team.current();
1715
+ return principal === TA_OWNER ? undefined : this.links.who(principal);
1716
+ }
1717
+ offer(id) {
1718
+ const offer = this.data.offers.find((one) => one.id === id);
1719
+ if (!offer) {
1720
+ throw new OfferError("No such offer.");
1721
+ }
1722
+ return offer;
1723
+ }
1724
+ user(id) {
1725
+ const user = this.data.users.find((one) => one.id === id);
1726
+ if (!user) {
1727
+ throw new OfferError("No such user.");
1728
+ }
1729
+ return user;
1730
+ }
1731
+ state(user, now = Date.now()) {
1732
+ const offer = this.data.offers.find((one) => one.id === user.offer);
1733
+ return OfferQuota.state(user.grant, user.used, now, !offer ? "closed" : offer.paused ? "closed" : user.paused ? "paused" : undefined);
1734
+ }
1735
+ async commit(line) {
1736
+ await this.store.save();
1737
+ if (line) {
1738
+ await this.store.record({ at: Date.now(), ...line });
1739
+ }
1740
+ }
1741
+ async tell(id, title, text) {
1742
+ await this.host.callPackageHost("@celljs/ta-notify", "notify", [{ from: NAME, id, level: "ask", title, text, view: OFFERS_VIEW }]).catch(() => {
1743
+ return;
1744
+ });
1745
+ }
1746
+ }
1747
+
1748
+ // web-src/offer-mcp-tasks.ts
1749
+ import { randomUUID as randomUUID3 } from "node:crypto";
1750
+ var TTL = { least: 60000, most: 24 * 60 * 60000, usual: 60 * 60000 };
1751
+ var POLL_MS = 3000;
1752
+ var KEPT = 50;
1753
+
1754
+ class Held {
1755
+ id;
1756
+ owner;
1757
+ createdAt;
1758
+ ttl;
1759
+ status = "working";
1760
+ statusMessage;
1761
+ updatedAt;
1762
+ result;
1763
+ abort = new AbortController;
1764
+ finish;
1765
+ ended = new Promise((resolve) => {
1766
+ this.finish = resolve;
1767
+ });
1768
+ constructor(id, owner, createdAt, ttl) {
1769
+ this.id = id;
1770
+ this.owner = owner;
1771
+ this.createdAt = createdAt;
1772
+ this.ttl = ttl;
1773
+ this.updatedAt = createdAt;
1774
+ }
1775
+ shown() {
1776
+ return {
1777
+ taskId: this.id,
1778
+ status: this.status,
1779
+ ...this.statusMessage ? { statusMessage: this.statusMessage } : {},
1780
+ createdAt: new Date(this.createdAt).toISOString(),
1781
+ lastUpdatedAt: new Date(this.updatedAt).toISOString(),
1782
+ ttl: this.ttl,
1783
+ ...this.status === "working" ? { pollInterval: POLL_MS } : {}
1784
+ };
1785
+ }
1786
+ }
1787
+
1788
+ class OfferMcpTasks {
1789
+ tasks = new Map;
1790
+ start(owner, ttl, work, now = Date.now()) {
1791
+ this.tidy(owner, now);
1792
+ const kept = typeof ttl === "number" && Number.isFinite(ttl) ? Math.min(TTL.most, Math.max(TTL.least, ttl)) : TTL.usual;
1793
+ const held = new Held(randomUUID3(), owner, now, kept);
1794
+ this.tasks.set(held.id, held);
1795
+ work(held.abort.signal).catch((error) => ({ content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], isError: true })).then((result) => {
1796
+ if (held.status === "working") {
1797
+ held.status = result.isError ? "failed" : "completed";
1798
+ held.result = result;
1799
+ held.updatedAt = Date.now();
1800
+ if (result.isError) {
1801
+ held.statusMessage = result.content[0]?.text.slice(0, 200);
1802
+ }
1803
+ }
1804
+ held.finish();
1805
+ });
1806
+ return held.shown();
1807
+ }
1808
+ get(owner, id, now = Date.now()) {
1809
+ return this.of(owner, id, now)?.shown();
1810
+ }
1811
+ list(owner, now = Date.now()) {
1812
+ this.tidy(owner, now);
1813
+ return [...this.tasks.values()].filter((one) => one.owner === owner).map((one) => one.shown());
1814
+ }
1815
+ async result(owner, id, now = Date.now()) {
1816
+ const held = this.of(owner, id, now);
1817
+ if (!held) {
1818
+ return;
1819
+ }
1820
+ await held.ended;
1821
+ const result = held.result ?? { content: [{ type: "text", text: held.statusMessage ?? held.status }], isError: true };
1822
+ return { task: held.shown(), result };
1823
+ }
1824
+ cancel(owner, id, now = Date.now()) {
1825
+ const held = this.of(owner, id, now);
1826
+ if (!held) {
1827
+ return;
1828
+ }
1829
+ if (held.status !== "working") {
1830
+ return "ended";
1831
+ }
1832
+ held.status = "cancelled";
1833
+ held.statusMessage = "The task was cancelled by request.";
1834
+ held.updatedAt = now;
1835
+ held.abort.abort();
1836
+ held.finish();
1837
+ return held.shown();
1838
+ }
1839
+ dispose() {
1840
+ for (const held of this.tasks.values()) {
1841
+ held.abort.abort();
1842
+ }
1843
+ this.tasks.clear();
1844
+ }
1845
+ of(owner, id, now) {
1846
+ const held = typeof id === "string" ? this.tasks.get(id) : undefined;
1847
+ if (!held || held.owner !== owner) {
1848
+ return;
1849
+ }
1850
+ if (held.createdAt + held.ttl <= now) {
1851
+ held.abort.abort();
1852
+ this.tasks.delete(held.id);
1853
+ return;
1854
+ }
1855
+ return held;
1856
+ }
1857
+ tidy(owner, now) {
1858
+ const theirs = [];
1859
+ for (const held of this.tasks.values()) {
1860
+ if (held.createdAt + held.ttl <= now) {
1861
+ held.abort.abort();
1862
+ this.tasks.delete(held.id);
1863
+ } else if (held.owner === owner) {
1864
+ theirs.push(held);
1865
+ }
1866
+ }
1867
+ const ended = theirs.filter((one) => one.status !== "working");
1868
+ for (const old of ended.slice(0, Math.max(0, theirs.length - KEPT + 1))) {
1869
+ this.tasks.delete(old.id);
1870
+ }
1871
+ }
1872
+ }
1873
+
1874
+ // web-src/offer-oauth-util.ts
1875
+ import { createHash as createHash3, createHmac, timingSafeEqual } from "node:crypto";
1876
+ var MCP_SCOPE = "ask";
1877
+ var CLIENT_PREFIX = "ta_ci_";
1878
+ var DOCUMENT_BYTES = 1e4;
1879
+ var DOCUMENT_MS = 5000;
1880
+ var DOCUMENT_KEEP_MS = 10 * 60000;
1881
+ var CORS = {
1882
+ "access-control-allow-origin": "*",
1883
+ "access-control-allow-methods": "GET, POST, OPTIONS",
1884
+ "access-control-allow-headers": "authorization, content-type, mcp-protocol-version, mcp-session-id, last-event-id",
1885
+ "access-control-expose-headers": "www-authenticate, mcp-session-id",
1886
+ "access-control-max-age": "600"
1887
+ };
1888
+ var json = (status, value, headers = {}) => ({
1889
+ status,
1890
+ headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", ...CORS, ...headers },
1891
+ body: JSON.stringify(value)
1892
+ });
1893
+ var LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]"]);
1894
+ var NOT_APPS = new Set(["javascript:", "data:", "vbscript:", "file:", "blob:", "about:", "ws:", "wss:", "ftp:"]);
1895
+ var OfferOAuthUtil;
1896
+ ((OfferOAuthUtil) => {
1897
+ OfferOAuthUtil.answer = json;
1898
+ function urls(base) {
1899
+ const url = new URL(base);
1900
+ return {
1901
+ issuer: base,
1902
+ resource: `${base}/mcp`,
1903
+ authorize: `${base}/oauth/authorize`,
1904
+ token: `${base}/oauth/token`,
1905
+ register: `${base}/oauth/register`,
1906
+ resourceMetadata: `${url.origin}/.well-known/oauth-protected-resource${url.pathname}/mcp`
1907
+ };
1908
+ }
1909
+ OfferOAuthUtil.urls = urls;
1910
+ function resourceMetadata(base, name) {
1911
+ const at = urls(base);
1912
+ return json(200, {
1913
+ resource: at.resource,
1914
+ authorization_servers: [at.issuer],
1915
+ scopes_supported: [MCP_SCOPE],
1916
+ bearer_methods_supported: ["header"],
1917
+ resource_name: name
1918
+ });
1919
+ }
1920
+ OfferOAuthUtil.resourceMetadata = resourceMetadata;
1921
+ function serverMetadata(base) {
1922
+ const at = urls(base);
1923
+ return json(200, {
1924
+ issuer: at.issuer,
1925
+ authorization_endpoint: at.authorize,
1926
+ token_endpoint: at.token,
1927
+ registration_endpoint: at.register,
1928
+ scopes_supported: [MCP_SCOPE],
1929
+ response_types_supported: ["code"],
1930
+ response_modes_supported: ["query"],
1931
+ grant_types_supported: ["authorization_code", "refresh_token"],
1932
+ code_challenge_methods_supported: ["S256"],
1933
+ token_endpoint_auth_methods_supported: ["none"],
1934
+ client_id_metadata_document_supported: true,
1935
+ authorization_response_iss_parameter_supported: true
1936
+ });
1937
+ }
1938
+ OfferOAuthUtil.serverMetadata = serverMetadata;
1939
+ function error(status, code, description) {
1940
+ return json(status, { error: code, error_description: description });
1941
+ }
1942
+ OfferOAuthUtil.error = error;
1943
+ function challenge(base, message, invalid) {
1944
+ const parts = [
1945
+ ...base ? [`resource_metadata="${urls(base).resourceMetadata}"`] : [],
1946
+ `scope="${MCP_SCOPE}"`,
1947
+ ...invalid ? ['error="invalid_token"'] : []
1948
+ ];
1949
+ return json(401, { error: invalid ? "invalid_token" : "unauthorized", error_description: message }, { "www-authenticate": `Bearer ${parts.join(", ")}` });
1950
+ }
1951
+ OfferOAuthUtil.challenge = challenge;
1952
+ function redirectable(uri) {
1953
+ if (typeof uri !== "string" || uri.length > 500) {
1954
+ return false;
1955
+ }
1956
+ let url;
1957
+ try {
1958
+ url = new URL(uri);
1959
+ } catch {
1960
+ return false;
1961
+ }
1962
+ if (url.hash || uri.includes("#") || url.username || url.password) {
1963
+ return false;
1964
+ }
1965
+ if (url.protocol === "https:") {
1966
+ return true;
1967
+ }
1968
+ if (url.protocol === "http:") {
1969
+ return LOOPBACK.has(url.hostname);
1970
+ }
1971
+ return /^[a-z][a-z0-9+.-]*:$/.test(url.protocol) && !NOT_APPS.has(url.protocol);
1972
+ }
1973
+ OfferOAuthUtil.redirectable = redirectable;
1974
+ function listed(uri, redirects) {
1975
+ return redirects.some((one) => {
1976
+ if (one === uri) {
1977
+ return true;
1978
+ }
1979
+ try {
1980
+ const [a, b] = [new URL(one), new URL(uri)];
1981
+ return a.protocol === "http:" && LOOPBACK.has(a.hostname) && a.hostname === b.hostname && a.pathname === b.pathname && a.search === b.search;
1982
+ } catch {
1983
+ return false;
1984
+ }
1985
+ });
1986
+ }
1987
+ OfferOAuthUtil.listed = listed;
1988
+ function register(secret, name, redirects) {
1989
+ const said = Buffer.from(JSON.stringify({ n: name, r: redirects })).toString("base64url");
1990
+ return `${CLIENT_PREFIX}${said}.${sign(secret, said)}`;
1991
+ }
1992
+ OfferOAuthUtil.register = register;
1993
+ async function client(secret, id, read = fetch) {
1994
+ if (typeof id !== "string" || id.length > 4000) {
1995
+ return;
1996
+ }
1997
+ if (id.startsWith(CLIENT_PREFIX)) {
1998
+ const [said, signature] = id.slice(CLIENT_PREFIX.length).split(".");
1999
+ if (!secret || !said || !signature || !same(signature, sign(secret, said))) {
2000
+ return;
2001
+ }
2002
+ try {
2003
+ const { n: n2, r } = JSON.parse(Buffer.from(said, "base64url").toString("utf8"));
2004
+ return { id, name: n2, redirects: r };
2005
+ } catch {
2006
+ return;
2007
+ }
2008
+ }
2009
+ return document(id, read);
2010
+ }
2011
+ OfferOAuthUtil.client = client;
2012
+ function verifies(verifier, challenge2) {
2013
+ if (typeof verifier !== "string" || !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) {
2014
+ return false;
2015
+ }
2016
+ return same(createHash3("sha256").update(verifier).digest("base64url"), challenge2);
2017
+ }
2018
+ OfferOAuthUtil.verifies = verifies;
2019
+ function nameOf(value, fallback) {
2020
+ const name = typeof value === "string" ? value.replace(/\p{Cc}|[<>]/gu, "").trim().slice(0, 60) : "";
2021
+ return name || fallback;
2022
+ }
2023
+ OfferOAuthUtil.nameOf = nameOf;
2024
+ const documents = new Map;
2025
+ async function document(id, read) {
2026
+ let url;
2027
+ try {
2028
+ url = new URL(id);
2029
+ } catch {
2030
+ return;
2031
+ }
2032
+ const host = url.hostname;
2033
+ if (url.protocol !== "https:" || url.pathname === "/" || url.hash || url.username || /^[\d.]+$|^\[|^localhost$|\.local$|\.localhost$|\.internal$/i.test(host) || !host.includes(".")) {
2034
+ return;
2035
+ }
2036
+ const now = Date.now();
2037
+ const kept = documents.get(id);
2038
+ if (kept && kept.until > now) {
2039
+ return kept.client;
2040
+ }
2041
+ let client2;
2042
+ try {
2043
+ const answer2 = await read(id, { redirect: "error", signal: AbortSignal.timeout(DOCUMENT_MS), headers: { accept: "application/json" } });
2044
+ const text = answer2.ok ? await answer2.text() : "";
2045
+ const value = text && text.length <= DOCUMENT_BYTES ? JSON.parse(text) : undefined;
2046
+ const redirects = Array.isArray(value?.redirect_uris) ? value.redirect_uris.filter(redirectable).slice(0, 10) : [];
2047
+ if (value && value.client_id === id && redirects.length) {
2048
+ client2 = { id, name: nameOf(value.client_name, host), redirects };
2049
+ }
2050
+ } catch {
2051
+ client2 = undefined;
2052
+ }
2053
+ documents.set(id, { ...client2 ? { client: client2 } : {}, until: now + DOCUMENT_KEEP_MS });
2054
+ for (const [other, one] of documents) {
2055
+ if (one.until <= now) {
2056
+ documents.delete(other);
2057
+ }
2058
+ }
2059
+ return client2;
2060
+ }
2061
+ function sign(secret, text) {
2062
+ return createHmac("sha256", secret).update(text).digest("base64url").slice(0, 32);
2063
+ }
2064
+ function same(a, b) {
2065
+ const [x, y] = [Buffer.from(a), Buffer.from(b)];
2066
+ return x.length === y.length && timingSafeEqual(x, y);
2067
+ }
2068
+ })(OfferOAuthUtil ||= {});
2069
+
2070
+ // web-src/offer-mcp-wire.ts
2071
+ var MCP_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26"];
2072
+ var MCP_PING_MS = 20000;
2073
+ var MCP_ERRORS = { parse: -32700, request: -32600, method: -32601, params: -32602, internal: -32603 };
2074
+ var HEADERS = { "cache-control": "no-store", ...CORS };
2075
+ var OfferMcpWire;
2076
+ ((OfferMcpWire) => {
2077
+ function read(body) {
2078
+ let value;
2079
+ try {
2080
+ value = JSON.parse(body || "null");
2081
+ } catch {
2082
+ return "parse";
2083
+ }
2084
+ const message = value;
2085
+ return message && typeof message === "object" && !Array.isArray(message) && message.jsonrpc === "2.0" ? message : "request";
2086
+ }
2087
+ OfferMcpWire.read = read;
2088
+ function result(id, result2) {
2089
+ return JSON.stringify({ jsonrpc: "2.0", id: id ?? null, result: result2 });
2090
+ }
2091
+ OfferMcpWire.result = result;
2092
+ function error(id, code, message) {
2093
+ return JSON.stringify({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });
2094
+ }
2095
+ OfferMcpWire.error = error;
2096
+ function notification(method, params) {
2097
+ return JSON.stringify({ jsonrpc: "2.0", method, params });
2098
+ }
2099
+ OfferMcpWire.notification = notification;
2100
+ function json2(message, status = 200) {
2101
+ return { status, headers: { "content-type": "application/json; charset=utf-8", ...HEADERS }, body: message };
2102
+ }
2103
+ OfferMcpWire.json = json2;
2104
+ function accepted() {
2105
+ return { status: 202, headers: { ...HEADERS } };
2106
+ }
2107
+ OfferMcpWire.accepted = accepted;
2108
+ function event(message) {
2109
+ return `event: message
2110
+ data: ${message}
2111
+
2112
+ `;
2113
+ }
2114
+ OfferMcpWire.event = event;
2115
+ function streams(headers) {
2116
+ return (headers.accept ?? "").includes("text/event-stream");
2117
+ }
2118
+ OfferMcpWire.streams = streams;
2119
+ async function answer(headers, work) {
2120
+ if (!streams(headers)) {
2121
+ return json2(await work(() => {
2122
+ return;
2123
+ }));
2124
+ }
2125
+ const pipe = new Pipe;
2126
+ const timer = setInterval(() => pipe.push(`: ping
2127
+
2128
+ `), MCP_PING_MS);
2129
+ timer.unref?.();
2130
+ work((message) => pipe.push(event(message))).catch((failure) => error(undefined, MCP_ERRORS.internal, failure instanceof Error ? failure.message : String(failure))).then((last) => {
2131
+ clearInterval(timer);
2132
+ pipe.push(event(last));
2133
+ pipe.close();
2134
+ });
2135
+ return { status: 200, headers: { "content-type": "text/event-stream; charset=utf-8", ...HEADERS }, body: pipe.read() };
2136
+ }
2137
+ OfferMcpWire.answer = answer;
2138
+ })(OfferMcpWire ||= {});
2139
+
2140
+ class Pipe {
2141
+ queue = [];
2142
+ wake;
2143
+ closed = false;
2144
+ push(text) {
2145
+ if (!this.closed) {
2146
+ this.queue.push(text);
2147
+ this.wake?.();
2148
+ }
2149
+ }
2150
+ close() {
2151
+ this.closed = true;
2152
+ this.wake?.();
2153
+ }
2154
+ async* read() {
2155
+ for (;; ) {
2156
+ const text = this.queue.shift();
2157
+ if (text !== undefined) {
2158
+ yield text;
2159
+ } else if (this.closed) {
2160
+ return;
2161
+ } else {
2162
+ await new Promise((resolve) => {
2163
+ this.wake = resolve;
2164
+ });
2165
+ this.wake = undefined;
2166
+ }
2167
+ }
2168
+ }
2169
+ }
2170
+
2171
+ // web-src/offer-mcp.ts
2172
+ var TOOL = "ask";
2173
+ var RELATED = "io.modelcontextprotocol/related-task";
2174
+ var PROGRESS_MS = 1000;
2175
+ var PROGRESS_CHARS = 200;
2176
+ var failed = (text) => ({ content: [{ type: "text", text }], isError: true });
2177
+
2178
+ class OfferMcp {
2179
+ ctx;
2180
+ tasks = new OfferMcpTasks;
2181
+ constructor(ctx) {
2182
+ this.ctx = ctx;
2183
+ }
2184
+ async http(request) {
2185
+ const method = request.method.toUpperCase();
2186
+ if (method === "OPTIONS") {
2187
+ return { status: 204, headers: { ...CORS } };
2188
+ }
2189
+ const caller = this.ctx.calls.caller(request.headers, "mcp");
2190
+ if ("refused" in caller) {
2191
+ return caller.status === 401 ? OfferOAuthUtil.challenge(request.base, caller.message, !!request.headers.authorization) : OfferOAuthUtil.answer(caller.status, { error: caller.code, error_description: caller.message });
2192
+ }
2193
+ if (method !== "POST") {
2194
+ return { status: 405, headers: { allow: "POST, OPTIONS", ...CORS } };
2195
+ }
2196
+ const message = OfferMcpWire.read(request.body);
2197
+ if (typeof message === "string") {
2198
+ return OfferMcpWire.json(OfferMcpWire.error(undefined, message === "parse" ? MCP_ERRORS.parse : MCP_ERRORS.request, "Not a JSON-RPC message."), 400);
2199
+ }
2200
+ if (message.id === undefined || !message.method) {
2201
+ return OfferMcpWire.accepted();
2202
+ }
2203
+ return this.answer(caller, message, request);
2204
+ }
2205
+ async answer(caller, message, request) {
2206
+ const { id } = message;
2207
+ const params = message.params ?? {};
2208
+ const owner = caller.user.id;
2209
+ const reply = (result) => OfferMcpWire.json(OfferMcpWire.result(id, result));
2210
+ const wrong = (code, text) => OfferMcpWire.json(OfferMcpWire.error(id, code, text));
2211
+ switch (message.method) {
2212
+ case "initialize": {
2213
+ const asked = String(params.protocolVersion ?? "");
2214
+ return reply({
2215
+ protocolVersion: MCP_VERSIONS.includes(asked) ? asked : MCP_VERSIONS[0],
2216
+ capabilities: { tools: {}, tasks: { list: {}, cancel: {}, requests: { tools: { call: {} } } } },
2217
+ serverInfo: { name: "ta-offer", title: caller.offer.name, version: "1" },
2218
+ instructions: this.describe(caller)
2219
+ });
2220
+ }
2221
+ case "ping":
2222
+ return reply({});
2223
+ case "tools/list":
2224
+ return reply({ tools: [this.tool(caller)] });
2225
+ case "tools/call":
2226
+ return this.call(caller, id, params, request);
2227
+ case "tasks/get": {
2228
+ const task = this.tasks.get(owner, params.taskId);
2229
+ return task ? reply(task) : wrong(MCP_ERRORS.params, "Failed to retrieve task: Task not found");
2230
+ }
2231
+ case "tasks/list":
2232
+ return params.cursor ? wrong(MCP_ERRORS.params, "Invalid cursor.") : reply({ tasks: this.tasks.list(owner) });
2233
+ case "tasks/cancel": {
2234
+ const task = this.tasks.cancel(owner, params.taskId);
2235
+ return task === "ended" ? wrong(MCP_ERRORS.params, "Cannot cancel task: already in a terminal status") : task ? reply(task) : wrong(MCP_ERRORS.params, "Failed to cancel task: Task not found");
2236
+ }
2237
+ case "tasks/result":
2238
+ if (!this.tasks.get(owner, params.taskId)) {
2239
+ return wrong(MCP_ERRORS.params, "Failed to retrieve task: Task not found");
2240
+ }
2241
+ return OfferMcpWire.answer(request.headers, async () => {
2242
+ const done = await this.tasks.result(owner, params.taskId);
2243
+ return done ? OfferMcpWire.result(id, { ...done.result, _meta: { [RELATED]: { taskId: done.task.taskId } } }) : OfferMcpWire.error(id, MCP_ERRORS.params, "Failed to retrieve task: Task has expired");
2244
+ });
2245
+ default:
2246
+ return wrong(MCP_ERRORS.method, `No method ${message.method}.`);
2247
+ }
2248
+ }
2249
+ async call(caller, id, params, request) {
2250
+ const args = params.arguments ?? {};
2251
+ if (params.name !== TOOL) {
2252
+ return OfferMcpWire.json(OfferMcpWire.error(id, MCP_ERRORS.params, `No tool ${String(params.name)}; this server has "${TOOL}".`));
2253
+ }
2254
+ if (typeof args.message !== "string" || !args.message.trim() || args.conversation !== undefined && typeof args.conversation !== "string") {
2255
+ return OfferMcpWire.json(OfferMcpWire.result(id, failed('Give "message" (text), and "conversation" (an id ask gave) to go on with one.')));
2256
+ }
2257
+ const input = { text: args.message, ...args.conversation ? { conversation: args.conversation } : {} };
2258
+ const task = params.task;
2259
+ if (task && typeof task === "object") {
2260
+ const made = this.tasks.start(caller.user.id, task.ttl, (signal) => this.ask(caller, input, signal));
2261
+ return OfferMcpWire.json(OfferMcpWire.result(id, { task: made }));
2262
+ }
2263
+ const token = params._meta?.progressToken;
2264
+ return OfferMcpWire.answer(request.headers, async (notify) => {
2265
+ let said = "";
2266
+ let at = 0;
2267
+ let n2 = 0;
2268
+ const result = await this.ask(caller, input, request.signal, (part) => {
2269
+ said += part;
2270
+ n2 += 1;
2271
+ const now = Date.now();
2272
+ if ((typeof token === "string" || typeof token === "number") && now - at >= PROGRESS_MS) {
2273
+ at = now;
2274
+ notify(OfferMcpWire.notification("notifications/progress", { progressToken: token, progress: n2, message: said.slice(-PROGRESS_CHARS) }));
2275
+ }
2276
+ });
2277
+ return OfferMcpWire.result(id, result);
2278
+ });
2279
+ }
2280
+ async ask(caller, input, signal, part) {
2281
+ const call = await this.ctx.calls.ask(caller, input, signal);
2282
+ if ("refused" in call) {
2283
+ return failed(call.message);
2284
+ }
2285
+ for await (const text of call.turn.parts) {
2286
+ part?.(text);
2287
+ }
2288
+ const end = await call.turn.done;
2289
+ const short = OfferCalls.failure(end);
2290
+ if (short) {
2291
+ return failed(short.message);
2292
+ }
2293
+ return {
2294
+ content: [
2295
+ { type: "text", text: end.text },
2296
+ { type: "text", text: `(To go on with this conversation, call ${TOOL} with conversation "${call.conversation}".)` }
2297
+ ],
2298
+ structuredContent: { answer: end.text, conversation: call.conversation }
2299
+ };
2300
+ }
2301
+ describe(caller) {
2302
+ const { offer, member } = caller;
2303
+ const intro = offer.intro ? `: ${offer.intro}` : ".";
2304
+ return `${offer.name}, an agent of ${member.owner} opened to you through Ta${intro} Ask it with the tool ${TOOL}; each call is a turn of a conversation, and the id it gives goes on with it.`;
2305
+ }
2306
+ tool(caller) {
2307
+ return {
2308
+ name: TOOL,
2309
+ title: caller.offer.name,
2310
+ description: `${this.describe(caller)} What it uses counts in your plan.`,
2311
+ inputSchema: {
2312
+ type: "object",
2313
+ properties: {
2314
+ message: { type: "string", description: "What to ask or tell it." },
2315
+ conversation: { type: "string", description: "The conversation to go on with, as an earlier call gave it; none starts a new one." }
2316
+ },
2317
+ required: ["message"],
2318
+ additionalProperties: false
2319
+ },
2320
+ outputSchema: {
2321
+ type: "object",
2322
+ properties: { answer: { type: "string" }, conversation: { type: "string" } },
2323
+ required: ["answer", "conversation"]
2324
+ },
2325
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
2326
+ execution: { taskSupport: "optional" }
2327
+ };
2328
+ }
2329
+ }
2330
+
2331
+ // web-src/offer-meter.ts
2332
+ class OfferMeterBook {
2333
+ ctx;
2334
+ constructor(ctx) {
2335
+ this.ctx = ctx;
2336
+ }
2337
+ userOf(sessionFile) {
2338
+ return sessionFile ? this.ctx.data.users.find((user) => user.sessions.includes(sessionFile)) : undefined;
2339
+ }
2340
+ gate(sessionFile, marked, now = Date.now()) {
2341
+ const user = this.userOf(sessionFile);
2342
+ if (!user) {
2343
+ return marked ? OfferTexts.blocked("closed") : undefined;
2344
+ }
2345
+ const state = this.ctx.state(user, now);
2346
+ return state.block === "none" ? undefined : OfferTexts.blocked(state.block);
2347
+ }
2348
+ async meter(sessionFile, usage, now = Date.now()) {
2349
+ const user = this.userOf(sessionFile);
2350
+ const tokens = OfferQuota.tokensOf(usage);
2351
+ if (!user || tokens <= 0) {
2352
+ return;
2353
+ }
2354
+ user.used = OfferQuota.add(user.used, tokens, usage?.cost?.total ?? 0, now);
2355
+ user.lastAt = now;
2356
+ await this.ctx.commit();
2357
+ }
2358
+ }
2359
+
2360
+ // web-src/offer-oauth.ts
2361
+ import { randomBytes as randomBytes3, randomUUID as randomUUID4 } from "node:crypto";
2362
+
2363
+ // web-src/offer-oauth-page.ts
2364
+ var WORDS = {
2365
+ "zh-CN": {
2366
+ title: "连接到 Ta",
2367
+ asks: "「{client}」想以你的身份使用开放给你的智能体。",
2368
+ where: "连上后会回到:{where}",
2369
+ how: "在 Ta 的「开放给我的」里点「连接 MCP 客户端」,把显示的连接码填在下面。不是你自己发起的,关掉这页就好。",
2370
+ code: "连接码",
2371
+ connect: "连接",
2372
+ wrong: "连接码不对或已过期,回 Ta 里重新拿一个。",
2373
+ blocked: "试错太多次了,10 分钟后再试。",
2374
+ bad: "这个连接请求不完整,回到客户端重新连接。",
2375
+ off: "提供者关掉了 API 调用,暂时连不上。"
2376
+ },
2377
+ "zh-TW": {
2378
+ title: "連接到 Ta",
2379
+ asks: "「{client}」想以你的身分使用開放給你的智慧體。",
2380
+ where: "連上後會回到:{where}",
2381
+ how: "在 Ta 的「開放給我的」裡點「連接 MCP 用戶端」,把顯示的連接碼填在下面。不是你自己發起的,關掉這頁就好。",
2382
+ code: "連接碼",
2383
+ connect: "連接",
2384
+ wrong: "連接碼不對或已過期,回 Ta 裡重新拿一個。",
2385
+ blocked: "試錯太多次了,10 分鐘後再試。",
2386
+ bad: "這個連接請求不完整,回到用戶端重新連接。",
2387
+ off: "提供者關掉了 API 呼叫,暫時連不上。"
2388
+ },
2389
+ "en-US": {
2390
+ title: "Connect to Ta",
2391
+ asks: "“{client}” wants to use the agent opened to you, as you.",
2392
+ where: "Once connected it goes back to: {where}",
2393
+ how: "In Ta, open Opened to me and tap Connect an MCP client, then type the code it shows below. If you did not start this, just close the page.",
2394
+ code: "Code",
2395
+ connect: "Connect",
2396
+ wrong: "That code is wrong or expired; get a new one in Ta.",
2397
+ blocked: "Too many wrong tries; try again in 10 minutes.",
2398
+ bad: "This request to connect is incomplete; connect again from the client.",
2399
+ off: "The owner turned off the API; it cannot connect for now."
2400
+ },
2401
+ "ja-JP": {
2402
+ title: "Ta に接続",
2403
+ asks: "「{client}」があなたとして、公開されたエージェントを使おうとしています。",
2404
+ where: "接続後の戻り先:{where}",
2405
+ how: "Ta の「公開されたもの」で「MCP クライアントを接続」を押し、表示された接続コードを下に入力してください。心当たりがなければこのページを閉じてください。",
2406
+ code: "接続コード",
2407
+ connect: "接続",
2408
+ wrong: "接続コードが違うか期限切れです。Ta で新しいコードを取得してください。",
2409
+ blocked: "失敗が多すぎます。10 分後にもう一度お試しください。",
2410
+ bad: "この接続リクエストは不完全です。クライアントから接続し直してください。",
2411
+ off: "提供者が API を停止しました。今は接続できません。"
2412
+ }
2413
+ };
2414
+ var htmlOf = (text) => text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
2415
+ var STYLE = `
2416
+ :root{color-scheme:light dark;--fg:#1f1f1f;--muted:#6b6b6b;--line:#e5e5e5;--bg:#f7f7f7;--card:#fff;--accent:#16a34a;--bad:#dc2626}
2417
+ @media (prefers-color-scheme:dark){:root{--fg:#ececec;--muted:#9a9a9a;--line:#333;--bg:#141414;--card:#1e1e1e}}
2418
+ *{box-sizing:border-box}body{margin:0;font:.9375rem/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC",sans-serif;background:var(--bg);color:var(--fg)}
2419
+ main{max-width:420px;margin:12vh auto 0;padding:0 16px}.card{background:var(--card);border:1px solid var(--line);border-radius:16px;padding:24px}
2420
+ h1{font-size:1.25rem;font-weight:600;margin:0 0 12px}p{margin:0 0 10px}.muted{color:var(--muted);font-size:.8125rem;word-break:break-all}
2421
+ .error{color:var(--bad);font-size:.875rem}label{display:block;font-size:.8125rem;color:var(--muted);margin:16px 0 6px}
2422
+ input{width:100%;font:600 1.375rem/1.2 ui-monospace,Menlo,monospace;letter-spacing:.12em;text-transform:uppercase;padding:12px 14px;border:1px solid var(--line);border-radius:10px;background:transparent;color:inherit}
2423
+ button{margin-top:16px;width:100%;padding:12px;border:0;border-radius:10px;background:var(--accent);color:#fff;font-family:inherit;font-weight:600;font-size:.9375rem;line-height:1;cursor:pointer}
2424
+ `;
2425
+ var OfferOAuthPage;
2426
+ ((OfferOAuthPage) => {
2427
+ function language(headers) {
2428
+ return TaLanguageUtil.of(headers["accept-language"]?.split(",")[0]);
2429
+ }
2430
+ OfferOAuthPage.language = language;
2431
+ function ask(language2, client, redirect, action2, problem) {
2432
+ const words = WORDS[language2];
2433
+ let where = redirect;
2434
+ try {
2435
+ const url = new URL(redirect);
2436
+ where = url.host ? `${url.protocol}//${url.host}` : url.protocol;
2437
+ } catch {}
2438
+ const body = `<h1>${htmlOf(words.title)}</h1>
2439
+ <p>${htmlOf(words.asks.replace("{client}", client))}</p>
2440
+ <p class="muted">${htmlOf(words.where.replace("{where}", where))}</p>
2441
+ <p class="muted">${htmlOf(words.how)}</p>
2442
+ ${problem ? `<p class="error">${htmlOf(words[problem])}</p>` : ""}
2443
+ <form method="post" action="?${htmlOf(action2)}">
2444
+ <label for="code">${htmlOf(words.code)}</label>
2445
+ <input id="code" name="code" autocomplete="one-time-code" autocapitalize="characters" spellcheck="false" maxlength="16" required autofocus placeholder="XXXXX-XXXXX">
2446
+ <button type="submit">${htmlOf(words.connect)}</button>
2447
+ </form>`;
2448
+ return html(language2, words.title, body, problem === "blocked" ? 429 : problem ? 400 : 200);
2449
+ }
2450
+ OfferOAuthPage.ask = ask;
2451
+ function failed2(language2, problem) {
2452
+ const words = WORDS[language2];
2453
+ return html(language2, words.title, `<h1>${htmlOf(words.title)}</h1><p class="error">${htmlOf(words[problem])}</p>`, problem === "off" ? 403 : 400);
2454
+ }
2455
+ OfferOAuthPage.failed = failed2;
2456
+ function html(language2, title, body, status) {
2457
+ return {
2458
+ status,
2459
+ headers: {
2460
+ "content-type": "text/html; charset=utf-8",
2461
+ "cache-control": "no-store",
2462
+ "referrer-policy": "no-referrer",
2463
+ "x-frame-options": "DENY",
2464
+ "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'"
2465
+ },
2466
+ body: `<!doctype html><html lang="${language2}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${htmlOf(title)}</title><style>${STYLE}</style></head><body><main><div class="card">${body}</div></main></body></html>`
2467
+ };
2468
+ }
2469
+ })(OfferOAuthPage ||= {});
2470
+
2471
+ // web-src/offer-oauth.ts
2472
+ var CODE_MS = 5 * 60000;
2473
+ var ACCESS_MS = 60 * 60000;
2474
+ var REFRESH_MS = 30 * 24 * 60 * 60000;
2475
+ var CODES_MAX = 500;
2476
+ var form = (request) => {
2477
+ if ((request.headers["content-type"] ?? "").includes("application/json")) {
2478
+ try {
2479
+ const value = JSON.parse(request.body || "{}");
2480
+ return new URLSearchParams(Object.entries(value).flatMap(([key, one]) => typeof one === "string" ? [[key, one]] : []));
2481
+ } catch {
2482
+ return new URLSearchParams;
2483
+ }
2484
+ }
2485
+ return new URLSearchParams(request.body);
2486
+ };
2487
+ var sendBack = (redirect, params) => {
2488
+ const url = new URL(redirect);
2489
+ for (const [key, value] of Object.entries(params)) {
2490
+ if (value !== undefined) {
2491
+ url.searchParams.set(key, value);
2492
+ }
2493
+ }
2494
+ return { status: 303, headers: { location: url.toString(), "cache-control": "no-store", "referrer-policy": "no-referrer" } };
2495
+ };
2496
+
2497
+ class OfferOAuth {
2498
+ ctx;
2499
+ codes = new Map;
2500
+ constructor(ctx) {
2501
+ this.ctx = ctx;
2502
+ }
2503
+ async http(request) {
2504
+ const path = request.path.replace(/\/+$/, "");
2505
+ const method = request.method.toUpperCase();
2506
+ const known = /^\.well-known\/(oauth-protected-resource|oauth-authorization-server|openid-configuration)(\/mcp)?$/.exec(path);
2507
+ if (!known && !path.startsWith("oauth/")) {
2508
+ return;
2509
+ }
2510
+ if (method === "OPTIONS") {
2511
+ return { status: 204, headers: { ...CORS } };
2512
+ }
2513
+ const { base } = request;
2514
+ if (!base) {
2515
+ return OfferOAuthUtil.error(404, "not_found", "This relay does not pass the address OAuth needs; use an API key.");
2516
+ }
2517
+ if (known) {
2518
+ return known[1] === "oauth-protected-resource" ? OfferOAuthUtil.resourceMetadata(base, "Ta") : OfferOAuthUtil.serverMetadata(base);
2519
+ }
2520
+ if (path === "oauth/register" && method === "POST") {
2521
+ return this.register(request);
2522
+ }
2523
+ if (path === "oauth/authorize" && (method === "GET" || method === "POST")) {
2524
+ return this.authorize(request, base);
2525
+ }
2526
+ if (path === "oauth/token" && method === "POST") {
2527
+ return this.token(request, base);
2528
+ }
2529
+ return OfferOAuthUtil.error(404, "not_found", "No such endpoint.");
2530
+ }
2531
+ async register(request) {
2532
+ let said;
2533
+ try {
2534
+ said = JSON.parse(request.body || "{}");
2535
+ } catch {
2536
+ return OfferOAuthUtil.error(400, "invalid_client_metadata", "The body is not JSON.");
2537
+ }
2538
+ const redirects = Array.isArray(said.redirect_uris) ? said.redirect_uris : [];
2539
+ if (!redirects.length || redirects.length > 5 || !redirects.every(OfferOAuthUtil.redirectable)) {
2540
+ return OfferOAuthUtil.error(400, "invalid_redirect_uri", "redirect_uris: 1 to 5, https, http to localhost, or an app scheme.");
2541
+ }
2542
+ if (said.token_endpoint_auth_method !== undefined && said.token_endpoint_auth_method !== "none") {
2543
+ return OfferOAuthUtil.error(400, "invalid_client_metadata", 'Only public clients (token_endpoint_auth_method "none").');
2544
+ }
2545
+ const name = OfferOAuthUtil.nameOf(said.client_name, "MCP client");
2546
+ const id = OfferOAuthUtil.register(await this.secret(), name, redirects);
2547
+ return OfferOAuthUtil.answer(201, {
2548
+ client_id: id,
2549
+ client_id_issued_at: Math.floor(Date.now() / 1000),
2550
+ client_name: name,
2551
+ redirect_uris: redirects,
2552
+ grant_types: ["authorization_code", "refresh_token"],
2553
+ response_types: ["code"],
2554
+ token_endpoint_auth_method: "none",
2555
+ scope: MCP_SCOPE
2556
+ });
2557
+ }
2558
+ async authorize(request, base) {
2559
+ const language = OfferOAuthPage.language(request.headers);
2560
+ const asked = await this.asked(new URLSearchParams(request.query), base);
2561
+ if (!asked.ok) {
2562
+ return asked.back ? sendBack(asked.back.redirect, { error: asked.back.error, state: asked.back.state, iss: base }) : OfferOAuthPage.failed(language, asked.problem);
2563
+ }
2564
+ if (request.method.toUpperCase() === "GET") {
2565
+ return OfferOAuthPage.ask(language, asked.client.name, asked.redirect, request.query);
2566
+ }
2567
+ const taken = this.ctx.connects.take(form(request).get("code"), request.client);
2568
+ if (taken === "wrong" || taken === "blocked") {
2569
+ return OfferOAuthPage.ask(language, asked.client.name, asked.redirect, request.query, taken);
2570
+ }
2571
+ const user = this.ctx.data.users.find((one) => one.id === taken);
2572
+ const offer = user && this.ctx.data.offers.find((one) => one.id === user.offer);
2573
+ if (!user || !offer || offer.api === false) {
2574
+ return OfferOAuthPage.failed(language, "off");
2575
+ }
2576
+ const now = Date.now();
2577
+ for (const [hash, one] of this.codes) {
2578
+ if (one.until <= now || this.codes.size > CODES_MAX) {
2579
+ this.codes.delete(hash);
2580
+ }
2581
+ }
2582
+ const code = OfferKeys.secret(TOKEN_PREFIX.code);
2583
+ this.codes.set(code.hash, {
2584
+ user: user.id,
2585
+ client: asked.client,
2586
+ redirect: asked.redirect,
2587
+ challenge: asked.challenge,
2588
+ ...asked.resource ? { resource: asked.resource } : {},
2589
+ until: now + CODE_MS
2590
+ });
2591
+ return sendBack(asked.redirect, { code: code.value, state: asked.state, iss: base });
2592
+ }
2593
+ async asked(params, base) {
2594
+ const client = await OfferOAuthUtil.client(this.ctx.data.secret, params.get("client_id"));
2595
+ const redirect = params.get("redirect_uri") ?? (client?.redirects.length === 1 ? client.redirects[0] : "");
2596
+ if (!client || !redirect || !OfferOAuthUtil.redirectable(redirect) || !OfferOAuthUtil.listed(redirect, client.redirects)) {
2597
+ return { ok: false, problem: "bad" };
2598
+ }
2599
+ const state = params.get("state") ?? undefined;
2600
+ const back = (error) => ({ ok: false, problem: "bad", back: { redirect, error, ...state ? { state } : {} } });
2601
+ const challenge = params.get("code_challenge") ?? "";
2602
+ if (params.get("response_type") !== "code") {
2603
+ return back("unsupported_response_type");
2604
+ }
2605
+ if (params.get("code_challenge_method") !== "S256" || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) {
2606
+ return back("invalid_request");
2607
+ }
2608
+ const scope = params.get("scope");
2609
+ if (scope && !scope.split(" ").every((one) => one === MCP_SCOPE || one === "")) {
2610
+ return back("invalid_scope");
2611
+ }
2612
+ const resource = params.get("resource") ?? undefined;
2613
+ if (resource && !this.ours(resource, base)) {
2614
+ return back("invalid_target");
2615
+ }
2616
+ return { ok: true, client, redirect, challenge, ...state ? { state } : {}, ...resource ? { resource } : {} };
2617
+ }
2618
+ async token(request, base) {
2619
+ const params = form(request);
2620
+ const now = Date.now();
2621
+ const resource = params.get("resource");
2622
+ if (resource && !this.ours(resource, base)) {
2623
+ return OfferOAuthUtil.error(400, "invalid_target", "The resource is not this MCP server.");
2624
+ }
2625
+ if (params.get("grant_type") === "authorization_code") {
2626
+ const hash = OfferKeys.hashOf(params.get("code") ?? "");
2627
+ const granted = this.codes.get(hash);
2628
+ this.codes.delete(hash);
2629
+ if (!granted || granted.until <= now || granted.client.id !== params.get("client_id") || params.has("redirect_uri") && params.get("redirect_uri") !== granted.redirect || !OfferOAuthUtil.verifies(params.get("code_verifier"), granted.challenge)) {
2630
+ return OfferOAuthUtil.error(400, "invalid_grant", "The code is not valid.");
2631
+ }
2632
+ const user = this.ctx.data.users.find((one) => one.id === granted.user);
2633
+ return user ? this.issue(user, granted.client, now) : OfferOAuthUtil.error(400, "invalid_grant", "No one of this code uses the offer now.");
2634
+ }
2635
+ if (params.get("grant_type") === "refresh_token") {
2636
+ const hash = OfferKeys.hashOf(params.get("refresh_token") ?? "");
2637
+ for (const user of this.ctx.data.users) {
2638
+ const held = user.clients?.find((one) => one.refresh === hash);
2639
+ if (held) {
2640
+ if (held.refreshUntil <= now || held.client !== params.get("client_id")) {
2641
+ return OfferOAuthUtil.error(400, "invalid_grant", "The refresh token is not valid.");
2642
+ }
2643
+ return this.issue(user, { id: held.client, name: held.name, redirects: [] }, now, held);
2644
+ }
2645
+ }
2646
+ return OfferOAuthUtil.error(400, "invalid_grant", "The refresh token is not valid.");
2647
+ }
2648
+ return OfferOAuthUtil.error(400, "unsupported_grant_type", "authorization_code or refresh_token.");
2649
+ }
2650
+ async issue(user, client, now, held) {
2651
+ const offer = this.ctx.data.offers.find((one) => one.id === user.offer);
2652
+ if (!offer || offer.api === false) {
2653
+ return OfferOAuthUtil.error(400, "invalid_grant", "The owner turned off the API of this agent.");
2654
+ }
2655
+ const access = OfferKeys.secret(TOKEN_PREFIX.access);
2656
+ const refresh = OfferKeys.secret(TOKEN_PREFIX.refresh);
2657
+ const tokens = { access: access.hash, accessUntil: now + ACCESS_MS, refresh: refresh.hash, refreshUntil: now + REFRESH_MS };
2658
+ if (held) {
2659
+ Object.assign(held, tokens, { lastAt: now });
2660
+ await this.ctx.commit();
2661
+ } else {
2662
+ const added = { id: randomUUID4(), name: client.name, client: client.id, ...tokens, createdAt: now };
2663
+ user.clients = [...user.clients ?? [], added].slice(-LIMITS.clients);
2664
+ await this.ctx.commit({ what: "client", offer: user.offer, user: user.id, by: user.member });
2665
+ }
2666
+ return OfferOAuthUtil.answer(200, {
2667
+ access_token: access.value,
2668
+ token_type: "Bearer",
2669
+ expires_in: ACCESS_MS / 1000,
2670
+ refresh_token: refresh.value,
2671
+ scope: MCP_SCOPE
2672
+ });
2673
+ }
2674
+ ours(resource, base) {
2675
+ const trimmed = resource.replace(/\/+$/, "");
2676
+ return trimmed === OfferOAuthUtil.urls(base).resource || trimmed === base;
2677
+ }
2678
+ async secret() {
2679
+ if (!this.ctx.data.secret) {
2680
+ this.ctx.data.secret = randomBytes3(32).toString("base64url");
2681
+ await this.ctx.commit();
2682
+ }
2683
+ return this.ctx.data.secret;
2684
+ }
2685
+ }
2686
+
2687
+ // web-src/offer-owner.ts
2688
+ import { randomUUID as randomUUID5 } from "node:crypto";
2689
+ var SHOWN_PAYMENTS = 50;
2690
+ var text = (value, max) => typeof value === "string" ? value.trim().slice(0, max) : "";
2691
+
2692
+ class OfferOwner {
2693
+ ctx;
2694
+ constructor(ctx) {
2695
+ this.ctx = ctx;
2696
+ }
2697
+ async overview() {
2698
+ this.ctx.requireOwner();
2699
+ const { data, links } = this.ctx;
2700
+ const agents = await this.ctx.conversations.agents();
2701
+ const invites = new Set(data.offers.map((offer) => offer.invite?.id).filter((id) => !!id));
2702
+ const joins = await links.waiting(invites);
2703
+ const now = Date.now();
2704
+ const answered = data.payments.filter((one) => one.status !== "waiting").slice(-SHOWN_PAYMENTS);
2705
+ const payee = await this.ctx.store.payee();
2706
+ return {
2707
+ offers: data.offers.map((offer) => {
2708
+ const agent = agents.find((one) => one.id === offer.agent);
2709
+ return {
2710
+ ...offer,
2711
+ ...agent ? { agentName: agent.name, face: agent.face, mark: agent.mark, ...agent.model ? { model: agent.model } : {} } : { gone: true }
2712
+ };
2713
+ }),
2714
+ users: data.users.map(({ keys, calls: _calls, clients, ...user }) => ({
2715
+ ...user,
2716
+ keys: keys?.length ?? 0,
2717
+ clients: clients?.length ?? 0,
2718
+ state: this.ctx.state(user, now),
2719
+ online: links.online(user.member)
2720
+ })),
2721
+ payments: [...data.payments.filter((one) => one.status === "waiting"), ...answered.reverse()],
2722
+ payee: { picture: !!payee.picture, ...payee.note ? { note: payee.note } : {} },
2723
+ joins: joins.map((join2) => ({
2724
+ id: join2.id,
2725
+ offer: data.offers.find((offer) => offer.invite?.id === join2.invite)?.id ?? "",
2726
+ name: join2.name,
2727
+ at: join2.at,
2728
+ ...join2.account ? { account: join2.account.name ?? join2.account.id } : {}
2729
+ }))
2730
+ };
2731
+ }
2732
+ async agents() {
2733
+ this.ctx.requireOwner();
2734
+ return (await this.ctx.conversations.agents()).map(({ id, name, mark, face, model }) => ({
2735
+ id,
2736
+ name,
2737
+ mark,
2738
+ face,
2739
+ role: "",
2740
+ ...model ? { model } : {}
2741
+ }));
2742
+ }
2743
+ async save(input) {
2744
+ this.ctx.requireOwner();
2745
+ const { data } = this.ctx;
2746
+ const before = input?.id ? this.ctx.offer(input.id) : undefined;
2747
+ const agent = await this.ctx.conversations.agent(String(input?.agent ?? before?.agent ?? ""));
2748
+ if (!agent) {
2749
+ throw new OfferError("No such agent.");
2750
+ }
2751
+ const plans = OfferQuota.clean(input?.plans ?? before?.plans, LIMITS);
2752
+ if (!plans.length) {
2753
+ throw new OfferError("An offer needs a plan at least.");
2754
+ }
2755
+ const trial = typeof input?.trial === "string" ? plans.find((plan) => plan.id === input.trial && plan.price === 0)?.id : undefined;
2756
+ const approve = input?.approve !== false;
2757
+ const api = input?.api === undefined ? before?.api !== false : input.api !== false;
2758
+ const offer = {
2759
+ id: before?.id ?? randomUUID5(),
2760
+ agent: agent.id,
2761
+ name: text(input?.name, LIMITS.name) || agent.name,
2762
+ ...text(input?.intro, LIMITS.intro) ? { intro: text(input?.intro, LIMITS.intro) } : {},
2763
+ approve,
2764
+ plans,
2765
+ ...trial ? { trial } : {},
2766
+ ...before?.invite ? { invite: before.invite } : {},
2767
+ ...before?.past ? { past: before.past } : {},
2768
+ ...before?.paused ? { paused: true } : {},
2769
+ ...api ? {} : { api: false },
2770
+ createdAt: before?.createdAt ?? Date.now()
2771
+ };
2772
+ const language = typeof input?.language === "string" ? input.language : undefined;
2773
+ if (!offer.invite) {
2774
+ offer.invite = await this.ctx.links.create(offer.name, approve, language);
2775
+ } else if (before && before.approve !== approve) {
2776
+ await this.ctx.links.setApprove(offer.invite.id, approve);
2777
+ }
2778
+ data.offers = before ? data.offers.map((one) => one.id === offer.id ? offer : one) : [...data.offers, offer];
2779
+ await this.ctx.commit(before ? undefined : { what: "open", offer: offer.id, by: TA_OWNER });
2780
+ return offer;
2781
+ }
2782
+ async renewLink(id, language) {
2783
+ this.ctx.requireOwner();
2784
+ const offer = this.ctx.offer(id);
2785
+ const old = offer.invite;
2786
+ offer.invite = await this.ctx.links.create(offer.name, offer.approve, typeof language === "string" ? language : undefined);
2787
+ if (old) {
2788
+ await this.ctx.links.stop(old.id);
2789
+ offer.past = [...offer.past ?? [], old.id].slice(-20);
2790
+ }
2791
+ await this.ctx.commit();
2792
+ return offer;
2793
+ }
2794
+ async setPaused(id, paused) {
2795
+ this.ctx.requireOwner();
2796
+ const offer = this.ctx.offer(id);
2797
+ offer.paused = paused === true || undefined;
2798
+ await this.ctx.commit({ what: paused === true ? "pause" : "resume", offer: offer.id, by: TA_OWNER });
2799
+ }
2800
+ async remove(id) {
2801
+ this.ctx.requireOwner();
2802
+ const { data, links } = this.ctx;
2803
+ const offer = this.ctx.offer(id);
2804
+ if (offer.invite) {
2805
+ await links.stop(offer.invite.id);
2806
+ }
2807
+ const gone = data.users.filter((user) => user.offer === offer.id);
2808
+ data.offers = data.offers.filter((one) => one !== offer);
2809
+ data.users = data.users.filter((user) => user.offer !== offer.id);
2810
+ for (const member of new Set(gone.map((user) => user.member))) {
2811
+ if (!data.users.some((user) => user.member === member)) {
2812
+ await links.remove(member);
2813
+ }
2814
+ }
2815
+ await this.ctx.commit({ what: "close", offer: offer.id, by: TA_OWNER });
2816
+ }
2817
+ async answerJoin(join2, accept) {
2818
+ this.ctx.requireOwner();
2819
+ await this.ctx.links.answer(String(join2), accept === true);
2820
+ }
2821
+ async answerPayment(id, accept) {
2822
+ this.ctx.requireOwner();
2823
+ const { payment, user } = this.ctx.payments.answer(id, accept === true, TA_OWNER);
2824
+ await this.ctx.commit({
2825
+ what: accept === true ? "paid" : "refused",
2826
+ offer: payment.offer,
2827
+ user: payment.user,
2828
+ plan: payment.plan,
2829
+ amount: payment.amount,
2830
+ by: TA_OWNER
2831
+ });
2832
+ if (user) {
2833
+ await this.ctx.commit({ what: "grant", offer: user.offer, user: user.id, plan: payment.plan, by: TA_OWNER });
2834
+ }
2835
+ }
2836
+ async grant(userId, plan, amount) {
2837
+ this.ctx.requireOwner();
2838
+ const user = this.ctx.user(userId);
2839
+ const payment = this.ctx.payments.offline(user, this.ctx.offer(user.offer), plan, amount, TA_OWNER);
2840
+ await this.ctx.commit({ what: "grant", offer: user.offer, user: user.id, plan: payment.plan, amount: payment.amount, by: TA_OWNER });
2841
+ }
2842
+ async setUserPaused(userId, paused) {
2843
+ this.ctx.requireOwner();
2844
+ const user = this.ctx.user(userId);
2845
+ user.paused = paused === true || undefined;
2846
+ await this.ctx.commit({ what: paused === true ? "pause" : "resume", offer: user.offer, user: user.id, by: TA_OWNER });
2847
+ }
2848
+ async removeUser(userId) {
2849
+ this.ctx.requireOwner();
2850
+ const { data } = this.ctx;
2851
+ const user = this.ctx.user(userId);
2852
+ data.users = data.users.filter((one) => one !== user);
2853
+ if (!data.users.some((one) => one.member === user.member)) {
2854
+ await this.ctx.links.remove(user.member);
2855
+ }
2856
+ await this.ctx.commit({ what: "remove", offer: user.offer, user: user.id, by: TA_OWNER });
2857
+ }
2858
+ async setPayee(input) {
2859
+ this.ctx.requireOwner();
2860
+ const before = await this.ctx.store.payee();
2861
+ let picture = before.picture;
2862
+ if (input?.picture === null) {
2863
+ picture = undefined;
2864
+ } else if (input?.picture !== undefined) {
2865
+ if (typeof input.picture !== "string" || !/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(input.picture) || input.picture.length > LIMITS.picture) {
2866
+ throw new OfferError("The code to pay by is a picture of PNG, JPEG or WebP, 300 KB at most.");
2867
+ }
2868
+ picture = input.picture;
2869
+ }
2870
+ const note = input?.note === undefined ? before.note : text(input.note, LIMITS.note);
2871
+ await this.ctx.store.setPayee({ ...picture ? { picture } : {}, ...note ? { note } : {} });
2872
+ }
2873
+ }
2874
+
2875
+ // web-src/offer-use.ts
2876
+ import { randomUUID as randomUUID6 } from "node:crypto";
2877
+ class OfferUse {
2878
+ ctx;
2879
+ constructor(ctx) {
2880
+ this.ctx = ctx;
2881
+ }
2882
+ async mine() {
2883
+ const member = this.ctx.caller();
2884
+ if (!member) {
2885
+ return [];
2886
+ }
2887
+ const users = await this.bind(member);
2888
+ const agents = await this.ctx.conversations.agents();
2889
+ const payee = await this.ctx.store.payee();
2890
+ const now = Date.now();
2891
+ return users.flatMap((user) => {
2892
+ const offer = this.ctx.data.offers.find((one) => one.id === user.offer);
2893
+ if (!offer) {
2894
+ return [];
2895
+ }
2896
+ const agent = agents.find((one) => one.id === offer.agent);
2897
+ const waiting = this.ctx.payments.waitingOf(user.id);
2898
+ return [
2899
+ {
2900
+ offer: {
2901
+ id: offer.id,
2902
+ name: offer.name,
2903
+ ...offer.intro ? { intro: offer.intro } : {},
2904
+ ...agent ? { face: agent.face, mark: agent.mark } : {},
2905
+ owner: member.owner,
2906
+ plans: offer.plans,
2907
+ ...offer.paused ? { paused: true } : {}
2908
+ },
2909
+ user: {
2910
+ id: user.id,
2911
+ name: user.name,
2912
+ grant: user.grant,
2913
+ used: user.used,
2914
+ sessions: user.sessions,
2915
+ ...user.paused ? { paused: true } : {}
2916
+ },
2917
+ state: this.ctx.state(user, now),
2918
+ ...waiting ? { waiting: { id: waiting.id, plan: waiting.plan, amount: waiting.amount, code: waiting.code, at: waiting.at } } : {},
2919
+ payable: !!payee.picture,
2920
+ ...payee.note ? { payeeNote: payee.note } : {},
2921
+ ...this.apiOf(offer, user)
2922
+ }
2923
+ ];
2924
+ });
2925
+ }
2926
+ async start(offerId) {
2927
+ const { member, user, offer } = await this.of(offerId);
2928
+ const state = this.ctx.state(user);
2929
+ if (state.block !== "none") {
2930
+ throw new OfferError(OfferTexts.blocked(state.block));
2931
+ }
2932
+ const agent = await this.ctx.conversations.agent(offer.agent);
2933
+ if (!agent) {
2934
+ throw new OfferError(OfferTexts.blocked("closed"));
2935
+ }
2936
+ const { sessionId, sessionFile } = await this.ctx.conversations.start(member, offer, agent);
2937
+ if (sessionFile && !user.sessions.includes(sessionFile)) {
2938
+ user.sessions = [...user.sessions, sessionFile];
2939
+ }
2940
+ user.lastAt = Date.now();
2941
+ await this.ctx.commit();
2942
+ return { sessionId };
2943
+ }
2944
+ async pay(offerId, plan) {
2945
+ const { user, offer } = await this.of(offerId);
2946
+ const payment = this.ctx.payments.claim(user, offer, plan);
2947
+ await this.ctx.commit();
2948
+ await this.ctx.tell(`pay:${payment.id}`, OfferTexts.paidTitle(), OfferTexts.paid(user.name, offer.name, payment.amount, payment.code));
2949
+ return { id: payment.id, code: payment.code, amount: payment.amount };
2950
+ }
2951
+ async cancelPay(offerId, payment) {
2952
+ const { user } = await this.of(offerId);
2953
+ this.ctx.payments.cancel(user, payment);
2954
+ await this.ctx.commit();
2955
+ }
2956
+ async payee(offerId) {
2957
+ await this.of(offerId);
2958
+ return this.ctx.store.payee();
2959
+ }
2960
+ async createKey(offerId, name) {
2961
+ const { user, offer } = await this.of(offerId);
2962
+ const base = this.ctx.links.apiBase(offer.invite?.link, NAME);
2963
+ if (offer.api === false || !base) {
2964
+ throw new OfferError("The owner did not open this agent to the API.");
2965
+ }
2966
+ if ((user.keys?.length ?? 0) >= LIMITS.keys) {
2967
+ throw new OfferError(`At most ${LIMITS.keys} keys: remove one first.`);
2968
+ }
2969
+ const made = OfferKeys.make();
2970
+ const id = randomUUID6();
2971
+ const label = typeof name === "string" && name.trim() ? name.trim().slice(0, LIMITS.keyName) : made.hint;
2972
+ user.keys = [...user.keys ?? [], { id, name: label, hash: made.hash, hint: made.hint, createdAt: Date.now() }];
2973
+ await this.ctx.commit({ what: "key", offer: offer.id, user: user.id, by: user.member });
2974
+ return { key: made.key, hint: made.hint, base };
2975
+ }
2976
+ async removeKey(offerId, keyId) {
2977
+ const { user, offer } = await this.of(offerId);
2978
+ if (!user.keys?.some((key) => key.id === keyId)) {
2979
+ throw new OfferError("No such key.");
2980
+ }
2981
+ user.keys = user.keys.filter((key) => key.id !== keyId);
2982
+ await this.ctx.commit({ what: "unkey", offer: offer.id, user: user.id, by: user.member });
2983
+ }
2984
+ async connectCode(offerId) {
2985
+ const { user, offer } = await this.of(offerId);
2986
+ if (offer.api === false) {
2987
+ throw new OfferError("The owner turned off the API of this agent.");
2988
+ }
2989
+ return this.ctx.connects.make(user.id);
2990
+ }
2991
+ async removeClient(offerId, clientId) {
2992
+ const { user, offer } = await this.of(offerId);
2993
+ if (!user.clients?.some((client) => client.id === clientId)) {
2994
+ throw new OfferError("No such client.");
2995
+ }
2996
+ user.clients = user.clients.filter((client) => client.id !== clientId);
2997
+ await this.ctx.commit({ what: "unclient", offer: offer.id, user: user.id, by: user.member });
2998
+ }
2999
+ apiOf(offer, user) {
3000
+ const base = offer.api === false ? undefined : this.ctx.links.apiBase(offer.invite?.link, NAME);
3001
+ const keys = (user.keys ?? []).map(({ hash: _hash, ...shown }) => shown);
3002
+ const clients = (user.clients ?? []).map(({ id, name, createdAt, lastAt }) => ({ id, name, createdAt, ...lastAt ? { lastAt } : {} }));
3003
+ return base ? { api: { base, keys, mcp: `${base}/mcp`, clients } } : {};
3004
+ }
3005
+ async of(offerId) {
3006
+ const member = this.ctx.caller();
3007
+ if (!member) {
3008
+ throw new OfferError("Only one let in to use an offer does this.");
3009
+ }
3010
+ const users = await this.bind(member);
3011
+ const user = users.find((one) => one.offer === offerId);
3012
+ const offer = user && this.ctx.data.offers.find((one) => one.id === user.offer);
3013
+ if (!user || !offer) {
3014
+ throw new OfferError("No such offer of yours.");
3015
+ }
3016
+ return { member, user, offer };
3017
+ }
3018
+ async bind(member) {
3019
+ const { data } = this.ctx;
3020
+ const offer = member.via ? data.offers.find((one) => one.invite?.id === member.via || one.past?.includes(member.via)) : undefined;
3021
+ if (offer && !data.users.some((user) => user.member === member.id && user.offer === offer.id)) {
3022
+ const now = Date.now();
3023
+ const trial = offer.plans.find((plan) => plan.id === offer.trial);
3024
+ const used = OfferQuota.emptyMeter(now);
3025
+ const user = {
3026
+ id: `${member.id}|${offer.id}`,
3027
+ member: member.id,
3028
+ offer: offer.id,
3029
+ name: member.name,
3030
+ joinedAt: now,
3031
+ ...trial ? { grant: OfferQuota.grant(trial, "trial", now) } : {},
3032
+ used,
3033
+ sessions: []
3034
+ };
3035
+ data.users.push(user);
3036
+ await this.ctx.commit({ what: "join", offer: offer.id, user: user.id, ...trial ? { plan: trial.id } : {}, by: member.id });
3037
+ }
3038
+ return data.users.filter((user) => user.member === member.id);
3039
+ }
3040
+ }
3041
+
3042
+ // web-src/offer-service.ts
3043
+ var TIDY_MS = 3600000;
3044
+
3045
+ class OfferService {
3046
+ ctx;
3047
+ owner;
3048
+ use;
3049
+ meters;
3050
+ api;
3051
+ mcp;
3052
+ oauth;
3053
+ turns;
3054
+ timer;
3055
+ constructor(host) {
3056
+ this.ctx = new OfferContext(host);
3057
+ this.owner = new OfferOwner(this.ctx);
3058
+ this.use = new OfferUse(this.ctx);
3059
+ this.meters = new OfferMeterBook(this.ctx);
3060
+ this.api = new OfferApi(this.ctx);
3061
+ this.mcp = new OfferMcp(this.ctx);
3062
+ this.oauth = new OfferOAuth(this.ctx);
3063
+ this.turns = this.ctx.turns;
3064
+ }
3065
+ async http(request) {
3066
+ if (request.path.replace(/\/+$/, "") === "mcp") {
3067
+ return this.mcp.http(request);
3068
+ }
3069
+ return await this.oauth.http(request) ?? this.api.http(request);
3070
+ }
3071
+ async start() {
3072
+ await this.ctx.store.load();
3073
+ this.ctx.turns.start();
3074
+ const tidy = () => {
3075
+ this.ctx.payments.tidy();
3076
+ this.ctx.commit();
3077
+ };
3078
+ tidy();
3079
+ this.timer = setInterval(tidy, TIDY_MS);
3080
+ this.timer.unref?.();
3081
+ }
3082
+ dispose() {
3083
+ clearInterval(this.timer);
3084
+ this.mcp.tasks.dispose();
3085
+ this.ctx.turns.dispose();
3086
+ }
3087
+ }
3088
+
3089
+ // web-src/host.ts
3090
+ async function activate(host) {
3091
+ const service = new OfferService(host);
3092
+ await service.start();
3093
+ const { owner, use } = service;
3094
+ return {
3095
+ _offer: service,
3096
+ dispose: () => service.dispose(),
3097
+ http: (request) => service.http(request),
3098
+ overview: () => owner.overview(),
3099
+ agents: () => owner.agents(),
3100
+ save: (input) => owner.save(input),
3101
+ renewLink: (offer, language) => owner.renewLink(offer, language),
3102
+ setPaused: (offer, paused) => owner.setPaused(offer, paused),
3103
+ remove: (offer) => owner.remove(offer),
3104
+ answerJoin: (join2, accept) => owner.answerJoin(join2, accept),
3105
+ answerPayment: (payment, accept) => owner.answerPayment(payment, accept),
3106
+ grant: (user, plan, amount) => owner.grant(user, plan, amount),
3107
+ setUserPaused: (user, paused) => owner.setUserPaused(user, paused),
3108
+ removeUser: (user) => owner.removeUser(user),
3109
+ setPayee: (input) => owner.setPayee(input),
3110
+ mine: () => use.mine(),
3111
+ start: (offer) => use.start(offer),
3112
+ pay: (offer, plan) => use.pay(offer, plan),
3113
+ cancelPay: (offer, payment) => use.cancelPay(offer, payment),
3114
+ payee: (offer) => use.payee(offer),
3115
+ createKey: (offer, name) => use.createKey(offer, name),
3116
+ removeKey: (offer, key) => use.removeKey(offer, key),
3117
+ connectCode: (offer) => use.connectCode(offer),
3118
+ removeClient: (offer, client) => use.removeClient(offer, client)
3119
+ };
3120
+ }
3121
+ export {
3122
+ activate as default
3123
+ };