@stav-ai/cli 0.1.6 → 0.1.9

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.
@@ -0,0 +1,626 @@
1
+ /**
2
+ * stav agent — pair this computer with a Sovereign Data Agent and watch it.
3
+ * The wire contract is WATCH.md of the Stav Agent Connector.
4
+ *
5
+ * stav agent list | pair <agent> | watch [<agent>] | forget <agent>
6
+ *
7
+ * Not in --help while the feature is not open to everybody.
8
+ */
9
+ import os from 'node:os';
10
+ import { StavError } from '../errors.js';
11
+ import { request } from '../http.js';
12
+ import { keyPair } from '../noise.js';
13
+ import { terminalText } from '../terminal-text.js';
14
+ import { Pairings } from './pairings.js';
15
+ import { passkeyPage } from './passkey.js';
16
+ import { questionOf, Questions } from './questions.js';
17
+ import { Channel, ChannelEnd, watchUrl } from './relay.js';
18
+ import { clock, StepPrinter, word } from './steps.js';
19
+ import { challenge, decode, fingerprint, pskOf, readCode, readFingerprint } from './wire.js';
20
+ const USAGE = `Usage:
21
+ stav agent list The Sovereign Data Agents you may watch
22
+ stav agent pair <agent> Pair this computer with an agent
23
+ stav agent watch [<agent>] Watch an agent's work, live
24
+ stav agent forget <agent> Remove this computer from an agent`;
25
+ const UUID = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
26
+ /** What coding agents set in the shells they run. */
27
+ const AGENT_MARKERS = ['AI_AGENT', 'AGENT', 'CLAUDECODE', 'CODEX_CI', 'CODEX_THREAD_ID', 'GEMINI_CLI', 'OPENCODE', 'CURSOR_AGENT', 'COPILOT_CLI'];
28
+ export const TIMES = {
29
+ /** One answer of the relay or the connector. The relay itself gives up after 10 s. */
30
+ answer: 30_000,
31
+ page: 5 * 60_000,
32
+ /** The connector sends something every 30 s. */
33
+ silent: 90_000,
34
+ /** A view can be taken up again for this long. */
35
+ resume: 10 * 60_000,
36
+ firstRetry: 1_000,
37
+ /** At most 60 tickets an hour: a whole break of 10 minutes uses about 20. */
38
+ lastRetry: 30_000,
39
+ };
40
+ const WAITS = {
41
+ needs_approval: 'it waits for your approval',
42
+ needs_login: 'it waits for you to sign in where its data is',
43
+ needs_answer: 'it waits for your answer',
44
+ needs_access: 'it waits for you to give it access',
45
+ };
46
+ /** In our own words, after the agent's line. */
47
+ const waits = (a) => (a.waiting ? `, ${WAITS[a.waiting] ?? 'it waits for you'}` : '');
48
+ /**
49
+ * A program the person did not start can read what this terminal shows. This
50
+ * stops it only from doing so by accident; what it cannot stop is in
51
+ * WATCH.md § 9.
52
+ */
53
+ function guard(command, d) {
54
+ if (AGENT_MARKERS.some((m) => d.env[m])) {
55
+ throw new StavError(`stav agent ${command} does not run inside a coding agent: it would see what the data agent sees. Open a separate terminal and run it there.`, 'coding_agent');
56
+ }
57
+ if (!d.isTerminal) {
58
+ throw new StavError(`stav agent ${command} needs a terminal: its input and output cannot be a pipe or a file. Open a separate terminal and run it there.`, 'no_terminal');
59
+ }
60
+ }
61
+ export async function agentCommand(args, d) {
62
+ const [command, name, ...more] = args;
63
+ const takes = { list: 0, pair: 1, watch: 1, forget: 1 }[command ?? ''];
64
+ if (takes === undefined || (name ? 1 : 0) + more.length > takes || (!name && (command === 'pair' || command === 'forget'))) {
65
+ // Never repeat what was typed: it may be a pairing code.
66
+ await d.write(`${USAGE}\n`);
67
+ return 1;
68
+ }
69
+ if (command === 'pair' || command === 'watch')
70
+ guard(command, d);
71
+ const url = command === 'pair' || command === 'watch' ? watchUrl(d.cfg.relayUrl) : '';
72
+ const store = await d.openStore();
73
+ const pairings = new Pairings(store, d.cfg);
74
+ await pairings.check();
75
+ const run = new Run(d, store, pairings, url);
76
+ switch (command) {
77
+ case 'list':
78
+ return run.list();
79
+ case 'pair':
80
+ return run.pair(name);
81
+ case 'watch':
82
+ return run.watch(name);
83
+ default:
84
+ return run.forget(name);
85
+ }
86
+ }
87
+ /** One agent by its id, slug or name. */
88
+ function pick(all, typed) {
89
+ const low = typed.toLowerCase();
90
+ for (const key of ['id', 'slug', 'name']) {
91
+ const found = all.filter((a) => a[key].toLowerCase() === low);
92
+ if (found.length > 1)
93
+ throw new StavError(`More than one agent is called "${typed}". Use the id: ${found.map((a) => a.id).join(', ')}.`, 'ambiguous');
94
+ if (found.length)
95
+ return found[0];
96
+ }
97
+ return null;
98
+ }
99
+ /** A name on one line, as the page and the connector take it. */
100
+ function plainName(text, max, fallback) {
101
+ const clean = terminalText(text).replace(/[\s\p{Cs}]+/gu, ' ').trim();
102
+ return [...clean].slice(0, max).join('').trim() || fallback;
103
+ }
104
+ /** The passkey in `client_data` was used for this handshake (and this number). */
105
+ function isFor(answer, want) {
106
+ try {
107
+ return JSON.parse(decode(answer.client_data, 'base64url').toString()).challenge === want.toString('base64url');
108
+ }
109
+ catch {
110
+ return false;
111
+ }
112
+ }
113
+ /** The connector has at most 1 MiB unread for a viewer, so an honest one never sends this much. */
114
+ const MAX_HELD = 2 * 1024 * 1024;
115
+ /** Why this computer may not answer, and who can change that. */
116
+ const mayNot = (p) => (p.can_answer
117
+ ? `This computer may not answer ${p.name} now: you need the right at Stav, and the data side must allow this computer. Ask an owner or admin of the workspace.`
118
+ : `This computer may only watch ${p.name}. To answer too, pair it again: run stav agent forget ${p.agent_id}, let somebody run stav-agent-connector pair --can-answer where the data is, then run stav agent pair ${p.slug}.`);
119
+ /** Codes after which the same view can be taken up again. */
120
+ const RETRY = ['lost', 'silent', 'slow', 'agent_offline', 'internal', 'no_answer', 'ticket_invalid'];
121
+ const ENDS = {
122
+ lost: 'The connection to Stav\'s relay was lost, or could not be made.',
123
+ silent: 'Nothing came for too long.',
124
+ bad_message: 'Something came that is not from the paired connector. The view was closed.',
125
+ replaced: 'This computer opened a newer view of the agent, so this one was closed.',
126
+ protocol: 'Stav\'s relay closed the view because of a wrong message. A newer Stav CLI may help.',
127
+ not_enabled: 'Sovereign Data Agents are switched off for this workspace.',
128
+ ticket_invalid: 'Stav\'s relay did not take the ticket. Try again.',
129
+ too_many: 'Three other computers watch this agent already. Try again when one of them has stopped.',
130
+ ended: 'Stav closed the view: a right, your sign-in, this computer or the agent was changed.',
131
+ slow: 'This terminal was too slow to take what came.',
132
+ timeout: 'The passkey was not used within 2 minutes. Run the command again.',
133
+ agent_offline: 'The Agent Connector\'s connection ended.',
134
+ internal: 'Something failed at Stav. Try again later.',
135
+ };
136
+ function endText(e) {
137
+ if (e.code === 'closed')
138
+ return `The Agent Connector closed the connection (${word(e.reason)}).`;
139
+ return ENDS[e.code] ?? `Stav's relay closed the connection (${word(e.code)}).`;
140
+ }
141
+ const REFUSED = {
142
+ passkey_refused: 'The Agent Connector did not accept the passkey.',
143
+ resume_refused: 'The view cannot be taken up again. Run stav agent watch again and use your passkey.',
144
+ too_many: 'The Agent Connector has 50 paired computers already. One of them must be removed there first.',
145
+ };
146
+ const refusedText = (f) => REFUSED[String(f.code)] ?? `The Agent Connector refused (${word(f.code)}).`;
147
+ const removedAtStav = (p) => new StavError(`This computer, or the agent, was removed at Stav, or you may no longer watch ${p.name}. To pair again, run stav agent forget ${p.agent_id}, then stav agent pair ${p.slug}.`, 'device_removed');
148
+ const byeText = (f) => (f.code === 'removed' ? 'This computer was removed from the agent\'s list, so the view ended.' : `The Agent Connector ended the view (${word(f.code)}).`);
149
+ class Run {
150
+ d;
151
+ store;
152
+ pairings;
153
+ relay;
154
+ /** The person pressed Ctrl-C. */
155
+ over = false;
156
+ questions = null;
157
+ constructor(d, store, pairings, relay) {
158
+ this.d = d;
159
+ this.store = store;
160
+ this.pairings = pairings;
161
+ this.relay = relay;
162
+ }
163
+ say(line = '') {
164
+ return this.d.write(`${terminalText(line)}\n`);
165
+ }
166
+ async token() {
167
+ const t = await this.d.token(this.store);
168
+ if (!t)
169
+ throw new StavError('You are not signed in. Run stav login.', 'not_signed_in');
170
+ return t;
171
+ }
172
+ async call(path, teamId, o = {}) {
173
+ return request(this.d.fetchFn, `${this.d.cfg.apiUrl}${path}`, { token: await this.token(), teamId, ...o });
174
+ }
175
+ /** The agents the person may watch. Null when the workspace has no such agents at all. */
176
+ async watchable() {
177
+ const answer = await this.call('/api/agents/watchable', await this.d.workspace(this.store), { nullOn: [404] });
178
+ return answer && (answer.agents ?? [])
179
+ .map((a) => ({ ...a, slug: plainName(a.slug, 64, a.id), name: plainName(a.name, 128, a.id) }))
180
+ .sort((a, b) => Number(Boolean(b.waiting)) - Number(Boolean(a.waiting)));
181
+ }
182
+ async noAgents() {
183
+ await this.say('This workspace has no Sovereign Data Agents.');
184
+ return 1;
185
+ }
186
+ find(all, typed) {
187
+ const a = pick(all, typed);
188
+ // Without what was typed: it may be a pairing code.
189
+ if (!a)
190
+ throw new StavError('You may watch no agent of that name in this workspace. Run stav agent list to see them, or stav workspace to change the workspace.', 'no_such_agent');
191
+ return a;
192
+ }
193
+ async list() {
194
+ const all = await this.watchable();
195
+ if (!all)
196
+ return this.noAgents();
197
+ if (!all.length)
198
+ await this.say('You may watch no agent in this workspace.');
199
+ for (const a of all) {
200
+ const paired = await this.pairings.get(a.id).then((p) => (p ? 'paired with this computer' : 'not paired'), () => 'the stored pairing cannot be read');
201
+ await this.say(`${a.slug.padEnd(20)} ${a.name.padEnd(24)} ${a.online ? 'online ' : 'offline'} ${paired}${waits(a)}`);
202
+ }
203
+ return 0;
204
+ }
205
+ ticket(a, path, body = {}) {
206
+ return this.call(`/api/agents/${encodeURIComponent(a.id)}/${path}`, a.team_id, { body });
207
+ }
208
+ /** Opens the passkey page. The address is shown too: a browser may be on another screen. */
209
+ async page(o) {
210
+ const page = await passkeyPage(o);
211
+ await this.say('Opening your browser. If it does not open, visit:');
212
+ await this.say(page.url);
213
+ this.d.openBrowser(page.url);
214
+ return page;
215
+ }
216
+ portal() {
217
+ return new URL(this.d.cfg.apiUrl).origin;
218
+ }
219
+ // ---- pair ----
220
+ async pair(typed) {
221
+ const all = await this.watchable();
222
+ if (!all)
223
+ return this.noAgents();
224
+ const a = this.find(all, typed);
225
+ if (await this.pairings.get(a.id)) {
226
+ throw new StavError(`This computer is paired with ${a.name} already. To pair it again, run stav agent forget ${a.id} first.`, 'already_paired');
227
+ }
228
+ await this.say('Where the data is, run: stav-agent-connector pair');
229
+ let code = null;
230
+ for (let i = 0; !code; i++) {
231
+ code = readCode(await this.d.ask('Type the pairing code it shows (it stays hidden): ', { hidden: true }));
232
+ if (!code && i === 2)
233
+ throw new StavError('That is not a pairing code.', 'bad_code');
234
+ if (!code)
235
+ await this.say('That is not a pairing code: it has 26 letters and digits.');
236
+ }
237
+ const computer = plainName(os.hostname().replace(/\.local$/, ''), 64, 'computer');
238
+ const own = keyPair();
239
+ const t = await this.ticket(a, 'pairing-ticket');
240
+ if (!t)
241
+ throw new StavError('Stav made no ticket.', 'empty');
242
+ const names = { agent_id: a.id, team_id: t.team_id, user_id: t.user_id, device_id: '' };
243
+ let ch;
244
+ try {
245
+ ch = await Channel.open({ url: this.relay, ticket: t.ticket, kind: 'pair', names, own, psk: pskOf(code), timeoutMs: this.d.times.answer });
246
+ }
247
+ catch (e) {
248
+ if (!(e instanceof ChannelEnd))
249
+ throw e;
250
+ if (e.code === 'no_answer')
251
+ throw new StavError('No answer. The code is wrong, used or older than 10 minutes, or the Agent Connector is off. Ask for a new code.', 'no_answer');
252
+ throw new StavError(endText(e), e.code);
253
+ }
254
+ let passkey;
255
+ let sent = false;
256
+ let done;
257
+ const page = await this.page({ portal: this.portal(), h: ch.hash, agent: a.name, mode: 'pair', computer, signal: ch.connection.ended, timeoutMs: this.d.times.page })
258
+ .catch((e) => {
259
+ ch.close();
260
+ throw e;
261
+ });
262
+ try {
263
+ passkey = await this.checkedPasskey(page.answer, ch);
264
+ ch.send({ t: 'passkey', computer, ...passkey });
265
+ sent = true;
266
+ done = await ch.wait(this.d.times.answer, 'paired', 'refused');
267
+ }
268
+ catch (e) {
269
+ const used = 'The pairing code is used up: ask for a new one.';
270
+ if (e instanceof ChannelEnd) {
271
+ throw new StavError(`${endText(e)} ${sent ? 'The Agent Connector may have this computer on its list already. ' : ''}${used}`, e.code);
272
+ }
273
+ throw e instanceof StavError ? new StavError(`${e.message} ${used}`, e.code) : e;
274
+ }
275
+ finally {
276
+ page.close();
277
+ ch.close();
278
+ }
279
+ if (done.t === 'refused')
280
+ throw new StavError(`${refusedText(done)} Ask for a new code.`, word(done.code));
281
+ const p = {
282
+ v: 1, agent_id: a.id, team_id: t.team_id, user_id: t.user_id, slug: a.slug, name: a.name, computer,
283
+ private_key: own.private.toString('base64'), connector_key: ch.connectorKey.toString('base64'),
284
+ passkey_id: passkey.id, can_answer: done.can_answer === true,
285
+ };
286
+ await this.pairings.save(p);
287
+ await this.say(`This computer is paired with ${a.name}, as "${computer}".`);
288
+ try {
289
+ await this.tellStav(p);
290
+ }
291
+ catch (e) {
292
+ await this.say(`Stav does not know this computer yet: ${e instanceof Error ? e.message : String(e)} The next stav agent watch tries again.`);
293
+ return 1;
294
+ }
295
+ await this.say(`Watch it with: stav agent watch ${p.slug}`);
296
+ return 0;
297
+ }
298
+ /**
299
+ * The passkey from the page, only when the person typed the fingerprint of
300
+ * that same key. The page shows it before it sends the key, so the question
301
+ * comes first.
302
+ */
303
+ async checkedPasskey(answer, ch) {
304
+ // Cancelled in the browser: take the question back.
305
+ const gone = new AbortController();
306
+ answer.catch((e) => gone.abort(e));
307
+ let typed = null;
308
+ for (let i = 0; !typed; i++) {
309
+ typed = readFingerprint(await this.d.ask('Type the fingerprint the page shows: ', { signal: gone.signal }));
310
+ if (!typed && i === 4)
311
+ throw new StavError('That is not a fingerprint.', 'bad_fingerprint');
312
+ if (!typed)
313
+ await this.say('A fingerprint has 10 letters and digits.');
314
+ }
315
+ await this.say('Now press the button on the page.');
316
+ const passkey = await answer;
317
+ if (typed !== fingerprint(decode(passkey.public_key, 'base64url')) || !isFor(passkey, challenge('pair', ch.hash))) {
318
+ throw new StavError('Stopped, and nothing was paired. The passkey that came back is not the one the page showed. If you typed the fingerprint right, another program on this computer may have answered: find out which one before you try again.', 'fingerprint_mismatch');
319
+ }
320
+ return passkey;
321
+ }
322
+ /** Puts this computer on Stav's list, and stores the id it gets there. */
323
+ async tellStav(p) {
324
+ const device = await this.call(`/api/agents/${encodeURIComponent(p.agent_id)}/devices`, p.team_id, {
325
+ body: { device_public_key: keyPair(decode(p.private_key, 'base64', 32)).public.toString('base64'), name: p.computer, can_answer: p.can_answer },
326
+ }).catch((e) => {
327
+ throw e instanceof StavError && e.code === 'device_removed' ? removedAtStav(p) : e;
328
+ });
329
+ if (typeof device?.id !== 'string' || !device.id)
330
+ throw new StavError('Stav gave this computer no id.', 'empty');
331
+ const next = { ...p, device_id: device.id };
332
+ await this.pairings.save(next);
333
+ return next;
334
+ }
335
+ // ---- watch ----
336
+ async watch(typed) {
337
+ let channel = null;
338
+ const printer = new StepPrinter(this.d.columns);
339
+ const view = this.view(typed, printer, (ch) => {
340
+ channel = ch;
341
+ if (this.over)
342
+ ch.close();
343
+ });
344
+ let stop;
345
+ const interrupted = new Promise((resolve) => {
346
+ stop = this.d.onInterrupt(() => resolve('interrupted'));
347
+ });
348
+ try {
349
+ const code = await Promise.race([view, interrupted]);
350
+ if (code !== 'interrupted')
351
+ return code;
352
+ this.over = true;
353
+ const answer = this.questions?.abort();
354
+ view.catch(() => undefined);
355
+ await this.d.write(`${printer.close()}${answer ? `${answer} ` : ''}Stopped watching.\n`);
356
+ return 0;
357
+ }
358
+ finally {
359
+ stop();
360
+ channel?.close();
361
+ }
362
+ }
363
+ async choose(typed) {
364
+ const all = await this.watchable();
365
+ if (!all)
366
+ return null;
367
+ if (typed) {
368
+ const agent = this.find(all, typed);
369
+ const pairing = await this.pairings.get(agent.id);
370
+ if (!pairing)
371
+ throw new StavError(`This computer is not paired with ${agent.name}. Run stav agent pair ${agent.slug}.`, 'not_paired');
372
+ return { agent, pairing };
373
+ }
374
+ const paired = [];
375
+ for (const agent of all) {
376
+ const pairing = await this.pairings.get(agent.id);
377
+ if (pairing)
378
+ paired.push({ agent, pairing });
379
+ }
380
+ if (!paired.length)
381
+ throw new StavError('This computer is paired with no agent you may watch in this workspace. Run stav agent list, then stav agent pair <agent>.', 'not_paired');
382
+ if (paired.length === 1)
383
+ return paired[0];
384
+ for (const [i, { agent }] of paired.entries())
385
+ await this.say(`${i + 1} ${agent.name} (${agent.slug})${waits(agent)}`);
386
+ const answer = await this.d.ask('Which one? ');
387
+ const chosen = /^\d{1,4}$/.test(answer) ? paired[Number(answer) - 1] : undefined;
388
+ if (chosen)
389
+ return chosen;
390
+ const agent = pick(paired.map((p) => p.agent), answer);
391
+ if (!agent)
392
+ throw new StavError('There is no such agent in the list.', 'no_such_agent');
393
+ return paired.find((p) => p.agent === agent);
394
+ }
395
+ async connect(p) {
396
+ const t = await this.ticket({ id: p.agent_id, team_id: p.team_id }, 'watch-ticket', { device_id: p.device_id }).catch((e) => {
397
+ throw e instanceof StavError && (e.status === 404 || e.code === 'device_removed') ? removedAtStav(p) : e;
398
+ });
399
+ if (!t)
400
+ throw new StavError('Stav made no ticket.', 'empty');
401
+ if (t.user_id !== p.user_id || t.team_id !== p.team_id) {
402
+ throw new StavError(`Another person, or another workspace, paired this computer with ${p.name}. Sign in as that person, or run stav agent forget ${p.agent_id} and pair it again.`, 'other_person');
403
+ }
404
+ return Channel.open({
405
+ url: this.relay, ticket: t.ticket, kind: 'watch', own: keyPair(decode(p.private_key, 'base64', 32)), connectorKey: decode(p.connector_key, 'base64', 32),
406
+ names: { agent_id: p.agent_id, team_id: p.team_id, user_id: p.user_id, device_id: p.device_id }, timeoutMs: this.d.times.answer,
407
+ });
408
+ }
409
+ async view(typed, printer, onChannel) {
410
+ const chosen = await this.choose(typed);
411
+ if (!chosen)
412
+ return this.noAgents();
413
+ const { agent } = chosen;
414
+ const { name } = agent;
415
+ const p = chosen.pairing.device_id ? chosen.pairing : await this.tellStav(chosen.pairing);
416
+ const ours = (line) => this.d.write(`${printer.close()}${terminalText(line)}\n`);
417
+ let ch;
418
+ let view;
419
+ try {
420
+ ch = await this.connect(p);
421
+ onChannel(ch);
422
+ view = await this.prove(ch, name, p);
423
+ }
424
+ catch (e) {
425
+ if (!(e instanceof ChannelEnd))
426
+ throw e;
427
+ if (e.code !== 'no_answer')
428
+ throw new StavError(endText(e), e.code);
429
+ // The relay says the same when the connector is off and when it closed the door.
430
+ const online = (await this.watchable().catch(() => null))?.find((a) => a.id === agent.id)?.online;
431
+ const state = online === undefined ? '' : ` Stav last showed the agent as ${online ? 'online' : 'offline'}.`;
432
+ throw new StavError(`No answer from ${name}.${state} Its Agent Connector may be off, or this computer is no longer paired there: then run stav agent forget ${p.agent_id} and pair it again.`, 'no_answer');
433
+ }
434
+ await ours(`You are watching ${name}, until ${clock(view.endsAt)}. Press Ctrl-C to stop.`);
435
+ await ours('You see what the agent sent to its model and got back. Steps of calls that ran at the same time are mixed.');
436
+ const questions = new Questions({ ask: this.d.ask, write: this.d.write, say: ours, mayNot: mayNot(p) }, printer);
437
+ this.questions = questions;
438
+ await questions.connected(ch, view.canAnswer, view.question);
439
+ const shown = { view, printer, questions, held: [], heldBytes: 0, unread: 0 };
440
+ try {
441
+ for (;;) {
442
+ let end;
443
+ try {
444
+ const bye = await this.stream(ch, shown);
445
+ if (bye.code !== 'time')
446
+ throw new StavError(byeText(bye), word(bye.code));
447
+ await this.settle(ch, shown);
448
+ await ours('The 8 hours of this view are over. Run stav agent watch again to go on.');
449
+ return 0;
450
+ }
451
+ catch (e) {
452
+ if (!(e instanceof ChannelEnd))
453
+ throw e;
454
+ end = e;
455
+ }
456
+ if (this.over || !RETRY.includes(end.code))
457
+ throw new StavError(endText(end), end.code);
458
+ // Not into a line the person is typing.
459
+ if (!questions.asking)
460
+ await ours(`${endText(end)} Connecting again…`);
461
+ ch = await this.resume(p, view, onChannel);
462
+ if (!questions.asking)
463
+ await ours('Connected again.');
464
+ // The connector sends them again: the resume named the last step that was shown.
465
+ shown.held = [];
466
+ shown.heldBytes = 0;
467
+ await questions.connected(ch, view.canAnswer, view.question);
468
+ }
469
+ }
470
+ catch (e) {
471
+ await this.settle(ch, shown);
472
+ throw e;
473
+ }
474
+ }
475
+ /** The view is over: no prompt, and what came before the end is shown. */
476
+ async settle(ch, s) {
477
+ if (this.over)
478
+ return;
479
+ await s.questions.stop();
480
+ await this.flush(ch, s);
481
+ await this.d.write(s.printer.close());
482
+ }
483
+ /** Shows the number, gets the passkey, and waits for `open`. */
484
+ async prove(ch, agent, p) {
485
+ const { number } = await ch.wait(this.d.times.answer, 'number');
486
+ if (typeof number !== 'string' || !/^[0-9]{6}$/.test(number))
487
+ throw new ChannelEnd('bad_message');
488
+ await this.say(`Type this number into the page, and use your passkey: ${number.slice(0, 3)} ${number.slice(3)}`);
489
+ const page = await this.page({ portal: this.portal(), h: ch.hash, agent, mode: 'watch', id: p.passkey_id, signal: ch.connection.ended, timeoutMs: this.d.times.page });
490
+ try {
491
+ const passkey = await page.answer;
492
+ if (!isFor(passkey, challenge('watch', ch.hash, number))) {
493
+ throw new StavError('The number typed into the page was not the one shown here. Run stav agent watch again.', 'wrong_number');
494
+ }
495
+ ch.send({ t: 'passkey', ...passkey });
496
+ return opened(await ch.wait(this.d.times.answer, 'open', 'refused', 'bye'));
497
+ }
498
+ finally {
499
+ page.close();
500
+ }
501
+ }
502
+ /** Shows what comes until `bye`. A ChannelEnd when the connection ended. */
503
+ async stream(ch, s) {
504
+ for (;;) {
505
+ const { frame, size } = await ch.next(this.d.times.silent);
506
+ if (frame.t === 'bye')
507
+ return frame;
508
+ if (frame.t === 'step') {
509
+ s.held.push({ frame, size });
510
+ s.heldBytes += size;
511
+ if (s.heldBytes > MAX_HELD)
512
+ throw new ChannelEnd('bad_message');
513
+ }
514
+ else {
515
+ await s.questions.frame(frame);
516
+ }
517
+ if (!s.questions.hold)
518
+ await this.flush(ch, s);
519
+ }
520
+ }
521
+ /** Shows the steps that came, and tells the connector. */
522
+ async flush(ch, s) {
523
+ const { held } = s;
524
+ s.held = [];
525
+ s.heldBytes = 0;
526
+ for (const { frame, size } of held) {
527
+ const text = s.printer.step(frame);
528
+ if (text)
529
+ await this.d.write(text);
530
+ if (Number.isSafeInteger(frame.n) && frame.n > s.view.after)
531
+ s.view.after = frame.n;
532
+ // A frame has at most 60,000 bytes, so this tells the connector at least every 64 KiB.
533
+ s.unread += size;
534
+ if (s.unread < 4096)
535
+ continue;
536
+ s.unread = 0;
537
+ try {
538
+ ch.send({ t: 'read', n: s.view.after });
539
+ }
540
+ catch {
541
+ // The connection ended. What came before that is still shown, and next() says why.
542
+ }
543
+ }
544
+ }
545
+ /** A new connection for the same view, without the passkey. */
546
+ async resume(p, view, onChannel) {
547
+ const until = Math.min(Date.now() + this.d.times.resume, view.endsAt * 1000);
548
+ for (let wait = this.d.times.firstRetry;; wait = Math.min(wait * 2, this.d.times.lastRetry)) {
549
+ await new Promise((resolve) => setTimeout(resolve, wait));
550
+ if (this.over || Date.now() >= until)
551
+ break;
552
+ try {
553
+ const ch = await this.connect(p);
554
+ onChannel(ch);
555
+ // The number is for the passkey; a resume has its own secret.
556
+ ch.send({ t: 'resume', secret: view.secret, after: view.after });
557
+ const { secret, canAnswer, question } = opened(await ch.wait(this.d.times.answer, 'open', 'refused', 'bye'));
558
+ // As the relay does when it sees the change first.
559
+ if (canAnswer !== view.canAnswer)
560
+ throw new StavError(ENDS.ended, 'ended');
561
+ Object.assign(view, { secret, question });
562
+ return ch;
563
+ }
564
+ catch (e) {
565
+ const again = e instanceof ChannelEnd ? RETRY.includes(e.code)
566
+ : e instanceof StavError && (e.code === 'network' || e.status === 429 || (e.status ?? 0) >= 500);
567
+ if (again)
568
+ continue;
569
+ throw e instanceof ChannelEnd ? new StavError(endText(e), e.code) : e;
570
+ }
571
+ }
572
+ throw new StavError('The connection did not come back in time. Run stav agent watch again and use your passkey.', 'lost');
573
+ }
574
+ // ---- forget ----
575
+ async forget(typed) {
576
+ const all = await this.pairings.all().catch(() => []);
577
+ const readable = all.flatMap(({ pairing }) => (pairing ? [{ ...pairing, id: pairing.agent_id }] : []));
578
+ const found = pick(readable, typed);
579
+ if (!found) {
580
+ // By its id, also when what is stored cannot be read or the list is gone.
581
+ const id = typed.toLowerCase();
582
+ const p = await this.pairings.get(id).catch((e) => {
583
+ // Another word than an id gets the message: it says to use the id.
584
+ if (e instanceof StavError && e.code === 'pairing_damaged' && UUID.test(id))
585
+ return 'damaged';
586
+ throw e;
587
+ });
588
+ if (!p)
589
+ throw new StavError('This computer is paired with no agent of that name.', 'not_paired');
590
+ if (p === 'damaged') {
591
+ await this.pairings.remove(id);
592
+ await this.say('The pairing is removed from this computer. It could not be read, so Stav was not told: ask an owner or admin of the workspace to remove this computer there.');
593
+ return 0;
594
+ }
595
+ return this.forgetPairing(p);
596
+ }
597
+ return this.forgetPairing(found);
598
+ }
599
+ async forgetPairing(p) {
600
+ if (p.device_id) {
601
+ try {
602
+ await this.call(`/api/data-agents/${encodeURIComponent(p.agent_id)}/devices/${encodeURIComponent(p.device_id)}`, p.team_id, { method: 'DELETE', nullOn: [404] });
603
+ }
604
+ catch (e) {
605
+ if (!(e instanceof StavError))
606
+ throw e;
607
+ throw new StavError(`Stav could not remove this computer: ${e.message} The pairing is still stored here; try again later.`, e.code, e.status);
608
+ }
609
+ }
610
+ await this.pairings.remove(p.agent_id);
611
+ const left = p.device_id ? '' : ' Stav may still have it on its list: an owner or admin of the workspace can remove it there.';
612
+ await this.say(`This computer is no longer paired with ${p.name}.${left}`);
613
+ return 0;
614
+ }
615
+ }
616
+ /** What the `open` frame says, or the refusal as an error. */
617
+ function opened(f) {
618
+ if (f.t === 'bye')
619
+ throw new StavError(byeText(f), word(f.code));
620
+ if (f.t === 'refused')
621
+ throw new StavError(refusedText(f), word(f.code));
622
+ const question = questionOf(f);
623
+ if (!decode(f.resume, 'base64url', 32) || !Number.isSafeInteger(f.ends_at) || question === null)
624
+ throw new ChannelEnd('bad_message');
625
+ return { secret: f.resume, after: 0, endsAt: f.ends_at, canAnswer: f.can_answer === true, question };
626
+ }