@mitralab.io/platform-sdk 1.2.0-beta.1 → 1.2.0-beta.2

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,56 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## 1.2.0-beta.2
6
+
7
+ - Add `requestEmailCode({ email, language? })` and `verifyEmailCode({ receipt, code })`: sign-in by
8
+ email with no platform screen at all. The application renders its own address and code fields,
9
+ IAM sends a message branded as the app, and the verification returns the single-use exchange
10
+ code the SDK redeems for the same app session SSO produces.
11
+ - Land the link that message carries on the application's own origin, as `#emailToken=<token>`,
12
+ completed by the same `completeEmailSignInRedirect()` at startup. The link is inspected before it
13
+ is consumed and spent only when IAM reports the origin the page is on and the one-time state of
14
+ the request pending in this browser, so another browser, another device, or a scanner opening
15
+ links on the way to a mailbox consumes nothing and leaves the link valid for whoever asked.
16
+ - Keep the pending headless request under the same `mitra_email_redirect_{appId}` key the auth page
17
+ flow uses, with the same 10 minutes and the same contents: the one-time state and the app origin,
18
+ never a token. It is written once IAM accepts the request, so a resend IAM refuses, a rate limit
19
+ being the everyday case, leaves the message already in the mailbox completable by its link.
20
+ - Take only `emailToken` out of the URL when the link lands, leaving the rest of the fragment
21
+ exactly as it was found, so an application that routes on it keeps its route.
22
+ - Send `brand` and `language` with the request: the brand comes from the app info `init()` reads,
23
+ and asking before `init()` fails with `INVALID_CONFIGURATION` instead of branding a message at
24
+ random. The language is the caller's, then the browser's, then `pt-BR`.
25
+ - Add `MitraApiError.retryAfterSeconds`, read from `Retry-After`, so a `429` says how long to wait
26
+ instead of leaving the application to guess. It is `null` when the response carries no delay,
27
+ including when CORS keeps the header from reaching the browser. The field is the last constructor
28
+ parameter and optional, so existing construction is unchanged.
29
+ - Keep `signInWithEmail()`, the platform page popup and redirect, working exactly as before, along
30
+ with the `#codeMitra` completion and the Google and Microsoft flows.
31
+
32
+ ## 1.1.5-beta.0
33
+
34
+ - The eight `agentCredentials` methods take a trailing `{ scope: "ACCOUNT" }`, sent as the
35
+ `scope=ACCOUNT` query parameter, and `session({ create: true })` and `agentTasks.create()`
36
+ accept `scope: "ACCOUNT"` in the create body, so the credential and the chat resolve against
37
+ the person's own account instead of the app. Without `scope` nothing changes on the wire. The
38
+ Copilot honors `ACCOUNT` only for apps listed by flag and answers
39
+ `ACCOUNT_CREDENTIAL_NOT_ALLOWED` otherwise.
40
+ - Depend on `@mitralab.io/sdk-core@0.2.5-beta.0`, which carries the `scope` option through the
41
+ credential calls and into the create request and exports `AgentCredentialScope` and
42
+ `AgentCredentialOptions`.
43
+
44
+ ## 1.1.4-beta.0
45
+
46
+ - On the direct channel the message and the interrupt are written on the box socket, as the
47
+ client frames the box already reads, instead of `POST /copilot/api/v1/tasks/{id}/inputs`. The
48
+ box asks the Copilot for admission itself and answers on the same socket, so the Copilot's host
49
+ socket buffer no longer bounds the message: the only limit is the box channel's own. REST stays
50
+ for a chat with no box socket, for a socket not open at the moment of the send, a redial in
51
+ progress included, and for every approval answer. A frame written on a socket that closes
52
+ before the box acknowledges it is not resent over REST, since the box may have admitted the
53
+ turn already; the redial's replay recovers it.
54
+
5
55
  ## 1.1.3
6
56
 
7
57
  - A chat created through `session({ create: true })` over the `auto` or `websocket` transport is
