@mitralab.io/sdk-core 0.2.11 → 0.2.12-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,416 +1,109 @@
1
1
  # Mitra SDK Core
2
2
 
3
- Environment-neutral TypeScript contracts and API modules shared by Mitra JavaScript SDKs.
3
+ Base comum dos SDKs JavaScript da Mitra: tipos e módulos de API que não dependem de ambiente. **App não instala o Core direto.** No browser, use [`@mitralab.io/platform-sdk`](https://www.npmjs.com/package/@mitralab.io/platform-sdk); dentro de uma Server Function, use [`@mitralab.io/functions-sdk`](https://www.npmjs.com/package/@mitralab.io/functions-sdk). Os dois já trazem o Core. Instale este pacote só para escrever um SDK ou adaptador da Mitra para outro runtime.
4
4
 
5
- Most application and Server Function code should install a concrete SDK instead:
6
-
7
- - `@mitralab.io/platform-sdk` for browser applications
8
- - `@mitralab.io/functions-sdk` for Mitra Server Functions
9
-
10
- The core package exists so concrete SDKs build direct backend requests from one
11
- contract. It exposes the API values returned by each service. It does not expose
12
- MCP envelopes, `CallToolResult`, or MCP-formatted text.
13
-
14
- The versioned contract corpus in `contracts/` is the canonical source for the
15
- MCP, JavaScript, and Python capability matrix. Its manifest identifies the
16
- current fixture and pins every packaged version with SHA-256. Core executes all
17
- success operations and response validation. Functions JavaScript inherits those
18
- checks and owns its HTTP adapter cases. Python consumes all case groups because
19
- it does not depend on Core, using a digest-pinned snapshot so tests stay offline.
20
-
21
- ## Boundary
22
-
23
- The package contains:
24
-
25
- - common types and data transfer objects
26
- - safe path segment encoding
27
- - structural response validation
28
- - authentication and app members
29
- - Code Studio apps, files, builds, deploys, versions, and rollback
30
- - schema, records, custom queries, SQL, imports, and Data Sources
31
- - Functions, versions, publishing, rollback, executions, visibility, and secrets
32
- - Function scheduling composed into single-Function create, patch, get, and list
33
- - business agents and workflows
34
- - integration configs, resources, templates, tests, proxying, and executions
35
- - Copilot tasks, messages, credentials and the last subscription window each one reported, models,
36
- and app connections
37
- - an Agent task live-session state machine with bounded queue and `sendAndWait`, and the direct
38
- channel to the chat's box
39
- - Messenger notifications and composed safe app context
40
- - anonymous public Function execution
41
- - a minimal transport interface injected by each concrete SDK
42
-
43
- The package does not contain:
44
-
45
- - `fetch` or any other HTTP implementation, or a WebSocket implementation
46
- - tokens, authorization headers, or environment variables
47
- - login, sign-up, logout, refresh, browser storage, or auth listeners
48
- - retry, redirect, timeout, or client lifecycle policy
49
-
50
- Those concerns stay in the concrete SDK because browser sessions and Server Function runtime credentials have different security and failure semantics.
51
-
52
- ## Agent task live sessions
53
-
54
- Core owns the state machine and the direct channel to the chat's box. A concrete SDK implements
55
- `AgentTaskEventSource`, the Copilot stream a chat falls back to, then composes it with the REST
56
- task module:
57
-
58
- ```typescript
59
- import {
60
- createAgentTaskSessionManager,
61
- withAgentTaskSessions,
62
- type AgentTaskEventSource,
63
- type SdkCore,
64
- } from "@mitralab.io/sdk-core"
65
-
66
- declare const eventSource: AgentTaskEventSource
67
- declare const core: SdkCore
68
-
69
- const sessions = createAgentTaskSessionManager({
70
- tasks: core.agentTasks,
71
- eventSource,
72
- directChannel: { apiUrl: "https://api.mitralab.ai" },
73
- })
74
- const agentTasks = withAgentTaskSessions(core.agentTasks, sessions)
75
- const session = agentTasks.session({ taskId: "task-id", transport: "http" })
76
- const result = await session.sendAndWait("Summarize the app", { timeoutMs: 120_000 })
77
- ```
78
-
79
- The event source must complete `open()` after its streaming handshake, so Core opens the channel
80
- before posting the prompt. Core forwards the session's `auto`, `websocket`, or `http` transport
81
- preference to `open()`; the concrete adapter selects or rejects it. HTTP/SSE has no replay cursor.
82
- During an active turn Core performs one
83
- reconnection and reconciles persisted messages; live deltas across that gap are not guaranteed to
84
- be lossless. Abort and timeout stop the local `sendAndWait` waiter but do not interrupt the remote
85
- turn. Use `cancel()` when interruption is intended.
86
-
87
- **Turn usage.** `turnEnd` and the result of `sendAndWait` carry `usage` (`AgentTurnUsage`) when
88
- the turn's `stepFinish` reported it, on the direct channel and on the Copilot stream alike. The
89
- Agent message that closed a turn carries the same object as `usage` in `listMessages`, and
90
- `loadHistory` keeps it on that `agent` item. `inputTokens` and `outputTokens` are always there;
91
- `reasoningTokens`, `cacheReadTokens`, `cacheCreationTokens`, `model`, `provider`, `costUsd`
92
- (this turn, USD), `costUsdRaw` (the provider session so far) and `costSource` only when the
93
- harness reports them (Codex sends no cost and no cache writes). `inputTokens` is the input
94
- without cache, as in the legacy platform; cache is counted apart in `cacheReadTokens` and
95
- `cacheCreationTokens`. Also optional: `requestCount` and `requests` (`AgentTurnUsageRequest`,
96
- one entry per provider call or per model), `durationMs` (the provider's time, sent by the box
97
- in `stepFinish`, so it shows in the live `turnEnd` and in the history), and `authMode`
98
- (`subscription`, `api_key`, `included_ai`, `custom`, `unknown`, or a newer string passed
99
- through as is) and `requestMessageId`, which only the Copilot's record has: they show in
100
- `listMessages`, `loadHistory` and a recovered turn, never in the live `turnEnd`. A turn or
101
- message without usage has no `usage` field. A value the SDK cannot read is dropped rather than
102
- failing the page or the turn: counts must be non-negative integers, costs finite numbers, and
103
- a bad `requests` item leaves the list.
104
-
105
- ### Direct channel
106
-
107
- The direct channel is on when the concrete SDK passes `directChannel.apiUrl`, and it serves a
108
- business agent's chat, the one with an `agentId`: only those have a box. Any other chat, or any
109
- chat without `apiUrl`, stays on the event source and REST inputs, with no channel request and
110
- no T3 default. A business agent's chat asks the Copilot once where it is served
111
- (`POST /api/v1/tasks/{id}/channel`, through `agentTasks.channel`) and talks to the box that
112
- answers. The box runs the turn; the Copilot hands out the channel, admits every turn and
113
- receives the box log. A new business agent's chat is created with `runtime: "T3"` so it is born
114
- on its box, unless the session names a runtime; the Copilot refuses T3 for any other chat
115
- (`RUNTIME_REQUIRES_AGENT_APP`).
116
-
117
- `session({ taskId })` reads the task before it opens anything, so the same rule holds for an
118
- existing chat: with no `agentId` it never asks for `/channel`; with an `agentId` it asks and the
119
- Copilot decides. A chat the Copilot will not serve on its box (not on T3, answered for example
120
- with `RUNTIME_NOT_T3`) is a raw `channelDeclined` with `reason: "unavailable"` and the Copilot's
121
- message, and the session goes on through the event source and REST inputs, with no `error`
122
- event for the app.
123
-
124
- - **Transport.** `websocket` uses the box socket. `http` uses the box's HTTP routes next to the
125
- socket path: `POST .../api/mitra/chat/messages` to send and `GET .../api/mitra/chat/events`
126
- (SSE, from a sequence) to read, keeping the `grant` and `ticket` query of the channel URL.
127
- `auto` uses the socket when a WebSocket implementation is available and HTTP otherwise, which
128
- is the case of a Serverless Function.
129
- The grant in those URLs lasts 10 minutes and the dev proxy ticket 60 seconds: a 401 or 403 without
130
- an `error_code` on the POST or on opening the stream asks the Copilot for the channel again and
131
- retries once on the fresh URLs; a second rejection is an error. One with an `error_code` is a
132
- refusal and is answered once, as it came.
133
- - **Host rule.** The channel URL carries a grant, so Core only reaches the API gateway host
134
- (`directChannel.apiUrl`, over `wss:` when the API is `https:`) or a fleet box host over `wss:` (`*.e2b.app`,
135
- `*.e2b-<env>.mitralab.ai`), on either transport.
136
- - **Fallback, always visible.** When the Copilot answers 202 or an error (a Copilot without
137
- `/channel`), the body has no `wsUrl`, the host is outside the rule, a `websocket` session has
138
- no WebSocket, the box cannot be reached (a handshake that times out or is refused, a proxy
139
- blocking its host, a network error on the HTTP stream), or the box has no HTTP routes (a 404,
140
- or a stream that is not `text/event-stream`, from a template older than them), the
141
- session stays on the event source and REST inputs and first emits a raw `channelDeclined`
142
- event with `reason` `unavailable`, `body`, `host`, `websocket`, or `http_unsupported`.
143
- - **Runtimes without WebSocket.** Core uses `directChannel.WebSocket` when given, otherwise
144
- `globalThis.WebSocket`; Node 18 and 20 have none, so inject one such as `ws` or let `auto` take
145
- HTTP. The socket type only asks for `readyState`, the four `on*` handlers, `send`, and `close`.
146
- HTTP uses `directChannel.fetch` when given, otherwise `globalThis.fetch`.
147
- - **Admission.** The session counts a message as sent only when the box answers for it: the
148
- `stepStart` frame on the stream, or the 200 of the HTTP POST, both the box starting the turn
149
- the Copilot admitted. The session then emits `accepted`, and from there the turn runs and
150
- reaches the Copilot's log even if this process goes away. A refusal is reported once through
151
- `error`: an `error` frame on the stream, or a POST answered 409 (not admitted), 400 (bad
152
- frame), 413 (too large), 503 (nobody to admit) or 504 (no admission or turn within 30 s), each
153
- with `{error_code, message}`, which rejects `sendAndWait` with `AgentTaskTurnError` carrying
154
- that code and message. A box silent for 35 s with the wire up fails the send; a redial pauses that clock and a successful one
155
- restarts it. Over REST, `accepted` follows the Copilot's 202. A caller that does not
156
- wait for the answer, such as a Serverless Function, awaits `accepted` before it returns;
157
- `sendAndWait` waits for the whole turn.
158
- - **Drops.** A socket or stream lost in the middle of a turn, or while a message waits for
159
- admission, is redialed with backoff (1, 2, 4, 8, 16 s), asking the Copilot for the channel on
160
- each attempt and replaying the box log from the last sequence seen, so an admission that
161
- happened during the drop still arrives. A POST the network lost is not sent again for the same
162
- reason. The raw `channelReconnecting` and `channelConnected` events report the redial. An idle
163
- wire that closes, a socket superseded by another open (4409), a redial that gives up, or a
164
- Copilot that stops offering the channel is a disconnect for the session. Opening never replays
165
- older frames: what an idle chat missed is history.
166
- - Interrupts go to the box too; approvals stay on REST.
167
- - **Status of the HTTP transport.** Not yet proven against a real box. It needs the box HTTP
168
- routes in the t3code-mitra fork (mitralab-dev/t3code-mitra#180, in progress) and, behind the
169
- dev proxy, a gateway route for them: the gateway only routes `.../api/mitra/chat/ws` today.
170
- Until both ship, an `http` session, or an `auto` one without WebSocket, falls back to the
171
- Copilot with `channelDeclined`. The WebSocket transport was proven against a dev box.
172
-
173
- ## Installation
5
+ ## Instalação
174
6
 
175
7
  ```bash
176
8
  npm install @mitralab.io/sdk-core
177
9
  ```
178
10
 
179
- Node.js 18 or newer is required. The package has no runtime dependencies; the direct channel
180
- needs a WebSocket implementation on runtimes without a global one.
11
+ Node 18 ou mais novo. Publicado em ESM e CommonJS, com tipos e sem dependências de runtime.
181
12
 
182
- ## Transport contract
13
+ ## Início rápido
183
14
 
184
- SDK adapters provide one transport per service. A transport receives the service-local path and request options, then returns the parsed response payload.
15
+ Os módulos de API não fazem HTTP: você entrega um `Transport` por serviço, que recebe o path e as opções e devolve o corpo já parseado. Autenticação, headers, timeout e erro HTTP ficam com ele. A exceção é o canal direto dos chats de agente (`directChannel`), que fala com o gateway por WebSocket ou `fetch`, fora do `Transport`.
185
16
 
186
17
  ```typescript
187
- import { createSdkCore, type Transport } from "@mitralab.io/sdk-core"
188
-
189
- declare const iam: Transport
190
- declare const dataManager: Transport
191
- declare const functions: Transport
192
- declare const integration: Transport
193
- declare const codeStudio: Transport
194
- declare const copilot: Transport
195
- declare const messenger: Transport
196
- declare const publicFunctions: Transport
197
-
198
- let appId: string | undefined
18
+ import { createSdkCore, type Transport, type TransportRequestOptions } from "@mitralab.io/sdk-core"
19
+
20
+ const apiUrl = process.env.MITRA_API_URL!
21
+ const accessToken = process.env.MITRA_TOKEN!
22
+ const appId = process.env.MITRA_APP_ID!
23
+
24
+ function fetchTransport(service: string): Transport {
25
+ return {
26
+ async request<T>(path: string, options: TransportRequestOptions = {}): Promise<T> {
27
+ const url = new URL(`${apiUrl}/${service}${path}`)
28
+ for (const [key, value] of Object.entries(options.params ?? {})) {
29
+ for (const item of [value].flat()) {
30
+ if (item !== undefined) url.searchParams.append(key, String(item))
31
+ }
32
+ }
33
+ const headers = new Headers({ "Content-Type": "application/json", ...options.headers })
34
+ headers.set("Authorization", `Bearer ${accessToken}`)
35
+ headers.set("X-App-Id", appId)
36
+ const response = await fetch(url, {
37
+ method: options.method ?? "GET",
38
+ headers,
39
+ body: options.body === undefined ? null : JSON.stringify(options.body),
40
+ redirect: "error",
41
+ })
42
+ if (!response.ok) throw new Error(`Request failed with status ${response.status}`)
43
+ const text = await response.text()
44
+ return (text ? JSON.parse(text) : undefined) as T
45
+ },
46
+ }
47
+ }
199
48
 
200
49
  const core = createSdkCore({
201
50
  transports: {
202
- auth: iam,
203
- dataManager,
204
- functions,
205
- integration,
206
- codeStudio,
207
- copilot,
208
- messenger,
209
- publicFunctions,
51
+ auth: fetchTransport("iam"),
52
+ dataManager: fetchTransport("data-manager"),
53
+ functions: fetchTransport("functions"),
54
+ integration: fetchTransport("integration"),
210
55
  },
211
56
  getAppId: () => appId,
212
- functions: {
213
- executeInvocationType: "sync",
214
- emptyInput: "empty-object",
215
- },
216
57
  })
217
58
 
218
- const { data: tasks } = await core.entities.getTable("Task").list({ limit: 20 })
219
- const context = await core.context.getAppContext()
59
+ const { data: tasks, hasMore } = await core.entities.getTable("Task").list({ limit: 20 })
220
60
  ```
221
61
 
222
- The transport owns URL resolution, authentication, serialization, error parsing, redirects, retries, and timeouts. The core never reads or stores credentials.
62
+ ## O que dá para fazer
223
63
 
224
- List methods return the producer's summary DTO when it differs from the detail
225
- response. Custom Query summaries omit `sql`, Workflow summaries omit
226
- `definition`, and integration resource summaries contain only `id`, `name`,
227
- `method`, and `endpoint`. App, integration template, and template config lists
228
- likewise expose their producer summary DTOs, while their `get` methods return
229
- the complete detail DTOs.
64
+ - `entities`: CRUD nas tabelas do app, por `getTable(nome)` ou `core.entities.<Tabela>`.
65
+ - `queries`, `customQueries`, `sql` e `schema`: queries salvas, SQL parametrizado e estrutura das tabelas.
66
+ - `functions`, `publicFunctions`, `functionsAdmin` e `workflows`: executar e administrar Server Functions e workflows.
67
+ - `integration`, `integrationAdmin`, `integrationResources` e `integrationTemplates`: chamadas a APIs externas e a configuração delas.
68
+ - `agentTasks`, com `createAgentTaskSessionManager` e `withAgentTaskSessions`: chats de agente com `send`, `sendAndWait`, `cancel` e eventos. O gerenciador recebe `tasks`, o `eventSource` do seu SDK e `directChannel`, com o `apiUrl` do gateway e, se quiser, `WebSocket` e `fetch`.
69
+ - `apps`, `context`, `agents`, `agentConnections`, `agentCredentials`, `members`, `messenger`, `imports`, `dataSources` e `auth`: o app em si, a configuração de agentes e os demais recursos.
70
+ - `resolveApiKeyToken`, `readTokenAppId` e `tokenAuthorizesApp`: contrato da troca de API key por token, para o SDK que autentica por chave.
230
71
 
231
- Record list and filter methods preserve the Data Manager envelope with `data`,
232
- `limit`, `skip`, `total`, and `hasMore`. Spring list endpoints from Code Studio,
233
- Functions, Data Manager, and Copilot use stable pagination metadata under
234
- `page`. Integration still returns its legacy flat Spring page metadata, so its
235
- list methods expose `totalElements` at the top level.
72
+ ## Configuração
236
73
 
237
- The complete DTOs preserve producer field names and nullability. This includes
238
- Code Studio app routing, domains, color, plan, version, and timestamps;
239
- Workflow execution scope, trigger, current step, context, and timestamps; and
240
- Integration template login/request schemas, config metadata, and resource
241
- parameter schemas. `apps.build()` returns the `AppDeploy` produced by the build
242
- endpoint. `apps.publish()` continues to return the updated `AppDefinition`.
74
+ | Opção | Obrigatória | Uso |
75
+ | ------------------------------------------------------------ | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
76
+ | `transports.auth`, `dataManager`, `functions`, `integration` | sim | um `Transport` para cada serviço |
77
+ | `transports.codeStudio`, `copilot`, `messenger` | não | sem eles falham com `SdkCoreConfigurationError`, antes de sair a requisição: `apps` (`codeStudio`); `agentTasks`, `agentConnections`, `agentCredentials` e `agents.listModels` (`copilot`); `messenger`. O resto de `agents` usa `functions` |
78
+ | `transports.publicFunctions` | não | transporte anônimo de `publicFunctions`, sem `Authorization` nem `X-App-Id` |
79
+ | `getAppId` | não | devolve o app fixado pelo seu SDK; usado por `context` |
80
+ | `functions.executeInvocationType` | não | `sync` ou `async` em `functions.execute`; sem valor, vale o padrão do servidor |
81
+ | `functions.emptyInput` | não | `empty-object` manda `{ "input": {} }` quando não há input; `omit-body` não manda corpo |
82
+ | `errors` | não | `SdkCoreErrorFactory` para o seu SDK lançar as próprias classes no lugar de `SdkCoreConfigurationError` e `SdkCoreResponseError` |
243
83
 
244
- Code Studio deploys use the producer field names `deployUrl` and
245
- `errorMessage`, together with `appId`, `appVersionId`, `logs`, `durationMs`,
246
- `startedAt`, `finishedAt`, and `createdAt`. Integration execution history uses
247
- `success` rather than a synthetic status and preserves nullable request,
248
- response, error, source, and duration fields.
84
+ ## Erros
249
85
 
250
- Integration configs can be executed by identifier with `integration.execute()`
251
- or by their app-scoped alias with `integration.executeByAlias()`. Both methods
252
- send the proxy request unchanged apart from the required `source: "SDK"` audit
253
- field and validate the same proxy result.
86
+ | Erro | Quando | O que fazer |
87
+ | -------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
88
+ | `SdkCoreConfigurationError` | entrada inválida: path vazio, `deleteMany({})`, transporte opcional ausente, API key ou app vazios | corrija a chamada ou passe o transporte que falta |
89
+ | `SdkCoreResponseError` (`code` `INVALID_RESPONSE`) | resposta de sucesso fora do contrato | confira se o transporte devolve o corpo parseado; se sim, atualize o Core |
90
+ | `AgentTaskTurnError` | o turno do agente foi recusado ou terminou com erro; `code` traz o motivo, quando vem | mostre o erro e deixe a pessoa mandar de novo |
91
+ | erro do seu `Transport` | falha HTTP ou de rede | trate no seu SDK; o Core repassa o erro sem mudar, exceto em `agentCredentials.usage` e `agentConnections.usage`, que devolvem `null` quando o erro traz `code` `CREDENTIAL_USAGE_NOT_FOUND` |
254
92
 
255
- An integration config normally points at a catalog template through `templateId`.
256
- When the provider has no template, `integrationAdmin.create()`,
257
- `integrationAdmin.bulkCreate()`, and `integrationAdmin.testCredentials()` accept
258
- an inline definition instead, in the same shapes the catalog uses:
93
+ ## Boas práticas
259
94
 
260
- ```typescript
261
- await integrationAdmin.create({
262
- alias: "erp-inline",
263
- fieldsSchemaInline: [
264
- { key: "base_url", label: "Base URL", type: "url", required: true },
265
- { key: "access_key_code", label: "Access Key Code", type: "secret", required: true },
266
- { key: "access_key_token", label: "Access Key Token", type: "secret", required: true },
267
- ],
268
- requestConfigInline: {
269
- headers: {
270
- "X-Access-Key-Code": "{{access_key_code}}",
271
- "X-Access-Key-Token": "{{access_key_token}}",
272
- },
273
- credential_rules: null,
274
- },
275
- loginConfigInline: null,
276
- values: { base_url: "https://api.example.com", access_key_code: "...", access_key_token: "..." },
277
- })
278
- ```
279
-
280
- Send `templateId` or the inline definition, never both and never neither. The
281
- Integration service owns that rule and answers 400; Core forwards whatever the
282
- caller sends. Configs created this way report `templateId: null` and echo the
283
- three inline fields back on every config response, with secrets in `config`
284
- masked exactly as they are for template-backed configs.
285
-
286
- Inline fields are authored as `IntegrationFieldSchemaInput`, which makes
287
- `placeholder` and `default` optional because the producer stores an omitted one
288
- as null. Responses keep the strict `IntegrationFieldSchema`, where both
289
- properties are always present.
290
-
291
- `integrationAdmin.list()` is the native equivalent for listing configured
292
- integrations. It calls `GET /api/v1/template-configs` and returns the producer's
293
- paginated `TemplateConfigSummary` values. With an app-scoped token, the
294
- Integration service filters the page to that app.
295
-
296
- `auth`, `dataManager`, `functions`, and `integration` remain required for
297
- backward compatibility. `codeStudio`, `copilot`, and `messenger` are optional;
298
- calling their modules without the corresponding transport fails with a
299
- configuration error before making a request.
300
-
301
- `publicFunctions` is deliberately separate and never falls back to the
302
- authenticated Functions transport. Its adapter must target the Functions public
303
- base URL and must not attach `Authorization` or `X-App-Id`. It calls
304
- `POST /public/v1/functions/{id}/execute` with `X-Invocation-Type: sync` or
305
- `async`. Public async is fire-and-forget because the producer does not expose
306
- anonymous polling. Callers that need a result use public sync execution, or the
307
- authenticated `functions.executeAsync` and `functions.getExecution` methods.
308
-
309
- ## App scope and permissions
310
-
311
- Core accepts app identifiers but does not inspect tokens or implement service
312
- authorization. A concrete app-scoped adapter must fix `appId` to its trusted
313
- runtime value. It must not let caller input select another app. This is
314
- especially important for Code Studio because its alpha endpoints do not enforce
315
- an app claim in every path. `apps.list()` and `apps.create()` are tenant-wide and
316
- are not available to app-scoped tokens.
317
-
318
- `context.getAppContext()` always uses the trusted current app and deliberately
319
- excludes app members. The Server Function token does not have `MEMBER_READ`, so
320
- the composed context must not call IAM's member endpoint. `members` remains a
321
- separate Core module for callers whose token has that permission. Function
322
- secret operations still require their dedicated permissions. Agent tools that
323
- resolve a business `agent_id` and the two tenant-wide app collection operations
324
- are not applicable to an app-scoped token. Messenger delivery also depends on
325
- a configured channel. These are service authorization constraints, not changes
326
- to the remaining Core contracts.
327
-
328
- Custom Query creation accepts optional `isVirtualTable` and `connectionId`
329
- fields and forwards them unchanged to the Data Manager. Omitting
330
- `isVirtualTable` preserves the producer default of `false`; `connectionId` only
331
- selects an external connection for a Virtual Table.
332
-
333
- Custom query execution targets the Data Manager alpha contract and sends only
334
- `parameters`. Data Manager resolves the Data Source from the authenticated app,
335
- so the concrete adapter must use the app-scoped JWT and must not accept a caller
336
- selected Data Source for this operation.
95
+ - Fixe o app no adaptador: `getAppId` e o header `X-App-Id` vêm do valor configurado no seu SDK, nunca de um argumento de quem chama. Aplique as credenciais depois dos headers de `options`, como no exemplo, para que eles não as substituam.
96
+ - O Core não repete requisição nem renova token. Se o seu transporte repetir, repita só o que não grava.
97
+ - `publicFunctions` precisa de um transporte sem credencial. O Core não usa o transporte autenticado no lugar dele.
98
+ - `sendAndWait` com `timeoutMs` ou `signal` só para de esperar; o turno continua no servidor. Para interromper, chame `cancel()`.
99
+ - `cancel()` chamado antes de a box aceitar o prompt espera esse aceite e só então manda o stop; a promise resolve depois disso. Se o prompt não chegar a virar turno, nada é enviado e o status não passa por `cancelled`.
100
+ - O `open()` do seu `eventSource` só deve resolver depois que o stream estiver conectado, para nenhum evento do turno se perder.
337
101
 
338
- ## MCP capability coverage
339
-
340
- [`contracts/v0.2.0-beta.0/mcp-tool-parity.json`](contracts/v0.2.0-beta.0/mcp-tool-parity.json)
341
- maps all 120 `@McpTool` methods from 18 alpha tool classes to the typed Core
342
- surface. Multiplexed MCP tools map to separate SDK methods. Composition and alias
343
- tools record equivalence instead of creating duplicate APIs. Git credentials are
344
- excluded because they are an internal Sandbox endpoint, not an MCP capability.
345
- The deprecated Functions bridge remains owned by `@mitralab.io/functions-sdk`.
346
-
347
- The MCP `bulkUpdateFunctions` tool maps to `functionsAdmin.bulkPatch()` and
348
- `PATCH /api/v1/functions/bulk`, preserving omitted fields. The separate
349
- `functionsAdmin.bulkUpdate()` method remains a full replacement over PUT.
350
- Single-Function create and patch inputs also expose `cronExpression`,
351
- `cronInputJson`, and `cronEnabled` as one composed scheduling unit. On create,
352
- omitting all three creates no schedule; supplying any of them requires a
353
- non-blank `cronExpression`. The new schedule uses `UTC` and starts `ACTIVE`
354
- unless `cronEnabled` is `false`. On patch, null or omitted schedule fields
355
- preserve their stored values, an empty `cronInputJson` object clears the input,
356
- and a blank `cronExpression` removes the schedule. A non-blank expression can
357
- create a missing schedule in `UTC`; `cronEnabled` explicitly pauses or resumes
358
- it. These composed writes require `SCHEDULE_WRITE` and `FUNCTION_EXECUTE` in
359
- addition to the Function write permission.
360
-
361
- Function detail and list responses return all three fields when the caller has
362
- `SCHEDULE_READ`. Without it, all three are null without querying Scheduler. The
363
- same all-null shape represents a Function that has no schedule, so these
364
- responses alone cannot distinguish absence from missing read permission. All
365
- Function bulk create, update, and patch inputs prohibit embedded schedule
366
- fields; their dedicated types omit them. Compose scheduling only through the
367
- single-Function create and patch methods.
368
-
369
- The MCP `FunctionTools.getExecution` operation maps to
370
- `functionsAdmin.getExecution(functionId, executionId)` and its nested Function
371
- execution route. The runtime-only `functions.getExecution(executionId)` remains
372
- available for callers of the separate global execution endpoint.
373
-
374
- Core deliberately exposes no separate schedule facade. The MCP scheduling capability is composed
375
- through the three cron fields on `functionsAdmin.create()` and `patch()`, with state returned by
376
- `get()` and `list()`. This keeps one public Function contract instead of duplicating the Scheduler
377
- producer lifecycle.
378
-
379
- Legacy Git credentials and record operations selected by `jdbcConnectionConfigId` have no native
380
- Core equivalent. Git credential minting is an internal Sandbox operation authenticated between
381
- services, and the public Data Manager records API resolves the app Data Source from the token
382
- without accepting a connection selector. Core does not synthesize either behavior through a BFF
383
- or raw SQL.
384
-
385
- ## Error mapping
386
-
387
- By default, invalid configuration and invalid responses throw `SdkCoreConfigurationError` and `SdkCoreResponseError`. A concrete SDK can inject an `SdkCoreErrorFactory` so these failures keep that SDK's established public error classes.
388
-
389
- ## Development
102
+ ## Desenvolvimento
390
103
 
391
104
  ```bash
392
- npm install
105
+ npm ci
393
106
  npm run check
394
107
  ```
395
108
 
396
- The build produces ESM, CommonJS, `.d.ts`, and `.d.cts` artifacts. Package smoke tests install the generated tarball into a clean consumer and validate both module systems and TypeScript resolution.
397
-
398
- ## Release order
399
-
400
- Core is the producer for the concrete SDK adapters, so it publishes first. For a prerelease
401
- `X.Y.Z-beta.N`, currently `0.2.0-beta.1`:
402
-
403
- 1. Merge the source, the `package.json` version, and the matching contract corpus version to
404
- `main` in the same pull request. The Release workflow bumps nothing.
405
- 2. Run the Release workflow with version `X.Y.Z-beta.N`. It checks that the requested version
406
- already matches `package.json`, runs the full package check, then tags and publishes the
407
- prerelease under npm's `beta` dist-tag.
408
- 3. Confirm `npm view @mitralab.io/sdk-core@X.Y.Z-beta.N version` returns the same version.
409
- 4. Regenerate each adapter lockfile from the npm registry and pin this repository commit in the
410
- adapter's contract-source manifest before publishing that adapter.
411
-
412
- Stable `X.Y.Z` releases use npm's default `latest` dist-tag. The workflow accepts only that stable
413
- form or the prerelease form `X.Y.Z-beta.N`.
414
-
415
- Do not publish an adapter against a local tarball or a `file:` dependency. Tarballs are only for
416
- pre-release validation while the registry artifact does not exist.
109
+ O `check` roda format, lint, typecheck, testes, build, a conferência dos exports e do corpus de contrato em `contracts/`, e um smoke test do pacote. A publicação no npm sai do workflow Release, sempre antes dos SDKs que dependem do Core.
package/dist/index.cjs CHANGED
@@ -4103,6 +4103,8 @@ var CoreAgentTaskSession = class {
4103
4103
  openingPromise = null;
4104
4104
  createPromise = null;
4105
4105
  dispatching = false;
4106
+ // Resolves true once the box admitted the prompt in flight; false when it never became a turn.
4107
+ dispatch = null;
4106
4108
  recoveryUsed = false;
4107
4109
  // Turns the server already ended. A box flushes the text it had buffered for a stopped turn
4108
4110
  // after the interrupted terminal (dev, 2026-09-14); that text must not open a turn of its own.
@@ -4169,6 +4171,7 @@ var CoreAgentTaskSession = class {
4169
4171
  return waiter.promise;
4170
4172
  }
4171
4173
  async cancel() {
4174
+ if (this.dispatch && !await this.dispatch) return;
4172
4175
  if (this._status !== "streaming" && this._status !== "cancelled") return;
4173
4176
  try {
4174
4177
  await this.sendInput({ type: "interrupt" });
@@ -4275,21 +4278,24 @@ var CoreAgentTaskSession = class {
4275
4278
  }
4276
4279
  startDispatch(prompt, options, waiter) {
4277
4280
  this.dispatching = true;
4278
- void this.dispatchSend(prompt, options, waiter).catch((error) => {
4281
+ const dispatch = this.dispatchSend(prompt, options, waiter).catch((error) => {
4279
4282
  waiter?.reject(error);
4280
4283
  this.emitError("Failed to send Agent prompt", error);
4281
4284
  if (this._status === "streaming") this.setStatus("idle");
4282
4285
  this.flushQueue();
4286
+ return false;
4283
4287
  }).finally(() => {
4284
4288
  this.dispatching = false;
4289
+ if (this.dispatch === dispatch) this.dispatch = null;
4285
4290
  if (this._status === "idle") this.flushQueue();
4286
4291
  });
4292
+ this.dispatch = dispatch;
4287
4293
  }
4288
4294
  async dispatchSend(prompt, options, waiter) {
4289
4295
  if (this.openingPromise && !await this.openingPromise) {
4290
4296
  throw new Error("Agent task session could not be opened.");
4291
4297
  }
4292
- if (this.isClosed() || waiter?.settled) return;
4298
+ if (this.isClosed() || waiter?.settled) return false;
4293
4299
  await this.ensureTask();
4294
4300
  const input = {
4295
4301
  type: "message",
@@ -4299,11 +4305,11 @@ var CoreAgentTaskSession = class {
4299
4305
  };
4300
4306
  if (this.isClosed()) {
4301
4307
  await this.sendInput(input).catch(() => void 0);
4302
- return;
4308
+ return false;
4303
4309
  }
4304
- if (waiter?.settled) return;
4310
+ if (waiter?.settled) return false;
4305
4311
  await this.ensureChannel();
4306
- if (this.isClosed() || waiter?.settled) return;
4312
+ if (this.isClosed() || waiter?.settled) return false;
4307
4313
  await this.captureTurnBaseline();
4308
4314
  this._content = "";
4309
4315
  this.recoveryUsed = false;
@@ -4313,7 +4319,9 @@ var CoreAgentTaskSession = class {
4313
4319
  this.activeWaiter = waiter;
4314
4320
  this.setStatus("streaming");
4315
4321
  this.emit("turnStart", {});
4316
- if (await this.sendInput(input)) this.emit("accepted", {});
4322
+ if (!await this.sendInput(input)) return false;
4323
+ this.emit("accepted", {});
4324
+ return true;
4317
4325
  }
4318
4326
  async ensureTask() {
4319
4327
  if (this._taskId) return;
package/dist/index.js CHANGED
@@ -4031,6 +4031,8 @@ var CoreAgentTaskSession = class {
4031
4031
  openingPromise = null;
4032
4032
  createPromise = null;
4033
4033
  dispatching = false;
4034
+ // Resolves true once the box admitted the prompt in flight; false when it never became a turn.
4035
+ dispatch = null;
4034
4036
  recoveryUsed = false;
4035
4037
  // Turns the server already ended. A box flushes the text it had buffered for a stopped turn
4036
4038
  // after the interrupted terminal (dev, 2026-09-14); that text must not open a turn of its own.
@@ -4097,6 +4099,7 @@ var CoreAgentTaskSession = class {
4097
4099
  return waiter.promise;
4098
4100
  }
4099
4101
  async cancel() {
4102
+ if (this.dispatch && !await this.dispatch) return;
4100
4103
  if (this._status !== "streaming" && this._status !== "cancelled") return;
4101
4104
  try {
4102
4105
  await this.sendInput({ type: "interrupt" });
@@ -4203,21 +4206,24 @@ var CoreAgentTaskSession = class {
4203
4206
  }
4204
4207
  startDispatch(prompt, options, waiter) {
4205
4208
  this.dispatching = true;
4206
- void this.dispatchSend(prompt, options, waiter).catch((error) => {
4209
+ const dispatch = this.dispatchSend(prompt, options, waiter).catch((error) => {
4207
4210
  waiter?.reject(error);
4208
4211
  this.emitError("Failed to send Agent prompt", error);
4209
4212
  if (this._status === "streaming") this.setStatus("idle");
4210
4213
  this.flushQueue();
4214
+ return false;
4211
4215
  }).finally(() => {
4212
4216
  this.dispatching = false;
4217
+ if (this.dispatch === dispatch) this.dispatch = null;
4213
4218
  if (this._status === "idle") this.flushQueue();
4214
4219
  });
4220
+ this.dispatch = dispatch;
4215
4221
  }
4216
4222
  async dispatchSend(prompt, options, waiter) {
4217
4223
  if (this.openingPromise && !await this.openingPromise) {
4218
4224
  throw new Error("Agent task session could not be opened.");
4219
4225
  }
4220
- if (this.isClosed() || waiter?.settled) return;
4226
+ if (this.isClosed() || waiter?.settled) return false;
4221
4227
  await this.ensureTask();
4222
4228
  const input = {
4223
4229
  type: "message",
@@ -4227,11 +4233,11 @@ var CoreAgentTaskSession = class {
4227
4233
  };
4228
4234
  if (this.isClosed()) {
4229
4235
  await this.sendInput(input).catch(() => void 0);
4230
- return;
4236
+ return false;
4231
4237
  }
4232
- if (waiter?.settled) return;
4238
+ if (waiter?.settled) return false;
4233
4239
  await this.ensureChannel();
4234
- if (this.isClosed() || waiter?.settled) return;
4240
+ if (this.isClosed() || waiter?.settled) return false;
4235
4241
  await this.captureTurnBaseline();
4236
4242
  this._content = "";
4237
4243
  this.recoveryUsed = false;
@@ -4241,7 +4247,9 @@ var CoreAgentTaskSession = class {
4241
4247
  this.activeWaiter = waiter;
4242
4248
  this.setStatus("streaming");
4243
4249
  this.emit("turnStart", {});
4244
- if (await this.sendInput(input)) this.emit("accepted", {});
4250
+ if (!await this.sendInput(input)) return false;
4251
+ this.emit("accepted", {});
4252
+ return true;
4245
4253
  }
4246
4254
  async ensureTask() {
4247
4255
  if (this._taskId) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mitralab.io/sdk-core",
3
- "version": "0.2.11",
3
+ "version": "0.2.12-beta.0",
4
4
  "description": "Environment-neutral contracts and modules shared by Mitra JavaScript SDKs",
5
5
  "type": "module",
6
6
  "sideEffects": false,