@mitralab.io/platform-sdk 1.4.1 → 1.5.0-beta.1

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/README.md CHANGED
@@ -3,19 +3,17 @@
3
3
  [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=mitra-platform-sdk&metric=alert_status&token=28d7be14b66d6f88d706347e2418af5ea39ab3e9)](https://sonarcloud.io/summary/new_code?id=mitra-platform-sdk)
4
4
  [![Coverage](https://sonarcloud.io/api/project_badges/measure?project=mitra-platform-sdk&metric=coverage&token=28d7be14b66d6f88d706347e2418af5ea39ab3e9)](https://sonarcloud.io/summary/new_code?id=mitra-platform-sdk)
5
5
 
6
- JavaScript and TypeScript SDK for browser applications built on the Mitra Platform. Applications generated by Code Studio use this package to authenticate users, access Data Manager entities, execute Server Functions and custom queries, call integrations, and run live Agent tasks.
6
+ SDK JavaScript e TypeScript para apps de browser feitos na Mitra: login da pessoa, dados do app, Server Functions, queries, integrações e chats de agente. Para código que roda dentro de uma Server Function, use [`@mitralab.io/functions-sdk`](https://www.npmjs.com/package/@mitralab.io/functions-sdk).
7
7
 
8
- The browser transport uses standard Web APIs only, including `fetch`, `WebSocket`, `ReadableStream`, `AbortController`, browser storage, `URL`, `Proxy`, `crypto`, and `atob`. Shared contracts and API modules come from `@mitralab.io/sdk-core`, without bringing browser authentication into the Core package.
9
-
10
- ## Installation
8
+ ## Instalação
11
9
 
12
10
  ```bash
13
11
  npm install @mitralab.io/platform-sdk
14
12
  ```
15
13
 
16
- Node.js 18 or newer is required for development and server-side tooling. The runtime application must provide the browser Web APIs used by the SDK.
14
+ Roda no browser, com as APIs dele (`fetch`, `WebSocket`, `localStorage`). Para desenvolver, Node 18 ou mais novo. Publicado em ESM e CommonJS, com tipos.
17
15
 
18
- ## Quick start
16
+ ## Início rápido
19
17
 
20
18
  ```typescript
21
19
  import { createClient } from "@mitralab.io/platform-sdk"
@@ -23,542 +21,92 @@ import { createClient } from "@mitralab.io/platform-sdk"
23
21
  export const mitra = createClient({
24
22
  appId: import.meta.env.VITE_MITRA_APP_ID,
25
23
  apiUrl: import.meta.env.VITE_MITRA_API_URL,
26
- onError: (error) => console.error(error.status, error.code, error.message),
27
24
  })
28
25
 
29
26
  await mitra.init()
30
- ```
31
-
32
- `init()` resolves the application's public Code Studio configuration, including nullable
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
36
- Platform 1.x compatibility flow; native Entities and Custom Queries resolve the current app through
37
- the authenticated request. Call `init()` during application startup before the compatibility
38
- sign-up method needs `allowSignup` or the login screen needs `emailLoginEnabled`.
39
-
40
- ## Configuration
41
-
42
- | Field | Required | Description |
43
- |---|---|---|
44
- | `appId` | yes | ID of the published Code Studio application. |
45
- | `apiUrl` | yes | Base URL of the Mitra API gateway. |
46
- | `authPageUrl` | no | Absolute URL of `sdk-auth.html`. Falls back to `window.__mitraEnv.authPageUrl`, then `/sdk-auth.html` on the `apiUrl` origin. |
47
- | `onError` | no | Global callback for API errors. |
48
-
49
- The client derives service endpoints from `apiUrl`: `/iam`, `/data-manager`, `/functions`, `/integration`, `/copilot`, and `/code-studio`.
50
27
 
51
- ## Boundary
52
-
53
- The Platform SDK owns:
54
-
55
- - browser Google and Microsoft SSO, browser email sign-in, logout, and session refresh
56
- - trusted session adoption for the embedded app preview
57
- - session persistence in `localStorage`
58
- - auth-state listeners
59
- - proactive token refresh before authenticated native requests
60
- - one retry after reactive `401` recovery with the current session
61
- - browser HTTP transport and public application initialization
62
- - the Copilot WebSocket and HTTP/SSE streams an Agent chat falls back to, and the offline outbox for its prompts
63
-
64
- `@mitralab.io/sdk-core` owns the shared entities, custom queries, Functions, integrations, Agent task lifecycle and the direct channel to the chat's box, `auth.me`, safe paths, and structural response validation. Server Function code should use `@mitralab.io/functions-sdk` instead of this browser SDK.
65
-
66
- ## Authentication
67
-
68
- ```typescript
69
- const user = await mitra.auth.signInWithGoogle({ mode: "popup" })
70
-
71
- const unsubscribe = mitra.auth.onAuthStateChange((currentUser) => {
72
- console.log(currentUser?.email)
73
- })
74
-
75
- mitra.auth.signOut("/login")
76
- unsubscribe()
77
- ```
78
-
79
- 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.
80
-
81
- 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.
82
-
83
- ### Signing in as a process
84
-
85
- Google and Microsoft SSO both need a person to complete a redirect. A process that runs on its own -
86
- a cron, a background collector, another service - signs in with an api key created in
87
- **Settings -> API keys**:
88
-
89
- ```typescript
90
- const mitra = createClient({ appId, apiUrl, apiKey: process.env.MITRA_API_KEY })
91
-
92
- await mitra.auth.signInWithApiKey()
93
- ```
94
-
95
- Which key to create depends on what the process does. A **Business** key reaches the published
96
- product: read and write records, run queries, execute functions and integrations. A **Developer**
97
- key adds authoring. An **Administrator** key belongs to a workspace rather than a product; the SDK
98
- issues this app's token from it, and the platform decides on that call what the key's owner
99
- actually reaches here, so the key never widens anyone's access.
100
-
101
- This session is not written to storage and carries no refresh token. The key does not expire and is
102
- revoked by deleting it, so renewing means signing in again rather than holding a second secret.
103
-
104
- **Server runtimes only.** In a browser the key would be served to every visitor inside the bundle,
105
- so the method refuses to run when a `window` exists.
106
-
107
- An embedded preview can adopt the app-scoped session it receives from the platform without exchanging it:
108
-
109
- ```typescript
110
- mitra.auth.setSession({ accessToken, refreshToken })
111
- await mitra.auth.checkAuth()
112
- ```
113
-
114
- Proactive and reactive callers share one in-flight refresh. Successful refresh rotates and persists both tokens and updates the legacy session bridge without calling `auth.me()` or notifying public auth-state listeners. A refresh response that arrives after sign-out or after another login/session replacement is discarded and cannot restore or overwrite that newer state. Network failures, `408`, `429`, and `5xx` responses preserve the current session; the original HTTP request proceeds with the current token so a later `401` can use the reactive fallback. `auth.me()` also preserves that retained session when the fallback refresh is transient. Other IAM `4xx` responses are definitive and clear the session.
115
-
116
- JWT decoding is not user authentication. It schedules refresh and prevents cross-app session adoption. Every decodable access and refresh token must contain `app_id` exactly equal to the client's configured `appId`; opaque tokens are kept for rollout compatibility and remain validated by the server.
117
-
118
- Custom WebSocket or Server-Sent Events boundaries can refresh explicitly before connecting:
119
-
120
- ```typescript
121
- const fresh = await mitra.auth.ensureFreshSession(30_000)
122
-
123
- if (!fresh) {
124
- // A required refresh failed. The SDK may still retain the session after a
125
- // transient failure, but this boundary can choose whether to connect.
28
+ if (!mitra.auth.isAuthenticated) {
29
+ await mitra.auth.signInWithGoogle({ mode: "popup" })
126
30
  }
127
- ```
128
-
129
- `ensureFreshSession()` returns `true` when the token does not need refresh or refresh succeeds. It returns `false` when a required refresh fails, including a transient failure that intentionally preserves the current session.
130
31
 
131
- Google SSO uses a popup by default. The SDK opens `sdk-auth.html`, validates the popup source, origin, and one-time state, exchanges the returned code directly with IAM, stores both tokens, and fetches the current user:
132
-
133
- ```typescript
134
- const user = await mitra.auth.signInWithGoogle({ mode: "popup" })
32
+ const { data: tasks } = await mitra.entities.Task.list({ sort: "-created_at", limit: 10 })
135
33
  ```
136
34
 
137
- The public Google options contain only `mode`. Account creation and locale are producer concerns, so the SDK does not send `create` or `language` to IAM. During rollout, the popup also accepts the older auth page token response.
138
-
139
- Deprecated `LoginOptions` still preserve `returnTo` and `title` for source compatibility. They are not copied into the new Google API: the legacy runtime never read `title`, did not pass caller `returnTo` into popup login, and hardcoded the current URL for redirect login.
35
+ No app gerado pelo Code Studio, `VITE_MITRA_APP_ID` e `VITE_MITRA_API_URL` já vêm preenchidos no build.
140
36
 
141
- Redirect mode stores the one-time state and options in `sessionStorage`. Complete it during application startup before rendering authenticated routes:
37
+ ## O que dá para fazer
142
38
 
143
- ```typescript
144
- const redirectedUser = await mitra.auth.completeGoogleSignInRedirect()
145
-
146
- if (!redirectedUser) {
147
- await mitra.auth.signInWithGoogle({ mode: "redirect" })
148
- }
149
- ```
150
-
151
- Redirect errors are accepted only when `stateMitra` matches the stored one-time state. A missing or mismatched state leaves the fragment and redirect context untouched and does not expose `errorMitra`. The current alpha `sdk-auth.html` error redirect omits `stateMitra`, so those error redirects are intentionally rejected until that producer echoes the state; popup errors already carry state and are unaffected.
39
+ - `auth`: login com Google (`signInWithGoogle`), Microsoft (`signInWithMicrosoft`) ou código por e-mail, mais `currentUser`, `onAuthStateChange` e `signOut`.
40
+ - `entities.<Tabela>`: `list`, `filter`, `get`, `create`, `bulkCreate`, `update`, `delete` e `deleteMany` nas tabelas do app.
41
+ - `queries.execute(id, params)`: roda uma query salva no app.
42
+ - `functions`: `execute` espera o resultado da Server Function; `executeAsync` devolve a execução para acompanhar com `getExecution` ou parar com `cancelExecution`. `publicFunctions` chama as Functions publicadas como públicas, sem login.
43
+ - `integration.executeByAlias(alias, request)`: chama uma API externa configurada no app. A credencial do provedor fica na Mitra e não passa pelo browser.
44
+ - `agentTasks.session(...)`: chat com agente, com `send`, `sendAndWait`, `cancel` e eventos como `delta`, `turnEnd` e `error`.
45
+ - `agentCredentials`: credenciais de provedor de IA e modelos disponíveis.
152
46
 
153
- Configure the auth page explicitly when it is hosted outside the API gateway origin:
47
+ Login por código no e-mail, para quem monta a própria tela:
154
48
 
155
49
  ```typescript
156
- const mitra = createClient({
157
- appId,
158
- apiUrl,
159
- authPageUrl: "https://app.example.com/sdk-auth.html",
160
- })
50
+ const { receipt } = await mitra.auth.requestEmailCode({ email })
51
+ const user = await mitra.auth.verifyEmailCode({ receipt, code })
161
52
  ```
162
53
 
163
- ### Signing in with email
164
-
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:
54
+ Chat com agente:
169
55
 
170
56
  ```typescript
171
- const { receipt, resendAfterSeconds } = await mitra.auth.requestEmailCode({
172
- email: "person@example.com",
57
+ const chat = mitra.agentTasks.session({ taskId })
58
+ chat.on("delta", ({ delta, kind }) => {
59
+ if (kind === "text") render(delta)
173
60
  })
174
-
175
- const user = await mitra.auth.verifyEmailCode({ receipt, code: "123456" })
176
- ```
177
-
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:
192
-
193
- ```typescript
194
- await mitra.init()
195
-
196
- if (mitra.emailLoginEnabled) {
197
- // render the email field
198
- }
199
- ```
200
-
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
209
-
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:
213
-
214
- ```typescript
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 }
61
+ const { content } = await chat.sendAndWait("Resuma os pedidos de hoje")
62
+ chat.close()
227
63
  ```
228
64
 
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.
65
+ ## Configuração
240
66
 
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 |
67
+ | Campo | Obrigatório | Uso |
250
68
  |---|---|---|
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.
69
+ | `appId` | sim | ID do app no Code Studio |
70
+ | `apiUrl` | sim | URL do API gateway da Mitra |
71
+ | `onError` | não | callback com o `MitraApiError` das falhas de `entities`, `queries`, `functions`, `integration`, `agentTasks` e `agentCredentials`; `init()`, login, `publicFunctions` e falha de rede não passam por ele e são tratados no `catch` de cada chamada |
72
+ | `authPageUrl` | não | URL da página de login da Mitra; sem ela, o SDK descobre sozinho |
73
+ | `apiKey` | não | chave padrão de `auth.signInWithApiKey()`; só em código de servidor, nunca no bundle do browser |
262
74
 
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.
75
+ ## Erros
267
76
 
268
- #### Through the platform page
77
+ Falhas de API lançam `MitraApiError`, com `status`, `code`, `details` e `retryAfterSeconds`. O SDK mascara o token da sessão, credenciais `Bearer` e campos com nome sensível, como `password` ou `apiKey`, em `details`. Texto livre fora disso, como `password=...` dentro de uma mensagem, passa como veio: não trate mensagem e detalhes como saneados antes de mandar para log.
269
78
 
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()
277
- ```
278
-
279
- It opens a popup by default, and redirect mode navigates the current page
280
- instead:
281
-
282
- ```typescript
283
- await mitra.auth.signInWithEmail({ mode: "redirect" })
284
- ```
285
-
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:
305
-
306
- ```typescript
307
- const user =
308
- (await mitra.auth.completeEmailSignInRedirect()) ??
309
- (await mitra.auth.completeGoogleSignInRedirect()) ??
310
- (await mitra.auth.completeMicrosoftSignInRedirect())
311
- ```
312
-
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
325
- reload.
326
-
327
- ## Entities
328
-
329
- ```typescript
330
- type Task = {
331
- id: string
332
- title: string
333
- status: "pending" | "done"
334
- }
335
-
336
- const { data: tasks } = await mitra.entities.getTable<Task>("Task").list({
337
- sort: "-created_at",
338
- limit: 10,
339
- fields: ["id", "title", "status"],
340
- })
341
-
342
- const pending = await mitra.entities.Task.filter({ status: "pending" })
343
- const created = await mitra.entities.Task.create({ title: "New task" })
344
- await mitra.entities.Task.update(created.id, { status: "done" })
345
- await mitra.entities.Task.delete(created.id)
346
- ```
347
-
348
- Table names are case-sensitive and must match the Data Manager table name. Record operations use `/api/v1/tables/{table}/records`. Application and tenant scope come from the authenticated context, not from a data source in the path.
349
-
350
- The native producer does not accept `jdbcConnectionConfigId` or `dataSourceId` on public record requests. The deprecated record helpers still expose their legacy arguments, but there is no native equivalent until Data Manager defines an app-safe backend contract. The SDK does not translate those arguments into query parameters or SQL.
351
-
352
- `update(id, fields)` sends the Data Manager PUT contract, which applies the supplied fields as a partial record update and preserves omitted fields. A separate `patch` alias would duplicate that producer behavior, so the native surface keeps one method.
353
-
354
- ## Server Functions
355
-
356
- ```typescript
357
- const execution = await mitra.functions.execute("function-id", {
358
- orderId: "order-123",
359
- })
360
-
361
- console.log(execution.id, execution.status)
362
- ```
363
-
364
- `execute` sends `X-Invocation-Type: sync` and waits for the terminal result. `executeAsync` sends `async` and returns the initial execution for polling or cancellation.
365
-
366
- The complete native lifecycle is also available. `getExecution` is kept because the Functions producer exposes execution polling and Agent consumers use it:
367
-
368
- ```typescript
369
- const queued = await mitra.functions.executeAsync("function-id", { orderId: "order-123" })
370
- const current = await mitra.functions.getExecution(queued.id)
371
- await mitra.functions.cancelExecution(current.id)
372
- ```
373
-
374
- Public Functions use a separate anonymous transport. It never adds `Authorization` or `X-App-Id`:
375
-
376
- ```typescript
377
- const result = await mitra.publicFunctions.execute("public-function-id", { sku: "A-1" })
378
- const queuedPublic = await mitra.publicFunctions.executeAsync("public-function-id", { sku: "A-1" })
379
- ```
380
-
381
- Public async execution is fire-and-forget. The public API does not expose anonymous polling or
382
- cancellation. Use synchronous `publicFunctions.execute` when the screen needs the result, or the
383
- authenticated `functions.executeAsync` plus `functions.getExecution` flow after login.
384
-
385
- ## Agent tasks and credentials
386
-
387
- The browser-safe Copilot modules call the native service directly. `agentTasks` provides list, read, create, rename, archive, HTTP input, history, and live sessions. These direct primitives match the Copilot producer and MCP contract. Core owns session state, queueing, recovery, reconciliation, and the direct channel to the chat's box; Platform supplies the authenticated Copilot WebSocket/SSE streams a chat falls back to and the offline outbox. `agentCredentials` provides safe credential status, model discovery, API key, OAuth, and device authorization flows. Raw credentials are write-only.
388
-
389
- ```typescript
390
- const credentials = await mitra.agentCredentials.list()
391
- const models = await mitra.agentCredentials.listModels()
392
- const chats = await mitra.agentTasks.list({ archived: false, size: 20 })
393
- ```
394
-
395
- Create a live task lazily on the first message. `agentId` names the business agent the chat belongs to; without it the chat is a plain Copilot chat:
396
-
397
- ```typescript
398
- const session = mitra.agentTasks.session({
399
- create: true,
400
- agentId,
401
- agentType: models[0].agentType,
402
- reasoningEffort: models[0].reasoningOptions[0],
403
- })
404
-
405
- const unsubscribe = session.on("delta", ({ delta, kind }) => {
406
- console.log(kind, delta)
407
- })
408
-
409
- session.send("Analyze this application")
410
- session.respondApproval(true)
411
- await session.cancel()
412
- unsubscribe()
413
- session.close()
414
- ```
415
-
416
- A business agent's chat (`create: true` with an `agentId`) is born on the T3 box (`runtime: "T3"` in the create request) whenever the session can reach the box, over any transport, `http` included, so the first open does not wait for the box to adopt it. A chat without `agentId` is created without `runtime` and never asks for the direct channel: the Copilot refuses T3 outside an agent chat (`RUNTIME_REQUIRES_AGENT_APP`). Pass `runtime: "RUNNER"` or `runtime: "T3"` to decide explicitly.
417
-
418
- `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.
419
-
420
- Open an existing task with `session({ taskId })`. A session on a business agent's chat (a task with an `agentId`) asks the Copilot once where the chat is served (`POST /copilot/api/v1/tasks/{taskId}/channel`) and talks to the box that runs the agent when one is offered; any other chat never asks and stays on the Copilot stream described below. This direct channel lives in `@mitralab.io/sdk-core` (0.2.9 and later); this package passes it the API URL and nothing else, so the rules below are Core's. 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 stream without a republish.
421
-
422
- - **Transport.** `auto`, the default, uses the box socket in the browser. `websocket` uses the box socket. `http` uses the box's HTTP routes next to the socket path (`POST .../api/mitra/chat/messages` to send, `GET .../api/mitra/chat/events` as SSE to read), for browsers or proxies where WebSockets are unavailable; before 1.3.0 it meant the Copilot SSE, which is now only its fallback. A business agent's new chat is created with `runtime: "T3"` so it is born on its box, unless the session names a runtime.
423
- - **Host rule.** The box is followed only when its address is on the API host (proxy mode, `/__ide/<box>/...`) or on a fleet box host over `wss:` (direct mode, `<port>-<box>.e2b.app` or `<port>-<box>.e2b-<fleet>.mitralab.ai`), the same allowlist the gateway trusts on `/__ide`.
424
- - **Fallback, always visible.** When the Copilot offers no box (a `202` or an error), the body has no address, the host is outside the rule, the box cannot be reached, or the box has no HTTP routes, the chat follows the Copilot stream (`/copilot/ws/tasks/{taskId}`, falling back to `/copilot/api/v1/tasks/{taskId}/events` for `auto`) and the session first emits a `raw` event of type `channelDeclined` with `reason` `unavailable`, `body`, `host`, `websocket` or `http_unsupported` (and `host` or `error` when known). A channel request that fails is not reported to the client's global `onError`: it is not an error for the application.
425
- - **Sending.** On the box, the message and the interrupt go to the box itself, as the frames it 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 session emits `accepted` once the box starts the admitted turn, or once the Copilot accepts a REST send; a message the box refuses surfaces through the `error` event with the box's code, and a box that confirms nothing within 35 seconds fails the send. `POST /copilot/api/v1/tasks/{taskId}/inputs` is the path when there is no box wire: a chat on the Copilot stream, a box wire that is down at the moment of the send (a drop being redialed included), and every approval answer. A message whose wire drops before the box answers is not sent again over REST, because the box may already have admitted the turn; the redial replays the box log.
426
- - **Drops.** Opening the box never asks it to replay: what an idle chat missed is history, which the application loads over REST. A box wire that drops in the middle of a turn is redialed with a bounded backoff (1, 2, 4, 8 and 16 seconds) and the replay from the last position seen on that box, so the answer keeps streaming; 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`. The disconnect reaches the session, 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, so the next send reopens the channel. Recovery through persisted history is unchanged.
427
-
428
- 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.
429
-
430
- 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.
431
-
432
- 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.
433
-
434
- 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.
435
-
436
- A custom provider the person adds by API is a credential like the others, managed on `/api/v1/credentials/custom-providers` with the same trailing `options`: `listCustomProviders({ scope: "ACCOUNT" })` returns the person's OpenAI-compatible providers with the API key masked, `createCustomProvider({ name, baseUrl, apiKey, models }, { scope: "ACCOUNT" })` adds one under a name the person chooses and returns the list after creation, and `deleteCustomProvider(id, { scope: "ACCOUNT" })` removes it for good. The API key is write-only and `models` takes 1 to 32 model ids; each joins the catalog `listModels()` returns as `custom/<providerId>/<model>`, and a chat runs on one of them by sending the `agentType` that catalog row returns, the same way a built-in model is chosen. The Copilot requires `scope: "ACCOUNT"` on an app token. The three methods take no provider argument and no provider guard applies.
437
-
438
- The subscription usage, the meters behind the bar the IDE shows for a Claude or ChatGPT login, is readable with no chat open: `usage("ANTHROPIC")` (or `"OPENAI"`, with the same trailing `options`) resolves to `{ harness, observedAt, status, windows: [{ kind, usedPercent, resetsAt, windowSeconds }] }`, the last reading a chat on that credential reported, or `null` while none has. `windows` carries every window the provider reports (Claude: `FIVE_HOUR`, `WEEKLY`, `WEEKLY_OPUS` and any other it sends; Codex: primary and secondary, named by duration) and `status` is the provider's own (Claude: `allowed`, `allowed_warning`, `rejected`). Only a turn on the person's own subscription login, or the agent connection's, reports a window; an API key, a custom provider and the included AI never do. During a turn on the box the session emits the same reading live, in the same shape, as `providerUsage`, and the Copilot keeps it for the next `usage()`:
439
-
440
- ```typescript
441
- session.on("providerUsage", ({ status, windows }) => console.log(status, windows))
442
- const usage = await mitra.agentCredentials.usage("ANTHROPIC")
443
- ```
444
-
445
- 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.
446
-
447
- ## Custom queries
448
-
449
- ```typescript
450
- const result = await mitra.queries.execute("query-id", {
451
- status: "active",
452
- })
453
-
454
- console.log(result.rows, result.affectedRows)
455
- ```
456
-
457
- Custom Query execution sends only `parameters`. Data Manager resolves its Data Source from the
458
- authenticated app, so Queries work without a caller-selected `dataSourceId` and do not depend on
459
- `init()`.
460
-
461
- ## Integrations
462
-
463
- List the current app's saved configs without exposing the Core admin module:
464
-
465
- ```typescript
466
- const configs = await mitra.integration.list({ page: 0, size: 20, sort: "alias,asc" })
467
- ```
468
-
469
- The Integration producer derives the app from the authenticated token, so this list is app-scoped. A listed config carries `templateId: null` when it was created from an inline definition instead of a catalog template.
470
-
471
- Execute a predefined resource:
472
-
473
- ```typescript
474
- const result = await mitra.integration.executeResource("resource-id", {
475
- description: "Notebook",
476
- limit: 10,
477
- })
478
- ```
479
-
480
- Or execute an integration config directly:
481
-
482
- ```typescript
483
- const result = await mitra.integration.execute("config-id", {
484
- method: "GET",
485
- endpoint: "/users",
486
- queryParams: { limit: "10" },
487
- })
488
-
489
- console.log(result.status, result.body)
490
- ```
491
-
492
- An app can also address a saved config by its app-scoped alias:
493
-
494
- ```typescript
495
- const result = await mitra.integration.executeByAlias("billing", {
496
- method: "POST",
497
- endpoint: "/invoices",
498
- body: { customerId: "customer-1" },
499
- })
500
- ```
501
-
502
- Integration credentials are injected by the Integration service. Do not pass provider credentials through browser input.
503
-
504
- ## Legacy surface
505
-
506
- The public surface of `mitra-interactions-sdk` is re-exported from this package so an application can replace the legacy dependency without rewriting its call sites. Runtime re-exports are marked `@deprecated` and name their replacement, or state that no replacement exists yet. Every legacy type is an identity-preserving alias marked as a deprecated compatibility type.
507
-
508
- ```typescript
509
- import { createClient, loginWithGoogleMitra } from "@mitralab.io/platform-sdk"
510
-
511
- export const mitra = createClient({ appId, apiUrl })
512
-
513
- await loginWithGoogleMitra()
514
- console.log(mitra.auth.accessToken)
515
- ```
516
-
517
- Google, Microsoft and e-mail sign-in have native replacements: `mitra.auth.signInWithGoogle`, `mitra.auth.signInWithMicrosoft` and `mitra.auth.signInWithEmail`, each with its `complete...SignInRedirect` counterpart. Agent tasks, Agent credentials, public Functions, entities, custom queries, Function execution, and integrations also have native replacements. Only `loginMitra('mitra')` still has no native equivalent and remains available through the deprecated re-export surface.
518
-
519
- `createClient` configures the legacy SDK with both `baseURL` and `authUrl` set to `${apiUrl}/legacy`, after removing trailing slashes, plus `projectId: appId`. This keeps deprecated calls and legacy login routed through the BFF while the new modules call their native APIs directly. Its `authPageUrl` uses the same precedence as native Google SSO: explicit client config, `window.__mitraEnv.authPageUrl`, then `/sdk-auth.html` on the `apiUrl` origin. Existing query parameters are preserved.
520
-
521
- The bridge shares the session in both directions. A session persisted under `mitra_auth_{appId}` is handed to the legacy SDK at startup; native sign-in, Google SSO, proactive or reactive refresh, manual token changes, and sign-out update its active configuration. Sessions produced by legacy login or refresh are persisted back under the same new storage key. The bridge only propagates sessions the two SDKs produce: it never starts a login and never triggers a refresh of its own.
522
-
523
- The legacy package exposes no sign-out API for deleting the refresh token stored in its private `mitra-session` entry. Native sign-out safely removes both credentials from the active legacy configuration, so deprecated calls cannot authenticate or refresh. A later direct call to `configureSdkMitra` can restore that private persisted refresh token; applications should keep configuration ownership in `createClient` during the migration.
524
-
525
- The legacy SDK does not return a user, so `auth.currentUser` stays empty after a legacy login. Call `mitra.auth.me()` to populate it. Calling `configureSdkMitra` directly replaces the legacy configuration and its refresh hook until the next bridged session change, so it should not be mixed with a client-managed migration.
526
-
527
- ## Errors and request behavior
528
-
529
- API failures throw `MitraApiError`:
79
+ | `status` ou `code` | Quando | O que fazer |
80
+ |---|---|---|
81
+ | `401` | a sessão acabou e não deu para renovar | leve a pessoa ao login de novo |
82
+ | `403` | a pessoa não tem acesso ao recurso | confira as permissões dela no app |
83
+ | `429`, `5xx` | limite de requisições ou falha no servidor | espere `retryAfterSeconds`, quando vier, e repita se a operação puder ser repetida |
84
+ | `INVALID_CONFIGURATION` | argumento inválido, ou `requestEmailCode()` antes de `init()` | corrija o argumento ou chame `init()` no startup |
85
+ | `UNSUPPORTED_AUTH_METHOD` | `signIn` ou `signUp` com senha | use Google, Microsoft ou código por e-mail |
86
+ | `INVALID_CODE` | o código digitado não confere | peça para a pessoa conferir o código |
87
+ | `MAGIC_LINK_EXPIRED`, `MAGIC_LINK_USED`, `MAGIC_LINK_INVALID` | o link do e-mail venceu, já foi usado ou não vale | peça um código novo |
88
+ | `REDIRECT_NOT_ALLOWED` | o servidor respondeu com redirect | confira o `apiUrl` |
89
+ | `INVALID_RESPONSE` | resposta fora do formato esperado | atualize o SDK; se continuar, abra uma issue |
530
90
 
531
- ```typescript
532
- import { MitraApiError } from "@mitralab.io/platform-sdk"
91
+ Falha de rede chega como o erro do próprio `fetch` (`TypeError`), sem passar por `onError`.
533
92
 
534
- try {
535
- await mitra.entities.Task.get("missing-id")
536
- } catch (error) {
537
- if (error instanceof MitraApiError) {
538
- console.error(error.status, error.code, error.message)
539
- }
540
- }
541
- ```
93
+ ## Boas práticas
542
94
 
543
- A `429` also carries `error.retryAfterSeconds`, read from the `Retry-After`
544
- header, so the application can tell the person how long to wait instead of
545
- guessing. It is `null` when the response carries no such delay, which includes
546
- the case where the gateway does not expose the header to this origin and the one
547
- where the server answers with an HTTP date rather than a number of seconds.
95
+ - Chame `await mitra.init()` no startup, antes de montar a tela de login: `allowSignup`, `emailLoginEnabled` e o login por e-mail dependem dele.
96
+ - Com `mode: "redirect"`, chame no startup o `completeGoogleSignInRedirect()`, `completeMicrosoftSignInRedirect()` ou `completeEmailSignInRedirect()` do método que você usa. Cada um devolve `null` quando a URL não é dele. O link do e-mail completa o login no mesmo browser que pediu o código; em outro aparelho, a pessoa digita o código.
97
+ - A sessão fica no `localStorage` do domínio do app, na chave `mitra_auth_{appId}`, e é renovada sozinha antes de vencer. `signOut()` limpa.
98
+ - O SDK só repete uma requisição depois de renovar o token num `401`. Fora isso, quem decide repetir é o app.
99
+ - Nunca coloque API key em código que vai para o browser, nem passe uma em `createClient({ apiKey })` num app de browser: o bundle entrega a chave a quem abrir o app. O `signInWithApiKey()` recusa rodar no browser, mas isso não tira do bundle uma chave escrita nele. Para processo sem pessoa, como cron ou coletor, use `@mitralab.io/functions-sdk` com `createClientFromApiKey`.
548
100
 
549
- 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.
101
+ ## Migração do `mitra-interactions-sdk`
550
102
 
551
- 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]`.
103
+ Os exports do SDK legado continuam neste pacote, marcados `@deprecated`, e dividem a sessão com o cliente novo. Troque a dependência, crie o cliente com `createClient` e substitua as chamadas aos poucos: o aviso de cada export diz o método novo. Não chame `configureSdkMitra` direto, porque o `createClient` já configura o legado.
552
104
 
553
- ## Development
105
+ ## Desenvolvimento
554
106
 
555
107
  ```bash
556
- npm install
108
+ npm ci
557
109
  npm run check
558
110
  ```
559
111
 
560
- Platform `1.1.0-beta.2` targets exactly `@mitralab.io/sdk-core@0.2.0-beta.1`, published on the `beta` dist-tag. The manifest and lock keep the registry spec and its verified integrity, so `npm ci` resolves Core from a clean checkout. To validate against a Core prerelease that is not published yet, point `MITRA_SDK_CORE_TARBALL` at its tarball for the package smoke test. Do not commit a `file:` dependency.
561
-
562
- The build produces ESM, CommonJS, `.d.ts`, and `.d.cts` artifacts. Package checks inspect the public tarball with Are The Types Wrong, install it into an isolated consumer, and validate ESM, CommonJS, and TypeScript resolution.
563
-
564
- See [CHANGELOG.md](CHANGELOG.md) for release history and [LICENSE](LICENSE) for license terms.
112
+ O `check` roda lint, typecheck, testes, build e um smoke test do pacote. A publicação no npm sai do workflow Release.