@truefoundry/assistant-ui-runtime 0.1.7 → 0.1.9

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.
Files changed (36) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +19 -15
  3. package/dist/chunk-CXBZ6WLZ.js +636 -0
  4. package/dist/chunk-CXBZ6WLZ.js.map +1 -0
  5. package/dist/index.d.ts +3 -3
  6. package/dist/index.js +14 -5
  7. package/dist/index.js.map +1 -1
  8. package/dist/plugins/truefoundry-agent-server-adapter/index.d.ts +81 -35
  9. package/dist/plugins/truefoundry-agent-server-adapter/index.js +3 -1
  10. package/dist/server/index.d.ts +2 -2
  11. package/dist/{types-DbNsU075.d.ts → types-6yWuWHzK.d.ts} +109 -28
  12. package/package.json +1 -1
  13. package/src/convertTurnMessages.ts +4 -0
  14. package/src/draft/truefoundryDraftThreadListAdapter.ts +4 -1
  15. package/src/harness.temp.ts +85 -0
  16. package/src/index.ts +27 -0
  17. package/src/plugins/truefoundry-agent-server-adapter/README.md +83 -44
  18. package/src/plugins/truefoundry-agent-server-adapter/chatServer.ts +365 -0
  19. package/src/plugins/truefoundry-agent-server-adapter/cp.test.ts +444 -0
  20. package/src/plugins/truefoundry-agent-server-adapter/cp.ts +482 -0
  21. package/src/plugins/truefoundry-agent-server-adapter/createTrueFoundryAgentUIServer.ts +94 -0
  22. package/src/plugins/truefoundry-agent-server-adapter/guards.ts +1 -1
  23. package/src/plugins/truefoundry-agent-server-adapter/index.ts +20 -391
  24. package/src/plugins/truefoundry-agent-server-adapter/normalizeAgentSpec.test.ts +85 -0
  25. package/src/plugins/truefoundry-agent-server-adapter/normalizeAgentSpec.ts +84 -0
  26. package/src/plugins/truefoundry-agent-server-adapter/types.ts +1 -1
  27. package/src/server/index.ts +20 -0
  28. package/src/server/types.ts +125 -28
  29. package/src/streamTurn.test.ts +27 -27
  30. package/src/streamTurn.ts +2 -2
  31. package/src/truefoundryOwnedSessionsThreadListAdapter.ts +4 -1
  32. package/src/truefoundryThreadListAdapter.test.ts +22 -0
  33. package/src/truefoundryThreadListAdapter.ts +4 -1
  34. package/src/useTrueFoundryAgentMessages.test.tsx +1 -1
  35. package/dist/chunk-SQDOTGP2.js +0 -292
  36. package/dist/chunk-SQDOTGP2.js.map +0 -1
@@ -1,8 +1,11 @@
1
1
  # truefoundry-agent-server-adapter
2
2
 
