veryfront 0.1.479 → 0.1.481

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.
@@ -0,0 +1,326 @@
1
+ import * as dntShim from "../../_dnt.shims.js";
2
+ import {
3
+ type HostToolSet,
4
+ type RemoteMCPToolSourceConfig,
5
+ type RemoteToolSource,
6
+ } from "../tool/index.js";
7
+ import { runWithRequestContextAsync, serverLogger } from "../utils/index.js";
8
+ import {
9
+ resolveVeryfrontCloudModelId,
10
+ resolveVeryfrontCloudThinkingProviderOptions,
11
+ } from "../provider/veryfront-cloud/model-catalog.js";
12
+ import {
13
+ runWithVeryfrontCloudContext,
14
+ runWithVeryfrontCloudContextAsync,
15
+ type VeryfrontCloudContext,
16
+ } from "../provider/veryfront-cloud/context.js";
17
+ import { agent } from "./factory.js";
18
+ import {
19
+ applyDefaultResearchArtifactPath,
20
+ createDefaultResearchRunArtifactMirrorHandler,
21
+ shouldRetryCreateResearchArtifactAsUpdate,
22
+ } from "./default-research-artifact-support.js";
23
+ import { createHostedChatRuntimeAgentAdapter } from "./hosted-chat-runtime-agent-adapter.js";
24
+ import type {
25
+ HostedChatRuntimeCreationOptions,
26
+ HostedChatRuntimeCreationResult,
27
+ } from "./hosted-chat-runtime-contract.js";
28
+ import {
29
+ type HostedChatRuntimeToolAssemblyResult,
30
+ prepareHostedChatRuntimeToolAssembly,
31
+ type PrepareHostedChatRuntimeToolAssemblyInput,
32
+ } from "./hosted-chat-runtime-tool-assembly.js";
33
+ import {
34
+ createHostedRuntimeStateResolver,
35
+ type HostedRuntimeStateResolverContext,
36
+ } from "./hosted-runtime-state-resolver.js";
37
+ import type { ProjectSteeringMutationResult } from "./project-steering-mutation.js";
38
+ import type {
39
+ RuntimeAgentMarkdownDefinition,
40
+ RuntimeAgentThinkingConfig,
41
+ } from "./runtime-agent-definition.js";
42
+ import type { AgentConfig } from "./types.js";
43
+
44
+ export type DefaultHostedChatRuntimeConfig = {
45
+ apiUrl: string;
46
+ apiMcpUrl: string;
47
+ studioMcpUrl?: string | null;
48
+ };
49
+
50
+ export type DefaultHostedChatRuntimeLogger = {
51
+ warn(message: string, metadata?: Record<string, unknown>): void;
52
+ };
53
+
54
+ export type DefaultHostedChatRuntimeCreationOptions =
55
+ & HostedChatRuntimeCreationOptions<
56
+ RuntimeAgentMarkdownDefinition,
57
+ RuntimeAgentThinkingConfig
58
+ >
59
+ & {
60
+ userId?: string;
61
+ };
62
+
63
+ export type DefaultHostedChatRuntimeTaskContext = HostedRuntimeStateResolverContext & {
64
+ authToken: string;
65
+ projectId: string;
66
+ branchId: string | null;
67
+ model: string | undefined;
68
+ clientProfile?: DefaultHostedChatRuntimeCreationOptions["clientProfile"];
69
+ conversationId?: string;
70
+ userId?: string;
71
+ parentRunId?: string;
72
+ parentMessageId?: string;
73
+ availableSkillIds?: string[];
74
+ publishParentRunEvents?: DefaultHostedChatRuntimeCreationOptions["publishParentRunEvents"];
75
+ availableToolNames?: string[];
76
+ };
77
+
78
+ export type CreateDefaultHostedChatRuntimeContextInput = {
79
+ options: DefaultHostedChatRuntimeCreationOptions;
80
+ modelId: string;
81
+ };
82
+
83
+ export type DefaultHostedChatRuntimeSystemRefreshInput = {
84
+ taskContext: DefaultHostedChatRuntimeTaskContext;
85
+ liveProjectSteering: NonNullable<DefaultHostedChatRuntimeCreationOptions["liveProjectSteering"]>;
86
+ toolAssembly: HostedChatRuntimeToolAssemblyResult;
87
+ };
88
+
89
+ export type DefaultHostedChatRuntimeSteeringMutationInput = {
90
+ mutation: ProjectSteeringMutationResult;
91
+ taskContext: DefaultHostedChatRuntimeTaskContext;
92
+ };
93
+
94
+ export type DefaultHostedChatRuntimeProjectSwitchInput = {
95
+ projectId: string;
96
+ taskContext: DefaultHostedChatRuntimeTaskContext;
97
+ };
98
+
99
+ export type CreateDefaultHostedChatRuntimeOptions = {
100
+ options: DefaultHostedChatRuntimeCreationOptions;
101
+ config: DefaultHostedChatRuntimeConfig;
102
+ buildLocalTools: (taskContext: DefaultHostedChatRuntimeTaskContext) => HostToolSet;
103
+ createTaskContext?: (
104
+ input: CreateDefaultHostedChatRuntimeContextInput,
105
+ ) => DefaultHostedChatRuntimeTaskContext;
106
+ refreshSystem?: (
107
+ input: DefaultHostedChatRuntimeSystemRefreshInput,
108
+ ) => Promise<string> | string;
109
+ onSteeringMutation?: (
110
+ input: DefaultHostedChatRuntimeSteeringMutationInput,
111
+ ) => Promise<void> | void;
112
+ onStudioProjectSwitch?: (
113
+ input: DefaultHostedChatRuntimeProjectSwitchInput,
114
+ ) => Promise<boolean> | boolean;
115
+ projectScopedRemoteToolOptions?:
116
+ PrepareHostedChatRuntimeToolAssemblyInput["projectScopedRemoteToolOptions"];
117
+ createRemoteToolSource?: (config: RemoteMCPToolSourceConfig) => RemoteToolSource;
118
+ traceLocalTools?: PrepareHostedChatRuntimeToolAssemblyInput["traceLocalTools"];
119
+ preloadLatestConversationUserText?: boolean;
120
+ logger?: DefaultHostedChatRuntimeLogger;
121
+ };
122
+
123
+ function createDefaultTaskContext(
124
+ input: CreateDefaultHostedChatRuntimeContextInput,
125
+ ): DefaultHostedChatRuntimeTaskContext {
126
+ return {
127
+ authToken: input.options.authToken,
128
+ projectId: input.options.projectId ?? "",
129
+ branchId: input.options.branchId ?? null,
130
+ model: input.modelId,
131
+ clientProfile: input.options.clientProfile,
132
+ conversationId: input.options.conversationId,
133
+ userId: input.options.userId,
134
+ parentRunId: input.options.parentRunId,
135
+ parentMessageId: input.options.parentMessageId,
136
+ availableSkillIds: input.options.availableSkillIds,
137
+ publishParentRunEvents: input.options.publishParentRunEvents,
138
+ };
139
+ }
140
+
141
+ function incrementSteeringRevision(context: DefaultHostedChatRuntimeTaskContext): void {
142
+ context.steeringRevision = (context.steeringRevision ?? 0) + 1;
143
+ }
144
+
145
+ async function buildToolAssembly(
146
+ input: CreateDefaultHostedChatRuntimeOptions & {
147
+ taskContext: DefaultHostedChatRuntimeTaskContext;
148
+ },
149
+ ): Promise<HostedChatRuntimeToolAssemblyResult> {
150
+ return prepareHostedChatRuntimeToolAssembly({
151
+ taskContext: input.taskContext,
152
+ instructions: input.options.instructions,
153
+ localTools: input.buildLocalTools(input.taskContext),
154
+ apiUrl: input.config.apiUrl,
155
+ apiMcpUrl: input.config.apiMcpUrl,
156
+ studioMcpUrl: input.config.studioMcpUrl,
157
+ conversationId: input.options.conversationId,
158
+ allowedToolNames: input.options.allowedTools ?? null,
159
+ projectScopedRemoteToolOptions: input.projectScopedRemoteToolOptions,
160
+ createRemoteToolSource: input.createRemoteToolSource,
161
+ traceLocalTools: input.traceLocalTools,
162
+ preloadLatestConversationUserText: input.preloadLatestConversationUserText,
163
+ prepareRemoteToolInput: ({ toolName, toolInput }) =>
164
+ applyDefaultResearchArtifactPath(toolName, toolInput, input.taskContext),
165
+ shouldRetryWithRemoteTool: ({ toolName, toolInput, error }) =>
166
+ shouldRetryCreateResearchArtifactAsUpdate({
167
+ toolName,
168
+ toolInput,
169
+ taskContext: input.taskContext,
170
+ error,
171
+ }),
172
+ onSteeringMutation: async (mutation) => {
173
+ await input.onSteeringMutation?.({ mutation, taskContext: input.taskContext });
174
+ if (mutation.instructionsChanged || mutation.skillsChanged) {
175
+ incrementSteeringRevision(input.taskContext);
176
+ }
177
+ },
178
+ onStudioProjectSwitch: async (projectId) => {
179
+ const changed = await input.onStudioProjectSwitch?.({
180
+ projectId,
181
+ taskContext: input.taskContext,
182
+ });
183
+ if (changed) {
184
+ incrementSteeringRevision(input.taskContext);
185
+ }
186
+ },
187
+ });
188
+ }
189
+
190
+ function createRuntimeAgentConfig(input: {
191
+ options: DefaultHostedChatRuntimeCreationOptions;
192
+ taskContext: DefaultHostedChatRuntimeTaskContext;
193
+ toolAssembly: HostedChatRuntimeToolAssemblyResult;
194
+ modelId: string;
195
+ refreshSystem?: CreateDefaultHostedChatRuntimeOptions["refreshSystem"];
196
+ }): AgentConfig {
197
+ const liveProjectSteering = input.options.liveProjectSteering;
198
+ const systemRefresh = input.refreshSystem;
199
+ const refreshSystem = systemRefresh && liveProjectSteering
200
+ ? () =>
201
+ systemRefresh({
202
+ taskContext: input.taskContext,
203
+ liveProjectSteering,
204
+ toolAssembly: input.toolAssembly,
205
+ })
206
+ : undefined;
207
+
208
+ return {
209
+ id: "veryfront-hosted-runtime",
210
+ model: input.modelId,
211
+ system: input.toolAssembly.systemInstructions,
212
+ tools: input.toolAssembly.runtimeTools,
213
+ remoteTools: input.toolAssembly.remoteToolSources,
214
+ allowedRemoteTools: input.toolAssembly.compatibleRemoteToolNames,
215
+ maxSteps: input.options.maxSteps ?? 50,
216
+ resolveModelTransport: ({ resolvedModel }) => {
217
+ const providerOptions = resolveVeryfrontCloudThinkingProviderOptions(
218
+ resolvedModel,
219
+ input.options.thinking,
220
+ );
221
+ return providerOptions ? { providerOptions } : {};
222
+ },
223
+ resolveRuntimeState: createHostedRuntimeStateResolver({
224
+ taskContext: input.taskContext,
225
+ refreshSystem,
226
+ }),
227
+ onToolResult: createDefaultResearchRunArtifactMirrorHandler({
228
+ taskContext: input.taskContext,
229
+ remoteToolSource: input.toolAssembly.remoteToolSources[0],
230
+ }),
231
+ };
232
+ }
233
+
234
+ function createCloudContext(input: {
235
+ config: DefaultHostedChatRuntimeConfig;
236
+ options: DefaultHostedChatRuntimeCreationOptions;
237
+ }): VeryfrontCloudContext {
238
+ return {
239
+ apiBaseUrl: input.config.apiUrl,
240
+ apiToken: input.options.authToken,
241
+ serviceLayer: "cloud",
242
+ };
243
+ }
244
+
245
+ function runWithDefaultHostedRequestContext<TResult>(
246
+ input: {
247
+ taskContext: DefaultHostedChatRuntimeTaskContext;
248
+ cloudContext: VeryfrontCloudContext;
249
+ operation: () => Promise<TResult>;
250
+ },
251
+ ): Promise<TResult> {
252
+ const requestContext = {
253
+ logger: serverLogger.child({
254
+ project_id: input.taskContext.projectId || undefined,
255
+ user_id: input.taskContext.userId,
256
+ conversation_id: input.taskContext.conversationId,
257
+ }),
258
+ requestId: dntShim.crypto.randomUUID(),
259
+ projectId: input.taskContext.projectId || undefined,
260
+ userId: input.taskContext.userId,
261
+ conversationId: input.taskContext.conversationId,
262
+ };
263
+
264
+ return runWithRequestContextAsync(
265
+ requestContext,
266
+ () => runWithVeryfrontCloudContextAsync(input.cloudContext, input.operation),
267
+ );
268
+ }
269
+
270
+ export async function createDefaultHostedChatRuntime(
271
+ input: CreateDefaultHostedChatRuntimeOptions,
272
+ ): Promise<HostedChatRuntimeCreationResult> {
273
+ const modelId = resolveVeryfrontCloudModelId(input.options.model);
274
+ const cloudContext = createCloudContext({
275
+ config: input.config,
276
+ options: input.options,
277
+ });
278
+ const taskContext = input.createTaskContext
279
+ ? input.createTaskContext({ options: input.options, modelId })
280
+ : createDefaultTaskContext({ options: input.options, modelId });
281
+ const cleanup = () => Promise.resolve();
282
+
283
+ try {
284
+ const toolAssembly = await buildToolAssembly({
285
+ ...input,
286
+ taskContext,
287
+ });
288
+ const runtimeAgentConfig = createRuntimeAgentConfig({
289
+ options: input.options,
290
+ taskContext,
291
+ toolAssembly,
292
+ modelId,
293
+ refreshSystem: input.refreshSystem,
294
+ });
295
+ const runtimeAgent = runWithVeryfrontCloudContext(
296
+ cloudContext,
297
+ () => agent(runtimeAgentConfig),
298
+ );
299
+
300
+ return {
301
+ runtimeKind: "framework",
302
+ modelId,
303
+ cleanup,
304
+ agent: createHostedChatRuntimeAgentAdapter({
305
+ runtimeAgent,
306
+ runStream: (operation) =>
307
+ runWithDefaultHostedRequestContext({
308
+ taskContext,
309
+ cloudContext,
310
+ operation,
311
+ }),
312
+ warnOrphanedToolInput: (message, metadata) => {
313
+ input.logger?.warn(message, {
314
+ ...metadata,
315
+ ...(taskContext.projectId ? { project_id: taskContext.projectId } : {}),
316
+ ...(taskContext.userId ? { user_id: taskContext.userId } : {}),
317
+ ...(taskContext.conversationId ? { conversation_id: taskContext.conversationId } : {}),
318
+ });
319
+ },
320
+ }),
321
+ };
322
+ } catch (error) {
323
+ await cleanup();
324
+ throw error;
325
+ }
326
+ }