@yolk-sdk/agent 0.1.0-canary.19 → 0.1.0-canary.21
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 +25 -1
- package/dist/client/attachments.d.mts +8 -0
- package/dist/client/attachments.d.mts.map +1 -0
- package/dist/client/attachments.mjs +36 -0
- package/dist/client/attachments.mjs.map +1 -0
- package/dist/client/index.d.mts +2 -1
- package/dist/client/index.mjs +2 -1
- package/dist/client/state.d.mts +4 -2
- package/dist/client/state.d.mts.map +1 -1
- package/dist/client/state.mjs +42 -22
- package/dist/client/state.mjs.map +1 -1
- package/dist/client/transport.d.mts +1 -1
- package/dist/client/transport.mjs +1 -1
- package/dist/compaction/transformer.d.mts +1 -1
- package/dist/loop/error.d.mts +3 -2
- package/dist/loop/error.d.mts.map +1 -1
- package/dist/loop/error.mjs +6 -3
- package/dist/loop/error.mjs.map +1 -1
- package/dist/loop/llm-event.d.mts +1 -1
- package/dist/loop/llm-event.mjs +1 -1
- package/dist/loop/run.d.mts +1 -1
- package/dist/loop/run.d.mts.map +1 -1
- package/dist/loop/run.mjs +18 -4
- package/dist/loop/run.mjs.map +1 -1
- package/dist/loop/services/context-transformer.d.mts +1 -1
- package/dist/loop/services/llm-provider.d.mts +1 -1
- package/dist/loop/services/loop-config.mjs +1 -1
- package/dist/loop/services/loop-config.mjs.map +1 -1
- package/dist/loop/services/tool-executor.d.mts +1 -1
- package/dist/loop/testing/faux-provider.mjs +1 -1
- package/dist/loop/testing/test-tool-executor.mjs +1 -1
- package/dist/protocol/content.d.mts +15 -1
- package/dist/protocol/content.d.mts.map +1 -1
- package/dist/protocol/content.mjs +76 -1
- package/dist/protocol/content.mjs.map +1 -1
- package/dist/protocol/event.d.mts +17 -5
- package/dist/protocol/event.d.mts.map +1 -1
- package/dist/protocol/event.mjs +24 -3
- package/dist/protocol/event.mjs.map +1 -1
- package/dist/protocol/index.d.mts +3 -3
- package/dist/protocol/index.d.mts.map +1 -1
- package/dist/protocol/index.mjs +3 -3
- package/dist/providers/anthropic/claude-provider.d.mts.map +1 -1
- package/dist/providers/anthropic/claude-provider.mjs +48 -17
- package/dist/providers/anthropic/claude-provider.mjs.map +1 -1
- package/dist/providers/openai/codex-provider.d.mts +1 -1
- package/dist/providers/openai/codex-provider.d.mts.map +1 -1
- package/dist/providers/openai/codex-provider.mjs +60 -18
- package/dist/providers/openai/codex-provider.mjs.map +1 -1
- package/dist/providers/openai/provider.d.mts.map +1 -1
- package/dist/providers/openai/provider.mjs +28 -12
- package/dist/providers/openai/provider.mjs.map +1 -1
- package/dist/providers/provider-error.d.mts +32 -0
- package/dist/providers/provider-error.d.mts.map +1 -0
- package/dist/providers/provider-error.mjs +91 -0
- package/dist/providers/provider-error.mjs.map +1 -0
- package/dist/react/chat-core.d.mts +3 -1
- package/dist/react/chat-core.d.mts.map +1 -1
- package/dist/react/chat-core.mjs +42 -6
- package/dist/react/chat-core.mjs.map +1 -1
- package/dist/react/chat-items.d.mts +8 -2
- package/dist/react/chat-items.d.mts.map +1 -1
- package/dist/react/chat-items.mjs +17 -10
- package/dist/react/chat-items.mjs.map +1 -1
- package/dist/react/chat-messages.mjs +1 -1
- package/dist/react/chat-session-events.d.mts +1 -1
- package/dist/react/chat-session-events.mjs +1 -1
- package/dist/react/use-agent-chat.mjs +1 -1
- package/dist/runtime/error.d.mts +1 -1
- package/dist/runtime/error.mjs +1 -1
- package/dist/runtime/run-runtime.d.mts +1 -1
- package/dist/runtime/session-event-store.d.mts +1 -1
- package/dist/runtime/session-event-store.mjs +1 -1
- package/dist/tools/question.d.mts +1 -1
- package/dist/tools/question.mjs +1 -1
- package/dist/tools/registry.d.mts +1 -1
- package/dist/tools/registry.mjs +1 -1
- package/dist/tools/task.d.mts +1 -1
- package/dist/tools/task.mjs +1 -1
- package/dist/voice/tool-bridge.mjs +1 -1
- package/package.json +1 -1
- package/src/client/attachments.ts +45 -0
- package/src/client/index.ts +1 -0
- package/src/client/state.ts +43 -18
- package/src/loop/error.ts +6 -3
- package/src/loop/run.ts +27 -4
- package/src/loop/services/loop-config.ts +1 -1
- package/src/protocol/content.ts +129 -0
- package/src/protocol/event.ts +26 -2
- package/src/protocol/index.ts +8 -0
- package/src/providers/anthropic/claude-provider.ts +74 -23
- package/src/providers/openai/codex-provider.ts +81 -19
- package/src/providers/openai/provider.ts +45 -19
- package/src/providers/provider-error.ts +213 -0
- package/src/react/chat-core.ts +46 -5
- package/src/react/chat-items.ts +10 -3
package/README.md
CHANGED
|
@@ -22,7 +22,7 @@ Canary APIs are unstable. Keep all `@yolk-sdk/*` packages on the same version.
|
|
|
22
22
|
| `@yolk-sdk/agent/loop` | Stateless LLM/tool loop |
|
|
23
23
|
| `@yolk-sdk/agent/loop/testing` | Faux provider and tool executor test helpers |
|
|
24
24
|
| `@yolk-sdk/agent/runtime` | Transcript or append-backed runtime orchestration |
|
|
25
|
-
| `@yolk-sdk/agent/client` | HTTP/NDJSON transport, HITL resume,
|
|
25
|
+
| `@yolk-sdk/agent/client` | HTTP/NDJSON transport, HITL resume, retry/error state helpers |
|
|
26
26
|
| `@yolk-sdk/agent/compaction` | Pure host-owned context budget, planning, and transformer utils |
|
|
27
27
|
| `@yolk-sdk/agent/tools` | Tool module registry, `makeTool`, task/question tool contracts |
|
|
28
28
|
| `@yolk-sdk/agent/react` | Headless React chat hook, reducer, selectors, and render model |
|
|
@@ -43,6 +43,7 @@ Canary APIs are unstable. Keep all `@yolk-sdk/*` packages on the same version.
|
|
|
43
43
|
import {
|
|
44
44
|
hitlResponseEvent,
|
|
45
45
|
makeSubagentRunId,
|
|
46
|
+
ProviderErrorInfo,
|
|
46
47
|
questionResponseStructuredContent,
|
|
47
48
|
UserMessage
|
|
48
49
|
} from '@yolk-sdk/agent/protocol'
|
|
@@ -89,6 +90,24 @@ const program = run({
|
|
|
89
90
|
// Provide LLM provider, loop config, context transformer, and tool executor layers in the host app.
|
|
90
91
|
```
|
|
91
92
|
|
|
93
|
+
## Provider failures and retries
|
|
94
|
+
|
|
95
|
+
Provider adapters classify safe failure metadata at the boundary. The loop owns bounded retry
|
|
96
|
+
policy and emits protocol-visible retry/error state:
|
|
97
|
+
|
|
98
|
+
- `ProviderErrorInfo` carries safe provider id, failure kind, HTTP status, provider code, and
|
|
99
|
+
optional `retryAfterMs`.
|
|
100
|
+
- `AgentRetry.provider` exposes current retry metadata and chosen `delayMs`.
|
|
101
|
+
- `AgentError.provider` preserves final terminal metadata.
|
|
102
|
+
- `AgentErrorCode` includes `rate_limit`, `overloaded`, `context_overflow`, and generic
|
|
103
|
+
`provider_error`.
|
|
104
|
+
- Client and React state keep `error: string | null` for compatibility and add typed `errorInfo` /
|
|
105
|
+
`retryInfo`.
|
|
106
|
+
- `buildAgentChatItems` can project active retry state as an `AgentChatItem` with `_tag: 'Retry'`.
|
|
107
|
+
|
|
108
|
+
Raw provider response bodies stay out of protocol/UI. Hosts own durable persistence and display of
|
|
109
|
+
typed retry/error state.
|
|
110
|
+
|
|
92
111
|
## Context compaction
|
|
93
112
|
|
|
94
113
|
`@yolk-sdk/agent/compaction` provides pure scaffolding only. It does not call a model, persist
|
|
@@ -130,6 +149,10 @@ Build sources with `inlineBase64AttachmentSource`, `urlAttachmentSource`, or
|
|
|
130
149
|
for simple apps, or persist `Ref` values and call `resolveContentAttachmentSources` at your storage
|
|
131
150
|
boundary before provider execution. Host apps own upload, auth, retention, and ref hydration policy.
|
|
132
151
|
|
|
152
|
+
For text files, use `documentPartFromText`, `inferTextDocumentMimeType`, and the client helper
|
|
153
|
+
`documentPartFromTextFile` to create UTF-8 inline `DocumentPart` values without trusting filename
|
|
154
|
+
extensions over explicit non-text MIME types.
|
|
155
|
+
|
|
133
156
|
Use model capabilities like `textOnlyModelCapabilities`, `textImageModelCapabilities`, or
|
|
134
157
|
`textImageDocumentModelCapabilities` so the loop rejects unsupported inputs before provider calls.
|
|
135
158
|
|
|
@@ -216,6 +239,7 @@ defects, storage failures, or implementation bugs.
|
|
|
216
239
|
|
|
217
240
|
- Choose models/providers and map provider streams into protocol events.
|
|
218
241
|
- Persist sessions, transcripts, and append logs.
|
|
242
|
+
- Persist terminal provider failures and clear active run ids where applicable.
|
|
219
243
|
- Provide tools, approval policy, auth, storage, and observability.
|
|
220
244
|
- Compact context and decide memory/search policy.
|
|
221
245
|
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
//#region src/client/attachments.d.ts
|
|
2
|
+
declare const textFromBlob: (blob: Blob) => Promise<string>;
|
|
3
|
+
declare const documentPartFromTextFile: (file: File, options?: {
|
|
4
|
+
readonly title?: string;
|
|
5
|
+
}) => Promise<import("@yolk-sdk/agent/protocol").DocumentPart | undefined>;
|
|
6
|
+
//#endregion
|
|
7
|
+
export { documentPartFromTextFile, textFromBlob };
|
|
8
|
+
//# sourceMappingURL=attachments.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attachments.d.mts","names":[],"sources":["../../src/client/attachments.ts"],"mappings":";cAEa,YAAA,GAAgB,IAAA,EAAM,IAAA,KAAI,OAAA;AAAA,cAqB1B,wBAAA,GACX,IAAA,EAAM,IAAA,EACN,OAAA;EAAA,SACW,KAAA;AAAA,MACV,OAAA,oCAAA,YAAA"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { documentPartFromText, inferTextDocumentMimeType } from "@yolk-sdk/agent/protocol";
|
|
2
|
+
//#region src/client/attachments.ts
|
|
3
|
+
const textFromBlob = (blob) => {
|
|
4
|
+
if (typeof blob.text === "function") return blob.text();
|
|
5
|
+
if (typeof FileReader === "undefined") return Promise.reject(/* @__PURE__ */ new Error("Could not read text"));
|
|
6
|
+
return new Promise((resolve, reject) => {
|
|
7
|
+
const reader = new FileReader();
|
|
8
|
+
reader.addEventListener("load", () => {
|
|
9
|
+
if (typeof reader.result === "string") {
|
|
10
|
+
resolve(reader.result);
|
|
11
|
+
return;
|
|
12
|
+
}
|
|
13
|
+
reject(/* @__PURE__ */ new Error("Could not read text"));
|
|
14
|
+
});
|
|
15
|
+
reader.addEventListener("error", () => reject(/* @__PURE__ */ new Error("Could not read text")));
|
|
16
|
+
reader.addEventListener("abort", () => reject(/* @__PURE__ */ new Error("Could not read text")));
|
|
17
|
+
reader.readAsText(blob);
|
|
18
|
+
});
|
|
19
|
+
};
|
|
20
|
+
const documentPartFromTextFile = async (file, options) => {
|
|
21
|
+
const mimeType = inferTextDocumentMimeType({
|
|
22
|
+
filename: file.name,
|
|
23
|
+
mimeType: file.type
|
|
24
|
+
});
|
|
25
|
+
if (mimeType === void 0) return void 0;
|
|
26
|
+
return documentPartFromText({
|
|
27
|
+
text: await textFromBlob(file),
|
|
28
|
+
filename: file.name,
|
|
29
|
+
mimeType,
|
|
30
|
+
title: options?.title
|
|
31
|
+
});
|
|
32
|
+
};
|
|
33
|
+
//#endregion
|
|
34
|
+
export { documentPartFromTextFile, textFromBlob };
|
|
35
|
+
|
|
36
|
+
//# sourceMappingURL=attachments.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attachments.mjs","names":[],"sources":["../../src/client/attachments.ts"],"sourcesContent":["import { documentPartFromText, inferTextDocumentMimeType } from '@yolk-sdk/agent/protocol'\n\nexport const textFromBlob = (blob: Blob) => {\n if (typeof blob.text === 'function') return blob.text()\n if (typeof FileReader === 'undefined') return Promise.reject(new Error('Could not read text'))\n\n return new Promise<string>((resolve, reject) => {\n const reader = new FileReader()\n\n reader.addEventListener('load', () => {\n if (typeof reader.result === 'string') {\n resolve(reader.result)\n return\n }\n\n reject(new Error('Could not read text'))\n })\n reader.addEventListener('error', () => reject(new Error('Could not read text')))\n reader.addEventListener('abort', () => reject(new Error('Could not read text')))\n reader.readAsText(blob)\n })\n}\n\nexport const documentPartFromTextFile = async (\n file: File,\n options?: {\n readonly title?: string\n }\n) => {\n const mimeType = inferTextDocumentMimeType({\n filename: file.name,\n mimeType: file.type\n })\n\n if (mimeType === undefined) return undefined\n\n const text = await textFromBlob(file)\n\n return documentPartFromText({\n text,\n filename: file.name,\n mimeType,\n title: options?.title\n })\n}\n"],"mappings":";;AAEA,MAAa,gBAAgB,SAAe;CAC1C,IAAI,OAAO,KAAK,SAAS,YAAY,OAAO,KAAK,KAAK;CACtD,IAAI,OAAO,eAAe,aAAa,OAAO,QAAQ,uBAAO,IAAI,MAAM,qBAAqB,CAAC;CAE7F,OAAO,IAAI,SAAiB,SAAS,WAAW;EAC9C,MAAM,SAAS,IAAI,WAAW;EAE9B,OAAO,iBAAiB,cAAc;GACpC,IAAI,OAAO,OAAO,WAAW,UAAU;IACrC,QAAQ,OAAO,MAAM;IACrB;GACF;GAEA,uBAAO,IAAI,MAAM,qBAAqB,CAAC;EACzC,CAAC;EACD,OAAO,iBAAiB,eAAe,uBAAO,IAAI,MAAM,qBAAqB,CAAC,CAAC;EAC/E,OAAO,iBAAiB,eAAe,uBAAO,IAAI,MAAM,qBAAqB,CAAC,CAAC;EAC/E,OAAO,WAAW,IAAI;CACxB,CAAC;AACH;AAEA,MAAa,2BAA2B,OACtC,MACA,YAGG;CACH,MAAM,WAAW,0BAA0B;EACzC,UAAU,KAAK;EACf,UAAU,KAAK;CACjB,CAAC;CAED,IAAI,aAAa,KAAA,GAAW,OAAO,KAAA;CAInC,OAAO,qBAAqB;EAC1B,MAAA,MAHiB,aAAa,IAAI;EAIlC,UAAU,KAAK;EACf;EACA,OAAO,SAAS;CAClB,CAAC;AACH"}
|
package/dist/client/index.d.mts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { documentPartFromTextFile, textFromBlob } from "./attachments.mjs";
|
|
1
2
|
import { AgentClientState, AgentRunStatus, AgentToolRun, AgentTranscript, ApplyAgentEventOptions, appendAgentMessage, applyAgentEvent, completedToolRuns, initialAgentClientState, isActiveToolRun, markAgentAborted, markAgentError, reduceAgentEvents, submitAgentUserMessage, toolRunsFromHitlRequests } from "./state.mjs";
|
|
2
3
|
import { AgentHttpResponseInfo, AgentTransportError, CancelAgentRunRequest, StreamAgentEventsRequest, StreamAgentRunEventsRequest, StreamCloudflareAgentEventsRequest, SubmitQuestionResponseRequest, SubmitToolApprovalResponseRequest, cancelAgentRun, collectAgentEvents, collectAgentEventsEffect, streamAgentEventStream, streamAgentEvents, streamAgentRunEventStream, streamAgentRunEvents, streamCloudflareAgentEventStream, streamCloudflareAgentEvents, streamQuestionResponseEventStream, streamToolApprovalResponseEventStream, submitQuestionResponse, submitToolApprovalResponse } from "./transport.mjs";
|
|
3
|
-
export { type AgentClientState, type AgentHttpResponseInfo, type AgentRunStatus, type AgentToolRun, type AgentTranscript, AgentTransportError, type ApplyAgentEventOptions, type CancelAgentRunRequest, type StreamAgentEventsRequest, type StreamAgentRunEventsRequest, type StreamCloudflareAgentEventsRequest, type SubmitQuestionResponseRequest, type SubmitToolApprovalResponseRequest, appendAgentMessage, applyAgentEvent, cancelAgentRun, collectAgentEvents, collectAgentEventsEffect, completedToolRuns, initialAgentClientState, isActiveToolRun, markAgentAborted, markAgentError, reduceAgentEvents, streamAgentEventStream, streamAgentEvents, streamAgentRunEventStream, streamAgentRunEvents, streamCloudflareAgentEventStream, streamCloudflareAgentEvents, streamQuestionResponseEventStream, streamToolApprovalResponseEventStream, submitAgentUserMessage, submitQuestionResponse, submitToolApprovalResponse, toolRunsFromHitlRequests };
|
|
4
|
+
export { type AgentClientState, type AgentHttpResponseInfo, type AgentRunStatus, type AgentToolRun, type AgentTranscript, AgentTransportError, type ApplyAgentEventOptions, type CancelAgentRunRequest, type StreamAgentEventsRequest, type StreamAgentRunEventsRequest, type StreamCloudflareAgentEventsRequest, type SubmitQuestionResponseRequest, type SubmitToolApprovalResponseRequest, appendAgentMessage, applyAgentEvent, cancelAgentRun, collectAgentEvents, collectAgentEventsEffect, completedToolRuns, documentPartFromTextFile, initialAgentClientState, isActiveToolRun, markAgentAborted, markAgentError, reduceAgentEvents, streamAgentEventStream, streamAgentEvents, streamAgentRunEventStream, streamAgentRunEvents, streamCloudflareAgentEventStream, streamCloudflareAgentEvents, streamQuestionResponseEventStream, streamToolApprovalResponseEventStream, submitAgentUserMessage, submitQuestionResponse, submitToolApprovalResponse, textFromBlob, toolRunsFromHitlRequests };
|
package/dist/client/index.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { documentPartFromTextFile, textFromBlob } from "./attachments.mjs";
|
|
1
2
|
import { appendAgentMessage, applyAgentEvent, completedToolRuns, initialAgentClientState, isActiveToolRun, markAgentAborted, markAgentError, reduceAgentEvents, submitAgentUserMessage, toolRunsFromHitlRequests } from "./state.mjs";
|
|
2
3
|
import { AgentTransportError, cancelAgentRun, collectAgentEvents, collectAgentEventsEffect, streamAgentEventStream, streamAgentEvents, streamAgentRunEventStream, streamAgentRunEvents, streamCloudflareAgentEventStream, streamCloudflareAgentEvents, streamQuestionResponseEventStream, streamToolApprovalResponseEventStream, submitQuestionResponse, submitToolApprovalResponse } from "./transport.mjs";
|
|
3
|
-
export { AgentTransportError, appendAgentMessage, applyAgentEvent, cancelAgentRun, collectAgentEvents, collectAgentEventsEffect, completedToolRuns, initialAgentClientState, isActiveToolRun, markAgentAborted, markAgentError, reduceAgentEvents, streamAgentEventStream, streamAgentEvents, streamAgentRunEventStream, streamAgentRunEvents, streamCloudflareAgentEventStream, streamCloudflareAgentEvents, streamQuestionResponseEventStream, streamToolApprovalResponseEventStream, submitAgentUserMessage, submitQuestionResponse, submitToolApprovalResponse, toolRunsFromHitlRequests };
|
|
4
|
+
export { AgentTransportError, appendAgentMessage, applyAgentEvent, cancelAgentRun, collectAgentEvents, collectAgentEventsEffect, completedToolRuns, documentPartFromTextFile, initialAgentClientState, isActiveToolRun, markAgentAborted, markAgentError, reduceAgentEvents, streamAgentEventStream, streamAgentEvents, streamAgentRunEventStream, streamAgentRunEvents, streamCloudflareAgentEventStream, streamCloudflareAgentEvents, streamQuestionResponseEventStream, streamToolApprovalResponseEventStream, submitAgentUserMessage, submitQuestionResponse, submitToolApprovalResponse, textFromBlob, toolRunsFromHitlRequests };
|
package/dist/client/state.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AgentEvent, AgentMessage, HitlRequest, QuestionRequest, QuestionResponse, ToolApprovalRequest, ToolCall, ToolResult, UserMessage } from "@yolk-sdk/agent/protocol";
|
|
1
|
+
import { AgentError, AgentEvent, AgentMessage, AgentRetry, HitlRequest, QuestionRequest, QuestionResponse, ToolApprovalRequest, ToolCall, ToolResult, UserMessage } from "@yolk-sdk/agent/protocol";
|
|
2
2
|
|
|
3
3
|
//#region src/client/state.d.ts
|
|
4
4
|
type AgentRunStatus = 'idle' | 'running' | 'waiting' | 'done' | 'error' | 'aborted';
|
|
@@ -57,6 +57,8 @@ type AgentClientState = {
|
|
|
57
57
|
readonly reasoning: string;
|
|
58
58
|
readonly toolRuns: ReadonlyArray<AgentToolRun>;
|
|
59
59
|
readonly error: string | null;
|
|
60
|
+
readonly errorInfo: AgentError | null;
|
|
61
|
+
readonly retryInfo: AgentRetry | null;
|
|
60
62
|
readonly seenEventIds: ReadonlyArray<string>;
|
|
61
63
|
};
|
|
62
64
|
type ApplyAgentEventOptions = {
|
|
@@ -96,7 +98,7 @@ declare const appendAgentMessage: (messages: ReadonlyArray<AgentMessage>, messag
|
|
|
96
98
|
declare const applyAgentEvent: (state: AgentClientState, event: AgentEvent) => AgentClientState;
|
|
97
99
|
declare const applyAgentEventWithOptions: (state: AgentClientState, event: AgentEvent, options?: ApplyAgentEventOptions) => AgentClientState;
|
|
98
100
|
declare const submitAgentUserMessage: (state: AgentClientState, message: UserMessage) => AgentClientState;
|
|
99
|
-
declare const markAgentError: (state: AgentClientState, message?: string) => AgentClientState;
|
|
101
|
+
declare const markAgentError: (state: AgentClientState, message?: string, errorInfo?: AgentError | null) => AgentClientState;
|
|
100
102
|
declare const markAgentAborted: (state: AgentClientState) => AgentClientState;
|
|
101
103
|
declare const reduceAgentEvents: (events: ReadonlyArray<AgentEvent>, initialState?: AgentClientState, options?: ApplyAgentEventOptions) => AgentClientState;
|
|
102
104
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.d.mts","names":[],"sources":["../../src/client/state.ts"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"state.d.mts","names":[],"sources":["../../src/client/state.ts"],"mappings":";;;KAcY,cAAA;AAAA,KAEA,YAAA;EAAA,SAEG,IAAA;EAAA,SACA,EAAA;EAAA,SACA,IAAA;EAAA,SACA,KAAA;AAAA;EAAA,SAEA,IAAA;EAAA,SAA6B,IAAA,EAAM,QAAA;AAAA;EAAA,SAEnC,IAAA;EAAA,SACA,IAAA,EAAM,QAAA;EAAA,SACN,OAAA,GAAU,mBAAA;AAAA;EAAA,SAEV,IAAA;EAAA,SAAyB,UAAA;EAAA,SAA6B,MAAA;AAAA;EAAA,SACtD,IAAA;EAAA,SAAoC,OAAA,EAAS,eAAA;AAAA;EAAA,SAE7C,IAAA;EAAA,SACA,QAAA,EAAU,gBAAA;EAAA,SACV,OAAA,GAAU,eAAA;AAAA;EAAA,SAGV,IAAA;EAAA,SACA,QAAA,EAAU,gBAAA;EAAA,SACV,OAAA,GAAU,eAAA;AAAA;EAAA,SAEV,IAAA;EAAA,SAA4B,IAAA,EAAM,QAAA;EAAA,SAAmB,WAAA;AAAA;EAAA,SAErD,IAAA;EAAA,SACA,IAAA,EAAM,QAAA;EAAA,SACN,MAAA,EAAQ,UAAA;EAAA,SACR,WAAA;EAAA,SACA,SAAA;AAAA;EAAA,SAGA,IAAA;EAAA,SACA,IAAA,EAAM,QAAA;EAAA,SACN,OAAA;EAAA,SACA,SAAA;AAAA;EAAA,SAEA,IAAA;EAAA,SAAoC,IAAA,EAAM,QAAA;EAAA,SAAmB,MAAA,EAAQ,UAAA;AAAA;AAAA,KAIxE,gBAAA;EAAA,SACD,MAAA,EAAQ,cAAA;EAAA,SACR,QAAA,EAAU,aAAA,CAAc,YAAA;EAAA,SACxB,YAAA,EAAc,aAAA,CAAc,YAAA;EAAA,SAC5B,IAAA;EAAA,SACA,SAAA;EAAA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,OAAA,GAAS,sBAAA,KAA2B,gBAAA"}
|
package/dist/client/state.mjs
CHANGED
|
@@ -7,8 +7,14 @@ const initialAgentClientState = {
|
|
|
7
7
|
reasoning: "",
|
|
8
8
|
toolRuns: [],
|
|
9
9
|
error: null,
|
|
10
|
+
errorInfo: null,
|
|
11
|
+
retryInfo: null,
|
|
10
12
|
seenEventIds: []
|
|
11
13
|
};
|
|
14
|
+
const clearRetryInfo = (state) => state.retryInfo === null ? state : {
|
|
15
|
+
...state,
|
|
16
|
+
retryInfo: null
|
|
17
|
+
};
|
|
12
18
|
const hasSeenEvent = (state, event) => event.eventId !== void 0 && state.seenEventIds.includes(event.eventId);
|
|
13
19
|
const rememberEvent = (state, event) => event.eventId === void 0 ? state : {
|
|
14
20
|
...state,
|
|
@@ -117,18 +123,20 @@ const applyAgentEventUnchecked = (state, event, nowMs) => {
|
|
|
117
123
|
reasoning: "",
|
|
118
124
|
liveMessages: [],
|
|
119
125
|
toolRuns: completedToolRuns(state.toolRuns),
|
|
120
|
-
error: null
|
|
126
|
+
error: null,
|
|
127
|
+
errorInfo: null,
|
|
128
|
+
retryInfo: null
|
|
121
129
|
};
|
|
122
|
-
case "AgentError": return markAgentError(state, event.message);
|
|
123
|
-
case "LLMTextDelta": return {
|
|
130
|
+
case "AgentError": return markAgentError(state, event.message, event);
|
|
131
|
+
case "LLMTextDelta": return clearRetryInfo({
|
|
124
132
|
...state,
|
|
125
133
|
text: `${state.text}${event.text}`
|
|
126
|
-
};
|
|
127
|
-
case "LLMReasoningDelta": return {
|
|
134
|
+
});
|
|
135
|
+
case "LLMReasoningDelta": return clearRetryInfo({
|
|
128
136
|
...state,
|
|
129
137
|
reasoning: `${state.reasoning}${event.text}`
|
|
130
|
-
};
|
|
131
|
-
case "ToolInputStart": return {
|
|
138
|
+
});
|
|
139
|
+
case "ToolInputStart": return clearRetryInfo({
|
|
132
140
|
...state,
|
|
133
141
|
toolRuns: replaceToolRun(state.toolRuns, {
|
|
134
142
|
_tag: "InputStreaming",
|
|
@@ -136,18 +144,18 @@ const applyAgentEventUnchecked = (state, event, nowMs) => {
|
|
|
136
144
|
name: event.name,
|
|
137
145
|
input: ""
|
|
138
146
|
})
|
|
139
|
-
};
|
|
140
|
-
case "ToolInputDelta": return {
|
|
147
|
+
});
|
|
148
|
+
case "ToolInputDelta": return clearRetryInfo({
|
|
141
149
|
...state,
|
|
142
150
|
toolRuns: appendToolInputDelta(state.toolRuns, event.id, event.delta)
|
|
143
|
-
};
|
|
144
|
-
case "ToolInputEnd": return {
|
|
151
|
+
});
|
|
152
|
+
case "ToolInputEnd": return clearRetryInfo({
|
|
145
153
|
...state,
|
|
146
154
|
toolRuns: replaceToolRun(state.toolRuns, {
|
|
147
155
|
_tag: "InputReady",
|
|
148
156
|
call: event.call
|
|
149
157
|
})
|
|
150
|
-
};
|
|
158
|
+
});
|
|
151
159
|
case "ToolApprovalRequested": return {
|
|
152
160
|
...state,
|
|
153
161
|
toolRuns: replaceToolRun(state.toolRuns, {
|
|
@@ -211,20 +219,20 @@ const applyAgentEventUnchecked = (state, event, nowMs) => {
|
|
|
211
219
|
endedAtMs: nowMs
|
|
212
220
|
})
|
|
213
221
|
};
|
|
214
|
-
case "ProviderToolResult": return {
|
|
222
|
+
case "ProviderToolResult": return clearRetryInfo({
|
|
215
223
|
...state,
|
|
216
224
|
toolRuns: replaceToolRun(state.toolRuns, {
|
|
217
225
|
_tag: "ProviderCompleted",
|
|
218
226
|
call: event.call,
|
|
219
227
|
result: event.result
|
|
220
228
|
})
|
|
221
|
-
};
|
|
222
|
-
case "AssistantMessage": return {
|
|
229
|
+
});
|
|
230
|
+
case "AssistantMessage": return clearRetryInfo({
|
|
223
231
|
...state,
|
|
224
232
|
liveMessages: [...state.liveMessages, event.message],
|
|
225
233
|
text: "",
|
|
226
234
|
reasoning: ""
|
|
227
|
-
};
|
|
235
|
+
});
|
|
228
236
|
case "AgentEnd": return {
|
|
229
237
|
...state,
|
|
230
238
|
status: "done",
|
|
@@ -232,7 +240,8 @@ const applyAgentEventUnchecked = (state, event, nowMs) => {
|
|
|
232
240
|
liveMessages: [],
|
|
233
241
|
text: "",
|
|
234
242
|
reasoning: "",
|
|
235
|
-
toolRuns: completedToolRuns(state.toolRuns)
|
|
243
|
+
toolRuns: completedToolRuns(state.toolRuns),
|
|
244
|
+
retryInfo: null
|
|
236
245
|
};
|
|
237
246
|
case "AgentAwaitingInput": return {
|
|
238
247
|
...state,
|
|
@@ -241,9 +250,14 @@ const applyAgentEventUnchecked = (state, event, nowMs) => {
|
|
|
241
250
|
liveMessages: [],
|
|
242
251
|
text: "",
|
|
243
252
|
reasoning: "",
|
|
244
|
-
error: null
|
|
253
|
+
error: null,
|
|
254
|
+
errorInfo: null,
|
|
255
|
+
retryInfo: null
|
|
256
|
+
};
|
|
257
|
+
case "AgentRetry": return {
|
|
258
|
+
...state,
|
|
259
|
+
retryInfo: event
|
|
245
260
|
};
|
|
246
|
-
case "AgentRetry":
|
|
247
261
|
case "CompactionEnd":
|
|
248
262
|
case "CompactionStart":
|
|
249
263
|
case "LLMStreamEnd":
|
|
@@ -264,19 +278,25 @@ const submitAgentUserMessage = (state, message) => ({
|
|
|
264
278
|
reasoning: "",
|
|
265
279
|
toolRuns: completedToolRuns(state.toolRuns),
|
|
266
280
|
error: null,
|
|
281
|
+
errorInfo: null,
|
|
282
|
+
retryInfo: null,
|
|
267
283
|
seenEventIds: []
|
|
268
284
|
});
|
|
269
|
-
const markAgentError = (state, message = "Agent request failed") => ({
|
|
285
|
+
const markAgentError = (state, message = "Agent request failed", errorInfo = null) => ({
|
|
270
286
|
...state,
|
|
271
287
|
status: "error",
|
|
272
288
|
toolRuns: completedToolRuns(state.toolRuns),
|
|
273
|
-
error: message
|
|
289
|
+
error: message,
|
|
290
|
+
errorInfo,
|
|
291
|
+
retryInfo: null
|
|
274
292
|
});
|
|
275
293
|
const markAgentAborted = (state) => ({
|
|
276
294
|
...state,
|
|
277
295
|
status: "aborted",
|
|
278
296
|
toolRuns: completedToolRuns(state.toolRuns),
|
|
279
|
-
error: null
|
|
297
|
+
error: null,
|
|
298
|
+
errorInfo: null,
|
|
299
|
+
retryInfo: null
|
|
280
300
|
});
|
|
281
301
|
const reduceAgentEvents = (events, initialState = initialAgentClientState, options = {}) => events.reduce((state, event) => applyAgentEventWithOptions(state, event, options), initialState);
|
|
282
302
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.mjs","names":[],"sources":["../../src/client/state.ts"],"sourcesContent":["import {\n type AgentEvent,\n type AgentMessage,\n type HitlRequest,\n type QuestionRequest,\n type QuestionResponse,\n type ToolCall,\n type ToolApprovalRequest,\n type ToolResult,\n type UserMessage\n} from '@yolk-sdk/agent/protocol'\n\nexport type AgentRunStatus = 'idle' | 'running' | 'waiting' | 'done' | 'error' | 'aborted'\n\nexport type AgentToolRun =\n | {\n readonly _tag: 'InputStreaming'\n readonly id: string\n readonly name?: string\n readonly input: string\n }\n | { readonly _tag: 'InputReady'; readonly call: ToolCall }\n | {\n readonly _tag: 'ApprovalRequested'\n readonly call: ToolCall\n readonly request?: ToolApprovalRequest\n }\n | { readonly _tag: 'Denied'; readonly toolCallId: string; readonly reason: string }\n | { readonly _tag: 'QuestionRequested'; readonly request: QuestionRequest }\n | {\n readonly _tag: 'QuestionAnswered'\n readonly response: QuestionResponse\n readonly request?: QuestionRequest\n }\n | {\n readonly _tag: 'QuestionCancelled'\n readonly response: QuestionResponse\n readonly request?: QuestionRequest\n }\n | { readonly _tag: 'Executing'; readonly call: ToolCall; readonly startedAtMs: number }\n | {\n readonly _tag: 'Completed'\n readonly call: ToolCall\n readonly result: ToolResult\n readonly startedAtMs: number\n readonly endedAtMs: number\n }\n | {\n readonly _tag: 'Errored'\n readonly call: ToolCall\n readonly message: string\n readonly endedAtMs: number\n }\n | { readonly _tag: 'ProviderCompleted'; readonly call: ToolCall; readonly result: ToolResult }\n\ntype StartedAgentToolRun = Extract<AgentToolRun, { readonly _tag: 'Executing' | 'Completed' }>\n\nexport type AgentClientState = {\n readonly status: AgentRunStatus\n readonly messages: ReadonlyArray<AgentMessage>\n readonly liveMessages: ReadonlyArray<AgentMessage>\n readonly text: string\n readonly reasoning: string\n readonly toolRuns: ReadonlyArray<AgentToolRun>\n readonly error: string | null\n readonly seenEventIds: ReadonlyArray<string>\n}\n\nexport type ApplyAgentEventOptions = {\n readonly nowMs?: number\n}\n\nexport type AgentTranscript = readonly [AgentMessage, ...Array<AgentMessage>]\n\nexport const initialAgentClientState: AgentClientState = {\n status: 'idle',\n messages: [],\n liveMessages: [],\n text: '',\n reasoning: '',\n toolRuns: [],\n error: null,\n seenEventIds: []\n}\n\nconst hasSeenEvent = (state: AgentClientState, event: AgentEvent) =>\n event.eventId !== undefined && state.seenEventIds.includes(event.eventId)\n\nconst rememberEvent = (state: AgentClientState, event: AgentEvent): AgentClientState =>\n event.eventId === undefined\n ? state\n : { ...state, seenEventIds: [...state.seenEventIds, event.eventId] }\n\nconst toolRunId = (run: AgentToolRun) => {\n switch (run._tag) {\n case 'InputStreaming':\n return run.id\n case 'Denied':\n return run.toolCallId\n case 'QuestionRequested':\n return run.request.toolCallId\n case 'QuestionAnswered':\n case 'QuestionCancelled':\n return run.response.toolCallId\n case 'InputReady':\n case 'ApprovalRequested':\n case 'Executing':\n case 'Completed':\n case 'Errored':\n case 'ProviderCompleted':\n return run.call.id\n }\n}\n\nexport const isActiveToolRun = (run: AgentToolRun) =>\n run._tag !== 'Completed' &&\n run._tag !== 'Errored' &&\n run._tag !== 'Denied' &&\n run._tag !== 'QuestionAnswered' &&\n run._tag !== 'QuestionCancelled' &&\n run._tag !== 'ProviderCompleted'\n\nexport const completedToolRuns = (runs: ReadonlyArray<AgentToolRun>) =>\n runs.filter(run => run._tag === 'Completed')\n\nexport const toolRunsFromHitlRequests = (\n requests: ReadonlyArray<HitlRequest>\n): ReadonlyArray<AgentToolRun> =>\n requests.map(request => {\n switch (request._tag) {\n case 'QuestionRequest':\n return { _tag: 'QuestionRequested', request }\n case 'ToolApprovalRequest':\n return { _tag: 'ApprovalRequested', call: request.call, request }\n }\n })\n\nconst replaceToolRun = (\n runs: ReadonlyArray<AgentToolRun>,\n run: AgentToolRun\n): ReadonlyArray<AgentToolRun> => {\n const id = toolRunId(run)\n const replaceIndex = runs.findIndex(current => toolRunId(current) === id)\n\n if (replaceIndex === -1) {\n return [...runs, run]\n }\n\n return runs.flatMap((current, index) => {\n if (toolRunId(current) !== id) {\n return [current]\n }\n\n return index === replaceIndex ? [run] : []\n })\n}\n\nconst isStartedToolRun = (run: AgentToolRun): run is StartedAgentToolRun =>\n run._tag === 'Executing' || run._tag === 'Completed'\n\nconst startedAtMsFor = (runs: ReadonlyArray<AgentToolRun>, toolCallId: string) =>\n runs.filter(isStartedToolRun).find(run => run.call.id === toolCallId)?.startedAtMs\n\nconst appendToolInputDelta = (\n runs: ReadonlyArray<AgentToolRun>,\n id: string,\n delta: string\n): ReadonlyArray<AgentToolRun> =>\n runs.map(run =>\n run._tag === 'InputStreaming' && run.id === id ? { ...run, input: `${run.input}${delta}` } : run\n )\n\nconst questionRequestForToolCall = (\n runs: ReadonlyArray<AgentToolRun>,\n toolCallId: string\n): QuestionRequest | undefined =>\n runs.flatMap(run => {\n if (toolRunId(run) !== toolCallId) {\n return []\n }\n\n switch (run._tag) {\n case 'QuestionRequested':\n return [run.request]\n case 'QuestionAnswered':\n case 'QuestionCancelled':\n return run.request === undefined ? [] : [run.request]\n case 'InputStreaming':\n case 'InputReady':\n case 'ApprovalRequested':\n case 'Denied':\n case 'Executing':\n case 'Completed':\n case 'Errored':\n case 'ProviderCompleted':\n return []\n }\n })[0]\n\nconst questionAnsweredRun = (\n response: QuestionResponse,\n request: QuestionRequest | undefined\n): AgentToolRun =>\n request === undefined\n ? { _tag: 'QuestionAnswered', response }\n : { _tag: 'QuestionAnswered', response, request }\n\nconst questionCancelledRun = (\n response: QuestionResponse,\n request: QuestionRequest | undefined\n): AgentToolRun =>\n request === undefined\n ? { _tag: 'QuestionCancelled', response }\n : { _tag: 'QuestionCancelled', response, request }\n\nexport const appendAgentMessage = (\n messages: ReadonlyArray<AgentMessage>,\n message: AgentMessage\n): AgentTranscript => {\n const first = messages[0]\n\n if (first === undefined) {\n return [message]\n }\n\n return [first, ...messages.slice(1), message]\n}\n\nexport const applyAgentEvent = (state: AgentClientState, event: AgentEvent): AgentClientState => {\n const nowMs = 0\n\n return applyAgentEventWithOptions(state, event, { nowMs })\n}\n\nexport const applyAgentEventWithOptions = (\n state: AgentClientState,\n event: AgentEvent,\n options: ApplyAgentEventOptions = {}\n): AgentClientState => {\n const nowMs = options.nowMs ?? 0\n\n if (hasSeenEvent(state, event)) {\n return state\n }\n\n return rememberEvent(applyAgentEventUnchecked(state, event, nowMs), event)\n}\n\nconst applyAgentEventUnchecked = (\n state: AgentClientState,\n event: AgentEvent,\n nowMs: number\n): AgentClientState => {\n switch (event._tag) {\n case 'AgentStart':\n return {\n ...state,\n status: 'running',\n text: '',\n reasoning: '',\n liveMessages: [],\n toolRuns: completedToolRuns(state.toolRuns),\n error: null\n }\n case 'AgentError':\n return markAgentError(state, event.message)\n case 'LLMTextDelta':\n return { ...state, text: `${state.text}${event.text}` }\n case 'LLMReasoningDelta':\n return { ...state, reasoning: `${state.reasoning}${event.text}` }\n case 'ToolInputStart':\n return {\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'InputStreaming',\n id: event.id,\n name: event.name,\n input: ''\n })\n }\n case 'ToolInputDelta':\n return { ...state, toolRuns: appendToolInputDelta(state.toolRuns, event.id, event.delta) }\n case 'ToolInputEnd':\n return {\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, { _tag: 'InputReady', call: event.call })\n }\n case 'ToolApprovalRequested':\n return {\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'ApprovalRequested',\n call: event.call,\n request: event.request\n })\n }\n case 'ToolApprovalGranted':\n return state\n case 'ToolApprovalDenied':\n return {\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'Denied',\n toolCallId: event.toolCallId,\n reason: event.reason\n })\n }\n case 'QuestionRequested':\n return {\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'QuestionRequested',\n request: event.request\n })\n }\n case 'QuestionAnswered':\n return {\n ...state,\n toolRuns: replaceToolRun(\n state.toolRuns,\n questionAnsweredRun(\n event.response,\n questionRequestForToolCall(state.toolRuns, event.response.toolCallId)\n )\n )\n }\n case 'QuestionCancelled':\n return {\n ...state,\n toolRuns: replaceToolRun(\n state.toolRuns,\n questionCancelledRun(\n event.response,\n questionRequestForToolCall(state.toolRuns, event.response.toolCallId)\n )\n )\n }\n case 'ToolExecutionStarted':\n return {\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'Executing',\n call: event.call,\n startedAtMs: nowMs\n })\n }\n case 'ToolExecutionCompleted': {\n const endedAtMs = nowMs\n const startedAtMs = startedAtMsFor(state.toolRuns, event.call.id) ?? endedAtMs\n\n return {\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'Completed',\n call: event.call,\n result: event.result,\n startedAtMs,\n endedAtMs\n })\n }\n }\n case 'ToolExecutionError':\n return {\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'Errored',\n call: event.call,\n message: event.message,\n endedAtMs: nowMs\n })\n }\n case 'ProviderToolResult':\n return {\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'ProviderCompleted',\n call: event.call,\n result: event.result\n })\n }\n case 'AssistantMessage':\n return {\n ...state,\n liveMessages: [...state.liveMessages, event.message],\n text: '',\n reasoning: ''\n }\n case 'AgentEnd':\n return {\n ...state,\n status: 'done',\n messages: [...state.messages, ...event.messages],\n liveMessages: [],\n text: '',\n reasoning: '',\n toolRuns: completedToolRuns(state.toolRuns)\n }\n case 'AgentAwaitingInput':\n return {\n ...state,\n status: 'waiting',\n messages: [...state.messages, ...event.messages],\n liveMessages: [],\n text: '',\n reasoning: '',\n error: null\n }\n case 'AgentRetry':\n case 'CompactionEnd':\n case 'CompactionStart':\n case 'LLMStreamEnd':\n case 'LLMStreamStart':\n case 'SubagentCompleted':\n case 'SubagentStarted':\n case 'TurnEnd':\n case 'TurnStart':\n case 'UsageUpdate':\n return state\n }\n}\n\nexport const submitAgentUserMessage = (\n state: AgentClientState,\n message: UserMessage\n): AgentClientState => ({\n ...state,\n status: 'running',\n messages: appendAgentMessage(state.messages, message),\n liveMessages: [],\n text: '',\n reasoning: '',\n toolRuns: completedToolRuns(state.toolRuns),\n error: null,\n seenEventIds: []\n})\n\nexport const markAgentError = (\n state: AgentClientState,\n message = 'Agent request failed'\n): AgentClientState => ({\n ...state,\n status: 'error',\n toolRuns: completedToolRuns(state.toolRuns),\n error: message\n})\n\nexport const markAgentAborted = (state: AgentClientState): AgentClientState => ({\n ...state,\n status: 'aborted',\n toolRuns: completedToolRuns(state.toolRuns),\n error: null\n})\n\nexport const reduceAgentEvents = (\n events: ReadonlyArray<AgentEvent>,\n initialState: AgentClientState = initialAgentClientState,\n options: ApplyAgentEventOptions = {}\n) =>\n events.reduce((state, event) => applyAgentEventWithOptions(state, event, options), initialState)\n"],"mappings":";AA0EA,MAAa,0BAA4C;CACvD,QAAQ;CACR,UAAU,CAAC;CACX,cAAc,CAAC;CACf,MAAM;CACN,WAAW;CACX,UAAU,CAAC;CACX,OAAO;CACP,cAAc,CAAC;AACjB;AAEA,MAAM,gBAAgB,OAAyB,UAC7C,MAAM,YAAY,KAAA,KAAa,MAAM,aAAa,SAAS,MAAM,OAAO;AAE1E,MAAM,iBAAiB,OAAyB,UAC9C,MAAM,YAAY,KAAA,IACd,QACA;CAAE,GAAG;CAAO,cAAc,CAAC,GAAG,MAAM,cAAc,MAAM,OAAO;AAAE;AAEvE,MAAM,aAAa,QAAsB;CACvC,QAAQ,IAAI,MAAZ;EACE,KAAK,kBACH,OAAO,IAAI;EACb,KAAK,UACH,OAAO,IAAI;EACb,KAAK,qBACH,OAAO,IA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U,OAAO;CACpD,cAAc,CAAC;CACf,MAAM;CACN,WAAW;CACX,UAAU,kBAAkB,MAAM,QAAQ;CAC1C,OAAO;CACP,cAAc,CAAC;AACjB;AAEA,MAAa,kBACX,OACA,UAAU,4BACY;CACtB,GAAG;CACH,QAAQ;CACR,UAAU,kBAAkB,MAAM,QAAQ;CAC1C,OAAO;AACT;AAEA,MAAa,oBAAoB,WAA+C;CAC9E,GAAG;CACH,QAAQ;CACR,UAAU,kBAAkB,MAAM,QAAQ;CAC1C,OAAO;AACT;AAEA,MAAa,qBACX,QACA,eAAiC,yBACjC,UAAkC,CAAC,MAEnC,OAAO,QAAQ,OAAO,UAAU,2BAA2B,OAAO,OAAO,OAAO,GAAG,YAAY"}
|
|
1
|
+
{"version":3,"file":"state.mjs","names":[],"sources":["../../src/client/state.ts"],"sourcesContent":["import {\n type AgentError,\n type AgentEvent,\n type AgentMessage,\n type AgentRetry,\n type HitlRequest,\n type QuestionRequest,\n type QuestionResponse,\n type ToolCall,\n type ToolApprovalRequest,\n type ToolResult,\n type UserMessage\n} from '@yolk-sdk/agent/protocol'\n\nexport type AgentRunStatus = 'idle' | 'running' | 'waiting' | 'done' | 'error' | 'aborted'\n\nexport type AgentToolRun =\n | {\n readonly _tag: 'InputStreaming'\n readonly id: string\n readonly name?: string\n readonly input: string\n }\n | { readonly _tag: 'InputReady'; readonly call: ToolCall }\n | {\n readonly _tag: 'ApprovalRequested'\n readonly call: ToolCall\n readonly request?: ToolApprovalRequest\n }\n | { readonly _tag: 'Denied'; readonly toolCallId: string; readonly reason: string }\n | { readonly _tag: 'QuestionRequested'; readonly request: QuestionRequest }\n | {\n readonly _tag: 'QuestionAnswered'\n readonly response: QuestionResponse\n readonly request?: QuestionRequest\n }\n | {\n readonly _tag: 'QuestionCancelled'\n readonly response: QuestionResponse\n readonly request?: QuestionRequest\n }\n | { readonly _tag: 'Executing'; readonly call: ToolCall; readonly startedAtMs: number }\n | {\n readonly _tag: 'Completed'\n readonly call: ToolCall\n readonly result: ToolResult\n readonly startedAtMs: number\n readonly endedAtMs: number\n }\n | {\n readonly _tag: 'Errored'\n readonly call: ToolCall\n readonly message: string\n readonly endedAtMs: number\n }\n | { readonly _tag: 'ProviderCompleted'; readonly call: ToolCall; readonly result: ToolResult }\n\ntype StartedAgentToolRun = Extract<AgentToolRun, { readonly _tag: 'Executing' | 'Completed' }>\n\nexport type AgentClientState = {\n readonly status: AgentRunStatus\n readonly messages: ReadonlyArray<AgentMessage>\n readonly liveMessages: ReadonlyArray<AgentMessage>\n readonly text: string\n readonly reasoning: string\n readonly toolRuns: ReadonlyArray<AgentToolRun>\n readonly error: string | null\n readonly errorInfo: AgentError | null\n readonly retryInfo: AgentRetry | null\n readonly seenEventIds: ReadonlyArray<string>\n}\n\nexport type ApplyAgentEventOptions = {\n readonly nowMs?: number\n}\n\nexport type AgentTranscript = readonly [AgentMessage, ...Array<AgentMessage>]\n\nexport const initialAgentClientState: AgentClientState = {\n status: 'idle',\n messages: [],\n liveMessages: [],\n text: '',\n reasoning: '',\n toolRuns: [],\n error: null,\n errorInfo: null,\n retryInfo: null,\n seenEventIds: []\n}\n\nconst clearRetryInfo = (state: AgentClientState): AgentClientState =>\n state.retryInfo === null ? state : { ...state, retryInfo: null }\n\nconst hasSeenEvent = (state: AgentClientState, event: AgentEvent) =>\n event.eventId !== undefined && state.seenEventIds.includes(event.eventId)\n\nconst rememberEvent = (state: AgentClientState, event: AgentEvent): AgentClientState =>\n event.eventId === undefined\n ? state\n : { ...state, seenEventIds: [...state.seenEventIds, event.eventId] }\n\nconst toolRunId = (run: AgentToolRun) => {\n switch (run._tag) {\n case 'InputStreaming':\n return run.id\n case 'Denied':\n return run.toolCallId\n case 'QuestionRequested':\n return run.request.toolCallId\n case 'QuestionAnswered':\n case 'QuestionCancelled':\n return run.response.toolCallId\n case 'InputReady':\n case 'ApprovalRequested':\n case 'Executing':\n case 'Completed':\n case 'Errored':\n case 'ProviderCompleted':\n return run.call.id\n }\n}\n\nexport const isActiveToolRun = (run: AgentToolRun) =>\n run._tag !== 'Completed' &&\n run._tag !== 'Errored' &&\n run._tag !== 'Denied' &&\n run._tag !== 'QuestionAnswered' &&\n run._tag !== 'QuestionCancelled' &&\n run._tag !== 'ProviderCompleted'\n\nexport const completedToolRuns = (runs: ReadonlyArray<AgentToolRun>) =>\n runs.filter(run => run._tag === 'Completed')\n\nexport const toolRunsFromHitlRequests = (\n requests: ReadonlyArray<HitlRequest>\n): ReadonlyArray<AgentToolRun> =>\n requests.map(request => {\n switch (request._tag) {\n case 'QuestionRequest':\n return { _tag: 'QuestionRequested', request }\n case 'ToolApprovalRequest':\n return { _tag: 'ApprovalRequested', call: request.call, request }\n }\n })\n\nconst replaceToolRun = (\n runs: ReadonlyArray<AgentToolRun>,\n run: AgentToolRun\n): ReadonlyArray<AgentToolRun> => {\n const id = toolRunId(run)\n const replaceIndex = runs.findIndex(current => toolRunId(current) === id)\n\n if (replaceIndex === -1) {\n return [...runs, run]\n }\n\n return runs.flatMap((current, index) => {\n if (toolRunId(current) !== id) {\n return [current]\n }\n\n return index === replaceIndex ? [run] : []\n })\n}\n\nconst isStartedToolRun = (run: AgentToolRun): run is StartedAgentToolRun =>\n run._tag === 'Executing' || run._tag === 'Completed'\n\nconst startedAtMsFor = (runs: ReadonlyArray<AgentToolRun>, toolCallId: string) =>\n runs.filter(isStartedToolRun).find(run => run.call.id === toolCallId)?.startedAtMs\n\nconst appendToolInputDelta = (\n runs: ReadonlyArray<AgentToolRun>,\n id: string,\n delta: string\n): ReadonlyArray<AgentToolRun> =>\n runs.map(run =>\n run._tag === 'InputStreaming' && run.id === id ? { ...run, input: `${run.input}${delta}` } : run\n )\n\nconst questionRequestForToolCall = (\n runs: ReadonlyArray<AgentToolRun>,\n toolCallId: string\n): QuestionRequest | undefined =>\n runs.flatMap(run => {\n if (toolRunId(run) !== toolCallId) {\n return []\n }\n\n switch (run._tag) {\n case 'QuestionRequested':\n return [run.request]\n case 'QuestionAnswered':\n case 'QuestionCancelled':\n return run.request === undefined ? [] : [run.request]\n case 'InputStreaming':\n case 'InputReady':\n case 'ApprovalRequested':\n case 'Denied':\n case 'Executing':\n case 'Completed':\n case 'Errored':\n case 'ProviderCompleted':\n return []\n }\n })[0]\n\nconst questionAnsweredRun = (\n response: QuestionResponse,\n request: QuestionRequest | undefined\n): AgentToolRun =>\n request === undefined\n ? { _tag: 'QuestionAnswered', response }\n : { _tag: 'QuestionAnswered', response, request }\n\nconst questionCancelledRun = (\n response: QuestionResponse,\n request: QuestionRequest | undefined\n): AgentToolRun =>\n request === undefined\n ? { _tag: 'QuestionCancelled', response }\n : { _tag: 'QuestionCancelled', response, request }\n\nexport const appendAgentMessage = (\n messages: ReadonlyArray<AgentMessage>,\n message: AgentMessage\n): AgentTranscript => {\n const first = messages[0]\n\n if (first === undefined) {\n return [message]\n }\n\n return [first, ...messages.slice(1), message]\n}\n\nexport const applyAgentEvent = (state: AgentClientState, event: AgentEvent): AgentClientState => {\n const nowMs = 0\n\n return applyAgentEventWithOptions(state, event, { nowMs })\n}\n\nexport const applyAgentEventWithOptions = (\n state: AgentClientState,\n event: AgentEvent,\n options: ApplyAgentEventOptions = {}\n): AgentClientState => {\n const nowMs = options.nowMs ?? 0\n\n if (hasSeenEvent(state, event)) {\n return state\n }\n\n return rememberEvent(applyAgentEventUnchecked(state, event, nowMs), event)\n}\n\nconst applyAgentEventUnchecked = (\n state: AgentClientState,\n event: AgentEvent,\n nowMs: number\n): AgentClientState => {\n switch (event._tag) {\n case 'AgentStart':\n return {\n ...state,\n status: 'running',\n text: '',\n reasoning: '',\n liveMessages: [],\n toolRuns: completedToolRuns(state.toolRuns),\n error: null,\n errorInfo: null,\n retryInfo: null\n }\n case 'AgentError':\n return markAgentError(state, event.message, event)\n case 'LLMTextDelta':\n return clearRetryInfo({ ...state, text: `${state.text}${event.text}` })\n case 'LLMReasoningDelta':\n return clearRetryInfo({ ...state, reasoning: `${state.reasoning}${event.text}` })\n case 'ToolInputStart':\n return clearRetryInfo({\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'InputStreaming',\n id: event.id,\n name: event.name,\n input: ''\n })\n })\n case 'ToolInputDelta':\n return clearRetryInfo({\n ...state,\n toolRuns: appendToolInputDelta(state.toolRuns, event.id, event.delta)\n })\n case 'ToolInputEnd':\n return clearRetryInfo({\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, { _tag: 'InputReady', call: event.call })\n })\n case 'ToolApprovalRequested':\n return {\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'ApprovalRequested',\n call: event.call,\n request: event.request\n })\n }\n case 'ToolApprovalGranted':\n return state\n case 'ToolApprovalDenied':\n return {\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'Denied',\n toolCallId: event.toolCallId,\n reason: event.reason\n })\n }\n case 'QuestionRequested':\n return {\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'QuestionRequested',\n request: event.request\n })\n }\n case 'QuestionAnswered':\n return {\n ...state,\n toolRuns: replaceToolRun(\n state.toolRuns,\n questionAnsweredRun(\n event.response,\n questionRequestForToolCall(state.toolRuns, event.response.toolCallId)\n )\n )\n }\n case 'QuestionCancelled':\n return {\n ...state,\n toolRuns: replaceToolRun(\n state.toolRuns,\n questionCancelledRun(\n event.response,\n questionRequestForToolCall(state.toolRuns, event.response.toolCallId)\n )\n )\n }\n case 'ToolExecutionStarted':\n return {\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'Executing',\n call: event.call,\n startedAtMs: nowMs\n })\n }\n case 'ToolExecutionCompleted': {\n const endedAtMs = nowMs\n const startedAtMs = startedAtMsFor(state.toolRuns, event.call.id) ?? endedAtMs\n\n return {\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'Completed',\n call: event.call,\n result: event.result,\n startedAtMs,\n endedAtMs\n })\n }\n }\n case 'ToolExecutionError':\n return {\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'Errored',\n call: event.call,\n message: event.message,\n endedAtMs: nowMs\n })\n }\n case 'ProviderToolResult':\n return clearRetryInfo({\n ...state,\n toolRuns: replaceToolRun(state.toolRuns, {\n _tag: 'ProviderCompleted',\n call: event.call,\n result: event.result\n })\n })\n case 'AssistantMessage':\n return clearRetryInfo({\n ...state,\n liveMessages: [...state.liveMessages, event.message],\n text: '',\n reasoning: ''\n })\n case 'AgentEnd':\n return {\n ...state,\n status: 'done',\n messages: [...state.messages, ...event.messages],\n liveMessages: [],\n text: '',\n reasoning: '',\n toolRuns: completedToolRuns(state.toolRuns),\n retryInfo: null\n }\n case 'AgentAwaitingInput':\n return {\n ...state,\n status: 'waiting',\n messages: [...state.messages, ...event.messages],\n liveMessages: [],\n text: '',\n reasoning: '',\n error: null,\n errorInfo: null,\n retryInfo: null\n }\n case 'AgentRetry':\n return { ...state, retryInfo: event }\n case 'CompactionEnd':\n case 'CompactionStart':\n case 'LLMStreamEnd':\n case 'LLMStreamStart':\n case 'SubagentCompleted':\n case 'SubagentStarted':\n case 'TurnEnd':\n case 'TurnStart':\n case 'UsageUpdate':\n return state\n }\n}\n\nexport const submitAgentUserMessage = (\n state: AgentClientState,\n message: UserMessage\n): AgentClientState => ({\n ...state,\n status: 'running',\n messages: appendAgentMessage(state.messages, message),\n liveMessages: [],\n text: '',\n reasoning: '',\n toolRuns: completedToolRuns(state.toolRuns),\n error: null,\n errorInfo: null,\n retryInfo: null,\n seenEventIds: []\n})\n\nexport const markAgentError = (\n state: AgentClientState,\n message = 'Agent request failed',\n errorInfo: AgentError | null = null\n): AgentClientState => ({\n ...state,\n status: 'error',\n toolRuns: completedToolRuns(state.toolRuns),\n error: message,\n errorInfo,\n retryInfo: null\n})\n\nexport const markAgentAborted = (state: AgentClientState): AgentClientState => ({\n ...state,\n status: 'aborted',\n toolRuns: completedToolRuns(state.toolRuns),\n error: null,\n errorInfo: null,\n retryInfo: null\n})\n\nexport const reduceAgentEvents = (\n events: ReadonlyArray<AgentEvent>,\n initialState: AgentClientState = initialAgentClientState,\n options: ApplyAgentEventOptions = {}\n) =>\n events.reduce((state, event) => applyAgentEventWithOptions(state, event, options), initialState)\n"],"mappings":";AA8EA,MAAa,0BAA4C;CACvD,QAAQ;CACR,UAAU,CAAC;CACX,cAAc,CAAC;CACf,MAAM;CACN,WAAW;CACX,UAAU,CAAC;CACX,OAAO;CACP,WAAW;CACX,WAAW;CACX,cAAc,CAAC;AACjB;AAEA,MAAM,kBAAkB,UACtB,MAAM,cAAc,OAAO,QAAQ;CAAE,GAAG;CAAO,WAAW;AAAK;AAEjE,MAAM,gBAAgB,OAAyB,UAC7C,MAAM,YAAY,KAAA,KAAa,MAAM,aAAa,SAAS,MAAM,OAAO;AAE1E,MAAM,iBAAiB,OAAyB,UAC9C,MAAM,YAAY,KAAA,IACd,QACA;CAAE,GAAG;CAAO,cAAc,CAAC,GAAG,MAAM,cAAc,MAAM,OAAO;AAAE;AAEvE,MAAM,aAAa,QAAsB;CACvC,QAAQ,IAAI,MAAZ;EACE,KAAK,kBACH,OAAO,IAAI;EACb,KAAK,UACH,OAAO,IAAI;EACb,KAAK,qBACH,OAAO,IAAI,QAAQ;EACrB,KAAK;EACL,KAAK,qBACH,OAAO,IAAI,SAAS;EACtB,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,qBACH,OAAO,IAAI,KAAK;CACpB;AACF;AAEA,MAAa,mBAAmB,QAC9B,IAAI,SAAS,eACb,IAAI,SAAS,aACb,IAAI,SAAS,YACb,IAAI,SAAS,sBACb,IAAI,SAAS,uBACb,IAAI,SAAS;AAEf,MAAa,qBAAqB,SAChC,KAAK,QAAO,QAAO,IAAI,SAAS,WAAW;AAE7C,MAAa,4BACX,aAEA,SAAS,KAAI,YAAW;CACtB,QAAQ,QAAQ,MAAhB;EACE,KAAK,mBACH,OAAO;GAAE,MAAM;GAAqB;EAAQ;EAC9C,KAAK,uBACH,OAAO;GAAE,MAAM;GAAqB,MA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CACR,UAAU,kBAAkB,MAAM,QAAQ;CAC1C,OAAO;CACP,WAAW;CACX,WAAW;AACb;AAEA,MAAa,qBACX,QACA,eAAiC,yBACjC,UAAkC,CAAC,MAEnC,OAAO,QAAQ,OAAO,UAAU,2BAA2B,OAAO,OAAO,OAAO,GAAG,YAAY"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { AgentTranscript } from "./state.mjs";
|
|
2
|
+
import { AgentEvent, AgentReasoningEffort, HitlResponse, QuestionResponse, ToolApprovalResponse } from "@yolk-sdk/agent/protocol";
|
|
2
3
|
import { Cause, Effect, Layer, Stream } from "effect";
|
|
3
4
|
import { HttpClient } from "effect/unstable/http";
|
|
4
5
|
import * as Schema from "effect/Schema";
|
|
5
|
-
import { AgentEvent, AgentReasoningEffort, HitlResponse, QuestionResponse, ToolApprovalResponse } from "@yolk-sdk/agent/protocol";
|
|
6
6
|
|
|
7
7
|
//#region src/client/transport.d.ts
|
|
8
8
|
declare const AgentTransportError_base: Schema.Class<AgentTransportError, Schema.TaggedStruct<"AgentTransportError", {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { AgentEvent, AgentWebSocketServerMessage, QuestionResponseInput, ToolApprovalResponseInput, UserInput } from "@yolk-sdk/agent/protocol";
|
|
1
2
|
import { Cause, Channel, Effect, Exit, Pull, Queue, Ref, Scope, Stream } from "effect";
|
|
2
3
|
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/unstable/http";
|
|
3
4
|
import * as Schema from "effect/Schema";
|
|
4
|
-
import { AgentEvent, AgentWebSocketServerMessage, QuestionResponseInput, ToolApprovalResponseInput, UserInput } from "@yolk-sdk/agent/protocol";
|
|
5
5
|
//#region src/client/transport.ts
|
|
6
6
|
var AgentTransportError = class extends Schema.TaggedErrorClass()("AgentTransportError", {
|
|
7
7
|
message: Schema.String,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { TranscriptTokenEstimator } from "./estimator.mjs";
|
|
2
2
|
import { CompactionResult } from "./window.mjs";
|
|
3
|
-
import { Layer } from "effect";
|
|
4
3
|
import { AgentMessage } from "@yolk-sdk/agent/protocol";
|
|
4
|
+
import { Layer } from "effect";
|
|
5
5
|
import { ContextTransformer } from "@yolk-sdk/agent/loop";
|
|
6
6
|
|
|
7
7
|
//#region src/compaction/transformer.d.ts
|
package/dist/loop/error.d.mts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
+
import { AgentError, ProviderErrorInfo } from "@yolk-sdk/agent/protocol";
|
|
1
2
|
import * as Schema from "effect/Schema";
|
|
2
|
-
import { AgentError } from "@yolk-sdk/agent/protocol";
|
|
3
3
|
|
|
4
4
|
//#region src/loop/error.d.ts
|
|
5
5
|
declare const LLMError_base: Schema.Class<LLMError, Schema.TaggedStruct<"LLMError", {
|
|
6
|
-
readonly cause: Schema.Literals<readonly ["validation_error", "provider_error", "rate_limit", "context_overflow", "invalid_response"]>;
|
|
6
|
+
readonly cause: Schema.Literals<readonly ["validation_error", "provider_error", "rate_limit", "overloaded", "context_overflow", "invalid_response"]>;
|
|
7
7
|
readonly message: Schema.String;
|
|
8
8
|
readonly retryable: Schema.Boolean;
|
|
9
|
+
readonly provider: Schema.optional<typeof ProviderErrorInfo>;
|
|
9
10
|
}>, import("effect/Cause").YieldableError>;
|
|
10
11
|
declare class LLMError extends LLMError_base {}
|
|
11
12
|
declare const FauxExhaustedError_base: Schema.Class<FauxExhaustedError, Schema.TaggedStruct<"FauxExhaustedError", {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.d.mts","names":[],"sources":["../../src/loop/error.ts"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"error.d.mts","names":[],"sources":["../../src/loop/error.ts"],"mappings":";;;;cAC6F,aAAA;;;;;;cAEhF,QAAA,SAAiB,aAY5B;AAAA,cAAG,uBAAA;;;cAEQ,kBAAA,SAA2B,uBAKvC;AAAA,cAAG,cAAA;;;;;cAES,SAAA,SAAkB,cAa7B;AAAA,cAAG,0BAAA;;;;;cAEQ,qBAAA,SAA8B,0BAO1C;AAAA,cAAG,eAAA;;;cAES,UAAA,SAAmB,eAE9B;AAAA,KAEU,gBAAA,GAAmB,QAAA,GAAW,kBAAA,GAAqB,UAAA;AAAA,KAEnD,cAAA,GAAiB,gBAAA,GAAmB,SAAA,GAAY,qBAAA;AAAA,cAmB/C,0BAAA,GAA8B,KAAA,EAAO,cAAA,KAAiB,UAkClE"}
|
package/dist/loop/error.mjs
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
|
+
import { AgentError, ProviderErrorInfo } from "@yolk-sdk/agent/protocol";
|
|
1
2
|
import * as Schema from "effect/Schema";
|
|
2
|
-
import { AgentError } from "@yolk-sdk/agent/protocol";
|
|
3
3
|
//#region src/loop/error.ts
|
|
4
4
|
var LLMError = class extends Schema.TaggedErrorClass()("LLMError", {
|
|
5
5
|
cause: Schema.Literals([
|
|
6
6
|
"validation_error",
|
|
7
7
|
"provider_error",
|
|
8
8
|
"rate_limit",
|
|
9
|
+
"overloaded",
|
|
9
10
|
"context_overflow",
|
|
10
11
|
"invalid_response"
|
|
11
12
|
]),
|
|
12
13
|
message: Schema.String,
|
|
13
|
-
retryable: Schema.Boolean
|
|
14
|
+
retryable: Schema.Boolean,
|
|
15
|
+
provider: Schema.optional(ProviderErrorInfo)
|
|
14
16
|
}) {};
|
|
15
17
|
var FauxExhaustedError = class extends Schema.TaggedErrorClass()("FauxExhaustedError", { message: Schema.String }) {};
|
|
16
18
|
var ToolError = class extends Schema.TaggedErrorClass()("ToolError", {
|
|
@@ -54,7 +56,8 @@ const agentLoopErrorToAgentError = (error) => {
|
|
|
54
56
|
case "LLMError": return AgentError.make({
|
|
55
57
|
code: error.cause,
|
|
56
58
|
message: error.message,
|
|
57
|
-
retryable: error.retryable
|
|
59
|
+
retryable: error.retryable,
|
|
60
|
+
...error.provider === void 0 ? {} : { provider: error.provider }
|
|
58
61
|
});
|
|
59
62
|
case "ToolError": return AgentError.make({
|
|
60
63
|
code: toolErrorCode(error),
|
package/dist/loop/error.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"error.mjs","names":[],"sources":["../../src/loop/error.ts"],"sourcesContent":["import * as Schema from 'effect/Schema'\nimport { AgentError, type AgentErrorCode } from '@yolk-sdk/agent/protocol'\n\nexport class LLMError extends Schema.TaggedErrorClass<LLMError>()('LLMError', {\n cause: Schema.Literals([\n 'validation_error',\n 'provider_error',\n 'rate_limit',\n 'context_overflow',\n 'invalid_response'\n ]),\n message: Schema.String,\n retryable: Schema.Boolean\n}) {}\n\nexport class FauxExhaustedError extends Schema.TaggedErrorClass<FauxExhaustedError>()(\n 'FauxExhaustedError',\n {\n message: Schema.String\n }\n) {}\n\nexport class ToolError extends Schema.TaggedErrorClass<ToolError>()('ToolError', {\n tool: Schema.String,\n message: Schema.String,\n cause: Schema.Literals([\n 'validation',\n 'invalid_input',\n 'execution',\n 'timeout',\n 'permission',\n 'denied',\n 'not_found',\n 'unavailable'\n ])\n}) {}\n\nexport class ContextTransformError extends Schema.TaggedErrorClass<ContextTransformError>()(\n 'ContextTransformError',\n {\n cause: Schema.Literals(['context_overflow', 'invalid_response']),\n message: Schema.String,\n retryable: Schema.Boolean\n }\n) {}\n\nexport class AbortError extends Schema.TaggedErrorClass<AbortError>()('AbortError', {\n reason: Schema.Literals(['user', 'system', 'max_turns'])\n}) {}\n\nexport type LLMProviderError = LLMError | FauxExhaustedError | AbortError\n\nexport type AgentLoopError = LLMProviderError | ToolError | ContextTransformError\n\nconst toolErrorCode = (error: ToolError): AgentErrorCode => {\n switch (error.cause) {\n case 'validation':\n case 'invalid_input':\n return 'validation_error'\n case 'timeout':\n return 'tool_timeout'\n case 'permission':\n case 'denied':\n return 'tool_denied'\n case 'execution':\n case 'not_found':\n case 'unavailable':\n return 'tool_error'\n }\n}\n\nexport const agentLoopErrorToAgentError = (error: AgentLoopError): AgentError => {\n switch (error._tag) {\n case 'LLMError':\n return AgentError.make({\n code: error.cause,\n message: error.message,\n retryable: error.retryable\n })\n case 'ToolError':\n return AgentError.make({\n code: toolErrorCode(error),\n message: error.message,\n retryable: error.cause === 'timeout'\n })\n case 'ContextTransformError':\n return AgentError.make({\n code: error.cause,\n message: error.message,\n retryable: error.retryable\n })\n case 'AbortError':\n return AgentError.make({\n code: 'aborted',\n message: `Agent run aborted: ${error.reason}`,\n retryable: error.reason === 'system'\n })\n case 'FauxExhaustedError':\n return AgentError.make({\n code: 'provider_error',\n message: error.message,\n retryable: false\n })\n }\n}\n"],"mappings":";;;AAGA,IAAa,WAAb,cAA8B,OAAO,iBAA2B,EAAE,YAAY;CAC5E,OAAO,OAAO,SAAS;EACrB;EACA;EACA;EACA;EACA;CACF,CAAC;CACD,SAAS,OAAO;CAChB,WAAW,OAAO;
|
|
1
|
+
{"version":3,"file":"error.mjs","names":[],"sources":["../../src/loop/error.ts"],"sourcesContent":["import * as Schema from 'effect/Schema'\nimport { AgentError, ProviderErrorInfo, type AgentErrorCode } from '@yolk-sdk/agent/protocol'\n\nexport class LLMError extends Schema.TaggedErrorClass<LLMError>()('LLMError', {\n cause: Schema.Literals([\n 'validation_error',\n 'provider_error',\n 'rate_limit',\n 'overloaded',\n 'context_overflow',\n 'invalid_response'\n ]),\n message: Schema.String,\n retryable: Schema.Boolean,\n provider: Schema.optional(ProviderErrorInfo)\n}) {}\n\nexport class FauxExhaustedError extends Schema.TaggedErrorClass<FauxExhaustedError>()(\n 'FauxExhaustedError',\n {\n message: Schema.String\n }\n) {}\n\nexport class ToolError extends Schema.TaggedErrorClass<ToolError>()('ToolError', {\n tool: Schema.String,\n message: Schema.String,\n cause: Schema.Literals([\n 'validation',\n 'invalid_input',\n 'execution',\n 'timeout',\n 'permission',\n 'denied',\n 'not_found',\n 'unavailable'\n ])\n}) {}\n\nexport class ContextTransformError extends Schema.TaggedErrorClass<ContextTransformError>()(\n 'ContextTransformError',\n {\n cause: Schema.Literals(['context_overflow', 'invalid_response']),\n message: Schema.String,\n retryable: Schema.Boolean\n }\n) {}\n\nexport class AbortError extends Schema.TaggedErrorClass<AbortError>()('AbortError', {\n reason: Schema.Literals(['user', 'system', 'max_turns'])\n}) {}\n\nexport type LLMProviderError = LLMError | FauxExhaustedError | AbortError\n\nexport type AgentLoopError = LLMProviderError | ToolError | ContextTransformError\n\nconst toolErrorCode = (error: ToolError): AgentErrorCode => {\n switch (error.cause) {\n case 'validation':\n case 'invalid_input':\n return 'validation_error'\n case 'timeout':\n return 'tool_timeout'\n case 'permission':\n case 'denied':\n return 'tool_denied'\n case 'execution':\n case 'not_found':\n case 'unavailable':\n return 'tool_error'\n }\n}\n\nexport const agentLoopErrorToAgentError = (error: AgentLoopError): AgentError => {\n switch (error._tag) {\n case 'LLMError':\n return AgentError.make({\n code: error.cause,\n message: error.message,\n retryable: error.retryable,\n ...(error.provider === undefined ? {} : { provider: error.provider })\n })\n case 'ToolError':\n return AgentError.make({\n code: toolErrorCode(error),\n message: error.message,\n retryable: error.cause === 'timeout'\n })\n case 'ContextTransformError':\n return AgentError.make({\n code: error.cause,\n message: error.message,\n retryable: error.retryable\n })\n case 'AbortError':\n return AgentError.make({\n code: 'aborted',\n message: `Agent run aborted: ${error.reason}`,\n retryable: error.reason === 'system'\n })\n case 'FauxExhaustedError':\n return AgentError.make({\n code: 'provider_error',\n message: error.message,\n retryable: false\n })\n }\n}\n"],"mappings":";;;AAGA,IAAa,WAAb,cAA8B,OAAO,iBAA2B,EAAE,YAAY;CAC5E,OAAO,OAAO,SAAS;EACrB;EACA;EACA;EACA;EACA;EACA;CACF,CAAC;CACD,SAAS,OAAO;CAChB,WAAW,OAAO;CAClB,UAAU,OAAO,SAAS,iBAAiB;AAC7C,CAAC,EAAE,CAAC;AAEJ,IAAa,qBAAb,cAAwC,OAAO,iBAAqC,EAClF,sBACA,EACE,SAAS,OAAO,OAClB,CACF,EAAE,CAAC;AAEH,IAAa,YAAb,cAA+B,OAAO,iBAA4B,EAAE,aAAa;CAC/E,MAAM,OAAO;CACb,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C;CACL;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import * as Schema from "effect/Schema";
|
|
2
1
|
import { AgentUsage, ToolCall, ToolResult } from "@yolk-sdk/agent/protocol";
|
|
2
|
+
import * as Schema from "effect/Schema";
|
|
3
3
|
|
|
4
4
|
//#region src/loop/llm-event.d.ts
|
|
5
5
|
declare const LLMTextDelta_base: Schema.Class<LLMTextDelta, Schema.TaggedStruct<"TextDelta", {
|
package/dist/loop/llm-event.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import * as Schema from "effect/Schema";
|
|
2
1
|
import { AgentUsage, ToolCall, ToolResult } from "@yolk-sdk/agent/protocol";
|
|
2
|
+
import * as Schema from "effect/Schema";
|
|
3
3
|
//#region src/loop/llm-event.ts
|
|
4
4
|
var LLMTextDelta = class extends Schema.TaggedClass()("TextDelta", { text: Schema.String }) {};
|
|
5
5
|
var LLMReasoningDelta = class extends Schema.TaggedClass()("ReasoningDelta", { text: Schema.String }) {};
|
package/dist/loop/run.d.mts
CHANGED
|
@@ -3,8 +3,8 @@ import { ContextTransformer } from "./services/context-transformer.mjs";
|
|
|
3
3
|
import { LLMProvider } from "./services/llm-provider.mjs";
|
|
4
4
|
import { LoopConfig } from "./services/loop-config.mjs";
|
|
5
5
|
import { ToolExecutor } from "./services/tool-executor.mjs";
|
|
6
|
-
import { Stream } from "effect";
|
|
7
6
|
import { AgentEvent, AgentMessage, AgentModelCapabilities, AgentReasoningEffort, AgentUsage, HitlResponse, ToolCall, ToolDef } from "@yolk-sdk/agent/protocol";
|
|
7
|
+
import { Stream } from "effect";
|
|
8
8
|
|
|
9
9
|
//#region src/loop/run.d.ts
|
|
10
10
|
type AgentLoopRunId = string;
|
package/dist/loop/run.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"run.d.mts","names":[],"sources":["../../src/loop/run.ts"],"mappings":";;;;;;;;;KAoEY,cAAA;AAAA,KAEA,SAAA;EAA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,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,cA6C7C,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
|
@@ -4,9 +4,9 @@ import { ContextTransformer } from "./services/context-transformer.mjs";
|
|
|
4
4
|
import { LLMProvider } from "./services/llm-provider.mjs";
|
|
5
5
|
import { LoopConfig } from "./services/loop-config.mjs";
|
|
6
6
|
import { ToolExecutor } from "./services/tool-executor.mjs";
|
|
7
|
+
import { AgentAwaitingInput, AgentEnd, AgentRetry, AgentStart, AssistantMessageEvent, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolResult, QuestionRequest, QuestionRequested, QuestionToolParams, SubagentCompleted, SubagentStarted, ToolApprovalRequest, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UsageUpdate, addAgentUsage, assistantHostToolCalls, contentParts, contentPreview, formatQuestionResponseContent, hitlResponseEvent, makeSubagentRunId, questionResponseStructuredContent, zeroAgentUsage } from "@yolk-sdk/agent/protocol";
|
|
7
8
|
import { Clock, Effect, Ref, Stream } from "effect";
|
|
8
9
|
import * as Schema from "effect/Schema";
|
|
9
|
-
import { AgentAwaitingInput, AgentEnd, AgentRetry, AgentStart, AssistantMessageEvent, LLMReasoningDelta, LLMStreamEnd, LLMStreamStart, LLMTextDelta, ProviderToolResult, QuestionRequest, QuestionRequested, QuestionToolParams, SubagentCompleted, SubagentStarted, ToolApprovalRequest, ToolApprovalRequested, ToolExecutionCompleted, ToolExecutionError, ToolExecutionStarted, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultMessage, TurnEnd, TurnStart, UsageUpdate, addAgentUsage, assistantHostToolCalls, contentParts, contentPreview, formatQuestionResponseContent, hitlResponseEvent, makeSubagentRunId, questionResponseStructuredContent, 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;
|
|
@@ -111,7 +111,20 @@ const isLlmEvent = (event) => {
|
|
|
111
111
|
default: return false;
|
|
112
112
|
}
|
|
113
113
|
};
|
|
114
|
-
const
|
|
114
|
+
const maxUnhintedRetryDelayMs = 3e4;
|
|
115
|
+
const maxHintedRetryDelayMs = 2147483647;
|
|
116
|
+
const validDelayMs = (delayMs) => Number.isFinite(delayMs) && delayMs >= 0 ? Math.floor(delayMs) : void 0;
|
|
117
|
+
const hintedRetryDelayMs = (error) => {
|
|
118
|
+
const delayMs = error.provider?.retryAfterMs;
|
|
119
|
+
const validDelay = delayMs === void 0 ? void 0 : validDelayMs(delayMs);
|
|
120
|
+
return validDelay === void 0 ? void 0 : Math.min(validDelay, maxHintedRetryDelayMs);
|
|
121
|
+
};
|
|
122
|
+
const retryDelayMs = (baseDelayMs, attempt, error) => {
|
|
123
|
+
const hintedDelay = hintedRetryDelayMs(error);
|
|
124
|
+
if (hintedDelay !== void 0) return hintedDelay;
|
|
125
|
+
const delayMs = validDelayMs(baseDelayMs * 2 ** Math.max(0, attempt - 1)) ?? 0;
|
|
126
|
+
return Math.min(delayMs, maxUnhintedRetryDelayMs);
|
|
127
|
+
};
|
|
115
128
|
const retryReason = (error) => error.cause;
|
|
116
129
|
const retrySleep = (delayMs) => delayMs === 0 ? Effect.void : Effect.sleep(`${delayMs} millis`);
|
|
117
130
|
const failAgentLoopError = (error) => Stream.fail(error);
|
|
@@ -119,12 +132,13 @@ const sleepStream = (delayMs) => Stream.fromEffect(retrySleep(delayMs)).pipe(Str
|
|
|
119
132
|
const withProviderRetries = (stream, loopConfig, makeStream, attempt) => Stream.unwrap(Ref.make(false).pipe(Effect.map((emittedProviderEvent) => stream.pipe(Stream.tap(() => Ref.set(emittedProviderEvent, true)), Stream.catchTags({
|
|
120
133
|
LLMError: (error) => Stream.unwrap(Ref.get(emittedProviderEvent).pipe(Effect.map((emitted) => {
|
|
121
134
|
if (emitted || !error.retryable || error.cause === "context_overflow" || attempt > loopConfig.maxRetries) return failAgentLoopError(error);
|
|
122
|
-
const delayMs = retryDelayMs(loopConfig.retryBaseDelayMs, attempt);
|
|
135
|
+
const delayMs = retryDelayMs(loopConfig.retryBaseDelayMs, attempt, error);
|
|
123
136
|
return Stream.make(AgentRetry.make({
|
|
124
137
|
attempt,
|
|
125
138
|
reason: retryReason(error),
|
|
126
139
|
delayMs,
|
|
127
|
-
message: error.message
|
|
140
|
+
message: error.message,
|
|
141
|
+
...error.provider === void 0 ? {} : { provider: error.provider }
|
|
128
142
|
})).pipe(Stream.concat(sleepStream(delayMs)), Stream.concat(withProviderRetries(makeStream(), loopConfig, makeStream, attempt + 1)));
|
|
129
143
|
}))),
|
|
130
144
|
AbortError: failAgentLoopError,
|