@librechat/agents 4.2.8 → 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 (101) 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/harness/model.cjs +6 -3
  14. package/dist/cjs/harness/model.cjs.map +1 -1
  15. package/dist/cjs/llm/google/utils/signatures.cjs +5 -3
  16. package/dist/cjs/llm/google/utils/signatures.cjs.map +1 -1
  17. package/dist/cjs/llm/invocation.cjs +19 -0
  18. package/dist/cjs/llm/invocation.cjs.map +1 -0
  19. package/dist/cjs/llm/providerTextBoundary.cjs +6 -5
  20. package/dist/cjs/llm/providerTextBoundary.cjs.map +1 -1
  21. package/dist/cjs/main.cjs +13 -0
  22. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs +3 -2
  23. package/dist/cjs/tools/BashProgrammaticToolCalling.cjs.map +1 -1
  24. package/dist/cjs/tools/ProgrammaticCallerPolicy.cjs +24 -1
  25. package/dist/cjs/tools/ProgrammaticCallerPolicy.cjs.map +1 -1
  26. package/dist/cjs/tools/ProgrammaticToolCalling.cjs +3 -2
  27. package/dist/cjs/tools/ProgrammaticToolCalling.cjs.map +1 -1
  28. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs +2 -1
  29. package/dist/cjs/tools/local/LocalProgrammaticToolCalling.cjs.map +1 -1
  30. package/dist/cjs/tools/subagent/SubagentExecutor.cjs +15 -3
  31. package/dist/cjs/tools/subagent/SubagentExecutor.cjs.map +1 -1
  32. package/dist/cjs/tools/subagent/childGraphConfig.cjs +13 -1
  33. package/dist/cjs/tools/subagent/childGraphConfig.cjs.map +1 -1
  34. package/dist/cjs/tools/subagent/hostArgs.cjs +2 -0
  35. package/dist/cjs/tools/subagent/hostArgs.cjs.map +1 -1
  36. package/dist/esm/agents/AgentContext.mjs +32 -2
  37. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  38. package/dist/esm/harness/fileBindings.mjs +93 -0
  39. package/dist/esm/harness/fileBindings.mjs.map +1 -0
  40. package/dist/esm/harness/fileService.mjs +140 -0
  41. package/dist/esm/harness/fileService.mjs.map +1 -0
  42. package/dist/esm/harness/fileStream.mjs +76 -0
  43. package/dist/esm/harness/fileStream.mjs.map +1 -0
  44. package/dist/esm/harness/files.mjs +97 -0
  45. package/dist/esm/harness/files.mjs.map +1 -0
  46. package/dist/esm/harness/index.mjs +3 -0
  47. package/dist/esm/harness/index.mjs.map +1 -1
  48. package/dist/esm/harness/model.mjs +6 -3
  49. package/dist/esm/harness/model.mjs.map +1 -1
  50. package/dist/esm/llm/google/utils/signatures.mjs +5 -3
  51. package/dist/esm/llm/google/utils/signatures.mjs.map +1 -1
  52. package/dist/esm/llm/invocation.mjs +18 -0
  53. package/dist/esm/llm/invocation.mjs.map +1 -0
  54. package/dist/esm/llm/providerTextBoundary.mjs +6 -5
  55. package/dist/esm/llm/providerTextBoundary.mjs.map +1 -1
  56. package/dist/esm/main.mjs +5 -2
  57. package/dist/esm/tools/BashProgrammaticToolCalling.mjs +3 -2
  58. package/dist/esm/tools/BashProgrammaticToolCalling.mjs.map +1 -1
  59. package/dist/esm/tools/ProgrammaticCallerPolicy.mjs +24 -1
  60. package/dist/esm/tools/ProgrammaticCallerPolicy.mjs.map +1 -1
  61. package/dist/esm/tools/ProgrammaticToolCalling.mjs +3 -2
  62. package/dist/esm/tools/ProgrammaticToolCalling.mjs.map +1 -1
  63. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs +2 -1
  64. package/dist/esm/tools/local/LocalProgrammaticToolCalling.mjs.map +1 -1
  65. package/dist/esm/tools/subagent/SubagentExecutor.mjs +15 -3
  66. package/dist/esm/tools/subagent/SubagentExecutor.mjs.map +1 -1
  67. package/dist/esm/tools/subagent/childGraphConfig.mjs +13 -1
  68. package/dist/esm/tools/subagent/childGraphConfig.mjs.map +1 -1
  69. package/dist/esm/tools/subagent/hostArgs.mjs +2 -1
  70. package/dist/esm/tools/subagent/hostArgs.mjs.map +1 -1
  71. package/dist/types/harness/fileBindings.d.ts +13 -0
  72. package/dist/types/harness/fileService.d.ts +37 -0
  73. package/dist/types/harness/fileStream.d.ts +7 -0
  74. package/dist/types/harness/files.d.ts +108 -0
  75. package/dist/types/harness/index.d.ts +7 -0
  76. package/dist/types/harness/model.d.ts +5 -3
  77. package/dist/types/llm/invocation.d.ts +9 -0
  78. package/dist/types/tools/ProgrammaticCallerPolicy.d.ts +1 -0
  79. package/dist/types/tools/subagent/hostArgs.d.ts +6 -0
  80. package/dist/types/tools/subagent/index.d.ts +1 -1
  81. package/dist/types/types/graph.d.ts +6 -3
  82. package/package.json +1 -1
  83. package/src/agents/AgentContext.ts +68 -2
  84. package/src/harness/fileBindings.ts +156 -0
  85. package/src/harness/fileService.ts +217 -0
  86. package/src/harness/fileStream.ts +99 -0
  87. package/src/harness/files.ts +185 -0
  88. package/src/harness/index.ts +25 -0
  89. package/src/harness/model.ts +20 -5
  90. package/src/llm/google/utils/signatures.ts +10 -3
  91. package/src/llm/invocation.ts +29 -0
  92. package/src/llm/providerTextBoundary.ts +12 -3
  93. package/src/tools/BashProgrammaticToolCalling.ts +5 -2
  94. package/src/tools/ProgrammaticCallerPolicy.ts +42 -3
  95. package/src/tools/ProgrammaticToolCalling.ts +4 -1
  96. package/src/tools/local/LocalProgrammaticToolCalling.ts +4 -0
  97. package/src/tools/subagent/SubagentExecutor.ts +98 -32
  98. package/src/tools/subagent/childGraphConfig.ts +33 -1
  99. package/src/tools/subagent/hostArgs.ts +7 -0
  100. package/src/tools/subagent/index.ts +1 -0
  101. package/src/types/graph.ts +6 -3
