@openartifactsai/server-sdk 0.0.0-stage → 0.23.0-rc.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/LICENSE +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/bin/frame-host.d.ts +2 -0
- package/bin/frame-host.js +47 -0
- package/package.json +124 -4
- package/src/child.d.ts +37 -0
- package/src/child.js +64 -0
- package/src/connectors/connectors.d.ts +101 -0
- package/src/connectors/connectors.js +256 -0
- package/src/connectors/daemon-connectors.d.ts +34 -0
- package/src/connectors/daemon-connectors.js +73 -0
- package/src/connectors/index.d.ts +7 -0
- package/src/connectors/index.js +7 -0
- package/src/connectors/mcp-client.d.ts +157 -0
- package/src/connectors/mcp-client.js +483 -0
- package/src/daemon.d.ts +119 -0
- package/src/daemon.js +301 -0
- package/src/frame/access.d.ts +69 -0
- package/src/frame/access.js +168 -0
- package/src/frame/client/comments.css +1 -0
- package/src/frame/client/comments.js +58 -0
- package/src/frame/client/imports.d.ts +6 -0
- package/src/frame/client/imports.js +112 -0
- package/src/frame/client/mcp-shell.js +345 -0
- package/src/frame/client/mcp.js +253 -0
- package/src/frame/client/runtime.js +1363 -0
- package/src/frame/client/sample.js +762 -0
- package/src/frame/client/shell.css +51 -0
- package/src/frame/client/shell.html +29 -0
- package/src/frame/client/shell.js +1417 -0
- package/src/frame/comments.d.ts +102 -0
- package/src/frame/comments.js +379 -0
- package/src/frame/core.d.ts +313 -0
- package/src/frame/core.js +1757 -0
- package/src/frame/db.d.ts +162 -0
- package/src/frame/db.js +604 -0
- package/src/frame/declaration.d.ts +30 -0
- package/src/frame/declaration.js +60 -0
- package/src/frame/env.d.ts +262 -0
- package/src/frame/env.js +13 -0
- package/src/frame/files.d.ts +130 -0
- package/src/frame/files.js +472 -0
- package/src/frame/index.d.ts +35 -0
- package/src/frame/index.js +33 -0
- package/src/frame/local.d.ts +126 -0
- package/src/frame/local.js +612 -0
- package/src/frame/mcp-relay.d.ts +79 -0
- package/src/frame/mcp-relay.js +191 -0
- package/src/frame/page-api.d.ts +48 -0
- package/src/frame/page-api.js +1 -0
- package/src/frame/page-comments.d.ts +109 -0
- package/src/frame/page-comments.js +1 -0
- package/src/frame/page-db.d.ts +88 -0
- package/src/frame/page-db.js +1 -0
- package/src/frame/page-imports.d.ts +2 -0
- package/src/frame/page-imports.js +2 -0
- package/src/frame/page-services.d.ts +124 -0
- package/src/frame/page-services.js +1 -0
- package/src/frame/page-values.d.ts +90 -0
- package/src/frame/page-values.js +1 -0
- package/src/frame/sample-relay.d.ts +42 -0
- package/src/frame/sample-relay.js +186 -0
- package/src/frame/snapshot-action.d.ts +18 -0
- package/src/frame/snapshot-action.js +82 -0
- package/src/frame/wire.d.ts +198 -0
- package/src/frame/wire.js +21 -0
- package/src/index.d.ts +17 -0
- package/src/index.js +17 -0
- package/src/lan.d.ts +75 -0
- package/src/lan.js +200 -0
- package/src/legacy-env.d.ts +7 -0
- package/src/legacy-env.js +14 -0
- package/src/serve.d.ts +375 -0
- package/src/serve.js +811 -0
- package/src/snapshot.d.ts +41 -0
- package/src/snapshot.js +224 -0
- package/src/type-package.d.ts +48 -0
- package/src/type-package.js +114 -0
- package/src/ws.d.ts +50 -0
- package/src/ws.js +203 -0
- package/src/zip.d.ts +197 -0
- package/src/zip.js +662 -0
|
@@ -0,0 +1,762 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
(() => {
|
|
3
|
+
// packages/protocol/src/sample.ts
|
|
4
|
+
var SAMPLE_MAX_PROMPT_BYTES = 262144;
|
|
5
|
+
var SAMPLE_MAX_TURNS = 1e3;
|
|
6
|
+
var SAMPLE_MAX_IMAGES = 4;
|
|
7
|
+
var SAMPLE_MAX_IMAGE_INPUT_BYTES = 20 * 1024 * 1024;
|
|
8
|
+
var SAMPLE_MAX_IMAGE_INPUT_SIDE = 1e4;
|
|
9
|
+
var SAMPLE_MAX_IMAGE_INPUT_PIXELS = 64e6;
|
|
10
|
+
var SAMPLE_IMAGE_TARGET_PIXELS = 12e5;
|
|
11
|
+
var SAMPLE_IMAGE_MAX_SIDE = 1568;
|
|
12
|
+
var SAMPLE_IMAGE_MAX_BYTES = 2 * 1024 * 1024;
|
|
13
|
+
var SAMPLE_IMAGES_MAX_TOTAL_BYTES = 5 * 1024 * 1024;
|
|
14
|
+
var SAMPLE_IMAGE_MEDIA_TYPES = Object.freeze(["image/jpeg", "image/png", "image/webp", "image/gif"]);
|
|
15
|
+
var SAMPLE_MAX_TOOLS = 16;
|
|
16
|
+
var SAMPLE_TOOL_NAME_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
|
|
17
|
+
var SAMPLE_MAX_TOOL_DESCRIPTION_BYTES = 1024;
|
|
18
|
+
var SAMPLE_MAX_TOOL_SCHEMA_BYTES = 4096;
|
|
19
|
+
var SAMPLE_MAX_TOOL_SCHEMA_DEPTH = 8;
|
|
20
|
+
var SAMPLE_MAX_TOOL_DEFINITIONS_BYTES = 32768;
|
|
21
|
+
var SAMPLE_MAX_TOOL_RESULT_BYTES = 32768;
|
|
22
|
+
var SAMPLE_TOOL_EXECUTE_MS = 15e4;
|
|
23
|
+
var SAMPLE_ACKED_WAIT_MS = 9e5;
|
|
24
|
+
var SAMPLE_MAX_RUNNING = 2;
|
|
25
|
+
var SAMPLE_MAX_WAITING = 4;
|
|
26
|
+
var SAMPLE_MAX_QUEUED_BEFORE_START = SAMPLE_MAX_RUNNING + SAMPLE_MAX_WAITING;
|
|
27
|
+
var SAMPLE_CACHE_DEFAULT_MS = 3e5;
|
|
28
|
+
var SAMPLE_CACHE_MAX_MS = 864e5;
|
|
29
|
+
var MODEL_TIERS = Object.freeze(["quick", "default", "complex"]);
|
|
30
|
+
var SAMPLE_EFFORTS = Object.freeze(["low", "medium", "high"]);
|
|
31
|
+
var MODEL_EFFORTS = Object.freeze(["low", "medium", "high", "xhigh", "max"]);
|
|
32
|
+
var SAMPLE_ERROR_CODES = Object.freeze([
|
|
33
|
+
/** The page's signal aborted. */
|
|
34
|
+
"cancelled",
|
|
35
|
+
/** A malformed call: nothing was sent. */
|
|
36
|
+
"invalid_request",
|
|
37
|
+
/** Over {@link SAMPLE_MAX_PROMPT_BYTES}, or the rounds outgrew what the model reads at once. */
|
|
38
|
+
"prompt_too_large",
|
|
39
|
+
/** The arguments could not be prepared (read like `invalid_request`). */
|
|
40
|
+
"transform_error",
|
|
41
|
+
/** Over {@link SAMPLE_MAX_QUEUED_BEFORE_START} calls waiting while the page side of `sample` loads. */
|
|
42
|
+
"queue_overflow",
|
|
43
|
+
/** The person has not allowed this artifact to use a model, or declined. */
|
|
44
|
+
"not_granted",
|
|
45
|
+
/** No model can be used for this person at all. */
|
|
46
|
+
"sampling_disabled",
|
|
47
|
+
/** The artifact no longer declares `sample`. */
|
|
48
|
+
"not_declared",
|
|
49
|
+
/** Granted, but this view cannot use it (a snapshot, a read-only view, no outer Shell on a site). */
|
|
50
|
+
"capability_disabled",
|
|
51
|
+
/** The method is not in the runtime serving this view. */
|
|
52
|
+
"capability_removed",
|
|
53
|
+
/** The view cannot send images, or the page does not declare them. */
|
|
54
|
+
"images_unavailable",
|
|
55
|
+
/** The source cannot run page tools. */
|
|
56
|
+
"tools_unavailable",
|
|
57
|
+
/** Too many calls at once or this hour, or the source's own rate limit. */
|
|
58
|
+
"rate_limited",
|
|
59
|
+
/** The source refused the key: the person must fix it in the model settings. */
|
|
60
|
+
"session_expired",
|
|
61
|
+
/** An image was of the wrong type, undecodable, or too large. */
|
|
62
|
+
"image_rejected",
|
|
63
|
+
/** The model declined; any partial answer is withdrawn (no `text`). */
|
|
64
|
+
"refused",
|
|
65
|
+
/** The model wrote no text. */
|
|
66
|
+
"empty_completion",
|
|
67
|
+
/** `json` only: the reply held no JSON value, or was cut short; `text` is the raw reply. */
|
|
68
|
+
"invalid_json",
|
|
69
|
+
/** Anything else: a service or connection failure, before or during the answer. */
|
|
70
|
+
"upstream_error"
|
|
71
|
+
]);
|
|
72
|
+
var SAMPLE_METHODS = Object.freeze({
|
|
73
|
+
sample: "sample",
|
|
74
|
+
toolResults: "toolResults",
|
|
75
|
+
cancelCall: "cancelCall",
|
|
76
|
+
imagesRefused: "imagesRefused",
|
|
77
|
+
state: "state",
|
|
78
|
+
request: "request",
|
|
79
|
+
manage: "manage"
|
|
80
|
+
});
|
|
81
|
+
var FRAME_SAMPLE_ROUTES = Object.freeze({
|
|
82
|
+
/** `POST` {@link FrameSampleRequest}: start a call; the answer is an NDJSON stream of {@link SampleStreamEvent}s. */
|
|
83
|
+
call: "/api/frame/sample",
|
|
84
|
+
/** `POST` {@link FrameSampleToolRequest}: hand back one round's tool results; answers `{ok: true}`. */
|
|
85
|
+
tool: "/api/frame/sample/tool",
|
|
86
|
+
/** `GET`: this view's {@link SampleLimits}. */
|
|
87
|
+
limits: "/api/frame/sample/limits",
|
|
88
|
+
/** `GET ?client=`: {@link FrameSampleState}, whether a call would be asked about; read only, never a dialog. */
|
|
89
|
+
state: "/api/frame/sample/state"
|
|
90
|
+
});
|
|
91
|
+
var MODEL_PROVIDER_KINDS = Object.freeze(["openai", "anthropic", "gemini"]);
|
|
92
|
+
var DEFAULT_MODEL_BASE_URLS = Object.freeze({
|
|
93
|
+
openai: "https://api.openai.com/v1",
|
|
94
|
+
anthropic: "https://api.anthropic.com",
|
|
95
|
+
gemini: "https://generativelanguage.googleapis.com"
|
|
96
|
+
});
|
|
97
|
+
var DEFAULT_ANTHROPIC_MODELS = Object.freeze({ quick: "claude-haiku-5-5", default: "claude-sonnet-5-5", complex: "claude-opus-5-5" });
|
|
98
|
+
var SAMPLE_LIBRARY_ROUTES = Object.freeze({
|
|
99
|
+
/** `GET` → {@link ModelsListResponse}. */
|
|
100
|
+
modelsList: "models.list",
|
|
101
|
+
/** `POST` {@link ModelsSetRequest}. */
|
|
102
|
+
modelsSet: "models.set",
|
|
103
|
+
/** `GET` → {@link ModelsCatalogResponse}. */
|
|
104
|
+
modelsCatalog: "models.catalog",
|
|
105
|
+
/** `POST` {@link ModelsRemoveRequest}. */
|
|
106
|
+
modelsRemove: "models.remove",
|
|
107
|
+
/** `POST` {@link ModelsTestRequest} → {@link ModelsTestResult}. */
|
|
108
|
+
modelsTest: "models.test",
|
|
109
|
+
/** `GET` → {@link GrantsListResponse}. */
|
|
110
|
+
grantsList: "grants.list",
|
|
111
|
+
/** `POST` {@link GrantsAnswerRequest}. */
|
|
112
|
+
grantsAnswer: "grants.answer",
|
|
113
|
+
/** `POST` {@link GrantsRevokeRequest}. */
|
|
114
|
+
grantsRevoke: "grants.revoke",
|
|
115
|
+
/** `GET` → {@link UsageSummaryResponse}. */
|
|
116
|
+
usageSummary: "usage.summary"
|
|
117
|
+
});
|
|
118
|
+
var utf8 = new TextEncoder();
|
|
119
|
+
var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
120
|
+
function sampleInputBytes(input) {
|
|
121
|
+
if (typeof input === "string") return utf8.encode(input).length;
|
|
122
|
+
if (!Array.isArray(input)) return 0;
|
|
123
|
+
let n = 0;
|
|
124
|
+
for (const turn of input) if (isRecord(turn) && typeof turn.content === "string") n += utf8.encode(turn.content).length;
|
|
125
|
+
return n;
|
|
126
|
+
}
|
|
127
|
+
function sampleInputProblem(input) {
|
|
128
|
+
if (typeof input === "string") return input.trim() ? null : "input is empty: pass the prompt as the first argument.";
|
|
129
|
+
if (!Array.isArray(input)) {
|
|
130
|
+
if (isRecord(input) && "prompt" in input) return "input: pass the prompt string itself as the first argument, not {prompt}.";
|
|
131
|
+
return "input: a prompt string, or an array of {role, content} turns.";
|
|
132
|
+
}
|
|
133
|
+
if (!input.length) return "input: the turn list is empty.";
|
|
134
|
+
if (input.length > SAMPLE_MAX_TURNS) return `input: at most ${SAMPLE_MAX_TURNS} turns.`;
|
|
135
|
+
for (let i = 0; i < input.length; i++) {
|
|
136
|
+
const turn = input[i];
|
|
137
|
+
if (!isRecord(turn)) return `input[${i}]: a {role, content} object.`;
|
|
138
|
+
if (turn.role !== "user" && turn.role !== "assistant") return `input[${i}].role: "user" or "assistant".`;
|
|
139
|
+
if (typeof turn.content !== "string" || !turn.content.trim()) return `input[${i}].content: a non-empty string.`;
|
|
140
|
+
}
|
|
141
|
+
if (input[0].role !== "user") return "input: the first turn must be a user turn (standing instructions go in a leading user turn).";
|
|
142
|
+
if (input[input.length - 1].role !== "user") return "input: the last turn must be a user turn.";
|
|
143
|
+
return null;
|
|
144
|
+
}
|
|
145
|
+
function depthOf(value, depth = 0) {
|
|
146
|
+
if (typeof value !== "object" || value === null) return depth;
|
|
147
|
+
let max = depth + 1;
|
|
148
|
+
for (const v of Object.values(value)) max = Math.max(max, depthOf(v, depth + 1));
|
|
149
|
+
return max;
|
|
150
|
+
}
|
|
151
|
+
function sampleToolsProblem(tools) {
|
|
152
|
+
if (!Array.isArray(tools)) return "tools: an array of {name, description, inputSchema?, execute} objects.";
|
|
153
|
+
if (tools.length > SAMPLE_MAX_TOOLS) return `tools: at most ${SAMPLE_MAX_TOOLS}.`;
|
|
154
|
+
const names = /* @__PURE__ */ new Set();
|
|
155
|
+
let total = 0;
|
|
156
|
+
for (let i = 0; i < tools.length; i++) {
|
|
157
|
+
const tool = tools[i];
|
|
158
|
+
if (!isRecord(tool)) return `tools[${i}]: a plain object.`;
|
|
159
|
+
if (typeof tool.name !== "string" || !SAMPLE_TOOL_NAME_PATTERN.test(tool.name)) return `tools[${i}].name: 1-128 of A-Z a-z 0-9 _ -.`;
|
|
160
|
+
if (names.has(tool.name)) return `tools[${i}].name: "${tool.name}" is already in the list.`;
|
|
161
|
+
names.add(tool.name);
|
|
162
|
+
if (typeof tool.description !== "string" || !tool.description.trim()) return `tools[${i}].description: required, what the tool does and returns.`;
|
|
163
|
+
const descriptionBytes = utf8.encode(tool.description).length;
|
|
164
|
+
if (descriptionBytes > SAMPLE_MAX_TOOL_DESCRIPTION_BYTES) return `tools[${i}].description: at most ${SAMPLE_MAX_TOOL_DESCRIPTION_BYTES} bytes.`;
|
|
165
|
+
let schemaBytes = 0;
|
|
166
|
+
if (tool.inputSchema !== void 0) {
|
|
167
|
+
if (!isRecord(tool.inputSchema) || tool.inputSchema.type !== "object") return `tools[${i}].inputSchema: a JSON Schema {type: "object", ...}.`;
|
|
168
|
+
let json;
|
|
169
|
+
try {
|
|
170
|
+
json = JSON.stringify(tool.inputSchema);
|
|
171
|
+
} catch {
|
|
172
|
+
return `tools[${i}].inputSchema: must be plain JSON.`;
|
|
173
|
+
}
|
|
174
|
+
schemaBytes = utf8.encode(json).length;
|
|
175
|
+
if (schemaBytes > SAMPLE_MAX_TOOL_SCHEMA_BYTES) return `tools[${i}].inputSchema: at most ${SAMPLE_MAX_TOOL_SCHEMA_BYTES} bytes.`;
|
|
176
|
+
if (depthOf(tool.inputSchema) > SAMPLE_MAX_TOOL_SCHEMA_DEPTH) return `tools[${i}].inputSchema: nested at most ${SAMPLE_MAX_TOOL_SCHEMA_DEPTH} deep.`;
|
|
177
|
+
}
|
|
178
|
+
total += utf8.encode(tool.name).length + descriptionBytes + schemaBytes;
|
|
179
|
+
}
|
|
180
|
+
if (total > SAMPLE_MAX_TOOL_DEFINITIONS_BYTES) return `tools: at most ${SAMPLE_MAX_TOOL_DEFINITIONS_BYTES} bytes of definitions together.`;
|
|
181
|
+
return null;
|
|
182
|
+
}
|
|
183
|
+
function normalizeSampleCache(cache, hasTools) {
|
|
184
|
+
if (hasTools) return cache === void 0 || cache === false ? { cache: false } : { problem: "cache: a call with tools is never cached; leave cache out." };
|
|
185
|
+
if (cache === void 0 || cache === true) return { cache: { gcTime: SAMPLE_CACHE_DEFAULT_MS } };
|
|
186
|
+
if (cache === false) return { cache: false };
|
|
187
|
+
if (!isRecord(cache)) return { problem: "cache: true, false, or {gcTime?, refresh?}." };
|
|
188
|
+
for (const key of Object.keys(cache)) if (key !== "gcTime" && key !== "refresh") return { problem: `cache.${key}: not an option (gcTime, refresh).` };
|
|
189
|
+
let gcTime = SAMPLE_CACHE_DEFAULT_MS;
|
|
190
|
+
if (cache.gcTime !== void 0) {
|
|
191
|
+
if (typeof cache.gcTime !== "number" || !Number.isFinite(cache.gcTime) || cache.gcTime <= 0) return { problem: "cache.gcTime: a finite number of ms above 0 (cache: false turns caching off)." };
|
|
192
|
+
gcTime = Math.min(cache.gcTime, SAMPLE_CACHE_MAX_MS);
|
|
193
|
+
}
|
|
194
|
+
if (cache.refresh !== void 0 && typeof cache.refresh !== "boolean") return { problem: "cache.refresh: true or false." };
|
|
195
|
+
return { cache: cache.refresh ? { gcTime, refresh: true } : { gcTime } };
|
|
196
|
+
}
|
|
197
|
+
function parseSampleJson(text) {
|
|
198
|
+
const attempt = (s) => {
|
|
199
|
+
try {
|
|
200
|
+
return { ok: true, value: JSON.parse(s) };
|
|
201
|
+
} catch {
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
};
|
|
205
|
+
const whole = text.trim();
|
|
206
|
+
if (!whole) return { ok: false };
|
|
207
|
+
const direct = attempt(whole);
|
|
208
|
+
if (direct) return direct;
|
|
209
|
+
const fences = [...whole.matchAll(/```[^\n`]*\n([\s\S]*?)```/g)];
|
|
210
|
+
if (fences.length === 1) {
|
|
211
|
+
const fenced = attempt(fences[0][1].trim());
|
|
212
|
+
if (fenced) return fenced;
|
|
213
|
+
}
|
|
214
|
+
if (fences.length > 1) return { ok: false };
|
|
215
|
+
const starts = [whole.indexOf("{"), whole.indexOf("[")].filter((i) => i >= 0);
|
|
216
|
+
const end = Math.max(whole.lastIndexOf("}"), whole.lastIndexOf("]"));
|
|
217
|
+
if (!starts.length || end < 0) return { ok: false };
|
|
218
|
+
const start = Math.min(...starts);
|
|
219
|
+
if (end <= start) return { ok: false };
|
|
220
|
+
return attempt(whole.slice(start, end + 1)) ?? { ok: false };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// packages/server-sdk/src/frame/client/sample-images.ts
|
|
224
|
+
var SAMPLE_IMAGE_STEPS = [1, 0.75, 0.5, 0.35];
|
|
225
|
+
var SAMPLE_IMAGE_PHOTO = [0.85, 0.72, 0.6];
|
|
226
|
+
var SAMPLE_IMAGE_KEEPABLE = /* @__PURE__ */ new Set(["image/jpeg", "image/png", "image/webp", "image/gif"]);
|
|
227
|
+
function imageByteBudget(count) {
|
|
228
|
+
return Math.min(SAMPLE_IMAGE_MAX_BYTES, Math.floor(SAMPLE_IMAGES_MAX_TOTAL_BYTES / Math.max(1, count)));
|
|
229
|
+
}
|
|
230
|
+
function imageInputProblem(width, height) {
|
|
231
|
+
if (!(width > 0 && height > 0)) return "it has no pixels";
|
|
232
|
+
if (Math.max(width, height) > SAMPLE_MAX_IMAGE_INPUT_SIDE) return `it is over ${SAMPLE_MAX_IMAGE_INPUT_SIDE} pixels on a side`;
|
|
233
|
+
if (width * height > SAMPLE_MAX_IMAGE_INPUT_PIXELS) return `it is over ${SAMPLE_MAX_IMAGE_INPUT_PIXELS} pixels`;
|
|
234
|
+
return null;
|
|
235
|
+
}
|
|
236
|
+
function imageScale(width, height) {
|
|
237
|
+
return Math.min(1, Math.sqrt(SAMPLE_IMAGE_TARGET_PIXELS / (width * height)), SAMPLE_IMAGE_MAX_SIDE / Math.max(width, height));
|
|
238
|
+
}
|
|
239
|
+
function scaledSize(width, height, scale) {
|
|
240
|
+
const w = Math.max(1, Math.min(SAMPLE_IMAGE_MAX_SIDE, Math.round(width * scale)));
|
|
241
|
+
const h = Math.max(1, Math.min(SAMPLE_IMAGE_MAX_SIDE, Math.round(height * scale)));
|
|
242
|
+
return { width: w, height: h };
|
|
243
|
+
}
|
|
244
|
+
function keepsAsPicked(type, bytes, width, height, budget, rotated) {
|
|
245
|
+
return SAMPLE_IMAGE_KEEPABLE.has(type) && imageScale(width, height) >= 1 && bytes <= budget && !rotated;
|
|
246
|
+
}
|
|
247
|
+
function imageAttempts(width, height, alpha) {
|
|
248
|
+
const first = imageScale(width, height);
|
|
249
|
+
const out = [];
|
|
250
|
+
const seen = /* @__PURE__ */ new Set();
|
|
251
|
+
for (const step of SAMPLE_IMAGE_STEPS) {
|
|
252
|
+
const size = scaledSize(width, height, first * step);
|
|
253
|
+
const key = `${size.width}x${size.height}`;
|
|
254
|
+
if (seen.has(key)) continue;
|
|
255
|
+
seen.add(key);
|
|
256
|
+
if (alpha) {
|
|
257
|
+
out.push({ ...size, type: "image/png" }, { ...size, type: "image/webp", quality: 0.9 }, { ...size, type: "image/webp", quality: 0.75 });
|
|
258
|
+
} else {
|
|
259
|
+
for (const quality of SAMPLE_IMAGE_PHOTO) out.push({ ...size, type: "image/jpeg", quality });
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
return out;
|
|
263
|
+
}
|
|
264
|
+
function jpegRotated(bytes) {
|
|
265
|
+
if (bytes.length < 4 || bytes[0] !== 255 || bytes[1] !== 216) return false;
|
|
266
|
+
let at = 2;
|
|
267
|
+
while (at + 4 <= bytes.length) {
|
|
268
|
+
if (bytes[at] !== 255) return false;
|
|
269
|
+
const marker = bytes[at + 1];
|
|
270
|
+
if (marker === 218 || marker === 217) return false;
|
|
271
|
+
const length = bytes[at + 2] << 8 | bytes[at + 3];
|
|
272
|
+
if (length < 2) return false;
|
|
273
|
+
if (marker === 225 && at + 10 <= bytes.length && String.fromCharCode(...bytes.subarray(at + 4, at + 8)) === "Exif") {
|
|
274
|
+
return exifOrientation(bytes.subarray(at + 10, Math.min(bytes.length, at + 2 + length))) > 1;
|
|
275
|
+
}
|
|
276
|
+
at += 2 + length;
|
|
277
|
+
}
|
|
278
|
+
return false;
|
|
279
|
+
}
|
|
280
|
+
function exifOrientation(tiff) {
|
|
281
|
+
if (tiff.length < 8) return 1;
|
|
282
|
+
const little = tiff[0] === 73 && tiff[1] === 73;
|
|
283
|
+
if (!little && !(tiff[0] === 77 && tiff[1] === 77)) return 1;
|
|
284
|
+
const u16 = (i) => i + 2 > tiff.length ? 0 : little ? tiff[i] | tiff[i + 1] << 8 : tiff[i] << 8 | tiff[i + 1];
|
|
285
|
+
const u32 = (i) => i + 4 > tiff.length ? 0 : little ? u16(i) + u16(i + 2) * 65536 : u16(i) * 65536 + u16(i + 2);
|
|
286
|
+
const dir = u32(4);
|
|
287
|
+
const entries = u16(dir);
|
|
288
|
+
for (let i = 0; i < entries; i++) {
|
|
289
|
+
const entry = dir + 2 + i * 12;
|
|
290
|
+
if (entry + 12 > tiff.length) return 1;
|
|
291
|
+
if (u16(entry) === 274) return u16(entry + 8) || 1;
|
|
292
|
+
}
|
|
293
|
+
return 1;
|
|
294
|
+
}
|
|
295
|
+
async function headOf(blob) {
|
|
296
|
+
return new Uint8Array(await blob.slice(0, 65536).arrayBuffer());
|
|
297
|
+
}
|
|
298
|
+
async function prepareImage(blob, budget, codec) {
|
|
299
|
+
const rotated = blob.type === "image/jpeg" && jpegRotated(await headOf(blob));
|
|
300
|
+
if (!codec) {
|
|
301
|
+
if (SAMPLE_IMAGE_KEEPABLE.has(blob.type) && blob.size <= budget && !rotated) return { blob, kept: true };
|
|
302
|
+
return { problem: `it is ${blob.size} bytes, over the ${budget} this call allows, and this page cannot downsize images` };
|
|
303
|
+
}
|
|
304
|
+
let image;
|
|
305
|
+
try {
|
|
306
|
+
image = await codec.decode(blob);
|
|
307
|
+
} catch (error) {
|
|
308
|
+
return { problem: `it could not be decoded (${error?.message ?? error})` };
|
|
309
|
+
}
|
|
310
|
+
try {
|
|
311
|
+
const tooBig = imageInputProblem(image.width, image.height);
|
|
312
|
+
if (tooBig) return { problem: tooBig };
|
|
313
|
+
if (keepsAsPicked(blob.type, blob.size, image.width, image.height, budget, rotated)) return { blob, kept: true };
|
|
314
|
+
let drawn = null;
|
|
315
|
+
let alpha = null;
|
|
316
|
+
const first = scaledSize(image.width, image.height, imageScale(image.width, image.height));
|
|
317
|
+
if (blob.type !== "image/jpeg") {
|
|
318
|
+
drawn = { key: `${first.width}x${first.height}`, image: await image.draw(first.width, first.height) };
|
|
319
|
+
alpha = drawn.image.alpha;
|
|
320
|
+
}
|
|
321
|
+
for (const attempt of imageAttempts(image.width, image.height, alpha === true)) {
|
|
322
|
+
const key = `${attempt.width}x${attempt.height}`;
|
|
323
|
+
if (!drawn || drawn.key !== key) drawn = { key, image: await image.draw(attempt.width, attempt.height) };
|
|
324
|
+
const out = await drawn.image.encode(attempt.type, attempt.quality);
|
|
325
|
+
if (out && out.type === attempt.type && out.size > 0 && out.size <= budget) return { blob: out, kept: false };
|
|
326
|
+
}
|
|
327
|
+
return { problem: `it could not be made smaller than ${budget} bytes` };
|
|
328
|
+
} finally {
|
|
329
|
+
image.close();
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
function browserImageCodec() {
|
|
333
|
+
const g = globalThis;
|
|
334
|
+
if (typeof g.createImageBitmap !== "function") return null;
|
|
335
|
+
const hasOffscreen = typeof g.OffscreenCanvas === "function";
|
|
336
|
+
if (!hasOffscreen && !g.document?.createElement) return null;
|
|
337
|
+
const canvasOf = (w, h) => {
|
|
338
|
+
if (hasOffscreen) return new g.OffscreenCanvas(w, h);
|
|
339
|
+
const c = g.document.createElement("canvas");
|
|
340
|
+
c.width = w;
|
|
341
|
+
c.height = h;
|
|
342
|
+
return c;
|
|
343
|
+
};
|
|
344
|
+
return {
|
|
345
|
+
async decode(blob) {
|
|
346
|
+
const bitmap = await g.createImageBitmap(blob, { imageOrientation: "from-image" });
|
|
347
|
+
return {
|
|
348
|
+
width: bitmap.width,
|
|
349
|
+
height: bitmap.height,
|
|
350
|
+
close: () => bitmap.close(),
|
|
351
|
+
async draw(width, height) {
|
|
352
|
+
const canvas = canvasOf(width, height);
|
|
353
|
+
const ctx = canvas.getContext("2d", { willReadFrequently: true });
|
|
354
|
+
if (!ctx) throw new Error("no 2d canvas");
|
|
355
|
+
ctx.imageSmoothingEnabled = true;
|
|
356
|
+
ctx.imageSmoothingQuality = "high";
|
|
357
|
+
ctx.drawImage(bitmap, 0, 0, width, height);
|
|
358
|
+
let alpha = false;
|
|
359
|
+
try {
|
|
360
|
+
const data = ctx.getImageData(0, 0, width, height).data;
|
|
361
|
+
for (let i = 3; i < data.length; i += 4) {
|
|
362
|
+
if (data[i] !== 255) {
|
|
363
|
+
alpha = true;
|
|
364
|
+
break;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
} catch {
|
|
368
|
+
alpha = true;
|
|
369
|
+
}
|
|
370
|
+
return {
|
|
371
|
+
alpha,
|
|
372
|
+
encode: (type, quality) => {
|
|
373
|
+
if ("convertToBlob" in canvas) return canvas.convertToBlob({ type, quality }).catch(() => null);
|
|
374
|
+
return new Promise((resolve) => canvas.toBlob(resolve, type, quality));
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// packages/server-sdk/src/frame/client/sample.ts
|
|
384
|
+
(() => {
|
|
385
|
+
"use strict";
|
|
386
|
+
const register = window.__openArtifactsSample;
|
|
387
|
+
if (typeof register !== "function") return;
|
|
388
|
+
const OPTIONS = /* @__PURE__ */ new Set(["onText", "signal", "tools", "images", "modelTier", "model", "effort", "fast", "cache"]);
|
|
389
|
+
const TIERS = /* @__PURE__ */ new Set([...MODEL_TIERS, "inherit"]);
|
|
390
|
+
const EFFORTS = /* @__PURE__ */ new Set(["low", "medium", "high"]);
|
|
391
|
+
const CODES = new Set(SAMPLE_ERROR_CODES);
|
|
392
|
+
const MEDIA_TYPES = new Set(SAMPLE_IMAGE_MEDIA_TYPES);
|
|
393
|
+
const LIMITS_MS = 2e4;
|
|
394
|
+
const utf82 = new TextEncoder();
|
|
395
|
+
const noted = /* @__PURE__ */ new Set();
|
|
396
|
+
const isRecord2 = (v) => typeof v === "object" && v !== null;
|
|
397
|
+
const bytesOf = (text) => utf82.encode(text).length;
|
|
398
|
+
function note(text) {
|
|
399
|
+
if (noted.has(text)) return;
|
|
400
|
+
noted.add(text);
|
|
401
|
+
console.warn(`openArtifacts.sample: ${text}`);
|
|
402
|
+
}
|
|
403
|
+
function failure(code, message, text) {
|
|
404
|
+
return text ? { code, message, text } : { code, message };
|
|
405
|
+
}
|
|
406
|
+
const isPlain = (v) => {
|
|
407
|
+
if (!isRecord2(v) || Array.isArray(v)) return false;
|
|
408
|
+
const proto = Object.getPrototypeOf(v);
|
|
409
|
+
return proto === null || proto === Object.prototype;
|
|
410
|
+
};
|
|
411
|
+
const isSignal = (v) => typeof AbortSignal !== "undefined" && v instanceof AbortSignal;
|
|
412
|
+
const isBlob = (v) => typeof Blob !== "undefined" && v instanceof Blob;
|
|
413
|
+
function prepare(input, given, json, aborted, images, refused) {
|
|
414
|
+
if (given !== void 0 && given !== null && !isPlain(given)) {
|
|
415
|
+
return failure("invalid_request", "options: a plain object such as {onText, signal, modelTier}.");
|
|
416
|
+
}
|
|
417
|
+
const options = given ?? {};
|
|
418
|
+
const unknown = Object.keys(options).filter((k) => !OPTIONS.has(k));
|
|
419
|
+
if (unknown.length) note(`${unknown.map((k) => `options.${k}`).join(", ")} ${unknown.length > 1 ? "are not options" : "is not an option"}; ignored.`);
|
|
420
|
+
let signal = null;
|
|
421
|
+
if (options.signal !== void 0) {
|
|
422
|
+
if (!isSignal(options.signal)) {
|
|
423
|
+
const controller = isRecord2(options.signal) && isSignal(options.signal.signal);
|
|
424
|
+
return failure("invalid_request", controller ? "options.signal: pass controller.signal, not the AbortController." : "options.signal: an AbortSignal.");
|
|
425
|
+
}
|
|
426
|
+
signal = options.signal;
|
|
427
|
+
if (signal.aborted) {
|
|
428
|
+
if (aborted) note("the signal passed was already aborted, so the call was cancelled: create a new AbortController for each call.");
|
|
429
|
+
return failure("cancelled", "The signal was aborted before the call was sent.");
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
if (options.onText !== void 0 && typeof options.onText !== "function") return failure("invalid_request", "options.onText: a function.");
|
|
433
|
+
const modelTier = options.modelTier === void 0 ? "default" : options.modelTier;
|
|
434
|
+
if (typeof modelTier !== "string" || !TIERS.has(modelTier)) return failure("invalid_request", 'options.modelTier: "default", "complex", "quick" or "inherit".');
|
|
435
|
+
const inputProblem = sampleInputProblem(input);
|
|
436
|
+
if (inputProblem) return failure("invalid_request", inputProblem);
|
|
437
|
+
if (sampleInputBytes(input) > SAMPLE_MAX_PROMPT_BYTES) return failure("prompt_too_large", `input: at most ${SAMPLE_MAX_PROMPT_BYTES} bytes of text.`);
|
|
438
|
+
const wire = {};
|
|
439
|
+
const tools = /* @__PURE__ */ new Map();
|
|
440
|
+
if (options.tools !== void 0) {
|
|
441
|
+
const toolsProblem = sampleToolsProblem(options.tools);
|
|
442
|
+
if (toolsProblem) return failure("invalid_request", toolsProblem);
|
|
443
|
+
const list = options.tools;
|
|
444
|
+
for (let i = 0; i < list.length; i++) {
|
|
445
|
+
const tool = list[i];
|
|
446
|
+
if (typeof tool.execute !== "function") return failure("invalid_request", `tools[${i}].execute: a function, run here when the model calls the tool.`);
|
|
447
|
+
const spec = { name: tool.name, description: tool.description };
|
|
448
|
+
if (tool.inputSchema !== void 0) spec.inputSchema = JSON.parse(JSON.stringify(tool.inputSchema));
|
|
449
|
+
tools.set(spec.name, { spec, execute: tool.execute });
|
|
450
|
+
}
|
|
451
|
+
if (tools.size) wire.tools = [...tools.values()].map((t) => t.spec);
|
|
452
|
+
}
|
|
453
|
+
const cache = normalizeSampleCache(options.cache, tools.size > 0);
|
|
454
|
+
if ("problem" in cache) return failure("invalid_request", cache.problem);
|
|
455
|
+
wire.cache = cache.cache;
|
|
456
|
+
if (options.model !== void 0) {
|
|
457
|
+
if (modelTier === "inherit") note('options.model is ignored with modelTier "inherit".');
|
|
458
|
+
else if (typeof options.model === "string" && options.model.trim()) wire.model = options.model.trim();
|
|
459
|
+
else note("options.model: a model id string; ignored.");
|
|
460
|
+
}
|
|
461
|
+
if (options.effort !== void 0) {
|
|
462
|
+
if (typeof options.effort === "string" && EFFORTS.has(options.effort)) wire.effort = options.effort;
|
|
463
|
+
else note('options.effort: "low", "medium" or "high"; ignored.');
|
|
464
|
+
}
|
|
465
|
+
if (options.fast !== void 0 && options.fast !== null) {
|
|
466
|
+
if (options.fast === "auto" || options.fast === false) wire.fast = options.fast;
|
|
467
|
+
else note('options.fast: "auto" or false; ignored.');
|
|
468
|
+
}
|
|
469
|
+
if (json) wire.format = "json";
|
|
470
|
+
let blobs = [];
|
|
471
|
+
if (options.images !== void 0) {
|
|
472
|
+
const given2 = options.images;
|
|
473
|
+
if (isBlob(given2)) blobs = [given2];
|
|
474
|
+
else if (Array.isArray(given2)) blobs = given2.slice();
|
|
475
|
+
else if (isRecord2(given2) && typeof given2.length === "number") blobs = Array.from(given2);
|
|
476
|
+
else return failure("invalid_request", "options.images: a Blob or File, or a list of them.");
|
|
477
|
+
for (let i = 0; i < blobs.length; i++) if (!isBlob(blobs[i])) return failure("invalid_request", `options.images[${i}]: a Blob or File.`);
|
|
478
|
+
if (blobs.length && !images) return failure("images_unavailable", "This page cannot send images: its declaration needs capabilities: {sample: {images: true}}.");
|
|
479
|
+
if (blobs.length > SAMPLE_MAX_IMAGES) {
|
|
480
|
+
refused(blobs.length);
|
|
481
|
+
return failure("image_rejected", `At most ${SAMPLE_MAX_IMAGES} images per call.`);
|
|
482
|
+
}
|
|
483
|
+
for (let i = 0; i < blobs.length; i++) {
|
|
484
|
+
const blob = blobs[i];
|
|
485
|
+
if (!MEDIA_TYPES.has(blob.type)) return failure("image_rejected", `options.images[${i}]: ${blob.type || "an untyped file"} is not one of ${SAMPLE_IMAGE_MEDIA_TYPES.join(", ")}.`);
|
|
486
|
+
if (blob.size > SAMPLE_MAX_IMAGE_INPUT_BYTES) return failure("image_rejected", `options.images[${i}]: over ${SAMPLE_MAX_IMAGE_INPUT_BYTES} bytes.`);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
return {
|
|
490
|
+
input,
|
|
491
|
+
modelTier,
|
|
492
|
+
options: wire,
|
|
493
|
+
images: blobs,
|
|
494
|
+
tools,
|
|
495
|
+
onText: typeof options.onText === "function" ? options.onText : null,
|
|
496
|
+
signal
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
async function base64Of(blob) {
|
|
500
|
+
const bytes = new Uint8Array(await blob.arrayBuffer());
|
|
501
|
+
let out = "";
|
|
502
|
+
for (let i = 0; i < bytes.length; i += 32768) out += String.fromCharCode.apply(null, bytes.subarray(i, i + 32768));
|
|
503
|
+
return btoa(out);
|
|
504
|
+
}
|
|
505
|
+
async function wireImages(blobs) {
|
|
506
|
+
const budget = imageByteBudget(blobs.length);
|
|
507
|
+
const codec = browserImageCodec();
|
|
508
|
+
const prepared = await Promise.all(blobs.map((blob) => prepareImage(blob, budget, codec)));
|
|
509
|
+
const out = [];
|
|
510
|
+
for (let i = 0; i < prepared.length; i++) {
|
|
511
|
+
const p = prepared[i];
|
|
512
|
+
if ("problem" in p) return failure("image_rejected", `options.images[${i}]: ${p.problem}.`);
|
|
513
|
+
out.push({ mediaType: p.blob.type, data: await base64Of(p.blob) });
|
|
514
|
+
}
|
|
515
|
+
return out;
|
|
516
|
+
}
|
|
517
|
+
function encodeResult(name, value) {
|
|
518
|
+
const tooLarge = (bytes2) => {
|
|
519
|
+
note(`tool ${name} returned ${bytes2} bytes; at most ${SAMPLE_MAX_TOOL_RESULT_BYTES} go back to the model.`);
|
|
520
|
+
return { content: `Error: result too large (${bytes2} bytes, at most ${SAMPLE_MAX_TOOL_RESULT_BYTES}); return less.`, isError: true };
|
|
521
|
+
};
|
|
522
|
+
if (typeof value === "string") {
|
|
523
|
+
const bytes2 = bytesOf(value);
|
|
524
|
+
return bytes2 > SAMPLE_MAX_TOOL_RESULT_BYTES ? tooLarge(bytes2) : { content: value };
|
|
525
|
+
}
|
|
526
|
+
if (value === void 0) return { content: "(no return value)" };
|
|
527
|
+
let text;
|
|
528
|
+
try {
|
|
529
|
+
text = JSON.stringify(value);
|
|
530
|
+
} catch (error) {
|
|
531
|
+
note(`tool ${name} returned a value that is not JSON (${error?.message ?? error}).`);
|
|
532
|
+
}
|
|
533
|
+
if (text === void 0) return { content: "Error: the result cannot be sent as JSON; return a string or plain data.", isError: true };
|
|
534
|
+
const bytes = bytesOf(text);
|
|
535
|
+
return bytes > SAMPLE_MAX_TOOL_RESULT_BYTES ? tooLarge(bytes) : { content: text };
|
|
536
|
+
}
|
|
537
|
+
function thrownResult(name, error) {
|
|
538
|
+
console.warn(`openArtifacts.sample: tool ${name} threw:`, error);
|
|
539
|
+
const message = isRecord2(error) && typeof error.message === "string" ? error.message : String(error);
|
|
540
|
+
let content = `Error: ${message}`;
|
|
541
|
+
while (bytesOf(content) > SAMPLE_MAX_TOOL_RESULT_BYTES) content = content.slice(0, Math.floor(content.length * 0.9));
|
|
542
|
+
return { content, isError: true };
|
|
543
|
+
}
|
|
544
|
+
register((host) => {
|
|
545
|
+
const running = /* @__PURE__ */ new Set();
|
|
546
|
+
function call(input, options, json, aborted) {
|
|
547
|
+
return new Promise((resolve, reject) => {
|
|
548
|
+
if (!host.framed) return reject(failure("capability_disabled", "This page is not inside its frame shell."));
|
|
549
|
+
const imagesOn = host.config().images === true;
|
|
550
|
+
const ready = prepare(input, options, json, aborted, imagesOn, (count) => host.send(host.id(), "imagesRefused", [count], false));
|
|
551
|
+
if ("code" in ready) return reject(ready);
|
|
552
|
+
const { signal, onText, tools } = ready;
|
|
553
|
+
let id = null;
|
|
554
|
+
let settled = false;
|
|
555
|
+
let text = "";
|
|
556
|
+
let shown = "";
|
|
557
|
+
let lastRound = 0;
|
|
558
|
+
let timer = null;
|
|
559
|
+
const toolControllers = /* @__PURE__ */ new Set();
|
|
560
|
+
const stopTimer = () => {
|
|
561
|
+
if (timer) clearTimeout(timer);
|
|
562
|
+
timer = null;
|
|
563
|
+
};
|
|
564
|
+
const settle = () => {
|
|
565
|
+
if (settled) return false;
|
|
566
|
+
settled = true;
|
|
567
|
+
stopTimer();
|
|
568
|
+
if (id) host.route(id, null);
|
|
569
|
+
running.delete(entry);
|
|
570
|
+
signal?.removeEventListener("abort", onAbort);
|
|
571
|
+
for (const c of toolControllers) c.abort(new Error("The sample call ended."));
|
|
572
|
+
toolControllers.clear();
|
|
573
|
+
return true;
|
|
574
|
+
};
|
|
575
|
+
const fail = (error) => {
|
|
576
|
+
if (settle()) reject(error);
|
|
577
|
+
};
|
|
578
|
+
const withText = (code, message) => failure(code, message, shown || void 0);
|
|
579
|
+
const end = (code, message, tell) => {
|
|
580
|
+
if (settled) return;
|
|
581
|
+
if (tell && id) host.send(host.id(), "cancelCall", [id], false);
|
|
582
|
+
fail(withText(code, message));
|
|
583
|
+
};
|
|
584
|
+
const entry = { end };
|
|
585
|
+
function onAbort() {
|
|
586
|
+
end("cancelled", "The call was cancelled.", true);
|
|
587
|
+
}
|
|
588
|
+
signal?.addEventListener("abort", onAbort);
|
|
589
|
+
running.add(entry);
|
|
590
|
+
const arm = (ms) => {
|
|
591
|
+
stopTimer();
|
|
592
|
+
timer = setTimeout(() => end("upstream_error", "sample did not answer in time.", true), ms);
|
|
593
|
+
};
|
|
594
|
+
const deliver = (update) => {
|
|
595
|
+
if (settled || !onText || signal?.aborted) return;
|
|
596
|
+
try {
|
|
597
|
+
const out = onText(update);
|
|
598
|
+
if (isRecord2(out) && typeof out.then === "function") {
|
|
599
|
+
out.then(void 0, (error) => console.error("openArtifacts.sample: onText rejected:", error));
|
|
600
|
+
}
|
|
601
|
+
} catch (error) {
|
|
602
|
+
console.error("openArtifacts.sample: onText threw:", error);
|
|
603
|
+
}
|
|
604
|
+
};
|
|
605
|
+
const show = () => {
|
|
606
|
+
if (!text.trim() || text.length <= shown.length) return;
|
|
607
|
+
const delta = text.slice(shown.length);
|
|
608
|
+
shown = text;
|
|
609
|
+
deliver({ text, delta });
|
|
610
|
+
};
|
|
611
|
+
const runTools = (calls) => {
|
|
612
|
+
const list = Array.isArray(calls) ? calls.filter((c) => isRecord2(c) && typeof c.id === "string" && typeof c.name === "string") : [];
|
|
613
|
+
stopTimer();
|
|
614
|
+
lastRound = text.length;
|
|
615
|
+
const runOne = (c) => new Promise((done2) => {
|
|
616
|
+
const tool = tools.get(c.name);
|
|
617
|
+
if (!tool) {
|
|
618
|
+
note(`the model called ${c.name}, which is not in this call's tools.`);
|
|
619
|
+
const offered = [...tools.keys()].join(", ") || "none";
|
|
620
|
+
done2({ id: c.id, content: `Error: no tool named "${c.name.slice(0, 128)}"; this call offers: ${offered}.`, isError: true });
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
const controller = new AbortController();
|
|
624
|
+
toolControllers.add(controller);
|
|
625
|
+
let over = false;
|
|
626
|
+
const finish = (result) => {
|
|
627
|
+
if (over) return;
|
|
628
|
+
over = true;
|
|
629
|
+
clearTimeout(limit);
|
|
630
|
+
toolControllers.delete(controller);
|
|
631
|
+
done2({ id: c.id, ...result });
|
|
632
|
+
};
|
|
633
|
+
const limit = setTimeout(() => {
|
|
634
|
+
controller.abort(new Error(`${c.name} took over ${SAMPLE_TOOL_EXECUTE_MS / 1e3} s.`));
|
|
635
|
+
finish({ content: `Error: ${c.name} did not finish within ${SAMPLE_TOOL_EXECUTE_MS / 1e3} s.`, isError: true });
|
|
636
|
+
}, SAMPLE_TOOL_EXECUTE_MS);
|
|
637
|
+
controller.signal.addEventListener("abort", () => clearTimeout(limit), { once: true });
|
|
638
|
+
let out;
|
|
639
|
+
try {
|
|
640
|
+
out = tool.execute(isRecord2(c.input) && !Array.isArray(c.input) ? c.input : {}, { signal: controller.signal });
|
|
641
|
+
} catch (error) {
|
|
642
|
+
finish(thrownResult(c.name, error));
|
|
643
|
+
return;
|
|
644
|
+
}
|
|
645
|
+
Promise.resolve(out).then(
|
|
646
|
+
(value) => finish(encodeResult(c.name, value)),
|
|
647
|
+
(error) => finish(thrownResult(c.name, error))
|
|
648
|
+
);
|
|
649
|
+
});
|
|
650
|
+
void Promise.all(list.map(runOne)).then((results) => {
|
|
651
|
+
if (settled || !id) return;
|
|
652
|
+
if (!host.send(host.id(), "toolResults", [id, results], false)) return end("upstream_error", "The tool results could not be sent.", true);
|
|
653
|
+
arm(host.budget());
|
|
654
|
+
});
|
|
655
|
+
};
|
|
656
|
+
const done = (result) => {
|
|
657
|
+
if (!isRecord2(result) || typeof result.text !== "string") return fail(withText("upstream_error", "The answer was not one."));
|
|
658
|
+
const final = result.text;
|
|
659
|
+
if (!final.trim()) return fail(failure("empty_completion", "The model wrote no text."));
|
|
660
|
+
if (!final.startsWith(shown)) return fail(withText("upstream_error", "The answer does not continue what had streamed."));
|
|
661
|
+
if (final.length > shown.length) {
|
|
662
|
+
text = final;
|
|
663
|
+
show();
|
|
664
|
+
if (settled) return;
|
|
665
|
+
}
|
|
666
|
+
const truncated = result.truncated === true;
|
|
667
|
+
if (json) {
|
|
668
|
+
if (truncated) return fail(failure("invalid_json", "The reply was cut short before its JSON was complete.", final));
|
|
669
|
+
const parsed = parseSampleJson(lastRound > 0 && lastRound <= final.length ? final.slice(lastRound) : final);
|
|
670
|
+
if (!parsed.ok) return fail(failure("invalid_json", "The reply holds no JSON value.", final));
|
|
671
|
+
if (settle()) resolve(parsed.value);
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
const tier = typeof result.modelTierApplied === "string" && MODEL_TIERS.includes(result.modelTierApplied) ? result.modelTierApplied : "default";
|
|
675
|
+
const out = { text: final, truncated, modelTierApplied: tier };
|
|
676
|
+
if (typeof result.modelApplied === "string") out.modelApplied = result.modelApplied;
|
|
677
|
+
if (settle()) resolve(out);
|
|
678
|
+
};
|
|
679
|
+
const failed = (error) => {
|
|
680
|
+
const e = isRecord2(error) ? error : {};
|
|
681
|
+
const code = typeof e.code === "string" && CODES.has(e.code) ? e.code : "upstream_error";
|
|
682
|
+
const message = typeof e.message === "string" && e.message ? e.message : code;
|
|
683
|
+
const partial = code === "refused" ? void 0 : typeof e.text === "string" ? e.text : shown || void 0;
|
|
684
|
+
fail(failure(code, message, partial));
|
|
685
|
+
};
|
|
686
|
+
const onMessage = (d) => {
|
|
687
|
+
if (settled) return;
|
|
688
|
+
if (d.__frame_cap_ack === true) return arm(SAMPLE_ACKED_WAIT_MS);
|
|
689
|
+
if (d.__frame_cap_p === true) {
|
|
690
|
+
const p = isRecord2(d.p) ? d.p : {};
|
|
691
|
+
if (p.type === "text" && typeof p.text === "string") {
|
|
692
|
+
arm(host.budget());
|
|
693
|
+
if (!p.text) return;
|
|
694
|
+
text += p.text;
|
|
695
|
+
show();
|
|
696
|
+
} else if (p.type === "tool_use") runTools(p.calls);
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
if (d.__frame_cap_r === true) {
|
|
700
|
+
if (d.error != null) failed(d.error);
|
|
701
|
+
else done(d.result);
|
|
702
|
+
}
|
|
703
|
+
};
|
|
704
|
+
const send = (options2) => {
|
|
705
|
+
if (settled) return;
|
|
706
|
+
if (signal?.aborted) return fail(failure("cancelled", "The call was cancelled before it was sent."));
|
|
707
|
+
id = host.id();
|
|
708
|
+
host.route(id, onMessage);
|
|
709
|
+
arm(host.budget());
|
|
710
|
+
if (!host.send(id, "sample", [ready.input, ready.modelTier, options2], true)) fail(failure("upstream_error", "The call could not be sent."));
|
|
711
|
+
};
|
|
712
|
+
if (!ready.images.length) {
|
|
713
|
+
queueMicrotask(() => send(ready.options));
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
wireImages(ready.images).then(
|
|
717
|
+
(images) => Array.isArray(images) ? send({ ...ready.options, images }) : fail(images),
|
|
718
|
+
(error) => fail(failure("image_rejected", `An image could not be read (${error?.message ?? error}).`))
|
|
719
|
+
);
|
|
720
|
+
});
|
|
721
|
+
}
|
|
722
|
+
function limits() {
|
|
723
|
+
return new Promise((resolve, reject) => {
|
|
724
|
+
if (!host.framed) return reject(failure("capability_disabled", "This page is not inside its frame shell."));
|
|
725
|
+
const id = host.id();
|
|
726
|
+
const timer = setTimeout(() => {
|
|
727
|
+
host.route(id, null);
|
|
728
|
+
reject(failure("upstream_error", "sample.limits did not answer in time."));
|
|
729
|
+
}, LIMITS_MS);
|
|
730
|
+
host.route(id, (d) => {
|
|
731
|
+
if (d.__frame_cap_r !== true) return;
|
|
732
|
+
clearTimeout(timer);
|
|
733
|
+
host.route(id, null);
|
|
734
|
+
if (d.error != null || !isRecord2(d.result)) {
|
|
735
|
+
const e = isRecord2(d.error) ? d.error : {};
|
|
736
|
+
return reject(failure(typeof e.code === "string" && CODES.has(e.code) ? e.code : "upstream_error", typeof e.message === "string" ? e.message : "The limits could not be read."));
|
|
737
|
+
}
|
|
738
|
+
const out = { ...d.result };
|
|
739
|
+
if (host.config().images !== true) delete out.images;
|
|
740
|
+
else if (isRecord2(out.images)) out.images = { ...out.images, maxSide: SAMPLE_IMAGE_MAX_SIDE, maxBytes: SAMPLE_IMAGE_MAX_BYTES, maxTotalBytes: SAMPLE_IMAGES_MAX_TOTAL_BYTES };
|
|
741
|
+
resolve(out);
|
|
742
|
+
});
|
|
743
|
+
if (!host.send(id, "limits", [], false)) {
|
|
744
|
+
clearTimeout(timer);
|
|
745
|
+
host.route(id, null);
|
|
746
|
+
reject(failure("upstream_error", "sample.limits could not be sent."));
|
|
747
|
+
}
|
|
748
|
+
});
|
|
749
|
+
}
|
|
750
|
+
return {
|
|
751
|
+
call,
|
|
752
|
+
limits,
|
|
753
|
+
rewired: (message) => {
|
|
754
|
+
for (const r of [...running]) r.end("upstream_error", message, true);
|
|
755
|
+
},
|
|
756
|
+
pagehide: () => {
|
|
757
|
+
for (const r of [...running]) r.end("cancelled", "The page was closed.", true);
|
|
758
|
+
}
|
|
759
|
+
};
|
|
760
|
+
});
|
|
761
|
+
})();
|
|
762
|
+
})();
|