package/README.md CHANGED
@@ -30,7 +30,9 @@ await mitra.init()
30
30
  ```
31
31
 
32
32
  `init()` resolves the application's public Code Studio configuration, including nullable
33
- `dataSourceId`, `allowSignup`, and `emailLoginEnabled`. The Data Source value remains part of the
33
+ `dataSourceId`, `allowSignup`, and `emailLoginEnabled`. It also reads the application's brand, which
34
+ does not become a public property: it is what `requestEmailCode()` sends so IAM writes the
35
+ message as the application. The Data Source value remains part of the
34
36
  Platform 1.x compatibility flow; native Entities and Custom Queries resolve the current app through
35
37
  the authenticated request. Call `init()` during application startup before the compatibility
36
38
  sign-up method needs `allowSignup` or the login screen needs `emailLoginEnabled`.
@@ -160,67 +162,146 @@ const mitra = createClient({
160
162
 
161
163
  ### Signing in with email
162
164
 
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:
165
+ Email sign-in needs neither a password nor an SSO account, and the application
166
+ never has to send anyone to a platform screen. It renders its own address and
167
+ code fields, IAM sends a message branded as the app, and the link in that
168
+ message comes back to the application's own origin:
167
169
 
168
170
  ```typescript
169
- const user = await mitra.auth.signInWithEmail()
171
+ const { receipt, resendAfterSeconds } = await mitra.auth.requestEmailCode({
172
+ email: "person@example.com",
173
+ })
174
+
175
+ const user = await mitra.auth.verifyEmailCode({ receipt, code: "123456" })
170
176
  ```
171
177
 
172
- Not every app is in the rollout. `mitra.emailLoginEnabled` is this app's own verdict, read from
173
- `/info` during `init()`, and it is what a login screen should offer the option on:
178
+ `requestEmailCode()` answers the same way whatever the address is, so nothing in
179
+ it says whether that person already exists. The `receipt` names the request when
180
+ the code comes back; it is not a credential and authorizes nothing on its own.
181
+ Resending is calling `requestEmailCode()` again, which replaces the request in
182
+ flight; `resendAfterSeconds` is how long to wait before offering that.
183
+
184
+ The message is written in `pt-BR` or `en`. Pass `language` to choose; without it
185
+ the SDK reads the browser's language and falls back to `pt-BR`.
186
+
187
+ `requestEmailCode()` needs `init()` to have run, because the message is branded
188
+ with the app's own brand, read from `/info`. Calling it before that fails with
189
+ `INVALID_CONFIGURATION` rather than sending a message branded at random.
190
+ `mitra.emailLoginEnabled`, read from the same `/info`, is this app's own verdict
191
+ about the rollout, and it is what a login screen should offer the option on:
174
192
 
175
193
  ```typescript
176
194
  await mitra.init()
177
195
 
178
196
  if (mitra.emailLoginEnabled) {
179
- // render "sign in with email"
197
+ // render the email field
180
198
  }
181
199
  ```
182
200
 
183
- It is `false` before `init()` runs, `false` when the server answers without the field or with
184
- something that is not a boolean, and `false` is the safe answer: the app is outside the rollout,
185
- IAM answers a request neutrally without sending anything, and the person would wait for a message
186
- that never arrives. Calling `signInWithEmail()` anyway is not blocked by the SDK; the verdict is
187
- there so the application does not offer a door that does not open.
201
+ It is `false` before `init()` runs, `false` when the server answers without the
202
+ field or with something that is not a boolean, and `false` is the safe answer:
203
+ the app is outside the rollout, IAM answers a request neutrally without sending
204
+ anything, and the person would wait for a message that never arrives. Calling
205
+ the email methods anyway is not blocked by the SDK; the verdict is there so the
206
+ application does not offer a door that does not open.
207
+
208
+ #### The link in the message
188
209
 
189
- Redirect mode navigates the current page instead of opening a popup, and is completed during
190
- startup like the SSO redirect:
210
+ The same message carries a link back to this application's own origin, as
211
+ `#emailToken=<token>`. Complete it during application startup, before rendering
212
+ authenticated routes:
191
213
 
