@truefoundry/assistant-ui-runtime 0.1.6-rc.0 → 0.1.7

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 (38) hide show
  1. package/README.md +193 -579
  2. package/dist/chunk-3A2EPLQG.js +93 -0
  3. package/dist/chunk-3A2EPLQG.js.map +1 -0
  4. package/dist/chunk-SQDOTGP2.js +292 -0
  5. package/dist/chunk-SQDOTGP2.js.map +1 -0
  6. package/dist/index.d.ts +24 -36
  7. package/dist/index.js +276 -249
  8. package/dist/index.js.map +1 -1
  9. package/dist/plugins/truefoundry-agent-server-adapter/index.d.ts +134 -5
  10. package/dist/plugins/truefoundry-agent-server-adapter/index.js +16 -195
  11. package/dist/plugins/truefoundry-agent-server-adapter/index.js.map +1 -1
  12. package/dist/server/index.d.ts +17 -0
  13. package/dist/server/index.js +9 -0
  14. package/dist/server/index.js.map +1 -0
  15. package/dist/{types-VUBzoJT2.d.ts → types-DbNsU075.d.ts} +212 -19
  16. package/package.json +10 -5
  17. package/src/{private → draft}/agentSpec.ts +14 -17
  18. package/src/{private → draft}/draftSessionBridge.ts +1 -2
  19. package/src/{private → draft}/truefoundryDraftThreadListAdapter.test.ts +1 -1
  20. package/src/{private → draft}/truefoundryDraftThreadListAdapter.ts +2 -1
  21. package/src/{private → draft}/useDraftAgentSpec.ts +16 -5
  22. package/src/draftAgentConfig.test.ts +2 -1
  23. package/src/index.ts +71 -7
  24. package/src/plugins/truefoundry-agent-server-adapter/README.md +178 -0
  25. package/src/plugins/truefoundry-agent-server-adapter/guards.test.ts +113 -0
  26. package/src/plugins/truefoundry-agent-server-adapter/guards.ts +130 -0
  27. package/src/plugins/truefoundry-agent-server-adapter/index.ts +154 -40
  28. package/src/plugins/truefoundry-agent-server-adapter/types.ts +137 -0
  29. package/src/plugins/truefoundry-agent-server-adapter/types.typecheck.ts +164 -0
  30. package/src/server/index.ts +23 -0
  31. package/src/server/types.ts +272 -21
  32. package/src/truefoundryExtras.ts +4 -1
  33. package/src/truefoundryOwnedSessionsThreadListAdapter.ts +1 -1
  34. package/src/types.ts +1 -2
  35. package/src/useTrueFoundryAgentMessages.test.tsx +261 -1
  36. package/src/useTrueFoundryAgentMessages.ts +284 -176
  37. package/src/useTrueFoundryAgentRuntime.ts +31 -21
  38. /package/src/{private → draft}/useDraftAgentSpec.test.tsx +0 -0
@@ -1,6 +1,128 @@
1
1
  import { AgentSessionClient } from 'truefoundry-gateway-sdk/agents';
2
2
  import { PrivateAgentSessionClient } from 'truefoundry-gateway-sdk/agents/private';
