pi-openai-toolkit 0.7.2 → 0.9.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/README.md +81 -8
- package/README_zh.md +84 -8
- package/extensions/auto-mode.ts +1 -0
- package/extensions/image-generation.ts +1 -0
- package/package.json +27 -4
- package/src/auto-mode/extension.ts +273 -0
- package/src/auto-mode/policy.ts +77 -0
- package/src/auto-mode/reviewer.ts +239 -0
- package/src/auto-mode/types.ts +58 -0
- package/src/compact-client.ts +4 -51
- package/src/config.ts +128 -11
- package/src/extension-runtime.ts +12 -4
- package/src/image-generation/artifacts.ts +237 -0
- package/src/image-generation/client.ts +248 -0
- package/src/image-generation/eligibility.ts +18 -0
- package/src/image-generation/extension.ts +160 -0
- package/src/image-generation/protocol.ts +405 -0
- package/src/image-generation/references.ts +194 -0
- package/src/image-generation/render.ts +252 -0
- package/src/image-generation/service.ts +243 -0
- package/src/image-generation/types.ts +184 -0
- package/src/model-scope.ts +17 -0
- package/src/native-fallback.ts +19 -6
- package/src/remote-v2-client.ts +7 -51
- package/src/responses-headers.ts +67 -0
- package/src/runtime.ts +43 -4
- package/src/types.ts +65 -9
- package/src/web-search/types.ts +3 -5
- package/tsconfig.check.json +17 -0
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import { readFileSync, realpathSync, statSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
3
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
4
|
+
import {
|
|
5
|
+
getAgentDir,
|
|
6
|
+
type Theme,
|
|
7
|
+
type ToolRenderResultOptions,
|
|
8
|
+
} from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import {
|
|
10
|
+
Container,
|
|
11
|
+
getCapabilities,
|
|
12
|
+
Image,
|
|
13
|
+
Spacer,
|
|
14
|
+
Text,
|
|
15
|
+
type Component,
|
|
16
|
+
} from "@earendil-works/pi-tui";
|
|
17
|
+
import { getGeneratedImagesRoot } from "./artifacts";
|
|
18
|
+
import { isValidPng, readPngDimensions } from "./protocol";
|
|
19
|
+
import {
|
|
20
|
+
IMAGE_GENERATION_MIME_TYPE,
|
|
21
|
+
MAX_GENERATED_IMAGE_BYTES,
|
|
22
|
+
isImageGenerationDetails,
|
|
23
|
+
type GenerateImageParams,
|
|
24
|
+
type ImageGenerationDetails,
|
|
25
|
+
} from "./types";
|
|
26
|
+
|
|
27
|
+
export type ImageGenerationRenderState = Record<string, never>;
|
|
28
|
+
|
|
29
|
+
export type ImageGenerationRenderContext = {
|
|
30
|
+
lastComponent: Component | undefined;
|
|
31
|
+
showImages: boolean;
|
|
32
|
+
isError: boolean;
|
|
33
|
+
isPartial: boolean;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
export type ImageRendererDependencies = {
|
|
37
|
+
getAgentDir: () => string;
|
|
38
|
+
getCapabilities: typeof getCapabilities;
|
|
39
|
+
readFileSync: typeof readFileSync;
|
|
40
|
+
realpathSync: typeof realpathSync;
|
|
41
|
+
statSync: typeof statSync;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const DEFAULT_RENDER_DEPS: ImageRendererDependencies = {
|
|
45
|
+
getAgentDir,
|
|
46
|
+
getCapabilities,
|
|
47
|
+
readFileSync,
|
|
48
|
+
realpathSync,
|
|
49
|
+
statSync,
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
function isPathInsideOrEqual(root: string, candidate: string): boolean {
|
|
53
|
+
const rel = relative(root, candidate);
|
|
54
|
+
return rel === "" || (!rel.startsWith(`..${sep}`) && rel !== ".." && !isAbsolute(rel));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function resultText(result: AgentToolResult<ImageGenerationDetails>): string {
|
|
58
|
+
return result.content
|
|
59
|
+
.filter((block): block is { type: "text"; text: string } => block.type === "text")
|
|
60
|
+
.map((block) => block.text)
|
|
61
|
+
.join("\n")
|
|
62
|
+
.trim();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
class DiskBackedImageResult extends Container {
|
|
66
|
+
readonly artifactPath?: string;
|
|
67
|
+
readonly fileSize?: number;
|
|
68
|
+
readonly mtimeMs?: number;
|
|
69
|
+
readonly showImages: boolean;
|
|
70
|
+
readonly textValue: string;
|
|
71
|
+
|
|
72
|
+
constructor(args: {
|
|
73
|
+
text: string;
|
|
74
|
+
artifactPath?: string;
|
|
75
|
+
fileSize?: number;
|
|
76
|
+
mtimeMs?: number;
|
|
77
|
+
showImages: boolean;
|
|
78
|
+
base64?: string;
|
|
79
|
+
theme: Theme;
|
|
80
|
+
previewWarning?: string;
|
|
81
|
+
}) {
|
|
82
|
+
super();
|
|
83
|
+
this.artifactPath = args.artifactPath;
|
|
84
|
+
this.fileSize = args.fileSize;
|
|
85
|
+
this.mtimeMs = args.mtimeMs;
|
|
86
|
+
this.showImages = args.showImages;
|
|
87
|
+
this.textValue = `${args.text}\n${args.previewWarning ?? ""}`;
|
|
88
|
+
this.addChild(new Text(args.theme.fg("toolOutput", args.text), 0, 0));
|
|
89
|
+
if (args.previewWarning) {
|
|
90
|
+
this.addChild(new Text(args.theme.fg("muted", args.previewWarning), 0, 0));
|
|
91
|
+
}
|
|
92
|
+
if (args.base64) {
|
|
93
|
+
this.addChild(new Spacer(1));
|
|
94
|
+
this.addChild(
|
|
95
|
+
new Image(
|
|
96
|
+
args.base64,
|
|
97
|
+
IMAGE_GENERATION_MIME_TYPE,
|
|
98
|
+
{ fallbackColor: (text) => args.theme.fg("toolOutput", text) },
|
|
99
|
+
{ maxWidthCells: 60, filename: args.artifactPath },
|
|
100
|
+
),
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
matches(args: {
|
|
106
|
+
text: string;
|
|
107
|
+
artifactPath?: string;
|
|
108
|
+
fileSize?: number;
|
|
109
|
+
mtimeMs?: number;
|
|
110
|
+
showImages: boolean;
|
|
111
|
+
previewWarning?: string;
|
|
112
|
+
}): boolean {
|
|
113
|
+
return (
|
|
114
|
+
this.textValue === `${args.text}\n${args.previewWarning ?? ""}` &&
|
|
115
|
+
this.artifactPath === args.artifactPath &&
|
|
116
|
+
this.fileSize === args.fileSize &&
|
|
117
|
+
this.mtimeMs === args.mtimeMs &&
|
|
118
|
+
this.showImages === args.showImages
|
|
119
|
+
);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function textOnly(args: {
|
|
124
|
+
text: string;
|
|
125
|
+
theme: Theme;
|
|
126
|
+
context: ImageGenerationRenderContext;
|
|
127
|
+
previewWarning?: string;
|
|
128
|
+
}): Component {
|
|
129
|
+
const previous = args.context.lastComponent;
|
|
130
|
+
if (
|
|
131
|
+
previous instanceof DiskBackedImageResult &&
|
|
132
|
+
previous.matches({
|
|
133
|
+
text: args.text,
|
|
134
|
+
showImages: false,
|
|
135
|
+
previewWarning: args.previewWarning,
|
|
136
|
+
})
|
|
137
|
+
) {
|
|
138
|
+
return previous;
|
|
139
|
+
}
|
|
140
|
+
return new DiskBackedImageResult({
|
|
141
|
+
text: args.text,
|
|
142
|
+
showImages: false,
|
|
143
|
+
theme: args.theme,
|
|
144
|
+
previewWarning: args.previewWarning,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function createImageGenerationResultRenderer(
|
|
149
|
+
deps: ImageRendererDependencies = DEFAULT_RENDER_DEPS,
|
|
150
|
+
): (
|
|
151
|
+
result: AgentToolResult<ImageGenerationDetails>,
|
|
152
|
+
options: ToolRenderResultOptions,
|
|
153
|
+
theme: Theme,
|
|
154
|
+
context: ImageGenerationRenderContext,
|
|
155
|
+
) => Component {
|
|
156
|
+
return (result, _options, theme, context) => {
|
|
157
|
+
const text = resultText(result) || "Image generation finished.";
|
|
158
|
+
if (
|
|
159
|
+
context.isError ||
|
|
160
|
+
context.isPartial ||
|
|
161
|
+
!context.showImages ||
|
|
162
|
+
!isImageGenerationDetails(result.details) ||
|
|
163
|
+
!deps.getCapabilities().images
|
|
164
|
+
) {
|
|
165
|
+
return textOnly({ text, theme, context });
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const artifactPath = resolve(result.details.artifactPath);
|
|
169
|
+
let root: string;
|
|
170
|
+
let realArtifact: string;
|
|
171
|
+
let info: ReturnType<typeof statSync>;
|
|
172
|
+
try {
|
|
173
|
+
root = deps.realpathSync(getGeneratedImagesRoot(deps.getAgentDir()));
|
|
174
|
+
realArtifact = deps.realpathSync(artifactPath);
|
|
175
|
+
info = deps.statSync(realArtifact);
|
|
176
|
+
} catch {
|
|
177
|
+
return textOnly({
|
|
178
|
+
text,
|
|
179
|
+
theme,
|
|
180
|
+
context,
|
|
181
|
+
previewWarning: "Image preview unavailable: the saved artifact is missing.",
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (
|
|
186
|
+
!isPathInsideOrEqual(root, realArtifact) ||
|
|
187
|
+
!info.isFile() ||
|
|
188
|
+
info.size <= 0 ||
|
|
189
|
+
info.size > MAX_GENERATED_IMAGE_BYTES
|
|
190
|
+
) {
|
|
191
|
+
return textOnly({
|
|
192
|
+
text,
|
|
193
|
+
theme,
|
|
194
|
+
context,
|
|
195
|
+
previewWarning: "Image preview unavailable: the artifact path or file is not safe.",
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const previous = context.lastComponent;
|
|
200
|
+
if (
|
|
201
|
+
previous instanceof DiskBackedImageResult &&
|
|
202
|
+
previous.matches({
|
|
203
|
+
text,
|
|
204
|
+
artifactPath: realArtifact,
|
|
205
|
+
fileSize: info.size,
|
|
206
|
+
mtimeMs: info.mtimeMs,
|
|
207
|
+
showImages: true,
|
|
208
|
+
})
|
|
209
|
+
) {
|
|
210
|
+
return previous;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
let bytes: Buffer;
|
|
214
|
+
try {
|
|
215
|
+
bytes = deps.readFileSync(realArtifact);
|
|
216
|
+
} catch {
|
|
217
|
+
return textOnly({
|
|
218
|
+
text,
|
|
219
|
+
theme,
|
|
220
|
+
context,
|
|
221
|
+
previewWarning: "Image preview unavailable: the artifact could not be read.",
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
if (bytes.length !== info.size || !isValidPng(bytes) || !readPngDimensions(bytes)) {
|
|
225
|
+
bytes.fill(0);
|
|
226
|
+
return textOnly({
|
|
227
|
+
text,
|
|
228
|
+
theme,
|
|
229
|
+
context,
|
|
230
|
+
previewWarning: "Image preview unavailable: the artifact is not a valid PNG.",
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
const base64 = bytes.toString("base64");
|
|
234
|
+
bytes.fill(0);
|
|
235
|
+
return new DiskBackedImageResult({
|
|
236
|
+
text,
|
|
237
|
+
artifactPath: realArtifact,
|
|
238
|
+
fileSize: info.size,
|
|
239
|
+
mtimeMs: info.mtimeMs,
|
|
240
|
+
showImages: true,
|
|
241
|
+
base64,
|
|
242
|
+
theme,
|
|
243
|
+
});
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export const renderImageGenerationResult = createImageGenerationResultRenderer();
|
|
248
|
+
|
|
249
|
+
export const _renderTest = {
|
|
250
|
+
DiskBackedImageResult,
|
|
251
|
+
isPathInsideOrEqual,
|
|
252
|
+
};
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { getAgentDir, type ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { loadToolkitConfig } from "../config";
|
|
3
|
+
import { resolveResponsesEnvironment } from "../runtime";
|
|
4
|
+
import {
|
|
5
|
+
copyImageToExplicitPath,
|
|
6
|
+
prepareExplicitOutputPath,
|
|
7
|
+
saveCanonicalImage,
|
|
8
|
+
} from "./artifacts";
|
|
9
|
+
import { requestGeneratedImage } from "./client";
|
|
10
|
+
import { isImageGenerationEnabledForModel } from "./eligibility";
|
|
11
|
+
import {
|
|
12
|
+
buildImageGenerationRequest,
|
|
13
|
+
normalizeGenerateImageParams,
|
|
14
|
+
} from "./protocol";
|
|
15
|
+
import {
|
|
16
|
+
clearPreparedReferences,
|
|
17
|
+
prepareReferenceImages,
|
|
18
|
+
} from "./references";
|
|
19
|
+
import {
|
|
20
|
+
IMAGE_GENERATION_CAPABLE_APIS,
|
|
21
|
+
IMAGE_GENERATION_MIME_TYPE,
|
|
22
|
+
IMAGE_GENERATION_MODEL,
|
|
23
|
+
ImageGenerationError,
|
|
24
|
+
sanitizeImageDiagnostic,
|
|
25
|
+
type GenerateImageParams,
|
|
26
|
+
type ImageGenerationExecutionResult,
|
|
27
|
+
type ImageGenerationFailureCode,
|
|
28
|
+
type ParsedGeneratedImage,
|
|
29
|
+
} from "./types";
|
|
30
|
+
|
|
31
|
+
export type ImageGenerationServiceDependencies = {
|
|
32
|
+
loadConfig: typeof loadToolkitConfig;
|
|
33
|
+
resolveRuntime: typeof resolveResponsesEnvironment;
|
|
34
|
+
getAgentDir: typeof getAgentDir;
|
|
35
|
+
prepareOutput: typeof prepareExplicitOutputPath;
|
|
36
|
+
prepareReferences: typeof prepareReferenceImages;
|
|
37
|
+
requestImage: typeof requestGeneratedImage;
|
|
38
|
+
saveCanonical: typeof saveCanonicalImage;
|
|
39
|
+
copyExplicit: typeof copyImageToExplicitPath;
|
|
40
|
+
clearReferences: typeof clearPreparedReferences;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const DEFAULT_SERVICE_DEPS: ImageGenerationServiceDependencies = {
|
|
44
|
+
loadConfig: loadToolkitConfig,
|
|
45
|
+
resolveRuntime: resolveResponsesEnvironment,
|
|
46
|
+
getAgentDir,
|
|
47
|
+
prepareOutput: prepareExplicitOutputPath,
|
|
48
|
+
prepareReferences: prepareReferenceImages,
|
|
49
|
+
requestImage: requestGeneratedImage,
|
|
50
|
+
saveCanonical: saveCanonicalImage,
|
|
51
|
+
copyExplicit: copyImageToExplicitPath,
|
|
52
|
+
clearReferences: clearPreparedReferences,
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
function runtimeFailure(
|
|
56
|
+
reason: string,
|
|
57
|
+
errorMessage?: string,
|
|
58
|
+
): ImageGenerationError {
|
|
59
|
+
switch (reason) {
|
|
60
|
+
case "disabled":
|
|
61
|
+
return new ImageGenerationError("disabled", "Image generation is disabled.");
|
|
62
|
+
case "unsupported-api":
|
|
63
|
+
case "missing-model":
|
|
64
|
+
return new ImageGenerationError(
|
|
65
|
+
"unsupported-model",
|
|
66
|
+
"Image generation is unavailable for the current model.",
|
|
67
|
+
);
|
|
68
|
+
case "missing-api-key":
|
|
69
|
+
case "auth-resolution-failed":
|
|
70
|
+
return new ImageGenerationError(
|
|
71
|
+
"authentication",
|
|
72
|
+
sanitizeImageDiagnostic(
|
|
73
|
+
errorMessage,
|
|
74
|
+
"Unable to resolve authentication for image generation with the current model.",
|
|
75
|
+
),
|
|
76
|
+
);
|
|
77
|
+
default:
|
|
78
|
+
return new ImageGenerationError(
|
|
79
|
+
"missing-runtime",
|
|
80
|
+
"Unable to resolve the current model's Responses endpoint for image generation.",
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function throwIfAborted(signal: AbortSignal | undefined): void {
|
|
86
|
+
if (signal?.aborted) {
|
|
87
|
+
throw new ImageGenerationError("aborted", "Image generation was cancelled.");
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function clientFailureCode(reason: string): ImageGenerationFailureCode {
|
|
92
|
+
switch (reason) {
|
|
93
|
+
case "aborted":
|
|
94
|
+
case "timeout":
|
|
95
|
+
case "authentication":
|
|
96
|
+
case "rate-limit":
|
|
97
|
+
case "request-rejected":
|
|
98
|
+
case "backend-unavailable":
|
|
99
|
+
case "network":
|
|
100
|
+
case "oversized-response":
|
|
101
|
+
case "malformed-response":
|
|
102
|
+
case "no-image":
|
|
103
|
+
return reason;
|
|
104
|
+
default:
|
|
105
|
+
return "network";
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function formatResultText(args: {
|
|
110
|
+
artifactPath: string;
|
|
111
|
+
outputPath?: string;
|
|
112
|
+
warning?: string;
|
|
113
|
+
edited: boolean;
|
|
114
|
+
width: number;
|
|
115
|
+
height: number;
|
|
116
|
+
}): string {
|
|
117
|
+
const lines = [
|
|
118
|
+
`${args.edited ? "Edited" : "Generated"} PNG image (${args.width}x${args.height}).`,
|
|
119
|
+
`Artifact: ${args.artifactPath}`,
|
|
120
|
+
];
|
|
121
|
+
if (args.outputPath) lines.push(`Copied to: ${args.outputPath}`);
|
|
122
|
+
if (args.warning) lines.push(`Warning: ${args.warning}`);
|
|
123
|
+
return lines.join("\n");
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function createImageGenerationExecutor(
|
|
127
|
+
deps: ImageGenerationServiceDependencies = DEFAULT_SERVICE_DEPS,
|
|
128
|
+
): (args: {
|
|
129
|
+
params: GenerateImageParams;
|
|
130
|
+
toolCallId: string;
|
|
131
|
+
signal?: AbortSignal;
|
|
132
|
+
ctx: ExtensionContext;
|
|
133
|
+
}) => Promise<ImageGenerationExecutionResult> {
|
|
134
|
+
return async (args) => {
|
|
135
|
+
const params = normalizeGenerateImageParams(args.params);
|
|
136
|
+
throwIfAborted(args.signal);
|
|
137
|
+
const { config } = deps.loadConfig();
|
|
138
|
+
if (!isImageGenerationEnabledForModel(args.ctx.model, config.imageGeneration)) {
|
|
139
|
+
throw new ImageGenerationError(
|
|
140
|
+
"unsupported-model",
|
|
141
|
+
"Image generation is not enabled for the current provider/model-id.",
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const runtimeResolution = await deps.resolveRuntime(args.ctx, {
|
|
146
|
+
enabled: config.imageGeneration.enabled,
|
|
147
|
+
responsesApis: IMAGE_GENERATION_CAPABLE_APIS,
|
|
148
|
+
});
|
|
149
|
+
if (!runtimeResolution.ok) {
|
|
150
|
+
throw runtimeFailure(runtimeResolution.reason, runtimeResolution.errorMessage);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const agentDir = deps.getAgentDir();
|
|
154
|
+
const explicitOutput = await deps.prepareOutput({
|
|
155
|
+
rawPath: params.outputPath,
|
|
156
|
+
agentDir,
|
|
157
|
+
ctx: args.ctx,
|
|
158
|
+
signal: args.signal,
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
const references = await deps.prepareReferences({
|
|
162
|
+
paths: params.referenceImagePaths,
|
|
163
|
+
ctx: args.ctx,
|
|
164
|
+
signal: args.signal,
|
|
165
|
+
});
|
|
166
|
+
let generated: ParsedGeneratedImage | undefined;
|
|
167
|
+
try {
|
|
168
|
+
throwIfAborted(args.signal);
|
|
169
|
+
const body = buildImageGenerationRequest({
|
|
170
|
+
routingModel: runtimeResolution.runtime.model,
|
|
171
|
+
params,
|
|
172
|
+
references,
|
|
173
|
+
});
|
|
174
|
+
const response = await deps.requestImage({
|
|
175
|
+
runtime: runtimeResolution.runtime,
|
|
176
|
+
body,
|
|
177
|
+
signal: args.signal,
|
|
178
|
+
});
|
|
179
|
+
if (!response.ok) {
|
|
180
|
+
throw new ImageGenerationError(
|
|
181
|
+
clientFailureCode(response.reason),
|
|
182
|
+
response.errorMessage,
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
generated = response.image;
|
|
186
|
+
|
|
187
|
+
const artifactPath = await deps.saveCanonical({
|
|
188
|
+
bytes: generated.bytes,
|
|
189
|
+
agentDir,
|
|
190
|
+
sessionId: args.ctx.sessionManager.getSessionId(),
|
|
191
|
+
imageCallId: generated.imageCallId || args.toolCallId,
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
let outputPath: string | undefined;
|
|
195
|
+
let warning: string | undefined;
|
|
196
|
+
if (explicitOutput) {
|
|
197
|
+
try {
|
|
198
|
+
await deps.copyExplicit({ bytes: generated.bytes, plan: explicitOutput });
|
|
199
|
+
outputPath = explicitOutput.path;
|
|
200
|
+
} catch (error) {
|
|
201
|
+
warning = sanitizeImageDiagnostic(
|
|
202
|
+
error instanceof Error ? error.message : error,
|
|
203
|
+
`The generated image was saved to the canonical artifact, but copying to ${explicitOutput.path} failed.`,
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
const edited = references.length > 0;
|
|
209
|
+
const details = {
|
|
210
|
+
artifactPath,
|
|
211
|
+
...(outputPath ? { outputPath } : {}),
|
|
212
|
+
routingModel: `${runtimeResolution.runtime.provider}/${runtimeResolution.runtime.model}`,
|
|
213
|
+
imageModel: IMAGE_GENERATION_MODEL,
|
|
214
|
+
imageCallId: generated.imageCallId,
|
|
215
|
+
...(generated.responseId ? { responseId: generated.responseId } : {}),
|
|
216
|
+
mimeType: IMAGE_GENERATION_MIME_TYPE,
|
|
217
|
+
byteCount: generated.bytes.length,
|
|
218
|
+
width: generated.width,
|
|
219
|
+
height: generated.height,
|
|
220
|
+
edited,
|
|
221
|
+
referenceCount: references.length,
|
|
222
|
+
...(generated.revisedPrompt ? { revisedPrompt: generated.revisedPrompt } : {}),
|
|
223
|
+
...(warning ? { warning } : {}),
|
|
224
|
+
};
|
|
225
|
+
return {
|
|
226
|
+
details,
|
|
227
|
+
text: formatResultText({
|
|
228
|
+
artifactPath,
|
|
229
|
+
outputPath,
|
|
230
|
+
warning,
|
|
231
|
+
edited,
|
|
232
|
+
width: generated.width,
|
|
233
|
+
height: generated.height,
|
|
234
|
+
}),
|
|
235
|
+
};
|
|
236
|
+
} finally {
|
|
237
|
+
deps.clearReferences(references);
|
|
238
|
+
generated?.bytes.fill(0);
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export const executeImageGeneration = createImageGenerationExecutor();
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
export const IMAGE_GENERATION_TOOL_NAME = "openai_generate_image";
|
|
2
|
+
export const IMAGE_GENERATION_MODEL = "gpt-image-2" as const;
|
|
3
|
+
export const IMAGE_GENERATION_MIME_TYPE = "image/png" as const;
|
|
4
|
+
export const IMAGE_GENERATION_CAPABLE_APIS = [
|
|
5
|
+
"openai-responses",
|
|
6
|
+
"openai-codex-responses",
|
|
7
|
+
] as const;
|
|
8
|
+
export const IMAGE_GENERATION_SIZES = [
|
|
9
|
+
"auto",
|
|
10
|
+
"1024x1024",
|
|
11
|
+
"1536x1024",
|
|
12
|
+
"1024x1536",
|
|
13
|
+
] as const;
|
|
14
|
+
export const IMAGE_GENERATION_QUALITIES = ["auto", "low", "medium", "high"] as const;
|
|
15
|
+
|
|
16
|
+
export const MAX_IMAGE_PROMPT_CHARS = 20_000;
|
|
17
|
+
export const MAX_REFERENCE_IMAGE_COUNT = 5;
|
|
18
|
+
export const MAX_REFERENCE_IMAGE_BYTES = 20 * 1024 * 1024;
|
|
19
|
+
export const MAX_TOTAL_REFERENCE_IMAGE_BYTES = 50 * 1024 * 1024;
|
|
20
|
+
export const MAX_GENERATED_IMAGE_BYTES = 32 * 1024 * 1024;
|
|
21
|
+
export const MAX_IMAGE_RESPONSE_BYTES = 48 * 1024 * 1024;
|
|
22
|
+
export const MAX_IMAGE_ERROR_BYTES = 64 * 1024;
|
|
23
|
+
export const IMAGE_REQUEST_TIMEOUT_MS = 5 * 60 * 1000;
|
|
24
|
+
export const MAX_IMAGE_PATH_CHARS = 4096;
|
|
25
|
+
export const MAX_IMAGE_DIAGNOSTIC_CHARS = 4096;
|
|
26
|
+
export const MAX_IMAGE_IDENTIFIER_CHARS = 256;
|
|
27
|
+
export const MAX_IMAGE_DIMENSION = 100_000;
|
|
28
|
+
|
|
29
|
+
export type ImageGenerationCapableApi = (typeof IMAGE_GENERATION_CAPABLE_APIS)[number];
|
|
30
|
+
export type ImageGenerationSize = (typeof IMAGE_GENERATION_SIZES)[number];
|
|
31
|
+
export type ImageGenerationQuality = (typeof IMAGE_GENERATION_QUALITIES)[number];
|
|
32
|
+
export type ImageGenerationAction = "generate" | "edit";
|
|
33
|
+
export type ReferenceImageMimeType = "image/png" | "image/jpeg" | "image/webp";
|
|
34
|
+
|
|
35
|
+
export type ImageGenerationModel = {
|
|
36
|
+
api?: string;
|
|
37
|
+
provider?: string;
|
|
38
|
+
id?: string;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export type GenerateImageParams = {
|
|
42
|
+
prompt: string;
|
|
43
|
+
referenceImagePaths?: string[] | null;
|
|
44
|
+
outputPath?: string | null;
|
|
45
|
+
size?: ImageGenerationSize;
|
|
46
|
+
quality?: ImageGenerationQuality;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export type NormalizedGenerateImageParams = {
|
|
50
|
+
prompt: string;
|
|
51
|
+
referenceImagePaths: string[];
|
|
52
|
+
outputPath?: string;
|
|
53
|
+
size: ImageGenerationSize;
|
|
54
|
+
quality: ImageGenerationQuality;
|
|
55
|
+
action: ImageGenerationAction;
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
export type PreparedReferenceImage = {
|
|
59
|
+
path: string;
|
|
60
|
+
mimeType: ReferenceImageMimeType;
|
|
61
|
+
bytes: Buffer;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export type ParsedGeneratedImage = {
|
|
65
|
+
bytes: Buffer;
|
|
66
|
+
imageCallId: string;
|
|
67
|
+
responseId?: string;
|
|
68
|
+
revisedPrompt?: string;
|
|
69
|
+
width: number;
|
|
70
|
+
height: number;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
export type ImageGenerationDetails = {
|
|
74
|
+
artifactPath: string;
|
|
75
|
+
outputPath?: string;
|
|
76
|
+
routingModel: string;
|
|
77
|
+
imageModel: typeof IMAGE_GENERATION_MODEL;
|
|
78
|
+
imageCallId: string;
|
|
79
|
+
responseId?: string;
|
|
80
|
+
mimeType: typeof IMAGE_GENERATION_MIME_TYPE;
|
|
81
|
+
byteCount: number;
|
|
82
|
+
width: number;
|
|
83
|
+
height: number;
|
|
84
|
+
edited: boolean;
|
|
85
|
+
referenceCount: number;
|
|
86
|
+
revisedPrompt?: string;
|
|
87
|
+
warning?: string;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
export type ImageGenerationExecutionResult = {
|
|
91
|
+
details: ImageGenerationDetails;
|
|
92
|
+
text: string;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
export type ImageGenerationFailureCode =
|
|
96
|
+
| "aborted"
|
|
97
|
+
| "timeout"
|
|
98
|
+
| "disabled"
|
|
99
|
+
| "unsupported-model"
|
|
100
|
+
| "missing-runtime"
|
|
101
|
+
| "invalid-parameters"
|
|
102
|
+
| "reference-input-invalid"
|
|
103
|
+
| "reference-upload-approval-required"
|
|
104
|
+
| "reference-upload-declined"
|
|
105
|
+
| "output-path-invalid"
|
|
106
|
+
| "output-path-approval-required"
|
|
107
|
+
| "output-path-declined"
|
|
108
|
+
| "authentication"
|
|
109
|
+
| "rate-limit"
|
|
110
|
+
| "request-rejected"
|
|
111
|
+
| "backend-unavailable"
|
|
112
|
+
| "network"
|
|
113
|
+
| "oversized-response"
|
|
114
|
+
| "malformed-response"
|
|
115
|
+
| "no-image"
|
|
116
|
+
| "artifact-write-failed";
|
|
117
|
+
|
|
118
|
+
export class ImageGenerationError extends Error {
|
|
119
|
+
readonly code: ImageGenerationFailureCode;
|
|
120
|
+
|
|
121
|
+
constructor(code: ImageGenerationFailureCode, message: string) {
|
|
122
|
+
super(message);
|
|
123
|
+
this.name = "ImageGenerationError";
|
|
124
|
+
this.code = code;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
129
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function isBoundedString(value: unknown, maxChars: number): value is string {
|
|
133
|
+
return typeof value === "string" && value.length > 0 && value.length <= maxChars;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function isImageGenerationDetails(value: unknown): value is ImageGenerationDetails {
|
|
137
|
+
if (!isRecord(value)) return false;
|
|
138
|
+
return (
|
|
139
|
+
isBoundedString(value.artifactPath, MAX_IMAGE_PATH_CHARS) &&
|
|
140
|
+
(value.outputPath === undefined || isBoundedString(value.outputPath, MAX_IMAGE_PATH_CHARS)) &&
|
|
141
|
+
isBoundedString(value.routingModel, MAX_IMAGE_DIAGNOSTIC_CHARS) &&
|
|
142
|
+
value.imageModel === IMAGE_GENERATION_MODEL &&
|
|
143
|
+
isBoundedString(value.imageCallId, MAX_IMAGE_IDENTIFIER_CHARS) &&
|
|
144
|
+
(value.responseId === undefined || isBoundedString(value.responseId, MAX_IMAGE_IDENTIFIER_CHARS)) &&
|
|
145
|
+
value.mimeType === IMAGE_GENERATION_MIME_TYPE &&
|
|
146
|
+
typeof value.byteCount === "number" &&
|
|
147
|
+
Number.isInteger(value.byteCount) &&
|
|
148
|
+
value.byteCount > 0 &&
|
|
149
|
+
value.byteCount <= MAX_GENERATED_IMAGE_BYTES &&
|
|
150
|
+
typeof value.width === "number" &&
|
|
151
|
+
Number.isInteger(value.width) &&
|
|
152
|
+
value.width > 0 &&
|
|
153
|
+
value.width <= MAX_IMAGE_DIMENSION &&
|
|
154
|
+
typeof value.height === "number" &&
|
|
155
|
+
Number.isInteger(value.height) &&
|
|
156
|
+
value.height > 0 &&
|
|
157
|
+
value.height <= MAX_IMAGE_DIMENSION &&
|
|
158
|
+
typeof value.edited === "boolean" &&
|
|
159
|
+
typeof value.referenceCount === "number" &&
|
|
160
|
+
Number.isInteger(value.referenceCount) &&
|
|
161
|
+
value.referenceCount >= 0 &&
|
|
162
|
+
value.referenceCount <= MAX_REFERENCE_IMAGE_COUNT &&
|
|
163
|
+
(value.revisedPrompt === undefined || isBoundedString(value.revisedPrompt, MAX_IMAGE_DIAGNOSTIC_CHARS)) &&
|
|
164
|
+
(value.warning === undefined || isBoundedString(value.warning, MAX_IMAGE_DIAGNOSTIC_CHARS))
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export function sanitizeImageDiagnostic(value: unknown, fallback: string): string {
|
|
169
|
+
if (typeof value !== "string") return fallback;
|
|
170
|
+
const normalized = value
|
|
171
|
+
.replace(/data:image\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/=]+/gi, "[REDACTED_IMAGE_DATA]")
|
|
172
|
+
.replace(/[A-Za-z0-9+/]{128,}={0,2}/g, "[REDACTED_BASE64]")
|
|
173
|
+
.replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer [REDACTED]")
|
|
174
|
+
.replace(
|
|
175
|
+
/\b(authorization|api[-_ ]?key|access[-_ ]?token|refresh[-_ ]?token|account[-_ ]?id|cookie)\s*[:=]\s*[^\s,;]+/gi,
|
|
176
|
+
"$1: [REDACTED]",
|
|
177
|
+
)
|
|
178
|
+
.replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g, "[REDACTED]")
|
|
179
|
+
.replace(/[\u0000-\u001f\u007f]+/g, " ")
|
|
180
|
+
.replace(/\s+/g, " ")
|
|
181
|
+
.trim();
|
|
182
|
+
if (!normalized) return fallback;
|
|
183
|
+
return normalized.slice(0, MAX_IMAGE_DIAGNOSTIC_CHARS);
|
|
184
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export type ExactModelScopeModel = {
|
|
2
|
+
provider?: string;
|
|
3
|
+
id?: string;
|
|
4
|
+
};
|
|
5
|
+
|
|
6
|
+
export function getExactModelKey(model: ExactModelScopeModel | undefined): string | undefined {
|
|
7
|
+
if (!model?.provider || !model.id) return undefined;
|
|
8
|
+
return `${model.provider}/${model.id}`;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function isExactModelAllowed(
|
|
12
|
+
model: ExactModelScopeModel | undefined,
|
|
13
|
+
allowlist: readonly string[],
|
|
14
|
+
): boolean {
|
|
15
|
+
const modelKey = getExactModelKey(model);
|
|
16
|
+
return modelKey !== undefined && allowlist.includes(modelKey);
|
|
17
|
+
}
|