@librechat/agents 4.2.9 → 4.2.10

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 (84) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +32 -2
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/harness/fileBindings.cjs +93 -0
  4. package/dist/cjs/harness/fileBindings.cjs.map +1 -0
  5. package/dist/cjs/harness/fileService.cjs +141 -0
  6. package/dist/cjs/harness/fileService.cjs.map +1 -0
  7. package/dist/cjs/harness/fileStream.cjs +76 -0
  8. package/dist/cjs/harness/fileStream.cjs.map +1 -0
  9. package/dist/cjs/harness/files.cjs +106 -0
  10. package/dist/cjs/harness/files.cjs.map +1 -0
  11. package/dist/cjs/harness/index.cjs +3 -0
  12. package/dist/cjs/harness/index.cjs.map +1 -1
  13. package/dist/cjs/llm/google/utils/signatures.cjs +5 -3
  14. package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -1
  15. package/dist/cjs/main.cjs +13 -0
  16. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +3 -2
  17. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  18. package/dist/cjs/tools/ProgrammaticCallerPolicy.cjs +24 -1
  19. package/dist/cjs/tools/ProgrammaticCallerPolicy.cjs.map +1 -1
  20. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +3 -2
  21. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  22. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs +2 -1
  23. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs.map +1 -1
  24. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +15 -3
  25. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  26. package/dist/cjs/tools/subagent/childGraphConfig.cjs +13 -1
  27. package/dist/cjs/tools/subagent/childGraphConfig.cjs.map +1 -1
  28. package/dist/cjs/tools/subagent/hostArgs.cjs +2 -0
  29. package/dist/cjs/tools/subagent/hostArgs.cjs.map +1 -1
  30. package/dist/esm/agents/AgentContext.mjs +32 -2
  31. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  32. package/dist/esm/harness/fileBindings.mjs +93 -0
  33. package/dist/esm/harness/fileBindings.mjs.map +1 -0
  34. package/dist/esm/harness/fileService.mjs +140 -0
  35. package/dist/esm/harness/fileService.mjs.map +1 -0
  36. package/dist/esm/harness/fileStream.mjs +76 -0
  37. package/dist/esm/harness/fileStream.mjs.map +1 -0
  38. package/dist/esm/harness/files.mjs +97 -0
  39. package/dist/esm/harness/files.mjs.map +1 -0
  40. package/dist/esm/harness/index.mjs +3 -0
  41. package/dist/esm/harness/index.mjs.map +1 -1
  42. package/dist/esm/llm/google/utils/signatures.mjs +5 -3
  43. package/dist/esm/llm/google/utils/signatures.mjs.map +1 -1
  44. package/dist/esm/main.mjs +5 -2
  45. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +3 -2
  46. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  47. package/dist/esm/tools/ProgrammaticCallerPolicy.mjs +24 -1
  48. package/dist/esm/tools/ProgrammaticCallerPolicy.mjs.map +1 -1
  49. package/dist/esm/tools/ProgrammaticToolCalling.mjs +3 -2
  50. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  51. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs +2 -1
  52. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs.map +1 -1
  53. package/dist/esm/tools/subagent/SubagentExecutor.mjs +15 -3
  54. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  55. package/dist/esm/tools/subagent/childGraphConfig.mjs +13 -1
  56. package/dist/esm/tools/subagent/childGraphConfig.mjs.map +1 -1
  57. package/dist/esm/tools/subagent/hostArgs.mjs +2 -1
  58. package/dist/esm/tools/subagent/hostArgs.mjs.map +1 -1
  59. package/dist/types/harness/fileBindings.d.ts +13 -0
  60. package/dist/types/harness/fileService.d.ts +37 -0
  61. package/dist/types/harness/fileStream.d.ts +7 -0
  62. package/dist/types/harness/files.d.ts +108 -0
  63. package/dist/types/harness/index.d.ts +6 -0
  64. package/dist/types/tools/ProgrammaticCallerPolicy.d.ts +1 -0
  65. package/dist/types/tools/subagent/hostArgs.d.ts +6 -0
  66. package/dist/types/tools/subagent/index.d.ts +1 -1
  67. package/dist/types/types/graph.d.ts +6 -3
  68. package/package.json +1 -1
  69. package/src/agents/AgentContext.ts +68 -2
  70. package/src/harness/fileBindings.ts +156 -0
  71. package/src/harness/fileService.ts +217 -0
  72. package/src/harness/fileStream.ts +99 -0
  73. package/src/harness/files.ts +185 -0
  74. package/src/harness/index.ts +24 -0
  75. package/src/llm/google/utils/signatures.ts +10 -3
  76. package/src/tools/BashProgrammaticToolCalling.ts +5 -2
  77. package/src/tools/ProgrammaticCallerPolicy.ts +42 -3
  78. package/src/tools/ProgrammaticToolCalling.ts +4 -1
  79. package/src/tools/local/LocalProgrammaticToolCalling.ts +4 -0
  80. package/src/tools/subagent/SubagentExecutor.ts +98 -32
  81. package/src/tools/subagent/childGraphConfig.ts +33 -1
  82. package/src/tools/subagent/hostArgs.ts +7 -0
  83. package/src/tools/subagent/index.ts +1 -0
  84. package/src/types/graph.ts +6 -3
