@qvac/harness 1.0.0-rc.17 → 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 (65) hide show
  1. package/CHANGELOG.md +59 -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 +8 -0
  15. package/dist-lib/lib/errors.js +9 -1
  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/office/engine/xlsx/sheet.js +10 -4
  30. package/dist-lib/lib/plugins/registry.d.ts +3 -0
  31. package/dist-lib/lib/serve.js +37 -1
  32. package/dist-lib/lib/sidecar/index.d.ts +1 -1
  33. package/dist-lib/lib/sidecar/index.js +3 -5
  34. package/dist-lib/lib/skills-host/index.js +6 -7
  35. package/dist-lib/lib/tools/index.d.ts +1 -0
  36. package/dist-lib/lib/tools/index.js +1 -1
  37. package/dist-lib/lib/tools/pdf/pages.js +6 -3
  38. package/dist-lib/lib/tools/pdf/recognize.js +2 -1
  39. package/dist-lib/lib/tools/skills/bundled-dir.d.ts +5 -1
  40. package/dist-lib/lib/tools/skills/bundled-dir.js +23 -20
  41. package/dist-lib/lib/tools/skills/catalog.d.ts +1 -1
  42. package/dist-lib/lib/tools/skills/catalog.js +1 -1
  43. package/dist-lib/lib/tools/skills/overlay-crud.d.ts +3 -3
  44. package/dist-lib/lib/tools/skills/overlay-crud.js +4 -4
  45. package/dist-lib/plugins/image/edit-image.js +3 -9
  46. package/dist-lib/plugins/image/generate-image.d.ts +14 -2
  47. package/dist-lib/plugins/image/generate-image.js +94 -8
  48. package/dist-lib/plugins/image/index.d.ts +2 -1
  49. package/dist-lib/plugins/image/index.js +8 -3
  50. package/dist-lib/plugins/music/generate-music.d.ts +18 -2
  51. package/dist-lib/plugins/music/generate-music.js +98 -16
  52. package/dist-lib/plugins/music/index.d.ts +2 -1
  53. package/dist-lib/plugins/music/index.js +6 -2
  54. package/dist-lib/plugins/python/bare-floor.js +1 -1
  55. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-arm64/qvac-sandbox.exe +0 -0
  56. package/dist-lib/plugins/sandbox-windows/prebuilds/win32-x64/qvac-sandbox.exe +0 -0
  57. package/dist-lib/plugins/walkie-talkie/index.d.ts +2 -0
  58. package/dist-lib/plugins/walkie-talkie/index.js +6 -1
  59. package/dist-lib/schema/generate.js +8 -1
  60. package/dist-lib/schema/harness.js +9 -2
  61. package/dist-lib/spec/hrpc/messages.js +46 -4
  62. package/dist-lib/spec/hyperschema/index.js +46 -4
  63. package/dist-lib/spec/hyperschema/schema.json +28 -0
  64. package/dist-lib/spec/hyperschema/types.d.ts +2 -2
  65. package/package.json +8 -9
@@ -5,18 +5,21 @@ import process from 'process';
5
5
  import { HarnessError } from '../../errors.js';
6
6
  import { userTmpPath } from '../../tmp-path.js';
7
7
  import { hashBundledSkills } from './bundled-hash.js';
