@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,503 @@
1
+ import { z } from 'zod';
2
+ import { randomUUID } from 'node:crypto';
3
+ import type {
4
+ HostFileService,
5
+ HostFileDescriptor,
6
+ HostFileErrorCode,
7
+ HostFileBindings,
8
+ HostFileReadRequest,
9
+ HostFileStageRequest,
10
+ HostFilePublishRequest,
11
+ } from '@/index';
12
+ import type {
13
+ RemoteSdkHostServices,
14
+ RemoteSdkLimits,
15
+ RemoteSdkStart,
16
+ } from './types';
17
+ import type { SdkAgentIdentity } from './identity';
18
+ import type { SdkRpc } from './peer';
19
+ import {
20
+ HostFileAdmission,
21
+ HostFileServiceError,
22
+ createHostFileBindings,
23
+ hostFileDescriptorSchema,
24
+ hostFileServiceDescriptorSchema,
25
+ hostFileReadRequestSchema,
26
+ hostFileStageRequestSchema,
27
+ hostFilePublishRequestSchema,
28
+ } from '@/index';
29
+ import { createPolicyReceiver, createPolicySender } from './sealed';
30
+ import { encodeSdkValue, decodeSdkValue } from './wire';
31
+
32
+ export const fileChannelSchema = z
33
+ .object({
34
+ version: z.literal(1),
35
+ publicKey: z.string().length(60),
36
+ descriptor: hostFileServiceDescriptorSchema,
37
+ sources: z.array(hostFileDescriptorSchema),
38
+ })
39
+ .strict();
40
+ const envelopeSchema = z
41
+ .object({
42
+ id: z.string().uuid(),
43
+ publicKey: z.string().length(60),
44
+ request: z.unknown(),
45
+ })
46
+ .strict();
47
+ const chunkSchema = z
48
+ .object({
49
+ id: z.string().uuid(),
50
+ index: z.number().int().nonnegative(),
51
+ })
52
+ .strict();
53
+ const resultSchema = z.discriminatedUnion('ok', [
54
+ z
55
+ .object({ version: z.literal(1), ok: z.literal(true), value: z.unknown() })
56
+ .strict(),
57
+ z
58
+ .object({
59
+ version: z.literal(1),
60
+ ok: z.literal(false),
61
+ code: z.enum([
62
+ 'incompatible',
63
+ 'forbidden',
64
+ 'conflict',
65
+ 'overflow',
66
+ 'cancelled',
67
+ 'timeout',
68
+ 'unavailable',
69
+ ]),
70
+ })
71
+ .strict(),
72
+ ]);
73
+ type FileChannelResult = z.infer<typeof resultSchema>;
74
+ type FileChannelCall = (
75
+ method: string,
76
+ data: unknown,
77
+ signal?: AbortSignal
78
+ ) => Promise<FileChannelResult>;
79
+ const bytesSchema = z.instanceof(Uint8Array);
80
+ const uploadSchema = z.discriminatedUnion('done', [
81
+ z.object({ done: z.literal(true) }).strict(),
82
+ z.object({ done: z.literal(false), data: bytesSchema }).strict(),
83
+ ]);
84
+
85
+ function failure(
86
+ error: unknown,
87
+ signal?: AbortSignal
88
+ ): {
89
+ version: 1;
90
+ ok: false;
91
+ code:
92
+ | 'incompatible'
93
+ | 'forbidden'
94
+ | 'overflow'
95
+ | 'timeout'
96
+ | 'cancelled'
97
+ | 'unavailable'
98
+ | 'conflict';
99
+ } {
100
+ let code: HostFileErrorCode = 'unavailable';
101
+ if (error instanceof HostFileServiceError) code = error.code;
102
+ if (signal?.aborted === true) code = 'cancelled';
103
+ return { version: 1 as const, ok: false as const, code };
104
+ }
105
+
106
+ function parseRequest(
107
+ method: string,
108
+ request: unknown
109
+ ): HostFileReadRequest | HostFileStageRequest | HostFilePublishRequest {
110
+ if (method === 'files.read') return hostFileReadRequestSchema.parse(request);
111
+ if (method === 'files.stage')
112
+ return hostFileStageRequestSchema.parse(request);
113
+ if (method === 'files.publish')
114
+ return hostFilePublishRequestSchema.parse(request);
115
+ throw new HostFileServiceError('incompatible');
116
+ }
117
+
118
+ function reply(value: unknown): unknown {
119
+ const result = resultSchema.safeParse(value);
120
+ if (!result.success) throw new HostFileServiceError('incompatible');
121
+ if (!result.data.ok) throw new HostFileServiceError(result.data.code);
122
+ return result.data.value;
123
+ }
124
+
125
+ /** Leave room for two base64 encodings, metadata, encryption, and the RPC envelope. */
126
+ function chunkLimit(limits: RemoteSdkLimits): number {
127
+ const bytes = Math.floor(
128
+ (Math.min(limits.maxFrameBytes, limits.maxBufferedBytes) - 8192) / 4
129
+ );
130
+ if (bytes < 1) throw new HostFileServiceError('overflow');
131
+ return bytes;
132
+ }
133
+
134
+ function sealValue(
135
+ seal: ReturnType<typeof createPolicySender>,
136
+ value: unknown,
137
+ limits: RemoteSdkLimits
138
+ ): {
139
+ version: 1;
140
+ publicKey: string;
141
+ nonce: string;
142
+ tag: string;
143
+ ciphertext: string;
144
+ } {
145
+ const sealed = seal(JSON.stringify(encodeSdkValue(value)));
146
+ // RPC ids/methods are bounded by the peer. Include their envelope budget before sending.
147
+ if (
148
+ Buffer.byteLength(JSON.stringify(sealed)) + 256 >
149
+ Math.min(limits.maxFrameBytes, limits.maxBufferedBytes)
150
+ )
151
+ throw new HostFileServiceError('overflow');
152
+ return sealed;
153
+ }
154
+
155
+ /** File contents are sealed before they reach RPC queues or durable recovery journals. */
156
+ export function createHostFileChannel(options: {
157
+ files: NonNullable<RemoteSdkHostServices['files']>;
158
+ identity: Readonly<SdkAgentIdentity>;
159
+ peer: { call: SdkRpc };
160
+ limits: RemoteSdkLimits;
161
+ signal: AbortSignal;
162
+ }): {
163
+ descriptor: NonNullable<RemoteSdkStart['files']>;
164
+ dispose(): void;
165
+ call: FileChannelCall;
166
+ } {
167
+ const receiver = createPolicyReceiver(options.limits.maxFrameBytes, 'files');
168
+ const descriptor = {
169
+ ...options.files.descriptor,
170
+ maxChunkBytes: Math.min(
171
+ options.files.descriptor.maxChunkBytes,
172
+ chunkLimit(options.limits)
173
+ ),
174
+ };
175
+ // Reuse SDK validation, including duplicate operations and inconsistent limits.
176
+ createHostFileBindings({
177
+ identity: options.identity,
178
+ descriptor,
179
+ service: options.files.service,
180
+ });
181
+ const sources = options.files.sources.map((file) =>
182
+ hostFileDescriptorSchema.parse(file)
183
+ );
184
+ const active = new Set<string>();
185
+ return {
186
+ descriptor: {
187
+ version: 1 as const,
188
+ publicKey: receiver.publicKey,
189
+ descriptor,
190
+ sources,
191
+ },
192
+ dispose: receiver.dispose,
193
+ call: async (
194
+ method: string,
195
+ data: unknown,
196
+ invocationSignal?: AbortSignal
197
+ ): Promise<FileChannelResult> => {
198
+ const signal = invocationSignal
199
+ ? AbortSignal.any([options.signal, invocationSignal])
200
+ : options.signal;
201
+ let id: string | undefined;
202
+ try {
203
+ signal.throwIfAborted();
204
+ const envelope = envelopeSchema.parse(
205
+ decodeSdkValue(JSON.parse(receiver.open(data)))
206
+ );
207
+ if (active.has(envelope.id)) throw new HostFileServiceError('conflict');
208
+ id = envelope.id;
209
+ active.add(id);
210
+ const seal = createPolicySender(
211
+ envelope.publicKey,
212
+ options.limits.maxFrameBytes,
213
+ 'files'
214
+ );
215
+ const request = parseRequest(method, envelope.request);
216
+ for (const key of [
217
+ 'runtimeId',
218
+ 'agentId',
219
+ 'runId',
220
+ 'userId',
221
+ 'tenantId',
222
+ 'conversationId',
223
+ ] as const)
224
+ if (request.identity[key] !== options.identity[key])
225
+ throw new HostFileServiceError('forbidden');
226
+ let value: unknown;
227
+ if ('offset' in request) {
228
+ if (!descriptor.operations.includes('read'))
229
+ throw new HostFileServiceError('forbidden');
230
+ if (request.length > descriptor.maxChunkBytes)
231
+ throw new HostFileServiceError('overflow');
232
+ value = await options.files.service.read(request, signal);
233
+ } else if ('filename' in request) {
234
+ if (!descriptor.operations.includes('stage'))
235
+ throw new HostFileServiceError('forbidden');
236
+ if (request.bytes > descriptor.maxFileBytes)
237
+ throw new HostFileServiceError('overflow');
238
+ const content = async function* (): AsyncGenerator<
239
+ Uint8Array,
240
+ void,
241
+ unknown
242
+ > {
243
+ for (let index = 0; ; index++) {
244
+ signal.throwIfAborted();
245
+ const packet = reply(
246
+ await options.peer.call(
247
+ 'files.chunk',
248
+ sealValue(seal, { id: envelope.id, index }, options.limits),
249
+ options.limits.rpcTimeoutMs,
250
+ signal
251
+ )
252
+ );
253
+ const received = z
254
+ .object({
255
+ id: z.literal(envelope.id),
256
+ index: z.literal(index),
257
+ chunk: uploadSchema,
258
+ })
259
+ .strict()
260
+ .parse(decodeSdkValue(JSON.parse(receiver.open(packet))));
261
+ const chunk = received.chunk;
262
+ if (chunk.done) return;
263
+ if (chunk.data.byteLength > descriptor.maxChunkBytes)
264
+ throw new HostFileServiceError('overflow');
265
+ yield chunk.data;
266
+ }
267
+ };
268
+ value = await options.files.service.stage(request, content(), signal);
269
+ } else {
270
+ if (!descriptor.operations.includes('publish'))
271
+ throw new HostFileServiceError('forbidden');
272
+ value = await options.files.service.publish(request, signal);
273
+ }
274
+ return {
275
+ version: 1 as const,
276
+ ok: true as const,
277
+ value: sealValue(seal, { id, value }, options.limits),
278
+ };
279
+ } catch (error) {
280
+ return failure(error, signal);
281
+ } finally {
282
+ if (id != null) active.delete(id);
283
+ }
284
+ },
285
+ };
286
+ }
287
+
288
+ /** Pull uploads one chunk at a time; no whole-file buffer and no speculative producer reads. */
289
+ export function createWorkerFileChannel(options: {
290
+ peer: { call: SdkRpc };
291
+ limits: RemoteSdkLimits;
292
+ signal: AbortSignal;
293
+ }): {
294
+ dispose(): void;
295
+ accept(data: unknown, signal?: AbortSignal): Promise<FileChannelResult>;
296
+ bind(
297
+ identity: Readonly<SdkAgentIdentity>,
298
+ input: NonNullable<RemoteSdkStart['files']>
299
+ ): HostFileBindings & { sources: readonly HostFileDescriptor[] };
300
+ } {
301
+ let receiver: ReturnType<typeof createPolicyReceiver> | undefined;
302
+ const uploads = new Map<
303
+ string,
304
+ {
305
+ iterator: AsyncIterator<Uint8Array>;
306
+ signal: AbortSignal;
307
+ index: number;
308
+ pulling: boolean;
309
+ }
310
+ >();
311
+ let bound = false;
312
+ let seal: ReturnType<typeof createPolicySender> | undefined;
313
+ let maxChunkBytes = 0;
314
+ return {
315
+ dispose: (): void | undefined => receiver?.dispose(),
316
+ accept: async (
317
+ data: unknown,
318
+ invocationSignal?: AbortSignal
319
+ ): Promise<FileChannelResult> => {
320
+ try {
321
+ if (!seal || !receiver) throw new HostFileServiceError('forbidden');
322
+ const chunk = chunkSchema.parse(
323
+ decodeSdkValue(JSON.parse(receiver.open(data)))
324
+ );
325
+ const upload = uploads.get(chunk.id);
326
+ if (!upload || upload.pulling || upload.index !== chunk.index)
327
+ throw new HostFileServiceError('conflict');
328
+ upload.signal.throwIfAborted();
329
+ invocationSignal?.throwIfAborted();
330
+ upload.pulling = true;
331
+ try {
332
+ const next = await upload.iterator.next();
333
+ upload.signal.throwIfAborted();
334
+ invocationSignal?.throwIfAborted();
335
+ if (
336
+ next.done !== true &&
337
+ (!(next.value instanceof Uint8Array) ||
338
+ next.value.byteLength > maxChunkBytes)
339
+ )
340
+ throw new HostFileServiceError('overflow');
341
+ upload.index++;
342
+ return {
343
+ version: 1 as const,
344
+ ok: true as const,
345
+ value: sealValue(
346
+ seal,
347
+ {
348
+ id: chunk.id,
349
+ index: chunk.index,
350
+ chunk:
351
+ next.done === true
352
+ ? { done: true }
353
+ : { done: false, data: next.value },
354
+ },
355
+ options.limits
356
+ ),
357
+ };
358
+ } finally {
359
+ upload.pulling = false;
360
+ }
361
+ } catch (error) {
362
+ return failure(error, options.signal);
363
+ }
364
+ },
365
+ bind: (
366
+ identity: Readonly<SdkAgentIdentity>,
367
+ input: NonNullable<RemoteSdkStart['files']>
368
+ ): HostFileBindings & { sources: readonly HostFileDescriptor[] } => {
369
+ if (bound) throw new HostFileServiceError('conflict');
370
+ const channel = fileChannelSchema.parse(input);
371
+ if (channel.descriptor.maxChunkBytes > chunkLimit(options.limits))
372
+ throw new HostFileServiceError('overflow');
373
+ maxChunkBytes = channel.descriptor.maxChunkBytes;
374
+ seal = createPolicySender(
375
+ channel.publicKey,
376
+ options.limits.maxFrameBytes,
377
+ 'files'
378
+ );
379
+ const recipient = createPolicyReceiver(
380
+ options.limits.maxFrameBytes,
381
+ 'files'
382
+ );
383
+ receiver = recipient;
384
+ bound = true;
385
+ const admission = new HostFileAdmission({
386
+ maxConcurrentOperations: Math.max(
387
+ 1,
388
+ Math.floor(options.limits.maxBufferedBytes / (2 * maxChunkBytes))
389
+ ),
390
+ maxBufferedBytes: options.limits.maxBufferedBytes,
391
+ });
392
+ const invoke = async (
393
+ method: string,
394
+ request: unknown,
395
+ signal: AbortSignal,
396
+ id = randomUUID()
397
+ ): Promise<unknown> => {
398
+ signal.throwIfAborted();
399
+ const result = reply(
400
+ await options.peer.call(
401
+ method,
402
+ sealValue(
403
+ seal!,
404
+ {
405
+ id,
406
+ publicKey: recipient.publicKey,
407
+ request,
408
+ },
409
+ options.limits
410
+ ),
411
+ options.limits.maxRunMs,
412
+ signal
413
+ )
414
+ );
415
+ const envelope = z
416
+ .object({ id: z.literal(id), value: z.unknown() })
417
+ .strict()
418
+ .parse(decodeSdkValue(JSON.parse(recipient.open(result))));
419
+ return envelope.value;
420
+ };
421
+ const bindSignal = (signal?: AbortSignal): AbortSignal =>
422
+ signal ? AbortSignal.any([options.signal, signal]) : options.signal;
423
+ const service: HostFileService = {
424
+ version: 1,
425
+ read: async (request, signal) => {
426
+ const release = admission.acquire(2 * maxChunkBytes);
427
+ try {
428
+ return z
429
+ .object({
430
+ reference: z.string(),
431
+ revision: z.string(),
432
+ offset: z.number(),
433
+ data: bytesSchema,
434
+ })
435
+ .strict()
436
+ .parse(await invoke('files.read', request, bindSignal(signal)));
437
+ } finally {
438
+ release();
439
+ }
440
+ },
441
+ stage: async (request, content, signal) => {
442
+ const release = admission.acquire(2 * maxChunkBytes);
443
+ const id = randomUUID();
444
+ let iterator: AsyncIterator<Uint8Array>;
445
+ try {
446
+ iterator = content[Symbol.asyncIterator]();
447
+ } catch (error) {
448
+ release();
449
+ throw error;
450
+ }
451
+ const boundSignal = bindSignal(signal);
452
+ uploads.set(id, {
453
+ iterator,
454
+ signal: boundSignal,
455
+ index: 0,
456
+ pulling: false,
457
+ });
458
+ try {
459
+ return hostFileDescriptorSchema.parse(
460
+ await invoke('files.stage', request, boundSignal, id)
461
+ );
462
+ } finally {
463
+ // A cancelled generator may still be cleaning up: keep its capacity charged.
464
+ void Promise.resolve()
465
+ .then(() => iterator.return?.())
466
+ .catch(() => undefined)
467
+ .finally(() => {
468
+ uploads.delete(id);
469
+ release();
470
+ });
471
+ }
472
+ },
473
+ publish: async (request, signal) => {
474
+ const release = admission.acquire(2 * maxChunkBytes);
475
+ try {
476
+ return z
477
+ .object({
478
+ operationId: z.string(),
479
+ file: hostFileDescriptorSchema,
480
+ })
481
+ .strict()
482
+ .parse(
483
+ await invoke('files.publish', request, bindSignal(signal))
484
+ );
485
+ } finally {
486
+ release();
487
+ }
488
+ },
489
+ };
490
+ const bindings = createHostFileBindings({
491
+ identity,
492
+ descriptor: channel.descriptor,
493
+ service,
494
+ });
495
+ return {
496
+ ...bindings,
497
+ sources: Object.freeze(
498
+ channel.sources.map((file): HostFileDescriptor => Object.freeze(file))
499
+ ),
500
+ };
501
+ },
502
+ };
503
+ }