@mitralab.io/functions-sdk 0.2.3 → 0.2.4

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,35 @@
2
2
 
3
3
  All notable changes to this project are documented in this file.
4
4
 
5
+ ## 0.2.4
6
+
7
+ Stable release of the 0.2.4-beta.0 line, already on the `beta` tag. This release only moves the
8
+ Core dependency to its stable number, so no runtime behavior in this package changes.
9
+
10
+ - Depend on `@mitralab.io/sdk-core@0.2.9`, the stable release of the 0.2.9-beta.1 surface: the
11
+ chat's direct channel to its box as the Agent session transport, limited to business agent chats.
12
+ - Pin the SDK-PARITY-001 corpus to Core `0.2.9` with its digest and immutable source commit.
13
+
14
+ ## 0.2.4-beta.0
15
+
16
+ - Depend on `@mitralab.io/sdk-core@0.2.9-beta.1`, which takes the chat's direct channel to its box
17
+ as the Agent session transport. Sessions ask the Copilot for the channel and send to the box:
18
+ over its WebSocket, or over its HTTP routes (POST to send, SSE to read) on a runtime without
19
+ one. The Copilot SSE and `POST /inputs` stay as the fallback, announced by a `channelDeclined`
20
+ raw event. Only an agent chat, a task with an `agentId`, goes to the box, also when opened by
21
+ `taskId`; a chat without `agentId` stays on the Copilot and never asks for the channel. New agent
22
+ chats are created with `runtime: "T3"` unless the session names a runtime.
23
+ - Wire the channel to the client's API URL. The box routes use `globalThis.fetch`, never the
24
+ client's `fetch`, so a custom fetch that adds `Authorization` cannot send the token to the box.
25
+ `auto` uses the box WebSocket when the runtime has one and HTTP otherwise, which is the case of
26
+ the Serverless Functions runtime on Node 20. No WebSocket dependency is added.
27
+ - Accept an optional `WebSocket` implementation, such as `ws`, in the client configuration.
28
+ - `transport: "websocket"` no longer rejects: it now means the box socket, and falls back to the
29
+ Copilot SSE with `channelDeclined` when no WebSocket is available.
30
+ - The new `accepted` session event fires when the box admits the turn, so a Function can send,
31
+ await it, and return. `sendAndWait` is unchanged.
32
+ - Pin the SDK-PARITY-001 corpus to Core `0.2.9-beta.1` with its digest and immutable source commit.
33
+
5
34
  ## 0.2.3
6
35
 
7
36
  Stable release of the 0.2.2-beta.0 and 0.2.3-beta.0 line. This release only moves the Core
package/README.md CHANGED
@@ -227,17 +227,22 @@ single-Function methods for composed scheduling.
227
227
  The native SDK deliberately has no separate schedule lifecycle methods. Create, patch, get, and
228
228
  list keep Function state and its composed cron fields in one contract.
229
229
 
230
- ### Live Agent sessions over HTTP
230
+ ### Live Agent sessions
231
231
 
232
- `agentTasks.session()` adds the Core session state machine to the native Copilot task module. The
233
- Functions adapter uses the direct HTTP channel because Server Functions do not provide a browser
234
- WebSocket runtime:
232
+ `agentTasks.session()` adds the Core session state machine to the native Copilot task module.
233
+ Core also owns the direct channel to the chat's box: the session asks the Copilot where the chat
234
+ is served (`POST /copilot/api/v1/tasks/{taskId}/channel`) and then talks to that box, which runs
235
+ the turn. This package only wires the channel to the client's API URL and WebSocket.
236
+
237
+ Only an agent chat, a task with an `agentId`, goes to the box, whether the session creates it or
238
+ opens it with `session({ taskId })`. A chat without `agentId` keeps the Copilot stream and inputs
239
+ as before and never asks for the channel.
235
240
 
236
241
  ```typescript
237
242
  const session = mitra.agentTasks.session({
238
243
  create: true,
244
+ agentId: "agent-id",
239
245
  agentType: "CODEX",
240
- transport: "http",
241
246
  })
242
247
 
243
248
  session.on("delta", ({ delta, kind }) => {
@@ -249,17 +254,74 @@ console.log(result.content)
249
254
  session.close()
250
255
  ```
251
256
 
