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('./douyin-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),child=(s,k)=>s?.properties?.[k]||(object(s?.additionalProperties)?s.additionalProperties:undefined);
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,path=[]){if(depth>40)fail('E_BAD_INPUT','Douyin parameters are too deeply nested');fn(v,s,path);if(Array.isArray(v))v.forEach(x=>walk(x,s?.items,fn,depth+1,path));else if(object(v))for(const [k,x]of Object.entries(v))walk(x,child(s,k),fn,depth+1,[...path,k]);}
function binding(config){const {metadata:m,credentials:c}=config;if(!m||!c||!/^[1-9]\d{0,24}$/.test(String(m.shop_id))||String(c.identity?.shop_id)!==String(m.shop_id))fail('E_TOOL_CALL_AUTH','Douyin shop binding does not match the verified grant');}
function validate(row,p,config){let bytes;try{bytes=Buffer.byteLength(JSON.stringify(p));}catch{fail('E_BAD_INPUT','Invalid Douyin parameters');}if(bytes>262144)fail('E_BAD_INPUT','Douyin 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 Douyin parameters; check described fields, required values and types');
walk(p,row.input_schema,(v,s,path)=>{if(typeof v==='number'&&!Number.isFinite(v))fail('E_BAD_INPUT','Invalid Douyin number');if(s?.['x-integer']&&(BigInt(v)<-9223372036854775808n||BigInt(v)>9223372036854775807n))fail('E_BAD_INPUT','Douyin int64 exceeds its documented range');if(s?.['x-number']&&!Number.isFinite(Number(v)))fail('E_BAD_INPUT','Invalid Douyin numeric value');if(s?.['x-separatedMax']&&v.split(s['x-separator']).length>s['x-separatedMax'])fail('E_BAD_INPUT','Douyin identifier list exceeds the host bound');
if(['shop_id','merge_shop_id'].includes(path.at(-1))&&String(v)!==String(config.metadata.shop_id))fail('E_BAD_INPUT','Douyin action cannot target another shop');
});
if(row.method==='open.getAuthInfo'&&(p.auth_id!==String(config.metadata.shop_id)||p.auth_subject_type!==undefined&&p.auth_subject_type!=='shop'))fail('E_BAD_INPUT','Only the currently bound Douyin shop authorization may be queried');
for(const [a,b]of [['create_time_start','create_time_end'],['update_time_start','update_time_end'],['start_time','end_time']])if(typeof p[a]==='number'&&typeof p[b]==='number'&&p[b]<p[a])fail('E_BAD_INPUT','Douyin time range is reversed');
for(const [action,list,key]of [['sku.syncStockBatchMultiProducts','items','uniq_id'],['material.batchUploadImageSync','materials','request_id'],['material.batchUploadVideoAsync','materials','request_id']])if(row.method===action){const ids=p[list].map(x=>String(x[key]));if(ids.some(x=>!x||x==='undefined')||new Set(ids).size!==ids.length)fail('E_BAD_INPUT','Douyin batch entries need distinct documented correlation identifiers');}
if(row.method==='product.batchOfflineProducts'&&new Set(p.product_ids).size!==p.product_ids.length)fail('E_BAD_INPUT','Provide each Douyin product once');
}
function defaults(v,s){if(Array.isArray(v))return v.map(x=>defaults(x,s?.items));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);}return out;}
function wire(v,s){if(s?.['x-integer']||s?.['x-number'])return String(v);if(Array.isArray(v))return '['+v.map(x=>wire(x,s?.items)).join(',')+']';if(object(v))return '{'+Object.keys(v).sort().map(k=>JSON.stringify(k)+':'+wire(v[k],child(s,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','Douyin 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)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','Douyin 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))]));return v;}return restore(value,schema);
}
function typed(v,s){if(v===null)return true;if(!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)&&Object.entries(v).every(([k,x])=>typed(x,child(s,k)));if(s.type==='array')return Array.isArray(v)&&v.every(x=>typed(x,s.items));if(s.type==='integer')return Number.isSafeInteger(v);return typeof v===s.type;}
function partial(v,s){if(Array.isArray(v))return v.some(x=>partial(x,s?.items));if(!object(v))return false;for(const [k,x]of Object.entries(v)){const f=child(s,k);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))return true;}return false;}
function correlate(expected,actual,key){if(!Array.isArray(actual)||actual.length!==expected.length)fail('E_TOOL_CALL_UPSTREAM','Douyin 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','Douyin returned duplicate or unrelated business acknowledgements');}
function ack(row,p,body,config){if(!object(body)||body.code!==10000||body.err_no!==undefined&&body.err_no!==0){const code=String(body?.code??'');if(code==='60000')fail('E_TOOL_CALL_RATE_LIMIT','Douyin rate limit reached');fail('E_TOOL_CALL_UPSTREAM','Douyin rejected the request or omitted its success code');}if(!typed(body,row.output_schema))fail('E_TOOL_CALL_UPSTREAM','Douyin returned fields with invalid types');
const data=body.data,props=row.output_schema.properties.data.properties,keys=Object.keys(props);if(keys.length&&(!object(data)||!keys.some(k=>data[k]!==undefined&&data[k]!==null)))fail('E_TOOL_CALL_UPSTREAM','Douyin omitted the documented business acknowledgement');
if(row.method==='open.getAuthInfo'&&(String(data.auth_id)!==String(config.metadata.shop_id)||String(data.status)!=='1'))fail('E_TOOL_CALL_AUTH','Douyin authorization no longer matches the bound shop');
if(row.method==='sku.syncStockBatchMultiProducts'){correlate(p.items.map(x=>x.uniq_id),data.results,'uniq_id');if(data.results.some(x=>x.status_code===undefined))fail('E_TOOL_CALL_UPSTREAM','Douyin omitted stock status codes');}
if(row.method==='product.batchOfflineProducts'){correlate(p.product_ids.map(String),data.resp_list,'product_id');if(data.resp_list.some(x=>x.code===undefined))fail('E_TOOL_CALL_UPSTREAM','Douyin omitted product result codes');if(data.resp_list.some(x=>String(x.code)!=='0'))return 'partial_or_failed';}
if(['material.batchUploadImageSync','material.batchUploadVideoAsync'].includes(row.method)){if(!object(data.success_map)||!object(data.failed_map))fail('E_TOOL_CALL_UPSTREAM','Douyin omitted material result maps');const actual=[...Object.keys(data.success_map),...Object.keys(data.failed_map)],expected=p.materials.map(x=>x.request_id);if(actual.length!==expected.length||new Set(actual).size!==actual.length||actual.some(x=>!expected.includes(x)))fail('E_TOOL_CALL_UPSTREAM','Douyin returned incomplete or conflicting material acknowledgements');}
if(row.method==='order.downloadShopAccountItem'){if(String(data.code)!=='100000')return 'partial_or_failed';if(typeof data.download_id!=='string'||!data.download_id)fail('E_TOOL_CALL_UPSTREAM','Douyin omitted the export task identifier');}
if(row.method==='order.downloadToShop'&&String(data.code)==='100015')return 'accepted';
if(partial(data,row.output_schema.properties.data))return 'partial_or_failed';
if(row.method==='material.uploadVideoAsync'||row.method==='material.uploadImageSync'){if(!data.material_id)fail('E_TOOL_CALL_UPSTREAM','Douyin omitted the material identifier');if(Number(data.audit_status)===4)return 'partial_or_failed';}
return row.risk==='R'?undefined:'accepted';
}
const secretKeys=new Set(['accesstoken','refreshtoken','appsecret','appkey','clientsecret','authorization','password','cookie','sign']);
function sanitize(data,credentials={},schema){const values=['access_token','refresh_token','app_secret','app_key'].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','Douyin response is too deeply nested');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&&['message','msg','sub_msg'].includes(k))&&!(child(s,k)&&(/^(?:status_msg|status_message|error_msg|err_msg|ErrMsg|code_msg)$/.test(k)||/^(?:msg|message)$/.test(k)&&/错误|失败|结果描述/.test(child(s,k).description||'')))).map(([k,x])=>[k,clean(x,child(s,k),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 Douyin merchant action');binding(config);validate(row,p,config);p=defaults(p,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','Douyin authorization could not be refreshed');}binding(config);
const c=config.credentials,timestamp=owner.timestamp(),paramJson=wire(p,row.input_schema),url=new URL('https://openapi-fxg.jinritemai.com'+row.path);for(const [k,v]of Object.entries({app_key:c.app_key,method:row.method,param_json:paramJson,timestamp,v:'2',sign_method:'hmac-sha256',sign:owner.sign(c.app_key,row.method,paramJson,timestamp,c.app_secret),access_token:token}))url.searchParams.set(k,String(v));
const deadline=AbortSignal.timeout(60000);let response,text;try{response=await requestFetch(url.toString(),{method:'POST',redirect:'error',signal:deadline,headers:{accept:'application/json','content-type':'application/json'},body:paramJson});}catch(error){fail(requestFailureCode(error,deadline),'Douyin request failed; inspect resource state before retrying an uncertain write');}if(!response.ok)throw httpFailure(response.status,'Douyin 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),'Douyin response could not be read completely');}
let body;try{body=parse(text,row.output_schema);}catch{fail('E_TOOL_CALL_UPSTREAM','Douyin 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};