@yolk-sdk/agent 0.1.0-canary.28 → 0.1.0-canary.30
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/README.md +6 -2
- package/dist/client/transport.d.mts.map +1 -1
- package/dist/client/transport.mjs +28 -4
- package/dist/client/transport.mjs.map +1 -1
- package/dist/protocol/event.d.mts +5 -1
- package/dist/protocol/event.d.mts.map +1 -1
- package/dist/protocol/event.mjs +2 -1
- package/dist/protocol/event.mjs.map +1 -1
- package/dist/protocol/index.d.mts +2 -2
- package/dist/protocol/index.d.mts.map +1 -1
- package/dist/protocol/index.mjs +2 -2
- package/package.json +1 -1
- package/src/client/transport.ts +36 -10
- package/src/protocol/event.ts +8 -0
- package/src/protocol/index.ts +3 -1
package/README.md
CHANGED
|
@@ -43,6 +43,7 @@ Canary APIs are unstable. Keep all `@yolk-sdk/*` packages on the same version.
|
|
|
43
43
|
import {
|
|
44
44
|
danglingHostToolCalls,
|
|
45
45
|
hitlResponseEvent,
|
|
46
|
+
isTerminalAgentEvent,
|
|
46
47
|
makeSubagentRunId,
|
|
47
48
|
ProviderErrorInfo,
|
|
48
49
|
questionResponseStructuredContent,
|
|
@@ -268,12 +269,15 @@ HITL is protocol-level, not UI-level:
|
|
|
268
269
|
- Approval is a host-enforced per-call gate for normal tools, not a model-callable permission tool or persisted allow-always system.
|
|
269
270
|
|
|
270
271
|
HTTP client helpers treat `AgentEnd`, `AgentError`, and `AgentAwaitingInput` as logical stream
|
|
271
|
-
end for consumers.
|
|
272
|
-
terminal event
|
|
272
|
+
end for consumers. Use `isTerminalAgentEvent` when projecting generic protocol streams. After a
|
|
273
|
+
terminal event the response body drains to EOF; cancellation before a terminal event still aborts
|
|
274
|
+
the active body reader.
|
|
273
275
|
Durable Workflow clients can use `streamAgentEventsUntilTerminal`,
|
|
274
276
|
`streamAgentRunEventsUntilTerminal`, and `streamAgentRunHitlResponseEventsUntilTerminal` to follow
|
|
275
277
|
continuation chunks by `x-workflow-run-id` and `x-workflow-stream-tail-index` headers. These helpers
|
|
276
278
|
fail with `AgentTransportError` if no terminal event is reached before the continuation limit.
|
|
279
|
+
Empty non-terminal continuation chunks are polling gaps: the client waits briefly, retries from the
|
|
280
|
+
same `startIndex`, and respects the request `signal` while waiting.
|
|
277
281
|
For HITL resume responses, `x-workflow-stream-tail-index` means the stream tail before the returned
|
|
278
282
|
body. The returned body starts at `tail + 1`; the next continuation starts after all returned
|
|
279
283
|
events. `continuationLimit: 0` disables follow-up chunks, so any non-terminal response fails
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport.d.mts","names":[],"sources":["../../src/client/transport.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"transport.d.mts","names":[],"sources":["../../src/client/transport.ts"],"mappings":";;;;;;;cA2BiD,wBAAA;;;;cAEpC,mBAAA,SAA4B,wBAMxC;AAAA,KAEW,wBAAA;EAAA,SACD,QAAA;EAAA,SACA,SAAA;EAAA,SACA,QAAA,EAAU,eAAA;EAAA,SACV,aAAA,GAAgB,aAAA,CAAc,YAAA;EAAA,SAC9B,KAAA;EAAA,SACA,eAAA,GAAkB,oBAAA;EAAA,SAClB,MAAA,GAAS,WAAA;EAAA,SACT,eAAA,GAAkB,KAAA,CAAM,KAAA,CAAM,UAAA,CAAW,UAAA;EAAA,SACzC,UAAA,IAAc,QAAA,EAAU,qBAAA;AAAA;AAAA,KAGvB,2BAAA;EAAA,SACD,QAAA;EAAA,SACA,UAAA;EAAA,SACA,MAAA,GAAS,WAAA;EAAA,SACT,eAAA,GAAkB,KAAA,CAAM,KAAA,CAAM,UAAA,CAAW,UAAA;EAAA,SACzC,UAAA,IAAc,QAAA,EAAU,qBAAA;AAAA;AAAA,KAGvB,uCAAA;EAAA,SACD,QAAA;EAAA,SACA,aAAA,EAAe,aAAA,CAAc,YAAA;EAAA,SAC7B,MAAA,GAAS,WAAA;EAAA,SACT,eAAA,GAAkB,KAAA,CAAM,KAAA,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A,sCAAA,UAAA,sCAAA,QAAA,sCAAA,kBAAA,sCAAA,WAAA,sCAAA,UAAA,sCAAA,eAAA,sCAAA,aAAA,sCAAA,SAAA,sCAAA,OAAA,sCAAA,cAAA,sCAAA,YAAA,sCAAA,iBAAA,sCAAA,cAAA,sCAAA,cAAA,sCAAA,YAAA,sCAAA,YAAA,sCAAA,qBAAA,sCAAA,qBAAA,sCAAA,mBAAA,sCAAA,kBAAA,sCAAA,iBAAA,sCAAA,gBAAA,sCAAA,iBAAA,sCAAA,oBAAA,sCAAA,sBAAA,sCAAA,kBAAA,sCAAA,kBAAA,sCAAA,eAAA,sCAAA,iBAAA,KAAA,mBAAA;AAAA,cAG7D,kBAAA,GAA4B,OAAA,EAAS,wBAAA,KAAwB,OAAA,qCAAA,UAAA,sCAAA,UAAA,sCAAA,QAAA,sCAAA,kBAAA,sCAAA,WAAA,sCAAA,UAAA,sCAAA,eAAA,sCAAA,aAAA,sCAAA,SAAA,sCAAA,OAAA,sCAAA,cAAA,sCAAA,YAAA,sCAAA,iBAAA,sCAAA,cAAA,sCAAA,cAAA,sCAAA,YAAA,sCAAA,YAAA,sCAAA,qBAAA,sCAAA,qBAAA,sCAAA,mBAAA,sCAAA,kBAAA,sCAAA,iBAAA,sCAAA,gBAAA,sCAAA,iBAAA,sCAAA,oBAAA,sCAAA,sBAAA,sCAAA,kBAAA,sCAAA,kBAAA,sCAAA,eAAA,sCAAA,iBAAA"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AgentEvent, AgentWebSocketServerMessage, QuestionResponseInput, ToolApprovalResponseInput, UserInput } from "@yolk-sdk/agent/protocol";
|
|
1
|
+
import { AgentEvent, AgentWebSocketServerMessage, QuestionResponseInput, ToolApprovalResponseInput, UserInput, isTerminalAgentEvent } from "@yolk-sdk/agent/protocol";
|
|
2
2
|
import { Cause, Channel, Effect, Exit, Pull, Queue, Ref, Scope, Stream } from "effect";
|
|
3
3
|
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
|
|
4
4
|
import * as Schema from "effect/Schema";
|
|
@@ -234,7 +234,6 @@ const cancelAgentRunEffect = (request) => Effect.gen(function* () {
|
|
|
234
234
|
cause: response.status
|
|
235
235
|
}));
|
|
236
236
|
}).pipe(Effect.provide(request.httpClientLayer ?? FetchHttpClient.layer));
|
|
237
|
-
const isTerminalAgentEvent = (event) => event._tag === "AgentEnd" || event._tag === "AgentError" || event._tag === "AgentAwaitingInput";
|
|
238
237
|
const responseToLineStream = (response) => response.stream.pipe(Stream.mapError(toHttpClientTransportError("Could not read agent response body")), Stream.decodeText, Stream.splitLines, Stream.map((line) => line.trim()), Stream.filter((line) => line.length > 0));
|
|
239
238
|
const closeScope = (scope) => Scope.close(scope, Exit.succeed(void 0));
|
|
240
239
|
const responseToEventStream = (response) => Stream.callback((queue) => Effect.gen(function* () {
|
|
@@ -322,6 +321,27 @@ const noProgressAgentRunContinuationError = (endpoint, startIndex) => new AgentT
|
|
|
322
321
|
startIndex
|
|
323
322
|
}
|
|
324
323
|
});
|
|
324
|
+
const noProgressAgentRunContinuationDelayMs = 250;
|
|
325
|
+
const waitForAgentRunContinuationProgress = (signal) => new Promise((resolve, reject) => {
|
|
326
|
+
if (signal === void 0) {
|
|
327
|
+
setTimeout(resolve, noProgressAgentRunContinuationDelayMs);
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
if (signal.aborted) {
|
|
331
|
+
reject(abortSignalError(signal));
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
const timeout = setTimeout(() => {
|
|
335
|
+
signal.removeEventListener("abort", onAbort);
|
|
336
|
+
resolve();
|
|
337
|
+
}, noProgressAgentRunContinuationDelayMs);
|
|
338
|
+
const onAbort = () => {
|
|
339
|
+
clearTimeout(timeout);
|
|
340
|
+
signal.removeEventListener("abort", onAbort);
|
|
341
|
+
reject(abortSignalError(signal));
|
|
342
|
+
};
|
|
343
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
344
|
+
});
|
|
325
345
|
const missingAgentRunTailIndexError = () => new AgentTransportError({
|
|
326
346
|
message: "Agent run HITL response missing x-workflow-stream-tail-index",
|
|
327
347
|
cause: "missing_tail_index"
|
|
@@ -360,7 +380,11 @@ const streamAgentRunContinuations = async function* (input) {
|
|
|
360
380
|
countOffset: totalCount,
|
|
361
381
|
onEvent: input.onEvent
|
|
362
382
|
});
|
|
363
|
-
if (chunk.count === 0 && !chunk.terminal)
|
|
383
|
+
if (chunk.count === 0 && !chunk.terminal) {
|
|
384
|
+
if (continuation >= limit - 1) throw noProgressAgentRunContinuationError(endpoint, startIndex);
|
|
385
|
+
await waitForAgentRunContinuationProgress(input.signal);
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
364
388
|
terminal = chunk.terminal;
|
|
365
389
|
startIndex = nextAgentRunStartIndex(startIndex, chunk.count);
|
|
366
390
|
totalCount += chunk.count;
|
|
@@ -468,7 +492,7 @@ const streamCloudflareAgentEventStream = (request) => applyAbortSignal(Stream.ca
|
|
|
468
492
|
if (!isAgentEvent(message)) return Effect.void;
|
|
469
493
|
return Effect.sync(() => {
|
|
470
494
|
Queue.offerUnsafe(queue, message);
|
|
471
|
-
if (message
|
|
495
|
+
if (isTerminalAgentEvent(message)) {
|
|
472
496
|
settled = true;
|
|
473
497
|
endQueue();
|
|
474
498
|
socket.close(1e3, "done");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport.mjs","names":[],"sources":["../../src/client/transport.ts"],"sourcesContent":["import { Cause, Channel, Effect, Exit, Pull, Queue, Ref, Scope, Stream, type Layer } from 'effect'\nimport {\n FetchHttpClient,\n HttpClient,\n HttpClientRequest,\n type HttpClientError,\n type HttpClientResponse\n} from 'effect/unstable/http'\nimport * as Schema from 'effect/Schema'\nimport {\n AgentEvent,\n AgentWebSocketServerMessage,\n QuestionResponseInput,\n ToolApprovalResponseInput,\n UserInput\n} from '@yolk-sdk/agent/protocol'\nimport type {\n AgentEvent as AgentEventType,\n AgentMessage,\n AgentReasoningEffort,\n AgentWebSocketServerMessage as AgentWebSocketServerMessageType,\n HitlResponse,\n QuestionResponse,\n ToolApprovalResponse,\n UserMessage\n} from '@yolk-sdk/agent/protocol'\nimport type { AgentTranscript } from './state.ts'\n\nexport class AgentTransportError extends Schema.TaggedErrorClass<AgentTransportError>()(\n 'AgentTransportError',\n {\n message: Schema.String,\n cause: Schema.Unknown\n }\n) {}\n\nexport type StreamAgentEventsRequest = {\n readonly endpoint?: string\n readonly sessionId: string\n readonly messages: AgentTranscript\n readonly hitlResponses?: ReadonlyArray<HitlResponse>\n readonly model?: string\n readonly reasoningEffort?: AgentReasoningEffort\n readonly signal?: AbortSignal\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>\n readonly onResponse?: (response: AgentHttpResponseInfo) => void\n}\n\nexport type StreamAgentRunEventsRequest = {\n readonly endpoint: string\n readonly startIndex?: number\n readonly signal?: AbortSignal\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>\n readonly onResponse?: (response: AgentHttpResponseInfo) => void\n}\n\nexport type StreamAgentRunHitlResponseEventsRequest = {\n readonly endpoint: string\n readonly hitlResponses: ReadonlyArray<HitlResponse>\n readonly signal?: AbortSignal\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>\n readonly onResponse?: (response: AgentHttpResponseInfo) => void\n}\n\nexport type StreamAgentEventHandler = (event: AgentEventType, count: number) => void\n\nexport type AgentRunContinuationOptions = {\n readonly continuationLimit?: number\n readonly onEvent?: StreamAgentEventHandler\n}\n\nexport type StreamAgentEventsUntilTerminalRequest = StreamAgentEventsRequest &\n AgentRunContinuationOptions & {\n readonly runEndpoint?: (runId: string) => string\n readonly onRunId?: (runId: string) => void\n }\n\nexport type StreamAgentRunEventsUntilTerminalRequest = StreamAgentRunEventsRequest &\n AgentRunContinuationOptions\n\nexport type StreamAgentRunHitlResponseEventsUntilTerminalRequest =\n StreamAgentRunHitlResponseEventsRequest & AgentRunContinuationOptions\n\nexport type CancelAgentRunRequest = {\n readonly endpoint: string\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>\n}\n\nexport type SubmitToolApprovalResponseRequest = StreamAgentEventsRequest & {\n readonly response: ToolApprovalResponse\n}\n\nexport type SubmitQuestionResponseRequest = StreamAgentEventsRequest & {\n readonly response: QuestionResponse\n}\n\nexport type AgentHttpResponseInfo = {\n readonly status: number\n readonly headers: Readonly<Record<string, string | undefined>>\n}\n\nexport type StreamCloudflareAgentEventsRequest = {\n readonly webSocketUrl: string\n readonly messages: AgentTranscript\n readonly hitlResponses?: ReadonlyArray<HitlResponse>\n readonly model?: string\n readonly reasoningEffort?: AgentReasoningEffort\n readonly signal?: AbortSignal\n}\n\nconst defaultEndpoint = '/api/agent'\nconst defaultRunContinuationLimit = 120\nconst relativeEndpointBase = 'http://yolk.local'\n\nconst headerValue = (headers: Readonly<Record<string, string | undefined>>, name: string) => {\n const direct = headers[name]\n\n if (direct !== undefined) {\n return direct\n }\n\n const normalizedName = name.toLowerCase()\n\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === normalizedName) {\n return value\n }\n }\n\n return undefined\n}\n\nconst nonEmptyHeaderValue = (\n headers: Readonly<Record<string, string | undefined>>,\n name: string\n) => {\n const value = headerValue(headers, name)?.trim()\n\n return value === undefined || value.length === 0 ? undefined : value\n}\n\nconst safeIntegerPattern = /^-?(0|[1-9]\\d*)$/\n\nconst parseSafeInteger = (raw: string) => {\n const value = raw.trim()\n\n if (!safeIntegerPattern.test(value)) {\n return undefined\n }\n\n const parsed = Number.parseInt(value, 10)\n\n return Number.isSafeInteger(parsed) ? parsed : undefined\n}\n\nexport const agentRunIdFromHeaders = (headers: Readonly<Record<string, string | undefined>>) =>\n nonEmptyHeaderValue(headers, 'x-workflow-run-id')\n\nexport const agentRunStreamTailIndexFromHeaders = (\n headers: Readonly<Record<string, string | undefined>>\n) => {\n const raw = nonEmptyHeaderValue(headers, 'x-workflow-stream-tail-index')\n if (raw === undefined) return undefined\n\n const parsed = parseSafeInteger(raw)\n\n return parsed !== undefined && parsed >= -1 ? parsed : undefined\n}\n\nexport const agentRunStreamStartIndexFromHeaders = (\n headers: Readonly<Record<string, string | undefined>>\n) => {\n const tailIndex = agentRunStreamTailIndexFromHeaders(headers)\n\n return tailIndex === undefined ? undefined : tailIndex + 1\n}\n\nexport const agentRunEndpointWithStartIndex = (endpoint: string, startIndex?: number) => {\n if (startIndex === undefined) return endpoint\n\n validateAgentRunStartIndex(startIndex)\n\n const parsed = parseEndpointOrThrow(endpoint)\n parsed.url.searchParams.set('startIndex', String(startIndex))\n\n return serializeEndpoint(parsed)\n}\n\ntype ParsedEndpoint = {\n readonly url: URL\n readonly absolute: boolean\n readonly leadingSlash: boolean\n}\n\nconst absoluteUrlPattern = /^[A-Za-z][A-Za-z\\d+.-]*:/\n\nconst parseEndpoint = (endpoint: string): ParsedEndpoint | undefined => {\n try {\n return {\n url: new URL(endpoint, relativeEndpointBase),\n absolute: absoluteUrlPattern.test(endpoint),\n leadingSlash: endpoint.startsWith('/')\n }\n } catch {\n return undefined\n }\n}\n\nconst parseEndpointOrThrow = (endpoint: string) => {\n const parsed = parseEndpoint(endpoint)\n\n if (parsed !== undefined) {\n return parsed\n }\n\n throw new AgentTransportError({\n message: 'Invalid agent run endpoint',\n cause: endpoint\n })\n}\n\nconst serializeEndpoint = (endpoint: ParsedEndpoint) => {\n if (endpoint.absolute) {\n return endpoint.url.toString()\n }\n\n const serialized = `${endpoint.url.pathname}${endpoint.url.search}${endpoint.url.hash}`\n\n return endpoint.leadingSlash ? serialized : serialized.slice(1)\n}\n\nconst appendEncodedPathSegment = (endpoint: string, segment: string) => {\n const parsed = parseEndpointOrThrow(endpoint)\n\n const basePath = parsed.url.pathname.endsWith('/')\n ? parsed.url.pathname.slice(0, -1)\n : parsed.url.pathname\n\n parsed.url.pathname = `${basePath}/${encodeURIComponent(segment)}`\n\n return serializeEndpoint(parsed)\n}\n\nconst defaultAgentRunEndpoint = (endpoint: string | undefined, runId: string) =>\n appendEncodedPathSegment(endpoint ?? defaultEndpoint, runId)\n\nconst agentRunContinuationLimit = (limit: number | undefined) => {\n if (limit === undefined) {\n return defaultRunContinuationLimit\n }\n\n if (!Number.isSafeInteger(limit) || limit < 0) {\n throw new AgentTransportError({\n message: 'Invalid agent run continuation limit',\n cause: limit\n })\n }\n\n return limit\n}\n\nconst validateAgentRunContinuationLimit = (limit: number | undefined) => {\n agentRunContinuationLimit(limit)\n}\n\nconst validateAgentRunStartIndex = (startIndex: number | undefined) => {\n if (startIndex === undefined || (Number.isSafeInteger(startIndex) && startIndex >= 0)) {\n return\n }\n\n throw new AgentTransportError({\n message: 'Invalid agent run stream start index',\n cause: startIndex\n })\n}\n\nconst nextAgentRunStartIndex = (startIndex: number | undefined, count: number) =>\n (startIndex ?? 0) + count\n\nconst unknownToMessage = (error: unknown) =>\n error instanceof Error ? error.message : String(error)\n\nconst toTransportError = (message: string, cause: unknown) =>\n new AgentTransportError({\n message,\n cause\n })\n\nconst toHttpClientTransportError = (message: string) => (error: HttpClientError.HttpClientError) =>\n toTransportError(`${message}: ${error.message}`, error)\n\nconst decodeAgentEvent = (value: unknown) =>\n Schema.decodeUnknownEffect(AgentEvent)(value).pipe(\n Effect.mapError(\n error =>\n new AgentTransportError({\n message: `Invalid agent event: ${unknownToMessage(error)}`,\n cause: error\n })\n )\n )\n\nconst decodeWebSocketServerMessage = (value: unknown) =>\n Schema.decodeUnknownEffect(AgentWebSocketServerMessage)(value).pipe(\n Effect.mapError(\n error =>\n new AgentTransportError({\n message: `Invalid agent WebSocket message: ${unknownToMessage(error)}`,\n cause: error\n })\n )\n )\n\nconst encodeJsonString = (value: unknown, message: string) =>\n Schema.encodeUnknownEffect(Schema.UnknownFromJsonString)(value).pipe(\n Effect.mapError(\n error =>\n new AgentTransportError({\n message: `${message}: ${unknownToMessage(error)}`,\n cause: error\n })\n )\n )\n\nconst decodeJsonString = (raw: string, message: string) =>\n Schema.decodeUnknownEffect(Schema.UnknownFromJsonString)(raw).pipe(\n Effect.mapError(\n error =>\n new AgentTransportError({\n message: `${message}: ${unknownToMessage(error)}`,\n cause: error\n })\n )\n )\n\nconst parseAgentEventLine = (line: string) =>\n Effect.gen(function* () {\n const parsed = yield* decodeJsonString(line, 'Invalid NDJSON line')\n\n return yield* decodeAgentEvent(parsed)\n })\n\nconst parseWebSocketServerMessage = (\n raw: string\n): Effect.Effect<AgentWebSocketServerMessageType, AgentTransportError> =>\n Effect.gen(function* () {\n const parsed = yield* decodeJsonString(raw, 'Invalid WebSocket message')\n\n return yield* decodeWebSocketServerMessage(parsed)\n })\n\nconst isUserMessage = (message: AgentMessage): message is UserMessage => message._tag === 'User'\n\nconst lastUserMessage = (\n messages: AgentTranscript\n): Effect.Effect<UserMessage, AgentTransportError> => {\n const reversed = messages.slice().reverse()\n const message = reversed.find(isUserMessage)\n\n if (message === undefined) {\n return Effect.fail(\n new AgentTransportError({\n message: 'Cloudflare WebSocket transport requires a user message',\n cause: messages\n })\n )\n }\n\n return Effect.succeed(message)\n}\n\nconst makeClientInputJson = (\n request: StreamCloudflareAgentEventsRequest,\n expectedRevision: number\n): Effect.Effect<string, AgentTransportError> =>\n Effect.gen(function* () {\n const hitlResponse = request.hitlResponses?.[0]\n\n if (request.hitlResponses !== undefined && request.hitlResponses.length > 1) {\n return yield* Effect.fail(\n new AgentTransportError({\n message: 'Cloudflare WebSocket transport supports one HITL response at a time',\n cause: request.hitlResponses\n })\n )\n }\n\n if (hitlResponse === undefined) {\n const message = yield* lastUserMessage(request.messages)\n\n return yield* encodeJsonString(\n UserInput.make({\n message,\n expectedRevision,\n model: request.model,\n reasoningEffort: request.reasoningEffort\n }),\n 'Could not serialize WebSocket user input'\n )\n }\n\n return yield* encodeJsonString(\n hitlResponse._tag === 'ToolApprovalResponse'\n ? ToolApprovalResponseInput.make({\n response: hitlResponse,\n expectedRevision,\n model: request.model,\n reasoningEffort: request.reasoningEffort\n })\n : QuestionResponseInput.make({\n response: hitlResponse,\n expectedRevision,\n model: request.model,\n reasoningEffort: request.reasoningEffort\n }),\n 'Could not serialize WebSocket HITL response'\n )\n })\n\nconst responseErrorMessage = (response: HttpClientResponse.HttpClientResponse) =>\n response.text.pipe(\n Effect.mapError(toHttpClientTransportError('Could not read agent error body')),\n Effect.map(text => (text.length > 0 ? text : `Request failed with ${response.status}`))\n )\n\nconst makeHttpRequest = (request: StreamAgentEventsRequest) =>\n encodeJsonString(\n {\n sessionId: request.sessionId,\n messages: request.messages,\n hitlResponses: request.hitlResponses,\n model: request.model,\n reasoningEffort: request.reasoningEffort\n },\n 'Could not serialize agent request'\n ).pipe(\n Effect.map(body =>\n HttpClientRequest.post(request.endpoint ?? defaultEndpoint).pipe(\n HttpClientRequest.setHeaders({\n accept: 'application/x-ndjson',\n 'content-type': 'application/json'\n }),\n HttpClientRequest.bodyText(body, 'application/json')\n )\n )\n )\n\nconst makeHttpRunHitlResponseRequest = (request: StreamAgentRunHitlResponseEventsRequest) =>\n encodeJsonString(\n { hitlResponses: request.hitlResponses },\n 'Could not serialize agent run HITL response'\n ).pipe(\n Effect.map(body =>\n HttpClientRequest.post(request.endpoint).pipe(\n HttpClientRequest.setHeaders({\n accept: 'application/x-ndjson',\n 'content-type': 'application/json'\n }),\n HttpClientRequest.bodyText(body, 'application/json')\n )\n )\n )\n\nconst requestAgentResponse = (request: StreamAgentEventsRequest) =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const httpRequest = yield* makeHttpRequest(request)\n const response = yield* client\n .execute(httpRequest)\n .pipe(Effect.mapError(toHttpClientTransportError('Agent request failed')))\n\n if (response.status >= 200 && response.status < 300) {\n yield* Effect.sync(() =>\n request.onResponse?.({ status: response.status, headers: response.headers })\n )\n return response\n }\n\n const message = yield* responseErrorMessage(response)\n\n return yield* Effect.fail(\n new AgentTransportError({\n message: `Agent request failed (${response.status}): ${message}`,\n cause: response.status\n })\n )\n })\n\nconst requestAgentRunResponse = (request: StreamAgentRunEventsRequest) =>\n Effect.gen(function* () {\n validateAgentRunStartIndex(request.startIndex)\n\n const client = yield* HttpClient.HttpClient\n const response = yield* client\n .execute(\n HttpClientRequest.get(\n agentRunEndpointWithStartIndex(request.endpoint, request.startIndex)\n ).pipe(HttpClientRequest.setHeaders({ accept: 'application/x-ndjson' }))\n )\n .pipe(Effect.mapError(toHttpClientTransportError('Agent run request failed')))\n\n if (response.status >= 200 && response.status < 300) {\n yield* Effect.sync(() =>\n request.onResponse?.({ status: response.status, headers: response.headers })\n )\n return response\n }\n\n const message = yield* responseErrorMessage(response)\n\n return yield* Effect.fail(\n new AgentTransportError({\n message: `Agent run request failed (${response.status}): ${message}`,\n cause: response.status\n })\n )\n })\n\nconst requestAgentRunHitlResponse = (request: StreamAgentRunHitlResponseEventsRequest) =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const httpRequest = yield* makeHttpRunHitlResponseRequest(request)\n const response = yield* client\n .execute(httpRequest)\n .pipe(Effect.mapError(toHttpClientTransportError('Agent run HITL request failed')))\n\n if (response.status >= 200 && response.status < 300) {\n yield* Effect.sync(() =>\n request.onResponse?.({ status: response.status, headers: response.headers })\n )\n return response\n }\n\n const message = yield* responseErrorMessage(response)\n\n return yield* Effect.fail(\n new AgentTransportError({\n message: `Agent run HITL request failed (${response.status}): ${message}`,\n cause: response.status\n })\n )\n })\n\nconst cancelAgentRunEffect = (request: CancelAgentRunRequest) =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const response = yield* client\n .execute(HttpClientRequest.delete(request.endpoint))\n .pipe(Effect.mapError(toHttpClientTransportError('Agent run cancel failed')))\n\n if (response.status >= 200 && response.status < 300) {\n return\n }\n\n const message = yield* responseErrorMessage(response)\n\n return yield* Effect.fail(\n new AgentTransportError({\n message: `Agent run cancel failed (${response.status}): ${message}`,\n cause: response.status\n })\n )\n }).pipe(Effect.provide(request.httpClientLayer ?? FetchHttpClient.layer))\n\nconst isTerminalAgentEvent = (event: AgentEventType) =>\n event._tag === 'AgentEnd' || event._tag === 'AgentError' || event._tag === 'AgentAwaitingInput'\n\nconst responseToLineStream = (response: HttpClientResponse.HttpClientResponse) =>\n response.stream.pipe(\n Stream.mapError(toHttpClientTransportError('Could not read agent response body')),\n Stream.decodeText,\n Stream.splitLines,\n Stream.map(line => line.trim()),\n Stream.filter(line => line.length > 0)\n )\n\nconst closeScope = (scope: Scope.Scope) => Scope.close(scope, Exit.succeed(undefined))\n\n// Protocol-terminal events finish the consumer stream, but HTTP bodies must still\n// drain to EOF so server runtimes do not observe client-side response aborts.\nconst responseToEventStream = (response: HttpClientResponse.HttpClientResponse) =>\n Stream.callback<AgentEventType, AgentTransportError>(queue =>\n Effect.gen(function* () {\n const callbackScope = yield* Scope.Scope\n // Own the response stream in a scope that can outlive the consumer after a\n // terminal event; before terminal, consumer cancellation closes it.\n const responseScope = yield* Scope.make()\n const responseScopeClosed = yield* Ref.make(false)\n const terminalReached = yield* Ref.make(false)\n const pull = yield* Channel.toPullScoped(\n Stream.toChannel(responseToLineStream(response)),\n responseScope\n )\n const closeResponseScope = Effect.gen(function* () {\n const closed = yield* Ref.get(responseScopeClosed)\n\n if (!closed) {\n yield* Ref.set(responseScopeClosed, true)\n yield* closeScope(responseScope)\n }\n })\n const endQueue = Queue.end(queue).pipe(Effect.asVoid)\n const failQueue = (cause: Cause.Cause<AgentTransportError>) =>\n Queue.failCause(queue, cause).pipe(Effect.andThen(closeResponseScope), Effect.asVoid)\n const drainResponse = (): Effect.Effect<void, AgentTransportError> =>\n Pull.matchEffect(pull, {\n onSuccess: () => drainResponse(),\n onFailure: cause => Effect.failCause(cause),\n onDone: () => Effect.void\n })\n const startTerminalDrain = Effect.gen(function* () {\n yield* Ref.set(terminalReached, true)\n yield* endQueue\n yield* drainResponse().pipe(\n Effect.catch(() => Effect.void),\n Effect.ensuring(closeResponseScope),\n Effect.forkDetach({ startImmediately: true }),\n Effect.asVoid\n )\n })\n const emitLines = (lines: ReadonlyArray<string>): Effect.Effect<void, AgentTransportError> =>\n Effect.gen(function* () {\n for (const line of lines) {\n const event = yield* parseAgentEventLine(line)\n\n yield* Queue.offer(queue, event)\n\n if (isTerminalAgentEvent(event)) {\n yield* startTerminalDrain\n return\n }\n }\n\n yield* run()\n })\n const run = (): Effect.Effect<void, AgentTransportError> =>\n Pull.matchEffect(pull, {\n onSuccess: emitLines,\n onFailure: failQueue,\n onDone: () => endQueue.pipe(Effect.andThen(closeResponseScope))\n })\n\n yield* Scope.addFinalizer(\n callbackScope,\n Effect.gen(function* () {\n const terminal = yield* Ref.get(terminalReached)\n\n if (!terminal) {\n yield* closeResponseScope\n }\n })\n )\n\n yield* run().pipe(\n Effect.catch(error => Queue.failCause(queue, Cause.fail(error)).pipe(Effect.asVoid))\n )\n })\n )\n\nconst abortSignalError = (signal: AbortSignal) =>\n new AgentTransportError({\n message: 'Agent request aborted',\n cause: signal.reason\n })\n\nconst abortSignalEffect = (signal: AbortSignal) =>\n Effect.callback<never, AgentTransportError>(resume => {\n if (signal.aborted) {\n resume(Effect.fail(abortSignalError(signal)))\n return Effect.void\n }\n\n const listener = () => resume(Effect.fail(abortSignalError(signal)))\n signal.addEventListener('abort', listener, { once: true })\n\n return Effect.sync(() => signal.removeEventListener('abort', listener))\n })\n\nconst applyAbortSignal = <A, E, R>(\n stream: Stream.Stream<A, E, R>,\n signal: AbortSignal | undefined\n) => (signal === undefined ? stream : stream.pipe(Stream.interruptWhen(abortSignalEffect(signal))))\n\nexport const streamAgentEventStream = (request: StreamAgentEventsRequest) =>\n applyAbortSignal(\n Stream.fromEffect(requestAgentResponse(request)).pipe(Stream.flatMap(responseToEventStream)),\n request.signal\n ).pipe(Stream.provide(request.httpClientLayer ?? FetchHttpClient.layer))\n\nexport const streamAgentRunEventStream = (request: StreamAgentRunEventsRequest) =>\n applyAbortSignal(\n Stream.fromEffect(requestAgentRunResponse(request)).pipe(Stream.flatMap(responseToEventStream)),\n request.signal\n ).pipe(Stream.provide(request.httpClientLayer ?? FetchHttpClient.layer))\n\nexport const streamAgentRunHitlResponseEventStream = (\n request: StreamAgentRunHitlResponseEventsRequest\n) =>\n applyAbortSignal(\n Stream.fromEffect(requestAgentRunHitlResponse(request)).pipe(\n Stream.flatMap(responseToEventStream)\n ),\n request.signal\n ).pipe(Stream.provide(request.httpClientLayer ?? FetchHttpClient.layer))\n\nexport const streamToolApprovalResponseEventStream = (request: SubmitToolApprovalResponseRequest) =>\n streamAgentEventStream({ ...request, hitlResponses: [request.response] })\n\nexport const streamQuestionResponseEventStream = (request: SubmitQuestionResponseRequest) =>\n streamAgentEventStream({ ...request, hitlResponses: [request.response] })\n\ntype AgentEventChunkResult = {\n readonly count: number\n readonly terminal: boolean\n}\n\ntype AgentRunContinuationInput = AgentRunContinuationOptions & {\n readonly endpoint: string | undefined\n readonly startIndex: number | undefined\n readonly countOffset: number\n readonly terminal: boolean\n readonly signal?: AbortSignal\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>\n readonly onResponse?: (response: AgentHttpResponseInfo) => void\n}\n\nconst missingAgentRunContinuationEndpointError = () =>\n new AgentTransportError({\n message: 'Agent run continuation failed: missing x-workflow-run-id',\n cause: 'missing_run_id'\n })\n\nconst exhaustedAgentRunContinuationLimitError = (limit: number) =>\n new AgentTransportError({\n message: 'Agent run continuation limit reached before a terminal event',\n cause: { limit }\n })\n\nconst noProgressAgentRunContinuationError = (endpoint: string, startIndex: number | undefined) =>\n new AgentTransportError({\n message: 'Agent run continuation made no progress before a terminal event',\n cause: { endpoint, startIndex }\n })\n\nconst missingAgentRunTailIndexError = () =>\n new AgentTransportError({\n message: 'Agent run HITL response missing x-workflow-stream-tail-index',\n cause: 'missing_tail_index'\n })\n\nconst streamAgentEventChunk = async function* (input: {\n readonly events: AsyncGenerator<AgentEventType, void, void>\n readonly countOffset: number\n readonly onEvent?: StreamAgentEventHandler\n}): AsyncGenerator<AgentEventType, AgentEventChunkResult, void> {\n let count = 0\n let terminal = false\n\n for await (const event of input.events) {\n count += 1\n terminal = terminal || isTerminalAgentEvent(event)\n input.onEvent?.(event, input.countOffset + count)\n yield event\n }\n\n return { count, terminal }\n}\n\nconst streamAgentRunContinuations = async function* (\n input: AgentRunContinuationInput\n): AsyncGenerator<AgentEventType, void, void> {\n let totalCount = input.countOffset\n let terminal = input.terminal\n let startIndex = input.startIndex\n const limit = agentRunContinuationLimit(input.continuationLimit)\n\n if (terminal) {\n return\n }\n\n if (input.endpoint === undefined) {\n throw missingAgentRunContinuationEndpointError()\n }\n\n for (let continuation = 0; continuation < limit; continuation += 1) {\n const endpoint = input.endpoint\n\n const chunk = yield* streamAgentEventChunk({\n events: streamAgentRunEvents({\n endpoint,\n startIndex,\n signal: input.signal,\n httpClientLayer: input.httpClientLayer,\n onResponse: input.onResponse\n }),\n countOffset: totalCount,\n onEvent: input.onEvent\n })\n\n if (chunk.count === 0 && !chunk.terminal) {\n throw noProgressAgentRunContinuationError(endpoint, startIndex)\n }\n\n terminal = chunk.terminal\n startIndex = nextAgentRunStartIndex(startIndex, chunk.count)\n totalCount += chunk.count\n\n if (terminal) {\n return\n }\n }\n\n throw exhaustedAgentRunContinuationLimitError(limit)\n}\n\nexport async function* streamAgentEventsUntilTerminal(\n request: StreamAgentEventsUntilTerminalRequest\n): AsyncGenerator<AgentEventType, void, void> {\n validateAgentRunContinuationLimit(request.continuationLimit)\n\n let runEndpoint: string | undefined\n let startIndex: number | undefined\n\n const firstChunk = yield* streamAgentEventChunk({\n events: streamAgentEvents({\n ...request,\n onResponse: response => {\n startIndex = agentRunStreamStartIndexFromHeaders(response.headers)\n const runId = agentRunIdFromHeaders(response.headers)\n if (runId !== undefined) {\n runEndpoint =\n request.runEndpoint?.(runId) ?? defaultAgentRunEndpoint(request.endpoint, runId)\n request.onRunId?.(runId)\n }\n\n request.onResponse?.(response)\n }\n }),\n countOffset: 0,\n onEvent: request.onEvent\n })\n\n yield* streamAgentRunContinuations({\n endpoint: runEndpoint,\n startIndex: nextAgentRunStartIndex(startIndex, firstChunk.count),\n countOffset: firstChunk.count,\n terminal: firstChunk.terminal,\n continuationLimit: request.continuationLimit,\n signal: request.signal,\n httpClientLayer: request.httpClientLayer,\n onResponse: request.onResponse,\n onEvent: request.onEvent\n })\n}\n\nexport async function* streamAgentRunEventsUntilTerminal(\n request: StreamAgentRunEventsUntilTerminalRequest\n): AsyncGenerator<AgentEventType, void, void> {\n validateAgentRunContinuationLimit(request.continuationLimit)\n\n const firstChunk = yield* streamAgentEventChunk({\n events: streamAgentRunEvents(request),\n countOffset: 0,\n onEvent: request.onEvent\n })\n\n yield* streamAgentRunContinuations({\n endpoint: request.endpoint,\n startIndex: nextAgentRunStartIndex(request.startIndex, firstChunk.count),\n countOffset: firstChunk.count,\n terminal: firstChunk.terminal,\n continuationLimit: request.continuationLimit,\n signal: request.signal,\n httpClientLayer: request.httpClientLayer,\n onResponse: request.onResponse,\n onEvent: request.onEvent\n })\n}\n\nexport async function* streamAgentRunHitlResponseEventsUntilTerminal(\n request: StreamAgentRunHitlResponseEventsUntilTerminalRequest\n): AsyncGenerator<AgentEventType, void, void> {\n validateAgentRunContinuationLimit(request.continuationLimit)\n\n let startIndex: number | undefined\n\n const firstChunk = yield* streamAgentEventChunk({\n events: streamAgentRunHitlResponseEvents({\n ...request,\n onResponse: response => {\n startIndex = agentRunStreamStartIndexFromHeaders(response.headers)\n request.onResponse?.(response)\n }\n }),\n countOffset: 0,\n onEvent: request.onEvent\n })\n\n if (!firstChunk.terminal && startIndex === undefined) {\n throw missingAgentRunTailIndexError()\n }\n\n yield* streamAgentRunContinuations({\n endpoint: request.endpoint,\n startIndex: nextAgentRunStartIndex(startIndex, firstChunk.count),\n countOffset: firstChunk.count,\n terminal: firstChunk.terminal,\n continuationLimit: request.continuationLimit,\n signal: request.signal,\n httpClientLayer: request.httpClientLayer,\n onResponse: request.onResponse,\n onEvent: request.onEvent\n })\n}\n\nconst isAgentEvent = (message: AgentWebSocketServerMessageType): message is AgentEventType =>\n message._tag !== 'SessionSnapshot'\n\nexport const streamCloudflareAgentEventStream = (request: StreamCloudflareAgentEventsRequest) =>\n applyAbortSignal(\n Stream.callback<AgentEventType, AgentTransportError>(queue =>\n Effect.gen(function* () {\n const socket = new WebSocket(request.webSocketUrl)\n let sentInput = false\n let settled = false\n const closeSocket = Effect.sync(() => {\n if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) {\n socket.close(1000, 'done')\n }\n })\n const failQueue = (error: AgentTransportError) =>\n Queue.failCauseUnsafe(queue, Cause.fail(error))\n const endQueue = () => Queue.endUnsafe(queue)\n const handleMessage = (event: MessageEvent) => {\n if (typeof event.data !== 'string') {\n failQueue(toTransportError('Agent WebSocket returned binary data', event.data))\n return\n }\n\n Effect.runFork(\n parseWebSocketServerMessage(event.data).pipe(\n Effect.flatMap(message => {\n if (message._tag === 'SessionSnapshot') {\n return sentInput\n ? Effect.void\n : makeClientInputJson(request, message.revision).pipe(\n Effect.flatMap(body => Effect.sync(() => socket.send(body))),\n Effect.tap(() =>\n Effect.sync(() => {\n sentInput = true\n })\n )\n )\n }\n\n if (!isAgentEvent(message)) {\n return Effect.void\n }\n\n return Effect.sync(() => {\n Queue.offerUnsafe(queue, message)\n if (\n message._tag === 'AgentEnd' ||\n message._tag === 'AgentError' ||\n message._tag === 'AgentAwaitingInput'\n ) {\n settled = true\n endQueue()\n socket.close(1000, 'done')\n }\n })\n }),\n Effect.catch(error => Effect.sync(() => failQueue(error)))\n )\n )\n }\n const handleError = () => {\n failQueue(toTransportError('Agent WebSocket failed', request.webSocketUrl))\n }\n const handleClose = () => {\n if (!settled) {\n failQueue(toTransportError('Agent WebSocket closed', request.webSocketUrl))\n }\n }\n\n yield* Effect.acquireRelease(\n Effect.sync(() => {\n socket.addEventListener('message', handleMessage)\n socket.addEventListener('error', handleError)\n socket.addEventListener('close', handleClose)\n }),\n () =>\n Effect.sync(() => {\n socket.removeEventListener('message', handleMessage)\n socket.removeEventListener('error', handleError)\n socket.removeEventListener('close', handleClose)\n }).pipe(Effect.andThen(closeSocket))\n )\n })\n ),\n request.signal\n )\n\nexport async function* streamCloudflareAgentEvents(\n request: StreamCloudflareAgentEventsRequest\n): AsyncGenerator<AgentEventType, void, void> {\n for await (const event of Stream.toAsyncIterable(streamCloudflareAgentEventStream(request))) {\n yield event\n }\n}\n\nexport async function* streamAgentEvents(\n request: StreamAgentEventsRequest\n): AsyncGenerator<AgentEventType, void, void> {\n for await (const event of Stream.toAsyncIterable(streamAgentEventStream(request))) {\n yield event\n }\n}\n\nexport async function* streamAgentRunEvents(\n request: StreamAgentRunEventsRequest\n): AsyncGenerator<AgentEventType, void, void> {\n for await (const event of Stream.toAsyncIterable(streamAgentRunEventStream(request))) {\n yield event\n }\n}\n\nexport async function* streamAgentRunHitlResponseEvents(\n request: StreamAgentRunHitlResponseEventsRequest\n): AsyncGenerator<AgentEventType, void, void> {\n for await (const event of Stream.toAsyncIterable(\n streamAgentRunHitlResponseEventStream(request)\n )) {\n yield event\n }\n}\n\nexport async function* submitToolApprovalResponse(\n request: SubmitToolApprovalResponseRequest\n): AsyncGenerator<AgentEventType, void, void> {\n for await (const event of Stream.toAsyncIterable(\n streamToolApprovalResponseEventStream(request)\n )) {\n yield event\n }\n}\n\nexport async function* submitQuestionResponse(\n request: SubmitQuestionResponseRequest\n): AsyncGenerator<AgentEventType, void, void> {\n for await (const event of Stream.toAsyncIterable(streamQuestionResponseEventStream(request))) {\n yield event\n }\n}\n\nexport const cancelAgentRun = (request: CancelAgentRunRequest) =>\n Effect.runPromise(cancelAgentRunEffect(request))\n\nexport const collectAgentEventsEffect = (request: StreamAgentEventsRequest) =>\n streamAgentEventStream(request).pipe(Stream.runCollect)\n\nexport const collectAgentEvents = async (request: StreamAgentEventsRequest) =>\n Array.from(await Effect.runPromise(collectAgentEventsEffect(request)))\n"],"mappings":";;;;;AA4BA,IAAa,sBAAb,cAAyC,OAAO,iBAAsC,EACpF,uBACA;CACE,SAAS,OAAO;CAChB,OAAO,OAAO;AAChB,CACF,EAAE,CAAC;AA4EH,MAAM,kBAAkB;AACxB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rB,SAC4C;CAC5C,WAAW,MAAM,SAAS,OAAO,gBAAgB,kCAAkC,OAAO,CAAC,GACzF,MAAM;AAEV;AAEA,MAAa,kBAAkB,YAC7B,OAAO,WAAW,qBAAqB,OAAO,CAAC;AAEjD,MAAa,4BAA4B,YACvC,uBAAuB,OAAO,EAAE,KAAK,OAAO,UAAU;AAExD,MAAa,qBAAqB,OAAO,YACvC,MAAM,KAAK,MAAM,OAAO,WAAW,yBAAyB,OAAO,CAAC,CAAC"}
|
|
1
|
+
{"version":3,"file":"transport.mjs","names":[],"sources":["../../src/client/transport.ts"],"sourcesContent":["import { Cause, Channel, Effect, Exit, Pull, Queue, Ref, Scope, Stream, type Layer } from 'effect'\nimport {\n FetchHttpClient,\n HttpClient,\n HttpClientRequest,\n type HttpClientError,\n type HttpClientResponse\n} from 'effect/unstable/http'\nimport * as Schema from 'effect/Schema'\nimport {\n AgentEvent,\n AgentWebSocketServerMessage,\n QuestionResponseInput,\n ToolApprovalResponseInput,\n UserInput,\n isTerminalAgentEvent\n} from '@yolk-sdk/agent/protocol'\nimport type {\n AgentEvent as AgentEventType,\n AgentMessage,\n AgentReasoningEffort,\n AgentWebSocketServerMessage as AgentWebSocketServerMessageType,\n HitlResponse,\n QuestionResponse,\n ToolApprovalResponse,\n UserMessage\n} from '@yolk-sdk/agent/protocol'\nimport type { AgentTranscript } from './state.ts'\n\nexport class AgentTransportError extends Schema.TaggedErrorClass<AgentTransportError>()(\n 'AgentTransportError',\n {\n message: Schema.String,\n cause: Schema.Unknown\n }\n) {}\n\nexport type StreamAgentEventsRequest = {\n readonly endpoint?: string\n readonly sessionId: string\n readonly messages: AgentTranscript\n readonly hitlResponses?: ReadonlyArray<HitlResponse>\n readonly model?: string\n readonly reasoningEffort?: AgentReasoningEffort\n readonly signal?: AbortSignal\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>\n readonly onResponse?: (response: AgentHttpResponseInfo) => void\n}\n\nexport type StreamAgentRunEventsRequest = {\n readonly endpoint: string\n readonly startIndex?: number\n readonly signal?: AbortSignal\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>\n readonly onResponse?: (response: AgentHttpResponseInfo) => void\n}\n\nexport type StreamAgentRunHitlResponseEventsRequest = {\n readonly endpoint: string\n readonly hitlResponses: ReadonlyArray<HitlResponse>\n readonly signal?: AbortSignal\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>\n readonly onResponse?: (response: AgentHttpResponseInfo) => void\n}\n\nexport type StreamAgentEventHandler = (event: AgentEventType, count: number) => void\n\nexport type AgentRunContinuationOptions = {\n readonly continuationLimit?: number\n readonly onEvent?: StreamAgentEventHandler\n}\n\nexport type StreamAgentEventsUntilTerminalRequest = StreamAgentEventsRequest &\n AgentRunContinuationOptions & {\n readonly runEndpoint?: (runId: string) => string\n readonly onRunId?: (runId: string) => void\n }\n\nexport type StreamAgentRunEventsUntilTerminalRequest = StreamAgentRunEventsRequest &\n AgentRunContinuationOptions\n\nexport type StreamAgentRunHitlResponseEventsUntilTerminalRequest =\n StreamAgentRunHitlResponseEventsRequest & AgentRunContinuationOptions\n\nexport type CancelAgentRunRequest = {\n readonly endpoint: string\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>\n}\n\nexport type SubmitToolApprovalResponseRequest = StreamAgentEventsRequest & {\n readonly response: ToolApprovalResponse\n}\n\nexport type SubmitQuestionResponseRequest = StreamAgentEventsRequest & {\n readonly response: QuestionResponse\n}\n\nexport type AgentHttpResponseInfo = {\n readonly status: number\n readonly headers: Readonly<Record<string, string | undefined>>\n}\n\nexport type StreamCloudflareAgentEventsRequest = {\n readonly webSocketUrl: string\n readonly messages: AgentTranscript\n readonly hitlResponses?: ReadonlyArray<HitlResponse>\n readonly model?: string\n readonly reasoningEffort?: AgentReasoningEffort\n readonly signal?: AbortSignal\n}\n\nconst defaultEndpoint = '/api/agent'\nconst defaultRunContinuationLimit = 120\nconst relativeEndpointBase = 'http://yolk.local'\n\nconst headerValue = (headers: Readonly<Record<string, string | undefined>>, name: string) => {\n const direct = headers[name]\n\n if (direct !== undefined) {\n return direct\n }\n\n const normalizedName = name.toLowerCase()\n\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === normalizedName) {\n return value\n }\n }\n\n return undefined\n}\n\nconst nonEmptyHeaderValue = (\n headers: Readonly<Record<string, string | undefined>>,\n name: string\n) => {\n const value = headerValue(headers, name)?.trim()\n\n return value === undefined || value.length === 0 ? undefined : value\n}\n\nconst safeIntegerPattern = /^-?(0|[1-9]\\d*)$/\n\nconst parseSafeInteger = (raw: string) => {\n const value = raw.trim()\n\n if (!safeIntegerPattern.test(value)) {\n return undefined\n }\n\n const parsed = Number.parseInt(value, 10)\n\n return Number.isSafeInteger(parsed) ? parsed : undefined\n}\n\nexport const agentRunIdFromHeaders = (headers: Readonly<Record<string, string | undefined>>) =>\n nonEmptyHeaderValue(headers, 'x-workflow-run-id')\n\nexport const agentRunStreamTailIndexFromHeaders = (\n headers: Readonly<Record<string, string | undefined>>\n) => {\n const raw = nonEmptyHeaderValue(headers, 'x-workflow-stream-tail-index')\n if (raw === undefined) return undefined\n\n const parsed = parseSafeInteger(raw)\n\n return parsed !== undefined && parsed >= -1 ? parsed : undefined\n}\n\nexport const agentRunStreamStartIndexFromHeaders = (\n headers: Readonly<Record<string, string | undefined>>\n) => {\n const tailIndex = agentRunStreamTailIndexFromHeaders(headers)\n\n return tailIndex === undefined ? undefined : tailIndex + 1\n}\n\nexport const agentRunEndpointWithStartIndex = (endpoint: string, startIndex?: number) => {\n if (startIndex === undefined) return endpoint\n\n validateAgentRunStartIndex(startIndex)\n\n const parsed = parseEndpointOrThrow(endpoint)\n parsed.url.searchParams.set('startIndex', String(startIndex))\n\n return serializeEndpoint(parsed)\n}\n\ntype ParsedEndpoint = {\n readonly url: URL\n readonly absolute: boolean\n readonly leadingSlash: boolean\n}\n\nconst absoluteUrlPattern = /^[A-Za-z][A-Za-z\\d+.-]*:/\n\nconst parseEndpoint = (endpoint: string): ParsedEndpoint | undefined => {\n try {\n return {\n url: new URL(endpoint, relativeEndpointBase),\n absolute: absoluteUrlPattern.test(endpoint),\n leadingSlash: endpoint.startsWith('/')\n }\n } catch {\n return undefined\n }\n}\n\nconst parseEndpointOrThrow = (endpoint: string) => {\n const parsed = parseEndpoint(endpoint)\n\n if (parsed !== undefined) {\n return parsed\n }\n\n throw new AgentTransportError({\n message: 'Invalid agent run endpoint',\n cause: endpoint\n })\n}\n\nconst serializeEndpoint = (endpoint: ParsedEndpoint) => {\n if (endpoint.absolute) {\n return endpoint.url.toString()\n }\n\n const serialized = `${endpoint.url.pathname}${endpoint.url.search}${endpoint.url.hash}`\n\n return endpoint.leadingSlash ? serialized : serialized.slice(1)\n}\n\nconst appendEncodedPathSegment = (endpoint: string, segment: string) => {\n const parsed = parseEndpointOrThrow(endpoint)\n\n const basePath = parsed.url.pathname.endsWith('/')\n ? parsed.url.pathname.slice(0, -1)\n : parsed.url.pathname\n\n parsed.url.pathname = `${basePath}/${encodeURIComponent(segment)}`\n\n return serializeEndpoint(parsed)\n}\n\nconst defaultAgentRunEndpoint = (endpoint: string | undefined, runId: string) =>\n appendEncodedPathSegment(endpoint ?? defaultEndpoint, runId)\n\nconst agentRunContinuationLimit = (limit: number | undefined) => {\n if (limit === undefined) {\n return defaultRunContinuationLimit\n }\n\n if (!Number.isSafeInteger(limit) || limit < 0) {\n throw new AgentTransportError({\n message: 'Invalid agent run continuation limit',\n cause: limit\n })\n }\n\n return limit\n}\n\nconst validateAgentRunContinuationLimit = (limit: number | undefined) => {\n agentRunContinuationLimit(limit)\n}\n\nconst validateAgentRunStartIndex = (startIndex: number | undefined) => {\n if (startIndex === undefined || (Number.isSafeInteger(startIndex) && startIndex >= 0)) {\n return\n }\n\n throw new AgentTransportError({\n message: 'Invalid agent run stream start index',\n cause: startIndex\n })\n}\n\nconst nextAgentRunStartIndex = (startIndex: number | undefined, count: number) =>\n (startIndex ?? 0) + count\n\nconst unknownToMessage = (error: unknown) =>\n error instanceof Error ? error.message : String(error)\n\nconst toTransportError = (message: string, cause: unknown) =>\n new AgentTransportError({\n message,\n cause\n })\n\nconst toHttpClientTransportError = (message: string) => (error: HttpClientError.HttpClientError) =>\n toTransportError(`${message}: ${error.message}`, error)\n\nconst decodeAgentEvent = (value: unknown) =>\n Schema.decodeUnknownEffect(AgentEvent)(value).pipe(\n Effect.mapError(\n error =>\n new AgentTransportError({\n message: `Invalid agent event: ${unknownToMessage(error)}`,\n cause: error\n })\n )\n )\n\nconst decodeWebSocketServerMessage = (value: unknown) =>\n Schema.decodeUnknownEffect(AgentWebSocketServerMessage)(value).pipe(\n Effect.mapError(\n error =>\n new AgentTransportError({\n message: `Invalid agent WebSocket message: ${unknownToMessage(error)}`,\n cause: error\n })\n )\n )\n\nconst encodeJsonString = (value: unknown, message: string) =>\n Schema.encodeUnknownEffect(Schema.UnknownFromJsonString)(value).pipe(\n Effect.mapError(\n error =>\n new AgentTransportError({\n message: `${message}: ${unknownToMessage(error)}`,\n cause: error\n })\n )\n )\n\nconst decodeJsonString = (raw: string, message: string) =>\n Schema.decodeUnknownEffect(Schema.UnknownFromJsonString)(raw).pipe(\n Effect.mapError(\n error =>\n new AgentTransportError({\n message: `${message}: ${unknownToMessage(error)}`,\n cause: error\n })\n )\n )\n\nconst parseAgentEventLine = (line: string) =>\n Effect.gen(function* () {\n const parsed = yield* decodeJsonString(line, 'Invalid NDJSON line')\n\n return yield* decodeAgentEvent(parsed)\n })\n\nconst parseWebSocketServerMessage = (\n raw: string\n): Effect.Effect<AgentWebSocketServerMessageType, AgentTransportError> =>\n Effect.gen(function* () {\n const parsed = yield* decodeJsonString(raw, 'Invalid WebSocket message')\n\n return yield* decodeWebSocketServerMessage(parsed)\n })\n\nconst isUserMessage = (message: AgentMessage): message is UserMessage => message._tag === 'User'\n\nconst lastUserMessage = (\n messages: AgentTranscript\n): Effect.Effect<UserMessage, AgentTransportError> => {\n const reversed = messages.slice().reverse()\n const message = reversed.find(isUserMessage)\n\n if (message === undefined) {\n return Effect.fail(\n new AgentTransportError({\n message: 'Cloudflare WebSocket transport requires a user message',\n cause: messages\n })\n )\n }\n\n return Effect.succeed(message)\n}\n\nconst makeClientInputJson = (\n request: StreamCloudflareAgentEventsRequest,\n expectedRevision: number\n): Effect.Effect<string, AgentTransportError> =>\n Effect.gen(function* () {\n const hitlResponse = request.hitlResponses?.[0]\n\n if (request.hitlResponses !== undefined && request.hitlResponses.length > 1) {\n return yield* Effect.fail(\n new AgentTransportError({\n message: 'Cloudflare WebSocket transport supports one HITL response at a time',\n cause: request.hitlResponses\n })\n )\n }\n\n if (hitlResponse === undefined) {\n const message = yield* lastUserMessage(request.messages)\n\n return yield* encodeJsonString(\n UserInput.make({\n message,\n expectedRevision,\n model: request.model,\n reasoningEffort: request.reasoningEffort\n }),\n 'Could not serialize WebSocket user input'\n )\n }\n\n return yield* encodeJsonString(\n hitlResponse._tag === 'ToolApprovalResponse'\n ? ToolApprovalResponseInput.make({\n response: hitlResponse,\n expectedRevision,\n model: request.model,\n reasoningEffort: request.reasoningEffort\n })\n : QuestionResponseInput.make({\n response: hitlResponse,\n expectedRevision,\n model: request.model,\n reasoningEffort: request.reasoningEffort\n }),\n 'Could not serialize WebSocket HITL response'\n )\n })\n\nconst responseErrorMessage = (response: HttpClientResponse.HttpClientResponse) =>\n response.text.pipe(\n Effect.mapError(toHttpClientTransportError('Could not read agent error body')),\n Effect.map(text => (text.length > 0 ? text : `Request failed with ${response.status}`))\n )\n\nconst makeHttpRequest = (request: StreamAgentEventsRequest) =>\n encodeJsonString(\n {\n sessionId: request.sessionId,\n messages: request.messages,\n hitlResponses: request.hitlResponses,\n model: request.model,\n reasoningEffort: request.reasoningEffort\n },\n 'Could not serialize agent request'\n ).pipe(\n Effect.map(body =>\n HttpClientRequest.post(request.endpoint ?? defaultEndpoint).pipe(\n HttpClientRequest.setHeaders({\n accept: 'application/x-ndjson',\n 'content-type': 'application/json'\n }),\n HttpClientRequest.bodyText(body, 'application/json')\n )\n )\n )\n\nconst makeHttpRunHitlResponseRequest = (request: StreamAgentRunHitlResponseEventsRequest) =>\n encodeJsonString(\n { hitlResponses: request.hitlResponses },\n 'Could not serialize agent run HITL response'\n ).pipe(\n Effect.map(body =>\n HttpClientRequest.post(request.endpoint).pipe(\n HttpClientRequest.setHeaders({\n accept: 'application/x-ndjson',\n 'content-type': 'application/json'\n }),\n HttpClientRequest.bodyText(body, 'application/json')\n )\n )\n )\n\nconst requestAgentResponse = (request: StreamAgentEventsRequest) =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const httpRequest = yield* makeHttpRequest(request)\n const response = yield* client\n .execute(httpRequest)\n .pipe(Effect.mapError(toHttpClientTransportError('Agent request failed')))\n\n if (response.status >= 200 && response.status < 300) {\n yield* Effect.sync(() =>\n request.onResponse?.({ status: response.status, headers: response.headers })\n )\n return response\n }\n\n const message = yield* responseErrorMessage(response)\n\n return yield* Effect.fail(\n new AgentTransportError({\n message: `Agent request failed (${response.status}): ${message}`,\n cause: response.status\n })\n )\n })\n\nconst requestAgentRunResponse = (request: StreamAgentRunEventsRequest) =>\n Effect.gen(function* () {\n validateAgentRunStartIndex(request.startIndex)\n\n const client = yield* HttpClient.HttpClient\n const response = yield* client\n .execute(\n HttpClientRequest.get(\n agentRunEndpointWithStartIndex(request.endpoint, request.startIndex)\n ).pipe(HttpClientRequest.setHeaders({ accept: 'application/x-ndjson' }))\n )\n .pipe(Effect.mapError(toHttpClientTransportError('Agent run request failed')))\n\n if (response.status >= 200 && response.status < 300) {\n yield* Effect.sync(() =>\n request.onResponse?.({ status: response.status, headers: response.headers })\n )\n return response\n }\n\n const message = yield* responseErrorMessage(response)\n\n return yield* Effect.fail(\n new AgentTransportError({\n message: `Agent run request failed (${response.status}): ${message}`,\n cause: response.status\n })\n )\n })\n\nconst requestAgentRunHitlResponse = (request: StreamAgentRunHitlResponseEventsRequest) =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const httpRequest = yield* makeHttpRunHitlResponseRequest(request)\n const response = yield* client\n .execute(httpRequest)\n .pipe(Effect.mapError(toHttpClientTransportError('Agent run HITL request failed')))\n\n if (response.status >= 200 && response.status < 300) {\n yield* Effect.sync(() =>\n request.onResponse?.({ status: response.status, headers: response.headers })\n )\n return response\n }\n\n const message = yield* responseErrorMessage(response)\n\n return yield* Effect.fail(\n new AgentTransportError({\n message: `Agent run HITL request failed (${response.status}): ${message}`,\n cause: response.status\n })\n )\n })\n\nconst cancelAgentRunEffect = (request: CancelAgentRunRequest) =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const response = yield* client\n .execute(HttpClientRequest.delete(request.endpoint))\n .pipe(Effect.mapError(toHttpClientTransportError('Agent run cancel failed')))\n\n if (response.status >= 200 && response.status < 300) {\n return\n }\n\n const message = yield* responseErrorMessage(response)\n\n return yield* Effect.fail(\n new AgentTransportError({\n message: `Agent run cancel failed (${response.status}): ${message}`,\n cause: response.status\n })\n )\n }).pipe(Effect.provide(request.httpClientLayer ?? FetchHttpClient.layer))\n\nconst responseToLineStream = (response: HttpClientResponse.HttpClientResponse) =>\n response.stream.pipe(\n Stream.mapError(toHttpClientTransportError('Could not read agent response body')),\n Stream.decodeText,\n Stream.splitLines,\n Stream.map(line => line.trim()),\n Stream.filter(line => line.length > 0)\n )\n\nconst closeScope = (scope: Scope.Scope) => Scope.close(scope, Exit.succeed(undefined))\n\n// Protocol-terminal events finish the consumer stream, but HTTP bodies must still\n// drain to EOF so server runtimes do not observe client-side response aborts.\nconst responseToEventStream = (response: HttpClientResponse.HttpClientResponse) =>\n Stream.callback<AgentEventType, AgentTransportError>(queue =>\n Effect.gen(function* () {\n const callbackScope = yield* Scope.Scope\n // Own the response stream in a scope that can outlive the consumer after a\n // terminal event; before terminal, consumer cancellation closes it.\n const responseScope = yield* Scope.make()\n const responseScopeClosed = yield* Ref.make(false)\n const terminalReached = yield* Ref.make(false)\n const pull = yield* Channel.toPullScoped(\n Stream.toChannel(responseToLineStream(response)),\n responseScope\n )\n const closeResponseScope = Effect.gen(function* () {\n const closed = yield* Ref.get(responseScopeClosed)\n\n if (!closed) {\n yield* Ref.set(responseScopeClosed, true)\n yield* closeScope(responseScope)\n }\n })\n const endQueue = Queue.end(queue).pipe(Effect.asVoid)\n const failQueue = (cause: Cause.Cause<AgentTransportError>) =>\n Queue.failCause(queue, cause).pipe(Effect.andThen(closeResponseScope), Effect.asVoid)\n const drainResponse = (): Effect.Effect<void, AgentTransportError> =>\n Pull.matchEffect(pull, {\n onSuccess: () => drainResponse(),\n onFailure: cause => Effect.failCause(cause),\n onDone: () => Effect.void\n })\n const startTerminalDrain = Effect.gen(function* () {\n yield* Ref.set(terminalReached, true)\n yield* endQueue\n yield* drainResponse().pipe(\n Effect.catch(() => Effect.void),\n Effect.ensuring(closeResponseScope),\n Effect.forkDetach({ startImmediately: true }),\n Effect.asVoid\n )\n })\n const emitLines = (lines: ReadonlyArray<string>): Effect.Effect<void, AgentTransportError> =>\n Effect.gen(function* () {\n for (const line of lines) {\n const event = yield* parseAgentEventLine(line)\n\n yield* Queue.offer(queue, event)\n\n if (isTerminalAgentEvent(event)) {\n yield* startTerminalDrain\n return\n }\n }\n\n yield* run()\n })\n const run = (): Effect.Effect<void, AgentTransportError> =>\n Pull.matchEffect(pull, {\n onSuccess: emitLines,\n onFailure: failQueue,\n onDone: () => endQueue.pipe(Effect.andThen(closeResponseScope))\n })\n\n yield* Scope.addFinalizer(\n callbackScope,\n Effect.gen(function* () {\n const terminal = yield* Ref.get(terminalReached)\n\n if (!terminal) {\n yield* closeResponseScope\n }\n })\n )\n\n yield* run().pipe(\n Effect.catch(error => Queue.failCause(queue, Cause.fail(error)).pipe(Effect.asVoid))\n )\n })\n )\n\nconst abortSignalError = (signal: AbortSignal) =>\n new AgentTransportError({\n message: 'Agent request aborted',\n cause: signal.reason\n })\n\nconst abortSignalEffect = (signal: AbortSignal) =>\n Effect.callback<never, AgentTransportError>(resume => {\n if (signal.aborted) {\n resume(Effect.fail(abortSignalError(signal)))\n return Effect.void\n }\n\n const listener = () => resume(Effect.fail(abortSignalError(signal)))\n signal.addEventListener('abort', listener, { once: true })\n\n return Effect.sync(() => signal.removeEventListener('abort', listener))\n })\n\nconst applyAbortSignal = <A, E, R>(\n stream: Stream.Stream<A, E, R>,\n signal: AbortSignal | undefined\n) => (signal === undefined ? stream : stream.pipe(Stream.interruptWhen(abortSignalEffect(signal))))\n\nexport const streamAgentEventStream = (request: StreamAgentEventsRequest) =>\n applyAbortSignal(\n Stream.fromEffect(requestAgentResponse(request)).pipe(Stream.flatMap(responseToEventStream)),\n request.signal\n ).pipe(Stream.provide(request.httpClientLayer ?? FetchHttpClient.layer))\n\nexport const streamAgentRunEventStream = (request: StreamAgentRunEventsRequest) =>\n applyAbortSignal(\n Stream.fromEffect(requestAgentRunResponse(request)).pipe(Stream.flatMap(responseToEventStream)),\n request.signal\n ).pipe(Stream.provide(request.httpClientLayer ?? FetchHttpClient.layer))\n\nexport const streamAgentRunHitlResponseEventStream = (\n request: StreamAgentRunHitlResponseEventsRequest\n) =>\n applyAbortSignal(\n Stream.fromEffect(requestAgentRunHitlResponse(request)).pipe(\n Stream.flatMap(responseToEventStream)\n ),\n request.signal\n ).pipe(Stream.provide(request.httpClientLayer ?? FetchHttpClient.layer))\n\nexport const streamToolApprovalResponseEventStream = (request: SubmitToolApprovalResponseRequest) =>\n streamAgentEventStream({ ...request, hitlResponses: [request.response] })\n\nexport const streamQuestionResponseEventStream = (request: SubmitQuestionResponseRequest) =>\n streamAgentEventStream({ ...request, hitlResponses: [request.response] })\n\ntype AgentEventChunkResult = {\n readonly count: number\n readonly terminal: boolean\n}\n\ntype AgentRunContinuationInput = AgentRunContinuationOptions & {\n readonly endpoint: string | undefined\n readonly startIndex: number | undefined\n readonly countOffset: number\n readonly terminal: boolean\n readonly signal?: AbortSignal\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>\n readonly onResponse?: (response: AgentHttpResponseInfo) => void\n}\n\nconst missingAgentRunContinuationEndpointError = () =>\n new AgentTransportError({\n message: 'Agent run continuation failed: missing x-workflow-run-id',\n cause: 'missing_run_id'\n })\n\nconst exhaustedAgentRunContinuationLimitError = (limit: number) =>\n new AgentTransportError({\n message: 'Agent run continuation limit reached before a terminal event',\n cause: { limit }\n })\n\nconst noProgressAgentRunContinuationError = (endpoint: string, startIndex: number | undefined) =>\n new AgentTransportError({\n message: 'Agent run continuation made no progress before a terminal event',\n cause: { endpoint, startIndex }\n })\n\nconst noProgressAgentRunContinuationDelayMs = 250\n\nconst waitForAgentRunContinuationProgress = (signal: AbortSignal | undefined) =>\n new Promise<void>((resolve, reject) => {\n if (signal === undefined) {\n setTimeout(resolve, noProgressAgentRunContinuationDelayMs)\n return\n }\n\n if (signal.aborted) {\n reject(abortSignalError(signal))\n return\n }\n\n const timeout = setTimeout(() => {\n signal.removeEventListener('abort', onAbort)\n resolve()\n }, noProgressAgentRunContinuationDelayMs)\n const onAbort = () => {\n clearTimeout(timeout)\n signal.removeEventListener('abort', onAbort)\n reject(abortSignalError(signal))\n }\n\n signal.addEventListener('abort', onAbort, { once: true })\n })\n\nconst missingAgentRunTailIndexError = () =>\n new AgentTransportError({\n message: 'Agent run HITL response missing x-workflow-stream-tail-index',\n cause: 'missing_tail_index'\n })\n\nconst streamAgentEventChunk = async function* (input: {\n readonly events: AsyncGenerator<AgentEventType, void, void>\n readonly countOffset: number\n readonly onEvent?: StreamAgentEventHandler\n}): AsyncGenerator<AgentEventType, AgentEventChunkResult, void> {\n let count = 0\n let terminal = false\n\n for await (const event of input.events) {\n count += 1\n terminal = terminal || isTerminalAgentEvent(event)\n input.onEvent?.(event, input.countOffset + count)\n yield event\n }\n\n return { count, terminal }\n}\n\nconst streamAgentRunContinuations = async function* (\n input: AgentRunContinuationInput\n): AsyncGenerator<AgentEventType, void, void> {\n let totalCount = input.countOffset\n let terminal = input.terminal\n let startIndex = input.startIndex\n const limit = agentRunContinuationLimit(input.continuationLimit)\n\n if (terminal) {\n return\n }\n\n if (input.endpoint === undefined) {\n throw missingAgentRunContinuationEndpointError()\n }\n\n for (let continuation = 0; continuation < limit; continuation += 1) {\n const endpoint = input.endpoint\n\n const chunk = yield* streamAgentEventChunk({\n events: streamAgentRunEvents({\n endpoint,\n startIndex,\n signal: input.signal,\n httpClientLayer: input.httpClientLayer,\n onResponse: input.onResponse\n }),\n countOffset: totalCount,\n onEvent: input.onEvent\n })\n\n if (chunk.count === 0 && !chunk.terminal) {\n if (continuation >= limit - 1) {\n throw noProgressAgentRunContinuationError(endpoint, startIndex)\n }\n\n await waitForAgentRunContinuationProgress(input.signal)\n continue\n }\n\n terminal = chunk.terminal\n startIndex = nextAgentRunStartIndex(startIndex, chunk.count)\n totalCount += chunk.count\n\n if (terminal) {\n return\n }\n }\n\n throw exhaustedAgentRunContinuationLimitError(limit)\n}\n\nexport async function* streamAgentEventsUntilTerminal(\n request: StreamAgentEventsUntilTerminalRequest\n): AsyncGenerator<AgentEventType, void, void> {\n validateAgentRunContinuationLimit(request.continuationLimit)\n\n let runEndpoint: string | undefined\n let startIndex: number | undefined\n\n const firstChunk = yield* streamAgentEventChunk({\n events: streamAgentEvents({\n ...request,\n onResponse: response => {\n startIndex = agentRunStreamStartIndexFromHeaders(response.headers)\n const runId = agentRunIdFromHeaders(response.headers)\n if (runId !== undefined) {\n runEndpoint =\n request.runEndpoint?.(runId) ?? defaultAgentRunEndpoint(request.endpoint, runId)\n request.onRunId?.(runId)\n }\n\n request.onResponse?.(response)\n }\n }),\n countOffset: 0,\n onEvent: request.onEvent\n })\n\n yield* streamAgentRunContinuations({\n endpoint: runEndpoint,\n startIndex: nextAgentRunStartIndex(startIndex, firstChunk.count),\n countOffset: firstChunk.count,\n terminal: firstChunk.terminal,\n continuationLimit: request.continuationLimit,\n signal: request.signal,\n httpClientLayer: request.httpClientLayer,\n onResponse: request.onResponse,\n onEvent: request.onEvent\n })\n}\n\nexport async function* streamAgentRunEventsUntilTerminal(\n request: StreamAgentRunEventsUntilTerminalRequest\n): AsyncGenerator<AgentEventType, void, void> {\n validateAgentRunContinuationLimit(request.continuationLimit)\n\n const firstChunk = yield* streamAgentEventChunk({\n events: streamAgentRunEvents(request),\n countOffset: 0,\n onEvent: request.onEvent\n })\n\n yield* streamAgentRunContinuations({\n endpoint: request.endpoint,\n startIndex: nextAgentRunStartIndex(request.startIndex, firstChunk.count),\n countOffset: firstChunk.count,\n terminal: firstChunk.terminal,\n continuationLimit: request.continuationLimit,\n signal: request.signal,\n httpClientLayer: request.httpClientLayer,\n onResponse: request.onResponse,\n onEvent: request.onEvent\n })\n}\n\nexport async function* streamAgentRunHitlResponseEventsUntilTerminal(\n request: StreamAgentRunHitlResponseEventsUntilTerminalRequest\n): AsyncGenerator<AgentEventType, void, void> {\n validateAgentRunContinuationLimit(request.continuationLimit)\n\n let startIndex: number | undefined\n\n const firstChunk = yield* streamAgentEventChunk({\n events: streamAgentRunHitlResponseEvents({\n ...request,\n onResponse: response => {\n startIndex = agentRunStreamStartIndexFromHeaders(response.headers)\n request.onResponse?.(response)\n }\n }),\n countOffset: 0,\n onEvent: request.onEvent\n })\n\n if (!firstChunk.terminal && startIndex === undefined) {\n throw missingAgentRunTailIndexError()\n }\n\n yield* streamAgentRunContinuations({\n endpoint: request.endpoint,\n startIndex: nextAgentRunStartIndex(startIndex, firstChunk.count),\n countOffset: firstChunk.count,\n terminal: firstChunk.terminal,\n continuationLimit: request.continuationLimit,\n signal: request.signal,\n httpClientLayer: request.httpClientLayer,\n onResponse: request.onResponse,\n onEvent: request.onEvent\n })\n}\n\nconst isAgentEvent = (message: AgentWebSocketServerMessageType): message is AgentEventType =>\n message._tag !== 'SessionSnapshot'\n\nexport const streamCloudflareAgentEventStream = (request: StreamCloudflareAgentEventsRequest) =>\n applyAbortSignal(\n Stream.callback<AgentEventType, AgentTransportError>(queue =>\n Effect.gen(function* () {\n const socket = new WebSocket(request.webSocketUrl)\n let sentInput = false\n let settled = false\n const closeSocket = Effect.sync(() => {\n if (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING) {\n socket.close(1000, 'done')\n }\n })\n const failQueue = (error: AgentTransportError) =>\n Queue.failCauseUnsafe(queue, Cause.fail(error))\n const endQueue = () => Queue.endUnsafe(queue)\n const handleMessage = (event: MessageEvent) => {\n if (typeof event.data !== 'string') {\n failQueue(toTransportError('Agent WebSocket returned binary data', event.data))\n return\n }\n\n Effect.runFork(\n parseWebSocketServerMessage(event.data).pipe(\n Effect.flatMap(message => {\n if (message._tag === 'SessionSnapshot') {\n return sentInput\n ? Effect.void\n : makeClientInputJson(request, message.revision).pipe(\n Effect.flatMap(body => Effect.sync(() => socket.send(body))),\n Effect.tap(() =>\n Effect.sync(() => {\n sentInput = true\n })\n )\n )\n }\n\n if (!isAgentEvent(message)) {\n return Effect.void\n }\n\n return Effect.sync(() => {\n Queue.offerUnsafe(queue, message)\n if (isTerminalAgentEvent(message)) {\n settled = true\n endQueue()\n socket.close(1000, 'done')\n }\n })\n }),\n Effect.catch(error => Effect.sync(() => failQueue(error)))\n )\n )\n }\n const handleError = () => {\n failQueue(toTransportError('Agent WebSocket failed', request.webSocketUrl))\n }\n const handleClose = () => {\n if (!settled) {\n failQueue(toTransportError('Agent WebSocket closed', request.webSocketUrl))\n }\n }\n\n yield* Effect.acquireRelease(\n Effect.sync(() => {\n socket.addEventListener('message', handleMessage)\n socket.addEventListener('error', handleError)\n socket.addEventListener('close', handleClose)\n }),\n () =>\n Effect.sync(() => {\n socket.removeEventListener('message', handleMessage)\n socket.removeEventListener('error', handleError)\n socket.removeEventListener('close', handleClose)\n }).pipe(Effect.andThen(closeSocket))\n )\n })\n ),\n request.signal\n )\n\nexport async function* streamCloudflareAgentEvents(\n request: StreamCloudflareAgentEventsRequest\n): AsyncGenerator<AgentEventType, void, void> {\n for await (const event of Stream.toAsyncIterable(streamCloudflareAgentEventStream(request))) {\n yield event\n }\n}\n\nexport async function* streamAgentEvents(\n request: StreamAgentEventsRequest\n): AsyncGenerator<AgentEventType, void, void> {\n for await (const event of Stream.toAsyncIterable(streamAgentEventStream(request))) {\n yield event\n }\n}\n\nexport async function* streamAgentRunEvents(\n request: StreamAgentRunEventsRequest\n): AsyncGenerator<AgentEventType, void, void> {\n for await (const event of Stream.toAsyncIterable(streamAgentRunEventStream(request))) {\n yield event\n }\n}\n\nexport async function* streamAgentRunHitlResponseEvents(\n request: StreamAgentRunHitlResponseEventsRequest\n): AsyncGenerator<AgentEventType, void, void> {\n for await (const event of Stream.toAsyncIterable(\n streamAgentRunHitlResponseEventStream(request)\n )) {\n yield event\n }\n}\n\nexport async function* submitToolApprovalResponse(\n request: SubmitToolApprovalResponseRequest\n): AsyncGenerator<AgentEventType, void, void> {\n for await (const event of Stream.toAsyncIterable(\n streamToolApprovalResponseEventStream(request)\n )) {\n yield event\n }\n}\n\nexport async function* submitQuestionResponse(\n request: SubmitQuestionResponseRequest\n): AsyncGenerator<AgentEventType, void, void> {\n for await (const event of Stream.toAsyncIterable(streamQuestionResponseEventStream(request))) {\n yield event\n }\n}\n\nexport const cancelAgentRun = (request: CancelAgentRunRequest) =>\n Effect.runPromise(cancelAgentRunEffect(request))\n\nexport const collectAgentEventsEffect = (request: StreamAgentEventsRequest) =>\n streamAgentEventStream(request).pipe(Stream.runCollect)\n\nexport const collectAgentEvents = async (request: StreamAgentEventsRequest) =>\n Array.from(await Effect.runPromise(collectAgentEventsEffect(request)))\n"],"mappings":";;;;;AA6BA,IAAa,sBAAb,cAAyC,OAAO,iBAAsC,EACpF,uBACA;CACE,SAAS,OAAO;CAChB,OAAO,OAAO;AAChB,CACF,EAAE,CAAC;AA4EH,MAAM,kBAAkB;AACxB,MAAM,8BAA8B;AACpC,MAAM,uBAAuB;AAE7B,MAAM,eAAe,SAAuD,SAAiB;CAC3F,MAAM,SAAS,QAAQ;CAEvB,IAAI,WAAW,KAAA,GACb,OAAO;CAGT,MAAM,iBAAiB,KAAK,YAAY;CAExC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,GAC/C,I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ACrB,SAC4C;CAC5C,WAAW,MAAM,SAAS,OAAO,gBAC/B,sCAAsC,OAAO,CAC/C,GACE,MAAM;AAEV;AAEA,gBAAuB,2BACrB,SAC4C;CAC5C,WAAW,MAAM,SAAS,OAAO,gBAC/B,sCAAsC,OAAO,CAC/C,GACE,MAAM;AAEV;AAEA,gBAAuB,uBACrB,SAC4C;CAC5C,WAAW,MAAM,SAAS,OAAO,gBAAgB,kCAAkC,OAAO,CAAC,GACzF,MAAM;AAEV;AAEA,MAAa,kBAAkB,YAC7B,OAAO,WAAW,qBAAqB,OAAO,CAAC;AAEjD,MAAa,4BAA4B,YACvC,uBAAuB,OAAO,EAAE,KAAK,OAAO,UAAU;AAExD,MAAa,qBAAqB,OAAO,YACvC,MAAM,KAAK,MAAM,OAAO,WAAW,yBAAyB,OAAO,CAAC,CAAC"}
|
|
@@ -239,6 +239,10 @@ declare const makeSubagentRunId: (parentToolCallId: string) => string;
|
|
|
239
239
|
declare const hitlResponseEvent: (response: HitlResponse) => AgentEvent;
|
|
240
240
|
declare const AgentEvent: Schema.Union<readonly [typeof AgentStart, typeof AgentError, typeof AgentEnd, typeof AgentAwaitingInput, typeof UsageUpdate, typeof AgentRetry, typeof CompactionStart, typeof CompactionEnd, typeof TurnStart, typeof TurnEnd, typeof LLMStreamStart, typeof LLMTextDelta, typeof LLMReasoningDelta, typeof ToolInputStart, typeof ToolInputDelta, typeof ToolInputEnd, typeof LLMStreamEnd, typeof AssistantMessageEvent, typeof ToolApprovalRequested, typeof ToolApprovalGranted, typeof ToolApprovalDenied, typeof QuestionRequested, typeof QuestionAnswered, typeof QuestionCancelled, typeof ToolExecutionStarted, typeof ToolExecutionCompleted, typeof ToolExecutionError, typeof ProviderToolResult, typeof SubagentStarted, typeof SubagentCompleted]>;
|
|
241
241
|
type AgentEvent = typeof AgentEvent.Type;
|
|
242
|
+
type TerminalAgentEvent = Extract<AgentEvent, {
|
|
243
|
+
readonly _tag: 'AgentEnd' | 'AgentError' | 'AgentAwaitingInput';
|
|
244
|
+
}>;
|
|
245
|
+
declare const isTerminalAgentEvent: (event: AgentEvent) => event is TerminalAgentEvent;
|
|
242
246
|
//#endregion
|
|
243
|
-
export { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderErrorInfo, ProviderFailureKind, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, hitlResponseEvent, makeSubagentRunId };
|
|
247
|
+
export { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderErrorInfo, ProviderFailureKind, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, TerminalAgentEvent, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, hitlResponseEvent, isTerminalAgentEvent, makeSubagentRunId };
|
|
244
248
|
//# sourceMappingURL=event.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event.d.mts","names":[],"sources":["../../src/protocol/event.ts"],"mappings":";;;;;;cAsBa,cAAA,EAAc,MAAA,CAAA,QAAA;AAAA,KACf,cAAA,UAAwB,cAAA,CAAe,IAAI;AAAA,cAE1C,cAAA,EAAc,MAAA,CAAA,QAAA;AAAA,KAgBf,cAAA,U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AAO,CACtC,UAAA;EAAA,SACW,IAAA;AAAA;AAAA,cAGA,oBAAA,GAAwB,KAAA,EAAO,UAAA,KAAa,KAAA,IAAS,kBAC+B"}
|
package/dist/protocol/event.mjs
CHANGED
|
@@ -274,7 +274,8 @@ const AgentEvent = Schema.Union([
|
|
|
274
274
|
SubagentStarted,
|
|
275
275
|
SubagentCompleted
|
|
276
276
|
]);
|
|
277
|
+
const isTerminalAgentEvent = (event) => event._tag === "AgentEnd" || event._tag === "AgentError" || event._tag === "AgentAwaitingInput";
|
|
277
278
|
//#endregion
|
|
278
|
-
export { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderErrorInfo, ProviderFailureKind, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, hitlResponseEvent, makeSubagentRunId };
|
|
279
|
+
export { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderErrorInfo, ProviderFailureKind, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, hitlResponseEvent, isTerminalAgentEvent, makeSubagentRunId };
|
|
279
280
|
|
|
280
281
|
//# sourceMappingURL=event.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"event.mjs","names":[],"sources":["../../src/protocol/event.ts"],"sourcesContent":["import * as Schema from 'effect/Schema'\nimport { AssistantAgentMessage, AgentMessage } from './message.ts'\nimport {\n HitlRequest,\n QuestionAnswer,\n QuestionRequest,\n QuestionResponse,\n ToolApprovalRequest,\n ToolApprovalResponse,\n ToolCall,\n ToolResult,\n type HitlResponse\n} from './tool.ts'\nimport { AgentUsage } from './usage.ts'\n\nconst NonEmptyTrimmedString = Schema.Trimmed.pipe(Schema.check(Schema.isNonEmpty()))\n\nconst EventIdentity = {\n eventId: Schema.optional(NonEmptyTrimmedString),\n createdAtMs: Schema.optional(Schema.Number)\n}\n\nexport const SubagentStatus = Schema.Literals(['running', 'completed', 'error'])\nexport type SubagentStatus = typeof SubagentStatus.Type\n\nexport const AgentErrorCode = Schema.Literals([\n 'validation_error',\n 'provider_error',\n 'rate_limit',\n 'overloaded',\n 'context_overflow',\n 'invalid_response',\n 'tool_error',\n 'tool_denied',\n 'tool_timeout',\n 'store_error',\n 'aborted',\n 'session_not_found',\n 'conflict',\n 'unknown'\n])\nexport type AgentErrorCode = typeof AgentErrorCode.Type\n\nexport const ProviderFailureKind = Schema.Literals([\n 'rate_limit',\n 'overloaded',\n 'server_error',\n 'network',\n 'stream',\n 'auth',\n 'context_overflow',\n 'invalid_response',\n 'unknown'\n])\nexport type ProviderFailureKind = typeof ProviderFailureKind.Type\n\nexport class ProviderErrorInfo extends Schema.Class<ProviderErrorInfo>('ProviderErrorInfo')({\n provider: NonEmptyTrimmedString,\n kind: ProviderFailureKind,\n status: Schema.optional(Schema.Number),\n providerCode: Schema.optional(Schema.String),\n retryAfterMs: Schema.optional(Schema.Number)\n}) {}\n\nexport class AgentStart extends Schema.TaggedClass<AgentStart>()('AgentStart', {\n ...EventIdentity\n}) {}\n\nexport class AgentError extends Schema.TaggedClass<AgentError>()('AgentError', {\n ...EventIdentity,\n code: AgentErrorCode,\n message: Schema.String,\n retryable: Schema.Boolean,\n provider: Schema.optional(ProviderErrorInfo)\n}) {}\n\nexport class AgentEnd extends Schema.TaggedClass<AgentEnd>()('AgentEnd', {\n ...EventIdentity,\n messages: Schema.Array(AgentMessage),\n turns: Schema.Number,\n usage: AgentUsage\n}) {}\n\nexport class AgentAwaitingInput extends Schema.TaggedClass<AgentAwaitingInput>()(\n 'AgentAwaitingInput',\n {\n ...EventIdentity,\n requests: Schema.NonEmptyArray(HitlRequest),\n messages: Schema.Array(AgentMessage),\n turns: Schema.Number,\n usage: AgentUsage\n }\n) {}\n\nexport class UsageUpdate extends Schema.TaggedClass<UsageUpdate>()('UsageUpdate', {\n ...EventIdentity,\n usage: AgentUsage\n}) {}\n\nexport class AgentRetry extends Schema.TaggedClass<AgentRetry>()('AgentRetry', {\n ...EventIdentity,\n attempt: Schema.Number,\n reason: AgentErrorCode,\n delayMs: Schema.Number,\n message: Schema.String,\n provider: Schema.optional(ProviderErrorInfo)\n}) {}\n\nexport class CompactionStart extends Schema.TaggedClass<CompactionStart>()('CompactionStart', {\n ...EventIdentity,\n strategy: Schema.String\n}) {}\n\nexport class CompactionEnd extends Schema.TaggedClass<CompactionEnd>()('CompactionEnd', {\n ...EventIdentity,\n strategy: Schema.String,\n beforeTokens: Schema.optional(Schema.Number),\n afterTokens: Schema.optional(Schema.Number)\n}) {}\n\nexport class TurnStart extends Schema.TaggedClass<TurnStart>()('TurnStart', {\n ...EventIdentity,\n turn: Schema.Number\n}) {}\n\nexport class TurnEnd extends Schema.TaggedClass<TurnEnd>()('TurnEnd', {\n ...EventIdentity,\n turn: Schema.Number,\n reason: Schema.Literals(['stop', 'tool_use'])\n}) {}\n\nexport class LLMStreamStart extends Schema.TaggedClass<LLMStreamStart>()('LLMStreamStart', {\n ...EventIdentity,\n turn: Schema.Number\n}) {}\n\nexport class LLMTextDelta extends Schema.TaggedClass<LLMTextDelta>()('LLMTextDelta', {\n ...EventIdentity,\n text: Schema.String,\n textSoFar: Schema.optional(Schema.String)\n}) {}\n\nexport class LLMReasoningDelta extends Schema.TaggedClass<LLMReasoningDelta>()(\n 'LLMReasoningDelta',\n {\n ...EventIdentity,\n text: Schema.String,\n reasoningSoFar: Schema.optional(Schema.String)\n }\n) {}\n\nexport class ToolInputStart extends Schema.TaggedClass<ToolInputStart>()('ToolInputStart', {\n ...EventIdentity,\n id: Schema.String,\n name: Schema.optional(Schema.String)\n}) {}\n\nexport class ToolInputDelta extends Schema.TaggedClass<ToolInputDelta>()('ToolInputDelta', {\n ...EventIdentity,\n id: Schema.String,\n delta: Schema.String\n}) {}\n\nexport class ToolInputEnd extends Schema.TaggedClass<ToolInputEnd>()('ToolInputEnd', {\n ...EventIdentity,\n call: ToolCall\n}) {}\n\nexport class ToolApprovalRequested extends Schema.TaggedClass<ToolApprovalRequested>()(\n 'ToolApprovalRequested',\n {\n ...EventIdentity,\n call: ToolCall,\n request: Schema.optional(ToolApprovalRequest)\n }\n) {}\n\nexport class ToolApprovalGranted extends Schema.TaggedClass<ToolApprovalGranted>()(\n 'ToolApprovalGranted',\n {\n ...EventIdentity,\n toolCallId: Schema.String,\n response: Schema.optional(ToolApprovalResponse)\n }\n) {}\n\nexport class ToolApprovalDenied extends Schema.TaggedClass<ToolApprovalDenied>()(\n 'ToolApprovalDenied',\n {\n ...EventIdentity,\n toolCallId: Schema.String,\n reason: Schema.String,\n response: Schema.optional(ToolApprovalResponse)\n }\n) {}\n\nexport class QuestionRequested extends Schema.TaggedClass<QuestionRequested>()(\n 'QuestionRequested',\n {\n ...EventIdentity,\n request: QuestionRequest\n }\n) {}\n\nexport class QuestionAnswered extends Schema.TaggedClass<QuestionAnswered>()('QuestionAnswered', {\n ...EventIdentity,\n response: QuestionResponse\n}) {}\n\nexport class QuestionCancelled extends Schema.TaggedClass<QuestionCancelled>()(\n 'QuestionCancelled',\n {\n ...EventIdentity,\n response: QuestionResponse\n }\n) {}\n\nexport class LLMStreamEnd extends Schema.TaggedClass<LLMStreamEnd>()('LLMStreamEnd', {\n ...EventIdentity,\n turn: Schema.Number\n}) {}\n\nexport class AssistantMessageEvent extends Schema.TaggedClass<AssistantMessageEvent>()(\n 'AssistantMessage',\n {\n ...EventIdentity,\n message: AssistantAgentMessage\n }\n) {}\n\nexport class ToolExecutionStarted extends Schema.TaggedClass<ToolExecutionStarted>()(\n 'ToolExecutionStarted',\n {\n ...EventIdentity,\n call: ToolCall\n }\n) {}\n\nexport class ToolExecutionCompleted extends Schema.TaggedClass<ToolExecutionCompleted>()(\n 'ToolExecutionCompleted',\n {\n ...EventIdentity,\n call: ToolCall,\n result: ToolResult\n }\n) {}\n\nexport class ToolExecutionError extends Schema.TaggedClass<ToolExecutionError>()(\n 'ToolExecutionError',\n {\n ...EventIdentity,\n call: ToolCall,\n message: Schema.String,\n code: AgentErrorCode\n }\n) {}\n\nexport class ProviderToolResult extends Schema.TaggedClass<ProviderToolResult>()(\n 'ProviderToolResult',\n {\n ...EventIdentity,\n call: ToolCall,\n result: ToolResult\n }\n) {}\n\nexport class SubagentStarted extends Schema.TaggedClass<SubagentStarted>()('SubagentStarted', {\n ...EventIdentity,\n parentToolCallId: NonEmptyTrimmedString,\n subagentRunId: NonEmptyTrimmedString,\n subagentType: NonEmptyTrimmedString,\n description: Schema.String,\n model: Schema.String\n}) {}\n\nexport class SubagentCompleted extends Schema.TaggedClass<SubagentCompleted>()(\n 'SubagentCompleted',\n {\n ...EventIdentity,\n parentToolCallId: NonEmptyTrimmedString,\n subagentRunId: NonEmptyTrimmedString,\n subagentType: NonEmptyTrimmedString,\n description: Schema.String,\n model: Schema.String,\n status: SubagentStatus,\n durationMs: Schema.Number,\n summary: Schema.optional(Schema.String)\n }\n) {}\n\nexport const makeSubagentRunId = (parentToolCallId: string) => `subagent:${parentToolCallId}`\n\nconst questionAnswerValue = (answer: QuestionAnswer) =>\n QuestionAnswer.make({\n questionId: answer.questionId,\n ...(answer.optionIds === undefined ? {} : { optionIds: [...answer.optionIds] }),\n ...(answer.customAnswer === undefined ? {} : { customAnswer: answer.customAnswer })\n })\n\nconst questionResponseValue = (response: QuestionResponse) =>\n QuestionResponse.make({\n requestId: response.requestId,\n toolCallId: response.toolCallId,\n outcome: response.outcome,\n source: response.source,\n ...(response.answers === undefined\n ? {}\n : { answers: response.answers.map(answer => questionAnswerValue(answer)) }),\n ...(response.reason === undefined ? {} : { reason: response.reason })\n })\n\nconst toolApprovalResponseValue = (response: ToolApprovalResponse) =>\n ToolApprovalResponse.make({\n requestId: response.requestId,\n toolCallId: response.toolCallId,\n decision: response.decision,\n source: response.source,\n ...(response.reason === undefined ? {} : { reason: response.reason })\n })\n\nexport const hitlResponseEvent = (response: HitlResponse): AgentEvent => {\n switch (response._tag) {\n case 'QuestionResponse': {\n const responseValue = questionResponseValue(response)\n\n return response.outcome === 'answered'\n ? QuestionAnswered.make({ response: responseValue })\n : QuestionCancelled.make({ response: responseValue })\n }\n case 'ToolApprovalResponse': {\n const responseValue = toolApprovalResponseValue(response)\n\n return response.decision === 'approved'\n ? ToolApprovalGranted.make({ toolCallId: response.toolCallId, response: responseValue })\n : ToolApprovalDenied.make({\n toolCallId: response.toolCallId,\n reason: response.reason ?? 'Denied by user',\n response: responseValue\n })\n }\n }\n}\n\nexport const AgentEvent = Schema.Union([\n AgentStart,\n AgentError,\n AgentEnd,\n AgentAwaitingInput,\n UsageUpdate,\n AgentRetry,\n CompactionStart,\n CompactionEnd,\n TurnStart,\n TurnEnd,\n LLMStreamStart,\n LLMTextDelta,\n LLMReasoningDelta,\n ToolInputStart,\n ToolInputDelta,\n ToolInputEnd,\n LLMStreamEnd,\n AssistantMessageEvent,\n ToolApprovalRequested,\n ToolApprovalGranted,\n ToolApprovalDenied,\n QuestionRequested,\n QuestionAnswered,\n QuestionCancelled,\n ToolExecutionStarted,\n ToolExecutionCompleted,\n ToolExecutionError,\n ProviderToolResult,\n SubagentStarted,\n SubagentCompleted\n])\nexport type AgentEvent = typeof AgentEvent.Type\n"],"mappings":";;;;;AAeA,MAAM,wBAAwB,OAA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CACjB,GAAI,SAAS,YAAY,KAAA,IACrB,CAAC,IACD,EAAE,SAAS,SAAS,QAAQ,KAAI,WAAU,oBAAoB,MAAM,CAAC,EAAE;CAC3E,GAAI,SAAS,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,SAAS,OAAO;AACrE,CAAC;AAEH,MAAM,6BAA6B,aACjC,qBAAqB,KAAK;CACxB,WAAW,SAAS;CACpB,YAAY,SAAS;CACrB,UAAU,SAAS;CACnB,QAAQ,SAAS;CACjB,GAAI,SAAS,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,SAAS,OAAO;AACrE,CAAC;AAEH,MAAa,qBAAqB,aAAuC;CACvE,QAAQ,SAAS,MAAjB;EACE,KAAK,oBAAoB;GACvB,MAAM,gBAAgB,sBAAsB,QAAQ;GAEpD,OAAO,SAAS,YAAY,aACxB,iBAAiB,KAAK,EAAE,UAAU,cAAc,CAAC,IACjD,kBAAkB,KAAK,EAAE,UAAU,cAAc,CAAC;EACxD;EACA,KAAK,wBAAwB;GAC3B,MAAM,gBAAgB,0BAA0B,QAAQ;GAExD,OAAO,SAAS,aAAa,aACzB,oBAAoB,KAAK;IAAE,YAAY,SAAS;IAAY,UAAU;GAAc,CAAC,IACrF,mBAAmB,KAAK;IACtB,YAAY,SAAS;IACrB,QAAQ,SAAS,UAAU;IAC3B,UAAU;GACZ,CAAC;EACP;CACF;AACF;AAEA,MAAa,aAAa,OAAO,MAAM;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"event.mjs","names":[],"sources":["../../src/protocol/event.ts"],"sourcesContent":["import * as Schema from 'effect/Schema'\nimport { AssistantAgentMessage, AgentMessage } from './message.ts'\nimport {\n HitlRequest,\n QuestionAnswer,\n QuestionRequest,\n QuestionResponse,\n ToolApprovalRequest,\n ToolApprovalResponse,\n ToolCall,\n ToolResult,\n type HitlResponse\n} from './tool.ts'\nimport { AgentUsage } from './usage.ts'\n\nconst NonEmptyTrimmedString = Schema.Trimmed.pipe(Schema.check(Schema.isNonEmpty()))\n\nconst EventIdentity = {\n eventId: Schema.optional(NonEmptyTrimmedString),\n createdAtMs: Schema.optional(Schema.Number)\n}\n\nexport const SubagentStatus = Schema.Literals(['running', 'completed', 'error'])\nexport type SubagentStatus = typeof SubagentStatus.Type\n\nexport const AgentErrorCode = Schema.Literals([\n 'validation_error',\n 'provider_error',\n 'rate_limit',\n 'overloaded',\n 'context_overflow',\n 'invalid_response',\n 'tool_error',\n 'tool_denied',\n 'tool_timeout',\n 'store_error',\n 'aborted',\n 'session_not_found',\n 'conflict',\n 'unknown'\n])\nexport type AgentErrorCode = typeof AgentErrorCode.Type\n\nexport const ProviderFailureKind = Schema.Literals([\n 'rate_limit',\n 'overloaded',\n 'server_error',\n 'network',\n 'stream',\n 'auth',\n 'context_overflow',\n 'invalid_response',\n 'unknown'\n])\nexport type ProviderFailureKind = typeof ProviderFailureKind.Type\n\nexport class ProviderErrorInfo extends Schema.Class<ProviderErrorInfo>('ProviderErrorInfo')({\n provider: NonEmptyTrimmedString,\n kind: ProviderFailureKind,\n status: Schema.optional(Schema.Number),\n providerCode: Schema.optional(Schema.String),\n retryAfterMs: Schema.optional(Schema.Number)\n}) {}\n\nexport class AgentStart extends Schema.TaggedClass<AgentStart>()('AgentStart', {\n ...EventIdentity\n}) {}\n\nexport class AgentError extends Schema.TaggedClass<AgentError>()('AgentError', {\n ...EventIdentity,\n code: AgentErrorCode,\n message: Schema.String,\n retryable: Schema.Boolean,\n provider: Schema.optional(ProviderErrorInfo)\n}) {}\n\nexport class AgentEnd extends Schema.TaggedClass<AgentEnd>()('AgentEnd', {\n ...EventIdentity,\n messages: Schema.Array(AgentMessage),\n turns: Schema.Number,\n usage: AgentUsage\n}) {}\n\nexport class AgentAwaitingInput extends Schema.TaggedClass<AgentAwaitingInput>()(\n 'AgentAwaitingInput',\n {\n ...EventIdentity,\n requests: Schema.NonEmptyArray(HitlRequest),\n messages: Schema.Array(AgentMessage),\n turns: Schema.Number,\n usage: AgentUsage\n }\n) {}\n\nexport class UsageUpdate extends Schema.TaggedClass<UsageUpdate>()('UsageUpdate', {\n ...EventIdentity,\n usage: AgentUsage\n}) {}\n\nexport class AgentRetry extends Schema.TaggedClass<AgentRetry>()('AgentRetry', {\n ...EventIdentity,\n attempt: Schema.Number,\n reason: AgentErrorCode,\n delayMs: Schema.Number,\n message: Schema.String,\n provider: Schema.optional(ProviderErrorInfo)\n}) {}\n\nexport class CompactionStart extends Schema.TaggedClass<CompactionStart>()('CompactionStart', {\n ...EventIdentity,\n strategy: Schema.String\n}) {}\n\nexport class CompactionEnd extends Schema.TaggedClass<CompactionEnd>()('CompactionEnd', {\n ...EventIdentity,\n strategy: Schema.String,\n beforeTokens: Schema.optional(Schema.Number),\n afterTokens: Schema.optional(Schema.Number)\n}) {}\n\nexport class TurnStart extends Schema.TaggedClass<TurnStart>()('TurnStart', {\n ...EventIdentity,\n turn: Schema.Number\n}) {}\n\nexport class TurnEnd extends Schema.TaggedClass<TurnEnd>()('TurnEnd', {\n ...EventIdentity,\n turn: Schema.Number,\n reason: Schema.Literals(['stop', 'tool_use'])\n}) {}\n\nexport class LLMStreamStart extends Schema.TaggedClass<LLMStreamStart>()('LLMStreamStart', {\n ...EventIdentity,\n turn: Schema.Number\n}) {}\n\nexport class LLMTextDelta extends Schema.TaggedClass<LLMTextDelta>()('LLMTextDelta', {\n ...EventIdentity,\n text: Schema.String,\n textSoFar: Schema.optional(Schema.String)\n}) {}\n\nexport class LLMReasoningDelta extends Schema.TaggedClass<LLMReasoningDelta>()(\n 'LLMReasoningDelta',\n {\n ...EventIdentity,\n text: Schema.String,\n reasoningSoFar: Schema.optional(Schema.String)\n }\n) {}\n\nexport class ToolInputStart extends Schema.TaggedClass<ToolInputStart>()('ToolInputStart', {\n ...EventIdentity,\n id: Schema.String,\n name: Schema.optional(Schema.String)\n}) {}\n\nexport class ToolInputDelta extends Schema.TaggedClass<ToolInputDelta>()('ToolInputDelta', {\n ...EventIdentity,\n id: Schema.String,\n delta: Schema.String\n}) {}\n\nexport class ToolInputEnd extends Schema.TaggedClass<ToolInputEnd>()('ToolInputEnd', {\n ...EventIdentity,\n call: ToolCall\n}) {}\n\nexport class ToolApprovalRequested extends Schema.TaggedClass<ToolApprovalRequested>()(\n 'ToolApprovalRequested',\n {\n ...EventIdentity,\n call: ToolCall,\n request: Schema.optional(ToolApprovalRequest)\n }\n) {}\n\nexport class ToolApprovalGranted extends Schema.TaggedClass<ToolApprovalGranted>()(\n 'ToolApprovalGranted',\n {\n ...EventIdentity,\n toolCallId: Schema.String,\n response: Schema.optional(ToolApprovalResponse)\n }\n) {}\n\nexport class ToolApprovalDenied extends Schema.TaggedClass<ToolApprovalDenied>()(\n 'ToolApprovalDenied',\n {\n ...EventIdentity,\n toolCallId: Schema.String,\n reason: Schema.String,\n response: Schema.optional(ToolApprovalResponse)\n }\n) {}\n\nexport class QuestionRequested extends Schema.TaggedClass<QuestionRequested>()(\n 'QuestionRequested',\n {\n ...EventIdentity,\n request: QuestionRequest\n }\n) {}\n\nexport class QuestionAnswered extends Schema.TaggedClass<QuestionAnswered>()('QuestionAnswered', {\n ...EventIdentity,\n response: QuestionResponse\n}) {}\n\nexport class QuestionCancelled extends Schema.TaggedClass<QuestionCancelled>()(\n 'QuestionCancelled',\n {\n ...EventIdentity,\n response: QuestionResponse\n }\n) {}\n\nexport class LLMStreamEnd extends Schema.TaggedClass<LLMStreamEnd>()('LLMStreamEnd', {\n ...EventIdentity,\n turn: Schema.Number\n}) {}\n\nexport class AssistantMessageEvent extends Schema.TaggedClass<AssistantMessageEvent>()(\n 'AssistantMessage',\n {\n ...EventIdentity,\n message: AssistantAgentMessage\n }\n) {}\n\nexport class ToolExecutionStarted extends Schema.TaggedClass<ToolExecutionStarted>()(\n 'ToolExecutionStarted',\n {\n ...EventIdentity,\n call: ToolCall\n }\n) {}\n\nexport class ToolExecutionCompleted extends Schema.TaggedClass<ToolExecutionCompleted>()(\n 'ToolExecutionCompleted',\n {\n ...EventIdentity,\n call: ToolCall,\n result: ToolResult\n }\n) {}\n\nexport class ToolExecutionError extends Schema.TaggedClass<ToolExecutionError>()(\n 'ToolExecutionError',\n {\n ...EventIdentity,\n call: ToolCall,\n message: Schema.String,\n code: AgentErrorCode\n }\n) {}\n\nexport class ProviderToolResult extends Schema.TaggedClass<ProviderToolResult>()(\n 'ProviderToolResult',\n {\n ...EventIdentity,\n call: ToolCall,\n result: ToolResult\n }\n) {}\n\nexport class SubagentStarted extends Schema.TaggedClass<SubagentStarted>()('SubagentStarted', {\n ...EventIdentity,\n parentToolCallId: NonEmptyTrimmedString,\n subagentRunId: NonEmptyTrimmedString,\n subagentType: NonEmptyTrimmedString,\n description: Schema.String,\n model: Schema.String\n}) {}\n\nexport class SubagentCompleted extends Schema.TaggedClass<SubagentCompleted>()(\n 'SubagentCompleted',\n {\n ...EventIdentity,\n parentToolCallId: NonEmptyTrimmedString,\n subagentRunId: NonEmptyTrimmedString,\n subagentType: NonEmptyTrimmedString,\n description: Schema.String,\n model: Schema.String,\n status: SubagentStatus,\n durationMs: Schema.Number,\n summary: Schema.optional(Schema.String)\n }\n) {}\n\nexport const makeSubagentRunId = (parentToolCallId: string) => `subagent:${parentToolCallId}`\n\nconst questionAnswerValue = (answer: QuestionAnswer) =>\n QuestionAnswer.make({\n questionId: answer.questionId,\n ...(answer.optionIds === undefined ? {} : { optionIds: [...answer.optionIds] }),\n ...(answer.customAnswer === undefined ? {} : { customAnswer: answer.customAnswer })\n })\n\nconst questionResponseValue = (response: QuestionResponse) =>\n QuestionResponse.make({\n requestId: response.requestId,\n toolCallId: response.toolCallId,\n outcome: response.outcome,\n source: response.source,\n ...(response.answers === undefined\n ? {}\n : { answers: response.answers.map(answer => questionAnswerValue(answer)) }),\n ...(response.reason === undefined ? {} : { reason: response.reason })\n })\n\nconst toolApprovalResponseValue = (response: ToolApprovalResponse) =>\n ToolApprovalResponse.make({\n requestId: response.requestId,\n toolCallId: response.toolCallId,\n decision: response.decision,\n source: response.source,\n ...(response.reason === undefined ? {} : { reason: response.reason })\n })\n\nexport const hitlResponseEvent = (response: HitlResponse): AgentEvent => {\n switch (response._tag) {\n case 'QuestionResponse': {\n const responseValue = questionResponseValue(response)\n\n return response.outcome === 'answered'\n ? QuestionAnswered.make({ response: responseValue })\n : QuestionCancelled.make({ response: responseValue })\n }\n case 'ToolApprovalResponse': {\n const responseValue = toolApprovalResponseValue(response)\n\n return response.decision === 'approved'\n ? ToolApprovalGranted.make({ toolCallId: response.toolCallId, response: responseValue })\n : ToolApprovalDenied.make({\n toolCallId: response.toolCallId,\n reason: response.reason ?? 'Denied by user',\n response: responseValue\n })\n }\n }\n}\n\nexport const AgentEvent = Schema.Union([\n AgentStart,\n AgentError,\n AgentEnd,\n AgentAwaitingInput,\n UsageUpdate,\n AgentRetry,\n CompactionStart,\n CompactionEnd,\n TurnStart,\n TurnEnd,\n LLMStreamStart,\n LLMTextDelta,\n LLMReasoningDelta,\n ToolInputStart,\n ToolInputDelta,\n ToolInputEnd,\n LLMStreamEnd,\n AssistantMessageEvent,\n ToolApprovalRequested,\n ToolApprovalGranted,\n ToolApprovalDenied,\n QuestionRequested,\n QuestionAnswered,\n QuestionCancelled,\n ToolExecutionStarted,\n ToolExecutionCompleted,\n ToolExecutionError,\n ProviderToolResult,\n SubagentStarted,\n SubagentCompleted\n])\nexport type AgentEvent = typeof AgentEvent.Type\n\nexport type TerminalAgentEvent = Extract<\n AgentEvent,\n { readonly _tag: 'AgentEnd' | 'AgentError' | 'AgentAwaitingInput' }\n>\n\nexport const isTerminalAgentEvent = (event: AgentEvent): event is TerminalAgentEvent =>\n event._tag === 'AgentEnd' || event._tag === 'AgentError' || event._tag === 'AgentAwaitingInput'\n"],"mappings":";;;;;AAeA,MAAM,wBAAwB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AAS;CACjB,GAAI,SAAS,YAAY,KAAA,IACrB,CAAC,IACD,EAAE,SAAS,SAAS,QAAQ,KAAI,WAAU,oBAAoB,MAAM,CAAC,EAAE;CAC3E,GAAI,SAAS,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,SAAS,OAAO;AACrE,CAAC;AAEH,MAAM,6BAA6B,aACjC,qBAAqB,KAAK;CACxB,WAAW,SAAS;CACpB,YAAY,SAAS;CACrB,UAAU,SAAS;CACnB,QAAQ,SAAS;CACjB,GAAI,SAAS,WAAW,KAAA,IAAY,CAAC,IAAI,EAAE,QAAQ,SAAS,OAAO;AACrE,CAAC;AAEH,MAAa,qBAAqB,aAAuC;CACvE,QAAQ,SAAS,MAAjB;EACE,KAAK,oBAAoB;GACvB,MAAM,gBAAgB,sBAAsB,QAAQ;GAEpD,OAAO,SAAS,YAAY,aACxB,iBAAiB,KAAK,EAAE,UAAU,cAAc,CAAC,IACjD,kBAAkB,KAAK,EAAE,UAAU,cAAc,CAAC;EACxD;EACA,KAAK,wBAAwB;GAC3B,MAAM,gBAAgB,0BAA0B,QAAQ;GAExD,OAAO,SAAS,aAAa,aACzB,oBAAoB,KAAK;IAAE,YAAY,SAAS;IAAY,UAAU;GAAc,CAAC,IACrF,mBAAmB,KAAK;IACtB,YAAY,SAAS;IACrB,QAAQ,SAAS,UAAU;IAC3B,UAAU;GACZ,CAAC;EACP;CACF;AACF;AAEA,MAAa,aAAa,OAAO,MAAM;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAQD,MAAa,wBAAwB,UACnC,MAAM,SAAS,cAAc,MAAM,SAAS,gBAAgB,MAAM,SAAS"}
|
|
@@ -3,12 +3,12 @@ import { AttachmentContentPart, AttachmentSource, AttachmentSourceResolver, Audi
|
|
|
3
3
|
import { ErrorToolResultInput, HitlRequest, HitlResponse, HitlResponseSource, PlainHitlResponse, PlainQuestionAnswer, PlainQuestionResponse, PlainToolApprovalResponse, QuestionAnswer, QuestionOption, QuestionPrompt, QuestionRequest, QuestionResponse, QuestionResponseOutcome, QuestionResponseStructuredContent, QuestionToolParams, ToolApprovalDecision, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalResponse, ToolCall, ToolDef, ToolResult, formatQuestionResponseContent, makeErrorToolResult, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, questionResponseStructuredContent } from "./tool.mjs";
|
|
4
4
|
import { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, DanglingHostToolCall, HostToolCallPart, MessageAnnotations, MessageAuthor, MessageEnvelope, ProviderToolCallPart, ProviderToolResultPart, RepairDanglingHostToolCallsOptions, ToolResultMessage, TranscriptInvariantValidation, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText, danglingHostToolCalls, messageContextText, prependMessageContextToContent, repairDanglingHostToolCalls, validateNoDanglingHostToolCalls } from "./message.mjs";
|
|
5
5
|
import { AgentInputUsage, AgentOutputUsage, AgentUsage, addAgentUsage, zeroAgentUsage } from "./usage.mjs";
|
|
6
|
-
import { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderErrorInfo, ProviderFailureKind, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, hitlResponseEvent, makeSubagentRunId } from "./event.mjs";
|
|
6
|
+
import { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderErrorInfo, ProviderFailureKind, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, TerminalAgentEvent, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, hitlResponseEvent, isTerminalAgentEvent, makeSubagentRunId } from "./event.mjs";
|
|
7
7
|
import { AgentReasoningEffort } from "./reasoning.mjs";
|
|
8
8
|
import { AgentWebSocketClientMessage, AgentWebSocketServerMessage, QuestionResponseInput, SessionSnapshot, ToolApprovalResponseInput, UserInput } from "./session.mjs";
|
|
9
9
|
|
|
10
10
|
//#region src/protocol/index.d.ts
|
|
11
11
|
type MessageId = string;
|
|
12
12
|
//#endregion
|
|
13
|
-
export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, type AttachmentContentPart, AttachmentSource, type AttachmentSourceResolver, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, type DanglingHostToolCall, DocumentPart, type ErrorToolResultInput, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, InlineBase64AttachmentSource, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageAnnotations, MessageAuthor, type MessageEnvelope, MessageId, type PlainHitlResponse, type PlainQuestionAnswer, type PlainQuestionResponse, type PlainToolApprovalResponse, ProviderErrorInfo, ProviderFailureKind, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, type QuestionResponseStructuredContent, QuestionToolParams, RefAttachmentSource, type RepairDanglingHostToolCallsOptions, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, type TranscriptInvariantValidation, TurnEnd, TurnStart, UrlAttachmentSource, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, danglingHostToolCalls, documentPartFromText, formatQuestionResponseContent, hitlResponseEvent, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, makeErrorToolResult, makeSubagentRunId, messageContextText, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, prependMessageContextToContent, questionResponseStructuredContent, refAttachmentSource, repairDanglingHostToolCalls, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities, textToBase64Utf8, urlAttachmentSource, validateNoDanglingHostToolCalls, zeroAgentUsage };
|
|
13
|
+
export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, type AttachmentContentPart, AttachmentSource, type AttachmentSourceResolver, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, type DanglingHostToolCall, DocumentPart, type ErrorToolResultInput, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, InlineBase64AttachmentSource, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageAnnotations, MessageAuthor, type MessageEnvelope, MessageId, type PlainHitlResponse, type PlainQuestionAnswer, type PlainQuestionResponse, type PlainToolApprovalResponse, ProviderErrorInfo, ProviderFailureKind, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, type QuestionResponseStructuredContent, QuestionToolParams, RefAttachmentSource, type RepairDanglingHostToolCallsOptions, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, type TerminalAgentEvent, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, type TranscriptInvariantValidation, TurnEnd, TurnStart, UrlAttachmentSource, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, danglingHostToolCalls, documentPartFromText, formatQuestionResponseContent, hitlResponseEvent, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTerminalAgentEvent, isTextDocumentMimeType, makeErrorToolResult, makeSubagentRunId, messageContextText, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, prependMessageContextToContent, questionResponseStructuredContent, refAttachmentSource, repairDanglingHostToolCalls, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities, textToBase64Utf8, urlAttachmentSource, validateNoDanglingHostToolCalls, zeroAgentUsage };
|
|
14
14
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/protocol/index.ts"],"mappings":";;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/protocol/index.ts"],"mappings":";;;;;;;;;;KAoKY,SAAA"}
|
package/dist/protocol/index.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import { AttachmentSource, AudioPart, Content, ContentPart, DocumentPart, ImageP
|
|
|
3
3
|
import { HitlRequest, HitlResponse, HitlResponseSource, QuestionAnswer, QuestionOption, QuestionPrompt, QuestionRequest, QuestionResponse, QuestionResponseOutcome, QuestionToolParams, ToolApprovalDecision, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalResponse, ToolCall, ToolDef, ToolResult, formatQuestionResponseContent, makeErrorToolResult, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, questionResponseStructuredContent } from "./tool.mjs";
|
|
4
4
|
import { AgentMessage, AssistantAgentMessage, AssistantPart, AssistantReasoningPart, AssistantTextPart, HostToolCallPart, MessageAnnotations, MessageAuthor, ProviderToolCallPart, ProviderToolResultPart, ToolResultMessage, UserMessage, assistantContent, assistantHostToolCalls, assistantReasoningText, danglingHostToolCalls, messageContextText, prependMessageContextToContent, repairDanglingHostToolCalls, validateNoDanglingHostToolCalls } from "./message.mjs";
|
|
5
5
|
import { AgentInputUsage, AgentOutputUsage, AgentUsage, addAgentUsage, zeroAgentUsage } from "./usage.mjs";
|
|
6
|
-
import { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderErrorInfo, ProviderFailureKind, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, hitlResponseEvent, makeSubagentRunId } from "./event.mjs";
|
|
6
|
+
import { AgentAwaitingInput, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentRetry, AgentStart, AssistantMessageEvent, CompactionEnd, CompactionStart, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderErrorInfo, ProviderFailureKind, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequested, SubagentCompleted, SubagentStarted, SubagentStatus, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, TurnEnd, TurnStart, UsageUpdate, hitlResponseEvent, isTerminalAgentEvent, makeSubagentRunId } from "./event.mjs";
|
|
7
7
|
import { AgentReasoningEffort } from "./reasoning.mjs";
|
|
8
8
|
import { AgentWebSocketClientMessage, AgentWebSocketServerMessage, QuestionResponseInput, SessionSnapshot, ToolApprovalResponseInput, UserInput } from "./session.mjs";
|
|
9
|
-
export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, AttachmentSource, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, DocumentPart, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, InlineBase64AttachmentSource, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageAnnotations, MessageAuthor, ProviderErrorInfo, ProviderFailureKind, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, QuestionToolParams, RefAttachmentSource, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UrlAttachmentSource, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, danglingHostToolCalls, documentPartFromText, formatQuestionResponseContent, hitlResponseEvent, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTextDocumentMimeType, makeErrorToolResult, makeSubagentRunId, messageContextText, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, prependMessageContextToContent, questionResponseStructuredContent, refAttachmentSource, repairDanglingHostToolCalls, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities, textToBase64Utf8, urlAttachmentSource, validateNoDanglingHostToolCalls, zeroAgentUsage };
|
|
9
|
+
export { AgentAwaitingInput, AgentContentCapabilities, AgentEnd, AgentError, AgentErrorCode, AgentEvent, AgentInputUsage, AgentMessage, AgentModelCapabilities, AgentOutputUsage, AgentReasoningEffort, AgentRetry, AgentStart, AgentUsage, AgentWebSocketClientMessage, AgentWebSocketServerMessage, AssistantAgentMessage, AssistantMessageEvent, AssistantPart, AssistantReasoningPart, AssistantTextPart, AttachmentSource, AudioPart, CompactionEnd, CompactionStart, Content, ContentPart, DocumentPart, HitlRequest, HitlResponse, HitlResponseSource, HostToolCallPart, ImagePart, InlineBase64AttachmentSource, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, MessageAnnotations, MessageAuthor, ProviderErrorInfo, ProviderFailureKind, ProviderToolCallPart, ProviderToolResult, ProviderToolResultPart, QuestionAnswer, QuestionAnswered, QuestionCancelled, QuestionOption, QuestionPrompt, QuestionRequest, QuestionRequested, QuestionResponse, QuestionResponseInput, QuestionResponseOutcome, QuestionToolParams, RefAttachmentSource, SessionSnapshot, SubagentCompleted, SubagentStarted, SubagentStatus, TextPart, ToolApprovalDecision, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalMode, ToolApprovalPolicy, ToolApprovalRequest, ToolApprovalRequested, ToolApprovalResponse, ToolApprovalResponseInput, ToolCall, ToolDef, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UrlAttachmentSource, UsageUpdate, UserInput, UserMessage, addAgentUsage, appendTextToContent, assistantContent, assistantHostToolCalls, assistantReasoningText, attachmentSourceBase64, attachmentSourceDataUrl, attachmentSourcePreview, attachmentSourceText, attachmentSourceUrl, contentPartPreview, contentPartText, contentParts, contentPreview, contentText, danglingHostToolCalls, documentPartFromText, formatQuestionResponseContent, hitlResponseEvent, inferTextDocumentMimeType, inlineBase64AttachmentSource, inlineBase64Source, isContentEmpty, isTerminalAgentEvent, isTextDocumentMimeType, makeErrorToolResult, makeSubagentRunId, messageContextText, plainHitlResponse, plainQuestionAnswer, plainQuestionResponse, plainToolApprovalResponse, prependMessageContextToContent, questionResponseStructuredContent, refAttachmentSource, repairDanglingHostToolCalls, resolveContentAttachmentSources, textDocumentMimeTypeFromFilename, textImageDocumentModelCapabilities, textImageModelCapabilities, textOnlyModelCapabilities, textToBase64Utf8, urlAttachmentSource, validateNoDanglingHostToolCalls, zeroAgentUsage };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yolk-sdk/agent",
|
|
3
|
-
"version": "0.1.0-canary.
|
|
3
|
+
"version": "0.1.0-canary.30",
|
|
4
4
|
"description": "Protocol, loop, runtime, client, compaction, tools, React, providers, OAuth, skillset, and voice primitives for building Yolk agents.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
package/src/client/transport.ts
CHANGED
|
@@ -12,7 +12,8 @@ import {
|
|
|
12
12
|
AgentWebSocketServerMessage,
|
|
13
13
|
QuestionResponseInput,
|
|
14
14
|
ToolApprovalResponseInput,
|
|
15
|
-
UserInput
|
|
15
|
+
UserInput,
|
|
16
|
+
isTerminalAgentEvent
|
|
16
17
|
} from '@yolk-sdk/agent/protocol'
|
|
17
18
|
import type {
|
|
18
19
|
AgentEvent as AgentEventType,
|
|
@@ -562,9 +563,6 @@ const cancelAgentRunEffect = (request: CancelAgentRunRequest) =>
|
|
|
562
563
|
)
|
|
563
564
|
}).pipe(Effect.provide(request.httpClientLayer ?? FetchHttpClient.layer))
|
|
564
565
|
|
|
565
|
-
const isTerminalAgentEvent = (event: AgentEventType) =>
|
|
566
|
-
event._tag === 'AgentEnd' || event._tag === 'AgentError' || event._tag === 'AgentAwaitingInput'
|
|
567
|
-
|
|
568
566
|
const responseToLineStream = (response: HttpClientResponse.HttpClientResponse) =>
|
|
569
567
|
response.stream.pipe(
|
|
570
568
|
Stream.mapError(toHttpClientTransportError('Could not read agent response body')),
|
|
@@ -742,6 +740,33 @@ const noProgressAgentRunContinuationError = (endpoint: string, startIndex: numbe
|
|
|
742
740
|
cause: { endpoint, startIndex }
|
|
743
741
|
})
|
|
744
742
|
|
|
743
|
+
const noProgressAgentRunContinuationDelayMs = 250
|
|
744
|
+
|
|
745
|
+
const waitForAgentRunContinuationProgress = (signal: AbortSignal | undefined) =>
|
|
746
|
+
new Promise<void>((resolve, reject) => {
|
|
747
|
+
if (signal === undefined) {
|
|
748
|
+
setTimeout(resolve, noProgressAgentRunContinuationDelayMs)
|
|
749
|
+
return
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
if (signal.aborted) {
|
|
753
|
+
reject(abortSignalError(signal))
|
|
754
|
+
return
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
const timeout = setTimeout(() => {
|
|
758
|
+
signal.removeEventListener('abort', onAbort)
|
|
759
|
+
resolve()
|
|
760
|
+
}, noProgressAgentRunContinuationDelayMs)
|
|
761
|
+
const onAbort = () => {
|
|
762
|
+
clearTimeout(timeout)
|
|
763
|
+
signal.removeEventListener('abort', onAbort)
|
|
764
|
+
reject(abortSignalError(signal))
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
signal.addEventListener('abort', onAbort, { once: true })
|
|
768
|
+
})
|
|
769
|
+
|
|
745
770
|
const missingAgentRunTailIndexError = () =>
|
|
746
771
|
new AgentTransportError({
|
|
747
772
|
message: 'Agent run HITL response missing x-workflow-stream-tail-index',
|
|
@@ -798,7 +823,12 @@ const streamAgentRunContinuations = async function* (
|
|
|
798
823
|
})
|
|
799
824
|
|
|
800
825
|
if (chunk.count === 0 && !chunk.terminal) {
|
|
801
|
-
|
|
826
|
+
if (continuation >= limit - 1) {
|
|
827
|
+
throw noProgressAgentRunContinuationError(endpoint, startIndex)
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
await waitForAgentRunContinuationProgress(input.signal)
|
|
831
|
+
continue
|
|
802
832
|
}
|
|
803
833
|
|
|
804
834
|
terminal = chunk.terminal
|
|
@@ -959,11 +989,7 @@ export const streamCloudflareAgentEventStream = (request: StreamCloudflareAgentE
|
|
|
959
989
|
|
|
960
990
|
return Effect.sync(() => {
|
|
961
991
|
Queue.offerUnsafe(queue, message)
|
|
962
|
-
if (
|
|
963
|
-
message._tag === 'AgentEnd' ||
|
|
964
|
-
message._tag === 'AgentError' ||
|
|
965
|
-
message._tag === 'AgentAwaitingInput'
|
|
966
|
-
) {
|
|
992
|
+
if (isTerminalAgentEvent(message)) {
|
|
967
993
|
settled = true
|
|
968
994
|
endQueue()
|
|
969
995
|
socket.close(1000, 'done')
|
package/src/protocol/event.ts
CHANGED
|
@@ -374,3 +374,11 @@ export const AgentEvent = Schema.Union([
|
|
|
374
374
|
SubagentCompleted
|
|
375
375
|
])
|
|
376
376
|
export type AgentEvent = typeof AgentEvent.Type
|
|
377
|
+
|
|
378
|
+
export type TerminalAgentEvent = Extract<
|
|
379
|
+
AgentEvent,
|
|
380
|
+
{ readonly _tag: 'AgentEnd' | 'AgentError' | 'AgentAwaitingInput' }
|
|
381
|
+
>
|
|
382
|
+
|
|
383
|
+
export const isTerminalAgentEvent = (event: AgentEvent): event is TerminalAgentEvent =>
|
|
384
|
+
event._tag === 'AgentEnd' || event._tag === 'AgentError' || event._tag === 'AgentAwaitingInput'
|