192
214
  ```typescript
193
- await mitra.auth.signInWithEmail({ mode: "redirect" })
215
+ const emailUser = await mitra.auth.completeEmailSignInRedirect()
216
+ ```
217
+
218
+ The token travels in the fragment, so it never reaches a server other than the
219
+ one this SDK sends it to. The SDK inspects the link first, without consuming it,
220
+ and spends it only when IAM reports the origin the page is on and the one-time
221
+ state of the request pending in this browser. That pending request is written by
222
+ `requestEmailCode()` to `localStorage` under `mitra_email_redirect_{appId}`, for
223
+ 10 minutes:
224
+
225
+ ```json
226
+ { "state": "email.<random>", "redirectUri": "https://app.example.com", "createdAt": 0 }
227
+ ```
228
+
229
+ **No token is written there.** What is persisted is only the record of a request
230
+ already in flight, which is the smallest thing that lets the tab the link opens
231
+ finish it, and it expires on its own. Writing it is best effort: without
232
+ `localStorage` the code typed into the application still signs in and only the
233
+ completion from the link is lost.
234
+
235
+ **The link has to be opened in the same browser that asked for the message.**
236
+ Another browser or device has no pending request, so the SDK consumes nothing,
237
+ returns `null`, and the link stays valid for the person who asked. The same
238
+ answer protects against a scanner that opens links on their way to a mailbox. On
239
+ another device, type the six-digit code instead.
240
+
241
+ Only `emailToken` is taken out of the URL. The rest of the fragment is left
242
+ exactly as it was found, so an application that routes on it keeps its route.
243
+
244
+ `completeEmailSignInRedirect()` returns `null` when the URL carries no sign-in
245
+ result, when it carries one belonging to another method's flow, and when it
246
+ carries a link this browser cannot claim. A link that does belong here but
247
+ cannot be used is reported as a `MitraApiError`:
248
+
249
+ | Code | Status | What happened |
250
+ |---|---|---|
251
+ | `MAGIC_LINK_EXPIRED` | 409 | The request behind the link is over. Ask for a new message. |
252
+ | `MAGIC_LINK_USED` | 409 | The link was already spent, here or elsewhere. |
253
+ | `MAGIC_LINK_INVALID` | 401 | IAM does not recognize the token in the link. |
254
+
255
+ `verifyEmailCode()` reports `INVALID_CODE` (401) for a code that does not match,
256
+ and the same `MAGIC_LINK_EXPIRED` and `MAGIC_LINK_USED` when the request is
257
+ over. Both methods report `RATE_LIMITED` (429) when IAM asks the person to slow
258
+ down, and `SIGNUP_NOT_ALLOWED`, `APP_ACCESS_REQUIRED`, `APP_ACCESS_REVOKED`
259
+ (403) or `APP_ACCESS_LIMIT_REACHED` (409) when this app does not admit that
260
+ address. A `429` carries `error.retryAfterSeconds` when the gateway exposes
261
+ `Retry-After`, and `null` when it does not.
262
+
263
+ `requestEmailCode()` also reports `INVALID_ORIGIN` (400) when the page asking
264
+ for the message is not on one of the origins published for this application, and
265
+ both methods report `VALIDATION_FAILED` (400) for a field IAM refuses to read,
266
+ such as a malformed address or a code that is not six digits.
267
+
268
+ #### Through the platform page
269
+
270
+ `signInWithEmail()` is the older flow and still works: the same platform page
271
+ SSO opens collects the address and the code, and the single-use exchange code it
272
+ returns is redeemed at `/iam/api/v1/auth/magic-link/exchange` for the same app
273
+ session:
274
+
275
+ ```typescript
276
+ const user = await mitra.auth.signInWithEmail()
194
277
  ```
195
278
 
279
+ It opens a popup by default, and redirect mode navigates the current page
280
+ instead:
281
+
196
282
  ```typescript
197
- const emailUser = await mitra.auth.completeEmailSignInRedirect()
283
+ await mitra.auth.signInWithEmail({ mode: "redirect" })
198
284
  ```
199
285
 
