@hubfluencer/mcp 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -29488,13 +29488,13 @@ function normalizeStatus(kind, slug, data) {
29488
29488
  const latest = asRecord(d.latest_render);
29489
29489
  const videoUrl = latest.video_url ?? null;
29490
29490
  if (kind === "short") {
29491
- const stage = d.stage ?? "unknown";
29491
+ const stage2 = d.stage ?? "unknown";
29492
29492
  const status = {
29493
29493
  kind,
29494
29494
  slug,
29495
- stage,
29496
- terminal: stage === "video_ready" || stage === "failed",
29497
- ready: stage === "video_ready",
29495
+ stage: stage2,
29496
+ terminal: stage2 === "video_ready" || stage2 === "failed",
29497
+ ready: stage2 === "video_ready",
29498
29498
  video_url: videoUrl,
29499
29499
  error: d.error_message ?? null
29500
29500
  };
@@ -29522,29 +29522,127 @@ function normalizeStatus(kind, slug, data) {
29522
29522
  };
29523
29523
  }
29524
29524
  if (kind === "slider") {
29525
- const stage = d.status ?? "unknown";
29525
+ const stage2 = d.status ?? "unknown";
29526
29526
  return {
29527
29527
  kind,
29528
29528
  slug,
29529
- stage,
29530
- terminal: stage === "completed" || stage === "failed",
29531
- ready: stage === "completed",
29529
+ stage: stage2,
29530
+ terminal: stage2 === "completed" || stage2 === "failed",
29531
+ ready: stage2 === "completed",
29532
29532
  video_url: null,
29533
29533
  error: d.error_message ?? null
29534
29534
  };
29535
29535
  }
29536
29536
  const autopilot = d.autopilot_status ?? "unknown";
29537
29537
  const renderStatus = latest.status ?? null;
29538
- const ready = renderStatus === "completed" && Boolean(videoUrl);
29539
- const terminal = ready || autopilot === "failed" || autopilot === "cancelled" || renderStatus === "failed";
29538
+ const segments = Array.isArray(d.segments) ? d.segments.map(asRecord) : [];
29539
+ const activeSegments = segments.filter((segment) => {
29540
+ const status = segment.status;
29541
+ const preview = segment.preview_status;
29542
+ return status === "processing" || preview === "processing" || preview === "generating";
29543
+ });
29544
+ const staleSegments = segments.filter((segment) => segment.video_stale === true && segment.status === "completed");
29545
+ const failedSegments = segments.filter((segment) => segment.status === "failed");
29546
+ const batchStatus = d.batch_generation_status ?? null;
29547
+ const batchActive = batchStatus === "running" || batchStatus === "preparing" || batchStatus === "awaiting_previews" || batchStatus === "paused_for_retry";
29548
+ const batchInsufficientCredits = batchStatus === "paused_insufficient_credits";
29549
+ const batchFailed = batchStatus === "failed";
29550
+ const autopilotActive = [
29551
+ "pending",
29552
+ "running",
29553
+ "generating",
29554
+ "rendering"
29555
+ ].includes(autopilot);
29556
+ const audioStale = d.narration_stale === true || d.voice_stale === true || d.music_stale === true;
29557
+ const renderStale = latest.is_stale === true;
29558
+ const renderFresh = latest.is_stale === false;
29559
+ const stale = renderStale || staleSegments.length > 0 || audioStale;
29560
+ const renderActive = renderStatus === "pending" || renderStatus === "rendering" || renderStatus === "processing";
29561
+ const scenarioActive = d.scenario_status === "generating" || d.scenario_apply_status === "applying";
29562
+ const narrationActive = d.narration_status === "generating";
29563
+ const scenarioFailed = d.scenario_status === "failed";
29564
+ const scenarioApplyFailed = d.scenario_apply_status === "failed";
29565
+ const narrationFailed = d.narration_status === "failed";
29566
+ const currentAudio = asRecord(d.current_audio);
29567
+ const currentMusic = asRecord(d.current_music);
29568
+ const audioVersions = Array.isArray(d.audio_versions) ? d.audio_versions.map(asRecord) : [];
29569
+ const musicVersions = Array.isArray(d.music_versions) ? d.music_versions.map(asRecord) : [];
29570
+ const numericVersion = (version2) => typeof version2 === "number" && Number.isFinite(version2) ? version2 : 0;
29571
+ const selectedAudioVersion = numericVersion(currentAudio.version);
29572
+ const selectedMusicVersion = numericVersion(currentMusic.version);
29573
+ const newerAudioVersions = audioVersions.filter((version2) => numericVersion(version2.version) > selectedAudioVersion);
29574
+ const newerMusicVersions = musicVersions.filter((version2) => numericVersion(version2.version) > selectedMusicVersion);
29575
+ const versionActive = (version2) => version2.status === "pending" || version2.status === "processing";
29576
+ const newestVersion = (versions2) => versions2.reduce((latest2, version2) => {
29577
+ if (!latest2)
29578
+ return version2;
29579
+ return numericVersion(version2.version) > numericVersion(latest2.version) ? version2 : latest2;
29580
+ }, null);
29581
+ const newestReplacementAudio = newestVersion(newerAudioVersions);
29582
+ const newestReplacementMusic = newestVersion(newerMusicVersions);
29583
+ const audioFailed = currentAudio.status === "failed" || currentMusic.status === "failed" || newestReplacementAudio?.status === "failed" || newestReplacementMusic?.status === "failed";
29584
+ const audioError = [
29585
+ newestReplacementAudio?.error_message,
29586
+ newestReplacementMusic?.error_message,
29587
+ currentAudio.error_message,
29588
+ currentMusic.error_message
29589
+ ].find((value) => typeof value === "string" && value.trim().length > 0);
29590
+ const audioActive = currentAudio.status === "pending" || currentAudio.status === "processing" || currentMusic.status === "pending" || currentMusic.status === "processing" || newerAudioVersions.some(versionActive) || newerMusicVersions.some(versionActive);
29591
+ const workActive = autopilotActive || batchActive || renderActive || scenarioActive || narrationActive || audioActive || activeSegments.length > 0;
29592
+ const ready = renderStatus === "completed" && Boolean(videoUrl) && renderFresh && !stale && !workActive && failedSegments.length === 0 && !audioFailed && !scenarioFailed && !scenarioApplyFailed && !narrationFailed && !batchFailed;
29593
+ const autopilotFailed = autopilot === "failed" || autopilot === "cancelled";
29594
+ const renderFailed = renderStatus === "failed";
29595
+ const failed = autopilotFailed || renderFailed || scenarioApplyFailed || scenarioFailed || narrationFailed || batchFailed || failedSegments.length > 0 || audioFailed;
29596
+ const terminal = ready || failed || batchInsufficientCredits || !workActive;
29597
+ let stage = autopilot;
29598
+ if (autopilot === "failed")
29599
+ stage = "failed";
29600
+ else if (autopilot === "cancelled")
29601
+ stage = "cancelled";
29602
+ else if (renderFailed)
29603
+ stage = "render_failed";
29604
+ else if (scenarioApplyFailed)
29605
+ stage = "scenario_apply_failed";
29606
+ else if (scenarioFailed)
29607
+ stage = "scenario_failed";
29608
+ else if (narrationFailed)
29609
+ stage = "narration_failed";
29610
+ else if (batchFailed)
29611
+ stage = "batch_failed";
29612
+ else if (failedSegments.length > 0)
29613
+ stage = "segment_failed";
29614
+ else if (audioFailed)
29615
+ stage = "audio_failed";
29616
+ else if (batchInsufficientCredits)
29617
+ stage = "insufficient_credits";
29618
+ else if (activeSegments.length > 0)
29619
+ stage = "segment_processing";
29620
+ else if (batchActive)
29621
+ stage = "segment_generation";
29622
+ else if (renderActive)
29623
+ stage = "rendering";
29624
+ else if (scenarioActive)
29625
+ stage = "scenario_processing";
29626
+ else if (narrationActive)
29627
+ stage = "narration_processing";
29628
+ else if (audioActive)
29629
+ stage = "audio_processing";
29630
+ else if (!workActive && stale)
29631
+ stage = "editing_required";
29632
+ else if (ready)
29633
+ stage = "completed";
29634
+ const segmentError = failedSegments.map((segment) => segment.error_message).find((value) => typeof value === "string" && value.length > 0);
29540
29635
  return {
29541
29636
  kind,
29542
29637
  slug,
29543
- stage: autopilot,
29638
+ stage,
29544
29639
  terminal,
29545
29640
  ready,
29546
29641
  video_url: videoUrl,
29547
- error: d.autopilot_error_message ?? null
29642
+ error: d.autopilot_error_message ?? latest.error_message ?? d.scenario_apply_error_message ?? d.scenario_error_message ?? d.narration_error_message ?? d.batch_generation_error_message ?? segmentError ?? audioError ?? (batchInsufficientCredits ? "Batch generation paused: not enough credits to finish. Top up or reduce scope, then resume." : null),
29643
+ stale,
29644
+ active_segment_ids: activeSegments.map((segment) => segment.id).filter((id) => typeof id === "number" || typeof id === "string"),
29645
+ stale_segment_ids: staleSegments.map((segment) => segment.id).filter((id) => typeof id === "number" || typeof id === "string")
29548
29646
  };
29549
29647
  }