3
- import { a as AgentChatServer } from '../../types-VUBzoJT2.js';
3
+ import { A as AgentSpec, C as CreateSessionRequest, L as ListSessionsParams, S as Session, T as Turn, a as TurnState, b as AgentChatServer, U as UpdateSessionRequest } from '../../types-DbNsU075.js';
4
+ import { TruefoundryGatewayApi } from 'truefoundry-gateway-sdk';
5
+
6
+ /**
7
+ * TrueFoundry-specific type extensions over the runtime's generic bases.
8
+ *
9
+ * The runtime defines minimal bases (SkillMount = {id,name}, McpServerMount =
10
+ * {id,name}, AgentSpec.config = unknown, etc.) that hosts extend via generics.
11
+ *
12
+ * This file builds the concrete TrueFoundry types by:
13
+ * - Importing the runtime's AgentSpec as the base to extend.
14
+ * - Importing concrete sub-types from the gateway SDK namespace rather than
15
+ * re-defining them — they're purely gateway concepts.
16
+ * - Composing a TfyAgentSpec that satisfies both the runtime's
17
+ * `TSpec extends AgentSpec` constraint and the gateway SDK's AgentSpec shape.
18
+ */
19
+
20
+ type TfyRuntimeConfig = TruefoundryGatewayApi.RuntimeConfig;
21
+ type TfyResponseFormat = TruefoundryGatewayApi.ResponseFormat;
22
+ type TfyModelParams = TruefoundryGatewayApi.ModelParams;
23
+ type TfySubject = TruefoundryGatewayApi.Subject;
24
+ type ToolsSelectorTag = "@all" | "@read-only";
25
+ type RequireApprovalToolsSelectorTag = "@all" | "@write" | "@destructive";
26
+ type ToolsSelectorItem = ToolsSelectorTag | string;
27
+ type RequireApprovalToolSelectorItem = RequireApprovalToolsSelectorTag | string;
28
+ type RuntimeSkillMount = NonNullable<NonNullable<AgentSpec["skills"]>[number]>;
29
+ type RuntimeMcpServerMount = NonNullable<NonNullable<AgentSpec["mcpServers"]>[number]>;
30
+ type TfySkillMount = RuntimeSkillMount & TruefoundryGatewayApi.SkillMount;
31
+ type TfyMcpServerMount = RuntimeMcpServerMount & TruefoundryGatewayApi.McpServer;
32
+ interface TfyAgentSpec extends AgentSpec<TruefoundryGatewayApi.Model, TfySkillMount, TfyMcpServerMount> {
33
+ config?: TruefoundryGatewayApi.RuntimeConfig;
34
+ responseFormat?: TruefoundryGatewayApi.ResponseFormat;
35
+ messages?: TruefoundryGatewayApi.AgentSpecUserMessage[];
36
+ }
37
+ type TfyTurnCancelledReason = TruefoundryGatewayApi.TurnStateCancelledReason;
38
+ type TfyTurnStateDoneOutput = TruefoundryGatewayApi.TurnStateDoneOutput;
39
+ type RuntimeTurnStateDone = Extract<TurnState, {
40
+ status: "done";
41
+ }>;
42
+ type RuntimeTurnStateCancelled = Extract<TurnState, {
43
+ status: "cancelled";
44
+ }>;
45
+ /**
46
+ * The runtime types `output` as `unknown` and `reason` as bare `string`. The
47
+ * gateway sends a model message and one of four reasons — `cancelled-for-next-turn`
48
+ * in particular is routine and should not render like a failure.
49
+ */
50
+ type TfyTurnState = Exclude<TurnState, {
51
+ status: "done" | "cancelled";
52
+ }> | (Omit<RuntimeTurnStateDone, "output"> & {
53
+ output?: TfyTurnStateDoneOutput;
54
+ }) | (Omit<RuntimeTurnStateCancelled, "reason"> & {
55
+ reason: TfyTurnCancelledReason;
56
+ });
57
+ interface TfyTurn extends Turn {
58
+ state: TfyTurnState;
59
+ createdBySubject: TfySubject;
60
+ }
61
+ interface TfySession<TSpec extends TfyAgentSpec = TfyAgentSpec> extends Session<TSpec> {
62
+ createdBySubject: TfySubject;
63
+ }
64
+ interface TfyCreateSessionRequest<TSpec extends TfyAgentSpec = TfyAgentSpec> extends CreateSessionRequest<TSpec> {
65
+ /** Sent as `x-tfy-metadata`, persisted server-side as `request_metadata`. */
66
+ tfyMetadata?: string;
67
+ }
68
+ interface TfyListSessionsParams extends ListSessionsParams {
69
+ /** Inclusive upper bound on `createdAt` (ISO-8601). */
70
+ endTimestamp?: string;
71
+ }
72
+ type TfyToolInfo = TruefoundryGatewayApi.ToolInfo;
73
+ type TfySystemToolInfo = TruefoundryGatewayApi.TrueFoundrySystemToolInfo;
74
+ type TfyMcpToolInfo = TruefoundryGatewayApi.McpToolInfo;
75
+ type TfyModelMessageUsage = TruefoundryGatewayApi.ModelMessageUsage;
76
+ type TfyFinishReason = TruefoundryGatewayApi.FinishReason;
77
+ type TfyThreadState = TruefoundryGatewayApi.ThreadState;
78
+ type TfyMcpServerInitInfo = TruefoundryGatewayApi.McpServerInitInfo;
79
+
80
+ /**
81
+ * Point-of-use narrowing for the event half of the gateway protocol.
82
+ *
83
+ * `AgentChatServer` hardcodes the runtime's event types on listEvents,
84
+ * listTurnEvents, subscribeToTurn and prepareAndExecuteTurn — there is no
85
+ * generic to override them from here. So instead of typing those channels,
86
+ * hosts call these guards on the values they receive.
87
+ *
88
+ * They validate rather than cast: this data comes off the network, and the
89
+ * runtime types the relevant fields as `unknown` precisely because nothing
90
+ * has checked them yet.
91
+ */
92
+
93
+ /**
94
+ * Identifies built-in tools such as `ask_user_question` and `create_sub_agent`.
95
+ * Note `toolInfo` is legitimately absent on streamed deltas, so callers must
96
+ * keep their `function.name` fallback rather than treating absence as an error.
97
+ */
98
+ declare function isTfySystemToolInfo(toolInfo: unknown): toolInfo is TfySystemToolInfo;
99
+ /** Carries `serverId` / `serverName`, so the UI can attribute a call to its MCP server. */
100
+ declare function isTfyMcpToolInfo(toolInfo: unknown): toolInfo is TfyMcpToolInfo;
101
+ declare function isTfyToolInfo(toolInfo: unknown): toolInfo is TfyToolInfo;
102
+ /**
103
+ * Token usage including the TrueFoundry-specific `inputTokensBreakdown`, which
104
+ * attributes input tokens across harness, skills, instructions, tool
105
+ * definitions and messages.
106
+ */
107
+ declare function getTfyUsage(source: {
108
+ usage?: unknown;
109
+ } | null | undefined): TfyModelMessageUsage | undefined;
110
+ /**
111
+ * Completion state of a sub-agent thread. The runtime types `thread.done`'s
112
+ * `state` as `unknown`, so a sub-agent that errored is otherwise
113
+ * indistinguishable from one that succeeded.
114
+ */
115
+ declare function getTfyThreadState(event: {
116
+ state?: unknown;
117
+ } | null | undefined): TfyThreadState | undefined;
118
+ /**
119
+ * Servers from an `mcp.initialize` event, including each one's `transportType`.
120
+ * The runtime models this event with an index signature, so the array is
121
+ * `unknown` until checked.
122
+ */
123
+ declare function getTfyMcpInitServers(event: {
124
+ mcpServers?: unknown;
125
+ } | null | undefined): TfyMcpServerInitInfo[] | undefined;
4
126
 
