@mitralab.io/platform-sdk 1.1.2 → 1.1.3

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 CHANGED
@@ -2,6 +2,45 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## 1.1.3
6
+
7
+ - A chat created through `session({ create: true })` over the `auto` or `websocket` transport is
8
+ born on the T3 box: the create request carries `runtime: "T3"`. A chat created with
9
+ `transport: "http"` stays on the runner, and an explicit `runtime` is forwarded as given.
10
+ - The box channel is asked for once. The Copilot now holds the channel request while the box
11
+ boots, so the 2 s polling on a 202 answer is gone; a 202 from an older Copilot means the chat
12
+ follows the Copilot socket.
13
+ - Depend on `@mitralab.io/sdk-core@0.2.4`, which carries the `runtime` session option into the
14
+ create request, exports `AgentTaskRuntime`, and sends a prompt whose task already exists even
15
+ when the session was closed inside its `taskCreated` handler.
16
+
17
+ ## 1.2.0-beta.1
18
+
19
+ - Add `signInWithEmail()`: the platform auth page collects the address and the one-time code, and
20
+ the single-use exchange code it returns is redeemed at IAM's `/auth/magic-link/exchange` for the
21
+ same app session Google and Microsoft SSO already produce.
22
+ - Add `completeEmailSignInRedirect()`, which finishes both the mobile redirect and the tab opened
23
+ by the link in the message.
24
+ - Keep the pending email request, the one-time state and the auth page URL and never a token, in
25
+ `localStorage` for 10 minutes, so the tab opened by the link in the message finishes the flow
26
+ through the same state check the redirect uses. Writing it is best effort for a popup and
27
+ required for a redirect.
28
+ - Consume a fragment of the flow's own provider even when it cannot be completed, so a rejected or
29
+ expired redirect is reported once instead of on every reload. A fragment of another flow stays
30
+ untouched, and a pending request is still dropped only when it expires.
31
+ - Name the flow in the one-time state (`google.<random>`, `microsoft.<random>`, `email.<random>`),
32
+ which the auth page echoes verbatim, so every `complete*SignInRedirect()` recognizes its own
33
+ fragment: a fragment from another method returns `null` untouched, whatever this browser has
34
+ pending, and an application that offers all three can call all three at startup in any order. A
35
+ fragment that names this flow without matching its pending request is rejected as forged.
36
+ - Generalize the auth page handshake into `AuthPageFlow`, parameterized by provider, exchange
37
+ route, and where the pending request lives, instead of a second copy for email.
38
+ - Upgrading mid-flow: a redirect started by an earlier version stored a state without the provider
39
+ name, so the completion after the upgrade returns `null` and the person signs in again. Nothing
40
+ is lost beyond that one attempt, and only for redirects in flight during the upgrade.
41
+ - Give each provider its own popup window name.
42
+ - Point the deprecated `signIn` and `signUp` failures at `signInWithEmail()`.
43
+
5
44
  ## 1.1.0-beta.2
6
45
 
7
46
  `1.1.0-beta.1` was published from `main` before this change landed, so it still depends on Core `0.2.0-beta.0`; use `1.1.0-beta.2`.
package/README.md CHANGED
@@ -50,7 +50,7 @@ The client derives service endpoints from `apiUrl`: `/iam`, `/data-manager`, `/f
50
50
 
51
51
  The Platform SDK owns:
52
52
 
53
- - browser Google SSO, logout, and session refresh
53
+ - browser Google and Microsoft SSO, browser email sign-in, logout, and session refresh
54
54
  - trusted session adoption for the embedded app preview
55
55
  - session persistence in `localStorage`
56
56
  - auth-state listeners
@@ -76,7 +76,7 @@ unsubscribe()
76
76
 
77
77
  Authentication state is stored under `mitra_auth_{appId}`. Before each authenticated native request, the SDK checks a JWT's `exp` claim with a 30-second safety window and refreshes directly through IAM when needed. Opaque tokens, malformed JWTs, and JWTs without a numeric `exp` remain server-authoritative and proceed to the request. A `401` still triggers reactive recovery and at most one retry. If another login or bridged session replaced the token while the request was in flight, the retry uses that current token without refreshing its session. If sign-out cleared the token, the old `401` neither refreshes nor retries.
78
78
 
79
- The generated-application authentication flow is Google SSO. The old native `signIn` and `signUp` names fail locally with `UNSUPPORTED_AUTH_METHOD` because IAM has no email/password endpoints. Deprecated login bindings remain available only through the legacy reexports.
79
+ A generated application signs people in with Google SSO, Microsoft SSO, or email. The old native `signIn` and `signUp` names fail locally with `UNSUPPORTED_AUTH_METHOD` because IAM has no email/password endpoints; `signInWithEmail()` is the email flow that replaced them. Deprecated login bindings remain available only through the legacy reexports.
80
80
 
81
81
  ### Signing in as a process
82
82
 
@@ -158,6 +158,72 @@ const mitra = createClient({
158
158
  })
159
159
  ```