29550
29648
  function startStateDiscriminator(kind, data) {
@@ -29574,10 +29672,10 @@ function makeVideoAutopilotKey(slug, a, startState) {
29574
29672
  return idemKey("autopilot", slug, a.prompt, a.product_subject ?? "", a.project_intent ?? "", a.language ?? "en", a.aspect ?? "", a.voice_id ?? "", a.creative_format ?? "", a.visual_language ?? "", a.theme ?? "", startState);
29575
29673
  }
29576
29674
  function editorAdCreateKey(a) {
29577
- return idemKey("create-editor", a.product_prompt ?? "", a.product_subject ?? "", a.project_intent ?? "", a.language ?? "en", a.creative_format ?? "", a.visual_language ?? "", a.theme ?? "", a.voice_id ?? "", a.export_aspect_ratio ?? "");
29675
+ return idemKey("create-editor", a.product_prompt ?? "", a.product_subject ?? "", a.project_intent ?? "", a.language ?? "en", a.creative_format ?? "", a.visual_language ?? "", a.theme ?? "", a.voice_id ?? "", a.export_aspect_ratio ?? "", a.product_image_path ?? "", a.product_image_identity ?? "", a.product_description ?? "", a.closing_image_path ?? "", a.closing_image_identity ?? "", a.logo_path ?? "", a.logo_identity ?? "", a.logo_treatment ?? "", a.logo_position ?? "", a.logo_duration_seconds === undefined ? "" : String(a.logo_duration_seconds), a.cast_mode ?? "");
29578
29676
  }
29579
29677
  function editorAdAutopilotKey(slug, a) {
29580
- return idemKey("autopilot", slug, a.product_prompt ?? "", a.product_subject ?? "", a.project_intent ?? "", a.language ?? "en", a.creative_format ?? "", a.visual_language ?? "", a.theme ?? "", a.voice_id ?? "", a.export_aspect_ratio ?? "");
29678
+ return idemKey("autopilot", slug, a.product_prompt ?? "", a.product_subject ?? "", a.project_intent ?? "", a.language ?? "en", a.creative_format ?? "", a.visual_language ?? "", a.theme ?? "", a.voice_id ?? "", a.export_aspect_ratio ?? "", a.product_image_path ?? "", a.product_description ?? "", a.closing_image_path ?? "", a.logo_path ?? "", a.logo_treatment ?? "", a.logo_position ?? "", a.logo_duration_seconds === undefined ? "" : String(a.logo_duration_seconds), a.cast_mode ?? "", a.max_credits === undefined ? "" : String(a.max_credits));
29581
29679
  }
29582
29680
  function sliderCreateKey(a) {
29583
29681
  return idemKey("create-slider", a.prompt, a.mode ?? "", a.template ?? "", a.slide_count === undefined ? "" : String(a.slide_count), a.aspect_ratio ?? "", a.accent_color ?? "", a.text_position ?? "");
@@ -29587,7 +29685,14 @@ function addSegmentKey(slug, index, nonce) {
29587
29685
  }
29588
29686
  function resolveSavePath(savePath) {
29589
29687
  const base = resolve(process.env.HUBFLUENCER_OUTPUT_DIR || process.cwd());
29590
- const target = isAbsolute(savePath) ? resolve(savePath) : resolve(base, savePath);
29688
+ let target;
29689
+ if (isAbsolute(savePath)) {
29690
+ target = resolve(savePath);
29691
+ } else {
29692
+ const workspaceCandidate = resolve(process.cwd(), savePath);
29693
+ const workspaceCandidateInsideBase = workspaceCandidate === base || workspaceCandidate.startsWith(base + sep);
29694
+ target = workspaceCandidateInsideBase ? workspaceCandidate : resolve(base, savePath);
29695
+ }
29591
29696
  if (!target.toLowerCase().endsWith(".mp4")) {
29592
29697
  throw new Error("save_path must end in .mp4");
29593
29698
  }
@@ -30027,7 +30132,7 @@ async function runCreateCampaign(client, args, log = () => {}) {
30027
30132
  items,
30028
30133
  summary,
30029
30134
  steps,
30030
- next: `get_campaign_pack({ id: ${campaignPackId} }) to review the drafts; then, for EACH draft you want to publish, generate it EXPLICITLY (a SEPARATE, PAID step): editor_ad/short → start_autopilot({ slug }) or the granular generate/render tools; carousel → generate_slider({ slug }).`,
30135
+ next: `get_campaign_pack({ id: ${campaignPackId} }) to review the drafts; then quote each editor draft with start_autopilot({ slug }) and, after approval, launch with start_autopilot({ slug, max_credits: approved_cap }); use generate_short/generate_slider for approved short/carousel drafts.`,
30031
30136
  note: `Campaign pack ${campaignPackId} created with ${summary.created} item(s), ${draftable} materialized into editable DRAFTS. ` + (positioning ? `Positioning: ${positioning}. ` : "") + "$0 so far (free AI-assist quota + 0-credit drafts). Generation/render is a separate, explicit, PAID step per draft — nothing was generated."
30032
30137
  };
30033
30138
  }
@@ -30127,7 +30232,7 @@ function readStoredCredentials() {
30127
30232
  // package.json
30128
30233
  var package_default = {
30129
30234
  name: "@hubfluencer/mcp",
30130
- version: "0.8.2",
30235
+ version: "0.9.0",
30131
30236
  description: "Model Context Protocol server for Hubfluencer — let AI agents generate post-ready shorts and editor ads.",
30132
30237
  license: "MIT",
30133
30238
  author: "Monocursive <contact@monocursive.com>",
@@ -30293,7 +30398,7 @@ class HubfluencerClient {
30293
30398
  if (e instanceof Error && (e.name === "TimeoutError" || e.name === "AbortError")) {
30294
30399
  throw new Error(`Request to ${method} ${path} timed out after ${attemptTimeoutMs}ms.`);
30295
30400
  }
30296
- throw e instanceof Error ? new Error(`Network error on ${method} ${path}: ${e.message}`) : e;
30401
+ throw e instanceof Error ? Object.assign(new Error(`Network error on ${method} ${path}: ${e.message}`), { retryable: isRetryableNetworkError(e) }) : e;
30297
30402
  }
30298
30403
  if (attempt < attempts && isRetryableStatus(res.status) && !deadlinePassed(deadline)) {
30299
30404
  await res.text().catch(() => {});
@@ -30437,6 +30542,9 @@ var getStatusOutput = exports_external.object({
30437
30542
  ready: exports_external.boolean().optional(),
30438
30543
  video_url: exports_external.union([exports_external.string(), exports_external.null()]).optional(),
30439
30544
  error: exports_external.union([exports_external.string(), exports_external.null()]).optional(),
30545
+ stale: exports_external.boolean().optional(),
30546
+ active_segment_ids: exports_external.array(exports_external.union([exports_external.number(), exports_external.string()])).optional(),
30547
+ stale_segment_ids: exports_external.array(exports_external.union([exports_external.number(), exports_external.string()])).optional(),
30440
30548
  latest_render_free: exports_external.boolean().optional(),
30441
30549
  last_free_rerender_failed: exports_external.boolean().optional()
30442
30550
  }).passthrough();
@@ -30448,6 +30556,9 @@ var waitForCompletionOutput = exports_external.object({
30448
30556
  ready: exports_external.boolean().optional(),
30449
30557
  video_url: exports_external.union([exports_external.string(), exports_external.null()]).optional(),
30450
30558
  error: exports_external.union([exports_external.string(), exports_external.null()]).optional(),
30559
+ stale: exports_external.boolean().optional(),
30560
+ active_segment_ids: exports_external.array(exports_external.union([exports_external.number(), exports_external.string()])).optional(),
30561
+ stale_segment_ids: exports_external.array(exports_external.union([exports_external.number(), exports_external.string()])).optional(),
30451
30562
  latest_render_free: exports_external.boolean().optional(),
30452
30563
  last_free_rerender_failed: exports_external.boolean().optional(),
30453
30564
  saved_to: exports_external.union([exports_external.string(), exports_external.null()]).optional(),
@@ -30511,6 +30622,11 @@ var createEditorOutput = exports_external.object({
30511
30622
  slug: exports_external.union([exports_external.string(), exports_external.null()]).optional(),
30512
30623
  kind: exports_external.string().optional(),
30513
30624
  status: projectRow.optional(),
30625
+ estimated_credits: exports_external.union([exports_external.number(), exports_external.null()]).optional(),
30626
+ available_credits: exports_external.union([exports_external.number(), exports_external.null()]).optional(),
30627
+ affordable: exports_external.boolean().optional(),
30628
+ charged: exports_external.boolean().optional(),
30629
+ note: exports_external.string().optional(),
30514
30630
  next: exports_external.string().optional()
30515
30631
  }).passthrough();
30516
30632
  var makeVideoOutput = exports_external.object({
@@ -30522,8 +30638,8 @@ var makeVideoOutput = exports_external.object({
30522
30638
  ready: exports_external.boolean().optional(),
30523
30639
  video_url: exports_external.union([exports_external.string(), exports_external.null()]).optional(),
30524
30640
  error: exports_external.union([exports_external.string(), exports_external.null()]).optional(),
30525
- estimated_credits: exports_external.unknown().optional(),
30526
- available_credits: exports_external.unknown().optional(),
30641
+ estimated_credits: exports_external.union([exports_external.number(), exports_external.null()]).optional(),
30642
+ available_credits: exports_external.union([exports_external.number(), exports_external.null()]).optional(),
30527
30643
  affordable: exports_external.boolean().optional(),
30528
30644
  charged: exports_external.boolean().optional(),
30529
30645
  saved_to: exports_external.union([exports_external.string(), exports_external.null()]).optional(),
@@ -30974,14 +31090,19 @@ function calendarScopeErrorText(status, code, message) {
30974
31090
  }
30975
31091
 
30976
31092
  // src/uploads.ts
30977
- import { createReadStream } from "node:fs";
30978
- import { open, readFile, stat } from "node:fs/promises";
31093
+ import { createHash as createHash2 } from "node:crypto";
31094
+ import { constants } from "node:fs";
31095
+ import { open, realpath, stat } from "node:fs/promises";
30979
31096
  import { basename, extname, isAbsolute as isAbsolute2, resolve as resolve2, sep as sep2 } from "node:path";
31097
+ import { Readable } from "node:stream";
30980
31098
  var sleep3 = (ms) => new Promise((r) => setTimeout(r, ms));
30981
31099
  var PART_RETRIES = 2;
30982
31100
  var ALLOW_LOOPBACK_FETCH = /^http:\/\/(localhost|127\.0\.0\.1|\[?::1\]?)/.test(process.env.HUBFLUENCER_BASE_URL || "");
30983
31101
  var MAX_VIDEO_BYTES = 500000000;
30984
31102
  var MAX_IMAGE_BYTES = 20 * 1024 * 1024;
31103
+ var MAX_PRODUCT_IMAGE_BYTES = 8 * 1024 * 1024;
31104
+ var MAX_LOGO_BYTES = 1 * 1024 * 1024;
31105
+ var MAX_CLOSING_IMAGE_BYTES = 20 * 1024 * 1024;
30985
31106
  var MULTIPART_THRESHOLD = 50 * 1024 * 1024;
30986
31107
  var MAX_CATALOG_VIDEO_DURATION_SECONDS = 60;
30987
31108
  var VIDEO_EXT_MIME = {
@@ -31005,6 +31126,53 @@ var CATALOG_ASSET_EXTS = Object.keys(CATALOG_EXT_MIME);
31005
31126
  function catalogMaxBytes(mime) {
31006
31127
  return mime.startsWith("video/") ? MAX_VIDEO_BYTES : MAX_IMAGE_BYTES;
31007
31128
  }
31129
+ function preparedUploadIdentity(file) {
31130
+ if (!file.bytes) {
31131
+ throw new Error("Prepared upload has no retained byte snapshot.");
31132
+ }
31133
+ return `${file.size}:${createHash2("sha256").update(file.bytes).digest("hex")}`;
31134
+ }
31135
+ async function fillPositionalRead(handle, buffer, offset, length, position) {
31136
+ let filled = 0;
31137
+ while (filled < length) {
31138
+ const { bytesRead } = await handle.read(buffer, offset + filled, length - filled, position + filled);
31139
+ if (bytesRead === 0)
31140
+ break;
31141
+ filled += bytesRead;
31142
+ }
31143
+ return filled;
31144
+ }
31145
+ async function closeReadHandle(handle) {
31146
+ await handle.close();
31147
+ }
31148
+ async function readValidatedBytes(file) {
31149
+ const buffer = Buffer.allocUnsafe(file.size);
31150
+ let offset = 0;
31151
+ while (offset < file.size) {
31152
+ const { bytesRead } = await file.handle.read(buffer, offset, file.size - offset, offset);
31153
+ if (bytesRead === 0) {
31154
+ throw new Error(`Short read: got ${offset} of ${file.size} validated bytes (file changed under us?).`);
31155
+ }
31156
+ offset += bytesRead;
31157
+ }
31158
+ return buffer;
31159
+ }
31160
+ function validatedByteStream(file) {
31161
+ return Readable.from(async function* () {
31162
+ const chunkSize = 1024 * 1024;
31163
+ let offset = 0;
31164
+ while (offset < file.size) {
31165
+ const length = Math.min(chunkSize, file.size - offset);
31166
+ const chunk = Buffer.allocUnsafe(length);
31167
+ const filled = await fillPositionalRead(file.handle, chunk, 0, length, offset);
31168
+ if (filled !== length) {
31169
+ throw new Error(`Short stream read: got ${filled} of ${length} bytes at offset ${offset} (file changed under us?).`);
31170
+ }
31171
+ offset += filled;
31172
+ yield chunk;
31173
+ }
31174
+ }());
31175
+ }
31008
31176
  function planMultipartParts(size, partSize) {
31009
31177
  if (!Number.isFinite(size) || size <= 0) {
31010
31178
  throw new Error(`size must be a positive number, got ${size}.`);
@@ -31027,14 +31195,29 @@ function assertFullRead(bytesRead, len, partNumber, offset) {
31027
31195
  throw new Error(`Short read on part ${partNumber}: got ${bytesRead} of ${len} bytes at offset ${offset} (file changed under us?).`);
31028
31196
  }
31029
31197
  }
31030
- async function resolveReadPath(filePath, extToMime, maxBytes) {
31198
+ async function openReadPath(filePath, extToMime, maxBytes) {
31031
31199
  if (!filePath || typeof filePath !== "string") {
31032
31200
  throw new Error("file_path is required.");
31033
31201
  }
31034
- const base = resolve2(process.env.HUBFLUENCER_INPUT_DIR || process.cwd());
31035
- const target = isAbsolute2(filePath) ? resolve2(filePath) : resolve2(base, filePath);
31202
+ const configuredBase = resolve2(process.env.HUBFLUENCER_INPUT_DIR || process.cwd());
31203
+ let base;
31204
+ try {
31205
+ base = await realpath(configuredBase);
31206
+ } catch (e) {
31207
+ throw new Error(`Cannot resolve input directory ${configuredBase}: ${e instanceof Error ? e.message : String(e)}`);
31208
+ }
31209
+ const requested = isAbsolute2(filePath) ? resolve2(filePath) : resolve2(configuredBase, filePath);
31210
+ if (requested !== configuredBase && !requested.startsWith(configuredBase + sep2)) {
31211
+ throw new Error(`file_path must be inside ${base} (set HUBFLUENCER_INPUT_DIR to change). Refusing to read ${requested}.`);
31212
+ }
31213
+ let target;
31214
+ try {
31215
+ target = await realpath(requested);
31216
+ } catch (e) {
31217
+ throw new Error(`Cannot read ${requested}: ${e instanceof Error ? e.message : String(e)}`);
31218
+ }
31036
31219
  if (target !== base && !target.startsWith(base + sep2)) {
31037
- throw new Error(`file_path must be inside ${base} (set HUBFLUENCER_INPUT_DIR to change). Refusing to read ${target}.`);
31220
+ throw new Error(`file_path must resolve inside ${base} (set HUBFLUENCER_INPUT_DIR to change). Refusing to read ${target}.`);
31038
31221
  }
31039
31222
  const ext = extname(target).slice(1).toLowerCase();
31040
31223
  const mime = extToMime[ext];
@@ -31042,21 +31225,57 @@ async function resolveReadPath(filePath, extToMime, maxBytes) {
31042
31225
  const allowed = Object.keys(extToMime).map((e) => `.${e}`).join(", ");
31043
31226
  throw new Error(`Unsupported file type ".${ext}". Allowed: ${allowed}.`);
31044
31227
  }
31045
- let size;
31228
+ let handle;
31046
31229
  try {
31047
- const st = await stat(target);
31230
+ handle = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
31231
+ const [openedStat, targetStat, currentTarget] = await Promise.all([
31232
+ handle.stat(),
31233
+ stat(target),
31234
+ realpath(requested)
31235
+ ]);
31236
+ if (currentTarget !== target)
31237
+ throw new Error("path changed while opening");
31238
+ const st = openedStat;
31048
31239
  if (!st.isFile())
31049
31240
  throw new Error("not a regular file");
31050
- size = st.size;
31241
+ if (st.dev !== targetStat.dev || st.ino !== targetStat.ino) {
31242
+ throw new Error("opened file does not match the validated target");
31243
+ }
31244
+ if (st.size <= 0)
31245
+ throw new Error(`${target} is empty.`);
31246
+ if (st.size > maxBytes) {
31247
+ throw new Error(`${target} is ${st.size} bytes — over the ${maxBytes}-byte cap for this asset type.`);
31248
+ }
31249
+ return { path: target, ext, mime, size: st.size, handle };
31051
31250
  } catch (e) {
31251
+ if (handle)
31252
+ await closeReadHandle(handle).catch(() => {
31253
+ return;
31254
+ });
31052
31255
  throw new Error(`Cannot read ${target}: ${e instanceof Error ? e.message : String(e)}`);
31053
31256
  }
31054
- if (size <= 0)
31055
- throw new Error(`${target} is empty.`);
31056
- if (size > maxBytes) {
31057
- throw new Error(`${target} is ${size} bytes — over the ${maxBytes}-byte cap for this asset type.`);
31257
+ }
31258
+ async function prepareImageUpload(filePath, maxBytes = MAX_IMAGE_BYTES) {
31259
+ const file = await openReadPath(filePath, IMAGE_EXT_MIME, maxBytes);
31260
+ try {
31261
+ file.bytes = await readValidatedBytes(file);
31262
+ return file;
31263
+ } catch (error2) {
31264
+ await closeReadHandle(file.handle);
31265
+ throw error2;
31266
+ }
31267
+ }
31268
+ function closePreparedUploadFile(file) {
31269
+ return closeReadHandle(file.handle);
31270
+ }
31271
+ async function resolveReadPath(filePath, extToMime, maxBytes) {
31272
+ const file = await openReadPath(filePath, extToMime, maxBytes);
31273
+ try {
31274
+ const { handle: _, ...resolved } = file;
31275
+ return resolved;
31276
+ } finally {
31277
+ await closeReadHandle(file.handle);
31058
31278
  }
31059
- return { path: target, ext, mime, size };
31060
31279
  }
31061
31280
  async function resolveVideoReadPath(filePath) {
31062
31281
  return resolveReadPath(filePath, VIDEO_EXT_MIME, MAX_VIDEO_BYTES);
@@ -31073,7 +31292,7 @@ async function putToPresignedUrl(url, body, contentType, timeoutMs = 300000, con
31073
31292
  fetchBody = body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength);
31074
31293
  fetchInit = { method: "PUT", headers, body: fetchBody };
31075
31294
  } else {
31076
- stream = createReadStream(body.filePath);
31295
+ stream = validatedByteStream(body);
31077
31296
  headers["content-length"] = String(contentLength ?? body.size);
31078
31297
  fetchInit = {
31079
31298
  method: "PUT",
@@ -31083,19 +31302,35 @@ async function putToPresignedUrl(url, body, contentType, timeoutMs = 300000, con
31083
31302
  };
31084
31303
  }
31085
31304
  fetchInit.signal = AbortSignal.timeout(timeoutMs);
31305
+ const closeStream = async () => {
31306
+ if (!stream || stream.closed)
31307
+ return;
31308
+ await new Promise((resolve3, reject) => {
31309
+ stream?.once("close", resolve3);
31310
+ stream?.once("error", reject);
31311
+ stream?.destroy();
31312
+ });
31313
+ };
31086
31314
  let resp;
31087
31315
  try {
31088
31316
  resp = await fetch(url, fetchInit);
31089
31317
  } catch (e) {
31090
- stream?.destroy();
31318
+ await closeStream().catch(() => {
31319
+ return;
31320
+ });
31091
31321
  if (e instanceof Error && (e.name === "TimeoutError" || e.name === "AbortError")) {
31092
31322
  throw markRetryable(`Upload PUT timed out after ${timeoutMs / 1000}s.`);
31093
31323
  }
31094
31324
  throw e instanceof Error ? markRetryable(`Upload PUT failed: ${e.message}`) : e;
31095
31325
  }
31326
+ await closeStream();
31096
31327
  if (!resp.ok) {
31097
31328
  const text = await resp.text().catch(() => "");
31098
- throw new Error(`Upload PUT rejected (HTTP ${resp.status})${text ? `: ${text.slice(0, 200)}` : ""}.`);
31329
+ const error2 = new Error(`Upload PUT rejected (HTTP ${resp.status})${text ? `: ${text.slice(0, 200)}` : ""}.`);
31330
+ if (isRetryableStatus(resp.status)) {
31331
+ Object.assign(error2, { retryable: true });
31332
+ }
31333
+ throw error2;
31099
31334
  }
31100
31335
  return resp.headers.get("etag") ?? undefined;
31101
31336
  }
@@ -31103,31 +31338,35 @@ function markRetryable(message) {
31103
31338
  return Object.assign(new Error(message), { retryable: true });
31104
31339
  }
31105
31340
  async function uploadVideoFile(client, slug, filePath, opts = {}) {
31106
- const file = await resolveReadPath(filePath, VIDEO_EXT_MIME, MAX_VIDEO_BYTES);
31341
+ const file = await openReadPath(filePath, VIDEO_EXT_MIME, MAX_VIDEO_BYTES);
31107
31342
  const filename = basename(file.path);
31108
31343
  const fit_mode = opts.fitMode === "cover" ? "cover" : undefined;
31109
31344
  const product_description = opts.productDescription;
31110
- if (file.size >= MULTIPART_THRESHOLD) {
31111
- return uploadVideoMultipart(client, slug, file, {
31345
+ try {
31346
+ if (file.size >= MULTIPART_THRESHOLD) {
31347
+ return await uploadVideoMultipart(client, slug, file, {
31348
+ filename,
31349
+ fit_mode,
31350
+ product_description
31351
+ }, opts.onProgress);
31352
+ }
31353
+ const buf = await readValidatedBytes(file);
31354
+ const presign = await client.post(`/editor/${slug}/uploads/presign`, {
31112
31355
  filename,
31356
+ mime_type: file.mime,
31357
+ size_bytes: file.size,
31113
31358
  fit_mode,
31114
31359
  product_description
31115
- }, opts.onProgress);
31360
+ });
31361
+ const { upload_id, presigned_url } = presign.data;
31362
+ await opts.onProgress?.(0, 1, `uploading ${filename}`);
31363
+ await putToPresignedUrl(presigned_url, buf, file.mime);
31364
+ await opts.onProgress?.(1, 1, `uploaded ${filename}, confirming`);
31365
+ const confirmed = await client.post(`/editor/${slug}/uploads/${upload_id}/confirm`);
31366
+ return { upload_id, status: confirmed.data?.status ?? "processing" };
31367
+ } finally {
31368
+ await closeReadHandle(file.handle);
31116
31369
  }
31117
- const presign = await client.post(`/editor/${slug}/uploads/presign`, {
31118
- filename,
31119
- mime_type: file.mime,
31120
- size_bytes: file.size,
31121
- fit_mode,
31122
- product_description
31123
- });
31124
- const { upload_id, presigned_url } = presign.data;
31125
- const buf = await readFile(file.path);
31126
- await opts.onProgress?.(0, 1, `uploading ${filename}`);
31127
- await putToPresignedUrl(presigned_url, buf, file.mime);
31128
- await opts.onProgress?.(1, 1, `uploaded ${filename}, confirming`);
31129
- const confirmed = await client.post(`/editor/${slug}/uploads/${upload_id}/confirm`);
31130
- return { upload_id, status: confirmed.data?.status ?? "processing" };
31131
31370
  }
31132
31371
  async function uploadPartWithRetry(client, slug, ids, part_number, chunk) {
31133
31372
  for (let attempt = 1;; attempt++) {
@@ -31143,7 +31382,8 @@ async function uploadPartWithRetry(client, slug, ids, part_number, chunk) {
31143
31382
  }
31144
31383
  return etag;
31145
31384
  } catch (e) {
31146
- if (attempt <= PART_RETRIES && isRetryableNetworkError(e)) {
31385
+ const status = e?.status;
31386
+ if (attempt <= PART_RETRIES && (isRetryableNetworkError(e) || typeof status === "number" && isRetryableStatus(status))) {
31147
31387
  await sleep3(backoffDelayMs(attempt, DEFAULT_RETRY));
31148
31388
  continue;
31149
31389
  }
@@ -31160,18 +31400,17 @@ async function uploadVideoMultipart(client, slug, file, meta2, onProgress) {
31160
31400
  product_description: meta2.product_description
31161
31401
  });
31162
31402
  const { upload_id, s3_upload_id, parts_count, part_size } = init.data;
31163
- const plan = planMultipartParts(file.size, part_size);
31164
- if (plan.length !== parts_count) {
31165
- throw new Error(`Multipart plan mismatch: server expects ${parts_count} parts, computed ${plan.length} for ${file.size} bytes at ${part_size}/part.`);
31166
- }
31167
- await onProgress?.(0, plan.length, `uploading ${meta2.filename} in ${plan.length} parts`);
31168
- const fh = await open(file.path, "r");
31169
- const parts = [];
31170
31403
  try {
31404
+ const plan = planMultipartParts(file.size, part_size);
31405
+ if (plan.length !== parts_count) {
31406
+ throw new Error(`Multipart plan mismatch: server expects ${parts_count} parts, computed ${plan.length} for ${file.size} bytes at ${part_size}/part.`);
31407
+ }
31408
+ await onProgress?.(0, plan.length, `uploading ${meta2.filename} in ${plan.length} parts`);
31409
+ const parts = [];
31171
31410
  for (const { part_number, offset, len } of plan) {
31172
31411
  const chunk = Buffer.alloc(len);
31173
- const { bytesRead } = await fh.read(chunk, 0, len, offset);
31174
- assertFullRead(bytesRead, len, part_number, offset);
31412
+ const filled = await fillPositionalRead(file.handle, chunk, 0, len, offset);
31413
+ assertFullRead(filled, len, part_number, offset);
31175
31414
  const etag = await uploadPartWithRetry(client, slug, { upload_id, s3_upload_id }, part_number, chunk);
31176
31415
  parts.push({ part_number, etag });
31177
31416
  await onProgress?.(part_number, plan.length, `uploaded part ${part_number}/${plan.length}`);
@@ -31186,73 +31425,95 @@ async function uploadVideoMultipart(client, slug, file, meta2, onProgress) {
31186
31425
  });
31187
31426
  } catch {}
31188
31427
  throw e;
31189
- } finally {
31190
- await fh.close();
31191
31428
  }
31192
31429
  }
31193
31430
  async function uploadImageFile(client, presignPath, filePath, maxBytes = MAX_IMAGE_BYTES) {
31194
- const file = await resolveReadPath(filePath, IMAGE_EXT_MIME, maxBytes);
31195
- const presign = await client.post(presignPath, {
31196
- mime_type: file.mime,
31197
- size_bytes: file.size
31198
- });
31199
- const { presigned_url, s3_key } = presign.data;
31200
- const buf = await readFile(file.path);
31201
- await putToPresignedUrl(presigned_url, buf, file.mime);
31202
- return { s3_key };
31431
+ const ownsFile = typeof filePath === "string";
31432
+ const file = ownsFile ? await openReadPath(filePath, IMAGE_EXT_MIME, maxBytes) : filePath;
31433
+ try {
31434
+ const buf = file.bytes ?? await readValidatedBytes(file);
31435
+ const presign = await client.post(presignPath, {
31436
+ mime_type: file.mime,
31437
+ size_bytes: file.size
31438
+ });
31439
+ const { presigned_url, s3_key } = presign.data;
31440
+ await putToPresignedUrl(presigned_url, buf, file.mime);
31441
+ return { s3_key };
31442
+ } finally {
31443
+ if (ownsFile)
31444
+ await closeReadHandle(file.handle);
31445
+ }
31203
31446
  }
31204
31447
  async function uploadShortPoster(client, slug, filePath) {
31205
- const file = await resolveReadPath(filePath, IMAGE_EXT_MIME, MAX_IMAGE_BYTES);
31206
- const presign = await client.post(`/shorts/${slug}/poster/presign`, { content_type: file.mime });
31207
- const { upload_url, s3_key } = presign;
31208
- const buf = await readFile(file.path);
31209
- await putToPresignedUrl(upload_url, buf, file.mime);
31210
- return { s3_key };
31448
+ const file = await openReadPath(filePath, IMAGE_EXT_MIME, MAX_IMAGE_BYTES);
31449
+ try {
31450
+ const buf = await readValidatedBytes(file);
31451
+ const presign = await client.post(`/shorts/${slug}/poster/presign`, { content_type: file.mime });
31452
+ const { upload_url, s3_key } = presign;
31453
+ await putToPresignedUrl(upload_url, buf, file.mime);
31454
+ return { s3_key };
31455
+ } finally {
31456
+ await closeReadHandle(file.handle);
31457
+ }
31211
31458
  }
31212
31459
  async function uploadCatalogAsset(client, filePath, opts = {}) {
31213
- const file = await resolveReadPath(filePath, CATALOG_EXT_MIME, MAX_VIDEO_BYTES);
31214
- const cap = catalogMaxBytes(file.mime);
31215
- if (file.size > cap) {
31216
- throw new Error(`${file.path} is ${file.size} bytes — over the ${cap}-byte cap for ${file.mime} catalog uploads.`);
31217
- }
31218
- if (file.mime.startsWith("video/")) {
31219
- const duration3 = opts.durationSeconds;
31220
- if (typeof duration3 !== "number" || !Number.isFinite(duration3) || duration3 <= 0 || duration3 > MAX_CATALOG_VIDEO_DURATION_SECONDS) {
31221
- throw new Error(`Catalog video uploads require durationSeconds to be greater than 0 and no more than ${MAX_CATALOG_VIDEO_DURATION_SECONDS} seconds.`);
31460
+ const file = await openReadPath(filePath, CATALOG_EXT_MIME, MAX_VIDEO_BYTES);
31461
+ try {
31462
+ const cap = catalogMaxBytes(file.mime);
31463
+ if (file.size > cap) {
31464
+ throw new Error(`${file.path} is ${file.size} bytes — over the ${cap}-byte cap for ${file.mime} catalog uploads.`);
31222
31465
  }
31466
+ if (file.mime.startsWith("video/")) {
31467
+ const duration3 = opts.durationSeconds;
31468
+ if (typeof duration3 !== "number" || !Number.isFinite(duration3) || duration3 <= 0 || duration3 > MAX_CATALOG_VIDEO_DURATION_SECONDS) {
31469
+ throw new Error(`Catalog video uploads require durationSeconds to be greater than 0 and no more than ${MAX_CATALOG_VIDEO_DURATION_SECONDS} seconds.`);
31470
+ }
31471
+ }
31472
+ const bufferedBytes = file.size < MULTIPART_THRESHOLD ? await readValidatedBytes(file) : undefined;
31473
+ const filename = basename(file.path);
31474
+ const presign = await client.post("/assets/presign", {
31475
+ filename,
31476
+ mime_type: file.mime,
31477
+ size_bytes: file.size
31478
+ });
31479
+ const { asset_id, presigned_url } = presign.data;
31480
+ if (file.size >= MULTIPART_THRESHOLD) {
31481
+ for (let attempt = 1;; attempt++) {
31482
+ try {
31483
+ await putToPresignedUrl(presigned_url, { handle: file.handle, size: file.size }, file.mime, 300000, file.size);
31484
+ break;
31485
+ } catch (error2) {
31486
+ if (attempt >= DEFAULT_RETRY.attempts || !isRetryableNetworkError(error2)) {
31487
+ throw error2;
31488
+ }
31489
+ await sleep3(backoffDelayMs(attempt, DEFAULT_RETRY));
31490
+ }
31491
+ }
31492
+ } else {
31493
+ await putToPresignedUrl(presigned_url, bufferedBytes, file.mime);
31494
+ }
31495
+ const confirmBody = {};
31496
+ if (typeof opts.description === "string" && opts.description.trim() !== "")
31497
+ confirmBody.description = opts.description;
31498
+ if (typeof opts.width === "number")
31499
+ confirmBody.width = opts.width;
31500
+ if (typeof opts.height === "number")
31501
+ confirmBody.height = opts.height;
31502
+ if (typeof opts.durationSeconds === "number")
31503
+ confirmBody.duration_seconds = opts.durationSeconds;
31504
+ const confirmed = await client.post(`/assets/${asset_id}/confirm`, confirmBody);
31505
+ const data = confirmed.data ?? {};
31506
+ return {
31507
+ asset_id,
31508
+ status: typeof data.status === "string" ? data.status : "ready",
31509
+ media_type: typeof data.media_type === "string" ? data.media_type : "",
31510
+ mime_type: typeof data.mime_type === "string" ? data.mime_type : file.mime,
31511
+ filename: typeof data.filename === "string" ? data.filename : filename,
31512
+ size_bytes: typeof data.size_bytes === "number" ? data.size_bytes : file.size
31513
+ };
31514
+ } finally {
31515
+ await closeReadHandle(file.handle);
31223
31516
  }
31224
- const filename = basename(file.path);
31225
- const presign = await client.post("/assets/presign", {
31226
- filename,
31227
- mime_type: file.mime,
31228
- size_bytes: file.size
31229
- });
31230
- const { asset_id, presigned_url } = presign.data;
31231
- if (file.size >= MULTIPART_THRESHOLD) {
31232
- await putToPresignedUrl(presigned_url, { filePath: file.path, size: file.size }, file.mime, 300000, file.size);
31233
- } else {
31234
- const buf = await readFile(file.path);
31235
- await putToPresignedUrl(presigned_url, buf, file.mime);
31236
- }
31237
- const confirmBody = {};
31238
- if (typeof opts.description === "string" && opts.description.trim() !== "")
31239
- confirmBody.description = opts.description;
31240
- if (typeof opts.width === "number")
31241
- confirmBody.width = opts.width;
31242
- if (typeof opts.height === "number")
31243
- confirmBody.height = opts.height;
31244
- if (typeof opts.durationSeconds === "number")
31245
- confirmBody.duration_seconds = opts.durationSeconds;
31246
- const confirmed = await client.post(`/assets/${asset_id}/confirm`, confirmBody);
31247
- const data = confirmed.data ?? {};
31248
- return {
31249
- asset_id,
31250
- status: typeof data.status === "string" ? data.status : "ready",
31251
- media_type: typeof data.media_type === "string" ? data.media_type : "",
31252
- mime_type: typeof data.mime_type === "string" ? data.mime_type : file.mime,
31253
- filename: typeof data.filename === "string" ? data.filename : filename,
31254
- size_bytes: typeof data.size_bytes === "number" ? data.size_bytes : file.size
31255
- };
31256
31517
  }
31257
31518
 
31258
31519
  // src/index.ts
@@ -31261,6 +31522,37 @@ async function fetchStatus(client, kind, slug, deadline) {
31261
31522
  const res = await client.get(path, undefined, deadline);
31262
31523
  return normalizeStatus(kind, slug, asRecord(res).data);
31263
31524
  }
31525
+ async function editorAutopilotQuote(client, slug, overrides = {}) {
31526
+ try {
31527
+ const params = new URLSearchParams;
31528
+ if (overrides.language)
31529
+ params.set("language", overrides.language);
31530
+ if (overrides.product_subject)
31531
+ params.set("product_subject", overrides.product_subject);
31532
+ if (overrides.product_prompt)
31533
+ params.set("product_prompt", overrides.product_prompt);
31534
+ const query = params.toString();
31535
+ const response = await client.get(`/editor/${slug}/autopilot/cost${query ? `?${query}` : ""}`);
31536
+ const cost = asRecord(asRecord(response).data);
31537
+ const estimated_credits = typeof cost.total === "number" ? cost.total : null;
31538
+ const available_credits = typeof cost.available_credits === "number" ? cost.available_credits : null;
31539
+ return {
31540
+ estimated_credits,
31541
+ available_credits,
31542
+ affordable: estimated_credits !== null && available_credits !== null && available_credits >= estimated_credits
31543
+ };
31544
+ } catch (error2) {
31545
+ const apiError = error2;
31546
+ if (typeof apiError.status === "number" && apiError.status >= 400 && apiError.status < 500 && apiError.status !== 429) {
31547
+ throw error2;
31548
+ }
31549
+ return {
31550
+ estimated_credits: null,
31551
+ available_credits: null,
31552
+ affordable: false
31553
+ };
31554
+ }
31555
+ }
31264
31556
  function isRecompositeInProgressConflict(e) {
31265
31557
  const err = e;
31266
31558
  if (err?.status !== 409)
@@ -31466,14 +31758,14 @@ var WRITE = {
31466
31758
  var SERVER_INSTRUCTIONS = `Hubfluencer turns a prompt — or a whole product page — into finished, post-ready vertical videos and image carousels, and can run the surrounding content operation (plan → draft → review → schedule → measure → repeat).
31467
31759
 
31468
31760
  MAKE ONE ASSET (simplest)
31469
- - make_video({ prompt }) creates, generates, and returns a finished MP4 — it picks a single-clip short or a multi-scene editor ad from the prompt (override with kind:"short"|"editor"). create_short / create_editor_ad are the per-product one-shots; create_slider makes an image carousel; create_tracking_video burns a CV overlay onto a local clip.
31761
+ - make_video({ prompt }) creates, generates, and returns a finished MP4 — it picks a single-clip short or a multi-scene editor ad from the prompt (override with kind:"short"|"editor"). create_editor_ad creates/configures/prices an editor and launches only with max_credits; create_short creates a short draft; create_slider makes an image carousel; create_tracking_video burns a CV overlay onto a local clip.
31470
31762
  - Granular (full control): create a draft, then drive the pipeline step by step (create_editor_draft → generate_scenario → apply_scenario → review/edit prompts (set_segment_prompt) → generate_segment(s) → generate_voice + generate_music → render; regenerate_segment re-rolls a completed scene as a new version). Poll with get_status / wait_for_completion; fetch with download_result (a slider has no MP4 — read its slides with get_slider).
31471
31763
 
31472
31764
  DELEGATE THE CONTENT OPERATION (the full loop — steps 1-3 are $0)
31473
31765
  1. ONBOARD a product: extract_product_page(url) pulls facts + imagery (SSRF-hardened, 0cr); import_product_image saves its picture/logo. Persist identity once with create_product_profile + create_brand_profile so every later draft inherits it instead of re-describing the brand.
31474
31766
  2. PLAN ($0, free quota — not credits): plan_campaign proposes angles/formats + a per-item credit estimate; generate_hook_variations writes hook options. create_campaign(url | product_profile_id) does 1-2 end-to-end and returns a pack of editable DRAFTS.
31475
31767
  3. PACK & MATERIALIZE ($0): create_campaign_pack / add_pack_variations assemble items; materialize_pack_item turns each into a 0-credit draft (editor_ad/short → a video project, carousel → a slider). list_campaign_packs lists packs; get_campaign_pack({ id }) shows every item's draft slug + credit estimate.
31476
- 4. GENERATE per draft (CREDITS — a separate, explicit step): run start_autopilot/generate_short/generate_slider on each draft slug. Nothing above this line spends video credits.
31768
+ 4. GENERATE per draft (CREDITS — a separate, explicit step): start_autopilot({slug}) quotes free; after approval, start_autopilot({slug,max_credits:approved_cap}) launches. Run generate_short/generate_slider for approved short/carousel drafts. Nothing above this line spends video credits.
31477
31769
  5. REVIEW: create_review_link mints a no-login page where a human approves/comments (list_review_links / revoke_review_link manage them). Gate spend or posting on approval.
31478
31770
  6. CALENDAR (reminder-only): schedule_post / list_scheduled_posts / reschedule_post / cancel_scheduled_post stage a calendar that pushes REMINDERS to the user — it does NOT auto-publish (posting to TikTok/IG stays a human step in the app). After the user posts the presigned export, call mark_scheduled_posted.
31479
31771
  7. MEASURE → DOUBLE DOWN: record_performance logs views/engagement (tag creatives via set_item_attributes); get_recommendations gives a CAUTIOUS, non-causal read of your own best hook/format (present its confidence + note as-is, never upgrade them); make_more_like_winner spins fresh hooks from a proven item — feed a winner back into add_pack_variations → step 4.
@@ -31481,11 +31773,11 @@ DELEGATE THE CONTENT OPERATION (the full loop — steps 1-3 are $0)
31481
31773
 
31482
31774
  CREDITS (spent server-side; each tool prices before charging — see its description)
31483
31775
  - Free (0 credits): every draft create/edit, reorder, all slider re-composites, short re-renders (rerender_short — applies text/style/CTA/end-card edits over a short's already-paid footage), and the whole onboard/plan/pack/materialize path (steps 1-3). get_credits shows the balance.
31484
- - Charged: short render 15; editor AI scene 5 (4 in a batch of ≥3); voice 3; music 5; editor render 0 (auto-charges ungenerated scenes); slider 1/slide; tracking render 1 (refunded on failure). make_video/create_* report the estimate first — pass dry_run to preview, max_credits to cap.
31776
+ - Charged: short render 15; editor AI scene 5 (4 in a batch of ≥3); voice 3; music 5; editor render 0 (auto-charges ungenerated scenes); slider 1/slide; tracking render 1 (refunded on failure). make_video supports dry_run/max_credits; create_editor_ad/start_autopilot require max_credits before launching.
31485
31777
  - AI ASSISTS (all generate_*/enhance/suggest/plan/hook tools) draw a FREE daily quota (20/day), NOT credits. On 429, set auto_unlock:true to spend 1 credit for +10 assists (retried once), or write the copy yourself and use the set_* tools.
31486
31778
 
31487
31779
  WAITING & RESUMING
31488
- - Renders run async and can take minutes. wait_for_completion polls a budget capped at 280s; if it returns terminal=false / timed_out, just CALL IT AGAIN with the same slug. make_video returns the slug + a resume hint on timeout.
31780
+ - Renders run async and can take minutes. wait_for_completion polls a budget capped at 280s; if it returns terminal=false / timed_out, just CALL IT AGAIN with the same slug. make_video returns the slug + a resume hint on timeout. A terminal result is not always ready: an editor can go terminal in a needs-action stage (editing_required = stale after edits, regenerate the flagged scenes/audio; insufficient_credits = batch parked, top up / reduce scope; idle = draft with nothing generating, start generation first) — act on those instead of re-polling.
31489
31781
  - Creates and charged actions are idempotency-keyed: a transport retry is safe; a genuine re-run after a terminal FAILURE restarts rather than replaying the dead attempt.
31490
31782
 
31491
31783
  LOCAL FILES (sandboxed)
@@ -31573,7 +31865,7 @@ registerTool("make_video", {
31573
31865
  save_path: exports_external.string().optional().describe("Optional .mp4 path to download to (confined to HUBFLUENCER_OUTPUT_DIR or cwd)"),
31574
31866
  max_wait_seconds: exports_external.number().optional().describe("Block budget seconds (default 240, capped 10–280)"),
31575
31867
  dry_run: exports_external.boolean().optional().describe("Preview only: create a free draft, price it, and STOP before spending credits. " + "Returns {estimated_credits, available_credits, slug}. Resume with generate_short / start_autopilot."),
31576
- max_credits: exports_external.number().optional().describe("Spend cap: refuse to start (no charge) if the priced estimate exceeds this. Returns the estimate.")
31868
+ max_credits: exports_external.number().int().nonnegative().optional().describe("Spend cap: refuse to start (no charge) if the priced estimate exceeds this. Returns the estimate.")
31577
31869
  },
31578
31870
  outputSchema: makeVideoOutput,
31579
31871
  annotations: { title: "Make a video", ...WRITE, idempotentHint: false }
@@ -31660,11 +31952,12 @@ registerTool("make_video", {
31660
31952
  estimated_credits = typeof cost.total === "number" ? cost.total : null;
31661
31953
  available_credits = typeof cost.available_credits === "number" ? cost.available_credits : null;
31662
31954
  } catch {}
31663
- const resume = kind === "short" ? `generate_short({ slug: "${slug}"${args.skip_auto_text ? ", skip_auto_text: true" : ""} })` : `start_autopilot({ slug: "${slug}" })`;
31955
+ const resume = kind === "short" ? `generate_short({ slug: "${slug}"${args.skip_auto_text ? ", skip_auto_text: true" : ""} })` : `start_autopilot({ slug: "${slug}", max_credits: ${estimated_credits ?? "<approved cap>"} })`;
31664
31956
  const affordable = available_credits === null || estimated_credits === null || available_credits >= estimated_credits;
31665
31957
  const overCap = args.max_credits != null && estimated_credits != null && estimated_credits > args.max_credits;
31666
- if (args.dry_run || overCap || !affordable) {
31667
- const note = args.dry_run ? `Dry run — created a free draft and priced it (${estimated_credits ?? "?"} credits, have ${available_credits ?? "?"}). To run it: ${resume}.` : overCap ? `Estimated ${estimated_credits} credits exceeds max_credits ${args.max_credits}; nothing charged. Raise max_credits, or run ${resume}.` : `Not enough credits (needs ${estimated_credits ?? "?"}, have ${available_credits ?? "?"}); nothing charged. Top up, then run ${resume}.`;
31958
+ const editorPriceUnavailableWithoutCap = kind === "editor" && estimated_credits === null && args.max_credits == null;
31959
+ if (args.dry_run || editorPriceUnavailableWithoutCap || overCap || !affordable) {
31960
+ const note = args.dry_run ? `Dry run — created a free draft and priced it (${estimated_credits ?? "?"} credits, have ${available_credits ?? "?"}). To run it: ${resume}.` : editorPriceUnavailableWithoutCap ? `Pricing is temporarily unavailable, so the editor was left as a free draft and nothing was charged. Retry the quote, then run start_autopilot({ slug: "${slug}", max_credits: <approved cap> }).` : overCap ? `Estimated ${estimated_credits} credits exceeds max_credits ${args.max_credits}; nothing charged. Raise max_credits, or run ${resume}.` : `Not enough credits (needs ${estimated_credits ?? "?"}, have ${available_credits ?? "?"}); nothing charged. Top up, then run ${resume}.`;
31668
31961
  return ok({
31669
31962
  slug,
31670
31963
  kind,
@@ -31684,7 +31977,11 @@ registerTool("make_video", {
31684
31977
  if (kind === "short") {
31685
31978
  await client.post(`/shorts/${slug}/generate`, args.skip_auto_text ? { skip_auto_text: true } : undefined, `gen-short:${slug}:${startState}${args.skip_auto_text ? ":bare" : ""}`);
31686
31979
  } else {
31687
- await client.post(`/editor/${slug}/autopilot`, undefined, makeVideoAutopilotKey(slug, args, startState));
31980
+ const approvedCap = args.max_credits ?? estimated_credits;
31981
+ if (approvedCap === null) {
31982
+ throw new Error("Editor autopilot launch requires max_credits or a live quote");
31983
+ }
31984
+ await client.post(`/editor/${slug}/autopilot`, { max_credits: approvedCap }, makeVideoAutopilotKey(slug, args, startState));
31688
31985
  }
31689
31986
  await reportProgress(extra, 0, `started ${kind} ${slug}`);
31690
31987
  const status = await pollToTerminal(client, kind, slug, extra, budgetMs, 15000);
@@ -32133,7 +32430,7 @@ registerTool("generate_short", {
32133
32430
  }));
32134
32431
  registerTool("rerender_short", {
32135
32432
  title: "Re-render a short (FREE — 0 credits)",
32136
- description: "FREE re-render: applies the short's current text/style/CTA/end-card state over the already-paid " + "footage and music — 0 credits. Use after update_short for copy/style/CTA tweaks. Footage or music " + "changes need generate_short (15 credits) instead. Edits that add/remove the end card (poster, " + "end_card) can shift the video between 12s and 14s; the pinned music bed is faded to fit rather than " + "regenerated for perfectly synced music after such a change, use generate_short. " + "Requires a completed generation to re-render over " + "(422 short_not_ready otherwise — run generate_short once first); while any generation/render is in " + "flight it reports in-progress (409) rather than duplicating. Then poll with get_status or " + "wait_for_completion (kind=short). A failed free re-render leaves the delivered video intact — retry " + "rerender_short, it stays free (the status fields latest_render_free / last_free_rerender_failed " + "report this when the server sends them).",
32433
+ description: "FREE re-render: applies the short's current text/style/CTA/end-card state over the already-paid " + "footage and music — 0 credits. Use after update_short for copy/style/CTA tweaks. Footage or music " + "changes need generate_short (15 credits) instead. Edits that add/remove the end card (poster, " + "end_card) can shift the video between 12s and 14s; when the pinned music bed is shorter than the " + "export it crossfades into a repeated continuation, then fades at the export end, without regeneration. " + "Requires a completed generation to re-render over " + "(422 short_not_ready otherwise — run generate_short once first); while any generation/render is in " + "flight it reports in-progress (409) rather than duplicating. Then poll with get_status or " + "wait_for_completion (kind=short). A failed free re-render leaves the delivered video intact — retry " + "rerender_short, it stays free (the status fields latest_render_free / last_free_rerender_failed " + "report this when the server sends them).",
32137
32434
  inputSchema: {
32138
32435
  slug: exports_external.string().describe("Short slug (from create_short)")
32139
32436
  },
@@ -32373,8 +32670,8 @@ registerTool("edit_slider_slide", {
32373
32670
  }
32374
32671
  }));
32375
32672
  registerTool("create_editor_ad", {
32376
- title: "Create a multi-scene editor ad (autopilot)",
32377
- description: "Creates an editor project from a product prompt and starts autopilot (server-orchestrated " + "scenario → segments → narration → voice → music → render). Each AI-generated scene is a fixed 8 seconds. " + "Returns the slug. Costs credits. Then poll with get_status / wait_for_completion (kind=editor). Prefer " + "make_video for the one-shot path. " + "BRANDING: to attach the user's own product image, brand logo, or closing card, create the draft with " + "create_editor_draft first, call set_product / set_logo / set_closing_image (all 0 credits), then " + "start_autopilot — autopilot weaves them in. (Editor ads carry their copy in-scene/narration, not as a " + "title overlay; for an on-screen title/subtitle use a short with headline/subheadline instead.) " + "For product_only or presenter_led cast modes, use create_editor_draft and configure the required " + "product/presenter before start_autopilot; this one-shot tool intentionally uses automatic casting.",
32673
+ title: "Create, configure, and price a multi-scene editor ad",
32674
+ description: "Creates an editor project, attaches any supplied local product/logo/closing assets BEFORE generation, " + "and prices autopilot (server-orchestrated " + "scenario → segments → narration → voice → music → render). Each AI-generated scene is a fixed 8 seconds. " + "Without max_credits it STOPS after the free draft/configuration and returns the live estimate. It starts " + "the paid pipeline only when max_credits is supplied and covers the estimate. Then poll with get_status / " + "wait_for_completion (kind=editor). Prefer make_video for a prompt-only one-shot. " + "Supplying assets here is safer than adding them after autopilot because the scenario and scenes are grounded " + "in the real product from the start. (Editor ads carry their copy in-scene/narration, not as a " + "title overlay; for an on-screen title/subtitle use a short with headline/subheadline instead.) " + "For a mascot or hero product that must stay visually identical with no human presenter, set " + "cast_mode:'product_only' together with product_image_path. Presenter-led casting still belongs on " + "create_editor_draft because it requires a separately configured presenter.",
32378
32675
  inputSchema: {
32379
32676
  product_prompt: exports_external.string().min(10).describe("Brief for the ad (min 10 chars)"),
32380
32677
  product_subject: exports_external.string().max(300).optional().describe('The concrete product or main subject the video must be about (e.g. "Bordeaux red wine, dark green ' + 'bottle with a gold label"). Distinct from the freeform brief: hard-grounds the AI scenario + narration ' + "so it cannot invent an unrelated product. Strongly recommended for ads."),
@@ -32384,42 +32681,139 @@ registerTool("create_editor_ad", {
32384
32681
  visual_language: exports_external.enum(VISUAL_LANGUAGES).optional().describe("Visual style direction and render look. Good default: kinetic_creator. When set it drives the look and a theme of 'none' is ignored."),
32385
32682
  theme: exports_external.string().optional().describe('Visual theme / genre overlay (default "realistic"). One of: none (no imposed style — segments follow your prompts literally), realistic, cinematic, anime, sci_fi, fantasy, noir, superhero, horror, mockumentary, sports, gaming, retro_80s, minimalist, cyberpunk.'),
32386
32683
  voice_id: exports_external.string().optional().describe("Preferred narration voice id (see list_voices); omit for the default voice"),
32387
- export_aspect_ratio: exports_external.enum(["9:16", "16:9", "1:1"]).optional().describe('Aspect ratio (default "9:16")')
32684
+ export_aspect_ratio: exports_external.enum(["9:16", "16:9", "1:1"]).optional().describe('Aspect ratio (default "9:16")'),
32685
+ product_image_path: exports_external.string().optional().describe("Local product image (.jpg/.jpeg/.png, ≤8 MiB) to attach before autopilot."),
32686
+ product_description: exports_external.string().max(500).optional().describe("Exact product/character description used with product_image_path."),
32687
+ closing_image_path: exports_external.string().optional().describe("Local closing-card image (.jpg/.jpeg/.png, ≤20 MiB)."),
32688
+ logo_path: exports_external.string().optional().describe("Local logo (.jpg/.jpeg/.png, ≤1 MiB) to overlay."),
32689
+ logo_treatment: exports_external.enum(["intro", "outro", "both", "none"]).optional().describe('When the logo bumper plays: "intro", "outro", "both" (default), or "none". Requires logo_path.'),
32690
+ logo_position: exports_external.enum(["top-left", "top-right", "bottom-left", "bottom-right"]).optional().describe('Logo corner: "top-left", "top-right" (default), "bottom-left", or "bottom-right". Requires logo_path.'),
32691
+ logo_duration_seconds: exports_external.number().min(0.5).max(3).optional().describe("Logo bumper duration in seconds, 0.5–3 (default 1.5). Requires logo_path."),
32692
+ cast_mode: exports_external.literal("product_only").optional().describe("Lock every AI scene to the supplied product/mascot reference with no people. Requires product_image_path."),
32693
+ max_credits: exports_external.number().int().nonnegative().optional().describe("Explicit spend cap. Omit to create/configure/price only; no credits are charged.")
32388
32694
  },
32389
32695
  outputSchema: createEditorOutput,
32390
32696
  annotations: { title: "Create editor ad", ...WRITE, idempotentHint: true }
32391
32697
  }, tool(async (args, client) => {
32392
- const langErr = validateLanguage(args.language);
32393
- if (langErr)
32394
- return fail(langErr);
32395
- const promptErr = validateProductPrompt(args.product_prompt);
32396
- if (promptErr)
32397
- return fail(promptErr);
32398
- const created = await client.post("/editor", {
32399
- language: args.language ?? "en",
32400
- product_prompt: args.product_prompt,
32401
- product_subject: args.product_subject,
32402
- project_intent: args.project_intent,
32403
- creative_format: args.creative_format,
32404
- visual_language: args.visual_language,
32405
- theme: args.theme,
32406
- voice_id: args.voice_id,
32407
- export_aspect_ratio: args.export_aspect_ratio
32408
- }, editorAdCreateKey(args));
32409
- const slug = created.data.slug;
32410
- const started = await client.post(`/editor/${slug}/autopilot`, undefined, editorAdAutopilotKey(slug, args));
32411
- const status = normalizeStatus("editor", slug, asRecord(started).data);
32412
- return ok({ slug, kind: "editor", status, next: "wait_for_completion" });
32698
+ const prepared = [];
32699
+ let productImage;
32700
+ let closingImage;
32701
+ let logo;
32702
+ try {
32703
+ const langErr = validateLanguage(args.language);
32704
+ if (langErr)
32705
+ return fail(langErr);
32706
+ const promptErr = validateProductPrompt(args.product_prompt);
32707
+ if (promptErr)
32708
+ return fail(promptErr);
32709
+ if (args.cast_mode === "product_only" && !args.product_image_path) {
32710
+ return fail("cast_mode product_only requires product_image_path so identity can be locked before generation.");
32711
+ }
32712
+ if ((args.logo_treatment !== undefined || args.logo_position !== undefined || args.logo_duration_seconds !== undefined) && !args.logo_path) {
32713
+ return fail("logo_treatment/logo_position/logo_duration_seconds require logo_path (the logo image they style). Provide logo_path or drop these settings.");
32714
+ }
32715
+ if (args.product_description !== undefined && !args.product_image_path) {
32716
+ return fail("product_description requires product_image_path (the product image it describes). Provide product_image_path or drop product_description.");
32717
+ }
32718
+ if (args.product_image_path) {
32719
+ productImage = await prepareImageUpload(args.product_image_path, MAX_PRODUCT_IMAGE_BYTES);
32720
+ prepared.push(productImage);
32721
+ }
32722
+ if (args.closing_image_path) {
32723
+ closingImage = await prepareImageUpload(args.closing_image_path, MAX_CLOSING_IMAGE_BYTES);
32724
+ prepared.push(closingImage);
32725
+ }
32726
+ if (args.logo_path) {
32727
+ logo = await prepareImageUpload(args.logo_path, MAX_LOGO_BYTES);
32728
+ prepared.push(logo);
32729
+ }
32730
+ const created = await client.post("/editor", {
32731
+ language: args.language ?? "en",
32732
+ product_prompt: args.product_prompt,
32733
+ product_subject: args.product_subject,
32734
+ project_intent: args.project_intent,
32735
+ creative_format: args.creative_format,
32736
+ visual_language: args.visual_language,
32737
+ theme: args.theme,
32738
+ voice_id: args.voice_id,
32739
+ export_aspect_ratio: args.export_aspect_ratio,
32740
+ cast_mode: args.cast_mode
32741
+ }, editorAdCreateKey({
32742
+ ...args,
32743
+ product_image_identity: productImage ? preparedUploadIdentity(productImage) : undefined,
32744
+ closing_image_identity: closingImage ? preparedUploadIdentity(closingImage) : undefined,
32745
+ logo_identity: logo ? preparedUploadIdentity(logo) : undefined
32746
+ }));
32747
+ const slug = created.data.slug;
32748
+ let configured = {};
32749
+ if (args.product_image_path || args.closing_image_path || args.logo_path) {
32750
+ const current = await client.get(`/editor/${slug}`);
32751
+ configured = asRecord(asRecord(current).data);
32752
+ }
32753
+ if (productImage && !configured.product_url) {
32754
+ const { s3_key } = await uploadImageFile(client, `/editor/${slug}/product/presign`, productImage, MAX_PRODUCT_IMAGE_BYTES);
32755
+ await client.post(`/editor/${slug}/product/confirm`, {
32756
+ s3_key,
32757
+ product_description: args.product_description
32758
+ });
32759
+ }
32760
+ if (closingImage && !configured.closing_image_url) {
32761
+ const { s3_key } = await uploadImageFile(client, `/editor/${slug}/closing-image/presign`, closingImage, MAX_CLOSING_IMAGE_BYTES);
32762
+ await client.post(`/editor/${slug}/closing-image/confirm`, {
32763
+ s3_key
32764
+ });
32765
+ }
32766
+ if (logo && !configured.logo_url) {
32767
+ const { s3_key } = await uploadImageFile(client, `/editor/${slug}/logo/presign`, logo, MAX_LOGO_BYTES);
32768
+ await client.post(`/editor/${slug}/logo/confirm`, { s3_key });
32769
+ }
32770
+ const logoSettings = {};
32771
+ if (args.logo_treatment !== undefined)
32772
+ logoSettings.logo_treatment = args.logo_treatment;
32773
+ if (args.logo_position !== undefined)
32774
+ logoSettings.logo_position = args.logo_position;
32775
+ if (args.logo_duration_seconds !== undefined)
32776
+ logoSettings.logo_duration_seconds = args.logo_duration_seconds;
32777
+ if (args.logo_path && Object.keys(logoSettings).length > 0)
32778
+ await client.patch(`/editor/${slug}/logo`, logoSettings);
32779
+ const quote = await editorAutopilotQuote(client, slug);
32780
+ const overCap = args.max_credits !== undefined && quote.estimated_credits !== null && quote.estimated_credits > args.max_credits;
32781
+ if (args.max_credits === undefined || quote.estimated_credits === null || overCap || !quote.affordable) {
32782
+ const note = args.max_credits === undefined ? `Free draft configured. Estimated ${quote.estimated_credits ?? "?"} credits (have ${quote.available_credits ?? "?"}); nothing charged. Relaunch with start_autopilot({ slug: "${slug}", max_credits: ${quote.estimated_credits ?? "<approved cap>"} }).` : quote.estimated_credits === null ? "Pricing is temporarily unavailable, so the paid pipeline was not started. Retry the quote later." : overCap ? `Estimated ${quote.estimated_credits} credits exceeds max_credits ${args.max_credits}; nothing charged.` : `Not enough credits (needs ${quote.estimated_credits}, have ${quote.available_credits ?? "?"}); nothing charged.`;
32783
+ return ok({
32784
+ slug,
32785
+ kind: "editor",
32786
+ ...quote,
32787
+ charged: false,
32788
+ note,
32789
+ next: "start_autopilot"
32790
+ });
32791
+ }
32792
+ const started = await client.post(`/editor/${slug}/autopilot`, { max_credits: args.max_credits }, editorAdAutopilotKey(slug, args));
32793
+ const status = normalizeStatus("editor", slug, asRecord(started).data);
32794
+ return ok({
32795
+ slug,
32796
+ kind: "editor",
32797
+ status,
32798
+ ...quote,
32799
+ charged: true,
32800
+ next: "wait_for_completion"
32801
+ });
32802
+ } finally {
32803
+ await Promise.all(prepared.map(closePreparedUploadFile));
32804
+ }
32413
32805
  }));
32414
32806
  registerTool("start_autopilot", {
32415
32807
  title: "Start autopilot on an existing editor draft",
32416
- description: "Starts server-orchestrated autopilot (scenario → segments → narration → voice → music → render) on an " + "EXISTING editor project/draft. Spends credits preview the estimate first with the autopilot/cost endpoint " + "or make_video({ dry_run:true }). Each call is a genuine start attempt (like tapping Launch in the app): " + "if a run is already in progress for this slug the server returns already_running — it never double-starts " + "or double-charges. Once finished, failed, or cancelled, calling again relaunches it (resume after a top-up, raising your spend cap, or a mid-pipeline failure). Then poll with " + 'wait_for_completion({ slug, kind: "editor" }).',
32808
+ description: "Starts server-orchestrated autopilot (scenario → segments → narration → voice → music → render) on an " + "EXISTING editor project/draft. Without max_credits it returns the live quote and charges nothing. Supply an " + "explicit max_credits cap to authorize launch; the tool refuses if pricing is unavailable, the estimate exceeds " + "the cap, or the balance is insufficient. Each authorized call is a genuine start attempt (like tapping Launch in the app): " + "if a run is already in progress for this slug the server returns already_running — it never double-starts " + "or double-charges. Once finished, failed, or cancelled, calling again relaunches it (resume after a top-up, raising your spend cap, or a mid-pipeline failure). Then poll with " + 'wait_for_completion({ slug, kind: "editor" }).',
32417
32809
  inputSchema: {
32418
32810
  slug: exports_external.string().describe("Editor project slug"),
32419
32811
  language: exports_external.enum(LANGUAGES).optional().describe('Optional language override applied before launch. Bare ISO-639-1 code only, e.g. "fr" — no ' + "region/script subtag. Drives scenario, narration, voice, and captions."),
32420
32812
  product_subject: exports_external.string().max(300).optional().describe("Optional locked product / main subject applied before launch so the AI cannot invent an " + "unrelated product."),
32421
- product_prompt: exports_external.string().optional().describe("Optional freeform brief to set/replace before launch.")
32813
+ product_prompt: exports_external.string().optional().describe("Optional freeform brief to set/replace before launch."),
32814
+ max_credits: exports_external.number().int().nonnegative().optional().describe("Explicit spend cap. Omit to quote only; no credits are charged.")
32422
32815
  },
32816
+ outputSchema: createEditorOutput,
32423
32817
  annotations: { title: "Start autopilot", ...WRITE, idempotentHint: false }
32424
32818
  }, tool(async (args, client) => {
32425
32819
  const langErr = validateLanguage(args.language);
@@ -32436,12 +32830,25 @@ registerTool("start_autopilot", {
32436
32830
  overrides.product_subject = args.product_subject;
32437
32831
  if (args.product_prompt !== undefined)
32438
32832
  overrides.product_prompt = args.product_prompt;
32439
- const started = await client.post(`/editor/${slug}/autopilot`, Object.keys(overrides).length > 0 ? overrides : undefined, idemKey("autopilot", slug, randomUUID()));
32833
+ const quote = await editorAutopilotQuote(client, slug, overrides);
32834
+ const overCap = args.max_credits !== undefined && quote.estimated_credits !== null && quote.estimated_credits > args.max_credits;
32835
+ if (args.max_credits === undefined || quote.estimated_credits === null || overCap || !quote.affordable) {
32836
+ return ok({
32837
+ slug,
32838
+ kind: "editor",
32839
+ ...quote,
32840
+ charged: false,
32841
+ note: args.max_credits === undefined ? `Quote only: estimated ${quote.estimated_credits ?? "?"} credits (have ${quote.available_credits ?? "?"}). Pass max_credits to authorize launch.` : quote.estimated_credits === null ? "Pricing is unavailable; launch refused because the spend cap cannot be enforced." : overCap ? `Estimated ${quote.estimated_credits} credits exceeds max_credits ${args.max_credits}; nothing charged.` : `Not enough credits (needs ${quote.estimated_credits}, have ${quote.available_credits ?? "?"}); nothing charged.`
32842
+ });
32843
+ }
32844
+ const started = await client.post(`/editor/${slug}/autopilot`, { ...overrides, max_credits: args.max_credits }, idemKey("autopilot", slug, randomUUID()));
32440
32845
  const status = normalizeStatus("editor", slug, asRecord(started).data);
32441
32846
  return ok({
32442
32847
  slug,
32443
32848
  kind: "editor",
32444
32849
  status,
32850
+ ...quote,
32851
+ charged: true,
32445
32852
  next: "wait_for_completion"
32446
32853
  });
32447
32854
  }));
@@ -32463,7 +32870,7 @@ registerTool("unlock_ai_assists", {
32463
32870
  }, tool(async (_args, client) => ok(await client.post("/ai-assists/unlock", undefined, await unlockKey(client)))));
32464
32871
  registerTool("create_editor_draft", {
32465
32872
  title: "Create an editor draft (no autopilot)",
32466
- description: "Creates an editor project from a product prompt and stops (NO autopilot). Costs 0 credits. Returns the " + "slug. Use this to drive the pipeline step by step (vs create_editor_ad which runs autopilot end to end). " + "Each AI-generated scene renders to a fixed 8 seconds (uploaded clips keep their own length). " + "product_prompt is optional content: send 10–5000 chars, or omit it entirely (empty is treated as omit).",
32873
+ description: "Creates an editor project from a product prompt and stops (NO autopilot). Costs 0 credits. Returns the " + "slug. Use this to drive the pipeline step by step (vs create_editor_ad which configures, quotes, and can launch autopilot with a spend cap). " + "Each AI-generated scene renders to a fixed 8 seconds (uploaded clips keep their own length). " + "product_prompt is optional content: send 10–5000 chars, or omit it entirely (empty is treated as omit).",
32467
32874
  inputSchema: {
32468
32875
  product_prompt: exports_external.string().min(10).max(5000).optional().describe("Brief for the ad — 10–5000 chars, or omit entirely"),
32469
32876
  product_subject: exports_external.string().max(300).optional().describe("The concrete product / main subject the video must be about. Hard-grounds the AI so it cannot " + "invent an unrelated product. Recommended for ads."),
@@ -32965,7 +33372,7 @@ async function pollUploadToReady(client, slug, uploadId, extra, budgetMs, interv
32965
33372
  }
32966
33373
  registerTool("upload_video", {
32967
33374
  title: "Upload a local video clip into an editor project",
32968
- description: "Uploads a local video FILE (your own footage) into an editor project and, by default, adds it to the timeline " + "as a finished scene. Unlike an AI-generated scene (a fixed 8 seconds), an uploaded clip keeps its own native " + "duration. Runs presign → PUT (resumable multipart for large files) → confirm, then polls until the " + "upload is processed (ready). file_path is a LOCAL path confined to HUBFLUENCER_INPUT_DIR (or cwd). Accepted: " + VIDEO_EXTS.map((e) => `.${e}`).join(", ") + " (≤500 MB, ≤5 min). Costs 0 credits. If add_to_timeline is false (default true) the clip is uploaded but not " + "placed — call add_segment_from_upload later.",
33375
+ description: "Uploads a local video FILE (your own footage) into an editor project and, by default, adds it to the timeline " + "as a finished scene. Unlike an AI-generated scene (a fixed 8 seconds), an uploaded clip keeps its own native " + "duration. Runs presign → PUT (resumable multipart for large files) → confirm, then polls until the " + "upload is processed (ready). file_path is a LOCAL path confined to HUBFLUENCER_INPUT_DIR (or cwd). Accepted: " + VIDEO_EXTS.map((e) => `.${e}`).join(", ") + " (≤500 MB decimal = 500,000,000 bytes, ≤5 min). Costs 0 credits. If add_to_timeline is false (default true) the clip is uploaded but not " + "placed — call add_segment_from_upload later.",
32969
33376
  inputSchema: {
32970
33377
  slug: exports_external.string().describe("Editor project slug"),
32971
33378
  file_path: exports_external.string().describe("Local video file path (inside HUBFLUENCER_INPUT_DIR or cwd)"),
@@ -33038,7 +33445,7 @@ registerTool("add_segment_from_upload", {
33038
33445
  }));
33039
33446
  registerTool("use_asset_for_segment", {
33040
33447
  title: "Reuse a clip/asset for a specific scene (0 credits)",
33041
- description: "Sets a specific scene's video from an existing asset — either a ready upload (upload_id) OR a completed scene " + "in the same project (source_segment_id). Provide EXACTLY ONE. 0 credits. Use it to reuse one uploaded clip " + "across scenes, or to swap a generated scene for your own footage.",
33448
+ description: "Sets a specific scene's video from an existing asset — either a ready upload (upload_id) OR a completed scene " + "in the same project (source_segment_id). Provide EXACTLY ONE. 0 credits. Use it to reuse one uploaded clip " + "across scenes, or to swap a generated scene for your own footage. The response includes continuity impact and " + "current narration/voice/music staleness. If the replacement duration differs, regenerate stale audio before render.",
33042
33449
  inputSchema: {
33043
33450
  slug: exports_external.string().describe("Editor project slug"),
33044
33451
  segment_id: exports_external.union([exports_external.number(), exports_external.string()]).describe("Target scene id (from get_editor)"),
@@ -33058,11 +33465,40 @@ registerTool("use_asset_for_segment", {
33058
33465
  }
33059
33466
  const body = hasUpload ? { upload_id: args.upload_id } : { source_segment_id: args.source_segment_id };
33060
33467
  const res = await client.post(`/editor/${args.slug}/segments/${String(args.segment_id)}/use-asset`, body);
33061
- return ok(asRecord(res).data ?? res);
33468
+ const segment = asRecord(asRecord(res).data ?? res);
33469
+ const impact = asRecord(segment.impact);
33470
+ const staleSegmentIds = Array.isArray(impact.stale_video_segment_ids) ? impact.stale_video_segment_ids : [];
33471
+ const requiresRegeneration = impact.requires_regeneration === true || staleSegmentIds.length > 0;
33472
+ let timeline;
33473
+ try {
33474
+ const current = await client.get(`/editor/${args.slug}`);
33475
+ const editor = asRecord(asRecord(current).data);
33476
+ timeline = {
33477
+ narration_stale: editor.narration_stale === true,
33478
+ voice_stale: editor.voice_stale === true,
33479
+ music_stale: editor.music_stale === true,
33480
+ stale_segment_ids: staleSegmentIds,
33481
+ requires_regeneration: requiresRegeneration
33482
+ };
33483
+ } catch {
33484
+ timeline = {
33485
+ narration_stale: null,
33486
+ voice_stale: null,
33487
+ music_stale: null,
33488
+ stale_segment_ids: staleSegmentIds,
33489
+ requires_regeneration: requiresRegeneration,
33490
+ enrichment_unavailable: true
33491
+ };
33492
+ }
33493
+ return ok({
33494
+ ...segment,
33495
+ timeline,
33496
+ next: timeline.requires_regeneration || timeline.narration_stale || timeline.voice_stale || timeline.music_stale ? "Regenerate the reported stale scenes/audio before render." : timeline.enrichment_unavailable ? "Scene swap succeeded, but audio staleness could not be verified (enrichment fetch failed) — call get_status before render to confirm." : "Timeline is current and can be rendered."
33497
+ });
33062
33498
  }));
33063
33499
  registerTool("set_product", {
33064
33500
  title: "Attach a product image (from a local file)",
33065
- description: "Uploads a local product image and attaches it to the project as the product. Accepted: " + IMAGE_EXTS.map((e) => `.${e}`).join(", ") + " (≤20 MB), local path confined to HUBFLUENCER_INPUT_DIR (or cwd). 0 credits. The FIRST product added " + "defaults every pending AI scene to feature it 'throughout' (change with set_product_placement). Optional " + "description (≤500 chars) guides how it's woven into scenes.",
33501
+ description: "Uploads a local product image and attaches it to the project as the product. Accepted: " + IMAGE_EXTS.map((e) => `.${e}`).join(", ") + " (≤8 MiB), local path confined to HUBFLUENCER_INPUT_DIR (or cwd). 0 credits. The FIRST product added " + "defaults every pending AI scene to feature it 'throughout' (change with set_product_placement). Optional " + "description (≤500 chars) guides how it's woven into scenes.",
33066
33502
  inputSchema: {
33067
33503
  slug: exports_external.string().describe("Editor project slug"),
33068
33504
  file_path: exports_external.string().describe("Local product image path (.jpg/.jpeg/.png)"),
@@ -33070,7 +33506,7 @@ registerTool("set_product", {
33070
33506
  },
33071
33507
  annotations: { title: "Set product", ...WRITE, idempotentHint: false }
33072
33508
  }, tool(async (args, client) => {
33073
- const { s3_key } = await uploadImageFile(client, `/editor/${args.slug}/product/presign`, args.file_path);
33509
+ const { s3_key } = await uploadImageFile(client, `/editor/${args.slug}/product/presign`, args.file_path, MAX_PRODUCT_IMAGE_BYTES);
33074
33510
  const res = await client.post(`/editor/${args.slug}/product/confirm`, { s3_key, product_description: args.description });
33075
33511
  return ok(asRecord(res).data ?? res);
33076
33512
  }));
@@ -33092,7 +33528,7 @@ registerTool("set_product_placement", {
33092
33528
  }));
33093
33529
  registerTool("set_closing_image", {
33094
33530
  title: "Set the closing-card image (0 credits)",
33095
- description: "Sets the optional ~2s end-card image. Either upload a local file (file_path; .jpg/.jpeg/.png ≤20 MB, confined " + "to HUBFLUENCER_INPUT_DIR/cwd) OR reuse the project's product image (from_product:true — a 0-credit server-side " + "copy, no upload). If a closing image already exists, pass overwrite:true to replace it (else " + "editor_closing_image_exists).",
33531
+ description: "Sets the optional ~2s end-card image. Either upload a local file (file_path; .jpg/.jpeg/.png ≤20 MiB, confined " + "to HUBFLUENCER_INPUT_DIR/cwd) OR reuse the project's product image (from_product:true — a 0-credit server-side " + "copy, no upload). If a closing image already exists, pass overwrite:true to replace it (else " + "editor_closing_image_exists).",
33096
33532
  inputSchema: {
33097
33533
  slug: exports_external.string().describe("Editor project slug"),
33098
33534
  file_path: exports_external.string().optional().describe("Local image to upload as the end card"),
@@ -33112,13 +33548,13 @@ registerTool("set_closing_image", {
33112
33548
  if (!args.file_path) {
33113
33549
  return fail("Provide file_path (a local image) or from_product:true.");
33114
33550
  }
33115
- const { s3_key } = await uploadImageFile(client, `/editor/${args.slug}/closing-image/presign`, args.file_path);
33551
+ const { s3_key } = await uploadImageFile(client, `/editor/${args.slug}/closing-image/presign`, args.file_path, MAX_CLOSING_IMAGE_BYTES);
33116
33552
  const res = await client.post(`/editor/${args.slug}/closing-image/confirm`, { s3_key });
33117
33553
  return ok(asRecord(res).data ?? res);
33118
33554
  }));
33119
33555
  registerTool("set_logo", {
33120
33556
  title: "Set a brand logo overlay (0 credits)",
33121
- description: "Uploads a local brand logo and overlays it on the video. Accepted: .png/.jpg/.jpeg (≤20 MB; PNG keeps " + "transparency), confined to HUBFLUENCER_INPUT_DIR/cwd. 0 credits. Optional placement controls: treatment, " + "position, duration_seconds.",
33557
+ description: "Uploads a local brand logo and overlays it on the video. Accepted: .png/.jpg/.jpeg (≤1 MiB; PNG keeps " + "transparency), confined to HUBFLUENCER_INPUT_DIR/cwd. 0 credits. Optional placement controls: treatment, " + "position, duration_seconds.",
33122
33558
  inputSchema: {
33123
33559
  slug: exports_external.string().describe("Editor project slug"),
33124
33560
  file_path: exports_external.string().describe("Local logo image (.png/.jpg/.jpeg)"),
@@ -33128,7 +33564,7 @@ registerTool("set_logo", {
33128
33564
  },
33129
33565
  annotations: { title: "Set logo", ...WRITE, idempotentHint: false }
33130
33566
  }, tool(async (args, client) => {
33131
- const { s3_key } = await uploadImageFile(client, `/editor/${args.slug}/logo/presign`, args.file_path);
33567
+ const { s3_key } = await uploadImageFile(client, `/editor/${args.slug}/logo/presign`, args.file_path, MAX_LOGO_BYTES);
33132
33568
  const confirmed = await client.post(`/editor/${args.slug}/logo/confirm`, { s3_key });
33133
33569
  let result = asRecord(confirmed).data ?? confirmed;
33134
33570
  const settings = {};
@@ -33146,7 +33582,7 @@ registerTool("set_logo", {
33146
33582
  }));
33147
33583
  registerTool("set_short_product", {
33148
33584
  title: "Attach a product image to a short (0 credits)",
33149
- description: "Uploads a local product image and attaches it to a SHORT so the product is woven into the footage. " + "Accepted: " + IMAGE_EXTS.map((e) => `.${e}`).join(", ") + " (≤20 MB), local path confined to HUBFLUENCER_INPUT_DIR (or cwd). 0 credits. Optional description " + "(≤500 chars) guides how it's featured. Attach BEFORE generate_short so the product is part of the scenes. " + "(This is the shorts equivalent of set_product for editor projects.)",
33585
+ description: "Uploads a local product image and attaches it to a SHORT so the product is woven into the footage. " + "Accepted: " + IMAGE_EXTS.map((e) => `.${e}`).join(", ") + " (≤20 MiB = 20,971,520 bytes), local path confined to HUBFLUENCER_INPUT_DIR (or cwd). 0 credits. Optional description " + "(≤500 chars) guides how it's featured. Attach BEFORE generate_short so the product is part of the scenes. " + "(This is the shorts equivalent of set_product for editor projects.)",
33150
33586
  inputSchema: {
33151
33587
  slug: exports_external.string().describe("Short slug (from create_short)"),
33152
33588
  file_path: exports_external.string().describe("Local product image path (.jpg/.jpeg/.png)"),
@@ -33164,7 +33600,7 @@ registerTool("set_short_product", {
33164
33600
  }));
33165
33601
  registerTool("set_short_poster", {
33166
33602
  title: "Set a short's end-card poster image (0 credits)",
33167
- description: "Uploads a local image as the SHORT's end-card poster — a closing still shown at the end (extends the " + "render from 12s to 14s). Accepted: " + IMAGE_EXTS.map((e) => `.${e}`).join(", ") + " (≤20 MB), confined to HUBFLUENCER_INPUT_DIR/cwd. 0 credits. There is one poster per short; calling " + "again replaces it. (Shorts have no logo overlay — for a brand logo use an editor project + set_logo.)",
33603
+ description: "Uploads a local image as the SHORT's end-card poster — a closing still shown at the end (extends the " + "render from 12s to 14s). Accepted: " + IMAGE_EXTS.map((e) => `.${e}`).join(", ") + " (≤20 MiB = 20,971,520 bytes), confined to HUBFLUENCER_INPUT_DIR/cwd. 0 credits. There is one poster per short; calling " + "again replaces it. (Shorts have no logo overlay — for a brand logo use an editor project + set_logo.)",
33168
33604
  inputSchema: {
33169
33605
  slug: exports_external.string().describe("Short slug (from create_short)"),
33170
33606
  file_path: exports_external.string().describe("Local poster image (.jpg/.jpeg/.png)"),
@@ -33191,7 +33627,7 @@ registerTool("get_status", {
33191
33627
  }));
33192
33628
  registerTool("wait_for_completion", {
33193
33629
  title: "Wait for a render to finish",
33194
- description: "Polls status (emitting progress) until terminal (ready/failed) or the wait budget is exhausted. " + "Generation can take several minutes; if it returns terminal=false, call again to keep waiting. " + "Pass save_path to download the finished MP4 when it's ready (e.g. to resume a make_video that timed out mid-render). " + 'Works for kind:"slider" too, but a carousel has no MP4 — it just goes terminal when composited; read the slide ' + "images with get_slider (save_path is ignored for sliders).",
33630
+ description: "Polls status (emitting progress) until terminal or the wait budget is exhausted. " + "Generation can take several minutes; if it returns terminal=false, call again to keep waiting. " + "terminal=true does NOT always mean ready=true: an editor can go terminal in a needs-action stage " + '(stage "editing_required" — a delivered render is stale after edits, regenerate the reported scenes/audio; ' + 'stage "insufficient_credits" — a batch is parked, top up or reduce scope; ' + 'stage "idle" — a draft with nothing generating, start generation first) that only a further tool call ' + "can advance — do NOT just re-poll those. " + "Pass save_path to download the finished MP4 when it's ready (e.g. to resume a make_video that timed out mid-render). " + 'Works for kind:"slider" too, but a carousel has no MP4 — it just goes terminal when composited; read the slide ' + "images with get_slider (save_path is ignored for sliders).",
33195
33631
  inputSchema: {
33196
33632
  slug: exports_external.string(),
33197
33633
  kind: kindSchema,
@@ -33766,7 +34202,7 @@ registerTool("materialize_episode", {
33766
34202
  const episode = summarizeEpisode(asRecord(res).data);
33767
34203
  return ok({
33768
34204
  ...episode,
33769
- next: episode.draft_slug ? "Generate this draft EXPLICITLY (a separate, PAID step): editor_ad/short start_autopilot({ slug }); carousel generate_slider({ slug })." : "Draft created — review it with list_series_episodes."
34205
+ next: episode.draft_slug ? "Price this draft with start_autopilot({ slug }); after approval launch it with start_autopilot({ slug, max_credits: approved_cap }). Carousel generation remains a separate paid generate_slider call." : "Draft created — review it with list_series_episodes."
33770
34206
  });
33771
34207
  }));
33772
34208
  registerTool("get_series_dashboard", {
@@ -34116,7 +34552,7 @@ registerTool("get_asset_quota", {
34116
34552
  }));
34117
34553
  registerTool("upload_asset", {
34118
34554
  title: "Upload a local file to your reusable asset catalog",
34119
- description: "Uploads a local IMAGE or VIDEO into your reusable asset catalog so it can be reused across projects. " + `Allowed types: ${CATALOG_ASSET_EXTS.map((e) => `.${e}`).join(", ")} — images ≤20 MiB, videos ≤500 MB. ` + "Runs presign → PUT → confirm; the confirm HEADs the object and validates size/type, so a mismatch 422s. " + "For a VIDEO you MUST pass duration_seconds (≤60; the server rejects a video with no/over-long duration). " + "Spends 0 credits. Scope: video:generate. Rate limit: 30/min. Requires an ACTIVE SUBSCRIPTION (402 " + "subscription_required otherwise). The local path is confined to HUBFLUENCER_INPUT_DIR (default: cwd). " + "Returns the confirmed asset id + media type + status.",
34555
+ description: "Uploads a local IMAGE or VIDEO into your reusable asset catalog so it can be reused across projects. " + `Allowed types: ${CATALOG_ASSET_EXTS.map((e) => `.${e}`).join(", ")} — images ≤20 MiB (20,971,520 bytes), videos ≤500 MB decimal (500,000,000 bytes). ` + "Runs presign → PUT → confirm; the confirm HEADs the object and validates size/type, so a mismatch 422s. " + "For a VIDEO you MUST pass duration_seconds (≤60; the server rejects a video with no/over-long duration). " + "Spends 0 credits. Scope: video:generate. Rate limit: 30/min. Requires an ACTIVE SUBSCRIPTION (402 " + "subscription_required otherwise). The local path is confined to HUBFLUENCER_INPUT_DIR (default: cwd). " + "Returns the confirmed asset id + media type + status.",
34120
34556
  inputSchema: {
34121
34557
  file_path: exports_external.string().describe("Path to a local image/video, inside HUBFLUENCER_INPUT_DIR (default: cwd)"),
34122
34558
  description: exports_external.string().optional().describe("Optional description stored with the asset"),