@qvac/harness 1.0.0-rc.18 → 1.0.0-rc.19

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.
Files changed (53) hide show
  1. package/CHANGELOG.md +37 -6
  2. package/dist-lib/index.d.ts +3 -1
  3. package/dist-lib/index.js +30 -0
  4. package/dist-lib/lib/capabilities/completion-engine/loop.d.ts +3 -2
  5. package/dist-lib/lib/capabilities/completion-engine/loop.js +4 -1
  6. package/dist-lib/lib/connect.d.ts +2 -0
  7. package/dist-lib/lib/connect.js +57 -0
  8. package/dist-lib/lib/contract/completion.d.ts +2 -0
  9. package/dist-lib/lib/contract/index.d.ts +1 -0
  10. package/dist-lib/lib/contract/media.d.ts +51 -0
  11. package/dist-lib/lib/contract/media.js +1 -0
  12. package/dist-lib/lib/contract/models.d.ts +2 -0
  13. package/dist-lib/lib/contract-types.d.ts +3 -1
  14. package/dist-lib/lib/errors.d.ts +4 -0
  15. package/dist-lib/lib/errors.js +4 -0
  16. package/dist-lib/lib/machine/completion/actions/completion.d.ts +1 -1
  17. package/dist-lib/lib/machine/completion/actions/completion.js +3 -7
  18. package/dist-lib/lib/machine/completion/implementations.d.ts +3 -3
  19. package/dist-lib/lib/machine/completion/implementations.js +4 -4
  20. package/dist-lib/lib/machine/completion/machine.d.ts +3 -3
  21. package/dist-lib/lib/machine/completion/machine.js +3 -3
  22. package/dist-lib/lib/machine/index.d.ts +3 -3
  23. package/dist-lib/lib/media-host.d.ts +12 -0
  24. package/dist-lib/lib/media-host.js +52 -0
  25. package/dist-lib/lib/media-port.d.ts +20 -0
  26. package/dist-lib/lib/media-port.js +77 -0
  27. package/dist-lib/lib/media-wire.d.ts +8 -0
  28. package/dist-lib/lib/media-wire.js +96 -0
  29. package/dist-lib/lib/plugins/registry.d.ts +3 -0
  30. package/dist-lib/lib/serve.js +37 -1
  31. package/dist-lib/lib/tools/pdf/pages.js +6 -3
  32. package/dist-lib/lib/tools/pdf/recognize.js +2 -1
  33. package/dist-lib/plugins/image/edit-image.js +3 -9
  34. package/dist-lib/plugins/image/generate-image.d.ts +14 -2
  35. package/dist-lib/plugins/image/generate-image.js +94 -8
  36. package/dist-lib/plugins/image/index.d.ts +2 -1
  37. package/dist-lib/plugins/image/index.js +8 -3
  38. package/dist-lib/plugins/music/generate-music.d.ts +18 -2
  39. package/dist-lib/plugins/music/generate-music.js +98 -16
  40. package/dist-lib/plugins/music/index.d.ts +2 -1
  41. package/dist-lib/plugins/music/index.js +6 -2
  42. package/dist-lib/plugins/python/bare-floor.js +1 -1
  43. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  44. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  45. package/dist-lib/plugins/walkie-talkie/index.d.ts +2 -0
  46. package/dist-lib/plugins/walkie-talkie/index.js +6 -1
  47. package/dist-lib/schema/generate.js +8 -1
  48. package/dist-lib/schema/harness.js +9 -2
  49. package/dist-lib/spec/hrpc/messages.js +46 -4
  50. package/dist-lib/spec/hyperschema/index.js +46 -4
  51. package/dist-lib/spec/hyperschema/schema.json +28 -0
  52. package/dist-lib/spec/hyperschema/types.d.ts +2 -2
  53. package/package.json +7 -8