@@ -0,0 +1,217 @@
1
+ import type {
2
+ HostFileService,
3
+ HostFileChunk,
4
+ HostFileDescriptor,
5
+ HostFilePublication,
6
+ HostFileServiceDescriptor,
7
+ HostFileReadRequest,
8
+ HostFileStageRequest,
9
+ HostFilePublishRequest,
10
+ } from './files';
11
+ import type { ExecutionIdentity } from './identity';
12
+ import {
13
+ HostFileServiceError,
14
+ normalizeHostFileError,
15
+ checkedHostFile,
16
+ checkedHostFileChunk,
17
+ checkedHostFileService,
18
+ hostFileReadRequestSchema,
19
+ hostFileStageRequestSchema,
20
+ hostFilePublishRequestSchema,
21
+ } from './files';
22
+ import {
23
+ snapshotExecutionIdentity,
24
+ matchesExecutionIdentity,
25
+ } from './identity';
26
+ import { createFileUpload } from './fileStream';
27
+
28
+ function positive(value: number): void {
29
+ if (!Number.isSafeInteger(value) || value <= 0)
30
+ throw new HostFileServiceError('incompatible');
31
+ }
32
+
33
+ /** Share across bindings in the host's quota scope. Hung storage retains its slot and byte reservation. */
34
+ export class HostFileAdmission {
35
+ private operations = 0;
36
+ private bytes = 0;
37
+ private readonly maxConcurrentOperations: number;
38
+ private readonly maxBufferedBytes: number;
39
+ constructor(limits: {
40
+ maxConcurrentOperations: number;
41
+ maxBufferedBytes: number;
42
+ }) {
43
+ positive(limits.maxConcurrentOperations);
44
+ positive(limits.maxBufferedBytes);
45
+ this.maxConcurrentOperations = limits.maxConcurrentOperations;
46
+ this.maxBufferedBytes = limits.maxBufferedBytes;
47
+ }
48
+ snapshot(): Readonly<{ operations: number; reservedBytes: number }> {
49
+ return Object.freeze({
50
+ operations: this.operations,
51
+ reservedBytes: this.bytes,
52
+ });
53
+ }
54
+ /** @internal Reservations are released only when storage and input cleanup settle. */
55
+ acquire(bytes: number): () => void {
56
+ if (!Number.isSafeInteger(bytes) || bytes < 0)
57
+ throw new HostFileServiceError('incompatible');
58
+ if (
59
+ this.operations >= this.maxConcurrentOperations ||
60
+ bytes > this.maxBufferedBytes - this.bytes
61
+ )
62
+ throw new HostFileServiceError('overflow');
63
+ this.operations++;
64
+ this.bytes += bytes;
65
+ let released = false;
66
+ return () => {
67
+ if (released) return;
68
+ released = true;
69
+ this.operations--;
70
+ this.bytes -= bytes;
71
+ };
72
+ }
73
+ }
74
+
75
+ /**
76
+ * The host adapter owns canonical ACL/revision checks on every operation, durable operation-ID
77
+ * reconciliation, private staging/cleanup, and publication through the native file pipeline.
78
+ * A request identity is asserted against the authenticated binding before any adapter call.
79
+ */
80
+ export type HostFileStore = Omit<HostFileService, 'version'>;
81
+
82
+ export function createHostFileService(options: {
83
+ identity: Readonly<ExecutionIdentity>;
84
+ descriptor: HostFileServiceDescriptor;
85
+ store: HostFileStore;
86
+ admission: HostFileAdmission;
87
+ timeoutMs: number;
88
+ /** Lifetime of the authenticated execution, independent of individual RPC cancellation. */
89
+ signal?: AbortSignal;
90
+ }): { descriptor: HostFileServiceDescriptor; service: HostFileService } {
91
+ const identity = snapshotExecutionIdentity(options.identity);
92
+ const descriptor = checkedHostFileService(options.descriptor);
93
+ const { store, admission, timeoutMs, signal: runSignal } = options;
94
+ positive(timeoutMs);
95
+ if (timeoutMs > 2147483647) throw new HostFileServiceError('incompatible');
96
+
97
+ function authorize(
98
+ operation: HostFileServiceDescriptor['operations'][number],
99
+ value: ExecutionIdentity
100
+ ): void {
101
+ if (
102
+ !descriptor.operations.includes(operation) ||
103
+ !matchesExecutionIdentity(identity, value)
104
+ )
105
+ throw new HostFileServiceError('forbidden');
106
+ }
107
+
108
+ async function execute<T>(
109
+ bytes: number,
110
+ signal: AbortSignal | undefined,
111
+ work: (signal: AbortSignal) => Promise<T>
112
+ ): Promise<T> {
113
+ const parent =
114
+ runSignal && signal
115
+ ? AbortSignal.any([runSignal, signal])
116
+ : (runSignal ?? signal);
117
+ if (parent?.aborted === true) throw new HostFileServiceError('cancelled');
118
+ const release = admission.acquire(bytes);
119
+ const controller = new AbortController();
120
+ const cancel = (): void =>
121
+ controller.abort(new HostFileServiceError('cancelled'));
122
+ parent?.addEventListener('abort', cancel, { once: true });
123
+ const timer = setTimeout(
124
+ () => controller.abort(new HostFileServiceError('timeout')),
125
+ timeoutMs
126
+ );
127
+ timer.unref();
128
+ let onAbort = (): void => undefined;
129
+ const aborted = new Promise<never>((_resolve, reject) => {
130
+ onAbort = (): void =>
131
+ reject(normalizeHostFileError(undefined, controller.signal));
132
+ controller.signal.addEventListener('abort', onAbort, { once: true });
133
+ });
134
+ const pending = Promise.resolve()
135
+ .then(async () => {
136
+ controller.signal.throwIfAborted();
137
+ return work(controller.signal);
138
+ })
139
+ .finally(release);
140
+ try {
141
+ const result = await Promise.race([pending, aborted]);
142
+ controller.signal.throwIfAborted();
143
+ return result;
144
+ } catch (error) {
145
+ throw normalizeHostFileError(error, controller.signal);
146
+ } finally {
147
+ clearTimeout(timer);
148
+ parent?.removeEventListener('abort', cancel);
149
+ controller.signal.removeEventListener('abort', onAbort);
150
+ controller.abort();
151
+ }
152
+ }
153
+
154
+ return {
155
+ descriptor,
156
+ service: {
157
+ version: 1,
158
+ read: async (input, signal): Promise<HostFileChunk> => {
159
+ const parsed = hostFileReadRequestSchema.safeParse(input);
160
+ if (!parsed.success) throw new HostFileServiceError('incompatible');
161
+ const request: HostFileReadRequest = { ...parsed.data, identity };
162
+ authorize('read', parsed.data.identity);
163
+ if (
164
+ request.length > descriptor.maxChunkBytes ||
165
+ request.offset > descriptor.maxFileBytes - request.length
166
+ )
167
+ throw new HostFileServiceError('overflow');
168
+ return execute(request.length * 2, signal, async (active) =>
169
+ checkedHostFileChunk(await store.read(request, active), request)
170
+ );
171
+ },
172
+ stage: async (input, content, signal): Promise<HostFileDescriptor> => {
173
+ const parsed = hostFileStageRequestSchema.safeParse(input);
174
+ if (!parsed.success) throw new HostFileServiceError('incompatible');
175
+ authorize('stage', parsed.data.identity);
176
+ const request: HostFileStageRequest = { ...parsed.data, identity };
177
+ if (request.bytes > descriptor.maxFileBytes)
178
+ throw new HostFileServiceError('overflow');
179
+ return execute(descriptor.maxChunkBytes * 2, signal, async (active) => {
180
+ const upload = createFileUpload(
181
+ content,
182
+ request,
183
+ descriptor.maxChunkBytes,
184
+ active,
185
+ true
186
+ );
187
+ try {
188
+ const file = checkedHostFile(
189
+ await store.stage(request, upload.content, active)
190
+ );
191
+ const sha256 = upload.finish();
192
+ if (file.bytes !== request.bytes || file.sha256 !== sha256)
193
+ throw new HostFileServiceError('incompatible');
194
+ return file;
195
+ } finally {
196
+ await upload.close();
197
+ }
198
+ });
199
+ },
200
+ publish: async (input, signal): Promise<HostFilePublication> => {
201
+ const parsed = hostFilePublishRequestSchema.safeParse(input);
202
+ if (!parsed.success) throw new HostFileServiceError('incompatible');
203
+ authorize('publish', parsed.data.identity);
204
+ const request: HostFilePublishRequest = { ...parsed.data, identity };
205
+ return execute(0, signal, async (active) => {
206
+ const result = await store.publish(request, active);
207
+ if (result.operationId !== request.operationId)
208
+ throw new HostFileServiceError('incompatible');
209
+ const file = checkedHostFile(result.file);
210
+ if (file.bytes > descriptor.maxFileBytes)
211
+ throw new HostFileServiceError('overflow');
212
+ return { operationId: request.operationId, file };
213
+ });
214
+ },
215
+ },
216
+ };
217
+ }
@@ -0,0 +1,99 @@
1
+ import { createHash } from 'node:crypto';
2
+ import type { HostFileStageRequest } from './files';
3
+ import { HostFileServiceError } from './files';
4
+
5
+ /** Single-consumer, bounded upload. Cleanup is owned by the operation, not the transport. */
6
+ export function createFileUpload(
7
+ source: AsyncIterable<Uint8Array>,
8
+ request: Pick<HostFileStageRequest, 'bytes' | 'sha256'>,
9
+ maxChunkBytes: number,
10
+ signal?: AbortSignal,
11
+ hash = false
12
+ ): {
13
+ content: AsyncIterable<Uint8Array>;
14
+ finish: () => string | undefined;
15
+ close: () => Promise<void>;
16
+ } {
17
+ const iterator = source[Symbol.asyncIterator]();
18
+ let closing: Promise<void> | undefined;
19
+ let started = false;
20
+ let complete = false;
21
+ let bytes = 0;
22
+ const checksum = hash ? createHash('sha256') : undefined;
23
+ let sha256: string | undefined;
24
+ const close = (): Promise<void> => {
25
+ closing ??= Promise.resolve().then(async () => {
26
+ await iterator.return?.();
27
+ });
28
+ return closing;
29
+ };
30
+ async function* stream(): AsyncGenerator<Uint8Array> {
31
+ try {
32
+ for (;;) {
33
+ signal?.throwIfAborted();
34
+ const next = await iterator.next();
35
+ signal?.throwIfAborted();
36
+ if (next.done === true) break;
37
+ if (!(next.value instanceof Uint8Array) || next.value.byteLength === 0)
38
+ throw new HostFileServiceError('incompatible');
39
+ if (
40
+ next.value.byteLength > maxChunkBytes ||
41
+ next.value.byteLength > request.bytes - bytes
42
+ )
43
+ throw new HostFileServiceError('overflow');
44
+ const chunk = Uint8Array.from(next.value);
45
+ bytes += chunk.byteLength;
46
+ checksum?.update(chunk);
47
+ yield chunk;
48
+ }
49
+ if (bytes !== request.bytes)
50
+ throw new HostFileServiceError('incompatible');
51
+ sha256 = checksum?.digest('hex');
52
+ if (
53
+ sha256 !== undefined &&
54
+ request.sha256 !== undefined &&
55
+ sha256 !== request.sha256
56
+ )
57
+ throw new HostFileServiceError('conflict');
58
+ complete = true;
59
+ } finally {
60
+ await close();
61
+ }
62
+ }
63
+ return {
64
+ content: {
65
+ [Symbol.asyncIterator](): AsyncIterator<Uint8Array> {
66
+ if (started || closing) throw new HostFileServiceError('incompatible');
67
+ started = true;
68
+ const generator = stream();
69
+ return {
70
+ next: (): Promise<IteratorResult<Uint8Array>> =>
71
+ closing
72
+ ? closing.then(() => ({ done: true, value: undefined }))
73
+ : generator.next(),
74
+ return: async (): Promise<IteratorResult<Uint8Array>> => {
75
+ try {
76
+ return await generator.return(undefined);
77
+ } finally {
78
+ await close();
79
+ }
80
+ },
81
+ throw: async (
82
+ error: unknown
83
+ ): Promise<IteratorResult<Uint8Array>> => {
84
+ try {
85
+ return await generator.throw(error);
86
+ } finally {
87
+ await close();
88
+ }
89
+ },
90
+ };
91
+ },
92
+ },
93
+ finish: (): string | undefined => {
94
+ if (!complete) throw new HostFileServiceError('incompatible');
95
+ return sha256;
96
+ },
97
+ close,
98
+ };
99
+ }
@@ -0,0 +1,185 @@
1
+ import { z } from 'zod';
2
+ import { executionIdentitySchema } from './identity';
3
+
4
+ const reference = z
5
+ .string()
6
+ .min(1)
7
+ .max(512)
8
+ .refine((value) => value.trim().length > 0);
9
+ const count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
10
+ const digest = z.string().regex(/^[a-f0-9]{64}$/);
11
+
12
+ /** Opaque host references and immutable revisions, never filesystem paths or signed URLs. */
13
+ export const hostFileDescriptorSchema = z.object({
14
+ reference,
15
+ revision: reference,
16
+ filename: z.string().min(1).max(255),
17
+ mediaType: z.string().min(1).max(255),
18
+ bytes: count,
19
+ sha256: digest.optional(),
20
+ });
21
+ export type HostFileDescriptor = Readonly<
22
+ z.infer<typeof hostFileDescriptorSchema>
23
+ >;
24
+
25
+ export const hostFileServiceDescriptorSchema = z.object({
26
+ version: z.literal(1),
27
+ operations: z.array(z.enum(['read', 'stage', 'publish'])).max(3),
28
+ maxFileBytes: count.positive(),
29
+ maxChunkBytes: count.positive(),
30
+ });
31
+ export type HostFileServiceDescriptor = Readonly<
32
+ Omit<z.infer<typeof hostFileServiceDescriptorSchema>, 'operations'>
33
+ > & { readonly operations: readonly ('read' | 'stage' | 'publish')[] };
34
+
35
+ const request = z.object({
36
+ version: z.literal(1),
37
+ identity: executionIdentitySchema,
38
+ });
39
+ export const hostFileReadRequestSchema = request.extend({
40
+ reference,
41
+ revision: reference,
42
+ offset: count,
43
+ length: count.positive(),
44
+ });
45
+ export const hostFileStageRequestSchema = request.extend({
46
+ operationId: reference,
47
+ filename: z.string().min(1).max(255),
48
+ mediaType: z.string().min(1).max(255),
49
+ bytes: count,
50
+ sha256: digest.optional(),
51
+ });
52
+ export const hostFilePublishRequestSchema = request.extend({
53
+ operationId: reference,
54
+ reference,
55
+ revision: reference,
56
+ });
57
+ export type HostFileReadRequest = Readonly<
58
+ z.infer<typeof hostFileReadRequestSchema>
59
+ >;
60
+ export type HostFileStageRequest = Readonly<
61
+ z.infer<typeof hostFileStageRequestSchema>
62
+ >;
63
+ export type HostFilePublishRequest = Readonly<
64
+ z.infer<typeof hostFilePublishRequestSchema>
65
+ >;
66
+ export interface HostFileChunk {
67
+ readonly reference: string;
68
+ readonly revision: string;
69
+ readonly offset: number;
70
+ readonly data: Uint8Array;
71
+ }
72
+ export interface HostFilePublication {
73
+ readonly operationId: string;
74
+ readonly file: HostFileDescriptor;
75
+ }
76
+
77
+ /**
78
+ * Authenticate the transport separately. Each operation must authorize the bound identity,
79
+ * reference and revision against canonical host storage. Staging is private; only publish
80
+ * enters the host's native attachment/event pipeline. Mutations are never automatically retried.
81
+ */
82
+ export interface HostFileService {
83
+ readonly version: 1;
84
+ read(
85
+ request: HostFileReadRequest,
86
+ signal?: AbortSignal
87
+ ): Promise<HostFileChunk>;
88
+ stage(
89
+ request: HostFileStageRequest,
90
+ content: AsyncIterable<Uint8Array>,
91
+ signal?: AbortSignal
92
+ ): Promise<HostFileDescriptor>;
93
+ publish(
94
+ request: HostFilePublishRequest,
95
+ signal?: AbortSignal
96
+ ): Promise<HostFilePublication>;
97
+ }
98
+
99
+ const codes = [
100
+ 'incompatible',
101
+ 'forbidden',
102
+ 'conflict',
103
+ 'overflow',
104
+ 'cancelled',
105
+ 'timeout',
106
+ 'unavailable',
107
+ ] as const;
108
+ export type HostFileErrorCode = (typeof codes)[number];
109
+ export class HostFileServiceError extends Error {
110
+ readonly code: HostFileErrorCode;
111
+ constructor(code: HostFileErrorCode) {
112
+ const safe = codes.includes(code) ? code : 'incompatible';
113
+ super(`Host file service: ${safe}`);
114
+ this.name = 'HostFileServiceError';
115
+ this.code = safe;
116
+ }
117
+ }
118
+
119
+ /** @internal Never forward adapter error text or abort reasons over the service boundary. */
120
+ export function normalizeHostFileError(
121
+ error: unknown,
122
+ signal?: AbortSignal
123
+ ): HostFileServiceError {
124
+ try {
125
+ if (signal?.aborted === true) {
126
+ return new HostFileServiceError(
127
+ signal.reason instanceof HostFileServiceError &&
128
+ signal.reason.code === 'timeout'
129
+ ? 'timeout'
130
+ : 'cancelled'
131
+ );
132
+ }
133
+ if (error instanceof HostFileServiceError)
134
+ return new HostFileServiceError(error.code);
135
+ } catch {
136
+ /** Adapter errors may contain throwing accessors; never expose them. */
137
+ }
138
+ return new HostFileServiceError('unavailable');
139
+ }
140
+
141
+ /** @internal Snapshot only public metadata, dropping host-specific fields. */
142
+ export function checkedHostFile(value: HostFileDescriptor): HostFileDescriptor {
143
+ const parsed = hostFileDescriptorSchema.safeParse(value);
144
+ if (!parsed.success) throw new HostFileServiceError('incompatible');
145
+ return Object.freeze(parsed.data);
146
+ }
147
+
148
+ /** @internal Reject mismatched/stale ranges before bytes enter a graph. */
149
+ export function checkedHostFileChunk(
150
+ value: HostFileChunk,
151
+ input: HostFileReadRequest
152
+ ): HostFileChunk {
153
+ if (
154
+ value.reference !== input.reference ||
155
+ value.revision !== input.revision ||
156
+ value.offset !== input.offset ||
157
+ !(value.data instanceof Uint8Array) ||
158
+ value.data.byteLength !== input.length
159
+ )
160
+ throw new HostFileServiceError('incompatible');
161
+ return {
162
+ reference: input.reference,
163
+ revision: input.revision,
164
+ offset: input.offset,
165
+ data: Uint8Array.from(value.data),
166
+ };
167
+ }
168
+
169
+ /** @internal Negotiation validates limits before constructing any graph adapter. */
170
+ export function checkedHostFileService(
171
+ value: HostFileServiceDescriptor
172
+ ): HostFileServiceDescriptor {
173
+ const parsed = hostFileServiceDescriptorSchema.safeParse(value);
174
+ if (
175
+ !parsed.success ||
176
+ parsed.data.maxChunkBytes > parsed.data.maxFileBytes ||
177
+ parsed.data.maxChunkBytes > Number.MAX_SAFE_INTEGER / 2 ||
178
+ new Set(parsed.data.operations).size !== parsed.data.operations.length
179
+ )
180
+ throw new HostFileServiceError('incompatible');
181
+ return Object.freeze({
182
+ ...parsed.data,
183
+ operations: Object.freeze([...parsed.data.operations]),
184
+ });
185
+ }
@@ -229,3 +229,27 @@ export type {
229
229
 
230
230
  export { createHostModelService, HostModelAdmission } from './modelService';
231
231
  export type { HostModelLimits } from './modelService';
232
+
233
+ export { createHostFileService, HostFileAdmission } from './fileService';
234
+ export type { HostFileStore } from './fileService';
235
+ export { createHostFileBindings } from './fileBindings';
236
+ export type { HostFileBindings } from './fileBindings';
237
+ export {
238
+ HostFileServiceError,
239
+ hostFileDescriptorSchema,
240
+ hostFileServiceDescriptorSchema,
241
+ hostFileReadRequestSchema,
242
+ hostFileStageRequestSchema,
243
+ hostFilePublishRequestSchema,
244
+ } from './files';
245
+ export type {
246
+ HostFileDescriptor,
247
+ HostFileServiceDescriptor,
248
+ HostFileService,
249
+ HostFileReadRequest,
250
+ HostFileStageRequest,
251
+ HostFilePublishRequest,
252
+ HostFileChunk,
253
+ HostFilePublication,
254
+ HostFileErrorCode,
255
+ } from './files';
@@ -152,21 +152,28 @@ export function restoreGeminiReplayParts(
152
152
  )
153
153
  return undefined;
154
154
  let text = '';
155
- let contentReasoning = '';
155
+ let contentReasoning: string | undefined;
156
156
  if (typeof message.content === 'string') text = message.content;
157
157
  else
158
158
  for (const block of message.content) {
159
159
  if (block.type === 'text' && typeof block.text === 'string')
160
160
  text += block.text;
161
161
  else if (block.type === 'thinking' && typeof block.thinking === 'string')
162
- contentReasoning += block.thinking;
162
+ contentReasoning = (contentReasoning ?? '') + block.thinking;
163
+ else if (
164
+ block.type === 'reasoning' &&
165
+ typeof block.reasoning === 'string'
166
+ )
167
+ contentReasoning = (contentReasoning ?? '') + block.reasoning;
163
168
  else if (!('functionCall' in block)) return undefined;
164
169
  }
165
- let reasoning = contentReasoning;
170
+ let reasoning = contentReasoning ?? '';
166
171
  if (typeof message.additional_kwargs.reasoning_content === 'string')
167
172
  reasoning = message.additional_kwargs.reasoning_content;
168
173
  if (typeof message.additional_kwargs.reasoning === 'string')
169
174
  reasoning = message.additional_kwargs.reasoning;
175
+ if (contentReasoning != null && contentReasoning !== reasoning)
176
+ return undefined;
170
177
  const calls = new Map(
171
178
  (message.tool_calls ?? []).map((call) => [call.id, call])
172
179
  );
@@ -32,8 +32,8 @@ import {
32
32
  runPlainExecution,
33
33
  formatCompletedResponse,
34
34
  } from './ProgrammaticToolCalling';
35
- import { logCodeApiDiagnostic } from '@/tools/diagnostics';
36
35
  import { resolveAttachedWorkspaceInstanceId } from '@/tools/workspaceIdentity';
36
+ import { logCodeApiDiagnostic } from '@/tools/diagnostics';
37
37
  import { INTENT_PROPERTY } from '@/tools/intentArg';
38
38
  import { Constants } from '@/common';
39
39
 
@@ -155,7 +155,9 @@ ${EXAMPLES}
155
155
  ${CORE_RULES}`;
156
156
 
157
157
  const TOOL_MANIFEST_DESCRIPTION =
158
- 'Exact registered tool names used by the code. Required when direct-only tools are configured; ' +
158
+ 'Registered tool names or their normalized sandbox function names used by the code. ' +
159
+ 'Use sandbox names in code, but registered names in tool_manifest when sandbox names collide. ' +
160
+ 'Required when direct-only tools are configured; ' +
159
161
  'validated before execution starts. Pass [] when the code calls no tools at all.';
160
162
 
161
163
  // ============================================================================
@@ -433,6 +435,7 @@ export function createBashProgrammaticToolCallingTool(
433
435
  allowedToolDefs: toolDefs,
434
436
  disallowedToolDefs,
435
437
  programmaticToolName,
438
+ normalizeIdentifier: normalizeToBashIdentifier,
436
439
  });
437
440
 
438
441
  /* These guard the replay path only. A call that selected no tools never
@@ -79,6 +79,7 @@ export function selectProgrammaticTools(args: {
79
79
  allowedToolDefs?: t.LCTool[];
80
80
  disallowedToolDefs?: t.LCTool[];
81
81
  programmaticToolName: string;
82
+ normalizeIdentifier?: (name: string) => string;
82
83
  }): t.LCTool[] {
83
84
  const allowedToolDefs = args.allowedToolDefs ?? [];
84
85
  const disallowedToolDefs = args.disallowedToolDefs ?? [];
@@ -111,6 +112,42 @@ export function selectProgrammaticTools(args: {
111
112
  const unknownNames = new Set(
112
113
  requestedToolNames.filter((name) => !allowedByName.has(name))
113
114
  );
115
+ if (unknownNames.size > 0 && args.normalizeIdentifier != null) {
116
+ const candidatesByIdentifier = new Map<string, t.LCTool[]>();
117
+ for (const toolDef of allowedToolDefs) {
118
+ const identifier = args.normalizeIdentifier(toolDef.name);
119
+ if (!unknownNames.has(identifier)) {
120
+ continue;
121
+ }
122
+ const candidates = candidatesByIdentifier.get(identifier) ?? [];
123
+ candidates.push(toolDef);
124
+ candidatesByIdentifier.set(identifier, candidates);
125
+ }
126
+
127
+ const disallowedAliases = new Set<string>();
128
+ for (const toolDef of disallowedToolDefs) {
129
+ const identifier = args.normalizeIdentifier(toolDef.name);
130
+ if (unknownNames.has(identifier)) {
131
+ disallowedAliases.add(toolDef.name);
132
+ }
133
+ }
134
+ assertDisallowedToolUsage(disallowedAliases, args.programmaticToolName);
135
+
136
+ for (const name of unknownNames) {
137
+ const candidates = candidatesByIdentifier.get(name);
138
+ if (candidates == null) {
139
+ continue;
140
+ }
141
+ assertUnambiguousIdentifiers(
142
+ candidates,
143
+ args.normalizeIdentifier,
144
+ args.programmaticToolName
145
+ );
146
+ allowedByName.set(name, candidates[0]);
147
+ unknownNames.delete(name);
148
+ }
149
+ }
150
+
114
151
  if (unknownNames.size > 0) {
115
152
  throw new Error(
116
153
  `Tool${unknownNames.size === 1 ? '' : 's'} ${[...unknownNames]
@@ -122,7 +159,9 @@ export function selectProgrammaticTools(args: {
122
159
  );
123
160
  }
124
161
 
125
- return [...new Set(requestedToolNames)].map(
126
- (name) => allowedByName.get(name) as t.LCTool
127
- );
162
+ return [
163
+ ...new Set(
164
+ requestedToolNames.map((name) => allowedByName.get(name) as t.LCTool)
165
+ ),
166
+ ];
128
167
  }
@@ -112,7 +112,9 @@ ${EXAMPLES}
112
112
  ${CORE_RULES}`;
113
113
 
114
114
  const TOOL_MANIFEST_DESCRIPTION =
115
- 'Exact registered tool names used by the code. Required when direct-only tools are configured; ' +
115
+ 'Registered tool names or their normalized sandbox function names used by the code. ' +
116
+ 'Use sandbox names in code, but registered names in tool_manifest when sandbox names collide. ' +
117
+ 'Required when direct-only tools are configured; ' +
116
118
  'validated before execution starts. Pass [] when the code calls no tools at all.';
117
119
 
118
120
  export function createProgrammaticToolCallingSchema(
@@ -1127,6 +1129,7 @@ export function createProgrammaticToolCallingTool(
1127
1129
  allowedToolDefs: toolDefs,
1128
1130
  disallowedToolDefs,
1129
1131
  programmaticToolName,
1132
+ normalizeIdentifier: normalizeToPythonIdentifier,
1130
1133
  });
1131
1134
 
1132
1135
  /* These guard the replay path only. A call that selected no tools never
@@ -600,6 +600,10 @@ async function runLocalProgrammaticTool(args: {
600
600
  allowedToolDefs: toolDefs,
601
601
  disallowedToolDefs,
602
602
  programmaticToolName: runnerName,
603
+ normalizeIdentifier:
604
+ args.runtime === 'bash'
605
+ ? normalizeToBashIdentifier
606
+ : normalizeToPythonIdentifier,
603
607
  });
604
608
 
605
609
  /* The local program builder supports zero stubs, so a call that selected no