3
- A gateway plugin that wraps [`truefoundry-gateway-sdk`](https://www.npmjs.com/package/truefoundry-gateway-sdk) into an [`AgentChatServer`](../../README.md#server-port-agentchatserver) for `@truefoundry/assistant-ui-runtime`.
3
+ TrueFoundry **agent UI server** for `@truefoundry/assistant-ui-runtime`: gateway chat + Control Plane builder lists.
4
4
 
5
- Named vs draft session routing is internal you pass `apiKey` / `baseUrl` (or pre-built clients) and get a flat server the runtime can call.
5
+ - **Preferred:** `createTrueFoundryAgentUIServer`chat + builder from `{ apiKey, cpURL, gatewayURL? }`
6
+ - **Chat-only escape hatch:** `createTrueFoundryChatServer` — gateway sessions only (CLI / tests)
7
+
8
+ The same API key bearer is used for Control Plane and gateway.
6
9
 
7
10
  ### Used by the [runtime Quick start](../../README.md#quick-start)
8
11
 
@@ -11,8 +14,11 @@ Named vs draft session routing is internal — you pass `apiKey` / `baseUrl` (or
11
14
  ## Table of contents
12
15
 
13
16
  - [Installation](#installation)
14
- - [Quick start](#quick-start)
15
- - [`createTrueFoundryChatServer` options](#createtruefoundrychatserver-options)
17
+ - [Quick start (full pack)](#quick-start-full-pack)
18
+ - [`createTrueFoundryAgentUIServer` options](#createtruefoundryagentuiserver-options)
19
+ - [Gateway URL resolution](#gateway-url-resolution)
20
+ - [Builder methods](#builder-methods)
21
+ - [Chat-only: `createTrueFoundryChatServer`](#chat-only-createtruefoundrychatserver)
16
22
  - [Named vs draft sessions](#named-vs-draft-sessions)
17
23
  - [Types & guards](#types--guards)
18
24
  - [Extending `TfyAgentSpec`](#extending-tfyagentspec)
@@ -37,44 +43,82 @@ yarn add @truefoundry/assistant-ui-runtime truefoundry-gateway-sdk
37
43
 
38
44
  ---
39
45
 
40
- ## Quick start
46
+ ## Quick start (full pack)
41
47
 
42
48
  ```tsx
43
- import { createTrueFoundryChatServer } from "@truefoundry/assistant-ui-runtime";
49
+ import { createTrueFoundryAgentUIServer } from "@truefoundry/assistant-ui-runtime";
44
50
  // Isolated import (no React):
45
- // import { createTrueFoundryChatServer } from "@truefoundry/assistant-ui-runtime/plugins/truefoundry-agent-server-adapter";
51
+ // import { createTrueFoundryAgentUIServer } from "@truefoundry/assistant-ui-runtime/plugins/truefoundry-agent-server-adapter";
46
52
 
47
- const server = createTrueFoundryChatServer({
53
+ const server = await createTrueFoundryAgentUIServer({
48
54
  apiKey: process.env.TFY_API_KEY!,
49
- baseUrl: process.env.TFY_GATEWAY_URL!,
55
+ cpURL: process.env.TFY_CP_URL!,
56
+ // gatewayURL: process.env.TFY_GATEWAY_URL, // optional
50
57
  });
51
58
 
52
- // Pass `server` to useTrueFoundryAgentRuntime({ server, agentName })
59
+ // Pass `server` to TrueFoundryAssistantUI / useTrueFoundryAgentRuntime
53
60
  ```
54
61
 
55
- That returns a `TrueFoundryChatServer` implementing `AgentChatServer` with concrete `TfySession` / `TfyTurn` types.
62
+ Returns `TrueFoundryAgentUIServer` = `AgentChatServer` & `AgentBuilderServer` (no settings `catalog`). Concurrent calls with the same credentials share one in-flight promise.
56
63
 
57
64
  ---
58
65
 
59
- ## `createTrueFoundryChatServer` options
66
+ ## `createTrueFoundryAgentUIServer` options
60
67
 
61
68
  | Option | Type | Required | Description |
62
69
  | ------ | ---- | -------- | ----------- |
63
- | `apiKey` | `string` | ✅ | TrueFoundry API key |
64
- | `baseUrl` | `string` | ✅ | Gateway base URL |
65
- | `client` | `AgentSessionClient` | — | Override the named-session client (otherwise built from `apiKey` / `baseUrl`) |
66
- | `privateClient` | `PrivateAgentSessionClient` | — | Override the draft/private client |
67
- | `deleteSession` | `(req: { sessionId: string }) => Promise<void>` | — | Optional delete hook — not on the gateway SDK today; pass your own if needed |
70
+ | `apiKey` | `string` | ✅ | Bearer for CP and gateway (same PAT) |
71
+ | `cpURL` | `string` | ✅ | Control Plane base URL (builder lists + optional `/session`) |
72
+ | `gatewayURL` | `string` | — | Gateway base URL; when omitted, resolved via CP session (see below) |
73
+
74
+ ---
75
+
76
+ ## Gateway URL resolution
77
+
78
+ 1. If `gatewayURL` is set → use it (no `/session` call)
79
+ 2. Else `GET {cpURL}/api/svc/v1/session` → `{cpURL}{env.LLM_GATEWAY_URL ?? "/api/llm"}/{tenantName}`
80
+ 3. If session fails or `tenantName` is missing → **throws** (no silent public-gateway fallback)
81
+
82
+ Pass a public gateway explicitly when needed, e.g. `https://gateway.truefoundry.ai/<tenant>`.
83
+
84
+ ---
85
+
86
+ ## Builder methods
87
+
88
+ Implemented against Control Plane HTTP (not the gateway SDK):
89
+
90
+ | Method | CP path |
91
+ | ------ | ------- |
92
+ | `getModels` | `GET /api/svc/v1/llm-gateway/model/enabled` |
93
+ | `getSkills` | `GET /api/ml/v1/agent-skills?include_empty_agent_skills=false` |
94
+ | `getMcp` | `GET /api/svc/v1/mcp-servers` |
95
+ | `searchAgents` | `GET /api/svc/v1/agents?type=truefoundry-agent&…` |
96
+ | `saveAgent` | `PUT /api/svc/v1/agents` (`{ manifest }`, upsert by name) |
97
+
98
+ Selector rows include TFY mount fields (`apiModel`, skill `fqn`, `mcpName`).
99
+
100
+ ---
101
+
102
+ ## Chat-only: `createTrueFoundryChatServer`
103
+
104
+ For CLI / tests that only need sessions:
68
105
 
69
106
  ```tsx
107
+ import { createTrueFoundryChatServer } from "@truefoundry/assistant-ui-runtime";
108
+
70
109
  const server = createTrueFoundryChatServer({
71
- apiKey,
72
- baseUrl,
73
- // client, privateClient, deleteSession — optional overrides
110
+ apiKey: process.env.TFY_API_KEY!,
111
+ baseUrl: process.env.TFY_GATEWAY_URL!,
74
112
  });
75
113
  ```
76
114
 
77
- Escape hatch for hosts that still need raw gateway clients:
115
+ | Option | Type | Required | Description |
116
+ | ------ | ---- | -------- | ----------- |
117
+ | `apiKey` | `string` | ✅ | TrueFoundry API key |
118
+ | `baseUrl` | `string` | ✅ | Gateway base URL |
119
+ | `client` | `AgentSessionClient` | — | Override the named-session client |
120
+ | `privateClient` | `PrivateAgentSessionClient` | — | Override the draft/private client |
121
+ | `deleteSession` | `(req: { sessionId: string }) => Promise<void>` | — | Optional delete hook |
78
122
 
79
123
  ```tsx
80
124
  const { client, privateClient } = server.getGatewayClients();
@@ -93,14 +137,10 @@ Routing is fully internal via an in-memory session-type cache populated by `crea
93
137
 
94
138
  `updateSession` is only allowed when `session.isMutable === true` (draft). Calling it on a named session throws.
95
139
 
96
- > Ensure `createSession` or `listSessions` ran before `getSession` / turn methods for a given id — the adapter must have cached the session type.
97
-
98
140
  ---
99
141
 
100
142
  ## Types & guards
101
143
 
102
- The plugin surfaces concrete gateway types for hosts that need them:
103
-
104
144
  ```tsx
105
145
  import type {
106
146
  TfyAgentSpec,
@@ -108,8 +148,9 @@ import type {
108
148
  TfyMcpServerMount,
109
149
  TfySession,
110
150
  TfyTurn,
111
- TfyTurnState,
112
- TfyToolInfo,
151
+ TfyModelSelectorEntry,
152
+ TfySkillSelectorEntry,
153
+ TfyConnectorSelectorEntry,
113
154
  } from "@truefoundry/assistant-ui-runtime";
114
155
 
115
156
  import {
@@ -122,8 +163,6 @@ import {
122
163
  } from "@truefoundry/assistant-ui-runtime";
123
164
  ```
124
165
 
125
- Use the type guards to narrow event fields typed as `unknown` by the runtime.
126
-
127
166
  ---
128
167
 
129
168
  ## Extending `TfyAgentSpec`
@@ -132,23 +171,20 @@ Only the **spec** is generic. Session / turn / list-params stay as concrete `Tfy
132
171
 
133
172
  ```tsx
134
173
  import {
135
- createTrueFoundryChatServer,
174
+ createTrueFoundryAgentUIServer,
136
175
  type TfyAgentSpec,
137
- type TrueFoundryChatServer,
176
+ type TrueFoundryAgentUIServer,
138
177
  } from "@truefoundry/assistant-ui-runtime";
139
178
 
140
179
  interface MySpec extends TfyAgentSpec {
141
180
  workspaceId: string;
142
- deploymentId: string;
143
181
  }
144
182
 
145
- const server: TrueFoundryChatServer<MySpec> = createTrueFoundryChatServer<MySpec>({
146
- apiKey,
147
- baseUrl,
148
- });
149
-
150
- const session = await server.getSession({ sessionId: "ses_abc" });
151
- console.log(session.agentSpec?.workspaceId); // string | undefined
183
+ const server: TrueFoundryAgentUIServer<MySpec> =
184
+ await createTrueFoundryAgentUIServer<MySpec>({
185
+ apiKey,
186
+ cpURL,
187
+ });
152
188
  ```
153
189
 
154
190
  ---
@@ -157,11 +193,14 @@ console.log(session.agentSpec?.workspaceId); // string | undefined
157
193
 
158
194
  | Export | Kind | Purpose |
159
195
  | ------ | ---- | ------- |
160
- | `createTrueFoundryChatServer` | Function | Build a `TrueFoundryChatServer` from gateway credentials / clients |
161
- | `CreateTrueFoundryChatServerOptions` | Type | Options bag above |
162
- | `TrueFoundryChatServer<TSpec>` | Type | `AgentChatServer` + `getGatewayClients()` |
196
+ | `createTrueFoundryAgentUIServer` | Function | Full pack: chat + builder |
197
+ | `CreateTrueFoundryAgentUIServerOptions` | Type | Options bag |
198
+ | `TrueFoundryAgentUIServer<TSpec>` | Type | Chat + builder result |
199
+ | `createTrueFoundryChatServer` | Function | Chat-only escape hatch |
200
+ | `TrueFoundryChatServer<TSpec>` | Type | Chat-only result |
201
+ | `TfyModelSelectorEntry`, … | Types | Builder selector rows |
163
202
  | `TfyAgentSpec`, `TfySession`, `TfyTurn`, … | Types | Concrete gateway DTOs |
164
- | `isTfyToolInfo`, `getTfyUsage`, … | Guards / helpers | Narrow / extract gateway event fields |
203
+ | `isTfyToolInfo`, `getTfyUsage`, … | Guards | Narrow gateway event fields |
165
204
 
166
205
  Import path:
167
206
 
@@ -169,7 +208,7 @@ Import path:
169
208
  "@truefoundry/assistant-ui-runtime/plugins/truefoundry-agent-server-adapter"
170
209
  ```
171
210
 
172
- (or the main `@truefoundry/assistant-ui-runtime` entry, which re-exports these symbols).
211
+ (or the main `@truefoundry/assistant-ui-runtime` entry).
173
212
 
174
213
  ---
175
214
 
@@ -0,0 +1,365 @@
1
+ import { AgentSessionClient } from "truefoundry-gateway-sdk/agents";
2
+ import type { AgentSession } from "truefoundry-gateway-sdk/agents";
3
+ import { PrivateAgentSessionClient } from "truefoundry-gateway-sdk/agents/private";
4
+ import type { AgentDraftSession } from "truefoundry-gateway-sdk/agents/private";
5
+ import type {
6
+ AgentChatServer,
7
+ ListResult,
8
+ TurnInputItem,
9
+ PreviousTurnIdInput,
10
+ UpdateSessionRequest,
11
+ } from "../../server/types.js";
12
+ import type {
13
+ SessionEventItem,
14
+ TurnEvent,
15
+ TurnStreamData,
16
+ } from "../../server/events.js";
17
+ import { normalizeAgentSpecForGateway } from "./normalizeAgentSpec.js";
18
+ import type {
19
+ TfyAgentSpec,
20
+ TfyCreateSessionRequest,
21
+ TfyListSessionsParams,
22
+ TfySession,
23
+ TfyTurn,
24
+ TfyTurnState,
25
+ } from "./types.js";
26
+
27
+ type GwSession = AgentSession | AgentDraftSession;
28
+
29
+ export type CreateTrueFoundryChatServerOptions = {
30
+ apiKey: string;
31
+ baseUrl: string;
32
+ /** Optional override — otherwise constructed from apiKey/baseUrl. */
33
+ client?: AgentSessionClient;
34
+ privateClient?: PrivateAgentSessionClient;
35
+ deleteSession?: (req: { sessionId: string }) => Promise<void>;
36
+ };
37
+
38
+ /**
39
+ * Only the spec is generic. Session/Turn/list-params are the concrete Tfy*
40
+ * types because the adapter builds them as fixed object literals — a generic
41
+ * there would type fields that nothing ever populates. The spec is safe: the
42
+ * gateway SDK serializes with `unrecognizedObjectKeys: "passthrough"`, so
43
+ * host-added spec fields survive the round trip.
44
+ */
45
+ export type TrueFoundryChatServer<TSpec extends TfyAgentSpec = TfyAgentSpec> =
46
+ AgentChatServer<
47
+ TSpec,
48
+ TfySession<TSpec>,
49
+ TfyCreateSessionRequest<TSpec>,
50
+ TfyListSessionsParams,
51
+ UpdateSessionRequest<TSpec>,
52
+ TfyTurn
53
+ > & {
54
+ /** Escape hatch for hosts that still need raw gateway clients. */
55
+ getGatewayClients(): {
56
+ client: AgentSessionClient;
57
+ privateClient: PrivateAgentSessionClient;
58
+ };
59
+ };
60
+
61
+ /** Gateway SDK errors carry the HTTP status as `statusCode`. */
62
+ function isNotFound(error: unknown): boolean {
63
+ return (
64
+ typeof error === "object" &&
65
+ error !== null &&
66
+ (error as { statusCode?: unknown }).statusCode === 404
67
+ );
68
+ }
69
+
70
+ function isDraft(session: GwSession): session is AgentDraftSession {
71
+ return (session as AgentDraftSession).type === "session/draft";
72
+ }
73
+
74
+ function toSession<TSpec extends TfyAgentSpec>(raw: GwSession): TfySession<TSpec> {
75
+ const mutable = isDraft(raw);
76
+ return {
77
+ id: raw.id,
78
+ title: raw.title,
79
+ agentName: raw.agentName,
80
+ ...(mutable ? { agentSpec: raw.agentSpec as TSpec } : {}),
81
+ isMutable: mutable,
82
+ createdBySubject: raw.createdBySubject,
83
+ createdAt: raw.createdAt,
84
+ updatedAt: raw.updatedAt,
85
+ };
86
+ }
87
+
88
+ function toTurn(raw: {
89
+ id: string;
90
+ sessionId: string;
91
+ previousTurnId?: string | null;
92
+ input?: TurnInputItem[];
93
+ state: unknown;
94
+ createdBySubject: TfyTurn["createdBySubject"];
95
+ createdAt: string;
96
+ }): TfyTurn {
97
+ return {
98
+ id: raw.id,
99
+ sessionId: raw.sessionId,
100
+ previousTurnId: raw.previousTurnId,
101
+ input: raw.input,
102
+ state: raw.state as TfyTurnState,
103
+ createdBySubject: raw.createdBySubject,
104
+ createdAt: raw.createdAt,
105
+ };
106
+ }
107
+
108
+ async function toListResult<TIn, TOut>(
109
+ page: {
110
+ data: TIn[];
111
+ response?: { pagination?: { nextPageToken?: string } };
112
+ hasNextPage?: () => boolean;
113
+ },
114
+ map: (item: TIn) => TOut,
115
+ ): Promise<ListResult<TOut>> {
116
+ const nextPageToken = page.response?.pagination?.nextPageToken;
117
+ return {
118
+ data: page.data.map(map),
119
+ ...(nextPageToken != null && nextPageToken !== ""
120
+ ? { nextPageToken }
121
+ : {}),
122
+ };
123
+ }
124
+
125
+ /**
126
+ * Wraps TrueFoundry gateway clients into a flat `AgentChatServer`.
127
+ * Named vs draft routing is fully internal — an in-memory session-type cache
128
+ * (populated by createSession/listSessions) determines which gateway client
129
+ * to call, falling back to a one-time probe for ids seen only in a URL.
130
+ */
131
+ export function createTrueFoundryChatServer<
132
+ TSpec extends TfyAgentSpec = TfyAgentSpec,
133
+ >(
134
+ opts: CreateTrueFoundryChatServerOptions,
135
+ ): TrueFoundryChatServer<TSpec> {
136
+ const gatewayOpts = { apiKey: opts.apiKey, baseUrl: opts.baseUrl };
137
+ const client = opts.client ?? new AgentSessionClient(gatewayOpts);
138
+ const privateClient =
139
+ opts.privateClient ?? new PrivateAgentSessionClient(gatewayOpts);
140
+
141
+ const sessionTypeCache = new Map<string, boolean>();
142
+ const sessionTypeProbes = new Map<string, Promise<boolean>>();
143
+
144
+ function cacheSessionType(session: {
145
+ id: string;
146
+ isMutable: boolean;
147
+ }): void {
148
+ sessionTypeCache.set(session.id, session.isMutable);
149
+ }
150
+
151
+ /**
152
+ * Resolving a session id straight from a URL (page reload / shared link)
153
+ * reaches the gateway before createSession or listSessions has cached the
154
+ * type, so discover it by probing the draft endpoint and falling back to
155
+ * the conversation endpoint. Concurrent callers share one probe.
156
+ */
157
+ async function probeSessionType(sessionId: string): Promise<boolean> {
158
+ const inflight = sessionTypeProbes.get(sessionId);
159
+ if (inflight != null) {
160
+ return inflight;
161
+ }
162
+ const probe = (async () => {
163
+ try {
164
+ await privateClient.getDraftSession({ draftSessionId: sessionId });
165
+ return true;
166
+ } catch (error) {
167
+ // Only a miss proves the id isn't a draft. Auth or transient
168
+ // failures would otherwise be retried as a conversation session
169
+ // and mislabel a real draft as named.
170
+ if (!isNotFound(error)) {
171
+ throw error;
172
+ }
173
+ await client.getSession({ sessionId });
174
+ return false;
175
+ }
176
+ })();
177
+ sessionTypeProbes.set(sessionId, probe);
178
+ try {
179
+ const isMutable = await probe;
180
+ sessionTypeCache.set(sessionId, isMutable);
181
+ return isMutable;
182
+ } finally {
183
+ sessionTypeProbes.delete(sessionId);
184
+ }
185
+ }
186
+
187
+ async function getSessionObj(sessionId: string): Promise<GwSession> {
188
+ const isMutable =
189
+ sessionTypeCache.get(sessionId) ?? (await probeSessionType(sessionId));
190
+ return isMutable
191
+ ? privateClient.getDraftSession({ draftSessionId: sessionId })
192
+ : client.getSession({ sessionId });
193
+ }
194
+
195
+ const server: TrueFoundryChatServer<TSpec> = {
196
+ async createSession(req) {
197
+ if (req.agentSpec != null) {
198
+ const draft = await privateClient.createDraftSession({
199
+ agentSpec: normalizeAgentSpecForGateway(req.agentSpec),
200
+ ...(req.agentName != null ? { agentName: req.agentName } : {}),
201
+ ...(req.tfyMetadata != null
202
+ ? { tfyMetadata: req.tfyMetadata }
203
+ : {}),
204
+ });
205
+ const session = toSession<TSpec>(draft);
206
+ cacheSessionType(session);
207
+ return session;
208
+ }
209
+ if (req.agentName != null) {
210
+ const named = await client.createSession({
211
+ agentName: req.agentName,
212
+ ...(req.tfyMetadata != null
213
+ ? { tfyMetadata: req.tfyMetadata }
214
+ : {}),
215
+ });
216
+ const session = toSession<TSpec>(named);
217
+ cacheSessionType(session);
218
+ return session;
219
+ }
220
+ throw new Error("createSession requires agentName and/or agentSpec");
221
+ },
222
+
223
+ async listSessions(req) {
224
+ const page = await privateClient.listOwnedSessions({
225
+ limit: req?.limit,
226
+ order: req?.order,
227
+ pageToken: req?.pageToken,
228
+ startTimestamp: req?.startTimestamp,
229
+ endTimestamp: req?.endTimestamp,
230
+ ...(req?.agentName != null ? { agentName: req.agentName } : {}),
231
+ });
232
+ const result = await toListResult(page, (s) => toSession<TSpec>(s));
233
+ for (const session of result.data) {
234
+ cacheSessionType(session);
235
+ }
236
+ return result;
237
+ },
238
+
239
+ async getSession({ sessionId }) {
240
+ const raw = await getSessionObj(sessionId);
241
+ const session = toSession<TSpec>(raw);
242
+ cacheSessionType(session);
243
+ return session;
244
+ },
245
+
246
+ async updateSession(req) {
247
+ const raw = await getSessionObj(req.sessionId);
248
+ if (!isDraft(raw)) {
249
+ throw new Error(
250
+ "updateSession: session is not mutable (isMutable=false)",
251
+ );
252
+ }
253
+ if (req.agentSpec != null) {
254
+ await raw.update({
255
+ agentSpec: normalizeAgentSpecForGateway(req.agentSpec),
256
+ });
257
+ }
258
+ return toSession<TSpec>(raw);
259
+ },
260
+
261
+ createTurn(req: {
262
+ sessionId: string;
263
+ input?: TurnInputItem[];
264
+ previousTurnId?: PreviousTurnIdInput;
265
+ abortSignal?: AbortSignal;
266
+ headers?: Record<string, string>;
267
+ }): AsyncIterable<TurnStreamData> {
268
+ return (async function* () {
269
+ const session = await getSessionObj(req.sessionId);
270
+ const prepared = session.prepareTurn({
271
+ input: req.input,
272
+ previousTurnId: req.previousTurnId ?? "auto",
273
+ });
274
+ yield* prepared.execute(
275
+ { stream: true },
276
+ {
277
+ ...(req.abortSignal != null
278
+ ? { abortSignal: req.abortSignal }
279
+ : {}),
280
+ ...(req.headers != null ? { headers: req.headers } : {}),
281
+ },
282
+ ) as AsyncIterable<TurnStreamData>;
283
+ })();
284
+ },
285
+
286
+ async cancelSession({ sessionId }) {
287
+ await (await getSessionObj(sessionId)).cancel();
288
+ },
289
+
290
+ async deleteSession({ sessionId }) {
291
+ if (opts.deleteSession == null) {
292
+ throw new Error(
293
+ "deleteSession is not on the gateway SDK. Pass deleteSession to createTrueFoundryChatServer.",
294
+ );
295
+ }
296
+ await opts.deleteSession({ sessionId });
297
+ },
298
+
299
+ // The runtime's signature offers `order`, but the gateway's listTurns
300
+ // takes no such param — forwarding it silently did nothing.
301
+ async listTurns({ sessionId, limit, pageToken }) {
302
+ const raw = await getSessionObj(sessionId);
303
+ const page = await raw.listTurns({
304
+ ...(limit != null ? { limit } : {}),
305
+ ...(pageToken != null ? { pageToken } : {}),
306
+ });
307
+ return toListResult(page, (turn) => toTurn(turn));
308
+ },
309
+
310
+ async getTurn({ sessionId, turnId }) {
311
+ const raw = await getSessionObj(sessionId);
312
+ return toTurn(await raw.getTurn({ turnId }));
313
+ },
314
+
315
+ async listEvents({ sessionId, pageToken, lastTurnId, limit }) {
316
+ const raw = await getSessionObj(sessionId);
317
+ const page = await raw.listEvents({
318
+ ...(limit != null ? { limit } : {}),
319
+ ...(pageToken != null ? { pageToken } : {}),
320
+ ...(lastTurnId != null ? { lastTurnId } : {}),
321
+ });
322
+ return toListResult(
323
+ page,
324
+ (item) => item as SessionEventItem,
325
+ );
326
+ },
327
+
328
+ async listTurnEvents({ sessionId, turnId, limit, pageToken, order }) {
329
+ const raw = await getSessionObj(sessionId);
330
+ const turn = await raw.getTurn({ turnId });
331
+ const page = await turn.listEvents({
332
+ ...(limit != null ? { limit } : {}),
333
+ ...(pageToken != null ? { pageToken } : {}),
334
+ ...(order != null ? { order } : {}),
335
+ });
336
+ return toListResult(page, (event) => event as TurnEvent);
337
+ },
338
+
339
+ async *subscribeToTurn({
340
+ sessionId,
341
+ turnId,
342
+ afterSequenceNumber,
343
+ abortSignal,
344
+ }) {
345
+ const raw = await getSessionObj(sessionId);
346
+ const turn = await raw.getTurn({ turnId });
347
+ yield* turn.stream(
348
+ afterSequenceNumber != null ? { afterSequenceNumber } : {},
349
+ abortSignal != null ? { abortSignal } : {},
350
+ ) as AsyncIterable<TurnStreamData>;
351
+ },
352
+
353
+ async downloadSandboxFile(sandboxId, req) {
354
+ const response = await privateClient.downloadSandboxFile(
355
+ sandboxId,
356
+ req,
357
+ );
358
+ return await response.blob();
359
+ },
360
+
361
+ getGatewayClients: () => ({ client, privateClient }),
362
+ };
363
+
364
+ return server;
365
+ }