@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.
- package/dist/cjs/runtime/admission.cjs +135 -0
- package/dist/cjs/runtime/admission.cjs.map +1 -0
- package/dist/cjs/runtime/checkpoint.cjs +40 -0
- package/dist/cjs/runtime/checkpoint.cjs.map +1 -0
- package/dist/cjs/runtime/client.cjs +435 -0
- package/dist/cjs/runtime/client.cjs.map +1 -0
- package/dist/cjs/runtime/files.cjs +301 -0
- package/dist/cjs/runtime/files.cjs.map +1 -0
- package/dist/cjs/runtime/hostTools.cjs +165 -0
- package/dist/cjs/runtime/hostTools.cjs.map +1 -0
- package/dist/cjs/runtime/index.cjs +11 -0
- package/dist/cjs/runtime/model.cjs +303 -0
- package/dist/cjs/runtime/model.cjs.map +1 -0
- package/dist/cjs/runtime/peer.cjs +209 -0
- package/dist/cjs/runtime/peer.cjs.map +1 -0
- package/dist/cjs/runtime/policy.cjs +77 -0
- package/dist/cjs/runtime/policy.cjs.map +1 -0
- package/dist/cjs/runtime/recovery/client.cjs +172 -0
- package/dist/cjs/runtime/recovery/client.cjs.map +1 -0
- package/dist/cjs/runtime/recovery/log.cjs +47 -0
- package/dist/cjs/runtime/recovery/log.cjs.map +1 -0
- package/dist/cjs/runtime/recovery/redis.cjs +239 -0
- package/dist/cjs/runtime/recovery/redis.cjs.map +1 -0
- package/dist/cjs/runtime/recovery/server.cjs +190 -0
- package/dist/cjs/runtime/recovery/server.cjs.map +1 -0
- package/dist/cjs/runtime/recovery/socket.cjs +298 -0
- package/dist/cjs/runtime/recovery/socket.cjs.map +1 -0
- package/dist/cjs/runtime/resume.cjs +115 -0
- package/dist/cjs/runtime/resume.cjs.map +1 -0
- package/dist/cjs/runtime/sealed.cjs +107 -0
- package/dist/cjs/runtime/sealed.cjs.map +1 -0
- package/dist/cjs/runtime/server.cjs +415 -0
- package/dist/cjs/runtime/server.cjs.map +1 -0
- package/dist/cjs/runtime/snapshot.cjs +61 -0
- package/dist/cjs/runtime/snapshot.cjs.map +1 -0
- package/dist/cjs/runtime/types.cjs +20 -0
- package/dist/cjs/runtime/types.cjs.map +1 -0
- package/dist/cjs/runtime/wire.cjs +84 -0
- package/dist/cjs/runtime/wire.cjs.map +1 -0
- package/dist/esm/runtime/admission.mjs +133 -0
- package/dist/esm/runtime/admission.mjs.map +1 -0
- package/dist/esm/runtime/checkpoint.mjs +39 -0
- package/dist/esm/runtime/checkpoint.mjs.map +1 -0
- package/dist/esm/runtime/client.mjs +432 -0
- package/dist/esm/runtime/client.mjs.map +1 -0
- package/dist/esm/runtime/files.mjs +299 -0
- package/dist/esm/runtime/files.mjs.map +1 -0
- package/dist/esm/runtime/hostTools.mjs +164 -0
- package/dist/esm/runtime/hostTools.mjs.map +1 -0
- package/dist/esm/runtime/index.mjs +5 -0
- package/dist/esm/runtime/model.mjs +301 -0
- package/dist/esm/runtime/model.mjs.map +1 -0
- package/dist/esm/runtime/peer.mjs +209 -0
- package/dist/esm/runtime/peer.mjs.map +1 -0
- package/dist/esm/runtime/policy.mjs +75 -0
- package/dist/esm/runtime/policy.mjs.map +1 -0
- package/dist/esm/runtime/recovery/client.mjs +172 -0
- package/dist/esm/runtime/recovery/client.mjs.map +1 -0
- package/dist/esm/runtime/recovery/log.mjs +46 -0
- package/dist/esm/runtime/recovery/log.mjs.map +1 -0
- package/dist/esm/runtime/recovery/redis.mjs +239 -0
- package/dist/esm/runtime/recovery/redis.mjs.map +1 -0
- package/dist/esm/runtime/recovery/server.mjs +189 -0
- package/dist/esm/runtime/recovery/server.mjs.map +1 -0
- package/dist/esm/runtime/recovery/socket.mjs +297 -0
- package/dist/esm/runtime/recovery/socket.mjs.map +1 -0
- package/dist/esm/runtime/resume.mjs +111 -0
- package/dist/esm/runtime/resume.mjs.map +1 -0
- package/dist/esm/runtime/sealed.mjs +106 -0
- package/dist/esm/runtime/sealed.mjs.map +1 -0
- package/dist/esm/runtime/server.mjs +413 -0
- package/dist/esm/runtime/server.mjs.map +1 -0
- package/dist/esm/runtime/snapshot.mjs +60 -0
- package/dist/esm/runtime/snapshot.mjs.map +1 -0
- package/dist/esm/runtime/types.mjs +19 -0
- package/dist/esm/runtime/types.mjs.map +1 -0
- package/dist/esm/runtime/wire.mjs +80 -0
- package/dist/esm/runtime/wire.mjs.map +1 -0
- package/dist/types/agents/AgentContext.d.ts +4 -4
- package/dist/types/agents/projection.d.ts +1 -1
- package/dist/types/events.d.ts +2 -2
- package/dist/types/graphs/Graph.d.ts +13 -13
- package/dist/types/graphs/MultiAgentGraph.d.ts +2 -2
- package/dist/types/graphs/acceptedModelResponse.d.ts +1 -1
- package/dist/types/graphs/createGraph.d.ts +4 -4
- package/dist/types/graphs/graphFactory.d.ts +1 -1
- package/dist/types/graphs/handoff.d.ts +1 -1
- package/dist/types/harness/index.d.ts +2 -2
- package/dist/types/harness/model.d.ts +3 -3
- package/dist/types/harness/providerText.d.ts +2 -2
- package/dist/types/hitl/approvalReview.d.ts +1 -1
- package/dist/types/hitl/askUserQuestion.d.ts +1 -1
- package/dist/types/hitl/askUserQuestions.d.ts +1 -1
- package/dist/types/hitl/askUserQuestionsInterrupt.d.ts +1 -1
- package/dist/types/hooks/types.d.ts +2 -2
- package/dist/types/instrumentation.d.ts +1 -1
- package/dist/types/langfuse.d.ts +3 -3
- package/dist/types/langfuseConfig.d.ts +2 -2
- package/dist/types/langfuseRuntimeContext.d.ts +1 -1
- package/dist/types/langfuseRuntimeScope.d.ts +2 -2
- package/dist/types/langfuseSpanRegistry.d.ts +1 -1
- package/dist/types/langfuseToolOutputTracing.d.ts +3 -3
- package/dist/types/llm/anthropic/index.d.ts +1 -1
- package/dist/types/llm/bedrock/index.d.ts +1 -1
- package/dist/types/llm/bedrock/toolCache.d.ts +2 -2
- package/dist/types/llm/contextOverflowRecovery.d.ts +2 -2
- package/dist/types/llm/contextPressureMeter.d.ts +2 -2
- package/dist/types/llm/google/index.d.ts +1 -1
- package/dist/types/llm/init.d.ts +1 -1
- package/dist/types/llm/invoke.d.ts +9 -9
- package/dist/types/llm/mistral/index.d.ts +1 -1
- package/dist/types/llm/openai/index.d.ts +2 -2
- package/dist/types/llm/openrouter/index.d.ts +2 -2
- package/dist/types/llm/openrouter/toolCache.d.ts +2 -2
- package/dist/types/llm/prepareProviderRequest.d.ts +3 -3
- package/dist/types/llm/promptCacheTools.d.ts +1 -1
- package/dist/types/llm/providerRegistry.d.ts +1 -1
- package/dist/types/llm/providerTextBoundary.d.ts +2 -2
- package/dist/types/llm/providerTextControls.d.ts +1 -1
- package/dist/types/llm/providers.d.ts +2 -2
- package/dist/types/llm/request.d.ts +1 -1
- package/dist/types/llm/stream/chunkAdapters.d.ts +1 -1
- package/dist/types/llm/streamLimits.d.ts +1 -1
- package/dist/types/llm/truncation.d.ts +1 -1
- package/dist/types/llm/vertexai/index.d.ts +1 -1
- package/dist/types/messages/alternation.d.ts +1 -1
- package/dist/types/messages/anthropicToolCache.d.ts +2 -2
- package/dist/types/messages/assistantPhase.d.ts +3 -3
- package/dist/types/messages/budget.d.ts +1 -1
- package/dist/types/messages/cache.d.ts +1 -1
- package/dist/types/messages/contextPruning.d.ts +2 -2
- package/dist/types/messages/core.d.ts +1 -1
- package/dist/types/messages/fading.d.ts +1 -1
- package/dist/types/messages/format.d.ts +2 -2
- package/dist/types/messages/ids.d.ts +2 -2
- package/dist/types/messages/injected.d.ts +1 -1
- package/dist/types/messages/langchain.d.ts +1 -1
- package/dist/types/messages/prune.d.ts +4 -4
- package/dist/types/messages/recency.d.ts +1 -1
- package/dist/types/messages/toolResultTypes.d.ts +1 -1
- package/dist/types/openai/arguments.d.ts +1 -1
- package/dist/types/openai/index.d.ts +1 -1
- package/dist/types/openai/toolProjection.d.ts +1 -1
- package/dist/types/prompts/activityLabel.d.ts +2 -2
- package/dist/types/prompts/reasoningLabel.d.ts +1 -1
- package/dist/types/rerank/search.d.ts +1 -1
- package/dist/types/responses/index.d.ts +1 -1
- package/dist/types/run.d.ts +3 -3
- package/dist/types/runtime/admission.d.ts +30 -0
- package/dist/types/runtime/checkpoint.d.ts +14 -0
- package/dist/types/runtime/client.d.ts +12 -0
- package/dist/types/runtime/files.d.ts +75 -0
- package/dist/types/runtime/hostTools.d.ts +22 -0
- package/dist/types/runtime/identity.d.ts +2 -0
- package/dist/types/runtime/index.d.ts +12 -0
- package/dist/types/runtime/model.d.ts +42 -0
- package/dist/types/runtime/peer.d.ts +55 -0
- package/dist/types/runtime/policy.d.ts +43 -0
- package/dist/types/runtime/recovery/client.d.ts +12 -0
- package/dist/types/runtime/recovery/journal.d.ts +62 -0
- package/dist/types/runtime/recovery/log.d.ts +9 -0
- package/dist/types/runtime/recovery/redis.d.ts +17 -0
- package/dist/types/runtime/recovery/server.d.ts +37 -0
- package/dist/types/runtime/recovery/socket.d.ts +72 -0
- package/dist/types/runtime/resume.d.ts +66 -0
- package/dist/types/runtime/sealed.d.ts +19 -0
- package/dist/types/runtime/server.d.ts +21 -0
- package/dist/types/runtime/snapshot.d.ts +12 -0
- package/dist/types/runtime/types.d.ts +125 -0
- package/dist/types/runtime/wire.d.ts +3 -0
- package/dist/types/session/handlers.d.ts +1 -1
- package/dist/types/session/types.d.ts +1 -1
- package/dist/types/stream.d.ts +3 -3
- package/dist/types/summarization/index.d.ts +1 -1
- package/dist/types/summarization/input.d.ts +1 -1
- package/dist/types/summarization/node.d.ts +6 -6
- package/dist/types/summarization/retry.d.ts +2 -2
- package/dist/types/summarization/semanticIndex.d.ts +2 -2
- package/dist/types/summarization/toolBudget.d.ts +1 -1
- package/dist/types/summarization/usage.d.ts +1 -1
- package/dist/types/tools/ArtifactDelivery.d.ts +1 -1
- package/dist/types/tools/ArtifactTruncation.d.ts +1 -1
- package/dist/types/tools/BashExecutor.d.ts +2 -2
- package/dist/types/tools/BashProgrammaticToolCalling.d.ts +2 -2
- package/dist/types/tools/CallerCapabilities.d.ts +1 -1
- package/dist/types/tools/CodeExecutor.d.ts +4 -4
- package/dist/types/tools/CodeSessionFileSummary.d.ts +1 -1
- package/dist/types/tools/ProgrammaticCallerPolicy.d.ts +1 -1
- package/dist/types/tools/ProgrammaticToolCalling.d.ts +2 -2
- package/dist/types/tools/ReadFile.d.ts +1 -1
- package/dist/types/tools/SkillTool.d.ts +1 -1
- package/dist/types/tools/SubagentTool.d.ts +3 -3
- package/dist/types/tools/ToolNode.d.ts +5 -5
- package/dist/types/tools/ToolSearch.d.ts +2 -2
- package/dist/types/tools/cloudflare/CloudflareBridgeRuntime.d.ts +1 -1
- package/dist/types/tools/cloudflare/CloudflareProgrammaticToolCalling.d.ts +1 -1
- package/dist/types/tools/cloudflare/CloudflareSandboxExecutionEngine.d.ts +2 -2
- package/dist/types/tools/cloudflare/CloudflareSandboxTools.d.ts +1 -1
- package/dist/types/tools/diagnostics.d.ts +1 -1
- package/dist/types/tools/eagerEventExecution.d.ts +1 -1
- package/dist/types/tools/handlers.d.ts +3 -3
- package/dist/types/tools/intentArg.d.ts +1 -1
- package/dist/types/tools/local/CompileCheckTool.d.ts +2 -2
- package/dist/types/tools/local/FileCheckpointer.d.ts +1 -1
- package/dist/types/tools/local/LocalCodingTools.d.ts +2 -2
- package/dist/types/tools/local/LocalExecutionEngine.d.ts +1 -1
- package/dist/types/tools/local/LocalExecutionTools.d.ts +1 -1
- package/dist/types/tools/local/LocalProgrammaticToolCalling.d.ts +1 -1
- package/dist/types/tools/local/bashAst.d.ts +1 -1
- package/dist/types/tools/local/resolveLocalExecutionTools.d.ts +1 -1
- package/dist/types/tools/local/syntaxCheck.d.ts +1 -1
- package/dist/types/tools/ptcTimeout.d.ts +1 -1
- package/dist/types/tools/runStepResume.d.ts +1 -1
- package/dist/types/tools/schema.d.ts +1 -1
- package/dist/types/tools/search/anthropic.d.ts +1 -1
- package/dist/types/tools/skillCatalog.d.ts +1 -1
- package/dist/types/tools/subagent/InMemorySubagentTaskStore.d.ts +1 -1
- package/dist/types/tools/subagent/SubagentExecutor.d.ts +5 -5
- package/dist/types/tools/subagent/SubagentReplay.d.ts +3 -3
- package/dist/types/tools/subagent/childGraphConfig.d.ts +2 -2
- package/dist/types/tools/subagent/diagnostics.d.ts +2 -2
- package/dist/types/tools/subagent/hostArgs.d.ts +2 -2
- package/dist/types/tools/toolBatchReplay.d.ts +3 -3
- package/dist/types/types/activityLabel.d.ts +2 -2
- package/dist/types/types/graph.d.ts +10 -10
- package/dist/types/types/llm.d.ts +9 -9
- package/dist/types/types/reasoningLabel.d.ts +1 -1
- package/dist/types/types/run.d.ts +8 -8
- package/dist/types/types/stream.d.ts +5 -5
- package/dist/types/types/summarize.d.ts +2 -2
- package/dist/types/types/tools.d.ts +8 -8
- package/dist/types/utils/errors.d.ts +1 -1
- package/dist/types/utils/events.d.ts +3 -3
- package/dist/types/utils/handlers.d.ts +3 -3
- package/dist/types/utils/llm.d.ts +2 -2
- package/dist/types/utils/llmConfig.d.ts +1 -1
- package/dist/types/utils/title.d.ts +1 -1
- package/dist/types/utils/toolSessions.d.ts +1 -1
- package/package.json +22 -3
- package/src/runtime/admission.ts +224 -0
- package/src/runtime/checkpoint.ts +66 -0
- package/src/runtime/client.ts +674 -0
- package/src/runtime/files.ts +503 -0
- package/src/runtime/hostTools.ts +243 -0
- package/src/runtime/identity.ts +3 -0
- package/src/runtime/index.ts +33 -0
- package/src/runtime/model.ts +452 -0
- package/src/runtime/peer.ts +262 -0
- package/src/runtime/policy.ts +150 -0
- package/src/runtime/recovery/client.ts +232 -0
- package/src/runtime/recovery/journal.ts +88 -0
- package/src/runtime/recovery/log.ts +70 -0
- package/src/runtime/recovery/redis.ts +342 -0
- package/src/runtime/recovery/server.ts +280 -0
- package/src/runtime/recovery/socket.ts +422 -0
- package/src/runtime/resume.ts +268 -0
- package/src/runtime/sealed.ts +144 -0
- package/src/runtime/server.ts +653 -0
- package/src/runtime/snapshot.ts +87 -0
- package/src/runtime/types.ts +184 -0
- package/src/runtime/wire.ts +96 -0
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import type {
|
|
4
|
+
RemoteSdkFactoryInput,
|
|
5
|
+
RemoteSdkHostServices,
|
|
6
|
+
RemoteSdkLimits,
|
|
7
|
+
RemoteSdkStart,
|
|
8
|
+
} from './types';
|
|
9
|
+
import type {
|
|
10
|
+
HostModelErrorCode,
|
|
11
|
+
HostModelRequest,
|
|
12
|
+
HostModelService,
|
|
13
|
+
} from '@/index';
|
|
14
|
+
import type { HostModelLifecycle, WorkerModelLifecycle } from './admission';
|
|
15
|
+
import type { SdkAgentIdentity } from './identity';
|
|
16
|
+
import type { SdkRpc } from './peer';
|
|
17
|
+
import {
|
|
18
|
+
AIMessageChunk,
|
|
19
|
+
isAIMessage,
|
|
20
|
+
isBaseMessage,
|
|
21
|
+
} from '@/langchain/messages';
|
|
22
|
+
import { HostChatModel, HostModelServiceError, toStoredMessage } from '@/index';
|
|
23
|
+
import { createPolicyReceiver, createPolicySender } from './sealed';
|
|
24
|
+
import { encodeSdkValue, decodeSdkValue } from './wire';
|
|
25
|
+
import { modelAttemptSchema } from './admission';
|
|
26
|
+
|
|
27
|
+
const operationSchema = z
|
|
28
|
+
.object({
|
|
29
|
+
id: z.string().uuid(),
|
|
30
|
+
publicKey: z.string().length(60),
|
|
31
|
+
request: z.unknown(),
|
|
32
|
+
context: modelAttemptSchema.optional(),
|
|
33
|
+
})
|
|
34
|
+
.strict();
|
|
35
|
+
const chunkSchema = z
|
|
36
|
+
.object({
|
|
37
|
+
id: z.string().uuid(),
|
|
38
|
+
index: z.number().int().nonnegative(),
|
|
39
|
+
message: z.unknown(),
|
|
40
|
+
})
|
|
41
|
+
.strict();
|
|
42
|
+
const replySchema = z.discriminatedUnion('ok', [
|
|
43
|
+
z.object({
|
|
44
|
+
version: z.literal(1),
|
|
45
|
+
ok: z.literal(true),
|
|
46
|
+
message: z.unknown().optional(),
|
|
47
|
+
}),
|
|
48
|
+
z.object({
|
|
49
|
+
version: z.literal(1),
|
|
50
|
+
ok: z.literal(false),
|
|
51
|
+
code: z.enum([
|
|
52
|
+
'incompatible',
|
|
53
|
+
'forbidden',
|
|
54
|
+
'blocked',
|
|
55
|
+
'overflow',
|
|
56
|
+
'timeout',
|
|
57
|
+
'cancelled',
|
|
58
|
+
'unavailable',
|
|
59
|
+
]),
|
|
60
|
+
}),
|
|
61
|
+
]);
|
|
62
|
+
type ModelFailure = { version: 1; ok: false; code: HostModelErrorCode };
|
|
63
|
+
type ModelReply =
|
|
64
|
+
| ModelFailure
|
|
65
|
+
| {
|
|
66
|
+
version: 1;
|
|
67
|
+
ok: true;
|
|
68
|
+
message?: ReturnType<ReturnType<typeof createPolicySender>>;
|
|
69
|
+
};
|
|
70
|
+
function failure(error: unknown): ModelFailure {
|
|
71
|
+
const normalized =
|
|
72
|
+
error instanceof HostModelServiceError
|
|
73
|
+
? error
|
|
74
|
+
: new HostModelServiceError('unavailable');
|
|
75
|
+
return {
|
|
76
|
+
version: 1 as const,
|
|
77
|
+
ok: false as const,
|
|
78
|
+
code: normalized.code,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function reply(value: unknown): { version: 1; ok: true; message?: unknown } {
|
|
82
|
+
const result = replySchema.safeParse(value);
|
|
83
|
+
if (!result.success) throw new HostModelServiceError('incompatible');
|
|
84
|
+
if (!result.data.ok) throw new HostModelServiceError(result.data.code);
|
|
85
|
+
return result.data;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function sealValue(
|
|
89
|
+
seal: ReturnType<typeof createPolicySender>,
|
|
90
|
+
value: unknown,
|
|
91
|
+
maxBytes: number
|
|
92
|
+
): ReturnType<ReturnType<typeof createPolicySender>> {
|
|
93
|
+
const text = JSON.stringify(encodeSdkValue(value));
|
|
94
|
+
if (Buffer.byteLength(text) > maxBytes)
|
|
95
|
+
throw new HostModelServiceError('overflow');
|
|
96
|
+
return seal(text);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** One byte window shared by every model stream on this execution's connection. */
|
|
100
|
+
export function createHostModelChannel(options: {
|
|
101
|
+
model: NonNullable<RemoteSdkHostServices['model']>;
|
|
102
|
+
lifecycle?: HostModelLifecycle;
|
|
103
|
+
peer: { call: SdkRpc };
|
|
104
|
+
limits: RemoteSdkLimits;
|
|
105
|
+
signal: AbortSignal;
|
|
106
|
+
}): {
|
|
107
|
+
call(
|
|
108
|
+
method: string,
|
|
109
|
+
data: unknown,
|
|
110
|
+
signal?: AbortSignal
|
|
111
|
+
): Promise<ModelReply>;
|
|
112
|
+
dispose(): void;
|
|
113
|
+
descriptor: NonNullable<RemoteSdkStart['model']>;
|
|
114
|
+
} {
|
|
115
|
+
// Reserve the other half for tools, checkpoints and control RPCs on the same peer.
|
|
116
|
+
const windowBytes = Math.max(
|
|
117
|
+
1,
|
|
118
|
+
Math.floor(options.limits.maxBufferedBytes / 2)
|
|
119
|
+
);
|
|
120
|
+
const receiver = createPolicyReceiver(options.limits.maxFrameBytes, 'model');
|
|
121
|
+
let bufferedBytes = 0;
|
|
122
|
+
const pending = new Set<Promise<void>>();
|
|
123
|
+
const ids = new Set<string>();
|
|
124
|
+
const call = async (
|
|
125
|
+
method: string,
|
|
126
|
+
data: unknown,
|
|
127
|
+
signal?: AbortSignal
|
|
128
|
+
): Promise<ModelReply> => {
|
|
129
|
+
const controller = new AbortController();
|
|
130
|
+
const boundSignal = AbortSignal.any([
|
|
131
|
+
options.signal,
|
|
132
|
+
controller.signal,
|
|
133
|
+
...(signal ? [signal] : []),
|
|
134
|
+
]);
|
|
135
|
+
let id: string | undefined;
|
|
136
|
+
const deliveries = new Set<Promise<void>>();
|
|
137
|
+
let deliveryError: unknown;
|
|
138
|
+
try {
|
|
139
|
+
const parsed = operationSchema.safeParse(
|
|
140
|
+
decodeSdkValue(JSON.parse(receiver.open(data)))
|
|
141
|
+
);
|
|
142
|
+
if (!parsed.success) throw new HostModelServiceError('incompatible');
|
|
143
|
+
if (ids.has(parsed.data.id)) throw new HostModelServiceError('forbidden');
|
|
144
|
+
id = parsed.data.id;
|
|
145
|
+
ids.add(id);
|
|
146
|
+
const seal = createPolicySender(
|
|
147
|
+
parsed.data.publicKey,
|
|
148
|
+
options.limits.maxFrameBytes,
|
|
149
|
+
'model'
|
|
150
|
+
);
|
|
151
|
+
// The SDK binding validates identity, reference, messages and allowed tools before admission.
|
|
152
|
+
const request = parsed.data.request as HostModelRequest;
|
|
153
|
+
if (method === 'model.invoke') {
|
|
154
|
+
const invoke = (): ReturnType<HostModelService['invoke']> =>
|
|
155
|
+
options.model.service.invoke(request, boundSignal);
|
|
156
|
+
const message = await (options.lifecycle
|
|
157
|
+
? options.lifecycle.invoke(parsed.data.context, invoke)
|
|
158
|
+
: invoke());
|
|
159
|
+
return {
|
|
160
|
+
version: 1,
|
|
161
|
+
ok: true,
|
|
162
|
+
message: sealValue(
|
|
163
|
+
seal,
|
|
164
|
+
{ id, message },
|
|
165
|
+
options.limits.maxFrameBytes
|
|
166
|
+
),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
if (method !== 'model.stream')
|
|
170
|
+
throw new HostModelServiceError('incompatible');
|
|
171
|
+
let index = 0;
|
|
172
|
+
const stream = (): ReturnType<HostModelService['stream']> =>
|
|
173
|
+
options.model.service.stream(request, boundSignal);
|
|
174
|
+
const source = options.lifecycle
|
|
175
|
+
? options.lifecycle.stream(parsed.data.context, stream)
|
|
176
|
+
: stream();
|
|
177
|
+
for await (const chunk of source) {
|
|
178
|
+
boundSignal.throwIfAborted();
|
|
179
|
+
if (deliveryError != null) throw deliveryError;
|
|
180
|
+
const payload = sealValue(
|
|
181
|
+
seal,
|
|
182
|
+
{ id, index: index++, message: toStoredMessage(chunk).data },
|
|
183
|
+
options.limits.maxFrameBytes
|
|
184
|
+
);
|
|
185
|
+
const bytes = Buffer.byteLength(
|
|
186
|
+
JSON.stringify(
|
|
187
|
+
encodeSdkValue({
|
|
188
|
+
type: 'call',
|
|
189
|
+
id: '00000000-0000-0000-0000-000000000000',
|
|
190
|
+
method: 'model.chunk',
|
|
191
|
+
data: payload,
|
|
192
|
+
})
|
|
193
|
+
)
|
|
194
|
+
);
|
|
195
|
+
if (bytes > options.limits.maxFrameBytes || bytes > windowBytes)
|
|
196
|
+
throw new HostModelServiceError('overflow');
|
|
197
|
+
while (bufferedBytes + bytes > windowBytes) {
|
|
198
|
+
await new Promise<void>((resolve, reject) => {
|
|
199
|
+
const abort = (): void =>
|
|
200
|
+
reject(new HostModelServiceError('cancelled'));
|
|
201
|
+
boundSignal.addEventListener('abort', abort, { once: true });
|
|
202
|
+
void Promise.race(pending).then(() => {
|
|
203
|
+
boundSignal.removeEventListener('abort', abort);
|
|
204
|
+
resolve();
|
|
205
|
+
});
|
|
206
|
+
if (boundSignal.aborted) abort();
|
|
207
|
+
});
|
|
208
|
+
boundSignal.throwIfAborted();
|
|
209
|
+
}
|
|
210
|
+
bufferedBytes += bytes;
|
|
211
|
+
const delivery = options.peer
|
|
212
|
+
.call('model.chunk', payload, options.limits.maxRunMs, boundSignal)
|
|
213
|
+
.then((value) => {
|
|
214
|
+
reply(value);
|
|
215
|
+
})
|
|
216
|
+
.catch((error: unknown) => {
|
|
217
|
+
deliveryError = error;
|
|
218
|
+
controller.abort();
|
|
219
|
+
})
|
|
220
|
+
.finally(() => {
|
|
221
|
+
bufferedBytes -= bytes;
|
|
222
|
+
pending.delete(delivery);
|
|
223
|
+
deliveries.delete(delivery);
|
|
224
|
+
});
|
|
225
|
+
pending.add(delivery);
|
|
226
|
+
deliveries.add(delivery);
|
|
227
|
+
}
|
|
228
|
+
await Promise.all(deliveries);
|
|
229
|
+
if (deliveryError != null) throw deliveryError;
|
|
230
|
+
boundSignal.throwIfAborted();
|
|
231
|
+
return { version: 1, ok: true };
|
|
232
|
+
} catch (error) {
|
|
233
|
+
return failure(error);
|
|
234
|
+
} finally {
|
|
235
|
+
controller.abort();
|
|
236
|
+
await Promise.all(deliveries);
|
|
237
|
+
if (id != null) ids.delete(id);
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
return {
|
|
241
|
+
call,
|
|
242
|
+
dispose: receiver.dispose,
|
|
243
|
+
descriptor: {
|
|
244
|
+
version: 1 as const,
|
|
245
|
+
publicKey: receiver.publicKey,
|
|
246
|
+
descriptor: options.model.descriptor,
|
|
247
|
+
},
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
interface ChunkDelivery {
|
|
252
|
+
chunk: AIMessageChunk;
|
|
253
|
+
settle: (error?: Error) => void;
|
|
254
|
+
}
|
|
255
|
+
interface ModelStream {
|
|
256
|
+
queue: Map<number, ChunkDelivery>;
|
|
257
|
+
next: number;
|
|
258
|
+
index: number;
|
|
259
|
+
done: boolean;
|
|
260
|
+
error?: Error;
|
|
261
|
+
wake: () => void;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Chunk receipts release credits only when consumed, so a slow graph bounds host production. */
|
|
265
|
+
export function createWorkerModelChannel(options: {
|
|
266
|
+
peer: { call: SdkRpc };
|
|
267
|
+
limits: RemoteSdkLimits;
|
|
268
|
+
signal: AbortSignal;
|
|
269
|
+
}): {
|
|
270
|
+
bind(
|
|
271
|
+
identity: Readonly<SdkAgentIdentity>,
|
|
272
|
+
descriptor: NonNullable<RemoteSdkStart['model']>,
|
|
273
|
+
admission?: WorkerModelLifecycle
|
|
274
|
+
): NonNullable<RemoteSdkFactoryInput['hostModel']>;
|
|
275
|
+
accept(data: unknown, signal?: AbortSignal): Promise<ModelReply>;
|
|
276
|
+
} {
|
|
277
|
+
const streams = new Map<string, ModelStream>();
|
|
278
|
+
let receiver: ReturnType<typeof createPolicyReceiver> | undefined;
|
|
279
|
+
let seal: ReturnType<typeof createPolicySender> | undefined;
|
|
280
|
+
let lifecycle: WorkerModelLifecycle | undefined;
|
|
281
|
+
const encodeRequest = (
|
|
282
|
+
id: string,
|
|
283
|
+
request: HostModelRequest,
|
|
284
|
+
context?: unknown
|
|
285
|
+
): ReturnType<ReturnType<typeof createPolicySender>> => {
|
|
286
|
+
if (!receiver || !seal) throw new HostModelServiceError('incompatible');
|
|
287
|
+
return sealValue(
|
|
288
|
+
seal,
|
|
289
|
+
{
|
|
290
|
+
id,
|
|
291
|
+
publicKey: receiver.publicKey,
|
|
292
|
+
request,
|
|
293
|
+
...(lifecycle && { context: lifecycle.current(context) }),
|
|
294
|
+
},
|
|
295
|
+
options.limits.maxFrameBytes
|
|
296
|
+
);
|
|
297
|
+
};
|
|
298
|
+
const open = (data: unknown): unknown => {
|
|
299
|
+
if (!receiver) throw new HostModelServiceError('incompatible');
|
|
300
|
+
return decodeSdkValue(JSON.parse(receiver.open(data)));
|
|
301
|
+
};
|
|
302
|
+
const stop = (state: ModelStream, error: Error): void => {
|
|
303
|
+
state.error = error;
|
|
304
|
+
state.done = true;
|
|
305
|
+
for (const delivery of state.queue.values()) delivery.settle(error);
|
|
306
|
+
state.queue.clear();
|
|
307
|
+
state.wake();
|
|
308
|
+
};
|
|
309
|
+
const dispose = (): void => {
|
|
310
|
+
receiver?.dispose();
|
|
311
|
+
for (const state of streams.values())
|
|
312
|
+
stop(state, new HostModelServiceError('cancelled'));
|
|
313
|
+
};
|
|
314
|
+
options.signal.addEventListener('abort', dispose, { once: true });
|
|
315
|
+
const service: HostModelService = {
|
|
316
|
+
version: 1,
|
|
317
|
+
invoke: async (request, signal, context?: unknown) => {
|
|
318
|
+
const id = randomUUID();
|
|
319
|
+
const result = reply(
|
|
320
|
+
await options.peer.call(
|
|
321
|
+
'model.invoke',
|
|
322
|
+
encodeRequest(id, request, context),
|
|
323
|
+
options.limits.maxRunMs,
|
|
324
|
+
signal ? AbortSignal.any([options.signal, signal]) : options.signal
|
|
325
|
+
)
|
|
326
|
+
);
|
|
327
|
+
const value = z
|
|
328
|
+
.object({ id: z.literal(id), message: z.unknown() })
|
|
329
|
+
.parse(open(result.message));
|
|
330
|
+
if (!isBaseMessage(value.message) || !isAIMessage(value.message))
|
|
331
|
+
throw new HostModelServiceError('incompatible');
|
|
332
|
+
return value.message;
|
|
333
|
+
},
|
|
334
|
+
stream: async function* (request, signal, context?: unknown) {
|
|
335
|
+
const id = randomUUID();
|
|
336
|
+
const payload = encodeRequest(id, request, context);
|
|
337
|
+
const controller = new AbortController();
|
|
338
|
+
const boundSignal = AbortSignal.any([
|
|
339
|
+
options.signal,
|
|
340
|
+
controller.signal,
|
|
341
|
+
...(signal ? [signal] : []),
|
|
342
|
+
]);
|
|
343
|
+
boundSignal.throwIfAborted();
|
|
344
|
+
const state: ModelStream = {
|
|
345
|
+
queue: new Map(),
|
|
346
|
+
next: 0,
|
|
347
|
+
index: 0,
|
|
348
|
+
done: false,
|
|
349
|
+
wake: () => {},
|
|
350
|
+
};
|
|
351
|
+
const abort = (): void =>
|
|
352
|
+
stop(state, new HostModelServiceError('cancelled'));
|
|
353
|
+
boundSignal.addEventListener('abort', abort, { once: true });
|
|
354
|
+
streams.set(id, state);
|
|
355
|
+
const completion = options.peer
|
|
356
|
+
.call('model.stream', payload, options.limits.maxRunMs, boundSignal)
|
|
357
|
+
.then((value) => {
|
|
358
|
+
reply(value);
|
|
359
|
+
state.done = true;
|
|
360
|
+
state.wake();
|
|
361
|
+
})
|
|
362
|
+
.catch((error: unknown) =>
|
|
363
|
+
stop(
|
|
364
|
+
state,
|
|
365
|
+
error instanceof HostModelServiceError
|
|
366
|
+
? error
|
|
367
|
+
: new HostModelServiceError('unavailable')
|
|
368
|
+
)
|
|
369
|
+
);
|
|
370
|
+
try {
|
|
371
|
+
for (;;) {
|
|
372
|
+
if (state.error) throw state.error;
|
|
373
|
+
const delivery = state.queue.get(state.next);
|
|
374
|
+
if (delivery) {
|
|
375
|
+
state.queue.delete(state.next++);
|
|
376
|
+
delivery.settle();
|
|
377
|
+
yield delivery.chunk;
|
|
378
|
+
continue;
|
|
379
|
+
}
|
|
380
|
+
if (state.done) return;
|
|
381
|
+
await new Promise<void>((resolve) => {
|
|
382
|
+
state.wake = resolve;
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
} finally {
|
|
386
|
+
controller.abort();
|
|
387
|
+
streams.delete(id);
|
|
388
|
+
boundSignal.removeEventListener('abort', abort);
|
|
389
|
+
await completion;
|
|
390
|
+
}
|
|
391
|
+
},
|
|
392
|
+
};
|
|
393
|
+
return {
|
|
394
|
+
bind: (
|
|
395
|
+
identity: Readonly<SdkAgentIdentity>,
|
|
396
|
+
descriptor: NonNullable<RemoteSdkStart['model']>,
|
|
397
|
+
admission?: WorkerModelLifecycle
|
|
398
|
+
): NonNullable<RemoteSdkFactoryInput['hostModel']> => {
|
|
399
|
+
if (
|
|
400
|
+
receiver ||
|
|
401
|
+
options.signal.aborted ||
|
|
402
|
+
Number(descriptor.version) !== 1
|
|
403
|
+
)
|
|
404
|
+
throw new HostModelServiceError('incompatible');
|
|
405
|
+
lifecycle = admission;
|
|
406
|
+
receiver = createPolicyReceiver(options.limits.maxFrameBytes, 'model');
|
|
407
|
+
seal = createPolicySender(
|
|
408
|
+
descriptor.publicKey,
|
|
409
|
+
options.limits.maxFrameBytes,
|
|
410
|
+
'model'
|
|
411
|
+
);
|
|
412
|
+
const config = { identity, descriptor: descriptor.descriptor, service };
|
|
413
|
+
return (
|
|
414
|
+
lifecycle ? lifecycle.model(config) : new HostChatModel(config)
|
|
415
|
+
).bindTools([...descriptor.descriptor.tools]);
|
|
416
|
+
},
|
|
417
|
+
accept: async (
|
|
418
|
+
data: unknown,
|
|
419
|
+
signal?: AbortSignal
|
|
420
|
+
): Promise<ModelReply> => {
|
|
421
|
+
try {
|
|
422
|
+
const parsed = chunkSchema.safeParse(open(data));
|
|
423
|
+
if (!parsed.success) throw new HostModelServiceError('incompatible');
|
|
424
|
+
const state = streams.get(parsed.data.id);
|
|
425
|
+
if (!state || state.done || state.index !== parsed.data.index)
|
|
426
|
+
throw new HostModelServiceError('incompatible');
|
|
427
|
+
const chunk = new AIMessageChunk(
|
|
428
|
+
parsed.data.message as ConstructorParameters<typeof AIMessageChunk>[0]
|
|
429
|
+
);
|
|
430
|
+
state.index++;
|
|
431
|
+
await new Promise<void>((resolve, reject) => {
|
|
432
|
+
const abort = (): void =>
|
|
433
|
+
stop(state, new HostModelServiceError('cancelled'));
|
|
434
|
+
state.queue.set(parsed.data.index, {
|
|
435
|
+
chunk,
|
|
436
|
+
settle: (error) => {
|
|
437
|
+
signal?.removeEventListener('abort', abort);
|
|
438
|
+
if (error) reject(error);
|
|
439
|
+
else resolve();
|
|
440
|
+
},
|
|
441
|
+
});
|
|
442
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
443
|
+
if (signal?.aborted === true) abort();
|
|
444
|
+
state.wake();
|
|
445
|
+
});
|
|
446
|
+
return { version: 1, ok: true };
|
|
447
|
+
} catch (error) {
|
|
448
|
+
return failure(error);
|
|
449
|
+
}
|
|
450
|
+
},
|
|
451
|
+
};
|
|
452
|
+
}
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { WebSocket } from 'ws';
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { encodeSdkValue, decodeSdkValue } from './wire';
|
|
5
|
+
|
|
6
|
+
/** Logical connections may survive replacement of their underlying WebSocket. */
|
|
7
|
+
export interface SdkSocket {
|
|
8
|
+
readonly readyState: number;
|
|
9
|
+
readonly bufferedAmount: number;
|
|
10
|
+
send(data: string): void;
|
|
11
|
+
close(code?: number): void;
|
|
12
|
+
on(event: 'message', listener: (data: WebSocket.RawData) => void): this;
|
|
13
|
+
on(event: 'close' | 'error', listener: () => void): this;
|
|
14
|
+
once(event: 'close' | 'error', listener: () => void): this;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Cancellation requests remote cleanup; settlement waits for its reply (or the RPC deadline). */
|
|
18
|
+
export type SdkRpc = (
|
|
19
|
+
method: string,
|
|
20
|
+
data: unknown,
|
|
21
|
+
timeoutMs?: number,
|
|
22
|
+
signal?: AbortSignal
|
|
23
|
+
) => Promise<unknown>;
|
|
24
|
+
export type SdkFrame =
|
|
25
|
+
| { type: 'call'; id: string; method: string; data: unknown }
|
|
26
|
+
| { type: 'cancel'; id: string }
|
|
27
|
+
| { type: 'result'; id: string; data: unknown; failed?: boolean }
|
|
28
|
+
| {
|
|
29
|
+
type: 'event';
|
|
30
|
+
name: string;
|
|
31
|
+
data: unknown;
|
|
32
|
+
metadata?: Record<string, unknown>;
|
|
33
|
+
}
|
|
34
|
+
| { type: 'snapshot'; data: unknown }
|
|
35
|
+
| { type: 'done'; data: unknown }
|
|
36
|
+
| { type: 'error' };
|
|
37
|
+
|
|
38
|
+
export interface SdkPeer {
|
|
39
|
+
call: SdkRpc;
|
|
40
|
+
send(frame: SdkFrame): void;
|
|
41
|
+
close(): void;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const frameSchema = z.discriminatedUnion('type', [
|
|
45
|
+
z.object({ type: z.literal('cancel'), id: z.string().uuid() }),
|
|
46
|
+
z.object({
|
|
47
|
+
type: z.literal('call'),
|
|
48
|
+
id: z.string().uuid(),
|
|
49
|
+
method: z.string().min(1).max(64),
|
|
50
|
+
data: z.unknown(),
|
|
51
|
+
}),
|
|
52
|
+
z.object({
|
|
53
|
+
type: z.literal('result'),
|
|
54
|
+
id: z.string().uuid(),
|
|
55
|
+
data: z.unknown(),
|
|
56
|
+
failed: z.boolean().optional(),
|
|
57
|
+
}),
|
|
58
|
+
z.object({
|
|
59
|
+
type: z.literal('event'),
|
|
60
|
+
name: z.string().min(1).max(128),
|
|
61
|
+
data: z.unknown(),
|
|
62
|
+
metadata: z.record(z.string(), z.unknown()).optional(),
|
|
63
|
+
}),
|
|
64
|
+
z.object({ type: z.literal('snapshot'), data: z.unknown() }),
|
|
65
|
+
z.object({ type: z.literal('done'), data: z.unknown() }),
|
|
66
|
+
z.object({ type: z.literal('error') }),
|
|
67
|
+
]);
|
|
68
|
+
|
|
69
|
+
/** Ordered dispatch and bounded RPC lifetime. Errors on this boundary never disclose upstream text. */
|
|
70
|
+
export function createSdkPeer(
|
|
71
|
+
socket: SdkSocket,
|
|
72
|
+
options: {
|
|
73
|
+
maxFrameBytes: number;
|
|
74
|
+
maxBufferedBytes: number;
|
|
75
|
+
timeoutMs: number;
|
|
76
|
+
onCall: SdkRpc;
|
|
77
|
+
onFrame: (frame: SdkFrame) => Promise<void>;
|
|
78
|
+
onClose: (error: Error) => void;
|
|
79
|
+
onError?: (error: unknown) => void;
|
|
80
|
+
}
|
|
81
|
+
): SdkPeer {
|
|
82
|
+
const pending = new Map<
|
|
83
|
+
string,
|
|
84
|
+
{ resolve: (data: unknown) => void; reject: (error: Error) => void }
|
|
85
|
+
>();
|
|
86
|
+
const incoming = new Map<string, AbortController>();
|
|
87
|
+
let queue = Promise.resolve();
|
|
88
|
+
let closed = false;
|
|
89
|
+
let queuedBytes = 0;
|
|
90
|
+
const report = (error: unknown): void => {
|
|
91
|
+
try {
|
|
92
|
+
options.onError?.(error);
|
|
93
|
+
} catch {
|
|
94
|
+
/* Diagnostics must not prevent cleanup. */
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
const failure = (): Error => new Error('SDK runtime connection failed');
|
|
98
|
+
const send = (frame: SdkFrame): void => {
|
|
99
|
+
if (closed || socket.readyState !== WebSocket.OPEN) throw failure();
|
|
100
|
+
const data = JSON.stringify(encodeSdkValue(frame));
|
|
101
|
+
if (
|
|
102
|
+
Buffer.byteLength(data) > options.maxFrameBytes ||
|
|
103
|
+
socket.bufferedAmount + Buffer.byteLength(data) > options.maxBufferedBytes
|
|
104
|
+
)
|
|
105
|
+
throw failure();
|
|
106
|
+
socket.send(data);
|
|
107
|
+
};
|
|
108
|
+
const close = (): void => {
|
|
109
|
+
if (closed) return;
|
|
110
|
+
closed = true;
|
|
111
|
+
for (const entry of pending.values()) entry.reject(failure());
|
|
112
|
+
pending.clear();
|
|
113
|
+
for (const controller of incoming.values()) controller.abort();
|
|
114
|
+
incoming.clear();
|
|
115
|
+
options.onClose(failure());
|
|
116
|
+
};
|
|
117
|
+
socket.on('close', close);
|
|
118
|
+
socket.on('error', close);
|
|
119
|
+
socket.on('message', (raw) => {
|
|
120
|
+
if (closed) return;
|
|
121
|
+
const bytes = Buffer.byteLength(raw.toString());
|
|
122
|
+
if (bytes > options.maxFrameBytes) {
|
|
123
|
+
socket.close(1009);
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
let frame: SdkFrame;
|
|
127
|
+
try {
|
|
128
|
+
frame = frameSchema.parse(decodeSdkValue(JSON.parse(raw.toString())));
|
|
129
|
+
} catch {
|
|
130
|
+
socket.close(1008);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
// Cancel before dispatch as well as during execution, without waiting behind event/hooks.
|
|
134
|
+
// Unknown/settled IDs are harmless; this cannot cancel another connection's invocation.
|
|
135
|
+
if (frame.type === 'cancel') {
|
|
136
|
+
incoming.get(frame.id)?.abort();
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
// RPC replies must bypass the event queue: a handler may itself be awaiting this reply.
|
|
140
|
+
if (frame.type === 'result') {
|
|
141
|
+
const entry = pending.get(frame.id);
|
|
142
|
+
if (entry == null) return;
|
|
143
|
+
pending.delete(frame.id);
|
|
144
|
+
if (frame.failed === true) entry.reject(failure());
|
|
145
|
+
else entry.resolve(frame.data);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
if (frame.type === 'call') {
|
|
149
|
+
if (incoming.has(frame.id)) {
|
|
150
|
+
close();
|
|
151
|
+
socket.close(1008);
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
const controller = new AbortController();
|
|
155
|
+
incoming.set(frame.id, controller);
|
|
156
|
+
queuedBytes += bytes;
|
|
157
|
+
if (queuedBytes > options.maxBufferedBytes) {
|
|
158
|
+
close();
|
|
159
|
+
socket.close(1009);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
const dispatch = (): Promise<void> =>
|
|
163
|
+
Promise.resolve()
|
|
164
|
+
.then(() => {
|
|
165
|
+
if (closed) throw failure();
|
|
166
|
+
controller.signal.throwIfAborted();
|
|
167
|
+
return options.onCall(
|
|
168
|
+
frame.method,
|
|
169
|
+
frame.data,
|
|
170
|
+
undefined,
|
|
171
|
+
controller.signal
|
|
172
|
+
);
|
|
173
|
+
})
|
|
174
|
+
.then(
|
|
175
|
+
(data) => send({ type: 'result', id: frame.id, data }),
|
|
176
|
+
(error) => {
|
|
177
|
+
report(error);
|
|
178
|
+
send({ type: 'result', id: frame.id, failed: true, data: null });
|
|
179
|
+
}
|
|
180
|
+
)
|
|
181
|
+
.catch(() => socket.close(1011))
|
|
182
|
+
.finally(() => {
|
|
183
|
+
incoming.delete(frame.id);
|
|
184
|
+
queuedBytes -= bytes;
|
|
185
|
+
});
|
|
186
|
+
// Hooks observe all earlier events and can reserve content slots for later ones.
|
|
187
|
+
// Ordinary RPCs stay reentrant; replies above always bypass this barrier.
|
|
188
|
+
if (frame.method === 'hook') queue = queue.then(dispatch);
|
|
189
|
+
else if (frame.method === 'tools')
|
|
190
|
+
queue = queue.then(() => {
|
|
191
|
+
void dispatch();
|
|
192
|
+
});
|
|
193
|
+
else void dispatch();
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
queuedBytes += bytes;
|
|
197
|
+
if (queuedBytes > options.maxBufferedBytes) {
|
|
198
|
+
close();
|
|
199
|
+
socket.close(1009);
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
queue = queue
|
|
203
|
+
.then(() => (closed ? undefined : options.onFrame(frame)))
|
|
204
|
+
.finally(() => {
|
|
205
|
+
queuedBytes -= bytes;
|
|
206
|
+
})
|
|
207
|
+
.catch((error) => {
|
|
208
|
+
report(error);
|
|
209
|
+
close();
|
|
210
|
+
socket.close(1011);
|
|
211
|
+
});
|
|
212
|
+
});
|
|
213
|
+
const call: SdkRpc = async (
|
|
214
|
+
method,
|
|
215
|
+
data,
|
|
216
|
+
timeoutMs = options.timeoutMs,
|
|
217
|
+
signal
|
|
218
|
+
) => {
|
|
219
|
+
signal?.throwIfAborted();
|
|
220
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) throw failure();
|
|
221
|
+
const id = randomUUID();
|
|
222
|
+
return new Promise((resolve, reject) => {
|
|
223
|
+
const abort = (): void => {
|
|
224
|
+
try {
|
|
225
|
+
send({ type: 'cancel', id });
|
|
226
|
+
} catch {
|
|
227
|
+
close();
|
|
228
|
+
socket.close(1011);
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
const cleanup = (): void => {
|
|
232
|
+
clearTimeout(timer);
|
|
233
|
+
signal?.removeEventListener('abort', abort);
|
|
234
|
+
};
|
|
235
|
+
const timer = setTimeout(() => {
|
|
236
|
+
cleanup();
|
|
237
|
+
pending.delete(id);
|
|
238
|
+
reject(failure());
|
|
239
|
+
}, timeoutMs);
|
|
240
|
+
timer.unref();
|
|
241
|
+
pending.set(id, {
|
|
242
|
+
resolve: (value) => {
|
|
243
|
+
cleanup();
|
|
244
|
+
resolve(value);
|
|
245
|
+
},
|
|
246
|
+
reject: (error) => {
|
|
247
|
+
cleanup();
|
|
248
|
+
reject(error);
|
|
249
|
+
},
|
|
250
|
+
});
|
|
251
|
+
try {
|
|
252
|
+
send({ type: 'call', id, method, data });
|
|
253
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
254
|
+
if (signal?.aborted === true) abort();
|
|
255
|
+
} catch (error) {
|
|
256
|
+
pending.get(id)?.reject(error instanceof Error ? error : failure());
|
|
257
|
+
pending.delete(id);
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
};
|
|
261
|
+
return { call, send, close };
|
|
262
|
+
}
|