@shiwano/ggen 0.1.0 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,30 @@
1
+ # @shiwano/ggen
2
+
3
+ Image, video, and audio generation for TypeScript. `GGen.open()` downloads the [ggen](https://github.com/shiwano/ggen) binary for your platform on first use and runs it on the local GPU, and a generation downloads the weights it needs.
4
+
5
+ ```sh
6
+ npm install @shiwano/ggen
7
+ ```
8
+
9
+ ```ts
10
+ import { GGen } from "@shiwano/ggen";
11
+
12
+ await using ggen = await GGen.open();
13
+
14
+ const { image } = await ggen.generate("krea2/image.generate", {
15
+ inputs: {
16
+ prompt: "A white ceramic teapot on a blue linen cloth in afternoon light.",
17
+ width: 1280,
18
+ height: 720,
19
+ },
20
+ });
21
+ await image.save("teapot.png");
22
+ ```
23
+
24
+ It runs on Linux x86_64 (CUDA, ROCm, Vulkan, CPU), Windows x64 (CUDA, ROCm, Vulkan, CPU), and macOS arm64 (Metal).
25
+
26
+ The operations, progress and cancellation, where the files go, and how to ship ggen with an app are in the [ggen README](https://github.com/shiwano/ggen#readme).
27
+
28
+ ## License
29
+
30
+ [MIT](https://github.com/shiwano/ggen/blob/main/LICENSE)
package/dist/binary.d.ts CHANGED
@@ -19,7 +19,8 @@ export interface BinaryOptions {
19
19
  onDownload?: ((progress: GGenDownloadProgress) => void) | undefined;
20
20
  manifest?: Manifest | undefined;
21
21
  }
22
- export declare function manifest(): Manifest;
22
+ /** The server version this package runs. */
23
+ export declare function serverVersion(): string;
23
24
  export declare function platform(): string;
24
25
  export declare function defaultBinaryDir(version: string): string;
25
26
  /** Returns the `ggen` executable and its backend, downloading it unless `download` is false. */
package/dist/binary.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { createHash } from "node:crypto";
2
+ import { createHash, randomUUID } from "node:crypto";
3
3
  import { readFileSync } from "node:fs";
4
4
  import { access, chmod, mkdir, mkdtemp, open, readFile, readdir, rename, rm, writeFile, } from "node:fs/promises";
5
5
  import { homedir } from "node:os";
@@ -7,12 +7,106 @@ import { join } from "node:path";
7
7
  import { Readable } from "node:stream";
8
8
  import { GGenError } from "./errors.js";
9
9
  import { extractZip } from "./zip.js";
10
- const AUTO_ORDER = ["cuda", "vulkan", "cpu"];
10
+ const AUTO_ORDER = ["cuda", "rocm", "vulkan", "cpu"];
11
11
  const BACKENDS = ["cpu", "cuda", "rocm", "vulkan", "metal"];
12
- let embedded;
13
- export function manifest() {
14
- embedded ??= JSON.parse(readFileSync(new URL("../manifest.json", import.meta.url), "utf8"));
15
- return embedded;
12
+ let server;
13
+ /** The server version this package runs. */
14
+ export function serverVersion() {
15
+ server ??= JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).ggen.server;
16
+ return server;
17
+ }
18
+ const RELEASES = "https://github.com/shiwano/ggen/releases/download";
19
+ const MANIFEST = "manifest.json";
20
+ const fetching = new Map();
21
+ function parseManifest(text, origin) {
22
+ const manifest = JSON.parse(text);
23
+ if (typeof manifest?.version !== "string" || !isObject(manifest.archives)) {
24
+ throw new Error(`${origin}: not a manifest`);
25
+ }
26
+ for (const [key, entry] of Object.entries(manifest.archives)) {
27
+ if (!isObject(entry) ||
28
+ typeof entry.sha256 !== "string" ||
29
+ typeof entry.url !== "string" ||
30
+ !/^[0-9a-f]{64}$/i.test(entry.sha256) ||
31
+ !(entry.size > 0) ||
32
+ !/^https?:\/\//.test(entry.url)) {
33
+ throw new Error(`${origin}: invalid entry ${key}`);
34
+ }
35
+ }
36
+ return manifest;
37
+ }
38
+ function isObject(value) {
39
+ return typeof value === "object" && value !== null && !Array.isArray(value);
40
+ }
41
+ /** `<binaryDir>/manifest.json`, unless it is absent or unreadable; one of another version is refused. */
42
+ async function savedManifest(binaryDir, version) {
43
+ const path = join(binaryDir, MANIFEST);
44
+ const text = await readFile(path, "utf8").catch(() => undefined);
45
+ if (text === undefined)
46
+ return undefined;
47
+ let manifest;
48
+ try {
49
+ manifest = parseManifest(text, path);
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ if (manifest.version !== version) {
55
+ throw new GGenError("BINARY_UNAVAILABLE", `${binaryDir} holds the binaries of ggen ${manifest.version}, not ${version}; use another binaryDir`);
56
+ }
57
+ return manifest;
58
+ }
59
+ /** The manifest of the release of `version`, saved as `<binaryDir>/manifest.json` when none is there. */
60
+ function releaseManifest(binaryDir, version) {
61
+ const key = `${binaryDir}\0${version}`;
62
+ let pending = fetching.get(key);
63
+ if (!pending) {
64
+ pending = (async () => {
65
+ const url = `${RELEASES}/v${version}/${MANIFEST}`;
66
+ let text;
67
+ let manifest;
68
+ try {
69
+ const response = await fetch(url);
70
+ if (!response.ok)
71
+ throw new Error(`HTTP ${response.status}`);
72
+ text = await response.text();
73
+ manifest = parseManifest(text, url);
74
+ if (manifest.version !== version) {
75
+ throw new Error(`version ${manifest.version}, expected ${version}`);
76
+ }
77
+ }
78
+ catch (cause) {
79
+ throw new GGenError("BINARY_UNAVAILABLE", `${url}: ${String(cause)}`, { cause });
80
+ }
81
+ await save(binaryDir, text);
82
+ await savedManifest(binaryDir, version);
83
+ return manifest;
84
+ })();
85
+ fetching.set(key, pending);
86
+ const settled = () => fetching.delete(key);
87
+ pending.then(settled, settled);
88
+ }
89
+ return pending;
90
+ }
91
+ /** Writes `text` as `<binaryDir>/manifest.json` unless a readable one is there. */
92
+ async function save(binaryDir, text) {
93
+ const path = join(binaryDir, MANIFEST);
94
+ const current = await readFile(path, "utf8").catch(() => undefined);
95
+ if (current !== undefined && readable(current))
96
+ return;
97
+ await mkdir(binaryDir, { recursive: true });
98
+ const temp = join(binaryDir, `.${MANIFEST}.${randomUUID()}`);
99
+ await writeFile(temp, text);
100
+ await rename(temp, path);
101
+ }
102
+ function readable(text) {
103
+ try {
104
+ parseManifest(text, MANIFEST);
105
+ return true;
106
+ }
107
+ catch {
108
+ return false;
109
+ }
16
110
  }
17
111
  export function platform() {
18
112
  const os = { linux: "linux", darwin: "darwin", win32: "windows" }[process.platform];
@@ -43,47 +137,102 @@ export async function resolveBinary(options = {}) {
43
137
  * Under `auto` a backend whose binary cannot be had or started falls through to the next.
44
138
  */
45
139
  export async function withBinary(options, start) {
46
- const source = options.manifest ?? manifest();
47
- const binaryDir = options.binaryDir ?? defaultBinaryDir(source.version);
140
+ const version = options.manifest?.version ?? serverVersion();
141
+ const binaryDir = options.binaryDir ?? defaultBinaryDir(version);
48
142
  const download = options.download ?? true;
143
+ const given = options.manifest;
144
+ const known = async () => given ?? (await savedManifest(binaryDir, version));
145
+ let pending;
146
+ const merged = () => {
147
+ if (given)
148
+ return Promise.resolve(given);
149
+ pending ??= (async () => {
150
+ const release = await releaseManifest(binaryDir, version);
151
+ const saved = await savedManifest(binaryDir, version);
152
+ return { version, archives: { ...release.archives, ...saved?.archives } };
153
+ })();
154
+ pending.catch(() => (pending = undefined));
155
+ return pending;
156
+ };
49
157
  const ensure = async (backend) => {
50
158
  const path = executable(binaryDir, backend);
51
159
  if (await exists(path)) {
52
160
  const key = `${platform()}-${backend}`;
53
- const expected = source.archives[key]?.sha256;
161
+ const expected = (await known())?.archives[key]?.sha256;
54
162
  const recorded = await readFile(join(binaryDir, key, ARCHIVE_DIGEST), "utf8").catch(() => undefined);
55
- if (expected && recorded && recorded.trim().toLowerCase() !== expected.toLowerCase()) {
56
- throw new GGenError("BINARY_UNAVAILABLE", `${join(binaryDir, key)} holds another archive than the manifest of ${source.version}; remove it`);
163
+ if (!expected || !recorded) {
164
+ await checkVersion(path, version);
165
+ }
166
+ else if (recorded.trim().toLowerCase() !== expected.toLowerCase()) {
167
+ throw new GGenError("BINARY_UNAVAILABLE", `${join(binaryDir, key)} holds another archive than the manifest of ${version}; remove it`);
57
168
  }
58
169
  return path;
59
170
  }
60
171
  if (!download) {
61
172
  throw new GGenError("BINARY_UNAVAILABLE", `${path} not found and download is false`);
62
173
  }
174
+ const local = await known();
175
+ const key = `${platform()}-${backend}`;
176
+ const source = local && key in local.archives ? local : await merged();
63
177
  await install(source, binaryDir, backend, options.onDownload);
64
178
  return path;
65
179
  };
66
- const order = options.backend === undefined || options.backend === "auto"
67
- ? await detect(source, binaryDir, download, ensure)
68
- : [options.backend];
180
+ const tried = [];
69
181
  const errors = [];
70
- for (const backend of order) {
71
- try {
72
- return await start({ path: await ensure(backend), backend });
182
+ const attempt = async (order) => {
183
+ for (const backend of order) {
184
+ if (tried.includes(backend))
185
+ continue;
186
+ tried.push(backend);
187
+ try {
188
+ return { value: await start({ path: await ensure(backend), backend }) };
189
+ }
190
+ catch (error) {
191
+ errors.push(error);
192
+ }
73
193
  }
74
- catch (error) {
75
- errors.push(error);
194
+ return undefined;
195
+ };
196
+ if (options.backend !== undefined && options.backend !== "auto") {
197
+ const done = await attempt([options.backend]);
198
+ if (done)
199
+ return done.value;
200
+ }
201
+ else {
202
+ const plan = (remote) => detect(known, merged, given !== undefined, version, binaryDir, download, ensure, remote);
203
+ let failure;
204
+ const first = await plan(false).catch((error) => {
205
+ failure = error;
206
+ return undefined;
207
+ });
208
+ let second;
209
+ if (first?.missing) {
210
+ second = await plan(true).catch(() => undefined);
211
+ const done = second && (await attempt(second.order));
212
+ if (done)
213
+ return done.value;
76
214
  }
215
+ const done = first && (await attempt(first.order));
216
+ if (done)
217
+ return done.value;
218
+ if (download && !first?.consulted && !second) {
219
+ second = await plan(true).catch(() => undefined);
220
+ const more = second && (await attempt(second.order));
221
+ if (more)
222
+ return more.value;
223
+ }
224
+ if (tried.length === 0)
225
+ throw failure;
77
226
  }
78
227
  if (errors.length === 1)
79
228
  throw errors[0];
80
229
  const last = errors.at(-1);
81
- throw new GGenError(last instanceof GGenError ? last.code : "BINARY_UNAVAILABLE", order.map((backend, i) => `${backend}: ${errors[i].message}`).join("; "), { cause: last });
230
+ throw new GGenError(last instanceof GGenError ? last.code : "BINARY_UNAVAILABLE", tried.map((backend, i) => `${backend}: ${errors[i].message}`).join("; "), { cause: last });
82
231
  }
83
- async function detect(source, binaryDir, download, ensure) {
232
+ async function detect(known, merged, given, version, binaryDir, download, ensure, remote) {
84
233
  const key = platform();
85
234
  if (key === "darwin-arm64")
86
- return ["metal"];
235
+ return { order: ["metal"], consulted: true };
87
236
  const present = (await readdir(binaryDir).catch(() => []))
88
237
  .filter((name) => name.startsWith(`${key}-`))
89
238
  .map((name) => name.slice(key.length + 1))
@@ -92,14 +241,32 @@ async function detect(source, binaryDir, download, ensure) {
92
241
  for (const b of present)
93
242
  if (await exists(executable(binaryDir, b)))
94
243
  installed.push(b);
95
- const candidates = AUTO_ORDER.filter((b) => installed.includes(b) || (download && `${key}-${b}` in source.archives));
244
+ let archives = {};
245
+ let unreachable = "";
246
+ let consulted = given;
247
+ if (download) {
248
+ const local = await known();
249
+ if (given || (!remote && local)) {
250
+ archives = local.archives;
251
+ }
252
+ else if (remote || !AUTO_ORDER.some((b) => installed.includes(b))) {
253
+ consulted = true;
254
+ try {
255
+ archives = (await merged()).archives;
256
+ }
257
+ catch (error) {
258
+ unreachable = ` (${error.message})`;
259
+ }
260
+ }
261
+ }
262
+ const candidates = AUTO_ORDER.filter((b) => installed.includes(b) || `${key}-${b}` in archives);
96
263
  if (candidates.length === 0) {
97
- const where = download ? `${binaryDir} or the manifest of ${source.version}` : binaryDir;
98
- const rocm = installed.includes("rocm") ? '; pass backend: "rocm" to use rocm' : "";
99
- throw new GGenError("BINARY_UNAVAILABLE", `no ggen binary for ${key} in ${where}${rocm}`);
264
+ const where = download ? `${binaryDir} or the manifest of ${version}` : binaryDir;
265
+ throw new GGenError("BINARY_UNAVAILABLE", `no ggen binary for ${key} in ${where}${unreachable}`);
266
+ }
267
+ if ((consulted || !download) && candidates.length === 1 && candidates[0] === "cpu") {
268
+ return { order: ["cpu"], consulted };
100
269
  }
101
- if (candidates.length === 1 && candidates[0] === "cpu")
102
- return ["cpu"];
103
270
  const probes = [
104
271
  ...candidates.filter((b) => b === "cpu"),
105
272
  ...candidates.filter((b) => b !== "cpu" && installed.includes(b)),
@@ -116,17 +283,28 @@ async function detect(source, binaryDir, download, ensure) {
116
283
  continue;
117
284
  }
118
285
  const usable = candidates.filter((b) => available.has(b));
286
+ const better = AUTO_ORDER.slice(0, AUTO_ORDER.indexOf(usable[0]));
287
+ const missing = download &&
288
+ !consulted &&
289
+ better.some((b) => available.has(b) && !installed.includes(b) && !(`${key}-${b}` in archives));
119
290
  if (usable.length > 0)
120
- return usable;
291
+ return { order: usable, consulted, missing };
121
292
  failures.push(`${probe}: none of ${candidates.join(", ")} has a device`);
122
293
  break;
123
294
  }
124
295
  if (candidates.includes("cpu"))
125
- return ["cpu"];
296
+ return { order: ["cpu"], consulted };
126
297
  throw new GGenError("BINARY_UNAVAILABLE", `no ggen backend for ${key} runs here (${failures.join("; ")})`);
127
298
  }
128
- async function devices(binary) {
129
- const child = spawn(binary, ["devices"], {
299
+ async function checkVersion(binary, version) {
300
+ const output = await run(binary, ["--version"]);
301
+ const actual = output.trim().split(/\s+/).at(-1);
302
+ if (actual !== version) {
303
+ throw new GGenError("BINARY_UNAVAILABLE", `${binary} is ggen ${actual}, not ${version}; use another binaryDir`);
304
+ }
305
+ }
306
+ async function run(binary, args) {
307
+ const child = spawn(binary, args, {
130
308
  stdio: ["ignore", "pipe", "pipe"],
131
309
  windowsHide: true,
132
310
  });
@@ -134,18 +312,22 @@ async function devices(binary) {
134
312
  let stderr = "";
135
313
  child.stdout.setEncoding("utf8").on("data", (chunk) => (stdout += chunk));
136
314
  child.stderr.setEncoding("utf8").on("data", (chunk) => (stderr += chunk));
315
+ const command = `${binary} ${args.join(" ")}`;
137
316
  const code = await new Promise((resolve, reject) => {
138
317
  child.once("error", reject);
139
318
  child.once("close", resolve);
140
319
  }).catch((cause) => {
141
- throw new GGenError("PROCESS_EXITED", `${binary} devices: ${String(cause)}`, { cause });
320
+ throw new GGenError("PROCESS_EXITED", `${command}: ${String(cause)}`, { cause });
142
321
  });
143
322
  if (code !== 0) {
144
- throw new GGenError("PROCESS_EXITED", `${binary} devices exited with ${code}`, {
323
+ throw new GGenError("PROCESS_EXITED", `${command} exited with ${code}`, {
145
324
  stderr: stderr.slice(-8192),
146
325
  });
147
326
  }
148
- const { devices } = JSON.parse(stdout);
327
+ return stdout;
328
+ }
329
+ async function devices(binary) {
330
+ const { devices } = JSON.parse(await run(binary, ["devices"]));
149
331
  return new Set(devices.map((device) => device.backend));
150
332
  }
151
333
  async function install(source, binaryDir, backend, onDownload) {
package/dist/client.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { components } from "./openapi.ts";
2
2
  type S = components["schemas"];
3
3
  export type Health = S["Health"];
4
4
  export type Job = S["Job"];
5
+ export type JobLog = S["JobLog"];
5
6
  export type JobRequest = S["JobRequest"];
6
7
  export type JobStatus = S["JobStatus"];
7
8
  export type JobSummary = S["JobSummary"];
@@ -44,10 +45,7 @@ export declare class GGenClient {
44
45
  deleteJob(jobId: string, options?: RequestOptions): Promise<void>;
45
46
  getJobLog(jobId: string, options?: RequestOptions & {
46
47
  offset?: number;
47
- }): Promise<{
48
- data: Uint8Array;
49
- nextOffset: number;
50
- }>;
48
+ }): Promise<JobLog>;
51
49
  /** The output `name`, or item `index` of an `images` output. */
52
50
  getJobOutput(jobId: string, name: string, index?: number, options?: RequestOptions): Promise<ReadableStream<Uint8Array>>;
53
51
  listUploads(options?: RequestOptions): Promise<Upload[]>;
package/dist/client.js CHANGED
@@ -73,15 +73,11 @@ export class GGenClient {
73
73
  async deleteJob(jobId, options) {
74
74
  await this.#request("DELETE", jobPath(jobId), options);
75
75
  }
76
- async getJobLog(jobId, options = {}) {
76
+ getJobLog(jobId, options = {}) {
77
77
  const query = new URLSearchParams();
78
78
  if (options.offset !== undefined)
79
79
  query.set("offset", String(options.offset));
80
- const response = await this.#request("GET", withQuery(`${jobPath(jobId)}/log`, query), options);
81
- return {
82
- data: new Uint8Array(await response.arrayBuffer()),
83
- nextOffset: Number(response.headers.get("X-Next-Offset")),
84
- };
80
+ return this.#json("GET", withQuery(`${jobPath(jobId)}/log`, query), options);
85
81
  }
86
82
  /** The output `name`, or item `index` of an `images` output. */
87
83
  async getJobOutput(jobId, name, index, options) {
package/dist/errors.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import type { components } from "./openapi.ts";
2
2
  export type GGenErrorCode = components["schemas"]["ErrorCode"] | "BINARY_UNAVAILABLE" | "PROCESS_EXITED" | "CANCELLED";
3
+ export type GGenLogRecord = components["schemas"]["LogRecord"];
3
4
  export interface GGenErrorDetails {
4
5
  field?: string | undefined;
5
- log?: string | undefined;
6
+ log?: GGenLogRecord[] | undefined;
6
7
  stderr?: string | undefined;
7
8
  status?: number | undefined;
8
9
  cause?: unknown;
@@ -12,7 +13,7 @@ export declare class GGenError extends Error {
12
13
  /** The input the error is about. */
13
14
  readonly field: string | undefined;
14
15
  /** The job log of a failed job. */
15
- readonly log: string | undefined;
16
+ readonly log: GGenLogRecord[] | undefined;
16
17
  /** The end of the process's stderr when it exited. */
17
18
  readonly stderr: string | undefined;
18
19
  /** The HTTP status, from `GGenClient`. */
package/dist/ggen.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type GGenBackend, type GGenDownloadProgress } from "./binary.ts";
2
+ import type { GGenLogRecord } from "./errors.ts";
2
3
  import { type GGenKinds } from "./kinds.ts";
3
4
  import type { components } from "./openapi.ts";
4
5
  type S = components["schemas"];
@@ -34,6 +35,8 @@ export interface GGenProgress {
34
35
  }
35
36
  export interface GGenJobOptions {
36
37
  onProgress?: ((progress: GGenProgress) => void) | undefined;
38
+ /** Each line added to the job log. */
39
+ onLog?: ((record: GGenLogRecord) => void) | undefined;
37
40
  signal?: AbortSignal | undefined;
38
41
  /** Job ID. Defaults to a random UUID. */
39
42
  id?: string | undefined;
package/dist/ggen.js CHANGED
@@ -81,7 +81,7 @@ export class GGen {
81
81
  return this.close();
82
82
  }
83
83
  async #run(request, options) {
84
- const { signal, onProgress } = options;
84
+ const { signal, onProgress, onLog } = options;
85
85
  signal?.throwIfAborted();
86
86
  const id = options.id ?? randomUUID();
87
87
  const progress = {
@@ -106,6 +106,7 @@ export class GGen {
106
106
  Object.assign(progress, message.progress);
107
107
  return onProgress?.({ ...progress });
108
108
  },
109
+ onLog: (message) => onLog?.(message.record),
109
110
  });
110
111
  if (!signal)
111
112
  return job.done;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { GGen, type GGenFamily, type GGenFetchOptions, type GGenFormats, type GGenGenerateOptions, type GGenInputs, type GGenJobOptions, type GGenKind, type GGenOptions, type GGenProgress, type GGenRequest, type GGenResult, } from "./ggen.ts";
2
2
  export type { GGenKinds } from "./kinds.ts";
3
- export { GGenError, type GGenErrorCode, type GGenErrorDetails } from "./errors.ts";
3
+ export { GGenError, type GGenErrorCode, type GGenErrorDetails, type GGenLogRecord, } from "./errors.ts";
4
4
  export { GGenAudio, GGenFile, GGenImage, GGenImages, type GGenOutput, GGenVideo, } from "./outputs.ts";
5
5
  export type { GGenBackend, GGenDownloadProgress } from "./binary.ts";
6
- export { type BinaryInput, GGenClient, type GGenClientOptions, type GetJobOptions, type Health, isTerminal, type Job, type JobRequest, type JobStatus, type JobSummary, type MediaType, type OperationDefinition, type RequestOptions, type Upload, type UploadId, uploadId, } from "./client.ts";
6
+ export { type BinaryInput, GGenClient, type GGenClientOptions, type GetJobOptions, type Health, isTerminal, type Job, type JobLog, type JobRequest, type JobStatus, type JobSummary, type MediaType, type OperationDefinition, type RequestOptions, type Upload, type UploadId, uploadId, } from "./client.ts";
7
7
  export type { components } from "./openapi.ts";
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  export { GGen, } from "./ggen.js";
2
- export { GGenError } from "./errors.js";
2
+ export { GGenError, } from "./errors.js";
3
3
  export { GGenAudio, GGenFile, GGenImage, GGenImages, GGenVideo, } from "./outputs.js";
4
4
  export { GGenClient, isTerminal, uploadId, } from "./client.js";
package/dist/openapi.d.ts CHANGED
@@ -879,6 +879,11 @@ export interface components {
879
879
  finishedAt: string | null;
880
880
  id: string;
881
881
  kind: string;
882
+ /**
883
+ * Format: int64
884
+ * @description Number of log records.
885
+ */
886
+ logCount: number;
882
887
  outputs: components["schemas"]["JobOutput"][];
883
888
  progress: null | components["schemas"]["Progress"];
884
889
  queuePosition: number | null;
@@ -897,6 +902,14 @@ export interface components {
897
902
  code: components["schemas"]["ErrorCode"];
898
903
  message: string;
899
904
  };
905
+ JobLog: {
906
+ /**
907
+ * Format: int64
908
+ * @description Offset for the next read.
909
+ */
910
+ nextOffset: number;
911
+ records: components["schemas"]["LogRecord"][];
912
+ };
900
913
  JobOutput: components["schemas"]["ImageOutput"] | components["schemas"]["AudioOutput"] | components["schemas"]["ImagesOutput"] | components["schemas"]["VideoOutput"];
901
914
  JobRequest: components["schemas"]["Krea2ImageGenerateRequest"] | components["schemas"]["MinimaxH3ImageGenerateRequest"] | components["schemas"]["MinimaxH3AudioGenerateRequest"] | components["schemas"]["MinimaxH3VideoGenerateRequest"] | components["schemas"]["MinimaxH3ImageImageEditRequest"] | components["schemas"]["QwenImageImageGenerateRequest"] | components["schemas"]["QwenImageImageEditRequest"] | components["schemas"]["MossImageImageGenerateRequest"] | components["schemas"]["Flux3ImageGenerateRequest"] | components["schemas"]["Flux3ImageEditRequest"] | components["schemas"]["ZImageImageGenerateRequest"] | components["schemas"]["Ideogram4ImageGenerateRequest"] | components["schemas"]["Fibo2ImageGenerateRequest"] | components["schemas"]["Fibo2ImageEditRequest"] | components["schemas"]["AnimaImageGenerateRequest"] | components["schemas"]["Ltx2VideoGenerateRequest"] | components["schemas"]["Seedvr2VideoUpscaleRequest"] | components["schemas"]["RelayVsrVideoUpscaleRequest"] | components["schemas"]["KandinskyImagesrImageUpscaleRequest"] | components["schemas"]["StableAudioAudioGenerateRequest"] | components["schemas"]["Zonos2AudioSpeechRequest"] | components["schemas"]["FishDrama3AudioSpeechRequest"] | components["schemas"]["Qwen3TtsAudioSpeechRequest"] | components["schemas"]["Qwen3TtsDesignAudioSpeechRequest"] | components["schemas"]["Zonos3AudioSpeechRequest"] | components["schemas"]["Voxcpm2AudioSpeechRequest"] | components["schemas"]["IrodoriTtsAudioSpeechRequest"] | components["schemas"]["AceStepAudioGenerateRequest"] | components["schemas"]["Yue2AudioGenerateRequest"] | components["schemas"]["MinimaxMusic3AudioGenerateRequest"] | components["schemas"]["MossSoundeffectAudioGenerateRequest"] | components["schemas"]["FetchRequest"];
902
915
  /** @enum {string} */
@@ -1002,6 +1015,12 @@ export interface components {
1002
1015
  configId: string;
1003
1016
  family: string;
1004
1017
  };
1018
+ /** @description One line of a job log. */
1019
+ LogRecord: {
1020
+ /** @enum {string} */
1021
+ level: "debug" | "info" | "warn" | "error";
1022
+ message: string;
1023
+ };
1005
1024
  Lora: {
1006
1025
  /** @description Path relative to a `--model-dir`. */
1007
1026
  file: string;
@@ -2086,14 +2105,14 @@ export interface components {
2086
2105
  */
2087
2106
  type: "error";
2088
2107
  };
2089
- SessionEvent: components["schemas"]["SessionReady"] | components["schemas"]["SessionStatus"] | components["schemas"]["SessionProgress"] | components["schemas"]["SessionSucceeded"] | components["schemas"]["SessionFailed"] | components["schemas"]["SessionCancelled"] | components["schemas"]["SessionError"];
2108
+ SessionEvent: components["schemas"]["SessionReady"] | components["schemas"]["SessionStatus"] | components["schemas"]["SessionProgress"] | components["schemas"]["SessionLog"] | components["schemas"]["SessionSucceeded"] | components["schemas"]["SessionFailed"] | components["schemas"]["SessionCancelled"] | components["schemas"]["SessionError"];
2090
2109
  /** @description The job failed. */
2091
2110
  SessionFailed: {
2092
2111
  error: components["schemas"]["JobError"];
2093
2112
  /** @description Job ID. */
2094
2113
  id: string;
2095
2114
  /** @description The whole job log. */
2096
- log: string;
2115
+ log: components["schemas"]["LogRecord"][];
2097
2116
  /**
2098
2117
  * @description discriminator enum property added by openapi-typescript
2099
2118
  * @enum {string}
@@ -2141,6 +2160,17 @@ export interface components {
2141
2160
  /** @description Shared by all items. */
2142
2161
  width: number;
2143
2162
  };
2163
+ /** @description A line was added to the job log. */
2164
+ SessionLog: {
2165
+ /** @description Job ID. */
2166
+ id: string;
2167
+ record: components["schemas"]["LogRecord"];
2168
+ /**
2169
+ * @description discriminator enum property added by openapi-typescript
2170
+ * @enum {string}
2171
+ */
2172
+ type: "log";
2173
+ };
2144
2174
  SessionOutput: components["schemas"]["SessionAudioOutput"] | components["schemas"]["SessionImageOutput"] | components["schemas"]["SessionImagesOutput"] | components["schemas"]["SessionVideoOutput"];
2145
2175
  /** @description Progress changed. */
2146
2176
  SessionProgress: {
@@ -2776,7 +2806,7 @@ export interface operations {
2776
2806
  getJobLog: {
2777
2807
  parameters: {
2778
2808
  query?: {
2779
- /** @description Byte offset to read from. */
2809
+ /** @description Record index to read from. */
2780
2810
  offset?: number;
2781
2811
  };
2782
2812
  header?: never;
@@ -2787,15 +2817,13 @@ export interface operations {
2787
2817
  };
2788
2818
  requestBody?: never;
2789
2819
  responses: {
2790
- /** @description Log bytes from `offset`. */
2820
+ /** @description Log records from `offset`. */
2791
2821
  200: {
2792
2822
  headers: {
2793
- /** @description Offset for the next read. */
2794
- "X-Next-Offset"?: number;
2795
2823
  [name: string]: unknown;
2796
2824
  };
2797
2825
  content: {
2798
- "application/octet-stream": string;
2826
+ "application/json": components["schemas"]["JobLog"];
2799
2827
  };
2800
2828
  };
2801
2829
  401: components["responses"]["Error"];
package/dist/session.d.ts CHANGED
@@ -5,6 +5,7 @@ export type SessionSucceeded = S["SessionSucceeded"];
5
5
  export interface JobHandlers {
6
6
  onStatus?: ((message: S["SessionStatus"]) => unknown) | undefined;
7
7
  onProgress?: ((message: S["SessionProgress"]) => unknown) | undefined;
8
+ onLog?: ((message: S["SessionLog"]) => unknown) | undefined;
8
9
  }
9
10
  export interface Submission {
10
11
  done: Promise<SessionSucceeded>;
package/dist/session.js CHANGED
@@ -121,8 +121,9 @@ export class Session {
121
121
  if (!job)
122
122
  return;
123
123
  if (job.failure) {
124
- if (message.type === "status" || message.type === "progress")
124
+ if (message.type === "status" || message.type === "progress" || message.type === "log") {
125
125
  return;
126
+ }
126
127
  this.#settle(message.id);
127
128
  return job.reject(job.failure.error);
128
129
  }
@@ -131,6 +132,8 @@ export class Session {
131
132
  return this.#notify(message.id, job, () => job.onStatus?.(message));
132
133
  case "progress":
133
134
  return this.#notify(message.id, job, () => job.onProgress?.(message));
135
+ case "log":
136
+ return this.#notify(message.id, job, () => job.onLog?.(message));
134
137
  case "succeeded": {
135
138
  this.#settle(message.id);
136
139
  if (job.running.length === 0)
package/package.json CHANGED
@@ -1,6 +1,9 @@
1
1
  {
2
2
  "name": "@shiwano/ggen",
3
- "version": "0.1.0",
3
+ "version": "0.1.3",
4
+ "ggen": {
5
+ "server": "0.1.3"
6
+ },
4
7
  "description": "Generate images, video and audio with ggen from TypeScript",
5
8
  "license": "MIT",
6
9
  "repository": {
@@ -16,22 +19,20 @@
16
19
  }
17
20
  },
18
21
  "files": [
19
- "dist",
20
- "manifest.json"
22
+ "dist"
21
23
  ],
22
24
  "engines": {
23
25
  "node": ">=20"
24
26
  },
25
27
  "scripts": {
26
28
  "generate": "openapi-typescript ../../openapi.json --default-non-nullable false --empty-objects-unknown -o src/openapi.ts && node scripts/generate.ts",
27
- "manifest": "node scripts/manifest.ts",
28
29
  "typecheck": "tsc --noEmit",
29
30
  "lint": "oxlint --deny-warnings .",
30
31
  "format": "oxfmt --write .",
31
32
  "format:check": "oxfmt --check .",
32
33
  "build": "tsc -p tsconfig.build.json",
33
34
  "test": "node --test test/*.test.ts",
34
- "prepack": "node scripts/manifest.ts && cp ../../LICENSE . && npm run build"
35
+ "prepack": "cp ../../LICENSE . && npm run build"
35
36
  },
36
37
  "devDependencies": {
37
38
  "@types/node": "24.19.2",
package/manifest.json DELETED
@@ -1,50 +0,0 @@
1
- {
2
- "version": "0.1.0",
3
- "archives": {
4
- "darwin-arm64-metal": {
5
- "url": "https://github.com/shiwano/ggen/releases/download/v0.1.0/ggen-darwin-arm64-metal.zip",
6
- "sha256": "c199378ddabbfc51d8d8115f664be68affc6e8264d252ce973f871bb41ebed78",
7
- "size": 37529244
8
- },
9
- "linux-x86_64-cpu": {
10
- "url": "https://github.com/shiwano/ggen/releases/download/v0.1.0/ggen-linux-x86_64-cpu.zip",
11
- "sha256": "58b01477665bd072fa40cdbe4b67ef86d7101549e36e1753b3c55f9f45726d08",
12
- "size": 36135163
13
- },
14
- "linux-x86_64-cuda": {
15
- "url": "https://github.com/shiwano/ggen/releases/download/v0.1.0/ggen-linux-x86_64-cuda.zip",
16
- "sha256": "a56b4573aeba40bc475151355675a6c9b62650880cca97d0beaad27f0eacfa0d",
17
- "size": 980800869
18
- },
19
- "linux-x86_64-rocm": {
20
- "url": "https://github.com/shiwano/ggen/releases/download/v0.1.0/ggen-linux-x86_64-rocm.zip",
21
- "sha256": "42402adb49f117e41ef58acc1a55261c590ba15ecdee7f5ca02a829ba6cd56a4",
22
- "size": 767894865
23
- },
24
- "linux-x86_64-vulkan": {
25
- "url": "https://github.com/shiwano/ggen/releases/download/v0.1.0/ggen-linux-x86_64-vulkan.zip",
26
- "sha256": "cdad013ba4b34d522dc57bfb6872be1c875959f025066bccbf0070adbe1fbbae",
27
- "size": 61418561
28
- },
29
- "windows-x86_64-cpu": {
30
- "url": "https://github.com/shiwano/ggen/releases/download/v0.1.0/ggen-windows-x86_64-cpu.zip",
31
- "sha256": "c642d80c241263bf1822da4c6693c39a27ed8d04d6eabbe04edb800303942d9e",
32
- "size": 28391821
33
- },
34
- "windows-x86_64-cuda": {
35
- "url": "https://github.com/shiwano/ggen/releases/download/v0.1.0/ggen-windows-x86_64-cuda.zip",
36
- "sha256": "23886213af29996e901ef841584415baf562ae38466a01abe5cb38fbebeac916",
37
- "size": 944137834
38
- },
39
- "windows-x86_64-rocm": {
40
- "url": "https://github.com/shiwano/ggen/releases/download/v0.1.0/ggen-windows-x86_64-rocm.zip",
41
- "sha256": "86fcfa9a994b6a62c6f4d4ef9574502e015b349131397ca6eb98cfa5f96b0e80",
42
- "size": 235544211
43
- },
44
- "windows-x86_64-vulkan": {
45
- "url": "https://github.com/shiwano/ggen/releases/download/v0.1.0/ggen-windows-x86_64-vulkan.zip",
46
- "sha256": "bb0e55f82dcbd9da0854d42f622715415a32d16e10cac777ce7c449cd91f1631",
47
- "size": 59564237
48
- }
49
- }
50
- }