omnius 1.0.155 → 1.0.156

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
@@ -11854,6 +11854,12 @@ var _sponsorDailyTokensUsed = 0;
11854
11854
  var _sponsorDailyResetAt = Date.now() + 86400000;
11855
11855
  var _sponsorBlockedRequests = 0;
11856
11856
  var _sponsorTokenRateSamples = [];
11857
+ var _sponsorMediaConfig = null;
11858
+ var _sponsorMediaActive = {};
11859
+ var _sponsorMediaRequestWindow = {};
11860
+ var _sponsorMediaDailyJobs = {};
11861
+ var _sponsorMediaDailyResetAt = Date.now() + 86400000;
11862
+ var _mediaByRequest = {};
11857
11863
 
11858
11864
  function _sponsorPrune(now) {
11859
11865
  while (_sponsorRequestWindow.length > 0 && _sponsorRequestWindow[0] < now - 60000) _sponsorRequestWindow.shift();
@@ -11927,6 +11933,80 @@ function _sponsorRecordUsage(inputTokens, outputTokens, includeRate) {
11927
11933
  if (includeRate !== false) _sponsorRecordTokenRate(output);
11928
11934
  }
11929
11935
 
11936
+ function _sponsorMediaPrune(now) {
11937
+ now = now || Date.now();
11938
+ if (_sponsorMediaDailyResetAt <= now) {
11939
+ _sponsorMediaDailyJobs = {};
11940
+ _sponsorMediaDailyResetAt = now + 86400000;
11941
+ }
11942
+ for (var key of Object.keys(_sponsorMediaRequestWindow)) {
11943
+ var arr = _sponsorMediaRequestWindow[key] || [];
11944
+ while (arr.length > 0 && arr[0] < now - 60000) arr.shift();
11945
+ _sponsorMediaRequestWindow[key] = arr;
11946
+ }
11947
+ }
11948
+
11949
+ function _sponsorMediaLimitsFor(modality) {
11950
+ if (!_sponsorMediaConfig || !_sponsorMediaConfig[modality]) return null;
11951
+ return _sponsorMediaConfig[modality];
11952
+ }
11953
+
11954
+ function _sponsorMediaAdmit(modality) {
11955
+ var limits = _sponsorMediaLimitsFor(modality);
11956
+ if (!limits || !limits.enabled) return { ok: false, reason: modality + ' sponsorship is disabled.' };
11957
+ var now = Date.now();
11958
+ _sponsorMediaPrune(now);
11959
+ var active = _sponsorMediaActive[modality] || 0;
11960
+ var window = _sponsorMediaRequestWindow[modality] || [];
11961
+ var daily = _sponsorMediaDailyJobs[modality] || 0;
11962
+ var maxConcurrent = Math.max(0, Number(limits.maxConcurrent || 0));
11963
+ var jobsPerMinute = Math.max(0, Number(limits.jobsPerMinute || 0));
11964
+ var jobsPerDay = Math.max(0, Number(limits.jobsPerDay || 0));
11965
+ if (maxConcurrent <= 0 || jobsPerMinute <= 0 || jobsPerDay <= 0) {
11966
+ _sponsorBlockedRequests++;
11967
+ return { ok: false, reason: modality + ' sponsorship is paused or has no quota configured.' };
11968
+ }
11969
+ if (_sponsorLimits && _sponsorActiveRequests >= _sponsorLimits.maxConcurrent) {
11970
+ _sponsorBlockedRequests++;
11971
+ return { ok: false, reason: 'Too many sponsor requests (' + _sponsorActiveRequests + '/' + _sponsorLimits.maxConcurrent + '). Try again shortly.' };
11972
+ }
11973
+ if (active >= maxConcurrent) {
11974
+ _sponsorBlockedRequests++;
11975
+ return { ok: false, reason: 'Too many concurrent ' + modality + ' jobs (' + active + '/' + maxConcurrent + '). Try again shortly.' };
11976
+ }
11977
+ if (window.length >= jobsPerMinute) {
11978
+ _sponsorBlockedRequests++;
11979
+ return { ok: false, reason: modality + ' rate limited (' + jobsPerMinute + ' jobs/min).' };
11980
+ }
11981
+ if (daily >= jobsPerDay) {
11982
+ _sponsorBlockedRequests++;
11983
+ return { ok: false, reason: modality + ' daily job budget exhausted.' };
11984
+ }
11985
+ _sponsorActiveRequests++;
11986
+ _sponsorMediaActive[modality] = active + 1;
11987
+ window.push(now);
11988
+ _sponsorMediaRequestWindow[modality] = window;
11989
+ _sponsorMediaDailyJobs[modality] = daily + 1;
11990
+ return { ok: true };
11991
+ }
11992
+
11993
+ function _sponsorMediaRelease(modality) {
11994
+ if (_sponsorActiveRequests > 0) _sponsorActiveRequests--;
11995
+ var active = _sponsorMediaActive[modality] || 0;
11996
+ if (active > 0) _sponsorMediaActive[modality] = active - 1;
11997
+ }
11998
+
11999
+ function _sponsorMediaGatewaySnapshot() {
12000
+ _sponsorMediaPrune(Date.now());
12001
+ return {
12002
+ active: _sponsorMediaActive,
12003
+ requestsInWindow: Object.fromEntries(Object.keys(_sponsorMediaRequestWindow).map(function(k) { return [k, (_sponsorMediaRequestWindow[k] || []).length]; })),
12004
+ dailyJobsUsed: _sponsorMediaDailyJobs,
12005
+ dailyResetAt: _sponsorMediaDailyResetAt,
12006
+ limits: _sponsorMediaConfig,
12007
+ };
12008
+ }
12009
+
11930
12010
  function _sponsorGatewaySnapshot() {
11931
12011
  var now = Date.now();
11932
12012
  _sponsorPrune(now);
@@ -11938,6 +12018,7 @@ function _sponsorGatewaySnapshot() {
11938
12018
  blockedRequests: _sponsorBlockedRequests,
11939
12019
  tokensPerSecond: _sponsorTokenRate(now),
11940
12020
  limits: _sponsorLimits,
12021
+ media: _sponsorMediaGatewaySnapshot(),
11941
12022
  };
11942
12023
  }
11943
12024
 
@@ -12916,6 +12997,10 @@ async function handleCmd(cmd) {
12916
12997
  } catch {}
12917
12998
  var sponsorLimitsArg = {};
12918
12999
  try { sponsorLimitsArg = args.limits ? JSON.parse(args.limits) : {}; } catch {}
13000
+ var sponsorServicesArg = [];
13001
+ try {
13002
+ if (args.services) sponsorServicesArg = typeof args.services === 'string' ? JSON.parse(args.services) : args.services;
13003
+ } catch {}
12919
13004
  var sponsorData = {
12920
13005
  type: 'sponsor.announce',
12921
13006
  peerId: (connected ? nexus.peerId : 'unknown') || 'unknown',
@@ -12923,6 +13008,8 @@ async function handleCmd(cmd) {
12923
13008
  name: args.name || 'Anonymous Sponsor',
12924
13009
  models: _saModels.length > 0 ? _saModels : _saModelDetails.map(function(m) { return m.name; }),
12925
13010
  modelDetails: _saModelDetails, // NX-07: per-model capacity
13011
+ services: Array.isArray(sponsorServicesArg) ? sponsorServicesArg : [],
13012
+ mediaCapabilities: Array.isArray(sponsorServicesArg) ? sponsorServicesArg.filter(function(s) { return s && s.kind && s.kind !== 'llm'; }) : [],
12926
13013
  tunnelUrl: args.tunnel_url || null,
12927
13014
  authKey: args.auth_key || '',
12928
13015
  limits: {
@@ -13007,6 +13094,8 @@ async function handleCmd(cmd) {
13007
13094
  rateLimit: String(sponsorData.limits.maxRequestsPerMinute) + '/min',
13008
13095
  sponsor: sponsorData,
13009
13096
  models: sponsorData.models,
13097
+ services: sponsorData.services,
13098
+ mediaCapabilities: sponsorData.mediaCapabilities,
13010
13099
  limits: sponsorData.limits,
13011
13100
  });
13012
13101
  writeResp(id, { ok: true, output: 'Sponsor announced: ' + sponsorData.name + ' (' + sponsorData.models.length + ' models) [DHT+GossipSub+NATS+KV+Room]' });
@@ -14183,7 +14272,7 @@ async function handleCmd(cmd) {
14183
14272
  if (typeof nexus.getRegisteredCapabilities === 'function' && typeof nexus.unregisterCapability === 'function') {
14184
14273
  var oldCaps = nexus.getRegisteredCapabilities();
14185
14274
  for (var oci = 0; oci < oldCaps.length; oci++) {
14186
- if (oldCaps[oci].startsWith('inference:') || oldCaps[oci] === 'system_metrics' || oldCaps[oci] === '__list_capabilities') {
14275
+ if (oldCaps[oci].startsWith('inference:') || oldCaps[oci].startsWith('media:') || oldCaps[oci] === 'system_metrics' || oldCaps[oci] === '__list_capabilities') {
14187
14276
  try { nexus.unregisterCapability(oldCaps[oci]); } catch {}
14188
14277
  }
14189
14278
  }
@@ -14217,6 +14306,18 @@ async function handleCmd(cmd) {
14217
14306
  } else {
14218
14307
  _sponsorLimits = null;
14219
14308
  }
14309
+ try {
14310
+ var mediaConfigRaw = args.media_config || args.media_limits || '';
14311
+ if (mediaConfigRaw) {
14312
+ var mediaHelpersForConfig = await import('@omnius/execution');
14313
+ _sponsorMediaConfig = mediaHelpersForConfig.normalizeSponsorMediaConfig(JSON.parse(mediaConfigRaw));
14314
+ } else {
14315
+ _sponsorMediaConfig = null;
14316
+ }
14317
+ } catch (mediaConfigErr) {
14318
+ dlog('expose: media sponsor config parse failed: ' + (mediaConfigErr.message || mediaConfigErr));
14319
+ _sponsorMediaConfig = null;
14320
+ }
14220
14321
 
14221
14322
  // Passthrough mode: forward from a remote /endpoint (Chutes, Groq, etc.)
14222
14323
  var isPassthrough = args.passthrough === 'true';
@@ -14762,6 +14863,228 @@ async function handleCmd(cmd) {
14762
14863
  });
14763
14864
  }
14764
14865
 
14866
+ var mediaServices = [];
14867
+ if (_sponsorMediaConfig) {
14868
+ try {
14869
+ var mediaModule = await import('@omnius/execution');
14870
+ mediaServices = mediaModule.buildSponsorMediaServices(_sponsorMediaConfig);
14871
+ for (var msi = 0; msi < mediaServices.length; msi++) {
14872
+ const mediaService = mediaServices[msi];
14873
+ if (typeof nexus.registerCapability === 'function') {
14874
+ nexus.registerCapability(mediaService.capability, async (request, stream) => {
14875
+ var mediaStreamClosed = false;
14876
+ async function mediaWrite(msg) {
14877
+ if (mediaStreamClosed) return;
14878
+ try { await stream.write(msg); } catch (mwErr) {
14879
+ mediaStreamClosed = true;
14880
+ dlog('media stream.write failed: ' + (mwErr.message || mwErr));
14881
+ }
14882
+ }
14883
+ var mediaChunks = [];
14884
+ var mediaInputDone = false;
14885
+ stream.onData(function(msg) {
14886
+ if (msg.type === 'invoke.chunk') {
14887
+ mediaChunks.push(typeof msg.data === 'string' ? msg.data : JSON.stringify(msg.data));
14888
+ }
14889
+ if (msg.type === 'invoke.done' || msg.type === 'invoke.end' || msg.type === 'invoke.close') {
14890
+ mediaInputDone = true;
14891
+ }
14892
+ });
14893
+ await mediaWrite({ type: 'invoke.accept', version: 1, requestId: request.requestId, accepted: true });
14894
+ var mediaWaitMs = 0;
14895
+ while (!mediaInputDone && mediaChunks.length === 0 && mediaWaitMs < 5000) {
14896
+ await new Promise(function(r) { setTimeout(r, 10); });
14897
+ mediaWaitMs += 10;
14898
+ }
14899
+ var mediaRawInput = mediaChunks.join('');
14900
+ if (exposeAuthKey) {
14901
+ var mediaReqAuthKey = '';
14902
+ try {
14903
+ var mediaAuthData = JSON.parse(mediaRawInput);
14904
+ if (mediaAuthData && typeof mediaAuthData === 'object' && mediaAuthData.auth_key) mediaReqAuthKey = mediaAuthData.auth_key;
14905
+ } catch {}
14906
+ if (!mediaReqAuthKey && request.metadata && request.metadata.auth_key) mediaReqAuthKey = request.metadata.auth_key;
14907
+ if (mediaReqAuthKey !== exposeAuthKey) {
14908
+ await mediaWrite({ type: 'invoke.event', version: 1, requestId: request.requestId, seq: 0, event: 'error', data: 'Unauthorized — invalid or missing auth key' });
14909
+ await mediaWrite({ type: 'invoke.done', version: 1, requestId: request.requestId, usage: { inputBytes: 0, outputBytes: 0 } });
14910
+ try { stream.close(); } catch {}
14911
+ return;
14912
+ }
14913
+ }
14914
+
14915
+ var mediaAdmissionOpen = false;
14916
+ var mediaStart = Date.now();
14917
+ var mediaModality = mediaService.kind;
14918
+ var mediaSeq = 0;
14919
+ try {
14920
+ var parsedMediaInput;
14921
+ try { parsedMediaInput = JSON.parse(mediaRawInput || '{}'); } catch { parsedMediaInput = { prompt: mediaRawInput || '' }; }
14922
+ var mediaHelpers = await import('@omnius/execution');
14923
+ var sanitized = mediaHelpers.sanitizeRemoteMediaGenerateRequest(parsedMediaInput, mediaService, _sponsorMediaConfig);
14924
+ if (!sanitized.ok) {
14925
+ throw new Error(sanitized.reason || 'Remote media request rejected');
14926
+ }
14927
+
14928
+ var admission = _sponsorMediaAdmit(mediaModality);
14929
+ if (!admission.ok) {
14930
+ await mediaWrite({ type: 'invoke.event', version: 1, requestId: request.requestId, seq: mediaSeq++, event: 'error', data: admission.reason });
14931
+ await mediaWrite({ type: 'invoke.done', version: 1, requestId: request.requestId, usage: { inputBytes: mediaRawInput.length, outputBytes: 0 } });
14932
+ try {
14933
+ appendFileSync(meteringFile, JSON.stringify({
14934
+ timestamp: Date.now(),
14935
+ peerId: request.from || 'unknown',
14936
+ service: mediaService.capability,
14937
+ capability: mediaService.capability,
14938
+ modality: mediaModality,
14939
+ model: mediaService.model || 'auto',
14940
+ direction: 'inbound',
14941
+ blocked: true,
14942
+ reason: admission.reason,
14943
+ outputBytes: 0,
14944
+ }) + '\\n');
14945
+ } catch {}
14946
+ try { stream.close(); } catch {}
14947
+ return;
14948
+ }
14949
+ mediaAdmissionOpen = true;
14950
+
14951
+ var safeArgs = sanitized.value.args || {};
14952
+ var progressCb = async function(event) {
14953
+ var payload = {
14954
+ type: 'progress',
14955
+ stage: String(event && event.stage ? event.stage : 'run'),
14956
+ message: String(event && event.message ? event.message : ''),
14957
+ percent: event && typeof event.percent === 'number' ? event.percent : undefined,
14958
+ };
14959
+ await mediaWrite({ type: 'invoke.event', version: 1, requestId: request.requestId, seq: mediaSeq++, event: 'progress', data: JSON.stringify(payload) });
14960
+ };
14961
+
14962
+ var tool;
14963
+ if (mediaModality === 'image') {
14964
+ tool = new mediaHelpers.ImageGenerateTool(process.cwd(), rawUrl);
14965
+ } else if (mediaModality === 'video') {
14966
+ tool = new mediaHelpers.VideoGenerateTool(process.cwd());
14967
+ } else {
14968
+ tool = new mediaHelpers.AudioGenerateTool(process.cwd());
14969
+ }
14970
+ if (tool && typeof tool.setProgressCallback === 'function') {
14971
+ tool.setProgressCallback(function(event) { progressCb(event).catch(function() {}); });
14972
+ }
14973
+ await mediaWrite({ type: 'invoke.event', version: 1, requestId: request.requestId, seq: mediaSeq++, event: 'progress', data: JSON.stringify({ type: 'progress', stage: 'start', message: 'Starting ' + mediaModality + ' generation' }) });
14974
+ var mediaResult = await tool.execute(safeArgs);
14975
+ if (!mediaResult || !mediaResult.success) {
14976
+ throw new Error((mediaResult && (mediaResult.error || mediaResult.output)) || 'Media generation failed');
14977
+ }
14978
+ var mutated = Array.isArray(mediaResult.mutatedFiles) ? mediaResult.mutatedFiles : [];
14979
+ var primaryPath = '';
14980
+ for (var mpi = 0; mpi < mutated.length; mpi++) {
14981
+ var pth = String(mutated[mpi] || '');
14982
+ if (mediaModality === 'image' && /\\.(png|jpe?g|webp)$/i.test(pth)) { primaryPath = pth; break; }
14983
+ if (mediaModality === 'video' && /\\.(mp4|webm)$/i.test(pth)) { primaryPath = pth; break; }
14984
+ if ((mediaModality === 'sound' || mediaModality === 'music') && /\\.(wav|mp3|flac|ogg)$/i.test(pth)) { primaryPath = pth; break; }
14985
+ }
14986
+ if (!primaryPath && mutated[0]) primaryPath = String(mutated[0]);
14987
+ if (!primaryPath || !existsSync(primaryPath)) throw new Error('Generated media artifact was not found');
14988
+ var artifactBytes = readFileSync(primaryPath);
14989
+ var limits = _sponsorMediaLimitsFor(mediaModality) || {};
14990
+ var maxBytes = Math.max(0, Number(limits.maxOutputBytes || 0));
14991
+ if (maxBytes > 0 && artifactBytes.length > maxBytes) {
14992
+ throw new Error('Generated artifact exceeds sponsor output limit (' + artifactBytes.length + '/' + maxBytes + ' bytes)');
14993
+ }
14994
+ var artifactId = mediaModality + '-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 8);
14995
+ var filename = require('node:path').basename(primaryPath);
14996
+ var mime = mediaHelpers.mediaMimeFromPath(primaryPath, mediaModality);
14997
+ var sha = createHash('sha256').update(artifactBytes).digest('hex');
14998
+ await mediaWrite({ type: 'invoke.event', version: 1, requestId: request.requestId, seq: mediaSeq++, event: 'artifact.begin', data: JSON.stringify({ type: 'artifact.begin', artifactId: artifactId, filename: filename, mime: mime, sizeBytes: artifactBytes.length, sha256: sha }) });
14999
+ var chunkSize = 64 * 1024;
15000
+ var chunkSeq = 0;
15001
+ for (var off = 0; off < artifactBytes.length; off += chunkSize) {
15002
+ var chunk = artifactBytes.subarray(off, Math.min(off + chunkSize, artifactBytes.length));
15003
+ await mediaWrite({ type: 'invoke.event', version: 1, requestId: request.requestId, seq: mediaSeq++, event: 'artifact.chunk', data: JSON.stringify({ type: 'artifact.chunk', artifactId: artifactId, seq: chunkSeq++, dataBase64: chunk.toString('base64') }) });
15004
+ }
15005
+ await mediaWrite({ type: 'invoke.event', version: 1, requestId: request.requestId, seq: mediaSeq++, event: 'artifact.end', data: JSON.stringify({ type: 'artifact.end', artifactId: artifactId, sha256: sha, sizeBytes: artifactBytes.length }) });
15006
+ var metadata = {
15007
+ ok: true,
15008
+ type: 'result',
15009
+ modality: mediaModality,
15010
+ model: safeArgs.model || mediaService.model || 'auto',
15011
+ backend: safeArgs.backend || mediaService.backend || 'auto',
15012
+ artifact: { artifactId: artifactId, filename: filename, mime: mime, sizeBytes: artifactBytes.length, sha256: sha },
15013
+ output: mediaResult.output || '',
15014
+ durationMs: Date.now() - mediaStart,
15015
+ system: null,
15016
+ };
15017
+ try {
15018
+ var sm2 = await _collectSysMetrics();
15019
+ if (sm2) metadata.system = Object.assign({}, sm2, { gateway: _sponsorGatewaySnapshot() });
15020
+ } catch {}
15021
+ await mediaWrite({ type: 'invoke.event', version: 1, requestId: request.requestId, seq: mediaSeq++, event: 'result', data: JSON.stringify(metadata) });
15022
+ await mediaWrite({ type: 'invoke.done', version: 1, requestId: request.requestId, usage: { inputBytes: mediaRawInput.length, outputBytes: artifactBytes.length } });
15023
+ _mediaByRequest[request.requestId] = {
15024
+ modality: mediaModality,
15025
+ model: String(safeArgs.model || mediaService.model || 'auto'),
15026
+ inputBytes: mediaRawInput.length,
15027
+ outputBytes: artifactBytes.length,
15028
+ durationMs: Date.now() - mediaStart,
15029
+ success: true,
15030
+ };
15031
+ try {
15032
+ appendFileSync(meteringFile, JSON.stringify({
15033
+ timestamp: Date.now(),
15034
+ peerId: request.from || 'unknown',
15035
+ service: mediaService.capability,
15036
+ capability: mediaService.capability,
15037
+ modality: mediaModality,
15038
+ model: String(safeArgs.model || mediaService.model || 'auto'),
15039
+ direction: 'inbound',
15040
+ inputBytes: mediaRawInput.length,
15041
+ outputBytes: artifactBytes.length,
15042
+ durationMs: Date.now() - mediaStart,
15043
+ success: true,
15044
+ }) + '\\n');
15045
+ } catch {}
15046
+ } catch (mediaErr) {
15047
+ var mediaErrMsg = mediaErr && mediaErr.message ? mediaErr.message : String(mediaErr);
15048
+ await mediaWrite({ type: 'invoke.event', version: 1, requestId: request.requestId, seq: mediaSeq++, event: 'error', data: mediaErrMsg });
15049
+ await mediaWrite({ type: 'invoke.done', version: 1, requestId: request.requestId, usage: { inputBytes: mediaRawInput.length, outputBytes: 0 } });
15050
+ try {
15051
+ appendFileSync(meteringFile, JSON.stringify({
15052
+ timestamp: Date.now(),
15053
+ peerId: request.from || 'unknown',
15054
+ service: mediaService.capability,
15055
+ capability: mediaService.capability,
15056
+ modality: mediaModality,
15057
+ model: mediaService.model || 'auto',
15058
+ direction: 'inbound',
15059
+ inputBytes: mediaRawInput.length,
15060
+ outputBytes: 0,
15061
+ durationMs: Date.now() - mediaStart,
15062
+ success: false,
15063
+ reason: mediaErrMsg,
15064
+ }) + '\\n');
15065
+ } catch {}
15066
+ } finally {
15067
+ if (mediaAdmissionOpen) _sponsorMediaRelease(mediaModality);
15068
+ try { stream.close(); } catch {}
15069
+ }
15070
+ });
15071
+ }
15072
+ await _publishCapabilityRecord(mediaService.capability, {
15073
+ description: 'Omnius sponsored ' + mediaService.kind + ' generation',
15074
+ pricing: 'sponsored',
15075
+ rateLimit: String(mediaService.limits.jobsPerMinute || 'provider-policy') + '/min',
15076
+ service: mediaService,
15077
+ model: mediaService.model,
15078
+ modality: mediaService.kind,
15079
+ limits: mediaService.limits,
15080
+ });
15081
+ }
15082
+ dlog('expose: registered ' + mediaServices.length + ' media sponsor capabilities');
15083
+ } catch (mediaExposeErr) {
15084
+ dlog('expose: media capability registration failed: ' + (mediaExposeErr.message || mediaExposeErr));
15085
+ }
15086
+ }
15087
+
14765
15088
  // Register system_metrics capability — returns CPU/GPU/memory utilization
14766
15089
  if (typeof nexus.registerCapability === 'function') {
14767
15090
  nexus.registerCapability('system_metrics', async (request, stream) => {
@@ -14892,7 +15215,7 @@ async function handleCmd(cmd) {
14892
15215
  quantization: pm.quantization || '',
14893
15216
  });
14894
15217
  }
14895
- var capsPayload = JSON.stringify({ capabilities: allCaps, models: modelsInfo, agentName: agentName, peerId: nexus.peerId });
15218
+ var capsPayload = JSON.stringify({ capabilities: allCaps, models: modelsInfo, services: mediaServices, mediaCapabilities: mediaServices, agentName: agentName, peerId: nexus.peerId });
14896
15219
  await stream.write({ type: 'invoke.event', version: 1, requestId: request.requestId, seq: 0, event: 'result', data: capsPayload });
14897
15220
  await stream.write({ type: 'invoke.done', version: 1, requestId: request.requestId, usage: { inputBytes: 0, outputBytes: capsPayload.length } });
14898
15221
  stream.close();
@@ -14910,12 +15233,14 @@ async function handleCmd(cmd) {
14910
15233
  quantization: pm.quantization || '',
14911
15234
  };
14912
15235
  }),
15236
+ services: mediaServices,
15237
+ mediaCapabilities: mediaServices,
14913
15238
  });
14914
15239
  }
14915
15240
 
14916
15241
  // Write pricing menu to file
