Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

12.2 KB
Raw Blame
'use strict';
const {requestFetch,requestFailureCode,httpFailure}=require('./commerce-request-context.cjs');
const {readBody}=require('./storefront-admin-api.cjs');
let contract,actions,validator;const checks=new Map(),source=()=>contract||=require('./weimob-api-contracts.cjs');
const object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v),fail=(code,message)=>{throw Object.assign(new Error(message),{code});};
const isNative=name=>Object.hasOwn(source().methods,name);
function actionsFor(){return actions||=Object.fromEntries(Object.entries(source().methods).map(([name,r])=>[name,{risk:r.risk,description:r.description,input_schema:r.input_schema}]));}
const child=(s,k)=>s?.properties?.[k]||(object(s?.additionalProperties)?s.additionalProperties:undefined);
function binding(config){const id=config.credentials?.identity?.business_operation_system_id;if(!/^[1-9][0-9]*$/.test(String(id))||String(id)!==String(config.metadata?.shop_id)||config.metadata?.shop_type!=='business_operation_system_id')fail('E_TOOL_CALL_AUTH','Weimob WOS merchant binding is missing or mismatched');}
function walk(v,s,fn,depth=0){if(depth>40)fail('E_BAD_INPUT','Weimob parameters are too deeply nested');fn(v,s);if(Array.isArray(v))v.forEach(x=>walk(x,s?.items,fn,depth+1));else if(object(v))for(const[k,x]of Object.entries(v))walk(x,child(s,k),fn,depth+1);}
function validate(row,p,config){let bytes;try{bytes=Buffer.byteLength(JSON.stringify(p));}catch{fail('E_BAD_INPUT','Invalid Weimob parameters');}if(bytes>262144)fail('E_BAD_INPUT','Weimob parameters exceed 256 KiB');
 walk(p,row.input_schema,(v,s)=>{if(typeof v==='number'&&(!Number.isFinite(v)||Number.isInteger(v)&&!Number.isSafeInteger(v)))fail('E_BAD_INPUT','Use an exact decimal string for large Weimob numbers');if(s?.['x-number']&&(typeof v==='string'&&v.length>310||!Number.isFinite(Number(v))))fail('E_BAD_INPUT','Weimob number exceeds the supported finite range');if(s?.['x-timeMaxDays']&&object(v)&&(Number(v.endTime)<Number(v.startTime)||Number(v.endTime)-Number(v.startTime)>s['x-timeMaxDays']*86400000))fail('E_BAD_INPUT','Weimob query time range exceeds its documented window');if(s?.['x-binding']&&(!config.credentials.identity[s['x-binding']]||String(v)!==String(config.credentials.identity[s['x-binding']])))fail('E_BAD_INPUT','Weimob action cannot target another merchant');});
 if(!validator){const{AjvJsonSchemaValidator}=require('@modelcontextprotocol/sdk/validation/ajv');validator=new AjvJsonSchemaValidator();}let check=checks.get(row.input_schema);if(!check){check=validator.getValidator(row.input_schema);checks.set(row.input_schema,check);}if(!check(p).valid)fail('E_BAD_INPUT','Invalid Weimob parameters; check the described fields and required values');
 const max={R:100,W:25,H:10,D:10}[row.risk];
 if(row.action==='weimob_shop.goods.assign'&&p.goodsIdList.length*p.vidList.length>10)fail('E_BAD_INPUT','Weimob assignment exceeds ten product-organization changes');
 if(['weimob_crm.coupon.receive','weimob_crm.coupon.precoupon.send'].includes(row.action)&&p.couponNums.reduce((sum,x)=>sum+Number(x.num),0)>10)fail('E_BAD_INPUT','Weimob issuance exceeds ten coupons');
 if(['weimob_shop.goods.classify.relation.update','haiding_scm.sku.assign','haiding_scm.storesku.delete'].includes(row.action)){const arrays=row.action.startsWith('weimob_shop')?[p.classifyIdList,p.goodsIdList]:[p.storeIds,p.skuIds,...(p.platforms?[p.platforms]:[])];if(arrays.reduce((n,x)=>n*(x?.length||1),1)>max)fail('E_BAD_INPUT','Weimob batch expands beyond this tool lane limit');}
 if(['weimob_shop.stock.update','weimob_shop.stock.presell.update','weimob_shop.stock.virtual.update'].includes(row.action)){const rows=p.goodsList||[],n=rows.reduce((sum,x)=>sum+(x.skuList?.length||0),0);if(n>max)fail('E_BAD_INPUT','Weimob inventory batch exceeds ten SKU changes');}
 for(const [action,key,id]of [['weimob_crm.customer.import','userList','userKey'],['haiding_scm.sku.import','skuList','externalId'],['haiding_scm.sku.update','skuList','id']])if(row.action===action){const values=p[key].filter(x=>x[id]!==undefined).map(x=>String(x[id]));if(new Set(values).size!==values.length)fail('E_BAD_INPUT','Provide distinct business identifiers for each Weimob batch item');}
}
function defaults(v,s){if(Array.isArray(v))return v.map(x=>defaults(x,s?.items));if(!object(v))return v;const out={...v};for(const[k,x]of Object.entries(s?.properties||{})){if(out[k]===undefined&&x['x-pageMax'])out[k]=x.default;if(out[k]!==undefined)out[k]=defaults(out[k],x);}return out;}
function wire(v,s){if(s?.['x-number'])return String(v);if(Array.isArray(v))return'['+v.map(x=>wire(x,s?.items)).join(',')+']';if(object(v))return'{'+Object.keys(v).sort().map(k=>JSON.stringify(k)+':'+wire(v[k],child(s,k))).join(',')+'}';return JSON.stringify(v);}
function parse(text){let depth=0,quoted=false,escaped=false;for(const c of text){if(quoted){if(escaped)escaped=false;else if(c==='\\')escaped=true;else if(c==='"')quoted=false;}else if(c==='"')quoted=true;else if(c==='{'||c==='['){if(++depth>40)fail('E_TOOL_CALL_UPSTREAM','Weimob response is too deeply nested');}else if(c==='}'||c===']')depth--;}
 return JSON.parse(text,(_k,v,c)=>{if(typeof v==='number'&&!Number.isFinite(v))fail('E_TOOL_CALL_UPSTREAM','Weimob returned a nonfinite number');if(typeof v==='number'&&Number.isInteger(v)&&!Number.isSafeInteger(v)){if(/^-?[0-9]+$/.test(c.source))return c.source;fail('E_TOOL_CALL_UPSTREAM','Weimob returned an imprecise scientific or fractional integer');}return v;});}
