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';
const {requestFetch,requestFailureCode,httpFailure}=require('./commerce-request-context.cjs');
const {readBody}=require('./storefront-admin-api.cjs');
let catalog,actions,validator;const checks=new Map();
const source=()=>catalog ||= require('./youzan-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){const type=config.credentials?.identity?.type;if(type===undefined)return row.shop_types.includes('微商城单店')&&row.shop_types.includes('零售单店');return row.shop_types.includes([0,2,9].includes(type)?'微商城单店':type===7?'零售单店':'');}
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.source_url,requirements:{billing:r.billing,shop_types:r.shop_types,permission_packages:r.permission_packages,authorization:'The connected application must have one of the documented capability packages. Shop type alone does not prove method permission.'}}]));return Object.fromEntries(Object.entries(actions).filter(([name])=>permitted(source().methods[name],config)));}
function binding(config){const id=String(config.credentials?.identity?.kdt_id??'');if(config.provider!=='youzan'||!/^[1-9][0-9]{0,24}$/.test(id)||id!==String(config.metadata?.kdt_id))fail('E_TOOL_CALL_AUTH','Youzan shop binding is missing or inconsistent');return id;}
function visit(value,schema,fn,depth=0){if(depth>32)fail('E_BAD_INPUT','Youzan parameters exceed the nesting limit');fn(value,schema);if(Array.isArray(value))value.forEach(v=>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 Youzan parameters');}if(!raw||Buffer.byteLength(raw)>262144)fail('E_BAD_INPUT','Youzan 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 Youzan parameters; inspect the documented fields and types');
const shop=binding(config);let count=0;
visit(p,row.input_schema,(v,s)=>{if(++count>10000)fail('E_BAD_INPUT','Youzan parameters exceed the node limit');if(typeof v==='number'&&(!Number.isFinite(v)||Number.isInteger(v)&&!Number.isSafeInteger(v)))fail('E_BAD_INPUT','Use an exact decimal string for Youzan 64-bit integers');if(s?.['x-long']&&(BigInt(v)<-9223372036854775808n||BigInt(v)>9223372036854775807n))fail('E_BAD_INPUT','Youzan integer exceeds its signed 64-bit range');if(s?.['x-shop-binding']&&String(v)!==shop)fail('E_BAD_INPUT','Youzan action must target the connected shop');if(s?.['x-client-binding']&&String(v)!==String(config.credentials.client_id))fail('E_BAD_INPUT','Youzan action must use the connected application');if(s?.['x-page-limit']&&(BigInt(v)<BigInt(s['x-page-min'])||BigInt(v)>BigInt(s['x-page-limit'])))fail('E_BAD_INPUT','Youzan page size exceeds its documented or host limit');});
const distinct=list=>Array.isArray(list)&&list.length>0&&list.every(x=>typeof x==='string'&&x.length>0)&&new Set(list).size===list.length;
if(row.method==='youzan.salesman.order.operate.settle'&&(!distinct(p.order_settle_open_d_t_o?.tids)||!Object.values(p.order_settle_open_d_t_o?.operator||{}).some(v=>typeof v==='string'&&v)))fail('E_BAD_INPUT','Select distinct orders and provide the documented settlement operator');
if(row.method==='youzan.logistics.waybill.apply'){const rows=p.trade_order_info_list;if(!distinct(rows?.map(r=>r.apply_id)))fail('E_BAD_INPUT','Provide distinct nonempty waybill idempotency keys');if(rows.some(r=>p.payment_type===0&&!(BigInt(r.package_info.weight??'0')>0n))||rows.reduce((n,r)=>n+BigInt(r.package_info.total_packages_count??'1'),0n)>10n)fail('E_BAD_INPUT','Provide the required package weight and at most ten packages');}
if(row.method==='youzan.item.sku.batch.update'){if(!Array.isArray(p.item_skus_list)||!p.item_skus_list.length||p.item_skus_list.some(r=>!r.item_id||!Array.isArray(r.skus)||!r.skus.length||r.skus.some(s=>!s.sku_id||s.stock_num===undefined&&s.price===undefined))||p.item_skus_list.reduce((n,r)=>n+r.skus.length,0)>10)fail('E_BAD_INPUT','Select up to ten existing product SKUs and their changes');const keys=p.item_skus_list.flatMap(r=>r.skus.map(s=>r.item_id+':'+s.sku_id));if(new Set(keys).size!==keys.length)fail('E_BAD_INPUT','Select each product SKU once');}
}
function exact(v,s){if(s?.['x-long'])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){return'{'+Object.entries(p).map(([k,v])=>JSON.stringify(k)+':'+(row.encoded_fields.includes(k)?JSON.stringify(exact(v,row.input_schema.properties[k])):exact(v,row.input_schema.properties[k]))).join(',')+'}';}
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','Youzan 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','Youzan 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','Youzan returned an imprecise integer');return c.source;}return v;});}
const trueValue=v=>v===true||v==='true',falseValue=v=>v===false||v==='false';
function normalize(value,fields){if(!object(value))fail('E_TOOL_CALL_UPSTREAM','Youzan returned malformed business data');const result={...value};for(const f of fields){const name=f.name;if(value[name]===undefined||value[name]===null)continue;let v=value[name],kind=f.kind;if(f.alternative&&(f.alternative==='integer'&&Number.isSafeInteger(v)||f.alternative==='long'&&(Number.isSafeInteger(v)||typeof v==='string'&&/^(0|-?[1-9][0-9]*)$/.test(v))||f.alternative==='boolean'&&typeof v==='boolean'||f.alternative==='numeric_string'&&typeof v==='string'&&/^-?(0|[1-9][0-9]*)(\.[0-9]+)?$/.test(v)||f.alternative==='array'&&Array.isArray(v)||f.alternative==='empty_string'&&v==='')){result[name]=v;continue;}if(f.children.length&&typeof v==='string'){try{v=parse(v);}catch{fail('E_TOOL_CALL_UPSTREAM','Youzan returned malformed structured business data');}}
const one=x=>{if(x===null)return x;if(f.children.length)return normalize(x,f.children);if(kind==='unknown'||kind==='date')return x;if(kind==='long'){if(!(Number.isSafeInteger(x)||typeof x==='string'&&/^(0|-?[1-9][0-9]*)$/.test(x)))fail('E_TOOL_CALL_UPSTREAM','Youzan returned an invalid exact integer');}else if(kind==='boolean'){if(!trueValue(x)&&!falseValue(x))fail('E_TOOL_CALL_UPSTREAM','Youzan returned an invalid business flag');}else if(kind==='integer'&&!Number.isSafeInteger(x)||kind==='number'&&(typeof x!=='number'||!Number.isFinite(x))||kind==='string'&&typeof x!=='string'||['object','map'].includes(kind)&&!object(x))fail('E_TOOL_CALL_UPSTREAM','Youzan returned a business field with an invalid type');return x;};
if(kind==='array'||f.container_conflict&&Array.isArray(v)){if(!Array.isArray(v))fail('E_TOOL_CALL_UPSTREAM','Youzan returned an invalid business list');result[name]=v.map(x=>f.children.length?normalize(x,f.children):normalize({item:x},[{name:'item',kind:f.item_kind||'unknown',children:[]}]).item);}else result[name]=one(v);
}return result;}
function partial(value,fields){if(!object(value))return false;for(const f of fields){const v=value[f.name];if(v===undefined||v===null)continue;if((f.result_flag||f.alternative==='boolean')&&falseValue(v))return true;if(f.failure_collection&&(Array.isArray(v)?v.length:object(v)&&Object.keys(v).length))return true;if(f.failure_count&&Number(v)>0)return true;if(f.children.length){if(Array.isArray(v)?v.some(x=>partial(x,f.children)):partial(v,f.children))return true;}}return false;}
const metadataFields=new Set(['success','is_success','isSuccess','successful','code','message','request_id','requestId','trace_id','paginator','pagination','page','page_no','page_size','total','total_count','total_results','count','has_more']);
function resourcePresent(v,f){if(v===undefined||v===null)return false;if(Array.isArray(v))return true;if(object(v)){if(f.kind==='map')return true;const fields=f.children.filter(x=>!metadataFields.has(x.name));return fields.length?fields.some(x=>resourcePresent(v[x.name],x)):Object.keys(v).some(k=>!metadataFields.has(k));}return true;}
function writeReceiptPresent(v,f){if(object(v)&&f.children.some(x=>x.result_flag&&(trueValue(v[x.name])||falseValue(v[x.name]))))return true;return resourcePresent(v,f);}
function correlate(requested,rows,key){if(!Array.isArray(rows)||rows.length!==requested.length)fail('E_TOOL_CALL_UPSTREAM','Youzan omitted individual business receipts; inspect results before retrying');const returned=rows.map(r=>String(r[key]));if(new Set(returned).size!==returned.length||returned.some(id=>!requested.includes(id)))fail('E_TOOL_CALL_UPSTREAM','Youzan returned duplicate or unrelated business receipts');}
function receipt(row,p,body,config){
if(row.method==='youzan.item.quantity.update'&&typeof body.data?.success!=='boolean')fail('E_TOOL_CALL_UPSTREAM','Youzan omitted the stock update receipt');
if(row.method==='youzan.item.delete'&&(!object(body.data)||typeof body.data.is_success!=='boolean'||String(body.data.item_id)!==String(p.item_id)))fail('E_TOOL_CALL_UPSTREAM','Youzan returned an incomplete or unrelated product deletion receipt');
if(row.method==='youzan.salesman.order.operate.settle'){correlate(p.order_settle_open_d_t_o.tids,body.data,'tid');if(body.data.some(r=>String(r.kdt_id)!==binding(config)||![r.cps_order_settle_res,r.bonus_order_settle_res].some(v=>typeof v?.is_success==='boolean')))fail('E_TOOL_CALL_UPSTREAM','Youzan omitted an attributable settlement receipt');}
if(row.method==='youzan.logistics.waybill.apply'){correlate(p.trade_order_info_list.map(r=>r.apply_id),body.data,'apply_id');if(body.data.some(r=>typeof r.success!=='boolean'||r.success&&(typeof r.express_no!=='string'||!r.express_no||r.code!==undefined&&r.code!==null&&r.code!==200)))fail('E_TOOL_CALL_UPSTREAM','Youzan omitted a valid waybill receipt');}
if(row.method==='youzan.item.sku.batch.update'){if(!Array.isArray(body.data?.fail_list))fail('E_TOOL_CALL_UPSTREAM','Youzan omitted the SKU batch failure list');const wanted=new Map(p.item_skus_list.map(r=>[String(r.item_id),new Set(r.skus.map(s=>String(s.sku_id)))])),seen=new Set();for(const r of body.data.fail_list){if(!wanted.has(String(r.item_id))||!Array.isArray(r.sku_list))fail('E_TOOL_CALL_UPSTREAM','Youzan returned an unrelated failed product');for(const sku of r.sku_list){const key=String(r.item_id)+':'+String(sku.sku_id);if(!wanted.get(String(r.item_id)).has(String(sku.sku_id))||seen.has(key))fail('E_TOOL_CALL_UPSTREAM','Youzan returned a duplicate or unrelated failed SKU');seen.add(key);}}}
if(row.method==='youzan.item.attribute.create'){if(p.request?.values)correlate(p.request.values.map(v=>v.name),body.data?.item_attribute_values,'name');if(String(body.data?.kdt_id)!==binding(config))fail('E_TOOL_CALL_AUTH','Youzan returned a different shop attribute');}
if(row.method==='youzan.ump.voucher.batch.send.callback'){const rows=body.data?.send_success_vouchers;if(!Array.isArray(rows)||typeof body.data.is_sent!=='boolean'||rows.some(r=>!p.verify_codes.includes(r.verify_code))||new Set(rows.map(r=>r.verify_code)).size!==rows.length)fail('E_TOOL_CALL_UPSTREAM','Youzan omitted attributable voucher results');if(body.data.is_sent&&rows.length!==p.verify_codes.length)fail('E_TOOL_CALL_UPSTREAM','Youzan reported completion with missing voucher receipts');}
}
function outcome(row,body,config,p){
if(!object(body)||body.error_response!==undefined&&body.error_response!==null)fail('E_TOOL_CALL_UPSTREAM','Youzan rejected the request; check the operation and application permission');
const modern=row.output_tree.some(f=>f.name==='code');
if(modern&&(!trueValue(body.success)||String(body.code)!=='200')){if(['4200','4201','4202','4203','40006'].includes(String(body.code)))fail('E_TOOL_CALL_AUTH','Youzan application permission or shop authorization is missing');fail('E_TOOL_CALL_UPSTREAM','Youzan did not acknowledge the request; check application permissions and the requested resource');}
const data=normalize(body,row.output_tree);const business=row.output_tree.filter(f=>!['code','success','message','request_id','requestId','trace_id','error_data','error_response'].includes(f.name));
if(business.length&&!business.some(f=>row.risk==='R'?resourcePresent(data[f.name],f):writeReceiptPresent(data[f.name],f)))fail('E_TOOL_CALL_UPSTREAM','Youzan omitted the documented business result');
if(!modern&&!business.length)fail('E_TOOL_CALL_UPSTREAM','Youzan omitted its response receipt');
if(row.method==='youzan.shop.get'){const shop=data.data||data.response;if(!object(shop)||String(shop.id??shop.kdt_id)!==binding(config))fail('E_TOOL_CALL_AUTH','Youzan returned a different shop; reconnect');}
receipt(row,p,data,config);const bad=partial(data,row.output_tree);if(row.risk==='R'&&bad)fail('E_TOOL_CALL_UPSTREAM','Youzan could not return the requested resource');
return{data,...(row.risk==='R'?{}:{status:bad?'partial_or_failed':'accepted',follow_up:'Inspect the returned per-item results and read back the resource or asynchronous task before treating the change as complete. Do not automatically retry an uncertain write.'})};
}
const secretNames=new Set(['access_token','refresh_token','client_secret','authorization','cookie']);
function sanitize(v,credentials,fields=[]){const secrets=['access_token','refresh_token','client_secret'].map(k=>credentials[k]).filter(x=>typeof x==='string'&&x.length>=3);function clean(x,n,tree){if(n>40)fail('E_TOOL_CALL_UPSTREAM','Youzan response exceeds the nesting limit');if(typeof x==='string'){for(const s of secrets)x=x.split(s).join('[redacted]');return x;}if(Array.isArray(x))return x.map(y=>clean(y,n+1,tree));if(!object(x))return x;const by=new Map(tree.map(f=>[f.name,f]));return Object.fromEntries(Object.entries(x).filter(([k])=>!secretNames.has(k.toLowerCase())&&!by.get(k)?.diagnostic&&!(n===0&&['message','request_id','requestId','trace_id','error_data'].includes(k))).map(([k,y])=>[k,clean(y,n+1,by.get(k)?.children||[])]));}return clean(v,0,fields);}
async function execute(config,name,p={},owner){const row=source().methods[name];if(!row)fail('E_BAD_INPUT','Unknown Youzan merchant action');binding(config);if(!permitted(row,config))fail('E_TOOL_CALL_AUTH','This Youzan action does not support the connected shop type');validate(row,p,config);
let token;try{token=await owner.token(config);}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'].includes(error?.code)?error.code:'E_TOOL_CALL_AUTH','Youzan authorization could not be refreshed');}binding(config);if(!permitted(row,config))fail('E_TOOL_CALL_AUTH','The refreshed Youzan shop type does not support this action');validate(row,p,config);
const url=new URL('https://open.youzanyun.com/api/'+row.method+'/'+row.version);url.searchParams.set('access_token',token);const deadline=AbortSignal.timeout(60000);let response,text;
try{response=await requestFetch(url.toString(),{method:'POST',redirect:'error',signal:deadline,headers:{'content-type':'application/json',accept:'application/json'},body:wire(row,p)});}catch(error){fail(requestFailureCode(error,deadline),'Youzan request failed; check resource state before retrying an uncertain write');}
if(!response.ok)throw httpFailure(response.status,'Youzan request failed; check shop authorization and application permissions');
try{text=await readBody(response);}catch(error){fail(error?.code==='E_CONNECTOR_RESPONSE_TOO_LARGE'?'E_TOOL_CALL_UPSTREAM':requestFailureCode(error,deadline),'Youzan response could not be read completely');}
let body;try{body=parse(text);}catch{fail('E_TOOL_CALL_UPSTREAM','Youzan returned invalid or imprecise JSON');}const result=outcome(row,body,config,p);return{...result,data:sanitize(result.data,config.credentials,row.output_tree)};
}
function validateResponseShape(name,text){const row=source().methods[name];if(!row)fail('E_BAD_INPUT','Unknown Youzan action');return normalize(parse(text),row.output_tree);}
module.exports={actionsFor,isNative,execute,parse,sanitize,validateResponseShape};