@kmlckj/aios-agent-server-sdk 0.0.7 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # AIOS Agent Server SDK 0.0.7
1
+ # AIOS Agent Server SDK 0.0.8
2
2
 
3
3
  面向 Node.js 应用的智能体开发 SDK。应用负责自己的界面和业务工具,SDK 提供智能体定义、会话、事件、审批、记忆及本地任务执行。
4
4
 
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{randomUUID as T}from"node:crypto";import{setTimeout as et}from"node:timers/promises";import Ar from"node:path";import{randomUUID as jt}from"node:crypto";var f=class extends Error{constructor(t,n,o){super(n,o);this.code=t;this.name="AiosSdkError"}};import hr from"node:http";import{setTimeout as gr}from"node:timers/promises";import L from"node:fs";import ot from"node:os";import oe from"node:path";import{createHash as ur}from"node:crypto";var _=class extends Error{constructor(t,n,o=2,i){super(n,i);this.code=t;this.exitCode=o;this.details=i?.details}details};import Ue from"node:path";import{createRequire as Zt}from"node:module";import{fileURLToPath as er}from"node:url";function tr(){let e=Zt(import.meta.url)(typeof AIOS_FILE_SECURITY_BINDING_PATH>"u"?"koffi":Ue.resolve(Ue.dirname(er(import.meta.url)),AIOS_FILE_SECURITY_BINDING_PATH)),t=e.load("advapi32.dll"),n=e.load("kernel32.dll");return{binding:e,attributes:n.func("uint32_t __stdcall GetFileAttributesW(const char16_t *path)"),error:n.func("uint32_t __stdcall GetLastError()"),close:n.func("int __stdcall CloseHandle(intptr_t handle)"),free:n.func("void * __stdcall LocalFree(void *memory)"),openToken:t.func("int __stdcall OpenProcessToken(intptr_t process, uint32_t access, _Out_ intptr_t *token)"),tokenInfo:t.func("int __stdcall GetTokenInformation(intptr_t token, int kind, void *data, uint32_t size, _Out_ uint32_t *needed)"),sidString:t.func("int __stdcall ConvertSidToStringSidW(const void *sid, _Out_ void **text)"),read:t.func("uint32_t __stdcall GetNamedSecurityInfoW(const char16_t *path, int kind, uint32_t information, _Out_ void **owner, void *group, _Out_ void **dacl, void *sacl, _Out_ void **descriptor)"),control:t.func("int __stdcall GetSecurityDescriptorControl(const void *descriptor, _Out_ uint16_t *control, _Out_ uint32_t *revision)"),aclInfo:t.func("int __stdcall GetAclInformation(const void *acl, void *data, uint32_t size, int kind)"),ace:t.func("int __stdcall GetAce(const void *acl, uint32_t index, _Out_ void **ace)"),descriptor:t.func("int __stdcall ConvertStringSecurityDescriptorToSecurityDescriptorW(const char16_t *sddl, uint32_t revision, _Out_ void **descriptor, void *size)"),dacl:t.func("int __stdcall GetSecurityDescriptorDacl(const void *descriptor, _Out_ int *present, _Out_ void **acl, _Out_ int *defaulted)"),write:t.func("uint32_t __stdcall SetNamedSecurityInfoW(const char16_t *path, int kind, uint32_t information, void *owner, void *group, const void *dacl, void *sacl)")}}var ne;function C(r,e,t){return Object.assign(new Error(`${e} '${r}' (Win32 ${t})`),{code:t===2||t===3?"ENOENT":t===5?"EACCES":"EIO",path:r,syscall:e,win32Code:t})}function Be(r,e){let t=[null];if(!r.sidString(e,t))throw C("","ConvertSidToStringSidW",r.error());try{return r.binding.decode(t[0],"char16_t",-1)}finally{r.free(t[0])}}function rr(r){let e=[0];if(!r.openToken(-1,8,e))throw C("","OpenProcessToken",r.error());try{let t=[0];r.tokenInfo(e[0],1,null,0,t);let n=r.error();if(n!==122)throw C("","GetTokenInformation",n);let o=Buffer.alloc(t[0]);if(!r.tokenInfo(e[0],1,o,o.length,t))throw C("","GetTokenInformation",r.error());return Be(r,r.binding.decode(o,"void *"))}finally{r.close(e[0])}}function nr(r,e){let t=Buffer.alloc(12);if(!r.aclInfo(e,t,t.length,2))throw C("","GetAclInformation",r.error());let n=[];for(let o=0;o<t.readUInt32LE(0);o++){let i=[null];if(!r.ace(e,o,i))throw C("","GetAce",r.error());let s=Buffer.from(r.binding.decode(i[0],"uint8_t",4)),a=s[0];if([1,6,10,12].includes(a)){n.push({type:a,flags:s[1],rights:0,sid:""});continue}if(![0,5,9,11].includes(a))throw new Error(`Unsupported private storage access rule: ${a}`);let c=Buffer.from(r.binding.decode(i[0],"uint8_t",s.readUInt16LE(2))),l=8;if(a===5||a===11){let d=c.readUInt32LE(8);l=12+(d&1?16:0)+(d&2?16:0)}n.push({type:a,flags:s[1],rights:c.readUInt32LE(4),sid:Be(r,c.subarray(l))})}return n}function or(r,e){ne??=tr();let t=Ue.toNamespacedPath(r),n=ne.attributes(t);if(n===4294967295)throw C(r,"GetFileAttributesW",ne.error());if(n&1024)throw new Error("Reparse points are not private storage");if(e&&!(n&16))throw new Error("Private root is not a directory");return{api:ne,name:t,user:rr(ne)}}function ir(r){let e=[null],t=[null],n=[null];return{owner:e,acl:t,descriptor:n,args:[r,1,5,e,null,t,null,n]}}function sr(r,e,t){let{api:n,user:o}=r;if(Be(n,e.owner[0])!==o)throw new Error("Storage owner mismatch");let i=[0],s=[0];if(!n.control(e.descriptor[0],i,s))throw C("","GetSecurityDescriptorControl",n.error());let a=e.acl[0]?nr(n,e.acl[0]):[],c=a[0],l=!!(i[0]&4096)&&a.length===1&&c.type===0&&c.flags===3&&c.rights===2032127&&c.sid===o;if(t&&!l)return!1;if(!e.acl[0])throw new Error("Storage has no discretionary access control list");if(a.some(d=>[0,5,9,11].includes(d.type)&&d.sid!==o&&d.sid!=="S-1-5-18"))throw new Error("Storage is accessible by another principal");return!0}function ar(r){let{api:e,user:t}=r,n=[null],o=[null];if(!e.descriptor(`D:P(A;OICI;FA;;;${t})`,1,n,null))throw C("","ConvertStringSecurityDescriptorToSecurityDescriptorW",e.error());try{if(!e.dacl(n[0],[0],o,[0]))throw C("","GetSecurityDescriptorDacl",e.error());return{descriptor:n[0],args:[r.name,1,2147483652,null,null,o[0],null]}}catch(i){throw e.free(n[0]),i}}function nt(r,e){let t=or(r,e),{api:n}=t,o=i=>{let s=ir(t.name),a=n.read(...s.args);if(a)throw C(r,"GetNamedSecurityInfoW",a);try{return sr(t,s,i)}finally{n.free(s.descriptor[0])}};if(!o(e)){let i=ar(t);try{let s=n.write(...i.args);if(s)throw C(r,"SetNamedSecurityInfoW",s)}finally{n.free(i.descriptor)}o(!1)}}function cr(r){throw r.code==="ENOENT"?r:new _("UNSAFE_DATA_DIRECTORY",`Windows 私有存储访问控制校验失败:${r instanceof Error?r.message:String(r)}`,1,{cause:r})}function $e(r,e){try{nt(r,e)}catch(t){cr(t)}}import dr from"node:fs";function lr(r,e="/proc"){let t;try{t=dr.readFileSync(`${e}/${r}/stat`,"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let n=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/);return{pid:r,parentPid:Number(n[1]),exited:n[0]==="Z"||n[0]==="X"}}function X(r){if(process.platform==="linux"){let e=lr(r);if(!e||e.exited)return!1}try{return process.kill(r,0),!0}catch(e){let t=e.code;if(t==="ESRCH")return!1;if(t==="EPERM")return!0;throw e}}function Y(r){L.mkdirSync(r,{recursive:!0,mode:448});let e=L.lstatSync(r);if(!e.isDirectory()||e.isSymbolicLink()||process.getuid&&e.uid!==process.getuid())throw new _("UNSAFE_DATA_DIRECTORY","CLI 私有目录的类型或所有者不正确。",1);process.platform==="win32"?$e(r,!0):L.chmodSync(r,448)}function ze(r){let e=ur("sha256").update(r).digest("hex").slice(0,32),t=oe.join(process.platform==="win32"?ot.tmpdir():"/tmp",`aios-cli-${process.getuid?.()??ot.userInfo().username}`);return{lock:oe.join(r,"daemon.lock"),mutex:oe.join(r,"daemon-owner.sqlite"),metadata:oe.join(r,"daemon.json"),socketDirectory:t,socket:process.platform==="win32"?`\\\\.\\pipe\\aios-cli-${e}`:oe.join(t,`${e}.sock`)}}function pr(r){let e=L.lstatSync(r,{throwIfNoEntry:!1});if(e&&(!e.isFile()||e.isSymbolicLink()))throw new _("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1);return e}function He(r){let e=pr(r);try{process.platform==="win32"&&e&&$e(r,!1)}catch(t){if(t.code==="ENOENT")return;throw t}return fr(r)}function fr(r){let e;try{e=L.openSync(r,L.constants.O_RDONLY|L.constants.O_NOFOLLOW)}catch(t){let n=t.code;if(n==="ENOENT")return;throw n==="ELOOP"?new _("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1):t}try{let t=L.fstatSync(e);if(!t.isFile()||process.getuid&&t.uid!==process.getuid()||process.platform!=="win32"&&(t.mode&63)!==0)throw new _("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1);try{return JSON.parse(L.readFileSync(e,"utf8"))}catch(n){throw n instanceof SyntaxError?new _("INVALID_DAEMON_METADATA","服务所有权记录损坏,原文件已保留。",1):n}}finally{L.closeSync(e)}}var mr=1,Dn=8*1024*1024;function Je(r){if(!r||typeof r!="object")return!1;let e=r;return e.protocol===mr&&Number.isSafeInteger(e.pid)&&Number(e.pid)>0&&(e.installationId===void 0||typeof e.installationId=="string")&&["instanceId","version","token","socket","root","startedAt"].every(t=>typeof e[t]=="string")}function it(r){let e=ze(r),t=He(e.metadata);if(!Je(t)||t.root!==r||t.socket!==e.socket||!X(t.pid))throw new f("CLI_NOT_RUNNING","请先启动指定数据目录的 CLI 后台服务。");if("sdkProtocol"in t)throw new f("RUNTIME_INCOMPATIBLE","该数据目录属于精简运行时,请使用 createClient。");return t}function ve(r){let e=ze(r),t=He(e.metadata);if(t!==void 0){if(!Je(t)||t.root!==r||t.socket!==e.socket||!("sdkProtocol"in t)||t.sdkProtocol!==1)throw new f("RUNTIME_INCOMPATIBLE","本机服务不支持当前 SDK 协议,或其归属记录不一致。");return X(t.pid)?t:void 0}}async function st(r,e){for(;;){e.throwIfAborted();let t=ve(r);if(t)return t;await gr(100,void 0,{signal:e})}}function ke(r,e,t,n,o,i,s=t==="runtime.drain"?0:12e4){let a=JSON.stringify({id:o,clientId:e,method:t,params:n});return Buffer.byteLength(a)>8*1024*1024?Promise.reject(new f("REQUEST_TOO_LARGE","SDK 请求超过 8 MiB。")):new Promise((c,l)=>{let d=u=>l(i?.aborted?i.reason:new f("OUTCOME_UNKNOWN",`请求 ${o} 的结果未知,请使用原命令 ID 查询回执。`,{cause:u})),p=hr.request({socketPath:r.socket,path:"/sdk",method:"POST",agent:!1,signal:i,headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json","content-length":Buffer.byteLength(a),"x-aios-protocol":"1","x-aios-instance":r.instanceId}},u=>{let h=[],g=0;u.on("data",y=>{g+=y.length,g>16777216?u.destroy(new Error("SDK 响应超过 16 MiB,请分页读取。")):h.push(y)}),u.once("error",d),u.once("end",()=>{try{if(u.statusCode===404)throw new f("SDK_UNSUPPORTED","此 CLI 版本未提供 SDK 接口,请使用包含 SDK 接口的版本。");let y=JSON.parse(Buffer.concat(h).toString("utf8"));if(y.id!==o||typeof y.ok!="boolean")throw new f("INVALID_RESPONSE","SDK 响应与请求不匹配。");if(!y.ok)throw new f(y.error?.code??"RUNTIME_ERROR",y.error?.message??"运行时返回未知错误。");c(y.value)}catch(y){l(y)}})});s>0&&p.setTimeout(s,()=>p.destroy(new Error("SDK 请求等待超时。"))),p.once("error",d),p.end(a)})}import R from"node:path";import ie from"node:fs";import{createHash as kr}from"node:crypto";import v from"node:fs";import D from"node:path";import{createHash as yr,randomUUID as Ie}from"node:crypto";var V=new Map,wr,be=/^(\d{16})-([a-f0-9]{64})\.json$/,Fe=r=>yr("sha256").update(r).digest("hex"),$=r=>`${r}.history`,at=r=>!0;function ct(r){if(v.existsSync(r+".bak")||v.existsSync(r+".bak.1"))return!0;try{return v.readdirSync($(r)).some(e=>be.test(e))}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Q=class extends Error{constructor(t,n,o=!1,i){let s=n==="missing"?"必要记录缺失":n==="temporarily_unavailable"?"记录暂时无法访问":n==="unsupported_version"?"记录版本不受支持":"记录已损坏";super(`${dt(t)}:${s}。请查看存储恢复详情。`);this.file=t;this.problem=n;this.recoveryAvailable=o;this.cause=i,this.name="StorageIntegrityError"}cause};function dt(r){return D.basename(r)==="settings.json"?"应用设置":D.basename(r).startsWith("codex-")?"任务执行记录":D.basename(r)}function Ve(r,e,t){let n;try{n=v.readFileSync(r)}catch(o){return{status:o.code==="ENOENT"?"missing":"temporarily_unavailable",error:o}}try{let o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n));if(t&&o&&typeof o=="object"&&"version"in o&&!t.includes(Number(o.version)))return{status:"unsupported_version",error:new Error("记录版本不受支持。")};if(!e(o))throw new Error("记录结构与所属文件不一致。");return{status:"healthy",value:o,bytes:n}}catch(o){return{status:"corrupt",error:o}}}function Ge(r,e){let t;try{t=v.readdirSync($(r))}catch(o){if(o.code==="ENOENT")t=[];else throw o}let n=[];for(let o of t.sort().reverse()){let i=be.exec(o);if(!i)continue;let s=D.join($(r),o),a=Ve(s,e);if(a.status==="temporarily_unavailable")throw a.error;a.status==="healthy"&&Fe(a.bytes)===i[2]&&n.push({file:s,generation:Number(i[1]),value:a.value,bytes:a.bytes})}if(!n.length)for(let o of[".bak",".bak.1"]){let i=Ve(r+o,e);if(i.status==="temporarily_unavailable")throw i.error;i.status==="healthy"&&n.push({file:r+o,generation:0,value:i.value,bytes:i.bytes})}return n}function lt(r,e,t,n){let o=D.resolve(r),i=V.get(o),s=new Q(r,e,t).message,a={id:i?.issue.id??Ie(),fileName:dt(r),status:e,message:s,detectedAt:i?.issue.detectedAt??new Date().toISOString(),recoveryAvailable:t};V.set(o,{issue:a,file:o,options:n}),(!i||i.issue.status!==e||i.issue.recoveryAvailable!==t)&&wr?.({...a}),V.size>256&&V.delete(V.keys().next().value)}function Ee(r,e,t){v.mkdirSync(D.dirname(r),{recursive:!0,mode:448});let n=`${r}.${Ie()}.tmp`,o;try{o=v.openSync(n,"wx",384),v.writeFileSync(o,e),t&&v.fsyncSync(o),v.closeSync(o),o=void 0,v.renameSync(n,r)}finally{o!==void 0&&v.closeSync(o);try{v.unlinkSync(n)}catch(i){if(i.code!=="ENOENT")throw i}}}function Sr(r){let e=D.join($(r),"damaged");v.mkdirSync(e,{recursive:!0,mode:448});try{v.copyFileSync(r,D.join(e,`${Date.now()}-${Ie()}.bin`),v.constants.COPYFILE_EXCL)}catch(t){if(t.code!=="ENOENT")throw t}}function ut(r,e={}){let t=e.validate??at,n=Ve(r,t,e.versions);if(n.status==="healthy")return{...n,recoveryAvailable:!1};if(n.status==="temporarily_unavailable"||n.status==="unsupported_version")return{...n,recoveryAvailable:!1};let o=Ge(r,t)[0];return{...n,backup:o,recoveryAvailable:!!o}}function pt(r,e={}){let t=ut(r,e);if(t.status==="healthy")return V.delete(D.resolve(r)),t.value;if(t.status==="missing"&&!t.recoveryAvailable&&!e.required&&!ct(r))return null;lt(r,t.status,t.recoveryAvailable,e);let n=v.existsSync($(r))?Math.max(0,...v.readdirSync($(r)).map(o=>Number(be.exec(o)?.[1]??0))):0;if(e.recover&&"backup"in t&&t.backup&&(e.allowOlderRecovery||t.backup.generation===n))return Sr(r),Ee(r,t.backup.bytes,!0),V.delete(D.resolve(r)),console.info("[storage-integrity] recovered",{file:r,source:t.backup.file}),t.backup.value;throw new Q(r,t.status,t.recoveryAvailable,t.error)}function ft(r,e,t){let n=Ge(r,t),o=Fe(e);if(n[0]?.generation&&Fe(n[0].bytes)===o)return;v.mkdirSync($(r),{recursive:!0,mode:448});let i=Math.max(0,...v.readdirSync($(r)).map(c=>Number(be.exec(c)?.[1]??0)))+1,s=D.join($(r),`${String(i).padStart(16,"0")}-${o}.json`),a=`${s}.${Ie()}.pending`;return Ee(a,e,!0),{temporary:a,destination:s}}function vr(r,e,t){let n=ft(r,e,t);if(n)try{v.renameSync(n.temporary,n.destination)}finally{try{v.unlinkSync(n.temporary)}catch(o){if(o.code!=="ENOENT")throw o}}}function mt(r,e,t={}){let n=t.validate??at;if(!n(e))throw new Q(r,"corrupt",!1,new Error("拒绝写入无效记录。"));let o=ut(r,t);if(o.status!=="healthy"&&!(o.status==="missing"&&!o.recoveryAvailable&&!ct(r)))throw lt(r,o.status,o.recoveryAvailable,t),new Q(r,o.status,o.recoveryAvailable,o.error);let i=Buffer.from(`${JSON.stringify(e,null,2)}
2
- `);t.checkpoint!==!1&&o.status==="healthy"&&vr(r,o.bytes,n);let s=t.checkpoint!==!1?ft(r,i,n):void 0;try{if(t.checkpoint!==!1)for(let a of Ge(r,n).slice(2))a.generation>0&&v.unlinkSync(a.file);if(Ee(r,i,t.durable!==!1),s)try{v.renameSync(s.temporary,s.destination)}catch(a){try{o.status==="healthy"?Ee(r,o.bytes,!0):v.unlinkSync(r)}catch(c){throw Object.assign(new Error("记录保存失败,且回滚未完成。"),{errors:[a,c]})}throw a}}finally{if(s)try{v.unlinkSync(s.temporary)}catch(a){if(a.code!=="ENOENT")throw a}}}function We(r){let e=new URL(r);if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.search||e.hash)throw new Error("平台基地址无效。");return e.toString().replace(/\/+$/,"")}function qe(r){let e=r.mode==="platform"?We(r.platformBaseUrl):null,t=[r.mode,r.appId,r.userScope,e];if(r.mode==="platform"&&r.authentication){let{userId:n,tenantId:o,workspaceId:i}=r.authentication.principal;t.push(JSON.stringify(["managed",n,o,i]))}return kr("sha256").update(JSON.stringify(t)).digest("hex")}function xe(r){let e=qe(r),t=R.resolve(r.runtime.dataDirectory),n=R.join(t,"applications",e);if(process.platform!=="win32")return n;let o=R.join(t,"a",e.slice(0,32)),i=gt(t,e);if(i){let s=i.version===1?n:o;if(!ie.statSync(s,{throwIfNoEntry:!1})?.isDirectory())throw new Error("应用运行目录丢失,请恢复原目录,不能创建空目录替代。");if(ie.existsSync(i.version===1?o:n))throw new Error("应用同时存在新旧运行目录,请检查数据完整性。");return s}if(ie.existsSync(n)){if(ie.existsSync(o))throw new Error("应用同时存在新旧运行目录,请检查数据完整性。");return n}if(ie.existsSync(o))throw new Error("应用短目录缺少布局记录,请检查数据完整性。");return o}var ht=(r,e)=>R.join(r,"a",e.slice(0,32)+".json");function gt(r,e){return pt(ht(r,e),{recover:!1,validate:t=>{let n=t;return!!n&&(n.version===1||n.version===2)&&n.identity===e}})}function yt(r){let e=xe(r);if(Y(e),process.platform==="win32"){let t=R.resolve(r.runtime.dataDirectory),n=qe(r);if(!gt(t,n)){let o=R.basename(R.dirname(e))==="applications"?1:2;mt(ht(t,n),{version:o,identity:n},{validate:i=>{let s=i;return!!s&&s.version===o&&s.identity===n}})}}return e}function wt(r){let e=xe(r),t=qe(r);if(process.platform==="win32"){let o=(i,s)=>R.join(R.resolve(i??r.runtime.dataDirectory),s,t.slice(0,20));return{tasks:o(void 0,"t"),workspaces:o(r.runtime.workspaceDirectory,"w"),cache:o(r.runtime.cacheDirectory,"c"),temporary:o(r.runtime.temporaryDirectory,"tmp")}}let n=(o,i)=>o?R.join(R.resolve(o),"applications",t,i):R.join(e,i);return{workspaces:n(r.runtime.workspaceDirectory,"workspaces"),cache:n(r.runtime.cacheDirectory,"cache"),temporary:n(r.runtime.temporaryDirectory,"tmp")}}import Ke from"node:path";function St(r){for(let[e,t]of Object.entries({appId:r.appId,userScope:r.userScope}))if(typeof t!="string"||!t.trim()||t.length>256||/[\u0000-\u001f]/u.test(t))throw new Error(`独立运行身份 ${e} 无效。`);if(r.mode!=="standalone")throw new Error("独立运行身份模式不匹配。");return{mode:"standalone",appId:r.appId,userScope:r.userScope}}function A(r,e){return Object.assign(new Error(e),{code:r})}function vt(r,e){if(!r||r.kind!=="managed")throw new Error("托管身份配置无效。");let t=r.principal;if(!t||typeof t.userId!="string"||!t.userId.trim()||![t.tenantId,t.workspaceId].every(o=>o===null||typeof o=="string"&&o.trim()))throw new Error("托管身份必须明确指定用户、租户和工作区;无租户或工作区时使用 null。");let n=r.allowedOrigins??[];if(!Array.isArray(n)||n.some(o=>{let i=new URL(o);return!["http:","https:"].includes(i.protocol)||i.origin!==o}))throw new Error("凭证目标必须是 HTTP(S) origin,不能包含路径或认证信息。");return new URL(e),{kind:"managed",principal:{userId:t.userId,tenantId:t.tenantId,workspaceId:t.workspaceId},allowedOrigins:[...new Set(n)]}}function kt(r,e,t,n=Date.now()){if(!r||typeof r.accessToken!="string"||!r.accessToken.trim())throw new Error("托管凭证缺少 accessToken。");let o=r.session;if(!o||o.user?.id!==e.userId||typeof o.platformBaseUrl!="string"||o.platformBaseUrl.replace(/\/+$/,"")!==t.replace(/\/+$/,""))throw A("MANAGED_IDENTITY_MISMATCH","托管凭证的平台或用户与绑定身份不一致。");let i=r.accessToken.split(".");if(i.length!==3)throw new Error("平台托管凭证必须是 JWT。");let s=JSON.parse(Buffer.from(i[1],"base64url").toString("utf8"));if(!s||typeof s!="object"||Array.isArray(s))throw new Error("平台凭证的 JWT 内容无效。");let a=(...E)=>{let W=E.map(x=>s[x]).find(x=>typeof x=="string"&&x.trim());return typeof W=="string"?W:null},c=a("sub"),l=a("tenantId","tenant_id"),d=a("workspaceId","workspace_id")??o.context?.currentWorkspaceId??null;if(c!==e.userId||l!==e.tenantId||d!==e.workspaceId||(o.context?.currentTenantId??null)!==e.tenantId||(o.context?.currentWorkspaceId??null)!==e.workspaceId)throw A("MANAGED_IDENTITY_MISMATCH","托管凭证续期不得改变用户、租户或工作区。");let p=Date.parse(o.accessTokenExpiresAt);if(!Number.isFinite(p)||p<=n||typeof s.exp!="number"||!Number.isFinite(s.exp)||s.exp*1e3<=n)throw A("MANAGED_CREDENTIAL_EXPIRED","应用返回的托管凭证已经过期。");if(typeof o.user.username!="string"||typeof o.user.displayName!="string"||!Array.isArray(o.user.roles)||!o.user.roles.every(E=>typeof E=="string")||!Array.isArray(o.tenants))throw new Error("托管凭证的用户资料格式无效。");let{id:u,username:h,displayName:g,email:y,phone:I,avatarUrl:S,tenantId:m,roles:w}=o.user,k=o.tenants.map(E=>{if(!E||typeof E.id!="string"||typeof E.name!="string"||typeof E.displayName!="string")throw new Error("托管凭证的租户资料格式无效。");return{id:E.id,name:E.name,displayName:E.displayName,status:E.status}});return{credential:{accessToken:r.accessToken,session:{user:{id:u,username:h,displayName:g,email:y,phone:I,avatarUrl:S,tenantId:m,roles:[...w]},tenants:k,context:{currentTenantId:e.tenantId,currentWorkspaceId:e.workspaceId,personalMode:o.context?.personalMode,contextVersion:o.context?.contextVersion},platformBaseUrl:t,authenticatedAt:o.authenticatedAt,accessTokenExpiresAt:o.accessTokenExpiresAt}},expiresAt:Math.min(p,s.exp*1e3),sessionId:a("sessionId","sid")}}function Et(r){if(r!==void 0){if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(e=>!["startupTimeoutMs","rpcTimeoutMs","methodTimeoutMs","shutdownTimeoutMs"].includes(e)))throw new Error("通信等待配置无效。");for(let e of["startupTimeoutMs","rpcTimeoutMs","shutdownTimeoutMs"]){let t=r[e];if(t!==void 0&&(!Number.isSafeInteger(t)||t<(e==="rpcTimeoutMs"?0:1)||t>2147483647))throw new Error(`${e} 必须是有效毫秒数。`)}if(r.methodTimeoutMs!==void 0){if(!r.methodTimeoutMs||typeof r.methodTimeoutMs!="object"||Array.isArray(r.methodTimeoutMs))throw new Error("方法等待配置无效。");for(let[e,t]of Object.entries(r.methodTimeoutMs))if(!/^[a-zA-Z][a-zA-Z0-9.]+$/.test(e)||!Number.isSafeInteger(t)||t<0||t>2147483647)throw new Error("方法等待配置无效。")}}}function It(r,e){return e?.methodTimeoutMs?.[r]??(r==="runtime.drain"?0:e?.rpcTimeoutMs??12e4)}function bt(r){if(!r||typeof r!="object"||Array.isArray(r)||Object.entries(r).some(([e,t])=>!["temperature","topP","maxOutputTokens","responseFormat"].includes(e)||typeof t!="boolean"))throw new Error("模型生成能力声明无效。")}function xt(r){if(r===void 0)return;if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(t=>!["storage","extraction"].includes(t))||r.storage!==void 0&&!["local","external"].includes(r.storage))throw new Error("记忆配置无效。");let e=r.extraction;if(e!==void 0&&(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(t=>!["enabled","idleMs","model","instructions","timeoutMs"].includes(t))||e.enabled!==void 0&&typeof e.enabled!="boolean"||e.idleMs!==void 0&&(!Number.isSafeInteger(e.idleMs)||e.idleMs<0||e.idleMs>2147483647)||e.timeoutMs!==void 0&&(!Number.isSafeInteger(e.timeoutMs)||e.timeoutMs<1||e.timeoutMs>2147483647)||e.model!==void 0&&(typeof e.model!="string"||!e.model.trim())||e.instructions!==void 0&&(typeof e.instructions!="string"||e.instructions.length>32e3)))throw new Error("记忆提取策略无效。")}function se(r){if(!r||!["platform","standalone"].includes(r.mode))throw new Error("必须明确选择 platform 或 standalone 模式。");if(St({mode:"standalone",appId:r.appId,userScope:r.userScope}),Et(r.communication),xt(r.memory),r.authorization!==void 0&&(!r.authorization||typeof r.authorization.required!="boolean"||Object.keys(r.authorization).some(e=>e!=="required")))throw new Error("会话授权配置无效。");if(r.generationCapabilities!==void 0){if(!r.generationCapabilities||typeof r.generationCapabilities!="object"||Array.isArray(r.generationCapabilities))throw new Error("模型能力目录无效。");Object.values(r.generationCapabilities).forEach(bt)}if(!r.runtime||typeof r.runtime.directory!="string"||!r.runtime.directory.trim()||typeof r.runtime.dataDirectory!="string"||!r.runtime.dataDirectory.trim())throw new Error("运行时目录和数据目录不能为空。");if(r.mode==="standalone"&&"platformBaseUrl"in r)throw new Error("独立模式不得配置平台基地址。");if(r.mode==="platform"&&"models"in r)throw new Error("平台模式不得配置独立模式模型列表。");if(r.mode==="standalone"&&"authentication"in r)throw new Error("独立模式不使用平台托管凭证。");if(r.runtime.tools&&Object.keys(r.runtime.tools).some(e=>!["node","python","git","bash","npm"].includes(e)))throw new Error("工具路径配置包含未知工具。");if(r.appName!==void 0&&(typeof r.appName!="string"||!r.appName.trim()||r.appName.length>128))throw new Error("应用名称无效。");for(let e of["workspaceDirectory","cacheDirectory","temporaryDirectory"]){let t=r.runtime[e];if(t!==void 0&&(typeof t!="string"||!t.trim()||!Ke.isAbsolute(t)))throw new Error(`${e} 必须是绝对目录路径。`)}return{...structuredClone(r),runtime:{...structuredClone(r.runtime),directory:Ke.resolve(r.runtime.directory),dataDirectory:Ke.resolve(r.runtime.dataDirectory)},...r.mode==="platform"?{platformBaseUrl:We(r.platformBaseUrl),...r.authentication!==void 0?{authentication:vt(r.authentication,r.platformBaseUrl)}:{}}:{}}}import{setTimeout as Tr}from"node:timers/promises";import F from"node:fs";import M from"node:path";import{createHash as Ct,verify as br}from"node:crypto";var At=`-----BEGIN PUBLIC KEY-----
1
+ import{randomUUID as T}from"node:crypto";import{setTimeout as et}from"node:timers/promises";import Ar from"node:path";import{randomUUID as jt}from"node:crypto";var f=class extends Error{constructor(t,n,o){super(n,o);this.code=t;this.name="AiosSdkError"}};import hr from"node:http";import{setTimeout as gr}from"node:timers/promises";import L from"node:fs";import ot from"node:os";import oe from"node:path";import{createHash as ur}from"node:crypto";var _=class extends Error{constructor(t,n,o=2,i){super(n,i);this.code=t;this.exitCode=o;this.details=i?.details}details};import Ue from"node:path";import{createRequire as Zt}from"node:module";import{fileURLToPath as er}from"node:url";function tr(){let e=Zt(import.meta.url)(typeof AIOS_FILE_SECURITY_BINDING_PATH>"u"?"koffi":Ue.resolve(Ue.dirname(er(import.meta.url)),AIOS_FILE_SECURITY_BINDING_PATH)),t=e.load("advapi32.dll"),n=e.load("kernel32.dll");return{binding:e,attributes:n.func("uint32_t __stdcall GetFileAttributesW(const char16_t *path)"),error:n.func("uint32_t __stdcall GetLastError()"),close:n.func("int __stdcall CloseHandle(intptr_t handle)"),free:n.func("void * __stdcall LocalFree(void *memory)"),openToken:t.func("int __stdcall OpenProcessToken(intptr_t process, uint32_t access, _Out_ intptr_t *token)"),tokenInfo:t.func("int __stdcall GetTokenInformation(intptr_t token, int kind, void *data, uint32_t size, _Out_ uint32_t *needed)"),sidString:t.func("int __stdcall ConvertSidToStringSidW(const void *sid, _Out_ void **text)"),read:t.func("uint32_t __stdcall GetNamedSecurityInfoW(const char16_t *path, int kind, uint32_t information, _Out_ void **owner, void *group, _Out_ void **dacl, void *sacl, _Out_ void **descriptor)"),control:t.func("int __stdcall GetSecurityDescriptorControl(const void *descriptor, _Out_ uint16_t *control, _Out_ uint32_t *revision)"),aclInfo:t.func("int __stdcall GetAclInformation(const void *acl, void *data, uint32_t size, int kind)"),ace:t.func("int __stdcall GetAce(const void *acl, uint32_t index, _Out_ void **ace)"),descriptor:t.func("int __stdcall ConvertStringSecurityDescriptorToSecurityDescriptorW(const char16_t *sddl, uint32_t revision, _Out_ void **descriptor, void *size)"),dacl:t.func("int __stdcall GetSecurityDescriptorDacl(const void *descriptor, _Out_ int *present, _Out_ void **acl, _Out_ int *defaulted)"),write:t.func("uint32_t __stdcall SetNamedSecurityInfoW(const char16_t *path, int kind, uint32_t information, void *owner, void *group, const void *dacl, void *sacl)")}}var ne;function R(r,e,t){return Object.assign(new Error(`${e} '${r}' (Win32 ${t})`),{code:t===2||t===3?"ENOENT":t===5?"EACCES":"EIO",path:r,syscall:e,win32Code:t})}function Be(r,e){let t=[null];if(!r.sidString(e,t))throw R("","ConvertSidToStringSidW",r.error());try{return r.binding.decode(t[0],"char16_t",-1)}finally{r.free(t[0])}}function rr(r){let e=[0];if(!r.openToken(-1,8,e))throw R("","OpenProcessToken",r.error());try{let t=[0];r.tokenInfo(e[0],1,null,0,t);let n=r.error();if(n!==122)throw R("","GetTokenInformation",n);let o=Buffer.alloc(t[0]);if(!r.tokenInfo(e[0],1,o,o.length,t))throw R("","GetTokenInformation",r.error());return Be(r,r.binding.decode(o,"void *"))}finally{r.close(e[0])}}function nr(r,e){let t=Buffer.alloc(12);if(!r.aclInfo(e,t,t.length,2))throw R("","GetAclInformation",r.error());let n=[];for(let o=0;o<t.readUInt32LE(0);o++){let i=[null];if(!r.ace(e,o,i))throw R("","GetAce",r.error());let s=Buffer.from(r.binding.decode(i[0],"uint8_t",4)),a=s[0];if([1,6,10,12].includes(a)){n.push({type:a,flags:s[1],rights:0,sid:""});continue}if(![0,5,9,11].includes(a))throw new Error(`Unsupported private storage access rule: ${a}`);let c=Buffer.from(r.binding.decode(i[0],"uint8_t",s.readUInt16LE(2))),l=8;if(a===5||a===11){let d=c.readUInt32LE(8);l=12+(d&1?16:0)+(d&2?16:0)}n.push({type:a,flags:s[1],rights:c.readUInt32LE(4),sid:Be(r,c.subarray(l))})}return n}function or(r,e){ne??=tr();let t=Ue.toNamespacedPath(r),n=ne.attributes(t);if(n===4294967295)throw R(r,"GetFileAttributesW",ne.error());if(n&1024)throw new Error("Reparse points are not private storage");if(e&&!(n&16))throw new Error("Private root is not a directory");return{api:ne,name:t,user:rr(ne)}}function ir(r){let e=[null],t=[null],n=[null];return{owner:e,acl:t,descriptor:n,args:[r,1,5,e,null,t,null,n]}}function sr(r,e,t){let{api:n,user:o}=r;if(Be(n,e.owner[0])!==o)throw new Error("Storage owner mismatch");let i=[0],s=[0];if(!n.control(e.descriptor[0],i,s))throw R("","GetSecurityDescriptorControl",n.error());let a=e.acl[0]?nr(n,e.acl[0]):[],c=a[0],l=!!(i[0]&4096)&&a.length===1&&c.type===0&&c.flags===3&&c.rights===2032127&&c.sid===o;if(t&&!l)return!1;if(!e.acl[0])throw new Error("Storage has no discretionary access control list");if(a.some(d=>[0,5,9,11].includes(d.type)&&d.sid!==o&&d.sid!=="S-1-5-18"))throw new Error("Storage is accessible by another principal");return!0}function ar(r){let{api:e,user:t}=r,n=[null],o=[null];if(!e.descriptor(`D:P(A;OICI;FA;;;${t})`,1,n,null))throw R("","ConvertStringSecurityDescriptorToSecurityDescriptorW",e.error());try{if(!e.dacl(n[0],[0],o,[0]))throw R("","GetSecurityDescriptorDacl",e.error());return{descriptor:n[0],args:[r.name,1,2147483652,null,null,o[0],null]}}catch(i){throw e.free(n[0]),i}}function nt(r,e){let t=or(r,e),{api:n}=t,o=i=>{let s=ir(t.name),a=n.read(...s.args);if(a)throw R(r,"GetNamedSecurityInfoW",a);try{return sr(t,s,i)}finally{n.free(s.descriptor[0])}};if(!o(e)){let i=ar(t);try{let s=n.write(...i.args);if(s)throw R(r,"SetNamedSecurityInfoW",s)}finally{n.free(i.descriptor)}o(!1)}}function cr(r){throw r.code==="ENOENT"?r:new _("UNSAFE_DATA_DIRECTORY",`Windows 私有存储访问控制校验失败:${r instanceof Error?r.message:String(r)}`,1,{cause:r})}function $e(r,e){try{nt(r,e)}catch(t){cr(t)}}import dr from"node:fs";function lr(r,e="/proc"){let t;try{t=dr.readFileSync(`${e}/${r}/stat`,"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let n=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/);return{pid:r,parentPid:Number(n[1]),exited:n[0]==="Z"||n[0]==="X"}}function X(r){if(process.platform==="linux"){let e=lr(r);if(!e||e.exited)return!1}try{return process.kill(r,0),!0}catch(e){let t=e.code;if(t==="ESRCH")return!1;if(t==="EPERM")return!0;throw e}}function Y(r){L.mkdirSync(r,{recursive:!0,mode:448});let e=L.lstatSync(r);if(!e.isDirectory()||e.isSymbolicLink()||process.getuid&&e.uid!==process.getuid())throw new _("UNSAFE_DATA_DIRECTORY","CLI 私有目录的类型或所有者不正确。",1);process.platform==="win32"?$e(r,!0):L.chmodSync(r,448)}function ze(r){let e=ur("sha256").update(r).digest("hex").slice(0,32),t=oe.join(process.platform==="win32"?ot.tmpdir():"/tmp",`aios-cli-${process.getuid?.()??ot.userInfo().username}`);return{lock:oe.join(r,"daemon.lock"),mutex:oe.join(r,"daemon-owner.sqlite"),metadata:oe.join(r,"daemon.json"),socketDirectory:t,socket:process.platform==="win32"?`\\\\.\\pipe\\aios-cli-${e}`:oe.join(t,`${e}.sock`)}}function pr(r){let e=L.lstatSync(r,{throwIfNoEntry:!1});if(e&&(!e.isFile()||e.isSymbolicLink()))throw new _("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1);return e}function He(r){let e=pr(r);try{process.platform==="win32"&&e&&$e(r,!1)}catch(t){if(t.code==="ENOENT")return;throw t}return fr(r)}function fr(r){let e;try{e=L.openSync(r,L.constants.O_RDONLY|L.constants.O_NOFOLLOW)}catch(t){let n=t.code;if(n==="ENOENT")return;throw n==="ELOOP"?new _("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1):t}try{let t=L.fstatSync(e);if(!t.isFile()||process.getuid&&t.uid!==process.getuid()||process.platform!=="win32"&&(t.mode&63)!==0)throw new _("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1);try{return JSON.parse(L.readFileSync(e,"utf8"))}catch(n){throw n instanceof SyntaxError?new _("INVALID_DAEMON_METADATA","服务所有权记录损坏,原文件已保留。",1):n}}finally{L.closeSync(e)}}var mr=1,Dn=8*1024*1024;function Je(r){if(!r||typeof r!="object")return!1;let e=r;return e.protocol===mr&&Number.isSafeInteger(e.pid)&&Number(e.pid)>0&&(e.installationId===void 0||typeof e.installationId=="string")&&["instanceId","version","token","socket","root","startedAt"].every(t=>typeof e[t]=="string")}function it(r){let e=ze(r),t=He(e.metadata);if(!Je(t)||t.root!==r||t.socket!==e.socket||!X(t.pid))throw new f("CLI_NOT_RUNNING","请先启动指定数据目录的 CLI 后台服务。");if("sdkProtocol"in t)throw new f("RUNTIME_INCOMPATIBLE","该数据目录属于精简运行时,请使用 createClient。");return t}function ve(r){let e=ze(r),t=He(e.metadata);if(t!==void 0){if(!Je(t)||t.root!==r||t.socket!==e.socket||!("sdkProtocol"in t)||t.sdkProtocol!==1)throw new f("RUNTIME_INCOMPATIBLE","本机服务不支持当前 SDK 协议,或其归属记录不一致。");return X(t.pid)?t:void 0}}async function st(r,e){for(;;){e.throwIfAborted();let t=ve(r);if(t)return t;await gr(100,void 0,{signal:e})}}function ke(r,e,t,n,o,i,s=t==="runtime.drain"?0:12e4){let a=JSON.stringify({id:o,clientId:e,method:t,params:n});return Buffer.byteLength(a)>8*1024*1024?Promise.reject(new f("REQUEST_TOO_LARGE","SDK 请求超过 8 MiB。")):new Promise((c,l)=>{let d=u=>l(i?.aborted?i.reason:new f("OUTCOME_UNKNOWN",`请求 ${o} 的结果未知,请使用原命令 ID 查询回执。`,{cause:u})),p=hr.request({socketPath:r.socket,path:"/sdk",method:"POST",agent:!1,signal:i,headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json","content-length":Buffer.byteLength(a),"x-aios-protocol":"1","x-aios-instance":r.instanceId}},u=>{let h=[],g=0;u.on("data",y=>{g+=y.length,g>16777216?u.destroy(new Error("SDK 响应超过 16 MiB,请分页读取。")):h.push(y)}),u.once("error",d),u.once("end",()=>{try{if(u.statusCode===404)throw new f("SDK_UNSUPPORTED","此 CLI 版本未提供 SDK 接口,请使用包含 SDK 接口的版本。");let y=JSON.parse(Buffer.concat(h).toString("utf8"));if(y.id!==o||typeof y.ok!="boolean")throw new f("INVALID_RESPONSE","SDK 响应与请求不匹配。");if(!y.ok)throw new f(y.error?.code??"RUNTIME_ERROR",y.error?.message??"运行时返回未知错误。");c(y.value)}catch(y){l(y)}})});s>0&&p.setTimeout(s,()=>p.destroy(new Error("SDK 请求等待超时。"))),p.once("error",d),p.end(a)})}import C from"node:path";import ie from"node:fs";import{createHash as kr}from"node:crypto";import v from"node:fs";import D from"node:path";import{createHash as yr,randomUUID as Ie}from"node:crypto";var V=new Map,wr,be=/^(\d{16})-([a-f0-9]{64})\.json$/,Fe=r=>yr("sha256").update(r).digest("hex"),$=r=>`${r}.history`,at=r=>!0;function ct(r){if(v.existsSync(r+".bak")||v.existsSync(r+".bak.1"))return!0;try{return v.readdirSync($(r)).some(e=>be.test(e))}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Q=class extends Error{constructor(t,n,o=!1,i){let s=n==="missing"?"必要记录缺失":n==="temporarily_unavailable"?"记录暂时无法访问":n==="unsupported_version"?"记录版本不受支持":"记录已损坏";super(`${dt(t)}:${s}。请查看存储恢复详情。`);this.file=t;this.problem=n;this.recoveryAvailable=o;this.cause=i,this.name="StorageIntegrityError"}cause};function dt(r){return D.basename(r)==="settings.json"?"应用设置":D.basename(r).startsWith("codex-")?"任务执行记录":D.basename(r)}function Ve(r,e,t){let n;try{n=v.readFileSync(r)}catch(o){return{status:o.code==="ENOENT"?"missing":"temporarily_unavailable",error:o}}try{let o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n));if(t&&o&&typeof o=="object"&&"version"in o&&!t.includes(Number(o.version)))return{status:"unsupported_version",error:new Error("记录版本不受支持。")};if(!e(o))throw new Error("记录结构与所属文件不一致。");return{status:"healthy",value:o,bytes:n}}catch(o){return{status:"corrupt",error:o}}}function Ge(r,e){let t;try{t=v.readdirSync($(r))}catch(o){if(o.code==="ENOENT")t=[];else throw o}let n=[];for(let o of t.sort().reverse()){let i=be.exec(o);if(!i)continue;let s=D.join($(r),o),a=Ve(s,e);if(a.status==="temporarily_unavailable")throw a.error;a.status==="healthy"&&Fe(a.bytes)===i[2]&&n.push({file:s,generation:Number(i[1]),value:a.value,bytes:a.bytes})}if(!n.length)for(let o of[".bak",".bak.1"]){let i=Ve(r+o,e);if(i.status==="temporarily_unavailable")throw i.error;i.status==="healthy"&&n.push({file:r+o,generation:0,value:i.value,bytes:i.bytes})}return n}function lt(r,e,t,n){let o=D.resolve(r),i=V.get(o),s=new Q(r,e,t).message,a={id:i?.issue.id??Ie(),fileName:dt(r),status:e,message:s,detectedAt:i?.issue.detectedAt??new Date().toISOString(),recoveryAvailable:t};V.set(o,{issue:a,file:o,options:n}),(!i||i.issue.status!==e||i.issue.recoveryAvailable!==t)&&wr?.({...a}),V.size>256&&V.delete(V.keys().next().value)}function Ee(r,e,t){v.mkdirSync(D.dirname(r),{recursive:!0,mode:448});let n=`${r}.${Ie()}.tmp`,o;try{o=v.openSync(n,"wx",384),v.writeFileSync(o,e),t&&v.fsyncSync(o),v.closeSync(o),o=void 0,v.renameSync(n,r)}finally{o!==void 0&&v.closeSync(o);try{v.unlinkSync(n)}catch(i){if(i.code!=="ENOENT")throw i}}}function Sr(r){let e=D.join($(r),"damaged");v.mkdirSync(e,{recursive:!0,mode:448});try{v.copyFileSync(r,D.join(e,`${Date.now()}-${Ie()}.bin`),v.constants.COPYFILE_EXCL)}catch(t){if(t.code!=="ENOENT")throw t}}function ut(r,e={}){let t=e.validate??at,n=Ve(r,t,e.versions);if(n.status==="healthy")return{...n,recoveryAvailable:!1};if(n.status==="temporarily_unavailable"||n.status==="unsupported_version")return{...n,recoveryAvailable:!1};let o=Ge(r,t)[0];return{...n,backup:o,recoveryAvailable:!!o}}function pt(r,e={}){let t=ut(r,e);if(t.status==="healthy")return V.delete(D.resolve(r)),t.value;if(t.status==="missing"&&!t.recoveryAvailable&&!e.required&&!ct(r))return null;lt(r,t.status,t.recoveryAvailable,e);let n=v.existsSync($(r))?Math.max(0,...v.readdirSync($(r)).map(o=>Number(be.exec(o)?.[1]??0))):0;if(e.recover&&"backup"in t&&t.backup&&(e.allowOlderRecovery||t.backup.generation===n))return Sr(r),Ee(r,t.backup.bytes,!0),V.delete(D.resolve(r)),console.info("[storage-integrity] recovered",{file:r,source:t.backup.file}),t.backup.value;throw new Q(r,t.status,t.recoveryAvailable,t.error)}function ft(r,e,t){let n=Ge(r,t),o=Fe(e);if(n[0]?.generation&&Fe(n[0].bytes)===o)return;v.mkdirSync($(r),{recursive:!0,mode:448});let i=Math.max(0,...v.readdirSync($(r)).map(c=>Number(be.exec(c)?.[1]??0)))+1,s=D.join($(r),`${String(i).padStart(16,"0")}-${o}.json`),a=`${s}.${Ie()}.pending`;return Ee(a,e,!0),{temporary:a,destination:s}}function vr(r,e,t){let n=ft(r,e,t);if(n)try{v.renameSync(n.temporary,n.destination)}finally{try{v.unlinkSync(n.temporary)}catch(o){if(o.code!=="ENOENT")throw o}}}function mt(r,e,t={}){let n=t.validate??at;if(!n(e))throw new Q(r,"corrupt",!1,new Error("拒绝写入无效记录。"));let o=ut(r,t);if(o.status!=="healthy"&&!(o.status==="missing"&&!o.recoveryAvailable&&!ct(r)))throw lt(r,o.status,o.recoveryAvailable,t),new Q(r,o.status,o.recoveryAvailable,o.error);let i=Buffer.from(`${JSON.stringify(e,null,2)}
2
+ `);t.checkpoint!==!1&&o.status==="healthy"&&vr(r,o.bytes,n);let s=t.checkpoint!==!1?ft(r,i,n):void 0;try{if(t.checkpoint!==!1)for(let a of Ge(r,n).slice(2))a.generation>0&&v.unlinkSync(a.file);if(Ee(r,i,t.durable!==!1),s)try{v.renameSync(s.temporary,s.destination)}catch(a){try{o.status==="healthy"?Ee(r,o.bytes,!0):v.unlinkSync(r)}catch(c){throw Object.assign(new Error("记录保存失败,且回滚未完成。"),{errors:[a,c]})}throw a}}finally{if(s)try{v.unlinkSync(s.temporary)}catch(a){if(a.code!=="ENOENT")throw a}}}function We(r){let e=new URL(r);if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.search||e.hash)throw new Error("平台基地址无效。");return e.toString().replace(/\/+$/,"")}function qe(r){let e=r.mode==="platform"?We(r.platformBaseUrl):null,t=[r.mode,r.appId,r.userScope,e];if(r.mode==="platform"&&r.authentication){let{userId:n,tenantId:o,workspaceId:i}=r.authentication.principal;t.push(JSON.stringify(["managed",n,o,i]))}return kr("sha256").update(JSON.stringify(t)).digest("hex")}function xe(r){let e=qe(r),t=C.resolve(r.runtime.dataDirectory),n=C.join(t,"applications",e);if(process.platform!=="win32")return n;let o=C.join(t,"a",e.slice(0,32)),i=gt(t,e);if(i){let s=i.version===1?n:o;if(!ie.statSync(s,{throwIfNoEntry:!1})?.isDirectory())throw new Error("应用运行目录丢失,请恢复原目录,不能创建空目录替代。");if(ie.existsSync(i.version===1?o:n))throw new Error("应用同时存在新旧运行目录,请检查数据完整性。");return s}if(ie.existsSync(n)){if(ie.existsSync(o))throw new Error("应用同时存在新旧运行目录,请检查数据完整性。");return n}if(ie.existsSync(o))throw new Error("应用短目录缺少布局记录,请检查数据完整性。");return o}var ht=(r,e)=>C.join(r,"a",e.slice(0,32)+".json");function gt(r,e){return pt(ht(r,e),{recover:!1,validate:t=>{let n=t;return!!n&&(n.version===1||n.version===2)&&n.identity===e}})}function yt(r){let e=xe(r);if(Y(e),process.platform==="win32"){let t=C.resolve(r.runtime.dataDirectory),n=qe(r);if(!gt(t,n)){let o=C.basename(C.dirname(e))==="applications"?1:2;mt(ht(t,n),{version:o,identity:n},{validate:i=>{let s=i;return!!s&&s.version===o&&s.identity===n}})}}return e}function wt(r){let e=xe(r),t=qe(r);if(process.platform==="win32"){let o=(i,s)=>C.join(C.resolve(i??r.runtime.dataDirectory),s,t.slice(0,20));return{tasks:o(void 0,"t"),workspaces:o(r.runtime.workspaceDirectory,"w"),cache:o(r.runtime.cacheDirectory,"c"),temporary:o(r.runtime.temporaryDirectory,"tmp")}}let n=(o,i)=>o?C.join(C.resolve(o),"applications",t,i):C.join(e,i);return{workspaces:n(r.runtime.workspaceDirectory,"workspaces"),cache:n(r.runtime.cacheDirectory,"cache"),temporary:n(r.runtime.temporaryDirectory,"tmp")}}import Ke from"node:path";function St(r){for(let[e,t]of Object.entries({appId:r.appId,userScope:r.userScope}))if(typeof t!="string"||!t.trim()||t.length>256||/[\u0000-\u001f]/u.test(t))throw new Error(`独立运行身份 ${e} 无效。`);if(r.mode!=="standalone")throw new Error("独立运行身份模式不匹配。");return{mode:"standalone",appId:r.appId,userScope:r.userScope}}function A(r,e){return Object.assign(new Error(e),{code:r})}function vt(r,e){if(!r||r.kind!=="managed")throw new Error("托管身份配置无效。");let t=r.principal;if(!t||typeof t.userId!="string"||!t.userId.trim()||![t.tenantId,t.workspaceId].every(o=>o===null||typeof o=="string"&&o.trim()))throw new Error("托管身份必须明确指定用户、租户和工作区;无租户或工作区时使用 null。");let n=r.allowedOrigins??[];if(!Array.isArray(n)||n.some(o=>{let i=new URL(o);return!["http:","https:"].includes(i.protocol)||i.origin!==o}))throw new Error("凭证目标必须是 HTTP(S) origin,不能包含路径或认证信息。");return new URL(e),{kind:"managed",principal:{userId:t.userId,tenantId:t.tenantId,workspaceId:t.workspaceId},allowedOrigins:[...new Set(n)]}}function kt(r,e,t,n=Date.now()){if(!r||typeof r.accessToken!="string"||!r.accessToken.trim())throw new Error("托管凭证缺少 accessToken。");let o=r.session;if(!o||o.user?.id!==e.userId||typeof o.platformBaseUrl!="string"||o.platformBaseUrl.replace(/\/+$/,"")!==t.replace(/\/+$/,""))throw A("MANAGED_IDENTITY_MISMATCH","托管凭证的平台或用户与绑定身份不一致。");let i=r.accessToken.split(".");if(i.length!==3)throw new Error("平台托管凭证必须是 JWT。");let s=JSON.parse(Buffer.from(i[1],"base64url").toString("utf8"));if(!s||typeof s!="object"||Array.isArray(s))throw new Error("平台凭证的 JWT 内容无效。");let a=(...E)=>{let W=E.map(x=>s[x]).find(x=>typeof x=="string"&&x.trim());return typeof W=="string"?W:null},c=a("sub"),l=a("tenantId","tenant_id"),d=a("workspaceId","workspace_id")??o.context?.currentWorkspaceId??null;if(c!==e.userId||l!==e.tenantId||d!==e.workspaceId||(o.context?.currentTenantId??null)!==e.tenantId||(o.context?.currentWorkspaceId??null)!==e.workspaceId)throw A("MANAGED_IDENTITY_MISMATCH","托管凭证续期不得改变用户、租户或工作区。");let p=Date.parse(o.accessTokenExpiresAt);if(!Number.isFinite(p)||p<=n||typeof s.exp!="number"||!Number.isFinite(s.exp)||s.exp*1e3<=n)throw A("MANAGED_CREDENTIAL_EXPIRED","应用返回的托管凭证已经过期。");if(typeof o.user.username!="string"||typeof o.user.displayName!="string"||!Array.isArray(o.user.roles)||!o.user.roles.every(E=>typeof E=="string")||!Array.isArray(o.tenants))throw new Error("托管凭证的用户资料格式无效。");let{id:u,username:h,displayName:g,email:y,phone:I,avatarUrl:S,tenantId:m,roles:w}=o.user,k=o.tenants.map(E=>{if(!E||typeof E.id!="string"||typeof E.name!="string"||typeof E.displayName!="string")throw new Error("托管凭证的租户资料格式无效。");return{id:E.id,name:E.name,displayName:E.displayName,status:E.status}});return{credential:{accessToken:r.accessToken,session:{user:{id:u,username:h,displayName:g,email:y,phone:I,avatarUrl:S,tenantId:m,roles:[...w]},tenants:k,context:{currentTenantId:e.tenantId,currentWorkspaceId:e.workspaceId,personalMode:o.context?.personalMode,contextVersion:o.context?.contextVersion},platformBaseUrl:t,authenticatedAt:o.authenticatedAt,accessTokenExpiresAt:o.accessTokenExpiresAt}},expiresAt:Math.min(p,s.exp*1e3),sessionId:a("sessionId","sid")}}function Et(r){if(r!==void 0){if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(e=>!["startupTimeoutMs","rpcTimeoutMs","methodTimeoutMs","shutdownTimeoutMs"].includes(e)))throw new Error("通信等待配置无效。");for(let e of["startupTimeoutMs","rpcTimeoutMs","shutdownTimeoutMs"]){let t=r[e];if(t!==void 0&&(!Number.isSafeInteger(t)||t<(e==="rpcTimeoutMs"?0:1)||t>2147483647))throw new Error(`${e} 必须是有效毫秒数。`)}if(r.methodTimeoutMs!==void 0){if(!r.methodTimeoutMs||typeof r.methodTimeoutMs!="object"||Array.isArray(r.methodTimeoutMs))throw new Error("方法等待配置无效。");for(let[e,t]of Object.entries(r.methodTimeoutMs))if(!/^[a-zA-Z][a-zA-Z0-9.]+$/.test(e)||!Number.isSafeInteger(t)||t<0||t>2147483647)throw new Error("方法等待配置无效。")}}}function It(r,e){return e?.methodTimeoutMs?.[r]??(r==="runtime.drain"?0:e?.rpcTimeoutMs??12e4)}function bt(r){if(!r||typeof r!="object"||Array.isArray(r)||Object.entries(r).some(([e,t])=>!["temperature","topP","maxOutputTokens","responseFormat"].includes(e)||typeof t!="boolean"))throw new Error("模型生成能力声明无效。")}function xt(r){if(r===void 0)return;if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(t=>!["storage","extraction"].includes(t))||r.storage!==void 0&&!["local","external"].includes(r.storage))throw new Error("记忆配置无效。");let e=r.extraction;if(e!==void 0&&(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(t=>!["enabled","idleMs","model","instructions","timeoutMs"].includes(t))||e.enabled!==void 0&&typeof e.enabled!="boolean"||e.idleMs!==void 0&&(!Number.isSafeInteger(e.idleMs)||e.idleMs<0||e.idleMs>2147483647)||e.timeoutMs!==void 0&&(!Number.isSafeInteger(e.timeoutMs)||e.timeoutMs<1||e.timeoutMs>2147483647)||e.model!==void 0&&(typeof e.model!="string"||!e.model.trim())||e.instructions!==void 0&&(typeof e.instructions!="string"||e.instructions.length>32e3)))throw new Error("记忆提取策略无效。")}function se(r){if(!r||!["platform","standalone"].includes(r.mode))throw new Error("必须明确选择 platform 或 standalone 模式。");if(St({mode:"standalone",appId:r.appId,userScope:r.userScope}),Et(r.communication),xt(r.memory),r.authorization!==void 0&&(!r.authorization||typeof r.authorization.required!="boolean"||Object.keys(r.authorization).some(e=>e!=="required")))throw new Error("会话授权配置无效。");if(r.generationCapabilities!==void 0){if(!r.generationCapabilities||typeof r.generationCapabilities!="object"||Array.isArray(r.generationCapabilities))throw new Error("模型能力目录无效。");Object.values(r.generationCapabilities).forEach(bt)}if(!r.runtime||typeof r.runtime.directory!="string"||!r.runtime.directory.trim()||typeof r.runtime.dataDirectory!="string"||!r.runtime.dataDirectory.trim())throw new Error("运行时目录和数据目录不能为空。");if(r.mode==="standalone"&&"platformBaseUrl"in r)throw new Error("独立模式不得配置平台基地址。");if(r.mode==="platform"&&"models"in r)throw new Error("平台模式不得配置独立模式模型列表。");if(r.mode==="standalone"&&"authentication"in r)throw new Error("独立模式不使用平台托管凭证。");if(r.runtime.tools&&Object.keys(r.runtime.tools).some(e=>!["node","python","git","bash","npm"].includes(e)))throw new Error("工具路径配置包含未知工具。");if(r.appName!==void 0&&(typeof r.appName!="string"||!r.appName.trim()||r.appName.length>128))throw new Error("应用名称无效。");for(let e of["workspaceDirectory","cacheDirectory","temporaryDirectory"]){let t=r.runtime[e];if(t!==void 0&&(typeof t!="string"||!t.trim()||!Ke.isAbsolute(t)))throw new Error(`${e} 必须是绝对目录路径。`)}return{...structuredClone(r),runtime:{...structuredClone(r.runtime),directory:Ke.resolve(r.runtime.directory),dataDirectory:Ke.resolve(r.runtime.dataDirectory)},...r.mode==="platform"?{platformBaseUrl:We(r.platformBaseUrl),...r.authentication!==void 0?{authentication:vt(r.authentication,r.platformBaseUrl)}:{}}:{}}}import{setTimeout as Tr}from"node:timers/promises";import F from"node:fs";import M from"node:path";import{createHash as Rt,verify as br}from"node:crypto";var At=`-----BEGIN PUBLIC KEY-----
3
3
  MCowBQYDK2VwAyEAH1NI5TKlc89zXnULhsNPzgN4M1ki3w5spKY7BH8VsZw=
4
- -----END PUBLIC KEY-----`;var Ae={version:"0.0.7",protocol:1,dataFormat:1,profile:"light"};import Te from"node:fs";import H from"node:path";import{createHash as Ir}from"node:crypto";var z=r=>new f("RUNTIME_INTEGRITY_FAILED",r);function Tt(r,e){if(!e||e.includes("\\")||H.posix.normalize(e)!==e||H.posix.isAbsolute(e)||e===".."||e.startsWith("../"))throw z(`共享运行资源路径无效:${e}`);let t=H.resolve(r,e),n=H.relative(r,Te.realpathSync(t));if(n===".."||n.startsWith(`..${H.sep}`)||H.isAbsolute(n))throw z(`共享运行资源越界:${e}`);return t}async function Ot(r,e){if(!e||typeof e!="object"||Array.isArray(e))throw z("缺少共享运行资源清单。");let t=e;if(t.root!=="../.."||typeof t.codex!="string"||!t.files||typeof t.files!="object"||Array.isArray(t.files))throw z("共享运行资源清单无效。");let n=Te.realpathSync(H.resolve(r,t.root));if(H.relative(n,r).split(H.sep).join("/")!=="runtime/sdk-host")throw z("共享宿主不在产品运行资源目录中。");let o=t.files;for(let i of[t.codex,"runtime/desktop-agent-runtime/index.js","runtime/desktop-agent-runtime/package.json"])if(!Object.hasOwn(o,i))throw z(`共享运行资源缺少必需文件:${i}`);for(let[i,s]of Object.entries(o)){if(!s||typeof s!="object"||Array.isArray(s))throw z(`共享运行资源属性无效:${i}`);let a=s,c=Tt(n,i),l=Te.lstatSync(c);if(a.type!=="file"||!l.isFile()||l.isSymbolicLink()||l.size!==a.size||typeof a.sha256!="string"||!/^[a-f0-9]{64}$/.test(a.sha256))throw z(`共享运行资源属性不匹配:${i}`);let d=Ir("sha256");for await(let p of Te.createReadStream(c))d.update(p);if(d.digest("hex")!==a.sha256)throw z(`共享运行资源摘要不匹配:${i}`)}return{root:n,codexExecutable:Tt(n,t.codex)}}var J=r=>new f("RUNTIME_INTEGRITY_FAILED",r);function Rt(r,e){let t=M.relative(r,e);return t!==".."&&!t.startsWith(`..${M.sep}`)&&!M.isAbsolute(t)}async function N(r,e=At,t={platform:process.platform,arch:process.arch}){let n=F.realpathSync(r),o=M.join(n,"aios-sdk-runtime.json"),i=F.readFileSync(o),s=JSON.parse(i.toString("utf8"));if(s.schemaVersion!==1||s.version!==Ae.version||s.protocol!==Ae.protocol||s.dataFormat!==Ae.dataFormat||s.platform!==t.platform||s.arch!==t.arch||!["light","product"].includes(String(s.profile)))throw new f("RUNTIME_INCOMPATIBLE","精简运行时版本、协议、数据格式、系统或架构不兼容。");let a=JSON.parse(F.readFileSync(M.join(n,"signature.json"),"utf8"));if(a.algorithm!=="ed25519"||typeof a.signature!="string"||a.publicKey?.trim()!==e.trim()||!br(null,i,e,Buffer.from(a.signature,"base64")))throw J("运行时清单签名与可信发布公钥不匹配。");if(!s.files||typeof s.files!="object"||Array.isArray(s.files))throw J("运行时缺少文件清单。");let c=s.files,l=["host.mjs","js-hook-runner.js","memory-worker.js","memory-schema-v1.sql","task-event-reader-worker.js","task-storage-recovery-worker.js","keyring.node",...s.profile==="light"?["resources/runtime/desktop-agent-runtime/index.js",`resources/runtime/codex/${t.platform}-${t.arch}/bin/${t.platform==="win32"?"codex.exe":"codex"}`]:[]];for(let S of l)if(!Object.hasOwn(c,S))throw J(`运行时缺少必需资源:${S}`);let d=new Map,p=S=>{for(let m of F.readdirSync(S)){let w=M.join(S,m),k=M.relative(n,w).split(M.sep).join("/");if(["aios-sdk-runtime.json","signature.json"].includes(k))continue;let B=F.lstatSync(w);B.isDirectory()&&!B.isSymbolicLink()?p(w):d.set(k,B)}};if(p(n),d.size!==Object.keys(c).length)throw J("运行时文件数量与清单不一致。");let u=[];for(let[S,m]of Object.entries(c)){let w=M.resolve(n,S),k=d.get(S);if(!S||S.includes("\\")||M.posix.normalize(S)!==S||!Rt(n,w)||!k)throw J(`运行时文件路径或归属不匹配:${S}`);if(m.type==="link"){if(!k.isSymbolicLink()||typeof m.link!="string"||M.isAbsolute(m.link)||F.readlinkSync(w)!==m.link||!Rt(n,F.realpathSync(w)))throw J(`运行时链接不匹配:${S}`)}else if(m.type==="file"){if(!k.isFile()||k.isSymbolicLink()||k.size!==m.size||!/^[a-f0-9]{64}$/.test(m.sha256)||t.platform!=="win32"&&(k.mode&73)!==(m.mode&73))throw J(`运行时文件属性不匹配:${S}`);u.push({file:w,name:S,entry:m})}else throw J(`运行时文件类型无效:${S}`)}let h=0,y=(await Promise.allSettled(Array.from({length:Math.min(8,u.length)},async()=>{for(;h<u.length;){let{file:S,name:m,entry:w}=u[h++],k=Ct("sha256");for await(let B of F.createReadStream(S))k.update(B);if(k.digest("hex")!==w.sha256)throw J(`运行时文件摘要不匹配:${m}`)}}))).find(S=>S.status==="rejected");if(y)throw y.reason;let I=s.profile==="product"?await Ot(n,s.resources):void 0;return{version:s.version,protocol:s.protocol,dataFormat:s.dataFormat,platform:t.platform,arch:t.arch,profile:s.profile,manifestSha256:Ct("sha256").update(i).digest("hex"),...I?{productResources:I}:{}}}import Nt from"node:fs";import Pt from"node:path";import{spawn as xr}from"node:child_process";function Oe(r){let{options:e}=r,t=yt(e),n=wt(e).temporary;Y(n);let o=Nt.openSync(Pt.join(t,"sdk-host.log"),"a",384),i=(()=>{try{return xr(e.runtime.nodeExecutable??process.execPath,[Pt.join(e.runtime.directory,"host.mjs")],{detached:!r.managed,windowsHide:!0,stdio:["ignore",o,o,"ipc"],env:{...process.env,TEMP:n,TMP:n,TMPDIR:n}})}finally{Nt.closeSync(o)}})(),s=new Promise(c=>{i.once("exit",(l,d)=>c({code:l,signal:d})),i.once("error",()=>{i.pid||c({code:null,signal:null})})}),a=new Promise((c,l)=>{let d=setTimeout(()=>h(new f("RUNTIME_START_TIMEOUT","SDK 服务未在指定时间内完成启动,请检查宿主日志。")),e.communication?.startupTimeoutMs??12e4),p=(g,y)=>h(new f("RUNTIME_START_FAILED",`SDK 服务启动进程退出(${g??y})。`)),u=g=>{if(!g||g.type!=="ready"){h(new f("RUNTIME_INCOMPATIBLE","宿主未返回当前 SDK 启动协议,请使用配套运行包。"));return}g.ok?h(void 0,g.value):h(new f(g.error.code,g.error.message))};function h(g,y){clearTimeout(d),i.removeListener("error",h),i.removeListener("exit",p),i.removeListener("message",u),g?l(g):c(y)}i.once("error",h),i.once("exit",p),i.on("message",u),i.send(r,g=>{g&&h(g)})});return{child:i,ready:a,exited:s}}var ae=class r{constructor(e,t,n){this.metadata=e;this.ownerExit=t;this.communication=n}eventWaitMs=0;closed=!1;clientId=jt();static async start(e,t){let n=se(e),o=Ar.resolve(n.runtime.directory),i=await N(o,n.runtime.trustedPublicKey),s=xe(n),a=ve(s);if(!a){let{child:c,ready:l}=Oe({options:n,verifiedPackage:i});try{a=await l}catch(d){if(!(d instanceof f)||d.code!=="DAEMON_ALREADY_OWNED")throw d;a=await st(s,AbortSignal.timeout(n.communication?.startupTimeoutMs??12e4))}finally{c.connected&&c.disconnect(),c.unref()}}return r.attach(n,a,i,t)}static async attach(e,t,n,o,i){if(t.version!==n.version||t.manifestSha256!==n.manifestSha256)throw new f("RUNTIME_INCOMPATIBLE","已运行的服务与指定运行包不一致,请由宿主所有者关闭后使用同一运行包重新启动。");let s=new r(t,i,e.communication),a=await s.call("attach",{options:e,pid:process.pid,manifestSha256:n.manifestSha256});if(s.eventWaitMs=a.eventWaitMs??0,o)try{await s.call("auth.bindProvider",o)}catch(c){throw await s.stop(),c}return s}call(e,t={},n=jt(),o){return this.closed?Promise.reject(new f("RUNTIME_CLOSED","SDK 客户端连接已关闭。")):this.ownerExit?.aborted?Promise.reject(this.ownerExit.reason):ke(this.metadata,this.clientId,e,t,n,o,It(e,this.communication))}async stop(){if(!this.closed){if(this.ownerExit?.aborted){this.closed=!0;return}await this.call("detach"),this.closed=!0}}async shutdown(){await this.call("shutdown"),this.closed=!0;let e=AbortSignal.timeout(this.communication?.shutdownTimeoutMs??12e4);for(;ve(this.metadata.root)?.instanceId===this.metadata.instanceId||X(this.metadata.pid);)await Tr(100,void 0,{signal:e})}};import Or from"node:path";import{randomUUID as _t}from"node:crypto";var Ce=class r{constructor(e){this.metadata=e}closed=!1;clientId=_t();static async connect(e){let t=new r(it(Or.resolve(e.dataDirectory)));return await t.call("attach",{sdkProtocol:1,options:e,pid:process.pid}),t}call(e,t={},n=_t(),o){return this.closed?Promise.reject(new f("RUNTIME_CLOSED","SDK 客户端连接已关闭。")):ke(this.metadata,this.clientId,e,t,n,o)}async stop(){this.closed||(await this.call("detach"),this.closed=!0)}async shutdown(){throw new f("SHARED_RUNTIME","连接已有 CLI 时,请通过 CLI 管理后台服务。")}};import Nr from"node:http";import{randomBytes as Pr,randomUUID as jr,timingSafeEqual as _r}from"node:crypto";import{Ajv as Dr}from"ajv";import{Ajv2020 as Mr}from"ajv/dist/2020.js";function Cr(r){let e={...r,kind:"aios-tool-result"};return Xe(e),e}function Z(r,e){if(typeof r!="string"||!r.trim())throw new Error(`工具返回的 ${e} 必须是非空字符串。`)}function Xe(r){if(!r||typeof r!="object"||!("kind"in r)||r.kind!=="aios-tool-result")return{content:[{type:"text",text:typeof r=="string"?r:JSON.stringify(r??null)}],isError:!1};let e=r;if(!Array.isArray(e.content))throw new Error("工具返回的 content 必须是数组。");let t=e.content.map(n=>{if(!n||typeof n!="object")throw new Error("工具返回的内容格式无效。");if(n.type==="text"){if(typeof n.text!="string")throw new Error("工具返回的 text 必须是字符串。");return{type:"text",text:n.text}}if(n.type==="image")return Z(n.data,"image.data"),Z(n.mimeType,"image.mimeType"),{type:"image",data:n.data,mimeType:n.mimeType};if(n.type==="resource"){let o=n.resource;Z(o?.uri,"resource.uri"),new URL(o.uri),o.mimeType!==void 0&&Z(o.mimeType,"resource.mimeType");let i="text"in o,s="blob"in o;if(i===s||i&&typeof o.text!="string"||s&&typeof o.blob!="string")throw new Error("工具文件内容必须且只能包含 text 或 blob。");return{type:"resource",resource:{uri:o.uri,...o.mimeType?{mimeType:o.mimeType}:{},...i?{text:o.text}:{blob:o.blob}}}}throw new Error("不支持的工具内容类型。")});if(e.data!==void 0){if(!e.data||typeof e.data!="object"||Array.isArray(e.data))throw new Error("工具返回的 data 必须是 JSON 对象。");t.push({type:"text",text:JSON.stringify(e.data)})}return e.error!==void 0&&(Z(e.error.code,"error.code"),Z(e.error.message,"error.message"),t.push({type:"text",text:JSON.stringify({error:e.error})})),{content:t,isError:e.error!==void 0}}var Dt=["projectId","collaborationProjectId","assistantId","platformSessionId","platformTurnId","platformTaskId","platformRunId","traceId"];function ce(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("执行上下文必须为对象。");return r}function G(r){if(typeof r!="string"||!r.trim()||r.length>512||/[\x00-\x1f\x7f]/.test(r))throw new Error("执行上下文字段必须为有效字符串,最多 512 字符。");return r}function Mt(r){let e=ce(r);if(Object.keys(e).some(t=>!["userId","tenantId","name"].includes(t)))throw new Error("执行主体包含未知字段。");return{userId:G(e.userId),tenantId:e.tenantId===null?null:G(e.tenantId),...e.name===void 0?{}:{name:G(e.name)}}}function Rr(r){let e=ce(r);if(Object.keys(e).some(n=>!["actor","owner","workspaceId","usageScene","metadata",...Dt].includes(n)))throw new Error("执行上下文包含未知字段。");if(!["personal","greeting","task","collaboration","coding"].includes(String(e.usageScene)))throw new Error("执行用量场景无效。");let t={actor:Mt(e.actor),owner:Mt(e.owner),workspaceId:e.workspaceId===null?null:G(e.workspaceId),usageScene:e.usageScene};for(let n of Dt)e[n]!==void 0&&(t[n]=G(e[n]));if(e.metadata!==void 0){let n=ce(e.metadata);if(Object.keys(n).length>16||JSON.stringify(n).length>8192)throw new Error("业务扩展元数据超过限制。");for(let[o,i]of Object.entries(n)){if(!/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(o))throw new Error("业务元数据命名空间无效。");let s=ce(i);if(Object.keys(s).length>32)throw new Error("业务元数据字段过多。");for(let[a,c]of Object.entries(s))if(!/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(a)||!(c===null||typeof c=="boolean"||typeof c=="number"&&Number.isFinite(c)||typeof c=="string"&&c.length<=1024&&!/[\x00-\x1f\x7f]/.test(c)))throw new Error("业务元数据字段无效。")}t.metadata=structuredClone(n)}return t}function Re(r){let e=ce(r);if(Object.keys(e).some(t=>!["sessionId","runId","context"].includes(t)))throw new Error("执行绑定包含未知字段。");return{sessionId:G(e.sessionId),runId:G(e.runId),...e.context===void 0?{}:{context:Rr(e.context)}}}async function Lt(r,e,t){let n=new Map,o=new Dr({strict:!0,strictTypes:!1,allErrors:!0,validateFormats:!1}),i=new Mr({strict:!0,strictTypes:!1,allErrors:!0,validateFormats:!1}),s=new Map;for(let m of e){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(m.name)||n.has(m.name))throw new Error(`业务工具名称无效或重复:${m.name}`);if(m.inputSchema.type!=="object")throw new Error(`业务工具 ${m.name} 的输入 schema 必须为 object。`);n.set(m.name,m);let w=m.inputSchema.$schema==="http://json-schema.org/draft-07/schema#"?o:i;s.set(m.name,w.compile(m.inputSchema))}let a=Pr(32).toString("hex"),c=new Map,l=new Set,d=!1,p,u,h=new Promise(m=>{u=m}),g=()=>p??=(async()=>{for(let m of c.values())m.abort(new Error("应用工具提供者已关闭。"));I.closeAllConnections(),await new Promise((m,w)=>I.close(k=>k?w(k):m())),u()})(),y=()=>{d&&l.size===0&&c.size===0&&g()},I=Nr.createServer(async(m,w)=>{let k=Buffer.from(`Bearer ${a}`),B=Buffer.from(m.headers.authorization??"");if(B.length!==k.length||!_r(B,k)){w.writeHead(401).end();return}if(m.url!=="/mcp"){w.writeHead(404).end();return}let E=m.headers["mcp-session-id"];if(m.method==="DELETE"&&typeof E=="string"&&l.delete(E)){for(let[j,q]of c)j.startsWith(`${E}:`)&&q.abort(new Error("工具会话已关闭。"));w.writeHead(204).end(),y();return}if(m.method!=="POST"){w.writeHead(405).end();return}let W=null,x=(j,q=!1)=>{let O=JSON.stringify({jsonrpc:"2.0",id:W,...q?{error:j}:{result:j}});w.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),w.end(O)};try{let j=0,q=[];for await(let b of m){let K=Buffer.from(b);if(j+=K.length,j>8*1024*1024)throw new Error("业务工具请求超过 8 MiB。");q.push(K)}let O=JSON.parse(Buffer.concat(q).toString("utf8"));if(W=O.id??null,O.method==="initialize"){if(d){x({code:-32e3,message:"应用工具提供者已注销。"},!0);return}let b=jr();l.add(b),w.setHeader("mcp-session-id",b),x({protocolVersion:"2025-03-26",capabilities:{tools:{listChanged:!1}},serverInfo:{name:r,version:"1"}});return}if(typeof E!="string"||!l.has(E)){w.writeHead(404).end();return}if(O.method==="notifications/cancelled"){c.get(`${E}:${String(O.params?.requestId)}`)?.abort(new Error("工具调用已取消。")),w.writeHead(202).end();return}if(O.id===void 0){w.writeHead(202).end();return}if(O.method==="ping"){x({});return}if(O.method==="tools/list"){x({tools:e.map(b=>({name:b.name,description:b.description,inputSchema:b.inputSchema,annotations:{readOnlyHint:b.readOnly,destructiveHint:!b.readOnly,openWorldHint:!0}}))});return}if(O.method!=="tools/call"){x({code:-32601,message:"不支持的 MCP 方法。"},!0);return}let ye=n.get(String(O.params?.name));if(!ye)throw new Error("业务工具不存在。");let ee=O.params?.arguments;if(!ee||typeof ee!="object"||Array.isArray(ee))throw new Error("工具参数必须是对象。");let tt=s.get(ye.name);if(!tt(ee)){x({content:[{type:"text",text:`工具参数不符合声明:${JSON.stringify(tt.errors)}`}],isError:!0});return}let te=new AbortController,we=`${E}:${String(W)}`;if(c.has(we))throw new Error("工具请求 ID 正在执行,不能重复提交。");c.set(we,te);let rt=()=>{w.writableEnded||te.abort(new Error("工具请求连接已关闭。"))};w.once("close",rt);let re="validation";try{let K=O.params?._meta?.["aios/execution"],{invocationId:Le,...Kt}=K??{},Se=K===void 0?void 0:Re(Kt);if(K&&(typeof Le!="string"||!Le))throw new Error("工具调用标识缺失。");re="execution";let Xt=await ye.execute(ee,{signal:te.signal,callId:we,...Se&&t?{files:{resolve:(Yt,Qt)=>t(Se.sessionId,Yt,Qt,te.signal)}}:{},...Se?{execution:Ut({...Se,invocationId:Le})}:{}});re="serialization",te.signal.throwIfAborted(),x(Xe(Xt))}catch(b){x({content:[{type:"text",text:JSON.stringify({error:{message:(b instanceof Error?b.message:String(b)).slice(0,4096),capability:ye.name,phase:re,side_effects:re==="validation"?"not_started":re==="serialization"?"completed":"unknown",next_action:"先核对实际结果,不要因工具返回失败而直接重复执行。"}})}],isError:!0})}finally{w.removeListener("close",rt),c.delete(we),y()}}catch(j){x({code:-32602,message:j instanceof Error?j.message:String(j)},!0)}});return await new Promise((m,w)=>{I.once("error",w),I.listen(0,"127.0.0.1",m)}),{descriptor:{id:r,name:r,transport:"HTTP",url:`http://127.0.0.1:${I.address().port}/mcp`,bearerToken:a,tools:e.map(m=>m.name),defaultToolsApproval:"prompt",toolApprovals:Object.fromEntries(e.map(m=>[m.name,m.readOnly?"auto":"prompt"]))},close:g,closed:h,status:()=>({retired:d,sessions:l.size,calls:c.size,closing:!!p}),retire:()=>{d=!0,y()}}}function Ut(r){return r&&typeof r=="object"&&(Object.values(r).forEach(Ut),Object.freeze(r)),r}import{createHash as $r}from"node:crypto";var Lr=/^[a-z][a-z0-9_]{0,63}$/u;function Ur(r){return r.trim().toLowerCase()}function Ye(r){let e=Ur(r);if(!Lr.test(e))throw new Error("MCP 技能引用标识只能包含小写字母、数字和下划线,必须以字母开头,最长 64 个字符");return e}function Br(r){return`aios_mcp_${Ye(r)}`}function Bt(r,e){let t=e.trim();if(!t)throw new Error("MCP 工具名称不能为空");return`mcp__${Br(r)}__${t}`}function Ne(r){return r.toolProviderId===void 0?`app_${$r("sha256").update(JSON.stringify([r.id,r.version])).digest("hex").slice(0,32)}`:Ye(r.toolProviderId)}function Qe(r,e){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(e))throw new Error("业务工具名称无效。");return Bt(Ne(r),e)}import{randomUUID as zr}from"node:crypto";function Ze(r,e){if(!e)return r;function t(n){try{return n()}catch(o){process.emitWarning("SDK 诊断导出器执行失败,请检查应用诊断配置。",{code:"SDK_DIAGNOSTICS_FAILED",detail:o instanceof Error?o.name:typeof o})}}return{get eventWaitMs(){return r.eventWaitMs},stop:()=>r.stop(),shutdown:()=>r.shutdown(),async call(n,o,i=zr(),s){let a=performance.now(),c={name:"sdk.rpc",method:n,requestId:i},l=t(()=>e.startSpan?.("sdk.rpc",{method:n,requestId:i}));t(()=>e.log?.(Object.freeze({...c,phase:"started"})));let d="completed",p;try{return await r.call(n,o,i,s)}catch(u){throw d="failed",p=u&&typeof u=="object"&&"code"in u&&typeof u.code=="string"&&/^[A-Z0-9_]{1,80}$/.test(u.code)?u.code:"RPC_ERROR",u}finally{let u=performance.now()-a,h=Object.freeze({...c,phase:d,durationMs:u,...p?{errorCode:p}:{}});t(()=>e.log?.(h)),t(()=>e.metric?.("sdk.rpc.duration_ms",u,{method:n,outcome:d})),t(()=>l?.end(h))}}}}async function Pe(r,e){let t;try{t=await r()}catch(n){try{await e()}catch(o){throw new AggregateError([n,o],"文件传输及清理均失败。",{cause:n})}throw n}return await e(),t}var je=class{constructor(e,t){this.transport=e;this.sessionId=t}resolve(e,t="read",n){return this.transport.call("session.file.resolve",{id:this.sessionId,path:e,access:t},void 0,n)}call(e,t,n){return this.transport.call(`session.file.transfer.${e}`,{id:this.sessionId,...t},void 0,n)}async export(e,t,n){let{signal:o}=n,i=await this.call("begin",{kind:"export",path:e},o),s=this,a=0,c=(async function*(){for(;a<i.bytes;){o?.throwIfAborted();let l=await s.call("read",{transferId:i.id,offset:a},o);if(l.bytes<=0)throw new Error("导出数据意外结束。");a+=l.bytes,yield Buffer.from(l.data,"base64")}})();return Pe(async()=>{let l=await t.put({...n,source:c,sha256:i.sha256,bytes:i.bytes});if(o?.throwIfAborted(),a!==i.bytes||!l.version||l.key!==n.key)throw new Error("存储适配器未完整接收文件或未返回正确版本。");return{stored:l,file:i.file,sha256:i.sha256,bytes:i.bytes}},()=>Pe(()=>c.return(void 0),()=>this.call("close",{transferId:i.id})))}async import(e,t,n){if(!e.key||!e.version)throw new Error("导入必须指定对象存储键及版本。");let{signal:o}=n;o?.throwIfAborted();let i=await t.get({key:e.key,version:e.version,signal:o}),s=i.source[Symbol.asyncIterator](),a;return Pe(async()=>{a=await this.call("begin",{kind:"import",path:n.path,expectedVersion:n.expectedVersion,bytes:i.bytes,sha256:i.sha256},o);let c=0;for(;;){o?.throwIfAborted();let d=await s.next();if(d.done)break;let p=d.value;for(let u=0;u<p.byteLength;u+=a.chunkBytes){o?.throwIfAborted();let h=Buffer.from(p.subarray(u,u+a.chunkBytes));c=(await this.call("write",{transferId:a.id,offset:c,data:h.toString("base64")},o)).offset}}return o?.throwIfAborted(),{file:await this.call("commit",{transferId:a.id},o),source:e}},()=>Pe(async()=>s.return?.(),async()=>{a&&await this.call("close",{transferId:a.id})}))}};import Hr from"node:http";import{randomBytes as Jr,timingSafeEqual as Fr}from"node:crypto";async function $t(r){let e=Jr(32).toString("hex"),t=new Set,n=Hr.createServer(async(i,s)=>{let a=Buffer.from(`Bearer ${e}`),c=Buffer.from(i.headers.authorization??"");if(c.length!==a.length||!Fr(c,a)){s.writeHead(401).end();return}if(i.method!=="POST"||i.url!=="/callbacks"){s.writeHead(404).end();return}let l=new AbortController;t.add(l),s.once("close",()=>{s.writableFinished||l.abort(new Error("应用回调请求已断开。"))});try{let d=[],p=0;for await(let I of i){let S=Buffer.from(I);if(p+=S.length,p>64*1024*1024)throw new Error("应用回调请求超过 64 MiB。");d.push(S)}let u=JSON.parse(Buffer.concat(d).toString("utf8")),h=r.get(u.method);if(!h)throw Object.assign(new Error("应用回调不存在。"),{code:"APPLICATION_PROVIDER_OFFLINE"});let g=await h(u.params,l.signal);l.signal.throwIfAborted();let y=JSON.stringify({ok:!0,value:g});s.writeHead(200,{"content-type":"application/json"}).end(y)}catch(d){s.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify({ok:!1,error:{message:d instanceof Error?d.message:String(d),code:d&&typeof d=="object"&&"code"in d?String(d.code):"APPLICATION_CALLBACK_FAILED"}}))}finally{t.delete(l)}});return await new Promise((i,s)=>{n.once("error",s),n.listen(0,"127.0.0.1",i)}),{connection:{url:`http://127.0.0.1:${n.address().port}/callbacks`,token:e,methods:[...r.keys()]},close:async()=>{for(let i of t)i.abort(new Error("应用回调服务已关闭。"));n.closeAllConnections(),await new Promise((i,s)=>n.close(a=>a?s(a):i()))}}}function zt(r){if(!Array.isArray(r)||r.length>2)throw new Error("JS Hook 定义无效。");let e=new Set;return r.map(t=>{if(!t||typeof t!="object"||!["PreToolUse","PostToolUse"].includes(t.event)||e.has(t.event)||typeof t.callback!="string"||!/^hook\.[a-z0-9_]+\.(PreToolUse|PostToolUse)$/.test(t.callback)||!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1||t.timeoutMs>36e5||t.matcher!==void 0&&(typeof t.matcher!="string"||!t.matcher.trim())||Object.keys(t).some(n=>!["event","callback","matcher","timeoutMs"].includes(n)))throw new Error("JS Hook 字段无效。");return e.add(t.event),structuredClone(t)})}function Ht(r,e){let t=e===void 0?{}:e;if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(n=>!["decision","reason","additionalContext"].includes(n))||t.decision!==void 0&&!["continue","deny"].includes(t.decision)||["reason","additionalContext"].some(n=>{let o=t[n];return o!==void 0&&(typeof o!="string"||o.length>32e3)})||t.decision==="deny"&&!t.reason?.trim())throw new Error("Hook 决定无效,拒绝必须说明原因。");return{...t.decision==="deny"?{decision:"block",reason:t.reason}:{},hookSpecificOutput:{hookEventName:r,...t.additionalContext?{additionalContext:t.additionalContext}:{}}}}import Qr from"node:http";import{randomBytes as Zr,timingSafeEqual as en}from"node:crypto";var Vr="[REDACTED]",Gr="(?:密码|口令|密钥|令牌|私钥|凭据|验证码)",Wr=new RegExp(`(${Gr}\\s*["']?\\s*(?:[::=]|是(?!否)|为)\\s*)(?:"([^"]*)"|'([^']*)'|“([^”]*)”|‘([^’]*)’|([^\\s"'“”‘’,。;,;}]+))`,"gu");var qr=["authorization","password","passwd","passphrase","token","api[-_]?key","secret","cookie","credentials?","private[-_]?key","pat"].join("|"),Jt=`(?:[a-z0-9]+[-_])*(?:${qr})`,Kr=new RegExp(`(\\b${Jt}\\b["']?\\s*[:=]\\s*["']?)([^\\s"',};&,。;]+)`,"gi"),Xr=new RegExp(`([?&]${Jt}=)([^&#\\s]*)`,"gi");function Ft(r){return r.replace(/(\/codex\/)[a-f0-9]+(?=\/v1\b)/gi,"$1[REDACTED]").replace(/(\/model-usage\/)[a-f0-9]+/gi,"$1[REDACTED]").replace(/\b(authorization|proxy-authorization)\s*:\s*[^\r\n]+/gi,"$1: [REDACTED]").replace(/\b(set-cookie|cookie)\s*:\s*[^\r\n]+/gi,"$1: [REDACTED]").replace(/\b(bearer|basic)\s+[^\s"',}]+/gi,"$1 [REDACTED]").replace(/(https?:\/\/[^\s/:@]+:)[^\s/@]+(@)/gi,"$1[REDACTED]$2").replace(Xr,"$1[REDACTED]").replace(Kr,"$1[REDACTED]").replace(Wr,(e,t,n,o,i,s)=>{let a=n!==void 0?['"','"']:o!==void 0?["'","'"]:i!==void 0?["“","”"]:s!==void 0?["‘","’"]:["",""];return`${t}${a[0]}${Vr}${a[1]}`})}import{randomUUID as Yr}from"node:crypto";var _e=class{id=Yr();sequence=0;records=[];listeners=new Set;closed=!1;publish(e){this.records.push({...structuredClone(e),cursor:`${this.id}:${++this.sequence}`,occurredAt:new Date().toISOString()}),this.records.length>256&&this.records.shift(),this.wake()}close(){this.closed=!0,this.wake()}wake(){for(let e of this.listeners)e()}async*stream(e={}){let t=this.sequence-this.records.length;if(e.after!==void 0){let[n,o,i]=e.after.split(":");if(t=Number(o),n!==this.id||i!==void 0||!/^\d+$/.test(o??"")||!Number.isSafeInteger(t)||t>this.sequence)throw A("AUTH_EVENT_CURSOR_INVALID","授权事件游标不属于当前凭证提供者。")}for(;;){e.signal?.throwIfAborted();let n=this.sequence-this.records.length;if(t<n)throw A("AUTH_EVENT_CURSOR_EXPIRED","授权事件游标已超出内存保留范围,请重新读取授权状态。");let o=this.records[t-n];if(o){t++,yield structuredClone(o);continue}if(this.closed)return;await new Promise((i,s)=>{let a=()=>{this.listeners.delete(c),e.signal?.removeEventListener("abort",l)},c=()=>{a(),i()},l=()=>{a(),s(e.signal.reason)};this.listeners.add(c),e.signal?.addEventListener("abort",l,{once:!0})})}}};var De=class{constructor(e,t,n){this.authentication=e;this.platformBaseUrl=t;this.provider=n}events=new _e;entries=new Map;sequence=0;epoch=0;revoked=!1;closed=!1;expiration;execution(e){if(e===void 0)return;let t=Re(e),{context:n}=t,o=this.authentication.principal;if(n&&(n.actor.userId!==o.userId||n.actor.tenantId!==o.tenantId||n.workspaceId!==o.workspaceId))throw A("EXECUTION_PRINCIPAL_MISMATCH","凭证请求的操作者、租户和空间与实例主体不一致。");return n&&(Object.freeze(n.actor),Object.freeze(n.owner),Object.freeze(n)),Object.freeze(t)}clear(){this.epoch++;for(let e of this.entries.values())e.controller.abort(A("MANAGED_AUTHORIZATION_CHANGED","解析凭证期间授权已改变。"));this.entries.clear(),clearTimeout(this.expiration)}revoke(e,t){let n=this.execution(e);return t!==void 0&&this.entries.get(JSON.stringify(n)??"")?.generation!==t?!1:(this.clear(),this.revoked=!0,this.events.publish({type:"invalidated",scope:"provider",reason:"revoked",execution:n,code:"MANAGED_AUTHORIZATION_REVOKED"}),!0)}async resolve(e,t,n){if(this.closed)throw A("MANAGED_PROVIDER_UNAVAILABLE","凭证提供者已关闭。");if(this.revoked&&e!=="explicit")throw A("MANAGED_AUTHORIZATION_REVOKED","应用托管授权已撤销。");let o=this.execution(t),i=JSON.stringify(o)??"";if(e==="explicit"&&o)throw new Error("显式刷新作用于整个实例,不能指定单轮上下文。");let s=this.entries.get(i);if(e==="explicit"&&(!s?.pending||s.reason!=="explicit")&&(this.clear(),s=void 0),s||(s={execution:o,generation:0,controller:new AbortController}),this.entries.delete(i),this.entries.set(i,s),s.pending)await s.pending;else{let a=e==="explicit"||e==="rejected"&&n===s.generation;if(a||!s.cached||s.cached.expiresAt<=Date.now()+3e4){let c=a?e:s.cached||s.expired?"expiring":"initial";s.cached=void 0;let l=this.epoch;s.reason=c;let d=this.load(s,c,l);s.pending=d;try{await d}finally{s.pending===d&&(s.pending=void 0),this.trim()}}}if(!s.cached||s.controller.signal.aborted)throw A("MANAGED_AUTHORIZATION_CHANGED","解析凭证期间授权已改变。");return{...s.cached.credential,generation:s.generation}}trim(){for(let[e,t]of this.entries){if(this.entries.size<=128)return;t.pending||this.entries.delete(e)}}async load(e,t,n){try{let o=await this.provider({reason:t,signal:e.controller.signal,execution:e.execution});if(e.controller.signal.throwIfAborted(),n!==this.epoch)throw A("MANAGED_AUTHORIZATION_CHANGED","解析凭证期间授权已改变。");if(o===null)throw this.revoke(),A("MANAGED_AUTHORIZATION_REVOKED","应用未提供有效授权。");e.cached=kt(o,this.authentication.principal,this.platformBaseUrl),e.expired=!1,e.generation=++this.sequence,this.revoked=!1,this.events.publish({type:"authorized",scope:"credential",reason:t,execution:e.execution,expiresAt:new Date(e.cached.expiresAt).toISOString()})}catch(o){if(n===this.epoch){let i=o&&typeof o=="object"&&"code"in o?String(o.code):"";this.events.publish({type:"invalidated",scope:"credential",reason:"provider_error",execution:e.execution,code:["MANAGED_IDENTITY_MISMATCH","MANAGED_CREDENTIAL_EXPIRED"].includes(i)?i:"MANAGED_CREDENTIAL_ERROR"})}throw o}finally{this.scheduleExpiration()}}scheduleExpiration(){clearTimeout(this.expiration);let e=1/0;for(let t of this.entries.values())t.cached&&(e=Math.min(e,t.cached.expiresAt));e===1/0||this.closed||(this.expiration=setTimeout(()=>{for(let t of this.entries.values())t.cached&&t.cached.expiresAt<=Date.now()&&(t.cached=void 0,t.expired=!0,this.events.publish({type:"invalidated",scope:"credential",reason:"expired",execution:t.execution,code:"MANAGED_CREDENTIAL_EXPIRED"}));this.scheduleExpiration()},Math.min(2147483647,Math.max(1,e-Date.now()))),this.expiration.unref())}close(){this.closed=!0,this.clear(),this.revoked=!0,this.events.publish({type:"invalidated",scope:"provider",reason:"closed",code:"MANAGED_PROVIDER_UNAVAILABLE"}),this.events.close()}};async function Vt(r,e,t){let n=Zr(32).toString("hex"),o=new De(r,e,t),i=Qr.createServer(async(s,a)=>{let c=Buffer.from(`Bearer ${n}`),l=Buffer.from(s.headers.authorization??"");if(c.length!==l.length||!en(c,l)){a.writeHead(401).end();return}if(s.method!=="POST"||s.url!=="/credentials"){a.writeHead(404).end();return}try{let d=0,p=[];for await(let g of s){let y=Buffer.from(g);if(d+=y.length,d>64*1024)throw new Error("凭证请求过大。");p.push(y)}let u=JSON.parse(Buffer.concat(p).toString("utf8"));if(u.generation!==void 0&&(!Number.isSafeInteger(u.generation)||u.generation<1))throw new Error("凭证版本无效。");let h;if(u.revoke===!0)h={revoked:o.revoke(u.execution,u.generation)};else{if(!["initial","expiring","rejected","explicit"].includes(String(u.reason)))throw new Error("凭证解析原因无效。");if(u.reason==="rejected"&&u.generation===void 0)throw new Error("被拒凭证版本无效。");h=await o.resolve(u.reason,u.execution,u.generation)}a.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),a.end(JSON.stringify(h))}catch(d){a.writeHead(400,{"content-type":"application/json","cache-control":"no-store"}),a.end(JSON.stringify({error:{code:d&&typeof d=="object"&&"code"in d?String(d.code):"MANAGED_CREDENTIAL_ERROR",message:Ft(d instanceof Error?d.message:String(d))}}))}});return await new Promise((s,a)=>{i.once("error",a),i.listen(0,"127.0.0.1",s)}),{connection:{url:`http://127.0.0.1:${i.address().port}/credentials`,token:n},events:o.events,close:async()=>{o.close(),i.closeAllConnections(),await new Promise((s,a)=>i.close(c=>c?a(c):s()))}}}import{randomUUID as tn}from"node:crypto";import{setTimeout as Gt}from"node:timers/promises";var de=class{constructor(e,t){this.connection=e;this.authorizationEvents=t}managedEvents(e={}){let t=this.authorizationEvents?.();if(!t)throw new f("MANAGED_PROVIDER_UNAVAILABLE","此客户端未注册托管凭证提供者。");return t.stream(e)}login(e){return this.connection().call("auth.login",e)}getToken(){return this.connection().call("auth.token")}refresh(){return this.connection().call("auth.refresh")}refreshManaged(){return this.connection().call("auth.managed.refresh")}revokeManaged(){return this.connection().call("auth.managed.revoke")}status(){return this.connection().call("auth.status")}context(){return this.connection().call("auth.context")}logout(){return this.connection().call("auth.logout")}completePasswordChange(e){return this.connection().call("auth.password",e)}switchSubject(e){return this.connection().call("auth.switchSubject",e)}async startBrowserLogin(e={}){let t=this.connection(),n=await t.call("auth.browser.start",{...e,requestId:e.requestId??tn()});return new le(t,n.id)}resumeBrowserLogin(e){return new le(this.connection(),e)}},le=class{constructor(e,t){this.transport=e;this.id=t}status(){return this.transport.call("auth.browser.status",{id:this.id})}cancel(){return this.transport.call("auth.browser.cancel",{id:this.id})}async getAuthorizationUrl(e={}){for(;;){e.signal?.throwIfAborted();let t=await this.status();if(this.checkFailure(t),t.state==="waiting"&&t.authorizationUrl)return t.authorizationUrl;if(t.state==="completed")throw new f("LOGIN_ALREADY_COMPLETED","网页登录已完成,请读取登录结果。");await Gt(150,void 0,e)}}async wait(e={}){for(;;){e.signal?.throwIfAborted();let t=await this.status();if(this.checkFailure(t),t.state==="completed"&&t.session)return t.session;await Gt(250,void 0,e)}}checkFailure(e){if(e.state==="failed")throw new f(e.error.code,e.error.message);if(e.state==="cancelled")throw new f("LOGIN_CANCELLED","网页登录已取消。")}};var ue=class{constructor(e){this.connection=e}call(e,t={}){return this.connection().call(`platform.${e}`,t)}getSession(){return this.call("session")}getUser(){return this.call("user")}getTenants(){return this.call("tenants")}getContext(){return this.call("context")}models={list:()=>this.call("models.list"),listSpeechRecognition:()=>this.call("models.speech")};experts={prepare:(e,t)=>this.call("experts.prepare",{...e,...t?{resolved:t}:{}})};account={getSummary:(e={})=>this.call("account.summary",e),listPlanPurchases:()=>this.call("account.purchases"),getUsage:e=>this.call("account.usage",e)};skills={getHome:()=>this.call("skills.home"),install:e=>this.call("skills.install",e),remove:(e,t)=>this.call("skills.remove",{skillId:e,tenantId:t}),getVersions:e=>this.call("skills.versions",e),updateVersion:e=>this.call("skills.updateVersion",e),search:(e={})=>this.call("skills.search",e),getDetail:(e,t)=>this.call("skills.detail",{skillId:e,tenantId:t}),listCategories:()=>this.call("skills.categories"),prepareForLocalTask:e=>this.call("skills.prepare",e)};plugins={list:(e={})=>this.call("plugins.list",e),getDetail:e=>this.call("plugins.detail",{recordId:e}),listCategories:()=>this.call("plugins.categories"),prepare:(e,t,n)=>this.call("plugins.prepare",{pluginId:e,recordId:t,resourceVersion:n}),getAuthorization:e=>this.call("plugins.authorization.get",{pluginId:e}),saveAuthorization:(e,t)=>this.call("plugins.authorization.save",{pluginId:e,request:t}),revokeAuthorization:e=>this.call("plugins.authorization.revoke",{pluginId:e}),verifyAuthorization:e=>this.call("plugins.authorization.verify",{pluginId:e})};knowledge={tree:()=>this.call("knowledge.tree"),search:(e={})=>this.call("knowledge.search",e),listDocuments:e=>this.call("knowledge.documents",e),readDocument:e=>this.call("knowledge.read",e),getDocumentDownloadLink:e=>this.call("knowledge.downloadLink",{documentId:e})}};import U from"node:fs";import P from"node:path";import{createHash as rn}from"node:crypto";import{createRequire as nn}from"node:module";import{t as on,x as sn}from"tar";var an=nn(import.meta.url),cn=["win32-x64","darwin-x64","darwin-arm64","linux-x64","linux-arm64"];function dn(r=`${process.platform}-${process.arch}`){if(!cn.includes(r))throw new f("RUNTIME_UNSUPPORTED",`尚未提供 ${r} 的精简运行时。`);let e=`@kmlckj/aios-runtime-${r}`;try{return P.dirname(an.resolve(`${e}/package.json`))}catch(t){throw t.code!=="MODULE_NOT_FOUND"?t:new f("RUNTIME_PACKAGE_MISSING",`缺少 ${e}。请安装对应版本的运行时包,不要使用 --omit=optional;也可显式指定 runtime.directory。`)}}async function ln(r){let e=rn("sha256");for await(let t of U.createReadStream(r))e.update(t);return e.digest("hex")}async function un(r,e){let t=new Set,n,o=i=>{if(!i||i.includes("\\")||i.includes("\0")||P.posix.isAbsolute(i)||/^[A-Za-z]:/.test(i)||i.split("/").includes(".."))throw new Error(`运行时归档路径无效:${i}`)};if(await on({file:r,strict:!0,onReadEntry(i){try{o(i.path);let s=P.posix.normalize(i.path).replace(/\/$/,"");if(t.has(s))throw new Error(`运行时归档包含重复路径:${s}`);if(t.add(s),!["File","OldFile","Directory","SymbolicLink","Link"].includes(i.type))throw new Error(`运行时归档条目类型无效:${i.type}`);if(i.linkpath){if(P.posix.isAbsolute(i.linkpath)||i.linkpath.includes("\\")||/^[A-Za-z]:/.test(i.linkpath))throw new Error(`运行时归档链接越界:${s}`);o(i.type==="SymbolicLink"?P.posix.join(P.posix.dirname(s),i.linkpath):i.linkpath)}}catch(s){n??=s}}}),n)throw n;await sn({file:r,cwd:e,strict:!0,preservePaths:!1})}async function pe(r,e){if(r.runtime?.directory!==void 0)return se(r);let t=e??dn(),n=JSON.parse(U.readFileSync(P.join(t,"package.json"),"utf8")),o=JSON.parse(U.readFileSync(new URL("../package.json",import.meta.url),"utf8")),i=JSON.parse(U.readFileSync(P.join(t,"runtime-package.json"),"utf8")),s=`${process.platform}-${process.arch}`;if(n.name!==`@kmlckj/aios-runtime-${s}`||n.version!==o.version||i.schemaVersion!==1||i.version!==o.version||i.target!==s||i.archive?.file!=="payload.tar.gz"||!/^[a-f0-9]{64}$/.test(i.archive.sha256)||!Number.isSafeInteger(i.archive.size)||i.archive.size<=0)throw new f("RUNTIME_INCOMPATIBLE","npm 运行时包的版本、平台或归档清单与 SDK 不一致。");if(!r.runtime||typeof r.runtime.dataDirectory!="string"||!r.runtime.dataDirectory.trim())throw new Error("运行时数据目录不能为空。");let a=P.resolve(r.runtime.dataDirectory,"runtimes"),c=P.join(a,`${s}-${i.archive.sha256}`),l=se({...r,runtime:{...r.runtime,directory:c}});if(U.existsSync(c))return await N(c,l.runtime.trustedPublicKey),l;let d=P.join(t,i.archive.file);if(U.statSync(d).size!==i.archive.size||await ln(d)!==i.archive.sha256)throw new f("RUNTIME_INTEGRITY_FAILED","npm 运行时归档内容与清单不一致。");Y(a);let p=U.mkdtempSync(P.join(a,".unpack-"));try{await un(d,p),await N(p,l.runtime.trustedPublicKey);try{U.renameSync(p,c)}catch(u){if(!U.existsSync(c))throw u;await N(c,l.runtime.trustedPublicKey)}return l}finally{U.rmSync(p,{recursive:!0,force:!0})}}import{randomUUID as pn}from"node:crypto";function Wt(r){let e=n=>{let o=r[n];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>864e5)throw Object.assign(new Error(`${n} 必须是 0 至 86400000 毫秒的整数。`),{code:"INVALID_DRAIN_OPTIONS"});return o},t=e("timeoutMs");if(r.onTimeout==="cancel")return{timeoutMs:t,onTimeout:"cancel",cancelTimeoutMs:e("cancelTimeoutMs")};if(r.onTimeout==="return")return{timeoutMs:t,onTimeout:"return"};throw Object.assign(new Error("必须明确选择排空到期后返回或取消。"),{code:"INVALID_DRAIN_OPTIONS"})}var fe=class r{constructor(e,t,n,o,i,s){this.options=e;this.metadata=t;this.verified=n;this.child=o;this.exited=i;this.connector=s;o.on("message",this.onMessage),o.on("error",this.onError),o.once("disconnect",this.onDisconnect),i.then(a=>{this.exit=a,this.exitController.abort(new f("RUNTIME_EXITED","SDK 宿主进程已退出。")),this.onError(new f("RUNTIME_EXITED",`SDK 宿主已退出(${a.code??a.signal})。`)),o.removeListener("message",this.onMessage),o.removeListener("error",this.onError),o.removeListener("disconnect",this.onDisconnect)})}exit;exitController=new AbortController;shutdownRequest;pending=new Map;static async start(e,t,n){let o=Wt({...t.shutdown}),i=await pe(e),s=await N(i.runtime.directory,i.runtime.trustedPublicKey),{child:a,ready:c,exited:l}=Oe({options:i,verifiedPackage:s,managed:{shutdown:o}});try{let d=await c;return new r(i,d,s,a,l,n)}catch(d){throw a.connected&&a.disconnect(),a.unref(),d}}get pid(){return this.metadata.pid}get instanceId(){return this.metadata.instanceId}connect(e={}){return this.exit||!this.child.connected?Promise.reject(new f("RUNTIME_EXITED","受管宿主连接已结束。")):this.connector(this.options,this.metadata,this.verified,e,this.exitController.signal)}shutdown(){if(this.shutdownRequest)return this.shutdownRequest;if(this.exit||!this.child.connected)return Promise.reject(new f("RUNTIME_EXITED","受管宿主连接已结束,请读取 wait 的退出结果。"));let e=pn();return this.shutdownRequest=new Promise((t,n)=>{this.pending.set(e,{resolve:t,reject:n}),this.child.send({type:"shutdown",id:e},o=>{o&&(this.pending.delete(e),n(o))})}).then(async t=>{if(t.status==="drained"){let n=await this.wait();if(n.code!==0)throw new f("RUNTIME_EXIT_FAILED",`SDK 宿主清理后异常退出(${n.code??n.signal})。`)}else this.shutdownRequest=void 0;return t},t=>{throw this.shutdownRequest=void 0,t}),this.shutdownRequest}wait(){return this.exited}onMessage=e=>{if(e.type!=="shutdown")return;let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.ok?t.resolve(e.value):t.reject(new f(e.error.code,e.error.message)))};onError=e=>{for(let t of this.pending.values())t.reject(e);this.pending.clear()};onDisconnect=()=>this.onError(new f("HOST_DISCONNECTED","宿主控制通道已断开,请读取 wait 的退出结果。"))};function qt(r,e){if(e.credentials&&(r.mode!=="platform"||!r.authentication))throw new Error("凭证回调只能用于平台托管模式。");if(e.authorize&&!r.authorization?.required)throw new Error("会话授权回调需要 authorization.required=true。");if(e.memoryStore&&r.memory?.storage!=="external")throw new Error("记忆存储适配器需要 memory.storage=external。")}var he=class r{constructor(e,t,n,o={}){this.transport=e;this.options=t;this.mode=n;this.services=o;this.transport=Ze(e,o.diagnostics)}toolProviders=new Set;activeToolProviders=new Map;credentialProvider;callbacks;callbackHandlers=new Map;lifecycleQueue=Promise.resolve();closed=!1;scheduleLifecycle(e){let t=this.lifecycleQueue.then(e);return this.lifecycleQueue=t.then(()=>{},()=>{}),t}assertOpen(){if(this.closed)throw new f("RUNTIME_CLOSED","SDK 客户端连接已关闭。")}async startCallbacks(){let e=this.callbackHandlers;if(this.services.authorize&&e.set("session.authorize",(i,s)=>this.services.authorize(Object.freeze(i),{signal:s})),this.services.memoryStore){let i=this.services.memoryStore;e.set("memory.read",(s,a)=>i.read(s,a)),e.set("memory.compareAndSwap",(s,a)=>i.compareAndSwap(s,a))}if(!e.size)return;let t=this.callbacks,n=t??await $t(e),o={...n.connection,methods:[...e.keys()]};try{await this.transport.call("application.callbacks",{connection:o}),this.callbacks=n}catch(i){throw t||await n.close(),i}}static async start(e,t,n){qt(e,t);let o=e.mode==="platform"&&e.authentication&&t.credentials?await Vt(e.authentication,e.platformBaseUrl,t.credentials):void 0;try{return{transport:n?await ae.attach(e,n.metadata,n.verified,o?.connection,n.exitSignal):await ae.start(e,o?.connection),provider:o}}catch(i){throw await o?.close(),i}}static async create(e,t={}){let n=await pe(e),{transport:o,provider:i}=await r.start(n,t),s=new r(o,n,n.mode,t);s.credentialProvider=i;try{await s.startCallbacks()}catch(a){throw await s.close(),a}return s}static startManaged(e,t){return fe.start(e,t,async(n,o,i,s,a)=>{let{transport:c,provider:l}=await r.start(n,s,{metadata:o,verified:i,exitSignal:a}),d=new r(c,n,n.mode,s);d.credentialProvider=l;try{await d.startCallbacks()}catch(p){throw await d.close(),p}return d})}static async connectCli(e){return new r(await Ce.connect(e),e,"platform")}auth=new de(()=>this.transport,()=>this.credentialProvider?.events);platform=new ue(()=>this.transport);runtime={health:e=>this.transport.call("runtime.health",{},void 0,e),activity:()=>this.transport.call("runtime.activity"),drain:(e,t)=>this.transport.call("runtime.drain",e,void 0,t)};resources={limits:{get:()=>this.transport.call("resources.limits.get"),set:(e,t,n)=>this.transport.call("resources.limits.set",{key:e,value:t,revision:n})},cache:{status:()=>this.transport.call("resources.cache.status"),prune:(e={})=>this.transport.call("resources.cache.prune",e)}};skills={list:()=>this.transport.call("skills.list"),importVersion:e=>this.transport.call("skills.importVersion",e),importPaths:e=>this.transport.call("skills.import",{paths:e}),remove:e=>this.transport.call("skills.remove",{reference:e})};plugins={list:()=>this.transport.call("plugins.list"),install:(e,t)=>this.transport.call("plugins.install",{recordId:e,source:t}),update:(e,t,n)=>this.transport.call("plugins.update",{pluginId:e,recordId:t,expectedRevision:n}),setEnabled:(e,t,n)=>this.transport.call("plugins.setEnabled",{pluginId:e,enabled:t,expectedRevision:n}),remove:(e,t)=>this.transport.call("plugins.remove",{pluginId:e,expectedRevision:t})};settings={get:()=>this.transport.call("settings.get"),set:(e,t,n)=>this.transport.call("settings.set",{domain:e,value:t,revision:n})};native={settings:()=>this.transport.call("native.settings"),configure:(e,t)=>this.transport.call("native.configure",{value:e,revision:t}),status:e=>this.transport.call("native.status",{kind:e}),registerBrowser:()=>this.transport.call("native.register"),unregisterBrowser:()=>this.transport.call("native.unregister")};memory={get:e=>this.transport.call("memory.get",e),setEnabled:e=>this.transport.call("memory.setEnabled",e),edit:e=>this.transport.call("memory.edit",e),reset:e=>this.transport.call("memory.reset",e)};async setPlatformBaseUrl(e){if(!("mode"in this.options)||this.options.mode!=="platform")throw new Error("独立模式不使用平台基地址。");await this.configure({platformBaseUrl:e})}getConfiguration(){return this.transport.call("configuration.get")}configure(e){return this.scheduleLifecycle(()=>this.applyConfiguration(e))}async applyConfiguration(e){if(this.assertOpen(),!("mode"in this.options))throw new Error("连接已有 CLI 时请通过 CLI 修改全局配置。");if(this.options.mode==="standalone"&&e.platformBaseUrl!==void 0)throw new Error("独立模式不使用平台基地址。");if(this.options.mode==="platform"&&e.models!==void 0)throw new Error("平台模型由平台管理;外部模型请使用独立模式。");let t=await pe({...this.options,...e});qt(t,this.services),await N(t.runtime.directory,t.runtime.trustedPublicKey),await this.transport.call("configuration.validate",{options:t}),await this.transport.shutdown(),await this.disconnect();let{transport:n,provider:o}=await r.start(t,this.services);this.transport=Ze(n,this.services.diagnostics),this.credentialProvider=o,this.options=t,this.closed=!1;try{await this.startCallbacks()}catch(i){throw await this.disconnect(),i}return this.getConfiguration()}capabilities(e={}){return this.transport.call("capabilities",e)}dependencies(){return this.transport.call("dependencies")}defineAgent(e){return this.scheduleLifecycle(()=>this.registerAgent(e))}async registerAgent(e){this.assertOpen();let{tools:t,toolProviderId:n,jsHooks:o,...i}=e,s=Ne(e),a=[],c=new Map;for(let[u,h]of Object.entries(o??{})){if(!["beforeTool","afterTool"].includes(u)||!h||typeof h.execute!="function")throw new Error("JS Hook 必须提供执行函数。");let g=u==="beforeTool"?"PreToolUse":"PostToolUse",y=`hook.${s}.${g}`;a.push({event:g,callback:y,timeoutMs:h.timeoutMs??3e4,...h.matcher?{matcher:h.matcher}:{}}),c.set(y,this.callbackHandlers.get(y))}o&&(i.jsHookDefinitions=zt(a));let l=JSON.stringify([e.id,e.version]),d=this.activeToolProviders.get(s);if(d&&d.agent!==l)throw new Error("应用工具提供者 ID 已被其他智能体使用。");let p=t?.length?await Lt(s,t,(u,h,g,y)=>this.transport.call("session.file.resolve",{id:u,path:h,access:g},void 0,y)):void 0;p&&this.toolProviders.add(p);try{for(let[g,y]of Object.entries(o??{})){let I=g==="beforeTool"?"PreToolUse":"PostToolUse";this.callbackHandlers.set(`hook.${s}.${I}`,async(S,m)=>{let w=await y.execute(Object.freeze(S),{signal:m});return Ht(I,w),w})}o&&await this.startCallbacks();let u=[...i.mcpServers??[],...p?[p.descriptor]:[]];await this.transport.call("agent.define",{...i,mcpServers:u,...p?{applicationToolProviderId:s}:{}}),d?.provider?.retire();let h={agent:l,provider:p};return this.activeToolProviders.set(s,h),p&&p.closed.then(()=>{this.toolProviders.delete(p)}),new Me(this.transport,e.id,e.version,p,t?.map(g=>({name:g.name,reference:Qe(e,g.name)})),()=>{if(this.activeToolProviders.get(s)!==h)throw new Error("此工具提供者已被新注册替换,请使用当前 Agent 句柄。")})}catch(u){for(let[h,g]of c)g?this.callbackHandlers.set(h,g):this.callbackHandlers.delete(h);throw p&&(this.toolProviders.delete(p),await p.close()),u}}async openSession(e){return new ge(this.transport,await this.transport.call("session.get",{id:e}))}async openAgent(e,t){return this.assertOpen(),await this.transport.call("agent.providers",{agentId:e,agentVersion:t}),new Me(this.transport,e,t)}listSessions(e={}){return this.transport.call("session.list",e)}shutdown(){return this.scheduleLifecycle(async()=>{this.assertOpen(),await this.transport.shutdown(),await this.disconnect()})}close(){return this.scheduleLifecycle(()=>this.disconnect())}async disconnect(){if(!this.closed){this.closed=!0;try{await this.transport.stop()}finally{await Promise.all([...this.toolProviders].map(e=>e.close()).concat(this.credentialProvider?[this.credentialProvider.close()]:[])),this.callbacks&&(await this.callbacks.close(),this.callbacks=void 0),this.callbackHandlers.clear(),this.toolProviders.clear(),this.activeToolProviders.clear(),this.credentialProvider=void 0}}}},Me=class{constructor(e,t,n,o,i=[],s=()=>{}){this.transport=e;this.id=t;this.version=n;this.provider=o;this.tools=i;this.assertCurrentProvider=s}async createSession(e={}){return new ge(this.transport,await this.transport.call("session.create",{agentId:this.id,agentVersion:this.version,...e,creationId:e.creationId??T()}))}async adoptSession(e,t={}){return new ge(this.transport,await this.transport.call("session.bind",{id:e,agentId:this.id,agentVersion:this.version,policy:t.policy}))}providerStatus(){return this.transport.call("agent.providers",{agentId:this.id,agentVersion:this.version})}unregisterProvider(){return this.assertCurrentProvider(),this.transport.call("agent.unregisterProvider",{agentId:this.id,agentVersion:this.version})}async releaseProvider(){return await this.unregisterProvider(),this.provider?.retire(),this.provider?.status()}waitProviderClosed(){return this.provider?.closed??Promise.resolve()}},ge=class r{constructor(e,t){this.transport=e;this.info=t;this.id=t.id,this.files=new je(e,this.id)}id;files;runtimeTuning(){return this.transport.call("session.runtimeTuning",{id:this.id})}memory={get:(e={})=>this.transport.call("memory.get",{...e,sessionId:this.id}),edit:e=>this.transport.call("memory.edit",{...e,sessionId:this.id}),reset:()=>this.transport.call("memory.reset",{sessionId:this.id}),setEnabled:e=>this.transport.call("memory.setEnabled",{enabled:e,sessionId:this.id})};async send(e,t={}){let n=t.commandId??T(),o=await this.transport.call("session.send",{id:this.id,content:e,options:{...t,commandId:n}});return new me(this.transport,this.id,o.runId,n)}enqueue(e,t={}){return this.transport.call("session.enqueue",{id:this.id,content:e,options:{...t,commandId:t.commandId??T()}})}queue(){return this.transport.call("session.queue",{id:this.id})}editQueued(e,t,n,o=T()){return this.transport.call("session.queue.edit",{id:this.id,pendingMessageId:e,content:t,queueVersion:n,commandId:o})}removeQueued(e,t,n=T()){return this.transport.call("session.queue.delete",{id:this.id,pendingMessageId:e,queueVersion:t.queueVersion,targetRunId:t.activeRunId,commandId:n})}reorderQueue(e,t,n=T()){return this.transport.call("session.queue.reorder",{id:this.id,pendingMessageIds:e,queueVersion:t,commandId:n})}dispatchQueued(e,t,n,o=T()){return this.transport.call("session.queue.send",{id:this.id,pendingMessageId:e,queueVersion:t,targetRunId:n,commandId:o})}history(){return this.transport.call("session.history",{id:this.id})}rename(e,t){return this.transport.call("session.rename",{id:this.id,name:e,expectedRevision:t})}setArchived(e,t){return this.transport.call("session.archive",{id:this.id,archived:e,expectedRevision:t})}runs(e={},t){return this.transport.call("session.runs",{id:this.id,...e},void 0,t)}async*events(e={}){let t=e.cursor;for(;;){e.signal?.throwIfAborted();let n=await this.transport.call("session.events",{id:this.id,cursor:t,waitMs:this.transport.eventWaitMs??0},void 0,e.signal);for(let o of n.events)e.signal?.throwIfAborted(),yield o;t=n.cursor,this.transport.eventWaitMs||await et(150,void 0,{signal:e.signal})}}eventPage(e={}){return this.transport.call("session.events",{id:this.id,cursor:e.cursor,waitMs:0},void 0,e.signal)}queryHistory(e={}){return this.transport.call("session.history.query",{id:this.id,...e})}clear(e){return this.transport.call("session.clear",{id:this.id,...e})}delete(e){return this.transport.call("session.delete",{id:this.id,...e})}artifacts(e={},t={}){return this.transport.call("session.artifacts",{id:this.id,query:e},void 0,t.signal)}operations(e={}){return this.transport.call("session.operations",{id:this.id,...e})}teamState(){return this.transport.call("session.team.state",{id:this.id})}async createBackgroundSession(e,t=T()){let n=await this.transport.call("session.team.background",{id:this.id,memberId:e,creationId:t});return new r(this.transport,n)}operation(e,t={}){return this.transport.call("session.operation",{id:this.id,operationId:e},void 0,t.signal)}cancelOperation(e,t={}){return this.transport.call("session.operation.cancel",{id:this.id,operationId:e},void 0,t.signal)}configuration(e){return this.transport.call("session.configuration",{id:this.id,revision:e})}configure(e,t){return this.transport.call("session.defaults",{id:this.id,defaults:e,expectedRevision:t})}configureBuiltins(e,t){return this.transport.call("session.builtins",{id:this.id,builtins:e,expectedRevision:t})}updateAgent(e){return this.transport.call("session.agent",{id:this.id,...e})}receipt(e){return this.transport.call("session.receipt",{id:this.id,commandId:e})}resumeRun(e){return new me(this.transport,this.id,e)}async compact(e=T()){let t=await this.transport.call("session.compact",{id:this.id,commandId:e});return new me(this.transport,this.id,t.runId,e)}},me=class r{constructor(e,t,n,o){this.transport=e;this.taskId=t;this.id=n;this.commandId=o}state(e={}){return this.transport.call("run.state",{taskId:this.taskId,runId:this.id},void 0,e.signal)}context(){return this.transport.call("run.context",{taskId:this.taskId,runId:this.id})}memoryPolicy(){return this.transport.call("run.memoryPolicy",{taskId:this.taskId,runId:this.id})}team(e,t={}){return this.transport.call("session.team.command",{id:this.taskId,runId:this.id,command:e},void 0,t.signal)}artifacts(e={},t={}){return this.transport.call("session.artifacts",{id:this.taskId,query:{...e,runId:this.id}},void 0,t.signal)}operations(){return this.transport.call("session.operations",{id:this.taskId,runId:this.id})}operation(e,t={}){return this.transport.call("session.operation",{id:this.taskId,runId:this.id,operationId:e},void 0,t.signal)}cancelOperation(e,t={}){return this.transport.call("session.operation.cancel",{id:this.taskId,runId:this.id,operationId:e},void 0,t.signal)}cancel(e=T()){return this.transport.call("run.cancel",{taskId:this.taskId,runId:this.id,commandId:e})}detach(){return this.transport.call("run.detach",{taskId:this.taskId,runId:this.id})}approve(e,t,n=T()){return this.transport.call("run.approve",{taskId:this.taskId,runId:this.id,toolCallId:e,decision:t,commandId:n})}answer(e,t,n=T()){return this.transport.call("run.answer",{taskId:this.taskId,runId:this.id,requestId:e,response:t,commandId:n})}cancelInput(e,t=T()){return this.transport.call("run.cancelInput",{taskId:this.taskId,runId:this.id,requestId:e,commandId:t})}async confirmPlan(e=T()){let t=await this.transport.call("run.confirmPlan",{taskId:this.taskId,runId:this.id,commandId:e});return new r(this.transport,this.taskId,t.runId,e)}async*events(e={}){let t=e.cursor;for(;;){e.signal?.throwIfAborted();let n=await this.transport.call("run.events",{taskId:this.taskId,runId:this.id,cursor:t,waitMs:this.transport.eventWaitMs??0},void 0,e.signal);for(let o of n.events)e.signal?.throwIfAborted(),yield o;if(t=n.cursor,n.terminal)return;this.transport.eventWaitMs||await et(150,void 0,{signal:e.signal})}}async wait(e={}){for(;;){e.signal?.throwIfAborted();let t=this.transport.eventWaitMs?await this.transport.call("run.wait",{taskId:this.taskId,runId:this.id,waitMs:this.transport.eventWaitMs},void 0,e.signal):await this.state(e);if(t.status!=="running"&&t.status!=="queued")return t;this.transport.eventWaitMs||await et(150,void 0,{signal:e.signal})}}},vs=he.create,ks=he.connectCli,Es=he.startManaged;export{Me as Agent,he as AiosClient,f as AiosSdkError,de as AuthApi,le as BrowserLogin,fe as ManagedHost,ue as PlatformApi,me as Run,ge as Session,Ne as applicationToolProviderId,Qe as applicationToolReference,ks as connectCli,vs as createClient,Es as startManagedHost,Cr as toolResult,N as validateRuntime};
4
+ -----END PUBLIC KEY-----`;var Ae={version:"0.0.8",protocol:1,dataFormat:1,profile:"light"};import Te from"node:fs";import H from"node:path";import{createHash as Ir}from"node:crypto";var z=r=>new f("RUNTIME_INTEGRITY_FAILED",r);function Tt(r,e){if(!e||e.includes("\\")||H.posix.normalize(e)!==e||H.posix.isAbsolute(e)||e===".."||e.startsWith("../"))throw z(`共享运行资源路径无效:${e}`);let t=H.resolve(r,e),n=H.relative(r,Te.realpathSync(t));if(n===".."||n.startsWith(`..${H.sep}`)||H.isAbsolute(n))throw z(`共享运行资源越界:${e}`);return t}async function Ot(r,e){if(!e||typeof e!="object"||Array.isArray(e))throw z("缺少共享运行资源清单。");let t=e;if(t.root!=="../.."||typeof t.codex!="string"||!t.files||typeof t.files!="object"||Array.isArray(t.files))throw z("共享运行资源清单无效。");let n=Te.realpathSync(H.resolve(r,t.root));if(H.relative(n,r).split(H.sep).join("/")!=="runtime/sdk-host")throw z("共享宿主不在产品运行资源目录中。");let o=t.files;for(let i of[t.codex,"runtime/desktop-agent-runtime/index.js","runtime/desktop-agent-runtime/package.json"])if(!Object.hasOwn(o,i))throw z(`共享运行资源缺少必需文件:${i}`);for(let[i,s]of Object.entries(o)){if(!s||typeof s!="object"||Array.isArray(s))throw z(`共享运行资源属性无效:${i}`);let a=s,c=Tt(n,i),l=Te.lstatSync(c);if(a.type!=="file"||!l.isFile()||l.isSymbolicLink()||l.size!==a.size||typeof a.sha256!="string"||!/^[a-f0-9]{64}$/.test(a.sha256))throw z(`共享运行资源属性不匹配:${i}`);let d=Ir("sha256");for await(let p of Te.createReadStream(c))d.update(p);if(d.digest("hex")!==a.sha256)throw z(`共享运行资源摘要不匹配:${i}`)}return{root:n,codexExecutable:Tt(n,t.codex)}}var J=r=>new f("RUNTIME_INTEGRITY_FAILED",r);function Ct(r,e){let t=M.relative(r,e);return t!==".."&&!t.startsWith(`..${M.sep}`)&&!M.isAbsolute(t)}async function N(r,e=At,t={platform:process.platform,arch:process.arch}){let n=F.realpathSync(r),o=M.join(n,"aios-sdk-runtime.json"),i=F.readFileSync(o),s=JSON.parse(i.toString("utf8"));if(s.schemaVersion!==1||s.version!==Ae.version||s.protocol!==Ae.protocol||s.dataFormat!==Ae.dataFormat||s.platform!==t.platform||s.arch!==t.arch||!["light","product"].includes(String(s.profile)))throw new f("RUNTIME_INCOMPATIBLE","精简运行时版本、协议、数据格式、系统或架构不兼容。");let a=JSON.parse(F.readFileSync(M.join(n,"signature.json"),"utf8"));if(a.algorithm!=="ed25519"||typeof a.signature!="string"||a.publicKey?.trim()!==e.trim()||!br(null,i,e,Buffer.from(a.signature,"base64")))throw J("运行时清单签名与可信发布公钥不匹配。");if(!s.files||typeof s.files!="object"||Array.isArray(s.files))throw J("运行时缺少文件清单。");let c=s.files,l=["host.mjs","js-hook-runner.js","memory-worker.js","memory-schema-v1.sql","task-event-reader-worker.js","task-storage-recovery-worker.js","keyring.node",...s.profile==="light"?["resources/runtime/desktop-agent-runtime/index.js",`resources/runtime/codex/${t.platform}-${t.arch}/bin/${t.platform==="win32"?"codex.exe":"codex"}`]:[]];for(let S of l)if(!Object.hasOwn(c,S))throw J(`运行时缺少必需资源:${S}`);let d=new Map,p=S=>{for(let m of F.readdirSync(S)){let w=M.join(S,m),k=M.relative(n,w).split(M.sep).join("/");if(["aios-sdk-runtime.json","signature.json"].includes(k))continue;let B=F.lstatSync(w);B.isDirectory()&&!B.isSymbolicLink()?p(w):d.set(k,B)}};if(p(n),d.size!==Object.keys(c).length)throw J("运行时文件数量与清单不一致。");let u=[];for(let[S,m]of Object.entries(c)){let w=M.resolve(n,S),k=d.get(S);if(!S||S.includes("\\")||M.posix.normalize(S)!==S||!Ct(n,w)||!k)throw J(`运行时文件路径或归属不匹配:${S}`);if(m.type==="link"){if(!k.isSymbolicLink()||typeof m.link!="string"||M.isAbsolute(m.link)||F.readlinkSync(w)!==m.link||!Ct(n,F.realpathSync(w)))throw J(`运行时链接不匹配:${S}`)}else if(m.type==="file"){if(!k.isFile()||k.isSymbolicLink()||k.size!==m.size||!/^[a-f0-9]{64}$/.test(m.sha256)||t.platform!=="win32"&&(k.mode&73)!==(m.mode&73))throw J(`运行时文件属性不匹配:${S}`);u.push({file:w,name:S,entry:m})}else throw J(`运行时文件类型无效:${S}`)}let h=0,y=(await Promise.allSettled(Array.from({length:Math.min(8,u.length)},async()=>{for(;h<u.length;){let{file:S,name:m,entry:w}=u[h++],k=Rt("sha256");for await(let B of F.createReadStream(S))k.update(B);if(k.digest("hex")!==w.sha256)throw J(`运行时文件摘要不匹配:${m}`)}}))).find(S=>S.status==="rejected");if(y)throw y.reason;let I=s.profile==="product"?await Ot(n,s.resources):void 0;return{version:s.version,protocol:s.protocol,dataFormat:s.dataFormat,platform:t.platform,arch:t.arch,profile:s.profile,manifestSha256:Rt("sha256").update(i).digest("hex"),...I?{productResources:I}:{}}}import Nt from"node:fs";import Pt from"node:path";import{spawn as xr}from"node:child_process";function Oe(r){let{options:e}=r,t=yt(e),n=wt(e).temporary;Y(n);let o=Nt.openSync(Pt.join(t,"sdk-host.log"),"a",384),i=(()=>{try{return xr(e.runtime.nodeExecutable??process.execPath,[Pt.join(e.runtime.directory,"host.mjs")],{detached:!r.managed,windowsHide:!0,stdio:["ignore",o,o,"ipc"],env:{...process.env,TEMP:n,TMP:n,TMPDIR:n}})}finally{Nt.closeSync(o)}})(),s=new Promise(c=>{i.once("exit",(l,d)=>c({code:l,signal:d})),i.once("error",()=>{i.pid||c({code:null,signal:null})})}),a=new Promise((c,l)=>{let d=setTimeout(()=>h(new f("RUNTIME_START_TIMEOUT","SDK 服务未在指定时间内完成启动,请检查宿主日志。")),e.communication?.startupTimeoutMs??12e4),p=(g,y)=>h(new f("RUNTIME_START_FAILED",`SDK 服务启动进程退出(${g??y})。`)),u=g=>{if(!g||g.type!=="ready"){h(new f("RUNTIME_INCOMPATIBLE","宿主未返回当前 SDK 启动协议,请使用配套运行包。"));return}g.ok?h(void 0,g.value):h(new f(g.error.code,g.error.message))};function h(g,y){clearTimeout(d),i.removeListener("error",h),i.removeListener("exit",p),i.removeListener("message",u),g?l(g):c(y)}i.once("error",h),i.once("exit",p),i.on("message",u),i.send(r,g=>{g&&h(g)})});return{child:i,ready:a,exited:s}}var ae=class r{constructor(e,t,n){this.metadata=e;this.ownerExit=t;this.communication=n}eventWaitMs=0;closed=!1;clientId=jt();static async start(e,t){let n=se(e),o=Ar.resolve(n.runtime.directory),i=await N(o,n.runtime.trustedPublicKey),s=xe(n),a=ve(s);if(!a){let{child:c,ready:l}=Oe({options:n,verifiedPackage:i});try{a=await l}catch(d){if(!(d instanceof f)||d.code!=="DAEMON_ALREADY_OWNED")throw d;a=await st(s,AbortSignal.timeout(n.communication?.startupTimeoutMs??12e4))}finally{c.connected&&c.disconnect(),c.unref()}}return r.attach(n,a,i,t)}static async attach(e,t,n,o,i){if(t.version!==n.version||t.manifestSha256!==n.manifestSha256)throw new f("RUNTIME_INCOMPATIBLE","已运行的服务与指定运行包不一致,请由宿主所有者关闭后使用同一运行包重新启动。");let s=new r(t,i,e.communication),a=await s.call("attach",{options:e,pid:process.pid,manifestSha256:n.manifestSha256});if(s.eventWaitMs=a.eventWaitMs??0,o)try{await s.call("auth.bindProvider",o)}catch(c){throw await s.stop(),c}return s}call(e,t={},n=jt(),o){return this.closed?Promise.reject(new f("RUNTIME_CLOSED","SDK 客户端连接已关闭。")):this.ownerExit?.aborted?Promise.reject(this.ownerExit.reason):ke(this.metadata,this.clientId,e,t,n,o,It(e,this.communication))}async stop(){if(!this.closed){if(this.ownerExit?.aborted){this.closed=!0;return}await this.call("detach"),this.closed=!0}}async shutdown(){await this.call("shutdown"),this.closed=!0;let e=AbortSignal.timeout(this.communication?.shutdownTimeoutMs??12e4);for(;ve(this.metadata.root)?.instanceId===this.metadata.instanceId||X(this.metadata.pid);)await Tr(100,void 0,{signal:e})}};import Or from"node:path";import{randomUUID as _t}from"node:crypto";var Re=class r{constructor(e){this.metadata=e}closed=!1;clientId=_t();static async connect(e){let t=new r(it(Or.resolve(e.dataDirectory)));return await t.call("attach",{sdkProtocol:1,options:e,pid:process.pid}),t}call(e,t={},n=_t(),o){return this.closed?Promise.reject(new f("RUNTIME_CLOSED","SDK 客户端连接已关闭。")):ke(this.metadata,this.clientId,e,t,n,o)}async stop(){this.closed||(await this.call("detach"),this.closed=!0)}async shutdown(){throw new f("SHARED_RUNTIME","连接已有 CLI 时,请通过 CLI 管理后台服务。")}};import Nr from"node:http";import{randomBytes as Pr,randomUUID as jr,timingSafeEqual as _r}from"node:crypto";import{Ajv as Dr}from"ajv";import{Ajv2020 as Mr}from"ajv/dist/2020.js";function Rr(r){let e={...r,kind:"aios-tool-result"};return Xe(e),e}function Z(r,e){if(typeof r!="string"||!r.trim())throw new Error(`工具返回的 ${e} 必须是非空字符串。`)}function Xe(r){if(!r||typeof r!="object"||!("kind"in r)||r.kind!=="aios-tool-result")return{content:[{type:"text",text:typeof r=="string"?r:JSON.stringify(r??null)}],isError:!1};let e=r;if(!Array.isArray(e.content))throw new Error("工具返回的 content 必须是数组。");let t=e.content.map(n=>{if(!n||typeof n!="object")throw new Error("工具返回的内容格式无效。");if(n.type==="text"){if(typeof n.text!="string")throw new Error("工具返回的 text 必须是字符串。");return{type:"text",text:n.text}}if(n.type==="image")return Z(n.data,"image.data"),Z(n.mimeType,"image.mimeType"),{type:"image",data:n.data,mimeType:n.mimeType};if(n.type==="resource"){let o=n.resource;Z(o?.uri,"resource.uri"),new URL(o.uri),o.mimeType!==void 0&&Z(o.mimeType,"resource.mimeType");let i="text"in o,s="blob"in o;if(i===s||i&&typeof o.text!="string"||s&&typeof o.blob!="string")throw new Error("工具文件内容必须且只能包含 text 或 blob。");return{type:"resource",resource:{uri:o.uri,...o.mimeType?{mimeType:o.mimeType}:{},...i?{text:o.text}:{blob:o.blob}}}}throw new Error("不支持的工具内容类型。")});if(e.data!==void 0){if(!e.data||typeof e.data!="object"||Array.isArray(e.data))throw new Error("工具返回的 data 必须是 JSON 对象。");t.push({type:"text",text:JSON.stringify(e.data)})}return e.error!==void 0&&(Z(e.error.code,"error.code"),Z(e.error.message,"error.message"),t.push({type:"text",text:JSON.stringify({error:e.error})})),{content:t,isError:e.error!==void 0}}var Dt=["projectId","collaborationProjectId","assistantId","platformSessionId","platformTurnId","platformTaskId","platformRunId","traceId"];function ce(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("执行上下文必须为对象。");return r}function G(r){if(typeof r!="string"||!r.trim()||r.length>512||/[\x00-\x1f\x7f]/.test(r))throw new Error("执行上下文字段必须为有效字符串,最多 512 字符。");return r}function Mt(r){let e=ce(r);if(Object.keys(e).some(t=>!["userId","tenantId","name"].includes(t)))throw new Error("执行主体包含未知字段。");return{userId:G(e.userId),tenantId:e.tenantId===null?null:G(e.tenantId),...e.name===void 0?{}:{name:G(e.name)}}}function Cr(r){let e=ce(r);if(Object.keys(e).some(n=>!["actor","owner","workspaceId","usageScene","metadata",...Dt].includes(n)))throw new Error("执行上下文包含未知字段。");if(!["personal","greeting","task","collaboration","coding"].includes(String(e.usageScene)))throw new Error("执行用量场景无效。");let t={actor:Mt(e.actor),owner:Mt(e.owner),workspaceId:e.workspaceId===null?null:G(e.workspaceId),usageScene:e.usageScene};for(let n of Dt)e[n]!==void 0&&(t[n]=G(e[n]));if(e.metadata!==void 0){let n=ce(e.metadata);if(Object.keys(n).length>16||JSON.stringify(n).length>8192)throw new Error("业务扩展元数据超过限制。");for(let[o,i]of Object.entries(n)){if(!/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(o))throw new Error("业务元数据命名空间无效。");let s=ce(i);if(Object.keys(s).length>32)throw new Error("业务元数据字段过多。");for(let[a,c]of Object.entries(s))if(!/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(a)||!(c===null||typeof c=="boolean"||typeof c=="number"&&Number.isFinite(c)||typeof c=="string"&&c.length<=1024&&!/[\x00-\x1f\x7f]/.test(c)))throw new Error("业务元数据字段无效。")}t.metadata=structuredClone(n)}return t}function Ce(r){let e=ce(r);if(Object.keys(e).some(t=>!["sessionId","runId","context"].includes(t)))throw new Error("执行绑定包含未知字段。");return{sessionId:G(e.sessionId),runId:G(e.runId),...e.context===void 0?{}:{context:Cr(e.context)}}}async function Lt(r,e,t){let n=new Map,o=new Dr({strict:!0,strictTypes:!1,allErrors:!0,validateFormats:!1}),i=new Mr({strict:!0,strictTypes:!1,allErrors:!0,validateFormats:!1}),s=new Map;for(let m of e){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(m.name)||n.has(m.name))throw new Error(`业务工具名称无效或重复:${m.name}`);if(m.inputSchema.type!=="object")throw new Error(`业务工具 ${m.name} 的输入 schema 必须为 object。`);n.set(m.name,m);let w=m.inputSchema.$schema==="http://json-schema.org/draft-07/schema#"?o:i;s.set(m.name,w.compile(m.inputSchema))}let a=Pr(32).toString("hex"),c=new Map,l=new Set,d=!1,p,u,h=new Promise(m=>{u=m}),g=()=>p??=(async()=>{for(let m of c.values())m.abort(new Error("应用工具提供者已关闭。"));I.closeAllConnections(),await new Promise((m,w)=>I.close(k=>k?w(k):m())),u()})(),y=()=>{d&&l.size===0&&c.size===0&&g()},I=Nr.createServer(async(m,w)=>{let k=Buffer.from(`Bearer ${a}`),B=Buffer.from(m.headers.authorization??"");if(B.length!==k.length||!_r(B,k)){w.writeHead(401).end();return}if(m.url!=="/mcp"){w.writeHead(404).end();return}let E=m.headers["mcp-session-id"];if(m.method==="DELETE"&&typeof E=="string"&&l.delete(E)){for(let[j,q]of c)j.startsWith(`${E}:`)&&q.abort(new Error("工具会话已关闭。"));w.writeHead(204).end(),y();return}if(m.method!=="POST"){w.writeHead(405).end();return}let W=null,x=(j,q=!1)=>{let O=JSON.stringify({jsonrpc:"2.0",id:W,...q?{error:j}:{result:j}});w.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),w.end(O)};try{let j=0,q=[];for await(let b of m){let K=Buffer.from(b);if(j+=K.length,j>8*1024*1024)throw new Error("业务工具请求超过 8 MiB。");q.push(K)}let O=JSON.parse(Buffer.concat(q).toString("utf8"));if(W=O.id??null,O.method==="initialize"){if(d){x({code:-32e3,message:"应用工具提供者已注销。"},!0);return}let b=jr();l.add(b),w.setHeader("mcp-session-id",b),x({protocolVersion:"2025-03-26",capabilities:{tools:{listChanged:!1}},serverInfo:{name:r,version:"1"}});return}if(typeof E!="string"||!l.has(E)){w.writeHead(404).end();return}if(O.method==="notifications/cancelled"){c.get(`${E}:${String(O.params?.requestId)}`)?.abort(new Error("工具调用已取消。")),w.writeHead(202).end();return}if(O.id===void 0){w.writeHead(202).end();return}if(O.method==="ping"){x({});return}if(O.method==="tools/list"){x({tools:e.map(b=>({name:b.name,description:b.description,inputSchema:b.inputSchema,annotations:{readOnlyHint:b.readOnly,destructiveHint:!b.readOnly,openWorldHint:!0}}))});return}if(O.method!=="tools/call"){x({code:-32601,message:"不支持的 MCP 方法。"},!0);return}let ye=n.get(String(O.params?.name));if(!ye)throw new Error("业务工具不存在。");let ee=O.params?.arguments;if(!ee||typeof ee!="object"||Array.isArray(ee))throw new Error("工具参数必须是对象。");let tt=s.get(ye.name);if(!tt(ee)){x({content:[{type:"text",text:`工具参数不符合声明:${JSON.stringify(tt.errors)}`}],isError:!0});return}let te=new AbortController,we=`${E}:${String(W)}`;if(c.has(we))throw new Error("工具请求 ID 正在执行,不能重复提交。");c.set(we,te);let rt=()=>{w.writableEnded||te.abort(new Error("工具请求连接已关闭。"))};w.once("close",rt);let re="validation";try{let K=O.params?._meta?.["aios/execution"],{invocationId:Le,...Kt}=K??{},Se=K===void 0?void 0:Ce(Kt);if(K&&(typeof Le!="string"||!Le))throw new Error("工具调用标识缺失。");re="execution";let Xt=await ye.execute(ee,{signal:te.signal,callId:we,...Se&&t?{files:{resolve:(Yt,Qt)=>t(Se.sessionId,Yt,Qt,te.signal)}}:{},...Se?{execution:Ut({...Se,invocationId:Le})}:{}});re="serialization",te.signal.throwIfAborted(),x(Xe(Xt))}catch(b){x({content:[{type:"text",text:JSON.stringify({error:{message:(b instanceof Error?b.message:String(b)).slice(0,4096),capability:ye.name,phase:re,side_effects:re==="validation"?"not_started":re==="serialization"?"completed":"unknown",next_action:"先核对实际结果,不要因工具返回失败而直接重复执行。"}})}],isError:!0})}finally{w.removeListener("close",rt),c.delete(we),y()}}catch(j){x({code:-32602,message:j instanceof Error?j.message:String(j)},!0)}});return await new Promise((m,w)=>{I.once("error",w),I.listen(0,"127.0.0.1",m)}),{descriptor:{id:r,name:r,transport:"HTTP",url:`http://127.0.0.1:${I.address().port}/mcp`,bearerToken:a,tools:e.map(m=>m.name),defaultToolsApproval:"prompt",toolApprovals:Object.fromEntries(e.map(m=>[m.name,m.readOnly?"auto":"prompt"]))},close:g,closed:h,status:()=>({retired:d,sessions:l.size,calls:c.size,closing:!!p}),retire:()=>{d=!0,y()}}}function Ut(r){return r&&typeof r=="object"&&(Object.values(r).forEach(Ut),Object.freeze(r)),r}import{createHash as $r}from"node:crypto";var Lr=/^[a-z][a-z0-9_]{0,63}$/u;function Ur(r){return r.trim().toLowerCase()}function Ye(r){let e=Ur(r);if(!Lr.test(e))throw new Error("MCP 技能引用标识只能包含小写字母、数字和下划线,必须以字母开头,最长 64 个字符");return e}function Br(r){return`aios_mcp_${Ye(r)}`}function Bt(r,e){let t=e.trim();if(!t)throw new Error("MCP 工具名称不能为空");return`mcp__${Br(r)}__${t}`}function Ne(r){return r.toolProviderId===void 0?`app_${$r("sha256").update(JSON.stringify([r.id,r.version])).digest("hex").slice(0,32)}`:Ye(r.toolProviderId)}function Qe(r,e){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(e))throw new Error("业务工具名称无效。");return Bt(Ne(r),e)}import{randomUUID as zr}from"node:crypto";function Ze(r,e){if(!e)return r;function t(n){try{return n()}catch(o){process.emitWarning("SDK 诊断导出器执行失败,请检查应用诊断配置。",{code:"SDK_DIAGNOSTICS_FAILED",detail:o instanceof Error?o.name:typeof o})}}return{get eventWaitMs(){return r.eventWaitMs},stop:()=>r.stop(),shutdown:()=>r.shutdown(),async call(n,o,i=zr(),s){let a=performance.now(),c={name:"sdk.rpc",method:n,requestId:i},l=t(()=>e.startSpan?.("sdk.rpc",{method:n,requestId:i}));t(()=>e.log?.(Object.freeze({...c,phase:"started"})));let d="completed",p;try{return await r.call(n,o,i,s)}catch(u){throw d="failed",p=u&&typeof u=="object"&&"code"in u&&typeof u.code=="string"&&/^[A-Z0-9_]{1,80}$/.test(u.code)?u.code:"RPC_ERROR",u}finally{let u=performance.now()-a,h=Object.freeze({...c,phase:d,durationMs:u,...p?{errorCode:p}:{}});t(()=>e.log?.(h)),t(()=>e.metric?.("sdk.rpc.duration_ms",u,{method:n,outcome:d})),t(()=>l?.end(h))}}}}async function Pe(r,e){let t;try{t=await r()}catch(n){try{await e()}catch(o){throw new AggregateError([n,o],"文件传输及清理均失败。",{cause:n})}throw n}return await e(),t}var je=class{constructor(e,t){this.transport=e;this.sessionId=t}resolve(e,t="read",n){return this.transport.call("session.file.resolve",{id:this.sessionId,path:e,access:t},void 0,n)}call(e,t,n){return this.transport.call(`session.file.transfer.${e}`,{id:this.sessionId,...t},void 0,n)}async export(e,t,n){let{signal:o}=n,i=await this.call("begin",{kind:"export",path:e},o),s=this,a=0,c=(async function*(){for(;a<i.bytes;){o?.throwIfAborted();let l=await s.call("read",{transferId:i.id,offset:a},o);if(l.bytes<=0)throw new Error("导出数据意外结束。");a+=l.bytes,yield Buffer.from(l.data,"base64")}})();return Pe(async()=>{let l=await t.put({...n,source:c,sha256:i.sha256,bytes:i.bytes});if(o?.throwIfAborted(),a!==i.bytes||!l.version||l.key!==n.key)throw new Error("存储适配器未完整接收文件或未返回正确版本。");return{stored:l,file:i.file,sha256:i.sha256,bytes:i.bytes}},()=>Pe(()=>c.return(void 0),()=>this.call("close",{transferId:i.id})))}async import(e,t,n){if(!e.key||!e.version)throw new Error("导入必须指定对象存储键及版本。");let{signal:o}=n;o?.throwIfAborted();let i=await t.get({key:e.key,version:e.version,signal:o}),s=i.source[Symbol.asyncIterator](),a;return Pe(async()=>{a=await this.call("begin",{kind:"import",path:n.path,expectedVersion:n.expectedVersion,bytes:i.bytes,sha256:i.sha256},o);let c=0;for(;;){o?.throwIfAborted();let d=await s.next();if(d.done)break;let p=d.value;for(let u=0;u<p.byteLength;u+=a.chunkBytes){o?.throwIfAborted();let h=Buffer.from(p.subarray(u,u+a.chunkBytes));c=(await this.call("write",{transferId:a.id,offset:c,data:h.toString("base64")},o)).offset}}return o?.throwIfAborted(),{file:await this.call("commit",{transferId:a.id},o),source:e}},()=>Pe(async()=>s.return?.(),async()=>{a&&await this.call("close",{transferId:a.id})}))}};import Hr from"node:http";import{randomBytes as Jr,timingSafeEqual as Fr}from"node:crypto";async function $t(r){let e=Jr(32).toString("hex"),t=new Set,n=Hr.createServer(async(i,s)=>{let a=Buffer.from(`Bearer ${e}`),c=Buffer.from(i.headers.authorization??"");if(c.length!==a.length||!Fr(c,a)){s.writeHead(401).end();return}if(i.method!=="POST"||i.url!=="/callbacks"){s.writeHead(404).end();return}let l=new AbortController;t.add(l),s.once("close",()=>{s.writableFinished||l.abort(new Error("应用回调请求已断开。"))});try{let d=[],p=0;for await(let I of i){let S=Buffer.from(I);if(p+=S.length,p>64*1024*1024)throw new Error("应用回调请求超过 64 MiB。");d.push(S)}let u=JSON.parse(Buffer.concat(d).toString("utf8")),h=r.get(u.method);if(!h)throw Object.assign(new Error("应用回调不存在。"),{code:"APPLICATION_PROVIDER_OFFLINE"});let g=await h(u.params,l.signal);l.signal.throwIfAborted();let y=JSON.stringify({ok:!0,value:g});s.writeHead(200,{"content-type":"application/json"}).end(y)}catch(d){s.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify({ok:!1,error:{message:d instanceof Error?d.message:String(d),code:d&&typeof d=="object"&&"code"in d?String(d.code):"APPLICATION_CALLBACK_FAILED"}}))}finally{t.delete(l)}});return await new Promise((i,s)=>{n.once("error",s),n.listen(0,"127.0.0.1",i)}),{connection:{url:`http://127.0.0.1:${n.address().port}/callbacks`,token:e,methods:[...r.keys()]},close:async()=>{for(let i of t)i.abort(new Error("应用回调服务已关闭。"));n.closeAllConnections(),await new Promise((i,s)=>n.close(a=>a?s(a):i()))}}}function zt(r){if(!Array.isArray(r)||r.length>2)throw new Error("JS Hook 定义无效。");let e=new Set;return r.map(t=>{if(!t||typeof t!="object"||!["PreToolUse","PostToolUse"].includes(t.event)||e.has(t.event)||typeof t.callback!="string"||!/^hook\.[a-z0-9_]+\.(PreToolUse|PostToolUse)$/.test(t.callback)||!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1||t.timeoutMs>36e5||t.matcher!==void 0&&(typeof t.matcher!="string"||!t.matcher.trim())||Object.keys(t).some(n=>!["event","callback","matcher","timeoutMs"].includes(n)))throw new Error("JS Hook 字段无效。");return e.add(t.event),structuredClone(t)})}function Ht(r,e){let t=e===void 0?{}:e;if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(n=>!["decision","reason","additionalContext"].includes(n))||t.decision!==void 0&&!["continue","deny"].includes(t.decision)||["reason","additionalContext"].some(n=>{let o=t[n];return o!==void 0&&(typeof o!="string"||o.length>32e3)})||t.decision==="deny"&&!t.reason?.trim())throw new Error("Hook 决定无效,拒绝必须说明原因。");return{...t.decision==="deny"?{decision:"block",reason:t.reason}:{},hookSpecificOutput:{hookEventName:r,...t.additionalContext?{additionalContext:t.additionalContext}:{}}}}import Qr from"node:http";import{randomBytes as Zr,timingSafeEqual as en}from"node:crypto";var Vr="[REDACTED]",Gr="(?:密码|口令|密钥|令牌|私钥|凭据|验证码)",Wr=new RegExp(`(${Gr}\\s*["']?\\s*(?:[::=]|是(?!否)|为)\\s*)(?:"([^"]*)"|'([^']*)'|“([^”]*)”|‘([^’]*)’|([^\\s"'“”‘’,。;,;}]+))`,"gu");var qr=["authorization","password","passwd","passphrase","token","api[-_]?key","secret","cookie","credentials?","private[-_]?key","pat"].join("|"),Jt=`(?:[a-z0-9]+[-_])*(?:${qr})`,Kr=new RegExp(`(\\b${Jt}\\b["']?\\s*[:=]\\s*["']?)([^\\s"',};&,。;]+)`,"gi"),Xr=new RegExp(`([?&]${Jt}=)([^&#\\s]*)`,"gi");function Ft(r){return r.replace(/(\/codex\/)[a-f0-9]+(?=\/v1\b)/gi,"$1[REDACTED]").replace(/(\/model-usage\/)[a-f0-9]+/gi,"$1[REDACTED]").replace(/\b(authorization|proxy-authorization)\s*:\s*[^\r\n]+/gi,"$1: [REDACTED]").replace(/\b(set-cookie|cookie)\s*:\s*[^\r\n]+/gi,"$1: [REDACTED]").replace(/\b(bearer|basic)\s+[^\s"',}]+/gi,"$1 [REDACTED]").replace(/(https?:\/\/[^\s/:@]+:)[^\s/@]+(@)/gi,"$1[REDACTED]$2").replace(Xr,"$1[REDACTED]").replace(Kr,"$1[REDACTED]").replace(Wr,(e,t,n,o,i,s)=>{let a=n!==void 0?['"','"']:o!==void 0?["'","'"]:i!==void 0?["“","”"]:s!==void 0?["‘","’"]:["",""];return`${t}${a[0]}${Vr}${a[1]}`})}import{randomUUID as Yr}from"node:crypto";var _e=class{id=Yr();sequence=0;records=[];listeners=new Set;closed=!1;publish(e){this.records.push({...structuredClone(e),cursor:`${this.id}:${++this.sequence}`,occurredAt:new Date().toISOString()}),this.records.length>256&&this.records.shift(),this.wake()}close(){this.closed=!0,this.wake()}wake(){for(let e of this.listeners)e()}async*stream(e={}){let t=this.sequence-this.records.length;if(e.after!==void 0){let[n,o,i]=e.after.split(":");if(t=Number(o),n!==this.id||i!==void 0||!/^\d+$/.test(o??"")||!Number.isSafeInteger(t)||t>this.sequence)throw A("AUTH_EVENT_CURSOR_INVALID","授权事件游标不属于当前凭证提供者。")}for(;;){e.signal?.throwIfAborted();let n=this.sequence-this.records.length;if(t<n)throw A("AUTH_EVENT_CURSOR_EXPIRED","授权事件游标已超出内存保留范围,请重新读取授权状态。");let o=this.records[t-n];if(o){t++,yield structuredClone(o);continue}if(this.closed)return;await new Promise((i,s)=>{let a=()=>{this.listeners.delete(c),e.signal?.removeEventListener("abort",l)},c=()=>{a(),i()},l=()=>{a(),s(e.signal.reason)};this.listeners.add(c),e.signal?.addEventListener("abort",l,{once:!0})})}}};var De=class{constructor(e,t,n){this.authentication=e;this.platformBaseUrl=t;this.provider=n}events=new _e;entries=new Map;sequence=0;epoch=0;revoked=!1;closed=!1;expiration;execution(e){if(e===void 0)return;let t=Ce(e),{context:n}=t,o=this.authentication.principal;if(n&&(n.actor.userId!==o.userId||n.actor.tenantId!==o.tenantId||n.workspaceId!==o.workspaceId))throw A("EXECUTION_PRINCIPAL_MISMATCH","凭证请求的操作者、租户和空间与实例主体不一致。");return n&&(Object.freeze(n.actor),Object.freeze(n.owner),Object.freeze(n)),Object.freeze(t)}clear(){this.epoch++;for(let e of this.entries.values())e.controller.abort(A("MANAGED_AUTHORIZATION_CHANGED","解析凭证期间授权已改变。"));this.entries.clear(),clearTimeout(this.expiration)}revoke(e,t){let n=this.execution(e);return t!==void 0&&this.entries.get(JSON.stringify(n)??"")?.generation!==t?!1:(this.clear(),this.revoked=!0,this.events.publish({type:"invalidated",scope:"provider",reason:"revoked",execution:n,code:"MANAGED_AUTHORIZATION_REVOKED"}),!0)}async resolve(e,t,n){if(this.closed)throw A("MANAGED_PROVIDER_UNAVAILABLE","凭证提供者已关闭。");if(this.revoked&&e!=="explicit")throw A("MANAGED_AUTHORIZATION_REVOKED","应用托管授权已撤销。");let o=this.execution(t),i=JSON.stringify(o)??"";if(e==="explicit"&&o)throw new Error("显式刷新作用于整个实例,不能指定单轮上下文。");let s=this.entries.get(i);if(e==="explicit"&&(!s?.pending||s.reason!=="explicit")&&(this.clear(),s=void 0),s||(s={execution:o,generation:0,controller:new AbortController}),this.entries.delete(i),this.entries.set(i,s),s.pending)await s.pending;else{let a=e==="explicit"||e==="rejected"&&n===s.generation;if(a||!s.cached||s.cached.expiresAt<=Date.now()+3e4){let c=a?e:s.cached||s.expired?"expiring":"initial";s.cached=void 0;let l=this.epoch;s.reason=c;let d=this.load(s,c,l);s.pending=d;try{await d}finally{s.pending===d&&(s.pending=void 0),this.trim()}}}if(!s.cached||s.controller.signal.aborted)throw A("MANAGED_AUTHORIZATION_CHANGED","解析凭证期间授权已改变。");return{...s.cached.credential,generation:s.generation}}trim(){for(let[e,t]of this.entries){if(this.entries.size<=128)return;t.pending||this.entries.delete(e)}}async load(e,t,n){try{let o=await this.provider({reason:t,signal:e.controller.signal,execution:e.execution});if(e.controller.signal.throwIfAborted(),n!==this.epoch)throw A("MANAGED_AUTHORIZATION_CHANGED","解析凭证期间授权已改变。");if(o===null)throw this.revoke(),A("MANAGED_AUTHORIZATION_REVOKED","应用未提供有效授权。");e.cached=kt(o,this.authentication.principal,this.platformBaseUrl),e.expired=!1,e.generation=++this.sequence,this.revoked=!1,this.events.publish({type:"authorized",scope:"credential",reason:t,execution:e.execution,expiresAt:new Date(e.cached.expiresAt).toISOString()})}catch(o){if(n===this.epoch){let i=o&&typeof o=="object"&&"code"in o?String(o.code):"";this.events.publish({type:"invalidated",scope:"credential",reason:"provider_error",execution:e.execution,code:["MANAGED_IDENTITY_MISMATCH","MANAGED_CREDENTIAL_EXPIRED"].includes(i)?i:"MANAGED_CREDENTIAL_ERROR"})}throw o}finally{this.scheduleExpiration()}}scheduleExpiration(){clearTimeout(this.expiration);let e=1/0;for(let t of this.entries.values())t.cached&&(e=Math.min(e,t.cached.expiresAt));e===1/0||this.closed||(this.expiration=setTimeout(()=>{for(let t of this.entries.values())t.cached&&t.cached.expiresAt<=Date.now()&&(t.cached=void 0,t.expired=!0,this.events.publish({type:"invalidated",scope:"credential",reason:"expired",execution:t.execution,code:"MANAGED_CREDENTIAL_EXPIRED"}));this.scheduleExpiration()},Math.min(2147483647,Math.max(1,e-Date.now()))),this.expiration.unref())}close(){this.closed=!0,this.clear(),this.revoked=!0,this.events.publish({type:"invalidated",scope:"provider",reason:"closed",code:"MANAGED_PROVIDER_UNAVAILABLE"}),this.events.close()}};async function Vt(r,e,t){let n=Zr(32).toString("hex"),o=new De(r,e,t),i=Qr.createServer(async(s,a)=>{let c=Buffer.from(`Bearer ${n}`),l=Buffer.from(s.headers.authorization??"");if(c.length!==l.length||!en(c,l)){a.writeHead(401).end();return}if(s.method!=="POST"||s.url!=="/credentials"){a.writeHead(404).end();return}try{let d=0,p=[];for await(let g of s){let y=Buffer.from(g);if(d+=y.length,d>64*1024)throw new Error("凭证请求过大。");p.push(y)}let u=JSON.parse(Buffer.concat(p).toString("utf8"));if(u.generation!==void 0&&(!Number.isSafeInteger(u.generation)||u.generation<1))throw new Error("凭证版本无效。");let h;if(u.revoke===!0)h={revoked:o.revoke(u.execution,u.generation)};else{if(!["initial","expiring","rejected","explicit"].includes(String(u.reason)))throw new Error("凭证解析原因无效。");if(u.reason==="rejected"&&u.generation===void 0)throw new Error("被拒凭证版本无效。");h=await o.resolve(u.reason,u.execution,u.generation)}a.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),a.end(JSON.stringify(h))}catch(d){a.writeHead(400,{"content-type":"application/json","cache-control":"no-store"}),a.end(JSON.stringify({error:{code:d&&typeof d=="object"&&"code"in d?String(d.code):"MANAGED_CREDENTIAL_ERROR",message:Ft(d instanceof Error?d.message:String(d))}}))}});return await new Promise((s,a)=>{i.once("error",a),i.listen(0,"127.0.0.1",s)}),{connection:{url:`http://127.0.0.1:${i.address().port}/credentials`,token:n},events:o.events,close:async()=>{o.close(),i.closeAllConnections(),await new Promise((s,a)=>i.close(c=>c?a(c):s()))}}}import{randomUUID as tn}from"node:crypto";import{setTimeout as Gt}from"node:timers/promises";var de=class{constructor(e,t){this.connection=e;this.authorizationEvents=t}managedEvents(e={}){let t=this.authorizationEvents?.();if(!t)throw new f("MANAGED_PROVIDER_UNAVAILABLE","此客户端未注册托管凭证提供者。");return t.stream(e)}login(e){return this.connection().call("auth.login",e)}getToken(){return this.connection().call("auth.token")}refresh(){return this.connection().call("auth.refresh")}refreshManaged(){return this.connection().call("auth.managed.refresh")}revokeManaged(){return this.connection().call("auth.managed.revoke")}status(){return this.connection().call("auth.status")}context(){return this.connection().call("auth.context")}logout(){return this.connection().call("auth.logout")}completePasswordChange(e){return this.connection().call("auth.password",e)}switchSubject(e){return this.connection().call("auth.switchSubject",e)}async startBrowserLogin(e={}){let t=this.connection(),n=await t.call("auth.browser.start",{...e,requestId:e.requestId??tn()});return new le(t,n.id)}resumeBrowserLogin(e){return new le(this.connection(),e)}},le=class{constructor(e,t){this.transport=e;this.id=t}status(){return this.transport.call("auth.browser.status",{id:this.id})}cancel(){return this.transport.call("auth.browser.cancel",{id:this.id})}async getAuthorizationUrl(e={}){for(;;){e.signal?.throwIfAborted();let t=await this.status();if(this.checkFailure(t),t.state==="waiting"&&t.authorizationUrl)return t.authorizationUrl;if(t.state==="completed")throw new f("LOGIN_ALREADY_COMPLETED","网页登录已完成,请读取登录结果。");await Gt(150,void 0,e)}}async wait(e={}){for(;;){e.signal?.throwIfAborted();let t=await this.status();if(this.checkFailure(t),t.state==="completed"&&t.session)return t.session;await Gt(250,void 0,e)}}checkFailure(e){if(e.state==="failed")throw new f(e.error.code,e.error.message);if(e.state==="cancelled")throw new f("LOGIN_CANCELLED","网页登录已取消。")}};var ue=class{constructor(e){this.connection=e}call(e,t={}){return this.connection().call(`platform.${e}`,t)}getSession(){return this.call("session")}getUser(){return this.call("user")}getTenants(){return this.call("tenants")}getContext(){return this.call("context")}models={list:()=>this.call("models.list"),listSpeechRecognition:()=>this.call("models.speech")};experts={prepare:(e,t)=>this.call("experts.prepare",{...e,...t?{resolved:t}:{}})};account={getSummary:(e={})=>this.call("account.summary",e),listPlanPurchases:()=>this.call("account.purchases"),getUsage:e=>this.call("account.usage",e)};skills={getHome:()=>this.call("skills.home"),install:e=>this.call("skills.install",e),remove:(e,t)=>this.call("skills.remove",{skillId:e,tenantId:t}),getVersions:e=>this.call("skills.versions",e),updateVersion:e=>this.call("skills.updateVersion",e),search:(e={})=>this.call("skills.search",e),getDetail:(e,t)=>this.call("skills.detail",{skillId:e,tenantId:t}),listCategories:()=>this.call("skills.categories"),prepareForLocalTask:e=>this.call("skills.prepare",e)};plugins={list:(e={})=>this.call("plugins.list",e),getDetail:e=>this.call("plugins.detail",{recordId:e}),listCategories:()=>this.call("plugins.categories"),prepare:(e,t,n)=>this.call("plugins.prepare",{pluginId:e,recordId:t,resourceVersion:n}),getAuthorization:e=>this.call("plugins.authorization.get",{pluginId:e}),saveAuthorization:(e,t)=>this.call("plugins.authorization.save",{pluginId:e,request:t}),revokeAuthorization:e=>this.call("plugins.authorization.revoke",{pluginId:e}),verifyAuthorization:e=>this.call("plugins.authorization.verify",{pluginId:e})};knowledge={tree:()=>this.call("knowledge.tree"),search:(e={})=>this.call("knowledge.search",e),listDocuments:e=>this.call("knowledge.documents",e),readDocument:e=>this.call("knowledge.read",e),getDocumentDownloadLink:e=>this.call("knowledge.downloadLink",{documentId:e})}};import U from"node:fs";import P from"node:path";import{createHash as rn}from"node:crypto";import{createRequire as nn}from"node:module";import{t as on,x as sn}from"tar";var an=nn(import.meta.url),cn=["win32-x64","darwin-x64","darwin-arm64","linux-x64","linux-arm64"];function dn(r=`${process.platform}-${process.arch}`){if(!cn.includes(r))throw new f("RUNTIME_UNSUPPORTED",`尚未提供 ${r} 的精简运行时。`);let e=`@kmlckj/aios-runtime-${r}`;try{return P.dirname(an.resolve(`${e}/package.json`))}catch(t){throw t.code!=="MODULE_NOT_FOUND"?t:new f("RUNTIME_PACKAGE_MISSING",`缺少 ${e}。请安装对应版本的运行时包,不要使用 --omit=optional;也可显式指定 runtime.directory。`)}}async function ln(r){let e=rn("sha256");for await(let t of U.createReadStream(r))e.update(t);return e.digest("hex")}async function un(r,e){let t=new Set,n,o=i=>{if(!i||i.includes("\\")||i.includes("\0")||P.posix.isAbsolute(i)||/^[A-Za-z]:/.test(i)||i.split("/").includes(".."))throw new Error(`运行时归档路径无效:${i}`)};if(await on({file:r,strict:!0,onReadEntry(i){try{o(i.path);let s=P.posix.normalize(i.path).replace(/\/$/,"");if(t.has(s))throw new Error(`运行时归档包含重复路径:${s}`);if(t.add(s),!["File","OldFile","Directory","SymbolicLink","Link"].includes(i.type))throw new Error(`运行时归档条目类型无效:${i.type}`);if(i.linkpath){if(P.posix.isAbsolute(i.linkpath)||i.linkpath.includes("\\")||/^[A-Za-z]:/.test(i.linkpath))throw new Error(`运行时归档链接越界:${s}`);o(i.type==="SymbolicLink"?P.posix.join(P.posix.dirname(s),i.linkpath):i.linkpath)}}catch(s){n??=s}}}),n)throw n;await sn({file:r,cwd:e,strict:!0,preservePaths:!1})}async function pe(r,e){if(r.runtime?.directory!==void 0)return se(r);let t=e??dn(),n=JSON.parse(U.readFileSync(P.join(t,"package.json"),"utf8")),o=JSON.parse(U.readFileSync(new URL("../package.json",import.meta.url),"utf8")),i=JSON.parse(U.readFileSync(P.join(t,"runtime-package.json"),"utf8")),s=`${process.platform}-${process.arch}`;if(n.name!==`@kmlckj/aios-runtime-${s}`||n.version!==o.version||i.schemaVersion!==1||i.version!==o.version||i.target!==s||i.archive?.file!=="payload.tar.gz"||!/^[a-f0-9]{64}$/.test(i.archive.sha256)||!Number.isSafeInteger(i.archive.size)||i.archive.size<=0)throw new f("RUNTIME_INCOMPATIBLE","npm 运行时包的版本、平台或归档清单与 SDK 不一致。");if(!r.runtime||typeof r.runtime.dataDirectory!="string"||!r.runtime.dataDirectory.trim())throw new Error("运行时数据目录不能为空。");let a=P.resolve(r.runtime.dataDirectory,"runtimes"),c=P.join(a,`${s}-${i.archive.sha256}`),l=se({...r,runtime:{...r.runtime,directory:c}});if(U.existsSync(c))return await N(c,l.runtime.trustedPublicKey),l;let d=P.join(t,i.archive.file);if(U.statSync(d).size!==i.archive.size||await ln(d)!==i.archive.sha256)throw new f("RUNTIME_INTEGRITY_FAILED","npm 运行时归档内容与清单不一致。");Y(a);let p=U.mkdtempSync(P.join(a,".unpack-"));try{await un(d,p),await N(p,l.runtime.trustedPublicKey);try{U.renameSync(p,c)}catch(u){if(!U.existsSync(c))throw u;await N(c,l.runtime.trustedPublicKey)}return l}finally{U.rmSync(p,{recursive:!0,force:!0})}}import{randomUUID as pn}from"node:crypto";function Wt(r){let e=n=>{let o=r[n];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>864e5)throw Object.assign(new Error(`${n} 必须是 0 至 86400000 毫秒的整数。`),{code:"INVALID_DRAIN_OPTIONS"});return o},t=e("timeoutMs");if(r.onTimeout==="cancel")return{timeoutMs:t,onTimeout:"cancel",cancelTimeoutMs:e("cancelTimeoutMs")};if(r.onTimeout==="return")return{timeoutMs:t,onTimeout:"return"};throw Object.assign(new Error("必须明确选择排空到期后返回或取消。"),{code:"INVALID_DRAIN_OPTIONS"})}var fe=class r{constructor(e,t,n,o,i,s){this.options=e;this.metadata=t;this.verified=n;this.child=o;this.exited=i;this.connector=s;o.on("message",this.onMessage),o.on("error",this.onError),o.once("disconnect",this.onDisconnect),i.then(a=>{this.exit=a,this.exitController.abort(new f("RUNTIME_EXITED","SDK 宿主进程已退出。")),this.onError(new f("RUNTIME_EXITED",`SDK 宿主已退出(${a.code??a.signal})。`)),o.removeListener("message",this.onMessage),o.removeListener("error",this.onError),o.removeListener("disconnect",this.onDisconnect)})}exit;exitController=new AbortController;shutdownRequest;pending=new Map;static async start(e,t,n){let o=Wt({...t.shutdown}),i=await pe(e),s=await N(i.runtime.directory,i.runtime.trustedPublicKey),{child:a,ready:c,exited:l}=Oe({options:i,verifiedPackage:s,managed:{shutdown:o}});try{let d=await c;return new r(i,d,s,a,l,n)}catch(d){throw a.connected&&a.disconnect(),a.unref(),d}}get pid(){return this.metadata.pid}get instanceId(){return this.metadata.instanceId}connect(e={}){return this.exit||!this.child.connected?Promise.reject(new f("RUNTIME_EXITED","受管宿主连接已结束。")):this.connector(this.options,this.metadata,this.verified,e,this.exitController.signal)}shutdown(){if(this.shutdownRequest)return this.shutdownRequest;if(this.exit||!this.child.connected)return Promise.reject(new f("RUNTIME_EXITED","受管宿主连接已结束,请读取 wait 的退出结果。"));let e=pn();return this.shutdownRequest=new Promise((t,n)=>{this.pending.set(e,{resolve:t,reject:n}),this.child.send({type:"shutdown",id:e},o=>{o&&(this.pending.delete(e),n(o))})}).then(async t=>{if(t.status==="drained"){let n=await this.wait();if(n.code!==0)throw new f("RUNTIME_EXIT_FAILED",`SDK 宿主清理后异常退出(${n.code??n.signal})。`)}else this.shutdownRequest=void 0;return t},t=>{throw this.shutdownRequest=void 0,t}),this.shutdownRequest}wait(){return this.exited}onMessage=e=>{if(e.type!=="shutdown")return;let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.ok?t.resolve(e.value):t.reject(new f(e.error.code,e.error.message)))};onError=e=>{for(let t of this.pending.values())t.reject(e);this.pending.clear()};onDisconnect=()=>this.onError(new f("HOST_DISCONNECTED","宿主控制通道已断开,请读取 wait 的退出结果。"))};function qt(r,e){if(e.credentials&&(r.mode!=="platform"||!r.authentication))throw new Error("凭证回调只能用于平台托管模式。");if(e.authorize&&!r.authorization?.required)throw new Error("会话授权回调需要 authorization.required=true。");if(e.memoryStore&&r.memory?.storage!=="external")throw new Error("记忆存储适配器需要 memory.storage=external。")}var he=class r{constructor(e,t,n,o={}){this.transport=e;this.options=t;this.mode=n;this.services=o;this.transport=Ze(e,o.diagnostics)}toolProviders=new Set;activeToolProviders=new Map;credentialProvider;callbacks;callbackHandlers=new Map;lifecycleQueue=Promise.resolve();closed=!1;scheduleLifecycle(e){let t=this.lifecycleQueue.then(e);return this.lifecycleQueue=t.then(()=>{},()=>{}),t}assertOpen(){if(this.closed)throw new f("RUNTIME_CLOSED","SDK 客户端连接已关闭。")}async startCallbacks(){let e=this.callbackHandlers;if(this.services.authorize&&e.set("session.authorize",(i,s)=>this.services.authorize(Object.freeze(i),{signal:s})),this.services.memoryStore){let i=this.services.memoryStore;e.set("memory.read",(s,a)=>i.read(s,a)),e.set("memory.compareAndSwap",(s,a)=>i.compareAndSwap(s,a))}if(!e.size)return;let t=this.callbacks,n=t??await $t(e),o={...n.connection,methods:[...e.keys()]};try{await this.transport.call("application.callbacks",{connection:o}),this.callbacks=n}catch(i){throw t||await n.close(),i}}static async start(e,t,n){qt(e,t);let o=e.mode==="platform"&&e.authentication&&t.credentials?await Vt(e.authentication,e.platformBaseUrl,t.credentials):void 0;try{return{transport:n?await ae.attach(e,n.metadata,n.verified,o?.connection,n.exitSignal):await ae.start(e,o?.connection),provider:o}}catch(i){throw await o?.close(),i}}static async create(e,t={}){let n=await pe(e),{transport:o,provider:i}=await r.start(n,t),s=new r(o,n,n.mode,t);s.credentialProvider=i;try{await s.startCallbacks()}catch(a){throw await s.close(),a}return s}static startManaged(e,t){return fe.start(e,t,async(n,o,i,s,a)=>{let{transport:c,provider:l}=await r.start(n,s,{metadata:o,verified:i,exitSignal:a}),d=new r(c,n,n.mode,s);d.credentialProvider=l;try{await d.startCallbacks()}catch(p){throw await d.close(),p}return d})}static async connectCli(e){return new r(await Re.connect(e),e,"platform")}auth=new de(()=>this.transport,()=>this.credentialProvider?.events);platform=new ue(()=>this.transport);runtime={health:e=>this.transport.call("runtime.health",{},void 0,e),activity:()=>this.transport.call("runtime.activity"),drain:(e,t)=>this.transport.call("runtime.drain",e,void 0,t)};resources={limits:{get:()=>this.transport.call("resources.limits.get"),set:(e,t,n)=>this.transport.call("resources.limits.set",{key:e,value:t,revision:n})},cache:{status:()=>this.transport.call("resources.cache.status"),prune:(e={})=>this.transport.call("resources.cache.prune",e)}};skills={list:()=>this.transport.call("skills.list"),importVersion:e=>this.transport.call("skills.importVersion",e),importPaths:e=>this.transport.call("skills.import",{paths:e}),remove:e=>this.transport.call("skills.remove",{reference:e})};plugins={list:()=>this.transport.call("plugins.list"),install:(e,t)=>this.transport.call("plugins.install",{recordId:e,source:t}),update:(e,t,n)=>this.transport.call("plugins.update",{pluginId:e,recordId:t,expectedRevision:n}),setEnabled:(e,t,n)=>this.transport.call("plugins.setEnabled",{pluginId:e,enabled:t,expectedRevision:n}),remove:(e,t)=>this.transport.call("plugins.remove",{pluginId:e,expectedRevision:t})};settings={get:()=>this.transport.call("settings.get"),set:(e,t,n)=>this.transport.call("settings.set",{domain:e,value:t,revision:n})};native={settings:()=>this.transport.call("native.settings"),configure:(e,t)=>this.transport.call("native.configure",{value:e,revision:t}),status:e=>this.transport.call("native.status",{kind:e}),registerBrowser:()=>this.transport.call("native.register"),unregisterBrowser:()=>this.transport.call("native.unregister")};memory={get:e=>this.transport.call("memory.get",e),setEnabled:e=>this.transport.call("memory.setEnabled",e),edit:e=>this.transport.call("memory.edit",e),reset:e=>this.transport.call("memory.reset",e)};async setPlatformBaseUrl(e){if(!("mode"in this.options)||this.options.mode!=="platform")throw new Error("独立模式不使用平台基地址。");await this.configure({platformBaseUrl:e})}getConfiguration(){return this.transport.call("configuration.get")}configure(e){return this.scheduleLifecycle(()=>this.applyConfiguration(e))}async applyConfiguration(e){if(this.assertOpen(),!("mode"in this.options))throw new Error("连接已有 CLI 时请通过 CLI 修改全局配置。");if(this.options.mode==="standalone"&&e.platformBaseUrl!==void 0)throw new Error("独立模式不使用平台基地址。");if(this.options.mode==="platform"&&e.models!==void 0)throw new Error("平台模型由平台管理;外部模型请使用独立模式。");let t=await pe({...this.options,...e});qt(t,this.services),await N(t.runtime.directory,t.runtime.trustedPublicKey),await this.transport.call("configuration.validate",{options:t}),await this.transport.shutdown(),await this.disconnect();let{transport:n,provider:o}=await r.start(t,this.services);this.transport=Ze(n,this.services.diagnostics),this.credentialProvider=o,this.options=t,this.closed=!1;try{await this.startCallbacks()}catch(i){throw await this.disconnect(),i}return this.getConfiguration()}capabilities(e={}){return this.transport.call("capabilities",e)}dependencies(){return this.transport.call("dependencies")}defineAgent(e){return this.scheduleLifecycle(()=>this.registerAgent(e))}async registerAgent(e){this.assertOpen();let{tools:t,toolProviderId:n,jsHooks:o,...i}=e,s=Ne(e),a=[],c=new Map;for(let[u,h]of Object.entries(o??{})){if(!["beforeTool","afterTool"].includes(u)||!h||typeof h.execute!="function")throw new Error("JS Hook 必须提供执行函数。");let g=u==="beforeTool"?"PreToolUse":"PostToolUse",y=`hook.${s}.${g}`;a.push({event:g,callback:y,timeoutMs:h.timeoutMs??3e4,...h.matcher?{matcher:h.matcher}:{}}),c.set(y,this.callbackHandlers.get(y))}o&&(i.jsHookDefinitions=zt(a));let l=JSON.stringify([e.id,e.version]),d=this.activeToolProviders.get(s);if(d&&d.agent!==l)throw new Error("应用工具提供者 ID 已被其他智能体使用。");let p=t?.length?await Lt(s,t,(u,h,g,y)=>this.transport.call("session.file.resolve",{id:u,path:h,access:g},void 0,y)):void 0;p&&this.toolProviders.add(p);try{for(let[g,y]of Object.entries(o??{})){let I=g==="beforeTool"?"PreToolUse":"PostToolUse";this.callbackHandlers.set(`hook.${s}.${I}`,async(S,m)=>{let w=await y.execute(Object.freeze(S),{signal:m});return Ht(I,w),w})}o&&await this.startCallbacks();let u=[...i.mcpServers??[],...p?[p.descriptor]:[]];await this.transport.call("agent.define",{...i,mcpServers:u,...p?{applicationToolProviderId:s}:{}}),d?.provider?.retire();let h={agent:l,provider:p};return this.activeToolProviders.set(s,h),p&&p.closed.then(()=>{this.toolProviders.delete(p)}),new Me(this.transport,e.id,e.version,p,t?.map(g=>({name:g.name,reference:Qe(e,g.name)})),()=>{if(this.activeToolProviders.get(s)!==h)throw new Error("此工具提供者已被新注册替换,请使用当前 Agent 句柄。")})}catch(u){for(let[h,g]of c)g?this.callbackHandlers.set(h,g):this.callbackHandlers.delete(h);throw p&&(this.toolProviders.delete(p),await p.close()),u}}async openSession(e){return new ge(this.transport,await this.transport.call("session.get",{id:e}))}async openAgent(e,t){return this.assertOpen(),await this.transport.call("agent.providers",{agentId:e,agentVersion:t}),new Me(this.transport,e,t)}listSessions(e={}){return this.transport.call("session.list",e)}shutdown(){return this.scheduleLifecycle(async()=>{this.assertOpen(),await this.transport.shutdown(),await this.disconnect()})}close(){return this.scheduleLifecycle(()=>this.disconnect())}async disconnect(){if(!this.closed){this.closed=!0;try{await this.transport.stop()}finally{await Promise.all([...this.toolProviders].map(e=>e.close()).concat(this.credentialProvider?[this.credentialProvider.close()]:[])),this.callbacks&&(await this.callbacks.close(),this.callbacks=void 0),this.callbackHandlers.clear(),this.toolProviders.clear(),this.activeToolProviders.clear(),this.credentialProvider=void 0}}}},Me=class{constructor(e,t,n,o,i=[],s=()=>{}){this.transport=e;this.id=t;this.version=n;this.provider=o;this.tools=i;this.assertCurrentProvider=s}async createSession(e={}){return new ge(this.transport,await this.transport.call("session.create",{agentId:this.id,agentVersion:this.version,...e,creationId:e.creationId??T()}))}async adoptSession(e,t={}){return new ge(this.transport,await this.transport.call("session.bind",{id:e,agentId:this.id,agentVersion:this.version,policy:t.policy}))}providerStatus(){return this.transport.call("agent.providers",{agentId:this.id,agentVersion:this.version})}unregisterProvider(){return this.assertCurrentProvider(),this.transport.call("agent.unregisterProvider",{agentId:this.id,agentVersion:this.version})}async releaseProvider(){return await this.unregisterProvider(),this.provider?.retire(),this.provider?.status()}waitProviderClosed(){return this.provider?.closed??Promise.resolve()}},ge=class r{constructor(e,t){this.transport=e;this.info=t;this.id=t.id,this.files=new je(e,this.id)}id;files;runtimeTuning(){return this.transport.call("session.runtimeTuning",{id:this.id})}memory={get:(e={})=>this.transport.call("memory.get",{...e,sessionId:this.id}),edit:e=>this.transport.call("memory.edit",{...e,sessionId:this.id}),reset:()=>this.transport.call("memory.reset",{sessionId:this.id}),setEnabled:e=>this.transport.call("memory.setEnabled",{enabled:e,sessionId:this.id})};async send(e,t={}){let n=t.commandId??T(),o=await this.transport.call("session.send",{id:this.id,content:e,options:{...t,commandId:n}});return new me(this.transport,this.id,o.runId,n)}enqueue(e,t={}){return this.transport.call("session.enqueue",{id:this.id,content:e,options:{...t,commandId:t.commandId??T()}})}queue(){return this.transport.call("session.queue",{id:this.id})}editQueued(e,t,n,o=T()){return this.transport.call("session.queue.edit",{id:this.id,pendingMessageId:e,content:t,queueVersion:n,commandId:o})}removeQueued(e,t,n=T()){return this.transport.call("session.queue.delete",{id:this.id,pendingMessageId:e,queueVersion:t.queueVersion,targetRunId:t.activeRunId,commandId:n})}reorderQueue(e,t,n=T()){return this.transport.call("session.queue.reorder",{id:this.id,pendingMessageIds:e,queueVersion:t,commandId:n})}dispatchQueued(e,t,n,o=T()){return this.transport.call("session.queue.send",{id:this.id,pendingMessageId:e,queueVersion:t,targetRunId:n,commandId:o})}history(){return this.transport.call("session.history",{id:this.id})}rename(e,t){return this.transport.call("session.rename",{id:this.id,name:e,expectedRevision:t})}setArchived(e,t){return this.transport.call("session.archive",{id:this.id,archived:e,expectedRevision:t})}runs(e={},t){return this.transport.call("session.runs",{id:this.id,...e},void 0,t)}async*events(e={}){let t=e.cursor;for(;;){e.signal?.throwIfAborted();let n=await this.transport.call("session.events",{id:this.id,cursor:t,waitMs:this.transport.eventWaitMs??0},void 0,e.signal);for(let o of n.events)e.signal?.throwIfAborted(),yield o;t=n.cursor,this.transport.eventWaitMs||await et(150,void 0,{signal:e.signal})}}eventPage(e={}){return this.transport.call("session.events",{id:this.id,cursor:e.cursor,waitMs:0},void 0,e.signal)}queryHistory(e={}){return this.transport.call("session.history.query",{id:this.id,...e})}clear(e){return this.transport.call("session.clear",{id:this.id,...e})}delete(e){return this.transport.call("session.delete",{id:this.id,...e})}artifacts(e={},t={}){return this.transport.call("session.artifacts",{id:this.id,query:e},void 0,t.signal)}operations(e={}){return this.transport.call("session.operations",{id:this.id,...e})}teamState(){return this.transport.call("session.team.state",{id:this.id})}async createBackgroundSession(e,t=T()){let n=await this.transport.call("session.team.background",{id:this.id,memberId:e,creationId:t});return new r(this.transport,n)}operation(e,t={}){return this.transport.call("session.operation",{id:this.id,operationId:e},void 0,t.signal)}cancelOperation(e,t={}){return this.transport.call("session.operation.cancel",{id:this.id,operationId:e},void 0,t.signal)}configuration(e){return this.transport.call("session.configuration",{id:this.id,revision:e})}configure(e,t){return this.transport.call("session.defaults",{id:this.id,defaults:e,expectedRevision:t})}configureBuiltins(e,t){return this.transport.call("session.builtins",{id:this.id,builtins:e,expectedRevision:t})}updateAgent(e){return this.transport.call("session.agent",{id:this.id,...e})}receipt(e){return this.transport.call("session.receipt",{id:this.id,commandId:e})}resumeRun(e){return new me(this.transport,this.id,e)}async compact(e=T()){let t=await this.transport.call("session.compact",{id:this.id,commandId:e});return new me(this.transport,this.id,t.runId,e)}},me=class r{constructor(e,t,n,o){this.transport=e;this.taskId=t;this.id=n;this.commandId=o}state(e={}){return this.transport.call("run.state",{taskId:this.taskId,runId:this.id},void 0,e.signal)}context(){return this.transport.call("run.context",{taskId:this.taskId,runId:this.id})}memoryPolicy(){return this.transport.call("run.memoryPolicy",{taskId:this.taskId,runId:this.id})}team(e,t={}){return this.transport.call("session.team.command",{id:this.taskId,runId:this.id,command:e},void 0,t.signal)}artifacts(e={},t={}){return this.transport.call("session.artifacts",{id:this.taskId,query:{...e,runId:this.id}},void 0,t.signal)}operations(){return this.transport.call("session.operations",{id:this.taskId,runId:this.id})}operation(e,t={}){return this.transport.call("session.operation",{id:this.taskId,runId:this.id,operationId:e},void 0,t.signal)}cancelOperation(e,t={}){return this.transport.call("session.operation.cancel",{id:this.taskId,runId:this.id,operationId:e},void 0,t.signal)}cancel(e=T()){return this.transport.call("run.cancel",{taskId:this.taskId,runId:this.id,commandId:e})}detach(){return this.transport.call("run.detach",{taskId:this.taskId,runId:this.id})}approve(e,t,n=T()){return this.transport.call("run.approve",{taskId:this.taskId,runId:this.id,toolCallId:e,decision:t,commandId:n})}answer(e,t,n=T()){return this.transport.call("run.answer",{taskId:this.taskId,runId:this.id,requestId:e,response:t,commandId:n})}cancelInput(e,t=T()){return this.transport.call("run.cancelInput",{taskId:this.taskId,runId:this.id,requestId:e,commandId:t})}async confirmPlan(e=T()){let t=await this.transport.call("run.confirmPlan",{taskId:this.taskId,runId:this.id,commandId:e});return new r(this.transport,this.taskId,t.runId,e)}async*events(e={}){let t=e.cursor;for(;;){e.signal?.throwIfAborted();let n=await this.transport.call("run.events",{taskId:this.taskId,runId:this.id,cursor:t,waitMs:this.transport.eventWaitMs??0},void 0,e.signal);for(let o of n.events)e.signal?.throwIfAborted(),yield o;if(t=n.cursor,n.terminal)return;this.transport.eventWaitMs||await et(150,void 0,{signal:e.signal})}}async wait(e={}){for(;;){e.signal?.throwIfAborted();let t=this.transport.eventWaitMs?await this.transport.call("run.wait",{taskId:this.taskId,runId:this.id,waitMs:this.transport.eventWaitMs},void 0,e.signal):await this.state(e);if(t.status!=="running"&&t.status!=="queued")return t;this.transport.eventWaitMs||await et(150,void 0,{signal:e.signal})}}},vs=he.create,ks=he.connectCli,Es=he.startManaged;export{Me as Agent,he as AiosClient,f as AiosSdkError,de as AuthApi,le as BrowserLogin,fe as ManagedHost,ue as PlatformApi,me as Run,ge as Session,Ne as applicationToolProviderId,Qe as applicationToolReference,ks as connectCli,vs as createClient,Es as startManagedHost,Rr as toolResult,N as validateRuntime};
@@ -26,6 +26,7 @@ export interface ModelRoutingIdentity {
26
26
  }
27
27
  export declare const LICOS_MODEL_ROUTING_HEADER_NAMES: readonly ["X-Licos-Current-User-Id", "X-Licos-Current-User-Name", "X-Licos-Current-Org-Id", "X-Licos-Current-Org-Name", "X-Licos-Owner-Project-Id", "X-Licos-Owner-Project-Name", "X-Licos-Owner-Project-Type", "X-Licos-Owner-Application-Type", "X-Licos-Owner-Workspace-Id", "X-Licos-Owner-Workspace-Name", "X-Licos-Owner-Org-Id", "X-Licos-Owner-Org-Name", "X-Licos-Owner-User-Id", "X-Licos-Owner-User-Name", "X-Licos-Owner-Workflow-Id", "X-Licos-Owner-Workflow-Name", "X-Licos-Owner-Plugin-Id", "X-Licos-Owner-Plugin-Name", "X-Licos-Runtime-Env", "X-Licos-UsagScene"];
28
28
  export declare function encodeLicosHeaderValue(name: string, value: string): string;
29
+ export declare function modelRequiredHeaders(value: unknown): Record<string, string>;
29
30
  export declare function modelRoutingHeaders(identity: ModelRoutingIdentity, usageScene?: string | undefined): {
30
31
  'X-AIOS-Execution-Context'?: string | undefined;
31
32
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kmlckj/aios-agent-server-sdk",
3
- "version": "0.0.7",
3
+ "version": "0.0.8",
4
4
  "description": "AIOS agent application SDK for Node.js",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -16,11 +16,11 @@
16
16
  "tar": "7.5.22"
17
17
  },
18
18
  "optionalDependencies": {
19
- "@kmlckj/aios-runtime-win32-x64": "0.0.7",
20
- "@kmlckj/aios-runtime-darwin-x64": "0.0.7",
21
- "@kmlckj/aios-runtime-darwin-arm64": "0.0.7",
22
- "@kmlckj/aios-runtime-linux-x64": "0.0.7",
23
- "@kmlckj/aios-runtime-linux-arm64": "0.0.7"
19
+ "@kmlckj/aios-runtime-win32-x64": "0.0.8",
20
+ "@kmlckj/aios-runtime-darwin-x64": "0.0.8",
21
+ "@kmlckj/aios-runtime-darwin-arm64": "0.0.8",
22
+ "@kmlckj/aios-runtime-linux-x64": "0.0.8",
23
+ "@kmlckj/aios-runtime-linux-arm64": "0.0.8"
24
24
  },
25
25
  "exports": {
26
26
  ".": {