200
- Call `completeEmailSignInRedirect()` at startup even when sign-in was started as a popup, because
201
- the message carries a link as well as the code, and that link opens a **new tab**. That tab never
202
- saw the popup, so the pending request has to outlive the tab that opened it: the one-time state
203
- and the resolved auth page URL are written to `localStorage` under `mitra_email_redirect_{appId}`
204
- for 10 minutes, dropped when the flow completes, or discarded as stale the next time a result is read. `sessionStorage`,
205
- which the SSO redirect uses, is scoped to a single tab and cannot answer for another one. The link still has
206
- to be opened in the same browser that started the sign-in: another browser or device has no pending request,
207
- refuses the fragment, and the exchange code was already spent by the page. On another device, use the
208
- six-digit code in the popup instead.
209
-
210
- **No token is written there.** What is persisted is only the record of a request already in
211
- flight, which is the smallest thing that lets the other tab finish it, and it expires on its own.
212
- The tab opened by the link comes back with the same one-time state the flow started with, so it
213
- is completed by exactly the check the redirect uses; a request older than 10 minutes is discarded
214
- rather than completed. Writing the request is best effort for a popup: without `localStorage` the
215
- popup still signs in and only the completion from the link is lost, while redirect mode, which has
216
- nowhere else to keep it, fails at the start.
217
-
218
- When the person finishes in the tab the link opened, the `signInWithEmail()` call still waiting in
219
- the original tab eventually times out. Treat that rejection as a cancelled popup: the session is
220
- already established wherever the application called `completeEmailSignInRedirect()`.
221
-
222
- One fragment belongs to one flow, and an application that offers more than one method can call
223
- every completion at startup, in any order:
286
+ Both come back as `#codeMitra` and `#stateMitra`, and are completed by the same
287
+ `completeEmailSignInRedirect()` at startup. The message that page sends carries a
288
+ link too, which opens a **new tab** that never saw the popup, so the pending
289
+ request is written before the popup opens, for the same 10 minutes and under the
290
+ same key. `sessionStorage`, which the SSO redirect uses, is scoped to a single
291
+ tab and cannot answer for another one. Writing the request is best effort for a
292
+ popup: without `localStorage` the popup still signs in and only the completion
293
+ from the link is lost, while redirect mode, which has nowhere else to keep it,
294
+ fails at the start.
295
+
296
+ When the person finishes in the tab the link opened, the `signInWithEmail()`
297
+ call still waiting in the original tab eventually times out. Treat that
298
+ rejection as a cancelled popup: the session is already established wherever the
299
+ application called `completeEmailSignInRedirect()`.
300
+
301
+ #### One fragment, one flow
302
+
303
+ An application that offers more than one method can call every completion at
304
+ startup, in any order:
224
305
 
225
306
  ```typescript
226
307
  const user =
@@ -229,16 +310,18 @@ const user =
229
310
  (await mitra.auth.completeMicrosoftSignInRedirect())
230
311
  ```
231
312
 
232
- A chain like that propagates a rejection: an expired request or a forged fragment on the first
233
- completion keeps the others from running. Wrap each call in `try`/`catch` when the application
234
- should still try the remaining methods after one of them refuses a fragment.
235
-
236
- The one-time state each flow generates names that flow, as in `google.<random>` or
237
- `email.<random>`, and the auth page echoes it verbatim, so a completion recognizes its own
238
- fragment. A fragment from another method returns `null` and leaves the fragment and that other
239
- flow's pending request untouched, whatever this browser has pending. A fragment that does name
240
- this flow but does not match its pending request is rejected as forged, and the fragment is
241
- removed from the URL on the way out, so the rejection is reported once instead of on every
313
+ A chain like that propagates a rejection: an expired request or a forged
314
+ fragment on the first completion keeps the others from running. Wrap each call
315
+ in `try`/`catch` when the application should still try the remaining methods
316
+ after one of them refuses a fragment.
317
+
318
+ The one-time state each flow generates names that flow, as in `google.<random>`
319
+ or `email.<random>`, and the auth page echoes it verbatim, so a completion
320
+ recognizes its own fragment. A fragment from another method returns `null` and
321
+ leaves the fragment and that other flow's pending request untouched, whatever
322
+ this browser has pending. A fragment that does name this flow but does not match
323
+ its pending request is rejected as forged, and the fragment is removed from the
324
+ URL on the way out, so the rejection is reported once instead of on every
242
325
  reload.
