@kmlckj/aios-agent-server-sdk 0.0.2 → 0.0.6

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.2
1
+ # AIOS Agent Server SDK 0.0.6
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;运行时系统/架构须与宿主一致。
@@ -75,6 +77,8 @@ await client.close();
75
77
 
76
78
  `auth.getToken()` 和 `auth.refresh()` 是显式获取凭据接口,调用方应妥善处理结果。普通配置、用户和资源查询不返回模型密钥。默认凭据仅在会话内保存;需要持久登录时选择 `credentialStore: { kind: 'system' }`,或使用带解锁口令的 `vault`。
77
79
 
80
+ 重启宿主后先恢复登录或重新绑定托管凭据,再调用 `openSession()`、`resumeRun()` 续接原会话;会话历史持久化不会把内存中的登录凭据一并保存。
81
+
78
82
  平台地址必须是 HTTP(S) 基地址,可包含端口,不能包含认证信息、业务路径、查询或片段。切换平台要在空闲且仅当前客户端连接时调用 `setPlatformBaseUrl()`,重新登录并注册智能体;不同平台历史和凭据隔离。
79
83
 
80
84
  ## 应用托管平台身份
@@ -159,9 +163,9 @@ CLI 必须运行支持 SDK 协议及能力选择的构建;旧版本没有 `/sd
159
163
 
160
164
  长工具结果由共享运行时保存,模型收到预览与 `next` 续读引用。外部 MCP 和应用回调同样适用,读取已有结果不会再次执行回调。结构化 MCP 输出在代理侧明确声明“原结果或归档引用”两种形式;完整业务数据可从归档读取,图片等非文本块保持原类型。
161
165
 
162
- 续读使用 `aios_tool_results.read_tool_output`,参数为本任务的 `output_id` 与字节 `offset`。它是已启用工具的结果交付服务,只能读取本任务产生的托管结果,不接受任意文件路径;关闭内置文件工具不会启用 `read_file`。没有任何 AIOS 工具或外部提供者时,不启动该服务。
166
+ 动态工具、文档摘要和命令日志统一通过 `next` 返回 `server/tool/output_id/offset`,续读使用 `aios_tool_results.read_tool_output`,参数为本任务的 `output_id` 与字节 `offset`。不再向模型返回内部归档文件路径,改变 cwd 不影响续读。它是已启用工具的结果交付服务,只能读取本任务产生的托管结果,不接受任意文件路径;关闭内置文件工具不会启用 `read_file`。没有任何 AIOS 工具或外部提供者时,不启动该服务。
163
167
 
164
- 单份文本结果、每路命令日志的保存上限为 64 MiB。命令日志保留退出状态和独立的完整性标记;容量不足、磁盘错误或内容已清理都会明确返回,不自动重跑原操作。结果保存在工作目录的 `.aios/tool-output/<任务范围>/` 下,随该目录管理;不会在任务刚结束时删除,以便历史任务继续读取。
168
+ 单份文本结果、每路命令日志的保存上限为 64 MiB。命令日志保留退出状态和独立的完整性标记;容量不足、磁盘错误或内容已清理都会明确返回,不自动重跑原操作。归档由宿主管理,保存于工作区根目录的 `.aios/tool-output/<任务范围>/`,独立于任务 cwd;不会在任务刚结束时删除,以便历史任务继续读取。旧版归档位置及已有 `output_id/offset` 引用保持可读,历史事件中的旧路径字段仍可解析为续读引用。
165
169
 
166
170
  ```js
167
171
  const catalog = await client.capabilities({ kind: 'tool', category: 'documents' });
