palbase 0.21.0 → 0.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/backend/engine.js +2 -2
- package/dist/backend/env.js +1 -1
- package/dist/backend/index.js +11 -11
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{6B2JVMVC.js → 2TXIGYOJ.js} +1 -1
- package/dist/chunks/{BC7DKAEV.js → 4HAHFRWH.js} +2 -2
- package/dist/chunks/5Q3GX7V7.js +22 -0
- package/dist/chunks/{LHLXKWXT.js → ASHJUFAR.js} +2 -2
- package/dist/chunks/{UTZFJM2O.js → BUZEU3KO.js} +2 -2
- package/dist/chunks/{LHC3VBGV.js → CNM6KHAV.js} +1 -1
- package/dist/chunks/{3MPGMDIO.js → CYQ5IWPO.js} +1 -1
- package/dist/chunks/{Y3KNVE2U.js → EPLCUBM7.js} +1 -1
- package/dist/chunks/{XZY2DTL7.js → GRMAYURX.js} +2 -2
- package/dist/chunks/{5BNYK6GP.js → GUJW2U4D.js} +1 -1
- package/dist/chunks/GXOAVCC5.js +21 -0
- package/dist/chunks/{RTL4OAKC.js → IPHVAOYL.js} +1 -1
- package/dist/chunks/{BQTZYHJN.js → JEBQEIT2.js} +2 -2
- package/dist/chunks/{BYKIJBPE.js → KSRQ5B2V.js} +2 -2
- package/dist/chunks/{PI2NU4TV.js → MQJN2IGB.js} +2 -2
- package/dist/chunks/{PKYERPHS.js → QRRNK56K.js} +2 -2
- package/dist/chunks/{YALT2FTV.js → RRS3QIHN.js} +2 -2
- package/dist/chunks/{23M37HPW.js → RZE7ZGC5.js} +2 -2
- package/dist/chunks/{TUJQKUDT.js → SI3QKQTV.js} +2 -2
- package/dist/chunks/U7YF4HAG.js +18 -0
- package/dist/chunks/{7LCTRRHG.js → X2IT755X.js} +1 -1
- package/dist/chunks/{SIIBIKCD.js → YCVPM3S4.js} +2 -2
- package/dist/chunks/{QZMFPTXQ.js → ZWM2JBGV.js} +2 -2
- package/dist/cli.js +130 -126
- package/dist/cloud/index.js +2 -2
- package/dist/refuse/ai.js +1 -1
- package/dist/refuse/backend.js +1 -1
- package/dist/refuse/cloud.js +1 -1
- package/dist/refuse/server.js +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/testing.js +2 -2
- package/dist/web/index.js +2 -2
- package/dist/web/message.js +2 -2
- package/dist/web/palbe.js +2 -2
- package/dist/web/paywall.js +2 -2
- package/dist/web/push-sw.js +1 -1
- package/dist/web/ssr.js +2 -2
- package/dist/web/vite.js +2 -2
- package/package.json +2 -2
- package/types/ai/src/chats.d.ts +20 -1
- package/types/ai/src/index.d.ts +2 -2
- package/types/ai/src/tools.d.ts +20 -0
- package/types/backend/src/attest.d.ts +18 -2
- package/types/backend/src/bootstrap.d.ts +2 -4
- package/types/backend/src/database.d.ts +12 -2
- package/types/backend/src/engine.d.ts +10 -3
- package/types/backend/src/index.d.ts +1 -1
- package/types/internal/src/modules/ai.d.ts +46 -2
- package/types/web/src/notify.d.ts +44 -2
- package/dist/chunks/DEMLN2MO.js +0 -18
- package/dist/chunks/PJLACUYP.js +0 -22
- package/dist/chunks/TACI6JAQ.js +0 -21
|
@@ -142,10 +142,17 @@ export interface RequestDatabases {
|
|
|
142
142
|
rollback(reason: unknown): Promise<void>;
|
|
143
143
|
};
|
|
144
144
|
}
|
|
145
|
+
/**
|
|
146
|
+
* What the host knows of a request beyond the Request: the peer's address, and the request-target as it came on the
|
|
147
|
+
* wire (its path and query, byte for byte) — what a device's proof signed, which the Request's URL, parsed, may have
|
|
148
|
+
* encoded otherwise (a ' or a ^ in a query).
|
|
149
|
+
*/
|
|
150
|
+
export interface RequestInfo {
|
|
151
|
+
remoteAddress?: string;
|
|
152
|
+
target?: string;
|
|
153
|
+
}
|
|
145
154
|
export interface App {
|
|
146
|
-
handle(request: Request, info?:
|
|
147
|
-
remoteAddress?: string;
|
|
148
|
-
}): Promise<Response>;
|
|
155
|
+
handle(request: Request, info?: RequestInfo): Promise<Response>;
|
|
149
156
|
start(): Promise<void>;
|
|
150
157
|
stop(): Promise<void>;
|
|
151
158
|
readonly routes: readonly string[];
|
|
@@ -9,7 +9,7 @@ export type { AgentContext, ToolContext, TurnDefinition, TurnMessage } from '../
|
|
|
9
9
|
export { getWebhookManifest, type WebhookEventHandler, type WebhookMeta } from './webhooks.js';
|
|
10
10
|
export { DiError, type DiErrorKind } from './container.js';
|
|
11
11
|
export { BadRequest, Conflict, DeadlockDetected, Forbidden, HttpError, NotFound, PalError, SerializationFailure, TooManyRequests, Unauthorized, UniqueViolation, defineError, type DefinedError, type DefinedErrorWithData, type Envelope, type FieldIssue, } from './errors.js';
|
|
12
|
-
export { createApp, MAX_BODY_BYTES, type App, type AppOptions, type AppTokens, type ClientInfo, type CorsOptions, type UserT } from './engine.js';
|
|
12
|
+
export { createApp, MAX_BODY_BYTES, type App, type AppOptions, type AppTokens, type ClientInfo, type CorsOptions, type RequestInfo, type UserT } from './engine.js';
|
|
13
13
|
export { ContractRunEnded, MigrationRunEnded, PalbaseFactory, type AppConfig, type PalbaseApplication } from './bootstrap.js';
|
|
14
14
|
export { SchemaNotPushed } from './database.js';
|
|
15
15
|
export type { DatabaseConfig } from './database.js';
|
|
@@ -1,4 +1,25 @@
|
|
|
1
1
|
import { type Reply, type Transport } from '../transport.js';
|
|
2
|
+
/**
|
|
3
|
+
* A second model beside the agent: it reads what the agent does after every step — its messages, the reasoning its model gives, its tool calls and what they answered — and, when a decision goes against the agent's instructions, its goal or the advisor's own rules (instructions), tells the agent so at its next step. The agent may ask it, and a turn's answer waits for its reading. It only reads: the agent's workspace, and the tools of the MCP servers named here that say they only read (readOnlyHint). Its calls are the turn's: they count in its cost and its limit.
|
|
4
|
+
*/
|
|
5
|
+
export type Advisor = {
|
|
6
|
+
/**
|
|
7
|
+
* How hard its model thinks. Left out: the platform's.
|
|
8
|
+
*/
|
|
9
|
+
effort?: "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
|
10
|
+
/**
|
|
11
|
+
* Its rules: what it watches the agent for.
|
|
12
|
+
*/
|
|
13
|
+
instructions?: string;
|
|
14
|
+
/**
|
|
15
|
+
* A role (fast, default, strong) or a catalogue model. Left out: the agent's.
|
|
16
|
+
*/
|
|
17
|
+
model?: string;
|
|
18
|
+
/**
|
|
19
|
+
* MCP servers it reads with (source mcp; 32 at most): a turn gives it a server's tools that say they only read (readOnlyHint) — those named in only, which must say so (400 advisor_tool_not_read_only otherwise). Nothing it reads waits for a person (approval false).
|
|
20
|
+
*/
|
|
21
|
+
tools?: ToolRef[];
|
|
22
|
+
};
|
|
2
23
|
/**
|
|
3
24
|
* An agent of the project's. One its backend defines (source code) is its build's: it is changed in the code, and here is what its last turn was defined as. One the project keeps (source platform) is changed as a draft, and its chats talk to the version published.
|
|
4
25
|
*/
|
|
@@ -55,6 +76,7 @@ export type Agent = {
|
|
|
55
76
|
* What an agent is: its instructions, model, tools and subagents, and the shape of its one-shot answers.
|
|
56
77
|
*/
|
|
57
78
|
export type AgentDefinition = {
|
|
79
|
+
advisor?: Advisor;
|
|
58
80
|
/**
|
|
59
81
|
* The window, in tokens, the turn works in (the model's standard one unless said; more is billed as its provider bills it — GET /ai/models, context_window and max_input_tokens).
|
|
60
82
|
*/
|
|
@@ -418,7 +440,7 @@ export type ChatPart = {
|
|
|
418
440
|
*/
|
|
419
441
|
part_id: string;
|
|
420
442
|
/**
|
|
421
|
-
* message, turn, text, reset, thinking, tool, agent, goal, voice, transcript — as the stream says them.
|
|
443
|
+
* message, turn, text, reset, thinking, tool, agent, advisor, goal, voice, transcript — as the stream says them.
|
|
422
444
|
*/
|
|
423
445
|
type: string;
|
|
424
446
|
};
|
|
@@ -2105,10 +2127,32 @@ export type TurnBudget = {
|
|
|
2105
2127
|
*/
|
|
2106
2128
|
max_cost_usd: number;
|
|
2107
2129
|
};
|
|
2130
|
+
/**
|
|
2131
|
+
* What the agent's advisor spent reading the turn so far: inside the turn's totals and its run's, said apart. Absent when the agent has no advisor, or it has spent nothing yet.
|
|
2132
|
+
*/
|
|
2133
|
+
export type TurnAdvisorCost = {
|
|
2134
|
+
cache_read_tokens: number;
|
|
2135
|
+
cache_write_tokens: number;
|
|
2136
|
+
/**
|
|
2137
|
+
* What its calls cost, in billionths of a US dollar.
|
|
2138
|
+
*/
|
|
2139
|
+
cost_nano_usd: number;
|
|
2140
|
+
input_tokens: number;
|
|
2141
|
+
output_tokens: number;
|
|
2142
|
+
/**
|
|
2143
|
+
* Its model has no price: the cost is a lower bound.
|
|
2144
|
+
*/
|
|
2145
|
+
unpriced: boolean;
|
|
2146
|
+
/**
|
|
2147
|
+
* cost_nano_usd in dollars.
|
|
2148
|
+
*/
|
|
2149
|
+
usd: number;
|
|
2150
|
+
};
|
|
2108
2151
|
/**
|
|
2109
2152
|
* What one turn of a chat cost so far: its model calls and its subagents', at the engine's frozen rates.
|
|
2110
2153
|
*/
|
|
2111
2154
|
export type TurnCost = {
|
|
2155
|
+
advisor?: TurnAdvisorCost;
|
|
2112
2156
|
/**
|
|
2113
2157
|
* The chat.
|
|
2114
2158
|
*/
|
|
@@ -2959,7 +3003,7 @@ export declare function client(t: Transport): {
|
|
|
2959
3003
|
/**
|
|
2960
3004
|
* Pipe the chat into a channel
|
|
2961
3005
|
*
|
|
2962
|
-
* Writes the chat's stream into a channel of the project's realtime from now on — a gateway's, durable — as the platform: the members' messages, the turns, the answer as it is written (gathered into a few writes a second), the tools and subagents, each the channel's event `chat` {type, id?, data}, under an id of its own so a retry is kept once. The types: `message` (a ChatMessage, as the agent got it), `turn` ({response_id, status: running|waiting|completed|failed|canceled|timed_out|budget_exceeded, user_id, solo, goal: {goal_id, role: work|verify, seq} — a turn of the chat's goal, waiting: {reason: approval|tool_output|subagents|message, text_offset, approval_id, tool_call_id, tool_name, input, publication}, end: completed|failed|stopped|budget_exceeded — as the turn's event says it, error: {code, message, retryable}}), `text` ({response_id, offset, text}: the agent's answer as it is written, at its byte offset), `reset` ({response_id, offset}: discard the answer past offset), `thinking` ({response_id, run_id, step_id, text}: the model's reasoning as it thinks, when the agent shows it — thinking: visible), `tool` ({response_id, run_id, call_id, name, status: running|awaiting_output|awaiting_approval|approved|denied|expired|completed|failed|canceled, text_offset, input, output, image_count, is_error, approval_id, agent_response_id, …}), `agent` ({run_id, response_id, parent_response_id, name, required, status, text_offset}: a subagent at work), `goal` ({goal_id, kind: set|updated|turn_started|judged|verified|status_changed|cleared, goal: {objective, rubric, status, stop_code, stop_reason, phase, max_turns, max_cost_usd}, role, seq, response_id, run_id, verdict, reason, missing, from, to, code}: the chat's goal's words), `voice` ({voice_id, user_id, delegation, status: started|closed, seconds, close_reason}: the chat's live voice began or ended), `transcript` ({id, voice_id, role: user|assistant, user_id, author_name, text, final, created_at}: a line it said either way — the chat's history's message of kind voice, by its id), `seen` (the journal moved past what was handed already), and — first, in a fork's channel — `history` ({forked_from: {chat_id, before_message}, part, parts, items: [{role: user|assistant, message_id, client_id, author, author_name, text, metadata, created_at, response_id, text_truncated, attachments}]}: what the fork began with, a few items a part, a long text cut in its part, its id h and the part's place). Every type but text and reset has the journal's sequence as its id; text_offset says where in the answer a tool or subagent part happened. The project's backend is not in the stream: the gateway's members hear the chat from realtime, and one that was away is given what it missed there. Put again with the same channel it goes on where it is — one realtime refused is tried again; with another, from the chat's start, and nothing more is written into the one before. The project's server's alone.
|
|
3006
|
+
* Writes the chat's stream into a channel of the project's realtime from now on — a gateway's, durable — as the platform: the members' messages, the turns, the answer as it is written (gathered into a few writes a second), the tools and subagents, each the channel's event `chat` {type, id?, data}, under an id of its own so a retry is kept once. The types: `message` (a ChatMessage, as the agent got it), `turn` ({response_id, status: running|waiting|completed|failed|canceled|timed_out|budget_exceeded, user_id, solo, goal: {goal_id, role: work|verify, seq} — a turn of the chat's goal, waiting: {reason: approval|tool_output|subagents|message, text_offset, approval_id, tool_call_id, tool_name, input, publication}, end: completed|failed|stopped|budget_exceeded — as the turn's event says it, error: {code, message, retryable}}), `text` ({response_id, offset, text}: the agent's answer as it is written, at its byte offset), `reset` ({response_id, offset}: discard the answer past offset), `thinking` ({response_id, run_id, step_id, text}: the model's reasoning as it thinks, when the agent shows it — thinking: visible), `tool` ({response_id, run_id, call_id, name, status: running|awaiting_output|awaiting_approval|approved|denied|expired|completed|failed|canceled, text_offset, input, output, image_count, is_error, approval_id, agent_response_id, …}), `agent` ({run_id, response_id, parent_response_id, name, required, status, text_offset}: a subagent at work), `advisor` ({response_id, run_id, seq, kind: step|final|ask, verdict: none|heads_up|answer|unreadable, rule, message, question, told}: the agent's advisor read its work — after a step, at its answer, which waits for it, or because the agent asked; told: the agent was told at its next step), `goal` ({goal_id, kind: set|updated|turn_started|judged|verified|status_changed|cleared, goal: {objective, rubric, status, stop_code, stop_reason, phase, max_turns, max_cost_usd}, role, seq, response_id, run_id, verdict, reason, missing, from, to, code}: the chat's goal's words), `voice` ({voice_id, user_id, delegation, status: started|closed, seconds, close_reason}: the chat's live voice began or ended), `transcript` ({id, voice_id, role: user|assistant, user_id, author_name, text, final, created_at}: a line it said either way — the chat's history's message of kind voice, by its id), `seen` (the journal moved past what was handed already), and — first, in a fork's channel — `history` ({forked_from: {chat_id, before_message}, part, parts, items: [{role: user|assistant, message_id, client_id, author, author_name, text, metadata, created_at, response_id, text_truncated, attachments}]}: what the fork began with, a few items a part, a long text cut in its part, its id h and the part's place). Every type but text and reset has the journal's sequence as its id; text_offset says where in the answer a tool or subagent part happened. The project's backend is not in the stream: the gateway's members hear the chat from realtime, and one that was away is given what it missed there. Put again with the same channel it goes on where it is — one realtime refused is tried again; with another, from the chat's start, and nothing more is written into the one before. The project's server's alone.
|
|
2963
3007
|
*/
|
|
2964
3008
|
putChatPipe(input: {
|
|
2965
3009
|
path: {
|
|
@@ -18,6 +18,9 @@ type Globals = {
|
|
|
18
18
|
serviceWorker?: ServiceWorkerContainer;
|
|
19
19
|
language?: string;
|
|
20
20
|
};
|
|
21
|
+
location?: {
|
|
22
|
+
href: string;
|
|
23
|
+
};
|
|
21
24
|
Notification?: {
|
|
22
25
|
permission: NotificationPermission;
|
|
23
26
|
requestPermission(): Promise<NotificationPermission>;
|
|
@@ -33,7 +36,16 @@ export declare class WebPush {
|
|
|
33
36
|
private publishableKey;
|
|
34
37
|
private g;
|
|
35
38
|
private registered;
|
|
36
|
-
/**
|
|
39
|
+
/** Which change of who is signed in, or word of the app's, the registration is for: an older one's tries stop. */
|
|
40
|
+
private generation;
|
|
41
|
+
/** Ends a registration's wait between tries at once: a newer change, or the app's own subscribe or unsubscribe. */
|
|
42
|
+
private wake;
|
|
43
|
+
/**
|
|
44
|
+
* Palbase's subscription ended for a person who changed, its replacement not registered yet: what the next
|
|
45
|
+
* registration makes (with the ended one's key), whichever change it is for.
|
|
46
|
+
*/
|
|
47
|
+
private replacing;
|
|
48
|
+
/** The registration again for a change of who is signed in, while it runs (its retries too). */
|
|
37
49
|
changing: Promise<unknown>;
|
|
38
50
|
constructor(transport: Transport, session: SessionManager, installation: Installation, baseUrl: string, publishableKey: string, g?: Globals);
|
|
39
51
|
/** Whether this browser takes pushes at all (a service worker, the Push API, notifications). */
|
|
@@ -47,11 +59,41 @@ export declare class WebPush {
|
|
|
47
59
|
* takes pushes now, false when the person refused or the browser has none.
|
|
48
60
|
*/
|
|
49
61
|
subscribe(opts?: PushSubscribeOptions): Promise<boolean>;
|
|
50
|
-
/**
|
|
62
|
+
/**
|
|
63
|
+
* Stops this browser's pushes: its subscription ends, and the project forgets the device as it next pushes it. A
|
|
64
|
+
* registration still trying for a change of who is signed in stops first: none makes a subscription again after.
|
|
65
|
+
*/
|
|
51
66
|
unsubscribe(): Promise<void>;
|
|
67
|
+
/** The app's own subscribe or unsubscribe: newer than any change's registration, which ends its tries. */
|
|
68
|
+
private supersede;
|
|
52
69
|
/** Registers the browser's subscription again (as the app starts, or as people sign in and out): nothing when it has none. */
|
|
53
70
|
refresh(): Promise<void>;
|
|
71
|
+
/**
|
|
72
|
+
* The subscription registered again for whoever is signed in now. One the project cannot be told of (unreachable as
|
|
73
|
+
* someone signs in or out) ends at once: kept, it would stay the last person's device — their pushes shown to whoever
|
|
74
|
+
* is here now, as on a shared computer signed out of offline. A new one takes its place (no prompt: the person
|
|
75
|
+
* allowed it), which no push for the last person reaches, registered once the project can be reached and tried
|
|
76
|
+
* again meanwhile: a dropped connection ends no pushes the person allowed. Only Palbase's ends — never another
|
|
77
|
+
* worker's.
|
|
78
|
+
*/
|
|
79
|
+
private registerFor;
|
|
80
|
+
/** A wait between tries, which a newer change or the app's own word ends at once. */
|
|
81
|
+
private pause;
|
|
82
|
+
/**
|
|
83
|
+
* The registration of Palbase's worker for this project — the project its URL's key names, whatever key of the
|
|
84
|
+
* project it was registered with (one since rotated too). A page's other workers — the app's own, another push
|
|
85
|
+
* service's (FCM, OneSignal), another project's — and their subscriptions are not Palbase's to register or end.
|
|
86
|
+
*/
|
|
87
|
+
private ours;
|
|
88
|
+
private isOurs;
|
|
89
|
+
/** Palbase's subscription in this browser: the one on its worker's registration. */
|
|
54
90
|
private current;
|
|
91
|
+
/**
|
|
92
|
+
* Where Palbase's worker is registered: the scope asked for, else its folder — unless another worker holds it. A
|
|
93
|
+
* scope holds one worker, so registering there would replace the app's (its offline cache, another service's pushes):
|
|
94
|
+
* Palbase's takes a scope of its own beside it instead; a push reaches its worker whatever pages that controls.
|
|
95
|
+
*/
|
|
96
|
+
private scopeFor;
|
|
55
97
|
private register;
|
|
56
98
|
}
|
|
57
99
|
/** pb.notify: the project's notifications, as this app takes them. */
|
package/dist/chunks/DEMLN2MO.js
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
/*! palbase 0.21.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{a as M,c as he,d as ye,e as be}from"./UTZFJM2O.js";import{a as we}from"./RTL4OAKC.js";import{a as pe}from"./LHLXKWXT.js";import{a as ge,b as fe,c as me}from"./BQTZYHJN.js";import{b as $,d as ue}from"./XZY2DTL7.js";async function*ke(e,t={}){let o=e.getReader(),a=new TextDecoder,i="",l="",u=[],h,r=()=>{o.cancel().catch(()=>{})};t.signal?.addEventListener("abort",r,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:s}=await o.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=a.decode(s,{stream:!0});for(let d=i.indexOf(`
|
|
3
|
-
`);d>=0;d=i.indexOf(`
|
|
4
|
-
`)){let p=i.slice(0,i[d-1]==="\r"?d-1:d);i=i.slice(d+1),p===""?(l!==""&&(yield h===void 0?{event:l,data:u.join(`
|
|
5
|
-
`)}:{event:l,data:u.join(`
|
|
6
|
-
`),id:h}),l="",u=[],h=void 0):p.startsWith("event:")?l=ee(p,6):p.startsWith("data:")?u.push(ee(p,5)):p.startsWith("id:")&&(h=ee(p,3))}}}finally{t.signal?.removeEventListener("abort",r);try{await o.cancel()}catch{}}}function ee(e,t){let o=e.slice(t);return o.startsWith(" ")?o.slice(1):o}var ct=/\s/;function W(e,t){for(;t<e.length&&ct.test(e[t]);)t++;return t}function Te(e,t){let o="";for(let a=t+1;a<e.length;a++){let i=e[a];if(i==='"')return{value:o,complete:!0,empty:!1,at:a+1};if(i!=="\\"){o+=i;continue}let l=e[a+1];if(l===void 0)break;if(l==="u"){let u=e.slice(a+2,a+6);if(u.length<4)break;o+=String.fromCharCode(Number.parseInt(u,16)),a+=5;continue}o+={n:`
|
|
7
|
-
`,t:" ",r:"\r",b:"\b",f:"\f"}[l]??l,a++}return{value:o,complete:!1,empty:!1,at:e.length}}function te(e,t){t=W(e,t);let o=e[t];if(o===void 0)return{value:void 0,complete:!1,empty:!0,at:t};if(o==='"')return Te(e,t);if(o==="{")return lt(e,t);if(o==="[")return ut(e,t);let a=t;for(;a<e.length&&/[-+0-9.A-Za-z]/.test(e[a]);)a++;if(a===e.length)return{value:void 0,complete:!1,empty:!0,at:a};try{return{value:JSON.parse(e.slice(t,a)),complete:!0,empty:!1,at:a}}catch{return{value:void 0,complete:!1,empty:!0,at:e.length}}}function lt(e,t){let o={},a=t+1;for(;;){if(a=W(e,a),e[a]==="}")return{value:o,complete:!0,empty:!1,at:a+1};if(e[a]===","){a++;continue}if(e[a]!=='"')return{value:o,complete:!1,empty:!1,at:e.length};let i=Te(e,a);if(!i.complete)return{value:o,complete:!1,empty:!1,at:e.length};if(a=W(e,i.at),e[a]!==":")return{value:o,complete:!1,empty:!1,at:e.length};let l=te(e,a+1);if(l.empty||Object.defineProperty(o,i.value,{value:l.value,enumerable:!0,writable:!0,configurable:!0}),!l.complete)return{value:o,complete:!1,empty:!1,at:e.length};a=l.at}}function ut(e,t){let o=[],a=t+1;for(;;){if(a=W(e,a),e[a]==="]")return{value:o,complete:!0,empty:!1,at:a+1};if(e[a]===","){a++;continue}if(a>=e.length)return{value:o,complete:!1,empty:!1,at:a};let i=te(e,a);if(i.empty||o.push(i.value),!i.complete)return{value:o,complete:!1,empty:!1,at:e.length};a=i.at}}function ne(e){let t=te(e,0);return t.empty?void 0:t.value}var b=class extends Error{path;constructor(t,o){super(`${t}: ${o}`),this.name="AISchemaError",this.path=t}},pt=new Set(["type","properties","required","additionalProperties","items","enum","description","title","minimum","maximum","minLength","maxLength","minItems","maxItems"]),gt=new Set(["format","pattern","exclusiveMinimum","exclusiveMaximum","multipleOf","uniqueItems","contentEncoding","contentMediaType","default","examples","readOnly","writeOnly","deprecated","$comment"]),ft=new Set(["object","array","string","integer","number","boolean"]),Se=12,xe=512,mt=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/;function j(e,t="answer"){if(!mt.test(t))throw new b(t||"(name)","a schema name starts with a letter and holds letters, digits, _ and -, 64 at most");let o=e?.["~standard"];if(!o||o.version!==1||typeof o.validate!="function")throw new b(t,"not a Standard Schema: pass a zod (4.2+), valibot or arktype schema");if(!o.jsonSchema||typeof o.jsonSchema.output!="function")throw new b(t,`${o.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let a;try{a=o.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(u){throw new b(t,`the schema has a part JSON Schema cannot say (${u.message}): a function, a transform, a date \u2014 give the model a string and convert it after`)}if(a.type!=="object")throw new b(t,"the answer is an object: wrap the value in z.object({ \u2026 })");let l=re(a,t,0,{properties:0});return{name:t,json:l,async check(u){let h=await o.validate(u);if(h.issues){let r=h.issues[0],n=(r?.path??[]).map(s=>String(typeof s=="object"?s.key:s)).join(".");throw new b(n?`${t}.${n}`:t,`the model's answer does not match the schema: ${r?.message??"invalid"}`)}return h.value}}}function re(e,t,o,a){if(o>Se)throw new b(t,`nests deeper than ${Se} levels, the most the provider takes`);for(let u of["anyOf","oneOf","allOf"])if(u in e)throw new b(t,ht(e[u])??"is a union of several shapes: the provider holds a model to one shape per field \u2014 use an enum, or one object with every field");for(let u of["$ref","$defs","definitions","$dynamicRef"])if(u in e)throw new b(t,"refers to another schema (a recursive or shared type): the provider takes no references \u2014 write the shape out, a bounded number of levels deep");if(e.type==="object"&&("propertyNames"in e||"patternProperties"in e||e.additionalProperties!==void 0&&e.additionalProperties!==!1))throw new b(t,"accepts fields it does not name (a record, passthrough or catchall): the provider holds a model only to the fields named \u2014 name them");for(let u of["prefixItems","patternProperties","propertyNames","not","if","then","else","dependentRequired","dependentSchemas","const","minProperties","maxProperties","contains","unevaluatedProperties","unevaluatedItems"])if(u in e)throw new b(t,`uses ${u}, which the provider cannot hold a model to`);if(Array.isArray(e.type))throw new b(t,`may be ${e.type.join(" or ")}: one type per field \u2014 a nullable field is not expressible; give it a value that means "none" (an empty string, an enum member)`);let i=e.type;if(typeof i!="string"&&!("enum"in e))throw new b(t,"has no type: the provider holds a model only to a typed value");if(typeof i=="string"&&!ft.has(i))throw new b(t,`is of type ${i}, which the provider does not take`);let l={};for(let[u,h]of Object.entries(e))if(!(u==="$schema"||u==="id"||u==="$id")&&!gt.has(u)){if(!pt.has(u))throw new b(t,`uses ${u}, which the provider cannot hold a model to`);l[u]=h}if("enum"in e&&typeof i!="string"){let u=e.enum,h=new Set(u.map(r=>r===null?"null":typeof r));if(h.size!==1||h.has("null"))throw new b(t,"an enum of values of several types (or with null): one type per field");l.type=h.has("string")?"string":h.has("boolean")?"boolean":"number"}if(i==="object"){let u=e.properties??{},h=Object.keys(u);if(h.length===0)throw new b(t,"is an object with no fields (a record, or any object): the provider holds a model only to named fields \u2014 name them");if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new b(t,"accepts fields it does not name (passthrough, catchall, record): the provider holds a model only to the fields named");if(a.properties+=h.length,a.properties>xe)throw new b(t,`the schema has more than ${xe} fields in all, the most the provider takes`);let r=new Set(e.required??[]),n={};for(let s of h){if(!r.has(s))throw new b(`${t}.${s}`,'is optional: the provider makes the model write every field \u2014 make it required (give it a value that means "none"), or leave it out of the schema');n[s]=re(u[s],`${t}.${s}`,o+1,a)}l.properties=n,l.required=h,l.additionalProperties=!1}if(i==="array"){let u=e.items;if(!u||typeof u!="object"||Array.isArray(u))throw new b(t,"is a list with no one shape for its items: the provider takes a list of one shape");l.items=re(u,`${t}[]`,o+1,a)}return l}function ht(e){if(Array.isArray(e)&&e.length===2&&e.some(t=>t?.type==="null"))return'is nullable: the provider makes the model write a value of one type \u2014 drop .nullable() and give it a value that means "none"'}var yt=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function F(e){return Array.isArray(e)&&e.length>0&&e.every(Ae)?e.map(ve):Ae(e)?[ve(e)]:e==null?[{type:"text",text:""}]:typeof e=="string"?[{type:"text",text:e}]:[{type:"text",text:JSON.stringify(e)??String(e)}]}function Ae(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.type==="text"?typeof t.text=="string":t.type==="image"?(typeof t.mediaType=="string"||typeof t.media_type=="string")&&(typeof t.data=="string"||t.data instanceof Uint8Array):t.type===void 0&&typeof t.mediaType=="string"&&t.bytes instanceof Uint8Array}function ve(e){if("type"in e&&e.type==="text")return{type:"text",text:e.text};let t="bytes"in e||"mediaType"in e?e.mediaType:e.media_type;if(!yt.has(t))throw new TypeError(`a tool's picture is image/png, image/jpeg, image/webp or image/gif (got ${JSON.stringify(t)})`);let o="bytes"in e?e.bytes:e.data;return{type:"image",media_type:t,data:typeof o=="string"?o:bt(o)}}function bt(e){let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)}var Oe=Symbol.for("palbase.ai.deferred"),_e=60,Re=86400;function Me(e={}){let t=e?.expiresInSeconds;if(t!==void 0&&(!Number.isInteger(t)||t<_e||t>Re))throw new TypeError(`ai.deferred: expiresInSeconds is how long the call waits for its answer, ${_e} to ${Re} seconds (got ${String(t)})`);return Object.freeze({[Oe]:!0,...t!==void 0?{expiresInSeconds:t}:{}})}function wt(e){return typeof e=="object"&&e!==null&&e[Oe]===!0}var kt=Symbol.for("palbase.ai.declared"),Tt=Symbol.for("palbase.ai.tool_error"),se=class extends Error{constructor(t){super(t),this.name="ToolError",Object.defineProperty(this,Tt,{value:!0})}};function B(){let e=globalThis,t=e[kt]??={tools:new Map,clientTools:new Map,agents:new Map,repos:new Map,twice:new Set};return t.repos??=new Map,t.clientTools??=new Map,t}function X(e,t,o,a,i=(l,u)=>l===u){let l=e.get(o);l===void 0?e.set(o,a):i(l,a)||B().twice.add(`${t}:${o}`)}var je=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,v=/^[a-z][a-z0-9_-]{0,63}$/;function Be(e,t){if(e===void 0)return{type:"object",properties:{}};let o=e?.["~standard"];if(!o||o.version!==1||typeof o.validate!="function")throw new TypeError(`${t}: input is a Standard Schema \u2014 a zod (4.2+), valibot or arktype object schema`);if(!o.jsonSchema||typeof o.jsonSchema.output!="function")throw new TypeError(`${t}: ${o.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let a;try{a=o.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(h){throw new TypeError(`${t}: the input has a part JSON Schema cannot say (${h.message}) \u2014 a function, a transform, a date: take a string and convert it in run`)}if(a.type!=="object")throw new TypeError(`${t}: a tool takes an object \u2014 wrap the input in z.object({ \u2026 })`);let i=JSON.stringify(a);if(/"\$(ref|defs|dynamicRef)"/.test(i))throw new TypeError(`${t}: the input refers to another schema (a recursive or shared type) \u2014 write the shape out`);let{$schema:l,...u}=a;return u}function De(e){let t=`ai.tool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!je.test(e.name))throw new TypeError(`${t}: name is letters, digits, _ and -, starting with a letter, at most 64`);if(typeof e.description!="string"||e.description.trim()==="")throw new TypeError(`${t}: description says what it does \u2014 the agent reads it to choose`);if(typeof e.run!="function")throw new TypeError(`${t}: run(input, ctx) is what a call does`);if(e.machine!==void 0&&!v.test(e.machine))throw new TypeError(`${t}: machine is the name of one of the project's machines`);if(e.input===void 0)throw new TypeError(`${t}: input is what it takes \u2014 z.object({}) for nothing`);let o=Be(e.input,t),a=e.input["~standard"],i=e.run,l={source:"backend",name:e.name,description:e.description,input:e.input,parameters:o,approval:e.approval===!0,...e.machine!==void 0?{machine:e.machine}:{},async call(h,r){let n=await a.validate(h);if(n.issues){let d=n.issues[0],p=(d?.path??[]).map(_=>String(typeof _=="object"?_.key:_)).join(".");return{output:[{type:"text",text:`the input does not match ${e.name}'s schema${p?` at ${p}`:""}: ${d?.message??"invalid"}`}],is_error:!0}}let s=await i(n.value,r);return wt(s)?r.chatId===""?{output:[{type:"text",text:`${e.name} answers later, and a one-shot answer waits for no call: it answers at once, or in a chat`}],is_error:!0}:{deferred:!0,...s.expiresInSeconds!==void 0?{expires_in_seconds:s.expiresInSeconds}:{}}:{output:F(s),is_error:!1}}};Object.freeze(l);let u=B();return u.clientTools.has(l.name)&&u.twice.add(`tool:${l.name}`),X(u.tools,"tool",l.name,l),l}function Ne(e){let t=`ai.clientTool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!je.test(e.name))throw new TypeError(`${t}: name is letters, digits, _ and -, starting with a letter, at most 64`);if(typeof e.description!="string"||e.description.trim()==="")throw new TypeError(`${t}: description says what it does \u2014 the agent reads it to choose`);let o=Object.freeze({source:"client",name:e.name,description:e.description,parameters:Be(e.input,t),approval:e.approval===!0}),a=B();return a.tools.has(o.name)&&a.twice.add(`tool:${o.name}`),X(a.clientTools,"tool",o.name,o,(i,l)=>JSON.stringify(i)===JSON.stringify(l)),o}var St=/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;function Ue(e){let t=e??{};if(typeof t.name!="string"||!v.test(t.name))throw new TypeError("ai.repo: name is lowercase letters, digits, _ and -, starting with a letter, at most 64");if(typeof t.repository!="string"||!St.test(t.repository))throw new TypeError(`ai.repo(${JSON.stringify(t.name)}): repository is a GitHub repository, owner/name`);if(typeof t.token!="function")throw new TypeError(`ai.repo(${JSON.stringify(t.name)}): token is the function that gives a token for one clone or push`);if(t.machine!==void 0&&!v.test(t.machine))throw new TypeError(`ai.repo(${JSON.stringify(t.name)}): machine is the project's machine that gives its tokens`);let o=t.token,a={kind:"repo",name:t.name,repository:t.repository,defaultBranch:t.defaultBranch??"main",...t.machine!==void 0?{machine:t.machine}:{},async token(i){return await o(i)}};return X(B().repos,"repo",t.name,a),a}function Ge(e){if(typeof e!="function")throw new TypeError("ai.repoTokens(give): give is the function that gives a token for one clone or push of a repository put by name");let t=B();t.repoTokens===void 0?t.repoTokens=e:t.repoTokens!==e&&t.twice.add("repoTokens")}function Le(e,t,o={}){let a=`ai.agent(${JSON.stringify(e??null)})`;if(typeof e!="string"||!v.test(e))throw new TypeError(`${a}: name is lowercase letters, digits, _ and -, starting with a letter, at most 64`);if(typeof t!="function")throw new TypeError(`${a}: the agent is a function of the turn's context that returns its definition`);let i=o??{};if(i.machine!==void 0&&!v.test(i.machine))throw new TypeError(`${a}: machine is the name of one of the project's machines`);let l=i.description===void 0?void 0:Je(i.description,a),u={kind:"agent",name:e,...l!==void 0?{description:l}:{},...i.machine!==void 0?{machine:i.machine}:{},async resolve(h){let r=await t(h),n=Z(r,`${a} for chat ${h.chatId}`);if(n.backend!==void 0)throw new TypeError(`${a}: a backend's agent is its definition \u2014 it names no other backend`);return n.description===void 0&&l!==void 0&&(n.description=l),{definition:n,tools:xt(r)}}};return Object.freeze(u),X(B().agents,"agent",e,u),u}function V(e){return typeof e=="object"&&e!==null&&e.kind==="agent"?e:void 0}function xt(e){return[...e.tools??[],...(e.subagents??[]).flatMap(o=>o.tools??[])].filter(o=>o.source==="backend")}var Ce=["web.search","web.fetch","workspace.fetch_archive"];function K(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a tool is ai.tool(\u2026), ai.clientTool(\u2026), { source: 'https', name }, { source: 'mcp', name } or { source: 'platform', name }`);let o=e.approval===!0?{approval:!0}:{};switch(e.source){case"backend":if(typeof e.call!="function")throw new TypeError(`${t}: a backend tool is made with ai.tool({ name, description, input, run })`);return{source:"backend",name:e.name,description:e.description,parameters:e.parameters,...o,...e.machine!==void 0?{machine:e.machine}:{}};case"client":return{source:"client",name:e.name,description:e.description,parameters:e.parameters,...o};case"https":if(typeof e.name!="string"||!v.test(e.name))throw new TypeError(`${t}: { source: 'https', name } names an endpoint the project put`);return{source:"https",name:e.name,...o};case"mcp":if(typeof e.name!="string"||!v.test(e.name))throw new TypeError(`${t}: { source: 'mcp', name } names an MCP server the project put`);return{source:"mcp",name:e.name,...o,...e.only!==void 0?{only:[...e.only]}:{}};case"platform":{let a=Object.keys(e).filter(i=>i!=="source"&&i!=="name");if(typeof e.name!="string"||!Ce.includes(e.name))throw new TypeError(`${t}: { source: 'platform', name } names one of the platform's tools: ${Ce.join(", ")}`);if(a.length>0)throw new TypeError(`${t}: the platform's ${e.name} is given by its name alone (not ${a.join(", ")})`);return{source:"platform",name:e.name}}default:throw new TypeError(`${t}: a tool's source is backend, client, https, mcp or platform (got ${JSON.stringify(e.source)})`)}}var Ee=1e4,Pe=["none","minimal","low","medium","high","xhigh","max"],At=1e8,vt=/^[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8})*$/,Ie=1024;function Je(e,t){if(typeof e!="string"||e.trim()===""||e.length>Ie)throw new TypeError(`${t}: description says what the agent is for, in a sentence or two (${Ie} characters at most)`);return e}function _t(e,t){let o=e?.prepared;if(o!==void 0&&typeof o=="object"&&o!==null&&typeof o.json=="object")return o.json;if(typeof e!="object"||e===null||!("~standard"in e))throw new TypeError(`${t}: output is the shape of its one-shot answers \u2014 a zod (valibot, arktype) object schema, or ai.schema(name, schema)`);return j(e,"output").json}function ae(e,t){if(!Number.isInteger(e)||e<1||e>Ee)throw new TypeError(`${t}: maxToolCalls is a whole number, 1 to ${Ee} (got ${String(e)})`);return e}function $e(e,t){let o={};if(e.effort!==void 0){if(typeof e.effort!="string"||!Pe.includes(e.effort))throw new TypeError(`${t}: effort is one of ${Pe.join(", ")} \u2014 which a model takes is its catalogue entry's (ai.models())`);o.effort=e.effort}if(e.contextWindow!==void 0){if(!Number.isInteger(e.contextWindow)||e.contextWindow<1||e.contextWindow>At)throw new TypeError(`${t}: contextWindow is a number of tokens (got ${String(e.contextWindow)})`);o.context_window=e.contextWindow}if(e.thinking!==void 0){if(e.thinking!=="visible"&&e.thinking!=="hidden")throw new TypeError(`${t}: thinking is visible (the model's reasoning in the chat's stream) or hidden`);o.thinking=e.thinking}return o}function Z(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a definition is { description, instructions, model, tools, subagents, maxToolCalls, effort, contextWindow, thinking, language, output }`);let o={};if(e.description!==void 0&&(o.description=Je(e.description,t)),e.instructions!==void 0&&(o.instructions=e.instructions),e.model!==void 0&&(o.model=e.model),e.maxToolCalls!==void 0&&(o.max_tool_calls=ae(e.maxToolCalls,t)),Object.assign(o,$e(e,t)),e.language!==void 0){if(typeof e.language!="string"||e.language.length>35||!vt.test(e.language))throw new TypeError(`${t}: language is the language of the person the turn works for, as a BCP 47 tag (tr, en-GB)`);o.language=e.language}if(e.output!==void 0&&(o.output=_t(e.output,t)),e.tools!==void 0&&(o.tools=e.tools.map(a=>K(a,t))),e.subagents!==void 0){for(let a of e.subagents){let i=(a?.tools??[]).find(l=>l?.source==="platform");if(i)throw new TypeError(`${t} subagent ${a.name}: the platform's ${i.name} is the agent's tool \u2014 its subagents work with the agent's`)}o.subagents=e.subagents.map(a=>({name:a.name,description:a.description,...a.instructions!==void 0?{instructions:a.instructions}:{},...a.model!==void 0?{model:a.model}:{},...a.required!==void 0?{required:a.required}:{},...$e(a,`${t} subagent ${a.name}`),...a.tools!==void 0?{tools:a.tools.map(i=>K(i,`${t} subagent ${a.name}`))}:{}}))}return o}function D(e,t){if(typeof e!="string"||!v.test(e))throw new TypeError(`${t}: an agent's name is lowercase letters, digits, _ and -, starting with a letter, at most 64 (got ${JSON.stringify(e)})`);return e}function ze(e,t){if(!Number.isSafeInteger(e)||e<1)throw new TypeError(`${t}: revision is the draft's revision as it was read (Agent's revision), a whole number from 1 (got ${String(e)})`);return e}function Ve(e,t){let o={approve:e};return t.reason!==void 0&&(o.reason=t.reason),t.as!==void 0&&(o.as=t.as),o}var Rt=/^[a-z][a-z0-9-]{1,62}$/,qe=4,We=8;function Ct(e){let t={},o=(a,i)=>{if(typeof a?.bucket!="string"||!Rt.test(a.bucket))throw new TypeError(`chats.send: ${i}'s bucket is one of the project's buckets, by its name`);if(typeof a.path!="string"||a.path===""||a.path.length>1024)throw new TypeError(`chats.send: ${i}'s path is its path in the bucket (1024 characters at most)`);return{bucket:a.bucket,path:a.path}};if(e.images!==void 0){if(!Array.isArray(e.images)||e.images.length>qe)throw new TypeError(`chats.send: images are ${qe} at most \u2014 as many as the model is shown at once`);t.images=e.images.map((a,i)=>o(a,`images[${i}]`))}if(e.files!==void 0){if(!Array.isArray(e.files)||e.files.length>We)throw new TypeError(`chats.send: files are ${We} at most`);t.files=e.files.map((a,i)=>{let l=o(a,`files[${i}]`);if(a.filename!==void 0){if(typeof a.filename!="string"||a.filename===""||a.filename.length>255)throw new TypeError(`chats.send: files[${i}].filename is its name in the workspace (255 characters at most)`);l.filename=a.filename}if(a.contentType!==void 0){if(typeof a.contentType!="string"||a.contentType===""||a.contentType.length>128)throw new TypeError(`chats.send: files[${i}].contentType is a media type (application/pdf)`);l.content_type=a.contentType}return l})}return t}function H(e){return{id:e.id,chatId:e.chat_id,userId:e.user_id,delegation:e.delegation,status:e.status,seconds:e.seconds,startedAt:e.started_at,closedAt:e.closed_at,closeReason:e.close_reason??""}}var Et=["speak","tell","know","instruct"];function Fe(){return"cm_"+crypto.randomUUID()}async function Y(e,t,o=4){for(let a=1;;a++)try{return await e()}catch(i){if(a>=o||!(i instanceof $)||i.status===429||t?.aborted)throw i;let l=me(i,a,30);if(l===void 0)throw i;await new Promise((u,h)=>{let r=setTimeout(u,l*1e3);t?.addEventListener("abort",()=>(clearTimeout(r),h(t.reason)),{once:!0})})}}function oe(e){return{id:e.id,chatId:e.chat_id,objective:e.objective,rubric:e.rubric,status:e.status,stopCode:e.stop_code,stopReason:e.stop_reason,phase:e.phase,setBy:e.set_by,maxTurns:e.max_turns,budget:e.budget===null?null:{maxCostUsd:e.budget.max_cost_usd},usage:{turns:e.usage.turns,verifications:e.usage.verifications,costUsd:e.usage.cost_usd,costIsLowerBound:e.usage.cost_is_lower_bound,activeSeconds:e.usage.active_seconds},achievedAt:e.achieved_at,createdAt:e.created_at,updatedAt:e.updated_at}}var Ke=e=>({user_id:e.userId,...e.name!==void 0?{name:e.name}:{},...e.email!==void 0?{email:e.email}:{},...e.owner!==void 0?{owner:e.owner}:{}}),Pt=/^[A-Za-z0-9-]{1,64}$/,Xe=16;function It(e){if(!Array.isArray(e)||e.length>Xe)throw new TypeError(`chats.create: workspace.trailers are ${Xe} at most, each { key, value }`);return e.map((t,o)=>{if(typeof t?.key!="string"||!Pt.test(t.key))throw new TypeError(`chats.create: workspace.trailers[${o}].key is a git trailer's token: letters, digits and -, at most 64 (PalCore-Task, Co-authored-by)`);if(typeof t.value!="string"||t.value===""||/[\r\n]/.test(t.value)||new TextEncoder().encode(t.value).byteLength>512)throw new TypeError(`chats.create: workspace.trailers[${o}].value is one line of 512 bytes at most`);return{key:t.key,value:t.value}})}function $t(e){return{runId:e.run_id,responseId:e.response_id,parentRunId:e.parent_run_id??null,subagent:e.subagent,model:e.model,state:e.state,inputTokens:e.input_tokens,outputTokens:e.output_tokens,cacheReadTokens:e.cache_read_tokens,cacheWriteTokens:e.cache_write_tokens,costNanoUsd:e.cost_nano_usd,usd:e.usd,unpriced:e.unpriced}}function Ze(e){return{clients:e.clients,userMessagesPerMinute:e.user_messages_per_minute,historyLimitBytes:e.history_limit_bytes,historyBytes:e.history_bytes,monthlyBudgetUsd:e.monthly_budget_usd??null}}function Ot(e){return new Proxy(e,{get(t,o){let a=t[o];return typeof a=="function"?(...i)=>M(a.apply(t,i)):a}})}function He(e){let t=Ot(e),o={async create(r){let n=typeof r.agent=="string"||r.agent===void 0?r.agent:V(r.agent)?.name;if(r.agent!==void 0&&n===void 0)throw new TypeError("chats.create: agent is one of the project's agents by name (name@N for a version), or a backend's ai.agent");if(n===void 0&&r.definition===void 0)throw new TypeError("chats.create: an agent (one of the project's, by name) or a definition of the chat's own");let s={agent:n??"assistant"};return r.definition!==void 0&&(s.definition=Z(r.definition,"chats.create")),r.title!==void 0&&(s.title=r.title),r.metadata!==void 0&&(s.metadata=r.metadata),r.members!==void 0&&(s.members=r.members.map(Ke)),r.workspace!==void 0&&(s.workspace={repos:r.workspace.repos.map(d=>({repo:typeof d.repo=="string"?d.repo:d.repo.name,...d.branch!==void 0?{branch:d.branch}:{}})),...r.workspace.autoPush!==void 0?{auto_push:r.workspace.autoPush}:{},...r.workspace.trailers!==void 0?{trailers:It(r.workspace.trailers)}:{}}),(await t.createChat({body:s,signal:r.signal})).data},async get(r,n={}){return(await t.getChat({path:{chat_id:r},signal:n.signal})).data},async list(r={}){let n=r.metadata===void 0?void 0:Object.entries(r.metadata).map(([d,p])=>`${d}:${p}`),s=(await t.listChats({query:{member:r.member,limit:r.limit,cursor:r.cursor,metadata:n},signal:r.signal})).data;return s.next_cursor===void 0?{chats:s.chats}:{chats:s.chats,nextCursor:s.next_cursor}},async delete(r){await t.deleteChat({path:{chat_id:r}})},members:{async put(r,n,s){let d={};return s.name!==void 0&&(d.name=s.name),s.email!==void 0&&(d.email=s.email),s.owner!==void 0&&(d.owner=s.owner),(await t.putChatMember({path:{chat_id:r,user_id:n},body:d})).data},async delete(r,n){await t.deleteChatMember({path:{chat_id:r,user_id:n}})}},async send(r,n){let s={client_id:n.clientId??Fe(),text:n.text};return n.delivery!==void 0&&(s.delivery=n.delivery),n.as!==void 0&&(s.as=n.as),n.budget!==void 0&&(s.budget={max_cost_usd:n.budget.maxCostUsd}),n.metadata!==void 0&&(s.metadata=n.metadata),n.context!==void 0&&(s.context=n.context),Object.assign(s,Ct(n)),Y(async()=>(await t.sendChatMessage({path:{chat_id:r},body:s,signal:n.signal})).data,n.signal)},async turnCost(r,n,s={}){let d=(await t.getChatTurnCost({path:{chat_id:r,response_id:n},signal:s.signal})).data;return{chatId:d.chat_id,responseId:d.response_id,inputTokens:d.input_tokens,outputTokens:d.output_tokens,costNanoUsd:d.cost_nano_usd,usd:d.usd,unpriced:d.unpriced,final:d.final,runs:d.runs.map($t)}},async artifacts(r,n,s={}){return(await t.listChatTurnArtifacts({path:{chat_id:r,response_id:n},signal:s.signal})).data.artifacts.map(p=>({id:p.id,mediaType:p.media_type,...p.logical_type?{logicalType:p.logical_type}:{},sizeBytes:p.size_bytes,checksum:p.checksum,createdAt:p.created_at}))},async artifact(r,n,s,d={}){return(await t.getChatTurnArtifact({path:{chat_id:r,response_id:n,artifact_id:s},signal:d.signal})).data},async messages(r,n={}){let s=(await t.listChatMessages({path:{chat_id:r},query:{limit:n.limit,cursor:n.cursor},signal:n.signal})).data;return s.next_cursor===void 0?{messages:s.messages}:{messages:s.messages,nextCursor:s.next_cursor}},async parts(r,n={}){if(n.cursor!==void 0&&n.before!==void 0)throw new TypeError("chats.parts: cursor (where a page left off) or before (the oldest part the app's channel holds, by its id), not both");if(n.before!==void 0&&(!Number.isSafeInteger(n.before)||n.before<1))throw new TypeError(`chats.parts: before is a part's id \u2014 its journal sequence, a whole number from 1 (got ${String(n.before)})`);let s=(await t.listChatParts({path:{chat_id:r},query:{limit:n.limit,cursor:n.cursor,before:n.before},signal:n.signal})).data,d=s.parts.map(p=>({type:p.type,...p.id!==void 0?{id:p.id}:{},partId:p.part_id,data:p.data}));return s.next_cursor===void 0?{parts:d}:{parts:d,nextCursor:s.next_cursor}},async toolCall(r,n,s={}){let d=(await t.getChatToolCall({path:{chat_id:r,call_id:n},signal:s.signal})).data;return{callId:d.call_id,name:d.name,status:d.status,runId:d.run_id,responseId:d.response_id,input:d.input,output:d.output,outputBytes:d.output_bytes,imageCount:d.image_count,isError:d.is_error}},async toolCalls(r,n){if(typeof n?.turn!="string"||n.turn==="")throw new TypeError("chats.toolCalls: turn is the turn's responseId \u2014 a message's, or a turn's or an agent part's");let s=(await t.listTurnToolCalls({path:{chat_id:r},query:{turn:n.turn,limit:n.limit,cursor:n.cursor},signal:n.signal})).data,d=s.tool_calls.map(p=>({callId:p.call_id,name:p.name,state:p.state,createdAt:p.created_at,updatedAt:p.updated_at,arguments:p.arguments,...p.result!==void 0?{result:p.result}:{}}));return s.next_cursor===void 0?{toolCalls:d}:{toolCalls:d,nextCursor:s.next_cursor}},workspace:{async file(r,n,s={}){if(typeof n!="string"||n==="")throw new TypeError("chats.workspace.file: path is the file as the workspace's tree names it (repo/output/app/App.zip)");return(await t.getChatWorkspaceFile({path:{chat_id:r},query:{path:n,...s.manifest!==void 0?{manifest:s.manifest}:{}},signal:s.signal})).data},async addRepo(r,n){let s=typeof n?.repo=="string"?n.repo:n?.repo?.name;if(typeof s!="string"||!v.test(s))throw new TypeError("chats.workspace.addRepo: repo is the project's name for the repository (ai.repos.put), or its ai.repo");let d={repo:s};return n.branch!==void 0&&(d.branch=n.branch),(await t.addChatWorkspaceRepo({path:{chat_id:r},body:d,signal:n.signal})).data}},events(r){if(typeof r!="string"||!/^chat_[0-9a-f]{32}$/.test(r))throw new TypeError(`chats.events(id): a chat's id, chat_ and 32 hex digits (got ${JSON.stringify(r)})`);return Object.freeze({kind:"ai.chat",chatId:r,async pipe(n,s={}){await t.putChatPipe({path:{chat_id:r},body:{topic:n},signal:s.signal})},async unpipe(n={}){await t.deleteChatPipe({path:{chat_id:r},signal:n.signal})}})},async stop(r,n={}){return(await t.stopChat({path:{chat_id:r},...n.as!==void 0?{body:{as:n.as}}:{},signal:n.signal})).data.stopped},async approve(r,n,s={}){return(await t.decideChatApproval({path:{chat_id:r,approval_id:n},body:Ve(!0,s)})).data},async deny(r,n,s={}){return(await t.decideChatApproval({path:{chat_id:r,approval_id:n},body:Ve(!1,s)})).data},async answer(r,n,s,d={}){let p={output:F(s)};d.isError&&(p.is_error=!0),d.as!==void 0&&(p.as=d.as);try{return await Y(()=>t.answerChatToolCall({path:{chat_id:r,call_id:n},body:p})),!0}catch(_){if(_ instanceof $&&_.status===409)return!1;throw _}},async sendToSubagent(r,n,s,d={}){let p={client_id:d.clientId??Fe(),text:s};d.as!==void 0&&(p.as=d.as);let _=await Y(async()=>(await t.sendSubagentMessage({path:{chat_id:r,run_id:n},body:p})).data);return{runId:_.run_id,clientId:_.client_id}},async stopSubagent(r,n,s={}){return{runId:(await Y(async()=>(await t.stopSubagent({path:{chat_id:r,run_id:n},body:s.as!==void 0?{as:s.as}:{},signal:s.signal})).data,s.signal)).run_id}},async fork(r,n){if(typeof n?.beforeMessage!="string"||n.beforeMessage==="")throw new TypeError("chats.fork: beforeMessage is the id of the message the fork is cut before (a message's id, msg_\u2026)");let s={before_message:n.beforeMessage};return n.title!==void 0&&(s.title=n.title),n.members!==void 0&&(s.members=n.members.map(Ke)),(await t.forkChat({path:{chat_id:r},body:s,signal:n.signal})).data},goal:{async set(r,n){let s={objective:n.objective};return n.rubric!==void 0&&(s.rubric=n.rubric),n.maxTurns!==void 0&&(s.max_turns=n.maxTurns),n.budget!==void 0&&(s.budget={max_cost_usd:n.budget.maxCostUsd}),n.as!==void 0&&(s.as=n.as),oe((await t.setChatGoal({path:{chat_id:r},body:s,signal:n.signal})).data)},async get(r,n={}){return oe((await t.getChatGoal({path:{chat_id:r},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})).data)},async update(r,n){let s={};return n.status!==void 0&&(s.status=n.status),n.reason!==void 0&&(s.reason=n.reason),n.objective!==void 0&&(s.objective=n.objective),n.rubric!==void 0&&(s.rubric=n.rubric),n.maxTurns!==void 0&&(s.max_turns=n.maxTurns),n.budget!==void 0&&(s.budget=n.budget===null?null:{max_cost_usd:n.budget.maxCostUsd}),n.as!==void 0&&(s.as=n.as),oe((await t.updateChatGoal({path:{chat_id:r},body:s,signal:n.signal})).data)},async clear(r,n={}){await t.clearChatGoal({path:{chat_id:r},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})}},voice:{async start(r,n){if(typeof n?.sdp!="string"||!n.sdp.startsWith("v="))throw new TypeError("chats.voice.start: sdp is the app's WebRTC offer (an SDP, v=0 \u2026): its peer connection's localDescription.sdp");if(n.delegation!==void 0&&n.delegation!=="chat"&&n.delegation!=="events")throw new TypeError("chats.voice.start: delegation is chat (a turn of the chat) or events (ai.voice.delegated)");let s={sdp:n.sdp};n.voice!==void 0&&(s.voice=n.voice),n.delegation!==void 0&&(s.delegation=n.delegation),n.as!==void 0&&(s.as=n.as),n.instructions!==void 0&&(s.instructions=n.instructions),n.context!==void 0&&(s.context=n.context);let d=(await t.startChatVoice({path:{chat_id:r},body:s,signal:n.signal})).data;if(typeof d.sdp!="string"||d.sdp==="")throw new $({op:"startChatVoice",status:502,code:"no_answer",message:"the voice was started but its WebRTC answer was not given"});return{...H(d),sdp:d.sdp}},async get(r,n,s={}){return H((await t.getChatVoice({path:{chat_id:r,voice_id:n},query:s.as!==void 0?{as:s.as}:void 0,signal:s.signal})).data)},async command(r,n,s){if(!Et.includes(s?.type))throw new TypeError("chats.voice.command: type is speak (say this exactly), tell (say it in your own words), know (keep it in mind) or instruct (behave so)");if(typeof s.text!="string"||s.text==="")throw new TypeError("chats.voice.command: text is what the voice is given");if(s.delegationId!==void 0&&s.type!=="speak"&&s.type!=="tell")throw new TypeError("chats.voice.command: delegationId names the request a speak or a tell answers");if(s.interrupt!==void 0&&(typeof s.interrupt!="boolean"||s.type!=="speak"))throw new TypeError("chats.voice.command: interrupt is a speak's: it cuts what the voice is saying");let d={type:s.type,text:s.text};return s.delegationId!==void 0&&(d.delegation_id=s.delegationId),s.interrupt===!0&&(d.interrupt=!0),s.as!==void 0&&(d.as=s.as),H((await t.commandChatVoice({path:{chat_id:r,voice_id:n},body:d,signal:s.signal})).data)},async close(r,n,s={}){return H((await t.closeChatVoice({path:{chat_id:r,voice_id:n},query:s.as!==void 0?{as:s.as}:void 0,signal:s.signal})).data)}}},a={async list(r={}){return(await t.listAgents({signal:r.signal})).data.agents},async get(r,n={}){return(await t.getAgent({path:{name:D(r,"agents.get")},signal:n.signal})).data},async saveDraft(r,n,s={}){let d=`agents.saveDraft(${JSON.stringify(r)})`;if(D(r,"agents.saveDraft"),V(n))throw new TypeError(`${d}: a backend's ai.agent is its code's \u2014 its build's contract names it, and its chats ask its machine; it has no draft to save`);if(n===void 0)throw new TypeError(`${d}: its definition \u2014 { instructions, model, tools, \u2026 }`);let p=Z(n,d);return(await t.putAgent({path:{name:r},...s.revision!==void 0?{query:{revision:ze(s.revision,d)}}:{},body:p,signal:s.signal})).data},async publish(r,n={}){let s=`agents.publish(${JSON.stringify(r)})`;D(r,"agents.publish");let d=n.revision!==void 0?{revision:ze(n.revision,s)}:{};return(await t.publishAgent({path:{name:r},body:d,signal:n.signal})).data},async rollback(r,n,s={}){if(D(r,"agents.rollback"),!Number.isSafeInteger(n)||n<1)throw new TypeError(`agents.rollback(${JSON.stringify(r)}): version is one it had \u2014 a whole number from 1 (got ${String(n)})`);return(await t.rollbackAgent({path:{name:r},body:{version:n},signal:s.signal})).data},async versions(r,n={}){D(r,"agents.versions");let s=(await t.listAgentVersions({path:{name:r},query:{limit:n.limit,cursor:n.cursor},signal:n.signal})).data;return s.next_cursor===void 0?{versions:s.versions,publishedVersion:s.published_version}:{versions:s.versions,publishedVersion:s.published_version,nextCursor:s.next_cursor}},async delete(r,n={}){await t.deleteAgent({path:{name:D(r,"agents.delete")},signal:n.signal})},async tools(r={}){return(await t.listTools({signal:r.signal})).data.tools}},i={async put(r,n){let s={kind:n.kind,url:n.url};return n.description!==void 0&&(s.description=n.description),n.parameters!==void 0&&(s.parameters=n.parameters),n.approval!==void 0&&(s.approval=n.approval),(await t.putEndpoint({path:{name:r},body:s})).data},async list(){return(await t.listEndpoints({})).data.endpoints},async delete(r){await t.deleteEndpoint({path:{name:r}})}},l={async get(){return Ze((await t.getSettings({})).data)},async put(r){let n={};return r.clients!==void 0&&(n.clients=r.clients),r.userMessagesPerMinute!==void 0&&(n.user_messages_per_minute=r.userMessagesPerMinute),r.historyLimitBytes!==void 0&&(n.history_limit_bytes=r.historyLimitBytes),Ze((await t.putSettings({body:n})).data)}},u=r=>({name:r.name,repository:r.repository,defaultBranch:r.default_branch,backend:r.backend,createdAt:r.created_at});return{chats:o,agents:a,endpoints:i,settings:l,repos:{async put(r,n){let s=typeof r=="string"?r:r.name;if(typeof s!="string"||!v.test(s))throw new TypeError("repos.put: name is lowercase letters, digits, _ and -, starting with a letter, at most 64");let d=typeof r=="string"?{repository:n?.repository??"",...n?.defaultBranch?{default_branch:n.defaultBranch}:{},...n?.backend?{backend:n.backend}:{}}:{repository:r.repository,default_branch:r.defaultBranch,...r.machine?{backend:r.machine}:{}};return u((await t.putRepo({path:{name:s},body:d})).data)},async list(r={}){let n=(await t.listRepos({query:{limit:r.limit,cursor:r.cursor}})).data,s=n.repos.map(u);return n.next_cursor===void 0?{repos:s}:{repos:s,nextCursor:n.next_cursor}},async delete(r){await t.deleteRepo({path:{name:r}})}}}}var Mt=/^pb_[a-z0-9]+_s/;function Ye(e){let t=globalThis;return t.process?.env?.[e]??t.Deno?.env?.get(e)}function ie(){return"ai_"+crypto.randomUUID()}function de(e){if(e.prepared)return e;let t=e;return{name:"answer",schema:t,prepared:j(t,"answer")}}var Qe=4,jt=/^[a-z][a-z0-9-]{1,62}$/,et=["image/png","image/jpeg","image/webp","image/gif"],tt=5<<20,nt=6<<20;function ot(e){let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)}function Bt(e){return e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e)?-1:e.length/4*3-(e.endsWith("==")?2:e.endsWith("=")?1:0)}function Dt(e){if(!Array.isArray(e))throw new TypeError("images is a list of { bucket, path } (a file of the project's storage), { url } (an https address) or { mediaType, data } (its bytes)");if(e.length>Qe)throw new TypeError(`a question takes ${Qe} pictures at most (got ${e.length})`);let t=0;return e.map((o,a)=>{let i=o??{};if("bytes"in i||o instanceof Uint8Array)throw new TypeError(`images[${a}]: a picture's bytes are { mediaType, data } \u2014 or, in the project's storage, { bucket, path }`);if("data"in i||"mediaType"in i){if(i.bucket!==void 0||i.path!==void 0||i.url!==void 0)throw new TypeError(`images[${a}] is { bucket, path }, { url } or { mediaType, data }: one of them`);if(typeof i.mediaType!="string"||!et.includes(i.mediaType))throw new TypeError(`images[${a}].mediaType is the picture's type: ${et.join(", ")}`);let l=i.data instanceof Uint8Array?ot(i.data):i.data,u=typeof l=="string"?Bt(l):-1;if(u<0)throw new TypeError(`images[${a}].data is the picture's bytes: base64, or a Uint8Array`);if(u===0||u>tt)throw new TypeError(`images[${a}] is ${u} bytes: a picture given by its bytes is 1 byte to ${tt>>20} MiB`);if(t+=u,t>nt)throw new TypeError(`the pictures given by their bytes are ${nt>>20} MiB at most together: put a larger one in the project's storage and give { bucket, path }`);return{media_type:i.mediaType,data:l}}if(typeof i.url=="string"){if(i.bucket!==void 0||i.path!==void 0)throw new TypeError(`images[${a}] is { bucket, path } or { url }, not both`);let l;try{l=new URL(i.url)}catch{throw new TypeError(`images[${a}].url is not an address: ${JSON.stringify(i.url.slice(0,80))}`)}if(l.protocol!=="https:"||i.url.length>2048)throw new TypeError(`images[${a}].url is an https address of 2048 characters at most`);return{url:i.url}}if(typeof i.bucket!="string"||!jt.test(i.bucket)||typeof i.path!="string"||i.path==="")throw new TypeError(`images[${a}] is { bucket, path } \u2014 a file of the project's storage \u2014 { url } or { mediaType, data }`);return{bucket:i.bucket,path:i.path}})}var Nt=/^[a-z][a-z0-9_-]{0,63}(@[1-9][0-9]{0,8})?$/;function it(e){let t=typeof e=="string"?e:V(e)?.name;if(typeof t!="string"||!Nt.test(t))throw new TypeError(`agent is one of the project's agents by name (support), name@N for its version N (support@3), or a backend's ai.agent (got ${JSON.stringify(typeof e=="string"?e:typeof e)})`);return t}function q(e,t={},o){if(e.prompt===void 0&&e.messages===void 0)throw new TypeError("ask a model something: prompt, or messages");let a={...t};if(e.agent!==void 0&&(a.agent=it(e.agent)),e.prompt!==void 0&&(a.input=e.prompt),e.messages!==void 0&&(a.messages=e.messages),e.instructions!==void 0&&(a.instructions=e.instructions),e.model!==void 0&&(a.model=e.model),e.metadata!==void 0&&(a.metadata=e.metadata),e.images!==void 0&&(a.images=Dt(e.images)),e.tools!==void 0&&(a.tools=e.tools.map((i,l)=>{if(i?.source==="client")throw new TypeError(`tools[${l}]: ${i.name} is a client tool \u2014 an app answers it, in a chat; a one-shot answer has no app to wait for`);if(i?.source==="platform")throw new TypeError(`tools[${l}]: the platform's ${i.name} is a chat's agent's tool \u2014 a one-shot answer is given none`);let u=K(i,`tools[${l}]`);return u.source==="backend"&&u.machine===void 0&&o!==void 0&&(u.machine=o),u})),e.maxToolCalls!==void 0){if(!e.tools?.length)throw new TypeError("maxToolCalls bounds the calls of the tools given: give tools");a.max_tool_calls=ae(e.maxToolCalls,"ask")}return a}function rt(e,t){if(e.output===null||e.output===void 0)throw new b(t,"the answer is text, not a document: the agent has no output (the shape of its one-shot answers) \u2014 give it one, give generate a schema, or ask() it");return e.output}var E=class extends Error{code;response;constructor(t){super(t.error?.message??`the response ended ${t.status}`),this.name="AIResponseError",this.code=t.error?.code??t.status,this.response=t}};function Ut(e){let t=Uint8Array.from(atob(e),i=>i.charCodeAt(0)),o=new DataView(t.buffer,t.byteOffset,t.byteLength),a=new Array(t.byteLength/4);for(let i=0;i<a.length;i++)a[i]=o.getFloat32(i*4,!0);return a}async function st(e){let t,o;return e instanceof Uint8Array?(t=e,o=at(t)):typeof Blob<"u"&&e instanceof Blob?(t=new Uint8Array(await e.arrayBuffer()),o=e.type||at(t)):(t=e.bytes,o=e.mediaType),{media_type:o,data:ot(t)}}function at(e){return e[0]===137&&e[1]===80?"image/png":e[0]===255&&e[1]===216?"image/jpeg":e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":"application/octet-stream"}function Gt(e){let t=e.url??Ye("PALBASE_URL"),o=e.secretKey??Ye("PALBASE_SECRET_KEY");if(typeof t!="string"||t==="")throw new TypeError("url is the project address (https://<ref>.<domain>) \u2014 or set PALBASE_URL");if(typeof o!="string"||!Mt.test(o))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026) \u2014 or set PALBASE_SECRET_KEY; a model call is billed to the project, so it is never made with a publishable key");let a=fe(ue({baseUrl:t,credentials:{secretKey:o},fetch:e.fetch}),e.retry??ge);return pe.client(a)}function Lt(e){return new Proxy({},{get:(t,o)=>e.ai[o]})}function Jt(e={}){if(we())throw new TypeError("palbase/ai runs on a server: it speaks with the project secret key, which never goes into a browser or a mobile app \u2014 call your backend, and let it ask the model");if(e.machine!==void 0&&!v.test(e.machine))throw new TypeError("machine is the name of one of the project's machines");let t=e.server?Lt(e.server):Gt(e),o=e.resumeFor??12e4;async function a(c,g,m=ie()){return M(t.createResponse({headers:{"Idempotency-Key":m},body:c,signal:g}))}async function i(c,g={}){return(await t.getResponse({path:{response_id:c},signal:g.signal})).data}async function l(c,g,m,S,y){let w=0,x=c,R=ie(),N=()=>Date.now()+o,U=N();for(let G=0;;G++)try{if(x||(g===null?x=(await a({...y,stream:!0},S,R)).data:x=(await t.followResponse({path:{response_id:g},query:{offset:w},signal:S})).data),!x.body)throw new Error("the stream has no body");for await(let k of ke(x.body)){let A=JSON.parse(k.data);switch(k.event){case"response":g===null&&(g=A.id,m.admitted(A));break;case"delta":{let O=A.offset+he(A.text);if(O>w){let Q=A.offset>=w?A.text:be(A.text,w-A.offset);m.delta(w,Q),w=O}U=N();break}case"reset":A.offset<w&&(w=A.offset,m.reset(w));break;case"terminal":return A}}throw new Error("the stream ended before its answer did")}catch(k){if(x=null,S?.aborted||k instanceof $&&k.status>0&&k.status<500&&k.status!==429||g===null&&!(k instanceof $)||Date.now()>U)throw k;await new Promise(A=>setTimeout(A,Math.min(250*2**Math.min(G,4),4e3)))}}function u(c){if(c.status!=="completed")throw new E(c);return c.text??""}function h(c,g){let m=q(c,g?{schema:g.prepared.json,schema_name:g.name}:{},e.machine),S=[],y=!1,w,x=null,R=()=>{let f=x;x=null,f?.()},N,U,G=new Promise((f,T)=>{N=f,U=T});G.catch(()=>{});let k="",A=l(null,null,{admitted:f=>N(f.id),delta:(f,T)=>{k+=T,S.push(T),R()},reset:f=>{let T=ye(k,f);k=k.slice(0,T),S.push("\0reset:"+T),R()}},c.signal,m).then(f=>{let T=f.status==="completed"?f.text??"":"";return T.length>k.length&&T.startsWith(k)&&(S.push(T.slice(k.length)),k=T),y=!0,R(),f},f=>{throw y=!0,w=f,U(f),R(),f});A.catch(()=>{});async function*O(){for(let f=0;;f++){for(;f>=S.length;){if(y){if(w)throw w;return}await new Promise(T=>x=T)}yield S[f]}}async function*Q(){for await(let f of O())f.startsWith("\0reset:")||(yield f)}async function*dt(){let f="",T="";for await(let J of O()){J.startsWith("\0reset:")?f=f.slice(0,Number(J.slice(7))):f+=J;let P=ne(f);if(P===void 0)continue;let I=JSON.stringify(P);I!==T&&(T=I,yield P)}}let L=A.then(f=>{if(f.status!=="completed")throw new E(f);return f});L.catch(()=>{});let ce=g?L.then(f=>g.prepared.check(f.output)):Promise.reject(new TypeError("object is a schema stream's"));ce.catch(()=>{});let le=L.then(f=>f.text??k);return le.catch(()=>{}),{id:G,response:L,text:le,get textStream(){return Q()},get partialObjectStream(){return dt()},object:ce,toResponse(f={}){let T=new TextEncoder,J=new ReadableStream({async start(I){try{for await(let z of O())z.startsWith("\0reset:")?I.enqueue(T.encode(`event: reset
|
|
8
|
-
data: ${JSON.stringify({offset:Number(z.slice(7))})}
|
|
9
|
-
|
|
10
|
-
`)):I.enqueue(T.encode(`data: ${JSON.stringify({text:z})}
|
|
11
|
-
|
|
12
|
-
`));let C=await L;I.enqueue(T.encode(`event: done
|
|
13
|
-
data: ${JSON.stringify({id:C.id,text:C.text,output:C.output,usage:C.usage})}
|
|
14
|
-
|
|
15
|
-
`))}catch(C){let z=C instanceof E||C instanceof $?C.code:"stream_failed";I.enqueue(T.encode(`event: error
|
|
16
|
-
data: ${JSON.stringify({code:z})}
|
|
17
|
-
|
|
18
|
-
`))}finally{I.close()}}}),P=new Headers(f.headers);return P.set("content-type","text/event-stream"),P.set("cache-control","no-store"),P.set("x-accel-buffering","no"),new globalThis.Response(J,{...f,headers:P})}}}async function r(c,g){return l(null,null,{admitted:()=>{},delta:()=>{},reset:()=>{}},c.signal,q(c,g,e.machine))}let{chats:n,agents:s,endpoints:d,settings:p,repos:_}=He(t);return{module:t,chats:n,agents:s,endpoints:d,settings:p,repos:_,tool:De,clientTool:Ne,deferred:Me,agent:Le,repo:Ue,repoTokens:Ge,async ask(c,g={}){let m=typeof c=="string"?{...g,prompt:c}:c;return u(await r(m,{}))},async generate(c){if(c.schema===void 0){if(c.agent===void 0)throw new TypeError("generate: a schema \u2014 the answer's shape \u2014 or an agent whose output is");if(c.background){let x=(await a(q(c,{background:!0},e.machine),c.signal)).data;return{id:x.id,status:x.status}}let y=await r(c,{});if(y.status!=="completed")throw new E(y);return rt(y,it(c.agent))}let g=de(c.schema),m={schema:g.prepared.json,schema_name:g.name};if(c.background){let w=(await a(q(c,{...m,background:!0},e.machine),c.signal)).data;return{id:w.id,status:w.status}}let S=await r(c,m);if(S.status!=="completed")throw new E(S);return g.prepared.check(S.output)},stream(c){return h(c,c.schema?de(c.schema):void 0)},async start(c){let g=(await a(q(c,{background:!0},e.machine),c.signal)).data;return{id:g.id,status:g.status}},schema(c,g){return{name:c,schema:g,prepared:j(g,c)}},response:i,async result(c,g){let m=await i(c);if(m.status!=="completed")throw new E(m);return g===void 0?rt(m,"the response"):de(g).prepared.check(m.output)},async cancel(c){return(await t.cancelResponse({path:{response_id:c}})).data},async embed(c,g={}){let m=Array.isArray(c)?c:[c],S=[];for(let y=0;y<m.length;y+=1024){let w=await M(t.createEmbeddings({body:{input:m.slice(y,y+1024),model:g.model,dimensions:g.dimensions},signal:g.signal}));for(let x of w.data.vectors)S.push(Ut(x))}return Array.isArray(c)?S:S[0]},async image(c){let g={prompt:c.prompt};for(let y of["model","size","quality","background","format","count"])c[y]!==void 0&&(g[y]=c[y]);c.references?.length&&(g.references=await Promise.all(c.references.map(st))),c.mask&&(g.mask=await st(c.mask));let m=(await M(t.createImage({headers:{"Idempotency-Key":ie()},body:g,signal:c.signal}))).data;for(let y=0;m.status==="running";y++){if(await new Promise(w=>setTimeout(w,Math.min(500+y*250,3e3))),c.signal?.aborted)throw c.signal.reason;m=(await t.getImage({path:{image_id:m.id},signal:c.signal})).data}if(m.status!=="completed")throw new Error(`the image failed: ${m.error?.code??"image_failed"}: ${m.error?.message??""}`);let S=await Promise.all(m.files.map(async y=>{let x=(await t.getImageFile({path:{image_id:m.id,position:y.position},signal:c.signal})).data;return{mediaType:y.media_type,bytes:new Uint8Array(await x.arrayBuffer())}}));return{id:m.id,model:m.model,pictures:S,costNanoUSD:m.usage?.cost_nano_usd??0,save(y,w,x=0){let R=S[x];if(!R)throw new RangeError(`the job made ${S.length} picture(s)`);return y.upload(w,R.bytes,{contentType:R.mediaType})}}},async models(){return(await t.listModels({})).data},async usage(c={}){let g=c.metadata===void 0?void 0:JSON.stringify(c.metadata),m=(await t.listUsage({query:{kind:c.kind,limit:c.limit,cursor:c.cursor,metadata:g}})).data;return{usage:m.usage,nextCursor:m.next_cursor}},async spend(c={}){return(await t.getSpend({signal:c.signal})).data},async connectProvider(c,g){return(await t.connectProvider({path:{provider:c},body:{key:g}})).data},async disconnectProvider(c){await t.disconnectProvider({path:{provider:c}})}}}export{ne as a,b,j as c,se as d,E as e,Jt as f};
|