@librechat/agents 4.2.10 → 4.2.11

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 (261) hide show
  1. package/dist/cjs/runtime/admission.cjs +135 -0
  2. package/dist/cjs/runtime/admission.cjs.map +1 -0
  3. package/dist/cjs/runtime/checkpoint.cjs +40 -0
  4. package/dist/cjs/runtime/checkpoint.cjs.map +1 -0
  5. package/dist/cjs/runtime/client.cjs +435 -0
  6. package/dist/cjs/runtime/client.cjs.map +1 -0
  7. package/dist/cjs/runtime/files.cjs +301 -0
  8. package/dist/cjs/runtime/files.cjs.map +1 -0
  9. package/dist/cjs/runtime/hostTools.cjs +165 -0
  10. package/dist/cjs/runtime/hostTools.cjs.map +1 -0
  11. package/dist/cjs/runtime/index.cjs +11 -0
  12. package/dist/cjs/runtime/model.cjs +303 -0
  13. package/dist/cjs/runtime/model.cjs.map +1 -0
  14. package/dist/cjs/runtime/peer.cjs +209 -0
  15. package/dist/cjs/runtime/peer.cjs.map +1 -0
  16. package/dist/cjs/runtime/policy.cjs +77 -0
  17. package/dist/cjs/runtime/policy.cjs.map +1 -0
  18. package/dist/cjs/runtime/recovery/client.cjs +172 -0
  19. package/dist/cjs/runtime/recovery/client.cjs.map +1 -0
  20. package/dist/cjs/runtime/recovery/log.cjs +47 -0
  21. package/dist/cjs/runtime/recovery/log.cjs.map +1 -0
  22. package/dist/cjs/runtime/recovery/redis.cjs +239 -0
  23. package/dist/cjs/runtime/recovery/redis.cjs.map +1 -0
  24. package/dist/cjs/runtime/recovery/server.cjs +190 -0
  25. package/dist/cjs/runtime/recovery/server.cjs.map +1 -0
  26. package/dist/cjs/runtime/recovery/socket.cjs +298 -0
  27. package/dist/cjs/runtime/recovery/socket.cjs.map +1 -0
  28. package/dist/cjs/runtime/resume.cjs +115 -0
  29. package/dist/cjs/runtime/resume.cjs.map +1 -0
  30. package/dist/cjs/runtime/sealed.cjs +107 -0
  31. package/dist/cjs/runtime/sealed.cjs.map +1 -0
  32. package/dist/cjs/runtime/server.cjs +415 -0
  33. package/dist/cjs/runtime/server.cjs.map +1 -0
  34. package/dist/cjs/runtime/snapshot.cjs +61 -0
  35. package/dist/cjs/runtime/snapshot.cjs.map +1 -0
  36. package/dist/cjs/runtime/types.cjs +20 -0
  37. package/dist/cjs/runtime/types.cjs.map +1 -0
  38. package/dist/cjs/runtime/wire.cjs +84 -0
  39. package/dist/cjs/runtime/wire.cjs.map +1 -0
  40. package/dist/esm/runtime/admission.mjs +133 -0
  41. package/dist/esm/runtime/admission.mjs.map +1 -0
  42. package/dist/esm/runtime/checkpoint.mjs +39 -0
  43. package/dist/esm/runtime/checkpoint.mjs.map +1 -0
  44. package/dist/esm/runtime/client.mjs +432 -0
  45. package/dist/esm/runtime/client.mjs.map +1 -0
  46. package/dist/esm/runtime/files.mjs +299 -0
  47. package/dist/esm/runtime/files.mjs.map +1 -0
  48. package/dist/esm/runtime/hostTools.mjs +164 -0
  49. package/dist/esm/runtime/hostTools.mjs.map +1 -0
  50. package/dist/esm/runtime/index.mjs +5 -0
  51. package/dist/esm/runtime/model.mjs +301 -0
  52. package/dist/esm/runtime/model.mjs.map +1 -0
  53. package/dist/esm/runtime/peer.mjs +209 -0
  54. package/dist/esm/runtime/peer.mjs.map +1 -0
  55. package/dist/esm/runtime/policy.mjs +75 -0
  56. package/dist/esm/runtime/policy.mjs.map +1 -0
  57. package/dist/esm/runtime/recovery/client.mjs +172 -0
  58. package/dist/esm/runtime/recovery/client.mjs.map +1 -0
  59. package/dist/esm/runtime/recovery/log.mjs +46 -0
  60. package/dist/esm/runtime/recovery/log.mjs.map +1 -0
  61. package/dist/esm/runtime/recovery/redis.mjs +239 -0
  62. package/dist/esm/runtime/recovery/redis.mjs.map +1 -0
  63. package/dist/esm/runtime/recovery/server.mjs +189 -0
  64. package/dist/esm/runtime/recovery/server.mjs.map +1 -0
  65. package/dist/esm/runtime/recovery/socket.mjs +297 -0
  66. package/dist/esm/runtime/recovery/socket.mjs.map +1 -0
  67. package/dist/esm/runtime/resume.mjs +111 -0
  68. package/dist/esm/runtime/resume.mjs.map +1 -0
  69. package/dist/esm/runtime/sealed.mjs +106 -0
  70. package/dist/esm/runtime/sealed.mjs.map +1 -0
  71. package/dist/esm/runtime/server.mjs +413 -0
  72. package/dist/esm/runtime/server.mjs.map +1 -0
  73. package/dist/esm/runtime/snapshot.mjs +60 -0
  74. package/dist/esm/runtime/snapshot.mjs.map +1 -0
  75. package/dist/esm/runtime/types.mjs +19 -0
  76. package/dist/esm/runtime/types.mjs.map +1 -0
  77. package/dist/esm/runtime/wire.mjs +80 -0
  78. package/dist/esm/runtime/wire.mjs.map +1 -0
  79. package/dist/types/agents/AgentContext.d.ts +4 -4
  80. package/dist/types/agents/projection.d.ts +1 -1
  81. package/dist/types/events.d.ts +2 -2
  82. package/dist/types/graphs/Graph.d.ts +13 -13
  83. package/dist/types/graphs/MultiAgentGraph.d.ts +2 -2
  84. package/dist/types/graphs/acceptedModelResponse.d.ts +1 -1
  85. package/dist/types/graphs/createGraph.d.ts +4 -4
  86. package/dist/types/graphs/graphFactory.d.ts +1 -1
  87. package/dist/types/graphs/handoff.d.ts +1 -1
  88. package/dist/types/harness/index.d.ts +2 -2
  89. package/dist/types/harness/model.d.ts +3 -3
  90. package/dist/types/harness/providerText.d.ts +2 -2
  91. package/dist/types/hitl/approvalReview.d.ts +1 -1
  92. package/dist/types/hitl/askUserQuestion.d.ts +1 -1
  93. package/dist/types/hitl/askUserQuestions.d.ts +1 -1
  94. package/dist/types/hitl/askUserQuestionsInterrupt.d.ts +1 -1
  95. package/dist/types/hooks/types.d.ts +2 -2
  96. package/dist/types/instrumentation.d.ts +1 -1
  97. package/dist/types/langfuse.d.ts +3 -3
  98. package/dist/types/langfuseConfig.d.ts +2 -2
  99. package/dist/types/langfuseRuntimeContext.d.ts +1 -1
  100. package/dist/types/langfuseRuntimeScope.d.ts +2 -2
  101. package/dist/types/langfuseSpanRegistry.d.ts +1 -1
  102. package/dist/types/langfuseToolOutputTracing.d.ts +3 -3
  103. package/dist/types/llm/anthropic/index.d.ts +1 -1
  104. package/dist/types/llm/bedrock/index.d.ts +1 -1
  105. package/dist/types/llm/bedrock/toolCache.d.ts +2 -2
  106. package/dist/types/llm/contextOverflowRecovery.d.ts +2 -2
  107. package/dist/types/llm/contextPressureMeter.d.ts +2 -2
  108. package/dist/types/llm/google/index.d.ts +1 -1
  109. package/dist/types/llm/init.d.ts +1 -1
  110. package/dist/types/llm/invoke.d.ts +9 -9
  111. package/dist/types/llm/mistral/index.d.ts +1 -1
  112. package/dist/types/llm/openai/index.d.ts +2 -2
  113. package/dist/types/llm/openrouter/index.d.ts +2 -2
  114. package/dist/types/llm/openrouter/toolCache.d.ts +2 -2
  115. package/dist/types/llm/prepareProviderRequest.d.ts +3 -3
  116. package/dist/types/llm/promptCacheTools.d.ts +1 -1
  117. package/dist/types/llm/providerRegistry.d.ts +1 -1
  118. package/dist/types/llm/providerTextBoundary.d.ts +2 -2
  119. package/dist/types/llm/providerTextControls.d.ts +1 -1
  120. package/dist/types/llm/providers.d.ts +2 -2
  121. package/dist/types/llm/request.d.ts +1 -1
  122. package/dist/types/llm/stream/chunkAdapters.d.ts +1 -1
  123. package/dist/types/llm/streamLimits.d.ts +1 -1
  124. package/dist/types/llm/truncation.d.ts +1 -1
  125. package/dist/types/llm/vertexai/index.d.ts +1 -1
  126. package/dist/types/messages/alternation.d.ts +1 -1
  127. package/dist/types/messages/anthropicToolCache.d.ts +2 -2
  128. package/dist/types/messages/assistantPhase.d.ts +3 -3
  129. package/dist/types/messages/budget.d.ts +1 -1
  130. package/dist/types/messages/cache.d.ts +1 -1
  131. package/dist/types/messages/contextPruning.d.ts +2 -2
  132. package/dist/types/messages/core.d.ts +1 -1
  133. package/dist/types/messages/fading.d.ts +1 -1
  134. package/dist/types/messages/format.d.ts +2 -2
  135. package/dist/types/messages/ids.d.ts +2 -2
  136. package/dist/types/messages/injected.d.ts +1 -1
  137. package/dist/types/messages/langchain.d.ts +1 -1
  138. package/dist/types/messages/prune.d.ts +4 -4
  139. package/dist/types/messages/recency.d.ts +1 -1
  140. package/dist/types/messages/toolResultTypes.d.ts +1 -1
  141. package/dist/types/openai/arguments.d.ts +1 -1
  142. package/dist/types/openai/index.d.ts +1 -1
  143. package/dist/types/openai/toolProjection.d.ts +1 -1
  144. package/dist/types/prompts/activityLabel.d.ts +2 -2
  145. package/dist/types/prompts/reasoningLabel.d.ts +1 -1
  146. package/dist/types/rerank/search.d.ts +1 -1
  147. package/dist/types/responses/index.d.ts +1 -1
  148. package/dist/types/run.d.ts +3 -3
  149. package/dist/types/runtime/admission.d.ts +30 -0
  150. package/dist/types/runtime/checkpoint.d.ts +14 -0
  151. package/dist/types/runtime/client.d.ts +12 -0
  152. package/dist/types/runtime/files.d.ts +75 -0
  153. package/dist/types/runtime/hostTools.d.ts +22 -0
  154. package/dist/types/runtime/identity.d.ts +2 -0
  155. package/dist/types/runtime/index.d.ts +12 -0
  156. package/dist/types/runtime/model.d.ts +42 -0
  157. package/dist/types/runtime/peer.d.ts +55 -0
  158. package/dist/types/runtime/policy.d.ts +43 -0
  159. package/dist/types/runtime/recovery/client.d.ts +12 -0
  160. package/dist/types/runtime/recovery/journal.d.ts +62 -0
  161. package/dist/types/runtime/recovery/log.d.ts +9 -0
  162. package/dist/types/runtime/recovery/redis.d.ts +17 -0
  163. package/dist/types/runtime/recovery/server.d.ts +37 -0
  164. package/dist/types/runtime/recovery/socket.d.ts +72 -0
  165. package/dist/types/runtime/resume.d.ts +66 -0
  166. package/dist/types/runtime/sealed.d.ts +19 -0
  167. package/dist/types/runtime/server.d.ts +21 -0
  168. package/dist/types/runtime/snapshot.d.ts +12 -0
  169. package/dist/types/runtime/types.d.ts +125 -0
  170. package/dist/types/runtime/wire.d.ts +3 -0
  171. package/dist/types/session/handlers.d.ts +1 -1
  172. package/dist/types/session/types.d.ts +1 -1
  173. package/dist/types/stream.d.ts +3 -3
  174. package/dist/types/summarization/index.d.ts +1 -1
  175. package/dist/types/summarization/input.d.ts +1 -1
  176. package/dist/types/summarization/node.d.ts +6 -6
  177. package/dist/types/summarization/retry.d.ts +2 -2
  178. package/dist/types/summarization/semanticIndex.d.ts +2 -2
  179. package/dist/types/summarization/toolBudget.d.ts +1 -1
  180. package/dist/types/summarization/usage.d.ts +1 -1
  181. package/dist/types/tools/ArtifactDelivery.d.ts +1 -1
  182. package/dist/types/tools/ArtifactTruncation.d.ts +1 -1
  183. package/dist/types/tools/BashExecutor.d.ts +2 -2
  184. package/dist/types/tools/BashProgrammaticToolCalling.d.ts +2 -2
  185. package/dist/types/tools/CallerCapabilities.d.ts +1 -1
  186. package/dist/types/tools/CodeExecutor.d.ts +4 -4
  187. package/dist/types/tools/CodeSessionFileSummary.d.ts +1 -1
  188. package/dist/types/tools/ProgrammaticCallerPolicy.d.ts +1 -1
  189. package/dist/types/tools/ProgrammaticToolCalling.d.ts +2 -2
  190. package/dist/types/tools/ReadFile.d.ts +1 -1
  191. package/dist/types/tools/SkillTool.d.ts +1 -1
  192. package/dist/types/tools/SubagentTool.d.ts +3 -3
  193. package/dist/types/tools/ToolNode.d.ts +5 -5
  194. package/dist/types/tools/ToolSearch.d.ts +2 -2
  195. package/dist/types/tools/cloudflare/CloudflareBridgeRuntime.d.ts +1 -1
  196. package/dist/types/tools/cloudflare/CloudflareProgrammaticToolCalling.d.ts +1 -1
  197. package/dist/types/tools/cloudflare/CloudflareSandboxExecutionEngine.d.ts +2 -2
  198. package/dist/types/tools/cloudflare/CloudflareSandboxTools.d.ts +1 -1
  199. package/dist/types/tools/diagnostics.d.ts +1 -1
  200. package/dist/types/tools/eagerEventExecution.d.ts +1 -1
  201. package/dist/types/tools/handlers.d.ts +3 -3
  202. package/dist/types/tools/intentArg.d.ts +1 -1
  203. package/dist/types/tools/local/CompileCheckTool.d.ts +2 -2
  204. package/dist/types/tools/local/FileCheckpointer.d.ts +1 -1
  205. package/dist/types/tools/local/LocalCodingTools.d.ts +2 -2
  206. package/dist/types/tools/local/LocalExecutionEngine.d.ts +1 -1
  207. package/dist/types/tools/local/LocalExecutionTools.d.ts +1 -1
  208. package/dist/types/tools/local/LocalProgrammaticToolCalling.d.ts +1 -1
  209. package/dist/types/tools/local/bashAst.d.ts +1 -1
  210. package/dist/types/tools/local/resolveLocalExecutionTools.d.ts +1 -1
  211. package/dist/types/tools/local/syntaxCheck.d.ts +1 -1
  212. package/dist/types/tools/ptcTimeout.d.ts +1 -1
  213. package/dist/types/tools/runStepResume.d.ts +1 -1
  214. package/dist/types/tools/schema.d.ts +1 -1
  215. package/dist/types/tools/search/anthropic.d.ts +1 -1
  216. package/dist/types/tools/skillCatalog.d.ts +1 -1
  217. package/dist/types/tools/subagent/InMemorySubagentTaskStore.d.ts +1 -1
  218. package/dist/types/tools/subagent/SubagentExecutor.d.ts +5 -5
  219. package/dist/types/tools/subagent/SubagentReplay.d.ts +3 -3
  220. package/dist/types/tools/subagent/childGraphConfig.d.ts +2 -2
  221. package/dist/types/tools/subagent/diagnostics.d.ts +2 -2
  222. package/dist/types/tools/subagent/hostArgs.d.ts +2 -2
  223. package/dist/types/tools/toolBatchReplay.d.ts +3 -3
  224. package/dist/types/types/activityLabel.d.ts +2 -2
  225. package/dist/types/types/graph.d.ts +10 -10
  226. package/dist/types/types/llm.d.ts +9 -9
  227. package/dist/types/types/reasoningLabel.d.ts +1 -1
  228. package/dist/types/types/run.d.ts +8 -8
  229. package/dist/types/types/stream.d.ts +5 -5
  230. package/dist/types/types/summarize.d.ts +2 -2
  231. package/dist/types/types/tools.d.ts +8 -8
  232. package/dist/types/utils/errors.d.ts +1 -1
  233. package/dist/types/utils/events.d.ts +3 -3
  234. package/dist/types/utils/handlers.d.ts +3 -3
  235. package/dist/types/utils/llm.d.ts +2 -2
  236. package/dist/types/utils/llmConfig.d.ts +1 -1
  237. package/dist/types/utils/title.d.ts +1 -1
  238. package/dist/types/utils/toolSessions.d.ts +1 -1
  239. package/package.json +22 -3
  240. package/src/runtime/admission.ts +224 -0
  241. package/src/runtime/checkpoint.ts +66 -0
  242. package/src/runtime/client.ts +674 -0
  243. package/src/runtime/files.ts +503 -0
  244. package/src/runtime/hostTools.ts +243 -0
  245. package/src/runtime/identity.ts +3 -0
  246. package/src/runtime/index.ts +33 -0
  247. package/src/runtime/model.ts +452 -0
  248. package/src/runtime/peer.ts +262 -0
  249. package/src/runtime/policy.ts +150 -0
  250. package/src/runtime/recovery/client.ts +232 -0
  251. package/src/runtime/recovery/journal.ts +88 -0
  252. package/src/runtime/recovery/log.ts +70 -0
  253. package/src/runtime/recovery/redis.ts +342 -0
  254. package/src/runtime/recovery/server.ts +280 -0
  255. package/src/runtime/recovery/socket.ts +422 -0
  256. package/src/runtime/resume.ts +268 -0
  257. package/src/runtime/sealed.ts +144 -0
  258. package/src/runtime/server.ts +653 -0
  259. package/src/runtime/snapshot.ts +87 -0
  260. package/src/runtime/types.ts +184 -0
  261. package/src/runtime/wire.ts +96 -0