160
160
 
161
+ ### Signing in with email
162
+
163
+ Email sign-in needs neither a password nor an SSO account. The same platform page opens, a popup
164
+ by default, collects the address, sends a six-digit code, and IAM answers with a single-use
165
+ exchange code that the SDK redeems at `/iam/api/v1/auth/magic-link/exchange`. What comes back is
166
+ the app session SSO already returns, persisted and refreshed the same way:
167
+
168
+ ```typescript
169
+ const user = await mitra.auth.signInWithEmail()
170
+ ```
171
+
172
+ Redirect mode navigates the current page instead of opening a popup, and is completed during
173
+ startup like the SSO redirect:
174
+
175
+ ```typescript
176
+ await mitra.auth.signInWithEmail({ mode: "redirect" })
177
+ ```
178
+
179
+ ```typescript
180
+ const emailUser = await mitra.auth.completeEmailSignInRedirect()
181
+ ```
182
+
183
+ Call `completeEmailSignInRedirect()` at startup even when sign-in was started as a popup, because
184
+ the message carries a link as well as the code, and that link opens a **new tab**. That tab never
185
+ saw the popup, so the pending request has to outlive the tab that opened it: the one-time state
186
+ and the resolved auth page URL are written to `localStorage` under `mitra_email_redirect_{appId}`
187
+ for 10 minutes, dropped when the flow completes, or discarded as stale the next time a result is read. `sessionStorage`,
188
+ which the SSO redirect uses, is scoped to a single tab and cannot answer for another one. The link still has
189
+ to be opened in the same browser that started the sign-in: another browser or device has no pending request,
190
+ refuses the fragment, and the exchange code was already spent by the page. On another device, use the
191
+ six-digit code in the popup instead.
192
+
193
+ **No token is written there.** What is persisted is only the record of a request already in
194
+ flight, which is the smallest thing that lets the other tab finish it, and it expires on its own.
195
+ The tab opened by the link comes back with the same one-time state the flow started with, so it
196
+ is completed by exactly the check the redirect uses; a request older than 10 minutes is discarded
197
+ rather than completed. Writing the request is best effort for a popup: without `localStorage` the
198
+ popup still signs in and only the completion from the link is lost, while redirect mode, which has
199
+ nowhere else to keep it, fails at the start.
200
+
201
+ When the person finishes in the tab the link opened, the `signInWithEmail()` call still waiting in
202
+ the original tab eventually times out. Treat that rejection as a cancelled popup: the session is
203
+ already established wherever the application called `completeEmailSignInRedirect()`.
204
+
205
+ One fragment belongs to one flow, and an application that offers more than one method can call
206
+ every completion at startup, in any order:
207
+
208
+ ```typescript
209
+ const user =
210
+ (await mitra.auth.completeEmailSignInRedirect()) ??
211
+ (await mitra.auth.completeGoogleSignInRedirect()) ??
212
+ (await mitra.auth.completeMicrosoftSignInRedirect())
213
+ ```
214
+
215
+ A chain like that propagates a rejection: an expired request or a forged fragment on the first
216
+ completion keeps the others from running. Wrap each call in `try`/`catch` when the application
217
+ should still try the remaining methods after one of them refuses a fragment.
218
+
219
+ The one-time state each flow generates names that flow, as in `google.<random>` or
220
+ `email.<random>`, and the auth page echoes it verbatim, so a completion recognizes its own
221
+ fragment. A fragment from another method returns `null` and leaves the fragment and that other
222
+ flow's pending request untouched, whatever this browser has pending. A fragment that does name
223
+ this flow but does not match its pending request is rejected as forged, and the fragment is
224
+ removed from the URL on the way out, so the rejection is reported once instead of on every
225
+ reload.
226
+
161
227
  ## Entities
162
228
 
163
229
  ```typescript
@@ -246,7 +312,9 @@ unsubscribe()
246
312
  session.close()
247
313
  ```
248
314
 
