Hermes Agent backup - 2026-06-02 04:28:40
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +3 -0
- baoyu_skills/baoyu-imagine/scripts/build-batch.test.ts +190 -0
- baoyu_skills/baoyu-imagine/scripts/build-batch.ts +239 -0
- baoyu_skills/baoyu-imagine/scripts/codex-imagegen/cache.ts +80 -0
- baoyu_skills/baoyu-imagine/scripts/codex-imagegen/logger.ts +39 -0
- baoyu_skills/baoyu-imagine/scripts/codex-imagegen/main.ts +326 -0
- baoyu_skills/baoyu-imagine/scripts/codex-imagegen/parser.ts +64 -0
- baoyu_skills/baoyu-imagine/scripts/codex-imagegen/spawn.ts +81 -0
- baoyu_skills/baoyu-imagine/scripts/codex-imagegen/types.ts +79 -0
- baoyu_skills/baoyu-imagine/scripts/codex-imagegen/validator.ts +55 -0
- baoyu_skills/baoyu-imagine/scripts/main.test.ts +623 -0
- baoyu_skills/baoyu-imagine/scripts/main.ts +1249 -0
- baoyu_skills/baoyu-imagine/scripts/providers/azure.test.ts +189 -0
- baoyu_skills/baoyu-imagine/scripts/providers/azure.ts +192 -0
- baoyu_skills/baoyu-imagine/scripts/providers/codex-cli.test.ts +62 -0
- baoyu_skills/baoyu-imagine/scripts/providers/codex-cli.ts +197 -0
- baoyu_skills/baoyu-imagine/scripts/providers/dashscope.test.ts +392 -0
- baoyu_skills/baoyu-imagine/scripts/providers/dashscope.ts +625 -0
- baoyu_skills/baoyu-imagine/scripts/providers/google.test.ts +130 -0
- baoyu_skills/baoyu-imagine/scripts/providers/google.ts +351 -0
- baoyu_skills/baoyu-imagine/scripts/providers/jimeng.test.ts +115 -0
- baoyu_skills/baoyu-imagine/scripts/providers/jimeng.ts +467 -0
- baoyu_skills/baoyu-imagine/scripts/providers/minimax.test.ts +175 -0
- baoyu_skills/baoyu-imagine/scripts/providers/minimax.ts +220 -0
- baoyu_skills/baoyu-imagine/scripts/providers/openai.test.ts +179 -0
- baoyu_skills/baoyu-imagine/scripts/providers/openai.ts +444 -0
- baoyu_skills/baoyu-imagine/scripts/providers/openrouter.test.ts +169 -0
- baoyu_skills/baoyu-imagine/scripts/providers/openrouter.ts +372 -0
- baoyu_skills/baoyu-imagine/scripts/providers/replicate.test.ts +310 -0
- baoyu_skills/baoyu-imagine/scripts/providers/replicate.ts +616 -0
- baoyu_skills/baoyu-imagine/scripts/providers/seedream.test.ts +245 -0
- baoyu_skills/baoyu-imagine/scripts/providers/seedream.ts +341 -0
- baoyu_skills/baoyu-imagine/scripts/providers/zai.test.ts +181 -0
- baoyu_skills/baoyu-imagine/scripts/providers/zai.ts +306 -0
- baoyu_skills/baoyu-imagine/scripts/types.ts +92 -0
- config/.env +5 -0
- config/config.yaml +80 -0
- cron/.tick.lock +0 -0
- logs/agent.log +41 -0
- logs/errors.log +5 -0
- logs/gateway-exit-diag.log +1 -0
- logs/gateway.log +18 -0
- metadata.json +5 -0
- personality/SOUL.md +1 -0
- skills/.bundled_manifest +90 -0
- skills/apikey-image-gen/SKILL.md +182 -0
- skills/apple/DESCRIPTION.md +2 -0
- skills/apple/apple-notes/SKILL.md +90 -0
- skills/apple/apple-reminders/SKILL.md +130 -0
- skills/apple/findmy/SKILL.md +131 -0
.gitattributes
CHANGED
|
@@ -58,3 +58,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
# Video files - compressed
|
| 59 |
*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
skills/research/research-paper-writing/templates/colm2025/colm2025_conference.pdf filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
skills/research/research-paper-writing/templates/iclr2026/iclr2026_conference.pdf filter=lfs diff=lfs merge=lfs -text
|
| 63 |
+
skills/research/research-paper-writing/templates/icml2026/example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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from "node:assert/strict";
|
| 2 |
+
import fs from "node:fs/promises";
|
| 3 |
+
import os from "node:os";
|
| 4 |
+
import path from "node:path";
|
| 5 |
+
import { execFile } from "node:child_process";
|
| 6 |
+
import { promisify } from "node:util";
|
| 7 |
+
import test from "node:test";
|
| 8 |
+
|
| 9 |
+
const execFileAsync = promisify(execFile);
|
| 10 |
+
const repoRoot = path.resolve(import.meta.dirname, "..", "..", "..");
|
| 11 |
+
const scriptPath = path.join(repoRoot, "skills", "baoyu-image-gen", "scripts", "build-batch.ts");
|
| 12 |
+
|
| 13 |
+
async function makeFixture(): Promise<{
|
| 14 |
+
root: string;
|
| 15 |
+
outlinePath: string;
|
| 16 |
+
promptsDir: string;
|
| 17 |
+
outputPath: string;
|
| 18 |
+
}> {
|
| 19 |
+
const root = await fs.mkdtemp(path.join(os.tmpdir(), "baoyu-image-gen-build-batch-"));
|
| 20 |
+
const outlinePath = path.join(root, "outline.md");
|
| 21 |
+
const promptsDir = path.join(root, "prompts");
|
| 22 |
+
const outputPath = path.join(root, "batch.json");
|
| 23 |
+
|
| 24 |
+
await fs.mkdir(promptsDir, { recursive: true });
|
| 25 |
+
await fs.writeFile(
|
| 26 |
+
outlinePath,
|
| 27 |
+
`## Illustration 1
|
| 28 |
+
**Position**: demo
|
| 29 |
+
**Purpose**: demo
|
| 30 |
+
**Visual Content**: demo
|
| 31 |
+
**Filename**: 01-demo.png
|
| 32 |
+
`,
|
| 33 |
+
);
|
| 34 |
+
await fs.writeFile(path.join(promptsDir, "01-demo.md"), "A demo prompt\n");
|
| 35 |
+
|
| 36 |
+
return { root, outlinePath, promptsDir, outputPath };
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
async function runBuildBatch(args: string[]): Promise<void> {
|
| 40 |
+
await execFileAsync(process.execPath, ["--import", "tsx", scriptPath, ...args], {
|
| 41 |
+
cwd: repoRoot,
|
| 42 |
+
});
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
test("build-batch omits default model so baoyu-image-gen can resolve env or EXTEND defaults", async () => {
|
| 46 |
+
const fixture = await makeFixture();
|
| 47 |
+
|
| 48 |
+
await runBuildBatch([
|
| 49 |
+
"--outline",
|
| 50 |
+
fixture.outlinePath,
|
| 51 |
+
"--prompts",
|
| 52 |
+
fixture.promptsDir,
|
| 53 |
+
"--output",
|
| 54 |
+
fixture.outputPath,
|
| 55 |
+
]);
|
| 56 |
+
|
| 57 |
+
const batch = JSON.parse(await fs.readFile(fixture.outputPath, "utf8")) as {
|
| 58 |
+
tasks: Array<Record<string, unknown>>;
|
| 59 |
+
};
|
| 60 |
+
|
| 61 |
+
assert.equal(batch.tasks.length, 1);
|
| 62 |
+
assert.equal(batch.tasks[0]?.provider, "replicate");
|
| 63 |
+
assert.equal(Object.hasOwn(batch.tasks[0]!, "model"), false);
|
| 64 |
+
});
|
| 65 |
+
|
| 66 |
+
test("build-batch preserves explicit model overrides", async () => {
|
| 67 |
+
const fixture = await makeFixture();
|
| 68 |
+
|
| 69 |
+
await runBuildBatch([
|
| 70 |
+
"--outline",
|
| 71 |
+
fixture.outlinePath,
|
| 72 |
+
"--prompts",
|
| 73 |
+
fixture.promptsDir,
|
| 74 |
+
"--output",
|
| 75 |
+
fixture.outputPath,
|
| 76 |
+
"--model",
|
| 77 |
+
"acme/custom-model",
|
| 78 |
+
]);
|
| 79 |
+
|
| 80 |
+
const batch = JSON.parse(await fs.readFile(fixture.outputPath, "utf8")) as {
|
| 81 |
+
tasks: Array<Record<string, unknown>>;
|
| 82 |
+
};
|
| 83 |
+
|
| 84 |
+
assert.equal(batch.tasks[0]?.model, "acme/custom-model");
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
test("build-batch propagates direct-usage references from prompt frontmatter", async () => {
|
| 88 |
+
const fixture = await makeFixture();
|
| 89 |
+
|
| 90 |
+
await fs.writeFile(
|
| 91 |
+
path.join(fixture.promptsDir, "01-demo.md"),
|
| 92 |
+
`---
|
| 93 |
+
illustration_id: 01
|
| 94 |
+
type: infographic
|
| 95 |
+
references:
|
| 96 |
+
- ref_id: 01
|
| 97 |
+
filename: 01-ref-brand.png
|
| 98 |
+
usage: direct
|
| 99 |
+
- ref_id: 02
|
| 100 |
+
filename: 02-ref-style.png
|
| 101 |
+
usage: style
|
| 102 |
+
---
|
| 103 |
+
|
| 104 |
+
A demo prompt
|
| 105 |
+
`,
|
| 106 |
+
);
|
| 107 |
+
|
| 108 |
+
await runBuildBatch([
|
| 109 |
+
"--outline",
|
| 110 |
+
fixture.outlinePath,
|
| 111 |
+
"--prompts",
|
| 112 |
+
fixture.promptsDir,
|
| 113 |
+
"--output",
|
| 114 |
+
fixture.outputPath,
|
| 115 |
+
]);
|
| 116 |
+
|
| 117 |
+
const batch = JSON.parse(await fs.readFile(fixture.outputPath, "utf8")) as {
|
| 118 |
+
tasks: Array<Record<string, unknown>>;
|
| 119 |
+
};
|
| 120 |
+
|
| 121 |
+
assert.deepEqual(batch.tasks[0]?.ref, ["references/01-ref-brand.png"]);
|
| 122 |
+
});
|
| 123 |
+
|
| 124 |
+
test("build-batch omits ref field when no direct references exist", async () => {
|
| 125 |
+
const fixture = await makeFixture();
|
| 126 |
+
|
| 127 |
+
await fs.writeFile(
|
| 128 |
+
path.join(fixture.promptsDir, "01-demo.md"),
|
| 129 |
+
`---
|
| 130 |
+
illustration_id: 01
|
| 131 |
+
references:
|
| 132 |
+
- ref_id: 01
|
| 133 |
+
filename: 01-ref-palette.png
|
| 134 |
+
usage: palette
|
| 135 |
+
---
|
| 136 |
+
|
| 137 |
+
A demo prompt
|
| 138 |
+
`,
|
| 139 |
+
);
|
| 140 |
+
|
| 141 |
+
await runBuildBatch([
|
| 142 |
+
"--outline",
|
| 143 |
+
fixture.outlinePath,
|
| 144 |
+
"--prompts",
|
| 145 |
+
fixture.promptsDir,
|
| 146 |
+
"--output",
|
| 147 |
+
fixture.outputPath,
|
| 148 |
+
]);
|
| 149 |
+
|
| 150 |
+
const batch = JSON.parse(await fs.readFile(fixture.outputPath, "utf8")) as {
|
| 151 |
+
tasks: Array<Record<string, unknown>>;
|
| 152 |
+
};
|
| 153 |
+
|
| 154 |
+
assert.equal(Object.hasOwn(batch.tasks[0]!, "ref"), false);
|
| 155 |
+
});
|
| 156 |
+
|
| 157 |
+
test("build-batch honors --refs-dir override", async () => {
|
| 158 |
+
const fixture = await makeFixture();
|
| 159 |
+
|
| 160 |
+
await fs.writeFile(
|
| 161 |
+
path.join(fixture.promptsDir, "01-demo.md"),
|
| 162 |
+
`---
|
| 163 |
+
illustration_id: 01
|
| 164 |
+
references:
|
| 165 |
+
- ref_id: 01
|
| 166 |
+
filename: brand.png
|
| 167 |
+
usage: direct
|
| 168 |
+
---
|
| 169 |
+
|
| 170 |
+
A demo prompt
|
| 171 |
+
`,
|
| 172 |
+
);
|
| 173 |
+
|
| 174 |
+
await runBuildBatch([
|
| 175 |
+
"--outline",
|
| 176 |
+
fixture.outlinePath,
|
| 177 |
+
"--prompts",
|
| 178 |
+
fixture.promptsDir,
|
| 179 |
+
"--output",
|
| 180 |
+
fixture.outputPath,
|
| 181 |
+
"--refs-dir",
|
| 182 |
+
"refs",
|
| 183 |
+
]);
|
| 184 |
+
|
| 185 |
+
const batch = JSON.parse(await fs.readFile(fixture.outputPath, "utf8")) as {
|
| 186 |
+
tasks: Array<Record<string, unknown>>;
|
| 187 |
+
};
|
| 188 |
+
|
| 189 |
+
assert.deepEqual(batch.tasks[0]?.ref, ["refs/brand.png"]);
|
| 190 |
+
});
|
baoyu_skills/baoyu-imagine/scripts/build-batch.ts
ADDED
|
@@ -0,0 +1,239 @@
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import path from "node:path";
|
| 2 |
+
import process from "node:process";
|
| 3 |
+
import { readdir, readFile, writeFile } from "node:fs/promises";
|
| 4 |
+
|
| 5 |
+
type CliArgs = {
|
| 6 |
+
outlinePath: string | null;
|
| 7 |
+
promptsDir: string | null;
|
| 8 |
+
outputPath: string | null;
|
| 9 |
+
imagesDir: string | null;
|
| 10 |
+
refsDir: string;
|
| 11 |
+
provider: string;
|
| 12 |
+
model: string | null;
|
| 13 |
+
aspectRatio: string;
|
| 14 |
+
quality: string;
|
| 15 |
+
jobs: number | null;
|
| 16 |
+
help: boolean;
|
| 17 |
+
};
|
| 18 |
+
|
| 19 |
+
type OutlineEntry = {
|
| 20 |
+
index: number;
|
| 21 |
+
filename: string;
|
| 22 |
+
};
|
| 23 |
+
|
| 24 |
+
type PromptReference = {
|
| 25 |
+
filename: string;
|
| 26 |
+
usage: "direct" | "style" | "palette";
|
| 27 |
+
};
|
| 28 |
+
|
| 29 |
+
function printUsage(): void {
|
| 30 |
+
console.log(`Usage:
|
| 31 |
+
bun <baseDir>/scripts/build-batch.ts --outline outline.md --prompts prompts --output batch.json --images-dir attachments
|
| 32 |
+
npx -y tsx <baseDir>/scripts/build-batch.ts --outline outline.md --prompts prompts --output batch.json --images-dir attachments
|
| 33 |
+
|
| 34 |
+
Options:
|
| 35 |
+
--outline <path> Path to outline.md
|
| 36 |
+
--prompts <path> Path to prompts directory
|
| 37 |
+
--output <path> Path to output batch.json
|
| 38 |
+
--images-dir <path> Directory for generated images
|
| 39 |
+
--refs-dir <path> Directory holding reference images, relative to batch file (default: references)
|
| 40 |
+
--provider <name> Provider for baoyu-image-gen batch tasks (default: replicate)
|
| 41 |
+
--model <id> Explicit model for baoyu-image-gen batch tasks (default: resolved by baoyu-image-gen config/env)
|
| 42 |
+
--ar <ratio> Aspect ratio for all tasks (default: 16:9)
|
| 43 |
+
--quality <level> Quality for all tasks (default: 2k)
|
| 44 |
+
--jobs <count> Recommended worker count metadata (optional)
|
| 45 |
+
-h, --help Show help`);
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
function parseArgs(argv: string[]): CliArgs {
|
| 49 |
+
const args: CliArgs = {
|
| 50 |
+
outlinePath: null,
|
| 51 |
+
promptsDir: null,
|
| 52 |
+
outputPath: null,
|
| 53 |
+
imagesDir: null,
|
| 54 |
+
refsDir: "references",
|
| 55 |
+
provider: "replicate",
|
| 56 |
+
model: null,
|
| 57 |
+
aspectRatio: "16:9",
|
| 58 |
+
quality: "2k",
|
| 59 |
+
jobs: null,
|
| 60 |
+
help: false,
|
| 61 |
+
};
|
| 62 |
+
|
| 63 |
+
for (let i = 0; i < argv.length; i++) {
|
| 64 |
+
const current = argv[i]!;
|
| 65 |
+
if (current === "--outline") args.outlinePath = argv[++i] ?? null;
|
| 66 |
+
else if (current === "--prompts") args.promptsDir = argv[++i] ?? null;
|
| 67 |
+
else if (current === "--output") args.outputPath = argv[++i] ?? null;
|
| 68 |
+
else if (current === "--images-dir") args.imagesDir = argv[++i] ?? null;
|
| 69 |
+
else if (current === "--refs-dir") args.refsDir = argv[++i] ?? args.refsDir;
|
| 70 |
+
else if (current === "--provider") args.provider = argv[++i] ?? args.provider;
|
| 71 |
+
else if (current === "--model") args.model = argv[++i] ?? args.model;
|
| 72 |
+
else if (current === "--ar") args.aspectRatio = argv[++i] ?? args.aspectRatio;
|
| 73 |
+
else if (current === "--quality") args.quality = argv[++i] ?? args.quality;
|
| 74 |
+
else if (current === "--jobs") {
|
| 75 |
+
const value = argv[++i];
|
| 76 |
+
args.jobs = value ? parseInt(value, 10) : null;
|
| 77 |
+
} else if (current === "--help" || current === "-h") {
|
| 78 |
+
args.help = true;
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
return args;
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
function parsePromptReferences(content: string): PromptReference[] {
|
| 85 |
+
const fmMatch = content.match(/^---\s*\n([\s\S]*?)\n---\s*(?:\n|$)/);
|
| 86 |
+
if (!fmMatch) return [];
|
| 87 |
+
const lines = fmMatch[1]!.split(/\r?\n/);
|
| 88 |
+
|
| 89 |
+
const refs: PromptReference[] = [];
|
| 90 |
+
let current: Partial<PromptReference> | null = null;
|
| 91 |
+
let inReferences = false;
|
| 92 |
+
let listIndent = 0;
|
| 93 |
+
|
| 94 |
+
const flush = () => {
|
| 95 |
+
if (current?.filename) {
|
| 96 |
+
refs.push({
|
| 97 |
+
filename: current.filename,
|
| 98 |
+
usage: (current.usage ?? "direct") as PromptReference["usage"],
|
| 99 |
+
});
|
| 100 |
+
}
|
| 101 |
+
current = null;
|
| 102 |
+
};
|
| 103 |
+
|
| 104 |
+
const unquote = (raw: string): string => raw.trim().replace(/^["']|["']$/g, "");
|
| 105 |
+
|
| 106 |
+
for (const line of lines) {
|
| 107 |
+
if (!line.trim() || line.trim().startsWith("#")) continue;
|
| 108 |
+
|
| 109 |
+
const keyMatch = line.match(/^(\S[^:]*):\s*(.*)$/);
|
| 110 |
+
if (keyMatch) {
|
| 111 |
+
flush();
|
| 112 |
+
if (keyMatch[1] === "references") {
|
| 113 |
+
inReferences = true;
|
| 114 |
+
listIndent = 0;
|
| 115 |
+
continue;
|
| 116 |
+
}
|
| 117 |
+
inReferences = false;
|
| 118 |
+
continue;
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
if (!inReferences) continue;
|
| 122 |
+
|
| 123 |
+
const itemMatch = line.match(/^(\s*)-\s*(.*)$/);
|
| 124 |
+
if (itemMatch) {
|
| 125 |
+
flush();
|
| 126 |
+
listIndent = itemMatch[1]!.length;
|
| 127 |
+
current = {};
|
| 128 |
+
const rest = itemMatch[2]!.trim();
|
| 129 |
+
if (rest) {
|
| 130 |
+
const kv = rest.match(/^(\w+)\s*:\s*(.*)$/);
|
| 131 |
+
if (kv && (kv[1] === "filename" || kv[1] === "usage")) {
|
| 132 |
+
(current as Record<string, string>)[kv[1]] = unquote(kv[2]!);
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
continue;
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
const kvMatch = line.match(/^(\s+)(\w+)\s*:\s*(.*)$/);
|
| 139 |
+
if (kvMatch && kvMatch[1]!.length > listIndent && current) {
|
| 140 |
+
if (kvMatch[2] === "filename" || kvMatch[2] === "usage") {
|
| 141 |
+
(current as Record<string, string>)[kvMatch[2]!] = unquote(kvMatch[3]!);
|
| 142 |
+
}
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
flush();
|
| 146 |
+
|
| 147 |
+
return refs;
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
function parseOutline(content: string): OutlineEntry[] {
|
| 151 |
+
const entries: OutlineEntry[] = [];
|
| 152 |
+
const blocks = content.split(/^## Illustration\s+/m).slice(1);
|
| 153 |
+
|
| 154 |
+
for (const block of blocks) {
|
| 155 |
+
const indexMatch = block.match(/^(\d+)/);
|
| 156 |
+
const filenameMatch = block.match(/\*\*Filename\*\*:\s*(.+)/);
|
| 157 |
+
if (indexMatch && filenameMatch) {
|
| 158 |
+
entries.push({
|
| 159 |
+
index: parseInt(indexMatch[1]!, 10),
|
| 160 |
+
filename: filenameMatch[1]!.trim(),
|
| 161 |
+
});
|
| 162 |
+
}
|
| 163 |
+
}
|
| 164 |
+
return entries;
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
async function findPromptFile(promptsDir: string, entry: OutlineEntry): Promise<string | null> {
|
| 168 |
+
const files = await readdir(promptsDir);
|
| 169 |
+
const prefix = String(entry.index).padStart(2, "0");
|
| 170 |
+
const match = files.find((f) => f.startsWith(prefix) && f.endsWith(".md"));
|
| 171 |
+
return match ? path.join(promptsDir, match) : null;
|
| 172 |
+
}
|
| 173 |
+
|
| 174 |
+
async function main(): Promise<void> {
|
| 175 |
+
const args = parseArgs(process.argv.slice(2));
|
| 176 |
+
if (args.help) {
|
| 177 |
+
printUsage();
|
| 178 |
+
return;
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
if (!args.outlinePath) {
|
| 182 |
+
console.error("Error: --outline is required");
|
| 183 |
+
process.exit(1);
|
| 184 |
+
}
|
| 185 |
+
if (!args.promptsDir) {
|
| 186 |
+
console.error("Error: --prompts is required");
|
| 187 |
+
process.exit(1);
|
| 188 |
+
}
|
| 189 |
+
if (!args.outputPath) {
|
| 190 |
+
console.error("Error: --output is required");
|
| 191 |
+
process.exit(1);
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
const outlineContent = await readFile(args.outlinePath, "utf8");
|
| 195 |
+
const entries = parseOutline(outlineContent);
|
| 196 |
+
|
| 197 |
+
if (entries.length === 0) {
|
| 198 |
+
console.error("No illustration entries found in outline.");
|
| 199 |
+
process.exit(1);
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
const tasks = [];
|
| 203 |
+
for (const entry of entries) {
|
| 204 |
+
const promptFile = await findPromptFile(args.promptsDir, entry);
|
| 205 |
+
if (!promptFile) {
|
| 206 |
+
console.error(`Warning: No prompt file found for illustration ${entry.index}, skipping.`);
|
| 207 |
+
continue;
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
const imageDir = args.imagesDir ?? path.dirname(args.outputPath);
|
| 211 |
+
const promptContent = await readFile(promptFile, "utf8");
|
| 212 |
+
const refs = parsePromptReferences(promptContent)
|
| 213 |
+
.filter((r) => r.usage === "direct")
|
| 214 |
+
.map((r) => path.posix.join(args.refsDir, r.filename));
|
| 215 |
+
|
| 216 |
+
const task: Record<string, unknown> = {
|
| 217 |
+
id: `illustration-${String(entry.index).padStart(2, "0")}`,
|
| 218 |
+
promptFiles: [promptFile],
|
| 219 |
+
image: path.join(imageDir, entry.filename),
|
| 220 |
+
provider: args.provider,
|
| 221 |
+
ar: args.aspectRatio,
|
| 222 |
+
quality: args.quality,
|
| 223 |
+
};
|
| 224 |
+
if (args.model) task.model = args.model;
|
| 225 |
+
if (refs.length > 0) task.ref = refs;
|
| 226 |
+
tasks.push(task);
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
const output: Record<string, unknown> = { tasks };
|
| 230 |
+
if (args.jobs) output.jobs = args.jobs;
|
| 231 |
+
|
| 232 |
+
await writeFile(args.outputPath, JSON.stringify(output, null, 2) + "\n");
|
| 233 |
+
console.log(`Batch file written: ${args.outputPath} (${tasks.length} tasks)`);
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
main().catch((error) => {
|
| 237 |
+
console.error(error instanceof Error ? error.message : String(error));
|
| 238 |
+
process.exit(1);
|
| 239 |
+
});
|
baoyu_skills/baoyu-imagine/scripts/codex-imagegen/cache.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { createHash } from "node:crypto";
|
| 2 |
+
import { mkdir, readFile, writeFile, copyFile, stat } from "node:fs/promises";
|
| 3 |
+
import { existsSync, openSync, closeSync } from "node:fs";
|
| 4 |
+
import path from "node:path";
|
| 5 |
+
import { setTimeout as delay } from "node:timers/promises";
|
| 6 |
+
|
| 7 |
+
export function cacheKey(prompt: string, aspect: string, refs: string[]): string {
|
| 8 |
+
const h = createHash("sha256");
|
| 9 |
+
h.update(prompt);
|
| 10 |
+
h.update("|");
|
| 11 |
+
h.update(aspect);
|
| 12 |
+
h.update("|");
|
| 13 |
+
for (const r of [...refs].sort()) h.update(r);
|
| 14 |
+
return h.digest("hex").slice(0, 16);
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
export async function lookupCache(cacheDir: string, key: string): Promise<string | null> {
|
| 18 |
+
const entry = path.join(cacheDir, `${key}.png`);
|
| 19 |
+
try {
|
| 20 |
+
const s = await stat(entry);
|
| 21 |
+
if (s.size > 1000) return entry;
|
| 22 |
+
} catch {}
|
| 23 |
+
return null;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
export async function storeCache(cacheDir: string, key: string, sourcePath: string): Promise<void> {
|
| 27 |
+
await mkdir(cacheDir, { recursive: true });
|
| 28 |
+
const entry = path.join(cacheDir, `${key}.png`);
|
| 29 |
+
await copyFile(sourcePath, entry);
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
export class FileLock {
|
| 33 |
+
private fd: number | null = null;
|
| 34 |
+
constructor(private lockPath: string) {}
|
| 35 |
+
|
| 36 |
+
async acquire(timeoutMs = 30_000): Promise<void> {
|
| 37 |
+
const start = Date.now();
|
| 38 |
+
await mkdir(path.dirname(this.lockPath), { recursive: true });
|
| 39 |
+
while (Date.now() - start < timeoutMs) {
|
| 40 |
+
try {
|
| 41 |
+
this.fd = openSync(this.lockPath, "wx");
|
| 42 |
+
return;
|
| 43 |
+
} catch (e: any) {
|
| 44 |
+
if (e.code !== "EEXIST") throw e;
|
| 45 |
+
if (await this.isStale()) {
|
| 46 |
+
try {
|
| 47 |
+
await this.release(true);
|
| 48 |
+
} catch {}
|
| 49 |
+
continue;
|
| 50 |
+
}
|
| 51 |
+
await delay(200);
|
| 52 |
+
}
|
| 53 |
+
}
|
| 54 |
+
throw new Error(`Failed to acquire lock at ${this.lockPath} within ${timeoutMs}ms`);
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
private async isStale(): Promise<boolean> {
|
| 58 |
+
try {
|
| 59 |
+
const s = await stat(this.lockPath);
|
| 60 |
+
return Date.now() - s.mtimeMs > 10 * 60 * 1000;
|
| 61 |
+
} catch {
|
| 62 |
+
return true;
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
async release(force = false): Promise<void> {
|
| 67 |
+
if (this.fd != null) {
|
| 68 |
+
try {
|
| 69 |
+
closeSync(this.fd);
|
| 70 |
+
} catch {}
|
| 71 |
+
this.fd = null;
|
| 72 |
+
}
|
| 73 |
+
if (existsSync(this.lockPath) || force) {
|
| 74 |
+
const { unlink } = await import("node:fs/promises");
|
| 75 |
+
try {
|
| 76 |
+
await unlink(this.lockPath);
|
| 77 |
+
} catch {}
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/codex-imagegen/logger.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { appendFile, mkdir } from "node:fs/promises";
|
| 2 |
+
import path from "node:path";
|
| 3 |
+
|
| 4 |
+
export interface LogEntry {
|
| 5 |
+
ts: string;
|
| 6 |
+
level: "info" | "warn" | "error";
|
| 7 |
+
event: string;
|
| 8 |
+
[k: string]: unknown;
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
export class JsonLogger {
|
| 12 |
+
constructor(private logFile: string | null, public verbose: boolean) {}
|
| 13 |
+
|
| 14 |
+
async log(level: LogEntry["level"], event: string, extra: Record<string, unknown> = {}): Promise<void> {
|
| 15 |
+
const entry: LogEntry = { ts: new Date().toISOString(), level, event, ...extra };
|
| 16 |
+
const line = JSON.stringify(entry);
|
| 17 |
+
if (this.verbose) process.stderr.write(`[${level}] ${event} ${jsonExtras(extra)}\n`);
|
| 18 |
+
if (this.logFile) {
|
| 19 |
+
await mkdir(path.dirname(this.logFile), { recursive: true });
|
| 20 |
+
await appendFile(this.logFile, line + "\n", "utf-8");
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
info(event: string, extra?: Record<string, unknown>) {
|
| 25 |
+
return this.log("info", event, extra);
|
| 26 |
+
}
|
| 27 |
+
warn(event: string, extra?: Record<string, unknown>) {
|
| 28 |
+
return this.log("warn", event, extra);
|
| 29 |
+
}
|
| 30 |
+
error(event: string, extra?: Record<string, unknown>) {
|
| 31 |
+
return this.log("error", event, extra);
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
function jsonExtras(extra: Record<string, unknown>): string {
|
| 36 |
+
const entries = Object.entries(extra);
|
| 37 |
+
if (entries.length === 0) return "";
|
| 38 |
+
return entries.map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ");
|
| 39 |
+
}
|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 |
+
import { readFile, mkdir, copyFile, stat } from "node:fs/promises";
|
| 3 |
+
import { homedir } from "node:os";
|
| 4 |
+
import path from "node:path";
|
| 5 |
+
import process from "node:process";
|
| 6 |
+
import { setTimeout as delay } from "node:timers/promises";
|
| 7 |
+
import { GenError, type CliOptions, type GenerateResult } from "./types.ts";
|
| 8 |
+
import { runCodexExec } from "./spawn.ts";
|
| 9 |
+
import { findCpToTarget, verifyImageGenWasInvoked, verifyOutput } from "./validator.ts";
|
| 10 |
+
import { cacheKey, lookupCache, storeCache, FileLock } from "./cache.ts";
|
| 11 |
+
import { JsonLogger } from "./logger.ts";
|
| 12 |
+
|
| 13 |
+
const HELP = `codex-imagegen — generate images via Codex CLI's image_gen tool
|
| 14 |
+
|
| 15 |
+
Usage:
|
| 16 |
+
codex-imagegen --image <output.png> [--prompt <text> | --prompt-file <path>] [options]
|
| 17 |
+
|
| 18 |
+
Required:
|
| 19 |
+
--image <path> Output PNG path
|
| 20 |
+
--prompt <text> Prompt text (or use --prompt-file)
|
| 21 |
+
--prompt-file <path> Read prompt from file
|
| 22 |
+
|
| 23 |
+
Options:
|
| 24 |
+
--aspect <ratio> Aspect ratio (1:1, 16:9, 9:16, 4:3, 2.35:1). Default: 1:1
|
| 25 |
+
--ref <file> Reference image (repeatable)
|
| 26 |
+
--timeout <ms> Codex exec timeout in ms. Default: 300000
|
| 27 |
+
--retries <n> Retry attempts on retryable errors. Default: 2
|
| 28 |
+
--retry-delay <ms> Base retry delay (exponential). Default: 1500
|
| 29 |
+
--cache-dir <path> Enable idempotency cache. Disabled by default.
|
| 30 |
+
--log-file <path> Append JSONL log
|
| 31 |
+
-v, --verbose Verbose stderr logging
|
| 32 |
+
-h, --help Show this help
|
| 33 |
+
|
| 34 |
+
Stdout: single JSON line on success or failure.
|
| 35 |
+
`;
|
| 36 |
+
|
| 37 |
+
const SHELL_METACHAR = /[;|&`$<>\n\r()'"]/;
|
| 38 |
+
|
| 39 |
+
function assertSafePath(label: string, value: string): void {
|
| 40 |
+
if (SHELL_METACHAR.test(value)) {
|
| 41 |
+
throw new GenError(
|
| 42 |
+
"invalid_args",
|
| 43 |
+
`${label} contains shell metacharacters and would be unsafe to interpolate into the codex instruction: ${value}`,
|
| 44 |
+
false,
|
| 45 |
+
);
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
function parseArgs(argv: string[]): CliOptions {
|
| 50 |
+
const opts: CliOptions = {
|
| 51 |
+
prompt: "",
|
| 52 |
+
promptFile: null,
|
| 53 |
+
outputPath: "",
|
| 54 |
+
aspect: "1:1",
|
| 55 |
+
refImages: [],
|
| 56 |
+
timeoutMs: 300_000,
|
| 57 |
+
retries: 2,
|
| 58 |
+
retryDelayMs: 1500,
|
| 59 |
+
cacheDir: null,
|
| 60 |
+
logFile: null,
|
| 61 |
+
verbose: false,
|
| 62 |
+
};
|
| 63 |
+
for (let i = 0; i < argv.length; i++) {
|
| 64 |
+
const a = argv[i];
|
| 65 |
+
const next = () => argv[++i];
|
| 66 |
+
switch (a) {
|
| 67 |
+
case "--prompt": opts.prompt = next(); break;
|
| 68 |
+
case "--prompt-file": opts.promptFile = next(); break;
|
| 69 |
+
case "--image": opts.outputPath = next(); break;
|
| 70 |
+
case "--aspect": opts.aspect = next(); break;
|
| 71 |
+
case "--ref": opts.refImages.push(next()); break;
|
| 72 |
+
case "--timeout": opts.timeoutMs = Number(next()); break;
|
| 73 |
+
case "--retries": opts.retries = Number(next()); break;
|
| 74 |
+
case "--retry-delay": opts.retryDelayMs = Number(next()); break;
|
| 75 |
+
case "--cache-dir": opts.cacheDir = next(); break;
|
| 76 |
+
case "--log-file": opts.logFile = next(); break;
|
| 77 |
+
case "-v":
|
| 78 |
+
case "--verbose": opts.verbose = true; break;
|
| 79 |
+
case "-h":
|
| 80 |
+
case "--help": process.stdout.write(HELP); process.exit(0);
|
| 81 |
+
default: throw new GenError("invalid_args", `Unknown argument: ${a}`, false);
|
| 82 |
+
}
|
| 83 |
+
}
|
| 84 |
+
if (!opts.outputPath) throw new GenError("invalid_args", "--image is required", false);
|
| 85 |
+
if (opts.prompt && opts.promptFile) {
|
| 86 |
+
throw new GenError("invalid_args", "--prompt and --prompt-file are mutually exclusive", false);
|
| 87 |
+
}
|
| 88 |
+
if (!opts.prompt && !opts.promptFile) {
|
| 89 |
+
throw new GenError("invalid_args", "--prompt or --prompt-file required", false);
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
// Resolve every filesystem path to absolute up front, so behavior is
|
| 93 |
+
// independent of the caller's cwd. This matters when the wrapper is
|
| 94 |
+
// invoked from a skill running in an arbitrary working directory.
|
| 95 |
+
const cwd = process.cwd();
|
| 96 |
+
const toAbs = (p: string) => (path.isAbsolute(p) ? p : path.resolve(cwd, p));
|
| 97 |
+
|
| 98 |
+
opts.outputPath = toAbs(opts.outputPath);
|
| 99 |
+
if (opts.promptFile) opts.promptFile = toAbs(opts.promptFile);
|
| 100 |
+
opts.refImages = opts.refImages.map(toAbs);
|
| 101 |
+
if (opts.cacheDir) opts.cacheDir = toAbs(opts.cacheDir);
|
| 102 |
+
if (opts.logFile) opts.logFile = toAbs(opts.logFile);
|
| 103 |
+
|
| 104 |
+
// The output and ref paths are interpolated raw into the agent instruction
|
| 105 |
+
// sent to `codex exec --sandbox danger-full-access`. A path containing shell
|
| 106 |
+
// metacharacters could be misread by the agent's shell when it cp's the
|
| 107 |
+
// result into place. Reject upfront rather than trusting the agent to quote.
|
| 108 |
+
assertSafePath("--image path", opts.outputPath);
|
| 109 |
+
for (const ref of opts.refImages) assertSafePath("--ref path", ref);
|
| 110 |
+
|
| 111 |
+
return opts;
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
async function loadPrompt(opts: CliOptions): Promise<string> {
|
| 115 |
+
if (opts.prompt) return opts.prompt;
|
| 116 |
+
const file = opts.promptFile!;
|
| 117 |
+
try {
|
| 118 |
+
return await readFile(file, "utf-8");
|
| 119 |
+
} catch {
|
| 120 |
+
throw new GenError("prompt_file_missing", `Prompt file not found: ${file}`, false);
|
| 121 |
+
}
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
function buildInstruction(prompt: string, opts: CliOptions): string {
|
| 125 |
+
const refHint = opts.refImages.length > 0
|
| 126 |
+
? `\nREFERENCE IMAGES (attached above): ${opts.refImages.length} image(s) provided for style/composition guidance.\n`
|
| 127 |
+
: "";
|
| 128 |
+
return `You have an internal tool called image_gen for image generation. Use it.
|
| 129 |
+
|
| 130 |
+
TASK: Generate an image with the spec below, then save to disk.
|
| 131 |
+
|
| 132 |
+
PROMPT:
|
| 133 |
+
${prompt}
|
| 134 |
+
|
| 135 |
+
ASPECT RATIO: ${opts.aspect}
|
| 136 |
+
OUTPUT PATH: ${opts.outputPath}
|
| 137 |
+
${refHint}
|
| 138 |
+
STEPS:
|
| 139 |
+
1. Call image_gen with the prompt and aspect ratio above${opts.refImages.length > 0 ? " (using the attached reference images for guidance)" : ""}.
|
| 140 |
+
2. Move or copy the resulting image from Codex default location ($CODEX_HOME/generated_images/...) to: ${opts.outputPath}
|
| 141 |
+
3. Verify with: ls -la ${opts.outputPath}
|
| 142 |
+
4. Reply with ONLY this JSON line (no markdown fences, no other text):
|
| 143 |
+
{"status":"ok","path":"${opts.outputPath}","bytes":<file_size_in_bytes>}
|
| 144 |
+
|
| 145 |
+
HARD CONSTRAINTS:
|
| 146 |
+
- Do NOT use curl, wget, Python, or any external API.
|
| 147 |
+
- Do NOT use bash to fabricate an image; only image_gen produces real pixels.
|
| 148 |
+
- Use ONLY the image_gen internal tool.`;
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
async function attemptGenerate(
|
| 152 |
+
opts: CliOptions,
|
| 153 |
+
instruction: string,
|
| 154 |
+
attempt: number,
|
| 155 |
+
log: JsonLogger,
|
| 156 |
+
): Promise<{ bytes: number; threadId: string | null; usage: any; toolCalls: any[] }> {
|
| 157 |
+
await log.info("attempt.start", { attempt, output: opts.outputPath, aspect: opts.aspect });
|
| 158 |
+
|
| 159 |
+
const run = await runCodexExec({
|
| 160 |
+
instruction,
|
| 161 |
+
timeoutMs: opts.timeoutMs,
|
| 162 |
+
refImages: opts.refImages,
|
| 163 |
+
});
|
| 164 |
+
|
| 165 |
+
await log.info("codex.completed", {
|
| 166 |
+
duration_ms: run.durationMs,
|
| 167 |
+
thread_id: run.threadId,
|
| 168 |
+
tool_calls: run.toolCalls.length,
|
| 169 |
+
usage: run.usage,
|
| 170 |
+
raw_log: run.rawLogPath,
|
| 171 |
+
});
|
| 172 |
+
|
| 173 |
+
// verify: thread id must be present
|
| 174 |
+
if (!run.threadId) {
|
| 175 |
+
throw new GenError("agent_refused", "No thread id in event stream");
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
// verify: image_gen was actually invoked (check $CODEX_HOME/generated_images/{threadId}/)
|
| 179 |
+
const ver = await verifyImageGenWasInvoked(run.threadId);
|
| 180 |
+
if (!ver.ok) {
|
| 181 |
+
// secondary verify: did tool_calls include cp/mv from generated_images to our target
|
| 182 |
+
if (!findCpToTarget(run.toolCalls, opts.outputPath)) {
|
| 183 |
+
throw new GenError("no_image_gen_tool_use", `image_gen was not invoked: ${ver.reason}`);
|
| 184 |
+
}
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
// verify output
|
| 188 |
+
const { bytes } = await verifyOutput(opts.outputPath);
|
| 189 |
+
|
| 190 |
+
return {
|
| 191 |
+
bytes,
|
| 192 |
+
threadId: run.threadId,
|
| 193 |
+
usage: run.usage,
|
| 194 |
+
toolCalls: run.toolCalls.map((tc) => ({ tool: tc.tool, status: tc.status })),
|
| 195 |
+
};
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
async function generate(opts: CliOptions, log: JsonLogger): Promise<GenerateResult> {
|
| 199 |
+
const startEpoch = Date.now();
|
| 200 |
+
const prompt = await loadPrompt(opts);
|
| 201 |
+
|
| 202 |
+
// Cache lookup
|
| 203 |
+
if (opts.cacheDir) {
|
| 204 |
+
const key = cacheKey(prompt, opts.aspect, opts.refImages);
|
| 205 |
+
const cached = await lookupCache(opts.cacheDir, key);
|
| 206 |
+
if (cached) {
|
| 207 |
+
await mkdir(path.dirname(opts.outputPath), { recursive: true });
|
| 208 |
+
await copyFile(cached, opts.outputPath);
|
| 209 |
+
const s = await stat(opts.outputPath);
|
| 210 |
+
await log.info("cache.hit", { key, source: cached });
|
| 211 |
+
return {
|
| 212 |
+
status: "ok",
|
| 213 |
+
path: opts.outputPath,
|
| 214 |
+
bytes: s.size,
|
| 215 |
+
elapsed_seconds: 0,
|
| 216 |
+
thread_id: null,
|
| 217 |
+
attempts: 0,
|
| 218 |
+
cached: true,
|
| 219 |
+
usage: null,
|
| 220 |
+
tool_calls: [],
|
| 221 |
+
};
|
| 222 |
+
}
|
| 223 |
+
await log.info("cache.miss", { key });
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
// lock to prevent concurrent codex exec
|
| 227 |
+
const lockDir = opts.cacheDir ?? path.join(homedir(), ".cache", "baoyu-codex-imagegen");
|
| 228 |
+
const lock = new FileLock(path.join(lockDir, "codex-exec.lock"));
|
| 229 |
+
try {
|
| 230 |
+
await lock.acquire(60_000);
|
| 231 |
+
} catch (e) {
|
| 232 |
+
throw new GenError("lock_busy", String(e), false);
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
await mkdir(path.dirname(opts.outputPath), { recursive: true });
|
| 236 |
+
const instruction = buildInstruction(prompt, opts);
|
| 237 |
+
|
| 238 |
+
let lastErr: GenError | null = null;
|
| 239 |
+
let lastAttempt = 0;
|
| 240 |
+
try {
|
| 241 |
+
for (let attempt = 1; attempt <= opts.retries + 1; attempt++) {
|
| 242 |
+
lastAttempt = attempt;
|
| 243 |
+
try {
|
| 244 |
+
const result = await attemptGenerate(opts, instruction, attempt, log);
|
| 245 |
+
|
| 246 |
+
// write to cache
|
| 247 |
+
if (opts.cacheDir) {
|
| 248 |
+
const key = cacheKey(prompt, opts.aspect, opts.refImages);
|
| 249 |
+
await storeCache(opts.cacheDir, key, opts.outputPath);
|
| 250 |
+
await log.info("cache.stored", { key });
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
return {
|
| 254 |
+
status: "ok",
|
| 255 |
+
path: opts.outputPath,
|
| 256 |
+
bytes: result.bytes,
|
| 257 |
+
elapsed_seconds: Math.round((Date.now() - startEpoch) / 1000),
|
| 258 |
+
thread_id: result.threadId,
|
| 259 |
+
attempts: attempt,
|
| 260 |
+
cached: false,
|
| 261 |
+
usage: result.usage,
|
| 262 |
+
tool_calls: result.toolCalls,
|
| 263 |
+
};
|
| 264 |
+
} catch (e) {
|
| 265 |
+
lastErr = e instanceof GenError ? e : new GenError("spawn_failed", String(e));
|
| 266 |
+
await log.warn("attempt.failed", {
|
| 267 |
+
attempt,
|
| 268 |
+
kind: lastErr.kind,
|
| 269 |
+
retryable: lastErr.retryable,
|
| 270 |
+
error: lastErr.message,
|
| 271 |
+
});
|
| 272 |
+
if (!lastErr.retryable || attempt > opts.retries) break;
|
| 273 |
+
const wait = opts.retryDelayMs * Math.pow(2, attempt - 1);
|
| 274 |
+
await log.info("retry.wait", { wait_ms: wait, next_attempt: attempt + 1 });
|
| 275 |
+
await delay(wait);
|
| 276 |
+
}
|
| 277 |
+
}
|
| 278 |
+
} finally {
|
| 279 |
+
await lock.release();
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
const err = lastErr ?? new GenError("spawn_failed", "Unknown failure");
|
| 283 |
+
err.attempts = lastAttempt;
|
| 284 |
+
throw err;
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
async function main() {
|
| 288 |
+
let opts: CliOptions;
|
| 289 |
+
try {
|
| 290 |
+
opts = parseArgs(process.argv.slice(2));
|
| 291 |
+
} catch (e) {
|
| 292 |
+
const err = e instanceof GenError ? e : new GenError("invalid_args", String(e), false);
|
| 293 |
+
process.stderr.write(`Error: ${err.message}\n`);
|
| 294 |
+
process.exit(2);
|
| 295 |
+
}
|
| 296 |
+
|
| 297 |
+
const log = new JsonLogger(opts.logFile, opts.verbose);
|
| 298 |
+
await log.info("start", { output: opts.outputPath, aspect: opts.aspect, refs: opts.refImages.length });
|
| 299 |
+
|
| 300 |
+
try {
|
| 301 |
+
const result = await generate(opts, log);
|
| 302 |
+
await log.info("done", { bytes: result.bytes, attempts: result.attempts, cached: result.cached });
|
| 303 |
+
process.stdout.write(JSON.stringify(result) + "\n");
|
| 304 |
+
process.exit(0);
|
| 305 |
+
} catch (e) {
|
| 306 |
+
const err = e instanceof GenError ? e : new GenError("spawn_failed", String(e));
|
| 307 |
+
await log.error("failed", { kind: err.kind, error: err.message, attempts: err.attempts ?? 0 });
|
| 308 |
+
const out: GenerateResult = {
|
| 309 |
+
status: "error",
|
| 310 |
+
path: opts.outputPath,
|
| 311 |
+
bytes: 0,
|
| 312 |
+
elapsed_seconds: 0,
|
| 313 |
+
thread_id: null,
|
| 314 |
+
attempts: err.attempts ?? 0,
|
| 315 |
+
cached: false,
|
| 316 |
+
usage: null,
|
| 317 |
+
tool_calls: [],
|
| 318 |
+
error: err.message,
|
| 319 |
+
error_kind: err.kind,
|
| 320 |
+
};
|
| 321 |
+
process.stdout.write(JSON.stringify(out) + "\n");
|
| 322 |
+
process.exit(1);
|
| 323 |
+
}
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
main();
|
baoyu_skills/baoyu-imagine/scripts/codex-imagegen/parser.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { CodexRunResult, ToolCall, TokenUsage } from "./types.ts";
|
| 2 |
+
|
| 3 |
+
export function parseEventStream(raw: string): Omit<CodexRunResult, "rawLogPath" | "durationMs"> {
|
| 4 |
+
const lines = raw.split("\n").filter((l) => l.trim().length > 0);
|
| 5 |
+
let threadId: string | null = null;
|
| 6 |
+
let agentMessage: string | null = null;
|
| 7 |
+
let usage: TokenUsage | null = null;
|
| 8 |
+
const toolCallsById = new Map<string, ToolCall>();
|
| 9 |
+
|
| 10 |
+
for (const line of lines) {
|
| 11 |
+
let event: any;
|
| 12 |
+
try {
|
| 13 |
+
event = JSON.parse(line);
|
| 14 |
+
} catch {
|
| 15 |
+
continue;
|
| 16 |
+
}
|
| 17 |
+
const type = event?.type;
|
| 18 |
+
if (type === "thread.started") {
|
| 19 |
+
threadId = event.thread_id ?? null;
|
| 20 |
+
} else if (type === "item.started" || type === "item.completed") {
|
| 21 |
+
const item = event.item;
|
| 22 |
+
if (!item?.id) continue;
|
| 23 |
+
const tc: ToolCall = {
|
| 24 |
+
id: item.id,
|
| 25 |
+
tool: deriveToolName(item),
|
| 26 |
+
status: item.status ?? (type === "item.completed" ? "completed" : "in_progress"),
|
| 27 |
+
command: item.command,
|
| 28 |
+
};
|
| 29 |
+
toolCallsById.set(item.id, tc);
|
| 30 |
+
if (item.type === "agent_message" && type === "item.completed") {
|
| 31 |
+
agentMessage = String(item.text ?? "");
|
| 32 |
+
}
|
| 33 |
+
} else if (type === "turn.completed") {
|
| 34 |
+
const u = event.usage;
|
| 35 |
+
if (u) {
|
| 36 |
+
usage = {
|
| 37 |
+
input: u.input_tokens ?? 0,
|
| 38 |
+
cached_input: u.cached_input_tokens ?? 0,
|
| 39 |
+
output: u.output_tokens ?? 0,
|
| 40 |
+
reasoning: u.reasoning_output_tokens ?? 0,
|
| 41 |
+
};
|
| 42 |
+
}
|
| 43 |
+
}
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
return {
|
| 47 |
+
threadId,
|
| 48 |
+
toolCalls: Array.from(toolCallsById.values()),
|
| 49 |
+
agentMessage,
|
| 50 |
+
usage,
|
| 51 |
+
};
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
function deriveToolName(item: any): string {
|
| 55 |
+
if (item.type === "command_execution") return "shell";
|
| 56 |
+
if (item.type === "agent_message") return "agent_message";
|
| 57 |
+
if (item.type === "image_gen" || item.type === "image_generation") return "image_gen";
|
| 58 |
+
if (typeof item.tool === "string") return item.tool;
|
| 59 |
+
return item.type ?? "unknown";
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
export function hasImageGenInvocation(toolCalls: ToolCall[]): boolean {
|
| 63 |
+
return toolCalls.some((tc) => tc.tool === "image_gen");
|
| 64 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/codex-imagegen/spawn.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { spawn } from "node:child_process";
|
| 2 |
+
import { writeFile, mkdtemp } from "node:fs/promises";
|
| 3 |
+
import { tmpdir } from "node:os";
|
| 4 |
+
import path from "node:path";
|
| 5 |
+
import { GenError, type CodexRunResult } from "./types.ts";
|
| 6 |
+
import { parseEventStream } from "./parser.ts";
|
| 7 |
+
|
| 8 |
+
export interface SpawnInput {
|
| 9 |
+
instruction: string;
|
| 10 |
+
timeoutMs: number;
|
| 11 |
+
refImages?: string[];
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
export async function runCodexExec(input: SpawnInput): Promise<CodexRunResult> {
|
| 15 |
+
const start = Date.now();
|
| 16 |
+
const logDir = await mkdtemp(path.join(tmpdir(), "codex-imggen-"));
|
| 17 |
+
const rawLogPath = path.join(logDir, "stream.jsonl");
|
| 18 |
+
|
| 19 |
+
// --skip-git-repo-check: lets the wrapper run from non-git cwds
|
| 20 |
+
// (e.g. /tmp, or a skill installed under ~/.claude/plugins/...).
|
| 21 |
+
// Without it, codex refuses with "Not inside a trusted directory".
|
| 22 |
+
const args = [
|
| 23 |
+
"exec",
|
| 24 |
+
"--json",
|
| 25 |
+
"--sandbox",
|
| 26 |
+
"danger-full-access",
|
| 27 |
+
"--skip-git-repo-check",
|
| 28 |
+
];
|
| 29 |
+
for (const img of input.refImages ?? []) {
|
| 30 |
+
args.push("--image", img);
|
| 31 |
+
}
|
| 32 |
+
args.push("-");
|
| 33 |
+
|
| 34 |
+
let timedOut = false;
|
| 35 |
+
const child = spawn("codex", args, { stdio: ["pipe", "pipe", "pipe"] });
|
| 36 |
+
|
| 37 |
+
let stdout = "";
|
| 38 |
+
let stderr = "";
|
| 39 |
+
child.stdout.on("data", (chunk) => {
|
| 40 |
+
stdout += chunk.toString();
|
| 41 |
+
});
|
| 42 |
+
child.stderr.on("data", (chunk) => {
|
| 43 |
+
stderr += chunk.toString();
|
| 44 |
+
});
|
| 45 |
+
|
| 46 |
+
child.stdin.write(input.instruction);
|
| 47 |
+
child.stdin.end();
|
| 48 |
+
|
| 49 |
+
const timer = setTimeout(() => {
|
| 50 |
+
timedOut = true;
|
| 51 |
+
child.kill("SIGTERM");
|
| 52 |
+
setTimeout(() => child.kill("SIGKILL"), 2000);
|
| 53 |
+
}, input.timeoutMs);
|
| 54 |
+
|
| 55 |
+
const exit = await new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve) => {
|
| 56 |
+
child.on("close", (code, signal) => resolve({ code, signal }));
|
| 57 |
+
});
|
| 58 |
+
clearTimeout(timer);
|
| 59 |
+
|
| 60 |
+
await writeFile(rawLogPath, stdout + (stderr ? `\n--- stderr ---\n${stderr}` : ""));
|
| 61 |
+
|
| 62 |
+
if (timedOut) {
|
| 63 |
+
throw new GenError("timeout", `codex exec exceeded ${input.timeoutMs}ms (log: ${rawLogPath})`);
|
| 64 |
+
}
|
| 65 |
+
if (exit.code !== 0) {
|
| 66 |
+
if (stderr.includes("command not found") || stderr.includes("not found: codex")) {
|
| 67 |
+
throw new GenError("codex_not_installed", "codex CLI not installed", false);
|
| 68 |
+
}
|
| 69 |
+
throw new GenError(
|
| 70 |
+
"spawn_failed",
|
| 71 |
+
`codex exec exited ${exit.code} signal=${exit.signal} (log: ${rawLogPath})`,
|
| 72 |
+
);
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
const parsed = parseEventStream(stdout);
|
| 76 |
+
return {
|
| 77 |
+
...parsed,
|
| 78 |
+
rawLogPath,
|
| 79 |
+
durationMs: Date.now() - start,
|
| 80 |
+
};
|
| 81 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/codex-imagegen/types.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export interface CliOptions {
|
| 2 |
+
prompt: string;
|
| 3 |
+
promptFile: string | null;
|
| 4 |
+
outputPath: string;
|
| 5 |
+
aspect: string;
|
| 6 |
+
refImages: string[];
|
| 7 |
+
timeoutMs: number;
|
| 8 |
+
retries: number;
|
| 9 |
+
retryDelayMs: number;
|
| 10 |
+
cacheDir: string | null;
|
| 11 |
+
logFile: string | null;
|
| 12 |
+
verbose: boolean;
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
export interface ToolCall {
|
| 16 |
+
id: string;
|
| 17 |
+
tool: string;
|
| 18 |
+
status: string;
|
| 19 |
+
command?: string;
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
export interface TokenUsage {
|
| 23 |
+
input: number;
|
| 24 |
+
cached_input: number;
|
| 25 |
+
output: number;
|
| 26 |
+
reasoning: number;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
export interface CodexRunResult {
|
| 30 |
+
threadId: string | null;
|
| 31 |
+
toolCalls: ToolCall[];
|
| 32 |
+
agentMessage: string | null;
|
| 33 |
+
usage: TokenUsage | null;
|
| 34 |
+
rawLogPath: string;
|
| 35 |
+
durationMs: number;
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
export interface GenerateResult {
|
| 39 |
+
status: "ok" | "error";
|
| 40 |
+
path: string;
|
| 41 |
+
bytes: number;
|
| 42 |
+
elapsed_seconds: number;
|
| 43 |
+
thread_id: string | null;
|
| 44 |
+
attempts: number;
|
| 45 |
+
cached: boolean;
|
| 46 |
+
usage: TokenUsage | null;
|
| 47 |
+
tool_calls: { tool: string; status: string }[];
|
| 48 |
+
error?: string;
|
| 49 |
+
error_kind?: ErrorKind;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
export type ErrorKind =
|
| 53 |
+
| "codex_not_installed"
|
| 54 |
+
| "invalid_args"
|
| 55 |
+
| "prompt_file_missing"
|
| 56 |
+
| "spawn_failed"
|
| 57 |
+
| "timeout"
|
| 58 |
+
| "no_image_gen_tool_use"
|
| 59 |
+
| "output_missing"
|
| 60 |
+
| "invalid_png"
|
| 61 |
+
| "agent_refused"
|
| 62 |
+
| "lock_busy";
|
| 63 |
+
|
| 64 |
+
export const RETRYABLE: ReadonlySet<ErrorKind> = new Set([
|
| 65 |
+
"spawn_failed",
|
| 66 |
+
"timeout",
|
| 67 |
+
"no_image_gen_tool_use",
|
| 68 |
+
"output_missing",
|
| 69 |
+
"invalid_png",
|
| 70 |
+
"agent_refused",
|
| 71 |
+
]);
|
| 72 |
+
|
| 73 |
+
export class GenError extends Error {
|
| 74 |
+
attempts?: number;
|
| 75 |
+
constructor(public kind: ErrorKind, message: string, public retryable?: boolean) {
|
| 76 |
+
super(message);
|
| 77 |
+
this.retryable = retryable ?? RETRYABLE.has(kind);
|
| 78 |
+
}
|
| 79 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/codex-imagegen/validator.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { stat, readdir } from "node:fs/promises";
|
| 2 |
+
import { homedir } from "node:os";
|
| 3 |
+
import path from "node:path";
|
| 4 |
+
import { GenError } from "./types.ts";
|
| 5 |
+
import type { ToolCall } from "./types.ts";
|
| 6 |
+
|
| 7 |
+
const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
| 8 |
+
|
| 9 |
+
export function codexHome(): string {
|
| 10 |
+
return process.env.CODEX_HOME ?? path.join(homedir(), ".codex");
|
| 11 |
+
}
|
| 12 |
+
|
| 13 |
+
export async function verifyImageGenWasInvoked(threadId: string | null): Promise<{ ok: boolean; reason?: string }> {
|
| 14 |
+
if (!threadId) return { ok: false, reason: "no thread id" };
|
| 15 |
+
const dir = path.join(codexHome(), "generated_images", threadId);
|
| 16 |
+
try {
|
| 17 |
+
const entries = await readdir(dir);
|
| 18 |
+
const pngs = entries.filter((e) => e.toLowerCase().endsWith(".png"));
|
| 19 |
+
if (pngs.length === 0) return { ok: false, reason: `no PNG in ${dir}` };
|
| 20 |
+
return { ok: true };
|
| 21 |
+
} catch (e: any) {
|
| 22 |
+
return { ok: false, reason: `cannot read ${dir}: ${e?.code ?? e?.message}` };
|
| 23 |
+
}
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
export function findCpToTarget(toolCalls: ToolCall[], target: string): boolean {
|
| 27 |
+
return toolCalls.some(
|
| 28 |
+
(tc) =>
|
| 29 |
+
tc.tool === "shell" &&
|
| 30 |
+
typeof tc.command === "string" &&
|
| 31 |
+
(tc.command.includes(target) || tc.command.includes(path.basename(target))) &&
|
| 32 |
+
/\b(cp|mv|cat)\b/.test(tc.command) &&
|
| 33 |
+
tc.command.includes("generated_images"),
|
| 34 |
+
);
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
export async function verifyOutput(outputPath: string): Promise<{ bytes: number }> {
|
| 38 |
+
let s;
|
| 39 |
+
try {
|
| 40 |
+
s = await stat(outputPath);
|
| 41 |
+
} catch {
|
| 42 |
+
throw new GenError("output_missing", `Output file not created: ${outputPath}`);
|
| 43 |
+
}
|
| 44 |
+
if (s.size < 1000) {
|
| 45 |
+
throw new GenError("invalid_png", `Output file too small (${s.size} bytes)`);
|
| 46 |
+
}
|
| 47 |
+
const file = Bun.file(outputPath);
|
| 48 |
+
const head = new Uint8Array(await file.slice(0, 8).arrayBuffer());
|
| 49 |
+
for (let i = 0; i < PNG_MAGIC.length; i++) {
|
| 50 |
+
if (head[i] !== PNG_MAGIC[i]) {
|
| 51 |
+
throw new GenError("invalid_png", `Output is not a valid PNG (magic mismatch)`);
|
| 52 |
+
}
|
| 53 |
+
}
|
| 54 |
+
return { bytes: s.size };
|
| 55 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/main.test.ts
ADDED
|
@@ -0,0 +1,623 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from "node:assert/strict";
|
| 2 |
+
import fs from "node:fs/promises";
|
| 3 |
+
import os from "node:os";
|
| 4 |
+
import path from "node:path";
|
| 5 |
+
import test, { type TestContext } from "node:test";
|
| 6 |
+
|
| 7 |
+
import type { CliArgs, ExtendConfig } from "./types.ts";
|
| 8 |
+
import {
|
| 9 |
+
createTaskArgs,
|
| 10 |
+
detectProvider,
|
| 11 |
+
getConfiguredMaxWorkers,
|
| 12 |
+
getConfiguredProviderRateLimits,
|
| 13 |
+
getWorkerCount,
|
| 14 |
+
isRetryableGenerationError,
|
| 15 |
+
loadBatchTasks,
|
| 16 |
+
loadExtendConfig,
|
| 17 |
+
mergeConfig,
|
| 18 |
+
normalizeOutputImagePath,
|
| 19 |
+
parseArgs,
|
| 20 |
+
parseOpenAIImageApiDialect,
|
| 21 |
+
parseSimpleYaml,
|
| 22 |
+
validateReferenceImages,
|
| 23 |
+
} from "./main.ts";
|
| 24 |
+
|
| 25 |
+
function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
| 26 |
+
return {
|
| 27 |
+
prompt: null,
|
| 28 |
+
promptFiles: [],
|
| 29 |
+
imagePath: null,
|
| 30 |
+
provider: null,
|
| 31 |
+
model: null,
|
| 32 |
+
aspectRatio: null,
|
| 33 |
+
aspectRatioSource: null,
|
| 34 |
+
size: null,
|
| 35 |
+
quality: null,
|
| 36 |
+
imageSize: null,
|
| 37 |
+
imageSizeSource: null,
|
| 38 |
+
imageApiDialect: null,
|
| 39 |
+
referenceImages: [],
|
| 40 |
+
n: 1,
|
| 41 |
+
batchFile: null,
|
| 42 |
+
jobs: null,
|
| 43 |
+
json: false,
|
| 44 |
+
help: false,
|
| 45 |
+
...overrides,
|
| 46 |
+
};
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
function useEnv(
|
| 50 |
+
t: TestContext,
|
| 51 |
+
values: Record<string, string | null>,
|
| 52 |
+
): void {
|
| 53 |
+
const previous = new Map<string, string | undefined>();
|
| 54 |
+
for (const [key, value] of Object.entries(values)) {
|
| 55 |
+
previous.set(key, process.env[key]);
|
| 56 |
+
if (value == null) {
|
| 57 |
+
delete process.env[key];
|
| 58 |
+
} else {
|
| 59 |
+
process.env[key] = value;
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
t.after(() => {
|
| 64 |
+
for (const [key, value] of previous.entries()) {
|
| 65 |
+
if (value == null) {
|
| 66 |
+
delete process.env[key];
|
| 67 |
+
} else {
|
| 68 |
+
process.env[key] = value;
|
| 69 |
+
}
|
| 70 |
+
}
|
| 71 |
+
});
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
async function makeTempDir(prefix: string): Promise<string> {
|
| 75 |
+
return fs.mkdtemp(path.join(os.tmpdir(), prefix));
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
test("parseArgs parses the main baoyu-image-gen CLI flags", () => {
|
| 79 |
+
const args = parseArgs([
|
| 80 |
+
"--promptfiles",
|
| 81 |
+
"prompts/system.md",
|
| 82 |
+
"prompts/content.md",
|
| 83 |
+
"--image",
|
| 84 |
+
"out/hero",
|
| 85 |
+
"--provider",
|
| 86 |
+
"zai",
|
| 87 |
+
"--quality",
|
| 88 |
+
"2k",
|
| 89 |
+
"--imageSize",
|
| 90 |
+
"4k",
|
| 91 |
+
"--imageApiDialect",
|
| 92 |
+
"ratio-metadata",
|
| 93 |
+
"--ref",
|
| 94 |
+
"ref/one.png",
|
| 95 |
+
"ref/two.jpg",
|
| 96 |
+
"--n",
|
| 97 |
+
"3",
|
| 98 |
+
"--jobs",
|
| 99 |
+
"5",
|
| 100 |
+
"--json",
|
| 101 |
+
]);
|
| 102 |
+
|
| 103 |
+
assert.deepEqual(args.promptFiles, ["prompts/system.md", "prompts/content.md"]);
|
| 104 |
+
assert.equal(args.imagePath, "out/hero");
|
| 105 |
+
assert.equal(args.provider, "zai");
|
| 106 |
+
assert.equal(args.quality, "2k");
|
| 107 |
+
assert.equal(args.aspectRatioSource, null);
|
| 108 |
+
assert.equal(args.imageSize, "4K");
|
| 109 |
+
assert.equal(args.imageSizeSource, "cli");
|
| 110 |
+
assert.equal(args.imageApiDialect, "ratio-metadata");
|
| 111 |
+
assert.deepEqual(args.referenceImages, ["ref/one.png", "ref/two.jpg"]);
|
| 112 |
+
assert.equal(args.n, 3);
|
| 113 |
+
assert.equal(args.jobs, 5);
|
| 114 |
+
assert.equal(args.json, true);
|
| 115 |
+
});
|
| 116 |
+
|
| 117 |
+
test("parseArgs falls back to positional prompt and rejects invalid provider", () => {
|
| 118 |
+
const positional = parseArgs(["draw", "a", "cat"]);
|
| 119 |
+
assert.equal(positional.prompt, "draw a cat");
|
| 120 |
+
|
| 121 |
+
assert.throws(
|
| 122 |
+
() => parseArgs(["--provider", "stability"]),
|
| 123 |
+
/Invalid provider/,
|
| 124 |
+
);
|
| 125 |
+
});
|
| 126 |
+
|
| 127 |
+
test("validateReferenceImages can skip remote URLs for providers that support them", async () => {
|
| 128 |
+
await validateReferenceImages(["https://example.com/ref.png"], { allowRemoteUrls: true });
|
| 129 |
+
|
| 130 |
+
await assert.rejects(
|
| 131 |
+
() => validateReferenceImages(["https://example.com/ref.png"]),
|
| 132 |
+
/Reference image not found/,
|
| 133 |
+
);
|
| 134 |
+
});
|
| 135 |
+
|
| 136 |
+
test("parseSimpleYaml parses nested defaults and provider limits", () => {
|
| 137 |
+
const yaml = `
|
| 138 |
+
version: 2
|
| 139 |
+
default_provider: openrouter
|
| 140 |
+
default_quality: normal
|
| 141 |
+
default_aspect_ratio: '16:9'
|
| 142 |
+
default_image_size: 2K
|
| 143 |
+
default_image_api_dialect: ratio-metadata
|
| 144 |
+
default_model:
|
| 145 |
+
google: gemini-3-pro-image
|
| 146 |
+
openai: gpt-image-2
|
| 147 |
+
zai: glm-image
|
| 148 |
+
azure: image-prod
|
| 149 |
+
minimax: image-01
|
| 150 |
+
batch:
|
| 151 |
+
max_workers: 8
|
| 152 |
+
provider_limits:
|
| 153 |
+
google:
|
| 154 |
+
concurrency: 2
|
| 155 |
+
start_interval_ms: 900
|
| 156 |
+
openai:
|
| 157 |
+
concurrency: 4
|
| 158 |
+
zai:
|
| 159 |
+
concurrency: 2
|
| 160 |
+
start_interval_ms: 1000
|
| 161 |
+
minimax:
|
| 162 |
+
concurrency: 2
|
| 163 |
+
start_interval_ms: 1400
|
| 164 |
+
azure:
|
| 165 |
+
concurrency: 1
|
| 166 |
+
start_interval_ms: 1500
|
| 167 |
+
`;
|
| 168 |
+
|
| 169 |
+
const config = parseSimpleYaml(yaml);
|
| 170 |
+
|
| 171 |
+
assert.equal(config.version, 2);
|
| 172 |
+
assert.equal(config.default_provider, "openrouter");
|
| 173 |
+
assert.equal(config.default_quality, "normal");
|
| 174 |
+
assert.equal(config.default_aspect_ratio, "16:9");
|
| 175 |
+
assert.equal(config.default_image_size, "2K");
|
| 176 |
+
assert.equal(config.default_image_api_dialect, "ratio-metadata");
|
| 177 |
+
assert.equal(config.default_model?.google, "gemini-3-pro-image");
|
| 178 |
+
assert.equal(config.default_model?.openai, "gpt-image-2");
|
| 179 |
+
assert.equal(config.default_model?.zai, "glm-image");
|
| 180 |
+
assert.equal(config.default_model?.azure, "image-prod");
|
| 181 |
+
assert.equal(config.default_model?.minimax, "image-01");
|
| 182 |
+
assert.equal(config.batch?.max_workers, 8);
|
| 183 |
+
assert.deepEqual(config.batch?.provider_limits?.google, {
|
| 184 |
+
concurrency: 2,
|
| 185 |
+
start_interval_ms: 900,
|
| 186 |
+
});
|
| 187 |
+
assert.deepEqual(config.batch?.provider_limits?.openai, {
|
| 188 |
+
concurrency: 4,
|
| 189 |
+
});
|
| 190 |
+
assert.deepEqual(config.batch?.provider_limits?.zai, {
|
| 191 |
+
concurrency: 2,
|
| 192 |
+
start_interval_ms: 1000,
|
| 193 |
+
});
|
| 194 |
+
assert.deepEqual(config.batch?.provider_limits?.minimax, {
|
| 195 |
+
concurrency: 2,
|
| 196 |
+
start_interval_ms: 1400,
|
| 197 |
+
});
|
| 198 |
+
assert.deepEqual(config.batch?.provider_limits?.azure, {
|
| 199 |
+
concurrency: 1,
|
| 200 |
+
start_interval_ms: 1500,
|
| 201 |
+
});
|
| 202 |
+
});
|
| 203 |
+
|
| 204 |
+
test("loadExtendConfig renames legacy EXTEND.md when the new path is missing", async () => {
|
| 205 |
+
const root = await makeTempDir("baoyu-image-gen-extend-");
|
| 206 |
+
const cwd = path.join(root, "project");
|
| 207 |
+
const home = path.join(root, "home");
|
| 208 |
+
const legacyPath = path.join(cwd, ".baoyu-skills", "baoyu-imagine", "EXTEND.md");
|
| 209 |
+
const currentPath = path.join(cwd, ".baoyu-skills", "baoyu-image-gen", "EXTEND.md");
|
| 210 |
+
|
| 211 |
+
await fs.mkdir(path.dirname(legacyPath), { recursive: true });
|
| 212 |
+
await fs.mkdir(home, { recursive: true });
|
| 213 |
+
await fs.writeFile(legacyPath, `---
|
| 214 |
+
default_provider: google
|
| 215 |
+
default_quality: 2k
|
| 216 |
+
---
|
| 217 |
+
`);
|
| 218 |
+
|
| 219 |
+
const config = await loadExtendConfig(cwd, home);
|
| 220 |
+
|
| 221 |
+
assert.equal(config.default_provider, "google");
|
| 222 |
+
assert.equal(config.default_quality, "2k");
|
| 223 |
+
await fs.access(currentPath);
|
| 224 |
+
await assert.rejects(() => fs.access(legacyPath));
|
| 225 |
+
});
|
| 226 |
+
|
| 227 |
+
test("loadExtendConfig leaves legacy EXTEND.md untouched when both paths exist", async () => {
|
| 228 |
+
const root = await makeTempDir("baoyu-image-gen-extend-dual-");
|
| 229 |
+
const cwd = path.join(root, "project");
|
| 230 |
+
const home = path.join(root, "home");
|
| 231 |
+
const legacyPath = path.join(cwd, ".baoyu-skills", "baoyu-imagine", "EXTEND.md");
|
| 232 |
+
const currentPath = path.join(cwd, ".baoyu-skills", "baoyu-image-gen", "EXTEND.md");
|
| 233 |
+
|
| 234 |
+
await fs.mkdir(path.dirname(legacyPath), { recursive: true });
|
| 235 |
+
await fs.mkdir(path.dirname(currentPath), { recursive: true });
|
| 236 |
+
await fs.mkdir(home, { recursive: true });
|
| 237 |
+
await fs.writeFile(legacyPath, `---
|
| 238 |
+
default_provider: google
|
| 239 |
+
---
|
| 240 |
+
`);
|
| 241 |
+
await fs.writeFile(currentPath, `---
|
| 242 |
+
default_provider: openai
|
| 243 |
+
---
|
| 244 |
+
`);
|
| 245 |
+
|
| 246 |
+
const config = await loadExtendConfig(cwd, home);
|
| 247 |
+
|
| 248 |
+
assert.equal(config.default_provider, "openai");
|
| 249 |
+
assert.equal(await fs.readFile(legacyPath, "utf8"), `---
|
| 250 |
+
default_provider: google
|
| 251 |
+
---
|
| 252 |
+
`);
|
| 253 |
+
assert.equal(await fs.readFile(currentPath, "utf8"), `---
|
| 254 |
+
default_provider: openai
|
| 255 |
+
---
|
| 256 |
+
`);
|
| 257 |
+
});
|
| 258 |
+
|
| 259 |
+
test("mergeConfig only fills values missing from CLI args", () => {
|
| 260 |
+
const merged = mergeConfig(
|
| 261 |
+
makeArgs({
|
| 262 |
+
provider: "openai",
|
| 263 |
+
quality: null,
|
| 264 |
+
aspectRatio: null,
|
| 265 |
+
imageSize: "4K",
|
| 266 |
+
}),
|
| 267 |
+
{
|
| 268 |
+
default_provider: "google",
|
| 269 |
+
default_quality: "2k",
|
| 270 |
+
default_aspect_ratio: "3:2",
|
| 271 |
+
default_image_size: "2K",
|
| 272 |
+
default_image_api_dialect: "ratio-metadata",
|
| 273 |
+
} satisfies Partial<ExtendConfig>,
|
| 274 |
+
);
|
| 275 |
+
|
| 276 |
+
assert.equal(merged.provider, "openai");
|
| 277 |
+
assert.equal(merged.quality, "2k");
|
| 278 |
+
assert.equal(merged.aspectRatio, "3:2");
|
| 279 |
+
assert.equal(merged.aspectRatioSource, "config");
|
| 280 |
+
assert.equal(merged.imageSize, "4K");
|
| 281 |
+
assert.equal(merged.imageSizeSource, "cli");
|
| 282 |
+
assert.equal(merged.imageApiDialect, "ratio-metadata");
|
| 283 |
+
});
|
| 284 |
+
|
| 285 |
+
test("mergeConfig tags inherited imageSize defaults so providers can ignore incompatible config", () => {
|
| 286 |
+
const merged = mergeConfig(
|
| 287 |
+
makeArgs(),
|
| 288 |
+
{
|
| 289 |
+
default_image_size: "2K",
|
| 290 |
+
} satisfies Partial<ExtendConfig>,
|
| 291 |
+
);
|
| 292 |
+
|
| 293 |
+
assert.equal(merged.imageSize, "2K");
|
| 294 |
+
assert.equal(merged.imageSizeSource, "config");
|
| 295 |
+
});
|
| 296 |
+
|
| 297 |
+
test("mergeConfig falls back to OPENAI_IMAGE_API_DIALECT when CLI and EXTEND are unset", (t) => {
|
| 298 |
+
useEnv(t, {
|
| 299 |
+
OPENAI_IMAGE_API_DIALECT: "ratio-metadata",
|
| 300 |
+
});
|
| 301 |
+
|
| 302 |
+
const merged = mergeConfig(makeArgs(), {});
|
| 303 |
+
assert.equal(merged.imageApiDialect, "ratio-metadata");
|
| 304 |
+
});
|
| 305 |
+
|
| 306 |
+
test("parseOpenAIImageApiDialect validates supported values", () => {
|
| 307 |
+
assert.equal(parseOpenAIImageApiDialect("openai-native"), "openai-native");
|
| 308 |
+
assert.equal(parseOpenAIImageApiDialect("ratio-metadata"), "ratio-metadata");
|
| 309 |
+
assert.equal(parseOpenAIImageApiDialect(null), null);
|
| 310 |
+
assert.throws(
|
| 311 |
+
() => parseOpenAIImageApiDialect("gateway-magic"),
|
| 312 |
+
/Invalid OpenAI image API dialect/,
|
| 313 |
+
);
|
| 314 |
+
});
|
| 315 |
+
|
| 316 |
+
test("detectProvider rejects non-ref-capable providers and prefers Google first when multiple keys exist", (t) => {
|
| 317 |
+
assert.throws(
|
| 318 |
+
() =>
|
| 319 |
+
detectProvider(
|
| 320 |
+
makeArgs({
|
| 321 |
+
provider: "zai",
|
| 322 |
+
referenceImages: ["ref.png"],
|
| 323 |
+
}),
|
| 324 |
+
),
|
| 325 |
+
/Reference images require a ref-capable provider/,
|
| 326 |
+
);
|
| 327 |
+
|
| 328 |
+
useEnv(t, {
|
| 329 |
+
GOOGLE_API_KEY: "google-key",
|
| 330 |
+
OPENAI_API_KEY: "openai-key",
|
| 331 |
+
OPENROUTER_API_KEY: null,
|
| 332 |
+
DASHSCOPE_API_KEY: null,
|
| 333 |
+
MINIMAX_API_KEY: null,
|
| 334 |
+
REPLICATE_API_TOKEN: null,
|
| 335 |
+
JIMENG_ACCESS_KEY_ID: null,
|
| 336 |
+
JIMENG_SECRET_ACCESS_KEY: null,
|
| 337 |
+
ARK_API_KEY: null,
|
| 338 |
+
});
|
| 339 |
+
assert.equal(detectProvider(makeArgs()), "google");
|
| 340 |
+
});
|
| 341 |
+
|
| 342 |
+
test("detectProvider selects an available ref-capable provider for reference-image tasks", (t) => {
|
| 343 |
+
useEnv(t, {
|
| 344 |
+
GOOGLE_API_KEY: null,
|
| 345 |
+
OPENAI_API_KEY: "openai-key",
|
| 346 |
+
AZURE_OPENAI_API_KEY: null,
|
| 347 |
+
AZURE_OPENAI_BASE_URL: null,
|
| 348 |
+
OPENROUTER_API_KEY: null,
|
| 349 |
+
DASHSCOPE_API_KEY: null,
|
| 350 |
+
MINIMAX_API_KEY: null,
|
| 351 |
+
REPLICATE_API_TOKEN: null,
|
| 352 |
+
JIMENG_ACCESS_KEY_ID: null,
|
| 353 |
+
JIMENG_SECRET_ACCESS_KEY: null,
|
| 354 |
+
ARK_API_KEY: null,
|
| 355 |
+
});
|
| 356 |
+
assert.equal(
|
| 357 |
+
detectProvider(makeArgs({ referenceImages: ["ref.png"] })),
|
| 358 |
+
"openai",
|
| 359 |
+
);
|
| 360 |
+
});
|
| 361 |
+
|
| 362 |
+
test("detectProvider selects Azure when only Azure credentials are configured", (t) => {
|
| 363 |
+
useEnv(t, {
|
| 364 |
+
GOOGLE_API_KEY: null,
|
| 365 |
+
OPENAI_API_KEY: null,
|
| 366 |
+
AZURE_OPENAI_API_KEY: "azure-key",
|
| 367 |
+
AZURE_OPENAI_BASE_URL: "https://example.openai.azure.com",
|
| 368 |
+
OPENROUTER_API_KEY: null,
|
| 369 |
+
DASHSCOPE_API_KEY: null,
|
| 370 |
+
MINIMAX_API_KEY: null,
|
| 371 |
+
REPLICATE_API_TOKEN: null,
|
| 372 |
+
JIMENG_ACCESS_KEY_ID: null,
|
| 373 |
+
JIMENG_SECRET_ACCESS_KEY: null,
|
| 374 |
+
ARK_API_KEY: null,
|
| 375 |
+
});
|
| 376 |
+
|
| 377 |
+
assert.equal(detectProvider(makeArgs()), "azure");
|
| 378 |
+
assert.equal(
|
| 379 |
+
detectProvider(makeArgs({ referenceImages: ["ref.png"] })),
|
| 380 |
+
"azure",
|
| 381 |
+
);
|
| 382 |
+
});
|
| 383 |
+
|
| 384 |
+
test("detectProvider selects Z.AI when credentials are present or the model id matches", (t) => {
|
| 385 |
+
useEnv(t, {
|
| 386 |
+
GOOGLE_API_KEY: null,
|
| 387 |
+
OPENAI_API_KEY: null,
|
| 388 |
+
AZURE_OPENAI_API_KEY: null,
|
| 389 |
+
AZURE_OPENAI_BASE_URL: null,
|
| 390 |
+
OPENROUTER_API_KEY: null,
|
| 391 |
+
DASHSCOPE_API_KEY: null,
|
| 392 |
+
ZAI_API_KEY: "zai-key",
|
| 393 |
+
BIGMODEL_API_KEY: null,
|
| 394 |
+
MINIMAX_API_KEY: null,
|
| 395 |
+
REPLICATE_API_TOKEN: null,
|
| 396 |
+
JIMENG_ACCESS_KEY_ID: null,
|
| 397 |
+
JIMENG_SECRET_ACCESS_KEY: null,
|
| 398 |
+
ARK_API_KEY: null,
|
| 399 |
+
});
|
| 400 |
+
|
| 401 |
+
assert.equal(detectProvider(makeArgs()), "zai");
|
| 402 |
+
assert.equal(detectProvider(makeArgs({ model: "glm-image" })), "zai");
|
| 403 |
+
});
|
| 404 |
+
|
| 405 |
+
test("detectProvider infers Seedream from model id and allows Seedream reference-image workflows", (t) => {
|
| 406 |
+
useEnv(t, {
|
| 407 |
+
GOOGLE_API_KEY: null,
|
| 408 |
+
OPENAI_API_KEY: null,
|
| 409 |
+
OPENROUTER_API_KEY: null,
|
| 410 |
+
DASHSCOPE_API_KEY: null,
|
| 411 |
+
MINIMAX_API_KEY: null,
|
| 412 |
+
REPLICATE_API_TOKEN: null,
|
| 413 |
+
JIMENG_ACCESS_KEY_ID: null,
|
| 414 |
+
JIMENG_SECRET_ACCESS_KEY: null,
|
| 415 |
+
ARK_API_KEY: "ark-key",
|
| 416 |
+
});
|
| 417 |
+
|
| 418 |
+
assert.equal(
|
| 419 |
+
detectProvider(
|
| 420 |
+
makeArgs({
|
| 421 |
+
model: "doubao-seedream-4-5-251128",
|
| 422 |
+
referenceImages: ["ref.png"],
|
| 423 |
+
}),
|
| 424 |
+
),
|
| 425 |
+
"seedream",
|
| 426 |
+
);
|
| 427 |
+
|
| 428 |
+
assert.equal(
|
| 429 |
+
detectProvider(
|
| 430 |
+
makeArgs({
|
| 431 |
+
provider: "seedream",
|
| 432 |
+
referenceImages: ["ref.png"],
|
| 433 |
+
}),
|
| 434 |
+
),
|
| 435 |
+
"seedream",
|
| 436 |
+
);
|
| 437 |
+
});
|
| 438 |
+
|
| 439 |
+
test("detectProvider allows DashScope reference-image workflows when explicitly chosen for wan2.7 models", (t) => {
|
| 440 |
+
useEnv(t, {
|
| 441 |
+
GOOGLE_API_KEY: null,
|
| 442 |
+
OPENAI_API_KEY: null,
|
| 443 |
+
AZURE_OPENAI_API_KEY: null,
|
| 444 |
+
AZURE_OPENAI_BASE_URL: null,
|
| 445 |
+
OPENROUTER_API_KEY: null,
|
| 446 |
+
DASHSCOPE_API_KEY: "dashscope-key",
|
| 447 |
+
MINIMAX_API_KEY: null,
|
| 448 |
+
REPLICATE_API_TOKEN: null,
|
| 449 |
+
JIMENG_ACCESS_KEY_ID: null,
|
| 450 |
+
JIMENG_SECRET_ACCESS_KEY: null,
|
| 451 |
+
ARK_API_KEY: null,
|
| 452 |
+
});
|
| 453 |
+
|
| 454 |
+
assert.equal(
|
| 455 |
+
detectProvider(
|
| 456 |
+
makeArgs({
|
| 457 |
+
provider: "dashscope",
|
| 458 |
+
model: "wan2.7-image-pro",
|
| 459 |
+
referenceImages: ["ref.png"],
|
| 460 |
+
}),
|
| 461 |
+
),
|
| 462 |
+
"dashscope",
|
| 463 |
+
);
|
| 464 |
+
});
|
| 465 |
+
|
| 466 |
+
test("detectProvider selects MiniMax when only MiniMax credentials are configured or the model id matches", (t) => {
|
| 467 |
+
useEnv(t, {
|
| 468 |
+
GOOGLE_API_KEY: null,
|
| 469 |
+
OPENAI_API_KEY: null,
|
| 470 |
+
AZURE_OPENAI_API_KEY: null,
|
| 471 |
+
AZURE_OPENAI_BASE_URL: null,
|
| 472 |
+
OPENROUTER_API_KEY: null,
|
| 473 |
+
DASHSCOPE_API_KEY: null,
|
| 474 |
+
MINIMAX_API_KEY: "minimax-key",
|
| 475 |
+
REPLICATE_API_TOKEN: null,
|
| 476 |
+
JIMENG_ACCESS_KEY_ID: null,
|
| 477 |
+
JIMENG_SECRET_ACCESS_KEY: null,
|
| 478 |
+
ARK_API_KEY: null,
|
| 479 |
+
});
|
| 480 |
+
|
| 481 |
+
assert.equal(detectProvider(makeArgs()), "minimax");
|
| 482 |
+
assert.equal(detectProvider(makeArgs({ referenceImages: ["ref.png"] })), "minimax");
|
| 483 |
+
assert.equal(detectProvider(makeArgs({ model: "image-01-live" })), "minimax");
|
| 484 |
+
});
|
| 485 |
+
|
| 486 |
+
test("batch worker and provider-rate-limit configuration prefer env over EXTEND config", (t) => {
|
| 487 |
+
useEnv(t, {
|
| 488 |
+
BAOYU_IMAGE_GEN_MAX_WORKERS: "12",
|
| 489 |
+
BAOYU_IMAGE_GEN_GOOGLE_CONCURRENCY: "5",
|
| 490 |
+
BAOYU_IMAGE_GEN_GOOGLE_START_INTERVAL_MS: "450",
|
| 491 |
+
BAOYU_IMAGE_GEN_ZAI_CONCURRENCY: "4",
|
| 492 |
+
});
|
| 493 |
+
|
| 494 |
+
const extendConfig: Partial<ExtendConfig> = {
|
| 495 |
+
batch: {
|
| 496 |
+
max_workers: 7,
|
| 497 |
+
provider_limits: {
|
| 498 |
+
google: {
|
| 499 |
+
concurrency: 2,
|
| 500 |
+
start_interval_ms: 900,
|
| 501 |
+
},
|
| 502 |
+
zai: {
|
| 503 |
+
concurrency: 1,
|
| 504 |
+
start_interval_ms: 1200,
|
| 505 |
+
},
|
| 506 |
+
minimax: {
|
| 507 |
+
concurrency: 1,
|
| 508 |
+
start_interval_ms: 1500,
|
| 509 |
+
},
|
| 510 |
+
},
|
| 511 |
+
},
|
| 512 |
+
};
|
| 513 |
+
|
| 514 |
+
assert.equal(getConfiguredMaxWorkers(extendConfig), 12);
|
| 515 |
+
assert.deepEqual(getConfiguredProviderRateLimits(extendConfig).google, {
|
| 516 |
+
concurrency: 5,
|
| 517 |
+
startIntervalMs: 450,
|
| 518 |
+
});
|
| 519 |
+
assert.deepEqual(getConfiguredProviderRateLimits(extendConfig).zai, {
|
| 520 |
+
concurrency: 4,
|
| 521 |
+
startIntervalMs: 1200,
|
| 522 |
+
});
|
| 523 |
+
assert.deepEqual(getConfiguredProviderRateLimits(extendConfig).minimax, {
|
| 524 |
+
concurrency: 1,
|
| 525 |
+
startIntervalMs: 1500,
|
| 526 |
+
});
|
| 527 |
+
});
|
| 528 |
+
|
| 529 |
+
test("loadBatchTasks and createTaskArgs resolve batch-relative paths", async (t) => {
|
| 530 |
+
const root = await makeTempDir("baoyu-image-gen-batch-");
|
| 531 |
+
t.after(() => fs.rm(root, { recursive: true, force: true }));
|
| 532 |
+
|
| 533 |
+
const batchFile = path.join(root, "jobs", "batch.json");
|
| 534 |
+
await fs.mkdir(path.dirname(batchFile), { recursive: true });
|
| 535 |
+
await fs.writeFile(
|
| 536 |
+
batchFile,
|
| 537 |
+
JSON.stringify({
|
| 538 |
+
jobs: 2,
|
| 539 |
+
tasks: [
|
| 540 |
+
{
|
| 541 |
+
id: "hero",
|
| 542 |
+
promptFiles: ["prompts/hero.md"],
|
| 543 |
+
image: "out/hero",
|
| 544 |
+
ref: ["refs/hero.png", "https://example.com/ref.png"],
|
| 545 |
+
ar: "16:9",
|
| 546 |
+
},
|
| 547 |
+
],
|
| 548 |
+
}),
|
| 549 |
+
);
|
| 550 |
+
|
| 551 |
+
const loaded = await loadBatchTasks(batchFile);
|
| 552 |
+
assert.equal(loaded.jobs, 2);
|
| 553 |
+
assert.equal(loaded.batchDir, path.dirname(batchFile));
|
| 554 |
+
assert.equal(loaded.tasks[0]?.id, "hero");
|
| 555 |
+
|
| 556 |
+
const taskArgs = createTaskArgs(
|
| 557 |
+
makeArgs({
|
| 558 |
+
provider: "replicate",
|
| 559 |
+
quality: "2k",
|
| 560 |
+
imageApiDialect: "ratio-metadata",
|
| 561 |
+
json: true,
|
| 562 |
+
}),
|
| 563 |
+
loaded.tasks[0]!,
|
| 564 |
+
loaded.batchDir,
|
| 565 |
+
);
|
| 566 |
+
|
| 567 |
+
assert.deepEqual(taskArgs.promptFiles, [
|
| 568 |
+
path.join(loaded.batchDir, "prompts/hero.md"),
|
| 569 |
+
]);
|
| 570 |
+
assert.equal(taskArgs.imagePath, path.join(loaded.batchDir, "out/hero"));
|
| 571 |
+
assert.deepEqual(taskArgs.referenceImages, [
|
| 572 |
+
path.join(loaded.batchDir, "refs/hero.png"),
|
| 573 |
+
"https://example.com/ref.png",
|
| 574 |
+
]);
|
| 575 |
+
assert.equal(taskArgs.provider, "replicate");
|
| 576 |
+
assert.equal(taskArgs.aspectRatio, "16:9");
|
| 577 |
+
assert.equal(taskArgs.quality, "2k");
|
| 578 |
+
assert.equal(taskArgs.imageApiDialect, "ratio-metadata");
|
| 579 |
+
assert.equal(taskArgs.json, true);
|
| 580 |
+
});
|
| 581 |
+
|
| 582 |
+
test("path normalization, worker count, and retry classification follow expected rules", () => {
|
| 583 |
+
assert.match(normalizeOutputImagePath("out/sample"), /out[\\/]+sample\.png$/);
|
| 584 |
+
assert.match(normalizeOutputImagePath("out/sample", ".jpg"), /out[\\/]+sample\.jpg$/);
|
| 585 |
+
assert.match(normalizeOutputImagePath("out/sample.webp"), /out[\\/]+sample\.webp$/);
|
| 586 |
+
|
| 587 |
+
assert.equal(getWorkerCount(8, null, 3), 3);
|
| 588 |
+
assert.equal(getWorkerCount(2, 6, 5), 2);
|
| 589 |
+
assert.equal(getWorkerCount(5, 0, 4), 1);
|
| 590 |
+
|
| 591 |
+
assert.equal(isRetryableGenerationError(new Error("API error (401): denied")), false);
|
| 592 |
+
assert.equal(
|
| 593 |
+
isRetryableGenerationError(
|
| 594 |
+
new Error("Replicate returned 2 outputs, but baoyu-image-gen currently supports saving exactly one image per request."),
|
| 595 |
+
),
|
| 596 |
+
false,
|
| 597 |
+
);
|
| 598 |
+
assert.equal(
|
| 599 |
+
isRetryableGenerationError(
|
| 600 |
+
new Error("DashScope wan2.7 image models accept at most 9 reference images. Received 10."),
|
| 601 |
+
),
|
| 602 |
+
false,
|
| 603 |
+
);
|
| 604 |
+
assert.equal(
|
| 605 |
+
isRetryableGenerationError(
|
| 606 |
+
new Error("DashScope wan2.7 image models in baoyu-image-gen support exactly one output image per request."),
|
| 607 |
+
),
|
| 608 |
+
false,
|
| 609 |
+
);
|
| 610 |
+
assert.equal(
|
| 611 |
+
isRetryableGenerationError(
|
| 612 |
+
new Error("DashScope wan2.7 image models support aspect ratios in [1:8, 8:1]."),
|
| 613 |
+
),
|
| 614 |
+
false,
|
| 615 |
+
);
|
| 616 |
+
assert.equal(
|
| 617 |
+
isRetryableGenerationError(
|
| 618 |
+
new Error("DashScope wan2.7-image requires total pixels between 768*768 and 2048*2048."),
|
| 619 |
+
),
|
| 620 |
+
false,
|
| 621 |
+
);
|
| 622 |
+
assert.equal(isRetryableGenerationError(new Error("socket hang up")), true);
|
| 623 |
+
});
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import path from "node:path";
|
| 2 |
+
import process from "node:process";
|
| 3 |
+
import { homedir } from "node:os";
|
| 4 |
+
import { fileURLToPath } from "node:url";
|
| 5 |
+
import { access, mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
| 6 |
+
import type {
|
| 7 |
+
BatchFile,
|
| 8 |
+
BatchTaskInput,
|
| 9 |
+
CliArgs,
|
| 10 |
+
ExtendConfig,
|
| 11 |
+
OpenAIImageApiDialect,
|
| 12 |
+
Provider,
|
| 13 |
+
} from "./types";
|
| 14 |
+
|
| 15 |
+
type ProviderModule = {
|
| 16 |
+
getDefaultModel: () => string;
|
| 17 |
+
generateImage: (prompt: string, model: string, args: CliArgs) => Promise<Uint8Array>;
|
| 18 |
+
validateArgs?: (model: string, args: CliArgs) => void;
|
| 19 |
+
getDefaultOutputExtension?: (model: string, args: CliArgs) => string;
|
| 20 |
+
};
|
| 21 |
+
|
| 22 |
+
type PreparedTask = {
|
| 23 |
+
id: string;
|
| 24 |
+
prompt: string;
|
| 25 |
+
args: CliArgs;
|
| 26 |
+
provider: Provider;
|
| 27 |
+
model: string;
|
| 28 |
+
outputPath: string;
|
| 29 |
+
providerModule: ProviderModule;
|
| 30 |
+
};
|
| 31 |
+
|
| 32 |
+
type TaskResult = {
|
| 33 |
+
id: string;
|
| 34 |
+
provider: Provider;
|
| 35 |
+
model: string;
|
| 36 |
+
outputPath: string;
|
| 37 |
+
success: boolean;
|
| 38 |
+
attempts: number;
|
| 39 |
+
error: string | null;
|
| 40 |
+
};
|
| 41 |
+
|
| 42 |
+
type ProviderRateLimit = {
|
| 43 |
+
concurrency: number;
|
| 44 |
+
startIntervalMs: number;
|
| 45 |
+
};
|
| 46 |
+
|
| 47 |
+
type LoadedBatchTasks = {
|
| 48 |
+
tasks: BatchTaskInput[];
|
| 49 |
+
jobs: number | null;
|
| 50 |
+
batchDir: string;
|
| 51 |
+
};
|
| 52 |
+
|
| 53 |
+
const MAX_ATTEMPTS = 3;
|
| 54 |
+
const DEFAULT_MAX_WORKERS = 10;
|
| 55 |
+
const POLL_WAIT_MS = 250;
|
| 56 |
+
const DEFAULT_PROVIDER_RATE_LIMITS: Record<Provider, ProviderRateLimit> = {
|
| 57 |
+
replicate: { concurrency: 5, startIntervalMs: 700 },
|
| 58 |
+
google: { concurrency: 3, startIntervalMs: 1100 },
|
| 59 |
+
openai: { concurrency: 3, startIntervalMs: 1100 },
|
| 60 |
+
openrouter: { concurrency: 3, startIntervalMs: 1100 },
|
| 61 |
+
dashscope: { concurrency: 3, startIntervalMs: 1100 },
|
| 62 |
+
zai: { concurrency: 3, startIntervalMs: 1100 },
|
| 63 |
+
minimax: { concurrency: 3, startIntervalMs: 1100 },
|
| 64 |
+
jimeng: { concurrency: 3, startIntervalMs: 1100 },
|
| 65 |
+
seedream: { concurrency: 3, startIntervalMs: 1100 },
|
| 66 |
+
azure: { concurrency: 3, startIntervalMs: 1100 },
|
| 67 |
+
"codex-cli": { concurrency: 1, startIntervalMs: 2000 },
|
| 68 |
+
};
|
| 69 |
+
|
| 70 |
+
function printUsage(): void {
|
| 71 |
+
console.log(`Usage:
|
| 72 |
+
npx -y bun scripts/main.ts --prompt "A cat" --image cat.png
|
| 73 |
+
npx -y bun scripts/main.ts --promptfiles system.md content.md --image out.png
|
| 74 |
+
npx -y bun scripts/main.ts --batchfile batch.json
|
| 75 |
+
|
| 76 |
+
Options:
|
| 77 |
+
-p, --prompt <text> Prompt text
|
| 78 |
+
--promptfiles <files...> Read prompt from files (concatenated)
|
| 79 |
+
--image <path> Output image path (required in single-image mode)
|
| 80 |
+
--batchfile <path> JSON batch file for multi-image generation
|
| 81 |
+
--jobs <count> Worker count for batch mode (default: auto, max from config, built-in default 10)
|
| 82 |
+
--provider google|openai|openrouter|dashscope|zai|minimax|replicate|jimeng|seedream|azure|codex-cli Force provider (auto-detect by default)
|
| 83 |
+
-m, --model <id> Model ID
|
| 84 |
+
--ar <ratio> Aspect ratio (e.g., 16:9, 1:1, 4:3)
|
| 85 |
+
--size <WxH> Size (e.g., 1024x1024)
|
| 86 |
+
--quality normal|2k Quality preset (default: 2k)
|
| 87 |
+
--imageSize 1K|2K|4K Image size for Google/OpenRouter (default: from quality)
|
| 88 |
+
--imageApiDialect <id> OpenAI-compatible image dialect: openai-native|ratio-metadata
|
| 89 |
+
--ref <files...> Reference images (Google, OpenAI, Azure, OpenRouter, Replicate supported families, MiniMax, Seedream 4.0/4.5/5.0, or DashScope wan2.7-image*)
|
| 90 |
+
--n <count> Number of images for the current task (default: 1; Replicate currently requires 1)
|
| 91 |
+
--json JSON output
|
| 92 |
+
-h, --help Show help
|
| 93 |
+
|
| 94 |
+
Batch file format:
|
| 95 |
+
{
|
| 96 |
+
"jobs": 4,
|
| 97 |
+
"tasks": [
|
| 98 |
+
{
|
| 99 |
+
"id": "hero",
|
| 100 |
+
"promptFiles": ["prompts/hero.md"],
|
| 101 |
+
"image": "out/hero.png",
|
| 102 |
+
"provider": "replicate",
|
| 103 |
+
"model": "google/nano-banana-2",
|
| 104 |
+
"ar": "16:9"
|
| 105 |
+
}
|
| 106 |
+
]
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
Behavior:
|
| 110 |
+
- Batch mode automatically runs in parallel when pending tasks >= 2
|
| 111 |
+
- Each image retries automatically up to 3 attempts
|
| 112 |
+
- Batch summary reports success count, failure count, and per-image errors
|
| 113 |
+
- Replicate currently supports single-image save semantics only; --n must stay at 1
|
| 114 |
+
|
| 115 |
+
Environment variables:
|
| 116 |
+
OPENAI_API_KEY OpenAI API key
|
| 117 |
+
OPENROUTER_API_KEY OpenRouter API key
|
| 118 |
+
GOOGLE_API_KEY Google API key
|
| 119 |
+
GEMINI_API_KEY Gemini API key (alias for GOOGLE_API_KEY)
|
| 120 |
+
DASHSCOPE_API_KEY DashScope API key
|
| 121 |
+
ZAI_API_KEY Z.AI API key
|
| 122 |
+
BIGMODEL_API_KEY Backward-compatible alias for Z.AI API key
|
| 123 |
+
MINIMAX_API_KEY MiniMax API key
|
| 124 |
+
REPLICATE_API_TOKEN Replicate API token
|
| 125 |
+
JIMENG_ACCESS_KEY_ID Jimeng Access Key ID
|
| 126 |
+
JIMENG_SECRET_ACCESS_KEY Jimeng Secret Access Key
|
| 127 |
+
ARK_API_KEY Seedream/Ark API key
|
| 128 |
+
OPENAI_IMAGE_MODEL Default OpenAI model (gpt-image-2)
|
| 129 |
+
OPENROUTER_IMAGE_MODEL Default OpenRouter model (google/gemini-3.1-flash-image)
|
| 130 |
+
GOOGLE_IMAGE_MODEL Default Google model (gemini-3-pro-image)
|
| 131 |
+
DASHSCOPE_IMAGE_MODEL Default DashScope model (qwen-image-2.0-pro)
|
| 132 |
+
ZAI_IMAGE_MODEL Default Z.AI model (glm-image)
|
| 133 |
+
BIGMODEL_IMAGE_MODEL Backward-compatible alias for Z.AI model (glm-image)
|
| 134 |
+
MINIMAX_IMAGE_MODEL Default MiniMax model (image-01)
|
| 135 |
+
REPLICATE_IMAGE_MODEL Default Replicate model (google/nano-banana-2)
|
| 136 |
+
JIMENG_IMAGE_MODEL Default Jimeng model (jimeng_t2i_v40)
|
| 137 |
+
SEEDREAM_IMAGE_MODEL Default Seedream model (doubao-seedream-5-0-260128)
|
| 138 |
+
OPENAI_BASE_URL Custom OpenAI endpoint
|
| 139 |
+
OPENAI_IMAGE_API_DIALECT OpenAI-compatible image dialect (openai-native|ratio-metadata)
|
| 140 |
+
OPENAI_IMAGE_USE_CHAT Use /chat/completions instead of /images/generations (true|false)
|
| 141 |
+
OPENROUTER_BASE_URL Custom OpenRouter endpoint
|
| 142 |
+
OPENROUTER_HTTP_REFERER Optional app URL for OpenRouter attribution
|
| 143 |
+
OPENROUTER_TITLE Optional app name for OpenRouter attribution
|
| 144 |
+
GOOGLE_BASE_URL Custom Google endpoint
|
| 145 |
+
DASHSCOPE_BASE_URL Custom DashScope endpoint
|
| 146 |
+
ZAI_BASE_URL Custom Z.AI endpoint
|
| 147 |
+
BIGMODEL_BASE_URL Backward-compatible alias for Z.AI endpoint
|
| 148 |
+
MINIMAX_BASE_URL Custom MiniMax endpoint
|
| 149 |
+
REPLICATE_BASE_URL Custom Replicate endpoint
|
| 150 |
+
JIMENG_BASE_URL Custom Jimeng endpoint
|
| 151 |
+
AZURE_OPENAI_API_KEY Azure OpenAI API key
|
| 152 |
+
AZURE_OPENAI_BASE_URL Azure OpenAI resource or deployment endpoint
|
| 153 |
+
AZURE_OPENAI_DEPLOYMENT Default Azure deployment name
|
| 154 |
+
AZURE_API_VERSION Azure API version (default: 2025-04-01-preview)
|
| 155 |
+
AZURE_OPENAI_IMAGE_MODEL Backward-compatible Azure deployment/model alias (defaults to gpt-image-2)
|
| 156 |
+
SEEDREAM_BASE_URL Custom Seedream endpoint
|
| 157 |
+
BAOYU_IMAGE_GEN_MAX_WORKERS Override batch worker cap
|
| 158 |
+
BAOYU_IMAGE_GEN_<PROVIDER>_CONCURRENCY Override provider concurrency (use underscores: BAOYU_IMAGE_GEN_CODEX_CLI_CONCURRENCY)
|
| 159 |
+
BAOYU_IMAGE_GEN_<PROVIDER>_START_INTERVAL_MS Override provider start gap in ms
|
| 160 |
+
BAOYU_CODEX_IMAGEGEN_BIN Path to codex-imagegen wrapper (default: bundled scripts/codex-imagegen/main.ts; accepts .ts or legacy .sh/binary)
|
| 161 |
+
BAOYU_CODEX_IMAGEGEN_CACHE_DIR Enable idempotency cache for codex-cli provider (default: disabled)
|
| 162 |
+
BAOYU_CODEX_IMAGEGEN_TIMEOUT_MS Per-attempt codex exec timeout for codex-cli provider (default: 300000)
|
| 163 |
+
BAOYU_CODEX_IMAGEGEN_RETRIES Codex-side retry attempts on retryable errors (default: 2)
|
| 164 |
+
BAOYU_CODEX_IMAGEGEN_LOG_FILE Append JSONL diagnostic log for codex-cli provider
|
| 165 |
+
|
| 166 |
+
Env file load order: CLI args > EXTEND.md > process.env > <cwd>/.baoyu-skills/.env > ~/.baoyu-skills/.env`);
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
export function parseArgs(argv: string[]): CliArgs {
|
| 170 |
+
const out: CliArgs = {
|
| 171 |
+
prompt: null,
|
| 172 |
+
promptFiles: [],
|
| 173 |
+
imagePath: null,
|
| 174 |
+
provider: null,
|
| 175 |
+
model: null,
|
| 176 |
+
aspectRatio: null,
|
| 177 |
+
aspectRatioSource: null,
|
| 178 |
+
size: null,
|
| 179 |
+
quality: null,
|
| 180 |
+
imageSize: null,
|
| 181 |
+
imageSizeSource: null,
|
| 182 |
+
imageApiDialect: null,
|
| 183 |
+
referenceImages: [],
|
| 184 |
+
n: 1,
|
| 185 |
+
batchFile: null,
|
| 186 |
+
jobs: null,
|
| 187 |
+
json: false,
|
| 188 |
+
help: false,
|
| 189 |
+
};
|
| 190 |
+
|
| 191 |
+
const positional: string[] = [];
|
| 192 |
+
|
| 193 |
+
const takeMany = (i: number): { items: string[]; next: number } => {
|
| 194 |
+
const items: string[] = [];
|
| 195 |
+
let j = i + 1;
|
| 196 |
+
while (j < argv.length) {
|
| 197 |
+
const v = argv[j]!;
|
| 198 |
+
if (v.startsWith("-")) break;
|
| 199 |
+
items.push(v);
|
| 200 |
+
j++;
|
| 201 |
+
}
|
| 202 |
+
return { items, next: j - 1 };
|
| 203 |
+
};
|
| 204 |
+
|
| 205 |
+
for (let i = 0; i < argv.length; i++) {
|
| 206 |
+
const a = argv[i]!;
|
| 207 |
+
|
| 208 |
+
if (a === "--help" || a === "-h") {
|
| 209 |
+
out.help = true;
|
| 210 |
+
continue;
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
if (a === "--json") {
|
| 214 |
+
out.json = true;
|
| 215 |
+
continue;
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
if (a === "--prompt" || a === "-p") {
|
| 219 |
+
const v = argv[++i];
|
| 220 |
+
if (!v) throw new Error(`Missing value for ${a}`);
|
| 221 |
+
out.prompt = v;
|
| 222 |
+
continue;
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
if (a === "--promptfiles") {
|
| 226 |
+
const { items, next } = takeMany(i);
|
| 227 |
+
if (items.length === 0) throw new Error("Missing files for --promptfiles");
|
| 228 |
+
out.promptFiles.push(...items);
|
| 229 |
+
i = next;
|
| 230 |
+
continue;
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
if (a === "--image") {
|
| 234 |
+
const v = argv[++i];
|
| 235 |
+
if (!v) throw new Error("Missing value for --image");
|
| 236 |
+
out.imagePath = v;
|
| 237 |
+
continue;
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
if (a === "--batchfile") {
|
| 241 |
+
const v = argv[++i];
|
| 242 |
+
if (!v) throw new Error("Missing value for --batchfile");
|
| 243 |
+
out.batchFile = v;
|
| 244 |
+
continue;
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
if (a === "--jobs") {
|
| 248 |
+
const v = argv[++i];
|
| 249 |
+
if (!v) throw new Error("Missing value for --jobs");
|
| 250 |
+
out.jobs = parseInt(v, 10);
|
| 251 |
+
if (isNaN(out.jobs) || out.jobs < 1) throw new Error(`Invalid worker count: ${v}`);
|
| 252 |
+
continue;
|
| 253 |
+
}
|
| 254 |
+
|
| 255 |
+
if (a === "--provider") {
|
| 256 |
+
const v = argv[++i];
|
| 257 |
+
if (
|
| 258 |
+
v !== "google" &&
|
| 259 |
+
v !== "openai" &&
|
| 260 |
+
v !== "openrouter" &&
|
| 261 |
+
v !== "dashscope" &&
|
| 262 |
+
v !== "zai" &&
|
| 263 |
+
v !== "minimax" &&
|
| 264 |
+
v !== "replicate" &&
|
| 265 |
+
v !== "jimeng" &&
|
| 266 |
+
v !== "seedream" &&
|
| 267 |
+
v !== "azure" &&
|
| 268 |
+
v !== "codex-cli"
|
| 269 |
+
) {
|
| 270 |
+
throw new Error(`Invalid provider: ${v}`);
|
| 271 |
+
}
|
| 272 |
+
out.provider = v;
|
| 273 |
+
continue;
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
if (a === "--model" || a === "-m") {
|
| 277 |
+
const v = argv[++i];
|
| 278 |
+
if (!v) throw new Error(`Missing value for ${a}`);
|
| 279 |
+
out.model = v;
|
| 280 |
+
continue;
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
if (a === "--ar") {
|
| 284 |
+
const v = argv[++i];
|
| 285 |
+
if (!v) throw new Error("Missing value for --ar");
|
| 286 |
+
out.aspectRatio = v;
|
| 287 |
+
out.aspectRatioSource = "cli";
|
| 288 |
+
continue;
|
| 289 |
+
}
|
| 290 |
+
|
| 291 |
+
if (a === "--size") {
|
| 292 |
+
const v = argv[++i];
|
| 293 |
+
if (!v) throw new Error("Missing value for --size");
|
| 294 |
+
out.size = v;
|
| 295 |
+
continue;
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
if (a === "--quality") {
|
| 299 |
+
const v = argv[++i];
|
| 300 |
+
if (v !== "normal" && v !== "2k") throw new Error(`Invalid quality: ${v}`);
|
| 301 |
+
out.quality = v;
|
| 302 |
+
continue;
|
| 303 |
+
}
|
| 304 |
+
|
| 305 |
+
if (a === "--imageSize") {
|
| 306 |
+
const v = argv[++i]?.toUpperCase();
|
| 307 |
+
if (v !== "1K" && v !== "2K" && v !== "4K") throw new Error(`Invalid imageSize: ${v}`);
|
| 308 |
+
out.imageSize = v;
|
| 309 |
+
out.imageSizeSource = "cli";
|
| 310 |
+
continue;
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
if (a === "--imageApiDialect") {
|
| 314 |
+
const v = argv[++i];
|
| 315 |
+
if (v !== "openai-native" && v !== "ratio-metadata") {
|
| 316 |
+
throw new Error(`Invalid imageApiDialect: ${v}`);
|
| 317 |
+
}
|
| 318 |
+
out.imageApiDialect = v;
|
| 319 |
+
continue;
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
if (a === "--ref" || a === "--reference") {
|
| 323 |
+
const { items, next } = takeMany(i);
|
| 324 |
+
if (items.length === 0) throw new Error(`Missing files for ${a}`);
|
| 325 |
+
out.referenceImages.push(...items);
|
| 326 |
+
i = next;
|
| 327 |
+
continue;
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
if (a === "--n") {
|
| 331 |
+
const v = argv[++i];
|
| 332 |
+
if (!v) throw new Error("Missing value for --n");
|
| 333 |
+
out.n = parseInt(v, 10);
|
| 334 |
+
if (isNaN(out.n) || out.n < 1) throw new Error(`Invalid count: ${v}`);
|
| 335 |
+
continue;
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
if (a.startsWith("-")) {
|
| 339 |
+
throw new Error(`Unknown option: ${a}`);
|
| 340 |
+
}
|
| 341 |
+
|
| 342 |
+
positional.push(a);
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
if (!out.prompt && out.promptFiles.length === 0 && positional.length > 0) {
|
| 346 |
+
out.prompt = positional.join(" ");
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
return out;
|
| 350 |
+
}
|
| 351 |
+
|
| 352 |
+
async function loadEnvFile(p: string): Promise<Record<string, string>> {
|
| 353 |
+
try {
|
| 354 |
+
const content = await readFile(p, "utf8");
|
| 355 |
+
const env: Record<string, string> = {};
|
| 356 |
+
for (const line of content.split("\n")) {
|
| 357 |
+
const trimmed = line.trim();
|
| 358 |
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
| 359 |
+
const idx = trimmed.indexOf("=");
|
| 360 |
+
if (idx === -1) continue;
|
| 361 |
+
const key = trimmed.slice(0, idx).trim();
|
| 362 |
+
let val = trimmed.slice(idx + 1).trim();
|
| 363 |
+
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
|
| 364 |
+
val = val.slice(1, -1);
|
| 365 |
+
}
|
| 366 |
+
env[key] = val;
|
| 367 |
+
}
|
| 368 |
+
return env;
|
| 369 |
+
} catch {
|
| 370 |
+
return {};
|
| 371 |
+
}
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
async function loadEnv(): Promise<void> {
|
| 375 |
+
const home = homedir();
|
| 376 |
+
const cwd = process.cwd();
|
| 377 |
+
|
| 378 |
+
const homeEnv = await loadEnvFile(path.join(home, ".baoyu-skills", ".env"));
|
| 379 |
+
const cwdEnv = await loadEnvFile(path.join(cwd, ".baoyu-skills", ".env"));
|
| 380 |
+
|
| 381 |
+
for (const [k, v] of Object.entries(homeEnv)) {
|
| 382 |
+
if (!process.env[k]) process.env[k] = v;
|
| 383 |
+
}
|
| 384 |
+
for (const [k, v] of Object.entries(cwdEnv)) {
|
| 385 |
+
if (!process.env[k]) process.env[k] = v;
|
| 386 |
+
}
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
export function extractYamlFrontMatter(content: string): string | null {
|
| 390 |
+
const match = content.match(/^---\s*\n([\s\S]*?)\n---\s*$/m);
|
| 391 |
+
return match ? match[1] : null;
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
export function parseSimpleYaml(yaml: string): Partial<ExtendConfig> {
|
| 395 |
+
const config: Partial<ExtendConfig> = {};
|
| 396 |
+
const lines = yaml.split("\n");
|
| 397 |
+
let currentKey: string | null = null;
|
| 398 |
+
let currentProvider: Provider | null = null;
|
| 399 |
+
|
| 400 |
+
for (const line of lines) {
|
| 401 |
+
const trimmed = line.trim();
|
| 402 |
+
const indent = line.match(/^\s*/)?.[0].length ?? 0;
|
| 403 |
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
| 404 |
+
|
| 405 |
+
if (trimmed.includes(":") && !trimmed.startsWith("-")) {
|
| 406 |
+
const colonIdx = trimmed.indexOf(":");
|
| 407 |
+
const key = trimmed.slice(0, colonIdx).trim();
|
| 408 |
+
let value = trimmed.slice(colonIdx + 1).trim();
|
| 409 |
+
|
| 410 |
+
if (value === "null" || value === "") {
|
| 411 |
+
value = "null";
|
| 412 |
+
}
|
| 413 |
+
|
| 414 |
+
if (key === "version") {
|
| 415 |
+
config.version = value === "null" ? 1 : parseInt(value, 10);
|
| 416 |
+
} else if (key === "default_provider") {
|
| 417 |
+
config.default_provider = value === "null" ? null : (value as Provider);
|
| 418 |
+
} else if (key === "default_quality") {
|
| 419 |
+
config.default_quality = value === "null" ? null : value as "normal" | "2k";
|
| 420 |
+
} else if (key === "default_aspect_ratio") {
|
| 421 |
+
const cleaned = value.replace(/['"]/g, "");
|
| 422 |
+
config.default_aspect_ratio = cleaned === "null" ? null : cleaned;
|
| 423 |
+
} else if (key === "default_image_size") {
|
| 424 |
+
config.default_image_size = value === "null" ? null : value as "1K" | "2K" | "4K";
|
| 425 |
+
} else if (key === "default_image_api_dialect") {
|
| 426 |
+
config.default_image_api_dialect =
|
| 427 |
+
value === "null" ? null : parseOpenAIImageApiDialect(value);
|
| 428 |
+
} else if (key === "default_model") {
|
| 429 |
+
config.default_model = {
|
| 430 |
+
google: null,
|
| 431 |
+
openai: null,
|
| 432 |
+
openrouter: null,
|
| 433 |
+
dashscope: null,
|
| 434 |
+
zai: null,
|
| 435 |
+
minimax: null,
|
| 436 |
+
replicate: null,
|
| 437 |
+
jimeng: null,
|
| 438 |
+
seedream: null,
|
| 439 |
+
azure: null,
|
| 440 |
+
"codex-cli": null,
|
| 441 |
+
};
|
| 442 |
+
currentKey = "default_model";
|
| 443 |
+
currentProvider = null;
|
| 444 |
+
} else if (key === "batch") {
|
| 445 |
+
config.batch = {};
|
| 446 |
+
currentKey = "batch";
|
| 447 |
+
currentProvider = null;
|
| 448 |
+
} else if (currentKey === "batch" && indent >= 2 && key === "max_workers") {
|
| 449 |
+
config.batch ??= {};
|
| 450 |
+
config.batch.max_workers = value === "null" ? null : parseInt(value, 10);
|
| 451 |
+
} else if (currentKey === "batch" && indent >= 2 && key === "provider_limits") {
|
| 452 |
+
config.batch ??= {};
|
| 453 |
+
config.batch.provider_limits ??= {};
|
| 454 |
+
currentKey = "provider_limits";
|
| 455 |
+
currentProvider = null;
|
| 456 |
+
} else if (
|
| 457 |
+
currentKey === "provider_limits" &&
|
| 458 |
+
indent >= 4 &&
|
| 459 |
+
(
|
| 460 |
+
key === "google" ||
|
| 461 |
+
key === "openai" ||
|
| 462 |
+
key === "openrouter" ||
|
| 463 |
+
key === "dashscope" ||
|
| 464 |
+
key === "zai" ||
|
| 465 |
+
key === "minimax" ||
|
| 466 |
+
key === "replicate" ||
|
| 467 |
+
key === "jimeng" ||
|
| 468 |
+
key === "seedream" ||
|
| 469 |
+
key === "azure" ||
|
| 470 |
+
key === "codex-cli"
|
| 471 |
+
)
|
| 472 |
+
) {
|
| 473 |
+
config.batch ??= {};
|
| 474 |
+
config.batch.provider_limits ??= {};
|
| 475 |
+
config.batch.provider_limits[key] ??= {};
|
| 476 |
+
currentProvider = key;
|
| 477 |
+
} else if (
|
| 478 |
+
currentKey === "default_model" &&
|
| 479 |
+
(
|
| 480 |
+
key === "google" ||
|
| 481 |
+
key === "openai" ||
|
| 482 |
+
key === "openrouter" ||
|
| 483 |
+
key === "dashscope" ||
|
| 484 |
+
key === "zai" ||
|
| 485 |
+
key === "minimax" ||
|
| 486 |
+
key === "replicate" ||
|
| 487 |
+
key === "jimeng" ||
|
| 488 |
+
key === "seedream" ||
|
| 489 |
+
key === "azure" ||
|
| 490 |
+
key === "codex-cli"
|
| 491 |
+
)
|
| 492 |
+
) {
|
| 493 |
+
const cleaned = value.replace(/['"]/g, "");
|
| 494 |
+
config.default_model![key] = cleaned === "null" ? null : cleaned;
|
| 495 |
+
} else if (
|
| 496 |
+
currentKey === "provider_limits" &&
|
| 497 |
+
currentProvider &&
|
| 498 |
+
indent >= 6 &&
|
| 499 |
+
(key === "concurrency" || key === "start_interval_ms")
|
| 500 |
+
) {
|
| 501 |
+
config.batch ??= {};
|
| 502 |
+
config.batch.provider_limits ??= {};
|
| 503 |
+
const providerLimit = (config.batch.provider_limits[currentProvider] ??= {});
|
| 504 |
+
if (key === "concurrency") {
|
| 505 |
+
providerLimit.concurrency = value === "null" ? null : parseInt(value, 10);
|
| 506 |
+
} else {
|
| 507 |
+
providerLimit.start_interval_ms = value === "null" ? null : parseInt(value, 10);
|
| 508 |
+
}
|
| 509 |
+
}
|
| 510 |
+
}
|
| 511 |
+
}
|
| 512 |
+
|
| 513 |
+
return config;
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
export function parseOpenAIImageApiDialect(
|
| 517 |
+
value: string | undefined | null
|
| 518 |
+
): OpenAIImageApiDialect | null {
|
| 519 |
+
if (!value) return null;
|
| 520 |
+
const normalized = value.replace(/['"]/g, "").trim();
|
| 521 |
+
if (normalized === "openai-native" || normalized === "ratio-metadata") return normalized;
|
| 522 |
+
throw new Error(`Invalid OpenAI image API dialect: ${value}`);
|
| 523 |
+
}
|
| 524 |
+
|
| 525 |
+
type ExtendConfigPathPair = {
|
| 526 |
+
current: string;
|
| 527 |
+
legacy: string;
|
| 528 |
+
};
|
| 529 |
+
|
| 530 |
+
function getExtendConfigPathPairs(cwd: string, home: string): ExtendConfigPathPair[] {
|
| 531 |
+
return [
|
| 532 |
+
{
|
| 533 |
+
current: path.join(cwd, ".baoyu-skills", "baoyu-image-gen", "EXTEND.md"),
|
| 534 |
+
legacy: path.join(cwd, ".baoyu-skills", "baoyu-imagine", "EXTEND.md"),
|
| 535 |
+
},
|
| 536 |
+
{
|
| 537 |
+
current: path.join(home, ".baoyu-skills", "baoyu-image-gen", "EXTEND.md"),
|
| 538 |
+
legacy: path.join(home, ".baoyu-skills", "baoyu-imagine", "EXTEND.md"),
|
| 539 |
+
},
|
| 540 |
+
];
|
| 541 |
+
}
|
| 542 |
+
|
| 543 |
+
async function exists(filePath: string): Promise<boolean> {
|
| 544 |
+
try {
|
| 545 |
+
await access(filePath);
|
| 546 |
+
return true;
|
| 547 |
+
} catch {
|
| 548 |
+
return false;
|
| 549 |
+
}
|
| 550 |
+
}
|
| 551 |
+
|
| 552 |
+
async function migrateLegacyExtendConfig(cwd: string, home: string): Promise<void> {
|
| 553 |
+
for (const { current, legacy } of getExtendConfigPathPairs(cwd, home)) {
|
| 554 |
+
const [hasCurrent, hasLegacy] = await Promise.all([exists(current), exists(legacy)]);
|
| 555 |
+
if (hasCurrent || !hasLegacy) continue;
|
| 556 |
+
await mkdir(path.dirname(current), { recursive: true });
|
| 557 |
+
await rename(legacy, current);
|
| 558 |
+
}
|
| 559 |
+
}
|
| 560 |
+
|
| 561 |
+
export async function loadExtendConfig(
|
| 562 |
+
cwd = process.cwd(),
|
| 563 |
+
home = homedir(),
|
| 564 |
+
): Promise<Partial<ExtendConfig>> {
|
| 565 |
+
await migrateLegacyExtendConfig(cwd, home);
|
| 566 |
+
|
| 567 |
+
const paths = getExtendConfigPathPairs(cwd, home).map(({ current }) => current);
|
| 568 |
+
|
| 569 |
+
for (const p of paths) {
|
| 570 |
+
try {
|
| 571 |
+
const content = await readFile(p, "utf8");
|
| 572 |
+
const yaml = extractYamlFrontMatter(content);
|
| 573 |
+
if (!yaml) continue;
|
| 574 |
+
return parseSimpleYaml(yaml);
|
| 575 |
+
} catch {
|
| 576 |
+
continue;
|
| 577 |
+
}
|
| 578 |
+
}
|
| 579 |
+
|
| 580 |
+
return {};
|
| 581 |
+
}
|
| 582 |
+
|
| 583 |
+
export function mergeConfig(args: CliArgs, extend: Partial<ExtendConfig>): CliArgs {
|
| 584 |
+
const aspectRatio = args.aspectRatio ?? extend.default_aspect_ratio ?? null;
|
| 585 |
+
const imageSize = args.imageSize ?? extend.default_image_size ?? null;
|
| 586 |
+
const imageApiDialect =
|
| 587 |
+
args.imageApiDialect ??
|
| 588 |
+
extend.default_image_api_dialect ??
|
| 589 |
+
parseOpenAIImageApiDialect(process.env.OPENAI_IMAGE_API_DIALECT);
|
| 590 |
+
return {
|
| 591 |
+
...args,
|
| 592 |
+
provider: args.provider ?? extend.default_provider ?? null,
|
| 593 |
+
quality: args.quality ?? extend.default_quality ?? null,
|
| 594 |
+
aspectRatio,
|
| 595 |
+
aspectRatioSource:
|
| 596 |
+
args.aspectRatioSource ??
|
| 597 |
+
(args.aspectRatio !== null ? "cli" : (aspectRatio !== null ? "config" : null)),
|
| 598 |
+
imageSize,
|
| 599 |
+
imageSizeSource:
|
| 600 |
+
args.imageSizeSource ??
|
| 601 |
+
(args.imageSize !== null ? "cli" : (imageSize !== null ? "config" : null)),
|
| 602 |
+
imageApiDialect,
|
| 603 |
+
};
|
| 604 |
+
}
|
| 605 |
+
|
| 606 |
+
export function parsePositiveInt(value: string | undefined): number | null {
|
| 607 |
+
if (!value) return null;
|
| 608 |
+
const parsed = parseInt(value, 10);
|
| 609 |
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
| 610 |
+
}
|
| 611 |
+
|
| 612 |
+
export function parsePositiveBatchInt(value: unknown): number | null {
|
| 613 |
+
if (value === null || value === undefined) return null;
|
| 614 |
+
if (typeof value === "number") {
|
| 615 |
+
return Number.isInteger(value) && value > 0 ? value : null;
|
| 616 |
+
}
|
| 617 |
+
if (typeof value === "string") {
|
| 618 |
+
return parsePositiveInt(value);
|
| 619 |
+
}
|
| 620 |
+
return null;
|
| 621 |
+
}
|
| 622 |
+
|
| 623 |
+
export function getConfiguredMaxWorkers(extendConfig: Partial<ExtendConfig>): number {
|
| 624 |
+
const envValue = parsePositiveInt(process.env.BAOYU_IMAGE_GEN_MAX_WORKERS);
|
| 625 |
+
const configValue = extendConfig.batch?.max_workers ?? null;
|
| 626 |
+
return Math.max(1, envValue ?? configValue ?? DEFAULT_MAX_WORKERS);
|
| 627 |
+
}
|
| 628 |
+
|
| 629 |
+
export function getConfiguredProviderRateLimits(
|
| 630 |
+
extendConfig: Partial<ExtendConfig>
|
| 631 |
+
): Record<Provider, ProviderRateLimit> {
|
| 632 |
+
const configured: Record<Provider, ProviderRateLimit> = {
|
| 633 |
+
replicate: { ...DEFAULT_PROVIDER_RATE_LIMITS.replicate },
|
| 634 |
+
google: { ...DEFAULT_PROVIDER_RATE_LIMITS.google },
|
| 635 |
+
openai: { ...DEFAULT_PROVIDER_RATE_LIMITS.openai },
|
| 636 |
+
openrouter: { ...DEFAULT_PROVIDER_RATE_LIMITS.openrouter },
|
| 637 |
+
dashscope: { ...DEFAULT_PROVIDER_RATE_LIMITS.dashscope },
|
| 638 |
+
zai: { ...DEFAULT_PROVIDER_RATE_LIMITS.zai },
|
| 639 |
+
minimax: { ...DEFAULT_PROVIDER_RATE_LIMITS.minimax },
|
| 640 |
+
jimeng: { ...DEFAULT_PROVIDER_RATE_LIMITS.jimeng },
|
| 641 |
+
seedream: { ...DEFAULT_PROVIDER_RATE_LIMITS.seedream },
|
| 642 |
+
azure: { ...DEFAULT_PROVIDER_RATE_LIMITS.azure },
|
| 643 |
+
"codex-cli": { ...DEFAULT_PROVIDER_RATE_LIMITS["codex-cli"] },
|
| 644 |
+
};
|
| 645 |
+
|
| 646 |
+
for (const provider of ["replicate", "google", "openai", "openrouter", "dashscope", "zai", "minimax", "jimeng", "seedream", "azure", "codex-cli"] as Provider[]) {
|
| 647 |
+
const envPrefix = `BAOYU_IMAGE_GEN_${provider.toUpperCase().replace(/-/g, "_")}`;
|
| 648 |
+
const extendLimit = extendConfig.batch?.provider_limits?.[provider];
|
| 649 |
+
configured[provider] = {
|
| 650 |
+
concurrency:
|
| 651 |
+
parsePositiveInt(process.env[`${envPrefix}_CONCURRENCY`]) ??
|
| 652 |
+
extendLimit?.concurrency ??
|
| 653 |
+
configured[provider].concurrency,
|
| 654 |
+
startIntervalMs:
|
| 655 |
+
parsePositiveInt(process.env[`${envPrefix}_START_INTERVAL_MS`]) ??
|
| 656 |
+
extendLimit?.start_interval_ms ??
|
| 657 |
+
configured[provider].startIntervalMs,
|
| 658 |
+
};
|
| 659 |
+
}
|
| 660 |
+
|
| 661 |
+
return configured;
|
| 662 |
+
}
|
| 663 |
+
|
| 664 |
+
async function readPromptFromFiles(files: string[]): Promise<string> {
|
| 665 |
+
const parts: string[] = [];
|
| 666 |
+
for (const f of files) {
|
| 667 |
+
parts.push(await readFile(f, "utf8"));
|
| 668 |
+
}
|
| 669 |
+
return parts.join("\n\n");
|
| 670 |
+
}
|
| 671 |
+
|
| 672 |
+
async function readPromptFromStdin(): Promise<string | null> {
|
| 673 |
+
if (process.stdin.isTTY) return null;
|
| 674 |
+
try {
|
| 675 |
+
const chunks: Buffer[] = [];
|
| 676 |
+
for await (const chunk of process.stdin) {
|
| 677 |
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
| 678 |
+
}
|
| 679 |
+
const value = Buffer.concat(chunks).toString("utf8").trim();
|
| 680 |
+
return value.length > 0 ? value : null;
|
| 681 |
+
} catch {
|
| 682 |
+
return null;
|
| 683 |
+
}
|
| 684 |
+
}
|
| 685 |
+
|
| 686 |
+
export function normalizeOutputImagePath(p: string, defaultExtension = ".png"): string {
|
| 687 |
+
const full = path.resolve(p);
|
| 688 |
+
const ext = path.extname(full);
|
| 689 |
+
if (ext) return full;
|
| 690 |
+
return `${full}${defaultExtension}`;
|
| 691 |
+
}
|
| 692 |
+
|
| 693 |
+
function inferProviderFromModel(model: string | null): Provider | null {
|
| 694 |
+
if (!model) return null;
|
| 695 |
+
const normalized = model.trim();
|
| 696 |
+
if (normalized.includes("seedream") || normalized.includes("seededit")) return "seedream";
|
| 697 |
+
if (normalized === "image-01" || normalized === "image-01-live") return "minimax";
|
| 698 |
+
if (normalized === "glm-image" || normalized === "cogview-4-250304") return "zai";
|
| 699 |
+
return null;
|
| 700 |
+
}
|
| 701 |
+
|
| 702 |
+
export function detectProvider(args: CliArgs): Provider {
|
| 703 |
+
if (
|
| 704 |
+
args.referenceImages.length > 0 &&
|
| 705 |
+
args.provider &&
|
| 706 |
+
args.provider !== "google" &&
|
| 707 |
+
args.provider !== "openai" &&
|
| 708 |
+
args.provider !== "azure" &&
|
| 709 |
+
args.provider !== "openrouter" &&
|
| 710 |
+
args.provider !== "replicate" &&
|
| 711 |
+
args.provider !== "seedream" &&
|
| 712 |
+
args.provider !== "minimax" &&
|
| 713 |
+
args.provider !== "dashscope" &&
|
| 714 |
+
args.provider !== "codex-cli"
|
| 715 |
+
) {
|
| 716 |
+
throw new Error(
|
| 717 |
+
"Reference images require a ref-capable provider. Use --provider google (Gemini multimodal), --provider openai (GPT Image edits), --provider azure (Azure OpenAI), --provider openrouter (OpenRouter multimodal), --provider replicate, --provider dashscope with a wan2.7 image model, --provider seedream for supported Seedream models, --provider minimax for MiniMax subject-reference workflows, or --provider codex-cli (Codex image_gen with references)."
|
| 718 |
+
);
|
| 719 |
+
}
|
| 720 |
+
|
| 721 |
+
if (args.provider) return args.provider;
|
| 722 |
+
|
| 723 |
+
const hasGoogle = !!(process.env.GOOGLE_API_KEY || process.env.GEMINI_API_KEY);
|
| 724 |
+
const hasAzure = !!(process.env.AZURE_OPENAI_API_KEY && process.env.AZURE_OPENAI_BASE_URL);
|
| 725 |
+
const hasOpenai = !!process.env.OPENAI_API_KEY;
|
| 726 |
+
const hasOpenrouter = !!process.env.OPENROUTER_API_KEY;
|
| 727 |
+
const hasDashscope = !!process.env.DASHSCOPE_API_KEY;
|
| 728 |
+
const hasZai = !!(process.env.ZAI_API_KEY || process.env.BIGMODEL_API_KEY);
|
| 729 |
+
const hasMinimax = !!process.env.MINIMAX_API_KEY;
|
| 730 |
+
const hasReplicate = !!process.env.REPLICATE_API_TOKEN;
|
| 731 |
+
const hasJimeng = !!(process.env.JIMENG_ACCESS_KEY_ID && process.env.JIMENG_SECRET_ACCESS_KEY);
|
| 732 |
+
const hasSeedream = !!process.env.ARK_API_KEY;
|
| 733 |
+
const modelProvider = inferProviderFromModel(args.model);
|
| 734 |
+
|
| 735 |
+
if (modelProvider === "seedream") {
|
| 736 |
+
if (!hasSeedream) {
|
| 737 |
+
throw new Error("Model looks like a Volcengine ARK image model, but ARK_API_KEY is not set.");
|
| 738 |
+
}
|
| 739 |
+
return "seedream";
|
| 740 |
+
}
|
| 741 |
+
|
| 742 |
+
if (modelProvider === "minimax") {
|
| 743 |
+
if (!hasMinimax) {
|
| 744 |
+
throw new Error("Model looks like a MiniMax image model, but MINIMAX_API_KEY is not set.");
|
| 745 |
+
}
|
| 746 |
+
return "minimax";
|
| 747 |
+
}
|
| 748 |
+
|
| 749 |
+
if (modelProvider === "zai") {
|
| 750 |
+
if (!hasZai) {
|
| 751 |
+
throw new Error("Model looks like a Z.AI image model, but ZAI_API_KEY is not set.");
|
| 752 |
+
}
|
| 753 |
+
return "zai";
|
| 754 |
+
}
|
| 755 |
+
|
| 756 |
+
if (args.referenceImages.length > 0) {
|
| 757 |
+
if (hasGoogle) return "google";
|
| 758 |
+
if (hasOpenai) return "openai";
|
| 759 |
+
if (hasAzure) return "azure";
|
| 760 |
+
if (hasOpenrouter) return "openrouter";
|
| 761 |
+
if (hasReplicate) return "replicate";
|
| 762 |
+
if (hasSeedream) return "seedream";
|
| 763 |
+
if (hasMinimax) return "minimax";
|
| 764 |
+
throw new Error(
|
| 765 |
+
"Reference images require Google, OpenAI, Azure, OpenRouter, Replicate, supported Seedream models, or MiniMax. Set GOOGLE_API_KEY/GEMINI_API_KEY, OPENAI_API_KEY, AZURE_OPENAI_API_KEY+AZURE_OPENAI_BASE_URL, OPENROUTER_API_KEY, REPLICATE_API_TOKEN, ARK_API_KEY, or MINIMAX_API_KEY, or remove --ref."
|
| 766 |
+
);
|
| 767 |
+
}
|
| 768 |
+
|
| 769 |
+
const available = [
|
| 770 |
+
hasGoogle && "google",
|
| 771 |
+
hasOpenai && "openai",
|
| 772 |
+
hasAzure && "azure",
|
| 773 |
+
hasOpenrouter && "openrouter",
|
| 774 |
+
hasDashscope && "dashscope",
|
| 775 |
+
hasZai && "zai",
|
| 776 |
+
hasMinimax && "minimax",
|
| 777 |
+
hasReplicate && "replicate",
|
| 778 |
+
hasJimeng && "jimeng",
|
| 779 |
+
hasSeedream && "seedream",
|
| 780 |
+
].filter(Boolean) as Provider[];
|
| 781 |
+
|
| 782 |
+
if (available.length === 1) return available[0]!;
|
| 783 |
+
if (available.length > 1) return available[0]!;
|
| 784 |
+
|
| 785 |
+
throw new Error(
|
| 786 |
+
"No API key found. Set GOOGLE_API_KEY, GEMINI_API_KEY, OPENAI_API_KEY, AZURE_OPENAI_API_KEY+AZURE_OPENAI_BASE_URL, OPENROUTER_API_KEY, DASHSCOPE_API_KEY, ZAI_API_KEY, MINIMAX_API_KEY, REPLICATE_API_TOKEN, JIMENG keys, or ARK_API_KEY.\n" +
|
| 787 |
+
"Create ~/.baoyu-skills/.env or <cwd>/.baoyu-skills/.env with your keys."
|
| 788 |
+
);
|
| 789 |
+
}
|
| 790 |
+
|
| 791 |
+
export type ReferenceImageValidationOptions = {
|
| 792 |
+
allowRemoteUrls?: boolean;
|
| 793 |
+
};
|
| 794 |
+
|
| 795 |
+
function isRemoteReferenceImage(refPath: string): boolean {
|
| 796 |
+
return /^https?:\/\//i.test(refPath);
|
| 797 |
+
}
|
| 798 |
+
|
| 799 |
+
function shouldAllowRemoteReferenceImages(provider: Provider | null): boolean {
|
| 800 |
+
return provider === "dashscope";
|
| 801 |
+
}
|
| 802 |
+
|
| 803 |
+
export async function validateReferenceImages(
|
| 804 |
+
referenceImages: string[],
|
| 805 |
+
options: ReferenceImageValidationOptions = {},
|
| 806 |
+
): Promise<void> {
|
| 807 |
+
for (const refPath of referenceImages) {
|
| 808 |
+
if (options.allowRemoteUrls && isRemoteReferenceImage(refPath)) continue;
|
| 809 |
+
const fullPath = path.resolve(refPath);
|
| 810 |
+
try {
|
| 811 |
+
await access(fullPath);
|
| 812 |
+
} catch {
|
| 813 |
+
throw new Error(`Reference image not found: ${fullPath}`);
|
| 814 |
+
}
|
| 815 |
+
}
|
| 816 |
+
}
|
| 817 |
+
|
| 818 |
+
export function isRetryableGenerationError(error: unknown): boolean {
|
| 819 |
+
const msg = error instanceof Error ? error.message : String(error);
|
| 820 |
+
const nonRetryableMarkers = [
|
| 821 |
+
"Reference image",
|
| 822 |
+
"not supported",
|
| 823 |
+
"only supported",
|
| 824 |
+
"No API key found",
|
| 825 |
+
"is required",
|
| 826 |
+
"Invalid ",
|
| 827 |
+
"Unexpected ",
|
| 828 |
+
"API error (400)",
|
| 829 |
+
"API error (401)",
|
| 830 |
+
"API error (402)",
|
| 831 |
+
"API error (403)",
|
| 832 |
+
"API error (404)",
|
| 833 |
+
"temporarily disabled",
|
| 834 |
+
"supports saving exactly one image",
|
| 835 |
+
"supports only",
|
| 836 |
+
"support exactly one output image",
|
| 837 |
+
"support aspect ratios in",
|
| 838 |
+
"requires total pixels between",
|
| 839 |
+
"accept at most",
|
| 840 |
+
];
|
| 841 |
+
return !nonRetryableMarkers.some((marker) => msg.includes(marker));
|
| 842 |
+
}
|
| 843 |
+
|
| 844 |
+
async function loadProviderModule(provider: Provider): Promise<ProviderModule> {
|
| 845 |
+
if (provider === "google") return (await import("./providers/google")) as ProviderModule;
|
| 846 |
+
if (provider === "dashscope") return (await import("./providers/dashscope")) as ProviderModule;
|
| 847 |
+
if (provider === "zai") return (await import("./providers/zai")) as ProviderModule;
|
| 848 |
+
if (provider === "minimax") return (await import("./providers/minimax")) as ProviderModule;
|
| 849 |
+
if (provider === "replicate") return (await import("./providers/replicate")) as ProviderModule;
|
| 850 |
+
if (provider === "openrouter") return (await import("./providers/openrouter")) as ProviderModule;
|
| 851 |
+
if (provider === "jimeng") return (await import("./providers/jimeng")) as ProviderModule;
|
| 852 |
+
if (provider === "seedream") return (await import("./providers/seedream")) as ProviderModule;
|
| 853 |
+
if (provider === "azure") return (await import("./providers/azure")) as ProviderModule;
|
| 854 |
+
if (provider === "codex-cli") return (await import("./providers/codex-cli")) as ProviderModule;
|
| 855 |
+
return (await import("./providers/openai")) as ProviderModule;
|
| 856 |
+
}
|
| 857 |
+
|
| 858 |
+
async function loadPromptForArgs(args: CliArgs): Promise<string | null> {
|
| 859 |
+
let prompt: string | null = args.prompt;
|
| 860 |
+
if (!prompt && args.promptFiles.length > 0) {
|
| 861 |
+
prompt = await readPromptFromFiles(args.promptFiles);
|
| 862 |
+
}
|
| 863 |
+
return prompt;
|
| 864 |
+
}
|
| 865 |
+
|
| 866 |
+
function getModelForProvider(
|
| 867 |
+
provider: Provider,
|
| 868 |
+
requestedModel: string | null,
|
| 869 |
+
extendConfig: Partial<ExtendConfig>,
|
| 870 |
+
providerModule: ProviderModule
|
| 871 |
+
): string {
|
| 872 |
+
if (requestedModel) return requestedModel;
|
| 873 |
+
if (extendConfig.default_model) {
|
| 874 |
+
if (provider === "google" && extendConfig.default_model.google) return extendConfig.default_model.google;
|
| 875 |
+
if (provider === "openai" && extendConfig.default_model.openai) return extendConfig.default_model.openai;
|
| 876 |
+
if (provider === "openrouter" && extendConfig.default_model.openrouter) {
|
| 877 |
+
return extendConfig.default_model.openrouter;
|
| 878 |
+
}
|
| 879 |
+
if (provider === "dashscope" && extendConfig.default_model.dashscope) return extendConfig.default_model.dashscope;
|
| 880 |
+
if (provider === "zai" && extendConfig.default_model.zai) return extendConfig.default_model.zai;
|
| 881 |
+
if (provider === "minimax" && extendConfig.default_model.minimax) return extendConfig.default_model.minimax;
|
| 882 |
+
if (provider === "replicate" && extendConfig.default_model.replicate) return extendConfig.default_model.replicate;
|
| 883 |
+
if (provider === "jimeng" && extendConfig.default_model.jimeng) return extendConfig.default_model.jimeng;
|
| 884 |
+
if (provider === "seedream" && extendConfig.default_model.seedream) return extendConfig.default_model.seedream;
|
| 885 |
+
if (provider === "azure" && extendConfig.default_model.azure) return extendConfig.default_model.azure;
|
| 886 |
+
if (provider === "codex-cli" && extendConfig.default_model["codex-cli"]) return extendConfig.default_model["codex-cli"];
|
| 887 |
+
}
|
| 888 |
+
return providerModule.getDefaultModel();
|
| 889 |
+
}
|
| 890 |
+
|
| 891 |
+
async function prepareSingleTask(args: CliArgs, extendConfig: Partial<ExtendConfig>): Promise<PreparedTask> {
|
| 892 |
+
if (!args.quality) args.quality = "2k";
|
| 893 |
+
|
| 894 |
+
const prompt = (await loadPromptForArgs(args)) ?? (await readPromptFromStdin());
|
| 895 |
+
if (!prompt) throw new Error("Prompt is required");
|
| 896 |
+
if (!args.imagePath) throw new Error("--image is required");
|
| 897 |
+
if (args.referenceImages.length > 0) {
|
| 898 |
+
await validateReferenceImages(args.referenceImages, {
|
| 899 |
+
allowRemoteUrls: shouldAllowRemoteReferenceImages(args.provider),
|
| 900 |
+
});
|
| 901 |
+
}
|
| 902 |
+
|
| 903 |
+
const provider = detectProvider(args);
|
| 904 |
+
const providerModule = await loadProviderModule(provider);
|
| 905 |
+
const model = getModelForProvider(provider, args.model, extendConfig, providerModule);
|
| 906 |
+
providerModule.validateArgs?.(model, args);
|
| 907 |
+
const defaultOutputExtension = providerModule.getDefaultOutputExtension?.(model, args) ?? ".png";
|
| 908 |
+
|
| 909 |
+
return {
|
| 910 |
+
id: "single",
|
| 911 |
+
prompt,
|
| 912 |
+
args,
|
| 913 |
+
provider,
|
| 914 |
+
model,
|
| 915 |
+
outputPath: normalizeOutputImagePath(args.imagePath, defaultOutputExtension),
|
| 916 |
+
providerModule,
|
| 917 |
+
};
|
| 918 |
+
}
|
| 919 |
+
|
| 920 |
+
export async function loadBatchTasks(batchFilePath: string): Promise<LoadedBatchTasks> {
|
| 921 |
+
const resolvedBatchFilePath = path.resolve(batchFilePath);
|
| 922 |
+
const content = await readFile(resolvedBatchFilePath, "utf8");
|
| 923 |
+
const parsed = JSON.parse(content.replace(/^\uFEFF/, "")) as BatchFile;
|
| 924 |
+
const batchDir = path.dirname(resolvedBatchFilePath);
|
| 925 |
+
if (Array.isArray(parsed)) {
|
| 926 |
+
return {
|
| 927 |
+
tasks: parsed,
|
| 928 |
+
jobs: null,
|
| 929 |
+
batchDir,
|
| 930 |
+
};
|
| 931 |
+
}
|
| 932 |
+
if (parsed && typeof parsed === "object" && Array.isArray(parsed.tasks)) {
|
| 933 |
+
const jobs = parsePositiveBatchInt(parsed.jobs);
|
| 934 |
+
if (parsed.jobs !== undefined && parsed.jobs !== null && jobs === null) {
|
| 935 |
+
throw new Error("Invalid batch file. jobs must be a positive integer when provided.");
|
| 936 |
+
}
|
| 937 |
+
return {
|
| 938 |
+
tasks: parsed.tasks,
|
| 939 |
+
jobs,
|
| 940 |
+
batchDir,
|
| 941 |
+
};
|
| 942 |
+
}
|
| 943 |
+
throw new Error("Invalid batch file. Expected an array of tasks or an object with a tasks array.");
|
| 944 |
+
}
|
| 945 |
+
|
| 946 |
+
export function resolveBatchPath(batchDir: string, filePath: string): string {
|
| 947 |
+
return path.isAbsolute(filePath) ? filePath : path.resolve(batchDir, filePath);
|
| 948 |
+
}
|
| 949 |
+
|
| 950 |
+
function resolveBatchReferencePath(batchDir: string, filePath: string): string {
|
| 951 |
+
return isRemoteReferenceImage(filePath) ? filePath : resolveBatchPath(batchDir, filePath);
|
| 952 |
+
}
|
| 953 |
+
|
| 954 |
+
export function createTaskArgs(baseArgs: CliArgs, task: BatchTaskInput, batchDir: string): CliArgs {
|
| 955 |
+
return {
|
| 956 |
+
...baseArgs,
|
| 957 |
+
prompt: task.prompt ?? null,
|
| 958 |
+
promptFiles: task.promptFiles ? task.promptFiles.map((filePath) => resolveBatchPath(batchDir, filePath)) : [],
|
| 959 |
+
imagePath: task.image ? resolveBatchPath(batchDir, task.image) : null,
|
| 960 |
+
provider: task.provider ?? baseArgs.provider ?? null,
|
| 961 |
+
model: task.model ?? baseArgs.model ?? null,
|
| 962 |
+
aspectRatio: task.ar ?? baseArgs.aspectRatio ?? null,
|
| 963 |
+
aspectRatioSource: task.ar != null ? "task" : (baseArgs.aspectRatioSource ?? null),
|
| 964 |
+
size: task.size ?? baseArgs.size ?? null,
|
| 965 |
+
quality: task.quality ?? baseArgs.quality ?? null,
|
| 966 |
+
imageSize: task.imageSize ?? baseArgs.imageSize ?? null,
|
| 967 |
+
imageSizeSource: task.imageSize != null ? "task" : (baseArgs.imageSizeSource ?? null),
|
| 968 |
+
imageApiDialect: task.imageApiDialect ?? baseArgs.imageApiDialect ?? null,
|
| 969 |
+
referenceImages: task.ref ? task.ref.map((filePath) => resolveBatchReferencePath(batchDir, filePath)) : [],
|
| 970 |
+
n: task.n ?? baseArgs.n,
|
| 971 |
+
batchFile: null,
|
| 972 |
+
jobs: baseArgs.jobs,
|
| 973 |
+
json: baseArgs.json,
|
| 974 |
+
help: false,
|
| 975 |
+
};
|
| 976 |
+
}
|
| 977 |
+
|
| 978 |
+
async function prepareBatchTasks(
|
| 979 |
+
args: CliArgs,
|
| 980 |
+
extendConfig: Partial<ExtendConfig>
|
| 981 |
+
): Promise<{ tasks: PreparedTask[]; jobs: number | null }> {
|
| 982 |
+
if (!args.batchFile) throw new Error("--batchfile is required in batch mode");
|
| 983 |
+
const { tasks: taskInputs, jobs: batchJobs, batchDir } = await loadBatchTasks(args.batchFile);
|
| 984 |
+
if (taskInputs.length === 0) throw new Error("Batch file does not contain any tasks.");
|
| 985 |
+
|
| 986 |
+
const prepared: PreparedTask[] = [];
|
| 987 |
+
for (let i = 0; i < taskInputs.length; i++) {
|
| 988 |
+
const task = taskInputs[i]!;
|
| 989 |
+
const taskArgs = createTaskArgs(args, task, batchDir);
|
| 990 |
+
const prompt = await loadPromptForArgs(taskArgs);
|
| 991 |
+
if (!prompt) throw new Error(`Task ${i + 1} is missing prompt or promptFiles.`);
|
| 992 |
+
if (!taskArgs.imagePath) throw new Error(`Task ${i + 1} is missing image output path.`);
|
| 993 |
+
if (taskArgs.referenceImages.length > 0) {
|
| 994 |
+
await validateReferenceImages(taskArgs.referenceImages, {
|
| 995 |
+
allowRemoteUrls: shouldAllowRemoteReferenceImages(taskArgs.provider),
|
| 996 |
+
});
|
| 997 |
+
}
|
| 998 |
+
|
| 999 |
+
const provider = detectProvider(taskArgs);
|
| 1000 |
+
const providerModule = await loadProviderModule(provider);
|
| 1001 |
+
const model = getModelForProvider(provider, taskArgs.model, extendConfig, providerModule);
|
| 1002 |
+
providerModule.validateArgs?.(model, taskArgs);
|
| 1003 |
+
const defaultOutputExtension = providerModule.getDefaultOutputExtension?.(model, taskArgs) ?? ".png";
|
| 1004 |
+
prepared.push({
|
| 1005 |
+
id: task.id || `task-${String(i + 1).padStart(2, "0")}`,
|
| 1006 |
+
prompt,
|
| 1007 |
+
args: taskArgs,
|
| 1008 |
+
provider,
|
| 1009 |
+
model,
|
| 1010 |
+
outputPath: normalizeOutputImagePath(taskArgs.imagePath, defaultOutputExtension),
|
| 1011 |
+
providerModule,
|
| 1012 |
+
});
|
| 1013 |
+
}
|
| 1014 |
+
|
| 1015 |
+
return {
|
| 1016 |
+
tasks: prepared,
|
| 1017 |
+
jobs: args.jobs ?? batchJobs,
|
| 1018 |
+
};
|
| 1019 |
+
}
|
| 1020 |
+
|
| 1021 |
+
async function writeImage(outputPath: string, imageData: Uint8Array): Promise<void> {
|
| 1022 |
+
await mkdir(path.dirname(outputPath), { recursive: true });
|
| 1023 |
+
await writeFile(outputPath, imageData);
|
| 1024 |
+
}
|
| 1025 |
+
|
| 1026 |
+
async function generatePreparedTask(task: PreparedTask): Promise<TaskResult> {
|
| 1027 |
+
console.error(`Using ${task.provider} / ${task.model} for ${task.id}`);
|
| 1028 |
+
console.error(
|
| 1029 |
+
`Switch model: --model <id> | EXTEND.md default_model.${task.provider} | env ${task.provider.toUpperCase()}_IMAGE_MODEL`
|
| 1030 |
+
);
|
| 1031 |
+
|
| 1032 |
+
let attempts = 0;
|
| 1033 |
+
while (attempts < MAX_ATTEMPTS) {
|
| 1034 |
+
attempts += 1;
|
| 1035 |
+
try {
|
| 1036 |
+
const imageData = await task.providerModule.generateImage(task.prompt, task.model, task.args);
|
| 1037 |
+
await writeImage(task.outputPath, imageData);
|
| 1038 |
+
return {
|
| 1039 |
+
id: task.id,
|
| 1040 |
+
provider: task.provider,
|
| 1041 |
+
model: task.model,
|
| 1042 |
+
outputPath: task.outputPath,
|
| 1043 |
+
success: true,
|
| 1044 |
+
attempts,
|
| 1045 |
+
error: null,
|
| 1046 |
+
};
|
| 1047 |
+
} catch (error) {
|
| 1048 |
+
const message = error instanceof Error ? error.message : String(error);
|
| 1049 |
+
const canRetry = attempts < MAX_ATTEMPTS && isRetryableGenerationError(error);
|
| 1050 |
+
if (canRetry) {
|
| 1051 |
+
console.error(`[${task.id}] Attempt ${attempts}/${MAX_ATTEMPTS} failed, retrying...`);
|
| 1052 |
+
continue;
|
| 1053 |
+
}
|
| 1054 |
+
return {
|
| 1055 |
+
id: task.id,
|
| 1056 |
+
provider: task.provider,
|
| 1057 |
+
model: task.model,
|
| 1058 |
+
outputPath: task.outputPath,
|
| 1059 |
+
success: false,
|
| 1060 |
+
attempts,
|
| 1061 |
+
error: message,
|
| 1062 |
+
};
|
| 1063 |
+
}
|
| 1064 |
+
}
|
| 1065 |
+
|
| 1066 |
+
return {
|
| 1067 |
+
id: task.id,
|
| 1068 |
+
provider: task.provider,
|
| 1069 |
+
model: task.model,
|
| 1070 |
+
outputPath: task.outputPath,
|
| 1071 |
+
success: false,
|
| 1072 |
+
attempts: MAX_ATTEMPTS,
|
| 1073 |
+
error: "Unknown failure",
|
| 1074 |
+
};
|
| 1075 |
+
}
|
| 1076 |
+
|
| 1077 |
+
function createProviderGate(providerRateLimits: Record<Provider, ProviderRateLimit>) {
|
| 1078 |
+
const state = new Map<Provider, { active: number; lastStartedAt: number }>();
|
| 1079 |
+
|
| 1080 |
+
return async function acquire(provider: Provider): Promise<() => void> {
|
| 1081 |
+
const limit = providerRateLimits[provider];
|
| 1082 |
+
while (true) {
|
| 1083 |
+
const current = state.get(provider) ?? { active: 0, lastStartedAt: 0 };
|
| 1084 |
+
const now = Date.now();
|
| 1085 |
+
const enoughCapacity = current.active < limit.concurrency;
|
| 1086 |
+
const enoughGap = now - current.lastStartedAt >= limit.startIntervalMs;
|
| 1087 |
+
if (enoughCapacity && enoughGap) {
|
| 1088 |
+
state.set(provider, { active: current.active + 1, lastStartedAt: now });
|
| 1089 |
+
return () => {
|
| 1090 |
+
const latest = state.get(provider) ?? { active: 1, lastStartedAt: now };
|
| 1091 |
+
state.set(provider, {
|
| 1092 |
+
active: Math.max(0, latest.active - 1),
|
| 1093 |
+
lastStartedAt: latest.lastStartedAt,
|
| 1094 |
+
});
|
| 1095 |
+
};
|
| 1096 |
+
}
|
| 1097 |
+
await new Promise((resolve) => setTimeout(resolve, POLL_WAIT_MS));
|
| 1098 |
+
}
|
| 1099 |
+
};
|
| 1100 |
+
}
|
| 1101 |
+
|
| 1102 |
+
export function getWorkerCount(taskCount: number, jobs: number | null, maxWorkers: number): number {
|
| 1103 |
+
const requested = jobs ?? Math.min(taskCount, maxWorkers);
|
| 1104 |
+
return Math.max(1, Math.min(requested, taskCount, maxWorkers));
|
| 1105 |
+
}
|
| 1106 |
+
|
| 1107 |
+
async function runBatchTasks(
|
| 1108 |
+
tasks: PreparedTask[],
|
| 1109 |
+
jobs: number | null,
|
| 1110 |
+
extendConfig: Partial<ExtendConfig>
|
| 1111 |
+
): Promise<TaskResult[]> {
|
| 1112 |
+
if (tasks.length === 1) {
|
| 1113 |
+
return [await generatePreparedTask(tasks[0]!)];
|
| 1114 |
+
}
|
| 1115 |
+
|
| 1116 |
+
const maxWorkers = getConfiguredMaxWorkers(extendConfig);
|
| 1117 |
+
const providerRateLimits = getConfiguredProviderRateLimits(extendConfig);
|
| 1118 |
+
const acquireProvider = createProviderGate(providerRateLimits);
|
| 1119 |
+
const workerCount = getWorkerCount(tasks.length, jobs, maxWorkers);
|
| 1120 |
+
console.error(`Batch mode: ${tasks.length} tasks, ${workerCount} workers, parallel mode enabled.`);
|
| 1121 |
+
for (const provider of ["replicate", "google", "openai", "openrouter", "dashscope", "zai", "minimax", "jimeng", "seedream", "azure", "codex-cli"] as Provider[]) {
|
| 1122 |
+
const limit = providerRateLimits[provider];
|
| 1123 |
+
console.error(`- ${provider}: concurrency=${limit.concurrency}, startIntervalMs=${limit.startIntervalMs}`);
|
| 1124 |
+
}
|
| 1125 |
+
|
| 1126 |
+
let nextIndex = 0;
|
| 1127 |
+
const results: TaskResult[] = new Array(tasks.length);
|
| 1128 |
+
|
| 1129 |
+
const worker = async (): Promise<void> => {
|
| 1130 |
+
while (true) {
|
| 1131 |
+
const currentIndex = nextIndex;
|
| 1132 |
+
nextIndex += 1;
|
| 1133 |
+
if (currentIndex >= tasks.length) return;
|
| 1134 |
+
|
| 1135 |
+
const task = tasks[currentIndex]!;
|
| 1136 |
+
const release = await acquireProvider(task.provider);
|
| 1137 |
+
try {
|
| 1138 |
+
results[currentIndex] = await generatePreparedTask(task);
|
| 1139 |
+
} finally {
|
| 1140 |
+
release();
|
| 1141 |
+
}
|
| 1142 |
+
}
|
| 1143 |
+
};
|
| 1144 |
+
|
| 1145 |
+
await Promise.all(Array.from({ length: workerCount }, () => worker()));
|
| 1146 |
+
return results;
|
| 1147 |
+
}
|
| 1148 |
+
|
| 1149 |
+
function printBatchSummary(results: TaskResult[]): void {
|
| 1150 |
+
const successCount = results.filter((result) => result.success).length;
|
| 1151 |
+
const failureCount = results.length - successCount;
|
| 1152 |
+
|
| 1153 |
+
console.error("");
|
| 1154 |
+
console.error("Batch generation summary:");
|
| 1155 |
+
console.error(`- Total: ${results.length}`);
|
| 1156 |
+
console.error(`- Succeeded: ${successCount}`);
|
| 1157 |
+
console.error(`- Failed: ${failureCount}`);
|
| 1158 |
+
|
| 1159 |
+
if (failureCount > 0) {
|
| 1160 |
+
console.error("Failure reasons:");
|
| 1161 |
+
for (const result of results.filter((item) => !item.success)) {
|
| 1162 |
+
console.error(`- ${result.id}: ${result.error}`);
|
| 1163 |
+
}
|
| 1164 |
+
}
|
| 1165 |
+
}
|
| 1166 |
+
|
| 1167 |
+
function emitJson(payload: unknown): void {
|
| 1168 |
+
console.log(JSON.stringify(payload, null, 2));
|
| 1169 |
+
}
|
| 1170 |
+
|
| 1171 |
+
async function runSingleMode(args: CliArgs, extendConfig: Partial<ExtendConfig>): Promise<void> {
|
| 1172 |
+
const task = await prepareSingleTask(args, extendConfig);
|
| 1173 |
+
const result = await generatePreparedTask(task);
|
| 1174 |
+
if (!result.success) {
|
| 1175 |
+
throw new Error(result.error || "Generation failed");
|
| 1176 |
+
}
|
| 1177 |
+
|
| 1178 |
+
if (args.json) {
|
| 1179 |
+
emitJson({
|
| 1180 |
+
savedImage: result.outputPath,
|
| 1181 |
+
provider: result.provider,
|
| 1182 |
+
model: result.model,
|
| 1183 |
+
attempts: result.attempts,
|
| 1184 |
+
prompt: task.prompt.slice(0, 200),
|
| 1185 |
+
});
|
| 1186 |
+
return;
|
| 1187 |
+
}
|
| 1188 |
+
|
| 1189 |
+
console.log(result.outputPath);
|
| 1190 |
+
}
|
| 1191 |
+
|
| 1192 |
+
async function runBatchMode(args: CliArgs, extendConfig: Partial<ExtendConfig>): Promise<void> {
|
| 1193 |
+
const { tasks, jobs } = await prepareBatchTasks(args, extendConfig);
|
| 1194 |
+
const results = await runBatchTasks(tasks, jobs, extendConfig);
|
| 1195 |
+
printBatchSummary(results);
|
| 1196 |
+
|
| 1197 |
+
if (args.json) {
|
| 1198 |
+
emitJson({
|
| 1199 |
+
mode: "batch",
|
| 1200 |
+
total: results.length,
|
| 1201 |
+
succeeded: results.filter((item) => item.success).length,
|
| 1202 |
+
failed: results.filter((item) => !item.success).length,
|
| 1203 |
+
results,
|
| 1204 |
+
});
|
| 1205 |
+
}
|
| 1206 |
+
|
| 1207 |
+
if (results.some((item) => !item.success)) {
|
| 1208 |
+
process.exitCode = 1;
|
| 1209 |
+
}
|
| 1210 |
+
}
|
| 1211 |
+
|
| 1212 |
+
async function main(): Promise<void> {
|
| 1213 |
+
const args = parseArgs(process.argv.slice(2));
|
| 1214 |
+
if (args.help) {
|
| 1215 |
+
printUsage();
|
| 1216 |
+
return;
|
| 1217 |
+
}
|
| 1218 |
+
|
| 1219 |
+
await loadEnv();
|
| 1220 |
+
const extendConfig = await loadExtendConfig();
|
| 1221 |
+
const mergedArgs = mergeConfig(args, extendConfig);
|
| 1222 |
+
if (!mergedArgs.quality) mergedArgs.quality = "2k";
|
| 1223 |
+
|
| 1224 |
+
if (mergedArgs.batchFile) {
|
| 1225 |
+
await runBatchMode(mergedArgs, extendConfig);
|
| 1226 |
+
return;
|
| 1227 |
+
}
|
| 1228 |
+
|
| 1229 |
+
await runSingleMode(mergedArgs, extendConfig);
|
| 1230 |
+
}
|
| 1231 |
+
|
| 1232 |
+
function isDirectExecution(metaUrl: string): boolean {
|
| 1233 |
+
const entryPath = process.argv[1];
|
| 1234 |
+
if (!entryPath) return false;
|
| 1235 |
+
|
| 1236 |
+
try {
|
| 1237 |
+
return path.resolve(entryPath) === fileURLToPath(metaUrl);
|
| 1238 |
+
} catch {
|
| 1239 |
+
return false;
|
| 1240 |
+
}
|
| 1241 |
+
}
|
| 1242 |
+
|
| 1243 |
+
if (isDirectExecution(import.meta.url)) {
|
| 1244 |
+
main().catch((error) => {
|
| 1245 |
+
const message = error instanceof Error ? error.message : String(error);
|
| 1246 |
+
console.error(message);
|
| 1247 |
+
process.exit(1);
|
| 1248 |
+
});
|
| 1249 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/providers/azure.test.ts
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from "node:assert/strict";
|
| 2 |
+
import fs from "node:fs/promises";
|
| 3 |
+
import os from "node:os";
|
| 4 |
+
import path from "node:path";
|
| 5 |
+
import test, { type TestContext } from "node:test";
|
| 6 |
+
|
| 7 |
+
import type { CliArgs } from "../types.ts";
|
| 8 |
+
import {
|
| 9 |
+
generateImage,
|
| 10 |
+
getDefaultModel,
|
| 11 |
+
parseAzureBaseURL,
|
| 12 |
+
validateArgs,
|
| 13 |
+
} from "./azure.ts";
|
| 14 |
+
|
| 15 |
+
function useEnv(
|
| 16 |
+
t: TestContext,
|
| 17 |
+
values: Record<string, string | null>,
|
| 18 |
+
): void {
|
| 19 |
+
const previous = new Map<string, string | undefined>();
|
| 20 |
+
for (const [key, value] of Object.entries(values)) {
|
| 21 |
+
previous.set(key, process.env[key]);
|
| 22 |
+
if (value == null) {
|
| 23 |
+
delete process.env[key];
|
| 24 |
+
} else {
|
| 25 |
+
process.env[key] = value;
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
t.after(() => {
|
| 30 |
+
for (const [key, value] of previous.entries()) {
|
| 31 |
+
if (value == null) {
|
| 32 |
+
delete process.env[key];
|
| 33 |
+
} else {
|
| 34 |
+
process.env[key] = value;
|
| 35 |
+
}
|
| 36 |
+
}
|
| 37 |
+
});
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
| 41 |
+
return {
|
| 42 |
+
prompt: null,
|
| 43 |
+
promptFiles: [],
|
| 44 |
+
imagePath: null,
|
| 45 |
+
provider: null,
|
| 46 |
+
model: null,
|
| 47 |
+
aspectRatio: null,
|
| 48 |
+
size: null,
|
| 49 |
+
quality: null,
|
| 50 |
+
imageSize: null,
|
| 51 |
+
imageApiDialect: null,
|
| 52 |
+
referenceImages: [],
|
| 53 |
+
n: 1,
|
| 54 |
+
batchFile: null,
|
| 55 |
+
jobs: null,
|
| 56 |
+
json: false,
|
| 57 |
+
help: false,
|
| 58 |
+
...overrides,
|
| 59 |
+
};
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
async function makeTempDir(prefix: string): Promise<string> {
|
| 63 |
+
return fs.mkdtemp(path.join(os.tmpdir(), prefix));
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
test("Azure endpoint parsing and default deployment selection follow env precedence", (t) => {
|
| 67 |
+
assert.deepEqual(parseAzureBaseURL("https://example.openai.azure.com"), {
|
| 68 |
+
resourceBaseURL: "https://example.openai.azure.com/openai",
|
| 69 |
+
deployment: null,
|
| 70 |
+
});
|
| 71 |
+
assert.deepEqual(
|
| 72 |
+
parseAzureBaseURL("https://example.openai.azure.com/openai/deployments/from-url"),
|
| 73 |
+
{
|
| 74 |
+
resourceBaseURL: "https://example.openai.azure.com/openai",
|
| 75 |
+
deployment: "from-url",
|
| 76 |
+
},
|
| 77 |
+
);
|
| 78 |
+
|
| 79 |
+
useEnv(t, {
|
| 80 |
+
AZURE_OPENAI_BASE_URL: "https://example.openai.azure.com/openai/deployments/from-url",
|
| 81 |
+
AZURE_OPENAI_DEPLOYMENT: "explicit-deploy",
|
| 82 |
+
AZURE_OPENAI_IMAGE_MODEL: "env-fallback",
|
| 83 |
+
});
|
| 84 |
+
assert.equal(getDefaultModel(), "explicit-deploy");
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
test("Azure validateArgs rejects unsupported edit input formats before the API call", () => {
|
| 88 |
+
assert.doesNotThrow(() =>
|
| 89 |
+
validateArgs("demo-deployment", makeArgs({ referenceImages: ["hero.png", "photo.jpeg"] })),
|
| 90 |
+
);
|
| 91 |
+
assert.throws(
|
| 92 |
+
() => validateArgs("demo-deployment", makeArgs({ referenceImages: ["hero.webp"] })),
|
| 93 |
+
/PNG or JPG\/JPEG/,
|
| 94 |
+
);
|
| 95 |
+
});
|
| 96 |
+
|
| 97 |
+
test("Azure image generation routes model to deployment and sends mapped quality", async (t) => {
|
| 98 |
+
useEnv(t, {
|
| 99 |
+
AZURE_OPENAI_API_KEY: "azure-key",
|
| 100 |
+
AZURE_OPENAI_BASE_URL: "https://example.openai.azure.com/openai/deployments/default-deploy",
|
| 101 |
+
AZURE_API_VERSION: null,
|
| 102 |
+
AZURE_OPENAI_DEPLOYMENT: null,
|
| 103 |
+
AZURE_OPENAI_IMAGE_MODEL: null,
|
| 104 |
+
});
|
| 105 |
+
|
| 106 |
+
const originalFetch = globalThis.fetch;
|
| 107 |
+
t.after(() => {
|
| 108 |
+
globalThis.fetch = originalFetch;
|
| 109 |
+
});
|
| 110 |
+
|
| 111 |
+
const calls: Array<{ url: string; body: string }> = [];
|
| 112 |
+
globalThis.fetch = async (input, init) => {
|
| 113 |
+
calls.push({
|
| 114 |
+
url: String(input),
|
| 115 |
+
body: String(init?.body ?? ""),
|
| 116 |
+
});
|
| 117 |
+
return Response.json({
|
| 118 |
+
data: [{ b64_json: Buffer.from("azure-image").toString("base64") }],
|
| 119 |
+
});
|
| 120 |
+
};
|
| 121 |
+
|
| 122 |
+
const bytes = await generateImage(
|
| 123 |
+
"A calm lake at sunset",
|
| 124 |
+
"custom-deploy",
|
| 125 |
+
makeArgs({ quality: "normal" }),
|
| 126 |
+
);
|
| 127 |
+
|
| 128 |
+
assert.equal(Buffer.from(bytes).toString("utf8"), "azure-image");
|
| 129 |
+
assert.equal(
|
| 130 |
+
calls[0]?.url,
|
| 131 |
+
"https://example.openai.azure.com/openai/deployments/custom-deploy/images/generations?api-version=2025-04-01-preview",
|
| 132 |
+
);
|
| 133 |
+
|
| 134 |
+
const body = JSON.parse(calls[0]!.body) as Record<string, string>;
|
| 135 |
+
assert.equal(body.quality, "medium");
|
| 136 |
+
assert.equal(body.size, "1024x1024");
|
| 137 |
+
});
|
| 138 |
+
|
| 139 |
+
test("Azure image edits include quality in multipart requests", async (t) => {
|
| 140 |
+
const root = await makeTempDir("baoyu-image-gen-azure-");
|
| 141 |
+
t.after(() => fs.rm(root, { recursive: true, force: true }));
|
| 142 |
+
|
| 143 |
+
const pngPath = path.join(root, "ref.png");
|
| 144 |
+
const jpgPath = path.join(root, "ref.jpg");
|
| 145 |
+
await fs.writeFile(pngPath, "png-bytes");
|
| 146 |
+
await fs.writeFile(jpgPath, "jpg-bytes");
|
| 147 |
+
|
| 148 |
+
useEnv(t, {
|
| 149 |
+
AZURE_OPENAI_API_KEY: "azure-key",
|
| 150 |
+
AZURE_OPENAI_BASE_URL: "https://example.openai.azure.com",
|
| 151 |
+
AZURE_API_VERSION: "2025-04-01-preview",
|
| 152 |
+
AZURE_OPENAI_DEPLOYMENT: null,
|
| 153 |
+
AZURE_OPENAI_IMAGE_MODEL: null,
|
| 154 |
+
});
|
| 155 |
+
|
| 156 |
+
const originalFetch = globalThis.fetch;
|
| 157 |
+
t.after(() => {
|
| 158 |
+
globalThis.fetch = originalFetch;
|
| 159 |
+
});
|
| 160 |
+
|
| 161 |
+
const calls: Array<{ url: string; form: FormData }> = [];
|
| 162 |
+
globalThis.fetch = async (input, init) => {
|
| 163 |
+
calls.push({
|
| 164 |
+
url: String(input),
|
| 165 |
+
form: init?.body as FormData,
|
| 166 |
+
});
|
| 167 |
+
return Response.json({
|
| 168 |
+
data: [{ b64_json: Buffer.from("edited-image").toString("base64") }],
|
| 169 |
+
});
|
| 170 |
+
};
|
| 171 |
+
|
| 172 |
+
const bytes = await generateImage(
|
| 173 |
+
"Add warm lighting",
|
| 174 |
+
"edit-deploy",
|
| 175 |
+
makeArgs({
|
| 176 |
+
quality: "2k",
|
| 177 |
+
referenceImages: [pngPath, jpgPath],
|
| 178 |
+
}),
|
| 179 |
+
);
|
| 180 |
+
|
| 181 |
+
assert.equal(Buffer.from(bytes).toString("utf8"), "edited-image");
|
| 182 |
+
assert.equal(
|
| 183 |
+
calls[0]?.url,
|
| 184 |
+
"https://example.openai.azure.com/openai/deployments/edit-deploy/images/edits?api-version=2025-04-01-preview",
|
| 185 |
+
);
|
| 186 |
+
assert.equal(calls[0]?.form.get("quality"), "high");
|
| 187 |
+
assert.equal(calls[0]?.form.get("size"), "1024x1024");
|
| 188 |
+
assert.equal(calls[0]?.form.getAll("image[]").length, 2);
|
| 189 |
+
});
|
baoyu_skills/baoyu-imagine/scripts/providers/azure.ts
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import path from "node:path";
|
| 2 |
+
import { readFile } from "node:fs/promises";
|
| 3 |
+
import type { CliArgs } from "../types";
|
| 4 |
+
import { getOpenAISize, extractImageFromResponse } from "./openai.ts";
|
| 5 |
+
|
| 6 |
+
type OpenAIImageResponse = { data: Array<{ url?: string; b64_json?: string }> };
|
| 7 |
+
type AzureEndpoint = {
|
| 8 |
+
resourceBaseURL: string;
|
| 9 |
+
deployment: string | null;
|
| 10 |
+
};
|
| 11 |
+
|
| 12 |
+
const DEFAULT_AZURE_API_VERSION = "2025-04-01-preview";
|
| 13 |
+
const AZURE_EDIT_IMAGE_EXTENSIONS = new Set([".png", ".jpg", ".jpeg"]);
|
| 14 |
+
|
| 15 |
+
export function parseAzureBaseURL(url: string): AzureEndpoint {
|
| 16 |
+
const parsed = new URL(url);
|
| 17 |
+
const trimmedPath = parsed.pathname.replace(/\/+$/, "");
|
| 18 |
+
const deploymentMatch = trimmedPath.match(/^(.*?)(?:\/openai)?\/deployments\/([^/]+)$/);
|
| 19 |
+
|
| 20 |
+
if (deploymentMatch) {
|
| 21 |
+
parsed.pathname = `${deploymentMatch[1] || ""}/openai`;
|
| 22 |
+
return {
|
| 23 |
+
resourceBaseURL: parsed.toString().replace(/\/+$/, ""),
|
| 24 |
+
deployment: decodeURIComponent(deploymentMatch[2]!),
|
| 25 |
+
};
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
parsed.pathname = trimmedPath.endsWith("/openai") ? trimmedPath : `${trimmedPath}/openai`;
|
| 29 |
+
return {
|
| 30 |
+
resourceBaseURL: parsed.toString().replace(/\/+$/, ""),
|
| 31 |
+
deployment: null,
|
| 32 |
+
};
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
export function getDefaultModel(): string {
|
| 36 |
+
const explicitDeployment = process.env.AZURE_OPENAI_DEPLOYMENT?.trim();
|
| 37 |
+
if (explicitDeployment) return explicitDeployment;
|
| 38 |
+
|
| 39 |
+
const baseURL = process.env.AZURE_OPENAI_BASE_URL;
|
| 40 |
+
if (baseURL) {
|
| 41 |
+
try {
|
| 42 |
+
const { deployment } = parseAzureBaseURL(baseURL);
|
| 43 |
+
if (deployment) return deployment;
|
| 44 |
+
} catch {
|
| 45 |
+
// Ignore invalid URLs here so the required-env check can raise the user-facing error later.
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
return process.env.AZURE_OPENAI_IMAGE_MODEL || "gpt-image-2";
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
function getEndpoint(): AzureEndpoint {
|
| 53 |
+
const url = process.env.AZURE_OPENAI_BASE_URL;
|
| 54 |
+
if (!url) {
|
| 55 |
+
throw new Error(
|
| 56 |
+
"AZURE_OPENAI_BASE_URL is required. Set it to your Azure resource or deployment endpoint, e.g.: https://your-resource.openai.azure.com or https://your-resource.openai.azure.com/openai/deployments/your-deployment"
|
| 57 |
+
);
|
| 58 |
+
}
|
| 59 |
+
return parseAzureBaseURL(url);
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
function getApiKey(): string {
|
| 63 |
+
const key = process.env.AZURE_OPENAI_API_KEY;
|
| 64 |
+
if (!key) {
|
| 65 |
+
throw new Error(
|
| 66 |
+
"AZURE_OPENAI_API_KEY is required. Get it from Azure Portal → your OpenAI resource → Keys and Endpoint."
|
| 67 |
+
);
|
| 68 |
+
}
|
| 69 |
+
return key;
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
function getApiVersion(): string {
|
| 73 |
+
return process.env.AZURE_API_VERSION || DEFAULT_AZURE_API_VERSION;
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
function getDeployment(model: string): string {
|
| 77 |
+
const deployment = model.trim();
|
| 78 |
+
if (!deployment) {
|
| 79 |
+
throw new Error(
|
| 80 |
+
"Azure deployment name is required. Use --model <deployment>, AZURE_OPENAI_DEPLOYMENT, AZURE_OPENAI_IMAGE_MODEL, or embed the deployment in AZURE_OPENAI_BASE_URL."
|
| 81 |
+
);
|
| 82 |
+
}
|
| 83 |
+
return deployment;
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
function buildURL(deployment: string, pathSuffix: string): string {
|
| 87 |
+
const { resourceBaseURL } = getEndpoint();
|
| 88 |
+
return `${resourceBaseURL}/deployments/${encodeURIComponent(deployment)}${pathSuffix}?api-version=${getApiVersion()}`;
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
function authHeaders(): Record<string, string> {
|
| 92 |
+
return { "api-key": getApiKey() };
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
function getAzureQuality(quality: CliArgs["quality"]): "medium" | "high" {
|
| 96 |
+
return quality === "2k" ? "high" : "medium";
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
export function validateArgs(_model: string, args: CliArgs): void {
|
| 100 |
+
for (const refPath of args.referenceImages) {
|
| 101 |
+
const ext = path.extname(refPath).toLowerCase();
|
| 102 |
+
if (!AZURE_EDIT_IMAGE_EXTENSIONS.has(ext)) {
|
| 103 |
+
throw new Error(
|
| 104 |
+
`Azure OpenAI reference images must be PNG or JPG/JPEG. Unsupported file: ${refPath}`
|
| 105 |
+
);
|
| 106 |
+
}
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
export async function generateImage(
|
| 111 |
+
prompt: string,
|
| 112 |
+
model: string,
|
| 113 |
+
args: CliArgs
|
| 114 |
+
): Promise<Uint8Array> {
|
| 115 |
+
const deployment = getDeployment(model);
|
| 116 |
+
const size = args.size || getOpenAISize(model, args.aspectRatio, args.quality);
|
| 117 |
+
|
| 118 |
+
if (args.referenceImages.length > 0) {
|
| 119 |
+
return generateWithAzureEdits(prompt, deployment, size, args.referenceImages, args.quality);
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
return generateWithAzureGenerations(prompt, deployment, size, args.quality);
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
async function generateWithAzureGenerations(
|
| 126 |
+
prompt: string,
|
| 127 |
+
deployment: string,
|
| 128 |
+
size: string,
|
| 129 |
+
quality: CliArgs["quality"]
|
| 130 |
+
): Promise<Uint8Array> {
|
| 131 |
+
const body: Record<string, any> = {
|
| 132 |
+
prompt,
|
| 133 |
+
size,
|
| 134 |
+
n: 1,
|
| 135 |
+
quality: getAzureQuality(quality),
|
| 136 |
+
};
|
| 137 |
+
|
| 138 |
+
const res = await fetch(buildURL(deployment, "/images/generations"), {
|
| 139 |
+
method: "POST",
|
| 140 |
+
headers: {
|
| 141 |
+
"Content-Type": "application/json",
|
| 142 |
+
...authHeaders(),
|
| 143 |
+
},
|
| 144 |
+
body: JSON.stringify(body),
|
| 145 |
+
});
|
| 146 |
+
|
| 147 |
+
if (!res.ok) {
|
| 148 |
+
const err = await res.text();
|
| 149 |
+
throw new Error(`Azure OpenAI API error: ${err}`);
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
const result = (await res.json()) as OpenAIImageResponse;
|
| 153 |
+
return extractImageFromResponse(result);
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
async function generateWithAzureEdits(
|
| 157 |
+
prompt: string,
|
| 158 |
+
deployment: string,
|
| 159 |
+
size: string,
|
| 160 |
+
referenceImages: string[],
|
| 161 |
+
quality: CliArgs["quality"]
|
| 162 |
+
): Promise<Uint8Array> {
|
| 163 |
+
const form = new FormData();
|
| 164 |
+
form.append("prompt", prompt);
|
| 165 |
+
form.append("size", size);
|
| 166 |
+
form.append("n", "1");
|
| 167 |
+
form.append("quality", getAzureQuality(quality));
|
| 168 |
+
|
| 169 |
+
for (const refPath of referenceImages) {
|
| 170 |
+
const bytes = await readFile(refPath);
|
| 171 |
+
const filename = path.basename(refPath);
|
| 172 |
+
const mimeType = path.extname(filename).toLowerCase() === ".png" ? "image/png" : "image/jpeg";
|
| 173 |
+
const blob = new Blob([bytes], { type: mimeType });
|
| 174 |
+
form.append("image[]", blob, filename);
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
const res = await fetch(buildURL(deployment, "/images/edits"), {
|
| 178 |
+
method: "POST",
|
| 179 |
+
headers: {
|
| 180 |
+
...authHeaders(),
|
| 181 |
+
},
|
| 182 |
+
body: form,
|
| 183 |
+
});
|
| 184 |
+
|
| 185 |
+
if (!res.ok) {
|
| 186 |
+
const err = await res.text();
|
| 187 |
+
throw new Error(`Azure OpenAI edits API error: ${err}`);
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
const result = (await res.json()) as OpenAIImageResponse;
|
| 191 |
+
return extractImageFromResponse(result);
|
| 192 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/providers/codex-cli.test.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from "node:assert/strict";
|
| 2 |
+
import test from "node:test";
|
| 3 |
+
|
| 4 |
+
import type { CliArgs } from "../types.ts";
|
| 5 |
+
import {
|
| 6 |
+
getDefaultModel,
|
| 7 |
+
getDefaultOutputExtension,
|
| 8 |
+
validateArgs,
|
| 9 |
+
} from "./codex-cli.ts";
|
| 10 |
+
|
| 11 |
+
function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
| 12 |
+
return {
|
| 13 |
+
prompt: null,
|
| 14 |
+
promptFiles: [],
|
| 15 |
+
imagePath: null,
|
| 16 |
+
provider: "codex-cli",
|
| 17 |
+
model: null,
|
| 18 |
+
aspectRatio: null,
|
| 19 |
+
aspectRatioSource: null,
|
| 20 |
+
size: null,
|
| 21 |
+
quality: "2k",
|
| 22 |
+
imageSize: null,
|
| 23 |
+
imageSizeSource: null,
|
| 24 |
+
imageApiDialect: null,
|
| 25 |
+
referenceImages: [],
|
| 26 |
+
n: 1,
|
| 27 |
+
batchFile: null,
|
| 28 |
+
jobs: null,
|
| 29 |
+
json: false,
|
| 30 |
+
help: false,
|
| 31 |
+
...overrides,
|
| 32 |
+
};
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
test("codex-cli defaults to codex-image-gen model and PNG output", () => {
|
| 36 |
+
assert.equal(getDefaultModel(), "codex-image-gen");
|
| 37 |
+
assert.equal(getDefaultOutputExtension(), ".png");
|
| 38 |
+
});
|
| 39 |
+
|
| 40 |
+
test("codex-cli validateArgs rejects n>1 with a non-retryable message", () => {
|
| 41 |
+
assert.throws(
|
| 42 |
+
() => validateArgs("codex-image-gen", makeArgs({ n: 2 })),
|
| 43 |
+
/supports only n=1/,
|
| 44 |
+
);
|
| 45 |
+
});
|
| 46 |
+
|
| 47 |
+
test("codex-cli validateArgs rejects ratio-metadata dialect", () => {
|
| 48 |
+
assert.throws(
|
| 49 |
+
() => validateArgs("codex-image-gen", makeArgs({ imageApiDialect: "ratio-metadata" })),
|
| 50 |
+
/Invalid imageApiDialect/,
|
| 51 |
+
);
|
| 52 |
+
});
|
| 53 |
+
|
| 54 |
+
test("codex-cli validateArgs accepts default n=1 with no dialect", () => {
|
| 55 |
+
assert.doesNotThrow(() => validateArgs("codex-image-gen", makeArgs()));
|
| 56 |
+
});
|
| 57 |
+
|
| 58 |
+
test("codex-cli validateArgs accepts reference images (Codex image_gen supports refs)", () => {
|
| 59 |
+
assert.doesNotThrow(() =>
|
| 60 |
+
validateArgs("codex-image-gen", makeArgs({ referenceImages: ["/tmp/a.png", "/tmp/b.png"] })),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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import path from "node:path";
|
| 2 |
+
import { spawn } from "node:child_process";
|
| 3 |
+
import { fileURLToPath } from "node:url";
|
| 4 |
+
import { tmpdir } from "node:os";
|
| 5 |
+
import { mkdir, readFile, rm, writeFile, access } from "node:fs/promises";
|
| 6 |
+
import { randomBytes } from "node:crypto";
|
| 7 |
+
import type { CliArgs } from "../types";
|
| 8 |
+
|
| 9 |
+
const PROVIDER_FILE = fileURLToPath(import.meta.url);
|
| 10 |
+
const SCRIPTS_DIR = path.resolve(path.dirname(PROVIDER_FILE), "..");
|
| 11 |
+
const BUNDLED_WRAPPER = path.join(SCRIPTS_DIR, "codex-imagegen", "main.ts");
|
| 12 |
+
|
| 13 |
+
type WrapperOkResult = {
|
| 14 |
+
status: "ok";
|
| 15 |
+
path: string;
|
| 16 |
+
bytes: number;
|
| 17 |
+
elapsed_seconds: number;
|
| 18 |
+
thread_id: string | null;
|
| 19 |
+
attempts: number;
|
| 20 |
+
cached: boolean;
|
| 21 |
+
};
|
| 22 |
+
|
| 23 |
+
type WrapperErrorResult = {
|
| 24 |
+
status: "error";
|
| 25 |
+
path: string;
|
| 26 |
+
bytes: number;
|
| 27 |
+
error: string;
|
| 28 |
+
error_kind: string;
|
| 29 |
+
};
|
| 30 |
+
|
| 31 |
+
type WrapperResult = WrapperOkResult | WrapperErrorResult;
|
| 32 |
+
|
| 33 |
+
export function getDefaultModel(): string {
|
| 34 |
+
return "codex-image-gen";
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
export function getDefaultOutputExtension(): string {
|
| 38 |
+
return ".png";
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
export function validateArgs(_model: string, args: CliArgs): void {
|
| 42 |
+
if (args.n > 1) {
|
| 43 |
+
throw new Error(
|
| 44 |
+
"codex-cli provider supports only n=1 (Codex image_gen returns a single image per call).",
|
| 45 |
+
);
|
| 46 |
+
}
|
| 47 |
+
if (args.imageApiDialect && args.imageApiDialect !== "openai-native") {
|
| 48 |
+
throw new Error(
|
| 49 |
+
`Invalid imageApiDialect for codex-cli: ${args.imageApiDialect}. codex-cli does not use OpenAI Images API dialects.`,
|
| 50 |
+
);
|
| 51 |
+
}
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
async function exists(filePath: string): Promise<boolean> {
|
| 55 |
+
try {
|
| 56 |
+
await access(filePath);
|
| 57 |
+
return true;
|
| 58 |
+
} catch {
|
| 59 |
+
return false;
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
async function resolveWrapperPath(): Promise<string> {
|
| 64 |
+
const override = process.env.BAOYU_CODEX_IMAGEGEN_BIN;
|
| 65 |
+
if (override) {
|
| 66 |
+
if (!(await exists(override))) {
|
| 67 |
+
throw new Error(
|
| 68 |
+
`Invalid BAOYU_CODEX_IMAGEGEN_BIN: ${override} does not exist.`,
|
| 69 |
+
);
|
| 70 |
+
}
|
| 71 |
+
return override;
|
| 72 |
+
}
|
| 73 |
+
if (await exists(BUNDLED_WRAPPER)) return BUNDLED_WRAPPER;
|
| 74 |
+
throw new Error(
|
| 75 |
+
`codex-cli wrapper not found at ${BUNDLED_WRAPPER}. ` +
|
| 76 |
+
`Reinstall baoyu-image-gen, or set BAOYU_CODEX_IMAGEGEN_BIN to a codex-imagegen main.ts (or .sh) path.`,
|
| 77 |
+
);
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
type SpawnResult = {
|
| 81 |
+
stdout: string;
|
| 82 |
+
stderr: string;
|
| 83 |
+
code: number;
|
| 84 |
+
};
|
| 85 |
+
|
| 86 |
+
async function spawnWrapper(wrapperPath: string, cliArgs: string[]): Promise<SpawnResult> {
|
| 87 |
+
return new Promise((resolve, reject) => {
|
| 88 |
+
const isTs = wrapperPath.endsWith(".ts");
|
| 89 |
+
const command = isTs ? "bun" : wrapperPath;
|
| 90 |
+
const args = isTs ? [wrapperPath, ...cliArgs] : cliArgs;
|
| 91 |
+
const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] });
|
| 92 |
+
let stdout = "";
|
| 93 |
+
let stderr = "";
|
| 94 |
+
child.stdout.on("data", (chunk: Buffer) => {
|
| 95 |
+
stdout += chunk.toString("utf8");
|
| 96 |
+
});
|
| 97 |
+
child.stderr.on("data", (chunk: Buffer) => {
|
| 98 |
+
const text = chunk.toString("utf8");
|
| 99 |
+
stderr += text;
|
| 100 |
+
process.stderr.write(text);
|
| 101 |
+
});
|
| 102 |
+
child.on("error", (err) => reject(err));
|
| 103 |
+
child.on("close", (code) => resolve({ stdout, stderr, code: code ?? 1 }));
|
| 104 |
+
});
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
function parseWrapperJson(stdout: string): WrapperResult {
|
| 108 |
+
const trimmed = stdout.trim();
|
| 109 |
+
if (!trimmed) {
|
| 110 |
+
throw new Error("Invalid codex-cli response: empty stdout from wrapper.");
|
| 111 |
+
}
|
| 112 |
+
const lastLine = trimmed.split(/\r?\n/).pop() ?? trimmed;
|
| 113 |
+
try {
|
| 114 |
+
return JSON.parse(lastLine) as WrapperResult;
|
| 115 |
+
} catch (parseErr) {
|
| 116 |
+
throw new Error(
|
| 117 |
+
`Invalid codex-cli response: could not parse JSON from wrapper stdout (${(parseErr as Error).message}).`,
|
| 118 |
+
);
|
| 119 |
+
}
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
function parsePositiveInt(value: string | undefined): number | null {
|
| 123 |
+
if (!value) return null;
|
| 124 |
+
const parsed = parseInt(value, 10);
|
| 125 |
+
return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
function getEnvOverride(name: string): string | null {
|
| 129 |
+
const value = process.env[name];
|
| 130 |
+
return value && value.length > 0 ? value : null;
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
export async function generateImage(
|
| 134 |
+
prompt: string,
|
| 135 |
+
_model: string,
|
| 136 |
+
args: CliArgs,
|
| 137 |
+
): Promise<Uint8Array> {
|
| 138 |
+
const wrapperPath = await resolveWrapperPath();
|
| 139 |
+
|
| 140 |
+
const sessionDir = path.join(tmpdir(), "baoyu-image-gen-codex-cli");
|
| 141 |
+
await mkdir(sessionDir, { recursive: true });
|
| 142 |
+
const token = randomBytes(8).toString("hex");
|
| 143 |
+
const tmpOutput = path.join(sessionDir, `out-${token}.png`);
|
| 144 |
+
const tmpPrompt = path.join(sessionDir, `prompt-${token}.md`);
|
| 145 |
+
await writeFile(tmpPrompt, prompt, "utf8");
|
| 146 |
+
|
| 147 |
+
const aspect = args.aspectRatio ?? "1:1";
|
| 148 |
+
const cliArgs: string[] = [
|
| 149 |
+
"--image",
|
| 150 |
+
tmpOutput,
|
| 151 |
+
"--prompt-file",
|
| 152 |
+
tmpPrompt,
|
| 153 |
+
"--aspect",
|
| 154 |
+
aspect,
|
| 155 |
+
];
|
| 156 |
+
|
| 157 |
+
for (const ref of args.referenceImages) {
|
| 158 |
+
cliArgs.push("--ref", path.resolve(ref));
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
const cacheDir = getEnvOverride("BAOYU_CODEX_IMAGEGEN_CACHE_DIR");
|
| 162 |
+
if (cacheDir) cliArgs.push("--cache-dir", cacheDir);
|
| 163 |
+
|
| 164 |
+
const timeoutMs = parsePositiveInt(process.env.BAOYU_CODEX_IMAGEGEN_TIMEOUT_MS);
|
| 165 |
+
if (timeoutMs) cliArgs.push("--timeout", String(timeoutMs));
|
| 166 |
+
|
| 167 |
+
const retries = parsePositiveInt(process.env.BAOYU_CODEX_IMAGEGEN_RETRIES);
|
| 168 |
+
if (retries !== null) cliArgs.push("--retries", String(retries));
|
| 169 |
+
|
| 170 |
+
const logFile = getEnvOverride("BAOYU_CODEX_IMAGEGEN_LOG_FILE");
|
| 171 |
+
if (logFile) cliArgs.push("--log-file", logFile);
|
| 172 |
+
|
| 173 |
+
try {
|
| 174 |
+
const spawnResult = await spawnWrapper(wrapperPath, cliArgs);
|
| 175 |
+
const parsed = parseWrapperJson(spawnResult.stdout);
|
| 176 |
+
|
| 177 |
+
if (parsed.status === "error") {
|
| 178 |
+
throw new Error(
|
| 179 |
+
`Invalid codex-cli result (${parsed.error_kind}): ${parsed.error}`,
|
| 180 |
+
);
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
if (spawnResult.code !== 0) {
|
| 184 |
+
throw new Error(
|
| 185 |
+
`Invalid codex-cli result: wrapper exited with code ${spawnResult.code} despite reporting status=ok.`,
|
| 186 |
+
);
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
const bytes = await readFile(parsed.path ?? tmpOutput);
|
| 190 |
+
return new Uint8Array(bytes);
|
| 191 |
+
} finally {
|
| 192 |
+
await Promise.allSettled([
|
| 193 |
+
rm(tmpOutput, { force: true }),
|
| 194 |
+
rm(tmpPrompt, { force: true }),
|
| 195 |
+
]);
|
| 196 |
+
}
|
| 197 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/providers/dashscope.test.ts
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from "node:assert/strict";
|
| 2 |
+
import test, { type TestContext } from "node:test";
|
| 3 |
+
|
| 4 |
+
import {
|
| 5 |
+
generateImage,
|
| 6 |
+
getDefaultModel,
|
| 7 |
+
getModelFamily,
|
| 8 |
+
getQwen2SizeFromAspectRatio,
|
| 9 |
+
getSizeFromAspectRatio,
|
| 10 |
+
getWan27SizeFromAspectRatio,
|
| 11 |
+
normalizeSize,
|
| 12 |
+
parseAspectRatio,
|
| 13 |
+
parseSize,
|
| 14 |
+
resolveSizeForModel,
|
| 15 |
+
} from "./dashscope.ts";
|
| 16 |
+
import type { CliArgs } from "../types.ts";
|
| 17 |
+
|
| 18 |
+
function makeCliArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
| 19 |
+
return {
|
| 20 |
+
prompt: null,
|
| 21 |
+
promptFiles: [],
|
| 22 |
+
imagePath: null,
|
| 23 |
+
provider: "dashscope",
|
| 24 |
+
model: null,
|
| 25 |
+
aspectRatio: null,
|
| 26 |
+
aspectRatioSource: null,
|
| 27 |
+
size: null,
|
| 28 |
+
quality: "2k",
|
| 29 |
+
imageSize: null,
|
| 30 |
+
imageSizeSource: null,
|
| 31 |
+
imageApiDialect: null,
|
| 32 |
+
referenceImages: [],
|
| 33 |
+
n: 1,
|
| 34 |
+
batchFile: null,
|
| 35 |
+
jobs: null,
|
| 36 |
+
json: false,
|
| 37 |
+
help: false,
|
| 38 |
+
...overrides,
|
| 39 |
+
};
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
function useEnv(
|
| 43 |
+
t: TestContext,
|
| 44 |
+
values: Record<string, string | null>,
|
| 45 |
+
): void {
|
| 46 |
+
const previous = new Map<string, string | undefined>();
|
| 47 |
+
for (const [key, value] of Object.entries(values)) {
|
| 48 |
+
previous.set(key, process.env[key]);
|
| 49 |
+
if (value == null) {
|
| 50 |
+
delete process.env[key];
|
| 51 |
+
} else {
|
| 52 |
+
process.env[key] = value;
|
| 53 |
+
}
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
t.after(() => {
|
| 57 |
+
for (const [key, value] of previous.entries()) {
|
| 58 |
+
if (value == null) {
|
| 59 |
+
delete process.env[key];
|
| 60 |
+
} else {
|
| 61 |
+
process.env[key] = value;
|
| 62 |
+
}
|
| 63 |
+
}
|
| 64 |
+
});
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
test("DashScope default model prefers env override and otherwise uses qwen-image-2.0-pro", (t) => {
|
| 68 |
+
useEnv(t, { DASHSCOPE_IMAGE_MODEL: null });
|
| 69 |
+
assert.equal(getDefaultModel(), "qwen-image-2.0-pro");
|
| 70 |
+
|
| 71 |
+
process.env.DASHSCOPE_IMAGE_MODEL = "qwen-image-max";
|
| 72 |
+
assert.equal(getDefaultModel(), "qwen-image-max");
|
| 73 |
+
});
|
| 74 |
+
|
| 75 |
+
test("DashScope aspect-ratio parsing accepts numeric ratios only", () => {
|
| 76 |
+
assert.deepEqual(parseAspectRatio("3:2"), { width: 3, height: 2 });
|
| 77 |
+
assert.equal(parseAspectRatio("square"), null);
|
| 78 |
+
assert.equal(parseAspectRatio("-1:2"), null);
|
| 79 |
+
});
|
| 80 |
+
|
| 81 |
+
test("DashScope model family routing distinguishes qwen-2.0, fixed-size qwen, wan2.7, and legacy models", () => {
|
| 82 |
+
assert.equal(getModelFamily("qwen-image-2.0-pro"), "qwen2");
|
| 83 |
+
assert.equal(getModelFamily("qwen-image"), "qwenFixed");
|
| 84 |
+
assert.equal(getModelFamily("wan2.7-image"), "wan27");
|
| 85 |
+
assert.equal(getModelFamily("wan2.7-image-pro"), "wan27");
|
| 86 |
+
assert.equal(getModelFamily("z-image-turbo"), "legacy");
|
| 87 |
+
assert.equal(getModelFamily("wanx-v1"), "legacy");
|
| 88 |
+
});
|
| 89 |
+
|
| 90 |
+
test("Legacy DashScope size selection keeps the previous quality-based heuristic", () => {
|
| 91 |
+
assert.equal(getSizeFromAspectRatio(null, "normal"), "1024*1024");
|
| 92 |
+
assert.equal(getSizeFromAspectRatio("16:9", "normal"), "1280*720");
|
| 93 |
+
assert.equal(getSizeFromAspectRatio("16:9", "2k"), "2048*1152");
|
| 94 |
+
assert.equal(getSizeFromAspectRatio("invalid", "2k"), "1536*1536");
|
| 95 |
+
});
|
| 96 |
+
|
| 97 |
+
test("Qwen 2.0 recommended sizes follow the official common-ratio table", () => {
|
| 98 |
+
assert.equal(getQwen2SizeFromAspectRatio(null, "normal"), "1024*1024");
|
| 99 |
+
assert.equal(getQwen2SizeFromAspectRatio(null, "2k"), "1536*1536");
|
| 100 |
+
assert.equal(getQwen2SizeFromAspectRatio("16:9", "normal"), "1280*720");
|
| 101 |
+
assert.equal(getQwen2SizeFromAspectRatio("21:9", "2k"), "2048*872");
|
| 102 |
+
});
|
| 103 |
+
|
| 104 |
+
test("Qwen 2.0 derives free-form sizes within pixel budget for uncommon ratios", () => {
|
| 105 |
+
const size = getQwen2SizeFromAspectRatio("5:2", "normal");
|
| 106 |
+
const parsed = parseSize(size);
|
| 107 |
+
assert.ok(parsed);
|
| 108 |
+
assert.ok(parsed.width * parsed.height >= 512 * 512);
|
| 109 |
+
assert.ok(parsed.width * parsed.height <= 2048 * 2048);
|
| 110 |
+
assert.ok(Math.abs(parsed.width / parsed.height - 2.5) < 0.08);
|
| 111 |
+
});
|
| 112 |
+
|
| 113 |
+
test("resolveSizeForModel validates explicit qwen-image-2.0 sizes by total pixels", () => {
|
| 114 |
+
assert.equal(
|
| 115 |
+
resolveSizeForModel("qwen-image-2.0-pro", {
|
| 116 |
+
size: "2048x872",
|
| 117 |
+
aspectRatio: null,
|
| 118 |
+
quality: "2k",
|
| 119 |
+
}),
|
| 120 |
+
"2048*872",
|
| 121 |
+
);
|
| 122 |
+
|
| 123 |
+
assert.throws(
|
| 124 |
+
() =>
|
| 125 |
+
resolveSizeForModel("qwen-image-2.0-pro", {
|
| 126 |
+
size: "4096x4096",
|
| 127 |
+
aspectRatio: null,
|
| 128 |
+
quality: "2k",
|
| 129 |
+
}),
|
| 130 |
+
/total pixels between/,
|
| 131 |
+
);
|
| 132 |
+
});
|
| 133 |
+
|
| 134 |
+
test("resolveSizeForModel enforces fixed sizes for qwen-image-max/plus/image", () => {
|
| 135 |
+
assert.equal(
|
| 136 |
+
resolveSizeForModel("qwen-image-max", {
|
| 137 |
+
size: null,
|
| 138 |
+
aspectRatio: "1:1",
|
| 139 |
+
quality: "2k",
|
| 140 |
+
}),
|
| 141 |
+
"1328*1328",
|
| 142 |
+
);
|
| 143 |
+
|
| 144 |
+
assert.equal(
|
| 145 |
+
resolveSizeForModel("qwen-image", {
|
| 146 |
+
size: "1664x928",
|
| 147 |
+
aspectRatio: "9:16",
|
| 148 |
+
quality: "normal",
|
| 149 |
+
}),
|
| 150 |
+
"1664*928",
|
| 151 |
+
);
|
| 152 |
+
|
| 153 |
+
assert.throws(
|
| 154 |
+
() =>
|
| 155 |
+
resolveSizeForModel("qwen-image-max", {
|
| 156 |
+
size: null,
|
| 157 |
+
aspectRatio: "21:9",
|
| 158 |
+
quality: "2k",
|
| 159 |
+
}),
|
| 160 |
+
/supports only fixed ratios/,
|
| 161 |
+
);
|
| 162 |
+
|
| 163 |
+
assert.throws(
|
| 164 |
+
() =>
|
| 165 |
+
resolveSizeForModel("qwen-image-plus", {
|
| 166 |
+
size: "1024x1024",
|
| 167 |
+
aspectRatio: null,
|
| 168 |
+
quality: "2k",
|
| 169 |
+
}),
|
| 170 |
+
/support only these sizes/,
|
| 171 |
+
);
|
| 172 |
+
});
|
| 173 |
+
|
| 174 |
+
test("DashScope size normalization converts WxH into provider format", () => {
|
| 175 |
+
assert.equal(normalizeSize("1024x1024"), "1024*1024");
|
| 176 |
+
assert.equal(normalizeSize("2048*1152"), "2048*1152");
|
| 177 |
+
});
|
| 178 |
+
|
| 179 |
+
test("Wan 2.7 derives sizes that match the requested ratio at the chosen pixel budget", () => {
|
| 180 |
+
const square2k = getWan27SizeFromAspectRatio(null, "2k", 2048 * 2048);
|
| 181 |
+
const parsedSquare = parseSize(square2k);
|
| 182 |
+
assert.ok(parsedSquare);
|
| 183 |
+
assert.equal(parsedSquare.width, parsedSquare.height);
|
| 184 |
+
assert.ok(parsedSquare.width * parsedSquare.height <= 2048 * 2048);
|
| 185 |
+
|
| 186 |
+
const widescreen = getWan27SizeFromAspectRatio("16:9", "2k", 2048 * 2048);
|
| 187 |
+
const parsedWide = parseSize(widescreen);
|
| 188 |
+
assert.ok(parsedWide);
|
| 189 |
+
assert.ok(Math.abs(parsedWide.width / parsedWide.height - 16 / 9) < 0.05);
|
| 190 |
+
assert.ok(parsedWide.width * parsedWide.height <= 2048 * 2048);
|
| 191 |
+
|
| 192 |
+
const pro4k = getWan27SizeFromAspectRatio("16:9", "2k", 4096 * 4096);
|
| 193 |
+
const parsed4k = parseSize(pro4k);
|
| 194 |
+
assert.ok(parsed4k);
|
| 195 |
+
assert.ok(parsed4k.width * parsed4k.height > 2048 * 2048);
|
| 196 |
+
assert.ok(parsed4k.width * parsed4k.height <= 4096 * 4096);
|
| 197 |
+
});
|
| 198 |
+
|
| 199 |
+
test("Wan 2.7 rejects aspect ratios outside the [1:8, 8:1] range", () => {
|
| 200 |
+
assert.throws(
|
| 201 |
+
() => getWan27SizeFromAspectRatio("9:1", "2k", 2048 * 2048),
|
| 202 |
+
/1:8, 8:1/,
|
| 203 |
+
);
|
| 204 |
+
assert.throws(
|
| 205 |
+
() => getWan27SizeFromAspectRatio("1:9", "normal", 2048 * 2048),
|
| 206 |
+
/1:8, 8:1/,
|
| 207 |
+
);
|
| 208 |
+
});
|
| 209 |
+
|
| 210 |
+
test("Wan 2.7 derived sizes stay inside the boundary ratio limits after rounding", () => {
|
| 211 |
+
for (const ar of ["8:1", "1:8"]) {
|
| 212 |
+
const size = getWan27SizeFromAspectRatio(ar, "2k", 2048 * 2048);
|
| 213 |
+
const parsed = parseSize(size);
|
| 214 |
+
assert.ok(parsed);
|
| 215 |
+
const ratio = parsed.width / parsed.height;
|
| 216 |
+
assert.ok(ratio >= 1 / 8);
|
| 217 |
+
assert.ok(ratio <= 8);
|
| 218 |
+
assert.ok(parsed.width * parsed.height <= 2048 * 2048);
|
| 219 |
+
}
|
| 220 |
+
});
|
| 221 |
+
|
| 222 |
+
test("resolveSizeForModel routes wan2.7-image to the 2K-capped derivation", () => {
|
| 223 |
+
const size = resolveSizeForModel("wan2.7-image", {
|
| 224 |
+
size: null,
|
| 225 |
+
aspectRatio: "16:9",
|
| 226 |
+
quality: "2k",
|
| 227 |
+
});
|
| 228 |
+
const parsed = parseSize(size);
|
| 229 |
+
assert.ok(parsed);
|
| 230 |
+
assert.ok(parsed.width * parsed.height <= 2048 * 2048);
|
| 231 |
+
assert.ok(Math.abs(parsed.width / parsed.height - 16 / 9) < 0.05);
|
| 232 |
+
});
|
| 233 |
+
|
| 234 |
+
test("resolveSizeForModel allows wan2.7-image-pro 4K only when there are no reference images", () => {
|
| 235 |
+
assert.equal(
|
| 236 |
+
resolveSizeForModel("wan2.7-image-pro", {
|
| 237 |
+
size: "4096*4096",
|
| 238 |
+
aspectRatio: null,
|
| 239 |
+
quality: "2k",
|
| 240 |
+
}),
|
| 241 |
+
"4096*4096",
|
| 242 |
+
);
|
| 243 |
+
|
| 244 |
+
assert.throws(
|
| 245 |
+
() =>
|
| 246 |
+
resolveSizeForModel("wan2.7-image-pro", {
|
| 247 |
+
size: "4096*4096",
|
| 248 |
+
aspectRatio: null,
|
| 249 |
+
quality: "2k",
|
| 250 |
+
referenceImages: ["a.png"],
|
| 251 |
+
}),
|
| 252 |
+
/total pixels between 768\*768 and 2048\*2048/,
|
| 253 |
+
);
|
| 254 |
+
|
| 255 |
+
const proWithRef = resolveSizeForModel("wan2.7-image-pro", {
|
| 256 |
+
size: null,
|
| 257 |
+
aspectRatio: "1:1",
|
| 258 |
+
quality: "2k",
|
| 259 |
+
referenceImages: ["a.png"],
|
| 260 |
+
});
|
| 261 |
+
const parsedRef = parseSize(proWithRef);
|
| 262 |
+
assert.ok(parsedRef);
|
| 263 |
+
assert.ok(parsedRef.width * parsedRef.height <= 2048 * 2048);
|
| 264 |
+
});
|
| 265 |
+
|
| 266 |
+
test("Wan 2.7 request body forces n=1 and omits prompt_extend / negative_prompt", async (t) => {
|
| 267 |
+
useEnv(t, { DASHSCOPE_API_KEY: "fake-key" });
|
| 268 |
+
|
| 269 |
+
const originalFetch = globalThis.fetch;
|
| 270 |
+
let capturedBody: any = null;
|
| 271 |
+
globalThis.fetch = (async (_url: string, init?: RequestInit) => {
|
| 272 |
+
capturedBody = JSON.parse(String(init?.body));
|
| 273 |
+
return new Response(
|
| 274 |
+
JSON.stringify({
|
| 275 |
+
output: {
|
| 276 |
+
choices: [
|
| 277 |
+
{
|
| 278 |
+
message: {
|
| 279 |
+
content: [{ image: "data:image/png;base64,iVBORw0KGgo=" }],
|
| 280 |
+
},
|
| 281 |
+
},
|
| 282 |
+
],
|
| 283 |
+
},
|
| 284 |
+
}),
|
| 285 |
+
{ status: 200, headers: { "content-type": "application/json" } },
|
| 286 |
+
);
|
| 287 |
+
}) as typeof fetch;
|
| 288 |
+
t.after(() => {
|
| 289 |
+
globalThis.fetch = originalFetch;
|
| 290 |
+
});
|
| 291 |
+
|
| 292 |
+
await generateImage("hello", "wan2.7-image-pro", makeCliArgs({ aspectRatio: "1:1" }));
|
| 293 |
+
|
| 294 |
+
assert.equal(capturedBody.model, "wan2.7-image-pro");
|
| 295 |
+
assert.deepEqual(Object.keys(capturedBody.parameters).sort(), ["n", "size", "watermark"]);
|
| 296 |
+
assert.equal(capturedBody.parameters.n, 1);
|
| 297 |
+
assert.equal(capturedBody.parameters.watermark, false);
|
| 298 |
+
assert.equal(typeof capturedBody.parameters.size, "string");
|
| 299 |
+
assert.ok(!("prompt_extend" in capturedBody.parameters));
|
| 300 |
+
assert.ok(!("negative_prompt" in capturedBody.parameters));
|
| 301 |
+
|
| 302 |
+
assert.deepEqual(capturedBody.input.messages[0].content, [{ text: "hello" }]);
|
| 303 |
+
});
|
| 304 |
+
|
| 305 |
+
test("Wan 2.7 request body forwards remote reference image URLs", async (t) => {
|
| 306 |
+
useEnv(t, { DASHSCOPE_API_KEY: "fake-key" });
|
| 307 |
+
|
| 308 |
+
const originalFetch = globalThis.fetch;
|
| 309 |
+
let capturedBody: any = null;
|
| 310 |
+
globalThis.fetch = (async (_url: string, init?: RequestInit) => {
|
| 311 |
+
capturedBody = JSON.parse(String(init?.body));
|
| 312 |
+
return new Response(
|
| 313 |
+
JSON.stringify({
|
| 314 |
+
output: {
|
| 315 |
+
choices: [
|
| 316 |
+
{
|
| 317 |
+
message: {
|
| 318 |
+
content: [{ image: "data:image/png;base64,iVBORw0KGgo=" }],
|
| 319 |
+
},
|
| 320 |
+
},
|
| 321 |
+
],
|
| 322 |
+
},
|
| 323 |
+
}),
|
| 324 |
+
{ status: 200, headers: { "content-type": "application/json" } },
|
| 325 |
+
);
|
| 326 |
+
}) as typeof fetch;
|
| 327 |
+
t.after(() => {
|
| 328 |
+
globalThis.fetch = originalFetch;
|
| 329 |
+
});
|
| 330 |
+
|
| 331 |
+
await generateImage(
|
| 332 |
+
"combine these",
|
| 333 |
+
"wan2.7-image-pro",
|
| 334 |
+
makeCliArgs({ referenceImages: ["https://example.com/ref.png"] }),
|
| 335 |
+
);
|
| 336 |
+
|
| 337 |
+
assert.deepEqual(capturedBody.input.messages[0].content, [
|
| 338 |
+
{ image: "https://example.com/ref.png" },
|
| 339 |
+
{ text: "combine these" },
|
| 340 |
+
]);
|
| 341 |
+
});
|
| 342 |
+
|
| 343 |
+
test("Wan 2.7 rejects --n > 1 to prevent silent multi-image billing", async (t) => {
|
| 344 |
+
useEnv(t, { DASHSCOPE_API_KEY: "fake-key" });
|
| 345 |
+
|
| 346 |
+
await assert.rejects(
|
| 347 |
+
() => generateImage("hi", "wan2.7-image-pro", makeCliArgs({ n: 2 })),
|
| 348 |
+
/support exactly one output image/,
|
| 349 |
+
);
|
| 350 |
+
});
|
| 351 |
+
|
| 352 |
+
test("resolveSizeForModel validates explicit wan2.7 sizes by pixel budget and ratio", () => {
|
| 353 |
+
assert.equal(
|
| 354 |
+
resolveSizeForModel("wan2.7-image-pro", {
|
| 355 |
+
size: "3840x2160",
|
| 356 |
+
aspectRatio: null,
|
| 357 |
+
quality: "2k",
|
| 358 |
+
}),
|
| 359 |
+
"3840*2160",
|
| 360 |
+
);
|
| 361 |
+
|
| 362 |
+
assert.throws(
|
| 363 |
+
() =>
|
| 364 |
+
resolveSizeForModel("wan2.7-image-pro", {
|
| 365 |
+
size: "3840x2160",
|
| 366 |
+
aspectRatio: null,
|
| 367 |
+
quality: "2k",
|
| 368 |
+
referenceImages: ["a.png"],
|
| 369 |
+
}),
|
| 370 |
+
/total pixels between 768\*768 and 2048\*2048/,
|
| 371 |
+
);
|
| 372 |
+
|
| 373 |
+
assert.throws(
|
| 374 |
+
() =>
|
| 375 |
+
resolveSizeForModel("wan2.7-image", {
|
| 376 |
+
size: "4096x4096",
|
| 377 |
+
aspectRatio: null,
|
| 378 |
+
quality: "2k",
|
| 379 |
+
}),
|
| 380 |
+
/total pixels between 768\*768 and 2048\*2048/,
|
| 381 |
+
);
|
| 382 |
+
|
| 383 |
+
assert.throws(
|
| 384 |
+
() =>
|
| 385 |
+
resolveSizeForModel("wan2.7-image-pro", {
|
| 386 |
+
size: "3072*256",
|
| 387 |
+
aspectRatio: null,
|
| 388 |
+
quality: "2k",
|
| 389 |
+
}),
|
| 390 |
+
/1:8, 8:1/,
|
| 391 |
+
);
|
| 392 |
+
});
|
baoyu_skills/baoyu-imagine/scripts/providers/dashscope.ts
ADDED
|
@@ -0,0 +1,625 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import path from "node:path";
|
| 2 |
+
import { readFile } from "node:fs/promises";
|
| 3 |
+
import type { CliArgs, Quality } from "../types";
|
| 4 |
+
|
| 5 |
+
type DashScopeModelFamily = "qwen2" | "qwenFixed" | "wan27" | "legacy";
|
| 6 |
+
|
| 7 |
+
type DashScopeModelSpec = {
|
| 8 |
+
family: DashScopeModelFamily;
|
| 9 |
+
defaultSize: string;
|
| 10 |
+
};
|
| 11 |
+
|
| 12 |
+
const DEFAULT_MODEL = "qwen-image-2.0-pro";
|
| 13 |
+
const MIN_QWEN_2_TOTAL_PIXELS = 512 * 512;
|
| 14 |
+
const MAX_QWEN_2_TOTAL_PIXELS = 2048 * 2048;
|
| 15 |
+
const SIZE_STEP = 16;
|
| 16 |
+
const QWEN_NEGATIVE_PROMPT =
|
| 17 |
+
"低分辨率,低画质,肢体畸形,手指畸形,画面过饱和,蜡像感,人脸无细节,过度光滑,画面具有AI感,构图混乱,文字模糊,扭曲";
|
| 18 |
+
|
| 19 |
+
const QWEN_2_TARGET_PIXELS: Record<Quality, number> = {
|
| 20 |
+
normal: 1024 * 1024,
|
| 21 |
+
"2k": 1536 * 1536,
|
| 22 |
+
};
|
| 23 |
+
|
| 24 |
+
const MIN_WAN27_TOTAL_PIXELS = 768 * 768;
|
| 25 |
+
const MAX_WAN27_PRO_T2I_PIXELS = 4096 * 4096;
|
| 26 |
+
const MAX_WAN27_GENERAL_PIXELS = 2048 * 2048;
|
| 27 |
+
const WAN27_MAX_REFERENCE_IMAGES = 9;
|
| 28 |
+
|
| 29 |
+
const WAN27_TARGET_PIXELS: Record<Quality, number> = {
|
| 30 |
+
normal: 1024 * 1024,
|
| 31 |
+
"2k": 2048 * 2048,
|
| 32 |
+
};
|
| 33 |
+
|
| 34 |
+
const QWEN_2_RECOMMENDED: Record<string, Record<Quality, string>> = {
|
| 35 |
+
"1:1": { normal: "1024*1024", "2k": "1536*1536" },
|
| 36 |
+
"2:3": { normal: "768*1152", "2k": "1024*1536" },
|
| 37 |
+
"3:2": { normal: "1152*768", "2k": "1536*1024" },
|
| 38 |
+
"3:4": { normal: "960*1280", "2k": "1080*1440" },
|
| 39 |
+
"4:3": { normal: "1280*960", "2k": "1440*1080" },
|
| 40 |
+
"9:16": { normal: "720*1280", "2k": "1080*1920" },
|
| 41 |
+
"16:9": { normal: "1280*720", "2k": "1920*1080" },
|
| 42 |
+
"21:9": { normal: "1344*576", "2k": "2048*872" },
|
| 43 |
+
};
|
| 44 |
+
|
| 45 |
+
const QWEN_FIXED_SIZES_BY_RATIO: Record<string, string> = {
|
| 46 |
+
"16:9": "1664*928",
|
| 47 |
+
"4:3": "1472*1104",
|
| 48 |
+
"1:1": "1328*1328",
|
| 49 |
+
"3:4": "1104*1472",
|
| 50 |
+
"9:16": "928*1664",
|
| 51 |
+
};
|
| 52 |
+
|
| 53 |
+
const QWEN_FIXED_SIZES = Object.values(QWEN_FIXED_SIZES_BY_RATIO);
|
| 54 |
+
|
| 55 |
+
const LEGACY_STANDARD_SIZES: [number, number][] = [
|
| 56 |
+
[1024, 1024],
|
| 57 |
+
[1280, 720],
|
| 58 |
+
[720, 1280],
|
| 59 |
+
[1024, 768],
|
| 60 |
+
[768, 1024],
|
| 61 |
+
[1536, 1024],
|
| 62 |
+
[1024, 1536],
|
| 63 |
+
[1536, 864],
|
| 64 |
+
[864, 1536],
|
| 65 |
+
];
|
| 66 |
+
|
| 67 |
+
const LEGACY_STANDARD_SIZES_2K: [number, number][] = [
|
| 68 |
+
[1536, 1536],
|
| 69 |
+
[2048, 1152],
|
| 70 |
+
[1152, 2048],
|
| 71 |
+
[1536, 1024],
|
| 72 |
+
[1024, 1536],
|
| 73 |
+
[1536, 864],
|
| 74 |
+
[864, 1536],
|
| 75 |
+
[2048, 2048],
|
| 76 |
+
];
|
| 77 |
+
|
| 78 |
+
const QWEN_2_SPEC: DashScopeModelSpec = {
|
| 79 |
+
family: "qwen2",
|
| 80 |
+
defaultSize: "1024*1024",
|
| 81 |
+
};
|
| 82 |
+
|
| 83 |
+
const QWEN_FIXED_SPEC: DashScopeModelSpec = {
|
| 84 |
+
family: "qwenFixed",
|
| 85 |
+
defaultSize: QWEN_FIXED_SIZES_BY_RATIO["16:9"],
|
| 86 |
+
};
|
| 87 |
+
|
| 88 |
+
const WAN27_SPEC: DashScopeModelSpec = {
|
| 89 |
+
family: "wan27",
|
| 90 |
+
defaultSize: "2048*2048",
|
| 91 |
+
};
|
| 92 |
+
|
| 93 |
+
const LEGACY_SPEC: DashScopeModelSpec = {
|
| 94 |
+
family: "legacy",
|
| 95 |
+
defaultSize: "1536*1536",
|
| 96 |
+
};
|
| 97 |
+
|
| 98 |
+
const MODEL_SPEC_ALIASES: Record<string, DashScopeModelSpec> = {
|
| 99 |
+
"qwen-image-2.0-pro": QWEN_2_SPEC,
|
| 100 |
+
"qwen-image-2.0-pro-2026-03-03": QWEN_2_SPEC,
|
| 101 |
+
"qwen-image-2.0": QWEN_2_SPEC,
|
| 102 |
+
"qwen-image-2.0-2026-03-03": QWEN_2_SPEC,
|
| 103 |
+
"qwen-image-max": QWEN_FIXED_SPEC,
|
| 104 |
+
"qwen-image-max-2025-12-30": QWEN_FIXED_SPEC,
|
| 105 |
+
"qwen-image-plus": QWEN_FIXED_SPEC,
|
| 106 |
+
"qwen-image-plus-2026-01-09": QWEN_FIXED_SPEC,
|
| 107 |
+
"qwen-image": QWEN_FIXED_SPEC,
|
| 108 |
+
"wan2.7-image-pro": WAN27_SPEC,
|
| 109 |
+
"wan2.7-image": WAN27_SPEC,
|
| 110 |
+
};
|
| 111 |
+
|
| 112 |
+
export function getDefaultModel(): string {
|
| 113 |
+
return process.env.DASHSCOPE_IMAGE_MODEL || DEFAULT_MODEL;
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
function getReferenceImageMime(filePath: string): string {
|
| 117 |
+
const ext = path.extname(filePath).toLowerCase();
|
| 118 |
+
if (ext === ".jpg" || ext === ".jpeg") return "image/jpeg";
|
| 119 |
+
if (ext === ".webp") return "image/webp";
|
| 120 |
+
if (ext === ".bmp") return "image/bmp";
|
| 121 |
+
return "image/png";
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
async function loadReferenceImage(refPath: string): Promise<string> {
|
| 125 |
+
if (/^https?:\/\//i.test(refPath)) {
|
| 126 |
+
return refPath;
|
| 127 |
+
}
|
| 128 |
+
const fullPath = path.resolve(refPath);
|
| 129 |
+
const bytes = await readFile(fullPath);
|
| 130 |
+
return `data:${getReferenceImageMime(fullPath)};base64,${bytes.toString("base64")}`;
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
function getApiKey(): string | null {
|
| 134 |
+
return process.env.DASHSCOPE_API_KEY || null;
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
function getBaseUrl(): string {
|
| 138 |
+
const base = process.env.DASHSCOPE_BASE_URL || "https://dashscope.aliyuncs.com";
|
| 139 |
+
return base.replace(/\/+$/g, "");
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
function getModelSpec(model: string): DashScopeModelSpec {
|
| 143 |
+
return MODEL_SPEC_ALIASES[model.trim().toLowerCase()] || LEGACY_SPEC;
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
export function getModelFamily(model: string): DashScopeModelFamily {
|
| 147 |
+
return getModelSpec(model).family;
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
function normalizeQuality(quality: CliArgs["quality"]): Quality {
|
| 151 |
+
return quality === "normal" ? "normal" : "2k";
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
export function parseAspectRatio(ar: string): { width: number; height: number } | null {
|
| 155 |
+
const match = ar.match(/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/);
|
| 156 |
+
if (!match) return null;
|
| 157 |
+
const w = parseFloat(match[1]!);
|
| 158 |
+
const h = parseFloat(match[2]!);
|
| 159 |
+
if (w <= 0 || h <= 0) return null;
|
| 160 |
+
return { width: w, height: h };
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
export function normalizeSize(size: string): string {
|
| 164 |
+
return size.replace("x", "*");
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
export function parseSize(size: string): { width: number; height: number } | null {
|
| 168 |
+
const match = normalizeSize(size).match(/^(\d+)\*(\d+)$/);
|
| 169 |
+
if (!match) return null;
|
| 170 |
+
const width = Number(match[1]);
|
| 171 |
+
const height = Number(match[2]);
|
| 172 |
+
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
|
| 173 |
+
return null;
|
| 174 |
+
}
|
| 175 |
+
return { width, height };
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
function formatSize(width: number, height: number): string {
|
| 179 |
+
return `${width}*${height}`;
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
function getRatioValue(ar: string): number | null {
|
| 183 |
+
const parsed = parseAspectRatio(ar);
|
| 184 |
+
if (!parsed) return null;
|
| 185 |
+
return parsed.width / parsed.height;
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
function findKnownRatioKey(ar: string, candidates: string[], tolerance = 0.02): string | null {
|
| 189 |
+
const targetRatio = getRatioValue(ar);
|
| 190 |
+
if (targetRatio == null) return null;
|
| 191 |
+
|
| 192 |
+
let bestKey: string | null = null;
|
| 193 |
+
let bestDiff = Infinity;
|
| 194 |
+
|
| 195 |
+
for (const candidate of candidates) {
|
| 196 |
+
const candidateRatio = getRatioValue(candidate);
|
| 197 |
+
if (candidateRatio == null) continue;
|
| 198 |
+
const diff = Math.abs(candidateRatio - targetRatio);
|
| 199 |
+
if (diff < bestDiff) {
|
| 200 |
+
bestDiff = diff;
|
| 201 |
+
bestKey = candidate;
|
| 202 |
+
}
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
return bestDiff <= tolerance ? bestKey : null;
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
function roundToStep(value: number): number {
|
| 209 |
+
return Math.max(SIZE_STEP, Math.round(value / SIZE_STEP) * SIZE_STEP);
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
function floorToStep(value: number): number {
|
| 213 |
+
return Math.max(SIZE_STEP, Math.floor(value / SIZE_STEP) * SIZE_STEP);
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
function fitToPixelBudget(
|
| 217 |
+
width: number,
|
| 218 |
+
height: number,
|
| 219 |
+
minPixels: number,
|
| 220 |
+
maxPixels: number,
|
| 221 |
+
): { width: number; height: number } {
|
| 222 |
+
let nextWidth = width;
|
| 223 |
+
let nextHeight = height;
|
| 224 |
+
let pixels = nextWidth * nextHeight;
|
| 225 |
+
|
| 226 |
+
if (pixels > maxPixels) {
|
| 227 |
+
const scale = Math.sqrt(maxPixels / pixels);
|
| 228 |
+
nextWidth *= scale;
|
| 229 |
+
nextHeight *= scale;
|
| 230 |
+
} else if (pixels < minPixels) {
|
| 231 |
+
const scale = Math.sqrt(minPixels / pixels);
|
| 232 |
+
nextWidth *= scale;
|
| 233 |
+
nextHeight *= scale;
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
let roundedWidth = roundToStep(nextWidth);
|
| 237 |
+
let roundedHeight = roundToStep(nextHeight);
|
| 238 |
+
pixels = roundedWidth * roundedHeight;
|
| 239 |
+
|
| 240 |
+
while (pixels > maxPixels && (roundedWidth > SIZE_STEP || roundedHeight > SIZE_STEP)) {
|
| 241 |
+
if (roundedWidth >= roundedHeight && roundedWidth > SIZE_STEP) {
|
| 242 |
+
roundedWidth -= SIZE_STEP;
|
| 243 |
+
} else if (roundedHeight > SIZE_STEP) {
|
| 244 |
+
roundedHeight -= SIZE_STEP;
|
| 245 |
+
} else {
|
| 246 |
+
break;
|
| 247 |
+
}
|
| 248 |
+
pixels = roundedWidth * roundedHeight;
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
while (pixels < minPixels) {
|
| 252 |
+
if (roundedWidth <= roundedHeight) {
|
| 253 |
+
roundedWidth += SIZE_STEP;
|
| 254 |
+
} else {
|
| 255 |
+
roundedHeight += SIZE_STEP;
|
| 256 |
+
}
|
| 257 |
+
pixels = roundedWidth * roundedHeight;
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
return { width: roundedWidth, height: roundedHeight };
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
function clampWan27DerivedSizeToRatioBounds(
|
| 264 |
+
size: { width: number; height: number },
|
| 265 |
+
): { width: number; height: number } {
|
| 266 |
+
let { width, height } = size;
|
| 267 |
+
const ratio = width / height;
|
| 268 |
+
|
| 269 |
+
if (ratio > 8) {
|
| 270 |
+
width = floorToStep(height * 8);
|
| 271 |
+
} else if (ratio < 1 / 8) {
|
| 272 |
+
height = floorToStep(width * 8);
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
return { width, height };
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
export function getSizeFromAspectRatio(ar: string | null, quality: CliArgs["quality"]): string {
|
| 279 |
+
const normalizedQuality = normalizeQuality(quality);
|
| 280 |
+
const sizes = normalizedQuality === "2k" ? LEGACY_STANDARD_SIZES_2K : LEGACY_STANDARD_SIZES;
|
| 281 |
+
const defaultSize = normalizedQuality === "2k" ? "1536*1536" : "1024*1024";
|
| 282 |
+
|
| 283 |
+
if (!ar) return defaultSize;
|
| 284 |
+
|
| 285 |
+
const parsed = parseAspectRatio(ar);
|
| 286 |
+
if (!parsed) return defaultSize;
|
| 287 |
+
|
| 288 |
+
const targetRatio = parsed.width / parsed.height;
|
| 289 |
+
let best = defaultSize;
|
| 290 |
+
let bestDiff = Infinity;
|
| 291 |
+
|
| 292 |
+
for (const [width, height] of sizes) {
|
| 293 |
+
const diff = Math.abs(width / height - targetRatio);
|
| 294 |
+
if (diff < bestDiff) {
|
| 295 |
+
bestDiff = diff;
|
| 296 |
+
best = formatSize(width, height);
|
| 297 |
+
}
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
return best;
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
export function getQwen2SizeFromAspectRatio(ar: string | null, quality: CliArgs["quality"]): string {
|
| 304 |
+
const normalizedQuality = normalizeQuality(quality);
|
| 305 |
+
|
| 306 |
+
if (!ar) {
|
| 307 |
+
return QWEN_2_RECOMMENDED["1:1"][normalizedQuality];
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
const recommendedRatio = findKnownRatioKey(ar, Object.keys(QWEN_2_RECOMMENDED));
|
| 311 |
+
if (recommendedRatio) {
|
| 312 |
+
return QWEN_2_RECOMMENDED[recommendedRatio][normalizedQuality];
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
const parsed = parseAspectRatio(ar);
|
| 316 |
+
if (!parsed) {
|
| 317 |
+
return QWEN_2_RECOMMENDED["1:1"][normalizedQuality];
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
const targetRatio = parsed.width / parsed.height;
|
| 321 |
+
const targetPixels = QWEN_2_TARGET_PIXELS[normalizedQuality];
|
| 322 |
+
const rawWidth = Math.sqrt(targetPixels * targetRatio);
|
| 323 |
+
const rawHeight = Math.sqrt(targetPixels / targetRatio);
|
| 324 |
+
const fitted = fitToPixelBudget(
|
| 325 |
+
rawWidth,
|
| 326 |
+
rawHeight,
|
| 327 |
+
MIN_QWEN_2_TOTAL_PIXELS,
|
| 328 |
+
MAX_QWEN_2_TOTAL_PIXELS,
|
| 329 |
+
);
|
| 330 |
+
|
| 331 |
+
return formatSize(fitted.width, fitted.height);
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
function isWan27ProModel(model: string): boolean {
|
| 335 |
+
return model.trim().toLowerCase() === "wan2.7-image-pro";
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
function getWan27MaxPixels(model: string, hasReferenceImages: boolean): number {
|
| 339 |
+
if (isWan27ProModel(model) && !hasReferenceImages) {
|
| 340 |
+
return MAX_WAN27_PRO_T2I_PIXELS;
|
| 341 |
+
}
|
| 342 |
+
return MAX_WAN27_GENERAL_PIXELS;
|
| 343 |
+
}
|
| 344 |
+
|
| 345 |
+
export function getWan27SizeFromAspectRatio(
|
| 346 |
+
ar: string | null,
|
| 347 |
+
quality: CliArgs["quality"],
|
| 348 |
+
maxPixels: number,
|
| 349 |
+
): string {
|
| 350 |
+
const normalizedQuality = normalizeQuality(quality);
|
| 351 |
+
const targetPixels = Math.min(WAN27_TARGET_PIXELS[normalizedQuality], maxPixels);
|
| 352 |
+
|
| 353 |
+
if (!ar) {
|
| 354 |
+
const side = roundToStep(Math.sqrt(targetPixels));
|
| 355 |
+
return formatSize(side, side);
|
| 356 |
+
}
|
| 357 |
+
|
| 358 |
+
const parsed = parseAspectRatio(ar);
|
| 359 |
+
if (!parsed) {
|
| 360 |
+
const side = roundToStep(Math.sqrt(targetPixels));
|
| 361 |
+
return formatSize(side, side);
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
const ratio = parsed.width / parsed.height;
|
| 365 |
+
if (ratio < 1 / 8 || ratio > 8) {
|
| 366 |
+
throw new Error(
|
| 367 |
+
`DashScope wan2.7 image models support aspect ratios in [1:8, 8:1]. Received "${ar}".`
|
| 368 |
+
);
|
| 369 |
+
}
|
| 370 |
+
|
| 371 |
+
const rawWidth = Math.sqrt(targetPixels * ratio);
|
| 372 |
+
const rawHeight = Math.sqrt(targetPixels / ratio);
|
| 373 |
+
const fitted = fitToPixelBudget(
|
| 374 |
+
rawWidth,
|
| 375 |
+
rawHeight,
|
| 376 |
+
MIN_WAN27_TOTAL_PIXELS,
|
| 377 |
+
maxPixels,
|
| 378 |
+
);
|
| 379 |
+
const bounded = clampWan27DerivedSizeToRatioBounds(fitted);
|
| 380 |
+
|
| 381 |
+
return formatSize(bounded.width, bounded.height);
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
function validateWan27Size(size: string, maxPixels: number, model: string): string {
|
| 385 |
+
const normalized = normalizeSize(size);
|
| 386 |
+
const parsed = validateSizeFormat(normalized);
|
| 387 |
+
const totalPixels = parsed.width * parsed.height;
|
| 388 |
+
if (totalPixels < MIN_WAN27_TOTAL_PIXELS || totalPixels > maxPixels) {
|
| 389 |
+
const limit = maxPixels === MAX_WAN27_PRO_T2I_PIXELS ? "4096*4096" : "2048*2048";
|
| 390 |
+
throw new Error(
|
| 391 |
+
`DashScope ${model} requires total pixels between 768*768 and ${limit} ` +
|
| 392 |
+
`for the current request. Received ${normalized} (${totalPixels} pixels).`
|
| 393 |
+
);
|
| 394 |
+
}
|
| 395 |
+
const ratio = parsed.width / parsed.height;
|
| 396 |
+
if (ratio < 1 / 8 || ratio > 8) {
|
| 397 |
+
throw new Error(
|
| 398 |
+
`DashScope wan2.7 image models support aspect ratios in [1:8, 8:1]. ` +
|
| 399 |
+
`Received ${normalized} (ratio ${ratio.toFixed(3)}).`
|
| 400 |
+
);
|
| 401 |
+
}
|
| 402 |
+
return normalized;
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
function getQwenFixedSizeFromAspectRatio(ar: string | null, quality: CliArgs["quality"]): string {
|
| 406 |
+
if (quality === "normal") {
|
| 407 |
+
console.warn(
|
| 408 |
+
"DashScope qwen-image-max/plus/image models use fixed output sizes; --quality normal does not change the generated resolution."
|
| 409 |
+
);
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
if (!ar) return QWEN_FIXED_SPEC.defaultSize;
|
| 413 |
+
|
| 414 |
+
const ratioKey = findKnownRatioKey(ar, Object.keys(QWEN_FIXED_SIZES_BY_RATIO));
|
| 415 |
+
if (!ratioKey) {
|
| 416 |
+
throw new Error(
|
| 417 |
+
`DashScope model supports only fixed ratios ${Object.keys(QWEN_FIXED_SIZES_BY_RATIO).join(", ")}. ` +
|
| 418 |
+
`For custom ratios like "${ar}", use --model qwen-image-2.0-pro.`
|
| 419 |
+
);
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
return QWEN_FIXED_SIZES_BY_RATIO[ratioKey]!;
|
| 423 |
+
}
|
| 424 |
+
|
| 425 |
+
function validateSizeFormat(size: string): { width: number; height: number } {
|
| 426 |
+
const parsed = parseSize(size);
|
| 427 |
+
if (!parsed) {
|
| 428 |
+
throw new Error(`Invalid DashScope size "${size}". Expected <width>x<height> or <width>*<height>.`);
|
| 429 |
+
}
|
| 430 |
+
return parsed;
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
function validateQwen2Size(size: string): string {
|
| 434 |
+
const normalized = normalizeSize(size);
|
| 435 |
+
const parsed = validateSizeFormat(normalized);
|
| 436 |
+
const totalPixels = parsed.width * parsed.height;
|
| 437 |
+
if (totalPixels < MIN_QWEN_2_TOTAL_PIXELS || totalPixels > MAX_QWEN_2_TOTAL_PIXELS) {
|
| 438 |
+
throw new Error(
|
| 439 |
+
`DashScope qwen-image-2.0* models require total pixels between ${MIN_QWEN_2_TOTAL_PIXELS} ` +
|
| 440 |
+
`and ${MAX_QWEN_2_TOTAL_PIXELS}. Received ${normalized} (${totalPixels} pixels).`
|
| 441 |
+
);
|
| 442 |
+
}
|
| 443 |
+
return normalized;
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
function validateQwenFixedSize(size: string): string {
|
| 447 |
+
const normalized = normalizeSize(size);
|
| 448 |
+
validateSizeFormat(normalized);
|
| 449 |
+
if (!QWEN_FIXED_SIZES.includes(normalized)) {
|
| 450 |
+
throw new Error(
|
| 451 |
+
`DashScope qwen-image-max/plus/image models support only these sizes: ${QWEN_FIXED_SIZES.join(", ")}. ` +
|
| 452 |
+
`Received ${normalized}.`
|
| 453 |
+
);
|
| 454 |
+
}
|
| 455 |
+
return normalized;
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
export function resolveSizeForModel(
|
| 459 |
+
model: string,
|
| 460 |
+
args: Pick<CliArgs, "size" | "aspectRatio" | "quality"> & { referenceImages?: string[] },
|
| 461 |
+
): string {
|
| 462 |
+
const spec = getModelSpec(model);
|
| 463 |
+
const referenceCount = args.referenceImages?.length ?? 0;
|
| 464 |
+
|
| 465 |
+
if (spec.family === "wan27") {
|
| 466 |
+
const maxPixels = getWan27MaxPixels(model, referenceCount > 0);
|
| 467 |
+
if (args.size) return validateWan27Size(args.size, maxPixels, model);
|
| 468 |
+
return getWan27SizeFromAspectRatio(args.aspectRatio, args.quality, maxPixels);
|
| 469 |
+
}
|
| 470 |
+
|
| 471 |
+
if (args.size) {
|
| 472 |
+
if (spec.family === "qwen2") return validateQwen2Size(args.size);
|
| 473 |
+
if (spec.family === "qwenFixed") return validateQwenFixedSize(args.size);
|
| 474 |
+
validateSizeFormat(args.size);
|
| 475 |
+
return normalizeSize(args.size);
|
| 476 |
+
}
|
| 477 |
+
|
| 478 |
+
if (spec.family === "qwen2") {
|
| 479 |
+
return getQwen2SizeFromAspectRatio(args.aspectRatio, args.quality);
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
if (spec.family === "qwenFixed") {
|
| 483 |
+
return getQwenFixedSizeFromAspectRatio(args.aspectRatio, args.quality);
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
return getSizeFromAspectRatio(args.aspectRatio, args.quality);
|
| 487 |
+
}
|
| 488 |
+
|
| 489 |
+
function buildParameters(
|
| 490 |
+
family: DashScopeModelFamily,
|
| 491 |
+
size: string,
|
| 492 |
+
): Record<string, unknown> {
|
| 493 |
+
if (family === "wan27") {
|
| 494 |
+
return {
|
| 495 |
+
size,
|
| 496 |
+
n: 1,
|
| 497 |
+
watermark: false,
|
| 498 |
+
};
|
| 499 |
+
}
|
| 500 |
+
|
| 501 |
+
const parameters: Record<string, unknown> = {
|
| 502 |
+
prompt_extend: false,
|
| 503 |
+
size,
|
| 504 |
+
};
|
| 505 |
+
|
| 506 |
+
if (family === "qwen2" || family === "qwenFixed") {
|
| 507 |
+
parameters.watermark = false;
|
| 508 |
+
parameters.negative_prompt = QWEN_NEGATIVE_PROMPT;
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
return parameters;
|
| 512 |
+
}
|
| 513 |
+
|
| 514 |
+
type DashScopeResponse = {
|
| 515 |
+
output?: {
|
| 516 |
+
result_image?: string;
|
| 517 |
+
choices?: Array<{
|
| 518 |
+
message?: {
|
| 519 |
+
content?: Array<{ image?: string }>;
|
| 520 |
+
};
|
| 521 |
+
}>;
|
| 522 |
+
};
|
| 523 |
+
};
|
| 524 |
+
|
| 525 |
+
async function extractImageFromResponse(result: DashScopeResponse): Promise<Uint8Array> {
|
| 526 |
+
let imageData: string | null = null;
|
| 527 |
+
|
| 528 |
+
if (result.output?.result_image) {
|
| 529 |
+
imageData = result.output.result_image;
|
| 530 |
+
} else if (result.output?.choices?.[0]?.message?.content) {
|
| 531 |
+
const content = result.output.choices[0].message.content;
|
| 532 |
+
for (const item of content) {
|
| 533 |
+
if (item.image) {
|
| 534 |
+
imageData = item.image;
|
| 535 |
+
break;
|
| 536 |
+
}
|
| 537 |
+
}
|
| 538 |
+
}
|
| 539 |
+
|
| 540 |
+
if (!imageData) {
|
| 541 |
+
console.error("Response:", JSON.stringify(result, null, 2));
|
| 542 |
+
throw new Error("No image in response");
|
| 543 |
+
}
|
| 544 |
+
|
| 545 |
+
if (imageData.startsWith("http://") || imageData.startsWith("https://")) {
|
| 546 |
+
const imgRes = await fetch(imageData);
|
| 547 |
+
if (!imgRes.ok) throw new Error("Failed to download image");
|
| 548 |
+
const buf = await imgRes.arrayBuffer();
|
| 549 |
+
return new Uint8Array(buf);
|
| 550 |
+
}
|
| 551 |
+
|
| 552 |
+
return Uint8Array.from(Buffer.from(imageData, "base64"));
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
export async function generateImage(
|
| 556 |
+
prompt: string,
|
| 557 |
+
model: string,
|
| 558 |
+
args: CliArgs
|
| 559 |
+
): Promise<Uint8Array> {
|
| 560 |
+
const apiKey = getApiKey();
|
| 561 |
+
if (!apiKey) throw new Error("DASHSCOPE_API_KEY is required");
|
| 562 |
+
|
| 563 |
+
const spec = getModelSpec(model);
|
| 564 |
+
|
| 565 |
+
if (args.referenceImages.length > 0 && spec.family !== "wan27") {
|
| 566 |
+
throw new Error(
|
| 567 |
+
"Reference images are not supported with this DashScope model. Use a wan2.7 image model (--model wan2.7-image-pro or wan2.7-image), or switch to --provider google with a Gemini multimodal model."
|
| 568 |
+
);
|
| 569 |
+
}
|
| 570 |
+
|
| 571 |
+
if (args.referenceImages.length > WAN27_MAX_REFERENCE_IMAGES) {
|
| 572 |
+
throw new Error(
|
| 573 |
+
`DashScope wan2.7 image models accept at most ${WAN27_MAX_REFERENCE_IMAGES} reference images. Received ${args.referenceImages.length}.`
|
| 574 |
+
);
|
| 575 |
+
}
|
| 576 |
+
|
| 577 |
+
if (spec.family === "wan27" && args.n !== 1) {
|
| 578 |
+
throw new Error(
|
| 579 |
+
"DashScope wan2.7 image models in baoyu-image-gen support exactly one output image per request (extra images would be billed but discarded). Remove --n or use --n 1."
|
| 580 |
+
);
|
| 581 |
+
}
|
| 582 |
+
|
| 583 |
+
const size = resolveSizeForModel(model, args);
|
| 584 |
+
const url = `${getBaseUrl()}/api/v1/services/aigc/multimodal-generation/generation`;
|
| 585 |
+
|
| 586 |
+
const content: Array<Record<string, unknown>> = [];
|
| 587 |
+
if (spec.family === "wan27" && args.referenceImages.length > 0) {
|
| 588 |
+
for (const refPath of args.referenceImages) {
|
| 589 |
+
content.push({ image: await loadReferenceImage(refPath) });
|
| 590 |
+
}
|
| 591 |
+
}
|
| 592 |
+
content.push({ text: prompt });
|
| 593 |
+
|
| 594 |
+
const body = {
|
| 595 |
+
model,
|
| 596 |
+
input: {
|
| 597 |
+
messages: [
|
| 598 |
+
{
|
| 599 |
+
role: "user",
|
| 600 |
+
content,
|
| 601 |
+
},
|
| 602 |
+
],
|
| 603 |
+
},
|
| 604 |
+
parameters: buildParameters(spec.family, size),
|
| 605 |
+
};
|
| 606 |
+
|
| 607 |
+
console.log(`Generating image with DashScope (${model})...`, { family: spec.family, size });
|
| 608 |
+
|
| 609 |
+
const res = await fetch(url, {
|
| 610 |
+
method: "POST",
|
| 611 |
+
headers: {
|
| 612 |
+
"Content-Type": "application/json",
|
| 613 |
+
Authorization: `Bearer ${apiKey}`,
|
| 614 |
+
},
|
| 615 |
+
body: JSON.stringify(body),
|
| 616 |
+
});
|
| 617 |
+
|
| 618 |
+
if (!res.ok) {
|
| 619 |
+
const err = await res.text();
|
| 620 |
+
throw new Error(`DashScope API error (${res.status}): ${err}`);
|
| 621 |
+
}
|
| 622 |
+
|
| 623 |
+
const result = await res.json() as DashScopeResponse;
|
| 624 |
+
return extractImageFromResponse(result);
|
| 625 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/providers/google.test.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from "node:assert/strict";
|
| 2 |
+
import test, { type TestContext } from "node:test";
|
| 3 |
+
|
| 4 |
+
import type { CliArgs } from "../types.ts";
|
| 5 |
+
import {
|
| 6 |
+
addAspectRatioToPrompt,
|
| 7 |
+
buildGoogleUrl,
|
| 8 |
+
buildPromptWithAspect,
|
| 9 |
+
extractInlineImageData,
|
| 10 |
+
extractPredictedImageData,
|
| 11 |
+
getGoogleImageSize,
|
| 12 |
+
isGoogleImagen,
|
| 13 |
+
isGoogleMultimodal,
|
| 14 |
+
normalizeGoogleModelId,
|
| 15 |
+
} from "./google.ts";
|
| 16 |
+
|
| 17 |
+
function useEnv(
|
| 18 |
+
t: TestContext,
|
| 19 |
+
values: Record<string, string | null>,
|
| 20 |
+
): void {
|
| 21 |
+
const previous = new Map<string, string | undefined>();
|
| 22 |
+
for (const [key, value] of Object.entries(values)) {
|
| 23 |
+
previous.set(key, process.env[key]);
|
| 24 |
+
if (value == null) {
|
| 25 |
+
delete process.env[key];
|
| 26 |
+
} else {
|
| 27 |
+
process.env[key] = value;
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
t.after(() => {
|
| 32 |
+
for (const [key, value] of previous.entries()) {
|
| 33 |
+
if (value == null) {
|
| 34 |
+
delete process.env[key];
|
| 35 |
+
} else {
|
| 36 |
+
process.env[key] = value;
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
});
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
| 43 |
+
return {
|
| 44 |
+
prompt: null,
|
| 45 |
+
promptFiles: [],
|
| 46 |
+
imagePath: null,
|
| 47 |
+
provider: null,
|
| 48 |
+
model: null,
|
| 49 |
+
aspectRatio: null,
|
| 50 |
+
size: null,
|
| 51 |
+
quality: null,
|
| 52 |
+
imageSize: null,
|
| 53 |
+
imageApiDialect: null,
|
| 54 |
+
referenceImages: [],
|
| 55 |
+
n: 1,
|
| 56 |
+
batchFile: null,
|
| 57 |
+
jobs: null,
|
| 58 |
+
json: false,
|
| 59 |
+
help: false,
|
| 60 |
+
...overrides,
|
| 61 |
+
};
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
test("Google provider helpers normalize model IDs and select image size defaults", () => {
|
| 65 |
+
assert.equal(
|
| 66 |
+
normalizeGoogleModelId("models/gemini-3.1-flash-image-preview"),
|
| 67 |
+
"gemini-3.1-flash-image-preview",
|
| 68 |
+
);
|
| 69 |
+
assert.equal(isGoogleMultimodal("models/gemini-3-pro-image-preview"), true);
|
| 70 |
+
assert.equal(isGoogleMultimodal("gemini-3-pro-image"), true);
|
| 71 |
+
assert.equal(isGoogleMultimodal("gemini-3.1-flash-image"), true);
|
| 72 |
+
assert.equal(isGoogleMultimodal("models/gemini-3-pro-image"), true);
|
| 73 |
+
assert.equal(isGoogleImagen("imagen-3.0-generate-002"), true);
|
| 74 |
+
assert.equal(getGoogleImageSize(makeArgs({ imageSize: null, quality: "2k" })), "2K");
|
| 75 |
+
assert.equal(getGoogleImageSize(makeArgs({ imageSize: "4K", quality: "normal" })), "4K");
|
| 76 |
+
});
|
| 77 |
+
|
| 78 |
+
test("Google URL builder appends v1beta when the base URL does not already include it", (t) => {
|
| 79 |
+
useEnv(t, { GOOGLE_BASE_URL: "https://generativelanguage.googleapis.com" });
|
| 80 |
+
assert.equal(
|
| 81 |
+
buildGoogleUrl("models/demo:generateContent"),
|
| 82 |
+
"https://generativelanguage.googleapis.com/v1beta/models/demo:generateContent",
|
| 83 |
+
);
|
| 84 |
+
});
|
| 85 |
+
|
| 86 |
+
test("Google URL and prompt helpers preserve existing v1beta paths and aspect hints", (t) => {
|
| 87 |
+
useEnv(t, { GOOGLE_BASE_URL: "https://example.com/custom/v1beta/" });
|
| 88 |
+
assert.equal(
|
| 89 |
+
buildGoogleUrl("/models/demo:predict"),
|
| 90 |
+
"https://example.com/custom/v1beta/models/demo:predict",
|
| 91 |
+
);
|
| 92 |
+
|
| 93 |
+
assert.equal(
|
| 94 |
+
addAspectRatioToPrompt("A city skyline", "16:9"),
|
| 95 |
+
"A city skyline Aspect ratio: 16:9.",
|
| 96 |
+
);
|
| 97 |
+
assert.equal(
|
| 98 |
+
buildPromptWithAspect("A city skyline", "16:9", "2k"),
|
| 99 |
+
"A city skyline Aspect ratio: 16:9. High resolution 2048px.",
|
| 100 |
+
);
|
| 101 |
+
});
|
| 102 |
+
|
| 103 |
+
test("Google response extractors find inline and predicted image payloads", () => {
|
| 104 |
+
assert.equal(
|
| 105 |
+
extractInlineImageData({
|
| 106 |
+
candidates: [
|
| 107 |
+
{
|
| 108 |
+
content: {
|
| 109 |
+
parts: [{ inlineData: { data: "inline-base64" } }],
|
| 110 |
+
},
|
| 111 |
+
},
|
| 112 |
+
],
|
| 113 |
+
}),
|
| 114 |
+
"inline-base64",
|
| 115 |
+
);
|
| 116 |
+
|
| 117 |
+
assert.equal(
|
| 118 |
+
extractPredictedImageData({
|
| 119 |
+
predictions: [{ image: { imageBytes: "predicted-base64" } }],
|
| 120 |
+
}),
|
| 121 |
+
"predicted-base64",
|
| 122 |
+
);
|
| 123 |
+
|
| 124 |
+
assert.equal(
|
| 125 |
+
extractPredictedImageData({
|
| 126 |
+
generatedImages: [{ bytesBase64Encoded: "generated-base64" }],
|
| 127 |
+
}),
|
| 128 |
+
"generated-base64",
|
| 129 |
+
);
|
| 130 |
+
});
|
baoyu_skills/baoyu-imagine/scripts/providers/google.ts
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import path from "node:path";
|
| 2 |
+
import { readFile } from "node:fs/promises";
|
| 3 |
+
import { execFileSync } from "node:child_process";
|
| 4 |
+
import type { CliArgs } from "../types";
|
| 5 |
+
|
| 6 |
+
const GOOGLE_MULTIMODAL_MODELS = [
|
| 7 |
+
"gemini-3-pro-image",
|
| 8 |
+
"gemini-3.1-flash-image",
|
| 9 |
+
"gemini-3-pro-image-preview",
|
| 10 |
+
"gemini-3-flash-preview",
|
| 11 |
+
"gemini-3.1-flash-image-preview",
|
| 12 |
+
];
|
| 13 |
+
const GOOGLE_IMAGEN_MODELS = [
|
| 14 |
+
"imagen-3.0-generate-002",
|
| 15 |
+
"imagen-3.0-generate-001",
|
| 16 |
+
];
|
| 17 |
+
|
| 18 |
+
export function getDefaultModel(): string {
|
| 19 |
+
return process.env.GOOGLE_IMAGE_MODEL || "gemini-3-pro-image";
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
export function normalizeGoogleModelId(model: string): string {
|
| 23 |
+
return model.startsWith("models/") ? model.slice("models/".length) : model;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
export function isGoogleMultimodal(model: string): boolean {
|
| 27 |
+
const normalized = normalizeGoogleModelId(model);
|
| 28 |
+
return GOOGLE_MULTIMODAL_MODELS.some((m) => normalized.includes(m));
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
export function isGoogleImagen(model: string): boolean {
|
| 32 |
+
const normalized = normalizeGoogleModelId(model);
|
| 33 |
+
return GOOGLE_IMAGEN_MODELS.some((m) => normalized.includes(m));
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
function getGoogleApiKey(): string | null {
|
| 37 |
+
return process.env.GOOGLE_API_KEY || process.env.GEMINI_API_KEY || null;
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
export function getGoogleImageSize(args: CliArgs): "1K" | "2K" | "4K" {
|
| 41 |
+
if (args.imageSize) return args.imageSize as "1K" | "2K" | "4K";
|
| 42 |
+
return args.quality === "2k" ? "2K" : "1K";
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
function getGoogleBaseUrl(): string {
|
| 46 |
+
const base =
|
| 47 |
+
process.env.GOOGLE_BASE_URL || "https://generativelanguage.googleapis.com";
|
| 48 |
+
return base.replace(/\/+$/g, "");
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
export function buildGoogleUrl(pathname: string): string {
|
| 52 |
+
const base = getGoogleBaseUrl();
|
| 53 |
+
const cleanedPath = pathname.replace(/^\/+/g, "");
|
| 54 |
+
if (base.endsWith("/v1beta")) return `${base}/${cleanedPath}`;
|
| 55 |
+
return `${base}/v1beta/${cleanedPath}`;
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
function toModelPath(model: string): string {
|
| 59 |
+
const modelId = normalizeGoogleModelId(model);
|
| 60 |
+
return `models/${modelId}`;
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
function getHttpProxy(): string | null {
|
| 64 |
+
return (
|
| 65 |
+
process.env.https_proxy ||
|
| 66 |
+
process.env.HTTPS_PROXY ||
|
| 67 |
+
process.env.http_proxy ||
|
| 68 |
+
process.env.HTTP_PROXY ||
|
| 69 |
+
process.env.ALL_PROXY ||
|
| 70 |
+
null
|
| 71 |
+
);
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
async function postGoogleJsonViaCurl<T>(
|
| 75 |
+
url: string,
|
| 76 |
+
apiKey: string,
|
| 77 |
+
body: unknown,
|
| 78 |
+
): Promise<T> {
|
| 79 |
+
const proxy = getHttpProxy();
|
| 80 |
+
const bodyStr = JSON.stringify(body);
|
| 81 |
+
const args = [
|
| 82 |
+
"-s",
|
| 83 |
+
"--connect-timeout",
|
| 84 |
+
"30",
|
| 85 |
+
"--max-time",
|
| 86 |
+
"300",
|
| 87 |
+
...(proxy ? ["-x", proxy] : []),
|
| 88 |
+
url,
|
| 89 |
+
"-H",
|
| 90 |
+
"Content-Type: application/json",
|
| 91 |
+
"-H",
|
| 92 |
+
`x-goog-api-key: ${apiKey}`,
|
| 93 |
+
"-d",
|
| 94 |
+
"@-",
|
| 95 |
+
];
|
| 96 |
+
|
| 97 |
+
let result = "";
|
| 98 |
+
try {
|
| 99 |
+
result = execFileSync("curl", args, {
|
| 100 |
+
input: bodyStr,
|
| 101 |
+
encoding: "utf8",
|
| 102 |
+
maxBuffer: 100 * 1024 * 1024,
|
| 103 |
+
timeout: 310000,
|
| 104 |
+
});
|
| 105 |
+
} catch (error) {
|
| 106 |
+
const e = error as { message?: string; stderr?: string | Buffer };
|
| 107 |
+
const stderrText =
|
| 108 |
+
typeof e.stderr === "string"
|
| 109 |
+
? e.stderr
|
| 110 |
+
: e.stderr
|
| 111 |
+
? e.stderr.toString("utf8")
|
| 112 |
+
: "";
|
| 113 |
+
const details = stderrText.trim() || e.message || "curl request failed";
|
| 114 |
+
throw new Error(`Google API request failed via curl: ${details}`);
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
const parsed = JSON.parse(result) as any;
|
| 118 |
+
if (parsed.error) {
|
| 119 |
+
throw new Error(
|
| 120 |
+
`Google API error (${parsed.error.code}): ${parsed.error.message}`,
|
| 121 |
+
);
|
| 122 |
+
}
|
| 123 |
+
return parsed as T;
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
async function postGoogleJsonViaFetch<T>(
|
| 127 |
+
url: string,
|
| 128 |
+
apiKey: string,
|
| 129 |
+
body: unknown,
|
| 130 |
+
): Promise<T> {
|
| 131 |
+
const res = await fetch(url, {
|
| 132 |
+
method: "POST",
|
| 133 |
+
headers: {
|
| 134 |
+
"Content-Type": "application/json",
|
| 135 |
+
"x-goog-api-key": apiKey,
|
| 136 |
+
},
|
| 137 |
+
body: JSON.stringify(body),
|
| 138 |
+
});
|
| 139 |
+
|
| 140 |
+
if (!res.ok) {
|
| 141 |
+
const err = await res.text();
|
| 142 |
+
throw new Error(`Google API error (${res.status}): ${err}`);
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
return (await res.json()) as T;
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
async function postGoogleJson<T>(pathname: string, body: unknown): Promise<T> {
|
| 149 |
+
const apiKey = getGoogleApiKey();
|
| 150 |
+
if (!apiKey) throw new Error("GOOGLE_API_KEY or GEMINI_API_KEY is required");
|
| 151 |
+
|
| 152 |
+
const url = buildGoogleUrl(pathname);
|
| 153 |
+
const proxy = getHttpProxy();
|
| 154 |
+
|
| 155 |
+
// When an HTTP proxy is detected, use curl instead of fetch.
|
| 156 |
+
// Bun's fetch has a known issue where long-lived connections through
|
| 157 |
+
// HTTP proxies get their sockets closed unexpectedly, causing image
|
| 158 |
+
// generation requests to fail with "socket connection was closed
|
| 159 |
+
// unexpectedly". Using curl as the HTTP client works around this.
|
| 160 |
+
if (proxy) {
|
| 161 |
+
return postGoogleJsonViaCurl<T>(url, apiKey, body);
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
return postGoogleJsonViaFetch<T>(url, apiKey, body);
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
export function buildPromptWithAspect(
|
| 168 |
+
prompt: string,
|
| 169 |
+
ar: string | null,
|
| 170 |
+
quality: CliArgs["quality"],
|
| 171 |
+
): string {
|
| 172 |
+
let result = prompt;
|
| 173 |
+
if (ar) {
|
| 174 |
+
result += ` Aspect ratio: ${ar}.`;
|
| 175 |
+
}
|
| 176 |
+
if (quality === "2k") {
|
| 177 |
+
result += " High resolution 2048px.";
|
| 178 |
+
}
|
| 179 |
+
return result;
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
export function addAspectRatioToPrompt(prompt: string, ar: string | null): string {
|
| 183 |
+
if (!ar) return prompt;
|
| 184 |
+
return `${prompt} Aspect ratio: ${ar}.`;
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
async function readImageAsBase64(
|
| 188 |
+
p: string,
|
| 189 |
+
): Promise<{ data: string; mimeType: string }> {
|
| 190 |
+
const buf = await readFile(p);
|
| 191 |
+
const ext = path.extname(p).toLowerCase();
|
| 192 |
+
let mimeType = "image/png";
|
| 193 |
+
if (ext === ".jpg" || ext === ".jpeg") mimeType = "image/jpeg";
|
| 194 |
+
else if (ext === ".gif") mimeType = "image/gif";
|
| 195 |
+
else if (ext === ".webp") mimeType = "image/webp";
|
| 196 |
+
return { data: buf.toString("base64"), mimeType };
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
export function extractInlineImageData(response: {
|
| 200 |
+
candidates?: Array<{
|
| 201 |
+
content?: { parts?: Array<{ inlineData?: { data?: string } }> };
|
| 202 |
+
}>;
|
| 203 |
+
}): string | null {
|
| 204 |
+
for (const candidate of response.candidates || []) {
|
| 205 |
+
for (const part of candidate.content?.parts || []) {
|
| 206 |
+
const data = part.inlineData?.data;
|
| 207 |
+
if (typeof data === "string" && data.length > 0) return data;
|
| 208 |
+
}
|
| 209 |
+
}
|
| 210 |
+
return null;
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
export function extractPredictedImageData(response: {
|
| 214 |
+
predictions?: Array<any>;
|
| 215 |
+
generatedImages?: Array<any>;
|
| 216 |
+
}): string | null {
|
| 217 |
+
const candidates = [
|
| 218 |
+
...(response.predictions || []),
|
| 219 |
+
...(response.generatedImages || []),
|
| 220 |
+
];
|
| 221 |
+
for (const candidate of candidates) {
|
| 222 |
+
if (!candidate || typeof candidate !== "object") continue;
|
| 223 |
+
if (typeof candidate.imageBytes === "string") return candidate.imageBytes;
|
| 224 |
+
if (typeof candidate.bytesBase64Encoded === "string")
|
| 225 |
+
return candidate.bytesBase64Encoded;
|
| 226 |
+
if (typeof candidate.data === "string") return candidate.data;
|
| 227 |
+
const image = candidate.image;
|
| 228 |
+
if (image && typeof image === "object") {
|
| 229 |
+
if (typeof image.imageBytes === "string") return image.imageBytes;
|
| 230 |
+
if (typeof image.bytesBase64Encoded === "string")
|
| 231 |
+
return image.bytesBase64Encoded;
|
| 232 |
+
if (typeof image.data === "string") return image.data;
|
| 233 |
+
}
|
| 234 |
+
}
|
| 235 |
+
return null;
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
async function generateWithGemini(
|
| 239 |
+
prompt: string,
|
| 240 |
+
model: string,
|
| 241 |
+
args: CliArgs,
|
| 242 |
+
): Promise<Uint8Array> {
|
| 243 |
+
const promptWithAspect = addAspectRatioToPrompt(prompt, args.aspectRatio);
|
| 244 |
+
const parts: Array<{
|
| 245 |
+
text?: string;
|
| 246 |
+
inlineData?: { data: string; mimeType: string };
|
| 247 |
+
}> = [];
|
| 248 |
+
for (const refPath of args.referenceImages) {
|
| 249 |
+
const { data, mimeType } = await readImageAsBase64(refPath);
|
| 250 |
+
parts.push({ inlineData: { data, mimeType } });
|
| 251 |
+
}
|
| 252 |
+
parts.push({ text: promptWithAspect });
|
| 253 |
+
|
| 254 |
+
const imageConfig: { imageSize: "1K" | "2K" | "4K" } = {
|
| 255 |
+
imageSize: getGoogleImageSize(args),
|
| 256 |
+
};
|
| 257 |
+
|
| 258 |
+
console.log("Generating image with Gemini...", imageConfig);
|
| 259 |
+
const response = await postGoogleJson<{
|
| 260 |
+
candidates?: Array<{
|
| 261 |
+
content?: { parts?: Array<{ inlineData?: { data?: string } }> };
|
| 262 |
+
}>;
|
| 263 |
+
}>(`${toModelPath(model)}:generateContent`, {
|
| 264 |
+
contents: [
|
| 265 |
+
{
|
| 266 |
+
role: "user",
|
| 267 |
+
parts,
|
| 268 |
+
},
|
| 269 |
+
],
|
| 270 |
+
generationConfig: {
|
| 271 |
+
responseModalities: ["IMAGE"],
|
| 272 |
+
imageConfig,
|
| 273 |
+
},
|
| 274 |
+
});
|
| 275 |
+
console.log("Generation completed.");
|
| 276 |
+
|
| 277 |
+
const imageData = extractInlineImageData(response);
|
| 278 |
+
if (imageData) return Uint8Array.from(Buffer.from(imageData, "base64"));
|
| 279 |
+
|
| 280 |
+
throw new Error("No image in response");
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
async function generateWithImagen(
|
| 284 |
+
prompt: string,
|
| 285 |
+
model: string,
|
| 286 |
+
args: CliArgs,
|
| 287 |
+
): Promise<Uint8Array> {
|
| 288 |
+
const fullPrompt = buildPromptWithAspect(
|
| 289 |
+
prompt,
|
| 290 |
+
args.aspectRatio,
|
| 291 |
+
args.quality,
|
| 292 |
+
);
|
| 293 |
+
const imageSize = getGoogleImageSize(args);
|
| 294 |
+
if (imageSize === "4K") {
|
| 295 |
+
console.error(
|
| 296 |
+
"Warning: Imagen models do not support 4K imageSize, using 2K instead.",
|
| 297 |
+
);
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
const parameters: Record<string, unknown> = {
|
| 301 |
+
sampleCount: args.n,
|
| 302 |
+
};
|
| 303 |
+
if (args.aspectRatio) {
|
| 304 |
+
parameters.aspectRatio = args.aspectRatio;
|
| 305 |
+
}
|
| 306 |
+
if (imageSize === "1K" || imageSize === "2K") {
|
| 307 |
+
parameters.imageSize = imageSize;
|
| 308 |
+
} else {
|
| 309 |
+
parameters.imageSize = "2K";
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
const response = await postGoogleJson<{
|
| 313 |
+
predictions?: Array<any>;
|
| 314 |
+
generatedImages?: Array<any>;
|
| 315 |
+
}>(`${toModelPath(model)}:predict`, {
|
| 316 |
+
instances: [
|
| 317 |
+
{
|
| 318 |
+
prompt: fullPrompt,
|
| 319 |
+
},
|
| 320 |
+
],
|
| 321 |
+
parameters,
|
| 322 |
+
});
|
| 323 |
+
|
| 324 |
+
const imageData = extractPredictedImageData(response);
|
| 325 |
+
if (imageData) return Uint8Array.from(Buffer.from(imageData, "base64"));
|
| 326 |
+
|
| 327 |
+
throw new Error("No image in response");
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
+
export async function generateImage(
|
| 331 |
+
prompt: string,
|
| 332 |
+
model: string,
|
| 333 |
+
args: CliArgs,
|
| 334 |
+
): Promise<Uint8Array> {
|
| 335 |
+
if (isGoogleImagen(model)) {
|
| 336 |
+
if (args.referenceImages.length > 0) {
|
| 337 |
+
throw new Error(
|
| 338 |
+
"Reference images are not supported with Imagen models. Use a Gemini multimodal model such as gemini-3-pro-image, gemini-3.1-flash-image, gemini-3-pro-image-preview, gemini-3-flash-preview, or gemini-3.1-flash-image-preview.",
|
| 339 |
+
);
|
| 340 |
+
}
|
| 341 |
+
return generateWithImagen(prompt, model, args);
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
if (!isGoogleMultimodal(model) && args.referenceImages.length > 0) {
|
| 345 |
+
throw new Error(
|
| 346 |
+
"Reference images are only supported with Gemini multimodal models such as gemini-3-pro-image, gemini-3.1-flash-image, gemini-3-pro-image-preview, gemini-3-flash-preview, or gemini-3.1-flash-image-preview.",
|
| 347 |
+
);
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
return generateWithGemini(prompt, model, args);
|
| 351 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/providers/jimeng.test.ts
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from "node:assert/strict";
|
| 2 |
+
import test, { type TestContext } from "node:test";
|
| 3 |
+
|
| 4 |
+
import type { CliArgs } from "../types.ts";
|
| 5 |
+
import { generateImage } from "./jimeng.ts";
|
| 6 |
+
|
| 7 |
+
function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
| 8 |
+
return {
|
| 9 |
+
prompt: null,
|
| 10 |
+
promptFiles: [],
|
| 11 |
+
imagePath: null,
|
| 12 |
+
provider: null,
|
| 13 |
+
model: null,
|
| 14 |
+
aspectRatio: null,
|
| 15 |
+
size: null,
|
| 16 |
+
quality: null,
|
| 17 |
+
imageSize: null,
|
| 18 |
+
imageApiDialect: null,
|
| 19 |
+
referenceImages: [],
|
| 20 |
+
n: 1,
|
| 21 |
+
batchFile: null,
|
| 22 |
+
jobs: null,
|
| 23 |
+
json: false,
|
| 24 |
+
help: false,
|
| 25 |
+
...overrides,
|
| 26 |
+
};
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
function useEnv(
|
| 30 |
+
t: TestContext,
|
| 31 |
+
values: Record<string, string | null>,
|
| 32 |
+
): void {
|
| 33 |
+
const previous = new Map<string, string | undefined>();
|
| 34 |
+
for (const [key, value] of Object.entries(values)) {
|
| 35 |
+
previous.set(key, process.env[key]);
|
| 36 |
+
if (value == null) {
|
| 37 |
+
delete process.env[key];
|
| 38 |
+
} else {
|
| 39 |
+
process.env[key] = value;
|
| 40 |
+
}
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
t.after(() => {
|
| 44 |
+
for (const [key, value] of previous.entries()) {
|
| 45 |
+
if (value == null) {
|
| 46 |
+
delete process.env[key];
|
| 47 |
+
} else {
|
| 48 |
+
process.env[key] = value;
|
| 49 |
+
}
|
| 50 |
+
}
|
| 51 |
+
});
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
test("Jimeng submit request uses prompt field expected by current API", async (t) => {
|
| 55 |
+
useEnv(t, {
|
| 56 |
+
JIMENG_ACCESS_KEY_ID: "test-access-key",
|
| 57 |
+
JIMENG_SECRET_ACCESS_KEY: "test-secret-key",
|
| 58 |
+
JIMENG_BASE_URL: null,
|
| 59 |
+
JIMENG_REGION: null,
|
| 60 |
+
});
|
| 61 |
+
|
| 62 |
+
const originalFetch = globalThis.fetch;
|
| 63 |
+
t.after(() => {
|
| 64 |
+
globalThis.fetch = originalFetch;
|
| 65 |
+
});
|
| 66 |
+
|
| 67 |
+
const calls: Array<{
|
| 68 |
+
input: string;
|
| 69 |
+
init?: RequestInit;
|
| 70 |
+
}> = [];
|
| 71 |
+
|
| 72 |
+
globalThis.fetch = async (input, init) => {
|
| 73 |
+
calls.push({
|
| 74 |
+
input: String(input),
|
| 75 |
+
init,
|
| 76 |
+
});
|
| 77 |
+
|
| 78 |
+
if (calls.length === 1) {
|
| 79 |
+
return Response.json({
|
| 80 |
+
code: 10000,
|
| 81 |
+
data: {
|
| 82 |
+
task_id: "task-123",
|
| 83 |
+
},
|
| 84 |
+
});
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
return Response.json({
|
| 88 |
+
code: 10000,
|
| 89 |
+
data: {
|
| 90 |
+
status: "done",
|
| 91 |
+
binary_data_base64: [Buffer.from("jimeng-image").toString("base64")],
|
| 92 |
+
},
|
| 93 |
+
});
|
| 94 |
+
};
|
| 95 |
+
|
| 96 |
+
const image = await generateImage(
|
| 97 |
+
"A quiet bamboo forest",
|
| 98 |
+
"jimeng_t2i_v40",
|
| 99 |
+
makeArgs({ quality: "normal" }),
|
| 100 |
+
);
|
| 101 |
+
|
| 102 |
+
assert.equal(Buffer.from(image).toString("utf8"), "jimeng-image");
|
| 103 |
+
assert.equal(calls.length, 2);
|
| 104 |
+
assert.equal(
|
| 105 |
+
calls[0]?.input,
|
| 106 |
+
"https://visual.volcengineapi.com/?Action=CVSync2AsyncSubmitTask&Version=2022-08-31",
|
| 107 |
+
);
|
| 108 |
+
|
| 109 |
+
const submitBody = JSON.parse(String(calls[0]?.init?.body)) as Record<string, unknown>;
|
| 110 |
+
assert.equal(submitBody.req_key, "jimeng_t2i_v40");
|
| 111 |
+
assert.equal(submitBody.prompt, "A quiet bamboo forest");
|
| 112 |
+
assert.ok(!("prompt_text" in submitBody));
|
| 113 |
+
assert.equal(submitBody.width, 1024);
|
| 114 |
+
assert.equal(submitBody.height, 1024);
|
| 115 |
+
});
|
baoyu_skills/baoyu-imagine/scripts/providers/jimeng.ts
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { CliArgs } from "../types";
|
| 2 |
+
import * as crypto from "node:crypto";
|
| 3 |
+
|
| 4 |
+
type JimengSizePreset = "normal" | "2k" | "4k";
|
| 5 |
+
|
| 6 |
+
export function getDefaultModel(): string {
|
| 7 |
+
return process.env.JIMENG_IMAGE_MODEL || "jimeng_t2i_v40";
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
function getAccessKey(): string | null {
|
| 11 |
+
return process.env.JIMENG_ACCESS_KEY_ID || null;
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
function getSecretKey(): string | null {
|
| 15 |
+
return process.env.JIMENG_SECRET_ACCESS_KEY || null;
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
function getRegion(): string {
|
| 19 |
+
return process.env.JIMENG_REGION || "cn-north-1";
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
function getBaseUrl(): string {
|
| 23 |
+
return process.env.JIMENG_BASE_URL || "https://visual.volcengineapi.com";
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
function resolveEndpoint(query: Record<string, string>): {
|
| 27 |
+
url: string;
|
| 28 |
+
host: string;
|
| 29 |
+
canonicalUri: string;
|
| 30 |
+
} {
|
| 31 |
+
let baseUrl: URL;
|
| 32 |
+
try {
|
| 33 |
+
baseUrl = new URL(getBaseUrl());
|
| 34 |
+
} catch {
|
| 35 |
+
throw new Error(`Invalid JIMENG_BASE_URL: ${getBaseUrl()}`);
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
baseUrl.search = "";
|
| 39 |
+
for (const [key, value] of Object.entries(query).sort(([a], [b]) => a.localeCompare(b))) {
|
| 40 |
+
baseUrl.searchParams.set(key, value);
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
return {
|
| 44 |
+
url: baseUrl.toString(),
|
| 45 |
+
host: baseUrl.host,
|
| 46 |
+
canonicalUri: baseUrl.pathname || "/",
|
| 47 |
+
};
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
/**
|
| 51 |
+
* Volcengine HMAC-SHA256 signature generation
|
| 52 |
+
* Following the official documentation at:
|
| 53 |
+
* https://www.volcengine.com/docs/85621/1817045
|
| 54 |
+
*/
|
| 55 |
+
function generateSignature(
|
| 56 |
+
method: string,
|
| 57 |
+
query: Record<string, string>,
|
| 58 |
+
headers: Record<string, string>,
|
| 59 |
+
body: string,
|
| 60 |
+
accessKey: string,
|
| 61 |
+
secretKey: string,
|
| 62 |
+
region: string,
|
| 63 |
+
service: string,
|
| 64 |
+
canonicalUri: string
|
| 65 |
+
): string {
|
| 66 |
+
// 1. Create canonical request
|
| 67 |
+
// Sort query parameters alphabetically
|
| 68 |
+
const sortedQuery = Object.entries(query)
|
| 69 |
+
.sort(([a], [b]) => a.localeCompare(b))
|
| 70 |
+
.map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
|
| 71 |
+
.join("&");
|
| 72 |
+
|
| 73 |
+
// Sort headers alphabetically and create canonical headers
|
| 74 |
+
const sortedHeaders = Object.entries(headers)
|
| 75 |
+
.sort(([a], [b]) => a.localeCompare(b))
|
| 76 |
+
.map(([k, v]) => `${k.toLowerCase()}:${v.trim()}\n`)
|
| 77 |
+
.join("");
|
| 78 |
+
|
| 79 |
+
const signedHeaders = Object.keys(headers)
|
| 80 |
+
.sort()
|
| 81 |
+
.map(k => k.toLowerCase())
|
| 82 |
+
.join(";");
|
| 83 |
+
|
| 84 |
+
const hashedPayload = crypto.createHash("sha256").update(body, "utf8").digest("hex");
|
| 85 |
+
|
| 86 |
+
const canonicalRequest = [
|
| 87 |
+
method,
|
| 88 |
+
canonicalUri,
|
| 89 |
+
sortedQuery,
|
| 90 |
+
sortedHeaders,
|
| 91 |
+
signedHeaders,
|
| 92 |
+
hashedPayload,
|
| 93 |
+
].join("\n");
|
| 94 |
+
|
| 95 |
+
const hashedCanonicalRequest = crypto
|
| 96 |
+
.createHash("sha256")
|
| 97 |
+
.update(canonicalRequest, "utf8")
|
| 98 |
+
.digest("hex");
|
| 99 |
+
|
| 100 |
+
// 2. Create string to sign
|
| 101 |
+
const algorithm = "HMAC-SHA256";
|
| 102 |
+
const timestamp = headers["X-Date"] || headers["x-date"];
|
| 103 |
+
if (!timestamp) {
|
| 104 |
+
throw new Error("Jimeng signature generation requires an X-Date header.");
|
| 105 |
+
}
|
| 106 |
+
const dateStamp = timestamp.slice(0, 8);
|
| 107 |
+
|
| 108 |
+
const credentialScope = `${dateStamp}/${region}/${service}/request`;
|
| 109 |
+
|
| 110 |
+
const stringToSign = [
|
| 111 |
+
algorithm,
|
| 112 |
+
timestamp,
|
| 113 |
+
credentialScope,
|
| 114 |
+
hashedCanonicalRequest,
|
| 115 |
+
].join("\n");
|
| 116 |
+
|
| 117 |
+
// 3. Calculate signature
|
| 118 |
+
const kDate = crypto
|
| 119 |
+
.createHmac("sha256", secretKey)
|
| 120 |
+
.update(dateStamp)
|
| 121 |
+
.digest();
|
| 122 |
+
|
| 123 |
+
const kRegion = crypto.createHmac("sha256", kDate).update(region).digest();
|
| 124 |
+
const kService = crypto.createHmac("sha256", kRegion).update(service).digest();
|
| 125 |
+
const kSigning = crypto.createHmac("sha256", kService).update("request").digest();
|
| 126 |
+
|
| 127 |
+
const signature = crypto
|
| 128 |
+
.createHmac("sha256", kSigning)
|
| 129 |
+
.update(stringToSign)
|
| 130 |
+
.digest("hex");
|
| 131 |
+
|
| 132 |
+
// 4. Create authorization header
|
| 133 |
+
return `${algorithm} Credential=${accessKey}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`;
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
/**
|
| 137 |
+
* Parse aspect ratio string like "16:9", "1:1", "4:3" into width and height
|
| 138 |
+
*/
|
| 139 |
+
function parseAspectRatio(ar: string): { width: number; height: number } | null {
|
| 140 |
+
const match = ar.match(/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/);
|
| 141 |
+
if (!match) return null;
|
| 142 |
+
const w = parseFloat(match[1]!);
|
| 143 |
+
const h = parseFloat(match[2]!);
|
| 144 |
+
if (w <= 0 || h <= 0) return null;
|
| 145 |
+
return { width: w, height: h };
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
/**
|
| 149 |
+
* Supported size presets for different quality levels
|
| 150 |
+
* Based on Volcengine Jimeng documentation
|
| 151 |
+
*/
|
| 152 |
+
const SIZE_PRESETS: Record<string, Record<string, string>> = {
|
| 153 |
+
normal: {
|
| 154 |
+
"1:1": "1024x1024",
|
| 155 |
+
"4:3": "1360x1020",
|
| 156 |
+
"16:9": "1536x864",
|
| 157 |
+
"3:2": "1440x960",
|
| 158 |
+
"21:9": "1920x824",
|
| 159 |
+
},
|
| 160 |
+
"2k": {
|
| 161 |
+
"1:1": "2048x2048",
|
| 162 |
+
"4:3": "2304x1728",
|
| 163 |
+
"16:9": "2560x1440",
|
| 164 |
+
"3:2": "2496x1664",
|
| 165 |
+
"21:9": "3024x1296",
|
| 166 |
+
},
|
| 167 |
+
"4k": {
|
| 168 |
+
"1:1": "4096x4096",
|
| 169 |
+
"4:3": "4694x3520",
|
| 170 |
+
"16:9": "5404x3040",
|
| 171 |
+
"3:2": "4992x3328",
|
| 172 |
+
"21:9": "6198x2656",
|
| 173 |
+
},
|
| 174 |
+
};
|
| 175 |
+
|
| 176 |
+
function normalizeDimensions(value: string): string | null {
|
| 177 |
+
const match = value.trim().match(/^(\d+)\s*[xX*]\s*(\d+)$/);
|
| 178 |
+
if (!match) return null;
|
| 179 |
+
return `${match[1]}x${match[2]}`;
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
function getClosestPresetSize(ar: string | null, qualityLevel: JimengSizePreset): string {
|
| 183 |
+
const presets = SIZE_PRESETS[qualityLevel];
|
| 184 |
+
const defaultSize = presets["1:1"]!;
|
| 185 |
+
|
| 186 |
+
if (!ar) return defaultSize;
|
| 187 |
+
|
| 188 |
+
const parsed = parseAspectRatio(ar);
|
| 189 |
+
if (!parsed) return defaultSize;
|
| 190 |
+
|
| 191 |
+
const targetRatio = parsed.width / parsed.height;
|
| 192 |
+
let bestMatch = defaultSize;
|
| 193 |
+
let bestDiff = Infinity;
|
| 194 |
+
|
| 195 |
+
for (const [ratio, size] of Object.entries(presets)) {
|
| 196 |
+
const [w, h] = ratio.split(":").map(Number);
|
| 197 |
+
const presetRatio = w / h;
|
| 198 |
+
const diff = Math.abs(presetRatio - targetRatio);
|
| 199 |
+
if (diff < bestDiff) {
|
| 200 |
+
bestDiff = diff;
|
| 201 |
+
bestMatch = size;
|
| 202 |
+
}
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
return bestMatch;
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
function normalizeImageSizePreset(imageSize: string, ar: string | null): string | null {
|
| 209 |
+
const preset = imageSize.trim().toUpperCase();
|
| 210 |
+
if (preset === "1K") return getClosestPresetSize(ar, "normal");
|
| 211 |
+
if (preset === "2K") return getClosestPresetSize(ar, "2k");
|
| 212 |
+
if (preset === "4K") return getClosestPresetSize(ar, "4k");
|
| 213 |
+
return normalizeDimensions(imageSize);
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
function getImageSize(ar: string | null, quality: CliArgs["quality"], imageSize?: string | null): string {
|
| 217 |
+
if (imageSize) {
|
| 218 |
+
const normalizedSize = normalizeImageSizePreset(imageSize, ar);
|
| 219 |
+
if (normalizedSize) return normalizedSize;
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
// Default to 2K quality if not specified
|
| 223 |
+
const qualityLevel: JimengSizePreset = quality === "normal" ? "normal" : "2k";
|
| 224 |
+
return getClosestPresetSize(ar, qualityLevel);
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
/**
|
| 228 |
+
* Step 1: Submit async task to Volcengine Jimeng API
|
| 229 |
+
*/
|
| 230 |
+
async function submitTask(
|
| 231 |
+
prompt: string,
|
| 232 |
+
model: string,
|
| 233 |
+
size: string,
|
| 234 |
+
accessKey: string,
|
| 235 |
+
secretKey: string,
|
| 236 |
+
region: string
|
| 237 |
+
): Promise<string> {
|
| 238 |
+
// Query parameters for submit endpoint
|
| 239 |
+
const query = {
|
| 240 |
+
Action: "CVSync2AsyncSubmitTask",
|
| 241 |
+
Version: "2022-08-31",
|
| 242 |
+
};
|
| 243 |
+
const endpoint = resolveEndpoint(query);
|
| 244 |
+
|
| 245 |
+
// Request body - Jimeng API expects width/height as separate integers
|
| 246 |
+
const [width, height] = size.split("x").map(Number);
|
| 247 |
+
const bodyObj = {
|
| 248 |
+
req_key: model,
|
| 249 |
+
prompt,
|
| 250 |
+
// Use separate width and height parameters instead of size string
|
| 251 |
+
width: width,
|
| 252 |
+
height: height,
|
| 253 |
+
// Optional: seed for reproducibility
|
| 254 |
+
// seed: Math.floor(Math.random() * 999999),
|
| 255 |
+
};
|
| 256 |
+
|
| 257 |
+
const body = JSON.stringify(bodyObj);
|
| 258 |
+
|
| 259 |
+
// Headers
|
| 260 |
+
const timestampHeader = new Date().toISOString().replace(/[:\-]|\.\d{3}/g, "");
|
| 261 |
+
const headers = {
|
| 262 |
+
"Content-Type": "application/json",
|
| 263 |
+
"X-Date": timestampHeader,
|
| 264 |
+
"Host": endpoint.host,
|
| 265 |
+
};
|
| 266 |
+
|
| 267 |
+
// Generate signature
|
| 268 |
+
const authorization = generateSignature(
|
| 269 |
+
"POST",
|
| 270 |
+
query,
|
| 271 |
+
headers,
|
| 272 |
+
body,
|
| 273 |
+
accessKey,
|
| 274 |
+
secretKey,
|
| 275 |
+
region,
|
| 276 |
+
"cv",
|
| 277 |
+
endpoint.canonicalUri
|
| 278 |
+
);
|
| 279 |
+
|
| 280 |
+
console.error(`Submitting task to Jimeng (${model})...`, { width, height });
|
| 281 |
+
|
| 282 |
+
const res = await fetch(endpoint.url, {
|
| 283 |
+
method: "POST",
|
| 284 |
+
headers: {
|
| 285 |
+
...headers,
|
| 286 |
+
"Authorization": authorization,
|
| 287 |
+
},
|
| 288 |
+
body,
|
| 289 |
+
});
|
| 290 |
+
|
| 291 |
+
if (!res.ok) {
|
| 292 |
+
const err = await res.text();
|
| 293 |
+
throw new Error(`Jimeng API submit error (${res.status}): ${err}`);
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
const result = (await res.json()) as {
|
| 297 |
+
code?: number;
|
| 298 |
+
message?: string;
|
| 299 |
+
data?: {
|
| 300 |
+
task_id?: string;
|
| 301 |
+
};
|
| 302 |
+
};
|
| 303 |
+
|
| 304 |
+
// Volcengine API returns code 10000 for success
|
| 305 |
+
if (result.code !== 10000 || !result.data?.task_id) {
|
| 306 |
+
console.error("Submit response:", JSON.stringify(result, null, 2));
|
| 307 |
+
throw new Error(`Failed to submit task: ${result.message || "Unknown error"}`);
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
return result.data.task_id;
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
/**
|
| 314 |
+
* Step 2: Poll for task result
|
| 315 |
+
* Returns image data directly as Uint8Array
|
| 316 |
+
*/
|
| 317 |
+
async function pollForResult(
|
| 318 |
+
taskId: string,
|
| 319 |
+
model: string,
|
| 320 |
+
accessKey: string,
|
| 321 |
+
secretKey: string,
|
| 322 |
+
region: string
|
| 323 |
+
): Promise<Uint8Array> {
|
| 324 |
+
const maxAttempts = 60;
|
| 325 |
+
const pollIntervalMs = 2000;
|
| 326 |
+
|
| 327 |
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
| 328 |
+
// Query parameters for result endpoint
|
| 329 |
+
const query = {
|
| 330 |
+
Action: "CVSync2AsyncGetResult",
|
| 331 |
+
Version: "2022-08-31",
|
| 332 |
+
};
|
| 333 |
+
const endpoint = resolveEndpoint(query);
|
| 334 |
+
|
| 335 |
+
// Request body - include req_key and task_id
|
| 336 |
+
const bodyObj = {
|
| 337 |
+
req_key: model,
|
| 338 |
+
task_id: taskId,
|
| 339 |
+
};
|
| 340 |
+
|
| 341 |
+
const body = JSON.stringify(bodyObj);
|
| 342 |
+
|
| 343 |
+
// Headers
|
| 344 |
+
const timestampHeader = new Date().toISOString().replace(/[:\-]|\.\d{3}/g, "");
|
| 345 |
+
const headers = {
|
| 346 |
+
"Content-Type": "application/json",
|
| 347 |
+
"X-Date": timestampHeader,
|
| 348 |
+
"Host": endpoint.host,
|
| 349 |
+
};
|
| 350 |
+
|
| 351 |
+
// Generate signature
|
| 352 |
+
const authorization = generateSignature(
|
| 353 |
+
"POST",
|
| 354 |
+
query,
|
| 355 |
+
headers,
|
| 356 |
+
body,
|
| 357 |
+
accessKey,
|
| 358 |
+
secretKey,
|
| 359 |
+
region,
|
| 360 |
+
"cv",
|
| 361 |
+
endpoint.canonicalUri
|
| 362 |
+
);
|
| 363 |
+
|
| 364 |
+
const res = await fetch(endpoint.url, {
|
| 365 |
+
method: "POST",
|
| 366 |
+
headers: {
|
| 367 |
+
...headers,
|
| 368 |
+
"Authorization": authorization,
|
| 369 |
+
},
|
| 370 |
+
body,
|
| 371 |
+
});
|
| 372 |
+
|
| 373 |
+
if (!res.ok) {
|
| 374 |
+
const err = await res.text();
|
| 375 |
+
throw new Error(`Jimeng API poll error (${res.status}): ${err}`);
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
const result = (await res.json()) as {
|
| 379 |
+
code?: number;
|
| 380 |
+
message?: string;
|
| 381 |
+
data?: {
|
| 382 |
+
status?: string;
|
| 383 |
+
image_urls?: string[];
|
| 384 |
+
binary_data_base64?: string[];
|
| 385 |
+
};
|
| 386 |
+
};
|
| 387 |
+
|
| 388 |
+
// Volcengine API returns code 10000 for success
|
| 389 |
+
if (result.code === 10000 && result.data) {
|
| 390 |
+
const { status, image_urls, binary_data_base64 } = result.data;
|
| 391 |
+
|
| 392 |
+
// Check for base64 image data (preferred by Jimeng)
|
| 393 |
+
if (binary_data_base64 && binary_data_base64.length > 0) {
|
| 394 |
+
console.error("Image received as base64 data");
|
| 395 |
+
const base64Data = binary_data_base64[0]!;
|
| 396 |
+
// Convert base64 to Uint8Array
|
| 397 |
+
const binaryString = Buffer.from(base64Data, "base64").toString("binary");
|
| 398 |
+
const bytes = new Uint8Array(binaryString.length);
|
| 399 |
+
for (let i = 0; i < binaryString.length; i++) {
|
| 400 |
+
bytes[i] = binaryString.charCodeAt(i);
|
| 401 |
+
}
|
| 402 |
+
return bytes;
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
// Fallback to URL format
|
| 406 |
+
if (status === "done" && image_urls && image_urls.length > 0) {
|
| 407 |
+
// Download from URL
|
| 408 |
+
console.error(`Downloading image from ${image_urls[0]}...`);
|
| 409 |
+
const imgRes = await fetch(image_urls[0]!);
|
| 410 |
+
if (!imgRes.ok) {
|
| 411 |
+
throw new Error(`Failed to download image from ${image_urls[0]}`);
|
| 412 |
+
}
|
| 413 |
+
const buffer = await imgRes.arrayBuffer();
|
| 414 |
+
return new Uint8Array(buffer);
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
if (status === "in_queue" || status === "generating") {
|
| 418 |
+
console.error(`Task status: ${status} (${attempt + 1}/${maxAttempts})`);
|
| 419 |
+
await new Promise(resolve => setTimeout(resolve, pollIntervalMs));
|
| 420 |
+
continue;
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
if (status === "fail") {
|
| 424 |
+
throw new Error(`Jimeng task failed: ${result.message || "Generation failed"}`);
|
| 425 |
+
}
|
| 426 |
+
}
|
| 427 |
+
|
| 428 |
+
console.error("Poll response:", JSON.stringify(result, null, 2));
|
| 429 |
+
throw new Error(`Unexpected response during polling: ${result.message || "Unknown error"}`);
|
| 430 |
+
}
|
| 431 |
+
|
| 432 |
+
throw new Error("Task timeout: image generation took too long");
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
export async function generateImage(
|
| 436 |
+
prompt: string,
|
| 437 |
+
model: string,
|
| 438 |
+
args: CliArgs
|
| 439 |
+
): Promise<Uint8Array> {
|
| 440 |
+
if (args.referenceImages.length > 0) {
|
| 441 |
+
throw new Error(
|
| 442 |
+
"Jimeng does not support reference images. Use --provider google, openai, openrouter, or replicate."
|
| 443 |
+
);
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
const accessKey = getAccessKey();
|
| 447 |
+
const secretKey = getSecretKey();
|
| 448 |
+
const region = getRegion();
|
| 449 |
+
|
| 450 |
+
if (!accessKey || !secretKey) {
|
| 451 |
+
throw new Error(
|
| 452 |
+
"JIMENG_ACCESS_KEY_ID and JIMENG_SECRET_ACCESS_KEY are required. " +
|
| 453 |
+
"Get your credentials from https://console.volcengine.com/iam/keymanage"
|
| 454 |
+
);
|
| 455 |
+
}
|
| 456 |
+
|
| 457 |
+
const size = getImageSize(args.aspectRatio, args.quality, args.imageSize);
|
| 458 |
+
|
| 459 |
+
// Step 1: Submit task
|
| 460 |
+
const taskId = await submitTask(prompt, model, size, accessKey, secretKey, region);
|
| 461 |
+
|
| 462 |
+
// Step 2: Poll for result (returns image data directly)
|
| 463 |
+
const imageData = await pollForResult(taskId, model, accessKey, secretKey, region);
|
| 464 |
+
|
| 465 |
+
console.error("Image generation complete!");
|
| 466 |
+
return imageData;
|
| 467 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/providers/minimax.test.ts
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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1 |
+
import assert from "node:assert/strict";
|
| 2 |
+
import fs from "node:fs/promises";
|
| 3 |
+
import os from "node:os";
|
| 4 |
+
import path from "node:path";
|
| 5 |
+
import test, { type TestContext } from "node:test";
|
| 6 |
+
|
| 7 |
+
import type { CliArgs } from "../types.ts";
|
| 8 |
+
import {
|
| 9 |
+
buildMinimaxUrl,
|
| 10 |
+
buildRequestBody,
|
| 11 |
+
buildSubjectReference,
|
| 12 |
+
extractImageFromResponse,
|
| 13 |
+
parsePixelSize,
|
| 14 |
+
validateArgs,
|
| 15 |
+
} from "./minimax.ts";
|
| 16 |
+
|
| 17 |
+
function useEnv(
|
| 18 |
+
t: TestContext,
|
| 19 |
+
values: Record<string, string | null>,
|
| 20 |
+
): void {
|
| 21 |
+
const previous = new Map<string, string | undefined>();
|
| 22 |
+
for (const [key, value] of Object.entries(values)) {
|
| 23 |
+
previous.set(key, process.env[key]);
|
| 24 |
+
if (value == null) {
|
| 25 |
+
delete process.env[key];
|
| 26 |
+
} else {
|
| 27 |
+
process.env[key] = value;
|
| 28 |
+
}
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
t.after(() => {
|
| 32 |
+
for (const [key, value] of previous.entries()) {
|
| 33 |
+
if (value == null) {
|
| 34 |
+
delete process.env[key];
|
| 35 |
+
} else {
|
| 36 |
+
process.env[key] = value;
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
});
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
| 43 |
+
return {
|
| 44 |
+
prompt: null,
|
| 45 |
+
promptFiles: [],
|
| 46 |
+
imagePath: null,
|
| 47 |
+
provider: null,
|
| 48 |
+
model: null,
|
| 49 |
+
aspectRatio: null,
|
| 50 |
+
size: null,
|
| 51 |
+
quality: null,
|
| 52 |
+
imageSize: null,
|
| 53 |
+
imageApiDialect: null,
|
| 54 |
+
referenceImages: [],
|
| 55 |
+
n: 1,
|
| 56 |
+
batchFile: null,
|
| 57 |
+
jobs: null,
|
| 58 |
+
json: false,
|
| 59 |
+
help: false,
|
| 60 |
+
...overrides,
|
| 61 |
+
};
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
test("MiniMax URL builder uses documented default and normalizes /v1 suffixes", (t) => {
|
| 65 |
+
useEnv(t, { MINIMAX_BASE_URL: null });
|
| 66 |
+
assert.equal(buildMinimaxUrl(), "https://api.minimaxi.com/v1/image_generation");
|
| 67 |
+
|
| 68 |
+
process.env.MINIMAX_BASE_URL = "https://api.minimax.io";
|
| 69 |
+
assert.equal(buildMinimaxUrl(), "https://api.minimax.io/v1/image_generation");
|
| 70 |
+
|
| 71 |
+
process.env.MINIMAX_BASE_URL = "https://proxy.example.com/custom/v1/";
|
| 72 |
+
assert.equal(buildMinimaxUrl(), "https://proxy.example.com/custom/v1/image_generation");
|
| 73 |
+
});
|
| 74 |
+
|
| 75 |
+
test("MiniMax size parsing and validation follow documented constraints", () => {
|
| 76 |
+
assert.deepEqual(parsePixelSize("1536x1024"), { width: 1536, height: 1024 });
|
| 77 |
+
assert.deepEqual(parsePixelSize("1536*1024"), { width: 1536, height: 1024 });
|
| 78 |
+
assert.equal(parsePixelSize("wide"), null);
|
| 79 |
+
|
| 80 |
+
validateArgs("image-01", makeArgs({ size: "1536x1024", n: 9 }));
|
| 81 |
+
|
| 82 |
+
assert.throws(
|
| 83 |
+
() => validateArgs("image-01-live", makeArgs({ size: "1536x1024" })),
|
| 84 |
+
/only supported with model image-01/,
|
| 85 |
+
);
|
| 86 |
+
assert.throws(
|
| 87 |
+
() => validateArgs("image-01", makeArgs({ size: "1537x1024" })),
|
| 88 |
+
/divisible by 8/,
|
| 89 |
+
);
|
| 90 |
+
assert.throws(
|
| 91 |
+
() => validateArgs("image-01", makeArgs({ aspectRatio: "2.35:1" })),
|
| 92 |
+
/aspect_ratio must be one of/,
|
| 93 |
+
);
|
| 94 |
+
assert.throws(
|
| 95 |
+
() => validateArgs("image-01", makeArgs({ n: 10 })),
|
| 96 |
+
/at most 9 images/,
|
| 97 |
+
);
|
| 98 |
+
});
|
| 99 |
+
|
| 100 |
+
test("MiniMax request body maps aspect ratio, size, n, and subject references", async (t) => {
|
| 101 |
+
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "minimax-test-"));
|
| 102 |
+
t.after(() => fs.rm(dir, { recursive: true, force: true }));
|
| 103 |
+
|
| 104 |
+
const refPath = path.join(dir, "portrait.png");
|
| 105 |
+
await fs.writeFile(refPath, Buffer.from("portrait"));
|
| 106 |
+
|
| 107 |
+
const ratioBody = await buildRequestBody(
|
| 108 |
+
"A portrait by the window",
|
| 109 |
+
"image-01",
|
| 110 |
+
makeArgs({ aspectRatio: "16:9", n: 2, referenceImages: [refPath] }),
|
| 111 |
+
);
|
| 112 |
+
assert.equal(ratioBody.aspect_ratio, "16:9");
|
| 113 |
+
assert.equal(ratioBody.n, 2);
|
| 114 |
+
assert.equal(ratioBody.response_format, "base64");
|
| 115 |
+
assert.match(ratioBody.subject_reference?.[0]?.image_file || "", /^data:image\/png;base64,/);
|
| 116 |
+
|
| 117 |
+
const sizeBody = await buildRequestBody(
|
| 118 |
+
"A portrait by the window",
|
| 119 |
+
"image-01",
|
| 120 |
+
makeArgs({ size: "1536x1024" }),
|
| 121 |
+
);
|
| 122 |
+
assert.equal(sizeBody.width, 1536);
|
| 123 |
+
assert.equal(sizeBody.height, 1024);
|
| 124 |
+
assert.equal(sizeBody.aspect_ratio, undefined);
|
| 125 |
+
});
|
| 126 |
+
|
| 127 |
+
test("MiniMax subject references require supported file types", async (t) => {
|
| 128 |
+
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "minimax-ref-"));
|
| 129 |
+
t.after(() => fs.rm(dir, { recursive: true, force: true }));
|
| 130 |
+
|
| 131 |
+
const good = path.join(dir, "portrait.jpg");
|
| 132 |
+
const bad = path.join(dir, "portrait.webp");
|
| 133 |
+
await fs.writeFile(good, Buffer.from("portrait"));
|
| 134 |
+
await fs.writeFile(bad, Buffer.from("portrait"));
|
| 135 |
+
|
| 136 |
+
const subjectReference = await buildSubjectReference([good]);
|
| 137 |
+
assert.equal(subjectReference?.[0]?.type, "character");
|
| 138 |
+
|
| 139 |
+
await assert.rejects(
|
| 140 |
+
() => buildSubjectReference([bad]),
|
| 141 |
+
/only supports JPG, JPEG, or PNG/,
|
| 142 |
+
);
|
| 143 |
+
});
|
| 144 |
+
|
| 145 |
+
test("MiniMax response extraction supports base64 and URL payloads", async (t) => {
|
| 146 |
+
const originalFetch = globalThis.fetch;
|
| 147 |
+
t.after(() => {
|
| 148 |
+
globalThis.fetch = originalFetch;
|
| 149 |
+
});
|
| 150 |
+
|
| 151 |
+
const fromBase64 = await extractImageFromResponse({
|
| 152 |
+
data: {
|
| 153 |
+
image_base64: [Buffer.from("hello").toString("base64")],
|
| 154 |
+
},
|
| 155 |
+
});
|
| 156 |
+
assert.equal(Buffer.from(fromBase64).toString("utf8"), "hello");
|
| 157 |
+
|
| 158 |
+
globalThis.fetch = async () =>
|
| 159 |
+
new Response(Uint8Array.from([1, 2, 3]), {
|
| 160 |
+
status: 200,
|
| 161 |
+
headers: { "Content-Type": "image/jpeg" },
|
| 162 |
+
});
|
| 163 |
+
|
| 164 |
+
const fromUrl = await extractImageFromResponse({
|
| 165 |
+
data: {
|
| 166 |
+
image_urls: ["https://example.com/output.jpg"],
|
| 167 |
+
},
|
| 168 |
+
});
|
| 169 |
+
assert.deepEqual([...fromUrl], [1, 2, 3]);
|
| 170 |
+
|
| 171 |
+
await assert.rejects(
|
| 172 |
+
() => extractImageFromResponse({ base_resp: { status_code: 1001, status_msg: "blocked" } }),
|
| 173 |
+
/blocked/,
|
| 174 |
+
);
|
| 175 |
+
});
|
baoyu_skills/baoyu-imagine/scripts/providers/minimax.ts
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import path from "node:path";
|
| 2 |
+
import { readFile } from "node:fs/promises";
|
| 3 |
+
|
| 4 |
+
import type { CliArgs } from "../types";
|
| 5 |
+
|
| 6 |
+
const DEFAULT_MODEL = "image-01";
|
| 7 |
+
const MAX_REFERENCE_IMAGE_BYTES = 10 * 1024 * 1024;
|
| 8 |
+
const SUPPORTED_ASPECT_RATIOS = new Set(["1:1", "16:9", "4:3", "3:2", "2:3", "3:4", "9:16", "21:9"]);
|
| 9 |
+
|
| 10 |
+
type MinimaxSubjectReference = {
|
| 11 |
+
type: "character";
|
| 12 |
+
image_file: string;
|
| 13 |
+
};
|
| 14 |
+
|
| 15 |
+
type MinimaxRequestBody = {
|
| 16 |
+
model: string;
|
| 17 |
+
prompt: string;
|
| 18 |
+
response_format: "base64";
|
| 19 |
+
aspect_ratio?: string;
|
| 20 |
+
width?: number;
|
| 21 |
+
height?: number;
|
| 22 |
+
n?: number;
|
| 23 |
+
subject_reference?: MinimaxSubjectReference[];
|
| 24 |
+
};
|
| 25 |
+
|
| 26 |
+
type MinimaxResponse = {
|
| 27 |
+
id?: string;
|
| 28 |
+
data?: {
|
| 29 |
+
image_urls?: string[];
|
| 30 |
+
image_base64?: string[];
|
| 31 |
+
};
|
| 32 |
+
base_resp?: {
|
| 33 |
+
status_code?: number;
|
| 34 |
+
status_msg?: string;
|
| 35 |
+
};
|
| 36 |
+
};
|
| 37 |
+
|
| 38 |
+
export function getDefaultModel(): string {
|
| 39 |
+
return process.env.MINIMAX_IMAGE_MODEL || DEFAULT_MODEL;
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
function getApiKey(): string | null {
|
| 43 |
+
return process.env.MINIMAX_API_KEY || null;
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
export function buildMinimaxUrl(): string {
|
| 47 |
+
const base = (process.env.MINIMAX_BASE_URL || "https://api.minimaxi.com").replace(/\/+$/g, "");
|
| 48 |
+
return base.endsWith("/v1") ? `${base}/image_generation` : `${base}/v1/image_generation`;
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
function getMimeType(filename: string): "image/jpeg" | "image/png" {
|
| 52 |
+
const ext = path.extname(filename).toLowerCase();
|
| 53 |
+
if (ext === ".jpg" || ext === ".jpeg") return "image/jpeg";
|
| 54 |
+
if (ext === ".png") return "image/png";
|
| 55 |
+
throw new Error(
|
| 56 |
+
`MiniMax subject_reference only supports JPG, JPEG, or PNG files: ${filename}`
|
| 57 |
+
);
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
export function parsePixelSize(size: string): { width: number; height: number } | null {
|
| 61 |
+
const match = size.trim().match(/^(\d+)\s*[xX*]\s*(\d+)$/);
|
| 62 |
+
if (!match) return null;
|
| 63 |
+
|
| 64 |
+
const width = parseInt(match[1]!, 10);
|
| 65 |
+
const height = parseInt(match[2]!, 10);
|
| 66 |
+
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
|
| 67 |
+
return null;
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
return { width, height };
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
function validatePixelSize(width: number, height: number): void {
|
| 74 |
+
if (width < 512 || width > 2048 || height < 512 || height > 2048) {
|
| 75 |
+
throw new Error("MiniMax custom size must keep width and height between 512 and 2048.");
|
| 76 |
+
}
|
| 77 |
+
if (width % 8 !== 0 || height % 8 !== 0) {
|
| 78 |
+
throw new Error("MiniMax custom size requires width and height divisible by 8.");
|
| 79 |
+
}
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
export function validateArgs(model: string, args: CliArgs): void {
|
| 83 |
+
if (args.n > 9) {
|
| 84 |
+
throw new Error("MiniMax supports at most 9 images per request.");
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
if (args.aspectRatio && !SUPPORTED_ASPECT_RATIOS.has(args.aspectRatio)) {
|
| 88 |
+
throw new Error(
|
| 89 |
+
`MiniMax aspect_ratio must be one of: ${Array.from(SUPPORTED_ASPECT_RATIOS).join(", ")}.`
|
| 90 |
+
);
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
if (args.size && !args.aspectRatio) {
|
| 94 |
+
if (model !== "image-01") {
|
| 95 |
+
throw new Error("MiniMax custom --size is only supported with model image-01. Use --model image-01 or pass --ar instead.");
|
| 96 |
+
}
|
| 97 |
+
const parsed = parsePixelSize(args.size);
|
| 98 |
+
if (!parsed) {
|
| 99 |
+
throw new Error("MiniMax --size must be in WxH format, for example 1536x1024.");
|
| 100 |
+
}
|
| 101 |
+
validatePixelSize(parsed.width, parsed.height);
|
| 102 |
+
}
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
export async function buildSubjectReference(
|
| 106 |
+
referenceImages: string[],
|
| 107 |
+
): Promise<MinimaxSubjectReference[] | undefined> {
|
| 108 |
+
if (referenceImages.length === 0) return undefined;
|
| 109 |
+
|
| 110 |
+
const subjectReference: MinimaxSubjectReference[] = [];
|
| 111 |
+
for (const refPath of referenceImages) {
|
| 112 |
+
const bytes = await readFile(refPath);
|
| 113 |
+
if (bytes.length > MAX_REFERENCE_IMAGE_BYTES) {
|
| 114 |
+
throw new Error(`MiniMax subject_reference images must be smaller than 10MB: ${refPath}`);
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
subjectReference.push({
|
| 118 |
+
type: "character",
|
| 119 |
+
image_file: `data:${getMimeType(refPath)};base64,${bytes.toString("base64")}`,
|
| 120 |
+
});
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
return subjectReference;
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
export async function buildRequestBody(
|
| 127 |
+
prompt: string,
|
| 128 |
+
model: string,
|
| 129 |
+
args: CliArgs,
|
| 130 |
+
): Promise<MinimaxRequestBody> {
|
| 131 |
+
validateArgs(model, args);
|
| 132 |
+
|
| 133 |
+
const body: MinimaxRequestBody = {
|
| 134 |
+
model,
|
| 135 |
+
prompt,
|
| 136 |
+
response_format: "base64",
|
| 137 |
+
};
|
| 138 |
+
|
| 139 |
+
if (args.aspectRatio) {
|
| 140 |
+
body.aspect_ratio = args.aspectRatio;
|
| 141 |
+
} else if (args.size) {
|
| 142 |
+
const parsed = parsePixelSize(args.size);
|
| 143 |
+
if (!parsed) {
|
| 144 |
+
throw new Error("MiniMax --size must be in WxH format, for example 1536x1024.");
|
| 145 |
+
}
|
| 146 |
+
body.width = parsed.width;
|
| 147 |
+
body.height = parsed.height;
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
if (args.n > 1) {
|
| 151 |
+
body.n = args.n;
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
const subjectReference = await buildSubjectReference(args.referenceImages);
|
| 155 |
+
if (subjectReference) {
|
| 156 |
+
body.subject_reference = subjectReference;
|
| 157 |
+
}
|
| 158 |
+
|
| 159 |
+
return body;
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
async function downloadImage(url: string): Promise<Uint8Array> {
|
| 163 |
+
const response = await fetch(url);
|
| 164 |
+
if (!response.ok) {
|
| 165 |
+
throw new Error(`Failed to download image from MiniMax: ${response.status}`);
|
| 166 |
+
}
|
| 167 |
+
return new Uint8Array(await response.arrayBuffer());
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
export async function extractImageFromResponse(result: MinimaxResponse): Promise<Uint8Array> {
|
| 171 |
+
const baseResp = result.base_resp;
|
| 172 |
+
if (baseResp && baseResp.status_code !== undefined && baseResp.status_code !== 0) {
|
| 173 |
+
throw new Error(baseResp.status_msg || `MiniMax API returned status_code=${baseResp.status_code}`);
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
const base64Image = result.data?.image_base64?.[0];
|
| 177 |
+
if (base64Image) {
|
| 178 |
+
return Uint8Array.from(Buffer.from(base64Image, "base64"));
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
const url = result.data?.image_urls?.[0];
|
| 182 |
+
if (url) {
|
| 183 |
+
return downloadImage(url);
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
throw new Error("No image data in MiniMax response");
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
export function getDefaultOutputExtension(): ".jpg" {
|
| 190 |
+
return ".jpg";
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
export async function generateImage(
|
| 194 |
+
prompt: string,
|
| 195 |
+
model: string,
|
| 196 |
+
args: CliArgs
|
| 197 |
+
): Promise<Uint8Array> {
|
| 198 |
+
const apiKey = getApiKey();
|
| 199 |
+
if (!apiKey) {
|
| 200 |
+
throw new Error("MINIMAX_API_KEY is required. Get one from https://platform.minimaxi.com/");
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
const body = await buildRequestBody(prompt, model, args);
|
| 204 |
+
const response = await fetch(buildMinimaxUrl(), {
|
| 205 |
+
method: "POST",
|
| 206 |
+
headers: {
|
| 207 |
+
"Content-Type": "application/json",
|
| 208 |
+
Authorization: `Bearer ${apiKey}`,
|
| 209 |
+
},
|
| 210 |
+
body: JSON.stringify(body),
|
| 211 |
+
});
|
| 212 |
+
|
| 213 |
+
if (!response.ok) {
|
| 214 |
+
const err = await response.text();
|
| 215 |
+
throw new Error(`MiniMax API error (${response.status}): ${err}`);
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
const result = (await response.json()) as MinimaxResponse;
|
| 219 |
+
return extractImageFromResponse(result);
|
| 220 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/providers/openai.test.ts
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 2 |
+
import test from "node:test";
|
| 3 |
+
|
| 4 |
+
import type { CliArgs } from "../types.ts";
|
| 5 |
+
import {
|
| 6 |
+
buildOpenAIGenerationsBody,
|
| 7 |
+
extractImageFromResponse,
|
| 8 |
+
getDefaultModel,
|
| 9 |
+
getOpenAIAspectRatio,
|
| 10 |
+
getOpenAIImageApiDialect,
|
| 11 |
+
getOpenAIResolution,
|
| 12 |
+
getMimeType,
|
| 13 |
+
getOpenAISize,
|
| 14 |
+
getOrientationFromAspectRatio,
|
| 15 |
+
inferAspectRatioFromSize,
|
| 16 |
+
inferResolutionFromSize,
|
| 17 |
+
parseAspectRatio,
|
| 18 |
+
validateArgs,
|
| 19 |
+
} from "./openai.ts";
|
| 20 |
+
|
| 21 |
+
function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
| 22 |
+
return {
|
| 23 |
+
prompt: null,
|
| 24 |
+
promptFiles: [],
|
| 25 |
+
imagePath: null,
|
| 26 |
+
provider: null,
|
| 27 |
+
model: null,
|
| 28 |
+
aspectRatio: null,
|
| 29 |
+
size: null,
|
| 30 |
+
quality: "2k",
|
| 31 |
+
imageSize: null,
|
| 32 |
+
imageApiDialect: null,
|
| 33 |
+
referenceImages: [],
|
| 34 |
+
n: 1,
|
| 35 |
+
batchFile: null,
|
| 36 |
+
jobs: null,
|
| 37 |
+
json: false,
|
| 38 |
+
help: false,
|
| 39 |
+
...overrides,
|
| 40 |
+
};
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
test("OpenAI aspect-ratio parsing and size selection match model families", () => {
|
| 44 |
+
assert.equal(getDefaultModel(), "gpt-image-2");
|
| 45 |
+
assert.deepEqual(parseAspectRatio("16:9"), { width: 16, height: 9 });
|
| 46 |
+
assert.equal(parseAspectRatio("wide"), null);
|
| 47 |
+
assert.equal(parseAspectRatio("0:1"), null);
|
| 48 |
+
|
| 49 |
+
assert.equal(getOpenAISize("dall-e-3", "16:9", "2k"), "1792x1024");
|
| 50 |
+
assert.equal(getOpenAISize("dall-e-3", "9:16", "normal"), "1024x1792");
|
| 51 |
+
assert.equal(getOpenAISize("dall-e-2", "16:9", "2k"), "1024x1024");
|
| 52 |
+
assert.equal(getOpenAISize("gpt-image-1.5", "16:9", "2k"), "1536x1024");
|
| 53 |
+
assert.equal(getOpenAISize("gpt-image-1.5", "4:3", "2k"), "1024x1024");
|
| 54 |
+
assert.equal(getOpenAISize("gpt-image-2", "16:9", "2k"), "2048x1152");
|
| 55 |
+
assert.equal(getOpenAISize("gpt-image-2", "9:16", "2k"), "1152x2048");
|
| 56 |
+
assert.equal(getOpenAISize("gpt-image-2", "4:3", "2k"), "2048x1536");
|
| 57 |
+
assert.equal(getOpenAISize("gpt-image-2", "2.35:1", "normal"), "1248x528");
|
| 58 |
+
assert.equal(inferAspectRatioFromSize("1536x1024"), "3:2");
|
| 59 |
+
assert.equal(inferResolutionFromSize("1536x1024"), "2K");
|
| 60 |
+
assert.equal(getOpenAIAspectRatio({ aspectRatio: null, size: "2048x1152" }), "16:9");
|
| 61 |
+
assert.equal(getOpenAIResolution({ imageSize: null, size: "2048x1152", quality: "normal" }), "2K");
|
| 62 |
+
assert.equal(getOrientationFromAspectRatio("16:9"), "landscape");
|
| 63 |
+
assert.equal(getOrientationFromAspectRatio("9:16"), "portrait");
|
| 64 |
+
assert.equal(getOrientationFromAspectRatio("1:1"), null);
|
| 65 |
+
assert.equal(getOpenAIImageApiDialect({ imageApiDialect: null }), "openai-native");
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
test("OpenAI generations body switches between native and ratio-metadata dialects", () => {
|
| 69 |
+
assert.deepEqual(
|
| 70 |
+
buildOpenAIGenerationsBody("Draw a skyline", "gpt-image-2", {
|
| 71 |
+
aspectRatio: "16:9",
|
| 72 |
+
size: null,
|
| 73 |
+
quality: "2k",
|
| 74 |
+
imageSize: null,
|
| 75 |
+
imageApiDialect: null,
|
| 76 |
+
}),
|
| 77 |
+
{
|
| 78 |
+
model: "gpt-image-2",
|
| 79 |
+
prompt: "Draw a skyline",
|
| 80 |
+
size: "2048x1152",
|
| 81 |
+
quality: "high",
|
| 82 |
+
},
|
| 83 |
+
);
|
| 84 |
+
|
| 85 |
+
assert.deepEqual(
|
| 86 |
+
buildOpenAIGenerationsBody("Draw a skyline", "gemini-3-pro-image-preview", {
|
| 87 |
+
aspectRatio: "16:9",
|
| 88 |
+
size: null,
|
| 89 |
+
quality: "2k",
|
| 90 |
+
imageSize: null,
|
| 91 |
+
imageApiDialect: "ratio-metadata",
|
| 92 |
+
}),
|
| 93 |
+
{
|
| 94 |
+
model: "gemini-3-pro-image-preview",
|
| 95 |
+
prompt: "Draw a skyline",
|
| 96 |
+
size: "16:9",
|
| 97 |
+
metadata: {
|
| 98 |
+
resolution: "2K",
|
| 99 |
+
orientation: "landscape",
|
| 100 |
+
},
|
| 101 |
+
},
|
| 102 |
+
);
|
| 103 |
+
|
| 104 |
+
assert.deepEqual(
|
| 105 |
+
buildOpenAIGenerationsBody("Draw a portrait", "gemini-3-pro-image-preview", {
|
| 106 |
+
aspectRatio: null,
|
| 107 |
+
size: "1152x2048",
|
| 108 |
+
quality: "normal",
|
| 109 |
+
imageSize: null,
|
| 110 |
+
imageApiDialect: "ratio-metadata",
|
| 111 |
+
}),
|
| 112 |
+
{
|
| 113 |
+
model: "gemini-3-pro-image-preview",
|
| 114 |
+
prompt: "Draw a portrait",
|
| 115 |
+
size: "9:16",
|
| 116 |
+
metadata: {
|
| 117 |
+
resolution: "2K",
|
| 118 |
+
orientation: "portrait",
|
| 119 |
+
},
|
| 120 |
+
},
|
| 121 |
+
);
|
| 122 |
+
});
|
| 123 |
+
|
| 124 |
+
test("OpenAI validates gpt-image-2 custom size constraints", () => {
|
| 125 |
+
assert.doesNotThrow(() =>
|
| 126 |
+
validateArgs("gpt-image-2", makeArgs({ size: "3840x2160" })),
|
| 127 |
+
);
|
| 128 |
+
assert.doesNotThrow(() =>
|
| 129 |
+
validateArgs("gpt-image-2-2026-04-21", makeArgs({ aspectRatio: "2.35:1" })),
|
| 130 |
+
);
|
| 131 |
+
|
| 132 |
+
assert.throws(
|
| 133 |
+
() => validateArgs("gpt-image-2", makeArgs({ size: "1024x576" })),
|
| 134 |
+
/total pixels/,
|
| 135 |
+
);
|
| 136 |
+
assert.throws(
|
| 137 |
+
() => validateArgs("gpt-image-2", makeArgs({ size: "1025x1024" })),
|
| 138 |
+
/multiples of 16px/,
|
| 139 |
+
);
|
| 140 |
+
assert.throws(
|
| 141 |
+
() => validateArgs("gpt-image-2", makeArgs({ aspectRatio: "4:1" })),
|
| 142 |
+
/must not exceed 3:1/,
|
| 143 |
+
);
|
| 144 |
+
});
|
| 145 |
+
|
| 146 |
+
test("OpenAI mime-type detection covers supported reference image extensions", () => {
|
| 147 |
+
assert.equal(getMimeType("frame.png"), "image/png");
|
| 148 |
+
assert.equal(getMimeType("frame.jpg"), "image/jpeg");
|
| 149 |
+
assert.equal(getMimeType("frame.webp"), "image/webp");
|
| 150 |
+
assert.equal(getMimeType("frame.gif"), "image/gif");
|
| 151 |
+
});
|
| 152 |
+
|
| 153 |
+
test("OpenAI response extraction supports base64 and URL download flows", async (t) => {
|
| 154 |
+
const originalFetch = globalThis.fetch;
|
| 155 |
+
t.after(() => {
|
| 156 |
+
globalThis.fetch = originalFetch;
|
| 157 |
+
});
|
| 158 |
+
|
| 159 |
+
const fromBase64 = await extractImageFromResponse({
|
| 160 |
+
data: [{ b64_json: Buffer.from("hello").toString("base64") }],
|
| 161 |
+
});
|
| 162 |
+
assert.equal(Buffer.from(fromBase64).toString("utf8"), "hello");
|
| 163 |
+
|
| 164 |
+
globalThis.fetch = async () =>
|
| 165 |
+
new Response(Uint8Array.from([1, 2, 3]), {
|
| 166 |
+
status: 200,
|
| 167 |
+
headers: { "Content-Type": "application/octet-stream" },
|
| 168 |
+
});
|
| 169 |
+
|
| 170 |
+
const fromUrl = await extractImageFromResponse({
|
| 171 |
+
data: [{ url: "https://example.com/image.png" }],
|
| 172 |
+
});
|
| 173 |
+
assert.deepEqual([...fromUrl], [1, 2, 3]);
|
| 174 |
+
|
| 175 |
+
await assert.rejects(
|
| 176 |
+
() => extractImageFromResponse({ data: [{}] }),
|
| 177 |
+
/No image in response/,
|
| 178 |
+
);
|
| 179 |
+
});
|
baoyu_skills/baoyu-imagine/scripts/providers/openai.ts
ADDED
|
@@ -0,0 +1,444 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import path from "node:path";
|
| 2 |
+
import { readFile } from "node:fs/promises";
|
| 3 |
+
import type { CliArgs, OpenAIImageApiDialect } from "../types";
|
| 4 |
+
|
| 5 |
+
export function getDefaultModel(): string {
|
| 6 |
+
return process.env.OPENAI_IMAGE_MODEL || "gpt-image-2";
|
| 7 |
+
}
|
| 8 |
+
|
| 9 |
+
type OpenAIImageResponse = { data: Array<{ url?: string; b64_json?: string }> };
|
| 10 |
+
|
| 11 |
+
export function parseAspectRatio(ar: string): { width: number; height: number } | null {
|
| 12 |
+
const match = ar.match(/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/);
|
| 13 |
+
if (!match) return null;
|
| 14 |
+
const w = parseFloat(match[1]!);
|
| 15 |
+
const h = parseFloat(match[2]!);
|
| 16 |
+
if (w <= 0 || h <= 0) return null;
|
| 17 |
+
return { width: w, height: h };
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
type SizeMapping = {
|
| 21 |
+
square: string;
|
| 22 |
+
landscape: string;
|
| 23 |
+
portrait: string;
|
| 24 |
+
};
|
| 25 |
+
|
| 26 |
+
type OpenAIGenerationsBody = Record<string, unknown>;
|
| 27 |
+
|
| 28 |
+
function isGptImageModel(model: string): boolean {
|
| 29 |
+
return model.includes("gpt-image");
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
function isGptImage2Model(model: string): boolean {
|
| 33 |
+
return model.includes("gpt-image-2");
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
function roundToMultiple(value: number, multiple: number): number {
|
| 37 |
+
return Math.max(multiple, Math.round(value / multiple) * multiple);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
function buildGptImage2SizeFromAspectRatio(
|
| 41 |
+
ar: string | null,
|
| 42 |
+
quality: CliArgs["quality"],
|
| 43 |
+
): string {
|
| 44 |
+
const parsed = ar ? parseAspectRatio(ar) : null;
|
| 45 |
+
const ratio = parsed ? parsed.width / parsed.height : 1;
|
| 46 |
+
|
| 47 |
+
if (!parsed || Math.abs(ratio - 1) < 0.1) {
|
| 48 |
+
const edge = quality === "2k" ? 2048 : 1024;
|
| 49 |
+
return `${edge}x${edge}`;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
const targetLongEdge = quality === "2k" ? 2048 : 1024;
|
| 53 |
+
let width: number;
|
| 54 |
+
let height: number;
|
| 55 |
+
|
| 56 |
+
if (ratio > 1) {
|
| 57 |
+
width = targetLongEdge;
|
| 58 |
+
height = roundToMultiple(width / ratio, 16);
|
| 59 |
+
} else {
|
| 60 |
+
height = targetLongEdge;
|
| 61 |
+
width = roundToMultiple(height * ratio, 16);
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
while (width * height < 655_360) {
|
| 65 |
+
if (ratio > 1) {
|
| 66 |
+
width += 16;
|
| 67 |
+
height = roundToMultiple(width / ratio, 16);
|
| 68 |
+
} else {
|
| 69 |
+
height += 16;
|
| 70 |
+
width = roundToMultiple(height * ratio, 16);
|
| 71 |
+
}
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
return `${width}x${height}`;
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
export function getOpenAISize(
|
| 78 |
+
model: string,
|
| 79 |
+
ar: string | null,
|
| 80 |
+
quality: CliArgs["quality"]
|
| 81 |
+
): string {
|
| 82 |
+
const isDalle3 = model.includes("dall-e-3");
|
| 83 |
+
const isDalle2 = model.includes("dall-e-2");
|
| 84 |
+
|
| 85 |
+
if (isDalle2) {
|
| 86 |
+
return "1024x1024";
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
if (isGptImage2Model(model)) {
|
| 90 |
+
return buildGptImage2SizeFromAspectRatio(ar, quality);
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
const sizes: SizeMapping = isDalle3
|
| 94 |
+
? {
|
| 95 |
+
square: "1024x1024",
|
| 96 |
+
landscape: "1792x1024",
|
| 97 |
+
portrait: "1024x1792",
|
| 98 |
+
}
|
| 99 |
+
: {
|
| 100 |
+
square: "1024x1024",
|
| 101 |
+
landscape: "1536x1024",
|
| 102 |
+
portrait: "1024x1536",
|
| 103 |
+
};
|
| 104 |
+
|
| 105 |
+
if (!ar) return sizes.square;
|
| 106 |
+
|
| 107 |
+
const parsed = parseAspectRatio(ar);
|
| 108 |
+
if (!parsed) return sizes.square;
|
| 109 |
+
|
| 110 |
+
const ratio = parsed.width / parsed.height;
|
| 111 |
+
|
| 112 |
+
if (Math.abs(ratio - 1) < 0.1) return sizes.square;
|
| 113 |
+
if (ratio > 1.5) return sizes.landscape;
|
| 114 |
+
if (ratio < 0.67) return sizes.portrait;
|
| 115 |
+
return sizes.square;
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
function parsePixelSize(value: string): { width: number; height: number } | null {
|
| 119 |
+
const match = value.match(/^(\d+)\s*[xX]\s*(\d+)$/);
|
| 120 |
+
if (!match) return null;
|
| 121 |
+
|
| 122 |
+
const width = parseInt(match[1]!, 10);
|
| 123 |
+
const height = parseInt(match[2]!, 10);
|
| 124 |
+
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
|
| 125 |
+
return null;
|
| 126 |
+
}
|
| 127 |
+
|
| 128 |
+
return { width, height };
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
function gcd(a: number, b: number): number {
|
| 132 |
+
let x = Math.abs(a);
|
| 133 |
+
let y = Math.abs(b);
|
| 134 |
+
while (y !== 0) {
|
| 135 |
+
const next = x % y;
|
| 136 |
+
x = y;
|
| 137 |
+
y = next;
|
| 138 |
+
}
|
| 139 |
+
return x || 1;
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
export function getOpenAIImageApiDialect(args: Pick<CliArgs, "imageApiDialect">): OpenAIImageApiDialect {
|
| 143 |
+
return args.imageApiDialect ?? "openai-native";
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
export function inferAspectRatioFromSize(size: string | null): string | null {
|
| 147 |
+
if (!size) return null;
|
| 148 |
+
const parsed = parsePixelSize(size);
|
| 149 |
+
if (!parsed) return null;
|
| 150 |
+
|
| 151 |
+
const divisor = gcd(parsed.width, parsed.height);
|
| 152 |
+
return `${parsed.width / divisor}:${parsed.height / divisor}`;
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
export function inferResolutionFromSize(size: string | null): "1K" | "2K" | "4K" | null {
|
| 156 |
+
if (!size) return null;
|
| 157 |
+
const parsed = parsePixelSize(size);
|
| 158 |
+
if (!parsed) return null;
|
| 159 |
+
|
| 160 |
+
const longestEdge = Math.max(parsed.width, parsed.height);
|
| 161 |
+
if (longestEdge <= 1024) return "1K";
|
| 162 |
+
if (longestEdge <= 2048) return "2K";
|
| 163 |
+
return "4K";
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
export function getOpenAIAspectRatio(args: Pick<CliArgs, "aspectRatio" | "size">): string {
|
| 167 |
+
return args.aspectRatio ?? inferAspectRatioFromSize(args.size) ?? "1:1";
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
export function getOpenAIResolution(
|
| 171 |
+
args: Pick<CliArgs, "imageSize" | "size" | "quality">
|
| 172 |
+
): "1K" | "2K" | "4K" {
|
| 173 |
+
if (args.imageSize === "1K" || args.imageSize === "2K" || args.imageSize === "4K") {
|
| 174 |
+
return args.imageSize;
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
const inferred = inferResolutionFromSize(args.size);
|
| 178 |
+
if (inferred) return inferred;
|
| 179 |
+
|
| 180 |
+
return args.quality === "normal" ? "1K" : "2K";
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
function getOpenAIQuality(model: string, quality: CliArgs["quality"]): "standard" | "hd" | "medium" | "high" | null {
|
| 184 |
+
if (model.includes("dall-e-3")) {
|
| 185 |
+
return quality === "2k" ? "hd" : "standard";
|
| 186 |
+
}
|
| 187 |
+
|
| 188 |
+
if (isGptImageModel(model)) {
|
| 189 |
+
return quality === "2k" ? "high" : "medium";
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
return null;
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
export function getOrientationFromAspectRatio(ar: string): "landscape" | "portrait" | null {
|
| 196 |
+
const parsed = parseAspectRatio(ar);
|
| 197 |
+
if (!parsed) return null;
|
| 198 |
+
|
| 199 |
+
const ratio = parsed.width / parsed.height;
|
| 200 |
+
if (Math.abs(ratio - 1) < 0.1) return null;
|
| 201 |
+
return ratio > 1 ? "landscape" : "portrait";
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
export function buildOpenAIGenerationsBody(
|
| 205 |
+
prompt: string,
|
| 206 |
+
model: string,
|
| 207 |
+
args: Pick<CliArgs, "aspectRatio" | "size" | "quality" | "imageSize" | "imageApiDialect">
|
| 208 |
+
): OpenAIGenerationsBody {
|
| 209 |
+
if (getOpenAIImageApiDialect(args) === "ratio-metadata") {
|
| 210 |
+
const aspectRatio = getOpenAIAspectRatio(args);
|
| 211 |
+
const metadata: Record<string, string> = {
|
| 212 |
+
resolution: getOpenAIResolution(args),
|
| 213 |
+
};
|
| 214 |
+
const orientation = getOrientationFromAspectRatio(aspectRatio);
|
| 215 |
+
if (orientation) metadata.orientation = orientation;
|
| 216 |
+
|
| 217 |
+
return {
|
| 218 |
+
model,
|
| 219 |
+
prompt,
|
| 220 |
+
size: aspectRatio,
|
| 221 |
+
metadata,
|
| 222 |
+
};
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
const body: OpenAIGenerationsBody = {
|
| 226 |
+
model,
|
| 227 |
+
prompt,
|
| 228 |
+
size: args.size || getOpenAISize(model, args.aspectRatio, args.quality),
|
| 229 |
+
};
|
| 230 |
+
|
| 231 |
+
const quality = getOpenAIQuality(model, args.quality);
|
| 232 |
+
if (quality) {
|
| 233 |
+
body.quality = quality;
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
return body;
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
export function validateArgs(model: string, args: CliArgs): void {
|
| 240 |
+
if (!isGptImage2Model(model)) return;
|
| 241 |
+
|
| 242 |
+
if (args.aspectRatio && !args.size) {
|
| 243 |
+
const parsed = parseAspectRatio(args.aspectRatio);
|
| 244 |
+
if (!parsed) {
|
| 245 |
+
throw new Error(`Invalid gpt-image-2 aspect ratio: ${args.aspectRatio}`);
|
| 246 |
+
}
|
| 247 |
+
const ratio = parsed.width / parsed.height;
|
| 248 |
+
if (Math.max(ratio, 1 / ratio) > 3) {
|
| 249 |
+
throw new Error("gpt-image-2 aspect ratio must not exceed 3:1.");
|
| 250 |
+
}
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
if (!args.size) return;
|
| 254 |
+
|
| 255 |
+
const parsedSize = parsePixelSize(args.size);
|
| 256 |
+
if (!parsedSize) {
|
| 257 |
+
throw new Error(`Invalid gpt-image-2 --size: ${args.size}. Expected <width>x<height>.`);
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
const { width, height } = parsedSize;
|
| 261 |
+
const totalPixels = width * height;
|
| 262 |
+
const ratio = Math.max(width, height) / Math.min(width, height);
|
| 263 |
+
|
| 264 |
+
if (Math.max(width, height) > 3840) {
|
| 265 |
+
throw new Error("gpt-image-2 --size maximum edge length must be 3840px or less.");
|
| 266 |
+
}
|
| 267 |
+
if (width % 16 !== 0 || height % 16 !== 0) {
|
| 268 |
+
throw new Error("gpt-image-2 --size width and height must both be multiples of 16px.");
|
| 269 |
+
}
|
| 270 |
+
if (ratio > 3) {
|
| 271 |
+
throw new Error("gpt-image-2 --size long edge to short edge ratio must not exceed 3:1.");
|
| 272 |
+
}
|
| 273 |
+
if (totalPixels < 655_360 || totalPixels > 8_294_400) {
|
| 274 |
+
throw new Error("gpt-image-2 --size total pixels must be between 655,360 and 8,294,400.");
|
| 275 |
+
}
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
export async function generateImage(
|
| 279 |
+
prompt: string,
|
| 280 |
+
model: string,
|
| 281 |
+
args: CliArgs
|
| 282 |
+
): Promise<Uint8Array> {
|
| 283 |
+
const baseURL = process.env.OPENAI_BASE_URL || "https://api.openai.com/v1";
|
| 284 |
+
const apiKey = process.env.OPENAI_API_KEY;
|
| 285 |
+
|
| 286 |
+
if (!apiKey) {
|
| 287 |
+
throw new Error(
|
| 288 |
+
"OPENAI_API_KEY is required. Codex/ChatGPT desktop login does not automatically grant OpenAI Images API access to this script."
|
| 289 |
+
);
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
if (process.env.OPENAI_IMAGE_USE_CHAT === "true") {
|
| 293 |
+
return generateWithChatCompletions(baseURL, apiKey, prompt, model);
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
const imageApiDialect = getOpenAIImageApiDialect(args);
|
| 297 |
+
|
| 298 |
+
if (args.referenceImages.length > 0) {
|
| 299 |
+
if (imageApiDialect !== "openai-native") {
|
| 300 |
+
throw new Error(
|
| 301 |
+
"Reference images are not supported with the ratio-metadata OpenAI dialect yet. Use openai-native, Google, Azure, OpenRouter, MiniMax, Seedream, or Replicate for image-edit workflows."
|
| 302 |
+
);
|
| 303 |
+
}
|
| 304 |
+
if (model.includes("dall-e-2") || model.includes("dall-e-3")) {
|
| 305 |
+
throw new Error(
|
| 306 |
+
"Reference images with OpenAI in this skill require GPT Image models. Use --model gpt-image-2 (or another gpt-image model)."
|
| 307 |
+
);
|
| 308 |
+
}
|
| 309 |
+
const size = args.size || getOpenAISize(model, args.aspectRatio, args.quality);
|
| 310 |
+
return generateWithOpenAIEdits(baseURL, apiKey, prompt, model, size, args.referenceImages, args.quality);
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
return generateWithOpenAIGenerations(
|
| 314 |
+
baseURL,
|
| 315 |
+
apiKey,
|
| 316 |
+
buildOpenAIGenerationsBody(prompt, model, args)
|
| 317 |
+
);
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
async function generateWithChatCompletions(
|
| 321 |
+
baseURL: string,
|
| 322 |
+
apiKey: string,
|
| 323 |
+
prompt: string,
|
| 324 |
+
model: string
|
| 325 |
+
): Promise<Uint8Array> {
|
| 326 |
+
const res = await fetch(`${baseURL}/chat/completions`, {
|
| 327 |
+
method: "POST",
|
| 328 |
+
headers: {
|
| 329 |
+
"Content-Type": "application/json",
|
| 330 |
+
Authorization: `Bearer ${apiKey}`,
|
| 331 |
+
},
|
| 332 |
+
body: JSON.stringify({
|
| 333 |
+
model,
|
| 334 |
+
messages: [{ role: "user", content: prompt }],
|
| 335 |
+
}),
|
| 336 |
+
});
|
| 337 |
+
|
| 338 |
+
if (!res.ok) {
|
| 339 |
+
const err = await res.text();
|
| 340 |
+
throw new Error(`OpenAI API error: ${err}`);
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
const result = (await res.json()) as { choices: Array<{ message: { content: string } }> };
|
| 344 |
+
const content = result.choices[0]?.message?.content ?? "";
|
| 345 |
+
|
| 346 |
+
const match = content.match(/data:image\/[^;]+;base64,([A-Za-z0-9+/=]+)/);
|
| 347 |
+
if (match) {
|
| 348 |
+
return Uint8Array.from(Buffer.from(match[1]!, "base64"));
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
throw new Error("No image found in chat completions response");
|
| 352 |
+
}
|
| 353 |
+
|
| 354 |
+
async function generateWithOpenAIGenerations(
|
| 355 |
+
baseURL: string,
|
| 356 |
+
apiKey: string,
|
| 357 |
+
body: OpenAIGenerationsBody
|
| 358 |
+
): Promise<Uint8Array> {
|
| 359 |
+
const res = await fetch(`${baseURL}/images/generations`, {
|
| 360 |
+
method: "POST",
|
| 361 |
+
headers: {
|
| 362 |
+
"Content-Type": "application/json",
|
| 363 |
+
Authorization: `Bearer ${apiKey}`,
|
| 364 |
+
},
|
| 365 |
+
body: JSON.stringify(body),
|
| 366 |
+
});
|
| 367 |
+
|
| 368 |
+
if (!res.ok) {
|
| 369 |
+
const err = await res.text();
|
| 370 |
+
throw new Error(`OpenAI API error: ${err}`);
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
const result = (await res.json()) as OpenAIImageResponse;
|
| 374 |
+
return extractImageFromResponse(result);
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
async function generateWithOpenAIEdits(
|
| 378 |
+
baseURL: string,
|
| 379 |
+
apiKey: string,
|
| 380 |
+
prompt: string,
|
| 381 |
+
model: string,
|
| 382 |
+
size: string,
|
| 383 |
+
referenceImages: string[],
|
| 384 |
+
quality: CliArgs["quality"]
|
| 385 |
+
): Promise<Uint8Array> {
|
| 386 |
+
const form = new FormData();
|
| 387 |
+
form.append("model", model);
|
| 388 |
+
form.append("prompt", prompt);
|
| 389 |
+
form.append("size", size);
|
| 390 |
+
|
| 391 |
+
const openAIQuality = getOpenAIQuality(model, quality);
|
| 392 |
+
if (openAIQuality && openAIQuality !== "standard" && openAIQuality !== "hd") {
|
| 393 |
+
form.append("quality", openAIQuality);
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
for (const refPath of referenceImages) {
|
| 397 |
+
const bytes = await readFile(refPath);
|
| 398 |
+
const filename = path.basename(refPath);
|
| 399 |
+
const mimeType = getMimeType(filename);
|
| 400 |
+
const blob = new Blob([bytes], { type: mimeType });
|
| 401 |
+
form.append("image[]", blob, filename);
|
| 402 |
+
}
|
| 403 |
+
|
| 404 |
+
const res = await fetch(`${baseURL}/images/edits`, {
|
| 405 |
+
method: "POST",
|
| 406 |
+
headers: {
|
| 407 |
+
Authorization: `Bearer ${apiKey}`,
|
| 408 |
+
},
|
| 409 |
+
body: form,
|
| 410 |
+
});
|
| 411 |
+
|
| 412 |
+
if (!res.ok) {
|
| 413 |
+
const err = await res.text();
|
| 414 |
+
throw new Error(`OpenAI edits API error: ${err}`);
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
const result = (await res.json()) as OpenAIImageResponse;
|
| 418 |
+
return extractImageFromResponse(result);
|
| 419 |
+
}
|
| 420 |
+
|
| 421 |
+
export function getMimeType(filename: string): string {
|
| 422 |
+
const ext = path.extname(filename).toLowerCase();
|
| 423 |
+
if (ext === ".jpg" || ext === ".jpeg") return "image/jpeg";
|
| 424 |
+
if (ext === ".webp") return "image/webp";
|
| 425 |
+
if (ext === ".gif") return "image/gif";
|
| 426 |
+
return "image/png";
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
export async function extractImageFromResponse(result: OpenAIImageResponse): Promise<Uint8Array> {
|
| 430 |
+
const img = result.data[0];
|
| 431 |
+
|
| 432 |
+
if (img?.b64_json) {
|
| 433 |
+
return Uint8Array.from(Buffer.from(img.b64_json, "base64"));
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
if (img?.url) {
|
| 437 |
+
const imgRes = await fetch(img.url);
|
| 438 |
+
if (!imgRes.ok) throw new Error("Failed to download image");
|
| 439 |
+
const buf = await imgRes.arrayBuffer();
|
| 440 |
+
return new Uint8Array(buf);
|
| 441 |
+
}
|
| 442 |
+
|
| 443 |
+
throw new Error("No image in response");
|
| 444 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/providers/openrouter.test.ts
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from "node:assert/strict";
|
| 2 |
+
import test from "node:test";
|
| 3 |
+
|
| 4 |
+
import type { CliArgs } from "../types.ts";
|
| 5 |
+
import {
|
| 6 |
+
buildContent,
|
| 7 |
+
buildRequestBody,
|
| 8 |
+
extractImageFromResponse,
|
| 9 |
+
getAspectRatio,
|
| 10 |
+
getImageSize,
|
| 11 |
+
validateArgs,
|
| 12 |
+
} from "./openrouter.ts";
|
| 13 |
+
|
| 14 |
+
const GEMINI_MODEL = "google/gemini-3.1-flash-image-preview";
|
| 15 |
+
const GEMINI_25_MODEL = "google/gemini-2.5-flash-image";
|
| 16 |
+
const GPT_5_IMAGE_MODEL = "openai/gpt-5-image";
|
| 17 |
+
const OPENROUTER_AUTO_MODEL = "openrouter/auto";
|
| 18 |
+
const FLUX_MODEL = "black-forest-labs/flux.2-pro";
|
| 19 |
+
|
| 20 |
+
function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
| 21 |
+
return {
|
| 22 |
+
prompt: null,
|
| 23 |
+
promptFiles: [],
|
| 24 |
+
imagePath: null,
|
| 25 |
+
provider: null,
|
| 26 |
+
model: null,
|
| 27 |
+
aspectRatio: null,
|
| 28 |
+
size: null,
|
| 29 |
+
quality: null,
|
| 30 |
+
imageSize: null,
|
| 31 |
+
imageApiDialect: null,
|
| 32 |
+
referenceImages: [],
|
| 33 |
+
n: 1,
|
| 34 |
+
batchFile: null,
|
| 35 |
+
jobs: null,
|
| 36 |
+
json: false,
|
| 37 |
+
help: false,
|
| 38 |
+
...overrides,
|
| 39 |
+
};
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
test("OpenRouter request body uses image_config and string content for text-only prompts", () => {
|
| 43 |
+
const args = makeArgs({ aspectRatio: "16:9", quality: "2k" });
|
| 44 |
+
const body = buildRequestBody("hello", GEMINI_MODEL, args, []);
|
| 45 |
+
|
| 46 |
+
assert.deepEqual(body.image_config, {
|
| 47 |
+
image_size: "2K",
|
| 48 |
+
aspect_ratio: "16:9",
|
| 49 |
+
});
|
| 50 |
+
assert.deepEqual(body.provider, {
|
| 51 |
+
require_parameters: true,
|
| 52 |
+
});
|
| 53 |
+
assert.deepEqual(body.modalities, ["image", "text"]);
|
| 54 |
+
assert.equal(body.stream, false);
|
| 55 |
+
assert.equal(body.messages[0].content, "hello");
|
| 56 |
+
});
|
| 57 |
+
|
| 58 |
+
test("OpenRouter request body keeps text+image modalities for current text+image models", () => {
|
| 59 |
+
for (const model of [GEMINI_MODEL, GEMINI_25_MODEL, GPT_5_IMAGE_MODEL, OPENROUTER_AUTO_MODEL]) {
|
| 60 |
+
const body = buildRequestBody("hello", model, makeArgs({ quality: "2k" }), []);
|
| 61 |
+
|
| 62 |
+
assert.deepEqual(body.image_config, {
|
| 63 |
+
image_size: "2K",
|
| 64 |
+
});
|
| 65 |
+
assert.deepEqual(body.provider, {
|
| 66 |
+
require_parameters: true,
|
| 67 |
+
});
|
| 68 |
+
assert.deepEqual(body.modalities, ["image", "text"]);
|
| 69 |
+
assert.equal(body.messages[0].content, "hello");
|
| 70 |
+
}
|
| 71 |
+
});
|
| 72 |
+
|
| 73 |
+
test("OpenRouter request body uses image-only modalities for image-only models under CLI defaults", () => {
|
| 74 |
+
const body = buildRequestBody("hello", FLUX_MODEL, makeArgs({ quality: "2k" }), []);
|
| 75 |
+
|
| 76 |
+
assert.deepEqual(body.image_config, {
|
| 77 |
+
image_size: "2K",
|
| 78 |
+
});
|
| 79 |
+
assert.deepEqual(body.provider, {
|
| 80 |
+
require_parameters: true,
|
| 81 |
+
});
|
| 82 |
+
assert.deepEqual(body.modalities, ["image"]);
|
| 83 |
+
assert.equal(body.stream, false);
|
| 84 |
+
assert.equal(body.messages[0].content, "hello");
|
| 85 |
+
});
|
| 86 |
+
|
| 87 |
+
test("OpenRouter helper omits image_config when no size or quality is passed", () => {
|
| 88 |
+
const body = buildRequestBody("hello", FLUX_MODEL, makeArgs(), []);
|
| 89 |
+
|
| 90 |
+
assert.equal(body.image_config, undefined);
|
| 91 |
+
assert.equal(body.provider, undefined);
|
| 92 |
+
assert.deepEqual(body.modalities, ["image"]);
|
| 93 |
+
assert.equal(body.stream, false);
|
| 94 |
+
assert.equal(body.messages[0].content, "hello");
|
| 95 |
+
});
|
| 96 |
+
|
| 97 |
+
test("OpenRouter request body keeps multimodal array content when references are provided", () => {
|
| 98 |
+
const content = buildContent("hello", ["data:image/png;base64,abc"]);
|
| 99 |
+
assert.ok(Array.isArray(content));
|
| 100 |
+
assert.deepEqual(content[0], { type: "text", text: "hello" });
|
| 101 |
+
assert.deepEqual(content[1], {
|
| 102 |
+
type: "image_url",
|
| 103 |
+
image_url: { url: "data:image/png;base64,abc" },
|
| 104 |
+
});
|
| 105 |
+
});
|
| 106 |
+
|
| 107 |
+
test("OpenRouter size and aspect helpers infer supported values", () => {
|
| 108 |
+
assert.equal(getImageSize(makeArgs()), null);
|
| 109 |
+
assert.equal(getImageSize(makeArgs({ quality: "normal" })), "1K");
|
| 110 |
+
assert.equal(getImageSize(makeArgs({ size: "2048x1024" })), "2K");
|
| 111 |
+
assert.equal(getAspectRatio(GEMINI_MODEL, makeArgs({ size: "1600x900" })), "16:9");
|
| 112 |
+
assert.equal(getAspectRatio(GEMINI_MODEL, makeArgs({ size: "1024x4096" })), "1:4");
|
| 113 |
+
assert.equal(getAspectRatio(GEMINI_25_MODEL, makeArgs({ size: "1600x900" })), "16:9");
|
| 114 |
+
assert.equal(getAspectRatio(FLUX_MODEL, makeArgs({ size: "1024x4096" })), null);
|
| 115 |
+
});
|
| 116 |
+
|
| 117 |
+
test("OpenRouter validates explicit aspect ratios and inferred size ratios against model support", () => {
|
| 118 |
+
assert.doesNotThrow(() =>
|
| 119 |
+
validateArgs(GEMINI_MODEL, makeArgs({ aspectRatio: "1:4" })),
|
| 120 |
+
);
|
| 121 |
+
assert.doesNotThrow(() =>
|
| 122 |
+
validateArgs(GEMINI_MODEL, makeArgs({ size: "1024x4096" })),
|
| 123 |
+
);
|
| 124 |
+
assert.throws(
|
| 125 |
+
() => validateArgs(GEMINI_25_MODEL, makeArgs({ aspectRatio: "1:4" })),
|
| 126 |
+
/does not support aspect ratio 1:4/,
|
| 127 |
+
);
|
| 128 |
+
assert.throws(
|
| 129 |
+
() => validateArgs(FLUX_MODEL, makeArgs({ aspectRatio: "1:4" })),
|
| 130 |
+
/does not support aspect ratio 1:4/,
|
| 131 |
+
);
|
| 132 |
+
assert.throws(
|
| 133 |
+
() => validateArgs(GEMINI_MODEL, makeArgs({ size: "2048x1024" })),
|
| 134 |
+
/does not support size 2048x1024 \(aspect ratio 2:1\)/,
|
| 135 |
+
);
|
| 136 |
+
});
|
| 137 |
+
|
| 138 |
+
test("OpenRouter response extraction supports inline image data and finish_reason errors", async () => {
|
| 139 |
+
const bytes = await extractImageFromResponse({
|
| 140 |
+
choices: [
|
| 141 |
+
{
|
| 142 |
+
message: {
|
| 143 |
+
images: [
|
| 144 |
+
{
|
| 145 |
+
image_url: {
|
| 146 |
+
url: `data:image/png;base64,${Buffer.from("hello").toString("base64")}`,
|
| 147 |
+
},
|
| 148 |
+
},
|
| 149 |
+
],
|
| 150 |
+
},
|
| 151 |
+
},
|
| 152 |
+
],
|
| 153 |
+
});
|
| 154 |
+
assert.equal(Buffer.from(bytes).toString("utf8"), "hello");
|
| 155 |
+
|
| 156 |
+
await assert.rejects(
|
| 157 |
+
() =>
|
| 158 |
+
extractImageFromResponse({
|
| 159 |
+
choices: [
|
| 160 |
+
{
|
| 161 |
+
finish_reason: "error",
|
| 162 |
+
native_finish_reason: "MALFORMED_FUNCTION_CALL",
|
| 163 |
+
message: { content: null },
|
| 164 |
+
},
|
| 165 |
+
],
|
| 166 |
+
}),
|
| 167 |
+
/finish_reason=MALFORMED_FUNCTION_CALL/,
|
| 168 |
+
);
|
| 169 |
+
});
|
baoyu_skills/baoyu-imagine/scripts/providers/openrouter.ts
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import path from "node:path";
|
| 2 |
+
import { readFile } from "node:fs/promises";
|
| 3 |
+
import type { CliArgs } from "../types";
|
| 4 |
+
|
| 5 |
+
const DEFAULT_MODEL = "google/gemini-3.1-flash-image";
|
| 6 |
+
const COMMON_ASPECT_RATIOS = [
|
| 7 |
+
"1:1",
|
| 8 |
+
"2:3",
|
| 9 |
+
"3:2",
|
| 10 |
+
"3:4",
|
| 11 |
+
"4:3",
|
| 12 |
+
"4:5",
|
| 13 |
+
"5:4",
|
| 14 |
+
"9:16",
|
| 15 |
+
"16:9",
|
| 16 |
+
"21:9",
|
| 17 |
+
];
|
| 18 |
+
const GEMINI_EXTENDED_ASPECT_RATIOS = ["1:4", "4:1", "1:8", "8:1"];
|
| 19 |
+
|
| 20 |
+
type OpenRouterImageEntry = {
|
| 21 |
+
image_url?: string | { url?: string | null } | null;
|
| 22 |
+
imageUrl?: string | { url?: string | null } | null;
|
| 23 |
+
};
|
| 24 |
+
|
| 25 |
+
type OpenRouterMessagePart = {
|
| 26 |
+
type?: string;
|
| 27 |
+
text?: string;
|
| 28 |
+
image_url?: string | { url?: string | null } | null;
|
| 29 |
+
imageUrl?: string | { url?: string | null } | null;
|
| 30 |
+
};
|
| 31 |
+
|
| 32 |
+
type OpenRouterResponse = {
|
| 33 |
+
choices?: Array<{
|
| 34 |
+
finish_reason?: string | null;
|
| 35 |
+
native_finish_reason?: string | null;
|
| 36 |
+
message?: {
|
| 37 |
+
images?: OpenRouterImageEntry[];
|
| 38 |
+
content?: string | OpenRouterMessagePart[] | null;
|
| 39 |
+
};
|
| 40 |
+
}>;
|
| 41 |
+
};
|
| 42 |
+
|
| 43 |
+
export function getDefaultModel(): string {
|
| 44 |
+
return process.env.OPENROUTER_IMAGE_MODEL || DEFAULT_MODEL;
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
function normalizeModelId(model: string): string {
|
| 48 |
+
return model.trim().toLowerCase().split(":")[0]!;
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
function isTextAndImageModel(model: string): boolean {
|
| 52 |
+
const normalized = normalizeModelId(model);
|
| 53 |
+
if (normalized === "openrouter/auto") {
|
| 54 |
+
return true;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
if (normalized.startsWith("google/gemini-") && normalized.includes("image")) {
|
| 58 |
+
return true;
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
if (normalized.startsWith("openai/gpt-") && normalized.includes("image")) {
|
| 62 |
+
return true;
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
return false;
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
function getSupportedAspectRatios(model: string): Set<string> {
|
| 69 |
+
const normalized = normalizeModelId(model);
|
| 70 |
+
if (
|
| 71 |
+
normalized !== "google/gemini-3.1-flash-image" &&
|
| 72 |
+
normalized !== "google/gemini-3.1-flash-image-preview"
|
| 73 |
+
) {
|
| 74 |
+
return new Set(COMMON_ASPECT_RATIOS);
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
return new Set([...COMMON_ASPECT_RATIOS, ...GEMINI_EXTENDED_ASPECT_RATIOS]);
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
function getApiKey(): string | null {
|
| 81 |
+
return process.env.OPENROUTER_API_KEY || null;
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
function getBaseUrl(): string {
|
| 85 |
+
const base = process.env.OPENROUTER_BASE_URL || "https://openrouter.ai/api/v1";
|
| 86 |
+
return base.replace(/\/+$/g, "");
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
function getHeaders(apiKey: string): Record<string, string> {
|
| 90 |
+
const headers: Record<string, string> = {
|
| 91 |
+
"Content-Type": "application/json",
|
| 92 |
+
Authorization: `Bearer ${apiKey}`,
|
| 93 |
+
};
|
| 94 |
+
|
| 95 |
+
const referer = process.env.OPENROUTER_HTTP_REFERER?.trim();
|
| 96 |
+
if (referer) {
|
| 97 |
+
headers["HTTP-Referer"] = referer;
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
const title = process.env.OPENROUTER_TITLE?.trim();
|
| 101 |
+
if (title) {
|
| 102 |
+
headers["X-OpenRouter-Title"] = title;
|
| 103 |
+
headers["X-Title"] = title;
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
return headers;
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
function parsePixelSize(value: string): { width: number; height: number } | null {
|
| 110 |
+
const match = value.match(/^(\d+)\s*[xX]\s*(\d+)$/);
|
| 111 |
+
if (!match) return null;
|
| 112 |
+
|
| 113 |
+
const width = parseInt(match[1]!, 10);
|
| 114 |
+
const height = parseInt(match[2]!, 10);
|
| 115 |
+
|
| 116 |
+
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
|
| 117 |
+
return null;
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
return { width, height };
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
function gcd(a: number, b: number): number {
|
| 124 |
+
let x = Math.abs(a);
|
| 125 |
+
let y = Math.abs(b);
|
| 126 |
+
while (y !== 0) {
|
| 127 |
+
const next = x % y;
|
| 128 |
+
x = y;
|
| 129 |
+
y = next;
|
| 130 |
+
}
|
| 131 |
+
return x || 1;
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
function inferAspectRatio(size: string | null): string | null {
|
| 135 |
+
if (!size) return null;
|
| 136 |
+
const parsed = parsePixelSize(size);
|
| 137 |
+
if (!parsed) return null;
|
| 138 |
+
|
| 139 |
+
const divisor = gcd(parsed.width, parsed.height);
|
| 140 |
+
return `${parsed.width / divisor}:${parsed.height / divisor}`;
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
function inferImageSize(size: string | null): "1K" | "2K" | "4K" | null {
|
| 144 |
+
if (!size) return null;
|
| 145 |
+
const parsed = parsePixelSize(size);
|
| 146 |
+
if (!parsed) return null;
|
| 147 |
+
|
| 148 |
+
const longestEdge = Math.max(parsed.width, parsed.height);
|
| 149 |
+
if (longestEdge <= 1024) return "1K";
|
| 150 |
+
if (longestEdge <= 2048) return "2K";
|
| 151 |
+
return "4K";
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
export function getImageSize(args: CliArgs): "1K" | "2K" | "4K" | null {
|
| 155 |
+
if (args.imageSize) return args.imageSize as "1K" | "2K" | "4K";
|
| 156 |
+
|
| 157 |
+
const inferredFromSize = inferImageSize(args.size);
|
| 158 |
+
if (inferredFromSize) return inferredFromSize;
|
| 159 |
+
|
| 160 |
+
if (args.quality === "normal") return "1K";
|
| 161 |
+
if (args.quality === "2k") return "2K";
|
| 162 |
+
return null;
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
export function getAspectRatio(model: string, args: CliArgs): string | null {
|
| 166 |
+
if (args.aspectRatio) return args.aspectRatio;
|
| 167 |
+
|
| 168 |
+
const inferred = inferAspectRatio(args.size);
|
| 169 |
+
if (!inferred || !getSupportedAspectRatios(model).has(inferred)) {
|
| 170 |
+
return null;
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
return inferred;
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
function getModalities(model: string): string[] {
|
| 177 |
+
return isTextAndImageModel(model) ? ["image", "text"] : ["image"];
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
export function validateArgs(model: string, args: CliArgs): void {
|
| 181 |
+
const requestedAspectRatio = args.aspectRatio || inferAspectRatio(args.size);
|
| 182 |
+
if (!requestedAspectRatio) {
|
| 183 |
+
return;
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
const supported = getSupportedAspectRatios(model);
|
| 187 |
+
if (supported.has(requestedAspectRatio)) {
|
| 188 |
+
return;
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
const requestedValue = args.aspectRatio
|
| 192 |
+
? `aspect ratio ${requestedAspectRatio}`
|
| 193 |
+
: `size ${args.size} (aspect ratio ${requestedAspectRatio})`;
|
| 194 |
+
|
| 195 |
+
throw new Error(
|
| 196 |
+
`OpenRouter model ${model} does not support ${requestedValue}. Supported values: ${Array.from(supported).join(", ")}`
|
| 197 |
+
);
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
function getMimeType(filename: string): string {
|
| 201 |
+
const ext = path.extname(filename).toLowerCase();
|
| 202 |
+
if (ext === ".jpg" || ext === ".jpeg") return "image/jpeg";
|
| 203 |
+
if (ext === ".webp") return "image/webp";
|
| 204 |
+
if (ext === ".gif") return "image/gif";
|
| 205 |
+
return "image/png";
|
| 206 |
+
}
|
| 207 |
+
|
| 208 |
+
async function readImageAsDataUrl(filePath: string): Promise<string> {
|
| 209 |
+
const bytes = await readFile(filePath);
|
| 210 |
+
return `data:${getMimeType(filePath)};base64,${bytes.toString("base64")}`;
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
export function buildContent(
|
| 214 |
+
prompt: string,
|
| 215 |
+
referenceImages: string[],
|
| 216 |
+
): string | Array<Record<string, unknown>> {
|
| 217 |
+
if (referenceImages.length === 0) {
|
| 218 |
+
return prompt;
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
const content: Array<Record<string, unknown>> = [{ type: "text", text: prompt }];
|
| 222 |
+
|
| 223 |
+
for (const imageUrl of referenceImages) {
|
| 224 |
+
content.push({
|
| 225 |
+
type: "image_url",
|
| 226 |
+
image_url: { url: imageUrl },
|
| 227 |
+
});
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
return content;
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
function extractImageUrl(entry: OpenRouterImageEntry | OpenRouterMessagePart): string | null {
|
| 234 |
+
const value = entry.image_url ?? entry.imageUrl;
|
| 235 |
+
if (!value) return null;
|
| 236 |
+
if (typeof value === "string") return value;
|
| 237 |
+
return value.url ?? null;
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
function decodeDataUrl(value: string): Uint8Array | null {
|
| 241 |
+
const match = value.match(/^data:image\/[^;]+;base64,([A-Za-z0-9+/=]+)$/);
|
| 242 |
+
if (!match) return null;
|
| 243 |
+
return Uint8Array.from(Buffer.from(match[1]!, "base64"));
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
async function downloadImage(value: string): Promise<Uint8Array> {
|
| 247 |
+
const inline = decodeDataUrl(value);
|
| 248 |
+
if (inline) return inline;
|
| 249 |
+
|
| 250 |
+
if (value.startsWith("http://") || value.startsWith("https://")) {
|
| 251 |
+
const response = await fetch(value);
|
| 252 |
+
if (!response.ok) {
|
| 253 |
+
throw new Error(`Failed to download OpenRouter image: ${response.status}`);
|
| 254 |
+
}
|
| 255 |
+
const buffer = await response.arrayBuffer();
|
| 256 |
+
return new Uint8Array(buffer);
|
| 257 |
+
}
|
| 258 |
+
|
| 259 |
+
return Uint8Array.from(Buffer.from(value, "base64"));
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
export async function extractImageFromResponse(result: OpenRouterResponse): Promise<Uint8Array> {
|
| 263 |
+
const choice = result.choices?.[0];
|
| 264 |
+
const message = choice?.message;
|
| 265 |
+
|
| 266 |
+
for (const image of message?.images ?? []) {
|
| 267 |
+
const imageUrl = extractImageUrl(image);
|
| 268 |
+
if (imageUrl) return downloadImage(imageUrl);
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
if (Array.isArray(message?.content)) {
|
| 272 |
+
for (const item of message.content) {
|
| 273 |
+
const imageUrl = extractImageUrl(item);
|
| 274 |
+
if (imageUrl) return downloadImage(imageUrl);
|
| 275 |
+
|
| 276 |
+
if (item.type === "text" && item.text) {
|
| 277 |
+
const inline = decodeDataUrl(item.text);
|
| 278 |
+
if (inline) return inline;
|
| 279 |
+
}
|
| 280 |
+
}
|
| 281 |
+
} else if (typeof message?.content === "string") {
|
| 282 |
+
const inline = decodeDataUrl(message.content);
|
| 283 |
+
if (inline) return inline;
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
const finishReason =
|
| 287 |
+
choice?.native_finish_reason || choice?.finish_reason || "unknown";
|
| 288 |
+
throw new Error(
|
| 289 |
+
`No image in OpenRouter response (finish_reason=${finishReason})`,
|
| 290 |
+
);
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
export function buildRequestBody(
|
| 294 |
+
prompt: string,
|
| 295 |
+
model: string,
|
| 296 |
+
args: CliArgs,
|
| 297 |
+
referenceImages: string[],
|
| 298 |
+
): Record<string, unknown> {
|
| 299 |
+
validateArgs(model, args);
|
| 300 |
+
|
| 301 |
+
const imageConfig: Record<string, string> = {};
|
| 302 |
+
|
| 303 |
+
const imageSize = getImageSize(args);
|
| 304 |
+
if (imageSize) {
|
| 305 |
+
imageConfig.image_size = imageSize;
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
const aspectRatio = getAspectRatio(model, args);
|
| 309 |
+
if (aspectRatio) {
|
| 310 |
+
imageConfig.aspect_ratio = aspectRatio;
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
const body: Record<string, unknown> = {
|
| 314 |
+
messages: [
|
| 315 |
+
{
|
| 316 |
+
role: "user",
|
| 317 |
+
content: buildContent(prompt, referenceImages),
|
| 318 |
+
},
|
| 319 |
+
],
|
| 320 |
+
modalities: getModalities(model),
|
| 321 |
+
stream: false,
|
| 322 |
+
};
|
| 323 |
+
|
| 324 |
+
if (Object.keys(imageConfig).length > 0) {
|
| 325 |
+
body.image_config = imageConfig;
|
| 326 |
+
body.provider = {
|
| 327 |
+
require_parameters: true,
|
| 328 |
+
};
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
return body;
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
export async function generateImage(
|
| 335 |
+
prompt: string,
|
| 336 |
+
model: string,
|
| 337 |
+
args: CliArgs
|
| 338 |
+
): Promise<Uint8Array> {
|
| 339 |
+
const apiKey = getApiKey();
|
| 340 |
+
if (!apiKey) {
|
| 341 |
+
throw new Error("OPENROUTER_API_KEY is required. Get one at https://openrouter.ai/settings/keys");
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
const referenceImages: string[] = [];
|
| 345 |
+
for (const refPath of args.referenceImages) {
|
| 346 |
+
referenceImages.push(await readImageAsDataUrl(refPath));
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
const body = {
|
| 350 |
+
model,
|
| 351 |
+
...buildRequestBody(prompt, model, args, referenceImages),
|
| 352 |
+
};
|
| 353 |
+
|
| 354 |
+
console.log(
|
| 355 |
+
`Generating image with OpenRouter (${model})...`,
|
| 356 |
+
(body.image_config as Record<string, string>),
|
| 357 |
+
);
|
| 358 |
+
|
| 359 |
+
const response = await fetch(`${getBaseUrl()}/chat/completions`, {
|
| 360 |
+
method: "POST",
|
| 361 |
+
headers: getHeaders(apiKey),
|
| 362 |
+
body: JSON.stringify(body),
|
| 363 |
+
});
|
| 364 |
+
|
| 365 |
+
if (!response.ok) {
|
| 366 |
+
const errorText = await response.text();
|
| 367 |
+
throw new Error(`OpenRouter API error (${response.status}): ${errorText}`);
|
| 368 |
+
}
|
| 369 |
+
|
| 370 |
+
const result = (await response.json()) as OpenRouterResponse;
|
| 371 |
+
return extractImageFromResponse(result);
|
| 372 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/providers/replicate.test.ts
ADDED
|
@@ -0,0 +1,310 @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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from "node:assert/strict";
|
| 2 |
+
import test from "node:test";
|
| 3 |
+
|
| 4 |
+
import type { CliArgs } from "../types.ts";
|
| 5 |
+
import {
|
| 6 |
+
buildInput,
|
| 7 |
+
extractOutputUrl,
|
| 8 |
+
getDefaultModel,
|
| 9 |
+
getModelFamily,
|
| 10 |
+
parseModelId,
|
| 11 |
+
validateArgs,
|
| 12 |
+
} from "./replicate.ts";
|
| 13 |
+
|
| 14 |
+
function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
| 15 |
+
return {
|
| 16 |
+
prompt: null,
|
| 17 |
+
promptFiles: [],
|
| 18 |
+
imagePath: null,
|
| 19 |
+
provider: null,
|
| 20 |
+
model: null,
|
| 21 |
+
aspectRatio: null,
|
| 22 |
+
aspectRatioSource: null,
|
| 23 |
+
size: null,
|
| 24 |
+
quality: null,
|
| 25 |
+
imageSize: null,
|
| 26 |
+
imageSizeSource: null,
|
| 27 |
+
imageApiDialect: null,
|
| 28 |
+
referenceImages: [],
|
| 29 |
+
n: 1,
|
| 30 |
+
batchFile: null,
|
| 31 |
+
jobs: null,
|
| 32 |
+
json: false,
|
| 33 |
+
help: false,
|
| 34 |
+
...overrides,
|
| 35 |
+
};
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
test("Replicate default model now points at nano-banana-2", () => {
|
| 39 |
+
const previous = process.env.REPLICATE_IMAGE_MODEL;
|
| 40 |
+
delete process.env.REPLICATE_IMAGE_MODEL;
|
| 41 |
+
try {
|
| 42 |
+
assert.equal(getDefaultModel(), "google/nano-banana-2");
|
| 43 |
+
} finally {
|
| 44 |
+
if (previous == null) {
|
| 45 |
+
delete process.env.REPLICATE_IMAGE_MODEL;
|
| 46 |
+
} else {
|
| 47 |
+
process.env.REPLICATE_IMAGE_MODEL = previous;
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
});
|
| 51 |
+
|
| 52 |
+
test("Replicate model parsing and family detection accept supported official ids", () => {
|
| 53 |
+
assert.deepEqual(parseModelId("google/nano-banana-2"), {
|
| 54 |
+
owner: "google",
|
| 55 |
+
name: "nano-banana-2",
|
| 56 |
+
version: null,
|
| 57 |
+
});
|
| 58 |
+
assert.deepEqual(parseModelId("owner/model:abc123"), {
|
| 59 |
+
owner: "owner",
|
| 60 |
+
name: "model",
|
| 61 |
+
version: "abc123",
|
| 62 |
+
});
|
| 63 |
+
|
| 64 |
+
assert.equal(getModelFamily("google/nano-banana-pro"), "nano-banana");
|
| 65 |
+
assert.equal(getModelFamily("bytedance/seedream-4.5"), "seedream45");
|
| 66 |
+
assert.equal(getModelFamily("bytedance/seedream-5-lite"), "seedream5lite");
|
| 67 |
+
assert.equal(getModelFamily("wan-video/wan-2.7-image"), "wan27image");
|
| 68 |
+
assert.equal(getModelFamily("wan-video/wan-2.7-image-pro"), "wan27imagepro");
|
| 69 |
+
assert.equal(getModelFamily("stability-ai/sdxl"), "unknown");
|
| 70 |
+
|
| 71 |
+
assert.throws(
|
| 72 |
+
() => parseModelId("just-a-model-name"),
|
| 73 |
+
/Invalid Replicate model format/,
|
| 74 |
+
);
|
| 75 |
+
});
|
| 76 |
+
|
| 77 |
+
test("Replicate nano-banana input builder maps refs, aspect ratio, and quality presets", () => {
|
| 78 |
+
assert.deepEqual(
|
| 79 |
+
buildInput(
|
| 80 |
+
"google/nano-banana-2",
|
| 81 |
+
"A robot painter",
|
| 82 |
+
makeArgs({
|
| 83 |
+
aspectRatio: "16:9",
|
| 84 |
+
quality: "2k",
|
| 85 |
+
}),
|
| 86 |
+
["data:image/png;base64,AAAA"],
|
| 87 |
+
),
|
| 88 |
+
{
|
| 89 |
+
prompt: "A robot painter",
|
| 90 |
+
resolution: "2K",
|
| 91 |
+
output_format: "png",
|
| 92 |
+
aspect_ratio: "16:9",
|
| 93 |
+
image_input: ["data:image/png;base64,AAAA"],
|
| 94 |
+
},
|
| 95 |
+
);
|
| 96 |
+
|
| 97 |
+
assert.deepEqual(
|
| 98 |
+
buildInput(
|
| 99 |
+
"google/nano-banana-2",
|
| 100 |
+
"A robot painter",
|
| 101 |
+
makeArgs({ size: "1024x1024", quality: "normal" }),
|
| 102 |
+
[],
|
| 103 |
+
),
|
| 104 |
+
{
|
| 105 |
+
prompt: "A robot painter",
|
| 106 |
+
resolution: "1K",
|
| 107 |
+
output_format: "png",
|
| 108 |
+
aspect_ratio: "1:1",
|
| 109 |
+
},
|
| 110 |
+
);
|
| 111 |
+
});
|
| 112 |
+
|
| 113 |
+
test("Replicate Seedream and Wan inputs use family-specific request fields", () => {
|
| 114 |
+
assert.deepEqual(
|
| 115 |
+
buildInput(
|
| 116 |
+
"bytedance/seedream-4.5",
|
| 117 |
+
"A cinematic portrait",
|
| 118 |
+
makeArgs({ quality: "2k", referenceImages: ["local.png"] }),
|
| 119 |
+
["data:image/png;base64,AAAA"],
|
| 120 |
+
),
|
| 121 |
+
{
|
| 122 |
+
prompt: "A cinematic portrait",
|
| 123 |
+
size: "4K",
|
| 124 |
+
image_input: ["data:image/png;base64,AAAA"],
|
| 125 |
+
aspect_ratio: "match_input_image",
|
| 126 |
+
},
|
| 127 |
+
);
|
| 128 |
+
|
| 129 |
+
assert.deepEqual(
|
| 130 |
+
buildInput(
|
| 131 |
+
"bytedance/seedream-4.5",
|
| 132 |
+
"A cinematic portrait",
|
| 133 |
+
makeArgs({ size: "1536x1024" }),
|
| 134 |
+
[],
|
| 135 |
+
),
|
| 136 |
+
{
|
| 137 |
+
prompt: "A cinematic portrait",
|
| 138 |
+
size: "custom",
|
| 139 |
+
width: 1536,
|
| 140 |
+
height: 1024,
|
| 141 |
+
},
|
| 142 |
+
);
|
| 143 |
+
|
| 144 |
+
assert.deepEqual(
|
| 145 |
+
buildInput(
|
| 146 |
+
"bytedance/seedream-5-lite",
|
| 147 |
+
"A poster",
|
| 148 |
+
makeArgs({ aspectRatio: "21:9", quality: "2k" }),
|
| 149 |
+
[],
|
| 150 |
+
),
|
| 151 |
+
{
|
| 152 |
+
prompt: "A poster",
|
| 153 |
+
size: "3K",
|
| 154 |
+
aspect_ratio: "21:9",
|
| 155 |
+
},
|
| 156 |
+
);
|
| 157 |
+
|
| 158 |
+
assert.deepEqual(
|
| 159 |
+
buildInput(
|
| 160 |
+
"wan-video/wan-2.7-image",
|
| 161 |
+
"A storyboard frame",
|
| 162 |
+
makeArgs({ aspectRatio: "16:9", quality: "2k" }),
|
| 163 |
+
[],
|
| 164 |
+
),
|
| 165 |
+
{
|
| 166 |
+
prompt: "A storyboard frame",
|
| 167 |
+
size: "2048*1152",
|
| 168 |
+
},
|
| 169 |
+
);
|
| 170 |
+
|
| 171 |
+
assert.deepEqual(
|
| 172 |
+
buildInput(
|
| 173 |
+
"wan-video/wan-2.7-image-pro",
|
| 174 |
+
"Blend these references",
|
| 175 |
+
makeArgs({ size: "2K", referenceImages: ["a.png", "b.png"] }),
|
| 176 |
+
["ref-a", "ref-b"],
|
| 177 |
+
),
|
| 178 |
+
{
|
| 179 |
+
prompt: "Blend these references",
|
| 180 |
+
size: "2K",
|
| 181 |
+
images: ["ref-a", "ref-b"],
|
| 182 |
+
},
|
| 183 |
+
);
|
| 184 |
+
});
|
| 185 |
+
|
| 186 |
+
test("Replicate validateArgs blocks misleading multi-output and unsupported family options locally", () => {
|
| 187 |
+
assert.throws(
|
| 188 |
+
() =>
|
| 189 |
+
validateArgs(
|
| 190 |
+
"google/nano-banana-2",
|
| 191 |
+
makeArgs({ n: 2 }),
|
| 192 |
+
),
|
| 193 |
+
/exactly one output image/,
|
| 194 |
+
);
|
| 195 |
+
|
| 196 |
+
assert.throws(
|
| 197 |
+
() =>
|
| 198 |
+
validateArgs(
|
| 199 |
+
"bytedance/seedream-4.5",
|
| 200 |
+
makeArgs({ size: "1K" }),
|
| 201 |
+
),
|
| 202 |
+
/2K, 4K, or an explicit WxH size/,
|
| 203 |
+
);
|
| 204 |
+
|
| 205 |
+
assert.throws(
|
| 206 |
+
() =>
|
| 207 |
+
validateArgs(
|
| 208 |
+
"bytedance/seedream-5-lite",
|
| 209 |
+
makeArgs({ size: "4K" }),
|
| 210 |
+
),
|
| 211 |
+
/supports 2K or 3K output/,
|
| 212 |
+
);
|
| 213 |
+
|
| 214 |
+
assert.throws(
|
| 215 |
+
() =>
|
| 216 |
+
validateArgs(
|
| 217 |
+
"wan-video/wan-2.7-image",
|
| 218 |
+
makeArgs({ referenceImages: new Array(10).fill("ref.png") }),
|
| 219 |
+
),
|
| 220 |
+
/at most 9 reference images/,
|
| 221 |
+
);
|
| 222 |
+
|
| 223 |
+
assert.throws(
|
| 224 |
+
() =>
|
| 225 |
+
validateArgs(
|
| 226 |
+
"wan-video/wan-2.7-image-pro",
|
| 227 |
+
makeArgs({ referenceImages: ["ref.png"], size: "4K" }),
|
| 228 |
+
),
|
| 229 |
+
/only supports 4K text-to-image/,
|
| 230 |
+
);
|
| 231 |
+
|
| 232 |
+
assert.throws(
|
| 233 |
+
() =>
|
| 234 |
+
validateArgs(
|
| 235 |
+
"stability-ai/sdxl",
|
| 236 |
+
makeArgs({ aspectRatio: "16:9" }),
|
| 237 |
+
),
|
| 238 |
+
/compatibility list/,
|
| 239 |
+
);
|
| 240 |
+
|
| 241 |
+
assert.doesNotThrow(() =>
|
| 242 |
+
validateArgs(
|
| 243 |
+
"google/nano-banana-2",
|
| 244 |
+
makeArgs({ imageSize: "2K", imageSizeSource: "config" }),
|
| 245 |
+
),
|
| 246 |
+
);
|
| 247 |
+
|
| 248 |
+
assert.throws(
|
| 249 |
+
() =>
|
| 250 |
+
validateArgs(
|
| 251 |
+
"google/nano-banana-2",
|
| 252 |
+
makeArgs({ imageSize: "2K", imageSizeSource: "cli" }),
|
| 253 |
+
),
|
| 254 |
+
/do not use --imageSize/,
|
| 255 |
+
);
|
| 256 |
+
|
| 257 |
+
assert.doesNotThrow(() =>
|
| 258 |
+
validateArgs(
|
| 259 |
+
"stability-ai/sdxl",
|
| 260 |
+
makeArgs({ aspectRatio: "16:9", aspectRatioSource: "config" }),
|
| 261 |
+
),
|
| 262 |
+
);
|
| 263 |
+
|
| 264 |
+
assert.throws(
|
| 265 |
+
() =>
|
| 266 |
+
validateArgs(
|
| 267 |
+
"stability-ai/sdxl",
|
| 268 |
+
makeArgs({ aspectRatio: "16:9", aspectRatioSource: "cli" }),
|
| 269 |
+
),
|
| 270 |
+
/compatibility list/,
|
| 271 |
+
);
|
| 272 |
+
|
| 273 |
+
assert.doesNotThrow(() =>
|
| 274 |
+
validateArgs(
|
| 275 |
+
"stability-ai/sdxl",
|
| 276 |
+
makeArgs(),
|
| 277 |
+
),
|
| 278 |
+
);
|
| 279 |
+
});
|
| 280 |
+
|
| 281 |
+
test("Replicate output extraction supports single outputs and rejects silent multi-image drops", () => {
|
| 282 |
+
assert.equal(
|
| 283 |
+
extractOutputUrl({ output: "https://example.com/a.png" } as never),
|
| 284 |
+
"https://example.com/a.png",
|
| 285 |
+
);
|
| 286 |
+
assert.equal(
|
| 287 |
+
extractOutputUrl({ output: ["https://example.com/b.png"] } as never),
|
| 288 |
+
"https://example.com/b.png",
|
| 289 |
+
);
|
| 290 |
+
assert.equal(
|
| 291 |
+
extractOutputUrl({ output: { url: "https://example.com/c.png" } } as never),
|
| 292 |
+
"https://example.com/c.png",
|
| 293 |
+
);
|
| 294 |
+
|
| 295 |
+
assert.throws(
|
| 296 |
+
() =>
|
| 297 |
+
extractOutputUrl({
|
| 298 |
+
output: [
|
| 299 |
+
"https://example.com/one.png",
|
| 300 |
+
"https://example.com/two.png",
|
| 301 |
+
],
|
| 302 |
+
} as never),
|
| 303 |
+
/supports saving exactly one image/,
|
| 304 |
+
);
|
| 305 |
+
|
| 306 |
+
assert.throws(
|
| 307 |
+
() => extractOutputUrl({ output: { invalid: true } } as never),
|
| 308 |
+
/Unexpected Replicate output format/,
|
| 309 |
+
);
|
| 310 |
+
});
|
baoyu_skills/baoyu-imagine/scripts/providers/replicate.ts
ADDED
|
@@ -0,0 +1,616 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import path from "node:path";
|
| 2 |
+
import { readFile } from "node:fs/promises";
|
| 3 |
+
import type { CliArgs } from "../types";
|
| 4 |
+
|
| 5 |
+
const DEFAULT_MODEL = "google/nano-banana-2";
|
| 6 |
+
const SYNC_WAIT_SECONDS = 60;
|
| 7 |
+
const POLL_INTERVAL_MS = 2000;
|
| 8 |
+
const MAX_POLL_MS = 300_000;
|
| 9 |
+
const DOCUMENTED_REPLICATE_ASPECT_RATIOS = new Set([
|
| 10 |
+
"1:1",
|
| 11 |
+
"2:3",
|
| 12 |
+
"3:2",
|
| 13 |
+
"3:4",
|
| 14 |
+
"4:3",
|
| 15 |
+
"5:4",
|
| 16 |
+
"4:5",
|
| 17 |
+
"9:16",
|
| 18 |
+
"16:9",
|
| 19 |
+
"21:9",
|
| 20 |
+
]);
|
| 21 |
+
|
| 22 |
+
export type ReplicateModelFamily =
|
| 23 |
+
| "nano-banana"
|
| 24 |
+
| "seedream45"
|
| 25 |
+
| "seedream5lite"
|
| 26 |
+
| "wan27image"
|
| 27 |
+
| "wan27imagepro"
|
| 28 |
+
| "unknown";
|
| 29 |
+
|
| 30 |
+
type PixelSize = {
|
| 31 |
+
width: number;
|
| 32 |
+
height: number;
|
| 33 |
+
};
|
| 34 |
+
|
| 35 |
+
type Seedream45Size = "2K" | "4K" | { width: number; height: number };
|
| 36 |
+
|
| 37 |
+
export function getDefaultModel(): string {
|
| 38 |
+
return process.env.REPLICATE_IMAGE_MODEL || DEFAULT_MODEL;
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
function getApiToken(): string | null {
|
| 42 |
+
return process.env.REPLICATE_API_TOKEN || null;
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
function getBaseUrl(): string {
|
| 46 |
+
const base = process.env.REPLICATE_BASE_URL || "https://api.replicate.com";
|
| 47 |
+
return base.replace(/\/+$/g, "");
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
function normalizeModelId(model: string): string {
|
| 51 |
+
return model.trim().toLowerCase().split(":")[0]!;
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
export function getModelFamily(model: string): ReplicateModelFamily {
|
| 55 |
+
const normalized = normalizeModelId(model);
|
| 56 |
+
|
| 57 |
+
if (
|
| 58 |
+
normalized === "google/nano-banana" ||
|
| 59 |
+
normalized === "google/nano-banana-pro" ||
|
| 60 |
+
normalized === "google/nano-banana-2"
|
| 61 |
+
) {
|
| 62 |
+
return "nano-banana";
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
if (normalized === "bytedance/seedream-4.5") {
|
| 66 |
+
return "seedream45";
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
if (normalized === "bytedance/seedream-5-lite") {
|
| 70 |
+
return "seedream5lite";
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
if (normalized === "wan-video/wan-2.7-image") {
|
| 74 |
+
return "wan27image";
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
if (normalized === "wan-video/wan-2.7-image-pro") {
|
| 78 |
+
return "wan27imagepro";
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
return "unknown";
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
export function parseModelId(model: string): { owner: string; name: string; version: string | null } {
|
| 85 |
+
const [ownerName, version] = model.split(":");
|
| 86 |
+
const parts = ownerName!.split("/");
|
| 87 |
+
if (parts.length !== 2 || !parts[0] || !parts[1]) {
|
| 88 |
+
throw new Error(
|
| 89 |
+
`Invalid Replicate model format: "${model}". Expected "owner/name" or "owner/name:version".`
|
| 90 |
+
);
|
| 91 |
+
}
|
| 92 |
+
return { owner: parts[0], name: parts[1], version: version || null };
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
function parsePixelSize(value: string): PixelSize | null {
|
| 96 |
+
const match = value.trim().match(/^(\d+)\s*[xX*]\s*(\d+)$/);
|
| 97 |
+
if (!match) return null;
|
| 98 |
+
|
| 99 |
+
const width = parseInt(match[1]!, 10);
|
| 100 |
+
const height = parseInt(match[2]!, 10);
|
| 101 |
+
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
|
| 102 |
+
return null;
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
return { width, height };
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
function parseAspectRatio(value: string): PixelSize | null {
|
| 109 |
+
const match = value.trim().match(/^(\d+)\s*:\s*(\d+)$/);
|
| 110 |
+
if (!match) return null;
|
| 111 |
+
|
| 112 |
+
const width = parseInt(match[1]!, 10);
|
| 113 |
+
const height = parseInt(match[2]!, 10);
|
| 114 |
+
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
|
| 115 |
+
return null;
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
return { width, height };
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
function gcd(a: number, b: number): number {
|
| 122 |
+
let x = Math.abs(a);
|
| 123 |
+
let y = Math.abs(b);
|
| 124 |
+
|
| 125 |
+
while (y !== 0) {
|
| 126 |
+
const next = x % y;
|
| 127 |
+
x = y;
|
| 128 |
+
y = next;
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
return x || 1;
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
function inferAspectRatioFromSize(size: string): string | null {
|
| 135 |
+
const parsed = parsePixelSize(size);
|
| 136 |
+
if (!parsed) return null;
|
| 137 |
+
|
| 138 |
+
const divisor = gcd(parsed.width, parsed.height);
|
| 139 |
+
const normalized = `${parsed.width / divisor}:${parsed.height / divisor}`;
|
| 140 |
+
if (!DOCUMENTED_REPLICATE_ASPECT_RATIOS.has(normalized)) {
|
| 141 |
+
return null;
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
return normalized;
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
function getQualityPreset(args: CliArgs): "normal" | "2k" {
|
| 148 |
+
return args.quality === "normal" ? "normal" : "2k";
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
function validateDocumentedAspectRatio(model: string, aspectRatio: string): void {
|
| 152 |
+
if (aspectRatio === "match_input_image") {
|
| 153 |
+
return;
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
if (DOCUMENTED_REPLICATE_ASPECT_RATIOS.has(aspectRatio)) {
|
| 157 |
+
return;
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
throw new Error(
|
| 161 |
+
`Replicate model ${model} does not support aspect ratio ${aspectRatio}. Supported values: ${Array.from(DOCUMENTED_REPLICATE_ASPECT_RATIOS).join(", ")}`
|
| 162 |
+
);
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
function getRequestedAspectRatio(model: string, args: CliArgs): string | null {
|
| 166 |
+
if (args.aspectRatio) {
|
| 167 |
+
validateDocumentedAspectRatio(model, args.aspectRatio);
|
| 168 |
+
return args.aspectRatio;
|
| 169 |
+
}
|
| 170 |
+
|
| 171 |
+
if (!args.size) return null;
|
| 172 |
+
|
| 173 |
+
const inferred = inferAspectRatioFromSize(args.size);
|
| 174 |
+
if (!inferred) {
|
| 175 |
+
throw new Error(
|
| 176 |
+
`Replicate model ${model} cannot derive a supported aspect ratio from --size ${args.size}. Use one of: ${Array.from(DOCUMENTED_REPLICATE_ASPECT_RATIOS).join(", ")}`
|
| 177 |
+
);
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
return inferred;
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
function getNanoBananaResolution(args: CliArgs): "1K" | "2K" {
|
| 184 |
+
if (args.size) {
|
| 185 |
+
const parsed = parsePixelSize(args.size);
|
| 186 |
+
if (!parsed) {
|
| 187 |
+
throw new Error("Replicate nano-banana --size must be in WxH format, for example 1536x1024.");
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
const longestEdge = Math.max(parsed.width, parsed.height);
|
| 191 |
+
if (longestEdge <= 1024) return "1K";
|
| 192 |
+
if (longestEdge <= 2048) return "2K";
|
| 193 |
+
throw new Error("Replicate nano-banana only supports sizes that map to 1K or 2K output.");
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
return getQualityPreset(args) === "normal" ? "1K" : "2K";
|
| 197 |
+
}
|
| 198 |
+
|
| 199 |
+
function resolveSeedream45Size(args: CliArgs): Seedream45Size {
|
| 200 |
+
if (args.size) {
|
| 201 |
+
const upper = args.size.trim().toUpperCase();
|
| 202 |
+
if (upper === "2K" || upper === "4K") {
|
| 203 |
+
return upper;
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
const parsed = parsePixelSize(args.size);
|
| 207 |
+
if (!parsed) {
|
| 208 |
+
throw new Error("Replicate Seedream 4.5 --size must be 2K, 4K, or an explicit WxH size.");
|
| 209 |
+
}
|
| 210 |
+
if (parsed.width < 1024 || parsed.width > 4096 || parsed.height < 1024 || parsed.height > 4096) {
|
| 211 |
+
throw new Error("Replicate Seedream 4.5 custom --size must keep width and height between 1024 and 4096.");
|
| 212 |
+
}
|
| 213 |
+
return parsed;
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
return getQualityPreset(args) === "normal" ? "2K" : "4K";
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
function resolveSeedream5LiteSize(args: CliArgs): "2K" | "3K" {
|
| 220 |
+
if (args.size) {
|
| 221 |
+
const upper = args.size.trim().toUpperCase();
|
| 222 |
+
if (upper === "2K" || upper === "3K") {
|
| 223 |
+
return upper;
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
throw new Error("Replicate Seedream 5 Lite currently supports 2K or 3K output in this tool.");
|
| 227 |
+
}
|
| 228 |
+
|
| 229 |
+
return getQualityPreset(args) === "normal" ? "2K" : "3K";
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
function formatCustomWanSize(size: PixelSize): string {
|
| 233 |
+
return `${size.width}*${size.height}`;
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
function resolveWanSizeFromAspectRatio(
|
| 237 |
+
aspectRatio: string,
|
| 238 |
+
maxDimension: number,
|
| 239 |
+
): string {
|
| 240 |
+
const parsedRatio = parseAspectRatio(aspectRatio);
|
| 241 |
+
if (!parsedRatio) {
|
| 242 |
+
throw new Error(`Replicate Wan aspect ratio must be in W:H format, got ${aspectRatio}.`);
|
| 243 |
+
}
|
| 244 |
+
|
| 245 |
+
const scale = Math.min(maxDimension / parsedRatio.width, maxDimension / parsedRatio.height);
|
| 246 |
+
const width = Math.max(1, Math.floor(parsedRatio.width * scale));
|
| 247 |
+
const height = Math.max(1, Math.floor(parsedRatio.height * scale));
|
| 248 |
+
return formatCustomWanSize({ width, height });
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
function resolveWanSize(family: "wan27image" | "wan27imagepro", args: CliArgs): "1K" | "2K" | "4K" | string {
|
| 252 |
+
const referenceMode = args.referenceImages.length > 0;
|
| 253 |
+
const maxDimension = family === "wan27imagepro" && !referenceMode ? 4096 : 2048;
|
| 254 |
+
|
| 255 |
+
if (args.size) {
|
| 256 |
+
const upper = args.size.trim().toUpperCase();
|
| 257 |
+
if (upper === "1K" || upper === "2K" || upper === "4K") {
|
| 258 |
+
if (upper === "4K" && family !== "wan27imagepro") {
|
| 259 |
+
throw new Error("Replicate Wan 2.7 Image only supports 1K, 2K, or custom sizes up to 2048px.");
|
| 260 |
+
}
|
| 261 |
+
if (upper === "4K" && referenceMode) {
|
| 262 |
+
throw new Error("Replicate Wan 2.7 Image Pro only supports 4K text-to-image. Remove --ref or lower the size.");
|
| 263 |
+
}
|
| 264 |
+
return upper;
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
const parsed = parsePixelSize(args.size);
|
| 268 |
+
if (!parsed) {
|
| 269 |
+
throw new Error("Replicate Wan --size must be 1K, 2K, 4K, or an explicit WxH size.");
|
| 270 |
+
}
|
| 271 |
+
if (parsed.width > maxDimension || parsed.height > maxDimension) {
|
| 272 |
+
throw new Error(
|
| 273 |
+
`Replicate ${family === "wan27imagepro" ? "Wan 2.7 Image Pro" : "Wan 2.7 Image"} custom --size must keep width and height at or below ${maxDimension}px in the current mode.`
|
| 274 |
+
);
|
| 275 |
+
}
|
| 276 |
+
return formatCustomWanSize(parsed);
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
if (args.aspectRatio) {
|
| 280 |
+
return resolveWanSizeFromAspectRatio(
|
| 281 |
+
args.aspectRatio,
|
| 282 |
+
getQualityPreset(args) === "normal" ? 1024 : 2048,
|
| 283 |
+
);
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
return getQualityPreset(args) === "normal" ? "1K" : "2K";
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
function buildNanoBananaInput(
|
| 290 |
+
prompt: string,
|
| 291 |
+
model: string,
|
| 292 |
+
args: CliArgs,
|
| 293 |
+
referenceImages: string[],
|
| 294 |
+
): Record<string, unknown> {
|
| 295 |
+
const input: Record<string, unknown> = {
|
| 296 |
+
prompt,
|
| 297 |
+
resolution: getNanoBananaResolution(args),
|
| 298 |
+
output_format: "png",
|
| 299 |
+
};
|
| 300 |
+
|
| 301 |
+
const aspectRatio = getRequestedAspectRatio(model, args);
|
| 302 |
+
if (aspectRatio) {
|
| 303 |
+
input.aspect_ratio = aspectRatio;
|
| 304 |
+
} else if (referenceImages.length > 0) {
|
| 305 |
+
input.aspect_ratio = "match_input_image";
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
if (referenceImages.length > 0) {
|
| 309 |
+
input.image_input = referenceImages;
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
return input;
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
function buildSeedreamInput(
|
| 316 |
+
family: "seedream45" | "seedream5lite",
|
| 317 |
+
prompt: string,
|
| 318 |
+
model: string,
|
| 319 |
+
args: CliArgs,
|
| 320 |
+
referenceImages: string[],
|
| 321 |
+
): Record<string, unknown> {
|
| 322 |
+
const size = family === "seedream45" ? resolveSeedream45Size(args) : resolveSeedream5LiteSize(args);
|
| 323 |
+
const input: Record<string, unknown> = {
|
| 324 |
+
prompt,
|
| 325 |
+
};
|
| 326 |
+
|
| 327 |
+
if (family === "seedream45" && typeof size === "object") {
|
| 328 |
+
input.size = "custom";
|
| 329 |
+
input.width = size.width;
|
| 330 |
+
input.height = size.height;
|
| 331 |
+
} else {
|
| 332 |
+
input.size = size;
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
if (referenceImages.length > 0) {
|
| 336 |
+
input.image_input = referenceImages;
|
| 337 |
+
}
|
| 338 |
+
|
| 339 |
+
if (args.aspectRatio) {
|
| 340 |
+
validateDocumentedAspectRatio(model, args.aspectRatio);
|
| 341 |
+
input.aspect_ratio = args.aspectRatio;
|
| 342 |
+
} else if (referenceImages.length > 0 && family === "seedream45") {
|
| 343 |
+
input.aspect_ratio = "match_input_image";
|
| 344 |
+
}
|
| 345 |
+
|
| 346 |
+
return input;
|
| 347 |
+
}
|
| 348 |
+
|
| 349 |
+
function buildWanInput(
|
| 350 |
+
family: "wan27image" | "wan27imagepro",
|
| 351 |
+
prompt: string,
|
| 352 |
+
args: CliArgs,
|
| 353 |
+
referenceImages: string[],
|
| 354 |
+
): Record<string, unknown> {
|
| 355 |
+
const input: Record<string, unknown> = {
|
| 356 |
+
prompt,
|
| 357 |
+
size: resolveWanSize(family, args),
|
| 358 |
+
};
|
| 359 |
+
|
| 360 |
+
if (referenceImages.length > 0) {
|
| 361 |
+
input.images = referenceImages;
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
return input;
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
export function validateArgs(model: string, args: CliArgs): void {
|
| 368 |
+
parseModelId(model);
|
| 369 |
+
|
| 370 |
+
if (args.n !== 1) {
|
| 371 |
+
throw new Error("Replicate integration currently supports exactly one output image per request. Remove --n or use --n 1.");
|
| 372 |
+
}
|
| 373 |
+
|
| 374 |
+
if (args.imageSize && args.imageSizeSource !== "config") {
|
| 375 |
+
throw new Error("Replicate models in baoyu-image-gen do not use --imageSize. Use --quality, --ar, or --size instead.");
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
const family = getModelFamily(model);
|
| 379 |
+
|
| 380 |
+
if (family === "nano-banana") {
|
| 381 |
+
if (args.referenceImages.length > 14) {
|
| 382 |
+
throw new Error("Replicate nano-banana supports at most 14 reference images.");
|
| 383 |
+
}
|
| 384 |
+
if (args.aspectRatio) {
|
| 385 |
+
validateDocumentedAspectRatio(model, args.aspectRatio);
|
| 386 |
+
}
|
| 387 |
+
if (args.size) {
|
| 388 |
+
getRequestedAspectRatio(model, args);
|
| 389 |
+
getNanoBananaResolution(args);
|
| 390 |
+
}
|
| 391 |
+
return;
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
if (family === "seedream45") {
|
| 395 |
+
if (args.referenceImages.length > 14) {
|
| 396 |
+
throw new Error("Replicate Seedream 4.5 supports at most 14 reference images.");
|
| 397 |
+
}
|
| 398 |
+
if (args.aspectRatio) {
|
| 399 |
+
validateDocumentedAspectRatio(model, args.aspectRatio);
|
| 400 |
+
}
|
| 401 |
+
resolveSeedream45Size(args);
|
| 402 |
+
return;
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
if (family === "seedream5lite") {
|
| 406 |
+
if (args.referenceImages.length > 14) {
|
| 407 |
+
throw new Error("Replicate Seedream 5 Lite supports at most 14 reference images.");
|
| 408 |
+
}
|
| 409 |
+
if (args.aspectRatio) {
|
| 410 |
+
validateDocumentedAspectRatio(model, args.aspectRatio);
|
| 411 |
+
}
|
| 412 |
+
resolveSeedream5LiteSize(args);
|
| 413 |
+
return;
|
| 414 |
+
}
|
| 415 |
+
|
| 416 |
+
if (family === "wan27image" || family === "wan27imagepro") {
|
| 417 |
+
if (args.referenceImages.length > 9) {
|
| 418 |
+
throw new Error("Replicate Wan 2.7 image models support at most 9 reference images.");
|
| 419 |
+
}
|
| 420 |
+
if (args.aspectRatio) {
|
| 421 |
+
const parsed = parseAspectRatio(args.aspectRatio);
|
| 422 |
+
if (!parsed) {
|
| 423 |
+
throw new Error(`Replicate Wan aspect ratio must be in W:H format, got ${args.aspectRatio}.`);
|
| 424 |
+
}
|
| 425 |
+
}
|
| 426 |
+
resolveWanSize(family, args);
|
| 427 |
+
return;
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
const hasExplicitAspectRatio = !!args.aspectRatio && args.aspectRatioSource !== "config";
|
| 431 |
+
|
| 432 |
+
if (args.referenceImages.length > 0 || hasExplicitAspectRatio || args.size) {
|
| 433 |
+
throw new Error(
|
| 434 |
+
`Replicate model ${model} is not in the baoyu-image-gen compatibility list. Supported families: google/nano-banana*, bytedance/seedream-4.5, bytedance/seedream-5-lite, wan-video/wan-2.7-image, wan-video/wan-2.7-image-pro.`
|
| 435 |
+
);
|
| 436 |
+
}
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
export function getDefaultOutputExtension(model: string): ".png" {
|
| 440 |
+
const _family = getModelFamily(model);
|
| 441 |
+
return ".png";
|
| 442 |
+
}
|
| 443 |
+
|
| 444 |
+
export function buildInput(
|
| 445 |
+
model: string,
|
| 446 |
+
prompt: string,
|
| 447 |
+
args: CliArgs,
|
| 448 |
+
referenceImages: string[],
|
| 449 |
+
): Record<string, unknown> {
|
| 450 |
+
const family = getModelFamily(model);
|
| 451 |
+
|
| 452 |
+
if (family === "nano-banana") {
|
| 453 |
+
return buildNanoBananaInput(prompt, model, args, referenceImages);
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
if (family === "seedream45" || family === "seedream5lite") {
|
| 457 |
+
return buildSeedreamInput(family, prompt, model, args, referenceImages);
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
if (family === "wan27image" || family === "wan27imagepro") {
|
| 461 |
+
return buildWanInput(family, prompt, args, referenceImages);
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
return { prompt };
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
async function readImageAsDataUrl(p: string): Promise<string> {
|
| 468 |
+
const buf = await readFile(p);
|
| 469 |
+
const ext = path.extname(p).toLowerCase();
|
| 470 |
+
let mimeType = "image/png";
|
| 471 |
+
if (ext === ".jpg" || ext === ".jpeg") mimeType = "image/jpeg";
|
| 472 |
+
else if (ext === ".gif") mimeType = "image/gif";
|
| 473 |
+
else if (ext === ".webp") mimeType = "image/webp";
|
| 474 |
+
return `data:${mimeType};base64,${buf.toString("base64")}`;
|
| 475 |
+
}
|
| 476 |
+
|
| 477 |
+
type PredictionResponse = {
|
| 478 |
+
id: string;
|
| 479 |
+
status: string;
|
| 480 |
+
output: unknown;
|
| 481 |
+
error: string | null;
|
| 482 |
+
urls?: { get?: string };
|
| 483 |
+
};
|
| 484 |
+
|
| 485 |
+
async function createPrediction(
|
| 486 |
+
apiToken: string,
|
| 487 |
+
model: { owner: string; name: string; version: string | null },
|
| 488 |
+
input: Record<string, unknown>,
|
| 489 |
+
sync: boolean
|
| 490 |
+
): Promise<PredictionResponse> {
|
| 491 |
+
const baseUrl = getBaseUrl();
|
| 492 |
+
|
| 493 |
+
let url: string;
|
| 494 |
+
const body: Record<string, unknown> = { input };
|
| 495 |
+
|
| 496 |
+
if (model.version) {
|
| 497 |
+
url = `${baseUrl}/v1/predictions`;
|
| 498 |
+
body.version = model.version;
|
| 499 |
+
} else {
|
| 500 |
+
url = `${baseUrl}/v1/models/${model.owner}/${model.name}/predictions`;
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
const headers: Record<string, string> = {
|
| 504 |
+
Authorization: `Bearer ${apiToken}`,
|
| 505 |
+
"Content-Type": "application/json",
|
| 506 |
+
};
|
| 507 |
+
|
| 508 |
+
if (sync) {
|
| 509 |
+
headers["Prefer"] = `wait=${SYNC_WAIT_SECONDS}`;
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
const res = await fetch(url, {
|
| 513 |
+
method: "POST",
|
| 514 |
+
headers,
|
| 515 |
+
body: JSON.stringify(body),
|
| 516 |
+
});
|
| 517 |
+
|
| 518 |
+
if (!res.ok) {
|
| 519 |
+
const err = await res.text();
|
| 520 |
+
throw new Error(`Replicate API error (${res.status}): ${err}`);
|
| 521 |
+
}
|
| 522 |
+
|
| 523 |
+
return (await res.json()) as PredictionResponse;
|
| 524 |
+
}
|
| 525 |
+
|
| 526 |
+
async function pollPrediction(apiToken: string, getUrl: string): Promise<PredictionResponse> {
|
| 527 |
+
const start = Date.now();
|
| 528 |
+
|
| 529 |
+
while (Date.now() - start < MAX_POLL_MS) {
|
| 530 |
+
const res = await fetch(getUrl, {
|
| 531 |
+
headers: { Authorization: `Bearer ${apiToken}` },
|
| 532 |
+
});
|
| 533 |
+
|
| 534 |
+
if (!res.ok) {
|
| 535 |
+
const err = await res.text();
|
| 536 |
+
throw new Error(`Replicate poll error (${res.status}): ${err}`);
|
| 537 |
+
}
|
| 538 |
+
|
| 539 |
+
const prediction = (await res.json()) as PredictionResponse;
|
| 540 |
+
|
| 541 |
+
if (prediction.status === "succeeded") return prediction;
|
| 542 |
+
if (prediction.status === "failed" || prediction.status === "canceled") {
|
| 543 |
+
throw new Error(`Replicate prediction ${prediction.status}: ${prediction.error || "unknown error"}`);
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
await new Promise((r) => setTimeout(r, POLL_INTERVAL_MS));
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
throw new Error(`Replicate prediction timed out after ${MAX_POLL_MS / 1000}s`);
|
| 550 |
+
}
|
| 551 |
+
|
| 552 |
+
export function extractOutputUrl(prediction: PredictionResponse): string {
|
| 553 |
+
const output = prediction.output;
|
| 554 |
+
|
| 555 |
+
if (typeof output === "string") return output;
|
| 556 |
+
|
| 557 |
+
if (Array.isArray(output)) {
|
| 558 |
+
if (output.length !== 1) {
|
| 559 |
+
throw new Error(
|
| 560 |
+
`Replicate returned ${output.length} outputs, but baoyu-image-gen currently supports saving exactly one image per request.`
|
| 561 |
+
);
|
| 562 |
+
}
|
| 563 |
+
const first = output[0];
|
| 564 |
+
if (typeof first === "string") return first;
|
| 565 |
+
}
|
| 566 |
+
|
| 567 |
+
if (output && typeof output === "object" && "url" in output) {
|
| 568 |
+
const url = (output as Record<string, unknown>).url;
|
| 569 |
+
if (typeof url === "string") return url;
|
| 570 |
+
}
|
| 571 |
+
|
| 572 |
+
throw new Error(`Unexpected Replicate output format: ${JSON.stringify(output)}`);
|
| 573 |
+
}
|
| 574 |
+
|
| 575 |
+
async function downloadImage(url: string): Promise<Uint8Array> {
|
| 576 |
+
const res = await fetch(url);
|
| 577 |
+
if (!res.ok) throw new Error(`Failed to download image from Replicate: ${res.status}`);
|
| 578 |
+
const buf = await res.arrayBuffer();
|
| 579 |
+
return new Uint8Array(buf);
|
| 580 |
+
}
|
| 581 |
+
|
| 582 |
+
export async function generateImage(
|
| 583 |
+
prompt: string,
|
| 584 |
+
model: string,
|
| 585 |
+
args: CliArgs
|
| 586 |
+
): Promise<Uint8Array> {
|
| 587 |
+
const apiToken = getApiToken();
|
| 588 |
+
if (!apiToken) throw new Error("REPLICATE_API_TOKEN is required. Get one at https://replicate.com/account/api-tokens");
|
| 589 |
+
|
| 590 |
+
const parsedModel = parseModelId(model);
|
| 591 |
+
validateArgs(model, args);
|
| 592 |
+
|
| 593 |
+
const refDataUrls: string[] = [];
|
| 594 |
+
for (const refPath of args.referenceImages) {
|
| 595 |
+
refDataUrls.push(await readImageAsDataUrl(refPath));
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
+
const input = buildInput(model, prompt, args, refDataUrls);
|
| 599 |
+
|
| 600 |
+
console.log(`Generating image with Replicate (${model})...`);
|
| 601 |
+
|
| 602 |
+
let prediction = await createPrediction(apiToken, parsedModel, input, true);
|
| 603 |
+
|
| 604 |
+
if (prediction.status !== "succeeded") {
|
| 605 |
+
if (!prediction.urls?.get) {
|
| 606 |
+
throw new Error("Replicate prediction did not return a poll URL");
|
| 607 |
+
}
|
| 608 |
+
console.log("Waiting for prediction to complete...");
|
| 609 |
+
prediction = await pollPrediction(apiToken, prediction.urls.get);
|
| 610 |
+
}
|
| 611 |
+
|
| 612 |
+
console.log("Generation completed.");
|
| 613 |
+
|
| 614 |
+
const outputUrl = extractOutputUrl(prediction);
|
| 615 |
+
return downloadImage(outputUrl);
|
| 616 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/providers/seedream.test.ts
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 4 |
+
import path from "node:path";
|
| 5 |
+
import test, { type TestContext } from "node:test";
|
| 6 |
+
|
| 7 |
+
import type { CliArgs } from "../types.ts";
|
| 8 |
+
import {
|
| 9 |
+
buildImageInput,
|
| 10 |
+
buildRequestBody,
|
| 11 |
+
generateImage,
|
| 12 |
+
getDefaultOutputExtension,
|
| 13 |
+
resolveSeedreamSize,
|
| 14 |
+
validateArgs,
|
| 15 |
+
} from "./seedream.ts";
|
| 16 |
+
|
| 17 |
+
function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
| 18 |
+
return {
|
| 19 |
+
prompt: null,
|
| 20 |
+
promptFiles: [],
|
| 21 |
+
imagePath: null,
|
| 22 |
+
provider: null,
|
| 23 |
+
model: null,
|
| 24 |
+
aspectRatio: null,
|
| 25 |
+
size: null,
|
| 26 |
+
quality: null,
|
| 27 |
+
imageSize: null,
|
| 28 |
+
imageApiDialect: null,
|
| 29 |
+
referenceImages: [],
|
| 30 |
+
n: 1,
|
| 31 |
+
batchFile: null,
|
| 32 |
+
jobs: null,
|
| 33 |
+
json: false,
|
| 34 |
+
help: false,
|
| 35 |
+
...overrides,
|
| 36 |
+
};
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
function useEnv(
|
| 40 |
+
t: TestContext,
|
| 41 |
+
values: Record<string, string | null>,
|
| 42 |
+
): void {
|
| 43 |
+
const previous = new Map<string, string | undefined>();
|
| 44 |
+
for (const [key, value] of Object.entries(values)) {
|
| 45 |
+
previous.set(key, process.env[key]);
|
| 46 |
+
if (value == null) {
|
| 47 |
+
delete process.env[key];
|
| 48 |
+
} else {
|
| 49 |
+
process.env[key] = value;
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
t.after(() => {
|
| 54 |
+
for (const [key, value] of previous.entries()) {
|
| 55 |
+
if (value == null) {
|
| 56 |
+
delete process.env[key];
|
| 57 |
+
} else {
|
| 58 |
+
process.env[key] = value;
|
| 59 |
+
}
|
| 60 |
+
}
|
| 61 |
+
});
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
async function makeTempPng(t: TestContext, name: string): Promise<string> {
|
| 65 |
+
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "seedream-test-"));
|
| 66 |
+
t.after(() => fs.rm(dir, { recursive: true, force: true }));
|
| 67 |
+
|
| 68 |
+
const filePath = path.join(dir, name);
|
| 69 |
+
const png1x1 =
|
| 70 |
+
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a7m0AAAAASUVORK5CYII=";
|
| 71 |
+
await fs.writeFile(filePath, Buffer.from(png1x1, "base64"));
|
| 72 |
+
return filePath;
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
test("Seedream request body and default extensions follow official model capabilities", () => {
|
| 76 |
+
const five = buildRequestBody(
|
| 77 |
+
"A robot illustrator",
|
| 78 |
+
"doubao-seedream-5-0-260128",
|
| 79 |
+
makeArgs(),
|
| 80 |
+
);
|
| 81 |
+
assert.equal(five.size, "2K");
|
| 82 |
+
assert.equal(five.response_format, "url");
|
| 83 |
+
assert.equal(five.output_format, "png");
|
| 84 |
+
assert.equal(getDefaultOutputExtension("doubao-seedream-5-0-260128"), ".png");
|
| 85 |
+
|
| 86 |
+
const fourFive = buildRequestBody(
|
| 87 |
+
"A robot illustrator",
|
| 88 |
+
"doubao-seedream-4-5-251128",
|
| 89 |
+
makeArgs(),
|
| 90 |
+
);
|
| 91 |
+
assert.equal(fourFive.size, "2K");
|
| 92 |
+
assert.equal(fourFive.response_format, "url");
|
| 93 |
+
assert.ok(!("output_format" in fourFive));
|
| 94 |
+
assert.equal(getDefaultOutputExtension("doubao-seedream-4-5-251128"), ".jpg");
|
| 95 |
+
|
| 96 |
+
assert.throws(
|
| 97 |
+
() =>
|
| 98 |
+
buildRequestBody(
|
| 99 |
+
"Change the bubbles into hearts",
|
| 100 |
+
"doubao-seededit-3-0-i2i-250628",
|
| 101 |
+
makeArgs({ referenceImages: ["ref.png"] }),
|
| 102 |
+
"data:image/png;base64,AAAA",
|
| 103 |
+
),
|
| 104 |
+
/no longer supported/,
|
| 105 |
+
);
|
| 106 |
+
});
|
| 107 |
+
|
| 108 |
+
test("Seedream size selection validates model-specific presets", () => {
|
| 109 |
+
assert.equal(
|
| 110 |
+
resolveSeedreamSize("doubao-seedream-4-0-250828", makeArgs({ quality: "normal" })),
|
| 111 |
+
"1K",
|
| 112 |
+
);
|
| 113 |
+
assert.equal(
|
| 114 |
+
resolveSeedreamSize("doubao-seedream-3-0-t2i-250415", makeArgs({ quality: "2k" })),
|
| 115 |
+
"2048x2048",
|
| 116 |
+
);
|
| 117 |
+
|
| 118 |
+
assert.throws(
|
| 119 |
+
() =>
|
| 120 |
+
resolveSeedreamSize("doubao-seedream-5-0-260128", makeArgs({ size: "4K" })),
|
| 121 |
+
/only supports 2K, 3K/,
|
| 122 |
+
);
|
| 123 |
+
assert.throws(
|
| 124 |
+
() =>
|
| 125 |
+
resolveSeedreamSize("doubao-seedream-3-0-t2i-250415", makeArgs({ imageSize: "2K" })),
|
| 126 |
+
/only supports explicit WxH sizes/,
|
| 127 |
+
);
|
| 128 |
+
assert.throws(
|
| 129 |
+
() =>
|
| 130 |
+
resolveSeedreamSize("doubao-seededit-3-0-i2i-250628", makeArgs({ size: "1024x1024" })),
|
| 131 |
+
/no longer supported/,
|
| 132 |
+
);
|
| 133 |
+
});
|
| 134 |
+
|
| 135 |
+
test("Seedream reference-image support is model-specific", () => {
|
| 136 |
+
assert.doesNotThrow(() =>
|
| 137 |
+
validateArgs(
|
| 138 |
+
"doubao-seedream-5-0-260128",
|
| 139 |
+
makeArgs({ referenceImages: ["a.png", "b.png"] }),
|
| 140 |
+
),
|
| 141 |
+
);
|
| 142 |
+
|
| 143 |
+
assert.throws(
|
| 144 |
+
() =>
|
| 145 |
+
validateArgs(
|
| 146 |
+
"doubao-seedream-3-0-t2i-250415",
|
| 147 |
+
makeArgs({ referenceImages: ["a.png"] }),
|
| 148 |
+
),
|
| 149 |
+
/does not support reference images/,
|
| 150 |
+
);
|
| 151 |
+
|
| 152 |
+
assert.throws(
|
| 153 |
+
() =>
|
| 154 |
+
validateArgs(
|
| 155 |
+
"doubao-seededit-3-0-i2i-250628",
|
| 156 |
+
makeArgs(),
|
| 157 |
+
),
|
| 158 |
+
/no longer supported/,
|
| 159 |
+
);
|
| 160 |
+
|
| 161 |
+
assert.throws(
|
| 162 |
+
() =>
|
| 163 |
+
validateArgs(
|
| 164 |
+
"ep-20260315171508-t8br2",
|
| 165 |
+
makeArgs({ referenceImages: ["a.png"] }),
|
| 166 |
+
),
|
| 167 |
+
/require a known model ID/,
|
| 168 |
+
);
|
| 169 |
+
});
|
| 170 |
+
|
| 171 |
+
test("Seedream image input encodes local references as data URLs", async (t) => {
|
| 172 |
+
const refOne = await makeTempPng(t, "one.png");
|
| 173 |
+
const refTwo = await makeTempPng(t, "two.png");
|
| 174 |
+
|
| 175 |
+
const single = await buildImageInput("doubao-seedream-4-5-251128", [refOne]);
|
| 176 |
+
assert.match(String(single), /^data:image\/png;base64,/);
|
| 177 |
+
|
| 178 |
+
const multiple = await buildImageInput("doubao-seedream-5-0-260128", [refOne, refTwo]);
|
| 179 |
+
assert.ok(Array.isArray(multiple));
|
| 180 |
+
assert.equal(multiple.length, 2);
|
| 181 |
+
});
|
| 182 |
+
|
| 183 |
+
test("Seedream generateImage posts the documented response_format and downloads the returned URL", async (t) => {
|
| 184 |
+
useEnv(t, { ARK_API_KEY: "test-key", SEEDREAM_BASE_URL: null });
|
| 185 |
+
|
| 186 |
+
const originalFetch = globalThis.fetch;
|
| 187 |
+
t.after(() => {
|
| 188 |
+
globalThis.fetch = originalFetch;
|
| 189 |
+
});
|
| 190 |
+
|
| 191 |
+
const calls: Array<{
|
| 192 |
+
input: string;
|
| 193 |
+
init?: RequestInit;
|
| 194 |
+
}> = [];
|
| 195 |
+
|
| 196 |
+
globalThis.fetch = async (input, init) => {
|
| 197 |
+
calls.push({
|
| 198 |
+
input: String(input),
|
| 199 |
+
init,
|
| 200 |
+
});
|
| 201 |
+
|
| 202 |
+
if (calls.length === 1) {
|
| 203 |
+
return Response.json({
|
| 204 |
+
model: "doubao-seedream-4-5-251128",
|
| 205 |
+
created: 1740000000,
|
| 206 |
+
data: [
|
| 207 |
+
{
|
| 208 |
+
url: "https://example.com/generated-image",
|
| 209 |
+
size: "2048x2048",
|
| 210 |
+
},
|
| 211 |
+
],
|
| 212 |
+
usage: {
|
| 213 |
+
generated_images: 1,
|
| 214 |
+
output_tokens: 1,
|
| 215 |
+
total_tokens: 1,
|
| 216 |
+
},
|
| 217 |
+
});
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
return new Response(Uint8Array.from([7, 8, 9]), {
|
| 221 |
+
status: 200,
|
| 222 |
+
headers: { "Content-Type": "image/jpeg" },
|
| 223 |
+
});
|
| 224 |
+
};
|
| 225 |
+
|
| 226 |
+
const image = await generateImage(
|
| 227 |
+
"A robot illustrator",
|
| 228 |
+
"doubao-seedream-4-5-251128",
|
| 229 |
+
makeArgs(),
|
| 230 |
+
);
|
| 231 |
+
|
| 232 |
+
assert.deepEqual([...image], [7, 8, 9]);
|
| 233 |
+
assert.equal(calls.length, 2);
|
| 234 |
+
assert.equal(
|
| 235 |
+
calls[0]?.input,
|
| 236 |
+
"https://ark.cn-beijing.volces.com/api/v3/images/generations",
|
| 237 |
+
);
|
| 238 |
+
|
| 239 |
+
const requestBody = JSON.parse(String(calls[0]?.init?.body)) as Record<string, unknown>;
|
| 240 |
+
assert.equal(requestBody.model, "doubao-seedream-4-5-251128");
|
| 241 |
+
assert.equal(requestBody.size, "2K");
|
| 242 |
+
assert.equal(requestBody.response_format, "url");
|
| 243 |
+
assert.ok(!("output_format" in requestBody));
|
| 244 |
+
assert.equal(calls[1]?.input, "https://example.com/generated-image");
|
| 245 |
+
});
|
baoyu_skills/baoyu-imagine/scripts/providers/seedream.ts
ADDED
|
@@ -0,0 +1,341 @@
|
|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
|
| 1 |
+
import path from "node:path";
|
| 2 |
+
import { readFile } from "node:fs/promises";
|
| 3 |
+
|
| 4 |
+
import type { CliArgs } from "../types";
|
| 5 |
+
|
| 6 |
+
export type SeedreamModelFamily =
|
| 7 |
+
| "seedream5"
|
| 8 |
+
| "seedream45"
|
| 9 |
+
| "seedream40"
|
| 10 |
+
| "seedream30"
|
| 11 |
+
| "unknown";
|
| 12 |
+
|
| 13 |
+
type SeedreamRequestImage = string | string[];
|
| 14 |
+
|
| 15 |
+
type SeedreamRequestBody = {
|
| 16 |
+
model: string;
|
| 17 |
+
prompt: string;
|
| 18 |
+
size: string;
|
| 19 |
+
response_format: "url";
|
| 20 |
+
watermark: boolean;
|
| 21 |
+
image?: SeedreamRequestImage;
|
| 22 |
+
output_format?: "png";
|
| 23 |
+
};
|
| 24 |
+
|
| 25 |
+
type SeedreamImageResponse = {
|
| 26 |
+
model?: string;
|
| 27 |
+
created?: number;
|
| 28 |
+
data?: Array<{
|
| 29 |
+
url?: string;
|
| 30 |
+
b64_json?: string;
|
| 31 |
+
size?: string;
|
| 32 |
+
error?: {
|
| 33 |
+
code?: string;
|
| 34 |
+
message?: string;
|
| 35 |
+
};
|
| 36 |
+
}>;
|
| 37 |
+
usage?: {
|
| 38 |
+
generated_images: number;
|
| 39 |
+
output_tokens: number;
|
| 40 |
+
total_tokens: number;
|
| 41 |
+
};
|
| 42 |
+
error?: {
|
| 43 |
+
code?: string;
|
| 44 |
+
message?: string;
|
| 45 |
+
};
|
| 46 |
+
};
|
| 47 |
+
|
| 48 |
+
export function getDefaultModel(): string {
|
| 49 |
+
return process.env.SEEDREAM_IMAGE_MODEL || "doubao-seedream-5-0-260128";
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
function getApiKey(): string | null {
|
| 53 |
+
return process.env.ARK_API_KEY || null;
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
function getBaseUrl(): string {
|
| 57 |
+
return process.env.SEEDREAM_BASE_URL || "https://ark.cn-beijing.volces.com/api/v3";
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
function parsePixelSize(value: string): { width: number; height: number } | null {
|
| 61 |
+
const match = value.trim().match(/^(\d+)\s*[xX]\s*(\d+)$/);
|
| 62 |
+
if (!match) return null;
|
| 63 |
+
|
| 64 |
+
const width = parseInt(match[1]!, 10);
|
| 65 |
+
const height = parseInt(match[2]!, 10);
|
| 66 |
+
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
|
| 67 |
+
return null;
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
return { width, height };
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
function normalizePixelSize(value: string): string | null {
|
| 74 |
+
const parsed = parsePixelSize(value);
|
| 75 |
+
if (!parsed) return null;
|
| 76 |
+
return `${parsed.width}x${parsed.height}`;
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
function normalizeSizePreset(value: string): string | null {
|
| 80 |
+
const upper = value.trim().toUpperCase();
|
| 81 |
+
if (upper === "ADAPTIVE") return "adaptive";
|
| 82 |
+
if (upper === "1K" || upper === "2K" || upper === "3K" || upper === "4K") return upper;
|
| 83 |
+
return null;
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
function normalizeSizeValue(value: string): string | null {
|
| 87 |
+
return normalizeSizePreset(value) ?? normalizePixelSize(value);
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
function getMimeType(filename: string): string {
|
| 91 |
+
const ext = path.extname(filename).toLowerCase();
|
| 92 |
+
if (ext === ".jpg" || ext === ".jpeg") return "image/jpeg";
|
| 93 |
+
if (ext === ".webp") return "image/webp";
|
| 94 |
+
if (ext === ".gif") return "image/gif";
|
| 95 |
+
if (ext === ".bmp") return "image/bmp";
|
| 96 |
+
if (ext === ".tiff" || ext === ".tif") return "image/tiff";
|
| 97 |
+
return "image/png";
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
async function readImageAsDataUrl(filePath: string): Promise<string> {
|
| 101 |
+
const bytes = await readFile(filePath);
|
| 102 |
+
return `data:${getMimeType(filePath)};base64,${bytes.toString("base64")}`;
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
export function getModelFamily(model: string): SeedreamModelFamily {
|
| 106 |
+
const normalized = model.trim();
|
| 107 |
+
if (/^doubao-seedream-5-0(?:-lite)?-\d+$/.test(normalized)) return "seedream5";
|
| 108 |
+
if (/^doubao-seedream-4-5-\d+$/.test(normalized)) return "seedream45";
|
| 109 |
+
if (/^doubao-seedream-4-0-\d+$/.test(normalized)) return "seedream40";
|
| 110 |
+
if (/^doubao-seedream-3-0-t2i-\d+$/.test(normalized)) return "seedream30";
|
| 111 |
+
return "unknown";
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
function isRemovedSeededitModel(model: string): boolean {
|
| 115 |
+
return /^doubao-seededit-3-0-i2i-\d+$/.test(model.trim());
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
function assertSupportedModel(model: string): void {
|
| 119 |
+
if (isRemovedSeededitModel(model)) {
|
| 120 |
+
throw new Error(
|
| 121 |
+
`${model} is no longer supported. SeedEdit 3.0 support has been removed from this tool; use Seedream 5.0/4.5/4.0/3.0 instead.`
|
| 122 |
+
);
|
| 123 |
+
}
|
| 124 |
+
}
|
| 125 |
+
|
| 126 |
+
export function supportsReferenceImages(model: string): boolean {
|
| 127 |
+
const family = getModelFamily(model);
|
| 128 |
+
return family === "seedream5" || family === "seedream45" || family === "seedream40";
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
function supportsOutputFormat(model: string): boolean {
|
| 132 |
+
return getModelFamily(model) === "seedream5";
|
| 133 |
+
}
|
| 134 |
+
|
| 135 |
+
export function getDefaultOutputExtension(model: string): ".png" | ".jpg" {
|
| 136 |
+
assertSupportedModel(model);
|
| 137 |
+
return supportsOutputFormat(model) ? ".png" : ".jpg";
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
export function getDefaultSeedreamSize(model: string, args: CliArgs): string {
|
| 141 |
+
assertSupportedModel(model);
|
| 142 |
+
const family = getModelFamily(model);
|
| 143 |
+
|
| 144 |
+
if (family === "seedream5") return "2K";
|
| 145 |
+
if (family === "seedream45") return "2K";
|
| 146 |
+
if (family === "seedream40") return args.quality === "normal" ? "1K" : "2K";
|
| 147 |
+
if (family === "seedream30") return args.quality === "2k" ? "2048x2048" : "1024x1024";
|
| 148 |
+
return "2K";
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
export function resolveSeedreamSize(model: string, args: CliArgs): string {
|
| 152 |
+
assertSupportedModel(model);
|
| 153 |
+
const family = getModelFamily(model);
|
| 154 |
+
const requested = args.size || args.imageSize || null;
|
| 155 |
+
const normalized = requested ? normalizeSizeValue(requested) : null;
|
| 156 |
+
|
| 157 |
+
if (!normalized) {
|
| 158 |
+
return getDefaultSeedreamSize(model, args);
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
if (family === "seedream30") {
|
| 162 |
+
const pixelSize = normalizePixelSize(normalized);
|
| 163 |
+
if (!pixelSize) {
|
| 164 |
+
throw new Error("Seedream 3.0 only supports explicit WxH sizes such as 1024x1024.");
|
| 165 |
+
}
|
| 166 |
+
return pixelSize;
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
if (family === "seedream5") {
|
| 170 |
+
if (normalized === "4K" || normalized === "1K" || normalized === "adaptive") {
|
| 171 |
+
throw new Error("Seedream 5.0 only supports 2K, 3K, or explicit WxH sizes.");
|
| 172 |
+
}
|
| 173 |
+
return normalized;
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
if (family === "seedream45") {
|
| 177 |
+
if (normalized === "1K" || normalized === "3K" || normalized === "adaptive") {
|
| 178 |
+
throw new Error("Seedream 4.5 only supports 2K, 4K, or explicit WxH sizes.");
|
| 179 |
+
}
|
| 180 |
+
return normalized;
|
| 181 |
+
}
|
| 182 |
+
|
| 183 |
+
if (family === "seedream40") {
|
| 184 |
+
if (normalized === "3K" || normalized === "adaptive") {
|
| 185 |
+
throw new Error("Seedream 4.0 only supports 1K, 2K, 4K, or explicit WxH sizes.");
|
| 186 |
+
}
|
| 187 |
+
return normalized;
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
if (normalized === "adaptive") {
|
| 191 |
+
throw new Error("Adaptive size is not supported by Seedream image generation.");
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
if (normalized === "1K" || normalized === "3K" || normalized === "4K") {
|
| 195 |
+
throw new Error(
|
| 196 |
+
"Unknown Seedream model ID. Use a documented model ID or pass an explicit WxH size instead of preset imageSize."
|
| 197 |
+
);
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
return normalized;
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
export function validateArgs(model: string, args: CliArgs): void {
|
| 204 |
+
assertSupportedModel(model);
|
| 205 |
+
const family = getModelFamily(model);
|
| 206 |
+
const refCount = args.referenceImages.length;
|
| 207 |
+
|
| 208 |
+
if (refCount === 0) {
|
| 209 |
+
resolveSeedreamSize(model, args);
|
| 210 |
+
return;
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
if (family === "unknown") {
|
| 214 |
+
throw new Error(
|
| 215 |
+
"Reference images with Seedream require a known model ID. Use Seedream 5.0/4.5/4.0 model IDs instead of an endpoint ID."
|
| 216 |
+
);
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
if (!supportsReferenceImages(model)) {
|
| 220 |
+
throw new Error(`${model} does not support reference images.`);
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
if ((family === "seedream5" || family === "seedream45" || family === "seedream40") && refCount > 14) {
|
| 224 |
+
throw new Error(`${model} supports at most 14 reference images.`);
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
resolveSeedreamSize(model, args);
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
export async function buildImageInput(
|
| 231 |
+
model: string,
|
| 232 |
+
referenceImages: string[],
|
| 233 |
+
): Promise<SeedreamRequestImage | undefined> {
|
| 234 |
+
if (referenceImages.length === 0) return undefined;
|
| 235 |
+
assertSupportedModel(model);
|
| 236 |
+
|
| 237 |
+
const encoded = await Promise.all(referenceImages.map((refPath) => readImageAsDataUrl(refPath)));
|
| 238 |
+
|
| 239 |
+
return encoded.length === 1 ? encoded[0]! : encoded;
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
export function buildRequestBody(
|
| 243 |
+
prompt: string,
|
| 244 |
+
model: string,
|
| 245 |
+
args: CliArgs,
|
| 246 |
+
imageInput?: SeedreamRequestImage,
|
| 247 |
+
): SeedreamRequestBody {
|
| 248 |
+
validateArgs(model, args);
|
| 249 |
+
|
| 250 |
+
const requestBody: SeedreamRequestBody = {
|
| 251 |
+
model,
|
| 252 |
+
prompt,
|
| 253 |
+
size: resolveSeedreamSize(model, args),
|
| 254 |
+
response_format: "url",
|
| 255 |
+
watermark: false,
|
| 256 |
+
};
|
| 257 |
+
|
| 258 |
+
if (imageInput) {
|
| 259 |
+
requestBody.image = imageInput;
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
if (supportsOutputFormat(model)) {
|
| 263 |
+
requestBody.output_format = "png";
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
return requestBody;
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
async function downloadImage(url: string): Promise<Uint8Array> {
|
| 270 |
+
const imgResponse = await fetch(url);
|
| 271 |
+
if (!imgResponse.ok) {
|
| 272 |
+
throw new Error(`Failed to download image from ${url}`);
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
const buffer = await imgResponse.arrayBuffer();
|
| 276 |
+
return new Uint8Array(buffer);
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
export async function extractImageFromResponse(result: SeedreamImageResponse): Promise<Uint8Array> {
|
| 280 |
+
const first = result.data?.find((item) => item.url || item.b64_json || item.error);
|
| 281 |
+
|
| 282 |
+
if (!first) {
|
| 283 |
+
throw new Error("No image data in Seedream response");
|
| 284 |
+
}
|
| 285 |
+
|
| 286 |
+
if (first.error) {
|
| 287 |
+
throw new Error(first.error.message || "Seedream returned an image generation error");
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
if (first.b64_json) {
|
| 291 |
+
return Uint8Array.from(Buffer.from(first.b64_json, "base64"));
|
| 292 |
+
}
|
| 293 |
+
|
| 294 |
+
if (first.url) {
|
| 295 |
+
console.error(`Downloading image from ${first.url}...`);
|
| 296 |
+
return downloadImage(first.url);
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
throw new Error("No image URL or base64 data in Seedream response");
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
export async function generateImage(
|
| 303 |
+
prompt: string,
|
| 304 |
+
model: string,
|
| 305 |
+
args: CliArgs,
|
| 306 |
+
): Promise<Uint8Array> {
|
| 307 |
+
const apiKey = getApiKey();
|
| 308 |
+
if (!apiKey) {
|
| 309 |
+
throw new Error(
|
| 310 |
+
"ARK_API_KEY is required. " +
|
| 311 |
+
"Get your API key from https://console.volcengine.com/ark"
|
| 312 |
+
);
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
validateArgs(model, args);
|
| 316 |
+
const imageInput = await buildImageInput(model, args.referenceImages);
|
| 317 |
+
const requestBody = buildRequestBody(prompt, model, args, imageInput);
|
| 318 |
+
|
| 319 |
+
console.error(`Calling Seedream API (${model}) with size: ${requestBody.size}`);
|
| 320 |
+
|
| 321 |
+
const response = await fetch(`${getBaseUrl()}/images/generations`, {
|
| 322 |
+
method: "POST",
|
| 323 |
+
headers: {
|
| 324 |
+
"Content-Type": "application/json",
|
| 325 |
+
Authorization: `Bearer ${apiKey}`,
|
| 326 |
+
},
|
| 327 |
+
body: JSON.stringify(requestBody),
|
| 328 |
+
});
|
| 329 |
+
|
| 330 |
+
if (!response.ok) {
|
| 331 |
+
const err = await response.text();
|
| 332 |
+
throw new Error(`Seedream API error (${response.status}): ${err}`);
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
const result = (await response.json()) as SeedreamImageResponse;
|
| 336 |
+
if (result.error) {
|
| 337 |
+
throw new Error(result.error.message || "Seedream API returned an error");
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
return extractImageFromResponse(result);
|
| 341 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/providers/zai.test.ts
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import assert from "node:assert/strict";
|
| 2 |
+
import test, { type TestContext } from "node:test";
|
| 3 |
+
|
| 4 |
+
import type { CliArgs } from "../types.ts";
|
| 5 |
+
import {
|
| 6 |
+
buildRequestBody,
|
| 7 |
+
buildZaiUrl,
|
| 8 |
+
extractImageFromResponse,
|
| 9 |
+
getDefaultModel,
|
| 10 |
+
getModelFamily,
|
| 11 |
+
parseAspectRatio,
|
| 12 |
+
parseSize,
|
| 13 |
+
resolveSizeForModel,
|
| 14 |
+
validateArgs,
|
| 15 |
+
} from "./zai.ts";
|
| 16 |
+
|
| 17 |
+
function makeArgs(overrides: Partial<CliArgs> = {}): CliArgs {
|
| 18 |
+
return {
|
| 19 |
+
prompt: null,
|
| 20 |
+
promptFiles: [],
|
| 21 |
+
imagePath: null,
|
| 22 |
+
provider: null,
|
| 23 |
+
model: null,
|
| 24 |
+
aspectRatio: null,
|
| 25 |
+
size: null,
|
| 26 |
+
quality: null,
|
| 27 |
+
imageSize: null,
|
| 28 |
+
imageApiDialect: null,
|
| 29 |
+
referenceImages: [],
|
| 30 |
+
n: 1,
|
| 31 |
+
batchFile: null,
|
| 32 |
+
jobs: null,
|
| 33 |
+
json: false,
|
| 34 |
+
help: false,
|
| 35 |
+
...overrides,
|
| 36 |
+
};
|
| 37 |
+
}
|
| 38 |
+
|
| 39 |
+
function useEnv(
|
| 40 |
+
t: TestContext,
|
| 41 |
+
values: Record<string, string | null>,
|
| 42 |
+
): void {
|
| 43 |
+
const previous = new Map<string, string | undefined>();
|
| 44 |
+
for (const [key, value] of Object.entries(values)) {
|
| 45 |
+
previous.set(key, process.env[key]);
|
| 46 |
+
if (value == null) {
|
| 47 |
+
delete process.env[key];
|
| 48 |
+
} else {
|
| 49 |
+
process.env[key] = value;
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
t.after(() => {
|
| 54 |
+
for (const [key, value] of previous.entries()) {
|
| 55 |
+
if (value == null) {
|
| 56 |
+
delete process.env[key];
|
| 57 |
+
} else {
|
| 58 |
+
process.env[key] = value;
|
| 59 |
+
}
|
| 60 |
+
}
|
| 61 |
+
});
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
test("Z.AI default model prefers env override and otherwise uses glm-image", (t) => {
|
| 65 |
+
useEnv(t, {
|
| 66 |
+
ZAI_IMAGE_MODEL: null,
|
| 67 |
+
BIGMODEL_IMAGE_MODEL: null,
|
| 68 |
+
});
|
| 69 |
+
assert.equal(getDefaultModel(), "glm-image");
|
| 70 |
+
|
| 71 |
+
process.env.BIGMODEL_IMAGE_MODEL = "cogview-4-250304";
|
| 72 |
+
assert.equal(getDefaultModel(), "cogview-4-250304");
|
| 73 |
+
});
|
| 74 |
+
|
| 75 |
+
test("Z.AI URL builder normalizes host, v4 base, and full endpoint inputs", (t) => {
|
| 76 |
+
useEnv(t, { ZAI_BASE_URL: "https://api.z.ai" });
|
| 77 |
+
assert.equal(buildZaiUrl(), "https://api.z.ai/api/paas/v4/images/generations");
|
| 78 |
+
|
| 79 |
+
process.env.ZAI_BASE_URL = "https://proxy.example.com/api/paas/v4/";
|
| 80 |
+
assert.equal(buildZaiUrl(), "https://proxy.example.com/api/paas/v4/images/generations");
|
| 81 |
+
|
| 82 |
+
process.env.ZAI_BASE_URL = "https://proxy.example.com/custom/images/generations";
|
| 83 |
+
assert.equal(buildZaiUrl(), "https://proxy.example.com/custom/images/generations");
|
| 84 |
+
});
|
| 85 |
+
|
| 86 |
+
test("Z.AI model family and parsing helpers recognize documented formats", () => {
|
| 87 |
+
assert.equal(getModelFamily("glm-image"), "glm");
|
| 88 |
+
assert.equal(getModelFamily("cogview-4-250304"), "legacy");
|
| 89 |
+
assert.deepEqual(parseAspectRatio("16:9"), { width: 16, height: 9 });
|
| 90 |
+
assert.equal(parseAspectRatio("wide"), null);
|
| 91 |
+
assert.deepEqual(parseSize("1280x1280"), { width: 1280, height: 1280 });
|
| 92 |
+
assert.deepEqual(parseSize("1472*1088"), { width: 1472, height: 1088 });
|
| 93 |
+
assert.equal(parseSize("big"), null);
|
| 94 |
+
});
|
| 95 |
+
|
| 96 |
+
test("Z.AI size resolution follows documented recommended ratios and validates custom sizes", () => {
|
| 97 |
+
assert.equal(
|
| 98 |
+
resolveSizeForModel("glm-image", makeArgs({ aspectRatio: "16:9", quality: "2k" })),
|
| 99 |
+
"1728x960",
|
| 100 |
+
);
|
| 101 |
+
assert.equal(
|
| 102 |
+
resolveSizeForModel("cogview-4-250304", makeArgs({ aspectRatio: "4:3", quality: "normal" })),
|
| 103 |
+
"1152x864",
|
| 104 |
+
);
|
| 105 |
+
assert.equal(
|
| 106 |
+
resolveSizeForModel("glm-image", makeArgs({ size: "1568x1056", quality: "2k" })),
|
| 107 |
+
"1568x1056",
|
| 108 |
+
);
|
| 109 |
+
|
| 110 |
+
const uncommon = resolveSizeForModel(
|
| 111 |
+
"glm-image",
|
| 112 |
+
makeArgs({ aspectRatio: "5:2", quality: "normal" }),
|
| 113 |
+
);
|
| 114 |
+
const parsed = parseSize(uncommon);
|
| 115 |
+
assert.ok(parsed);
|
| 116 |
+
assert.ok(parsed.width % 32 === 0);
|
| 117 |
+
assert.ok(parsed.height % 32 === 0);
|
| 118 |
+
assert.ok(parsed.width * parsed.height <= 2 ** 22);
|
| 119 |
+
|
| 120 |
+
assert.throws(
|
| 121 |
+
() => resolveSizeForModel("glm-image", makeArgs({ size: "1000x1000", quality: "2k" })),
|
| 122 |
+
/between 1024 and 2048/,
|
| 123 |
+
);
|
| 124 |
+
assert.throws(
|
| 125 |
+
() => resolveSizeForModel("glm-image", makeArgs({ size: "1280x1260", quality: "2k" })),
|
| 126 |
+
/divisible by 32/,
|
| 127 |
+
);
|
| 128 |
+
assert.throws(
|
| 129 |
+
() => resolveSizeForModel("cogview-4-250304", makeArgs({ size: "2048x2048", quality: "2k" })),
|
| 130 |
+
/must not exceed 2\^21 total pixels/,
|
| 131 |
+
);
|
| 132 |
+
});
|
| 133 |
+
|
| 134 |
+
test("Z.AI validation rejects unsupported refs and multi-image requests", () => {
|
| 135 |
+
assert.throws(
|
| 136 |
+
() => validateArgs("glm-image", makeArgs({ referenceImages: ["ref.png"] })),
|
| 137 |
+
/text-to-image only/,
|
| 138 |
+
);
|
| 139 |
+
assert.throws(
|
| 140 |
+
() => validateArgs("glm-image", makeArgs({ n: 2 })),
|
| 141 |
+
/single image per request/,
|
| 142 |
+
);
|
| 143 |
+
});
|
| 144 |
+
|
| 145 |
+
test("Z.AI request body maps skill quality and resolved size into provider fields", () => {
|
| 146 |
+
const body = buildRequestBody(
|
| 147 |
+
"A cinematic science poster",
|
| 148 |
+
"glm-image",
|
| 149 |
+
makeArgs({ aspectRatio: "4:3", quality: "normal" }),
|
| 150 |
+
);
|
| 151 |
+
|
| 152 |
+
assert.deepEqual(body, {
|
| 153 |
+
model: "glm-image",
|
| 154 |
+
prompt: "A cinematic science poster",
|
| 155 |
+
quality: "standard",
|
| 156 |
+
size: "1472x1088",
|
| 157 |
+
});
|
| 158 |
+
});
|
| 159 |
+
|
| 160 |
+
test("Z.AI response extraction downloads the returned image URL", async (t) => {
|
| 161 |
+
const originalFetch = globalThis.fetch;
|
| 162 |
+
t.after(() => {
|
| 163 |
+
globalThis.fetch = originalFetch;
|
| 164 |
+
});
|
| 165 |
+
|
| 166 |
+
globalThis.fetch = async () =>
|
| 167 |
+
new Response(Uint8Array.from([1, 2, 3]), {
|
| 168 |
+
status: 200,
|
| 169 |
+
headers: { "Content-Type": "image/png" },
|
| 170 |
+
});
|
| 171 |
+
|
| 172 |
+
const image = await extractImageFromResponse({
|
| 173 |
+
data: [{ url: "https://cdn.example.com/glm-image.png" }],
|
| 174 |
+
});
|
| 175 |
+
assert.deepEqual([...image], [1, 2, 3]);
|
| 176 |
+
|
| 177 |
+
await assert.rejects(
|
| 178 |
+
() => extractImageFromResponse({ data: [{}] }),
|
| 179 |
+
/No image URL/,
|
| 180 |
+
);
|
| 181 |
+
});
|
baoyu_skills/baoyu-imagine/scripts/providers/zai.ts
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import type { CliArgs, Quality } from "../types";
|
| 2 |
+
|
| 3 |
+
type ZaiModelFamily = "glm" | "legacy";
|
| 4 |
+
|
| 5 |
+
type ZaiRequestBody = {
|
| 6 |
+
model: string;
|
| 7 |
+
prompt: string;
|
| 8 |
+
quality: "hd" | "standard";
|
| 9 |
+
size: string;
|
| 10 |
+
};
|
| 11 |
+
|
| 12 |
+
type ZaiResponse = {
|
| 13 |
+
data?: Array<{ url?: string }>;
|
| 14 |
+
};
|
| 15 |
+
|
| 16 |
+
const DEFAULT_MODEL = "glm-image";
|
| 17 |
+
const GLM_MAX_PIXELS = 2 ** 22;
|
| 18 |
+
const LEGACY_MAX_PIXELS = 2 ** 21;
|
| 19 |
+
const GLM_SIZE_STEP = 32;
|
| 20 |
+
const LEGACY_SIZE_STEP = 16;
|
| 21 |
+
|
| 22 |
+
const GLM_RECOMMENDED_SIZES: Record<string, string> = {
|
| 23 |
+
"1:1": "1280x1280",
|
| 24 |
+
"3:2": "1568x1056",
|
| 25 |
+
"2:3": "1056x1568",
|
| 26 |
+
"4:3": "1472x1088",
|
| 27 |
+
"3:4": "1088x1472",
|
| 28 |
+
"16:9": "1728x960",
|
| 29 |
+
"9:16": "960x1728",
|
| 30 |
+
};
|
| 31 |
+
|
| 32 |
+
const LEGACY_RECOMMENDED_SIZES: Record<string, string> = {
|
| 33 |
+
"1:1": "1024x1024",
|
| 34 |
+
"9:16": "768x1344",
|
| 35 |
+
"3:4": "864x1152",
|
| 36 |
+
"16:9": "1344x768",
|
| 37 |
+
"4:3": "1152x864",
|
| 38 |
+
"2:1": "1440x720",
|
| 39 |
+
"1:2": "720x1440",
|
| 40 |
+
};
|
| 41 |
+
|
| 42 |
+
export function getDefaultModel(): string {
|
| 43 |
+
return process.env.ZAI_IMAGE_MODEL || process.env.BIGMODEL_IMAGE_MODEL || DEFAULT_MODEL;
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
function getApiKey(): string | null {
|
| 47 |
+
return process.env.ZAI_API_KEY || process.env.BIGMODEL_API_KEY || null;
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
export function buildZaiUrl(): string {
|
| 51 |
+
const base = (process.env.ZAI_BASE_URL || process.env.BIGMODEL_BASE_URL || "https://api.z.ai/api/paas/v4")
|
| 52 |
+
.replace(/\/+$/g, "");
|
| 53 |
+
if (base.endsWith("/images/generations")) return base;
|
| 54 |
+
if (base.endsWith("/api/paas/v4")) return `${base}/images/generations`;
|
| 55 |
+
if (base.endsWith("/v4")) return `${base}/images/generations`;
|
| 56 |
+
return `${base}/api/paas/v4/images/generations`;
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
export function getModelFamily(model: string): ZaiModelFamily {
|
| 60 |
+
return model.trim().toLowerCase() === "glm-image" ? "glm" : "legacy";
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
export function parseAspectRatio(ar: string): { width: number; height: number } | null {
|
| 64 |
+
const match = ar.match(/^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/);
|
| 65 |
+
if (!match) return null;
|
| 66 |
+
const width = Number(match[1]);
|
| 67 |
+
const height = Number(match[2]);
|
| 68 |
+
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
|
| 69 |
+
return null;
|
| 70 |
+
}
|
| 71 |
+
return { width, height };
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
export function parseSize(size: string): { width: number; height: number } | null {
|
| 75 |
+
const match = size.trim().match(/^(\d+)\s*[xX*]\s*(\d+)$/);
|
| 76 |
+
if (!match) return null;
|
| 77 |
+
const width = parseInt(match[1]!, 10);
|
| 78 |
+
const height = parseInt(match[2]!, 10);
|
| 79 |
+
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
|
| 80 |
+
return null;
|
| 81 |
+
}
|
| 82 |
+
return { width, height };
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
function formatSize(width: number, height: number): string {
|
| 86 |
+
return `${width}x${height}`;
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
function roundToStep(value: number, step: number): number {
|
| 90 |
+
return Math.max(step, Math.round(value / step) * step);
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
function getRatioValue(ar: string): number | null {
|
| 94 |
+
const parsed = parseAspectRatio(ar);
|
| 95 |
+
if (!parsed) return null;
|
| 96 |
+
return parsed.width / parsed.height;
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
function findClosestRatioKey(ar: string, candidates: string[]): string | null {
|
| 100 |
+
const targetRatio = getRatioValue(ar);
|
| 101 |
+
if (targetRatio == null) return null;
|
| 102 |
+
|
| 103 |
+
let bestKey: string | null = null;
|
| 104 |
+
let bestDiff = Infinity;
|
| 105 |
+
for (const candidate of candidates) {
|
| 106 |
+
const candidateRatio = getRatioValue(candidate);
|
| 107 |
+
if (candidateRatio == null) continue;
|
| 108 |
+
const diff = Math.abs(candidateRatio - targetRatio);
|
| 109 |
+
if (diff < bestDiff) {
|
| 110 |
+
bestDiff = diff;
|
| 111 |
+
bestKey = candidate;
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
return bestDiff <= 0.05 ? bestKey : null;
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
function getTargetPixels(quality: Quality): number {
|
| 119 |
+
return quality === "normal" ? 1024 * 1024 : 1536 * 1536;
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
function fitToPixelBudget(
|
| 123 |
+
width: number,
|
| 124 |
+
height: number,
|
| 125 |
+
targetPixels: number,
|
| 126 |
+
maxPixels: number,
|
| 127 |
+
step: number,
|
| 128 |
+
): { width: number; height: number } {
|
| 129 |
+
let nextWidth = width;
|
| 130 |
+
let nextHeight = height;
|
| 131 |
+
const pixels = nextWidth * nextHeight;
|
| 132 |
+
|
| 133 |
+
if (pixels > maxPixels) {
|
| 134 |
+
const scale = Math.sqrt(maxPixels / pixels);
|
| 135 |
+
nextWidth *= scale;
|
| 136 |
+
nextHeight *= scale;
|
| 137 |
+
} else {
|
| 138 |
+
const scale = Math.sqrt(targetPixels / pixels);
|
| 139 |
+
nextWidth *= scale;
|
| 140 |
+
nextHeight *= scale;
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
let roundedWidth = roundToStep(nextWidth, step);
|
| 144 |
+
let roundedHeight = roundToStep(nextHeight, step);
|
| 145 |
+
let roundedPixels = roundedWidth * roundedHeight;
|
| 146 |
+
|
| 147 |
+
while (roundedPixels > maxPixels && (roundedWidth > step || roundedHeight > step)) {
|
| 148 |
+
if (roundedWidth >= roundedHeight && roundedWidth > step) {
|
| 149 |
+
roundedWidth -= step;
|
| 150 |
+
} else if (roundedHeight > step) {
|
| 151 |
+
roundedHeight -= step;
|
| 152 |
+
} else {
|
| 153 |
+
break;
|
| 154 |
+
}
|
| 155 |
+
roundedPixels = roundedWidth * roundedHeight;
|
| 156 |
+
}
|
| 157 |
+
|
| 158 |
+
return { width: roundedWidth, height: roundedHeight };
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
function validateCustomSize(
|
| 162 |
+
size: string,
|
| 163 |
+
family: ZaiModelFamily,
|
| 164 |
+
): string {
|
| 165 |
+
const parsed = parseSize(size);
|
| 166 |
+
if (!parsed) {
|
| 167 |
+
throw new Error("Z.AI --size must be in WxH format, for example 1280x1280.");
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
const widthStep = family === "glm" ? GLM_SIZE_STEP : LEGACY_SIZE_STEP;
|
| 171 |
+
const minEdge = family === "glm" ? 1024 : 512;
|
| 172 |
+
const maxPixels = family === "glm" ? GLM_MAX_PIXELS : LEGACY_MAX_PIXELS;
|
| 173 |
+
|
| 174 |
+
if (parsed.width < minEdge || parsed.width > 2048 || parsed.height < minEdge || parsed.height > 2048) {
|
| 175 |
+
throw new Error(
|
| 176 |
+
family === "glm"
|
| 177 |
+
? "GLM-image custom size requires width and height between 1024 and 2048."
|
| 178 |
+
: "Z.AI legacy image models require width and height between 512 and 2048."
|
| 179 |
+
);
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
if (parsed.width % widthStep !== 0 || parsed.height % widthStep !== 0) {
|
| 183 |
+
throw new Error(
|
| 184 |
+
family === "glm"
|
| 185 |
+
? "GLM-image custom size requires width and height divisible by 32."
|
| 186 |
+
: "Z.AI legacy image models require width and height divisible by 16."
|
| 187 |
+
);
|
| 188 |
+
}
|
| 189 |
+
|
| 190 |
+
if (parsed.width * parsed.height > maxPixels) {
|
| 191 |
+
throw new Error(
|
| 192 |
+
family === "glm"
|
| 193 |
+
? "GLM-image custom size must not exceed 2^22 total pixels."
|
| 194 |
+
: "Z.AI legacy image size must not exceed 2^21 total pixels."
|
| 195 |
+
);
|
| 196 |
+
}
|
| 197 |
+
|
| 198 |
+
return formatSize(parsed.width, parsed.height);
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
export function resolveSizeForModel(
|
| 202 |
+
model: string,
|
| 203 |
+
args: Pick<CliArgs, "size" | "aspectRatio" | "quality">,
|
| 204 |
+
): string {
|
| 205 |
+
const family = getModelFamily(model);
|
| 206 |
+
const quality = args.quality === "normal" ? "normal" : "2k";
|
| 207 |
+
|
| 208 |
+
if (args.size) {
|
| 209 |
+
return validateCustomSize(args.size, family);
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
const recommended = family === "glm" ? GLM_RECOMMENDED_SIZES : LEGACY_RECOMMENDED_SIZES;
|
| 213 |
+
const defaultSize = family === "glm" ? "1280x1280" : "1024x1024";
|
| 214 |
+
|
| 215 |
+
if (!args.aspectRatio) return defaultSize;
|
| 216 |
+
|
| 217 |
+
const recommendedRatio = findClosestRatioKey(args.aspectRatio, Object.keys(recommended));
|
| 218 |
+
if (recommendedRatio) {
|
| 219 |
+
return recommended[recommendedRatio]!;
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
const parsedRatio = parseAspectRatio(args.aspectRatio);
|
| 223 |
+
if (!parsedRatio) return defaultSize;
|
| 224 |
+
|
| 225 |
+
const targetPixels = getTargetPixels(quality);
|
| 226 |
+
const maxPixels = family === "glm" ? GLM_MAX_PIXELS : LEGACY_MAX_PIXELS;
|
| 227 |
+
const step = family === "glm" ? GLM_SIZE_STEP : LEGACY_SIZE_STEP;
|
| 228 |
+
const fit = fitToPixelBudget(
|
| 229 |
+
parsedRatio.width,
|
| 230 |
+
parsedRatio.height,
|
| 231 |
+
targetPixels,
|
| 232 |
+
maxPixels,
|
| 233 |
+
step,
|
| 234 |
+
);
|
| 235 |
+
return formatSize(fit.width, fit.height);
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
function getZaiQuality(quality: CliArgs["quality"]): "hd" | "standard" {
|
| 239 |
+
return quality === "normal" ? "standard" : "hd";
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
export function validateArgs(_model: string, args: CliArgs): void {
|
| 243 |
+
if (args.referenceImages.length > 0) {
|
| 244 |
+
throw new Error("Z.AI GLM-image currently supports text-to-image only in baoyu-image-gen. Remove --ref or choose another provider.");
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
if (args.n > 1) {
|
| 248 |
+
throw new Error("Z.AI image generation currently returns a single image per request in baoyu-image-gen.");
|
| 249 |
+
}
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
export function buildRequestBody(
|
| 253 |
+
prompt: string,
|
| 254 |
+
model: string,
|
| 255 |
+
args: CliArgs,
|
| 256 |
+
): ZaiRequestBody {
|
| 257 |
+
validateArgs(model, args);
|
| 258 |
+
return {
|
| 259 |
+
model,
|
| 260 |
+
prompt,
|
| 261 |
+
quality: getZaiQuality(args.quality),
|
| 262 |
+
size: resolveSizeForModel(model, args),
|
| 263 |
+
};
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
export async function extractImageFromResponse(result: ZaiResponse): Promise<Uint8Array> {
|
| 267 |
+
const url = result.data?.[0]?.url;
|
| 268 |
+
if (!url) {
|
| 269 |
+
throw new Error("No image URL in Z.AI response");
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
const imageResponse = await fetch(url);
|
| 273 |
+
if (!imageResponse.ok) {
|
| 274 |
+
throw new Error(`Failed to download image from Z.AI: ${imageResponse.status}`);
|
| 275 |
+
}
|
| 276 |
+
|
| 277 |
+
return new Uint8Array(await imageResponse.arrayBuffer());
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
export async function generateImage(
|
| 281 |
+
prompt: string,
|
| 282 |
+
model: string,
|
| 283 |
+
args: CliArgs,
|
| 284 |
+
): Promise<Uint8Array> {
|
| 285 |
+
const apiKey = getApiKey();
|
| 286 |
+
if (!apiKey) {
|
| 287 |
+
throw new Error("ZAI_API_KEY is required. Get one from https://docs.z.ai/.");
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
const response = await fetch(buildZaiUrl(), {
|
| 291 |
+
method: "POST",
|
| 292 |
+
headers: {
|
| 293 |
+
"Content-Type": "application/json",
|
| 294 |
+
Authorization: `Bearer ${apiKey}`,
|
| 295 |
+
},
|
| 296 |
+
body: JSON.stringify(buildRequestBody(prompt, model, args)),
|
| 297 |
+
});
|
| 298 |
+
|
| 299 |
+
if (!response.ok) {
|
| 300 |
+
const err = await response.text();
|
| 301 |
+
throw new Error(`Z.AI API error (${response.status}): ${err}`);
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
const result = (await response.json()) as ZaiResponse;
|
| 305 |
+
return extractImageFromResponse(result);
|
| 306 |
+
}
|
baoyu_skills/baoyu-imagine/scripts/types.ts
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
export type Provider =
|
| 2 |
+
| "google"
|
| 3 |
+
| "openai"
|
| 4 |
+
| "openrouter"
|
| 5 |
+
| "dashscope"
|
| 6 |
+
| "zai"
|
| 7 |
+
| "minimax"
|
| 8 |
+
| "replicate"
|
| 9 |
+
| "jimeng"
|
| 10 |
+
| "seedream"
|
| 11 |
+
| "azure"
|
| 12 |
+
| "codex-cli";
|
| 13 |
+
export type Quality = "normal" | "2k";
|
| 14 |
+
export type OpenAIImageApiDialect = "openai-native" | "ratio-metadata";
|
| 15 |
+
|
| 16 |
+
export type CliArgs = {
|
| 17 |
+
prompt: string | null;
|
| 18 |
+
promptFiles: string[];
|
| 19 |
+
imagePath: string | null;
|
| 20 |
+
provider: Provider | null;
|
| 21 |
+
model: string | null;
|
| 22 |
+
aspectRatio: string | null;
|
| 23 |
+
aspectRatioSource?: "cli" | "task" | "config" | null;
|
| 24 |
+
size: string | null;
|
| 25 |
+
quality: Quality | null;
|
| 26 |
+
imageSize: string | null;
|
| 27 |
+
imageSizeSource?: "cli" | "task" | "config" | null;
|
| 28 |
+
imageApiDialect: OpenAIImageApiDialect | null;
|
| 29 |
+
referenceImages: string[];
|
| 30 |
+
n: number;
|
| 31 |
+
batchFile: string | null;
|
| 32 |
+
jobs: number | null;
|
| 33 |
+
json: boolean;
|
| 34 |
+
help: boolean;
|
| 35 |
+
};
|
| 36 |
+
|
| 37 |
+
export type BatchTaskInput = {
|
| 38 |
+
id?: string;
|
| 39 |
+
prompt?: string | null;
|
| 40 |
+
promptFiles?: string[];
|
| 41 |
+
image?: string;
|
| 42 |
+
provider?: Provider | null;
|
| 43 |
+
model?: string | null;
|
| 44 |
+
ar?: string | null;
|
| 45 |
+
size?: string | null;
|
| 46 |
+
quality?: Quality | null;
|
| 47 |
+
imageSize?: "1K" | "2K" | "4K" | null;
|
| 48 |
+
imageApiDialect?: OpenAIImageApiDialect | null;
|
| 49 |
+
ref?: string[];
|
| 50 |
+
n?: number;
|
| 51 |
+
};
|
| 52 |
+
|
| 53 |
+
export type BatchFile =
|
| 54 |
+
| BatchTaskInput[]
|
| 55 |
+
| {
|
| 56 |
+
tasks: BatchTaskInput[];
|
| 57 |
+
jobs?: number | null;
|
| 58 |
+
};
|
| 59 |
+
|
| 60 |
+
export type ExtendConfig = {
|
| 61 |
+
version: number;
|
| 62 |
+
default_provider: Provider | null;
|
| 63 |
+
default_quality: Quality | null;
|
| 64 |
+
default_aspect_ratio: string | null;
|
| 65 |
+
default_image_size: "1K" | "2K" | "4K" | null;
|
| 66 |
+
default_image_api_dialect: OpenAIImageApiDialect | null;
|
| 67 |
+
default_model: {
|
| 68 |
+
google: string | null;
|
| 69 |
+
openai: string | null;
|
| 70 |
+
openrouter: string | null;
|
| 71 |
+
dashscope: string | null;
|
| 72 |
+
zai: string | null;
|
| 73 |
+
minimax: string | null;
|
| 74 |
+
replicate: string | null;
|
| 75 |
+
jimeng: string | null;
|
| 76 |
+
seedream: string | null;
|
| 77 |
+
azure: string | null;
|
| 78 |
+
"codex-cli": string | null;
|
| 79 |
+
};
|
| 80 |
+
batch?: {
|
| 81 |
+
max_workers?: number | null;
|
| 82 |
+
provider_limits?: Partial<
|
| 83 |
+
Record<
|
| 84 |
+
Provider,
|
| 85 |
+
{
|
| 86 |
+
concurrency?: number | null;
|
| 87 |
+
start_interval_ms?: number | null;
|
| 88 |
+
}
|
| 89 |
+
>
|
| 90 |
+
>;
|
| 91 |
+
};
|
| 92 |
+
};
|
config/.env
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
API_SERVER_ENABLED=true
|
| 2 |
+
API_SERVER_HOST=127.0.0.1
|
| 3 |
+
API_SERVER_PORT=8642
|
| 4 |
+
GATEWAY_ALLOW_ALL_USERS=true
|
| 5 |
+
HERMES_MODEL=moonshotai/kimi-k2-thinking
|
config/config.yaml
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
model:
|
| 2 |
+
default: moonshotai/kimi-k2-thinking
|
| 3 |
+
provider: nvidia
|
| 4 |
+
base_url: https://integrate.api.nvidia.com/v1
|
| 5 |
+
auxiliary:
|
| 6 |
+
vision:
|
| 7 |
+
provider: nvidia
|
| 8 |
+
model: ''
|
| 9 |
+
timeout: 120
|
| 10 |
+
download_timeout: 30
|
| 11 |
+
web_extract:
|
| 12 |
+
provider: nvidia
|
| 13 |
+
model: ''
|
| 14 |
+
timeout: 360
|
| 15 |
+
compression:
|
| 16 |
+
provider: nvidia
|
| 17 |
+
model: ''
|
| 18 |
+
timeout: 120
|
| 19 |
+
title_generation:
|
| 20 |
+
provider: nvidia
|
| 21 |
+
model: ''
|
| 22 |
+
timeout: 30
|
| 23 |
+
session_search:
|
| 24 |
+
provider: auto
|
| 25 |
+
model: ''
|
| 26 |
+
timeout: 30
|
| 27 |
+
skills_hub:
|
| 28 |
+
provider: auto
|
| 29 |
+
model: ''
|
| 30 |
+
timeout: 30
|
| 31 |
+
approval:
|
| 32 |
+
provider: auto
|
| 33 |
+
model: ''
|
| 34 |
+
timeout: 30
|
| 35 |
+
mcp:
|
| 36 |
+
provider: auto
|
| 37 |
+
model: ''
|
| 38 |
+
timeout: 30
|
| 39 |
+
flush_memories:
|
| 40 |
+
provider: auto
|
| 41 |
+
model: ''
|
| 42 |
+
timeout: 30
|
| 43 |
+
delegation:
|
| 44 |
+
model: ''
|
| 45 |
+
provider: nvidia
|
| 46 |
+
max_iterations: 50
|
| 47 |
+
reasoning_effort: medium
|
| 48 |
+
api_server:
|
| 49 |
+
enabled: true
|
| 50 |
+
port: 8642
|
| 51 |
+
host: 127.0.0.1
|
| 52 |
+
terminal:
|
| 53 |
+
backend: local
|
| 54 |
+
timeout: 300
|
| 55 |
+
shell: /bin/bash
|
| 56 |
+
env_passthrough:
|
| 57 |
+
- GEMINI_API_KEY
|
| 58 |
+
- GOOGLE_API_KEY
|
| 59 |
+
- SILICONFLOW_API_KEY
|
| 60 |
+
- GOOGLE_IMAGE_MODEL
|
| 61 |
+
- GOOGLE_BASE_URL
|
| 62 |
+
display:
|
| 63 |
+
skin: default
|
| 64 |
+
show_tool_progress: true
|
| 65 |
+
show_resume: true
|
| 66 |
+
spinner: dots
|
| 67 |
+
agent:
|
| 68 |
+
max_iterations: 50
|
| 69 |
+
approval_mode: ask
|
| 70 |
+
dangerous_command_approval: ask
|
| 71 |
+
gateway_timeout: 300
|
| 72 |
+
memory:
|
| 73 |
+
enabled: true
|
| 74 |
+
provider: local
|
| 75 |
+
compression:
|
| 76 |
+
enabled: true
|
| 77 |
+
threshold: 0.5
|
| 78 |
+
cron:
|
| 79 |
+
enabled: true
|
| 80 |
+
tick_interval: 60
|
cron/.tick.lock
ADDED
|
File without changes
|
logs/agent.log
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
2026-06-02 04:27:44,388 INFO hermes_cli.plugins: Plugin 'browser-browser-use' registered browser provider: browser-use
|
| 2 |
+
2026-06-02 04:27:44,390 INFO hermes_cli.plugins: Plugin 'browser-browserbase' registered browser provider: browserbase
|
| 3 |
+
2026-06-02 04:27:44,391 INFO hermes_cli.plugins: Plugin 'browser-firecrawl' registered browser provider: firecrawl
|
| 4 |
+
2026-06-02 04:27:44,488 INFO hermes_cli.plugins: Plugin 'fal' registered image_gen provider: fal
|
| 5 |
+
2026-06-02 04:27:44,488 INFO hermes_cli.plugins: Plugin 'krea' registered image_gen provider: krea
|
| 6 |
+
2026-06-02 04:27:44,489 INFO hermes_cli.plugins: Plugin 'openai' registered image_gen provider: openai
|
| 7 |
+
2026-06-02 04:27:44,490 INFO hermes_cli.plugins: Plugin 'openai-codex' registered image_gen provider: openai-codex
|
| 8 |
+
2026-06-02 04:27:44,491 INFO hermes_cli.plugins: Plugin 'xai' registered image_gen provider: xai
|
| 9 |
+
2026-06-02 04:27:44,527 INFO hermes_cli.plugins: Plugin 'fal' registered video_gen provider: fal
|
| 10 |
+
2026-06-02 04:27:44,528 INFO hermes_cli.plugins: Plugin 'xai' registered video_gen provider: xai
|
| 11 |
+
2026-06-02 04:27:44,530 INFO hermes_cli.plugins: Plugin 'web-brave-free' registered web provider: brave-free
|
| 12 |
+
2026-06-02 04:27:44,531 INFO hermes_cli.plugins: Plugin 'web-ddgs' registered web provider: ddgs
|
| 13 |
+
2026-06-02 04:27:44,533 INFO hermes_cli.plugins: Plugin 'web-exa' registered web provider: exa
|
| 14 |
+
2026-06-02 04:27:44,535 INFO hermes_cli.plugins: Plugin 'web-firecrawl' registered web provider: firecrawl
|
| 15 |
+
2026-06-02 04:27:44,536 INFO hermes_cli.plugins: Plugin 'web-parallel' registered web provider: parallel
|
| 16 |
+
2026-06-02 04:27:44,537 INFO hermes_cli.plugins: Plugin 'web-searxng' registered web provider: searxng
|
| 17 |
+
2026-06-02 04:27:44,538 INFO hermes_cli.plugins: Plugin 'web-tavily' registered web provider: tavily
|
| 18 |
+
2026-06-02 04:27:44,541 INFO hermes_cli.plugins: Plugin 'web-xai' registered web provider: xai
|
| 19 |
+
2026-06-02 04:27:44,828 INFO hermes_cli.plugins: Plugin discovery complete: 33 found, 28 enabled
|
| 20 |
+
2026-06-02 04:27:45,762 INFO tools.lazy_deps: Lazy-installing discord.py[voice]==2.7.1 brotlicffi==1.2.0.1 for feature 'platform.discord'
|
| 21 |
+
2026-06-02 04:27:53,369 INFO tools.tirith_security: tirith not found — downloading latest release for x86_64-unknown-linux-gnu...
|
| 22 |
+
2026-06-02 04:27:54,119 INFO tools.tirith_security: cosign not on PATH — installing tirith with SHA-256 verification only (install cosign for full supply chain verification)
|
| 23 |
+
2026-06-02 04:27:55,264 INFO gateway.run: Starting Hermes Gateway...
|
| 24 |
+
2026-06-02 04:27:55,265 INFO gateway.run: Session storage: /data/.hermes/sessions
|
| 25 |
+
2026-06-02 04:27:55,271 INFO gateway.run: Agent budget: max_iterations=90 (agent.max_turns from config.yaml, or HERMES_MAX_ITERATIONS from .env, or default 90)
|
| 26 |
+
2026-06-02 04:27:55,272 INFO gateway.run: Secret redaction: ENABLED (tool output, logs, and chat responses are scrubbed before delivery)
|
| 27 |
+
2026-06-02 04:27:55,286 INFO tools.tirith_security: tirith installed to /data/.hermes/bin/tirith (SHA-256 only)
|
| 28 |
+
2026-06-02 04:27:55,424 INFO gateway.run: Connecting to api_server...
|
| 29 |
+
2026-06-02 04:27:55,438 ERROR gateway.platforms.api_server: [Api_Server] Refusing to start: API_SERVER_KEY is required for the API server, including loopback-only binds on 127.0.0.1.
|
| 30 |
+
2026-06-02 04:27:55,440 WARNING gateway.run: ✗ api_server failed to connect
|
| 31 |
+
2026-06-02 04:27:55,445 INFO gateway.platforms.api_server: [Api_Server] API server stopped
|
| 32 |
+
2026-06-02 04:27:55,452 WARNING gateway.run: Gateway started with no connected platforms — 1 platform(s) queued for retry: api_server: failed to connect
|
| 33 |
+
2026-06-02 04:27:55,455 WARNING gateway.run: No adapter could be created for any of the 1 configured platform(s). Check that required dependencies are installed and credentials are set. Gateway will continue for cron job execution.
|
| 34 |
+
2026-06-02 04:27:55,465 INFO gateway.run: Channel directory built: 0 target(s)
|
| 35 |
+
2026-06-02 04:27:55,465 INFO gateway.run: Starting reconnection watcher for 1 failed platform(s): api_server
|
| 36 |
+
2026-06-02 04:27:55,466 INFO gateway.run: Press Ctrl+C to stop
|
| 37 |
+
2026-06-02 04:27:55,470 INFO gateway.run: Cron ticker started (interval=60s)
|
| 38 |
+
2026-06-02 04:28:00,485 INFO gateway.run: kanban dispatcher: embedded in gateway (interval=60.0s)
|
| 39 |
+
2026-06-02 04:28:25,508 INFO gateway.run: Reconnecting api_server (attempt 2)...
|
| 40 |
+
2026-06-02 04:28:25,511 ERROR gateway.platforms.api_server: [Api_Server] Refusing to start: API_SERVER_KEY is required for the API server, including loopback-only binds on 127.0.0.1.
|
| 41 |
+
2026-06-02 04:28:25,522 INFO gateway.run: Reconnect api_server failed, next retry in 60s
|
logs/errors.log
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
2026-06-02 04:27:55,438 ERROR gateway.platforms.api_server: [Api_Server] Refusing to start: API_SERVER_KEY is required for the API server, including loopback-only binds on 127.0.0.1.
|
| 2 |
+
2026-06-02 04:27:55,440 WARNING gateway.run: ✗ api_server failed to connect
|
| 3 |
+
2026-06-02 04:27:55,452 WARNING gateway.run: Gateway started with no connected platforms — 1 platform(s) queued for retry: api_server: failed to connect
|
| 4 |
+
2026-06-02 04:27:55,455 WARNING gateway.run: No adapter could be created for any of the 1 configured platform(s). Check that required dependencies are installed and credentials are set. Gateway will continue for cron job execution.
|
| 5 |
+
2026-06-02 04:28:25,511 ERROR gateway.platforms.api_server: [Api_Server] Refusing to start: API_SERVER_KEY is required for the API server, including loopback-only binds on 127.0.0.1.
|
logs/gateway-exit-diag.log
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"ts": "2026-06-02T04:27:45.521326+00:00", "tag": "gateway.start", "pid": 48, "python": "3.11.15", "platform": "linux", "replace": true, "argv": ["/usr/local/bin/hermes", "gateway", "run", "--replace"], "stdin_is_tty": false, "absorb_windows_console_controls": false}
|
logs/gateway.log
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
2026-06-02 04:27:55,264 INFO gateway.run: Starting Hermes Gateway...
|
| 2 |
+
2026-06-02 04:27:55,265 INFO gateway.run: Session storage: /data/.hermes/sessions
|
| 3 |
+
2026-06-02 04:27:55,271 INFO gateway.run: Agent budget: max_iterations=90 (agent.max_turns from config.yaml, or HERMES_MAX_ITERATIONS from .env, or default 90)
|
| 4 |
+
2026-06-02 04:27:55,272 INFO gateway.run: Secret redaction: ENABLED (tool output, logs, and chat responses are scrubbed before delivery)
|
| 5 |
+
2026-06-02 04:27:55,424 INFO gateway.run: Connecting to api_server...
|
| 6 |
+
2026-06-02 04:27:55,438 ERROR gateway.platforms.api_server: [Api_Server] Refusing to start: API_SERVER_KEY is required for the API server, including loopback-only binds on 127.0.0.1.
|
| 7 |
+
2026-06-02 04:27:55,440 WARNING gateway.run: ✗ api_server failed to connect
|
| 8 |
+
2026-06-02 04:27:55,445 INFO gateway.platforms.api_server: [Api_Server] API server stopped
|
| 9 |
+
2026-06-02 04:27:55,452 WARNING gateway.run: Gateway started with no connected platforms — 1 platform(s) queued for retry: api_server: failed to connect
|
| 10 |
+
2026-06-02 04:27:55,455 WARNING gateway.run: No adapter could be created for any of the 1 configured platform(s). Check that required dependencies are installed and credentials are set. Gateway will continue for cron job execution.
|
| 11 |
+
2026-06-02 04:27:55,465 INFO gateway.run: Channel directory built: 0 target(s)
|
| 12 |
+
2026-06-02 04:27:55,465 INFO gateway.run: Starting reconnection watcher for 1 failed platform(s): api_server
|
| 13 |
+
2026-06-02 04:27:55,466 INFO gateway.run: Press Ctrl+C to stop
|
| 14 |
+
2026-06-02 04:27:55,470 INFO gateway.run: Cron ticker started (interval=60s)
|
| 15 |
+
2026-06-02 04:28:00,485 INFO gateway.run: kanban dispatcher: embedded in gateway (interval=60.0s)
|
| 16 |
+
2026-06-02 04:28:25,508 INFO gateway.run: Reconnecting api_server (attempt 2)...
|
| 17 |
+
2026-06-02 04:28:25,511 ERROR gateway.platforms.api_server: [Api_Server] Refusing to start: API_SERVER_KEY is required for the API server, including loopback-only binds on 127.0.0.1.
|
| 18 |
+
2026-06-02 04:28:25,522 INFO gateway.run: Reconnect api_server failed, next retry in 60s
|
metadata.json
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"timestamp": "2026-06-02T04:28:40.143240",
|
| 3 |
+
"version": "0.10.0",
|
| 4 |
+
"hermes_home": "/data/.hermes"
|
| 5 |
+
}
|
personality/SOUL.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
You are Hermes Agent, an intelligent AI assistant created by Nous Research. You are helpful, knowledgeable, and direct. You assist users with a wide range of tasks including answering questions, writing and editing code, analyzing information, creative work, and executing actions via your tools. You communicate clearly, admit uncertainty when appropriate, and prioritize being genuinely useful over being verbose unless otherwise directed below. Be targeted and efficient in your exploration and investigations.
|
skills/.bundled_manifest
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
airtable:30f47a4b29827da14e655356c0edd8a7
|
| 2 |
+
apple-notes:5e448abf984561fb33b197045ce41388
|
| 3 |
+
apple-reminders:b38e5f2558c2842808fe85df10226598
|
| 4 |
+
architecture-diagram:ca5e216b2014eef4f38f0a488eaf3545
|
| 5 |
+
arxiv:6d14337b8c41aec140ff169cae6d6a8b
|
| 6 |
+
ascii-art:3aea656d9b8fb9d054ce37565e704a04
|
| 7 |
+
ascii-video:2c8277458b2ef50421ce44debb9d81ad
|
| 8 |
+
audiocraft-audio-generation:c207bdbf300ea5c42decc9cb6a596d1c
|
| 9 |
+
baoyu-article-illustrator:bfea57e0608ff6010bbbb75238db89e5
|
| 10 |
+
baoyu-comic:8ff68387b01dea27ce049837ae9ecc47
|
| 11 |
+
baoyu-infographic:53edf7d1b9398d62f4ccb0755e27913e
|
| 12 |
+
blogwatcher:3f30bdd408c771501b94fab9289579c6
|
| 13 |
+
claude-code:231f7e3cb0b2b91f64ce4b23fc2cef4d
|
| 14 |
+
claude-design:c1b63b7651b66fd15d096e57728ec686
|
| 15 |
+
codebase-inspection:29f67c87df868dd08e76c57b86c7a5c6
|
| 16 |
+
codex:a116c5f880869f663b2974c2c9a79dbd
|
| 17 |
+
comfyui:ff1569b4844cadfa562f1ba0eadd3d20
|
| 18 |
+
debugging-hermes-tui-commands:b093ceac961144fb3e72e57b12a5d354
|
| 19 |
+
design-md:b40264457352831ab1d06f3ec671b532
|
| 20 |
+
dogfood:ae6e92c2cd27c3da8a0587f089d19fe3
|
| 21 |
+
dspy:64659f5eba8f127700fa931f58175f01
|
| 22 |
+
evaluating-llms-harness:ac24cf5202db5b024b3079023797a0f6
|
| 23 |
+
excalidraw:7a00db63b8cfce000d363d7e9e987c22
|
| 24 |
+
findmy:1d7dd3ae39cf25357a374c6bfb956442
|
| 25 |
+
gif-search:d02d7fb065dfc143c079f15b8d8af1a7
|
| 26 |
+
github-auth:c58654476268579b4cfa5953bb4160d0
|
| 27 |
+
github-code-review:b771855b5c56b5e3a2546167a51667ba
|
| 28 |
+
github-issues:429ec06cde7578e4ebba451d8106f008
|
| 29 |
+
github-pr-workflow:48b6aceaae5333f6d3ed2d72f595331b
|
| 30 |
+
github-repo-management:c5c05bc85dfcda2b7ac2f2006be9efe0
|
| 31 |
+
godmode:c3cfb5bdbbf594356e2c8f9b0ed636f0
|
| 32 |
+
google-workspace:270767dbe11c533ae52d249e81cdb0ca
|
| 33 |
+
heartmula:96a5927a5f221065260ddb2e0f1d77ec
|
| 34 |
+
hermes-agent:59936f6e34e3f57f809590bd6fe25a6f
|
| 35 |
+
hermes-agent-skill-authoring:4fefd83beeea0a8a32f5ae006f10f00d
|
| 36 |
+
hermes-s6-container-supervision:d1dd00ca7688c85813f325a564490431
|
| 37 |
+
himalaya:7ae61574914c25d57a001d1e1efe39bf
|
| 38 |
+
huggingface-hub:da338c5152d72db030bb81d923d1c64d
|
| 39 |
+
humanizer:6645b341862575f452e86139c5c71ce9
|
| 40 |
+
ideation:8cfdaafa9abda023643427110c8c3073
|
| 41 |
+
imessage:f545da0f5cc64dd9ee1ffd2b7733a11b
|
| 42 |
+
jupyter-live-kernel:352c43dc28428592abbc8c91cb5ce295
|
| 43 |
+
kanban-codex-lane:94b53308d74fe3b55f198b9d9e905cf7
|
| 44 |
+
kanban-orchestrator:8d4ea0e85653c37b4501e4084e78880c
|
| 45 |
+
kanban-worker:938bb76ff84b5867dcc0594c04e804b4
|
| 46 |
+
linear:4f623e8ae6cba4bde4bab58aee428a81
|
| 47 |
+
llama-cpp:0991055ce47146735f0ed02d7658a254
|
| 48 |
+
llm-wiki:ca957fbfecd9e573a1f99db3937a1969
|
| 49 |
+
macos-computer-use:fb1787b32be343b87078d2ae2618dbcf
|
| 50 |
+
manim-video:2ad3d68c3eb5d2675c05138100d3e48b
|
| 51 |
+
maps:8c750d234425410861d284850fee6130
|
| 52 |
+
minecraft-modpack-server:71e51465a1df193d7505ee47a91b6dbd
|
| 53 |
+
nano-pdf:6c643bd0cfb0548ff0ddaf367d4da6d1
|
| 54 |
+
native-mcp:3e758c66efed8f27c2153729d2050c87
|
| 55 |
+
node-inspect-debugger:55501511963a3a6410fc767b5ed3e21c
|
| 56 |
+
notion:930f6c7d327dd86553f45e2da9d9901e
|
| 57 |
+
obliteratus:d3333944ef536dbe9238766f2f626eae
|
| 58 |
+
obsidian:be02894afa45a908623ad6f9b7594199
|
| 59 |
+
ocr-and-documents:bc1e56f38862f4df75572a73066d3a71
|
| 60 |
+
opencode:d2a166c7f2c74f6e47d548ed1290c458
|
| 61 |
+
openhue:ce1dd061d7f49d4752a4c0711ad2666c
|
| 62 |
+
p5js:5f09fa1cb8494c93bc2f5bcbd34a2ead
|
| 63 |
+
pixel-art:29f4cc9e236bea7d3cafc8d6b1a1d08d
|
| 64 |
+
plan:50c4df52eb6b0932649a444bc9984e0a
|
| 65 |
+
pokemon-player:db79617ea4a61e0d6727d38402fb1f94
|
| 66 |
+
polymarket:8d6651afb31d704b46b7f549f6696b7b
|
| 67 |
+
popular-web-designs:b3fd685e8fbcf981755609ce98a4eea9
|
| 68 |
+
powerpoint:f94c23ef503eccef9b7413d965b8037b
|
| 69 |
+
pretext:f17f2b6211eb81b96e1fc5d48ecc96a4
|
| 70 |
+
python-debugpy:b87e0abf179c14ea51c7559dc99eb22c
|
| 71 |
+
requesting-code-review:9944f54e8ba5c294b47ee93f3e8f239d
|
| 72 |
+
research-paper-writing:dbe2d301baeaab5c5b0539a733233a34
|
| 73 |
+
segment-anything-model:7f1317da421fb8eada27aeacdbb21d30
|
| 74 |
+
serving-llms-vllm:92d66ae1f1112924634fcdcff2f86bc7
|
| 75 |
+
sketch:f8833126112824f6a916c69630cfd042
|
| 76 |
+
songsee:644dc0f267b6661a3df6c76ce80d7f1f
|
| 77 |
+
songwriting-and-ai-music:52be403c894c7bd7d6fe70f7eeaf9460
|
| 78 |
+
spike:8b01bbb339d72d13a8a3214a018969c4
|
| 79 |
+
spotify:a0ffe21977c14dc8da5dca039de83b0f
|
| 80 |
+
subagent-driven-development:f434c120ce9cc40fadb9ff970b45c1e7
|
| 81 |
+
systematic-debugging:55a23d83e936d3c7c04d4e5fa803558e
|
| 82 |
+
teams-meeting-pipeline:810d4862830d1eb3daccf898f7c5ee85
|
| 83 |
+
test-driven-development:31fb75eff421db47e527bce28c493df3
|
| 84 |
+
touchdesigner-mcp:0664ded9138795d5518def4d16037650
|
| 85 |
+
webhook-subscriptions:b1ffc6d6a3cf3f59ea8eb7dcd178c555
|
| 86 |
+
weights-and-biases:8f0e1ee92fdf7b42a1dad448176d7c64
|
| 87 |
+
writing-plans:ebe31eb58f7a09a7cd8fad4d422b9d3b
|
| 88 |
+
xurl:113313cc0bfb95c795074f350bb05ef7
|
| 89 |
+
youtube-content:7bb34f7c31d139df45b0adc6221b02dd
|
| 90 |
+
yuanbao:7844c287c57b42dccf51127f15e0751b
|
skills/apikey-image-gen/SKILL.md
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: apikey-image-gen
|
| 3 |
+
description: "Generate or edit images through Hermes Web UI using the selected/requested profile's fun-codex provider from config.yaml."
|
| 4 |
+
version: 1.0.0
|
| 5 |
+
author: Ekko
|
| 6 |
+
license: MIT
|
| 7 |
+
platforms: [linux, macos, windows, termux]
|
| 8 |
+
metadata:
|
| 9 |
+
hermes:
|
| 10 |
+
tags: [api.apikey.fun, image-generation, image-editing, media]
|
| 11 |
+
prerequisites:
|
| 12 |
+
commands: [curl]
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# APIKEY Image Generation
|
| 16 |
+
|
| 17 |
+
Use this skill when the user wants to generate an image, generate an image from a reference image, or edit an existing image.
|
| 18 |
+
|
| 19 |
+
Always call Hermes Web UI's media endpoint. Do not call `api.apikey.fun` directly, and do not ask the user for an API key. The server reads the selected/requested profile's `config.yaml` and uses the `custom_providers` entry named `fun-codex`:
|
| 20 |
+
|
| 21 |
+
Do not use any built-in image generation tool as a fallback. If the Hermes Web UI endpoint returns `401`, `403`, connection failure, or any other error, stop and report the Hermes Web UI error to the user.
|
| 22 |
+
|
| 23 |
+
```yaml
|
| 24 |
+
custom_providers:
|
| 25 |
+
- name: fun-codex
|
| 26 |
+
base_url: https://api.apikey.fun/v1
|
| 27 |
+
api_key: ...
|
| 28 |
+
model: gpt-5.5
|
| 29 |
+
api_mode: codex_responses
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
Endpoint:
|
| 33 |
+
|
| 34 |
+
```bash
|
| 35 |
+
POST <Hermes Web UI base URL>/api/hermes/media/apikey-image-generate
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
Resolve the Hermes Web UI base URL in this order:
|
| 39 |
+
|
| 40 |
+
1. `HERMES_WEB_UI_URL` environment variable, if set.
|
| 41 |
+
2. `http://127.0.0.1:${PORT}`, if `PORT` is set.
|
| 42 |
+
3. `http://127.0.0.1:8648` for local development.
|
| 43 |
+
|
| 44 |
+
When Hermes Web UI is running from Docker Compose, the default external URL is `http://127.0.0.1:6060`.
|
| 45 |
+
|
| 46 |
+
Authentication:
|
| 47 |
+
|
| 48 |
+
Send the Hermes Web UI server bearer token. This token is accepted only by Hermes Web UI media generation endpoints for agent skills; it is not a general Web UI login token.
|
| 49 |
+
|
| 50 |
+
Resolve the token in this order:
|
| 51 |
+
|
| 52 |
+
1. `AUTH_TOKEN` environment variable, if set.
|
| 53 |
+
2. `${HERMES_WEB_UI_HOME}/.token`, if `HERMES_WEB_UI_HOME` is set.
|
| 54 |
+
3. `${HERMES_WEBUI_STATE_DIR}/.token`, if `HERMES_WEBUI_STATE_DIR` is set.
|
| 55 |
+
4. `~/.hermes-web-ui/.token`.
|
| 56 |
+
|
| 57 |
+
Profile selection:
|
| 58 |
+
|
| 59 |
+
Use the current Hermes profile from the run instructions by sending `X-Hermes-Profile`.
|
| 60 |
+
|
| 61 |
+
If the run instructions include `[Current Hermes profile: <name>]`, include:
|
| 62 |
+
|
| 63 |
+
```bash
|
| 64 |
+
-H "X-Hermes-Profile: <name>"
|
| 65 |
+
```
|
| 66 |
+
|
| 67 |
+
Replace `<name>` with the exact profile name from the run instructions. Never send a placeholder value such as `<name>` or `<current-hermes-profile>`.
|
| 68 |
+
|
| 69 |
+
If no current profile is provided, omit the header and let the server fall back to the current Hermes active profile.
|
| 70 |
+
|
| 71 |
+
## Modes
|
| 72 |
+
|
| 73 |
+
### Text To Image
|
| 74 |
+
|
| 75 |
+
Use when there is no input image.
|
| 76 |
+
|
| 77 |
+
```json
|
| 78 |
+
{
|
| 79 |
+
"mode": "text",
|
| 80 |
+
"prompt": "A high quality product image of a matte black mechanical keyboard on a clean desk",
|
| 81 |
+
"size": "1024x1024",
|
| 82 |
+
"output_path": "/absolute/path/to/output.png"
|
| 83 |
+
}
|
| 84 |
+
```
|
| 85 |
+
|
| 86 |
+
The server calls `POST /v1/images/generations` against the `fun-codex` base URL.
|
| 87 |
+
|
| 88 |
+
### Image To Image
|
| 89 |
+
|
| 90 |
+
Use when the user provides a reference image and wants a new image based on it.
|
| 91 |
+
|
| 92 |
+
```json
|
| 93 |
+
{
|
| 94 |
+
"mode": "image",
|
| 95 |
+
"prompt": "Use this reference composition and generate a refined technology brand poster",
|
| 96 |
+
"image_path": "/absolute/path/to/reference.png",
|
| 97 |
+
"size": "1024x1024",
|
| 98 |
+
"output_path": "/absolute/path/to/output.png"
|
| 99 |
+
}
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
The server calls `POST /v1/responses` against the `fun-codex` base URL.
|
| 103 |
+
|
| 104 |
+
### Image Edit
|
| 105 |
+
|
| 106 |
+
Use when the user wants to modify an existing image while preserving parts of it.
|
| 107 |
+
|
| 108 |
+
```json
|
| 109 |
+
{
|
| 110 |
+
"mode": "edit",
|
| 111 |
+
"prompt": "Change the background to blue and keep the subject unchanged",
|
| 112 |
+
"image_path": "/absolute/path/to/source.png",
|
| 113 |
+
"size": "1024x1024",
|
| 114 |
+
"output_path": "/absolute/path/to/edited.png"
|
| 115 |
+
}
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
The server calls `POST /v1/images/edits` against the `fun-codex` base URL.
|
| 119 |
+
|
| 120 |
+
## Request Fields
|
| 121 |
+
|
| 122 |
+
- `mode`: `text`, `image`, or `edit`.
|
| 123 |
+
- `prompt`: required.
|
| 124 |
+
- `image_path`: local png, jpeg, or webp path. Required for `image` and `edit` unless using `image_url` or `image_base64`.
|
| 125 |
+
- `image_url`: optional alternative image input.
|
| 126 |
+
- `image_base64`: optional alternative image input. If it is not a data URI, include `mime_type`.
|
| 127 |
+
- `n`: number of images. Defaults to `1`.
|
| 128 |
+
- `size`: defaults to `1024x1024`. Common values: `1024x1024`, `1536x1024`, `1024x1536`, `2048x2048`, `3840x2160`, `2160x3840`, `auto`.
|
| 129 |
+
- `quality`: defaults to `auto`.
|
| 130 |
+
- `model`: optional override. Text/edit default to `gpt-image-2`; image mode defaults to the `fun-codex` model in `config.yaml`.
|
| 131 |
+
- `image_model`: optional image tool model for image mode. Defaults to `gpt-image-2`.
|
| 132 |
+
- `output_path`: optional absolute output file path. If omitted, the server saves to `${HERMES_WEB_UI_HOME:-~/.hermes-web-ui}/media/*.png`.
|
| 133 |
+
- `timeout_ms`: defaults to `600000`.
|
| 134 |
+
|
| 135 |
+
## Curl Template
|
| 136 |
+
|
| 137 |
+
```bash
|
| 138 |
+
TOKEN="${AUTH_TOKEN:-}"
|
| 139 |
+
if [ -z "$TOKEN" ] && [ -n "${HERMES_WEB_UI_HOME:-}" ] && [ -f "$HERMES_WEB_UI_HOME/.token" ]; then
|
| 140 |
+
TOKEN="$(cat "$HERMES_WEB_UI_HOME/.token")"
|
| 141 |
+
fi
|
| 142 |
+
if [ -z "$TOKEN" ] && [ -n "${HERMES_WEBUI_STATE_DIR:-}" ] && [ -f "$HERMES_WEBUI_STATE_DIR/.token" ]; then
|
| 143 |
+
TOKEN="$(cat "$HERMES_WEBUI_STATE_DIR/.token")"
|
| 144 |
+
fi
|
| 145 |
+
if [ -z "$TOKEN" ] && [ -f "$HOME/.hermes-web-ui/.token" ]; then
|
| 146 |
+
TOKEN="$(cat "$HOME/.hermes-web-ui/.token")"
|
| 147 |
+
fi
|
| 148 |
+
if [ -z "$TOKEN" ]; then
|
| 149 |
+
echo "Missing Hermes Web UI token. Check AUTH_TOKEN, HERMES_WEB_UI_HOME, HERMES_WEBUI_STATE_DIR, or ~/.hermes-web-ui/.token." >&2
|
| 150 |
+
exit 1
|
| 151 |
+
fi
|
| 152 |
+
|
| 153 |
+
BASE_URL="${HERMES_WEB_UI_URL:-}"
|
| 154 |
+
if [ -z "$BASE_URL" ]; then
|
| 155 |
+
BASE_URL="http://127.0.0.1:${PORT:-8648}"
|
| 156 |
+
fi
|
| 157 |
+
BASE_URL="${BASE_URL%/}"
|
| 158 |
+
|
| 159 |
+
curl -sS -X POST "$BASE_URL/api/hermes/media/apikey-image-generate" \
|
| 160 |
+
-H "Authorization: Bearer $TOKEN" \
|
| 161 |
+
-H 'Content-Type: application/json' \
|
| 162 |
+
-d '{
|
| 163 |
+
"mode": "text",
|
| 164 |
+
"prompt": "A cinematic 4K photo of a silver robot hand holding a small glowing cube",
|
| 165 |
+
"size": "3840x2160",
|
| 166 |
+
"output_path": "/absolute/path/to/output.png"
|
| 167 |
+
}'
|
| 168 |
+
```
|
| 169 |
+
|
| 170 |
+
Successful responses include:
|
| 171 |
+
|
| 172 |
+
```json
|
| 173 |
+
{
|
| 174 |
+
"ok": true,
|
| 175 |
+
"mode": "text",
|
| 176 |
+
"output_paths": ["/absolute/path/to/output.png"],
|
| 177 |
+
"provider": "fun-codex",
|
| 178 |
+
"base_url": "https://api.apikey.fun/v1"
|
| 179 |
+
}
|
| 180 |
+
```
|
| 181 |
+
|
| 182 |
+
If the response code is `missing_fun_codex_provider`, tell the user to configure `fun-codex` in the selected/requested profile's `config.yaml`.
|
skills/apple/DESCRIPTION.md
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apple / macOS skills — tools that interact with the Mac desktop (Finder,
|
| 2 |
+
native apps) or system features (accessibility, screenshots).
|
skills/apple/apple-notes/SKILL.md
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: apple-notes
|
| 3 |
+
description: "Manage Apple Notes via memo CLI: create, search, edit."
|
| 4 |
+
version: 1.0.0
|
| 5 |
+
author: Hermes Agent
|
| 6 |
+
license: MIT
|
| 7 |
+
platforms: [macos]
|
| 8 |
+
metadata:
|
| 9 |
+
hermes:
|
| 10 |
+
tags: [Notes, Apple, macOS, note-taking]
|
| 11 |
+
related_skills: [obsidian]
|
| 12 |
+
prerequisites:
|
| 13 |
+
commands: [memo]
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
# Apple Notes
|
| 17 |
+
|
| 18 |
+
Use `memo` to manage Apple Notes directly from the terminal. Notes sync across all Apple devices via iCloud.
|
| 19 |
+
|
| 20 |
+
## Prerequisites
|
| 21 |
+
|
| 22 |
+
- **macOS** with Notes.app
|
| 23 |
+
- Install: `brew tap antoniorodr/memo && brew install antoniorodr/memo/memo`
|
| 24 |
+
- Grant Automation access to Notes.app when prompted (System Settings → Privacy → Automation)
|
| 25 |
+
|
| 26 |
+
## When to Use
|
| 27 |
+
|
| 28 |
+
- User asks to create, view, or search Apple Notes
|
| 29 |
+
- Saving information to Notes.app for cross-device access
|
| 30 |
+
- Organizing notes into folders
|
| 31 |
+
- Exporting notes to Markdown/HTML
|
| 32 |
+
|
| 33 |
+
## When NOT to Use
|
| 34 |
+
|
| 35 |
+
- Obsidian vault management → use the `obsidian` skill
|
| 36 |
+
- Bear Notes → separate app (not supported here)
|
| 37 |
+
- Quick agent-only notes → use the `memory` tool instead
|
| 38 |
+
|
| 39 |
+
## Quick Reference
|
| 40 |
+
|
| 41 |
+
### View Notes
|
| 42 |
+
|
| 43 |
+
```bash
|
| 44 |
+
memo notes # List all notes
|
| 45 |
+
memo notes -f "Folder Name" # Filter by folder
|
| 46 |
+
memo notes -s "query" # Search notes (fuzzy)
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
### Create Notes
|
| 50 |
+
|
| 51 |
+
```bash
|
| 52 |
+
memo notes -a # Interactive editor
|
| 53 |
+
memo notes -a "Note Title" # Quick add with title
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
### Edit Notes
|
| 57 |
+
|
| 58 |
+
```bash
|
| 59 |
+
memo notes -e # Interactive selection to edit
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
### Delete Notes
|
| 63 |
+
|
| 64 |
+
```bash
|
| 65 |
+
memo notes -d # Interactive selection to delete
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
### Move Notes
|
| 69 |
+
|
| 70 |
+
```bash
|
| 71 |
+
memo notes -m # Move note to folder (interactive)
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
### Export Notes
|
| 75 |
+
|
| 76 |
+
```bash
|
| 77 |
+
memo notes -ex # Export to HTML/Markdown
|
| 78 |
+
```
|
| 79 |
+
|
| 80 |
+
## Limitations
|
| 81 |
+
|
| 82 |
+
- Cannot edit notes containing images or attachments
|
| 83 |
+
- Interactive prompts require terminal access (use pty=true if needed)
|
| 84 |
+
- macOS only — requires Apple Notes.app
|
| 85 |
+
|
| 86 |
+
## Rules
|
| 87 |
+
|
| 88 |
+
1. Prefer Apple Notes when user wants cross-device sync (iPhone/iPad/Mac)
|
| 89 |
+
2. Use the `memory` tool for agent-internal notes that don't need to sync
|
| 90 |
+
3. Use the `obsidian` skill for Markdown-native knowledge management
|
skills/apple/apple-reminders/SKILL.md
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: apple-reminders
|
| 3 |
+
description: "Apple Reminders via remindctl: add, list, complete."
|
| 4 |
+
version: 1.0.0
|
| 5 |
+
author: Hermes Agent
|
| 6 |
+
license: MIT
|
| 7 |
+
platforms: [macos]
|
| 8 |
+
metadata:
|
| 9 |
+
hermes:
|
| 10 |
+
tags: [Reminders, tasks, todo, macOS, Apple]
|
| 11 |
+
prerequisites:
|
| 12 |
+
commands: [remindctl]
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# Apple Reminders
|
| 16 |
+
|
| 17 |
+
Use `remindctl` to manage Apple Reminders directly from the terminal. Tasks sync across all Apple devices via iCloud.
|
| 18 |
+
|
| 19 |
+
## Prerequisites
|
| 20 |
+
|
| 21 |
+
- **macOS** with Reminders.app
|
| 22 |
+
- Install: `brew install steipete/tap/remindctl`
|
| 23 |
+
- Grant Reminders permission when prompted
|
| 24 |
+
- Check: `remindctl status` / Request: `remindctl authorize`
|
| 25 |
+
|
| 26 |
+
## When to Use
|
| 27 |
+
|
| 28 |
+
- User mentions "reminder" or "Reminders app"
|
| 29 |
+
- Creating personal to-dos with due dates that sync to iOS
|
| 30 |
+
- Managing Apple Reminders lists
|
| 31 |
+
- User wants tasks to appear on their iPhone/iPad
|
| 32 |
+
|
| 33 |
+
## When NOT to Use
|
| 34 |
+
|
| 35 |
+
- Scheduling agent alerts → use the cronjob tool instead
|
| 36 |
+
- Calendar events → use Apple Calendar or Google Calendar
|
| 37 |
+
- Project task management → use GitHub Issues, Notion, etc.
|
| 38 |
+
- If user says "remind me" but means an agent alert → clarify first
|
| 39 |
+
|
| 40 |
+
## Quick Reference
|
| 41 |
+
|
| 42 |
+
### View Reminders
|
| 43 |
+
|
| 44 |
+
```bash
|
| 45 |
+
remindctl # Today's reminders
|
| 46 |
+
remindctl today # Today
|
| 47 |
+
remindctl tomorrow # Tomorrow
|
| 48 |
+
remindctl week # This week
|
| 49 |
+
remindctl overdue # Past due
|
| 50 |
+
remindctl all # Everything
|
| 51 |
+
remindctl 2026-01-04 # Specific date
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
### Manage Lists
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
remindctl list # List all lists
|
| 58 |
+
remindctl list Work # Show specific list
|
| 59 |
+
remindctl list Projects --create # Create list
|
| 60 |
+
remindctl list Work --delete # Delete list
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
### Create Reminders
|
| 64 |
+
|
| 65 |
+
```bash
|
| 66 |
+
remindctl add "Buy milk"
|
| 67 |
+
remindctl add --title "Call mom" --list Personal --due tomorrow
|
| 68 |
+
remindctl add --title "Meeting prep" --due "2026-02-15 09:00"
|
| 69 |
+
```
|
| 70 |
+
|
| 71 |
+
### Due Time vs Alarm / Early Nudge
|
| 72 |
+
|
| 73 |
+
`--due` and `--alarm` are different fields:
|
| 74 |
+
|
| 75 |
+
- `--due` sets the reminder's due date/time.
|
| 76 |
+
- `--alarm` sets the EventKit alarm/notification trigger. Timed due reminders may default to an alarm at the due time, but pass `--alarm` explicitly when the user asks for an earlier nudge.
|
| 77 |
+
|
| 78 |
+
For a reminder due at 2:00 PM with a notification 30 minutes earlier:
|
| 79 |
+
|
| 80 |
+
```bash
|
| 81 |
+
remindctl add --title "Hairdresser" --due "2026-05-15 14:00" --alarm "2026-05-15 13:30"
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
To edit an existing reminder:
|
| 85 |
+
|
| 86 |
+
```bash
|
| 87 |
+
remindctl edit 87354 --due "2026-05-15 14:00" --alarm "2026-05-15 13:30"
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
The Reminders UI may show or group the item by the alarm time because that is when the notification fires. Verify with JSON instead of assuming the due time moved:
|
| 91 |
+
|
| 92 |
+
```bash
|
| 93 |
+
remindctl today --json
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
Expected shape:
|
| 97 |
+
|
| 98 |
+
- `dueDate`: actual due time
|
| 99 |
+
- `alarmDate`: notification / early nudge time
|
| 100 |
+
|
| 101 |
+
Apple's public `EKReminder` docs list only reminder-specific properties. Alarm support comes from inherited `EKCalendarItem` behavior exposed by remindctl's `--alarm` flag.
|
| 102 |
+
|
| 103 |
+
### Complete / Delete
|
| 104 |
+
|
| 105 |
+
```bash
|
| 106 |
+
remindctl complete 1 2 3 # Complete by ID
|
| 107 |
+
remindctl delete 4A83 --force # Delete by ID
|
| 108 |
+
```
|
| 109 |
+
|
| 110 |
+
### Output Formats
|
| 111 |
+
|
| 112 |
+
```bash
|
| 113 |
+
remindctl today --json # JSON for scripting
|
| 114 |
+
remindctl today --plain # TSV format
|
| 115 |
+
remindctl today --quiet # Counts only
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
## Date Formats
|
| 119 |
+
|
| 120 |
+
Accepted by `--due` and date filters:
|
| 121 |
+
- `today`, `tomorrow`, `yesterday`
|
| 122 |
+
- `YYYY-MM-DD`
|
| 123 |
+
- `YYYY-MM-DD HH:mm`
|
| 124 |
+
- ISO 8601 (`2026-01-04T12:34:56Z`)
|
| 125 |
+
|
| 126 |
+
## Rules
|
| 127 |
+
|
| 128 |
+
1. When user says "remind me", clarify: Apple Reminders (syncs to phone) vs agent cronjob alert
|
| 129 |
+
2. Always confirm reminder content and due date before creating
|
| 130 |
+
3. Use `--json` for programmatic parsing
|
skills/apple/findmy/SKILL.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
name: findmy
|
| 3 |
+
description: "Track Apple devices/AirTags via FindMy.app on macOS."
|
| 4 |
+
version: 1.0.0
|
| 5 |
+
author: Hermes Agent
|
| 6 |
+
license: MIT
|
| 7 |
+
platforms: [macos]
|
| 8 |
+
metadata:
|
| 9 |
+
hermes:
|
| 10 |
+
tags: [FindMy, AirTag, location, tracking, macOS, Apple]
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
# Find My (Apple)
|
| 14 |
+
|
| 15 |
+
Track Apple devices and AirTags via the FindMy.app on macOS. Since Apple doesn't
|
| 16 |
+
provide a CLI for FindMy, this skill uses AppleScript to open the app and
|
| 17 |
+
screen capture to read device locations.
|
| 18 |
+
|
| 19 |
+
## Prerequisites
|
| 20 |
+
|
| 21 |
+
- **macOS** with Find My app and iCloud signed in
|
| 22 |
+
- Devices/AirTags already registered in Find My
|
| 23 |
+
- Screen Recording permission for terminal (System Settings → Privacy → Screen Recording)
|
| 24 |
+
- **Optional but recommended**: Install `peekaboo` for better UI automation:
|
| 25 |
+
`brew install steipete/tap/peekaboo`
|
| 26 |
+
|
| 27 |
+
## When to Use
|
| 28 |
+
|
| 29 |
+
- User asks "where is my [device/cat/keys/bag]?"
|
| 30 |
+
- Tracking AirTag locations
|
| 31 |
+
- Checking device locations (iPhone, iPad, Mac, AirPods)
|
| 32 |
+
- Monitoring pet or item movement over time (AirTag patrol routes)
|
| 33 |
+
|
| 34 |
+
## Method 1: AppleScript + Screenshot (Basic)
|
| 35 |
+
|
| 36 |
+
### Open FindMy and Navigate
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
# Open Find My app
|
| 40 |
+
osascript -e 'tell application "FindMy" to activate'
|
| 41 |
+
|
| 42 |
+
# Wait for it to load
|
| 43 |
+
sleep 3
|
| 44 |
+
|
| 45 |
+
# Take a screenshot of the Find My window
|
| 46 |
+
screencapture -w -o /tmp/findmy.png
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
Then use `vision_analyze` to read the screenshot:
|
| 50 |
+
```
|
| 51 |
+
vision_analyze(image_url="/tmp/findmy.png", question="What devices/items are shown and what are their locations?")
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
### Switch Between Tabs
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
# Switch to Devices tab
|
| 58 |
+
osascript -e '
|
| 59 |
+
tell application "System Events"
|
| 60 |
+
tell process "FindMy"
|
| 61 |
+
click button "Devices" of toolbar 1 of window 1
|
| 62 |
+
end tell
|
| 63 |
+
end tell'
|
| 64 |
+
|
| 65 |
+
# Switch to Items tab (AirTags)
|
| 66 |
+
osascript -e '
|
| 67 |
+
tell application "System Events"
|
| 68 |
+
tell process "FindMy"
|
| 69 |
+
click button "Items" of toolbar 1 of window 1
|
| 70 |
+
end tell
|
| 71 |
+
end tell'
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
## Method 2: Peekaboo UI Automation (Recommended)
|
| 75 |
+
|
| 76 |
+
If `peekaboo` is installed, use it for more reliable UI interaction:
|
| 77 |
+
|
| 78 |
+
```bash
|
| 79 |
+
# Open Find My
|
| 80 |
+
osascript -e 'tell application "FindMy" to activate'
|
| 81 |
+
sleep 3
|
| 82 |
+
|
| 83 |
+
# Capture and annotate the UI
|
| 84 |
+
peekaboo see --app "FindMy" --annotate --path /tmp/findmy-ui.png
|
| 85 |
+
|
| 86 |
+
# Click on a specific device/item by element ID
|
| 87 |
+
peekaboo click --on B3 --app "FindMy"
|
| 88 |
+
|
| 89 |
+
# Capture the detail view
|
| 90 |
+
peekaboo image --app "FindMy" --path /tmp/findmy-detail.png
|
| 91 |
+
```
|
| 92 |
+
|
| 93 |
+
Then analyze with vision:
|
| 94 |
+
```
|
| 95 |
+
vision_analyze(image_url="/tmp/findmy-detail.png", question="What is the location shown for this device/item? Include address and coordinates if visible.")
|
| 96 |
+
```
|
| 97 |
+
|
| 98 |
+
## Workflow: Track AirTag Location Over Time
|
| 99 |
+
|
| 100 |
+
For monitoring an AirTag (e.g., tracking a cat's patrol route):
|
| 101 |
+
|
| 102 |
+
```bash
|
| 103 |
+
# 1. Open FindMy to Items tab
|
| 104 |
+
osascript -e 'tell application "FindMy" to activate'
|
| 105 |
+
sleep 3
|
| 106 |
+
|
| 107 |
+
# 2. Click on the AirTag item (stay on page — AirTag only updates when page is open)
|
| 108 |
+
|
| 109 |
+
# 3. Periodically capture location
|
| 110 |
+
while true; do
|
| 111 |
+
screencapture -w -o /tmp/findmy-$(date +%H%M%S).png
|
| 112 |
+
sleep 300 # Every 5 minutes
|
| 113 |
+
done
|
| 114 |
+
```
|
| 115 |
+
|
| 116 |
+
Analyze each screenshot with vision to extract coordinates, then compile a route.
|
| 117 |
+
|
| 118 |
+
## Limitations
|
| 119 |
+
|
| 120 |
+
- FindMy has **no CLI or API** — must use UI automation
|
| 121 |
+
- AirTags only update location while the FindMy page is actively displayed
|
| 122 |
+
- Location accuracy depends on nearby Apple devices in the FindMy network
|
| 123 |
+
- Screen Recording permission required for screenshots
|
| 124 |
+
- AppleScript UI automation may break across macOS versions
|
| 125 |
+
|
| 126 |
+
## Rules
|
| 127 |
+
|
| 128 |
+
1. Keep FindMy app in the foreground when tracking AirTags (updates stop when minimized)
|
| 129 |
+
2. Use `vision_analyze` to read screenshot content — don't try to parse pixels
|
| 130 |
+
3. For ongoing tracking, use a cronjob to periodically capture and log locations
|
| 131 |
+
4. Respect privacy — only track devices/items the user owns
|