@1agents/dsh-a2a 0.0.0-stage → 0.1.0
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 +57 -2
- package/cordis.patch.yml +10 -0
- package/dist/approvals.js +49 -0
- package/dist/cli.js +15 -0
- package/dist/executor.js +121 -0
- package/dist/index.js +18 -0
- package/dist/sdk-runtime.js +116 -0
- package/dist/server.js +46 -0
- package/dist/shared/a2a/workbench-ui.js +182 -0
- package/dist/workbench-ui/app.css +453 -0
- package/dist/workbench-ui/app.js +13 -0
- package/dist/workbench-ui/chunk-23JHGYT3.js +1 -0
- package/dist/workbench-ui/chunk-3H6STGPV.js +1 -0
- package/dist/workbench-ui/chunk-3SNBBMGH.js +1 -0
- package/dist/workbench-ui/chunk-3XJZ6DIE.js +1 -0
- package/dist/workbench-ui/chunk-44KDLLKJ.js +1 -0
- package/dist/workbench-ui/chunk-46H7FU5Y.js +7 -0
- package/dist/workbench-ui/chunk-4N44QPL7.js +1 -0
- package/dist/workbench-ui/chunk-4YN4BS7I.js +1 -0
- package/dist/workbench-ui/chunk-53EG4IVQ.js +96 -0
- package/dist/workbench-ui/chunk-5FIPUNR4.js +1 -0
- package/dist/workbench-ui/chunk-6DWWYA6G.js +2 -0
- package/dist/workbench-ui/chunk-6FU3T633.js +99 -0
- package/dist/workbench-ui/chunk-6XKIHRA4.js +1 -0
- package/dist/workbench-ui/chunk-7GIX43Y5.js +1 -0
- package/dist/workbench-ui/chunk-7Q4WBGX6.js +4 -0
- package/dist/workbench-ui/chunk-A3BQM7HR.js +1 -0
- package/dist/workbench-ui/chunk-AFCFDDOP.js +24 -0
- package/dist/workbench-ui/chunk-AG67EUYD.js +89 -0
- package/dist/workbench-ui/chunk-AGJHMMTN.js +1 -0
- package/dist/workbench-ui/chunk-AO6JUBV6.js +41 -0
- package/dist/workbench-ui/chunk-AUSLTP43.js +72 -0
- package/dist/workbench-ui/chunk-AVZL46TT.js +1 -0
- package/dist/workbench-ui/chunk-AZRIGIV2.js +168 -0
- package/dist/workbench-ui/chunk-B2LIVH37.js +1 -0
- package/dist/workbench-ui/chunk-B7YX5TR5.js +1 -0
- package/dist/workbench-ui/chunk-BCB4X4XX.js +1 -0
- package/dist/workbench-ui/chunk-BCRQUL2A.js +88 -0
- package/dist/workbench-ui/chunk-BI6UHHQP.js +1 -0
- package/dist/workbench-ui/chunk-BLSLQ4AQ.js +120 -0
- package/dist/workbench-ui/chunk-C3QSRS6E.js +1 -0
- package/dist/workbench-ui/chunk-CK7M2PJ3.js +62 -0
- package/dist/workbench-ui/chunk-CM6LZ7TU.js +1 -0
- package/dist/workbench-ui/chunk-CP63H27F.js +36 -0
- package/dist/workbench-ui/chunk-CPUMMIS2.js +70 -0
- package/dist/workbench-ui/chunk-CSEIBI5U.js +2 -0
- package/dist/workbench-ui/chunk-CUS65DKZ.js +161 -0
- package/dist/workbench-ui/chunk-CVQY7TNC.js +1 -0
- package/dist/workbench-ui/chunk-D6S3XBIX.js +106 -0
- package/dist/workbench-ui/chunk-E253Y562.js +1 -0
- package/dist/workbench-ui/chunk-EADDJUDC.js +1 -0
- package/dist/workbench-ui/chunk-EBGJ3YXG.js +206 -0
- package/dist/workbench-ui/chunk-EKPVZ3WY.js +8 -0
- package/dist/workbench-ui/chunk-EQDCEAFY.js +1 -0
- package/dist/workbench-ui/chunk-ES3SSDJY.js +40 -0
- package/dist/workbench-ui/chunk-ESFD2H7N.js +231 -0
- package/dist/workbench-ui/chunk-FVOHPMS6.js +1 -0
- package/dist/workbench-ui/chunk-FXMQAGVT.js +1 -0
- package/dist/workbench-ui/chunk-GGTADRXD.js +24 -0
- package/dist/workbench-ui/chunk-GHIVPGNQ.js +1 -0
- package/dist/workbench-ui/chunk-GLU2YQV2.js +1 -0
- package/dist/workbench-ui/chunk-GOCKBYSM.js +1 -0
- package/dist/workbench-ui/chunk-H2KMMTJB.js +1 -0
- package/dist/workbench-ui/chunk-HGVLDNPP.js +39 -0
- package/dist/workbench-ui/chunk-HSAVC5GY.js +1 -0
- package/dist/workbench-ui/chunk-HSEAD2JH.js +1 -0
- package/dist/workbench-ui/chunk-HSIHOBTY.js +1 -0
- package/dist/workbench-ui/chunk-IZXOKUGG.js +67 -0
- package/dist/workbench-ui/chunk-JFT2LC2T.js +1 -0
- package/dist/workbench-ui/chunk-JHL3ZDYK.js +3 -0
- package/dist/workbench-ui/chunk-JMORLCZG.js +257 -0
- package/dist/workbench-ui/chunk-JR4SIX7A.js +1 -0
- package/dist/workbench-ui/chunk-K23HAGEH.js +30 -0
- package/dist/workbench-ui/chunk-K43JDCBH.js +1 -0
- package/dist/workbench-ui/chunk-KINKFJY7.js +1 -0
- package/dist/workbench-ui/chunk-KKQSA4LI.js +2 -0
- package/dist/workbench-ui/chunk-KOUZX3UX.js +1 -0
- package/dist/workbench-ui/chunk-KR4DRHW2.js +78 -0
- package/dist/workbench-ui/chunk-KT4DJNOR.js +1 -0
- package/dist/workbench-ui/chunk-KTPNKRRZ.js +292 -0
- package/dist/workbench-ui/chunk-LFHIPGSU.js +7 -0
- package/dist/workbench-ui/chunk-LWDL4HZB.js +125 -0
- package/dist/workbench-ui/chunk-MVYC3CY4.js +1 -0
- package/dist/workbench-ui/chunk-NWUPALCY.js +129 -0
- package/dist/workbench-ui/chunk-NY7C662Z.js +1 -0
- package/dist/workbench-ui/chunk-O76WTHWP.js +1 -0
- package/dist/workbench-ui/chunk-OTF7YHRE.js +162 -0
- package/dist/workbench-ui/chunk-P6TKKRKP.js +1 -0
- package/dist/workbench-ui/chunk-PFHOOWV3.js +1 -0
- package/dist/workbench-ui/chunk-PUQLANIM.js +1 -0
- package/dist/workbench-ui/chunk-PZCGBYVO.js +1 -0
- package/dist/workbench-ui/chunk-QOHUZGP4.js +1 -0
- package/dist/workbench-ui/chunk-QSEG3OFF.js +1 -0
- package/dist/workbench-ui/chunk-QYPOXZIA.js +84 -0
- package/dist/workbench-ui/chunk-R6SOF3JC.js +1 -0
- package/dist/workbench-ui/chunk-RCLOYU5F.js +1 -0
- package/dist/workbench-ui/chunk-RSRUP64S.js +1 -0
- package/dist/workbench-ui/chunk-RVAIT6JW.js +1 -0
- package/dist/workbench-ui/chunk-S2CCN3II.js +1 -0
- package/dist/workbench-ui/chunk-S2Q52W46.js +1 -0
- package/dist/workbench-ui/chunk-S2W5THJ5.js +1 -0
- package/dist/workbench-ui/chunk-S6ZQZNOX.js +1 -0
- package/dist/workbench-ui/chunk-S74PLMMS.js +1 -0
- package/dist/workbench-ui/chunk-S7C4HKEY.js +1 -0
- package/dist/workbench-ui/chunk-SDTB3Q65.js +1 -0
- package/dist/workbench-ui/chunk-SLPRGYUV.js +32 -0
- package/dist/workbench-ui/chunk-SQE76S5B.js +1 -0
- package/dist/workbench-ui/chunk-SSDZPVPW.js +1 -0
- package/dist/workbench-ui/chunk-SVI7DGIE.js +1 -0
- package/dist/workbench-ui/chunk-T6QKLZ4H.js +62 -0
- package/dist/workbench-ui/chunk-TJNRPTFL.js +1 -0
- package/dist/workbench-ui/chunk-TP6U4EDH.js +2 -0
- package/dist/workbench-ui/chunk-TYAAT3GQ.js +1 -0
- package/dist/workbench-ui/chunk-U6OCY4ZH.js +1 -0
- package/dist/workbench-ui/chunk-UAN3NLRF.js +1 -0
- package/dist/workbench-ui/chunk-UMLU3FIX.js +1 -0
- package/dist/workbench-ui/chunk-URIY2OTM.js +1 -0
- package/dist/workbench-ui/chunk-V2NUKAA7.js +38 -0
- package/dist/workbench-ui/chunk-V4QLL4TE.js +139 -0
- package/dist/workbench-ui/chunk-VASHXUK4.js +2 -0
- package/dist/workbench-ui/chunk-VJLIWNIU.js +1 -0
- package/dist/workbench-ui/chunk-VQNQFBID.js +1 -0
- package/dist/workbench-ui/chunk-VSIWU7XA.js +3 -0
- package/dist/workbench-ui/chunk-VSJASPUZ.js +321 -0
- package/dist/workbench-ui/chunk-VXPNUNUX.js +3 -0
- package/dist/workbench-ui/chunk-WBKLDCV6.js +1 -0
- package/dist/workbench-ui/chunk-WOKJM3FY.js +1 -0
- package/dist/workbench-ui/chunk-X3U3NA3X.js +34 -0
- package/dist/workbench-ui/chunk-XBYU7M4J.js +1 -0
- package/dist/workbench-ui/chunk-XBZAO4ID.js +10 -0
- package/dist/workbench-ui/chunk-XLLPZ2WO.js +1 -0
- package/dist/workbench-ui/chunk-YFVL4NJL.js +1 -0
- package/dist/workbench-ui/chunk-YRFQENM4.js +1 -0
- package/dist/workbench-ui/chunk-YUADQVB2.js +1 -0
- package/dist/workbench-ui/chunk-Z3TCAKM5.js +1 -0
- package/dist/workbench-ui/chunk-Z6QR6FRE.js +10 -0
- package/dist/workbench-ui/chunk-ZJPSORPP.js +3 -0
- package/dist/workbench-ui/chunk-ZLGCSTR2.js +15 -0
- package/dist/workbench-ui/chunk-ZLR4SG5X.js +1 -0
- package/dist/workbench-ui/chunk-ZND3TTGF.js +1 -0
- package/dist/workbench-ui/chunk-ZOP3ZYH7.js +2 -0
- package/dist/workbench-ui/index.html +14 -0
- package/dist/workbench.js +53 -0
- package/package.json +25 -4
package/README.md
CHANGED
|
@@ -1,3 +1,58 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @1agents/dsh-a2a
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
独立的 A2A HTTP 服务,仅调用已安装的 DSH headless runtime。它不依赖 `@1agents/dsh-acp`,不连接 ACP 端口,不注册 ACP preset,不管理 ACP 进程。
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
dsh-a2a ./dsh-a2a.local.json
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
配置示例(令牌通过 `DSH_A2A_TOKEN` 环境变量提供):
|
|
10
|
+
|
|
11
|
+
```json
|
|
12
|
+
{
|
|
13
|
+
"host": "127.0.0.1",
|
|
14
|
+
"port": 3080,
|
|
15
|
+
"publicUrl": "http://127.0.0.1:3080",
|
|
16
|
+
"stateDirectory": "/absolute/path/to/.1agents/state/dsh-a2a",
|
|
17
|
+
"runtime": {
|
|
18
|
+
"command": "dsh",
|
|
19
|
+
"args": ["--profile", "headless"]
|
|
20
|
+
},
|
|
21
|
+
"workbench": {
|
|
22
|
+
"url": "http://127.0.0.1:36814",
|
|
23
|
+
"token": "<gateway-workbench-token>",
|
|
24
|
+
"pageRelaySecret": "<gateway-workbench-page-relay-secret>"
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
服务在自己的端口提供 `/.well-known/agent-card.json` 和 `/a2a`。DSH 插件模式通过 Cordis effect 管理相同服务的生命周期;只应由一个实例启动服务,其他客户端连接其 A2A 地址。`publicUrl` 仅描述对外地址,监听由 `host` 和 `port` 决定。
|
|
30
|
+
|
|
31
|
+
运行环境须安装支持 `--json`、`--session-id`、`--approval-policy never` 的 DSH headless。源码契约参考本机 DSH 0.2.2-rc.2。`runtime.command` 和 `runtime.args` 是管理员配置的可执行文件和参数数组,不经过 shell;可以显式指向安装版的命令入口。模型、工具、权限和凭据由 headless profile 配置,不继承 Web/Desktop 的全部设置。默认 headless 不读取 GUI 的保存登录,需按 DSH 官方配置启用所需认证。
|
|
32
|
+
|
|
33
|
+
每次执行启动一个 headless 进程,最终回执和退出码同时成功才报告完成;后续任务通过持久化 runtime session ID 续跑。A2A 返回的是服务自己的稳定 session ID,运行记录保存对应 DSH ID。崩溃、取消或缺少 final 回执会标记结果不确定,阻止静默重发;需人工检查运行记录和 DSH 会话再恢复。
|
|
34
|
+
|
|
35
|
+
本版本只接受 headless 固定 composition(省略 agentPreset 或使用 standard);不支持任意 preset、逐任务模型选择、ACP 会话删除和原 Web 工作台接管。默认 headless 模式由 `--approval-policy never` 拒绝需要审批的调用;需要交互式执行审批时使用下述 SDK 模式。Web 工作台迁移到本服务的 `/workbench/ui`(默认 `http://127.0.0.1:3080/workbench/ui`)。使用 `DSH_A2A_TOKEN` 登录,服务端通过 `workbench.url` 转发任务、聊天、产物与审核 API;网关凭据不会发送到浏览器。`pageRelaySecret` 必须与网关一致,才能提交发布、验收和继续任务等人工决定。任务账本仍由网关管理,本包不另建一套账本。未配置网关时可以加载页面和登录,但业务 API 返回配置缺失。原来的父级 DSH GUI 接管入口与 MCP 回传仍不可用。
|
|
36
|
+
|
|
37
|
+
A2A 协议、持久化任务和预检暂复用 `@1agents/acp-service/a2a` 的宿主无关库。这是共享协议库依赖,不会启动 ACP 服务;协议库独立打包不属于本次改动。
|
|
38
|
+
|
|
39
|
+
交互式执行审批配置:
|
|
40
|
+
|
|
41
|
+
```json
|
|
42
|
+
{
|
|
43
|
+
"runtime": {
|
|
44
|
+
"mode": "sdk",
|
|
45
|
+
"command": "dsh",
|
|
46
|
+
"args": ["--profile", "sdk"],
|
|
47
|
+
"permissionMode": "workspace-write",
|
|
48
|
+
"provider": "<configured-provider>",
|
|
49
|
+
"model": "<configured-model>"
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
SDK 模式使用 DSH 原生 JSON-RPC,初始化启用 `approvalRequests`,不使用 ACP。runtime 的权限策略应允许 ask(never 会在发送审批前拒绝)。A2A 任务须由网关携带 `metadata.1agents.execution` 的 jobId/attemptId,且配置 workbench.url/token。审批以 permission 过程请求展示在现有工作台,浏览器原有回答 API 决定批准或拒绝;批准仅授予 allowed-once。缺少任务绑定、请求过期、网关失败、执行取消或连接中断不会放行;取消尽力写回网关。子 Agent 的审批当前拒绝为 cancelled,避免未验证父子关系时错绑任务。SDK 会话与 headless 会话的 profile 不同,应使用独立 stateDirectory,禁止直接切换既有会话。
|
|
55
|
+
|
|
56
|
+
SDK 每轮等待 session/wait 和精确根会话的 turn/end,再关闭 runtime;恢复使用 session/resume。原生问答、计划审核、DSH GUI 接管不在本次执行审批接入范围。
|
|
57
|
+
|
|
58
|
+
本地验收:10 项自动测试通过;在 DSH 0.2.2-rc.2 上通过真实 Web 页面登录、真实 Grok SDK 模型执行、工作区外写入审批与浏览器“允许本次”回传,文件内容核验通过;浏览器拒绝后模型停止,拒绝目标文件未创建。独立 tarball 从 npm 公共依赖干净安装后,agent card、工作台 HTML 和脚本可访问。验收同时修复后台标签首次不加载任务的问题。Grok Web 插件采用延迟注册时,SDK composition 须等待适配器就绪后再 initialize。尚未配置系统常驻启动。
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
3
|
+
async function requestApproval(workbench, execution, sessionId, params, signal) {
|
|
4
|
+
if (!workbench?.url || !execution?.jobId || !execution?.attemptId) return { outcome: "cancelled" };
|
|
5
|
+
const origin = new URL(workbench.url).origin;
|
|
6
|
+
const headers = { "Content-Type": "application/json", ...workbench.token ? { Authorization: `Bearer ${workbench.token}` } : {} };
|
|
7
|
+
const requestId = `prc-${randomUUID().replaceAll("-", "")}`;
|
|
8
|
+
const path = `/workbench/tasks/${encodeURIComponent(execution.jobId)}/process-requests`;
|
|
9
|
+
const send = async (suffix, method, body, requestSignal = signal) => {
|
|
10
|
+
const response = await fetch(new URL(path + suffix, origin), {
|
|
11
|
+
method,
|
|
12
|
+
headers,
|
|
13
|
+
signal: requestSignal,
|
|
14
|
+
redirect: "error",
|
|
15
|
+
...body ? { body: JSON.stringify(body) } : {}
|
|
16
|
+
});
|
|
17
|
+
if (!response.ok) throw new Error(`Approval gateway returned ${response.status}`);
|
|
18
|
+
return response.json();
|
|
19
|
+
};
|
|
20
|
+
try {
|
|
21
|
+
const opened = await send("", "POST", {
|
|
22
|
+
requestId,
|
|
23
|
+
jobId: execution.jobId,
|
|
24
|
+
attemptId: execution.attemptId,
|
|
25
|
+
sessionId,
|
|
26
|
+
kind: "permission",
|
|
27
|
+
toolTitle: String(params.toolName ?? "DSH operation").slice(0, 500),
|
|
28
|
+
toolDetail: String(params.reason ?? "").slice(0, 16384)
|
|
29
|
+
});
|
|
30
|
+
if (opened.requestId !== requestId) throw new Error("Approval receipt identity mismatch");
|
|
31
|
+
for (; ; ) {
|
|
32
|
+
signal.throwIfAborted();
|
|
33
|
+
const view = await send(`/${requestId}`, "GET");
|
|
34
|
+
if (view.requestId !== requestId || view.jobId !== execution.jobId) throw new Error("Approval identity mismatch");
|
|
35
|
+
if (view.status === "answered") return { outcome: view.answer?.outcome === "approved" ? "allowed-once" : view.answer?.outcome === "rejected" ? "rejected" : "cancelled" };
|
|
36
|
+
if (view.status !== "pending" || !Number.isFinite(Date.parse(view.deadlineAt)) || Date.parse(view.deadlineAt) <= Date.now()) break;
|
|
37
|
+
await delay(workbench.pollMs ?? 200, void 0, { signal });
|
|
38
|
+
}
|
|
39
|
+
} catch {
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
await send(`/${requestId}/answers`, "POST", { clientRequestId: `cancel:${requestId}`, outcome: "cancelled" }, AbortSignal.timeout(5e3));
|
|
43
|
+
} catch {
|
|
44
|
+
}
|
|
45
|
+
return { outcome: "cancelled" };
|
|
46
|
+
}
|
|
47
|
+
export {
|
|
48
|
+
requestApproval
|
|
49
|
+
};
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import { startA2AService } from "./server.js";
|
|
4
|
+
if (process.argv.length !== 3 || ["--help", "-h"].includes(process.argv[2])) {
|
|
5
|
+
console.log("Usage: dsh-a2a <config.json>\nStart a standalone A2A endpoint backed by the installed DSH headless runtime.");
|
|
6
|
+
process.exit(process.argv.length === 3 ? 0 : 1);
|
|
7
|
+
}
|
|
8
|
+
const config = JSON.parse(await readFile(process.argv[2], "utf8"));
|
|
9
|
+
const service = await startA2AService(config);
|
|
10
|
+
for (const event of ["SIGINT", "SIGTERM"]) process.once(event, () => {
|
|
11
|
+
void service.close().catch(() => {
|
|
12
|
+
process.exitCode = 1;
|
|
13
|
+
});
|
|
14
|
+
});
|
|
15
|
+
console.log(`DSH A2A listening at ${config.publicUrl ?? "http://127.0.0.1:3080"}`);
|
package/dist/executor.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { mkdir, readFile, writeFile, rename } from "node:fs/promises";
|
|
4
|
+
import { resolve, join } from "node:path";
|
|
5
|
+
import { createInterface } from "node:readline";
|
|
6
|
+
import { runA2APreflight } from "@1agents/acp-service/a2a";
|
|
7
|
+
import { runSdk } from "./sdk-runtime.js";
|
|
8
|
+
class HeadlessDshBackend {
|
|
9
|
+
constructor({ directory, command = "dsh", args, env = {}, mode = "headless", provider, model, workbench, permissionMode }) {
|
|
10
|
+
if (!["headless", "sdk"].includes(mode)) throw new Error("Unknown DSH runtime mode");
|
|
11
|
+
this.runtime = { mode, command, args: args ?? ["--profile", mode], env, provider, model, workbench, permissionMode };
|
|
12
|
+
this.directory = resolve(directory);
|
|
13
|
+
this.command = command;
|
|
14
|
+
this.args = this.runtime.args;
|
|
15
|
+
this.env = env;
|
|
16
|
+
this.active = /* @__PURE__ */ new Map();
|
|
17
|
+
}
|
|
18
|
+
file(id) {
|
|
19
|
+
if (!/^dsh-a2a-[a-f0-9-]{36}$/.test(id)) throw new Error("Invalid DSH execution session identity");
|
|
20
|
+
return join(this.directory, `${id}.json`);
|
|
21
|
+
}
|
|
22
|
+
async save(record) {
|
|
23
|
+
await mkdir(this.directory, { recursive: true, mode: 448 });
|
|
24
|
+
const file = this.file(record.sessionId), temp = `${file}.${randomUUID()}.tmp`;
|
|
25
|
+
await writeFile(temp, JSON.stringify(record), { mode: 384 });
|
|
26
|
+
await rename(temp, file);
|
|
27
|
+
}
|
|
28
|
+
async load(id) {
|
|
29
|
+
return JSON.parse(await readFile(this.file(id), "utf8"));
|
|
30
|
+
}
|
|
31
|
+
preflight(input) {
|
|
32
|
+
return runA2APreflight(input);
|
|
33
|
+
}
|
|
34
|
+
async prepare(input, { signal } = {}) {
|
|
35
|
+
signal?.throwIfAborted();
|
|
36
|
+
if (input.agentPreset && input.agentPreset !== "standard") throw new Error("Only the configured DSH headless composition is supported");
|
|
37
|
+
if (input.provider || input.model) throw new Error("Configure the model on the DSH headless profile");
|
|
38
|
+
const previous = input.sessionId ? await this.load(input.sessionId) : void 0;
|
|
39
|
+
const cwd = resolve(input.cwd ?? previous?.cwd ?? process.cwd());
|
|
40
|
+
if (previous && previous.cwd !== cwd) throw new Error("Existing session cwd conflicts");
|
|
41
|
+
const preflight = await this.preflight({ ...input.preflight, cwd });
|
|
42
|
+
if (!preflight.ok) throw new Error("DSH workspace preflight failed");
|
|
43
|
+
const record = previous ?? { sessionId: `dsh-a2a-${randomUUID()}`, cwd, agentPreset: "standard" };
|
|
44
|
+
signal?.throwIfAborted();
|
|
45
|
+
if (!previous) await this.save(record);
|
|
46
|
+
return { sessionId: record.sessionId, cwd, agentPreset: "standard", preflight };
|
|
47
|
+
}
|
|
48
|
+
async run(target, prompt, options) {
|
|
49
|
+
if (this.active.has(target.sessionId)) throw new Error("DSH session is busy");
|
|
50
|
+
this.active.set(target.sessionId, true);
|
|
51
|
+
try {
|
|
52
|
+
const record = await this.load(target.sessionId);
|
|
53
|
+
if (record.uncertain) throw new Error("Previous DSH execution has an unknown outcome; inspect its persisted session before recovery");
|
|
54
|
+
await options.beforeStart?.(options.signal);
|
|
55
|
+
options.signal.throwIfAborted();
|
|
56
|
+
record.uncertain = true;
|
|
57
|
+
await this.save(record);
|
|
58
|
+
if (this.runtime.mode === "sdk") return await runSdk(this.runtime, record, prompt, options, (value) => this.save(value));
|
|
59
|
+
const args = [...this.args, "--json", "--approval-policy", "never", ...record.runtimeSessionId ? ["--session-id", record.runtimeSessionId] : [], "-"];
|
|
60
|
+
let final, runtimeSessionId, invalid = false;
|
|
61
|
+
const child = spawn(this.command, args, { cwd: record.cwd, env: { ...process.env, ...this.env }, stdio: ["pipe", "pipe", "pipe"] });
|
|
62
|
+
const abort = () => {
|
|
63
|
+
child.kill("SIGTERM");
|
|
64
|
+
};
|
|
65
|
+
options.signal.addEventListener("abort", abort, { once: true });
|
|
66
|
+
if (options.signal.aborted) abort();
|
|
67
|
+
const killer = setInterval(() => {
|
|
68
|
+
if (options.signal.aborted) child.kill("SIGKILL");
|
|
69
|
+
}, 1e3);
|
|
70
|
+
const lines = createInterface({ input: child.stdout });
|
|
71
|
+
lines.on("line", (line) => {
|
|
72
|
+
try {
|
|
73
|
+
const event = JSON.parse(line);
|
|
74
|
+
if (event.type === "session") runtimeSessionId = event.sessionId;
|
|
75
|
+
if (event.type === "final") final = event;
|
|
76
|
+
} catch {
|
|
77
|
+
invalid = true;
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
child.stderr.resume();
|
|
81
|
+
child.stdin.on("error", () => {
|
|
82
|
+
});
|
|
83
|
+
child.stdin.end(prompt);
|
|
84
|
+
let code;
|
|
85
|
+
try {
|
|
86
|
+
code = await new Promise((resolve2, reject) => {
|
|
87
|
+
child.once("error", reject);
|
|
88
|
+
child.once("close", resolve2);
|
|
89
|
+
});
|
|
90
|
+
} finally {
|
|
91
|
+
clearInterval(killer);
|
|
92
|
+
options.signal.removeEventListener("abort", abort);
|
|
93
|
+
lines.close();
|
|
94
|
+
}
|
|
95
|
+
if (record.runtimeSessionId && runtimeSessionId && record.runtimeSessionId !== runtimeSessionId) invalid = true;
|
|
96
|
+
if (record.runtimeSessionId && final?.sessionId && record.runtimeSessionId !== final.sessionId) invalid = true;
|
|
97
|
+
if (runtimeSessionId) record.runtimeSessionId = runtimeSessionId;
|
|
98
|
+
if (final?.sessionId) {
|
|
99
|
+
if (runtimeSessionId && final.sessionId !== runtimeSessionId) invalid = true;
|
|
100
|
+
record.runtimeSessionId = final.sessionId;
|
|
101
|
+
}
|
|
102
|
+
record.uncertain = invalid || !final || options.signal.aborted;
|
|
103
|
+
await this.save(record);
|
|
104
|
+
options.signal.throwIfAborted();
|
|
105
|
+
return { outcome: code === 0 && !invalid && final?.reason?.kind === "completed" ? "completed" : "failed", text: typeof final?.text === "string" ? final.text : typeof final?.answer === "string" ? final.answer : "", ...code === 0 && final?.reason?.kind === "completed" && !invalid ? {} : { detail: "DSH headless did not report a completed final turn" } };
|
|
106
|
+
} finally {
|
|
107
|
+
this.active.delete(target.sessionId);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async status(target) {
|
|
111
|
+
await this.load(target.sessionId);
|
|
112
|
+
return { attached: true, activeTurn: this.active.has(target.sessionId) };
|
|
113
|
+
}
|
|
114
|
+
async close(target) {
|
|
115
|
+
if (this.active.has(target.sessionId)) return { processReleased: "pending", acp: false };
|
|
116
|
+
return { processReleased: true, acp: false };
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
export {
|
|
120
|
+
HeadlessDshBackend
|
|
121
|
+
};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { startA2AService } from "./server.js";
|
|
2
|
+
import { HeadlessDshBackend } from "./executor.js";
|
|
3
|
+
import { startA2AService as startA2AService2 } from "./server.js";
|
|
4
|
+
const name = "oneagents-dsh-a2a";
|
|
5
|
+
const inject = [];
|
|
6
|
+
async function apply(ctx, config = {}) {
|
|
7
|
+
await ctx.effect(async () => {
|
|
8
|
+
const service = await startA2AService2(config);
|
|
9
|
+
return () => service.close();
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
export {
|
|
13
|
+
HeadlessDshBackend,
|
|
14
|
+
apply,
|
|
15
|
+
inject,
|
|
16
|
+
name,
|
|
17
|
+
startA2AService
|
|
18
|
+
};
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { createInterface } from "node:readline";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import { requestApproval } from "./approvals.js";
|
|
5
|
+
async function runSdk(runtime, record, prompt, options, save) {
|
|
6
|
+
if (!runtime.provider || !runtime.model) throw new Error("SDK runtime requires provider and model configuration");
|
|
7
|
+
const child = spawn(runtime.command, runtime.args, { cwd: record.cwd, env: { ...process.env, ...runtime.env }, stdio: ["pipe", "pipe", "pipe"] });
|
|
8
|
+
const controller = new AbortController(), signal = AbortSignal.any([options.signal, controller.signal]);
|
|
9
|
+
const pending = /* @__PURE__ */ new Map(), approvalTasks = /* @__PURE__ */ new Set();
|
|
10
|
+
let serial = 0, terminal, text = "", alive = true;
|
|
11
|
+
const write = (value) => {
|
|
12
|
+
if (alive && !child.stdin.destroyed) child.stdin.write(`${JSON.stringify(value)}
|
|
13
|
+
`);
|
|
14
|
+
};
|
|
15
|
+
child.stdin.on("error", () => {
|
|
16
|
+
});
|
|
17
|
+
child.stderr.resume();
|
|
18
|
+
const exited = new Promise((resolve) => child.once("close", (code) => resolve(code)));
|
|
19
|
+
const fail = (error) => {
|
|
20
|
+
controller.abort(error);
|
|
21
|
+
for (const task of pending.values()) task.reject(error);
|
|
22
|
+
pending.clear();
|
|
23
|
+
};
|
|
24
|
+
child.once("error", fail);
|
|
25
|
+
child.once("close", () => {
|
|
26
|
+
alive = false;
|
|
27
|
+
fail(new Error("DSH SDK transport closed"));
|
|
28
|
+
});
|
|
29
|
+
const request = (method, params) => new Promise((resolve, reject) => {
|
|
30
|
+
if (signal.aborted) return reject(signal.reason);
|
|
31
|
+
const id = ++serial;
|
|
32
|
+
const timer = ["initialize", "shutdown", "session/resume"].includes(method) ? setTimeout(() => {
|
|
33
|
+
pending.delete(id);
|
|
34
|
+
reject(new Error(`DSH SDK ${method} timed out`));
|
|
35
|
+
}, runtime.timeoutMs ?? 3e4) : void 0;
|
|
36
|
+
pending.set(id, { resolve: (value) => {
|
|
37
|
+
clearTimeout(timer);
|
|
38
|
+
resolve(value);
|
|
39
|
+
}, reject: (error) => {
|
|
40
|
+
clearTimeout(timer);
|
|
41
|
+
reject(error);
|
|
42
|
+
} });
|
|
43
|
+
write({ jsonrpc: "2.0", id, method, params });
|
|
44
|
+
});
|
|
45
|
+
const lines = createInterface({ input: child.stdout });
|
|
46
|
+
lines.on("line", (line) => {
|
|
47
|
+
let frame;
|
|
48
|
+
try {
|
|
49
|
+
frame = JSON.parse(line);
|
|
50
|
+
} catch {
|
|
51
|
+
return fail(new Error("Malformed DSH SDK frame"));
|
|
52
|
+
}
|
|
53
|
+
if (frame.method && frame.id !== void 0) {
|
|
54
|
+
if (frame.method !== "approval/request") return write({ jsonrpc: "2.0", id: frame.id, error: { code: -32601, message: "Unsupported runtime request" } });
|
|
55
|
+
const task = (frame.params?.sessionId === record.runtimeSessionId ? requestApproval(runtime.workbench, options.execution, record.sessionId, frame.params, signal) : Promise.resolve({ outcome: "cancelled" })).then((result) => {
|
|
56
|
+
if (!signal.aborted) write({ jsonrpc: "2.0", id: frame.id, result });
|
|
57
|
+
});
|
|
58
|
+
approvalTasks.add(task);
|
|
59
|
+
void task.finally(() => approvalTasks.delete(task));
|
|
60
|
+
} else if (frame.method === "session.event" && frame.params?.sessionId === record.runtimeSessionId) {
|
|
61
|
+
const event = frame.params.event;
|
|
62
|
+
if (event?.type === "turn/end") terminal = event.data?.reason;
|
|
63
|
+
if (event?.type === "assistant/message") {
|
|
64
|
+
const content = event.data?.message?.content;
|
|
65
|
+
if (Array.isArray(content)) text = content.filter((part) => part.type === "text").map((part) => part.text).join("");
|
|
66
|
+
}
|
|
67
|
+
} else if (frame.id !== void 0) {
|
|
68
|
+
const task = pending.get(frame.id);
|
|
69
|
+
if (!task) return;
|
|
70
|
+
pending.delete(frame.id);
|
|
71
|
+
if (frame.error) task.reject(new Error("DSH SDK request failed"));
|
|
72
|
+
else task.resolve(frame.result);
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
const abort = () => {
|
|
76
|
+
fail(options.signal.reason);
|
|
77
|
+
child.kill("SIGTERM");
|
|
78
|
+
};
|
|
79
|
+
options.signal.addEventListener("abort", abort, { once: true });
|
|
80
|
+
const force = setInterval(() => {
|
|
81
|
+
if (signal.aborted) child.kill("SIGKILL");
|
|
82
|
+
}, 1e3);
|
|
83
|
+
try {
|
|
84
|
+
options.signal.throwIfAborted();
|
|
85
|
+
const initialized = await request("initialize", { cwd: record.cwd, provider: runtime.provider, model: runtime.model, approvalRequests: true });
|
|
86
|
+
if (initialized?.serverInfo?.name !== "deepseek-harness-sdk-runtime") throw new Error("Unexpected DSH runtime");
|
|
87
|
+
if (record.runtimeSessionId) await request("session/resume", { sessionId: record.runtimeSessionId });
|
|
88
|
+
else {
|
|
89
|
+
record.runtimeSessionId = `session-${randomUUID()}`;
|
|
90
|
+
await save(record);
|
|
91
|
+
}
|
|
92
|
+
if (runtime.permissionMode) await request("session/query", { sessionId: record.runtimeSessionId, contentBlocks: [{ type: "text", text: `/permission ${runtime.permissionMode}` }] });
|
|
93
|
+
terminal = void 0;
|
|
94
|
+
text = "";
|
|
95
|
+
await request("session/prompt", { sessionId: record.runtimeSessionId, contentBlocks: [{ type: "text", text: prompt }] });
|
|
96
|
+
await request("session/wait", { sessionId: record.runtimeSessionId });
|
|
97
|
+
record.uncertain = !terminal;
|
|
98
|
+
await save(record);
|
|
99
|
+
await request("shutdown", {});
|
|
100
|
+
const code = await exited;
|
|
101
|
+
return { outcome: code === 0 && terminal?.kind === "completed" ? "completed" : "failed", text };
|
|
102
|
+
} finally {
|
|
103
|
+
controller.abort();
|
|
104
|
+
child.kill("SIGTERM");
|
|
105
|
+
const timer = setTimeout(() => child.kill("SIGKILL"), 1e3);
|
|
106
|
+
await exited;
|
|
107
|
+
clearTimeout(timer);
|
|
108
|
+
clearInterval(force);
|
|
109
|
+
options.signal.removeEventListener("abort", abort);
|
|
110
|
+
lines.close();
|
|
111
|
+
await Promise.allSettled(approvalTasks);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
export {
|
|
115
|
+
runSdk
|
|
116
|
+
};
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { createA2AServer } from "@1agents/acp-service/a2a";
|
|
5
|
+
import { HeadlessDshBackend } from "./executor.js";
|
|
6
|
+
import { createWorkbench, WORKBENCH_UI_PATH } from "./workbench.js";
|
|
7
|
+
async function startA2AService(config = {}) {
|
|
8
|
+
const { host = "127.0.0.1", port = 3080, runtime = {}, workbench, tokenEnv = "DSH_A2A_TOKEN", token = process.env[tokenEnv], stateDirectory = join(homedir(), ".1agents", "state", "dsh-a2a"), publicUrl = `http://${host}:${port}`, ...options } = config;
|
|
9
|
+
const backend = new HeadlessDshBackend({ ...runtime, workbench, directory: join(stateDirectory, "sessions") });
|
|
10
|
+
const a2a = await createA2AServer({ ...options, backend, token, stateDirectory, publicUrl });
|
|
11
|
+
const workbenchHandler = createWorkbench(workbench, token);
|
|
12
|
+
const server = createServer((req, res) => {
|
|
13
|
+
void (async () => {
|
|
14
|
+
const url = new URL(req.url ?? "/", "http://localhost"), path = url.pathname;
|
|
15
|
+
if (path === WORKBENCH_UI_PATH || path.startsWith(`${WORKBENCH_UI_PATH}/`)) await workbenchHandler(req, res, url);
|
|
16
|
+
else if (path === "/.well-known/agent-card.json") await a2a.cardHandler(req, res);
|
|
17
|
+
else if (path === a2a.path || path.startsWith(`${a2a.path}/`)) await a2a.handler(req, res);
|
|
18
|
+
else {
|
|
19
|
+
res.writeHead(404);
|
|
20
|
+
res.end();
|
|
21
|
+
}
|
|
22
|
+
})().catch(() => {
|
|
23
|
+
if (!res.headersSent) res.writeHead(500);
|
|
24
|
+
res.end();
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
try {
|
|
28
|
+
await new Promise((resolve, reject) => {
|
|
29
|
+
server.once("error", reject);
|
|
30
|
+
server.listen(port, host, resolve);
|
|
31
|
+
});
|
|
32
|
+
} catch (error) {
|
|
33
|
+
await a2a.close();
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
let closing;
|
|
37
|
+
return { server, backend, close: () => closing ??= (async () => {
|
|
38
|
+
const stopped = new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
|
|
39
|
+
await a2a.close();
|
|
40
|
+
server.closeAllConnections();
|
|
41
|
+
await stopped;
|
|
42
|
+
})() };
|
|
43
|
+
}
|
|
44
|
+
export {
|
|
45
|
+
startA2AService
|
|
46
|
+
};
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The gateway's own workbench page. A logged-in same-origin browser reaches the same routes as the bearer API.
|
|
3
|
+
* Without a configured token the page needs no login; writes still need a same-origin browser.
|
|
4
|
+
*/
|
|
5
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
6
|
+
import { existsSync } from 'node:fs';
|
|
7
|
+
import { readFile } from 'node:fs/promises';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
export const WORKBENCH_UI_PATH = '/workbench/ui';
|
|
11
|
+
const API_PATH = `${WORKBENCH_UI_PATH}/api`;
|
|
12
|
+
const COOKIE = 'acp_workbench';
|
|
13
|
+
const SESSION_MS = 12 * 60 * 60 * 1000;
|
|
14
|
+
const MAX_SESSIONS = 64;
|
|
15
|
+
const ASSETS = { 'app.js': 'text/javascript; charset=utf-8', 'app.css': 'text/css; charset=utf-8' };
|
|
16
|
+
/** Lazy-loaded renderer chunks (markdown, highlighting) emitted by the page build. */
|
|
17
|
+
const CHUNK = /^chunk-[A-Za-z0-9_-]+\.js$/;
|
|
18
|
+
const SECURITY_HEADERS = {
|
|
19
|
+
'Content-Security-Policy': "default-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
|
|
20
|
+
'X-Content-Type-Options': 'nosniff',
|
|
21
|
+
'Referrer-Policy': 'no-referrer',
|
|
22
|
+
'Cache-Control': 'no-store',
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Built output sits in dist/workbench-ui; the source tree runs from src/a2a under tsx. Only the build
|
|
26
|
+
* has app.js, so the page source directory beside src is never served.
|
|
27
|
+
*/
|
|
28
|
+
function assetDirectory() {
|
|
29
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
30
|
+
return [path.resolve(here, '../../workbench-ui'), path.resolve(here, '../../dist/workbench-ui')]
|
|
31
|
+
.find(directory => existsSync(path.join(directory, 'app.js')));
|
|
32
|
+
}
|
|
33
|
+
function send(res, status, type, payload, headers = {}) {
|
|
34
|
+
res.writeHead(status, { ...SECURITY_HEADERS, 'Content-Type': type, ...headers });
|
|
35
|
+
res.end(payload);
|
|
36
|
+
}
|
|
37
|
+
function sendJson(res, status, data, headers = {}) {
|
|
38
|
+
send(res, status, 'application/json', JSON.stringify(data), headers);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The page and its static assets under WORKBENCH_UI_PATH. `frameAncestors` lets a host that embeds the
|
|
42
|
+
* page in its own frame (DSH) allow exactly that; the gateway's own page is never framed.
|
|
43
|
+
*/
|
|
44
|
+
export async function serveWorkbenchPage(req, res, pathname, options = {}) {
|
|
45
|
+
const headers = options.frameAncestors === "'self'"
|
|
46
|
+
? { 'Content-Security-Policy': SECURITY_HEADERS['Content-Security-Policy'].replace("frame-ancestors 'none'", "frame-ancestors 'self'") } : {};
|
|
47
|
+
if (req.method !== 'GET')
|
|
48
|
+
return sendJson(res, 405, { error: 'Method not allowed' }, headers);
|
|
49
|
+
const directory = assetDirectory();
|
|
50
|
+
if (!directory)
|
|
51
|
+
return sendJson(res, 503, { error: 'Workbench page is not built' }, headers);
|
|
52
|
+
if (pathname === WORKBENCH_UI_PATH || pathname === `${WORKBENCH_UI_PATH}/`) {
|
|
53
|
+
return send(res, 200, 'text/html; charset=utf-8', await readFile(path.join(directory, 'index.html')), headers);
|
|
54
|
+
}
|
|
55
|
+
const asset = pathname.slice(`${WORKBENCH_UI_PATH}/`.length);
|
|
56
|
+
const type = Object.hasOwn(ASSETS, asset) ? ASSETS[asset] : CHUNK.test(asset) ? ASSETS['app.js'] : undefined;
|
|
57
|
+
if (!type)
|
|
58
|
+
return sendJson(res, 404, { error: 'No workbench page asset' }, headers);
|
|
59
|
+
try {
|
|
60
|
+
return send(res, 200, type, await readFile(path.join(directory, asset)), headers);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
return sendJson(res, 404, { error: 'No workbench page asset' }, headers);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** Agent sessions and CLI tools never act as the human reviewer. */
|
|
67
|
+
export function isAgentRequest(req) {
|
|
68
|
+
if (['x-oneagents-session-id', 'x-oneagents-session-token', 'x-oneagents-turn-id'].some(name => req.headers[name]))
|
|
69
|
+
return true;
|
|
70
|
+
const origin = String(req.headers['x-oneagents-origin'] ?? '').toLowerCase();
|
|
71
|
+
return origin === 'mcp' || origin === 'cli' || Boolean(req.headers.authorization);
|
|
72
|
+
}
|
|
73
|
+
/** Same rule as the former 1agents proxy: a direct browser request whose Origin authority is this Host. */
|
|
74
|
+
export function sameOriginBrowser(req) {
|
|
75
|
+
if (req.headers['sec-fetch-site'] !== 'same-origin')
|
|
76
|
+
return false;
|
|
77
|
+
try {
|
|
78
|
+
const origin = new URL(String(req.headers.origin ?? ''));
|
|
79
|
+
if (!['http:', 'https:'].includes(origin.protocol) || origin.username || origin.password)
|
|
80
|
+
return false;
|
|
81
|
+
if ((origin.pathname !== '' && origin.pathname !== '/') || origin.search || origin.hash)
|
|
82
|
+
return false;
|
|
83
|
+
return origin.host.toLowerCase() === String(req.headers.host ?? '').toLowerCase();
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function cookieValue(req) {
|
|
90
|
+
for (const part of String(req.headers.cookie ?? '').split(';')) {
|
|
91
|
+
const [name, ...value] = part.trim().split('=');
|
|
92
|
+
if (name === COOKIE)
|
|
93
|
+
return value.join('=');
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
async function readToken(req) {
|
|
97
|
+
let length = 0;
|
|
98
|
+
const chunks = [];
|
|
99
|
+
for await (const data of req) {
|
|
100
|
+
length += data.length;
|
|
101
|
+
if (length > 4096)
|
|
102
|
+
throw new Error('Request body too large');
|
|
103
|
+
chunks.push(Buffer.from(data));
|
|
104
|
+
}
|
|
105
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8')).token;
|
|
106
|
+
}
|
|
107
|
+
export class WorkbenchUi {
|
|
108
|
+
token;
|
|
109
|
+
now;
|
|
110
|
+
sessions = new Map();
|
|
111
|
+
constructor(token, now = Date.now) {
|
|
112
|
+
this.token = token;
|
|
113
|
+
this.now = now;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Serves the page, the login session and static assets. For an authorized page API call it returns
|
|
117
|
+
* the matching /workbench route, which the caller dispatches exactly like the bearer API.
|
|
118
|
+
*/
|
|
119
|
+
async handle(req, res, url) {
|
|
120
|
+
const pathname = url.pathname;
|
|
121
|
+
if (!pathname.startsWith(`${API_PATH}/`))
|
|
122
|
+
return void await serveWorkbenchPage(req, res, pathname);
|
|
123
|
+
if (isAgentRequest(req))
|
|
124
|
+
return void sendJson(res, 403, { error: 'browser_action_required', message: 'Agents and tools use the bearer workbench API, not the page.' });
|
|
125
|
+
const write = req.method !== 'GET';
|
|
126
|
+
if (write && !sameOriginBrowser(req)) {
|
|
127
|
+
return void sendJson(res, 403, { error: 'browser_action_required', message: '请在本工作台页面提交。' });
|
|
128
|
+
}
|
|
129
|
+
if (pathname === `${API_PATH}/session`)
|
|
130
|
+
return this.session(req, res);
|
|
131
|
+
if (!this.authorized(req))
|
|
132
|
+
return void sendJson(res, 401, { error: 'login_required', message: '请先登录工作台。' });
|
|
133
|
+
return { route: `/workbench${pathname.slice(API_PATH.length)}` };
|
|
134
|
+
}
|
|
135
|
+
authorized(req) {
|
|
136
|
+
if (!this.token)
|
|
137
|
+
return true;
|
|
138
|
+
const id = cookieValue(req);
|
|
139
|
+
const expires = id ? this.sessions.get(id) : undefined;
|
|
140
|
+
if (!id || expires === undefined)
|
|
141
|
+
return false;
|
|
142
|
+
if (expires <= this.now()) {
|
|
143
|
+
this.sessions.delete(id);
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
async session(req, res) {
|
|
149
|
+
if (req.method === 'GET')
|
|
150
|
+
return void sendJson(res, 200, { authenticated: this.authorized(req), loginRequired: Boolean(this.token) });
|
|
151
|
+
if (req.method === 'DELETE') {
|
|
152
|
+
const id = cookieValue(req);
|
|
153
|
+
if (id)
|
|
154
|
+
this.sessions.delete(id);
|
|
155
|
+
return void sendJson(res, 200, { authenticated: false }, { 'Set-Cookie': `${COOKIE}=; HttpOnly; SameSite=Strict; Path=${WORKBENCH_UI_PATH}; Max-Age=0` });
|
|
156
|
+
}
|
|
157
|
+
if (req.method !== 'POST')
|
|
158
|
+
return void sendJson(res, 405, { error: 'Method not allowed' });
|
|
159
|
+
if (!this.token)
|
|
160
|
+
return void sendJson(res, 200, { authenticated: true });
|
|
161
|
+
let supplied;
|
|
162
|
+
try {
|
|
163
|
+
supplied = await readToken(req);
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
return void sendJson(res, 400, { error: 'invalid', message: '请求格式不正确。' });
|
|
167
|
+
}
|
|
168
|
+
const expected = Buffer.from(this.token), given = Buffer.from(typeof supplied === 'string' ? supplied : '');
|
|
169
|
+
if (given.length !== expected.length || !timingSafeEqual(given, expected)) {
|
|
170
|
+
return void sendJson(res, 401, { error: 'login_failed', message: '工作台令牌不正确。' });
|
|
171
|
+
}
|
|
172
|
+
const now = this.now();
|
|
173
|
+
for (const [id, expires] of this.sessions)
|
|
174
|
+
if (expires <= now)
|
|
175
|
+
this.sessions.delete(id);
|
|
176
|
+
while (this.sessions.size >= MAX_SESSIONS)
|
|
177
|
+
this.sessions.delete(this.sessions.keys().next().value);
|
|
178
|
+
const id = randomBytes(32).toString('base64url');
|
|
179
|
+
this.sessions.set(id, now + SESSION_MS);
|
|
180
|
+
return void sendJson(res, 200, { authenticated: true }, { 'Set-Cookie': `${COOKIE}=${id}; HttpOnly; SameSite=Strict; Path=${WORKBENCH_UI_PATH}; Max-Age=${SESSION_MS / 1000}` });
|
|
181
|
+
}
|
|
182
|
+
}
|