fix(agent): isolate conversation workspaces
This commit is contained in:
@@ -12,6 +12,7 @@ export type SessionBinding = {
|
||||
clientSessionId: string;
|
||||
sessionId: string;
|
||||
startedAt: number;
|
||||
workspaceDirectory?: string;
|
||||
};
|
||||
|
||||
export type SessionContext = {
|
||||
@@ -52,20 +53,26 @@ export class ChatSessionBridge {
|
||||
await this.abortActiveRuntime(requestContext.clientSessionId, existingSessionId);
|
||||
|
||||
let sessionId = existingSessionId;
|
||||
let runtimeSession;
|
||||
let created = false;
|
||||
if (!sessionId) {
|
||||
const session = await this.runtime.createSession();
|
||||
sessionId = session.id;
|
||||
runtimeSession = await this.runtime.createSession(undefined, {
|
||||
conversationWorkspace: true,
|
||||
});
|
||||
sessionId = runtimeSession.id;
|
||||
requestContext = {
|
||||
...requestContext,
|
||||
clientSessionId: sessionId,
|
||||
};
|
||||
created = true;
|
||||
} else {
|
||||
runtimeSession = await this.runtime.getSession(sessionId);
|
||||
}
|
||||
const binding: SessionBinding = {
|
||||
clientSessionId: requestContext.clientSessionId,
|
||||
sessionId,
|
||||
startedAt: Date.now(),
|
||||
workspaceDirectory: runtimeSession.directory,
|
||||
};
|
||||
setRuntimeSessionContext({
|
||||
accessToken: requestContext.accessToken,
|
||||
@@ -79,6 +86,7 @@ export class ChatSessionBridge {
|
||||
sessionId,
|
||||
tokenExpiresAt: requestContext.tokenExpiresAt,
|
||||
traceId: requestContext.traceId,
|
||||
workspaceDirectory: runtimeSession.directory,
|
||||
});
|
||||
|
||||
return { binding, requestContext, created };
|
||||
|
||||
+5
-1
@@ -7,6 +7,8 @@ import {
|
||||
parseAgentModelOptions,
|
||||
} from "./chat/modelConfig.js";
|
||||
|
||||
export const RESULT_REF_IMPORT_DIRECTORY = "./data/conversation-workspaces";
|
||||
|
||||
// 本地开发可在项目根目录放 .local.env;已存在的系统环境变量优先级更高。
|
||||
dotenv.config({ path: ".local.env", override: false });
|
||||
|
||||
@@ -116,7 +118,9 @@ const envSchema = z
|
||||
// result_ref 持久化存储目录。
|
||||
RESULT_REF_STORAGE_DIR: z.string().default("./data/result-refs"),
|
||||
// 仅允许 store_render_ref 从该目录导入受控 JSON 包装文件。
|
||||
RESULT_REF_IMPORT_DIR: z.string().default("./data/result-imports"),
|
||||
RESULT_REF_IMPORT_DIR: z
|
||||
.literal(RESULT_REF_IMPORT_DIRECTORY)
|
||||
.default(RESULT_REF_IMPORT_DIRECTORY),
|
||||
// 单个渲染包装 JSON 的最大导入字节数。
|
||||
RESULT_REF_IMPORT_MAX_BYTES: z.coerce
|
||||
.number()
|
||||
|
||||
+46
-6
@@ -1,4 +1,4 @@
|
||||
import { realpath, stat } from "node:fs/promises";
|
||||
import { lstat, realpath, stat } from "node:fs/promises";
|
||||
import { isAbsolute, relative } from "node:path";
|
||||
|
||||
import { readJsonFile, removeFileIfExists } from "../utils/fileStore.js";
|
||||
@@ -68,9 +68,19 @@ export class ResultReferenceResolver {
|
||||
|
||||
async registerRenderPayloadFile(
|
||||
filePath: string,
|
||||
input: Omit<RegisterResultReferenceInput, "data" | "kind" | "schemaVersion">,
|
||||
input: Omit<RegisterResultReferenceInput, "data" | "kind" | "schemaVersion"> & {
|
||||
workspaceDirectory: string;
|
||||
},
|
||||
) {
|
||||
const resolvedFilePath = await resolvePathInsideRoot(filePath, this.importRoot);
|
||||
const resolvedWorkspaceDirectory = await resolveConversationWorkspace(
|
||||
input.workspaceDirectory,
|
||||
this.importRoot,
|
||||
);
|
||||
const resolvedFilePath = await resolvePathInsideRoot(
|
||||
filePath,
|
||||
resolvedWorkspaceDirectory,
|
||||
"render payload file must be inside the current conversation workspace",
|
||||
);
|
||||
const fileStat = await stat(resolvedFilePath);
|
||||
if (!fileStat.isFile()) {
|
||||
throw new Error("render payload path must point to a regular file");
|
||||
@@ -95,8 +105,9 @@ export class ResultReferenceResolver {
|
||||
throw new Error("render payload file does not contain a valid junction render payload");
|
||||
}
|
||||
|
||||
const { workspaceDirectory: _workspaceDirectory, ...registrationInput } = input;
|
||||
const record = await this.register({
|
||||
...input,
|
||||
...registrationInput,
|
||||
data: payload,
|
||||
kind: RESULT_REFERENCE_KIND.renderJunctionsPayload,
|
||||
schemaVersion: 1,
|
||||
@@ -186,7 +197,36 @@ export const extractRenderJunctionPayload = (
|
||||
};
|
||||
};
|
||||
|
||||
const resolvePathInsideRoot = async (filePath: string, rootPath: string) => {
|
||||
const resolveConversationWorkspace = async (
|
||||
workspaceDirectory: string,
|
||||
importRoot: string,
|
||||
) => {
|
||||
const workspaceLinkStat = await lstat(workspaceDirectory);
|
||||
if (workspaceLinkStat.isSymbolicLink()) {
|
||||
throw new Error("conversation workspace must not be a symbolic link");
|
||||
}
|
||||
const resolvedImportRoot = await realpath(importRoot);
|
||||
const resolvedWorkspaceDirectory = await resolvePathInsideRoot(
|
||||
workspaceDirectory,
|
||||
resolvedImportRoot,
|
||||
"conversation workspace must be inside RESULT_REF_IMPORT_DIR",
|
||||
);
|
||||
const relativeWorkspace = relative(resolvedImportRoot, resolvedWorkspaceDirectory);
|
||||
if (!relativeWorkspace || relativeWorkspace.includes("/") || relativeWorkspace.includes("\\")) {
|
||||
throw new Error("conversation workspace must be a direct child of RESULT_REF_IMPORT_DIR");
|
||||
}
|
||||
const workspaceStat = await stat(resolvedWorkspaceDirectory);
|
||||
if (!workspaceStat.isDirectory()) {
|
||||
throw new Error("conversation workspace must point to a directory");
|
||||
}
|
||||
return resolvedWorkspaceDirectory;
|
||||
};
|
||||
|
||||
const resolvePathInsideRoot = async (
|
||||
filePath: string,
|
||||
rootPath: string,
|
||||
outsideMessage = "render payload file must be inside RESULT_REF_IMPORT_DIR",
|
||||
) => {
|
||||
if (!isAbsolute(filePath)) {
|
||||
throw new Error("render payload file_path must be absolute");
|
||||
}
|
||||
@@ -200,7 +240,7 @@ const resolvePathInsideRoot = async (filePath: string, rootPath: string) => {
|
||||
relativePath.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ||
|
||||
isAbsolute(relativePath)
|
||||
) {
|
||||
throw new Error("render payload file must be inside RESULT_REF_IMPORT_DIR");
|
||||
throw new Error(outsideMessage);
|
||||
}
|
||||
return resolvedFilePath;
|
||||
};
|
||||
|
||||
+7
-2
@@ -155,7 +155,9 @@ export const buildChatRouter = (
|
||||
const actorKey = toActorKey(userId);
|
||||
const projectKey = toProjectKey(projectId);
|
||||
const requestedSessionId = parsed.data.session_id?.trim();
|
||||
const sessionId = requestedSessionId || (await runtime.createSession()).id;
|
||||
const sessionId =
|
||||
requestedSessionId ||
|
||||
(await runtime.createSession(undefined, { conversationWorkspace: true })).id;
|
||||
|
||||
const { record, created } = await sessionMetadataStore.ensure({
|
||||
actorKey,
|
||||
@@ -451,7 +453,9 @@ export const buildChatRouter = (
|
||||
res.status(404).json({ message: "source session not found" });
|
||||
return;
|
||||
}
|
||||
const forkSession = await runtime.createSession();
|
||||
const forkSession = await runtime.createSession(undefined, {
|
||||
conversationWorkspace: true,
|
||||
});
|
||||
const { record: targetSessionRecord } = await sessionMetadataStore.ensure({
|
||||
actorKey,
|
||||
parentSessionId: sourceSessionId,
|
||||
@@ -874,6 +878,7 @@ export const buildChatRouter = (
|
||||
traceId: requestContext.traceId,
|
||||
projectId: requestContext.projectId,
|
||||
signal: abortController.signal,
|
||||
workspaceRoot: binding.workspaceDirectory,
|
||||
write: (event, data) => {
|
||||
publish(event, data);
|
||||
},
|
||||
|
||||
@@ -62,9 +62,32 @@ export const resolvePermissionApproval = (
|
||||
permission: string,
|
||||
context: PermissionApprovalContext = {},
|
||||
) => {
|
||||
if (isDirectRecursiveForceRemove(permission, context)) {
|
||||
return {
|
||||
autoApprove: false,
|
||||
autoReject: true,
|
||||
title: "已拒绝递归强制删除",
|
||||
detail: "当前安全策略禁止直接执行带 recursive 和 force 参数的 rm 命令。",
|
||||
} as const;
|
||||
}
|
||||
|
||||
if (
|
||||
approvalMode === "always" &&
|
||||
normalizePermission(permission) === "bash" &&
|
||||
containsPotentialRemoveCommand(context)
|
||||
) {
|
||||
return {
|
||||
autoApprove: false,
|
||||
autoReject: false,
|
||||
title: "等待删除命令确认",
|
||||
detail: "删除命令不会由始终允许模式代为批准,请确认本次具体操作。",
|
||||
} as const;
|
||||
}
|
||||
|
||||
if (approvalMode === "always") {
|
||||
return {
|
||||
autoApprove: true,
|
||||
autoReject: false,
|
||||
title: "已按始终允许模式放行",
|
||||
detail:
|
||||
"当前会话处于始终允许模式,已放行本次权限请求;明确禁止的权限仍由 OpenCode 拒绝。",
|
||||
@@ -74,6 +97,7 @@ export const resolvePermissionApproval = (
|
||||
if (approvalMode === "auto" && canAutoApprovePermission(permission, context)) {
|
||||
return {
|
||||
autoApprove: true,
|
||||
autoReject: false,
|
||||
title: "已自动批准低风险权限",
|
||||
detail: "当前批准模式允许自动执行低风险工具,已放行本次请求。",
|
||||
} as const;
|
||||
@@ -81,11 +105,135 @@ export const resolvePermissionApproval = (
|
||||
|
||||
return {
|
||||
autoApprove: false,
|
||||
autoReject: false,
|
||||
title: "等待权限确认",
|
||||
detail: undefined,
|
||||
} as const;
|
||||
};
|
||||
|
||||
const isDirectRecursiveForceRemove = (
|
||||
permission: string,
|
||||
context: PermissionApprovalContext,
|
||||
): boolean => {
|
||||
if (normalizePermission(permission) !== "bash") {
|
||||
return false;
|
||||
}
|
||||
const command =
|
||||
typeof context.metadata?.command === "string"
|
||||
? context.metadata.command
|
||||
: context.patterns?.join("\n");
|
||||
if (!command) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return splitShellCommandSegments(command).some((segment) => {
|
||||
const words = tokenizeShellSegment(segment);
|
||||
let commandIndex = 0;
|
||||
while (commandIndex < words.length) {
|
||||
const word = words[commandIndex]!;
|
||||
const executable = word.split("/").at(-1)?.toLowerCase();
|
||||
if (word === "!" || /^[A-Za-z_][A-Za-z0-9_]*=/.test(word)) {
|
||||
commandIndex += 1;
|
||||
continue;
|
||||
}
|
||||
if (executable === "command") {
|
||||
commandIndex += 1;
|
||||
while (words[commandIndex]?.startsWith("-") && words[commandIndex] !== "--") {
|
||||
commandIndex += 1;
|
||||
}
|
||||
if (words[commandIndex] === "--") commandIndex += 1;
|
||||
continue;
|
||||
}
|
||||
if (executable === "env") {
|
||||
commandIndex += 1;
|
||||
while (commandIndex < words.length) {
|
||||
const envWord = words[commandIndex]!;
|
||||
if (envWord === "--") {
|
||||
commandIndex += 1;
|
||||
break;
|
||||
}
|
||||
if (envWord === "-u" || envWord === "--unset") {
|
||||
commandIndex += 2;
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
envWord.startsWith("-") ||
|
||||
/^[A-Za-z_][A-Za-z0-9_]*=/.test(envWord)
|
||||
) {
|
||||
commandIndex += 1;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (executable === "sudo" || executable === "doas") {
|
||||
commandIndex += 1;
|
||||
while (words[commandIndex]?.startsWith("-")) {
|
||||
commandIndex += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (executable === "busybox" && words[commandIndex + 1] === "rm") {
|
||||
commandIndex += 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
const executable = words[commandIndex]?.split("/").at(-1)?.toLowerCase();
|
||||
if (executable !== "rm") {
|
||||
return false;
|
||||
}
|
||||
|
||||
let recursive = false;
|
||||
let force = false;
|
||||
for (const word of words.slice(commandIndex + 1)) {
|
||||
if (word === "--") {
|
||||
break;
|
||||
}
|
||||
if (word === "--recursive") {
|
||||
recursive = true;
|
||||
} else if (word === "--force") {
|
||||
force = true;
|
||||
} else if (/^-[^-]/.test(word)) {
|
||||
recursive ||= /[rR]/.test(word.slice(1));
|
||||
force ||= word.slice(1).includes("f");
|
||||
}
|
||||
}
|
||||
return recursive && force;
|
||||
});
|
||||
};
|
||||
|
||||
const containsPotentialRemoveCommand = (
|
||||
context: PermissionApprovalContext,
|
||||
): boolean => {
|
||||
const command =
|
||||
typeof context.metadata?.command === "string"
|
||||
? context.metadata.command
|
||||
: context.patterns?.join("\n");
|
||||
if (!command) {
|
||||
return false;
|
||||
}
|
||||
const normalized = command
|
||||
.replace(/\$\{[^}]*\}|\$[A-Za-z_][A-Za-z0-9_]*/gu, "")
|
||||
.replace(/["'\\]/gu, "");
|
||||
return /(^|[^A-Za-z0-9_])(?:[^\s/]+\/)*rm(?=$|[^A-Za-z0-9_])/iu.test(normalized);
|
||||
};
|
||||
|
||||
const splitShellCommandSegments = (command: string): string[] =>
|
||||
command.split(/&&|\|\||[;|()\n]/u);
|
||||
|
||||
const tokenizeShellSegment = (segment: string): string[] =>
|
||||
(segment.match(/(?:[^\s"'\\]+|"(?:\\.|[^"])*"|'[^']*')+/gu) ?? []).map(
|
||||
(word) => {
|
||||
const quoted = word.match(/^(?:"([\s\S]*)"|'([\s\S]*)')$/u);
|
||||
return (quoted ? (quoted[1] ?? quoted[2] ?? "") : word).replace(
|
||||
/(["'])|\\(.)/gu,
|
||||
"$2",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const isSafeWorkspaceSearch = (
|
||||
permission: "glob" | "grep",
|
||||
context: PermissionApprovalContext,
|
||||
|
||||
+22
-10
@@ -71,6 +71,7 @@ type StreamPromptOptions = {
|
||||
traceId?: string;
|
||||
projectId?: string;
|
||||
signal?: AbortSignal;
|
||||
workspaceRoot?: string;
|
||||
write: (event: string, data: Record<string, unknown>) => void;
|
||||
};
|
||||
|
||||
@@ -157,6 +158,7 @@ export const streamPromptResponse = async ({
|
||||
traceId,
|
||||
projectId,
|
||||
signal,
|
||||
workspaceRoot,
|
||||
write,
|
||||
}: StreamPromptOptions): Promise<{
|
||||
aborted: boolean;
|
||||
@@ -397,7 +399,7 @@ export const streamPromptResponse = async ({
|
||||
{
|
||||
metadata: event.properties.metadata,
|
||||
patterns: event.properties.patterns,
|
||||
workspaceRoot: process.cwd(),
|
||||
workspaceRoot: workspaceRoot ?? process.cwd(),
|
||||
},
|
||||
);
|
||||
logDevelopmentDebug("permission request received", {
|
||||
@@ -410,20 +412,25 @@ export const streamPromptResponse = async ({
|
||||
emitProgress({
|
||||
id: `permission-${event.properties.id}`,
|
||||
phase: "permission",
|
||||
status: permissionApproval.autoApprove ? "completed" : "running",
|
||||
status: permissionApproval.autoReject
|
||||
? "error"
|
||||
: permissionApproval.autoApprove
|
||||
? "completed"
|
||||
: "running",
|
||||
title: permissionApproval.title,
|
||||
detail: permissionApproval.detail ?? buildPermissionDetail(event),
|
||||
});
|
||||
if (permissionApproval.autoApprove) {
|
||||
if (permissionApproval.autoApprove || permissionApproval.autoReject) {
|
||||
const reply = permissionApproval.autoReject ? "reject" : "once";
|
||||
await runtime.replyPermission({
|
||||
requestId: event.properties.id,
|
||||
sessionId,
|
||||
reply: "once",
|
||||
reply,
|
||||
});
|
||||
write("permission_response", {
|
||||
session_id: clientSessionId,
|
||||
request_id: event.properties.id,
|
||||
reply: "once" satisfies PermissionReply,
|
||||
reply: reply satisfies PermissionReply,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
@@ -448,7 +455,7 @@ export const streamPromptResponse = async ({
|
||||
{
|
||||
metadata: event.properties.metadata,
|
||||
patterns: event.properties.resources,
|
||||
workspaceRoot: process.cwd(),
|
||||
workspaceRoot: workspaceRoot ?? process.cwd(),
|
||||
},
|
||||
);
|
||||
logDevelopmentDebug("permission v2 request received", {
|
||||
@@ -461,20 +468,25 @@ export const streamPromptResponse = async ({
|
||||
emitProgress({
|
||||
id: `permission-${event.properties.id}`,
|
||||
phase: "permission",
|
||||
status: permissionApproval.autoApprove ? "completed" : "running",
|
||||
status: permissionApproval.autoReject
|
||||
? "error"
|
||||
: permissionApproval.autoApprove
|
||||
? "completed"
|
||||
: "running",
|
||||
title: permissionApproval.title,
|
||||
detail: permissionApproval.detail ?? buildPermissionV2Detail(event),
|
||||
});
|
||||
if (permissionApproval.autoApprove) {
|
||||
if (permissionApproval.autoApprove || permissionApproval.autoReject) {
|
||||
const reply = permissionApproval.autoReject ? "reject" : "once";
|
||||
await runtime.replyPermission({
|
||||
requestId: event.properties.id,
|
||||
sessionId,
|
||||
reply: "once",
|
||||
reply,
|
||||
});
|
||||
write("permission_response", {
|
||||
session_id: clientSessionId,
|
||||
request_id: event.properties.id,
|
||||
reply: "once" satisfies PermissionReply,
|
||||
reply: reply satisfies PermissionReply,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
+42
-5
@@ -2,11 +2,14 @@ import {
|
||||
createOpencode,
|
||||
type OpencodeClient,
|
||||
} from "@opencode-ai/sdk/v2";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { chmod, mkdir, rmdir } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { config } from "../config.js";
|
||||
import { logger } from "../logger.js";
|
||||
import { ensureDirectory } from "../utils/fileStore.js";
|
||||
import {
|
||||
cleanupExpiredToolOutputs,
|
||||
resolveOpencodeToolOutputDirectory,
|
||||
@@ -126,12 +129,46 @@ export class OpencodeRuntimeAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
async createSession(title?: string) {
|
||||
async createSession(
|
||||
title?: string,
|
||||
options: {
|
||||
conversationWorkspace?: boolean;
|
||||
workspaceRoot?: string;
|
||||
} = {},
|
||||
) {
|
||||
const client = await this.ensureClient();
|
||||
const response = await client.session.create({
|
||||
title,
|
||||
});
|
||||
return requireData(response.data, "session.create");
|
||||
if (!options.conversationWorkspace) {
|
||||
const response = await client.session.create({ title });
|
||||
return requireData(response.data, "session.create");
|
||||
}
|
||||
|
||||
const workspaceRoot = resolve(
|
||||
options.workspaceRoot ?? config.RESULT_REF_IMPORT_DIR,
|
||||
);
|
||||
const directory = resolve(workspaceRoot, `conversation-${randomUUID()}`);
|
||||
await ensureDirectory(workspaceRoot);
|
||||
await chmod(workspaceRoot, 0o700);
|
||||
await mkdir(directory, { mode: 0o700 });
|
||||
try {
|
||||
const response = await client.session.create({
|
||||
directory,
|
||||
title,
|
||||
permission: [
|
||||
{ permission: "read", pattern: `${directory}/**`, action: "allow" },
|
||||
{ permission: "edit", pattern: `${directory}/**`, action: "ask" },
|
||||
],
|
||||
});
|
||||
return requireData(response.data, "session.create");
|
||||
} catch (error) {
|
||||
await rmdir(directory).catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getSession(sessionId: string) {
|
||||
const client = await this.ensureClient();
|
||||
const response = await client.session.get({ sessionID: sessionId });
|
||||
return requireData(response.data, "session.get");
|
||||
}
|
||||
|
||||
async sendPrompt(sessionId: string, text: string) {
|
||||
|
||||
@@ -15,6 +15,7 @@ export type RuntimeSessionContext = {
|
||||
sessionId: string;
|
||||
tokenExpiresAt?: string;
|
||||
traceId: string;
|
||||
workspaceDirectory?: string;
|
||||
};
|
||||
|
||||
const contexts = new Map<string, RuntimeSessionContext>();
|
||||
|
||||
@@ -342,6 +342,13 @@ app.post("/internal/tools/store-render-ref", async (req, res) => {
|
||||
res.status(400).json({ message: "file_path is required" });
|
||||
return;
|
||||
}
|
||||
if (!context.workspaceDirectory) {
|
||||
res.status(400).json({
|
||||
message: "conversation workspace is required",
|
||||
detail: "create a new conversation before importing render data",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const record = await resultReferenceResolver.registerRenderPayloadFile(filePath, {
|
||||
@@ -352,6 +359,7 @@ app.post("/internal/tools/store-render-ref", async (req, res) => {
|
||||
sessionId: context.clientSessionId,
|
||||
source: RESULT_REFERENCE_SOURCE.agentGenerated,
|
||||
traceId: context.traceId,
|
||||
workspaceDirectory: context.workspaceDirectory,
|
||||
});
|
||||
res.json({
|
||||
ok: true,
|
||||
|
||||
Reference in New Issue
Block a user