5
127
  type CreateTrueFoundryChatServerOptions = {
6
128
  apiKey: string;
@@ -12,7 +134,14 @@ type CreateTrueFoundryChatServerOptions = {
12
134
  sessionId: string;
13
135
  }) => Promise<void>;
14
136
  };
15
- type TrueFoundryChatServer = AgentChatServer & {
137
+ /**
138
+ * Only the spec is generic. Session/Turn/list-params are the concrete Tfy*
139
+ * types because the adapter builds them as fixed object literals — a generic
140
+ * there would type fields that nothing ever populates. The spec is safe: the
141
+ * gateway SDK serializes with `unrecognizedObjectKeys: "passthrough"`, so
142
+ * host-added spec fields survive the round trip.
143
+ */
144
+ type TrueFoundryChatServer<TSpec extends TfyAgentSpec = TfyAgentSpec> = AgentChatServer<TSpec, TfySession<TSpec>, TfyCreateSessionRequest<TSpec>, TfyListSessionsParams, UpdateSessionRequest<TSpec>, TfyTurn> & {
16
145
  /** Escape hatch for hosts that still need raw gateway clients. */
17
146
  getGatewayClients(): {
18
147
  client: AgentSessionClient;
@@ -23,8 +152,8 @@ type TrueFoundryChatServer = AgentChatServer & {
23
152
  * Wraps TrueFoundry gateway clients into a flat `AgentChatServer`.
24
153
  * Named vs draft routing is fully internal — an in-memory session-type cache
25
154
  * (populated by createSession/listSessions) determines which gateway client
26
- * to call. No try/catch fallback, no double network calls.
155
+ * to call, falling back to a one-time probe for ids seen only in a URL.
27
156
  */
28
- declare function createTrueFoundryChatServer(opts: CreateTrueFoundryChatServerOptions): TrueFoundryChatServer;
157
+ declare function createTrueFoundryChatServer<TSpec extends TfyAgentSpec = TfyAgentSpec>(opts: CreateTrueFoundryChatServerOptions): TrueFoundryChatServer<TSpec>;
29
158
 
30
- export { type CreateTrueFoundryChatServerOptions, type TrueFoundryChatServer, createTrueFoundryChatServer };
159
+ export { type CreateTrueFoundryChatServerOptions, type RequireApprovalToolSelectorItem, type RequireApprovalToolsSelectorTag, type TfyAgentSpec, type TfyCreateSessionRequest, type TfyFinishReason, type TfyListSessionsParams, type TfyMcpServerInitInfo, type TfyMcpServerMount, type TfyMcpToolInfo, type TfyModelMessageUsage, type TfyModelParams, type TfyResponseFormat, type TfyRuntimeConfig, type TfySession, type TfySkillMount, type TfySubject, type TfySystemToolInfo, type TfyThreadState, type TfyToolInfo, type TfyTurn, type TfyTurnCancelledReason, type TfyTurnState, type TfyTurnStateDoneOutput, type ToolsSelectorItem, type ToolsSelectorTag, type TrueFoundryChatServer, createTrueFoundryChatServer, getTfyMcpInitServers, getTfyThreadState, getTfyUsage, isTfyMcpToolInfo, isTfySystemToolInfo, isTfyToolInfo };
@@ -1,198 +1,19 @@
1
- // src/plugins/truefoundry-agent-server-adapter/index.ts
2
- import { AgentSessionClient } from "truefoundry-gateway-sdk/agents";
3
- import { PrivateAgentSessionClient } from "truefoundry-gateway-sdk/agents/private";
4
- function isDraft(session) {
5
- return session.type === "session/draft";
6
- }
7
- function toSession(raw) {
8
- const mutable = isDraft(raw);
9
- return {
10
- id: raw.id,
11
- title: raw.title,
12
- agentName: raw.agentName,
13
- ...mutable ? { agentSpec: raw.agentSpec } : {},
14
- isMutable: mutable,
15
- createdAt: raw.createdAt,
16
- updatedAt: raw.updatedAt
17
- };
18
- }
19
- function toTurn(raw) {
20
- return {
21
- id: raw.id,
22
- sessionId: raw.sessionId,
23
- previousTurnId: raw.previousTurnId,
24
- input: raw.input,
25
- state: raw.state,
26
- createdAt: raw.createdAt
27
- };
28
- }
29
- async function toListResult(page, map) {
30
- const nextPageToken = page.response?.pagination?.nextPageToken;
31
- return {
32
- data: page.data.map(map),
33
- ...nextPageToken != null && nextPageToken !== "" ? { nextPageToken } : {}
34
- };
35
- }
36
- function createTrueFoundryChatServer(opts) {
37
- const gatewayOpts = { apiKey: opts.apiKey, baseUrl: opts.baseUrl };
38
- const client = opts.client ?? new AgentSessionClient(gatewayOpts);
39
- const privateClient = opts.privateClient ?? new PrivateAgentSessionClient(gatewayOpts);
40
- const sessionTypeCache = /* @__PURE__ */ new Map();
41
- function cacheSessionType(session) {
42
- sessionTypeCache.set(session.id, session.isMutable);
43
- }
44
- function getSessionObj(sessionId) {
45
- const isMutable = sessionTypeCache.get(sessionId);
46
- if (isMutable === true) {
47
- return privateClient.getDraftSession({ draftSessionId: sessionId });
48
- }
49
- if (isMutable === false) {
50
- return client.getSession({ sessionId });
51
- }
52
- throw new Error(
53
- `Cannot resolve session "${sessionId}": session type not cached. Ensure createSession or listSessions was called first.`
54
- );
55
- }
56
- const server = {
57
- async createSession(req) {
58
- if (req.agentSpec != null) {
59
- const draft = await privateClient.createDraftSession({
60
- agentSpec: req.agentSpec,
61
- ...req.agentName != null ? { agentName: req.agentName } : {}
62
- });
63
- const session = toSession(draft);
64
- cacheSessionType(session);
65
- return session;
66
- }
67
- if (req.agentName != null) {
68
- const named = await client.createSession({
69
- agentName: req.agentName
70
- });
71
- const session = toSession(named);
72
- cacheSessionType(session);
73
- return session;
74
- }
75
- throw new Error("createSession requires agentName and/or agentSpec");
76
- },
77
- async listSessions(req) {
78
- const page = await privateClient.listOwnedSessions({
79
- limit: req?.limit,
80
- order: req?.order,
81
- pageToken: req?.pageToken,
82
- startTimestamp: req?.startTimestamp,
83
- ...req?.agentName != null ? { agentName: req.agentName } : {}
84
- });
85
- const result = await toListResult(page, toSession);
86
- for (const session of result.data) {
87
- cacheSessionType(session);
88
- }
89
- return result;
90
- },
91
- async getSession({ sessionId }) {
92
- const raw = await getSessionObj(sessionId);
93
- const session = toSession(raw);
94
- cacheSessionType(session);
95
- return session;
96
- },
97
- async updateSession(req) {
98
- const raw = await getSessionObj(req.sessionId);
99
- if (!isDraft(raw)) {
100
- throw new Error(
101
- "updateSession: session is not mutable (isMutable=false)"
102
- );
103
- }
104
- if (req.agentSpec != null) {
105
- await raw.update({ agentSpec: req.agentSpec });
106
- }
107
- return toSession(raw);
108
- },
109
- prepareAndExecuteTurn(req) {
110
- return (async function* () {
111
- const session = await getSessionObj(req.sessionId);
112
- const prepared = session.prepareTurn({
113
- input: req.input,
114
- previousTurnId: req.previousTurnId ?? "auto"
115
- });
116
- yield* prepared.execute(
117
- { stream: true },
118
- {
119
- ...req.abortSignal != null ? { abortSignal: req.abortSignal } : {},
120
- ...req.headers != null ? { headers: req.headers } : {}
121
- }
122
- );
123
- })();
124
- },
125
- async cancelSession({ sessionId }) {
126
- await (await getSessionObj(sessionId)).cancel();
127
- },
128
- async deleteSession({ sessionId }) {
129
- if (opts.deleteSession == null) {
130
- throw new Error(
131
- "deleteSession is not on the gateway SDK. Pass deleteSession to createTrueFoundryChatServer."
132
- );
133
- }
134
- await opts.deleteSession({ sessionId });
135
- },
136
- async listTurns({ sessionId, limit, pageToken, order }) {
137
- const raw = await getSessionObj(sessionId);
138
- const page = await raw.listTurns({
139
- ...limit != null ? { limit } : {},
140
- ...pageToken != null ? { pageToken } : {},
141
- ...order != null ? { order } : {}
142
- });
143
- return toListResult(page, (turn) => toTurn(turn));
144
- },
145
- async getTurn({ sessionId, turnId }) {
146
- const raw = await getSessionObj(sessionId);
147
- return toTurn(await raw.getTurn({ turnId }));
148
- },
149
- async listEvents({ sessionId, pageToken, lastTurnId, limit }) {
150
- const raw = await getSessionObj(sessionId);
151
- const page = await raw.listEvents({
152
- ...limit != null ? { limit } : {},
153
- ...pageToken != null ? { pageToken } : {},
154
- ...lastTurnId != null ? { lastTurnId } : {}
155
- });
156
- return toListResult(
157
- page,
158
- (item) => item
159
- );
160
- },
161
- async listTurnEvents({ sessionId, turnId, limit, pageToken, order }) {
162
- const raw = await getSessionObj(sessionId);
163
- const turn = await raw.getTurn({ turnId });
164
- const page = await turn.listEvents({
165
- ...limit != null ? { limit } : {},
166
- ...pageToken != null ? { pageToken } : {},
167
- ...order != null ? { order } : {}
168
- });
169
- return toListResult(page, (event) => event);
170
- },
171
- async *subscribeToTurn({
172
- sessionId,
173
- turnId,
174
- afterSequenceNumber,
175
- abortSignal
176
- }) {
177
- const raw = await getSessionObj(sessionId);
178
- const turn = await raw.getTurn({ turnId });
179
- yield* turn.stream(
180
- afterSequenceNumber != null ? { afterSequenceNumber } : {},
181
- abortSignal != null ? { abortSignal } : {}
182
- );
183
- },
184
- async downloadSandboxFile(sandboxId, req) {
185
- const response = await privateClient.downloadSandboxFile(
186
- sandboxId,
187
- req
188
- );
189
- return await response.blob();
190
- },
191
- getGatewayClients: () => ({ client, privateClient })
192
- };
193
- return server;
194
- }
1
+ import {
2
+ createTrueFoundryChatServer,
3
+ getTfyMcpInitServers,
4
+ getTfyThreadState,
5
+ getTfyUsage,
6
+ isTfyMcpToolInfo,
7
+ isTfySystemToolInfo,
8
+ isTfyToolInfo
9
+ } from "../../chunk-SQDOTGP2.js";
195
10
  export {
196
- createTrueFoundryChatServer
11
+ createTrueFoundryChatServer,
12
+ getTfyMcpInitServers,
13
+ getTfyThreadState,
14
+ getTfyUsage,
15
+ isTfyMcpToolInfo,
16
+ isTfySystemToolInfo,
17
+ isTfyToolInfo
197
18
  };
198
19
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/plugins/truefoundry-agent-server-adapter/index.ts"],"sourcesContent":["import { AgentSessionClient } from \"truefoundry-gateway-sdk/agents\";\nimport type { AgentSession } from \"truefoundry-gateway-sdk/agents\";\nimport { PrivateAgentSessionClient } from \"truefoundry-gateway-sdk/agents/private\";\nimport type { AgentDraftSession } from \"truefoundry-gateway-sdk/agents/private\";\nimport type {\n AgentChatServer,\n AgentSpec,\n ListResult,\n Session,\n Turn,\n TurnInputItem,\n PreviousTurnIdInput,\n} from \"../../server/types.js\";\nimport type {\n TurnEvent,\n TurnStreamData,\n SessionEventItem,\n} from \"../../server/events.js\";\n\ntype GwSession = AgentSession | AgentDraftSession;\n\nexport type CreateTrueFoundryChatServerOptions = {\n apiKey: string;\n baseUrl: string;\n /** Optional override — otherwise constructed from apiKey/baseUrl. */\n client?: AgentSessionClient;\n privateClient?: PrivateAgentSessionClient;\n deleteSession?: (req: { sessionId: string }) => Promise<void>;\n};\n\nexport type TrueFoundryChatServer = AgentChatServer & {\n /** Escape hatch for hosts that still need raw gateway clients. */\n getGatewayClients(): {\n client: AgentSessionClient;\n privateClient: PrivateAgentSessionClient;\n };\n};\n\nfunction isDraft(session: GwSession): session is AgentDraftSession {\n return (session as AgentDraftSession).type === \"session/draft\";\n}\n\nfunction toSession(raw: GwSession): Session {\n const mutable = isDraft(raw);\n return {\n id: raw.id,\n title: raw.title,\n agentName: raw.agentName,\n ...(mutable ? { agentSpec: raw.agentSpec as AgentSpec } : {}),\n isMutable: mutable,\n createdAt: raw.createdAt,\n updatedAt: raw.updatedAt,\n };\n}\n\nfunction toTurn(raw: {\n id: string;\n sessionId: string;\n previousTurnId?: string | null;\n input?: TurnInputItem[];\n state: Turn[\"state\"];\n createdAt: string;\n}): Turn {\n return {\n id: raw.id,\n sessionId: raw.sessionId,\n previousTurnId: raw.previousTurnId,\n input: raw.input as TurnInputItem[] | undefined,\n state: raw.state as Turn[\"state\"],\n createdAt: raw.createdAt,\n };\n}\n\nasync function toListResult<TIn, TOut>(\n page: {\n data: TIn[];\n response?: { pagination?: { nextPageToken?: string } };\n hasNextPage?: () => boolean;\n },\n map: (item: TIn) => TOut,\n): Promise<ListResult<TOut>> {\n const nextPageToken = page.response?.pagination?.nextPageToken;\n return {\n data: page.data.map(map),\n ...(nextPageToken != null && nextPageToken !== \"\"\n ? { nextPageToken }\n : {}),\n };\n}\n\n/**\n * Wraps TrueFoundry gateway clients into a flat `AgentChatServer`.\n * Named vs draft routing is fully internal — an in-memory session-type cache\n * (populated by createSession/listSessions) determines which gateway client\n * to call. No try/catch fallback, no double network calls.\n */\nexport function createTrueFoundryChatServer(\n opts: CreateTrueFoundryChatServerOptions,\n): TrueFoundryChatServer {\n const gatewayOpts = { apiKey: opts.apiKey, baseUrl: opts.baseUrl };\n const client = opts.client ?? new AgentSessionClient(gatewayOpts);\n const privateClient =\n opts.privateClient ?? new PrivateAgentSessionClient(gatewayOpts);\n\n const sessionTypeCache = new Map<string, boolean>();\n\n function cacheSessionType(session: Session): void {\n sessionTypeCache.set(session.id, session.isMutable);\n }\n\n function getSessionObj(sessionId: string): Promise<GwSession> {\n const isMutable = sessionTypeCache.get(sessionId);\n if (isMutable === true) {\n return privateClient.getDraftSession({ draftSessionId: sessionId });\n }\n if (isMutable === false) {\n return client.getSession({ sessionId });\n }\n throw new Error(\n `Cannot resolve session \"${sessionId}\": session type not cached. ` +\n `Ensure createSession or listSessions was called first.`,\n );\n }\n\n const server: TrueFoundryChatServer = {\n async createSession(req) {\n if (req.agentSpec != null) {\n const draft = await privateClient.createDraftSession({\n agentSpec: req.agentSpec as never,\n ...(req.agentName != null ? { agentName: req.agentName } : {}),\n });\n const session = toSession(draft);\n cacheSessionType(session);\n return session;\n }\n if (req.agentName != null) {\n const named = await client.createSession({\n agentName: req.agentName,\n });\n const session = toSession(named);\n cacheSessionType(session);\n return session;\n }\n throw new Error(\"createSession requires agentName and/or agentSpec\");\n },\n\n async listSessions(req) {\n const page = await privateClient.listOwnedSessions({\n limit: req?.limit,\n order: req?.order,\n pageToken: req?.pageToken,\n startTimestamp: req?.startTimestamp,\n ...(req?.agentName != null ? { agentName: req.agentName } : {}),\n });\n const result = await toListResult(page, toSession);\n for (const session of result.data) {\n cacheSessionType(session);\n }\n return result;\n },\n\n async getSession({ sessionId }) {\n const raw = await getSessionObj(sessionId);\n const session = toSession(raw);\n cacheSessionType(session);\n return session;\n },\n\n async updateSession(req) {\n const raw = await getSessionObj(req.sessionId);\n if (!isDraft(raw)) {\n throw new Error(\n \"updateSession: session is not mutable (isMutable=false)\",\n );\n }\n if (req.agentSpec != null) {\n await raw.update({ agentSpec: req.agentSpec as never });\n }\n return toSession(raw);\n },\n\n prepareAndExecuteTurn(req: {\n sessionId: string;\n input?: TurnInputItem[];\n previousTurnId?: PreviousTurnIdInput;\n abortSignal?: AbortSignal;\n headers?: Record<string, string>;\n }): AsyncIterable<TurnStreamData> {\n return (async function* () {\n const session = await getSessionObj(req.sessionId);\n const prepared = session.prepareTurn({\n input: req.input,\n previousTurnId: req.previousTurnId ?? \"auto\",\n });\n yield* prepared.execute(\n { stream: true },\n {\n ...(req.abortSignal != null\n ? { abortSignal: req.abortSignal }\n : {}),\n ...(req.headers != null ? { headers: req.headers } : {}),\n },\n ) as AsyncIterable<TurnStreamData>;\n })();\n },\n\n async cancelSession({ sessionId }) {\n await (await getSessionObj(sessionId)).cancel();\n },\n\n async deleteSession({ sessionId }) {\n if (opts.deleteSession == null) {\n throw new Error(\n \"deleteSession is not on the gateway SDK. Pass deleteSession to createTrueFoundryChatServer.\",\n );\n }\n await opts.deleteSession({ sessionId });\n },\n\n async listTurns({ sessionId, limit, pageToken, order }) {\n const raw = await getSessionObj(sessionId);\n const page = await raw.listTurns({\n ...(limit != null ? { limit } : {}),\n ...(pageToken != null ? { pageToken } : {}),\n ...(order != null ? { order } : {}),\n });\n return toListResult(page, (turn) => toTurn(turn));\n },\n\n async getTurn({ sessionId, turnId }) {\n const raw = await getSessionObj(sessionId);\n return toTurn(await raw.getTurn({ turnId }));\n },\n\n async listEvents({ sessionId, pageToken, lastTurnId, limit }) {\n const raw = await getSessionObj(sessionId);\n const page = await raw.listEvents({\n ...(limit != null ? { limit } : {}),\n ...(pageToken != null ? { pageToken } : {}),\n ...(lastTurnId != null ? { lastTurnId } : {}),\n });\n return toListResult(\n page,\n (item) => item as SessionEventItem,\n );\n },\n\n async listTurnEvents({ sessionId, turnId, limit, pageToken, order }) {\n const raw = await getSessionObj(sessionId);\n const turn = await raw.getTurn({ turnId });\n const page = await turn.listEvents({\n ...(limit != null ? { limit } : {}),\n ...(pageToken != null ? { pageToken } : {}),\n ...(order != null ? { order } : {}),\n });\n return toListResult(page, (event) => event as TurnEvent);\n },\n\n async *subscribeToTurn({\n sessionId,\n turnId,\n afterSequenceNumber,\n abortSignal,\n }) {\n const raw = await getSessionObj(sessionId);\n const turn = await raw.getTurn({ turnId });\n yield* turn.stream(\n afterSequenceNumber != null ? { afterSequenceNumber } : {},\n abortSignal != null ? { abortSignal } : {},\n ) as AsyncIterable<TurnStreamData>;\n },\n\n async downloadSandboxFile(sandboxId, req) {\n const response = await privateClient.downloadSandboxFile(\n sandboxId,\n req,\n );\n return await response.blob();\n },\n\n getGatewayClients: () => ({ client, privateClient }),\n };\n\n return server;\n}\n"],"mappings":";AAAA,SAAS,0BAA0B;AAEnC,SAAS,iCAAiC;AAoC1C,SAAS,QAAQ,SAAkD;AAC/D,SAAQ,QAA8B,SAAS;AACnD;AAEA,SAAS,UAAU,KAAyB;AACxC,QAAM,UAAU,QAAQ,GAAG;AAC3B,SAAO;AAAA,IACH,IAAI,IAAI;AAAA,IACR,OAAO,IAAI;AAAA,IACX,WAAW,IAAI;AAAA,IACf,GAAI,UAAU,EAAE,WAAW,IAAI,UAAuB,IAAI,CAAC;AAAA,IAC3D,WAAW;AAAA,IACX,WAAW,IAAI;AAAA,IACf,WAAW,IAAI;AAAA,EACnB;AACJ;AAEA,SAAS,OAAO,KAOP;AACL,SAAO;AAAA,IACH,IAAI,IAAI;AAAA,IACR,WAAW,IAAI;AAAA,IACf,gBAAgB,IAAI;AAAA,IACpB,OAAO,IAAI;AAAA,IACX,OAAO,IAAI;AAAA,IACX,WAAW,IAAI;AAAA,EACnB;AACJ;AAEA,eAAe,aACX,MAKA,KACyB;AACzB,QAAM,gBAAgB,KAAK,UAAU,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I,CAAC;AAAA,MAC/C,CAAC;AACD,aAAO;AAAA,QACH;AAAA,QACA,CAAC,SAAS;AAAA,MACd;AAAA,IACJ;AAAA,IAEA,MAAM,eAAe,EAAE,WAAW,QAAQ,OAAO,WAAW,MAAM,GAAG;AACjE,YAAM,MAAM,MAAM,cAAc,SAAS;AACzC,YAAM,OAAO,MAAM,IAAI,QAAQ,EAAE,OAAO,CAAC;AACzC,YAAM,OAAO,MAAM,KAAK,WAAW;AAAA,QAC/B,GAAI,SAAS,OAAO,EAAE,MAAM,IAAI,CAAC;AAAA,QACjC,GAAI,aAAa,OAAO,EAAE,UAAU,IAAI,CAAC;AAAA,QACzC,GAAI,SAAS,OAAO,EAAE,MAAM,IAAI,CAAC;AAAA,MACrC,CAAC;AACD,aAAO,aAAa,MAAM,CAAC,UAAU,KAAkB;AAAA,IAC3D;AAAA,IAEA,OAAO,gBAAgB;AAAA,MACnB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACJ,GAAG;AACC,YAAM,MAAM,MAAM,cAAc,SAAS;AACzC,YAAM,OAAO,MAAM,IAAI,QAAQ,EAAE,OAAO,CAAC;AACzC,aAAO,KAAK;AAAA,QACR,uBAAuB,OAAO,EAAE,oBAAoB,IAAI,CAAC;AAAA,QACzD,eAAe,OAAO,EAAE,YAAY,IAAI,CAAC;AAAA,MAC7C;AAAA,IACJ;AAAA,IAEA,MAAM,oBAAoB,WAAW,KAAK;AACtC,YAAM,WAAW,MAAM,cAAc;AAAA,QACjC;AAAA,QACA;AAAA,MACJ;AACA,aAAO,MAAM,SAAS,KAAK;AAAA,IAC/B;AAAA,IAEA,mBAAmB,OAAO,EAAE,QAAQ,cAAc;AAAA,EACtD;AAEA,SAAO;AACX;","names":[]}
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,17 @@
1
+ import { R as TurnStreamingEvent, Y as DeltaEvents, c as TurnEvent } from '../types-DbNsU075.js';
2
+ export { Z as ActionRequiredEvent, h as AgentBuilderServer, b as AgentChatServer, _ as AgentInfo, $ as AgentParent, a0 as AgentSelectorEntry, A as AgentSpec, i as AgentUIServerPort, a1 as ApprovalDecision, j as CatalogServer, a2 as ChunkDeltaToolCall, k as ConnectorAuth, l as ConnectorAuthPublic, m as ConnectorAuthType, n as ConnectorBase, o as ConnectorCatalogEntry, p as ConnectorCatalogServer, q as ConnectorConfigBase, a3 as ConnectorSelectorEntry, r as CreateConnectorRequest, s as CreateModelProviderRequest, C as CreateSessionRequest, t as CreateSkillRequest, u as ListResult, a4 as ListSessionsOrder, L as ListSessionsParams, M as McpAuthRequiredEvent, a5 as McpInitializeEvent, a6 as McpServerAuthInfo, a7 as McpServerMount, a8 as Model, v as ModelCatalogServer, w as ModelEntry, a9 as ModelMessageContentPart, aa as ModelMessageDeltaEvent, x as ModelMessageEvent, ab as ModelParams, y as ModelProviderBase, z as ModelProviderCatalogEntry, B as ModelProviderConfigBase, ac as ModelSelectorEntry, ad as PageParams, P as PreviousTurnIdInput, D as ProviderType, E as SandboxCreatedEvent, ae as SearchAgentSelectorParams, S as Session, F as SessionEventItem, G as SkillBase, H as SkillCatalogServer, af as SkillMount, ag as SkillSelectorEntry, d as ThreadCreatedEvent, ah as ThreadDoneEvent, I as ToolApprovalRequiredEvent, J as ToolBase, K as ToolCall, ai as ToolCallFunction, aj as ToolCallRef, ak as ToolInfo, al as ToolResponseEvent, N as ToolResponseRequiredEvent, T as Turn, am as TurnCreatedEvent, an as TurnDoneEvent, g as TurnInputItem, a as TurnState, ao as TurnStateCancelled, O as TurnStateDone, ap as TurnStateError, aq as TurnStateRunning, Q as TurnStreamData, V as UpdateConnectorRequest, W as UpdateModelProviderRequest, U as UpdateSessionRequest, X as UserMessage, ar as UserMessageContent, f as UserToolApprovalEvent, e as UserToolResponseEvent } from '../types-DbNsU075.js';
3
+
4
+ /**
5
+ * Local implementations of streaming delta helpers.
6
+ * Formerly imported from truefoundry-gateway-sdk/agents.
7
+ */
8
+
9
+ /** True for `.delta` streaming events. */
10
+ declare function isEventDelta(event: TurnStreamingEvent): event is DeltaEvents;
11
+ /**
12
+ * Merge `delta` into `base` in place (same `id` required).
13
+ * Currently handles `model.message.delta` → `model.message`.
14
+ */
15
+ declare function mergeEventDelta(base: TurnEvent, delta: DeltaEvents): void;
16
+
17
+ export { DeltaEvents, TurnEvent, TurnStreamingEvent, isEventDelta, mergeEventDelta };
@@ -0,0 +1,9 @@
1
+ import {
2
+ isEventDelta,
3
+ mergeEventDelta
4
+ } from "../chunk-3A2EPLQG.js";
5
+ export {
6
+ isEventDelta,
7
+ mergeEventDelta
8
+ };
9
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}