@yolk-sdk/agent 0.0.1-canary.1 → 0.0.1-canary.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +53 -10
- package/dist/client/transport.d.mts.map +1 -1
- package/dist/client/transport.mjs +49 -2
- package/dist/client/transport.mjs.map +1 -1
- package/dist/loop/run.d.mts.map +1 -1
- package/dist/loop/run.mjs +5 -4
- package/dist/loop/run.mjs.map +1 -1
- package/dist/protocol/capability.d.mts +3 -1
- package/dist/protocol/capability.d.mts.map +1 -1
- package/dist/protocol/capability.mjs +14 -1
- package/dist/protocol/capability.mjs.map +1 -1
- package/dist/protocol/content.d.mts +44 -6
- package/dist/protocol/content.d.mts.map +1 -1
- package/dist/protocol/content.mjs +80 -11
- package/dist/protocol/content.mjs.map +1 -1
- package/dist/protocol/event.d.mts +2 -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 +4 -4
- package/dist/protocol/index.d.mts.map +1 -1
- package/dist/protocol/index.mjs +4 -4
- package/dist/protocol/message.d.mts +4 -4
- package/dist/protocol/tool.d.mts +2 -2
- package/dist/runtime/run-runtime.d.mts.map +1 -1
- package/dist/runtime/run-runtime.mjs +27 -1
- package/dist/runtime/run-runtime.mjs.map +1 -1
- package/dist/tools/index.d.mts +2 -2
- package/dist/tools/index.mjs +2 -2
- package/dist/tools/task.d.mts +22 -3
- package/dist/tools/task.d.mts.map +1 -1
- package/dist/tools/task.mjs +31 -2
- package/dist/tools/task.mjs.map +1 -1
- package/package.json +1 -1
- package/src/client/README.md +2 -0
- package/src/client/transport.ts +91 -10
- package/src/loop/run.ts +8 -3
- package/src/protocol/capability.ts +9 -2
- package/src/protocol/content.ts +142 -6
- package/src/protocol/event.ts +2 -0
- package/src/protocol/index.ts +17 -0
- package/src/runtime/run-runtime.ts +55 -1
- package/src/tools/README.md +72 -0
- package/src/tools/index.ts +7 -1
- package/src/tools/task.ts +70 -2
package/README.md
CHANGED
|
@@ -14,23 +14,28 @@ Canary APIs are unstable. Keep all `@yolk-sdk/*` packages on the same version.
|
|
|
14
14
|
|
|
15
15
|
## Subpaths
|
|
16
16
|
|
|
17
|
-
| Subpath
|
|
18
|
-
|
|
|
19
|
-
| `@yolk-sdk/agent/protocol`
|
|
20
|
-
| `@yolk-sdk/agent/loop`
|
|
21
|
-
| `@yolk-sdk/agent/loop/testing` | Faux provider and tool executor test helpers
|
|
22
|
-
| `@yolk-sdk/agent/runtime`
|
|
23
|
-
| `@yolk-sdk/agent/client`
|
|
24
|
-
| `@yolk-sdk/agent/tools`
|
|
17
|
+
| Subpath | Purpose |
|
|
18
|
+
| ------------------------------ | -------------------------------------------------------------- |
|
|
19
|
+
| `@yolk-sdk/agent/protocol` | Wire messages, events, content, usage, tool schemas |
|
|
20
|
+
| `@yolk-sdk/agent/loop` | Stateless LLM/tool loop |
|
|
21
|
+
| `@yolk-sdk/agent/loop/testing` | Faux provider and tool executor test helpers |
|
|
22
|
+
| `@yolk-sdk/agent/runtime` | Transcript or append-backed runtime orchestration |
|
|
23
|
+
| `@yolk-sdk/agent/client` | HTTP/NDJSON transport, HITL resume, and client state helpers |
|
|
24
|
+
| `@yolk-sdk/agent/tools` | Tool module registry, `makeTool`, task/question tool contracts |
|
|
25
25
|
|
|
26
26
|
## Imports
|
|
27
27
|
|
|
28
28
|
```ts
|
|
29
|
-
import { UserMessage } from '@yolk-sdk/agent/protocol'
|
|
29
|
+
import { makeSubagentRunId, UserMessage } from '@yolk-sdk/agent/protocol'
|
|
30
30
|
import { run } from '@yolk-sdk/agent/loop'
|
|
31
31
|
import { runRuntime } from '@yolk-sdk/agent/runtime'
|
|
32
32
|
import { initialAgentClientState } from '@yolk-sdk/agent/client'
|
|
33
|
-
import {
|
|
33
|
+
import {
|
|
34
|
+
makeNonRecursiveTaskToolModule,
|
|
35
|
+
makeTaskToolResult,
|
|
36
|
+
makeQuestionToolModule,
|
|
37
|
+
resolveTools
|
|
38
|
+
} from '@yolk-sdk/agent/tools'
|
|
34
39
|
```
|
|
35
40
|
|
|
36
41
|
Test helpers live behind their own subpath:
|
|
@@ -56,6 +61,23 @@ const program = run({
|
|
|
56
61
|
// Provide LLM provider, loop config, context transformer, and tool executor layers in the host app.
|
|
57
62
|
```
|
|
58
63
|
|
|
64
|
+
## Protocol content
|
|
65
|
+
|
|
66
|
+
`Content` is either plain text or ordered parts:
|
|
67
|
+
|
|
68
|
+
- `TextPart`
|
|
69
|
+
- `ImagePart` with `InlineBase64`, `Url`, or host-owned `Ref` source
|
|
70
|
+
- `DocumentPart` with `InlineBase64`, `Url`, or host-owned `Ref` source
|
|
71
|
+
- `AudioPart` with `InlineBase64`, `Url`, or host-owned `Ref` source
|
|
72
|
+
|
|
73
|
+
Build sources with `inlineBase64AttachmentSource`, `urlAttachmentSource`, or
|
|
74
|
+
`refAttachmentSource`. Providers require inline/resolved media before lowering. Use inline base64
|
|
75
|
+
for simple apps, or persist `Ref` values and call `resolveContentAttachmentSources` at your storage
|
|
76
|
+
boundary before provider execution. Host apps own upload, auth, retention, and ref hydration policy.
|
|
77
|
+
|
|
78
|
+
Use model capabilities like `textOnlyModelCapabilities`, `textImageModelCapabilities`, or
|
|
79
|
+
`textImageDocumentModelCapabilities` so the loop rejects unsupported inputs before provider calls.
|
|
80
|
+
|
|
59
81
|
## Human-in-the-loop
|
|
60
82
|
|
|
61
83
|
HITL is protocol-level, not UI-level:
|
|
@@ -67,6 +89,27 @@ HITL is protocol-level, not UI-level:
|
|
|
67
89
|
- Use `makeQuestionToolModule` to expose the package-owned `question` tool; answers resume as structured tool results and model-visible text with selected labels.
|
|
68
90
|
- Approval is a host-enforced per-call gate for normal tools, not a model-callable permission tool or persisted allow-always system.
|
|
69
91
|
|
|
92
|
+
HTTP client helpers treat `AgentEnd`, `AgentError`, and `AgentAwaitingInput` as logical stream
|
|
93
|
+
end for consumers. After a terminal event the response body drains to EOF; cancellation before a
|
|
94
|
+
terminal event still aborts the active body reader.
|
|
95
|
+
|
|
96
|
+
## Task subagents
|
|
97
|
+
|
|
98
|
+
`task` is the package-owned contract for subagent delegation. The SDK provides schema,
|
|
99
|
+
validation, non-recursive module wiring, subagent result extraction, and structured task result
|
|
100
|
+
metadata. Host apps provide the actual nested runtime.
|
|
101
|
+
|
|
102
|
+
Recommended setup:
|
|
103
|
+
|
|
104
|
+
- expose `makeNonRecursiveTaskToolModule` only to the top-level agent
|
|
105
|
+
- resolve subagent tools with `subagent: true`
|
|
106
|
+
- omit `task` from subagent toolsets
|
|
107
|
+
- include only tools that are safe for autonomous delegated work
|
|
108
|
+
- use `makeSubagentRunId(call.id)` for protocol-aligned run ids
|
|
109
|
+
- return `makeTaskToolResult(...)` so UI can show subagent id, type, status, model, and timing
|
|
110
|
+
|
|
111
|
+
See `examples/next/lib/agents/workflow-runtime/text-response.ts` for host-owned execution wiring.
|
|
112
|
+
|
|
70
113
|
## Host responsibilities
|
|
71
114
|
|
|
72
115
|
- Choose models/providers and map provider streams into protocol events.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport.d.mts","names":[],"sources":["../../src/client/transport.ts"],"mappings":";;;;;;;cA0BiD,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,MAAA,GAAS,WAAA;EAAA,SACT,eAAA,GAAkB,KAAA,CAAM,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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 { Cause, Effect, Queue, Stream } from "effect";
|
|
1
|
+
import { Cause, Channel, Effect, Exit, Pull, Queue, Ref, Scope, Stream } from "effect";
|
|
2
2
|
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
|
|
3
3
|
import * as Schema from "effect/Schema";
|
|
4
4
|
import { AgentEvent, AgentWebSocketServerMessage, QuestionResponseInput, ToolApprovalResponseInput, UserInput } from "@yolk-sdk/agent/protocol";
|
|
@@ -124,7 +124,54 @@ const cancelAgentRunEffect = (request) => Effect.gen(function* () {
|
|
|
124
124
|
cause: response.status
|
|
125
125
|
}));
|
|
126
126
|
}).pipe(Effect.provide(request.httpClientLayer ?? FetchHttpClient.layer));
|
|
127
|
-
const
|
|
127
|
+
const isTerminalAgentEvent = (event) => event._tag === "AgentEnd" || event._tag === "AgentError" || event._tag === "AgentAwaitingInput";
|
|
128
|
+
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));
|
|
129
|
+
const closeScope = (scope) => Scope.close(scope, Exit.succeed(void 0));
|
|
130
|
+
const responseToEventStream = (response) => Stream.callback((queue) => Effect.gen(function* () {
|
|
131
|
+
const callbackScope = yield* Scope.Scope;
|
|
132
|
+
const responseScope = yield* Scope.make();
|
|
133
|
+
const responseScopeClosed = yield* Ref.make(false);
|
|
134
|
+
const terminalReached = yield* Ref.make(false);
|
|
135
|
+
const pull = yield* Channel.toPullScoped(Stream.toChannel(responseToLineStream(response)), responseScope);
|
|
136
|
+
const closeResponseScope = Effect.gen(function* () {
|
|
137
|
+
if (!(yield* Ref.get(responseScopeClosed))) {
|
|
138
|
+
yield* Ref.set(responseScopeClosed, true);
|
|
139
|
+
yield* closeScope(responseScope);
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
const endQueue = Queue.end(queue).pipe(Effect.asVoid);
|
|
143
|
+
const failQueue = (cause) => Queue.failCause(queue, cause).pipe(Effect.andThen(closeResponseScope), Effect.asVoid);
|
|
144
|
+
const drainResponse = () => Pull.matchEffect(pull, {
|
|
145
|
+
onSuccess: () => drainResponse(),
|
|
146
|
+
onFailure: (cause) => Effect.failCause(cause),
|
|
147
|
+
onDone: () => Effect.void
|
|
148
|
+
});
|
|
149
|
+
const startTerminalDrain = Effect.gen(function* () {
|
|
150
|
+
yield* Ref.set(terminalReached, true);
|
|
151
|
+
yield* endQueue;
|
|
152
|
+
yield* drainResponse().pipe(Effect.catch(() => Effect.void), Effect.ensuring(closeResponseScope), Effect.forkDetach({ startImmediately: true }), Effect.asVoid);
|
|
153
|
+
});
|
|
154
|
+
const emitLines = (lines) => Effect.gen(function* () {
|
|
155
|
+
for (const line of lines) {
|
|
156
|
+
const event = yield* parseAgentEventLine(line);
|
|
157
|
+
yield* Queue.offer(queue, event);
|
|
158
|
+
if (isTerminalAgentEvent(event)) {
|
|
159
|
+
yield* startTerminalDrain;
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
yield* run();
|
|
164
|
+
});
|
|
165
|
+
const run = () => Pull.matchEffect(pull, {
|
|
166
|
+
onSuccess: emitLines,
|
|
167
|
+
onFailure: failQueue,
|
|
168
|
+
onDone: () => endQueue.pipe(Effect.andThen(closeResponseScope))
|
|
169
|
+
});
|
|
170
|
+
yield* Scope.addFinalizer(callbackScope, Effect.gen(function* () {
|
|
171
|
+
if (!(yield* Ref.get(terminalReached))) yield* closeResponseScope;
|
|
172
|
+
}));
|
|
173
|
+
yield* run().pipe(Effect.catch((error) => Queue.failCause(queue, Cause.fail(error)).pipe(Effect.asVoid)));
|
|
174
|
+
}));
|
|
128
175
|
const abortSignalError = (signal) => new AgentTransportError({
|
|
129
176
|
message: "Agent request aborted",
|
|
130
177
|
cause: signal.reason
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport.mjs","names":[],"sources":["../../src/client/transport.ts"],"sourcesContent":["import { Cause, Effect, Queue, 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 signal?: AbortSignal\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>\n readonly onResponse?: (response: AgentHttpResponseInfo) => void\n}\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'\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 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(() => request.onResponse?.({ status: response.status, headers: response.headers }))\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 const client = yield* HttpClient.HttpClient\n const response = yield* client\n .execute(\n HttpClientRequest.get(request.endpoint).pipe(\n HttpClientRequest.setHeaders({ accept: 'application/x-ndjson' })\n )\n )\n .pipe(Effect.mapError(toHttpClientTransportError('Agent run request failed')))\n\n if (response.status >= 200 && response.status < 300) {\n yield* Effect.sync(() => request.onResponse?.({ status: response.status, headers: response.headers }))\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 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 responseToEventStream = (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 Stream.mapEffect(parseAgentEventLine),\n Stream.takeUntil(\n event =>\n event._tag === 'AgentEnd' ||\n event._tag === 'AgentError' ||\n event._tag === 'AgentAwaitingInput'\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 streamToolApprovalResponseEventStream = (\n request: SubmitToolApprovalResponseRequest\n) => streamAgentEventStream({ ...request, hitlResponses: [request.response] })\n\nexport const streamQuestionResponseEventStream = (request: SubmitQuestionResponseRequest) =>\n streamAgentEventStream({ ...request, hitlResponses: [request.response] })\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* submitToolApprovalResponse(\n request: SubmitToolApprovalResponseRequest\n): AsyncGenerator<AgentEventType, void, void> {\n for await (const event of Stream.toAsyncIterable(streamToolApprovalResponseEventStream(request))) {\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;AAgDH,MAAM,kBAAkB;AAExB,MAAM,oBAAoB,UACxB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAEvD,MAAM,oBAAoB,SAAiB,UACzC,IAAI,oBAAoB;CACtB;CACA;AACF,CAAC;AAEH,MAAM,8BAA8B,aAAqB,UACvD,iBAAiB,GAAG,QAAQ,IAAI,MAAM,WAAW,KAAK;AAExD,MAAM,oBAAoB,UACxB,OAAO,oBAAoB,UAAU,EAAE,KAAK,EAAE,KAC5C,OAAO,UACL,UACE,IAAI,oBAAoB;CACtB,SAAS,wBAAwB,iBAAiB,KAAK;CACvD,OAAO;AACT,CAAC,CACL,CACF;AAEF,MAAM,gCAAgC,UACpC,OAAO,oBAAoB,2BAA2B,EAAE,KAAK,EAAE,KAC7D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;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} 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 signal?: AbortSignal\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>\n readonly onResponse?: (response: AgentHttpResponseInfo) => void\n}\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'\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 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(() => request.onResponse?.({ status: response.status, headers: response.headers }))\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 const client = yield* HttpClient.HttpClient\n const response = yield* client\n .execute(\n HttpClientRequest.get(request.endpoint).pipe(\n HttpClientRequest.setHeaders({ accept: 'application/x-ndjson' })\n )\n )\n .pipe(Effect.mapError(toHttpClientTransportError('Agent run request failed')))\n\n if (response.status >= 200 && response.status < 300) {\n yield* Effect.sync(() => request.onResponse?.({ status: response.status, headers: response.headers }))\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 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' ||\n event._tag === 'AgentError' ||\n 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 streamToolApprovalResponseEventStream = (\n request: SubmitToolApprovalResponseRequest\n) => streamAgentEventStream({ ...request, hitlResponses: [request.response] })\n\nexport const streamQuestionResponseEventStream = (request: SubmitQuestionResponseRequest) =>\n streamAgentEventStream({ ...request, hitlResponses: [request.response] })\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* submitToolApprovalResponse(\n request: SubmitToolApprovalResponseRequest\n): AsyncGenerator<AgentEventType, void, void> {\n for await (const event of Stream.toAsyncIterable(streamToolApprovalResponseEventStream(request))) {\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;AAgDH,MAAM,kBAAkB;AAExB,MAAM,oBAAoB,UACxB,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAEvD,MAAM,oBAAoB,SAAiB,UACzC,IAAI,oBAAoB;CACtB;CACA;AACF,CAAC;AAEH,MAAM,8BAA8B,aAAqB,UACvD,iBAAiB,GAAG,QAAQ,IAAI,MAAM,WAAW,KAAK;AAExD,MAAM,oBAAoB,UACxB,OAAO,oBAAoB,UAAU,EAAE,KAAK,EAAE,KAC5C,OAAO,UACL,UACE,IAAI,oBAAoB;CACtB,SAAS,wBAAwB,iBAAiB,KAAK;CACvD,OAAO;AACT,CAAC,CACL,CACF;AAEF,MAAM,gCAAgC,UACpC,OAAO,oBAAoB,2BAA2B,EAAE,KAAK,EAAE,KAC7D,OAAO,UACL,UACE,IAAI,oBAAoB;CACtB,SAAS,oCAAoC,iBAAiB,KAAK;CACnE,OAAO;AACT,CAAC,CACL,CACF;AAEF,MAAM,oBAAoB,OAAgB,YACxC,OAAO,oBAAoB,OAAO,qBAAqB,EAAE,KAAK,EAAE,KAC9D,OAAO,UACL,UACE,IAAI,oBAAoB;CACtB,SAAS,GAAG,QAAQ,IAAI,iBAAiB,KAAK;CAC9C,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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"}
|
package/dist/loop/run.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.d.mts","names":[],"sources":["../../src/loop/run.ts"],"mappings":";;;;;;;;;
|
|
1
|
+
{"version":3,"file":"run.d.mts","names":[],"sources":["../../src/loop/run.ts"],"mappings":";;;;;;;;;KAsEY,cAAA;AAAA,KAEA,SAAA;EAAA,SACD,QAAA,EAAU,aAAA,CAAc,YAAA;EAAA,SACxB,YAAA;EAAA,SACA,KAAA,EAAO,aAAA,CAAc,OAAA;EAAA,SACrB,aAAA,GAAgB,aAAA,CAAc,YAAA;EAAA,SAC9B,KAAA;EAAA,SACA,eAAA,GAAkB,oBAAA;EAAA,SAClB,YAAA,GAAe,sBAAA;AAAA;AAAA,KAGd,eAAA,GAAkB,SAAS;EAAA,SAC5B,IAAI;AAAA;AAAA,KAGH,eAAA;EAAA,SACD,KAAA,EAAO,aAAA,CAAc,QAAA;EAAA,SACrB,KAAA,GAAQ,aAAA,CAAc,OAAA;EAAA,SACtB,aAAA,GAAgB,aAAA,CAAc,YAAA;EAAA,SAC9B,KAAA;EAAA,SACA,eAAA,GAAkB,aAAA,CAAc,YAAA;EAAA,SAChC,IAAA;EAAA,SACA,KAAA,GAAQ,UAAA;AAAA;AAAA,cAqhCN,YAAA,GACX,MAAA,EAAQ,eAAA,KACP,MAAA,CAAO,MAAA,CAAO,UAAA,EAAY,cAAA,EAAgB,kBAAA,GAAqB,WAAA,GAAc,UAAA;AAAA,cAuBnE,YAAA,GACX,MAAA,EAAQ,eAAA,KACP,MAAA,CAAO,MAAA,CAAO,UAAA,EAAY,cAAA,EAAgB,UAAA,GAAa,YAAA;AAAA,cA4C7C,GAAA,GACX,MAAA,EAAQ,SAAA,KACP,MAAA,CAAO,MAAA,CACR,UAAA,EACA,cAAA,EACA,kBAAA,GAAqB,WAAA,GAAc,UAAA,GAAa,YAAA"}
|
package/dist/loop/run.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { LoopConfig } from "./services/loop-config.mjs";
|
|
|
6
6
|
import { ToolExecutor } from "./services/tool-executor.mjs";
|
|
7
7
|
import { Clock, Effect, Ref, Stream } from "effect";
|
|
8
8
|
import * as Schema from "effect/Schema";
|
|
9
|
-
import { AgentAwaitingInput, AgentEnd, AgentRetry, AgentStart, AssistantMessageEvent, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequest, QuestionRequested, QuestionToolParams, SubagentCompleted, SubagentStarted, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequest, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UsageUpdate, addAgentUsage, assistantHostToolCalls, contentParts, contentPreview, formatQuestionResponseContent, zeroAgentUsage } from "@yolk-sdk/agent/protocol";
|
|
9
|
+
import { AgentAwaitingInput, AgentEnd, AgentRetry, AgentStart, AssistantMessageEvent, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolResult, QuestionAnswered, QuestionCancelled, QuestionRequest, QuestionRequested, QuestionToolParams, SubagentCompleted, SubagentStarted, ToolApprovalDenied, ToolApprovalGranted, ToolApprovalRequest, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UsageUpdate, addAgentUsage, assistantHostToolCalls, contentParts, contentPreview, formatQuestionResponseContent, makeSubagentRunId, zeroAgentUsage } from "@yolk-sdk/agent/protocol";
|
|
10
10
|
//#region src/loop/run.ts
|
|
11
11
|
const questionToolName = "question";
|
|
12
12
|
const objectField = (input, key) => input !== null && typeof input === "object" ? Object.getOwnPropertyDescriptor(input, key)?.value : void 0;
|
|
@@ -20,7 +20,7 @@ const taskCallMetadata = (call) => {
|
|
|
20
20
|
const description = nonEmptyStringField(call.params, "description");
|
|
21
21
|
if (subagentType === void 0 || description === void 0) return;
|
|
22
22
|
return {
|
|
23
|
-
subagentRunId:
|
|
23
|
+
subagentRunId: makeSubagentRunId(call.id),
|
|
24
24
|
subagentType,
|
|
25
25
|
description
|
|
26
26
|
};
|
|
@@ -59,6 +59,7 @@ const validateContent = (message, capabilities) => Effect.forEach(contentPartsFr
|
|
|
59
59
|
switch (part._tag) {
|
|
60
60
|
case "Text": return capabilities.input.text ? Effect.void : Effect.fail(unsupportedInputError("Text input is not supported by this model"));
|
|
61
61
|
case "Image": return capabilities.input.image ? Effect.void : Effect.fail(unsupportedInputError("Image input is not supported by this model"));
|
|
62
|
+
case "Document": return capabilities.input.document ? Effect.void : Effect.fail(unsupportedInputError("Document input is not supported by this model"));
|
|
62
63
|
case "Audio": return capabilities.input.audio ? Effect.void : Effect.fail(unsupportedInputError("Audio input is not supported by this model"));
|
|
63
64
|
}
|
|
64
65
|
});
|
|
@@ -175,8 +176,8 @@ const toolDefFor = (tools, call) => tools.find((tool) => tool.name === call.name
|
|
|
175
176
|
const approvalRequired = (tools, call) => toolDefFor(tools, call)?.approval?.mode === "manual";
|
|
176
177
|
const approvalRequestId = (call) => `approval:${call.id}`;
|
|
177
178
|
const questionRequestId = (call) => `question:${call.id}`;
|
|
178
|
-
const matchesApproval = (response, call) => response.toolCallId === call.id
|
|
179
|
-
const matchesQuestion = (response, call) => response.toolCallId === call.id
|
|
179
|
+
const matchesApproval = (response, call) => response.toolCallId === call.id && response.requestId === approvalRequestId(call);
|
|
180
|
+
const matchesQuestion = (response, call) => response.toolCallId === call.id && response.requestId === questionRequestId(call);
|
|
180
181
|
const approvalResponseFor = (responses, call) => responses.flatMap((response) => response._tag === "ToolApprovalResponse" && matchesApproval(response, call) ? [response] : [])[0];
|
|
181
182
|
const questionResponseFor = (responses, call) => responses.flatMap((response) => response._tag === "QuestionResponse" && matchesQuestion(response, call) ? [response] : [])[0];
|
|
182
183
|
const toolApprovalRequest = (tools, call) => ToolApprovalRequest.make({
|