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 contract,actions,validator;const checks=new Map(),source=()=>contract ||= require('./kuaishou-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);
const resolve=(s,root,value)=>{if(s?.$ref)s=root.$defs[s.$ref.split('/').at(-1)];if(s?.anyOf&&!s['x-integer']&&!s['x-number']&&value!==undefined){const match=s.anyOf.find(x=>{x=resolve(x,root);return x?.type==='array'?Array.isArray(value):x?.type==='object'?object(value):x?.['x-integer']?Number.isSafeInteger(value)||typeof value==='string':x?.type==='integer'?Number.isInteger(value):typeof value===x?.type;});if(match)return resolve(match,root,value);}return s;};
const child=(s,k,root)=>{s=resolve(s,root);return s?.properties?.[k]||(object(s?.additionalProperties)?s.additionalProperties:undefined);};
function scopes(config){const value=config.credentials?.scope;return new Set((Array.isArray(value)?value:String(value||'').split(/[\s,]+/)).filter(Boolean));}
function allowed(row,config){const granted=scopes(config);return row.scopes.some(x=>granted.has(x));}
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}]));return Object.fromEntries(Object.entries(actions).filter(([name])=>allowed(source().methods[name],config)));}
function walk(v,s,root,fn,depth=0){if(depth>40)fail('E_BAD_INPUT','Kuaishou parameters are too deeply nested');s=resolve(s,root,v);fn(v,s);if(Array.isArray(v))v.forEach(x=>walk(x,s?.items,root,fn,depth+1));else if(object(v))for(const [k,x]of Object.entries(v))walk(x,child(s,k,root),root,fn,depth+1);}
function binding(config){const c=config.credentials;if(!c||!/^[1-9]\d{0,18}$/.test(String(c.identity?.shop_id))||typeof c.identity?.open_id!=='string'||!c.identity.open_id)fail('E_TOOL_CALL_AUTH','Kuaishou merchant binding is missing');}
const memberBatches={ 'open.member.batch.update.basic':['basicChangeInfo','data'], 'open.member.batch.update.level':['levelChangeInfo','updateResultList'], 'open.member.batch.update.point':['pointChangeInfo','data'], 'open.merchant.member.batch.update.basic':['memberChangeInfo','data'], 'open.merchant.member.batch.update.level':['levelChangeInfo','data'], 'open.merchant.member.batch.update.point':['pointChangeInfo','data'] };
function validate(row,p,config){let bytes;try{bytes=Buffer.byteLength(JSON.stringify(p));}catch{fail('E_BAD_INPUT','Invalid Kuaishou parameters');}if(bytes>262144)fail('E_BAD_INPUT','Kuaishou parameters exceed 256 KiB');
walk(p,row.input_schema,row.input_schema,(v,s)=>{if(typeof v==='number'&&(!Number.isFinite(v)||Number.isInteger(v)&&!Number.isSafeInteger(v)))fail('E_BAD_INPUT','Use the documented exact integer string for large Kuaishou IDs');if(config&&s?.['x-binding']&&String(v)!==String(config.credentials.identity[s['x-binding']]))fail('E_BAD_INPUT','Kuaishou 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 Kuaishou parameters; check described fields, required values and types');
walk(p,row.input_schema,row.input_schema,(v,s)=>{if(s?.['x-integer']&&(BigInt(v)<-9223372036854775808n||BigInt(v)>9223372036854775807n))fail('E_BAD_INPUT','Kuaishou int64 exceeds its documented range');if(s?.['x-decimalPlaces']!==undefined&&Math.abs(Number(v)*10**s['x-decimalPlaces']-Math.round(Number(v)*10**s['x-decimalPlaces']))>1e-8)fail('E_BAD_INPUT','Kuaishou numeric value exceeds the documented decimal places');if(s?.['x-number']&&!Number.isFinite(Number(v)))fail('E_BAD_INPUT','Invalid Kuaishou numeric value');for(const [key,compare]of [['x-minimum',(a,b)=>a<b],['x-maximum',(a,b)=>a>b],['x-exclusiveMinimum',(a,b)=>a<=b],['x-exclusiveMaximum',(a,b)=>a>=b]])if(s?.[key]!==undefined){const cast=s['x-integer']?BigInt:Number;if(compare(cast(v),cast(s[key])))fail('E_BAD_INPUT','Kuaishou numeric value exceeds its documented bounds');}});
const windowDays={'open.order.cursor.list':7,'open.seller.order.cps.list':1,'open.seller.order.refund.pcursor.list':1}[row.action];if(windowDays){const begin=BigInt(p.beginTime),end=BigInt(p.endTime),now=BigInt(Date.now());if(begin>=end||end-begin>BigInt(windowDays*86400000)||begin<now-90n*86400000n||end>now+60000n)fail('E_BAD_INPUT','Kuaishou query time range is outside the documented window');}
const member=memberBatches[row.action];if(member){const rows=p[member[0]];if(!Array.isArray(rows)||!rows.length||rows.some(x=>typeof x.openId!=='string'||!x.openId)||new Set(rows.map(x=>x.openId)).size!==rows.length)fail('E_BAD_INPUT','Provide a nonempty batch of distinct member identities');}
if(row.action==='open.express.ebill.get'){const rows=p.getEbillOrderRequest,ids=rows.map(x=>x.requestId);if(!rows.length||new Set(ids).size!==ids.length)fail('E_BAD_INPUT','Provide distinct waybill request identifiers');if(config&&rows.some(x=>![config.credentials.identity.shop_id,config.credentials.identity.open_id].includes(x.merchantCode)))fail('E_BAD_INPUT','Waybill requests must use the bound merchant');if(rows.reduce((sum,x)=>sum+Number(x.totalPackageQuantity??1),0)>10)fail('E_BAD_INPUT','Waybill requests may allocate at most ten packages');}
}
function defaults(v,s,root){s=resolve(s,root);if(Array.isArray(v))return v.map(x=>defaults(x,s?.items,root));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,root);}return out;}
function wire(v,s,root){s=resolve(s,root);if(s?.['x-integer']||s?.['x-number'])return String(v);if(Array.isArray(v))return '['+v.map(x=>wire(x,s?.items,root)).join(',')+']';if(object(v))return '{'+Object.keys(v).filter(k=>v[k]!==undefined).sort().map(k=>JSON.stringify(k)+':'+wire(v[k],child(s,k,root),root)).join(',')+'}';return JSON.stringify(v);}
// Trusted legacy owner calls use official method names unchanged (including open.).
// Only canonical safe int32 strings are normalized; scope/binding remain the owner's responsibility.
function serializeParameters(name,p={}){const row=source().methods[name];if(!row)fail('E_BAD_INPUT','Unknown Kuaishou merchant action');function normalize(v,s,depth=0){if(depth>40)fail('E_BAD_INPUT','Kuaishou parameters are too deeply nested');s=resolve(s,row.input_schema,v);if(s?.type==='integer'&&typeof v==='string'&&/^-?(0|[1-9][0-9]*)$/.test(v)&&Number.isSafeInteger(Number(v)))return Number(v);if(Array.isArray(v))return v.map(x=>normalize(x,s?.items,depth+1));if(object(v))return Object.fromEntries(Object.entries(v).filter(([,x])=>x!==undefined).map(([k,x])=>[k,normalize(x,child(s,k,row.input_schema),depth+1)]));return v;}p=normalize(p,row.input_schema);validate(row,p);return wire(defaults(p,row.input_schema,row.input_schema),row.input_schema,row.input_schema);}
class IntegerToken{constructor(value){this.value=value;}}
function parse(text,schema){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','Kuaishou response is too deeply nested');}else if(c==='}'||c===']')depth--;}
const value=JSON.parse(text,(_k,v,c)=>typeof v==='number'&&!Number.isSafeInteger(v)&&/^-?[0-9]+$/.test(c.source)?new IntegerToken(c.source):v);
function restore(v,s){s=resolve(s,schema,v instanceof IntegerToken?0:v);if(v instanceof IntegerToken)return s?.type==='number'?Number(v.value):v.value;if(typeof v==='number'&&(!Number.isFinite(v)||s?.type!=='number'&&Number.isInteger(v)&&!Number.isSafeInteger(v)))fail('E_TOOL_CALL_UPSTREAM','Kuaishou returned an imprecise integer');if(Array.isArray(v))return v.map(x=>restore(x,s?.items));if(object(v))return Object.fromEntries(Object.entries(v).map(([k,x])=>[k,restore(x,child(s,k,schema))]));return v;}return restore(value,schema);
}
function typed(v,s,root){s=resolve(s,root,v);if(s?.anyOf&&!s['x-integer']&&!s['x-number'])return s.anyOf.some(x=>typed(v,x,root));if(v===null||!s)return true;if(s['x-integer'])return Number.isSafeInteger(v)||typeof v==='string'&&/^-?[0-9]+$/.test(v);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.type==='object')return object(v)&&(!s['x-pageLists']||s['x-pageLists'].every(k=>Array.isArray(v[k])))&&Object.entries(v).every(([k,x])=>typed(x,child(s,k,root),root));if(s.type==='array')return Array.isArray(v)&&v.every(x=>typed(x,s.items,root));if(s.type==='integer')return Number.isSafeInteger(v);return typeof v===s.type;}
function partial(v,s,root){s=resolve(s,root,v);if(Array.isArray(v))return v.some(x=>partial(x,s?.items,root));if(!object(v))return false;for(const [k,x]of Object.entries(v)){const f=child(s,k,root);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(f['x-resultBoolean']&&x===false)return true;if(f['x-successValues']&&x!==null&&!f['x-successValues'].includes(String(x)))return true;if(partial(x,f,root))return true;}return false;}
function businessPresent(v,s,root){s=resolve(s,root,v);if(v===undefined||v===null)return false;if(s?.type==='object'&&Object.keys(s.properties||{}).length)return object(v)&&Object.keys(s.properties).some(k=>v[k]!==undefined&&v[k]!==null);return true;}
function correlate(expected,actual,key){if(!Array.isArray(actual)||actual.length!==expected.length)fail('E_TOOL_CALL_UPSTREAM','Kuaishou omitted individual business acknowledgements');const ids=actual.map(x=>String(x[key]));if(new Set(ids).size!==ids.length||ids.some(x=>!expected.includes(x)))fail('E_TOOL_CALL_UPSTREAM','Kuaishou returned duplicate or unrelated business acknowledgements');}
const diagnostic=new Set(['code','msg','sub_code','sub_msg','result','error_msg','errorMsg']);
function ack(row,p,body,config){if(!object(body)||body.result!==1){if(['100200101','100200102','100200106','100200107'].includes(String(body?.result)))fail('E_TOOL_CALL_AUTH','Kuaishou authorization is invalid or lacks the required scope');fail('E_TOOL_CALL_UPSTREAM','Kuaishou rejected the request or omitted its success result');}if(!typed(body,row.output_schema,row.output_schema))fail('E_TOOL_CALL_UPSTREAM','Kuaishou returned fields with invalid types');
const business=Object.keys(row.output_schema.properties).filter(k=>!diagnostic.has(k)&&!['cursor','pcursor','total','baseRespInfo'].includes(k));if(business.length&&!business.some(k=>businessPresent(body[k],row.output_schema.properties[k],row.output_schema)))fail('E_TOOL_CALL_UPSTREAM','Kuaishou omitted the documented business response');
if(row.path==='/open/user/seller/get'&&(String(body.data?.sellerId)!==String(config.credentials.identity.shop_id)||body.data?.openId!==config.credentials.identity.open_id))fail('E_TOOL_CALL_AUTH','Kuaishou seller no longer matches the bound merchant');
const member=memberBatches[row.action];if(member){const rows=body[member[1]];correlate(p[member[0]].map(x=>x.openId),rows,'openId');if(rows.some(x=>typeof x.result!=='boolean'))fail('E_TOOL_CALL_UPSTREAM','Kuaishou omitted member result flags');}
if(row.action==='open.express.ebill.get'){correlate(p.getEbillOrderRequest.map(x=>x.requestId),body.data,'requestId');if(body.data.some(x=>typeof x.baseResponse?.success!=='boolean'||x.baseResponse.success&&(!Array.isArray(x.data)||!x.data.length||x.data.some(y=>typeof y.waybillCode!=='string'||!y.waybillCode))))fail('E_TOOL_CALL_UPSTREAM','Kuaishou omitted waybill success or business identifiers');}
if(row.action==='open.item.new'&&(!body.data?.kwaiItemId||!Array.isArray(body.data?.skuIdMapping)))fail('E_TOOL_CALL_UPSTREAM','Kuaishou omitted created product or SKU identifiers');
if(partial(body,row.output_schema,row.output_schema))return 'partial_or_failed';return row.risk==='R'?undefined:'accepted';
}
const secretKeys=new Set(['accesstoken','refreshtoken','appsecret','appkey','signsecret','clientsecret','authorization','password','cookie','sign']);
function sanitize(data,credentials={},schema){const values=['access_token','refresh_token','app_secret','app_key','sign_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','Kuaishou response is too deeply nested');s=resolve(s,schema,v);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===0&&['msg','sub_msg','error_msg','errorMsg'].includes(k))&&!child(s,k,schema)?.['x-diagnostic']).map(([k,x])=>[k,clean(x,child(s,k,schema),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 Kuaishou merchant action');binding(config);if(!allowed(row,config))fail('E_TOOL_CALL_AUTH','Kuaishou grant does not include this action scope');validate(row,p,config);p=defaults(p,row.input_schema,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)$/.test(error?.code)?error.code:'E_TOOL_CALL_AUTH','Kuaishou authorization could not be refreshed');}binding(config);if(!allowed(row,config))fail('E_TOOL_CALL_AUTH','Kuaishou refreshed grant no longer includes this action scope');
const c=config.credentials,common={appkey:c.app_key,method:name,version:row.version,param:wire(p,row.input_schema,row.input_schema),access_token:token,timestamp:String(Date.now()),signMethod:'HMAC_SHA256'};common.sign=owner.sign(common,c.sign_secret);const url=new URL('https://openapi.kwaixiaodian.com'+row.path),form=new URLSearchParams(common).toString(),deadline=AbortSignal.timeout(60000),options={method:row.method,redirect:'error',signal:deadline,headers:{accept:'application/json'}};if(row.method==='GET')url.search=form;else{options.body=form;options.headers['content-type']='application/x-www-form-urlencoded';}
let response,text;try{response=await requestFetch(url.toString(),options);}catch(error){fail(requestFailureCode(error,deadline),'Kuaishou request failed; inspect resource state before retrying an uncertain write');}if(!response.ok)throw httpFailure(response.status,'Kuaishou request failed; check authorization and method permissions');try{text=await readBody(response);}catch(error){fail(error?.code==='E_CONNECTOR_RESPONSE_TOO_LARGE'?'E_TOOL_CALL_UPSTREAM':requestFailureCode(error,deadline),'Kuaishou response could not be read completely');}
let body;try{body=parse(text,row.output_schema);}catch{fail('E_TOOL_CALL_UPSTREAM','Kuaishou returned invalid or imprecise JSON');}const status=ack(row,p,body,config);return {data:sanitize(body,c,row.output_schema),...(status?{status}:{}),...(status==='accepted'?{follow_up:'Read back the resource or task status before treating the change as complete. Do not automatically retry.'}:{})};
}
module.exports={actionsFor,isNative,execute,sanitize,parse,serializeParameters};