243
326
 
244
327
  ## Entities
@@ -331,12 +414,18 @@ session.close()
331
414
 
332
415
  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.
333
416
 
417
+ `session({ create: true, agentId, scope: "ACCOUNT" })` and `agentTasks.create({ agentType, agentId, scope: "ACCOUNT" })` send `scope` in the create body, so the chat runs on the credential the person connected to their own account, the one the IDE and the builder read, instead of the agent's connection. The Copilot honors `ACCOUNT` only for apps listed by flag and answers `ACCOUNT_CREDENTIAL_NOT_ALLOWED` otherwise; a turn without a credential on the account fails with `ACCOUNT_CREDENTIAL_MISSING`. Through `agentTasks.session(...)` those refusals reach the session `error` event with the message and code the Copilot sends; through `agentTasks.create()` and the `agentCredentials` methods they reject the promise with a `MitraApiError` carrying status and code. No platform session is involved: the app token is used as always. Without `scope` nothing changes.
418
+
334
419
  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.
335
420
 
421
+ On the direct channel the message and the interrupt are written on the box socket itself, as the frames the box reads from a client: `{ "type": "message", "content", "agentType"?, "reasoningEffort"? }` and `{ "type": "interrupt" }`. The box asks the Copilot to admit the turn and the Copilot records the history; the admission, its refusal and the turn itself come back on that same socket as the events the session already handles, so a message the box refuses surfaces through the `error` event with the box's code. `POST /copilot/api/v1/tasks/{taskId}/inputs` is the path when there is no box socket: a chat served by the Copilot socket or by SSE, a box socket that is not open at the moment of the send (a drop being redialed included), and every approval answer. A frame written on a socket that closes before the box acknowledges it is not sent again over REST, because the box may already have admitted the turn; the redial replays the box log, as it does for a turn started over REST.
422
+
336
423
  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.
337
424
 
338
425
  API keys and removal accept `ANTHROPIC` or `OPENAI`. OAuth accepts only `ANTHROPIC`; device authorization accepts only `OPENAI`. The facade enforces those producer-supported pairs in TypeScript and at runtime.
339
426
 
427
+ Every `agentCredentials` method takes a trailing `options` with `scope: "ACCOUNT"`, sent as the `scope` query parameter, so the credential is read from or written to the person's own account instead of the app: `startOAuth("ANTHROPIC", { scope: "ACCOUNT" })`, `exchangeOAuth("ANTHROPIC", input, { scope: "ACCOUNT" })`, `list({ scope: "ACCOUNT" })`. The Copilot honors `ACCOUNT` only for apps listed by flag and answers `ACCOUNT_CREDENTIAL_NOT_ALLOWED` otherwise. No platform session is involved: the app token is used as always. Without `options` the request is the same as before.
428
+
340
429
  The browser token roles expose Agent tasks, credential status, and model discovery. Administrative business-Agent CRUD is intentionally not exposed by this adapter because the `USE` app role does not carry `AGENT_*` authority.
341
430
 
342
431
  ## Custom queries
@@ -435,6 +524,12 @@ try {
435
524
  }
436
525
  ```
437
526
 
527
+ A `429` also carries `error.retryAfterSeconds`, read from the `Retry-After`
528
+ header, so the application can tell the person how long to wait instead of
529
+ guessing. It is `null` when the response carries no such delay, which includes
530
+ the case where the gateway does not expose the header to this origin and the one
531
+ where the server answers with an HTTP date rather than a number of seconds.
532
+
438
533
  The transport refuses HTTP redirects. Statuses `307` and `308`, opaque redirects, and responses already marked as redirected fail without replay. The only automatic replay is the single request attempted after reactive `401` recovery with either a refreshed token or a session that changed while the original request was in flight.
439
534
 
440
535
  Before constructing `MitraApiError`, the SDK recursively redacts the token used by the request and credentials in `Bearer` format from the error message, code, details, arrays, values, and object keys. Values under credential fields such as `accessToken`, `refreshToken`, `apiKey`, `password`, `authorization`, `secret`, and `clientSecret` are also replaced with `[REDACTED]`.