@celljs/ta-offer 0.0.0-stage → 4.38.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,1124 @@
1
+ // ../ta-protocol/esm/common/language.js
2
+ var TaLanguageUtil;
3
+ (function(TaLanguageUtil2) {
4
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
5
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
6
+ function of(tag) {
7
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
8
+ if (/^zh(\b|-)/.test(said)) {
9
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
10
+ }
11
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
12
+ }
13
+ TaLanguageUtil2.of = of;
14
+ function server(env = typeof process === "undefined" ? {} : process.env) {
15
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
16
+ }
17
+ TaLanguageUtil2.server = server;
18
+ function pick(language, words) {
19
+ return words[of(language)];
20
+ }
21
+ TaLanguageUtil2.pick = pick;
22
+ function say(words) {
23
+ return words[server()];
24
+ }
25
+ TaLanguageUtil2.say = say;
26
+ function chinese(language) {
27
+ return of(language).startsWith("zh");
28
+ }
29
+ TaLanguageUtil2.chinese = chinese;
30
+ function cjk(language) {
31
+ return of(language) !== "en-US";
32
+ }
33
+ TaLanguageUtil2.cjk = cjk;
34
+ function list(language, items) {
35
+ return items.join(cjk(language) ? "、" : ", ");
36
+ }
37
+ TaLanguageUtil2.list = list;
38
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
39
+
40
+ // ../ta-protocol/esm/common/team-protocol.js
41
+ var TA_OWNER = "owner";
42
+ var TA_UNDECLARED = "extensions.install";
43
+ var TaPermissionUtil;
44
+ (function(TaPermissionUtil2) {
45
+ function read(pi) {
46
+ const given = pi === null || pi === undefined ? undefined : pi.permissions;
47
+ const map = (value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).filter((entry) => typeof entry[1] === "string")) : undefined;
48
+ const host2 = map(given === null || given === undefined ? undefined : given.host);
49
+ const tools = map(given === null || given === undefined ? undefined : given.tools);
50
+ return { ...host2 ? { host: host2 } : {}, ...tools ? { tools } : {} };
51
+ }
52
+ TaPermissionUtil2.read = read;
53
+ function host(manifest, method, kind) {
54
+ var _a, _b, _c, _d;
55
+ const host2 = (_a = manifest === null || manifest === undefined ? undefined : manifest.host) !== null && _a !== undefined ? _a : {};
56
+ const own = (key) => {
57
+ var _a2;
58
+ return (_a2 = Object.getOwnPropertyDescriptor(host2, key)) === null || _a2 === undefined ? undefined : _a2.value;
59
+ };
60
+ 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;
61
+ }
62
+ TaPermissionUtil2.host = host;
63
+ })(TaPermissionUtil || (TaPermissionUtil = {}));
64
+ var action = (id, en, zh, tw, ja, more = {}) => ({
65
+ id,
66
+ area: id.split(".")[0],
67
+ title: { en, "zh-CN": zh, ...tw ? { "zh-TW": tw } : {}, ...ja ? { "ja-JP": ja } : {} },
68
+ ...more
69
+ });
70
+ var TA_ACTIONS = [
71
+ action("chat.view", "See conversations", "查看对话", "檢視對話", "会話を確認"),
72
+ action("chat.send", "Send in conversations", "在对话里发消息", "在對話裡發訊息", "会話にメッセージを送信"),
73
+ action("chat.create", "Start conversations", "新建对话", "新建對話", "新しい会話を開始"),
74
+ action("chat.stop", "Stop a reply", "停止回复", "停止回覆", "返信を停止"),
75
+ action("chat.manage", "Rename, archive and close conversations", "改名、归档、关闭对话", "改名、歸檔、關閉對話", "会話の名前変更、アーカイブ、クローズ"),
76
+ action("chat.share", "Share by a link", "生成分享链接", "生成分享連結", "共有リンクで共有"),
77
+ action("agent.view", "See agents", "查看智能体", "檢視智慧體", "エージェントを確認"),
78
+ action("agent.use", "Talk with agents", "和智能体对话", "和智慧體對話", "エージェントと対話"),
79
+ action("agent.edit", "Create, change and remove agents", "新建、修改、删除智能体", "新建、修改、刪除智慧體", "エージェントを作成・変更・削除"),
80
+ action("channel.view", "See channels", "查看频道", "檢視頻道", "チャネルを確認"),
81
+ action("channel.post", "Post in channels", "在频道里发言", "在頻道里發言", "チャネルに投稿"),
82
+ action("channel.manage", "Create and change channels", "新建、管理频道", "新建、管理頻道", "チャネルを作成・管理"),
83
+ action("task.view", "See tasks", "查看任务", "檢視任務", "タスクを確認"),
84
+ action("task.create", "Hand out tasks", "派任务", "派任務", "タスクを割り当て"),
85
+ action("task.manage", "Take over and stop tasks", "接管、停止任务", "接管、停止任務", "タスクを引き継ぎ・停止"),
86
+ action("files.read", "Read files", "读文件", "讀檔案", "ファイルを読取", { scoped: true }),
87
+ action("files.write", "Change files", "改文件", "改檔案", "ファイルを変更", { scoped: true }),
88
+ action("commands.run", "Let Ta run commands", "让 Ta 运行命令", "讓 Ta 執行命令", "Ta にコマンド実行を許可", { scoped: true, risky: true }),
89
+ action("commands.terminal", "Open terminals", "打开终端", "開啟終端機", "ターミナルを開く", { scoped: true, risky: true }),
90
+ action("hosts.use", "Use remote hosts", "使用远程主机", "使用遠端主機", "リモートホストを使用", { risky: true }),
91
+ action("models.use", "Use the models", "使用模型", "使用模型", "モデルを使用"),
92
+ action("models.manage", "Sign in to models", "登录和更换模型账号", "登入和更換模型帳號", "モデルアカウントにサインイン・変更", { grant: "single" }),
93
+ action("cron.view", "See scheduled tasks", "查看定时任务", "檢視定時任務", "スケジュールタスクを確認"),
94
+ action("cron.manage", "Change scheduled tasks", "管理定时任务", "管理定時任務", "スケジュールタスクを管理"),
95
+ action("extensions.use", "Use extensions", "使用扩展", "使用擴充功能", "拡張機能を使用"),
96
+ action("extensions.install", "Install and turn off extensions", "安装、停用扩展", "安裝、停用擴充功能", "拡張機能をインストール・無効化"),
97
+ action("extensions.trust", "Decide how far others' extensions reach", "决定别人的扩展能用到哪一步", "決定別人的擴充功能能用到哪一步", "他の人の拡張機能に許す範囲を決める", { risky: true }),
98
+ action("settings.view", "See settings", "查看设置", "檢視設定", "設定を確認"),
99
+ action("settings.manage", "Change settings", "修改设置", "修改設定", "設定を変更"),
100
+ action("members.view", "See members", "查看成员", "檢視成員", "メンバーを確認"),
101
+ action("members.invite", "Invite people", "邀请别人", "邀請別人", "メンバーを招待"),
102
+ action("members.approve", "Answer requests", "处理申请", "處理申請", "リクエストに対応"),
103
+ action("members.roles", "Change roles and members", "管理角色和成员", "管理角色和成員", "ロールとメンバーを管理"),
104
+ action("audit.view", "See the record", "查看记录", "檢視記錄", "レコードを確認")
105
+ ];
106
+ var TA_OWNER_ACTIONS = [
107
+ action("desktop.view", "See remote desktops", "查看远程桌面", "檢視遠端桌面", "リモートデスクトップを見る", { risky: true }),
108
+ action("desktop.control", "Work remote desktops", "操作远程桌面", "操作遠端桌面", "リモートデスクトップを操作", { risky: true }),
109
+ action("models.owner", "Ask models on the owner's keys", "用你的密钥和本机模型做判断", "用你的金鑰和本機模型做判斷", "あなたのキーとローカルモデルで判断", {
110
+ risky: true
111
+ })
112
+ ];
113
+ var OWNER_AREAS = ["desktop"];
114
+ var TaActionUtil;
115
+ (function(TaActionUtil2) {
116
+ const byId = new Map(TA_ACTIONS.map((one) => [one.id, one]));
117
+ const titled = new Map([...TA_ACTIONS, ...TA_OWNER_ACTIONS].map((one) => [one.id, one]));
118
+ function info(id) {
119
+ return byId.get(id);
120
+ }
121
+ TaActionUtil2.info = info;
122
+ function title(id, language) {
123
+ var _a;
124
+ var _b, _c;
125
+ const title2 = (_a = titled.get(id)) === null || _a === undefined ? undefined : _a.title;
126
+ if (!title2) {
127
+ return id;
128
+ }
129
+ return TaLanguageUtil.pick(language, {
130
+ "zh-CN": title2["zh-CN"],
131
+ "zh-TW": (_b = title2["zh-TW"]) !== null && _b !== undefined ? _b : title2["zh-CN"],
132
+ "en-US": title2.en,
133
+ "ja-JP": (_c = title2["ja-JP"]) !== null && _c !== undefined ? _c : title2.en
134
+ });
135
+ }
136
+ TaActionUtil2.title = title;
137
+ function grantable(id) {
138
+ const info2 = byId.get(id);
139
+ return !!info2 && !OWNER_AREAS.includes(info2.area);
140
+ }
141
+ TaActionUtil2.grantable = grantable;
142
+ function inRoles(id) {
143
+ var _a;
144
+ return grantable(id) && ((_a = byId.get(id)) === null || _a === undefined ? undefined : _a.grant) !== "single";
145
+ }
146
+ TaActionUtil2.inRoles = inRoles;
147
+ function inside(dir, path) {
148
+ const base = dir.replace(/\/+$/, "");
149
+ return path === base || path.startsWith(`${base}/`) || base === "";
150
+ }
151
+ TaActionUtil2.inside = inside;
152
+ })(TaActionUtil || (TaActionUtil = {}));
153
+
154
+ // ../ta-protocol/esm/common/redactor.js
155
+ var REDACTED = "[redacted]";
156
+ var WHOLE = [
157
+ ["PRIVATE_KEY", /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----/g],
158
+ ["API_KEY", /\bsk-(?:ant-|proj-)?[A-Za-z0-9_-]{20,}/g],
159
+ ["GITHUB_TOKEN", /\bgh[pousr]_[A-Za-z0-9]{30,}\b/g],
160
+ ["GITHUB_TOKEN", /\bgithub_pat_[A-Za-z0-9_]{40,}\b/g],
161
+ ["GITLAB_TOKEN", /\bglpat-[A-Za-z0-9_-]{20,}\b/g],
162
+ ["SLACK_TOKEN", /\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g],
163
+ ["AWS_ACCESS_KEY_ID", /\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g],
164
+ ["GOOGLE_API_KEY", /\bAIza[0-9A-Za-z_-]{35}\b/g],
165
+ ["JWT", /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g]
166
+ ];
167
+ var NAMED = [
168
+ /(\bBearer\s+)[A-Za-z0-9._~+/-]{16,}=*/gi,
169
+ /(\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,
170
+ /(:\/\/[^\s:/@]+:)([^\s@/]{3,})(@)/g
171
+ ];
172
+
173
+ class Redactor {
174
+ constructor() {
175
+ this.count = 0;
176
+ }
177
+ text(text) {
178
+ let out = text;
179
+ for (const [, pattern] of WHOLE) {
180
+ out = out.replace(pattern, () => this.hide());
181
+ }
182
+ out = out.replace(NAMED[0], (_match, before) => before + this.hide());
183
+ out = out.replace(NAMED[1], (match, before, value) => Redactor.placeholder(value) ? match : before + this.hide());
184
+ out = out.replace(NAMED[2], (_match, before, _value, after) => before + this.hide() + after);
185
+ return out;
186
+ }
187
+ value(value, max) {
188
+ if (typeof value === "string") {
189
+ return Redactor.cut(this.text(value), max);
190
+ }
191
+ if (Array.isArray(value)) {
192
+ return value.map((item) => this.value(item, max));
193
+ }
194
+ if (value && typeof value === "object") {
195
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, this.value(item, max)]));
196
+ }
197
+ return value;
198
+ }
199
+ static spans(text) {
200
+ var _a;
201
+ var _b;
202
+ const found = [];
203
+ for (const [kind, pattern] of WHOLE) {
204
+ for (const match of text.matchAll(pattern)) {
205
+ found.push({ start: match.index, end: match.index + match[0].length, kind });
206
+ }
207
+ }
208
+ for (const match of text.matchAll(NAMED[0])) {
209
+ found.push({ start: match.index + match[1].length, end: match.index + match[0].length, kind: "BEARER_TOKEN" });
210
+ }
211
+ for (const match of text.matchAll(NAMED[1])) {
212
+ if (!Redactor.placeholder(match[2])) {
213
+ const start = match.index + match[1].length;
214
+ const name = (_b = (_a = /[A-Za-z0-9_.-]+/.exec(match[1])) === null || _a === undefined ? undefined : _a[0]) !== null && _b !== undefined ? _b : "SECRET";
215
+ found.push({ start, end: start + match[2].length, kind: name.replace(/[^A-Za-z0-9]+/g, "_").toUpperCase() });
216
+ }
217
+ }
218
+ for (const match of text.matchAll(NAMED[2])) {
219
+ const start = match.index + match[1].length;
220
+ found.push({ start, end: start + match[2].length, kind: "URL_PASSWORD" });
221
+ }
222
+ found.sort((a, b) => a.start - b.start || b.end - a.end);
223
+ const spans = [];
224
+ for (const span of found) {
225
+ const last = spans.at(-1);
226
+ if (!last || span.start >= last.end) {
227
+ spans.push(span);
228
+ }
229
+ }
230
+ return spans;
231
+ }
232
+ static cut(text, max) {
233
+ return text.length > max ? `${text.slice(0, max)}…` : text;
234
+ }
235
+ hide() {
236
+ this.count++;
237
+ return REDACTED;
238
+ }
239
+ static placeholder(value) {
240
+ return /^(?:\$|<|\{|\[redacted|process\.env|os\.environ|xxx|\*{3})/i.test(value) || /^(?:true|false|null|undefined|none|string|number)$/i.test(value);
241
+ }
242
+ }
243
+
244
+ // web-src/offer-protocol.ts
245
+ var NAME = "@celljs/ta-offer";
246
+ var OFFERS_VIEW = `${NAME}/offers`;
247
+ var OFFER_MARK = "[ta:offer]";
248
+ var DATA_KEY = "data";
249
+ var PAYEE_KEY = "payee";
250
+ var EMPTY_DATA = { v: 1, offers: [], users: [], payments: [] };
251
+ var LIMITS = { name: 40, intro: 300, plans: 6, planName: 20, note: 300, picture: 400000 };
252
+
253
+ // web-src/offer-conversations.ts
254
+ var CHANNELS = "@celljs/ta-channels";
255
+ var OfferRole;
256
+ ((OfferRole) => {
257
+ function of(agent, offer) {
258
+ return [
259
+ OFFER_MARK,
260
+ `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.`,
261
+ new Redactor().text(agent.role.trim())
262
+ ].join(`
263
+ `);
264
+ }
265
+ OfferRole.of = of;
266
+ })(OfferRole ||= {});
267
+
268
+ class OfferConversations {
269
+ host;
270
+ constructor(host) {
271
+ this.host = host;
272
+ }
273
+ async agents() {
274
+ const listed = await this.host.callPackageHost(CHANNELS, "listAgents").catch(() => []);
275
+ return Array.isArray(listed) ? listed : [];
276
+ }
277
+ async agent(id) {
278
+ return (await this.agents()).find((agent) => agent.id === id);
279
+ }
280
+ async start(member, offer, agent) {
281
+ if (!member.home) {
282
+ throw new Error("One using an offer works in a home of their own; this member has none.");
283
+ }
284
+ const home = member.home;
285
+ return this.host.team.actAs(member.id, async () => {
286
+ const { sessionId } = await this.host.openSession({
287
+ cwd: home,
288
+ appendSystemPrompt: OfferRole.of(agent, offer),
289
+ ...agent.model ? { model: agent.model } : {}
290
+ });
291
+ await this.host.setSessionName(sessionId, offer.name).catch(() => {
292
+ return;
293
+ });
294
+ const { sessionFile } = await this.host.getState(sessionId);
295
+ return { sessionId, ...sessionFile ? { sessionFile } : {} };
296
+ });
297
+ }
298
+ }
299
+
300
+ // web-src/offer-links.ts
301
+ var TEAM = "@celljs/ta-team";
302
+ var USER_ROLE = "user";
303
+ var LINK_DAYS = 365;
304
+
305
+ class OfferLinks {
306
+ host;
307
+ constructor(host) {
308
+ this.host = host;
309
+ }
310
+ call(method, ...params) {
311
+ return this.host.callPackageHost(TEAM, method, params);
312
+ }
313
+ async create(what, approve, language) {
314
+ const invite = await this.call("createInvite", {
315
+ role: USER_ROLE,
316
+ days: LINK_DAYS,
317
+ approve,
318
+ what,
319
+ ...language ? { language } : {}
320
+ });
321
+ return { id: invite.id, link: invite.link, expiresAt: invite.expiresAt };
322
+ }
323
+ async setApprove(invite, approve) {
324
+ await this.call("setInviteApprove", invite, approve);
325
+ }
326
+ async stop(invite) {
327
+ await this.call("stopInvite", invite).catch(() => {
328
+ return;
329
+ });
330
+ }
331
+ async waiting(invites) {
332
+ if (!invites.size) {
333
+ return [];
334
+ }
335
+ const overview = await this.call("overview").catch(() => {
336
+ return;
337
+ });
338
+ return (overview?.joins ?? []).filter((join) => join.status === "waiting" && invites.has(join.invite));
339
+ }
340
+ async answer(join, accept) {
341
+ await this.call("answerJoin", join, accept, USER_ROLE);
342
+ }
343
+ async remove(member) {
344
+ this.host.team.disconnect(member);
345
+ await this.call("removeMember", member).catch(() => {
346
+ return;
347
+ });
348
+ }
349
+ who(principal) {
350
+ const info = this.host.team.describe(principal);
351
+ return info?.role === USER_ROLE ? info : undefined;
352
+ }
353
+ online(member) {
354
+ return (this.host.team.connected()[member] ?? 0) > 0;
355
+ }
356
+ }
357
+
358
+ // web-src/offer-payments.ts
359
+ import { randomInt, randomUUID } from "node:crypto";
360
+
361
+ // web-src/offer-quota.ts
362
+ var DAY_MS = 86400000;
363
+ var OfferQuota;
364
+ ((OfferQuota) => {
365
+ function day(now) {
366
+ const date = new Date(now);
367
+ const pad = (n) => String(n).padStart(2, "0");
368
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
369
+ }
370
+ OfferQuota.day = day;
371
+ function nextDay(now) {
372
+ const date = new Date(now);
373
+ return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).getTime();
374
+ }
375
+ OfferQuota.nextDay = nextDay;
376
+ function emptyMeter(now) {
377
+ return { total: 0, day: day(now), today: 0, cost: 0 };
378
+ }
379
+ OfferQuota.emptyMeter = emptyMeter;
380
+ function tokensOf(usage) {
381
+ const n = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
382
+ return Math.ceil(n(usage?.input) + n(usage?.output) + n(usage?.cacheWrite) + n(usage?.cacheRead) / 10);
383
+ }
384
+ OfferQuota.tokensOf = tokensOf;
385
+ function add(meter, tokens, cost, now) {
386
+ const today = day(now);
387
+ const same = meter.day === today;
388
+ return {
389
+ total: meter.total + tokens,
390
+ day: today,
391
+ today: (same ? meter.today : 0) + tokens,
392
+ cost: meter.cost + (Number.isFinite(cost) && cost > 0 ? cost : 0)
393
+ };
394
+ }
395
+ OfferQuota.add = add;
396
+ function grant(plan, by, now, before) {
397
+ const old = before?.grant;
398
+ const total = before?.used.total ?? 0;
399
+ 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;
400
+ return {
401
+ plan: plan.id,
402
+ name: plan.name,
403
+ price: plan.price,
404
+ ...plan.tokens !== undefined ? { tokens: plan.tokens + carried } : {},
405
+ ...plan.daily !== undefined ? { daily: plan.daily } : {},
406
+ ...plan.days ? { days: plan.days } : {},
407
+ ...total ? { from: total } : {},
408
+ startsAt: now,
409
+ ...plan.days ? { endsAt: now + plan.days * DAY_MS } : {},
410
+ by
411
+ };
412
+ }
413
+ OfferQuota.grant = grant;
414
+ function state(grant2, meter, now, stopped) {
415
+ if (!grant2) {
416
+ return { block: "expired" };
417
+ }
418
+ const today = meter.day === day(now) ? meter.today : 0;
419
+ const left = grant2.tokens !== undefined ? Math.max(0, grant2.tokens - (meter.total - (grant2.from ?? 0))) : undefined;
420
+ const todayLeft = grant2.daily !== undefined ? Math.max(0, grant2.daily - today) : undefined;
421
+ const state2 = {
422
+ block: "none",
423
+ ...left !== undefined ? { left } : {},
424
+ ...todayLeft !== undefined ? { todayLeft, resetsAt: nextDay(now) } : {},
425
+ ...grant2.endsAt !== undefined ? { endsAt: grant2.endsAt } : {}
426
+ };
427
+ if (stopped) {
428
+ return { ...state2, block: stopped };
429
+ }
430
+ if (grant2.endsAt !== undefined && grant2.endsAt <= now) {
431
+ return { ...state2, block: "expired" };
432
+ }
433
+ if (left === 0) {
434
+ return { ...state2, block: "total" };
435
+ }
436
+ if (todayLeft === 0) {
437
+ return { ...state2, block: "daily" };
438
+ }
439
+ return state2;
440
+ }
441
+ OfferQuota.state = state;
442
+ function clean(plans, limits) {
443
+ const whole = (value, min, max) => {
444
+ const n = Math.floor(Number(value));
445
+ return Number.isFinite(n) && n >= min ? Math.min(n, max) : undefined;
446
+ };
447
+ const seen = new Set;
448
+ const out = [];
449
+ for (const one of Array.isArray(plans) ? plans : []) {
450
+ const given = one;
451
+ const id = typeof given?.id === "string" && /^[A-Za-z0-9_-]{1,24}$/.test(given.id) ? given.id : undefined;
452
+ const name = typeof given?.name === "string" ? given.name.trim().slice(0, limits.planName) : "";
453
+ if (!id || !name || seen.has(id) || out.length >= limits.plans) {
454
+ continue;
455
+ }
456
+ seen.add(id);
457
+ const tokens = whole(given.tokens, 1, 1000000000000);
458
+ const daily = whole(given.daily, 1, 1000000000000);
459
+ const days = whole(given.days, 1, 3660);
460
+ out.push({
461
+ id,
462
+ name,
463
+ price: whole(given.price, 0, 1e9) ?? 0,
464
+ ...tokens !== undefined ? { tokens } : {},
465
+ ...daily !== undefined ? { daily } : {},
466
+ ...days !== undefined ? { days } : {}
467
+ });
468
+ }
469
+ return out;
470
+ }
471
+ OfferQuota.clean = clean;
472
+ })(OfferQuota ||= {});
473
+
474
+ // web-src/offer-payments.ts
475
+ var MAX_WAITING = 1;
476
+ var WAIT_DAYS = 14;
477
+ var DAY_MS2 = 86400000;
478
+ var KEEP = 500;
479
+
480
+ class OfferPayments {
481
+ store;
482
+ constructor(store) {
483
+ this.store = store;
484
+ }
485
+ waitingOf(user) {
486
+ return this.store.data.payments.find((one) => one.user === user && one.status === "waiting");
487
+ }
488
+ claim(user, offer, planId, now = Date.now()) {
489
+ const plan = offer.plans.find((one) => one.id === planId);
490
+ if (!plan || plan.price <= 0) {
491
+ throw new Error("No such plan to pay for.");
492
+ }
493
+ const waiting = this.store.data.payments.filter((one) => one.user === user.id && one.status === "waiting");
494
+ for (const old of waiting.slice(0, Math.max(0, waiting.length + 1 - MAX_WAITING))) {
495
+ old.status = "refused";
496
+ old.answeredAt = now;
497
+ }
498
+ const payment = {
499
+ id: randomUUID(),
500
+ user: user.id,
501
+ offer: offer.id,
502
+ plan: plan.id,
503
+ amount: plan.price,
504
+ code: String(randomInt(1000, 1e4)),
505
+ at: now,
506
+ status: "waiting",
507
+ way: "code"
508
+ };
509
+ this.store.data.payments.push(payment);
510
+ return payment;
511
+ }
512
+ cancel(user, id, now = Date.now()) {
513
+ const payment = this.store.data.payments.find((one) => one.id === id && one.user === user.id && one.status === "waiting");
514
+ if (payment) {
515
+ payment.status = "refused";
516
+ payment.answeredAt = now;
517
+ }
518
+ }
519
+ answer(id, accept, by, now = Date.now()) {
520
+ const payment = this.store.data.payments.find((one) => one.id === id && one.status === "waiting");
521
+ if (!payment) {
522
+ throw new Error("No such payment waiting.");
523
+ }
524
+ payment.status = accept ? "confirmed" : "refused";
525
+ payment.answeredAt = now;
526
+ const user = accept ? this.give(payment.user, payment.offer, payment.plan, by, now) : undefined;
527
+ return { payment, ...user ? { user } : {} };
528
+ }
529
+ offline(user, offer, planId, amount, by, now = Date.now()) {
530
+ const plan = offer.plans.find((one) => one.id === planId);
531
+ if (!plan) {
532
+ throw new Error("No such plan.");
533
+ }
534
+ const fen = Number.isFinite(Number(amount)) && Number(amount) >= 0 ? Math.floor(Number(amount)) : plan.price;
535
+ const payment = {
536
+ id: randomUUID(),
537
+ user: user.id,
538
+ offer: offer.id,
539
+ plan: plan.id,
540
+ amount: fen,
541
+ code: "",
542
+ at: now,
543
+ status: "confirmed",
544
+ answeredAt: now,
545
+ way: "offline"
546
+ };
547
+ this.store.data.payments.push(payment);
548
+ this.give(user.id, offer.id, plan.id, by, now);
549
+ return payment;
550
+ }
551
+ tidy(now = Date.now()) {
552
+ for (const one of this.store.data.payments) {
553
+ if (one.status === "waiting" && now - one.at > WAIT_DAYS * DAY_MS2) {
554
+ one.status = "refused";
555
+ one.answeredAt = now;
556
+ }
557
+ }
558
+ const answered = this.store.data.payments.filter((one) => one.status !== "waiting");
559
+ if (answered.length > KEEP) {
560
+ const drop = new Set(answered.slice(0, answered.length - KEEP));
561
+ this.store.data.payments = this.store.data.payments.filter((one) => !drop.has(one));
562
+ }
563
+ }
564
+ give(userId, offerId, planId, by, now) {
565
+ const user = this.store.data.users.find((one) => one.id === userId);
566
+ const plan = this.store.data.offers.find((one) => one.id === offerId)?.plans.find((one) => one.id === planId);
567
+ if (!user || !plan) {
568
+ return;
569
+ }
570
+ user.grant = OfferQuota.grant(plan, by, now, user);
571
+ return user;
572
+ }
573
+ }
574
+
575
+ // web-src/offer-store.ts
576
+ import { appendFile, mkdir } from "node:fs/promises";
577
+ import { join } from "node:path";
578
+ class OfferStore {
579
+ host;
580
+ data = structuredClone(EMPTY_DATA);
581
+ writing = Promise.resolve();
582
+ constructor(host) {
583
+ this.host = host;
584
+ }
585
+ async load() {
586
+ const kept = await this.host.getExtensionData(NAME, DATA_KEY).catch(() => {
587
+ return;
588
+ });
589
+ this.data = {
590
+ v: 1,
591
+ offers: Array.isArray(kept?.offers) ? kept.offers : [],
592
+ users: Array.isArray(kept?.users) ? kept.users : [],
593
+ payments: Array.isArray(kept?.payments) ? kept.payments : []
594
+ };
595
+ }
596
+ save() {
597
+ const value = structuredClone(this.data);
598
+ this.writing = this.writing.then(() => this.host.setExtensionData(NAME, DATA_KEY, value)).catch(() => {
599
+ return;
600
+ });
601
+ return this.writing;
602
+ }
603
+ async payee() {
604
+ const kept = await this.host.getExtensionData(NAME, PAYEE_KEY).catch(() => {
605
+ return;
606
+ });
607
+ return {
608
+ ...typeof kept?.picture === "string" ? { picture: kept.picture } : {},
609
+ ...typeof kept?.note === "string" ? { note: kept.note } : {}
610
+ };
611
+ }
612
+ setPayee(payee) {
613
+ return this.host.setExtensionData(NAME, PAYEE_KEY, payee);
614
+ }
615
+ async record(line) {
616
+ const dir = join(this.host.agentDir, "offer");
617
+ await mkdir(dir, { recursive: true, mode: 448 }).catch(() => {
618
+ return;
619
+ });
620
+ await appendFile(join(dir, "ledger.jsonl"), `${JSON.stringify(line)}
621
+ `, { mode: 384 }).catch(() => {
622
+ return;
623
+ });
624
+ }
625
+ }
626
+
627
+ // web-src/offer-context.ts
628
+ class OfferError extends Error {
629
+ }
630
+
631
+ class OfferContext {
632
+ host;
633
+ store;
634
+ links;
635
+ conversations;
636
+ payments;
637
+ constructor(host) {
638
+ this.host = host;
639
+ this.store = new OfferStore(host);
640
+ this.links = new OfferLinks(host);
641
+ this.conversations = new OfferConversations(host);
642
+ this.payments = new OfferPayments(this.store);
643
+ }
644
+ get data() {
645
+ return this.store.data;
646
+ }
647
+ requireOwner() {
648
+ if (this.host.team.current() !== TA_OWNER) {
649
+ throw new OfferError("Only the owner of this Ta does this.");
650
+ }
651
+ }
652
+ caller() {
653
+ const principal = this.host.team.current();
654
+ return principal === TA_OWNER ? undefined : this.links.who(principal);
655
+ }
656
+ offer(id) {
657
+ const offer = this.data.offers.find((one) => one.id === id);
658
+ if (!offer) {
659
+ throw new OfferError("No such offer.");
660
+ }
661
+ return offer;
662
+ }
663
+ user(id) {
664
+ const user = this.data.users.find((one) => one.id === id);
665
+ if (!user) {
666
+ throw new OfferError("No such user.");
667
+ }
668
+ return user;
669
+ }
670
+ state(user, now = Date.now()) {
671
+ const offer = this.data.offers.find((one) => one.id === user.offer);
672
+ return OfferQuota.state(user.grant, user.used, now, !offer ? "closed" : offer.paused ? "closed" : user.paused ? "paused" : undefined);
673
+ }
674
+ async commit(line) {
675
+ await this.store.save();
676
+ if (line) {
677
+ await this.store.record({ at: Date.now(), ...line });
678
+ }
679
+ }
680
+ async tell(id, title, text) {
681
+ await this.host.callPackageHost("@celljs/ta-notify", "notify", [{ from: NAME, id, level: "ask", title, text, view: OFFERS_VIEW }]).catch(() => {
682
+ return;
683
+ });
684
+ }
685
+ }
686
+
687
+ // web-src/offer-texts.ts
688
+ function yuan(fen) {
689
+ return (fen / 100).toFixed(fen % 100 === 0 ? 0 : 2);
690
+ }
691
+ var OfferTexts;
692
+ ((OfferTexts) => {
693
+ function paidTitle() {
694
+ return TaLanguageUtil.say({ "zh-CN": "有人要付款开通", "zh-TW": "有人要付款開通", "en-US": "Someone is paying", "ja-JP": "支払いの申し出があります" });
695
+ }
696
+ OfferTexts.paidTitle = paidTitle;
697
+ function paid(name, offer, amount, code) {
698
+ const price = yuan(amount);
699
+ return TaLanguageUtil.say({
700
+ "zh-CN": `${name} 要付 ¥${price} 开通${offer},付款备注核对码 ${code}。收到钱后再确认开通。`,
701
+ "zh-TW": `${name} 要付 ¥${price} 開通${offer},付款備註核對碼 ${code}。收到錢後再確認開通。`,
702
+ "en-US": `${name} is paying ¥${price} for ${offer}, with the code ${code} in the note. Confirm once it came in.`,
703
+ "ja-JP": `${name} さんが ¥${price} で${offer}を開通しようとしています。備考の照合コードは ${code}。入金を確認してから開通してください。`
704
+ });
705
+ }
706
+ OfferTexts.paid = paid;
707
+ function blocked(block) {
708
+ switch (block) {
709
+ case "daily":
710
+ return TaLanguageUtil.say({
711
+ "zh-CN": "今天的额度用完了,明天 0 点恢复。也可以在“开放给我的”里换个方案。",
712
+ "zh-TW": "今天的額度用完了,明天 0 點恢復。也可以在「開放給我的」裡換個方案。",
713
+ "en-US": "Today’s allowance is used up; it comes back at midnight. Or pick another plan in Opened to me.",
714
+ "ja-JP": "今日の利用枠を使い切りました。午前 0 時に戻ります。「公開されたもの」でプランを変えることもできます。"
715
+ });
716
+ case "paused":
717
+ case "closed":
718
+ return TaLanguageUtil.say({
719
+ "zh-CN": "提供者暂停了这个智能体,恢复后就能接着用。",
720
+ "zh-TW": "提供者暫停了這個智慧體,恢復後就能接著用。",
721
+ "en-US": "Its owner paused this agent for now; you can go on once they open it again.",
722
+ "ja-JP": "提供者がこのエージェントを一時停止しました。再開されれば続けられます。"
723
+ });
724
+ default:
725
+ return TaLanguageUtil.say({
726
+ "zh-CN": "额度用完了。在“开放给我的”里选个方案,付款后提供者确认就能接着用。",
727
+ "zh-TW": "額度用完了。在「開放給我的」裡選個方案,付款後提供者確認就能接著用。",
728
+ "en-US": "Your allowance is used up. Pick a plan in Opened to me; once its owner confirms your payment, go on.",
729
+ "ja-JP": "利用枠を使い切りました。「公開されたもの」でプランを選び、支払いが確認されれば続けられます。"
730
+ });
731
+ }
732
+ }
733
+ OfferTexts.blocked = blocked;
734
+ })(OfferTexts ||= {});
735
+
736
+ // web-src/offer-meter.ts
737
+ class OfferMeterBook {
738
+ ctx;
739
+ constructor(ctx) {
740
+ this.ctx = ctx;
741
+ }
742
+ userOf(sessionFile) {
743
+ return sessionFile ? this.ctx.data.users.find((user) => user.sessions.includes(sessionFile)) : undefined;
744
+ }
745
+ gate(sessionFile, marked, now = Date.now()) {
746
+ const user = this.userOf(sessionFile);
747
+ if (!user) {
748
+ return marked ? OfferTexts.blocked("closed") : undefined;
749
+ }
750
+ const state = this.ctx.state(user, now);
751
+ return state.block === "none" ? undefined : OfferTexts.blocked(state.block);
752
+ }
753
+ async meter(sessionFile, usage, now = Date.now()) {
754
+ const user = this.userOf(sessionFile);
755
+ const tokens = OfferQuota.tokensOf(usage);
756
+ if (!user || tokens <= 0) {
757
+ return;
758
+ }
759
+ user.used = OfferQuota.add(user.used, tokens, usage?.cost?.total ?? 0, now);
760
+ user.lastAt = now;
761
+ await this.ctx.commit();
762
+ }
763
+ }
764
+
765
+ // web-src/offer-owner.ts
766
+ import { randomUUID as randomUUID2 } from "node:crypto";
767
+ var SHOWN_PAYMENTS = 50;
768
+ var text = (value, max) => typeof value === "string" ? value.trim().slice(0, max) : "";
769
+
770
+ class OfferOwner {
771
+ ctx;
772
+ constructor(ctx) {
773
+ this.ctx = ctx;
774
+ }
775
+ async overview() {
776
+ this.ctx.requireOwner();
777
+ const { data, links } = this.ctx;
778
+ const agents = await this.ctx.conversations.agents();
779
+ const invites = new Set(data.offers.map((offer) => offer.invite?.id).filter((id) => !!id));
780
+ const joins = await links.waiting(invites);
781
+ const now = Date.now();
782
+ const answered = data.payments.filter((one) => one.status !== "waiting").slice(-SHOWN_PAYMENTS);
783
+ const payee = await this.ctx.store.payee();
784
+ return {
785
+ offers: data.offers.map((offer) => {
786
+ const agent = agents.find((one) => one.id === offer.agent);
787
+ return {
788
+ ...offer,
789
+ ...agent ? { agentName: agent.name, face: agent.face, mark: agent.mark, ...agent.model ? { model: agent.model } : {} } : { gone: true }
790
+ };
791
+ }),
792
+ users: data.users.map((user) => ({ ...user, state: this.ctx.state(user, now), online: links.online(user.member) })),
793
+ payments: [...data.payments.filter((one) => one.status === "waiting"), ...answered.reverse()],
794
+ payee: { picture: !!payee.picture, ...payee.note ? { note: payee.note } : {} },
795
+ joins: joins.map((join2) => ({
796
+ id: join2.id,
797
+ offer: data.offers.find((offer) => offer.invite?.id === join2.invite)?.id ?? "",
798
+ name: join2.name,
799
+ at: join2.at,
800
+ ...join2.account ? { account: join2.account.name ?? join2.account.id } : {}
801
+ }))
802
+ };
803
+ }
804
+ async agents() {
805
+ this.ctx.requireOwner();
806
+ return (await this.ctx.conversations.agents()).map(({ id, name, mark, face, model }) => ({
807
+ id,
808
+ name,
809
+ mark,
810
+ face,
811
+ role: "",
812
+ ...model ? { model } : {}
813
+ }));
814
+ }
815
+ async save(input) {
816
+ this.ctx.requireOwner();
817
+ const { data } = this.ctx;
818
+ const before = input?.id ? this.ctx.offer(input.id) : undefined;
819
+ const agent = await this.ctx.conversations.agent(String(input?.agent ?? before?.agent ?? ""));
820
+ if (!agent) {
821
+ throw new OfferError("No such agent.");
822
+ }
823
+ const plans = OfferQuota.clean(input?.plans ?? before?.plans, LIMITS);
824
+ if (!plans.length) {
825
+ throw new OfferError("An offer needs a plan at least.");
826
+ }
827
+ const trial = typeof input?.trial === "string" ? plans.find((plan) => plan.id === input.trial && plan.price === 0)?.id : undefined;
828
+ const approve = input?.approve !== false;
829
+ const offer = {
830
+ id: before?.id ?? randomUUID2(),
831
+ agent: agent.id,
832
+ name: text(input?.name, LIMITS.name) || agent.name,
833
+ ...text(input?.intro, LIMITS.intro) ? { intro: text(input?.intro, LIMITS.intro) } : {},
834
+ approve,
835
+ plans,
836
+ ...trial ? { trial } : {},
837
+ ...before?.invite ? { invite: before.invite } : {},
838
+ ...before?.past ? { past: before.past } : {},
839
+ ...before?.paused ? { paused: true } : {},
840
+ createdAt: before?.createdAt ?? Date.now()
841
+ };
842
+ const language = typeof input?.language === "string" ? input.language : undefined;
843
+ if (!offer.invite) {
844
+ offer.invite = await this.ctx.links.create(offer.name, approve, language);
845
+ } else if (before && before.approve !== approve) {
846
+ await this.ctx.links.setApprove(offer.invite.id, approve);
847
+ }
848
+ data.offers = before ? data.offers.map((one) => one.id === offer.id ? offer : one) : [...data.offers, offer];
849
+ await this.ctx.commit(before ? undefined : { what: "open", offer: offer.id, by: TA_OWNER });
850
+ return offer;
851
+ }
852
+ async renewLink(id, language) {
853
+ this.ctx.requireOwner();
854
+ const offer = this.ctx.offer(id);
855
+ const old = offer.invite;
856
+ offer.invite = await this.ctx.links.create(offer.name, offer.approve, typeof language === "string" ? language : undefined);
857
+ if (old) {
858
+ await this.ctx.links.stop(old.id);
859
+ offer.past = [...offer.past ?? [], old.id].slice(-20);
860
+ }
861
+ await this.ctx.commit();
862
+ return offer;
863
+ }
864
+ async setPaused(id, paused) {
865
+ this.ctx.requireOwner();
866
+ const offer = this.ctx.offer(id);
867
+ offer.paused = paused === true || undefined;
868
+ await this.ctx.commit({ what: paused === true ? "pause" : "resume", offer: offer.id, by: TA_OWNER });
869
+ }
870
+ async remove(id) {
871
+ this.ctx.requireOwner();
872
+ const { data, links } = this.ctx;
873
+ const offer = this.ctx.offer(id);
874
+ if (offer.invite) {
875
+ await links.stop(offer.invite.id);
876
+ }
877
+ const gone = data.users.filter((user) => user.offer === offer.id);
878
+ data.offers = data.offers.filter((one) => one !== offer);
879
+ data.users = data.users.filter((user) => user.offer !== offer.id);
880
+ for (const member of new Set(gone.map((user) => user.member))) {
881
+ if (!data.users.some((user) => user.member === member)) {
882
+ await links.remove(member);
883
+ }
884
+ }
885
+ await this.ctx.commit({ what: "close", offer: offer.id, by: TA_OWNER });
886
+ }
887
+ async answerJoin(join2, accept) {
888
+ this.ctx.requireOwner();
889
+ await this.ctx.links.answer(String(join2), accept === true);
890
+ }
891
+ async answerPayment(id, accept) {
892
+ this.ctx.requireOwner();
893
+ const { payment, user } = this.ctx.payments.answer(id, accept === true, TA_OWNER);
894
+ await this.ctx.commit({
895
+ what: accept === true ? "paid" : "refused",
896
+ offer: payment.offer,
897
+ user: payment.user,
898
+ plan: payment.plan,
899
+ amount: payment.amount,
900
+ by: TA_OWNER
901
+ });
902
+ if (user) {
903
+ await this.ctx.commit({ what: "grant", offer: user.offer, user: user.id, plan: payment.plan, by: TA_OWNER });
904
+ }
905
+ }
906
+ async grant(userId, plan, amount) {
907
+ this.ctx.requireOwner();
908
+ const user = this.ctx.user(userId);
909
+ const payment = this.ctx.payments.offline(user, this.ctx.offer(user.offer), plan, amount, TA_OWNER);
910
+ await this.ctx.commit({ what: "grant", offer: user.offer, user: user.id, plan: payment.plan, amount: payment.amount, by: TA_OWNER });
911
+ }
912
+ async setUserPaused(userId, paused) {
913
+ this.ctx.requireOwner();
914
+ const user = this.ctx.user(userId);
915
+ user.paused = paused === true || undefined;
916
+ await this.ctx.commit({ what: paused === true ? "pause" : "resume", offer: user.offer, user: user.id, by: TA_OWNER });
917
+ }
918
+ async removeUser(userId) {
919
+ this.ctx.requireOwner();
920
+ const { data } = this.ctx;
921
+ const user = this.ctx.user(userId);
922
+ data.users = data.users.filter((one) => one !== user);
923
+ if (!data.users.some((one) => one.member === user.member)) {
924
+ await this.ctx.links.remove(user.member);
925
+ }
926
+ await this.ctx.commit({ what: "remove", offer: user.offer, user: user.id, by: TA_OWNER });
927
+ }
928
+ async setPayee(input) {
929
+ this.ctx.requireOwner();
930
+ const before = await this.ctx.store.payee();
931
+ let picture = before.picture;
932
+ if (input?.picture === null) {
933
+ picture = undefined;
934
+ } else if (input?.picture !== undefined) {
935
+ if (typeof input.picture !== "string" || !/^data:image\/(png|jpeg|webp);base64,[A-Za-z0-9+/=]+$/.test(input.picture) || input.picture.length > LIMITS.picture) {
936
+ throw new OfferError("The code to pay by is a picture of PNG, JPEG or WebP, 300 KB at most.");
937
+ }
938
+ picture = input.picture;
939
+ }
940
+ const note = input?.note === undefined ? before.note : text(input.note, LIMITS.note);
941
+ await this.ctx.store.setPayee({ ...picture ? { picture } : {}, ...note ? { note } : {} });
942
+ }
943
+ }
944
+
945
+ // web-src/offer-use.ts
946
+ class OfferUse {
947
+ ctx;
948
+ constructor(ctx) {
949
+ this.ctx = ctx;
950
+ }
951
+ async mine() {
952
+ const member = this.ctx.caller();
953
+ if (!member) {
954
+ return [];
955
+ }
956
+ const users = await this.bind(member);
957
+ const agents = await this.ctx.conversations.agents();
958
+ const payee = await this.ctx.store.payee();
959
+ const now = Date.now();
960
+ return users.flatMap((user) => {
961
+ const offer = this.ctx.data.offers.find((one) => one.id === user.offer);
962
+ if (!offer) {
963
+ return [];
964
+ }
965
+ const agent = agents.find((one) => one.id === offer.agent);
966
+ const waiting = this.ctx.payments.waitingOf(user.id);
967
+ return [
968
+ {
969
+ offer: {
970
+ id: offer.id,
971
+ name: offer.name,
972
+ ...offer.intro ? { intro: offer.intro } : {},
973
+ ...agent ? { face: agent.face, mark: agent.mark } : {},
974
+ owner: member.owner,
975
+ plans: offer.plans,
976
+ ...offer.paused ? { paused: true } : {}
977
+ },
978
+ user: {
979
+ id: user.id,
980
+ name: user.name,
981
+ grant: user.grant,
982
+ used: user.used,
983
+ sessions: user.sessions,
984
+ ...user.paused ? { paused: true } : {}
985
+ },
986
+ state: this.ctx.state(user, now),
987
+ ...waiting ? { waiting: { id: waiting.id, plan: waiting.plan, amount: waiting.amount, code: waiting.code, at: waiting.at } } : {},
988
+ payable: !!payee.picture,
989
+ ...payee.note ? { payeeNote: payee.note } : {}
990
+ }
991
+ ];
992
+ });
993
+ }
994
+ async start(offerId) {
995
+ const { member, user, offer } = await this.of(offerId);
996
+ const state = this.ctx.state(user);
997
+ if (state.block !== "none") {
998
+ throw new OfferError(OfferTexts.blocked(state.block));
999
+ }
1000
+ const agent = await this.ctx.conversations.agent(offer.agent);
1001
+ if (!agent) {
1002
+ throw new OfferError(OfferTexts.blocked("closed"));
1003
+ }
1004
+ const { sessionId, sessionFile } = await this.ctx.conversations.start(member, offer, agent);
1005
+ if (sessionFile && !user.sessions.includes(sessionFile)) {
1006
+ user.sessions = [...user.sessions, sessionFile];
1007
+ }
1008
+ user.lastAt = Date.now();
1009
+ await this.ctx.commit();
1010
+ return { sessionId };
1011
+ }
1012
+ async pay(offerId, plan) {
1013
+ const { user, offer } = await this.of(offerId);
1014
+ const payment = this.ctx.payments.claim(user, offer, plan);
1015
+ await this.ctx.commit();
1016
+ await this.ctx.tell(`pay:${payment.id}`, OfferTexts.paidTitle(), OfferTexts.paid(user.name, offer.name, payment.amount, payment.code));
1017
+ return { id: payment.id, code: payment.code, amount: payment.amount };
1018
+ }
1019
+ async cancelPay(offerId, payment) {
1020
+ const { user } = await this.of(offerId);
1021
+ this.ctx.payments.cancel(user, payment);
1022
+ await this.ctx.commit();
1023
+ }
1024
+ async payee(offerId) {
1025
+ await this.of(offerId);
1026
+ return this.ctx.store.payee();
1027
+ }
1028
+ async of(offerId) {
1029
+ const member = this.ctx.caller();
1030
+ if (!member) {
1031
+ throw new OfferError("Only one let in to use an offer does this.");
1032
+ }
1033
+ const users = await this.bind(member);
1034
+ const user = users.find((one) => one.offer === offerId);
1035
+ const offer = user && this.ctx.data.offers.find((one) => one.id === user.offer);
1036
+ if (!user || !offer) {
1037
+ throw new OfferError("No such offer of yours.");
1038
+ }
1039
+ return { member, user, offer };
1040
+ }
1041
+ async bind(member) {
1042
+ const { data } = this.ctx;
1043
+ const offer = member.via ? data.offers.find((one) => one.invite?.id === member.via || one.past?.includes(member.via)) : undefined;
1044
+ if (offer && !data.users.some((user) => user.member === member.id && user.offer === offer.id)) {
1045
+ const now = Date.now();
1046
+ const trial = offer.plans.find((plan) => plan.id === offer.trial);
1047
+ const used = OfferQuota.emptyMeter(now);
1048
+ const user = {
1049
+ id: `${member.id}|${offer.id}`,
1050
+ member: member.id,
1051
+ offer: offer.id,
1052
+ name: member.name,
1053
+ joinedAt: now,
1054
+ ...trial ? { grant: OfferQuota.grant(trial, "trial", now) } : {},
1055
+ used,
1056
+ sessions: []
1057
+ };
1058
+ data.users.push(user);
1059
+ await this.ctx.commit({ what: "join", offer: offer.id, user: user.id, ...trial ? { plan: trial.id } : {}, by: member.id });
1060
+ }
1061
+ return data.users.filter((user) => user.member === member.id);
1062
+ }
1063
+ }
1064
+
1065
+ // web-src/offer-service.ts
1066
+ var TIDY_MS = 3600000;
1067
+
1068
+ class OfferService {
1069
+ ctx;
1070
+ owner;
1071
+ use;
1072
+ meters;
1073
+ timer;
1074
+ constructor(host) {
1075
+ this.ctx = new OfferContext(host);
1076
+ this.owner = new OfferOwner(this.ctx);
1077
+ this.use = new OfferUse(this.ctx);
1078
+ this.meters = new OfferMeterBook(this.ctx);
1079
+ }
1080
+ async start() {
1081
+ await this.ctx.store.load();
1082
+ const tidy = () => {
1083
+ this.ctx.payments.tidy();
1084
+ this.ctx.commit();
1085
+ };
1086
+ tidy();
1087
+ this.timer = setInterval(tidy, TIDY_MS);
1088
+ this.timer.unref?.();
1089
+ }
1090
+ dispose() {
1091
+ clearInterval(this.timer);
1092
+ }
1093
+ }
1094
+
1095
+ // web-src/host.ts
1096
+ async function activate(host) {
1097
+ const service = new OfferService(host);
1098
+ await service.start();
1099
+ const { owner, use } = service;
1100
+ return {
1101
+ _offer: service,
1102
+ dispose: () => service.dispose(),
1103
+ overview: () => owner.overview(),
1104
+ agents: () => owner.agents(),
1105
+ save: (input) => owner.save(input),
1106
+ renewLink: (offer, language) => owner.renewLink(offer, language),
1107
+ setPaused: (offer, paused) => owner.setPaused(offer, paused),
1108
+ remove: (offer) => owner.remove(offer),
1109
+ answerJoin: (join2, accept) => owner.answerJoin(join2, accept),
1110
+ answerPayment: (payment, accept) => owner.answerPayment(payment, accept),
1111
+ grant: (user, plan, amount) => owner.grant(user, plan, amount),
1112
+ setUserPaused: (user, paused) => owner.setUserPaused(user, paused),
1113
+ removeUser: (user) => owner.removeUser(user),
1114
+ setPayee: (input) => owner.setPayee(input),
1115
+ mine: () => use.mine(),
1116
+ start: (offer) => use.start(offer),
1117
+ pay: (offer, plan) => use.pay(offer, plan),
1118
+ cancelPay: (offer, payment) => use.cancelPay(offer, payment),
1119
+ payee: (offer) => use.payee(offer)
1120
+ };
1121
+ }
1122
+ export {
1123
+ activate as default
1124
+ };