@mitralab.io/sdk-core 0.2.11-beta.0 → 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 +75 -382
- package/contracts/README.md +5 -0
- package/contracts/manifest.json +6 -1
- package/contracts/v0.2.11/sdk-parity.json +2902 -0
- package/dist/index.cjs +14 -6
- package/dist/index.js +14 -6
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,416 +1,109 @@
|
|
|
1
1
|
# Mitra SDK Core
|
|
2
2
|
|
|
3
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
##
|
|
13
|
+
## Início rápido
|
|
183
14
|
|
|
184
|
-
|
|
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
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
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
|
-
|
|
62
|
+
## O que dá para fazer
|
|
223
63
|
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
`
|
|
227
|
-
`
|
|
228
|
-
|
|
229
|
-
|
|
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
|
-
|
|
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
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
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
|
-
|
|
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
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
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
|
-
|
|
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
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
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
|
-
##
|
|
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
|
|
105
|
+
npm ci
|
|
393
106
|
npm run check
|
|
394
107
|
```
|
|
395
108
|
|
|
396
|
-
|
|
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/contracts/README.md
CHANGED
|
@@ -24,6 +24,11 @@ publishes.
|
|
|
24
24
|
|
|
25
25
|
## Versions
|
|
26
26
|
|
|
27
|
+
- `0.2.11` is the stable release of the `0.2.11-beta.0` surface: the agent turn usage in
|
|
28
|
+
`AgentTurnUsage` on `AgentMessage.usage`, on the `agent` item of `loadHistory` and on `turnEnd`
|
|
29
|
+
and `sendAndWait`. Same parity cases; the version exists so a consumer pinning the stable package
|
|
30
|
+
can pin a corpus with the same number.
|
|
31
|
+
|
|
27
32
|
- `0.2.11-beta.0` is the `0.2.10` parity surface republished with the agent turn usage:
|
|
28
33
|
`AgentTurnUsage` on `AgentMessage.usage`, on the `agent` item of `loadHistory` and on `turnEnd`
|
|
29
34
|
and `sendAndWait`, which the parity cases do not cover. Same parity cases; the version exists so
|
package/contracts/manifest.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"contract": "SDK-PARITY-001",
|
|
3
|
-
"current": "0.2.11
|
|
3
|
+
"current": "0.2.11",
|
|
4
4
|
"versions": [
|
|
5
5
|
{
|
|
6
6
|
"version": "0.1.0",
|
|
@@ -100,6 +100,11 @@
|
|
|
100
100
|
"version": "0.2.11-beta.0",
|
|
101
101
|
"path": "v0.2.11-beta.0/sdk-parity.json",
|
|
102
102
|
"sha256": "37f39080f5403d829bd08eba832ec6f5a3916b650e21f7f4a2fa6030f352bde5"
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
"version": "0.2.11",
|
|
106
|
+
"path": "v0.2.11/sdk-parity.json",
|
|
107
|
+
"sha256": "36cdb3f4198079b700022b70e03d9fe75b855ec222f23b3832f25e714650ea7f"
|
|
103
108
|
}
|
|
104
109
|
]
|
|
105
110
|
}
|