249
- Open an existing task with `session({ taskId })`. The default `auto` transport refreshes before connecting, asks the Copilot where the chat is served, and opens whichever channel it names: the box that runs the agent when one is offered, `/copilot/ws/tasks/{taskId}` otherwise. The choice belongs to the server, never to application configuration, so a Copilot that stops offering the box leaves every application on the Copilot socket without a republish. Opening the box never asks it to replay, whether the conversation is new to the session or is being opened again after an idle close: what an idle conversation missed is history, which the application loads over REST. A box socket that drops in the middle of a turn is redialed by the SDK itself, with a bounded backoff (1, 2, 4, 8 and 16 seconds) and the replay from the last position seen on that socket, so the answer keeps streaming; a position taken on one box is forgotten when the Copilot points the conversation to another box; replayed `textChunk` frames reach the `delta` event like live text. While that happens the session emits `raw` events of type `channelReconnecting` (payload `attempt`, `maxAttempts`, `reason`) and `channelConnected` (payload `attempt`); the session `status` stays `streaming`, because Core has no reconnecting status. The disconnect reaches Core, and with it the `error` event, only when the attempts run out or the Copilot no longer offers the box. A drop with no turn in flight, a channel taken over by another tab (close code 4409), and any close of the Copilot socket the session did not ask for are reported at once, whatever the code, so the next send reopens the channel instead of waiting on a socket that is gone. Recovery through persisted history plus the HTTP/SSE channel is unchanged. Set `transport: "http"` when WebSockets are unavailable. Messages sent during a turn enter a FIFO queue with a maximum of 10 items; the session also exposes edit, remove, clear, approval, cancel, history, close, and typed events.
315
+ A chat created with `create: true` over the `auto` or `websocket` transport is born on the T3 box (`runtime: "T3"` in the create request), so the first open does not wait for the box to adopt it; a chat created with `transport: "http"` stays on the Copilot runner. Pass `runtime: "RUNNER"` or `runtime: "T3"` to decide explicitly.
316
+
317
+ Open an existing task with `session({ taskId })`. The default `auto` transport refreshes before connecting, asks the Copilot once where the chat is served, and opens whichever channel it names: the box that runs the agent when one is offered, `/copilot/ws/tasks/{taskId}` otherwise. The Copilot holds that request while the box boots and answers only once the box is ready or cannot be had; the SDK does not poll. The choice belongs to the server, never to application configuration, so a Copilot that stops offering the box leaves every application on the Copilot socket without a republish. Opening the box never asks it to replay, whether the conversation is new to the session or is being opened again after an idle close: what an idle conversation missed is history, which the application loads over REST. A box socket that drops in the middle of a turn is redialed by the SDK itself, with a bounded backoff (1, 2, 4, 8 and 16 seconds) and the replay from the last position seen on that socket, so the answer keeps streaming; a position taken on one box is forgotten when the Copilot points the conversation to another box; replayed `textChunk` frames reach the `delta` event like live text. While that happens the session emits `raw` events of type `channelReconnecting` (payload `attempt`, `maxAttempts`, `reason`) and `channelConnected` (payload `attempt`); the session `status` stays `streaming`, because Core has no reconnecting status. The disconnect reaches Core, and with it the `error` event, only when the attempts run out or the Copilot no longer offers the box. A drop with no turn in flight, a channel taken over by another tab (close code 4409), and any close of the Copilot socket the session did not ask for are reported at once, whatever the code, so the next send reopens the channel instead of waiting on a socket that is gone. Recovery through persisted history plus the HTTP/SSE channel is unchanged. Set `transport: "http"` when WebSockets are unavailable. Messages sent during a turn enter a FIFO queue with a maximum of 10 items; the session also exposes edit, remove, clear, approval, cancel, history, close, and typed events.
250
318
 
251
319
  A prompt sent while the browser says it is offline (`navigator.onLine === false`) does not enter Core at all, because Core opens the channel and reads the turn baseline before the prompt goes out and every one of those requests would fail first: the session keeps the prompt in an outbox, emits a `raw` event of type `inputUnsent` (payload `attempt` 0, `reason`, `waitingForOnline` true) and hands it to Core, in order, when the browser fires `online`; the turn starts then. A prompt whose `POST /inputs` went out but got no response at all is kept the same way: the session sends the same request again when the browser fires `online` or on a bounded backoff (2, 5, 10, 20 and 40 seconds), while the turn stays `streaming`, with `inputUnsent` events (payload `attempt`, `reason`, `waitingForOnline`, `retryInMs` when a timer is armed) and, once it goes through, `inputSent` (payload `attempts`). A response from the server, an error included, is never retried: the prompt fails through the `error` event as before. A session closed with a prompt still waiting emits `error` with code `INPUT_UNSENT` before it goes quiet, and `sendAndWait` rejects. The retry cannot tell a request the server never received from one whose response was lost on the way back, so a prompt may reach the server twice in that case; the Copilot's `/inputs` accepts no client message id yet. The public `agentTasks.sendInput` primitive is not held back: it fails immediately, as it always did.
252
320
 
package/dist/index.cjs CHANGED
@@ -434,16 +434,37 @@ async function resolveApiKeySession(publicClient, appId, apiKey) {
434
434
  );
435
435
  }
436
436
 
437
- // src/modules/google-auth.ts
437
+ // src/modules/auth-page-flow.ts
438
438
  var import_sdk_core2 = require("@mitralab.io/sdk-core");
439
439
  var RESULT_TYPE = "mitra-oauth-result";