function typed(v,s){if(!s||v===null)return true;if(s['x-number'])return typeof v==='number'&&Number.isFinite(v)||typeof v==='string'&&/^-?(0|[1-9][0-9]*)(\.[0-9]+)?$/.test(v);if(s.anyOf)return s.anyOf.some(x=>typed(v,x));if(Array.isArray(s.type))return s.type.some(t=>typed(v,{...s,type:t}));if(s.type==='object')return object(v)&&Object.entries(v).every(([k,x])=>typed(x,child(s,k)));if(s.type==='array')return Array.isArray(v)&&v.every(x=>typed(x,s.items));if(s.type==='integer')return Number.isSafeInteger(v);return typeof v===s.type;}
function partial(v,s){if(!s)return false;if(s['x-resultBoolean']&&v===false)return true;if(Array.isArray(v))return v.some(x=>partial(x,s.items));if(!object(v))return false;for(const[k,x]of Object.entries(v)){const f=child(s,k);if(!f)continue;if(f['x-failureCollection']&&(Array.isArray(x)?x.length:object(x)&&Object.keys(x).length))return true;if(f['x-failureCount']&&Number(x)>0)return true;if(partial(x,f))return true;}return false;}
function correlate(expected,actual){const ids=actual.map(String);if(ids.length!==expected.length||new Set(ids).size!==ids.length||ids.some(x=>!expected.includes(x)))fail('E_TOOL_CALL_UPSTREAM','Weimob omitted, duplicated or mismatched batch acknowledgements');}
function ack(row,p,body,config){if(!object(body)||!object(body.code)||String(body.code.errcode)!=='0')fail('E_TOOL_CALL_UPSTREAM','Weimob rejected the request or omitted its success code');if(!Object.hasOwn(body,'data')||body.data===null)fail('E_TOOL_CALL_UPSTREAM','Weimob omitted the documented business result');if(!typed(body,row.output_schema))fail('E_TOOL_CALL_UPSTREAM','Weimob returned fields with invalid documented types');const data=body.data,s=row.output_schema.properties.data,props=s.properties||{};
 if(object(data)&&Object.keys(props).length){const keys=Object.keys(props).filter(k=>!['pageNum','pageSize','pageIndex','page','totalCount','total','totalPage','hasNext','scrollId','cursor','globalTicket'].includes(k)&&!props[k]['x-diagnostic']);if(keys.length&&!keys.some(k=>data[k]!==undefined&&data[k]!==null))fail('E_TOOL_CALL_UPSTREAM','Weimob omitted business resources from its response');const pageKeys=Object.keys(props).filter(k=>props[k].type==='array'&&['pageList','list','items','results','scrollList'].includes(k));if(('totalCount'in props||'total'in props||'pageNum'in props||'pageIndex'in props)&&pageKeys.some(k=>!Array.isArray(data[k])))fail('E_TOOL_CALL_UPSTREAM','Weimob returned page metadata without the resource list');}
 if(row.action==='bos.info.get'&&String(data.bosId)!==String(config.credentials.identity.business_operation_system_id))fail('E_TOOL_CALL_AUTH','Weimob returned a different WOS merchant');
 if(['weimob_shop.goods.create','weimob_shop.goods.update'].includes(row.action)&&(!data.goodsId||!Array.isArray(data.skuList)))fail('E_TOOL_CALL_UPSTREAM','Weimob omitted product or SKU identifiers');
 const batches={'weimob_crm.customer.import':['userList','userKey','errorList','successCnt','errorCnt'],'haiding_scm.sku.import':['skuList','externalId','failList','successCount','failCount'],'haiding_scm.sku.update':['skuList','id','failList','successCount','failCount']};const b=batches[row.action];if(b){const success=data.successList||[],failed=data[b[2]]||[];if(!Array.isArray(success)||!Array.isArray(failed)||Number(data[b[3]])!==success.length||Number(data[b[4]])!==failed.length)fail('E_TOOL_CALL_UPSTREAM','Weimob batch counts do not match individual results');const expected=p[b[0]],key=expected.every(x=>x[b[1]]!==undefined)?b[1]:row.action==='weimob_crm.customer.import'&&expected.every(x=>x.phone)?'phone':undefined;if(success.length+failed.length!==expected.length)fail('E_TOOL_CALL_UPSTREAM','Weimob omitted batch results');if(key)correlate(expected.map(x=>String(x[key])),[...success,...failed].map(x=>x[key]));}
 if(row.action==='weimob_guide.material.custom.deleteList'){if(!Array.isArray(data.successList)||!Array.isArray(data.failList))fail('E_TOOL_CALL_UPSTREAM','Weimob omitted material deletion results');correlate(p.contentMaterialIdList.map(String),[...data.successList,...data.failList.map(x=>x.contentMaterialId)]);}
 if(partial(body,row.output_schema))return'partial_or_failed';return row.risk==='R'?undefined:'accepted';
}
const secretKeys=new Set(['accesstoken','refreshtoken','clientid','clientsecret','authorization','password','cookie','jsapiticket']);
function sanitize(data,credentials={},schema){const values=['access_token','refresh_token','client_id','client_secret'].map(k=>credentials[k]).filter(v=>typeof v==='string'&&v.length>=3);function clean(v,s,depth=0){if(depth>40)fail('E_TOOL_CALL_UPSTREAM','Weimob response is too deeply nested');if(typeof v==='string'){for(const secret of values)v=v.split(secret).join('[redacted]');return v;}if(Array.isArray(v))return v.map(x=>clean(x,s?.items,depth+1));if(!object(v))return v;return Object.fromEntries(Object.entries(v).filter(([k])=>!secretKeys.has(k.replace(/[_-]/g,'').toLowerCase())&&!(depth===1&&s===schema?.properties?.code&&k==='errmsg')&&!child(s,k)?.['x-diagnostic']).map(([k,x])=>[k,clean(x,child(s,k),depth+1)]));}return clean(data,schema);}
async function execute(config,name,p={},owner){const row=source().methods[name];if(!row)fail('E_BAD_INPUT','Unknown Weimob WOS action');binding(config);validate(row,p,config);p=defaults(p,row.input_schema);let token;try{token=await owner.token(config);}catch(error){const code=requestFailureCode(error);fail(code==='E_TOOL_CALL_CANCELLED'||code==='E_TOOL_CALL_TIMEOUT'?code:/^E_TOOL_CALL_(AUTH|RATE_LIMIT|UPSTREAM|NETWORK|TIMEOUT|CANCELLED)$/.test(error?.code)?error.code:'E_TOOL_CALL_AUTH','Weimob authorization could not be refreshed');}binding(config);
 const url=new URL('https://dopen.weimob.com'+row.path);url.searchParams.set('accesstoken',token);const deadline=AbortSignal.timeout(60000);let response,text;try{response=await requestFetch(url.toString(),{method:'POST',headers:{accept:'application/json','content-type':'application/json'},body:wire(p,row.input_schema),redirect:'error',signal:deadline});}catch(error){fail(requestFailureCode(error,deadline),'Weimob request failed; inspect business state before retrying an uncertain write');}if(!response.ok)throw httpFailure(response.status,'Weimob request failed; check application capability approval');try{text=await readBody(response);}catch(error){fail(error?.code==='E_CONNECTOR_RESPONSE_TOO_LARGE'?'E_TOOL_CALL_UPSTREAM':requestFailureCode(error,deadline),'Weimob response could not be read completely');}
 let body;try{body=parse(text);}catch{fail('E_TOOL_CALL_UPSTREAM','Weimob returned invalid or imprecise JSON');}const status=ack(row,p,body,config);return{data:sanitize(body,config.credentials,row.output_schema),...(status?{status}:{}),...(status==='accepted'?{follow_up:'Read back the resource or asynchronous task before treating the change as complete. Do not automatically retry.'}:{})};}
module.exports={actionsFor,isNative,execute,sanitize,parse};