14917
15242
  const pricingFile = join(nexusDir, 'pricing.json');
14918
- writeFileSync(pricingFile, JSON.stringify({ updated: new Date().toISOString(), models: pricingMenu }, null, 2));
15243
+ writeFileSync(pricingFile, JSON.stringify({ updated: new Date().toISOString(), models: pricingMenu, services: mediaServices }, null, 2));
14919
15244
  writeStatus({ exposedModels: pricingMenu.length });
14920
15245
 
14921
15246
  const lines = ['Exposed ' + pricingMenu.length + ' model(s) as nexus capabilities:'];
@@ -14925,6 +15250,13 @@ async function handleCmd(cmd) {
14925
15250
  : '$' + p.pricing.input_per_1m_tokens + '/$' + p.pricing.output_per_1m_tokens + ' per 1M tokens';
14926
15251
  lines.push(' inference:' + p.model + ' — ' + cost);
14927
15252
  }
15253
+ if (mediaServices.length > 0) {
15254
+ lines.push('');
15255
+ lines.push('Exposed ' + mediaServices.length + ' media generation service(s):');
15256
+ for (var msl = 0; msl < mediaServices.length; msl++) {
15257
+ lines.push(' ' + mediaServices[msl].capability + ' — sponsored ' + mediaServices[msl].kind);
15258
+ }
15259
+ }
14928
15260
  lines.push('');
14929
15261
  lines.push('Pricing menu saved to ' + pricingFile);
14930
15262
  lines.push('Market rates: ' + Object.keys(marketRates).length + ' models from OpenRouter');
