blink 0.1.72 → 0.1.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/browser/agent/client/index.cjs +21 -0
  2. package/dist/browser/agent/client/index.d.cts +4 -0
  3. package/dist/browser/agent/client/index.d.ts +4 -0
  4. package/dist/browser/agent/client/index.js +21 -0
  5. package/dist/browser/agent/index.browser.cjs +1 -0
  6. package/dist/browser/agent/index.browser.d.cts +3 -0
  7. package/dist/browser/agent/index.browser.d.ts +3 -0
  8. package/dist/browser/agent/index.browser.js +1 -0
  9. package/dist/browser/chat-B5eFQu26.d.cts +129 -0
  10. package/dist/browser/chat-BN7SYTWY.d.ts +129 -0
  11. package/dist/browser/control/index.cjs +1 -0
  12. package/dist/browser/control/index.d.cts +187 -0
  13. package/dist/browser/control/index.d.ts +187 -0
  14. package/dist/browser/control/index.js +1 -0
  15. package/dist/browser/index-B5faDAC2.d.ts +53 -0
  16. package/dist/browser/index-C-GJWB97.d.cts +53 -0
  17. package/dist/browser/index.browser-09e-NXpn.cjs +1 -0
  18. package/dist/browser/index.browser-0KfCzcI7.js +1 -0
  19. package/dist/browser/index.browser-BUMCZUeQ.d.ts +180 -0
  20. package/dist/browser/index.browser-CnGab8Yp.d.cts +180 -0
  21. package/dist/browser/index.node-DJv-HF6j.js +3 -0
  22. package/dist/browser/index.node-mda_IL6K.cjs +3 -0
  23. package/dist/browser/react/index.cjs +1 -1
  24. package/dist/browser/react/index.d.cts +6 -5
  25. package/dist/browser/react/index.d.ts +6 -5
  26. package/dist/browser/react/index.js +1 -1
  27. package/dist/browser/validator-CvSEfFnI.cjs +1 -0
  28. package/dist/browser/validator-DOrmtI_l.js +1 -0
  29. package/dist/cli/{auth-Dw-wJ1IM.js → auth-BUNIOupD.js} +1 -1
  30. package/dist/cli/{chat-CvTLq5E0.js → chat-L0VBV1Zr.js} +1 -1
  31. package/dist/cli/{dev-Cr9A596F.js → dev-CMwHkKBI.js} +133 -137
  32. package/dist/cli/index.js +4 -4
  33. package/dist/cli/{init-LfebhEg-.js → init-B6vWokUI.js} +24 -22
  34. package/dist/cli/login-DKW_KVCA.js +1 -0
  35. package/dist/node/agent/index.node.cjs +10 -0
  36. package/dist/node/agent/index.node.d.cts +2 -0
  37. package/dist/node/agent/index.node.d.ts +2 -0
  38. package/dist/node/agent/index.node.js +10 -0
  39. package/dist/node/index.node-BBpGHHxe.d.ts +460 -0
  40. package/dist/node/index.node-iaeCqAo6.d.cts +460 -0
  41. package/dist/node/test.d.cts +20 -50
  42. package/dist/node/test.d.ts +20 -50
  43. package/package.json +21 -19
  44. package/dist/browser/api/index.browser.cjs +0 -1
  45. package/dist/browser/api/index.browser.d.cts +0 -2
  46. package/dist/browser/api/index.browser.d.ts +0 -2
  47. package/dist/browser/api/index.browser.js +0 -1
  48. package/dist/browser/client-3mJjOKuh.d.ts +0 -94
  49. package/dist/browser/client-B7xl9jGk.d.cts +0 -94
  50. package/dist/browser/client-BbZudkEc.js +0 -21
  51. package/dist/browser/client-DFaZjb1-.cjs +0 -21
  52. package/dist/browser/http/index.cjs +0 -1
  53. package/dist/browser/http/index.d.cts +0 -207
  54. package/dist/browser/http/index.d.ts +0 -207
  55. package/dist/browser/http/index.js +0 -1
  56. package/dist/browser/index.browser-BwGhLjB7.cjs +0 -1
  57. package/dist/browser/index.browser-Dj8kjB6X.js +0 -1
  58. package/dist/browser/index.browser-c6tjyX5u.d.cts +0 -316
  59. package/dist/browser/index.browser-ekIUKJkA.d.ts +0 -316
  60. package/dist/cli/login-KHDcJ0iZ.js +0 -1
  61. package/dist/node/api/index.node.cjs +0 -30
  62. package/dist/node/api/index.node.d.cts +0 -82
  63. package/dist/node/api/index.node.d.ts +0 -82
  64. package/dist/node/api/index.node.js +0 -30
  65. package/dist/node/index.browser-Bo1v3lXu.d.cts +0 -316
  66. package/dist/node/index.browser-Dhyi8IHz.d.ts +0 -316
  67. /package/dist/cli/{dist-CN69Y-yA.js → dist-NqrnQGst.js} +0 -0
  68. /package/dist/cli/{open-Cr8lEmcs.js → open-CSMQaj0E.js} +0 -0
