@truefoundry/assistant-ui-runtime 0.1.5 → 0.1.6

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 (70) hide show
  1. package/README.md +198 -401
  2. package/dist/chunk-3A2EPLQG.js +93 -0
  3. package/dist/chunk-3A2EPLQG.js.map +1 -0
  4. package/dist/chunk-Q2SHKMLM.js +270 -0
  5. package/dist/chunk-Q2SHKMLM.js.map +1 -0
  6. package/dist/index.d.ts +24 -29
  7. package/dist/index.js +264 -237
  8. package/dist/index.js.map +1 -1
  9. package/dist/plugins/truefoundry-agent-server-adapter/index.d.ts +162 -0
  10. package/dist/plugins/truefoundry-agent-server-adapter/index.js +19 -0
  11. package/dist/plugins/truefoundry-agent-server-adapter/index.js.map +1 -0
  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-BfiFf8O1.d.ts +468 -0
  16. package/package.json +19 -6
  17. package/src/askUserQuestion.ts +3 -3
  18. package/src/buildEditedUserMessageContent.test.ts +2 -2
  19. package/src/collectPending.ts +1 -1
  20. package/src/convertTurnMessages.test.ts +141 -196
  21. package/src/convertTurnMessages.ts +130 -76
  22. package/src/createSubAgent.ts +1 -1
  23. package/src/draftAgentConfig.test.ts +26 -29
  24. package/src/extractTurnUserText.ts +1 -1
  25. package/src/foldPeerThreads.test.ts +1 -1
  26. package/src/foldPeerThreads.ts +3 -2
  27. package/src/index.ts +80 -4
  28. package/src/listPages.ts +21 -0
  29. package/src/loadSessionSnapshot.test.ts +9 -8
  30. package/src/loadSessionSnapshot.ts +9 -14
  31. package/src/mcpAuth.ts +6 -3
  32. package/src/messageCustomMetadata.ts +1 -1
  33. package/src/modelMessageContent.ts +1 -1
  34. package/src/modelMessageImageContent.test.ts +1 -1
  35. package/src/modelMessageImageContent.ts +7 -6
  36. package/src/plugins/truefoundry-agent-server-adapter/README.md +178 -0
  37. package/src/plugins/truefoundry-agent-server-adapter/guards.test.ts +113 -0
  38. package/src/plugins/truefoundry-agent-server-adapter/guards.ts +130 -0
  39. package/src/plugins/truefoundry-agent-server-adapter/index.ts +359 -0
  40. package/src/plugins/truefoundry-agent-server-adapter/types.ts +135 -0
  41. package/src/plugins/truefoundry-agent-server-adapter/types.typecheck.ts +164 -0
  42. package/src/private/agentSpec.ts +8 -3
  43. package/src/private/draftSessionBridge.ts +14 -13
  44. package/src/private/truefoundryDraftThreadListAdapter.test.ts +44 -49
  45. package/src/private/truefoundryDraftThreadListAdapter.ts +22 -16
  46. package/src/requiredActionInputs.ts +1 -1
  47. package/src/requiredActionsFromActiveUpdate.test.ts +1 -1
  48. package/src/server/eventUtils.ts +120 -0
  49. package/src/server/events.ts +246 -0
  50. package/src/server/index.ts +66 -0
  51. package/src/server/types.ts +319 -0
  52. package/src/sessionSnapshot.ts +1 -1
  53. package/src/sessions.ts +5 -21
  54. package/src/streamTurn.test.ts +172 -155
  55. package/src/streamTurn.ts +51 -48
  56. package/src/toolApproval.ts +4 -4
  57. package/src/toolResponse.ts +4 -4
  58. package/src/truefoundryExtras.ts +1 -1
  59. package/src/truefoundryOwnedSessionsThreadListAdapter.test.ts +26 -29
  60. package/src/truefoundryOwnedSessionsThreadListAdapter.ts +18 -23
  61. package/src/truefoundryThreadListAdapter.test.ts +16 -18
  62. package/src/truefoundryThreadListAdapter.ts +7 -7
  63. package/src/turnEventHelpers.ts +1 -1
  64. package/src/types.ts +2 -16
  65. package/src/useTrueFoundryAgentMessages.test.tsx +38 -70
  66. package/src/useTrueFoundryAgentMessages.ts +32 -44
  67. package/src/useTrueFoundryAgentRuntime.ts +11 -28
  68. package/src/private/bindDraftAgentSession.test.ts +0 -54
  69. package/src/private/bindDraftAgentSession.ts +0 -28
  70. package/src/private/getGatewayFromPrivateClient.ts +0 -13