@@ -95984,7 +96316,7 @@ var require_auto = __commonJS({
95984
96316
  // ../node_modules/acme-client/src/client.js
95985
96317
  var require_client = __commonJS({
95986
96318
  "../node_modules/acme-client/src/client.js"(exports, module) {
95987
- var { createHash: createHash32 } = __require("crypto");
96319
+ var { createHash: createHash34 } = __require("crypto");
95988
96320
  var { getPemBodyAsB64u } = require_crypto();
95989
96321
  var { log: log22 } = require_logger();
95990
96322
  var HttpClient = require_http();
@@ -96295,14 +96627,14 @@ var require_client = __commonJS({
96295
96627
  */
96296
96628
  async getChallengeKeyAuthorization(challenge) {
96297
96629
  const jwk = this.http.getJwk();
96298
- const keysum = createHash32("sha256").update(JSON.stringify(jwk));
96630
+ const keysum = createHash34("sha256").update(JSON.stringify(jwk));
96299
96631
  const thumbprint = keysum.digest("base64url");
96300
96632
  const result = `${challenge.token}.${thumbprint}`;
96301
96633
  if (challenge.type === "http-01") {
96302
96634
  return result;
96303
96635
  }
96304
96636
  if (challenge.type === "dns-01") {
96305
- return createHash32("sha256").update(result).digest("base64url");
96637
+ return createHash34("sha256").update(result).digest("base64url");
96306
96638
  }
96307
96639
  if (challenge.type === "tls-alpn-01") {
96308
96640
  return result;
@@ -132214,7 +132546,7 @@ var require_snapshot_recorder = __commonJS({
132214
132546
  "../node_modules/undici/lib/mock/snapshot-recorder.js"(exports, module) {
132215
132547
  "use strict";
132216
132548
  var { writeFile: writeFile24, readFile: readFile23, mkdir: mkdir20 } = __require("node:fs/promises");
132217
- var { dirname: dirname43, resolve: resolve56 } = __require("node:path");
132549
+ var { dirname: dirname44, resolve: resolve56 } = __require("node:path");
132218
132550
  var { setTimeout: setTimeout3, clearTimeout: clearTimeout3 } = __require("node:timers");
132219
132551
  var { InvalidArgumentError, UndiciError } = require_errors2();
132220
132552
  var { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = require_snapshot_utils();
@@ -132445,7 +132777,7 @@ var require_snapshot_recorder = __commonJS({
132445
132777
  throw new InvalidArgumentError("Snapshot path is required");
132446
132778
  }
132447
132779
  const resolvedPath = resolve56(path12);
132448
- await mkdir20(dirname43(resolvedPath), { recursive: true });
132780
+ await mkdir20(dirname44(resolvedPath), { recursive: true });
132449
132781
  const data = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({
132450
132782
  hash,
132451
132783
  snapshot
@@ -238982,7 +239314,7 @@ var require_websocket2 = __commonJS({
238982
239314
  var http6 = __require("http");
238983
239315
  var net5 = __require("net");
238984
239316
  var tls2 = __require("tls");
238985
- var { randomBytes: randomBytes29, createHash: createHash32 } = __require("crypto");
239317
+ var { randomBytes: randomBytes29, createHash: createHash34 } = __require("crypto");
238986
239318
  var { Duplex: Duplex3, Readable } = __require("stream");
238987
239319
  var { URL: URL3 } = __require("url");
238988
239320
  var PerMessageDeflate3 = require_permessage_deflate2();
@@ -239642,7 +239974,7 @@ var require_websocket2 = __commonJS({
239642
239974
  abortHandshake(websocket, socket, "Invalid Upgrade header");
239643
239975
  return;
239644
239976
  }
239645
- const digest3 = createHash32("sha1").update(key + GUID).digest("base64");
239977
+ const digest3 = createHash34("sha1").update(key + GUID).digest("base64");
239646
239978
  if (res.headers["sec-websocket-accept"] !== digest3) {
239647
239979
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
239648
239980
  return;
@@ -240009,7 +240341,7 @@ var require_websocket_server = __commonJS({
240009
240341
  var EventEmitter15 = __require("events");
240010
240342
  var http6 = __require("http");
240011
240343
  var { Duplex: Duplex3 } = __require("stream");
240012
- var { createHash: createHash32 } = __require("crypto");
240344
+ var { createHash: createHash34 } = __require("crypto");
240013
240345
  var extension3 = require_extension2();
240014
240346
  var PerMessageDeflate3 = require_permessage_deflate2();
240015
240347
  var subprotocol3 = require_subprotocol();
@@ -240310,7 +240642,7 @@ var require_websocket_server = __commonJS({
240310
240642
  );
240311
240643
  }
240312
240644
  if (this._state > RUNNING) return abortHandshake(socket, 503);
240313
- const digest3 = createHash32("sha1").update(key + GUID).digest("base64");
240645
+ const digest3 = createHash34("sha1").update(key + GUID).digest("base64");
240314
240646
  const headers = [
240315
240647
  "HTTP/1.1 101 Switching Protocols",
240316
240648
  "Upgrade: websocket",
@@ -246107,15 +246439,15 @@ var init_ls = __esm({
246107
246439
  });
246108
246440
 
246109
246441
  // ../node_modules/@helia/unixfs/dist/src/commands/mkdir.js
246110
- async function mkdir6(parentCid, dirname43, blockstore, options2 = {}) {
246111
- if (dirname43.includes("/")) {
246442
+ async function mkdir6(parentCid, dirname44, blockstore, options2 = {}) {
246443
+ if (dirname44.includes("/")) {
246112
246444
  throw new InvalidParametersError4("Path must not have slashes");
246113
246445
  }
246114
246446
  const entry = await exporter2(parentCid, blockstore, options2);
246115
246447
  if (entry.type !== "directory") {
246116
246448
  throw new NotADirectoryError(`${parentCid.toString()} was not a UnixFS directory`);
246117
246449
  }
246118
- log16("creating %s", dirname43);
246450
+ log16("creating %s", dirname44);
246119
246451
  const metadata = new UnixFS({
246120
246452
  type: "directory",
246121
246453
  mode: options2.mode,
@@ -246131,9 +246463,9 @@ async function mkdir6(parentCid, dirname43, blockstore, options2 = {}) {
246131
246463
  await blockstore.put(emptyDirCid, buf);
246132
246464
  const [directory, pblink] = await Promise.all([
246133
246465
  cidToDirectory(parentCid, blockstore, options2),
246134
- cidToPBLink(emptyDirCid, dirname43, blockstore, options2)
246466
+ cidToPBLink(emptyDirCid, dirname44, blockstore, options2)
246135
246467
  ]);
246136
- log16("adding empty dir called %s to %c", dirname43, parentCid);
246468
+ log16("adding empty dir called %s to %c", dirname44, parentCid);
246137
246469
  const result = await addLink(directory, pblink, blockstore, {
246138
246470
  ...options2,
246139
246471
  allowOverwriting: options2.force
@@ -246632,8 +246964,8 @@ var init_unixfs2 = __esm({
246632
246964
  async *ls(cid, options2 = {}) {
246633
246965
  yield* ls(cid, this.components.blockstore, options2);
246634
246966
  }
246635
- async mkdir(cid, dirname43, options2 = {}) {
246636
- return mkdir6(cid, dirname43, this.components.blockstore, options2);
246967
+ async mkdir(cid, dirname44, options2 = {}) {
246968
+ return mkdir6(cid, dirname44, this.components.blockstore, options2);
246637
246969
  }
246638
246970
  async rm(cid, path12, options2 = {}) {
246639
246971
  return rm3(cid, path12, this.components.blockstore, options2);
@@ -250030,8 +250362,8 @@ var require_pattern = __commonJS({
250030
250362
  }
250031
250363
  exports.endsWithSlashGlobStar = endsWithSlashGlobStar;
250032
250364
  function isAffectDepthOfReadingPattern(pattern) {
250033
- const basename34 = path12.basename(pattern);
250034
- return endsWithSlashGlobStar(pattern) || isStaticPattern(basename34);
250365
+ const basename35 = path12.basename(pattern);
250366
+ return endsWithSlashGlobStar(pattern) || isStaticPattern(basename35);
250035
250367
  }
250036
250368
  exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
250037
250369
  function expandPatternsWithBraceExpansion(patterns) {
@@ -253117,13 +253449,13 @@ Justification: ${justification || "(none provided)"}`,
253117
253449
  }
253118
253450
  const snapshot = JSON.stringify(this.selfState, null, 2);
253119
253451
  try {
253120
- const { createHash: createHash32 } = await import("node:crypto");
253452
+ const { createHash: createHash34 } = await import("node:crypto");
253121
253453
  const snapshotDir = join32(this.cwd, ".omnius", "identity", "snapshots");
253122
253454
  await mkdir7(snapshotDir, { recursive: true });
253123
253455
  const version4 = this.selfState.version;
253124
253456
  const snapshotPath = join32(snapshotDir, `v${version4}.json`);
253125
253457
  await writeFile12(snapshotPath, snapshot, "utf8");
253126
- const hash = createHash32("sha256").update(snapshot).digest("hex");
253458
+ const hash = createHash34("sha256").update(snapshot).digest("hex");
253127
253459
  await writeFile12(join32(this.cwd, ".omnius", "identity", "latest-hash.txt"), hash, "utf8");
253128
253460
  let ipfsCid = "";
253129
253461
  try {
@@ -253256,8 +253588,8 @@ New: ${newNarrative.slice(0, 200)}...`,
253256
253588
  }
253257
253589
  // ── Helpers ──────────────────────────────────────────────────────────────
253258
253590
  createDefaultState() {
253259
- const { createHash: createHash32 } = __require("node:crypto");
253260
- const machineId = createHash32("sha256").update(this.cwd).digest("hex").slice(0, 12);
253591
+ const { createHash: createHash34 } = __require("node:crypto");
253592
+ const machineId = createHash34("sha256").update(this.cwd).digest("hex").slice(0, 12);
253261
253593
  return {
253262
253594
  self_id: `omnius-${machineId}`,
253263
253595
  version: 1,
@@ -253339,9 +253671,9 @@ New: ${newNarrative.slice(0, 200)}...`,
253339
253671
  let cid;
253340
253672
  if (this.selfState.version > prevVersion) {
253341
253673
  try {
253342
- const { createHash: createHash32 } = await import("node:crypto");
253674
+ const { createHash: createHash34 } = await import("node:crypto");
253343
253675
  const stateJson = JSON.stringify(this.selfState);
253344
- const hash = createHash32("sha256").update(stateJson).digest("hex").slice(0, 32);
253676
+ const hash = createHash34("sha256").update(stateJson).digest("hex").slice(0, 32);
253345
253677
  const cidsPath = join32(this.cwd, ".omnius", "identity", "cids.json");
253346
253678
  const cidsData = { latest: "", hash, version: this.selfState.version };
253347
253679
  try {
@@ -262581,6 +262913,436 @@ ${llmAnnotation}` : result.llmContent;
262581
262913
  }
262582
262914
  });
262583
262915
 
262916
+ // packages/execution/dist/tools/sponsor-media.js
262917
+ import { createHash as createHash6 } from "node:crypto";
262918
+ function normalizeSponsorMediaConfig(value2) {
262919
+ const input = typeof value2 === "object" && value2 !== null ? value2 : {};
262920
+ const config = structuredClone(DEFAULT_SPONSOR_MEDIA_LIMITS);
262921
+ for (const modality of SPONSOR_MEDIA_MODALITIES) {
262922
+ const raw = input[modality];
262923
+ if (!raw || typeof raw !== "object")
262924
+ continue;
262925
+ const src2 = raw;
262926
+ const dst = config[modality];
262927
+ dst.enabled = booleanValue(src2["enabled"], dst.enabled);
262928
+ dst.allowedModels = normalizeAllowedModels(src2["allowedModels"] ?? src2["allowed_models"], dst.allowedModels);
262929
+ dst.maxConcurrent = positiveInt(src2["maxConcurrent"] ?? src2["max_concurrent"], dst.maxConcurrent);
262930
+ dst.jobsPerMinute = positiveInt(src2["jobsPerMinute"] ?? src2["jobs_per_minute"], dst.jobsPerMinute);
262931
+ dst.jobsPerDay = positiveInt(src2["jobsPerDay"] ?? src2["jobs_per_day"], dst.jobsPerDay);
262932
+ dst.maxOutputBytes = positiveInt(src2["maxOutputBytes"] ?? src2["max_output_bytes"], dst.maxOutputBytes);
262933
+ dst.maxWidth = optionalPositiveInt(src2["maxWidth"] ?? src2["max_width"], dst.maxWidth);
262934
+ dst.maxHeight = optionalPositiveInt(src2["maxHeight"] ?? src2["max_height"], dst.maxHeight);
262935
+ dst.maxMegapixels = optionalPositiveNumber(src2["maxMegapixels"] ?? src2["max_megapixels"], dst.maxMegapixels);
262936
+ dst.maxDurationSec = optionalPositiveNumber(src2["maxDurationSec"] ?? src2["max_duration_sec"], dst.maxDurationSec);
262937
+ dst.maxFrames = optionalPositiveInt(src2["maxFrames"] ?? src2["max_frames"], dst.maxFrames);
262938
+ dst.maxFps = optionalPositiveInt(src2["maxFps"] ?? src2["max_fps"], dst.maxFps);
262939
+ dst.maxSteps = optionalPositiveInt(src2["maxSteps"] ?? src2["max_steps"], dst.maxSteps);
262940
+ }
262941
+ return config;
262942
+ }
262943
+ function sponsorMediaCapabilityName(modality, model = "auto") {
262944
+ return `${SPONSOR_MEDIA_CAPABILITY_PREFIX}${modality}:${slugCapabilityPart(model || "auto")}`;
262945
+ }
262946
+ function parseSponsorMediaCapability(capability) {
262947
+ const parts = capability.split(":");
262948
+ if (parts.length < 3 || parts[0] !== "media")
262949
+ return null;
262950
+ const modality = parts[1];
262951
+ if (!SPONSOR_MEDIA_MODALITIES.includes(modality))
262952
+ return null;
262953
+ return { modality, modelSlug: parts.slice(2).join(":") || "auto" };
262954
+ }
262955
+ function buildSponsorMediaServices(configLike) {
262956
+ const config = normalizeSponsorMediaConfig(configLike);
262957
+ const services = [];
262958
+ for (const modality of SPONSOR_MEDIA_MODALITIES) {
262959
+ const limits = config[modality];
262960
+ if (!limits.enabled)
262961
+ continue;
262962
+ const models = limits.allowedModels === "all" || limits.allowedModels.length === 0 ? ["auto"] : limits.allowedModels;
262963
+ for (const model of models) {
262964
+ services.push({
262965
+ kind: modality,
262966
+ capability: sponsorMediaCapabilityName(modality, model),
262967
+ model,
262968
+ input: mediaInputsFor(modality),
262969
+ output: mediaOutputsFor(modality),
262970
+ limits: serializeMediaLimits(limits)
262971
+ });
262972
+ }
262973
+ }
262974
+ return services;
262975
+ }
262976
+ function sanitizeRemoteMediaGenerateRequest(input, service, configLike) {
262977
+ const parsed = parseRemoteMediaRequest(input, service.kind);
262978
+ if (!parsed.ok)
262979
+ return parsed;
262980
+ const req2 = parsed.value;
262981
+ const config = normalizeSponsorMediaConfig(configLike);
262982
+ const modality = req2.modality;
262983
+ const limits = config[modality];
262984
+ if (!limits.enabled)
262985
+ return { ok: false, reason: `${modality} sponsorship is disabled` };
262986
+ if (service.kind !== modality)
262987
+ return { ok: false, reason: `Capability ${service.capability} cannot serve ${modality}` };
262988
+ const options2 = req2.options && typeof req2.options === "object" ? { ...req2.options } : {};
262989
+ for (const key of Object.keys(options2)) {
262990
+ if (REMOTE_UNSAFE_KEYS.has(key)) {
262991
+ return { ok: false, reason: `Remote media option '${key}' is not allowed` };
262992
+ }
262993
+ }
262994
+ for (const key of LOCAL_PATH_INPUT_KEYS) {
262995
+ const value2 = options2[key];
262996
+ if (value2 === void 0)
262997
+ continue;
262998
+ if (typeof value2 !== "string")
262999
+ return { ok: false, reason: `${key} must be a URL or uploaded artifact reference` };
263000
+ if (!isSafeRemoteInputRef(value2)) {
263001
+ return { ok: false, reason: `${key} cannot reference provider-local paths` };
263002
+ }
263003
+ }
263004
+ if (Array.isArray(req2.inputs) && req2.inputs.length > 0) {
263005
+ for (const remoteInput of req2.inputs) {
263006
+ if (!remoteInput || typeof remoteInput !== "object")
263007
+ return { ok: false, reason: "Invalid remote media input" };
263008
+ if (!remoteInput.dataBase64 && !remoteInput.url)
263009
+ return { ok: false, reason: "Remote media inputs require dataBase64 or url" };
263010
+ if (remoteInput.url && !isSafeRemoteInputRef(remoteInput.url))
263011
+ return { ok: false, reason: "Remote media input URL is not allowed" };
263012
+ }
263013
+ }
263014
+ const requestedModel = req2.model || (typeof options2["model"] === "string" ? String(options2["model"]) : "");
263015
+ const serviceModel = service.model && service.model !== "auto" ? service.model : "";
263016
+ const model = serviceModel || requestedModel;
263017
+ if (serviceModel && requestedModel && requestedModel !== serviceModel) {
263018
+ return { ok: false, reason: `Capability ${service.capability} only serves model ${serviceModel}` };
263019
+ }
263020
+ if (model && limits.allowedModels !== "all" && !limits.allowedModels.includes(model)) {
263021
+ return { ok: false, reason: `Model not allowed for ${modality}: ${model}` };
263022
+ }
263023
+ const args = {
263024
+ ...options2,
263025
+ prompt: req2.prompt,
263026
+ action: "generate",
263027
+ playback: false
263028
+ };
263029
+ if (model)
263030
+ args["model"] = model;
263031
+ if (req2.backend)
263032
+ args["backend"] = req2.backend;
263033
+ if (modality === "sound" || modality === "music")
263034
+ args["kind"] = modality;
263035
+ args["fallback"] = options2["fallback"] === false ? false : true;
263036
+ const estimatedUnits = {
263037
+ inputChars: req2.prompt.length
263038
+ };
263039
+ if (modality === "image") {
263040
+ clampNumberArg(args, "width", limits.maxWidth);
263041
+ clampNumberArg(args, "height", limits.maxHeight);
263042
+ clampNumberArg(args, "steps", limits.maxSteps);
263043
+ const width = numberFrom(args["width"]);
263044
+ const height = numberFrom(args["height"]);
263045
+ if (width && height && limits.maxMegapixels && width * height / 1e6 > limits.maxMegapixels) {
263046
+ return { ok: false, reason: `Image exceeds ${limits.maxMegapixels} megapixels` };
263047
+ }
263048
+ if (width)
263049
+ estimatedUnits.width = width;
263050
+ if (height)
263051
+ estimatedUnits.height = height;
263052
+ const steps = numberFrom(args["steps"]);
263053
+ if (steps)
263054
+ estimatedUnits.steps = steps;
263055
+ } else if (modality === "video") {
263056
+ clampNumberArg(args, "width", limits.maxWidth);
263057
+ clampNumberArg(args, "height", limits.maxHeight);
263058
+ clampNumberArg(args, "duration_seconds", limits.maxDurationSec);
263059
+ clampNumberArg(args, "num_frames", limits.maxFrames);
263060
+ clampNumberArg(args, "fps", limits.maxFps);
263061
+ clampNumberArg(args, "steps", limits.maxSteps);
263062
+ const width = numberFrom(args["width"]);
263063
+ const height = numberFrom(args["height"]);
263064
+ if (width)
263065
+ estimatedUnits.width = width;
263066
+ if (height)
263067
+ estimatedUnits.height = height;
263068
+ const durationSec = numberFrom(args["duration_seconds"]);
263069
+ if (durationSec)
263070
+ estimatedUnits.durationSec = durationSec;
263071
+ const frames = numberFrom(args["num_frames"]);
263072
+ if (frames)
263073
+ estimatedUnits.frames = frames;
263074
+ const fps = numberFrom(args["fps"]);
263075
+ if (fps)
263076
+ estimatedUnits.fps = fps;
263077
+ const steps = numberFrom(args["steps"]);
263078
+ if (steps)
263079
+ estimatedUnits.steps = steps;
263080
+ } else {
263081
+ clampNumberArg(args, "duration", limits.maxDurationSec);
263082
+ clampNumberArg(args, "steps", limits.maxSteps);
263083
+ const durationSec = numberFrom(args["duration"]);
263084
+ if (durationSec)
263085
+ estimatedUnits.durationSec = durationSec;
263086
+ const steps = numberFrom(args["steps"]);
263087
+ if (steps)
263088
+ estimatedUnits.steps = steps;
263089
+ }
263090
+ return { ok: true, value: { args, estimatedUnits } };
263091
+ }
263092
+ function artifactManifestFromBytes(args) {
263093
+ const hash = createHash6("sha256").update(args.bytes).digest("hex");
263094
+ return {
263095
+ artifactId: args.artifactId,
263096
+ filename: args.filename,
263097
+ mime: args.mime,
263098
+ sizeBytes: args.bytes.byteLength,
263099
+ sha256: hash
263100
+ };
263101
+ }
263102
+ function mediaMimeFromPath(path12, modality) {
263103
+ const lc = path12.toLowerCase();
263104
+ if (lc.endsWith(".png"))
263105
+ return "image/png";
263106
+ if (lc.endsWith(".jpg") || lc.endsWith(".jpeg"))
263107
+ return "image/jpeg";
263108
+ if (lc.endsWith(".webp"))
263109
+ return "image/webp";
263110
+ if (lc.endsWith(".mp4"))
263111
+ return "video/mp4";
263112
+ if (lc.endsWith(".webm"))
263113
+ return "video/webm";
263114
+ if (lc.endsWith(".wav"))
263115
+ return "audio/wav";
263116
+ if (lc.endsWith(".mp3"))
263117
+ return "audio/mpeg";
263118
+ if (modality === "image")
263119
+ return "image/png";
263120
+ if (modality === "video")
263121
+ return "video/mp4";
263122
+ return "audio/wav";
263123
+ }
263124
+ function defaultExtensionForMime(mime) {
263125
+ if (mime === "image/png")
263126
+ return ".png";
263127
+ if (mime === "image/jpeg")
263128
+ return ".jpg";
263129
+ if (mime === "image/webp")
263130
+ return ".webp";
263131
+ if (mime === "video/mp4")
263132
+ return ".mp4";
263133
+ if (mime === "video/webm")
263134
+ return ".webm";
263135
+ if (mime === "audio/mpeg")
263136
+ return ".mp3";
263137
+ if (mime === "audio/wav" || mime === "audio/x-wav")
263138
+ return ".wav";
263139
+ return ".bin";
263140
+ }
263141
+ function parseRemoteMediaRequest(input, fallbackModality) {
263142
+ let raw = input;
263143
+ if (typeof raw === "string") {
263144
+ try {
263145
+ raw = JSON.parse(raw);
263146
+ } catch {
263147
+ raw = { prompt: raw };
263148
+ }
263149
+ }
263150
+ if (!raw || typeof raw !== "object")
263151
+ return { ok: false, reason: "Remote media request must be an object" };
263152
+ const obj = raw;
263153
+ const prompt = String(obj["prompt"] ?? "").trim();
263154
+ if (!prompt)
263155
+ return { ok: false, reason: "Remote media prompt is required" };
263156
+ const modality = String(obj["modality"] ?? fallbackModality);
263157
+ if (!SPONSOR_MEDIA_MODALITIES.includes(modality))
263158
+ return { ok: false, reason: `Unsupported media modality: ${String(obj["modality"])}` };
263159
+ return {
263160
+ ok: true,
263161
+ value: {
263162
+ modality,
263163
+ prompt,
263164
+ model: typeof obj["model"] === "string" && obj["model"].trim() ? obj["model"].trim() : void 0,
263165
+ backend: typeof obj["backend"] === "string" && obj["backend"].trim() ? obj["backend"].trim() : void 0,
263166
+ options: obj["options"] && typeof obj["options"] === "object" ? obj["options"] : void 0,
263167
+ inputs: Array.isArray(obj["inputs"]) ? obj["inputs"] : void 0,
263168
+ auth_key: typeof obj["auth_key"] === "string" ? obj["auth_key"] : void 0
263169
+ }
263170
+ };
263171
+ }
263172
+ function serializeMediaLimits(limits) {
263173
+ return {
263174
+ enabled: limits.enabled,
263175
+ allowedModels: limits.allowedModels,
263176
+ maxConcurrent: limits.maxConcurrent,
263177
+ jobsPerMinute: limits.jobsPerMinute,
263178
+ jobsPerDay: limits.jobsPerDay,
263179
+ maxOutputBytes: limits.maxOutputBytes,
263180
+ ...limits.maxWidth !== void 0 ? { maxWidth: limits.maxWidth } : {},
263181
+ ...limits.maxHeight !== void 0 ? { maxHeight: limits.maxHeight } : {},
263182
+ ...limits.maxMegapixels !== void 0 ? { maxMegapixels: limits.maxMegapixels } : {},
263183
+ ...limits.maxDurationSec !== void 0 ? { maxDurationSec: limits.maxDurationSec } : {},
263184
+ ...limits.maxFrames !== void 0 ? { maxFrames: limits.maxFrames } : {},
263185
+ ...limits.maxFps !== void 0 ? { maxFps: limits.maxFps } : {},
263186
+ ...limits.maxSteps !== void 0 ? { maxSteps: limits.maxSteps } : {}
263187
+ };
263188
+ }
263189
+ function mediaInputsFor(modality) {
263190
+ if (modality === "image")
263191
+ return ["prompt"];
263192
+ if (modality === "video")
263193
+ return ["prompt", "image", "audio_input"];
263194
+ return ["prompt"];
263195
+ }
263196
+ function mediaOutputsFor(modality) {
263197
+ if (modality === "image")
263198
+ return ["image/png", "image/jpeg", "image/webp"];
263199
+ if (modality === "video")
263200
+ return ["video/mp4"];
263201
+ return ["audio/wav", "audio/mpeg"];
263202
+ }
263203
+ function slugCapabilityPart(value2) {
263204
+ const slug = value2.trim().replace(/[^a-zA-Z0-9._-]/g, "_").replace(/^_+|_+$/g, "");
263205
+ return slug || "auto";
263206
+ }
263207
+ function booleanValue(value2, fallback) {
263208
+ if (typeof value2 === "boolean")
263209
+ return value2;
263210
+ if (typeof value2 === "string")
263211
+ return /^(1|true|yes|on)$/i.test(value2.trim());
263212
+ return fallback;
263213
+ }
263214
+ function positiveInt(value2, fallback) {
263215
+ const n2 = Number(value2);
263216
+ return Number.isFinite(n2) && n2 > 0 ? Math.floor(n2) : fallback;
263217
+ }
263218
+ function optionalPositiveInt(value2, fallback) {
263219
+ if (value2 === void 0 || value2 === null || value2 === "")
263220
+ return fallback;
263221
+ const n2 = Number(value2);
263222
+ return Number.isFinite(n2) && n2 > 0 ? Math.floor(n2) : fallback;
263223
+ }
263224
+ function optionalPositiveNumber(value2, fallback) {
263225
+ if (value2 === void 0 || value2 === null || value2 === "")
263226
+ return fallback;
263227
+ const n2 = Number(value2);
263228
+ return Number.isFinite(n2) && n2 > 0 ? n2 : fallback;
263229
+ }
263230
+ function normalizeAllowedModels(value2, fallback) {
263231
+ if (value2 === "all")
263232
+ return "all";
263233
+ if (Array.isArray(value2)) {
263234
+ const models = value2.map((item) => String(item).trim()).filter(Boolean);
263235
+ return models.length > 0 ? [...new Set(models)] : fallback;
263236
+ }
263237
+ if (typeof value2 === "string" && value2.trim()) {
263238
+ const raw = value2.trim();
263239
+ if (raw === "all")
263240
+ return "all";
263241
+ const models = raw.split(",").map((item) => item.trim()).filter(Boolean);
263242
+ return models.length > 0 ? [...new Set(models)] : fallback;
263243
+ }
263244
+ return fallback;
263245
+ }
263246
+ function clampNumberArg(args, key, max) {
263247
+ if (max === void 0)
263248
+ return;
263249
+ const value2 = numberFrom(args[key]);
263250
+ if (value2 === void 0)
263251
+ return;
263252
+ args[key] = Math.min(value2, max);
263253
+ }
263254
+ function numberFrom(value2) {
263255
+ const n2 = Number(value2);
263256
+ return Number.isFinite(n2) && n2 > 0 ? n2 : void 0;
263257
+ }
263258
+ function isSafeRemoteInputRef(value2) {
263259
+ const raw = value2.trim();
263260
+ if (!raw)
263261
+ return false;
263262
+ if (/^https?:\/\//i.test(raw))
263263
+ return true;
263264
+ if (/^data:[a-z0-9.+/-]+;base64,/i.test(raw))
263265
+ return true;
263266
+ if (/^artifact:[a-zA-Z0-9._:-]+$/.test(raw))
263267
+ return true;
263268
+ return false;
263269
+ }
263270
+ var SPONSOR_MEDIA_MODALITIES, SPONSOR_MEDIA_CAPABILITY_PREFIX, DEFAULT_SPONSOR_MEDIA_LIMITS, REMOTE_UNSAFE_KEYS, LOCAL_PATH_INPUT_KEYS;
263271
+ var init_sponsor_media = __esm({
263272
+ "packages/execution/dist/tools/sponsor-media.js"() {
263273
+ "use strict";
263274
+ SPONSOR_MEDIA_MODALITIES = ["image", "video", "sound", "music"];
263275
+ SPONSOR_MEDIA_CAPABILITY_PREFIX = "media:";
263276
+ DEFAULT_SPONSOR_MEDIA_LIMITS = {
263277
+ image: {
263278
+ enabled: false,
263279
+ allowedModels: "all",
263280
+ maxConcurrent: 1,
263281
+ jobsPerMinute: 6,
263282
+ jobsPerDay: 60,
263283
+ maxOutputBytes: 25 * 1024 * 1024,
263284
+ maxWidth: 1024,
263285
+ maxHeight: 1024,
263286
+ maxMegapixels: 1.25,
263287
+ maxSteps: 40
263288
+ },
263289
+ video: {
263290
+ enabled: false,
263291
+ allowedModels: "all",
263292
+ maxConcurrent: 1,
263293
+ jobsPerMinute: 2,
263294
+ jobsPerDay: 12,
263295
+ maxOutputBytes: 250 * 1024 * 1024,
263296
+ maxWidth: 1280,
263297
+ maxHeight: 720,
263298
+ maxDurationSec: 8,
263299
+ maxFrames: 129,
263300
+ maxFps: 24,
263301
+ maxSteps: 50
263302
+ },
263303
+ sound: {
263304
+ enabled: false,
263305
+ allowedModels: "all",
263306
+ maxConcurrent: 1,
263307
+ jobsPerMinute: 4,
263308
+ jobsPerDay: 40,
263309
+ maxOutputBytes: 50 * 1024 * 1024,
263310
+ maxDurationSec: 15,
263311
+ maxSteps: 50
263312
+ },
263313
+ music: {
263314
+ enabled: false,
263315
+ allowedModels: "all",
263316
+ maxConcurrent: 1,
263317
+ jobsPerMinute: 2,
263318
+ jobsPerDay: 20,
263319
+ maxOutputBytes: 80 * 1024 * 1024,
263320
+ maxDurationSec: 30,
263321
+ maxSteps: 80
263322
+ }
263323
+ };
263324
+ REMOTE_UNSAFE_KEYS = /* @__PURE__ */ new Set([
263325
+ "action",
263326
+ "setup",
263327
+ "prewarm",
263328
+ "prepare",
263329
+ "pull",
263330
+ "python",
263331
+ "hf_token",
263332
+ "model_path",
263333
+ "playback"
263334
+ ]);
263335
+ LOCAL_PATH_INPUT_KEYS = /* @__PURE__ */ new Set([
263336
+ "image",
263337
+ "image_path",
263338
+ "init_image",
263339
+ "source_image",
263340
+ "reference_image",
263341
+ "audio_input"
263342
+ ]);
263343
+ }
263344
+ });
263345
+
262584
263346
  // packages/execution/dist/tools/structured-read.js
262585
263347
  import { readFile as readFile15, stat as stat5 } from "node:fs/promises";
262586
263348
  import { resolve as resolve21, extname as extname5 } from "node:path";
@@ -265923,7 +266685,7 @@ import { execSync as execSync23, exec as execCb, spawnSync as spawnSync4 } from
265923
266685
  import { readFile as readFile16, writeFile as writeFile20, mkdir as mkdir15 } from "node:fs/promises";
265924
266686
  import { resolve as resolve28, join as join48 } from "node:path";
265925
266687
  import { homedir as homedir13 } from "node:os";
265926
- import { randomBytes as randomBytes12, createHash as createHash6 } from "node:crypto";
266688
+ import { randomBytes as randomBytes12, createHash as createHash7 } from "node:crypto";
265927
266689
  function isValidCron(expr) {
265928
266690
  const parts = expr.trim().split(/\s+/);
265929
266691
  if (parts.length !== 5)
@@ -266359,7 +267121,7 @@ var init_scheduler = __esm({
266359
267121
  }
266360
267122
  const scope = String(args["scope"] ?? "local");
266361
267123
  const fingerprint = `${resolve28(this.workingDir)}|${task}|${cronExpr}|${scope}`;
266362
- const id = `sched-${createHash6("sha1").update(fingerprint).digest("hex").slice(0, 8)}`;
267124
+ const id = `sched-${createHash7("sha1").update(fingerprint).digest("hex").slice(0, 8)}`;
266363
267125
  const oneShot = Boolean(args["one_shot"]);
266364
267126
  const maxRuns = typeof args["max_runs"] === "number" ? args["max_runs"] : void 0;
266365
267127
  const newTask = {
@@ -270515,7 +271277,7 @@ var init_import_graph = __esm({
270515
271277
  import { createRequire as __createRequireGlob } from "node:module";
270516
271278
  import ignore from "ignore";
270517
271279
  import { readFile as readFile21, stat as stat6 } from "node:fs/promises";
270518
- import { createHash as createHash7 } from "node:crypto";
271280
+ import { createHash as createHash8 } from "node:crypto";
270519
271281
  import { join as join56, relative as relative5, extname as extname8, basename as basename13 } from "node:path";
270520
271282
  var __requireGlob, glob2, DEFAULT_EXCLUDE, LANGUAGE_MAP, CodebaseIndexer;
270521
271283
  var init_codebase_indexer = __esm({
@@ -270583,7 +271345,7 @@ var init_codebase_indexer = __esm({
270583
271345
  if (fileStat.size > this.config.maxFileSize)
270584
271346
  continue;
270585
271347
  const content = await readFile21(fullPath);
270586
- const hash = createHash7("sha256").update(content).digest("hex");
271348
+ const hash = createHash8("sha256").update(content).digest("hex");
270587
271349
  const ext = extname8(relativePath);
270588
271350
  indexed.push({
270589
271351
  path: fullPath,
@@ -410087,9 +410849,9 @@ ${lanes.join("\n")}
410087
410849
  /*ignoreCase*/
410088
410850
  false
410089
410851
  )) {
410090
- const basename34 = getBaseFileName(a2.fileName);
410091
- if (basename34 === "lib.d.ts" || basename34 === "lib.es6.d.ts") return 0;
410092
- const name10 = removeSuffix(removePrefix(basename34, "lib."), ".d.ts");
410852
+ const basename35 = getBaseFileName(a2.fileName);
410853
+ if (basename35 === "lib.d.ts" || basename35 === "lib.es6.d.ts") return 0;
410854
+ const name10 = removeSuffix(removePrefix(basename35, "lib."), ".d.ts");
410093
410855
  const index = libs.indexOf(name10);
410094
410856
  if (index !== -1) return index + 1;
410095
410857
  }
@@ -474015,8 +474777,8 @@ ${options2.prefix}` : "\n" : options2.prefix
474015
474777
  }
474016
474778
  };
474017
474779
  for (const file of files) {
474018
- const basename34 = getBaseFileName(file);
474019
- if (basename34 === "package.json" || basename34 === "bower.json") {
474780
+ const basename35 = getBaseFileName(file);
474781
+ if (basename35 === "package.json" || basename35 === "bower.json") {
474020
474782
  createProjectWatcher(
474021
474783
  file,
474022
474784
  "FileWatcher"
@@ -477700,8 +478462,8 @@ All files are: ${JSON.stringify(names)}`,
477700
478462
  var _a;
477701
478463
  const fileOrDirectoryPath = removeIgnoredPath(this.toPath(fileOrDirectory));
477702
478464
  if (!fileOrDirectoryPath) return;
477703
- const basename34 = getBaseFileName(fileOrDirectoryPath);
477704
- if (((_a = result.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.size) && (basename34 === "package.json" || basename34 === "node_modules")) {
478465
+ const basename35 = getBaseFileName(fileOrDirectoryPath);
478466
+ if (((_a = result.affectedModuleSpecifierCacheProjects) == null ? void 0 : _a.size) && (basename35 === "package.json" || basename35 === "node_modules")) {
477705
478467
  result.affectedModuleSpecifierCacheProjects.forEach((project) => {
477706
478468
  var _a2;
477707
478469
  (_a2 = project.getModuleSpecifierCache()) == null ? void 0 : _a2.clear();
@@ -486582,7 +487344,7 @@ var require_path_browserify = __commonJS({
486582
487344
  _makeLong: function _makeLong(path12) {
486583
487345
  return path12;
486584
487346
  },
486585
- dirname: function dirname43(path12) {
487347
+ dirname: function dirname44(path12) {
486586
487348
  assertPath(path12);
486587
487349
  if (path12.length === 0) return ".";
486588
487350
  var code8 = path12.charCodeAt(0);
@@ -486604,7 +487366,7 @@ var require_path_browserify = __commonJS({
486604
487366
  if (hasRoot && end === 1) return "//";
486605
487367
  return path12.slice(0, end);
486606
487368
  },
486607
- basename: function basename34(path12, ext) {
487369
+ basename: function basename35(path12, ext) {
486608
487370
  if (ext !== void 0 && typeof ext !== "string") throw new TypeError('"ext" argument must be a string');
486609
487371
  assertPath(path12);
486610
487372
  var start2 = 0;
@@ -514895,7 +515657,7 @@ var init_ts_morph_parser = __esm({
514895
515657
 
514896
515658
  // packages/indexer/dist/code-graph-db.js
514897
515659
  import { createRequire as createRequire2 } from "node:module";
514898
- import { createHash as createHash8 } from "node:crypto";
515660
+ import { createHash as createHash9 } from "node:crypto";
514899
515661
  import { mkdirSync as mkdirSync16, readFileSync as readFileSync30 } from "node:fs";
514900
515662
  import { join as join57, dirname as dirname14, extname as extname9 } from "node:path";
514901
515663
  function loadDatabaseCtor() {
@@ -514967,7 +515729,7 @@ function extractFileImports(content, filePath) {
514967
515729
  return imports.map((p2) => p2.replace(/\.(js|ts|jsx|tsx|mjs|cjs)$/, ""));
514968
515730
  }
514969
515731
  function hashContent(content) {
514970
- return createHash8("sha1").update(content).digest("hex").slice(0, 16);
515732
+ return createHash9("sha1").update(content).digest("hex").slice(0, 16);
514971
515733
  }
514972
515734
  function detectLanguage(filePath) {
514973
515735
  return EXT_TO_LANG[extname9(filePath)] ?? "unknown";
@@ -523476,7 +524238,7 @@ var init_client3 = __esm({
523476
524238
  import { existsSync as existsSync53, readFileSync as readFileSync39, writeFileSync as writeFileSync24, mkdirSync as mkdirSync27, chmodSync, statSync as statSync24 } from "node:fs";
523477
524239
  import { join as join69, dirname as dirname16 } from "node:path";
523478
524240
  import { homedir as homedir22 } from "node:os";
523479
- import { randomBytes as randomBytes18, createHash as createHash9 } from "node:crypto";
524241
+ import { randomBytes as randomBytes18, createHash as createHash10 } from "node:crypto";
523480
524242
  function secretsPath(scope, repoRoot) {
523481
524243
  return scope === "global" ? join69(homedir22(), ".omnius", "secrets.json") : join69(repoRoot, ".omnius", "secrets.json");
523482
524244
  }
@@ -523517,7 +524279,7 @@ function sanitizeHint(hint) {
523517
524279
  return hint.toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 32) || "GENERIC";
523518
524280
  }
523519
524281
  function shortDigest(value2) {
523520
- return createHash9("sha256").update(value2).digest("hex").slice(0, 6);
524282
+ return createHash10("sha256").update(value2).digest("hex").slice(0, 6);
523521
524283
  }
523522
524284
  function randomSuffix() {
523523
524285
  return randomBytes18(3).toString("hex");
@@ -525213,7 +525975,7 @@ var init_environment_snapshot = __esm({
525213
525975
  import { execSync as execSync43 } from "node:child_process";
525214
525976
  import { existsSync as existsSync57, mkdirSync as mkdirSync29, writeFileSync as writeFileSync27, readFileSync as readFileSync43, readdirSync as readdirSync20, unlinkSync as unlinkSync12 } from "node:fs";
525215
525977
  import { join as join72, basename as basename15 } from "node:path";
525216
- import { createHash as createHash10 } from "node:crypto";
525978
+ import { createHash as createHash11 } from "node:crypto";
525217
525979
  function isYouTubeUrl2(url) {
525218
525980
  return /(?:youtube\.com\/(?:watch|shorts|live|embed|v\/)|youtu\.be\/)/i.test(url);
525219
525981
  }
@@ -525241,7 +526003,7 @@ function ensureFfmpeg() {
525241
526003
  function imageHash(imagePath) {
525242
526004
  try {
525243
526005
  const data = readFileSync43(imagePath);
525244
- return createHash10("md5").update(data).digest("hex").slice(0, 12);
526006
+ return createHash11("md5").update(data).digest("hex").slice(0, 12);
525245
526007
  } catch {
525246
526008
  return "unknown";
525247
526009
  }
@@ -526897,6 +527659,7 @@ __export(dist_exports, {
526897
527659
  DEFAULT_MUSIC_MODEL: () => DEFAULT_MUSIC_MODEL,
526898
527660
  DEFAULT_OLLAMA_IMAGE_MODEL: () => DEFAULT_OLLAMA_IMAGE_MODEL,
526899
527661
  DEFAULT_SOUND_MODEL: () => DEFAULT_SOUND_MODEL,
527662
+ DEFAULT_SPONSOR_MEDIA_LIMITS: () => DEFAULT_SPONSOR_MEDIA_LIMITS,
526900
527663
  DESKTOP_DEPS: () => DESKTOP_DEPS,
526901
527664
  DebateTool: () => DebateTool,
526902
527665
  DesktopClickTool: () => DesktopClickTool,
@@ -526959,6 +527722,8 @@ __export(dist_exports, {
526959
527722
  ReplTool: () => ReplTool,
526960
527723
  ReplayWithInterventionTool: () => ReplayWithInterventionTool,
526961
527724
  RepoMapTool: () => RepoMapTool,
527725
+ SPONSOR_MEDIA_CAPABILITY_PREFIX: () => SPONSOR_MEDIA_CAPABILITY_PREFIX,
527726
+ SPONSOR_MEDIA_MODALITIES: () => SPONSOR_MEDIA_MODALITIES,
526962
527727
  SchedulerTool: () => SchedulerTool,
526963
527728
  ScreenshotTool: () => ScreenshotTool,
526964
527729
  SdrScanTool: () => SdrScanTool,
@@ -527005,6 +527770,7 @@ __export(dist_exports, {
527005
527770
  aliasTool: () => aliasTool,
527006
527771
  applyPatch: () => applyPatch,
527007
527772
  applyToolResultTriage: () => applyToolResultTriage,
527773
+ artifactManifestFromBytes: () => artifactManifestFromBytes,
527008
527774
  audioGenerationDir: () => audioGenerationDir,
527009
527775
  audioGenerationSetupPlan: () => audioGenerationSetupPlan,
527010
527776
  audioGenerationVenvDir: () => audioGenerationVenvDir,
@@ -527018,6 +527784,7 @@ __export(dist_exports, {
527018
527784
  buildMcpToolName: () => buildMcpToolName,
527019
527785
  buildScaffoldedPrompt: () => buildScaffoldedPrompt,
527020
527786
  buildSkillsSummary: () => buildSkillsSummary,
527787
+ buildSponsorMediaServices: () => buildSponsorMediaServices,
527021
527788
  buildSubProcessArgs: () => buildSubProcessArgs,
527022
527789
  buildToolManifestFromModule: () => buildToolManifestFromModule,
527023
527790
  canInvokeTool: () => canInvokeTool,
@@ -527037,6 +527804,7 @@ __export(dist_exports, {
527037
527804
  createTransport: () => createTransport,
527038
527805
  createWorktree: () => createWorktree2,
527039
527806
  defaultExposureForTool: () => defaultExposureForTool,
527807
+ defaultExtensionForMime: () => defaultExtensionForMime,
527040
527808
  deleteTodos: () => deleteTodos,
527041
527809
  detectElevationMethod: () => detectElevationMethod,
527042
527810
  detectLegacyCaches: () => detectLegacyCaches,
@@ -527128,14 +527896,17 @@ __export(dist_exports, {
527128
527896
  markReverted: () => markReverted,
527129
527897
  markSessionValidated: () => markSessionValidated,
527130
527898
  measureRepoCacheBytes: () => measureRepoCacheBytes,
527899
+ mediaMimeFromPath: () => mediaMimeFromPath,
527131
527900
  migrateLegacyCaches: () => migrateLegacyCaches,
527132
527901
  networkEgressErrorMessage: () => networkEgressErrorMessage,
527133
527902
  normalizeMcpName: () => normalizeMcpName,
527134
527903
  normalizeNetworkHostname: () => normalizeNetworkHostname,
527904
+ normalizeSponsorMediaConfig: () => normalizeSponsorMediaConfig,
527135
527905
  omniusHomeDir: () => omniusHomeDir,
527136
527906
  packetPath: () => packetPath,
527137
527907
  parseMcpMarkdown: () => parseMcpMarkdown,
527138
527908
  parseMcpToolName: () => parseMcpToolName,
527909
+ parseSponsorMediaCapability: () => parseSponsorMediaCapability,
527139
527910
  playSoundFile: () => playSoundFile,
527140
527911
  promoteWorkingNotes: () => promoteWorkingNotes,
527141
527912
  quarantineSecret: () => quarantineSecret,
@@ -527166,6 +527937,7 @@ __export(dist_exports, {
527166
527937
  runTypecheck: () => runTypecheck,
527167
527938
  runValidationPipeline: () => runValidationPipeline,
527168
527939
  sanitizeReminderDeliveryText: () => sanitizeReminderDeliveryText,
527940
+ sanitizeRemoteMediaGenerateRequest: () => sanitizeRemoteMediaGenerateRequest,
527169
527941
  saveCustomToolDefinition: () => saveCustomToolDefinition,
527170
527942
  saveMcpServerToConfig: () => saveMcpServerToConfig,
527171
527943
  savePacket: () => savePacket,
@@ -527179,6 +527951,7 @@ __export(dist_exports, {
527179
527951
  sha256Text: () => sha256Text,
527180
527952
  shannonEntropy: () => shannonEntropy,
527181
527953
  spawnFullSubAgent: () => spawnFullSubAgent,
527954
+ sponsorMediaCapabilityName: () => sponsorMediaCapabilityName,
527182
527955
  stableJson: () => stableJson,
527183
527956
  stopFullSubAgent: () => stopFullSubAgent,
527184
527957
  summarizeLog: () => summarizeLog,
@@ -527266,6 +528039,7 @@ var init_dist5 = __esm({
527266
528039
  init_audio_generate();
527267
528040
  init_model_store();
527268
528041
  init_video_generate();
528042
+ init_sponsor_media();
527269
528043
  init_structured_read();
527270
528044
  init_vision();
527271
528045
  init_desktop_click();
@@ -531825,14 +532599,14 @@ var init_artifact_inspector = __esm({
531825
532599
  // packages/orchestrator/dist/lesson-bank.js
531826
532600
  import { existsSync as existsSync66, mkdirSync as mkdirSync32, appendFileSync as appendFileSync2, readFileSync as readFileSync51 } from "node:fs";
531827
532601
  import { join as join79, dirname as dirname22 } from "node:path";
531828
- import { createHash as createHash11 } from "node:crypto";
532602
+ import { createHash as createHash12 } from "node:crypto";
531829
532603
  function tokenize2(text) {
531830
532604
  if (!text)
531831
532605
  return [];
531832
532606
  return text.toLowerCase().split(TOKENIZE_RE).filter((t2) => t2.length >= 3).slice(0, 80);
531833
532607
  }
531834
532608
  function shortHash(s2) {
531835
- return createHash11("sha256").update(s2).digest("hex").slice(0, 16);
532609
+ return createHash12("sha256").update(s2).digest("hex").slice(0, 16);
531836
532610
  }
531837
532611
  function solicit(args) {
531838
532612
  const { taskGoal, stem, reflections, successOutputPreview } = args;
@@ -535457,7 +536231,7 @@ var init_pprRetrieval = __esm({
535457
536231
  import { join as join85 } from "node:path";
535458
536232
  import { mkdirSync as mkdirSync34, existsSync as existsSync72 } from "node:fs";
535459
536233
  import { randomUUID as randomUUID8 } from "node:crypto";
535460
- import { createHash as createHash12 } from "node:crypto";
536234
+ import { createHash as createHash13 } from "node:crypto";
535461
536235
  function readEpisodeAffect2(metadata) {
535462
536236
  if (!metadata || typeof metadata !== "object")
535463
536237
  return null;
@@ -535675,7 +536449,7 @@ var init_episodeStore = __esm({
535675
536449
  insert(ep) {
535676
536450
  const id = randomUUID8();
535677
536451
  const now = Date.now();
535678
- const contentHash2 = createHash12("sha256").update(ep.content).digest("hex").slice(0, 16);
536452
+ const contentHash2 = createHash13("sha256").update(ep.content).digest("hex").slice(0, 16);
535679
536453
  const modality = ep.modality ?? "text";
535680
536454
  const rawImportance = ep.importance ?? autoImportance(ep.toolName ?? null, modality, ep.content);
535681
536455
  const modulated = ep.emotionalState ? modulateImportance(sanitizeImportance(rawImportance), ep.emotionalState) : sanitizeImportance(rawImportance);
@@ -536209,9 +536983,9 @@ var init_temporalGraph = __esm({
536209
536983
  });
536210
536984
 
536211
536985
  // packages/memory/dist/multimodalIdentity.js
536212
- import { createHash as createHash13 } from "node:crypto";
536986
+ import { createHash as createHash14 } from "node:crypto";
536213
536987
  function stableHash(value2) {
536214
- return createHash13("sha256").update(value2).digest("hex").slice(0, 24);
536988
+ return createHash14("sha256").update(value2).digest("hex").slice(0, 24);
536215
536989
  }
536216
536990
  function normalizeAtom(value2) {
536217
536991
  return value2.trim().toLowerCase().replace(/\s+/g, " ");
@@ -536568,9 +537342,9 @@ var init_gistCompressor = __esm({
536568
537342
  });
536569
537343
 
536570
537344
  // packages/memory/dist/graphWalk.js
536571
- import { createHash as createHash14 } from "node:crypto";
537345
+ import { createHash as createHash15 } from "node:crypto";
536572
537346
  function seededUnit(seed) {
536573
- const digest3 = createHash14("sha256").update(seed || "graph-walk").digest();
537347
+ const digest3 = createHash15("sha256").update(seed || "graph-walk").digest();
536574
537348
  const value2 = digest3.readUInt32BE(0);
536575
537349
  return value2 / 4294967295;
536576
537350
  }
@@ -540701,7 +541475,7 @@ var init_memoryStageContext = __esm({
540701
541475
  });
540702
541476
 
540703
541477
  // packages/memory/dist/sessionGist.js
540704
- import { createHash as createHash15 } from "node:crypto";
541478
+ import { createHash as createHash16 } from "node:crypto";
540705
541479
  function inferDomain(input) {
540706
541480
  const blob = [
540707
541481
  input.goal,
@@ -540726,7 +541500,7 @@ function inferDomain(input) {
540726
541500
  return ranked[0][0];
540727
541501
  }
540728
541502
  function computeGoalHash(goal) {
540729
- return createHash15("sha256").update(goal.trim().toLowerCase()).digest("hex").slice(0, 16);
541503
+ return createHash16("sha256").update(goal.trim().toLowerCase()).digest("hex").slice(0, 16);
540730
541504
  }
540731
541505
  function clip(text, n2) {
540732
541506
  if (!text)
@@ -540937,12 +541711,12 @@ var init_toolOutcomes = __esm({
540937
541711
  });
540938
541712
 
540939
541713
  // packages/memory/dist/stagnationRecipes.js
540940
- import { createHash as createHash16 } from "node:crypto";
541714
+ import { createHash as createHash17 } from "node:crypto";
540941
541715
  function fingerprintSignature(fp) {
540942
541716
  const normClusters = (fp.errorClusters ?? []).map((s2) => (s2 || "").toLowerCase().replace(/[0-9]+/g, "N").replace(/\s+/g, " ").trim()).filter(Boolean).sort();
540943
541717
  const tool = (fp.stuckTool ?? "").toLowerCase().trim();
540944
541718
  const blob = `tool=${tool};clusters=${normClusters.join("|")}`;
540945
- return createHash16("sha256").update(blob).digest("hex").slice(0, 16);
541719
+ return createHash17("sha256").update(blob).digest("hex").slice(0, 16);
540946
541720
  }
540947
541721
  function crystallize(store2, input) {
540948
541722
  const sig = fingerprintSignature(input.fingerprint);
@@ -540999,7 +541773,7 @@ var init_stagnationRecipes = __esm({
540999
541773
  });
541000
541774
 
541001
541775
  // packages/memory/dist/codebaseMap.js
541002
- import { createHash as createHash17, randomUUID as randomUUID12 } from "node:crypto";
541776
+ import { createHash as createHash18, randomUUID as randomUUID12 } from "node:crypto";
541003
541777
  function freshNodeId() {
541004
541778
  return randomUUID12();
541005
541779
  }
@@ -541013,7 +541787,7 @@ var init_codebaseMap = __esm({
541013
541787
  touchCount = /* @__PURE__ */ new Map();
541014
541788
  constructor(db, repoRoot, commitSha) {
541015
541789
  this.db = db;
541016
- this.repoFp = createHash17("sha256").update(`${repoRoot}::${commitSha ?? "no-commit"}`).digest("hex").slice(0, 16);
541790
+ this.repoFp = createHash18("sha256").update(`${repoRoot}::${commitSha ?? "no-commit"}`).digest("hex").slice(0, 16);
541017
541791
  this.ensureSchema();
541018
541792
  }
541019
541793
  ensureSchema() {
@@ -541195,7 +541969,7 @@ var init_codebaseMap = __esm({
541195
541969
  }
541196
541970
  /** Stable composite id: `<kind>:<sha16(path)>` so insert ON CONFLICT works. */
541197
541971
  idFor(kind, path12) {
541198
- const h = createHash17("sha256").update(`${this.repoFp}:${kind}:${path12}`).digest("hex").slice(0, 24);
541972
+ const h = createHash18("sha256").update(`${this.repoFp}:${kind}:${path12}`).digest("hex").slice(0, 24);
541199
541973
  return `${kind}-${h}`;
541200
541974
  }
541201
541975
  };
@@ -543706,7 +544480,7 @@ import { existsSync as existsSync80, readFileSync as readFileSync62, statSync as
543706
544480
  import { execSync as execSync46 } from "node:child_process";
543707
544481
  import { homedir as homedir29, platform as platform3, arch as arch2, totalmem as totalmem3, freemem as freemem3, hostname as hostname3 } from "node:os";
543708
544482
  import { join as join93 } from "node:path";
543709
- import { createHash as createHash18 } from "node:crypto";
544483
+ import { createHash as createHash19 } from "node:crypto";
543710
544484
  function capturePreflightSnapshot(workingDir) {
543711
544485
  const warnings = [];
543712
544486
  const configFingerprints = {};
@@ -543873,7 +544647,7 @@ function expandPath(p2) {
543873
544647
  return p2;
543874
544648
  }
543875
544649
  function sha2563(s2) {
543876
- return createHash18("sha256").update(s2).digest("hex").slice(0, 16);
544650
+ return createHash19("sha256").update(s2).digest("hex").slice(0, 16);
543877
544651
  }
543878
544652
  function freeDiskBytes(path12 = "/tmp") {
543879
544653
  try {
@@ -550135,8 +550909,8 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
550135
550909
  if (process.env["OMNIUS_DISABLE_ADAPTIVE_RETRIEVAL"] !== "1") {
550136
550910
  const goalForSig = (this._taskState.goal || "").slice(0, 200);
550137
550911
  const recentTools = this._toolSequence.slice(-5).join("|");
550138
- const { createHash: createHash32 } = await import("node:crypto");
550139
- const sig = createHash32("sha256").update(`${goalForSig}::${recentTools}`).digest("hex").slice(0, 16);
550912
+ const { createHash: createHash34 } = await import("node:crypto");
550913
+ const sig = createHash34("sha256").update(`${goalForSig}::${recentTools}`).digest("hex").slice(0, 16);
550140
550914
  if (this._lastPprSig === sig && this._lastPprMemoryLines.length > 0) {
550141
550915
  compacted.push({
550142
550916
  role: "system",
@@ -563592,10 +564366,10 @@ transcribe-cli error: ${transcribeCliError}` : "";
563592
564366
  wordTimestamps: false
563593
564367
  });
563594
564368
  if (outputDir) {
563595
- const { basename: basename34 } = await import("node:path");
564369
+ const { basename: basename35 } = await import("node:path");
563596
564370
  const transcriptDir = join102(outputDir, ".omnius", "transcripts");
563597
564371
  mkdirSync48(transcriptDir, { recursive: true });
563598
- const outFile = join102(transcriptDir, `${basename34(filePath)}.txt`);
564372
+ const outFile = join102(transcriptDir, `${basename35(filePath)}.txt`);
563599
564373
  writeFileSync43(outFile, result.text, "utf-8");
563600
564374
  }
563601
564375
  return {
@@ -563611,10 +564385,10 @@ transcribe-cli error: ${transcribeCliError}` : "";
563611
564385
  const fb = await transcribeFileViaWhisper(filePath, this.config.model);
563612
564386
  if (fb) {
563613
564387
  if (outputDir) {
563614
- const { basename: basename34 } = await import("node:path");
564388
+ const { basename: basename35 } = await import("node:path");
563615
564389
  const transcriptDir = join102(outputDir, ".omnius", "transcripts");
563616
564390
  mkdirSync48(transcriptDir, { recursive: true });
563617
- const outFile = join102(transcriptDir, `${basename34(filePath)}.txt`);
564391
+ const outFile = join102(transcriptDir, `${basename35(filePath)}.txt`);
563618
564392
  writeFileSync43(outFile, fb.text, "utf-8");
563619
564393
  }
563620
564394
  return fb;
@@ -565862,7 +566636,7 @@ var require_websocket3 = __commonJS({
565862
566636
  var http6 = __require("http");
565863
566637
  var net5 = __require("net");
565864
566638
  var tls2 = __require("tls");
565865
- var { randomBytes: randomBytes29, createHash: createHash32 } = __require("crypto");
566639
+ var { randomBytes: randomBytes29, createHash: createHash34 } = __require("crypto");
565866
566640
  var { Duplex: Duplex3, Readable } = __require("stream");
565867
566641
  var { URL: URL3 } = __require("url");
565868
566642
  var PerMessageDeflate3 = require_permessage_deflate3();
@@ -566522,7 +567296,7 @@ var require_websocket3 = __commonJS({
566522
567296
  abortHandshake(websocket, socket, "Invalid Upgrade header");
566523
567297
  return;
566524
567298
  }
566525
- const digest3 = createHash32("sha1").update(key + GUID).digest("base64");
567299
+ const digest3 = createHash34("sha1").update(key + GUID).digest("base64");
566526
567300
  if (res.headers["sec-websocket-accept"] !== digest3) {
566527
567301
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
566528
567302
  return;
@@ -566889,7 +567663,7 @@ var require_websocket_server2 = __commonJS({
566889
567663
  var EventEmitter15 = __require("events");
566890
567664
  var http6 = __require("http");
566891
567665
  var { Duplex: Duplex3 } = __require("stream");
566892
- var { createHash: createHash32 } = __require("crypto");
567666
+ var { createHash: createHash34 } = __require("crypto");
566893
567667
  var extension3 = require_extension3();
566894
567668
  var PerMessageDeflate3 = require_permessage_deflate3();
566895
567669
  var subprotocol3 = require_subprotocol2();
@@ -567190,7 +567964,7 @@ var require_websocket_server2 = __commonJS({
567190
567964
  );
567191
567965
  }
567192
567966
  if (this._state > RUNNING) return abortHandshake(socket, 503);
567193
- const digest3 = createHash32("sha1").update(key + GUID).digest("base64");
567967
+ const digest3 = createHash34("sha1").update(key + GUID).digest("base64");
567194
567968
  const headers = [
567195
567969
  "HTTP/1.1 101 Switching Protocols",
567196
567970
  "Upgrade: websocket",
@@ -567943,6 +568717,10 @@ var init_command_registry = __esm({
567943
568717
  ["/ipfs import <cid>", "Import a shared IPFS tool or skill reference"],
567944
568718
  ["/sponsor", "Sponsor inference - onboarding wizard or dashboard"],
567945
568719
  ["/sponsor status", "Show sponsor dashboard with usage metrics"],
568720
+ ["/sponsor image <prompt>", "Generate an image on a sponsored peer"],
568721
+ ["/sponsor video <prompt>", "Generate a video on a sponsored peer"],
568722
+ ["/sponsor sound <prompt>", "Generate a sound effect on a sponsored peer"],
568723
+ ["/sponsor music <prompt>", "Generate music on a sponsored peer"],
567946
568724
  ["/sponsor pause", "Pause active sponsorship"],
567947
568725
  ["/sponsor remove", "Remove sponsorship entirely"],
567948
568726
  ["/endpoint sponsor", "Browse and connect to sponsored inference from the nexus mesh"],
@@ -571976,14 +572754,14 @@ var init_voice_session = __esm({
571976
572754
  });
571977
572755
 
571978
572756
  // packages/cli/src/tui/scoped-personality.ts
571979
- import { createHash as createHash19 } from "node:crypto";
572757
+ import { createHash as createHash20 } from "node:crypto";
571980
572758
  import { appendFileSync as appendFileSync5, existsSync as existsSync88, mkdirSync as mkdirSync49, readFileSync as readFileSync69, writeFileSync as writeFileSync44 } from "node:fs";
571981
572759
  import { join as join103, resolve as resolve39 } from "node:path";
571982
572760
  function safeName(input) {
571983
572761
  return input.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 80) || "default";
571984
572762
  }
571985
572763
  function scopeHash(scope) {
571986
- return createHash19("sha1").update(`${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
572764
+ return createHash20("sha1").update(`${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
571987
572765
  }
571988
572766
  function scopedPersonalityDir(repoRoot, kind) {
571989
572767
  return resolve39(repoRoot, ".omnius", "scoped-personality", kind);
@@ -572314,7 +573092,7 @@ var init_scoped_personality = __esm({
572314
573092
  });
572315
573093
 
572316
573094
  // packages/cli/src/tui/voice-soul.ts
572317
- import { createHash as createHash20 } from "node:crypto";
573095
+ import { createHash as createHash21 } from "node:crypto";
572318
573096
  import { existsSync as existsSync89, readdirSync as readdirSync29, readFileSync as readFileSync70 } from "node:fs";
572319
573097
  import { basename as basename20, join as join104, resolve as resolve40 } from "node:path";
572320
573098
  function compactText(text, limit) {
@@ -572329,7 +573107,7 @@ function blockText(text, limit) {
572329
573107
  ... [truncated]`;
572330
573108
  }
572331
573109
  function scopeStateKey(scope, surface) {
572332
- return createHash20("sha1").update(`${surface}:${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
573110
+ return createHash21("sha1").update(`${surface}:${scope.kind}:${scope.id}`).digest("hex").slice(0, 16);
572333
573111
  }
572334
573112
  function safeName2(input) {
572335
573113
  return input.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 80) || "default";
@@ -572857,6 +573635,26 @@ function serializeSponsorModels(stats) {
572857
573635
  (a2, b) => (b.tokensIn + b.tokensOut || b.requests) - (a2.tokensIn + a2.tokensOut || a2.requests)
572858
573636
  );
572859
573637
  }
573638
+ function parseMediaUsageKey(key) {
573639
+ const [rawModality, ...modelParts] = key.split(":");
573640
+ const modality = SPONSOR_MEDIA_MODALITIES.includes(rawModality) ? rawModality : "image";
573641
+ return { modality, model: modelParts.join(":") || "auto" };
573642
+ }
573643
+ function serializeSponsorMedia(stats) {
573644
+ return Array.from(stats.mediaUsage.entries()).map(([key, meter]) => {
573645
+ const parsed = parseMediaUsageKey(key);
573646
+ return {
573647
+ key,
573648
+ modality: parsed.modality,
573649
+ model: parsed.model,
573650
+ jobs: meter.jobs,
573651
+ bytesOut: meter.bytesOut,
573652
+ failures: meter.failures,
573653
+ avgLatencyMs: meter.jobs > 0 ? Math.round(meter.totalLatencyMs / meter.jobs) : 0,
573654
+ lastUsed: meter.lastUsed
573655
+ };
573656
+ }).sort((a2, b) => (b.jobs || b.bytesOut) - (a2.jobs || a2.bytesOut));
573657
+ }
572860
573658
  function serializeSponsorPeers(stats) {
572861
573659
  return Array.from(stats.users.values()).map((user) => ({
572862
573660
  peer: user.ip,
@@ -572872,7 +573670,20 @@ function serializeSponsorPeers(stats) {
572872
573670
  tokensIn: meter.tokensIn,
572873
573671
  tokensOut: meter.tokensOut,
572874
573672
  lastUsed: meter.lastUsed
572875
- })).sort((a2, b) => b.tokensIn + b.tokensOut - (a2.tokensIn + a2.tokensOut))
573673
+ })).sort((a2, b) => b.tokensIn + b.tokensOut - (a2.tokensIn + a2.tokensOut)),
573674
+ media: Array.from(user.media.entries()).map(([key, meter]) => {
573675
+ const parsed = parseMediaUsageKey(key);
573676
+ return {
573677
+ key,
573678
+ modality: parsed.modality,
573679
+ model: parsed.model,
573680
+ jobs: meter.jobs,
573681
+ bytesOut: meter.bytesOut,
573682
+ failures: meter.failures,
573683
+ avgLatencyMs: meter.jobs > 0 ? Math.round(meter.totalLatencyMs / meter.jobs) : 0,
573684
+ lastUsed: meter.lastUsed
573685
+ };
573686
+ }).sort((a2, b) => (b.jobs || b.bytesOut) - (a2.jobs || a2.bytesOut))
572876
573687
  })).sort((a2, b) => (b.tokensIn + b.tokensOut || b.requests) - (a2.tokensIn + a2.tokensOut || a2.requests));
572877
573688
  }
572878
573689
  function nextSponsorDailyReset(now = Date.now()) {
@@ -573070,6 +573881,7 @@ var HOP_BY_HOP_HEADERS, CF_HEADERS_PREFIX, DEFAULT_EXPOSE_MAX_BODY_BYTES, INTERN
573070
573881
  var init_expose = __esm({
573071
573882
  "packages/cli/src/tui/expose.ts"() {
573072
573883
  "use strict";
573884
+ init_dist5();
573073
573885
  init_render();
573074
573886
  init_usage_bars();
573075
573887
  init_typed_node_events();
@@ -573155,6 +573967,7 @@ var init_expose = __esm({
573155
573967
  tokensPerSecond: 0,
573156
573968
  startedAt: Date.now(),
573157
573969
  modelUsage: /* @__PURE__ */ new Map(),
573970
+ mediaUsage: /* @__PURE__ */ new Map(),
573158
573971
  users: /* @__PURE__ */ new Map(),
573159
573972
  budgetTokensRemaining: 0,
573160
573973
  budgetTokensTotal: 0,
@@ -573267,8 +574080,10 @@ var init_expose = __esm({
573267
574080
  maxConcurrent: this._sponsorLimits.maxConcurrent,
573268
574081
  blockedRequests: this._sponsorBlockedRequests,
573269
574082
  allowedModels: this._sponsorLimits.allowedModels === "all" ? "all" : [...this._sponsorLimits.allowedModels],
574083
+ mediaLimits: this._sponsorLimits.media ? normalizeSponsorMediaConfig(this._sponsorLimits.media) : void 0,
573270
574084
  peers: serializeSponsorPeers(this._stats),
573271
- models: serializeSponsorModels(this._stats)
574085
+ models: serializeSponsorModels(this._stats),
574086
+ media: serializeSponsorMedia(this._stats)
573272
574087
  };
573273
574088
  }
573274
574089
  recordServedTokens(tokens, now = Date.now()) {
@@ -573526,7 +574341,8 @@ var init_expose = __esm({
573526
574341
  tokensIn: 0,
573527
574342
  tokensOut: 0,
573528
574343
  activeRequests: 0,
573529
- models: /* @__PURE__ */ new Map()
574344
+ models: /* @__PURE__ */ new Map(),
574345
+ media: /* @__PURE__ */ new Map()
573530
574346
  };
573531
574347
  this._stats.users.set(userIp, user);
573532
574348
  }
@@ -574030,6 +574846,7 @@ ${this.formatConnectionInfo()}`);
574030
574846
  this.emit("stats", {
574031
574847
  ...this._stats,
574032
574848
  modelUsage: new Map(this._stats.modelUsage),
574849
+ mediaUsage: new Map(this._stats.mediaUsage),
574033
574850
  users: new Map(this._stats.users),
574034
574851
  sponsorUsage: this._stats.sponsorUsage ? { ...this._stats.sponsorUsage } : null
574035
574852
  });
@@ -574095,6 +574912,10 @@ ${this.formatConnectionInfo()}`);
574095
574912
  total: s2.sponsorUsage.maxConcurrent
574096
574913
  })}`);
574097
574914
  lines.push(` ${c3.cyan("Blocked".padEnd(18))} ${s2.sponsorUsage.blockedRequests}`);
574915
+ const enabledMedia = s2.sponsorUsage.mediaLimits ? SPONSOR_MEDIA_MODALITIES.filter((modality) => s2.sponsorUsage?.mediaLimits?.[modality]?.enabled) : [];
574916
+ if (enabledMedia.length > 0) {
574917
+ lines.push(` ${c3.cyan("Media".padEnd(18))} ${enabledMedia.join(", ")}`);
574918
+ }
574098
574919
  }
574099
574920
  const visibleModels = Array.from(s2.modelUsage.entries()).filter(([model]) => !INTERNAL_CAPABILITIES.has(model));
574100
574921
  if (visibleModels.length > 0) {
@@ -574112,6 +574933,15 @@ ${this.formatConnectionInfo()}`);
574112
574933
  lines.push(` ${c3.cyan(model.padEnd(30))} ${count} reqs ${c3.dim(`in:${fmtTokens(mIn)} out:${fmtTokens(mOut)}`)}`);
574113
574934
  }
574114
574935
  }
574936
+ const mediaUsage = serializeSponsorMedia(s2);
574937
+ if (mediaUsage.length > 0) {
574938
+ lines.push("");
574939
+ lines.push(` ${c3.bold("Media Jobs")}`);
574940
+ for (const media of mediaUsage.slice(0, 10)) {
574941
+ const mb = media.bytesOut > 0 ? `${(media.bytesOut / (1024 * 1024)).toFixed(1)}MB` : "0MB";
574942
+ lines.push(` ${c3.cyan(media.key.padEnd(30))} ${media.jobs} jobs ${c3.dim(`${mb} out ${media.avgLatencyMs}ms avg`)}`);
574943
+ }
574944
+ }
574115
574945
  if (s2.users.size > 0) {
574116
574946
  lines.push("");
574117
574947
  lines.push(` ${c3.bold("Active Users")} (${s2.users.size})`);
@@ -574180,6 +575010,7 @@ ${this.formatConnectionInfo()}`);
574180
575010
  tokensPerSecond: 0,
574181
575011
  startedAt: Date.now(),
574182
575012
  modelUsage: /* @__PURE__ */ new Map(),
575013
+ mediaUsage: /* @__PURE__ */ new Map(),
574183
575014
  users: /* @__PURE__ */ new Map(),
574184
575015
  budgetTokensRemaining: 0,
574185
575016
  budgetTokensTotal: 0,
@@ -574318,8 +575149,10 @@ ${this.formatConnectionInfo()}`);
574318
575149
  maxConcurrent: this._sponsorLimits.maxConcurrent,
574319
575150
  blockedRequests: this._sponsorBlockedRequests,
574320
575151
  allowedModels: this._sponsorLimits.allowedModels === "all" ? "all" : [...this._sponsorLimits.allowedModels],
575152
+ mediaLimits: this._sponsorLimits.media ? normalizeSponsorMediaConfig(this._sponsorLimits.media) : void 0,
574321
575153
  peers: serializeSponsorPeers(this._stats),
574322
- models: serializeSponsorModels(this._stats)
575154
+ models: serializeSponsorModels(this._stats),
575155
+ media: serializeSponsorMedia(this._stats)
574323
575156
  };
574324
575157
  }
574325
575158
  recordServedTokens(tokens, now = Date.now()) {
@@ -574344,6 +575177,9 @@ ${this.formatConnectionInfo()}`);
574344
575177
  exposeArgs.daily_tokens_used = String(this._dailyTokensUsed);
574345
575178
  exposeArgs.daily_tokens_reset_at = String(this._dailyTokensResetAt);
574346
575179
  exposeArgs.allowed_models = this._sponsorLimits.allowedModels === "all" ? "all" : this._sponsorLimits.allowedModels.join(",");
575180
+ if (this._sponsorLimits.media) {
575181
+ exposeArgs.media_config = JSON.stringify(normalizeSponsorMediaConfig(this._sponsorLimits.media));
575182
+ }
574347
575183
  }
574348
575184
  return exposeArgs;
574349
575185
  }
@@ -574594,6 +575430,55 @@ ${this.formatConnectionInfo()}`);
574594
575430
  this.refreshSponsorUsageStats();
574595
575431
  continue;
574596
575432
  }
575433
+ if (record.modality) {
575434
+ const modality = String(record.modality);
575435
+ const modelName = String(record.model || "auto");
575436
+ const mediaKey2 = `${modality}:${modelName}`;
575437
+ const outputBytes = safeNonNegativeInt(record.outputBytes ?? record.artifactBytes ?? 0);
575438
+ const durationMs = safeNonNegativeInt(record.durationMs);
575439
+ let mediaMeter = this._stats.mediaUsage.get(mediaKey2);
575440
+ if (!mediaMeter) {
575441
+ mediaMeter = { jobs: 0, bytesOut: 0, failures: 0, lastUsed: 0, totalLatencyMs: 0 };
575442
+ this._stats.mediaUsage.set(mediaKey2, mediaMeter);
575443
+ }
575444
+ mediaMeter.jobs++;
575445
+ mediaMeter.bytesOut += outputBytes;
575446
+ mediaMeter.failures += record.success === false ? 1 : 0;
575447
+ mediaMeter.lastUsed = Date.now();
575448
+ mediaMeter.totalLatencyMs += durationMs;
575449
+ this.recordSponsorRequest();
575450
+ const peerId2 = record.from || record.peerId || "unknown";
575451
+ const shortPeer2 = peerId2.length > 16 ? peerId2.slice(0, 16) + "..." : peerId2;
575452
+ let user2 = this._stats.users.get(shortPeer2);
575453
+ if (!user2) {
575454
+ user2 = {
575455
+ ip: shortPeer2,
575456
+ firstSeen: Date.now(),
575457
+ lastSeen: Date.now(),
575458
+ requests: 0,
575459
+ tokensIn: 0,
575460
+ tokensOut: 0,
575461
+ activeRequests: 0,
575462
+ models: /* @__PURE__ */ new Map(),
575463
+ media: /* @__PURE__ */ new Map()
575464
+ };
575465
+ this._stats.users.set(shortPeer2, user2);
575466
+ }
575467
+ user2.requests++;
575468
+ user2.lastSeen = Date.now();
575469
+ let userMedia = user2.media.get(mediaKey2);
575470
+ if (!userMedia) {
575471
+ userMedia = { jobs: 0, bytesOut: 0, failures: 0, lastUsed: 0, totalLatencyMs: 0 };
575472
+ user2.media.set(mediaKey2, userMedia);
575473
+ }
575474
+ userMedia.jobs++;
575475
+ userMedia.bytesOut += outputBytes;
575476
+ userMedia.failures += record.success === false ? 1 : 0;
575477
+ userMedia.lastUsed = Date.now();
575478
+ userMedia.totalLatencyMs += durationMs;
575479
+ this._stats.modelUsage.set(mediaKey2, (this._stats.modelUsage.get(mediaKey2) ?? 0) + 1);
575480
+ continue;
575481
+ }
574597
575482
  let tokIn = 0;
574598
575483
  let tokOut = 0;
574599
575484
  if (typeof record.inputTokens === "number" && typeof record.outputTokens === "number") {
@@ -574629,7 +575514,8 @@ ${this.formatConnectionInfo()}`);
574629
575514
  tokensIn: 0,
574630
575515
  tokensOut: 0,
574631
575516
  activeRequests: 0,
574632
- models: /* @__PURE__ */ new Map()
575517
+ models: /* @__PURE__ */ new Map(),
575518
+ media: /* @__PURE__ */ new Map()
574633
575519
  };
574634
575520
  this._stats.users.set(shortPeer, user);
574635
575521
  }
@@ -574684,6 +575570,7 @@ ${this.formatConnectionInfo()}`);
574684
575570
  this.emit("stats", {
574685
575571
  ...this._stats,
574686
575572
  modelUsage: new Map(this._stats.modelUsage),
575573
+ mediaUsage: new Map(this._stats.mediaUsage),
574687
575574
  users: new Map(this._stats.users),
574688
575575
  sponsorUsage: this._stats.sponsorUsage ? { ...this._stats.sponsorUsage } : null
574689
575576
  });
@@ -574823,7 +575710,7 @@ var init_types = __esm({
574823
575710
  });
574824
575711
 
574825
575712
  // packages/cli/src/tui/p2p/secret-vault.ts
574826
- import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes21, scryptSync as scryptSync2, createHash as createHash21 } from "node:crypto";
575713
+ import { createCipheriv as createCipheriv3, createDecipheriv as createDecipheriv3, randomBytes as randomBytes21, scryptSync as scryptSync2, createHash as createHash22 } from "node:crypto";
574827
575714
  import { readFileSync as readFileSync72, writeFileSync as writeFileSync46, existsSync as existsSync91, mkdirSync as mkdirSync51 } from "node:fs";
574828
575715
  import { dirname as dirname28 } from "node:path";
574829
575716
  var PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, CIPHER_ALGO, SALT_LEN, IV_LEN, KEY_LEN, SecretVault;
@@ -575068,7 +575955,7 @@ var init_secret_vault = __esm({
575068
575955
  /** Generate a deterministic fingerprint of vault contents (for sync verification) */
575069
575956
  fingerprint() {
575070
575957
  const names = Array.from(this.secrets.keys()).sort();
575071
- const hash = createHash21("sha256");
575958
+ const hash = createHash22("sha256");
575072
575959
  for (const name10 of names) {
575073
575960
  hash.update(name10 + ":");
575074
575961
  hash.update(this.secrets.get(name10).value);
@@ -575083,7 +575970,7 @@ var init_secret_vault = __esm({
575083
575970
  // packages/cli/src/tui/p2p/peer-mesh.ts
575084
575971
  import { EventEmitter as EventEmitter9 } from "node:events";
575085
575972
  import { createServer as createServer6 } from "node:http";
575086
- import { randomBytes as randomBytes22, createHash as createHash22, generateKeyPairSync } from "node:crypto";
575973
+ import { randomBytes as randomBytes22, createHash as createHash23, generateKeyPairSync } from "node:crypto";
575087
575974
  var PING_INTERVAL_MS, PEER_TIMEOUT_MS, GOSSIP_INTERVAL_MS, MAX_PEERS, PeerMesh;
575088
575975
  var init_peer_mesh = __esm({
575089
575976
  "packages/cli/src/tui/p2p/peer-mesh.ts"() {
@@ -575100,7 +575987,7 @@ var init_peer_mesh = __esm({
575100
575987
  const { publicKey: publicKey2, privateKey } = generateKeyPairSync("ed25519");
575101
575988
  this.publicKey = publicKey2.export({ type: "spki", format: "der" });
575102
575989
  this.privateKey = privateKey.export({ type: "pkcs8", format: "der" });
575103
- this.peerId = createHash22("sha256").update(this.publicKey).digest("base64url").slice(0, 22);
575990
+ this.peerId = createHash23("sha256").update(this.publicKey).digest("base64url").slice(0, 22);
575104
575991
  this.capabilities = options2.capabilities;
575105
575992
  this.displayName = options2.displayName;
575106
575993
  this._authKey = options2.authKey ?? randomBytes22(24).toString("base64url");
@@ -576438,7 +577325,7 @@ __export(omnius_directory_exports, {
576438
577325
  import { appendFileSync as appendFileSync6, cpSync as cpSync2, existsSync as existsSync94, mkdirSync as mkdirSync53, readFileSync as readFileSync75, writeFileSync as writeFileSync48, readdirSync as readdirSync31, statSync as statSync36, unlinkSync as unlinkSync17, openSync as openSync2, closeSync as closeSync2, renameSync as renameSync4, watch as fsWatch2 } from "node:fs";
576439
577326
  import { join as join110, relative as relative9, basename as basename21, dirname as dirname31, resolve as resolve41 } from "node:path";
576440
577327
  import { homedir as homedir34 } from "node:os";
576441
- import { createHash as createHash23 } from "node:crypto";
577328
+ import { createHash as createHash24 } from "node:crypto";
576442
577329
  function isGitRoot(dir) {
576443
577330
  const gitPath = join110(dir, ".git");
576444
577331
  if (!existsSync94(gitPath)) return false;
@@ -576892,7 +577779,7 @@ function buildHandoffPrompt(repoRoot) {
576892
577779
  return lines.join("\n");
576893
577780
  }
576894
577781
  function computeDedupeHash(task, savedAt) {
576895
- return createHash23("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
577782
+ return createHash24("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
576896
577783
  }
576897
577784
  function generateSessionId() {
576898
577785
  const timestamp = Date.now().toString(36);
@@ -591805,7 +592692,8 @@ function defaultConfig2() {
591805
592692
  maxRequestsPerMinute: 60,
591806
592693
  maxTokensPerDay: 1e5,
591807
592694
  maxConcurrent: 5,
591808
- allowedModels: "all"
592695
+ allowedModels: "all",
592696
+ media: normalizeSponsorMediaConfig(DEFAULT_SPONSOR_MEDIA_LIMITS)
591809
592697
  },
591810
592698
  cohereEnabled: true,
591811
592699
  status: "inactive",
@@ -591813,6 +592701,10 @@ function defaultConfig2() {
591813
592701
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
591814
592702
  };
591815
592703
  }
592704
+ function normalizeLoadedSponsorConfig(config) {
592705
+ config.rateLimits.media = normalizeSponsorMediaConfig(config.rateLimits.media);
592706
+ return config;
592707
+ }
591816
592708
  function endpointAuthToken(authHeader) {
591817
592709
  const raw = (authHeader || "").trim();
591818
592710
  if (!raw) return void 0;
@@ -592454,6 +593346,99 @@ async function stepTransport(config, rl, availableRows) {
592454
593346
  }
592455
593347
  return false;
592456
593348
  }
593349
+ function mediaLimitSummary(modality, media) {
593350
+ const limits = media[modality];
593351
+ if (modality === "image") {
593352
+ return `${limits.maxConcurrent} concurrent, ${limits.jobsPerDay}/day, ${limits.maxWidth}x${limits.maxHeight}, ${limits.maxSteps} steps`;
593353
+ }
593354
+ if (modality === "video") {
593355
+ return `${limits.maxConcurrent} concurrent, ${limits.jobsPerDay}/day, ${limits.maxDurationSec}s, ${limits.maxFrames} frames, ${limits.maxOutputBytes} bytes`;
593356
+ }
593357
+ return `${limits.maxConcurrent} concurrent, ${limits.jobsPerDay}/day, ${limits.maxDurationSec}s, ${limits.maxOutputBytes} bytes`;
593358
+ }
593359
+ async function stepMedia(config, rl, availableRows) {
593360
+ const media = normalizeSponsorMediaConfig(config.rateLimits.media);
593361
+ config.rateLimits.media = media;
593362
+ const items = [
593363
+ { key: "hdr", label: "Sponsored Media Generation" },
593364
+ { key: "desc", label: " Remote consumers use /sponsor image|video|sound|music. Setup/prewarm stays provider-only." }
593365
+ ];
593366
+ for (const modality of SPONSOR_MEDIA_MODALITIES) {
593367
+ const limits = media[modality];
593368
+ items.push({
593369
+ key: `toggle:${modality}`,
593370
+ label: ` ${limits.enabled ? "[x]" : "[ ]"} ${modality}`,
593371
+ detail: mediaLimitSummary(modality, media)
593372
+ });
593373
+ }
593374
+ items.push({ key: "sep", label: "" });
593375
+ items.push({ key: "next", label: selectColors.green(" Next Step →") });
593376
+ const updateItem = (item, modality) => {
593377
+ const limits = media[modality];
593378
+ item.label = ` ${limits.enabled ? "[x]" : "[ ]"} ${modality}`;
593379
+ item.detail = mediaLimitSummary(modality, media);
593380
+ };
593381
+ const result = await tuiSelect({
593382
+ items,
593383
+ title: "Step 5/7 — Media Generation",
593384
+ rl,
593385
+ skipKeys: ["hdr", "desc", "sep"],
593386
+ availableRows,
593387
+ customKeyHint: " space/Enter toggle e edit limits",
593388
+ onAction: (item, action) => {
593389
+ if (action !== "space" || !item.key.startsWith("toggle:")) return false;
593390
+ const modality = item.key.slice("toggle:".length);
593391
+ media[modality].enabled = !media[modality].enabled;
593392
+ updateItem(item, modality);
593393
+ return true;
593394
+ },
593395
+ onEnter: (item, helpers) => {
593396
+ if (item.key.startsWith("toggle:")) {
593397
+ const modality = item.key.slice("toggle:".length);
593398
+ media[modality].enabled = !media[modality].enabled;
593399
+ updateItem(item, modality);
593400
+ helpers.render();
593401
+ return true;
593402
+ }
593403
+ return false;
593404
+ },
593405
+ onCustomKey: (item, key, helpers) => {
593406
+ if (key !== "e" && key !== "E" || !item.key.startsWith("toggle:")) return false;
593407
+ const modality = item.key.slice("toggle:".length);
593408
+ const limits = media[modality];
593409
+ helpers.getInput("Max concurrent jobs:", String(limits.maxConcurrent)).then((concurrent) => {
593410
+ const c8 = parseInt(concurrent ?? "", 10);
593411
+ if (Number.isFinite(c8) && c8 > 0) limits.maxConcurrent = c8;
593412
+ helpers.getInput("Jobs/day:", String(limits.jobsPerDay)).then((daily) => {
593413
+ const d2 = parseInt(daily ?? "", 10);
593414
+ if (Number.isFinite(d2) && d2 > 0) limits.jobsPerDay = d2;
593415
+ const durationKey = modality === "image" ? "Max steps:" : "Max duration seconds:";
593416
+ const durationValue = modality === "image" ? limits.maxSteps : limits.maxDurationSec;
593417
+ helpers.getInput(durationKey, String(durationValue ?? "")).then((value2) => {
593418
+ const n2 = parseInt(value2 ?? "", 10);
593419
+ if (Number.isFinite(n2) && n2 > 0) {
593420
+ if (modality === "image") limits.maxSteps = n2;
593421
+ else limits.maxDurationSec = n2;
593422
+ }
593423
+ updateItem(item, modality);
593424
+ helpers.render();
593425
+ });
593426
+ });
593427
+ });
593428
+ return true;
593429
+ },
593430
+ renderRow: (item, focused, _isActive) => {
593431
+ const prefix = focused ? selectColors.blue("❯ ") : " ";
593432
+ if (item.key === "hdr") return selectColors.bold(item.label);
593433
+ if (item.key === "desc") return selectColors.dim(item.label);
593434
+ if (item.detail) return `${prefix}${item.label}
593435
+ ${selectColors.dim(item.detail)}`;
593436
+ return `${prefix}${item.label}`;
593437
+ }
593438
+ });
593439
+ if (!result.confirmed) return false;
593440
+ return result.key === "next";
593441
+ }
592457
593442
  async function stepCohere(config, rl, availableRows) {
592458
593443
  const items = [
592459
593444
  { key: "hdr", label: "COHERE — Distributed Intelligence (Experimental)" },
@@ -592480,7 +593465,7 @@ async function stepCohere(config, rl, availableRows) {
592480
593465
  ];
592481
593466
  const result = await tuiSelect({
592482
593467
  items,
592483
- title: "Step 5/6 — COHERE Distributed Intelligence",
593468
+ title: "Step 6/7 — COHERE Distributed Intelligence",
592484
593469
  rl,
592485
593470
  skipKeys: ["hdr", "desc1", "desc2", "desc3", "desc4", "desc5", "desc6", "desc7", "desc8", "desc9", "desc10", "desc11", "desc12", "desc13", "desc14", "desc15", "desc16", "sep1", "sep2"],
592486
593471
  availableRows,
@@ -592517,6 +593502,9 @@ async function stepReview(config, rl, availableRows) {
592517
593502
  const transports = [];
592518
593503
  if (config.transport.cloudflared) transports.push("Cloudflared Tunnel");
592519
593504
  if (config.transport.libp2p) transports.push("libp2p P2P");
593505
+ const media = normalizeSponsorMediaConfig(config.rateLimits.media);
593506
+ config.rateLimits.media = media;
593507
+ const mediaEnabled = SPONSOR_MEDIA_MODALITIES.filter((modality) => media[modality].enabled);
592520
593508
  const items = [
592521
593509
  { key: "hdr", label: "Review Sponsorship Configuration" },
592522
593510
  { key: "info_ep", label: ` Endpoints: ${epList}` },
@@ -592524,16 +593512,17 @@ async function stepReview(config, rl, availableRows) {
592524
593512
  { key: "info_link", label: ` Link: ${config.header.linkEnabled ? `${config.header.linkUrl} [${config.header.linkText || config.header.message}]` : "(none)"}` },
592525
593513
  { key: "info_transport", label: ` Transport: ${transports.join(" + ")}` },
592526
593514
  { key: "info_limits", label: ` Limits: ${config.rateLimits.maxRequestsPerMinute} req/min, ${config.rateLimits.maxTokensPerDay.toLocaleString()} tokens/day` },
593515
+ { key: "info_media", label: ` Media: ${mediaEnabled.length > 0 ? mediaEnabled.join(", ") : "disabled"}` },
592527
593516
  { key: "info_cohere", label: ` COHERE: ${config.cohereEnabled ? "enabled (distributed inference)" : "disabled"}` },
592528
593517
  { key: "sep", label: "" },
592529
- { key: "go_live", label: selectColors.green(" ✦ Go Live & Sponsor Inference ") },
593518
+ { key: "go_live", label: selectColors.green(" ✦ Go Live & Sponsor Services ") },
592530
593519
  { key: "cancel", label: selectColors.dim(" Cancel") }
592531
593520
  ];
592532
593521
  const result = await tuiSelect({
592533
593522
  items,
592534
- title: "Step 6/6 — Review & Go Live",
593523
+ title: "Step 7/7 — Review & Go Live",
592535
593524
  rl,
592536
- skipKeys: ["hdr", "sep", "info_ep", "info_msg", "info_link", "info_transport", "info_limits", "info_cohere"],
593525
+ skipKeys: ["hdr", "sep", "info_ep", "info_msg", "info_link", "info_transport", "info_limits", "info_media", "info_cohere"],
592537
593526
  availableRows
592538
593527
  });
592539
593528
  if (!result.confirmed || result.key === "cancel") return false;
@@ -592542,11 +593531,14 @@ async function stepReview(config, rl, availableRows) {
592542
593531
  async function showSponsorDashboard(config, projectDir2, rl, availableRows, sponsorUsage) {
592543
593532
  const isPaused = config.status === "paused";
592544
593533
  const enabledEps = config.endpoints.filter((e2) => e2.enabled);
593534
+ config.rateLimits.media = normalizeSponsorMediaConfig(config.rateLimits.media);
593535
+ const enabledMedia = SPONSOR_MEDIA_MODALITIES.filter((modality) => config.rateLimits.media?.[modality]?.enabled);
592545
593536
  const dailyTokensLimit = sponsorUsage?.dailyTokensLimit || config.rateLimits.maxTokensPerDay;
592546
593537
  const requestsPerMinuteLimit = sponsorUsage?.requestsPerMinuteLimit || config.rateLimits.maxRequestsPerMinute;
592547
593538
  const maxConcurrent = sponsorUsage?.maxConcurrent || config.rateLimits.maxConcurrent;
592548
593539
  const topModels = (sponsorUsage?.models ?? []).slice(0, 5);
592549
593540
  const topPeers = (sponsorUsage?.peers ?? []).slice(0, 5);
593541
+ const topMedia = (sponsorUsage?.media ?? []).slice(0, 5);
592550
593542
  const usageItems = [
592551
593543
  {
592552
593544
  key: "info_usage_totals",
@@ -592602,12 +593594,23 @@ async function showSponsorDashboard(config, projectDir2, rl, availableRows, spon
592602
593594
  });
592603
593595
  }
592604
593596
  }
593597
+ if (topMedia.length > 0) {
593598
+ usageItems.push({ key: "info_usage_media_hdr", label: " Media" });
593599
+ for (const [idx, media] of topMedia.entries()) {
593600
+ const mb = media.bytesOut > 0 ? `${(media.bytesOut / (1024 * 1024)).toFixed(1)}MB` : "0MB";
593601
+ usageItems.push({
593602
+ key: `info_usage_media_${idx}`,
593603
+ label: ` ${media.key}: ${media.jobs} jobs · ${mb}`
593604
+ });
593605
+ }
593606
+ }
592605
593607
  const items = [
592606
593608
  { key: "hdr", label: "Sponsor Dashboard" },
592607
593609
  { key: "info_status", label: ` Status: ${isPaused ? "● PAUSED" : "● ACTIVE"}` },
592608
593610
  { key: "info_ep", label: ` Endpoints: ${enabledEps.map((e2) => e2.label).join(", ")}` },
592609
593611
  { key: "info_transport", label: ` Transport: ${[config.transport.cloudflared ? "Cloudflared" : "", config.transport.libp2p ? "libp2p" : ""].filter(Boolean).join(" + ")}` },
592610
593612
  { key: "info_limits", label: ` Limits: ${config.rateLimits.maxRequestsPerMinute} req/min, ${config.rateLimits.maxTokensPerDay.toLocaleString()} tokens/day, ${config.rateLimits.maxConcurrent} concurrent` },
593613
+ { key: "info_media", label: ` Media: ${enabledMedia.length > 0 ? enabledMedia.join(", ") : "disabled"}` },
592611
593614
  { key: "info_usage_hdr", label: " Usage" },
592612
593615
  ...usageItems,
592613
593616
  { key: "sep", label: "" },
@@ -592626,7 +593629,7 @@ async function showSponsorDashboard(config, projectDir2, rl, availableRows, spon
592626
593629
  return result.key || "close";
592627
593630
  }
592628
593631
  async function runSponsorWizard(ctx3) {
592629
- let config = loadSponsorConfig(ctx3.projectDir) || defaultConfig2();
593632
+ let config = normalizeLoadedSponsorConfig(loadSponsorConfig(ctx3.projectDir) || defaultConfig2());
592630
593633
  renderInfo("Starting sponsor onboarding wizard...\n");
592631
593634
  if (!await stepEndpoints(config, ctx3.ollamaUrl, ctx3.rl, ctx3.availableRows, ctx3.projectDir)) {
592632
593635
  renderInfo("Sponsor wizard cancelled.");
@@ -592644,6 +593647,11 @@ async function runSponsorWizard(ctx3) {
592644
593647
  return null;
592645
593648
  }
592646
593649
  saveSponsorConfig(ctx3.projectDir, config);
593650
+ if (!await stepMedia(config, ctx3.rl, ctx3.availableRows)) {
593651
+ renderInfo("Sponsor wizard cancelled.");
593652
+ return null;
593653
+ }
593654
+ saveSponsorConfig(ctx3.projectDir, config);
592647
593655
  if (!await stepCohere(config, ctx3.rl, ctx3.availableRows)) {
592648
593656
  renderInfo("Sponsor wizard cancelled.");
592649
593657
  return null;
@@ -592685,6 +593693,7 @@ var init_sponsor_wizard = __esm({
592685
593693
  init_tui_select();
592686
593694
  init_render();
592687
593695
  init_usage_bars();
593696
+ init_dist5();
592688
593697
  }
592689
593698
  });
592690
593699
 
@@ -596871,6 +597880,7 @@ __export(commands_exports, {
596871
597880
  });
596872
597881
  import * as nodeOs from "node:os";
596873
597882
  import { execSync as nodeExecSync } from "node:child_process";
597883
+ import { createHash as createHash25 } from "node:crypto";
596874
597884
  import {
596875
597885
  existsSync as existsSync107,
596876
597886
  readFileSync as readFileSync86,
@@ -596883,7 +597893,7 @@ import {
596883
597893
  appendFileSync as appendFileSync8,
596884
597894
  writeSync as writeSync2
596885
597895
  } from "node:fs";
596886
- import { relative as relative11, join as join120 } from "node:path";
597896
+ import { basename as basename23, dirname as dirname35, relative as relative11, join as join120 } from "node:path";
596887
597897
  async function parseJsonResponse(resp, source) {
596888
597898
  const body = await resp.text();
596889
597899
  const trimmed = body.trim();
@@ -597277,12 +598287,12 @@ async function ensureVoiceDeps(ctx3) {
597277
598287
  renderInfo(res.log.split("\n").slice(-3).join(" ").slice(0, 200));
597278
598288
  }
597279
598289
  if (typeof mod2.getVenvPython === "function") {
597280
- const { dirname: dirname43 } = await import("node:path");
598290
+ const { dirname: dirname44 } = await import("node:path");
597281
598291
  const { existsSync: existsSync137 } = await import("node:fs");
597282
598292
  const venvPy = mod2.getVenvPython();
597283
598293
  if (existsSync137(venvPy)) {
597284
598294
  process.env.TRANSCRIBE_PYTHON = venvPy;
597285
- const venvBin = dirname43(venvPy);
598295
+ const venvBin = dirname44(venvPy);
597286
598296
  const sep4 = process.platform === "win32" ? ";" : ":";
597287
598297
  const cur = process.env.PATH || "";
597288
598298
  if (!cur.split(sep4).includes(venvBin)) {
@@ -601238,6 +602248,11 @@ sleep 1
601238
602248
  return "handled";
601239
602249
  }
601240
602250
  case "sponsor": {
602251
+ const mediaCommand = parseSponsorMediaCommand(arg);
602252
+ if (mediaCommand) {
602253
+ await handleSponsorMediaCommand(ctx3, mediaCommand.modality, mediaCommand.rest);
602254
+ return "handled";
602255
+ }
601241
602256
  if (!ctx3.rl) {
601242
602257
  renderWarning("Sponsor wizard requires interactive mode.");
601243
602258
  return "handled";
@@ -601484,6 +602499,21 @@ sleep 1
601484
602499
  if (allModels.length > 0) {
601485
602500
  config.rateLimits.allowedModels = allModels;
601486
602501
  }
602502
+ config.rateLimits.media = normalizeSponsorMediaConfig(config.rateLimits.media);
602503
+ const sponsorServices = [
602504
+ ...allModels.map((model) => ({
602505
+ kind: "llm",
602506
+ capability: `inference:${model.replace(/[^a-zA-Z0-9._-]/g, "_")}`,
602507
+ model,
602508
+ input: ["messages", "prompt"],
602509
+ output: ["text"],
602510
+ limits: {
602511
+ maxRequestsPerMinute: config.rateLimits.maxRequestsPerMinute,
602512
+ maxTokensPerDay: config.rateLimits.maxTokensPerDay
602513
+ }
602514
+ })),
602515
+ ...buildSponsorMediaServices(config.rateLimits.media)
602516
+ ];
601487
602517
  renderInfo(
601488
602518
  `Sponsoring ${primaryProvider.label} endpoint: ${new URL(primaryUrl).host}`
601489
602519
  );
@@ -601742,8 +602772,11 @@ sleep 1
601742
602772
  limits: {
601743
602773
  maxRequestsPerMinute: config.rateLimits.maxRequestsPerMinute,
601744
602774
  maxTokensPerDay: config.rateLimits.maxTokensPerDay,
601745
- maxConcurrent: config.rateLimits.maxConcurrent
602775
+ maxConcurrent: config.rateLimits.maxConcurrent,
602776
+ media: config.rateLimits.media
601746
602777
  },
602778
+ services: sponsorServices,
602779
+ mediaCapabilities: sponsorServices.filter((service) => service.kind !== "llm"),
601747
602780
  banner: "none",
601748
602781
  message: config.header.message || sponsorName,
601749
602782
  linkUrl: config.header.linkUrl,
@@ -606033,14 +607066,14 @@ async function handleVoiceMenu(ctx3, save2, hasLocal) {
606033
607066
  if (!jsonDrop.confirmed || !jsonDrop.path) {
606034
607067
  continue;
606035
607068
  }
606036
- const { basename: basename34, join: pathJoin } = await import("node:path");
607069
+ const { basename: basename35, join: pathJoin } = await import("node:path");
606037
607070
  const {
606038
607071
  copyFileSync: copyFileSync5,
606039
607072
  mkdirSync: mkdirSync84,
606040
607073
  existsSync: exists2
606041
607074
  } = await import("node:fs");
606042
607075
  const { homedir: homedir56 } = await import("node:os");
606043
- const modelName = basename34(onnxDrop.path, ".onnx").replace(
607076
+ const modelName = basename35(onnxDrop.path, ".onnx").replace(
606044
607077
  /[^a-zA-Z0-9_-]/g,
606045
607078
  "-"
606046
607079
  );
@@ -606427,7 +607460,7 @@ async function handleVoiceList(ctx3, focusFilename) {
606427
607460
  copyFileSync: cpf,
606428
607461
  mkdirSync: mkd
606429
607462
  } = __require("node:fs");
606430
- const { basename: basename34, join: pjoin } = __require("node:path");
607463
+ const { basename: basename35, join: pjoin } = __require("node:path");
606431
607464
  if (!fe(src2)) {
606432
607465
  renderError(`File not found: ${src2}`);
606433
607466
  helpers.render();
@@ -606440,7 +607473,7 @@ async function handleVoiceList(ctx3, focusFilename) {
606440
607473
  "clone-refs"
606441
607474
  );
606442
607475
  mkd(refsDir, { recursive: true });
606443
- const destName = basename34(src2);
607476
+ const destName = basename35(src2);
606444
607477
  const dest = pjoin(refsDir, destName);
606445
607478
  cpf(src2, dest);
606446
607479
  renderInfo(`Imported "${destName}" → ${dest}`);
@@ -606924,6 +607957,340 @@ async function handleEndpoint(arg, ctx3, local = false) {
606924
607957
  );
606925
607958
  }
606926
607959
  }
607960
+ function parseSponsorMediaCommand(arg) {
607961
+ const trimmed = arg.trim();
607962
+ if (!trimmed) return null;
607963
+ const firstSpace = trimmed.indexOf(" ");
607964
+ const head = (firstSpace >= 0 ? trimmed.slice(0, firstSpace) : trimmed).toLowerCase();
607965
+ if (head !== "image" && head !== "video" && head !== "sound" && head !== "music") return null;
607966
+ return {
607967
+ modality: head,
607968
+ rest: firstSpace >= 0 ? trimmed.slice(firstSpace + 1).trim() : ""
607969
+ };
607970
+ }
607971
+ function parseSponsorMediaArgs(rest) {
607972
+ const tokens = shellLikeTokens(rest);
607973
+ const promptParts = [];
607974
+ const options2 = {};
607975
+ let model;
607976
+ let backend;
607977
+ for (let i2 = 0; i2 < tokens.length; i2++) {
607978
+ const token = tokens[i2];
607979
+ if (!token.startsWith("--")) {
607980
+ promptParts.push(token);
607981
+ continue;
607982
+ }
607983
+ const eq = token.indexOf("=");
607984
+ const key = token.slice(2, eq >= 0 ? eq : void 0).replace(/-/g, "_");
607985
+ const rawValue = eq >= 0 ? token.slice(eq + 1) : tokens[i2 + 1];
607986
+ if (eq < 0 && rawValue && !rawValue.startsWith("--")) i2++;
607987
+ const value2 = coerceSponsorMediaOption(rawValue ?? "true");
607988
+ if (key === "model" && typeof value2 === "string") model = value2;
607989
+ else if (key === "backend" && typeof value2 === "string") backend = value2;
607990
+ else options2[key] = value2;
607991
+ }
607992
+ return { prompt: promptParts.join(" ").trim(), options: options2, model, backend };
607993
+ }
607994
+ function shellLikeTokens(input) {
607995
+ const tokens = [];
607996
+ let current = "";
607997
+ let quote = "";
607998
+ let escaped = false;
607999
+ for (const ch of input) {
608000
+ if (escaped) {
608001
+ current += ch;
608002
+ escaped = false;
608003
+ continue;
608004
+ }
608005
+ if (ch === "\\") {
608006
+ escaped = true;
608007
+ continue;
608008
+ }
608009
+ if (quote) {
608010
+ if (ch === quote) quote = "";
608011
+ else current += ch;
608012
+ continue;
608013
+ }
608014
+ if (ch === "'" || ch === '"') {
608015
+ quote = ch;
608016
+ continue;
608017
+ }
608018
+ if (ch === " " || ch === " ") {
608019
+ if (current) {
608020
+ tokens.push(current);
608021
+ current = "";
608022
+ }
608023
+ continue;
608024
+ }
608025
+ current += ch;
608026
+ }
608027
+ if (current) tokens.push(current);
608028
+ return tokens;
608029
+ }
608030
+ function coerceSponsorMediaOption(value2) {
608031
+ const lower = value2.toLowerCase();
608032
+ if (lower === "true" || lower === "yes" || lower === "on") return true;
608033
+ if (lower === "false" || lower === "no" || lower === "off") return false;
608034
+ const n2 = Number(value2);
608035
+ if (Number.isFinite(n2) && value2.trim() !== "") return n2;
608036
+ return value2;
608037
+ }
608038
+ async function discoverSponsorMediaCandidates(ctx3, modality) {
608039
+ const rawSponsors = [];
608040
+ const projectDir2 = ctx3.repoRoot ?? process.cwd();
608041
+ try {
608042
+ const nexus = new NexusTool(projectDir2);
608043
+ const status = String((await nexus.execute({ action: "status" }))?.output ?? "");
608044
+ if (!/Connected:\s*true/i.test(status) && ctx3.nexusConnect) {
608045
+ await ctx3.nexusConnect();
608046
+ }
608047
+ const discovered = await nexus.execute({ action: "sponsor_discover", timeout_ms: "5000" });
608048
+ const output = String(discovered?.output ?? "");
608049
+ if (output) {
608050
+ const parsed = JSON.parse(output);
608051
+ rawSponsors.push(...Array.isArray(parsed.sponsors) ? parsed.sponsors : []);
608052
+ }
608053
+ } catch {
608054
+ }
608055
+ try {
608056
+ const resp = await fetch("https://omnius.nexus/api/v1/sponsors", { signal: AbortSignal.timeout(5e3) });
608057
+ if (resp.ok) {
608058
+ const data = await parseJsonResponse(resp, "Sponsor directory");
608059
+ rawSponsors.push(...(data.sponsors ?? []).filter((s2) => s2.status === "active"));
608060
+ }
608061
+ } catch {
608062
+ }
608063
+ try {
608064
+ const knownFile = join120(projectDir2, ".omnius", "sponsor", "known-sponsors.json");
608065
+ if (existsSync107(knownFile)) {
608066
+ const saved = JSON.parse(readFileSync86(knownFile, "utf8"));
608067
+ if (Array.isArray(saved)) rawSponsors.push(...saved);
608068
+ }
608069
+ } catch {
608070
+ }
608071
+ const seen = /* @__PURE__ */ new Set();
608072
+ const candidates = [];
608073
+ for (const raw of rawSponsors) {
608074
+ const peerId = String(raw?.libp2pPeerId || raw?.peerId || "").trim();
608075
+ if (!peerId) continue;
608076
+ const services = normalizeSponsorServices(raw);
608077
+ const mediaServices = services.filter((service) => service.kind === modality);
608078
+ if (mediaServices.length === 0) continue;
608079
+ const sponsor = {
608080
+ name: String(raw?.name || "Unknown Sponsor"),
608081
+ peerId,
608082
+ authKey: String(raw?.authKey || raw?.auth_key || "").trim() || void 0,
608083
+ services
608084
+ };
608085
+ for (const service of mediaServices) {
608086
+ const key = `${peerId}:${service.capability}`;
608087
+ if (seen.has(key)) continue;
608088
+ seen.add(key);
608089
+ candidates.push({ sponsor, service });
608090
+ }
608091
+ }
608092
+ return candidates;
608093
+ }
608094
+ function normalizeSponsorServices(raw) {
608095
+ const services = Array.isArray(raw?.services) ? raw.services : Array.isArray(raw?.mediaCapabilities) ? raw.mediaCapabilities : [];
608096
+ return services.map((service) => {
608097
+ const kind = String(service?.kind || "");
608098
+ if (kind !== "llm" && kind !== "image" && kind !== "video" && kind !== "sound" && kind !== "music") return null;
608099
+ const capability = String(service?.capability || "").trim();
608100
+ if (!capability) return null;
608101
+ return {
608102
+ kind,
608103
+ capability,
608104
+ model: String(service?.model || "auto"),
608105
+ backend: service?.backend ? String(service.backend) : void 0,
608106
+ input: Array.isArray(service?.input) ? service.input.map(String) : [],
608107
+ output: Array.isArray(service?.output) ? service.output.map(String) : [],
608108
+ limits: service?.limits && typeof service.limits === "object" ? service.limits : {}
608109
+ };
608110
+ }).filter((service) => Boolean(service));
608111
+ }
608112
+ async function handleSponsorMediaCommand(ctx3, modality, rest) {
608113
+ const parsedArgs = parseSponsorMediaArgs(rest);
608114
+ if (!parsedArgs.prompt) {
608115
+ renderInfo(`Usage: /sponsor ${modality} "<prompt>" [--model name] [--backend name]`);
608116
+ return;
608117
+ }
608118
+ renderInfo(`Scanning for sponsored ${modality} generation services...`);
608119
+ const candidates = await discoverSponsorMediaCandidates(ctx3, modality);
608120
+ if (candidates.length === 0) {
608121
+ renderWarning(`No sponsored ${modality} generation services found.`);
608122
+ return;
608123
+ }
608124
+ let selected = candidates[0];
608125
+ if (ctx3.rl && candidates.length > 1) {
608126
+ const items = [
608127
+ { key: "hdr", label: `Sponsored ${modality} Services` },
608128
+ ...candidates.map((candidate, index) => ({
608129
+ key: String(index),
608130
+ label: ` ${candidate.sponsor.name}`,
608131
+ detail: `${candidate.service.capability} · model ${candidate.service.model || "auto"}`
608132
+ }))
608133
+ ];
608134
+ const result2 = await tuiSelect({
608135
+ items,
608136
+ title: `Choose Sponsored ${modality}`,
608137
+ rl: ctx3.rl,
608138
+ skipKeys: ["hdr"],
608139
+ availableRows: ctx3.availableContentRows?.()
608140
+ });
608141
+ if (!result2.confirmed) {
608142
+ renderInfo("Cancelled.");
608143
+ return;
608144
+ }
608145
+ selected = candidates[Number(result2.key) || 0] ?? selected;
608146
+ }
608147
+ const projectDir2 = ctx3.repoRoot ?? process.cwd();
608148
+ const streamDir = join120(projectDir2, ".omnius", "sponsor", "streams");
608149
+ mkdirSync59(streamDir, { recursive: true });
608150
+ const streamFile = join120(streamDir, `media-${Date.now()}-${Math.random().toString(36).slice(2, 8)}.jsonl`);
608151
+ writeFileSync54(streamFile, "", "utf8");
608152
+ const request = {
608153
+ modality,
608154
+ prompt: parsedArgs.prompt,
608155
+ ...parsedArgs.model ? { model: parsedArgs.model } : {},
608156
+ ...parsedArgs.backend ? { backend: parsedArgs.backend } : {},
608157
+ options: parsedArgs.options,
608158
+ ...selected.sponsor.authKey ? { auth_key: selected.sponsor.authKey } : {}
608159
+ };
608160
+ renderInfo(`Requesting ${modality} from ${selected.sponsor.name} (${selected.service.capability})...`);
608161
+ const nexus = new NexusTool(projectDir2);
608162
+ const start2 = await nexus.execute({
608163
+ action: "invoke_capability",
608164
+ target_peer: selected.sponsor.peerId,
608165
+ capability: selected.service.capability,
608166
+ input: JSON.stringify(request),
608167
+ stream_file: streamFile
608168
+ });
608169
+ if (!start2.success) {
608170
+ renderError(start2.error || start2.output || "Remote media invocation failed to start.");
608171
+ return;
608172
+ }
608173
+ const result = await collectSponsorMediaStream({
608174
+ streamFile,
608175
+ outputRoot: join120(projectDir2, ".omnius", "remote-media", selected.sponsor.peerId.slice(0, 16)),
608176
+ modality
608177
+ });
608178
+ if (!result.ok) {
608179
+ renderError(result.error);
608180
+ return;
608181
+ }
608182
+ renderInfo(`${modality} generated: ${result.path}`);
608183
+ if (result.metadata?.model) renderInfo(`Model: ${result.metadata.model}`);
608184
+ }
608185
+ async function collectSponsorMediaStream(args) {
608186
+ mkdirSync59(args.outputRoot, { recursive: true });
608187
+ let offset = 0;
608188
+ let pending2 = "";
608189
+ let done = false;
608190
+ let lastProgress = "";
608191
+ let metadata = null;
608192
+ const artifacts = /* @__PURE__ */ new Map();
608193
+ const deadline = Date.now() + 30 * 60 * 1e3;
608194
+ while (!done && Date.now() < deadline) {
608195
+ await new Promise((resolve56) => setTimeout(resolve56, 250));
608196
+ if (!existsSync107(args.streamFile)) continue;
608197
+ const raw = readFileSync86(args.streamFile, "utf8");
608198
+ if (raw.length <= offset) continue;
608199
+ pending2 += raw.slice(offset);
608200
+ offset = raw.length;
608201
+ const lines = pending2.split("\n");
608202
+ pending2 = lines.pop() ?? "";
608203
+ for (const line of lines) {
608204
+ if (!line.trim()) continue;
608205
+ let eventLine;
608206
+ try {
608207
+ eventLine = JSON.parse(line);
608208
+ } catch {
608209
+ continue;
608210
+ }
608211
+ if (eventLine.type === "done") {
608212
+ done = true;
608213
+ continue;
608214
+ }
608215
+ if (eventLine.type === "error") {
608216
+ return { ok: false, error: String(eventLine.error || "Remote media stream failed") };
608217
+ }
608218
+ if (eventLine.type !== "event") continue;
608219
+ if (eventLine.event === "error") {
608220
+ return { ok: false, error: String(eventLine.data || "Remote media generation failed") };
608221
+ }
608222
+ const payload = parseMaybeJson(eventLine.data);
608223
+ if (eventLine.event === "progress") {
608224
+ const msg = String(payload?.message || payload?.stage || eventLine.data || "");
608225
+ if (msg && msg !== lastProgress) {
608226
+ lastProgress = msg;
608227
+ renderInfo(`${args.modality}: ${msg}`);
608228
+ }
608229
+ continue;
608230
+ }
608231
+ if (eventLine.event === "artifact.begin") {
608232
+ const artifactId2 = String(payload?.artifactId || "artifact");
608233
+ artifacts.set(artifactId2, {
608234
+ filename: String(payload?.filename || `${artifactId2}${defaultExtensionForMime(String(payload?.mime || ""))}`),
608235
+ mime: String(payload?.mime || mediaMimeFromPath(payload?.filename || "", args.modality)),
608236
+ chunks: [],
608237
+ sizeBytes: typeof payload?.sizeBytes === "number" ? payload.sizeBytes : void 0,
608238
+ sha256: typeof payload?.sha256 === "string" ? payload.sha256 : void 0
608239
+ });
608240
+ continue;
608241
+ }
608242
+ if (eventLine.event === "artifact.chunk") {
608243
+ const artifactId2 = String(payload?.artifactId || "artifact");
608244
+ let artifact2 = artifacts.get(artifactId2);
608245
+ if (!artifact2) {
608246
+ artifact2 = { filename: `${artifactId2}.bin`, mime: "application/octet-stream", chunks: [] };
608247
+ artifacts.set(artifactId2, artifact2);
608248
+ }
608249
+ if (typeof payload?.dataBase64 === "string") {
608250
+ artifact2.chunks.push(Buffer.from(payload.dataBase64, "base64"));
608251
+ }
608252
+ continue;
608253
+ }
608254
+ if (eventLine.event === "artifact.end") {
608255
+ const artifactId2 = String(payload?.artifactId || "artifact");
608256
+ const artifact2 = artifacts.get(artifactId2);
608257
+ if (artifact2) {
608258
+ artifact2.sha256 = String(payload?.sha256 || artifact2.sha256 || "");
608259
+ artifact2.sizeBytes = typeof payload?.sizeBytes === "number" ? payload.sizeBytes : artifact2.sizeBytes;
608260
+ }
608261
+ continue;
608262
+ }
608263
+ if (eventLine.event === "result") {
608264
+ metadata = payload;
608265
+ }
608266
+ }
608267
+ }
608268
+ if (!done) return { ok: false, error: "Remote media stream timed out." };
608269
+ const first2 = artifacts.entries().next();
608270
+ if (first2.done) return { ok: false, error: "Remote media completed without an artifact." };
608271
+ const [artifactId, artifact] = first2.value;
608272
+ const bytes = Buffer.concat(artifact.chunks);
608273
+ if (artifact.sizeBytes !== void 0 && bytes.length !== artifact.sizeBytes) {
608274
+ return { ok: false, error: `Artifact size mismatch for ${artifactId}: ${bytes.length}/${artifact.sizeBytes}` };
608275
+ }
608276
+ if (artifact.sha256) {
608277
+ const sha = createHash25("sha256").update(bytes).digest("hex");
608278
+ if (sha !== artifact.sha256) return { ok: false, error: `Artifact hash mismatch for ${artifactId}` };
608279
+ }
608280
+ const safeName3 = basename23(artifact.filename).replace(/[^\w.-]/g, "_") || `artifact${defaultExtensionForMime(artifact.mime)}`;
608281
+ const outputPath3 = join120(args.outputRoot, safeName3);
608282
+ mkdirSync59(dirname35(outputPath3), { recursive: true });
608283
+ writeFileSync54(outputPath3, bytes);
608284
+ return { ok: true, path: outputPath3, metadata };
608285
+ }
608286
+ function parseMaybeJson(value2) {
608287
+ if (typeof value2 !== "string") return value2;
608288
+ try {
608289
+ return JSON.parse(value2);
608290
+ } catch {
608291
+ return value2;
608292
+ }
608293
+ }
606927
608294
  async function handleSponsoredEndpoint(ctx3, local) {
606928
608295
  renderInfo("Scanning for sponsored inference endpoints...");
606929
608296
  const sponsors = [];
@@ -607029,6 +608396,8 @@ async function handleSponsoredEndpoint(ctx3, local) {
607029
608396
  peerId: ns.peerId || void 0,
607030
608397
  authKey: ns.authKey || "",
607031
608398
  models: Array.isArray(ns.models) ? ns.models : (ns.models || "").split(",").filter(Boolean),
608399
+ services: normalizeSponsorServices(ns),
608400
+ mediaCapabilities: normalizeSponsorServices(ns).filter((service) => service.kind !== "llm"),
607032
608401
  limits: {
607033
608402
  rpm: ns.limits?.maxRequestsPerMinute || 60,
607034
608403
  tpd: ns.limits?.maxTokensPerDay || 1e5
@@ -607093,6 +608462,8 @@ async function handleSponsoredEndpoint(ctx3, local) {
607093
608462
  peerId: ks.peerId || void 0,
607094
608463
  authKey: ks.authKey || "",
607095
608464
  models: Array.isArray(ks.models) ? ks.models : [],
608465
+ services: normalizeSponsorServices(ks),
608466
+ mediaCapabilities: normalizeSponsorServices(ks).filter((service) => service.kind !== "llm"),
607096
608467
  limits: {
607097
608468
  rpm: ks.limits?.maxRequestsPerMinute || 60,
607098
608469
  tpd: ks.limits?.maxTokensPerDay || 1e5
@@ -607385,14 +608756,14 @@ async function handlePeerEndpoint(peerId, authKey, ctx3, local) {
607385
608756
  if (models.length > 0) {
607386
608757
  try {
607387
608758
  const { writeFileSync: writeFileSync76, mkdirSync: mkdirSync84 } = await import("node:fs");
607388
- const { join: join154, dirname: dirname43 } = await import("node:path");
608759
+ const { join: join154, dirname: dirname44 } = await import("node:path");
607389
608760
  const cachePath = join154(
607390
608761
  ctx3.repoRoot || process.cwd(),
607391
608762
  ".omnius",
607392
608763
  "nexus",
607393
608764
  "peer-models-cache.json"
607394
608765
  );
607395
- mkdirSync84(dirname43(cachePath), { recursive: true });
608766
+ mkdirSync84(dirname44(cachePath), { recursive: true });
607396
608767
  writeFileSync76(
607397
608768
  cachePath,
607398
608769
  JSON.stringify(
@@ -608367,10 +609738,10 @@ async function handleUpdate(subcommand, ctx3) {
608367
609738
  try {
608368
609739
  const { createRequire: createRequire10 } = await import("node:module");
608369
609740
  const { fileURLToPath: fileURLToPath21 } = await import("node:url");
608370
- const { dirname: dirname43, join: join154 } = await import("node:path");
609741
+ const { dirname: dirname44, join: join154 } = await import("node:path");
608371
609742
  const { existsSync: existsSync137 } = await import("node:fs");
608372
609743
  const req2 = createRequire10(import.meta.url);
608373
- const thisDir = dirname43(fileURLToPath21(import.meta.url));
609744
+ const thisDir = dirname44(fileURLToPath21(import.meta.url));
608374
609745
  const candidates = [
608375
609746
  join154(thisDir, "..", "package.json"),
608376
609747
  join154(thisDir, "..", "..", "package.json"),
@@ -610214,7 +611585,7 @@ var init_commands = __esm({
610214
611585
 
610215
611586
  // packages/cli/src/tui/project-context.ts
610216
611587
  import { existsSync as existsSync108, readFileSync as readFileSync87, readdirSync as readdirSync36 } from "node:fs";
610217
- import { join as join121, basename as basename23 } from "node:path";
611588
+ import { join as join121, basename as basename24 } from "node:path";
610218
611589
  import { execSync as execSync54 } from "node:child_process";
610219
611590
  import { homedir as homedir42 } from "node:os";
610220
611591
  function getModelTier(modelName) {
@@ -610295,7 +611666,7 @@ function loadMemoryContext(repoRoot) {
610295
611666
  try {
610296
611667
  const raw = readFileSync87(join121(dir, file), "utf-8");
610297
611668
  const entries = JSON.parse(raw);
610298
- const topic = basename23(file, ".json");
611669
+ const topic = basename24(file, ".json");
610299
611670
  for (const [k, v] of Object.entries(entries)) {
610300
611671
  if (!v?.value) continue;
610301
611672
  all2.push({ topic, key: k, value: String(v.value), scope, ts: v.timestamp ?? "" });
@@ -610559,7 +611930,7 @@ __export(visual_identity_association_exports, {
610559
611930
  formatVisualIdentityAssociationContext: () => formatVisualIdentityAssociationContext,
610560
611931
  stageVisualIdentityAssertion: () => stageVisualIdentityAssertion
610561
611932
  });
610562
- import { basename as basename24 } from "node:path";
611933
+ import { basename as basename25 } from "node:path";
610563
611934
  function normalizePersonName(name10) {
610564
611935
  return name10.trim().toLowerCase().replace(/\s+/g, " ");
610565
611936
  }
@@ -610881,7 +612252,7 @@ async function associateVisualIdentityFromImage(options2) {
610881
612252
  relation: "same_person_candidate",
610882
612253
  confidence: match.confidence,
610883
612254
  assertedBy: { id: "visual_memory", displayName: "visual_memory", isBot: true },
610884
- note: `Prior enrolled visual-memory face match for ${basename24(options2.imagePath)}`
612255
+ note: `Prior enrolled visual-memory face match for ${basename25(options2.imagePath)}`
610885
612256
  }]
610886
612257
  });
610887
612258
  if (result2.episodeId) committedEpisodeIds.push(result2.episodeId);
@@ -610926,7 +612297,7 @@ async function associateVisualIdentityFromImage(options2) {
610926
612297
  relation: "depicts",
610927
612298
  confidence: item.confidence,
610928
612299
  assertedBy: item.sender || options2.sender,
610929
- note: item.note || `Applied explicit pending identity assertion to ${basename24(options2.imagePath)}`
612300
+ note: item.note || `Applied explicit pending identity assertion to ${basename25(options2.imagePath)}`
610930
612301
  }]
610931
612302
  });
610932
612303
  if (result2.episodeId) committedEpisodeIds.push(result2.episodeId);
@@ -610984,7 +612355,7 @@ var init_visual_identity_association = __esm({
610984
612355
 
610985
612356
  // packages/cli/src/tui/identity-memory-tool.ts
610986
612357
  import { existsSync as existsSync109 } from "node:fs";
610987
- import { basename as basename25, extname as extname14, resolve as resolve45 } from "node:path";
612358
+ import { basename as basename26, extname as extname14, resolve as resolve45 } from "node:path";
610988
612359
  function personKey2(name10) {
610989
612360
  return `person:${name10.trim().toLowerCase().replace(/\s+/g, " ")}`;
610990
612361
  }
@@ -611053,7 +612424,7 @@ async function resolveMediaFromArgs(args, opts) {
611053
612424
  path: path12,
611054
612425
  media,
611055
612426
  modality: inferModality(media),
611056
- label: basename25(path12)
612427
+ label: basename26(path12)
611057
612428
  };
611058
612429
  }
611059
612430
  function edgeDirection(edge, nodeId, otherText) {
@@ -611211,7 +612582,7 @@ var init_identity_memory_tool = __esm({
611211
612582
  } else if (shouldEnrollFace) {
611212
612583
  faceLine = "face enrollment: skipped because no resolved image path was available";
611213
612584
  }
611214
- const mediaLine = resolvedMedia ? `media: ${resolvedMedia.label || basename25(resolvedMedia.path)} (${resolvedMedia.path})` : "media: none; stored as scoped textual identity evidence only";
612585
+ const mediaLine = resolvedMedia ? `media: ${resolvedMedia.label || basename26(resolvedMedia.path)} (${resolvedMedia.path})` : "media: none; stored as scoped textual identity evidence only";
611215
612586
  const output = [
611216
612587
  `Stored identity evidence for ${name10}.`,
611217
612588
  `relation: ${relation}`,
@@ -612152,7 +613523,7 @@ var init_banner = __esm({
612152
613523
 
612153
613524
  // packages/cli/src/tui/carousel-descriptors.ts
612154
613525
  import { existsSync as existsSync111, readFileSync as readFileSync89, writeFileSync as writeFileSync56, mkdirSync as mkdirSync62, readdirSync as readdirSync37 } from "node:fs";
612155
- import { join as join124, basename as basename26 } from "node:path";
613526
+ import { join as join124, basename as basename27 } from "node:path";
612156
613527
  function loadToolProfile(repoRoot) {
612157
613528
  const filePath = join124(repoRoot, OMNIUS_DIR, "context", TOOL_PROFILE_FILE);
612158
613529
  try {
@@ -612248,7 +613619,7 @@ function generateDescriptors(repoRoot) {
612248
613619
  extractFromSessions(repoRoot, tags);
612249
613620
  extractFromMemory(repoRoot, tags);
612250
613621
  extractFromToolProfile(profile, tags);
612251
- const repoName2 = basename26(repoRoot);
613622
+ const repoName2 = basename27(repoRoot);
612252
613623
  if (repoName2 && !tags.includes(repoName2)) {
612253
613624
  tags.push(repoName2);
612254
613625
  }
@@ -613428,7 +614799,7 @@ var init_edit_history = __esm({
613428
614799
 
613429
614800
  // packages/cli/src/tui/promptLoader.ts
613430
614801
  import { readFileSync as readFileSync90, existsSync as existsSync112 } from "node:fs";
613431
- import { join as join126, dirname as dirname35 } from "node:path";
614802
+ import { join as join126, dirname as dirname36 } from "node:path";
613432
614803
  import { fileURLToPath as fileURLToPath16 } from "node:url";
613433
614804
  function loadPrompt3(promptPath, vars) {
613434
614805
  let content = cache7.get(promptPath);
@@ -613448,7 +614819,7 @@ var init_promptLoader3 = __esm({
613448
614819
  "packages/cli/src/tui/promptLoader.ts"() {
613449
614820
  "use strict";
613450
614821
  __filename5 = fileURLToPath16(import.meta.url);
613451
- __dirname6 = dirname35(__filename5);
614822
+ __dirname6 = dirname36(__filename5);
613452
614823
  devPath2 = join126(__dirname6, "..", "..", "prompts");
613453
614824
  publishedPath2 = join126(__dirname6, "..", "prompts");
613454
614825
  PROMPTS_DIR3 = existsSync112(devPath2) ? devPath2 : publishedPath2;
@@ -613458,7 +614829,7 @@ var init_promptLoader3 = __esm({
613458
614829
 
613459
614830
  // packages/cli/src/tui/dream-engine.ts
613460
614831
  import { mkdirSync as mkdirSync64, writeFileSync as writeFileSync57, readFileSync as readFileSync91, existsSync as existsSync113, readdirSync as readdirSync38 } from "node:fs";
613461
- import { join as join127, basename as basename27 } from "node:path";
614832
+ import { join as join127, basename as basename28 } from "node:path";
613462
614833
  import { execSync as execSync55 } from "node:child_process";
613463
614834
  function setDreamWriteContent(fn) {
613464
614835
  _dreamWriteContent = fn;
@@ -613671,7 +615042,7 @@ var init_dream_engine = __esm({
613671
615042
  const rawPath = String(args["path"] ?? "");
613672
615043
  const content = String(args["content"] ?? "");
613673
615044
  if (!rawPath) return { success: false, output: "", error: "path is required", durationMs: Date.now() - start2 };
613674
- const targetPath = rawPath.startsWith("/") || rawPath.startsWith(".omnius/autoresearch") ? join127(this.autoresearchDir, basename27(rawPath)) : join127(this.autoresearchDir, rawPath);
615045
+ const targetPath = rawPath.startsWith("/") || rawPath.startsWith(".omnius/autoresearch") ? join127(this.autoresearchDir, basename28(rawPath)) : join127(this.autoresearchDir, rawPath);
613675
615046
  if (!targetPath.startsWith(this.autoresearchDir)) {
613676
615047
  return { success: false, output: "", error: "Autoresearch mode: writes are confined to .omnius/autoresearch/", durationMs: Date.now() - start2 };
613677
615048
  }
@@ -613706,7 +615077,7 @@ var init_dream_engine = __esm({
613706
615077
  const rawPath = String(args["path"] ?? "");
613707
615078
  const oldStr = String(args["old_string"] ?? "");
613708
615079
  const newStr = String(args["new_string"] ?? "");
613709
- const targetPath = rawPath.startsWith("/") || rawPath.startsWith(".omnius/autoresearch") ? join127(this.autoresearchDir, basename27(rawPath)) : join127(this.autoresearchDir, rawPath);
615080
+ const targetPath = rawPath.startsWith("/") || rawPath.startsWith(".omnius/autoresearch") ? join127(this.autoresearchDir, basename28(rawPath)) : join127(this.autoresearchDir, rawPath);
613710
615081
  if (!targetPath.startsWith(this.autoresearchDir)) {
613711
615082
  return { success: false, output: "", error: "Autoresearch mode: edits are confined to .omnius/autoresearch/", durationMs: Date.now() - start2 };
613712
615083
  }
@@ -613759,7 +615130,7 @@ var init_dream_engine = __esm({
613759
615130
  const rawPath = String(args["path"] ?? "");
613760
615131
  const content = String(args["content"] ?? "");
613761
615132
  if (!rawPath) return { success: false, output: "", error: "path is required", durationMs: Date.now() - start2 };
613762
- const targetPath = rawPath.startsWith("/") || rawPath.startsWith(".omnius/dreams") ? join127(this.dreamsDir, basename27(rawPath)) : join127(this.dreamsDir, rawPath);
615133
+ const targetPath = rawPath.startsWith("/") || rawPath.startsWith(".omnius/dreams") ? join127(this.dreamsDir, basename28(rawPath)) : join127(this.dreamsDir, rawPath);
613763
615134
  if (!targetPath.startsWith(this.dreamsDir)) {
613764
615135
  return { success: false, output: "", error: "Dream mode: writes are confined to .omnius/dreams/", durationMs: Date.now() - start2 };
613765
615136
  }
@@ -613794,7 +615165,7 @@ var init_dream_engine = __esm({
613794
615165
  const rawPath = String(args["path"] ?? "");
613795
615166
  const oldStr = String(args["old_string"] ?? "");
613796
615167
  const newStr = String(args["new_string"] ?? "");
613797
- const targetPath = rawPath.startsWith("/") || rawPath.startsWith(".omnius/dreams") ? join127(this.dreamsDir, basename27(rawPath)) : join127(this.dreamsDir, rawPath);
615168
+ const targetPath = rawPath.startsWith("/") || rawPath.startsWith(".omnius/dreams") ? join127(this.dreamsDir, basename28(rawPath)) : join127(this.dreamsDir, rawPath);
613798
615169
  if (!targetPath.startsWith(this.dreamsDir)) {
613799
615170
  return { success: false, output: "", error: "Dream mode: edits are confined to .omnius/dreams/", durationMs: Date.now() - start2 };
613800
615171
  }
@@ -615395,7 +616766,7 @@ var init_bless_engine = __esm({
615395
616766
 
615396
616767
  // packages/cli/src/tui/dmn-engine.ts
615397
616768
  import { existsSync as existsSync114, readFileSync as readFileSync92, writeFileSync as writeFileSync58, mkdirSync as mkdirSync65, readdirSync as readdirSync39, unlinkSync as unlinkSync21 } from "node:fs";
615398
- import { join as join128, basename as basename28 } from "node:path";
616769
+ import { join as join128, basename as basename29 } from "node:path";
615399
616770
  function buildDMNGatherPrompt(recentTaskSummaries, dueReminders, attentionItems, memoryTopics, capabilities, competence, reflectionBuffer) {
615400
616771
  const competenceReport = competence.length > 0 ? competence.map((c8) => {
615401
616772
  const rate = c8.attempts > 0 ? Math.round(c8.successes / c8.attempts * 100) : 0;
@@ -616146,7 +617517,7 @@ OUTPUT: Call task_complete with JSON:
616146
617517
  try {
616147
617518
  const files = readdirSync39(dir).filter((f2) => f2.endsWith(".json"));
616148
617519
  for (const f2 of files) {
616149
- const topic = basename28(f2, ".json");
617520
+ const topic = basename29(f2, ".json");
616150
617521
  if (!topics.includes(topic)) topics.push(topic);
616151
617522
  }
616152
617523
  } catch {
@@ -616200,7 +617571,7 @@ OUTPUT: Call task_complete with JSON:
616200
617571
 
616201
617572
  // packages/cli/src/tui/snr-engine.ts
616202
617573
  import { existsSync as existsSync115, readdirSync as readdirSync40, readFileSync as readFileSync93 } from "node:fs";
616203
- import { join as join129, basename as basename29 } from "node:path";
617574
+ import { join as join129, basename as basename30 } from "node:path";
616204
617575
  function computeDPrime(signalScores, noiseScores) {
616205
617576
  if (signalScores.length === 0 || noiseScores.length === 0) return 0;
616206
617577
  const mean = (arr) => arr.reduce((s2, v) => s2 + v, 0) / arr.length;
@@ -616494,7 +617865,7 @@ Call task_complete with the JSON array when done.`,
616494
617865
  try {
616495
617866
  const files = readdirSync40(dir).filter((f2) => f2.endsWith(".json"));
616496
617867
  for (const f2 of files) {
616497
- const topic = basename29(f2, ".json");
617868
+ const topic = basename30(f2, ".json");
616498
617869
  if (topics.length > 0 && !topics.includes(topic)) continue;
616499
617870
  try {
616500
617871
  const data = JSON.parse(readFileSync93(join129(dir, f2), "utf-8"));
@@ -617977,8 +619348,8 @@ import {
617977
619348
  } from "node:fs";
617978
619349
  import { mkdir as mkdir19 } from "node:fs/promises";
617979
619350
  import {
617980
- basename as basename30,
617981
- dirname as dirname36,
619351
+ basename as basename31,
619352
+ dirname as dirname37,
617982
619353
  extname as extname15,
617983
619354
  isAbsolute as isAbsolute7,
617984
619355
  join as join130,
@@ -618142,7 +619513,7 @@ function scopedTool(base3, root, mode) {
618142
619513
  if (mode === "edit" && !existsSync116(guarded.path.abs)) {
618143
619514
  const materialized = materializeTelegramCreativeArtifactForSend(rootAbs, guarded.path.rel);
618144
619515
  if (!materialized.ok) return denied(materialized.error);
618145
- mkdirSync66(dirname36(guarded.path.abs), { recursive: true });
619516
+ mkdirSync66(dirname37(guarded.path.abs), { recursive: true });
618146
619517
  writeFileSync59(guarded.path.abs, readFileSync94(materialized.path));
618147
619518
  materialized.cleanup?.();
618148
619519
  restoredEditPath = guarded.path.abs;
@@ -618211,7 +619582,7 @@ function guardPath(root, rawPath) {
618211
619582
  error: `Path escapes the public creative workspace. Use a relative path under ${rootAbs}.`
618212
619583
  };
618213
619584
  }
618214
- if (basename30(abs) === MANIFEST_FILE) {
619585
+ if (basename31(abs) === MANIFEST_FILE) {
618215
619586
  return { ok: false, error: "The creative workspace manifest is internal and cannot be edited." };
618216
619587
  }
618217
619588
  return { ok: true, path: { abs, rel } };
@@ -618303,7 +619674,7 @@ function rememberCreated(root, absPath) {
618303
619674
  manifest.objects[rel] = {
618304
619675
  logicalRel: rel,
618305
619676
  storedRel,
618306
- originalName: basename30(guarded.path.abs),
619677
+ originalName: basename31(guarded.path.abs),
618307
619678
  prefixBytes: prefix.length,
618308
619679
  encrypted: true,
618309
619680
  key: key.toString("base64"),
@@ -618354,7 +619725,7 @@ function materializeTelegramCreativeArtifactForSend(root, rawPath) {
618354
619725
  }
618355
619726
  const stageDir = join130(rootAbs, SEND_DIR, `${Date.now()}-${randomBytes23(8).toString("hex")}`);
618356
619727
  mkdirSync66(stageDir, { recursive: true });
618357
- const staged = join130(stageDir, object.originalName || basename30(rel));
619728
+ const staged = join130(stageDir, object.originalName || basename31(rel));
618358
619729
  writeFileSync59(staged, payload);
618359
619730
  return {
618360
619731
  ok: true,
@@ -618522,7 +619893,7 @@ var init_telegram_creative_tools = __esm({
618522
619893
  }
618523
619894
  let result;
618524
619895
  try {
618525
- await mkdir19(dirname36(guarded.path.abs), { recursive: true });
619896
+ await mkdir19(dirname37(guarded.path.abs), { recursive: true });
618526
619897
  const tts = new TtsGenerateTool();
618527
619898
  result = await tts.execute({
618528
619899
  text,
@@ -619024,7 +620395,7 @@ var init_soul_observations = __esm({
619024
620395
  // packages/cli/src/tui/telegram-channel-dmn.ts
619025
620396
  import { existsSync as existsSync117, mkdirSync as mkdirSync67, readdirSync as readdirSync41, readFileSync as readFileSync95, writeFileSync as writeFileSync60 } from "node:fs";
619026
620397
  import { join as join131 } from "node:path";
619027
- import { createHash as createHash24 } from "node:crypto";
620398
+ import { createHash as createHash26 } from "node:crypto";
619028
620399
  function safeFilePart(value2) {
619029
620400
  return value2.replace(/[^A-Za-z0-9_.-]+/g, "_").slice(0, 80) || "telegram";
619030
620401
  }
@@ -619032,7 +620403,7 @@ function daydreamRoot(repoRoot) {
619032
620403
  return join131(repoRoot, ".omnius", "telegram-daydreams");
619033
620404
  }
619034
620405
  function sessionDir(repoRoot, sessionKey) {
619035
- const hash = createHash24("sha1").update(sessionKey).digest("hex").slice(0, 20);
620406
+ const hash = createHash26("sha1").update(sessionKey).digest("hex").slice(0, 20);
619036
620407
  return join131(daydreamRoot(repoRoot), safeFilePart(hash));
619037
620408
  }
619038
620409
  function compactLine2(value2, max = 220) {
@@ -619117,7 +620488,7 @@ function buildReplyOpportunities(input, openQuestions) {
619117
620488
  return opportunities;
619118
620489
  }
619119
620490
  function daydreamOpportunityId(input, trigger) {
619120
- return createHash24("sha1").update(`${input.sessionKey}:${input.generatedAtMs}:${trigger}`).digest("hex").slice(0, 16);
620491
+ return createHash26("sha1").update(`${input.sessionKey}:${input.generatedAtMs}:${trigger}`).digest("hex").slice(0, 16);
619121
620492
  }
619122
620493
  function clamp019(value2) {
619123
620494
  if (!Number.isFinite(value2)) return 0;
@@ -619437,7 +620808,7 @@ function buildTelegramChannelDaydream(input, corpus, extraction, extractionCommi
619437
620808
  const seed = `${input.sessionKey}:${input.generatedAtMs}:${input.history.length}`;
619438
620809
  return {
619439
620810
  version: 3,
619440
- id: createHash24("sha1").update(seed).digest("hex").slice(0, 16),
620811
+ id: createHash26("sha1").update(seed).digest("hex").slice(0, 16),
619441
620812
  sessionKey: input.sessionKey,
619442
620813
  chatId: input.chatId,
619443
620814
  chatTitle: input.chatTitle,
@@ -619650,12 +621021,12 @@ var init_telegram_channel_dmn = __esm({
619650
621021
  });
619651
621022
 
619652
621023
  // packages/cli/src/tui/telegram-reflection-corpus.ts
619653
- import { createHash as createHash25 } from "node:crypto";
621024
+ import { createHash as createHash27 } from "node:crypto";
619654
621025
  function telegramReflectionMemoryDbPaths(repoRoot) {
619655
621026
  return omniusMemoryDbPaths(repoRoot);
619656
621027
  }
619657
621028
  function stableHash2(value2, length4 = 16) {
619658
- return createHash25("sha1").update(value2).digest("hex").slice(0, length4);
621029
+ return createHash27("sha1").update(value2).digest("hex").slice(0, length4);
619659
621030
  }
619660
621031
  function clean3(value2) {
619661
621032
  return String(value2 ?? "").replace(/\s+/g, " ").trim();
@@ -620385,7 +621756,7 @@ var init_telegram_reflection_extraction = __esm({
620385
621756
  });
620386
621757
 
620387
621758
  // packages/cli/src/tui/telegram-social-state-types.ts
620388
- import { createHash as createHash26 } from "node:crypto";
621759
+ import { createHash as createHash28 } from "node:crypto";
620389
621760
  function telegramSocialActorKey(actor) {
620390
621761
  if (!actor) return "unknown";
620391
621762
  if (typeof actor.userId === "number") return `user:${actor.userId}`;
@@ -620409,7 +621780,7 @@ function appendUnique(items, value2, max) {
620409
621780
  return next.slice(-max);
620410
621781
  }
620411
621782
  function hashTelegramSocialId(parts) {
620412
- return createHash26("sha1").update(parts.map((part) => String(part ?? "")).join(":")).digest("hex").slice(0, 16);
621783
+ return createHash28("sha1").update(parts.map((part) => String(part ?? "")).join(":")).digest("hex").slice(0, 16);
620413
621784
  }
620414
621785
  function cleanUsername(value2) {
620415
621786
  if (typeof value2 !== "string") return void 0;
@@ -621187,10 +622558,10 @@ var init_vision_ingress = __esm({
621187
622558
 
621188
622559
  // packages/cli/src/tui/telegram-bridge.ts
621189
622560
  import { mkdirSync as mkdirSync68, existsSync as existsSync119, unlinkSync as unlinkSync24, readdirSync as readdirSync42, statSync as statSync43, statfsSync as statfsSync5, readFileSync as readFileSync97, writeFileSync as writeFileSync62, appendFileSync as appendFileSync10 } from "node:fs";
621190
- import { join as join133, resolve as resolve47, basename as basename31, relative as relative13, isAbsolute as isAbsolute8, extname as extname16 } from "node:path";
622561
+ import { join as join133, resolve as resolve47, basename as basename32, relative as relative13, isAbsolute as isAbsolute8, extname as extname16 } from "node:path";
621191
622562
  import { homedir as homedir43 } from "node:os";
621192
622563
  import { writeFile as writeFileAsync } from "node:fs/promises";
621193
- import { createHash as createHash27, randomBytes as randomBytes24, randomInt } from "node:crypto";
622564
+ import { createHash as createHash29, randomBytes as randomBytes24, randomInt } from "node:crypto";
621194
622565
  function cleanTelegramDecisionNote(value2, maxLength = 260) {
621195
622566
  if (typeof value2 !== "string") return void 0;
621196
622567
  const clean5 = stripTelegramHiddenThinking(value2).replace(/\s+/g, " ").trim();
@@ -622129,7 +623500,7 @@ function buildTelegramRuntimeContext(now = /* @__PURE__ */ new Date(), repoRoot)
622129
623500
  ].filter(Boolean).join("\n");
622130
623501
  }
622131
623502
  function telegramSessionIdFromKey(sessionKey) {
622132
- return `telegram-${createHash27("sha1").update(sessionKey).digest("hex").slice(0, 16)}`;
623503
+ return `telegram-${createHash29("sha1").update(sessionKey).digest("hex").slice(0, 16)}`;
622133
623504
  }
622134
623505
  function normalizeTelegramSubAgentLimit(value2) {
622135
623506
  const parsed = typeof value2 === "number" ? value2 : typeof value2 === "string" && value2.trim() ? Number(value2.trim()) : TELEGRAM_SUB_AGENT_DEFAULT_LIMIT;
@@ -623744,7 +625115,7 @@ External acquisition contract:
623744
625115
  return !!this.adminAuthChallenge && this.adminAuthChallenge.expiresAtMs > Date.now();
623745
625116
  }
623746
625117
  hashAdminAuthCode(code8) {
623747
- return createHash27("sha256").update(`omnius-telegram-admin:${code8.trim()}`).digest("hex");
625118
+ return createHash29("sha256").update(`omnius-telegram-admin:${code8.trim()}`).digest("hex");
623748
625119
  }
623749
625120
  viewIdForMessage(msg) {
623750
625121
  return `telegram-${this.sessionKeyForMessage(msg).replace(/[^A-Za-z0-9_-]/g, "-")}`;
@@ -624667,11 +626038,11 @@ ${mediaContext}` : ""
624667
626038
  return payload;
624668
626039
  }
624669
626040
  telegramConversationPath(sessionKey) {
624670
- const safe = createHash27("sha1").update(sessionKey).digest("hex").slice(0, 20);
626041
+ const safe = createHash29("sha1").update(sessionKey).digest("hex").slice(0, 20);
624671
626042
  return join133(this.telegramConversationDir, `${safe}.json`);
624672
626043
  }
624673
626044
  telegramConversationLedgerPath(sessionKey) {
624674
- const safe = createHash27("sha1").update(sessionKey).digest("hex").slice(0, 20);
626045
+ const safe = createHash29("sha1").update(sessionKey).digest("hex").slice(0, 20);
624675
626046
  return join133(this.telegramConversationDir, `${safe}.events.jsonl`);
624676
626047
  }
624677
626048
  telegramDb() {
@@ -624899,7 +626270,7 @@ ${mediaContext}` : ""
624899
626270
  users,
624900
626271
  relationships: Array.isArray(raw.relationships) ? raw.relationships.slice(0, TELEGRAM_ASSOCIATIVE_RELATION_LIMIT).map((fact) => this.normalizeTelegramAssociativeFact(fact)) : [],
624901
626272
  actions: Array.isArray(raw.actions) ? raw.actions.slice(-TELEGRAM_ASSOCIATIVE_ACTION_LIMIT).map((action) => ({
624902
- id: String(action.id || createHash27("sha1").update(JSON.stringify(action)).digest("hex").slice(0, 12)),
626273
+ id: String(action.id || createHash29("sha1").update(JSON.stringify(action)).digest("hex").slice(0, 12)),
624903
626274
  ts: typeof action.ts === "number" ? action.ts : Date.now(),
624904
626275
  role: action.role === "assistant" ? "assistant" : "user",
624905
626276
  speaker: String(action.speaker || "unknown"),
@@ -624916,7 +626287,7 @@ ${mediaContext}` : ""
624916
626287
  const text = String(raw.text || "").trim();
624917
626288
  const now = Date.now();
624918
626289
  return {
624919
- id: String(raw.id || createHash27("sha1").update(text || String(now)).digest("hex").slice(0, 12)),
626290
+ id: String(raw.id || createHash29("sha1").update(text || String(now)).digest("hex").slice(0, 12)),
624920
626291
  text,
624921
626292
  tags: Array.isArray(raw.tags) ? raw.tags.map(String).slice(0, 16) : [],
624922
626293
  speakers: Array.isArray(raw.speakers) ? raw.speakers.map(String).slice(0, 16) : [],
@@ -625118,7 +626489,7 @@ ${mediaContext}` : ""
625118
626489
  }
625119
626490
  telegramHistoryBackfillMessageId(sessionKey, entry, index) {
625120
626491
  if (typeof entry.messageId === "number" && Number.isFinite(entry.messageId)) return entry.messageId;
625121
- const digest3 = createHash27("sha1").update(`${sessionKey}:${index}:${entry.role}:${entry.ts ?? ""}:${entry.text}`).digest("hex").slice(0, 8);
626492
+ const digest3 = createHash29("sha1").update(`${sessionKey}:${index}:${entry.role}:${entry.ts ?? ""}:${entry.text}`).digest("hex").slice(0, 8);
625122
626493
  return -Number.parseInt(digest3, 16);
625123
626494
  }
625124
626495
  backfillTelegramLoadedHistory(sessionKey, history) {
@@ -625889,7 +627260,7 @@ ${mediaContext}` : ""
625889
627260
  }
625890
627261
  const matchingEntry = mediaEntries.find((entry) => {
625891
627262
  if (resolve47(entry.localPath) === resolve47(raw)) return true;
625892
- if (basename31(entry.localPath) === raw) return true;
627263
+ if (basename32(entry.localPath) === raw) return true;
625893
627264
  if (entry.fileUniqueId === raw || entry.fileId === raw) return true;
625894
627265
  if (entry.messageId && String(entry.messageId) === raw) return true;
625895
627266
  if (entry.messageId && `message_id:${entry.messageId}` === raw.toLowerCase()) return true;
@@ -625926,7 +627297,7 @@ ${mediaContext}` : ""
625926
627297
  }
625927
627298
  return entries.find((entry2) => {
625928
627299
  if (resolve47(entry2.localPath) === resolve47(ref)) return true;
625929
- if (basename31(entry2.localPath) === ref) return true;
627300
+ if (basename32(entry2.localPath) === ref) return true;
625930
627301
  if (entry2.fileUniqueId === ref || entry2.fileId === ref) return true;
625931
627302
  if (entry2.messageId && String(entry2.messageId) === ref) return true;
625932
627303
  return false;
@@ -625954,7 +627325,7 @@ ${mediaContext}` : ""
625954
627325
  caption: entry.caption
625955
627326
  },
625956
627327
  modality,
625957
- label: `Telegram message_id ${entry.messageId || "unknown"} ${basename31(entry.localPath)}`,
627328
+ label: `Telegram message_id ${entry.messageId || "unknown"} ${basename32(entry.localPath)}`,
625958
627329
  extractedContent: entry.extractedContent
625959
627330
  };
625960
627331
  }
@@ -626011,7 +627382,7 @@ ${mediaContext}` : ""
626011
627382
  const now = entry.ts ?? Date.now();
626012
627383
  memory.updatedAt = now;
626013
627384
  const speaker = telegramHistorySpeaker(entry);
626014
- const actionId = createHash27("sha1").update(`${sessionKey}:${entry.role}:${entry.messageId ?? ""}:${now}:${entry.text}`).digest("hex").slice(0, 16);
627385
+ const actionId = createHash29("sha1").update(`${sessionKey}:${entry.role}:${entry.messageId ?? ""}:${now}:${entry.text}`).digest("hex").slice(0, 16);
626015
627386
  if (!memory.actions.some((action) => action.id === actionId)) {
626016
627387
  memory.actions.push({
626017
627388
  id: actionId,
@@ -626133,7 +627504,7 @@ ${mediaContext}` : ""
626133
627504
  let fact = facts.find((item) => item.text.toLowerCase() === key);
626134
627505
  if (!fact) {
626135
627506
  fact = {
626136
- id: createHash27("sha1").update(`${entry.chatId ?? ""}:${key}`).digest("hex").slice(0, 12),
627507
+ id: createHash29("sha1").update(`${entry.chatId ?? ""}:${key}`).digest("hex").slice(0, 12),
626137
627508
  text: clean5,
626138
627509
  tags: telegramMemoryTags(clean5, entry.mediaSummary),
626139
627510
  speakers: [],
@@ -626188,7 +627559,7 @@ ${mediaContext}` : ""
626188
627559
  const titleTags = tags.slice(0, 4);
626189
627560
  const title = titleTags.length > 0 ? `${speaker} / ${titleTags.join(" ")}` : `${speaker} / conversation`;
626190
627561
  const card = {
626191
- id: createHash27("sha1").update(`${sessionKey}:${now}:${speaker}:${text}`).digest("hex").slice(0, 12),
627562
+ id: createHash29("sha1").update(`${sessionKey}:${now}:${speaker}:${text}`).digest("hex").slice(0, 12),
626192
627563
  title,
626193
627564
  notes: [],
626194
627565
  tags: [],
@@ -626905,8 +628276,8 @@ ${cardLines.join("\n")}`);
626905
628276
  const caption = entry.caption ? ` caption=${telegramContextJsonString(entry.caption, 120)}` : "";
626906
628277
  const extracted = entry.extractedContent ? `
626907
628278
  extracted=${telegramContextJsonString(entry.extractedContent.replace(/\s+/g, " "), 220)}` : "";
626908
- const alias = entry.messageId ? `message_id:${entry.messageId}` : basename31(entry.localPath);
626909
- return `- ${alias}${replyMark}: ${kind}; file ${basename31(entry.localPath)}${caption}${extracted}`;
628279
+ const alias = entry.messageId ? `message_id:${entry.messageId}` : basename32(entry.localPath);
628280
+ return `- ${alias}${replyMark}: ${kind}; file ${basename32(entry.localPath)}${caption}${extracted}`;
626910
628281
  });
626911
628282
  sections.push([
626912
628283
  "### Recent Chat Media",
@@ -628330,7 +629701,7 @@ ${list}` : "No shared group target is currently known for this sender. Ask in th
628330
629701
  }
628331
629702
  telegramRunnerStateDir(sessionKey) {
628332
629703
  if (!this.repoRoot) return void 0;
628333
- const safe = createHash27("sha1").update(sessionKey).digest("hex").slice(0, 20);
629704
+ const safe = createHash29("sha1").update(sessionKey).digest("hex").slice(0, 20);
628334
629705
  return join133(this.repoRoot, ".omnius", "telegram-runner-state", safe);
628335
629706
  }
628336
629707
  buildTelegramAdminOverviewContext(currentSessionKey) {
@@ -631781,12 +633152,12 @@ Scoped workspace: ${scopedRoot}`,
631781
633152
  return { success: true, output: `No recent ${kind} media is available in this Telegram chat scope.`, durationMs: performance.now() - start2 };
631782
633153
  }
631783
633154
  const lines = entries.map((entry, index) => {
631784
- const pathAlias = entry.messageId ? `message_id:${entry.messageId}` : basename31(entry.localPath);
633155
+ const pathAlias = entry.messageId ? `message_id:${entry.messageId}` : basename32(entry.localPath);
631785
633156
  const parts = [
631786
633157
  `${index + 1}. message_id ${entry.messageId || "unknown"}`,
631787
633158
  currentMsg?.replyToMessageId === entry.messageId ? "replied-to" : "",
631788
633159
  telegramCachedMediaIsImage(entry) ? "image" : telegramCachedMediaIsPdf(entry) ? "pdf" : telegramCachedMediaIsAudio(entry) ? "audio" : telegramCachedMediaIsVideo(entry) ? "video" : entry.mediaType,
631789
- `file=${basename31(entry.localPath)}`,
633160
+ `file=${basename32(entry.localPath)}`,
631790
633161
  `path_alias=${pathAlias}`,
631791
633162
  entry.caption ? `caption=${telegramContextJsonString(entry.caption, 140)}` : ""
631792
633163
  ].filter(Boolean);
@@ -631913,8 +633284,8 @@ Scoped workspace: ${scopedRoot}`,
631913
633284
  if (bridge.telegramFileSendAlreadyDeliveredForMessage(currentMsg, sendFingerprint)) {
631914
633285
  return {
631915
633286
  success: true,
631916
- output: `Telegram file already sent in this turn: ${basename31(file.path)} as ${kind} to ${String(target.chatId)}`,
631917
- llmContent: `Already sent ${basename31(file.path)} to Telegram as ${kind}; do not send it again.`,
633287
+ output: `Telegram file already sent in this turn: ${basename32(file.path)} as ${kind} to ${String(target.chatId)}`,
633288
+ llmContent: `Already sent ${basename32(file.path)} to Telegram as ${kind}; do not send it again.`,
631918
633289
  durationMs: performance.now() - start2,
631919
633290
  mutated: false,
631920
633291
  mutatedFiles: []
@@ -631931,8 +633302,8 @@ Scoped workspace: ${scopedRoot}`,
631931
633302
  bridge.rememberTelegramDeliveredArtifactForMessage(currentMsg, ledgerPath);
631932
633303
  return {
631933
633304
  success: true,
631934
- output: `Sent Telegram file: ${basename31(file.path)} as ${kind} to ${String(target.chatId)}${messageId ? ` (message_id ${messageId})` : ""}`,
631935
- llmContent: `Sent ${basename31(file.path)} to Telegram as ${kind}.`,
633305
+ output: `Sent Telegram file: ${basename32(file.path)} as ${kind} to ${String(target.chatId)}${messageId ? ` (message_id ${messageId})` : ""}`,
633306
+ llmContent: `Sent ${basename32(file.path)} to Telegram as ${kind}.`,
631936
633307
  durationMs: performance.now() - start2,
631937
633308
  mutated: false,
631938
633309
  mutatedFiles: []
@@ -632417,7 +633788,7 @@ ${text}`.trim());
632417
633788
  if (!existsSync119(media.value)) throw new Error(`File does not exist: ${media.value}`);
632418
633789
  const buffer2 = readFileSync97(media.value);
632419
633790
  const boundary = `----omnius-media-${Date.now()}-${Math.random().toString(36).slice(2)}`;
632420
- const filename = basename31(media.value);
633791
+ const filename = basename32(media.value);
632421
633792
  const contentType = mimeForPath(media.value, media.kind);
632422
633793
  const parts = [];
632423
633794
  const addField = (name10, value2) => {
@@ -632657,7 +634028,7 @@ Content-Type: ${contentType}\r
632657
634028
  continue;
632658
634029
  }
632659
634030
  const buffer2 = readFileSync97(pathOrFileId);
632660
- const filename = basename31(pathOrFileId);
634031
+ const filename = basename32(pathOrFileId);
632661
634032
  parts.push(Buffer.from(`--${boundary}\r
632662
634033
  `));
632663
634034
  parts.push(Buffer.from(
@@ -633868,7 +635239,7 @@ __export(projects_exports, {
633868
635239
  });
633869
635240
  import { readFileSync as readFileSync99, writeFileSync as writeFileSync64, mkdirSync as mkdirSync70, existsSync as existsSync121, statSync as statSync44, renameSync as renameSync7 } from "node:fs";
633870
635241
  import { homedir as homedir45 } from "node:os";
633871
- import { basename as basename32, join as join135, resolve as resolve48 } from "node:path";
635242
+ import { basename as basename33, join as join135, resolve as resolve48 } from "node:path";
633872
635243
  import { randomUUID as randomUUID15 } from "node:crypto";
633873
635244
  function readAll2() {
633874
635245
  try {
@@ -633916,7 +635287,7 @@ function registerProject(root, pid) {
633916
635287
  } else {
633917
635288
  entry = {
633918
635289
  root: canonical,
633919
- name: basename32(canonical) || canonical,
635290
+ name: basename33(canonical) || canonical,
633920
635291
  firstSeen: now,
633921
635292
  lastSeen: now,
633922
635293
  pid: pid ?? null,
@@ -634856,14 +636227,14 @@ var init_access_policy = __esm({
634856
636227
  });
634857
636228
 
634858
636229
  // packages/cli/src/api/project-preferences.ts
634859
- import { createHash as createHash28 } from "node:crypto";
636230
+ import { createHash as createHash30 } from "node:crypto";
634860
636231
  import { existsSync as existsSync122, mkdirSync as mkdirSync71, readFileSync as readFileSync100, renameSync as renameSync8, writeFileSync as writeFileSync65, unlinkSync as unlinkSync26 } from "node:fs";
634861
636232
  import { homedir as homedir46 } from "node:os";
634862
636233
  import { join as join136, resolve as resolve49 } from "node:path";
634863
636234
  import { randomUUID as randomUUID16 } from "node:crypto";
634864
636235
  function projectKey(root) {
634865
636236
  const canonical = resolve49(root);
634866
- return createHash28("sha256").update(canonical).digest("hex").slice(0, 16);
636237
+ return createHash30("sha256").update(canonical).digest("hex").slice(0, 16);
634867
636238
  }
634868
636239
  function projectDir(root) {
634869
636240
  return join136(PROJECTS_DIR, projectKey(root));
@@ -635916,7 +637287,7 @@ var init_audit_log = __esm({
635916
637287
  // packages/cli/src/api/disk-task-output.ts
635917
637288
  import { open } from "node:fs/promises";
635918
637289
  import { existsSync as existsSync124, mkdirSync as mkdirSync73, statSync as statSync45 } from "node:fs";
635919
- import { dirname as dirname38 } from "node:path";
637290
+ import { dirname as dirname39 } from "node:path";
635920
637291
  import * as fsConstants from "node:constants";
635921
637292
  var O_NOFOLLOW2, O_APPEND2, O_CREAT2, O_WRONLY2, OPEN_FLAGS_WRITE, OPEN_MODE, DiskTaskOutput;
635922
637293
  var init_disk_task_output = __esm({
@@ -635935,7 +637306,7 @@ var init_disk_task_output = __esm({
635935
637306
  fileSize = 0;
635936
637307
  constructor(outputPath3) {
635937
637308
  this.path = outputPath3;
635938
- mkdirSync73(dirname38(outputPath3), { recursive: true });
637309
+ mkdirSync73(dirname39(outputPath3), { recursive: true });
635939
637310
  }
635940
637311
  /** Queue content for async append. Non-blocking. */
635941
637312
  append(chunk) {
@@ -636041,7 +637412,7 @@ var init_disk_task_output = __esm({
636041
637412
  });
636042
637413
 
636043
637414
  // packages/cli/src/api/http.ts
636044
- import { createHash as createHash29 } from "node:crypto";
637415
+ import { createHash as createHash31 } from "node:crypto";
636045
637416
  function problemDetails(opts) {
636046
637417
  const p2 = {
636047
637418
  type: opts.type ?? "about:blank",
@@ -636104,7 +637475,7 @@ function paginated(items, page2, total) {
636104
637475
  }
636105
637476
  function computeEtag(payload) {
636106
637477
  const json = typeof payload === "string" ? payload : JSON.stringify(payload);
636107
- const hash = createHash29("sha1").update(json).digest("hex").slice(0, 16);
637478
+ const hash = createHash31("sha1").update(json).digest("hex").slice(0, 16);
636108
637479
  return `W/"${hash}"`;
636109
637480
  }
636110
637481
  function checkNotModified(req2, res, etag) {
@@ -650048,7 +651419,7 @@ var init_profiles = __esm({
650048
651419
  // packages/cli/src/docker.ts
650049
651420
  import { execSync as execSync57, spawn as spawn31 } from "node:child_process";
650050
651421
  import { existsSync as existsSync132, mkdirSync as mkdirSync78, writeFileSync as writeFileSync70 } from "node:fs";
650051
- import { join as join145, resolve as resolve50, dirname as dirname39 } from "node:path";
651422
+ import { join as join145, resolve as resolve50, dirname as dirname40 } from "node:path";
650052
651423
  import { homedir as homedir52 } from "node:os";
650053
651424
  import { fileURLToPath as fileURLToPath17 } from "node:url";
650054
651425
  function getDockerDir() {
@@ -650059,7 +651430,7 @@ function getDockerDir() {
650059
651430
  } catch {
650060
651431
  }
650061
651432
  try {
650062
- const thisDir = dirname39(fileURLToPath17(import.meta.url));
651433
+ const thisDir = dirname40(fileURLToPath17(import.meta.url));
650063
651434
  return join145(thisDir, "..", "..", "..", "docker");
650064
651435
  } catch {
650065
651436
  }
@@ -650346,7 +651717,7 @@ __export(embedding_workers_exports, {
650346
651717
  startEmbeddingWorkers: () => startEmbeddingWorkers,
650347
651718
  stopEmbeddingWorkers: () => stopEmbeddingWorkers
650348
651719
  });
650349
- import { basename as basename33, join as join146 } from "node:path";
651720
+ import { basename as basename34, join as join146 } from "node:path";
650350
651721
  function startEmbeddingWorkers(opts) {
650351
651722
  if (_running) return;
650352
651723
  _running = true;
@@ -650412,7 +651783,7 @@ async function runEmbeddingTask(modality, episodeId, taskId, opts) {
650412
651783
  try {
650413
651784
  if (!_aligner) {
650414
651785
  const stateRoot = process.env.OMNIUS_DIR || process.cwd();
650415
- const omniusDir = basename33(stateRoot) === ".omnius" ? stateRoot : join146(stateRoot, ".omnius");
651786
+ const omniusDir = basename34(stateRoot) === ".omnius" ? stateRoot : join146(stateRoot, ".omnius");
650416
651787
  const memDir = join146(omniusDir, "memory");
650417
651788
  _aligner = new EmbeddingAligner(
650418
651789
  `${modality}-${emb.length}`,
@@ -650528,12 +651899,12 @@ import * as http5 from "node:http";
650528
651899
  import * as https3 from "node:https";
650529
651900
  import { createRequire as createRequire7 } from "node:module";
650530
651901
  import { fileURLToPath as fileURLToPath18 } from "node:url";
650531
- import { dirname as dirname40, join as join147, resolve as resolve51 } from "node:path";
651902
+ import { dirname as dirname41, join as join147, resolve as resolve51 } from "node:path";
650532
651903
  import { homedir as homedir53 } from "node:os";
650533
651904
  import { spawn as spawn32, execSync as execSync58 } from "node:child_process";
650534
651905
  import { mkdirSync as mkdirSync79, writeFileSync as writeFileSync71, readFileSync as readFileSync108, readdirSync as readdirSync47, existsSync as existsSync133, watch as fsWatch4, renameSync as renameSync9, unlinkSync as unlinkSync28 } from "node:fs";
650535
651906
  import { randomBytes as randomBytes27, randomUUID as randomUUID17 } from "node:crypto";
650536
- import { createHash as createHash31 } from "node:crypto";
651907
+ import { createHash as createHash33 } from "node:crypto";
650537
651908
  function memoryDbPaths3(baseDir = process.cwd()) {
650538
651909
  const dir = join147(baseDir, ".omnius");
650539
651910
  return {
@@ -650544,7 +651915,7 @@ function memoryDbPaths3(baseDir = process.cwd()) {
650544
651915
  }
650545
651916
  function getVersion3() {
650546
651917
  try {
650547
- const thisDir = dirname40(fileURLToPath18(import.meta.url));
651918
+ const thisDir = dirname41(fileURLToPath18(import.meta.url));
650548
651919
  const candidates = [
650549
651920
  join147(thisDir, "..", "package.json"),
650550
651921
  join147(thisDir, "..", "..", "package.json"),
@@ -653160,7 +654531,7 @@ async function handleV1Update(req2, res, requestId) {
653160
654531
  }, { subject: req2._authUser ?? "anonymous" });
653161
654532
  const fs11 = require4("node:fs");
653162
654533
  const nodeBin = process.execPath;
653163
- const nodeDir = dirname40(nodeBin);
654534
+ const nodeDir = dirname41(nodeBin);
653164
654535
  const { execSync: es } = require4("node:child_process");
653165
654536
  const isWin2 = process.platform === "win32";
653166
654537
  let npmBin = "";
@@ -653175,7 +654546,7 @@ async function handleV1Update(req2, res, requestId) {
653175
654546
  const dir = join147(homedir53(), ".omnius");
653176
654547
  fs11.mkdirSync(dir, { recursive: true });
653177
654548
  const logFd = fs11.openSync(logPath3, "w");
653178
- const npmPrefix = dirname40(nodeDir);
654549
+ const npmPrefix = dirname41(nodeDir);
653179
654550
  let globalBinDir = "";
653180
654551
  try {
653181
654552
  if (isWin2) {
@@ -656455,7 +657826,7 @@ function listScheduledTasks() {
656455
657826
  const schedule = String(t2?.schedule || t2?.cron || t2?.when || "");
656456
657827
  const enabled2 = typeof t2?.enabled === "boolean" ? t2.enabled : true;
656457
657828
  const realId = typeof t2?.id === "string" && t2.id ? t2.id : null;
656458
- const fallbackId = createHash31("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
657829
+ const fallbackId = createHash33("sha1").update(`${file}#${i2}`).digest("hex").slice(0, 16);
656459
657830
  const uid = realId || fallbackId;
656460
657831
  const key = `${uid}`;
656461
657832
  if (seen.has(key)) return;
@@ -656572,8 +657943,8 @@ function deleteScheduledById(id) {
656572
657943
  if (id) candidates.push(id);
656573
657944
  if (typeof entry?.id === "string" && entry.id && !candidates.includes(entry.id)) candidates.push(entry.id);
656574
657945
  try {
656575
- const { createHash: createHash32 } = require4("node:crypto");
656576
- const fallback = createHash32("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
657946
+ const { createHash: createHash34 } = require4("node:crypto");
657947
+ const fallback = createHash34("sha1").update(`${target.file}#${target.index}`).digest("hex").slice(0, 16);
656577
657948
  if (!candidates.includes(fallback)) candidates.push(fallback);
656578
657949
  } catch {
656579
657950
  }
@@ -658349,7 +659720,7 @@ var init_clipboard_media = __esm({
658349
659720
 
658350
659721
  // packages/cli/src/tui/interactive.ts
658351
659722
  import { cwd } from "node:process";
658352
- import { resolve as resolve52, join as join149, dirname as dirname41, extname as extname17, relative as relative14 } from "node:path";
659723
+ import { resolve as resolve52, join as join149, dirname as dirname42, extname as extname17, relative as relative14 } from "node:path";
658353
659724
  import { createRequire as createRequire8 } from "node:module";
658354
659725
  import { fileURLToPath as fileURLToPath19 } from "node:url";
658355
659726
  import {
@@ -658376,7 +659747,7 @@ function formatTimeAgo2(date) {
658376
659747
  function getVersion4() {
658377
659748
  try {
658378
659749
  const require5 = createRequire8(import.meta.url);
658379
- const thisDir = dirname41(fileURLToPath19(import.meta.url));
659750
+ const thisDir = dirname42(fileURLToPath19(import.meta.url));
658380
659751
  const candidates = [
658381
659752
  join149(thisDir, "..", "package.json"),
658382
659753
  join149(thisDir, "..", "..", "package.json"),
@@ -666547,13 +667918,13 @@ NEW TASK: ${fullInput}`;
666547
667918
  writeContent(() => renderError(errMsg));
666548
667919
  if (failureStore) {
666549
667920
  try {
666550
- const { createHash: createHash32 } = await import("node:crypto");
667921
+ const { createHash: createHash34 } = await import("node:crypto");
666551
667922
  failureStore.insert({
666552
667923
  taskId: "",
666553
667924
  sessionId: `${Date.now()}`,
666554
667925
  repoRoot,
666555
667926
  failureType: "runtime-error",
666556
- fingerprint: createHash32("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
667927
+ fingerprint: createHash34("sha256").update(errMsg.slice(0, 200)).digest("hex").slice(0, 16),
666557
667928
  filePath: null,
666558
667929
  errorMessage: errMsg.slice(0, 500),
666559
667930
  context: null,
@@ -668338,7 +669709,7 @@ init_typed_node_events();
668338
669709
  import { createRequire as createRequire9 } from "node:module";
668339
669710
  import { parseArgs as nodeParseArgs2 } from "node:util";
668340
669711
  import { fileURLToPath as fileURLToPath20 } from "node:url";
668341
- import { dirname as dirname42, join as join153 } from "node:path";
669712
+ import { dirname as dirname43, join as join153 } from "node:path";
668342
669713
 
668343
669714
  // packages/cli/src/cli.ts
668344
669715
  init_typed_node_events();
@@ -668486,7 +669857,7 @@ try {
668486
669857
  function getVersion5() {
668487
669858
  try {
668488
669859
  const require5 = createRequire9(import.meta.url);
668489
- const pkgPath = join153(dirname42(fileURLToPath20(import.meta.url)), "..", "package.json");
669860
+ const pkgPath = join153(dirname43(fileURLToPath20(import.meta.url)), "..", "package.json");
668490
669861
  const pkg = require5(pkgPath);
668491
669862
  return pkg.version;
668492
669863
  } catch {