@celljs/ta-offer 4.38.0 → 4.40.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/extension/index.mjs +16 -6
- package/host/index.mjs +2084 -48
- package/package.json +3 -3
- package/web/index.js +542 -57
package/host/index.mjs
CHANGED
|
@@ -1,3 +1,363 @@
|
|
|
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, "&").replace(/"/g, """).replace(/\n/g, " ");
|
|
279
|
+
}
|
|
280
|
+
function unquote(text) {
|
|
281
|
+
return text.replace(/"/g, '"').replace(/&/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
|
+
|
|
1
361
|
// ../ta-protocol/esm/common/language.js
|
|
2
362
|
var TaLanguageUtil;
|
|
3
363
|
(function(TaLanguageUtil2) {
|
|
@@ -37,6 +397,494 @@ var TaLanguageUtil;
|
|
|
37
397
|
TaLanguageUtil2.list = list;
|
|
38
398
|
})(TaLanguageUtil || (TaLanguageUtil = {}));
|
|
39
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
|
+
|
|
40
888
|
// ../ta-protocol/esm/common/team-protocol.js
|
|
41
889
|
var TA_OWNER = "owner";
|
|
42
890
|
var TA_UNDECLARED = "extensions.install";
|
|
@@ -151,6 +999,50 @@ var TaActionUtil;
|
|
|
151
999
|
TaActionUtil2.inside = inside;
|
|
152
1000
|
})(TaActionUtil || (TaActionUtil = {}));
|
|
153
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
|
+
|
|
154
1046
|
// ../ta-protocol/esm/common/redactor.js
|
|
155
1047
|
var REDACTED = "[redacted]";
|
|
156
1048
|
var WHOLE = [
|
|
@@ -248,7 +1140,7 @@ var OFFER_MARK = "[ta:offer]";
|
|
|
248
1140
|
var DATA_KEY = "data";
|
|
249
1141
|
var PAYEE_KEY = "payee";
|
|
250
1142
|
var EMPTY_DATA = { v: 1, offers: [], users: [], payments: [] };
|
|
251
|
-
var LIMITS = { name: 40, intro: 300, plans: 6, planName: 20, note: 300, picture: 400000 };
|
|
1143
|
+
var LIMITS = { name: 40, intro: 300, plans: 6, planName: 20, note: 300, picture: 400000, keys: 5, keyName: 30, clients: 10 };
|
|
252
1144
|
|
|
253
1145
|
// web-src/offer-conversations.ts
|
|
254
1146
|
var CHANNELS = "@celljs/ta-channels";
|
|
@@ -295,6 +1187,17 @@ class OfferConversations {
|
|
|
295
1187
|
return { sessionId, ...sessionFile ? { sessionFile } : {} };
|
|
296
1188
|
});
|
|
297
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
|
+
}
|
|
298
1201
|
}
|
|
299
1202
|
|
|
300
1203
|
// web-src/offer-links.ts
|
|
@@ -350,6 +1253,15 @@ class OfferLinks {
|
|
|
350
1253
|
const info = this.host.team.describe(principal);
|
|
351
1254
|
return info?.role === USER_ROLE ? info : undefined;
|
|
352
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
|
+
}
|
|
353
1265
|
online(member) {
|
|
354
1266
|
return (this.host.team.connected()[member] ?? 0) > 0;
|
|
355
1267
|
}
|
|
@@ -624,22 +1536,171 @@ class OfferStore {
|
|
|
624
1536
|
}
|
|
625
1537
|
}
|
|
626
1538
|
|
|
627
|
-
// web-src/offer-
|
|
628
|
-
|
|
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
|
+
}
|
|
629
1592
|
}
|
|
630
1593
|
|
|
631
|
-
class
|
|
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 {
|
|
632
1688
|
host;
|
|
633
1689
|
store;
|
|
634
1690
|
links;
|
|
635
1691
|
conversations;
|
|
636
1692
|
payments;
|
|
1693
|
+
turns;
|
|
1694
|
+
calls;
|
|
1695
|
+
connects = new OfferConnects;
|
|
637
1696
|
constructor(host) {
|
|
638
1697
|
this.host = host;
|
|
639
1698
|
this.store = new OfferStore(host);
|
|
640
1699
|
this.links = new OfferLinks(host);
|
|
641
1700
|
this.conversations = new OfferConversations(host);
|
|
642
1701
|
this.payments = new OfferPayments(this.store);
|
|
1702
|
+
this.turns = new OfferTurns(host);
|
|
1703
|
+
this.calls = new OfferCalls(this);
|
|
643
1704
|
}
|
|
644
1705
|
get data() {
|
|
645
1706
|
return this.store.data;
|
|
@@ -684,54 +1745,625 @@ class OfferContext {
|
|
|
684
1745
|
}
|
|
685
1746
|
}
|
|
686
1747
|
|
|
687
|
-
// web-src/offer-
|
|
688
|
-
|
|
689
|
-
|
|
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
|
+
}
|
|
690
1786
|
}
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
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();
|
|
695
1807
|
}
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
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
|
+
import { lookup } from "node:dns/promises";
|
|
1877
|
+
import { BlockList, isIP } from "node:net";
|
|
1878
|
+
var MCP_SCOPE = "ask";
|
|
1879
|
+
var CLIENT_PREFIX = "ta_ci_";
|
|
1880
|
+
var DOCUMENT_BYTES = 1e4;
|
|
1881
|
+
var DOCUMENT_MS = 5000;
|
|
1882
|
+
var DOCUMENT_KEEP_MS = 10 * 60000;
|
|
1883
|
+
var CORS = {
|
|
1884
|
+
"access-control-allow-origin": "*",
|
|
1885
|
+
"access-control-allow-methods": "GET, POST, OPTIONS",
|
|
1886
|
+
"access-control-allow-headers": "authorization, content-type, mcp-protocol-version, mcp-session-id, last-event-id",
|
|
1887
|
+
"access-control-expose-headers": "www-authenticate, mcp-session-id",
|
|
1888
|
+
"access-control-max-age": "600"
|
|
1889
|
+
};
|
|
1890
|
+
var json = (status, value, headers = {}) => ({
|
|
1891
|
+
status,
|
|
1892
|
+
headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store", ...CORS, ...headers },
|
|
1893
|
+
body: JSON.stringify(value)
|
|
1894
|
+
});
|
|
1895
|
+
var NOT_PUBLIC = new BlockList;
|
|
1896
|
+
for (const [network, prefix] of [
|
|
1897
|
+
["0.0.0.0", 8],
|
|
1898
|
+
["10.0.0.0", 8],
|
|
1899
|
+
["100.64.0.0", 10],
|
|
1900
|
+
["127.0.0.0", 8],
|
|
1901
|
+
["169.254.0.0", 16],
|
|
1902
|
+
["172.16.0.0", 12],
|
|
1903
|
+
["192.0.0.0", 24],
|
|
1904
|
+
["192.168.0.0", 16],
|
|
1905
|
+
["198.18.0.0", 15],
|
|
1906
|
+
["224.0.0.0", 4],
|
|
1907
|
+
["240.0.0.0", 4]
|
|
1908
|
+
]) {
|
|
1909
|
+
NOT_PUBLIC.addSubnet(network, prefix, "ipv4");
|
|
1910
|
+
}
|
|
1911
|
+
for (const [network, prefix] of [
|
|
1912
|
+
["::", 127],
|
|
1913
|
+
["64:ff9b::", 96],
|
|
1914
|
+
["fc00::", 7],
|
|
1915
|
+
["fe80::", 10],
|
|
1916
|
+
["ff00::", 8]
|
|
1917
|
+
]) {
|
|
1918
|
+
NOT_PUBLIC.addSubnet(network, prefix, "ipv6");
|
|
1919
|
+
}
|
|
1920
|
+
var resolveAll = async (host) => (await lookup(host, { all: true, verbatim: true })).map((one) => one.address);
|
|
1921
|
+
var LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]"]);
|
|
1922
|
+
var NOT_APPS = new Set(["javascript:", "data:", "vbscript:", "file:", "blob:", "about:", "ws:", "wss:", "ftp:"]);
|
|
1923
|
+
var OfferOAuthUtil;
|
|
1924
|
+
((OfferOAuthUtil) => {
|
|
1925
|
+
OfferOAuthUtil.answer = json;
|
|
1926
|
+
function urls(base) {
|
|
1927
|
+
const url = new URL(base);
|
|
1928
|
+
return {
|
|
1929
|
+
issuer: base,
|
|
1930
|
+
resource: `${base}/mcp`,
|
|
1931
|
+
authorize: `${base}/oauth/authorize`,
|
|
1932
|
+
token: `${base}/oauth/token`,
|
|
1933
|
+
register: `${base}/oauth/register`,
|
|
1934
|
+
resourceMetadata: `${url.origin}/.well-known/oauth-protected-resource${url.pathname}/mcp`
|
|
1935
|
+
};
|
|
1936
|
+
}
|
|
1937
|
+
OfferOAuthUtil.urls = urls;
|
|
1938
|
+
function resourceMetadata(base, name) {
|
|
1939
|
+
const at = urls(base);
|
|
1940
|
+
return json(200, {
|
|
1941
|
+
resource: at.resource,
|
|
1942
|
+
authorization_servers: [at.issuer],
|
|
1943
|
+
scopes_supported: [MCP_SCOPE],
|
|
1944
|
+
bearer_methods_supported: ["header"],
|
|
1945
|
+
resource_name: name
|
|
704
1946
|
});
|
|
705
1947
|
}
|
|
706
|
-
|
|
707
|
-
function
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
1948
|
+
OfferOAuthUtil.resourceMetadata = resourceMetadata;
|
|
1949
|
+
function serverMetadata(base) {
|
|
1950
|
+
const at = urls(base);
|
|
1951
|
+
return json(200, {
|
|
1952
|
+
issuer: at.issuer,
|
|
1953
|
+
authorization_endpoint: at.authorize,
|
|
1954
|
+
token_endpoint: at.token,
|
|
1955
|
+
registration_endpoint: at.register,
|
|
1956
|
+
scopes_supported: [MCP_SCOPE],
|
|
1957
|
+
response_types_supported: ["code"],
|
|
1958
|
+
response_modes_supported: ["query"],
|
|
1959
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
1960
|
+
code_challenge_methods_supported: ["S256"],
|
|
1961
|
+
token_endpoint_auth_methods_supported: ["none"],
|
|
1962
|
+
client_id_metadata_document_supported: true,
|
|
1963
|
+
authorization_response_iss_parameter_supported: true
|
|
1964
|
+
});
|
|
1965
|
+
}
|
|
1966
|
+
OfferOAuthUtil.serverMetadata = serverMetadata;
|
|
1967
|
+
function error(status, code, description) {
|
|
1968
|
+
return json(status, { error: code, error_description: description });
|
|
1969
|
+
}
|
|
1970
|
+
OfferOAuthUtil.error = error;
|
|
1971
|
+
function challenge(base, message, invalid) {
|
|
1972
|
+
const parts = [
|
|
1973
|
+
...base ? [`resource_metadata="${urls(base).resourceMetadata}"`] : [],
|
|
1974
|
+
`scope="${MCP_SCOPE}"`,
|
|
1975
|
+
...invalid ? ['error="invalid_token"'] : []
|
|
1976
|
+
];
|
|
1977
|
+
return json(401, { error: invalid ? "invalid_token" : "unauthorized", error_description: message }, { "www-authenticate": `Bearer ${parts.join(", ")}` });
|
|
1978
|
+
}
|
|
1979
|
+
OfferOAuthUtil.challenge = challenge;
|
|
1980
|
+
function redirectable(uri) {
|
|
1981
|
+
if (typeof uri !== "string" || uri.length > 500) {
|
|
1982
|
+
return false;
|
|
1983
|
+
}
|
|
1984
|
+
let url;
|
|
1985
|
+
try {
|
|
1986
|
+
url = new URL(uri);
|
|
1987
|
+
} catch {
|
|
1988
|
+
return false;
|
|
1989
|
+
}
|
|
1990
|
+
if (url.hash || uri.includes("#") || url.username || url.password) {
|
|
1991
|
+
return false;
|
|
1992
|
+
}
|
|
1993
|
+
if (url.protocol === "https:") {
|
|
1994
|
+
return true;
|
|
1995
|
+
}
|
|
1996
|
+
if (url.protocol === "http:") {
|
|
1997
|
+
return LOOPBACK.has(url.hostname);
|
|
1998
|
+
}
|
|
1999
|
+
return /^[a-z][a-z0-9+.-]*:$/.test(url.protocol) && !NOT_APPS.has(url.protocol);
|
|
2000
|
+
}
|
|
2001
|
+
OfferOAuthUtil.redirectable = redirectable;
|
|
2002
|
+
function listed(uri, redirects) {
|
|
2003
|
+
return redirects.some((one) => {
|
|
2004
|
+
if (one === uri) {
|
|
2005
|
+
return true;
|
|
2006
|
+
}
|
|
2007
|
+
try {
|
|
2008
|
+
const [a, b] = [new URL(one), new URL(uri)];
|
|
2009
|
+
return a.protocol === "http:" && LOOPBACK.has(a.hostname) && a.hostname === b.hostname && a.pathname === b.pathname && a.search === b.search;
|
|
2010
|
+
} catch {
|
|
2011
|
+
return false;
|
|
2012
|
+
}
|
|
2013
|
+
});
|
|
2014
|
+
}
|
|
2015
|
+
OfferOAuthUtil.listed = listed;
|
|
2016
|
+
function register(secret, name, redirects) {
|
|
2017
|
+
const said = Buffer.from(JSON.stringify({ n: name, r: redirects })).toString("base64url");
|
|
2018
|
+
return `${CLIENT_PREFIX}${said}.${sign(secret, said)}`;
|
|
2019
|
+
}
|
|
2020
|
+
OfferOAuthUtil.register = register;
|
|
2021
|
+
async function client(secret, id, read = fetch, resolve = resolveAll) {
|
|
2022
|
+
if (typeof id !== "string" || id.length > 4000) {
|
|
2023
|
+
return;
|
|
2024
|
+
}
|
|
2025
|
+
if (id.startsWith(CLIENT_PREFIX)) {
|
|
2026
|
+
const [said, signature] = id.slice(CLIENT_PREFIX.length).split(".");
|
|
2027
|
+
if (!secret || !said || !signature || !same(signature, sign(secret, said))) {
|
|
2028
|
+
return;
|
|
2029
|
+
}
|
|
2030
|
+
try {
|
|
2031
|
+
const { n: n2, r } = JSON.parse(Buffer.from(said, "base64url").toString("utf8"));
|
|
2032
|
+
return { id, name: n2, redirects: r };
|
|
2033
|
+
} catch {
|
|
2034
|
+
return;
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
return document(id, read, resolve);
|
|
2038
|
+
}
|
|
2039
|
+
OfferOAuthUtil.client = client;
|
|
2040
|
+
function publicAddress(address) {
|
|
2041
|
+
const family = isIP(address);
|
|
2042
|
+
return family !== 0 && !NOT_PUBLIC.check(address, family === 4 ? "ipv4" : "ipv6");
|
|
2043
|
+
}
|
|
2044
|
+
OfferOAuthUtil.publicAddress = publicAddress;
|
|
2045
|
+
function verifies(verifier, challenge2) {
|
|
2046
|
+
if (typeof verifier !== "string" || !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) {
|
|
2047
|
+
return false;
|
|
2048
|
+
}
|
|
2049
|
+
return same(createHash3("sha256").update(verifier).digest("base64url"), challenge2);
|
|
2050
|
+
}
|
|
2051
|
+
OfferOAuthUtil.verifies = verifies;
|
|
2052
|
+
function nameOf(value, fallback) {
|
|
2053
|
+
const name = typeof value === "string" ? value.replace(/\p{Cc}|[<>]/gu, "").trim().slice(0, 60) : "";
|
|
2054
|
+
return name || fallback;
|
|
2055
|
+
}
|
|
2056
|
+
OfferOAuthUtil.nameOf = nameOf;
|
|
2057
|
+
const documents = new Map;
|
|
2058
|
+
async function document(id, read, resolve) {
|
|
2059
|
+
let url;
|
|
2060
|
+
try {
|
|
2061
|
+
url = new URL(id);
|
|
2062
|
+
} catch {
|
|
2063
|
+
return;
|
|
2064
|
+
}
|
|
2065
|
+
const host = url.hostname;
|
|
2066
|
+
if (url.protocol !== "https:" || url.pathname === "/" || url.hash || url.username || /^[\d.]+$|^\[|^localhost$|\.local$|\.localhost$|\.internal$/i.test(host) || !host.includes(".")) {
|
|
2067
|
+
return;
|
|
2068
|
+
}
|
|
2069
|
+
const now = Date.now();
|
|
2070
|
+
const kept = documents.get(id);
|
|
2071
|
+
if (kept && kept.until > now) {
|
|
2072
|
+
return kept.client;
|
|
2073
|
+
}
|
|
2074
|
+
let client2;
|
|
2075
|
+
try {
|
|
2076
|
+
const addresses = await resolve(host);
|
|
2077
|
+
if (!addresses.length || !addresses.every(publicAddress)) {
|
|
2078
|
+
throw new Error("Not of the internet.");
|
|
2079
|
+
}
|
|
2080
|
+
const answer2 = await read(id, { redirect: "error", signal: AbortSignal.timeout(DOCUMENT_MS), headers: { accept: "application/json" } });
|
|
2081
|
+
const text = answer2.ok ? await answer2.text() : "";
|
|
2082
|
+
const value = text && text.length <= DOCUMENT_BYTES ? JSON.parse(text) : undefined;
|
|
2083
|
+
const redirects = Array.isArray(value?.redirect_uris) ? value.redirect_uris.filter(redirectable).slice(0, 10) : [];
|
|
2084
|
+
if (value && value.client_id === id && redirects.length) {
|
|
2085
|
+
client2 = { id, name: nameOf(value.client_name, host), redirects };
|
|
2086
|
+
}
|
|
2087
|
+
} catch {
|
|
2088
|
+
client2 = undefined;
|
|
2089
|
+
}
|
|
2090
|
+
documents.set(id, { ...client2 ? { client: client2 } : {}, until: now + DOCUMENT_KEEP_MS });
|
|
2091
|
+
for (const [other, one] of documents) {
|
|
2092
|
+
if (one.until <= now) {
|
|
2093
|
+
documents.delete(other);
|
|
2094
|
+
}
|
|
2095
|
+
}
|
|
2096
|
+
return client2;
|
|
2097
|
+
}
|
|
2098
|
+
function sign(secret, text) {
|
|
2099
|
+
return createHmac("sha256", secret).update(text).digest("base64url").slice(0, 32);
|
|
2100
|
+
}
|
|
2101
|
+
function same(a, b) {
|
|
2102
|
+
const [x, y] = [Buffer.from(a), Buffer.from(b)];
|
|
2103
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
2104
|
+
}
|
|
2105
|
+
})(OfferOAuthUtil ||= {});
|
|
2106
|
+
|
|
2107
|
+
// web-src/offer-mcp-wire.ts
|
|
2108
|
+
var MCP_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26"];
|
|
2109
|
+
var MCP_PING_MS = 20000;
|
|
2110
|
+
var MCP_ERRORS = { parse: -32700, request: -32600, method: -32601, params: -32602, internal: -32603 };
|
|
2111
|
+
var HEADERS = { "cache-control": "no-store", ...CORS };
|
|
2112
|
+
var OfferMcpWire;
|
|
2113
|
+
((OfferMcpWire) => {
|
|
2114
|
+
function read(body) {
|
|
2115
|
+
let value;
|
|
2116
|
+
try {
|
|
2117
|
+
value = JSON.parse(body || "null");
|
|
2118
|
+
} catch {
|
|
2119
|
+
return "parse";
|
|
2120
|
+
}
|
|
2121
|
+
const message = value;
|
|
2122
|
+
return message && typeof message === "object" && !Array.isArray(message) && message.jsonrpc === "2.0" ? message : "request";
|
|
2123
|
+
}
|
|
2124
|
+
OfferMcpWire.read = read;
|
|
2125
|
+
function result(id, result2) {
|
|
2126
|
+
return JSON.stringify({ jsonrpc: "2.0", id: id ?? null, result: result2 });
|
|
2127
|
+
}
|
|
2128
|
+
OfferMcpWire.result = result;
|
|
2129
|
+
function error(id, code, message) {
|
|
2130
|
+
return JSON.stringify({ jsonrpc: "2.0", id: id ?? null, error: { code, message } });
|
|
2131
|
+
}
|
|
2132
|
+
OfferMcpWire.error = error;
|
|
2133
|
+
function notification(method, params) {
|
|
2134
|
+
return JSON.stringify({ jsonrpc: "2.0", method, params });
|
|
2135
|
+
}
|
|
2136
|
+
OfferMcpWire.notification = notification;
|
|
2137
|
+
function json2(message, status = 200) {
|
|
2138
|
+
return { status, headers: { "content-type": "application/json; charset=utf-8", ...HEADERS }, body: message };
|
|
2139
|
+
}
|
|
2140
|
+
OfferMcpWire.json = json2;
|
|
2141
|
+
function accepted() {
|
|
2142
|
+
return { status: 202, headers: { ...HEADERS } };
|
|
2143
|
+
}
|
|
2144
|
+
OfferMcpWire.accepted = accepted;
|
|
2145
|
+
function event(message) {
|
|
2146
|
+
return `event: message
|
|
2147
|
+
data: ${message}
|
|
2148
|
+
|
|
2149
|
+
`;
|
|
2150
|
+
}
|
|
2151
|
+
OfferMcpWire.event = event;
|
|
2152
|
+
function streams(headers) {
|
|
2153
|
+
return (headers.accept ?? "").includes("text/event-stream");
|
|
2154
|
+
}
|
|
2155
|
+
OfferMcpWire.streams = streams;
|
|
2156
|
+
async function answer(headers, work) {
|
|
2157
|
+
if (!streams(headers)) {
|
|
2158
|
+
return json2(await work(() => {
|
|
2159
|
+
return;
|
|
2160
|
+
}));
|
|
2161
|
+
}
|
|
2162
|
+
const pipe = new Pipe;
|
|
2163
|
+
const timer = setInterval(() => pipe.push(`: ping
|
|
2164
|
+
|
|
2165
|
+
`), MCP_PING_MS);
|
|
2166
|
+
timer.unref?.();
|
|
2167
|
+
work((message) => pipe.push(event(message))).catch((failure) => error(undefined, MCP_ERRORS.internal, failure instanceof Error ? failure.message : String(failure))).then((last) => {
|
|
2168
|
+
clearInterval(timer);
|
|
2169
|
+
pipe.push(event(last));
|
|
2170
|
+
pipe.close();
|
|
2171
|
+
});
|
|
2172
|
+
return { status: 200, headers: { "content-type": "text/event-stream; charset=utf-8", ...HEADERS }, body: pipe.read() };
|
|
2173
|
+
}
|
|
2174
|
+
OfferMcpWire.answer = answer;
|
|
2175
|
+
})(OfferMcpWire ||= {});
|
|
2176
|
+
|
|
2177
|
+
class Pipe {
|
|
2178
|
+
queue = [];
|
|
2179
|
+
wake;
|
|
2180
|
+
closed = false;
|
|
2181
|
+
push(text) {
|
|
2182
|
+
if (!this.closed) {
|
|
2183
|
+
this.queue.push(text);
|
|
2184
|
+
this.wake?.();
|
|
2185
|
+
}
|
|
2186
|
+
}
|
|
2187
|
+
close() {
|
|
2188
|
+
this.closed = true;
|
|
2189
|
+
this.wake?.();
|
|
2190
|
+
}
|
|
2191
|
+
async* read() {
|
|
2192
|
+
for (;; ) {
|
|
2193
|
+
const text = this.queue.shift();
|
|
2194
|
+
if (text !== undefined) {
|
|
2195
|
+
yield text;
|
|
2196
|
+
} else if (this.closed) {
|
|
2197
|
+
return;
|
|
2198
|
+
} else {
|
|
2199
|
+
await new Promise((resolve) => {
|
|
2200
|
+
this.wake = resolve;
|
|
715
2201
|
});
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
2202
|
+
this.wake = undefined;
|
|
2203
|
+
}
|
|
2204
|
+
}
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
|
|
2208
|
+
// web-src/offer-mcp.ts
|
|
2209
|
+
var TOOL = "ask";
|
|
2210
|
+
var RELATED = "io.modelcontextprotocol/related-task";
|
|
2211
|
+
var PROGRESS_MS = 1000;
|
|
2212
|
+
var PROGRESS_CHARS = 200;
|
|
2213
|
+
var failed = (text) => ({ content: [{ type: "text", text }], isError: true });
|
|
2214
|
+
|
|
2215
|
+
class OfferMcp {
|
|
2216
|
+
ctx;
|
|
2217
|
+
tasks = new OfferMcpTasks;
|
|
2218
|
+
constructor(ctx) {
|
|
2219
|
+
this.ctx = ctx;
|
|
2220
|
+
}
|
|
2221
|
+
async http(request) {
|
|
2222
|
+
const method = request.method.toUpperCase();
|
|
2223
|
+
if (method === "OPTIONS") {
|
|
2224
|
+
return { status: 204, headers: { ...CORS } };
|
|
2225
|
+
}
|
|
2226
|
+
const caller = this.ctx.calls.caller(request.headers, "mcp");
|
|
2227
|
+
if ("refused" in caller) {
|
|
2228
|
+
return caller.status === 401 ? OfferOAuthUtil.challenge(request.base, caller.message, !!request.headers.authorization) : OfferOAuthUtil.answer(caller.status, { error: caller.code, error_description: caller.message });
|
|
2229
|
+
}
|
|
2230
|
+
if (method !== "POST") {
|
|
2231
|
+
return { status: 405, headers: { allow: "POST, OPTIONS", ...CORS } };
|
|
2232
|
+
}
|
|
2233
|
+
const message = OfferMcpWire.read(request.body);
|
|
2234
|
+
if (typeof message === "string") {
|
|
2235
|
+
return OfferMcpWire.json(OfferMcpWire.error(undefined, message === "parse" ? MCP_ERRORS.parse : MCP_ERRORS.request, "Not a JSON-RPC message."), 400);
|
|
2236
|
+
}
|
|
2237
|
+
if (message.id === undefined || !message.method) {
|
|
2238
|
+
return OfferMcpWire.accepted();
|
|
2239
|
+
}
|
|
2240
|
+
return this.answer(caller, message, request);
|
|
2241
|
+
}
|
|
2242
|
+
async answer(caller, message, request) {
|
|
2243
|
+
const { id } = message;
|
|
2244
|
+
const params = message.params ?? {};
|
|
2245
|
+
const owner = caller.user.id;
|
|
2246
|
+
const reply = (result) => OfferMcpWire.json(OfferMcpWire.result(id, result));
|
|
2247
|
+
const wrong = (code, text) => OfferMcpWire.json(OfferMcpWire.error(id, code, text));
|
|
2248
|
+
switch (message.method) {
|
|
2249
|
+
case "initialize": {
|
|
2250
|
+
const asked = String(params.protocolVersion ?? "");
|
|
2251
|
+
return reply({
|
|
2252
|
+
protocolVersion: MCP_VERSIONS.includes(asked) ? asked : MCP_VERSIONS[0],
|
|
2253
|
+
capabilities: { tools: {}, tasks: { list: {}, cancel: {}, requests: { tools: { call: {} } } } },
|
|
2254
|
+
serverInfo: { name: "ta-offer", title: caller.offer.name, version: "1" },
|
|
2255
|
+
instructions: this.describe(caller)
|
|
723
2256
|
});
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
2257
|
+
}
|
|
2258
|
+
case "ping":
|
|
2259
|
+
return reply({});
|
|
2260
|
+
case "tools/list":
|
|
2261
|
+
return reply({ tools: [this.tool(caller)] });
|
|
2262
|
+
case "tools/call":
|
|
2263
|
+
return this.call(caller, id, params, request);
|
|
2264
|
+
case "tasks/get": {
|
|
2265
|
+
const task = this.tasks.get(owner, params.taskId);
|
|
2266
|
+
return task ? reply(task) : wrong(MCP_ERRORS.params, "Failed to retrieve task: Task not found");
|
|
2267
|
+
}
|
|
2268
|
+
case "tasks/list":
|
|
2269
|
+
return params.cursor ? wrong(MCP_ERRORS.params, "Invalid cursor.") : reply({ tasks: this.tasks.list(owner) });
|
|
2270
|
+
case "tasks/cancel": {
|
|
2271
|
+
const task = this.tasks.cancel(owner, params.taskId);
|
|
2272
|
+
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");
|
|
2273
|
+
}
|
|
2274
|
+
case "tasks/result":
|
|
2275
|
+
if (!this.tasks.get(owner, params.taskId)) {
|
|
2276
|
+
return wrong(MCP_ERRORS.params, "Failed to retrieve task: Task not found");
|
|
2277
|
+
}
|
|
2278
|
+
return OfferMcpWire.answer(request.headers, async () => {
|
|
2279
|
+
const done = await this.tasks.result(owner, params.taskId);
|
|
2280
|
+
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");
|
|
730
2281
|
});
|
|
2282
|
+
default:
|
|
2283
|
+
return wrong(MCP_ERRORS.method, `No method ${message.method}.`);
|
|
731
2284
|
}
|
|
732
2285
|
}
|
|
733
|
-
|
|
734
|
-
|
|
2286
|
+
async call(caller, id, params, request) {
|
|
2287
|
+
const args = params.arguments ?? {};
|
|
2288
|
+
if (params.name !== TOOL) {
|
|
2289
|
+
return OfferMcpWire.json(OfferMcpWire.error(id, MCP_ERRORS.params, `No tool ${String(params.name)}; this server has "${TOOL}".`));
|
|
2290
|
+
}
|
|
2291
|
+
if (typeof args.message !== "string" || !args.message.trim() || args.conversation !== undefined && typeof args.conversation !== "string") {
|
|
2292
|
+
return OfferMcpWire.json(OfferMcpWire.result(id, failed('Give "message" (text), and "conversation" (an id ask gave) to go on with one.')));
|
|
2293
|
+
}
|
|
2294
|
+
const input = { text: args.message, ...args.conversation ? { conversation: args.conversation } : {} };
|
|
2295
|
+
const task = params.task;
|
|
2296
|
+
if (task && typeof task === "object") {
|
|
2297
|
+
const made = this.tasks.start(caller.user.id, task.ttl, (signal) => this.ask(caller, input, signal));
|
|
2298
|
+
return OfferMcpWire.json(OfferMcpWire.result(id, { task: made }));
|
|
2299
|
+
}
|
|
2300
|
+
const token = params._meta?.progressToken;
|
|
2301
|
+
return OfferMcpWire.answer(request.headers, async (notify) => {
|
|
2302
|
+
let said = "";
|
|
2303
|
+
let at = 0;
|
|
2304
|
+
let n2 = 0;
|
|
2305
|
+
const result = await this.ask(caller, input, request.signal, (part) => {
|
|
2306
|
+
said += part;
|
|
2307
|
+
n2 += 1;
|
|
2308
|
+
const now = Date.now();
|
|
2309
|
+
if ((typeof token === "string" || typeof token === "number") && now - at >= PROGRESS_MS) {
|
|
2310
|
+
at = now;
|
|
2311
|
+
notify(OfferMcpWire.notification("notifications/progress", { progressToken: token, progress: n2, message: said.slice(-PROGRESS_CHARS) }));
|
|
2312
|
+
}
|
|
2313
|
+
});
|
|
2314
|
+
return OfferMcpWire.result(id, result);
|
|
2315
|
+
});
|
|
2316
|
+
}
|
|
2317
|
+
async ask(caller, input, signal, part) {
|
|
2318
|
+
const call = await this.ctx.calls.ask(caller, input, signal);
|
|
2319
|
+
if ("refused" in call) {
|
|
2320
|
+
return failed(call.message);
|
|
2321
|
+
}
|
|
2322
|
+
for await (const text of call.turn.parts) {
|
|
2323
|
+
part?.(text);
|
|
2324
|
+
}
|
|
2325
|
+
const end = await call.turn.done;
|
|
2326
|
+
const short = OfferCalls.failure(end);
|
|
2327
|
+
if (short) {
|
|
2328
|
+
return failed(short.message);
|
|
2329
|
+
}
|
|
2330
|
+
return {
|
|
2331
|
+
content: [
|
|
2332
|
+
{ type: "text", text: end.text },
|
|
2333
|
+
{ type: "text", text: `(To go on with this conversation, call ${TOOL} with conversation "${call.conversation}".)` }
|
|
2334
|
+
],
|
|
2335
|
+
structuredContent: { answer: end.text, conversation: call.conversation }
|
|
2336
|
+
};
|
|
2337
|
+
}
|
|
2338
|
+
describe(caller) {
|
|
2339
|
+
const { offer, member } = caller;
|
|
2340
|
+
const intro = offer.intro ? `: ${offer.intro}` : ".";
|
|
2341
|
+
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.`;
|
|
2342
|
+
}
|
|
2343
|
+
tool(caller) {
|
|
2344
|
+
return {
|
|
2345
|
+
name: TOOL,
|
|
2346
|
+
title: caller.offer.name,
|
|
2347
|
+
description: `${this.describe(caller)} What it uses counts in your plan.`,
|
|
2348
|
+
inputSchema: {
|
|
2349
|
+
type: "object",
|
|
2350
|
+
properties: {
|
|
2351
|
+
message: { type: "string", description: "What to ask or tell it." },
|
|
2352
|
+
conversation: { type: "string", description: "The conversation to go on with, as an earlier call gave it; none starts a new one." }
|
|
2353
|
+
},
|
|
2354
|
+
required: ["message"],
|
|
2355
|
+
additionalProperties: false
|
|
2356
|
+
},
|
|
2357
|
+
outputSchema: {
|
|
2358
|
+
type: "object",
|
|
2359
|
+
properties: { answer: { type: "string" }, conversation: { type: "string" } },
|
|
2360
|
+
required: ["answer", "conversation"]
|
|
2361
|
+
},
|
|
2362
|
+
annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: true },
|
|
2363
|
+
execution: { taskSupport: "optional" }
|
|
2364
|
+
};
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
735
2367
|
|
|
736
2368
|
// web-src/offer-meter.ts
|
|
737
2369
|
class OfferMeterBook {
|
|
@@ -762,8 +2394,335 @@ class OfferMeterBook {
|
|
|
762
2394
|
}
|
|
763
2395
|
}
|
|
764
2396
|
|
|
2397
|
+
// web-src/offer-oauth.ts
|
|
2398
|
+
import { randomBytes as randomBytes3, randomUUID as randomUUID4 } from "node:crypto";
|
|
2399
|
+
|
|
2400
|
+
// web-src/offer-oauth-page.ts
|
|
2401
|
+
var WORDS = {
|
|
2402
|
+
"zh-CN": {
|
|
2403
|
+
title: "连接到 Ta",
|
|
2404
|
+
asks: "「{client}」想以你的身份使用开放给你的智能体。",
|
|
2405
|
+
where: "连上后会回到:{where}",
|
|
2406
|
+
how: "在 Ta 的「开放给我的」里点「连接 MCP 客户端」,把显示的连接码填在下面。不是你自己发起的,关掉这页就好。",
|
|
2407
|
+
code: "连接码",
|
|
2408
|
+
connect: "连接",
|
|
2409
|
+
wrong: "连接码不对或已过期,回 Ta 里重新拿一个。",
|
|
2410
|
+
blocked: "试错太多次了,10 分钟后再试。",
|
|
2411
|
+
bad: "这个连接请求不完整,回到客户端重新连接。",
|
|
2412
|
+
off: "提供者关掉了 API 调用,暂时连不上。"
|
|
2413
|
+
},
|
|
2414
|
+
"zh-TW": {
|
|
2415
|
+
title: "連接到 Ta",
|
|
2416
|
+
asks: "「{client}」想以你的身分使用開放給你的智慧體。",
|
|
2417
|
+
where: "連上後會回到:{where}",
|
|
2418
|
+
how: "在 Ta 的「開放給我的」裡點「連接 MCP 用戶端」,把顯示的連接碼填在下面。不是你自己發起的,關掉這頁就好。",
|
|
2419
|
+
code: "連接碼",
|
|
2420
|
+
connect: "連接",
|
|
2421
|
+
wrong: "連接碼不對或已過期,回 Ta 裡重新拿一個。",
|
|
2422
|
+
blocked: "試錯太多次了,10 分鐘後再試。",
|
|
2423
|
+
bad: "這個連接請求不完整,回到用戶端重新連接。",
|
|
2424
|
+
off: "提供者關掉了 API 呼叫,暫時連不上。"
|
|
2425
|
+
},
|
|
2426
|
+
"en-US": {
|
|
2427
|
+
title: "Connect to Ta",
|
|
2428
|
+
asks: "“{client}” wants to use the agent opened to you, as you.",
|
|
2429
|
+
where: "Once connected it goes back to: {where}",
|
|
2430
|
+
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.",
|
|
2431
|
+
code: "Code",
|
|
2432
|
+
connect: "Connect",
|
|
2433
|
+
wrong: "That code is wrong or expired; get a new one in Ta.",
|
|
2434
|
+
blocked: "Too many wrong tries; try again in 10 minutes.",
|
|
2435
|
+
bad: "This request to connect is incomplete; connect again from the client.",
|
|
2436
|
+
off: "The owner turned off the API; it cannot connect for now."
|
|
2437
|
+
},
|
|
2438
|
+
"ja-JP": {
|
|
2439
|
+
title: "Ta に接続",
|
|
2440
|
+
asks: "「{client}」があなたとして、公開されたエージェントを使おうとしています。",
|
|
2441
|
+
where: "接続後の戻り先:{where}",
|
|
2442
|
+
how: "Ta の「公開されたもの」で「MCP クライアントを接続」を押し、表示された接続コードを下に入力してください。心当たりがなければこのページを閉じてください。",
|
|
2443
|
+
code: "接続コード",
|
|
2444
|
+
connect: "接続",
|
|
2445
|
+
wrong: "接続コードが違うか期限切れです。Ta で新しいコードを取得してください。",
|
|
2446
|
+
blocked: "失敗が多すぎます。10 分後にもう一度お試しください。",
|
|
2447
|
+
bad: "この接続リクエストは不完全です。クライアントから接続し直してください。",
|
|
2448
|
+
off: "提供者が API を停止しました。今は接続できません。"
|
|
2449
|
+
}
|
|
2450
|
+
};
|
|
2451
|
+
var htmlOf = (text) => text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
|
|
2452
|
+
var STYLE = `
|
|
2453
|
+
:root{color-scheme:light dark;--fg:#1f1f1f;--muted:#6b6b6b;--line:#e5e5e5;--bg:#f7f7f7;--card:#fff;--accent:#16a34a;--bad:#dc2626}
|
|
2454
|
+
@media (prefers-color-scheme:dark){:root{--fg:#ececec;--muted:#9a9a9a;--line:#333;--bg:#141414;--card:#1e1e1e}}
|
|
2455
|
+
*{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)}
|
|
2456
|
+
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}
|
|
2457
|
+
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}
|
|
2458
|
+
.error{color:var(--bad);font-size:.875rem}label{display:block;font-size:.8125rem;color:var(--muted);margin:16px 0 6px}
|
|
2459
|
+
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}
|
|
2460
|
+
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}
|
|
2461
|
+
`;
|
|
2462
|
+
var OfferOAuthPage;
|
|
2463
|
+
((OfferOAuthPage) => {
|
|
2464
|
+
function language(headers) {
|
|
2465
|
+
return TaLanguageUtil.of(headers["accept-language"]?.split(",")[0]);
|
|
2466
|
+
}
|
|
2467
|
+
OfferOAuthPage.language = language;
|
|
2468
|
+
function ask(language2, client, redirect, action2, problem) {
|
|
2469
|
+
const words = WORDS[language2];
|
|
2470
|
+
let where = redirect;
|
|
2471
|
+
try {
|
|
2472
|
+
const url = new URL(redirect);
|
|
2473
|
+
where = url.host ? `${url.protocol}//${url.host}` : url.protocol;
|
|
2474
|
+
} catch {}
|
|
2475
|
+
const body = `<h1>${htmlOf(words.title)}</h1>
|
|
2476
|
+
<p>${htmlOf(words.asks.replace("{client}", client))}</p>
|
|
2477
|
+
<p class="muted">${htmlOf(words.where.replace("{where}", where))}</p>
|
|
2478
|
+
<p class="muted">${htmlOf(words.how)}</p>
|
|
2479
|
+
${problem ? `<p class="error">${htmlOf(words[problem])}</p>` : ""}
|
|
2480
|
+
<form method="post" action="?${htmlOf(action2)}">
|
|
2481
|
+
<label for="code">${htmlOf(words.code)}</label>
|
|
2482
|
+
<input id="code" name="code" autocomplete="one-time-code" autocapitalize="characters" spellcheck="false" maxlength="16" required autofocus placeholder="XXXXX-XXXXX">
|
|
2483
|
+
<button type="submit">${htmlOf(words.connect)}</button>
|
|
2484
|
+
</form>`;
|
|
2485
|
+
return html(language2, words.title, body, problem === "blocked" ? 429 : problem ? 400 : 200);
|
|
2486
|
+
}
|
|
2487
|
+
OfferOAuthPage.ask = ask;
|
|
2488
|
+
function failed2(language2, problem) {
|
|
2489
|
+
const words = WORDS[language2];
|
|
2490
|
+
return html(language2, words.title, `<h1>${htmlOf(words.title)}</h1><p class="error">${htmlOf(words[problem])}</p>`, problem === "off" ? 403 : 400);
|
|
2491
|
+
}
|
|
2492
|
+
OfferOAuthPage.failed = failed2;
|
|
2493
|
+
function html(language2, title, body, status) {
|
|
2494
|
+
return {
|
|
2495
|
+
status,
|
|
2496
|
+
headers: {
|
|
2497
|
+
"content-type": "text/html; charset=utf-8",
|
|
2498
|
+
"cache-control": "no-store",
|
|
2499
|
+
"referrer-policy": "no-referrer",
|
|
2500
|
+
"x-frame-options": "DENY",
|
|
2501
|
+
"content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'"
|
|
2502
|
+
},
|
|
2503
|
+
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>`
|
|
2504
|
+
};
|
|
2505
|
+
}
|
|
2506
|
+
})(OfferOAuthPage ||= {});
|
|
2507
|
+
|
|
2508
|
+
// web-src/offer-oauth.ts
|
|
2509
|
+
var CODE_MS = 5 * 60000;
|
|
2510
|
+
var ACCESS_MS = 60 * 60000;
|
|
2511
|
+
var REFRESH_MS = 30 * 24 * 60 * 60000;
|
|
2512
|
+
var CODES_MAX = 500;
|
|
2513
|
+
var form = (request) => {
|
|
2514
|
+
if ((request.headers["content-type"] ?? "").includes("application/json")) {
|
|
2515
|
+
try {
|
|
2516
|
+
const value = JSON.parse(request.body || "{}");
|
|
2517
|
+
return new URLSearchParams(Object.entries(value).flatMap(([key, one]) => typeof one === "string" ? [[key, one]] : []));
|
|
2518
|
+
} catch {
|
|
2519
|
+
return new URLSearchParams;
|
|
2520
|
+
}
|
|
2521
|
+
}
|
|
2522
|
+
return new URLSearchParams(request.body);
|
|
2523
|
+
};
|
|
2524
|
+
var sendBack = (redirect, params) => {
|
|
2525
|
+
const url = new URL(redirect);
|
|
2526
|
+
for (const [key, value] of Object.entries(params)) {
|
|
2527
|
+
if (value !== undefined) {
|
|
2528
|
+
url.searchParams.set(key, value);
|
|
2529
|
+
}
|
|
2530
|
+
}
|
|
2531
|
+
return { status: 303, headers: { location: url.toString(), "cache-control": "no-store", "referrer-policy": "no-referrer" } };
|
|
2532
|
+
};
|
|
2533
|
+
|
|
2534
|
+
class OfferOAuth {
|
|
2535
|
+
ctx;
|
|
2536
|
+
codes = new Map;
|
|
2537
|
+
constructor(ctx) {
|
|
2538
|
+
this.ctx = ctx;
|
|
2539
|
+
}
|
|
2540
|
+
async http(request) {
|
|
2541
|
+
const path = request.path.replace(/\/+$/, "");
|
|
2542
|
+
const method = request.method.toUpperCase();
|
|
2543
|
+
const known = /^\.well-known\/(oauth-protected-resource|oauth-authorization-server|openid-configuration)(\/mcp)?$/.exec(path);
|
|
2544
|
+
if (!known && !path.startsWith("oauth/")) {
|
|
2545
|
+
return;
|
|
2546
|
+
}
|
|
2547
|
+
if (method === "OPTIONS") {
|
|
2548
|
+
return { status: 204, headers: { ...CORS } };
|
|
2549
|
+
}
|
|
2550
|
+
const { base } = request;
|
|
2551
|
+
if (!base) {
|
|
2552
|
+
return OfferOAuthUtil.error(404, "not_found", "This relay does not pass the address OAuth needs; use an API key.");
|
|
2553
|
+
}
|
|
2554
|
+
if (known) {
|
|
2555
|
+
return known[1] === "oauth-protected-resource" ? OfferOAuthUtil.resourceMetadata(base, "Ta") : OfferOAuthUtil.serverMetadata(base);
|
|
2556
|
+
}
|
|
2557
|
+
if (path === "oauth/register" && method === "POST") {
|
|
2558
|
+
return this.register(request);
|
|
2559
|
+
}
|
|
2560
|
+
if (path === "oauth/authorize" && (method === "GET" || method === "POST")) {
|
|
2561
|
+
return this.authorize(request, base);
|
|
2562
|
+
}
|
|
2563
|
+
if (path === "oauth/token" && method === "POST") {
|
|
2564
|
+
return this.token(request, base);
|
|
2565
|
+
}
|
|
2566
|
+
return OfferOAuthUtil.error(404, "not_found", "No such endpoint.");
|
|
2567
|
+
}
|
|
2568
|
+
async register(request) {
|
|
2569
|
+
let said;
|
|
2570
|
+
try {
|
|
2571
|
+
said = JSON.parse(request.body || "{}");
|
|
2572
|
+
} catch {
|
|
2573
|
+
return OfferOAuthUtil.error(400, "invalid_client_metadata", "The body is not JSON.");
|
|
2574
|
+
}
|
|
2575
|
+
const redirects = Array.isArray(said.redirect_uris) ? said.redirect_uris : [];
|
|
2576
|
+
if (!redirects.length || redirects.length > 5 || !redirects.every(OfferOAuthUtil.redirectable)) {
|
|
2577
|
+
return OfferOAuthUtil.error(400, "invalid_redirect_uri", "redirect_uris: 1 to 5, https, http to localhost, or an app scheme.");
|
|
2578
|
+
}
|
|
2579
|
+
if (said.token_endpoint_auth_method !== undefined && said.token_endpoint_auth_method !== "none") {
|
|
2580
|
+
return OfferOAuthUtil.error(400, "invalid_client_metadata", 'Only public clients (token_endpoint_auth_method "none").');
|
|
2581
|
+
}
|
|
2582
|
+
const name = OfferOAuthUtil.nameOf(said.client_name, "MCP client");
|
|
2583
|
+
const id = OfferOAuthUtil.register(await this.secret(), name, redirects);
|
|
2584
|
+
return OfferOAuthUtil.answer(201, {
|
|
2585
|
+
client_id: id,
|
|
2586
|
+
client_id_issued_at: Math.floor(Date.now() / 1000),
|
|
2587
|
+
client_name: name,
|
|
2588
|
+
redirect_uris: redirects,
|
|
2589
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
2590
|
+
response_types: ["code"],
|
|
2591
|
+
token_endpoint_auth_method: "none",
|
|
2592
|
+
scope: MCP_SCOPE
|
|
2593
|
+
});
|
|
2594
|
+
}
|
|
2595
|
+
async authorize(request, base) {
|
|
2596
|
+
const language = OfferOAuthPage.language(request.headers);
|
|
2597
|
+
const asked = await this.asked(new URLSearchParams(request.query), base);
|
|
2598
|
+
if (!asked.ok) {
|
|
2599
|
+
return asked.back ? sendBack(asked.back.redirect, { error: asked.back.error, state: asked.back.state, iss: base }) : OfferOAuthPage.failed(language, asked.problem);
|
|
2600
|
+
}
|
|
2601
|
+
if (request.method.toUpperCase() === "GET") {
|
|
2602
|
+
return OfferOAuthPage.ask(language, asked.client.name, asked.redirect, request.query);
|
|
2603
|
+
}
|
|
2604
|
+
const taken = this.ctx.connects.take(form(request).get("code"), request.client);
|
|
2605
|
+
if (taken === "wrong" || taken === "blocked") {
|
|
2606
|
+
return OfferOAuthPage.ask(language, asked.client.name, asked.redirect, request.query, taken);
|
|
2607
|
+
}
|
|
2608
|
+
const user = this.ctx.data.users.find((one) => one.id === taken);
|
|
2609
|
+
const offer = user && this.ctx.data.offers.find((one) => one.id === user.offer);
|
|
2610
|
+
if (!user || !offer || offer.api === false) {
|
|
2611
|
+
return OfferOAuthPage.failed(language, "off");
|
|
2612
|
+
}
|
|
2613
|
+
const now = Date.now();
|
|
2614
|
+
for (const [hash, one] of this.codes) {
|
|
2615
|
+
if (one.until <= now || this.codes.size > CODES_MAX) {
|
|
2616
|
+
this.codes.delete(hash);
|
|
2617
|
+
}
|
|
2618
|
+
}
|
|
2619
|
+
const code = OfferKeys.secret(TOKEN_PREFIX.code);
|
|
2620
|
+
this.codes.set(code.hash, {
|
|
2621
|
+
user: user.id,
|
|
2622
|
+
client: asked.client,
|
|
2623
|
+
redirect: asked.redirect,
|
|
2624
|
+
challenge: asked.challenge,
|
|
2625
|
+
...asked.resource ? { resource: asked.resource } : {},
|
|
2626
|
+
until: now + CODE_MS
|
|
2627
|
+
});
|
|
2628
|
+
return sendBack(asked.redirect, { code: code.value, state: asked.state, iss: base });
|
|
2629
|
+
}
|
|
2630
|
+
async asked(params, base) {
|
|
2631
|
+
const client = await OfferOAuthUtil.client(this.ctx.data.secret, params.get("client_id"));
|
|
2632
|
+
const redirect = params.get("redirect_uri") ?? (client?.redirects.length === 1 ? client.redirects[0] : "");
|
|
2633
|
+
if (!client || !redirect || !OfferOAuthUtil.redirectable(redirect) || !OfferOAuthUtil.listed(redirect, client.redirects)) {
|
|
2634
|
+
return { ok: false, problem: "bad" };
|
|
2635
|
+
}
|
|
2636
|
+
const state = params.get("state") ?? undefined;
|
|
2637
|
+
const back = (error) => ({ ok: false, problem: "bad", back: { redirect, error, ...state ? { state } : {} } });
|
|
2638
|
+
const challenge = params.get("code_challenge") ?? "";
|
|
2639
|
+
if (params.get("response_type") !== "code") {
|
|
2640
|
+
return back("unsupported_response_type");
|
|
2641
|
+
}
|
|
2642
|
+
if (params.get("code_challenge_method") !== "S256" || !/^[A-Za-z0-9_-]{43}$/.test(challenge)) {
|
|
2643
|
+
return back("invalid_request");
|
|
2644
|
+
}
|
|
2645
|
+
const scope = params.get("scope");
|
|
2646
|
+
if (scope && !scope.split(" ").every((one) => one === MCP_SCOPE || one === "")) {
|
|
2647
|
+
return back("invalid_scope");
|
|
2648
|
+
}
|
|
2649
|
+
const resource = params.get("resource") ?? undefined;
|
|
2650
|
+
if (resource && !this.ours(resource, base)) {
|
|
2651
|
+
return back("invalid_target");
|
|
2652
|
+
}
|
|
2653
|
+
return { ok: true, client, redirect, challenge, ...state ? { state } : {}, ...resource ? { resource } : {} };
|
|
2654
|
+
}
|
|
2655
|
+
async token(request, base) {
|
|
2656
|
+
const params = form(request);
|
|
2657
|
+
const now = Date.now();
|
|
2658
|
+
const resource = params.get("resource");
|
|
2659
|
+
if (resource && !this.ours(resource, base)) {
|
|
2660
|
+
return OfferOAuthUtil.error(400, "invalid_target", "The resource is not this MCP server.");
|
|
2661
|
+
}
|
|
2662
|
+
if (params.get("grant_type") === "authorization_code") {
|
|
2663
|
+
const hash = OfferKeys.hashOf(params.get("code") ?? "");
|
|
2664
|
+
const granted = this.codes.get(hash);
|
|
2665
|
+
this.codes.delete(hash);
|
|
2666
|
+
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)) {
|
|
2667
|
+
return OfferOAuthUtil.error(400, "invalid_grant", "The code is not valid.");
|
|
2668
|
+
}
|
|
2669
|
+
const user = this.ctx.data.users.find((one) => one.id === granted.user);
|
|
2670
|
+
return user ? this.issue(user, granted.client, now) : OfferOAuthUtil.error(400, "invalid_grant", "No one of this code uses the offer now.");
|
|
2671
|
+
}
|
|
2672
|
+
if (params.get("grant_type") === "refresh_token") {
|
|
2673
|
+
const hash = OfferKeys.hashOf(params.get("refresh_token") ?? "");
|
|
2674
|
+
for (const user of this.ctx.data.users) {
|
|
2675
|
+
const held = user.clients?.find((one) => one.refresh === hash);
|
|
2676
|
+
if (held) {
|
|
2677
|
+
if (held.refreshUntil <= now || held.client !== params.get("client_id")) {
|
|
2678
|
+
return OfferOAuthUtil.error(400, "invalid_grant", "The refresh token is not valid.");
|
|
2679
|
+
}
|
|
2680
|
+
return this.issue(user, { id: held.client, name: held.name, redirects: [] }, now, held);
|
|
2681
|
+
}
|
|
2682
|
+
}
|
|
2683
|
+
return OfferOAuthUtil.error(400, "invalid_grant", "The refresh token is not valid.");
|
|
2684
|
+
}
|
|
2685
|
+
return OfferOAuthUtil.error(400, "unsupported_grant_type", "authorization_code or refresh_token.");
|
|
2686
|
+
}
|
|
2687
|
+
async issue(user, client, now, held) {
|
|
2688
|
+
const offer = this.ctx.data.offers.find((one) => one.id === user.offer);
|
|
2689
|
+
if (!offer || offer.api === false) {
|
|
2690
|
+
return OfferOAuthUtil.error(400, "invalid_grant", "The owner turned off the API of this agent.");
|
|
2691
|
+
}
|
|
2692
|
+
const access = OfferKeys.secret(TOKEN_PREFIX.access);
|
|
2693
|
+
const refresh = OfferKeys.secret(TOKEN_PREFIX.refresh);
|
|
2694
|
+
const tokens = { access: access.hash, accessUntil: now + ACCESS_MS, refresh: refresh.hash, refreshUntil: now + REFRESH_MS };
|
|
2695
|
+
if (held) {
|
|
2696
|
+
Object.assign(held, tokens, { lastAt: now });
|
|
2697
|
+
await this.ctx.commit();
|
|
2698
|
+
} else {
|
|
2699
|
+
const added = { id: randomUUID4(), name: client.name, client: client.id, ...tokens, createdAt: now };
|
|
2700
|
+
user.clients = [...user.clients ?? [], added].slice(-LIMITS.clients);
|
|
2701
|
+
await this.ctx.commit({ what: "client", offer: user.offer, user: user.id, by: user.member });
|
|
2702
|
+
}
|
|
2703
|
+
return OfferOAuthUtil.answer(200, {
|
|
2704
|
+
access_token: access.value,
|
|
2705
|
+
token_type: "Bearer",
|
|
2706
|
+
expires_in: ACCESS_MS / 1000,
|
|
2707
|
+
refresh_token: refresh.value,
|
|
2708
|
+
scope: MCP_SCOPE
|
|
2709
|
+
});
|
|
2710
|
+
}
|
|
2711
|
+
ours(resource, base) {
|
|
2712
|
+
const trimmed = resource.replace(/\/+$/, "");
|
|
2713
|
+
return trimmed === OfferOAuthUtil.urls(base).resource || trimmed === base;
|
|
2714
|
+
}
|
|
2715
|
+
async secret() {
|
|
2716
|
+
if (!this.ctx.data.secret) {
|
|
2717
|
+
this.ctx.data.secret = randomBytes3(32).toString("base64url");
|
|
2718
|
+
await this.ctx.commit();
|
|
2719
|
+
}
|
|
2720
|
+
return this.ctx.data.secret;
|
|
2721
|
+
}
|
|
2722
|
+
}
|
|
2723
|
+
|
|
765
2724
|
// web-src/offer-owner.ts
|
|
766
|
-
import { randomUUID as
|
|
2725
|
+
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
767
2726
|
var SHOWN_PAYMENTS = 50;
|
|
768
2727
|
var text = (value, max) => typeof value === "string" ? value.trim().slice(0, max) : "";
|
|
769
2728
|
|
|
@@ -789,7 +2748,13 @@ class OfferOwner {
|
|
|
789
2748
|
...agent ? { agentName: agent.name, face: agent.face, mark: agent.mark, ...agent.model ? { model: agent.model } : {} } : { gone: true }
|
|
790
2749
|
};
|
|
791
2750
|
}),
|
|
792
|
-
users: data.users.map((
|
|
2751
|
+
users: data.users.map(({ keys, calls: _calls, clients, ...user }) => ({
|
|
2752
|
+
...user,
|
|
2753
|
+
keys: keys?.length ?? 0,
|
|
2754
|
+
clients: clients?.length ?? 0,
|
|
2755
|
+
state: this.ctx.state(user, now),
|
|
2756
|
+
online: links.online(user.member)
|
|
2757
|
+
})),
|
|
793
2758
|
payments: [...data.payments.filter((one) => one.status === "waiting"), ...answered.reverse()],
|
|
794
2759
|
payee: { picture: !!payee.picture, ...payee.note ? { note: payee.note } : {} },
|
|
795
2760
|
joins: joins.map((join2) => ({
|
|
@@ -826,8 +2791,9 @@ class OfferOwner {
|
|
|
826
2791
|
}
|
|
827
2792
|
const trial = typeof input?.trial === "string" ? plans.find((plan) => plan.id === input.trial && plan.price === 0)?.id : undefined;
|
|
828
2793
|
const approve = input?.approve !== false;
|
|
2794
|
+
const api = input?.api === undefined ? before?.api !== false : input.api !== false;
|
|
829
2795
|
const offer = {
|
|
830
|
-
id: before?.id ??
|
|
2796
|
+
id: before?.id ?? randomUUID5(),
|
|
831
2797
|
agent: agent.id,
|
|
832
2798
|
name: text(input?.name, LIMITS.name) || agent.name,
|
|
833
2799
|
...text(input?.intro, LIMITS.intro) ? { intro: text(input?.intro, LIMITS.intro) } : {},
|
|
@@ -837,6 +2803,7 @@ class OfferOwner {
|
|
|
837
2803
|
...before?.invite ? { invite: before.invite } : {},
|
|
838
2804
|
...before?.past ? { past: before.past } : {},
|
|
839
2805
|
...before?.paused ? { paused: true } : {},
|
|
2806
|
+
...api ? {} : { api: false },
|
|
840
2807
|
createdAt: before?.createdAt ?? Date.now()
|
|
841
2808
|
};
|
|
842
2809
|
const language = typeof input?.language === "string" ? input.language : undefined;
|
|
@@ -943,6 +2910,7 @@ class OfferOwner {
|
|
|
943
2910
|
}
|
|
944
2911
|
|
|
945
2912
|
// web-src/offer-use.ts
|
|
2913
|
+
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
946
2914
|
class OfferUse {
|
|
947
2915
|
ctx;
|
|
948
2916
|
constructor(ctx) {
|
|
@@ -986,7 +2954,8 @@ class OfferUse {
|
|
|
986
2954
|
state: this.ctx.state(user, now),
|
|
987
2955
|
...waiting ? { waiting: { id: waiting.id, plan: waiting.plan, amount: waiting.amount, code: waiting.code, at: waiting.at } } : {},
|
|
988
2956
|
payable: !!payee.picture,
|
|
989
|
-
...payee.note ? { payeeNote: payee.note } : {}
|
|
2957
|
+
...payee.note ? { payeeNote: payee.note } : {},
|
|
2958
|
+
...this.apiOf(offer, user)
|
|
990
2959
|
}
|
|
991
2960
|
];
|
|
992
2961
|
});
|
|
@@ -1025,6 +2994,51 @@ class OfferUse {
|
|
|
1025
2994
|
await this.of(offerId);
|
|
1026
2995
|
return this.ctx.store.payee();
|
|
1027
2996
|
}
|
|
2997
|
+
async createKey(offerId, name) {
|
|
2998
|
+
const { user, offer } = await this.of(offerId);
|
|
2999
|
+
const base = this.ctx.links.apiBase(offer.invite?.link, NAME);
|
|
3000
|
+
if (offer.api === false || !base) {
|
|
3001
|
+
throw new OfferError("The owner did not open this agent to the API.");
|
|
3002
|
+
}
|
|
3003
|
+
if ((user.keys?.length ?? 0) >= LIMITS.keys) {
|
|
3004
|
+
throw new OfferError(`At most ${LIMITS.keys} keys: remove one first.`);
|
|
3005
|
+
}
|
|
3006
|
+
const made = OfferKeys.make();
|
|
3007
|
+
const id = randomUUID6();
|
|
3008
|
+
const label = typeof name === "string" && name.trim() ? name.trim().slice(0, LIMITS.keyName) : made.hint;
|
|
3009
|
+
user.keys = [...user.keys ?? [], { id, name: label, hash: made.hash, hint: made.hint, createdAt: Date.now() }];
|
|
3010
|
+
await this.ctx.commit({ what: "key", offer: offer.id, user: user.id, by: user.member });
|
|
3011
|
+
return { key: made.key, hint: made.hint, base };
|
|
3012
|
+
}
|
|
3013
|
+
async removeKey(offerId, keyId) {
|
|
3014
|
+
const { user, offer } = await this.of(offerId);
|
|
3015
|
+
if (!user.keys?.some((key) => key.id === keyId)) {
|
|
3016
|
+
throw new OfferError("No such key.");
|
|
3017
|
+
}
|
|
3018
|
+
user.keys = user.keys.filter((key) => key.id !== keyId);
|
|
3019
|
+
await this.ctx.commit({ what: "unkey", offer: offer.id, user: user.id, by: user.member });
|
|
3020
|
+
}
|
|
3021
|
+
async connectCode(offerId) {
|
|
3022
|
+
const { user, offer } = await this.of(offerId);
|
|
3023
|
+
if (offer.api === false) {
|
|
3024
|
+
throw new OfferError("The owner turned off the API of this agent.");
|
|
3025
|
+
}
|
|
3026
|
+
return this.ctx.connects.make(user.id);
|
|
3027
|
+
}
|
|
3028
|
+
async removeClient(offerId, clientId) {
|
|
3029
|
+
const { user, offer } = await this.of(offerId);
|
|
3030
|
+
if (!user.clients?.some((client) => client.id === clientId)) {
|
|
3031
|
+
throw new OfferError("No such client.");
|
|
3032
|
+
}
|
|
3033
|
+
user.clients = user.clients.filter((client) => client.id !== clientId);
|
|
3034
|
+
await this.ctx.commit({ what: "unclient", offer: offer.id, user: user.id, by: user.member });
|
|
3035
|
+
}
|
|
3036
|
+
apiOf(offer, user) {
|
|
3037
|
+
const base = offer.api === false ? undefined : this.ctx.links.apiBase(offer.invite?.link, NAME);
|
|
3038
|
+
const keys = (user.keys ?? []).map(({ hash: _hash, ...shown }) => shown);
|
|
3039
|
+
const clients = (user.clients ?? []).map(({ id, name, createdAt, lastAt }) => ({ id, name, createdAt, ...lastAt ? { lastAt } : {} }));
|
|
3040
|
+
return base ? { api: { base, keys, mcp: `${base}/mcp`, clients } } : {};
|
|
3041
|
+
}
|
|
1028
3042
|
async of(offerId) {
|
|
1029
3043
|
const member = this.ctx.caller();
|
|
1030
3044
|
if (!member) {
|
|
@@ -1070,15 +3084,30 @@ class OfferService {
|
|
|
1070
3084
|
owner;
|
|
1071
3085
|
use;
|
|
1072
3086
|
meters;
|
|
3087
|
+
api;
|
|
3088
|
+
mcp;
|
|
3089
|
+
oauth;
|
|
3090
|
+
turns;
|
|
1073
3091
|
timer;
|
|
1074
3092
|
constructor(host) {
|
|
1075
3093
|
this.ctx = new OfferContext(host);
|
|
1076
3094
|
this.owner = new OfferOwner(this.ctx);
|
|
1077
3095
|
this.use = new OfferUse(this.ctx);
|
|
1078
3096
|
this.meters = new OfferMeterBook(this.ctx);
|
|
3097
|
+
this.api = new OfferApi(this.ctx);
|
|
3098
|
+
this.mcp = new OfferMcp(this.ctx);
|
|
3099
|
+
this.oauth = new OfferOAuth(this.ctx);
|
|
3100
|
+
this.turns = this.ctx.turns;
|
|
3101
|
+
}
|
|
3102
|
+
async http(request) {
|
|
3103
|
+
if (request.path.replace(/\/+$/, "") === "mcp") {
|
|
3104
|
+
return this.mcp.http(request);
|
|
3105
|
+
}
|
|
3106
|
+
return await this.oauth.http(request) ?? this.api.http(request);
|
|
1079
3107
|
}
|
|
1080
3108
|
async start() {
|
|
1081
3109
|
await this.ctx.store.load();
|
|
3110
|
+
this.ctx.turns.start();
|
|
1082
3111
|
const tidy = () => {
|
|
1083
3112
|
this.ctx.payments.tidy();
|
|
1084
3113
|
this.ctx.commit();
|
|
@@ -1089,6 +3118,8 @@ class OfferService {
|
|
|
1089
3118
|
}
|
|
1090
3119
|
dispose() {
|
|
1091
3120
|
clearInterval(this.timer);
|
|
3121
|
+
this.mcp.tasks.dispose();
|
|
3122
|
+
this.ctx.turns.dispose();
|
|
1092
3123
|
}
|
|
1093
3124
|
}
|
|
1094
3125
|
|
|
@@ -1100,6 +3131,7 @@ async function activate(host) {
|
|
|
1100
3131
|
return {
|
|
1101
3132
|
_offer: service,
|
|
1102
3133
|
dispose: () => service.dispose(),
|
|
3134
|
+
http: (request) => service.http(request),
|
|
1103
3135
|
overview: () => owner.overview(),
|
|
1104
3136
|
agents: () => owner.agents(),
|
|
1105
3137
|
save: (input) => owner.save(input),
|
|
@@ -1116,7 +3148,11 @@ async function activate(host) {
|
|
|
1116
3148
|
start: (offer) => use.start(offer),
|
|
1117
3149
|
pay: (offer, plan) => use.pay(offer, plan),
|
|
1118
3150
|
cancelPay: (offer, payment) => use.cancelPay(offer, payment),
|
|
1119
|
-
payee: (offer) => use.payee(offer)
|
|
3151
|
+
payee: (offer) => use.payee(offer),
|
|
3152
|
+
createKey: (offer, name) => use.createKey(offer, name),
|
|
3153
|
+
removeKey: (offer, key) => use.removeKey(offer, key),
|
|
3154
|
+
connectCode: (offer) => use.connectCode(offer),
|
|
3155
|
+
removeClient: (offer, client) => use.removeClient(offer, client)
|
|
1120
3156
|
};
|
|
1121
3157
|
}
|
|
1122
3158
|
export {
|