@@ -0,0 +1,162 @@
1
+ import { AgentSessionClient } from 'truefoundry-gateway-sdk/agents';
2
+ import { PrivateAgentSessionClient } from 'truefoundry-gateway-sdk/agents/private';
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-BfiFf8O1.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 {
33
+ model: TruefoundryGatewayApi.Model;
34
+ skills?: TfySkillMount[];
35
+ mcpServers?: TfyMcpServerMount[];
36
+ config?: TruefoundryGatewayApi.RuntimeConfig;
37
+ responseFormat?: TruefoundryGatewayApi.ResponseFormat;
38
+ messages?: TruefoundryGatewayApi.AgentSpecUserMessage[];
39
+ }
40
+ type TfyTurnCancelledReason = TruefoundryGatewayApi.TurnStateCancelledReason;
41
+ type TfyTurnStateDoneOutput = TruefoundryGatewayApi.TurnStateDoneOutput;
42
+ type RuntimeTurnStateDone = Extract<TurnState, {
43
+ status: "done";
44
+ }>;
45
+ type RuntimeTurnStateCancelled = Extract<TurnState, {
46
+ status: "cancelled";
47
+ }>;
48
+ /**
49
+ * The runtime types `output` as `unknown` and `reason` as bare `string`. The
50
+ * gateway sends a model message and one of four reasons — `cancelled-for-next-turn`
51
+ * in particular is routine and should not render like a failure.
52
+ */
53
+ type TfyTurnState = Exclude<TurnState, {
54
+ status: "done" | "cancelled";
55
+ }> | (Omit<RuntimeTurnStateDone, "output"> & {
56
+ output?: TfyTurnStateDoneOutput;
57
+ }) | (Omit<RuntimeTurnStateCancelled, "reason"> & {
58
+ reason: TfyTurnCancelledReason;
59
+ });
60
+ interface TfyTurn extends Turn {
61
+ state: TfyTurnState;
62
+ createdBySubject: TfySubject;
63
+ }
64
+ interface TfySession<TSpec extends TfyAgentSpec = TfyAgentSpec> extends Session<TSpec> {
65
+ createdBySubject: TfySubject;
66
+ }
67
+ interface TfyCreateSessionRequest<TSpec extends TfyAgentSpec = TfyAgentSpec> extends CreateSessionRequest<TSpec> {
68
+ /** Sent as `x-tfy-metadata`, persisted server-side as `request_metadata`. */
69
+ tfyMetadata?: string;
70
+ }
71
+ interface TfyListSessionsParams extends ListSessionsParams {
72
+ /** Inclusive upper bound on `createdAt` (ISO-8601). */
73
+ endTimestamp?: string;
74
+ }
75
+ type TfyToolInfo = TruefoundryGatewayApi.ToolInfo;
76
+ type TfySystemToolInfo = TruefoundryGatewayApi.TrueFoundrySystemToolInfo;
77
+ type TfyMcpToolInfo = TruefoundryGatewayApi.McpToolInfo;
78
+ type TfyModelMessageUsage = TruefoundryGatewayApi.ModelMessageUsage;
79
+ type TfyFinishReason = TruefoundryGatewayApi.FinishReason;
80
+ type TfyThreadState = TruefoundryGatewayApi.ThreadState;
81
+ type TfyMcpServerInitInfo = TruefoundryGatewayApi.McpServerInitInfo;
82
+
83
+ /**
84
+ * Point-of-use narrowing for the event half of the gateway protocol.
85
+ *
86
+ * `AgentChatServer` hardcodes the runtime's event types on listEvents,
87
+ * listTurnEvents, subscribeToTurn and prepareAndExecuteTurn — there is no
88
+ * generic to override them from here. So instead of typing those channels,
89
+ * hosts call these guards on the values they receive.
90
+ *
91
+ * They validate rather than cast: this data comes off the network, and the
92
+ * runtime types the relevant fields as `unknown` precisely because nothing
93
+ * has checked them yet.
94
+ */
95
+
96
+ /**
97
+ * Identifies built-in tools such as `ask_user_question` and `create_sub_agent`.
98
+ * Note `toolInfo` is legitimately absent on streamed deltas, so callers must
99
+ * keep their `function.name` fallback rather than treating absence as an error.
100
+ */
101
+ declare function isTfySystemToolInfo(toolInfo: unknown): toolInfo is TfySystemToolInfo;
102
+ /** Carries `serverId` / `serverName`, so the UI can attribute a call to its MCP server. */
103
+ declare function isTfyMcpToolInfo(toolInfo: unknown): toolInfo is TfyMcpToolInfo;
104
+ declare function isTfyToolInfo(toolInfo: unknown): toolInfo is TfyToolInfo;
105
+ /**
106
+ * Token usage including the TrueFoundry-specific `inputTokensBreakdown`, which
107
+ * attributes input tokens across harness, skills, instructions, tool
108
+ * definitions and messages.
109
+ */
110
+ declare function getTfyUsage(source: {
111
+ usage?: unknown;
112
+ } | null | undefined): TfyModelMessageUsage | undefined;
113
+ /**
114
+ * Completion state of a sub-agent thread. The runtime types `thread.done`'s
115
+ * `state` as `unknown`, so a sub-agent that errored is otherwise
116
+ * indistinguishable from one that succeeded.
117
+ */
118
+ declare function getTfyThreadState(event: {
119
+ state?: unknown;
120
+ } | null | undefined): TfyThreadState | undefined;
121
+ /**
122
+ * Servers from an `mcp.initialize` event, including each one's `transportType`.
123
+ * The runtime models this event with an index signature, so the array is
124
+ * `unknown` until checked.
125
+ */
126
+ declare function getTfyMcpInitServers(event: {
127
+ mcpServers?: unknown;
128
+ } | null | undefined): TfyMcpServerInitInfo[] | undefined;
129
+
130
+ type CreateTrueFoundryChatServerOptions = {
131
+ apiKey: string;
132
+ baseUrl: string;
133
+ /** Optional override — otherwise constructed from apiKey/baseUrl. */
134
+ client?: AgentSessionClient;
135
+ privateClient?: PrivateAgentSessionClient;
136
+ deleteSession?: (req: {
137
+ sessionId: string;
138
+ }) => Promise<void>;
139
+ };
140
+ /**
141
+ * Only the spec is generic. Session/Turn/list-params are the concrete Tfy*
142
+ * types because the adapter builds them as fixed object literals — a generic
143
+ * there would type fields that nothing ever populates. The spec is safe: the
144
+ * gateway SDK serializes with `unrecognizedObjectKeys: "passthrough"`, so
145
+ * host-added spec fields survive the round trip.
146
+ */
147
+ type TrueFoundryChatServer<TSpec extends TfyAgentSpec = TfyAgentSpec> = AgentChatServer<TSpec, TfySession<TSpec>, TfyCreateSessionRequest<TSpec>, TfyListSessionsParams, UpdateSessionRequest<TSpec>, TfyTurn> & {
148
+ /** Escape hatch for hosts that still need raw gateway clients. */
149
+ getGatewayClients(): {
150
+ client: AgentSessionClient;
151
+ privateClient: PrivateAgentSessionClient;
152
+ };
153
+ };
154
+ /**
155
+ * Wraps TrueFoundry gateway clients into a flat `AgentChatServer`.
156
+ * Named vs draft routing is fully internal — an in-memory session-type cache
157
+ * (populated by createSession/listSessions) determines which gateway client
158
+ * to call. No try/catch fallback, no double network calls.
159
+ */
160
+ declare function createTrueFoundryChatServer<TSpec extends TfyAgentSpec = TfyAgentSpec>(opts: CreateTrueFoundryChatServerOptions): TrueFoundryChatServer<TSpec>;
161
+
162
+ 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 };
@@ -0,0 +1,19 @@
1
+ import {
2
+ createTrueFoundryChatServer,
3
+ getTfyMcpInitServers,
4
+ getTfyThreadState,
5
+ getTfyUsage,
6
+ isTfyMcpToolInfo,
7
+ isTfySystemToolInfo,
8
+ isTfyToolInfo
9
+ } from "../../chunk-Q2SHKMLM.js";
10
+ export {
11
+ createTrueFoundryChatServer,
12
+ getTfyMcpInitServers,
13
+ getTfyThreadState,
14
+ getTfyUsage,
15
+ isTfyMcpToolInfo,
16
+ isTfySystemToolInfo,
17
+ isTfyToolInfo
18
+ };
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,17 @@
1
+ import { r as TurnStreamingEvent, D as DeltaEvents, c as TurnEvent } from '../types-BfiFf8O1.js';
2
+ export { t as ActionRequiredEvent, h as AgentBuilderServer, b as AgentChatServer, u as AgentInfo, v as AgentParent, w as AgentSelectorEntry, A as AgentSpec, x as ApprovalDecision, y as ChunkDeltaToolCall, z as ConnectorSelectorEntry, C as CreateSessionRequest, i as ListResult, B as ListSessionsOrder, L as ListSessionsParams, M as McpAuthRequiredEvent, E as McpInitializeEvent, F as McpServerAuthInfo, G as McpServerMount, H as Model, I as ModelMessageContentPart, J as ModelMessageDeltaEvent, j as ModelMessageEvent, K as ModelParams, N as ModelSelectorEntry, O as PageParams, P as PreviousTurnIdInput, k as SandboxCreatedEvent, Q as SearchAgentSelectorParams, S as Session, l as SessionEventItem, R as SkillMount, V as SkillSelectorEntry, d as ThreadCreatedEvent, W as ThreadDoneEvent, m as ToolApprovalRequiredEvent, n as ToolCall, X as ToolCallFunction, Y as ToolCallRef, Z as ToolInfo, _ as ToolResponseEvent, o as ToolResponseRequiredEvent, T as Turn, $ as TurnCreatedEvent, a0 as TurnDoneEvent, g as TurnInputItem, a as TurnState, a1 as TurnStateCancelled, p as TurnStateDone, a2 as TurnStateError, a3 as TurnStateRunning, q as TurnStreamData, U as UpdateSessionRequest, s as UserMessage, a4 as UserMessageContent, f as UserToolApprovalEvent, e as UserToolResponseEvent } from '../types-BfiFf8O1.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":[]}
@@ -0,0 +1,468 @@
1
+ /**
2
+ * Runtime-owned turn/stream event protocol.
3
+ *
4
+ * Hosts must emit events matching these shapes. The TFY adapter maps
5
+ * truefoundry-gateway-sdk events 1:1 onto these types.
6
+ */
7
+
8
+ interface ToolCallFunction {
9
+ name: string;
10
+ arguments: string;
11
+ }
12
+ type ToolInfo = {
13
+ type: "truefoundry-system";
14
+ name: string;
15
+ } | {
16
+ type: "mcp";
17
+ serverId: string;
18
+ serverName: string;
19
+ name: string;
20
+ } | {
21
+ type: string;
22
+ name?: string;
23
+ [key: string]: unknown;
24
+ };
25
+ interface ToolCall {
26
+ id: string;
27
+ type: "function";
28
+ function: ToolCallFunction;
29
+ toolInfo?: ToolInfo;
30
+ providerSpecificFields?: Record<string, unknown>;
31
+ }
32
+ /** Ref used by approval/response-required events. */
33
+ interface ToolCallRef {
34
+ id: string;
35
+ sourceEventId: string;
36
+ }
37
+ interface ChunkDeltaToolCall {
38
+ index: number;
39
+ id?: string;
40
+ type?: "function";
41
+ function?: {
42
+ name?: string;
43
+ arguments?: string;
44
+ };
45
+ toolInfo?: ToolInfo;
46
+ providerSpecificFields?: Record<string, unknown>;
47
+ }
48
+ type ModelMessageContentPart = {
49
+ type: "text";
50
+ text: string;
51
+ } | {
52
+ type: "refusal";
53
+ refusal: string;
54
+ } | {
55
+ type: "image_url";
56
+ image_url: {
57
+ url: string;
58
+ };
59
+ };
60
+ interface ModelMessageEvent {
61
+ type: "model.message";
62
+ id: string;
63
+ threadId: string;
64
+ content?: string | ModelMessageContentPart[] | null;
65
+ name?: string;
66
+ refusal?: string | null;
67
+ reasoningContent?: string;
68
+ toolCalls?: ToolCall[];
69
+ finishReason?: string | null;
70
+ createdAt: string;
71
+ usage?: unknown;
72
+ }
73
+ interface ModelMessageDeltaEvent {
74
+ type: "model.message.delta";
75
+ id: string;
76
+ threadId: string;
77
+ content?: string | null;
78
+ refusal?: string | null;
79
+ reasoningContent?: string;
80
+ toolCalls?: ChunkDeltaToolCall[];
81
+ finishReason?: string | null;
82
+ createdAt?: string;
83
+ usage?: unknown;
84
+ /** Extended content-block deltas (image streaming). */
85
+ contentBlocks?: Array<{
86
+ index: number;
87
+ delta: {
88
+ type: "text";
89
+ text?: string;
90
+ } | {
91
+ type: "image_url";
92
+ image_url?: {
93
+ url?: string;
94
+ };
95
+ };
96
+ }>;
97
+ content_blocks?: Array<{
98
+ index: number;
99
+ delta: {
100
+ type: "text";
101
+ text?: string;
102
+ } | {
103
+ type: "image_url";
104
+ image_url?: {
105
+ url?: string;
106
+ };
107
+ };
108
+ }>;
109
+ }
110
+ interface ToolResponseEvent {
111
+ type: "tool.response";
112
+ id: string;
113
+ threadId: string;
114
+ toolCallId: string;
115
+ content: string;
116
+ createdAt: string;
117
+ }
118
+ interface ToolApprovalRequiredEvent {
119
+ type: "tool.approval_required";
120
+ id: string;
121
+ createdAt: string;
122
+ threadId: string;
123
+ toolCalls: ToolCallRef[];
124
+ }
125
+ interface ToolResponseRequiredEvent {
126
+ type: "tool.response_required";
127
+ id: string;
128
+ createdAt: string;
129
+ threadId: string;
130
+ toolCalls: ToolCallRef[];
131
+ }
132
+ interface AgentInfo {
133
+ type?: string;
134
+ name: string;
135
+ input: string;
136
+ model?: string;
137
+ }
138
+ interface AgentParent {
139
+ threadId: string;
140
+ toolCallId: string;
141
+ }
142
+ interface ThreadCreatedEvent {
143
+ type: "thread.created";
144
+ id: string;
145
+ threadId: string;
146
+ title: string;
147
+ agentInfo: AgentInfo;
148
+ parent: AgentParent;
149
+ createdAt: string;
150
+ }
151
+ interface ThreadDoneEvent {
152
+ type: "thread.done";
153
+ id: string;
154
+ threadId: string;
155
+ title?: string;
156
+ createdAt: string;
157
+ state?: unknown;
158
+ }
159
+ interface McpServerAuthInfo {
160
+ id: string;
161
+ name: string;
162
+ authUrl: string;
163
+ }
164
+ interface McpAuthRequiredEvent {
165
+ type: "mcp.auth_required";
166
+ id: string;
167
+ createdAt: string;
168
+ threadId?: string | null;
169
+ mcpServers: McpServerAuthInfo[];
170
+ }
171
+ interface SandboxCreatedEvent {
172
+ type: "sandbox.created";
173
+ id: string;
174
+ createdAt: string;
175
+ sandboxId: string;
176
+ threadId: string | null;
177
+ }
178
+ interface McpInitializeEvent {
179
+ type: "mcp.initialize";
180
+ id: string;
181
+ createdAt: string;
182
+ threadId: string | null;
183
+ [key: string]: unknown;
184
+ }
185
+ interface TurnCreatedEvent {
186
+ type: "turn.created";
187
+ id: string;
188
+ turnId: string;
189
+ previousTurnId?: string | null;
190
+ input?: TurnInputItem[];
191
+ state?: {
192
+ status: "running";
193
+ };
194
+ createdAt: string;
195
+ threadId?: string | null;
196
+ }
197
+ interface TurnDoneEvent {
198
+ type: "turn.done";
199
+ id: string;
200
+ state: Exclude<TurnState, {
201
+ status: "running";
202
+ }>;
203
+ createdAt: string;
204
+ threadId?: string | null;
205
+ }
206
+ /** Events stored in fold buckets (non-delta, non-turn-lifecycle). */
207
+ type TurnEvent = ModelMessageEvent | ToolResponseEvent | ThreadCreatedEvent | ThreadDoneEvent | McpAuthRequiredEvent | McpInitializeEvent | SandboxCreatedEvent | ToolApprovalRequiredEvent | ToolResponseRequiredEvent;
208
+ /** Full streaming event union (includes deltas + turn lifecycle). */
209
+ type TurnStreamingEvent = TurnEvent | ModelMessageDeltaEvent | TurnCreatedEvent | TurnDoneEvent;
210
+ type ActionRequiredEvent = ToolApprovalRequiredEvent | ToolResponseRequiredEvent | McpAuthRequiredEvent;
211
+ interface TurnStreamData<TStreamEvent extends TurnStreamingEvent = TurnStreamingEvent> {
212
+ sequenceNumber: number;
213
+ event: TStreamEvent;
214
+ }
215
+ /** Session-level event item from `listEvents`. */
216
+ interface SessionEventItem {
217
+ turnId: string;
218
+ event: TurnCreatedEvent | TurnDoneEvent | TurnEvent;
219
+ }
220
+ type DeltaEvents = ModelMessageDeltaEvent;
221
+
222
+ /**
223
+ * FE-owned AgentUIServer contract.
224
+ *
225
+ * Rule: only methods/fields the runtime or UI invokes.
226
+ * Hosts extend via `T extends Base` for system-specific extras.
227
+ * No dependency on truefoundry-gateway-sdk.
228
+ */
229
+
230
+ /** Model selector row. Host extends for apiModel, modelId, pricing, etc. */
231
+ interface ModelSelectorEntry {
232
+ name: string;
233
+ provider: string;
234
+ }
235
+ /** Skill selector row. Host extends for fqn, preload, etc. */
236
+ interface SkillSelectorEntry {
237
+ id: string;
238
+ name: string;
239
+ description?: string;
240
+ }
241
+ /** MCP connector selector row. Host extends for type, enableTools, url, etc. */
242
+ interface ConnectorSelectorEntry {
243
+ id: string;
244
+ name: string;
245
+ description?: string;
246
+ }
247
+ /** Agent selector row — UI shows name only. Host extends for metadata. */
248
+ interface AgentSelectorEntry {
249
+ name: string;
250
+ }
251
+ type SearchAgentSelectorParams = {
252
+ query?: string;
253
+ limit?: number;
254
+ offset?: number;
255
+ };
256
+ /**
257
+ * Mounts written to AgentSpec.skills[] / AgentSpec.mcpServers[].
258
+ *
259
+ * These are opaque to the runtime — it stores and forwards them but never reads
260
+ * a field, and the backend owns the shape (the gateway identifies a skill by
261
+ * `fqn`, with no `id` or `name` anywhere). So the base constrains only that a
262
+ * mount is an object; hosts intersect their concrete mount type over it, as
263
+ * `TfySkillMount` / `TfyMcpServerMount` do in the gateway adapter.
264
+ *
265
+ * Naming a field here would not just be unread, it would be wrong: a base with
266
+ * required fields rejects the backend's own payloads, and one with only optional
267
+ * fields is a weak type, which TypeScript rejects for a source that shares no
268
+ * property with it — the gateway's registry skill shares none.
269
+ */
270
+ type SkillMount = object;
271
+ type McpServerMount = object;
272
+ interface ModelParams {
273
+ maxTokens?: number;
274
+ reasoningEffort?: string;
275
+ }
276
+ interface Model {
277
+ name: string;
278
+ params?: ModelParams;
279
+ }
280
+ /**
281
+ * SDK-owned agent definition — fields the FE reads/writes.
282
+ * Host adds additional fields via `TSpec extends AgentSpec`.
283
+ */
284
+ interface AgentSpec {
285
+ model: Model;
286
+ skills?: SkillMount[];
287
+ mcpServers?: McpServerMount[];
288
+ instructions?: string;
289
+ messages?: unknown[];
290
+ variables?: Record<string, string>;
291
+ responseFormat?: unknown;
292
+ config?: unknown;
293
+ }
294
+ interface Session<TSpec extends AgentSpec = AgentSpec> {
295
+ id: string;
296
+ title?: string | null;
297
+ agentName?: string | null;
298
+ agentSpec?: TSpec;
299
+ /** true → mutable builder + updateSession(spec) allowed. */
300
+ isMutable: boolean;
301
+ createdAt: string;
302
+ updatedAt: string;
303
+ }
304
+ interface CreateSessionRequest<TSpec extends AgentSpec = AgentSpec> {
305
+ agentName?: string;
306
+ agentSpec?: TSpec;
307
+ title?: string;
308
+ }
309
+ interface UpdateSessionRequest<TSpec extends AgentSpec = AgentSpec> {
310
+ sessionId: string;
311
+ agentSpec?: TSpec;
312
+ title?: string;
313
+ }
314
+ interface ListResult<T> {
315
+ data: T[];
316
+ nextPageToken?: string;
317
+ }
318
+ type ListSessionsOrder = "asc" | "desc";
319
+ type PageParams = {
320
+ limit?: number;
321
+ order?: ListSessionsOrder;
322
+ pageToken?: string;
323
+ };
324
+ interface ListSessionsParams extends PageParams {
325
+ agentName?: string;
326
+ /** Host-specific filter (e.g. TFY startTimestamp). */
327
+ startTimestamp?: string;
328
+ }
329
+ type PreviousTurnIdInput = "auto" | string;
330
+ type UserMessageContent = string | Array<{
331
+ type: "text";
332
+ text: string;
333
+ } | {
334
+ type: "file";
335
+ name: string;
336
+ data: string;
337
+ }>;
338
+ interface UserMessage {
339
+ type: "user.message";
340
+ content: UserMessageContent;
341
+ }
342
+ type ApprovalDecision = {
343
+ status: "allow";
344
+ } | {
345
+ status: "deny";
346
+ reason?: string;
347
+ };
348
+ interface UserToolApprovalEvent {
349
+ type: "user.tool_approval";
350
+ threadId: string;
351
+ toolCallId: string;
352
+ approval: ApprovalDecision;
353
+ }
354
+ interface UserToolResponseEvent {
355
+ type: "user.tool_response";
356
+ threadId: string;
357
+ toolCallId: string;
358
+ content: string;
359
+ }
360
+ type TurnInputItem = UserMessage | UserToolApprovalEvent | UserToolResponseEvent;
361
+ type TurnStateRunning = {
362
+ status: "running";
363
+ };
364
+ type TurnStateDone = {
365
+ status: "done";
366
+ output?: unknown;
367
+ requiredActions?: ActionRequiredEvent[];
368
+ completedAt: string;
369
+ };
370
+ type TurnStateCancelled = {
371
+ status: "cancelled";
372
+ reason: string;
373
+ completedAt: string;
374
+ };
375
+ type TurnStateError = {
376
+ status: "error";
377
+ message: string;
378
+ completedAt: string;
379
+ };
380
+ type TurnState = TurnStateRunning | TurnStateDone | TurnStateCancelled | TurnStateError;
381
+ /** Plain turn DTO — no methods. */
382
+ interface Turn {
383
+ id: string;
384
+ sessionId: string;
385
+ previousTurnId?: string | null;
386
+ input?: TurnInputItem[];
387
+ state: TurnState;
388
+ createdAt: string;
389
+ }
390
+ /**
391
+ * Chat / session port — the runtime calls these.
392
+ *
393
+ * All session ops are flat (sessionId param). No gateway client dependency.
394
+ * `createTrueFoundryServer` is one possible implementation (TFY adapter).
395
+ */
396
+ interface AgentChatServer<TSpec extends AgentSpec = AgentSpec, TSession extends Session<TSpec> = Session<TSpec>, TCreate extends CreateSessionRequest<TSpec> = CreateSessionRequest<TSpec>, TList extends ListSessionsParams = ListSessionsParams, TUpdate extends UpdateSessionRequest<TSpec> = UpdateSessionRequest<TSpec>, TTurn extends Turn = Turn> {
397
+ createSession(req: TCreate): Promise<TSession>;
398
+ listSessions(req?: TList): Promise<ListResult<TSession>>;
399
+ getSession(req: {
400
+ sessionId: string;
401
+ }): Promise<TSession>;
402
+ updateSession(req: TUpdate): Promise<TSession>;
403
+ prepareAndExecuteTurn(req: {
404
+ sessionId: string;
405
+ input?: TurnInputItem[];
406
+ previousTurnId?: PreviousTurnIdInput;
407
+ abortSignal?: AbortSignal;
408
+ headers?: Record<string, string>;
409
+ }): AsyncIterable<TurnStreamData>;
410
+ cancelSession(req: {
411
+ sessionId: string;
412
+ }): Promise<void>;
413
+ deleteSession?(req: {
414
+ sessionId: string;
415
+ }): Promise<void>;
416
+ listTurns(req: {
417
+ sessionId: string;
418
+ limit?: number;
419
+ pageToken?: string;
420
+ order?: ListSessionsOrder;
421
+ }): Promise<ListResult<TTurn>>;
422
+ getTurn(req: {
423
+ sessionId: string;
424
+ turnId: string;
425
+ }): Promise<TTurn>;
426
+ listEvents(req: {
427
+ sessionId: string;
428
+ pageToken?: string;
429
+ lastTurnId?: string;
430
+ limit?: number;
431
+ }): Promise<ListResult<SessionEventItem>>;
432
+ /** Optional per-turn event listing (hydrate in-flight turn content). */
433
+ listTurnEvents?(req: {
434
+ sessionId: string;
435
+ turnId: string;
436
+ limit?: number;
437
+ pageToken?: string;
438
+ order?: ListSessionsOrder;
439
+ }): Promise<ListResult<TurnEvent>>;
440
+ subscribeToTurn?(req: {
441
+ sessionId: string;
442
+ turnId: string;
443
+ afterSequenceNumber?: number;
444
+ abortSignal?: AbortSignal;
445
+ }): AsyncIterable<TurnStreamData>;
446
+ downloadSandboxFile?(sandboxId: string, req: {
447
+ path: string;
448
+ }): Promise<Blob>;
449
+ }
450
+ /**
451
+ * Builder catalog + persist port — atoms call these.
452
+ * Passed separately from the runtime's chat server.
453
+ */
454
+ interface AgentBuilderServer<TSpec extends AgentSpec = AgentSpec, TModel extends ModelSelectorEntry = ModelSelectorEntry, TSkill extends SkillSelectorEntry = SkillSelectorEntry, TMcp extends ConnectorSelectorEntry = ConnectorSelectorEntry, TAgent extends AgentSelectorEntry = AgentSelectorEntry, TSave = unknown> {
455
+ getModels(): Promise<TModel[]>;
456
+ getSkills(): Promise<TSkill[]>;
457
+ getMcp(): Promise<TMcp[]>;
458
+ searchAgents(req?: SearchAgentSelectorParams): Promise<TAgent[]>;
459
+ saveAgent(req: {
460
+ agentName: string;
461
+ agentSpec: TSpec;
462
+ }): Promise<TSave>;
463
+ deleteAgent?(req: {
464
+ agentName: string;
465
+ }): Promise<void>;
466
+ }
467
+
468
+ export type { TurnCreatedEvent as $, AgentSpec as A, ListSessionsOrder as B, CreateSessionRequest as C, DeltaEvents as D, McpInitializeEvent as E, McpServerAuthInfo as F, McpServerMount as G, Model as H, ModelMessageContentPart as I, ModelMessageDeltaEvent as J, ModelParams as K, ListSessionsParams as L, McpAuthRequiredEvent as M, ModelSelectorEntry as N, PageParams as O, PreviousTurnIdInput as P, SearchAgentSelectorParams as Q, SkillMount as R, Session as S, Turn as T, UpdateSessionRequest as U, SkillSelectorEntry as V, ThreadDoneEvent as W, ToolCallFunction as X, ToolCallRef as Y, ToolInfo as Z, ToolResponseEvent as _, TurnState as a, TurnDoneEvent as a0, TurnStateCancelled as a1, TurnStateError as a2, TurnStateRunning as a3, UserMessageContent as a4, AgentChatServer as b, TurnEvent as c, ThreadCreatedEvent as d, UserToolResponseEvent as e, UserToolApprovalEvent as f, TurnInputItem as g, AgentBuilderServer as h, ListResult as i, ModelMessageEvent as j, SandboxCreatedEvent as k, SessionEventItem as l, ToolApprovalRequiredEvent as m, ToolCall as n, ToolResponseRequiredEvent as o, TurnStateDone as p, TurnStreamData as q, TurnStreamingEvent as r, UserMessage as s, ActionRequiredEvent as t, AgentInfo as u, AgentParent as v, AgentSelectorEntry as w, ApprovalDecision as x, ChunkDeltaToolCall as y, ConnectorSelectorEntry as z };