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.

18.4 KB
Raw Blame
'use strict';
const {requestFailureCode}=require('./commerce-request-context.cjs');
let catalog,actions,validator;const checks=new Map();
const source=()=>catalog ||= require('./taobao-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 permitted(row,config){return row.seller_types.length===2||row.seller_types.includes(config.credentials?.identity?.seller_type);}
function actionsFor(config){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,seller_types:r.seller_types}}]));return Object.fromEntries(Object.entries(actions).filter(([name])=>permitted(source().methods[name],config)));}
function binding(config){const c=config.credentials||{},identity=c.identity||{};if(config.provider!=='taobao_top'||!/^[1-9][0-9]{0,24}$/.test(String(identity.user_id||''))||typeof identity.nick!=='string'||!identity.nick||typeof c.app_key!=='string'||typeof c.app_secret!=='string')fail('E_TOOL_CALL_AUTH','Taobao seller binding is missing; reconnect this account');return identity;}
function visit(value,schema,fn,depth=0){if(depth>32)fail('E_BAD_INPUT','Taobao parameters exceed the nesting limit');fn(value,schema);if(Array.isArray(value))for(const v of value)visit(v,schema?.items,fn,depth+1);else if(object(value))for(const[k,v]of Object.entries(value))visit(v,schema?.properties?.[k]||(object(schema?.additionalProperties)?schema.additionalProperties:undefined),fn,depth+1);}
function validate(row,p,config){let raw;try{raw=JSON.stringify(p);}catch{fail('E_BAD_INPUT','Invalid Taobao parameters');}if(!raw||Buffer.byteLength(raw)>262144)fail('E_BAD_INPUT','Taobao parameters exceed the 256 KiB host limit');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 Taobao fields; inspect the action contract');const identity=binding(config);let nodes=0;
 visit(p,row.input_schema,(v,s)=>{if(++nodes>10000)fail('E_BAD_INPUT','Taobao parameters exceed the node limit');if(typeof v==='number'&&(!Number.isFinite(v)||Number.isInteger(v)&&!Number.isSafeInteger(v)))fail('E_BAD_INPUT','Supply exact decimal strings for large Taobao integers');if(s?.['x-top-number']){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','Taobao number exceeds its documented or host limit');}if(s?.['x-binding']==='id'&&String(v)!==String(identity.user_id)||s?.['x-binding']==='nick'&&v!==identity.nick||s?.['x-binding']==='subnick'&&(typeof v!=='string'||!v.startsWith(identity.nick+':')||v.length<=identity.nick.length+1))fail('E_BAD_INPUT','This action must target the connected seller or its subaccount');});
 for(const f of row.wire_fields)if(!f.structured&&f.type.endsWith('[]')&&p[f.name]?.some(v=>String(v).includes(',')))fail('E_BAD_INPUT','Individual list entries cannot contain the TOP list delimiter');
 if(['taobao.traderate.add','taobao.traderate.list.add'].includes(row.method)&&p.role!=='seller')fail('E_BAD_INPUT','This seller connector can submit seller reviews only');
 if(row.method==='taobao.item.quantity.update'&&(BigInt(p.type??1)!==1n&&BigInt(p.type??1)!==2n||BigInt(p.type??1)===1n&&BigInt(p.quantity)<0n))fail('E_BAD_INPUT','Use the documented stock mode and a nonnegative absolute quantity');
 if(['tmall.item.quantity.update','tmall.item.price.update','tmall.item.outerid.update'].includes(row.method)){const field=row.method.includes('quantity')?'sku_quantities':row.method.includes('price')?'sku_prices':'sku_outer_ids';const entries=p[field];if(entries){const keys=entries.map(x=>String(x.sku_id??x.properties??x.outer_id??''));if(keys.some(x=>!x)||new Set(keys).size!==keys.length)fail('E_BAD_INPUT','Select each SKU once using a documented SKU identifier');}}
 if(row.method==='taobao.skus.quantity.update'){const pairs=stockPairs(p);if(BigInt(p.type??1)!==1n&&BigInt(p.type??1)!==2n||BigInt(p.type??1)===1n&&pairs.some(x=>BigInt(x[1])<0n))fail('E_BAD_INPUT','Use the documented stock mode and nonnegative absolute quantities');}
 if(row.method==='tmall.item.quantity.update'){if(p.sku_quantities?.length){const modes=p.sku_quantities.map(x=>['sku_id','properties','outer_id'].filter(k=>x[k]!==undefined));if(modes.some(x=>x.length!==1)||new Set(modes.map(x=>x[0])).size!==1)fail('E_BAD_INPUT','Use one consistent SKU identification mode per inventory update');}if(p.item_quantity===undefined&&!p.sku_quantities?.length)fail('E_BAD_INPUT','Provide a product or SKU quantity');const mode=BigInt(p.options?.type??1);if(![1n,2n].includes(mode)||mode===1n&&[p.item_quantity,...(p.sku_quantities||[]).map(x=>x.quantity)].filter(x=>x!==undefined).some(x=>BigInt(x)<0n))fail('E_BAD_INPUT','Use the documented stock mode and nonnegative absolute quantities');if(p.options?.outer_biz_key!==undefined&&!/^[a-fA-F0-9]+$/.test(p.options.outer_biz_key))fail('E_BAD_INPUT','The stock idempotency key must use hexadecimal characters');}
 if(row.method==='cainiao.waybill.ii.get'){const dto=p.param_waybill_cloud_print_apply_new_request,rows=dto.trade_order_info_dtos;if(!rows?.length||!distinct(rows.map(x=>x.object_id)))fail('E_BAD_INPUT','Select up to ten waybill requests with unique request IDs');const ids=rows.map(x=>x.package_info?.id).filter(x=>x!==undefined);if(ids.some(x=>!/^[a-zA-Z0-9_]+$/.test(x))||!distinct(ids.map(x=>x.toLowerCase())))fail('E_BAD_INPUT','Waybill package IDs must be distinct and use the documented characters');if(rows.reduce((n,x)=>n+BigInt(x.package_info?.total_packages_count??1),0n)>10n)fail('E_BAD_INPUT','A waybill request may cover at most ten packages');}
 if(row.method==='alibaba.logistics.mail.order.delivery.preference.add'&&!distinct(p.mail_order_delivery_preference_top_request_dto.mail_order_delivery_preference_d_t_o_list?.map(x=>x.unique_key)))fail('E_BAD_INPUT','Supply distinct nonempty delivery preference idempotency keys');
}
function distinct(ids){return Array.isArray(ids)&&ids.every(x=>typeof x==='string'&&x.length>0)&&new Set(ids).size===ids.length;}
function stockPairs(p){const field=p.skuid_quantities?'skuid_quantities':'outerid_quantities',raw=p[field];if(typeof raw!=='string'||!raw)fail('E_BAD_INPUT','Provide the documented SKU quantity pairs');const rows=raw.split(';').map(s=>s.split(':'));if(!rows.length||rows.length>10||rows.some(x=>x.length!==2||!x[0]||field==='skuid_quantities'&&!/^[1-9][0-9]{0,18}$/.test(x[0])||!/^(0|-?[1-9][0-9]*)$/.test(x[1]))||new Set(rows.map(x=>x[0])).size!==rows.length)fail('E_BAD_INPUT','Provide at most ten distinct SKU quantity pairs');return rows;}

function exact(v,s){if(s?.['x-top-number'])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]||(object(s?.additionalProperties)?s.additionalProperties:undefined))).join(',')+'}';return JSON.stringify(v);}
function wire(row,p){if(['taobao.item.seller.get','taobao.trade.fullinfo.get','taobao.trade.get'].includes(row.method))p={...p,fields:[...new Set([...String(p.fields||'').split(',').filter(Boolean),row.method==='taobao.item.seller.get'?'num_iid':'tid'])].join(',')};if(row.method==='taobao.user.seller.get')p={...p,fields:[...new Set([...(p.fields||[]),'user_id'])]};const result={};for(const f of row.wire_fields){const v=p[f.name];if(v===undefined)continue;result[f.name]=f.structured||f.type==='Json'?exact(v,row.input_schema.properties[f.name]):Array.isArray(v)?v.map(String).join(','):String(v);}return result;}
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','Taobao response exceeds the nesting limit');}else if(c==='}'||c===']')depth--;}
 return JSON.parse(text,(_key,v,c)=>{if(typeof v==='number'&&!Number.isFinite(v))fail('E_TOOL_CALL_UPSTREAM','Taobao 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','Taobao returned an imprecise integer');return c.source;}return v;});}