440
- var PROVIDER_LABELS = {
441
- google: "Google",
442
- microsoft: "Microsoft"
440
+ var FIVE_MINUTES_MS = 5 * 60 * 1e3;
441
+ var TEN_MINUTES_MS = 10 * 60 * 1e3;
442
+ var PROVIDERS = {
443
+ google: {
444
+ label: "Google",
445
+ exchangePath: "/api/v1/auth/google",
446
+ sendsRedirectUri: true,
447
+ redirectStorage: "sessionStorage",
448
+ popupTimeoutMs: FIVE_MINUTES_MS
449
+ },
450
+ microsoft: {
451
+ label: "Microsoft",
452
+ exchangePath: "/api/v1/auth/microsoft",
453
+ sendsRedirectUri: true,
454
+ redirectStorage: "sessionStorage",
455
+ popupTimeoutMs: FIVE_MINUTES_MS
456
+ },
457
+ email: {
458
+ label: "Email",
459
+ exchangePath: "/api/v1/auth/magic-link/exchange",
460
+ sendsRedirectUri: false,
461
+ redirectStorage: "localStorage",
462
+ pendingRequestTtlMs: TEN_MINUTES_MS,
463
+ popupTimeoutMs: TEN_MINUTES_MS
464
+ }
443
465
  };
444
466
  var POPUP_WIDTH = 480;
445
467
  var POPUP_HEIGHT = 600;
446
- var POPUP_TIMEOUT_MS = 5 * 60 * 1e3;
447
468
  var POPUP_CLOSED_POLL_MS = 500;
448
469
  function expectAuthTokenResponse(value) {
449
470
  const response = (0, import_sdk_core2.expectObject)(
@@ -464,12 +485,13 @@ function expectAuthTokenResponse(value) {
464
485
  tokenType: response.tokenType
465
486
  };
466
487
  }
467
- var GoogleAuthFlow = class {
488
+ var AuthPageFlow = class {
468
489
  appId;
469
490
  apiUrl;
470
491
  configuredAuthPageUrl;
471
492
  client;
472
493
  provider;
494
+ profile;
473
495
  providerLabel;
474
496
  redirectStorageKey;
475
497
  popupPromise = null;
@@ -479,7 +501,8 @@ var GoogleAuthFlow = class {
479
501
  this.configuredAuthPageUrl = config.authPageUrl;
480
502
  this.client = config.client;
481
503
  this.provider = config.provider ?? "google";
482
- this.providerLabel = PROVIDER_LABELS[this.provider];
504
+ this.profile = PROVIDERS[this.provider];
505
+ this.providerLabel = this.profile.label;
483
506
  this.redirectStorageKey = `mitra_${this.provider}_redirect_${config.appId}`;
484
507
  }
485
508
  signIn(options = {}) {
@@ -496,6 +519,19 @@ var GoogleAuthFlow = class {
496
519
  });
497
520
  return this.popupPromise;
498
521
  }
522
+ /**
523
+ * Finishes a redirect this provider started, or returns `null` when the URL
524
+ * carries no result or carries one that belongs to another provider's flow.
525
+ *
526
+ * The state generated at the start of every flow is prefixed with the provider
527
+ * name, and the auth page echoes it verbatim, so a fragment identifies its own
528
+ * flow. An application that offers several methods can call every completion
529
+ * at startup, in any order, even while other methods have requests pending.
530
+ *
531
+ * A fragment of this flow is always consumed, including when it cannot be
532
+ * completed, so a failure is reported once instead of on every reload. A
533
+ * fragment of another flow is left exactly as it was found.
534
+ */
499
535
  async completeRedirect() {
500
536
  const browserWindow = this.requireBrowser();
501
537
  const params = new URLSearchParams(browserWindow.location.hash.replace(/^#/, ""));
@@ -504,17 +540,36 @@ var GoogleAuthFlow = class {
504
540
  const error = params.get("errorMitra");
505
541
  if (code === null && state === null && error === null) return null;
506
542
  const context = this.readRedirectContext(browserWindow);
507
- if (!state?.trim()) {
508
- throw new Error(`${this.providerLabel} sign-in redirect is missing state.`);
543
+ const hasState = state !== null && state.trim() !== "";
544
+ if (hasState && !this.ownsState(state)) return null;
545
+ if (!hasState && !context) return null;
546
+ if (!hasState) {
547
+ throw this.discardOwnRedirect(
548
+ browserWindow,
549
+ `${this.providerLabel} sign-in redirect is missing state.`
550
+ );
551
+ }
552
+ if (context && this.hasExpired(context)) {
553
+ this.clearRedirectContext(browserWindow);
554
+ throw this.discardOwnRedirect(
555
+ browserWindow,
556
+ `${this.providerLabel} sign-in request expired before it was completed.`
557
+ );
509
558
  }
510
559
  if (context?.state !== state) {
511
- throw new Error(`Invalid ${this.providerLabel} sign-in state (possible CSRF).`);
560
+ throw this.discardOwnRedirect(
561
+ browserWindow,
562
+ `Invalid ${this.providerLabel} sign-in state (possible CSRF).`
563
+ );
512
564
  }
513
565
  const expectedRedirectUri = this.getRedirectUri(
514
566
  resolveAuthPageUrl(this.apiUrl, this.configuredAuthPageUrl, browserWindow)
515
567
  );
516
568
  if (context.redirectUri !== expectedRedirectUri) {
517
- throw new Error(`${this.providerLabel} sign-in redirect context is invalid.`);
569
+ throw this.discardOwnRedirect(
570
+ browserWindow,
571
+ `${this.providerLabel} sign-in redirect context is invalid.`
572
+ );
518
573
  }
519
574
  this.cleanRedirectFragment(browserWindow);
520
575
  this.clearRedirectContext(browserWindow);
@@ -533,8 +588,13 @@ var GoogleAuthFlow = class {
533
588
  this.configuredAuthPageUrl,
534
589
  browserWindow
535
590
  );
591
+ const completedInAnotherTab = this.profile.pendingRequestTtlMs !== void 0;
592
+ if (completedInAnotherTab) {
593
+ this.writeRedirectContext(browserWindow, this.newRedirectContext(state, authPageUrl));
594
+ }
536
595
  const popup = this.openPopup(browserWindow, this.buildStartUrl(browserWindow, authPageUrl, state));
537
596
  const result = await this.waitForPopupResult(browserWindow, popup, authPageUrl.origin, state);
597
+ if (completedInAnotherTab) this.clearRedirectContext(browserWindow);
538
598
  if (result.code) return this.exchangeCode(result.code, this.getRedirectUri(authPageUrl));
539
599
  return expectAuthTokenResponse(result.token);
540
600
  }
@@ -545,20 +605,20 @@ var GoogleAuthFlow = class {
545
605
  this.configuredAuthPageUrl,
546
606
  browserWindow
547
607
  );
548
- const context = {
549
- state,
550
- redirectUri: this.getRedirectUri(authPageUrl)
551
- };
552
- this.persistRedirectContext(browserWindow, context);
608
+ if (!this.writeRedirectContext(browserWindow, this.newRedirectContext(state, authPageUrl))) {
609
+ throw new Error(
610
+ `${this.providerLabel} sign-in redirect requires ${this.profile.redirectStorage}.`
611
+ );
612
+ }
553
613
  const startUrl = this.buildStartUrl(browserWindow, authPageUrl, state);
554
614
  browserWindow.location.assign(startUrl.toString());
555
615
  return new Promise(() => void 0);
556
616
  }
557
617
  async exchangeCode(code, redirectUri) {
558
- const response = await this.client.post(`/api/v1/auth/${this.provider}`, {
618
+ const response = await this.client.post(this.profile.exchangePath, {
559
619
  appId: this.appId,
560
620
  code,
561
- redirectUri
621
+ ...this.profile.sendsRedirectUri ? { redirectUri } : {}
562
622
  });
563
623
  return expectAuthTokenResponse(response);
564
624
  }
@@ -575,13 +635,41 @@ var GoogleAuthFlow = class {
575
635
  getRedirectUri(authPageUrl) {
576
636
  return `${authPageUrl.origin}${authPageUrl.pathname}`;
577
637
  }
638
+ newRedirectContext(state, authPageUrl) {
639
+ return {
640
+ state,
641
+ redirectUri: this.getRedirectUri(authPageUrl),
642
+ createdAt: Date.now()
643
+ };
644
+ }
645
+ /**
646
+ * Reports a fragment of this flow that cannot be completed, dropping it from the
647
+ * URL first. Nobody else claims a fragment that names this flow, so leaving it
648
+ * there would make the application fail again on every reload.
649
+ */
650
+ discardOwnRedirect(browserWindow, message) {
651
+ this.cleanRedirectFragment(browserWindow);
652
+ return new Error(message);
653
+ }
654
+ /** Whether a state echoed by the auth page was generated by this provider's flow. */
655
+ ownsState(state) {
656
+ return state.startsWith(`${this.provider}.`);
657
+ }
658
+ hasExpired(context) {
659
+ const ttlMs = this.profile.pendingRequestTtlMs;
660
+ if (ttlMs === void 0) return false;
661
+ if (!Number.isFinite(context.createdAt)) return true;
662
+ return Date.now() - context.createdAt > ttlMs;
663
+ }
664
+ /** A one-time state that names the flow that created it, so its fragment is recognizable. */
578
665
  generateState() {
579
666
  if (!globalThis.crypto?.getRandomValues) {
580
667
  throw new Error(`${this.providerLabel} sign-in requires crypto.getRandomValues.`);
581
668
  }
582
669
  const bytes = new Uint8Array(16);
583
670
  globalThis.crypto.getRandomValues(bytes);
584
- return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
671
+ const random = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
672
+ return `${this.provider}.${random}`;
585
673
  }
586
674
  openPopup(browserWindow, url) {
587
675
  const outerWidth = browserWindow.outerWidth || browserWindow.screen.width;
@@ -590,7 +678,7 @@ var GoogleAuthFlow = class {
590
678
  const top = Math.max(0, (browserWindow.screenY || 0) + (outerHeight - POPUP_HEIGHT) / 2);
591
679
  const popup = browserWindow.open(
592
680
  url.toString(),
593
- "mitra-google-oauth",
681
+ `mitra-${this.provider}-auth`,
594
682
  `width=${POPUP_WIDTH},height=${POPUP_HEIGHT},left=${left},top=${top},menubar=no,toolbar=no,status=no`
595
683
  );
596
684
  if (!popup) {
@@ -603,7 +691,7 @@ var GoogleAuthFlow = class {
603
691
  const timeout = globalThis.setTimeout(() => {
604
692
  cleanup();
605
693
  reject(new Error(`${this.providerLabel} sign-in timed out.`));
606
- }, POPUP_TIMEOUT_MS);
694
+ }, this.profile.popupTimeoutMs);
607
695
  const closedPoll = globalThis.setInterval(() => {
608
696
  if (popup.closed) {
609
697
  cleanup();
@@ -628,7 +716,7 @@ var GoogleAuthFlow = class {
628
716
  const code = typeof data.code === "string" && data.code.trim() ? data.code : void 0;
629
717
  if (!code && data.token === void 0) {
630
718
  cleanup();
631
- reject(new Error("Google auth page returned neither code nor token."));
719
+ reject(new Error(`${this.providerLabel} auth page returned neither code nor token.`));
632
720
  return;
633
721
  }
634
722
  cleanup();
@@ -643,22 +731,28 @@ var GoogleAuthFlow = class {
643
731
  browserWindow.addEventListener("message", onMessage);
644
732
  });
645
733
  }
646
- persistRedirectContext(browserWindow, context) {
734
+ /** Writes the pending request, reporting whether storage accepted it. */
735
+ writeRedirectContext(browserWindow, context) {
647
736
  try {
648
- browserWindow.sessionStorage.setItem(this.redirectStorageKey, JSON.stringify(context));
737
+ browserWindow[this.profile.redirectStorage].setItem(
738
+ this.redirectStorageKey,
739
+ JSON.stringify(context)
740
+ );
741
+ return true;
649
742
  } catch {
650
- throw new Error(`${this.providerLabel} sign-in redirect requires sessionStorage.`);
743
+ return false;
651
744
  }
652
745
  }
653
746
  readRedirectContext(browserWindow) {
654
747
  try {
655
- const raw = browserWindow.sessionStorage.getItem(this.redirectStorageKey);
748
+ const raw = browserWindow[this.profile.redirectStorage].getItem(this.redirectStorageKey);
656
749
  if (!raw) return null;
657
750
  const value = JSON.parse(raw);
658
751
  if (typeof value.state !== "string" || typeof value.redirectUri !== "string") return null;
659
752
  return {
660
753
  state: value.state,
661
- redirectUri: value.redirectUri
754
+ redirectUri: value.redirectUri,
755
+ createdAt: typeof value.createdAt === "number" ? value.createdAt : Number.NaN
662
756
  };
663
757
  } catch {
664
758
  return null;
@@ -666,7 +760,7 @@ var GoogleAuthFlow = class {
666
760
  }
667
761
  clearRedirectContext(browserWindow) {
668
762
  try {
669
- browserWindow.sessionStorage.removeItem(this.redirectStorageKey);
763
+ browserWindow[this.profile.redirectStorage].removeItem(this.redirectStorageKey);
670
764
  } catch {
671
765
  }
672
766
  }
@@ -736,6 +830,7 @@ var AuthModule = class {
736
830
  currentUserApi;
737
831
  googleAuth;
738
832
  microsoftAuth;
833
+ emailAuth;
739
834
  constructor(appId, iamBaseUrl, options = {}) {
740
835
  this.appId = appId;
741
836
  const trimmedIamBaseUrl = stripTrailingSlashes(iamBaseUrl);
@@ -752,19 +847,26 @@ var AuthModule = class {
752
847
  onUnauthorized: (requestToken) => this.handleUnauthorized(requestToken)
753
848
  });
754
849
  this.currentUserApi = (0, import_sdk_core3.createAuthModule)(this.authedClient, coreErrors);
755
- this.googleAuth = new GoogleAuthFlow({
850
+ this.googleAuth = new AuthPageFlow({
756
851
  appId,
757
852
  apiUrl,
758
853
  authPageUrl: options.authPageUrl,
759
854
  client: this.publicClient
760
855
  });
761
- this.microsoftAuth = new GoogleAuthFlow({
856
+ this.microsoftAuth = new AuthPageFlow({
762
857
  appId,
763
858
  apiUrl,
764
859
  authPageUrl: options.authPageUrl,
765
860
  client: this.publicClient,
766
861
  provider: "microsoft"
767
862
  });
863
+ this.emailAuth = new AuthPageFlow({
864
+ appId,
865
+ apiUrl,
866
+ authPageUrl: options.authPageUrl,
867
+ client: this.publicClient,
868
+ provider: "email"
869
+ });
768
870
  this.loadFromStorage();
769
871
  const readAccessToken = () => this.#accessToken;
770
872
  sessionPorts.set(this, {
@@ -790,10 +892,10 @@ var AuthModule = class {
790
892
  get isAuthenticated() {
791
893
  return this._currentUser !== null && this.#accessToken !== null;
792
894
  }
793
- /** @deprecated Email/password authentication is not implemented by IAM. Use Google or Microsoft SSO. */
895
+ /** @deprecated Email/password authentication is not implemented by IAM. Use signInWithEmail() or SSO. */
794
896
  async signIn(_credentials) {
795
897
  throw new MitraApiError(
796
- "Email/password authentication is not available. Use signInWithGoogle() or signInWithMicrosoft().",
898
+ "Email/password authentication is not available. Use signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
797
899
  0,
798
900
  "UNSUPPORTED_AUTH_METHOD"
799
901
  );
@@ -879,8 +981,10 @@ var AuthModule = class {
879
981
  *
880
982
  * The method consumes and clears the fragment and stored CSRF context, sends
881
983
  * the single-use code directly to IAM, persists both tokens, calls `auth.me()`,
882
- * and notifies auth-state listeners. It returns `null` when the current URL is
883
- * not a Google SSO redirect. Redirect errors must carry the same `stateMitra`
984
+ * and notifies auth-state listeners. It returns `null` when the current URL
985
+ * carries no redirect result, and also when it carries one this flow never
986
+ * started, so an application that offers several methods can call every
987
+ * completion at startup. Redirect errors must carry the same `stateMitra`
884
988
  * stored at the start of the flow before their message is exposed or consumed.
885
989
  *
886
990
  * @returns The authenticated user, or `null` when no redirect result is present.
@@ -916,10 +1020,54 @@ var AuthModule = class {
916
1020
  const tokenResponse = await this.microsoftAuth.completeRedirect();
917
1021
  return tokenResponse ? this.establishSession(tokenResponse) : null;
918
1022
  }
919
- /** @deprecated Email/password registration is not implemented by IAM. Use Google or Microsoft SSO. */
1023
+ /**
1024
+ * Signs in with a one-time code sent by email: the same auth-page handshake as
1025
+ * SSO, where the platform page collects the address and the code, and IAM
1026
+ * hands back a single-use exchange code redeemed at `/auth/magic-link/exchange`.
1027
+ * Popup by default; redirect mode navigates away.
1028
+ *
1029
+ * The message also carries a link. Because that link opens a new tab, the
1030
+ * pending request is kept in `localStorage` for 10 minutes - the one-time state
1031
+ * and the auth page URL, never a token - so
1032
+ * {@link completeEmailSignInRedirect} can finish the flow in that tab.
1033
+ *
1034
+ * @param options - Popup or redirect mode.
1035
+ * @returns The authenticated and hydrated user in popup mode.
1036
+ * @throws {MitraApiError} When IAM rejects the exchange code.
1037
+ * @throws {Error} When the browser blocks or cancels the popup, the flow times
1038
+ * out, or the response fails origin, source, state, or shape validation. A
1039
+ * person who finishes through the link instead of the popup leaves this call
1040
+ * to time out, which the application should treat as a cancelled popup.
1041
+ *
1042
+ * @example
1043
+ * ```typescript
1044
+ * const user = await mitra.auth.signInWithEmail();
1045
+ * ```
1046
+ */
1047
+ async signInWithEmail(options = {}) {
1048
+ return this.establishSession(await this.emailAuth.signIn(options));
1049
+ }
1050
+ /**
1051
+ * Completes an email sign-in from `#codeMitra` and `#stateMitra`, during
1052
+ * application startup like {@link completeGoogleSignInRedirect}.
1053
+ *
1054
+ * It covers both ways the flow comes back, and they are the same check: a
1055
+ * redirect in the tab that started it, and the tab the link in the message
1056
+ * opened. Both carry the one-time state this SDK generated, which the second
1057
+ * tab matches against the pending request kept in `localStorage`. A request
1058
+ * older than 10 minutes is discarded instead of completed.
1059
+ *
1060
+ * @returns The authenticated user, or `null` when the URL carries no result or
1061
+ * carries one that belongs to another sign-in method's flow.
1062
+ */
1063
+ async completeEmailSignInRedirect() {
1064
+ const tokenResponse = await this.emailAuth.completeRedirect();
1065
+ return tokenResponse ? this.establishSession(tokenResponse) : null;
1066
+ }
1067
+ /** @deprecated Email/password registration is not implemented by IAM. Use signInWithEmail() or SSO. */
920
1068
  async signUp(_data) {
921
1069
  throw new MitraApiError(
922
- "Email/password registration is not available. Use signInWithGoogle() or signInWithMicrosoft().",
1070
+ "Email/password registration is not available. Use signInWithEmail(), signInWithGoogle() or signInWithMicrosoft().",
923
1071
  0,
924
1072
  "UNSUPPORTED_AUTH_METHOD"
925
1073
  );
@@ -1660,8 +1808,6 @@ function holdSendsWhileOffline(session, outbox) {
1660
1808
 
1661
1809
  // src/modules/agent-session.ts
1662
1810
  var CONNECT_TIMEOUT_MS = 15e3;
1663
- var CHANNEL_BOOT_TIMEOUT_MS = 9e4;
1664
- var CHANNEL_BOOT_RETRY_MS = 2e3;
1665
1811
  var SILENCE_TIMEOUT_MS = 6e4;
1666
1812
  var RECONNECT_DELAYS_MS = [1e3, 2e3, 4e3, 8e3, 16e3];
1667
1813
  var SUPERSEDED_CLOSE_CODE = 4409;
@@ -1827,28 +1973,28 @@ var BrowserAgentTaskEventSource = class {
1827
1973
  requestDirectChannel(taskId, token, signal) {
1828
1974
  return this.askDirectChannel(taskId, token, signal).catch(() => null);
1829
1975
  }
1830
- /** Like `requestDirectChannel`, but a request the network lost is thrown, not a refusal. */
1976
+ /**
1977
+ * Like `requestDirectChannel`, but a request the network lost is thrown, not a refusal.
1978
+ *
1979
+ * One request. The copilot holds it while the box boots and answers 200 with the channel, or
1980
+ * an error status once the box cannot be had. A 202 comes only from a copilot older than that
1981
+ * contract, which used to mean "still booting, ask again": there is no channel to open, and
1982
+ * the conversation follows the copilot socket. Polling here again would put the wait back on
1983
+ * the client that the server now owns.
1984
+ */
1831
1985
  async askDirectChannel(taskId, token, signal) {
1986
+ if (signal?.aborted) return null;
1832
1987
  const url = `${this.apiUrl}/copilot/api/v1/tasks/${encodeURIComponent(taskId)}/channel`;
1833
- const deadline = Date.now() + CHANNEL_BOOT_TIMEOUT_MS;
1834
- for (; ; ) {
1835
- if (signal?.aborted) return null;
1836
- const response = await globalThis.fetch(url, {
1837
- method: "POST",
1838
- headers: { Authorization: `Bearer ${stripBearer2(token)}` },
1839
- ...signal ? { signal } : {}
1840
- });
1841
- if (response.status === 202) {
1842
- if (Date.now() >= deadline) return null;
1843
- await sleep(CHANNEL_BOOT_RETRY_MS, signal);
1844
- continue;
1845
- }
1846
- if (!response.ok) return null;
1847
- try {
1848
- return toDirectChannel(await response.json(), this.apiUrl);
1849
- } catch {
1850
- return null;
1851
- }
1988
+ const response = await globalThis.fetch(url, {
1989
+ method: "POST",
1990
+ headers: { Authorization: `Bearer ${stripBearer2(token)}` },
1991
+ ...signal ? { signal } : {}
1992
+ });
1993
+ if (response.status === 202 || !response.ok) return null;
1994
+ try {
1995
+ return toDirectChannel(await response.json(), this.apiUrl);
1996
+ } catch {
1997
+ return null;
1852
1998
  }
1853
1999
  }
1854
2000
  async openWebSocket(taskId, observer, signal) {
@@ -2136,6 +2282,10 @@ var BrowserAgentTaskEventSource = class {
2136
2282
  };
2137
2283
 
2138
2284
  // src/modules/agent-tasks.ts
2285
+ function bornOnBox(options) {
2286
+ if (!("create" in options) || options.runtime || options.transport === "http") return options;
2287
+ return { ...options, runtime: "T3" };
2288
+ }
2139
2289
  function createBrowserAgentTasksModule(httpClient, auth, apiUrl) {
2140
2290
  const tasks = (0, import_sdk_core8.createAgentTasksModule)(httpClient, coreErrors);
2141
2291
  const source = new BrowserAgentTaskEventSource(auth, apiUrl);
@@ -2165,7 +2315,7 @@ function createBrowserAgentTasksModule(httpClient, auth, apiUrl) {
2165
2315
  eventSource
2166
2316
  });
2167
2317
  return (0, import_sdk_core8.withAgentTaskSessions)(tasks, {
2168
- session: (options) => holdSendsWhileOffline(manager.session(options), outbox)
2318
+ session: (options) => holdSendsWhileOffline(manager.session(bornOnBox(options)), outbox)
2169
2319
  });
2170
2320
  }
2171
2321