@mitralab.io/sdk-core 0.3.0-beta.2 → 0.3.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/CHANGELOG.md CHANGED
@@ -2,6 +2,159 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## 0.3.1
6
+
7
+ Two additions over endpoints of the Copilot, which both need the Copilot with mitra-copilot#549.
8
+ The SDK passes the Copilot's answers through and keeps nothing of its own. It also ships the
9
+ messenger email templates and app sender `main` held as unreleased (the last entries).
10
+
11
+ - `agentCredentials.providers(agentId?, options?)`: the providers the next turn can run on, one
12
+ call to the Copilot's `GET /api/v1/models/providers` (needs `MODEL_READ` and `CREDENTIAL_READ`),
13
+ returned as it comes: one entry per built-in provider and per custom provider, in the catalog's
14
+ order, each with `provider`, `providerName`, `models` and `usage`. `usage` is null on a custom
15
+ provider, before a turn reported a window, on an API key, and when the Copilot could not read
16
+ the subscription: a failed reading does not fail the list. New type `AgentReadyProvider`.
17
+ - `agentTasks.listMessages(id, { before })`: only the rows recorded before the message `before`
18
+ names, sent as the `before` query parameter, so the next page back holds still while new rows
19
+ come. `session.loadOlder()` and `session.hasOlder` sit on it: `loadOlder` reads the page before
20
+ the oldest row `history` holds, with the size `loadHistory` used, puts it before `history` and
21
+ emits `historyLoaded`, resolving with the items it added; `hasOlder` is what the last page read
22
+ said (the Copilot signals more with `totalPages > number + 1`). With nothing older it resolves
23
+ with none and calls nothing. A `before` of another chat, or one that does not exist, is a 404
24
+ that rejects the call. A `loadOlder` still reading when `history` is replaced (a `loadHistory`,
25
+ the turn recovery) resolves with none and adds nothing.
26
+ - `messenger` manages the current app's account email templates on Messenger's
27
+ `/api/v1/email/templates` and `/api/v1/email/template-types` routes: `listEmailTemplates()`,
28
+ `getEmailTemplateType(type)`, `getEmailTemplate(type)`, `upsertEmailTemplate(type, input)`,
29
+ `previewEmailTemplate(type)` and `deleteEmailTemplate(type)`. `EmailTemplateType` is the four
30
+ types an app token may edit: `SIGN_IN`, `SSO_GUIDANCE`, `APP_USER_INVITED` and
31
+ `APP_ACCESS_REQUIRED`.
32
+ - The `appId` comes from `getAppId`, now passed to the messenger module too, never from the
33
+ caller; without it the app calls fail with `SdkCoreConfigurationError` before any request. The
34
+ `PUT` body is built field by field, so an untyped `appId` or `senderIdentityId` is dropped, and
35
+ `textBody` is left out when absent, which clears the saved one.
36
+ - `upsertEmailTemplate` saves and then renders the preview. A preview failure after a successful
37
+ save resolves with `preview: null` and the error in `previewError` instead of rejecting.
38
+ - Messenger refusals (`400` `TEMPLATE_MISSING_VARIABLE` or `VALIDATION_FAILED` for a blank
39
+ subject or HTML body, `403` `ACCESS_DENIED` for another app, no edit access or a type outside the
40
+ four, `404` on a delete without an app row) come from the transport unchanged.
41
+ - In responses `type` is a string, not `EmailTemplateType`: a console token also lists the
42
+ platform's other types, and a type Messenger opens later must not break the list.
43
+ - `messenger` manages the current app's sender on the routes Messenger opens to an app token whose
44
+ person is OWNER or ADMIN of the app's workspace: `listEmailSenders()`
45
+ (`GET /api/v1/email/identities/workspace`), `registerEmailSender({ email, displayName })`,
46
+ `resendEmailSenderVerification(id)`, `confirmEmailSender(id, code)`, `getEmailSettings()` and
47
+ `updateEmailSettings(input)` (`GET` and `PUT /api/v1/email/apps/{appId}/settings`, with the app
48
+ from `getAppId`). Bodies are built field by field; `updateEmailSettings` replaces the whole
49
+ setting, so a field left out or `null` is cleared.
50
+ - `registerEmailSender` does not tell a new address (`201`) from one the person already owned
51
+ (`200`), since the transport does not expose the HTTP status; the returned `status` and
52
+ `ownerConfirmationPending` say whether the code still has to be confirmed.
53
+ - In sender responses `status`, `effectiveSender.source` and `effectiveSender.reason` are strings,
54
+ so a value Messenger adds later does not break the read. The routes an app token may not use
55
+ (the person's full list, rename, delete, sharing with workspaces) stay out of the SDK.
56
+
57
+ ## 0.3.0
58
+
59
+ This release consolidates the work published to npm as `0.3.0-beta.1` and `0.3.0-beta.2` (below)
60
+ with what came after them. The history keeps the format of 0.2.13; against a box that predates
61
+ this release the new functions (queue, steer, background tasks) find nothing to show.
62
+
63
+ - `session.history` is the conversation as it happens: while a turn runs, the box's frames grow it
64
+ with the same items the Copilot records, in the box's order. The question enters where the box
65
+ took it (its turn's `stepStart` or the `steer` that took it in), as the person wrote it, as the
66
+ Copilot records it: after a box that died, the box ran it with the recovered context ahead of it,
67
+ and the live question no longer shows that context. Each stretch of text or reasoning grows on
68
+ the item of its `itemId`. A tool's call and its result are two items, each where it came, as the
69
+ stream sends them and the reload (and 0.2.13) has them; an app that shows a tool as one line
70
+ joins them by `toolId`, as T3's own screen does. The call that spawned a subagent carries its
71
+ last state. An approval or a question T3 asks mid-turn (the box's `approval` and
72
+ `user_input_request` frames) enters as an `approval` or `userInputRequest` item with the frame's
73
+ payload, where it came, as the reload has it; it still reaches the app as a `raw` event too. A
74
+ piece the loaded history already has grows in place, and a frame it already holds
75
+ (a replay after a reconnect or an F5) changes nothing. The reload at the turn's end brings back
76
+ the same pieces in the same order. An app draws `history`, `queue` and `subagents` and keeps
77
+ nothing of its own.
78
+ - A message sent while a turn runs no longer waits in a local queue of the SDK: it goes to the box
79
+ at once, with no mode by default. T3 decides, as its own composer does, steering it into the
80
+ running turn when the provider takes a steer and queueing it otherwise.
81
+ `send(prompt, { mode: "steer" })` takes it into the running turn on purpose (T3 refuses a steer
82
+ while the turn is not running yet) and `send(prompt, { mode: "queue" })` waits in T3's queue for
83
+ a turn of its own. This replaces the `mode: "steer"` that 0.3.0-beta.1 put on every message of
84
+ the direct channel. A box before this release ignores the field and lets T3 decide.
85
+ - `queue` and `queueChange` mirror T3's queue of the chat from the box's `messageQueued` frames (the
86
+ ones with a `position`), with `position`, `queueHeld`, `sequence` and `turnId` as optional
87
+ fields. A message leaves when a turn takes it (`stepStart` or `steer` naming its
88
+ `clientMessageId`), when the box takes it out on a cancel (`messageQueued` with `position: null`
89
+ and `cancelled: true`, no terminal) or when it ends before running; that end rejects only its
90
+ own `sendAndWait` and ends no turn, as in T3: when it is the message that opened this session's
91
+ turn, the session follows its next queued message once the box starts it, or goes back to
92
+ `idle` with no `turnEnd` when none is left. A refusal of a queue command (an `error` with
93
+ `command`) is only emitted as `error` and fails no turn. On the direct channel, a queued
94
+ message's frames and a terminal naming another turn than the followed one never change the turn
95
+ a redial resumes or the one closed as interrupted when the box goes away. The queue methods are
96
+ no longer deprecated and their signatures are unchanged: `removeQueueItem` sends
97
+ `queued-run.cancel`, `editQueueItem` sends `queued-run.edit` and `clearQueue` sends one cancel
98
+ per queued message, on the box channel only. `steerQueueItem(id)` moves a queued message into
99
+ the running turn with T3's `queued-message.promote-to-steer`. A Stop holds the queue, as T3's
100
+ Stop does, until `resumeQueue()` (T3's `queue.resume`).
101
+ - `backgroundTasks` (and the event of the same name) is the work the provider keeps going in the
102
+ background as T3 shows it waiting: a background command, a Monitor, a subagent. It is state, not
103
+ history.
104
+ - `send` returns the `clientMessageId` the message goes out with, the id the box echoes when it
105
+ takes the message; `undefined` for a blank prompt, which is not sent. A caller that ignores the
106
+ return is unaffected. The id also goes in the `POST /inputs` body when the message goes to the
107
+ Copilot, which keeps it and hands it to the box: `send` returns the id on every path.
108
+ - The history is the stream as the Copilot recorded it, one row per piece: `loadHistory` asks for
109
+ every row with `kinds=all` (new `AgentMessageListOptions.kinds`, which `listMessages` sends as a
110
+ query parameter), and each row becomes its own item. A `REASONING` row is an item of the new
111
+ kind `reasoning`; a `SUBAGENT_TEXT` row is an `agent` item with `parentToolId`; a subagent's
112
+ tools are `tool` items; `APPROVAL` and `USER_INPUT_REQUEST` rows are items of the new kinds
113
+ `approval` and `userInputRequest`, with the payload of the box frame as it came (the same that
114
+ reaches the session live as `raw`). History items carry what the Copilot recorded: `sequence`,
115
+ `lastSequence`, `boxLog`, `itemId`, `parentToolId`, `clientMessageId`, `subagent` and `reason`.
116
+ `subagent` has the shape of the box's `subagentUpdate` (`AgentSubagentFrame`, partial); a tool
117
+ item keeps `parentToolId` on `tool` only. A lost turn is recovered with `kinds=all` too, and
118
+ reads its answer only from the chat's own `TEXT`, `ERROR` and `TOOL_USE` rows. A question still
119
+ waiting in the queue is not in the history: it shows in `queue` until its turn starts. Without
120
+ the parameter the Copilot answers the rows 0.2.13 read. Nothing is derived or attached: a frame
121
+ or row without a field leaves it out.
122
+ - The events the session already emits carry, as optional fields, what the box frame named:
123
+ `sequence`, `itemId`, `turnId` (the frame's `lifecycle.turnId`) and `parentToolId` on a
124
+ subagent's text and tools. `delta` and `subagentDelta` also carry `itemDelta`, the frame's piece
125
+ of its item without the separator 0.2.13 joined two text items with. `steered` also carries the
126
+ steered message's `turnId`, `sequence` and `clientMessageId`; `turnEnd` carries the `sequence`
127
+ and `turnId` of its `stepFinish`. `turnStart` opened by the box's `stepStart` carries the `text`
128
+ and `clientMessageId` of the message whose turn it is, with `sequence`, `itemId` and `turnId`:
129
+ the question reaches the app there also when the history does not have it yet.
130
+ - `session({ taskId })` opened in the middle of a run asks the box for the replay from where the
131
+ loaded history ends (the highest `lastSequence ?? sequence` of its newest `boxLog`), with the
132
+ request the redial already makes, before any live frame: what the Copilot has not recorded yet
133
+ reaches the session and nothing the history has comes twice. When the channel's `boxLog` (new
134
+ optional field of `AgentTaskChannel`) is another log than the history's newest, the replay
135
+ starts at the box log's beginning. On the socket the same decision as the redial is made from
136
+ the box's `hello`: a `lastSequence` short of the history's end is another log too. The channel
137
+ cursor starts at the replay point, so a drop in the middle of the replay asks again for what did
138
+ not arrive. A history without `sequence` asks for no replay, as before. A turn the replay opens
139
+ keeps the session `streaming` after the open. The event source gets the cursor as a fifth,
140
+ optional `open` argument, which a concrete SDK may ignore.
141
+ - The queue and subagent state the box sends again after a replay, each a copy of the line that
142
+ said it last with that line's `sequence`, is taken as state: a copy of what the session already
143
+ holds emits no `queueChange` or `subagent` again, and on a fresh open it fills `queue` and
144
+ `subagents`.
145
+ - A `toolResult` that comes after its turn ended (a background subagent settling later, sent by the
146
+ box under the turn that called it) is emitted as that tool's `tool` result. It opens no turn,
147
+ leaves `status` and `content` alone and, on the direct channel, does not mark the chat as in a
148
+ turn: it used to be dropped.
149
+ - A `stepStart` naming a turn while no turn runs starts that turn with its content clean, and
150
+ `accepted` is emitted at the frame that names the message (`stepStart`, `steer` or
151
+ `messageQueued`). A message sent right after a `turnEnd`, before the previous admission was
152
+ heard, no longer takes the text of the turn that ended, and a turn whose frames arrive in one
153
+ tick gives the same events as one whose frames arrive spaced out. A turn the agent opens by
154
+ itself no longer carries the previous turn's text in `turnEnd.content`. A message sent once the
155
+ box took the opening one, before that admission reached the sending code, goes out as a message
156
+ of its own.
157
+
5
158
  ## 0.3.0-beta.2
6
159
 
7
160
  - `messenger.sendEmail({ to, subject, html, text?, cc?, bcc?, replyTo? })` sends an email through
@@ -21,7 +174,7 @@ All notable changes to this project are documented in this file.
21
174
  validator accepts their absence, as a Code Studio that predates them sends, and rejects a value
22
175
  that is not a boolean.
23
176
 
24
- ## 0.3.0
177
+ ## 0.3.0-beta.1
25
178
 
26
179
  Rollout gate: this version goes into the app SDKs (`@mitralab.io/platform-sdk` and the Functions
27
180
  SDK) only once the environment has no old agent box left, that is, no box still running on the
@@ -59,9 +212,19 @@ exact version.
59
212
  event is emitted and the turn and the messages waiting for the box are left alone. With the box
60
213
  channel down, the answer is not sent and an `error` says so; the Copilot does not take it.
61
214
  - A turn whose box went away while the socket redialed (the Copilot points the chat to another
62
- box, or the same address comes back with an empty log) ends as `interrupted` with the text it
63
- had, so the next message opens a turn of its own. A terminal the new box sends for that turn
64
- is ignored.
215
+ box, the same address comes back with an empty log, or the box's `hello` names another T3
216
+ thread or a log short of the session's cursor) ends as `interrupted` with the text it had, so
217
+ the next message opens a turn of its own. A terminal the new box sends for that turn is
218
+ ignored. On the socket, once the box said which thread it serves, the redial asks for the
219
+ replay only after the new box's `hello`: behind the dev proxy every box of a chat has the same
220
+ address, and asking a new box for the old cursor ended the next message's turn as an empty
221
+ `interrupted`. On the socket, the new box is then replayed from the start of its log, which
222
+ may already hold the start of the next message's turn; over HTTP the stream still opens from
223
+ the sequence the Copilot reported.
224
+ - A box `stepFinish` whose `lifecycle` names no turn no longer ends a turn whose `turnId` the
225
+ session already got from the box. A box asked to replay past its log sends such a terminal for
226
+ the turn of a box that is gone; it used to end the running turn as an empty `interrupted` and
227
+ the real terminal right after it was ignored.
65
228
  - The box's `steer` frame marks where T3 took a message into the running turn, with no turn of
66
229
  its own: the session answers that message with the running turn and emits the new `steered`
67
230
  event with its `text` and `messageId`, for the app to show it at that point. The frame also
@@ -69,7 +232,9 @@ exact version.
69
232
  into a turn another client opened follows that turn from the `steer` on.
70
233
  - A turn whose `sendAndWait` already gave up on `timeoutMs` or `signal` is still closed from the
71
234
  history when the stream drops: the recovery no longer stops with the waiter, and the session
72
- does not stay `streaming` forever.
235
+ does not stay `streaming` forever. A `sendAndWait` that gives up before the message went out,
236
+ while the task or the box channel is still on its way, no longer drops it: the message goes
237
+ out and the session follows its turn.
73
238
  - A turn the session closes from the history after the stream dropped closes only on the row
74
239
  that ends it: the agent row carrying the turn's usage, or an `ERROR` row. The Copilot writes a
75
240
  turn's rows while it runs, so the first new row was often a comment from the middle of the
@@ -91,8 +256,9 @@ exact version.
91
256
  `progress`, `startedAt`, `endedAt` (epoch ms) and `childThreadId` from the box's
92
257
  `subagentUpdate` frame; an update with no status keeps the one before. Frames of the child
93
258
  thread, marked with `parentToolId`, come as `subagentDelta` and `subagentTool` and never touch
94
- the chat's turn: they open none, end none, admit no message, stay out of `content` and do not
95
- change the redial. `stopSubagent(subagentId)` stops one over the box channel; without it an
259
+ the chat's turn: they open none, end none, admit no message and do not change the redial. Their
260
+ text and tools also reach `delta`, `content` and `tool` (with `parentToolId`), as they did in
261
+ 0.2.13, so an app that only bumps the version keeps seeing them. `stopSubagent(subagentId)` stops one over the box channel; without it an
96
262
  `error` says so and nothing goes out. `AgentTaskInput` gains `mode` and `subagent.stop`,
97
263
  `AgentToolEvent` gains `parentToolId`, and `AgentSubagent` and `AgentSubagentStatus` are
98
264
  exported.
package/README.md CHANGED
@@ -67,7 +67,7 @@ const { data: tasks, hasMore } = await core.entities.getTable("Task").list({ lim
67
67
  - `integration`, `integrationAdmin`, `integrationResources` e `integrationTemplates`: chamadas a APIs externas e a configuração delas.
68
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
69
  - `apps`, `context`, `agents`, `agentConnections`, `agentCredentials`, `members`, `imports`, `dataSources` e `auth`: o app em si, a configuração de agentes e os demais recursos.
70
- - `messenger`: `notify` avisa o usuário autenticado e `sendEmail` manda e-mail com o remetente do app.
70
+ - `messenger`: `notify` avisa o usuário autenticado, `sendEmail` manda e-mail com o remetente do app, `listEmailTemplates`, `getEmailTemplateType`, `getEmailTemplate`, `upsertEmailTemplate`, `previewEmailTemplate` e `deleteEmailTemplate` cuidam dos templates de e-mail de conta do app, e `listEmailSenders`, `registerEmailSender`, `resendEmailSenderVerification`, `confirmEmailSender`, `getEmailSettings` e `updateEmailSettings` cuidam do remetente dele.
71
71
  - `resolveApiKeyToken`, `readTokenAppId` e `tokenAuthorizesApp`: contrato da troca de API key por token, para o SDK que autentica por chave.
72
72
 
73
73
  ## Configuração
@@ -77,7 +77,7 @@ const { data: tasks, hasMore } = await core.entities.getTable("Task").list({ lim
77
77
  | `transports.auth`, `dataManager`, `functions`, `integration` | sim | um `Transport` para cada serviço |
78
78
  | `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` |
79
79
  | `transports.publicFunctions` | não | transporte anônimo de `publicFunctions`, sem `Authorization` nem `X-App-Id` |
80
- | `getAppId` | não | devolve o app fixado pelo seu SDK; usado por `context` |
80
+ | `getAppId` | não | devolve o app fixado pelo seu SDK; usado por `context` e pelos templates e configurações de e-mail do `messenger` |
81
81
  | `functions.executeInvocationType` | não | `sync` ou `async` em `functions.execute`; sem valor, vale o padrão do servidor |
82
82
  | `functions.emptyInput` | não | `empty-object` manda `{ "input": {} }` quando não há input; `omit-body` não manda corpo |
83
83
  | `errors` | não | `SdkCoreErrorFactory` para o seu SDK lançar as próprias classes no lugar de `SdkCoreConfigurationError` e `SdkCoreResponseError` |
@@ -97,12 +97,19 @@ const { data: tasks, hasMore } = await core.entities.getTable("Task").list({ lim
97
97
  - O Core não repete requisição nem renova token. Se o seu transporte repetir, repita só o que não grava.
98
98
  - `publicFunctions` precisa de um transporte sem credencial. O Core não usa o transporte autenticado no lugar dele.
99
99
  - `sendEmail({ to, subject, html, text?, cc?, bcc?, replyTo? })` não tem `from`: o Messenger usa o remetente do app do token. Por isso só o backend do app manda e-mail, com o token trocado pela API key ou o token da Server Function; token de usuário final do app recebe `403`. `to`, `cc` e `bcc` são listas com um endereço por item. Os limites ficam no Messenger e chegam como erro do seu `Transport`: `400` acima do limite de destinatários dele somando os três campos e `429` acima da cota diária do app, com o header `Retry-After` e `retry_after_seconds` no corpo.
100
+ - Templates de e-mail: os métodos do `messenger` cobrem os quatro tipos de conta que o app reescreve com o próprio token (`EmailTemplateType`: `SIGN_IN`, `SSO_GUIDANCE`, `APP_USER_INVITED` e `APP_ACCESS_REQUIRED`). O `appId` vem do `getAppId`, sem argumento de quem chama; sem ele, os métodos do app falham com `SdkCoreConfigurationError` antes da requisição. O Messenger aceita o token de app quando ele é do mesmo app e tem edição no app (`FUNCTION_WRITE`). `listEmailTemplates()` traz a linha do app e a da plataforma (`platformDefault: true`), então um tipo pode vir duas vezes; `getEmailTemplate(type)` devolve a do app ou, sem ela, a da plataforma. `getEmailTemplateType(type)` lista as variáveis, usadas como `$nome`; toda variável obrigatória precisa estar no assunto ou no HTML. `upsertEmailTemplate(type, { subject, htmlBody, textBody? })` substitui o template inteiro (sem `textBody`, o texto salvo antes some) e devolve `{ template, preview }`; se só o preview falhar, a promise resolve com `preview: null` e o erro em `previewError`, porque o template já está salvo. O preview mostra o template salvo (ou o da plataforma) com os valores de exemplo do catálogo; ele não prova qual HTML sai no envio, porque isso depende do remetente do app e da política de marca. `deleteEmailTemplate(type)` volta ao texto da plataforma. As recusas chegam como erro do seu `Transport`, com o `error_code` do Messenger: `400` `TEMPLATE_MISSING_VARIABLE` (variável obrigatória faltando) ou `VALIDATION_FAILED` (assunto ou HTML em branco), `403` `ACCESS_DENIED` (outro app, sem edição no app ou tipo fora dos quatro) e, no delete sem versão do app, `404`. Na resposta, `type` vem como string: com token de console a lista traz também os outros tipos da plataforma.
101
+ - Remetente do app: com token de app, o Messenger só atende quando o token tem edição no app (`FUNCTION_WRITE`) e a pessoa do token é OWNER ou ADMIN do workspace do app, senão `403` `ACCESS_DENIED`; com o IAM fora do ar, `503` `TENANT_ROLE_UNAVAILABLE`. `listEmailSenders()` lista os endereços disponíveis no workspace do token. `registerEmailSender({ email, displayName })` cadastra o endereço em nome da pessoa e já o deixa disponível no workspace do app; endereço que já é da pessoa volta como está gravado, disponível também, e endereço de outra pessoa é `409` `SENDER_EMAIL_TAKEN`; domínio da plataforma é `422` `SENDER_DOMAIN_RESERVED` e acima do limite de endereços da pessoa, `422` `SENDER_IDENTITY_LIMIT_REACHED`. O retorno não diz se o endereço foi criado ou reaproveitado, porque o Messenger distingue só pelo status HTTP (`201` ou `200`) e o `Transport` não o repassa: o que decide o passo seguinte é o `status` e o `ownerConfirmationPending` do endereço. O cadastro manda à caixa do endereço o link da AWS e um código de 6 dígitos; `confirmEmailSender(id, code)` confirma o código que a pessoa leu (`422` `SENDER_CONFIRMATION_INVALID` com código errado ou vencido, e a quinta falha invalida o código) e `resendEmailSenderVerification(id)` manda de novo o link da AWS enquanto a AWS não verificou o endereço e um código novo só enquanto a pessoa ainda não confirmou um (`429` `RATE_LIMITED` antes de 60 segundos, `400` `IDENTITY_ALREADY_VERIFIED` em endereço verificado). Nesses dois, endereço fora do workspace do app ou de outra pessoa é `404`, e código fora do formato de 6 dígitos é `400` `VALIDATION_FAILED`. `getEmailSettings()` e `updateEmailSettings({ senderIdentityId?, displayName?, replyTo? })` leem e substituem a configuração do app do `getAppId`; o `PUT` substitui tudo, então campo ausente ou `null` é apagado. O `senderIdentityId` aceita endereço `PENDING`, que só passa a assinar quando vira `VERIFIED`; endereço fora do workspace é `404` e endereço `FAILED` é `422` `SENDER_IDENTITY_FAILED`. `effectiveSender` mostra o From que vale agora: o e-mail só sai pelo endereço do app quando ele está `VERIFIED` e disponível no workspace, senão sai pela marca, com o motivo em `reason`. `status`, `source` e `reason` vêm como string, para um valor novo do Messenger não quebrar a leitura. Listar todos os endereços da pessoa, renomear, apagar e mudar o workspace de um endereço ficam no console e fora do SDK.
100
102
  - `sendAndWait` com `timeoutMs` ou `signal` só para de esperar; o turno continua no servidor. Para interromper, chame `cancel()`. A sessão continua acompanhando esse turno: se o canal cair depois do prazo, ela ainda fecha o turno pelo histórico, como faz com um `send`. Pelo histórico, o turno só fecha na linha que o termina: a do agente com o uso do turno, ou uma linha `ERROR`. As linhas que o Copilot grava com o turno rodando e a resposta atrasada da pergunta anterior não fecham nada. O stream do Copilot repete o turno em andamento a partir do que o histórico dele tem; o que a sessão já viu, pelo `sequence` da box, não sai de novo.
101
103
  - `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`. Mensagem mandada depois do `cancel()`, com o stop ainda sem resposta, sai como qualquer outra; a box espera o turno parado terminar e dá a ela um turno próprio, e o `sendAndWait` dela resolve com esse turno. Turno parado que a sessão fecha pelo histórico termina com `reason` `interrupted`.
102
- - Toda mensagem sai na hora, com ou sem turno rodando; a sessão não guarda fila. Com turno rodando, a box coloca a mensagem dentro do turno em andamento (steering nativo do provedor), põe na fila do provedor para um turno próprio, ou dá a ela um turno próprio se o turno já acabou; o `sendAndWait` de cada mensagem resolve com o turno que a respondeu. No canal direto ela vai pelo socket com `mode: "steer"` (sem ele, a box põe a mensagem na fila do T3) e um `clientMessageId`, que a box devolve no frame que a aceita (`stepStart` ou `messageQueued`, este sem o prazo de 35 s). Quando o T3 entrega a mensagem ao turno em andamento, a box marca o ponto com um frame `steer`, sem turno novo: a sessão emite `steered` com `text` e `messageId`, para o app mostrar a mensagem ali, e o `turnEnd` daquele turno responde a ela. Se o turno acabar antes, ela ganha turno próprio, que abre com `stepStart`. O `clientMessageId` também volta no `error` que a recusa, que rejeita só aquela mensagem. Com o socket reconectando, ou sem canal direto, vai ao Copilot (`POST /inputs`), que a guarda como pendente enquanto a box liga. A mensagem mandada com turno rodando leva `agentType` e `reasoningEffort` para a box, que não troca o modelo do turno em andamento e os usa se a mensagem virar turno próprio; só quando vai ao Copilot com turno rodando eles são tirados, porque o Copilot reinicia a sessão viva para outro modelo. Recusa do Copilot com status de erro rejeita aquela mensagem e emite `error`. Falha no envio rejeita o `sendAndWait` e emite `error`; mensagem que ainda não saiu quando a sessão fecha é rejeitada e não é enviada. `queue`, `editQueueItem`, `removeQueueItem`, `clearQueue` e `queueChange` continuam na API só por compatibilidade, marcados como deprecated: a fila é sempre vazia, os métodos não fazem nada e o evento não é emitido.
103
- - Subagentes: o evento `subagent` traz `subagentId`, `toolId` (o `toolId` do `tool` que o criou), `status` (os do T3: `pending`, `running`, `waiting`, `completed`, `failed`, `cancelled`, `interrupted`, `idle`; quando o T3 não manda status, fica o anterior), `progress`, `startedAt`, `endedAt` (epoch ms) e `childThreadId`; `session.subagents` guarda o último estado de cada um. A conversa do subagente vem em `subagentDelta` e `subagentTool`, com `parentToolId`, e nunca entra em `delta`, `content` nem no ciclo do turno do chat. `stopSubagent(subagentId)` para só ele e deixa o turno seguir; vai só pelo canal direto, e sem ele sai um `error` e nada é enviado.
104
+ - Toda mensagem sai na hora, com ou sem turno rodando; a sessão não guarda fila. Com turno rodando, a box coloca a mensagem dentro do turno em andamento (steering nativo do provedor), põe na fila do provedor para um turno próprio, ou dá a ela um turno próprio se o turno já acabou; o `sendAndWait` de cada mensagem resolve com o turno que a respondeu. No canal direto ela vai pelo socket sem `mode` por padrão, e o T3 decide como no composer dele: entra no turno em andamento quando o provedor aceita steer, ou espera na fila do T3. `send(prompt, { mode: "steer" })` pede o steer de propósito (o T3 recusa enquanto o turno ainda não está rodando) e `send(prompt, { mode: "queue" })` pede a fila; `steerQueueItem(id)` leva um item da fila para o turno em andamento e `resumeQueue()` retoma a fila que o Stop segurou. A mensagem leva também um `clientMessageId`, que a box devolve no frame que a aceita (`stepStart` ou `messageQueued`, este sem o prazo de 35 s). O `send` devolve esse `clientMessageId` (ou `undefined` para texto em branco, que não sai). Quando o T3 entrega a mensagem ao turno em andamento, a box marca o ponto com um frame `steer`, sem turno novo: a sessão emite `steered` com `text` e `messageId`, para o app mostrar a mensagem ali, e o `turnEnd` daquele turno responde a ela. Se o turno acabar antes, ela ganha turno próprio, que abre com `stepStart`. O `clientMessageId` também volta no `error` que a recusa, que rejeita só aquela mensagem. Com o socket reconectando, ou sem canal direto, vai ao Copilot (`POST /inputs`) com o mesmo `clientMessageId`, que o Copilot guarda com a mensagem pendente enquanto a box liga e entrega à box, que o devolve igual. A mensagem mandada com turno rodando leva `agentType` e `reasoningEffort` para a box, que não troca o modelo do turno em andamento e os usa se a mensagem virar turno próprio; só quando vai ao Copilot com turno rodando eles são tirados, porque o Copilot reinicia a sessão viva para outro modelo. Recusa do Copilot com status de erro rejeita aquela mensagem e emite `error`. Falha no envio rejeita o `sendAndWait` e emite `error`; mensagem que ainda não saiu quando a sessão fecha é rejeitada e não é enviada. A sessão não guarda fila própria: `queue` e `queueChange` mostram a fila do T3 que a box informa com `messageQueued` (só os que têm `position`), de qualquer cliente do chat, com `id` (o `clientMessageId`), `text`, `position`, `queueHeld`, `sequence` e `turnId`. A mensagem sai da fila quando um turno a pega (`stepStart` ou `steer` com o mesmo `clientMessageId`), quando a box a tira da fila por um `queued-run.cancel` (`messageQueued` com `position: null` e `cancelled: true`, sem `stepFinish`) ou quando ela termina antes de rodar; a saída sem turno rejeita só o `sendAndWait` dela e não mexe no turno em andamento. Como no T3, cancelar um item da fila só tira aquele item: nenhum turno termina por isso. Se ele era a mensagem que abriu o turno desta sessão, ainda esperando atrás do turno de outro cliente, a sessão segue a próxima mensagem dela na fila quando a box a começa, ou volta a `idle` se não sobrou nenhuma, sem `turnEnd`. Frame de mensagem da fila nunca troca o turno que o canal acompanha para reconectar. `removeQueueItem(id)` manda `queued-run.cancel`, `editQueueItem(id, text)` manda `queued-run.edit` e `clearQueue()` manda um `queued-run.cancel` por item; a fila muda quando a box responde, não antes. A recusa de um desses comandos chega como `error` com `command` (`queued-run.cancel` ou `queued-run.edit`): a sessão só emite o `error`, a mensagem fica onde está e nenhum turno falha. Os três vão só pelo canal direto; sem ele sai um `error` e nada é enviado. Depois do replay a box manda de novo a fila e os subagentes como estão, com o `sequence` da linha que os disse por último: o que a sessão já tem não sai de novo em `queueChange` nem em `subagent`, e numa abertura nova isso preenche `queue` e `subagents`.
105
+ - Subagentes: o evento `subagent` traz `subagentId`, `toolId` (o `toolId` do `tool` que o criou), `status` (os do T3: `pending`, `running`, `waiting`, `completed`, `failed`, `cancelled`, `interrupted`, `idle`; quando o T3 não manda status, fica o anterior), `progress`, `startedAt`, `endedAt` (epoch ms) e `childThreadId`; `session.subagents` guarda o último estado de cada um. A conversa do subagente vem em `subagentDelta` e `subagentTool`, com `parentToolId`, e não abre nem fecha o turno do chat. Como na 0.2.13, o texto dela também entra em `delta` e `content`, e as ferramentas também saem em `tool`, com `parentToolId`. O resultado de subagente em segundo plano que termina depois do turno dono chega como `tool` de fase `result` com o `toolId` da chamada, sem abrir turno nem mexer em `status` e `content`. `stopSubagent(subagentId)` para só ele e deixa o turno seguir; vai só pelo canal direto, e sem ele sai um `error` e nada é enviado.
106
+ - Peças e ordem: cada evento que já existe leva, como campos opcionais, o que o frame da box trouxe: `sequence` (a ordem do log da box), `itemId` (o id do item no T3), `turnId` (o `lifecycle.turnId`) e, no texto e nas ferramentas de subagente, `parentToolId`. O `delta` (e o `subagentDelta`) traz também `itemDelta`, o pedaço do item como a box mandou: igual ao `delta`, menos no primeiro pedaço de um item de texto que vem depois de outro, em que o `delta` começa com o separador de linha dupla que a 0.2.13 usava para juntar os dois. Quem desenha por item usa `itemDelta`. O `steered` traz também o `turnId` da mensagem (o `id` do item dela no histórico), `sequence` e `clientMessageId`; o `turnEnd` traz o `sequence` e o `turnId` do `stepFinish`. O item do `history` traz o que o Copilot gravou: `sequence` (o do primeiro pedaço da peça, igual ao do evento ao vivo), `lastSequence` (o do último pedaço, só quando a peça veio em mais de um), `boxLog` (qual log da box conta o `sequence`; box que sobe sem o log recomeça), `itemId`, `parentToolId`, `clientMessageId` na pergunta, `subagent` na ferramenta que criou o subagente e `reason` na linha que fechou o turno. O `subagent` tem o formato do frame `subagentUpdate` da box, sem conversão. Na ferramenta, o `parentToolId` fica em `tool.parentToolId`. O histórico é o streaming gravado, uma linha por peça: o `loadHistory` pede todas as linhas com `kinds=all` e cada linha vira um item, como veio. Linha `REASONING` vira item `reasoning` (raciocínio, com `itemId` e, no do subagente, `parentToolId`); linha `SUBAGENT_TEXT` vira item `agent` com `parentToolId`; ferramenta de subagente é item `tool` com `tool.parentToolId`; linha `APPROVAL` vira item `approval` e linha `USER_INPUT_REQUEST` vira item `userInputRequest`, os dois com o `payload` do frame da box como veio (o mesmo que chega ao vivo como evento `raw`). Ao vivo, os frames `approval` e `user_input_request` entram no `history` como esses mesmos itens, na posição em que vieram, igual ao recarregado. A recuperação de turno perdido também pede `kinds=all`, para o `history` seguir com todas as peças, e lê a resposta só das linhas do próprio chat (`TEXT`, `ERROR` e `TOOL_USE` sem `parentToolId`). Com `kinds=all`, a pergunta que ainda espera na fila não vem no histórico: ela aparece em `queue` até o turno dela começar. O `turnStart` aberto pelo `stepStart` da box traz o `text` e o `clientMessageId` da mensagem daquele turno, com `sequence`, `itemId` e `turnId`: é ali que o app mostra a pergunta, também quando o histórico ainda não a tem (F5 logo depois do envio). Sem o parâmetro, o Copilot devolve só as linhas que a 0.2.13 lia. A SDK só repassa: não ordena, não agrupa e não deduz nada. Frame ou linha sem o campo deixa o campo de fora.
107
+ - Turno e tempo de entrega: quem decide se a mensagem entra no turno em andamento ou ganha turno próprio é a box, não o tempo local da SDK. Um `stepStart` com `turnId` sem turno rodando abre o turno com o `content` limpo, e o `accepted` sai no frame que nomeia a mensagem. Frames que chegam juntos num tick dão os mesmos eventos que frames espaçados.
104
108
  - Pergunta do agente no meio do turno: o T3 pode pedir uma resposta à pessoa. O pedido chega como evento `raw` de tipo `user_input_request`, com o item do T3 no `payload` (perguntas e `requestId`); o turno fica esperando, sem prazo da SDK. Responda com `session.respondUserInput(requestId, answers, attachmentsByQuestionId?)`, que vai direto para a box. Se a box recusar a resposta, sai um `error` e o turno continua; com o canal direto fora (reconectando ou chat sem box), a resposta não é enviada e sai um `error` dizendo isso, para o app mandar de novo depois do `channelConnected`.
109
+ - Provedores e uso: `agentCredentials.providers(agentId?, options?)` devolve os provedores em que o próximo turno pode rodar, como o Copilot monta numa chamada só (`GET /api/v1/models/providers`, com `MODEL_READ` e `CREDENTIAL_READ`): um por provedor nativo e um por provedor personalizado de `listModels(agentId)`, na ordem do catálogo, cada um com `provider`, `providerName` (o nome do personalizado, `null` no nativo), `models` e `usage` (a mesma leitura de `usage(provider)`, só nos nativos). A SDK devolve a lista como veio. `usage` vem `null` no provedor personalizado, sem janela reportada, com chave de API e quando o Copilot não conseguiu ler a assinatura: a falha dessa leitura não derruba a lista. Com `agentId`, os modelos são os da conexão do agente e a leitura continua sendo a do login da pessoa. Precisa do Copilot com a mitra-copilot#549; um Copilot sem a rota responde 404, que rejeita a chamada.
110
+ - Conversa anterior: `agentTasks.listMessages(id, { before })` lê só as linhas gravadas antes da mensagem `before` (o id dela), então a página de trás não anda quando chegam linhas novas. `session.hasOlder` diz se o Copilot tem linhas antes da linha mais antiga do `history`, pela última página lida (a do `loadHistory` também), e `session.loadOlder()` lê a página de trás dela com o tamanho que o `loadHistory` usou e põe antes do `history`, na ordem da box. Resolve com os itens que acrescentou (nenhum quando não há mais, sem chamar o Copilot) e emite `historyLoaded`. Um `loadOlder` que ainda estava lendo quando o `history` foi trocado (um `loadHistory`, a recuperação de turno) descarta o que leu; a recuperação relê as linhas mais novas e o `loadOlder` volta a ler a partir delas. O Copilot diz que há mais quando a página tem outra depois dela (`totalPages > number + 1`), e responde 404 a um `before` de outra conversa ou que não existe, que rejeita a chamada. Precisa do Copilot com a mitra-copilot#549; um Copilot sem ela ignora o `before` e devolve as linhas mais novas.
105
111
  - Portão de rollout da 0.3.0: ela só entra nas SDKs de app (`platform-sdk` e SDK de Functions) quando o ambiente tiver zero box antiga (template do fork `experimental`). A box antiga trata a mensagem do meio do turno como início de turno novo, zera o uso e a identidade do turno, e nada disso aparece como erro. A SDK não distingue box antiga de box nova; o portão é o bump nas SDKs de app, que fixam a versão exata desta.
112
+ - Abrir o chat no meio de uma run (F5): o `session({ taskId })` carrega o histórico e pede à box o replay a partir de onde ele termina, o maior `lastSequence` (ou `sequence`, quando a linha não traz `lastSequence`) do `boxLog` mais novo, com o mesmo pedido que o redial já faz e antes de qualquer frame ao vivo. O que o Copilot ainda não gravou chega no replay, e nada do histórico vem duas vezes. No socket, a decisão é a mesma do redial, pelo `hello` da box: se o `boxLog` do canal for outro que o do histórico (o Copilot sobe o `boxLog` quando a box troca de thread) ou o `lastSequence` do `hello` for menor que esse ponto, o log é outro e o replay começa do início dele. No HTTP, decide só pelo `boxLog`, antes de abrir o stream. O cursor do canal começa no ponto do replay, então uma queda no meio dele pede de novo só o que faltou. Histórico sem `sequence` não pede replay, como antes.
106
113
  - O `open()` do seu `eventSource` só deve resolver depois que o stream estiver conectado, para nenhum evento do turno se perder.
107
114
 
108
115
  ## Desenvolvimento
@@ -24,6 +24,18 @@ publishes.
24
24
 
25
25
  ## Versions
26
26
 
27
+ - `0.3.1` is the `0.3.0` parity surface with `agentCredentials.providers()`, the `before` option of
28
+ `agentTasks.listMessages()`, `session.loadOlder()` and the messenger email templates, which the
29
+ parity cases do not cover. Same
30
+ parity cases; the version exists so a consumer pinning the package can pin a corpus with the same
31
+ number.
32
+
33
+ - `0.3.0` is the stable release of the `0.3.0-beta.2` surface with the agent session that follows
34
+ T3: the live `history`, the queue mirrored from the box, `steerQueueItem`, `resumeQueue` and
35
+ `backgroundTasks`, which the parity cases do not cover. Same parity cases; the version exists so a
36
+ consumer pinning the stable package can pin a corpus with the same number. Its directory was
37
+ committed before the betas and was never published, so this release ships it as it is.
38
+
27
39
  - `0.3.0-beta.2` is the `0.3.0-beta.1` parity surface republished with `messenger.sendEmail()` and the
28
40
  `emailLoginEnabled` and `passwordLoginEnabled` fields of `apps.update()`, which the parity cases do
29
41
  not cover. Same parity cases; the version exists so a consumer pinning the package can pin a corpus
@@ -34,11 +46,6 @@ publishes.
34
46
  corpus with the same number. `0.3.0-beta.0` shipped the same code without its own corpus and has
35
47
  no entry here.
36
48
 
37
- - `0.3.0` is the `0.2.13` parity surface republished with the agent session that holds no
38
- messages: every message goes out at once and the queue API is deprecated and always empty.
39
- Same parity cases; the version exists so a consumer pinning the package can pin a corpus with
40
- the same number.
41
-
42
49
  - `0.2.13` is the `0.2.12` parity surface republished with the occupied context of the chat:
43
50
  `contextTokens` and `contextWindow` on `AgentTurnUsage`, which the parity cases do not cover.
44
51
  Same parity cases; the version exists so a consumer pinning the package can pin a corpus with
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "contract": "SDK-PARITY-001",
3
- "current": "0.3.0-beta.2",
3
+ "current": "0.3.1",
4
4
  "versions": [
5
5
  {
6
6
  "version": "0.1.0",
@@ -135,6 +135,11 @@
135
135
  "version": "0.3.0-beta.2",
136
136
  "path": "v0.3.0-beta.2/sdk-parity.json",
137
137
  "sha256": "0bc945032e37eddd4418dc5178af404975c38da27f35d31e8a13f2fda77cffd1"
138
+ },
139
+ {
140
+ "version": "0.3.1",
141
+ "path": "v0.3.1/sdk-parity.json",
142
+ "sha256": "c5ca69f7aeba83bad0dbc3828e859a114053037c489fed4d4412317dd1515ada"
138
143
  }
139
144
  ]
140
145
  }