const yes=v=>v===true||v==='true',no=v=>v===false||v==='false';
function shape(value,fields){if(!object(value))fail('E_TOOL_CALL_UPSTREAM','Taobao returned malformed business data');const out={...value};for(const f of fields){let v=value[f.name];if(v===undefined||v===null)continue;const one=x=>{if(x===null)return x;if(f.alternative==='integer'&&Number.isSafeInteger(x))return x;if(f.children.length)return shape(x,f.children);if(f.type==='Number'&&!(typeof x==='number'&&Number.isFinite(x)&&(!Number.isInteger(x)||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')fail('E_TOOL_CALL_UPSTREAM','Taobao returned a business field with an invalid type');if(!['Number','Boolean','String','Date','Price','Json'].includes(f.type)&&!object(x))fail('E_TOOL_CALL_UPSTREAM','Taobao returned an invalid business object');return x;};if(f.array){if(!f.children.length&&object(v)&&Object.keys(v).length===1&&Array.isArray(v[f.type.toLowerCase()]))v=v[f.type.toLowerCase()];if(!Array.isArray(v))fail('E_TOOL_CALL_UPSTREAM','Taobao returned an invalid business list');out[f.name]=v.map(one);}else out[f.name]=one(v);}return out;}
function failure(value,fields,inList=false){if(!object(value))return false;for(const f of fields){const v=value[f.name];if(v===undefined||v===null)continue;if(f.success_flag&&no(v)||f.failure_flag&&yes(v)||f.success_codes&&!f.success_codes.includes(String(v))||f.failure_list&&(Array.isArray(v)?v.length:typeof v==='string'&&v.length)||f.failure_count&&Number(v)>0)return true;if(f.children.length){if(Array.isArray(v)){if(inList&&v.some(x=>failure(x,f.children,true)))return true;}else if(failure(v,f.children,inList))return true;}}return false;}
const metadata=new Set(['request_id','trace_id','total_results','total_count','total_page','page_no','page_size','page_index','has_next','has_more','code','error_code','error_message','error_msg','error_desc']);
function resource(value,f,allowFlag){if(value===undefined||value===null)return false;if(f.diagnostic||metadata.has(f.name)||(!allowFlag&&(f.success_flag||f.failure_flag)))return false;if(Array.isArray(value))return true;if(object(value)){if(f.children.length)return f.children.some(c=>resource(value[c.name],c,allowFlag));return Object.keys(value).some(k=>!metadata.has(k));}return typeof value==='string'?value.length>0:true;}
function checkEnvelopeFlags(value,fields){for(const f of fields){const v=value?.[f.name];if(f.success_flag&&v===undefined)fail('E_TOOL_CALL_UPSTREAM','Taobao omitted its business acknowledgement');if(f.children.length&&!f.array&&object(v))checkEnvelopeFlags(v,f.children);}}
function same(a,b){return a!==undefined&&b!==undefined&&String(a)===String(b);}
function receipt(row,p,b){const m=row.method;
 if(['taobao.item.quantity.update','taobao.item.delete','taobao.item.update.listing','taobao.item.update.delisting','taobao.item.update.listing.tmall','taobao.item.update.delisting.tmall'].includes(m)){if(!same(b.item?.num_iid,p.num_iid))fail('E_TOOL_CALL_UPSTREAM','Taobao returned an unrelated or missing product receipt');if(m==='taobao.item.quantity.update'&&BigInt(p.type??1)===1n){if(p.sku_id){const skus=b.item.skus;if(!Array.isArray(skus)||!skus.some(s=>same(s.sku_id,p.sku_id)&&same(s.quantity,p.quantity)))fail('E_TOOL_CALL_UPSTREAM','Taobao did not confirm the requested SKU quantity');}else if(!p.outer_id&&!same(b.item.num,p.quantity))fail('E_TOOL_CALL_UPSTREAM','Taobao did not confirm the requested product quantity');}}
 if(['taobao.trade.memo.add','taobao.trade.memo.update','taobao.trade.close','taobao.trade.ordersku.update','taobao.trade.shippingaddress.update','taobao.trade.postage.update'].includes(m)&&!same(b.trade?.tid,p.tid))fail('E_TOOL_CALL_UPSTREAM','Taobao returned an unrelated or missing order receipt');
 if(['alibaba.item.edit.submit','alibaba.item.operate.delete','alibaba.item.operate.downshelf','alibaba.item.operate.upshelf'].includes(m)&&b.item_id!==undefined&&!same(b.item_id,p.item_id))fail('E_TOOL_CALL_UPSTREAM','Taobao returned an unrelated item receipt');
 if(m==='taobao.item.sku.delete'&&b.sku?.sku_id===undefined)fail('E_TOOL_CALL_UPSTREAM','Taobao omitted the deleted SKU identity');
 if(m==='tmall.item.quantity.update'&&!same(b.quantity_update_result,p.item_id))fail('E_TOOL_CALL_UPSTREAM','Tmall returned an unrelated inventory update receipt');
 if(m==='taobao.skus.quantity.update'){if(!same(b.item?.num_iid,p.num_iid)||!Array.isArray(b.item?.skus))fail('E_TOOL_CALL_UPSTREAM','Taobao omitted the batch stock receipt');if(p.skuid_quantities){const pairs=stockPairs(p),rows=b.item.skus;correlate(pairs.map(x=>x[0]),rows.map(x=>String(x.sku_id)));if(BigInt(p.type??1)===1n&&pairs.some(([id,quantity])=>!rows.some(x=>same(x.sku_id,id)&&same(x.quantity,quantity))))fail('E_TOOL_CALL_UPSTREAM','Taobao did not confirm each requested absolute SKU quantity');}}
 if(m==='cainiao.waybill.ii.get'){const dto=p.param_waybill_cloud_print_apply_new_request;correlate(dto.trade_order_info_dtos.map(x=>x.object_id),b.modules?.map(x=>x.object_id));if(b.modules.some(x=>typeof x.waybill_code!=='string'||!x.waybill_code||typeof x.print_data!=='string'||!x.print_data||x.cp_code!==undefined&&x.cp_code!==dto.cp_code))fail('E_TOOL_CALL_UPSTREAM','Cainiao omitted attributable waybill data');}
 if(m==='alibaba.logistics.mail.order.delivery.preference.add'){const data=b.api_result?.data;if(!Array.isArray(data?.success_mail_order_unique_key_list)||!Array.isArray(data?.failed_mail_order_unique_key_list))fail('E_TOOL_CALL_UPSTREAM','Taobao omitted individual preference receipts');correlate(p.mail_order_delivery_preference_top_request_dto.mail_order_delivery_preference_d_t_o_list.map(x=>x.unique_key),[...data.success_mail_order_unique_key_list,...data.failed_mail_order_unique_key_list]);}
}
function correlate(wanted,actual){if(!Array.isArray(actual)||actual.length!==wanted.length||new Set(actual).size!==actual.length||actual.some(x=>!wanted.includes(x)))fail('E_TOOL_CALL_UPSTREAM','Taobao returned missing, duplicate or unrelated batch receipts');}

function outcome(row,body,p,config){if(!object(body)||body.error_response!==undefined)fail('E_TOOL_CALL_UPSTREAM','Taobao rejected the request; check the action and application permissions');let b=body[row.response_wrapper];if(!object(b))fail('E_TOOL_CALL_UPSTREAM','Taobao omitted the documented response envelope');b=shape(b,row.output_tree);body={...body,[row.response_wrapper]:b};checkEnvelopeFlags(b,row.output_tree);const bad=failure(b,row.output_tree,row.risk!=='R');if(row.risk==='R'&&bad)fail('E_TOOL_CALL_UPSTREAM','Taobao could not return the requested resource');const present=row.output_tree.some(f=>resource(b[f.name],f,row.risk!=='R'));
 const explicitEmpty=row.risk==='R'&&row.output_tree.some(f=>f.array)&&['total_results','total_count'].some(k=>Object.hasOwn(b,k)&&same(b[k],0));if(!present&&!explicitEmpty)fail('E_TOOL_CALL_UPSTREAM','Taobao omitted its documented business result');
 if(row.method==='taobao.user.seller.get'&&(!object(b.user)||!same(b.user.user_id,config.credentials.identity.user_id)))fail('E_TOOL_CALL_AUTH','Taobao returned a different seller');if(row.method==='taobao.item.seller.get'&&!same(b.item?.num_iid,p.num_iid)||['taobao.trade.fullinfo.get','taobao.trade.get'].includes(row.method)&&!same(b.trade?.tid,p.tid))fail('E_TOOL_CALL_UPSTREAM','Taobao returned a different requested resource');if(row.risk!=='R')receipt(row,p,b);
 return{data:body,...(row.risk==='R'?{}:{status:bad?'partial_or_failed':'accepted',follow_up:'Inspect individual receipts and read back the resource or asynchronous task before treating the change as complete. Do not automatically replay an uncertain write.'})};}
const secretNames=new Set(['access_token','refresh_token','app_secret','client_secret','session','authorization','cookie']);
function sanitize(value,credentials={},fields=[]){const secrets=['access_token','refresh_token','app_secret','client_secret'].map(k=>credentials[k]).filter(s=>typeof s==='string'&&s.length>=3);function clean(v,tree,depth){if(depth>40)fail('E_TOOL_CALL_UPSTREAM','Taobao 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])=>!secretNames.has(k.toLowerCase())&&!by.get(k)?.diagnostic&&!['request_id','trace_id'].includes(k)).map(([k,x])=>[k,clean(x,by.get(k)?.children||[],depth+1)]));}return clean(value,fields,0);}
async function execute(config,name,p={},owner){const row=source().methods[name];if(!row)fail('E_BAD_INPUT','Unknown Taobao merchant action');binding(config);if(!permitted(row,config))fail('E_TOOL_CALL_AUTH','This action requires a verified Tmall seller');validate(row,p,config);let body;try{body=await owner.request(config,row.method,wire(row,p));}catch(error){const code=requestFailureCode(error);fail(['E_TOOL_CALL_CANCELLED','E_TOOL_CALL_TIMEOUT'].includes(code)?code:['E_TOOL_CALL_AUTH','E_TOOL_CALL_RATE_LIMIT','E_TOOL_CALL_UPSTREAM','E_TOOL_CALL_NETWORK','E_TOOL_CALL_TIMEOUT','E_TOOL_CALL_CANCELLED','E_BAD_INPUT'].includes(error?.code)?error.code:'E_TOOL_CALL_UPSTREAM','Taobao request failed; check permissions and read back any uncertain write before retrying');}binding(config);if(!permitted(row,config))fail('E_TOOL_CALL_AUTH','The refreshed seller does not support this action');const r=outcome(row,body,p,config);return{...r,data:sanitize(r.data,config.credentials,[{name:row.response_wrapper,children:row.output_tree}])};}
function validateResponseShape(name,text){const r=source().methods[name];if(!r)fail('E_BAD_INPUT','Unknown Taobao action');const b=parse(text);return shape(b[r.response_wrapper],r.output_tree);}
function fieldsFor(method){const fields=source().methods[method]?.selectable_fields;if(!fields)fail('E_BAD_INPUT','No reviewed Taobao field projection exists for this alias');return fields.join(',');}
module.exports={actionsFor,isNative,execute,parse,sanitize,validateResponseShape,fieldsFor};