pi-durable-bot 0.8.2 → 0.8.4
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/CHANGELOG.md +34 -0
- package/README.md +11 -6
- package/dist/agent/mcp.js +4 -2
- package/dist/agent/mcp.js.map +1 -1
- package/dist/agent/models.js +60 -0
- package/dist/agent/models.js.map +1 -1
- package/dist/bot/bot.js +9 -0
- package/dist/bot/bot.js.map +1 -1
- package/dist/bot/prompt.js +3 -1
- package/dist/bot/prompt.js.map +1 -1
- package/dist/channels/teams/index.js +1327 -0
- package/dist/channels/teams/index.js.map +1 -0
- package/dist/channels/teams/sdk.js +57 -0
- package/dist/channels/teams/sdk.js.map +1 -0
- package/dist/cli/ai.js +6 -58
- package/dist/cli/ai.js.map +1 -1
- package/dist/cli/login-link.js +90 -0
- package/dist/cli/login-link.js.map +1 -0
- package/dist/cli/login.js +24 -2
- package/dist/cli/login.js.map +1 -1
- package/dist/cli/mcp.js +7 -2
- package/dist/cli/mcp.js.map +1 -1
- package/dist/cli/pages.js +20 -6
- package/dist/cli/pages.js.map +1 -1
- package/dist/gateway/log.js +4 -1
- package/dist/gateway/log.js.map +1 -1
- package/dist/pages/host.js +68 -2
- package/dist/pages/host.js.map +1 -1
- package/dist/pages/login-page.js +202 -0
- package/dist/pages/login-page.js.map +1 -0
- package/dist/pages/login.js +848 -0
- package/dist/pages/login.js.map +1 -0
- package/dist/pages/server.js +121 -6
- package/dist/pages/server.js.map +1 -1
- package/dist/pages/store.js +22 -4
- package/dist/pages/store.js.map +1 -1
- package/docs/for-agents.md +6 -3
- package/kit/login/login.css +498 -0
- package/kit/login/login.js +481 -0
- package/package.json +17 -14
- package/skills/pages/SKILL.md +32 -3
- package/skills/teams-channel/SKILL.md +131 -0
|
@@ -0,0 +1,848 @@
|
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { CredentialSynchronizationError } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { formatTime } from "../core/time.js";
|
|
4
|
+
// Login pages: one-time links with which a person signs in to a model provider, with a subscription or an API key, from
|
|
5
|
+
// any device. The login is pi's own (models.login), run in this process as pots login runs it in a terminal, so the
|
|
6
|
+
// callback servers stay here, and the PKCE verifier too, unless pi puts it in the sign-in URL (Anthropic's does). The
|
|
7
|
+
// page renders pi's AuthInteraction: pi's questions become fields and buttons, its sign-in links and device codes are
|
|
8
|
+
// shown, and the page follows pi while it waits. pi writes the login to its auth.json, which every bot of this user and
|
|
9
|
+
// the pi command line share. Nothing happens before Start; the first browser that presses Start keeps the link (a
|
|
10
|
+
// cookie). The person may sign in several times, until Done or the end of the link. Each login wakes the bot once, with
|
|
11
|
+
// the provider and the models it can use now: never a key, a code, a sign-in URL, an account, or pi's own error text,
|
|
12
|
+
// which can hold a provider's answer.
|
|
13
|
+
//
|
|
14
|
+
// pi reads a stored key as a config value: "!command" runs a command, and "$NAME" takes an environment variable. A key
|
|
15
|
+
// typed on the page is stored so that pi reads it back as it was typed (literalKey): a page never runs a command here.
|
|
16
|
+
/** A login link that nobody started stops working after this long. */
|
|
17
|
+
export const LOGIN_UNOPENED_MS = 3_600_000;
|
|
18
|
+
/** How long a login link works after Start: as long as OpenAI's device codes. */
|
|
19
|
+
export const LOGIN_MINUTES = 15;
|
|
20
|
+
/** The name of the cookie that binds a link to the browser that pressed Start. */
|
|
21
|
+
export const LOGIN_COOKIE = "pots_login";
|
|
22
|
+
/** How long a page's question for news waits, and when a failed wake is tried again. For tests: change them. */
|
|
23
|
+
export const loginTimes = { waitMs: 20_000, wakeRetryMs: 10_000 };
|
|
24
|
+
const DAY_MS = 86_400_000;
|
|
25
|
+
/** Login links are listed and kept this long after they were made. */
|
|
26
|
+
const KEEP_MS = 7 * DAY_MS;
|
|
27
|
+
const MAX_TEXT = 2_000;
|
|
28
|
+
/** The longest answer to one of pi's questions: a key, a code or a pasted URL. */
|
|
29
|
+
const MAX_ANSWER = 8_192;
|
|
30
|
+
/** What the page shows of pi's messages, at most, so a long one cannot fill it. */
|
|
31
|
+
const MAX_SHOWN = 2_000;
|
|
32
|
+
/** Models listed in a wake, at most. */
|
|
33
|
+
const MAX_LISTED = 12;
|
|
34
|
+
const SCHEMA = `
|
|
35
|
+
CREATE TABLE IF NOT EXISTS bot_login_links (
|
|
36
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
37
|
+
token TEXT NOT NULL UNIQUE,
|
|
38
|
+
provider TEXT,
|
|
39
|
+
text TEXT NOT NULL DEFAULT '',
|
|
40
|
+
made_for TEXT,
|
|
41
|
+
created_at INTEGER NOT NULL,
|
|
42
|
+
expires_at INTEGER NOT NULL,
|
|
43
|
+
state TEXT NOT NULL,
|
|
44
|
+
started_at INTEGER,
|
|
45
|
+
browser TEXT,
|
|
46
|
+
running TEXT,
|
|
47
|
+
failed INTEGER NOT NULL DEFAULT 0,
|
|
48
|
+
ended_at INTEGER,
|
|
49
|
+
woken_at INTEGER
|
|
50
|
+
);
|
|
51
|
+
CREATE TABLE IF NOT EXISTS bot_logins (
|
|
52
|
+
link_id INTEGER NOT NULL,
|
|
53
|
+
n INTEGER NOT NULL,
|
|
54
|
+
provider TEXT NOT NULL,
|
|
55
|
+
way TEXT NOT NULL,
|
|
56
|
+
at INTEGER NOT NULL,
|
|
57
|
+
note TEXT NOT NULL,
|
|
58
|
+
woken_at INTEGER,
|
|
59
|
+
PRIMARY KEY (link_id, n)
|
|
60
|
+
);
|
|
61
|
+
`;
|
|
62
|
+
const linkId = (row) => `G${row.id}`;
|
|
63
|
+
const hash = (secret) => createHash("sha256").update(secret).digest("hex");
|
|
64
|
+
const madeFor = (person) => person ?? "anyone";
|
|
65
|
+
const wayWords = (way) => (way === "oauth" ? "subscription" : "API key");
|
|
66
|
+
const clip = (text) => (text.length > MAX_SHOWN ? `${text.slice(0, MAX_SHOWN)}…` : text);
|
|
67
|
+
/** An http or https URL as pi gives it, or undefined: nothing else is shown as a link. */
|
|
68
|
+
function webUrl(value) {
|
|
69
|
+
if (typeof value !== "string" || !URL.canParse(value))
|
|
70
|
+
return undefined;
|
|
71
|
+
const url = new URL(value);
|
|
72
|
+
return url.protocol === "https:" || url.protocol === "http:" ? url.href : undefined;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* A key as pi stores it so that pi reads it back as it is. pi reads "$$" as "$" and "$!" as "!", and runs a value that
|
|
76
|
+
* starts with "!" as a command; with every "$" and "!" written so, a key never runs a command or takes a variable.
|
|
77
|
+
*/
|
|
78
|
+
export const literalKey = (key) => key.replace(/[$!]/g, (char) => `$${char}`);
|
|
79
|
+
/**
|
|
80
|
+
* Pots' logins of one provider, one at a time, for all bots that share pi's models in this process: a login checks
|
|
81
|
+
* what it replaces when its turn comes. pi has a queue of its own too, but it says nothing when a login's turn comes.
|
|
82
|
+
*/
|
|
83
|
+
const turns = new WeakMap();
|
|
84
|
+
/** Wait for this provider's turn, or until the signal ends the wait. Resolves with the function that ends the turn. */
|
|
85
|
+
async function turn(models, provider, signal, waiting) {
|
|
86
|
+
let queue = turns.get(models);
|
|
87
|
+
if (!queue)
|
|
88
|
+
turns.set(models, (queue = new Map()));
|
|
89
|
+
const before = queue.get(provider);
|
|
90
|
+
let end;
|
|
91
|
+
const mine = new Promise((resolve) => (end = resolve));
|
|
92
|
+
const tail = (before ?? Promise.resolve()).then(() => mine);
|
|
93
|
+
queue.set(provider, tail);
|
|
94
|
+
void tail.then(() => {
|
|
95
|
+
if (queue.get(provider) === tail)
|
|
96
|
+
queue.delete(provider);
|
|
97
|
+
});
|
|
98
|
+
if (before) {
|
|
99
|
+
waiting();
|
|
100
|
+
try {
|
|
101
|
+
await new Promise((resolve, reject) => {
|
|
102
|
+
if (signal.aborted)
|
|
103
|
+
return reject(abortError(signal));
|
|
104
|
+
const stop = () => reject(abortError(signal));
|
|
105
|
+
signal.addEventListener("abort", stop, { once: true });
|
|
106
|
+
void before.then(() => {
|
|
107
|
+
signal.removeEventListener("abort", stop);
|
|
108
|
+
resolve();
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
end();
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return end;
|
|
118
|
+
}
|
|
119
|
+
/** A way's ID, to compare loosely: pi writes device_code, device-code, copy_code. */
|
|
120
|
+
const loose = (id) => id.toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
121
|
+
/** Ways that need files or programs on the computer itself, which a person on another device cannot set up. */
|
|
122
|
+
const COMPUTER_ONLY = new Set(["credentialchain", "awsprofile", "adc", "applicationdefaultcredentials", "serviceaccount"]);
|
|
123
|
+
/** Ways that work from another device, where pi also offers a browser way whose callback goes to the computer itself. */
|
|
124
|
+
const OTHER_DEVICE = new Set(["devicecode", "copycode", "device", "headless"]);
|
|
125
|
+
/**
|
|
126
|
+
* pi's choices of a way to sign in, as the page offers them. Where pi offers a browser way and a device-code or
|
|
127
|
+
* copy-code way, the second works from another device: it comes first, marked recommended, and pi's own "(default)"
|
|
128
|
+
* or "(recommended)" goes from the labels. Ways that work only on the computer itself are left out and named. When no
|
|
129
|
+
* ID matches, pi's options stay as they are.
|
|
130
|
+
*/
|
|
131
|
+
export function shapeOptions(options) {
|
|
132
|
+
const hidden = options.filter((option) => COMPUTER_ONLY.has(loose(option.id))).map((option) => option.label);
|
|
133
|
+
const shown = options.filter((option) => !COMPUTER_ONLY.has(loose(option.id)));
|
|
134
|
+
const best = shown.find((option) => OTHER_DEVICE.has(loose(option.id)));
|
|
135
|
+
const browser = shown.some((option) => loose(option.id).includes("browser"));
|
|
136
|
+
if (!best || !browser)
|
|
137
|
+
return { options: shown.map((option) => ({ ...option })), hidden };
|
|
138
|
+
const plain = (label) => label.replace(/\s*\((default|recommended)\)\s*$/i, "");
|
|
139
|
+
return {
|
|
140
|
+
options: [best, ...shown.filter((option) => option !== best)].map((option) => ({ ...option, label: plain(option.label), ...(option === best ? { recommended: true } : {}) })),
|
|
141
|
+
hidden,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
/** The login links of one bot, in its bot.sqlite, and the logins that run on them. */
|
|
145
|
+
export class BotLogins {
|
|
146
|
+
#options;
|
|
147
|
+
#sql;
|
|
148
|
+
#clock;
|
|
149
|
+
#live = new Map();
|
|
150
|
+
#stopped = false;
|
|
151
|
+
#wakeRetry;
|
|
152
|
+
/** For pots login --link: called when a link ends. */
|
|
153
|
+
onEnd;
|
|
154
|
+
constructor(options) {
|
|
155
|
+
this.#options = options;
|
|
156
|
+
this.#sql = options.sql;
|
|
157
|
+
this.#clock = options.clock ?? Date.now;
|
|
158
|
+
}
|
|
159
|
+
static async open(options) {
|
|
160
|
+
await options.sql.exec(SCHEMA);
|
|
161
|
+
return new BotLogins(options);
|
|
162
|
+
}
|
|
163
|
+
#models() {
|
|
164
|
+
const models = this.#options.models();
|
|
165
|
+
if (!models)
|
|
166
|
+
throw new Error("pi's models are not loaded in this process");
|
|
167
|
+
return models;
|
|
168
|
+
}
|
|
169
|
+
/** The providers the page offers: pi's subscriptions, and pi's providers that take an API key (also TypeSafe). */
|
|
170
|
+
async #choices() {
|
|
171
|
+
const models = this.#models();
|
|
172
|
+
const stored = await storedCredentials(models);
|
|
173
|
+
const providers = models.getProviders();
|
|
174
|
+
const choice = (provider, name) => {
|
|
175
|
+
const now = stored.get(provider.id);
|
|
176
|
+
return now === undefined ? { id: provider.id, name, replaces: false } : { id: provider.id, name, replaces: true, stored: now };
|
|
177
|
+
};
|
|
178
|
+
return {
|
|
179
|
+
oauth: providers.filter((provider) => provider.auth.oauth).map((provider) => choice(provider, oauthName(provider))),
|
|
180
|
+
api_key: providers.filter((provider) => provider.auth.apiKey?.login).map((provider) => choice(provider, provider.name)),
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
/** A provider's name, for the page of a link made for it. */
|
|
184
|
+
providerName(id) {
|
|
185
|
+
return this.#options.models()?.getProvider(id)?.name;
|
|
186
|
+
}
|
|
187
|
+
// ---- Links ----
|
|
188
|
+
/** pots page login: a link, written before it is given out. */
|
|
189
|
+
async create(input) {
|
|
190
|
+
const text = (input.text ?? "").trim();
|
|
191
|
+
if (text.length > MAX_TEXT)
|
|
192
|
+
throw new Error(`--text is longer than ${MAX_TEXT} characters`);
|
|
193
|
+
const person = input.person?.trim() || null;
|
|
194
|
+
if (person && (person.length > 200 || /[\u0000-\u001f\u007f]/.test(person)))
|
|
195
|
+
throw new Error("bad --for: a person's address, on one line");
|
|
196
|
+
const provider = input.provider?.trim() || null;
|
|
197
|
+
if (provider) {
|
|
198
|
+
const choices = await this.#choices();
|
|
199
|
+
if (![...choices.oauth, ...choices.api_key].some((choice) => choice.id === provider)) {
|
|
200
|
+
const ids = [...new Set([...choices.oauth, ...choices.api_key].map((choice) => choice.id))].sort();
|
|
201
|
+
throw new Error(`bad --provider ${JSON.stringify(provider)}: pi has no login or API key for it. pi's providers: ${ids.join(", ")}`);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
else
|
|
205
|
+
this.#models();
|
|
206
|
+
const token = randomBytes(18).toString("base64url");
|
|
207
|
+
const now = this.#clock();
|
|
208
|
+
const expiresAt = now + LOGIN_UNOPENED_MS;
|
|
209
|
+
const id = await this.#sql.transaction(async (tx) => {
|
|
210
|
+
await tx.run("INSERT INTO bot_login_links (token, provider, text, made_for, created_at, expires_at, state) VALUES (?, ?, ?, ?, ?, ?, 'open')", token, provider, text, person, now, expiresAt);
|
|
211
|
+
return (await tx.get("SELECT last_insert_rowid() AS id")).id;
|
|
212
|
+
});
|
|
213
|
+
this.#arm(id, expiresAt);
|
|
214
|
+
this.#options.print("login link made", { link: `G${id}`, ...(provider ? { provider } : {}) });
|
|
215
|
+
return { id: `G${id}`, token, expiresAt };
|
|
216
|
+
}
|
|
217
|
+
async #row(token) {
|
|
218
|
+
return this.#sql.get("SELECT * FROM bot_login_links WHERE token = ?", token);
|
|
219
|
+
}
|
|
220
|
+
/** A row's state now: a live link past its time counts as expired, before its timer has run. */
|
|
221
|
+
#state(row) {
|
|
222
|
+
return (row.state === "open" || row.state === "started") && row.expires_at <= this.#clock() ? "expired" : row.state;
|
|
223
|
+
}
|
|
224
|
+
#mine(row, secret) {
|
|
225
|
+
if (!row.browser || !secret)
|
|
226
|
+
return false;
|
|
227
|
+
const given = Buffer.from(hash(secret), "hex");
|
|
228
|
+
const kept = Buffer.from(row.browser, "hex");
|
|
229
|
+
return given.length === kept.length && timingSafeEqual(given, kept);
|
|
230
|
+
}
|
|
231
|
+
#view(row, secret) {
|
|
232
|
+
return {
|
|
233
|
+
id: linkId(row),
|
|
234
|
+
state: this.#state(row),
|
|
235
|
+
text: row.text,
|
|
236
|
+
provider: row.provider,
|
|
237
|
+
expiresAt: row.expires_at,
|
|
238
|
+
startedAt: row.started_at,
|
|
239
|
+
mine: this.#mine(row, secret),
|
|
240
|
+
madeFor: row.made_for,
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
/** The link with this token, for its page; undefined when there is none. Looking never starts it. */
|
|
244
|
+
async view(token, secret) {
|
|
245
|
+
const row = await this.#row(token);
|
|
246
|
+
if (!row)
|
|
247
|
+
return undefined;
|
|
248
|
+
if (this.#state(row) !== row.state)
|
|
249
|
+
await this.checkExpiry();
|
|
250
|
+
return this.#view(row, secret);
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* The link's state for its page. after: the version the page has; the answer waits, up to loginTimes.waitMs, until
|
|
254
|
+
* something changes, so the page follows pi while it waits for a device code.
|
|
255
|
+
*/
|
|
256
|
+
async state(token, secret, after) {
|
|
257
|
+
let row = await this.#row(token);
|
|
258
|
+
if (!row)
|
|
259
|
+
return undefined;
|
|
260
|
+
const live = this.#live.get(row.id);
|
|
261
|
+
if (after !== undefined && live && live.version <= after && this.#state(row) === "started" && this.#mine(row, secret) && !this.#stopped) {
|
|
262
|
+
await new Promise((resolve) => {
|
|
263
|
+
const done = () => {
|
|
264
|
+
clearTimeout(timer);
|
|
265
|
+
live.waiters.delete(done);
|
|
266
|
+
resolve();
|
|
267
|
+
};
|
|
268
|
+
const timer = setTimeout(done, loginTimes.waitMs);
|
|
269
|
+
live.waiters.add(done);
|
|
270
|
+
});
|
|
271
|
+
row = (await this.#row(token)) ?? row;
|
|
272
|
+
}
|
|
273
|
+
if (this.#state(row) !== row.state)
|
|
274
|
+
await this.checkExpiry();
|
|
275
|
+
const now = this.#clock();
|
|
276
|
+
const base = { id: linkId(row), state: this.#state(row), mine: this.#mine(row, secret), now, expires: row.expires_at, started: row.started_at, provider: row.provider };
|
|
277
|
+
const current = this.#live.get(row.id);
|
|
278
|
+
if (!base.mine || base.state !== "started")
|
|
279
|
+
return { ...base, version: current?.version ?? 0, ...(base.mine && current ? { outcomes: current.outcomes } : {}) };
|
|
280
|
+
const login = current?.login;
|
|
281
|
+
return {
|
|
282
|
+
...base,
|
|
283
|
+
version: current?.version ?? 0,
|
|
284
|
+
choices: await this.#choices(),
|
|
285
|
+
...(login
|
|
286
|
+
? {
|
|
287
|
+
login: {
|
|
288
|
+
provider: login.provider,
|
|
289
|
+
name: login.name,
|
|
290
|
+
way: login.way,
|
|
291
|
+
replaces: login.replaces,
|
|
292
|
+
events: login.events,
|
|
293
|
+
...(login.question ? { question: publicQuestion(login.question) } : {}),
|
|
294
|
+
},
|
|
295
|
+
}
|
|
296
|
+
: {}),
|
|
297
|
+
outcomes: current?.outcomes ?? [],
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* The person pressed Start. The first browser to do so keeps the link: it gets a new secret for its cookie. The same
|
|
302
|
+
* browser may press it again (the page reloaded, or was opened again), and keeps its secret.
|
|
303
|
+
*/
|
|
304
|
+
async start(token, secret) {
|
|
305
|
+
const row = await this.#row(token);
|
|
306
|
+
if (!row)
|
|
307
|
+
return { ok: false, status: 404, code: "missing", error: "This link does not work." };
|
|
308
|
+
const state = this.#state(row);
|
|
309
|
+
if (state === "started") {
|
|
310
|
+
if (!this.#mine(row, secret))
|
|
311
|
+
return { ok: false, status: 409, code: "elsewhere", error: "This link is open on another device." };
|
|
312
|
+
return { ok: true, secret: secret, view: this.#view(row, secret) };
|
|
313
|
+
}
|
|
314
|
+
if (state !== "open")
|
|
315
|
+
return { ok: false, status: 410, code: state, error: "This link has ended." };
|
|
316
|
+
const fresh = randomBytes(32).toString("base64url");
|
|
317
|
+
const now = this.#clock();
|
|
318
|
+
const bound = await this.#sql.transaction(async (tx) => {
|
|
319
|
+
const current = await tx.get("SELECT * FROM bot_login_links WHERE id = ?", row.id);
|
|
320
|
+
if (!current || this.#state(current) !== "open")
|
|
321
|
+
return current;
|
|
322
|
+
await tx.run("UPDATE bot_login_links SET state = 'started', started_at = ?, browser = ?, expires_at = ? WHERE id = ?", now, hash(fresh), now + LOGIN_MINUTES * 60_000, row.id);
|
|
323
|
+
return await tx.get("SELECT * FROM bot_login_links WHERE id = ?", row.id);
|
|
324
|
+
});
|
|
325
|
+
if (!bound || bound.browser !== hash(fresh)) {
|
|
326
|
+
if (bound && this.#state(bound) === "started") {
|
|
327
|
+
if (this.#mine(bound, secret))
|
|
328
|
+
return { ok: true, secret: secret, view: this.#view(bound, secret) };
|
|
329
|
+
return { ok: false, status: 409, code: "elsewhere", error: "This link is open on another device." };
|
|
330
|
+
}
|
|
331
|
+
return { ok: false, status: 410, code: bound ? this.#state(bound) : "missing", error: "This link has ended." };
|
|
332
|
+
}
|
|
333
|
+
this.#liveOf(row.id);
|
|
334
|
+
this.#arm(row.id, bound.expires_at);
|
|
335
|
+
this.#options.print("login page started", { link: linkId(row) });
|
|
336
|
+
return { ok: true, secret: fresh, view: this.#view(bound, fresh) };
|
|
337
|
+
}
|
|
338
|
+
/** A started link of this browser, or why the page cannot act on it. */
|
|
339
|
+
async #own(token, secret) {
|
|
340
|
+
const row = await this.#row(token);
|
|
341
|
+
if (!row)
|
|
342
|
+
return { ok: false, status: 404, code: "missing", error: "This link does not work." };
|
|
343
|
+
if (!this.#mine(row, secret))
|
|
344
|
+
return { ok: false, status: 403, code: "elsewhere", error: "Only the device that pressed Start can use this link." };
|
|
345
|
+
if (this.#state(row) !== "started" || this.#stopped)
|
|
346
|
+
return { ok: false, status: 410, code: this.#state(row), error: "This link has ended." };
|
|
347
|
+
return { row, live: this.#liveOf(row.id) };
|
|
348
|
+
}
|
|
349
|
+
/** The person chose a provider and a way: pi's login runs, and its questions and events go to the page. */
|
|
350
|
+
async begin(token, secret, provider, way, replace) {
|
|
351
|
+
const own = await this.#own(token, secret);
|
|
352
|
+
if ("ok" in own)
|
|
353
|
+
return own;
|
|
354
|
+
const { row, live } = own;
|
|
355
|
+
if (live.login || live.beginning)
|
|
356
|
+
return { ok: false, status: 409, code: "busy", error: "A sign-in runs on this page already." };
|
|
357
|
+
if (way !== "oauth" && way !== "api_key")
|
|
358
|
+
return { ok: false, status: 400, error: '"way" must be "oauth" or "api_key"' };
|
|
359
|
+
// Taken before the wait for pi's list, so a second request at the same time finds the page busy.
|
|
360
|
+
live.beginning = true;
|
|
361
|
+
let choices;
|
|
362
|
+
try {
|
|
363
|
+
choices = await this.#choices();
|
|
364
|
+
}
|
|
365
|
+
finally {
|
|
366
|
+
live.beginning = false;
|
|
367
|
+
}
|
|
368
|
+
// The link may have ended while pi listed its providers.
|
|
369
|
+
if (this.#stopped || this.#live.get(row.id) !== live)
|
|
370
|
+
return { ok: false, status: 410, code: "ended", error: "This link has ended." };
|
|
371
|
+
const choice = choices[way].find((item) => item.id === provider);
|
|
372
|
+
if (!choice)
|
|
373
|
+
return { ok: false, status: 400, error: `pi has no ${way === "oauth" ? "subscription login" : "API key"} for ${JSON.stringify(provider)}` };
|
|
374
|
+
const confirmed = typeof replace === "string" && replace.length <= 100 ? { confirmed: replace } : {};
|
|
375
|
+
const login = { provider, name: choice.name, way, replaces: choice.replaces, ...confirmed, abort: new AbortController(), events: [] };
|
|
376
|
+
live.login = login;
|
|
377
|
+
await this.#sql.run("UPDATE bot_login_links SET running = ? WHERE id = ?", provider, row.id);
|
|
378
|
+
this.#bump(live);
|
|
379
|
+
this.#options.print("login page signs in", { link: linkId(row), provider, way });
|
|
380
|
+
void this.#run(row, live, login).catch((error) => this.#options.print("login page failed", { link: linkId(row), error: error instanceof Error ? error.message : String(error) }));
|
|
381
|
+
return { ok: true };
|
|
382
|
+
}
|
|
383
|
+
/** The person answered pi's open question. */
|
|
384
|
+
async answer(token, secret, question, value) {
|
|
385
|
+
const own = await this.#own(token, secret);
|
|
386
|
+
if ("ok" in own)
|
|
387
|
+
return own;
|
|
388
|
+
const open = own.live.login?.question;
|
|
389
|
+
if (!open || open.id !== question)
|
|
390
|
+
return { ok: false, status: 409, code: "gone", error: "This question is no longer open." };
|
|
391
|
+
if (typeof value !== "string" || value.length > MAX_ANSWER)
|
|
392
|
+
return { ok: false, status: 400, error: `the answer must be text of at most ${MAX_ANSWER} characters` };
|
|
393
|
+
const answer = value.trim();
|
|
394
|
+
if (open.type === "select" && !open.options.some((option) => option.id === answer))
|
|
395
|
+
return { ok: false, status: 400, error: "choose one of the options" };
|
|
396
|
+
if (open.type === "replace" && answer !== "replace" && answer !== "cancel")
|
|
397
|
+
return { ok: false, status: 400, error: '"replace" or "cancel"' };
|
|
398
|
+
// pi saves an empty key as it is, over the key it had, and then counts the provider as not signed in.
|
|
399
|
+
if ((open.type === "secret" || open.type === "manual_code") && answer === "")
|
|
400
|
+
return { ok: false, status: 400, error: "It cannot be empty." };
|
|
401
|
+
if (/[\u0000-\u001f\u007f]/.test(answer))
|
|
402
|
+
return { ok: false, status: 400, error: "It has a line break or another control character; paste it again." };
|
|
403
|
+
own.live.login.question = undefined;
|
|
404
|
+
this.#bump(own.live);
|
|
405
|
+
open.resolve(answer);
|
|
406
|
+
return { ok: true };
|
|
407
|
+
}
|
|
408
|
+
/** The person cancelled the sign-in that runs: the page goes back to the choice. */
|
|
409
|
+
async cancel(token, secret) {
|
|
410
|
+
const own = await this.#own(token, secret);
|
|
411
|
+
if ("ok" in own)
|
|
412
|
+
return own;
|
|
413
|
+
const login = own.live.login;
|
|
414
|
+
if (login) {
|
|
415
|
+
login.stopped = "cancelled";
|
|
416
|
+
login.abort.abort(new Error("Cancelled."));
|
|
417
|
+
}
|
|
418
|
+
return { ok: true };
|
|
419
|
+
}
|
|
420
|
+
/** The person pressed Done: the link ends. */
|
|
421
|
+
async done(token, secret) {
|
|
422
|
+
const own = await this.#own(token, secret);
|
|
423
|
+
if ("ok" in own)
|
|
424
|
+
return own;
|
|
425
|
+
await this.#finish(own.row.id, "done");
|
|
426
|
+
return { ok: true };
|
|
427
|
+
}
|
|
428
|
+
/** pots page unlink: by link ID (G3) or token. The link ID, or undefined when it is not a login link of this bot. */
|
|
429
|
+
async revoke(link) {
|
|
430
|
+
const number = /^G(\d+)$/.exec(link);
|
|
431
|
+
const row = number
|
|
432
|
+
? await this.#sql.get("SELECT * FROM bot_login_links WHERE id = ?", Number(number[1]))
|
|
433
|
+
: /^[A-Za-z0-9_-]{16,128}$/.test(link)
|
|
434
|
+
? await this.#row(link)
|
|
435
|
+
: undefined;
|
|
436
|
+
if (!row || row.state === "revoked")
|
|
437
|
+
return undefined;
|
|
438
|
+
await this.#finish(row.id, "revoked");
|
|
439
|
+
return linkId(row);
|
|
440
|
+
}
|
|
441
|
+
/** For pots page list: the links of the last 7 days, with the providers signed in through each. */
|
|
442
|
+
async list() {
|
|
443
|
+
const rows = await this.#sql.all("SELECT * FROM bot_login_links WHERE state != 'revoked' ORDER BY id");
|
|
444
|
+
const logins = await this.#sql.all("SELECT * FROM bot_logins ORDER BY link_id, n");
|
|
445
|
+
return rows.map((row) => ({
|
|
446
|
+
link: linkId(row),
|
|
447
|
+
token: row.token,
|
|
448
|
+
for: row.made_for,
|
|
449
|
+
provider: row.provider,
|
|
450
|
+
created: row.created_at,
|
|
451
|
+
expires: row.expires_at,
|
|
452
|
+
state: this.#state(row),
|
|
453
|
+
started: row.started_at,
|
|
454
|
+
ended: row.ended_at,
|
|
455
|
+
signedIn: logins.filter((login) => login.link_id === row.id).map((login) => `${login.provider} (${wayWords(login.way)})`),
|
|
456
|
+
}));
|
|
457
|
+
}
|
|
458
|
+
// ---- The login ----
|
|
459
|
+
#liveOf(id) {
|
|
460
|
+
let live = this.#live.get(id);
|
|
461
|
+
if (!live) {
|
|
462
|
+
live = { version: 1, waiters: new Set(), outcomes: [] };
|
|
463
|
+
this.#live.set(id, live);
|
|
464
|
+
}
|
|
465
|
+
return live;
|
|
466
|
+
}
|
|
467
|
+
/** Something changed that the page shows: the pages that wait hear of it now. */
|
|
468
|
+
#bump(live) {
|
|
469
|
+
live.version += 1;
|
|
470
|
+
for (const waiter of [...live.waiters])
|
|
471
|
+
waiter();
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Put a question on the page and wait for its answer. It is withdrawn when one of the signals ends: the login stopped,
|
|
475
|
+
* or pi got the answer another way, such as its callback.
|
|
476
|
+
*/
|
|
477
|
+
#ask(live, login, shown, signals, literal = false) {
|
|
478
|
+
return new Promise((resolve, reject) => {
|
|
479
|
+
const aborted = signals.find((signal) => signal.aborted);
|
|
480
|
+
if (aborted)
|
|
481
|
+
return reject(abortError(aborted));
|
|
482
|
+
const withdraw = (signal) => () => {
|
|
483
|
+
if (login.question?.id !== shown.id)
|
|
484
|
+
return;
|
|
485
|
+
login.question = undefined;
|
|
486
|
+
this.#bump(live);
|
|
487
|
+
reject(abortError(signal));
|
|
488
|
+
};
|
|
489
|
+
for (const signal of signals)
|
|
490
|
+
signal.addEventListener("abort", withdraw(signal), { once: true });
|
|
491
|
+
login.question = { ...shown, resolve: (value) => resolve(literal ? literalKey(value) : value), reject };
|
|
492
|
+
this.#bump(live);
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
/** pi's callbacks, answered on the page. */
|
|
496
|
+
#interaction(live, login) {
|
|
497
|
+
return {
|
|
498
|
+
signal: login.abort.signal,
|
|
499
|
+
prompt: async (prompt) => {
|
|
500
|
+
const signals = [login.abort.signal, ...(prompt.signal ? [prompt.signal] : [])];
|
|
501
|
+
const id = randomBytes(9).toString("base64url");
|
|
502
|
+
if (prompt.type === "select") {
|
|
503
|
+
const shaped = shapeOptions(prompt.options);
|
|
504
|
+
if (shaped.options.length === 0)
|
|
505
|
+
throw new Error(`${shaped.hidden.join(", ")} must be set up on the computer itself, not from a page.`);
|
|
506
|
+
return this.#ask(live, login, { id, type: "select", message: clip(prompt.message), options: shaped.options, hidden: shaped.hidden }, signals);
|
|
507
|
+
}
|
|
508
|
+
// An API key login's secret is the key pi stores: as it was typed, never a command or a variable.
|
|
509
|
+
const literal = login.way === "api_key" && prompt.type === "secret";
|
|
510
|
+
return this.#ask(live, login, { id, type: prompt.type, message: clip(prompt.message), ...(prompt.placeholder ? { placeholder: clip(prompt.placeholder) } : {}) }, signals, literal);
|
|
511
|
+
},
|
|
512
|
+
notify: (event) => {
|
|
513
|
+
const shown = showEvent(event, this.#clock());
|
|
514
|
+
if (!shown)
|
|
515
|
+
return;
|
|
516
|
+
// One line of progress at a time: the newest.
|
|
517
|
+
login.events = [...login.events.filter((item) => !(shown.type === "progress" && item.type === "progress")), shown].slice(-20);
|
|
518
|
+
this.#bump(live);
|
|
519
|
+
},
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* The login's turn has come: what it replaces is checked again. A stored login is replaced only when the person
|
|
524
|
+
* confirmed on the page that they replace this one, as it is now; else the page asks, before any of pi's questions.
|
|
525
|
+
*/
|
|
526
|
+
async #checkReplaces(live, login) {
|
|
527
|
+
const now = (await storedCredentials(this.#models())).get(login.provider);
|
|
528
|
+
login.replaces = now !== undefined;
|
|
529
|
+
if (now !== undefined && now !== login.confirmed) {
|
|
530
|
+
this.#bump(live);
|
|
531
|
+
const answer = await this.#ask(live, login, { id: randomBytes(9).toString("base64url"), type: "replace", provider: login.name }, [login.abort.signal]);
|
|
532
|
+
if (answer !== "replace") {
|
|
533
|
+
login.stopped = "cancelled";
|
|
534
|
+
throw new Error("Cancelled.");
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
async #run(row, live, login) {
|
|
539
|
+
const models = this.#models();
|
|
540
|
+
const way = wayWords(login.way);
|
|
541
|
+
let committed = false;
|
|
542
|
+
let failure;
|
|
543
|
+
let end;
|
|
544
|
+
try {
|
|
545
|
+
end = await turn(models, login.provider, login.abort.signal, () => {
|
|
546
|
+
login.events = [...login.events, { type: "progress", message: `Waiting for another sign-in to ${login.name} to end…` }];
|
|
547
|
+
this.#bump(live);
|
|
548
|
+
});
|
|
549
|
+
login.events = login.events.filter((item) => item.type !== "progress");
|
|
550
|
+
await this.#checkReplaces(live, login);
|
|
551
|
+
const deviceId = this.#options.deviceId ? await this.#options.deviceId() : undefined;
|
|
552
|
+
try {
|
|
553
|
+
await models.login(login.provider, login.way, this.#interaction(live, login), deviceId ? { getDeviceId: () => deviceId } : {});
|
|
554
|
+
}
|
|
555
|
+
catch (error) {
|
|
556
|
+
// pi saved the login, and only its own models did not follow yet: the login counts.
|
|
557
|
+
if (!(error instanceof CredentialSynchronizationError))
|
|
558
|
+
throw error;
|
|
559
|
+
this.#options.print("login page: pi saved the login but did not update its models", { link: linkId(row), provider: login.provider });
|
|
560
|
+
}
|
|
561
|
+
committed = true;
|
|
562
|
+
saved.set(login.provider, (saved.get(login.provider) ?? 0) + 1);
|
|
563
|
+
}
|
|
564
|
+
catch (error) {
|
|
565
|
+
const reason = login.stopped === "cancelled" ? "Cancelled." : error instanceof Error ? error.message : String(error);
|
|
566
|
+
failure = { ok: false, provider: login.provider, name: login.name, way: login.way, cancelled: login.stopped === "cancelled", error: clip(reason) };
|
|
567
|
+
}
|
|
568
|
+
finally {
|
|
569
|
+
end?.();
|
|
570
|
+
}
|
|
571
|
+
login.question?.reject(new Error("The sign-in ended."));
|
|
572
|
+
login.question = undefined;
|
|
573
|
+
if (!committed) {
|
|
574
|
+
if (this.#stopped)
|
|
575
|
+
return;
|
|
576
|
+
if (live.login === login)
|
|
577
|
+
live.login = undefined;
|
|
578
|
+
if (login.stopped !== "ended")
|
|
579
|
+
live.outcomes = [...live.outcomes, failure].slice(-10);
|
|
580
|
+
await this.#sql.run(`UPDATE bot_login_links SET running = NULL${failure.cancelled || login.stopped === "ended" ? "" : ", failed = failed + 1"} WHERE id = ?`, row.id);
|
|
581
|
+
this.#options.print("login page did not sign in", { link: linkId(row), provider: login.provider, way, ...(failure.cancelled ? { cancelled: true } : {}) });
|
|
582
|
+
this.#bump(live);
|
|
583
|
+
return;
|
|
584
|
+
}
|
|
585
|
+
// pi has the login now. It is written down at once, before pi is asked for anything more, with a note without the
|
|
586
|
+
// models, so that the end of the link or a restart while they are listed and tried never says that nobody signed in.
|
|
587
|
+
const base = { ok: true, provider: login.provider, name: login.name, way: login.way, replaced: login.replaces, models: 0 };
|
|
588
|
+
const first = noteText(row, base, undefined);
|
|
589
|
+
const n = await this.#sql.transaction(async (tx) => {
|
|
590
|
+
const last = await tx.get("SELECT MAX(n) AS n FROM bot_logins WHERE link_id = ?", row.id);
|
|
591
|
+
const next = (last?.n ?? 0) + 1;
|
|
592
|
+
await tx.run("INSERT INTO bot_logins (link_id, n, provider, way, at, note) VALUES (?, ?, ?, ?, ?, ?)", row.id, next, login.provider, login.way, this.#clock(), first);
|
|
593
|
+
await tx.run("UPDATE bot_login_links SET running = NULL WHERE id = ?", row.id);
|
|
594
|
+
return next;
|
|
595
|
+
});
|
|
596
|
+
this.#options.print("login page signed in", { link: linkId(row), provider: login.provider, way });
|
|
597
|
+
if (this.#stopped)
|
|
598
|
+
return;
|
|
599
|
+
login.events = [...login.events.filter((item) => item.type !== "progress"), { type: "progress", message: "Signed in. Trying a model…" }];
|
|
600
|
+
this.#bump(live);
|
|
601
|
+
// A model that cannot be listed or tried does not undo the login.
|
|
602
|
+
const outcome = await this.#tryAfter(login).catch((error) => ({ ...base, modelProblem: clip(error instanceof Error ? error.message : String(error)) }));
|
|
603
|
+
const note = await this.#loginNote(row, outcome);
|
|
604
|
+
await this.#sql.run("UPDATE bot_logins SET note = ? WHERE link_id = ? AND n = ? AND woken_at IS NULL", note, row.id, n);
|
|
605
|
+
if (this.#stopped)
|
|
606
|
+
return;
|
|
607
|
+
if (live.login === login)
|
|
608
|
+
live.login = undefined;
|
|
609
|
+
if (login.stopped !== "ended")
|
|
610
|
+
live.outcomes = [...live.outcomes, outcome].slice(-10);
|
|
611
|
+
this.#bump(live);
|
|
612
|
+
await this.#wakeLogin(row.id, n);
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* After a login, as pots login does: the models pi can use with it now, and pi's default model of the provider tried,
|
|
616
|
+
* or the first one; for a provider that has only judges, such as TypeSafe's Jev, the first judge.
|
|
617
|
+
*/
|
|
618
|
+
async #tryAfter(login) {
|
|
619
|
+
const models = this.#models();
|
|
620
|
+
const base = { ok: true, provider: login.provider, name: login.name, way: login.way, replaced: login.replaces };
|
|
621
|
+
const chat = await models.getAvailable(login.provider);
|
|
622
|
+
if (chat.length > 0) {
|
|
623
|
+
const preferred = await this.#options.defaultModel?.(login.provider).catch(() => undefined);
|
|
624
|
+
const tried = chat.find((model) => model.id === preferred) ?? chat[0];
|
|
625
|
+
const name = `${tried.provider}/${tried.id}`;
|
|
626
|
+
const problem = this.#options.tryModel ? await this.#options.tryModel(models, name) : undefined;
|
|
627
|
+
return { ...base, model: name, models: chat.length, ...(problem ? { modelProblem: clip(problem) } : {}) };
|
|
628
|
+
}
|
|
629
|
+
const judges = await models.getAvailableOfType("classifier", login.provider);
|
|
630
|
+
if (judges.length > 0) {
|
|
631
|
+
const name = `${judges[0].provider}/${judges[0].id}`;
|
|
632
|
+
const problem = this.#options.tryJudge ? await this.#options.tryJudge(models, name) : undefined;
|
|
633
|
+
return { ...base, judge: name, models: 0, ...(problem ? { judgeProblem: clip(problem) } : {}) };
|
|
634
|
+
}
|
|
635
|
+
return { ...base, models: 0 };
|
|
636
|
+
}
|
|
637
|
+
/** The note of a login's wake: the provider, what it replaced, and the models and judges the bot can use with it now. */
|
|
638
|
+
async #loginNote(row, outcome) {
|
|
639
|
+
const models = this.#models();
|
|
640
|
+
// pi may fail to list them just after a login (its models did not follow yet): the note then leaves them out.
|
|
641
|
+
const listed = await Promise.all([models.getAvailable(outcome.provider), models.getAvailableOfType("classifier", outcome.provider)]).catch(() => undefined);
|
|
642
|
+
return noteText(row, outcome, listed && { chat: listed[0].map((model) => `${model.provider}/${model.id}`), judges: listed[1].map((model) => `${model.provider}/${model.id}`) });
|
|
643
|
+
}
|
|
644
|
+
async #wakeLogin(linkRowId, n) {
|
|
645
|
+
const row = await this.#sql.get("SELECT * FROM bot_logins WHERE link_id = ? AND n = ?", linkRowId, n);
|
|
646
|
+
if (!row || row.woken_at !== null)
|
|
647
|
+
return;
|
|
648
|
+
try {
|
|
649
|
+
await this.#options.wake(row.note, `login:G${linkRowId}:${n}`);
|
|
650
|
+
await this.#sql.run("UPDATE bot_logins SET woken_at = ? WHERE link_id = ? AND n = ?", this.#clock(), linkRowId, n);
|
|
651
|
+
}
|
|
652
|
+
catch (error) {
|
|
653
|
+
this.#options.print("login page wake failed", { link: `G${linkRowId}`, error: String(error) });
|
|
654
|
+
this.#retryWakes();
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
// ---- Ends ----
|
|
658
|
+
/** Run checkExpiry when the link's time comes. */
|
|
659
|
+
#arm(id, expiresAt) {
|
|
660
|
+
if (this.#stopped)
|
|
661
|
+
return;
|
|
662
|
+
const live = this.#liveOf(id);
|
|
663
|
+
clearTimeout(live.timer);
|
|
664
|
+
live.timer = setTimeout(() => void this.checkExpiry(), Math.max(0, expiresAt - this.#clock()) + 50).unref();
|
|
665
|
+
}
|
|
666
|
+
/** End the live links whose time has come. The timers call it; tests that move the clock call it too. */
|
|
667
|
+
async checkExpiry() {
|
|
668
|
+
const due = await this.#sql.all("SELECT * FROM bot_login_links WHERE state IN ('open', 'started') AND expires_at <= ?", this.#clock());
|
|
669
|
+
for (const row of due)
|
|
670
|
+
await this.#finish(row.id, "expired");
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* End a link: its new state goes into the table first. A login that runs stops, and the page hears of it. The bot is
|
|
674
|
+
* woken about the end when nobody signed in through the link, or when a restart lost a login, but not for a link it
|
|
675
|
+
* took back itself.
|
|
676
|
+
*/
|
|
677
|
+
async #finish(id, state) {
|
|
678
|
+
const now = this.#clock();
|
|
679
|
+
const ended = await this.#sql.transaction(async (tx) => {
|
|
680
|
+
const row = await tx.get("SELECT * FROM bot_login_links WHERE id = ?", id);
|
|
681
|
+
if (!row || (row.state !== "open" && row.state !== "started"))
|
|
682
|
+
return undefined;
|
|
683
|
+
const logins = (await tx.get("SELECT COUNT(*) AS n FROM bot_logins WHERE link_id = ?", id)).n;
|
|
684
|
+
const due = state === "restarted" || (state !== "revoked" && logins === 0);
|
|
685
|
+
await tx.run("UPDATE bot_login_links SET state = ?, ended_at = ?, woken_at = ? WHERE id = ?", state, now, due ? null : now, id);
|
|
686
|
+
return { ...row, state, ended_at: now, woken_at: due ? null : now };
|
|
687
|
+
});
|
|
688
|
+
if (!ended)
|
|
689
|
+
return;
|
|
690
|
+
const live = this.#live.get(id);
|
|
691
|
+
if (live) {
|
|
692
|
+
clearTimeout(live.timer);
|
|
693
|
+
if (live.login) {
|
|
694
|
+
live.login.stopped = "ended";
|
|
695
|
+
live.login.abort.abort(new Error(state === "done" ? "The page was closed with Done." : "The link ended."));
|
|
696
|
+
}
|
|
697
|
+
this.#bump(live);
|
|
698
|
+
this.#live.delete(id);
|
|
699
|
+
}
|
|
700
|
+
this.#options.print("login page ended", { link: linkId(ended), state });
|
|
701
|
+
if (ended.woken_at === null)
|
|
702
|
+
await this.#wakeEnd(ended);
|
|
703
|
+
this.onEnd?.(linkId(ended));
|
|
704
|
+
}
|
|
705
|
+
async #wakeEnd(row) {
|
|
706
|
+
try {
|
|
707
|
+
await this.#options.wake(this.#endNote(row), `login:${linkId(row)}:end`);
|
|
708
|
+
await this.#sql.run("UPDATE bot_login_links SET woken_at = ? WHERE id = ?", this.#clock(), row.id);
|
|
709
|
+
}
|
|
710
|
+
catch (error) {
|
|
711
|
+
this.#options.print("login page wake failed", { link: linkId(row), error: String(error) });
|
|
712
|
+
this.#retryWakes();
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
#endNote(row) {
|
|
716
|
+
const link = `link ${linkId(row)} (made for ${madeFor(row.made_for)})`;
|
|
717
|
+
const failed = row.failed > 0 ? ` ${row.failed === 1 ? "One sign-in" : `${row.failed} sign-ins`} on it failed; their page showed why.` : "";
|
|
718
|
+
if (row.state === "restarted") {
|
|
719
|
+
return `login page: Pots restarted while someone was signing in to ${row.running ?? "a provider"} on ${link}, so that sign-in was lost and the link ended. A new link (pots page login) lets them try again.`;
|
|
720
|
+
}
|
|
721
|
+
if (row.state === "done")
|
|
722
|
+
return `login page: someone pressed Done on ${link} without signing in to anything.${failed}`;
|
|
723
|
+
if (row.started_at === null)
|
|
724
|
+
return `login page: ${link} expired at ${formatTime(row.expires_at)}: nobody pressed Start within an hour.`;
|
|
725
|
+
return `login page: ${link} ended at ${formatTime(row.expires_at)}, ${LOGIN_MINUTES} minutes after Start, and nobody signed in.${failed}`;
|
|
726
|
+
}
|
|
727
|
+
/** Send the wakes that failed after a while, and again while one fails; the next start does too. */
|
|
728
|
+
#retryWakes() {
|
|
729
|
+
if (this.#wakeRetry || this.#stopped)
|
|
730
|
+
return;
|
|
731
|
+
this.#wakeRetry = setTimeout(() => {
|
|
732
|
+
this.#wakeRetry = undefined;
|
|
733
|
+
this.#wakePending().catch((error) => {
|
|
734
|
+
this.#options.print("login page wake failed", { error: String(error) });
|
|
735
|
+
this.#retryWakes();
|
|
736
|
+
});
|
|
737
|
+
}, loginTimes.wakeRetryMs).unref();
|
|
738
|
+
}
|
|
739
|
+
async #wakePending() {
|
|
740
|
+
for (const login of await this.#sql.all("SELECT * FROM bot_logins WHERE woken_at IS NULL ORDER BY link_id, n"))
|
|
741
|
+
await this.#wakeLogin(login.link_id, login.n);
|
|
742
|
+
for (const row of await this.#sql.all("SELECT * FROM bot_login_links WHERE state IN ('done', 'expired', 'restarted') AND woken_at IS NULL"))
|
|
743
|
+
await this.#wakeEnd(row);
|
|
744
|
+
}
|
|
745
|
+
// ---- Start and stop ----
|
|
746
|
+
/**
|
|
747
|
+
* After a start: a login that ran when Pots stopped is lost, as pi's sign-in was in this process, so its link ends as
|
|
748
|
+
* restarted. Links whose time came while Pots was stopped end; the others get their timers. Wakes not sent yet go.
|
|
749
|
+
*/
|
|
750
|
+
async resume() {
|
|
751
|
+
for (const row of await this.#sql.all("SELECT * FROM bot_login_links WHERE state = 'started' AND running IS NOT NULL"))
|
|
752
|
+
await this.#finish(row.id, "restarted");
|
|
753
|
+
for (const row of await this.#sql.all("SELECT * FROM bot_login_links WHERE state IN ('open', 'started')"))
|
|
754
|
+
this.#arm(row.id, row.expires_at);
|
|
755
|
+
await this.checkExpiry();
|
|
756
|
+
await this.#wakePending();
|
|
757
|
+
}
|
|
758
|
+
/** The gateway stops: logins that run stop; their links end as restarted at the next start. */
|
|
759
|
+
stop() {
|
|
760
|
+
this.#stopped = true;
|
|
761
|
+
clearTimeout(this.#wakeRetry);
|
|
762
|
+
for (const live of this.#live.values()) {
|
|
763
|
+
clearTimeout(live.timer);
|
|
764
|
+
live.login?.abort.abort(new Error("Pots is stopping."));
|
|
765
|
+
for (const waiter of [...live.waiters])
|
|
766
|
+
waiter();
|
|
767
|
+
}
|
|
768
|
+
this.#live.clear();
|
|
769
|
+
}
|
|
770
|
+
/** Forget login links 7 days after they were made, once they ended and the bot heard of them. */
|
|
771
|
+
async cleanup() {
|
|
772
|
+
const old = "SELECT id FROM bot_login_links WHERE created_at < ? AND state NOT IN ('open', 'started') AND woken_at IS NOT NULL";
|
|
773
|
+
const cutoff = this.#clock() - KEEP_MS;
|
|
774
|
+
await this.#sql.transaction(async (tx) => {
|
|
775
|
+
await tx.run(`DELETE FROM bot_logins WHERE woken_at IS NOT NULL AND link_id IN (${old})`, cutoff);
|
|
776
|
+
await tx.run(`DELETE FROM bot_login_links WHERE id IN (${old}) AND id NOT IN (SELECT link_id FROM bot_logins)`, cutoff);
|
|
777
|
+
});
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* Logins saved through login pages in this process, per provider. With the kind pi lists, they tell one stored login
|
|
782
|
+
* from the next without a secret: a login another page saved over the one a person confirmed to replace is a new one.
|
|
783
|
+
*/
|
|
784
|
+
const saved = new Map();
|
|
785
|
+
/**
|
|
786
|
+
* The providers pi has a login or key of now, each with a word for what is stored (Choice.stored). pi's ModelRuntime
|
|
787
|
+
* lists them without a secret; a plain Models does not.
|
|
788
|
+
*/
|
|
789
|
+
async function storedCredentials(models) {
|
|
790
|
+
const listing = models.listCredentials;
|
|
791
|
+
const items = listing ? await listing.call(models).catch(() => []) : [];
|
|
792
|
+
return new Map(items.map((item) => [item.providerId, `${item.type}.${saved.get(item.providerId) ?? 0}`]));
|
|
793
|
+
}
|
|
794
|
+
/** A login's note, with the models and judges pi listed, or none when it was not asked or could not list them. */
|
|
795
|
+
function noteText(row, outcome, listed) {
|
|
796
|
+
const list = (names) => (names.length > MAX_LISTED ? `${names.slice(0, MAX_LISTED).join(", ")} and ${names.length - MAX_LISTED} more` : names.join(", "));
|
|
797
|
+
const chat = listed?.chat ?? [];
|
|
798
|
+
const judges = listed?.judges ?? [];
|
|
799
|
+
const parts = [
|
|
800
|
+
`login page: someone used link ${linkId(row)} (made for ${madeFor(row.made_for)}) and signed in to ${outcome.name} (provider ${outcome.provider}, ${wayWords(outcome.way)}), for every bot and pi on this computer.`,
|
|
801
|
+
outcome.replaced ? `It replaced the ${outcome.provider} ${outcome.way === "oauth" ? "login" : "key"} that pi had before.` : "",
|
|
802
|
+
chat.length > 0 ? `Usable now: ${list(chat)}.` : "",
|
|
803
|
+
judges.length > 0 ? `Judges usable now: ${list(judges)}.` : "",
|
|
804
|
+
outcome.model ? (outcome.modelProblem ? `${outcome.model} did not answer when Pots tried it with this login.` : `${outcome.model} answered when Pots tried it.`) : "",
|
|
805
|
+
outcome.judge ? (outcome.judgeProblem ? `${outcome.judge} did not answer when Pots tried it as a judge.` : `${outcome.judge} answered when Pots tried it as a judge.`) : "",
|
|
806
|
+
listed && chat.length === 0 && judges.length === 0 ? "pi lists no model or judge for this login." : "",
|
|
807
|
+
];
|
|
808
|
+
return parts.filter(Boolean).join(" ");
|
|
809
|
+
}
|
|
810
|
+
/** A subscription's name as pots login shows it. */
|
|
811
|
+
function oauthName(provider) {
|
|
812
|
+
return provider.auth.oauth?.loginLabel ?? provider.auth.oauth?.name ?? provider.name;
|
|
813
|
+
}
|
|
814
|
+
function abortError(signal) {
|
|
815
|
+
return signal.reason instanceof Error ? signal.reason : new Error("The question was withdrawn.");
|
|
816
|
+
}
|
|
817
|
+
/** The question without its callbacks, for the page. */
|
|
818
|
+
function publicQuestion(question) {
|
|
819
|
+
const { resolve: _resolve, reject: _reject, ...shown } = question;
|
|
820
|
+
return shown;
|
|
821
|
+
}
|
|
822
|
+
/** One of pi's events as the page shows it, or undefined for one with no URL that can be opened. */
|
|
823
|
+
function showEvent(event, now) {
|
|
824
|
+
switch (event.type) {
|
|
825
|
+
case "auth_url": {
|
|
826
|
+
const url = webUrl(event.url);
|
|
827
|
+
return url ? { type: "auth_url", url, ...(event.instructions ? { instructions: clip(event.instructions) } : {}) } : undefined;
|
|
828
|
+
}
|
|
829
|
+
case "device_code": {
|
|
830
|
+
const url = webUrl(event.verificationUri);
|
|
831
|
+
if (!url)
|
|
832
|
+
return undefined;
|
|
833
|
+
return { type: "device_code", userCode: clip(event.userCode), verificationUri: url, ...(event.expiresInSeconds ? { expiresAt: now + event.expiresInSeconds * 1000 } : {}) };
|
|
834
|
+
}
|
|
835
|
+
case "info":
|
|
836
|
+
return {
|
|
837
|
+
type: "info",
|
|
838
|
+
message: clip(event.message),
|
|
839
|
+
links: (event.links ?? []).flatMap((link) => {
|
|
840
|
+
const url = webUrl(link.url);
|
|
841
|
+
return url ? [{ url, ...(link.label ? { label: clip(link.label) } : {}) }] : [];
|
|
842
|
+
}),
|
|
843
|
+
};
|
|
844
|
+
case "progress":
|
|
845
|
+
return { type: "progress", message: clip(event.message) };
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
//# sourceMappingURL=login.js.map
|