@@ -0,0 +1,52 @@
1
+ import { AbortController } from 'bare-abort-controller';
2
+ import fs from 'fs';
3
+ import { mediaRequestFrom, mediaResultWire } from './media-wire.js';
4
+ import { pushQueue } from './queue.js';
5
+ import { roundFailureWire } from './wire.js';
6
+ export class MediaHost {
7
+ _port;
8
+ _out = pushQueue();
9
+ _rounds = new Map();
10
+ constructor(port, send) {
11
+ this._port = port;
12
+ void this._drain(send);
13
+ }
14
+ ask(callId, payload) {
15
+ const controller = new AbortController();
16
+ this._rounds.set(callId, controller);
17
+ const tick = (payload) => {
18
+ if (this._rounds.has(callId)) {
19
+ void this._out.push({ type: 'media-round-tick', callId, payload });
20
+ }
21
+ };
22
+ void mediaRequestFrom(payload)
23
+ .then((request) => this._port(request, { signal: controller.signal, tick }))
24
+ .then(mediaResultWire)
25
+ .then((wire) => this._settle(callId, wire, wire.path), (err) => this._settle(callId, roundFailureWire(err)));
26
+ }
27
+ cancel(callId) {
28
+ this._rounds.get(callId)?.abort(undefined);
29
+ this._rounds.delete(callId);
30
+ }
31
+ close() {
32
+ for (const callId of [...this._rounds.keys()]) {
33
+ this.cancel(callId);
34
+ }
35
+ this._out.end();
36
+ }
37
+ _settle(callId, frame, staged) {
38
+ if (this._rounds.delete(callId)) {
39
+ void this._out.push({ type: 'media-round-result', callId, ...frame });
40
+ }
41
+ else if (staged) {
42
+ void fs.promises.unlink(staged).catch(noop);
43
+ }
44
+ }
45
+ async _drain(send) {
46
+ for await (const frame of this._out) {
47
+ send(frame);
48
+ await new Promise((resolve) => setTimeout(resolve, 0));
49
+ }
50
+ }
51
+ }
52
+ function noop() { }
@@ -0,0 +1,20 @@
1
+ import type { MediaRoundPort } from './contract/index.ts';
2
+ import type { RoundFrame } from './round-port.ts';
3
+ import type { WireEvent } from './wire.ts';
4
+ interface MediaFrame extends RoundFrame {
5
+ path?: string | null;
6
+ }
7
+ export declare class MediaPort {
8
+ private readonly _push;
9
+ private readonly _asked;
10
+ private _calls;
11
+ private _closed;
12
+ constructor(push: (event: WireEvent) => unknown);
13
+ port: MediaRoundPort;
14
+ frame(frame: MediaFrame): boolean;
15
+ close(): void;
16
+ private _settle;
17
+ private _assertLive;
18
+ private _take;
19
+ }
20
+ export {};
@@ -0,0 +1,77 @@
1
+ import { HarnessError } from './errors.js';
2
+ import { AbortedError } from './helpers/engine-error.js';
3
+ import { discardRequestWire, mediaRequestWire, mediaResultFrom, mediaTickFrom } from './media-wire.js';
4
+ export class MediaPort {
5
+ _push;
6
+ _asked = new Map();
7
+ _calls = 0;
8
+ _closed = false;
9
+ constructor(push) {
10
+ this._push = push;
11
+ }
12
+ port = async (request, io) => {
13
+ this._assertLive(io);
14
+ const payload = await mediaRequestWire(request);
15
+ try {
16
+ this._assertLive(io);
17
+ }
18
+ catch (err) {
19
+ await discardRequestWire(payload);
20
+ throw err;
21
+ }
22
+ const callId = String(this._calls++);
23
+ return new Promise((resolve, reject) => {
24
+ const cancel = () => {
25
+ if (!this._take(callId))
26
+ return;
27
+ this._push({ type: 'media-round-cancel', callId });
28
+ reject(new AbortedError());
29
+ };
30
+ this._asked.set(callId, { io, cancel, resolve, reject });
31
+ io.signal.addEventListener('abort', cancel, { once: true });
32
+ this._push({ type: 'media-round-ask', callId, payload });
33
+ });
34
+ };
35
+ frame(frame) {
36
+ switch (frame.type) {
37
+ case 'media-round-tick':
38
+ this._asked.get(frame.callId ?? '')?.io.tick(mediaTickFrom(frame.payload));
39
+ return true;
40
+ case 'media-round-result':
41
+ void this._settle(frame);
42
+ return true;
43
+ default:
44
+ return false;
45
+ }
46
+ }
47
+ close() {
48
+ this._closed = true;
49
+ for (const callId of [...this._asked.keys()]) {
50
+ this._take(callId)?.reject(new HarnessError('CLIENT_GONE'));
51
+ }
52
+ }
53
+ async _settle(frame) {
54
+ const asked = this._take(frame.callId ?? '');
55
+ try {
56
+ const result = await mediaResultFrom(frame);
57
+ asked?.resolve(result);
58
+ }
59
+ catch (err) {
60
+ asked?.reject(err);
61
+ }
62
+ }
63
+ _assertLive(io) {
64
+ if (this._closed) {
65
+ throw new HarnessError('CLIENT_GONE');
66
+ }
67
+ if (io.signal.aborted) {
68
+ throw new AbortedError();
69
+ }
70
+ }
71
+ _take(callId) {
72
+ const asked = this._asked.get(callId);
73
+ this._asked.delete(callId);
74
+ asked?.io.signal.removeEventListener('abort', asked.cancel);
75
+ return asked;
76
+ }
77
+ }
@@ -0,0 +1,8 @@
1
+ import type { MediaRoundRequest, MediaRoundResult, MediaTick } from './contract/index.ts';
2
+ import { type WireEvent } from './wire.ts';
3
+ export declare function mediaRequestWire(request: MediaRoundRequest): Promise<Record<string, unknown>>;
4
+ export declare function discardRequestWire(payload: Record<string, unknown>): Promise<void>;
5
+ export declare function mediaRequestFrom(payload: unknown): Promise<MediaRoundRequest>;
6
+ export declare function mediaResultWire(result: MediaRoundResult): Promise<Pick<WireEvent, 'path' | 'result'>>;
7
+ export declare function mediaResultFrom(wire: Pick<WireEvent, 'path' | 'result' | 'message' | 'payload'>): Promise<MediaRoundResult>;
8
+ export declare function mediaTickFrom(payload: unknown): MediaTick;
@@ -0,0 +1,96 @@
1
+ import fs from 'fs';
2
+ import { isRecord } from './guards.js';
3
+ import { stageFile } from './staging.js';
4
+ import { roundFailureFrom } from './wire.js';
5
+ const KINDS = ['image', 'music'];
6
+ export async function mediaRequestWire(request) {
7
+ const { images, ...json } = request;
8
+ const imagePaths = images
9
+ ? await Promise.all(images.map((bytes) => stageFile('media-source', bytes)))
10
+ : undefined;
11
+ return { ...json, imagePaths };
12
+ }
13
+ export async function discardRequestWire(payload) {
14
+ const paths = Array.isArray(payload.imagePaths) ? payload.imagePaths.map(String) : [];
15
+ await Promise.all(paths.map((file) => fs.promises.unlink(file).catch(noop)));
16
+ }
17
+ export async function mediaRequestFrom(payload) {
18
+ if (!isRecord(payload) || !KINDS.some((kind) => kind === payload.kind)) {
19
+ throw new TypeError('invalid media round request');
20
+ }
21
+ const paths = Array.isArray(payload.imagePaths) ? payload.imagePaths.map(String) : [];
22
+ const images = await Promise.all(paths.map(readStaged));
23
+ return {
24
+ kind: payload.kind === 'music' ? 'music' : 'image',
25
+ runId: String(payload.runId ?? ''),
26
+ modelChoice: typeof payload.modelChoice === 'string' ? payload.modelChoice : undefined,
27
+ params: isRecord(payload.params) ? payload.params : {},
28
+ images: paths.length ? images : undefined
29
+ };
30
+ }
31
+ export async function mediaResultWire(result) {
32
+ if ('error' in result) {
33
+ return { result: { error: result.error, code: result.code } };
34
+ }
35
+ const { bytes, ...json } = result;
36
+ return { path: await stageFile('media-output', bytes), result: json };
37
+ }
38
+ export async function mediaResultFrom(wire) {
39
+ const result = isRecord(wire.result) ? wire.result : {};
40
+ if (wire.path) {
41
+ return outputFrom(result, await readStaged(wire.path));
42
+ }
43
+ if (typeof result.error === 'string') {
44
+ return { error: result.error, code: typeof result.code === 'string' ? result.code : undefined };
45
+ }
46
+ throw roundFailureFrom(wire);
47
+ }
48
+ function outputFrom(result, bytes) {
49
+ if (result.kind === 'image') {
50
+ return { kind: 'image', bytes };
51
+ }
52
+ const format = isRecord(result.format) ? result.format : {};
53
+ const sampleRate = positive(format.sampleRate);
54
+ const channels = positive(format.channels);
55
+ const bitsPerSample = positive(format.bitsPerSample);
56
+ if (result.kind !== 'music' || !sampleRate || !channels || !bitsPerSample) {
57
+ throw new TypeError('invalid media round output');
58
+ }
59
+ return {
60
+ kind: 'music',
61
+ bytes,
62
+ format: { sampleRate, channels, bitsPerSample },
63
+ gpuRequested: result.gpuRequested === true,
64
+ stats: isRecord(result.stats) ? statsFrom(result.stats) : undefined
65
+ };
66
+ }
67
+ function statsFrom(stats) {
68
+ const number = (value) => (typeof value === 'number' ? value : undefined);
69
+ return {
70
+ audioDurationMs: number(stats.audioDurationMs),
71
+ totalTimeMs: number(stats.totalTimeMs),
72
+ realTimeFactor: number(stats.realTimeFactor),
73
+ backendDevice: number(stats.backendDevice),
74
+ backendId: number(stats.backendId)
75
+ };
76
+ }
77
+ function positive(value) {
78
+ return typeof value === 'number' && value > 0 ? value : undefined;
79
+ }
80
+ export function mediaTickFrom(payload) {
81
+ const tick = isRecord(payload) ? payload : {};
82
+ return {
83
+ step: Number(tick.step ?? 0),
84
+ total: Number(tick.total ?? 0),
85
+ stage: typeof tick.stage === 'string' ? tick.stage : undefined
86
+ };
87
+ }
88
+ async function readStaged(file) {
89
+ try {
90
+ return await fs.promises.readFile(file);
91
+ }
92
+ finally {
93
+ void fs.promises.unlink(file).catch(noop);
94
+ }
95
+ }
96
+ function noop() { }
@@ -4,6 +4,7 @@ import type { OcrService } from '../contract/ocr.ts';
4
4
  import type { SandboxService } from '../contract/sandbox.ts';