@@ -0,0 +1,674 @@
1
+ import { z } from 'zod';
2
+ import { WebSocket } from 'ws';
3
+ import jwt from 'jsonwebtoken';
4
+ import { randomUUID } from 'node:crypto';
5
+ import type {
6
+ RunStepResumeState,
7
+ MessageContentComplex,
8
+ FadingTier,
9
+ FadingTiers,
10
+ HandoffOutcome,
11
+ RunConfig,
12
+ RunInterruptResult,
13
+ RunStep,
14
+ RunStepClosedEvent,
15
+ } from '@/index';
16
+ import type {
17
+ RemoteSdkHostServices,
18
+ RemoteSdkOptions,
19
+ RemoteSdkSnapshot,
20
+ RemoteSdkStart,
21
+ SdkRunOptions,
22
+ SdkRun,
23
+ RemoteSdkResumeState,
24
+ SdkEventData,
25
+ } from './types';
26
+ import type { RecoveryClaim } from './recovery/server';
27
+ import type { SdkAgentIdentity } from './identity';
28
+ import {
29
+ Run,
30
+ executeHooks,
31
+ GraphEvents,
32
+ HOOK_EVENTS,
33
+ createContentAggregator,
34
+ BaseCheckpointSaver,
35
+ TOOL_APPROVAL_EXECUTION_SCOPE_CONFIG_KEY,
36
+ } from '@/index';
37
+ import { hydrateResumeRunSteps, reconcileRemoteResumeContent } from './resume';
38
+ import { connectRecoveringSdkSocket } from './recovery/client';
39
+ import { remoteSdkLimits, isRemoteSdkSecret } from './types';
40
+ import { createHostToolService } from './hostTools';
41
+ import { createSnapshotReceiver } from './snapshot';
42
+ import { createHostPolicyChannel } from './policy';
43
+ import { createHostModelChannel } from './model';
44
+ import { createHostFileChannel } from './files';
45
+ import { createSdkPeer } from './peer';
46
+
47
+ /** Construct a real local Run whose execution is delegated to one operator-trusted runtime. */
48
+ export async function createRemoteSdkRun({
49
+ config,
50
+ identity,
51
+ remote,
52
+ resumeState,
53
+ hostServices,
54
+ }: {
55
+ config: RunConfig;
56
+ hostServices?: RemoteSdkHostServices;
57
+ identity: Readonly<SdkAgentIdentity>;
58
+ remote: RemoteSdkOptions;
59
+ resumeState?: RemoteSdkResumeState;
60
+ }): ReturnType<typeof Run.create> {
61
+ if (hostServices?.modelProfile && !hostServices.model)
62
+ throw new Error('Builder model profile requires a host model');
63
+ if ((config.clientDelegatedToolNames?.length ?? 0) > 0)
64
+ throw new Error(
65
+ 'Remote SDK client-owned tools require a supported ownership adapter'
66
+ );
67
+ if (config.providerTextProtection && !hostServices?.providerText)
68
+ throw new Error(
69
+ 'Remote SDK provider protection requires a supported policy adapter'
70
+ );
71
+ identity = Object.freeze({ ...identity });
72
+ const limits = remoteSdkLimits(remote);
73
+ const url = new URL(remote.url);
74
+ if (
75
+ url.username ||
76
+ url.password ||
77
+ url.hash ||
78
+ url.search ||
79
+ (url.protocol !== 'wss:' &&
80
+ !(
81
+ url.protocol === 'ws:' &&
82
+ ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
83
+ )) ||
84
+ !isRemoteSdkSecret(remote.secret)
85
+ )
86
+ throw new Error('Invalid SDK runtime connection configuration');
87
+ const run = await Run.create(config);
88
+ const graph = run.Graph;
89
+ if (graph == null) throw new Error('SDK runtime graph is unavailable');
90
+ let snapshot: RemoteSdkSnapshot | undefined;
91
+ const projection = createContentAggregator();
92
+ if (resumeState) {
93
+ projection.contentParts.push(...resumeState.content);
94
+ hydrateResumeRunSteps(
95
+ resumeState.steps,
96
+ projection.stepMap,
97
+ graph,
98
+ resumeState.content
99
+ );
100
+ for (const step of resumeState.steps) {
101
+ if (step.id.length === 0) continue;
102
+ graph.contentIndexMap.set(step.id, graph.contentData.length);
103
+ graph.contentData.push({ ...step });
104
+ }
105
+ }
106
+ const projectEvent = (event: GraphEvents, data: SdkEventData): void => {
107
+ // The aggregator maps worker indices to physical slots after seeded content.
108
+ projection.aggregateContent({
109
+ event,
110
+ data: data as Parameters<typeof projection.aggregateContent>[0]['data'],
111
+ });
112
+ if (event === GraphEvents.ON_RUN_STEP) {
113
+ const step = data as RunStep;
114
+ const position = graph.contentIndexMap.get(step.id);
115
+ if (position === undefined) {
116
+ graph.contentIndexMap.set(step.id, graph.contentData.length);
117
+ graph.contentData.push(step);
118
+ } else graph.contentData[position] = step;
119
+ hydrateResumeRunSteps([step], undefined, graph);
120
+ } else if (event === GraphEvents.ON_RUN_STEP_CLOSED) {
121
+ const closed = data as RunStepClosedEvent;
122
+ const step = graph.getRunStep(closed.id);
123
+ if (step) {
124
+ Object.assign(step, {
125
+ status: closed.status,
126
+ closed_at: closed.closed_at,
127
+ });
128
+ }
129
+ }
130
+ };
131
+ const createResumeState = graph.createRunStepResumeState.bind(graph);
132
+ graph.createRunStepResumeState = (): RunStepResumeState =>
133
+ snapshot?.runSteps ?? createResumeState();
134
+ graph.getContentParts = (): MessageContentComplex[] =>
135
+ snapshot?.content ?? projection.contentParts.filter((part) => part != null);
136
+ run.getRunMessages = (): ReturnType<SdkRun['getRunMessages']> =>
137
+ snapshot?.messages ?? [];
138
+ graph.getRunMessages = run.getRunMessages;
139
+ run.getInterrupt = <T>(): RunInterruptResult<T> | undefined =>
140
+ snapshot?.interrupt as RunInterruptResult<T> | undefined;
141
+ run.getHaltReason = (): string | undefined => snapshot?.haltReason;
142
+ run.getDiscoveredTools = (): string[] =>
143
+ snapshot?.state?.getDiscoveredTools ?? [];
144
+ run.getCalibrationRatio = (): number =>
145
+ snapshot?.state?.getCalibrationRatio ?? 1;
146
+ run.getFadingTier = (): FadingTier | undefined =>
147
+ snapshot?.state?.getFadingTier;
148
+ run.getFadingTiers = (): FadingTiers => snapshot?.state?.getFadingTiers ?? {};
149
+ run.getFadingTierResetAgentIds = (): string[] =>
150
+ snapshot?.state?.getFadingTierResetAgentIds ?? [];
151
+ run.getResolvedInstructionOverhead = (): number | undefined =>
152
+ snapshot?.state?.getResolvedInstructionOverhead;
153
+ run.getToolCount = (): number => snapshot?.state?.getToolCount ?? 0;
154
+ run.getOutputTruncated = (): boolean =>
155
+ snapshot?.state?.getOutputTruncated ?? false;
156
+ run.getHandoffOutcome = (): HandoffOutcome | undefined =>
157
+ snapshot?.state?.getHandoffOutcome;
158
+ const candidate = config.graphConfig.compileOptions?.checkpointer;
159
+ const saver =
160
+ candidate instanceof BaseCheckpointSaver ? candidate : undefined;
161
+ if (config.humanInTheLoop?.enabled === true && !saver)
162
+ throw new Error('Remote SDK approvals require a host checkpointer');
163
+ const agentConfig =
164
+ 'agents' in config.graphConfig
165
+ ? config.graphConfig.agents[0]
166
+ : config.graphConfig;
167
+ const descriptors = (agentConfig.toolDefinitions ?? []).map((definition) => ({
168
+ definition,
169
+ reference: definition.name,
170
+ }));
171
+ const toolHandler = config.customHandlers?.[GraphEvents.ON_TOOL_EXECUTE];
172
+ if (descriptors.length && !toolHandler)
173
+ throw new Error('Host tool handler is unavailable');
174
+ let invoked = false;
175
+ const execute = async (
176
+ operation: RemoteSdkStart['operation'],
177
+ input: RemoteSdkStart['input'],
178
+ options: SdkRunOptions,
179
+ resume?: unknown,
180
+ commandOptions?: RemoteSdkStart['commandOptions']
181
+ ): Promise<MessageContentComplex[] | undefined> => {
182
+ options.signal?.throwIfAborted();
183
+ if (invoked)
184
+ throw new Error(
185
+ 'SDK runtime Run already invoked; create a fresh Run for continuation'
186
+ );
187
+ invoked = true;
188
+ const threadId =
189
+ options.configurable?.thread_id ??
190
+ identity.conversationId ??
191
+ identity.runId;
192
+ if (
193
+ typeof threadId !== 'string' ||
194
+ (identity.conversationId != null &&
195
+ identity.conversationId.length > 0 &&
196
+ identity.conversationId !== threadId)
197
+ )
198
+ throw new Error('SDK runtime thread identity mismatch');
199
+ const boundConfigurable: Record<string, unknown> = {
200
+ ...options.configurable,
201
+ thread_id: threadId,
202
+ };
203
+ const makeToken = (recovery?: RecoveryClaim): string =>
204
+ // jsonwebtoken has no named ESM exports; the default import is required.
205
+ // eslint-disable-next-line import-x/no-named-as-default-member
206
+ jwt.sign(
207
+ {
208
+ protocolVersion: 1,
209
+ identity,
210
+ threadId,
211
+ invocationId: randomUUID(),
212
+ recovery,
213
+ },
214
+ remote.secret,
215
+ {
216
+ algorithm: 'HS256',
217
+ audience: identity.runtimeId,
218
+ issuer: 'librechat-sdk',
219
+ expiresIn: '60s',
220
+ }
221
+ );
222
+ const legacy = async (): Promise<WebSocket> => {
223
+ const socket = new WebSocket(remote.url, {
224
+ headers: { Authorization: `Bearer ${makeToken()}` },
225
+ handshakeTimeout: limits.connectTimeoutMs,
226
+ maxPayload: limits.maxFrameBytes,
227
+ followRedirects: false,
228
+ });
229
+ await new Promise<void>((resolve, reject) => {
230
+ const abort = (): void => {
231
+ socket.terminate();
232
+ reject(
233
+ Object.assign(new Error('SDK runtime connection cancelled'), {
234
+ name: 'AbortError',
235
+ })
236
+ );
237
+ };
238
+ const cleanup = (): void | undefined =>
239
+ options.signal?.removeEventListener('abort', abort);
240
+ socket.once('open', () => {
241
+ cleanup();
242
+ resolve();
243
+ });
244
+ socket.once('error', () => {
245
+ cleanup();
246
+ reject(new Error('SDK runtime connection failed'));
247
+ });
248
+ options.signal?.addEventListener('abort', abort, { once: true });
249
+ if (options.signal?.aborted === true) abort();
250
+ });
251
+
252
+ return socket;
253
+ };
254
+ const modelAdmission =
255
+ hostServices?.modelLifecycle?.attach(options.callbacks) === true;
256
+ const connection = remote.recovery
257
+ ? connectRecoveringSdkSocket({
258
+ url: remote.url,
259
+ token: makeToken,
260
+ generation:
261
+ typeof boundConfigurable.__librechat_checkpoint_ns === 'string'
262
+ ? boundConfigurable.__librechat_checkpoint_ns
263
+ : undefined,
264
+ limits,
265
+ recovery: remote.recovery,
266
+ signal: options.signal,
267
+ onError: remote.onError,
268
+ })
269
+ : legacy();
270
+ const socket = await connection.catch((error) => {
271
+ hostServices?.modelLifecycle?.dispose();
272
+ throw error;
273
+ });
274
+ const execution = new AbortController();
275
+ const providerText = hostServices?.providerText
276
+ ? createHostPolicyChannel(hostServices.providerText, limits)
277
+ : undefined;
278
+ const terminal = createSnapshotReceiver(limits.maxBufferedBytes);
279
+ snapshot = undefined;
280
+ let settled = false;
281
+ const hostInvocations = new Set<Promise<unknown>>();
282
+ const advertisedHooks = HOOK_EVENTS.filter(
283
+ (event) => config.hooks?.hasHookFor(event, identity.runId) === true
284
+ );
285
+ let hostFileChannel: ReturnType<typeof createHostFileChannel> | undefined;
286
+ let hostModelChannel: ReturnType<typeof createHostModelChannel> | undefined;
287
+ const result = new Promise<RemoteSdkSnapshot>((resolve, reject) => {
288
+ const finish = (value?: RemoteSdkSnapshot): void => {
289
+ if (settled) return;
290
+ settled = true;
291
+ if (value == null || hostServices?.modelLifecycle?.failure())
292
+ reject(
293
+ options.signal?.aborted === true
294
+ ? Object.assign(new Error('SDK runtime execution cancelled'), {
295
+ name: 'AbortError',
296
+ })
297
+ : (hostServices?.modelLifecycle?.failure() ??
298
+ new Error('SDK runtime execution failed'))
299
+ );
300
+ else resolve(value);
301
+ };
302
+ hostModelChannel = hostServices?.model
303
+ ? createHostModelChannel({
304
+ model: hostServices.model,
305
+ lifecycle: modelAdmission ? hostServices.modelLifecycle : undefined,
306
+ peer: { call: (...args) => peer.call(...args) },
307
+ limits,
308
+ signal: execution.signal,
309
+ })
310
+ : undefined;
311
+ hostFileChannel = hostServices?.files
312
+ ? createHostFileChannel({
313
+ files: hostServices.files,
314
+ identity,
315
+ peer: { call: (...args) => peer.call(...args) },
316
+ limits,
317
+ signal: execution.signal,
318
+ })
319
+ : undefined;
320
+ let hostToolInvoke: ReturnType<typeof createHostToolService> | undefined;
321
+ const peer = createSdkPeer(socket, {
322
+ ...limits,
323
+ timeoutMs: limits.rpcTimeoutMs,
324
+ onClose: () => {
325
+ execution.abort();
326
+ finish();
327
+ },
328
+ onError: remote.onError,
329
+ onFrame: async (frame) => {
330
+ if (frame.type === 'event') {
331
+ const event = z.nativeEnum(GraphEvents).parse(frame.name);
332
+ if (event === GraphEvents.ON_TOOL_EXECUTE)
333
+ throw new Error('Remote events cannot invoke host tools');
334
+ projectEvent(event, frame.data as SdkEventData);
335
+ await config.customHandlers?.[event]?.handle(
336
+ event,
337
+ frame.data as SdkEventData,
338
+ frame.metadata,
339
+ graph
340
+ );
341
+ } else if (frame.type === 'snapshot') {
342
+ terminal.accept(frame.data);
343
+ } else if (frame.type === 'done') {
344
+ if (hostInvocations.size)
345
+ throw new Error('Host tool execution has not drained');
346
+ finish(terminal.finish(frame.data));
347
+ } else if (frame.type === 'error') finish();
348
+ else throw new Error('Unexpected SDK runtime frame');
349
+ },
350
+ onCall: async (method, data, _timeoutMs, signal) => {
351
+ if (execution.signal.aborted || options.signal?.aborted === true)
352
+ throw new Error('SDK runtime execution stopped');
353
+ if (method.startsWith('files.')) {
354
+ if (!hostFileChannel) throw new Error('Host files are unavailable');
355
+ const invocation = hostFileChannel.call(method, data, signal);
356
+ hostInvocations.add(invocation);
357
+ try {
358
+ return await invocation;
359
+ } finally {
360
+ hostInvocations.delete(invocation);
361
+ }
362
+ }
363
+ if (method === 'model.node.end') {
364
+ if (!modelAdmission || !hostServices.modelLifecycle)
365
+ throw new Error('Model admission unavailable');
366
+ const admitted = hostServices.modelLifecycle.end(data);
367
+ return { version: 1, ok: true, admitted };
368
+ }
369
+ if (method === 'model.invoke' || method === 'model.stream') {
370
+ if (!hostModelChannel) throw new Error('Host model is unavailable');
371
+ const invocation = hostModelChannel.call(method, data, signal);
372
+ hostInvocations.add(invocation);
373
+ try {
374
+ return await invocation;
375
+ } finally {
376
+ hostInvocations.delete(invocation);
377
+ }
378
+ }
379
+ if (method === 'policy.providerText') {
380
+ if (!providerText)
381
+ throw new Error('Host provider policy is unavailable');
382
+ return providerText.inspect(
383
+ data,
384
+ signal
385
+ ? AbortSignal.any([execution.signal, signal])
386
+ : execution.signal
387
+ );
388
+ }
389
+ if (method === 'tools') {
390
+ if (!toolHandler || !descriptors.length)
391
+ throw new Error('Host tools are unavailable');
392
+ hostToolInvoke ??= createHostToolService({
393
+ identity,
394
+ tools: descriptors,
395
+ handler: toolHandler,
396
+ graph,
397
+ metadata: options.metadata,
398
+ configurable: {
399
+ ...options.configurable,
400
+ user_id: identity.userId,
401
+ run_id: identity.runId,
402
+ thread_id: threadId,
403
+ },
404
+ peer,
405
+ signal: execution.signal,
406
+ });
407
+ const invocation = hostToolInvoke(data, signal);
408
+ hostInvocations.add(invocation);
409
+ try {
410
+ return await invocation;
411
+ } finally {
412
+ hostInvocations.delete(invocation);
413
+ }
414
+ }
415
+ if (method === 'hook') {
416
+ if (config.hooks == null)
417
+ throw new Error('Host hooks are unavailable');
418
+ const args = data as {
419
+ input: Parameters<typeof executeHooks>[0]['input'] | undefined;
420
+ matchQuery?: string;
421
+ };
422
+ if (
423
+ args.input == null ||
424
+ !advertisedHooks.includes(args.input.hook_event_name)
425
+ )
426
+ throw new Error('Host hook is not enabled');
427
+ return executeHooks({
428
+ registry: config.hooks,
429
+ input: { ...args.input, runId: identity.runId, threadId },
430
+ matchQuery: args.matchQuery,
431
+ sessionId: identity.runId,
432
+ signal: execution.signal,
433
+ });
434
+ }
435
+ if (
436
+ !saver ||
437
+ typeof saver !== 'object' ||
438
+ !method.startsWith('checkpoint.')
439
+ )
440
+ throw new Error('Unsupported SDK operation');
441
+ const args = data as Parameters<typeof saver.put>;
442
+ const scope = (
443
+ config: Parameters<typeof saver.getTuple>[0],
444
+ before = false
445
+ ): Parameters<typeof saver.getTuple>[0] => {
446
+ const configurable = config.configurable;
447
+ const ns = configurable?.checkpoint_ns ?? '';
448
+ if (
449
+ ((!before || configurable?.thread_id != null) &&
450
+ configurable?.thread_id !== threadId) ||
451
+ (configurable?.__librechat_checkpoint_ns != null &&
452
+ configurable.__librechat_checkpoint_ns !==
453
+ boundConfigurable.__librechat_checkpoint_ns) ||
454
+ typeof ns !== 'string' ||
455
+ (configurable?.checkpoint_id != null &&
456
+ typeof configurable.checkpoint_id !== 'string')
457
+ ) {
458
+ throw new Error('Checkpoint scope mismatch');
459
+ }
460
+ return {
461
+ configurable: {
462
+ thread_id: threadId,
463
+ checkpoint_ns: ns,
464
+ ...(configurable?.checkpoint_id != null
465
+ ? { checkpoint_id: configurable.checkpoint_id }
466
+ : {}),
467
+ ...Object.fromEntries(
468
+ Object.entries(boundConfigurable).filter(([key]) =>
469
+ key.startsWith('__librechat_')
470
+ )
471
+ ),
472
+ },
473
+ };
474
+ };
475
+ args[0] = scope(args[0]);
476
+ if (method === 'checkpoint.getTuple') return saver.getTuple(args[0]);
477
+ if (method === 'checkpoint.put') return saver.put(...args);
478
+ if (method === 'checkpoint.putWrites')
479
+ return saver.putWrites(
480
+ ...(data as Parameters<typeof saver.putWrites>)
481
+ );
482
+ if (method === 'checkpoint.list') {
483
+ const list = z
484
+ .object({
485
+ limit: z.number().int().nonnegative().optional(),
486
+ filter: z.record(z.string(), z.unknown()).optional(),
487
+ before: z
488
+ .object({
489
+ configurable: z.record(z.string(), z.unknown()).optional(),
490
+ })
491
+ .optional(),
492
+ })
493
+ .strict()
494
+ .parse(Array.isArray(data) ? (data[1] ?? {}) : {});
495
+ const limit = Math.min(list.limit ?? 32, 32);
496
+ if (limit === 0) return [];
497
+ const tuples = [];
498
+ for await (const tuple of saver.list(args[0], {
499
+ limit,
500
+ filter: list.filter,
501
+ before: list.before ? scope(list.before, true) : undefined,
502
+ })) {
503
+ tuples.push(tuple);
504
+ if (tuples.length >= limit) break;
505
+ }
506
+ return tuples;
507
+ }
508
+ throw new Error('Unsupported SDK operation');
509
+ },
510
+ });
511
+ const abort = (): void => {
512
+ execution.abort();
513
+ socket.close(1000);
514
+ finish();
515
+ };
516
+ options.signal?.addEventListener('abort', abort, { once: true });
517
+ if (options.signal?.aborted === true) abort();
518
+ const timer = setTimeout(abort, limits.maxRunMs);
519
+ timer.unref();
520
+ socket.once('close', () => {
521
+ clearTimeout(timer);
522
+ options.signal?.removeEventListener('abort', abort);
523
+ });
524
+ const agent =
525
+ 'agents' in config.graphConfig
526
+ ? config.graphConfig.agents[0]
527
+ : config.graphConfig;
528
+ const start: RemoteSdkStart = {
529
+ transportVersion: 2,
530
+ files: hostFileChannel?.descriptor,
531
+ modelAdmission: modelAdmission
532
+ ? { version: 1, maxEntries: hostServices!.modelLifecycle!.maxEntries }
533
+ : undefined,
534
+ model: hostModelChannel?.descriptor,
535
+ providerText: providerText?.descriptor,
536
+ hostTools: descriptors.length ? descriptors : undefined,
537
+ operation,
538
+ input,
539
+ resume,
540
+ commandOptions,
541
+ options: {
542
+ recursionLimit: options.recursionLimit,
543
+ configurable: {
544
+ thread_id: threadId,
545
+ checkpoint_ns: options.configurable?.checkpoint_ns,
546
+ __librechat_checkpoint_ns:
547
+ options.configurable?.__librechat_checkpoint_ns,
548
+ [TOOL_APPROVAL_EXECUTION_SCOPE_CONFIG_KEY]:
549
+ options.configurable?.[TOOL_APPROVAL_EXECUTION_SCOPE_CONFIG_KEY],
550
+ run_id: identity.runId,
551
+ user_id: identity.userId,
552
+ },
553
+ },
554
+ handlers: [
555
+ ...new Set([
556
+ ...Object.keys(config.customHandlers ?? {}),
557
+ GraphEvents.ON_RUN_STEP,
558
+ GraphEvents.ON_RUN_STEP_DELTA,
559
+ GraphEvents.ON_RUN_STEP_COMPLETED,
560
+ GraphEvents.ON_RUN_STEP_CLOSED,
561
+ GraphEvents.ON_MESSAGE_DELTA,
562
+ GraphEvents.ON_REASONING_DELTA,
563
+ ]),
564
+ ].filter((name) => name !== GraphEvents.ON_TOOL_EXECUTE),
565
+ hooks: advertisedHooks,
566
+ checkpoint: Boolean(saver),
567
+ humanInTheLoop: config.humanInTheLoop,
568
+ streamLimits: config.streamLimits,
569
+ agent: {
570
+ id: identity.agentId,
571
+ name: agent.name,
572
+ instructions: agent.instructions,
573
+ model: hostServices?.modelProfile,
574
+ },
575
+ };
576
+ void (async (): Promise<void> => {
577
+ const capabilities = (await peer.call('capabilities', null)) as
578
+ | {
579
+ transportVersion?: number;
580
+ hostFiles?: number;
581
+ hostTools?: number;
582
+ providerText?: number;
583
+ hostModel?: number;
584
+ builderModel?: number;
585
+ modelAdmission?: number;
586
+ modelAdmissionWithProviderText?: number;
587
+ }
588
+ | null
589
+ | undefined;
590
+ if (capabilities?.transportVersion !== 2)
591
+ throw new Error('Worker transport capability unavailable');
592
+ if (hostFileChannel && capabilities.hostFiles !== 1)
593
+ throw new Error('Worker host file capability unavailable');
594
+ if (modelAdmission && capabilities.modelAdmission !== 1)
595
+ throw new Error('Worker model admission capability unavailable');
596
+ if (
597
+ modelAdmission &&
598
+ hostServices.providerText &&
599
+ capabilities.modelAdmissionWithProviderText !== 1
600
+ )
601
+ throw new Error(
602
+ 'Worker protected model admission capability unavailable'
603
+ );
604
+ if (hostServices?.modelProfile && capabilities.builderModel !== 1)
605
+ throw new Error('Worker builder model capability unavailable');
606
+ if (hostServices?.model && capabilities.hostModel !== 1)
607
+ throw new Error('Worker host model capability unavailable');
608
+ if (providerText && capabilities.providerText !== 1)
609
+ throw new Error('Worker provider policy capability unavailable');
610
+ if (descriptors.length) {
611
+ if (capabilities.hostTools !== 2)
612
+ throw new Error('Worker host tool capability unavailable');
613
+ }
614
+ await peer.call('run', start);
615
+ })().catch(() => finish());
616
+ });
617
+ try {
618
+ snapshot = await result;
619
+ if (
620
+ operation === 'resume' &&
621
+ resumeState != null &&
622
+ resumeState.content.length > 0
623
+ ) {
624
+ snapshot.content = reconcileRemoteResumeContent(
625
+ projection.contentParts.slice(0, resumeState.content.length),
626
+ snapshot
627
+ );
628
+ }
629
+ if (snapshot.runSteps) graph.restoreRunStepResumeState(snapshot.runSteps);
630
+ return snapshot.content?.filter(Boolean);
631
+ } finally {
632
+ execution.abort();
633
+ hostServices?.modelLifecycle?.dispose();
634
+ providerText?.dispose();
635
+ hostModelChannel?.dispose();
636
+ hostFileChannel?.dispose();
637
+ // A failed/cancelled remote run may leave host cleanup running. Keep the host
638
+ // execution enrolled until those handlers drain, even if the wire has closed.
639
+ await Promise.allSettled([...hostInvocations]);
640
+ socket.close(1000);
641
+ if ('waitForClose' in socket) {
642
+ let timeout: ReturnType<typeof setTimeout> | undefined;
643
+ await Promise.race([
644
+ socket.waitForClose(),
645
+ new Promise<void>((resolve) => {
646
+ timeout = setTimeout(() => {
647
+ socket.terminate();
648
+ resolve();
649
+ }, remote.recovery!.maxDisconnectMs);
650
+ }),
651
+ ]);
652
+ clearTimeout(timeout);
653
+ }
654
+ if (snapshot?.interrupt == null)
655
+ config.hooks?.clearSession(identity.runId);
656
+ }
657
+ };
658
+ run.processStream = (
659
+ input,
660
+ options
661
+ ): Promise<MessageContentComplex[] | undefined> => {
662
+ if (!('messages' in input))
663
+ throw new Error('Use the SDK resume entry point for continuation');
664
+ return execute('start', input, options);
665
+ };
666
+ run.resume = (
667
+ resume,
668
+ options,
669
+ _streamOptions,
670
+ commandOptions
671
+ ): Promise<MessageContentComplex[] | undefined> =>
672
+ execute('resume', { messages: [] }, options, resume, commandOptions);
673
+ return run;
674
+ }