Skip to content

Commit 938f25e

Browse files
author
Your Name
committed
fix(videos): deadline abort classification, pruned-path guard, video aliases, DNS noun
Address Wibias fourth CHANGES_REQUESTED review: 1. Deadline abort classification (required #1): - Replace 0.95 wall-clock heuristic with signal.reason.name === 'TimeoutError' - deadlineSignal declared outside try so catch can check deadlineSignal.aborted - Submit catch returns timeout error when deadlineSignal fires (not generic abort) 2. Don't deliver pruned artifact paths (required lidge-jun#2): - After batch prune, scan fulfilled results and rewrite any whose path no longer exists to ok:false with explanatory error 3. Wire video aliases (required lidge-jun#3): - planVideoBridge seeds toolNames with VIDEO_GEN_TOOL_NAME + any request function tools matching isVideoGenName (image-bridge parity) - core.ts filter only strips unnamespaced video_gen aliases (namespaced MCP tools are left alone) 4. Fix test fixtures (required lidge-jun#4): - authMode 'api_key' → 'key' (valid OcxProviderConfig value) 5. DNS error noun (small): - resolvePublicAddresses accepts optional noun param (default 'image') - downloadVideoToArtifact passes 'video'
1 parent c613b05 commit 938f25e

7 files changed

Lines changed: 49 additions & 28 deletions

File tree

‎src/images/artifacts.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -548,7 +548,7 @@ export async function downloadVideoToArtifact(
548548
if (assessment && assessment.kind !== "public" && assessment.kind !== "hostname") {
549549
throw new Error(`video URL targets ${assessment.detail}`);
550550
}
551-
const resolved = await resolvePublicAddresses(url);
551+
const resolved = await resolvePublicAddresses(url, "video");
552552
const pinned = pickPinnedAddress(resolved.addresses);
553553
const resp = await pinnedHttpsGet(url, pinned, signal, { maxBytes: MAX_VIDEO_DOWNLOAD_BYTES });
554554
if (!resp.ok) {

‎src/images/fulfill-video.ts‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -84,10 +84,11 @@ export async function* pollVideoWithHeartbeats(
8484
> {
8585
const start = Date.now();
8686
let interval = INITIAL_POLL_INTERVAL_MS;
87+
const timeoutStr = `video generation timed out after ${Math.floor(timeoutMs / 1000)}s`;
8788

8889
for (;;) {
8990
if (Date.now() - start >= timeoutMs) {
90-
return { ok: false, error: `video generation timed out after ${Math.floor(timeoutMs / 1000)}s` };
91+
return { ok: false, error: timeoutStr };
9192
}
9293

9394
try {
@@ -106,11 +107,11 @@ export async function* pollVideoWithHeartbeats(
106107
}
107108
// still processing — continue with backoff
108109
} catch (e) {
109-
if (signal.aborted) {
110-
return { ok: false, error: Date.now() - start >= timeoutMs * 0.95
111-
? `video generation timed out after ${Math.floor(timeoutMs / 1000)}s`
112-
: "client closed request during video generation" };
113-
}
110+
// Distinguish deadline-expiry from client-cancel.
111+
// AbortSignal.timeout sets signal.reason to a TimeoutError.
112+
const isDeadline = signal.aborted && e instanceof Error && e.name === "TimeoutError";
113+
if (isDeadline) return { ok: false, error: timeoutStr };
114+
if (signal.aborted) return { ok: false, error: "client closed request during video generation" };
114115
const status = (e as Error & { status?: number }).status;
115116
if (status && status >= 400 && status < 500 && status !== 429) {
116117
return { ok: false, error: `video poll failed permanently: HTTP ${status}` };
@@ -124,9 +125,8 @@ export async function* pollVideoWithHeartbeats(
124125
try {
125126
await sleep(interval, signal);
126127
} catch {
127-
if (Date.now() - start >= timeoutMs * 0.95) {
128-
return { ok: false, error: `video generation timed out after ${Math.floor(timeoutMs / 1000)}s` };
129-
}
128+
const isDeadline = signal.aborted && signal.reason instanceof Error && signal.reason.name === "TimeoutError";
129+
if (isDeadline) return { ok: false, error: timeoutStr };
130130
return { ok: false, error: "client closed request during video generation" };
131131
}
132132

‎src/images/loop.ts‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
* dedup, no describeImages/structuredOutput, no recordSidecarOutcome.
1212
*/
1313
import type { AdapterRequest, ProviderAdapter } from "../adapters/base";
14+
import { existsSync } from "node:fs";
1415
import { createAdapterEventQueue } from "../adapters/run-turn-queue";
1516
import type { AdapterEvent, OcxMessage, OcxParsedRequest, OcxProviderContinuationState, OcxRequestOptions, OcxThinkingContent, OcxUsage } from "../types";
1617
import { namespacedToolName } from "../types";
@@ -609,11 +610,11 @@ export async function runWithImageBridge(deps: ImageBridgeDeps): Promise<Respons
609610
vResult = { ok: false, model: videoPlan!.model, prompt: "", files: [], count: 0, error: vArgs.error };
610611
} else {
611612
paidVideoCalls += 1;
613+
const videoTimeout = videoTimeoutMs ?? 300_000;
614+
const deadlineSignal = AbortSignal.timeout(videoTimeout);
612615
try {
613-
const videoTimeout = videoTimeoutMs ?? 300_000;
614616
const videoDeadline = Date.now() + videoTimeout;
615617
// Bind submit to the shared deadline so submit + poll fit one budget.
616-
const deadlineSignal = AbortSignal.timeout(videoTimeout);
617618
const linkedDeadline = signal
618619
? AbortSignal.any([signal, deadlineSignal])
619620
: deadlineSignal;
@@ -650,9 +651,14 @@ export async function runWithImageBridge(deps: ImageBridgeDeps): Promise<Respons
650651
}
651652
}
652653
} catch (e) {
653-
if (signal.aborted) throw new LoopError(499, "client closed request during video-bridge");
654-
const error = e instanceof Error ? e.message : String(e);
655-
vResult = { ok: false, model: videoPlan!.model, prompt: vArgs.prompt ?? "", files: [], count: 0, error };
654+
if (deadlineSignal.aborted && !signal.aborted) {
655+
vResult = { ok: false, model: videoPlan!.model, prompt: vArgs.prompt ?? "", files: [], count: 0, error: `video generation timed out after ${Math.floor(videoTimeout / 1000)}s` };
656+
} else if (signal.aborted) {
657+
throw new LoopError(499, "client closed request during video-bridge");
658+
} else {
659+
const error = e instanceof Error ? e.message : String(e);
660+
vResult = { ok: false, model: videoPlan!.model, prompt: vArgs.prompt ?? "", files: [], count: 0, error };
661+
}
656662
}
657663
}
658664
if (signal.aborted) throw new LoopError(499, "client closed request during video-bridge");
@@ -696,6 +702,12 @@ export async function runWithImageBridge(deps: ImageBridgeDeps): Promise<Respons
696702
// Prune artifacts once after the entire batch so a tight keepCount
697703
// cannot delete a video from an earlier call in this same iteration.
698704
pruneArtifacts(videoPlan?.artifactsKeepCount ?? plan?.artifactsKeepCount);
705+
// Drop results whose artifact files were pruned — never hand the model a dead path.
706+
for (const f of fulfilled) {
707+
if (f.result.ok && f.result.path && !existsSync(f.result.path)) {
708+
f.result = { ...f.result, ok: false, path: undefined, files: [], count: 0, error: "artifact was pruned before delivery (increase artifactsKeepCount)" };
709+
}
710+
}
699711
const now = Date.now();
700712
messages.push({
701713
role: "assistant",

‎src/images/plan.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import type { OcxConfig, OcxParsedRequest, OcxProviderConfig } from "../types";
22
import type { ImageBridgePlan, VideoBridgePlan } from "./types";
33
import { resolveEnvValue } from "../config";
44
import { getProviderRegistryEntry } from "../providers/registry";
5-
import { IMAGE_GEN_TOOL_NAME, VIDEO_GEN_TOOL_NAME } from "./synthetic-tool";
5+
import { IMAGE_GEN_TOOL_NAME, VIDEO_GEN_TOOL_NAME, isVideoGenName } from "./synthetic-tool";
66

77
const DEFAULT_MODEL = "grok-imagine-image-quality";
88
/** Absolute ceiling for `images.timeoutMs` (matches /v1/images relay budget). */
@@ -91,7 +91,7 @@ const DEFAULT_VIDEO_MODEL = "grok-imagine-video";
9191
*/
9292
export async function planVideoBridge(
9393
config: OcxConfig,
94-
_parsed: OcxParsedRequest,
94+
parsed: OcxParsedRequest,
9595
routedProvider: OcxProviderConfig,
9696
): Promise<VideoBridgePlan | undefined> {
9797
if (config.images?.videoBridgeEnabled !== true) return undefined;
@@ -107,6 +107,15 @@ export async function planVideoBridge(
107107
const pinnedBaseUrl = (registryEntry?.baseUrl ?? "https://api.x.ai/v1").replace(/\/+$/, "");
108108
const toolNames = new Set<string>();
109109
toolNames.add(VIDEO_GEN_TOOL_NAME);
110+
// Collect any existing function tools whose name matches a video_gen alias
111+
// so the loop can intercept and replace them (image-bridge parity).
112+
for (const t of parsed.context?.tools ?? []) {
113+
const fnName = typeof t.name === "string" ? t.name
114+
: (t as unknown as { function?: { name?: string } }).function?.name;
115+
if (typeof fnName === "string" && isVideoGenName(fnName)) {
116+
toolNames.add(fnName);
117+
}
118+
}
110119
const timeoutMs = clampImageTimeoutMs(config.images?.videoTimeoutMs);
111120
const keepRaw = config.images?.artifactsKeepCount;
112121
const artifactsKeepCount =

‎src/lib/destination-policy.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -219,20 +219,20 @@ export function assessUrlDestination(url: string): UrlDestinationAssessment | nu
219219
* so callers can pin the connect peer and avoid a second, rebindable resolution.
220220
* DNS resolution failures are treated as unsafe (fail-closed).
221221
*/
222-
export async function resolvePublicAddresses(url: string): Promise<{
222+
export async function resolvePublicAddresses(url: string, noun: string = "image"): Promise<{
223223
hostname: string;
224224
addresses: { address: string; family: number }[];
225225
}> {
226226
let hostname: string;
227227
try {
228228
hostname = normalizeHostname(new URL(url.trim()).hostname);
229229
} catch {
230-
throw new Error("image URL is not a valid URL");
230+
throw new Error(`${noun} URL is not a valid URL`);
231231
}
232-
if (!hostname) throw new Error("image URL has no hostname");
232+
if (!hostname) throw new Error(`${noun} URL has no hostname`);
233233
const literalAssessment = assessDestination(url);
234234
if (literalAssessment && literalAssessment.kind !== "public" && literalAssessment.kind !== "hostname") {
235-
throw new Error(`image URL targets ${literalAssessment.detail}`);
235+
throw new Error(`${noun} URL targets ${literalAssessment.detail}`);
236236
}
237237
// Literal public IPs: no DNS round-trip; pin the literal itself.
238238
const literalKind = isIP(hostname);
@@ -245,10 +245,10 @@ export async function resolvePublicAddresses(url: string): Promise<{
245245
} catch {
246246
// If DNS fails, we can't verify — fail-closed (unlike provider config-time validation,
247247
// this is a runtime fetch to an untrusted URL, so be conservative).
248-
throw new Error(`image URL hostname ${hostname} could not be resolved`);
248+
throw new Error(`${noun} URL hostname ${hostname} could not be resolved`);
249249
}
250250
if (addresses.length === 0) {
251-
throw new Error(`image URL hostname ${hostname} could not be resolved`);
251+
throw new Error(`${noun} URL hostname ${hostname} could not be resolved`);
252252
}
253253
const publicAddresses: { address: string; family: number }[] = [];
254254
for (const { address, family } of addresses) {
@@ -257,7 +257,7 @@ export async function resolvePublicAddresses(url: string): Promise<{
257257
const ipKind = isIP(address) || (family === 4 || family === 6 ? family : 0);
258258
const assessment = ipKind === 4 ? classifyIpv4(address) : ipKind === 6 ? classifyIpv6(normalizeHostname(address)) : null;
259259
if (!assessment || assessment.kind !== "public") {
260-
throw new Error(`image URL hostname ${hostname} resolves to ${assessment?.detail ?? "an unsafe address"} (${address})`);
260+
throw new Error(`${noun} URL hostname ${hostname} resolves to ${assessment?.detail ?? "an unsafe address"} (${address})`);
261261
}
262262
publicAddresses.push({ address, family: ipKind === 4 || ipKind === 6 ? ipKind : (family || 4) });
263263
}

‎src/server/responses/core.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1625,8 +1625,8 @@ export async function handleResponses(
16251625
if (t.videoGeneration) return false;
16261626
if (imgPlan && imgPlan.toolNames.has(t.name)) return false;
16271627
if (imgPlan && t.namespace && imgPlan.toolNames.has(namespacedToolName(t.namespace, t.name))) return false;
1628-
if (vidPlan && vidPlan.toolNames.has(t.name)) return false;
1629-
if (vidPlan && t.namespace && vidPlan.toolNames.has(namespacedToolName(t.namespace, t.name))) return false;
1628+
// Only strip unnamespaced video_gen aliases — a namespaced MCP video_gen is left alone.
1629+
if (vidPlan && !t.namespace && vidPlan.toolNames.has(t.name)) return false;
16301630
return true;
16311631
})];
16321632
const existingNames = new Set(bridgeTools.map(t => t.name));

‎tests/videos/plan-video.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ function makeConfig(overrides: Partial<OcxConfig> = {}): OcxConfig {
77
const xai: OcxProviderConfig = {
88
name: "xai",
99
baseUrl: "https://api.x.ai/v1",
10-
authMode: "api_key",
10+
authMode: "key",
1111
apiKey: "xai-test-key",
1212
};
1313
return {
@@ -21,7 +21,7 @@ function makeParsed(): OcxParsedRequest {
2121
}
2222

2323
function makeProvider(host: string): OcxProviderConfig {
24-
return { baseUrl: `https://${host}`, authMode: "api_key", apiKey: "other-key" } as unknown as OcxProviderConfig;
24+
return { baseUrl: `https://${host}`, authMode: "key", apiKey: "other-key" } as unknown as OcxProviderConfig;
2525
}
2626

2727
describe("planVideoBridge", () => {

0 commit comments

Comments
 (0)