@@ -197,6 +201,8 @@ const run = await session.send('使用 document_workflow 将工作目录中的
197
201
 
198
202
  业务工具通过 `AgentDefinition.tools` 注册,提供 `name`、`description`、JSON Schema `inputSchema`、`readOnly` 和 `execute(input, { signal, callId })`。使用现有 MCP、权限、审批和取消链。默认权限下只读工具自动执行,写工具等待审批;完全权限遵循现有本地规则。回调函数及凭据不写入任务历史。
199
203
 
204
+ 显式 `mcpServers[].id` 的工具引用使用小写标识,只支持以字母开头的字母、数字和下划线,最长 64 个字符。注册时验证格式并拒绝大小写归一后的冲突;原始服务 ID 保留。
205
+
200
206
  普通字符串和 JSON 返回值仍作为文本交给模型。需要图片、文件内容或明确的业务错误时,使用公开的 `toolResult()`:
201
207
 
202
208
  ```ts
@@ -226,7 +232,7 @@ return toolResult({
226
232
  - `session.configuration(revision?)` / `configure(defaults, expectedRevision?)`:读取当前或已保存版本,修改会话默认值;上下文/思考等级可用 `null` 重置。
227
233
  - `session.configureBuiltins(selection, expectedRevision?)`:调整该会话内置能力。配置冲突返回 `CONFIGURATION_CONFLICT`;目标会话有运行、待处理交互或排队消息时返回 `SESSION_BUSY`。
228
234
  - `session.history()` / `artifacts()` / `compact()`:历史、产物及上下文压缩。
229
- - `session.enqueue()`、`queue()`、`editQueued()`、`removeQueued()`、`reorderQueue()`:排队管理,写操作携带读取到的 `queueVersion`,过期版本明确拒绝。
235
+ - `session.enqueue()`、`queue()`、`editQueued()`、`removeQueued()`、`reorderQueue()`:排队管理,写操作携带读取到的 `queueVersion`,过期版本明确拒绝。活动轮正常完成后自动派发下一条;空闲时入队由应用显式派发。原入队命令的 `receipt(commandId)` 可查询派发后的实际 `runId`,不要把入队消息 ID 当作已启动的执行 ID。
230
236
  - `dispatchQueued(messageId, queueVersion, targetRunId)`:传活动 runId 作为本轮补充指令;传 `null` 开始新轮。所有操作复用持久命令回执。
231
237
  - `run.events({ cursor, signal })`:增量事件;处理完一条后可保存其 `cursor`,下次从该位置恢复。用事件 `id` 去重;`sequence` 是该游标流内的顺序号,`runtimeSequence`(若存在)保留运行时原始序号。事件还包含 `schemaVersion: 1`、`sessionId`、`runId`。
232
238
  - `session.events({ cursor, signal })` / `eventPage()`:跨轮观察整个会话,保留一轮结束后才到达的积分等更新。事件保留工具详情、子线程/团队标识和可信业务 `context`,不会在一轮完成时关闭。详见 [事件与前端接入](EVENTS.md)。浏览器入口 `@kmlckj/aios-agent-server-sdk/events` 提供同源工具短句辅助函数及事件类型。
@@ -360,6 +366,8 @@ for (const reference of await run.operations()) {
360
366
 
361
367
  `runtime.dataDirectory` 保存宿主状态;可分别设置 `workspaceDirectory`、`cacheDirectory`、`temporaryDirectory` 三个绝对目录基址。每个基址仍按应用和主体分区,`getConfiguration().paths` 返回实际目录。新自动任务使用配置的工作区;已有任务继续使用原来保存的路径,不自动迁移文件。缓存清理只处理受管理的缓存,保留工作文件。任务执行子进程的 TEMP/TMP/TMPDIR 使用实际临时目录。
362
368
 
369
+ Windows 新应用采用短目录布局,已有应用保留原宿主目录。新任务使用独立的短任务目录;`paths.tasksDirectory` 返回新任务目录,`legacyTasksDirectory` 返回仍可读取的旧任务目录。每个任务的 `pathLayoutVersion: 2` 与宿主、仓库的布局记录共同确定位置,不按软件版本或创建日期猜测,也不搬迁历史文件。短目录的完整应用身份会被校验;目录缺失、布局版本未知或出现新旧重复记录时报告真实错误,不创建空任务替代。用户显式选择的工作目录保持原位置。macOS/Linux 保持原布局。短布局减少内部路径开销,不能消除任意外部程序自身的路径长度限制;部署时仍应选择较短的数据目录基址。
370
+
363
371
  ```ts
364
372
  const session = await agent.createSession({
365
373
  workspacePath: '/workspace',
@@ -373,6 +381,8 @@ const session = await agent.createSession({
373
381
 
374
382
  相对授权根和 cwd 按 workspacePath 解析;cwd 必须是其中已存在的目录。文件工具按 cwd 解析相对路径,写入前检查真实父目录和符号链接。SDK 状态目录可以位于平台根目录内,但不能被文件工具读取、修改或搜索;显式附件与已登记技能资源保留既有只读授权。未配置 `paths` 的历史任务沿用原有行为。
375
383
 
384
+ `task_update.artifact_paths` 和专家团产物登记的相对路径同样按调用者的 cwd 解析,并校验其读取授权。返回的文件引用可以直接交给文件工具再次读取;历史已保存的工作区相对产物引用保持原有含义,恢复会话不会改变指向。
385
+
376
386
  声明路径策略后,原生命令及 AIOS 受管命令使用同一份原生权限配置,恢复、分叉和后续轮次不会因“完全访问”放大目录授权,只读成员保持只读。当前 Windows 非提权沙箱无法执行分离的读目录或 deny-read 限制,会返回工具失败,不转为无沙箱执行。`windowsSandbox: 'elevated'` 仅供部署方已经配置相应系统沙箱的机器,本 SDK 不自动提权或创建系统账号;本机未验收该模式。
377
387
 
378
388
  数据分析、UI 和矢量产物工具中的模型脚本,在声明目录策略时也通过同一原生受控命令入口运行。拒绝执行会返回真实工具错误,不改用普通进程启动。应用注册的回调、第三方 MCP 和扩展代码运行在其自身宿主内,须由应用配置相应文件系统/容器边界。
package/dist/index.js CHANGED
@@ -1,55 +1,4 @@
1
- import{randomUUID as A}from"node:crypto";import{setTimeout as _e}from"node:timers/promises";import Lt from"node:path";import{randomUUID as rt}from"node:crypto";var h=class extends Error{constructor(t,n,o){super(n,o);this.code=t;this.name="AiosSdkError"}};import Pt from"node:http";import{setTimeout as jt}from"node:timers/promises";import j from"node:fs";import Be from"node:os";import K from"node:path";import{createHash as Tt}from"node:crypto";var O=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 Or,spawnSync as Et}from"node:child_process";import Ue from"node:path";function xe(r=process.env){let e=r.SystemRoot??r.SYSTEMROOT;if(!e||!Ue.win32.isAbsolute(e))throw new Error("Windows SystemRoot 未配置为绝对路径。");return Ue.win32.join(e,"System32","WindowsPowerShell","v1.0","powershell.exe")}function ze(r){let e=String.raw`
2
- $ErrorActionPreference = 'Stop'
3
- $ProgressPreference = 'SilentlyContinue'
4
- $env:PSModulePath = Join-Path $PSHOME 'Modules'
5
- [Console]::InputEncoding = New-Object Text.UTF8Encoding
6
- [Console]::OutputEncoding = New-Object Text.UTF8Encoding
7
- try {
8
- `+r+String.raw`
9
- } catch {
10
- [Console]::Error.WriteLine($_.Exception.ToString())
11
- exit 1
12
- }
13
- `;return["-NoLogo","-NoProfile","-NonInteractive","-OutputFormat","Text","-EncodedCommand",Buffer.from(e,"utf16le").toString("base64")]}var kt=String.raw`
14
- $spec = [Console]::In.ReadToEnd() | ConvertFrom-Json
15
- try { $item = Get-Item -LiteralPath $spec.path -Force }
16
- catch [Management.Automation.ItemNotFoundException] { exit 3 }
17
- function Read-StorageAccessControl($entry, $sections) {
18
- try { return $entry.GetAccessControl($sections) }
19
- catch {
20
- $cause = $_.Exception.GetBaseException()
21
- if ($cause -is [IO.FileNotFoundException] -or $cause -is [IO.DirectoryNotFoundException]) { exit 3 }
22
- throw
23
- }
24
- }
25
- $attributes = $item.Attributes
26
- if ([int]$attributes -eq -1) { exit 3 }
27
- if ($attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Reparse points are not private storage' }
28
- $sid = [Security.Principal.WindowsIdentity]::GetCurrent().User
29
- $sections = [Security.AccessControl.AccessControlSections]'Owner,Access'
30
- $acl = Read-StorageAccessControl $item $sections
31
- if ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -ne $sid.Value) { throw 'Storage owner mismatch' }
32
- if ($spec.secure) {
33
- if (!$item.PSIsContainer) { throw 'Private root is not a directory' }
34
- $inherit = [Security.AccessControl.InheritanceFlags]'ContainerInherit,ObjectInherit'
35
- $rules = @($acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]))
36
- $private = ($acl.AreAccessRulesProtected -and $rules.Count -eq 1 -and
37
- !$rules[0].IsInherited -and $rules[0].IdentityReference.Value -eq $sid.Value -and
38
- $rules[0].AccessControlType -eq 'Allow' -and $rules[0].FileSystemRights -eq 'FullControl' -and
39
- $rules[0].InheritanceFlags -eq $inherit -and $rules[0].PropagationFlags -eq 'None')
40
- if (!$private) {
41
- $acl = New-Object Security.AccessControl.DirectorySecurity
42
- $acl.SetAccessRuleProtection($true, $false)
43
- $rule = New-Object Security.AccessControl.FileSystemAccessRule($sid, 'FullControl', $inherit, 'None', 'Allow')
44
- $acl.AddAccessRule($rule)
45
- # Set only the DACL; repeating it would propagate across all installed resources.
46
- $item.SetAccessControl($acl)
47
- $acl = Read-StorageAccessControl $item $sections
48
- }
49
- }
50
- foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {
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
- }
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-----
1
+ import{randomUUID as T}from"node:crypto";import{setTimeout as et}from"node:timers/promises";import Ar from"node:path";import{randomUUID as jt}from"node:crypto";var f=class extends Error{constructor(t,n,o){super(n,o);this.code=t;this.name="AiosSdkError"}};import hr from"node:http";import{setTimeout as gr}from"node:timers/promises";import L from"node:fs";import ot from"node:os";import oe from"node:path";import{createHash as ur}from"node:crypto";var _=class extends Error{constructor(t,n,o=2,i){super(n,i);this.code=t;this.exitCode=o;this.details=i?.details}details};import Ue from"node:path";import{createRequire as Zt}from"node:module";import{fileURLToPath as er}from"node:url";function tr(){let e=Zt(import.meta.url)(typeof AIOS_FILE_SECURITY_BINDING_PATH>"u"?"koffi":Ue.resolve(Ue.dirname(er(import.meta.url)),AIOS_FILE_SECURITY_BINDING_PATH)),t=e.load("advapi32.dll"),n=e.load("kernel32.dll");return{binding:e,attributes:n.func("uint32_t __stdcall GetFileAttributesW(const char16_t *path)"),error:n.func("uint32_t __stdcall GetLastError()"),close:n.func("int __stdcall CloseHandle(intptr_t handle)"),free:n.func("void * __stdcall LocalFree(void *memory)"),openToken:t.func("int __stdcall OpenProcessToken(intptr_t process, uint32_t access, _Out_ intptr_t *token)"),tokenInfo:t.func("int __stdcall GetTokenInformation(intptr_t token, int kind, void *data, uint32_t size, _Out_ uint32_t *needed)"),sidString:t.func("int __stdcall ConvertSidToStringSidW(const void *sid, _Out_ void **text)"),read:t.func("uint32_t __stdcall GetNamedSecurityInfoW(const char16_t *path, int kind, uint32_t information, _Out_ void **owner, void *group, _Out_ void **dacl, void *sacl, _Out_ void **descriptor)"),control:t.func("int __stdcall GetSecurityDescriptorControl(const void *descriptor, _Out_ uint16_t *control, _Out_ uint32_t *revision)"),aclInfo:t.func("int __stdcall GetAclInformation(const void *acl, void *data, uint32_t size, int kind)"),ace:t.func("int __stdcall GetAce(const void *acl, uint32_t index, _Out_ void **ace)"),descriptor:t.func("int __stdcall ConvertStringSecurityDescriptorToSecurityDescriptorW(const char16_t *sddl, uint32_t revision, _Out_ void **descriptor, void *size)"),dacl:t.func("int __stdcall GetSecurityDescriptorDacl(const void *descriptor, _Out_ int *present, _Out_ void **acl, _Out_ int *defaulted)"),write:t.func("uint32_t __stdcall SetNamedSecurityInfoW(const char16_t *path, int kind, uint32_t information, void *owner, void *group, const void *dacl, void *sacl)")}}var ne;function C(r,e,t){return Object.assign(new Error(`${e} '${r}' (Win32 ${t})`),{code:t===2||t===3?"ENOENT":t===5?"EACCES":"EIO",path:r,syscall:e,win32Code:t})}function Be(r,e){let t=[null];if(!r.sidString(e,t))throw C("","ConvertSidToStringSidW",r.error());try{return r.binding.decode(t[0],"char16_t",-1)}finally{r.free(t[0])}}function rr(r){let e=[0];if(!r.openToken(-1,8,e))throw C("","OpenProcessToken",r.error());try{let t=[0];r.tokenInfo(e[0],1,null,0,t);let n=r.error();if(n!==122)throw C("","GetTokenInformation",n);let o=Buffer.alloc(t[0]);if(!r.tokenInfo(e[0],1,o,o.length,t))throw C("","GetTokenInformation",r.error());return Be(r,r.binding.decode(o,"void *"))}finally{r.close(e[0])}}function nr(r,e){let t=Buffer.alloc(12);if(!r.aclInfo(e,t,t.length,2))throw C("","GetAclInformation",r.error());let n=[];for(let o=0;o<t.readUInt32LE(0);o++){let i=[null];if(!r.ace(e,o,i))throw C("","GetAce",r.error());let s=Buffer.from(r.binding.decode(i[0],"uint8_t",4)),a=s[0];if([1,6,10,12].includes(a)){n.push({type:a,flags:s[1],rights:0,sid:""});continue}if(![0,5,9,11].includes(a))throw new Error(`Unsupported private storage access rule: ${a}`);let c=Buffer.from(r.binding.decode(i[0],"uint8_t",s.readUInt16LE(2))),l=8;if(a===5||a===11){let d=c.readUInt32LE(8);l=12+(d&1?16:0)+(d&2?16:0)}n.push({type:a,flags:s[1],rights:c.readUInt32LE(4),sid:Be(r,c.subarray(l))})}return n}function or(r,e){ne??=tr();let t=Ue.toNamespacedPath(r),n=ne.attributes(t);if(n===4294967295)throw C(r,"GetFileAttributesW",ne.error());if(n&1024)throw new Error("Reparse points are not private storage");if(e&&!(n&16))throw new Error("Private root is not a directory");return{api:ne,name:t,user:rr(ne)}}function ir(r){let e=[null],t=[null],n=[null];return{owner:e,acl:t,descriptor:n,args:[r,1,5,e,null,t,null,n]}}function sr(r,e,t){let{api:n,user:o}=r;if(Be(n,e.owner[0])!==o)throw new Error("Storage owner mismatch");let i=[0],s=[0];if(!n.control(e.descriptor[0],i,s))throw C("","GetSecurityDescriptorControl",n.error());let a=e.acl[0]?nr(n,e.acl[0]):[],c=a[0],l=!!(i[0]&4096)&&a.length===1&&c.type===0&&c.flags===3&&c.rights===2032127&&c.sid===o;if(t&&!l)return!1;if(!e.acl[0])throw new Error("Storage has no discretionary access control list");if(a.some(d=>[0,5,9,11].includes(d.type)&&d.sid!==o&&d.sid!=="S-1-5-18"))throw new Error("Storage is accessible by another principal");return!0}function ar(r){let{api:e,user:t}=r,n=[null],o=[null];if(!e.descriptor(`D:P(A;OICI;FA;;;${t})`,1,n,null))throw C("","ConvertStringSecurityDescriptorToSecurityDescriptorW",e.error());try{if(!e.dacl(n[0],[0],o,[0]))throw C("","GetSecurityDescriptorDacl",e.error());return{descriptor:n[0],args:[r.name,1,2147483652,null,null,o[0],null]}}catch(i){throw e.free(n[0]),i}}function nt(r,e){let t=or(r,e),{api:n}=t,o=i=>{let s=ir(t.name),a=n.read(...s.args);if(a)throw C(r,"GetNamedSecurityInfoW",a);try{return sr(t,s,i)}finally{n.free(s.descriptor[0])}};if(!o(e)){let i=ar(t);try{let s=n.write(...i.args);if(s)throw C(r,"SetNamedSecurityInfoW",s)}finally{n.free(i.descriptor)}o(!1)}}function cr(r){throw r.code==="ENOENT"?r:new _("UNSAFE_DATA_DIRECTORY",`Windows 私有存储访问控制校验失败:${r instanceof Error?r.message:String(r)}`,1,{cause:r})}function $e(r,e){try{nt(r,e)}catch(t){cr(t)}}import dr from"node:fs";function lr(r,e="/proc"){let t;try{t=dr.readFileSync(`${e}/${r}/stat`,"utf8")}catch(o){if(o.code==="ENOENT")return;throw o}let n=t.slice(t.lastIndexOf(")")+2).trim().split(/\s+/);return{pid:r,parentPid:Number(n[1]),exited:n[0]==="Z"||n[0]==="X"}}function X(r){if(process.platform==="linux"){let e=lr(r);if(!e||e.exited)return!1}try{return process.kill(r,0),!0}catch(e){let t=e.code;if(t==="ESRCH")return!1;if(t==="EPERM")return!0;throw e}}function Y(r){L.mkdirSync(r,{recursive:!0,mode:448});let e=L.lstatSync(r);if(!e.isDirectory()||e.isSymbolicLink()||process.getuid&&e.uid!==process.getuid())throw new _("UNSAFE_DATA_DIRECTORY","CLI 私有目录的类型或所有者不正确。",1);process.platform==="win32"?$e(r,!0):L.chmodSync(r,448)}function ze(r){let e=ur("sha256").update(r).digest("hex").slice(0,32),t=oe.join(process.platform==="win32"?ot.tmpdir():"/tmp",`aios-cli-${process.getuid?.()??ot.userInfo().username}`);return{lock:oe.join(r,"daemon.lock"),mutex:oe.join(r,"daemon-owner.sqlite"),metadata:oe.join(r,"daemon.json"),socketDirectory:t,socket:process.platform==="win32"?`\\\\.\\pipe\\aios-cli-${e}`:oe.join(t,`${e}.sock`)}}function pr(r){let e=L.lstatSync(r,{throwIfNoEntry:!1});if(e&&(!e.isFile()||e.isSymbolicLink()))throw new _("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1);return e}function He(r){let e=pr(r);try{process.platform==="win32"&&e&&$e(r,!1)}catch(t){if(t.code==="ENOENT")return;throw t}return fr(r)}function fr(r){let e;try{e=L.openSync(r,L.constants.O_RDONLY|L.constants.O_NOFOLLOW)}catch(t){let n=t.code;if(n==="ENOENT")return;throw n==="ELOOP"?new _("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1):t}try{let t=L.fstatSync(e);if(!t.isFile()||process.getuid&&t.uid!==process.getuid()||process.platform!=="win32"&&(t.mode&63)!==0)throw new _("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1);try{return JSON.parse(L.readFileSync(e,"utf8"))}catch(n){throw n instanceof SyntaxError?new _("INVALID_DAEMON_METADATA","服务所有权记录损坏,原文件已保留。",1):n}}finally{L.closeSync(e)}}var mr=1,Dn=8*1024*1024;function Je(r){if(!r||typeof r!="object")return!1;let e=r;return e.protocol===mr&&Number.isSafeInteger(e.pid)&&Number(e.pid)>0&&(e.installationId===void 0||typeof e.installationId=="string")&&["instanceId","version","token","socket","root","startedAt"].every(t=>typeof e[t]=="string")}function it(r){let e=ze(r),t=He(e.metadata);if(!Je(t)||t.root!==r||t.socket!==e.socket||!X(t.pid))throw new f("CLI_NOT_RUNNING","请先启动指定数据目录的 CLI 后台服务。");if("sdkProtocol"in t)throw new f("RUNTIME_INCOMPATIBLE","该数据目录属于精简运行时,请使用 createClient。");return t}function ve(r){let e=ze(r),t=He(e.metadata);if(t!==void 0){if(!Je(t)||t.root!==r||t.socket!==e.socket||!("sdkProtocol"in t)||t.sdkProtocol!==1)throw new f("RUNTIME_INCOMPATIBLE","本机服务不支持当前 SDK 协议,或其归属记录不一致。");return X(t.pid)?t:void 0}}async function st(r,e){for(;;){e.throwIfAborted();let t=ve(r);if(t)return t;await gr(100,void 0,{signal:e})}}function ke(r,e,t,n,o,i,s=t==="runtime.drain"?0:12e4){let a=JSON.stringify({id:o,clientId:e,method:t,params:n});return Buffer.byteLength(a)>8*1024*1024?Promise.reject(new f("REQUEST_TOO_LARGE","SDK 请求超过 8 MiB。")):new Promise((c,l)=>{let d=u=>l(i?.aborted?i.reason:new f("OUTCOME_UNKNOWN",`请求 ${o} 的结果未知,请使用原命令 ID 查询回执。`,{cause:u})),p=hr.request({socketPath:r.socket,path:"/sdk",method:"POST",agent:!1,signal:i,headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json","content-length":Buffer.byteLength(a),"x-aios-protocol":"1","x-aios-instance":r.instanceId}},u=>{let h=[],g=0;u.on("data",y=>{g+=y.length,g>16777216?u.destroy(new Error("SDK 响应超过 16 MiB,请分页读取。")):h.push(y)}),u.once("error",d),u.once("end",()=>{try{if(u.statusCode===404)throw new f("SDK_UNSUPPORTED","此 CLI 版本未提供 SDK 接口,请使用包含 SDK 接口的版本。");let y=JSON.parse(Buffer.concat(h).toString("utf8"));if(y.id!==o||typeof y.ok!="boolean")throw new f("INVALID_RESPONSE","SDK 响应与请求不匹配。");if(!y.ok)throw new f(y.error?.code??"RUNTIME_ERROR",y.error?.message??"运行时返回未知错误。");c(y.value)}catch(y){l(y)}})});s>0&&p.setTimeout(s,()=>p.destroy(new Error("SDK 请求等待超时。"))),p.once("error",d),p.end(a)})}import R from"node:path";import ie from"node:fs";import{createHash as kr}from"node:crypto";import v from"node:fs";import D from"node:path";import{createHash as yr,randomUUID as Ie}from"node:crypto";var V=new Map,wr,be=/^(\d{16})-([a-f0-9]{64})\.json$/,Fe=r=>yr("sha256").update(r).digest("hex"),$=r=>`${r}.history`,at=r=>!0;function ct(r){if(v.existsSync(r+".bak")||v.existsSync(r+".bak.1"))return!0;try{return v.readdirSync($(r)).some(e=>be.test(e))}catch(e){if(e.code==="ENOENT")return!1;throw e}}var Q=class extends Error{constructor(t,n,o=!1,i){let s=n==="missing"?"必要记录缺失":n==="temporarily_unavailable"?"记录暂时无法访问":n==="unsupported_version"?"记录版本不受支持":"记录已损坏";super(`${dt(t)}:${s}。请查看存储恢复详情。`);this.file=t;this.problem=n;this.recoveryAvailable=o;this.cause=i,this.name="StorageIntegrityError"}cause};function dt(r){return D.basename(r)==="settings.json"?"应用设置":D.basename(r).startsWith("codex-")?"任务执行记录":D.basename(r)}function Ve(r,e,t){let n;try{n=v.readFileSync(r)}catch(o){return{status:o.code==="ENOENT"?"missing":"temporarily_unavailable",error:o}}try{let o=JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(n));if(t&&o&&typeof o=="object"&&"version"in o&&!t.includes(Number(o.version)))return{status:"unsupported_version",error:new Error("记录版本不受支持。")};if(!e(o))throw new Error("记录结构与所属文件不一致。");return{status:"healthy",value:o,bytes:n}}catch(o){return{status:"corrupt",error:o}}}function Ge(r,e){let t;try{t=v.readdirSync($(r))}catch(o){if(o.code==="ENOENT")t=[];else throw o}let n=[];for(let o of t.sort().reverse()){let i=be.exec(o);if(!i)continue;let s=D.join($(r),o),a=Ve(s,e);if(a.status==="temporarily_unavailable")throw a.error;a.status==="healthy"&&Fe(a.bytes)===i[2]&&n.push({file:s,generation:Number(i[1]),value:a.value,bytes:a.bytes})}if(!n.length)for(let o of[".bak",".bak.1"]){let i=Ve(r+o,e);if(i.status==="temporarily_unavailable")throw i.error;i.status==="healthy"&&n.push({file:r+o,generation:0,value:i.value,bytes:i.bytes})}return n}function lt(r,e,t,n){let o=D.resolve(r),i=V.get(o),s=new Q(r,e,t).message,a={id:i?.issue.id??Ie(),fileName:dt(r),status:e,message:s,detectedAt:i?.issue.detectedAt??new Date().toISOString(),recoveryAvailable:t};V.set(o,{issue:a,file:o,options:n}),(!i||i.issue.status!==e||i.issue.recoveryAvailable!==t)&&wr?.({...a}),V.size>256&&V.delete(V.keys().next().value)}function Ee(r,e,t){v.mkdirSync(D.dirname(r),{recursive:!0,mode:448});let n=`${r}.${Ie()}.tmp`,o;try{o=v.openSync(n,"wx",384),v.writeFileSync(o,e),t&&v.fsyncSync(o),v.closeSync(o),o=void 0,v.renameSync(n,r)}finally{o!==void 0&&v.closeSync(o);try{v.unlinkSync(n)}catch(i){if(i.code!=="ENOENT")throw i}}}function Sr(r){let e=D.join($(r),"damaged");v.mkdirSync(e,{recursive:!0,mode:448});try{v.copyFileSync(r,D.join(e,`${Date.now()}-${Ie()}.bin`),v.constants.COPYFILE_EXCL)}catch(t){if(t.code!=="ENOENT")throw t}}function ut(r,e={}){let t=e.validate??at,n=Ve(r,t,e.versions);if(n.status==="healthy")return{...n,recoveryAvailable:!1};if(n.status==="temporarily_unavailable"||n.status==="unsupported_version")return{...n,recoveryAvailable:!1};let o=Ge(r,t)[0];return{...n,backup:o,recoveryAvailable:!!o}}function pt(r,e={}){let t=ut(r,e);if(t.status==="healthy")return V.delete(D.resolve(r)),t.value;if(t.status==="missing"&&!t.recoveryAvailable&&!e.required&&!ct(r))return null;lt(r,t.status,t.recoveryAvailable,e);let n=v.existsSync($(r))?Math.max(0,...v.readdirSync($(r)).map(o=>Number(be.exec(o)?.[1]??0))):0;if(e.recover&&"backup"in t&&t.backup&&(e.allowOlderRecovery||t.backup.generation===n))return Sr(r),Ee(r,t.backup.bytes,!0),V.delete(D.resolve(r)),console.info("[storage-integrity] recovered",{file:r,source:t.backup.file}),t.backup.value;throw new Q(r,t.status,t.recoveryAvailable,t.error)}function ft(r,e,t){let n=Ge(r,t),o=Fe(e);if(n[0]?.generation&&Fe(n[0].bytes)===o)return;v.mkdirSync($(r),{recursive:!0,mode:448});let i=Math.max(0,...v.readdirSync($(r)).map(c=>Number(be.exec(c)?.[1]??0)))+1,s=D.join($(r),`${String(i).padStart(16,"0")}-${o}.json`),a=`${s}.${Ie()}.pending`;return Ee(a,e,!0),{temporary:a,destination:s}}function vr(r,e,t){let n=ft(r,e,t);if(n)try{v.renameSync(n.temporary,n.destination)}finally{try{v.unlinkSync(n.temporary)}catch(o){if(o.code!=="ENOENT")throw o}}}function mt(r,e,t={}){let n=t.validate??at;if(!n(e))throw new Q(r,"corrupt",!1,new Error("拒绝写入无效记录。"));let o=ut(r,t);if(o.status!=="healthy"&&!(o.status==="missing"&&!o.recoveryAvailable&&!ct(r)))throw lt(r,o.status,o.recoveryAvailable,t),new Q(r,o.status,o.recoveryAvailable,o.error);let i=Buffer.from(`${JSON.stringify(e,null,2)}
2
+ `);t.checkpoint!==!1&&o.status==="healthy"&&vr(r,o.bytes,n);let s=t.checkpoint!==!1?ft(r,i,n):void 0;try{if(t.checkpoint!==!1)for(let a of Ge(r,n).slice(2))a.generation>0&&v.unlinkSync(a.file);if(Ee(r,i,t.durable!==!1),s)try{v.renameSync(s.temporary,s.destination)}catch(a){try{o.status==="healthy"?Ee(r,o.bytes,!0):v.unlinkSync(r)}catch(c){throw Object.assign(new Error("记录保存失败,且回滚未完成。"),{errors:[a,c]})}throw a}}finally{if(s)try{v.unlinkSync(s.temporary)}catch(a){if(a.code!=="ENOENT")throw a}}}function We(r){let e=new URL(r);if(!["http:","https:"].includes(e.protocol)||e.username||e.password||e.search||e.hash)throw new Error("平台基地址无效。");return e.toString().replace(/\/+$/,"")}function qe(r){let e=r.mode==="platform"?We(r.platformBaseUrl):null,t=[r.mode,r.appId,r.userScope,e];if(r.mode==="platform"&&r.authentication){let{userId:n,tenantId:o,workspaceId:i}=r.authentication.principal;t.push(JSON.stringify(["managed",n,o,i]))}return kr("sha256").update(JSON.stringify(t)).digest("hex")}function xe(r){let e=qe(r),t=R.resolve(r.runtime.dataDirectory),n=R.join(t,"applications",e);if(process.platform!=="win32")return n;let o=R.join(t,"a",e.slice(0,32)),i=gt(t,e);if(i){let s=i.version===1?n:o;if(!ie.statSync(s,{throwIfNoEntry:!1})?.isDirectory())throw new Error("应用运行目录丢失,请恢复原目录,不能创建空目录替代。");if(ie.existsSync(i.version===1?o:n))throw new Error("应用同时存在新旧运行目录,请检查数据完整性。");return s}if(ie.existsSync(n)){if(ie.existsSync(o))throw new Error("应用同时存在新旧运行目录,请检查数据完整性。");return n}if(ie.existsSync(o))throw new Error("应用短目录缺少布局记录,请检查数据完整性。");return o}var ht=(r,e)=>R.join(r,"a",e.slice(0,32)+".json");function gt(r,e){return pt(ht(r,e),{recover:!1,validate:t=>{let n=t;return!!n&&(n.version===1||n.version===2)&&n.identity===e}})}function yt(r){let e=xe(r);if(Y(e),process.platform==="win32"){let t=R.resolve(r.runtime.dataDirectory),n=qe(r);if(!gt(t,n)){let o=R.basename(R.dirname(e))==="applications"?1:2;mt(ht(t,n),{version:o,identity:n},{validate:i=>{let s=i;return!!s&&s.version===o&&s.identity===n}})}}return e}function wt(r){let e=xe(r),t=qe(r);if(process.platform==="win32"){let o=(i,s)=>R.join(R.resolve(i??r.runtime.dataDirectory),s,t.slice(0,20));return{tasks:o(void 0,"t"),workspaces:o(r.runtime.workspaceDirectory,"w"),cache:o(r.runtime.cacheDirectory,"c"),temporary:o(r.runtime.temporaryDirectory,"tmp")}}let n=(o,i)=>o?R.join(R.resolve(o),"applications",t,i):R.join(e,i);return{workspaces:n(r.runtime.workspaceDirectory,"workspaces"),cache:n(r.runtime.cacheDirectory,"cache"),temporary:n(r.runtime.temporaryDirectory,"tmp")}}import Ke from"node:path";function St(r){for(let[e,t]of Object.entries({appId:r.appId,userScope:r.userScope}))if(typeof t!="string"||!t.trim()||t.length>256||/[\u0000-\u001f]/u.test(t))throw new Error(`独立运行身份 ${e} 无效。`);if(r.mode!=="standalone")throw new Error("独立运行身份模式不匹配。");return{mode:"standalone",appId:r.appId,userScope:r.userScope}}function A(r,e){return Object.assign(new Error(e),{code:r})}function vt(r,e){if(!r||r.kind!=="managed")throw new Error("托管身份配置无效。");let t=r.principal;if(!t||typeof t.userId!="string"||!t.userId.trim()||![t.tenantId,t.workspaceId].every(o=>o===null||typeof o=="string"&&o.trim()))throw new Error("托管身份必须明确指定用户、租户和工作区;无租户或工作区时使用 null。");let n=r.allowedOrigins??[];if(!Array.isArray(n)||n.some(o=>{let i=new URL(o);return!["http:","https:"].includes(i.protocol)||i.origin!==o}))throw new Error("凭证目标必须是 HTTP(S) origin,不能包含路径或认证信息。");return new URL(e),{kind:"managed",principal:{userId:t.userId,tenantId:t.tenantId,workspaceId:t.workspaceId},allowedOrigins:[...new Set(n)]}}function kt(r,e,t,n=Date.now()){if(!r||typeof r.accessToken!="string"||!r.accessToken.trim())throw new Error("托管凭证缺少 accessToken。");let o=r.session;if(!o||o.user?.id!==e.userId||typeof o.platformBaseUrl!="string"||o.platformBaseUrl.replace(/\/+$/,"")!==t.replace(/\/+$/,""))throw A("MANAGED_IDENTITY_MISMATCH","托管凭证的平台或用户与绑定身份不一致。");let i=r.accessToken.split(".");if(i.length!==3)throw new Error("平台托管凭证必须是 JWT。");let s=JSON.parse(Buffer.from(i[1],"base64url").toString("utf8"));if(!s||typeof s!="object"||Array.isArray(s))throw new Error("平台凭证的 JWT 内容无效。");let a=(...E)=>{let W=E.map(x=>s[x]).find(x=>typeof x=="string"&&x.trim());return typeof W=="string"?W:null},c=a("sub"),l=a("tenantId","tenant_id"),d=a("workspaceId","workspace_id")??o.context?.currentWorkspaceId??null;if(c!==e.userId||l!==e.tenantId||d!==e.workspaceId||(o.context?.currentTenantId??null)!==e.tenantId||(o.context?.currentWorkspaceId??null)!==e.workspaceId)throw A("MANAGED_IDENTITY_MISMATCH","托管凭证续期不得改变用户、租户或工作区。");let p=Date.parse(o.accessTokenExpiresAt);if(!Number.isFinite(p)||p<=n||typeof s.exp!="number"||!Number.isFinite(s.exp)||s.exp*1e3<=n)throw A("MANAGED_CREDENTIAL_EXPIRED","应用返回的托管凭证已经过期。");if(typeof o.user.username!="string"||typeof o.user.displayName!="string"||!Array.isArray(o.user.roles)||!o.user.roles.every(E=>typeof E=="string")||!Array.isArray(o.tenants))throw new Error("托管凭证的用户资料格式无效。");let{id:u,username:h,displayName:g,email:y,phone:I,avatarUrl:S,tenantId:m,roles:w}=o.user,k=o.tenants.map(E=>{if(!E||typeof E.id!="string"||typeof E.name!="string"||typeof E.displayName!="string")throw new Error("托管凭证的租户资料格式无效。");return{id:E.id,name:E.name,displayName:E.displayName,status:E.status}});return{credential:{accessToken:r.accessToken,session:{user:{id:u,username:h,displayName:g,email:y,phone:I,avatarUrl:S,tenantId:m,roles:[...w]},tenants:k,context:{currentTenantId:e.tenantId,currentWorkspaceId:e.workspaceId,personalMode:o.context?.personalMode,contextVersion:o.context?.contextVersion},platformBaseUrl:t,authenticatedAt:o.authenticatedAt,accessTokenExpiresAt:o.accessTokenExpiresAt}},expiresAt:Math.min(p,s.exp*1e3),sessionId:a("sessionId","sid")}}function Et(r){if(r!==void 0){if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(e=>!["startupTimeoutMs","rpcTimeoutMs","methodTimeoutMs","shutdownTimeoutMs"].includes(e)))throw new Error("通信等待配置无效。");for(let e of["startupTimeoutMs","rpcTimeoutMs","shutdownTimeoutMs"]){let t=r[e];if(t!==void 0&&(!Number.isSafeInteger(t)||t<(e==="rpcTimeoutMs"?0:1)||t>2147483647))throw new Error(`${e} 必须是有效毫秒数。`)}if(r.methodTimeoutMs!==void 0){if(!r.methodTimeoutMs||typeof r.methodTimeoutMs!="object"||Array.isArray(r.methodTimeoutMs))throw new Error("方法等待配置无效。");for(let[e,t]of Object.entries(r.methodTimeoutMs))if(!/^[a-zA-Z][a-zA-Z0-9.]+$/.test(e)||!Number.isSafeInteger(t)||t<0||t>2147483647)throw new Error("方法等待配置无效。")}}}function It(r,e){return e?.methodTimeoutMs?.[r]??(r==="runtime.drain"?0:e?.rpcTimeoutMs??12e4)}function bt(r){if(!r||typeof r!="object"||Array.isArray(r)||Object.entries(r).some(([e,t])=>!["temperature","topP","maxOutputTokens","responseFormat"].includes(e)||typeof t!="boolean"))throw new Error("模型生成能力声明无效。")}function xt(r){if(r===void 0)return;if(!r||typeof r!="object"||Array.isArray(r)||Object.keys(r).some(t=>!["storage","extraction"].includes(t))||r.storage!==void 0&&!["local","external"].includes(r.storage))throw new Error("记忆配置无效。");let e=r.extraction;if(e!==void 0&&(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).some(t=>!["enabled","idleMs","model","instructions","timeoutMs"].includes(t))||e.enabled!==void 0&&typeof e.enabled!="boolean"||e.idleMs!==void 0&&(!Number.isSafeInteger(e.idleMs)||e.idleMs<0||e.idleMs>2147483647)||e.timeoutMs!==void 0&&(!Number.isSafeInteger(e.timeoutMs)||e.timeoutMs<1||e.timeoutMs>2147483647)||e.model!==void 0&&(typeof e.model!="string"||!e.model.trim())||e.instructions!==void 0&&(typeof e.instructions!="string"||e.instructions.length>32e3)))throw new Error("记忆提取策略无效。")}function se(r){if(!r||!["platform","standalone"].includes(r.mode))throw new Error("必须明确选择 platform 或 standalone 模式。");if(St({mode:"standalone",appId:r.appId,userScope:r.userScope}),Et(r.communication),xt(r.memory),r.authorization!==void 0&&(!r.authorization||typeof r.authorization.required!="boolean"||Object.keys(r.authorization).some(e=>e!=="required")))throw new Error("会话授权配置无效。");if(r.generationCapabilities!==void 0){if(!r.generationCapabilities||typeof r.generationCapabilities!="object"||Array.isArray(r.generationCapabilities))throw new Error("模型能力目录无效。");Object.values(r.generationCapabilities).forEach(bt)}if(!r.runtime||typeof r.runtime.directory!="string"||!r.runtime.directory.trim()||typeof r.runtime.dataDirectory!="string"||!r.runtime.dataDirectory.trim())throw new Error("运行时目录和数据目录不能为空。");if(r.mode==="standalone"&&"platformBaseUrl"in r)throw new Error("独立模式不得配置平台基地址。");if(r.mode==="platform"&&"models"in r)throw new Error("平台模式不得配置独立模式模型列表。");if(r.mode==="standalone"&&"authentication"in r)throw new Error("独立模式不使用平台托管凭证。");if(r.runtime.tools&&Object.keys(r.runtime.tools).some(e=>!["node","python","git","bash","npm"].includes(e)))throw new Error("工具路径配置包含未知工具。");if(r.appName!==void 0&&(typeof r.appName!="string"||!r.appName.trim()||r.appName.length>128))throw new Error("应用名称无效。");for(let e of["workspaceDirectory","cacheDirectory","temporaryDirectory"]){let t=r.runtime[e];if(t!==void 0&&(typeof t!="string"||!t.trim()||!Ke.isAbsolute(t)))throw new Error(`${e} 必须是绝对目录路径。`)}return{...structuredClone(r),runtime:{...structuredClone(r.runtime),directory:Ke.resolve(r.runtime.directory),dataDirectory:Ke.resolve(r.runtime.dataDirectory)},...r.mode==="platform"?{platformBaseUrl:We(r.platformBaseUrl),...r.authentication!==void 0?{authentication:vt(r.authentication,r.platformBaseUrl)}:{}}:{}}}import{setTimeout as Tr}from"node:timers/promises";import F from"node:fs";import M from"node:path";import{createHash as Ct,verify as br}from"node:crypto";var At=`-----BEGIN PUBLIC KEY-----
54
3
  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};
4
+ -----END PUBLIC KEY-----`;var Ae={version:"0.0.6",protocol:1,dataFormat:1,profile:"light"};import Te from"node:fs";import H from"node:path";import{createHash as Ir}from"node:crypto";var z=r=>new f("RUNTIME_INTEGRITY_FAILED",r);function Tt(r,e){if(!e||e.includes("\\")||H.posix.normalize(e)!==e||H.posix.isAbsolute(e)||e===".."||e.startsWith("../"))throw z(`共享运行资源路径无效:${e}`);let t=H.resolve(r,e),n=H.relative(r,Te.realpathSync(t));if(n===".."||n.startsWith(`..${H.sep}`)||H.isAbsolute(n))throw z(`共享运行资源越界:${e}`);return t}async function Ot(r,e){if(!e||typeof e!="object"||Array.isArray(e))throw z("缺少共享运行资源清单。");let t=e;if(t.root!=="../.."||typeof t.codex!="string"||!t.files||typeof t.files!="object"||Array.isArray(t.files))throw z("共享运行资源清单无效。");let n=Te.realpathSync(H.resolve(r,t.root));if(H.relative(n,r).split(H.sep).join("/")!=="runtime/sdk-host")throw z("共享宿主不在产品运行资源目录中。");let o=t.files;for(let i of[t.codex,"runtime/desktop-agent-runtime/index.js","runtime/desktop-agent-runtime/package.json"])if(!Object.hasOwn(o,i))throw z(`共享运行资源缺少必需文件:${i}`);for(let[i,s]of Object.entries(o)){if(!s||typeof s!="object"||Array.isArray(s))throw z(`共享运行资源属性无效:${i}`);let a=s,c=Tt(n,i),l=Te.lstatSync(c);if(a.type!=="file"||!l.isFile()||l.isSymbolicLink()||l.size!==a.size||typeof a.sha256!="string"||!/^[a-f0-9]{64}$/.test(a.sha256))throw z(`共享运行资源属性不匹配:${i}`);let d=Ir("sha256");for await(let p of Te.createReadStream(c))d.update(p);if(d.digest("hex")!==a.sha256)throw z(`共享运行资源摘要不匹配:${i}`)}return{root:n,codexExecutable:Tt(n,t.codex)}}var J=r=>new f("RUNTIME_INTEGRITY_FAILED",r);function Rt(r,e){let t=M.relative(r,e);return t!==".."&&!t.startsWith(`..${M.sep}`)&&!M.isAbsolute(t)}async function N(r,e=At,t={platform:process.platform,arch:process.arch}){let n=F.realpathSync(r),o=M.join(n,"aios-sdk-runtime.json"),i=F.readFileSync(o),s=JSON.parse(i.toString("utf8"));if(s.schemaVersion!==1||s.version!==Ae.version||s.protocol!==Ae.protocol||s.dataFormat!==Ae.dataFormat||s.platform!==t.platform||s.arch!==t.arch||!["light","product"].includes(String(s.profile)))throw new f("RUNTIME_INCOMPATIBLE","精简运行时版本、协议、数据格式、系统或架构不兼容。");let a=JSON.parse(F.readFileSync(M.join(n,"signature.json"),"utf8"));if(a.algorithm!=="ed25519"||typeof a.signature!="string"||a.publicKey?.trim()!==e.trim()||!br(null,i,e,Buffer.from(a.signature,"base64")))throw J("运行时清单签名与可信发布公钥不匹配。");if(!s.files||typeof s.files!="object"||Array.isArray(s.files))throw J("运行时缺少文件清单。");let c=s.files,l=["host.mjs","js-hook-runner.js","memory-worker.js","memory-schema-v1.sql","task-event-reader-worker.js","task-storage-recovery-worker.js","keyring.node",...s.profile==="light"?["resources/runtime/desktop-agent-runtime/index.js",`resources/runtime/codex/${t.platform}-${t.arch}/bin/${t.platform==="win32"?"codex.exe":"codex"}`]:[]];for(let S of l)if(!Object.hasOwn(c,S))throw J(`运行时缺少必需资源:${S}`);let d=new Map,p=S=>{for(let m of F.readdirSync(S)){let w=M.join(S,m),k=M.relative(n,w).split(M.sep).join("/");if(["aios-sdk-runtime.json","signature.json"].includes(k))continue;let B=F.lstatSync(w);B.isDirectory()&&!B.isSymbolicLink()?p(w):d.set(k,B)}};if(p(n),d.size!==Object.keys(c).length)throw J("运行时文件数量与清单不一致。");let u=[];for(let[S,m]of Object.entries(c)){let w=M.resolve(n,S),k=d.get(S);if(!S||S.includes("\\")||M.posix.normalize(S)!==S||!Rt(n,w)||!k)throw J(`运行时文件路径或归属不匹配:${S}`);if(m.type==="link"){if(!k.isSymbolicLink()||typeof m.link!="string"||M.isAbsolute(m.link)||F.readlinkSync(w)!==m.link||!Rt(n,F.realpathSync(w)))throw J(`运行时链接不匹配:${S}`)}else if(m.type==="file"){if(!k.isFile()||k.isSymbolicLink()||k.size!==m.size||!/^[a-f0-9]{64}$/.test(m.sha256)||t.platform!=="win32"&&(k.mode&73)!==(m.mode&73))throw J(`运行时文件属性不匹配:${S}`);u.push({file:w,name:S,entry:m})}else throw J(`运行时文件类型无效:${S}`)}let h=0,y=(await Promise.allSettled(Array.from({length:Math.min(8,u.length)},async()=>{for(;h<u.length;){let{file:S,name:m,entry:w}=u[h++],k=Ct("sha256");for await(let B of F.createReadStream(S))k.update(B);if(k.digest("hex")!==w.sha256)throw J(`运行时文件摘要不匹配:${m}`)}}))).find(S=>S.status==="rejected");if(y)throw y.reason;let I=s.profile==="product"?await Ot(n,s.resources):void 0;return{version:s.version,protocol:s.protocol,dataFormat:s.dataFormat,platform:t.platform,arch:t.arch,profile:s.profile,manifestSha256:Ct("sha256").update(i).digest("hex"),...I?{productResources:I}:{}}}import Nt from"node:fs";import Pt from"node:path";import{spawn as xr}from"node:child_process";function Oe(r){let{options:e}=r,t=yt(e),n=wt(e).temporary;Y(n);let o=Nt.openSync(Pt.join(t,"sdk-host.log"),"a",384),i=(()=>{try{return xr(e.runtime.nodeExecutable??process.execPath,[Pt.join(e.runtime.directory,"host.mjs")],{detached:!r.managed,windowsHide:!0,stdio:["ignore",o,o,"ipc"],env:{...process.env,TEMP:n,TMP:n,TMPDIR:n}})}finally{Nt.closeSync(o)}})(),s=new Promise(c=>{i.once("exit",(l,d)=>c({code:l,signal:d})),i.once("error",()=>{i.pid||c({code:null,signal:null})})}),a=new Promise((c,l)=>{let d=setTimeout(()=>h(new f("RUNTIME_START_TIMEOUT","SDK 服务未在指定时间内完成启动,请检查宿主日志。")),e.communication?.startupTimeoutMs??12e4),p=(g,y)=>h(new f("RUNTIME_START_FAILED",`SDK 服务启动进程退出(${g??y})。`)),u=g=>{if(!g||g.type!=="ready"){h(new f("RUNTIME_INCOMPATIBLE","宿主未返回当前 SDK 启动协议,请使用配套运行包。"));return}g.ok?h(void 0,g.value):h(new f(g.error.code,g.error.message))};function h(g,y){clearTimeout(d),i.removeListener("error",h),i.removeListener("exit",p),i.removeListener("message",u),g?l(g):c(y)}i.once("error",h),i.once("exit",p),i.on("message",u),i.send(r,g=>{g&&h(g)})});return{child:i,ready:a,exited:s}}var ae=class r{constructor(e,t,n){this.metadata=e;this.ownerExit=t;this.communication=n}eventWaitMs=0;closed=!1;clientId=jt();static async start(e,t){let n=se(e),o=Ar.resolve(n.runtime.directory),i=await N(o,n.runtime.trustedPublicKey),s=xe(n),a=ve(s);if(!a){let{child:c,ready:l}=Oe({options:n,verifiedPackage:i});try{a=await l}catch(d){if(!(d instanceof f)||d.code!=="DAEMON_ALREADY_OWNED")throw d;a=await st(s,AbortSignal.timeout(n.communication?.startupTimeoutMs??12e4))}finally{c.connected&&c.disconnect(),c.unref()}}return r.attach(n,a,i,t)}static async attach(e,t,n,o,i){if(t.version!==n.version||t.manifestSha256!==n.manifestSha256)throw new f("RUNTIME_INCOMPATIBLE","已运行的服务与指定运行包不一致,请由宿主所有者关闭后使用同一运行包重新启动。");let s=new r(t,i,e.communication),a=await s.call("attach",{options:e,pid:process.pid,manifestSha256:n.manifestSha256});if(s.eventWaitMs=a.eventWaitMs??0,o)try{await s.call("auth.bindProvider",o)}catch(c){throw await s.stop(),c}return s}call(e,t={},n=jt(),o){return this.closed?Promise.reject(new f("RUNTIME_CLOSED","SDK 客户端连接已关闭。")):this.ownerExit?.aborted?Promise.reject(this.ownerExit.reason):ke(this.metadata,this.clientId,e,t,n,o,It(e,this.communication))}async stop(){if(!this.closed){if(this.ownerExit?.aborted){this.closed=!0;return}await this.call("detach"),this.closed=!0}}async shutdown(){await this.call("shutdown"),this.closed=!0;let e=AbortSignal.timeout(this.communication?.shutdownTimeoutMs??12e4);for(;ve(this.metadata.root)?.instanceId===this.metadata.instanceId||X(this.metadata.pid);)await Tr(100,void 0,{signal:e})}};import Or from"node:path";import{randomUUID as _t}from"node:crypto";var Ce=class r{constructor(e){this.metadata=e}closed=!1;clientId=_t();static async connect(e){let t=new r(it(Or.resolve(e.dataDirectory)));return await t.call("attach",{sdkProtocol:1,options:e,pid:process.pid}),t}call(e,t={},n=_t(),o){return this.closed?Promise.reject(new f("RUNTIME_CLOSED","SDK 客户端连接已关闭。")):ke(this.metadata,this.clientId,e,t,n,o)}async stop(){this.closed||(await this.call("detach"),this.closed=!0)}async shutdown(){throw new f("SHARED_RUNTIME","连接已有 CLI 时,请通过 CLI 管理后台服务。")}};import Nr from"node:http";import{randomBytes as Pr,randomUUID as jr,timingSafeEqual as _r}from"node:crypto";import{Ajv as Dr}from"ajv";import{Ajv2020 as Mr}from"ajv/dist/2020.js";function Cr(r){let e={...r,kind:"aios-tool-result"};return Xe(e),e}function Z(r,e){if(typeof r!="string"||!r.trim())throw new Error(`工具返回的 ${e} 必须是非空字符串。`)}function Xe(r){if(!r||typeof r!="object"||!("kind"in r)||r.kind!=="aios-tool-result")return{content:[{type:"text",text:typeof r=="string"?r:JSON.stringify(r??null)}],isError:!1};let e=r;if(!Array.isArray(e.content))throw new Error("工具返回的 content 必须是数组。");let t=e.content.map(n=>{if(!n||typeof n!="object")throw new Error("工具返回的内容格式无效。");if(n.type==="text"){if(typeof n.text!="string")throw new Error("工具返回的 text 必须是字符串。");return{type:"text",text:n.text}}if(n.type==="image")return Z(n.data,"image.data"),Z(n.mimeType,"image.mimeType"),{type:"image",data:n.data,mimeType:n.mimeType};if(n.type==="resource"){let o=n.resource;Z(o?.uri,"resource.uri"),new URL(o.uri),o.mimeType!==void 0&&Z(o.mimeType,"resource.mimeType");let i="text"in o,s="blob"in o;if(i===s||i&&typeof o.text!="string"||s&&typeof o.blob!="string")throw new Error("工具文件内容必须且只能包含 text 或 blob。");return{type:"resource",resource:{uri:o.uri,...o.mimeType?{mimeType:o.mimeType}:{},...i?{text:o.text}:{blob:o.blob}}}}throw new Error("不支持的工具内容类型。")});if(e.data!==void 0){if(!e.data||typeof e.data!="object"||Array.isArray(e.data))throw new Error("工具返回的 data 必须是 JSON 对象。");t.push({type:"text",text:JSON.stringify(e.data)})}return e.error!==void 0&&(Z(e.error.code,"error.code"),Z(e.error.message,"error.message"),t.push({type:"text",text:JSON.stringify({error:e.error})})),{content:t,isError:e.error!==void 0}}var Dt=["projectId","collaborationProjectId","assistantId","platformSessionId","platformTurnId","platformTaskId","platformRunId","traceId"];function ce(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("执行上下文必须为对象。");return r}function G(r){if(typeof r!="string"||!r.trim()||r.length>512||/[\x00-\x1f\x7f]/.test(r))throw new Error("执行上下文字段必须为有效字符串,最多 512 字符。");return r}function Mt(r){let e=ce(r);if(Object.keys(e).some(t=>!["userId","tenantId","name"].includes(t)))throw new Error("执行主体包含未知字段。");return{userId:G(e.userId),tenantId:e.tenantId===null?null:G(e.tenantId),...e.name===void 0?{}:{name:G(e.name)}}}function Rr(r){let e=ce(r);if(Object.keys(e).some(n=>!["actor","owner","workspaceId","usageScene","metadata",...Dt].includes(n)))throw new Error("执行上下文包含未知字段。");if(!["personal","greeting","task","collaboration","coding"].includes(String(e.usageScene)))throw new Error("执行用量场景无效。");let t={actor:Mt(e.actor),owner:Mt(e.owner),workspaceId:e.workspaceId===null?null:G(e.workspaceId),usageScene:e.usageScene};for(let n of Dt)e[n]!==void 0&&(t[n]=G(e[n]));if(e.metadata!==void 0){let n=ce(e.metadata);if(Object.keys(n).length>16||JSON.stringify(n).length>8192)throw new Error("业务扩展元数据超过限制。");for(let[o,i]of Object.entries(n)){if(!/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(o))throw new Error("业务元数据命名空间无效。");let s=ce(i);if(Object.keys(s).length>32)throw new Error("业务元数据字段过多。");for(let[a,c]of Object.entries(s))if(!/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(a)||!(c===null||typeof c=="boolean"||typeof c=="number"&&Number.isFinite(c)||typeof c=="string"&&c.length<=1024&&!/[\x00-\x1f\x7f]/.test(c)))throw new Error("业务元数据字段无效。")}t.metadata=structuredClone(n)}return t}function Re(r){let e=ce(r);if(Object.keys(e).some(t=>!["sessionId","runId","context"].includes(t)))throw new Error("执行绑定包含未知字段。");return{sessionId:G(e.sessionId),runId:G(e.runId),...e.context===void 0?{}:{context:Rr(e.context)}}}async function Lt(r,e,t){let n=new Map,o=new Dr({strict:!0,strictTypes:!1,allErrors:!0,validateFormats:!1}),i=new Mr({strict:!0,strictTypes:!1,allErrors:!0,validateFormats:!1}),s=new Map;for(let m of e){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(m.name)||n.has(m.name))throw new Error(`业务工具名称无效或重复:${m.name}`);if(m.inputSchema.type!=="object")throw new Error(`业务工具 ${m.name} 的输入 schema 必须为 object。`);n.set(m.name,m);let w=m.inputSchema.$schema==="http://json-schema.org/draft-07/schema#"?o:i;s.set(m.name,w.compile(m.inputSchema))}let a=Pr(32).toString("hex"),c=new Map,l=new Set,d=!1,p,u,h=new Promise(m=>{u=m}),g=()=>p??=(async()=>{for(let m of c.values())m.abort(new Error("应用工具提供者已关闭。"));I.closeAllConnections(),await new Promise((m,w)=>I.close(k=>k?w(k):m())),u()})(),y=()=>{d&&l.size===0&&c.size===0&&g()},I=Nr.createServer(async(m,w)=>{let k=Buffer.from(`Bearer ${a}`),B=Buffer.from(m.headers.authorization??"");if(B.length!==k.length||!_r(B,k)){w.writeHead(401).end();return}if(m.url!=="/mcp"){w.writeHead(404).end();return}let E=m.headers["mcp-session-id"];if(m.method==="DELETE"&&typeof E=="string"&&l.delete(E)){for(let[j,q]of c)j.startsWith(`${E}:`)&&q.abort(new Error("工具会话已关闭。"));w.writeHead(204).end(),y();return}if(m.method!=="POST"){w.writeHead(405).end();return}let W=null,x=(j,q=!1)=>{let O=JSON.stringify({jsonrpc:"2.0",id:W,...q?{error:j}:{result:j}});w.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),w.end(O)};try{let j=0,q=[];for await(let b of m){let K=Buffer.from(b);if(j+=K.length,j>8*1024*1024)throw new Error("业务工具请求超过 8 MiB。");q.push(K)}let O=JSON.parse(Buffer.concat(q).toString("utf8"));if(W=O.id??null,O.method==="initialize"){if(d){x({code:-32e3,message:"应用工具提供者已注销。"},!0);return}let b=jr();l.add(b),w.setHeader("mcp-session-id",b),x({protocolVersion:"2025-03-26",capabilities:{tools:{listChanged:!1}},serverInfo:{name:r,version:"1"}});return}if(typeof E!="string"||!l.has(E)){w.writeHead(404).end();return}if(O.method==="notifications/cancelled"){c.get(`${E}:${String(O.params?.requestId)}`)?.abort(new Error("工具调用已取消。")),w.writeHead(202).end();return}if(O.id===void 0){w.writeHead(202).end();return}if(O.method==="ping"){x({});return}if(O.method==="tools/list"){x({tools:e.map(b=>({name:b.name,description:b.description,inputSchema:b.inputSchema,annotations:{readOnlyHint:b.readOnly,destructiveHint:!b.readOnly,openWorldHint:!0}}))});return}if(O.method!=="tools/call"){x({code:-32601,message:"不支持的 MCP 方法。"},!0);return}let ye=n.get(String(O.params?.name));if(!ye)throw new Error("业务工具不存在。");let ee=O.params?.arguments;if(!ee||typeof ee!="object"||Array.isArray(ee))throw new Error("工具参数必须是对象。");let tt=s.get(ye.name);if(!tt(ee)){x({content:[{type:"text",text:`工具参数不符合声明:${JSON.stringify(tt.errors)}`}],isError:!0});return}let te=new AbortController,we=`${E}:${String(W)}`;if(c.has(we))throw new Error("工具请求 ID 正在执行,不能重复提交。");c.set(we,te);let rt=()=>{w.writableEnded||te.abort(new Error("工具请求连接已关闭。"))};w.once("close",rt);let re="validation";try{let K=O.params?._meta?.["aios/execution"],{invocationId:Le,...Kt}=K??{},Se=K===void 0?void 0:Re(Kt);if(K&&(typeof Le!="string"||!Le))throw new Error("工具调用标识缺失。");re="execution";let Xt=await ye.execute(ee,{signal:te.signal,callId:we,...Se&&t?{files:{resolve:(Yt,Qt)=>t(Se.sessionId,Yt,Qt,te.signal)}}:{},...Se?{execution:Ut({...Se,invocationId:Le})}:{}});re="serialization",te.signal.throwIfAborted(),x(Xe(Xt))}catch(b){x({content:[{type:"text",text:JSON.stringify({error:{message:(b instanceof Error?b.message:String(b)).slice(0,4096),capability:ye.name,phase:re,side_effects:re==="validation"?"not_started":re==="serialization"?"completed":"unknown",next_action:"先核对实际结果,不要因工具返回失败而直接重复执行。"}})}],isError:!0})}finally{w.removeListener("close",rt),c.delete(we),y()}}catch(j){x({code:-32602,message:j instanceof Error?j.message:String(j)},!0)}});return await new Promise((m,w)=>{I.once("error",w),I.listen(0,"127.0.0.1",m)}),{descriptor:{id:r,name:r,transport:"HTTP",url:`http://127.0.0.1:${I.address().port}/mcp`,bearerToken:a,tools:e.map(m=>m.name),defaultToolsApproval:"prompt",toolApprovals:Object.fromEntries(e.map(m=>[m.name,m.readOnly?"auto":"prompt"]))},close:g,closed:h,status:()=>({retired:d,sessions:l.size,calls:c.size,closing:!!p}),retire:()=>{d=!0,y()}}}function Ut(r){return r&&typeof r=="object"&&(Object.values(r).forEach(Ut),Object.freeze(r)),r}import{createHash as $r}from"node:crypto";var Lr=/^[a-z][a-z0-9_]{0,63}$/u;function Ur(r){return r.trim().toLowerCase()}function Ye(r){let e=Ur(r);if(!Lr.test(e))throw new Error("MCP 技能引用标识只能包含小写字母、数字和下划线,必须以字母开头,最长 64 个字符");return e}function Br(r){return`aios_mcp_${Ye(r)}`}function Bt(r,e){let t=e.trim();if(!t)throw new Error("MCP 工具名称不能为空");return`mcp__${Br(r)}__${t}`}function Ne(r){return r.toolProviderId===void 0?`app_${$r("sha256").update(JSON.stringify([r.id,r.version])).digest("hex").slice(0,32)}`:Ye(r.toolProviderId)}function Qe(r,e){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(e))throw new Error("业务工具名称无效。");return Bt(Ne(r),e)}import{randomUUID as zr}from"node:crypto";function Ze(r,e){if(!e)return r;function t(n){try{return n()}catch(o){process.emitWarning("SDK 诊断导出器执行失败,请检查应用诊断配置。",{code:"SDK_DIAGNOSTICS_FAILED",detail:o instanceof Error?o.name:typeof o})}}return{get eventWaitMs(){return r.eventWaitMs},stop:()=>r.stop(),shutdown:()=>r.shutdown(),async call(n,o,i=zr(),s){let a=performance.now(),c={name:"sdk.rpc",method:n,requestId:i},l=t(()=>e.startSpan?.("sdk.rpc",{method:n,requestId:i}));t(()=>e.log?.(Object.freeze({...c,phase:"started"})));let d="completed",p;try{return await r.call(n,o,i,s)}catch(u){throw d="failed",p=u&&typeof u=="object"&&"code"in u&&typeof u.code=="string"&&/^[A-Z0-9_]{1,80}$/.test(u.code)?u.code:"RPC_ERROR",u}finally{let u=performance.now()-a,h=Object.freeze({...c,phase:d,durationMs:u,...p?{errorCode:p}:{}});t(()=>e.log?.(h)),t(()=>e.metric?.("sdk.rpc.duration_ms",u,{method:n,outcome:d})),t(()=>l?.end(h))}}}}async function Pe(r,e){let t;try{t=await r()}catch(n){try{await e()}catch(o){throw new AggregateError([n,o],"文件传输及清理均失败。",{cause:n})}throw n}return await e(),t}var je=class{constructor(e,t){this.transport=e;this.sessionId=t}resolve(e,t="read",n){return this.transport.call("session.file.resolve",{id:this.sessionId,path:e,access:t},void 0,n)}call(e,t,n){return this.transport.call(`session.file.transfer.${e}`,{id:this.sessionId,...t},void 0,n)}async export(e,t,n){let{signal:o}=n,i=await this.call("begin",{kind:"export",path:e},o),s=this,a=0,c=(async function*(){for(;a<i.bytes;){o?.throwIfAborted();let l=await s.call("read",{transferId:i.id,offset:a},o);if(l.bytes<=0)throw new Error("导出数据意外结束。");a+=l.bytes,yield Buffer.from(l.data,"base64")}})();return Pe(async()=>{let l=await t.put({...n,source:c,sha256:i.sha256,bytes:i.bytes});if(o?.throwIfAborted(),a!==i.bytes||!l.version||l.key!==n.key)throw new Error("存储适配器未完整接收文件或未返回正确版本。");return{stored:l,file:i.file,sha256:i.sha256,bytes:i.bytes}},()=>Pe(()=>c.return(void 0),()=>this.call("close",{transferId:i.id})))}async import(e,t,n){if(!e.key||!e.version)throw new Error("导入必须指定对象存储键及版本。");let{signal:o}=n;o?.throwIfAborted();let i=await t.get({key:e.key,version:e.version,signal:o}),s=i.source[Symbol.asyncIterator](),a;return Pe(async()=>{a=await this.call("begin",{kind:"import",path:n.path,expectedVersion:n.expectedVersion,bytes:i.bytes,sha256:i.sha256},o);let c=0;for(;;){o?.throwIfAborted();let d=await s.next();if(d.done)break;let p=d.value;for(let u=0;u<p.byteLength;u+=a.chunkBytes){o?.throwIfAborted();let h=Buffer.from(p.subarray(u,u+a.chunkBytes));c=(await this.call("write",{transferId:a.id,offset:c,data:h.toString("base64")},o)).offset}}return o?.throwIfAborted(),{file:await this.call("commit",{transferId:a.id},o),source:e}},()=>Pe(async()=>s.return?.(),async()=>{a&&await this.call("close",{transferId:a.id})}))}};import Hr from"node:http";import{randomBytes as Jr,timingSafeEqual as Fr}from"node:crypto";async function $t(r){let e=Jr(32).toString("hex"),t=new Set,n=Hr.createServer(async(i,s)=>{let a=Buffer.from(`Bearer ${e}`),c=Buffer.from(i.headers.authorization??"");if(c.length!==a.length||!Fr(c,a)){s.writeHead(401).end();return}if(i.method!=="POST"||i.url!=="/callbacks"){s.writeHead(404).end();return}let l=new AbortController;t.add(l),s.once("close",()=>{s.writableFinished||l.abort(new Error("应用回调请求已断开。"))});try{let d=[],p=0;for await(let I of i){let S=Buffer.from(I);if(p+=S.length,p>64*1024*1024)throw new Error("应用回调请求超过 64 MiB。");d.push(S)}let u=JSON.parse(Buffer.concat(d).toString("utf8")),h=r.get(u.method);if(!h)throw Object.assign(new Error("应用回调不存在。"),{code:"APPLICATION_PROVIDER_OFFLINE"});let g=await h(u.params,l.signal);l.signal.throwIfAborted();let y=JSON.stringify({ok:!0,value:g});s.writeHead(200,{"content-type":"application/json"}).end(y)}catch(d){s.writeHead(200,{"content-type":"application/json"}).end(JSON.stringify({ok:!1,error:{message:d instanceof Error?d.message:String(d),code:d&&typeof d=="object"&&"code"in d?String(d.code):"APPLICATION_CALLBACK_FAILED"}}))}finally{t.delete(l)}});return await new Promise((i,s)=>{n.once("error",s),n.listen(0,"127.0.0.1",i)}),{connection:{url:`http://127.0.0.1:${n.address().port}/callbacks`,token:e,methods:[...r.keys()]},close:async()=>{for(let i of t)i.abort(new Error("应用回调服务已关闭。"));n.closeAllConnections(),await new Promise((i,s)=>n.close(a=>a?s(a):i()))}}}function zt(r){if(!Array.isArray(r)||r.length>2)throw new Error("JS Hook 定义无效。");let e=new Set;return r.map(t=>{if(!t||typeof t!="object"||!["PreToolUse","PostToolUse"].includes(t.event)||e.has(t.event)||typeof t.callback!="string"||!/^hook\.[a-z0-9_]+\.(PreToolUse|PostToolUse)$/.test(t.callback)||!Number.isSafeInteger(t.timeoutMs)||t.timeoutMs<1||t.timeoutMs>36e5||t.matcher!==void 0&&(typeof t.matcher!="string"||!t.matcher.trim())||Object.keys(t).some(n=>!["event","callback","matcher","timeoutMs"].includes(n)))throw new Error("JS Hook 字段无效。");return e.add(t.event),structuredClone(t)})}function Ht(r,e){let t=e===void 0?{}:e;if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).some(n=>!["decision","reason","additionalContext"].includes(n))||t.decision!==void 0&&!["continue","deny"].includes(t.decision)||["reason","additionalContext"].some(n=>{let o=t[n];return o!==void 0&&(typeof o!="string"||o.length>32e3)})||t.decision==="deny"&&!t.reason?.trim())throw new Error("Hook 决定无效,拒绝必须说明原因。");return{...t.decision==="deny"?{decision:"block",reason:t.reason}:{},hookSpecificOutput:{hookEventName:r,...t.additionalContext?{additionalContext:t.additionalContext}:{}}}}import Qr from"node:http";import{randomBytes as Zr,timingSafeEqual as en}from"node:crypto";var Vr="[REDACTED]",Gr="(?:密码|口令|密钥|令牌|私钥|凭据|验证码)",Wr=new RegExp(`(${Gr}\\s*["']?\\s*(?:[::=]|是(?!否)|为)\\s*)(?:"([^"]*)"|'([^']*)'|“([^”]*)”|‘([^’]*)’|([^\\s"'“”‘’,。;,;}]+))`,"gu");var qr=["authorization","password","passwd","passphrase","token","api[-_]?key","secret","cookie","credentials?","private[-_]?key","pat"].join("|"),Jt=`(?:[a-z0-9]+[-_])*(?:${qr})`,Kr=new RegExp(`(\\b${Jt}\\b["']?\\s*[:=]\\s*["']?)([^\\s"',};&,。;]+)`,"gi"),Xr=new RegExp(`([?&]${Jt}=)([^&#\\s]*)`,"gi");function Ft(r){return r.replace(/(\/codex\/)[a-f0-9]+(?=\/v1\b)/gi,"$1[REDACTED]").replace(/(\/model-usage\/)[a-f0-9]+/gi,"$1[REDACTED]").replace(/\b(authorization|proxy-authorization)\s*:\s*[^\r\n]+/gi,"$1: [REDACTED]").replace(/\b(set-cookie|cookie)\s*:\s*[^\r\n]+/gi,"$1: [REDACTED]").replace(/\b(bearer|basic)\s+[^\s"',}]+/gi,"$1 [REDACTED]").replace(/(https?:\/\/[^\s/:@]+:)[^\s/@]+(@)/gi,"$1[REDACTED]$2").replace(Xr,"$1[REDACTED]").replace(Kr,"$1[REDACTED]").replace(Wr,(e,t,n,o,i,s)=>{let a=n!==void 0?['"','"']:o!==void 0?["'","'"]:i!==void 0?["“","”"]:s!==void 0?["‘","’"]:["",""];return`${t}${a[0]}${Vr}${a[1]}`})}import{randomUUID as Yr}from"node:crypto";var _e=class{id=Yr();sequence=0;records=[];listeners=new Set;closed=!1;publish(e){this.records.push({...structuredClone(e),cursor:`${this.id}:${++this.sequence}`,occurredAt:new Date().toISOString()}),this.records.length>256&&this.records.shift(),this.wake()}close(){this.closed=!0,this.wake()}wake(){for(let e of this.listeners)e()}async*stream(e={}){let t=this.sequence-this.records.length;if(e.after!==void 0){let[n,o,i]=e.after.split(":");if(t=Number(o),n!==this.id||i!==void 0||!/^\d+$/.test(o??"")||!Number.isSafeInteger(t)||t>this.sequence)throw A("AUTH_EVENT_CURSOR_INVALID","授权事件游标不属于当前凭证提供者。")}for(;;){e.signal?.throwIfAborted();let n=this.sequence-this.records.length;if(t<n)throw A("AUTH_EVENT_CURSOR_EXPIRED","授权事件游标已超出内存保留范围,请重新读取授权状态。");let o=this.records[t-n];if(o){t++,yield structuredClone(o);continue}if(this.closed)return;await new Promise((i,s)=>{let a=()=>{this.listeners.delete(c),e.signal?.removeEventListener("abort",l)},c=()=>{a(),i()},l=()=>{a(),s(e.signal.reason)};this.listeners.add(c),e.signal?.addEventListener("abort",l,{once:!0})})}}};var De=class{constructor(e,t,n){this.authentication=e;this.platformBaseUrl=t;this.provider=n}events=new _e;entries=new Map;sequence=0;epoch=0;revoked=!1;closed=!1;expiration;execution(e){if(e===void 0)return;let t=Re(e),{context:n}=t,o=this.authentication.principal;if(n&&(n.actor.userId!==o.userId||n.actor.tenantId!==o.tenantId||n.workspaceId!==o.workspaceId))throw A("EXECUTION_PRINCIPAL_MISMATCH","凭证请求的操作者、租户和空间与实例主体不一致。");return n&&(Object.freeze(n.actor),Object.freeze(n.owner),Object.freeze(n)),Object.freeze(t)}clear(){this.epoch++;for(let e of this.entries.values())e.controller.abort(A("MANAGED_AUTHORIZATION_CHANGED","解析凭证期间授权已改变。"));this.entries.clear(),clearTimeout(this.expiration)}revoke(e,t){let n=this.execution(e);return t!==void 0&&this.entries.get(JSON.stringify(n)??"")?.generation!==t?!1:(this.clear(),this.revoked=!0,this.events.publish({type:"invalidated",scope:"provider",reason:"revoked",execution:n,code:"MANAGED_AUTHORIZATION_REVOKED"}),!0)}async resolve(e,t,n){if(this.closed)throw A("MANAGED_PROVIDER_UNAVAILABLE","凭证提供者已关闭。");if(this.revoked&&e!=="explicit")throw A("MANAGED_AUTHORIZATION_REVOKED","应用托管授权已撤销。");let o=this.execution(t),i=JSON.stringify(o)??"";if(e==="explicit"&&o)throw new Error("显式刷新作用于整个实例,不能指定单轮上下文。");let s=this.entries.get(i);if(e==="explicit"&&(!s?.pending||s.reason!=="explicit")&&(this.clear(),s=void 0),s||(s={execution:o,generation:0,controller:new AbortController}),this.entries.delete(i),this.entries.set(i,s),s.pending)await s.pending;else{let a=e==="explicit"||e==="rejected"&&n===s.generation;if(a||!s.cached||s.cached.expiresAt<=Date.now()+3e4){let c=a?e:s.cached||s.expired?"expiring":"initial";s.cached=void 0;let l=this.epoch;s.reason=c;let d=this.load(s,c,l);s.pending=d;try{await d}finally{s.pending===d&&(s.pending=void 0),this.trim()}}}if(!s.cached||s.controller.signal.aborted)throw A("MANAGED_AUTHORIZATION_CHANGED","解析凭证期间授权已改变。");return{...s.cached.credential,generation:s.generation}}trim(){for(let[e,t]of this.entries){if(this.entries.size<=128)return;t.pending||this.entries.delete(e)}}async load(e,t,n){try{let o=await this.provider({reason:t,signal:e.controller.signal,execution:e.execution});if(e.controller.signal.throwIfAborted(),n!==this.epoch)throw A("MANAGED_AUTHORIZATION_CHANGED","解析凭证期间授权已改变。");if(o===null)throw this.revoke(),A("MANAGED_AUTHORIZATION_REVOKED","应用未提供有效授权。");e.cached=kt(o,this.authentication.principal,this.platformBaseUrl),e.expired=!1,e.generation=++this.sequence,this.revoked=!1,this.events.publish({type:"authorized",scope:"credential",reason:t,execution:e.execution,expiresAt:new Date(e.cached.expiresAt).toISOString()})}catch(o){if(n===this.epoch){let i=o&&typeof o=="object"&&"code"in o?String(o.code):"";this.events.publish({type:"invalidated",scope:"credential",reason:"provider_error",execution:e.execution,code:["MANAGED_IDENTITY_MISMATCH","MANAGED_CREDENTIAL_EXPIRED"].includes(i)?i:"MANAGED_CREDENTIAL_ERROR"})}throw o}finally{this.scheduleExpiration()}}scheduleExpiration(){clearTimeout(this.expiration);let e=1/0;for(let t of this.entries.values())t.cached&&(e=Math.min(e,t.cached.expiresAt));e===1/0||this.closed||(this.expiration=setTimeout(()=>{for(let t of this.entries.values())t.cached&&t.cached.expiresAt<=Date.now()&&(t.cached=void 0,t.expired=!0,this.events.publish({type:"invalidated",scope:"credential",reason:"expired",execution:t.execution,code:"MANAGED_CREDENTIAL_EXPIRED"}));this.scheduleExpiration()},Math.min(2147483647,Math.max(1,e-Date.now()))),this.expiration.unref())}close(){this.closed=!0,this.clear(),this.revoked=!0,this.events.publish({type:"invalidated",scope:"provider",reason:"closed",code:"MANAGED_PROVIDER_UNAVAILABLE"}),this.events.close()}};async function Vt(r,e,t){let n=Zr(32).toString("hex"),o=new De(r,e,t),i=Qr.createServer(async(s,a)=>{let c=Buffer.from(`Bearer ${n}`),l=Buffer.from(s.headers.authorization??"");if(c.length!==l.length||!en(c,l)){a.writeHead(401).end();return}if(s.method!=="POST"||s.url!=="/credentials"){a.writeHead(404).end();return}try{let d=0,p=[];for await(let g of s){let y=Buffer.from(g);if(d+=y.length,d>64*1024)throw new Error("凭证请求过大。");p.push(y)}let u=JSON.parse(Buffer.concat(p).toString("utf8"));if(u.generation!==void 0&&(!Number.isSafeInteger(u.generation)||u.generation<1))throw new Error("凭证版本无效。");let h;if(u.revoke===!0)h={revoked:o.revoke(u.execution,u.generation)};else{if(!["initial","expiring","rejected","explicit"].includes(String(u.reason)))throw new Error("凭证解析原因无效。");if(u.reason==="rejected"&&u.generation===void 0)throw new Error("被拒凭证版本无效。");h=await o.resolve(u.reason,u.execution,u.generation)}a.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),a.end(JSON.stringify(h))}catch(d){a.writeHead(400,{"content-type":"application/json","cache-control":"no-store"}),a.end(JSON.stringify({error:{code:d&&typeof d=="object"&&"code"in d?String(d.code):"MANAGED_CREDENTIAL_ERROR",message:Ft(d instanceof Error?d.message:String(d))}}))}});return await new Promise((s,a)=>{i.once("error",a),i.listen(0,"127.0.0.1",s)}),{connection:{url:`http://127.0.0.1:${i.address().port}/credentials`,token:n},events:o.events,close:async()=>{o.close(),i.closeAllConnections(),await new Promise((s,a)=>i.close(c=>c?a(c):s()))}}}import{randomUUID as tn}from"node:crypto";import{setTimeout as Gt}from"node:timers/promises";var de=class{constructor(e,t){this.connection=e;this.authorizationEvents=t}managedEvents(e={}){let t=this.authorizationEvents?.();if(!t)throw new f("MANAGED_PROVIDER_UNAVAILABLE","此客户端未注册托管凭证提供者。");return t.stream(e)}login(e){return this.connection().call("auth.login",e)}getToken(){return this.connection().call("auth.token")}refresh(){return this.connection().call("auth.refresh")}refreshManaged(){return this.connection().call("auth.managed.refresh")}revokeManaged(){return this.connection().call("auth.managed.revoke")}status(){return this.connection().call("auth.status")}context(){return this.connection().call("auth.context")}logout(){return this.connection().call("auth.logout")}completePasswordChange(e){return this.connection().call("auth.password",e)}switchSubject(e){return this.connection().call("auth.switchSubject",e)}async startBrowserLogin(e={}){let t=this.connection(),n=await t.call("auth.browser.start",{...e,requestId:e.requestId??tn()});return new le(t,n.id)}resumeBrowserLogin(e){return new le(this.connection(),e)}},le=class{constructor(e,t){this.transport=e;this.id=t}status(){return this.transport.call("auth.browser.status",{id:this.id})}cancel(){return this.transport.call("auth.browser.cancel",{id:this.id})}async getAuthorizationUrl(e={}){for(;;){e.signal?.throwIfAborted();let t=await this.status();if(this.checkFailure(t),t.state==="waiting"&&t.authorizationUrl)return t.authorizationUrl;if(t.state==="completed")throw new f("LOGIN_ALREADY_COMPLETED","网页登录已完成,请读取登录结果。");await Gt(150,void 0,e)}}async wait(e={}){for(;;){e.signal?.throwIfAborted();let t=await this.status();if(this.checkFailure(t),t.state==="completed"&&t.session)return t.session;await Gt(250,void 0,e)}}checkFailure(e){if(e.state==="failed")throw new f(e.error.code,e.error.message);if(e.state==="cancelled")throw new f("LOGIN_CANCELLED","网页登录已取消。")}};var ue=class{constructor(e){this.connection=e}call(e,t={}){return this.connection().call(`platform.${e}`,t)}getSession(){return this.call("session")}getUser(){return this.call("user")}getTenants(){return this.call("tenants")}getContext(){return this.call("context")}models={list:()=>this.call("models.list"),listSpeechRecognition:()=>this.call("models.speech")};experts={prepare:(e,t)=>this.call("experts.prepare",{...e,...t?{resolved:t}:{}})};account={getSummary:(e={})=>this.call("account.summary",e),listPlanPurchases:()=>this.call("account.purchases"),getUsage:e=>this.call("account.usage",e)};skills={getHome:()=>this.call("skills.home"),install:e=>this.call("skills.install",e),remove:(e,t)=>this.call("skills.remove",{skillId:e,tenantId:t}),getVersions:e=>this.call("skills.versions",e),updateVersion:e=>this.call("skills.updateVersion",e),search:(e={})=>this.call("skills.search",e),getDetail:(e,t)=>this.call("skills.detail",{skillId:e,tenantId:t}),listCategories:()=>this.call("skills.categories"),prepareForLocalTask:e=>this.call("skills.prepare",e)};plugins={list:(e={})=>this.call("plugins.list",e),getDetail:e=>this.call("plugins.detail",{recordId:e}),listCategories:()=>this.call("plugins.categories"),prepare:(e,t,n)=>this.call("plugins.prepare",{pluginId:e,recordId:t,resourceVersion:n}),getAuthorization:e=>this.call("plugins.authorization.get",{pluginId:e}),saveAuthorization:(e,t)=>this.call("plugins.authorization.save",{pluginId:e,request:t}),revokeAuthorization:e=>this.call("plugins.authorization.revoke",{pluginId:e}),verifyAuthorization:e=>this.call("plugins.authorization.verify",{pluginId:e})};knowledge={tree:()=>this.call("knowledge.tree"),search:(e={})=>this.call("knowledge.search",e),listDocuments:e=>this.call("knowledge.documents",e),readDocument:e=>this.call("knowledge.read",e),getDocumentDownloadLink:e=>this.call("knowledge.downloadLink",{documentId:e})}};import U from"node:fs";import P from"node:path";import{createHash as rn}from"node:crypto";import{createRequire as nn}from"node:module";import{t as on,x as sn}from"tar";var an=nn(import.meta.url),cn=["win32-x64","darwin-x64","darwin-arm64","linux-x64","linux-arm64"];function dn(r=`${process.platform}-${process.arch}`){if(!cn.includes(r))throw new f("RUNTIME_UNSUPPORTED",`尚未提供 ${r} 的精简运行时。`);let e=`@kmlckj/aios-runtime-${r}`;try{return P.dirname(an.resolve(`${e}/package.json`))}catch(t){throw t.code!=="MODULE_NOT_FOUND"?t:new f("RUNTIME_PACKAGE_MISSING",`缺少 ${e}。请安装对应版本的运行时包,不要使用 --omit=optional;也可显式指定 runtime.directory。`)}}async function ln(r){let e=rn("sha256");for await(let t of U.createReadStream(r))e.update(t);return e.digest("hex")}async function un(r,e){let t=new Set,n,o=i=>{if(!i||i.includes("\\")||i.includes("\0")||P.posix.isAbsolute(i)||/^[A-Za-z]:/.test(i)||i.split("/").includes(".."))throw new Error(`运行时归档路径无效:${i}`)};if(await on({file:r,strict:!0,onReadEntry(i){try{o(i.path);let s=P.posix.normalize(i.path).replace(/\/$/,"");if(t.has(s))throw new Error(`运行时归档包含重复路径:${s}`);if(t.add(s),!["File","OldFile","Directory","SymbolicLink","Link"].includes(i.type))throw new Error(`运行时归档条目类型无效:${i.type}`);if(i.linkpath){if(P.posix.isAbsolute(i.linkpath)||i.linkpath.includes("\\")||/^[A-Za-z]:/.test(i.linkpath))throw new Error(`运行时归档链接越界:${s}`);o(i.type==="SymbolicLink"?P.posix.join(P.posix.dirname(s),i.linkpath):i.linkpath)}}catch(s){n??=s}}}),n)throw n;await sn({file:r,cwd:e,strict:!0,preservePaths:!1})}async function pe(r,e){if(r.runtime?.directory!==void 0)return se(r);let t=e??dn(),n=JSON.parse(U.readFileSync(P.join(t,"package.json"),"utf8")),o=JSON.parse(U.readFileSync(new URL("../package.json",import.meta.url),"utf8")),i=JSON.parse(U.readFileSync(P.join(t,"runtime-package.json"),"utf8")),s=`${process.platform}-${process.arch}`;if(n.name!==`@kmlckj/aios-runtime-${s}`||n.version!==o.version||i.schemaVersion!==1||i.version!==o.version||i.target!==s||i.archive?.file!=="payload.tar.gz"||!/^[a-f0-9]{64}$/.test(i.archive.sha256)||!Number.isSafeInteger(i.archive.size)||i.archive.size<=0)throw new f("RUNTIME_INCOMPATIBLE","npm 运行时包的版本、平台或归档清单与 SDK 不一致。");if(!r.runtime||typeof r.runtime.dataDirectory!="string"||!r.runtime.dataDirectory.trim())throw new Error("运行时数据目录不能为空。");let a=P.resolve(r.runtime.dataDirectory,"runtimes"),c=P.join(a,`${s}-${i.archive.sha256}`),l=se({...r,runtime:{...r.runtime,directory:c}});if(U.existsSync(c))return await N(c,l.runtime.trustedPublicKey),l;let d=P.join(t,i.archive.file);if(U.statSync(d).size!==i.archive.size||await ln(d)!==i.archive.sha256)throw new f("RUNTIME_INTEGRITY_FAILED","npm 运行时归档内容与清单不一致。");Y(a);let p=U.mkdtempSync(P.join(a,".unpack-"));try{await un(d,p),await N(p,l.runtime.trustedPublicKey);try{U.renameSync(p,c)}catch(u){if(!U.existsSync(c))throw u;await N(c,l.runtime.trustedPublicKey)}return l}finally{U.rmSync(p,{recursive:!0,force:!0})}}import{randomUUID as pn}from"node:crypto";function Wt(r){let e=n=>{let o=r[n];if(typeof o!="number"||!Number.isSafeInteger(o)||o<0||o>864e5)throw Object.assign(new Error(`${n} 必须是 0 至 86400000 毫秒的整数。`),{code:"INVALID_DRAIN_OPTIONS"});return o},t=e("timeoutMs");if(r.onTimeout==="cancel")return{timeoutMs:t,onTimeout:"cancel",cancelTimeoutMs:e("cancelTimeoutMs")};if(r.onTimeout==="return")return{timeoutMs:t,onTimeout:"return"};throw Object.assign(new Error("必须明确选择排空到期后返回或取消。"),{code:"INVALID_DRAIN_OPTIONS"})}var fe=class r{constructor(e,t,n,o,i,s){this.options=e;this.metadata=t;this.verified=n;this.child=o;this.exited=i;this.connector=s;o.on("message",this.onMessage),o.on("error",this.onError),o.once("disconnect",this.onDisconnect),i.then(a=>{this.exit=a,this.exitController.abort(new f("RUNTIME_EXITED","SDK 宿主进程已退出。")),this.onError(new f("RUNTIME_EXITED",`SDK 宿主已退出(${a.code??a.signal})。`)),o.removeListener("message",this.onMessage),o.removeListener("error",this.onError),o.removeListener("disconnect",this.onDisconnect)})}exit;exitController=new AbortController;shutdownRequest;pending=new Map;static async start(e,t,n){let o=Wt({...t.shutdown}),i=await pe(e),s=await N(i.runtime.directory,i.runtime.trustedPublicKey),{child:a,ready:c,exited:l}=Oe({options:i,verifiedPackage:s,managed:{shutdown:o}});try{let d=await c;return new r(i,d,s,a,l,n)}catch(d){throw a.connected&&a.disconnect(),a.unref(),d}}get pid(){return this.metadata.pid}get instanceId(){return this.metadata.instanceId}connect(e={}){return this.exit||!this.child.connected?Promise.reject(new f("RUNTIME_EXITED","受管宿主连接已结束。")):this.connector(this.options,this.metadata,this.verified,e,this.exitController.signal)}shutdown(){if(this.shutdownRequest)return this.shutdownRequest;if(this.exit||!this.child.connected)return Promise.reject(new f("RUNTIME_EXITED","受管宿主连接已结束,请读取 wait 的退出结果。"));let e=pn();return this.shutdownRequest=new Promise((t,n)=>{this.pending.set(e,{resolve:t,reject:n}),this.child.send({type:"shutdown",id:e},o=>{o&&(this.pending.delete(e),n(o))})}).then(async t=>{if(t.status==="drained"){let n=await this.wait();if(n.code!==0)throw new f("RUNTIME_EXIT_FAILED",`SDK 宿主清理后异常退出(${n.code??n.signal})。`)}else this.shutdownRequest=void 0;return t},t=>{throw this.shutdownRequest=void 0,t}),this.shutdownRequest}wait(){return this.exited}onMessage=e=>{if(e.type!=="shutdown")return;let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.ok?t.resolve(e.value):t.reject(new f(e.error.code,e.error.message)))};onError=e=>{for(let t of this.pending.values())t.reject(e);this.pending.clear()};onDisconnect=()=>this.onError(new f("HOST_DISCONNECTED","宿主控制通道已断开,请读取 wait 的退出结果。"))};function qt(r,e){if(e.credentials&&(r.mode!=="platform"||!r.authentication))throw new Error("凭证回调只能用于平台托管模式。");if(e.authorize&&!r.authorization?.required)throw new Error("会话授权回调需要 authorization.required=true。");if(e.memoryStore&&r.memory?.storage!=="external")throw new Error("记忆存储适配器需要 memory.storage=external。")}var he=class r{constructor(e,t,n,o={}){this.transport=e;this.options=t;this.mode=n;this.services=o;this.transport=Ze(e,o.diagnostics)}toolProviders=new Set;activeToolProviders=new Map;credentialProvider;callbacks;callbackHandlers=new Map;lifecycleQueue=Promise.resolve();closed=!1;scheduleLifecycle(e){let t=this.lifecycleQueue.then(e);return this.lifecycleQueue=t.then(()=>{},()=>{}),t}assertOpen(){if(this.closed)throw new f("RUNTIME_CLOSED","SDK 客户端连接已关闭。")}async startCallbacks(){let e=this.callbackHandlers;if(this.services.authorize&&e.set("session.authorize",(i,s)=>this.services.authorize(Object.freeze(i),{signal:s})),this.services.memoryStore){let i=this.services.memoryStore;e.set("memory.read",(s,a)=>i.read(s,a)),e.set("memory.compareAndSwap",(s,a)=>i.compareAndSwap(s,a))}if(!e.size)return;let t=this.callbacks,n=t??await $t(e),o={...n.connection,methods:[...e.keys()]};try{await this.transport.call("application.callbacks",{connection:o}),this.callbacks=n}catch(i){throw t||await n.close(),i}}static async start(e,t,n){qt(e,t);let o=e.mode==="platform"&&e.authentication&&t.credentials?await Vt(e.authentication,e.platformBaseUrl,t.credentials):void 0;try{return{transport:n?await ae.attach(e,n.metadata,n.verified,o?.connection,n.exitSignal):await ae.start(e,o?.connection),provider:o}}catch(i){throw await o?.close(),i}}static async create(e,t={}){let n=await pe(e),{transport:o,provider:i}=await r.start(n,t),s=new r(o,n,n.mode,t);s.credentialProvider=i;try{await s.startCallbacks()}catch(a){throw await s.close(),a}return s}static startManaged(e,t){return fe.start(e,t,async(n,o,i,s,a)=>{let{transport:c,provider:l}=await r.start(n,s,{metadata:o,verified:i,exitSignal:a}),d=new r(c,n,n.mode,s);d.credentialProvider=l;try{await d.startCallbacks()}catch(p){throw await d.close(),p}return d})}static async connectCli(e){return new r(await Ce.connect(e),e,"platform")}auth=new de(()=>this.transport,()=>this.credentialProvider?.events);platform=new ue(()=>this.transport);runtime={health:e=>this.transport.call("runtime.health",{},void 0,e),activity:()=>this.transport.call("runtime.activity"),drain:(e,t)=>this.transport.call("runtime.drain",e,void 0,t)};resources={limits:{get:()=>this.transport.call("resources.limits.get"),set:(e,t,n)=>this.transport.call("resources.limits.set",{key:e,value:t,revision:n})},cache:{status:()=>this.transport.call("resources.cache.status"),prune:(e={})=>this.transport.call("resources.cache.prune",e)}};skills={list:()=>this.transport.call("skills.list"),importVersion:e=>this.transport.call("skills.importVersion",e),importPaths:e=>this.transport.call("skills.import",{paths:e}),remove:e=>this.transport.call("skills.remove",{reference:e})};plugins={list:()=>this.transport.call("plugins.list"),install:(e,t)=>this.transport.call("plugins.install",{recordId:e,source:t}),update:(e,t,n)=>this.transport.call("plugins.update",{pluginId:e,recordId:t,expectedRevision:n}),setEnabled:(e,t,n)=>this.transport.call("plugins.setEnabled",{pluginId:e,enabled:t,expectedRevision:n}),remove:(e,t)=>this.transport.call("plugins.remove",{pluginId:e,expectedRevision:t})};settings={get:()=>this.transport.call("settings.get"),set:(e,t,n)=>this.transport.call("settings.set",{domain:e,value:t,revision:n})};native={settings:()=>this.transport.call("native.settings"),configure:(e,t)=>this.transport.call("native.configure",{value:e,revision:t}),status:e=>this.transport.call("native.status",{kind:e}),registerBrowser:()=>this.transport.call("native.register"),unregisterBrowser:()=>this.transport.call("native.unregister")};memory={get:e=>this.transport.call("memory.get",e),setEnabled:e=>this.transport.call("memory.setEnabled",e),edit:e=>this.transport.call("memory.edit",e),reset:e=>this.transport.call("memory.reset",e)};async setPlatformBaseUrl(e){if(!("mode"in this.options)||this.options.mode!=="platform")throw new Error("独立模式不使用平台基地址。");await this.configure({platformBaseUrl:e})}getConfiguration(){return this.transport.call("configuration.get")}configure(e){return this.scheduleLifecycle(()=>this.applyConfiguration(e))}async applyConfiguration(e){if(this.assertOpen(),!("mode"in this.options))throw new Error("连接已有 CLI 时请通过 CLI 修改全局配置。");if(this.options.mode==="standalone"&&e.platformBaseUrl!==void 0)throw new Error("独立模式不使用平台基地址。");if(this.options.mode==="platform"&&e.models!==void 0)throw new Error("平台模型由平台管理;外部模型请使用独立模式。");let t=await pe({...this.options,...e});qt(t,this.services),await N(t.runtime.directory,t.runtime.trustedPublicKey),await this.transport.call("configuration.validate",{options:t}),await this.transport.shutdown(),await this.disconnect();let{transport:n,provider:o}=await r.start(t,this.services);this.transport=Ze(n,this.services.diagnostics),this.credentialProvider=o,this.options=t,this.closed=!1;try{await this.startCallbacks()}catch(i){throw await this.disconnect(),i}return this.getConfiguration()}capabilities(e={}){return this.transport.call("capabilities",e)}dependencies(){return this.transport.call("dependencies")}defineAgent(e){return this.scheduleLifecycle(()=>this.registerAgent(e))}async registerAgent(e){this.assertOpen();let{tools:t,toolProviderId:n,jsHooks:o,...i}=e,s=Ne(e),a=[],c=new Map;for(let[u,h]of Object.entries(o??{})){if(!["beforeTool","afterTool"].includes(u)||!h||typeof h.execute!="function")throw new Error("JS Hook 必须提供执行函数。");let g=u==="beforeTool"?"PreToolUse":"PostToolUse",y=`hook.${s}.${g}`;a.push({event:g,callback:y,timeoutMs:h.timeoutMs??3e4,...h.matcher?{matcher:h.matcher}:{}}),c.set(y,this.callbackHandlers.get(y))}o&&(i.jsHookDefinitions=zt(a));let l=JSON.stringify([e.id,e.version]),d=this.activeToolProviders.get(s);if(d&&d.agent!==l)throw new Error("应用工具提供者 ID 已被其他智能体使用。");let p=t?.length?await Lt(s,t,(u,h,g,y)=>this.transport.call("session.file.resolve",{id:u,path:h,access:g},void 0,y)):void 0;p&&this.toolProviders.add(p);try{for(let[g,y]of Object.entries(o??{})){let I=g==="beforeTool"?"PreToolUse":"PostToolUse";this.callbackHandlers.set(`hook.${s}.${I}`,async(S,m)=>{let w=await y.execute(Object.freeze(S),{signal:m});return Ht(I,w),w})}o&&await this.startCallbacks();let u=[...i.mcpServers??[],...p?[p.descriptor]:[]];await this.transport.call("agent.define",{...i,mcpServers:u,...p?{applicationToolProviderId:s}:{}}),d?.provider?.retire();let h={agent:l,provider:p};return this.activeToolProviders.set(s,h),p&&p.closed.then(()=>{this.toolProviders.delete(p)}),new Me(this.transport,e.id,e.version,p,t?.map(g=>({name:g.name,reference:Qe(e,g.name)})),()=>{if(this.activeToolProviders.get(s)!==h)throw new Error("此工具提供者已被新注册替换,请使用当前 Agent 句柄。")})}catch(u){for(let[h,g]of c)g?this.callbackHandlers.set(h,g):this.callbackHandlers.delete(h);throw p&&(this.toolProviders.delete(p),await p.close()),u}}async openSession(e){return new ge(this.transport,await this.transport.call("session.get",{id:e}))}async openAgent(e,t){return this.assertOpen(),await this.transport.call("agent.providers",{agentId:e,agentVersion:t}),new Me(this.transport,e,t)}listSessions(e={}){return this.transport.call("session.list",e)}shutdown(){return this.scheduleLifecycle(async()=>{this.assertOpen(),await this.transport.shutdown(),await this.disconnect()})}close(){return this.scheduleLifecycle(()=>this.disconnect())}async disconnect(){if(!this.closed){this.closed=!0;try{await this.transport.stop()}finally{await Promise.all([...this.toolProviders].map(e=>e.close()).concat(this.credentialProvider?[this.credentialProvider.close()]:[])),this.callbacks&&(await this.callbacks.close(),this.callbacks=void 0),this.callbackHandlers.clear(),this.toolProviders.clear(),this.activeToolProviders.clear(),this.credentialProvider=void 0}}}},Me=class{constructor(e,t,n,o,i=[],s=()=>{}){this.transport=e;this.id=t;this.version=n;this.provider=o;this.tools=i;this.assertCurrentProvider=s}async createSession(e={}){return new ge(this.transport,await this.transport.call("session.create",{agentId:this.id,agentVersion:this.version,...e,creationId:e.creationId??T()}))}async adoptSession(e,t={}){return new ge(this.transport,await this.transport.call("session.bind",{id:e,agentId:this.id,agentVersion:this.version,policy:t.policy}))}providerStatus(){return this.transport.call("agent.providers",{agentId:this.id,agentVersion:this.version})}unregisterProvider(){return this.assertCurrentProvider(),this.transport.call("agent.unregisterProvider",{agentId:this.id,agentVersion:this.version})}async releaseProvider(){return await this.unregisterProvider(),this.provider?.retire(),this.provider?.status()}waitProviderClosed(){return this.provider?.closed??Promise.resolve()}},ge=class r{constructor(e,t){this.transport=e;this.info=t;this.id=t.id,this.files=new je(e,this.id)}id;files;runtimeTuning(){return this.transport.call("session.runtimeTuning",{id:this.id})}memory={get:(e={})=>this.transport.call("memory.get",{...e,sessionId:this.id}),edit:e=>this.transport.call("memory.edit",{...e,sessionId:this.id}),reset:()=>this.transport.call("memory.reset",{sessionId:this.id}),setEnabled:e=>this.transport.call("memory.setEnabled",{enabled:e,sessionId:this.id})};async send(e,t={}){let n=t.commandId??T(),o=await this.transport.call("session.send",{id:this.id,content:e,options:{...t,commandId:n}});return new me(this.transport,this.id,o.runId,n)}enqueue(e,t={}){return this.transport.call("session.enqueue",{id:this.id,content:e,options:{...t,commandId:t.commandId??T()}})}queue(){return this.transport.call("session.queue",{id:this.id})}editQueued(e,t,n,o=T()){return this.transport.call("session.queue.edit",{id:this.id,pendingMessageId:e,content:t,queueVersion:n,commandId:o})}removeQueued(e,t,n=T()){return this.transport.call("session.queue.delete",{id:this.id,pendingMessageId:e,queueVersion:t.queueVersion,targetRunId:t.activeRunId,commandId:n})}reorderQueue(e,t,n=T()){return this.transport.call("session.queue.reorder",{id:this.id,pendingMessageIds:e,queueVersion:t,commandId:n})}dispatchQueued(e,t,n,o=T()){return this.transport.call("session.queue.send",{id:this.id,pendingMessageId:e,queueVersion:t,targetRunId:n,commandId:o})}history(){return this.transport.call("session.history",{id:this.id})}rename(e,t){return this.transport.call("session.rename",{id:this.id,name:e,expectedRevision:t})}setArchived(e,t){return this.transport.call("session.archive",{id:this.id,archived:e,expectedRevision:t})}runs(e={},t){return this.transport.call("session.runs",{id:this.id,...e},void 0,t)}async*events(e={}){let t=e.cursor;for(;;){e.signal?.throwIfAborted();let n=await this.transport.call("session.events",{id:this.id,cursor:t,waitMs:this.transport.eventWaitMs??0},void 0,e.signal);for(let o of n.events)e.signal?.throwIfAborted(),yield o;t=n.cursor,this.transport.eventWaitMs||await et(150,void 0,{signal:e.signal})}}eventPage(e={}){return this.transport.call("session.events",{id:this.id,cursor:e.cursor,waitMs:0},void 0,e.signal)}queryHistory(e={}){return this.transport.call("session.history.query",{id:this.id,...e})}clear(e){return this.transport.call("session.clear",{id:this.id,...e})}delete(e){return this.transport.call("session.delete",{id:this.id,...e})}artifacts(e={},t={}){return this.transport.call("session.artifacts",{id:this.id,query:e},void 0,t.signal)}operations(e={}){return this.transport.call("session.operations",{id:this.id,...e})}teamState(){return this.transport.call("session.team.state",{id:this.id})}async createBackgroundSession(e,t=T()){let n=await this.transport.call("session.team.background",{id:this.id,memberId:e,creationId:t});return new r(this.transport,n)}operation(e,t={}){return this.transport.call("session.operation",{id:this.id,operationId:e},void 0,t.signal)}cancelOperation(e,t={}){return this.transport.call("session.operation.cancel",{id:this.id,operationId:e},void 0,t.signal)}configuration(e){return this.transport.call("session.configuration",{id:this.id,revision:e})}configure(e,t){return this.transport.call("session.defaults",{id:this.id,defaults:e,expectedRevision:t})}configureBuiltins(e,t){return this.transport.call("session.builtins",{id:this.id,builtins:e,expectedRevision:t})}updateAgent(e){return this.transport.call("session.agent",{id:this.id,...e})}receipt(e){return this.transport.call("session.receipt",{id:this.id,commandId:e})}resumeRun(e){return new me(this.transport,this.id,e)}async compact(e=T()){let t=await this.transport.call("session.compact",{id:this.id,commandId:e});return new me(this.transport,this.id,t.runId,e)}},me=class r{constructor(e,t,n,o){this.transport=e;this.taskId=t;this.id=n;this.commandId=o}state(e={}){return this.transport.call("run.state",{taskId:this.taskId,runId:this.id},void 0,e.signal)}context(){return this.transport.call("run.context",{taskId:this.taskId,runId:this.id})}memoryPolicy(){return this.transport.call("run.memoryPolicy",{taskId:this.taskId,runId:this.id})}team(e,t={}){return this.transport.call("session.team.command",{id:this.taskId,runId:this.id,command:e},void 0,t.signal)}artifacts(e={},t={}){return this.transport.call("session.artifacts",{id:this.taskId,query:{...e,runId:this.id}},void 0,t.signal)}operations(){return this.transport.call("session.operations",{id:this.taskId,runId:this.id})}operation(e,t={}){return this.transport.call("session.operation",{id:this.taskId,runId:this.id,operationId:e},void 0,t.signal)}cancelOperation(e,t={}){return this.transport.call("session.operation.cancel",{id:this.taskId,runId:this.id,operationId:e},void 0,t.signal)}cancel(e=T()){return this.transport.call("run.cancel",{taskId:this.taskId,runId:this.id,commandId:e})}detach(){return this.transport.call("run.detach",{taskId:this.taskId,runId:this.id})}approve(e,t,n=T()){return this.transport.call("run.approve",{taskId:this.taskId,runId:this.id,toolCallId:e,decision:t,commandId:n})}answer(e,t,n=T()){return this.transport.call("run.answer",{taskId:this.taskId,runId:this.id,requestId:e,response:t,commandId:n})}cancelInput(e,t=T()){return this.transport.call("run.cancelInput",{taskId:this.taskId,runId:this.id,requestId:e,commandId:t})}async confirmPlan(e=T()){let t=await this.transport.call("run.confirmPlan",{taskId:this.taskId,runId:this.id,commandId:e});return new r(this.transport,this.taskId,t.runId,e)}async*events(e={}){let t=e.cursor;for(;;){e.signal?.throwIfAborted();let n=await this.transport.call("run.events",{taskId:this.taskId,runId:this.id,cursor:t,waitMs:this.transport.eventWaitMs??0},void 0,e.signal);for(let o of n.events)e.signal?.throwIfAborted(),yield o;if(t=n.cursor,n.terminal)return;this.transport.eventWaitMs||await et(150,void 0,{signal:e.signal})}}async wait(e={}){for(;;){e.signal?.throwIfAborted();let t=this.transport.eventWaitMs?await this.transport.call("run.wait",{taskId:this.taskId,runId:this.id,waitMs:this.transport.eventWaitMs},void 0,e.signal):await this.state(e);if(t.status!=="running"&&t.status!=="queued")return t;this.transport.eventWaitMs||await et(150,void 0,{signal:e.signal})}}},vs=he.create,ks=he.connectCli,Es=he.startManaged;export{Me as Agent,he as AiosClient,f as AiosSdkError,de as AuthApi,le as BrowserLogin,fe as ManagedHost,ue as PlatformApi,me as Run,ge as Session,Ne as applicationToolProviderId,Qe as applicationToolReference,ks as connectCli,vs as createClient,Es as startManagedHost,Cr as toolResult,N as validateRuntime};
@@ -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>;
@@ -124,6 +124,7 @@ export interface BusinessTool {
124
124
  execute(input: Record<string, unknown>, context: ToolContext): unknown | Promise<unknown>;
125
125
  }
126
126
  export interface McpServer {
127
+ /** The tool reference uses the lowercase ID: a letter followed by letters, digits or underscores, up to 64 characters. */
127
128
  id: string;
128
129
  name: string;
129
130
  transport: 'HTTP' | 'STDIO';
@@ -273,6 +274,7 @@ export interface ClientConfiguration {
273
274
  contextDirectory: string;
274
275
  resourcesDirectory: string;
275
276
  tasksDirectory: string;
277
+ legacyTasksDirectory?: string;
276
278
  workspacesDirectory: string;
277
279
  temporaryDirectory: string;
278
280
  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.2",
3
+ "version": "0.0.6",
4
4
  "description": "AIOS agent application SDK for Node.js",
5
5
  "type": "module",
6
6
  "publishConfig": {
@@ -12,14 +12,15 @@
12
12
  },
13
13
  "dependencies": {
14
14
  "ajv": "8.20.0",
15
+ "koffi": "3.1.1",
15
16
  "tar": "7.5.22"
16
17
  },
17
18
  "optionalDependencies": {
18
- "@kmlckj/aios-runtime-win32-x64": "0.0.2",
19
- "@kmlckj/aios-runtime-darwin-x64": "0.0.2",
20
- "@kmlckj/aios-runtime-darwin-arm64": "0.0.2",
21
- "@kmlckj/aios-runtime-linux-x64": "0.0.2",
22
- "@kmlckj/aios-runtime-linux-arm64": "0.0.2"
19
+ "@kmlckj/aios-runtime-win32-x64": "0.0.6",
20
+ "@kmlckj/aios-runtime-darwin-x64": "0.0.6",
21
+ "@kmlckj/aios-runtime-darwin-arm64": "0.0.6",
22
+ "@kmlckj/aios-runtime-linux-x64": "0.0.6",
23
+ "@kmlckj/aios-runtime-linux-arm64": "0.0.6"
23
24
  },
24
25
  "exports": {
25
26
  ".": {