252
- Existing tasks use `mitra.agentTasks.session({ taskId })`. The adapter opens
253
- `GET /copilot/api/v1/tasks/{taskId}/events` as a Server-Sent Events (SSE) stream before it sends
254
- input to `POST /inputs`. Both calls use the fixed runtime token in `Authorization` plus
255
- `X-App-Id`; credentials are never placed in the URL. `transport: "auto"` and `"http"` use this
256
- channel, while `"websocket"` rejects locally.
257
+ Existing tasks use `mitra.agentTasks.session({ taskId })`. A new agent chat is created on the
258
+ box runtime (`runtime: "T3"`) unless the session names another runtime.
259
+
260
+ `transport` picks how the session tries to reach the box:
261
+
262
+ - `auto`, the default, uses the box WebSocket when the runtime has one and the box HTTP routes
263
+ otherwise: a `POST` per message and a Server-Sent Events (SSE) stream for events.
264
+ - `http` uses the box HTTP routes.
265
+ - `websocket` uses the box WebSocket.
266
+
267
+ Until the box offers the route the session asks for, the session falls back to the Copilot and
268
+ says so with `channelDeclined` (see below). The transport is a preference, not a guarantee.
269
+
270
+ The Serverless Functions runtime runs Node 20, which has no global `WebSocket`, so sessions
271
+ there reach the box over HTTP. Node 22 and newer have one. To use the socket on a runtime without
272
+ it, pass an implementation such as `ws` when you create the client; this package does not depend
273
+ on one:
274
+
275
+ ```typescript
276
+ import WebSocket from "ws"
277
+
278
+ const mitra = createClient({ WebSocket })
279
+ ```
280
+
281
+ The box is reached through the channel URL the Copilot returns, which carries a short-lived
282
+ grant; the runtime token is never sent to the box. The box routes use `globalThis.fetch`, not the
283
+ `fetch` given to the client, so a custom fetch that adds `Authorization` cannot leak the token
284
+ there. Core follows only a channel on the configured
285
+ API host or a Mitra box host. When the Copilot offers no channel, or the offer cannot be followed
286
+ (for example a `websocket` session with no WebSocket available), the session stays on the
287
+ Copilot: it opens `GET /copilot/api/v1/tasks/{taskId}/events` as an SSE stream with the runtime
288
+ token in `Authorization` plus `X-App-Id`, and sends input to `POST /inputs`. That fallback is
289
+ never silent: the session first emits a `raw` event of type `channelDeclined` with the reason.
290
+
291
+ `timeoutMs` also bounds `POST /channel`, which the Copilot holds open while the box boots. A
292
+ short `timeoutMs` can abort that request, and the session then falls back to the Copilot with
293
+ `channelDeclined` reason `unavailable`; leave it unset, or above the box boot time, for agent
294
+ chats. On the Copilot stream, `timeoutMs` applies only while waiting for the SSE response
295
+ headers. The parser ignores `hello` and `ping` keepalives, and a stream silent for 60 seconds counts
296
+ as a disconnect; Core then reconnects once and reconciles persisted messages. The box channel has
297
+ its own handshake, silence, redial, and admission deadlines in Core.
298
+
299
+ #### Send and return
300
+
301
+ A Function does not have to wait for the whole turn. Once the box admits the message, the turn
302
+ runs and is recorded without the Function, so it can send, wait for `accepted`, and return:
303
+
304
+ ```typescript
305
+ export async function handler(input: { taskId: string; prompt: string }) {
306
+ const session = mitra.agentTasks.session({ taskId: input.taskId })
307
+ try {
308
+ await new Promise<void>((resolve, reject) => {
309
+ session.on("accepted", () => resolve())
310
+ session.on("error", ({ code, error }) =>
311
+ reject(new Error(code ? `${code}: ${error}` : error)),
312
+ )
313
+ session.send(input.prompt)
314
+ })
315
+ return { accepted: true }
316
+ } finally {
317
+ session.close()
318
+ }
319
+ }
320
+ ```
257
321
 
258
- When `timeoutMs` is configured, it applies only while waiting for the SSE response headers. Once
259
- the handshake succeeds, the body remains open until the session closes, its abort signal fires, or
260
- the server disconnects. The parser ignores `hello` and `ping` keepalives and forwards `message`
261
- events to the Core session manager. Core performs one reconnect and reconciles persisted messages
262
- after an unexpected disconnect.
322
+ `accepted` fires when the box starts the admitted turn, or after the Copilot's `202` on the
323
+ fallback. A refusal fires `error` instead, and a box that does not answer fails the send after
324
+ 35 seconds. Returning before `accepted` may lose the message.
263
325
 
264
326
  ### App-scoped Code Studio access
265
327
 
@@ -383,8 +445,7 @@ part of this package. Every re-export is the legacy binding itself, unchanged, a
383
445
  `@deprecated` with the new equivalent when one exists. Native raw SQL is available through `sql`;
384
446
  app authoring and Agent runtime modules cover most builder and Agent SDK operations. Builder-specific
385
447
  Git and direct-S3 flows have no one-to-one replacement and remain supported through the legacy
386
- exports. Live Agent sessions have a native HTTP and SSE replacement through
387
- `agentTasks.session()`.
448
+ exports. Live Agent sessions have a native replacement through `agentTasks.session()`.
388
449
 
389
450
  `getGitConfigMitra` remains legacy-only because credential minting is an internal Sandbox POST
390
451
  authenticated between services and is not published for app tokens. The Sandbox already owns Git
