omnius 1.0.154 → 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
 
@@ -12170,6 +12251,298 @@ function _readJson(path, fallback) {
12170
12251
  function _writeJson(path, value) {
12171
12252
  try { writeFileSync(path, JSON.stringify(value, null, 2)); } catch {}
12172
12253
  }
12254
+ const cohereEndpointCatalogFile = join(nexusDir, 'cohere-endpoint-catalog.json');
12255
+ var _cohereEndpointCatalog = {
12256
+ source: 'ollama',
12257
+ passthrough: false,
12258
+ endpointUrl: process.env.OLLAMA_HOST || process.env.OLLAMA_URL || 'http://localhost:11434',
12259
+ endpointAuth: '',
12260
+ models: [],
12261
+ pricingMenu: [],
12262
+ updatedAt: 0,
12263
+ };
12264
+ function _cohereRedactUrl(url) {
12265
+ var raw = String(url || '').trim();
12266
+ if (!raw) return '';
12267
+ try {
12268
+ var u = new URL(raw);
12269
+ u.username = '';
12270
+ u.password = '';
12271
+ u.search = '';
12272
+ u.hash = '';
12273
+ return u.toString().replace(/\\/+$/, '');
12274
+ } catch {
12275
+ return raw.replace(/([?&](?:api[_-]?key|key|token|auth)=)[^&]+/ig, '$1***');
12276
+ }
12277
+ }
12278
+ function _cohereNormalizeBaseUrl(rawUrl, passthrough) {
12279
+ var raw = String(rawUrl || '').trim() || 'http://localhost:11434';
12280
+ if (!passthrough) return raw.replace(/\\/+$/, '');
12281
+ return raw
12282
+ .replace(/\\/+$/, '')
12283
+ .replace(/\\/chat\\/completions$/, '')
12284
+ .replace(/\\/completions$/, '')
12285
+ .replace(/\\/models(\\/.*)?$/, '')
12286
+ .replace(/\\/v1$/, '')
12287
+ .replace(/\\/+$/, '');
12288
+ }
12289
+ function _cohereNormalizeModelRecord(model, source, passthrough) {
12290
+ if (!model) return null;
12291
+ var name = String(model.name || model.model || model.id || '').trim();
12292
+ if (!name) return null;
12293
+ var details = model.details || {};
12294
+ return {
12295
+ name: name,
12296
+ size: Number(model.size || 0) || 0,
12297
+ family: String(model.family || details.family || model.owned_by || ''),
12298
+ parameterSize: String(model.parameterSize || details.parameter_size || ''),
12299
+ quantization: String(model.quantization || details.quantization_level || ''),
12300
+ source: source || (passthrough ? 'openai-compatible' : 'ollama'),
12301
+ passthrough: !!passthrough,
12302
+ };
12303
+ }
12304
+ function _cohereModelLooksChatCapable(model) {
12305
+ var name = String(model && model.name || '').toLowerCase();
12306
+ var family = String(model && model.family || '').toLowerCase();
12307
+ var text = name + ' ' + family;
12308
+ if (!name) return false;
12309
+ if (/embed|embedding|rerank|nomic-bert|bge-|e5-|clip|whisper|tts|audio/i.test(text)) return false;
12310
+ if (/image|flux|stable.?diffusion|sdxl|dall|midjourney|vision-encoder/i.test(text)) return false;
12311
+ return true;
12312
+ }
12313
+ function _cohereChatScore(model) {
12314
+ var name = String(model && model.name || '').toLowerCase();
12315
+ var family = String(model && model.family || '').toLowerCase();
12316
+ var score = 1;
12317
+ if (/qwen3\\.5|qwen35|qwen3/i.test(name + ' ' + family)) score = 10;
12318
+ else if (/gpt-|claude|gemini|deepseek|llama|mistral|mixtral|command-r|nemotron|gemma/i.test(name + ' ' + family)) score = 8;
12319
+ else if (/chat|instruct|turbo|sonnet|opus|haiku/i.test(name + ' ' + family)) score = 6;
12320
+ if (/^omnius-/i.test(name)) score += 3;
12321
+ if (model && model.passthrough) score += 1;
12322
+ return score;
12323
+ }
12324
+ function _cohereAnnotateModels(models, source, passthrough) {
12325
+ var out = [];
12326
+ var input = Array.isArray(models) ? models : [];
12327
+ for (var i = 0; i < input.length; i++) {
12328
+ var rec = _cohereNormalizeModelRecord(input[i], source, passthrough);
12329
+ if (!rec || !_cohereModelLooksChatCapable(rec)) continue;
12330
+ rec._chatScore = _cohereChatScore(rec);
12331
+ out.push(rec);
12332
+ }
12333
+ return out;
12334
+ }
12335
+ function _cohereApplyAllowlist(models) {
12336
+ if (!_cohereAllowedModels) return Array.isArray(models) ? models : [];
12337
+ return (Array.isArray(models) ? models : []).filter(function(m) { return _cohereAllowedModels.has(m.name); });
12338
+ }
12339
+ function _coherePersistEndpointCatalog() {
12340
+ var pub = _cohereEndpointSnapshot(_cohereEndpointCatalog);
12341
+ pub.models = (_cohereEndpointCatalog.models || []).map(function(m) {
12342
+ return {
12343
+ name: m.name,
12344
+ size: m.size || 0,
12345
+ family: m.family || '',
12346
+ parameterSize: m.parameterSize || '',
12347
+ quantization: m.quantization || '',
12348
+ source: m.source || _cohereEndpointCatalog.source,
12349
+ passthrough: !!m.passthrough,
12350
+ };
12351
+ });
12352
+ pub.pricingMenu = Array.isArray(_cohereEndpointCatalog.pricingMenu) ? _cohereEndpointCatalog.pricingMenu : [];
12353
+ _writeJson(cohereEndpointCatalogFile, pub);
12354
+ }
12355
+ function _cohereRememberEndpointCatalog(opts) {
12356
+ opts = opts || {};
12357
+ var passthrough = opts.passthrough === true;
12358
+ var source = String(opts.source || (passthrough ? 'openai-compatible' : 'ollama'));
12359
+ var endpointUrl = _cohereNormalizeBaseUrl(opts.endpointUrl || opts.ollamaUrl || process.env.OLLAMA_HOST || process.env.OLLAMA_URL || 'http://localhost:11434', passthrough);
12360
+ var models = _cohereAnnotateModels(opts.models || [], source, passthrough);
12361
+ _cohereEndpointCatalog = {
12362
+ source: source,
12363
+ passthrough: passthrough,
12364
+ endpointUrl: endpointUrl,
12365
+ endpointAuth: String(opts.endpointAuth || ''),
12366
+ models: models,
12367
+ pricingMenu: Array.isArray(opts.pricingMenu) ? opts.pricingMenu : [],
12368
+ updatedAt: Date.now(),
12369
+ };
12370
+ _coherePersistEndpointCatalog();
12371
+ dlog('COHERE endpoint catalog updated: source=' + source + ' passthrough=' + passthrough + ' models=' + models.length);
12372
+ return _cohereEndpointCatalog;
12373
+ }
12374
+ function _cohereLoadPersistedEndpointCatalog() {
12375
+ var stored = _readJson(cohereEndpointCatalogFile, null);
12376
+ if (!stored || !Array.isArray(stored.models)) return null;
12377
+ return {
12378
+ source: String(stored.source || 'cached'),
12379
+ passthrough: stored.passthrough === true,
12380
+ endpointUrl: String(stored.endpointUrl || ''),
12381
+ endpointAuth: '',
12382
+ models: _cohereAnnotateModels(stored.models, String(stored.source || 'cached'), stored.passthrough === true),
12383
+ pricingMenu: Array.isArray(stored.pricingMenu) ? stored.pricingMenu : [],
12384
+ updatedAt: Number(stored.updatedAt || 0) || 0,
12385
+ cachedOnly: true,
12386
+ };
12387
+ }
12388
+ async function _cohereFetchEndpointCatalog(baseUrl, endpointAuth, passthrough) {
12389
+ var endpointUrl = _cohereNormalizeBaseUrl(baseUrl, passthrough);
12390
+ if (passthrough) {
12391
+ var headers = { 'Content-Type': 'application/json' };
12392
+ if (endpointAuth) headers['Authorization'] = 'Bearer ' + endpointAuth;
12393
+ var resp = await fetch(endpointUrl + '/v1/models', { headers: headers, signal: AbortSignal.timeout(10000) });
12394
+ if (!resp.ok) throw new Error('/v1/models HTTP ' + resp.status);
12395
+ var data = await resp.json();
12396
+ var list = Array.isArray(data.data) ? data.data : (Array.isArray(data.models) ? data.models : []);
12397
+ return {
12398
+ source: 'openai-compatible',
12399
+ passthrough: true,
12400
+ endpointUrl: endpointUrl,
12401
+ endpointAuth: String(endpointAuth || ''),
12402
+ models: _cohereAnnotateModels(list.map(function(m) {
12403
+ return {
12404
+ name: m.id || m.name || m.model,
12405
+ family: m.owned_by || m.family || '',
12406
+ size: m.size || 0,
12407
+ };
12408
+ }), 'openai-compatible', true),
12409
+ pricingMenu: [],
12410
+ updatedAt: Date.now(),
12411
+ };
12412
+ }
12413
+ var tagsResp = await fetch(endpointUrl + '/api/tags', { signal: AbortSignal.timeout(10000) });
12414
+ if (!tagsResp.ok) throw new Error('/api/tags HTTP ' + tagsResp.status);
12415
+ var tags = await tagsResp.json();
12416
+ return {
12417
+ source: 'ollama',
12418
+ passthrough: false,
12419
+ endpointUrl: endpointUrl,
12420
+ endpointAuth: '',
12421
+ models: _cohereAnnotateModels(tags.models || [], 'ollama', false),
12422
+ pricingMenu: [],
12423
+ updatedAt: Date.now(),
12424
+ };
12425
+ }
12426
+ async function _cohereGetModelCatalog(opts) {
12427
+ opts = opts || {};
12428
+ var now = Date.now();
12429
+ var active = _cohereEndpointCatalog;
12430
+ if (!opts.forceRefresh && active && active.models && active.models.length > 0 && now - (active.updatedAt || 0) < 60000) {
12431
+ return active;
12432
+ }
12433
+ if (active && active.endpointUrl && (!active.cachedOnly || active.endpointAuth || !active.passthrough)) {
12434
+ try {
12435
+ var fresh = await _cohereFetchEndpointCatalog(active.endpointUrl, active.endpointAuth || '', !!active.passthrough);
12436
+ fresh.pricingMenu = Array.isArray(active.pricingMenu) ? active.pricingMenu : [];
12437
+ _cohereEndpointCatalog = fresh;
12438
+ _coherePersistEndpointCatalog();
12439
+ return _cohereEndpointCatalog;
12440
+ } catch (err) {
12441
+ dlog('COHERE endpoint catalog refresh failed: ' + (err.message || err));
12442
+ if (active.models && active.models.length > 0) return active;
12443
+ }
12444
+ }
12445
+ var persisted = _cohereLoadPersistedEndpointCatalog();
12446
+ if (persisted && persisted.models && persisted.models.length > 0) return persisted;
12447
+ try {
12448
+ var fallback = await _cohereFetchEndpointCatalog(process.env.OLLAMA_HOST || process.env.OLLAMA_URL || 'http://localhost:11434', '', false);
12449
+ _cohereEndpointCatalog = fallback;
12450
+ _coherePersistEndpointCatalog();
12451
+ return _cohereEndpointCatalog;
12452
+ } catch (err2) {
12453
+ dlog('COHERE local Ollama catalog unavailable: ' + (err2.message || err2));
12454
+ }
12455
+ return Object.assign({}, active || {}, { models: [] });
12456
+ }
12457
+ function _cohereEndpointSnapshot(catalog) {
12458
+ var c = catalog || _cohereEndpointCatalog || {};
12459
+ return {
12460
+ source: String(c.source || 'unknown'),
12461
+ passthrough: c.passthrough === true,
12462
+ endpointUrl: _cohereRedactUrl(c.endpointUrl || ''),
12463
+ modelCount: Array.isArray(c.models) ? c.models.length : 0,
12464
+ updatedAt: Number(c.updatedAt || 0) || 0,
12465
+ cachedOnly: c.cachedOnly === true,
12466
+ };
12467
+ }
12468
+ function _cohereSelectModel(catalog, tier) {
12469
+ var models = _cohereApplyAllowlist(catalog && catalog.models || []);
12470
+ if (models.length === 0) return { model: '', models: [] };
12471
+ var passthrough = catalog && catalog.passthrough === true;
12472
+ var gb = 1024 * 1024 * 1024;
12473
+ var maxThresh = tier === 0 ? 8 * gb : tier === 1 ? 50 * gb : tier === 2 ? 100 * gb : Infinity;
12474
+ var minSize = tier === 0 ? 0 : tier === 1 ? 4 * gb : tier === 2 ? 12 * gb : 25 * gb;
12475
+ models.sort(function(a, b) {
12476
+ var sa = a._chatScore || 1, sb = b._chatScore || 1;
12477
+ if (sa !== sb) return sb - sa;
12478
+ return (a.size || 0) - (b.size || 0);
12479
+ });
12480
+ var selected = '';
12481
+ if (_cLastModel) {
12482
+ var warm = models.find(function(m) { return m.name === _cLastModel; });
12483
+ if (warm && (passthrough || ((warm.size || 0) >= minSize && (warm.size || 0) <= maxThresh))) selected = warm.name;
12484
+ }
12485
+ if (!selected) {
12486
+ var fit = passthrough
12487
+ ? models
12488
+ : models.filter(function(m) { return (m.size || 0) >= minSize && (m.size || 0) <= maxThresh; });
12489
+ selected = fit.length > 0 ? fit[0].name : '';
12490
+ }
12491
+ if (!selected && models.length > 0) selected = models[0].name;
12492
+ return { model: selected, models: models };
12493
+ }
12494
+ async function _cohereDirectEndpointFallback(catalog, model, requestData) {
12495
+ if (!catalog || catalog.passthrough !== true || !catalog.endpointUrl) {
12496
+ throw new Error('No passthrough endpoint is active for direct COHERE fallback');
12497
+ }
12498
+ var headers = { 'Content-Type': 'application/json' };
12499
+ if (catalog.endpointAuth) headers['Authorization'] = 'Bearer ' + catalog.endpointAuth;
12500
+ var messages = [];
12501
+ if (requestData && Array.isArray(requestData.messages) && requestData.messages.length > 0) {
12502
+ messages = requestData.messages;
12503
+ } else {
12504
+ messages = [{ role: 'user', content: String(requestData && requestData.query || '') }];
12505
+ }
12506
+ var maxTokens = Number(requestData && (requestData.maxTokens || requestData.max_tokens)) || 1024;
12507
+ var temperature = Number(requestData && requestData.temperature);
12508
+ var body = {
12509
+ model: model,
12510
+ messages: messages,
12511
+ stream: false,
12512
+ max_tokens: maxTokens > 0 ? maxTokens : 1024,
12513
+ temperature: Number.isFinite(temperature) ? temperature : 0.2,
12514
+ think: false,
12515
+ };
12516
+ var resp = await fetch(_cohereNormalizeBaseUrl(catalog.endpointUrl, true) + '/v1/chat/completions', {
12517
+ method: 'POST',
12518
+ headers: headers,
12519
+ body: JSON.stringify(body),
12520
+ signal: AbortSignal.timeout(120000),
12521
+ });
12522
+ if (!resp.ok) {
12523
+ var errText = '';
12524
+ try { errText = await resp.text(); } catch {}
12525
+ throw new Error('passthrough /v1/chat/completions HTTP ' + resp.status + ': ' + errText.slice(0, 200));
12526
+ }
12527
+ var data = await resp.json();
12528
+ var choices = data.choices || [];
12529
+ var first = choices[0] && choices[0].message ? choices[0].message : {};
12530
+ var content = String(first.content || first.reasoning || '').replace(/<think>[\\s\\S]*?<\\/think>/g, '').trim();
12531
+ var usage = data.usage || {};
12532
+ return {
12533
+ content: content,
12534
+ usage: {
12535
+ inputTokens: usage.prompt_tokens || usage.input_tokens || 0,
12536
+ outputTokens: usage.completion_tokens || usage.output_tokens || 0,
12537
+ },
12538
+ };
12539
+ }
12540
+ try {
12541
+ var _cohereStartupCatalog = _cohereLoadPersistedEndpointCatalog();
12542
+ if (_cohereStartupCatalog && _cohereStartupCatalog.models && _cohereStartupCatalog.models.length > 0) {
12543
+ _cohereEndpointCatalog = _cohereStartupCatalog;
12544
+ }
12545
+ } catch {}
12173
12546
  async function _dhtPutBounded(dht, key, value, label) {
12174
12547
  var op = (async function() {
12175
12548
  for await (var _ of dht.put(key, value)) {}
@@ -12624,6 +12997,10 @@ async function handleCmd(cmd) {
12624
12997
  } catch {}
12625
12998
  var sponsorLimitsArg = {};
12626
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 {}
12627
13004
  var sponsorData = {
12628
13005
  type: 'sponsor.announce',
12629
13006
  peerId: (connected ? nexus.peerId : 'unknown') || 'unknown',
@@ -12631,6 +13008,8 @@ async function handleCmd(cmd) {
12631
13008
  name: args.name || 'Anonymous Sponsor',
12632
13009
  models: _saModels.length > 0 ? _saModels : _saModelDetails.map(function(m) { return m.name; }),
12633
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'; }) : [],
12634
13013
  tunnelUrl: args.tunnel_url || null,
12635
13014
  authKey: args.auth_key || '',
12636
13015
  limits: {
@@ -12715,6 +13094,8 @@ async function handleCmd(cmd) {
12715
13094
  rateLimit: String(sponsorData.limits.maxRequestsPerMinute) + '/min',
12716
13095
  sponsor: sponsorData,
12717
13096
  models: sponsorData.models,
13097
+ services: sponsorData.services,
13098
+ mediaCapabilities: sponsorData.mediaCapabilities,
12718
13099
  limits: sponsorData.limits,
12719
13100
  });
12720
13101
  writeResp(id, { ok: true, output: 'Sponsor announced: ' + sponsorData.name + ' (' + sponsorData.models.length + ' models) [DHT+GossipSub+NATS+KV+Room]' });
@@ -13556,7 +13937,20 @@ async function handleCmd(cmd) {
13556
13937
 
13557
13938
  // WO-1.5: Publish capacity announcement on enable
13558
13939
  if (typeof _publishCapacityAnnouncement === 'function') {
13559
- try { _publishCapacityAnnouncement(); } catch {}
13940
+ try { await _publishCapacityAnnouncement(); } catch {}
13941
+ }
13942
+ try {
13943
+ var _ceCatalog = await _cohereGetModelCatalog({});
13944
+ await _publishCapabilityRecord('cohere_inference', {
13945
+ description: 'COHERE distributed inference provider',
13946
+ pricing: 'free',
13947
+ rateLimit: _sponsorLimits ? String(_sponsorLimits.maxRequestsPerMinute) + '/min' : 'provider-policy',
13948
+ endpoint: _cohereEndpointSnapshot(_ceCatalog),
13949
+ models: (_ceCatalog.models || []).map(function(m) { return m.name; }),
13950
+ passthrough: _ceCatalog.passthrough === true,
13951
+ });
13952
+ } catch (_cePubErr) {
13953
+ dlog('COHERE capability publish failed: ' + (_cePubErr.message || _cePubErr));
13560
13954
  }
13561
13955
  writeResp(id, { ok: true, output: 'COHERE inference handler enabled' });
13562
13956
  break;
@@ -13589,7 +13983,8 @@ async function handleCmd(cmd) {
13589
13983
  bytesOut: _cohereStats.bytesOut,
13590
13984
  modelsUsed: _cohereStats.modelsUsed,
13591
13985
  peersServed: _cohereStats.peersServed,
13592
- allowedModels: _cohereAllowedModels ? [..._cohereAllowedModels] : null
13986
+ allowedModels: _cohereAllowedModels ? [..._cohereAllowedModels] : null,
13987
+ endpoint: _cohereEndpointSnapshot(),
13593
13988
  };
13594
13989
  if (args.format === 'json' || args.json === true || args.json === 'true' || args.json === '1') {
13595
13990
  writeResp(id, { ok: true, output: JSON.stringify(_csSnapshot) });
@@ -13627,9 +14022,15 @@ async function handleCmd(cmd) {
13627
14022
  _csLines.push(' ' + _csPeers[_cpi][0].slice(0, 20) + '...: ' + _csPeers[_cpi][1] + ' queries');
13628
14023
  }
13629
14024
  _csLines.push('');
14025
+ _csLines.push('── Endpoint ──');
14026
+ var _csEndpoint = _cohereEndpointSnapshot();
14027
+ _csLines.push(' Source: ' + _csEndpoint.source + (_csEndpoint.passthrough ? ' (passthrough)' : ''));
14028
+ _csLines.push(' URL: ' + (_csEndpoint.endpointUrl || '(not set)'));
14029
+ _csLines.push(' Models: ' + _csEndpoint.modelCount + (_csEndpoint.cachedOnly ? ' (cached)' : ''));
14030
+ _csLines.push('');
13630
14031
  _csLines.push('── Model Allowlist ──');
13631
14032
  if (!_cohereAllowedModels) {
13632
- _csLines.push(' All downloaded models exposed (no filter)');
14033
+ _csLines.push(' All endpoint models exposed (no filter)');
13633
14034
  } else {
13634
14035
  _csLines.push(' ' + [..._cohereAllowedModels].join(', '));
13635
14036
  }
@@ -13659,21 +14060,36 @@ async function handleCmd(cmd) {
13659
14060
  break;
13660
14061
  }
13661
14062
  case 'cohere_list_models': {
13662
- var _clmOllamaUrl = process.env.OLLAMA_HOST || 'http://localhost:11434';
13663
- var _clmModels = [];
13664
- try {
13665
- var _clmResp = await fetch(_clmOllamaUrl + '/api/tags');
13666
- var _clmData = await _clmResp.json();
13667
- _clmModels = (_clmData.models || []).map(function(m) { return { name: m.name, size: m.size || 0, family: m.details?.family || '' }; });
13668
- } catch {}
13669
- var _clmLines = ['── Downloaded Models ──'];
14063
+ var _clmCatalog = await _cohereGetModelCatalog({ forceRefresh: args.refresh === 'true' || args.refresh === true || args.refresh === '1' });
14064
+ var _clmModels = Array.isArray(_clmCatalog.models) ? _clmCatalog.models : [];
14065
+ var _clmPayload = {
14066
+ models: _clmModels.map(function(m) { return m.name; }),
14067
+ exposedModels: _cohereApplyAllowlist(_clmModels).map(function(m) { return m.name; }),
14068
+ modelDetails: _clmModels.map(function(m) {
14069
+ return Object.assign({}, m, { exposed: !_cohereAllowedModels || _cohereAllowedModels.has(m.name) });
14070
+ }),
14071
+ source: _clmCatalog.source || 'unknown',
14072
+ passthrough: _clmCatalog.passthrough === true,
14073
+ endpoint: _cohereEndpointSnapshot(_clmCatalog),
14074
+ allowedModels: _cohereAllowedModels ? [..._cohereAllowedModels] : null,
14075
+ };
14076
+ if (args.format === 'json' || args.json === true || args.json === 'true' || args.json === '1') {
14077
+ writeResp(id, { ok: true, output: JSON.stringify(_clmPayload) });
14078
+ break;
14079
+ }
14080
+ var _clmLines = ['── Endpoint Models ──'];
14081
+ var _clmEndpoint = _cohereEndpointSnapshot(_clmCatalog);
14082
+ _clmLines.push(' Source: ' + _clmEndpoint.source + (_clmEndpoint.passthrough ? ' (passthrough)' : ''));
14083
+ _clmLines.push(' URL: ' + (_clmEndpoint.endpointUrl || '(not set)'));
14084
+ _clmLines.push('');
13670
14085
  for (var _clmi = 0; _clmi < _clmModels.length; _clmi++) {
13671
14086
  var _clmM = _clmModels[_clmi];
13672
14087
  var _clmAllowed = !_cohereAllowedModels || _cohereAllowedModels.has(_clmM.name);
13673
14088
  var _clmSizeGB = (_clmM.size / (1024*1024*1024)).toFixed(1);
13674
- _clmLines.push(' ' + (_clmAllowed ? '[EXPOSED]' : '[HIDDEN] ') + ' ' + _clmM.name + ' (' + _clmSizeGB + 'GB' + (_clmM.family ? ', ' + _clmM.family : '') + ')');
14089
+ var _clmMeta = _clmM.size > 0 ? _clmSizeGB + 'GB' : (_clmM.passthrough ? 'external' : 'size unknown');
14090
+ _clmLines.push(' ' + (_clmAllowed ? '[EXPOSED]' : '[HIDDEN] ') + ' ' + _clmM.name + ' (' + _clmMeta + (_clmM.family ? ', ' + _clmM.family : '') + ')');
13675
14091
  }
13676
- if (_clmModels.length === 0) _clmLines.push(' (no models found — is Ollama running?)');
14092
+ if (_clmModels.length === 0) _clmLines.push(' (no endpoint models found — check /endpoint and /expose passthrough)');
13677
14093
  _clmLines.push('');
13678
14094
  _clmLines.push(_cohereAllowedModels ? 'Allowlist: ' + [..._cohereAllowedModels].join(', ') : 'Allowlist: ALL (no filter active)');
13679
14095
  writeResp(id, { ok: true, output: _clmLines.join('\\n') });
@@ -13856,7 +14272,7 @@ async function handleCmd(cmd) {
13856
14272
  if (typeof nexus.getRegisteredCapabilities === 'function' && typeof nexus.unregisterCapability === 'function') {
13857
14273
  var oldCaps = nexus.getRegisteredCapabilities();
13858
14274
  for (var oci = 0; oci < oldCaps.length; oci++) {
13859
- 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') {
13860
14276
  try { nexus.unregisterCapability(oldCaps[oci]); } catch {}
13861
14277
  }
13862
14278
  }
@@ -13890,6 +14306,18 @@ async function handleCmd(cmd) {
13890
14306
  } else {
13891
14307
  _sponsorLimits = null;
13892
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
+ }
13893
14321
 
13894
14322
  // Passthrough mode: forward from a remote /endpoint (Chutes, Groq, etc.)
13895
14323
  var isPassthrough = args.passthrough === 'true';
@@ -14392,6 +14820,32 @@ async function handleCmd(cmd) {
14392
14820
  }
14393
14821
  }
14394
14822
 
14823
+ var _exCohereCatalog = _cohereRememberEndpointCatalog({
14824
+ source: isPassthrough ? 'openai-compatible' : 'ollama',
14825
+ passthrough: isPassthrough,
14826
+ endpointUrl: ollamaUrl,
14827
+ endpointAuth: endpointAuth,
14828
+ models: models,
14829
+ pricingMenu: pricingMenu,
14830
+ });
14831
+ if (cohereActive) {
14832
+ try {
14833
+ await _publishCapabilityRecord('cohere_inference', {
14834
+ description: 'COHERE distributed inference provider',
14835
+ pricing: 'free',
14836
+ rateLimit: _sponsorLimits ? String(_sponsorLimits.maxRequestsPerMinute) + '/min' : 'provider-policy',
14837
+ endpoint: _cohereEndpointSnapshot(_exCohereCatalog),
14838
+ models: (_exCohereCatalog.models || []).map(function(m) { return m.name; }),
14839
+ passthrough: isPassthrough,
14840
+ });
14841
+ } catch (_exCoherePubErr) {
14842
+ dlog('COHERE expose capability publish failed: ' + (_exCoherePubErr.message || _exCoherePubErr));
14843
+ }
14844
+ if (typeof _publishCapacityAnnouncement === 'function') {
14845
+ try { await _publishCapacityAnnouncement(); } catch {}
14846
+ }
14847
+ }
14848
+
14395
14849
  for (var pci = 0; pci < pricingMenu.length; pci++) {
14396
14850
  var capPricing = pricingMenu[pci];
14397
14851
  await _publishCapabilityRecord('inference:' + capPricing.model.replace(/[^a-zA-Z0-9._-]/g, '_'), {
@@ -14409,6 +14863,228 @@ async function handleCmd(cmd) {
14409
14863
  });
14410
14864
  }
14411
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
+
14412
15088
  // Register system_metrics capability — returns CPU/GPU/memory utilization
14413
15089
  if (typeof nexus.registerCapability === 'function') {
14414
15090
  nexus.registerCapability('system_metrics', async (request, stream) => {
@@ -14539,7 +15215,7 @@ async function handleCmd(cmd) {
14539
15215
  quantization: pm.quantization || '',
14540
15216
  });
14541
15217
  }
14542
- 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 });
14543
15219
  await stream.write({ type: 'invoke.event', version: 1, requestId: request.requestId, seq: 0, event: 'result', data: capsPayload });
14544
15220
  await stream.write({ type: 'invoke.done', version: 1, requestId: request.requestId, usage: { inputBytes: 0, outputBytes: capsPayload.length } });
14545
15221
  stream.close();
@@ -14557,12 +15233,14 @@ async function handleCmd(cmd) {
14557
15233
  quantization: pm.quantization || '',
14558
15234
  };
14559
15235
  }),
15236
+ services: mediaServices,
15237
+ mediaCapabilities: mediaServices,
14560
15238
  });
14561
15239
  }
14562
15240
 
14563
15241
  // Write pricing menu to file
14564
15242
  const pricingFile = join(nexusDir, 'pricing.json');
14565
- 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));
14566
15244
  writeStatus({ exposedModels: pricingMenu.length });
14567
15245
 
14568
15246
  const lines = ['Exposed ' + pricingMenu.length + ' model(s) as nexus capabilities:'];
@@ -14572,6 +15250,13 @@ async function handleCmd(cmd) {
14572
15250
  : '$' + p.pricing.input_per_1m_tokens + '/$' + p.pricing.output_per_1m_tokens + ' per 1M tokens';
14573
15251
  lines.push(' inference:' + p.model + ' — ' + cost);
14574
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
+ }
14575
15260
  lines.push('');
14576
15261
  lines.push('Pricing menu saved to ' + pricingFile);
14577
15262
  lines.push('Market rates: ' + Object.keys(marketRates).length + ' models from OpenRouter');
@@ -15340,13 +16025,12 @@ process.on('unhandledRejection', (reason) => {
15340
16025
  }
15341
16026
 
15342
16027
  // ── COHERE distributed inference handler ─────────────────────────
15343
- // ── COHERE distributed inference handler ─────────────────────────
15344
- // Subscribe to nexus.cohere.query, process through local Ollama,
15345
- // publish response to nexus.cohere.response.
16028
+ // Subscribe to nexus.cohere.query, process through the active Omnius
16029
+ // endpoint catalog, publish response to nexus.cohere.response.
15346
16030
  // SECURITY INVARIANTS:
15347
16031
  // 1. Handler constructs ISOLATED messages — no history, no system prompt
15348
- // 2. Only /api/tags (read model list) and /api/chat (inference) are called
15349
- // 3. NEVER calls /api/pull, /api/delete, /api/push, /api/create, /api/copy
16032
+ // 2. Model discovery is read-only: /api/tags or /v1/models
16033
+ // 3. Inference uses /v1/run first; direct fallback is passthrough-only
15350
16034
  // 4. Model allowlist filters which models are served to remote queries
15351
16035
  // 5. Inbound queries scanned for leaked secrets
15352
16036
  if (_natsConn && _natsCodec) {
@@ -15534,89 +16218,34 @@ process.on('unhandledRejection', (reason) => {
15534
16218
  dlog('COHERE query: ' + _cData.queryId + ' — ' + (_cData.query || '').slice(0, 80) + ' [elected, score=' + _cBidScore.toFixed(2) + ', bids=' + _cBids.size + ']');
15535
16219
  const _cStart = Date.now();
15536
16220
 
15537
- // OLLAMA SAFETY: Only two endpoints are ever called:
15538
- // GET /api/tags read available models (READ-ONLY)
15539
- // POST /api/chat — run inference on existing model (READ-ONLY)
16221
+ // Endpoint safety: COHERE model discovery is read-only.
16222
+ // Ollama providers: GET /api/tags only
16223
+ // Passthrough providers: GET /v1/models only
16224
+ // Remote COHERE queries never call Ollama model-management endpoints.
15540
16225
  // The following are NEVER called from remote requests:
15541
16226
  // POST /api/pull — download model (BLOCKED)
15542
16227
  // DELETE /api/delete — remove model (BLOCKED)
15543
16228
  // POST /api/push — upload model (BLOCKED)
15544
16229
  // POST /api/create — create model (BLOCKED)
15545
16230
  // POST /api/copy — copy model (BLOCKED)
15546
- const _cOllamaUrl = process.env.OLLAMA_HOST || 'http://localhost:11434';
16231
+ var _cCatalog = null;
15547
16232
  let _cModel = '';
15548
16233
  try {
15549
- const _cTags = await fetch(_cOllamaUrl + '/api/tags').then(function(r) { return r.json(); });
15550
- // Filter out non-chat models: embeddings, image generators, vision-only
15551
- // Use family/families from Ollama model cards for capability detection
15552
- var _cAllModels = (_cTags.models || []).filter(function(m) {
15553
- var name = (m.name || '').toLowerCase();
15554
- var family = ((m.details && m.details.family) || '').toLowerCase();
15555
- var families = (m.details && m.details.families) || [];
15556
- var famStr = families.join(' ').toLowerCase();
15557
- // Exclude embeddings
15558
- if (/embed|nomic-bert/i.test(name) || /embed|nomic-bert/i.test(family)) return false;
15559
- // Exclude image generation models (flux, sd, sdxl, image-turbo, etc.)
15560
- if (/image|flux|stable.?diffusion|sdxl|sd[0-9]|dall|turbo.*image|image.*turbo/i.test(name)) return false;
15561
- if (/flux|diffusion/i.test(family)) return false;
15562
- // Exclude pure vision models (keep multimodal like qwen3-vl that also do chat)
15563
- if (/^clip$|^vit$/i.test(family)) return false;
15564
- return true;
15565
- });
15566
- // Score models for chat/tool capability: prefer qwen, then tool-capable families
15567
- var _cChatFamilies = { qwen35: 10, qwen35moe: 10, qwen3: 9, qwen3moe: 9, qwen3next: 9, nemotron_h_moe: 8, mistral3: 7, llama: 6, gemma3: 6, seed_oss: 5, phi2: 3 };
15568
- for (var _cmi = 0; _cmi < _cAllModels.length; _cmi++) {
15569
- var _cmFam = ((_cAllModels[_cmi].details && _cAllModels[_cmi].details.family) || '').toLowerCase();
15570
- _cAllModels[_cmi]._chatScore = _cChatFamilies[_cmFam] || 1;
15571
- // Boost omnius- prefixed models (known good configs)
15572
- if (/^omnius-/i.test(_cAllModels[_cmi].name)) _cAllModels[_cmi]._chatScore += 3;
15573
- }
15574
- // Apply model allowlist — only serve allowed models to remote queries
15575
- var _cModels = _cohereAllowedModels
15576
- ? _cAllModels.filter(function(m) { return _cohereAllowedModels.has(m.name); })
15577
- : _cAllModels;
16234
+ _cCatalog = await _cohereGetModelCatalog({});
16235
+ var _cSelected = _cohereSelectModel(_cCatalog, _cTier);
16236
+ var _cModels = _cSelected.models || [];
15578
16237
  if (_cModels.length === 0 && _cohereAllowedModels) {
15579
- dlog('COHERE: no allowed models match downloaded models. Allowlist: ' + [..._cohereAllowedModels].join(', '));
16238
+ dlog('COHERE: no allowed models match endpoint catalog. Allowlist: ' + [..._cohereAllowedModels].join(', '));
15580
16239
  _cohereStats.queriesErrors++;
15581
16240
  _saveStats();
15582
16241
  continue;
15583
16242
  }
15584
- // CO-04/05: Model selection — tier determines minimum size, warm gets priority within tier
15585
- var _cGB = 1024 * 1024 * 1024;
15586
- // Tier thresholds: [max for trivial, max for moderate, max for complex, unlimited]
15587
- var _cMaxThresh = _cTier === 0 ? 8 * _cGB : _cTier === 1 ? 50 * _cGB : _cTier === 2 ? 100 * _cGB : Infinity;
15588
- // Minimum size: higher tiers REQUIRE bigger models
15589
- var _cMinSize = _cTier === 0 ? 0 : _cTier === 1 ? 4 * _cGB : _cTier === 2 ? 12 * _cGB : 25 * _cGB;
15590
-
15591
- // Sort by chat capability score (desc), then size within same score (asc)
15592
- _cModels.sort(function(a, b) {
15593
- var sa = a._chatScore || 1, sb = b._chatScore || 1;
15594
- if (sa !== sb) return sb - sa; // higher chat score first
15595
- return (a.size || 0) - (b.size || 0); // then smaller first within same score
15596
- });
15597
-
15598
- // Prefer warm model ONLY if it meets the minimum size for this tier
15599
- if (_cLastModel) {
15600
- var _cWarm = _cModels.find(function(m) { return m.name === _cLastModel; });
15601
- if (_cWarm && (_cWarm.size || 0) >= _cMinSize && (_cWarm.size || 0) <= _cMaxThresh) {
15602
- _cModel = _cWarm.name;
15603
- }
15604
- }
15605
- // Otherwise pick best-scored model that fits the tier range
15606
- // Models already sorted by chatScore desc, so first match is best
15607
- if (!_cModel) {
15608
- var _cFit = _cModels.filter(function(m) { return (m.size || 0) >= _cMinSize && (m.size || 0) <= _cMaxThresh; });
15609
- // Pick the one with highest chat score (already sorted)
15610
- _cModel = _cFit.length > 0 ? _cFit[0].name : '';
15611
- }
15612
- // Fallback: if no model fits the range, take the best-scored available
15613
- if (!_cModel && _cModels.length > 0) {
15614
- _cModel = _cModels[0].name; // first = highest chatScore
15615
- dlog('COHERE: no model fits tier ' + _cTier + ' range [' + (_cMinSize / _cGB).toFixed(0) + 'GB-' + (_cMaxThresh / _cGB).toFixed(0) + 'GB], using best-scored: ' + _cModel);
15616
- }
15617
- dlog('COHERE routing: tier=' + ['trivial','moderate','complex','expert'][_cTier] + ' model=' + _cModel + ' (chatScore=' + ((_cModels.find(function(m){return m.name===_cModel})||{})._chatScore||'?') + ')');
15618
- } catch {}
15619
- if (!_cModel) { dlog('COHERE: no Ollama models available'); _cohereStats.queriesErrors++; _saveStats(); continue; }
16243
+ _cModel = _cSelected.model || '';
16244
+ dlog('COHERE routing: source=' + ((_cCatalog && _cCatalog.source) || 'unknown') + ' passthrough=' + (!!(_cCatalog && _cCatalog.passthrough)) + ' tier=' + ['trivial','moderate','complex','expert'][_cTier] + ' model=' + _cModel + ' (chatScore=' + ((_cModels.find(function(m){return m.name===_cModel})||{})._chatScore||'?') + ')');
16245
+ } catch (_cCatalogErr) {
16246
+ dlog('COHERE catalog error: ' + (_cCatalogErr.message || _cCatalogErr));
16247
+ }
16248
+ if (!_cModel) { dlog('COHERE: no endpoint models available'); _cohereStats.queriesErrors++; _saveStats(); continue; }
15620
16249
  try {
15621
16250
  // Scan inbound query for leaked secrets (defense-in-depth)
15622
16251
  const _cSecretPatterns = [/sk-[a-zA-Z0-9]{20,}/g, /ghp_[a-zA-Z0-9]{36,}/g, /AKIA[0-9A-Z]{16}/g];
@@ -15652,6 +16281,10 @@ process.on('unhandledRejection', (reason) => {
15652
16281
  if (_cApiAvailable) {
15653
16282
  dlog('COHERE: routing through full AgenticRunner at ' + _cApiUrl + '/v1/run');
15654
16283
  try {
16284
+ var _cRunEnv = {};
16285
+ if (_cCatalog && _cCatalog.endpointUrl) _cRunEnv.OMNIUS_BACKEND_URL = _cCatalog.endpointUrl;
16286
+ if (_cCatalog && _cCatalog.endpointAuth) _cRunEnv.OMNIUS_API_KEY = _cCatalog.endpointAuth;
16287
+ if (_cModel) _cRunEnv.OMNIUS_MODEL = _cModel;
15655
16288
  var _cRunResp = await fetch(_cApiUrl + '/v1/run', {
15656
16289
  method: 'POST',
15657
16290
  headers: { 'Content-Type': 'application/json' },
@@ -15662,6 +16295,7 @@ process.on('unhandledRejection', (reason) => {
15662
16295
  timeout_s: 90,
15663
16296
  sandbox: 'none',
15664
16297
  profile: 'cohere-mesh',
16298
+ env: _cRunEnv,
15665
16299
  }),
15666
16300
  signal: AbortSignal.timeout(120000),
15667
16301
  });
@@ -15701,22 +16335,34 @@ process.on('unhandledRejection', (reason) => {
15701
16335
  if (_cContent) {
15702
16336
  dlog('COHERE: AgenticRunner responded (' + _cContent.length + ' chars)');
15703
16337
  } else {
15704
- dlog('COHERE: AgenticRunner returned empty — falling back to raw Ollama');
16338
+ dlog('COHERE: AgenticRunner returned empty');
15705
16339
  }
15706
16340
  } catch (_cRunErr) {
15707
- dlog('COHERE: AgenticRunner error: ' + (_cRunErr.message || _cRunErr) + ' — falling back');
16341
+ dlog('COHERE: AgenticRunner error: ' + (_cRunErr.message || _cRunErr));
15708
16342
  }
15709
16343
  } else {
15710
- dlog('COHERE: Omnius API not available at ' + _cApiUrl + ' — CANNOT process query (no raw Ollama fallback)');
15711
- _cContent = '[COHERE error] Omnius API server not running on this node. Start it with: omnius serve';
16344
+ dlog('COHERE: Omnius API not available at ' + _cApiUrl);
16345
+ }
16346
+
16347
+ // No raw local-Ollama fallback. If the user explicitly exposed an
16348
+ // OpenAI-compatible passthrough endpoint, use that endpoint directly
16349
+ // as a degraded fallback so COHERE still serves external providers.
16350
+ if (!_cContent && _cCatalog && _cCatalog.passthrough === true) {
16351
+ try {
16352
+ var _cDirect = await _cohereDirectEndpointFallback(_cCatalog, _cModel, _cData);
16353
+ _cContent = _cDirect.content || '';
16354
+ _cUsage = _cDirect.usage;
16355
+ if (_cContent) dlog('COHERE: direct passthrough fallback responded (' + _cContent.length + ' chars)');
16356
+ } catch (_cDirectErr) {
16357
+ dlog('COHERE: direct passthrough fallback failed: ' + (_cDirectErr.message || _cDirectErr));
16358
+ }
15712
16359
  }
15713
16360
 
15714
- // NO raw Ollama fallback — all queries MUST go through AgenticRunner
15715
- // If /v1/run failed or API unavailable, report the error instead of
15716
- // sending garbage responses without tools/context/system prompt.
15717
16361
  if (!_cContent) {
15718
- _cContent = '[COHERE error] AgenticRunner returned empty response. Check Omnius API server logs.';
15719
- dlog('COHERE: no content from AgenticRunner reporting error (no raw Ollama fallback)');
16362
+ _cContent = _cApiAvailable
16363
+ ? '[COHERE error] AgenticRunner returned empty response. Check Omnius API server logs.'
16364
+ : '[COHERE error] Omnius API server not running on this node. Start it with: omnius serve, or expose an OpenAI-compatible endpoint with /expose passthrough.';
16365
+ dlog('COHERE: no content from AgenticRunner or passthrough endpoint');
15720
16366
  }
15721
16367
 
15722
16368
  const _cLatency = Date.now() - _cStart;
@@ -16072,24 +16718,8 @@ process.on('unhandledRejection', (reason) => {
16072
16718
  async function _publishCapacityAnnouncement() {
16073
16719
  if (!cohereActive || !_natsConn || !_natsCodec) return;
16074
16720
  try {
16075
- var _capOllamaUrl = process.env.OLLAMA_HOST || 'http://localhost:11434';
16076
- var _capModels = [];
16077
- try {
16078
- var _capTags = await fetch(_capOllamaUrl + '/api/tags').then(function(r) { return r.json(); });
16079
- _capModels = (_capTags.models || []).map(function(m) {
16080
- return {
16081
- name: m.name,
16082
- size: m.size || 0,
16083
- family: m.details ? m.details.family || '' : '',
16084
- parameterSize: m.details ? m.details.parameter_size || '' : '',
16085
- quantization: m.details ? m.details.quantization_level || '' : '',
16086
- };
16087
- });
16088
- } catch {}
16089
- // Filter by allowlist
16090
- if (_cohereAllowedModels) {
16091
- _capModels = _capModels.filter(function(m) { return _cohereAllowedModels.has(m.name); });
16092
- }
16721
+ var _capCatalog = await _cohereGetModelCatalog({});
16722
+ var _capModels = _cohereApplyAllowlist(_capCatalog.models || []);
16093
16723
  var _capMetrics = await _collectSysMetrics();
16094
16724
  // CO-02: Enriched per-model capacity — warm/cold, specialty, estimated latency
16095
16725
  var _capEnriched = _capModels.map(function(m) {
@@ -16122,6 +16752,7 @@ process.on('unhandledRejection', (reason) => {
16122
16752
  agentName: agentName,
16123
16753
  agentType: agentType,
16124
16754
  cohereActive: cohereActive,
16755
+ endpoint: _cohereEndpointSnapshot(_capCatalog),
16125
16756
  models: _capEnriched,
16126
16757
  warmModel: _cLastModel || null,
16127
16758
  modelCount: _capEnriched.length,
@@ -16129,7 +16760,7 @@ process.on('unhandledRejection', (reason) => {
16129
16760
  totalVram: _capTotalVram,
16130
16761
  availableVram: _capAvailVram,
16131
16762
  specialties: _capSpecialties,
16132
- capabilities: ['inference'], // future: web_search, code_execution
16763
+ capabilities: ['inference', 'cohere_inference'],
16133
16764
  allowedModels: _cohereAllowedModels ? [..._cohereAllowedModels] : null,
16134
16765
  stats: {
16135
16766
  queriesAnswered: _cohereStats.queriesAnswered,
@@ -16198,6 +16829,7 @@ process.on('unhandledRejection', (reason) => {
16198
16829
  multiaddrs: [],
16199
16830
  timestamp: Date.now(),
16200
16831
  capabilities: _capModels.map(function(m) { return m.name; }),
16832
+ endpoint: _cohereEndpointSnapshot(_capCatalog),
16201
16833
  identityCid: _idCid || undefined,
16202
16834
  identityHash: _idHash || undefined,
16203
16835
  identityVersion: _idVersion || undefined,
@@ -17131,11 +17763,15 @@ process.on('SIGINT', () => process.emit('SIGTERM'));
17131
17763
  },
17132
17764
  format: {
17133
17765
  type: "string",
17134
- description: "For cohere_stats: set to 'json' for structured stats"
17766
+ description: "For cohere_stats/cohere_list_models: set to 'json' for structured output"
17135
17767
  },
17136
17768
  json: {
17137
17769
  type: "string",
17138
- description: "For cohere_stats: set to '1' for structured stats"
17770
+ description: "For cohere_stats/cohere_list_models: set to '1' for structured output"
17771
+ },
17772
+ refresh: {
17773
+ type: "string",
17774
+ description: "For cohere_list_models: set to '1' to refresh the active endpoint catalog"
17139
17775
  }
17140
17776
  },
17141
17777
  required: ["action"],
@@ -17282,7 +17918,7 @@ process.on('SIGINT', () => process.emit('SIGTERM'));
17282
17918
  result = await this.sendDaemonCmd("cohere_deny_model", { model: String(args.model ?? "") });
17283
17919
  break;
17284
17920
  case "cohere_list_models":
17285
- result = await this.sendDaemonCmd("cohere_list_models", {});
17921
+ result = await this.sendDaemonCmd("cohere_list_models", { format: String(args.format ?? ""), json: String(args.json ?? ""), refresh: String(args.refresh ?? "") });
17286
17922
  break;
17287
17923
  case "ipfs_add":
17288
17924
  result = await this.sendDaemonCmd("ipfs_add", { content: String(args.content ?? args.message ?? "") });
@@ -95680,7 +96316,7 @@ var require_auto = __commonJS({
95680
96316
  // ../node_modules/acme-client/src/client.js
95681
96317
  var require_client = __commonJS({
95682
96318
  "../node_modules/acme-client/src/client.js"(exports, module) {
95683
- var { createHash: createHash32 } = __require("crypto");
96319
+ var { createHash: createHash34 } = __require("crypto");
95684
96320
  var { getPemBodyAsB64u } = require_crypto();
95685
96321
  var { log: log22 } = require_logger();
95686
96322
  var HttpClient = require_http();
@@ -95991,14 +96627,14 @@ var require_client = __commonJS({
95991
96627
  */
95992
96628
  async getChallengeKeyAuthorization(challenge) {
95993
96629
  const jwk = this.http.getJwk();
95994
- const keysum = createHash32("sha256").update(JSON.stringify(jwk));
96630
+ const keysum = createHash34("sha256").update(JSON.stringify(jwk));
95995
96631
  const thumbprint = keysum.digest("base64url");
95996
96632
  const result = `${challenge.token}.${thumbprint}`;
95997
96633
  if (challenge.type === "http-01") {
95998
96634
  return result;
95999
96635
  }
96000
96636
  if (challenge.type === "dns-01") {
96001
- return createHash32("sha256").update(result).digest("base64url");
96637
+ return createHash34("sha256").update(result).digest("base64url");
96002
96638
  }
96003
96639
  if (challenge.type === "tls-alpn-01") {
96004
96640
  return result;
@@ -131910,7 +132546,7 @@ var require_snapshot_recorder = __commonJS({
131910
132546
  "../node_modules/undici/lib/mock/snapshot-recorder.js"(exports, module) {
131911
132547
  "use strict";
131912
132548
  var { writeFile: writeFile24, readFile: readFile23, mkdir: mkdir20 } = __require("node:fs/promises");
131913
- var { dirname: dirname43, resolve: resolve56 } = __require("node:path");
132549
+ var { dirname: dirname44, resolve: resolve56 } = __require("node:path");
131914
132550
  var { setTimeout: setTimeout3, clearTimeout: clearTimeout3 } = __require("node:timers");
131915
132551
  var { InvalidArgumentError, UndiciError } = require_errors2();
131916
132552
  var { hashId, isUrlExcludedFactory, normalizeHeaders, createHeaderFilters } = require_snapshot_utils();
@@ -132141,7 +132777,7 @@ var require_snapshot_recorder = __commonJS({
132141
132777
  throw new InvalidArgumentError("Snapshot path is required");
132142
132778
  }
132143
132779
  const resolvedPath = resolve56(path12);
132144
- await mkdir20(dirname43(resolvedPath), { recursive: true });
132780
+ await mkdir20(dirname44(resolvedPath), { recursive: true });
132145
132781
  const data = Array.from(this.#snapshots.entries()).map(([hash, snapshot]) => ({
132146
132782
  hash,
132147
132783
  snapshot
@@ -238678,7 +239314,7 @@ var require_websocket2 = __commonJS({
238678
239314
  var http6 = __require("http");
238679
239315
  var net5 = __require("net");
238680
239316
  var tls2 = __require("tls");
238681
- var { randomBytes: randomBytes29, createHash: createHash32 } = __require("crypto");
239317
+ var { randomBytes: randomBytes29, createHash: createHash34 } = __require("crypto");
238682
239318
  var { Duplex: Duplex3, Readable } = __require("stream");
238683
239319
  var { URL: URL3 } = __require("url");
238684
239320
  var PerMessageDeflate3 = require_permessage_deflate2();
@@ -239338,7 +239974,7 @@ var require_websocket2 = __commonJS({
239338
239974
  abortHandshake(websocket, socket, "Invalid Upgrade header");
239339
239975
  return;
239340
239976
  }
239341
- const digest3 = createHash32("sha1").update(key + GUID).digest("base64");
239977
+ const digest3 = createHash34("sha1").update(key + GUID).digest("base64");
239342
239978
  if (res.headers["sec-websocket-accept"] !== digest3) {
239343
239979
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
239344
239980
  return;
@@ -239705,7 +240341,7 @@ var require_websocket_server = __commonJS({
239705
240341
  var EventEmitter15 = __require("events");
239706
240342
  var http6 = __require("http");
239707
240343
  var { Duplex: Duplex3 } = __require("stream");
239708
- var { createHash: createHash32 } = __require("crypto");
240344
+ var { createHash: createHash34 } = __require("crypto");
239709
240345
  var extension3 = require_extension2();
239710
240346
  var PerMessageDeflate3 = require_permessage_deflate2();
239711
240347
  var subprotocol3 = require_subprotocol();
@@ -240006,7 +240642,7 @@ var require_websocket_server = __commonJS({
240006
240642
  );
240007
240643
  }
240008
240644
  if (this._state > RUNNING) return abortHandshake(socket, 503);
240009
- const digest3 = createHash32("sha1").update(key + GUID).digest("base64");
240645
+ const digest3 = createHash34("sha1").update(key + GUID).digest("base64");
240010
240646
  const headers = [
240011
240647
  "HTTP/1.1 101 Switching Protocols",
240012
240648
  "Upgrade: websocket",
@@ -245803,15 +246439,15 @@ var init_ls = __esm({
245803
246439
  });
245804
246440
 
245805
246441
  // ../node_modules/@helia/unixfs/dist/src/commands/mkdir.js
245806
- async function mkdir6(parentCid, dirname43, blockstore, options2 = {}) {
245807
- if (dirname43.includes("/")) {
246442
+ async function mkdir6(parentCid, dirname44, blockstore, options2 = {}) {
246443
+ if (dirname44.includes("/")) {
245808
246444
  throw new InvalidParametersError4("Path must not have slashes");
245809
246445
  }
245810
246446
  const entry = await exporter2(parentCid, blockstore, options2);
245811
246447
  if (entry.type !== "directory") {
245812
246448
  throw new NotADirectoryError(`${parentCid.toString()} was not a UnixFS directory`);
245813
246449
  }
245814
- log16("creating %s", dirname43);
246450
+ log16("creating %s", dirname44);
245815
246451
  const metadata = new UnixFS({
245816
246452
  type: "directory",
245817
246453
  mode: options2.mode,
@@ -245827,9 +246463,9 @@ async function mkdir6(parentCid, dirname43, blockstore, options2 = {}) {
245827
246463
  await blockstore.put(emptyDirCid, buf);
245828
246464
  const [directory, pblink] = await Promise.all([
245829
246465
  cidToDirectory(parentCid, blockstore, options2),
245830
- cidToPBLink(emptyDirCid, dirname43, blockstore, options2)
246466
+ cidToPBLink(emptyDirCid, dirname44, blockstore, options2)
245831
246467
  ]);
245832
- log16("adding empty dir called %s to %c", dirname43, parentCid);
246468
+ log16("adding empty dir called %s to %c", dirname44, parentCid);
245833
246469
  const result = await addLink(directory, pblink, blockstore, {
245834
246470
  ...options2,
245835
246471
  allowOverwriting: options2.force
@@ -246328,8 +246964,8 @@ var init_unixfs2 = __esm({
246328
246964
  async *ls(cid, options2 = {}) {
246329
246965
  yield* ls(cid, this.components.blockstore, options2);
246330
246966
  }
246331
- async mkdir(cid, dirname43, options2 = {}) {
246332
- return mkdir6(cid, dirname43, this.components.blockstore, options2);
246967
+ async mkdir(cid, dirname44, options2 = {}) {
246968
+ return mkdir6(cid, dirname44, this.components.blockstore, options2);
246333
246969
  }
246334
246970
  async rm(cid, path12, options2 = {}) {
246335
246971
  return rm3(cid, path12, this.components.blockstore, options2);
@@ -249726,8 +250362,8 @@ var require_pattern = __commonJS({
249726
250362
  }
249727
250363
  exports.endsWithSlashGlobStar = endsWithSlashGlobStar;
249728
250364
  function isAffectDepthOfReadingPattern(pattern) {
249729
- const basename34 = path12.basename(pattern);
249730
- return endsWithSlashGlobStar(pattern) || isStaticPattern(basename34);
250365
+ const basename35 = path12.basename(pattern);
250366
+ return endsWithSlashGlobStar(pattern) || isStaticPattern(basename35);
249731
250367
  }
249732
250368
  exports.isAffectDepthOfReadingPattern = isAffectDepthOfReadingPattern;
249733
250369
  function expandPatternsWithBraceExpansion(patterns) {
@@ -252813,13 +253449,13 @@ Justification: ${justification || "(none provided)"}`,
252813
253449
  }
252814
253450
  const snapshot = JSON.stringify(this.selfState, null, 2);
252815
253451
  try {
252816
- const { createHash: createHash32 } = await import("node:crypto");
253452
+ const { createHash: createHash34 } = await import("node:crypto");
252817
253453
  const snapshotDir = join32(this.cwd, ".omnius", "identity", "snapshots");
252818
253454
  await mkdir7(snapshotDir, { recursive: true });
252819
253455
  const version4 = this.selfState.version;
252820
253456
  const snapshotPath = join32(snapshotDir, `v${version4}.json`);
252821
253457
  await writeFile12(snapshotPath, snapshot, "utf8");
252822
- const hash = createHash32("sha256").update(snapshot).digest("hex");
253458
+ const hash = createHash34("sha256").update(snapshot).digest("hex");
252823
253459
  await writeFile12(join32(this.cwd, ".omnius", "identity", "latest-hash.txt"), hash, "utf8");
252824
253460
  let ipfsCid = "";
252825
253461
  try {
@@ -252952,8 +253588,8 @@ New: ${newNarrative.slice(0, 200)}...`,
252952
253588
  }
252953
253589
  // ── Helpers ──────────────────────────────────────────────────────────────
252954
253590
  createDefaultState() {
252955
- const { createHash: createHash32 } = __require("node:crypto");
252956
- 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);
252957
253593
  return {
252958
253594
  self_id: `omnius-${machineId}`,
252959
253595
  version: 1,
@@ -253035,9 +253671,9 @@ New: ${newNarrative.slice(0, 200)}...`,
253035
253671
  let cid;
253036
253672
  if (this.selfState.version > prevVersion) {
253037
253673
  try {
253038
- const { createHash: createHash32 } = await import("node:crypto");
253674
+ const { createHash: createHash34 } = await import("node:crypto");
253039
253675
  const stateJson = JSON.stringify(this.selfState);
253040
- const hash = createHash32("sha256").update(stateJson).digest("hex").slice(0, 32);
253676
+ const hash = createHash34("sha256").update(stateJson).digest("hex").slice(0, 32);
253041
253677
  const cidsPath = join32(this.cwd, ".omnius", "identity", "cids.json");
253042
253678
  const cidsData = { latest: "", hash, version: this.selfState.version };
253043
253679
  try {
@@ -262277,6 +262913,436 @@ ${llmAnnotation}` : result.llmContent;
262277
262913
  }
262278
262914
  });
262279
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
+
262280
263346
  // packages/execution/dist/tools/structured-read.js
262281
263347
  import { readFile as readFile15, stat as stat5 } from "node:fs/promises";
262282
263348
  import { resolve as resolve21, extname as extname5 } from "node:path";
@@ -265619,7 +266685,7 @@ import { execSync as execSync23, exec as execCb, spawnSync as spawnSync4 } from
265619
266685
  import { readFile as readFile16, writeFile as writeFile20, mkdir as mkdir15 } from "node:fs/promises";
265620
266686
  import { resolve as resolve28, join as join48 } from "node:path";
265621
266687
  import { homedir as homedir13 } from "node:os";
265622
- import { randomBytes as randomBytes12, createHash as createHash6 } from "node:crypto";
266688
+ import { randomBytes as randomBytes12, createHash as createHash7 } from "node:crypto";
265623
266689
  function isValidCron(expr) {
265624
266690
  const parts = expr.trim().split(/\s+/);
265625
266691
  if (parts.length !== 5)
@@ -266055,7 +267121,7 @@ var init_scheduler = __esm({
266055
267121
  }
266056
267122
  const scope = String(args["scope"] ?? "local");
266057
267123
  const fingerprint = `${resolve28(this.workingDir)}|${task}|${cronExpr}|${scope}`;
266058
- 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)}`;
266059
267125
  const oneShot = Boolean(args["one_shot"]);
266060
267126
  const maxRuns = typeof args["max_runs"] === "number" ? args["max_runs"] : void 0;
266061
267127
  const newTask = {
@@ -270211,7 +271277,7 @@ var init_import_graph = __esm({
270211
271277
  import { createRequire as __createRequireGlob } from "node:module";
270212
271278
  import ignore from "ignore";
270213
271279
  import { readFile as readFile21, stat as stat6 } from "node:fs/promises";
270214
- import { createHash as createHash7 } from "node:crypto";
271280
+ import { createHash as createHash8 } from "node:crypto";
270215
271281
  import { join as join56, relative as relative5, extname as extname8, basename as basename13 } from "node:path";
270216
271282
  var __requireGlob, glob2, DEFAULT_EXCLUDE, LANGUAGE_MAP, CodebaseIndexer;
270217
271283
  var init_codebase_indexer = __esm({
@@ -270279,7 +271345,7 @@ var init_codebase_indexer = __esm({
270279
271345
  if (fileStat.size > this.config.maxFileSize)
270280
271346
  continue;
270281
271347
  const content = await readFile21(fullPath);
270282
- const hash = createHash7("sha256").update(content).digest("hex");
271348
+ const hash = createHash8("sha256").update(content).digest("hex");
270283
271349
  const ext = extname8(relativePath);
270284
271350
  indexed.push({
270285
271351
  path: fullPath,
@@ -409783,9 +410849,9 @@ ${lanes.join("\n")}
409783
410849
  /*ignoreCase*/
409784
410850
  false
409785
410851
  )) {
409786
- const basename34 = getBaseFileName(a2.fileName);
409787
- if (basename34 === "lib.d.ts" || basename34 === "lib.es6.d.ts") return 0;
409788
- 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");
409789
410855
  const index = libs.indexOf(name10);
409790
410856
  if (index !== -1) return index + 1;
409791
410857
  }
@@ -473711,8 +474777,8 @@ ${options2.prefix}` : "\n" : options2.prefix
473711
474777
  }
473712
474778
  };
473713
474779
  for (const file of files) {
473714
- const basename34 = getBaseFileName(file);
473715
- if (basename34 === "package.json" || basename34 === "bower.json") {
474780
+ const basename35 = getBaseFileName(file);
474781
+ if (basename35 === "package.json" || basename35 === "bower.json") {
473716
474782
  createProjectWatcher(
473717
474783
  file,
473718
474784
  "FileWatcher"
@@ -477396,8 +478462,8 @@ All files are: ${JSON.stringify(names)}`,
477396
478462
  var _a;
477397
478463
  const fileOrDirectoryPath = removeIgnoredPath(this.toPath(fileOrDirectory));
477398
478464
  if (!fileOrDirectoryPath) return;
477399
- const basename34 = getBaseFileName(fileOrDirectoryPath);
477400
- 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")) {
477401
478467
  result.affectedModuleSpecifierCacheProjects.forEach((project) => {
477402
478468
  var _a2;
477403
478469
  (_a2 = project.getModuleSpecifierCache()) == null ? void 0 : _a2.clear();
@@ -486278,7 +487344,7 @@ var require_path_browserify = __commonJS({
486278
487344
  _makeLong: function _makeLong(path12) {
486279
487345
  return path12;
486280
487346
  },
486281
- dirname: function dirname43(path12) {
487347
+ dirname: function dirname44(path12) {
486282
487348
  assertPath(path12);
486283
487349
  if (path12.length === 0) return ".";
486284
487350
  var code8 = path12.charCodeAt(0);
@@ -486300,7 +487366,7 @@ var require_path_browserify = __commonJS({
486300
487366
  if (hasRoot && end === 1) return "//";
486301
487367
  return path12.slice(0, end);
486302
487368
  },
486303
- basename: function basename34(path12, ext) {
487369
+ basename: function basename35(path12, ext) {
486304
487370
  if (ext !== void 0 && typeof ext !== "string") throw new TypeError('"ext" argument must be a string');
486305
487371
  assertPath(path12);
486306
487372
  var start2 = 0;
@@ -514591,7 +515657,7 @@ var init_ts_morph_parser = __esm({
514591
515657
 
514592
515658
  // packages/indexer/dist/code-graph-db.js
514593
515659
  import { createRequire as createRequire2 } from "node:module";
514594
- import { createHash as createHash8 } from "node:crypto";
515660
+ import { createHash as createHash9 } from "node:crypto";
514595
515661
  import { mkdirSync as mkdirSync16, readFileSync as readFileSync30 } from "node:fs";
514596
515662
  import { join as join57, dirname as dirname14, extname as extname9 } from "node:path";
514597
515663
  function loadDatabaseCtor() {
@@ -514663,7 +515729,7 @@ function extractFileImports(content, filePath) {
514663
515729
  return imports.map((p2) => p2.replace(/\.(js|ts|jsx|tsx|mjs|cjs)$/, ""));
514664
515730
  }
514665
515731
  function hashContent(content) {
514666
- return createHash8("sha1").update(content).digest("hex").slice(0, 16);
515732
+ return createHash9("sha1").update(content).digest("hex").slice(0, 16);
514667
515733
  }
514668
515734
  function detectLanguage(filePath) {
514669
515735
  return EXT_TO_LANG[extname9(filePath)] ?? "unknown";
@@ -523172,7 +524238,7 @@ var init_client3 = __esm({
523172
524238
  import { existsSync as existsSync53, readFileSync as readFileSync39, writeFileSync as writeFileSync24, mkdirSync as mkdirSync27, chmodSync, statSync as statSync24 } from "node:fs";
523173
524239
  import { join as join69, dirname as dirname16 } from "node:path";
523174
524240
  import { homedir as homedir22 } from "node:os";
523175
- import { randomBytes as randomBytes18, createHash as createHash9 } from "node:crypto";
524241
+ import { randomBytes as randomBytes18, createHash as createHash10 } from "node:crypto";
523176
524242
  function secretsPath(scope, repoRoot) {
523177
524243
  return scope === "global" ? join69(homedir22(), ".omnius", "secrets.json") : join69(repoRoot, ".omnius", "secrets.json");
523178
524244
  }
@@ -523213,7 +524279,7 @@ function sanitizeHint(hint) {
523213
524279
  return hint.toUpperCase().replace(/[^A-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 32) || "GENERIC";
523214
524280
  }
523215
524281
  function shortDigest(value2) {
523216
- return createHash9("sha256").update(value2).digest("hex").slice(0, 6);
524282
+ return createHash10("sha256").update(value2).digest("hex").slice(0, 6);
523217
524283
  }
523218
524284
  function randomSuffix() {
523219
524285
  return randomBytes18(3).toString("hex");
@@ -524909,7 +525975,7 @@ var init_environment_snapshot = __esm({
524909
525975
  import { execSync as execSync43 } from "node:child_process";
524910
525976
  import { existsSync as existsSync57, mkdirSync as mkdirSync29, writeFileSync as writeFileSync27, readFileSync as readFileSync43, readdirSync as readdirSync20, unlinkSync as unlinkSync12 } from "node:fs";
524911
525977
  import { join as join72, basename as basename15 } from "node:path";
524912
- import { createHash as createHash10 } from "node:crypto";
525978
+ import { createHash as createHash11 } from "node:crypto";
524913
525979
  function isYouTubeUrl2(url) {
524914
525980
  return /(?:youtube\.com\/(?:watch|shorts|live|embed|v\/)|youtu\.be\/)/i.test(url);
524915
525981
  }
@@ -524937,7 +526003,7 @@ function ensureFfmpeg() {
524937
526003
  function imageHash(imagePath) {
524938
526004
  try {
524939
526005
  const data = readFileSync43(imagePath);
524940
- return createHash10("md5").update(data).digest("hex").slice(0, 12);
526006
+ return createHash11("md5").update(data).digest("hex").slice(0, 12);
524941
526007
  } catch {
524942
526008
  return "unknown";
524943
526009
  }
@@ -526593,6 +527659,7 @@ __export(dist_exports, {
526593
527659
  DEFAULT_MUSIC_MODEL: () => DEFAULT_MUSIC_MODEL,
526594
527660
  DEFAULT_OLLAMA_IMAGE_MODEL: () => DEFAULT_OLLAMA_IMAGE_MODEL,
526595
527661
  DEFAULT_SOUND_MODEL: () => DEFAULT_SOUND_MODEL,
527662
+ DEFAULT_SPONSOR_MEDIA_LIMITS: () => DEFAULT_SPONSOR_MEDIA_LIMITS,
526596
527663
  DESKTOP_DEPS: () => DESKTOP_DEPS,
526597
527664
  DebateTool: () => DebateTool,
526598
527665
  DesktopClickTool: () => DesktopClickTool,
@@ -526655,6 +527722,8 @@ __export(dist_exports, {
526655
527722
  ReplTool: () => ReplTool,
526656
527723
  ReplayWithInterventionTool: () => ReplayWithInterventionTool,
526657
527724
  RepoMapTool: () => RepoMapTool,
527725
+ SPONSOR_MEDIA_CAPABILITY_PREFIX: () => SPONSOR_MEDIA_CAPABILITY_PREFIX,
527726
+ SPONSOR_MEDIA_MODALITIES: () => SPONSOR_MEDIA_MODALITIES,
526658
527727
  SchedulerTool: () => SchedulerTool,
526659
527728
  ScreenshotTool: () => ScreenshotTool,
526660
527729
  SdrScanTool: () => SdrScanTool,
@@ -526701,6 +527770,7 @@ __export(dist_exports, {
526701
527770
  aliasTool: () => aliasTool,
526702
527771
  applyPatch: () => applyPatch,
526703
527772
  applyToolResultTriage: () => applyToolResultTriage,
527773
+ artifactManifestFromBytes: () => artifactManifestFromBytes,
526704
527774
  audioGenerationDir: () => audioGenerationDir,
526705
527775
  audioGenerationSetupPlan: () => audioGenerationSetupPlan,
526706
527776
  audioGenerationVenvDir: () => audioGenerationVenvDir,
@@ -526714,6 +527784,7 @@ __export(dist_exports, {
526714
527784
  buildMcpToolName: () => buildMcpToolName,
526715
527785
  buildScaffoldedPrompt: () => buildScaffoldedPrompt,
526716
527786
  buildSkillsSummary: () => buildSkillsSummary,
527787
+ buildSponsorMediaServices: () => buildSponsorMediaServices,
526717
527788
  buildSubProcessArgs: () => buildSubProcessArgs,
526718
527789
  buildToolManifestFromModule: () => buildToolManifestFromModule,
526719
527790
  canInvokeTool: () => canInvokeTool,
@@ -526733,6 +527804,7 @@ __export(dist_exports, {
526733
527804
  createTransport: () => createTransport,
526734
527805
  createWorktree: () => createWorktree2,
526735
527806
  defaultExposureForTool: () => defaultExposureForTool,
527807
+ defaultExtensionForMime: () => defaultExtensionForMime,
526736
527808
  deleteTodos: () => deleteTodos,
526737
527809
  detectElevationMethod: () => detectElevationMethod,
526738
527810
  detectLegacyCaches: () => detectLegacyCaches,
@@ -526824,14 +527896,17 @@ __export(dist_exports, {
526824
527896
  markReverted: () => markReverted,
526825
527897
  markSessionValidated: () => markSessionValidated,
526826
527898
  measureRepoCacheBytes: () => measureRepoCacheBytes,
527899
+ mediaMimeFromPath: () => mediaMimeFromPath,
526827
527900
  migrateLegacyCaches: () => migrateLegacyCaches,
526828
527901
  networkEgressErrorMessage: () => networkEgressErrorMessage,
526829
527902
  normalizeMcpName: () => normalizeMcpName,
526830
527903
  normalizeNetworkHostname: () => normalizeNetworkHostname,
527904
+ normalizeSponsorMediaConfig: () => normalizeSponsorMediaConfig,
526831
527905
  omniusHomeDir: () => omniusHomeDir,
526832
527906
  packetPath: () => packetPath,
526833
527907
  parseMcpMarkdown: () => parseMcpMarkdown,
526834
527908
  parseMcpToolName: () => parseMcpToolName,
527909
+ parseSponsorMediaCapability: () => parseSponsorMediaCapability,
526835
527910
  playSoundFile: () => playSoundFile,
526836
527911
  promoteWorkingNotes: () => promoteWorkingNotes,
526837
527912
  quarantineSecret: () => quarantineSecret,
@@ -526862,6 +527937,7 @@ __export(dist_exports, {
526862
527937
  runTypecheck: () => runTypecheck,
526863
527938
  runValidationPipeline: () => runValidationPipeline,
526864
527939
  sanitizeReminderDeliveryText: () => sanitizeReminderDeliveryText,
527940
+ sanitizeRemoteMediaGenerateRequest: () => sanitizeRemoteMediaGenerateRequest,
526865
527941
  saveCustomToolDefinition: () => saveCustomToolDefinition,
526866
527942
  saveMcpServerToConfig: () => saveMcpServerToConfig,
526867
527943
  savePacket: () => savePacket,
@@ -526875,6 +527951,7 @@ __export(dist_exports, {
526875
527951
  sha256Text: () => sha256Text,
526876
527952
  shannonEntropy: () => shannonEntropy,
526877
527953
  spawnFullSubAgent: () => spawnFullSubAgent,
527954
+ sponsorMediaCapabilityName: () => sponsorMediaCapabilityName,
526878
527955
  stableJson: () => stableJson,
526879
527956
  stopFullSubAgent: () => stopFullSubAgent,
526880
527957
  summarizeLog: () => summarizeLog,
@@ -526962,6 +528039,7 @@ var init_dist5 = __esm({
526962
528039
  init_audio_generate();
526963
528040
  init_model_store();
526964
528041
  init_video_generate();
528042
+ init_sponsor_media();
526965
528043
  init_structured_read();
526966
528044
  init_vision();
526967
528045
  init_desktop_click();
@@ -531521,14 +532599,14 @@ var init_artifact_inspector = __esm({
531521
532599
  // packages/orchestrator/dist/lesson-bank.js
531522
532600
  import { existsSync as existsSync66, mkdirSync as mkdirSync32, appendFileSync as appendFileSync2, readFileSync as readFileSync51 } from "node:fs";
531523
532601
  import { join as join79, dirname as dirname22 } from "node:path";
531524
- import { createHash as createHash11 } from "node:crypto";
532602
+ import { createHash as createHash12 } from "node:crypto";
531525
532603
  function tokenize2(text) {
531526
532604
  if (!text)
531527
532605
  return [];
531528
532606
  return text.toLowerCase().split(TOKENIZE_RE).filter((t2) => t2.length >= 3).slice(0, 80);
531529
532607
  }
531530
532608
  function shortHash(s2) {
531531
- return createHash11("sha256").update(s2).digest("hex").slice(0, 16);
532609
+ return createHash12("sha256").update(s2).digest("hex").slice(0, 16);
531532
532610
  }
531533
532611
  function solicit(args) {
531534
532612
  const { taskGoal, stem, reflections, successOutputPreview } = args;
@@ -535153,7 +536231,7 @@ var init_pprRetrieval = __esm({
535153
536231
  import { join as join85 } from "node:path";
535154
536232
  import { mkdirSync as mkdirSync34, existsSync as existsSync72 } from "node:fs";
535155
536233
  import { randomUUID as randomUUID8 } from "node:crypto";
535156
- import { createHash as createHash12 } from "node:crypto";
536234
+ import { createHash as createHash13 } from "node:crypto";
535157
536235
  function readEpisodeAffect2(metadata) {
535158
536236
  if (!metadata || typeof metadata !== "object")
535159
536237
  return null;
@@ -535371,7 +536449,7 @@ var init_episodeStore = __esm({
535371
536449
  insert(ep) {
535372
536450
  const id = randomUUID8();
535373
536451
  const now = Date.now();
535374
- 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);
535375
536453
  const modality = ep.modality ?? "text";
535376
536454
  const rawImportance = ep.importance ?? autoImportance(ep.toolName ?? null, modality, ep.content);
535377
536455
  const modulated = ep.emotionalState ? modulateImportance(sanitizeImportance(rawImportance), ep.emotionalState) : sanitizeImportance(rawImportance);
@@ -535905,9 +536983,9 @@ var init_temporalGraph = __esm({
535905
536983
  });
535906
536984
 
535907
536985
  // packages/memory/dist/multimodalIdentity.js
535908
- import { createHash as createHash13 } from "node:crypto";
536986
+ import { createHash as createHash14 } from "node:crypto";
535909
536987
  function stableHash(value2) {
535910
- return createHash13("sha256").update(value2).digest("hex").slice(0, 24);
536988
+ return createHash14("sha256").update(value2).digest("hex").slice(0, 24);
535911
536989
  }
535912
536990
  function normalizeAtom(value2) {
535913
536991
  return value2.trim().toLowerCase().replace(/\s+/g, " ");
@@ -536264,9 +537342,9 @@ var init_gistCompressor = __esm({
536264
537342
  });
536265
537343
 
536266
537344
  // packages/memory/dist/graphWalk.js
536267
- import { createHash as createHash14 } from "node:crypto";
537345
+ import { createHash as createHash15 } from "node:crypto";
536268
537346
  function seededUnit(seed) {
536269
- const digest3 = createHash14("sha256").update(seed || "graph-walk").digest();
537347
+ const digest3 = createHash15("sha256").update(seed || "graph-walk").digest();
536270
537348
  const value2 = digest3.readUInt32BE(0);
536271
537349
  return value2 / 4294967295;
536272
537350
  }
@@ -540397,7 +541475,7 @@ var init_memoryStageContext = __esm({
540397
541475
  });
540398
541476
 
540399
541477
  // packages/memory/dist/sessionGist.js
540400
- import { createHash as createHash15 } from "node:crypto";
541478
+ import { createHash as createHash16 } from "node:crypto";
540401
541479
  function inferDomain(input) {
540402
541480
  const blob = [
540403
541481
  input.goal,
@@ -540422,7 +541500,7 @@ function inferDomain(input) {
540422
541500
  return ranked[0][0];
540423
541501
  }
540424
541502
  function computeGoalHash(goal) {
540425
- 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);
540426
541504
  }
540427
541505
  function clip(text, n2) {
540428
541506
  if (!text)
@@ -540633,12 +541711,12 @@ var init_toolOutcomes = __esm({
540633
541711
  });
540634
541712
 
540635
541713
  // packages/memory/dist/stagnationRecipes.js
540636
- import { createHash as createHash16 } from "node:crypto";
541714
+ import { createHash as createHash17 } from "node:crypto";
540637
541715
  function fingerprintSignature(fp) {
540638
541716
  const normClusters = (fp.errorClusters ?? []).map((s2) => (s2 || "").toLowerCase().replace(/[0-9]+/g, "N").replace(/\s+/g, " ").trim()).filter(Boolean).sort();
540639
541717
  const tool = (fp.stuckTool ?? "").toLowerCase().trim();
540640
541718
  const blob = `tool=${tool};clusters=${normClusters.join("|")}`;
540641
- return createHash16("sha256").update(blob).digest("hex").slice(0, 16);
541719
+ return createHash17("sha256").update(blob).digest("hex").slice(0, 16);
540642
541720
  }
540643
541721
  function crystallize(store2, input) {
540644
541722
  const sig = fingerprintSignature(input.fingerprint);
@@ -540695,7 +541773,7 @@ var init_stagnationRecipes = __esm({
540695
541773
  });
540696
541774
 
540697
541775
  // packages/memory/dist/codebaseMap.js
540698
- import { createHash as createHash17, randomUUID as randomUUID12 } from "node:crypto";
541776
+ import { createHash as createHash18, randomUUID as randomUUID12 } from "node:crypto";
540699
541777
  function freshNodeId() {
540700
541778
  return randomUUID12();
540701
541779
  }
@@ -540709,7 +541787,7 @@ var init_codebaseMap = __esm({
540709
541787
  touchCount = /* @__PURE__ */ new Map();
540710
541788
  constructor(db, repoRoot, commitSha) {
540711
541789
  this.db = db;
540712
- 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);
540713
541791
  this.ensureSchema();
540714
541792
  }
540715
541793
  ensureSchema() {
@@ -540891,7 +541969,7 @@ var init_codebaseMap = __esm({
540891
541969
  }
540892
541970
  /** Stable composite id: `<kind>:<sha16(path)>` so insert ON CONFLICT works. */
540893
541971
  idFor(kind, path12) {
540894
- 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);
540895
541973
  return `${kind}-${h}`;
540896
541974
  }
540897
541975
  };
@@ -543402,7 +544480,7 @@ import { existsSync as existsSync80, readFileSync as readFileSync62, statSync as
543402
544480
  import { execSync as execSync46 } from "node:child_process";
543403
544481
  import { homedir as homedir29, platform as platform3, arch as arch2, totalmem as totalmem3, freemem as freemem3, hostname as hostname3 } from "node:os";
543404
544482
  import { join as join93 } from "node:path";
543405
- import { createHash as createHash18 } from "node:crypto";
544483
+ import { createHash as createHash19 } from "node:crypto";
543406
544484
  function capturePreflightSnapshot(workingDir) {
543407
544485
  const warnings = [];
543408
544486
  const configFingerprints = {};
@@ -543569,7 +544647,7 @@ function expandPath(p2) {
543569
544647
  return p2;
543570
544648
  }
543571
544649
  function sha2563(s2) {
543572
- return createHash18("sha256").update(s2).digest("hex").slice(0, 16);
544650
+ return createHash19("sha256").update(s2).digest("hex").slice(0, 16);
543573
544651
  }
543574
544652
  function freeDiskBytes(path12 = "/tmp") {
543575
544653
  try {
@@ -549831,8 +550909,8 @@ If you're stuck, try a completely different approach. Do NOT repeat what failed
549831
550909
  if (process.env["OMNIUS_DISABLE_ADAPTIVE_RETRIEVAL"] !== "1") {
549832
550910
  const goalForSig = (this._taskState.goal || "").slice(0, 200);
549833
550911
  const recentTools = this._toolSequence.slice(-5).join("|");
549834
- const { createHash: createHash32 } = await import("node:crypto");
549835
- 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);
549836
550914
  if (this._lastPprSig === sig && this._lastPprMemoryLines.length > 0) {
549837
550915
  compacted.push({
549838
550916
  role: "system",
@@ -563288,10 +564366,10 @@ transcribe-cli error: ${transcribeCliError}` : "";
563288
564366
  wordTimestamps: false
563289
564367
  });
563290
564368
  if (outputDir) {
563291
- const { basename: basename34 } = await import("node:path");
564369
+ const { basename: basename35 } = await import("node:path");
563292
564370
  const transcriptDir = join102(outputDir, ".omnius", "transcripts");
563293
564371
  mkdirSync48(transcriptDir, { recursive: true });
563294
- const outFile = join102(transcriptDir, `${basename34(filePath)}.txt`);
564372
+ const outFile = join102(transcriptDir, `${basename35(filePath)}.txt`);
563295
564373
  writeFileSync43(outFile, result.text, "utf-8");
563296
564374
  }
563297
564375
  return {
@@ -563307,10 +564385,10 @@ transcribe-cli error: ${transcribeCliError}` : "";
563307
564385
  const fb = await transcribeFileViaWhisper(filePath, this.config.model);
563308
564386
  if (fb) {
563309
564387
  if (outputDir) {
563310
- const { basename: basename34 } = await import("node:path");
564388
+ const { basename: basename35 } = await import("node:path");
563311
564389
  const transcriptDir = join102(outputDir, ".omnius", "transcripts");
563312
564390
  mkdirSync48(transcriptDir, { recursive: true });
563313
- const outFile = join102(transcriptDir, `${basename34(filePath)}.txt`);
564391
+ const outFile = join102(transcriptDir, `${basename35(filePath)}.txt`);
563314
564392
  writeFileSync43(outFile, fb.text, "utf-8");
563315
564393
  }
563316
564394
  return fb;
@@ -565558,7 +566636,7 @@ var require_websocket3 = __commonJS({
565558
566636
  var http6 = __require("http");
565559
566637
  var net5 = __require("net");
565560
566638
  var tls2 = __require("tls");
565561
- var { randomBytes: randomBytes29, createHash: createHash32 } = __require("crypto");
566639
+ var { randomBytes: randomBytes29, createHash: createHash34 } = __require("crypto");
565562
566640
  var { Duplex: Duplex3, Readable } = __require("stream");
565563
566641
  var { URL: URL3 } = __require("url");
565564
566642
  var PerMessageDeflate3 = require_permessage_deflate3();
@@ -566218,7 +567296,7 @@ var require_websocket3 = __commonJS({
566218
567296
  abortHandshake(websocket, socket, "Invalid Upgrade header");
566219
567297
  return;
566220
567298
  }
566221
- const digest3 = createHash32("sha1").update(key + GUID).digest("base64");
567299
+ const digest3 = createHash34("sha1").update(key + GUID).digest("base64");
566222
567300
  if (res.headers["sec-websocket-accept"] !== digest3) {
566223
567301
  abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
566224
567302
  return;
@@ -566585,7 +567663,7 @@ var require_websocket_server2 = __commonJS({
566585
567663
  var EventEmitter15 = __require("events");
566586
567664
  var http6 = __require("http");
566587
567665
  var { Duplex: Duplex3 } = __require("stream");
566588
- var { createHash: createHash32 } = __require("crypto");
567666
+ var { createHash: createHash34 } = __require("crypto");
566589
567667
  var extension3 = require_extension3();
566590
567668
  var PerMessageDeflate3 = require_permessage_deflate3();
566591
567669
  var subprotocol3 = require_subprotocol2();
@@ -566886,7 +567964,7 @@ var require_websocket_server2 = __commonJS({
566886
567964
  );
566887
567965
  }
566888
567966
  if (this._state > RUNNING) return abortHandshake(socket, 503);
566889
- const digest3 = createHash32("sha1").update(key + GUID).digest("base64");
567967
+ const digest3 = createHash34("sha1").update(key + GUID).digest("base64");
566890
567968
  const headers = [
566891
567969
  "HTTP/1.1 101 Switching Protocols",
566892
567970
  "Upgrade: websocket",
@@ -567639,6 +568717,10 @@ var init_command_registry = __esm({
567639
568717
  ["/ipfs import <cid>", "Import a shared IPFS tool or skill reference"],
567640
568718
  ["/sponsor", "Sponsor inference - onboarding wizard or dashboard"],
567641
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"],
567642
568724
  ["/sponsor pause", "Pause active sponsorship"],
567643
568725
  ["/sponsor remove", "Remove sponsorship entirely"],
567644
568726
  ["/endpoint sponsor", "Browse and connect to sponsored inference from the nexus mesh"],
@@ -571672,14 +572754,14 @@ var init_voice_session = __esm({
571672
572754
  });
571673
572755
 
571674
572756
  // packages/cli/src/tui/scoped-personality.ts
571675
- import { createHash as createHash19 } from "node:crypto";
572757
+ import { createHash as createHash20 } from "node:crypto";
571676
572758
  import { appendFileSync as appendFileSync5, existsSync as existsSync88, mkdirSync as mkdirSync49, readFileSync as readFileSync69, writeFileSync as writeFileSync44 } from "node:fs";
571677
572759
  import { join as join103, resolve as resolve39 } from "node:path";
571678
572760
  function safeName(input) {
571679
572761
  return input.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 80) || "default";
571680
572762
  }
571681
572763
  function scopeHash(scope) {
571682
- 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);
571683
572765
  }
571684
572766
  function scopedPersonalityDir(repoRoot, kind) {
571685
572767
  return resolve39(repoRoot, ".omnius", "scoped-personality", kind);
@@ -572010,7 +573092,7 @@ var init_scoped_personality = __esm({
572010
573092
  });
572011
573093
 
572012
573094
  // packages/cli/src/tui/voice-soul.ts
572013
- import { createHash as createHash20 } from "node:crypto";
573095
+ import { createHash as createHash21 } from "node:crypto";
572014
573096
  import { existsSync as existsSync89, readdirSync as readdirSync29, readFileSync as readFileSync70 } from "node:fs";
572015
573097
  import { basename as basename20, join as join104, resolve as resolve40 } from "node:path";
572016
573098
  function compactText(text, limit) {
@@ -572025,7 +573107,7 @@ function blockText(text, limit) {
572025
573107
  ... [truncated]`;
572026
573108
  }
572027
573109
  function scopeStateKey(scope, surface) {
572028
- 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);
572029
573111
  }
572030
573112
  function safeName2(input) {
572031
573113
  return input.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 80) || "default";
@@ -572553,6 +573635,26 @@ function serializeSponsorModels(stats) {
572553
573635
  (a2, b) => (b.tokensIn + b.tokensOut || b.requests) - (a2.tokensIn + a2.tokensOut || a2.requests)
572554
573636
  );
572555
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
+ }
572556
573658
  function serializeSponsorPeers(stats) {
572557
573659
  return Array.from(stats.users.values()).map((user) => ({
572558
573660
  peer: user.ip,
@@ -572568,7 +573670,20 @@ function serializeSponsorPeers(stats) {
572568
573670
  tokensIn: meter.tokensIn,
572569
573671
  tokensOut: meter.tokensOut,
572570
573672
  lastUsed: meter.lastUsed
572571
- })).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))
572572
573687
  })).sort((a2, b) => (b.tokensIn + b.tokensOut || b.requests) - (a2.tokensIn + a2.tokensOut || a2.requests));
572573
573688
  }
572574
573689
  function nextSponsorDailyReset(now = Date.now()) {
@@ -572766,6 +573881,7 @@ var HOP_BY_HOP_HEADERS, CF_HEADERS_PREFIX, DEFAULT_EXPOSE_MAX_BODY_BYTES, INTERN
572766
573881
  var init_expose = __esm({
572767
573882
  "packages/cli/src/tui/expose.ts"() {
572768
573883
  "use strict";
573884
+ init_dist5();
572769
573885
  init_render();
572770
573886
  init_usage_bars();
572771
573887
  init_typed_node_events();
@@ -572851,6 +573967,7 @@ var init_expose = __esm({
572851
573967
  tokensPerSecond: 0,
572852
573968
  startedAt: Date.now(),
572853
573969
  modelUsage: /* @__PURE__ */ new Map(),
573970
+ mediaUsage: /* @__PURE__ */ new Map(),
572854
573971
  users: /* @__PURE__ */ new Map(),
572855
573972
  budgetTokensRemaining: 0,
572856
573973
  budgetTokensTotal: 0,
@@ -572963,8 +574080,10 @@ var init_expose = __esm({
572963
574080
  maxConcurrent: this._sponsorLimits.maxConcurrent,
572964
574081
  blockedRequests: this._sponsorBlockedRequests,
572965
574082
  allowedModels: this._sponsorLimits.allowedModels === "all" ? "all" : [...this._sponsorLimits.allowedModels],
574083
+ mediaLimits: this._sponsorLimits.media ? normalizeSponsorMediaConfig(this._sponsorLimits.media) : void 0,
572966
574084
  peers: serializeSponsorPeers(this._stats),
572967
- models: serializeSponsorModels(this._stats)
574085
+ models: serializeSponsorModels(this._stats),
574086
+ media: serializeSponsorMedia(this._stats)
572968
574087
  };
572969
574088
  }
572970
574089
  recordServedTokens(tokens, now = Date.now()) {
@@ -573222,7 +574341,8 @@ var init_expose = __esm({
573222
574341
  tokensIn: 0,
573223
574342
  tokensOut: 0,
573224
574343
  activeRequests: 0,
573225
- models: /* @__PURE__ */ new Map()
574344
+ models: /* @__PURE__ */ new Map(),
574345
+ media: /* @__PURE__ */ new Map()
573226
574346
  };
573227
574347
  this._stats.users.set(userIp, user);
573228
574348
  }
@@ -573726,6 +574846,7 @@ ${this.formatConnectionInfo()}`);
573726
574846
  this.emit("stats", {
573727
574847
  ...this._stats,
573728
574848
  modelUsage: new Map(this._stats.modelUsage),
574849
+ mediaUsage: new Map(this._stats.mediaUsage),
573729
574850
  users: new Map(this._stats.users),
573730
574851
  sponsorUsage: this._stats.sponsorUsage ? { ...this._stats.sponsorUsage } : null
573731
574852
  });
@@ -573791,6 +574912,10 @@ ${this.formatConnectionInfo()}`);
573791
574912
  total: s2.sponsorUsage.maxConcurrent
573792
574913
  })}`);
573793
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
+ }
573794
574919
  }
573795
574920
  const visibleModels = Array.from(s2.modelUsage.entries()).filter(([model]) => !INTERNAL_CAPABILITIES.has(model));
573796
574921
  if (visibleModels.length > 0) {
@@ -573808,6 +574933,15 @@ ${this.formatConnectionInfo()}`);
573808
574933
  lines.push(` ${c3.cyan(model.padEnd(30))} ${count} reqs ${c3.dim(`in:${fmtTokens(mIn)} out:${fmtTokens(mOut)}`)}`);
573809
574934
  }
573810
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
+ }
573811
574945
  if (s2.users.size > 0) {
573812
574946
  lines.push("");
573813
574947
  lines.push(` ${c3.bold("Active Users")} (${s2.users.size})`);
@@ -573876,6 +575010,7 @@ ${this.formatConnectionInfo()}`);
573876
575010
  tokensPerSecond: 0,
573877
575011
  startedAt: Date.now(),
573878
575012
  modelUsage: /* @__PURE__ */ new Map(),
575013
+ mediaUsage: /* @__PURE__ */ new Map(),
573879
575014
  users: /* @__PURE__ */ new Map(),
573880
575015
  budgetTokensRemaining: 0,
573881
575016
  budgetTokensTotal: 0,
@@ -574014,8 +575149,10 @@ ${this.formatConnectionInfo()}`);
574014
575149
  maxConcurrent: this._sponsorLimits.maxConcurrent,
574015
575150
  blockedRequests: this._sponsorBlockedRequests,
574016
575151
  allowedModels: this._sponsorLimits.allowedModels === "all" ? "all" : [...this._sponsorLimits.allowedModels],
575152
+ mediaLimits: this._sponsorLimits.media ? normalizeSponsorMediaConfig(this._sponsorLimits.media) : void 0,
574017
575153
  peers: serializeSponsorPeers(this._stats),
574018
- models: serializeSponsorModels(this._stats)
575154
+ models: serializeSponsorModels(this._stats),
575155
+ media: serializeSponsorMedia(this._stats)
574019
575156
  };
574020
575157
  }
574021
575158
  recordServedTokens(tokens, now = Date.now()) {
@@ -574040,6 +575177,9 @@ ${this.formatConnectionInfo()}`);
574040
575177
  exposeArgs.daily_tokens_used = String(this._dailyTokensUsed);
574041
575178
  exposeArgs.daily_tokens_reset_at = String(this._dailyTokensResetAt);
574042
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
+ }
574043
575183
  }
574044
575184
  return exposeArgs;
574045
575185
  }
@@ -574290,6 +575430,55 @@ ${this.formatConnectionInfo()}`);
574290
575430
  this.refreshSponsorUsageStats();
574291
575431
  continue;
574292
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
+ }
574293
575482
  let tokIn = 0;
574294
575483
  let tokOut = 0;
574295
575484
  if (typeof record.inputTokens === "number" && typeof record.outputTokens === "number") {
@@ -574325,7 +575514,8 @@ ${this.formatConnectionInfo()}`);
574325
575514
  tokensIn: 0,
574326
575515
  tokensOut: 0,
574327
575516
  activeRequests: 0,
574328
- models: /* @__PURE__ */ new Map()
575517
+ models: /* @__PURE__ */ new Map(),
575518
+ media: /* @__PURE__ */ new Map()
574329
575519
  };
574330
575520
  this._stats.users.set(shortPeer, user);
574331
575521
  }
@@ -574380,6 +575570,7 @@ ${this.formatConnectionInfo()}`);
574380
575570
  this.emit("stats", {
574381
575571
  ...this._stats,
574382
575572
  modelUsage: new Map(this._stats.modelUsage),
575573
+ mediaUsage: new Map(this._stats.mediaUsage),
574383
575574
  users: new Map(this._stats.users),
574384
575575
  sponsorUsage: this._stats.sponsorUsage ? { ...this._stats.sponsorUsage } : null
574385
575576
  });
@@ -574519,7 +575710,7 @@ var init_types = __esm({
574519
575710
  });
574520
575711
 
574521
575712
  // packages/cli/src/tui/p2p/secret-vault.ts
574522
- 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";
574523
575714
  import { readFileSync as readFileSync72, writeFileSync as writeFileSync46, existsSync as existsSync91, mkdirSync as mkdirSync51 } from "node:fs";
574524
575715
  import { dirname as dirname28 } from "node:path";
574525
575716
  var PLACEHOLDER_PREFIX, PLACEHOLDER_SUFFIX, CIPHER_ALGO, SALT_LEN, IV_LEN, KEY_LEN, SecretVault;
@@ -574764,7 +575955,7 @@ var init_secret_vault = __esm({
574764
575955
  /** Generate a deterministic fingerprint of vault contents (for sync verification) */
574765
575956
  fingerprint() {
574766
575957
  const names = Array.from(this.secrets.keys()).sort();
574767
- const hash = createHash21("sha256");
575958
+ const hash = createHash22("sha256");
574768
575959
  for (const name10 of names) {
574769
575960
  hash.update(name10 + ":");
574770
575961
  hash.update(this.secrets.get(name10).value);
@@ -574779,7 +575970,7 @@ var init_secret_vault = __esm({
574779
575970
  // packages/cli/src/tui/p2p/peer-mesh.ts
574780
575971
  import { EventEmitter as EventEmitter9 } from "node:events";
574781
575972
  import { createServer as createServer6 } from "node:http";
574782
- import { randomBytes as randomBytes22, createHash as createHash22, generateKeyPairSync } from "node:crypto";
575973
+ import { randomBytes as randomBytes22, createHash as createHash23, generateKeyPairSync } from "node:crypto";
574783
575974
  var PING_INTERVAL_MS, PEER_TIMEOUT_MS, GOSSIP_INTERVAL_MS, MAX_PEERS, PeerMesh;
574784
575975
  var init_peer_mesh = __esm({
574785
575976
  "packages/cli/src/tui/p2p/peer-mesh.ts"() {
@@ -574796,7 +575987,7 @@ var init_peer_mesh = __esm({
574796
575987
  const { publicKey: publicKey2, privateKey } = generateKeyPairSync("ed25519");
574797
575988
  this.publicKey = publicKey2.export({ type: "spki", format: "der" });
574798
575989
  this.privateKey = privateKey.export({ type: "pkcs8", format: "der" });
574799
- 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);
574800
575991
  this.capabilities = options2.capabilities;
574801
575992
  this.displayName = options2.displayName;
574802
575993
  this._authKey = options2.authKey ?? randomBytes22(24).toString("base64url");
@@ -576134,7 +577325,7 @@ __export(omnius_directory_exports, {
576134
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";
576135
577326
  import { join as join110, relative as relative9, basename as basename21, dirname as dirname31, resolve as resolve41 } from "node:path";
576136
577327
  import { homedir as homedir34 } from "node:os";
576137
- import { createHash as createHash23 } from "node:crypto";
577328
+ import { createHash as createHash24 } from "node:crypto";
576138
577329
  function isGitRoot(dir) {
576139
577330
  const gitPath = join110(dir, ".git");
576140
577331
  if (!existsSync94(gitPath)) return false;
@@ -576588,7 +577779,7 @@ function buildHandoffPrompt(repoRoot) {
576588
577779
  return lines.join("\n");
576589
577780
  }
576590
577781
  function computeDedupeHash(task, savedAt) {
576591
- return createHash23("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
577782
+ return createHash24("sha256").update(`${task}|${savedAt}`).digest("hex").slice(0, 16);
576592
577783
  }
576593
577784
  function generateSessionId() {
576594
577785
  const timestamp = Date.now().toString(36);
@@ -591501,7 +592692,8 @@ function defaultConfig2() {
591501
592692
  maxRequestsPerMinute: 60,
591502
592693
  maxTokensPerDay: 1e5,
591503
592694
  maxConcurrent: 5,
591504
- allowedModels: "all"
592695
+ allowedModels: "all",
592696
+ media: normalizeSponsorMediaConfig(DEFAULT_SPONSOR_MEDIA_LIMITS)
591505
592697
  },
591506
592698
  cohereEnabled: true,
591507
592699
  status: "inactive",
@@ -591509,6 +592701,10 @@ function defaultConfig2() {
591509
592701
  updatedAt: (/* @__PURE__ */ new Date()).toISOString()
591510
592702
  };
591511
592703
  }
592704
+ function normalizeLoadedSponsorConfig(config) {
592705
+ config.rateLimits.media = normalizeSponsorMediaConfig(config.rateLimits.media);
592706
+ return config;
592707
+ }
591512
592708
  function endpointAuthToken(authHeader) {
591513
592709
  const raw = (authHeader || "").trim();
591514
592710
  if (!raw) return void 0;
@@ -592150,6 +593346,99 @@ async function stepTransport(config, rl, availableRows) {
592150
593346
  }
592151
593347
  return false;
592152
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
+ }
592153
593442
  async function stepCohere(config, rl, availableRows) {
592154
593443
  const items = [
592155
593444
  { key: "hdr", label: "COHERE — Distributed Intelligence (Experimental)" },
@@ -592176,7 +593465,7 @@ async function stepCohere(config, rl, availableRows) {
592176
593465
  ];
592177
593466
  const result = await tuiSelect({
592178
593467
  items,
592179
- title: "Step 5/6 — COHERE Distributed Intelligence",
593468
+ title: "Step 6/7 — COHERE Distributed Intelligence",
592180
593469
  rl,
592181
593470
  skipKeys: ["hdr", "desc1", "desc2", "desc3", "desc4", "desc5", "desc6", "desc7", "desc8", "desc9", "desc10", "desc11", "desc12", "desc13", "desc14", "desc15", "desc16", "sep1", "sep2"],
592182
593471
  availableRows,
@@ -592213,6 +593502,9 @@ async function stepReview(config, rl, availableRows) {
592213
593502
  const transports = [];
592214
593503
  if (config.transport.cloudflared) transports.push("Cloudflared Tunnel");
592215
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);
592216
593508
  const items = [
592217
593509
  { key: "hdr", label: "Review Sponsorship Configuration" },
592218
593510
  { key: "info_ep", label: ` Endpoints: ${epList}` },
@@ -592220,16 +593512,17 @@ async function stepReview(config, rl, availableRows) {
592220
593512
  { key: "info_link", label: ` Link: ${config.header.linkEnabled ? `${config.header.linkUrl} [${config.header.linkText || config.header.message}]` : "(none)"}` },
592221
593513
  { key: "info_transport", label: ` Transport: ${transports.join(" + ")}` },
592222
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"}` },
592223
593516
  { key: "info_cohere", label: ` COHERE: ${config.cohereEnabled ? "enabled (distributed inference)" : "disabled"}` },
592224
593517
  { key: "sep", label: "" },
592225
- { key: "go_live", label: selectColors.green(" ✦ Go Live & Sponsor Inference ") },
593518
+ { key: "go_live", label: selectColors.green(" ✦ Go Live & Sponsor Services ") },
592226
593519
  { key: "cancel", label: selectColors.dim(" Cancel") }
592227
593520
  ];
592228
593521
  const result = await tuiSelect({
592229
593522
  items,
592230
- title: "Step 6/6 — Review & Go Live",
593523
+ title: "Step 7/7 — Review & Go Live",
592231
593524
  rl,
592232
- 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"],
592233
593526
  availableRows
592234
593527
  });
592235
593528
  if (!result.confirmed || result.key === "cancel") return false;
@@ -592238,11 +593531,14 @@ async function stepReview(config, rl, availableRows) {
592238
593531
  async function showSponsorDashboard(config, projectDir2, rl, availableRows, sponsorUsage) {
592239
593532
  const isPaused = config.status === "paused";
592240
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);
592241
593536
  const dailyTokensLimit = sponsorUsage?.dailyTokensLimit || config.rateLimits.maxTokensPerDay;
592242
593537
  const requestsPerMinuteLimit = sponsorUsage?.requestsPerMinuteLimit || config.rateLimits.maxRequestsPerMinute;
592243
593538
  const maxConcurrent = sponsorUsage?.maxConcurrent || config.rateLimits.maxConcurrent;
592244
593539
  const topModels = (sponsorUsage?.models ?? []).slice(0, 5);
592245
593540
  const topPeers = (sponsorUsage?.peers ?? []).slice(0, 5);
593541
+ const topMedia = (sponsorUsage?.media ?? []).slice(0, 5);
592246
593542
  const usageItems = [
592247
593543
  {
592248
593544
  key: "info_usage_totals",
@@ -592298,12 +593594,23 @@ async function showSponsorDashboard(config, projectDir2, rl, availableRows, spon
592298
593594
  });
592299
593595
  }
592300
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
+ }
592301
593607
  const items = [
592302
593608
  { key: "hdr", label: "Sponsor Dashboard" },
592303
593609
  { key: "info_status", label: ` Status: ${isPaused ? "● PAUSED" : "● ACTIVE"}` },
592304
593610
  { key: "info_ep", label: ` Endpoints: ${enabledEps.map((e2) => e2.label).join(", ")}` },
592305
593611
  { key: "info_transport", label: ` Transport: ${[config.transport.cloudflared ? "Cloudflared" : "", config.transport.libp2p ? "libp2p" : ""].filter(Boolean).join(" + ")}` },
592306
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"}` },
592307
593614
  { key: "info_usage_hdr", label: " Usage" },
592308
593615
  ...usageItems,
592309
593616
  { key: "sep", label: "" },
@@ -592322,7 +593629,7 @@ async function showSponsorDashboard(config, projectDir2, rl, availableRows, spon
592322
593629
  return result.key || "close";
592323
593630
  }
592324
593631
  async function runSponsorWizard(ctx3) {
592325
- let config = loadSponsorConfig(ctx3.projectDir) || defaultConfig2();
593632
+ let config = normalizeLoadedSponsorConfig(loadSponsorConfig(ctx3.projectDir) || defaultConfig2());
592326
593633
  renderInfo("Starting sponsor onboarding wizard...\n");
592327
593634
  if (!await stepEndpoints(config, ctx3.ollamaUrl, ctx3.rl, ctx3.availableRows, ctx3.projectDir)) {
592328
593635
  renderInfo("Sponsor wizard cancelled.");
@@ -592340,6 +593647,11 @@ async function runSponsorWizard(ctx3) {
592340
593647
  return null;
592341
593648
  }
592342
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);
592343
593655
  if (!await stepCohere(config, ctx3.rl, ctx3.availableRows)) {
592344
593656
  renderInfo("Sponsor wizard cancelled.");
592345
593657
  return null;
@@ -592381,6 +593693,7 @@ var init_sponsor_wizard = __esm({
592381
593693
  init_tui_select();
592382
593694
  init_render();
592383
593695
  init_usage_bars();
593696
+ init_dist5();
592384
593697
  }
592385
593698
  });
592386
593699
 
@@ -596567,6 +597880,7 @@ __export(commands_exports, {
596567
597880
  });
596568
597881
  import * as nodeOs from "node:os";
596569
597882
  import { execSync as nodeExecSync } from "node:child_process";
597883
+ import { createHash as createHash25 } from "node:crypto";
596570
597884
  import {
596571
597885
  existsSync as existsSync107,
596572
597886
  readFileSync as readFileSync86,
@@ -596579,7 +597893,7 @@ import {
596579
597893
  appendFileSync as appendFileSync8,
596580
597894
  writeSync as writeSync2
596581
597895
  } from "node:fs";
596582
- 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";
596583
597897
  async function parseJsonResponse(resp, source) {
596584
597898
  const body = await resp.text();
596585
597899
  const trimmed = body.trim();
@@ -596973,12 +598287,12 @@ async function ensureVoiceDeps(ctx3) {
596973
598287
  renderInfo(res.log.split("\n").slice(-3).join(" ").slice(0, 200));
596974
598288
  }
596975
598289
  if (typeof mod2.getVenvPython === "function") {
596976
- const { dirname: dirname43 } = await import("node:path");
598290
+ const { dirname: dirname44 } = await import("node:path");
596977
598291
  const { existsSync: existsSync137 } = await import("node:fs");
596978
598292
  const venvPy = mod2.getVenvPython();
596979
598293
  if (existsSync137(venvPy)) {
596980
598294
  process.env.TRANSCRIBE_PYTHON = venvPy;
596981
- const venvBin = dirname43(venvPy);
598295
+ const venvBin = dirname44(venvPy);
596982
598296
  const sep4 = process.platform === "win32" ? ";" : ":";
596983
598297
  const cur = process.env.PATH || "";
596984
598298
  if (!cur.split(sep4).includes(venvBin)) {
@@ -600934,6 +602248,11 @@ sleep 1
600934
602248
  return "handled";
600935
602249
  }
600936
602250
  case "sponsor": {
602251
+ const mediaCommand = parseSponsorMediaCommand(arg);
602252
+ if (mediaCommand) {
602253
+ await handleSponsorMediaCommand(ctx3, mediaCommand.modality, mediaCommand.rest);
602254
+ return "handled";
602255
+ }
600937
602256
  if (!ctx3.rl) {
600938
602257
  renderWarning("Sponsor wizard requires interactive mode.");
600939
602258
  return "handled";
@@ -601180,6 +602499,21 @@ sleep 1
601180
602499
  if (allModels.length > 0) {
601181
602500
  config.rateLimits.allowedModels = allModels;
601182
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
+ ];
601183
602517
  renderInfo(
601184
602518
  `Sponsoring ${primaryProvider.label} endpoint: ${new URL(primaryUrl).host}`
601185
602519
  );
@@ -601438,8 +602772,11 @@ sleep 1
601438
602772
  limits: {
601439
602773
  maxRequestsPerMinute: config.rateLimits.maxRequestsPerMinute,
601440
602774
  maxTokensPerDay: config.rateLimits.maxTokensPerDay,
601441
- maxConcurrent: config.rateLimits.maxConcurrent
602775
+ maxConcurrent: config.rateLimits.maxConcurrent,
602776
+ media: config.rateLimits.media
601442
602777
  },
602778
+ services: sponsorServices,
602779
+ mediaCapabilities: sponsorServices.filter((service) => service.kind !== "llm"),
601443
602780
  banner: "none",
601444
602781
  message: config.header.message || sponsorName,
601445
602782
  linkUrl: config.header.linkUrl,
@@ -604995,7 +606332,14 @@ function emptyCohereStats(isActive = false) {
604995
606332
  bytesOut: 0,
604996
606333
  modelsUsed: {},
604997
606334
  peersServed: {},
604998
- allowedModels: null
606335
+ allowedModels: null,
606336
+ endpoint: {
606337
+ source: "unknown",
606338
+ passthrough: false,
606339
+ endpointUrl: "",
606340
+ modelCount: 0,
606341
+ updatedAt: 0
606342
+ }
604999
606343
  };
605000
606344
  }
605001
606345
  function numberField(value2) {
@@ -605014,6 +606358,7 @@ function parseCohereStatsOutput(output, isActive = false) {
605014
606358
  try {
605015
606359
  const parsed = JSON.parse(output);
605016
606360
  const active = typeof parsed.active === "boolean" ? parsed.active : String(parsed.status ?? "").toLowerCase() === "active";
606361
+ const endpointRaw = parsed.endpoint && typeof parsed.endpoint === "object" ? parsed.endpoint : {};
605017
606362
  return {
605018
606363
  status: active ? "active" : "inactive",
605019
606364
  active,
@@ -605029,7 +606374,15 @@ function parseCohereStatsOutput(output, isActive = false) {
605029
606374
  bytesOut: numberField(parsed.bytesOut),
605030
606375
  modelsUsed: mapNumberRecord(parsed.modelsUsed),
605031
606376
  peersServed: mapNumberRecord(parsed.peersServed),
605032
- allowedModels: Array.isArray(parsed.allowedModels) ? parsed.allowedModels.map(String) : null
606377
+ allowedModels: Array.isArray(parsed.allowedModels) ? parsed.allowedModels.map(String) : null,
606378
+ endpoint: {
606379
+ source: String(endpointRaw.source ?? "unknown"),
606380
+ passthrough: endpointRaw.passthrough === true,
606381
+ endpointUrl: String(endpointRaw.endpointUrl ?? ""),
606382
+ modelCount: numberField(endpointRaw.modelCount),
606383
+ updatedAt: numberField(endpointRaw.updatedAt),
606384
+ cachedOnly: endpointRaw.cachedOnly === true
606385
+ }
605033
606386
  };
605034
606387
  } catch {
605035
606388
  return emptyCohereStats(isActive);
@@ -605054,10 +606407,11 @@ async function fetchCohereDashboardState(ctx3) {
605054
606407
  } catch {
605055
606408
  }
605056
606409
  try {
605057
- const r2 = await nexus.execute({ action: "cohere_list_models" });
606410
+ const r2 = await nexus.execute({ action: "cohere_list_models", format: "json" });
605058
606411
  if (r2.success) {
605059
606412
  try {
605060
- state.modelList = JSON.parse(r2.output).models || [];
606413
+ const parsed = JSON.parse(r2.output);
606414
+ state.modelList = Array.isArray(parsed.models) ? parsed.models.map(String) : [];
605061
606415
  } catch {
605062
606416
  state.modelList = r2.output.split("\n").map((l2) => l2.trim()).filter(Boolean);
605063
606417
  }
@@ -605083,8 +606437,9 @@ function cohereStatusLines(stats, modelList) {
605083
606437
  `Sent out: ${stats.queriesSent} · avg latency ${stats.avgLatencyMs}ms`,
605084
606438
  `Data: in ${formatFileSize(stats.bytesIn)} · out ${formatFileSize(stats.bytesOut)}`,
605085
606439
  "",
605086
- `Models exposed: ${modelList.length}`,
605087
- `Allowlist: ${stats.allowedModels ? stats.allowedModels.join(", ") || "(empty)" : "all downloaded models"}`,
606440
+ `Endpoint: ${stats.endpoint.source}${stats.endpoint.passthrough ? " passthrough" : ""}${stats.endpoint.endpointUrl ? ` · ${stats.endpoint.endpointUrl}` : ""}`,
606441
+ `Models available: ${modelList.length || stats.endpoint.modelCount}${stats.endpoint.cachedOnly ? " (cached)" : ""}`,
606442
+ `Allowlist: ${stats.allowedModels ? stats.allowedModels.join(", ") || "(empty)" : "all endpoint models"}`,
605088
606443
  `Top models: ${modelEntries.length ? modelEntries.slice(0, 5).map(([m2, n2]) => `${m2} (${n2})`).join(", ") : "none yet"}`,
605089
606444
  `Peers served: ${peerEntries.length ? peerEntries.slice(0, 5).map(([p2, n2]) => `${p2.slice(0, 20)} (${n2})`).join(", ") : "none yet"}`
605090
606445
  ];
@@ -605098,7 +606453,7 @@ async function showCohereDashboard(ctx3) {
605098
606453
  while (true) {
605099
606454
  const currentActive = ctx3.isCohere?.() ?? false;
605100
606455
  const toggleLabel = currentActive ? "Disable COHERE" : "Enable COHERE";
605101
- const toggleDetail = currentActive ? `Active — forwarding ${ctx3.config.model}` : "Join the distributed cognitive commons";
606456
+ const toggleDetail = currentActive ? `Active — forwarding ${ctx3.config.model} via current endpoint` : "Join the distributed cognitive commons";
605102
606457
  const items = [
605103
606458
  {
605104
606459
  key: "hdr-status",
@@ -605711,14 +607066,14 @@ async function handleVoiceMenu(ctx3, save2, hasLocal) {
605711
607066
  if (!jsonDrop.confirmed || !jsonDrop.path) {
605712
607067
  continue;
605713
607068
  }
605714
- const { basename: basename34, join: pathJoin } = await import("node:path");
607069
+ const { basename: basename35, join: pathJoin } = await import("node:path");
605715
607070
  const {
605716
607071
  copyFileSync: copyFileSync5,
605717
607072
  mkdirSync: mkdirSync84,
605718
607073
  existsSync: exists2
605719
607074
  } = await import("node:fs");
605720
607075
  const { homedir: homedir56 } = await import("node:os");
605721
- const modelName = basename34(onnxDrop.path, ".onnx").replace(
607076
+ const modelName = basename35(onnxDrop.path, ".onnx").replace(
605722
607077
  /[^a-zA-Z0-9_-]/g,
605723
607078
  "-"
605724
607079
  );
@@ -606105,7 +607460,7 @@ async function handleVoiceList(ctx3, focusFilename) {
606105
607460
  copyFileSync: cpf,
606106
607461
  mkdirSync: mkd
606107
607462
  } = __require("node:fs");
606108
- const { basename: basename34, join: pjoin } = __require("node:path");
607463
+ const { basename: basename35, join: pjoin } = __require("node:path");
606109
607464
  if (!fe(src2)) {
606110
607465
  renderError(`File not found: ${src2}`);
606111
607466
  helpers.render();
@@ -606118,7 +607473,7 @@ async function handleVoiceList(ctx3, focusFilename) {
606118
607473
  "clone-refs"
606119
607474
  );
606120
607475
  mkd(refsDir, { recursive: true });
606121
- const destName = basename34(src2);
607476
+ const destName = basename35(src2);
606122
607477
  const dest = pjoin(refsDir, destName);
606123
607478
  cpf(src2, dest);
606124
607479
  renderInfo(`Imported "${destName}" → ${dest}`);
@@ -606602,6 +607957,340 @@ async function handleEndpoint(arg, ctx3, local = false) {
606602
607957
  );
606603
607958
  }
606604
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
+ }
606605
608294
  async function handleSponsoredEndpoint(ctx3, local) {
606606
608295
  renderInfo("Scanning for sponsored inference endpoints...");
606607
608296
  const sponsors = [];
@@ -606707,6 +608396,8 @@ async function handleSponsoredEndpoint(ctx3, local) {
606707
608396
  peerId: ns.peerId || void 0,
606708
608397
  authKey: ns.authKey || "",
606709
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"),
606710
608401
  limits: {
606711
608402
  rpm: ns.limits?.maxRequestsPerMinute || 60,
606712
608403
  tpd: ns.limits?.maxTokensPerDay || 1e5
@@ -606771,6 +608462,8 @@ async function handleSponsoredEndpoint(ctx3, local) {
606771
608462
  peerId: ks.peerId || void 0,
606772
608463
  authKey: ks.authKey || "",
606773
608464
  models: Array.isArray(ks.models) ? ks.models : [],
608465
+ services: normalizeSponsorServices(ks),
608466
+ mediaCapabilities: normalizeSponsorServices(ks).filter((service) => service.kind !== "llm"),
606774
608467
  limits: {
606775
608468
  rpm: ks.limits?.maxRequestsPerMinute || 60,
606776
608469
  tpd: ks.limits?.maxTokensPerDay || 1e5
@@ -607063,14 +608756,14 @@ async function handlePeerEndpoint(peerId, authKey, ctx3, local) {
607063
608756
  if (models.length > 0) {
607064
608757
  try {
607065
608758
  const { writeFileSync: writeFileSync76, mkdirSync: mkdirSync84 } = await import("node:fs");
607066
- const { join: join154, dirname: dirname43 } = await import("node:path");
608759
+ const { join: join154, dirname: dirname44 } = await import("node:path");
607067
608760
  const cachePath = join154(
607068
608761
  ctx3.repoRoot || process.cwd(),
607069
608762
  ".omnius",
607070
608763
  "nexus",
607071
608764
  "peer-models-cache.json"
607072
608765
  );
607073
- mkdirSync84(dirname43(cachePath), { recursive: true });
608766
+ mkdirSync84(dirname44(cachePath), { recursive: true });
607074
608767
  writeFileSync76(
607075
608768
  cachePath,
607076
608769
  JSON.stringify(
@@ -608045,10 +609738,10 @@ async function handleUpdate(subcommand, ctx3) {
608045
609738
  try {
608046
609739
  const { createRequire: createRequire10 } = await import("node:module");
608047
609740
  const { fileURLToPath: fileURLToPath21 } = await import("node:url");
608048
- const { dirname: dirname43, join: join154 } = await import("node:path");
609741
+ const { dirname: dirname44, join: join154 } = await import("node:path");
608049
609742
  const { existsSync: existsSync137 } = await import("node:fs");
608050
609743
  const req2 = createRequire10(import.meta.url);
608051
- const thisDir = dirname43(fileURLToPath21(import.meta.url));
609744
+ const thisDir = dirname44(fileURLToPath21(import.meta.url));
608052
609745
  const candidates = [
608053
609746
  join154(thisDir, "..", "package.json"),
608054
609747
  join154(thisDir, "..", "..", "package.json"),
@@ -609892,7 +611585,7 @@ var init_commands = __esm({
609892
611585
 
609893
611586
  // packages/cli/src/tui/project-context.ts
609894
611587
  import { existsSync as existsSync108, readFileSync as readFileSync87, readdirSync as readdirSync36 } from "node:fs";
609895
- import { join as join121, basename as basename23 } from "node:path";
611588
+ import { join as join121, basename as basename24 } from "node:path";
609896
611589
  import { execSync as execSync54 } from "node:child_process";
609897
611590
  import { homedir as homedir42 } from "node:os";
609898
611591
  function getModelTier(modelName) {
@@ -609973,7 +611666,7 @@ function loadMemoryContext(repoRoot) {
609973
611666
  try {
609974
611667
  const raw = readFileSync87(join121(dir, file), "utf-8");
609975
611668
  const entries = JSON.parse(raw);
609976
- const topic = basename23(file, ".json");
611669
+ const topic = basename24(file, ".json");
609977
611670
  for (const [k, v] of Object.entries(entries)) {
609978
611671
  if (!v?.value) continue;
609979
611672
  all2.push({ topic, key: k, value: String(v.value), scope, ts: v.timestamp ?? "" });
@@ -610237,7 +611930,7 @@ __export(visual_identity_association_exports, {
610237
611930
  formatVisualIdentityAssociationContext: () => formatVisualIdentityAssociationContext,
610238
611931
  stageVisualIdentityAssertion: () => stageVisualIdentityAssertion
610239
611932
  });
610240
- import { basename as basename24 } from "node:path";
611933
+ import { basename as basename25 } from "node:path";
610241
611934
  function normalizePersonName(name10) {
610242
611935
  return name10.trim().toLowerCase().replace(/\s+/g, " ");
610243
611936
  }
@@ -610559,7 +612252,7 @@ async function associateVisualIdentityFromImage(options2) {
610559
612252
  relation: "same_person_candidate",
610560
612253
  confidence: match.confidence,
610561
612254
  assertedBy: { id: "visual_memory", displayName: "visual_memory", isBot: true },
610562
- note: `Prior enrolled visual-memory face match for ${basename24(options2.imagePath)}`
612255
+ note: `Prior enrolled visual-memory face match for ${basename25(options2.imagePath)}`
610563
612256
  }]
610564
612257
  });
610565
612258
  if (result2.episodeId) committedEpisodeIds.push(result2.episodeId);
@@ -610604,7 +612297,7 @@ async function associateVisualIdentityFromImage(options2) {
610604
612297
  relation: "depicts",
610605
612298
  confidence: item.confidence,
610606
612299
  assertedBy: item.sender || options2.sender,
610607
- 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)}`
610608
612301
  }]
610609
612302
  });
610610
612303
  if (result2.episodeId) committedEpisodeIds.push(result2.episodeId);
@@ -610662,7 +612355,7 @@ var init_visual_identity_association = __esm({
610662
612355
 
610663
612356
  // packages/cli/src/tui/identity-memory-tool.ts
610664
612357
  import { existsSync as existsSync109 } from "node:fs";
610665
- 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";
610666
612359
  function personKey2(name10) {
610667
612360
  return `person:${name10.trim().toLowerCase().replace(/\s+/g, " ")}`;
610668
612361
  }
@@ -610731,7 +612424,7 @@ async function resolveMediaFromArgs(args, opts) {
610731
612424
  path: path12,
610732
612425
  media,
610733
612426
  modality: inferModality(media),
610734
- label: basename25(path12)
612427
+ label: basename26(path12)
610735
612428
  };
610736
612429
  }
610737
612430
  function edgeDirection(edge, nodeId, otherText) {
@@ -610889,7 +612582,7 @@ var init_identity_memory_tool = __esm({
610889
612582
  } else if (shouldEnrollFace) {
610890
612583
  faceLine = "face enrollment: skipped because no resolved image path was available";
610891
612584
  }
610892
- 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";
610893
612586
  const output = [
610894
612587
  `Stored identity evidence for ${name10}.`,
610895
612588
  `relation: ${relation}`,
@@ -611830,7 +613523,7 @@ var init_banner = __esm({
611830
613523
 
611831
613524
  // packages/cli/src/tui/carousel-descriptors.ts
611832
613525
  import { existsSync as existsSync111, readFileSync as readFileSync89, writeFileSync as writeFileSync56, mkdirSync as mkdirSync62, readdirSync as readdirSync37 } from "node:fs";
611833
- import { join as join124, basename as basename26 } from "node:path";
613526
+ import { join as join124, basename as basename27 } from "node:path";
611834
613527
  function loadToolProfile(repoRoot) {
611835
613528
  const filePath = join124(repoRoot, OMNIUS_DIR, "context", TOOL_PROFILE_FILE);
611836
613529
  try {
@@ -611926,7 +613619,7 @@ function generateDescriptors(repoRoot) {
611926
613619
  extractFromSessions(repoRoot, tags);
611927
613620
  extractFromMemory(repoRoot, tags);
611928
613621
  extractFromToolProfile(profile, tags);
611929
- const repoName2 = basename26(repoRoot);
613622
+ const repoName2 = basename27(repoRoot);
611930
613623
  if (repoName2 && !tags.includes(repoName2)) {
611931
613624
  tags.push(repoName2);
611932
613625
  }
@@ -613106,7 +614799,7 @@ var init_edit_history = __esm({
613106
614799
 
613107
614800
  // packages/cli/src/tui/promptLoader.ts
613108
614801
  import { readFileSync as readFileSync90, existsSync as existsSync112 } from "node:fs";
613109
- import { join as join126, dirname as dirname35 } from "node:path";
614802
+ import { join as join126, dirname as dirname36 } from "node:path";
613110
614803
  import { fileURLToPath as fileURLToPath16 } from "node:url";
613111
614804
  function loadPrompt3(promptPath, vars) {
613112
614805
  let content = cache7.get(promptPath);
@@ -613126,7 +614819,7 @@ var init_promptLoader3 = __esm({
613126
614819
  "packages/cli/src/tui/promptLoader.ts"() {
613127
614820
  "use strict";
613128
614821
  __filename5 = fileURLToPath16(import.meta.url);
613129
- __dirname6 = dirname35(__filename5);
614822
+ __dirname6 = dirname36(__filename5);
613130
614823
  devPath2 = join126(__dirname6, "..", "..", "prompts");
613131
614824
  publishedPath2 = join126(__dirname6, "..", "prompts");
613132
614825
  PROMPTS_DIR3 = existsSync112(devPath2) ? devPath2 : publishedPath2;
@@ -613136,7 +614829,7 @@ var init_promptLoader3 = __esm({
613136
614829
 
613137
614830
  // packages/cli/src/tui/dream-engine.ts
613138
614831
  import { mkdirSync as mkdirSync64, writeFileSync as writeFileSync57, readFileSync as readFileSync91, existsSync as existsSync113, readdirSync as readdirSync38 } from "node:fs";
613139
- import { join as join127, basename as basename27 } from "node:path";
614832
+ import { join as join127, basename as basename28 } from "node:path";
613140
614833
  import { execSync as execSync55 } from "node:child_process";
613141
614834
  function setDreamWriteContent(fn) {
613142
614835
  _dreamWriteContent = fn;
@@ -613349,7 +615042,7 @@ var init_dream_engine = __esm({
613349
615042
  const rawPath = String(args["path"] ?? "");
613350
615043
  const content = String(args["content"] ?? "");
613351
615044
  if (!rawPath) return { success: false, output: "", error: "path is required", durationMs: Date.now() - start2 };
613352
- 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);
613353
615046
  if (!targetPath.startsWith(this.autoresearchDir)) {
613354
615047
  return { success: false, output: "", error: "Autoresearch mode: writes are confined to .omnius/autoresearch/", durationMs: Date.now() - start2 };
613355
615048
  }
@@ -613384,7 +615077,7 @@ var init_dream_engine = __esm({
613384
615077
  const rawPath = String(args["path"] ?? "");
613385
615078
  const oldStr = String(args["old_string"] ?? "");
613386
615079
  const newStr = String(args["new_string"] ?? "");
613387
- 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);
613388
615081
  if (!targetPath.startsWith(this.autoresearchDir)) {
613389
615082
  return { success: false, output: "", error: "Autoresearch mode: edits are confined to .omnius/autoresearch/", durationMs: Date.now() - start2 };
613390
615083
  }
@@ -613437,7 +615130,7 @@ var init_dream_engine = __esm({
613437
615130
  const rawPath = String(args["path"] ?? "");
613438
615131
  const content = String(args["content"] ?? "");
613439
615132
  if (!rawPath) return { success: false, output: "", error: "path is required", durationMs: Date.now() - start2 };
613440
- 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);
613441
615134
  if (!targetPath.startsWith(this.dreamsDir)) {
613442
615135
  return { success: false, output: "", error: "Dream mode: writes are confined to .omnius/dreams/", durationMs: Date.now() - start2 };
613443
615136
  }
@@ -613472,7 +615165,7 @@ var init_dream_engine = __esm({
613472
615165
  const rawPath = String(args["path"] ?? "");
613473
615166
  const oldStr = String(args["old_string"] ?? "");
613474
615167
  const newStr = String(args["new_string"] ?? "");
613475
- 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);
613476
615169
  if (!targetPath.startsWith(this.dreamsDir)) {
613477
615170
  return { success: false, output: "", error: "Dream mode: edits are confined to .omnius/dreams/", durationMs: Date.now() - start2 };
613478
615171
  }
@@ -615073,7 +616766,7 @@ var init_bless_engine = __esm({
615073
616766
 
615074
616767
  // packages/cli/src/tui/dmn-engine.ts
615075
616768
  import { existsSync as existsSync114, readFileSync as readFileSync92, writeFileSync as writeFileSync58, mkdirSync as mkdirSync65, readdirSync as readdirSync39, unlinkSync as unlinkSync21 } from "node:fs";
615076
- import { join as join128, basename as basename28 } from "node:path";
616769
+ import { join as join128, basename as basename29 } from "node:path";
615077
616770
  function buildDMNGatherPrompt(recentTaskSummaries, dueReminders, attentionItems, memoryTopics, capabilities, competence, reflectionBuffer) {
615078
616771
  const competenceReport = competence.length > 0 ? competence.map((c8) => {
615079
616772
  const rate = c8.attempts > 0 ? Math.round(c8.successes / c8.attempts * 100) : 0;
@@ -615824,7 +617517,7 @@ OUTPUT: Call task_complete with JSON:
615824
617517
  try {
615825
617518
  const files = readdirSync39(dir).filter((f2) => f2.endsWith(".json"));
615826
617519
  for (const f2 of files) {
615827
- const topic = basename28(f2, ".json");
617520
+ const topic = basename29(f2, ".json");
615828
617521
  if (!topics.includes(topic)) topics.push(topic);
615829
617522
  }
615830
617523
  } catch {
@@ -615878,7 +617571,7 @@ OUTPUT: Call task_complete with JSON:
615878
617571
 
615879
617572
  // packages/cli/src/tui/snr-engine.ts
615880
617573
  import { existsSync as existsSync115, readdirSync as readdirSync40, readFileSync as readFileSync93 } from "node:fs";
615881
- import { join as join129, basename as basename29 } from "node:path";
617574
+ import { join as join129, basename as basename30 } from "node:path";
615882
617575
  function computeDPrime(signalScores, noiseScores) {
615883
617576
  if (signalScores.length === 0 || noiseScores.length === 0) return 0;
615884
617577
  const mean = (arr) => arr.reduce((s2, v) => s2 + v, 0) / arr.length;
@@ -616172,7 +617865,7 @@ Call task_complete with the JSON array when done.`,
616172
617865
  try {
616173
617866
  const files = readdirSync40(dir).filter((f2) => f2.endsWith(".json"));
616174
617867
  for (const f2 of files) {
616175
- const topic = basename29(f2, ".json");
617868
+ const topic = basename30(f2, ".json");
616176
617869
  if (topics.length > 0 && !topics.includes(topic)) continue;
616177
617870
  try {
616178
617871
  const data = JSON.parse(readFileSync93(join129(dir, f2), "utf-8"));
@@ -617655,8 +619348,8 @@ import {
617655
619348
  } from "node:fs";
617656
619349
  import { mkdir as mkdir19 } from "node:fs/promises";
617657
619350
  import {
617658
- basename as basename30,
617659
- dirname as dirname36,
619351
+ basename as basename31,
619352
+ dirname as dirname37,
617660
619353
  extname as extname15,
617661
619354
  isAbsolute as isAbsolute7,
617662
619355
  join as join130,
@@ -617820,7 +619513,7 @@ function scopedTool(base3, root, mode) {
617820
619513
  if (mode === "edit" && !existsSync116(guarded.path.abs)) {
617821
619514
  const materialized = materializeTelegramCreativeArtifactForSend(rootAbs, guarded.path.rel);
617822
619515
  if (!materialized.ok) return denied(materialized.error);
617823
- mkdirSync66(dirname36(guarded.path.abs), { recursive: true });
619516
+ mkdirSync66(dirname37(guarded.path.abs), { recursive: true });
617824
619517
  writeFileSync59(guarded.path.abs, readFileSync94(materialized.path));
617825
619518
  materialized.cleanup?.();
617826
619519
  restoredEditPath = guarded.path.abs;
@@ -617889,7 +619582,7 @@ function guardPath(root, rawPath) {
617889
619582
  error: `Path escapes the public creative workspace. Use a relative path under ${rootAbs}.`
617890
619583
  };
617891
619584
  }
617892
- if (basename30(abs) === MANIFEST_FILE) {
619585
+ if (basename31(abs) === MANIFEST_FILE) {
617893
619586
  return { ok: false, error: "The creative workspace manifest is internal and cannot be edited." };
617894
619587
  }
617895
619588
  return { ok: true, path: { abs, rel } };
@@ -617981,7 +619674,7 @@ function rememberCreated(root, absPath) {
617981
619674
  manifest.objects[rel] = {
617982
619675
  logicalRel: rel,
617983
619676
  storedRel,
617984
- originalName: basename30(guarded.path.abs),
619677
+ originalName: basename31(guarded.path.abs),
617985
619678
  prefixBytes: prefix.length,
617986
619679
  encrypted: true,
617987
619680
  key: key.toString("base64"),
@@ -618032,7 +619725,7 @@ function materializeTelegramCreativeArtifactForSend(root, rawPath) {
618032
619725
  }
618033
619726
  const stageDir = join130(rootAbs, SEND_DIR, `${Date.now()}-${randomBytes23(8).toString("hex")}`);
618034
619727
  mkdirSync66(stageDir, { recursive: true });
618035
- const staged = join130(stageDir, object.originalName || basename30(rel));
619728
+ const staged = join130(stageDir, object.originalName || basename31(rel));
618036
619729
  writeFileSync59(staged, payload);
618037
619730
  return {
618038
619731
  ok: true,
@@ -618200,7 +619893,7 @@ var init_telegram_creative_tools = __esm({
618200
619893
  }
618201
619894
  let result;
618202
619895
  try {
618203
- await mkdir19(dirname36(guarded.path.abs), { recursive: true });
619896
+ await mkdir19(dirname37(guarded.path.abs), { recursive: true });
618204
619897
  const tts = new TtsGenerateTool();
618205
619898
  result = await tts.execute({
618206
619899
  text,
@@ -618702,7 +620395,7 @@ var init_soul_observations = __esm({
618702
620395
  // packages/cli/src/tui/telegram-channel-dmn.ts
618703
620396
  import { existsSync as existsSync117, mkdirSync as mkdirSync67, readdirSync as readdirSync41, readFileSync as readFileSync95, writeFileSync as writeFileSync60 } from "node:fs";
618704
620397
  import { join as join131 } from "node:path";
618705
- import { createHash as createHash24 } from "node:crypto";
620398
+ import { createHash as createHash26 } from "node:crypto";
618706
620399
  function safeFilePart(value2) {
618707
620400
  return value2.replace(/[^A-Za-z0-9_.-]+/g, "_").slice(0, 80) || "telegram";
618708
620401
  }
@@ -618710,7 +620403,7 @@ function daydreamRoot(repoRoot) {
618710
620403
  return join131(repoRoot, ".omnius", "telegram-daydreams");
618711
620404
  }
618712
620405
  function sessionDir(repoRoot, sessionKey) {
618713
- const hash = createHash24("sha1").update(sessionKey).digest("hex").slice(0, 20);
620406
+ const hash = createHash26("sha1").update(sessionKey).digest("hex").slice(0, 20);
618714
620407
  return join131(daydreamRoot(repoRoot), safeFilePart(hash));
618715
620408
  }
618716
620409
  function compactLine2(value2, max = 220) {
@@ -618795,7 +620488,7 @@ function buildReplyOpportunities(input, openQuestions) {
618795
620488
  return opportunities;
618796
620489
  }
618797
620490
  function daydreamOpportunityId(input, trigger) {
618798
- 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);
618799
620492
  }
618800
620493
  function clamp019(value2) {
618801
620494
  if (!Number.isFinite(value2)) return 0;
@@ -619115,7 +620808,7 @@ function buildTelegramChannelDaydream(input, corpus, extraction, extractionCommi
619115
620808
  const seed = `${input.sessionKey}:${input.generatedAtMs}:${input.history.length}`;
619116
620809
  return {
619117
620810
  version: 3,
619118
- id: createHash24("sha1").update(seed).digest("hex").slice(0, 16),
620811
+ id: createHash26("sha1").update(seed).digest("hex").slice(0, 16),
619119
620812
  sessionKey: input.sessionKey,
619120
620813
  chatId: input.chatId,
619121
620814
  chatTitle: input.chatTitle,
@@ -619328,12 +621021,12 @@ var init_telegram_channel_dmn = __esm({
619328
621021
  });
619329
621022
 
619330
621023
  // packages/cli/src/tui/telegram-reflection-corpus.ts
619331
- import { createHash as createHash25 } from "node:crypto";
621024
+ import { createHash as createHash27 } from "node:crypto";
619332
621025
  function telegramReflectionMemoryDbPaths(repoRoot) {
619333
621026
  return omniusMemoryDbPaths(repoRoot);
619334
621027
  }
619335
621028
  function stableHash2(value2, length4 = 16) {
619336
- return createHash25("sha1").update(value2).digest("hex").slice(0, length4);
621029
+ return createHash27("sha1").update(value2).digest("hex").slice(0, length4);
619337
621030
  }
619338
621031
  function clean3(value2) {
619339
621032
  return String(value2 ?? "").replace(/\s+/g, " ").trim();
@@ -620063,7 +621756,7 @@ var init_telegram_reflection_extraction = __esm({
620063
621756
  });
620064
621757
 
620065
621758
  // packages/cli/src/tui/telegram-social-state-types.ts
620066
- import { createHash as createHash26 } from "node:crypto";
621759
+ import { createHash as createHash28 } from "node:crypto";
620067
621760
  function telegramSocialActorKey(actor) {
620068
621761
  if (!actor) return "unknown";
620069
621762
  if (typeof actor.userId === "number") return `user:${actor.userId}`;
@@ -620087,7 +621780,7 @@ function appendUnique(items, value2, max) {
620087
621780
  return next.slice(-max);
620088
621781
  }
620089
621782
  function hashTelegramSocialId(parts) {
620090
- 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);
620091
621784
  }
620092
621785
  function cleanUsername(value2) {
620093
621786
  if (typeof value2 !== "string") return void 0;
@@ -620865,10 +622558,10 @@ var init_vision_ingress = __esm({
620865
622558
 
620866
622559
  // packages/cli/src/tui/telegram-bridge.ts
620867
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";
620868
- 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";
620869
622562
  import { homedir as homedir43 } from "node:os";
620870
622563
  import { writeFile as writeFileAsync } from "node:fs/promises";
620871
- import { createHash as createHash27, randomBytes as randomBytes24, randomInt } from "node:crypto";
622564
+ import { createHash as createHash29, randomBytes as randomBytes24, randomInt } from "node:crypto";
620872
622565
  function cleanTelegramDecisionNote(value2, maxLength = 260) {
620873
622566
  if (typeof value2 !== "string") return void 0;
620874
622567
  const clean5 = stripTelegramHiddenThinking(value2).replace(/\s+/g, " ").trim();
@@ -621807,7 +623500,7 @@ function buildTelegramRuntimeContext(now = /* @__PURE__ */ new Date(), repoRoot)
621807
623500
  ].filter(Boolean).join("\n");
621808
623501
  }
621809
623502
  function telegramSessionIdFromKey(sessionKey) {
621810
- return `telegram-${createHash27("sha1").update(sessionKey).digest("hex").slice(0, 16)}`;
623503
+ return `telegram-${createHash29("sha1").update(sessionKey).digest("hex").slice(0, 16)}`;
621811
623504
  }
621812
623505
  function normalizeTelegramSubAgentLimit(value2) {
621813
623506
  const parsed = typeof value2 === "number" ? value2 : typeof value2 === "string" && value2.trim() ? Number(value2.trim()) : TELEGRAM_SUB_AGENT_DEFAULT_LIMIT;
@@ -623422,7 +625115,7 @@ External acquisition contract:
623422
625115
  return !!this.adminAuthChallenge && this.adminAuthChallenge.expiresAtMs > Date.now();
623423
625116
  }
623424
625117
  hashAdminAuthCode(code8) {
623425
- return createHash27("sha256").update(`omnius-telegram-admin:${code8.trim()}`).digest("hex");
625118
+ return createHash29("sha256").update(`omnius-telegram-admin:${code8.trim()}`).digest("hex");
623426
625119
  }
623427
625120
  viewIdForMessage(msg) {
623428
625121
  return `telegram-${this.sessionKeyForMessage(msg).replace(/[^A-Za-z0-9_-]/g, "-")}`;
@@ -624345,11 +626038,11 @@ ${mediaContext}` : ""
624345
626038
  return payload;
624346
626039
  }
624347
626040
  telegramConversationPath(sessionKey) {
624348
- const safe = createHash27("sha1").update(sessionKey).digest("hex").slice(0, 20);
626041
+ const safe = createHash29("sha1").update(sessionKey).digest("hex").slice(0, 20);
624349
626042
  return join133(this.telegramConversationDir, `${safe}.json`);
624350
626043
  }
624351
626044
  telegramConversationLedgerPath(sessionKey) {
624352
- const safe = createHash27("sha1").update(sessionKey).digest("hex").slice(0, 20);
626045
+ const safe = createHash29("sha1").update(sessionKey).digest("hex").slice(0, 20);
624353
626046
  return join133(this.telegramConversationDir, `${safe}.events.jsonl`);
624354
626047
  }
624355
626048
  telegramDb() {
@@ -624577,7 +626270,7 @@ ${mediaContext}` : ""
624577
626270
  users,
624578
626271
  relationships: Array.isArray(raw.relationships) ? raw.relationships.slice(0, TELEGRAM_ASSOCIATIVE_RELATION_LIMIT).map((fact) => this.normalizeTelegramAssociativeFact(fact)) : [],
624579
626272
  actions: Array.isArray(raw.actions) ? raw.actions.slice(-TELEGRAM_ASSOCIATIVE_ACTION_LIMIT).map((action) => ({
624580
- 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)),
624581
626274
  ts: typeof action.ts === "number" ? action.ts : Date.now(),
624582
626275
  role: action.role === "assistant" ? "assistant" : "user",
624583
626276
  speaker: String(action.speaker || "unknown"),
@@ -624594,7 +626287,7 @@ ${mediaContext}` : ""
624594
626287
  const text = String(raw.text || "").trim();
624595
626288
  const now = Date.now();
624596
626289
  return {
624597
- 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)),
624598
626291
  text,
624599
626292
  tags: Array.isArray(raw.tags) ? raw.tags.map(String).slice(0, 16) : [],
624600
626293
  speakers: Array.isArray(raw.speakers) ? raw.speakers.map(String).slice(0, 16) : [],
@@ -624796,7 +626489,7 @@ ${mediaContext}` : ""
624796
626489
  }
624797
626490
  telegramHistoryBackfillMessageId(sessionKey, entry, index) {
624798
626491
  if (typeof entry.messageId === "number" && Number.isFinite(entry.messageId)) return entry.messageId;
624799
- 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);
624800
626493
  return -Number.parseInt(digest3, 16);
624801
626494
  }
624802
626495
  backfillTelegramLoadedHistory(sessionKey, history) {
@@ -625567,7 +627260,7 @@ ${mediaContext}` : ""
625567
627260
  }
625568
627261
  const matchingEntry = mediaEntries.find((entry) => {
625569
627262
  if (resolve47(entry.localPath) === resolve47(raw)) return true;
625570
- if (basename31(entry.localPath) === raw) return true;
627263
+ if (basename32(entry.localPath) === raw) return true;
625571
627264
  if (entry.fileUniqueId === raw || entry.fileId === raw) return true;
625572
627265
  if (entry.messageId && String(entry.messageId) === raw) return true;
625573
627266
  if (entry.messageId && `message_id:${entry.messageId}` === raw.toLowerCase()) return true;
@@ -625604,7 +627297,7 @@ ${mediaContext}` : ""
625604
627297
  }
625605
627298
  return entries.find((entry2) => {
625606
627299
  if (resolve47(entry2.localPath) === resolve47(ref)) return true;
625607
- if (basename31(entry2.localPath) === ref) return true;
627300
+ if (basename32(entry2.localPath) === ref) return true;
625608
627301
  if (entry2.fileUniqueId === ref || entry2.fileId === ref) return true;
625609
627302
  if (entry2.messageId && String(entry2.messageId) === ref) return true;
625610
627303
  return false;
@@ -625632,7 +627325,7 @@ ${mediaContext}` : ""
625632
627325
  caption: entry.caption
625633
627326
  },
625634
627327
  modality,
625635
- label: `Telegram message_id ${entry.messageId || "unknown"} ${basename31(entry.localPath)}`,
627328
+ label: `Telegram message_id ${entry.messageId || "unknown"} ${basename32(entry.localPath)}`,
625636
627329
  extractedContent: entry.extractedContent
625637
627330
  };
625638
627331
  }
@@ -625689,7 +627382,7 @@ ${mediaContext}` : ""
625689
627382
  const now = entry.ts ?? Date.now();
625690
627383
  memory.updatedAt = now;
625691
627384
  const speaker = telegramHistorySpeaker(entry);
625692
- 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);
625693
627386
  if (!memory.actions.some((action) => action.id === actionId)) {
625694
627387
  memory.actions.push({
625695
627388
  id: actionId,
@@ -625811,7 +627504,7 @@ ${mediaContext}` : ""
625811
627504
  let fact = facts.find((item) => item.text.toLowerCase() === key);
625812
627505
  if (!fact) {
625813
627506
  fact = {
625814
- 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),
625815
627508
  text: clean5,
625816
627509
  tags: telegramMemoryTags(clean5, entry.mediaSummary),
625817
627510
  speakers: [],
@@ -625866,7 +627559,7 @@ ${mediaContext}` : ""
625866
627559
  const titleTags = tags.slice(0, 4);
625867
627560
  const title = titleTags.length > 0 ? `${speaker} / ${titleTags.join(" ")}` : `${speaker} / conversation`;
625868
627561
  const card = {
625869
- 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),
625870
627563
  title,
625871
627564
  notes: [],
625872
627565
  tags: [],
@@ -626583,8 +628276,8 @@ ${cardLines.join("\n")}`);
626583
628276
  const caption = entry.caption ? ` caption=${telegramContextJsonString(entry.caption, 120)}` : "";
626584
628277
  const extracted = entry.extractedContent ? `
626585
628278
  extracted=${telegramContextJsonString(entry.extractedContent.replace(/\s+/g, " "), 220)}` : "";
626586
- const alias = entry.messageId ? `message_id:${entry.messageId}` : basename31(entry.localPath);
626587
- 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}`;
626588
628281
  });
626589
628282
  sections.push([
626590
628283
  "### Recent Chat Media",
@@ -628008,7 +629701,7 @@ ${list}` : "No shared group target is currently known for this sender. Ask in th
628008
629701
  }
628009
629702
  telegramRunnerStateDir(sessionKey) {
628010
629703
  if (!this.repoRoot) return void 0;
628011
- const safe = createHash27("sha1").update(sessionKey).digest("hex").slice(0, 20);
629704
+ const safe = createHash29("sha1").update(sessionKey).digest("hex").slice(0, 20);
628012
629705
  return join133(this.repoRoot, ".omnius", "telegram-runner-state", safe);
628013
629706
  }
628014
629707
  buildTelegramAdminOverviewContext(currentSessionKey) {
@@ -631459,12 +633152,12 @@ Scoped workspace: ${scopedRoot}`,
631459
633152
  return { success: true, output: `No recent ${kind} media is available in this Telegram chat scope.`, durationMs: performance.now() - start2 };
631460
633153
  }
631461
633154
  const lines = entries.map((entry, index) => {
631462
- const pathAlias = entry.messageId ? `message_id:${entry.messageId}` : basename31(entry.localPath);
633155
+ const pathAlias = entry.messageId ? `message_id:${entry.messageId}` : basename32(entry.localPath);
631463
633156
  const parts = [
631464
633157
  `${index + 1}. message_id ${entry.messageId || "unknown"}`,
631465
633158
  currentMsg?.replyToMessageId === entry.messageId ? "replied-to" : "",
631466
633159
  telegramCachedMediaIsImage(entry) ? "image" : telegramCachedMediaIsPdf(entry) ? "pdf" : telegramCachedMediaIsAudio(entry) ? "audio" : telegramCachedMediaIsVideo(entry) ? "video" : entry.mediaType,
631467
- `file=${basename31(entry.localPath)}`,
633160
+ `file=${basename32(entry.localPath)}`,
631468
633161
  `path_alias=${pathAlias}`,
631469
633162
  entry.caption ? `caption=${telegramContextJsonString(entry.caption, 140)}` : ""
631470
633163
  ].filter(Boolean);
@@ -631591,8 +633284,8 @@ Scoped workspace: ${scopedRoot}`,
631591
633284
  if (bridge.telegramFileSendAlreadyDeliveredForMessage(currentMsg, sendFingerprint)) {
631592
633285
  return {
631593
633286
  success: true,
631594
- output: `Telegram file already sent in this turn: ${basename31(file.path)} as ${kind} to ${String(target.chatId)}`,
631595
- 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.`,
631596
633289
  durationMs: performance.now() - start2,
631597
633290
  mutated: false,
631598
633291
  mutatedFiles: []
@@ -631609,8 +633302,8 @@ Scoped workspace: ${scopedRoot}`,
631609
633302
  bridge.rememberTelegramDeliveredArtifactForMessage(currentMsg, ledgerPath);
631610
633303
  return {
631611
633304
  success: true,
631612
- output: `Sent Telegram file: ${basename31(file.path)} as ${kind} to ${String(target.chatId)}${messageId ? ` (message_id ${messageId})` : ""}`,
631613
- 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}.`,
631614
633307
  durationMs: performance.now() - start2,
631615
633308
  mutated: false,
631616
633309
  mutatedFiles: []
@@ -632095,7 +633788,7 @@ ${text}`.trim());
632095
633788
  if (!existsSync119(media.value)) throw new Error(`File does not exist: ${media.value}`);
632096
633789
  const buffer2 = readFileSync97(media.value);
632097
633790
  const boundary = `----omnius-media-${Date.now()}-${Math.random().toString(36).slice(2)}`;
632098
- const filename = basename31(media.value);
633791
+ const filename = basename32(media.value);
632099
633792
  const contentType = mimeForPath(media.value, media.kind);
632100
633793
  const parts = [];
632101
633794
  const addField = (name10, value2) => {
@@ -632335,7 +634028,7 @@ Content-Type: ${contentType}\r
632335
634028
  continue;
632336
634029
  }
632337
634030
  const buffer2 = readFileSync97(pathOrFileId);
632338
- const filename = basename31(pathOrFileId);
634031
+ const filename = basename32(pathOrFileId);
632339
634032
  parts.push(Buffer.from(`--${boundary}\r
632340
634033
  `));
632341
634034
  parts.push(Buffer.from(
@@ -633546,7 +635239,7 @@ __export(projects_exports, {
633546
635239
  });
633547
635240
  import { readFileSync as readFileSync99, writeFileSync as writeFileSync64, mkdirSync as mkdirSync70, existsSync as existsSync121, statSync as statSync44, renameSync as renameSync7 } from "node:fs";
633548
635241
  import { homedir as homedir45 } from "node:os";
633549
- 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";
633550
635243
  import { randomUUID as randomUUID15 } from "node:crypto";
633551
635244
  function readAll2() {
633552
635245
  try {
@@ -633594,7 +635287,7 @@ function registerProject(root, pid) {
633594
635287
  } else {
633595
635288
  entry = {
633596
635289
  root: canonical,
633597
- name: basename32(canonical) || canonical,
635290
+ name: basename33(canonical) || canonical,
633598
635291
  firstSeen: now,
633599
635292
  lastSeen: now,
633600
635293
  pid: pid ?? null,
@@ -634534,14 +636227,14 @@ var init_access_policy = __esm({
634534
636227
  });
634535
636228
 
634536
636229
  // packages/cli/src/api/project-preferences.ts
634537
- import { createHash as createHash28 } from "node:crypto";
636230
+ import { createHash as createHash30 } from "node:crypto";
634538
636231
  import { existsSync as existsSync122, mkdirSync as mkdirSync71, readFileSync as readFileSync100, renameSync as renameSync8, writeFileSync as writeFileSync65, unlinkSync as unlinkSync26 } from "node:fs";
634539
636232
  import { homedir as homedir46 } from "node:os";
634540
636233
  import { join as join136, resolve as resolve49 } from "node:path";
634541
636234
  import { randomUUID as randomUUID16 } from "node:crypto";
634542
636235
  function projectKey(root) {
634543
636236
  const canonical = resolve49(root);
634544
- return createHash28("sha256").update(canonical).digest("hex").slice(0, 16);
636237
+ return createHash30("sha256").update(canonical).digest("hex").slice(0, 16);
634545
636238
  }
634546
636239
  function projectDir(root) {
634547
636240
  return join136(PROJECTS_DIR, projectKey(root));
@@ -635594,7 +637287,7 @@ var init_audit_log = __esm({
635594
637287
  // packages/cli/src/api/disk-task-output.ts
635595
637288
  import { open } from "node:fs/promises";
635596
637289
  import { existsSync as existsSync124, mkdirSync as mkdirSync73, statSync as statSync45 } from "node:fs";
635597
- import { dirname as dirname38 } from "node:path";
637290
+ import { dirname as dirname39 } from "node:path";
635598
637291
  import * as fsConstants from "node:constants";
635599
637292
  var O_NOFOLLOW2, O_APPEND2, O_CREAT2, O_WRONLY2, OPEN_FLAGS_WRITE, OPEN_MODE, DiskTaskOutput;
635600
637293
  var init_disk_task_output = __esm({
@@ -635613,7 +637306,7 @@ var init_disk_task_output = __esm({
635613
637306
  fileSize = 0;
635614
637307
  constructor(outputPath3) {
635615
637308
  this.path = outputPath3;
635616
- mkdirSync73(dirname38(outputPath3), { recursive: true });
637309
+ mkdirSync73(dirname39(outputPath3), { recursive: true });
635617
637310
  }
635618
637311
  /** Queue content for async append. Non-blocking. */
635619
637312
  append(chunk) {
@@ -635719,7 +637412,7 @@ var init_disk_task_output = __esm({
635719
637412
  });
635720
637413
 
635721
637414
  // packages/cli/src/api/http.ts
635722
- import { createHash as createHash29 } from "node:crypto";
637415
+ import { createHash as createHash31 } from "node:crypto";
635723
637416
  function problemDetails(opts) {
635724
637417
  const p2 = {
635725
637418
  type: opts.type ?? "about:blank",
@@ -635782,7 +637475,7 @@ function paginated(items, page2, total) {
635782
637475
  }
635783
637476
  function computeEtag(payload) {
635784
637477
  const json = typeof payload === "string" ? payload : JSON.stringify(payload);
635785
- const hash = createHash29("sha1").update(json).digest("hex").slice(0, 16);
637478
+ const hash = createHash31("sha1").update(json).digest("hex").slice(0, 16);
635786
637479
  return `W/"${hash}"`;
635787
637480
  }
635788
637481
  function checkNotModified(req2, res, etag) {
@@ -649726,7 +651419,7 @@ var init_profiles = __esm({
649726
651419
  // packages/cli/src/docker.ts
649727
651420
  import { execSync as execSync57, spawn as spawn31 } from "node:child_process";
649728
651421
  import { existsSync as existsSync132, mkdirSync as mkdirSync78, writeFileSync as writeFileSync70 } from "node:fs";
649729
- 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";
649730
651423
  import { homedir as homedir52 } from "node:os";
649731
651424
  import { fileURLToPath as fileURLToPath17 } from "node:url";
649732
651425
  function getDockerDir() {
@@ -649737,7 +651430,7 @@ function getDockerDir() {
649737
651430
  } catch {
649738
651431
  }
649739
651432
  try {
649740
- const thisDir = dirname39(fileURLToPath17(import.meta.url));
651433
+ const thisDir = dirname40(fileURLToPath17(import.meta.url));
649741
651434
  return join145(thisDir, "..", "..", "..", "docker");
649742
651435
  } catch {
649743
651436
  }
@@ -650024,7 +651717,7 @@ __export(embedding_workers_exports, {
650024
651717
  startEmbeddingWorkers: () => startEmbeddingWorkers,
650025
651718
  stopEmbeddingWorkers: () => stopEmbeddingWorkers
650026
651719
  });
650027
- import { basename as basename33, join as join146 } from "node:path";
651720
+ import { basename as basename34, join as join146 } from "node:path";
650028
651721
  function startEmbeddingWorkers(opts) {
650029
651722
  if (_running) return;
650030
651723
  _running = true;
@@ -650090,7 +651783,7 @@ async function runEmbeddingTask(modality, episodeId, taskId, opts) {
650090
651783
  try {
650091
651784
  if (!_aligner) {
650092
651785
  const stateRoot = process.env.OMNIUS_DIR || process.cwd();
650093
- const omniusDir = basename33(stateRoot) === ".omnius" ? stateRoot : join146(stateRoot, ".omnius");
651786
+ const omniusDir = basename34(stateRoot) === ".omnius" ? stateRoot : join146(stateRoot, ".omnius");
650094
651787
  const memDir = join146(omniusDir, "memory");
650095
651788
  _aligner = new EmbeddingAligner(
650096
651789
  `${modality}-${emb.length}`,
@@ -650206,12 +651899,12 @@ import * as http5 from "node:http";
650206
651899
  import * as https3 from "node:https";
650207
651900
  import { createRequire as createRequire7 } from "node:module";
650208
651901
  import { fileURLToPath as fileURLToPath18 } from "node:url";
650209
- 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";
650210
651903
  import { homedir as homedir53 } from "node:os";
650211
651904
  import { spawn as spawn32, execSync as execSync58 } from "node:child_process";
650212
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";
650213
651906
  import { randomBytes as randomBytes27, randomUUID as randomUUID17 } from "node:crypto";
650214
- import { createHash as createHash31 } from "node:crypto";
651907
+ import { createHash as createHash33 } from "node:crypto";
650215
651908
  function memoryDbPaths3(baseDir = process.cwd()) {
650216
651909
  const dir = join147(baseDir, ".omnius");
650217
651910
  return {
@@ -650222,7 +651915,7 @@ function memoryDbPaths3(baseDir = process.cwd()) {
650222
651915
  }
650223
651916
  function getVersion3() {
650224
651917
  try {
650225
- const thisDir = dirname40(fileURLToPath18(import.meta.url));
651918
+ const thisDir = dirname41(fileURLToPath18(import.meta.url));
650226
651919
  const candidates = [
650227
651920
  join147(thisDir, "..", "package.json"),
650228
651921
  join147(thisDir, "..", "..", "package.json"),
@@ -652838,7 +654531,7 @@ async function handleV1Update(req2, res, requestId) {
652838
654531
  }, { subject: req2._authUser ?? "anonymous" });
652839
654532
  const fs11 = require4("node:fs");
652840
654533
  const nodeBin = process.execPath;
652841
- const nodeDir = dirname40(nodeBin);
654534
+ const nodeDir = dirname41(nodeBin);
652842
654535
  const { execSync: es } = require4("node:child_process");
652843
654536
  const isWin2 = process.platform === "win32";
652844
654537
  let npmBin = "";
@@ -652853,7 +654546,7 @@ async function handleV1Update(req2, res, requestId) {
652853
654546
  const dir = join147(homedir53(), ".omnius");
652854
654547
  fs11.mkdirSync(dir, { recursive: true });
652855
654548
  const logFd = fs11.openSync(logPath3, "w");
652856
- const npmPrefix = dirname40(nodeDir);
654549
+ const npmPrefix = dirname41(nodeDir);
652857
654550
  let globalBinDir = "";
652858
654551
  try {
652859
654552
  if (isWin2) {
@@ -656133,7 +657826,7 @@ function listScheduledTasks() {
656133
657826
  const schedule = String(t2?.schedule || t2?.cron || t2?.when || "");
656134
657827
  const enabled2 = typeof t2?.enabled === "boolean" ? t2.enabled : true;
656135
657828
  const realId = typeof t2?.id === "string" && t2.id ? t2.id : null;
656136
- 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);
656137
657830
  const uid = realId || fallbackId;
656138
657831
  const key = `${uid}`;
656139
657832
  if (seen.has(key)) return;
@@ -656250,8 +657943,8 @@ function deleteScheduledById(id) {
656250
657943
  if (id) candidates.push(id);
656251
657944
  if (typeof entry?.id === "string" && entry.id && !candidates.includes(entry.id)) candidates.push(entry.id);
656252
657945
  try {
656253
- const { createHash: createHash32 } = require4("node:crypto");
656254
- 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);
656255
657948
  if (!candidates.includes(fallback)) candidates.push(fallback);
656256
657949
  } catch {
656257
657950
  }
@@ -658027,7 +659720,7 @@ var init_clipboard_media = __esm({
658027
659720
 
658028
659721
  // packages/cli/src/tui/interactive.ts
658029
659722
  import { cwd } from "node:process";
658030
- 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";
658031
659724
  import { createRequire as createRequire8 } from "node:module";
658032
659725
  import { fileURLToPath as fileURLToPath19 } from "node:url";
658033
659726
  import {
@@ -658054,7 +659747,7 @@ function formatTimeAgo2(date) {
658054
659747
  function getVersion4() {
658055
659748
  try {
658056
659749
  const require5 = createRequire8(import.meta.url);
658057
- const thisDir = dirname41(fileURLToPath19(import.meta.url));
659750
+ const thisDir = dirname42(fileURLToPath19(import.meta.url));
658058
659751
  const candidates = [
658059
659752
  join149(thisDir, "..", "package.json"),
658060
659753
  join149(thisDir, "..", "..", "package.json"),
@@ -663757,7 +665450,7 @@ The user pasted a clipboard image saved at ${relPath}. Use the OCR, vision analy
663757
665450
  try {
663758
665451
  if (!commandCtx.isExposeActive?.()) {
663759
665452
  writeContent(
663760
- () => renderInfo("COHERE: exposing local inference to mesh...")
665453
+ () => renderInfo("COHERE: exposing current endpoint to mesh...")
663761
665454
  );
663762
665455
  await commandCtx.exposeStart?.("passthrough");
663763
665456
  }
@@ -666225,13 +667918,13 @@ NEW TASK: ${fullInput}`;
666225
667918
  writeContent(() => renderError(errMsg));
666226
667919
  if (failureStore) {
666227
667920
  try {
666228
- const { createHash: createHash32 } = await import("node:crypto");
667921
+ const { createHash: createHash34 } = await import("node:crypto");
666229
667922
  failureStore.insert({
666230
667923
  taskId: "",
666231
667924
  sessionId: `${Date.now()}`,
666232
667925
  repoRoot,
666233
667926
  failureType: "runtime-error",
666234
- 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),
666235
667928
  filePath: null,
666236
667929
  errorMessage: errMsg.slice(0, 500),
666237
667930
  context: null,
@@ -668016,7 +669709,7 @@ init_typed_node_events();
668016
669709
  import { createRequire as createRequire9 } from "node:module";
668017
669710
  import { parseArgs as nodeParseArgs2 } from "node:util";
668018
669711
  import { fileURLToPath as fileURLToPath20 } from "node:url";
668019
- import { dirname as dirname42, join as join153 } from "node:path";
669712
+ import { dirname as dirname43, join as join153 } from "node:path";
668020
669713
 
668021
669714
  // packages/cli/src/cli.ts
668022
669715
  init_typed_node_events();
@@ -668164,7 +669857,7 @@ try {
668164
669857
  function getVersion5() {
668165
669858
  try {
668166
669859
  const require5 = createRequire9(import.meta.url);
668167
- const pkgPath = join153(dirname42(fileURLToPath20(import.meta.url)), "..", "package.json");
669860
+ const pkgPath = join153(dirname43(fileURLToPath20(import.meta.url)), "..", "package.json");
668168
669861
  const pkg = require5(pkgPath);
668169
669862
  return pkg.version;
668170
669863
  } catch {