8
- import { SKILLS as BUNDLED_SKILLS } from '@qvac/skills/bundled';
9
- import { SKILLS_HASH as BUNDLED_SKILLS_HASH } from '@qvac/skills/hash';
10
- let inflight = null;
11
- export function ensureBundledSkillsDir() {
12
- inflight ??= materialize().finally(() => {
13
- inflight = null;
14
- });
15
- return inflight;
8
+ const inflight = new Map();
9
+ export function ensureBundledSkillsDir(bundle) {
10
+ if (!/^[0-9a-f]{16}$/.test(bundle.hash)) {
11
+ return Promise.reject(new HarnessError('BUNDLED_SKILLS_HASH_INVALID', [bundle.hash]));
12
+ }
13
+ let pending = inflight.get(bundle.hash);
14
+ if (!pending) {
15
+ pending = materialize(bundle).finally(() => inflight.delete(bundle.hash));
16
+ inflight.set(bundle.hash, pending);
17
+ }
18
+ return pending;
16
19
  }
17
- async function materialize() {
18
- const dir = userTmpPath('qvac-harness-skills-' + BUNDLED_SKILLS_HASH);
19
- if (await validTree(dir)) {
20
+ async function materialize(bundle) {
21
+ const dir = userTmpPath('qvac-harness-skills-' + bundle.hash);
22
+ if (await validTree(dir, bundle.hash)) {
20
23
  return dir;
21
24
  }
22
25
  const staging = `${dir}-staging-${process.pid}-${randomSuffix()}`;
@@ -25,14 +28,14 @@ async function materialize() {
25
28
  await fs.promises.chmod(staging, 0o700);
26
29
  }
27
30
  try {
28
- await writeTree(staging);
29
- if (!(await validTree(staging))) {
31
+ await writeTree(staging, bundle.skills);
32
+ if (!(await validTree(staging, bundle.hash))) {
30
33
  throw new HarnessError('BUNDLED_SKILLS_INVALID', [staging]);
31
34
  }
32
35
  if (await tryRename(staging, dir)) {
33
36
  return dir;
34
37
  }
35
- if (await validTree(dir)) {
38
+ if (await validTree(dir, bundle.hash)) {
36
39
  return dir;
37
40
  }
38
41
  const trash = `${dir}.trash-${process.pid}-${randomSuffix()}`;
@@ -40,7 +43,7 @@ async function materialize() {
40
43
  await fs.promises.rename(dir, trash);
41
44
  }
42
45
  catch (err) {
43
- if (await validTree(dir)) {
46
+ if (await validTree(dir, bundle.hash)) {
44
47
  return dir;
45
48
  }
46
49
  throw occupiedError(dir, err);
@@ -49,7 +52,7 @@ async function materialize() {
49
52
  if (await tryRename(staging, dir)) {
50
53
  return dir;
51
54
  }
52
- if (await validTree(dir)) {
55
+ if (await validTree(dir, bundle.hash)) {
53
56
  return dir;
54
57
  }
55
58
  throw tamperError(dir);
@@ -77,14 +80,14 @@ async function tryRename(from, to) {
77
80
  return false;
78
81
  }
79
82
  }
80
- async function writeTree(dir) {
81
- for (const [relPath, content] of Object.entries(BUNDLED_SKILLS)) {
83
+ async function writeTree(dir, skills) {
84
+ for (const [relPath, content] of Object.entries(skills)) {
82
85
  const target = path.join(dir, relPath);
83
86
  await fs.promises.mkdir(path.dirname(target), { recursive: true });
84
87
  await fs.promises.writeFile(target, content);
85
88
  }
86
89
  }
87
- async function validTree(dir) {
90
+ async function validTree(dir, hash) {
88
91
  try {
89
92
  if (os.platform() !== 'win32') {
90
93
  const stat = await fs.promises.lstat(dir);
@@ -96,7 +99,7 @@ async function validTree(dir) {
96
99
  if (files === null) {
97
100
  return false;
98
101
  }
99
- return hashBundledSkills(files) === BUNDLED_SKILLS_HASH;
102
+ return hashBundledSkills(files) === hash;
100
103
  }
101
104
  catch {
102
105
  return false;
@@ -66,6 +66,6 @@ export interface LoadSkillCatalogOptions {
66
66
  platform?: string | null;
67
67
  overlayDir?: string | null;
68
68
  }
69
- export declare function loadSkillCatalog(skillsDir: string, { platform, overlayDir }?: LoadSkillCatalogOptions): Promise<SkillCatalogEntry[]>;
69
+ export declare function loadSkillCatalog(skillsDir: string | null, { platform, overlayDir }?: LoadSkillCatalogOptions): Promise<SkillCatalogEntry[]>;
70
70
  export declare function mcpReadMethods(catalog: readonly SkillCatalogEntry[]): ReadonlyMap<string, ReadonlySet<string>>;
71
71
  export declare function detectPlatform(): string;
@@ -65,7 +65,7 @@ function stripCredentialChecks(requires) {
65
65
  return rest;
66
66
  }
67
67
  export async function loadSkillCatalog(skillsDir, { platform = detectPlatform(), overlayDir = resolveSkillsOverlayDir() } = {}) {
68
- const byName = await loadRoot(skillsDir);
68
+ const byName = skillsDir ? await loadRoot(skillsDir) : new Map();
69
69
  if (overlayDir) {
70
70
  for (const [name, overlay] of await loadRoot(overlayDir, 'overlay')) {
71
71
  byName.set(name, mergeOverlay(byName.get(name), overlay));
@@ -7,13 +7,13 @@ export interface SkillFileContent {
7
7
  readonly content: string;
8
8
  readonly origin: 'base' | 'overlay';
9
9
  }
10
- export declare function listManagedSkills(baseDir: string, overlayDir: string | null): Promise<ManagedSkill[]>;
11
- export declare function readSkillFile(baseDir: string, overlayDir: string | null, name: string): Promise<SkillFileContent | null>;
10
+ export declare function listManagedSkills(baseDir: string | null, overlayDir: string | null): Promise<ManagedSkill[]>;
11
+ export declare function readSkillFile(baseDir: string | null, overlayDir: string | null, name: string): Promise<SkillFileContent | null>;
12
12
  export declare function writeSkillFile(overlayDir: string, name: string, content: string): Promise<string>;
13
13
  export interface CopyBaseResult {
14
14
  copied: boolean;
15
15
  }
16
- export declare function copyBaseForEdit(baseDir: string, overlayDir: string, name: string): Promise<CopyBaseResult>;
16
+ export declare function copyBaseForEdit(baseDir: string | null, overlayDir: string, name: string): Promise<CopyBaseResult>;
17
17
  export interface DeleteOverlayResult {
18
18
  removed: boolean;
19
19
  }
@@ -26,7 +26,7 @@ async function readIfPresent(file) {
26
26
  }
27
27
  }
28
28
  export async function listManagedSkills(baseDir, overlayDir) {
29
- const base = await dirNames(baseDir);
29
+ const base = baseDir ? await dirNames(baseDir) : new Set();
30
30
  const overlay = overlayDir ? await dirNames(overlayDir) : new Set();
31
31
  const names = [...new Set([...base, ...overlay])].sort((a, b) => a.localeCompare(b));
32
32
  return names.map((name) => {
@@ -46,7 +46,7 @@ export async function readSkillFile(baseDir, overlayDir, name) {
46
46
  return { content: over, origin: 'overlay' };
47
47
  }
48
48
  }
49
- const base = await readIfPresent(path.join(baseDir, name, 'SKILL.md'));
49
+ const base = baseDir ? await readIfPresent(path.join(baseDir, name, 'SKILL.md')) : null;
50
50
  return base !== null ? { content: base, origin: 'base' } : null;
51
51
  }
52
52
  export async function writeSkillFile(overlayDir, name, content) {
@@ -65,8 +65,8 @@ export async function copyBaseForEdit(baseDir, overlayDir, name) {
65
65
  if (await exists(dest)) {
66
66
  return { copied: false };
67
67
  }
68
- const src = path.join(baseDir, name);
69
- if (!(await exists(src))) {
68
+ const src = baseDir && path.join(baseDir, name);
69
+ if (!src || !(await exists(src))) {
70
70
  throw new HarnessError('SKILL_NOT_FOUND', [name]);
71
71
  }
72
72
  await copyDir(src, dest);
@@ -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
  };
@@ -1,5 +1,5 @@
1
- import type { AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
- import type { MusicSettings, ToolDefinition, ToolExecuteContext } from '../../lib/contract/index.ts';
1
+ import { type AbortSignal as BareAbortSignal } from 'bare-abort-controller';
2
+ import type { MediaRoundServer, MusicSettings, ToolDefinition, ToolExecuteContext } from '../../lib/contract/index.ts';
3
3
  import type { ModelSrc } from '../../lib/models/context.ts';
4
4
  import { type MusicClamps, type MusicModelStages } from '../../lib/models/model-catalog.ts';
5
5
  import type { LoadRequests, ModelHost, TrackedLoad } from '../../lib/contract/models.ts';
@@ -89,6 +89,8 @@ export interface MusicRuntime {
89
89
  gpuRequested: boolean;
90
90
  defaultSteps?: number;
91
91
  ensureLoaded: (sdk: MusicGenSdk, options?: EnsureMusicLoadedOptions) => Promise<LoadedMusicModel>;
92
+ modelName(modelChoice?: string): string;
93
+ choiceFor(modelChoice?: string): string | undefined;
92
94
  unload(): Promise<void>;
93
95
  unloadIdle(): Promise<void>;
94
96
  acquire(): boolean;
@@ -99,10 +101,24 @@ export declare function createMusicRuntime({ loadSdk, onProgress, onBeforeLoad,
99
101
  export declare const BUSY_ERROR = "a music generation is already running; try again when it finishes";
100
102
  export interface MusicToolError {
101
103
  error: string;
104
+ code?: string;
102
105
  }
103
106
  export interface GeneratedTrack extends GeneratedAudio {
104
107
  stats?: MusicStats;
105
108
  }
109
+ export interface MusicOutput extends GeneratedTrack {
110
+ gpuRequested: boolean;
111
+ }
112
+ export interface AudioGenOptions {
113
+ readonly modelChoice?: string | undefined;
114
+ readonly inferenceSteps?: number | undefined;
115
+ readonly params: AudioGenParams;
116
+ readonly signal?: BareAbortSignal | undefined;
117
+ readonly onTick?: ((tick: MusicTick) => void) | undefined;
118
+ }
119
+ export declare function audioGen(runtime: MusicRuntime, ctx: ToolExecuteContext, options: AudioGenOptions): Promise<MusicOutput | MusicToolError>;
120
+ export declare function audioGenHere(runtime: MusicRuntime, { modelChoice, inferenceSteps, params, signal, onTick }: AudioGenOptions): Promise<MusicOutput | MusicToolError>;
121
+ export declare function audioGenServer(runtime: MusicRuntime, isCached: ModelHost['isCached'], clamps?: MusicClamps): MediaRoundServer;
106
122
  export interface RunAudioGenOptions {
107
123
  readonly modelId: string;
108
124
  readonly params: AudioGenParams;
@@ -1,5 +1,7 @@
1
+ import { AbortController } from 'bare-abort-controller';
1
2
  import process from 'process';
2
3
  import ScopeLock from 'scope-lock';
4
+ import { HarnessError } from '../../lib/errors.js';
3
5
  import { AbortedError, raceAbort } from '../../lib/helpers/race-abort.js';
4
6
  import { HarnessLog } from '../../lib/log.js';
5
7
  import { AUDIOGEN_CATALOG, musicChoiceForDit, musicDefaultSteps, musicModelSet } from '../../lib/models/model-catalog.js';
@@ -21,7 +23,7 @@ const MAX_MUSIC_META_CHARS = 32;
21
23
  const STAGE_WEIGHT = {
22
24
  lm: { base: 0, span: 80 },
23
25
  dit: { base: 80, span: 17 },
24
- vae: { base: 97, span: 3 }
26
+ vae: { base: 97, span: 2 }
25
27
  };
26
28
  export function musicPercentTick(onPercent) {
27
29
  let last = -1;
@@ -154,6 +156,8 @@ export function createMusicRuntime({ loadSdk, onProgress, onBeforeLoad, hold, re
154
156
  });
155
157
  return raceAbort(load, signal);
156
158
  },
159
+ modelName: (modelChoice) => musicProgressName(stagesFor(modelChoice, base).dit),
160
+ choiceFor: (modelChoice) => musicChoiceForDit(stagesFor(modelChoice, base).dit),
157
161
  unload,
158
162
  unloadIdle: () => (busy ? Promise.resolve() : unload()),
159
163
  acquire: () => (busy ? false : (busy = true)),
@@ -163,6 +167,92 @@ export function createMusicRuntime({ loadSdk, onProgress, onBeforeLoad, hold, re
163
167
  };
164
168
  }
165
169
  export const BUSY_ERROR = 'a music generation is already running; try again when it finishes';
170
+ export function audioGen(runtime, ctx, options) {
171
+ return ctx.mediaRound
172
+ ? audioGenThere(ctx.mediaRound, ctx.runId ?? '', {
173
+ ...options,
174
+ modelChoice: runtime.choiceFor(options.modelChoice)
175
+ })
176
+ : audioGenHere(runtime, options);
177
+ }
178
+ export async function audioGenHere(runtime, { modelChoice, inferenceSteps, params, signal, onTick }) {
179
+ if (!runtime.acquire()) {
180
+ return { error: BUSY_ERROR, code: 'busy' };
181
+ }
182
+ try {
183
+ const sdk = await runtime.loadSdk();
184
+ const { modelId } = await runtime.ensureLoaded(sdk, { signal, modelChoice, inferenceSteps });
185
+ const track = await runAudioGen(sdk, { modelId, params, signal, onTick });
186
+ return 'error' in track ? track : { ...track, gpuRequested: runtime.gpuRequested };
187
+ }
188
+ finally {
189
+ runtime.release();
190
+ }
191
+ }
192
+ async function audioGenThere(port, runId, { modelChoice, inferenceSteps, params, signal, onTick }) {
193
+ const asked = port({ kind: 'music', runId, modelChoice, params: { ...params, inferenceSteps } }, {
194
+ signal: signal ?? new AbortController().signal,
195
+ tick: ({ stage, step, total }) => onTick?.({ stage: stage ?? '', step, total })
196
+ });
197
+ const result = await raceAbort(asked, signal);
198
+ if ('error' in result) {
199
+ return result;
200
+ }
201
+ if (result.kind !== 'music') {
202
+ return { error: 'the serving device sent no audio' };
203
+ }
204
+ const { bytes, format, gpuRequested, stats } = result;
205
+ return { pcm: bytes, ...format, gpuRequested, stats };
206
+ }
207
+ export function audioGenServer(runtime, isCached, clamps) {
208
+ const cap = normalizeClamps(clamps);
209
+ return {
210
+ serve: async ({ modelChoice, params }, io) => {
211
+ const name = runtime.modelName(modelChoice);
212
+ if (!(await isCached(name, 'audiogen'))) {
213
+ throw new HarnessError('MEDIA_MODEL_MISSING', ['music', name]);
214
+ }
215
+ const steps = numberOf(params.inferenceSteps);
216
+ const audio = audioGenParamsFrom(params);
217
+ const track = await audioGenHere(runtime, {
218
+ modelChoice,
219
+ inferenceSteps: steps && Math.min(steps, cap.maxSteps),
220
+ params: { ...audio, duration: audio.duration && Math.min(audio.duration, cap.maxDuration) },
221
+ signal: io.signal,
222
+ onTick: (tick) => io.tick(tick)
223
+ });
224
+ if ('error' in track) {
225
+ return track;
226
+ }
227
+ const { pcm, sampleRate, channels, bitsPerSample, gpuRequested, stats } = track;
228
+ return {
229
+ kind: 'music',
230
+ bytes: pcm,
231
+ format: { sampleRate, channels, bitsPerSample },
232
+ gpuRequested,
233
+ stats
234
+ };
235
+ }
236
+ };
237
+ }
238
+ function audioGenParamsFrom(params) {
239
+ return {
240
+ caption: stringOf(params.caption) ?? '',
241
+ lyrics: stringOf(params.lyrics),
242
+ duration: numberOf(params.duration),
243
+ seed: numberOf(params.seed),
244
+ bpm: numberOf(params.bpm),
245
+ keyscale: stringOf(params.keyscale),
246
+ timesignature: stringOf(params.timesignature),
247
+ vocalLanguage: stringOf(params.vocalLanguage)
248
+ };
249
+ }
250
+ function numberOf(value) {
251
+ return typeof value === 'number' ? value : undefined;
252
+ }
253
+ function stringOf(value) {
254
+ return typeof value === 'string' ? value : undefined;
255
+ }
166
256
  export async function runAudioGen(sdk, { modelId, params, signal, onTick }) {
167
257
  if (signal?.aborted) {
168
258
  return { error: 'music generation canceled' };
@@ -485,9 +575,6 @@ export function createGenerateMusicTool(runtime, clamps) {
485
575
  if (!ctx?.attach) {
486
576
  return { error: 'this device cannot persist generated audio' };
487
577
  }
488
- if (!runtime.acquire()) {
489
- return { error: BUSY_ERROR, code: 'busy' };
490
- }
491
578
  const report = ctx.progress;
492
579
  const onTick = report && musicPercentTick((percentage) => report({ percentage }));
493
580
  const capMax = stepsCap ?? MAX_STEPS;
@@ -496,20 +583,15 @@ export function createGenerateMusicTool(runtime, clamps) {
496
583
  settingsSteps(choiceDefault ?? runtime.defaultSteps, capMax) ??
497
584
  stepsCap;
498
585
  try {
499
- const sdk = await runtime.loadSdk();
500
- const { modelId } = await runtime.ensureLoaded(sdk, {
501
- signal: ctx.signal,
502
- modelChoice: music.modelChoice,
503
- inferenceSteps: steps
504
- });
505
586
  const hasVocals = parsed.lyrics !== undefined &&
506
587
  parsed.lyrics.trim().toLowerCase() !== INSTRUMENTAL.toLowerCase();
507
588
  const instrumental = !hasVocals;
508
589
  const vocalLanguage = hasVocals
509
590
  ? (parsed.vocalLanguage ?? DEFAULT_VOCAL_LANGUAGE)
510
591
  : undefined;
511
- const result = await runAudioGen(sdk, {
512
- modelId,
592
+ const result = await audioGen(runtime, ctx, {
593
+ modelChoice: music.modelChoice,
594
+ inferenceSteps: steps,
513
595
  params: {
514
596
  caption: parsed.caption,
515
597
  lyrics: hasVocals ? parsed.lyrics : INSTRUMENTAL,
@@ -534,12 +616,13 @@ export function createGenerateMusicTool(runtime, clamps) {
534
616
  raw: true
535
617
  });
536
618
  const stats = presentStats(result.stats);
537
- const fallback = gpuFallback({ gpuRequested: runtime.gpuRequested, stats });
619
+ const { gpuRequested } = result;
620
+ const fallback = gpuFallback({ gpuRequested, stats });
538
621
  const notice = fallback ? CPU_FALLBACK_NOTICE : undefined;
539
- logBackendUsed({ gpuRequested: runtime.gpuRequested, stats, fallback });
622
+ logBackendUsed({ gpuRequested, stats, fallback });
540
623
  ctx.reportBackend?.({
541
624
  tool: GENERATE_MUSIC_TOOL,
542
- requestedGpu: runtime.gpuRequested,
625
+ requestedGpu: gpuRequested,
543
626
  device: backendDevice(stats),
544
627
  backend: backendName(stats?.backendId)
545
628
  });
@@ -567,7 +650,6 @@ export function createGenerateMusicTool(runtime, clamps) {
567
650
  throw err;
568
651
  }
569
652
  finally {
570
- runtime.release();
571
653
  report?.(null);
572
654
  }
573
655
  }