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.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
'use strict';
// Alibaba.com merchant TOP contracts; session lifecycle and signing belong to the existing owner.
const {requestFetch,requestFailureCode}=require('./commerce-request-context.cjs');
const {readBody}=require('./storefront-admin-api.cjs');
let catalog,actions,validator;const checks=new Map();
const source=()=>catalog ||= require('./icbu-api-contracts.cjs');
const object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
const 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,documentation_url:r.documentation_url,requirements:r.requirements}]));}
function visit(v,s,fn,depth=0){if(depth>40)fail('E_BAD_INPUT','Alibaba.com parameters exceed the nesting limit');fn(v,s);if(Array.isArray(v))for(const x of v)visit(x,s?.items,fn,depth+1);else if(object(v))for(const[k,x]of Object.entries(v))visit(x,s?.properties?.[k],fn,depth+1);}
function validate(row,p){let raw;try{raw=JSON.stringify(p);}catch{fail('E_BAD_INPUT','Invalid Alibaba.com parameters');}if(!raw||Buffer.byteLength(raw)>262144)fail('E_BAD_INPUT','Alibaba.com parameters exceed 256 KiB');
validator ||= new(require('@modelcontextprotocol/sdk/validation/ajv').AjvJsonSchemaValidator)();let check=checks.get(row);if(!check){check=validator.getValidator(row.input_schema);checks.set(row,check);}if(!check(p).valid)fail('E_BAD_INPUT','Invalid Alibaba.com fields; inspect the action contract');
let nodes=0;visit(p,row.input_schema,(v,s)=>{if(++nodes>20000)fail('E_BAD_INPUT','Too many Alibaba.com parameter values');if(typeof v==='number'&&(!Number.isFinite(v)||Number.isInteger(v)&&!Number.isSafeInteger(v)))fail('E_BAD_INPUT','Use exact decimal strings for large Alibaba.com integers');if(s?.['x-integer']){const n=BigInt(v);if(n< -9223372036854775808n||n>9223372036854775807n||s['x-min']!==undefined&&n<BigInt(s['x-min'])||s['x-max']!==undefined&&n>BigInt(s['x-max']))fail('E_BAD_INPUT','Alibaba.com number exceeds its documented limit');}});
for(const f of row.wire_fields)if(!f.structured&&f.type.endsWith('[]')&&p[f.name]?.some(x=>String(x).includes(',')))fail('E_BAD_INPUT','Individual TOP list values cannot contain commas');
if(row.method==='alibaba.icbu.product.batch.update.display'){const ids=p.product_id_list.split(',');if(ids.length>10||ids.some(x=>!x.trim())||new Set(ids).size!==ids.length)fail('E_BAD_INPUT','Select up to ten distinct product IDs');}
if(row.method==='alibaba.icbu.product.inventory.update'){const keys=p.request_param.inventory_list.map(x=>x.sku_id+'\0'+x.inventory_code);if(new Set(keys).size!==keys.length||p.request_param.inventory_list.some(x=>BigInt(x.inventory)<0n))fail('E_BAD_INPUT','Use distinct SKU and warehouse pairs with nonnegative stock changes');}
}
function exact(v,s){if(s?.['x-integer']||s?.['x-decimal'])return String(v);if(Array.isArray(v))return'['+v.map(x=>exact(x,s?.items)).join(',')+']';if(object(v))return'{'+Object.entries(v).map(([k,x])=>JSON.stringify(k)+':'+exact(x,s?.properties?.[k])).join(',')+'}';return JSON.stringify(v);}
function defaults(p,s){if(Array.isArray(p))return p.map(x=>defaults(x,s?.items));if(!object(p))return p;const out={...p};for(const[k,v]of Object.entries(s?.properties||{})){if(out[k]===undefined&&v.default!==undefined)out[k]=v.default;else if(out[k]!==undefined)out[k]=defaults(out[k],v);}return out;}
function wire(row,p){p=defaults(p,row.input_schema);const out={};for(const f of row.wire_fields){const v=p[f.name];if(v===undefined)continue;out[f.name]=f.structured||f.type==='Json'?exact(v,row.input_schema.properties[f.name]):Array.isArray(v)?v.map(x=>f.name==='keywords'?JSON.stringify(x):String(x)).join(','):String(v);}return out;}
function parse(text){if(Buffer.byteLength(text)>1048576)fail('E_TOOL_CALL_UPSTREAM','Alibaba.com response exceeds 1 MiB');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','Alibaba.com response exceeds the nesting limit');}else if(c==='}'||c===']')depth--;}
return JSON.parse(text,(_k,v,c)=>{if(typeof v==='number'&&!Number.isFinite(v))fail('E_TOOL_CALL_UPSTREAM','Alibaba.com returned a nonfinite number');if(typeof v==='number'&&Number.isInteger(v)&&!Number.isSafeInteger(v)){if(!/^-?[0-9]+$/.test(c.source))fail('E_TOOL_CALL_UPSTREAM','Alibaba.com returned an imprecise integer');return c.source;}return v;});}
const yes=v=>v===true||v==='true',no=v=>v===false||v==='false';
function arrayValue(v,f){if(Array.isArray(v))return v;if(object(v)&&Array.isArray(v[f.wrapper]))return v[f.wrapper];fail('E_TOOL_CALL_UPSTREAM','Alibaba.com returned an invalid documented list');}
function shape(value,fields){if(!object(value))fail('E_TOOL_CALL_UPSTREAM','Alibaba.com returned malformed business data');for(const f of fields){const v=value[f.name];if(v===undefined||v===null)continue;const one=x=>{if(x===null)return;if(f.children.length){shape(x,f.children);return;}if(f.type==='Number'&&!(Number.isSafeInteger(x)||typeof x==='string'&&/^(0|-?[1-9][0-9]*)$/.test(x))||f.type==='Boolean'&&!yes(x)&&!no(x)||['String','Date','Price'].includes(f.type)&&typeof x!=='string'||f.type==='BigDecimal'&&!(typeof x==='number'&&Number.isFinite(x)||typeof x==='string'&&/^-?(0|[1-9][0-9]*)(\.[0-9]+)?$/.test(x)))fail('E_TOOL_CALL_UPSTREAM','Alibaba.com returned a field with an invalid type');if(!['Number','Boolean','String','Date','Price','Json','BigDecimal'].includes(f.type)&&!object(x))fail('E_TOOL_CALL_UPSTREAM','Alibaba.com returned an invalid business object');};if(f.array)arrayValue(v,f).forEach(one);else one(v);}return value;}
const metadata=new Set(['request_id','trace_id','current_page','page_size','page_count','page_no','record_count','total_item','total_count','current_count','errorcode','error_code','error_type','sub_error_code','msg_code','code']);
function present(v,f,flags){if(v===undefined||v===null||f.diagnostic||metadata.has(f.name)||f.success_flag&&!flags)return false;if(f.array)return Array.isArray(arrayValue(v,f));if(object(v))return f.children.some(c=>present(v[c.name],c,flags));return typeof v==='string'?v.length>0:true;}
function failure(v,fields,requireFlags=true){let bad=false;for(const f of fields){const x=v?.[f.name];if(f.success_flag){if(requireFlags&&x===undefined)fail('E_TOOL_CALL_UPSTREAM','Alibaba.com omitted its business acknowledgement');if(no(x))bad=true;}if(x!==undefined&&x!==null&&f.children.length){if(f.array){for(const item of arrayValue(x,f))bad=failure(item,f.children,true)||bad;}else bad=failure(x,f.children,requireFlags)||bad;}}return bad;}
function same(a,b){return a!==undefined&&b!==undefined&&String(a)===String(b);}
function receipt(row,p,b){const m=row.method;
if(['alibaba.icbu.product.add','alibaba.icbu.product.add.draft','alibaba.icbu.product.update','alibaba.icbu.product.update.field'].includes(m)){if(typeof b.product_id!=='string'||!b.product_id||p.product_id&&!same(p.product_id,b.product_id))fail('E_TOOL_CALL_UPSTREAM','Alibaba.com omitted or mismatched the product receipt');}
if(m==='alibaba.icbu.product.schema.update'&&(!b.product_id||p.param_product_top_publish_request.product_id&&!same(b.product_id,p.param_product_top_publish_request.product_id)))fail('E_TOOL_CALL_UPSTREAM','Alibaba.com omitted or mismatched the product receipt');
if(m==='alibaba.icbu.product.group.add'&&!b.product_group?.group_id)fail('E_TOOL_CALL_UPSTREAM','Alibaba.com omitted the created product group');
if(m==='alibaba.icbu.photobank.group.operate'){const g=b.photo_group_result?.photobank_group,q=p.photo_group_operation_request;if(!g?.id||q?.operation!=='add'&&q?.group_id!==undefined&&!same(g.id,q.group_id))fail('E_TOOL_CALL_UPSTREAM','Alibaba.com omitted or mismatched the photo group receipt');}
if(m==='alibaba.onetouch.logistics.express.logistics.order.create'&&!b.result?.values?.order_number)fail('E_TOOL_CALL_UPSTREAM','Alibaba.com omitted the logistics order receipt');
if(m==='alibaba.icbu.quotation.post'&&!b.result?.result?.id)fail('E_TOOL_CALL_UPSTREAM','Alibaba.com omitted the quotation receipt');
if(m==='alibaba.icbu.product.inventory.update'&&!yes(b.result?.data))return true;
if(m==='alibaba.icbu.video.upload'&&b.msg_code!=='200')return true;
return false;
}
function outcome(row,p,body){if(!object(body)||body.error_response!==undefined)fail('E_TOOL_CALL_UPSTREAM','Alibaba.com rejected the request; check the merchant application permissions');const b=body[row.response_wrapper];shape(b,row.output_tree);let bad=failure(b,row.output_tree);
if(row.method==='alibaba.icbu.photobank.list'&&b.errorcode)bad=true;
if(row.method==='alibaba.icbu.product.batch.update.display'&&b.sub_error_code)bad=true;
if(row.risk==='R'&&bad)fail('E_TOOL_CALL_UPSTREAM','Alibaba.com could not return the requested business result');
const exceptional=row.method==='alibaba.scbp.showcase.status'&&b.total_count!==undefined&&b.current_count!==undefined||row.method==='alibaba.icbu.product.list'&&same(b.total_item,0)||row.method==='alibaba.icbu.video.upload'&&b.msg_code!==undefined;
if(!bad&&!exceptional&&!row.output_tree.some(f=>present(b[f.name],f,row.risk!=='R')))fail('E_TOOL_CALL_UPSTREAM','Alibaba.com omitted its documented business result');
if(row.method==='alibaba.icbu.product.get'&&!same(b.product?.product_id,p.product_id))fail('E_TOOL_CALL_UPSTREAM','Alibaba.com returned a different requested product');
if(row.risk!=='R'&&!bad)bad=receipt(row,p,b);
return{data:body,...(row.risk==='R'?{}:{status:bad?'partial_or_failed':'accepted',follow_up:'Read back the resource or asynchronous task before treating the change as complete. Do not automatically retry uncertain writes.'})};}
const secretKeys=new Set(['app_secret','client_secret','access_token','refresh_token','session','authorization','cookie']);
function sanitize(value,credentials={},fields=[]){const secrets=['app_key','app_secret','client_secret','access_token','refresh_token'].map(k=>credentials[k]).filter(v=>typeof v==='string'&&v.length>=3);function clean(v,tree,depth){if(depth>40)fail('E_TOOL_CALL_UPSTREAM','Alibaba.com response exceeds the nesting limit');if(typeof v==='string'){for(const s of secrets)v=v.split(s).join('[redacted]');return v;}if(Array.isArray(v))return v.map(x=>clean(x,tree,depth+1));if(!object(v))return v;const by=new Map(tree.map(f=>[f.name,f]));return Object.fromEntries(Object.entries(v).filter(([k])=>!secretKeys.has(k.toLowerCase())&&!by.get(k)?.diagnostic&&!['request_id','trace_id'].includes(k)).map(([k,x])=>{const f=by.get(k);return[k,clean(x,f?.array?[{name:f.wrapper,children:f.children}]:f?.children||[],depth+1)];}));}return clean(value,fields,0);}
function classified(error){const code=requestFailureCode(error);if(['E_TOOL_CALL_CANCELLED','E_TOOL_CALL_TIMEOUT'].includes(code))return code;if(['E_BAD_INPUT','E_TOOL_CALL_AUTH','E_TOOL_CALL_TIMEOUT','E_TOOL_CALL_CANCELLED','E_TOOL_CALL_RATE_LIMIT','E_TOOL_CALL_UPSTREAM','E_TOOL_CALL_NETWORK'].includes(error?.code))return error.code;if(['storefront_permission_denied','storefront_binding_mismatch','storefront_invalid_credentials'].includes(error?.code))return'E_TOOL_CALL_AUTH';return code||'E_TOOL_CALL_UPSTREAM';}
async function execute(config,name,p={},owner){const row=source().methods[name];if(!row)fail('E_BAD_INPUT','Unknown Alibaba.com merchant action');validate(row,p);try{owner.validateBinding(config);await owner.ensureToken(config);owner.validateBinding(config);}catch(e){fail(classified(e),'Alibaba.com authorization failed; reconnect the merchant account');}
const parameters={...wire(row,p),method:row.method,app_key:config.credentials.app_key,session:config.credentials.access_token,format:'json',v:'2.0',sign_method:'hmac',timestamp:owner.timestamp()};parameters.sign=owner.sign(parameters,config.credentials.app_secret);let response;
try{response=await requestFetch(owner.apiBase(config.provider,config.metadata),{method:'POST',headers:{accept:'application/json','content-type':'application/x-www-form-urlencoded'},body:new URLSearchParams(parameters).toString(),redirect:'error',signal:AbortSignal.timeout(60000)});}catch(e){fail(classified(e),'Alibaba.com request failed; read back an uncertain write before retrying');}
if(!response.ok)fail([401,403].includes(response.status)?'E_TOOL_CALL_AUTH':response.status===429?'E_TOOL_CALL_RATE_LIMIT':'E_TOOL_CALL_UPSTREAM','Alibaba.com could not complete the request');let body;try{body=parse(await readBody(response));}catch(e){fail(['E_TOOL_CALL_CANCELLED','E_TOOL_CALL_TIMEOUT'].includes(classified(e))?classified(e):'E_TOOL_CALL_UPSTREAM','Alibaba.com returned invalid or oversized business data');}
const result=outcome(row,p,body);return{...result,data:sanitize(result.data,config.credentials,[{name:row.response_wrapper,children:row.output_tree}])};}
function validateResponseShape(name,text){const row=source().methods[name];if(!row)fail('E_BAD_INPUT','Unknown Alibaba.com merchant action');const b=parse(text);return shape(b[row.response_wrapper],row.output_tree);}
module.exports={actionsFor,isNative,execute,parse,sanitize,validateResponseShape};