@aibridge/driver-agy 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +26 -2
- package/dist/index.mjs +126 -4
- package/package.json +2 -2
- package/src/generateImage.test.ts +181 -0
- package/src/generateImage.ts +174 -0
- package/src/index.ts +1 -0
- package/src/run.ts +2 -3
package/dist/index.d.mts
CHANGED
|
@@ -91,6 +91,30 @@ declare function parseModels(modelsById: Record<string, RawModelInfo>): AgyModel
|
|
|
91
91
|
declare function fetchAgyQuota(): Promise<AgyQuotaSnapshot>;
|
|
92
92
|
declare function findModelQuota(snapshot: AgyQuotaSnapshot, labelOrId: string): AgyModelQuota | undefined;
|
|
93
93
|
//#endregion
|
|
94
|
+
//#region src/generateImage.d.ts
|
|
95
|
+
interface ImageGenRequest {
|
|
96
|
+
readonly prompt: string;
|
|
97
|
+
readonly workDir: string;
|
|
98
|
+
readonly backendModel: string;
|
|
99
|
+
readonly effort?: string | undefined;
|
|
100
|
+
readonly aspectRatio: string | undefined;
|
|
101
|
+
readonly imagePaths: readonly string[];
|
|
102
|
+
readonly timeoutSec: number;
|
|
103
|
+
readonly forceful: boolean;
|
|
104
|
+
readonly minBytes: number;
|
|
105
|
+
}
|
|
106
|
+
type ImageResult = {
|
|
107
|
+
readonly kind: 'ok';
|
|
108
|
+
readonly path: string;
|
|
109
|
+
readonly bytes: number;
|
|
110
|
+
} | {
|
|
111
|
+
readonly kind: 'suspect';
|
|
112
|
+
} | {
|
|
113
|
+
readonly kind: 'error';
|
|
114
|
+
readonly reason: string;
|
|
115
|
+
};
|
|
116
|
+
declare function generateImage(req: ImageGenRequest, exec?: typeof runCaptured): Promise<ImageResult>;
|
|
117
|
+
//#endregion
|
|
94
118
|
//#region src/probe.d.ts
|
|
95
119
|
type Availability = {
|
|
96
120
|
readonly ok: true;
|
|
@@ -110,7 +134,7 @@ interface DelegationTask {
|
|
|
110
134
|
readonly tools: boolean;
|
|
111
135
|
readonly timeoutSec: number;
|
|
112
136
|
readonly cwd: string;
|
|
113
|
-
readonly backendModel: string
|
|
137
|
+
readonly backendModel: string;
|
|
114
138
|
readonly effort?: string | undefined;
|
|
115
139
|
readonly onStdout?: (chunk: string) => void;
|
|
116
140
|
readonly onStderr?: (chunk: string) => void;
|
|
@@ -128,4 +152,4 @@ type DelegationResult = {
|
|
|
128
152
|
};
|
|
129
153
|
declare function run(task: DelegationTask, exec?: typeof runCaptured): Promise<DelegationResult>;
|
|
130
154
|
//#endregion
|
|
131
|
-
export { AGY_CANONICAL_TO_NATIVE, type AgyModelQuota, type AgyPrintArgs, type AgyQuotaBucket, type AgyQuotaGroup, type AgyQuotaSnapshot, type Availability, type DelegationResult, type DelegationTask, agyTokenPath, buildAgyPrintArgs, fetchAgyQuota, findModelQuota, parseModels, parseQuotaGroups, probe, run };
|
|
155
|
+
export { AGY_CANONICAL_TO_NATIVE, type AgyModelQuota, type AgyPrintArgs, type AgyQuotaBucket, type AgyQuotaGroup, type AgyQuotaSnapshot, type Availability, type DelegationResult, type DelegationTask, type ImageGenRequest, type ImageResult, agyTokenPath, buildAgyPrintArgs, fetchAgyQuota, findModelQuota, generateImage, parseModels, parseQuotaGroups, probe, run };
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
1
|
+
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
2
2
|
import { homedir, tmpdir } from "node:os";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { isNotFound, runCaptured, stripAnsi } from "@aibridge/proc";
|
|
@@ -189,6 +189,129 @@ async function probe(run = runCaptured) {
|
|
|
189
189
|
}
|
|
190
190
|
}
|
|
191
191
|
//#endregion
|
|
192
|
+
//#region src/generateImage.ts
|
|
193
|
+
async function generateImage(req, exec = runCaptured) {
|
|
194
|
+
const agy = await probe(exec);
|
|
195
|
+
if (!agy.ok) return {
|
|
196
|
+
kind: "error",
|
|
197
|
+
reason: agy.error
|
|
198
|
+
};
|
|
199
|
+
let instruction;
|
|
200
|
+
if (req.imagePaths.length > 0) {
|
|
201
|
+
const refs = req.imagePaths.map((p) => JSON.stringify(p)).join(", ");
|
|
202
|
+
instruction = `Call the generate_image tool once with ImageName="aibridge-render", Prompt=${JSON.stringify(req.prompt)}, and ImagePaths=[${refs}]. Change only what the instruction asks, using the references for subject/identity.${req.aspectRatio ? ` Pass AspectRatio='${req.aspectRatio}' only if applicable.` : ""} After the tool returns, print ONLY the absolute filesystem path of the saved image on a single line. No other text.`;
|
|
203
|
+
} else instruction = `Call the generate_image tool once with ImageName="aibridge-render" and Prompt=${JSON.stringify(req.prompt)}.${req.aspectRatio ? ` Pass AspectRatio='${req.aspectRatio}'.` : ""} After the tool returns, print ONLY the absolute filesystem path of the saved image on a single line. No other text.`;
|
|
204
|
+
const beforePaths = brainImagePaths();
|
|
205
|
+
let result;
|
|
206
|
+
try {
|
|
207
|
+
result = await exec("agy", buildAgyPrintArgs(instruction, {
|
|
208
|
+
model: req.backendModel,
|
|
209
|
+
printTimeoutSec: req.timeoutSec,
|
|
210
|
+
skipPermissions: true,
|
|
211
|
+
addDirs: [req.workDir]
|
|
212
|
+
}), {
|
|
213
|
+
cwd: req.workDir,
|
|
214
|
+
timeoutMs: req.timeoutSec * 1e3
|
|
215
|
+
});
|
|
216
|
+
} catch (err) {
|
|
217
|
+
if (isNotFound(err)) return {
|
|
218
|
+
kind: "error",
|
|
219
|
+
reason: "\"agy\" not found on PATH."
|
|
220
|
+
};
|
|
221
|
+
throw err;
|
|
222
|
+
}
|
|
223
|
+
if (result.timedOut) return {
|
|
224
|
+
kind: "error",
|
|
225
|
+
reason: `agy render timed out after ~${req.timeoutSec}s; raise --timeout.`
|
|
226
|
+
};
|
|
227
|
+
const pathFromStdout = extractPathFromStdout(result.stdout);
|
|
228
|
+
if (pathFromStdout && existsSync(pathFromStdout)) {
|
|
229
|
+
const bytes = safeSize(pathFromStdout);
|
|
230
|
+
if (bytes >= req.minBytes) return {
|
|
231
|
+
kind: "ok",
|
|
232
|
+
path: pathFromStdout,
|
|
233
|
+
bytes
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
const newestHit = newestNewBrainImage(beforePaths);
|
|
237
|
+
if (newestHit && newestHit.bytes >= req.minBytes) return {
|
|
238
|
+
kind: "ok",
|
|
239
|
+
path: newestHit.path,
|
|
240
|
+
bytes: newestHit.bytes
|
|
241
|
+
};
|
|
242
|
+
if (result.code !== 0) {
|
|
243
|
+
const tail = stripAnsi(`${result.stderr}\n${result.stdout}`).trim().split("\n").slice(-3).join(" ").slice(0, 300);
|
|
244
|
+
return {
|
|
245
|
+
kind: "error",
|
|
246
|
+
reason: `agy exited ${result.code}${tail ? `: ${tail}` : ""}.`
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
return { kind: "suspect" };
|
|
250
|
+
}
|
|
251
|
+
function extractPathFromStdout(stdout) {
|
|
252
|
+
const text = stripAnsi(stdout).trim();
|
|
253
|
+
if (!text) return null;
|
|
254
|
+
for (const line of text.split("\n").map((l) => l.trim()).filter(Boolean)) if (line.startsWith("/") && existsSync(line) && isImagePath(line)) return line;
|
|
255
|
+
const m = text.match(/(\/(?:[^\s'"`]+)\.(?:png|jpe?g|webp|gif))/i);
|
|
256
|
+
if (m?.[1] && existsSync(m[1])) return m[1];
|
|
257
|
+
return null;
|
|
258
|
+
}
|
|
259
|
+
function isImagePath(p) {
|
|
260
|
+
return /\.(png|jpe?g|webp|gif)$/i.test(p);
|
|
261
|
+
}
|
|
262
|
+
function brainImagePaths() {
|
|
263
|
+
const root = join(homedir(), ".gemini", "antigravity-cli", "brain");
|
|
264
|
+
const paths = /* @__PURE__ */ new Set();
|
|
265
|
+
for (const session of safeReaddir(root)) {
|
|
266
|
+
const sessionDir = join(root, session);
|
|
267
|
+
for (const f of safeReaddir(sessionDir)) {
|
|
268
|
+
if (f.startsWith(".")) continue;
|
|
269
|
+
if (isImagePath(f)) paths.add(join(sessionDir, f));
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return paths;
|
|
273
|
+
}
|
|
274
|
+
function newestNewBrainImage(before) {
|
|
275
|
+
const root = join(homedir(), ".gemini", "antigravity-cli", "brain");
|
|
276
|
+
const hits = [];
|
|
277
|
+
for (const session of safeReaddir(root)) {
|
|
278
|
+
const sessionDir = join(root, session);
|
|
279
|
+
for (const f of safeReaddir(sessionDir)) {
|
|
280
|
+
if (f.startsWith(".")) continue;
|
|
281
|
+
if (!isImagePath(f)) continue;
|
|
282
|
+
const path = join(sessionDir, f);
|
|
283
|
+
if (!before.has(path)) hits.push({
|
|
284
|
+
path,
|
|
285
|
+
bytes: safeSize(path)
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
if (hits.length === 0) return null;
|
|
290
|
+
hits.sort((a, b) => mtime(b.path) - mtime(a.path));
|
|
291
|
+
return hits[0] ?? null;
|
|
292
|
+
}
|
|
293
|
+
function safeReaddir(dir) {
|
|
294
|
+
try {
|
|
295
|
+
return readdirSync(dir);
|
|
296
|
+
} catch {
|
|
297
|
+
return [];
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
function safeSize(path) {
|
|
301
|
+
try {
|
|
302
|
+
return statSync(path).size;
|
|
303
|
+
} catch {
|
|
304
|
+
return 0;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
function mtime(path) {
|
|
308
|
+
try {
|
|
309
|
+
return statSync(path).mtimeMs;
|
|
310
|
+
} catch {
|
|
311
|
+
return 0;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
//#endregion
|
|
192
315
|
//#region src/run.ts
|
|
193
316
|
const NOISE_RE = /^Shell cwd was reset[^\n]*$/gm;
|
|
194
317
|
const INSTALL_HINT = "Install the Antigravity CLI and sign in.";
|
|
@@ -206,9 +329,8 @@ async function run(task, exec = runCaptured) {
|
|
|
206
329
|
taskPrompt = `${task.prompt}\n\nYou are working in the repository rooted at ${task.cwd}; make ALL file edits there (any relative paths in the task are relative to that root). When the task is complete, write ONLY your final answer (the exact text you would otherwise print as your response, with no narration of your steps) to the file ${answerPath} — nothing else in that file. This is how your answer is captured; do not mention the file in the answer.`;
|
|
207
330
|
addDirs.push(task.cwd, tempDir);
|
|
208
331
|
}
|
|
209
|
-
const modelId = task.backendModel ?? "";
|
|
210
332
|
const args = buildAgyPrintArgs(taskPrompt, {
|
|
211
|
-
model:
|
|
333
|
+
model: task.backendModel,
|
|
212
334
|
printTimeoutSec: task.timeoutSec,
|
|
213
335
|
skipPermissions: task.tools,
|
|
214
336
|
addDirs: addDirs.length > 0 ? addDirs : void 0
|
|
@@ -268,4 +390,4 @@ async function run(task, exec = runCaptured) {
|
|
|
268
390
|
}
|
|
269
391
|
}
|
|
270
392
|
//#endregion
|
|
271
|
-
export { AGY_CANONICAL_TO_NATIVE, agyTokenPath, buildAgyPrintArgs, fetchAgyQuota, findModelQuota, parseModels, parseQuotaGroups, probe, run };
|
|
393
|
+
export { AGY_CANONICAL_TO_NATIVE, agyTokenPath, buildAgyPrintArgs, fetchAgyQuota, findModelQuota, generateImage, parseModels, parseQuotaGroups, probe, run };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aibridge/driver-agy",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Antigravity (agy) CLI driver for aibridge",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"src"
|
|
33
33
|
],
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@aibridge/proc": "0.
|
|
35
|
+
"@aibridge/proc": "0.3.0"
|
|
36
36
|
},
|
|
37
37
|
"devDependencies": {
|
|
38
38
|
"tsdown": "0.22.14"
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import type { RunResult } from '@aibridge/proc';
|
|
5
|
+
import { describe, expect, it } from 'vitest';
|
|
6
|
+
import { generateImage, type ImageGenRequest } from './generateImage.ts';
|
|
7
|
+
|
|
8
|
+
describe('generateImage', () => {
|
|
9
|
+
const baseReq: ImageGenRequest = {
|
|
10
|
+
prompt: 'A futuristic city skyline',
|
|
11
|
+
workDir: '/tmp/work',
|
|
12
|
+
backendModel: 'gemini-3.6-flash-high',
|
|
13
|
+
aspectRatio: undefined,
|
|
14
|
+
imagePaths: [],
|
|
15
|
+
timeoutSec: 600,
|
|
16
|
+
forceful: false,
|
|
17
|
+
minBytes: 10_000,
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
it('assembles correct prompt and argv shape for standard generation', async () => {
|
|
21
|
+
let capturedCmd = '';
|
|
22
|
+
let capturedArgs: readonly string[] = [];
|
|
23
|
+
|
|
24
|
+
const fakeExec = async (cmd: string, args: readonly string[]): Promise<RunResult> => {
|
|
25
|
+
if (args.includes('--version')) {
|
|
26
|
+
return {
|
|
27
|
+
code: 0,
|
|
28
|
+
signal: null,
|
|
29
|
+
stdout: 'agy version 1.0.0\n',
|
|
30
|
+
stderr: '',
|
|
31
|
+
timedOut: false,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
capturedCmd = cmd;
|
|
35
|
+
capturedArgs = args;
|
|
36
|
+
return { code: 0, signal: null, stdout: '', stderr: '', timedOut: false };
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const req: ImageGenRequest = {
|
|
40
|
+
...baseReq,
|
|
41
|
+
aspectRatio: '16:9',
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
await generateImage(req, fakeExec);
|
|
45
|
+
|
|
46
|
+
expect(capturedCmd).toBe('agy');
|
|
47
|
+
expect(capturedArgs).toContain('--model');
|
|
48
|
+
expect(capturedArgs).toContain('gemini-3.6-flash-high');
|
|
49
|
+
expect(capturedArgs).toContain('--dangerously-skip-permissions');
|
|
50
|
+
|
|
51
|
+
const promptIdx = capturedArgs.indexOf('-p');
|
|
52
|
+
expect(promptIdx).toBeGreaterThan(-1);
|
|
53
|
+
const promptArg = capturedArgs[promptIdx + 1] ?? '';
|
|
54
|
+
|
|
55
|
+
expect(promptArg).toContain('generate_image');
|
|
56
|
+
expect(promptArg).toContain('16:9');
|
|
57
|
+
expect(promptArg).toContain('print ONLY the absolute filesystem path');
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it('omits AspectRatio clause when aspectRatio is undefined', async () => {
|
|
61
|
+
let capturedPrompt = '';
|
|
62
|
+
|
|
63
|
+
const fakeExec = async (_cmd: string, args: readonly string[]): Promise<RunResult> => {
|
|
64
|
+
if (args.includes('--version')) {
|
|
65
|
+
return {
|
|
66
|
+
code: 0,
|
|
67
|
+
signal: null,
|
|
68
|
+
stdout: 'agy version 1.0.0\n',
|
|
69
|
+
stderr: '',
|
|
70
|
+
timedOut: false,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const promptIdx = args.indexOf('-p');
|
|
74
|
+
capturedPrompt = args[promptIdx + 1] ?? '';
|
|
75
|
+
return { code: 0, signal: null, stdout: '', stderr: '', timedOut: false };
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
await generateImage(baseReq, fakeExec);
|
|
79
|
+
|
|
80
|
+
expect(capturedPrompt).not.toContain('AspectRatio');
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
it('includes ImagePaths in prompt when reference images are provided', async () => {
|
|
84
|
+
let capturedPrompt = '';
|
|
85
|
+
|
|
86
|
+
const fakeExec = async (_cmd: string, args: readonly string[]): Promise<RunResult> => {
|
|
87
|
+
if (args.includes('--version')) {
|
|
88
|
+
return {
|
|
89
|
+
code: 0,
|
|
90
|
+
signal: null,
|
|
91
|
+
stdout: 'agy version 1.0.0\n',
|
|
92
|
+
stderr: '',
|
|
93
|
+
timedOut: false,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
const promptIdx = args.indexOf('-p');
|
|
97
|
+
capturedPrompt = args[promptIdx + 1] ?? '';
|
|
98
|
+
return { code: 0, signal: null, stdout: '', stderr: '', timedOut: false };
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const req: ImageGenRequest = {
|
|
102
|
+
...baseReq,
|
|
103
|
+
imagePaths: ['/tmp/a.png'],
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
await generateImage(req, fakeExec);
|
|
107
|
+
|
|
108
|
+
expect(capturedPrompt).toContain('ImagePaths');
|
|
109
|
+
expect(capturedPrompt).toContain('/tmp/a.png');
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
it('returns ok when stdout path is printed and exists with sufficient bytes', async () => {
|
|
113
|
+
const tmpDir = mkdtempSync(join(tmpdir(), 'agy-img-test-'));
|
|
114
|
+
const imgPath = join(tmpDir, 'output.png');
|
|
115
|
+
const content = Buffer.alloc(12_000);
|
|
116
|
+
writeFileSync(imgPath, content);
|
|
117
|
+
|
|
118
|
+
try {
|
|
119
|
+
const fakeExec = async (_cmd: string, args: readonly string[]): Promise<RunResult> => {
|
|
120
|
+
if (args.includes('--version')) {
|
|
121
|
+
return {
|
|
122
|
+
code: 0,
|
|
123
|
+
signal: null,
|
|
124
|
+
stdout: 'agy version 1.0.0\n',
|
|
125
|
+
stderr: '',
|
|
126
|
+
timedOut: false,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
return { code: 0, signal: null, stdout: `${imgPath}\n`, stderr: '', timedOut: false };
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
const res = await generateImage(baseReq, fakeExec);
|
|
133
|
+
expect(res).toEqual({
|
|
134
|
+
kind: 'ok',
|
|
135
|
+
path: imgPath,
|
|
136
|
+
bytes: 12_000,
|
|
137
|
+
});
|
|
138
|
+
} finally {
|
|
139
|
+
rmSync(tmpDir, { recursive: true, force: true });
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it('returns error when command times out', async () => {
|
|
144
|
+
const fakeExec = async (_cmd: string, args: readonly string[]): Promise<RunResult> => {
|
|
145
|
+
if (args.includes('--version')) {
|
|
146
|
+
return {
|
|
147
|
+
code: 0,
|
|
148
|
+
signal: null,
|
|
149
|
+
stdout: 'agy version 1.0.0\n',
|
|
150
|
+
stderr: '',
|
|
151
|
+
timedOut: false,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
return { code: null, signal: 'SIGTERM', stdout: '', stderr: '', timedOut: true };
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
const res = await generateImage(baseReq, fakeExec);
|
|
158
|
+
expect(res.kind).toBe('error');
|
|
159
|
+
if (res.kind === 'error') {
|
|
160
|
+
expect(res.reason).toContain('--timeout');
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
it('returns suspect when no output is produced and exit code is 0', async () => {
|
|
165
|
+
const fakeExec = async (_cmd: string, args: readonly string[]): Promise<RunResult> => {
|
|
166
|
+
if (args.includes('--version')) {
|
|
167
|
+
return {
|
|
168
|
+
code: 0,
|
|
169
|
+
signal: null,
|
|
170
|
+
stdout: 'agy version 1.0.0\n',
|
|
171
|
+
stderr: '',
|
|
172
|
+
timedOut: false,
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
return { code: 0, signal: null, stdout: 'Done tool call', stderr: '', timedOut: false };
|
|
176
|
+
};
|
|
177
|
+
|
|
178
|
+
const res = await generateImage(baseReq, fakeExec);
|
|
179
|
+
expect(res).toEqual({ kind: 'suspect' });
|
|
180
|
+
});
|
|
181
|
+
});
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { existsSync, readdirSync, statSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { isNotFound, type RunResult, runCaptured, stripAnsi } from '@aibridge/proc';
|
|
5
|
+
import { buildAgyPrintArgs } from './agy.ts';
|
|
6
|
+
import { probe } from './probe.ts';
|
|
7
|
+
|
|
8
|
+
export interface ImageGenRequest {
|
|
9
|
+
readonly prompt: string;
|
|
10
|
+
readonly workDir: string;
|
|
11
|
+
readonly backendModel: string;
|
|
12
|
+
readonly effort?: string | undefined;
|
|
13
|
+
readonly aspectRatio: string | undefined;
|
|
14
|
+
readonly imagePaths: readonly string[];
|
|
15
|
+
readonly timeoutSec: number;
|
|
16
|
+
readonly forceful: boolean;
|
|
17
|
+
readonly minBytes: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type ImageResult =
|
|
21
|
+
| { readonly kind: 'ok'; readonly path: string; readonly bytes: number }
|
|
22
|
+
| { readonly kind: 'suspect' }
|
|
23
|
+
| { readonly kind: 'error'; readonly reason: string };
|
|
24
|
+
|
|
25
|
+
interface Render {
|
|
26
|
+
readonly path: string;
|
|
27
|
+
readonly bytes: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function generateImage(
|
|
31
|
+
req: ImageGenRequest,
|
|
32
|
+
exec: typeof runCaptured = runCaptured,
|
|
33
|
+
): Promise<ImageResult> {
|
|
34
|
+
const agy = await probe(exec);
|
|
35
|
+
if (!agy.ok) return { kind: 'error', reason: agy.error };
|
|
36
|
+
|
|
37
|
+
let instruction: string;
|
|
38
|
+
if (req.imagePaths.length > 0) {
|
|
39
|
+
const refs = req.imagePaths.map(p => JSON.stringify(p)).join(', ');
|
|
40
|
+
instruction =
|
|
41
|
+
`Call the generate_image tool once with ImageName="aibridge-render", Prompt=${JSON.stringify(req.prompt)}, and ImagePaths=[${refs}]. ` +
|
|
42
|
+
`Change only what the instruction asks, using the references for subject/identity.` +
|
|
43
|
+
`${req.aspectRatio ? ` Pass AspectRatio='${req.aspectRatio}' only if applicable.` : ''}` +
|
|
44
|
+
` After the tool returns, print ONLY the absolute filesystem path of the saved image on a single line. No other text.`;
|
|
45
|
+
} else {
|
|
46
|
+
instruction =
|
|
47
|
+
`Call the generate_image tool once with ImageName="aibridge-render" and Prompt=${JSON.stringify(req.prompt)}.` +
|
|
48
|
+
`${req.aspectRatio ? ` Pass AspectRatio='${req.aspectRatio}'.` : ''}` +
|
|
49
|
+
` After the tool returns, print ONLY the absolute filesystem path of the saved image on a single line. No other text.`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const beforePaths = brainImagePaths();
|
|
53
|
+
|
|
54
|
+
let result: RunResult;
|
|
55
|
+
try {
|
|
56
|
+
const args = buildAgyPrintArgs(instruction, {
|
|
57
|
+
model: req.backendModel,
|
|
58
|
+
printTimeoutSec: req.timeoutSec,
|
|
59
|
+
skipPermissions: true,
|
|
60
|
+
addDirs: [req.workDir],
|
|
61
|
+
});
|
|
62
|
+
result = await exec('agy', args, { cwd: req.workDir, timeoutMs: req.timeoutSec * 1000 });
|
|
63
|
+
} catch (err) {
|
|
64
|
+
if (isNotFound(err)) return { kind: 'error', reason: '"agy" not found on PATH.' };
|
|
65
|
+
throw err;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (result.timedOut) {
|
|
69
|
+
return {
|
|
70
|
+
kind: 'error',
|
|
71
|
+
reason: `agy render timed out after ~${req.timeoutSec}s; raise --timeout.`,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const pathFromStdout = extractPathFromStdout(result.stdout);
|
|
76
|
+
if (pathFromStdout && existsSync(pathFromStdout)) {
|
|
77
|
+
const bytes = safeSize(pathFromStdout);
|
|
78
|
+
if (bytes >= req.minBytes) {
|
|
79
|
+
return { kind: 'ok', path: pathFromStdout, bytes };
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const newestHit = newestNewBrainImage(beforePaths);
|
|
84
|
+
if (newestHit && newestHit.bytes >= req.minBytes) {
|
|
85
|
+
return { kind: 'ok', path: newestHit.path, bytes: newestHit.bytes };
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (result.code !== 0) {
|
|
89
|
+
const tail = stripAnsi(`${result.stderr}\n${result.stdout}`)
|
|
90
|
+
.trim()
|
|
91
|
+
.split('\n')
|
|
92
|
+
.slice(-3)
|
|
93
|
+
.join(' ')
|
|
94
|
+
.slice(0, 300);
|
|
95
|
+
return { kind: 'error', reason: `agy exited ${result.code}${tail ? `: ${tail}` : ''}.` };
|
|
96
|
+
}
|
|
97
|
+
return { kind: 'suspect' };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function extractPathFromStdout(stdout: string): string | null {
|
|
101
|
+
const text = stripAnsi(stdout).trim();
|
|
102
|
+
if (!text) return null;
|
|
103
|
+
for (const line of text
|
|
104
|
+
.split('\n')
|
|
105
|
+
.map(l => l.trim())
|
|
106
|
+
.filter(Boolean)) {
|
|
107
|
+
if (line.startsWith('/') && existsSync(line) && isImagePath(line)) return line;
|
|
108
|
+
}
|
|
109
|
+
const m = text.match(/(\/(?:[^\s'"`]+)\.(?:png|jpe?g|webp|gif))/i);
|
|
110
|
+
if (m?.[1] && existsSync(m[1])) return m[1];
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function isImagePath(p: string): boolean {
|
|
115
|
+
return /\.(png|jpe?g|webp|gif)$/i.test(p);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function brainImagePaths(): Set<string> {
|
|
119
|
+
const root = join(homedir(), '.gemini', 'antigravity-cli', 'brain');
|
|
120
|
+
const paths = new Set<string>();
|
|
121
|
+
for (const session of safeReaddir(root)) {
|
|
122
|
+
const sessionDir = join(root, session);
|
|
123
|
+
for (const f of safeReaddir(sessionDir)) {
|
|
124
|
+
if (f.startsWith('.')) continue;
|
|
125
|
+
if (isImagePath(f)) {
|
|
126
|
+
paths.add(join(sessionDir, f));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return paths;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function newestNewBrainImage(before: Set<string>): Render | null {
|
|
134
|
+
const root = join(homedir(), '.gemini', 'antigravity-cli', 'brain');
|
|
135
|
+
const hits: Render[] = [];
|
|
136
|
+
for (const session of safeReaddir(root)) {
|
|
137
|
+
const sessionDir = join(root, session);
|
|
138
|
+
for (const f of safeReaddir(sessionDir)) {
|
|
139
|
+
if (f.startsWith('.')) continue;
|
|
140
|
+
if (!isImagePath(f)) continue;
|
|
141
|
+
const path = join(sessionDir, f);
|
|
142
|
+
if (!before.has(path)) {
|
|
143
|
+
hits.push({ path, bytes: safeSize(path) });
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (hits.length === 0) return null;
|
|
148
|
+
hits.sort((a, b) => mtime(b.path) - mtime(a.path));
|
|
149
|
+
return hits[0] ?? null;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function safeReaddir(dir: string): string[] {
|
|
153
|
+
try {
|
|
154
|
+
return readdirSync(dir);
|
|
155
|
+
} catch {
|
|
156
|
+
return [];
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function safeSize(path: string): number {
|
|
161
|
+
try {
|
|
162
|
+
return statSync(path).size;
|
|
163
|
+
} catch {
|
|
164
|
+
return 0;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function mtime(path: string): number {
|
|
169
|
+
try {
|
|
170
|
+
return statSync(path).mtimeMs;
|
|
171
|
+
} catch {
|
|
172
|
+
return 0;
|
|
173
|
+
}
|
|
174
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -10,6 +10,7 @@ export {
|
|
|
10
10
|
parseModels,
|
|
11
11
|
parseQuotaGroups,
|
|
12
12
|
} from './agyQuota.ts';
|
|
13
|
+
export { generateImage, type ImageGenRequest, type ImageResult } from './generateImage.ts';
|
|
13
14
|
export { type Availability, probe } from './probe.ts';
|
|
14
15
|
export { AGY_CANONICAL_TO_NATIVE } from './registry.ts';
|
|
15
16
|
export { type DelegationResult, type DelegationTask, run } from './run.ts';
|
package/src/run.ts
CHANGED
|
@@ -9,7 +9,7 @@ export interface DelegationTask {
|
|
|
9
9
|
readonly tools: boolean;
|
|
10
10
|
readonly timeoutSec: number;
|
|
11
11
|
readonly cwd: string;
|
|
12
|
-
readonly backendModel: string
|
|
12
|
+
readonly backendModel: string;
|
|
13
13
|
readonly effort?: string | undefined;
|
|
14
14
|
readonly onStdout?: (chunk: string) => void;
|
|
15
15
|
readonly onStderr?: (chunk: string) => void;
|
|
@@ -54,9 +54,8 @@ export async function run(
|
|
|
54
54
|
addDirs.push(task.cwd, tempDir);
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
const modelId = task.backendModel ?? '';
|
|
58
57
|
const args = buildAgyPrintArgs(taskPrompt, {
|
|
59
|
-
model:
|
|
58
|
+
model: task.backendModel,
|
|
60
59
|
printTimeoutSec: task.timeoutSec,
|
|
61
60
|
skipPermissions: task.tools,
|
|
62
61
|
addDirs: addDirs.length > 0 ? addDirs : undefined,
|