create-deepagent-server 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +292 -2
- package/bin/create-deepagent-server.js +27 -0
- package/package.json +50 -4
- package/src/args.js +195 -0
- package/src/cli.js +269 -0
- package/src/dependencies.js +34 -0
- package/src/prompts.js +86 -0
- package/src/registry.js +68 -0
- package/src/scaffold.js +181 -0
- package/src/setup.js +79 -0
- package/src/ui.js +43 -0
- package/src/version.js +1 -0
- package/src/versions.js +29 -0
- package/templates/deepagent/js/deployment/Dockerfile +19 -0
- package/templates/deepagent/js/scripts/check.js +97 -0
- package/templates/deepagent/js/scripts/dev.js +40 -0
- package/templates/deepagent/js/src/agents/factory.js +11 -0
- package/templates/deepagent/js/src/agents/index.js +4 -0
- package/templates/deepagent/js/src/agents/prompts/index.js +2 -0
- package/templates/deepagent/js/src/agents/prompts/loader.js +53 -0
- package/templates/deepagent/js/src/agents/prompts/subagents/analyst.md +17 -0
- package/templates/deepagent/js/src/agents/prompts/subagents/coder.md +17 -0
- package/templates/deepagent/js/src/agents/prompts/supervisor.js +21 -0
- package/templates/deepagent/js/src/agents/prompts/supervisor.md +41 -0
- package/templates/deepagent/js/src/agents/state/index.js +1 -0
- package/templates/deepagent/js/src/agents/state/types.js +11 -0
- package/templates/deepagent/js/src/agents/subagents/analyst.js +12 -0
- package/templates/deepagent/js/src/agents/subagents/coder.js +12 -0
- package/templates/deepagent/js/src/agents/subagents/index.js +9 -0
- package/templates/deepagent/js/src/agents/supervisor.js +64 -0
- package/templates/deepagent/js/src/api/app.js +29 -0
- package/templates/deepagent/js/src/api/middleware/auth.js +36 -0
- package/templates/deepagent/js/src/api/middleware/error.js +30 -0
- package/templates/deepagent/js/src/api/routes/agent.js +43 -0
- package/templates/deepagent/js/src/api/routes/health.js +40 -0
- package/templates/deepagent/js/src/api/routes/session.js +42 -0
- package/templates/deepagent/js/src/app.js +98 -0
- package/templates/deepagent/js/src/backends/composite.js +22 -0
- package/templates/deepagent/js/src/backends/filesystem.js +9 -0
- package/templates/deepagent/js/src/backends/index.js +60 -0
- package/templates/deepagent/js/src/backends/sandbox.js +26 -0
- package/templates/deepagent/js/src/config/agent.js +14 -0
- package/templates/deepagent/js/src/config/database.js +19 -0
- package/templates/deepagent/js/src/config/env.js +96 -0
- package/templates/deepagent/js/src/config/index.js +45 -0
- package/templates/deepagent/js/src/graph/checkpointer.js +28 -0
- package/templates/deepagent/js/src/graph/compile.js +9 -0
- package/templates/deepagent/js/src/graph/index.js +3 -0
- package/templates/deepagent/js/src/graph/store.js +28 -0
- package/templates/deepagent/js/src/index.js +39 -0
- package/templates/deepagent/js/src/memory/index.js +8 -0
- package/templates/deepagent/js/src/memory/manager.js +50 -0
- package/templates/deepagent/js/src/memory/store.js +43 -0
- package/templates/deepagent/js/src/middleware/approval.js +47 -0
- package/templates/deepagent/js/src/middleware/context.js +35 -0
- package/templates/deepagent/js/src/middleware/index.js +9 -0
- package/templates/deepagent/js/src/middleware/logging.js +70 -0
- package/templates/deepagent/js/src/middleware/security.js +58 -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 +40 -0
- package/templates/deepagent/js/src/schemas/common.js +24 -0
- package/templates/deepagent/js/src/schemas/locale.js +4 -0
- package/templates/deepagent/js/src/schemas/session.js +27 -0
- package/templates/deepagent/js/src/services/agent.js +136 -0
- package/templates/deepagent/js/src/services/memory.js +33 -0
- package/templates/deepagent/js/src/services/session.js +118 -0
- package/templates/deepagent/js/src/skills/index.js +21 -0
- package/templates/deepagent/js/src/skills/loader.js +75 -0
- package/templates/deepagent/js/src/storage/database/client.js +57 -0
- package/templates/deepagent/js/src/storage/database/migrations/001_init.sql +20 -0
- package/templates/deepagent/js/src/storage/logger/index.js +21 -0
- package/templates/deepagent/js/src/storage/redis/client.js +51 -0
- package/templates/deepagent/js/src/storage/shutdown/index.js +58 -0
- package/templates/deepagent/js/src/tools/database/index.js +1 -0
- package/templates/deepagent/js/src/tools/database/query.js +74 -0
- package/templates/deepagent/js/src/tools/filesystem/index.js +102 -0
- package/templates/deepagent/js/src/tools/index.js +25 -0
- package/templates/deepagent/js/src/tools/mcp/client.js +42 -0
- package/templates/deepagent/js/src/tools/mcp/connections.js +64 -0
- package/templates/deepagent/js/src/tools/mcp/index.js +10 -0
- package/templates/deepagent/js/src/tools/mcp/registry.js +36 -0
- package/templates/deepagent/js/src/utils/errors.js +73 -0
- package/templates/deepagent/js/src/utils/helpers.js +57 -0
- package/templates/deepagent/js/src/utils/validation.js +15 -0
- package/templates/deepagent/js/tests/agents/prompts.test.js +30 -0
- package/templates/deepagent/js/tests/agents/supervisor.test.js +42 -0
- package/templates/deepagent/js/tests/config/database.test.js +40 -0
- package/templates/deepagent/js/tests/integration/api.test.js +114 -0
- package/templates/deepagent/js/tests/middleware/security.test.js +27 -0
- 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 +27 -0
- package/templates/deepagent/shared/README.md +249 -0
- package/templates/deepagent/shared/_editorconfig +12 -0
- package/templates/deepagent/shared/_env.example +86 -0
- package/templates/deepagent/shared/_gitignore +22 -0
- package/templates/deepagent/shared/deployment/docker-compose.yml +60 -0
- package/templates/deepagent/shared/resources/AGENTS.md +32 -0
- package/templates/deepagent/shared/resources/knowledge/README.md +5 -0
- package/templates/deepagent/shared/skills/analysis/SKILL.md +28 -0
- package/templates/deepagent/shared/skills/coding/SKILL.md +28 -0
- package/templates/deepagent/shared/workspaces/README.md +5 -0
- package/templates/deepagent/ts/deployment/Dockerfile +25 -0
- package/templates/deepagent/ts/scripts/check.ts +99 -0
- package/templates/deepagent/ts/scripts/copy-assets.ts +37 -0
- package/templates/deepagent/ts/scripts/dev.ts +40 -0
- package/templates/deepagent/ts/src/agents/factory.ts +11 -0
- package/templates/deepagent/ts/src/agents/index.ts +4 -0
- package/templates/deepagent/ts/src/agents/prompts/index.ts +2 -0
- package/templates/deepagent/ts/src/agents/prompts/loader.ts +53 -0
- package/templates/deepagent/ts/src/agents/prompts/subagents/analyst.md +17 -0
- package/templates/deepagent/ts/src/agents/prompts/subagents/coder.md +17 -0
- package/templates/deepagent/ts/src/agents/prompts/supervisor.md +41 -0
- package/templates/deepagent/ts/src/agents/prompts/supervisor.ts +33 -0
- package/templates/deepagent/ts/src/agents/state/index.ts +1 -0
- package/templates/deepagent/ts/src/agents/state/types.ts +13 -0
- package/templates/deepagent/ts/src/agents/subagents/analyst.ts +18 -0
- package/templates/deepagent/ts/src/agents/subagents/coder.ts +14 -0
- package/templates/deepagent/ts/src/agents/subagents/index.ts +9 -0
- package/templates/deepagent/ts/src/agents/supervisor.ts +82 -0
- package/templates/deepagent/ts/src/api/app.ts +48 -0
- package/templates/deepagent/ts/src/api/middleware/auth.ts +38 -0
- package/templates/deepagent/ts/src/api/middleware/error.ts +33 -0
- package/templates/deepagent/ts/src/api/routes/agent.ts +48 -0
- package/templates/deepagent/ts/src/api/routes/health.ts +47 -0
- package/templates/deepagent/ts/src/api/routes/session.ts +47 -0
- package/templates/deepagent/ts/src/app.ts +111 -0
- package/templates/deepagent/ts/src/backends/composite.ts +34 -0
- package/templates/deepagent/ts/src/backends/filesystem.ts +19 -0
- package/templates/deepagent/ts/src/backends/index.ts +76 -0
- package/templates/deepagent/ts/src/backends/sandbox.ts +33 -0
- package/templates/deepagent/ts/src/config/agent.ts +37 -0
- package/templates/deepagent/ts/src/config/database.ts +21 -0
- package/templates/deepagent/ts/src/config/env.ts +106 -0
- package/templates/deepagent/ts/src/config/index.ts +84 -0
- package/templates/deepagent/ts/src/graph/checkpointer.ts +29 -0
- package/templates/deepagent/ts/src/graph/compile.ts +15 -0
- package/templates/deepagent/ts/src/graph/index.ts +3 -0
- package/templates/deepagent/ts/src/graph/store.ts +29 -0
- package/templates/deepagent/ts/src/index.ts +39 -0
- package/templates/deepagent/ts/src/memory/index.ts +11 -0
- package/templates/deepagent/ts/src/memory/manager.ts +76 -0
- package/templates/deepagent/ts/src/memory/store.ts +59 -0
- package/templates/deepagent/ts/src/middleware/approval.ts +49 -0
- package/templates/deepagent/ts/src/middleware/context.ts +37 -0
- package/templates/deepagent/ts/src/middleware/index.ts +9 -0
- package/templates/deepagent/ts/src/middleware/logging.ts +71 -0
- package/templates/deepagent/ts/src/middleware/security.ts +61 -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/schemas/agent.ts +48 -0
- package/templates/deepagent/ts/src/schemas/common.ts +26 -0
- package/templates/deepagent/ts/src/schemas/locale.ts +4 -0
- package/templates/deepagent/ts/src/schemas/session.ts +31 -0
- package/templates/deepagent/ts/src/services/agent.ts +170 -0
- package/templates/deepagent/ts/src/services/memory.ts +43 -0
- package/templates/deepagent/ts/src/services/session.ts +158 -0
- package/templates/deepagent/ts/src/skills/index.ts +26 -0
- package/templates/deepagent/ts/src/skills/loader.ts +90 -0
- package/templates/deepagent/ts/src/storage/database/client.ts +65 -0
- package/templates/deepagent/ts/src/storage/database/migrations/001_init.sql +20 -0
- package/templates/deepagent/ts/src/storage/logger/index.ts +25 -0
- package/templates/deepagent/ts/src/storage/redis/client.ts +57 -0
- package/templates/deepagent/ts/src/storage/shutdown/index.ts +82 -0
- package/templates/deepagent/ts/src/tools/database/index.ts +5 -0
- package/templates/deepagent/ts/src/tools/database/query.ts +79 -0
- package/templates/deepagent/ts/src/tools/filesystem/index.ts +110 -0
- package/templates/deepagent/ts/src/tools/index.ts +43 -0
- package/templates/deepagent/ts/src/tools/mcp/client.ts +54 -0
- package/templates/deepagent/ts/src/tools/mcp/connections.ts +68 -0
- package/templates/deepagent/ts/src/tools/mcp/index.ts +10 -0
- package/templates/deepagent/ts/src/tools/mcp/registry.ts +45 -0
- package/templates/deepagent/ts/src/utils/errors.ts +95 -0
- package/templates/deepagent/ts/src/utils/helpers.ts +57 -0
- package/templates/deepagent/ts/src/utils/validation.ts +17 -0
- package/templates/deepagent/ts/tests/agents/prompts.test.ts +30 -0
- package/templates/deepagent/ts/tests/agents/supervisor.test.ts +42 -0
- package/templates/deepagent/ts/tests/config/database.test.ts +40 -0
- package/templates/deepagent/ts/tests/integration/api.test.ts +122 -0
- package/templates/deepagent/ts/tests/middleware/security.test.ts +27 -0
- 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 +27 -0
- package/templates/deepagent/ts/tsconfig.json +19 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import "dotenv/config";
|
|
2
|
+
|
|
3
|
+
import { createApplication } from "./app.js";
|
|
4
|
+
import { loadConfig } from "./config/index.js";
|
|
5
|
+
import { createLogger } from "./storage/logger/index.js";
|
|
6
|
+
import { createShutdownManager } from "./storage/shutdown/index.js";
|
|
7
|
+
|
|
8
|
+
const config = loadConfig();
|
|
9
|
+
const logger = createLogger(config);
|
|
10
|
+
const shutdown = createShutdownManager({ logger });
|
|
11
|
+
|
|
12
|
+
const application = await createApplication(config);
|
|
13
|
+
|
|
14
|
+
const server = application.app.listen(config.server.port, config.server.host, () => {
|
|
15
|
+
logger.info(
|
|
16
|
+
{
|
|
17
|
+
host: config.server.host,
|
|
18
|
+
port: config.server.port,
|
|
19
|
+
model: `${config.model.provider}/${config.model.name}`,
|
|
20
|
+
},
|
|
21
|
+
"DeepAgent API 已启动",
|
|
22
|
+
);
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
server.on("error", (error) => {
|
|
26
|
+
logger.error({ error: error.message }, "HTTP 服务启动失败");
|
|
27
|
+
void shutdown.shutdown("server-error").finally(() => process.exit(1));
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
shutdown.register({
|
|
31
|
+
name: "http",
|
|
32
|
+
close: () =>
|
|
33
|
+
new Promise((resolve) => {
|
|
34
|
+
server.close(() => resolve());
|
|
35
|
+
}),
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
shutdown.register({ name: "application", close: application.close });
|
|
39
|
+
shutdown.install();
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { MemoryStore } from "./store.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 领域级长期记忆:按租户/用户隔离的偏好与事实,
|
|
5
|
+
* 存储在挂载于 `/memories/` 的同一个 BaseStore 中。
|
|
6
|
+
*/
|
|
7
|
+
export class MemoryManager {
|
|
8
|
+
memory;
|
|
9
|
+
root;
|
|
10
|
+
|
|
11
|
+
constructor({ store, rootNamespace = ["memories"] }) {
|
|
12
|
+
this.memory = new MemoryStore(store);
|
|
13
|
+
this.root = rootNamespace;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
namespaceFor({ tenantId, userId }) {
|
|
17
|
+
assertSegment(tenantId, "tenantId");
|
|
18
|
+
|
|
19
|
+
const segment = userId ? `user:${assertSegment(userId, "userId")}` : "shared";
|
|
20
|
+
return [...this.root, tenantId, segment];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async rememberPreference(target, key, value) {
|
|
24
|
+
await this.memory.put(this.namespaceFor(target), `preference:${key}`, value);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async rememberFact(target, key, value) {
|
|
28
|
+
await this.memory.put(this.namespaceFor(target), `fact:${key}`, value);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async recall(target, key) {
|
|
32
|
+
return this.memory.get(this.namespaceFor(target), key);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async list(target, limit = 50) {
|
|
36
|
+
return this.memory.search(this.namespaceFor(target), limit);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async forget(target, key) {
|
|
40
|
+
await this.memory.delete(this.namespaceFor(target), key);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
const assertSegment = (value, label) => {
|
|
45
|
+
if (!/^[a-zA-Z0-9._:-]{1,128}$/.test(value)) {
|
|
46
|
+
throw new Error(`${label} 必须为 1-128 个字符,仅允许字母、数字、点、下划线、冒号或短横线。`);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return value;
|
|
50
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 对 LangGraph `BaseStore`(InMemoryStore 或 PostgresStore)的轻量类型封装,
|
|
3
|
+
* 让应用其他部分不必直接处理 store 的底层细节。
|
|
4
|
+
*/
|
|
5
|
+
export class MemoryStore {
|
|
6
|
+
store;
|
|
7
|
+
constructor(store) {
|
|
8
|
+
this.store = store;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
async put(namespace, key, value) {
|
|
12
|
+
await this.store.put(namespace, key, {
|
|
13
|
+
...value,
|
|
14
|
+
updatedAt: new Date().toISOString(),
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
async get(namespace, key) {
|
|
19
|
+
const item = await this.store.get(namespace, key);
|
|
20
|
+
if (!item) return null;
|
|
21
|
+
|
|
22
|
+
return toRecord(item);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async search(namespacePrefix, limit = 20) {
|
|
26
|
+
const items = await this.store.search(namespacePrefix, { limit });
|
|
27
|
+
|
|
28
|
+
return items.map((item) => toRecord(item));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async delete(namespace, key) {
|
|
32
|
+
await this.store.delete(namespace, key);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const toRecord = (item) => {
|
|
37
|
+
return {
|
|
38
|
+
key: item.key,
|
|
39
|
+
namespace: item.namespace,
|
|
40
|
+
value: item.value,
|
|
41
|
+
...(item.updatedAt ? { updatedAt: new Date(item.updatedAt).toISOString() } : {}),
|
|
42
|
+
};
|
|
43
|
+
};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 会修改状态或操作基础设施的工具。它们会通过 `interruptOn` 暂停,
|
|
3
|
+
* 等待人工批准后再执行。
|
|
4
|
+
*/
|
|
5
|
+
export const SENSITIVE_TOOLS = [
|
|
6
|
+
"write_file",
|
|
7
|
+
"edit_file",
|
|
8
|
+
"delete",
|
|
9
|
+
"execute",
|
|
10
|
+
"write_workspace_file",
|
|
11
|
+
"query_database",
|
|
12
|
+
];
|
|
13
|
+
|
|
14
|
+
/** 模板已知的全部工具名称。 */
|
|
15
|
+
export const KNOWN_TOOLS = [
|
|
16
|
+
...SENSITIVE_TOOLS,
|
|
17
|
+
"read_file",
|
|
18
|
+
"read_workspace_file",
|
|
19
|
+
"list_workspace_files",
|
|
20
|
+
"ls",
|
|
21
|
+
"glob",
|
|
22
|
+
"grep",
|
|
23
|
+
"write_todos",
|
|
24
|
+
"task",
|
|
25
|
+
];
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 构建 `createDeepAgent` 使用的 `interruptOn` 映射。
|
|
29
|
+
*
|
|
30
|
+
* - none:不启用审批
|
|
31
|
+
* - sensitive:修改类工具执行前暂停(默认)
|
|
32
|
+
* - all:所有已知工具执行前都暂停
|
|
33
|
+
*/
|
|
34
|
+
export const createApprovalPolicy = (mode) => {
|
|
35
|
+
if (mode === "none") return {};
|
|
36
|
+
|
|
37
|
+
const tools = mode === "all" ? [...KNOWN_TOOLS] : [...SENSITIVE_TOOLS];
|
|
38
|
+
|
|
39
|
+
return Object.fromEntries(tools.map((tool) => [tool, true]));
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export const requiresApproval = (mode, toolName) => {
|
|
43
|
+
if (mode === "none") return false;
|
|
44
|
+
if (mode === "all") return KNOWN_TOOLS.includes(toolName);
|
|
45
|
+
|
|
46
|
+
return SENSITIVE_TOOLS.includes(toolName);
|
|
47
|
+
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { createMiddleware } from "langchain";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
export const runtimeContextSchema = z.object({
|
|
5
|
+
tenantId: z.string().default("default"),
|
|
6
|
+
userId: z.string().optional(),
|
|
7
|
+
threadId: z.string().optional(),
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* 把每次请求的上下文注入系统提示词。上下文由 API 通过
|
|
12
|
+
* `config.context` 提供,不会随会话持久化。
|
|
13
|
+
*/
|
|
14
|
+
export const createContextMiddleware = () => {
|
|
15
|
+
return createMiddleware({
|
|
16
|
+
name: "ContextMiddleware",
|
|
17
|
+
contextSchema: runtimeContextSchema,
|
|
18
|
+
|
|
19
|
+
wrapModelCall: async (request, handler) => {
|
|
20
|
+
const context = runtimeContextSchema.parse(request.runtime.context ?? {});
|
|
21
|
+
const lines = [
|
|
22
|
+
"## 运行时上下文",
|
|
23
|
+
`- 租户:${context.tenantId}`,
|
|
24
|
+
...(context.userId ? [`- 用户:${context.userId}`] : []),
|
|
25
|
+
...(context.threadId ? [`- 会话:${context.threadId}`] : []),
|
|
26
|
+
];
|
|
27
|
+
|
|
28
|
+
const systemPrompt = [request.systemPrompt, lines.join("\n")]
|
|
29
|
+
.filter((part) => Boolean(part && part.trim()))
|
|
30
|
+
.join("\n\n");
|
|
31
|
+
|
|
32
|
+
return handler({ ...request, systemPrompt, systemMessage: undefined });
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export {
|
|
2
|
+
createApprovalPolicy,
|
|
3
|
+
KNOWN_TOOLS,
|
|
4
|
+
requiresApproval,
|
|
5
|
+
SENSITIVE_TOOLS,
|
|
6
|
+
} from "./approval.js";
|
|
7
|
+
export { createContextMiddleware, runtimeContextSchema } from "./context.js";
|
|
8
|
+
export { createLoggingMiddleware } from "./logging.js";
|
|
9
|
+
export { createSecurityMiddleware, DANGEROUS_PATTERNS, findSecurityViolation } from "./security.js";
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { createMiddleware } from "langchain";
|
|
2
|
+
|
|
3
|
+
import { errorMessage, truncate } from "../utils/helpers.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 为每次模型和工具调用输出结构化日志。
|
|
7
|
+
* 对 payload 做截断,避免大段工具输出淹没日志。
|
|
8
|
+
*/
|
|
9
|
+
export const createLoggingMiddleware = (logger) => {
|
|
10
|
+
return createMiddleware({
|
|
11
|
+
name: "LoggingMiddleware",
|
|
12
|
+
|
|
13
|
+
wrapModelCall: async (request, handler) => {
|
|
14
|
+
const startedAt = Date.now();
|
|
15
|
+
|
|
16
|
+
return Promise.resolve(handler(request)).then(
|
|
17
|
+
(response) => {
|
|
18
|
+
logger.debug(
|
|
19
|
+
{
|
|
20
|
+
model: request.model?.getName?.() ?? "未知",
|
|
21
|
+
durationMs: Date.now() - startedAt,
|
|
22
|
+
toolCalls: response.tool_calls?.length ?? 0,
|
|
23
|
+
},
|
|
24
|
+
"模型调用完成",
|
|
25
|
+
);
|
|
26
|
+
return response;
|
|
27
|
+
},
|
|
28
|
+
(error) => {
|
|
29
|
+
logger.error(
|
|
30
|
+
{ durationMs: Date.now() - startedAt, error: errorMessage(error) },
|
|
31
|
+
"模型调用失败",
|
|
32
|
+
);
|
|
33
|
+
throw error;
|
|
34
|
+
},
|
|
35
|
+
);
|
|
36
|
+
},
|
|
37
|
+
|
|
38
|
+
wrapToolCall: async (request, handler) => {
|
|
39
|
+
const startedAt = Date.now();
|
|
40
|
+
logger.debug(
|
|
41
|
+
{
|
|
42
|
+
tool: request.toolCall.name,
|
|
43
|
+
args: truncate(JSON.stringify(request.toolCall.args ?? {}), 500),
|
|
44
|
+
},
|
|
45
|
+
"工具调用开始",
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
return Promise.resolve(handler(request)).then(
|
|
49
|
+
(result) => {
|
|
50
|
+
logger.debug(
|
|
51
|
+
{ tool: request.toolCall.name, durationMs: Date.now() - startedAt },
|
|
52
|
+
"工具调用完成",
|
|
53
|
+
);
|
|
54
|
+
return result;
|
|
55
|
+
},
|
|
56
|
+
(error) => {
|
|
57
|
+
logger.error(
|
|
58
|
+
{
|
|
59
|
+
tool: request.toolCall.name,
|
|
60
|
+
durationMs: Date.now() - startedAt,
|
|
61
|
+
error: errorMessage(error),
|
|
62
|
+
},
|
|
63
|
+
"工具调用失败",
|
|
64
|
+
);
|
|
65
|
+
throw error;
|
|
66
|
+
},
|
|
67
|
+
);
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { ToolMessage } from "@langchain/core/messages";
|
|
2
|
+
import { createMiddleware } from "langchain";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* 针对破坏性 shell/SQL 载荷的启发式规则。这是纵深防御,不是沙箱:
|
|
6
|
+
* 请以最小权限运行 Agent。
|
|
7
|
+
*/
|
|
8
|
+
export const DANGEROUS_PATTERNS = [
|
|
9
|
+
{
|
|
10
|
+
pattern: /\brm\s+-(?:[a-z]*r[a-z]*f|[a-z]*f[a-z]*r)\s+\/(?:\s|$)/i,
|
|
11
|
+
reason: "递归删除根目录",
|
|
12
|
+
},
|
|
13
|
+
{ pattern: /\bmkfs(?:\.\w+)?\b/i, reason: "格式化文件系统" },
|
|
14
|
+
{ pattern: /:\(\)\s*\{\s*:\|:\s*&\s*\};:/, reason: "fork 炸弹" },
|
|
15
|
+
{ pattern: /\bdd\s+if=.*\bof=\/dev\/[sh]d/i, reason: "直接写磁盘" },
|
|
16
|
+
{
|
|
17
|
+
pattern: /\b(?:curl|wget)\b[^\n|]*\|\s*(?:sudo\s+)?(?:ba|z|k)?sh\b/i,
|
|
18
|
+
reason: "把下载内容管道给 shell 执行",
|
|
19
|
+
},
|
|
20
|
+
{ pattern: /\bchmod\s+-R\s+777\s+\//i, reason: "根目录权限设为 777" },
|
|
21
|
+
{ pattern: /\bshutdown\b|\breboot\b/i, reason: "关闭主机" },
|
|
22
|
+
{ pattern: /\bDROP\s+(?:TABLE|DATABASE|SCHEMA)\b/i, reason: "破坏性 SQL" },
|
|
23
|
+
{ pattern: /\bTRUNCATE\s+TABLE\b/i, reason: "破坏性 SQL" },
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
export const findSecurityViolation = (value) => {
|
|
27
|
+
for (const { pattern, reason } of DANGEROUS_PATTERNS) {
|
|
28
|
+
if (pattern.test(value)) return reason;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return null;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 在工具执行前拒绝危险参数。模型会收到一条解释拦截原因的工具消息,
|
|
36
|
+
* 从而改用更安全的方式。
|
|
37
|
+
*/
|
|
38
|
+
export const createSecurityMiddleware = () => {
|
|
39
|
+
return createMiddleware({
|
|
40
|
+
name: "SecurityMiddleware",
|
|
41
|
+
|
|
42
|
+
wrapToolCall: async (request, handler) => {
|
|
43
|
+
const serializedArgs = JSON.stringify(request.toolCall.args ?? {});
|
|
44
|
+
const violation = findSecurityViolation(serializedArgs);
|
|
45
|
+
|
|
46
|
+
if (violation) {
|
|
47
|
+
return new ToolMessage({
|
|
48
|
+
content: `已被安全策略拦截:${violation}。请选择更安全的方式。`,
|
|
49
|
+
tool_call_id: request.toolCall.id ?? "未知",
|
|
50
|
+
name: request.toolCall.name,
|
|
51
|
+
status: "error",
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
return handler(request);
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { ConfigurationError } from "../utils/errors.js";
|
|
2
|
+
import { OPENAI_COMPATIBLE_PRESETS } from "./presets.js";
|
|
3
|
+
|
|
4
|
+
/** 未配置时的生成上限;MiniMax M3 最高支持 128K(含思考 token)。 */
|
|
5
|
+
export const DEFAULT_MAX_COMPLETION_TOKENS = 32_768;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* 把环境变量解析成模型配置。
|
|
9
|
+
* `MODEL_BASE_URL` 优先于预设地址,用于自建网关、代理或私有化部署。
|
|
10
|
+
*/
|
|
11
|
+
export const resolveModelConfig = (env) => {
|
|
12
|
+
const preset = OPENAI_COMPATIBLE_PRESETS[env.MODEL_PROVIDER];
|
|
13
|
+
const baseUrl = env.MODEL_BASE_URL ?? preset.baseUrl;
|
|
14
|
+
const name = env.MODEL_NAME ?? preset.defaultModel;
|
|
15
|
+
|
|
16
|
+
if (!baseUrl) {
|
|
17
|
+
throw new ConfigurationError(
|
|
18
|
+
`MODEL_PROVIDER=${env.MODEL_PROVIDER} 时必须设置 MODEL_BASE_URL(兼容 OpenAI 的接口地址)。`,
|
|
19
|
+
);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (!name) {
|
|
23
|
+
throw new ConfigurationError(
|
|
24
|
+
`MODEL_PROVIDER=${env.MODEL_PROVIDER} 时必须设置 MODEL_NAME(例如 qwen-plus、glm-4.6)。`,
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
return {
|
|
29
|
+
provider: env.MODEL_PROVIDER,
|
|
30
|
+
label: preset.label,
|
|
31
|
+
name,
|
|
32
|
+
baseUrl,
|
|
33
|
+
apiKey: env.MODEL_API_KEY ?? "",
|
|
34
|
+
temperature: env.MODEL_TEMPERATURE,
|
|
35
|
+
maxCompletionTokens:
|
|
36
|
+
env.MODEL_MAX_COMPLETION_TOKENS ?? env.MODEL_MAX_TOKENS ?? DEFAULT_MAX_COMPLETION_TOKENS,
|
|
37
|
+
};
|
|
38
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 模型层统一出口。
|
|
3
|
+
*
|
|
4
|
+
* 模板只保留一条接入路径:OpenAI 兼容协议。切换服务商改环境变量即可,
|
|
5
|
+
* 需要自定义时调整 `openai-compatible` 模块中 `ChatOpenAI` 的构造参数。
|
|
6
|
+
*/
|
|
7
|
+
export { resolveModelConfig } from "./config.js";
|
|
8
|
+
export { createChatModel } from "./openai-compatible.js";
|
|
9
|
+
export { MODEL_PROVIDERS, OPENAI_COMPATIBLE_PRESETS } from "./presets.js";
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { ChatOpenAI } from "@langchain/openai";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 用 OpenAI 兼容协议创建聊天模型。
|
|
5
|
+
*
|
|
6
|
+
* 所有请求都走 `POST {baseUrl}/chat/completions`,因此 OpenAI、DeepSeek、
|
|
7
|
+
* 通义千问、Kimi、智谱、OpenRouter、vLLM、Ollama 等共用同一份实现;
|
|
8
|
+
* 接入新服务通常只需要设置 `MODEL_BASE_URL` 与 `MODEL_NAME`。
|
|
9
|
+
*/
|
|
10
|
+
export const createChatModel = (config) => {
|
|
11
|
+
return new ChatOpenAI({
|
|
12
|
+
model: config.name,
|
|
13
|
+
temperature: config.temperature,
|
|
14
|
+
maxCompletionTokens: config.maxCompletionTokens,
|
|
15
|
+
configuration: { baseURL: config.baseUrl },
|
|
16
|
+
...(config.apiKey ? { apiKey: config.apiKey } : {}),
|
|
17
|
+
});
|
|
18
|
+
};
|
|
@@ -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
|
+
}
|