@blackbelt-technology/pi-dashboard-gmail-plugin 0.10.0 → 0.11.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.
@@ -0,0 +1,723 @@
1
+ /**
2
+ * Setup run engine (design D3–D5, D8, D9): one live run per dashboard, held in
3
+ * memory. A run connects the dedicated browser (private + ephemeral), drives the
4
+ * six-step recipe over CDP, pauses on human checkpoints and decisions, and ends
5
+ * `done`, `handoff` or `cancelled`. The run view is secret-free by construction:
6
+ * it never carries the client secret or the browser instance id.
7
+ * See change: add-gmail-auto-setup.
8
+ */
9
+ import { randomUUID } from "node:crypto";
10
+ import {
11
+ type Audience,
12
+ type BrowserRefusalReason,
13
+ type CheckpointKind,
14
+ type HandoffReason,
15
+ SETUP_STEP_IDS,
16
+ type SetupContinueRequest,
17
+ type SetupDecision,
18
+ type SetupRunRequest,
19
+ type SetupRunState,
20
+ type SetupRunView,
21
+ type SetupStepId,
22
+ type SetupStepStatus,
23
+ WIZARD_STEP_OF,
24
+ } from "../../shared/auto-setup.js";
25
+ import type { AccountStore } from "../accounts.js";
26
+ import { storeClient } from "../store-client.js";
27
+ import type { DedicatedBrowserService } from "./browser-service.js";
28
+ import { captureClient } from "./capture.js";
29
+ import { type AxNode, CdpConnection, CdpError, CdpPage, defaultWsFactory, NavigationError, type PageInfo, type WsFactory } from "./cdp-page.js";
30
+ import { RunAborted, SetupControl, SetupHandoff, SignInRequired } from "./errors.js";
31
+ import { maskSecrets } from "./mask.js";
32
+ import {
33
+ buildSteps,
34
+ DEFAULT_TIMING,
35
+ generateProjectId,
36
+ REQUIRED_DOMAINS,
37
+ SEL,
38
+ type Sel,
39
+ SIGN_IN_ORIGIN,
40
+ type StepDef,
41
+ type StepEnv,
42
+ type StepFacts,
43
+ type Timing,
44
+ validateLinks,
45
+ } from "./steps.js";
46
+
47
+ export interface RunDeps {
48
+ /** Looked up per run (and per signed-in action): the browser plugin may load later. */
49
+ getService(): DedicatedBrowserService | undefined;
50
+ store: AccountStore;
51
+ logger: { info(m: string): void; warn(m: string): void };
52
+ /** Persist the run's inputs to the plugin config (`projectId`, `ownerAccount`). */
53
+ saveSetup(partial: { projectId: string; ownerAccount: string }): Promise<void>;
54
+ timing?: Partial<Timing>;
55
+ wsFactory?: WsFactory;
56
+ newId?: () => string;
57
+ }
58
+
59
+ export type ContinueResult = { ok: true } | { ok: false; status: 400 | 409; error: string };
60
+
61
+ type PendingDecision = { decision: SetupDecision; resolve(a: SetupContinueRequest): void };
62
+
63
+ const badRequest = (error: string): ContinueResult => ({ ok: false, status: 400, error });
64
+
65
+ /** Poll a checkpoint predicate; a transient CDP error counts as "not done yet". */
66
+ async function untilTolerantOfCdp(until: () => Promise<boolean>): Promise<boolean> {
67
+ try {
68
+ return await until();
69
+ } catch (err) {
70
+ if (err instanceof CdpError) return false;
71
+ throw err;
72
+ }
73
+ }
74
+
75
+ /** Validate a human answer against the pending decision; resolves it on success (400 keeps the run waiting). */
76
+ function answerDecision(pd: PendingDecision, body: SetupContinueRequest): ContinueResult {
77
+ const { decision } = pd;
78
+ if (decision.kind === "audience") {
79
+ const audience: Audience | undefined = body.audience === "internal" || body.audience === "external" ? body.audience : undefined;
80
+ if (!audience) return badRequest("invalid_audience");
81
+ if (audience === "internal" && decision.detected !== "internal") return badRequest("audience_not_allowed");
82
+ pd.resolve({ audience });
83
+ return { ok: true };
84
+ }
85
+ if (body.confirmLinks !== true) return badRequest("confirm_required");
86
+ const v = validateLinks(body.links ?? decision.links);
87
+ if (!v.ok) return badRequest(v.error);
88
+ pd.resolve({ links: v.links, confirmLinks: true });
89
+ return { ok: true };
90
+ }
91
+
92
+ const BROWSER_REFUSALS: readonly string[] = [
93
+ "disabled",
94
+ "unloaded",
95
+ "no-chrome",
96
+ "no-display",
97
+ "owned-by-other-server",
98
+ "profile-in-use",
99
+ "launch-failed",
100
+ ] satisfies BrowserRefusalReason[];
101
+
102
+ function refusalReason(reason: string, fallback: HandoffReason): HandoffReason {
103
+ return BROWSER_REFUSALS.includes(reason) ? (reason as BrowserRefusalReason) : fallback;
104
+ }
105
+
106
+ const STEPS = buildSteps(captureClient);
107
+
108
+ const TERMINAL: readonly SetupRunState[] = ["done", "handoff", "cancelled"];
109
+
110
+ interface Deferred<T> {
111
+ promise: Promise<T>;
112
+ resolve(v: T): void;
113
+ reject(e: unknown): void;
114
+ }
115
+
116
+ function deferred<T>(): Deferred<T> {
117
+ let resolve!: (v: T) => void;
118
+ let reject!: (e: unknown) => void;
119
+ const promise = new Promise<T>((res, rej) => {
120
+ resolve = res;
121
+ reject = rej;
122
+ });
123
+ promise.catch(() => undefined); // losers of a race must not be unhandled
124
+ return { promise, resolve, reject };
125
+ }
126
+
127
+ const sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
128
+
129
+ /** The dedicated browser's CDP endpoint is always the dashboard's own loopback socket. */
130
+ function isLoopbackCdpUrl(raw: string): boolean {
131
+ try {
132
+ const u = new URL(raw);
133
+ return u.protocol === "ws:" && (u.hostname === "127.0.0.1" || u.hostname === "localhost" || u.hostname === "[::1]");
134
+ } catch {
135
+ return false;
136
+ }
137
+ }
138
+
139
+ /** Reject when `fn` does not settle in `ms` (a Chrome that never answers must not wedge the single run slot). */
140
+ async function withTimeout(ms: number, fn: () => Promise<void>): Promise<void> {
141
+ let timer: ReturnType<typeof setTimeout> | undefined;
142
+ try {
143
+ await Promise.race([
144
+ fn(),
145
+ new Promise<never>((_, reject) => {
146
+ timer = setTimeout(() => reject(new SetupHandoff("browser_closed", "project")), ms);
147
+ }),
148
+ ]);
149
+ } finally {
150
+ if (timer) clearTimeout(timer);
151
+ }
152
+ }
153
+
154
+ /** A pausable step limit: human waits do not count against the 60 s. */
155
+ class StepClock {
156
+ readonly expired = deferred<never>();
157
+ private remaining: number;
158
+ private startedAt = 0;
159
+ private timer?: ReturnType<typeof setTimeout>;
160
+ private stopped = false;
161
+ constructor(ms: number) {
162
+ this.remaining = ms;
163
+ this.resume();
164
+ }
165
+ pause(): void {
166
+ if (this.timer === undefined) return;
167
+ clearTimeout(this.timer);
168
+ this.timer = undefined;
169
+ this.remaining -= Date.now() - this.startedAt;
170
+ }
171
+ resume(): void {
172
+ if (this.stopped || this.timer !== undefined) return;
173
+ this.startedAt = Date.now();
174
+ this.timer = setTimeout(() => this.expired.reject(new SetupHandoff("timeout")), Math.max(0, this.remaining));
175
+ }
176
+ stop(): void {
177
+ this.stopped = true;
178
+ if (this.timer !== undefined) clearTimeout(this.timer);
179
+ this.timer = undefined;
180
+ }
181
+ }
182
+
183
+ /** One pass of a step; replaced after a sign-in interruption. */
184
+ interface Attempt {
185
+ dead: boolean;
186
+ clock: StepClock;
187
+ interrupt: Deferred<never>;
188
+ }
189
+
190
+ export interface RunInput {
191
+ mode: SetupRunRequest["mode"];
192
+ projectId: string;
193
+ ownerEmail: string;
194
+ }
195
+
196
+ export class SetupRun {
197
+ readonly id: string;
198
+ readonly input: RunInput;
199
+ readonly timing: Timing;
200
+ /** Resolves when the run has fully ended and released the browser (tests, cancel). */
201
+ settled: Promise<void> = Promise.resolve();
202
+
203
+ // — state surfaced in the view —
204
+ state: SetupRunState = "starting";
205
+ private step: SetupStepId = "project";
206
+ private readonly statuses = new Map<SetupStepId, SetupStepStatus>(SETUP_STEP_IDS.map((id) => [id, "pending"]));
207
+ private checkpoint?: CheckpointKind;
208
+ private decision?: SetupDecision;
209
+ private busyHolder?: string;
210
+ private handoff?: SetupRunView["handoff"];
211
+ readonly created: { projectId?: string; clients: string[] } = { clients: [] };
212
+ clientId?: string;
213
+ readonly facts: StepFacts = {};
214
+
215
+ // — internals shared with the step environment —
216
+ /** @internal */ ended = false;
217
+ /** @internal */ page?: CdpPage;
218
+ /** @internal */ service?: DedicatedBrowserService;
219
+ /** @internal */ signInPending = false;
220
+ /** @internal */ readonly deps: RunDeps;
221
+ private conn?: CdpConnection;
222
+ private instanceId?: string;
223
+ private closing = false;
224
+ private cleanupP?: Promise<void>;
225
+ private readonly abort = deferred<never>();
226
+ private abortErr?: SetupControl;
227
+ private attempt?: Attempt;
228
+ private inHumanWait = false;
229
+ private signInContinue = false;
230
+ private pendingDecision?: PendingDecision;
231
+ private takeoverRequested = deferred<void>();
232
+ private keepAlive?: ReturnType<typeof setInterval>;
233
+ private stepStart = Date.now();
234
+
235
+ constructor(deps: RunDeps, input: RunInput) {
236
+ this.deps = deps;
237
+ this.input = input;
238
+ this.id = (deps.newId ?? randomUUID)();
239
+ this.timing = { ...DEFAULT_TIMING, ...deps.timing };
240
+ }
241
+
242
+ get terminal(): boolean {
243
+ return TERMINAL.includes(this.state);
244
+ }
245
+
246
+ start(): void {
247
+ this.settled = this.main();
248
+ }
249
+
250
+ view(): SetupRunView {
251
+ const v: SetupRunView = {
252
+ runId: this.id,
253
+ state: this.state,
254
+ step: this.step,
255
+ steps: SETUP_STEP_IDS.map((id) => ({ id, status: this.statuses.get(id) ?? "pending" })),
256
+ projectId: this.input.projectId,
257
+ created: { ...(this.created.projectId ? { projectId: this.created.projectId } : {}), clients: [...this.created.clients] },
258
+ ownerEmail: this.input.ownerEmail,
259
+ };
260
+ if (this.checkpoint) v.checkpoint = { kind: this.checkpoint };
261
+ if (this.decision) v.decision = this.decision;
262
+ if (this.state === "busy") v.busy = { holder: this.busyHolder };
263
+ if (this.handoff) v.handoff = this.handoff;
264
+ if (this.clientId) v.clientId = this.clientId;
265
+ if (this.facts.audience) v.audience = this.facts.audience;
266
+ return v;
267
+ }
268
+
269
+ /** Answer a decision or acknowledge the sign-in checkpoint. 400 keeps the run waiting. */
270
+ continue(body: SetupContinueRequest): ContinueResult {
271
+ const pd = this.pendingDecision;
272
+ if (this.state === "waiting_decision" && pd) return answerDecision(pd, body);
273
+ if (this.state === "waiting_user" && this.checkpoint === "sign_in") {
274
+ this.signInContinue = true;
275
+ return { ok: true };
276
+ }
277
+ return { ok: false, status: 409, error: "not_waiting" };
278
+ }
279
+
280
+ /** Confirmed takeover of a busy dedicated profile. */
281
+ takeover(): ContinueResult {
282
+ if (this.state !== "busy") return { ok: false, status: 409, error: "not_busy" };
283
+ this.takeoverRequested.resolve();
284
+ return { ok: true };
285
+ }
286
+
287
+ async cancel(): Promise<void> {
288
+ if (this.ended) return;
289
+ this.ended = true;
290
+ this.state = "cancelled";
291
+ this.checkpoint = undefined;
292
+ this.decision = undefined;
293
+ this.deps.logger.info("[gmail] setup run cancelled");
294
+ this.abortWith(new RunAborted());
295
+ await this.cleanup();
296
+ }
297
+
298
+ // ───────────────────────── main flow ─────────────────────────
299
+
300
+ private async main(): Promise<void> {
301
+ try {
302
+ await this.deps.saveSetup({ projectId: this.input.projectId, ownerAccount: this.input.ownerEmail }).catch(() => undefined);
303
+ await this.connectBrowser();
304
+ this.state = "running";
305
+ for (const def of STEPS) await this.runStep(def);
306
+ this.ended = true;
307
+ this.state = "done";
308
+ this.deps.logger.info("[gmail] setup run done");
309
+ } catch (err) {
310
+ this.fail(err);
311
+ } finally {
312
+ await this.cleanup();
313
+ }
314
+ }
315
+
316
+ private fail(err: unknown): void {
317
+ if (this.state === "cancelled") return;
318
+ const cause = this.abortErr instanceof SetupHandoff ? this.abortErr : err;
319
+ if (cause instanceof RunAborted) return;
320
+ let reason: HandoffReason = "unexpected_page";
321
+ let step = this.step;
322
+ if (cause instanceof SetupHandoff) {
323
+ reason = cause.reason;
324
+ step = cause.step ?? this.step;
325
+ } else {
326
+ // Class name only: a message could carry page content.
327
+ this.deps.logger.warn(maskSecrets(`[gmail] setup run error: ${cause instanceof Error ? cause.name : "unknown"}`));
328
+ }
329
+ this.ended = true;
330
+ this.step = step;
331
+ this.statuses.set(step, "handoff");
332
+ this.handoff = {
333
+ step,
334
+ wizardStep: WIZARD_STEP_OF[step],
335
+ reason,
336
+ ...(reason === "domain_blocked" ? { domains: [...REQUIRED_DOMAINS] } : {}),
337
+ };
338
+ this.checkpoint = undefined;
339
+ this.decision = undefined;
340
+ this.state = "handoff";
341
+ this.logStep(step, `handoff:${reason}`);
342
+ }
343
+
344
+ private logStep(id: SetupStepId, outcome: string): void {
345
+ this.deps.logger.info(maskSecrets(`[gmail] setup step ${id} ${outcome} ${Date.now() - this.stepStart}ms`));
346
+ }
347
+
348
+ private abortWith(err: SetupControl): void {
349
+ this.abortErr ??= err;
350
+ this.abort.reject(err);
351
+ }
352
+
353
+ private async connectBrowser(): Promise<void> {
354
+ const service = this.deps.getService();
355
+ if (!service) throw new SetupHandoff("unloaded", "project");
356
+ this.service = service;
357
+ let res = await service.connect({ client: "gmail-setup", private: true, ephemeral: true });
358
+ if (this.ended) {
359
+ // Cancelled (or the browser closed) while the connect was pending: stay terminal, never enter `busy`.
360
+ if (res.ok) await service.disconnect(res.instanceId).catch(() => undefined);
361
+ throw new RunAborted();
362
+ }
363
+ if (!res.ok && res.reason === "busy") {
364
+ // The holder's instance id stays server-side; the view only names the holder.
365
+ this.busyHolder = res.holder;
366
+ this.state = "busy";
367
+ await Promise.race([this.takeoverRequested.promise, this.abort.promise]);
368
+ this.state = "starting";
369
+ res = await service.connect({ client: "gmail-setup", takeover: true, private: true, ephemeral: true });
370
+ }
371
+ if (this.ended) {
372
+ if (res.ok) await service.disconnect(res.instanceId).catch(() => undefined);
373
+ throw new RunAborted();
374
+ }
375
+ if (!res.ok) throw new SetupHandoff(refusalReason(res.reason, "launch-failed"), "project");
376
+ this.instanceId = res.instanceId;
377
+ try {
378
+ if (!isLoopbackCdpUrl(res.cdpUrl)) throw new SetupHandoff("launch-failed", "project");
379
+ await withTimeout(this.timing.stepLimitMs, async () => {
380
+ this.conn = await CdpConnection.connect(res.cdpUrl, this.deps.wsFactory ?? defaultWsFactory);
381
+ this.conn.onClose(() => {
382
+ if (!this.closing && !this.ended) this.abortWith(new SetupHandoff("browser_closed"));
383
+ });
384
+ this.page = await CdpPage.open(this.conn, { onSignInBlocked: () => this.onSignInBlocked() });
385
+ });
386
+ } catch (err) {
387
+ if (err instanceof SetupControl) throw err;
388
+ throw new SetupHandoff("browser_closed", "project");
389
+ }
390
+ // The browser plugin's idle sweep must never close a run that is waiting on a human.
391
+ this.keepAlive = setInterval(() => void this.page?.ping().catch(() => undefined), this.timing.keepAliveMs);
392
+ this.keepAlive.unref?.();
393
+ }
394
+
395
+ private onSignInBlocked(): void {
396
+ this.signInPending = true;
397
+ if (!this.inHumanWait && this.attempt) this.attempt.interrupt.reject(new SignInRequired());
398
+ }
399
+
400
+ private async runStep(def: StepDef): Promise<void> {
401
+ this.step = def.id;
402
+ this.statuses.set(def.id, "running");
403
+ this.stepStart = Date.now();
404
+ for (;;) {
405
+ if (this.abortErr) throw this.abortErr;
406
+ if (this.signInPending) await Promise.race([this.signInCheckpoint(), this.abort.promise]);
407
+ const attempt: Attempt = { dead: false, clock: new StepClock(this.timing.stepLimitMs), interrupt: deferred<never>() };
408
+ this.attempt = attempt;
409
+ try {
410
+ const outcome = await Promise.race([
411
+ this.execute(def, new AttemptEnv(this, attempt)),
412
+ attempt.clock.expired.promise,
413
+ attempt.interrupt.promise,
414
+ this.abort.promise,
415
+ ]);
416
+ this.statuses.set(def.id, outcome);
417
+ this.logStep(def.id, outcome);
418
+ return;
419
+ } catch (err) {
420
+ if (err instanceof SignInRequired) continue; // loop top runs the checkpoint, then the step restarts
421
+ throw err;
422
+ } finally {
423
+ attempt.dead = true;
424
+ attempt.clock.stop();
425
+ }
426
+ }
427
+ }
428
+
429
+ private async execute(def: StepDef, env: StepEnv): Promise<"done" | "skipped"> {
430
+ if (await def.check(env)) return "skipped";
431
+ await def.act(env);
432
+ if (!(await def.verify(env))) throw new SetupHandoff("unexpected_page");
433
+ return "done";
434
+ }
435
+
436
+ // ───────────────────────── human waits ─────────────────────────
437
+
438
+ /** @internal Run `fn` with the step clock paused and sign-in interrupts deferred. */
439
+ async humanWait(attempt: Attempt, fn: () => Promise<void>): Promise<void> {
440
+ attempt.clock.pause();
441
+ this.inHumanWait = true;
442
+ try {
443
+ await fn();
444
+ } finally {
445
+ this.inHumanWait = false;
446
+ attempt.clock.resume();
447
+ }
448
+ if (this.signInPending) throw new SignInRequired();
449
+ }
450
+
451
+ /** @internal */
452
+ async runCheckpoint(
453
+ attempt: Attempt,
454
+ kind: CheckpointKind,
455
+ until: () => Promise<boolean>,
456
+ opts?: { front?: boolean },
457
+ ): Promise<void> {
458
+ await this.humanWait(attempt, async () => {
459
+ this.state = "waiting_user";
460
+ this.checkpoint = kind;
461
+ try {
462
+ if (opts?.front) await this.page?.bringToFront().catch(() => undefined);
463
+ await this.pollCheckpoint(attempt, until);
464
+ } finally {
465
+ this.checkpoint = undefined;
466
+ if (!this.ended) this.state = "running";
467
+ }
468
+ });
469
+ }
470
+
471
+ /** Poll `until` every `pollMs` until true; times out into a handoff, aborts when the attempt/run dies. */
472
+ private async pollCheckpoint(attempt: Attempt, until: () => Promise<boolean>): Promise<void> {
473
+ const deadline = Date.now() + this.timing.checkpointLimitMs;
474
+ for (;;) {
475
+ if (await untilTolerantOfCdp(until)) return;
476
+ if (Date.now() >= deadline) throw new SetupHandoff("timeout");
477
+ await Promise.race([sleep(this.timing.pollMs), this.abort.promise]);
478
+ if (attempt.dead || this.ended) throw new RunAborted();
479
+ }
480
+ }
481
+
482
+ /** @internal */
483
+ async runDecision(attempt: Attempt, decision: SetupDecision): Promise<SetupContinueRequest> {
484
+ let answer: SetupContinueRequest = {};
485
+ await this.humanWait(attempt, async () => {
486
+ this.state = "waiting_decision";
487
+ this.decision = decision;
488
+ try {
489
+ // Raced with abort so a cancel or a closing browser releases the wait (and the `finally` below) at once.
490
+ answer = await Promise.race([
491
+ new Promise<SetupContinueRequest>((resolve) => {
492
+ this.pendingDecision = { decision, resolve };
493
+ }),
494
+ this.abort.promise,
495
+ ]);
496
+ } finally {
497
+ this.pendingDecision = undefined;
498
+ this.decision = undefined;
499
+ if (!this.ended) this.state = "running";
500
+ }
501
+ });
502
+ return answer;
503
+ }
504
+
505
+ /**
506
+ * Sign-in checkpoint (design D5): the run's own tab goes to `about:blank`; the
507
+ * Google sign-in page opens in a hidden tab of the run's ephemeral context.
508
+ * The run tab stays blank until that tab's origin leaves accounts.google.com
509
+ * or the user confirms, so no tab the run can read ever renders a password form.
510
+ */
511
+ private async signInCheckpoint(): Promise<void> {
512
+ const service = this.service;
513
+ const page = this.page;
514
+ if (!service || !page || !this.instanceId) throw new SetupHandoff("browser_closed");
515
+ this.inHumanWait = true;
516
+ this.state = "waiting_user";
517
+ this.checkpoint = "sign_in";
518
+ try {
519
+ await page.navigate("about:blank").catch(() => undefined);
520
+ const q = new URLSearchParams({
521
+ service: "cloudconsole",
522
+ continue: "https://console.cloud.google.com/",
523
+ login_hint: this.input.ownerEmail,
524
+ hl: "en",
525
+ });
526
+ const opened = await service.open({ url: `${SIGN_IN_ORIGIN}/ServiceLogin?${q.toString()}`, instanceId: this.instanceId });
527
+ if (!opened.ok) throw new SetupHandoff(refusalReason(opened.reason, "domain_blocked"));
528
+ await service.focus(opened.tabId).catch(() => undefined);
529
+ const deadline = Date.now() + this.timing.checkpointLimitMs;
530
+ for (;;) {
531
+ if (this.ended) throw new RunAborted();
532
+ if (this.signInContinue) return;
533
+ // `null` = the tab is gone (closed by the user, dead Chrome): not a completed sign-in; keep waiting for "I've signed in" or the timeout.
534
+ const origin = await service.tabOrigin(opened.tabId);
535
+ if (origin !== null && origin !== SIGN_IN_ORIGIN) return;
536
+ if (Date.now() >= deadline) throw new SetupHandoff("timeout");
537
+ await Promise.race([sleep(this.timing.pollMs), this.abort.promise]);
538
+ }
539
+ } finally {
540
+ this.signInPending = false;
541
+ this.signInContinue = false;
542
+ this.inHumanWait = false;
543
+ this.checkpoint = undefined;
544
+ if (!this.ended) this.state = "running";
545
+ }
546
+ }
547
+
548
+ // ───────────────────────── teardown ─────────────────────────
549
+
550
+ private cleanup(): Promise<void> {
551
+ this.cleanupP ??= (async () => {
552
+ if (this.keepAlive) clearInterval(this.keepAlive);
553
+ this.closing = true;
554
+ this.conn?.close();
555
+ // Only an instance this run connected; a busy holder's instance is never ours to close.
556
+ if (this.instanceId) await this.service?.disconnect(this.instanceId).catch(() => undefined);
557
+ })();
558
+ return this.cleanupP;
559
+ }
560
+ }
561
+
562
+ /** The capability surface a step attempt sees; stale once its attempt is replaced or the run ended. */
563
+ class AttemptEnv implements StepEnv {
564
+ private readonly run: SetupRun;
565
+ private readonly attempt: Attempt;
566
+
567
+ constructor(run: SetupRun, attempt: Attempt) {
568
+ this.run = run;
569
+ this.attempt = attempt;
570
+ }
571
+
572
+ get mode() {
573
+ return this.run.input.mode;
574
+ }
575
+ get projectId() {
576
+ return this.run.input.projectId;
577
+ }
578
+ get ownerEmail() {
579
+ return this.run.input.ownerEmail;
580
+ }
581
+ get timing() {
582
+ return this.run.timing;
583
+ }
584
+ get facts() {
585
+ return this.run.facts;
586
+ }
587
+ get created() {
588
+ return this.run.created;
589
+ }
590
+
591
+ private live(): CdpPage {
592
+ if (this.attempt.dead || this.run.ended || !this.run.page) throw new RunAborted();
593
+ return this.run.page;
594
+ }
595
+
596
+ async navigate(url: string): Promise<void> {
597
+ try {
598
+ await this.live().navigate(url);
599
+ } catch (err) {
600
+ // A navigation the redirect guard failed is a sign-in, not a refusal.
601
+ if (err instanceof NavigationError && this.run.signInPending) throw new SignInRequired();
602
+ throw err;
603
+ }
604
+ }
605
+ info(): Promise<PageInfo> {
606
+ return this.live().info();
607
+ }
608
+ text(): Promise<string> {
609
+ return this.live().text();
610
+ }
611
+ dialogText(): Promise<string> {
612
+ return this.live().dialogText();
613
+ }
614
+ find(sel: Sel): Promise<AxNode | undefined> {
615
+ return this.live().queryAXTree(sel.role, sel.name);
616
+ }
617
+ async click(sel: Sel): Promise<void> {
618
+ const node = await this.need(sel);
619
+ await this.live().clickNode(node);
620
+ }
621
+ async fill(sel: Sel, text: string): Promise<void> {
622
+ const node = await this.need(sel);
623
+ await this.live().fill(node, text);
624
+ }
625
+ bringToFront(): Promise<void> {
626
+ return this.live().bringToFront();
627
+ }
628
+
629
+ async waitFor<T>(probe: () => Promise<T | false | undefined | null>, ms: number): Promise<T | undefined> {
630
+ const end = Date.now() + ms;
631
+ for (;;) {
632
+ this.live();
633
+ try {
634
+ const v = await probe();
635
+ if (v) return v;
636
+ } catch (err) {
637
+ if (!(err instanceof CdpError)) throw err;
638
+ }
639
+ if (Date.now() >= end) return undefined;
640
+ await sleep(this.timing.pollMs);
641
+ }
642
+ }
643
+
644
+ async need(sel: Sel): Promise<AxNode> {
645
+ let termsHandled = false;
646
+ for (;;) {
647
+ const node = await this.waitFor(() => this.find(sel), this.timing.markerWaitMs);
648
+ if (node) return node;
649
+ // The terms dialog can render after load: wait for the user, then look again once.
650
+ if (!termsHandled && (await this.find(SEL.termsAgree))) {
651
+ termsHandled = true;
652
+ await this.checkpoint("console_terms", async () => !(await this.find(SEL.termsAgree)));
653
+ continue;
654
+ }
655
+ throw new SetupHandoff("unexpected_page");
656
+ }
657
+ }
658
+
659
+ checkpoint(kind: CheckpointKind, until: () => Promise<boolean>, opts?: { front?: boolean }): Promise<void> {
660
+ this.live();
661
+ return this.run.runCheckpoint(this.attempt, kind, until, opts);
662
+ }
663
+
664
+ decide(decision: SetupDecision): Promise<SetupContinueRequest> {
665
+ this.live();
666
+ return this.run.runDecision(this.attempt, decision);
667
+ }
668
+
669
+ async saveLinks(links: Parameters<StepEnv["saveLinks"]>[0]): Promise<void> {
670
+ this.live();
671
+ await this.run.deps.store.setSetupRecord({ links });
672
+ }
673
+
674
+ async downloadsDir(): Promise<string> {
675
+ this.live();
676
+ const status = await this.run.service?.status();
677
+ if (!status) throw new CdpError("status");
678
+ return status.downloadsDir;
679
+ }
680
+
681
+ async storeClient(json: unknown): Promise<{ ok: true; clientId: string } | { ok: false; error: string }> {
682
+ this.live();
683
+ const r = await storeClient(this.run.deps.store, json, this.run.deps.logger);
684
+ if (!r.ok) return { ok: false, error: r.error };
685
+ this.run.clientId = r.client.clientId;
686
+ return { ok: true, clientId: r.client.clientId };
687
+ }
688
+ }
689
+
690
+ /** Holds the runs of this dashboard process: one live, the last few kept for polling. */
691
+ export class SetupRunManager {
692
+ private readonly runs = new Map<string, SetupRun>();
693
+ private readonly deps: RunDeps;
694
+
695
+ constructor(deps: RunDeps) {
696
+ this.deps = deps;
697
+ }
698
+
699
+ get live(): SetupRun | undefined {
700
+ return [...this.runs.values()].find((r) => !r.terminal);
701
+ }
702
+
703
+ get(id: string): SetupRun | undefined {
704
+ return this.runs.get(id);
705
+ }
706
+
707
+ /** `undefined` → a run is already live. */
708
+ start(req: { mode: RunInput["mode"]; projectId?: string; ownerEmail: string }): SetupRun | undefined {
709
+ if (this.live) return undefined;
710
+ const run = new SetupRun(this.deps, {
711
+ mode: req.mode,
712
+ projectId: req.projectId ?? generateProjectId(),
713
+ ownerEmail: req.ownerEmail,
714
+ });
715
+ this.runs.set(run.id, run);
716
+ for (const [id, r] of this.runs) {
717
+ if (this.runs.size <= 5) break;
718
+ if (r.terminal) this.runs.delete(id);
719
+ }
720
+ run.start();
721
+ return run;
722
+ }
723
+ }