Files
pi-gori-media/extensions/goritech-media.ts
T

572 lines
22 KiB
TypeScript

/**
* Goritech Media Extension
*
* Adds three model-callable tools backed by an OpenAI-compatible media gateway:
*
* - generate_image: text-to-image (images/generations)
* - edit_image: image-to-image / edit (images/edits)
* - generate_video: text/image/first+last-frame video (videos, async job polling)
*
* Configuration (all optional if using defaults):
* GORITECHES_BASE_URL API base URL (default: https://api.goriteches.com/v1)
* GORITECHES_API_KEY API key; falls back to "goriteches" provider in ~/.pi/agent/models.json
* GORITECHES_IMAGE_MODEL default image generation model (default: gpt-image-2.5-flare)
* GORITECHES_EDIT_IMAGE_MODEL default image edit model (default: gpt-image-2.5-sunburst)
* GORITECHES_VIDEO_MODEL default video model (default: grok-imagine-video-1.5)
*
* Generated files are written to ./goritech-media/ under the current working directory.
*
* NOTE: video results are only stored for a limited time after completion;
* failed jobs can be re-downloaded later with /gori-fetch <request_id>.
*/
import { Type } from "@earendil-works/pi-ai";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { Text } from "@earendil-works/pi-tui";
import { execFile } from "node:child_process";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
const BASE_URL = process.env.GORITECHES_BASE_URL ?? "https://api.goriteches.com/v1";
const IMAGE_MODEL = process.env.GORITECHES_IMAGE_MODEL ?? "gpt-image-2.5-flare";
const EDIT_IMAGE_MODEL = process.env.GORITECHES_EDIT_IMAGE_MODEL ?? "gpt-image-2.5-sunburst";
const VIDEO_MODEL = process.env.GORITECHES_VIDEO_MODEL ?? "grok-imagine-video-1.5";
// ---------------------------------------------------------------------------
// API key resolution
// ---------------------------------------------------------------------------
let cachedApiKey: string | undefined;
function resolveApiKey(): string {
if (cachedApiKey) return cachedApiKey;
if (process.env.GORITECHES_API_KEY) {
cachedApiKey = process.env.GORITECHES_API_KEY;
return cachedApiKey;
}
try {
const modelsJson = JSON.parse(
fs.readFileSync(path.join(os.homedir(), ".pi/agent/models.json"), "utf8"),
);
const key = modelsJson?.providers?.goriteches?.apiKey;
if (typeof key === "string" && key) {
cachedApiKey = key;
return key;
}
} catch {
// fall through
}
throw new Error(
"No goriteches API key found. Set GORITECHES_API_KEY or configure the goriteches provider in ~/.pi/agent/models.json.",
);
}
// ---------------------------------------------------------------------------
// HTTP helpers
//
// IMPORTANT: all video API calls go through curl via child_process. The
// gateway routes by TLS/HTTP2 client fingerprint; Node's TLS stack gets
// pinned to the upstream node that created the video job and the MP4 is not
// synced across nodes, causing persistent 404s on /content after "done".
// curl's fingerprint routes correctly every time (verified empirically).
// ---------------------------------------------------------------------------
async function curl(args: string[], maxBuffer = 256 * 1024 * 1024): Promise<string> {
const { stdout } = await execFileAsync("curl", args, { maxBuffer });
return stdout.toString();
}
async function apiPost(urlPath: string, body: unknown): Promise<any> {
const tmp = path.join(os.tmpdir(), `gori-req-${Date.now()}-${Math.random().toString(36).slice(2)}.json`);
fs.writeFileSync(tmp, JSON.stringify(body));
try {
const text = await curl([
"-sS", "-m", "60", "-X", "POST",
`${BASE_URL}${urlPath}`,
"-H", `Authorization: Bearer ${resolveApiKey()}`,
"-H", "Content-Type: application/json",
"-d", `@${tmp}`,
]);
let json: any;
try { json = JSON.parse(text); } catch { throw new Error(`POST ${urlPath} -> ${text.slice(0, 300)}`); }
if (json?.error) throw new Error(`POST ${urlPath} -> ${json.error.message ?? text.slice(0, 300)}`);
return json;
} finally {
fs.rmSync(tmp, { force: true });
}
}
async function apiGetJson(urlPath: string): Promise<{ status: number; json: any }> {
const text = await curl(["-sS", "-m", "30", `${BASE_URL}${urlPath}`, "-H", `Authorization: Bearer ${resolveApiKey()}`, "-w", "\n%{http_code}"]);
const m = text.match(/\n(\d{3})\s*$/);
const status = m ? parseInt(m[1], 10) : 0;
const body = m ? text.slice(0, -m[0].length) : text;
try {
return { status, json: JSON.parse(body) };
} catch {
return { status, json: undefined };
}
}
async function apiDownload(urlPath: string, outFile: string): Promise<number> {
const url = `${BASE_URL}${urlPath}`;
const text = await curl([
"-sS", "-m", "120", url,
"-H", `Authorization: Bearer ${resolveApiKey()}`,
"-o", outFile, "-w", "%{http_code}",
]);
const code = parseInt(text.trim(), 10) || 0;
return code;
}
interface VideoJobResult {
status: any;
buf: Buffer;
}
async function runVideoJob(requestId: string): Promise<VideoJobResult> {
// poll
let status: any;
const deadline = Date.now() + 12 * 60 * 1000;
for (;;) {
if (Date.now() > deadline) throw new Error(`timed out waiting for job ${requestId}`);
await new Promise((r) => setTimeout(r, 5000));
const poll = await apiGetJson(`/videos/${requestId}`);
if (!poll.json) continue;
status = poll.json;
if (status.status === "done") break;
if (["failed", "error", "cancelled"].includes(status.status)) {
throw new Error(`job ${status.status}: ${JSON.stringify(status).slice(0, 200)}`);
}
}
const contentPath: string | undefined = status?.video?.url;
if (!contentPath) throw new Error(`job done but no video url`);
// status.video.url already includes the /v1 prefix; strip it since apiDownload prepends BASE_URL
const contentRel = contentPath.replace(/^\/v1/, "");
// download
const outPath = path.join(os.tmpdir(), `gori-out-${requestId}.mp4`);
try {
const dlDeadline = Date.now() + 10 * 60 * 1000;
for (;;) {
const code = await apiDownload(contentRel, outPath);
if (code === 200) {
return { status, buf: fs.readFileSync(outPath) };
}
if (Date.now() > dlDeadline) throw new Error(`download HTTP ${code} timeout`);
await new Promise((r) => setTimeout(r, 5000));
}
} finally {
fs.rmSync(outPath, { force: true });
}
}
// ---------------------------------------------------------------------------
// File helpers
// ---------------------------------------------------------------------------
// Session-scoped output directory override (set via /gori-output)
let sessionOutputDir: string | undefined;
function outputDir(cwd: string): string {
const dir = sessionOutputDir ?? process.env.GORITECHES_OUTPUT_DIR ?? path.join(cwd, "goritech-media");
fs.mkdirSync(dir, { recursive: true });
return dir;
}
function timestamp(): string {
return new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
}
function slug(text: string): string {
return (
text
.toLowerCase()
.replace(/[^a-z0-9一-鿿]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 30) || "media"
);
}
/** Read a local image file and return a data URI. */
function fileToDataUri(filePath: string): string {
const abs = path.resolve(filePath);
if (!fs.existsSync(abs)) throw new Error(`File not found: ${abs}`);
const ext = path.extname(abs).toLowerCase();
const mime =
ext === ".png" ? "image/png"
: ext === ".jpg" || ext === ".jpeg" ? "image/jpeg"
: ext === ".webp" ? "image/webp"
: ext === ".gif" ? "image/gif"
: undefined;
if (!mime) throw new Error(`Unsupported image extension "${ext}" for ${abs} (use png/jpg/webp/gif)`);
const b64 = fs.readFileSync(abs).toString("base64");
return `data:${mime};base64,${b64}`;
}
/** Accept a local path, http(s) URL, or data URI and return an API-usable image URL. */
function toImageUrl(input: string): string {
if (/^https?:\/\//i.test(input)) return input;
if (input.startsWith("data:image/")) return input;
return fileToDataUri(input);
}
function formatCost(ticks: unknown): string {
const n = Number(ticks);
if (!Number.isFinite(n)) return "unknown";
return `$${(n / 1e10).toFixed(3)}`;
}
// ---------------------------------------------------------------------------
// Extension
// ---------------------------------------------------------------------------
export default function goritechMedia(pi: ExtensionAPI) {
// -----------------------------------------------------------------------
// generate_image
// -----------------------------------------------------------------------
pi.registerTool({
name: "generate_image",
label: "Generate Image",
description: `Generate an image from a text prompt using ${IMAGE_MODEL} via the goriteches gateway. Returns the saved PNG file path. Use this whenever the user asks to draw, paint, or generate a picture/image.`,
parameters: Type.Object({
prompt: Type.String({ description: "Text description of the image to generate" }),
size: Type.Optional(
Type.Union(
[Type.Literal("1024x1024"), Type.Literal("1536x1024"), Type.Literal("1024x1536"), Type.Literal("auto")],
{ description: "Image size (default: 1024x1024)" },
),
),
filename: Type.Optional(Type.String({ description: "Optional output file name (without extension)" })),
}),
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
const cwd = ctx?.cwd ?? process.cwd();
const result = await apiPost("/images/generations", {
model: IMAGE_MODEL,
prompt: params.prompt,
size: params.size ?? "1024x1024",
});
const item = result?.data?.[0];
if (!item?.b64_json) {
throw new Error(`Unexpected images API response: ${JSON.stringify(result).slice(0, 300)}`);
}
const name = params.filename ?? `${timestamp()}-${slug(params.prompt)}`;
const filePath = path.join(outputDir(cwd), `${name}.png`);
fs.writeFileSync(filePath, Buffer.from(item.b64_json, "base64"));
return {
content: [
{ type: "text", text: `Image saved to: ${filePath}\nModel: ${IMAGE_MODEL} | Prompt: ${params.prompt}` },
{ type: "image", data: item.b64_json, mimeType: "image/png" },
],
details: { path: filePath, prompt: params.prompt, model: IMAGE_MODEL },
};
},
renderCall(args, theme) {
let text = theme.fg("toolTitle", theme.bold("generate_image "));
text += theme.fg("accent", args.prompt?.length > 60 ? `${args.prompt.slice(0, 57)}...` : args.prompt ?? "");
if (args.size) text += theme.fg("dim", ` (${args.size})`);
return new Text(text, 0, 0);
},
renderResult(result, { isPartial }, theme) {
if (isPartial) return new Text(theme.fg("warning", "Generating image..."), 0, 0);
const details = result.details as { path?: string } | undefined;
if (details?.path) {
return new Text(`${theme.fg("success", "✓ image")} ${theme.fg("accent", details.path)}`, 0, 0);
}
const content = result.content[0];
return new Text(content?.type === "text" ? content.text.slice(0, 200) : "done", 0, 0);
},
});
// -----------------------------------------------------------------------
// edit_image
// -----------------------------------------------------------------------
pi.registerTool({
name: "edit_image",
label: "Edit Image",
description: `Edit or transform an existing image using ${EDIT_IMAGE_MODEL} via the goriteches gateway (image-to-image / inpainting-style editing). Accepts one or more source images (local path, http(s) URL, or data URI) plus a text instruction describing the change. Returns the saved PNG file path. Use this whenever the user asks to modify, restyle, recolor, add/remove elements, or otherwise edit an existing image.`,
parameters: Type.Object({
image: Type.String({ description: "Source image: local file path (png/jpg/webp/gif), http(s) URL, or data URI" }),
prompt: Type.String({ description: "Text instruction describing the edit, e.g. 'change the circle to blue', 'add a party hat', 'make it watercolor style'" }),
extra_images: Type.Optional(
Type.Array(Type.String(), { description: "Additional reference/source images (same formats as image)" }),
),
filename: Type.Optional(Type.String({ description: "Optional output file name (without extension)" })),
}),
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
const cwd = ctx?.cwd ?? process.cwd();
const images = [params.image, ...(params.extra_images ?? [])].map((src) => ({ image_url: toImageUrl(src) }));
const result = await apiPost("/images/edits", {
model: EDIT_IMAGE_MODEL,
prompt: params.prompt,
images,
});
const item = result?.data?.[0];
if (!item?.b64_json) {
throw new Error(`Unexpected images/edits API response: ${JSON.stringify(result).slice(0, 300)}`);
}
const name = params.filename ?? `${timestamp()}-edit-${slug(params.prompt)}`;
const filePath = path.join(outputDir(cwd), `${name}.png`);
fs.writeFileSync(filePath, Buffer.from(item.b64_json, "base64"));
return {
content: [
{
type: "text",
text: `Edited image saved to: ${filePath}\nModel: ${EDIT_IMAGE_MODEL} | Source: ${params.image} | Edit: ${params.prompt}`,
},
{ type: "image", data: item.b64_json, mimeType: "image/png" },
],
details: { path: filePath, prompt: params.prompt, source: params.image, model: EDIT_IMAGE_MODEL },
};
},
renderCall(args, theme) {
let text = theme.fg("toolTitle", theme.bold("edit_image "));
text += theme.fg("accent", args.prompt?.length > 50 ? `${args.prompt.slice(0, 47)}...` : args.prompt ?? "");
if (args.image) text += theme.fg("dim", ` [${path.basename(args.image)}]`);
return new Text(text, 0, 0);
},
renderResult(result, { isPartial }, theme) {
if (isPartial) return new Text(theme.fg("warning", "Editing image..."), 0, 0);
const details = result.details as { path?: string } | undefined;
if (details?.path) {
return new Text(`${theme.fg("success", "✓ edited")} ${theme.fg("accent", details.path)}`, 0, 0);
}
const content = result.content[0];
return new Text(content?.type === "text" ? content.text.slice(0, 200) : "done", 0, 0);
},
});
// -----------------------------------------------------------------------
// generate_video
// -----------------------------------------------------------------------
pi.registerTool({
name: "generate_video",
label: "Generate Video",
description: `Generate a video using ${VIDEO_MODEL} via the goriteches gateway (xAI upstream). Supports pinning the exact first frame and/or last frame from local image files/URLs; the model interpolates between them. Also supports plain text-to-video when no frames are given. This is an async job (usually 1-3 minutes). Returns the saved MP4 file path.`,
parameters: Type.Object({
prompt: Type.Optional(
Type.String({ description: "Motion/transition description (optional when frames are pinned)" }),
),
first_frame: Type.Optional(
Type.String({ description: "First frame: local image path (png/jpg/webp), http(s) URL, or data URI" }),
),
last_frame: Type.Optional(
Type.String({
description:
"Last frame: local image path (png/jpg/webp), http(s) URL, or data URI. Requires grok-imagine-video-1.5.",
}),
),
duration: Type.Optional(
Type.Number({ description: "Video length in seconds, 1-15 (default: 8). Longer costs more (~$0.08/s)." }),
),
filename: Type.Optional(Type.String({ description: "Optional output file name (without extension)" })),
}),
async execute(_toolCallId, params, _signal, onUpdate, ctx) {
const cwd = ctx?.cwd ?? process.cwd();
if (!params.prompt && !params.first_frame && !params.last_frame) {
throw new Error("Provide at least a prompt or a frame image.");
}
const body: Record<string, unknown> = {
model: VIDEO_MODEL,
prompt: params.prompt ?? "",
duration: Math.min(Math.max(Math.round(params.duration ?? 8), 1), 15),
};
if (params.first_frame) body.image = { url: toImageUrl(params.first_frame) };
if (params.last_frame) body.last_frame = { url: toImageUrl(params.last_frame) };
const created = await apiPost("/videos", body);
const requestId: string | undefined = created?.request_id;
if (!requestId) throw new Error(`Unexpected videos API response: ${JSON.stringify(created).slice(0, 300)}`);
onUpdate?.({
content: [{ type: "text", text: `Video job ${requestId} submitted, generating...` }],
details: { requestId, status: "submitted" },
});
// Poll + download in a detached child process. Pi's provider client holds
// an HTTP/2 connection to the gateway that gets pinned to the upstream
// node which created this job; the MP4 is not synced across nodes, so
// in-process requests hit persistent 404s on /content after "done".
let jobResult: VideoJobResult;
try {
jobResult = await runVideoJob(requestId);
} catch (err: any) {
throw new Error(
`Video job ${requestId} failed: ${err?.message ?? err}. The result may still be uploading; retry with /gori-fetch ${requestId}`,
);
}
const { status, buf } = jobResult;
const name = params.filename ?? `${timestamp()}-${slug(params.prompt ?? "video")}`;
const filePath = path.join(outputDir(cwd), `${name}.mp4`);
fs.writeFileSync(filePath, buf);
const cost = formatCost(status?.usage?.cost_in_usd_ticks);
const duration = status?.video?.duration ?? body.duration;
const mode =
params.first_frame && params.last_frame ? "first+last frame interpolation"
: params.first_frame ? "image-to-video (first frame)"
: params.last_frame ? "last-frame pinned"
: "text-to-video";
return {
content: [
{
type: "text",
text: [
`Video saved to: ${filePath}`,
`Model: ${VIDEO_MODEL} | Mode: ${mode} | Duration: ${duration}s | Cost: ${cost}`,
params.prompt ? `Prompt: ${params.prompt}` : undefined,
]
.filter(Boolean)
.join("\n"),
},
],
details: {
path: filePath,
requestId,
model: VIDEO_MODEL,
mode,
duration,
cost,
prompt: params.prompt,
firstFrame: params.first_frame,
lastFrame: params.last_frame,
},
};
},
renderCall(args, theme) {
let text = theme.fg("toolTitle", theme.bold("generate_video "));
const frames = [args.first_frame && "first", args.last_frame && "last"].filter(Boolean).join("+");
if (frames) text += theme.fg("accent", `[${frames} frame] `);
text += theme.fg(
"accent",
args.prompt ? (args.prompt.length > 50 ? `${args.prompt.slice(0, 47)}...` : args.prompt) : "(no prompt)",
);
if (args.duration) text += theme.fg("dim", ` ${args.duration}s`);
return new Text(text, 0, 0);
},
renderResult(result, { isPartial }, theme) {
if (isPartial) {
const content = result.content[0];
const msg = content?.type === "text" ? content.text : "Generating video...";
return new Text(theme.fg("warning", msg), 0, 0);
}
const details = result.details as { path?: string; cost?: string; duration?: number } | undefined;
if (details?.path) {
return new Text(
`${theme.fg("success", "✓ video")} ${theme.fg("accent", details.path)}` +
theme.fg("dim", ` (${details.duration ?? "?"}s, ${details.cost ?? "?"})`),
0,
0,
);
}
const content = result.content[0];
return new Text(content?.type === "text" ? content.text.slice(0, 200) : "done", 0, 0);
},
});
// -----------------------------------------------------------------------
// /gori-fetch <request_id>: re-download a completed video job
// -----------------------------------------------------------------------
pi.registerCommand("gori-fetch", {
description: "Re-download a goriteches video by request_id (usage: /gori-fetch <request_id>)",
handler: async (args, ctx) => {
const requestId = args.trim();
if (!requestId) {
ctx.ui.notify("Usage: /gori-fetch <request_id>", "error");
return;
}
try {
const { status, buf } = await runVideoJob(requestId);
const filePath = path.join(outputDir(ctx.cwd ?? process.cwd()), `${timestamp()}-${requestId.slice(0, 8)}.mp4`);
fs.writeFileSync(filePath, buf);
ctx.ui.notify(`Saved ${filePath} (${formatCost(status?.usage?.cost_in_usd_ticks)})`, "info");
} catch (err: any) {
ctx.ui.notify(`/gori-fetch failed: ${err?.message ?? err}`, "error");
}
},
});
// -----------------------------------------------------------------------
// /gori-output [dir]: set or show output directory for this session
// -----------------------------------------------------------------------
pi.registerCommand("gori-output", {
description: "Set or show output directory (usage: /gori-output [dir], empty to reset, no args to show)",
handler: async (args, ctx) => {
const dir = args.trim();
if (!dir) {
const current = sessionOutputDir ?? process.env.GORITECHES_OUTPUT_DIR ?? path.join(ctx.cwd ?? process.cwd(), "goritech-media");
ctx.ui.notify(`Output dir: ${current}${sessionOutputDir ? " (session override)" : ""}\nUsage: /gori-output <dir> to set, /gori-output reset to clear`, "info");
return;
}
if (dir === "reset") {
sessionOutputDir = undefined;
ctx.ui.notify("Output dir reset to default (<cwd>/goritech-media or GORITECHES_OUTPUT_DIR env)", "info");
return;
}
const abs = path.resolve(ctx.cwd ?? process.cwd(), dir);
try {
fs.mkdirSync(abs, { recursive: true });
sessionOutputDir = abs;
ctx.ui.notify(`Output dir set to: ${abs} (this session only)`, "info");
} catch (err: any) {
ctx.ui.notify(`Failed to set output dir: ${err?.message ?? err}`, "error");
}
},
});
// -----------------------------------------------------------------------
// /gori-media command: quick smoke test + usage
// -----------------------------------------------------------------------
pi.registerCommand("gori-media", {
description: "Show goritech-media extension usage info",
handler: async (_args, ctx) => {
let keySource = "none";
if (process.env.GORITECHES_API_KEY) keySource = "GORITECHES_API_KEY env";
else {
try {
resolveApiKey();
keySource = "~/.pi/agent/models.json (goriteches provider)";
} catch {
keySource = "NOT FOUND";
}
}
ctx.ui.notify(
[
`goritech-media extension`,
`Base URL: ${BASE_URL}`,
`API key: ${keySource}`,
`Image model: ${IMAGE_MODEL} (gen) / ${EDIT_IMAGE_MODEL} (edit)`,
`Video model: ${VIDEO_MODEL}`,
`Output dir: ${sessionOutputDir ?? process.env.GORITECHES_OUTPUT_DIR ?? "<cwd>/goritech-media"}${sessionOutputDir ? " (session)" : ""}`,
``,
`Tools: generate_image, edit_image, generate_video (model-callable)`,
`Commands: /gori-output [dir], /gori-fetch <id>, /gori-media`,
].join("\n"),
"info",
);
},
});
}