@eum-agent/llm-capability-image 0.0.0-stage → 1.2.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/index.js +1581 -0
- package/package.json +56 -3
- package/ui/ui.js +4843 -0
- package/README.md +0 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1581 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { basename, dirname } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { randomUUID } from "node:crypto";
|
|
6
|
+
//#region src/artifact-origins.ts
|
|
7
|
+
const PATTERN = new RegExp(`^https://([a-z0-9][a-z0-9-]*)\\*((?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?){2,})$`);
|
|
8
|
+
const SHARD = /^[a-z0-9-]+$/;
|
|
9
|
+
function declarationOf(entry) {
|
|
10
|
+
const [, prefix, suffix] = PATTERN.exec(entry) ?? [];
|
|
11
|
+
if (prefix && suffix) return {
|
|
12
|
+
kind: "pattern",
|
|
13
|
+
prefix,
|
|
14
|
+
suffix
|
|
15
|
+
};
|
|
16
|
+
if (entry.includes("*")) return void 0;
|
|
17
|
+
let url;
|
|
18
|
+
try {
|
|
19
|
+
url = new URL(entry);
|
|
20
|
+
} catch {
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
if (url.protocol !== "https:" || url.username || url.password || url.origin !== entry) return void 0;
|
|
24
|
+
return {
|
|
25
|
+
kind: "exact",
|
|
26
|
+
origin: entry,
|
|
27
|
+
host: url.hostname,
|
|
28
|
+
port: Number(url.port || 443)
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function isArtifactOriginEntry(entry) {
|
|
32
|
+
return declarationOf(entry) !== void 0;
|
|
33
|
+
}
|
|
34
|
+
function artifactOriginMatches(entries, origin) {
|
|
35
|
+
return entries.some((entry) => {
|
|
36
|
+
const declaration = declarationOf(entry);
|
|
37
|
+
if (declaration?.kind === "exact") return declaration.origin === origin;
|
|
38
|
+
if (!declaration) return false;
|
|
39
|
+
const head = `https://${declaration.prefix}`;
|
|
40
|
+
if (!origin.startsWith(head) || !origin.endsWith(declaration.suffix)) return false;
|
|
41
|
+
return SHARD.test(origin.slice(head.length, origin.length - declaration.suffix.length));
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
function artifactOriginGrant(entry) {
|
|
45
|
+
const declaration = declarationOf(entry);
|
|
46
|
+
if (!declaration) return void 0;
|
|
47
|
+
return declaration.kind === "exact" ? {
|
|
48
|
+
host: declaration.host,
|
|
49
|
+
port: declaration.port,
|
|
50
|
+
exact: true
|
|
51
|
+
} : {
|
|
52
|
+
host: `${declaration.prefix}*${declaration.suffix}`,
|
|
53
|
+
port: 443,
|
|
54
|
+
exact: false
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
//#endregion
|
|
58
|
+
//#region src/runtime/models/redact.ts
|
|
59
|
+
function redactables(type, secrets) {
|
|
60
|
+
const out = { ...secrets };
|
|
61
|
+
for (const field of type.fields) {
|
|
62
|
+
if (field.kind !== "login") continue;
|
|
63
|
+
const value = secrets[field.key];
|
|
64
|
+
if (value === void 0) continue;
|
|
65
|
+
try {
|
|
66
|
+
const parsed = JSON.parse(value);
|
|
67
|
+
if (typeof parsed !== "object" || parsed === null) continue;
|
|
68
|
+
for (const [member, token] of Object.entries(parsed)) if (typeof token === "string" && token !== "") out[`${field.key}.${member}`] = token;
|
|
69
|
+
} catch {}
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
function trackLogin(handle, values) {
|
|
74
|
+
let count = 0;
|
|
75
|
+
function record(value) {
|
|
76
|
+
if (!value) return;
|
|
77
|
+
values[`login.${count++}`] = value;
|
|
78
|
+
try {
|
|
79
|
+
const parsed = JSON.parse(value);
|
|
80
|
+
if (parsed && typeof parsed === "object") {
|
|
81
|
+
for (const member of Object.values(parsed)) if (typeof member === "string") record(member);
|
|
82
|
+
}
|
|
83
|
+
} catch {}
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
async get(signal) {
|
|
87
|
+
const result = await handle.get(signal);
|
|
88
|
+
record(result.credential);
|
|
89
|
+
return result;
|
|
90
|
+
},
|
|
91
|
+
expire: (credential) => handle.expire(credential)
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
//#endregion
|
|
95
|
+
//#region src/runtime/models/binding-port.ts
|
|
96
|
+
function createImageBindingPort(adapter, call) {
|
|
97
|
+
const values = { ...call.secrets };
|
|
98
|
+
for (const [key, value] of Object.entries(call.secrets)) try {
|
|
99
|
+
const parsed = JSON.parse(value);
|
|
100
|
+
if (parsed && typeof parsed === "object") {
|
|
101
|
+
for (const [member, token] of Object.entries(parsed)) if (typeof token === "string" && token) values[`${key}.${member}`] = token;
|
|
102
|
+
}
|
|
103
|
+
} catch {}
|
|
104
|
+
function redact(value) {
|
|
105
|
+
for (const secret of Object.values(values).toSorted((a, b) => b.length - a.length)) if (secret) value = value.split(secret).join("****");
|
|
106
|
+
return value;
|
|
107
|
+
}
|
|
108
|
+
function failure(error) {
|
|
109
|
+
const source = error !== null && typeof error === "object" ? error : {};
|
|
110
|
+
const safe = new Error(typeof source.message === "string" ? redact(source.message) : "Image adapter failed");
|
|
111
|
+
if (typeof source.name === "string") safe.name = redact(source.name);
|
|
112
|
+
for (const key of [
|
|
113
|
+
"code",
|
|
114
|
+
"resultState",
|
|
115
|
+
"providerText",
|
|
116
|
+
"problem"
|
|
117
|
+
]) if (typeof source[key] === "string") Object.assign(safe, { [key]: redact(source[key]) });
|
|
118
|
+
for (const key of ["status", "retryAt"]) if (typeof source[key] === "number") Object.assign(safe, { [key]: source[key] });
|
|
119
|
+
if (typeof source.authored === "boolean") Object.assign(safe, { authored: source.authored });
|
|
120
|
+
return safe;
|
|
121
|
+
}
|
|
122
|
+
let port;
|
|
123
|
+
try {
|
|
124
|
+
port = adapter.createPort({
|
|
125
|
+
...call,
|
|
126
|
+
...call.login ? { login: trackLogin(call.login, values) } : {}
|
|
127
|
+
});
|
|
128
|
+
} catch (error) {
|
|
129
|
+
throw failure(error);
|
|
130
|
+
}
|
|
131
|
+
return { async generate(request, signal) {
|
|
132
|
+
try {
|
|
133
|
+
const result = await port.generate(request, signal);
|
|
134
|
+
if (!result || !Array.isArray(result.assets)) return result;
|
|
135
|
+
return {
|
|
136
|
+
...result,
|
|
137
|
+
assets: result.assets.map((asset) => ({
|
|
138
|
+
...asset,
|
|
139
|
+
body: { async *[Symbol.asyncIterator]() {
|
|
140
|
+
try {
|
|
141
|
+
yield* asset.body;
|
|
142
|
+
} catch (error) {
|
|
143
|
+
throw failure(error);
|
|
144
|
+
}
|
|
145
|
+
} }
|
|
146
|
+
}))
|
|
147
|
+
};
|
|
148
|
+
} catch (error) {
|
|
149
|
+
throw failure(error);
|
|
150
|
+
}
|
|
151
|
+
} };
|
|
152
|
+
}
|
|
153
|
+
//#endregion
|
|
154
|
+
//#region src/capability.ts
|
|
155
|
+
function assertImageAdapter(adapter) {
|
|
156
|
+
const value = adapter;
|
|
157
|
+
if (!value || typeof value.models !== "function" || typeof value.createPort !== "function") throw new Error("unsupported-binding: invalid Image adapter");
|
|
158
|
+
}
|
|
159
|
+
function containsCustomCheck(value, seen = /* @__PURE__ */ new Set()) {
|
|
160
|
+
if (value === null || typeof value !== "object" || seen.has(value)) return false;
|
|
161
|
+
seen.add(value);
|
|
162
|
+
const internal = value._zod;
|
|
163
|
+
if (internal) return containsCustomCheck(internal.def, seen);
|
|
164
|
+
const record = value;
|
|
165
|
+
return record.check === "custom" || Object.values(record).some((child) => containsCustomCheck(child, seen));
|
|
166
|
+
}
|
|
167
|
+
const unique = (values) => new Set(values).size === values.length;
|
|
168
|
+
const descriptors = z.array(z.strictObject({
|
|
169
|
+
id: z.string().trim().min(1),
|
|
170
|
+
label: z.string().trim().min(1),
|
|
171
|
+
outputKinds: z.array(z.enum([
|
|
172
|
+
"image",
|
|
173
|
+
"audio",
|
|
174
|
+
"video"
|
|
175
|
+
])).nonempty().refine(unique),
|
|
176
|
+
artifactOrigins: z.array(z.string().refine(isArtifactOriginEntry)).refine(unique).optional(),
|
|
177
|
+
operations: z.array(z.strictObject({
|
|
178
|
+
id: z.string().trim().min(1),
|
|
179
|
+
inputKinds: z.array(z.string().min(1)).refine(unique),
|
|
180
|
+
minInputs: z.number().int().nonnegative(),
|
|
181
|
+
maxInputs: z.number().int().nonnegative(),
|
|
182
|
+
paramsSchema: z.custom((value) => value instanceof z.ZodType)
|
|
183
|
+
}).refine((value) => value.minInputs <= value.maxInputs)).nonempty().refine((values) => unique(values.map((value) => value.id)))
|
|
184
|
+
})).refine((values) => unique(values.map((value) => value.id)));
|
|
185
|
+
function generationModelsOf(protocol, context) {
|
|
186
|
+
const adapter = protocol.adapters.image;
|
|
187
|
+
if (!adapter) return [];
|
|
188
|
+
assertImageAdapter(adapter);
|
|
189
|
+
const models = adapter.models(context);
|
|
190
|
+
if (!descriptors.safeParse(models).success) throw new Error("invalid Image model descriptors");
|
|
191
|
+
for (const model of models) {
|
|
192
|
+
if (!model.id || !model.label || !Array.isArray(model.outputKinds) || !Array.isArray(model.operations)) throw new Error("invalid Image model descriptor");
|
|
193
|
+
for (const operation of model.operations) {
|
|
194
|
+
if (!(operation.paramsSchema instanceof z.ZodObject) || !(operation.paramsSchema._zod.def.catchall instanceof z.ZodNever) || containsCustomCheck(operation.paramsSchema)) throw new Error("Image operation parameters must be a strict, lossless object schema");
|
|
195
|
+
operation.paramsSchema.toJSONSchema();
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return models;
|
|
199
|
+
}
|
|
200
|
+
const ImageDiscoveryFacts = z.object({ output: z.array(z.string()).optional() });
|
|
201
|
+
const ImageModelFacts = z.object({
|
|
202
|
+
modalities: z.object({ output: z.array(z.string()).optional() }).optional(),
|
|
203
|
+
generation: z.object({
|
|
204
|
+
outputKinds: z.array(z.string()).optional(),
|
|
205
|
+
operations: z.array(z.object({ id: z.string() })).optional()
|
|
206
|
+
}).optional()
|
|
207
|
+
});
|
|
208
|
+
function imageModelFor(input) {
|
|
209
|
+
assertImageAdapter(input.adapter);
|
|
210
|
+
const discovery = ImageDiscoveryFacts.safeParse(input.descriptor?.discoveryFacts).data;
|
|
211
|
+
const facts = ImageModelFacts.safeParse(input.descriptor?.modelFacts ?? input.facts).data;
|
|
212
|
+
const output = discovery?.output ?? facts?.modalities?.output ?? facts?.generation?.outputKinds;
|
|
213
|
+
if (output !== void 0 && !output.includes("image")) return void 0;
|
|
214
|
+
const declaredOperations = facts?.generation?.operations;
|
|
215
|
+
const context = {
|
|
216
|
+
providerId: input.ref.providerId,
|
|
217
|
+
config: input.config,
|
|
218
|
+
configuredModels: [{
|
|
219
|
+
id: input.ref.model,
|
|
220
|
+
...input.execution ? { execution: input.execution } : {}
|
|
221
|
+
}]
|
|
222
|
+
};
|
|
223
|
+
const model = input.adapter.models(context).find((item) => item.id === input.ref.model && item.outputKinds.includes("image"));
|
|
224
|
+
if (!model) return void 0;
|
|
225
|
+
const operations = model.operations.filter((operation) => (operation.id === "create" || operation.id === "edit") && (declaredOperations === void 0 || declaredOperations.some((one) => one.id === operation.id)));
|
|
226
|
+
return operations.length ? {
|
|
227
|
+
...model,
|
|
228
|
+
operations
|
|
229
|
+
} : void 0;
|
|
230
|
+
}
|
|
231
|
+
const imageCapability = {
|
|
232
|
+
id: "image",
|
|
233
|
+
tools: ["model_image_generate"],
|
|
234
|
+
label: "Image",
|
|
235
|
+
order: 20,
|
|
236
|
+
uiContributionKey: "image-models",
|
|
237
|
+
configurationPolicy: {
|
|
238
|
+
params: "retain",
|
|
239
|
+
connection: "cancel"
|
|
240
|
+
},
|
|
241
|
+
bindingSchema: z.record(z.string(), z.unknown()),
|
|
242
|
+
descriptorSchema: z.record(z.string(), z.unknown()),
|
|
243
|
+
paramsSchema(input) {
|
|
244
|
+
const operations = input.descriptor?.operations;
|
|
245
|
+
const fields = {};
|
|
246
|
+
if (Array.isArray(operations)) for (const operation of operations) {
|
|
247
|
+
if (!operation || typeof operation !== "object") continue;
|
|
248
|
+
const value = operation;
|
|
249
|
+
if (typeof value.id === "string" && value.parameterSchema && typeof value.parameterSchema === "object") fields[value.id] = z.fromJSONSchema(value.parameterSchema).optional();
|
|
250
|
+
}
|
|
251
|
+
return Object.keys(fields).length ? z.strictObject(fields) : z.strictObject({
|
|
252
|
+
create: z.record(z.string(), z.unknown()).optional(),
|
|
253
|
+
edit: z.record(z.string(), z.unknown()).optional()
|
|
254
|
+
});
|
|
255
|
+
},
|
|
256
|
+
validateAdapter: assertImageAdapter,
|
|
257
|
+
describeBinding(input) {
|
|
258
|
+
const model = imageModelFor(input);
|
|
259
|
+
return {
|
|
260
|
+
availability: {
|
|
261
|
+
available: !!model,
|
|
262
|
+
...!model ? { reason: "execution-unverified" } : {}
|
|
263
|
+
},
|
|
264
|
+
descriptor: { operations: model?.operations.map((operation) => ({
|
|
265
|
+
id: operation.id,
|
|
266
|
+
inputKinds: [...operation.inputKinds],
|
|
267
|
+
parameterSchema: structuredClone(operation.paramsSchema.toJSONSchema({ io: "input" }))
|
|
268
|
+
})) ?? [] }
|
|
269
|
+
};
|
|
270
|
+
},
|
|
271
|
+
createBinding(input) {
|
|
272
|
+
const model = imageModelFor(input);
|
|
273
|
+
return {
|
|
274
|
+
...imageCapability.describeBinding(input),
|
|
275
|
+
model,
|
|
276
|
+
async createPort() {
|
|
277
|
+
return createImageBindingPort(input.adapter, input.getCall());
|
|
278
|
+
},
|
|
279
|
+
async dispose() {}
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
//#endregion
|
|
284
|
+
//#region src/guidance.ts
|
|
285
|
+
const GUIDANCE = {
|
|
286
|
+
title: "Images",
|
|
287
|
+
entries: [{
|
|
288
|
+
tools: ["model_image_generate"],
|
|
289
|
+
text: "Use model_image_generate for image creation or editing. model_list with capabilityId image reports configured targets and operation parameter schemas. Explicit target overrides the retained image default. A failed default is never silently replaced. File references are returned after publication. If the conversation model cannot view images, do not claim to have inspected the generated result. Never automatically retry an unknown or failed submission.\nAfter successful generation or editing, deliver the image in your final reply using its canonical private attachment URI from the tool result's File reference. Choose presentation from the person's explicit request, task context and effective prompts. By default, show ordinary generation or editing inline as . When the person explicitly requests only a link, use [label](uri) with no inline image. To change only the presentation of an already delivered image, reuse its same URI without calling `model_image_generate` again.\nCopy the URI exactly as returned for that file; never guess or construct it, or substitute a local path, temporary download address, Base64, data URI, browser Blob URL or credential-bearing URL. If the image was saved and delivered as an attachment but no usable URI was returned, say it was generated but a body reference is currently unavailable; retain the attachment viewing entry, do not describe generation as failed, invent a link or generate again just to display it.\nFor failed, cancelled or unknown results, do not invent success, an image or a link, and do not automatically retry generation. Explain the actual result only while the turn can continue. If the whole turn was cancelled, preserve its cancellation state: do not append a reply, resume or restart the turn."
|
|
290
|
+
}]
|
|
291
|
+
};
|
|
292
|
+
//#endregion
|
|
293
|
+
//#region src/body-document.ts
|
|
294
|
+
const LocalBodyRefSchema = z.strictObject({
|
|
295
|
+
bodyId: z.uuid(),
|
|
296
|
+
codec: z.enum([
|
|
297
|
+
"utf8-text",
|
|
298
|
+
"json",
|
|
299
|
+
"opaque"
|
|
300
|
+
]),
|
|
301
|
+
formatVersion: z.literal(1),
|
|
302
|
+
byteLength: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
|
|
303
|
+
sha256: z.string().regex(/^[a-f0-9]{64}$/)
|
|
304
|
+
});
|
|
305
|
+
async function captureTextBody(text, ctx) {
|
|
306
|
+
ctx.signal.throwIfAborted();
|
|
307
|
+
const writer = await ctx.openBody("utf8-text", ctx.signal);
|
|
308
|
+
const encoder = new TextEncoder();
|
|
309
|
+
let offset = 0;
|
|
310
|
+
let index = 0;
|
|
311
|
+
try {
|
|
312
|
+
while (index < text.length) {
|
|
313
|
+
ctx.signal.throwIfAborted();
|
|
314
|
+
const chunk = /* @__PURE__ */ new Uint8Array(65536);
|
|
315
|
+
let end = Math.min(text.length, index + 32768);
|
|
316
|
+
if (end < text.length && /[\uD800-\uDBFF]/u.test(text[end - 1])) end--;
|
|
317
|
+
const { read, written } = encoder.encodeInto(text.slice(index, end), chunk);
|
|
318
|
+
if (!read) throw new Error("text_encoding_failed");
|
|
319
|
+
await writer.write(offset, chunk.subarray(0, written), ctx.signal);
|
|
320
|
+
offset += written;
|
|
321
|
+
index += read;
|
|
322
|
+
}
|
|
323
|
+
return (await writer.seal(ctx.signal)).body;
|
|
324
|
+
} catch (error) {
|
|
325
|
+
await writer.abort();
|
|
326
|
+
throw error;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
function createTextDocuments(render) {
|
|
330
|
+
const documents = /* @__PURE__ */ new WeakMap();
|
|
331
|
+
const prepare = (value, ctx) => {
|
|
332
|
+
const key = typeof value === "object" && value !== null ? value : void 0;
|
|
333
|
+
const prior = key ? documents.get(key) : void 0;
|
|
334
|
+
if (prior) return prior;
|
|
335
|
+
const work = (async () => {
|
|
336
|
+
const input = render(value);
|
|
337
|
+
const literals = input.nodes.filter((node) => node.kind === "literal");
|
|
338
|
+
const lengths = literals.map((node) => new TextEncoder().encode(node.text).byteLength);
|
|
339
|
+
if (literals.length === input.nodes.length && (lengths.some((length) => length > 4096) || lengths.reduce((sum, length) => sum + length, 0) > 16384 || input.nodes.length > 256)) {
|
|
340
|
+
const body = await captureTextBody(literals.map((node) => node.text).join(""), ctx);
|
|
341
|
+
return {
|
|
342
|
+
formatVersion: 1,
|
|
343
|
+
rendererVersion: 1,
|
|
344
|
+
nodes: [{
|
|
345
|
+
id: "text",
|
|
346
|
+
kind: "text-range",
|
|
347
|
+
body,
|
|
348
|
+
startByte: 0,
|
|
349
|
+
endByte: body.byteLength
|
|
350
|
+
}]
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
if (lengths.some((length) => length > 4096) || lengths.reduce((sum, length) => sum + length, 0) > 16384) {
|
|
354
|
+
const nodes = [];
|
|
355
|
+
const all = lengths.reduce((sum, length) => sum + length, 0) > 16384;
|
|
356
|
+
for (const node of input.nodes) {
|
|
357
|
+
if (node.kind !== "literal" || !all && new TextEncoder().encode(node.text).byteLength <= 4096) {
|
|
358
|
+
nodes.push(node);
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
const body = await captureTextBody(node.text, ctx);
|
|
362
|
+
nodes.push({
|
|
363
|
+
id: node.id,
|
|
364
|
+
kind: "text-range",
|
|
365
|
+
body,
|
|
366
|
+
startByte: 0,
|
|
367
|
+
endByte: body.byteLength
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
return {
|
|
371
|
+
...input,
|
|
372
|
+
nodes
|
|
373
|
+
};
|
|
374
|
+
}
|
|
375
|
+
return input;
|
|
376
|
+
})();
|
|
377
|
+
if (key) documents.set(key, work);
|
|
378
|
+
return work;
|
|
379
|
+
};
|
|
380
|
+
return {
|
|
381
|
+
prepare,
|
|
382
|
+
formatModel: prepare
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
//#endregion
|
|
386
|
+
//#region src/tool-data.ts
|
|
387
|
+
const variant = z.strictObject({
|
|
388
|
+
id: z.string().regex(/^[a-f0-9]{64}$/),
|
|
389
|
+
mediaType: z.string().min(1),
|
|
390
|
+
size: z.number().int().positive(),
|
|
391
|
+
width: z.number().int().positive().optional(),
|
|
392
|
+
height: z.number().int().positive().optional()
|
|
393
|
+
});
|
|
394
|
+
const file = variant.extend({
|
|
395
|
+
name: z.string().min(1).max(200),
|
|
396
|
+
forModel: variant.optional()
|
|
397
|
+
});
|
|
398
|
+
const ImageToolDataSchema = z.discriminatedUnion("ok", [z.strictObject({
|
|
399
|
+
ok: z.literal(true),
|
|
400
|
+
committed: z.literal(true),
|
|
401
|
+
target: z.strictObject({
|
|
402
|
+
providerId: z.string(),
|
|
403
|
+
model: z.string()
|
|
404
|
+
}),
|
|
405
|
+
text: LocalBodyRefSchema.optional(),
|
|
406
|
+
textError: z.literal("source_capture_failed").optional(),
|
|
407
|
+
fileIds: z.array(z.string().regex(/^[a-f0-9]{64}$/)).min(1).max(8),
|
|
408
|
+
files: z.array(file).min(1).max(8)
|
|
409
|
+
}).refine((data) => data.text !== void 0 !== (data.textError !== void 0)), z.strictObject({
|
|
410
|
+
ok: z.literal(false),
|
|
411
|
+
code: z.string().min(1).max(128),
|
|
412
|
+
message: z.string().max(1024),
|
|
413
|
+
resultState: z.enum([
|
|
414
|
+
"not-submitted",
|
|
415
|
+
"unknown",
|
|
416
|
+
"not-delivered"
|
|
417
|
+
])
|
|
418
|
+
})]);
|
|
419
|
+
//#endregion
|
|
420
|
+
//#region src/tool-document.ts
|
|
421
|
+
function imageDocument(data) {
|
|
422
|
+
if (!data.ok) return {
|
|
423
|
+
formatVersion: 1,
|
|
424
|
+
rendererVersion: 1,
|
|
425
|
+
nodes: [{
|
|
426
|
+
id: "failure",
|
|
427
|
+
kind: "literal",
|
|
428
|
+
text: data.message
|
|
429
|
+
}]
|
|
430
|
+
};
|
|
431
|
+
return {
|
|
432
|
+
formatVersion: 1,
|
|
433
|
+
rendererVersion: 1,
|
|
434
|
+
nodes: [
|
|
435
|
+
{
|
|
436
|
+
id: "target",
|
|
437
|
+
kind: "literal",
|
|
438
|
+
text: `Image model ${data.target.providerId}/${data.target.model}: ${data.files.length} generated image(s).\n`
|
|
439
|
+
},
|
|
440
|
+
...data.text ? [{
|
|
441
|
+
id: "text",
|
|
442
|
+
kind: "text-range",
|
|
443
|
+
body: data.text,
|
|
444
|
+
startByte: 0,
|
|
445
|
+
endByte: data.text.byteLength
|
|
446
|
+
}] : [{
|
|
447
|
+
id: "text-unavailable",
|
|
448
|
+
kind: "literal",
|
|
449
|
+
text: "The image was generated and saved, but its accompanying text could not be captured.\n"
|
|
450
|
+
}],
|
|
451
|
+
...data.files.map((file, index) => ({
|
|
452
|
+
id: `image-${index}`,
|
|
453
|
+
kind: "media-ref",
|
|
454
|
+
file
|
|
455
|
+
}))
|
|
456
|
+
]
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
function imageResult(data) {
|
|
460
|
+
return {
|
|
461
|
+
data,
|
|
462
|
+
execution: { state: data.ok ? "committed" : data.resultState === "not-submitted" ? "not-started" : "unknown" },
|
|
463
|
+
isError: !data.ok,
|
|
464
|
+
...!data.ok ? { error: {
|
|
465
|
+
code: data.code,
|
|
466
|
+
retryable: false
|
|
467
|
+
} } : {},
|
|
468
|
+
presentation: {
|
|
469
|
+
type: "image-generated",
|
|
470
|
+
schemaVersion: 1,
|
|
471
|
+
state: data.ok ? data.textError ? "partial" : "ready" : "error",
|
|
472
|
+
summary: data.ok ? `${data.files.length} image(s) generated` : data.message.slice(0, 512),
|
|
473
|
+
fields: data.ok ? {
|
|
474
|
+
providerId: data.target.providerId,
|
|
475
|
+
model: data.target.model,
|
|
476
|
+
count: data.files.length,
|
|
477
|
+
committed: true
|
|
478
|
+
} : {
|
|
479
|
+
code: data.code,
|
|
480
|
+
resultState: data.resultState
|
|
481
|
+
},
|
|
482
|
+
actions: [],
|
|
483
|
+
bodyRefs: data.ok && data.text ? [data.text] : []
|
|
484
|
+
}
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
//#endregion
|
|
488
|
+
//#region src/image-generation.ts
|
|
489
|
+
const common = {
|
|
490
|
+
target: z.strictObject({
|
|
491
|
+
providerId: z.string().min(1).max(512).describe("Exact configured provider connection ID from model_list."),
|
|
492
|
+
model: z.string().min(1).max(256).describe("Exact configured image model ID from model_list.")
|
|
493
|
+
}).optional().describe("Exact configured target; otherwise use the global image default."),
|
|
494
|
+
prompt: z.string().refine((value) => value.trim().length > 0 && [...value.trim()].length <= 32e3, { message: "The prompt must contain 1\u201332000 Unicode characters after trimming." }).meta({
|
|
495
|
+
minLength: 1,
|
|
496
|
+
maxLength: 32e3
|
|
497
|
+
}).describe("Image instructions; 1\u201332000 Unicode characters after trimming."),
|
|
498
|
+
params: z.record(z.string(), z.unknown()).default({}).describe("Parameters must match the selected model operation schema; omit to use that model default.")
|
|
499
|
+
};
|
|
500
|
+
const reference = z.union([z.strictObject({ fileId: z.string().regex(/^[0-9a-f]{64}$/).describe("Stored image file ID from this session.") }), z.strictObject({ path: z.string().min(1).max(4096).describe("Local image path to authorize before submission.") })]);
|
|
501
|
+
const create = {
|
|
502
|
+
...common,
|
|
503
|
+
operation: z.literal("create").default("create").describe("Create a new image without references.")
|
|
504
|
+
};
|
|
505
|
+
const edit = {
|
|
506
|
+
...common,
|
|
507
|
+
operation: z.literal("edit").describe("Edit existing images selected by one reference mechanism.")
|
|
508
|
+
};
|
|
509
|
+
const explicit = { reference_images: z.array(reference).min(1).max(14).describe("1\u201314 ordered references, subject to the selected model limit; mutually exclusive with recent count.") };
|
|
510
|
+
const recent = { num_last_images_to_include: z.number().int().min(1).max(14).describe("1\u201314 most recent distinct session images; mutually exclusive with explicit references.") };
|
|
511
|
+
const IMAGE_INPUT_SCHEMA = z.union([
|
|
512
|
+
z.strictObject(create),
|
|
513
|
+
z.strictObject({
|
|
514
|
+
...edit,
|
|
515
|
+
...explicit
|
|
516
|
+
}),
|
|
517
|
+
z.strictObject({
|
|
518
|
+
...edit,
|
|
519
|
+
...recent
|
|
520
|
+
})
|
|
521
|
+
]);
|
|
522
|
+
function refusal(message) {
|
|
523
|
+
return imageResult({
|
|
524
|
+
ok: false,
|
|
525
|
+
code: "invalid-input",
|
|
526
|
+
message: message.slice(0, 1024),
|
|
527
|
+
resultState: "not-submitted"
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
const FAILURE_TEXT = {
|
|
531
|
+
unsupported: "This connection does not support the requested image operation.",
|
|
532
|
+
"invalid-params": "The image request parameters are invalid.",
|
|
533
|
+
"invalid-input": "The selected reference images are missing, stale or unsupported.",
|
|
534
|
+
unavailable: "The current image generation connection is unavailable.",
|
|
535
|
+
busy: "Too many image calls are active; wait for one to finish.",
|
|
536
|
+
cancelled: "Image generation was cancelled.",
|
|
537
|
+
"credential-unavailable": "The connection credential is unavailable; check model settings.",
|
|
538
|
+
"not-signed-in": "Sign in to the selected connection in model settings.",
|
|
539
|
+
expired: "The provider sign-in expired; sign in again in model settings.",
|
|
540
|
+
forbidden: "This account or request is not permitted to generate an image.",
|
|
541
|
+
quota: "The image service rate or quota limit has been reached.",
|
|
542
|
+
timeout: "Image generation timed out.",
|
|
543
|
+
network: "The connection to the image service failed.",
|
|
544
|
+
provider: "The image service request failed.",
|
|
545
|
+
"invalid-output": "The returned image could not be read or did not meet output requirements.",
|
|
546
|
+
"too-large": "The image inputs or output exceeded the size limit.",
|
|
547
|
+
storage: "The generated image could not be saved."
|
|
548
|
+
};
|
|
549
|
+
const STATE_TEXT = {
|
|
550
|
+
"not-submitted": "No image request was submitted.",
|
|
551
|
+
unknown: "The server result is unknown; another attempt creates a new request.",
|
|
552
|
+
"not-delivered": "No image was delivered."
|
|
553
|
+
};
|
|
554
|
+
function failureOf(error, cancelled) {
|
|
555
|
+
const failure = error;
|
|
556
|
+
if (failure?.name !== "GenerationFailure" || typeof failure.code !== "string" || !Object.hasOwn(FAILURE_TEXT, failure.code)) return imageResult({
|
|
557
|
+
ok: false,
|
|
558
|
+
code: cancelled ? "cancelled" : "provider",
|
|
559
|
+
resultState: "unknown",
|
|
560
|
+
message: cancelled ? "Image generation was cancelled. No image was delivered." : "Image generation failed. No image was delivered."
|
|
561
|
+
});
|
|
562
|
+
const state = failure.resultState ?? "not-delivered";
|
|
563
|
+
const prefix = `${FAILURE_TEXT[failure.code]} ${STATE_TEXT[state] ?? STATE_TEXT["not-delivered"]}`;
|
|
564
|
+
const retryAt = failure.retryAt;
|
|
565
|
+
const retry = typeof retryAt === "number" && Number.isFinite(retryAt) && retryAt > 0 && retryAt <= 864e13 ? ` Retry after ${new Date(retryAt).toISOString()} UTC.` : "";
|
|
566
|
+
const detail = typeof failure.message === "string" ? ` ${failure.message}` : "";
|
|
567
|
+
return imageResult({
|
|
568
|
+
ok: false,
|
|
569
|
+
code: failure.code,
|
|
570
|
+
resultState: state,
|
|
571
|
+
message: (prefix + detail).slice(0, 511 - retry.length) + retry + " Do not automatically retry."
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
function imageGenerationTool(deps) {
|
|
575
|
+
const documents = createTextDocuments(imageDocument);
|
|
576
|
+
const candidates = (operation) => deps.generation.connections().flatMap((connection) => connection.models.filter((model) => model.outputKinds.includes("image")).flatMap((model) => model.operations.filter((one) => one.id === operation).map((descriptor) => ({
|
|
577
|
+
ref: {
|
|
578
|
+
providerId: connection.providerId,
|
|
579
|
+
model: model.id
|
|
580
|
+
},
|
|
581
|
+
descriptor
|
|
582
|
+
}))));
|
|
583
|
+
return {
|
|
584
|
+
name: "model_image_generate",
|
|
585
|
+
preload: false,
|
|
586
|
+
deliveryKind: "preview",
|
|
587
|
+
description: "Generate or edit an image using a configured image model. Inspect model_list for operation parameter schemas. Supply target to override the global image default. Never automatically retry a failed submission.",
|
|
588
|
+
inputSchema: IMAGE_INPUT_SCHEMA,
|
|
589
|
+
outputSchema: ImageToolDataSchema,
|
|
590
|
+
formatModel: documents.formatModel,
|
|
591
|
+
available(view) {
|
|
592
|
+
return view.model !== null && deps.generation.connections().some((connection) => connection.models.some((model) => model.outputKinds.includes("image") && model.operations.some((operation) => operation.id === "create" || operation.id === "edit")));
|
|
593
|
+
},
|
|
594
|
+
async execute(input, ctx) {
|
|
595
|
+
try {
|
|
596
|
+
const current = deps.generation.current(ctx);
|
|
597
|
+
const requested = input.target ?? deps.defaultModel();
|
|
598
|
+
const all = candidates(input.operation);
|
|
599
|
+
const eligible = requested ? all.filter((one) => one.ref.providerId === requested.providerId && one.ref.model === requested.model) : all;
|
|
600
|
+
if (!eligible.length) return refusal("The selected or default image model is unavailable for this operation. Choose an image model in settings or pass an explicit target. No request was submitted.");
|
|
601
|
+
if (eligible.length !== 1) return refusal("Multiple image models are available. Set a default image model or pass an explicit target from model_list.");
|
|
602
|
+
const selected = eligible[0];
|
|
603
|
+
const identity = deps.identity(selected.ref);
|
|
604
|
+
if (!identity) return refusal("The image connection is unavailable. No request was submitted.");
|
|
605
|
+
const merged = structuredClone({
|
|
606
|
+
...deps.params(selected.ref, input.operation),
|
|
607
|
+
...input.params
|
|
608
|
+
});
|
|
609
|
+
const params = selected.descriptor.paramsSchema.safeParse(merged);
|
|
610
|
+
if (!params.success) return refusal("The selected image model does not support these parameters. Inspect model_list for its operation schema.");
|
|
611
|
+
let prepared;
|
|
612
|
+
if (input.operation === "edit") {
|
|
613
|
+
const count = "reference_images" in input ? input.reference_images.length : input.num_last_images_to_include;
|
|
614
|
+
if (count < selected.descriptor.minInputs || count > selected.descriptor.maxInputs) return refusal("The selected image model does not support this number of reference images.");
|
|
615
|
+
const selection = "reference_images" in input ? input.reference_images : { recent: input.num_last_images_to_include };
|
|
616
|
+
const result = await deps.inputs.prepare(ctx, selection);
|
|
617
|
+
if (result.kind === "ask") return result.result;
|
|
618
|
+
if (result.kind === "refused") return refusal(result.message);
|
|
619
|
+
prepared = result.inputs;
|
|
620
|
+
}
|
|
621
|
+
const authorization = await deps.generation.authorizeArtifacts(ctx, selected.ref);
|
|
622
|
+
if (authorization.kind === "ask") return authorization.result;
|
|
623
|
+
if (authorization.kind === "refused") return refusal(authorization.message);
|
|
624
|
+
const next = deps.generation.current(ctx);
|
|
625
|
+
if (JSON.stringify(next?.ref) !== JSON.stringify(current?.ref) || next?.connectionRevision !== current?.connectionRevision || next?.registrationEpoch !== current?.registrationEpoch || deps.identity(selected.ref) !== identity) return refusal("The current conversation connection changed. No image request was submitted.");
|
|
626
|
+
if (!candidates(input.operation).some((one) => one.ref.providerId === selected.ref.providerId && one.ref.model === selected.ref.model)) return refusal("The selected image model became unavailable. No image request was submitted.");
|
|
627
|
+
ctx.signal.throwIfAborted();
|
|
628
|
+
const result = await deps.generation.generate(ctx, {
|
|
629
|
+
ref: selected.ref,
|
|
630
|
+
operation: input.operation,
|
|
631
|
+
outputKind: "image",
|
|
632
|
+
prompt: input.prompt.trim(),
|
|
633
|
+
params: params.data,
|
|
634
|
+
...prepared === void 0 ? {} : { inputs: prepared }
|
|
635
|
+
});
|
|
636
|
+
const text = result.text ?? "Image generated.";
|
|
637
|
+
let source;
|
|
638
|
+
try {
|
|
639
|
+
if ([...text].length > 16e3) throw new Error("invalid_image_text");
|
|
640
|
+
source = { text: await captureTextBody(text, ctx) };
|
|
641
|
+
} catch {
|
|
642
|
+
source = { textError: "source_capture_failed" };
|
|
643
|
+
}
|
|
644
|
+
return {
|
|
645
|
+
...imageResult(ImageToolDataSchema.parse({
|
|
646
|
+
ok: true,
|
|
647
|
+
committed: true,
|
|
648
|
+
target: selected.ref,
|
|
649
|
+
...source,
|
|
650
|
+
fileIds: result.files.map((file) => file.id),
|
|
651
|
+
files: [...result.files]
|
|
652
|
+
})),
|
|
653
|
+
files: result.files.map((file) => ({
|
|
654
|
+
fileId: file.id,
|
|
655
|
+
name: file.name
|
|
656
|
+
}))
|
|
657
|
+
};
|
|
658
|
+
} catch (error) {
|
|
659
|
+
return failureOf(error, ctx.signal.aborted);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
//#endregion
|
|
665
|
+
//#region src/adapters.ts
|
|
666
|
+
function imageAdapter(protocol) {
|
|
667
|
+
return protocol?.adapters.image;
|
|
668
|
+
}
|
|
669
|
+
//#endregion
|
|
670
|
+
//#region src/runtime/models/generation.ts
|
|
671
|
+
var GenerationFailure = class extends Error {
|
|
672
|
+
name = "GenerationFailure";
|
|
673
|
+
code;
|
|
674
|
+
resultState;
|
|
675
|
+
status;
|
|
676
|
+
retryAt;
|
|
677
|
+
constructor(code, message, resultState = "not-submitted", status, retryAt) {
|
|
678
|
+
super(message.slice(0, 512));
|
|
679
|
+
this.code = code;
|
|
680
|
+
this.resultState = resultState;
|
|
681
|
+
this.status = status;
|
|
682
|
+
this.retryAt = retryAt;
|
|
683
|
+
}
|
|
684
|
+
};
|
|
685
|
+
const FAILURE_CODES = /* @__PURE__ */ new Set([
|
|
686
|
+
"unsupported",
|
|
687
|
+
"invalid-params",
|
|
688
|
+
"invalid-input",
|
|
689
|
+
"unavailable",
|
|
690
|
+
"busy",
|
|
691
|
+
"cancelled",
|
|
692
|
+
"credential-unavailable",
|
|
693
|
+
"not-signed-in",
|
|
694
|
+
"expired",
|
|
695
|
+
"forbidden",
|
|
696
|
+
"quota",
|
|
697
|
+
"timeout",
|
|
698
|
+
"network",
|
|
699
|
+
"provider",
|
|
700
|
+
"invalid-output",
|
|
701
|
+
"too-large",
|
|
702
|
+
"storage"
|
|
703
|
+
]);
|
|
704
|
+
function fail(code, message) {
|
|
705
|
+
throw new GenerationFailure(code, message);
|
|
706
|
+
}
|
|
707
|
+
function untilAbort(promise, signal) {
|
|
708
|
+
if (signal.aborted) {
|
|
709
|
+
promise.catch(() => {});
|
|
710
|
+
signal.throwIfAborted();
|
|
711
|
+
}
|
|
712
|
+
return new Promise((resolve, reject) => {
|
|
713
|
+
const abort = () => reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
|
|
714
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
715
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
716
|
+
});
|
|
717
|
+
}
|
|
718
|
+
function createGenerationHost(deps) {
|
|
719
|
+
const prepared = /* @__PURE__ */ new WeakMap();
|
|
720
|
+
const active = /* @__PURE__ */ new Set();
|
|
721
|
+
const authorized = /* @__PURE__ */ new WeakMap();
|
|
722
|
+
const ports = /* @__PURE__ */ new Map();
|
|
723
|
+
let stopped = false;
|
|
724
|
+
function descriptor(owner, ref, crossOwner = false) {
|
|
725
|
+
const target = deps.target(ref);
|
|
726
|
+
if (!target?.enabled || target.lifetime.aborted || !crossOwner && target.owner !== owner || !imageAdapter(target.protocol)) fail("unavailable", "the generation provider is unavailable");
|
|
727
|
+
const model = deps.descriptors(target.protocol, {
|
|
728
|
+
providerId: ref.providerId,
|
|
729
|
+
config: target.config,
|
|
730
|
+
configuredModels: target.configuredModels
|
|
731
|
+
}).find((one) => one.id === ref.model);
|
|
732
|
+
if (!model) fail("unsupported", "the generation model is unsupported");
|
|
733
|
+
return {
|
|
734
|
+
target,
|
|
735
|
+
model
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
function bind(owner, crossOwner = false) {
|
|
739
|
+
return {
|
|
740
|
+
connections: () => deps.connections(crossOwner ? void 0 : owner),
|
|
741
|
+
current(ctx) {
|
|
742
|
+
deps.authenticate(owner, ctx);
|
|
743
|
+
return deps.current(ctx);
|
|
744
|
+
},
|
|
745
|
+
async authorizeArtifacts(ctx, ref) {
|
|
746
|
+
deps.authenticate(owner, ctx);
|
|
747
|
+
const { model, target } = descriptor(owner, ref, crossOwner);
|
|
748
|
+
const result = await deps.authorize(ctx, model.artifactOrigins ?? []);
|
|
749
|
+
if (result.kind === "ready") {
|
|
750
|
+
if (deps.target(ref)?.registrationEpoch !== target.registrationEpoch || deps.target(ref)?.protocolEpoch !== target.protocolEpoch || deps.target(ref)?.connectionRevision !== target.connectionRevision || !deps.target(ref)?.enabled || target.lifetime.aborted || ctx.signal.aborted) fail("cancelled", "the provider changed during authorization");
|
|
751
|
+
authorized.set(ctx, new Set(model.artifactOrigins ?? []));
|
|
752
|
+
}
|
|
753
|
+
return result;
|
|
754
|
+
},
|
|
755
|
+
async generate(ctx, input) {
|
|
756
|
+
deps.authenticate(owner, ctx);
|
|
757
|
+
if (stopped) fail("unavailable", "generation is stopped");
|
|
758
|
+
ctx.signal.throwIfAborted();
|
|
759
|
+
const { target, model } = descriptor(owner, input.ref, crossOwner);
|
|
760
|
+
const operation = model.operations.find((one) => one.id === input.operation);
|
|
761
|
+
if (!operation || !model.outputKinds.includes(input.outputKind)) fail("unsupported", "the generation operation is unsupported");
|
|
762
|
+
const prompt = input.prompt.trim();
|
|
763
|
+
if (!prompt || [...prompt].length > 32e3) fail("invalid-params", "the generation prompt must contain 1\u201332000 characters");
|
|
764
|
+
const params = operation.paramsSchema.safeParse(input.params);
|
|
765
|
+
if (!params.success) fail("invalid-params", `the generation parameters are invalid (${params.error.issues.slice(0, 4).map((issue) => `${issue.path.map(String).join(".") || "params"}: ${issue.code}`).join("; ")})`);
|
|
766
|
+
const selection = input.inputs === void 0 ? void 0 : prepared.get(input.inputs);
|
|
767
|
+
const historyRevision = deps.sessionRevision(ctx.sessionId);
|
|
768
|
+
if (input.inputs !== void 0 && (!selection || selection.owner !== owner || selection.ctx !== ctx || selection.sessionId !== ctx.sessionId || selection.callId !== ctx.toolCallId || selection.revision !== historyRevision)) fail("invalid-input", "the input selection is invalid or stale");
|
|
769
|
+
const inputs = selection?.files ?? [];
|
|
770
|
+
if (inputs.length < operation.minInputs || inputs.length > operation.maxInputs || inputs.some((file) => !operation.inputKinds.includes(file.mediaType.split("/")[0]))) fail("invalid-input", "the generation input count or media kind is unsupported");
|
|
771
|
+
const origins = model.artifactOrigins ?? [];
|
|
772
|
+
if (origins.some((origin) => !authorized.get(ctx)?.has(origin))) fail("forbidden", "authorize artifact origins before generation");
|
|
773
|
+
if (active.size >= 4 || [...active].filter((one) => one.ctx.sessionId === ctx.sessionId).length >= 2) fail("busy", "too many active generation calls");
|
|
774
|
+
const initial = deps.current(ctx);
|
|
775
|
+
const controller = new AbortController();
|
|
776
|
+
const deadline = AbortSignal.timeout(9e5);
|
|
777
|
+
const signal = AbortSignal.any([
|
|
778
|
+
ctx.signal,
|
|
779
|
+
target.lifetime,
|
|
780
|
+
controller.signal,
|
|
781
|
+
deadline
|
|
782
|
+
]);
|
|
783
|
+
const staged = [];
|
|
784
|
+
let submitted = false;
|
|
785
|
+
let responded = false;
|
|
786
|
+
let phase = "provider";
|
|
787
|
+
const admission = {
|
|
788
|
+
ctx,
|
|
789
|
+
controller,
|
|
790
|
+
assertCurrent() {
|
|
791
|
+
signal.throwIfAborted();
|
|
792
|
+
const now = deps.target(input.ref);
|
|
793
|
+
const current = deps.current(ctx);
|
|
794
|
+
if (!now?.enabled || now.owner !== target.owner || now.registrationEpoch !== target.registrationEpoch || now.protocolEpoch !== target.protocolEpoch || now.connectionRevision !== target.connectionRevision || historyRevision !== deps.sessionRevision(ctx.sessionId) || JSON.stringify(current?.ref) !== JSON.stringify(initial?.ref)) fail("cancelled", "the generation context changed");
|
|
795
|
+
}
|
|
796
|
+
};
|
|
797
|
+
active.add(admission);
|
|
798
|
+
let secrets = {};
|
|
799
|
+
try {
|
|
800
|
+
admission.assertCurrent();
|
|
801
|
+
const key = JSON.stringify([
|
|
802
|
+
owner,
|
|
803
|
+
input.ref.providerId,
|
|
804
|
+
input.ref.model,
|
|
805
|
+
"generation"
|
|
806
|
+
]);
|
|
807
|
+
let kept = ports.get(key);
|
|
808
|
+
if (!kept || kept.epoch !== target.registrationEpoch || kept.protocolEpoch !== target.protocolEpoch || kept.revision !== target.connectionRevision) {
|
|
809
|
+
const credential = deps.credential(input.ref, target.type);
|
|
810
|
+
const redactions = redactables(target.type, credential.secrets);
|
|
811
|
+
const login = credential.login === void 0 ? void 0 : trackLogin(credential.login, redactions);
|
|
812
|
+
secrets = redactions;
|
|
813
|
+
const port = imageAdapter(target.protocol).createPort({
|
|
814
|
+
endpointId: String(target.config.endpointId),
|
|
815
|
+
protocolId: target.protocol.type,
|
|
816
|
+
options: target.options,
|
|
817
|
+
providerId: input.ref.providerId,
|
|
818
|
+
model: input.ref.model,
|
|
819
|
+
config: target.config,
|
|
820
|
+
configuredModels: target.configuredModels,
|
|
821
|
+
secrets: credential.secrets,
|
|
822
|
+
...target.headers ? { headers: target.headers } : {},
|
|
823
|
+
...login ? { login } : {}
|
|
824
|
+
});
|
|
825
|
+
kept = {
|
|
826
|
+
ref: input.ref,
|
|
827
|
+
owner: target.owner,
|
|
828
|
+
epoch: target.registrationEpoch,
|
|
829
|
+
protocolEpoch: target.protocolEpoch,
|
|
830
|
+
revision: target.connectionRevision,
|
|
831
|
+
port,
|
|
832
|
+
secrets: redactions
|
|
833
|
+
};
|
|
834
|
+
ports.set(key, kept);
|
|
835
|
+
}
|
|
836
|
+
secrets = kept.secrets;
|
|
837
|
+
const port = kept.port;
|
|
838
|
+
submitted = true;
|
|
839
|
+
const firstDeadline = new AbortController();
|
|
840
|
+
const firstTimer = setTimeout(() => {
|
|
841
|
+
firstDeadline.abort(new DOMException("The first response timed out", "TimeoutError"));
|
|
842
|
+
}, 3e5);
|
|
843
|
+
firstTimer.unref();
|
|
844
|
+
const first = AbortSignal.any([signal, firstDeadline.signal]);
|
|
845
|
+
const result = await untilAbort((async () => port.generate({
|
|
846
|
+
accounting: deps.beginUsage?.(ctx),
|
|
847
|
+
identity: { callId: randomUUID() },
|
|
848
|
+
artifacts: deps.artifacts(ctx, origins),
|
|
849
|
+
operation: input.operation,
|
|
850
|
+
outputKind: input.outputKind,
|
|
851
|
+
prompt,
|
|
852
|
+
params: params.data,
|
|
853
|
+
inputs
|
|
854
|
+
}, first))(), first).finally(() => clearTimeout(firstTimer));
|
|
855
|
+
responded = true;
|
|
856
|
+
if (result === null || typeof result !== "object" || !Array.isArray(result.assets) || result.assets.length < 1 || result.assets.length > 8 || result.text !== void 0 && (typeof result.text !== "string" || [...result.text].length > 16e3)) fail("invalid-output", "the provider returned an invalid generation result");
|
|
857
|
+
phase = "stage";
|
|
858
|
+
let total = 0;
|
|
859
|
+
for (const asset of result.assets) {
|
|
860
|
+
admission.assertCurrent();
|
|
861
|
+
const body = (async function* () {
|
|
862
|
+
const iterator = asset.body[Symbol.asyncIterator]();
|
|
863
|
+
try {
|
|
864
|
+
for (;;) {
|
|
865
|
+
const next = await untilAbort(iterator.next(), AbortSignal.any([signal, AbortSignal.timeout(6e4)]));
|
|
866
|
+
if (next.done) break;
|
|
867
|
+
if (!(next.value instanceof Uint8Array)) fail("invalid-output", "the provider returned invalid asset bytes");
|
|
868
|
+
total += next.value.byteLength;
|
|
869
|
+
if (total > 268435456) fail("too-large", "the generation result exceeds 256 MiB");
|
|
870
|
+
yield next.value;
|
|
871
|
+
}
|
|
872
|
+
} finally {
|
|
873
|
+
iterator.return?.().catch(() => {});
|
|
874
|
+
}
|
|
875
|
+
})();
|
|
876
|
+
staged.push(await deps.files.stageStream(ctx.address.workspaceId, {
|
|
877
|
+
mediaType: asset.mediaType,
|
|
878
|
+
name: asset.name,
|
|
879
|
+
body
|
|
880
|
+
}, {
|
|
881
|
+
outputKind: input.outputKind,
|
|
882
|
+
signal
|
|
883
|
+
}));
|
|
884
|
+
}
|
|
885
|
+
phase = "commit";
|
|
886
|
+
const files = await deps.files.commitBatch(ctx.address.workspaceId, ctx.sessionId, staged, {
|
|
887
|
+
signal,
|
|
888
|
+
assertCurrent: admission.assertCurrent
|
|
889
|
+
});
|
|
890
|
+
return {
|
|
891
|
+
...result.text === void 0 ? {} : { text: result.text },
|
|
892
|
+
files
|
|
893
|
+
};
|
|
894
|
+
} catch (error) {
|
|
895
|
+
if (error instanceof GenerationFailure) {
|
|
896
|
+
if (submitted && error.resultState === "not-submitted") throw new GenerationFailure(error.code, error.message, responded ? "not-delivered" : "unknown", error.status, error.retryAt);
|
|
897
|
+
throw error;
|
|
898
|
+
}
|
|
899
|
+
const record = error;
|
|
900
|
+
const cancelled = ctx.signal.aborted || target.lifetime.aborted || controller.signal.aborted || record.name === "AbortError";
|
|
901
|
+
const timeout = record.name === "TimeoutError" || deadline.aborted;
|
|
902
|
+
const reported = typeof record.code === "string" && FAILURE_CODES.has(record.code) && (record.authored || record.name === "GenerationFailure") ? record.code : void 0;
|
|
903
|
+
const code = cancelled ? "cancelled" : timeout ? "timeout" : phase === "commit" ? "storage" : phase === "stage" ? record.problem === "too-large" ? "too-large" : "invalid-output" : reported ?? (record.name === "CredentialUnavailableError" ? "credential-unavailable" : record.status === 401 ? "expired" : record.status === 403 ? "forbidden" : record.status === 429 ? "quota" : "provider");
|
|
904
|
+
let message = (record.authored || reported) && typeof record.message === "string" ? record.message : code === "cancelled" ? "generation was cancelled" : code === "timeout" ? "generation timed out" : code === "storage" ? "the generated files could not be saved" : code === "invalid-output" ? "the generated media is invalid" : code === "expired" ? "your sign-in expired; sign in again" : "the generation provider call failed";
|
|
905
|
+
if (typeof record.providerText === "string") message += `: ${record.providerText.slice(0, 65536)}`;
|
|
906
|
+
for (const secret of Object.values(secrets)) if (secret) message = message.split(secret).join("****");
|
|
907
|
+
const retryAt = typeof record.retryAt === "number" && Number.isFinite(record.retryAt) && record.retryAt > 0 && record.retryAt <= 864e13 ? record.retryAt : void 0;
|
|
908
|
+
if (retryAt !== void 0) message += ` Retry after ${new Date(retryAt).toISOString()}.`;
|
|
909
|
+
const declaredState = record.name === "GenerationFailure" && reported !== void 0 && (record.resultState === "not-submitted" || record.resultState === "unknown" || record.resultState === "not-delivered") ? record.resultState : void 0;
|
|
910
|
+
throw new GenerationFailure(code, message, responded ? "not-delivered" : declaredState ?? (submitted ? "unknown" : "not-submitted"), typeof record.status === "number" ? record.status : void 0, retryAt);
|
|
911
|
+
} finally {
|
|
912
|
+
active.delete(admission);
|
|
913
|
+
deps.files.discard(staged);
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
};
|
|
917
|
+
}
|
|
918
|
+
return {
|
|
919
|
+
bindInputs(owner) {
|
|
920
|
+
return { async prepare(ctx, selectors) {
|
|
921
|
+
deps.authenticate(owner, ctx);
|
|
922
|
+
ctx.signal.throwIfAborted();
|
|
923
|
+
const revision = deps.sessionRevision(ctx.sessionId);
|
|
924
|
+
const result = await deps.prepare(ctx, selectors);
|
|
925
|
+
ctx.signal.throwIfAborted();
|
|
926
|
+
if (!Array.isArray(result)) return result;
|
|
927
|
+
if (revision !== deps.sessionRevision(ctx.sessionId)) fail("cancelled", "the session history changed");
|
|
928
|
+
const token = Object.freeze({});
|
|
929
|
+
prepared.set(token, {
|
|
930
|
+
owner,
|
|
931
|
+
ctx,
|
|
932
|
+
callId: ctx.toolCallId,
|
|
933
|
+
sessionId: ctx.sessionId,
|
|
934
|
+
revision,
|
|
935
|
+
files: result
|
|
936
|
+
});
|
|
937
|
+
return {
|
|
938
|
+
kind: "ready",
|
|
939
|
+
inputs: token
|
|
940
|
+
};
|
|
941
|
+
} };
|
|
942
|
+
},
|
|
943
|
+
bind,
|
|
944
|
+
bindCoordinator: (owner) => bind(owner, true),
|
|
945
|
+
invalidate() {
|
|
946
|
+
for (const [key, kept] of ports) {
|
|
947
|
+
const target = deps.target(kept.ref);
|
|
948
|
+
if (!target?.enabled || target.owner !== kept.owner || target.registrationEpoch !== kept.epoch || target.protocolEpoch !== kept.protocolEpoch || target.connectionRevision !== kept.revision) ports.delete(key);
|
|
949
|
+
}
|
|
950
|
+
for (const call of active) try {
|
|
951
|
+
call.assertCurrent();
|
|
952
|
+
} catch {
|
|
953
|
+
call.controller.abort();
|
|
954
|
+
}
|
|
955
|
+
},
|
|
956
|
+
stop() {
|
|
957
|
+
stopped = true;
|
|
958
|
+
ports.clear();
|
|
959
|
+
for (const call of active) call.controller.abort();
|
|
960
|
+
}
|
|
961
|
+
};
|
|
962
|
+
}
|
|
963
|
+
//#endregion
|
|
964
|
+
//#region src/runtime/models/generation-inputs.ts
|
|
965
|
+
const FILE_ORIGINAL_LIMIT = 20971520;
|
|
966
|
+
const READ_CHUNK = 1048576;
|
|
967
|
+
const IMAGE_MEDIA_TYPES = [
|
|
968
|
+
"image/png",
|
|
969
|
+
"image/jpeg",
|
|
970
|
+
"image/gif",
|
|
971
|
+
"image/webp"
|
|
972
|
+
];
|
|
973
|
+
const selectorsSchema = z.union([z.object({ recent: z.number().int().min(1).max(16) }).strict(), z.array(z.union([z.object({ fileId: z.string().regex(/^[0-9a-f]{64}$/) }).strict(), z.object({ path: z.string().min(1) }).strict()])).max(16)]);
|
|
974
|
+
function createGenerationInputReader(deps) {
|
|
975
|
+
return async (ctx, selectors) => {
|
|
976
|
+
ctx.signal.throwIfAborted();
|
|
977
|
+
const parsed = selectorsSchema.safeParse(selectors);
|
|
978
|
+
if (!parsed.success) return {
|
|
979
|
+
kind: "refused",
|
|
980
|
+
message: "invalid generation input selectors"
|
|
981
|
+
};
|
|
982
|
+
selectors = parsed.data;
|
|
983
|
+
const history = await deps.history(ctx);
|
|
984
|
+
ctx.signal.throwIfAborted();
|
|
985
|
+
const ordered = [];
|
|
986
|
+
for (const message of history) for (const part of message.content) {
|
|
987
|
+
if (part.type === "file") ordered.push(part.file);
|
|
988
|
+
if (part.type === "tool-result") ordered.push(...part.files ?? []);
|
|
989
|
+
}
|
|
990
|
+
const latest = new Map(ordered.map((file, index) => [file.id, {
|
|
991
|
+
file,
|
|
992
|
+
index
|
|
993
|
+
}]));
|
|
994
|
+
let selection;
|
|
995
|
+
if ("recent" in selectors) {
|
|
996
|
+
const recent = [...latest.values()].filter((one) => IMAGE_MEDIA_TYPES.includes(one.file.mediaType)).sort((a, b) => a.index - b.index).slice(-selectors.recent);
|
|
997
|
+
if (recent.length !== selectors.recent) return {
|
|
998
|
+
kind: "refused",
|
|
999
|
+
message: "the session does not contain enough recent images"
|
|
1000
|
+
};
|
|
1001
|
+
selection = recent.map((one) => ({ fileId: one.file.id }));
|
|
1002
|
+
} else selection = selectors;
|
|
1003
|
+
for (const item of selection) if ("fileId" in item) {
|
|
1004
|
+
const selected = latest.get(item.fileId);
|
|
1005
|
+
if (!selected) return {
|
|
1006
|
+
kind: "refused",
|
|
1007
|
+
message: "the selected file is not in this session history"
|
|
1008
|
+
};
|
|
1009
|
+
if (!IMAGE_MEDIA_TYPES.includes(selected.file.mediaType)) return {
|
|
1010
|
+
kind: "refused",
|
|
1011
|
+
message: "the selected file is not an image"
|
|
1012
|
+
};
|
|
1013
|
+
}
|
|
1014
|
+
const requested = selection.flatMap((item, index) => "path" in item ? [{
|
|
1015
|
+
index,
|
|
1016
|
+
path: item.path
|
|
1017
|
+
}] : []);
|
|
1018
|
+
const paths = /* @__PURE__ */ new Map();
|
|
1019
|
+
if (requested.length > 0) {
|
|
1020
|
+
const batch = await deps.scope.allowsMany(ctx, requested.map((item) => ({
|
|
1021
|
+
path: item.path,
|
|
1022
|
+
access: "read"
|
|
1023
|
+
})));
|
|
1024
|
+
ctx.signal.throwIfAborted();
|
|
1025
|
+
if (batch.ask && "awaitHuman" in batch.ask) return {
|
|
1026
|
+
kind: "ask",
|
|
1027
|
+
result: batch.ask
|
|
1028
|
+
};
|
|
1029
|
+
for (const [offset, item] of requested.entries()) {
|
|
1030
|
+
const verdict = batch.verdicts[offset];
|
|
1031
|
+
if (!verdict) return {
|
|
1032
|
+
kind: "refused",
|
|
1033
|
+
message: "the image path was not authorized"
|
|
1034
|
+
};
|
|
1035
|
+
if (!verdict.allowed) {
|
|
1036
|
+
if (verdict.reason === "ask" && "awaitHuman" in verdict.ask) return {
|
|
1037
|
+
kind: "ask",
|
|
1038
|
+
result: verdict.ask
|
|
1039
|
+
};
|
|
1040
|
+
return {
|
|
1041
|
+
kind: "refused",
|
|
1042
|
+
message: "message" in verdict ? verdict.message : "reading the selected image paths was refused"
|
|
1043
|
+
};
|
|
1044
|
+
}
|
|
1045
|
+
paths.set(item.index, verdict);
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
const files = [];
|
|
1049
|
+
try {
|
|
1050
|
+
for (const [index, item] of selection.entries()) {
|
|
1051
|
+
ctx.signal.throwIfAborted();
|
|
1052
|
+
let bytes;
|
|
1053
|
+
if ("path" in item) {
|
|
1054
|
+
const verdict = paths.get(index);
|
|
1055
|
+
if (verdict === void 0) return {
|
|
1056
|
+
kind: "refused",
|
|
1057
|
+
message: "the image path was not authorized"
|
|
1058
|
+
};
|
|
1059
|
+
const read = await readAuthorized(deps.clientFiles, verdict, ctx.signal);
|
|
1060
|
+
if (!Buffer.isBuffer(read)) return {
|
|
1061
|
+
kind: "refused",
|
|
1062
|
+
message: read.refused
|
|
1063
|
+
};
|
|
1064
|
+
bytes = read;
|
|
1065
|
+
} else bytes = await deps.files.read(ctx.address.workspaceId, item.fileId);
|
|
1066
|
+
if (!bytes || bytes.length > FILE_ORIGINAL_LIMIT) return {
|
|
1067
|
+
kind: "refused",
|
|
1068
|
+
message: "the selected image is missing or exceeds the input size limit"
|
|
1069
|
+
};
|
|
1070
|
+
const info = await deps.probeImage(bytes);
|
|
1071
|
+
ctx.signal.throwIfAborted();
|
|
1072
|
+
const held = bytes;
|
|
1073
|
+
files.push({
|
|
1074
|
+
mediaType: info.mediaType,
|
|
1075
|
+
size: held.length,
|
|
1076
|
+
async *read(signal) {
|
|
1077
|
+
signal.throwIfAborted();
|
|
1078
|
+
yield held;
|
|
1079
|
+
signal.throwIfAborted();
|
|
1080
|
+
}
|
|
1081
|
+
});
|
|
1082
|
+
}
|
|
1083
|
+
return files;
|
|
1084
|
+
} catch {
|
|
1085
|
+
ctx.signal.throwIfAborted();
|
|
1086
|
+
return {
|
|
1087
|
+
kind: "refused",
|
|
1088
|
+
message: "the selected image could not be read"
|
|
1089
|
+
};
|
|
1090
|
+
}
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
async function readAuthorized(clientFiles, verdict, signal) {
|
|
1094
|
+
const parentPath = dirname(verdict.path);
|
|
1095
|
+
const parent = await clientFiles.anchor(parentPath, {
|
|
1096
|
+
sealedDirectories: verdict.sealedDirectories,
|
|
1097
|
+
signal
|
|
1098
|
+
});
|
|
1099
|
+
try {
|
|
1100
|
+
signal.throwIfAborted();
|
|
1101
|
+
if (parent.path !== parentPath) return { refused: "the image path changed before it was read" };
|
|
1102
|
+
const reader = await parent.openRead([basename(verdict.path)]);
|
|
1103
|
+
try {
|
|
1104
|
+
const before = await reader.stat();
|
|
1105
|
+
const identity = verdict.identity;
|
|
1106
|
+
if (identity) {
|
|
1107
|
+
const observed = identity.path === verdict.path ? before : identity.path === parentPath ? await parent.stat() : void 0;
|
|
1108
|
+
if (!observed || observed.device !== identity.identity.device || observed.inode !== identity.identity.fileId) return { refused: "the image path changed before it was read" };
|
|
1109
|
+
}
|
|
1110
|
+
const size = BigInt(before.size);
|
|
1111
|
+
if (before.kind !== "file" || size < 0n || size > BigInt(FILE_ORIGINAL_LIMIT)) return { refused: "the image exceeds the input size limit" };
|
|
1112
|
+
const total = Number(size);
|
|
1113
|
+
const chunks = [];
|
|
1114
|
+
let position = 0;
|
|
1115
|
+
while (position < total) {
|
|
1116
|
+
signal.throwIfAborted();
|
|
1117
|
+
const chunk = await reader.read(position, Math.min(READ_CHUNK, total - position));
|
|
1118
|
+
if (!chunk.length || chunk.length > total - position) return { refused: "the image changed while it was read" };
|
|
1119
|
+
chunks.push(chunk);
|
|
1120
|
+
position += chunk.length;
|
|
1121
|
+
}
|
|
1122
|
+
if ((await reader.read(position, 1)).length || !sameObservation(before, await reader.stat())) return { refused: "the image changed while it was read" };
|
|
1123
|
+
return Buffer.concat(chunks, position);
|
|
1124
|
+
} finally {
|
|
1125
|
+
await reader.close();
|
|
1126
|
+
}
|
|
1127
|
+
} finally {
|
|
1128
|
+
await parent.close();
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
function sameObservation(before, after) {
|
|
1132
|
+
return before.device === after.device && before.inode === after.inode && before.kind === after.kind && before.size === after.size && before.modifiedNs === after.modifiedNs && before.changedNs === after.changedNs;
|
|
1133
|
+
}
|
|
1134
|
+
//#endregion
|
|
1135
|
+
//#region src/runtime/models/generation-services.ts
|
|
1136
|
+
function createGenerationServices(input) {
|
|
1137
|
+
const { ctx, manager, host } = input;
|
|
1138
|
+
const deps = {
|
|
1139
|
+
files: host.files,
|
|
1140
|
+
security: host.security,
|
|
1141
|
+
contexts: host.contexts,
|
|
1142
|
+
approval: input.approval,
|
|
1143
|
+
transport: host.transport,
|
|
1144
|
+
probeImage: host.media.probeImage
|
|
1145
|
+
};
|
|
1146
|
+
function session(id) {
|
|
1147
|
+
return host.contexts.session(id);
|
|
1148
|
+
}
|
|
1149
|
+
const identities = /* @__PURE__ */ new Map();
|
|
1150
|
+
const lifecycle = ctx.services.find?.("session-lifecycle");
|
|
1151
|
+
const callers = /* @__PURE__ */ new WeakMap();
|
|
1152
|
+
function sessionLease(request) {
|
|
1153
|
+
const call = callers.get(request.artifacts);
|
|
1154
|
+
if (!lifecycle || !call) return void 0;
|
|
1155
|
+
try {
|
|
1156
|
+
return lifecycle.enter(call.sessionId);
|
|
1157
|
+
} catch (error) {
|
|
1158
|
+
if (error instanceof Error && error.message.startsWith("not-found")) return void 0;
|
|
1159
|
+
throw error;
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
function target(ref) {
|
|
1163
|
+
const row = manager.store.findConnection(ref.providerId);
|
|
1164
|
+
if (!row) return void 0;
|
|
1165
|
+
const provider = manager.registries.models.entry(row.type);
|
|
1166
|
+
const selected = manager.store.findChannel(ref.providerId, "image");
|
|
1167
|
+
const capability = manager.registries.capabilities.entry("image");
|
|
1168
|
+
const protocol = selected && manager.registries.protocols.entry(selected.protocolId);
|
|
1169
|
+
if (!provider || !selected || !protocol || !capability || !protocol.type.adapters.image) return void 0;
|
|
1170
|
+
const configuredModels = manager.store.listBindings(ref.providerId, "image").filter((binding) => !binding.invalid).map((binding) => ({
|
|
1171
|
+
id: binding.ref.model,
|
|
1172
|
+
...binding.execution ? { execution: binding.execution } : {}
|
|
1173
|
+
}));
|
|
1174
|
+
const fingerprint = JSON.stringify([
|
|
1175
|
+
row.applicabilityRevision,
|
|
1176
|
+
row.enabled,
|
|
1177
|
+
selected.applicabilityRevision,
|
|
1178
|
+
configuredModels.find((model) => model.id === ref.model) ?? null,
|
|
1179
|
+
provider.registrationEpoch,
|
|
1180
|
+
protocol.registrationEpoch,
|
|
1181
|
+
capability.registrationEpoch
|
|
1182
|
+
]);
|
|
1183
|
+
const identityKey = JSON.stringify([ref.providerId, ref.model]);
|
|
1184
|
+
const prior = identities.get(identityKey);
|
|
1185
|
+
const revision = prior?.fingerprint === fingerprint ? prior.revision : (prior?.revision ?? 0) + 1;
|
|
1186
|
+
identities.set(identityKey, {
|
|
1187
|
+
fingerprint,
|
|
1188
|
+
revision
|
|
1189
|
+
});
|
|
1190
|
+
const original = protocol.type.adapters.image;
|
|
1191
|
+
const wrapped = {
|
|
1192
|
+
...protocol.type,
|
|
1193
|
+
adapters: {
|
|
1194
|
+
...protocol.type.adapters,
|
|
1195
|
+
image: {
|
|
1196
|
+
...original,
|
|
1197
|
+
createPort: () => ({ async generate(request, signal) {
|
|
1198
|
+
const session = sessionLease(request);
|
|
1199
|
+
const lease = await manager.acquire({
|
|
1200
|
+
...ref,
|
|
1201
|
+
capabilityId: "image"
|
|
1202
|
+
}, {
|
|
1203
|
+
signal,
|
|
1204
|
+
invocation: request.accounting,
|
|
1205
|
+
...session ? { session } : {}
|
|
1206
|
+
});
|
|
1207
|
+
try {
|
|
1208
|
+
return await (await lease.runtime.createPort()).generate(request, lease.signal);
|
|
1209
|
+
} finally {
|
|
1210
|
+
await lease.release().catch((error) => {
|
|
1211
|
+
if (!lease.signal.aborted) throw error;
|
|
1212
|
+
});
|
|
1213
|
+
}
|
|
1214
|
+
} })
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
};
|
|
1218
|
+
return {
|
|
1219
|
+
type: provider.type,
|
|
1220
|
+
protocol: wrapped,
|
|
1221
|
+
protocolEpoch: protocol.registrationEpoch,
|
|
1222
|
+
options: selected.options,
|
|
1223
|
+
owner: provider.owner,
|
|
1224
|
+
registrationEpoch: provider.registrationEpoch,
|
|
1225
|
+
lifetime: AbortSignal.any([
|
|
1226
|
+
provider.lifetime,
|
|
1227
|
+
protocol.lifetime,
|
|
1228
|
+
capability.lifetime
|
|
1229
|
+
]),
|
|
1230
|
+
enabled: row.enabled,
|
|
1231
|
+
config: {
|
|
1232
|
+
...row.config,
|
|
1233
|
+
endpointId: row.endpointId,
|
|
1234
|
+
protocolId: protocol.type.type
|
|
1235
|
+
},
|
|
1236
|
+
...row.headers.length ? { headers: Object.fromEntries(row.headers.map((one) => [one.name, one.value])) } : {},
|
|
1237
|
+
configuredModels,
|
|
1238
|
+
connectionRevision: revision
|
|
1239
|
+
};
|
|
1240
|
+
}
|
|
1241
|
+
function descriptors(providerId, found = target({
|
|
1242
|
+
providerId,
|
|
1243
|
+
model: ""
|
|
1244
|
+
})) {
|
|
1245
|
+
return found?.enabled ? generationModelsOf(found.protocol, {
|
|
1246
|
+
providerId,
|
|
1247
|
+
config: found.config,
|
|
1248
|
+
configuredModels: found.configuredModels
|
|
1249
|
+
}) : [];
|
|
1250
|
+
}
|
|
1251
|
+
function current(call) {
|
|
1252
|
+
const ref = session(call.sessionId)?.model;
|
|
1253
|
+
if (!ref) return null;
|
|
1254
|
+
const row = manager.store.findConnection(ref.providerId);
|
|
1255
|
+
const entry = row && manager.registries.models.entry(row.type);
|
|
1256
|
+
if (!row || !entry) return null;
|
|
1257
|
+
return {
|
|
1258
|
+
ref,
|
|
1259
|
+
type: row.type,
|
|
1260
|
+
owner: entry.owner,
|
|
1261
|
+
registrationEpoch: entry.registrationEpoch,
|
|
1262
|
+
connectionRevision: row.revision,
|
|
1263
|
+
loginState: null,
|
|
1264
|
+
chatInputKinds: []
|
|
1265
|
+
};
|
|
1266
|
+
}
|
|
1267
|
+
const approved = /* @__PURE__ */ new WeakMap();
|
|
1268
|
+
const generation = createGenerationHost({
|
|
1269
|
+
beginUsage: (call) => input.accounting?.begin({
|
|
1270
|
+
purpose: "image-generation",
|
|
1271
|
+
toolContext: call
|
|
1272
|
+
}),
|
|
1273
|
+
files: host.files,
|
|
1274
|
+
descriptors: generationModelsOf,
|
|
1275
|
+
authenticate: (owner, call) => host.contexts.authenticate(owner, call),
|
|
1276
|
+
current,
|
|
1277
|
+
target,
|
|
1278
|
+
connections(owner) {
|
|
1279
|
+
return manager.store.listConnections().flatMap((row) => {
|
|
1280
|
+
const entry = manager.registries.models.entry(row.type);
|
|
1281
|
+
if (!row.enabled || !entry || owner !== void 0 && entry.owner !== owner) return [];
|
|
1282
|
+
const found = target({
|
|
1283
|
+
providerId: row.providerId,
|
|
1284
|
+
model: ""
|
|
1285
|
+
});
|
|
1286
|
+
if (!found) return [];
|
|
1287
|
+
return [{
|
|
1288
|
+
providerId: row.providerId,
|
|
1289
|
+
type: row.type,
|
|
1290
|
+
owner: entry.owner,
|
|
1291
|
+
label: row.name,
|
|
1292
|
+
loginState: null,
|
|
1293
|
+
models: descriptors(row.providerId, found)
|
|
1294
|
+
}];
|
|
1295
|
+
});
|
|
1296
|
+
},
|
|
1297
|
+
credential(ref, type) {
|
|
1298
|
+
if (type.login && manager.connections().find((row) => row.providerId === ref.providerId)?.login?.state !== "signed-in") throw new GenerationFailure("not-signed-in", "Sign in to the selected connection in model settings.");
|
|
1299
|
+
const availability = manager.availability({
|
|
1300
|
+
...ref,
|
|
1301
|
+
capabilityId: "image"
|
|
1302
|
+
});
|
|
1303
|
+
if (!availability.available && availability.reason === "credential-unavailable") throw new GenerationFailure("credential-unavailable", "The connection credential is unavailable; check model settings.");
|
|
1304
|
+
return { secrets: {} };
|
|
1305
|
+
},
|
|
1306
|
+
sessionRevision: (id) => session(id)?.historyGeneration ?? -1,
|
|
1307
|
+
prepare: createGenerationInputReader({
|
|
1308
|
+
files: host.files,
|
|
1309
|
+
scope: input.fence,
|
|
1310
|
+
clientFiles: input.clientFiles,
|
|
1311
|
+
probeImage: host.media.probeImage,
|
|
1312
|
+
history: (call) => host.contexts.history(call)
|
|
1313
|
+
}),
|
|
1314
|
+
async authorize(ctx, origins) {
|
|
1315
|
+
ctx.signal.throwIfAborted();
|
|
1316
|
+
const needs = [];
|
|
1317
|
+
for (const origin of origins) {
|
|
1318
|
+
const grant = artifactOriginGrant(origin);
|
|
1319
|
+
if (!grant) return {
|
|
1320
|
+
kind: "refused",
|
|
1321
|
+
message: "artifact origins must be valid HTTPS declarations"
|
|
1322
|
+
};
|
|
1323
|
+
let host = grant.host;
|
|
1324
|
+
if (grant.exact) {
|
|
1325
|
+
const verdict = await deps.security.judgeAddress(origin);
|
|
1326
|
+
ctx.signal.throwIfAborted();
|
|
1327
|
+
if (verdict.kind !== "allowed") return {
|
|
1328
|
+
kind: "refused",
|
|
1329
|
+
message: "the artifact origin address was refused or unresolved"
|
|
1330
|
+
};
|
|
1331
|
+
host = verdict.host;
|
|
1332
|
+
}
|
|
1333
|
+
if (!deps.security.holdsHost(host, grant.port, "connect")) needs.push({
|
|
1334
|
+
host,
|
|
1335
|
+
port: grant.port
|
|
1336
|
+
});
|
|
1337
|
+
}
|
|
1338
|
+
ctx.signal.throwIfAborted();
|
|
1339
|
+
if (needs.length) {
|
|
1340
|
+
const decision = deps.approval.decide(ctx, {
|
|
1341
|
+
id: "generationArtifactOrigins",
|
|
1342
|
+
subject: "Download generated media",
|
|
1343
|
+
reason: "The provider will return generated media from these hosts.",
|
|
1344
|
+
targets: needs.map((one) => ({
|
|
1345
|
+
access: "connect",
|
|
1346
|
+
target: `${one.host}:${one.port}`
|
|
1347
|
+
})),
|
|
1348
|
+
accepts: [
|
|
1349
|
+
"allowed-once",
|
|
1350
|
+
"allowed-always",
|
|
1351
|
+
"rejected"
|
|
1352
|
+
],
|
|
1353
|
+
globalResource: true
|
|
1354
|
+
});
|
|
1355
|
+
if (decision.kind === "ask") {
|
|
1356
|
+
if ("awaitHuman" in decision.result) return {
|
|
1357
|
+
kind: "ask",
|
|
1358
|
+
result: decision.result
|
|
1359
|
+
};
|
|
1360
|
+
return {
|
|
1361
|
+
kind: "refused",
|
|
1362
|
+
message: "artifact authorization is unavailable"
|
|
1363
|
+
};
|
|
1364
|
+
}
|
|
1365
|
+
if (decision.result.kind !== "allowed-once" && decision.result.kind !== "allowed-always") return {
|
|
1366
|
+
kind: "refused",
|
|
1367
|
+
message: "artifact authorization was refused"
|
|
1368
|
+
};
|
|
1369
|
+
ctx.signal.throwIfAborted();
|
|
1370
|
+
if (decision.result.kind === "allowed-always") deps.security.recordHosts(needs.map((one) => ({
|
|
1371
|
+
host: one.host,
|
|
1372
|
+
port: one.port,
|
|
1373
|
+
operations: ["connect"]
|
|
1374
|
+
})));
|
|
1375
|
+
}
|
|
1376
|
+
approved.set(ctx, new Set(origins));
|
|
1377
|
+
return { kind: "ready" };
|
|
1378
|
+
},
|
|
1379
|
+
artifacts(ctx, origins) {
|
|
1380
|
+
const reader = { async fetch(url, signal) {
|
|
1381
|
+
let currentUrl = url;
|
|
1382
|
+
for (let hop = 0; hop <= 5; hop++) {
|
|
1383
|
+
signal.throwIfAborted();
|
|
1384
|
+
const parsed = new URL(currentUrl);
|
|
1385
|
+
if (!artifactOriginMatches(origins, parsed.origin) || !artifactOriginMatches([...approved.get(ctx) ?? []], parsed.origin) || parsed.username || parsed.password) throw new GenerationFailure("forbidden", "the artifact URL has an unauthorized origin", "not-delivered");
|
|
1386
|
+
const address = await deps.security.judgeAddress(currentUrl);
|
|
1387
|
+
if (address.kind !== "allowed") throw new GenerationFailure("forbidden", "the artifact address was refused or unresolved", "not-delivered");
|
|
1388
|
+
signal.throwIfAborted();
|
|
1389
|
+
const response = await deps.transport({
|
|
1390
|
+
url: currentUrl,
|
|
1391
|
+
addresses: address.addresses,
|
|
1392
|
+
headers: {
|
|
1393
|
+
"user-agent": "yaoguang",
|
|
1394
|
+
accept: "*/*"
|
|
1395
|
+
},
|
|
1396
|
+
signal
|
|
1397
|
+
});
|
|
1398
|
+
if ([
|
|
1399
|
+
301,
|
|
1400
|
+
302,
|
|
1401
|
+
303,
|
|
1402
|
+
307,
|
|
1403
|
+
308
|
|
1404
|
+
].includes(response.status)) {
|
|
1405
|
+
response.cancel();
|
|
1406
|
+
if (hop === 5 || !response.headers.location) throw new GenerationFailure("network", "the artifact redirect limit was exceeded", "not-delivered");
|
|
1407
|
+
currentUrl = new URL(response.headers.location, currentUrl).href;
|
|
1408
|
+
continue;
|
|
1409
|
+
}
|
|
1410
|
+
if (signal.aborted) {
|
|
1411
|
+
response.cancel();
|
|
1412
|
+
signal.throwIfAborted();
|
|
1413
|
+
}
|
|
1414
|
+
return artifactResponse(response, signal);
|
|
1415
|
+
}
|
|
1416
|
+
throw new GenerationFailure("network", "the artifact download failed", "not-delivered");
|
|
1417
|
+
} };
|
|
1418
|
+
callers.set(reader, ctx);
|
|
1419
|
+
return reader;
|
|
1420
|
+
}
|
|
1421
|
+
});
|
|
1422
|
+
const dispose = manager.onChanged(() => generation.invalidate());
|
|
1423
|
+
ctx.onDispose(() => {
|
|
1424
|
+
dispose();
|
|
1425
|
+
});
|
|
1426
|
+
ctx.signal.addEventListener("abort", () => generation.stop(), { once: true });
|
|
1427
|
+
return {
|
|
1428
|
+
...generation,
|
|
1429
|
+
identity(ref) {
|
|
1430
|
+
const found = target(ref);
|
|
1431
|
+
return found?.enabled && !found.lifetime.aborted ? JSON.stringify([
|
|
1432
|
+
found.owner,
|
|
1433
|
+
found.registrationEpoch,
|
|
1434
|
+
found.protocolEpoch,
|
|
1435
|
+
found.connectionRevision
|
|
1436
|
+
]) : void 0;
|
|
1437
|
+
},
|
|
1438
|
+
availability(address, id) {
|
|
1439
|
+
const ref = id ? session(id)?.model ?? null : null;
|
|
1440
|
+
const row = ref ? manager.store.findConnection(ref.providerId) : void 0;
|
|
1441
|
+
const entry = row ? manager.registries.models.entry(row.type) : void 0;
|
|
1442
|
+
let toolsAllowed;
|
|
1443
|
+
let chatInputKinds = [];
|
|
1444
|
+
try {
|
|
1445
|
+
const policy = ctx.services.get("model-tool-policy").availability(address, id);
|
|
1446
|
+
toolsAllowed = policy.toolsAllowed;
|
|
1447
|
+
chatInputKinds = policy.chatInputKinds;
|
|
1448
|
+
} catch {}
|
|
1449
|
+
return {
|
|
1450
|
+
toolsAllowed,
|
|
1451
|
+
sessionId: id ?? "",
|
|
1452
|
+
address,
|
|
1453
|
+
model: ref,
|
|
1454
|
+
type: row?.type ?? null,
|
|
1455
|
+
owner: entry?.owner ?? null,
|
|
1456
|
+
chatInputKinds: [...chatInputKinds],
|
|
1457
|
+
generation: ref ? descriptors(ref.providerId).map(({ id, label, outputKinds }) => ({
|
|
1458
|
+
id,
|
|
1459
|
+
label,
|
|
1460
|
+
outputKinds
|
|
1461
|
+
})) : [],
|
|
1462
|
+
loginState: null
|
|
1463
|
+
};
|
|
1464
|
+
}
|
|
1465
|
+
};
|
|
1466
|
+
}
|
|
1467
|
+
function artifactResponse(response, signal) {
|
|
1468
|
+
const iterator = response.body?.[Symbol.asyncIterator]();
|
|
1469
|
+
let finished = false;
|
|
1470
|
+
let streamController;
|
|
1471
|
+
const release = () => {
|
|
1472
|
+
if (finished) return;
|
|
1473
|
+
finished = true;
|
|
1474
|
+
signal.removeEventListener("abort", abort);
|
|
1475
|
+
response.cancel();
|
|
1476
|
+
if (iterator?.return) Promise.resolve().then(() => iterator.return?.()).catch(() => void 0);
|
|
1477
|
+
};
|
|
1478
|
+
const abort = () => {
|
|
1479
|
+
release();
|
|
1480
|
+
streamController?.error(signal.reason);
|
|
1481
|
+
};
|
|
1482
|
+
const body = iterator ? new ReadableStream({
|
|
1483
|
+
start(controller) {
|
|
1484
|
+
streamController = controller;
|
|
1485
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
1486
|
+
if (signal.aborted) abort();
|
|
1487
|
+
},
|
|
1488
|
+
async pull(controller) {
|
|
1489
|
+
try {
|
|
1490
|
+
signal.throwIfAborted();
|
|
1491
|
+
const next = await iterator.next();
|
|
1492
|
+
signal.throwIfAborted();
|
|
1493
|
+
if (finished) return;
|
|
1494
|
+
if (next.done) {
|
|
1495
|
+
controller.close();
|
|
1496
|
+
release();
|
|
1497
|
+
} else controller.enqueue(next.value);
|
|
1498
|
+
} catch (error) {
|
|
1499
|
+
if (!finished) controller.error(error);
|
|
1500
|
+
release();
|
|
1501
|
+
}
|
|
1502
|
+
},
|
|
1503
|
+
cancel() {
|
|
1504
|
+
release();
|
|
1505
|
+
}
|
|
1506
|
+
}) : null;
|
|
1507
|
+
if (body === null) release();
|
|
1508
|
+
try {
|
|
1509
|
+
return new Response(body, {
|
|
1510
|
+
status: response.status,
|
|
1511
|
+
statusText: response.statusText,
|
|
1512
|
+
headers: Object.fromEntries(Object.entries(response.headers).filter((entry) => entry[1] !== void 0))
|
|
1513
|
+
});
|
|
1514
|
+
} catch (error) {
|
|
1515
|
+
release();
|
|
1516
|
+
throw error;
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
//#endregion
|
|
1520
|
+
//#region src/index.ts
|
|
1521
|
+
const TOOL_NAMES = ["model_image_generate"];
|
|
1522
|
+
const ImageToolConfig = z.strictObject({ disabled: z.array(z.enum(TOOL_NAMES)).default([]) }).default({ disabled: [] });
|
|
1523
|
+
const plugin = {
|
|
1524
|
+
name: "@eum-agent/llm-capability-image",
|
|
1525
|
+
requires: [
|
|
1526
|
+
"model-management",
|
|
1527
|
+
"agent-capability-host",
|
|
1528
|
+
"approval",
|
|
1529
|
+
"fence",
|
|
1530
|
+
"client-files"
|
|
1531
|
+
],
|
|
1532
|
+
optionalServices: ["usage-accounting", "session-lifecycle"],
|
|
1533
|
+
provides: ["generation-runtime"],
|
|
1534
|
+
configSchema: ImageToolConfig,
|
|
1535
|
+
apply(ctx, config) {
|
|
1536
|
+
ctx.modelCapabilities.register({
|
|
1537
|
+
...imageCapability,
|
|
1538
|
+
tools: config.disabled.includes("model_image_generate") ? [] : TOOL_NAMES
|
|
1539
|
+
});
|
|
1540
|
+
const manager = ctx.services.get("model-management");
|
|
1541
|
+
const generation = createGenerationServices({
|
|
1542
|
+
accounting: ctx.services.find("usage-accounting"),
|
|
1543
|
+
ctx,
|
|
1544
|
+
manager,
|
|
1545
|
+
host: ctx.services.get("agent-capability-host"),
|
|
1546
|
+
approval: ctx.services.get("approval"),
|
|
1547
|
+
fence: ctx.services.get("fence"),
|
|
1548
|
+
clientFiles: ctx.services.get("client-files")
|
|
1549
|
+
});
|
|
1550
|
+
ctx.services.provide("generation-runtime", {
|
|
1551
|
+
bind: generation.bind,
|
|
1552
|
+
bindInputs: generation.bindInputs,
|
|
1553
|
+
availability: generation.availability,
|
|
1554
|
+
invalidate: generation.invalidate
|
|
1555
|
+
});
|
|
1556
|
+
if (!config.disabled.includes("model_image_generate")) ctx.tools.register(imageGenerationTool({
|
|
1557
|
+
generation: generation.bindCoordinator(ctx.pluginName),
|
|
1558
|
+
inputs: generation.bindInputs(ctx.pluginName),
|
|
1559
|
+
defaultModel: () => {
|
|
1560
|
+
const ref = manager.store.getDefault("image")?.ref;
|
|
1561
|
+
return ref ? {
|
|
1562
|
+
providerId: ref.providerId,
|
|
1563
|
+
model: ref.model
|
|
1564
|
+
} : null;
|
|
1565
|
+
},
|
|
1566
|
+
params: (ref, operation) => manager.store.findBinding({
|
|
1567
|
+
...ref,
|
|
1568
|
+
capabilityId: "image"
|
|
1569
|
+
})?.params[operation] ?? {},
|
|
1570
|
+
identity: generation.identity
|
|
1571
|
+
}));
|
|
1572
|
+
ctx.tools.guide(GUIDANCE);
|
|
1573
|
+
const ui = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
|
|
1574
|
+
if (existsSync(ui)) ctx.client.registerPackageFiles({
|
|
1575
|
+
root: dirname(ui),
|
|
1576
|
+
entry: "ui.js"
|
|
1577
|
+
});
|
|
1578
|
+
}
|
|
1579
|
+
};
|
|
1580
|
+
//#endregion
|
|
1581
|
+
export { ImageToolConfig, TOOL_NAMES, plugin as default };
|