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 owner=require('./marketplace-seller-api.cjs');
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('./shopee-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 type=s=>Array.isArray(s?.type)?s.type.find(x=>x!=='null'):s?.type;
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}]));}
function walk(v,s,fn,depth=0){if(depth>40)fail('E_BAD_INPUT','Shopee 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,s?.properties?.[k],fn,depth+1);}
function validate(row,p){let bytes;try{bytes=Buffer.byteLength(JSON.stringify(p));}catch{fail('E_BAD_INPUT','Invalid Shopee parameters');}if(bytes>256*1024)fail('E_BAD_INPUT','Shopee parameters exceed 256 KiB');
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 Shopee parameters; check the described fields and types');
walk(p,row.input_schema,(v,s)=>{if(s?.['x-integer']){const n=BigInt(v),unsigned=s['x-integer']==='uint64';if(n<(unsigned?0n:-9223372036854775808n)||n>(unsigned?18446744073709551615n:9223372036854775807n)||s['x-minInteger']!==undefined&&n<BigInt(s['x-minInteger'])||s['x-maxInteger']!==undefined&&n>BigInt(s['x-maxInteger']))fail('E_BAD_INPUT','Shopee integer exceeds its documented range');}if(s?.['x-csvMax']&&(v.split(',').some(x=>!x.trim())||v.split(',').length>s['x-csvMax']))fail('E_BAD_INPUT','Shopee identifier list exceeds the documented or host bound');if(s?.['x-pageMax']&&Number(v)>s['x-pageMax'])fail('E_BAD_INPUT','Shopee page exceeds the documented or host bound');if(typeof v==='number'&&!Number.isFinite(v))fail('E_BAD_INPUT','Invalid Shopee number');});
for(const fields of [['time_from','time_to'],['create_time_from','create_time_to'],['update_time_from','update_time_to']]){const [a,b]=fields;if(p[a]!==undefined&&p[b]!==undefined&&Number(p[b])<Number(p[a]))fail('E_BAD_INPUT','Shopee time range is reversed');}
if(row.path==='/api/v2/order/get_order_list'&&p.time_to-p.time_from>15*86400)fail('E_BAD_INPUT','Shopee order time range must not exceed 15 days');
for(const field of ['price_list','stock_list'])if(Array.isArray(p[field])){const ids=p[field].map(x=>String(x.model_id));if(new Set(ids).size!==ids.length)fail('E_BAD_INPUT','Provide each Shopee model once');}
if(p.stock_list&&p.stock_list.reduce((n,x)=>n+(x.seller_stock?.length||1),0)>10)fail('E_BAD_INPUT','Shopee stock targets exceed the existing high-impact batch limit');
}
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,child]of Object.entries(s.properties||{})){if(out[k]===undefined&&child['x-pageMax'])out[k]=child.default;if(out[k]!==undefined)out[k]=defaults(out[k],child);}return out;}
function wire(v,s){if(s?.['x-integer'])return String(v);if(Array.isArray(v))return '['+v.map(x=>wire(x,s?.items)).join(',')+']';if(object(v))return '{'+Object.entries(v).map(([k,x])=>JSON.stringify(k)+':'+wire(x,s?.properties?.[k])).join(',')+'}';return JSON.stringify(v);}
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','Shopee 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){if(v instanceof IntegerToken){if(type(s)==='number')return Number(v.value);return v.value;}if(typeof v==='number'&&(!Number.isFinite(v)||type(s)!=='number'&&Number.isInteger(v)&&!Number.isSafeInteger(v)))fail('E_TOOL_CALL_UPSTREAM','Shopee 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,s?.properties?.[k])]));return v;}return restore(value,schema);
}
function typed(v,s){if(v===null)return true;if(s['x-integer'])return Number.isSafeInteger(v)||typeof v==='string'&&/^-?[0-9]+$/.test(v);if(type(s)==='object')return object(v)&&Object.entries(v).every(([k,x])=>!s.properties[k]||typed(x,s.properties[k]));if(type(s)==='array')return Array.isArray(v)&&v.every(x=>typed(x,s.items));if(type(s)==='integer')return Number.isSafeInteger(v);return typeof v===type(s);}
const envelopeFields=new Set(['error','message','msg','error_msg','warning','request_id','timestamp']);
function partial(v){if(Array.isArray(v))return v.some(partial);if(!object(v))return false;for(const [k,x]of Object.entries(v)){if(/^(failure_list|failure_item_list|failed_list|failed_edits|fail_list|error_list)$/.test(k)&&Array.isArray(x)&&x.length)return true;if(/^(failed_count|failure_count)$/.test(k)&&typeof x==='number'&&x>0)return true;if(['success','is_success'].includes(k)&&x===false)return true;if(['error','fail_error'].includes(k)&&x!==''&&x!==0&&x!==null&&x!==undefined)return true;if(partial(x))return true;}return false;}
function ack(row,p,body){if(!object(body))fail('E_TOOL_CALL_UPSTREAM','Shopee returned an invalid envelope');const error=body.error;if(error!==undefined&&error!==''&&error!==0||Object.hasOwn(row.output_schema.properties,'error')&&error===undefined){if(typeof error==='string'&&/auth|token|permission|sign/i.test(error))fail('E_TOOL_CALL_AUTH','Shopee denied this method; check shop authorization and app permissions');if(typeof error==='string'&&/rate|frequency|limit_exceed/i.test(error))fail('E_TOOL_CALL_RATE_LIMIT','Shopee rate limit reached');fail('E_TOOL_CALL_UPSTREAM','Shopee rejected the request or omitted its result code');}
if(row.name==='v2.business_insights.get_marketing_hot_listing'&&body.code!==0)fail('E_TOOL_CALL_UPSTREAM','Shopee rejected the report request');if(row.name==='v2.shop.get_shop_info'&&(typeof body.shop_name!=='string'||!body.shop_name||typeof body.region!=='string'||!body.region))fail('E_TOOL_CALL_UPSTREAM','Shopee omitted shop identity');
if(!typed(body,row.output_schema))fail('E_TOOL_CALL_UPSTREAM','Shopee returned fields with invalid types');const business=Object.keys(row.output_schema.properties).filter(k=>!envelopeFields.has(k));if(business.length&&!business.some(k=>body[k]!==null&&body[k]!==undefined))fail('E_TOOL_CALL_UPSTREAM','Shopee omitted its business acknowledgement');
const data=body.response??body;if(object(data)&&business.includes('response')&&Object.keys(row.output_schema.properties.response.properties||{}).length&&!Object.keys(data).some(k=>Object.hasOwn(row.output_schema.properties.response.properties,k)))fail('E_TOOL_CALL_UPSTREAM','Shopee omitted its business data');
if(['v2.product.update_price','v2.product.update_stock'].includes(row.name)){
if(!Array.isArray(data.success_list)||!Array.isArray(data.failure_list))fail('E_TOOL_CALL_UPSTREAM','Shopee omitted individual model acknowledgements');
const requested=new Map((p.price_list||p.stock_list).map(x=>[String(x.model_id??0),x])),failed=new Set(),seen=new Set();
for(const item of data.failure_list){const id=String(item.model_id);if(!requested.has(id)||failed.has(id))fail('E_TOOL_CALL_UPSTREAM','Shopee returned duplicate or unrelated model failures');failed.add(id);}
for(const item of data.success_list){const id=String(item.model_id),request=requested.get(id);if(!request||failed.has(id))fail('E_TOOL_CALL_UPSTREAM','Shopee returned conflicting or unrelated model acknowledgements');const key=row.name==='v2.product.update_stock'?id+':'+String(item.location_id??''):id;if(seen.has(key))fail('E_TOOL_CALL_UPSTREAM','Shopee returned duplicate model acknowledgements');seen.add(key);if(row.name==='v2.product.update_stock'){const stock=request.seller_stock.find(x=>String(x.location_id??'')===String(item.location_id??''));if(!stock||String(stock.stock)!==String(item.stock))fail('E_TOOL_CALL_UPSTREAM','Shopee returned an unrelated stock-location acknowledgement');}}
for(const [id,request]of requested)if(!failed.has(id)){const keys=row.name==='v2.product.update_stock'?request.seller_stock.map(x=>id+':'+String(x.location_id??'')):[id];if(keys.some(k=>!seen.has(k)))fail('E_TOOL_CALL_UPSTREAM','Shopee omitted a model or stock-location acknowledgement');}
}
if(row.name==='v2.logistics.mass_ship_order'){if(!Array.isArray(body.success_list)||!Array.isArray(body.fail_list))fail('E_TOOL_CALL_UPSTREAM','Shopee omitted package acknowledgements');const expected=p.package_list.map(x=>x.package_number),actual=[...body.success_list,...body.fail_list].map(x=>x.package_number);if(actual.length!==expected.length||new Set(actual).size!==actual.length||actual.some(x=>!expected.includes(x)))fail('E_TOOL_CALL_UPSTREAM','Shopee returned incomplete package acknowledgements');}
if(partial(body))return 'partial_or_failed';
if(row.name==='v2.product.get_batch_task_result'){if(![1,2].includes(data.publish_status))fail('E_TOOL_CALL_UPSTREAM','Shopee omitted task completion state');return data.publish_status===1?'accepted':'acknowledged';}
const taskStates={
'v2.media_space.get_video_upload_result':{field:'status',pending:['INITIATED','TRANSCODING'],success:['SUCCEEDED'],failed:['FAILED','CANCELLED']},
'v2.media.get_video_upload_result':{field:'status',pending:['INITIATED','UPLOADING','UPLOADED','PROCESSING'],success:['SUCCEEDED'],failed:['FAILED','CANCELLED']},
'v2.logistics.get_shipping_document_job_status':{field:'job_status',pending:['PROCESSING'],success:['READY'],failed:['FAILED','EXPIRED']},
'v2.logistics.check_polygon_update_status':{field:'status',pending:[1],success:[0],failed:[2]},
'v2.payment.get_income_statement':{field:'status',pending:[1],success:[2,3],failed:[0,4]},
'v2.payment.get_income_report':{field:'status',pending:[1],success:[2,3],failed:[0,4]},
'v2.logistics.update_tracking_status':{field:'update_result',pending:[],success:['succeed'],failed:['failed']},
};const task=taskStates[row.name];if(task){const state=data[task.field];if(task.pending.includes(state))return 'accepted';if(task.failed.includes(state))return 'partial_or_failed';if(task.success.includes(state))return 'acknowledged';fail('E_TOOL_CALL_UPSTREAM','Shopee returned an unknown task result');}
if(row.risk==='R')return undefined;
if(Object.hasOwn(row.output_schema.properties.response?.properties||{},'task_id')&&(typeof data.task_id!=='number'&&typeof data.task_id!=='string'))fail('E_TOOL_CALL_UPSTREAM','Shopee omitted the asynchronous task identifier');
return 'accepted';
}
const secrets=new Set(['accesstoken','refreshtoken','partnerkey','clientsecret','authorization','password','cookie','sign']);
function redact(v,values,s,depth=0){if(typeof v==='string'){for(const secret of values)if(secret)v=v.split(secret).join('[redacted]');return v;}if(Array.isArray(v))return v.map(x=>redact(x,values,s?.items,depth));if(!object(v))return v;return Object.fromEntries(Object.entries(v).filter(([k])=>!secrets.has(k.replace(/[_-]/g,'').toLowerCase())&&!(depth===0&&['message','msg','error_msg','warning','debug_message'].includes(k))&&!(s?.properties?.[k]&&['fail_message','failed_reason','fail_reason','warning'].includes(k))&&!(s?.properties?.[k]&&['message','msg'].includes(k)&&/error/i.test(s.properties[k].description||''))).map(([k,x])=>[k,redact(x,values,s?.properties?.[k],depth+1)]));}
async function execute(config,name,p={}){const raw=source().methods[name];if(!raw)fail('E_BAD_INPUT','Unknown Shopee merchant action');const row={...raw,name};owner.validateBinding(config);validate(row,p);p=defaults(p,row.input_schema);
let token;try{await owner.ensureToken(config);token=config.credentials.access_token;}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','Shopee authorization could not be refreshed');}
const timestamp=Math.floor(Date.now()/1000),c=config.credentials,url=new URL(owner.apiBase('shopee',config.metadata)+row.path);url.searchParams.set('partner_id',c.partner_id);url.searchParams.set('timestamp',String(timestamp));if(row.identity==='Shop'){url.searchParams.set('access_token',token);url.searchParams.set('shop_id',config.metadata.shop_id);}url.searchParams.set('sign',owner.signShopee(c.partner_id,row.path,timestamp,c.partner_key,row.identity==='Shop'?token:'',row.identity==='Shop'?config.metadata.shop_id:''));
if(row.method==='GET')for(const [k,v]of Object.entries(p)){const s=row.input_schema.properties[k];url.searchParams.set(k,Array.isArray(v)&&s.items.type!=='object'?v.join(','):object(v)||Array.isArray(v)?wire(v,s):String(v));}
const deadline=AbortSignal.timeout(60000);let response,text;try{response=await requestFetch(url.toString(),{method:row.method,redirect:'error',signal:deadline,headers:{accept:'application/json',...(row.method==='POST'?{'content-type':'application/json'}:{})},...(row.method==='POST'?{body:wire(p,row.input_schema)}:{})});}catch(error){fail(requestFailureCode(error,deadline),'Shopee request failed; inspect the resource before retrying an uncertain write');}if(!response.ok)throw httpFailure(response.status,'Shopee request failed; check authorization and resource state');try{text=await readBody(response);}catch(error){fail(error?.code==='E_CONNECTOR_RESPONSE_TOO_LARGE'?'E_TOOL_CALL_UPSTREAM':requestFailureCode(error,deadline),'Shopee response could not be read completely');}
let body;try{body=parse(text,row.output_schema);}catch{fail('E_TOOL_CALL_UPSTREAM','Shopee returned invalid or imprecise JSON');}const status=ack(row,p,body);return {data:redact(body,[c.partner_key,c.access_token,c.refresh_token,token],row.output_schema),...(status?{status}:{}),...(status==='accepted'?{follow_up:'Verify task status or read back each affected resource before treating the change as complete; do not retry automatically.'}:{})};
}
module.exports={actionsFor,isNative,execute};