@@ -0,0 +1,15 @@
1
+ {
2
+ "contract": "SDK-PARITY-001",
3
+ "version": "0.2.9-beta.1",
4
+ "dependency": {
5
+ "package": "@mitralab.io/sdk-core",
6
+ "version": "0.2.9-beta.1",
7
+ "contractPath": "contracts/v0.2.9-beta.1/sdk-parity.json"
8
+ },
9
+ "sha256": "f0ec4130c399f7102ad20b6dc54ed50da957003d19d3ab811d013ce89b5cde06",
10
+ "source": {
11
+ "repository": "https://github.com/mitralab-dev/mitra-core-sdk",
12
+ "commit": "e16503d5b9055a1ad759ebc061a4f80a1be62ed2",
13
+ "path": "contracts/v0.2.9-beta.1/sdk-parity.json"
14
+ }
15
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "contract": "SDK-PARITY-001",
3
+ "version": "0.2.9",
4
+ "dependency": {
5
+ "package": "@mitralab.io/sdk-core",
6
+ "version": "0.2.9",
7
+ "contractPath": "contracts/v0.2.9/sdk-parity.json"
8
+ },
9
+ "sha256": "aa81d033dc4bf7ccd30d712568e6bccf1319a208e9072c40369a86b090bc5c13",
10
+ "source": {
11
+ "repository": "https://github.com/mitralab-dev/mitra-core-sdk",
12
+ "commit": "2ffae6d251aac3651793ac10ffe1a9203555b29c",
13
+ "path": "contracts/v0.2.9/sdk-parity.json"
14
+ }
15
+ }
package/dist/index.cjs CHANGED
@@ -363,12 +363,7 @@ var AgentTaskSseEventSource = class {
363
363
  constructor(config) {
364
364
  this.config = config;
365
365
  }
366
- async open(taskId, observer, signal, transport) {
367
- if (transport === "websocket") {
368
- throw new MitraConfigurationError(
369
- "WebSocket Agent sessions are not available in the Functions runtime"
370
- );
371
- }
366
+ async open(taskId, observer, signal) {
372
367
  if (signal?.aborted) throw signal.reason ?? new Error("Agent event stream was aborted");
373
368
  const controller = new AbortController();
374
369
  let handshakeTimedOut = false;
@@ -748,7 +743,8 @@ function resolveConfig(config = {}, environment = readDefaultEnvironment()) {
748
743
  appId,
749
744
  ...dataSourceId === void 0 ? {} : { dataSourceId: dataSourceId.trim() },
750
745
  ...timeoutMs === void 0 ? {} : { timeoutMs },
751
- fetch: fetchImplementation
746
+ fetch: fetchImplementation,
747
+ ...config.WebSocket === void 0 ? {} : { WebSocket: config.WebSocket }
752
748
  };
753
749
  }
754
750
 
@@ -829,27 +825,28 @@ var DefaultMitraClient = class {
829
825
  this.agentConnections = core.agentConnections;
830
826
  this.agentCredentials = core.agentCredentials;
831
827
  this.agents = core.agents;
832
- const agentSessionManager = (0, import_sdk_core3.createAgentTaskSessionManager)({
833
- tasks: core.agentTasks,
834
- eventSource: new AgentTaskSseEventSource({
835
- baseUrl: `${config.apiUrl}/copilot`,
836
- accessToken: config.accessToken,
837
- appId: config.appId,
838
- ...config.timeoutMs === void 0 ? {} : { timeoutMs: config.timeoutMs },
839
- fetch: config.fetch,
840
- errors: coreErrors
841
- })
842
- });
843
- this.agentTasks = (0, import_sdk_core3.withAgentTaskSessions)(core.agentTasks, {
844
- session: (options) => {
845
- if (options.transport === "websocket") {
846
- throw new MitraConfigurationError(
847
- "WebSocket Agent sessions are not available in the Functions runtime; use http or auto"
848
- );
828
+ this.agentTasks = (0, import_sdk_core3.withAgentTaskSessions)(
829
+ core.agentTasks,
830
+ (0, import_sdk_core3.createAgentTaskSessionManager)({
831
+ tasks: core.agentTasks,
832
+ eventSource: new AgentTaskSseEventSource({
833
+ baseUrl: `${config.apiUrl}/copilot`,
834
+ accessToken: config.accessToken,
835
+ appId: config.appId,
836
+ ...config.timeoutMs === void 0 ? {} : { timeoutMs: config.timeoutMs },
837
+ fetch: config.fetch,
838
+ errors: coreErrors
839
+ }),
840
+ // Core owns the channel to the box. Without a WebSocket, as in the Functions runtime on
841
+ // Node 20, `auto` reaches the box over HTTP. The box routes use the global fetch, never
842
+ // `config.fetch`: the grant in the channel URL is the box credential, and a custom fetch
843
+ // that adds `Authorization` would send the Function token to the box.
844
+ directChannel: {
845
+ apiUrl: config.apiUrl,
846
+ ...config.WebSocket === void 0 ? {} : { WebSocket: config.WebSocket }
849
847
  }
850
- return agentSessionManager.session(options);
851
- }
852
- });
848
+ })
849
+ );
853
850
  this.apps = appModules.apps;
854
851
  this.auth = core.auth;
855
852
  this.context = core.context;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { AppsModule, AppGetOptions, AppDefinition, AppUpdateInput, AppFiles, AppDeploy, AppPublishOptions, PageOptions, Page, AppVersion, SdkCore, AgentTasksWithSessions, AuthModule } from '@mitralab.io/sdk-core';
2
- export { AgentBulkDeleteResult, AgentConnectionCreateInput, AgentConnectionsModule, AgentCredentialsModule, AgentDefinition, AgentInput, AgentQueueItem, AgentSendAndWaitOptions, AgentSendOptions, AgentSessionTransport, AgentTask, AgentTaskCreateInput, AgentTaskEvent, AgentTaskEventConnection, AgentTaskEventObserver, AgentTaskEventSource, AgentTaskInput, AgentTaskListOptions, AgentTaskTurnError, AgentTasksModule, AgentTasksWithSessions, AgentTurnResult, AgentUpdateItem, AgentsModule, AppColor, AppContext, AppCreateInput, AppDefinition, AppDeploy, AppDomain, AppFiles, AppGetOptions, AppListOptions, AppMember, AppPublishOptions, AppSummary, AppUpdateInput, AppVersion, AppVersionStatus, AppsModule, AuthModule, AuthenticationResult, BatchExecution, BatchStatementResult, BulkUnsubscribeResult, ColumnInput, ConnectionConfig, ConnectionTestResult, ContextModule, CopilotProvider, AgentConnection as CoreAgentConnection, AgentMessage as CoreAgentMessage, AgentModel as CoreAgentModel, AgentTaskSession as CoreAgentTaskSession, AgentTaskSessionEventMap as CoreAgentTaskSessionEventMap, AgentTaskSessionOptions as CoreAgentTaskSessionOptions, AgentTaskSessionStatus as CoreAgentTaskSessionStatus, AgentTimelineItem as CoreAgentTimelineItem, AgentToolEvent as CoreAgentToolEvent, ListTablesOptions as CoreListTablesOptions, CredentialStatus, CustomQueriesModule, CustomQueryDefinition, CustomQueryInput, CustomQuerySummary, CustomQueryUpdateInput, DataSourceBulkItemResult, DataSourceBulkResult, DataSourceCreateInput, DataSourceDbType, DataSourceDefinition, DataSourceInstanceType, DataSourceUpdateInput, DataSourcesModule, DdlStatement, DeviceAuthorization, DmlStatement, EmptyFunctionInput, EntitiesModule, EntitiesProxy, EntityListOptions, EntityTable, ExistingAgentTaskSessionOptions, FunctionBulkCreateInput, FunctionBulkDeleteInput, FunctionBulkDeleteResult, FunctionBulkPatchInput, FunctionBulkPatchItem, FunctionBulkUpdateItem, FunctionCreateInput, FunctionDefinition, FunctionExecution, FunctionListOptions, FunctionPatchInput, FunctionRuntime, FunctionSecrets, FunctionSummary, FunctionUpdateInput, FunctionVersion, FunctionVersionListOptions, FunctionVisibility, FunctionsAdminModule, FunctionsModule, ImportColumnMapping, ImportDefinition, ImportExecution, ImportExecutionListOptions, ImportInput, ImportProcessing, ImportSchedule, ImportSource, ImportTarget, ImportsModule, IntegrationAdminModule, IntegrationConnectionStatus, IntegrationCredentialRule, IntegrationExecution, IntegrationFieldSchema, IntegrationFieldSchemaInput, IntegrationLoginConfig, IntegrationModule, IntegrationProxyMode, IntegrationRequestConfig, IntegrationResource, IntegrationResourceInput, IntegrationResourceParam, IntegrationResourceSummary, IntegrationResourceUpdateInput, IntegrationResourcesModule, IntegrationTemplate, IntegrationTemplateSummary, IntegrationTemplateType, IntegrationTemplatesModule, IntegrationTokenExtraction, InviteAppUserInput, InvocationType, JsonValue, ListTemplateConfigsOptions, MembersModule, MessengerModule, NewAgentTaskSessionOptions, OAuthExchangeInput, OAuthStartResult, Page, PageOptions, PlanPrice, ProviderCredentialStatus, ProxyInput, ProxyResult, PublicFunctionAsyncResult, PublicFunctionResult, PublicFunctionsModule, QueriesModule, QueryResult, SchemaModule, SchemaScope, SchemaTables, SqlModule, TableColumn, TableDefinition, TableForeignKey, TemplateConfig, TemplateConfigBulkItemResult, TemplateConfigBulkResult, TemplateConfigCreateInput, TemplateConfigPage, TemplateConfigSummary, TemplateConfigUpdateInput, Tenant, TestCredentialsInput, User, UserPlan, WorkflowDefinition, WorkflowExecution, WorkflowInput, WorkflowSummary, WorkflowsModule } from '@mitralab.io/sdk-core';
1
+ import { AppsModule, AppGetOptions, AppDefinition, AppUpdateInput, AppFiles, AppDeploy, AppPublishOptions, PageOptions, Page, AppVersion, AgentWebSocketConstructor, SdkCore, AgentTasksWithSessions, AuthModule } from '@mitralab.io/sdk-core';
2
+ export { AgentBulkDeleteResult, AgentConnectionCreateInput, AgentConnectionsModule, AgentCredentialsModule, AgentDefinition, AgentInput, AgentQueueItem, AgentSendAndWaitOptions, AgentSendOptions, AgentSessionTransport, AgentTask, AgentTaskCreateInput, AgentTaskEvent, AgentTaskEventConnection, AgentTaskEventObserver, AgentTaskEventSource, AgentTaskInput, AgentTaskListOptions, AgentTaskTurnError, AgentTasksModule, AgentTasksWithSessions, AgentTurnResult, AgentUpdateItem, AgentWebSocket, AgentWebSocketConstructor, AgentsModule, AppColor, AppContext, AppCreateInput, AppDefinition, AppDeploy, AppDomain, AppFiles, AppGetOptions, AppListOptions, AppMember, AppPublishOptions, AppSummary, AppUpdateInput, AppVersion, AppVersionStatus, AppsModule, AuthModule, AuthenticationResult, BatchExecution, BatchStatementResult, BulkUnsubscribeResult, ColumnInput, ConnectionConfig, ConnectionTestResult, ContextModule, CopilotProvider, AgentConnection as CoreAgentConnection, AgentMessage as CoreAgentMessage, AgentModel as CoreAgentModel, AgentTaskSession as CoreAgentTaskSession, AgentTaskSessionEventMap as CoreAgentTaskSessionEventMap, AgentTaskSessionOptions as CoreAgentTaskSessionOptions, AgentTaskSessionStatus as CoreAgentTaskSessionStatus, AgentTimelineItem as CoreAgentTimelineItem, AgentToolEvent as CoreAgentToolEvent, ListTablesOptions as CoreListTablesOptions, CredentialStatus, CustomQueriesModule, CustomQueryDefinition, CustomQueryInput, CustomQuerySummary, CustomQueryUpdateInput, DataSourceBulkItemResult, DataSourceBulkResult, DataSourceCreateInput, DataSourceDbType, DataSourceDefinition, DataSourceInstanceType, DataSourceUpdateInput, DataSourcesModule, DdlStatement, DeviceAuthorization, DmlStatement, EmptyFunctionInput, EntitiesModule, EntitiesProxy, EntityListOptions, EntityTable, ExistingAgentTaskSessionOptions, FunctionBulkCreateInput, FunctionBulkDeleteInput, FunctionBulkDeleteResult, FunctionBulkPatchInput, FunctionBulkPatchItem, FunctionBulkUpdateItem, FunctionCreateInput, FunctionDefinition, FunctionExecution, FunctionListOptions, FunctionPatchInput, FunctionRuntime, FunctionSecrets, FunctionSummary, FunctionUpdateInput, FunctionVersion, FunctionVersionListOptions, FunctionVisibility, FunctionsAdminModule, FunctionsModule, ImportColumnMapping, ImportDefinition, ImportExecution, ImportExecutionListOptions, ImportInput, ImportProcessing, ImportSchedule, ImportSource, ImportTarget, ImportsModule, IntegrationAdminModule, IntegrationConnectionStatus, IntegrationCredentialRule, IntegrationExecution, IntegrationFieldSchema, IntegrationFieldSchemaInput, IntegrationLoginConfig, IntegrationModule, IntegrationProxyMode, IntegrationRequestConfig, IntegrationResource, IntegrationResourceInput, IntegrationResourceParam, IntegrationResourceSummary, IntegrationResourceUpdateInput, IntegrationResourcesModule, IntegrationTemplate, IntegrationTemplateSummary, IntegrationTemplateType, IntegrationTemplatesModule, IntegrationTokenExtraction, InviteAppUserInput, InvocationType, JsonValue, ListTemplateConfigsOptions, MembersModule, MessengerModule, NewAgentTaskSessionOptions, OAuthExchangeInput, OAuthStartResult, Page, PageOptions, PlanPrice, ProviderCredentialStatus, ProxyInput, ProxyResult, PublicFunctionAsyncResult, PublicFunctionResult, PublicFunctionsModule, QueriesModule, QueryResult, SchemaModule, SchemaScope, SchemaTables, SqlModule, TableColumn, TableDefinition, TableForeignKey, TemplateConfig, TemplateConfigBulkItemResult, TemplateConfigBulkResult, TemplateConfigCreateInput, TemplateConfigPage, TemplateConfigSummary, TemplateConfigUpdateInput, Tenant, TestCredentialsInput, User, UserPlan, WorkflowDefinition, WorkflowExecution, WorkflowInput, WorkflowSummary, WorkflowsModule } from '@mitralab.io/sdk-core';
3
3
  import * as legacy from 'mitra-sdk';
4
4
 
5
5
  type AppScopedAppsModule = AppsModule;
@@ -50,7 +50,17 @@ interface MitraClientConfig {
50
50
  dataSourceId?: string;
51
51
  /** Optional request deadline. By default, the Functions runtime owns operation time limits. */
52
52
  timeoutMs?: number;
53
+ /**
54
+ * fetch for the Mitra API calls, which carry the access token. The Agent box routes never use
55
+ * it: they take `globalThis.fetch`, so a fetch that adds `Authorization` cannot hand the token
56
+ * to the box.
57
+ */
53
58
  fetch?: Fetch;
59
+ /**
60
+ * WebSocket implementation for Agent sessions, such as `ws`, when the runtime has no global one.
61
+ * Without either, Agent sessions reach the box over HTTP.
62
+ */
63
+ WebSocket?: AgentWebSocketConstructor;
54
64
  }
55
65
 
56
66
  interface MitraClient {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { AppsModule, AppGetOptions, AppDefinition, AppUpdateInput, AppFiles, AppDeploy, AppPublishOptions, PageOptions, Page, AppVersion, SdkCore, AgentTasksWithSessions, AuthModule } from '@mitralab.io/sdk-core';
2
- export { AgentBulkDeleteResult, AgentConnectionCreateInput, AgentConnectionsModule, AgentCredentialsModule, AgentDefinition, AgentInput, AgentQueueItem, AgentSendAndWaitOptions, AgentSendOptions, AgentSessionTransport, AgentTask, AgentTaskCreateInput, AgentTaskEvent, AgentTaskEventConnection, AgentTaskEventObserver, AgentTaskEventSource, AgentTaskInput, AgentTaskListOptions, AgentTaskTurnError, AgentTasksModule, AgentTasksWithSessions, AgentTurnResult, AgentUpdateItem, AgentsModule, AppColor, AppContext, AppCreateInput, AppDefinition, AppDeploy, AppDomain, AppFiles, AppGetOptions, AppListOptions, AppMember, AppPublishOptions, AppSummary, AppUpdateInput, AppVersion, AppVersionStatus, AppsModule, AuthModule, AuthenticationResult, BatchExecution, BatchStatementResult, BulkUnsubscribeResult, ColumnInput, ConnectionConfig, ConnectionTestResult, ContextModule, CopilotProvider, AgentConnection as CoreAgentConnection, AgentMessage as CoreAgentMessage, AgentModel as CoreAgentModel, AgentTaskSession as CoreAgentTaskSession, AgentTaskSessionEventMap as CoreAgentTaskSessionEventMap, AgentTaskSessionOptions as CoreAgentTaskSessionOptions, AgentTaskSessionStatus as CoreAgentTaskSessionStatus, AgentTimelineItem as CoreAgentTimelineItem, AgentToolEvent as CoreAgentToolEvent, ListTablesOptions as CoreListTablesOptions, CredentialStatus, CustomQueriesModule, CustomQueryDefinition, CustomQueryInput, CustomQuerySummary, CustomQueryUpdateInput, DataSourceBulkItemResult, DataSourceBulkResult, DataSourceCreateInput, DataSourceDbType, DataSourceDefinition, DataSourceInstanceType, DataSourceUpdateInput, DataSourcesModule, DdlStatement, DeviceAuthorization, DmlStatement, EmptyFunctionInput, EntitiesModule, EntitiesProxy, EntityListOptions, EntityTable, ExistingAgentTaskSessionOptions, FunctionBulkCreateInput, FunctionBulkDeleteInput, FunctionBulkDeleteResult, FunctionBulkPatchInput, FunctionBulkPatchItem, FunctionBulkUpdateItem, FunctionCreateInput, FunctionDefinition, FunctionExecution, FunctionListOptions, FunctionPatchInput, FunctionRuntime, FunctionSecrets, FunctionSummary, FunctionUpdateInput, FunctionVersion, FunctionVersionListOptions, FunctionVisibility, FunctionsAdminModule, FunctionsModule, ImportColumnMapping, ImportDefinition, ImportExecution, ImportExecutionListOptions, ImportInput, ImportProcessing, ImportSchedule, ImportSource, ImportTarget, ImportsModule, IntegrationAdminModule, IntegrationConnectionStatus, IntegrationCredentialRule, IntegrationExecution, IntegrationFieldSchema, IntegrationFieldSchemaInput, IntegrationLoginConfig, IntegrationModule, IntegrationProxyMode, IntegrationRequestConfig, IntegrationResource, IntegrationResourceInput, IntegrationResourceParam, IntegrationResourceSummary, IntegrationResourceUpdateInput, IntegrationResourcesModule, IntegrationTemplate, IntegrationTemplateSummary, IntegrationTemplateType, IntegrationTemplatesModule, IntegrationTokenExtraction, InviteAppUserInput, InvocationType, JsonValue, ListTemplateConfigsOptions, MembersModule, MessengerModule, NewAgentTaskSessionOptions, OAuthExchangeInput, OAuthStartResult, Page, PageOptions, PlanPrice, ProviderCredentialStatus, ProxyInput, ProxyResult, PublicFunctionAsyncResult, PublicFunctionResult, PublicFunctionsModule, QueriesModule, QueryResult, SchemaModule, SchemaScope, SchemaTables, SqlModule, TableColumn, TableDefinition, TableForeignKey, TemplateConfig, TemplateConfigBulkItemResult, TemplateConfigBulkResult, TemplateConfigCreateInput, TemplateConfigPage, TemplateConfigSummary, TemplateConfigUpdateInput, Tenant, TestCredentialsInput, User, UserPlan, WorkflowDefinition, WorkflowExecution, WorkflowInput, WorkflowSummary, WorkflowsModule } from '@mitralab.io/sdk-core';
1
+ import { AppsModule, AppGetOptions, AppDefinition, AppUpdateInput, AppFiles, AppDeploy, AppPublishOptions, PageOptions, Page, AppVersion, AgentWebSocketConstructor, SdkCore, AgentTasksWithSessions, AuthModule } from '@mitralab.io/sdk-core';
2
+ export { AgentBulkDeleteResult, AgentConnectionCreateInput, AgentConnectionsModule, AgentCredentialsModule, AgentDefinition, AgentInput, AgentQueueItem, AgentSendAndWaitOptions, AgentSendOptions, AgentSessionTransport, AgentTask, AgentTaskCreateInput, AgentTaskEvent, AgentTaskEventConnection, AgentTaskEventObserver, AgentTaskEventSource, AgentTaskInput, AgentTaskListOptions, AgentTaskTurnError, AgentTasksModule, AgentTasksWithSessions, AgentTurnResult, AgentUpdateItem, AgentWebSocket, AgentWebSocketConstructor, AgentsModule, AppColor, AppContext, AppCreateInput, AppDefinition, AppDeploy, AppDomain, AppFiles, AppGetOptions, AppListOptions, AppMember, AppPublishOptions, AppSummary, AppUpdateInput, AppVersion, AppVersionStatus, AppsModule, AuthModule, AuthenticationResult, BatchExecution, BatchStatementResult, BulkUnsubscribeResult, ColumnInput, ConnectionConfig, ConnectionTestResult, ContextModule, CopilotProvider, AgentConnection as CoreAgentConnection, AgentMessage as CoreAgentMessage, AgentModel as CoreAgentModel, AgentTaskSession as CoreAgentTaskSession, AgentTaskSessionEventMap as CoreAgentTaskSessionEventMap, AgentTaskSessionOptions as CoreAgentTaskSessionOptions, AgentTaskSessionStatus as CoreAgentTaskSessionStatus, AgentTimelineItem as CoreAgentTimelineItem, AgentToolEvent as CoreAgentToolEvent, ListTablesOptions as CoreListTablesOptions, CredentialStatus, CustomQueriesModule, CustomQueryDefinition, CustomQueryInput, CustomQuerySummary, CustomQueryUpdateInput, DataSourceBulkItemResult, DataSourceBulkResult, DataSourceCreateInput, DataSourceDbType, DataSourceDefinition, DataSourceInstanceType, DataSourceUpdateInput, DataSourcesModule, DdlStatement, DeviceAuthorization, DmlStatement, EmptyFunctionInput, EntitiesModule, EntitiesProxy, EntityListOptions, EntityTable, ExistingAgentTaskSessionOptions, FunctionBulkCreateInput, FunctionBulkDeleteInput, FunctionBulkDeleteResult, FunctionBulkPatchInput, FunctionBulkPatchItem, FunctionBulkUpdateItem, FunctionCreateInput, FunctionDefinition, FunctionExecution, FunctionListOptions, FunctionPatchInput, FunctionRuntime, FunctionSecrets, FunctionSummary, FunctionUpdateInput, FunctionVersion, FunctionVersionListOptions, FunctionVisibility, FunctionsAdminModule, FunctionsModule, ImportColumnMapping, ImportDefinition, ImportExecution, ImportExecutionListOptions, ImportInput, ImportProcessing, ImportSchedule, ImportSource, ImportTarget, ImportsModule, IntegrationAdminModule, IntegrationConnectionStatus, IntegrationCredentialRule, IntegrationExecution, IntegrationFieldSchema, IntegrationFieldSchemaInput, IntegrationLoginConfig, IntegrationModule, IntegrationProxyMode, IntegrationRequestConfig, IntegrationResource, IntegrationResourceInput, IntegrationResourceParam, IntegrationResourceSummary, IntegrationResourceUpdateInput, IntegrationResourcesModule, IntegrationTemplate, IntegrationTemplateSummary, IntegrationTemplateType, IntegrationTemplatesModule, IntegrationTokenExtraction, InviteAppUserInput, InvocationType, JsonValue, ListTemplateConfigsOptions, MembersModule, MessengerModule, NewAgentTaskSessionOptions, OAuthExchangeInput, OAuthStartResult, Page, PageOptions, PlanPrice, ProviderCredentialStatus, ProxyInput, ProxyResult, PublicFunctionAsyncResult, PublicFunctionResult, PublicFunctionsModule, QueriesModule, QueryResult, SchemaModule, SchemaScope, SchemaTables, SqlModule, TableColumn, TableDefinition, TableForeignKey, TemplateConfig, TemplateConfigBulkItemResult, TemplateConfigBulkResult, TemplateConfigCreateInput, TemplateConfigPage, TemplateConfigSummary, TemplateConfigUpdateInput, Tenant, TestCredentialsInput, User, UserPlan, WorkflowDefinition, WorkflowExecution, WorkflowInput, WorkflowSummary, WorkflowsModule } from '@mitralab.io/sdk-core';
3
3
  import * as legacy from 'mitra-sdk';
4
4
 
5
5
  type AppScopedAppsModule = AppsModule;
@@ -50,7 +50,17 @@ interface MitraClientConfig {
50
50
  dataSourceId?: string;
51
51
  /** Optional request deadline. By default, the Functions runtime owns operation time limits. */
52
52
  timeoutMs?: number;
53
+ /**
54
+ * fetch for the Mitra API calls, which carry the access token. The Agent box routes never use
55
+ * it: they take `globalThis.fetch`, so a fetch that adds `Authorization` cannot hand the token
56
+ * to the box.
57
+ */
53
58
  fetch?: Fetch;
59
+ /**
60
+ * WebSocket implementation for Agent sessions, such as `ws`, when the runtime has no global one.
61
+ * Without either, Agent sessions reach the box over HTTP.
62
+ */
63
+ WebSocket?: AgentWebSocketConstructor;
54
64
  }
55
65
 
56
66
  interface MitraClient {
package/dist/index.js CHANGED
@@ -269,12 +269,7 @@ var AgentTaskSseEventSource = class {
269
269
  constructor(config) {
270
270
  this.config = config;
271
271
  }
272
- async open(taskId, observer, signal, transport) {
273
- if (transport === "websocket") {
274
- throw new MitraConfigurationError(
275
- "WebSocket Agent sessions are not available in the Functions runtime"
276
- );
277
- }
272
+ async open(taskId, observer, signal) {
278
273
  if (signal?.aborted) throw signal.reason ?? new Error("Agent event stream was aborted");
279
274
  const controller = new AbortController();
280
275
  let handshakeTimedOut = false;
@@ -654,7 +649,8 @@ function resolveConfig(config = {}, environment = readDefaultEnvironment()) {
654
649
  appId,
655
650
  ...dataSourceId === void 0 ? {} : { dataSourceId: dataSourceId.trim() },
656
651
  ...timeoutMs === void 0 ? {} : { timeoutMs },
657
- fetch: fetchImplementation
652
+ fetch: fetchImplementation,
653
+ ...config.WebSocket === void 0 ? {} : { WebSocket: config.WebSocket }
658
654
  };
659
655
  }
660
656
 
@@ -735,27 +731,28 @@ var DefaultMitraClient = class {
735
731
  this.agentConnections = core.agentConnections;
736
732
  this.agentCredentials = core.agentCredentials;
737
733
  this.agents = core.agents;
738
- const agentSessionManager = createAgentTaskSessionManager({
739
- tasks: core.agentTasks,
740
- eventSource: new AgentTaskSseEventSource({
741
- baseUrl: `${config.apiUrl}/copilot`,
742
- accessToken: config.accessToken,
743
- appId: config.appId,
744
- ...config.timeoutMs === void 0 ? {} : { timeoutMs: config.timeoutMs },
745
- fetch: config.fetch,
746
- errors: coreErrors
747
- })
748
- });
749
- this.agentTasks = withAgentTaskSessions(core.agentTasks, {
750
- session: (options) => {
751
- if (options.transport === "websocket") {
752
- throw new MitraConfigurationError(
753
- "WebSocket Agent sessions are not available in the Functions runtime; use http or auto"
754
- );
734
+ this.agentTasks = withAgentTaskSessions(
735
+ core.agentTasks,
736
+ createAgentTaskSessionManager({
737
+ tasks: core.agentTasks,
738
+ eventSource: new AgentTaskSseEventSource({
739
+ baseUrl: `${config.apiUrl}/copilot`,
740
+ accessToken: config.accessToken,
741
+ appId: config.appId,
742
+ ...config.timeoutMs === void 0 ? {} : { timeoutMs: config.timeoutMs },
743
+ fetch: config.fetch,
744
+ errors: coreErrors
745
+ }),
746
+ // Core owns the channel to the box. Without a WebSocket, as in the Functions runtime on
747
+ // Node 20, `auto` reaches the box over HTTP. The box routes use the global fetch, never
748
+ // `config.fetch`: the grant in the channel URL is the box credential, and a custom fetch
749
+ // that adds `Authorization` would send the Function token to the box.
750
+ directChannel: {
751
+ apiUrl: config.apiUrl,
752
+ ...config.WebSocket === void 0 ? {} : { WebSocket: config.WebSocket }
755
753
  }
756
- return agentSessionManager.session(options);
757
- }
758
- });
754
+ })
755
+ );
759
756
  this.apps = appModules.apps;
760
757
  this.auth = core.auth;
761
758
  this.context = core.context;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mitralab.io/functions-sdk",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "JavaScript and TypeScript SDK for Mitra Server Functions",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -67,7 +67,7 @@
67
67
  "node": ">=18.0.0"
68
68
  },
69
69
  "dependencies": {
70
- "@mitralab.io/sdk-core": "0.2.8",
70
+ "@mitralab.io/sdk-core": "0.2.9",
71
71
  "mitra-sdk": "1.0.63-beta.42"
72
72
  },
73
73
  "devDependencies": {