@kmlckj/aios-agent-server-sdk 0.0.2 → 0.0.5
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.
|
|
1
|
+
# AIOS Agent Server SDK 0.0.5
|
|
2
2
|
|
|
3
3
|
面向 Node.js 应用的智能体开发 SDK。应用负责自己的界面和业务工具,SDK 提供智能体定义、会话、事件、审批、记忆及本地任务执行。
|
|
4
4
|
|
|
@@ -12,6 +12,8 @@ npm install @kmlckj/aios-agent-server-sdk
|
|
|
12
12
|
|
|
13
13
|
SDK 调用库只发布一份,npm 根据系统和处理器架构自动安装对应的 `@kmlckj/aios-runtime-*` 子包,不下载其他平台的二进制。本次正式交付范围为 Windows x64;其他平台须先完成对应运行时构建和发布,不能使用 Windows 子包。不要使用 `--omit=optional`。首次创建客户端时,将随 npm 安装的运行时归档校验并解压到 `runtime.dataDirectory/runtimes`;这个过程不访问网络、不运行 npm 安装脚本。后续初始化验证并复用同一份文件,升级不会覆盖正在运行的旧版本。
|
|
14
14
|
|
|
15
|
+
`session.send` 和 `session.enqueue` 支持正文为空字符串的仅附件消息,通过 `attachments`、`attachmentIds` 或 `references` 提供文件。正文与所有消息内容均为空时,由共用执行层拒绝。
|
|
16
|
+
|
|
15
17
|
`runtime.directory` 可以省略;显式指定时使用该目录,路径无效会报错,不转用 npm 包。离线交付仍支持安装 SDK `.tgz`、解压已签名的运行时并指定目录。当前版本的 npm 发布是否完成以发布记录为准,本说明不是已上架声明。
|
|
16
18
|
|
|
17
19
|
- 宿主使用 Node 22.23.2+(22 系列)或 Node 24;运行时系统/架构须与宿主一致。
|
|
@@ -159,9 +161,9 @@ CLI 必须运行支持 SDK 协议及能力选择的构建;旧版本没有 `/sd
|
|
|
159
161
|
|
|
160
162
|
长工具结果由共享运行时保存,模型收到预览与 `next` 续读引用。外部 MCP 和应用回调同样适用,读取已有结果不会再次执行回调。结构化 MCP 输出在代理侧明确声明“原结果或归档引用”两种形式;完整业务数据可从归档读取,图片等非文本块保持原类型。
|
|
161
163
|
|
|
162
|
-
|
|
164
|
+
动态工具、文档摘要和命令日志统一通过 `next` 返回 `server/tool/output_id/offset`,续读使用 `aios_tool_results.read_tool_output`,参数为本任务的 `output_id` 与字节 `offset`。不再向模型返回内部归档文件路径,改变 cwd 不影响续读。它是已启用工具的结果交付服务,只能读取本任务产生的托管结果,不接受任意文件路径;关闭内置文件工具不会启用 `read_file`。没有任何 AIOS 工具或外部提供者时,不启动该服务。
|
|
163
165
|
|
|
164
|
-
单份文本结果、每路命令日志的保存上限为 64 MiB
|
|
166
|
+
单份文本结果、每路命令日志的保存上限为 64 MiB。命令日志保留退出状态和独立的完整性标记;容量不足、磁盘错误或内容已清理都会明确返回,不自动重跑原操作。归档由宿主管理,保存于工作区根目录的 `.aios/tool-output/<任务范围>/`,独立于任务 cwd;不会在任务刚结束时删除,以便历史任务继续读取。旧版归档位置及已有 `output_id/offset` 引用保持可读,历史事件中的旧路径字段仍可解析为续读引用。
|
|
165
167
|
|
|
166
168
|
```js
|
|
167
169
|
const catalog = await client.capabilities({ kind: 'tool', category: 'documents' });
|
|
@@ -360,6 +362,8 @@ for (const reference of await run.operations()) {
|
|
|
360
362
|
|
|
361
363
|
`runtime.dataDirectory` 保存宿主状态;可分别设置 `workspaceDirectory`、`cacheDirectory`、`temporaryDirectory` 三个绝对目录基址。每个基址仍按应用和主体分区,`getConfiguration().paths` 返回实际目录。新自动任务使用配置的工作区;已有任务继续使用原来保存的路径,不自动迁移文件。缓存清理只处理受管理的缓存,保留工作文件。任务执行子进程的 TEMP/TMP/TMPDIR 使用实际临时目录。
|
|
362
364
|
|
|
365
|
+
Windows 新应用采用短目录布局,已有应用保留原宿主目录。新任务使用独立的短任务目录;`paths.tasksDirectory` 返回新任务目录,`legacyTasksDirectory` 返回仍可读取的旧任务目录。每个任务的 `pathLayoutVersion: 2` 与宿主、仓库的布局记录共同确定位置,不按软件版本或创建日期猜测,也不搬迁历史文件。短目录的完整应用身份会被校验;目录缺失、布局版本未知或出现新旧重复记录时报告真实错误,不创建空任务替代。用户显式选择的工作目录保持原位置。macOS/Linux 保持原布局。短布局减少内部路径开销,不能消除任意外部程序自身的路径长度限制;部署时仍应选择较短的数据目录基址。
|
|
366
|
+
|
|
363
367
|
```ts
|
|
364
368
|
const session = await agent.createSession({
|
|
365
369
|
workspacePath: '/workspace',
|
|
@@ -373,6 +377,8 @@ const session = await agent.createSession({
|
|
|
373
377
|
|
|
374
378
|
相对授权根和 cwd 按 workspacePath 解析;cwd 必须是其中已存在的目录。文件工具按 cwd 解析相对路径,写入前检查真实父目录和符号链接。SDK 状态目录可以位于平台根目录内,但不能被文件工具读取、修改或搜索;显式附件与已登记技能资源保留既有只读授权。未配置 `paths` 的历史任务沿用原有行为。
|
|
375
379
|
|
|
380
|
+
`task_update.artifact_paths` 和专家团产物登记的相对路径同样按调用者的 cwd 解析,并校验其读取授权。返回的文件引用可以直接交给文件工具再次读取;历史已保存的工作区相对产物引用保持原有含义,恢复会话不会改变指向。
|
|
381
|
+
|
|
376
382
|
声明路径策略后,原生命令及 AIOS 受管命令使用同一份原生权限配置,恢复、分叉和后续轮次不会因“完全访问”放大目录授权,只读成员保持只读。当前 Windows 非提权沙箱无法执行分离的读目录或 deny-read 限制,会返回工具失败,不转为无沙箱执行。`windowsSandbox: 'elevated'` 仅供部署方已经配置相应系统沙箱的机器,本 SDK 不自动提权或创建系统账号;本机未验收该模式。
|
|
377
383
|
|
|
378
384
|
数据分析、UI 和矢量产物工具中的模型脚本,在声明目录策略时也通过同一原生受控命令入口运行。拒绝执行会返回真实工具错误,不改用普通进程启动。应用注册的回调、第三方 MCP 和扩展代码运行在其自身宿主内,须由应用配置相应文件系统/容器边界。
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{randomUUID as
|
|
1
|
+
import{randomUUID as T}from"node:crypto";import{setTimeout as Ye}from"node:timers/promises";import yr from"node:path";import{randomUUID as Nt}from"node:crypto";var m=class extends Error{constructor(t,n,o){super(n,o);this.code=t;this.name="AiosSdkError"}};import sr from"node:http";import{setTimeout as ar}from"node:timers/promises";import _ from"node:fs";import rt from"node:os";import re from"node:path";import{createHash as rr}from"node:crypto";var j=class extends Error{constructor(t,n,o=2,i){super(n,i);this.code=t;this.exitCode=o;this.details=i?.details}details};import{execFile as un,spawnSync as Yt}from"node:child_process";import et from"node:path";function _e(r=process.env){let e=r.SystemRoot??r.SYSTEMROOT;if(!e||!et.win32.isAbsolute(e))throw new Error("Windows SystemRoot 未配置为绝对路径。");return et.win32.join(e,"System32","WindowsPowerShell","v1.0","powershell.exe")}function tt(r){let e=String.raw`
|
|
2
2
|
$ErrorActionPreference = 'Stop'
|
|
3
3
|
$ProgressPreference = 'SilentlyContinue'
|
|
4
4
|
$env:PSModulePath = Join-Path $PSHOME 'Modules'
|
|
@@ -10,7 +10,7 @@ try {
|
|
|
10
10
|
[Console]::Error.WriteLine($_.Exception.ToString())
|
|
11
11
|
exit 1
|
|
12
12
|
}
|
|
13
|
-
`;return["-NoLogo","-NoProfile","-NonInteractive","-OutputFormat","Text","-EncodedCommand",Buffer.from(e,"utf16le").toString("base64")]}var
|
|
13
|
+
`;return["-NoLogo","-NoProfile","-NonInteractive","-OutputFormat","Text","-EncodedCommand",Buffer.from(e,"utf16le").toString("base64")]}var Qt=String.raw`
|
|
14
14
|
$spec = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
15
15
|
try { $item = Get-Item -LiteralPath $spec.path -Force }
|
|
16
16
|
catch [Management.Automation.ItemNotFoundException] { exit 3 }
|
|
@@ -50,6 +50,7 @@ if ($spec.secure) {
|
|
|
50
50
|
foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {
|
|
51
51
|
if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -ne $sid.Value -and $rule.IdentityReference.Value -ne 'S-1-5-18') { throw 'Storage is accessible by another principal' }
|
|
52
52
|
}
|
|
53
|
-
`;function Ae(r,e){let t=Et(xe(),ze(kt),{input:JSON.stringify({path:r,secure:e}),windowsHide:!0,timeout:15e3,encoding:"utf8",maxBuffer:65536});xt(r,t.status,t.error,t.stderr)}function xt(r,e,t,n){if(e===3)throw Object.assign(new Error(`ENOENT: private storage path no longer exists, '${r}'`),{code:"ENOENT",path:r});if(t||e!==0)throw new O("UNSAFE_DATA_DIRECTORY",`Windows 私有存储访问控制校验失败:${t?.message??n.trim()}`,1)}import At from"node:fs";function bt(r,e="/proc"){let t;try{t=At.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 B(r){if(process.platform==="linux"){let e=bt(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 de(r){j.mkdirSync(r,{recursive:!0,mode:448});let e=j.lstatSync(r);if(!e.isDirectory()||e.isSymbolicLink()||process.getuid&&e.uid!==process.getuid())throw new O("UNSAFE_DATA_DIRECTORY","CLI 私有目录的类型或所有者不正确。",1);process.platform==="win32"?Ae(r,!0):j.chmodSync(r,448)}function be(r){let e=Tt("sha256").update(r).digest("hex").slice(0,32),t=K.join(process.platform==="win32"?Be.tmpdir():"/tmp",`aios-cli-${process.getuid?.()??Be.userInfo().username}`);return{lock:K.join(r,"daemon.lock"),mutex:K.join(r,"daemon-owner.sqlite"),metadata:K.join(r,"daemon.json"),socketDirectory:t,socket:process.platform==="win32"?`\\\\.\\pipe\\aios-cli-${e}`:K.join(t,`${e}.sock`)}}function Ct(r){let e=j.lstatSync(r,{throwIfNoEntry:!1});if(e&&(!e.isFile()||e.isSymbolicLink()))throw new O("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1);return e}function Te(r){let e=Ct(r);try{process.platform==="win32"&&e&&Ae(r,!1)}catch(t){if(t.code==="ENOENT")return;throw t}return Rt(r)}function Rt(r){let e;try{e=j.openSync(r,j.constants.O_RDONLY|j.constants.O_NOFOLLOW)}catch(t){let n=t.code;if(n==="ENOENT")return;throw n==="ELOOP"?new O("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1):t}try{let t=j.fstatSync(e);if(!t.isFile()||process.getuid&&t.uid!==process.getuid()||process.platform!=="win32"&&(t.mode&63)!==0)throw new O("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1);try{return JSON.parse(j.readFileSync(e,"utf8"))}catch(n){throw n instanceof SyntaxError?new O("INVALID_DAEMON_METADATA","服务所有权记录损坏,原文件已保留。",1):n}}finally{j.closeSync(e)}}var Ot=1,Jr=8*1024*1024;function Ce(r){if(!r||typeof r!="object")return!1;let e=r;return e.protocol===Ot&&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 He(r){let e=be(r),t=Te(e.metadata);if(!Ce(t)||t.root!==r||t.socket!==e.socket||!B(t.pid))throw new h("CLI_NOT_RUNNING","请先启动指定数据目录的 CLI 后台服务。");if("sdkProtocol"in t)throw new h("RUNTIME_INCOMPATIBLE","该数据目录属于精简运行时,请使用 createClient。");return t}function le(r){let e=be(r),t=Te(e.metadata);if(t!==void 0){if(!Ce(t)||t.root!==r||t.socket!==e.socket||!("sdkProtocol"in t)||t.sdkProtocol!==1)throw new h("RUNTIME_INCOMPATIBLE","本机服务不支持当前 SDK 协议,或其归属记录不一致。");return B(t.pid)?t:void 0}}async function Ve(r,e){for(;;){e.throwIfAborted();let t=le(r);if(t)return t;await jt(100,void 0,{signal:e})}}function ue(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 h("REQUEST_TOO_LARGE","SDK 请求超过 8 MiB。")):new Promise((c,u)=>{let d=l=>u(i?.aborted?i.reason:new h("OUTCOME_UNKNOWN",`请求 ${o} 的结果未知,请使用原命令 ID 查询回执。`,{cause:l})),m=Pt.request({socketPath:r.socket,path:"/sdk",method:"POST",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}},l=>{let y=[],g=0;l.on("data",p=>{g+=p.length,g>16777216?l.destroy(new Error("SDK 响应超过 16 MiB,请分页读取。")):y.push(p)}),l.once("error",d),l.once("end",()=>{try{if(l.statusCode===404)throw new h("SDK_UNSUPPORTED","此 CLI 版本未提供 SDK 接口,请使用包含 SDK 接口的版本。");let p=JSON.parse(Buffer.concat(y).toString("utf8"));if(p.id!==o||typeof p.ok!="boolean")throw new h("INVALID_RESPONSE","SDK 响应与请求不匹配。");if(!p.ok)throw new h(p.error?.code??"RUNTIME_ERROR",p.error?.message??"运行时返回未知错误。");c(p.value)}catch(p){u(p)}})});s>0&&m.setTimeout(s,()=>m.destroy(new Error("SDK 请求等待超时。"))),m.once("error",d),m.end(a)})}import H from"node:path";import{createHash as Nt}from"node:crypto";function Re(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 G(r){let e=r.mode==="platform"?Re(r.platformBaseUrl):null,t=[r.mode,r.appId,r.userScope,e];if(r.mode==="platform"&&r.authentication){let{userId:o,tenantId:i,workspaceId:s}=r.authentication.principal;t.push(JSON.stringify(["managed",o,i,s]))}let n=Nt("sha256").update(JSON.stringify(t)).digest("hex");return H.join(H.resolve(r.runtime.dataDirectory),"applications",n)}function Fe(r){let e=G(r),t=H.basename(e),n=(o,i)=>o?H.join(H.resolve(o),"applications",t,i):H.join(e,i);return{workspaces:n(r.runtime.workspaceDirectory,"workspaces"),cache:n(r.runtime.cacheDirectory,"cache"),temporary:n(r.runtime.temporaryDirectory,"tmp")}}import Oe from"node:path";function qe(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 x(r,e){return Object.assign(new Error(e),{code:r})}function Je(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 Ke(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 x("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=(...I)=>{let $=I.map(k=>s[k]).find(k=>typeof k=="string"&&k.trim());return typeof $=="string"?$:null},c=a("sub"),u=a("tenantId","tenant_id"),d=a("workspaceId","workspace_id")??o.context?.currentWorkspaceId??null;if(c!==e.userId||u!==e.tenantId||d!==e.workspaceId||(o.context?.currentTenantId??null)!==e.tenantId||(o.context?.currentWorkspaceId??null)!==e.workspaceId)throw x("MANAGED_IDENTITY_MISMATCH","托管凭证续期不得改变用户、租户或工作区。");let m=Date.parse(o.accessTokenExpiresAt);if(!Number.isFinite(m)||m<=n||typeof s.exp!="number"||!Number.isFinite(s.exp)||s.exp*1e3<=n)throw x("MANAGED_CREDENTIAL_EXPIRED","应用返回的托管凭证已经过期。");if(typeof o.user.username!="string"||typeof o.user.displayName!="string"||!Array.isArray(o.user.roles)||!o.user.roles.every(I=>typeof I=="string")||!Array.isArray(o.tenants))throw new Error("托管凭证的用户资料格式无效。");let{id:l,username:y,displayName:g,email:p,phone:S,avatarUrl:v,tenantId:f,roles:w}=o.user,_=o.tenants.map(I=>{if(!I||typeof I.id!="string"||typeof I.name!="string"||typeof I.displayName!="string")throw new Error("托管凭证的租户资料格式无效。");return{id:I.id,name:I.name,displayName:I.displayName,status:I.status}});return{credential:{accessToken:r.accessToken,session:{user:{id:l,username:y,displayName:g,email:p,phone:S,avatarUrl:v,tenantId:f,roles:[...w]},tenants:_,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(m,s.exp*1e3),sessionId:a("sessionId","sid")}}function Ge(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 Xe(r,e){return e?.methodTimeoutMs?.[r]??(r==="runtime.drain"?0:e?.rpcTimeoutMs??12e4)}function We(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 Qe(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 X(r){if(!r||!["platform","standalone"].includes(r.mode))throw new Error("必须明确选择 platform 或 standalone 模式。");if(qe({mode:"standalone",appId:r.appId,userScope:r.userScope}),Ge(r.communication),Qe(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(We)}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()||!Oe.isAbsolute(t)))throw new Error(`${e} 必须是绝对目录路径。`)}return{...structuredClone(r),runtime:{...structuredClone(r.runtime),directory:Oe.resolve(r.runtime.directory),dataDirectory:Oe.resolve(r.runtime.dataDirectory)},...r.mode==="platform"?{platformBaseUrl:Re(r.platformBaseUrl),...r.authentication!==void 0?{authentication:Je(r.authentication,r.platformBaseUrl)}:{}}:{}}}import{setTimeout as $t}from"node:timers/promises";import D from"node:fs";import P from"node:path";import{createHash as Ze,verify as Dt}from"node:crypto";var Ye=`-----BEGIN PUBLIC KEY-----
|
|
53
|
+
`;function Le(r,e){let t=Yt(_e(),tt(Qt),{input:JSON.stringify({path:r,secure:e}),windowsHide:!0,timeout:15e3,encoding:"utf8",maxBuffer:65536});Zt(r,t.status,t.error,t.stderr)}function Zt(r,e,t,n){if(e===3)throw Object.assign(new Error(`ENOENT: private storage path no longer exists, '${r}'`),{code:"ENOENT",path:r});if(t||e!==0)throw new j("UNSAFE_DATA_DIRECTORY",`Windows 私有存储访问控制校验失败:${t?.message??n.trim()}`,1)}import er from"node:fs";function tr(r,e="/proc"){let t;try{t=er.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=tr(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 W(r){_.mkdirSync(r,{recursive:!0,mode:448});let e=_.lstatSync(r);if(!e.isDirectory()||e.isSymbolicLink()||process.getuid&&e.uid!==process.getuid())throw new j("UNSAFE_DATA_DIRECTORY","CLI 私有目录的类型或所有者不正确。",1);process.platform==="win32"?Le(r,!0):_.chmodSync(r,448)}function $e(r){let e=rr("sha256").update(r).digest("hex").slice(0,32),t=re.join(process.platform==="win32"?rt.tmpdir():"/tmp",`aios-cli-${process.getuid?.()??rt.userInfo().username}`);return{lock:re.join(r,"daemon.lock"),mutex:re.join(r,"daemon-owner.sqlite"),metadata:re.join(r,"daemon.json"),socketDirectory:t,socket:process.platform==="win32"?`\\\\.\\pipe\\aios-cli-${e}`:re.join(t,`${e}.sock`)}}function nr(r){let e=_.lstatSync(r,{throwIfNoEntry:!1});if(e&&(!e.isFile()||e.isSymbolicLink()))throw new j("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1);return e}function Ue(r){let e=nr(r);try{process.platform==="win32"&&e&&Le(r,!1)}catch(t){if(t.code==="ENOENT")return;throw t}return or(r)}function or(r){let e;try{e=_.openSync(r,_.constants.O_RDONLY|_.constants.O_NOFOLLOW)}catch(t){let n=t.code;if(n==="ENOENT")return;throw n==="ELOOP"?new j("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1):t}try{let t=_.fstatSync(e);if(!t.isFile()||process.getuid&&t.uid!==process.getuid()||process.platform!=="win32"&&(t.mode&63)!==0)throw new j("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1);try{return JSON.parse(_.readFileSync(e,"utf8"))}catch(n){throw n instanceof SyntaxError?new j("INVALID_DAEMON_METADATA","服务所有权记录损坏,原文件已保留。",1):n}}finally{_.closeSync(e)}}var ir=1,Tn=8*1024*1024;function Be(r){if(!r||typeof r!="object")return!1;let e=r;return e.protocol===ir&&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 nt(r){let e=$e(r),t=Ue(e.metadata);if(!Be(t)||t.root!==r||t.socket!==e.socket||!X(t.pid))throw new m("CLI_NOT_RUNNING","请先启动指定数据目录的 CLI 后台服务。");if("sdkProtocol"in t)throw new m("RUNTIME_INCOMPATIBLE","该数据目录属于精简运行时,请使用 createClient。");return t}function we(r){let e=$e(r),t=Ue(e.metadata);if(t!==void 0){if(!Be(t)||t.root!==r||t.socket!==e.socket||!("sdkProtocol"in t)||t.sdkProtocol!==1)throw new m("RUNTIME_INCOMPATIBLE","本机服务不支持当前 SDK 协议,或其归属记录不一致。");return X(t.pid)?t:void 0}}async function ot(r,e){for(;;){e.throwIfAborted();let t=we(r);if(t)return t;await ar(100,void 0,{signal:e})}}function Se(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 m("REQUEST_TOO_LARGE","SDK 请求超过 8 MiB。")):new Promise((c,u)=>{let d=l=>u(i?.aborted?i.reason:new m("OUTCOME_UNKNOWN",`请求 ${o} 的结果未知,请使用原命令 ID 查询回执。`,{cause:l})),p=sr.request({socketPath:r.socket,path:"/sdk",method:"POST",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}},l=>{let h=[],g=0;l.on("data",y=>{g+=y.length,g>16777216?l.destroy(new Error("SDK 响应超过 16 MiB,请分页读取。")):h.push(y)}),l.once("error",d),l.once("end",()=>{try{if(l.statusCode===404)throw new m("SDK_UNSUPPORTED","此 CLI 版本未提供 SDK 接口,请使用包含 SDK 接口的版本。");let y=JSON.parse(Buffer.concat(h).toString("utf8"));if(y.id!==o||typeof y.ok!="boolean")throw new m("INVALID_RESPONSE","SDK 响应与请求不匹配。");if(!y.ok)throw new m(y.error?.code??"RUNTIME_ERROR",y.error?.message??"运行时返回未知错误。");c(y.value)}catch(y){u(y)}})});s>0&&p.setTimeout(s,()=>p.destroy(new Error("SDK 请求等待超时。"))),p.once("error",d),p.end(a)})}import O from"node:path";import ne from"node:fs";import{createHash as pr}from"node:crypto";import v from"node:fs";import M from"node:path";import{createHash as cr,randomUUID as Ee}from"node:crypto";var F=new Map,dr,ke=/^(\d{16})-([a-f0-9]{64})\.json$/,ze=r=>cr("sha256").update(r).digest("hex"),U=r=>`${r}.history`,it=r=>!0;function st(r){if(v.existsSync(r+".bak")||v.existsSync(r+".bak.1"))return!0;try{return v.readdirSync(U(r)).some(e=>ke.test(e))}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Y=class extends Error{constructor(t,n,o=!1,i){let s=n==="missing"?"必要记录缺失":n==="temporarily_unavailable"?"记录暂时无法访问":n==="unsupported_version"?"记录版本不受支持":"记录已损坏";super(`${at(t)}:${s}。请查看存储恢复详情。`);this.file=t;this.problem=n;this.recoveryAvailable=o;this.cause=i,this.name="StorageIntegrityError"}cause};function at(r){return M.basename(r)==="settings.json"?"应用设置":M.basename(r).startsWith("codex-")?"任务执行记录":M.basename(r)}function He(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 Je(r,e){let t;try{t=v.readdirSync(U(r))}catch(o){if(o.code==="ENOENT")t=[];else throw o}let n=[];for(let o of t.sort().reverse()){let i=ke.exec(o);if(!i)continue;let s=M.join(U(r),o),a=He(s,e);if(a.status==="temporarily_unavailable")throw a.error;a.status==="healthy"&&ze(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=He(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 ct(r,e,t,n){let o=M.resolve(r),i=F.get(o),s=new Y(r,e,t).message,a={id:i?.issue.id??Ee(),fileName:at(r),status:e,message:s,detectedAt:i?.issue.detectedAt??new Date().toISOString(),recoveryAvailable:t};F.set(o,{issue:a,file:o,options:n}),(!i||i.issue.status!==e||i.issue.recoveryAvailable!==t)&&dr?.({...a}),F.size>256&&F.delete(F.keys().next().value)}function ve(r,e,t){v.mkdirSync(M.dirname(r),{recursive:!0,mode:448});let n=`${r}.${Ee()}.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 lr(r){let e=M.join(U(r),"damaged");v.mkdirSync(e,{recursive:!0,mode:448});try{v.copyFileSync(r,M.join(e,`${Date.now()}-${Ee()}.bin`),v.constants.COPYFILE_EXCL)}catch(t){if(t.code!=="ENOENT")throw t}}function dt(r,e={}){let t=e.validate??it,n=He(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=Je(r,t)[0];return{...n,backup:o,recoveryAvailable:!!o}}function lt(r,e={}){let t=dt(r,e);if(t.status==="healthy")return F.delete(M.resolve(r)),t.value;if(t.status==="missing"&&!t.recoveryAvailable&&!e.required&&!st(r))return null;ct(r,t.status,t.recoveryAvailable,e);let n=v.existsSync(U(r))?Math.max(0,...v.readdirSync(U(r)).map(o=>Number(ke.exec(o)?.[1]??0))):0;if(e.recover&&"backup"in t&&t.backup&&(e.allowOlderRecovery||t.backup.generation===n))return lr(r),ve(r,t.backup.bytes,!0),F.delete(M.resolve(r)),console.info("[storage-integrity] recovered",{file:r,source:t.backup.file}),t.backup.value;throw new Y(r,t.status,t.recoveryAvailable,t.error)}function ut(r,e,t){let n=Je(r,t),o=ze(e);if(n[0]?.generation&&ze(n[0].bytes)===o)return;v.mkdirSync(U(r),{recursive:!0,mode:448});let i=Math.max(0,...v.readdirSync(U(r)).map(c=>Number(ke.exec(c)?.[1]??0)))+1,s=M.join(U(r),`${String(i).padStart(16,"0")}-${o}.json`),a=`${s}.${Ee()}.pending`;return ve(a,e,!0),{temporary:a,destination:s}}function ur(r,e,t){let n=ut(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 pt(r,e,t={}){let n=t.validate??it;if(!n(e))throw new Y(r,"corrupt",!1,new Error("拒绝写入无效记录。"));let o=dt(r,t);if(o.status!=="healthy"&&!(o.status==="missing"&&!o.recoveryAvailable&&!st(r)))throw ct(r,o.status,o.recoveryAvailable,t),new Y(r,o.status,o.recoveryAvailable,o.error);let i=Buffer.from(`${JSON.stringify(e,null,2)}
|
|
54
|
+
`);t.checkpoint!==!1&&o.status==="healthy"&&ur(r,o.bytes,n);let s=t.checkpoint!==!1?ut(r,i,n):void 0;try{if(t.checkpoint!==!1)for(let a of Je(r,n).slice(2))a.generation>0&&v.unlinkSync(a.file);if(ve(r,i,t.durable!==!1),s)try{v.renameSync(s.temporary,s.destination)}catch(a){try{o.status==="healthy"?ve(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 Fe(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 Ve(r){let e=r.mode==="platform"?Fe(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 pr("sha256").update(JSON.stringify(t)).digest("hex")}function Ie(r){let e=Ve(r),t=O.resolve(r.runtime.dataDirectory),n=O.join(t,"applications",e);if(process.platform!=="win32")return n;let o=O.join(t,"a",e.slice(0,32)),i=ft(t,e);if(i){let s=i.version===1?n:o;if(!ne.statSync(s,{throwIfNoEntry:!1})?.isDirectory())throw new Error("应用运行目录丢失,请恢复原目录,不能创建空目录替代。");if(ne.existsSync(i.version===1?o:n))throw new Error("应用同时存在新旧运行目录,请检查数据完整性。");return s}if(ne.existsSync(n)){if(ne.existsSync(o))throw new Error("应用同时存在新旧运行目录,请检查数据完整性。");return n}if(ne.existsSync(o))throw new Error("应用短目录缺少布局记录,请检查数据完整性。");return o}var mt=(r,e)=>O.join(r,"a",e.slice(0,32)+".json");function ft(r,e){return lt(mt(r,e),{recover:!1,validate:t=>{let n=t;return!!n&&(n.version===1||n.version===2)&&n.identity===e}})}function ht(r){let e=Ie(r);if(W(e),process.platform==="win32"){let t=O.resolve(r.runtime.dataDirectory),n=Ve(r);if(!ft(t,n)){let o=O.basename(O.dirname(e))==="applications"?1:2;pt(mt(t,n),{version:o,identity:n},{validate:i=>{let s=i;return!!s&&s.version===o&&s.identity===n}})}}return e}function gt(r){let e=Ie(r),t=Ve(r);if(process.platform==="win32"){let o=(i,s)=>O.join(O.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?O.join(O.resolve(o),"applications",t,i):O.join(e,i);return{workspaces:n(r.runtime.workspaceDirectory,"workspaces"),cache:n(r.runtime.cacheDirectory,"cache"),temporary:n(r.runtime.temporaryDirectory,"tmp")}}import qe from"node:path";function yt(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 wt(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 St(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=(...k)=>{let q=k.map(b=>s[b]).find(b=>typeof b=="string"&&b.trim());return typeof q=="string"?q:null},c=a("sub"),u=a("tenantId","tenant_id"),d=a("workspaceId","workspace_id")??o.context?.currentWorkspaceId??null;if(c!==e.userId||u!==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(k=>typeof k=="string")||!Array.isArray(o.tenants))throw new Error("托管凭证的用户资料格式无效。");let{id:l,username:h,displayName:g,email:y,phone:I,avatarUrl:S,tenantId:f,roles:w}=o.user,E=o.tenants.map(k=>{if(!k||typeof k.id!="string"||typeof k.name!="string"||typeof k.displayName!="string")throw new Error("托管凭证的租户资料格式无效。");return{id:k.id,name:k.name,displayName:k.displayName,status:k.status}});return{credential:{accessToken:r.accessToken,session:{user:{id:l,username:h,displayName:g,email:y,phone:I,avatarUrl:S,tenantId:f,roles:[...w]},tenants:E,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 vt(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 Et(r,e){return e?.methodTimeoutMs?.[r]??(r==="runtime.drain"?0:e?.rpcTimeoutMs??12e4)}function kt(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 It(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 oe(r){if(!r||!["platform","standalone"].includes(r.mode))throw new Error("必须明确选择 platform 或 standalone 模式。");if(yt({mode:"standalone",appId:r.appId,userScope:r.userScope}),vt(r.communication),It(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(kt)}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()||!qe.isAbsolute(t)))throw new Error(`${e} 必须是绝对目录路径。`)}return{...structuredClone(r),runtime:{...structuredClone(r.runtime),directory:qe.resolve(r.runtime.directory),dataDirectory:qe.resolve(r.runtime.dataDirectory)},...r.mode==="platform"?{platformBaseUrl:Fe(r.platformBaseUrl),...r.authentication!==void 0?{authentication:wt(r.authentication,r.platformBaseUrl)}:{}}:{}}}import{setTimeout as wr}from"node:timers/promises";import J from"node:fs";import D from"node:path";import{createHash as Tt,verify as hr}from"node:crypto";var xt=`-----BEGIN PUBLIC KEY-----
|
|
54
55
|
MCowBQYDK2VwAyEAH1NI5TKlc89zXnULhsNPzgN4M1ki3w5spKY7BH8VsZw=
|
|
55
|
-
-----END PUBLIC KEY-----`;var pe={version:"0.0.2",protocol:1,dataFormat:1,profile:"light"};var M=r=>new h("RUNTIME_INTEGRITY_FAILED",r);function et(r,e){let t=P.relative(r,e);return t!==".."&&!t.startsWith(`..${P.sep}`)&&!P.isAbsolute(t)}async function T(r,e=Ye){let t=D.realpathSync(r),n=P.join(t,"aios-sdk-runtime.json"),o=D.readFileSync(n),i=JSON.parse(o.toString("utf8"));if(i.schemaVersion!==1||i.version!==pe.version||i.protocol!==pe.protocol||i.dataFormat!==pe.dataFormat||i.platform!==process.platform||i.arch!==process.arch||i.profile!=="light")throw new h("RUNTIME_INCOMPATIBLE","精简运行时版本、协议、数据格式、系统或架构不兼容。");let s=JSON.parse(D.readFileSync(P.join(t,"signature.json"),"utf8"));if(s.algorithm!=="ed25519"||typeof s.signature!="string"||s.publicKey?.trim()!==e.trim()||!Dt(null,o,e,Buffer.from(s.signature,"base64")))throw M("运行时清单签名与可信发布公钥不匹配。");if(!i.files||typeof i.files!="object"||Array.isArray(i.files))throw M("运行时缺少文件清单。");let a=i.files,c=["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","resources/runtime/desktop-agent-runtime/index.js",`resources/runtime/codex/${process.platform}-${process.arch}/bin/${process.platform==="win32"?"codex.exe":"codex"}`];for(let p of c)if(!Object.hasOwn(a,p))throw M(`运行时缺少必需资源:${p}`);let u=new Map,d=p=>{for(let S of D.readdirSync(p)){let v=P.join(p,S),f=P.relative(t,v).split(P.sep).join("/");if(["aios-sdk-runtime.json","signature.json"].includes(f))continue;let w=D.lstatSync(v);w.isDirectory()&&!w.isSymbolicLink()?d(v):u.set(f,w)}};if(d(t),u.size!==Object.keys(a).length)throw M("运行时文件数量与清单不一致。");let m=[];for(let[p,S]of Object.entries(a)){let v=P.resolve(t,p),f=u.get(p);if(!p||p.includes("\\")||P.posix.normalize(p)!==p||!et(t,v)||!f)throw M(`运行时文件路径或归属不匹配:${p}`);if(S.type==="link"){if(!f.isSymbolicLink()||typeof S.link!="string"||P.isAbsolute(S.link)||D.readlinkSync(v)!==S.link||!et(t,D.realpathSync(v)))throw M(`运行时链接不匹配:${p}`)}else if(S.type==="file"){if(!f.isFile()||f.isSymbolicLink()||f.size!==S.size||!/^[a-f0-9]{64}$/.test(S.sha256)||process.platform!=="win32"&&(f.mode&73)!==(S.mode&73))throw M(`运行时文件属性不匹配:${p}`);m.push({file:v,name:p,entry:S})}else throw M(`运行时文件类型无效:${p}`)}let l=0,g=(await Promise.allSettled(Array.from({length:Math.min(8,m.length)},async()=>{for(;l<m.length;){let{file:p,name:S,entry:v}=m[l++],f=Ze("sha256");for await(let w of D.createReadStream(p))f.update(w);if(f.digest("hex")!==v.sha256)throw M(`运行时文件摘要不匹配:${S}`)}}))).find(p=>p.status==="rejected");if(g)throw g.reason;return{version:i.version,protocol:i.protocol,dataFormat:i.dataFormat,platform:process.platform,arch:process.arch,profile:"light",manifestSha256:Ze("sha256").update(o).digest("hex")}}import Pe from"node:fs";import tt from"node:path";import{spawn as _t}from"node:child_process";function me(r){let{options:e}=r,t=G(e);de(t);let n=Fe(e).temporary;Pe.mkdirSync(n,{recursive:!0});let o=Pe.openSync(tt.join(t,"sdk-host.log"),"a",384),i=(()=>{try{return _t(e.runtime.nodeExecutable??process.execPath,[tt.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{Pe.closeSync(o)}})(),s=new Promise(c=>{i.once("exit",(u,d)=>c({code:u,signal:d})),i.once("error",()=>{i.pid||c({code:null,signal:null})})}),a=new Promise((c,u)=>{let d=setTimeout(()=>y(new h("RUNTIME_START_TIMEOUT","SDK 服务未在指定时间内完成启动,请检查宿主日志。")),e.communication?.startupTimeoutMs??12e4),m=(g,p)=>y(new h("RUNTIME_START_FAILED",`SDK 服务启动进程退出(${g??p})。`)),l=g=>{if(!g||g.type!=="ready"){y(new h("RUNTIME_INCOMPATIBLE","宿主未返回当前 SDK 启动协议,请使用配套运行包。"));return}g.ok?y(void 0,g.value):y(new h(g.error.code,g.error.message))};function y(g,p){clearTimeout(d),i.removeListener("error",y),i.removeListener("exit",m),i.removeListener("message",l),g?u(g):c(p)}i.once("error",y),i.once("exit",m),i.on("message",l),i.send(r,g=>{g&&y(g)})});return{child:i,ready:a,exited:s}}var W=class r{constructor(e,t,n){this.metadata=e;this.ownerExit=t;this.communication=n}eventWaitMs=0;closed=!1;clientId=rt();static async start(e,t){let n=X(e),o=Lt.resolve(n.runtime.directory),i=await T(o,n.runtime.trustedPublicKey),s=G(n),a=le(s);if(!a){let{child:c,ready:u}=me({options:n,verifiedPackage:i});try{a=await u}catch(d){if(!(d instanceof h)||d.code!=="DAEMON_ALREADY_OWNED")throw d;a=await Ve(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 h("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=rt(),o){return this.closed?Promise.reject(new h("RUNTIME_CLOSED","SDK 客户端连接已关闭。")):this.ownerExit?.aborted?Promise.reject(this.ownerExit.reason):ue(this.metadata,this.clientId,e,t,n,o,Xe(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(;le(this.metadata.root)?.instanceId===this.metadata.instanceId||B(this.metadata.pid);)await $t(100,void 0,{signal:e})}};import Ut from"node:path";import{randomUUID as nt}from"node:crypto";var fe=class r{constructor(e){this.metadata=e}closed=!1;clientId=nt();static async connect(e){let t=new r(He(Ut.resolve(e.dataDirectory)));return await t.call("attach",{sdkProtocol:1,options:e,pid:process.pid}),t}call(e,t={},n=nt(),o){return this.closed?Promise.reject(new h("RUNTIME_CLOSED","SDK 客户端连接已关闭。")):ue(this.metadata,this.clientId,e,t,n,o)}async stop(){this.closed||(await this.call("detach"),this.closed=!0)}async shutdown(){throw new h("SHARED_RUNTIME","连接已有 CLI 时,请通过 CLI 管理后台服务。")}};import Ht from"node:http";import{randomBytes as Vt,randomUUID as Ft,timingSafeEqual as qt}from"node:crypto";import{Ajv as Jt}from"ajv";import{Ajv2020 as Kt}from"ajv/dist/2020.js";function zt(r){let e={...r,kind:"aios-tool-result"};return je(e),e}function V(r,e){if(typeof r!="string"||!r.trim())throw new Error(`工具返回的 ${e} 必须是非空字符串。`)}function je(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 V(n.data,"image.data"),V(n.mimeType,"image.mimeType"),{type:"image",data:n.data,mimeType:n.mimeType};if(n.type==="resource"){let o=n.resource;V(o?.uri,"resource.uri"),new URL(o.uri),o.mimeType!==void 0&&V(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&&(V(e.error.code,"error.code"),V(e.error.message,"error.message"),t.push({type:"text",text:JSON.stringify({error:e.error})})),{content:t,isError:e.error!==void 0}}var ot=["projectId","collaborationProjectId","assistantId","platformSessionId","platformTurnId","platformTaskId","platformRunId","traceId"];function Q(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("执行上下文必须为对象。");return r}function L(r){if(typeof r!="string"||!r.trim()||r.length>512||/[\x00-\x1f\x7f]/.test(r))throw new Error("执行上下文字段必须为有效字符串,最多 512 字符。");return r}function it(r){let e=Q(r);if(Object.keys(e).some(t=>!["userId","tenantId","name"].includes(t)))throw new Error("执行主体包含未知字段。");return{userId:L(e.userId),tenantId:e.tenantId===null?null:L(e.tenantId),...e.name===void 0?{}:{name:L(e.name)}}}function Bt(r){let e=Q(r);if(Object.keys(e).some(n=>!["actor","owner","workspaceId","usageScene","metadata",...ot].includes(n)))throw new Error("执行上下文包含未知字段。");if(!["personal","greeting","task","collaboration","coding"].includes(String(e.usageScene)))throw new Error("执行用量场景无效。");let t={actor:it(e.actor),owner:it(e.owner),workspaceId:e.workspaceId===null?null:L(e.workspaceId),usageScene:e.usageScene};for(let n of ot)e[n]!==void 0&&(t[n]=L(e[n]));if(e.metadata!==void 0){let n=Q(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=Q(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 he(r){let e=Q(r);if(Object.keys(e).some(t=>!["sessionId","runId","context"].includes(t)))throw new Error("执行绑定包含未知字段。");return{sessionId:L(e.sessionId),runId:L(e.runId),...e.context===void 0?{}:{context:Bt(e.context)}}}async function st(r,e,t){let n=new Map,o=new Jt({strict:!0,strictTypes:!1,allErrors:!0,validateFormats:!1}),i=new Kt({strict:!0,strictTypes:!1,allErrors:!0,validateFormats:!1}),s=new Map;for(let f of e){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(f.name)||n.has(f.name))throw new Error(`业务工具名称无效或重复:${f.name}`);if(f.inputSchema.type!=="object")throw new Error(`业务工具 ${f.name} 的输入 schema 必须为 object。`);n.set(f.name,f);let w=f.inputSchema.$schema==="http://json-schema.org/draft-07/schema#"?o:i;s.set(f.name,w.compile(f.inputSchema))}let a=Vt(32).toString("hex"),c=new Map,u=new Set,d=!1,m,l,y=new Promise(f=>{l=f}),g=()=>m??=(async()=>{for(let f of c.values())f.abort(new Error("应用工具提供者已关闭。"));S.closeAllConnections(),await new Promise((f,w)=>S.close(_=>_?w(_):f())),l()})(),p=()=>{d&&u.size===0&&c.size===0&&g()},S=Ht.createServer(async(f,w)=>{let _=Buffer.from(`Bearer ${a}`),Ee=Buffer.from(f.headers.authorization??"");if(Ee.length!==_.length||!qt(Ee,_)){w.writeHead(401).end();return}if(f.url!=="/mcp"){w.writeHead(404).end();return}let I=f.headers["mcp-session-id"];if(f.method==="DELETE"&&typeof I=="string"&&u.delete(I)){for(let[R,U]of c)R.startsWith(`${I}:`)&&U.abort(new Error("工具会话已关闭。"));w.writeHead(204).end(),p();return}if(f.method!=="POST"){w.writeHead(405).end();return}let $=null,k=(R,U=!1)=>{let b=JSON.stringify({jsonrpc:"2.0",id:$,...U?{error:R}:{result:R}});w.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),w.end(b)};try{let R=0,U=[];for await(let E of f){let z=Buffer.from(E);if(R+=z.length,R>8*1024*1024)throw new Error("业务工具请求超过 8 MiB。");U.push(z)}let b=JSON.parse(Buffer.concat(U).toString("utf8"));if($=b.id??null,b.method==="initialize"){if(d){k({code:-32e3,message:"应用工具提供者已注销。"},!0);return}let E=Ft();u.add(E),w.setHeader("mcp-session-id",E),k({protocolVersion:"2025-03-26",capabilities:{tools:{listChanged:!1}},serverInfo:{name:r,version:"1"}});return}if(typeof I!="string"||!u.has(I)){w.writeHead(404).end();return}if(b.method==="notifications/cancelled"){c.get(`${I}:${String(b.params?.requestId)}`)?.abort(new Error("工具调用已取消。")),w.writeHead(202).end();return}if(b.id===void 0){w.writeHead(202).end();return}if(b.method==="ping"){k({});return}if(b.method==="tools/list"){k({tools:e.map(E=>({name:E.name,description:E.description,inputSchema:E.inputSchema,annotations:{readOnlyHint:E.readOnly,destructiveHint:!E.readOnly,openWorldHint:!0}}))});return}if(b.method!=="tools/call"){k({code:-32601,message:"不支持的 MCP 方法。"},!0);return}let se=n.get(String(b.params?.name));if(!se)throw new Error("业务工具不存在。");let F=b.params?.arguments;if(!F||typeof F!="object"||Array.isArray(F))throw new Error("工具参数必须是对象。");let Le=s.get(se.name);if(!Le(F)){k({content:[{type:"text",text:`工具参数不符合声明:${JSON.stringify(Le.errors)}`}],isError:!0});return}let q=new AbortController,ae=`${I}:${String($)}`;if(c.has(ae))throw new Error("工具请求 ID 正在执行,不能重复提交。");c.set(ae,q);let $e=()=>{w.writableEnded||q.abort(new Error("工具请求连接已关闭。"))};w.once("close",$e);let J="validation";try{let z=b.params?._meta?.["aios/execution"],{invocationId:ke,...wt}=z??{},ce=z===void 0?void 0:he(wt);if(z&&(typeof ke!="string"||!ke))throw new Error("工具调用标识缺失。");J="execution";let St=await se.execute(F,{signal:q.signal,callId:ae,...ce&&t?{files:{resolve:(It,vt)=>t(ce.sessionId,It,vt,q.signal)}}:{},...ce?{execution:at({...ce,invocationId:ke})}:{}});J="serialization",q.signal.throwIfAborted(),k(je(St))}catch(E){k({content:[{type:"text",text:JSON.stringify({error:{message:(E instanceof Error?E.message:String(E)).slice(0,4096),capability:se.name,phase:J,side_effects:J==="validation"?"not_started":J==="serialization"?"completed":"unknown",next_action:"先核对实际结果,不要因工具返回失败而直接重复执行。"}})}],isError:!0})}finally{w.removeListener("close",$e),c.delete(ae),p()}}catch(R){k({code:-32602,message:R instanceof Error?R.message:String(R)},!0)}});return await new Promise((f,w)=>{S.once("error",w),S.listen(0,"127.0.0.1",f)}),{descriptor:{id:r,name:r,transport:"HTTP",url:`http://127.0.0.1:${S.address().port}/mcp`,bearerToken:a,tools:e.map(f=>f.name),defaultToolsApproval:"prompt",toolApprovals:Object.fromEntries(e.map(f=>[f.name,f.readOnly?"auto":"prompt"]))},close:g,closed:y,status:()=>({retired:d,sessions:u.size,calls:c.size,closing:!!m}),retire:()=>{d=!0,p()}}}function at(r){return r&&typeof r=="object"&&(Object.values(r).forEach(at),Object.freeze(r)),r}import{createHash as Qt}from"node:crypto";var Gt=/^[a-z][a-z0-9_]{0,63}$/u;function Xt(r){return r.trim().toLowerCase()}function Ne(r){let e=Xt(r);if(!Gt.test(e))throw new Error("MCP 技能引用标识只能包含小写字母、数字和下划线,必须以字母开头,最长 64 个字符");return e}function Wt(r){return`aios_mcp_${Ne(r)}`}function ct(r,e){let t=e.trim();if(!t)throw new Error("MCP 工具名称不能为空");return`mcp__${Wt(r)}__${t}`}function ge(r){return r.toolProviderId===void 0?`app_${Qt("sha256").update(JSON.stringify([r.id,r.version])).digest("hex").slice(0,32)}`:Ne(r.toolProviderId)}function Me(r,e){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(e))throw new Error("业务工具名称无效。");return ct(ge(r),e)}import{randomUUID as Yt}from"node:crypto";function De(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=Yt(),s){let a=performance.now(),c={name:"sdk.rpc",method:n,requestId:i},u=t(()=>e.startSpan?.("sdk.rpc",{method:n,requestId:i}));t(()=>e.log?.(Object.freeze({...c,phase:"started"})));let d="completed",m;try{return await r.call(n,o,i,s)}catch(l){throw d="failed",m=l&&typeof l=="object"&&"code"in l&&typeof l.code=="string"&&/^[A-Z0-9_]{1,80}$/.test(l.code)?l.code:"RPC_ERROR",l}finally{let l=performance.now()-a,y=Object.freeze({...c,phase:d,durationMs:l,...m?{errorCode:m}:{}});t(()=>e.log?.(y)),t(()=>e.metric?.("sdk.rpc.duration_ms",l,{method:n,outcome:d})),t(()=>u?.end(y))}}}}async function ye(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 we=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 u=await s.call("read",{transferId:i.id,offset:a},o);if(u.bytes<=0)throw new Error("导出数据意外结束。");a+=u.bytes,yield Buffer.from(u.data,"base64")}})();return ye(async()=>{let u=await t.put({...n,source:c,sha256:i.sha256,bytes:i.bytes});if(o?.throwIfAborted(),a!==i.bytes||!u.version||u.key!==n.key)throw new Error("存储适配器未完整接收文件或未返回正确版本。");return{stored:u,file:i.file,sha256:i.sha256,bytes:i.bytes}},()=>ye(()=>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 ye(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 m=d.value;for(let l=0;l<m.byteLength;l+=a.chunkBytes){o?.throwIfAborted();let y=Buffer.from(m.subarray(l,l+a.chunkBytes));c=(await this.call("write",{transferId:a.id,offset:c,data:y.toString("base64")},o)).offset}}return o?.throwIfAborted(),{file:await this.call("commit",{transferId:a.id},o),source:e}},()=>ye(async()=>s.return?.(),async()=>{a&&await this.call("close",{transferId:a.id})}))}};import Zt from"node:http";import{randomBytes as er,timingSafeEqual as tr}from"node:crypto";async function dt(r){let e=er(32).toString("hex"),t=new Set,n=Zt.createServer(async(i,s)=>{let a=Buffer.from(`Bearer ${e}`),c=Buffer.from(i.headers.authorization??"");if(c.length!==a.length||!tr(c,a)){s.writeHead(401).end();return}if(i.method!=="POST"||i.url!=="/callbacks"){s.writeHead(404).end();return}let u=new AbortController;t.add(u),s.once("close",()=>{s.writableFinished||u.abort(new Error("应用回调请求已断开。"))});try{let d=[],m=0;for await(let S of i){let v=Buffer.from(S);if(m+=v.length,m>64*1024*1024)throw new Error("应用回调请求超过 64 MiB。");d.push(v)}let l=JSON.parse(Buffer.concat(d).toString("utf8")),y=r.get(l.method);if(!y)throw Object.assign(new Error("应用回调不存在。"),{code:"APPLICATION_PROVIDER_OFFLINE"});let g=await y(l.params,u.signal);u.signal.throwIfAborted();let p=JSON.stringify({ok:!0,value:g});s.writeHead(200,{"content-type":"application/json"}).end(p)}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(u)}});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 lt(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 ut(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 dr from"node:http";import{randomBytes as lr,timingSafeEqual as ur}from"node:crypto";var rr="[REDACTED]",nr="(?:密码|口令|密钥|令牌|私钥|凭据|验证码)",or=new RegExp(`(${nr}\\s*["']?\\s*(?:[::=]|是(?!否)|为)\\s*)(?:"([^"]*)"|'([^']*)'|“([^”]*)”|‘([^’]*)’|([^\\s"'“”‘’,。;,;}]+))`,"gu");var ir=["authorization","password","passwd","passphrase","token","api[-_]?key","secret","cookie","credentials?","private[-_]?key","pat"].join("|"),pt=`(?:[a-z0-9]+[-_])*(?:${ir})`,sr=new RegExp(`(\\b${pt}\\b["']?\\s*[:=]\\s*["']?)([^\\s"',};&,。;]+)`,"gi"),ar=new RegExp(`([?&]${pt}=)([^&#\\s]*)`,"gi");function mt(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(ar,"$1[REDACTED]").replace(sr,"$1[REDACTED]").replace(or,(e,t,n,o,i,s)=>{let a=n!==void 0?['"','"']:o!==void 0?["'","'"]:i!==void 0?["“","”"]:s!==void 0?["‘","’"]:["",""];return`${t}${a[0]}${rr}${a[1]}`})}import{randomUUID as cr}from"node:crypto";var Se=class{id=cr();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 x("AUTH_EVENT_CURSOR_INVALID","授权事件游标不属于当前凭证提供者。")}for(;;){e.signal?.throwIfAborted();let n=this.sequence-this.records.length;if(t<n)throw x("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",u)},c=()=>{a(),i()},u=()=>{a(),s(e.signal.reason)};this.listeners.add(c),e.signal?.addEventListener("abort",u,{once:!0})})}}};var Ie=class{constructor(e,t,n){this.authentication=e;this.platformBaseUrl=t;this.provider=n}events=new Se;entries=new Map;sequence=0;epoch=0;revoked=!1;closed=!1;expiration;execution(e){if(e===void 0)return;let t=he(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 x("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(x("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 x("MANAGED_PROVIDER_UNAVAILABLE","凭证提供者已关闭。");if(this.revoked&&e!=="explicit")throw x("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 u=this.epoch;s.reason=c;let d=this.load(s,c,u);s.pending=d;try{await d}finally{s.pending===d&&(s.pending=void 0),this.trim()}}}if(!s.cached||s.controller.signal.aborted)throw x("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 x("MANAGED_AUTHORIZATION_CHANGED","解析凭证期间授权已改变。");if(o===null)throw this.revoke(),x("MANAGED_AUTHORIZATION_REVOKED","应用未提供有效授权。");e.cached=Ke(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 ft(r,e,t){let n=lr(32).toString("hex"),o=new Ie(r,e,t),i=dr.createServer(async(s,a)=>{let c=Buffer.from(`Bearer ${n}`),u=Buffer.from(s.headers.authorization??"");if(c.length!==u.length||!ur(c,u)){a.writeHead(401).end();return}if(s.method!=="POST"||s.url!=="/credentials"){a.writeHead(404).end();return}try{let d=0,m=[];for await(let g of s){let p=Buffer.from(g);if(d+=p.length,d>64*1024)throw new Error("凭证请求过大。");m.push(p)}let l=JSON.parse(Buffer.concat(m).toString("utf8"));if(l.generation!==void 0&&(!Number.isSafeInteger(l.generation)||l.generation<1))throw new Error("凭证版本无效。");let y;if(l.revoke===!0)y={revoked:o.revoke(l.execution,l.generation)};else{if(!["initial","expiring","rejected","explicit"].includes(String(l.reason)))throw new Error("凭证解析原因无效。");if(l.reason==="rejected"&&l.generation===void 0)throw new Error("被拒凭证版本无效。");y=await o.resolve(l.reason,l.execution,l.generation)}a.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),a.end(JSON.stringify(y))}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:mt(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 pr}from"node:crypto";import{setTimeout as ht}from"node:timers/promises";var Y=class{constructor(e,t){this.connection=e;this.authorizationEvents=t}managedEvents(e={}){let t=this.authorizationEvents?.();if(!t)throw new h("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??pr()});return new Z(t,n.id)}resumeBrowserLogin(e){return new Z(this.connection(),e)}},Z=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 h("LOGIN_ALREADY_COMPLETED","网页登录已完成,请读取登录结果。");await ht(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 ht(250,void 0,e)}}checkFailure(e){if(e.state==="failed")throw new h(e.error.code,e.error.message);if(e.state==="cancelled")throw new h("LOGIN_CANCELLED","网页登录已取消。")}};var ee=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 N from"node:fs";import C from"node:path";import{createHash as mr}from"node:crypto";import{createRequire as fr}from"node:module";import{t as hr,x as gr}from"tar";var yr=fr(import.meta.url),wr=["win32-x64","darwin-x64","darwin-arm64","linux-x64","linux-arm64"];function Sr(r=`${process.platform}-${process.arch}`){if(!wr.includes(r))throw new h("RUNTIME_UNSUPPORTED",`尚未提供 ${r} 的精简运行时。`);let e=`@kmlckj/aios-runtime-${r}`;try{return C.dirname(yr.resolve(`${e}/package.json`))}catch(t){throw t.code!=="MODULE_NOT_FOUND"?t:new h("RUNTIME_PACKAGE_MISSING",`缺少 ${e}。请安装对应版本的运行时包,不要使用 --omit=optional;也可显式指定 runtime.directory。`)}}async function Ir(r){let e=mr("sha256");for await(let t of N.createReadStream(r))e.update(t);return e.digest("hex")}async function vr(r,e){let t=new Set,n,o=i=>{if(!i||i.includes("\\")||i.includes("\0")||C.posix.isAbsolute(i)||/^[A-Za-z]:/.test(i)||i.split("/").includes(".."))throw new Error(`运行时归档路径无效:${i}`)};if(await hr({file:r,strict:!0,onReadEntry(i){try{o(i.path);let s=C.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(C.posix.isAbsolute(i.linkpath)||i.linkpath.includes("\\")||/^[A-Za-z]:/.test(i.linkpath))throw new Error(`运行时归档链接越界:${s}`);o(i.type==="SymbolicLink"?C.posix.join(C.posix.dirname(s),i.linkpath):i.linkpath)}}catch(s){n??=s}}}),n)throw n;await gr({file:r,cwd:e,strict:!0,preservePaths:!1})}async function te(r,e){if(r.runtime?.directory!==void 0)return X(r);let t=e??Sr(),n=JSON.parse(N.readFileSync(C.join(t,"package.json"),"utf8")),o=JSON.parse(N.readFileSync(new URL("../package.json",import.meta.url),"utf8")),i=JSON.parse(N.readFileSync(C.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 h("RUNTIME_INCOMPATIBLE","npm 运行时包的版本、平台或归档清单与 SDK 不一致。");if(!r.runtime||typeof r.runtime.dataDirectory!="string"||!r.runtime.dataDirectory.trim())throw new Error("运行时数据目录不能为空。");let a=C.resolve(r.runtime.dataDirectory,"runtimes"),c=C.join(a,`${s}-${i.archive.sha256}`),u=X({...r,runtime:{...r.runtime,directory:c}});if(N.existsSync(c))return await T(c,u.runtime.trustedPublicKey),u;let d=C.join(t,i.archive.file);if(N.statSync(d).size!==i.archive.size||await Ir(d)!==i.archive.sha256)throw new h("RUNTIME_INTEGRITY_FAILED","npm 运行时归档内容与清单不一致。");de(a);let m=N.mkdtempSync(C.join(a,".unpack-"));try{await vr(d,m),await T(m,u.runtime.trustedPublicKey);try{N.renameSync(m,c)}catch(l){if(!N.existsSync(c))throw l;await T(c,u.runtime.trustedPublicKey)}return u}finally{N.rmSync(m,{recursive:!0,force:!0})}}import{randomUUID as Er}from"node:crypto";function gt(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 re=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 h("RUNTIME_EXITED","SDK 宿主进程已退出。")),this.onError(new h("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=gt({...t.shutdown}),i=await te(e),s=await T(i.runtime.directory,i.runtime.trustedPublicKey),{child:a,ready:c,exited:u}=me({options:i,verifiedPackage:s,managed:{shutdown:o}});try{let d=await c;return new r(i,d,s,a,u,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 h("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 h("RUNTIME_EXITED","受管宿主连接已结束,请读取 wait 的退出结果。"));let e=Er();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 h("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 h(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 h("HOST_DISCONNECTED","宿主控制通道已断开,请读取 wait 的退出结果。"))};function yt(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 oe=class r{constructor(e,t,n,o={}){this.transport=e;this.options=t;this.mode=n;this.services=o;this.transport=De(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 h("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 dt(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){yt(e,t);let o=e.mode==="platform"&&e.authentication&&t.credentials?await ft(e.authentication,e.platformBaseUrl,t.credentials):void 0;try{return{transport:n?await W.attach(e,n.metadata,n.verified,o?.connection,n.exitSignal):await W.start(e,o?.connection),provider:o}}catch(i){throw await o?.close(),i}}static async create(e,t={}){let n=await te(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 re.start(e,t,async(n,o,i,s,a)=>{let{transport:c,provider:u}=await r.start(n,s,{metadata:o,verified:i,exitSignal:a}),d=new r(c,n,n.mode,s);d.credentialProvider=u;try{await d.startCallbacks()}catch(m){throw await d.close(),m}return d})}static async connectCli(e){return new r(await fe.connect(e),e,"platform")}auth=new Y(()=>this.transport,()=>this.credentialProvider?.events);platform=new ee(()=>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 te({...this.options,...e});yt(t,this.services),await T(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=De(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=ge(e),a=[],c=new Map;for(let[l,y]of Object.entries(o??{})){if(!["beforeTool","afterTool"].includes(l)||!y||typeof y.execute!="function")throw new Error("JS Hook 必须提供执行函数。");let g=l==="beforeTool"?"PreToolUse":"PostToolUse",p=`hook.${s}.${g}`;a.push({event:g,callback:p,timeoutMs:y.timeoutMs??3e4,...y.matcher?{matcher:y.matcher}:{}}),c.set(p,this.callbackHandlers.get(p))}o&&(i.jsHookDefinitions=lt(a));let u=JSON.stringify([e.id,e.version]),d=this.activeToolProviders.get(s);if(d&&d.agent!==u)throw new Error("应用工具提供者 ID 已被其他智能体使用。");let m=t?.length?await st(s,t,(l,y,g,p)=>this.transport.call("session.file.resolve",{id:l,path:y,access:g},void 0,p)):void 0;m&&this.toolProviders.add(m);try{for(let[g,p]of Object.entries(o??{})){let S=g==="beforeTool"?"PreToolUse":"PostToolUse";this.callbackHandlers.set(`hook.${s}.${S}`,async(v,f)=>{let w=await p.execute(Object.freeze(v),{signal:f});return ut(S,w),w})}o&&await this.startCallbacks();let l=[...i.mcpServers??[],...m?[m.descriptor]:[]];await this.transport.call("agent.define",{...i,mcpServers:l,...m?{applicationToolProviderId:s}:{}}),d?.provider?.retire();let y={agent:u,provider:m};return this.activeToolProviders.set(s,y),m&&m.closed.then(()=>{this.toolProviders.delete(m)}),new ve(this.transport,e.id,e.version,m,t?.map(g=>({name:g.name,reference:Me(e,g.name)})),()=>{if(this.activeToolProviders.get(s)!==y)throw new Error("此工具提供者已被新注册替换,请使用当前 Agent 句柄。")})}catch(l){for(let[y,g]of c)g?this.callbackHandlers.set(y,g):this.callbackHandlers.delete(y);throw m&&(this.toolProviders.delete(m),await m.close()),l}}async openSession(e){return new ie(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 ve(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}}}},ve=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 ie(this.transport,await this.transport.call("session.create",{agentId:this.id,agentVersion:this.version,...e,creationId:e.creationId??A()}))}async adoptSession(e,t={}){return new ie(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()}},ie=class r{constructor(e,t){this.transport=e;this.info=t;this.id=t.id,this.files=new we(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??A(),o=await this.transport.call("session.send",{id:this.id,content:e,options:{...t,commandId:n}});return new ne(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??A()}})}queue(){return this.transport.call("session.queue",{id:this.id})}editQueued(e,t,n,o=A()){return this.transport.call("session.queue.edit",{id:this.id,pendingMessageId:e,content:t,queueVersion:n,commandId:o})}removeQueued(e,t,n=A()){return this.transport.call("session.queue.delete",{id:this.id,pendingMessageId:e,queueVersion:t.queueVersion,targetRunId:t.activeRunId,commandId:n})}reorderQueue(e,t,n=A()){return this.transport.call("session.queue.reorder",{id:this.id,pendingMessageIds:e,queueVersion:t,commandId:n})}dispatchQueued(e,t,n,o=A()){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 _e(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=A()){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 ne(this.transport,this.id,e)}async compact(e=A()){let t=await this.transport.call("session.compact",{id:this.id,commandId:e});return new ne(this.transport,this.id,t.runId,e)}},ne=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=A()){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=A()){return this.transport.call("run.approve",{taskId:this.taskId,runId:this.id,toolCallId:e,decision:t,commandId:n})}answer(e,t,n=A()){return this.transport.call("run.answer",{taskId:this.taskId,runId:this.id,requestId:e,response:t,commandId:n})}cancelInput(e,t=A()){return this.transport.call("run.cancelInput",{taskId:this.taskId,runId:this.id,requestId:e,commandId:t})}async confirmPlan(e=A()){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 _e(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 _e(150,void 0,{signal:e.signal})}}},Si=oe.create,Ii=oe.connectCli,vi=oe.startManaged;export{ve as Agent,oe as AiosClient,h as AiosSdkError,Y as AuthApi,Z as BrowserLogin,re as ManagedHost,ee as PlatformApi,ne as Run,ie as Session,ge as applicationToolProviderId,Me as applicationToolReference,Ii as connectCli,Si as createClient,vi as startManagedHost,zt as toolResult,T as validateRuntime};
|
|
56
|
+
-----END PUBLIC KEY-----`;var xe={version:"0.0.5",protocol:1,dataFormat:1,profile:"light"};import be from"node:fs";import z from"node:path";import{createHash as fr}from"node:crypto";var B=r=>new m("RUNTIME_INTEGRITY_FAILED",r);function bt(r,e){if(!e||e.includes("\\")||z.posix.normalize(e)!==e||z.posix.isAbsolute(e)||e===".."||e.startsWith("../"))throw B(`共享运行资源路径无效:${e}`);let t=z.resolve(r,e),n=z.relative(r,be.realpathSync(t));if(n===".."||n.startsWith(`..${z.sep}`)||z.isAbsolute(n))throw B(`共享运行资源越界:${e}`);return t}async function At(r,e){if(!e||typeof e!="object"||Array.isArray(e))throw B("缺少共享运行资源清单。");let t=e;if(t.root!=="../.."||typeof t.codex!="string"||!t.files||typeof t.files!="object"||Array.isArray(t.files))throw B("共享运行资源清单无效。");let n=be.realpathSync(z.resolve(r,t.root));if(z.relative(n,r).split(z.sep).join("/")!=="runtime/sdk-host")throw B("共享宿主不在产品运行资源目录中。");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 B(`共享运行资源缺少必需文件:${i}`);for(let[i,s]of Object.entries(o)){if(!s||typeof s!="object"||Array.isArray(s))throw B(`共享运行资源属性无效:${i}`);let a=s,c=bt(n,i),u=be.lstatSync(c);if(a.type!=="file"||!u.isFile()||u.isSymbolicLink()||u.size!==a.size||typeof a.sha256!="string"||!/^[a-f0-9]{64}$/.test(a.sha256))throw B(`共享运行资源属性不匹配:${i}`);let d=fr("sha256");for await(let p of be.createReadStream(c))d.update(p);if(d.digest("hex")!==a.sha256)throw B(`共享运行资源摘要不匹配:${i}`)}return{root:n,codexExecutable:bt(n,t.codex)}}var H=r=>new m("RUNTIME_INTEGRITY_FAILED",r);function Ct(r,e){let t=D.relative(r,e);return t!==".."&&!t.startsWith(`..${D.sep}`)&&!D.isAbsolute(t)}async function R(r,e=xt,t={platform:process.platform,arch:process.arch}){let n=J.realpathSync(r),o=D.join(n,"aios-sdk-runtime.json"),i=J.readFileSync(o),s=JSON.parse(i.toString("utf8"));if(s.schemaVersion!==1||s.version!==xe.version||s.protocol!==xe.protocol||s.dataFormat!==xe.dataFormat||s.platform!==t.platform||s.arch!==t.arch||!["light","product"].includes(String(s.profile)))throw new m("RUNTIME_INCOMPATIBLE","精简运行时版本、协议、数据格式、系统或架构不兼容。");let a=JSON.parse(J.readFileSync(D.join(n,"signature.json"),"utf8"));if(a.algorithm!=="ed25519"||typeof a.signature!="string"||a.publicKey?.trim()!==e.trim()||!hr(null,i,e,Buffer.from(a.signature,"base64")))throw H("运行时清单签名与可信发布公钥不匹配。");if(!s.files||typeof s.files!="object"||Array.isArray(s.files))throw H("运行时缺少文件清单。");let c=s.files,u=["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 u)if(!Object.hasOwn(c,S))throw H(`运行时缺少必需资源:${S}`);let d=new Map,p=S=>{for(let f of J.readdirSync(S)){let w=D.join(S,f),E=D.relative(n,w).split(D.sep).join("/");if(["aios-sdk-runtime.json","signature.json"].includes(E))continue;let $=J.lstatSync(w);$.isDirectory()&&!$.isSymbolicLink()?p(w):d.set(E,$)}};if(p(n),d.size!==Object.keys(c).length)throw H("运行时文件数量与清单不一致。");let l=[];for(let[S,f]of Object.entries(c)){let w=D.resolve(n,S),E=d.get(S);if(!S||S.includes("\\")||D.posix.normalize(S)!==S||!Ct(n,w)||!E)throw H(`运行时文件路径或归属不匹配:${S}`);if(f.type==="link"){if(!E.isSymbolicLink()||typeof f.link!="string"||D.isAbsolute(f.link)||J.readlinkSync(w)!==f.link||!Ct(n,J.realpathSync(w)))throw H(`运行时链接不匹配:${S}`)}else if(f.type==="file"){if(!E.isFile()||E.isSymbolicLink()||E.size!==f.size||!/^[a-f0-9]{64}$/.test(f.sha256)||t.platform!=="win32"&&(E.mode&73)!==(f.mode&73))throw H(`运行时文件属性不匹配:${S}`);l.push({file:w,name:S,entry:f})}else throw H(`运行时文件类型无效:${S}`)}let h=0,y=(await Promise.allSettled(Array.from({length:Math.min(8,l.length)},async()=>{for(;h<l.length;){let{file:S,name:f,entry:w}=l[h++],E=Tt("sha256");for await(let $ of J.createReadStream(S))E.update($);if(E.digest("hex")!==w.sha256)throw H(`运行时文件摘要不匹配:${f}`)}}))).find(S=>S.status==="rejected");if(y)throw y.reason;let I=s.profile==="product"?await At(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:Tt("sha256").update(i).digest("hex"),...I?{productResources:I}:{}}}import Ot from"node:fs";import Rt from"node:path";import{spawn as gr}from"node:child_process";function Ae(r){let{options:e}=r,t=ht(e),n=gt(e).temporary;W(n);let o=Ot.openSync(Rt.join(t,"sdk-host.log"),"a",384),i=(()=>{try{return gr(e.runtime.nodeExecutable??process.execPath,[Rt.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{Ot.closeSync(o)}})(),s=new Promise(c=>{i.once("exit",(u,d)=>c({code:u,signal:d})),i.once("error",()=>{i.pid||c({code:null,signal:null})})}),a=new Promise((c,u)=>{let d=setTimeout(()=>h(new m("RUNTIME_START_TIMEOUT","SDK 服务未在指定时间内完成启动,请检查宿主日志。")),e.communication?.startupTimeoutMs??12e4),p=(g,y)=>h(new m("RUNTIME_START_FAILED",`SDK 服务启动进程退出(${g??y})。`)),l=g=>{if(!g||g.type!=="ready"){h(new m("RUNTIME_INCOMPATIBLE","宿主未返回当前 SDK 启动协议,请使用配套运行包。"));return}g.ok?h(void 0,g.value):h(new m(g.error.code,g.error.message))};function h(g,y){clearTimeout(d),i.removeListener("error",h),i.removeListener("exit",p),i.removeListener("message",l),g?u(g):c(y)}i.once("error",h),i.once("exit",p),i.on("message",l),i.send(r,g=>{g&&h(g)})});return{child:i,ready:a,exited:s}}var ie=class r{constructor(e,t,n){this.metadata=e;this.ownerExit=t;this.communication=n}eventWaitMs=0;closed=!1;clientId=Nt();static async start(e,t){let n=oe(e),o=yr.resolve(n.runtime.directory),i=await R(o,n.runtime.trustedPublicKey),s=Ie(n),a=we(s);if(!a){let{child:c,ready:u}=Ae({options:n,verifiedPackage:i});try{a=await u}catch(d){if(!(d instanceof m)||d.code!=="DAEMON_ALREADY_OWNED")throw d;a=await ot(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 m("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=Nt(),o){return this.closed?Promise.reject(new m("RUNTIME_CLOSED","SDK 客户端连接已关闭。")):this.ownerExit?.aborted?Promise.reject(this.ownerExit.reason):Se(this.metadata,this.clientId,e,t,n,o,Et(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(;we(this.metadata.root)?.instanceId===this.metadata.instanceId||X(this.metadata.pid);)await wr(100,void 0,{signal:e})}};import Sr from"node:path";import{randomUUID as Pt}from"node:crypto";var Te=class r{constructor(e){this.metadata=e}closed=!1;clientId=Pt();static async connect(e){let t=new r(nt(Sr.resolve(e.dataDirectory)));return await t.call("attach",{sdkProtocol:1,options:e,pid:process.pid}),t}call(e,t={},n=Pt(),o){return this.closed?Promise.reject(new m("RUNTIME_CLOSED","SDK 客户端连接已关闭。")):Se(this.metadata,this.clientId,e,t,n,o)}async stop(){this.closed||(await this.call("detach"),this.closed=!0)}async shutdown(){throw new m("SHARED_RUNTIME","连接已有 CLI 时,请通过 CLI 管理后台服务。")}};import kr from"node:http";import{randomBytes as Ir,randomUUID as xr,timingSafeEqual as br}from"node:crypto";import{Ajv as Ar}from"ajv";import{Ajv2020 as Tr}from"ajv/dist/2020.js";function vr(r){let e={...r,kind:"aios-tool-result"};return Ke(e),e}function Q(r,e){if(typeof r!="string"||!r.trim())throw new Error(`工具返回的 ${e} 必须是非空字符串。`)}function Ke(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 Q(n.data,"image.data"),Q(n.mimeType,"image.mimeType"),{type:"image",data:n.data,mimeType:n.mimeType};if(n.type==="resource"){let o=n.resource;Q(o?.uri,"resource.uri"),new URL(o.uri),o.mimeType!==void 0&&Q(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&&(Q(e.error.code,"error.code"),Q(e.error.message,"error.message"),t.push({type:"text",text:JSON.stringify({error:e.error})})),{content:t,isError:e.error!==void 0}}var jt=["projectId","collaborationProjectId","assistantId","platformSessionId","platformTurnId","platformTaskId","platformRunId","traceId"];function se(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("执行上下文必须为对象。");return r}function V(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=se(r);if(Object.keys(e).some(t=>!["userId","tenantId","name"].includes(t)))throw new Error("执行主体包含未知字段。");return{userId:V(e.userId),tenantId:e.tenantId===null?null:V(e.tenantId),...e.name===void 0?{}:{name:V(e.name)}}}function Er(r){let e=se(r);if(Object.keys(e).some(n=>!["actor","owner","workspaceId","usageScene","metadata",...jt].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:V(e.workspaceId),usageScene:e.usageScene};for(let n of jt)e[n]!==void 0&&(t[n]=V(e[n]));if(e.metadata!==void 0){let n=se(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=se(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=se(r);if(Object.keys(e).some(t=>!["sessionId","runId","context"].includes(t)))throw new Error("执行绑定包含未知字段。");return{sessionId:V(e.sessionId),runId:V(e.runId),...e.context===void 0?{}:{context:Er(e.context)}}}async function Dt(r,e,t){let n=new Map,o=new Ar({strict:!0,strictTypes:!1,allErrors:!0,validateFormats:!1}),i=new Tr({strict:!0,strictTypes:!1,allErrors:!0,validateFormats:!1}),s=new Map;for(let f of e){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(f.name)||n.has(f.name))throw new Error(`业务工具名称无效或重复:${f.name}`);if(f.inputSchema.type!=="object")throw new Error(`业务工具 ${f.name} 的输入 schema 必须为 object。`);n.set(f.name,f);let w=f.inputSchema.$schema==="http://json-schema.org/draft-07/schema#"?o:i;s.set(f.name,w.compile(f.inputSchema))}let a=Ir(32).toString("hex"),c=new Map,u=new Set,d=!1,p,l,h=new Promise(f=>{l=f}),g=()=>p??=(async()=>{for(let f of c.values())f.abort(new Error("应用工具提供者已关闭。"));I.closeAllConnections(),await new Promise((f,w)=>I.close(E=>E?w(E):f())),l()})(),y=()=>{d&&u.size===0&&c.size===0&&g()},I=kr.createServer(async(f,w)=>{let E=Buffer.from(`Bearer ${a}`),$=Buffer.from(f.headers.authorization??"");if($.length!==E.length||!br($,E)){w.writeHead(401).end();return}if(f.url!=="/mcp"){w.writeHead(404).end();return}let k=f.headers["mcp-session-id"];if(f.method==="DELETE"&&typeof k=="string"&&u.delete(k)){for(let[P,K]of c)P.startsWith(`${k}:`)&&K.abort(new Error("工具会话已关闭。"));w.writeHead(204).end(),y();return}if(f.method!=="POST"){w.writeHead(405).end();return}let q=null,b=(P,K=!1)=>{let C=JSON.stringify({jsonrpc:"2.0",id:q,...K?{error:P}:{result:P}});w.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),w.end(C)};try{let P=0,K=[];for await(let x of f){let G=Buffer.from(x);if(P+=G.length,P>8*1024*1024)throw new Error("业务工具请求超过 8 MiB。");K.push(G)}let C=JSON.parse(Buffer.concat(K).toString("utf8"));if(q=C.id??null,C.method==="initialize"){if(d){b({code:-32e3,message:"应用工具提供者已注销。"},!0);return}let x=xr();u.add(x),w.setHeader("mcp-session-id",x),b({protocolVersion:"2025-03-26",capabilities:{tools:{listChanged:!1}},serverInfo:{name:r,version:"1"}});return}if(typeof k!="string"||!u.has(k)){w.writeHead(404).end();return}if(C.method==="notifications/cancelled"){c.get(`${k}:${String(C.params?.requestId)}`)?.abort(new Error("工具调用已取消。")),w.writeHead(202).end();return}if(C.id===void 0){w.writeHead(202).end();return}if(C.method==="ping"){b({});return}if(C.method==="tools/list"){b({tools:e.map(x=>({name:x.name,description:x.description,inputSchema:x.inputSchema,annotations:{readOnlyHint:x.readOnly,destructiveHint:!x.readOnly,openWorldHint:!0}}))});return}if(C.method!=="tools/call"){b({code:-32601,message:"不支持的 MCP 方法。"},!0);return}let he=n.get(String(C.params?.name));if(!he)throw new Error("业务工具不存在。");let Z=C.params?.arguments;if(!Z||typeof Z!="object"||Array.isArray(Z))throw new Error("工具参数必须是对象。");let Qe=s.get(he.name);if(!Qe(Z)){b({content:[{type:"text",text:`工具参数不符合声明:${JSON.stringify(Qe.errors)}`}],isError:!0});return}let ee=new AbortController,ge=`${k}:${String(q)}`;if(c.has(ge))throw new Error("工具请求 ID 正在执行,不能重复提交。");c.set(ge,ee);let Ze=()=>{w.writableEnded||ee.abort(new Error("工具请求连接已关闭。"))};w.once("close",Ze);let te="validation";try{let G=C.params?._meta?.["aios/execution"],{invocationId:De,...Kt}=G??{},ye=G===void 0?void 0:Ce(Kt);if(G&&(typeof De!="string"||!De))throw new Error("工具调用标识缺失。");te="execution";let Gt=await he.execute(Z,{signal:ee.signal,callId:ge,...ye&&t?{files:{resolve:(Xt,Wt)=>t(ye.sessionId,Xt,Wt,ee.signal)}}:{},...ye?{execution:_t({...ye,invocationId:De})}:{}});te="serialization",ee.signal.throwIfAborted(),b(Ke(Gt))}catch(x){b({content:[{type:"text",text:JSON.stringify({error:{message:(x instanceof Error?x.message:String(x)).slice(0,4096),capability:he.name,phase:te,side_effects:te==="validation"?"not_started":te==="serialization"?"completed":"unknown",next_action:"先核对实际结果,不要因工具返回失败而直接重复执行。"}})}],isError:!0})}finally{w.removeListener("close",Ze),c.delete(ge),y()}}catch(P){b({code:-32602,message:P instanceof Error?P.message:String(P)},!0)}});return await new Promise((f,w)=>{I.once("error",w),I.listen(0,"127.0.0.1",f)}),{descriptor:{id:r,name:r,transport:"HTTP",url:`http://127.0.0.1:${I.address().port}/mcp`,bearerToken:a,tools:e.map(f=>f.name),defaultToolsApproval:"prompt",toolApprovals:Object.fromEntries(e.map(f=>[f.name,f.readOnly?"auto":"prompt"]))},close:g,closed:h,status:()=>({retired:d,sessions:u.size,calls:c.size,closing:!!p}),retire:()=>{d=!0,y()}}}function _t(r){return r&&typeof r=="object"&&(Object.values(r).forEach(_t),Object.freeze(r)),r}import{createHash as Nr}from"node:crypto";var Cr=/^[a-z][a-z0-9_]{0,63}$/u;function Or(r){return r.trim().toLowerCase()}function Ge(r){let e=Or(r);if(!Cr.test(e))throw new Error("MCP 技能引用标识只能包含小写字母、数字和下划线,必须以字母开头,最长 64 个字符");return e}function Rr(r){return`aios_mcp_${Ge(r)}`}function Lt(r,e){let t=e.trim();if(!t)throw new Error("MCP 工具名称不能为空");return`mcp__${Rr(r)}__${t}`}function Oe(r){return r.toolProviderId===void 0?`app_${Nr("sha256").update(JSON.stringify([r.id,r.version])).digest("hex").slice(0,32)}`:Ge(r.toolProviderId)}function Xe(r,e){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(e))throw new Error("业务工具名称无效。");return Lt(Oe(r),e)}import{randomUUID as Pr}from"node:crypto";function We(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=Pr(),s){let a=performance.now(),c={name:"sdk.rpc",method:n,requestId:i},u=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(l){throw d="failed",p=l&&typeof l=="object"&&"code"in l&&typeof l.code=="string"&&/^[A-Z0-9_]{1,80}$/.test(l.code)?l.code:"RPC_ERROR",l}finally{let l=performance.now()-a,h=Object.freeze({...c,phase:d,durationMs:l,...p?{errorCode:p}:{}});t(()=>e.log?.(h)),t(()=>e.metric?.("sdk.rpc.duration_ms",l,{method:n,outcome:d})),t(()=>u?.end(h))}}}}async function Re(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 Ne=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 u=await s.call("read",{transferId:i.id,offset:a},o);if(u.bytes<=0)throw new Error("导出数据意外结束。");a+=u.bytes,yield Buffer.from(u.data,"base64")}})();return Re(async()=>{let u=await t.put({...n,source:c,sha256:i.sha256,bytes:i.bytes});if(o?.throwIfAborted(),a!==i.bytes||!u.version||u.key!==n.key)throw new Error("存储适配器未完整接收文件或未返回正确版本。");return{stored:u,file:i.file,sha256:i.sha256,bytes:i.bytes}},()=>Re(()=>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 Re(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 l=0;l<p.byteLength;l+=a.chunkBytes){o?.throwIfAborted();let h=Buffer.from(p.subarray(l,l+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}},()=>Re(async()=>s.return?.(),async()=>{a&&await this.call("close",{transferId:a.id})}))}};import jr from"node:http";import{randomBytes as Mr,timingSafeEqual as Dr}from"node:crypto";async function $t(r){let e=Mr(32).toString("hex"),t=new Set,n=jr.createServer(async(i,s)=>{let a=Buffer.from(`Bearer ${e}`),c=Buffer.from(i.headers.authorization??"");if(c.length!==a.length||!Dr(c,a)){s.writeHead(401).end();return}if(i.method!=="POST"||i.url!=="/callbacks"){s.writeHead(404).end();return}let u=new AbortController;t.add(u),s.once("close",()=>{s.writableFinished||u.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 l=JSON.parse(Buffer.concat(d).toString("utf8")),h=r.get(l.method);if(!h)throw Object.assign(new Error("应用回调不存在。"),{code:"APPLICATION_PROVIDER_OFFLINE"});let g=await h(l.params,u.signal);u.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(u)}});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 Ut(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 Bt(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 Jr from"node:http";import{randomBytes as Fr,timingSafeEqual as Vr}from"node:crypto";var _r="[REDACTED]",Lr="(?:密码|口令|密钥|令牌|私钥|凭据|验证码)",$r=new RegExp(`(${Lr}\\s*["']?\\s*(?:[::=]|是(?!否)|为)\\s*)(?:"([^"]*)"|'([^']*)'|“([^”]*)”|‘([^’]*)’|([^\\s"'“”‘’,。;,;}]+))`,"gu");var Ur=["authorization","password","passwd","passphrase","token","api[-_]?key","secret","cookie","credentials?","private[-_]?key","pat"].join("|"),zt=`(?:[a-z0-9]+[-_])*(?:${Ur})`,Br=new RegExp(`(\\b${zt}\\b["']?\\s*[:=]\\s*["']?)([^\\s"',};&,。;]+)`,"gi"),zr=new RegExp(`([?&]${zt}=)([^&#\\s]*)`,"gi");function Ht(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(zr,"$1[REDACTED]").replace(Br,"$1[REDACTED]").replace($r,(e,t,n,o,i,s)=>{let a=n!==void 0?['"','"']:o!==void 0?["'","'"]:i!==void 0?["“","”"]:s!==void 0?["‘","’"]:["",""];return`${t}${a[0]}${_r}${a[1]}`})}import{randomUUID as Hr}from"node:crypto";var Pe=class{id=Hr();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",u)},c=()=>{a(),i()},u=()=>{a(),s(e.signal.reason)};this.listeners.add(c),e.signal?.addEventListener("abort",u,{once:!0})})}}};var je=class{constructor(e,t,n){this.authentication=e;this.platformBaseUrl=t;this.provider=n}events=new Pe;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 u=this.epoch;s.reason=c;let d=this.load(s,c,u);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=St(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 Jt(r,e,t){let n=Fr(32).toString("hex"),o=new je(r,e,t),i=Jr.createServer(async(s,a)=>{let c=Buffer.from(`Bearer ${n}`),u=Buffer.from(s.headers.authorization??"");if(c.length!==u.length||!Vr(c,u)){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 l=JSON.parse(Buffer.concat(p).toString("utf8"));if(l.generation!==void 0&&(!Number.isSafeInteger(l.generation)||l.generation<1))throw new Error("凭证版本无效。");let h;if(l.revoke===!0)h={revoked:o.revoke(l.execution,l.generation)};else{if(!["initial","expiring","rejected","explicit"].includes(String(l.reason)))throw new Error("凭证解析原因无效。");if(l.reason==="rejected"&&l.generation===void 0)throw new Error("被拒凭证版本无效。");h=await o.resolve(l.reason,l.execution,l.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:Ht(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 qr}from"node:crypto";import{setTimeout as Ft}from"node:timers/promises";var ae=class{constructor(e,t){this.connection=e;this.authorizationEvents=t}managedEvents(e={}){let t=this.authorizationEvents?.();if(!t)throw new m("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??qr()});return new ce(t,n.id)}resumeBrowserLogin(e){return new ce(this.connection(),e)}},ce=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 m("LOGIN_ALREADY_COMPLETED","网页登录已完成,请读取登录结果。");await Ft(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 Ft(250,void 0,e)}}checkFailure(e){if(e.state==="failed")throw new m(e.error.code,e.error.message);if(e.state==="cancelled")throw new m("LOGIN_CANCELLED","网页登录已取消。")}};var de=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 L from"node:fs";import N from"node:path";import{createHash as Kr}from"node:crypto";import{createRequire as Gr}from"node:module";import{t as Xr,x as Wr}from"tar";var Yr=Gr(import.meta.url),Qr=["win32-x64","darwin-x64","darwin-arm64","linux-x64","linux-arm64"];function Zr(r=`${process.platform}-${process.arch}`){if(!Qr.includes(r))throw new m("RUNTIME_UNSUPPORTED",`尚未提供 ${r} 的精简运行时。`);let e=`@kmlckj/aios-runtime-${r}`;try{return N.dirname(Yr.resolve(`${e}/package.json`))}catch(t){throw t.code!=="MODULE_NOT_FOUND"?t:new m("RUNTIME_PACKAGE_MISSING",`缺少 ${e}。请安装对应版本的运行时包,不要使用 --omit=optional;也可显式指定 runtime.directory。`)}}async function en(r){let e=Kr("sha256");for await(let t of L.createReadStream(r))e.update(t);return e.digest("hex")}async function tn(r,e){let t=new Set,n,o=i=>{if(!i||i.includes("\\")||i.includes("\0")||N.posix.isAbsolute(i)||/^[A-Za-z]:/.test(i)||i.split("/").includes(".."))throw new Error(`运行时归档路径无效:${i}`)};if(await Xr({file:r,strict:!0,onReadEntry(i){try{o(i.path);let s=N.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(N.posix.isAbsolute(i.linkpath)||i.linkpath.includes("\\")||/^[A-Za-z]:/.test(i.linkpath))throw new Error(`运行时归档链接越界:${s}`);o(i.type==="SymbolicLink"?N.posix.join(N.posix.dirname(s),i.linkpath):i.linkpath)}}catch(s){n??=s}}}),n)throw n;await Wr({file:r,cwd:e,strict:!0,preservePaths:!1})}async function le(r,e){if(r.runtime?.directory!==void 0)return oe(r);let t=e??Zr(),n=JSON.parse(L.readFileSync(N.join(t,"package.json"),"utf8")),o=JSON.parse(L.readFileSync(new URL("../package.json",import.meta.url),"utf8")),i=JSON.parse(L.readFileSync(N.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 m("RUNTIME_INCOMPATIBLE","npm 运行时包的版本、平台或归档清单与 SDK 不一致。");if(!r.runtime||typeof r.runtime.dataDirectory!="string"||!r.runtime.dataDirectory.trim())throw new Error("运行时数据目录不能为空。");let a=N.resolve(r.runtime.dataDirectory,"runtimes"),c=N.join(a,`${s}-${i.archive.sha256}`),u=oe({...r,runtime:{...r.runtime,directory:c}});if(L.existsSync(c))return await R(c,u.runtime.trustedPublicKey),u;let d=N.join(t,i.archive.file);if(L.statSync(d).size!==i.archive.size||await en(d)!==i.archive.sha256)throw new m("RUNTIME_INTEGRITY_FAILED","npm 运行时归档内容与清单不一致。");W(a);let p=L.mkdtempSync(N.join(a,".unpack-"));try{await tn(d,p),await R(p,u.runtime.trustedPublicKey);try{L.renameSync(p,c)}catch(l){if(!L.existsSync(c))throw l;await R(c,u.runtime.trustedPublicKey)}return u}finally{L.rmSync(p,{recursive:!0,force:!0})}}import{randomUUID as rn}from"node:crypto";function Vt(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 ue=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 m("RUNTIME_EXITED","SDK 宿主进程已退出。")),this.onError(new m("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=Vt({...t.shutdown}),i=await le(e),s=await R(i.runtime.directory,i.runtime.trustedPublicKey),{child:a,ready:c,exited:u}=Ae({options:i,verifiedPackage:s,managed:{shutdown:o}});try{let d=await c;return new r(i,d,s,a,u,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 m("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 m("RUNTIME_EXITED","受管宿主连接已结束,请读取 wait 的退出结果。"));let e=rn();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 m("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 m(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 m("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 me=class r{constructor(e,t,n,o={}){this.transport=e;this.options=t;this.mode=n;this.services=o;this.transport=We(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 m("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 Jt(e.authentication,e.platformBaseUrl,t.credentials):void 0;try{return{transport:n?await ie.attach(e,n.metadata,n.verified,o?.connection,n.exitSignal):await ie.start(e,o?.connection),provider:o}}catch(i){throw await o?.close(),i}}static async create(e,t={}){let n=await le(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 ue.start(e,t,async(n,o,i,s,a)=>{let{transport:c,provider:u}=await r.start(n,s,{metadata:o,verified:i,exitSignal:a}),d=new r(c,n,n.mode,s);d.credentialProvider=u;try{await d.startCallbacks()}catch(p){throw await d.close(),p}return d})}static async connectCli(e){return new r(await Te.connect(e),e,"platform")}auth=new ae(()=>this.transport,()=>this.credentialProvider?.events);platform=new de(()=>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 le({...this.options,...e});qt(t,this.services),await R(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=We(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=Oe(e),a=[],c=new Map;for(let[l,h]of Object.entries(o??{})){if(!["beforeTool","afterTool"].includes(l)||!h||typeof h.execute!="function")throw new Error("JS Hook 必须提供执行函数。");let g=l==="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=Ut(a));let u=JSON.stringify([e.id,e.version]),d=this.activeToolProviders.get(s);if(d&&d.agent!==u)throw new Error("应用工具提供者 ID 已被其他智能体使用。");let p=t?.length?await Dt(s,t,(l,h,g,y)=>this.transport.call("session.file.resolve",{id:l,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,f)=>{let w=await y.execute(Object.freeze(S),{signal:f});return Bt(I,w),w})}o&&await this.startCallbacks();let l=[...i.mcpServers??[],...p?[p.descriptor]:[]];await this.transport.call("agent.define",{...i,mcpServers:l,...p?{applicationToolProviderId:s}:{}}),d?.provider?.retire();let h={agent:u,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:Xe(e,g.name)})),()=>{if(this.activeToolProviders.get(s)!==h)throw new Error("此工具提供者已被新注册替换,请使用当前 Agent 句柄。")})}catch(l){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()),l}}async openSession(e){return new fe(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 fe(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 fe(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()}},fe=class r{constructor(e,t){this.transport=e;this.info=t;this.id=t.id,this.files=new Ne(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 pe(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 Ye(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 pe(this.transport,this.id,e)}async compact(e=T()){let t=await this.transport.call("session.compact",{id:this.id,commandId:e});return new pe(this.transport,this.id,t.runId,e)}},pe=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 Ye(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 Ye(150,void 0,{signal:e.signal})}}},ps=me.create,ms=me.connectCli,fs=me.startManaged;export{Me as Agent,me as AiosClient,m as AiosSdkError,ae as AuthApi,ce as BrowserLogin,ue as ManagedHost,de as PlatformApi,pe as Run,fe as Session,Oe as applicationToolProviderId,Xe as applicationToolReference,ms as connectCli,ps as createClient,fs as startManagedHost,vr as toolResult,R as validateRuntime};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export interface ProductRuntimeResources {
|
|
2
|
+
root: string;
|
|
3
|
+
codexExecutable: string;
|
|
4
|
+
}
|
|
5
|
+
/** References are covered by the same signed manifest as the small SDK host. */
|
|
6
|
+
export declare function validateProductResources(directory: string, value: unknown): Promise<ProductRuntimeResources>;
|
|
@@ -1,10 +1,12 @@
|
|
|
1
|
+
import { type ProductRuntimeResources } from './product-resources.js';
|
|
1
2
|
export interface VerifiedRuntime {
|
|
2
3
|
version: string;
|
|
3
4
|
protocol: number;
|
|
4
5
|
dataFormat: number;
|
|
5
6
|
platform: NodeJS.Platform;
|
|
6
7
|
arch: string;
|
|
7
|
-
profile: 'light';
|
|
8
|
+
profile: 'light' | 'product';
|
|
8
9
|
manifestSha256: string;
|
|
10
|
+
productResources?: ProductRuntimeResources;
|
|
9
11
|
}
|
|
10
|
-
export declare function validateSdkRuntimeDirectory(directory: string, trustedPublicKey?: string): Promise<VerifiedRuntime>;
|
|
12
|
+
export declare function validateSdkRuntimeDirectory(directory: string, trustedPublicKey?: string, expectedTarget?: Pick<VerifiedRuntime, 'platform' | 'arch'>): Promise<VerifiedRuntime>;
|
package/dist/sdk/src/types.d.ts
CHANGED
|
@@ -273,6 +273,7 @@ export interface ClientConfiguration {
|
|
|
273
273
|
contextDirectory: string;
|
|
274
274
|
resourcesDirectory: string;
|
|
275
275
|
tasksDirectory: string;
|
|
276
|
+
legacyTasksDirectory?: string;
|
|
276
277
|
workspacesDirectory: string;
|
|
277
278
|
temporaryDirectory: string;
|
|
278
279
|
cacheDirectory: string;
|
|
@@ -32,6 +32,8 @@ export interface LocalTask {
|
|
|
32
32
|
memoryScope?: import('./local-memory.js').MemoryScope;
|
|
33
33
|
/** Absent on pre-integrity task records. Original journal formats are unchanged. */
|
|
34
34
|
storageVersion?: 1;
|
|
35
|
+
/** Absent means the original directory. New tasks use the compact repository root. */
|
|
36
|
+
pathLayoutVersion?: 2;
|
|
35
37
|
/** Immutable command entry selected when the task was created; absent means the original native shell entry. */
|
|
36
38
|
commandEntryVersion?: 2;
|
|
37
39
|
/** Read-only projection; never saved back as execution state. */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kmlckj/aios-agent-server-sdk",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.5",
|
|
4
4
|
"description": "AIOS agent application SDK for Node.js",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -15,11 +15,11 @@
|
|
|
15
15
|
"tar": "7.5.22"
|
|
16
16
|
},
|
|
17
17
|
"optionalDependencies": {
|
|
18
|
-
"@kmlckj/aios-runtime-win32-x64": "0.0.
|
|
19
|
-
"@kmlckj/aios-runtime-darwin-x64": "0.0.
|
|
20
|
-
"@kmlckj/aios-runtime-darwin-arm64": "0.0.
|
|
21
|
-
"@kmlckj/aios-runtime-linux-x64": "0.0.
|
|
22
|
-
"@kmlckj/aios-runtime-linux-arm64": "0.0.
|
|
18
|
+
"@kmlckj/aios-runtime-win32-x64": "0.0.5",
|
|
19
|
+
"@kmlckj/aios-runtime-darwin-x64": "0.0.5",
|
|
20
|
+
"@kmlckj/aios-runtime-darwin-arm64": "0.0.5",
|
|
21
|
+
"@kmlckj/aios-runtime-linux-x64": "0.0.5",
|
|
22
|
+
"@kmlckj/aios-runtime-linux-arm64": "0.0.5"
|
|
23
23
|
},
|
|
24
24
|
"exports": {
|
|
25
25
|
".": {
|