Spaces:
Running
Running
Update core/commands.mjs
Browse files- core/commands.mjs +5 -5
core/commands.mjs
CHANGED
|
@@ -45,18 +45,18 @@ export const APCommands = {
|
|
| 45 |
const controller=new AbortController();const timeout=setTimeout(()=>controller.abort(),25000);
|
| 46 |
try{
|
| 47 |
const r=await fetch(endpoint+'/chat/completions',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer public'},body:JSON.stringify(body),signal:controller.signal});
|
| 48 |
-
if(!r.ok)throw Error('Servicio no disponible (HTTP '+r.status+')');
|
| 49 |
const j=await r.json();if(!j.choices?.[0]?.message)throw Error('Respuesta vac铆a');return j.choices[0].message;
|
| 50 |
}finally{clearTimeout(timeout);}
|
| 51 |
};
|
| 52 |
-
let last;
|
| 53 |
for(const endpoint of AP.endpoints){
|
| 54 |
let available=[];
|
| 55 |
try{const r=await fetch(endpoint+'/models',{headers:{'Authorization':'Bearer public'}});if(r.ok){const j=await r.json();available=(j.data||[]).map(x=>x.id).filter(x=>x.endsWith('-free'));}}catch(e){last=e;}
|
| 56 |
const candidates=AP.activeModel?[AP.activeModel,...available.filter(x=>x!==AP.activeModel)]:[AP.model,...available.filter(x=>x!==AP.model)];
|
| 57 |
-
for(const model of candidates){try{const response=await request(endpoint,model);AP.activeModel=model;return response;}catch(e){last=e;}}
|
| 58 |
}
|
| 59 |
-
throw last||Error('Servicio no disponible');
|
| 60 |
},
|
| 61 |
context(agent){const who=String(agent||'').toUpperCase();const base={stock:AP.query('SELECT * FROM stock_status'),orders:AP.query("SELECT l.order_id,l.sku,l.quantity,o.status,o.region FROM sales_order_lines l JOIN sales_orders o ON o.id=l.order_id"),proposals:AP.query('SELECT p.id,p.sku,p.proposed_qty,p.rationale,q.status FROM purchase_proposals p JOIN approval_queue q ON p.id=q.proposal_id')};if(who!=='ALPHA'&&who!=='BETA'&&who!=='GAMMA')return base;const providers=AP.query('SELECT s.id,s.name,s.lead_days,sp.sku,sp.unit_cost_cents,sp.min_order_qty FROM suppliers s JOIN supplier_products sp ON sp.supplier_id=s.id WHERE s.active=1');if(who==='ALPHA')return {...base,providers};if(who==='GAMMA')return {stock:base.stock,proposals:base.proposals,providers};return base;},
|
| 62 |
async ask(text,quiet=false,agent){
|
|
@@ -75,7 +75,7 @@ export const APCommands = {
|
|
| 75 |
let m=await AP.modelCall(messages,who==='ALPHA'?tools:undefined);
|
| 76 |
if(who==='ALPHA'&&m.tool_calls?.length){messages.push(m);for(const c of m.tool_calls.slice(0,2)){let result;try{if(c.function.name!=='proponer_reposicion')throw Error('Herramienta no admitida');result=await AP.command({cmd:'propuesta_crear',payload:JSON.parse(c.function.arguments),actor:who});}catch(e){result='Error: '+e.message;}messages.push({role:'tool',tool_call_id:c.id,content:result});}m=await AP.modelCall(messages);}
|
| 77 |
if(!quiet){AP.append(m.content||'No hubo respuesta del agente.','ai');if(webOn)AP.append('馃摎 Fuentes\n'+webSources,'ai');}AP.audit(who,'analisis_completado','agent',who,{model:AP.activeModel||AP.model});if(!quiet)AP.audit(who,'respuesta_modelo','chat',who,{text:String(m.content||'').slice(0,500)});await AP.persist();AP.render();AP.setAgentState(st,'Disponible',false);AP.note('An谩lisis finalizado 路 '+AP.query("SELECT count(*) AS n FROM approval_queue WHERE status='pendiente'")[0].n+' pendientes');
|
| 78 |
-
}catch(e){if(!quiet)AP.append('No se pudo contactar al agente. Tus datos y propuestas locales siguen disponibles.','ai');if(webOn&&webSources)AP.append('馃摎 Fuentes web (sin respuesta del modelo)\n'+webSources,'ai');if(!quiet)AP.audit(who,'chat_sin_respuesta','chat',who,{error:String(e&&e.message||e).slice(0,200)});AP.setAgentState(st,'Sin respuesta',false);AP.note('Agente no disponible: '+e.message,true);}finally{AP.busy=false;}
|
| 79 |
},
|
| 80 |
async cycle(){
|
| 81 |
if(!AP.db||AP.cycleBusy||AP.busy||document.hidden||!AP.agentsOn)return;
|
|
|
|
| 45 |
const controller=new AbortController();const timeout=setTimeout(()=>controller.abort(),25000);
|
| 46 |
try{
|
| 47 |
const r=await fetch(endpoint+'/chat/completions',{method:'POST',headers:{'Content-Type':'application/json','Authorization':'Bearer public'},body:JSON.stringify(body),signal:controller.signal});
|
| 48 |
+
if(!r.ok){let detail='';try{const ej=await r.json();const em=String(ej&&ej.error&&(ej.error.message||ej.error.type)||'');if(/freeusage|free.*limit|rate.?limit/i.test(em))detail=' 路 l铆mite de uso gratuito del servicio de modelos alcanzado; int茅ntalo m谩s tarde';else if(em)detail=' 路 '+em.slice(0,120);}catch(_){}throw Error('Servicio no disponible (HTTP '+r.status+')'+detail);}
|
| 49 |
const j=await r.json();if(!j.choices?.[0]?.message)throw Error('Respuesta vac铆a');return j.choices[0].message;
|
| 50 |
}finally{clearTimeout(timeout);}
|
| 51 |
};
|
| 52 |
+
let last,firstHttp;
|
| 53 |
for(const endpoint of AP.endpoints){
|
| 54 |
let available=[];
|
| 55 |
try{const r=await fetch(endpoint+'/models',{headers:{'Authorization':'Bearer public'}});if(r.ok){const j=await r.json();available=(j.data||[]).map(x=>x.id).filter(x=>x.endsWith('-free'));}}catch(e){last=e;}
|
| 56 |
const candidates=AP.activeModel?[AP.activeModel,...available.filter(x=>x!==AP.activeModel)]:[AP.model,...available.filter(x=>x!==AP.model)];
|
| 57 |
+
for(const model of candidates){try{const response=await request(endpoint,model);AP.activeModel=model;return response;}catch(e){last=e;if(!firstHttp&&/HTTP \d+/.test(e&&e.message||''))firstHttp=e;}}
|
| 58 |
}
|
| 59 |
+
throw firstHttp||last||Error('Servicio no disponible');
|
| 60 |
},
|
| 61 |
context(agent){const who=String(agent||'').toUpperCase();const base={stock:AP.query('SELECT * FROM stock_status'),orders:AP.query("SELECT l.order_id,l.sku,l.quantity,o.status,o.region FROM sales_order_lines l JOIN sales_orders o ON o.id=l.order_id"),proposals:AP.query('SELECT p.id,p.sku,p.proposed_qty,p.rationale,q.status FROM purchase_proposals p JOIN approval_queue q ON p.id=q.proposal_id')};if(who!=='ALPHA'&&who!=='BETA'&&who!=='GAMMA')return base;const providers=AP.query('SELECT s.id,s.name,s.lead_days,sp.sku,sp.unit_cost_cents,sp.min_order_qty FROM suppliers s JOIN supplier_products sp ON sp.supplier_id=s.id WHERE s.active=1');if(who==='ALPHA')return {...base,providers};if(who==='GAMMA')return {stock:base.stock,proposals:base.proposals,providers};return base;},
|
| 62 |
async ask(text,quiet=false,agent){
|
|
|
|
| 75 |
let m=await AP.modelCall(messages,who==='ALPHA'?tools:undefined);
|
| 76 |
if(who==='ALPHA'&&m.tool_calls?.length){messages.push(m);for(const c of m.tool_calls.slice(0,2)){let result;try{if(c.function.name!=='proponer_reposicion')throw Error('Herramienta no admitida');result=await AP.command({cmd:'propuesta_crear',payload:JSON.parse(c.function.arguments),actor:who});}catch(e){result='Error: '+e.message;}messages.push({role:'tool',tool_call_id:c.id,content:result});}m=await AP.modelCall(messages);}
|
| 77 |
if(!quiet){AP.append(m.content||'No hubo respuesta del agente.','ai');if(webOn)AP.append('馃摎 Fuentes\n'+webSources,'ai');}AP.audit(who,'analisis_completado','agent',who,{model:AP.activeModel||AP.model});if(!quiet)AP.audit(who,'respuesta_modelo','chat',who,{text:String(m.content||'').slice(0,500)});await AP.persist();AP.render();AP.setAgentState(st,'Disponible',false);AP.note('An谩lisis finalizado 路 '+AP.query("SELECT count(*) AS n FROM approval_queue WHERE status='pendiente'")[0].n+' pendientes');
|
| 78 |
+
}catch(e){const why=e&&e.message?': '+e.message:'';if(!quiet)AP.append('No se pudo contactar al agente'+why+'. Tus datos y propuestas locales siguen disponibles.','ai');if(webOn&&webSources)AP.append('馃摎 Fuentes web (sin respuesta del modelo)\n'+webSources,'ai');if(!quiet)AP.audit(who,'chat_sin_respuesta','chat',who,{error:String(e&&e.message||e).slice(0,200)});AP.setAgentState(st,'Sin respuesta',false);AP.note('Agente no disponible: '+e.message,true);}finally{AP.busy=false;}
|
| 79 |
},
|
| 80 |
async cycle(){
|
| 81 |
if(!AP.db||AP.cycleBusy||AP.busy||document.hidden||!AP.agentsOn)return;
|