Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: move federated asset staging out of the shared remote-media executor (#4827)

[._.]/ Adam Eivy6007d1e531b6
diff --git a/server/services/federatedMedia/inputAssets.js b/server/services/federatedMedia/inputAssets.js
index 4b72dd91f5..a676649aff 100644
--- a/server/services/federatedMedia/inputAssets.js
+++ b/server/services/federatedMedia/inputAssets.js
@@ -16,14 +16,26 @@
* The paths themselves never cross the wire — they are resolved to ids
* immediately before submission and are meaningless to the peer, which is the
* same reason the audio marker keeps its profile rather than a rendered prompt.
+ *
+ * That resolution — the upload itself — lives here too, not in the shared
+ * remote-media executor. Staging must still run inside a run's retry/cancel/
+ * timeout envelope, so the executor lends the ONE thing only it can provide (an
+ * authenticated, in-envelope `requestJson`) and everything image-shaped stays on
+ * this side of the seam: the size cap, the MIME allowlist, the digest check.
*/
+import { readFile, stat } from 'node:fs/promises';
import { z } from 'zod';
import {
+ FEDERATED_MEDIA_ASSET_MAX_BYTES,
FEDERATED_MEDIA_ASSET_MAX_COUNT,
+ FEDERATED_MEDIA_ASSET_MIME_TYPES,
FEDERATED_MEDIA_INPUT_ROLES,
+ federatedMediaAssetId,
+ federatedMediaAssetSchema,
isMultiInputRole,
} from '../../lib/federatedMediaWire.js';
+import { detectImageFormat, resolveImageInputPath, sha256File } from '../../lib/fileUtils.js';
// Deliberately NOT imported from remoteExecutor.js. That module statically
// pulls the peer registry and consumer, and this one is reached from the image
@@ -106,6 +118,115 @@ export function inputAssetRejection(capability, assets = []) {
return null;
}
+/**
+ * Build this run's conditioning-image stager: local path -> provider asset id
+ * (ADR docs/decisions/2026-08-22-federated-media-input-assets.md rule 1).
+ *
+ * The executor lends exactly one capability — `requestJson`, its own
+ * authenticated request helper already bound to the run, so peer resolution,
+ * auth, cancellation and the timeout envelope all stay intact and the upload
+ * happens INSIDE the run's retry/cancel envelope rather than beside it.
+ * Everything image-shaped — the approved-roots re-anchor, the size cap, the MIME
+ * allowlist, the digest verification — lives here, where the next non-image
+ * sub-request will not inherit it.
+ *
+ * The `localPath -> assetId` memo is per run and deliberately not persisted: an
+ * id names a slot in the provider's TTL-swept staging area, so caching it across
+ * a restart would produce a confident reference to bytes that are gone. Within
+ * one run the memo means a retried submission re-sends the body once, not once
+ * per attempt.
+ *
+ * @param {object} ctx
+ * @param {(path: string, options?: object, requestOptions?: object) => Promise<any>} ctx.requestJson
+ * @param {(message: string) => void} ctx.emitStatus
+ * @returns {(localPath: string) => Promise<string>}
+ */
+function createInputAssetStager({ requestJson, emitStatus }) {
+ const assetIds = new Map();
+
+ return async function stageInputAsset(localPath) {
+ const cached = assetIds.get(localPath);
+ if (cached) return cached;
+
+ // Re-anchored against the approved image roots on every attempt, exactly as
+ // the LOCAL runner re-validates the same input. The marker is persisted,
+ // user-editable queue state, so the path that becomes an outbound upload has
+ // to be one this machine would have rendered from — a bare basename resolves,
+ // and anything outside those roots resolves to null and is refused.
+ const resolved = resolveImageInputPath(localPath);
+ const info = resolved ? await stat(resolved).catch(() => null) : null;
+ if (!info?.isFile()) {
+ throw inputAssetError(
+ 'A conditioning image for this render is missing or unreadable',
+ 'MEDIA_PROVIDER_INPUT_UNREADABLE',
+ );
+ }
+ if (info.size > FEDERATED_MEDIA_ASSET_MAX_BYTES) {
+ throw inputAssetError(
+ 'A conditioning image for this render is too large to send to a peer',
+ 'MEDIA_PROVIDER_ASSET_TOO_LARGE',
+ );
+ }
+ // Streamed above 512 KB, so the ASK-FIRST path below never buffers a
+ // multi-megabyte image just to learn it is already staged.
+ const digest = await sha256File(resolved);
+ // Lazily imported, not statically: the image/video generate routes reach
+ // this module, and a static edge to the peer registry would drag it (and
+ // its settings/DB dependencies) into every route suite's module graph.
+ // Same reason remoteSubmission.js defers the same import.
+ const { getInstanceId } = await import('../instances.js');
+ const assetId = federatedMediaAssetId(await getInstanceId(), digest);
+
+ // Ask before sending. The id is fully derivable from our own instance id and
+ // the content digest — that is what content addressing buys — so a job
+ // replayed after a restart, or a second render from the same init image,
+ // costs one small GET instead of re-sending up to 32 MiB. A 404 is the
+ // normal miss (never uploaded, or swept), not an error.
+ const staged = await requestJson(`/api/federation/media/v1/assets/${assetId}`)
+ .then((body) => federatedMediaAssetSchema.safeParse(body), () => null);
+ if (staged?.success && staged.data.sha256 === digest) {
+ assetIds.set(localPath, staged.data.assetId);
+ return staged.data.assetId;
+ }
+
+ const body = await readFile(resolved).catch(() => null);
+ if (!body) {
+ throw inputAssetError(
+ 'A conditioning image for this render is missing or unreadable',
+ 'MEDIA_PROVIDER_INPUT_UNREADABLE',
+ );
+ }
+ const detected = detectImageFormat(body);
+ if (!detected || !FEDERATED_MEDIA_ASSET_MIME_TYPES.includes(detected.mime)) {
+ throw inputAssetError(
+ 'A conditioning image for this render is not a format peers accept',
+ 'MEDIA_PROVIDER_ASSET_TYPE_UNSUPPORTED',
+ );
+ }
+ emitStatus('Sending source image to the remote provider');
+ const response = await requestJson('/api/federation/media/v1/assets', {
+ method: 'POST',
+ headers: { 'Content-Type': detected.mime, 'X-Content-SHA256': digest },
+ body,
+ }, {
+ // A multi-megabyte upload legitimately outruns the JSON request timeout.
+ timeoutScale: 10,
+ });
+ const parsed = federatedMediaAssetSchema.safeParse(response);
+ // The provider echoes back the digest it computed. A mismatch means the
+ // bytes it stored are not the bytes we sent, and rendering from them would
+ // produce a plausible image of the wrong thing.
+ if (!parsed.success || parsed.data.sha256 !== digest) {
+ throw inputAssetError(
+ 'Remote media provider returned an invalid asset receipt',
+ 'MEDIA_PROVIDER_ASSET_INTEGRITY',
+ );
+ }
+ assetIds.set(localPath, parsed.data.assetId);
+ return parsed.data.assetId;
+ };
+}
+
/**
* Stage each local asset on the provider and fold the returned ids into the
* wire request.
@@ -120,12 +241,15 @@ export function inputAssetRejection(capability, assets = []) {
*
* @param {object} request - validated wire submission, without asset refs
* @param {Array<{role: string, path: string}>} assets
- * @param {(path: string) => Promise<string>} stageAsset - uploads and returns an assetId
+ * @param {{requestJson: Function, emitStatus: Function}} ctx - the executor's
+ * in-envelope request capability for this run; the stager is built from it
+ * lazily, so a text-only render never allocates one.
* @param {import('zod').ZodTypeAny} [schema] - refined schema for the finished body
* @returns {Promise<object>} the request with `{ assetId }` refs filled in
*/
-export async function applyRemoteInputAssets(request, assets, stageAsset, schema) {
+export async function applyRemoteInputAssets(request, assets, ctx, schema) {
if (!Array.isArray(assets) || assets.length === 0) return request;
+ const stageAsset = createInputAssetStager(ctx);
// Staged CONCURRENTLY: up to 8 independent multi-megabyte uploads, each one
// otherwise waiting out the last inside the run's timeout envelope. The
// results are folded in afterwards, in the original order, because reference
diff --git a/server/services/federatedMedia/remoteExecutor.js b/server/services/federatedMedia/remoteExecutor.js
index 9b937b6788..75494eb4b2 100644
--- a/server/services/federatedMedia/remoteExecutor.js
+++ b/server/services/federatedMedia/remoteExecutor.js
@@ -14,30 +14,31 @@
* supplied by the caller. The retry/cancel/idempotency/integrity semantics are
* NOT: they are the part that must stay identical across kinds, which is why
* this module owns them instead of each adapter re-deriving them.
+ *
+ * A kind whose request body cannot be built without talking to the peer first
+ * (image conditioning has to be uploaded and turned into asset ids) gets this
+ * run's own `requestJson` handed to `buildRequest` rather than a routine of its
+ * own here. The cross-kind concept is "an authenticated sub-request inside the
+ * run's envelope"; WHAT is sent stays with the kind that knows — see
+ * federatedMedia/inputAssets.js.
*/
import { createWriteStream } from 'node:fs';
-import { mkdir, readFile, rename, stat, unlink } from 'node:fs/promises';
+import { mkdir, rename, stat, unlink } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import { join } from 'node:path';
import { Readable, Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
+import { sha256File } from '../../lib/fileUtils.js';
import {
- detectImageFormat, resolveImageInputPath, sha256File, sha256Text,
-} from '../../lib/fileUtils.js';
-import {
- FEDERATED_MEDIA_ASSET_MAX_BYTES,
- FEDERATED_MEDIA_ASSET_MIME_TYPES,
FEDERATED_MEDIA_WIRE_VERSION,
- federatedMediaAssetId,
- federatedMediaAssetSchema,
federatedMediaProviderJobSchema,
} from '../../lib/federatedMediaWire.js';
import { peerFetch } from '../../lib/peerHttpClient.js';
import { peerBaseUrl } from '../../lib/peerUrl.js';
import { readResponseJson } from '../../lib/readResponseJson.js';
import { resolveFederatedMediaProvider } from '../federatedMediaConsumer.js';
-import { getInstanceId, getPeers } from '../instances.js';
+import { getPeers } from '../instances.js';
import { isTailnetPeer } from '../../lib/tailnetPeer.js';
const RETRYABLE_HTTP_STATUSES = new Set([408, 425, 429]);
@@ -76,7 +77,13 @@ const isRetryableTransportError = (error) =>
* @param {string} config.label - Human noun used in progress/failure messages.
* @param {import('events').EventEmitter} config.events - The kind's gen event emitter.
* @param {import('zod').ZodTypeAny} config.markerSchema - Schema for `params.remoteMedia`.
- * @param {(marker: object) => object} config.buildRequest - Wire submission body builder.
+ * @param {(marker: object, ctx: object) => object|Promise<object>} config.buildRequest -
+ * Wire submission body builder. `ctx` carries this run's `requestJson` — the
+ * same authenticated, in-envelope request helper the executor uses itself, so
+ * a body that has to make a sub-request while it is being built (staging
+ * conditioning images today) does so inside the run's retry, cancel and
+ * timeout envelope — plus `emitStatus` to narrate it. WHAT that sub-request is
+ * stays kind-specific; the executor only lends the channel.
* @param {(ctx: object) => {dir: string, filename: string}} config.resolveDestination -
* Where the verified result lands. Called per job so a PATHS proxy stays live.
* @param {(ctx: object) => Promise<object>} config.finalize - Register the downloaded
@@ -125,7 +132,15 @@ export function createRemoteMediaExecutor({
});
}
- async function withRequest(state, fn, { respectCancel = true, timeoutMs = requestTimeoutMs } = {}) {
+ // `timeoutScale` multiplies the JSON request timeout for a sub-request that
+ // legitimately outruns it (a multi-megabyte conditioning upload). It stays a
+ // scale rather than an absolute so callers outside this module never have to
+ // know — or fall out of sync with — the configured base timeout.
+ async function withRequest(
+ state,
+ fn,
+ { respectCancel = true, timeoutScale = 1, timeoutMs = requestTimeoutMs * timeoutScale } = {},
+ ) {
const controller = new AbortController();
const timer = timeoutMs === null ? null : setTimeout(() => controller.abort(), timeoutMs);
timer?.unref?.();
@@ -188,91 +203,6 @@ export function createRemoteMediaExecutor({
return body;
}
- /**
- * Upload one local conditioning image and return the provider's asset id
- * (ADR docs/decisions/2026-08-22-federated-media-input-assets.md rule 1).
- *
- * Memoized per run rather than persisted: an id belongs to the provider's
- * TTL-swept staging area, so caching it across a restart would produce a
- * confident reference to bytes that are gone. Within one run the cache means
- * a retried submission re-sends the body once, not once per attempt.
- *
- * The digest is computed here and echoed back by the provider; a mismatch
- * means the bytes it stored are not the bytes we sent, and rendering from
- * them would produce a plausible image of the wrong thing.
- */
- async function stageInputAsset(state, localPath) {
- const cached = state.assetIds.get(localPath);
- if (cached) return cached;
-
- // Re-anchored against the approved image roots on every attempt, exactly as
- // the LOCAL runner re-validates the same input. The marker is persisted,
- // user-editable queue state, so the path that becomes an outbound upload has
- // to be one this machine would have rendered from — a bare basename resolves,
- // and anything outside those roots resolves to null and is refused.
- const resolved = resolveImageInputPath(localPath);
- const info = resolved ? await stat(resolved).catch(() => null) : null;
- if (!info?.isFile()) {
- throw remoteMediaError('A conditioning image for this render is missing or unreadable', {
- code: 'MEDIA_PROVIDER_INPUT_UNREADABLE',
- });
- }
- if (info.size > FEDERATED_MEDIA_ASSET_MAX_BYTES) {
- throw remoteMediaError('A conditioning image for this render is too large to send to a peer', {
- code: 'MEDIA_PROVIDER_ASSET_TOO_LARGE',
- });
- }
- // Streamed above 512 KB, so the ASK-FIRST path below never buffers a
- // multi-megabyte image just to learn it is already staged.
- const digest = await sha256File(resolved);
- const assetId = federatedMediaAssetId(await getInstanceId(), digest);
-
- // Ask before sending. The id is fully derivable from our own instance id and
- // the content digest — that is what content addressing buys — so a job
- // replayed after a restart, or a second render from the same init image,
- // costs one small GET instead of re-sending up to 32 MiB. A 404 is the
- // normal miss (never uploaded, or swept), not an error.
- const staged = await requestJson(state, `/api/federation/media/v1/assets/${assetId}`)
- .then((body) => federatedMediaAssetSchema.safeParse(body), () => null);
- if (staged?.success && staged.data.sha256 === digest) {
- state.assetIds.set(localPath, staged.data.assetId);
- return staged.data.assetId;
- }
-
- const body = await readFile(resolved).catch(() => null);
- if (!body) {
- throw remoteMediaError('A conditioning image for this render is missing or unreadable', {
- code: 'MEDIA_PROVIDER_INPUT_UNREADABLE',
- });
- }
- const detected = detectImageFormat(body);
- if (!detected || !FEDERATED_MEDIA_ASSET_MIME_TYPES.includes(detected.mime)) {
- throw remoteMediaError('A conditioning image for this render is not a format peers accept', {
- code: 'MEDIA_PROVIDER_ASSET_TYPE_UNSUPPORTED',
- });
- }
- emitStatus(state.jobId, 'Sending source image to the remote provider');
- const response = await requestJson(state, '/api/federation/media/v1/assets', {
- method: 'POST',
- headers: { 'Content-Type': detected.mime, 'X-Content-SHA256': digest },
- body,
- }, {
- // A multi-megabyte upload legitimately outruns the JSON request timeout.
- timeoutMs: requestTimeoutMs * 10,
- });
- const parsed = federatedMediaAssetSchema.safeParse(response);
- // The provider echoes back the digest it computed. A mismatch means the
- // bytes it stored are not the bytes we sent, and rendering from them would
- // produce a plausible image of the wrong thing.
- if (!parsed.success || parsed.data.sha256 !== digest) {
- throw remoteMediaError('Remote media provider returned an invalid asset receipt', {
- code: 'MEDIA_PROVIDER_ASSET_INTEGRITY',
- });
- }
- state.assetIds.set(localPath, parsed.data.assetId);
- return parsed.data.assetId;
- }
-
function parseProviderJob(body, expectedId) {
const parsed = federatedMediaProviderJobSchema.safeParse(body);
if (!parsed.success || parsed.data.kind !== kind || (expectedId && parsed.data.id !== expectedId)) {
@@ -522,10 +452,14 @@ export function createRemoteMediaExecutor({
}
async function runRemote(state, marker) {
- // Awaited: an image/video marker resolves its persisted LOCAL conditioning
- // paths into provider asset ids here, inside this run's retry, cancel and
- // timeout envelope rather than before it.
- const request = await buildRequest(marker, { stageAsset: (path) => stageInputAsset(state, path) });
+ // Awaited, and handed this run's own request channel: an image/video marker
+ // resolves its persisted LOCAL conditioning paths into provider asset ids
+ // here, inside this run's retry, cancel and timeout envelope rather than
+ // before it. See federatedMedia/inputAssets.js for what that entails.
+ const request = await buildRequest(marker, {
+ requestJson: (path, options, requestOptions) => requestJson(state, path, options, requestOptions),
+ emitStatus: (message) => emitStatus(state.jobId, message),
+ });
const selection = { kind, engine: request.engine, modelId: request.modelId };
if (!marker.reconcile) await preflight(state, selection);
if (state.cancelRequested && !marker.reconcile && !state.submissionMayExist) throw canceledError();
@@ -570,11 +504,6 @@ export function createRemoteMediaExecutor({
// Absent on an interactive marker (and on any marker queued before this
// shipped), which reads correctly as "not a standing route".
standingRoute: marker.data.standingRoute === true,
- // localPath -> provider assetId, for this run only. Deliberately not
- // persisted: the id names a slot in the peer's TTL-swept staging area, so
- // a cached id that outlived the run would be a confident reference to
- // bytes that are gone. See federatedMedia/inputAssets.js.
- assetIds: new Map(),
requestController: null,
wake: null,
};
diff --git a/server/services/imageGen/remote.js b/server/services/imageGen/remote.js
index 86ff42e9c1..e434e6467c 100644
--- a/server/services/imageGen/remote.js
+++ b/server/services/imageGen/remote.js
@@ -54,8 +54,8 @@ const executor = createRemoteMediaExecutor({
label: 'image',
events: imageGenEvents,
markerSchema: remoteImageMarkerSchema,
- buildRequest: (marker, { stageAsset }) => applyRemoteInputAssets(
- marker.request, marker.inputAssets, stageAsset, federatedMediaImageJobSubmissionSchema,
+ buildRequest: (marker, ctx) => applyRemoteInputAssets(
+ marker.request, marker.inputAssets, ctx, federatedMediaImageJobSubmissionSchema,
),
// PATHS is read per job (not captured at module load) so a test that swaps
// the gallery directory still sees its own temp root. The `<jobId>.png`
diff --git a/server/services/videoGen/remote.js b/server/services/videoGen/remote.js
index ea4685d32a..47390c584f 100644
--- a/server/services/videoGen/remote.js
+++ b/server/services/videoGen/remote.js
@@ -56,8 +56,8 @@ const executor = createRemoteMediaExecutor({
label: 'video',
events: videoGenEvents,
markerSchema: remoteVideoMarkerSchema,
- buildRequest: (marker, { stageAsset }) => applyRemoteInputAssets(
- marker.request, marker.inputAssets, stageAsset, federatedMediaVideoJobSubmissionSchema,
+ buildRequest: (marker, ctx) => applyRemoteInputAssets(
+ marker.request, marker.inputAssets, ctx, federatedMediaVideoJobSubmissionSchema,
),
// `<jobId>.mp4` is videoGen/local.js's own filename shape, which is what the
// provider-side result guard and the local history row both key on.