create-deepagent-server 0.1.0 → 1.0.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 +83 -8
- package/package.json +1 -1
- package/src/args.js +6 -4
- package/src/cli.js +1 -4
- package/src/dependencies.js +1 -1
- package/src/prompts.js +1 -0
- package/src/registry.js +8 -8
- package/src/scaffold.js +21 -7
- package/src/setup.js +2 -0
- package/src/version.js +1 -1
- package/src/versions.js +1 -1
- package/templates/deepagent/js/scripts/check.js +34 -11
- package/templates/deepagent/js/scripts/dev.js +9 -0
- package/templates/deepagent/js/src/agents/factory.js +2 -1
- package/templates/deepagent/js/src/agents/prompts/loader.js +9 -0
- package/templates/deepagent/js/src/agents/prompts/supervisor.js +4 -0
- package/templates/deepagent/js/src/agents/prompts/supervisor.md +1 -2
- package/templates/deepagent/js/src/agents/state/types.js +1 -0
- package/templates/deepagent/js/src/agents/subagents/analyst.js +4 -3
- package/templates/deepagent/js/src/agents/subagents/coder.js +1 -0
- package/templates/deepagent/js/src/agents/subagents/index.js +5 -4
- package/templates/deepagent/js/src/agents/supervisor.js +12 -4
- package/templates/deepagent/js/src/api/app.js +7 -0
- package/templates/deepagent/js/src/api/middleware/auth.js +9 -0
- package/templates/deepagent/js/src/api/middleware/error.js +4 -0
- package/templates/deepagent/js/src/api/routes/agent.js +19 -49
- package/templates/deepagent/js/src/api/routes/health.js +12 -3
- package/templates/deepagent/js/src/api/routes/session.js +28 -48
- package/templates/deepagent/js/src/app.js +31 -12
- package/templates/deepagent/js/src/backends/composite.js +2 -0
- package/templates/deepagent/js/src/backends/filesystem.js +1 -0
- package/templates/deepagent/js/src/backends/index.js +35 -3
- package/templates/deepagent/js/src/backends/sandbox.js +3 -0
- package/templates/deepagent/js/src/config/agent.js +1 -0
- package/templates/deepagent/js/src/config/database.js +19 -0
- package/templates/deepagent/js/src/config/env.js +46 -23
- package/templates/deepagent/js/src/config/index.js +13 -3
- package/templates/deepagent/js/src/graph/checkpointer.js +10 -2
- package/templates/deepagent/js/src/graph/compile.js +1 -0
- package/templates/deepagent/js/src/graph/store.js +10 -2
- package/templates/deepagent/js/src/index.js +9 -2
- package/templates/deepagent/js/src/memory/index.js +2 -0
- package/templates/deepagent/js/src/memory/manager.js +21 -10
- package/templates/deepagent/js/src/memory/store.js +7 -0
- package/templates/deepagent/js/src/middleware/approval.js +6 -1
- package/templates/deepagent/js/src/middleware/context.js +5 -0
- package/templates/deepagent/js/src/middleware/logging.js +47 -43
- package/templates/deepagent/js/src/middleware/security.js +7 -0
- package/templates/deepagent/js/src/model/config.js +38 -0
- package/templates/deepagent/js/src/model/index.js +9 -0
- package/templates/deepagent/js/src/model/openai-compatible.js +18 -0
- package/templates/deepagent/js/src/model/presets.js +71 -0
- package/templates/deepagent/js/src/sandbox/config.js +12 -0
- package/templates/deepagent/js/src/sandbox/index.js +3 -0
- package/templates/deepagent/js/src/sandbox/manager.js +161 -0
- package/templates/deepagent/js/src/sandbox/opensandbox.js +195 -0
- package/templates/deepagent/js/src/schemas/agent.js +7 -0
- package/templates/deepagent/js/src/schemas/common.js +5 -0
- package/templates/deepagent/js/src/schemas/locale.js +1 -0
- package/templates/deepagent/js/src/schemas/session.js +4 -0
- package/templates/deepagent/js/src/services/{agent.service.js → agent.js} +39 -20
- package/templates/deepagent/js/src/services/{memory.service.js → memory.js} +13 -7
- package/templates/deepagent/js/src/services/{session.service.js → session.js} +43 -17
- package/templates/deepagent/js/src/skills/index.js +4 -0
- package/templates/deepagent/js/src/skills/loader.js +20 -10
- package/templates/deepagent/js/src/storage/database/client.js +57 -0
- package/templates/deepagent/{ts/src/infrastructure → js/src/storage}/database/migrations/001_init.sql +1 -1
- package/templates/deepagent/js/src/{infrastructure → storage}/logger/index.js +2 -0
- package/templates/deepagent/js/src/{infrastructure → storage}/redis/client.js +25 -19
- package/templates/deepagent/js/src/{infrastructure → storage}/shutdown/index.js +20 -13
- package/templates/deepagent/js/src/tools/database/index.js +1 -1
- package/templates/deepagent/js/src/tools/database/query.js +44 -32
- package/templates/deepagent/js/src/tools/filesystem/index.js +16 -0
- package/templates/deepagent/js/src/tools/index.js +6 -11
- package/templates/deepagent/js/src/tools/mcp/client.js +7 -0
- package/templates/deepagent/js/src/tools/mcp/connections.js +13 -3
- package/templates/deepagent/js/src/tools/mcp/index.js +2 -0
- package/templates/deepagent/js/src/tools/mcp/registry.js +15 -11
- package/templates/deepagent/js/src/utils/errors.js +9 -0
- package/templates/deepagent/js/src/utils/helpers.js +15 -0
- package/templates/deepagent/js/src/utils/validation.js +15 -0
- package/templates/deepagent/js/tests/agents/prompts.test.js +9 -3
- package/templates/deepagent/js/tests/agents/supervisor.test.js +13 -5
- package/templates/deepagent/js/tests/config/database.test.js +40 -0
- package/templates/deepagent/js/tests/integration/api.test.js +18 -3
- package/templates/deepagent/js/tests/middleware/security.test.js +4 -1
- package/templates/deepagent/js/tests/model/config.test.js +61 -0
- package/templates/deepagent/js/tests/sandbox/config.test.js +46 -0
- package/templates/deepagent/js/tests/sandbox/manager.test.js +236 -0
- package/templates/deepagent/js/tests/sandbox/opensandbox.test.js +173 -0
- package/templates/deepagent/js/tests/services/session.test.js +41 -0
- package/templates/deepagent/js/tests/tools/query.test.js +5 -1
- package/templates/deepagent/shared/README.md +101 -14
- package/templates/deepagent/shared/_env.example +40 -10
- package/templates/deepagent/shared/deployment/docker-compose.yml +8 -4
- package/templates/deepagent/shared/resources/AGENTS.md +1 -1
- package/templates/deepagent/ts/scripts/check.ts +19 -11
- package/templates/deepagent/ts/scripts/copy-assets.ts +2 -0
- package/templates/deepagent/ts/src/agents/factory.ts +1 -1
- package/templates/deepagent/ts/src/agents/prompts/loader.ts +1 -0
- package/templates/deepagent/ts/src/agents/prompts/supervisor.md +1 -2
- package/templates/deepagent/ts/src/agents/prompts/supervisor.ts +1 -1
- package/templates/deepagent/ts/src/agents/subagents/analyst.ts +7 -3
- package/templates/deepagent/ts/src/agents/subagents/index.ts +4 -5
- package/templates/deepagent/ts/src/agents/supervisor.ts +11 -9
- package/templates/deepagent/ts/src/api/app.ts +4 -4
- package/templates/deepagent/ts/src/api/middleware/auth.ts +1 -0
- package/templates/deepagent/ts/src/api/middleware/error.ts +1 -1
- package/templates/deepagent/ts/src/api/routes/agent.ts +13 -58
- package/templates/deepagent/ts/src/api/routes/health.ts +5 -3
- package/templates/deepagent/ts/src/api/routes/session.ts +21 -51
- package/templates/deepagent/ts/src/app.ts +19 -12
- package/templates/deepagent/ts/src/backends/index.ts +41 -7
- package/templates/deepagent/ts/src/backends/sandbox.ts +1 -0
- package/templates/deepagent/ts/src/config/database.ts +21 -0
- package/templates/deepagent/ts/src/config/env.ts +32 -28
- package/templates/deepagent/ts/src/config/index.ts +12 -4
- package/templates/deepagent/ts/src/graph/checkpointer.ts +5 -2
- package/templates/deepagent/ts/src/graph/store.ts +5 -2
- package/templates/deepagent/ts/src/index.ts +2 -2
- package/templates/deepagent/ts/src/memory/manager.ts +12 -10
- package/templates/deepagent/ts/src/memory/store.ts +2 -0
- package/templates/deepagent/ts/src/middleware/approval.ts +2 -2
- package/templates/deepagent/ts/src/middleware/logging.ts +43 -44
- package/templates/deepagent/ts/src/middleware/security.ts +1 -0
- package/templates/deepagent/ts/src/model/config.ts +56 -0
- package/templates/deepagent/ts/src/model/index.ts +14 -0
- package/templates/deepagent/ts/src/model/openai-compatible.ts +21 -0
- package/templates/deepagent/ts/src/model/presets.ts +82 -0
- package/templates/deepagent/ts/src/sandbox/config.ts +30 -0
- package/templates/deepagent/ts/src/sandbox/index.ts +7 -0
- package/templates/deepagent/ts/src/sandbox/manager.ts +176 -0
- package/templates/deepagent/ts/src/sandbox/opensandbox.ts +216 -0
- package/templates/deepagent/ts/src/services/{agent.service.ts → agent.ts} +22 -22
- package/templates/deepagent/ts/src/services/{memory.service.ts → memory.ts} +7 -7
- package/templates/deepagent/ts/src/services/{session.service.ts → session.ts} +29 -19
- package/templates/deepagent/ts/src/skills/loader.ts +6 -10
- package/templates/deepagent/ts/src/storage/database/client.ts +65 -0
- package/templates/deepagent/{js/src/infrastructure → ts/src/storage}/database/migrations/001_init.sql +1 -1
- package/templates/deepagent/ts/src/{infrastructure → storage}/redis/client.ts +14 -21
- package/templates/deepagent/ts/src/{infrastructure → storage}/shutdown/index.ts +10 -13
- package/templates/deepagent/ts/src/tools/database/index.ts +5 -1
- package/templates/deepagent/ts/src/tools/database/query.ts +40 -32
- package/templates/deepagent/ts/src/tools/filesystem/index.ts +2 -0
- package/templates/deepagent/ts/src/tools/index.ts +10 -8
- package/templates/deepagent/ts/src/tools/mcp/client.ts +1 -0
- package/templates/deepagent/ts/src/tools/mcp/connections.ts +3 -3
- package/templates/deepagent/ts/src/tools/mcp/registry.ts +9 -12
- package/templates/deepagent/ts/src/utils/helpers.ts +5 -0
- package/templates/deepagent/ts/src/utils/validation.ts +17 -0
- package/templates/deepagent/ts/tests/agents/prompts.test.ts +3 -3
- package/templates/deepagent/ts/tests/agents/supervisor.test.ts +5 -5
- package/templates/deepagent/ts/tests/config/database.test.ts +40 -0
- package/templates/deepagent/ts/tests/integration/api.test.ts +5 -6
- package/templates/deepagent/ts/tests/middleware/security.test.ts +1 -1
- package/templates/deepagent/ts/tests/model/config.test.ts +61 -0
- package/templates/deepagent/ts/tests/sandbox/config.test.ts +46 -0
- package/templates/deepagent/ts/tests/sandbox/manager.test.ts +241 -0
- package/templates/deepagent/ts/tests/sandbox/opensandbox.test.ts +188 -0
- package/templates/deepagent/ts/tests/services/session.test.ts +45 -0
- package/templates/deepagent/ts/tests/tools/query.test.ts +1 -1
- package/templates/deepagent/js/src/agents/prompts/subagents/researcher.md +0 -16
- package/templates/deepagent/js/src/agents/subagents/researcher.js +0 -12
- package/templates/deepagent/js/src/config/model.js +0 -34
- package/templates/deepagent/js/src/infrastructure/database/client.js +0 -43
- package/templates/deepagent/js/src/tools/search/index.js +0 -1
- package/templates/deepagent/js/src/tools/search/web-search.js +0 -54
- package/templates/deepagent/shared/skills/research/SKILL.md +0 -31
- package/templates/deepagent/ts/src/agents/prompts/subagents/researcher.md +0 -16
- package/templates/deepagent/ts/src/agents/subagents/researcher.ts +0 -15
- package/templates/deepagent/ts/src/config/model.ts +0 -49
- package/templates/deepagent/ts/src/infrastructure/database/client.ts +0 -61
- package/templates/deepagent/ts/src/tools/search/index.ts +0 -1
- package/templates/deepagent/ts/src/tools/search/web-search.ts +0 -82
- /package/templates/deepagent/ts/src/{infrastructure → storage}/logger/index.ts +0 -0
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI 兼容服务商预设。
|
|
3
|
+
*
|
|
4
|
+
* 模板统一通过 OpenAI 兼容协议(`POST {baseUrl}/chat/completions`)接入模型,
|
|
5
|
+
* 因此这里只维护各家的接口地址与默认模型。只要服务实现了同一套协议,
|
|
6
|
+
* 增加一个预设就能接入,不需要引入新的 SDK。
|
|
7
|
+
*/
|
|
8
|
+
export const MODEL_PROVIDERS = [
|
|
9
|
+
"openai",
|
|
10
|
+
"deepseek",
|
|
11
|
+
"moonshot",
|
|
12
|
+
"minimax",
|
|
13
|
+
"qwen",
|
|
14
|
+
"zhipu",
|
|
15
|
+
"openrouter",
|
|
16
|
+
"ollama",
|
|
17
|
+
"vllm",
|
|
18
|
+
"custom",
|
|
19
|
+
];
|
|
20
|
+
|
|
21
|
+
export const OPENAI_COMPATIBLE_PRESETS = {
|
|
22
|
+
openai: {
|
|
23
|
+
label: "OpenAI",
|
|
24
|
+
baseUrl: "https://api.openai.com/v1",
|
|
25
|
+
defaultModel: "gpt-4.1-mini",
|
|
26
|
+
},
|
|
27
|
+
deepseek: {
|
|
28
|
+
label: "DeepSeek",
|
|
29
|
+
baseUrl: "https://api.deepseek.com/v1",
|
|
30
|
+
defaultModel: "deepseek-chat",
|
|
31
|
+
},
|
|
32
|
+
moonshot: {
|
|
33
|
+
label: "Moonshot Kimi",
|
|
34
|
+
baseUrl: "https://api.moonshot.cn/v1",
|
|
35
|
+
defaultModel: "kimi-latest",
|
|
36
|
+
},
|
|
37
|
+
minimax: {
|
|
38
|
+
label: "MiniMax",
|
|
39
|
+
// 国内站为 api.minimaxi.com,国际站使用 https://api.minimax.io/v1。
|
|
40
|
+
baseUrl: "https://api.minimaxi.com/v1",
|
|
41
|
+
defaultModel: "MiniMax-M3",
|
|
42
|
+
},
|
|
43
|
+
qwen: {
|
|
44
|
+
label: "通义千问(阿里云百炼)",
|
|
45
|
+
baseUrl: "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
|
46
|
+
defaultModel: "qwen-plus",
|
|
47
|
+
},
|
|
48
|
+
zhipu: {
|
|
49
|
+
label: "智谱 GLM",
|
|
50
|
+
baseUrl: "https://open.bigmodel.cn/api/paas/v4",
|
|
51
|
+
defaultModel: "glm-4.6",
|
|
52
|
+
},
|
|
53
|
+
openrouter: {
|
|
54
|
+
label: "OpenRouter",
|
|
55
|
+
baseUrl: "https://openrouter.ai/api/v1",
|
|
56
|
+
defaultModel: "openai/gpt-4.1-mini",
|
|
57
|
+
},
|
|
58
|
+
ollama: {
|
|
59
|
+
label: "Ollama(本地)",
|
|
60
|
+
baseUrl: "http://localhost:11434/v1",
|
|
61
|
+
defaultModel: "qwen3:8b",
|
|
62
|
+
},
|
|
63
|
+
vllm: {
|
|
64
|
+
label: "vLLM(本地)",
|
|
65
|
+
baseUrl: "http://localhost:8000/v1",
|
|
66
|
+
},
|
|
67
|
+
custom: {
|
|
68
|
+
label: "自定义 OpenAI 兼容服务",
|
|
69
|
+
baseUrl: "",
|
|
70
|
+
},
|
|
71
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export const resolveSandboxConfig = (env) => {
|
|
2
|
+
return {
|
|
3
|
+
enabled: env.SANDBOX_ENABLED,
|
|
4
|
+
domain: env.OPEN_SANDBOX_DOMAIN,
|
|
5
|
+
protocol: env.OPEN_SANDBOX_PROTOCOL,
|
|
6
|
+
...(env.OPEN_SANDBOX_API_KEY ? { apiKey: env.OPEN_SANDBOX_API_KEY } : {}),
|
|
7
|
+
...(env.OPEN_SANDBOX_ID ? { sandboxId: env.OPEN_SANDBOX_ID } : {}),
|
|
8
|
+
image: env.SANDBOX_IMAGE,
|
|
9
|
+
...(env.SANDBOX_TIMEOUT_SECONDS > 0 ? { timeoutSeconds: env.SANDBOX_TIMEOUT_SECONDS } : {}),
|
|
10
|
+
workspaceRoot: env.SANDBOX_WORKSPACE_ROOT,
|
|
11
|
+
};
|
|
12
|
+
};
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { SandboxApiException } from "@alibaba-group/opensandbox";
|
|
2
|
+
|
|
3
|
+
import { errorMessage, isRecord } from "../utils/helpers.js";
|
|
4
|
+
import { createOpenSandboxBackend } from "./opensandbox.js";
|
|
5
|
+
|
|
6
|
+
/** 从工具运行时中取出会话 ID;memory/skills 中间件只传 state 时返回 undefined。 */
|
|
7
|
+
export const threadIdFromRuntime = (runtime) => {
|
|
8
|
+
if (!isRecord(runtime)) return undefined;
|
|
9
|
+
|
|
10
|
+
const context = runtime.context;
|
|
11
|
+
if (isRecord(context) && typeof context.threadId === "string" && context.threadId !== "") {
|
|
12
|
+
return context.threadId;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const config = runtime.config;
|
|
16
|
+
if (!isRecord(config)) return undefined;
|
|
17
|
+
|
|
18
|
+
const configurable = config.configurable;
|
|
19
|
+
if (!isRecord(configurable)) return undefined;
|
|
20
|
+
|
|
21
|
+
const threadId = configurable.thread_id;
|
|
22
|
+
return typeof threadId === "string" && threadId !== "" ? threadId : undefined;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** 续期节奏:TTL 的 1/3,且不少于 1 秒。 */
|
|
26
|
+
const renewIntervalMs = (timeoutSeconds) => Math.max(1_000, (timeoutSeconds * 1_000) / 3);
|
|
27
|
+
|
|
28
|
+
/** 判断沙箱是否已被服务端回收(过期、被 kill 或已不存在)。 */
|
|
29
|
+
const isGone = (error) => {
|
|
30
|
+
if (error instanceof SandboxApiException && error.statusCode === 404) return true;
|
|
31
|
+
|
|
32
|
+
const message = errorMessage(error).toLowerCase();
|
|
33
|
+
return ["not found", "no such", "terminated", "expired", "killed"].some((hint) =>
|
|
34
|
+
message.includes(hint),
|
|
35
|
+
);
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 按会话管理 OpenSandbox 沙箱。
|
|
40
|
+
*
|
|
41
|
+
* - 默认每个 `threadId` 首次使用时创建一个沙箱,该会话后续的消息、工具调用
|
|
42
|
+
* 与子 Agent 都复用同一个后端;
|
|
43
|
+
* - 配置了 `SANDBOX_TIMEOUT_SECONDS` 时,每次使用间隔超过 TTL 的 1/3 会调用
|
|
44
|
+
* `renew` 续期,活跃会话不会被服务端回收;续期发现沙箱已不存在时自动重建;
|
|
45
|
+
* - 配置 `OPEN_SANDBOX_ID` 时退化为「所有会话共享一个已存在的沙箱」,不续期;
|
|
46
|
+
* - 删除会话时调用 `release(threadId)`,进程退出时 `closeAll()`。
|
|
47
|
+
*/
|
|
48
|
+
export class SandboxManager {
|
|
49
|
+
config;
|
|
50
|
+
createSandbox;
|
|
51
|
+
now;
|
|
52
|
+
sandboxes = new Map();
|
|
53
|
+
renewedAt = new Map();
|
|
54
|
+
shared;
|
|
55
|
+
|
|
56
|
+
constructor(config, { create = createOpenSandboxBackend, now = Date.now } = {}) {
|
|
57
|
+
this.config = config;
|
|
58
|
+
this.createSandbox = create;
|
|
59
|
+
this.now = now;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 当前持有(或正在创建)的沙箱数量。 */
|
|
63
|
+
get size() {
|
|
64
|
+
return this.sandboxes.size + (this.shared ? 1 : 0);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
get(threadId) {
|
|
68
|
+
if (this.config.sandboxId) {
|
|
69
|
+
this.shared ??= this.createSandbox(this.config).catch((error) => {
|
|
70
|
+
this.shared = undefined;
|
|
71
|
+
throw error;
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
return this.shared;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const existing = this.sandboxes.get(threadId);
|
|
78
|
+
if (existing) return this.keepAlive(threadId, existing);
|
|
79
|
+
|
|
80
|
+
return this.create(threadId);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** 释放某个会话的沙箱;共享沙箱模式下不处理。 */
|
|
84
|
+
async release(threadId) {
|
|
85
|
+
if (this.config.sandboxId) return;
|
|
86
|
+
|
|
87
|
+
const pending = this.sandboxes.get(threadId);
|
|
88
|
+
this.sandboxes.delete(threadId);
|
|
89
|
+
this.renewedAt.delete(threadId);
|
|
90
|
+
if (!pending) return;
|
|
91
|
+
|
|
92
|
+
const sandbox = await pending.catch(() => undefined);
|
|
93
|
+
await sandbox?.destroy();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 关闭所有沙箱(应用退出时调用)。 */
|
|
97
|
+
async closeAll() {
|
|
98
|
+
const pending = this.config.sandboxId ? [this.shared] : [...this.sandboxes.values()];
|
|
99
|
+
|
|
100
|
+
this.shared = undefined;
|
|
101
|
+
this.sandboxes.clear();
|
|
102
|
+
this.renewedAt.clear();
|
|
103
|
+
|
|
104
|
+
const sandboxes = await Promise.all(
|
|
105
|
+
pending.map((item) => item?.catch(() => undefined) ?? Promise.resolve(undefined)),
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
await Promise.all(sandboxes.map((sandbox) => sandbox?.destroy() ?? Promise.resolve()));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
create(threadId) {
|
|
112
|
+
const created = this.createSandbox(this.config)
|
|
113
|
+
.then((sandbox) => {
|
|
114
|
+
this.renewedAt.set(threadId, this.now());
|
|
115
|
+
return sandbox;
|
|
116
|
+
})
|
|
117
|
+
.catch((error) => {
|
|
118
|
+
this.sandboxes.delete(threadId);
|
|
119
|
+
this.renewedAt.delete(threadId);
|
|
120
|
+
throw error;
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
this.sandboxes.set(threadId, created);
|
|
124
|
+
return created;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 使用中的沙箱按 TTL 的 1/3 续期,避免活跃会话被过期回收;
|
|
129
|
+
* 续期失败但沙箱仍在时继续复用,确认已被回收时重建。
|
|
130
|
+
*/
|
|
131
|
+
keepAlive(threadId, pending) {
|
|
132
|
+
const timeoutSeconds = this.config.timeoutSeconds;
|
|
133
|
+
if (!timeoutSeconds) return pending;
|
|
134
|
+
|
|
135
|
+
const now = this.now();
|
|
136
|
+
const renewedAt = this.renewedAt.get(threadId) ?? 0;
|
|
137
|
+
if (now - renewedAt < renewIntervalMs(timeoutSeconds)) return pending;
|
|
138
|
+
|
|
139
|
+
this.renewedAt.set(threadId, now);
|
|
140
|
+
|
|
141
|
+
return pending.then(async (sandbox) => {
|
|
142
|
+
return sandbox.renew(timeoutSeconds).then(
|
|
143
|
+
() => sandbox,
|
|
144
|
+
(error) => {
|
|
145
|
+
if (!isGone(error)) return sandbox;
|
|
146
|
+
|
|
147
|
+
return this.rebuild(threadId, sandbox);
|
|
148
|
+
},
|
|
149
|
+
);
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** 丢弃已失效的沙箱并立即创建一个新的。 */
|
|
154
|
+
rebuild(threadId, stale) {
|
|
155
|
+
this.sandboxes.delete(threadId);
|
|
156
|
+
this.renewedAt.delete(threadId);
|
|
157
|
+
void stale.destroy().catch(() => undefined);
|
|
158
|
+
|
|
159
|
+
return this.create(threadId);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { ConnectionConfig, Sandbox, SandboxApiException } from "@alibaba-group/opensandbox";
|
|
2
|
+
import { BaseSandbox } from "deepagents";
|
|
3
|
+
|
|
4
|
+
import { errorMessage } from "../utils/helpers.js";
|
|
5
|
+
|
|
6
|
+
const MAX_OUTPUT_CHARS = 100_000;
|
|
7
|
+
|
|
8
|
+
const parentDirectory = (filePath) => {
|
|
9
|
+
const index = filePath.lastIndexOf("/");
|
|
10
|
+
return index <= 0 ? "/" : filePath.slice(0, index);
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
const fileError = (error) => {
|
|
14
|
+
if (error instanceof SandboxApiException) {
|
|
15
|
+
if (error.statusCode === 404) return "file_not_found";
|
|
16
|
+
if (error.statusCode === 403) return "permission_denied";
|
|
17
|
+
if (error.statusCode === 400) return "invalid_path";
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const message = errorMessage(error).toLowerCase();
|
|
21
|
+
if (message.includes("not found") || message.includes("no such file")) return "file_not_found";
|
|
22
|
+
if (message.includes("permission")) return "permission_denied";
|
|
23
|
+
if (message.includes("directory")) return "is_directory";
|
|
24
|
+
|
|
25
|
+
return "invalid_path";
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const isMissingSession = (error) => {
|
|
29
|
+
if (error instanceof SandboxApiException && error.statusCode === 404) return true;
|
|
30
|
+
|
|
31
|
+
const message = errorMessage(error).toLowerCase();
|
|
32
|
+
return (
|
|
33
|
+
message.includes("session") &&
|
|
34
|
+
["not found", "expired", "invalid"].some((hint) => message.includes(hint))
|
|
35
|
+
);
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const formatExecution = (execution) => {
|
|
39
|
+
const stdout = execution.logs.stdout.map((message) => message.text);
|
|
40
|
+
const stderr = execution.logs.stderr.map((message) => `[stderr] ${message.text}`);
|
|
41
|
+
const output = [...stdout, ...stderr].join("\n");
|
|
42
|
+
const truncated = output.length > MAX_OUTPUT_CHARS;
|
|
43
|
+
const exitCode = execution.exitCode ?? execution.error?.exitCode ?? (execution.error ? 1 : 0);
|
|
44
|
+
|
|
45
|
+
return {
|
|
46
|
+
output: truncated ? `${output.slice(0, MAX_OUTPUT_CHARS)}\n… 输出已截断` : output,
|
|
47
|
+
exitCode,
|
|
48
|
+
truncated,
|
|
49
|
+
};
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 把 OpenSandbox 沙箱接入 deepagents。
|
|
54
|
+
*
|
|
55
|
+
* 一个后端实例持有同一个远程沙箱:`execute` 在沙箱内维护一个持久 bash session,
|
|
56
|
+
* 因此 `cd`、`export`、函数定义等状态会跨命令保留;命令按顺序串行执行,
|
|
57
|
+
* 避免并发命令互相覆盖 shell 状态。文件读写仍走 `sandbox.files`,
|
|
58
|
+
* `ls` / `read` / `grep` / `glob` / `edit` 由 `BaseSandbox` 复用 session 完成。
|
|
59
|
+
*/
|
|
60
|
+
export class OpenSandboxBackend extends BaseSandbox {
|
|
61
|
+
id;
|
|
62
|
+
|
|
63
|
+
sandbox;
|
|
64
|
+
workspaceRoot;
|
|
65
|
+
owned;
|
|
66
|
+
|
|
67
|
+
session;
|
|
68
|
+
queue = Promise.resolve();
|
|
69
|
+
|
|
70
|
+
constructor({ sandbox, workspaceRoot = "/workspace", owned = true }) {
|
|
71
|
+
super();
|
|
72
|
+
this.sandbox = sandbox;
|
|
73
|
+
this.workspaceRoot = workspaceRoot;
|
|
74
|
+
this.owned = owned;
|
|
75
|
+
this.id = sandbox.id;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
execute(command) {
|
|
79
|
+
const result = this.queue.then(() => this.runInSession(command));
|
|
80
|
+
|
|
81
|
+
this.queue = result.then(
|
|
82
|
+
() => undefined,
|
|
83
|
+
() => undefined,
|
|
84
|
+
);
|
|
85
|
+
|
|
86
|
+
return result;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
async uploadFiles(files) {
|
|
90
|
+
return Promise.all(
|
|
91
|
+
files.map(([filePath, content]) => {
|
|
92
|
+
const directory = parentDirectory(filePath);
|
|
93
|
+
const prepare = directory === "/" ? Promise.resolve() : this.ensureDirectory(directory);
|
|
94
|
+
|
|
95
|
+
return prepare
|
|
96
|
+
.then(() =>
|
|
97
|
+
this.sandbox.files.writeFiles([{ path: filePath, data: content, mode: 0o644 }]),
|
|
98
|
+
)
|
|
99
|
+
.then(
|
|
100
|
+
() => ({ path: filePath, error: null }),
|
|
101
|
+
(error) => ({ path: filePath, error: fileError(error) }),
|
|
102
|
+
);
|
|
103
|
+
}),
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async downloadFiles(paths) {
|
|
108
|
+
return Promise.all(
|
|
109
|
+
paths.map((filePath) => {
|
|
110
|
+
return this.sandbox.files.readBytes(filePath).then(
|
|
111
|
+
(content) => ({ path: filePath, content, error: null }),
|
|
112
|
+
(error) => ({ path: filePath, content: null, error: fileError(error) }),
|
|
113
|
+
);
|
|
114
|
+
}),
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 续期沙箱 TTL;服务端已回收时抛错(通常 404),由 SandboxManager 决定是否重建。 */
|
|
119
|
+
async renew(timeoutSeconds) {
|
|
120
|
+
await this.sandbox.renew(timeoutSeconds);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** 关闭会话、终止(仅限自建)沙箱并释放 SDK 连接资源。 */
|
|
124
|
+
async destroy() {
|
|
125
|
+
const session = await this.session?.catch(() => undefined);
|
|
126
|
+
if (session) {
|
|
127
|
+
await this.sandbox.commands.deleteSession(session).catch(() => undefined);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (this.owned) {
|
|
131
|
+
await this.sandbox.kill().catch(() => undefined);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
await this.sandbox.close().catch(() => undefined);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
runInSession(command) {
|
|
138
|
+
return this.executeInSession(command).catch((error) => {
|
|
139
|
+
if (!isMissingSession(error)) throw error;
|
|
140
|
+
|
|
141
|
+
this.session = undefined;
|
|
142
|
+
return this.executeInSession(command);
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async executeInSession(command) {
|
|
147
|
+
const sessionId = await this.ensureSession();
|
|
148
|
+
const execution = await this.sandbox.commands.runInSession(sessionId, command);
|
|
149
|
+
|
|
150
|
+
return formatExecution(execution);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
ensureSession() {
|
|
154
|
+
this.session ??= this.sandbox.commands
|
|
155
|
+
.createSession({ workingDirectory: this.workspaceRoot })
|
|
156
|
+
.catch((error) => {
|
|
157
|
+
this.session = undefined;
|
|
158
|
+
throw error;
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
return this.session;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
ensureDirectory(directory) {
|
|
165
|
+
return this.sandbox.files.createDirectories([{ path: directory, mode: 0o755 }]);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** 创建(或连接)OpenSandbox 沙箱,并预热工作目录。 */
|
|
170
|
+
export const createOpenSandboxBackend = async (config) => {
|
|
171
|
+
const connectionConfig = new ConnectionConfig({
|
|
172
|
+
domain: config.domain,
|
|
173
|
+
protocol: config.protocol,
|
|
174
|
+
...(config.apiKey ? { apiKey: config.apiKey } : {}),
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
const sandbox = config.sandboxId
|
|
178
|
+
? await Sandbox.connect({ connectionConfig, sandboxId: config.sandboxId })
|
|
179
|
+
: await Sandbox.create({
|
|
180
|
+
connectionConfig,
|
|
181
|
+
image: config.image,
|
|
182
|
+
timeoutSeconds: config.timeoutSeconds ?? null,
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
const owned = !config.sandboxId;
|
|
186
|
+
|
|
187
|
+
return sandbox.files.createDirectories([{ path: config.workspaceRoot, mode: 0o755 }]).then(
|
|
188
|
+
() => new OpenSandboxBackend({ sandbox, workspaceRoot: config.workspaceRoot, owned }),
|
|
189
|
+
async (error) => {
|
|
190
|
+
if (owned) await sandbox.kill().catch(() => undefined);
|
|
191
|
+
await sandbox.close().catch(() => undefined);
|
|
192
|
+
throw error;
|
|
193
|
+
},
|
|
194
|
+
);
|
|
195
|
+
};
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
|
|
2
3
|
import { threadIdSchema } from "./common.js";
|
|
4
|
+
|
|
3
5
|
export const invokeAgentSchema = z.object({
|
|
4
6
|
message: z.string().min(1).max(32_000),
|
|
5
7
|
threadId: threadIdSchema.optional(),
|
|
@@ -7,26 +9,31 @@ export const invokeAgentSchema = z.object({
|
|
|
7
9
|
userId: z.string().min(1).max(128).optional(),
|
|
8
10
|
objective: z.string().max(2_000).optional(),
|
|
9
11
|
});
|
|
12
|
+
|
|
10
13
|
export const messageSchema = z.object({
|
|
11
14
|
role: z.string(),
|
|
12
15
|
content: z.unknown(),
|
|
13
16
|
});
|
|
17
|
+
|
|
14
18
|
export const invokeAgentResponseSchema = z.object({
|
|
15
19
|
threadId: z.string(),
|
|
16
20
|
text: z.string(),
|
|
17
21
|
messages: z.array(messageSchema),
|
|
18
22
|
});
|
|
23
|
+
|
|
19
24
|
export const approvalDecisionSchema = z.discriminatedUnion("type", [
|
|
20
25
|
z.object({ type: z.literal("approve") }),
|
|
21
26
|
z.object({ type: z.literal("reject"), message: z.string().max(2_000).optional() }),
|
|
22
27
|
z.object({ type: z.literal("respond"), message: z.string().max(8_000) }),
|
|
23
28
|
]);
|
|
29
|
+
|
|
24
30
|
export const resumeAgentSchema = z.object({
|
|
25
31
|
threadId: threadIdSchema,
|
|
26
32
|
tenantId: z.string().min(1).max(128).default("default"),
|
|
27
33
|
userId: z.string().min(1).max(128).optional(),
|
|
28
34
|
decisions: z.array(approvalDecisionSchema).min(1),
|
|
29
35
|
});
|
|
36
|
+
|
|
30
37
|
export const streamEventSchema = z.object({
|
|
31
38
|
event: z.enum(["token", "values", "error", "done"]),
|
|
32
39
|
data: z.unknown(),
|
|
@@ -1,15 +1,20 @@
|
|
|
1
1
|
import "./locale.js";
|
|
2
|
+
|
|
2
3
|
import { z } from "zod";
|
|
4
|
+
|
|
3
5
|
export const idSchema = z.string().uuid();
|
|
6
|
+
|
|
4
7
|
export const threadIdSchema = z
|
|
5
8
|
.string()
|
|
6
9
|
.min(1)
|
|
7
10
|
.max(128)
|
|
8
11
|
.regex(/^[a-zA-Z0-9._:-]+$/, "会话 ID 只能包含字母、数字、点、下划线、冒号和短横线。");
|
|
12
|
+
|
|
9
13
|
export const paginationSchema = z.object({
|
|
10
14
|
limit: z.coerce.number().int().min(1).max(100).default(20),
|
|
11
15
|
offset: z.coerce.number().int().min(0).default(0),
|
|
12
16
|
});
|
|
17
|
+
|
|
13
18
|
export const apiErrorSchema = z.object({
|
|
14
19
|
error: z.object({
|
|
15
20
|
code: z.string(),
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
|
|
2
3
|
import { threadIdSchema } from "./common.js";
|
|
4
|
+
|
|
3
5
|
export const createSessionSchema = z.object({
|
|
4
6
|
threadId: threadIdSchema.optional(),
|
|
5
7
|
title: z.string().min(1).max(200).default("未命名会话"),
|
|
@@ -7,6 +9,7 @@ export const createSessionSchema = z.object({
|
|
|
7
9
|
userId: z.string().min(1).max(128).optional(),
|
|
8
10
|
metadata: z.record(z.string(), z.unknown()).default({}),
|
|
9
11
|
});
|
|
12
|
+
|
|
10
13
|
export const sessionSummarySchema = z.object({
|
|
11
14
|
threadId: z.string(),
|
|
12
15
|
title: z.string(),
|
|
@@ -17,6 +20,7 @@ export const sessionSummarySchema = z.object({
|
|
|
17
20
|
messageCount: z.number().int().nonnegative(),
|
|
18
21
|
metadata: z.record(z.string(), z.unknown()).default({}),
|
|
19
22
|
});
|
|
23
|
+
|
|
20
24
|
export const sessionListSchema = z.object({
|
|
21
25
|
sessions: z.array(sessionSummarySchema),
|
|
22
26
|
total: z.number().int().nonnegative(),
|
|
@@ -1,30 +1,38 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
+
|
|
2
3
|
import { Command } from "@langchain/langgraph";
|
|
4
|
+
|
|
3
5
|
import { lastMessageText } from "../utils/helpers.js";
|
|
6
|
+
|
|
4
7
|
/**
|
|
5
8
|
* 应用层 Agent API:构建 invoke 输入,附加会话、租户和运行时上下文,
|
|
6
9
|
* 并把结果整理为适合 HTTP 客户端的形式。
|
|
7
10
|
*/
|
|
8
11
|
export class AgentService {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
+
agent;
|
|
13
|
+
config;
|
|
14
|
+
sessions;
|
|
15
|
+
|
|
12
16
|
constructor({ agent, config, sessions }) {
|
|
13
|
-
this
|
|
14
|
-
this
|
|
15
|
-
this
|
|
17
|
+
this.agent = agent;
|
|
18
|
+
this.config = config;
|
|
19
|
+
this.sessions = sessions;
|
|
16
20
|
}
|
|
21
|
+
|
|
17
22
|
get graph() {
|
|
18
|
-
return this
|
|
23
|
+
return this.agent;
|
|
19
24
|
}
|
|
25
|
+
|
|
20
26
|
async invoke(input, { signal } = {}) {
|
|
21
27
|
const threadId = input.threadId ?? randomUUID();
|
|
22
|
-
|
|
28
|
+
|
|
29
|
+
await this.sessions?.ensure({
|
|
23
30
|
threadId,
|
|
24
31
|
tenantId: input.tenantId,
|
|
25
32
|
...(input.userId ? { userId: input.userId } : {}),
|
|
26
33
|
});
|
|
27
|
-
|
|
34
|
+
|
|
35
|
+
const result = await this.agent.invoke(
|
|
28
36
|
{
|
|
29
37
|
messages: [{ role: "user", content: input.message }],
|
|
30
38
|
tenantId: input.tenantId,
|
|
@@ -33,7 +41,7 @@ export class AgentService {
|
|
|
33
41
|
},
|
|
34
42
|
{
|
|
35
43
|
configurable: { thread_id: threadId },
|
|
36
|
-
recursionLimit: this
|
|
44
|
+
recursionLimit: this.config.agent.recursionLimit,
|
|
37
45
|
context: {
|
|
38
46
|
tenantId: input.tenantId,
|
|
39
47
|
...(input.userId ? { userId: input.userId } : {}),
|
|
@@ -42,18 +50,20 @@ export class AgentService {
|
|
|
42
50
|
...(signal ? { signal } : {}),
|
|
43
51
|
},
|
|
44
52
|
);
|
|
45
|
-
|
|
53
|
+
|
|
54
|
+
return this.finish(threadId, input.tenantId, result);
|
|
46
55
|
}
|
|
56
|
+
|
|
47
57
|
/**
|
|
48
58
|
* 恢复因审批而暂停的运行。decisions 会按顺序匹配待处理的工具调用
|
|
49
59
|
* (approve、reject 或 respond)。
|
|
50
60
|
*/
|
|
51
61
|
async resume(input, { signal } = {}) {
|
|
52
|
-
const result = await this
|
|
62
|
+
const result = await this.agent.invoke(
|
|
53
63
|
new Command({ resume: { decisions: input.decisions } }),
|
|
54
64
|
{
|
|
55
65
|
configurable: { thread_id: input.threadId },
|
|
56
|
-
recursionLimit: this
|
|
66
|
+
recursionLimit: this.config.agent.recursionLimit,
|
|
57
67
|
context: {
|
|
58
68
|
tenantId: input.tenantId,
|
|
59
69
|
...(input.userId ? { userId: input.userId } : {}),
|
|
@@ -62,17 +72,21 @@ export class AgentService {
|
|
|
62
72
|
...(signal ? { signal } : {}),
|
|
63
73
|
},
|
|
64
74
|
);
|
|
65
|
-
|
|
75
|
+
|
|
76
|
+
return this.finish(input.threadId, input.tenantId, result);
|
|
66
77
|
}
|
|
67
|
-
|
|
78
|
+
|
|
79
|
+
async finish(threadId, tenantId, result) {
|
|
68
80
|
const messages = Array.isArray(result.messages) ? result.messages : [];
|
|
69
81
|
const text = lastMessageText(messages);
|
|
70
82
|
const interrupts = Array.isArray(result.__interrupt__) ? result.__interrupt__ : [];
|
|
71
|
-
|
|
83
|
+
|
|
84
|
+
await this.sessions?.touch({
|
|
72
85
|
threadId,
|
|
73
86
|
tenantId,
|
|
74
87
|
lastMessage: text,
|
|
75
88
|
});
|
|
89
|
+
|
|
76
90
|
return {
|
|
77
91
|
threadId,
|
|
78
92
|
text,
|
|
@@ -80,15 +94,18 @@ export class AgentService {
|
|
|
80
94
|
...(interrupts.length > 0 ? { interrupts } : {}),
|
|
81
95
|
};
|
|
82
96
|
}
|
|
97
|
+
|
|
83
98
|
/** 以状态快照流式输出 Agent 的工作过程(适配 SSE)。 */
|
|
84
99
|
async *stream(input, { signal } = {}) {
|
|
85
100
|
const threadId = input.threadId ?? randomUUID();
|
|
86
|
-
|
|
101
|
+
|
|
102
|
+
await this.sessions?.ensure({
|
|
87
103
|
threadId,
|
|
88
104
|
tenantId: input.tenantId,
|
|
89
105
|
...(input.userId ? { userId: input.userId } : {}),
|
|
90
106
|
});
|
|
91
|
-
|
|
107
|
+
|
|
108
|
+
const stream = await this.agent.stream(
|
|
92
109
|
{
|
|
93
110
|
messages: [{ role: "user", content: input.message }],
|
|
94
111
|
tenantId: input.tenantId,
|
|
@@ -97,7 +114,7 @@ export class AgentService {
|
|
|
97
114
|
},
|
|
98
115
|
{
|
|
99
116
|
configurable: { thread_id: threadId },
|
|
100
|
-
recursionLimit: this
|
|
117
|
+
recursionLimit: this.config.agent.recursionLimit,
|
|
101
118
|
streamMode: "values",
|
|
102
119
|
context: {
|
|
103
120
|
tenantId: input.tenantId,
|
|
@@ -107,11 +124,13 @@ export class AgentService {
|
|
|
107
124
|
...(signal ? { signal } : {}),
|
|
108
125
|
},
|
|
109
126
|
);
|
|
127
|
+
|
|
110
128
|
for await (const chunk of stream) {
|
|
111
129
|
yield { event: "values", data: chunk };
|
|
112
130
|
}
|
|
113
131
|
}
|
|
132
|
+
|
|
114
133
|
async state(threadId) {
|
|
115
|
-
return this
|
|
134
|
+
return this.agent.getState({ configurable: { thread_id: threadId } });
|
|
116
135
|
}
|
|
117
136
|
}
|