@kmlckj/aios-agent-server-sdk 0.0.1 → 0.0.2
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 +34 -6
- package/dist/core/auth/platform-client.d.ts +7 -1
- package/dist/index.js +4 -4
- package/dist/sdk/src/index.d.ts +19 -16
- package/dist/sdk/src/platform.d.ts +4 -0
- package/dist/sdk/src/types.d.ts +6 -93
- package/dist/shared/account-schedules-api.d.ts +110 -0
- package/dist/shared/agent-team.d.ts +2 -0
- package/dist/shared/cloud-assistant-api.d.ts +11 -499
- package/dist/shared/cloud-task-resources.d.ts +24 -0
- package/dist/shared/cloud-task-runtime-api.d.ts +253 -0
- package/dist/shared/collaboration-api.d.ts +3 -2
- package/dist/shared/collaboration-deep-link.d.ts +0 -3
- package/dist/shared/collaboration-task-api.d.ts +3 -99
- package/dist/shared/collaboration-task-execution.d.ts +39 -0
- package/dist/shared/desktop-api.d.ts +1 -0
- package/dist/shared/execution-context.d.ts +25 -0
- package/dist/shared/expert-selection.d.ts +22 -0
- package/dist/shared/local-task-command.d.ts +2 -0
- package/dist/shared/managed-authorization.d.ts +2 -0
- package/dist/shared/profession-market-api.d.ts +1 -1
- package/dist/shared/sdk-session-contract.d.ts +96 -0
- package/dist/shared/task-enterprise-project-api.d.ts +75 -0
- package/dist/shared/task-execution-api.d.ts +35 -0
- package/package.json +32 -12
- package/dist/shared/cloud-task-event-api.d.ts +0 -22
package/README.md
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
# AIOS Agent Server SDK 0.0.
|
|
1
|
+
# AIOS Agent Server SDK 0.0.2
|
|
2
2
|
|
|
3
3
|
面向 Node.js 应用的智能体开发 SDK。应用负责自己的界面和业务工具,SDK 提供智能体定义、会话、事件、审批、记忆及本地任务执行。
|
|
4
4
|
|
|
5
|
+
已有不可变智能体版本可通过 `client.openAgent(id, version)` 重新取得句柄,不改变已保存定义或重新注册工具。宿主恢复“创建 Session 成功但未收到响应”的请求时,使用原 Agent 版本、`creationId` 和创建参数;取得会话后再通过 `updateAgent` 更新配置。不存在的版本会明确报错。
|
|
6
|
+
|
|
5
7
|
## 安装与运行
|
|
6
8
|
|
|
7
9
|
```sh
|
|
@@ -16,10 +18,27 @@ SDK 调用库只发布一份,npm 根据系统和处理器架构自动安装对
|
|
|
16
18
|
- 运行时包含任务引擎、工具实现、内置技能、记忆/任务 Worker、中文 PDF 字体及必要原生资源。
|
|
17
19
|
- 不包含 Node、Git、Python、npm、Bash 发行版,也不依赖 Electron 或 CLI 终端界面。
|
|
18
20
|
- Git/Python/Bash 是按需使用的外部程序;可显式设置路径,否则探测 PATH。显式错误路径会报错,不换用其他程序。Windows 的 WSL Bash 不作为本地 Bash 使用。
|
|
19
|
-
- HTML/Markdown 转 PDF
|
|
21
|
+
- HTML/Markdown 转 PDF 与桌面端、CLI 共用 Python/ReportLab 体系的静态 HTML 渲染器,不需要 Electron、Chromium 或浏览器路径配置。外部宿主通过 `runtime.tools.python` 提供已安装 `xhtml2pdf[fonts]==0.2.28`、`reportlab==5.1.0`、`fonttools==4.65.0` 的解释器;中文字体由运行包提供。Office 转 PDF 仍使用 `document_workflow` 平台文档服务。
|
|
20
22
|
- 每次创建客户端前验证可信签名、平台/协议/数据格式及完整文件清单。修改、缺失或多出的文件都会拒绝启动。
|
|
21
23
|
- macOS x64/arm64、Linux glibc x64/arm64 使用各自的原生运行时。历史候选的验收不代替当前源码版本的构建和发布;Mac 包需 Developer ID 签名及 Apple 公证,Linux 包需发布清单签名。
|
|
22
|
-
- HTML
|
|
24
|
+
- 公共技能资源支持按目录授权;HTML 转 PDF 保留作者字体顺序,并使用随包中文字体覆盖缺失字形。转换错误作为工具错误返回,不关闭宿主。
|
|
25
|
+
- 平台专家固定版本、专家团、场景上下文及受管宿主恢复均复用公共运行时;内核独占锁与已发布连接检查防止旧进程编号复用导致误报占用,保留仍存活宿主的互斥保护及持久化会话。
|
|
26
|
+
|
|
27
|
+
## 场景上下文
|
|
28
|
+
|
|
29
|
+
`session.send` 和 `session.enqueue` 的 `sceneContext` 接受 `sceneCaseId`、`name`、`skillReferences` 及可选的 `professionId`。消息历史和排队消息保留该对象,执行时由共用运行时将场景名称及标识放入本轮上下文。应用负责从已发布场景配置获取真实名称和依赖,绑定技能仍通过 `skills` 传入,专家或专家团沿用智能体定义的固定版本。
|
|
30
|
+
|
|
31
|
+
`skillReferences` 标记场景隐式注入的技能,用于将这些实现依赖合并在场景标识中展示。切换或移除场景时,应用只移除这些依赖,保留用户另行选择的技能。场景名称与示例提示词是业务数据,不能替代技能引用、资源授权或工具能力检查。应用前端应在收到发送回执后清空本轮场景选择;SDK 历史仍保存实际发送的场景。
|
|
32
|
+
|
|
33
|
+
## 平台专家与专家团
|
|
34
|
+
|
|
35
|
+
`client.platform.experts.prepare({ professionId, versionId })` 解析明确的已发布版本,返回 `profession` 展示引用、角色 `instructions` 和可选的 `team`。将返回的指令与应用业务规则组合,再传给 `client.defineAgent`;存在 `team` 时一并传入。不传版本、不以市场最新版本替换保存任务中的版本。首次解析会沿用平台的添加/启用/可用性检查;后续恢复复用本上下文已校验的不可变版本。
|
|
36
|
+
|
|
37
|
+
云端共享项目中,选择者可能不同于执行容器负责人。已完成业务授权的宿主可用第二个参数提供 `ResolvedExpertSource`,直接编译已授权角色内容或固定专家团 ZIP。浏览器和模型只提交专家/版本标识,不能决定该来源;宿主负责确认任务访问权限及资源使用权。临时下载 URL 在交付时生成,不写入持久命令或作为版本标识。
|
|
38
|
+
|
|
39
|
+
专家团 `team.package` 由共用校验器生成,包含主理人、成员、职业、指令、最大轮数、协作流程及写入策略。通常不手工拼装它。SDK 校验其成员定义一致性,成员路径/工具受父级授权范围约束;`leader_only` 禁止成员写入,`team_shared_workspace` 沿用父级允许的写入范围。成员事件、审批和结果仍走统一会话协议,主回复与成员回复应分开呈现。包内声明的技能只是依赖描述,不会绕过当前上下文的技能可用性或权限检查。
|
|
40
|
+
|
|
41
|
+
SDK 不维护产品“最近使用”或导航来源,交由应用前端按账号保存。
|
|
23
42
|
|
|
24
43
|
## 平台模式
|
|
25
44
|
|
|
@@ -87,7 +106,7 @@ async function openHostedAgent(principal: ManagedPrincipal, credentials: Credent
|
|
|
87
106
|
|
|
88
107
|
- 回调和 Token 只保存在内存,通过经过认证的本机私有连接供 SDK 宿主及产品执行进程使用;SDK 不接收或管理 refreshToken、密码。应用可在自己的凭证服务内完成刷新。
|
|
89
108
|
- 同一执行上下文的并发请求共用一次续期;不同会话/轮次/业务上下文分别取证和缓存,不复用实例查询的凭证缓存。内存最多保留 128 个空闲凭证上下文,淘汰后重新向应用取证;正在取证的请求不受这个缓存容量限制。HTTP 401 只允许使用新凭证再发送一次;再次被拒则撤销授权。普通服务错误、网络结果未知、流式上传不会被这层自动重放。
|
|
90
|
-
-
|
|
109
|
+
- 平台模型的调用地址直接采用经过身份验证的模型详情,模型网关无需再配置一份可信来源。普通请求仍仅向平台地址发送凭证;应用如需访问额外的非模型服务,可使用 `authentication.allowedOrigins`。带平台凭证的请求不自动跟随重定向。
|
|
91
110
|
- `auth.refreshManaged()` 返回公开会话;`auth.revokeManaged()` 撤销本机托管授权,不等于注销平台账号或回滚已发出的请求。返回 `null` 同样撤销;恢复须显式续期。托管模式不允许密码/网页登录、身份切换以及 `getToken()` / `refresh()` 导出凭据。
|
|
92
111
|
- 一个实例绑定一个平台主体,不能在续期时更换用户、租户或工作区,也不能通过 `configure()` 切换认证方式或平台;需要时创建新客户端。主体同时参与数据目录分区。实例重启后必须重新提供回调,不能从历史恢复 Token。
|
|
93
112
|
- 每个实例只能有一个在线凭证提供者。其他客户端可以不传 `credentials`,作为同配置观察连接。提供者客户端必须在任务和后台工作仍需要平台授权时保持存活;其 `close()` 会关闭回调,后续平台请求将返回真实授权错误。工具授权错误仍作为工具结果交给模型处理。
|
|
@@ -150,6 +169,12 @@ const dependencies = await client.dependencies();
|
|
|
150
169
|
const skills = await client.skills.importPaths([absoluteSkillDirectory]);
|
|
151
170
|
```
|
|
152
171
|
|
|
172
|
+
服务端分发固定版本时使用 `client.skills.importVersion({ packagePath, folderName, packageSha256 })`。
|
|
173
|
+
`packagePath` 是当前执行环境的绝对路径,`packageSha256` 是所选压缩包的 SHA-256;先验证完整字节再解包。
|
|
174
|
+
压缩包支持根目录直接包含 `SKILL.md`,或包含一个带 `SKILL.md` 的顶层目录;子目录中的技能说明和脚本保留在同一个包中。
|
|
175
|
+
`folderName` 由调用方为版本分配唯一名称,同一名称重复导入必须内容一致,不覆盖其他版本或正在运行的任务选择。
|
|
176
|
+
返回值可作为当前轮 `skills: [{ source: 'LOCAL', folderName, name, description, executionScope }]` 的选择,不修改其他会话的技能配置。
|
|
177
|
+
|
|
153
178
|
`enabled` 表示能力选择结果;`available` 表示当前模式、实现和依赖是否满足,并提供 `reason`。平台权限、模型能力、外部服务连接仍在实际调用时验证。`pdf_artifact.operations` 单独列出 HTML/Markdown 转换依赖;`document_workflow.operations` 的 `office-to-pdf` 表示平台办公文件转换,独立模式返回 `requires-platform`,平台模式关闭工具时返回 `disabled`。
|
|
154
179
|
|
|
155
180
|
Office 转 PDF 通过任务调用共享内置工具,工具参数为 `{ action: 'analyze', file: '报告.docx', outputs: ['pdf'] }`,同样适用于平台服务支持的 Excel、PPT 文件。转换会上传源文件至当前配置的平台文档服务,并将校验后的产物保存到任务工作区;不依赖桌面渲染,也不新增 `libreOfficeExecutable`。例如向已登录平台模式的会话发送:
|
|
@@ -206,9 +231,10 @@ return toolResult({
|
|
|
206
231
|
- `run.events({ cursor, signal })`:增量事件;处理完一条后可保存其 `cursor`,下次从该位置恢复。用事件 `id` 去重;`sequence` 是该游标流内的顺序号,`runtimeSequence`(若存在)保留运行时原始序号。事件还包含 `schemaVersion: 1`、`sessionId`、`runId`。
|
|
207
232
|
- `session.events({ cursor, signal })` / `eventPage()`:跨轮观察整个会话,保留一轮结束后才到达的积分等更新。事件保留工具详情、子线程/团队标识和可信业务 `context`,不会在一轮完成时关闭。详见 [事件与前端接入](EVENTS.md)。浏览器入口 `@kmlckj/aios-agent-server-sdk/events` 提供同源工具短句辅助函数及事件类型。
|
|
208
233
|
- `run.wait({ signal })`:等待当前运行完成或需要用户输入;`waiting` 不表示任务完成。`events`、`wait`、`state` 的 AbortSignal 只取消观察,不发送任务取消命令。
|
|
209
|
-
- `run.approve()` / `answer()` / `confirmPlan()
|
|
234
|
+
- `run.approve()` / `answer()` / `cancelInput()` / `confirmPlan()`:审批、补充回答、取消补充输入、计划确认。`cancelInput(requestId, commandId?)` 取消该轮指定的输入请求,不能用普通回答冒充取消。
|
|
210
235
|
- `run.cancel()`:仅取消该 runId;不会误取消之后开始的运行。
|
|
211
|
-
- `session.receipt(commandId)
|
|
236
|
+
- `session.receipt(commandId)`:发送结果丢失时查询原命令;返回 `null` 或 `disposition` 为 `accepted / duplicate / reconciling / rejected` 的回执,拒绝原因在回执的 `code / message`,不是内部日志的 `rejection` 字段。排队回执先返回 `messageId`,调度或补充到活动执行后返回真实 `runId`;不换新 ID 自动重试副作用操作。
|
|
237
|
+
- `run.cancel(commandId)`、`run.approve(toolCallId, decision, commandId)`、`run.answer(requestId, response, commandId)`、`run.cancelInput(requestId, commandId)`、`run.confirmPlan(commandId)` 和 `session.compact(commandId)` 均允许宿主指定命令 ID。HTTP 调用方须先保存该 ID;确认重试时使用相同输入与 ID,通过原 Session 查询回执。省略时 SDK 为一次独立调用生成 ID。`confirmPlan` 和 `compact` 返回的 Run 同时携带 `commandId`。
|
|
212
238
|
- `session.resumeRun(runId)`:重新观察原轮次;无需再次发送用户问题。
|
|
213
239
|
- `session.runs({ cursor, limit }, signal?)` 分页读取当前会话的运行记录,包含真实状态、消息数、消息/队列/终态时间和可信业务上下文。时间字段分别对应原日志,不冒充模型请求开始时间。列表派生自既有消息、终态索引和队列,不新增运行数据库;没有终态证据的旧执行显示 `interrupted`。列表有变化或游标跨会话时返回 `RUN_LIST_CONFLICT`,从首屏重新读取;单轮详情继续用 `resumeRun(id).state()/events()`。
|
|
214
240
|
- `session.queryHistory({ text, around, cursor, limit })`:分页搜索或定位消息。`clear({ historyVersion, cancelActive })` 清空目标会话的消息、事件、交互、原生上下文和阶段交接;`delete(...)` 删除会话记录。两者保留业务文件;自动工作区删除后移动至返回的 `retainedWorkspace`,其他会话仍引用该目录时拒绝移动。`historyVersion` 来自 `queryHistory()` 或 `queue()`,活动任务需要明确 `cancelActive: true`。
|
|
@@ -299,6 +325,8 @@ Windows 沙箱模式属于整个执行组件,父任务和成员不能声明互
|
|
|
299
325
|
|
|
300
326
|
父任务等待所属成员收敛,成员结果只向模型交付一次;应用调用 wait 观察结果不会消耗模型的结果。宿主排空时允许 wait/stop/close,不接受新委派。`teamState()` 无活动宿主时读取真实保存状态并返回 `ownerAvailable: false`;没有历史状态时返回 null,不伪造成功或重放任务。中断成员再委派时先恢复原线程与当前路由。
|
|
301
327
|
|
|
328
|
+
运行时自动记录成员任务的开始和完成状态。委派、追问以及等待的工具结果均提供 `task`(`workflow_task_id`、`team_run_id`、`owner_member_id`、`status`、`revision`),对应结果读取时的实际共享任务状态。正常开始或结束后无需重复更新状态;需要修改任务定义、负责人或状态时,先获取当前任务版本,再使用该 `revision` 更新。旧版本仍会被并发校验拒绝,不会自动覆盖其他成员的修改。
|
|
329
|
+
|
|
302
330
|
独立后台工作使用普通 Session,与父轮内的成员分开管理:
|
|
303
331
|
|
|
304
332
|
```ts
|
|
@@ -9,7 +9,9 @@ export type PlatformFetch = (input: string, init?: RequestInit) => Promise<Respo
|
|
|
9
9
|
export type PlatformHttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
10
10
|
export interface PlatformRequestInput {
|
|
11
11
|
method: PlatformHttpMethod;
|
|
12
|
-
path: `/api/${string}`;
|
|
12
|
+
path: `/api/${string}` | `/agent/api/${string}`;
|
|
13
|
+
/** Runtime APIs use HTTP status and a native JSON body, without a platform envelope. */
|
|
14
|
+
responseFormat?: 'native';
|
|
13
15
|
query?: Record<string, string | number | boolean | undefined>;
|
|
14
16
|
body?: unknown;
|
|
15
17
|
formData?: FormData;
|
|
@@ -19,6 +21,10 @@ export interface PlatformRequestInput {
|
|
|
19
21
|
emptyTenantContext?: boolean;
|
|
20
22
|
/** Resource binding scope. null explicitly selects personal scope. */
|
|
21
23
|
tenantId?: string | null;
|
|
24
|
+
/** Explicit resource scope; null omits the browser/desktop-selected workspace. */
|
|
25
|
+
workspaceId?: string | null;
|
|
26
|
+
/** Keep delayed writes and token refresh retries bound to their initiating account. */
|
|
27
|
+
expectedUserId?: string;
|
|
22
28
|
}
|
|
23
29
|
export interface PlatformAuthorizationProvider {
|
|
24
30
|
getAuthorization(): Promise<{
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{randomUUID as
|
|
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
2
|
$ErrorActionPreference = 'Stop'
|
|
3
3
|
$ProgressPreference = 'SilentlyContinue'
|
|
4
4
|
$env:PSModulePath = Join-Path $PSHOME 'Modules'
|
|
@@ -10,7 +10,7 @@ try {
|
|
|
10
10
|
[Console]::Error.WriteLine($_.Exception.ToString())
|
|
11
11
|
exit 1
|
|
12
12
|
}
|
|
13
|
-
`;return["-NoLogo","-NoProfile","-NonInteractive","-OutputFormat","Text","-EncodedCommand",Buffer.from(e,"utf16le").toString("base64")]}var
|
|
13
|
+
`;return["-NoLogo","-NoProfile","-NonInteractive","-OutputFormat","Text","-EncodedCommand",Buffer.from(e,"utf16le").toString("base64")]}var kt=String.raw`
|
|
14
14
|
$spec = [Console]::In.ReadToEnd() | ConvertFrom-Json
|
|
15
15
|
try { $item = Get-Item -LiteralPath $spec.path -Force }
|
|
16
16
|
catch [Management.Automation.ItemNotFoundException] { exit 3 }
|
|
@@ -50,6 +50,6 @@ if ($spec.secure) {
|
|
|
50
50
|
foreach ($rule in $acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier])) {
|
|
51
51
|
if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -ne $sid.Value -and $rule.IdentityReference.Value -ne 'S-1-5-18') { throw 'Storage is accessible by another principal' }
|
|
52
52
|
}
|
|
53
|
-
`;function ke(r,e){let t=vt(Ee(),Ue(Et),{input:JSON.stringify({path:r,secure:e}),windowsHide:!0,timeout:15e3,encoding:"utf8",maxBuffer:65536});kt(r,t.status,t.error,t.stderr)}function kt(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 xt(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 H(r){if(process.platform==="linux"){let e=xt(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 ce(r){N.mkdirSync(r,{recursive:!0,mode:448});let e=N.lstatSync(r);if(!e.isDirectory()||e.isSymbolicLink()||process.getuid&&e.uid!==process.getuid())throw new O("UNSAFE_DATA_DIRECTORY","CLI 私有目录的类型或所有者不正确。",1);process.platform==="win32"?ke(r,!0):N.chmodSync(r,448)}function Ae(r){let e=bt("sha256").update(r).digest("hex").slice(0,32),t=G.join(process.platform==="win32"?ze.tmpdir():"/tmp",`aios-cli-${process.getuid?.()??ze.userInfo().username}`);return{lock:G.join(r,"daemon.lock"),mutex:G.join(r,"daemon-owner.sqlite"),metadata:G.join(r,"daemon.json"),socketDirectory:t,socket:process.platform==="win32"?`\\\\.\\pipe\\aios-cli-${e}`:G.join(t,`${e}.sock`)}}function Tt(r){let e=N.lstatSync(r,{throwIfNoEntry:!1});if(e&&(!e.isFile()||e.isSymbolicLink()))throw new O("UNSAFE_DAEMON_METADATA","服务所有权文件的类型、权限或所有者不正确。",1);return e}function xe(r){let e=Tt(r);try{process.platform==="win32"&&e&&ke(r,!1)}catch(t){if(t.code==="ENOENT")return;throw t}return Ct(r)}function Ct(r){let e;try{e=N.openSync(r,N.constants.O_RDONLY|N.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=N.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(N.readFileSync(e,"utf8"))}catch(n){throw n instanceof SyntaxError?new O("INVALID_DAEMON_METADATA","服务所有权记录损坏,原文件已保留。",1):n}}finally{N.closeSync(e)}}var Rt=1,qr=8*1024*1024;function be(r){if(!r||typeof r!="object")return!1;let e=r;return e.protocol===Rt&&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 Be(r){let e=Ae(r),t=xe(e.metadata);if(!be(t)||t.root!==r||t.socket!==e.socket||!H(t.pid))throw new f("CLI_NOT_RUNNING","请先启动指定数据目录的 CLI 后台服务。");if("sdkProtocol"in t)throw new f("RUNTIME_INCOMPATIBLE","该数据目录属于精简运行时,请使用 createClient。");return t}function F(r){let e=Ae(r),t=xe(e.metadata);if(t!==void 0){if(!be(t)||t.root!==r||t.socket!==e.socket||!("sdkProtocol"in t)||t.sdkProtocol!==1)throw new f("RUNTIME_INCOMPATIBLE","本机服务不支持当前 SDK 协议,或其归属记录不一致。");return H(t.pid)?t:void 0}}async function He(r,e){for(;;){e.throwIfAborted();let t=F(r);if(t)return t;await Pt(100,void 0,{signal:e})}}function de(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,u)=>{let d=l=>u(i?.aborted?i.reason:new f("OUTCOME_UNKNOWN",`请求 ${o} 的结果未知,请使用原命令 ID 查询回执。`,{cause:l})),m=Ot.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 f("SDK_UNSUPPORTED","此 CLI 版本未提供 SDK 接口,请使用包含 SDK 接口的版本。");let p=JSON.parse(Buffer.concat(y).toString("utf8"));if(p.id!==o||typeof p.ok!="boolean")throw new f("INVALID_RESPONSE","SDK 响应与请求不匹配。");if(!p.ok)throw new f(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 V from"node:path";import{createHash as Nt}from"node:crypto";function Te(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 L(r){let e=r.mode==="platform"?Te(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 V.join(V.resolve(r.runtime.dataDirectory),"applications",n)}function Fe(r){let e=L(r),t=V.basename(e),n=(o,i)=>o?V.join(V.resolve(o),"applications",t,i):V.join(e,i);return{workspaces:n(r.runtime.workspaceDirectory,"workspaces"),cache:n(r.runtime.cacheDirectory,"cache"),temporary:n(r.runtime.temporaryDirectory,"tmp")}}import Ce from"node:path";function Ve(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 qe(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 Je(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=(...I)=>{let U=I.map(k=>s[k]).find(k=>typeof k=="string"&&k.trim());return typeof U=="string"?U:null},c=a("sub"),u=a("tenantId","tenant_id"),d=a("workspaceId","workspace_id")??o.context?.currentWorkspaceId??null;if(c!==e.userId||u!==e.tenantId||d!==e.workspaceId||(o.context?.currentTenantId??null)!==e.tenantId||(o.context?.currentWorkspaceId??null)!==e.workspaceId)throw A("MANAGED_IDENTITY_MISMATCH","托管凭证续期不得改变用户、租户或工作区。");let m=Date.parse(o.accessTokenExpiresAt);if(!Number.isFinite(m)||m<=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(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:h,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:h,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 Ke(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 Ge(r,e){return e?.methodTimeoutMs?.[r]??(r==="runtime.drain"?0:e?.rpcTimeoutMs??12e4)}function Xe(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 We(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(Ve({mode:"standalone",appId:r.appId,userScope:r.userScope}),Ke(r.communication),We(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(Xe)}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()||!Ce.isAbsolute(t)))throw new Error(`${e} 必须是绝对目录路径。`)}return{...structuredClone(r),runtime:{...structuredClone(r.runtime),directory:Ce.resolve(r.runtime.directory),dataDirectory:Ce.resolve(r.runtime.dataDirectory)},...r.mode==="platform"?{platformBaseUrl:Te(r.platformBaseUrl),...r.authentication!==void 0?{authentication:qe(r.authentication,r.platformBaseUrl)}:{}}:{}}}import{setTimeout as Lt}from"node:timers/promises";import D from"node:fs";import P from"node:path";import{createHash as Qe,verify as Mt}from"node:crypto";var Ye=`-----BEGIN PUBLIC KEY-----
|
|
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-----
|
|
54
54
|
MCowBQYDK2VwAyEAH1NI5TKlc89zXnULhsNPzgN4M1ki3w5spKY7BH8VsZw=
|
|
55
|
-
-----END PUBLIC KEY-----`;var le={version:"0.0.1",protocol:1,dataFormat:1,profile:"light"};var M=r=>new f("RUNTIME_INTEGRITY_FAILED",r);function Ze(r,e){let t=P.relative(r,e);return t!==".."&&!t.startsWith(`..${P.sep}`)&&!P.isAbsolute(t)}async function b(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!==le.version||i.protocol!==le.protocol||i.dataFormat!==le.dataFormat||i.platform!==process.platform||i.arch!==process.arch||i.profile!=="light")throw new f("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()||!Mt(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),h=P.relative(t,v).split(P.sep).join("/");if(["aios-sdk-runtime.json","signature.json"].includes(h))continue;let w=D.lstatSync(v);w.isDirectory()&&!w.isSymbolicLink()?d(v):u.set(h,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),h=u.get(p);if(!p||p.includes("\\")||P.posix.normalize(p)!==p||!Ze(t,v)||!h)throw M(`运行时文件路径或归属不匹配:${p}`);if(S.type==="link"){if(!h.isSymbolicLink()||typeof S.link!="string"||P.isAbsolute(S.link)||D.readlinkSync(v)!==S.link||!Ze(t,D.realpathSync(v)))throw M(`运行时链接不匹配:${p}`)}else if(S.type==="file"){if(!h.isFile()||h.isSymbolicLink()||h.size!==S.size||!/^[a-f0-9]{64}$/.test(S.sha256)||process.platform!=="win32"&&(h.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++],h=Qe("sha256");for await(let w of D.createReadStream(p))h.update(w);if(h.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:Qe("sha256").update(o).digest("hex")}}import Re from"node:fs";import et from"node:path";import{spawn as Dt}from"node:child_process";function ue(r){let{options:e}=r,t=L(e);ce(t);let n=Fe(e).temporary;Re.mkdirSync(n,{recursive:!0});let o=Re.openSync(et.join(t,"sdk-host.log"),"a",384),i=(()=>{try{return Dt(e.runtime.nodeExecutable??process.execPath,[et.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{Re.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 f("RUNTIME_START_TIMEOUT","SDK 服务未在指定时间内完成启动,请检查宿主日志。")),e.communication?.startupTimeoutMs??12e4),m=(g,p)=>y(new f("RUNTIME_START_FAILED",`SDK 服务启动进程退出(${g??p})。`)),l=g=>{if(!g||g.type!=="ready"){y(new f("RUNTIME_INCOMPATIBLE","宿主未返回当前 SDK 启动协议,请使用配套运行包。"));return}g.ok?y(void 0,g.value):y(new f(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=tt();static async start(e,t){let n=X(e),o=_t.resolve(n.runtime.directory),i=await b(o,n.runtime.trustedPublicKey),s=L(n),a=F(s);if(!a){let{child:c,ready:u}=ue({options:n,verifiedPackage:i});try{a=await u}catch(d){if(!(d instanceof f)||d.code!=="DAEMON_ALREADY_OWNED")throw d;a=await He(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=tt(),o){return this.closed?Promise.reject(new f("RUNTIME_CLOSED","SDK 客户端连接已关闭。")):this.ownerExit?.aborted?Promise.reject(this.ownerExit.reason):de(this.metadata,this.clientId,e,t,n,o,Ge(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(;F(this.metadata.root)?.instanceId===this.metadata.instanceId||H(this.metadata.pid);)await Lt(100,void 0,{signal:e})}};import $t from"node:path";import{randomUUID as rt}from"node:crypto";var pe=class r{constructor(e){this.metadata=e}closed=!1;clientId=rt();static async connect(e){let t=new r(Be($t.resolve(e.dataDirectory)));return await t.call("attach",{sdkProtocol:1,options:e,pid:process.pid}),t}call(e,t={},n=rt(),o){return this.closed?Promise.reject(new f("RUNTIME_CLOSED","SDK 客户端连接已关闭。")):de(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 Bt from"node:http";import{randomBytes as Ht,randomUUID as Ft,timingSafeEqual as Vt}from"node:crypto";import{Ajv as qt}from"ajv";import{Ajv2020 as Jt}from"ajv/dist/2020.js";function Ut(r){let e={...r,kind:"aios-tool-result"};return Oe(e),e}function q(r,e){if(typeof r!="string"||!r.trim())throw new Error(`工具返回的 ${e} 必须是非空字符串。`)}function Oe(r){if(!r||typeof r!="object"||!("kind"in r)||r.kind!=="aios-tool-result")return{content:[{type:"text",text:typeof r=="string"?r:JSON.stringify(r??null)}],isError:!1};let e=r;if(!Array.isArray(e.content))throw new Error("工具返回的 content 必须是数组。");let t=e.content.map(n=>{if(!n||typeof n!="object")throw new Error("工具返回的内容格式无效。");if(n.type==="text"){if(typeof n.text!="string")throw new Error("工具返回的 text 必须是字符串。");return{type:"text",text:n.text}}if(n.type==="image")return q(n.data,"image.data"),q(n.mimeType,"image.mimeType"),{type:"image",data:n.data,mimeType:n.mimeType};if(n.type==="resource"){let o=n.resource;q(o?.uri,"resource.uri"),new URL(o.uri),o.mimeType!==void 0&&q(o.mimeType,"resource.mimeType");let i="text"in o,s="blob"in o;if(i===s||i&&typeof o.text!="string"||s&&typeof o.blob!="string")throw new Error("工具文件内容必须且只能包含 text 或 blob。");return{type:"resource",resource:{uri:o.uri,...o.mimeType?{mimeType:o.mimeType}:{},...i?{text:o.text}:{blob:o.blob}}}}throw new Error("不支持的工具内容类型。")});if(e.data!==void 0){if(!e.data||typeof e.data!="object"||Array.isArray(e.data))throw new Error("工具返回的 data 必须是 JSON 对象。");t.push({type:"text",text:JSON.stringify(e.data)})}return e.error!==void 0&&(q(e.error.code,"error.code"),q(e.error.message,"error.message"),t.push({type:"text",text:JSON.stringify({error:e.error})})),{content:t,isError:e.error!==void 0}}var nt=["projectId","collaborationProjectId","assistantId","platformSessionId","platformTurnId","platformTaskId","platformRunId","traceId"];function Y(r){if(!r||typeof r!="object"||Array.isArray(r))throw new Error("执行上下文必须为对象。");return r}function $(r){if(typeof r!="string"||!r.trim()||r.length>512||/[\x00-\x1f\x7f]/.test(r))throw new Error("执行上下文字段必须为有效字符串,最多 512 字符。");return r}function ot(r){let e=Y(r);if(Object.keys(e).some(t=>!["userId","tenantId","name"].includes(t)))throw new Error("执行主体包含未知字段。");return{userId:$(e.userId),tenantId:e.tenantId===null?null:$(e.tenantId),...e.name===void 0?{}:{name:$(e.name)}}}function zt(r){let e=Y(r);if(Object.keys(e).some(n=>!["actor","owner","workspaceId","usageScene","metadata",...nt].includes(n)))throw new Error("执行上下文包含未知字段。");if(!["personal","greeting","task","collaboration","coding"].includes(String(e.usageScene)))throw new Error("执行用量场景无效。");let t={actor:ot(e.actor),owner:ot(e.owner),workspaceId:e.workspaceId===null?null:$(e.workspaceId),usageScene:e.usageScene};for(let n of nt)e[n]!==void 0&&(t[n]=$(e[n]));if(e.metadata!==void 0){let n=Y(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=Y(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 me(r){let e=Y(r);if(Object.keys(e).some(t=>!["sessionId","runId","context"].includes(t)))throw new Error("执行绑定包含未知字段。");return{sessionId:$(e.sessionId),runId:$(e.runId),...e.context===void 0?{}:{context:zt(e.context)}}}async function it(r,e,t){let n=new Map,o=new qt({strict:!0,strictTypes:!1,allErrors:!0,validateFormats:!1}),i=new Jt({strict:!0,strictTypes:!1,allErrors:!0,validateFormats:!1}),s=new Map;for(let h of e){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(h.name)||n.has(h.name))throw new Error(`业务工具名称无效或重复:${h.name}`);if(h.inputSchema.type!=="object")throw new Error(`业务工具 ${h.name} 的输入 schema 必须为 object。`);n.set(h.name,h);let w=h.inputSchema.$schema==="http://json-schema.org/draft-07/schema#"?o:i;s.set(h.name,w.compile(h.inputSchema))}let a=Ht(32).toString("hex"),c=new Map,u=new Set,d=!1,m,l,y=new Promise(h=>{l=h}),g=()=>m??=(async()=>{for(let h of c.values())h.abort(new Error("应用工具提供者已关闭。"));S.closeAllConnections(),await new Promise((h,w)=>S.close(_=>_?w(_):h())),l()})(),p=()=>{d&&u.size===0&&c.size===0&&g()},S=Bt.createServer(async(h,w)=>{let _=Buffer.from(`Bearer ${a}`),Se=Buffer.from(h.headers.authorization??"");if(Se.length!==_.length||!Vt(Se,_)){w.writeHead(401).end();return}if(h.url!=="/mcp"){w.writeHead(404).end();return}let I=h.headers["mcp-session-id"];if(h.method==="DELETE"&&typeof I=="string"&&u.delete(I)){for(let[C,z]of c)C.startsWith(`${I}:`)&&z.abort(new Error("工具会话已关闭。"));w.writeHead(204).end(),p();return}if(h.method!=="POST"){w.writeHead(405).end();return}let U=null,k=(C,z=!1)=>{w.writeHead(200,{"content-type":"application/json","cache-control":"no-store"}),w.end(JSON.stringify({jsonrpc:"2.0",id:U,...z?{error:C}:{result:C}}))};try{let C=0,z=[];for await(let E of h){let B=Buffer.from(E);if(C+=B.length,C>8*1024*1024)throw new Error("业务工具请求超过 8 MiB。");z.push(B)}let R=JSON.parse(Buffer.concat(z).toString("utf8"));if(U=R.id??null,R.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(R.method==="notifications/cancelled"){c.get(`${I}:${String(R.params?.requestId)}`)?.abort(new Error("工具调用已取消。")),w.writeHead(202).end();return}if(R.id===void 0){w.writeHead(202).end();return}if(R.method==="ping"){k({});return}if(R.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(R.method!=="tools/call"){k({code:-32601,message:"不支持的 MCP 方法。"},!0);return}let Ie=n.get(String(R.params?.name));if(!Ie)throw new Error("业务工具不存在。");let J=R.params?.arguments;if(!J||typeof J!="object"||Array.isArray(J))throw new Error("工具参数必须是对象。");let _e=s.get(Ie.name);if(!_e(J)){k({content:[{type:"text",text:`工具参数不符合声明:${JSON.stringify(_e.errors)}`}],isError:!0});return}let K=new AbortController,se=`${I}:${String(U)}`;if(c.has(se))throw new Error("工具请求 ID 正在执行,不能重复提交。");c.set(se,K);let Le=()=>{w.writableEnded||K.abort(new Error("工具请求连接已关闭。"))};w.once("close",Le);try{let B=R.params?._meta?.["aios/execution"],{invocationId:ve,...yt}=B??{},ae=B===void 0?void 0:me(yt);if(B&&(typeof ve!="string"||!ve))throw new Error("工具调用标识缺失。");let wt=await Ie.execute(J,{signal:K.signal,callId:se,...ae&&t?{files:{resolve:(St,It)=>t(ae.sessionId,St,It,K.signal)}}:{},...ae?{execution:st({...ae,invocationId:ve})}:{}});K.signal.throwIfAborted(),k(Oe(wt))}catch(E){k({content:[{type:"text",text:E instanceof Error?E.message:String(E)}],isError:!0})}finally{w.removeListener("close",Le),c.delete(se),p()}}catch(C){k({code:-32602,message:C instanceof Error?C.message:String(C)},!0)}});return await new Promise((h,w)=>{S.once("error",w),S.listen(0,"127.0.0.1",h)}),{descriptor:{id:r,name:r,transport:"HTTP",url:`http://127.0.0.1:${S.address().port}/mcp`,bearerToken:a,tools:e.map(h=>h.name),defaultToolsApproval:"prompt",toolApprovals:Object.fromEntries(e.map(h=>[h.name,h.readOnly?"auto":"prompt"]))},close:g,closed:y,status:()=>({retired:d,sessions:u.size,calls:c.size,closing:!!m}),retire:()=>{d=!0,p()}}}function st(r){return r&&typeof r=="object"&&(Object.values(r).forEach(st),Object.freeze(r)),r}import{createHash as Wt}from"node:crypto";var Kt=/^[a-z][a-z0-9_]{0,63}$/u;function Gt(r){return r.trim().toLowerCase()}function Pe(r){let e=Gt(r);if(!Kt.test(e))throw new Error("MCP 技能引用标识只能包含小写字母、数字和下划线,必须以字母开头,最长 64 个字符");return e}function Xt(r){return`aios_mcp_${Pe(r)}`}function at(r,e){let t=e.trim();if(!t)throw new Error("MCP 工具名称不能为空");return`mcp__${Xt(r)}__${t}`}function fe(r){return r.toolProviderId===void 0?`app_${Wt("sha256").update(JSON.stringify([r.id,r.version])).digest("hex").slice(0,32)}`:Pe(r.toolProviderId)}function Ne(r,e){if(!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(e))throw new Error("业务工具名称无效。");return at(fe(r),e)}import{randomUUID as Yt}from"node:crypto";function je(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 he(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 ge=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 he(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}},()=>he(()=>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 he(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}},()=>he(async()=>s.return?.(),async()=>{a&&await this.call("close",{transferId:a.id})}))}};import Qt from"node:http";import{randomBytes as Zt,timingSafeEqual as er}from"node:crypto";async function ct(r){let e=Zt(32).toString("hex"),t=new Set,n=Qt.createServer(async(i,s)=>{let a=Buffer.from(`Bearer ${e}`),c=Buffer.from(i.headers.authorization??"");if(c.length!==a.length||!er(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 dt(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 lt(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 cr from"node:http";import{randomBytes as dr,timingSafeEqual as lr}from"node:crypto";var tr="[REDACTED]",rr="(?:密码|口令|密钥|令牌|私钥|凭据|验证码)",nr=new RegExp(`(${rr}\\s*["']?\\s*(?:[::=]|是(?!否)|为)\\s*)(?:"([^"]*)"|'([^']*)'|“([^”]*)”|‘([^’]*)’|([^\\s"'“”‘’,。;,;}]+))`,"gu");var or=["authorization","password","passwd","passphrase","token","api[-_]?key","secret","cookie","credentials?","private[-_]?key","pat"].join("|"),ut=`(?:[a-z0-9]+[-_])*(?:${or})`,ir=new RegExp(`(\\b${ut}\\b["']?\\s*[:=]\\s*["']?)([^\\s"',};&,。;]+)`,"gi"),sr=new RegExp(`([?&]${ut}=)([^&#\\s]*)`,"gi");function pt(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(sr,"$1[REDACTED]").replace(ir,"$1[REDACTED]").replace(nr,(e,t,n,o,i,s)=>{let a=n!==void 0?['"','"']:o!==void 0?["'","'"]:i!==void 0?["“","”"]:s!==void 0?["‘","’"]:["",""];return`${t}${a[0]}${tr}${a[1]}`})}import{randomUUID as ar}from"node:crypto";var ye=class{id=ar();sequence=0;records=[];listeners=new Set;closed=!1;publish(e){this.records.push({...structuredClone(e),cursor:`${this.id}:${++this.sequence}`,occurredAt:new Date().toISOString()}),this.records.length>256&&this.records.shift(),this.wake()}close(){this.closed=!0,this.wake()}wake(){for(let e of this.listeners)e()}async*stream(e={}){let t=this.sequence-this.records.length;if(e.after!==void 0){let[n,o,i]=e.after.split(":");if(t=Number(o),n!==this.id||i!==void 0||!/^\d+$/.test(o??"")||!Number.isSafeInteger(t)||t>this.sequence)throw A("AUTH_EVENT_CURSOR_INVALID","授权事件游标不属于当前凭证提供者。")}for(;;){e.signal?.throwIfAborted();let n=this.sequence-this.records.length;if(t<n)throw A("AUTH_EVENT_CURSOR_EXPIRED","授权事件游标已超出内存保留范围,请重新读取授权状态。");let o=this.records[t-n];if(o){t++,yield structuredClone(o);continue}if(this.closed)return;await new Promise((i,s)=>{let a=()=>{this.listeners.delete(c),e.signal?.removeEventListener("abort",u)},c=()=>{a(),i()},u=()=>{a(),s(e.signal.reason)};this.listeners.add(c),e.signal?.addEventListener("abort",u,{once:!0})})}}};var we=class{constructor(e,t,n){this.authentication=e;this.platformBaseUrl=t;this.provider=n}events=new ye;entries=new Map;sequence=0;epoch=0;revoked=!1;closed=!1;expiration;execution(e){if(e===void 0)return;let t=me(e),{context:n}=t,o=this.authentication.principal;if(n&&(n.actor.userId!==o.userId||n.actor.tenantId!==o.tenantId||n.workspaceId!==o.workspaceId))throw A("EXECUTION_PRINCIPAL_MISMATCH","凭证请求的操作者、租户和空间与实例主体不一致。");return n&&(Object.freeze(n.actor),Object.freeze(n.owner),Object.freeze(n)),Object.freeze(t)}clear(){this.epoch++;for(let e of this.entries.values())e.controller.abort(A("MANAGED_AUTHORIZATION_CHANGED","解析凭证期间授权已改变。"));this.entries.clear(),clearTimeout(this.expiration)}revoke(e,t){let n=this.execution(e);return t!==void 0&&this.entries.get(JSON.stringify(n)??"")?.generation!==t?!1:(this.clear(),this.revoked=!0,this.events.publish({type:"invalidated",scope:"provider",reason:"revoked",execution:n,code:"MANAGED_AUTHORIZATION_REVOKED"}),!0)}async resolve(e,t,n){if(this.closed)throw A("MANAGED_PROVIDER_UNAVAILABLE","凭证提供者已关闭。");if(this.revoked&&e!=="explicit")throw A("MANAGED_AUTHORIZATION_REVOKED","应用托管授权已撤销。");let o=this.execution(t),i=JSON.stringify(o)??"";if(e==="explicit"&&o)throw new Error("显式刷新作用于整个实例,不能指定单轮上下文。");let s=this.entries.get(i);if(e==="explicit"&&(!s?.pending||s.reason!=="explicit")&&(this.clear(),s=void 0),s||(s={execution:o,generation:0,controller:new AbortController}),this.entries.delete(i),this.entries.set(i,s),s.pending)await s.pending;else{let a=e==="explicit"||e==="rejected"&&n===s.generation;if(a||!s.cached||s.cached.expiresAt<=Date.now()+3e4){let c=a?e:s.cached||s.expired?"expiring":"initial";s.cached=void 0;let u=this.epoch;s.reason=c;let d=this.load(s,c,u);s.pending=d;try{await d}finally{s.pending===d&&(s.pending=void 0),this.trim()}}}if(!s.cached||s.controller.signal.aborted)throw A("MANAGED_AUTHORIZATION_CHANGED","解析凭证期间授权已改变。");return{...s.cached.credential,generation:s.generation}}trim(){for(let[e,t]of this.entries){if(this.entries.size<=128)return;t.pending||this.entries.delete(e)}}async load(e,t,n){try{let o=await this.provider({reason:t,signal:e.controller.signal,execution:e.execution});if(e.controller.signal.throwIfAborted(),n!==this.epoch)throw A("MANAGED_AUTHORIZATION_CHANGED","解析凭证期间授权已改变。");if(o===null)throw this.revoke(),A("MANAGED_AUTHORIZATION_REVOKED","应用未提供有效授权。");e.cached=Je(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 mt(r,e,t){let n=dr(32).toString("hex"),o=new we(r,e,t),i=cr.createServer(async(s,a)=>{let c=Buffer.from(`Bearer ${n}`),u=Buffer.from(s.headers.authorization??"");if(c.length!==u.length||!lr(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:pt(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 ur}from"node:crypto";import{setTimeout as ft}from"node:timers/promises";var Q=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??ur()});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 f("LOGIN_ALREADY_COMPLETED","网页登录已完成,请读取登录结果。");await ft(150,void 0,e)}}async wait(e={}){for(;;){e.signal?.throwIfAborted();let t=await this.status();if(this.checkFailure(t),t.state==="completed"&&t.session)return t.session;await ft(250,void 0,e)}}checkFailure(e){if(e.state==="failed")throw new f(e.error.code,e.error.message);if(e.state==="cancelled")throw new f("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")};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 j from"node:fs";import T from"node:path";import{createHash as pr}from"node:crypto";import{createRequire as mr}from"node:module";import{t as fr,x as hr}from"tar";var gr=mr(import.meta.url),yr=["win32-x64","darwin-x64","darwin-arm64","linux-x64","linux-arm64"];function wr(r=`${process.platform}-${process.arch}`){if(!yr.includes(r))throw new f("RUNTIME_UNSUPPORTED",`尚未提供 ${r} 的精简运行时。`);let e=`@kmlckj/aios-runtime-${r}`;try{return T.dirname(gr.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 Sr(r){let e=pr("sha256");for await(let t of j.createReadStream(r))e.update(t);return e.digest("hex")}async function Ir(r,e){let t=new Set,n,o=i=>{if(!i||i.includes("\\")||i.includes("\0")||T.posix.isAbsolute(i)||/^[A-Za-z]:/.test(i)||i.split("/").includes(".."))throw new Error(`运行时归档路径无效:${i}`)};if(await fr({file:r,strict:!0,onReadEntry(i){try{o(i.path);let s=T.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(T.posix.isAbsolute(i.linkpath)||i.linkpath.includes("\\")||/^[A-Za-z]:/.test(i.linkpath))throw new Error(`运行时归档链接越界:${s}`);o(i.type==="SymbolicLink"?T.posix.join(T.posix.dirname(s),i.linkpath):i.linkpath)}}catch(s){n??=s}}}),n)throw n;await hr({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??wr(),n=JSON.parse(j.readFileSync(T.join(t,"package.json"),"utf8")),o=JSON.parse(j.readFileSync(new URL("../package.json",import.meta.url),"utf8")),i=JSON.parse(j.readFileSync(T.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=T.resolve(r.runtime.dataDirectory,"runtimes"),c=T.join(a,`${s}-${i.archive.sha256}`),u=X({...r,runtime:{...r.runtime,directory:c}});if(j.existsSync(c))return await b(c,u.runtime.trustedPublicKey),u;let d=T.join(t,i.archive.file);if(j.statSync(d).size!==i.archive.size||await Sr(d)!==i.archive.sha256)throw new f("RUNTIME_INTEGRITY_FAILED","npm 运行时归档内容与清单不一致。");ce(a);let m=j.mkdtempSync(T.join(a,".unpack-"));try{await Ir(d,m),await b(m,u.runtime.trustedPublicKey);try{j.renameSync(m,c)}catch(l){if(!j.existsSync(c))throw l;await b(c,u.runtime.trustedPublicKey)}return u}finally{j.rmSync(m,{recursive:!0,force:!0})}}import{randomUUID as vr}from"node:crypto";function ht(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 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=ht({...t.shutdown}),i=await te(e),s=await b(i.runtime.directory,i.runtime.trustedPublicKey);if(F(L(i)))throw new f("DAEMON_ALREADY_OWNED","此上下文已有运行中的宿主,不能接管其进程所有权。");let{child:a,ready:c,exited:u}=ue({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 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=vr();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 gt(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=je(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 ct(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){gt(e,t);let o=e.mode==="platform"&&e.authentication&&t.credentials?await mt(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 pe.connect(e),e,"platform")}auth=new Q(()=>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"),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});gt(t,this.services),await b(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=je(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=fe(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=dt(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 it(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,h)=>{let w=await p.execute(Object.freeze(v),{signal:h});return lt(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 De(this.transport,e.id,e.version,m,t?.map(g=>({name:g.name,reference:Ne(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}))}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}}}},De=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??x()}))}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 ge(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??x(),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??x()}})}queue(){return this.transport.call("session.queue",{id:this.id})}editQueued(e,t,n,o=x()){return this.transport.call("session.queue.edit",{id:this.id,pendingMessageId:e,content:t,queueVersion:n,commandId:o})}removeQueued(e,t,n=x()){return this.transport.call("session.queue.delete",{id:this.id,pendingMessageId:e,queueVersion:t.queueVersion,targetRunId:t.activeRunId,commandId:n})}reorderQueue(e,t,n=x()){return this.transport.call("session.queue.reorder",{id:this.id,pendingMessageIds:e,queueVersion:t,commandId:n})}dispatchQueued(e,t,n,o=x()){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 Me(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=x()){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(){let e=await this.transport.call("session.compact",{id:this.id,commandId:x()});return new ne(this.transport,this.id,e.runId)}},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(){return this.transport.call("run.cancel",{taskId:this.taskId,runId:this.id,commandId:x()})}detach(){return this.transport.call("run.detach",{taskId:this.taskId,runId:this.id})}approve(e,t){return this.transport.call("run.approve",{taskId:this.taskId,runId:this.id,toolCallId:e,decision:t,commandId:x()})}answer(e,t){return this.transport.call("run.answer",{taskId:this.taskId,runId:this.id,requestId:e,response:t,commandId:x()})}async confirmPlan(){let e=await this.transport.call("run.confirmPlan",{taskId:this.taskId,runId:this.id,commandId:x()});return new r(this.transport,this.taskId,e.runId)}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 Me(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 Me(150,void 0,{signal:e.signal})}}},Ii=oe.create,vi=oe.connectCli,Ei=oe.startManaged;export{De as Agent,oe as AiosClient,f as AiosSdkError,Q as AuthApi,Z as BrowserLogin,re as ManagedHost,ee as PlatformApi,ne as Run,ie as Session,fe as applicationToolProviderId,Ne as applicationToolReference,vi as connectCli,Ii as createClient,Ei as startManagedHost,Ut as toolResult,b as validateRuntime};
|
|
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};
|
package/dist/sdk/src/index.d.ts
CHANGED
|
@@ -66,6 +66,12 @@ export declare class AiosClient {
|
|
|
66
66
|
};
|
|
67
67
|
readonly skills: {
|
|
68
68
|
list: () => Promise<import("./types.js").LocalSkillDefinition[]>;
|
|
69
|
+
/** Installs an additive immutable package version; does not change task selections. */
|
|
70
|
+
importVersion: (request: {
|
|
71
|
+
packagePath: string;
|
|
72
|
+
folderName: string;
|
|
73
|
+
packageSha256: string;
|
|
74
|
+
}) => Promise<import("./types.js").LocalSkillDefinition>;
|
|
69
75
|
importPaths: (paths: string[]) => Promise<import("./types.js").LocalSkillDefinition[]>;
|
|
70
76
|
remove: (reference: string) => Promise<void>;
|
|
71
77
|
};
|
|
@@ -98,6 +104,8 @@ export declare class AiosClient {
|
|
|
98
104
|
defineAgent(definition: AgentDefinition): Promise<Agent>;
|
|
99
105
|
private registerAgent;
|
|
100
106
|
openSession(id: string): Promise<Session>;
|
|
107
|
+
/** Reopen an immutable, already defined agent version without replacing its tool registrations. */
|
|
108
|
+
openAgent(id: string, version: string): Promise<Agent>;
|
|
101
109
|
listSessions(query?: {
|
|
102
110
|
scope?: string;
|
|
103
111
|
includeArchived?: boolean;
|
|
@@ -152,19 +160,13 @@ export declare class Session {
|
|
|
152
160
|
setEnabled: (enabled: boolean) => Promise<import("./types.js").MemoryView>;
|
|
153
161
|
};
|
|
154
162
|
send(content: string, options?: SendOptions): Promise<Run>;
|
|
155
|
-
enqueue(content: string, options?: SendOptions): Promise<
|
|
156
|
-
status: string;
|
|
157
|
-
messageId: string;
|
|
158
|
-
}>;
|
|
163
|
+
enqueue(content: string, options?: SendOptions): Promise<import("../../shared/local-task-command.js").LocalTaskCommandResult>;
|
|
159
164
|
queue(): Promise<import("./types.js").QueueSnapshot>;
|
|
160
|
-
editQueued(messageId: string, content: string, queueVersion: string, commandId?:
|
|
161
|
-
removeQueued(messageId: string, snapshot: Pick<import('./types.js').QueueSnapshot, 'queueVersion' | 'activeRunId'>, commandId?:
|
|
162
|
-
reorderQueue(messageIds: string[], queueVersion: string, commandId?:
|
|
165
|
+
editQueued(messageId: string, content: string, queueVersion: string, commandId?: string): Promise<import("../../shared/local-task-command.js").LocalTaskCommandResult>;
|
|
166
|
+
removeQueued(messageId: string, snapshot: Pick<import('./types.js').QueueSnapshot, 'queueVersion' | 'activeRunId'>, commandId?: string): Promise<import("../../shared/local-task-command.js").LocalTaskCommandResult>;
|
|
167
|
+
reorderQueue(messageIds: string[], queueVersion: string, commandId?: string): Promise<import("../../shared/local-task-command.js").LocalTaskCommandResult>;
|
|
163
168
|
/** A non-null targetRunId adds this message to that active run; null starts its own run. */
|
|
164
|
-
dispatchQueued(messageId: string, queueVersion: string, targetRunId: string | null, commandId?:
|
|
165
|
-
status: string;
|
|
166
|
-
runId?: string;
|
|
167
|
-
}>;
|
|
169
|
+
dispatchQueued(messageId: string, queueVersion: string, targetRunId: string | null, commandId?: string): Promise<import("../../shared/local-task-command.js").LocalTaskCommandResult>;
|
|
168
170
|
history(): Promise<import("../../shared/local-task-api.js").LocalTaskMessage[]>;
|
|
169
171
|
rename(name: string, expectedRevision: string): Promise<SessionInfo>;
|
|
170
172
|
setArchived(archived: boolean, expectedRevision: string): Promise<SessionInfo>;
|
|
@@ -212,7 +214,7 @@ export declare class Session {
|
|
|
212
214
|
updateAgent(update: import('./types.js').SessionAgentUpdate): Promise<import("./types.js").SessionConfiguration>;
|
|
213
215
|
receipt(commandId: string): Promise<import("./types.js").CommandReceipt>;
|
|
214
216
|
resumeRun(runId: string): Run;
|
|
215
|
-
compact(): Promise<Run>;
|
|
217
|
+
compact(commandId?: string): Promise<Run>;
|
|
216
218
|
}
|
|
217
219
|
export declare class Run {
|
|
218
220
|
private readonly transport;
|
|
@@ -238,11 +240,12 @@ export declare class Run {
|
|
|
238
240
|
cancelOperation(operationId: string, options?: {
|
|
239
241
|
signal?: AbortSignal;
|
|
240
242
|
}): Promise<import("./types.js").TaskOperationSnapshot>;
|
|
241
|
-
cancel(): Promise<void>;
|
|
243
|
+
cancel(commandId?: string): Promise<void>;
|
|
242
244
|
detach(): Promise<void>;
|
|
243
|
-
approve(toolCallId: string, decision: 'approve' | 'approve_for_session' | 'deny'): Promise<void>;
|
|
244
|
-
answer(requestId: string, response: Record<string, unknown
|
|
245
|
-
|
|
245
|
+
approve(toolCallId: string, decision: 'approve' | 'approve_for_session' | 'deny', commandId?: string): Promise<void>;
|
|
246
|
+
answer(requestId: string, response: Record<string, unknown>, commandId?: string): Promise<void>;
|
|
247
|
+
cancelInput(requestId: string, commandId?: string): Promise<void>;
|
|
248
|
+
confirmPlan(commandId?: string): Promise<Run>;
|
|
246
249
|
/** Aborting observation never sends task cancellation. */
|
|
247
250
|
events(options?: {
|
|
248
251
|
cursor?: string;
|