@@ -29,4 +29,5 @@ export declare function selectProgrammaticTools(args: {
29
29
  allowedToolDefs?: t.LCTool[];
30
30
  disallowedToolDefs?: t.LCTool[];
31
31
  programmaticToolName: string;
32
+ normalizeIdentifier?: (name: string) => string;
32
33
  }): t.LCTool[];
@@ -1,5 +1,11 @@
1
1
  import type { SubagentHostArgs, SubagentHostArgSpec, SubagentHostArgSpecs } from '@/types/graph';
2
2
  import type { JsonSchemaType } from '@/types/tools';
3
+ /**
4
+ * Feature probe: `self` subagent configs may declare `hostArgs` together with
5
+ * `resolveAgentInputs` and a `configId`. Calls that pass host arguments are
6
+ * resolved through the resolver; calls that pass none reuse the self inputs.
7
+ */
8
+ export declare const SELF_SUBAGENT_HOST_ARGS_SUPPORTED = true;
3
9
  /** Bounds on host-declared subagent call arguments and their values. */
4
10
  export declare const SUBAGENT_HOST_ARG_LIMITS: Readonly<{
5
11
  argsPerSubagent: 8;
@@ -3,5 +3,5 @@ export type { SubagentExecuteParams, SubagentExecuteResult, SubagentExecutorOpti
3
3
  export { InMemorySubagentTaskStore } from './InMemorySubagentTaskStore';
4
4
  export type { InMemorySubagentTaskStoreOptions } from './InMemorySubagentTaskStore';
5
5
  export { SubagentResolutionError, SubagentHostArgumentError, getSubagentResolutionFailureMessage, getSubagentHostArgumentFailureMessage, } from './diagnostics';
6
- export { SUBAGENT_HOST_ARG_LIMITS, buildSubagentHostArgProperties, resolveSubagentHostArgs, } from './hostArgs';
6
+ export { SUBAGENT_HOST_ARG_LIMITS, SELF_SUBAGENT_HOST_ARGS_SUPPORTED, buildSubagentHostArgProperties, resolveSubagentHostArgs, } from './hostArgs';
7
7
  export type { SubagentHostArgumentFailure, SubagentHostArgumentRejection, SubagentResolutionPhase, SubagentResolutionCause, SubagentResolutionContext, SubagentResolutionDiagnostic, SubagentResolutionFailureHandler, } from './diagnostics';
@@ -497,8 +497,10 @@ export interface SubagentConfig extends SubagentConfigBase {
497
497
  agentInputs?: AgentInputs;
498
498
  /**
499
499
  * Resolve the full child config only after this descriptor is selected.
500
- * Eager `agentInputs` take precedence when also supplied. `self` and a
501
- * resolver are mutually exclusive and normalization rejects that pairing.
500
+ * Eager `agentInputs` take precedence when also supplied. A `self` config
501
+ * may set a resolver only together with `hostArgs` and a `configId`; it then
502
+ * runs only for calls that pass host arguments, and every other call reuses
503
+ * the self inputs. Normalization rejects any other `self` + resolver pairing.
502
504
  *
503
505
  * Resolvers should rebuild inputs from the stable execution context instead
504
506
  * of retaining request-owned state. The SDK keeps resolved inputs in memory
@@ -512,7 +514,8 @@ export interface SubagentConfig extends SubagentConfigBase {
512
514
  /**
513
515
  * Optional per-call arguments the parent model may pass for this subagent,
514
516
  * delivered to `resolveAgentInputs` as `context.hostArgs`. Only lazy
515
- * configs accept them. Declaring none leaves the tool schema unchanged.
517
+ * configs and `self` configs with a resolver accept them. Declaring none
518
+ * leaves the tool schema unchanged.
516
519
  */
517
520
  hostArgs?: SubagentHostArgSpecs;
518
521
  /** When true, reuse the parent's AgentInputs (context isolation without separate config). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@librechat/agents",
3
- "version": "4.2.8",
3
+ "version": "4.2.10",
4
4
  "reova": {
5
5
  "enabled": true,
6
6
  "endpoint": "https://telemetry.reo.dev/data"
@@ -57,7 +57,9 @@ import {
57
57
  Providers,
58
58
  } from '@/common';
59
59
  import { isTokenCounterCacheCompatible } from '@/llm/tokenCounterCacheCompatibility';
60
+ import { normalizeToBashIdentifier } from '@/tools/BashProgrammaticToolCalling';
60
61
  import { snapshotCompactionSemanticIndex } from '@/summarization/semanticIndex';
62
+ import { normalizeToPythonIdentifier } from '@/tools/ProgrammaticToolCalling';
61
63
  import { createExactTokenCountCache } from '@/llm/contextPressureMeter';
62
64
  import { markProviderTextInput } from '@/protection/providerTextInput';
63
65
  import { buildSummaryCarrierText } from '@/summarization/shared';
@@ -81,6 +83,7 @@ type PromptCacheProvider = Providers.ANTHROPIC | Providers.OPENROUTER;
81
83
  type ProgrammaticToolInstructionTarget = {
82
84
  name: string;
83
85
  codeGuidance: string;
86
+ runtimes: Array<'Bash' | 'Python'>;
84
87
  executesDirectly: boolean;
85
88
  };
86
89
 
@@ -680,12 +683,73 @@ export class AgentContext {
680
683
  .map((name) => `\`${name}\``)
681
684
  .join(
682
685
  ', '
683
- )}. Every ${programmaticRunnerNames} call must include a \`tool_manifest\` containing the exact registered names used by its code; the manifest is validated before execution starts.`
686
+ )}. Every ${programmaticRunnerNames} call must include a \`tool_manifest\` containing the registered names or sandbox names used by its code; the manifest is validated before execution starts.`
684
687
  : '';
688
+ const runtimes = new Set(
689
+ programmaticTools.flatMap((tool) => tool.runtimes)
690
+ );
691
+ const identifierOwners = new Map<string, string | null>();
692
+ for (const runtime of runtimes) {
693
+ const normalizeIdentifier =
694
+ runtime === 'Bash'
695
+ ? normalizeToBashIdentifier
696
+ : normalizeToPythonIdentifier;
697
+ for (const toolDefs of [
698
+ capabilities.codeExecutionTools,
699
+ capabilities.directOnlyTools,
700
+ ]) {
701
+ for (const toolDef of toolDefs) {
702
+ const key = `${runtime}:${normalizeIdentifier(toolDef.name)}`;
703
+ const owner = identifierOwners.get(key);
704
+ identifierOwners.set(
705
+ key,
706
+ owner === undefined || owner === toolDef.name ? toolDef.name : null
707
+ );
708
+ }
709
+ }
710
+ }
711
+ const sandboxNames: string[] = [];
712
+ const collidingNames: string[] = [];
713
+ for (const toolDef of capabilities.codeExecutionTools) {
714
+ const names: string[] = [];
715
+ const collisions: string[] = [];
716
+ for (const runtime of runtimes) {
717
+ const identifier =
718
+ runtime === 'Bash'
719
+ ? normalizeToBashIdentifier(toolDef.name)
720
+ : normalizeToPythonIdentifier(toolDef.name);
721
+ if (identifier === toolDef.name) {
722
+ continue;
723
+ }
724
+ if (identifierOwners.get(`${runtime}:${identifier}`) !== toolDef.name) {
725
+ collisions.push(`${runtime} code \`${identifier}\``);
726
+ } else {
727
+ names.push(`${runtime} \`${identifier}\``);
728
+ }
729
+ }
730
+ if (names.length > 0) {
731
+ sandboxNames.push(`- \`${toolDef.name}\`: ${names.join('; ')}`);
732
+ }
733
+ if (collisions.length > 0) {
734
+ collidingNames.push(`- \`${toolDef.name}\`: ${collisions.join('; ')}`);
735
+ }
736
+ }
737
+ const sandboxNameGuidance =
738
+ sandboxNames.length === 0
739
+ ? ''
740
+ : '\n\nUse sandbox names in both code and `tool_manifest` for the tools below; registered names are also accepted in `tool_manifest`:\n' +
741
+ sandboxNames.join('\n');
742
+ const collidingNameGuidance =
743
+ collidingNames.length === 0
744
+ ? ''
745
+ : '\n\nFor colliding sandbox names, use registered names in `tool_manifest` and sandbox names in code. Select only one tool per sandbox name:\n' +
746
+ collidingNames.join('\n');
685
747
  const boundary =
686
748
  '\n\n' +
687
749
  `Only these tools may be invoked inside ${programmaticRunnerNames}: ${quotedProgrammaticNames}.` +
688
- directOnlyBoundary;
750
+ directOnlyBoundary +
751
+ sandboxNameGuidance +
752
+ collidingNameGuidance;
689
753
 
690
754
  if (programmaticOnlyTools.length === 0) {
691
755
  return boundary;
@@ -730,6 +794,7 @@ export class AgentContext {
730
794
  targets.push({
731
795
  name: Constants.BASH_PROGRAMMATIC_TOOL_CALLING,
732
796
  codeGuidance: 'Bash code',
797
+ runtimes: ['Bash'],
733
798
  executesDirectly: this.isProgrammaticRunnerDirectlyBound(
734
799
  Constants.BASH_PROGRAMMATIC_TOOL_CALLING
735
800
  ),
@@ -751,6 +816,7 @@ export class AgentContext {
751
816
  codeGuidance: localDefault
752
817
  ? 'Bash code by default, or set `lang: "py"` to use Python code'
753
818
  : 'Python code',
819
+ runtimes: localDefault ? ['Bash', 'Python'] : ['Python'],
754
820
  executesDirectly: this.isProgrammaticRunnerDirectlyBound(
755
821
  Constants.PROGRAMMATIC_TOOL_CALLING
756
822
  ),
@@ -0,0 +1,156 @@
1
+ import type {
2
+ HostFileDescriptor,
3
+ HostFileStageRequest,
4
+ HostFileReadRequest,
5
+ HostFilePublication,
6
+ HostFileServiceDescriptor,
7
+ HostFileService,
8
+ } from './files';
9
+ import type { ExecutionIdentity } from './identity';
10
+ import {
11
+ HostFileServiceError,
12
+ normalizeHostFileError,
13
+ checkedHostFile,
14
+ checkedHostFileChunk,
15
+ checkedHostFileService,
16
+ hostFileStageRequestSchema,
17
+ hostFilePublishRequestSchema,
18
+ } from './files';
19
+ import { snapshotExecutionIdentity } from './identity';
20
+ import { createFileUpload } from './fileStream';
21
+
22
+ export interface HostFileBindings {
23
+ read(
24
+ file: HostFileDescriptor,
25
+ signal?: AbortSignal
26
+ ): AsyncIterable<Uint8Array>;
27
+ stage(
28
+ artifact: Omit<HostFileStageRequest, 'version' | 'identity'>,
29
+ content: AsyncIterable<Uint8Array>,
30
+ signal?: AbortSignal
31
+ ): Promise<HostFileDescriptor>;
32
+ publish(
33
+ file: HostFileDescriptor,
34
+ operationId: string,
35
+ signal?: AbortSignal
36
+ ): Promise<HostFilePublication>;
37
+ }
38
+
39
+ /** Pull-based graph adapter; at most one range or upload chunk is requested at a time. */
40
+ export function createHostFileBindings(options: {
41
+ identity: Readonly<ExecutionIdentity>;
42
+ descriptor: HostFileServiceDescriptor;
43
+ service: HostFileService;
44
+ }): HostFileBindings {
45
+ const identity = snapshotExecutionIdentity(options.identity);
46
+ const descriptor = checkedHostFileService(options.descriptor);
47
+ const service = options.service;
48
+ if (Number(service.version) !== 1)
49
+ throw new HostFileServiceError('incompatible');
50
+ function allow(
51
+ operation: HostFileServiceDescriptor['operations'][number],
52
+ signal?: AbortSignal
53
+ ): void {
54
+ if (!descriptor.operations.includes(operation))
55
+ throw new HostFileServiceError('forbidden');
56
+ if (signal?.aborted === true) throw new HostFileServiceError('cancelled');
57
+ }
58
+ return {
59
+ read: async function* (source, signal): AsyncGenerator<Uint8Array> {
60
+ try {
61
+ allow('read', signal);
62
+ const file = checkedHostFile(source);
63
+ if (file.bytes > descriptor.maxFileBytes)
64
+ throw new HostFileServiceError('overflow');
65
+ for (let offset = 0; offset < file.bytes; ) {
66
+ allow('read', signal);
67
+ const input: HostFileReadRequest = {
68
+ version: 1,
69
+ identity,
70
+ reference: file.reference,
71
+ revision: file.revision,
72
+ offset,
73
+ length: Math.min(descriptor.maxChunkBytes, file.bytes - offset),
74
+ };
75
+ const chunk = checkedHostFileChunk(
76
+ await service.read(input, signal),
77
+ input
78
+ );
79
+ allow('read', signal);
80
+ offset += chunk.data.byteLength;
81
+ yield chunk.data;
82
+ }
83
+ } catch (error) {
84
+ throw normalizeHostFileError(error, signal);
85
+ }
86
+ },
87
+ stage: async (artifact, content, signal): Promise<HostFileDescriptor> => {
88
+ try {
89
+ allow('stage', signal);
90
+ const parsed = hostFileStageRequestSchema.safeParse({
91
+ ...artifact,
92
+ version: 1,
93
+ identity,
94
+ });
95
+ if (!parsed.success) throw new HostFileServiceError('incompatible');
96
+ if (parsed.data.bytes > descriptor.maxFileBytes)
97
+ throw new HostFileServiceError('overflow');
98
+ const upload = createFileUpload(
99
+ content,
100
+ parsed.data,
101
+ descriptor.maxChunkBytes,
102
+ signal
103
+ );
104
+ try {
105
+ const file = checkedHostFile(
106
+ await service.stage(parsed.data, upload.content, signal)
107
+ );
108
+ upload.finish();
109
+ allow('stage', signal);
110
+ if (
111
+ file.sha256 === undefined ||
112
+ file.bytes !== parsed.data.bytes ||
113
+ (parsed.data.sha256 !== undefined &&
114
+ file.sha256 !== parsed.data.sha256)
115
+ )
116
+ throw new HostFileServiceError('incompatible');
117
+ return file;
118
+ } finally {
119
+ /** The host retains admission until source cleanup settles. Do not delay
120
+ * a cancellation/timeout response on an uncooperative producer here. */
121
+ void upload.close().catch(() => undefined);
122
+ }
123
+ } catch (error) {
124
+ throw normalizeHostFileError(error, signal);
125
+ }
126
+ },
127
+ publish: async (
128
+ source,
129
+ operationId,
130
+ signal
131
+ ): Promise<HostFilePublication> => {
132
+ try {
133
+ allow('publish', signal);
134
+ const file = checkedHostFile(source);
135
+ const parsed = hostFilePublishRequestSchema.safeParse({
136
+ version: 1,
137
+ identity,
138
+ operationId,
139
+ reference: file.reference,
140
+ revision: file.revision,
141
+ });
142
+ if (!parsed.success) throw new HostFileServiceError('incompatible');
143
+ const result = await service.publish(parsed.data, signal);
144
+ allow('publish', signal);
145
+ if (result.operationId !== operationId)
146
+ throw new HostFileServiceError('incompatible');
147
+ const published = checkedHostFile(result.file);
148
+ if (published.bytes > descriptor.maxFileBytes)
149
+ throw new HostFileServiceError('overflow');
150
+ return { operationId, file: published };
151
+ } catch (error) {
152
+ throw normalizeHostFileError(error, signal);
153
+ }
154
+ },
155
+ };
156
+ }
@@ -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
+ }