@@ -1,207 +0,0 @@
1
- import { Chat, ChatBehavior, Message } from "../index.browser-c6tjyX5u.cjs";
2
- import { APIServerURLEnvironmentVariable, CapabilitiesResponse, Client, ClientOptions, ExperimentalProvideCompletionsRequest, SendMessagesRequest, StreamResponseFormatHeader, streamSSE } from "../client-B7xl9jGk.cjs";
3
- import { UIMessageChunk } from "ai";
4
- import * as hono_types0 from "hono/types";
5
- import * as hono_hono_base0 from "hono/hono-base";
6
-
7
- //#region src/http/async-iterable-stream.d.ts
8
- /**
9
- * A type that combines AsyncIterable and ReadableStream.
10
- * This allows a ReadableStream to be consumed using for-await-of syntax.
11
- */
12
- type AsyncIterableStream<T> = AsyncIterable<T> & ReadableStream<T>;
13
- /**
14
- * Wraps a ReadableStream and returns an object that is both a ReadableStream and an AsyncIterable.
15
- * This enables consumption of the stream using for-await-of, with proper resource cleanup on early exit or error.
16
- *
17
- * @template T The type of the stream's chunks.
18
- * @param source The source ReadableStream to wrap.
19
- * @returns An AsyncIterableStream that can be used as both a ReadableStream and an AsyncIterable.
20
- */
21
- declare function createAsyncIterableStream<T>(source: ReadableStream<T>): AsyncIterableStream<T>;
22
- //#endregion
23
- //#region src/http/api.d.ts
24
- /**
25
- * APIBindings are functions that will be invoked by the agent.
26
- */
27
- type APIBindings = {
28
- storage: {
29
- kv: {
30
- get: (key: string) => Promise<string | undefined>;
31
- set: (key: string, value: string) => Promise<void>;
32
- del: (key: string) => Promise<void>;
33
- };
34
- };
35
- chat: {
36
- upsert: (id: string) => Promise<Chat>;
37
- sendMessages: (id: string, options: {
38
- messages: Message[];
39
- behavior: ChatBehavior;
40
- }) => Promise<void>;
41
- };
42
- };
43
- /**
44
- * To implement your own API bindings, you can use Hono's
45
- * `createServerAdapter` to create a server that will
46
- * handle requests to the API.
47
- *
48
- * ```ts
49
- * const server = createHTTPServer(
50
- * createServerAdapter((req) => {
51
- * return api.fetch(req, <your-bindings>);
52
- * })
53
- * );
54
- * server.listen(options.port);
55
- * ```
56
- */
57
- declare const api: hono_hono_base0.HonoBase<{
58
- Bindings: APIBindings;
59
- }, hono_types0.BlankSchema | hono_types0.MergeSchemaPath<{
60
- "/kv/:key": {
61
- $get: {
62
- input: {
63
- param: {
64
- key: string;
65
- };
66
- };
67
- output: {
68
- error: string;
69
- };
70
- outputFormat: "json";
71
- status: 400;
72
- } | {
73
- input: {
74
- param: {
75
- key: string;
76
- };
77
- };
78
- output: {
79
- value: string | undefined;
80
- };
81
- outputFormat: "json";
82
- status: 200;
83
- };
84
- };
85
- } & {
86
- "/kv/:key": {
87
- $post: {
88
- input: {
89
- json: {
90
- value: string;
91
- };
92
- } & {
93
- param: {
94
- key: string;
95
- };
96
- };
97
- output: {
98
- error: string;
99
- };
100
- outputFormat: "json";
101
- status: 400;
102
- } | {
103
- input: {
104
- json: {
105
- value: string;
106
- };
107
- } & {
108
- param: {
109
- key: string;
110
- };
111
- };
112
- output: null;
113
- outputFormat: "body";
114
- status: 204;
115
- };
116
- };
117
- } & {
118
- "/kv/:key": {
119
- $delete: {
120
- input: {
121
- param: {
122
- key: string;
123
- };
124
- };
125
- output: {
126
- error: string;
127
- };
128
- outputFormat: "json";
129
- status: 400;
130
- } | {
131
- input: {
132
- param: {
133
- key: string;
134
- };
135
- };
136
- output: null;
137
- outputFormat: "body";
138
- status: 204;
139
- };
140
- };
141
- }, "/storage"> | hono_types0.MergeSchemaPath<{
142
- "/:id": {
143
- $post: {
144
- input: {
145
- param: {
146
- id: string;
147
- };
148
- };
149
- output: {
150
- error: string;
151
- };
152
- outputFormat: "json";
153
- status: 400;
154
- } | {
155
- input: {
156
- param: {
157
- id: string;
158
- };
159
- };
160
- output: {
161
- id: string;
162
- };
163
- outputFormat: "json";
164
- status: 200;
165
- };
166
- };
167
- } & {
168
- "/:id/sendMessages": {
169
- $post: {
170
- input: {
171
- json: {
172
- messages: Message[];
173
- behavior: ChatBehavior;
174
- };
175
- } & {
176
- param: {
177
- id: string;
178
- };
179
- };
180
- output: {
181
- error: string;
182
- };
183
- outputFormat: "json";
184
- status: 400;
185
- } | {
186
- input: {
187
- json: {
188
- messages: Message[];
189
- behavior: ChatBehavior;
190
- };
191
- } & {
192
- param: {
193
- id: string;
194
- };
195
- };
196
- output: null;
197
- outputFormat: "body";
198
- status: 204;
199
- };
200
- };
201
- }, "/chat">, "/">;
202
- //#endregion
203
- //#region src/http/convert-response-to-ui-message-stream.d.ts
204
- type StreamResponseFormat = "ui-message" | "openai-chat" | "openai-response" | "anthropic" | "google" | "xai";
205
- declare function convertResponseToUIMessageStream(response: Response): ReadableStream<UIMessageChunk>;
206
- //#endregion
207
- export { APIBindings, APIServerURLEnvironmentVariable, AsyncIterableStream, CapabilitiesResponse, Client, ClientOptions, ExperimentalProvideCompletionsRequest, SendMessagesRequest, StreamResponseFormat, StreamResponseFormatHeader, api, convertResponseToUIMessageStream, createAsyncIterableStream, streamSSE };
@@ -1,207 +0,0 @@
1
- import { Chat, ChatBehavior, Message } from "../index.browser-ekIUKJkA.js";
2
- import { APIServerURLEnvironmentVariable, CapabilitiesResponse, Client, ClientOptions, ExperimentalProvideCompletionsRequest, SendMessagesRequest, StreamResponseFormatHeader, streamSSE } from "../client-3mJjOKuh.js";
3
- import { UIMessageChunk } from "ai";
4
- import * as hono_types0 from "hono/types";
5
- import * as hono_hono_base0 from "hono/hono-base";
6
-
7
- //#region src/http/async-iterable-stream.d.ts
8
- /**
9
- * A type that combines AsyncIterable and ReadableStream.
10
- * This allows a ReadableStream to be consumed using for-await-of syntax.
11
- */
12
- type AsyncIterableStream<T> = AsyncIterable<T> & ReadableStream<T>;
13
- /**
14
- * Wraps a ReadableStream and returns an object that is both a ReadableStream and an AsyncIterable.
15
- * This enables consumption of the stream using for-await-of, with proper resource cleanup on early exit or error.
16
- *
17
- * @template T The type of the stream's chunks.
18
- * @param source The source ReadableStream to wrap.
19
- * @returns An AsyncIterableStream that can be used as both a ReadableStream and an AsyncIterable.
20
- */
21
- declare function createAsyncIterableStream<T>(source: ReadableStream<T>): AsyncIterableStream<T>;
22
- //#endregion
23
- //#region src/http/api.d.ts
24
- /**
25
- * APIBindings are functions that will be invoked by the agent.
26
- */
27
- type APIBindings = {
28
- storage: {
29
- kv: {
30
- get: (key: string) => Promise<string | undefined>;
31
- set: (key: string, value: string) => Promise<void>;
32
- del: (key: string) => Promise<void>;
33
- };
34
- };
35
- chat: {
36
- upsert: (id: string) => Promise<Chat>;
37
- sendMessages: (id: string, options: {
38
- messages: Message[];
39
- behavior: ChatBehavior;
40
- }) => Promise<void>;
41
- };
42
- };
43
- /**
44
- * To implement your own API bindings, you can use Hono's
45
- * `createServerAdapter` to create a server that will
46
- * handle requests to the API.
47
- *
48
- * ```ts
49
- * const server = createHTTPServer(
50
- * createServerAdapter((req) => {
51
- * return api.fetch(req, <your-bindings>);
52
- * })
53
- * );
54
- * server.listen(options.port);
55
- * ```
56
- */
57
- declare const api: hono_hono_base0.HonoBase<{
58
- Bindings: APIBindings;
59
- }, hono_types0.BlankSchema | hono_types0.MergeSchemaPath<{
60
- "/kv/:key": {
61
- $get: {
62
- input: {
63
- param: {
64
- key: string;
65
- };
66
- };
67
- output: {
68
- error: string;
69
- };
70
- outputFormat: "json";
71
- status: 400;
72
- } | {
73
- input: {
74
- param: {
75
- key: string;
76
- };
77
- };
78
- output: {
79
- value: string | undefined;
80
- };
81
- outputFormat: "json";
82
- status: 200;
83
- };
84
- };
85
- } & {
86
- "/kv/:key": {
87
- $post: {
88
- input: {
89
- json: {
90
- value: string;
91
- };
92
- } & {
93
- param: {
94
- key: string;
95
- };
96
- };
97
- output: {
98
- error: string;
99
- };
100
- outputFormat: "json";
101
- status: 400;
102
- } | {
103
- input: {
104
- json: {
105
- value: string;
106
- };
107
- } & {
108
- param: {
109
- key: string;
110
- };
111
- };
112
- output: null;
113
- outputFormat: "body";
114
- status: 204;
115
- };
116
- };
117
- } & {
118
- "/kv/:key": {
119
- $delete: {
120
- input: {
121
- param: {
122
- key: string;
123
- };
124
- };
125
- output: {
126
- error: string;
127
- };
128
- outputFormat: "json";
129
- status: 400;
130
- } | {
131
- input: {
132
- param: {
133
- key: string;
134
- };
135
- };
136
- output: null;
137
- outputFormat: "body";
138
- status: 204;
139
- };
140
- };
141
- }, "/storage"> | hono_types0.MergeSchemaPath<{
142
- "/:id": {
143
- $post: {
144
- input: {
145
- param: {
146
- id: string;
147
- };
148
- };
149
- output: {
150
- error: string;
151
- };
152
- outputFormat: "json";
153
- status: 400;
154
- } | {
155
- input: {
156
- param: {
157
- id: string;
158
- };
159
- };
160
- output: {
161
- id: string;
162
- };
163
- outputFormat: "json";
164
- status: 200;
165
- };
166
- };
167
- } & {
168
- "/:id/sendMessages": {
169
- $post: {
170
- input: {
171
- json: {
172
- messages: Message[];
173
- behavior: ChatBehavior;
174
- };
175
- } & {
176
- param: {
177
- id: string;
178
- };
179
- };
180
- output: {
181
- error: string;
182
- };
183
- outputFormat: "json";
184
- status: 400;
185
- } | {
186
- input: {
187
- json: {
188
- messages: Message[];
189
- behavior: ChatBehavior;
190
- };
191
- } & {
192
- param: {
193
- id: string;
194
- };
195
- };
196
- output: null;
197
- outputFormat: "body";
198
- status: 204;
199
- };
200
- };
201
- }, "/chat">, "/">;
202
- //#endregion
203
- //#region src/http/convert-response-to-ui-message-stream.d.ts
204
- type StreamResponseFormat = "ui-message" | "openai-chat" | "openai-response" | "anthropic" | "google" | "xai";
205
- declare function convertResponseToUIMessageStream(response: Response): ReadableStream<UIMessageChunk>;
206
- //#endregion
207
- export { APIBindings, APIServerURLEnvironmentVariable, AsyncIterableStream, CapabilitiesResponse, Client, ClientOptions, ExperimentalProvideCompletionsRequest, SendMessagesRequest, StreamResponseFormat, StreamResponseFormatHeader, api, convertResponseToUIMessageStream, createAsyncIterableStream, streamSSE };
@@ -1 +0,0 @@
1
- import{APIServerURLEnvironmentVariable as e,Client as t,StreamResponseFormatHeader as n,checkOptionalParameter as r,convertResponseToUIMessageStream as i,decodeURIComponent_ as a,getPath as o,getPathNoStrict as s,getPattern as c,getQueryParam as l,getQueryParams as u,mergePath as d,parse as f,splitPath as p,splitRoutingPath as m,streamSSE as h,tryDecode as g}from"../client-BbZudkEc.js";function ee(e){let t=e.pipeThrough(new TransformStream);return t[Symbol.asyncIterator]=function(){let e=this.getReader(),t=!1;async function n(n){t=!0;try{n&&await e.cancel?.()}finally{try{e.releaseLock()}catch{}}}return{async next(){if(t)return{done:!0,value:void 0};let{done:r,value:i}=await e.read();return r?(await n(!0),{done:!0,value:void 0}):{done:!1,value:i}},async return(){return await n(!0),{done:!0,value:void 0}},async throw(e){throw await n(!0),e}}},t}var _=(e,t,n)=>(r,i)=>{let a=-1;return o(0);async function o(s){if(s<=a)throw Error(`next() called multiple times`);a=s;let c,l=!1,u;if(e[s]?(u=e[s][0][0],r.req.routeIndex=s):u=s===e.length&&i||void 0,u)try{c=await u(r,()=>o(s+1))}catch(e){if(e instanceof Error&&t)r.error=e,c=await t(e,r),l=!0;else throw e}else r.finalized===!1&&n&&(c=await n(r));return c&&(r.finalized===!1||l)&&(r.res=c),r}},te=Symbol(),ne=async(e,t=Object.create(null))=>{let{all:n=!1,dot:r=!1}=t,i=e instanceof x?e.raw.headers:e.headers,a=i.get(`Content-Type`);return a?.startsWith(`multipart/form-data`)||a?.startsWith(`application/x-www-form-urlencoded`)?re(e,{all:n,dot:r}):{}};async function re(e,t){let n=await e.formData();return n?v(n,t):{}}function v(e,t){let n=Object.create(null);return e.forEach((e,r)=>{let i=t.all||r.endsWith(`[]`);i?y(n,r,e):n[r]=e}),t.dot&&Object.entries(n).forEach(([e,t])=>{let r=e.includes(`.`);r&&(ie(n,e,t),delete n[e])}),n}var y=(e,t,n)=>{e[t]===void 0?t.endsWith(`[]`)?e[t]=[n]:e[t]=n:Array.isArray(e[t])?e[t].push(n):e[t]=[e[t],n]},ie=(e,t,n)=>{let r=e,i=t.split(`.`);i.forEach((e,t)=>{t===i.length-1?r[e]=n:((!r[e]||typeof r[e]!=`object`||Array.isArray(r[e])||r[e]instanceof File)&&(r[e]=Object.create(null)),r=r[e])})},b=e=>g(e,a),x=class{raw;#validatedData;#matchResult;routeIndex=0;path;bodyCache={};constructor(e,t=`/`,n=[[]]){this.raw=e,this.path=t,this.#matchResult=n,this.#validatedData={}}param(e){return e?this.#getDecodedParam(e):this.#getAllDecodedParams()}#getDecodedParam(e){let t=this.#matchResult[0][this.routeIndex][1][e],n=this.#getParamValue(t);return n&&/\%/.test(n)?b(n):n}#getAllDecodedParams(){let e={},t=Object.keys(this.#matchResult[0][this.routeIndex][1]);for(let n of t){let t=this.#getParamValue(this.#matchResult[0][this.routeIndex][1][n]);t!==void 0&&(e[n]=/\%/.test(t)?b(t):t)}return e}#getParamValue(e){return this.#matchResult[1]?this.#matchResult[1][e]:e}query(e){return l(this.url,e)}queries(e){return u(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t={};return this.raw.headers.forEach((e,n)=>{t[n]=e}),t}async parseBody(e){return this.bodyCache.parsedBody??=await ne(this,e)}#cachedBody=e=>{let{bodyCache:t,raw:n}=this,r=t[e];if(r)return r;let i=Object.keys(t)[0];return i?t[i].then(t=>(i===`json`&&(t=JSON.stringify(t)),new Response(t)[e]())):t[e]=n[e]()};json(){return this.#cachedBody(`text`).then(e=>JSON.parse(e))}text(){return this.#cachedBody(`text`)}arrayBuffer(){return this.#cachedBody(`arrayBuffer`)}blob(){return this.#cachedBody(`blob`)}formData(){return this.#cachedBody(`formData`)}addValidatedData(e,t){this.#validatedData[e]=t}valid(e){return this.#validatedData[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[te](){return this.#matchResult}get matchedRoutes(){return this.#matchResult[0].map(([[,e]])=>e)}get routePath(){return this.#matchResult[0].map(([[,e]])=>e)[this.routeIndex].path}},ae={Stringify:1,BeforeStream:2,Stream:3},S=(e,t)=>{let n=new String(e);return n.isEscaped=!0,n.callbacks=t,n},C=async(e,t,n,r,i)=>{typeof e==`object`&&!(e instanceof String)&&(e instanceof Promise||(e=e.toString()),e instanceof Promise&&(e=await e));let a=e.callbacks;if(!a?.length)return Promise.resolve(e);i?i[0]+=e:i=[e];let o=Promise.all(a.map(e=>e({phase:t,buffer:i,context:r}))).then(e=>Promise.all(e.filter(Boolean).map(e=>C(e,t,!1,r,i))).then(()=>i[0]));return n?S(await o,a):o},w=`text/plain; charset=UTF-8`,T=(e,t)=>({"Content-Type":e,...t}),oe=class{#rawRequest;#req;env={};#var;finalized=!1;error;#status;#executionCtx;#res;#layout;#renderer;#notFoundHandler;#preparedHeaders;#matchResult;#path;constructor(e,t){this.#rawRequest=e,t&&(this.#executionCtx=t.executionCtx,this.env=t.env,this.#notFoundHandler=t.notFoundHandler,this.#path=t.path,this.#matchResult=t.matchResult)}get req(){return this.#req??=new x(this.#rawRequest,this.#path,this.#matchResult),this.#req}get event(){if(this.#executionCtx&&`respondWith`in this.#executionCtx)return this.#executionCtx;throw Error(`This context has no FetchEvent`)}get executionCtx(){if(this.#executionCtx)return this.#executionCtx;throw Error(`This context has no ExecutionContext`)}get res(){return this.#res||=new Response(null,{headers:this.#preparedHeaders??=new Headers})}set res(e){if(this.#res&&e){e=new Response(e.body,e);for(let[t,n]of this.#res.headers.entries()){if(t===`content-type`)continue;if(t===`set-cookie`){let t=this.#res.headers.getSetCookie();e.headers.delete(`set-cookie`);for(let n of t)e.headers.append(`set-cookie`,n)}else e.headers.set(t,n)}}this.#res=e,this.finalized=!0}render=(...e)=>(this.#renderer??=e=>this.html(e),this.#renderer(...e));setLayout=e=>this.#layout=e;getLayout=()=>this.#layout;setRenderer=e=>{this.#renderer=e};header=(e,t,n)=>{this.finalized&&(this.#res=new Response(this.#res.body,this.#res));let r=this.#res?this.#res.headers:this.#preparedHeaders??=new Headers;t===void 0?r.delete(e):n?.append?r.append(e,t):r.set(e,t)};status=e=>{this.#status=e};set=(e,t)=>{this.#var??=new Map,this.#var.set(e,t)};get=e=>this.#var?this.#var.get(e):void 0;get var(){return this.#var?Object.fromEntries(this.#var):{}}#newResponse(e,t,n){let r=this.#res?new Headers(this.#res.headers):this.#preparedHeaders??new Headers;if(typeof t==`object`&&`headers`in t){let e=t.headers instanceof Headers?t.headers:new Headers(t.headers);for(let[t,n]of e)t.toLowerCase()===`set-cookie`?r.append(t,n):r.set(t,n)}if(n)for(let[e,t]of Object.entries(n))if(typeof t==`string`)r.set(e,t);else{r.delete(e);for(let n of t)r.append(e,n)}let i=typeof t==`number`?t:t?.status??this.#status;return new Response(e,{status:i,headers:r})}newResponse=(...e)=>this.#newResponse(...e);body=(e,t,n)=>this.#newResponse(e,t,n);text=(e,t,n)=>!this.#preparedHeaders&&!this.#status&&!t&&!n&&!this.finalized?new Response(e):this.#newResponse(e,t,T(w,n));json=(e,t,n)=>this.#newResponse(JSON.stringify(e),t,T(`application/json`,n));html=(e,t,n)=>{let r=e=>this.#newResponse(e,t,T(`text/html; charset=UTF-8`,n));return typeof e==`object`?C(e,ae.Stringify,!1,{}).then(r):r(e)};redirect=(e,t)=>{let n=String(e);return this.header(`Location`,/[^\x00-\xFF]/.test(n)?encodeURI(n):n),this.newResponse(null,t??302)};notFound=()=>(this.#notFoundHandler??=()=>new Response,this.#notFoundHandler(this))},E=`ALL`,se=`all`,D=[`get`,`post`,`put`,`delete`,`options`,`patch`],O=`Can not add a route since the matcher is already built.`,k=class extends Error{},ce=`__COMPOSED_HANDLER`,le=e=>e.text(`404 Not Found`,404),A=(e,t)=>{if(`getResponse`in e){let n=e.getResponse();return t.newResponse(n.body,n)}return console.error(e),t.text(`Internal Server Error`,500)},j=class{get;post;put;delete;options;patch;all;on;use;router;getPath;_basePath=`/`;#path=`/`;routes=[];constructor(e={}){let t=[...D,se];t.forEach(e=>{this[e]=(t,...n)=>(typeof t==`string`?this.#path=t:this.#addRoute(e,this.#path,t),n.forEach(t=>{this.#addRoute(e,this.#path,t)}),this)}),this.on=(e,t,...n)=>{for(let r of[t].flat()){this.#path=r;for(let t of[e].flat())n.map(e=>{this.#addRoute(t.toUpperCase(),this.#path,e)})}return this},this.use=(e,...t)=>(typeof e==`string`?this.#path=e:(this.#path=`*`,t.unshift(e)),t.forEach(e=>{this.#addRoute(E,this.#path,e)}),this);let{strict:n,...r}=e;Object.assign(this,r),this.getPath=n??!0?e.getPath??o:s}#clone(){let e=new j({router:this.router,getPath:this.getPath});return e.errorHandler=this.errorHandler,e.#notFoundHandler=this.#notFoundHandler,e.routes=this.routes,e}#notFoundHandler=le;errorHandler=A;route(e,t){let n=this.basePath(e);return t.routes.map(e=>{let r;t.errorHandler===A?r=e.handler:(r=async(n,r)=>(await _([],t.errorHandler)(n,()=>e.handler(n,r))).res,r[ce]=e.handler),n.#addRoute(e.method,e.path,r)}),this}basePath(e){let t=this.#clone();return t._basePath=d(this._basePath,e),t}onError=e=>(this.errorHandler=e,this);notFound=e=>(this.#notFoundHandler=e,this);mount(e,t,n){let r,i;n&&(typeof n==`function`?i=n:(i=n.optionHandler,r=n.replaceRequest===!1?e=>e:n.replaceRequest));let a=i?e=>{let t=i(e);return Array.isArray(t)?t:[t]}:e=>{let t;try{t=e.executionCtx}catch{}return[e.env,t]};r||=(()=>{let t=d(this._basePath,e),n=t===`/`?0:t.length;return e=>{let t=new URL(e.url);return t.pathname=t.pathname.slice(n)||`/`,new Request(t,e)}})();let o=async(e,n)=>{let i=await t(r(e.req.raw),...a(e));if(i)return i;await n()};return this.#addRoute(E,d(e,`*`),o),this}#addRoute(e,t,n){e=e.toUpperCase(),t=d(this._basePath,t);let r={basePath:this._basePath,path:t,method:e,handler:n};this.router.add(e,t,[n,r]),this.routes.push(r)}#handleError(e,t){if(e instanceof Error)return this.errorHandler(e,t);throw e}#dispatch(e,t,n,r){if(r===`HEAD`)return(async()=>new Response(null,await this.#dispatch(e,t,n,`GET`)))();let i=this.getPath(e,{env:n}),a=this.router.match(r,i),o=new oe(e,{path:i,matchResult:a,env:n,executionCtx:t,notFoundHandler:this.#notFoundHandler});if(a[0].length===1){let e;try{e=a[0][0][0][0](o,async()=>{o.res=await this.#notFoundHandler(o)})}catch(e){return this.#handleError(e,o)}return e instanceof Promise?e.then(e=>e||(o.finalized?o.res:this.#notFoundHandler(o))).catch(e=>this.#handleError(e,o)):e??this.#notFoundHandler(o)}let s=_(a[0],this.errorHandler,this.#notFoundHandler);return(async()=>{try{let e=await s(o);if(!e.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return e.res}catch(e){return this.#handleError(e,o)}})()}fetch=(e,...t)=>this.#dispatch(e,t[1],t[0],e.method);request=(e,t,n,r)=>e instanceof Request?this.fetch(t?new Request(e,t):e,n,r):(e=e.toString(),this.fetch(new Request(/^https?:\/\//.test(e)?e:`http://localhost${d(`/`,e)}`,t),n,r));fire=()=>{addEventListener(`fetch`,e=>{e.respondWith(this.#dispatch(e.request,e,void 0,e.request.method))})}},M=`[^/]+`,N=`.*`,P=`(?:|/.*)`,F=Symbol(),I=new Set(`.\\+*[^]$()`);function L(e,t){return e.length===1?t.length===1?e<t?-1:1:-1:t.length===1||e===N||e===P?1:t===N||t===P?-1:e===M?1:t===M?-1:e.length===t.length?e<t?-1:1:t.length-e.length}var R=class{#index;#varIndex;#children=Object.create(null);insert(e,t,n,r,i){if(e.length===0){if(this.#index!==void 0)throw F;if(i)return;this.#index=t;return}let[a,...o]=e,s=a===`*`?o.length===0?[``,``,N]:[``,``,M]:a===`/*`?[``,``,P]:a.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),c;if(s){let e=s[1],t=s[2]||M;if(e&&s[2]&&(t===`.*`||(t=t.replace(/^\((?!\?:)(?=[^)]+\)$)/,`(?:`),/\((?!\?:)/.test(t))))throw F;if(c=this.#children[t],!c){if(Object.keys(this.#children).some(e=>e!==N&&e!==P))throw F;if(i)return;c=this.#children[t]=new R,e!==``&&(c.#varIndex=r.varIndex++)}!i&&e!==``&&n.push([e,c.#varIndex])}else if(c=this.#children[a],!c){if(Object.keys(this.#children).some(e=>e.length>1&&e!==N&&e!==P))throw F;if(i)return;c=this.#children[a]=new R}c.insert(o,t,n,r,i)}buildRegExpStr(){let e=Object.keys(this.#children).sort(L),t=e.map(e=>{let t=this.#children[e];return(typeof t.#varIndex==`number`?`(${e})@${t.#varIndex}`:I.has(e)?`\\${e}`:e)+t.buildRegExpStr()});return typeof this.#index==`number`&&t.unshift(`#${this.#index}`),t.length===0?``:t.length===1?t[0]:`(?:`+t.join(`|`)+`)`}},z=class{#context={varIndex:0};#root=new R;insert(e,t,n){let r=[],i=[];for(let t=0;;){let n=!1;if(e=e.replace(/\{[^}]+\}/g,e=>{let r=`@\\${t}`;return i[t]=[r,e],t++,n=!0,r}),!n)break}let a=e.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let e=i.length-1;e>=0;e--){let[t]=i[e];for(let n=a.length-1;n>=0;n--)if(a[n].indexOf(t)!==-1){a[n]=a[n].replace(t,i[e][1]);break}}return this.#root.insert(a,t,r,this.#context,n),r}buildRegExp(){let e=this.#root.buildRegExpStr();if(e===``)return[/^$/,[],[]];let t=0,n=[],r=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(e,i,a)=>i===void 0?(a===void 0||(r[Number(a)]=++t),``):(n[++t]=Number(i),`$()`)),[RegExp(`^${e}`),n,r]}},B=[],V=[/^$/,[],Object.create(null)],H=Object.create(null);function U(e){return H[e]??=RegExp(e===`*`?``:`^${e.replace(/\/\*$|([.\\+*[^\]$()])/g,(e,t)=>t?`\\${t}`:`(?:|/.*)`)}$`)}function ue(){H=Object.create(null)}function de(e){let t=new z,n=[];if(e.length===0)return V;let r=e.map(e=>[!/\*|\/:/.test(e[0]),...e]).sort(([e,t],[n,r])=>e?1:n?-1:t.length-r.length),i=Object.create(null);for(let e=0,a=-1,o=r.length;e<o;e++){let[o,s,c]=r[e];o?i[s]=[c.map(([e])=>[e,Object.create(null)]),B]:a++;let l;try{l=t.insert(s,a,o)}catch(e){throw e===F?new k(s):e}o||(n[a]=c.map(([e,t])=>{let n=Object.create(null);for(--t;t>=0;t--){let[e,r]=l[t];n[e]=r}return[e,n]}))}let[a,o,s]=t.buildRegExp();for(let e=0,t=n.length;e<t;e++)for(let t=0,r=n[e].length;t<r;t++){let r=n[e][t]?.[1];if(!r)continue;let i=Object.keys(r);for(let e=0,t=i.length;e<t;e++)r[i[e]]=s[r[i[e]]]}let c=[];for(let e in o)c[e]=n[o[e]];return[a,c,i]}function W(e,t){if(e){for(let n of Object.keys(e).sort((e,t)=>t.length-e.length))if(U(n).test(t))return[...e[n]]}}var fe=class{name=`RegExpRouter`;#middleware;#routes;constructor(){this.#middleware={[E]:Object.create(null)},this.#routes={[E]:Object.create(null)}}add(e,t,n){let i=this.#middleware,a=this.#routes;if(!i||!a)throw Error(O);i[e]||[i,a].forEach(t=>{t[e]=Object.create(null),Object.keys(t[E]).forEach(n=>{t[e][n]=[...t[E][n]]})}),t===`/*`&&(t=`*`);let o=(t.match(/\/:/g)||[]).length;if(/\*$/.test(t)){let r=U(t);e===E?Object.keys(i).forEach(e=>{i[e][t]||=W(i[e],t)||W(i[E],t)||[]}):i[e][t]||=W(i[e],t)||W(i[E],t)||[],Object.keys(i).forEach(t=>{(e===E||e===t)&&Object.keys(i[t]).forEach(e=>{r.test(e)&&i[t][e].push([n,o])})}),Object.keys(a).forEach(t=>{(e===E||e===t)&&Object.keys(a[t]).forEach(e=>r.test(e)&&a[t][e].push([n,o]))});return}let s=r(t)||[t];for(let t=0,r=s.length;t<r;t++){let c=s[t];Object.keys(a).forEach(s=>{(e===E||e===s)&&(a[s][c]||=[...W(i[s],c)||W(i[E],c)||[]],a[s][c].push([n,o-r+t+1]))})}}match(e,t){ue();let n=this.#buildAllMatchers();return this.match=(e,t)=>{let r=n[e]||n[E],i=r[2][t];if(i)return i;let a=t.match(r[0]);if(!a)return[[],B];let o=a.indexOf(``,1);return[r[1][o],a]},this.match(e,t)}#buildAllMatchers(){let e=Object.create(null);return Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach(t=>{e[t]||=this.#buildMatcher(t)}),this.#middleware=this.#routes=void 0,e}#buildMatcher(e){let t=[],n=e===E;return[this.#middleware,this.#routes].forEach(r=>{let i=r[e]?Object.keys(r[e]).map(t=>[t,r[e][t]]):[];i.length===0?e!==E&&t.push(...Object.keys(r[E]).map(e=>[e,r[E][e]])):(n||=!0,t.push(...i))}),n?de(t):null}},pe=class{name=`SmartRouter`;#routers=[];#routes=[];constructor(e){this.#routers=e.routers}add(e,t,n){if(!this.#routes)throw Error(O);this.#routes.push([e,t,n])}match(e,t){if(!this.#routes)throw Error(`Fatal error`);let n=this.#routers,r=this.#routes,i=n.length,a=0,o;for(;a<i;a++){let i=n[a];try{for(let e=0,t=r.length;e<t;e++)i.add(...r[e]);o=i.match(e,t)}catch(e){if(e instanceof k)continue;throw e}this.match=i.match.bind(i),this.#routers=[i],this.#routes=void 0;break}if(a===i)throw Error(`Fatal error`);return this.name=`SmartRouter + ${this.activeRouter.name}`,o}get activeRouter(){if(this.#routes||this.#routers.length!==1)throw Error(`No active router has been determined yet.`);return this.#routers[0]}},G=Object.create(null),K=class{#methods;#children;#patterns;#order=0;#params=G;constructor(e,t,n){if(this.#children=n||Object.create(null),this.#methods=[],e&&t){let n=Object.create(null);n[e]={handler:t,possibleKeys:[],score:0},this.#methods=[n]}this.#patterns=[]}insert(e,t,n){this.#order=++this.#order;let r=this,i=m(t),a=[];for(let e=0,t=i.length;e<t;e++){let t=i[e],n=i[e+1],o=c(t,n),s=Array.isArray(o)?o[0]:t;if(s in r.#children){r=r.#children[s],o&&a.push(o[1]);continue}r.#children[s]=new K,o&&(r.#patterns.push(o),a.push(o[1])),r=r.#children[s]}return r.#methods.push({[e]:{handler:n,possibleKeys:a.filter((e,t,n)=>n.indexOf(e)===t),score:this.#order}}),r}#getHandlerSets(e,t,n,r){let i=[];for(let a=0,o=e.#methods.length;a<o;a++){let o=e.#methods[a],s=o[t]||o[E],c={};if(s!==void 0&&(s.params=Object.create(null),i.push(s),n!==G||r&&r!==G))for(let e=0,t=s.possibleKeys.length;e<t;e++){let t=s.possibleKeys[e],i=c[s.score];s.params[t]=r?.[t]&&!i?r[t]:n[t]??r?.[t],c[s.score]=!0}}return i}search(e,t){let n=[];this.#params=G;let r=this,i=[r],a=p(t),o=[];for(let t=0,r=a.length;t<r;t++){let s=a[t],c=t===r-1,l=[];for(let r=0,u=i.length;r<u;r++){let u=i[r],d=u.#children[s];d&&(d.#params=u.#params,c?(d.#children[`*`]&&n.push(...this.#getHandlerSets(d.#children[`*`],e,u.#params)),n.push(...this.#getHandlerSets(d,e,u.#params))):l.push(d));for(let r=0,i=u.#patterns.length;r<i;r++){let i=u.#patterns[r],d=u.#params===G?{}:{...u.#params};if(i===`*`){let t=u.#children[`*`];t&&(n.push(...this.#getHandlerSets(t,e,u.#params)),t.#params=d,l.push(t));continue}let[f,p,m]=i;if(!s&&!(m instanceof RegExp))continue;let h=u.#children[f],g=a.slice(t).join(`/`);if(m instanceof RegExp){let t=m.exec(g);if(t){if(d[p]=t[0],n.push(...this.#getHandlerSets(h,e,u.#params,d)),Object.keys(h.#children).length){h.#params=d;let e=t[0].match(/\//)?.length??0,n=o[e]||=[];n.push(h)}continue}}(m===!0||m.test(s))&&(d[p]=s,c?(n.push(...this.#getHandlerSets(h,e,d,u.#params)),h.#children[`*`]&&n.push(...this.#getHandlerSets(h.#children[`*`],e,d,u.#params))):(h.#params=d,l.push(h)))}}i=l.concat(o.shift()??[])}return n.length>1&&n.sort((e,t)=>e.score-t.score),[n.map(({handler:e,params:t})=>[e,t])]}},me=class{name=`TrieRouter`;#node;constructor(){this.#node=new K}add(e,t,n){let i=r(t);if(i){for(let t=0,r=i.length;t<r;t++)this.#node.insert(e,i[t],n);return}this.#node.insert(e,t,n)}match(e,t){return this.#node.search(e,t)}},q=class extends j{constructor(e={}){super(e),this.router=e.router??new pe({routers:[new fe,new me]})}},he=(e,t,n)=>{let r=e.req.raw.headers.get(`Cookie`);if(typeof t==`string`){if(!r)return;let e=t;n===`secure`?e=`__Secure-`+t:n===`host`&&(e=`__Host-`+t);let i=f(r,e);return i[e]}if(!r)return{};let i=f(r);return i},J=class extends Error{res;status;constructor(e=500,t){super(t?.message,{cause:t?.cause}),this.res=t?.res,this.status=e}getResponse(){if(this.res){let e=new Response(this.res.body,{status:this.status,headers:this.res.headers});return e}return new Response(this.message,{status:this.status})}},ge=(e,t)=>{let n=new Response(e,{headers:{"Content-Type":t}});return n.formData()},_e=/^application\/([a-z-\.]+\+)?json(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,ve=/^multipart\/form-data(;\s?boundary=[a-zA-Z0-9'"()+_,\-./:=?]+)?$/,ye=/^application\/x-www-form-urlencoded(;\s*[a-zA-Z0-9\-]+\=([^;]+))*$/,Y=(e,t)=>async(n,r)=>{let i={},a=n.req.header(`Content-Type`);switch(e){case`json`:if(!a||!_e.test(a))break;try{i=await n.req.json()}catch{throw new J(400,{message:`Malformed JSON in request body`})}break;case`form`:{if(!a||!(ve.test(a)||ye.test(a)))break;let e;if(n.req.bodyCache.formData)e=await n.req.bodyCache.formData;else try{let t=await n.req.arrayBuffer();e=await ge(t,a),n.req.bodyCache.formData=e}catch(e){let t=`Malformed FormData request.`;throw t+=e instanceof Error?` ${e.message}`:` ${String(e)}`,new J(400,{message:t})}let t={};e.forEach((e,n)=>{n.endsWith(`[]`)?(t[n]??=[]).push(e):Array.isArray(t[n])?t[n].push(e):n in t?t[n]=[t[n],e]:t[n]=e}),i=t;break}case`query`:i=Object.fromEntries(Object.entries(n.req.queries()).map(([e,t])=>t.length===1?[e,t[0]]:[e,t]));break;case`param`:i=n.req.param();break;case`header`:i=n.req.header();break;case`cookie`:i=he(n);break}let o=await t(i,n);if(o instanceof Response)return o;n.req.addValidatedData(e,o),await r()};const X=(e,t)=>e.json({error:t},400),Z=e=>{let t=e.req.param(`key`);return!t||t===``?{key:t,err:`Key is required`}:t.length>128?{key:t,err:`Key is too long. Max length is 128 characters.`}:{key:t}},Q=()=>new q,be=Q().get(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let r=await e.env.storage.kv.get(t);return e.json({value:r},200)}).post(`/kv/:key`,Y(`json`,(e,t)=>{let n=e.value;return n?typeof n==`string`?n.length>1024?X(t,`Value is too long. Max length is 1024 characters.`):{value:n}:X(t,`Value must be a string`):X(t,`Value is required`)}),async e=>{let{key:t,err:n}=Z(e);if(n)return X(e,n);let{value:r}=e.req.valid(`json`);return await e.env.storage.kv.set(t,r),e.body(null,204)}).delete(`/kv/:key`,async e=>{let{key:t,err:n}=Z(e);return n?X(e,n):(await e.env.storage.kv.del(t),e.body(null,204))}),$=e=>{let t=e.req.param(`id`);return t?t.length>128?{id:t,err:`ID is too long. Max length is 128 characters.`}:{id:t}:{id:t,err:`ID is required`}},xe=Q().basePath(`/:id`).post(`/`,async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let r=await e.env.chat.upsert(t);return e.json({id:r.id},200)}).post(`/sendMessages`,Y(`json`,(e,t)=>{let n=e.messages;if(!n)return X(t,`Messages are required`);if(!Array.isArray(n))return X(t,`Messages must be an array`);if(n.length===0)return X(t,`Messages must not be empty`);let r=e.behavior;return r!==`enqueue`&&r!==`interrupt`&&r!==`append`?X(t,`Invalid behavior`):{messages:n,behavior:r}}),async e=>{let{id:t,err:n}=$(e);if(n)return X(e,n);let{messages:r,behavior:i}=e.req.valid(`json`);try{await e.env.chat.sendMessages(t,{messages:r,behavior:i})}catch(t){return X(e,t instanceof Error?t.message:`Unknown error`)}return e.body(null,204)}),Se=new q().route(`/storage`,be).route(`/chat`,xe);export{e as APIServerURLEnvironmentVariable,t as Client,n as StreamResponseFormatHeader,Se as api,i as convertResponseToUIMessageStream,ee as createAsyncIterableStream,h as streamSSE};
@@ -1 +0,0 @@
1
- const e=require(`./client-DFaZjb1-.cjs`);let t=require(`ai`);t=e.__toESM(t);const n=Object.freeze({upsert:async t=>{let n=await e.client.chat[`:id`].$post({param:{id:t}});if(n.status!==200){let e=await n.json();throw Error(e.error)}return{id:t}},message:async(t,n,r)=>{let i=await e.client.chat[`:id`].sendMessages.$post({param:{id:t},json:{messages:[n],behavior:r?.behavior??`enqueue`}});if(i.status!==204){let e=await i.json();throw Error(e.error)}}}),r=Object.freeze({kv:Object.freeze({get:async t=>{let n=await e.client.storage.kv[`:key`].$get({param:{key:t}});if(n.status!==200){let e=await n.json();throw Error(e.error)}let r=await n.json();return r.value},set:async(t,n)=>{let r=await e.client.storage.kv[`:key`].$post({param:{key:t},json:{value:n}});if(r.status!==204){let e=await r.json();throw Error(e.error)}},del:async t=>{let n=await e.client.storage.kv[`:key`].$delete({param:{key:t}});if(n.status!==204){let e=await n.json();throw Error(e.error)}}})});function i(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}var a=class extends Error{constructor(e,t){super(e),this.response=t}};function o(e){return e}const s={withContext(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},with(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},async withApproval(e){let n={};for(let[t,r]of Object.entries(e.tools)){let e=r.execute;n[t]={...r,execute:async(t,n)=>{if(r.autoApprove&&e){let i=await r.autoApprove(t);if(i)return e(t,n)}let i={type:`tool-approval`,outcome:`pending`};return i}}}let r=e.messages[e.messages.length-1];if(!r?.parts)return n;let o=[];for(let n of r.parts){if(!(0,t.isToolUIPart)(n))continue;let r=(0,t.getToolName)(n),i=e.tools[r];if(!i||n.state!==`output-available`||!i.execute||!c(n.output))continue;n.output.outcome===`approved`&&o.push({toolName:(0,t.getToolName)(n),tool:i,input:n.input,toolCallId:n.toolCallId})}if(o.length>0){let n=(0,t.createUIMessageStream)({execute:async({writer:n})=>{n.write({type:`start-step`}),await Promise.all(o.map(async r=>{if(!r.tool.execute)throw Error(`Tool does not support execute.`);n.write({type:`tool-input-available`,toolCallId:r.toolCallId,toolName:r.toolName,input:r.input});try{let a=await r.tool.execute(r.input,{toolCallId:r.toolCallId,messages:(0,t.convertToModelMessages)(e.messages,{tools:e.tools}),abortSignal:e.abortSignal});if(i(a))for await(let e of a)n.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:e,preliminary:!0});n.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:a})}catch(e){n.write({type:`tool-output-error`,toolCallId:r.toolCallId,errorText:e instanceof Error?e.message:String(e)})}})),n.write({type:`finish`})}});throw new a(`Executing tools`,n)}return n},prefix(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}${r}`]=i;return n}};function c(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool-approval`}function l(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n!==void 0&&n.role===`user`&&!(typeof n.metadata!=`object`||n.metadata===null)&&`options`in n.metadata)return n.metadata.options}}function u(t,n){let r=new Headers(t.headers);return r.set(e.StreamResponseFormatHeader,n),new Response(t.body,{status:t.status,statusText:t.statusText,headers:r})}Object.defineProperty(exports,`chat`,{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,`isToolApprovalOutput`,{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,`lastUIOptions`,{enumerable:!0,get:function(){return l}}),Object.defineProperty(exports,`storage`,{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,`toolWithApproval`,{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,`tools`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`withResponseFormat`,{enumerable:!0,get:function(){return u}});
@@ -1 +0,0 @@
1
- import{StreamResponseFormatHeader as e,client as t}from"./client-BbZudkEc.js";import{convertToModelMessages as n,createUIMessageStream as r,getToolName as i,isToolUIPart as a}from"ai";const o=Object.freeze({upsert:async e=>{let n=await t.chat[`:id`].$post({param:{id:e}});if(n.status!==200){let e=await n.json();throw Error(e.error)}return{id:e}},message:async(e,n,r)=>{let i=await t.chat[`:id`].sendMessages.$post({param:{id:e},json:{messages:[n],behavior:r?.behavior??`enqueue`}});if(i.status!==204){let e=await i.json();throw Error(e.error)}}}),s=Object.freeze({kv:Object.freeze({get:async e=>{let n=await t.storage.kv[`:key`].$get({param:{key:e}});if(n.status!==200){let e=await n.json();throw Error(e.error)}let r=await n.json();return r.value},set:async(e,n)=>{let r=await t.storage.kv[`:key`].$post({param:{key:e},json:{value:n}});if(r.status!==204){let e=await r.json();throw Error(e.error)}},del:async e=>{let n=await t.storage.kv[`:key`].$delete({param:{key:e}});if(n.status!==204){let e=await n.json();throw Error(e.error)}}})});function c(e){return typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`}var l=class extends Error{constructor(e,t){super(e),this.response=t}};function u(e){return e}const d={withContext(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},with(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];n[r]=i.withContext(t)}return n},async withApproval(e){let t={};for(let[n,r]of Object.entries(e.tools)){let e=r.execute;t[n]={...r,execute:async(t,n)=>{if(r.autoApprove&&e){let i=await r.autoApprove(t);if(i)return e(t,n)}let i={type:`tool-approval`,outcome:`pending`};return i}}}let o=e.messages[e.messages.length-1];if(!o?.parts)return t;let s=[];for(let t of o.parts){if(!a(t))continue;let n=i(t),r=e.tools[n];if(!r||t.state!==`output-available`||!r.execute||!f(t.output))continue;t.output.outcome===`approved`&&s.push({toolName:i(t),tool:r,input:t.input,toolCallId:t.toolCallId})}if(s.length>0){let t=r({execute:async({writer:t})=>{t.write({type:`start-step`}),await Promise.all(s.map(async r=>{if(!r.tool.execute)throw Error(`Tool does not support execute.`);t.write({type:`tool-input-available`,toolCallId:r.toolCallId,toolName:r.toolName,input:r.input});try{let i=await r.tool.execute(r.input,{toolCallId:r.toolCallId,messages:n(e.messages,{tools:e.tools}),abortSignal:e.abortSignal});if(c(i))for await(let e of i)t.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:e,preliminary:!0});t.write({type:`tool-output-available`,toolCallId:r.toolCallId,output:i})}catch(e){t.write({type:`tool-output-error`,toolCallId:r.toolCallId,errorText:e instanceof Error?e.message:String(e)})}})),t.write({type:`finish`})}});throw new l(`Executing tools`,t)}return t},prefix(e,t){let n={};for(let[r,i]of Object.entries(e))n[`${t}${r}`]=i;return n}};function f(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool-approval`}function p(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n!==void 0&&n.role===`user`&&!(typeof n.metadata!=`object`||n.metadata===null)&&`options`in n.metadata)return n.metadata.options}}function m(t,n){let r=new Headers(t.headers);return r.set(e,n),new Response(t.body,{status:t.status,statusText:t.statusText,headers:r})}export{o as chat,f as isToolApprovalOutput,p as lastUIOptions,s as storage,u as toolWithApproval,d as tools,m as withResponseFormat};