palbase 0.43.2 → 0.44.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 +3 -3
- package/dist/backend/stack.js +1 -1
- package/dist/backend/test.js +2 -2
- package/dist/chunks/{NDSHGZTF.js → 34R3K5US.js} +1 -1
- package/dist/chunks/{6VXBCORH.js → 4UCIQG2Y.js} +1 -1
- package/dist/chunks/{5ZJSSVUB.js → 5CCR2TT2.js} +2 -2
- package/dist/chunks/{RLFOMLA6.js → B2UB6NXM.js} +1 -1
- package/dist/chunks/C23X4BLJ.js +18 -0
- package/dist/chunks/{ZGFYTDBX.js → CSQQWUK3.js} +1 -1
- package/dist/chunks/{CW6YXFVV.js → D3YUJVZV.js} +1 -1
- package/dist/chunks/{26QIRZHC.js → H46O3FTO.js} +2 -2
- package/dist/chunks/{B6G5JODS.js → J4STW4ES.js} +1 -1
- package/dist/chunks/{7L3EJBD5.js → K4C4USMS.js} +2 -2
- package/dist/chunks/{FCF3UM3A.js → MMATRRQU.js} +2 -2
- package/dist/chunks/{P5EFS7JB.js → NBS26HGY.js} +1 -1
- package/dist/chunks/{5AFQHJYE.js → NVOPULRM.js} +2 -2
- package/dist/chunks/{YDJSWRID.js → NZSNVZQT.js} +2 -2
- package/dist/chunks/{F2T72KU7.js → OIZX76IE.js} +2 -2
- package/dist/chunks/{GHB6JKVO.js → OS7P6J4N.js} +2 -2
- package/dist/chunks/{5V42WCTP.js → P6TUNAHK.js} +2 -2
- package/dist/chunks/{X6P5WU56.js → Q6UBSQPN.js} +2 -2
- package/dist/chunks/{UHAO6RWA.js → QKZQMN7B.js} +2 -2
- package/dist/chunks/{E6BZRE2N.js → R2ED6W3Q.js} +2 -2
- package/dist/chunks/{OLMU3ODF.js → URWXDZAD.js} +2 -2
- package/dist/chunks/{MLUWULWR.js → WWHXFMDI.js} +7 -7
- package/dist/chunks/{HJ6MXPE3.js → YIJIXCUR.js} +2 -2
- package/dist/cli.js +152 -152
- 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/ai.d.ts +21 -1
- package/types/ai/src/chats.d.ts +107 -3
- package/types/ai/src/index.d.ts +3 -2
- package/types/ai/src/pools.d.ts +177 -0
- package/types/ai/src/tools.d.ts +71 -3
- package/dist/chunks/XLZYPS2V.js +0 -18
package/types/ai/src/chats.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type * as modules from '../../internal/src/modules/index.js';
|
|
2
2
|
import { type ToolResult } from '../../internal/src/tool-output.js';
|
|
3
|
-
import { type AgentDefinitionInput, type BackendAgent, type BackendRepo } from './tools.js';
|
|
3
|
+
import { type AgentDefinitionInput, type BackendAgent, type BackendRepo, type WorkspaceTree } from './tools.js';
|
|
4
4
|
type Module = ReturnType<typeof modules.ai.client>;
|
|
5
5
|
export type Chat = modules.ai.Chat;
|
|
6
6
|
export type ChatMessage = modules.ai.ChatMessage;
|
|
@@ -51,6 +51,15 @@ export interface EndpointInput {
|
|
|
51
51
|
parameters?: Record<string, unknown>;
|
|
52
52
|
/** Every call waits for a person's yes. */
|
|
53
53
|
approval?: boolean;
|
|
54
|
+
/**
|
|
55
|
+
* True for an endpoint of the project's own — an MCP server or an https tool — that reads or writes a chat's
|
|
56
|
+
* workspace: each call tells it the tree it is made at (an MCP server in its _meta palbase/workspace, an https tool
|
|
57
|
+
* in its context.workspace: the chat's id, manifestId and seq), and the tree its answer names is waited for. Left out
|
|
58
|
+
* (false): any server's address — a third party's API or MCP server — told nothing of the chat's workspace (an https
|
|
59
|
+
* tool is told the turn's chatId as ever), a tree it answers ignored. An endpoint put before https tools took the
|
|
60
|
+
* setting is told nothing until it is put again with it. The backend's own tools are told the workspace always.
|
|
61
|
+
*/
|
|
62
|
+
workspace?: boolean;
|
|
54
63
|
}
|
|
55
64
|
export interface MemberInput {
|
|
56
65
|
userId: string;
|
|
@@ -106,6 +115,12 @@ export interface CreateChat {
|
|
|
106
115
|
*/
|
|
107
116
|
trailers?: CommitTrailer[];
|
|
108
117
|
};
|
|
118
|
+
/**
|
|
119
|
+
* The project's runner pool its workspace runs on (ai.pools), by its id or its name: its sessions run on the
|
|
120
|
+
* project's own machines enrolled there, a Mac or a Linux box. Left out, the platform's own Linux machines. A chat
|
|
121
|
+
* that names one works in a workspace; one the project has not is refused (400).
|
|
122
|
+
*/
|
|
123
|
+
pool?: string;
|
|
109
124
|
signal?: AbortSignal;
|
|
110
125
|
}
|
|
111
126
|
/** A repository the project's chats work in, as the module keeps it. */
|
|
@@ -495,7 +510,72 @@ export interface Voices {
|
|
|
495
510
|
signal?: AbortSignal;
|
|
496
511
|
}): Promise<ChatVoice>;
|
|
497
512
|
}
|
|
498
|
-
/**
|
|
513
|
+
/** What a write of a chat's workspace left: the tree it is at now — what a tool answers with ai.answer(output, { workspaceTree }). */
|
|
514
|
+
export interface WorkspaceWrite {
|
|
515
|
+
/** The file. */
|
|
516
|
+
path: string;
|
|
517
|
+
/** The tree the workspace is at now: a file of it is read by it (workspace.file's manifest). */
|
|
518
|
+
manifestId: string;
|
|
519
|
+
/** Its place in the workspace's history. */
|
|
520
|
+
seq: number;
|
|
521
|
+
}
|
|
522
|
+
/** A token of a chat's workspace, never said again: what it may do, what it is for, when it expires. */
|
|
523
|
+
export interface WorkspaceToken {
|
|
524
|
+
/** Its id: revoked by it. */
|
|
525
|
+
id: string;
|
|
526
|
+
/** read: the workspace followed; write: followed and written, both ways. */
|
|
527
|
+
access: 'read' | 'write' | (string & {});
|
|
528
|
+
/** What it is for — the machine's name: a conflict names its writer by it. */
|
|
529
|
+
label?: string;
|
|
530
|
+
expiresAt: string;
|
|
531
|
+
/** The workspace's id in the store. */
|
|
532
|
+
workspaceId: string;
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* A workspace token as it is minted: the token and where it syncs, said once — on the machine,
|
|
536
|
+
* `PALAI_WORKSPACE_TOKEN=<token> palai workspace sync --url <syncUrl> <dir>`, or the token on standard input with
|
|
537
|
+
* `--token-file -`; never on the command line (palai has no --token: any process on the machine could read it).
|
|
538
|
+
*/
|
|
539
|
+
export interface WorkspaceTokenMinted extends WorkspaceToken {
|
|
540
|
+
/** The token, said once: given palai workspace sync in PALAI_WORKSPACE_TOKEN, or on its standard input (--token-file -). */
|
|
541
|
+
token: string;
|
|
542
|
+
/** Where the workspace's token routes are, at the project's own address: `palai workspace sync --url <syncUrl> <dir>`. */
|
|
543
|
+
syncUrl: string;
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* The tokens of a chat's workspace, from its server: a machine of the customer's — a developer's computer, a CI
|
|
547
|
+
* runner — syncs the workspace with one (palai workspace sync), live and both ways (write) or followed (read). While
|
|
548
|
+
* one lives the chat's workspace events are told (ai.workspace.published, ai.workspace.conflict).
|
|
549
|
+
*/
|
|
550
|
+
export interface WorkspaceTokens {
|
|
551
|
+
/**
|
|
552
|
+
* Mints one, said once: it lives ttlSeconds (1 to 604 800; an hour when left out) — no longer than an environment's
|
|
553
|
+
* token it is minted with — and answers at the project's own address alone (syncUrl). A member who mints one (the
|
|
554
|
+
* project letting its app's users in) mints it for an hour at most; it is theirs alone, and stops answering when they
|
|
555
|
+
* leave the chat or the project turns clients off. A chat whose first turn has not opened its workspace has it opened
|
|
556
|
+
* now; a chat of no workspace: 409 no_workspace.
|
|
557
|
+
*/
|
|
558
|
+
create(id: string, token: {
|
|
559
|
+
access: 'read' | 'write';
|
|
560
|
+
ttlSeconds?: number;
|
|
561
|
+
label?: string;
|
|
562
|
+
signal?: AbortSignal;
|
|
563
|
+
}): Promise<WorkspaceTokenMinted>;
|
|
564
|
+
/** Its tokens — access, label, when each expires — none of them said again: the server's every one, a member's their own. */
|
|
565
|
+
list(id: string, options?: {
|
|
566
|
+
signal?: AbortSignal;
|
|
567
|
+
}): Promise<WorkspaceToken[]>;
|
|
568
|
+
/** Revoked at once: every token route refuses it from then, and an event stream open with it ends. A member revokes their own. */
|
|
569
|
+
revoke(id: string, tokenId: string, options?: {
|
|
570
|
+
signal?: AbortSignal;
|
|
571
|
+
}): Promise<void>;
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* A file's bytes as a workspace write takes them: text (written as UTF-8), bytes, a Blob, or a stream of bytes — a
|
|
575
|
+
* stream is read here whole first (64 MiB at most), so the write says its length, as the workspace's store asks.
|
|
576
|
+
*/
|
|
577
|
+
export type WorkspaceFileBody = string | Uint8Array | Blob | ReadableStream<Uint8Array>;
|
|
578
|
+
/** A chat's workspace, from its server: a file of a tree it published, written or removed, a repository put in it at work, its sync tokens. */
|
|
499
579
|
export interface Workspaces {
|
|
500
580
|
/**
|
|
501
581
|
* A file of the chat's workspace, its bytes: from the tree it is at now, or from the one an ai.workspace.published
|
|
@@ -516,6 +596,26 @@ export interface Workspaces {
|
|
|
516
596
|
branch?: string;
|
|
517
597
|
signal?: AbortSignal;
|
|
518
598
|
}): Promise<Chat>;
|
|
599
|
+
/**
|
|
600
|
+
* Writes one file of the chat's workspace, its bytes the body (64 MiB at most: a larger one is refused here, before it
|
|
601
|
+
* is sent — a stream as soon as it passes the bound — and by the module, 413 file_too_large): published over
|
|
602
|
+
* whatever the workspace's head holds — the write is deliberate, no conflict is made of it — and synced to every
|
|
603
|
+
* machine that holds the workspace, the session's own before the agent's next command; it is told as
|
|
604
|
+
* ai.workspace.published. path is relative to its root (repo/src/config.json): 1 to 2048 bytes, each segment 255 at
|
|
605
|
+
* most. A stream body is read whole before the write is sent, so it says its length. A backend tool that writes answers
|
|
606
|
+
* the tree it left: ai.answer(output, { workspaceTree: written }). A chat whose first turn has not opened its
|
|
607
|
+
* workspace has it opened now; a chat of no workspace: 409 no_workspace.
|
|
608
|
+
*/
|
|
609
|
+
write(id: string, path: string, body: WorkspaceFileBody, options?: {
|
|
610
|
+
contentType?: string;
|
|
611
|
+
signal?: AbortSignal;
|
|
612
|
+
}): Promise<WorkspaceWrite>;
|
|
613
|
+
/** Removes one file of the chat's workspace, as a write is made: synced to every machine that holds it. */
|
|
614
|
+
remove(id: string, path: string, options?: {
|
|
615
|
+
signal?: AbortSignal;
|
|
616
|
+
}): Promise<WorkspaceWrite>;
|
|
617
|
+
/** The tokens a machine of the customer's syncs the workspace with (palai workspace sync). */
|
|
618
|
+
readonly tokens: WorkspaceTokens;
|
|
519
619
|
}
|
|
520
620
|
export interface Chats {
|
|
521
621
|
create(chat: CreateChat): Promise<Chat>;
|
|
@@ -638,11 +738,15 @@ export interface Chats {
|
|
|
638
738
|
* The answer of a client tool's call (a tool event's call_id): true when it is the one taken, false when another came
|
|
639
739
|
* first. As a member (as): the app of the member whose turn it is answers it (403 not_your_turn otherwise). A
|
|
640
740
|
* backend tool that returned ai.deferred() — its ToolContext's chatId and callId — is answered here too, by the
|
|
641
|
-
* server as itself (never as a member), within the while it named.
|
|
741
|
+
* server as itself (never as a member), within the while it named. A tool that wrote the chat's workspace names the
|
|
742
|
+
* tree its writes left (workspaceTree: chats.workspace.write's answer, { manifestId, seq }, either or both), as an
|
|
743
|
+
* answer given at once does (ai.answer(output, { workspaceTree })): the agent's next command waits for the session's
|
|
744
|
+
* machine to have it.
|
|
642
745
|
*/
|
|
643
746
|
answer(id: string, callId: string, output: ToolResult, options?: {
|
|
644
747
|
isError?: boolean;
|
|
645
748
|
as?: string;
|
|
749
|
+
workspaceTree?: WorkspaceTree;
|
|
646
750
|
}): Promise<boolean>;
|
|
647
751
|
/** A message for one of the agent's subagents at work (an agent event's run_id, a tool call's ctx.runId), at its next step — as a member, held to their rules. */
|
|
648
752
|
sendToSubagent(id: string, runId: string, text: string, options?: {
|
package/types/ai/src/index.d.ts
CHANGED
|
@@ -4,7 +4,8 @@ export { AISchemaError, prepare } from './schema.js';
|
|
|
4
4
|
export { ToolError } from './tools.js';
|
|
5
5
|
export type { Infer, StandardSchema } from './schema.js';
|
|
6
6
|
export { partial } from './partial.js';
|
|
7
|
-
export type { AISettings, Agent, AgentTool, AgentVersion, Agents, Chat, ChatEvents, ChatGoal, ChatMessage, ChatStreamPart, ChatToolCall, ChatVoice, Chats, CommitTrailer, CreateChat, Decision, Endpoint, EndpointInput, Endpoints, ForkChat, GoalChange, Goals, MemberInput, MessageAttachment, MessageFile, MessageImage, Repo, Repos, SendMessage, SetGoal, Settings, StartVoice, TurnAdvisorCost, TurnArtifact, TurnCost, TurnRunCost, TurnToolCall, VoiceCommand, Voices, Workspaces, } from './chats.js';
|
|
8
|
-
export type {
|
|
7
|
+
export type { AISettings, Agent, AgentTool, AgentVersion, Agents, Chat, ChatEvents, ChatGoal, ChatMessage, ChatStreamPart, ChatToolCall, ChatVoice, Chats, CommitTrailer, CreateChat, Decision, Endpoint, EndpointInput, Endpoints, ForkChat, GoalChange, Goals, MemberInput, MessageAttachment, MessageFile, MessageImage, Repo, Repos, SendMessage, SetGoal, Settings, StartVoice, TurnAdvisorCost, TurnArtifact, TurnCost, TurnRunCost, TurnToolCall, VoiceCommand, Voices, WorkspaceFileBody, WorkspaceToken, WorkspaceTokenMinted, WorkspaceTokens, WorkspaceWrite, Workspaces, } from './chats.js';
|
|
8
|
+
export type { EnvVariable, EnvVariables, Pool, PoolKey, PoolKeyEnroll, PoolKeyMinted, PoolKeys, PoolMachine, PoolMachines, PoolState, Pools } from './pools.js';
|
|
9
|
+
export type { AdvisorDefinition, AgentContext, AgentDefinitionInput, BackendAgent, BackendAgentOptions, BackendRepo, BackendTool, BackendToolOptions, ChatContext, ClientTool, ClientToolOptions, DeferredAnswer, Effort, HttpsToolRef, McpToolRef, PlatformToolName, PlatformToolRef, PreparedOutput, RepoTokenContext, RepoTokens, SubagentDefinition, Thinking, Tool, ToolAnswer, ToolContext, ToolReply, ToolWorkspace, TurnDefinition, TurnMessage, WorkspaceTree, } from './tools.js';
|
|
9
10
|
export type { AgentEvent, ChatEvent, GoalEvent, GoalKind, HistoryEvent, HistoryItem, MessageEvent, Publication, ResetEvent, TextEvent, ThinkingEvent, ToolEvent, ToolStatus, TranscriptEvent, TurnEnd, TurnEvent, TurnStatus, VoiceEvent, WaitingReason, } from '../../internal/src/chat.js';
|
|
10
11
|
export type { ToolPart, ToolResult } from '../../internal/src/tool-output.js';
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import type * as modules from '../../internal/src/modules/index.js';
|
|
2
|
+
type Module = ReturnType<typeof modules.ai.client>;
|
|
3
|
+
/** A runner pool of the project's: its machines of one type — an operating system and an architecture. */
|
|
4
|
+
export interface Pool {
|
|
5
|
+
/** Its id: named by it, or by its name. */
|
|
6
|
+
id: string;
|
|
7
|
+
name: string;
|
|
8
|
+
os: 'linux' | 'macos' | (string & {});
|
|
9
|
+
arch: 'amd64' | 'arm64' | (string & {});
|
|
10
|
+
createdAt?: string;
|
|
11
|
+
/** A listed pool's: how many machines it has. */
|
|
12
|
+
machines?: number;
|
|
13
|
+
/** A listed pool's: how many sessions its machines take at once, and hold now. */
|
|
14
|
+
capacityTotal?: number;
|
|
15
|
+
capacityUsed?: number;
|
|
16
|
+
/** A listed pool's: how many sessions wait for a place. */
|
|
17
|
+
waiting?: number;
|
|
18
|
+
}
|
|
19
|
+
/** A pool's single-use enrolment key: never said again once it is minted. */
|
|
20
|
+
export interface PoolKey {
|
|
21
|
+
/** Its id: revoked by it. */
|
|
22
|
+
id: string;
|
|
23
|
+
label?: string;
|
|
24
|
+
createdAt?: string;
|
|
25
|
+
/** When it can no longer be used. */
|
|
26
|
+
expiresAt?: string;
|
|
27
|
+
/** When a machine last enrolled with it. */
|
|
28
|
+
lastUsedAt?: string;
|
|
29
|
+
revokedAt?: string;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Where a machine enrols, said with a key as it is minted: `palai enroll --url <url> --key-file <file>`, with
|
|
33
|
+
* `--server-name <serverName>` when the door's certificate names another host, and `--ca-file <file>` holding
|
|
34
|
+
* caCertificate when the door's certificate is not publicly trusted.
|
|
35
|
+
*/
|
|
36
|
+
export interface PoolKeyEnroll {
|
|
37
|
+
url: string;
|
|
38
|
+
serverName?: string;
|
|
39
|
+
/** The CA the door's certificate is signed by (PEM): saved to a file, palai enroll --ca-file. */
|
|
40
|
+
caCertificate?: string;
|
|
41
|
+
}
|
|
42
|
+
/** A key as it is minted: the key, said once, and where a machine enrols with it. */
|
|
43
|
+
export interface PoolKeyMinted extends PoolKey {
|
|
44
|
+
key: string;
|
|
45
|
+
/** The enrolment address: palai enroll --url. */
|
|
46
|
+
enrollUrl?: string;
|
|
47
|
+
enroll?: PoolKeyEnroll;
|
|
48
|
+
}
|
|
49
|
+
/** A machine of a pool: what it takes and holds, and whether it takes a new session. */
|
|
50
|
+
export interface PoolMachine {
|
|
51
|
+
/** Its id: cordoned, resumed and deleted by it (ai.machines). */
|
|
52
|
+
id: string;
|
|
53
|
+
/** online, offline, or cordoned (it takes no new session). */
|
|
54
|
+
state: 'online' | 'offline' | 'cordoned' | (string & {});
|
|
55
|
+
/** How many sessions it takes at once (palai enroll --capacity), and holds now. */
|
|
56
|
+
capacity: number;
|
|
57
|
+
used: number;
|
|
58
|
+
/** Its label, as it enrolled. */
|
|
59
|
+
label?: string;
|
|
60
|
+
os?: string;
|
|
61
|
+
arch?: string;
|
|
62
|
+
/** Since when it holds none; null: it holds one. */
|
|
63
|
+
idleSince: string | null;
|
|
64
|
+
lastSeenAt: string | null;
|
|
65
|
+
registeredAt: string | null;
|
|
66
|
+
}
|
|
67
|
+
/** A pool's state: what the project's own scaling loop reads to add a machine or take one away. */
|
|
68
|
+
export interface PoolState {
|
|
69
|
+
pool: {
|
|
70
|
+
id: string;
|
|
71
|
+
name: string;
|
|
72
|
+
os: string;
|
|
73
|
+
arch: string;
|
|
74
|
+
};
|
|
75
|
+
capacityTotal: number;
|
|
76
|
+
capacityUsed: number;
|
|
77
|
+
/** How many sessions wait for a place, and since when the oldest waits (null: none waits). */
|
|
78
|
+
waiting: number;
|
|
79
|
+
oldestWaitingSince: string | null;
|
|
80
|
+
machines: PoolMachine[];
|
|
81
|
+
}
|
|
82
|
+
/** A pool's enrolment keys: a machine enrols with one once (`palai enroll --url <enrollUrl> --key-file <file> --capacity <n>`). */
|
|
83
|
+
export interface PoolKeys {
|
|
84
|
+
/**
|
|
85
|
+
* Mints one, said once — here, never again — with where a machine enrols (enrollUrl, enroll): saved to a file on the
|
|
86
|
+
* machine, `palai enroll --url <enrollUrl> --key-file <file> --capacity <n>` (and --server-name, --ca-file when enroll
|
|
87
|
+
* says them) — never on a command line, where any process on the machine could read it; n is how many sessions the
|
|
88
|
+
* machine runs at once (1 or more, default 1). A machine enrolled with it serves the project's sessions once whoever
|
|
89
|
+
* minted it is gone: it is never minted for an environment's token.
|
|
90
|
+
*/
|
|
91
|
+
create(pool: string, options?: {
|
|
92
|
+
label?: string;
|
|
93
|
+
signal?: AbortSignal;
|
|
94
|
+
}): Promise<PoolKeyMinted>;
|
|
95
|
+
/** Its keys, none said. */
|
|
96
|
+
list(pool: string, options?: {
|
|
97
|
+
signal?: AbortSignal;
|
|
98
|
+
}): Promise<PoolKey[]>;
|
|
99
|
+
/** No machine enrols with it any more. */
|
|
100
|
+
revoke(keyId: string, options?: {
|
|
101
|
+
signal?: AbortSignal;
|
|
102
|
+
}): Promise<void>;
|
|
103
|
+
}
|
|
104
|
+
/** The project's runner pools: machines of its own its chats' workspaces run on, managed — and scaled — by the project. */
|
|
105
|
+
export interface Pools {
|
|
106
|
+
/** Makes one, of one type: its machines' os (linux, macos) and arch (amd64, arm64). A name taken already: 409 pool_exists. */
|
|
107
|
+
create(pool: {
|
|
108
|
+
name: string;
|
|
109
|
+
os: 'linux' | 'macos';
|
|
110
|
+
arch: 'amd64' | 'arm64';
|
|
111
|
+
signal?: AbortSignal;
|
|
112
|
+
}): Promise<Pool>;
|
|
113
|
+
/** Every pool of the project's, with what its machines hold and how many sessions wait. */
|
|
114
|
+
list(options?: {
|
|
115
|
+
signal?: AbortSignal;
|
|
116
|
+
}): Promise<Pool[]>;
|
|
117
|
+
/**
|
|
118
|
+
* Deletes a pool with no machine left in it, by its id or its name: cordon each machine, delete it once it holds no
|
|
119
|
+
* session (ai.machines.delete), then the pool. One with machines: 409 pool_not_empty.
|
|
120
|
+
*/
|
|
121
|
+
delete(pool: string, options?: {
|
|
122
|
+
signal?: AbortSignal;
|
|
123
|
+
}): Promise<void>;
|
|
124
|
+
/** What its owner's scaling loop reads: its machines, the sessions they take and hold, and how many wait. */
|
|
125
|
+
state(pool: string, options?: {
|
|
126
|
+
signal?: AbortSignal;
|
|
127
|
+
}): Promise<PoolState>;
|
|
128
|
+
readonly keys: PoolKeys;
|
|
129
|
+
}
|
|
130
|
+
/** The machines of the project's pools, by their id (a pool's state names them). */
|
|
131
|
+
export interface PoolMachines {
|
|
132
|
+
/** It takes no new session; the sessions it holds go on. */
|
|
133
|
+
cordon(id: string, options?: {
|
|
134
|
+
signal?: AbortSignal;
|
|
135
|
+
}): Promise<void>;
|
|
136
|
+
/** A cordoned machine takes sessions again. */
|
|
137
|
+
resume(id: string, options?: {
|
|
138
|
+
signal?: AbortSignal;
|
|
139
|
+
}): Promise<void>;
|
|
140
|
+
/** A cordoned machine that holds no session leaves its pool, its palai agent refused from then (409 machine_not_cordoned, machine_busy). */
|
|
141
|
+
delete(id: string, options?: {
|
|
142
|
+
signal?: AbortSignal;
|
|
143
|
+
}): Promise<void>;
|
|
144
|
+
}
|
|
145
|
+
/** One of the project's variables: its name, never its value. */
|
|
146
|
+
export interface EnvVariable {
|
|
147
|
+
key: string;
|
|
148
|
+
/** Whether it is a secret (said so in the list); every value is masked in a transcript either way. */
|
|
149
|
+
secret: boolean;
|
|
150
|
+
updatedAt: string;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* The project's variables: every command of every session of its agents begun from now has them — on the platform's
|
|
154
|
+
* Linux machines and on its own pools — beside an agent's own (its definition's env), masked in a transcript. A value
|
|
155
|
+
* is sealed where the sessions run: never answered, never logged.
|
|
156
|
+
*/
|
|
157
|
+
export interface EnvVariables {
|
|
158
|
+
/** Sets one, or sets it anew: a value of 1 byte to 32 KiB, no NUL; a secret unless secret: false. */
|
|
159
|
+
set(key: string, value: string, options?: {
|
|
160
|
+
secret?: boolean;
|
|
161
|
+
signal?: AbortSignal;
|
|
162
|
+
}): Promise<EnvVariable>;
|
|
163
|
+
/** Sessions begun from now no longer have it. */
|
|
164
|
+
unset(key: string, options?: {
|
|
165
|
+
signal?: AbortSignal;
|
|
166
|
+
}): Promise<void>;
|
|
167
|
+
/** Their names, sorted — whether each is a secret, and when it was set: never a value. */
|
|
168
|
+
list(options?: {
|
|
169
|
+
signal?: AbortSignal;
|
|
170
|
+
}): Promise<EnvVariable[]>;
|
|
171
|
+
}
|
|
172
|
+
export declare function poolsOf(module: Module): {
|
|
173
|
+
pools: Pools;
|
|
174
|
+
machines: PoolMachines;
|
|
175
|
+
env: EnvVariables;
|
|
176
|
+
};
|
|
177
|
+
export {};
|
package/types/ai/src/tools.d.ts
CHANGED
|
@@ -47,6 +47,30 @@ export interface ToolContext extends ChatContext {
|
|
|
47
47
|
runId: string;
|
|
48
48
|
/** The subagent that made the call, by its name; null: the agent itself. */
|
|
49
49
|
subagent: string | null;
|
|
50
|
+
/**
|
|
51
|
+
* The chat's workspace as the session last wrote it, its writes flushed before the call — absent when the chat
|
|
52
|
+
* works in none. Read a file of it at that tree (chats.workspace.file(chatId, path, { manifest: manifestId })); a
|
|
53
|
+
* tool that writes the workspace (chats.workspace.write) answers the tree its writes left with ai.answer(output, {
|
|
54
|
+
* workspaceTree }), and the agent's next command sees it.
|
|
55
|
+
*/
|
|
56
|
+
workspace?: ToolWorkspace;
|
|
57
|
+
}
|
|
58
|
+
/** The tree of a chat's workspace a tool is called at: what the session had written, flushed before the call. */
|
|
59
|
+
export interface ToolWorkspace {
|
|
60
|
+
/** The chat whose workspace it is. */
|
|
61
|
+
chatId: string;
|
|
62
|
+
/** The tree: a file of it is read by it (chats.workspace.file's manifest). */
|
|
63
|
+
manifestId?: string;
|
|
64
|
+
/** Its place in the workspace's history. */
|
|
65
|
+
seq?: number;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* The tree a tool's writes left a chat's workspace at — what chats.workspace.write answered ({ manifestId, seq }),
|
|
69
|
+
* either or both: the session's machine takes it before the agent's next command.
|
|
70
|
+
*/
|
|
71
|
+
export interface WorkspaceTree {
|
|
72
|
+
manifestId?: string;
|
|
73
|
+
seq?: number;
|
|
50
74
|
}
|
|
51
75
|
/** The message that opened a turn, as the backend that defines its agent is told of it. */
|
|
52
76
|
export interface TurnMessage {
|
|
@@ -93,7 +117,7 @@ export interface BackendToolOptions<S extends StandardSchema> {
|
|
|
93
117
|
* takes longer returns ai.deferred() at once — a chat's call waits, and the
|
|
94
118
|
* project's server answers it later with chats.answer(ctx.chatId, ctx.callId, output).
|
|
95
119
|
*/
|
|
96
|
-
run(input: Infer<S>, ctx: ToolContext): ToolResult | DeferredAnswer | Promise<ToolResult | DeferredAnswer>;
|
|
120
|
+
run(input: Infer<S>, ctx: ToolContext): ToolResult | DeferredAnswer | ToolReply | Promise<ToolResult | DeferredAnswer | ToolReply>;
|
|
97
121
|
/** Every call waits for a person's yes (a member of the chat, or the server). */
|
|
98
122
|
approval?: boolean;
|
|
99
123
|
/** The project's machine it runs on (default backend). */
|
|
@@ -111,14 +135,20 @@ export interface BackendTool<S extends StandardSchema = StandardSchema> {
|
|
|
111
135
|
/** The run, its input checked first: what the framework answers the platform's call with — an answer, or one to come (deferred). */
|
|
112
136
|
call(input: unknown, ctx: ToolContext): Promise<ToolAnswer>;
|
|
113
137
|
}
|
|
114
|
-
/** A backend tool's answer as the platform takes it: now (output), or later — the project's server gives it (chats.answer). */
|
|
138
|
+
/** A backend tool's answer as the platform takes it: now (output, and the tree its writes left the workspace at), or later — the project's server gives it (chats.answer). */
|
|
115
139
|
export type ToolAnswer = {
|
|
116
140
|
output: ToolContent[];
|
|
117
141
|
is_error: boolean;
|
|
142
|
+
workspace_tree?: WireWorkspaceTree;
|
|
118
143
|
} | {
|
|
119
144
|
deferred: true;
|
|
120
145
|
expires_in_seconds?: number;
|
|
121
146
|
};
|
|
147
|
+
/** A workspace's tree as the platform takes it in a tool's answer. */
|
|
148
|
+
export type WireWorkspaceTree = {
|
|
149
|
+
manifest_id?: string;
|
|
150
|
+
seq?: number;
|
|
151
|
+
};
|
|
122
152
|
declare const DEFERRED: unique symbol;
|
|
123
153
|
/** What a backend tool's run returns when its answer comes later: ai.deferred(). */
|
|
124
154
|
export interface DeferredAnswer {
|
|
@@ -136,6 +166,23 @@ export interface DeferredAnswer {
|
|
|
136
166
|
export declare function deferred(options?: {
|
|
137
167
|
expiresInSeconds?: number;
|
|
138
168
|
}): DeferredAnswer;
|
|
169
|
+
declare const REPLY: unique symbol;
|
|
170
|
+
/** What a backend tool's run returns with what it says beside its output: ai.answer(output, { workspaceTree }). */
|
|
171
|
+
export interface ToolReply {
|
|
172
|
+
readonly [REPLY]: true;
|
|
173
|
+
readonly output: ToolResult;
|
|
174
|
+
readonly workspaceTree?: WorkspaceTree;
|
|
175
|
+
}
|
|
176
|
+
/** The tree a tool says its writes left, as the platform takes it — refused here when the platform would drop it. */
|
|
177
|
+
export declare function workspaceTreeOf(t: unknown, what: string): WireWorkspaceTree;
|
|
178
|
+
/**
|
|
179
|
+
* A backend tool's output with the tree its writes left the chat's workspace at (chats.workspace.write's answer):
|
|
180
|
+
* the session's machine takes that tree before the agent's next command, so the agent sees what the tool wrote. A
|
|
181
|
+
* tool that wrote and then failed says it with its ToolError (new ToolError(message, { workspaceTree })).
|
|
182
|
+
*/
|
|
183
|
+
export declare function answer(output: ToolResult, options: {
|
|
184
|
+
workspaceTree: WorkspaceTree;
|
|
185
|
+
}): ToolReply;
|
|
139
186
|
export interface ClientToolOptions<S extends StandardSchema> {
|
|
140
187
|
name: string;
|
|
141
188
|
description: string;
|
|
@@ -252,6 +299,15 @@ export interface AgentDefinitionInput {
|
|
|
252
299
|
thinking?: Thinking;
|
|
253
300
|
/** The language of the person the turn works for, a BCP 47 tag (tr, en-GB): the model writes to them in it on every step, and so do its subagents. */
|
|
254
301
|
language?: string;
|
|
302
|
+
/**
|
|
303
|
+
* The agent's own variables, name → value (64 at most; a name upper-case letters, digits and _, a letter first, not
|
|
304
|
+
* PALAI_…; a value 32 KiB at most): every command of its sessions has them, on every pool, beside the project's
|
|
305
|
+
* (ai.env.set), masked in a transcript. A value is never read back — a definition read says each name with '' — and a
|
|
306
|
+
* name written with '' keeps the value it has.
|
|
307
|
+
*/
|
|
308
|
+
env?: Record<string, string>;
|
|
309
|
+
/** A shell script each of its sessions runs once at its start, before the agent's first command, on every pool (64 KiB at most). */
|
|
310
|
+
setup?: string;
|
|
255
311
|
/**
|
|
256
312
|
* The shape of its one-shot answers (ai.generate({ agent, prompt })): a zod (valibot, arktype) object schema, or
|
|
257
313
|
* ai.schema(name, schema) — checked as generate's schema is, here, when the definition is written. A chat's turns
|
|
@@ -327,9 +383,17 @@ export interface DeclaredAI {
|
|
|
327
383
|
* may name what the chat is not to read); the whole of it is in the app's log.
|
|
328
384
|
*/
|
|
329
385
|
export declare class ToolError extends Error {
|
|
330
|
-
|
|
386
|
+
/** The tree the tool's writes left the chat's workspace at before it failed: what it wrote, the agent sees all the same. */
|
|
387
|
+
readonly workspaceTree?: WorkspaceTree;
|
|
388
|
+
constructor(message: string, options?: {
|
|
389
|
+
workspaceTree?: WorkspaceTree;
|
|
390
|
+
});
|
|
331
391
|
}
|
|
332
392
|
export declare const AGENT_NAME: RegExp;
|
|
393
|
+
export declare const POOL_REF: RegExp;
|
|
394
|
+
export declare const LABEL_RULE = "128 bytes at most, no control, format (bidi, zero-width) or line-separator character";
|
|
395
|
+
/** Whether a label is one the module takes: 128 bytes at most, shown as it was written. */
|
|
396
|
+
export declare function shownAsWritten(label: unknown): label is string;
|
|
333
397
|
/** The input's JSON Schema: an object, written out (no references), as a provider takes a tool's parameters. */
|
|
334
398
|
export declare function parametersOf(schema: StandardSchema | undefined, what: string): Record<string, unknown>;
|
|
335
399
|
export declare function backendTool<S extends StandardSchema>(o: BackendToolOptions<S>): BackendTool<S>;
|
|
@@ -375,6 +439,10 @@ export declare function backendAgentOf(v: unknown): {
|
|
|
375
439
|
export declare function toolRef(t: Tool, what: string): ToolRef;
|
|
376
440
|
/** The most tool calls a turn or a one-shot answer makes: the engine's own bound. */
|
|
377
441
|
export declare const MAX_TOOL_CALLS = 10000;
|
|
442
|
+
export declare const ENV_KEY: RegExp;
|
|
443
|
+
export declare const MAX_ENV_VALUE_BYTES: number;
|
|
444
|
+
/** Whether a name is one a variable may have: never one of PALAI_…, the engine's own. */
|
|
445
|
+
export declare function envKeyOk(key: unknown): key is string;
|
|
378
446
|
/** The shape of an agent's one-shot answers as the module takes it: the JSON Schema generate's schema is sent as. */
|
|
379
447
|
export declare function outputOf(v: StandardSchema | PreparedOutput, what: string): Record<string, unknown>;
|
|
380
448
|
/** A definition's bound on its tool calls, refused here as the module would refuse it. */
|
package/dist/chunks/XLZYPS2V.js
DELETED
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
/*! palbase 0.43.2 — Palbase SDK License (see LICENSE) */
|
|
2
|
-
import{a as M,c as ye,d as be,e as we}from"./5AFQHJYE.js";import{a as ke}from"./RLFOMLA6.js";import{a as ge}from"./7L3EJBD5.js";import{a as fe,b as me,c as he}from"./X6P5WU56.js";import{b as $,d as pe}from"./OLMU3ODF.js";async function*Te(e,t={}){let a=e.getReader(),o=new TextDecoder,i="",l="",u=[],h,r=()=>{a.cancel().catch(()=>{})};t.signal?.addEventListener("abort",r,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:s}=await a.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=o.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 a.cancel()}catch{}}}function ee(e,t){let a=e.slice(t);return a.startsWith(" ")?a.slice(1):a}var ct=/\s/;function F(e,t){for(;t<e.length&&ct.test(e[t]);)t++;return t}function Se(e,t){let a="";for(let o=t+1;o<e.length;o++){let i=e[o];if(i==='"')return{value:a,complete:!0,empty:!1,at:o+1};if(i!=="\\"){a+=i;continue}let l=e[o+1];if(l===void 0)break;if(l==="u"){let u=e.slice(o+2,o+6);if(u.length<4)break;a+=String.fromCharCode(Number.parseInt(u,16)),o+=5;continue}a+={n:`
|
|
7
|
-
`,t:" ",r:"\r",b:"\b",f:"\f"}[l]??l,o++}return{value:a,complete:!1,empty:!1,at:e.length}}function te(e,t){t=F(e,t);let a=e[t];if(a===void 0)return{value:void 0,complete:!1,empty:!0,at:t};if(a==='"')return Se(e,t);if(a==="{")return lt(e,t);if(a==="[")return ut(e,t);let o=t;for(;o<e.length&&/[-+0-9.A-Za-z]/.test(e[o]);)o++;if(o===e.length)return{value:void 0,complete:!1,empty:!0,at:o};try{return{value:JSON.parse(e.slice(t,o)),complete:!0,empty:!1,at:o}}catch{return{value:void 0,complete:!1,empty:!0,at:e.length}}}function lt(e,t){let a={},o=t+1;for(;;){if(o=F(e,o),e[o]==="}")return{value:a,complete:!0,empty:!1,at:o+1};if(e[o]===","){o++;continue}if(e[o]!=='"')return{value:a,complete:!1,empty:!1,at:e.length};let i=Se(e,o);if(!i.complete)return{value:a,complete:!1,empty:!1,at:e.length};if(o=F(e,i.at),e[o]!==":")return{value:a,complete:!1,empty:!1,at:e.length};let l=te(e,o+1);if(l.empty||Object.defineProperty(a,i.value,{value:l.value,enumerable:!0,writable:!0,configurable:!0}),!l.complete)return{value:a,complete:!1,empty:!1,at:e.length};o=l.at}}function ut(e,t){let a=[],o=t+1;for(;;){if(o=F(e,o),e[o]==="]")return{value:a,complete:!0,empty:!1,at:o+1};if(e[o]===","){o++;continue}if(o>=e.length)return{value:a,complete:!1,empty:!1,at:o};let i=te(e,o);if(i.empty||a.push(i.value),!i.complete)return{value:a,complete:!1,empty:!1,at:e.length};o=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,a){super(`${t}: ${a}`),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"]),xe=12,Ae=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 a=e?.["~standard"];if(!a||a.version!==1||typeof a.validate!="function")throw new b(t,"not a Standard Schema: pass a zod (4.2+), valibot or arktype schema");if(!a.jsonSchema||typeof a.jsonSchema.output!="function")throw new b(t,`${a.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let o;try{o=a.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(o.type!=="object")throw new b(t,"the answer is an object: wrap the value in z.object({ \u2026 })");let l=re(o,t,0,{properties:0});return{name:t,json:l,async check(u){let h=await a.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,a,o){if(a>xe)throw new b(t,`nests deeper than ${xe} 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(o.properties+=h.length,o.properties>Ae)throw new b(t,`the schema has more than ${Ae} 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}`,a+1,o)}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}[]`,a+1,o)}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 K(e){return Array.isArray(e)&&e.length>0&&e.every(ve)?e.map(_e):ve(e)?[_e(e)]:e==null?[{type:"text",text:""}]:typeof e=="string"?[{type:"text",text:e}]:[{type:"text",text:JSON.stringify(e)??String(e)}]}function ve(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 _e(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 a="bytes"in e?e.bytes:e.data;return{type:"image",media_type:t,data:typeof a=="string"?a:bt(a)}}function bt(e){let t="";for(let a=0;a<e.length;a+=32768)t+=String.fromCharCode(...e.subarray(a,a+32768));return btoa(t)}var Oe=Symbol.for("palbase.ai.deferred"),Re=60,Ce=86400;function Me(e={}){let t=e?.expiresInSeconds;if(t!==void 0&&(!Number.isInteger(t)||t<Re||t>Ce))throw new TypeError(`ai.deferred: expiresInSeconds is how long the call waits for its answer, ${Re} to ${Ce} 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,a,o,i=(l,u)=>l===u){let l=e.get(a);l===void 0?e.set(a,o):i(l,o)||B().twice.add(`${t}:${a}`)}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 a=e?.["~standard"];if(!a||a.version!==1||typeof a.validate!="function")throw new TypeError(`${t}: input is a Standard Schema \u2014 a zod (4.2+), valibot or arktype object schema`);if(!a.jsonSchema||typeof a.jsonSchema.output!="function")throw new TypeError(`${t}: ${a.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let o;try{o=a.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(o.type!=="object")throw new TypeError(`${t}: a tool takes an object \u2014 wrap the input in z.object({ \u2026 })`);let i=JSON.stringify(o);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}=o;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 a=Be(e.input,t),o=e.input["~standard"],i=e.run,l={source:"backend",name:e.name,description:e.description,input:e.input,parameters:a,approval:e.approval===!0,...e.machine!==void 0?{machine:e.machine}:{},async call(h,r){let n=await o.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:K(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 a=Object.freeze({source:"client",name:e.name,description:e.description,parameters:Be(e.input,t),approval:e.approval===!0}),o=B();return o.tools.has(a.name)&&o.twice.add(`tool:${a.name}`),X(o.clientTools,"tool",a.name,a,(i,l)=>JSON.stringify(i)===JSON.stringify(l)),a}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 a=t.token,o={kind:"repo",name:t.name,repository:t.repository,defaultBranch:t.defaultBranch??"main",...t.machine!==void 0?{machine:t.machine}:{},async token(i){return await a(i)}};return X(B().repos,"repo",t.name,o),o}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,a={}){let o=`ai.agent(${JSON.stringify(e??null)})`;if(typeof e!="string"||!v.test(e))throw new TypeError(`${o}: name is lowercase letters, digits, _ and -, starting with a letter, at most 64`);if(typeof t!="function")throw new TypeError(`${o}: the agent is a function of the turn's context that returns its definition`);let i=a??{};if(i.machine!==void 0&&!v.test(i.machine))throw new TypeError(`${o}: machine is the name of one of the project's machines`);let l=i.description===void 0?void 0:Je(i.description,o),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,`${o} for chat ${h.chatId}`);if(n.backend!==void 0)throw new TypeError(`${o}: 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 W(e){return typeof e=="object"&&e!==null&&e.kind==="agent"?e:void 0}function xt(e){return[...e.tools??[],...(e.subagents??[]).flatMap(a=>a.tools??[])].filter(a=>a.source==="backend")}var Ee=["web.search","web.fetch","workspace.fetch_archive"];function V(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 a=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,...a,...e.machine!==void 0?{machine:e.machine}:{}};case"client":return{source:"client",name:e.name,description:e.description,parameters:e.parameters,...a};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,...a};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,...a,...e.only!==void 0?{only:[...e.only]}:{}};case"platform":{let o=Object.keys(e).filter(i=>i!=="source"&&i!=="name");if(typeof e.name!="string"||!Ee.includes(e.name))throw new TypeError(`${t}: { source: 'platform', name } names one of the platform's tools: ${Ee.join(", ")}`);if(o.length>0)throw new TypeError(`${t}: the platform's ${e.name} is given by its name alone (not ${o.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 Pe=1e4,Ie=["none","minimal","low","medium","high","xhigh","max"],At=1e8,vt=/^[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8})*$/,$e=1024;function Je(e,t){if(typeof e!="string"||e.trim()===""||e.length>$e)throw new TypeError(`${t}: description says what the agent is for, in a sentence or two (${$e} characters at most)`);return e}function _t(e,t){let a=e?.prepared;if(a!==void 0&&typeof a=="object"&&a!==null&&typeof a.json=="object")return a.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>Pe)throw new TypeError(`${t}: maxToolCalls is a whole number, 1 to ${Pe} (got ${String(e)})`);return e}function oe(e,t){let a={};if(e.effort!==void 0){if(typeof e.effort!="string"||!Ie.includes(e.effort))throw new TypeError(`${t}: effort is one of ${Ie.join(", ")} \u2014 which a model takes is its catalogue entry's (ai.models())`);a.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)})`);a.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`);a.thinking=e.thinking}return a}function Z(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a definition is { description, instructions, model, tools, subagents, advisor, maxToolCalls, effort, contextWindow, thinking, language, output }`);let a={};if(e.description!==void 0&&(a.description=Je(e.description,t)),e.instructions!==void 0&&(a.instructions=e.instructions),e.model!==void 0&&(a.model=e.model),e.maxToolCalls!==void 0&&(a.max_tool_calls=ae(e.maxToolCalls,t)),Object.assign(a,oe(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)`);a.language=e.language}if(e.output!==void 0&&(a.output=_t(e.output,t)),e.tools!==void 0&&(a.tools=e.tools.map(o=>V(o,t))),e.subagents!==void 0){for(let o of e.subagents){let i=(o?.tools??[]).find(l=>l?.source==="platform");if(i)throw new TypeError(`${t} subagent ${o.name}: the platform's ${i.name} is the agent's tool \u2014 its subagents work with the agent's`)}a.subagents=e.subagents.map(o=>({name:o.name,description:o.description,...o.instructions!==void 0?{instructions:o.instructions}:{},...o.model!==void 0?{model:o.model}:{},...o.required!==void 0?{required:o.required}:{},...oe(o,`${t} subagent ${o.name}`),...o.tools!==void 0?{tools:o.tools.map(i=>V(i,`${t} subagent ${o.name}`))}:{}}))}return e.advisor!==void 0&&(a.advisor=Rt(e.advisor,`${t} advisor`)),a}function Rt(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: an advisor is { model, instructions, effort, tools }`);let a={};if(e.model!==void 0&&(a.model=e.model),e.instructions!==void 0){if(typeof e.instructions!="string"||new TextEncoder().encode(e.instructions).length>64*1024)throw new TypeError(`${t}: instructions is text, 64 KiB at most`);a.instructions=e.instructions}let{effort:o}=oe({effort:e.effort},t);if(o!==void 0&&(a.effort=o),e.tools!==void 0){if(!Array.isArray(e.tools)||e.tools.length>32)throw new TypeError(`${t}: tools is 32 MCP servers at most`);a.tools=e.tools.map(i=>{if(i?.source!=="mcp")throw new TypeError(`${t}: the advisor reads; its tools are MCP servers' ({ source: 'mcp', name }), whose tools it is given when they say they only read`);if(i.approval===!0)throw new TypeError(`${t}: nothing the advisor reads waits for a person (approval)`);return V(i,t)})}return a}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 a={approve:e};return t.reason!==void 0&&(a.reason=t.reason),t.as!==void 0&&(a.as=t.as),a}var Ct=/^[a-z][a-z0-9-]{1,62}$/,We=4,qe=8;function Et(e){let t={},a=(o,i)=>{if(typeof o?.bucket!="string"||!Ct.test(o.bucket))throw new TypeError(`chats.send: ${i}'s bucket is one of the project's buckets, by its name`);if(typeof o.path!="string"||o.path===""||o.path.length>1024)throw new TypeError(`chats.send: ${i}'s path is its path in the bucket (1024 characters at most)`);return{bucket:o.bucket,path:o.path}};if(e.images!==void 0){if(!Array.isArray(e.images)||e.images.length>We)throw new TypeError(`chats.send: images are ${We} at most \u2014 as many as the model is shown at once`);t.images=e.images.map((o,i)=>a(o,`images[${i}]`))}if(e.files!==void 0){if(!Array.isArray(e.files)||e.files.length>qe)throw new TypeError(`chats.send: files are ${qe} at most`);t.files=e.files.map((o,i)=>{let l=a(o,`files[${i}]`);if(o.filename!==void 0){if(typeof o.filename!="string"||o.filename===""||o.filename.length>255)throw new TypeError(`chats.send: files[${i}].filename is its name in the workspace (255 characters at most)`);l.filename=o.filename}if(o.contentType!==void 0){if(typeof o.contentType!="string"||o.contentType===""||o.contentType.length>128)throw new TypeError(`chats.send: files[${i}].contentType is a media type (application/pdf)`);l.content_type=o.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 Pt=["speak","tell","know","instruct"];function Fe(){return"cm_"+crypto.randomUUID()}async function Y(e,t,a=4){for(let o=1;;o++)try{return await e()}catch(i){if(o>=a||!(i instanceof $)||i.status===429||t?.aborted)throw i;let l=he(i,o,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 ie(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}:{}}),It=/^[A-Za-z0-9-]{1,64}$/,Xe=16;function $t(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,a)=>{if(typeof t?.key!="string"||!It.test(t.key))throw new TypeError(`chats.create: workspace.trailers[${a}].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[${a}].value is one line of 512 bytes at most`);return{key:t.key,value:t.value}})}function Ot(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 Mt(e){return new Proxy(e,{get(t,a){let o=t[a];return typeof o=="function"?(...i)=>M(o.apply(t,i)):o}})}function He(e){let t=Mt(e),a={async create(r){let n=typeof r.agent=="string"||r.agent===void 0?r.agent:W(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:$t(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,Et(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,p={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(Ot)};return d.advisor&&(p.advisor={inputTokens:d.advisor.input_tokens,outputTokens:d.advisor.output_tokens,cacheReadTokens:d.advisor.cache_read_tokens,cacheWriteTokens:d.advisor.cache_write_tokens,costNanoUsd:d.advisor.cost_nano_usd,usd:d.advisor.usd,unpriced:d.advisor.unpriced}),p},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:K(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),ie((await t.setChatGoal({path:{chat_id:r},body:s,signal:n.signal})).data)},async get(r,n={}){return ie((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),ie((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(!Pt.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)}}},o={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"),W(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:a,agents:o,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 jt=/^pb_[a-z0-9]+_s/;function Ye(e){let t=globalThis;return t.process?.env?.[e]??t.Deno?.env?.get(e)}function de(){return"ai_"+crypto.randomUUID()}function ce(e){if(e.prepared)return e;let t=e;return{name:"answer",schema:t,prepared:j(t,"answer")}}var Qe=4,Bt=/^[a-z][a-z0-9-]{1,62}$/,et=["image/png","image/jpeg","image/webp","image/gif"],tt=5<<20,nt=6<<20;function at(e){let t="";for(let a=0;a<e.length;a+=32768)t+=String.fromCharCode(...e.subarray(a,a+32768));return btoa(t)}function Dt(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 Nt(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((a,o)=>{let i=a??{};if("bytes"in i||a instanceof Uint8Array)throw new TypeError(`images[${o}]: 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[${o}] is { bucket, path }, { url } or { mediaType, data }: one of them`);if(typeof i.mediaType!="string"||!et.includes(i.mediaType))throw new TypeError(`images[${o}].mediaType is the picture's type: ${et.join(", ")}`);let l=i.data instanceof Uint8Array?at(i.data):i.data,u=typeof l=="string"?Dt(l):-1;if(u<0)throw new TypeError(`images[${o}].data is the picture's bytes: base64, or a Uint8Array`);if(u===0||u>tt)throw new TypeError(`images[${o}] 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[${o}] is { bucket, path } or { url }, not both`);let l;try{l=new URL(i.url)}catch{throw new TypeError(`images[${o}].url is not an address: ${JSON.stringify(i.url.slice(0,80))}`)}if(l.protocol!=="https:"||i.url.length>2048)throw new TypeError(`images[${o}].url is an https address of 2048 characters at most`);return{url:i.url}}if(typeof i.bucket!="string"||!Bt.test(i.bucket)||typeof i.path!="string"||i.path==="")throw new TypeError(`images[${o}] is { bucket, path } \u2014 a file of the project's storage \u2014 { url } or { mediaType, data }`);return{bucket:i.bucket,path:i.path}})}var Ut=/^[a-z][a-z0-9_-]{0,63}(@[1-9][0-9]{0,8})?$/;function it(e){let t=typeof e=="string"?e:W(e)?.name;if(typeof t!="string"||!Ut.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={},a){if(e.prompt===void 0&&e.messages===void 0)throw new TypeError("ask a model something: prompt, or messages");let o={...t};if(e.agent!==void 0&&(o.agent=it(e.agent)),e.prompt!==void 0&&(o.input=e.prompt),e.messages!==void 0&&(o.messages=e.messages),e.instructions!==void 0&&(o.instructions=e.instructions),e.model!==void 0&&(o.model=e.model),e.metadata!==void 0&&(o.metadata=e.metadata),e.images!==void 0&&(o.images=Nt(e.images)),e.tools!==void 0&&(o.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=V(i,`tools[${l}]`);return u.source==="backend"&&u.machine===void 0&&a!==void 0&&(u.machine=a),u})),e.maxToolCalls!==void 0){if(!e.tools?.length)throw new TypeError("maxToolCalls bounds the calls of the tools given: give tools");o.max_tool_calls=ae(e.maxToolCalls,"ask")}return o}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 Gt(e){let t=Uint8Array.from(atob(e),i=>i.charCodeAt(0)),a=new DataView(t.buffer,t.byteOffset,t.byteLength),o=new Array(t.byteLength/4);for(let i=0;i<o.length;i++)o[i]=a.getFloat32(i*4,!0);return o}async function st(e){let t,a;return e instanceof Uint8Array?(t=e,a=ot(t)):typeof Blob<"u"&&e instanceof Blob?(t=new Uint8Array(await e.arrayBuffer()),a=e.type||ot(t)):(t=e.bytes,a=e.mediaType),{media_type:a,data:at(t)}}function ot(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 Lt(e){let t=e.url??Ye("PALBASE_URL"),a=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 a!="string"||!jt.test(a))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 o=me(pe({baseUrl:t,credentials:{secretKey:a},fetch:e.fetch}),e.retry??fe);return ge.client(o)}function Jt(e){return new Proxy({},{get:(t,a)=>e.ai[a]})}function zt(e={}){if(ke())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?Jt(e.server):Lt(e),a=e.resumeFor??12e4;async function o(c,g,m=de()){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=de(),N=()=>Date.now()+a,U=N();for(let G=0;;G++)try{if(x||(g===null?x=(await o({...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 Te(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+ye(A.text);if(O>w){let Q=A.offset>=w?A.text:we(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=be(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 le=g?L.then(f=>g.prepared.check(f.output)):Promise.reject(new TypeError("object is a schema stream's"));le.catch(()=>{});let ue=L.then(f=>f.text??k);return ue.catch(()=>{}),{id:G,response:L,text:ue,get textStream(){return Q()},get partialObjectStream(){return dt()},object:le,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 o(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=ce(c.schema),m={schema:g.prepared.json,schema_name:g.name};if(c.background){let w=(await o(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?ce(c.schema):void 0)},async start(c){let g=(await o(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"):ce(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(Gt(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":de()},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,zt as f};
|