palbase 0.20.0 → 0.22.1
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 +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{ILHFQK3J.js → 2V5VKJXB.js} +1 -1
- package/dist/chunks/{CFJYJRJ7.js → 352QZYNH.js} +2 -2
- package/dist/chunks/{W4JKOGHG.js → 3IKX72DZ.js} +3 -3
- package/dist/chunks/{2NYI4FOR.js → 3PDILHR3.js} +2 -2
- package/dist/chunks/{DUO4FFKV.js → 56MEPQGY.js} +2 -2
- package/dist/chunks/{Q6OD5IUC.js → 5NVQ2ZA3.js} +1 -1
- package/dist/chunks/{KGAMXI25.js → 6WAHQKN5.js} +2 -2
- package/dist/chunks/{LN7FO4IE.js → AVG7WTXK.js} +2 -2
- package/dist/chunks/{5QSFOMN7.js → B7IQBQTB.js} +2 -2
- package/dist/chunks/{7BSKXUEV.js → C65W55SB.js} +2 -2
- package/dist/chunks/{WXDISYY6.js → CDB73SNL.js} +2 -2
- package/dist/chunks/{X6Y7MMBI.js → DPGX7OSC.js} +2 -2
- package/dist/chunks/{MPCXNC4L.js → GUHTHKQ7.js} +1 -1
- package/dist/chunks/IE3B45K2.js +18 -0
- package/dist/chunks/{KSRRQWGG.js → IV4IHGMC.js} +2 -2
- package/dist/chunks/{UE4A6DEG.js → IZH73QQW.js} +2 -2
- package/dist/chunks/{O65ATC5C.js → OLWZ7DGN.js} +2 -2
- package/dist/chunks/{BSJV6PEL.js → PRLEJFRO.js} +1 -1
- package/dist/chunks/{U3U53UJF.js → PUU5G4P3.js} +1 -1
- package/dist/chunks/{4UGIL34D.js → QZX64KLT.js} +2 -2
- package/dist/chunks/{45465257.js → SBKB3O33.js} +2 -2
- package/dist/chunks/{6TW5HR5D.js → SO6WAEOL.js} +1 -1
- package/dist/chunks/{CGTOJ44L.js → V2V7QQAT.js} +1 -1
- package/dist/cli.js +82 -82
- 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/internal/src/modules/ai.d.ts +46 -2
- package/types/internal/src/modules/messaging.d.ts +16 -3
- package/types/web/src/messaging.d.ts +26 -5
- package/dist/chunks/ZYBPLNPD.js +0 -18
|
@@ -1239,14 +1239,18 @@ export type ScheduledPage = {
|
|
|
1239
1239
|
next_cursor?: string;
|
|
1240
1240
|
};
|
|
1241
1241
|
/**
|
|
1242
|
-
* A message a search found, and where it says what was asked.
|
|
1242
|
+
* A message a search found, and where it says what was asked — or, found by its meaning, how near the question it is.
|
|
1243
1243
|
*/
|
|
1244
1244
|
export type SearchHit = {
|
|
1245
1245
|
/**
|
|
1246
|
-
* Where it says a word of the search, in the order said.
|
|
1246
|
+
* Where it says a word of the search, in the order said; none for a message found by its meaning.
|
|
1247
1247
|
*/
|
|
1248
1248
|
matches: SearchMatch[];
|
|
1249
1249
|
message: Message;
|
|
1250
|
+
/**
|
|
1251
|
+
* Found by its meaning (by=meaning): how near the question it is, the cosine of their vectors (higher: nearer; what is found is at least 0.3).
|
|
1252
|
+
*/
|
|
1253
|
+
score?: number;
|
|
1250
1254
|
};
|
|
1251
1255
|
/**
|
|
1252
1256
|
* Where a message found says a word of the search: in its text, or a file's name. offset and length are in UTF-16 code units, as mentions are.
|
|
@@ -1360,6 +1364,10 @@ export type Settings = {
|
|
|
1360
1364
|
* Messages older are removed; null: kept for good.
|
|
1361
1365
|
*/
|
|
1362
1366
|
retention_days: number | null;
|
|
1367
|
+
/**
|
|
1368
|
+
* Messages are found by what they mean too (GET /messaging/search?by=meaning): each message's text — not a system message's, nor one seen a limited number of times, nor one of vanish mode — is embedded by the project's embedding model, through the AI module, billed to the project as its AI use (Palbase's provider: kept by it up to 30 days for abuse monitoring, never trained on). Off (the default): no message goes to a model.
|
|
1369
|
+
*/
|
|
1370
|
+
search_by_meaning: boolean;
|
|
1363
1371
|
};
|
|
1364
1372
|
/**
|
|
1365
1373
|
* Changes how the project runs its conversations; what it names changes.
|
|
@@ -1381,6 +1389,10 @@ export type SettingsRequest = {
|
|
|
1381
1389
|
* 1 to 36,500; null: for good.
|
|
1382
1390
|
*/
|
|
1383
1391
|
retention_days?: number | null;
|
|
1392
|
+
/**
|
|
1393
|
+
* Turned on, the messages written before are embedded too (a walk, in the background), and each one written from then on; turned off, nothing more is embedded and the vectors are removed.
|
|
1394
|
+
*/
|
|
1395
|
+
search_by_meaning?: boolean;
|
|
1384
1396
|
};
|
|
1385
1397
|
/**
|
|
1386
1398
|
* What changed for the reader since their cursor.
|
|
@@ -2388,7 +2400,8 @@ export declare function client(t: Transport): {
|
|
|
2388
2400
|
}): Promise<Reply<200, ScheduledMessage>>;
|
|
2389
2401
|
searchMessages(input: {
|
|
2390
2402
|
query: {
|
|
2391
|
-
q: string; /**
|
|
2403
|
+
q: string; /** words (the default): the messages that say every word of q. meaning: those nearest what q means (the project's search_by_meaning on): one page, the nearest first; cursor is not taken. */
|
|
2404
|
+
by?: "words" | "meaning"; /** Search one conversation of the reader's only. */
|
|
2392
2405
|
conversation_id?: string; /** How many (1 to 50; 20 when absent). */
|
|
2393
2406
|
limit?: number; /** The cursor a page handed out (next_cursor). */
|
|
2394
2407
|
cursor?: string;
|
|
@@ -105,11 +105,21 @@ export interface ThreadViewState {
|
|
|
105
105
|
focus: string | null;
|
|
106
106
|
}
|
|
107
107
|
export interface SearchOptions {
|
|
108
|
+
/**
|
|
109
|
+
* How messages are found: by their words (the default) — every word asked, each a word's beginning — or by what
|
|
110
|
+
* they mean ('meaning'): those nearest the question, sharing none of its words perhaps ("flight time" finds "THY
|
|
111
|
+
* leaves at 14:30"), the nearest first, each with its score; one page, no conversations found by their name. By
|
|
112
|
+
* meaning, the project's setting search_by_meaning is on — or the search is refused, a PalbaseError whose code says
|
|
113
|
+
* why: 'search_by_meaning_off' (409), 'ai_payment_required' (402: the project's AI use is spent for the month;
|
|
114
|
+
* search by words meanwhile), 'too_many_searches' (429: a person asks 30 questions at once and one more a minute;
|
|
115
|
+
* retryAfter says when), 'busy' or 'embedding_unavailable' (503, retryAfter).
|
|
116
|
+
*/
|
|
117
|
+
by?: 'words' | 'meaning';
|
|
108
118
|
/** Search one conversation of the person's only. */
|
|
109
119
|
conversationId?: string;
|
|
110
120
|
/** How many messages a page holds (1 to 50; 20 when absent). */
|
|
111
121
|
limit?: number;
|
|
112
|
-
/** The page after the one that handed out this cursor (nextCursor). */
|
|
122
|
+
/** The page after the one that handed out this cursor (nextCursor): a search by words alone. */
|
|
113
123
|
cursor?: string;
|
|
114
124
|
}
|
|
115
125
|
/** A message a search found, with what the app draws it with and where it opens. */
|
|
@@ -125,8 +135,13 @@ export interface SearchHit {
|
|
|
125
135
|
sender: Profile | null;
|
|
126
136
|
/** The other person of a direct conversation. */
|
|
127
137
|
peer: Profile | null;
|
|
128
|
-
/** Where it says what was asked: its text, or a file's name (UTF-16 code units). */
|
|
138
|
+
/** Where it says what was asked: its text, or a file's name (UTF-16 code units); none when found by its meaning. */
|
|
129
139
|
matches: SearchMatch[];
|
|
140
|
+
/**
|
|
141
|
+
* Found by its meaning (by: 'meaning'): how near the question it is — the cosine of their vectors, from 0.3 (what
|
|
142
|
+
* is found is at least that) to 1, higher nearer; null when found by its words.
|
|
143
|
+
*/
|
|
144
|
+
score: number | null;
|
|
130
145
|
/**
|
|
131
146
|
* The thread it answers in, when its conversation's timeline does not show it: open it with
|
|
132
147
|
* thread(conversation.id, threadRootId, { at: message.id }); null — open conversation(conversation.id, { at: message.id }).
|
|
@@ -143,11 +158,14 @@ export interface ConversationMatch {
|
|
|
143
158
|
matches: Hit[];
|
|
144
159
|
}
|
|
145
160
|
export interface SearchResults {
|
|
146
|
-
/**
|
|
161
|
+
/**
|
|
162
|
+
* The person's conversations whose name says every word asked, the latest first — on the first page alone of a
|
|
163
|
+
* search by words; none by meaning.
|
|
164
|
+
*/
|
|
147
165
|
conversations: ConversationMatch[];
|
|
148
|
-
/** The messages found, the newest first. */
|
|
166
|
+
/** The messages found, the newest first — by meaning, the nearest first. */
|
|
149
167
|
messages: SearchHit[];
|
|
150
|
-
/** The next page's cursor (search(query, { cursor })); null on the last. */
|
|
168
|
+
/** The next page's cursor (search(query, { cursor })); null on the last, and by meaning (one page). */
|
|
151
169
|
nextCursor: string | null;
|
|
152
170
|
}
|
|
153
171
|
/** Where a browser keeps it: IndexedDB, one object store of each person's state. */
|
|
@@ -278,6 +296,9 @@ export declare class Messaging {
|
|
|
278
296
|
* first, a page at a time: in all their conversations, or one (conversationId). Each comes with its conversation, its name and picture, who wrote
|
|
279
297
|
* it and where it says what was asked. On the first page, the conversations whose name says it too (a group's
|
|
280
298
|
* title, the other person's name), from the person's own list. A query with no word finds nothing.
|
|
299
|
+
*
|
|
300
|
+
* By meaning (by: 'meaning'; the project's setting search_by_meaning on), the messages nearest what the query
|
|
301
|
+
* means instead, the nearest first, each with its score: one page, no conversations by name. Opened as any find is.
|
|
281
302
|
*/
|
|
282
303
|
search(query: string, opts?: SearchOptions): Promise<SearchResults>;
|
|
283
304
|
/** The person's conversations whose name says every word asked: a group's title, the other person's name. */
|
package/dist/chunks/ZYBPLNPD.js
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
/*! palbase 0.20.0 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{a as M,c as he,d as ye,e as be}from"./X6Y7MMBI.js";import{a as we}from"./U3U53UJF.js";import{a as pe}from"./KGAMXI25.js";import{a as ge,b as fe,c as me}from"./KSRRQWGG.js";import{b as $,d as ue}from"./DUO4FFKV.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};
|