5
5
  import type { EgressProxyService } from '../contract/egress-proxy.ts';
6
6
  import type { EmbedHost, ModelHost } from '../contract/models.ts';
7
+ import type { MediaRoundServer } from '../contract/media.ts';
7
8
  import type { SpeechService } from '../contract/speech.ts';
8
9
  import type { HarnessHook, SkillReadiness } from '../contract/index.ts';
9
10
  import type { ExecLanguage, ExecRoute, ExecShell } from '../contract/exec.ts';
@@ -19,6 +20,8 @@ declare module './context.ts' {
19
20
  ocr: OcrService;
20
21
  sandbox: SandboxService;
21
22
  'egress-proxy': EgressProxyService;
23
+ 'image-rounds': MediaRoundServer;
24
+ 'music-rounds': MediaRoundServer;
22
25
  }
23
26
  }
24
27
  export interface PluginContext {
@@ -2,6 +2,7 @@ import b4a from 'b4a';
2
2
  import { AbortController } from 'bare-abort-controller';
3
3
  import fs from 'fs';
4
4
  import { HarnessError } from './errors.js';
5
+ import { AbortedError } from './helpers/engine-error.js';
5
6
  import { settleOnClose } from './rpc-session.js';
6
7
  import { pipeline, Readable } from 'streamx';
7
8
  import { bindApi } from '../spec/bind.js';
@@ -15,6 +16,8 @@ import { RunLog } from './run-log/index.js';
15
16
  import { errorMessage, isRecord } from './guards.js';
16
17
  import { HarnessLog } from './log.js';
17
18
  import { pushQueue } from './queue.js';
19
+ import { MediaPort } from './media-port.js';
20
+ import { mediaRequestFrom, mediaResultWire } from './media-wire.js';
18
21
  import { RoundPort } from './round-port.js';
19
22
  import { TextCoalescer } from './helpers/text-coalescer.js';
20
23
  import { prepareOpenclCache } from './models/opencl-cache.js';
@@ -185,6 +188,9 @@ function startPayloadFrom(value) {
185
188
  if (value.showImage === true) {
186
189
  payload.showImage = true;
187
190
  }
191
+ if (value.mediaRound === true) {
192
+ payload.mediaRound = true;
193
+ }
188
194
  if (value.runLog === null) {
189
195
  payload.runLog = null;
190
196
  }
@@ -663,6 +669,7 @@ function completion(harness) {
663
669
  const input = pushQueue();
664
670
  const controller = new AbortController();
665
671
  const rounds = new RoundPort((event) => events.push(event));
672
+ const media = new MediaPort((event) => events.push(event));
666
673
  let calls = 0;
667
674
  let started = false;
668
675
  let clientGone = false;
@@ -702,6 +709,7 @@ function completion(harness) {
702
709
  }
703
710
  pendingRunLog.clear();
704
711
  rounds.close();
712
+ media.close();
705
713
  input.end();
706
714
  events.end();
707
715
  };
@@ -709,7 +717,12 @@ function completion(harness) {
709
717
  duplex.on('end', gone);
710
718
  duplex.readStream?.on('close', gone);
711
719
  duplex.on('data', (frame) => {
712
- if (rounds.frame(frame)) {
720
+ if (rounds.frame(frame) || media.frame(frame)) {
721
+ return;
722
+ }
723
+ if (frame.type === 'media-round-ask' && !started) {
724
+ started = true;
725
+ void serveMedia(harness, frame.payload, { signal: controller.signal, events });
713
726
  return;
714
727
  }
715
728
  if (frame.type === 'model-round-ask' && !started) {
@@ -912,6 +925,7 @@ function completion(harness) {
912
925
  typedText: startPayload.typedText,
913
926
  replaysContext: startPayload.replaysContext,
914
927
  modelRound: startPayload.modelRound ? rounds.port : undefined,
928
+ mediaRound: startPayload.mediaRound ? media.port : undefined,
915
929
  roundCut: startPayload.roundCut ? rounds.roundCut : undefined,
916
930
  knowledge: startPayload.knowledge,
917
931
  planMode: startPayload.planMode,
@@ -1133,6 +1147,28 @@ function completion(harness) {
1133
1147
  HarnessLog.info('wire handed off');
1134
1148
  };
1135
1149
  }
1150
+ async function serveMedia(harness, payload, { signal, events }) {
1151
+ let settled;
1152
+ try {
1153
+ if (!harness.serveMediaRound) {
1154
+ throw new HarnessError('CAPABILITY_UNSUPPORTED', ['serveMediaRound']);
1155
+ }
1156
+ const result = await harness.serveMediaRound(await mediaRequestFrom(payload), {
1157
+ signal,
1158
+ tick: (tick) => void events.push({ type: 'media-round-tick', payload: tick })
1159
+ });
1160
+ if (signal.aborted) {
1161
+ throw new AbortedError();
1162
+ }
1163
+ settled = { type: 'media-round-result', ...(await mediaResultWire(result)) };
1164
+ }
1165
+ catch (err) {
1166
+ settled = { type: 'media-round-result', ...roundFailureWire(err) };
1167
+ }
1168
+ await events.push(settled);
1169
+ await events.push({ type: 'done' });
1170
+ events.end();
1171
+ }
1136
1172
  async function serveRound(harness, request, { signal, events }) {
1137
1173
  let sent = Promise.resolve();
1138
1174
  const queue = (step) => {
@@ -16,11 +16,14 @@ export async function pdfPages(bytes, { ocr, signal } = {}) {
16
16
  const recognized = ocr
17
17
  ? (await recognizePages({ doc, bytes }, { ocr, signal })).pages
18
18
  : undefined;
19
- return [...doc.textPages()].map(({ page, text }) => {
19
+ const pages = [];
20
+ for await (const { page, text } of doc.textPagesAsync()) {
21
+ signal?.throwIfAborted();
20
22
  const read = recognized?.get(page) ?? cleanText(text);
21
23
  const unread = !read && !recognized?.has(page) && doc.pageFlags(page).hasImage;
22
- return { page: page + 1, text: read, unread };
23
- });
24
+ pages.push({ page: page + 1, text: read, unread });
25
+ }
26
+ return pages;
24
27
  }
25
28
  finally {
26
29
  doc.close();
@@ -9,7 +9,8 @@ export async function recognizePages({ doc, bytes }, { ocr, signal, budget }) {
9
9
  const pages = new Map();
10
10
  let kept = null;
11
11
  let failed = false;
12
- for (const { page, text } of doc.textPages()) {
12
+ for await (const { page, text } of doc.textPagesAsync()) {
13
+ signal?.throwIfAborted();
13
14
  if (budget && budget.chars <= 0) {
14
15
  return { pages, unreadFrom: page };
15
16
  }
@@ -3,7 +3,7 @@ import fs from 'fs';
3
3
  import path from 'path';
4
4
  import { HarnessError } from '../../lib/errors.js';
5
5
  import { AbortedError } from '../../lib/helpers/race-abort.js';
6
- import { BUSY_ERROR, DIM_STEP, effectiveSteps, generationPercentTick, normalizeClamps, parseCommonArgs, runDiffusion } from './generate-image.js';
6
+ import { DIM_STEP, diffuse, effectiveSteps, generationPercentTick, normalizeClamps, parseCommonArgs } from './generate-image.js';
7
7
  const DEFAULT_STRENGTH = 0.7;
8
8
  const FLUX2_GUIDANCE = 3.5;
9
9
  const FLUX2_CFG_SCALE = 1;
@@ -192,9 +192,6 @@ export function createEditImageTool(runtime, { loadMedia = defaultLoadMedia, res
192
192
  if (sources.length > 1 && !inContext) {
193
193
  return { error: MULTI_SOURCE_UNSUPPORTED };
194
194
  }
195
- if (!runtime.acquire()) {
196
- return { error: BUSY_ERROR, code: 'busy' };
197
- }
198
195
  const report = ctx.progress;
199
196
  const onTick = report && generationPercentTick((percentage) => report({ percentage }), sources.length);
200
197
  try {
@@ -228,11 +225,9 @@ export function createEditImageTool(runtime, { loadMedia = defaultLoadMedia, res
228
225
  height = fitHeight;
229
226
  }
230
227
  }
231
- const sdk = await runtime.loadSdk();
232
- const { modelId } = await runtime.ensureLoaded(sdk, ctx.signal, ctx.image?.modelChoice);
233
228
  const fusion = inits.length > 1;
234
- const image = await runDiffusion(sdk, {
235
- modelId,
229
+ const image = await diffuse(runtime, ctx, {
230
+ modelChoice: ctx.image?.modelChoice,
236
231
  params: {
237
232
  prompt: common.prompt,
238
233
  width,
@@ -291,7 +286,6 @@ export function createEditImageTool(runtime, { loadMedia = defaultLoadMedia, res
291
286
  throw err;
292
287
  }
293
288
  finally {
294
- runtime.release();
295
289
  report?.(null);
296
290
  }
297
291
  }
@@ -1,5 +1,5 @@
1
- import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
- import type { ToolDefinition } from '../../lib/contract/index.ts';
1
+ import { type AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
+ import type { MediaRoundServer, ToolDefinition, ToolExecuteContext } from '../../lib/contract/index.ts';
3
3
  import type { ModelSrc } from '../../lib/models/context.ts';
4
4
  import { type ImageClamps, type ImageModelSet } from '../../lib/models/model-catalog.ts';
5
5
  import type { LoadRequests, ModelHost, TrackedLoad } from '../../lib/contract/models.ts';
@@ -77,6 +77,8 @@ export interface DiffusionRuntime {
77
77
  loadSdk: () => Promise<DiffusionSdk>;
78
78
  ensureLoaded: (sdk: DiffusionSdk, signal?: BareAbortSignal, modelChoice?: string) => Promise<LoadedDiffusionModel>;
79
79
  predictionFor(modelChoice?: string): 'flux2_flow' | undefined;
80
+ modelName(modelChoice?: string): string;
81
+ choiceFor(modelChoice?: string): string | undefined;
80
82
  unload(): Promise<void>;
81
83
  unloadIdle(): Promise<void>;
82
84
  acquire(): boolean;
@@ -87,6 +89,7 @@ export declare function createDiffusionRuntime({ loadSdk, onProgress, onLoaded,
87
89
  export declare const BUSY_ERROR = "an image generation is already running; try again when it finishes";
88
90
  export interface ImageToolError {
89
91
  error: string;
92
+ code?: string;
90
93
  }
91
94
  export interface RunDiffusionOptions {
92
95
  readonly modelId: string;
@@ -95,6 +98,15 @@ export interface RunDiffusionOptions {
95
98
  readonly onTick?: (tick: DiffusionTick) => void;
96
99
  }
97
100
  export declare function runDiffusion(sdk: DiffusionSdk, { modelId, params, signal, onTick }: RunDiffusionOptions): Promise<Uint8Array | ImageToolError>;
101
+ export interface DiffuseOptions {
102
+ readonly modelChoice?: string | undefined;
103
+ readonly params: DiffusionParams;
104
+ readonly signal?: BareAbortSignal | undefined;
105
+ readonly onTick?: ((tick: DiffusionTick) => void) | undefined;
106
+ }
107
+ export declare function diffuse(runtime: DiffusionRuntime, ctx: ToolExecuteContext, options: DiffuseOptions): Promise<Uint8Array | ImageToolError>;
108
+ export declare function diffuseHere(runtime: DiffusionRuntime, { modelChoice, params, signal, onTick }: DiffuseOptions): Promise<Uint8Array | ImageToolError>;
109
+ export declare function diffusionServer(runtime: DiffusionRuntime, isCached: ModelHost['isCached'], clamps?: ImageClamps): MediaRoundServer;
98
110
  export interface CommonImageArgs {
99
111
  prompt: string;
100
112
  steps?: number;
@@ -1,3 +1,4 @@
1
+ import { AbortController } from 'bare-abort-controller';
1
2
  import ScopeLock from 'scope-lock';
2
3
  import { HarnessError } from '../../lib/errors.js';
3
4
  import { AbortedError, raceAbort } from '../../lib/helpers/race-abort.js';
@@ -146,6 +147,11 @@ export function createDiffusionRuntime({ loadSdk, onProgress, onLoaded, onBefore
146
147
  return {
147
148
  loadSdk,
148
149
  predictionFor: (modelChoice) => ((modelChoice && imageModelFor(modelChoice)) || base).prediction,
150
+ modelName: (modelChoice) => diffusionProgressName((modelChoice && imageModelFor(modelChoice)) || base),
151
+ choiceFor: (modelChoice) => {
152
+ const set = (modelChoice && imageModelFor(modelChoice)) || base;
153
+ return DIFFUSION_CATALOG.find((entry) => entry.model.src === set.model)?.choice;
154
+ },
149
155
  ensureLoaded: async (sdk, signal, modelChoice) => {
150
156
  const set = (modelChoice && imageModelFor(modelChoice)) || base;
151
157
  const name = diffusionProgressName(set);
@@ -207,6 +213,92 @@ export async function runDiffusion(sdk, { modelId, params, signal, onTick }) {
207
213
  signal?.removeEventListener('abort', onAbort);
208
214
  }
209
215
  }
216
+ export function diffuse(runtime, ctx, options) {
217
+ if (!ctx.mediaRound) {
218
+ return diffuseHere(runtime, options);
219
+ }
220
+ return diffuseThere(ctx.mediaRound, ctx.runId ?? '', {
221
+ ...options,
222
+ modelChoice: runtime.choiceFor(options.modelChoice),
223
+ prediction: runtime.predictionFor(options.modelChoice)
224
+ });
225
+ }
226
+ export async function diffuseHere(runtime, { modelChoice, params, signal, onTick }) {
227
+ if (!runtime.acquire()) {
228
+ return { error: BUSY_ERROR, code: 'busy' };
229
+ }
230
+ try {
231
+ const sdk = await runtime.loadSdk();
232
+ const { modelId } = await runtime.ensureLoaded(sdk, signal, modelChoice);
233
+ return await runDiffusion(sdk, { modelId, params, signal, onTick });
234
+ }
235
+ finally {
236
+ runtime.release();
237
+ }
238
+ }
239
+ async function diffuseThere(port, runId, { modelChoice, prediction, params, signal, onTick }) {
240
+ const { init_image: image, init_images: images, ...json } = params;
241
+ const sources = images ?? (image ? [image] : undefined);
242
+ const asked = port({
243
+ kind: 'image',
244
+ runId,
245
+ modelChoice,
246
+ params: { ...json, prediction, init: images ? 'images' : sources && 'image' },
247
+ images: sources
248
+ }, {
249
+ signal: signal ?? new AbortController().signal,
250
+ tick: ({ step, total }) => onTick?.({ step, totalSteps: total, elapsedMs: 0 })
251
+ });
252
+ const result = await raceAbort(asked, signal);
253
+ if ('error' in result) {
254
+ return result;
255
+ }
256
+ return result.kind === 'image' ? result.bytes : { error: 'the serving device sent no image' };
257
+ }
258
+ export function diffusionServer(runtime, isCached, clamps) {
259
+ const cap = normalizeClamps(clamps);
260
+ return {
261
+ serve: async (request, io) => {
262
+ const name = runtime.modelName(request.modelChoice);
263
+ const planned = request.params.prediction ?? undefined;
264
+ if (!(await isCached(name, 'diffusion')) ||
265
+ planned !== runtime.predictionFor(request.modelChoice)) {
266
+ throw new HarnessError('MEDIA_MODEL_MISSING', ['image', name]);
267
+ }
268
+ const params = diffusionParamsFrom(request);
269
+ if (Math.max(params.width ?? 0, params.height ?? 0) > cap.maxDim) {
270
+ return { error: `this device generates images up to ${cap.maxDim}px`, code: 'too-large' };
271
+ }
272
+ const image = await diffuseHere(runtime, {
273
+ modelChoice: request.modelChoice,
274
+ params: { ...params, steps: params.steps && Math.min(params.steps, cap.maxSteps) },
275
+ signal: io.signal,
276
+ onTick: ({ step, totalSteps }) => io.tick({ step, total: totalSteps })
277
+ });
278
+ return image instanceof Uint8Array ? { kind: 'image', bytes: image } : image;
279
+ }
280
+ };
281
+ }
282
+ function diffusionParamsFrom({ params, images = [] }) {
283
+ const number = (key) => {
284
+ const value = params[key];
285
+ return typeof value === 'number' ? value : undefined;
286
+ };
287
+ return {
288
+ prompt: typeof params.prompt === 'string' ? params.prompt : '',
289
+ width: number('width'),
290
+ height: number('height'),
291
+ steps: number('steps'),
292
+ seed: number('seed'),
293
+ negative_prompt: typeof params.negative_prompt === 'string' ? params.negative_prompt : undefined,
294
+ strength: number('strength'),
295
+ guidance: number('guidance'),
296
+ cfg_scale: number('cfg_scale'),
297
+ auto_resize_ref_image: params.auto_resize_ref_image === true || undefined,
298
+ init_images: params.init === 'images' ? images : undefined,
299
+ init_image: params.init === 'image' ? images[0] : undefined
300
+ };
301
+ }
210
302
  export function parseCommonArgs(args, maxSteps = MAX_STEPS) {
211
303
  const prompt = typeof args.prompt === 'string' ? args.prompt.trim() : '';
212
304
  if (!prompt) {
@@ -349,16 +441,11 @@ export function createGenerateImageTool(runtime, clamps) {
349
441
  if (!ctx?.attach) {
350
442
  return { error: 'this device cannot persist generated images' };
351
443
  }
352
- if (!runtime.acquire()) {
353
- return { error: BUSY_ERROR, code: 'busy' };
354
- }
355
444
  const report = ctx.progress;
356
445
  const onTick = report && generationPercentTick((percentage) => report({ percentage }));
357
446
  try {
358
- const sdk = await runtime.loadSdk();
359
- const { modelId } = await runtime.ensureLoaded(sdk, ctx.signal, ctx.image?.modelChoice);
360
- const image = await runDiffusion(sdk, {
361
- modelId,
447
+ const image = await diffuse(runtime, ctx, {
448
+ modelChoice: ctx.image?.modelChoice,
362
449
  params: {
363
450
  prompt: parsed.prompt,
364
451
  width: parsed.width,
@@ -397,7 +484,6 @@ export function createGenerateImageTool(runtime, clamps) {
397
484
  throw err;
398
485
  }
399
486
  finally {
400
- runtime.release();
401
487
  report?.(null);
402
488
  }
403
489
  }
@@ -2,7 +2,7 @@ import type { ImageClamps, ImageModelSet } from '../../lib/models/model-catalog.
2
2
  import type { HarnessPlugin, PluginContext, PluginSetup } from '../../lib/plugins/index.ts';
3
3
  import { loadMediaCodecs } from './edit-image.ts';
4
4
  export { createEditImageTool } from './edit-image.ts';
5
- export { createDiffusionRuntime, createGenerateImageTool, generationPercentTick, settingsDimension, settingsSteps, type DiffusionRuntime, type DiffusionRuntimeOptions, type DiffusionSdk, type DiffusionTick } from './generate-image.ts';
5
+ export { createDiffusionRuntime, createGenerateImageTool, diffusionServer, generationPercentTick, settingsDimension, settingsSteps, type DiffusionRuntime, type DiffusionRuntimeOptions, type DiffusionSdk, type DiffusionTick } from './generate-image.ts';
6
6
  export interface ImageOptions {
7
7
  model: string | ImageModelSet;
8
8
  clamps?: ImageClamps;
@@ -12,6 +12,7 @@ export declare class Image implements HarnessPlugin {
12
12
  readonly name = "image";
13
13
  readonly api = 1;
14
14
  readonly needs: string[];
15
+ readonly provides: string[];
15
16
  readonly addons: {
16
17
  'diffusion-cpp': () => Promise<typeof import("@qvac/diffusion-cpp/addonLogging")>;
17
18
  'bare-image-resample': () => Promise<any>;
@@ -2,9 +2,9 @@ import { HarnessError } from '../../lib/errors.js';
2
2
  import { retryMemo } from '../../lib/helpers/retry-memo.js';
3
3
  import { PluginRegistry } from '../../lib/plugins/index.js';
4
4
  import { createEditImageTool, loadMediaCodecs } from './edit-image.js';
5
- import { createDiffusionRuntime, createGenerateImageTool } from './generate-image.js';
5
+ import { createDiffusionRuntime, createGenerateImageTool, diffusionServer } from './generate-image.js';
6
6
  export { createEditImageTool } from './edit-image.js';
7
- export { createDiffusionRuntime, createGenerateImageTool, generationPercentTick, settingsDimension, settingsSteps } from './generate-image.js';
7
+ export { createDiffusionRuntime, createGenerateImageTool, diffusionServer, generationPercentTick, settingsDimension, settingsSteps } from './generate-image.js';
8
8
  function diffusionRuntime(models, model) {
9
9
  const loadSdk = retryMemo(async () => {
10
10
  const sdk = await models.sdk();
@@ -54,6 +54,7 @@ export class Image {
54
54
  name = 'image';
55
55
  api = PluginRegistry.API_VERSION;
56
56
  needs = ['models'];
57
+ provides = ['image-rounds'];
57
58
  addons = {
58
59
  'diffusion-cpp': () => import('@qvac/diffusion-cpp/addonLogging'),
59
60
  'bare-image-resample': () => import('bare-image-resample'),
@@ -75,9 +76,13 @@ export class Image {
75
76
  }
76
77
  setup(ctx) {
77
78
  const { model, clamps } = this._options;
78
- const runtime = diffusionRuntime(ctx.service('models'), model);
79
+ const models = ctx.service('models');
80
+ const runtime = diffusionRuntime(models, model);
79
81
  return {
80
82
  tools: [createGenerateImageTool(runtime, clamps), createEditImageTool(runtime, {}, clamps)],
83
+ services: {
84
+ 'image-rounds': diffusionServer(runtime, (name, addon) => models.isCached(name, addon), clamps)
85
+ },
81
86
  unload: () => runtime.unload(),
82
87
  unloadIdle: () => runtime.unloadIdle()
83
88
  };