Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ce04704af2 | ||
|
|
004c9bb72d |
@@ -3,12 +3,25 @@ import { tool } from "@opencode-ai/plugin";
|
|||||||
const internalBaseUrl =
|
const internalBaseUrl =
|
||||||
process.env.TJWATER_AGENT_INTERNAL_BASE_URL ?? "http://127.0.0.1:8787";
|
process.env.TJWATER_AGENT_INTERNAL_BASE_URL ?? "http://127.0.0.1:8787";
|
||||||
const internalToken = process.env.TJWATER_AGENT_INTERNAL_TOKEN ?? "";
|
const internalToken = process.env.TJWATER_AGENT_INTERNAL_TOKEN ?? "";
|
||||||
const importDirectory =
|
|
||||||
process.env.RESULT_REF_IMPORT_DIR ?? "./data/result-imports";
|
type StoreRenderRefArgs = {
|
||||||
|
file_path?: unknown;
|
||||||
|
filePath?: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function resolveStoreRenderFilePath(args: StoreRenderRefArgs): string {
|
||||||
|
if (typeof args.file_path === "string" && args.file_path.trim() !== "") {
|
||||||
|
return args.file_path;
|
||||||
|
}
|
||||||
|
if (typeof args.filePath === "string" && args.filePath.trim() !== "") {
|
||||||
|
return args.filePath;
|
||||||
|
}
|
||||||
|
throw new Error("file_path is required");
|
||||||
|
}
|
||||||
|
|
||||||
export default tool({
|
export default tool({
|
||||||
description:
|
description:
|
||||||
`导入 ${importDirectory} 下的受控 JSON 包装文件并返回 render_ref。文件必须是 { metadata: object, location: { file_path: string }, data: { node_area_map, area_ids?, area_colors? } },location.file_path 必须与传入的绝对路径完全一致。只接受该目录内的真实文件,不接受目录外路径或指向目录外的符号链接。`,
|
"导入当前对话工作目录下的受控 JSON 包装文件并返回 render_ref。文件必须是 { metadata: object, location: { file_path: string }, data: { node_area_map, area_ids?, area_colors? } },location.file_path 必须与传入的绝对路径完全一致。只接受当前对话工作目录内的真实文件,不接受其他对话目录、目录外路径或指向目录外的符号链接。",
|
||||||
args: {
|
args: {
|
||||||
reason: tool.schema
|
reason: tool.schema
|
||||||
.string()
|
.string()
|
||||||
@@ -17,11 +30,17 @@ export default tool({
|
|||||||
),
|
),
|
||||||
file_path: tool.schema
|
file_path: tool.schema
|
||||||
.string()
|
.string()
|
||||||
|
.optional()
|
||||||
.describe(
|
.describe(
|
||||||
`位于 ${importDirectory} 内的包装 JSON 文件绝对路径。必须包含 metadata、location.file_path 和 data;data 才是 render_junctions 使用的 { node_area_map, area_ids?, area_colors? }。`,
|
"位于当前对话工作目录内的包装 JSON 文件绝对路径。必须包含 metadata、location.file_path 和 data;data 才是 render_junctions 使用的 { node_area_map, area_ids?, area_colors? }。",
|
||||||
),
|
),
|
||||||
|
filePath: tool.schema
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe("兼容旧调用的参数名;新调用应优先使用 file_path。"),
|
||||||
},
|
},
|
||||||
async execute(args, context) {
|
async execute(args, context) {
|
||||||
|
const filePath = resolveStoreRenderFilePath(args);
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${internalBaseUrl}/internal/tools/store-render-ref`,
|
`${internalBaseUrl}/internal/tools/store-render-ref`,
|
||||||
{
|
{
|
||||||
@@ -32,7 +51,7 @@ export default tool({
|
|||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
session_id: context.sessionID,
|
session_id: context.sessionID,
|
||||||
file_path: args.file_path,
|
file_path: filePath,
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -37,3 +37,5 @@ PRs should describe runtime behavior changes, list `bun run check` and any test
|
|||||||
## Security & Configuration Tips
|
## Security & Configuration Tips
|
||||||
|
|
||||||
Do not commit `.env`, logs, session transcripts, generated result references, or `node_modules/`. Keep registry and deploy credentials in Gitea secrets.
|
Do not commit `.env`, logs, session transcripts, generated result references, or `node_modules/`. Keep registry and deploy credentials in Gitea secrets.
|
||||||
|
|
||||||
|
Automatic approval for `glob` and `grep` must remain limited to canonical paths inside an explicit safe workspace subtree. Broad workspace-root searches, symlink escapes, external paths, and `.env`, `data/`, or `logs/` targets must stay interactive.
|
||||||
|
|||||||
@@ -86,11 +86,13 @@ TJWATER_API_BASE_URL=http://127.0.0.1:8000
|
|||||||
|
|
||||||
`opencode.json` 已启用 `experimental.continue_loop_on_deny`。用户拒绝权限请求后,OpenCode V1 会把拒绝结果交还给 Agent,让其尝试无需该权限的替代方案,而不是直接结束本轮执行。
|
`opencode.json` 已启用 `experimental.continue_loop_on_deny`。用户拒绝权限请求后,OpenCode V1 会把拒绝结果交还给 Agent,让其尝试无需该权限的替代方案,而不是直接结束本轮执行。
|
||||||
|
|
||||||
前端提供三种整体权限模式:“请求批准”只执行 OpenCode 明确允许的白名单,其他权限请求逐次交给用户确认;“自动批准”额外自动放行低风险业务工具,其他请求仍需确认;“始终允许”自动放行当前对话中所有未被 OpenCode 明确禁止的权限请求。自动放行统一使用单次批准,切换整体模式后立即恢复对应策略,不会写入持久授权。
|
前端提供三种整体权限模式:“请求批准”只执行 OpenCode 明确允许的白名单,其他权限请求逐次交给用户确认;“自动批准”额外自动放行低风险业务工具、skill,以及真实路径位于工作区安全子树且不涉及 `.env`、`data/`、`logs/` 的 glob/grep;工作区根目录的宽泛搜索仍需确认。“始终允许”自动放行当前对话中所有未被 OpenCode 明确禁止的权限请求。自动放行统一使用单次批准,切换整体模式后立即恢复对应策略,不会写入持久授权。
|
||||||
|
|
||||||
单次权限请求支持“允许一次”“保存授权”和“拒绝”。“保存授权”使用 OpenCode 的 `always` 回复,仅保存 OpenCode 为本次请求建议的权限范围,并只在当前 OpenCode 会话内生效。外部目录以及 `.env`、`data/`、`logs/` 路径仍由静态配置明确禁止,三种整体模式都不能绕过这些拒绝规则。
|
单次权限请求支持“允许一次”“保存授权”和“拒绝”。“保存授权”使用 OpenCode 的 `always` 回复,仅保存 OpenCode 为本次请求建议的权限范围,并只在当前 OpenCode 会话内生效。任意外部目录默认仍由静态配置禁止;`.env` 的直接访问以及通过结构化读写工具访问普通 `data/`、`logs/` 路径仍保持禁止。真实聊天会话使用 `data/conversation-workspaces/<随机目录>/` 作为独立工作目录,结果导入只能读取当前对话目录。普通 `rm <文件>` 仍可审批执行,常见的 `rm -rf`/`rm -fr` 递归强制删除形式会被静态拒绝。
|
||||||
|
|
||||||
`store_render_ref` 只会从 `RESULT_REF_IMPORT_DIR`(默认 `./data/result-imports`)导入包装格式 JSON。文件必须包含 `metadata`、`location.file_path` 和 `data`,且真实路径不能越出导入目录;单文件默认上限为 64 MiB,成功导入后源包装文件会被删除。
|
`store_render_ref` 只会从当前对话绑定的工作目录导入包装格式 JSON;工作区根目录固定为项目内的 `./data/conversation-workspaces`,以确保 OpenCode 能继续发现项目配置和工具。文件必须包含 `metadata`、`location.file_path` 和 `data`,且真实路径不能越出当前对话目录;单文件默认上限为 128 MiB,成功导入后只删除这一份源包装文件。升级前已经存在的会话没有独立工作目录,需要新建对话后才能使用该导入能力。
|
||||||
|
|
||||||
|
CLI 桥接层对 stdout 设置独立的 128 MiB 硬上限(`MAX_CLI_OUTPUT_BYTES`);stderr 最多保留 256 KiB(`MAX_CLI_STDERR_BYTES`),超出后截断但不会终止 CLI。`MAX_INLINE_RESULT_BYTES`(默认 12000 字节)只控制 OpenCode 的内联阈值,较大结果由 OpenCode 写入标准 `tool-output` 目录。Agent 启动时及后续定期清理其中超过 `RESULT_REF_TTL_HOURS`(默认 7 天)的 `tool_*` 文件。
|
||||||
|
|
||||||
## 配置与安全
|
## 配置与安全
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { emitApi } from "../core/http.js";
|
import { emitApi, requestAllPages } from "../core/http.js";
|
||||||
import { parseOptions, requiredString } from "../core/options.js";
|
import { optionalNumber, parseOptions, requiredString } from "../core/options.js";
|
||||||
|
import { success } from "../core/output.js";
|
||||||
import type { HandlerMap, RuntimeContext } from "../core/types.js";
|
import type { HandlerMap, RuntimeContext } from "../core/types.js";
|
||||||
|
|
||||||
function apiGet(ctx: RuntimeContext, argv: string[], summary: string, path: string, key: string): Promise<void> {
|
function apiGet(ctx: RuntimeContext, argv: string[], summary: string, path: string, key: string): Promise<void> {
|
||||||
@@ -7,20 +8,28 @@ function apiGet(ctx: RuntimeContext, argv: string[], summary: string, path: stri
|
|||||||
return emitApi(ctx, summary, { method: "GET", path, params: { [key]: requiredString(values, key) }, requireProject: true });
|
return emitApi(ctx, summary, { method: "GET", path, params: { [key]: requiredString(values, key) }, requireProject: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
function apiGetAll(ctx: RuntimeContext, summary: string, path: string): Promise<void> {
|
async function apiGetAll(ctx: RuntimeContext, argv: string[], summary: string, path: string): Promise<void> {
|
||||||
return emitApi(ctx, summary, { method: "GET", path, requireProject: true });
|
const { values } = parseOptions(argv, { limit: "integer", "page-size": "integer" });
|
||||||
|
const requestedPageSize = optionalNumber(values, "page-size") ?? optionalNumber(values, "limit") ?? 1000;
|
||||||
|
const pageSize = Math.min(1000, Math.max(1, requestedPageSize));
|
||||||
|
const [data, durationMs] = await requestAllPages(
|
||||||
|
ctx,
|
||||||
|
{ method: "GET", path, requireProject: true },
|
||||||
|
pageSize,
|
||||||
|
);
|
||||||
|
success(summary, data, ctx, durationMs);
|
||||||
}
|
}
|
||||||
|
|
||||||
export const networkHandlers: HandlerMap = {
|
export const networkHandlers: HandlerMap = {
|
||||||
"network get-junction-properties": (ctx, argv) => apiGet(ctx, argv, "读取节点属性成功", "/junctions/properties", "junction"),
|
"network get-junction-properties": (ctx, argv) => apiGet(ctx, argv, "读取节点属性成功", "/junctions/properties", "junction"),
|
||||||
"network get-pipe-properties": (ctx, argv) => apiGet(ctx, argv, "读取管道属性成功", "/pipes/properties", "pipe"),
|
"network get-pipe-properties": (ctx, argv) => apiGet(ctx, argv, "读取管道属性成功", "/pipes/properties", "pipe"),
|
||||||
"network get-all-pipes-properties": (ctx) => apiGetAll(ctx, "读取全部管道属性成功", "/pipes"),
|
"network get-all-pipes-properties": (ctx, argv) => apiGetAll(ctx, argv, "读取全部管道属性成功", "/pipes"),
|
||||||
"network get-reservoir-properties": (ctx, argv) => apiGet(ctx, argv, "读取水库属性成功", "/reservoirs/properties", "reservoir"),
|
"network get-reservoir-properties": (ctx, argv) => apiGet(ctx, argv, "读取水库属性成功", "/reservoirs/properties", "reservoir"),
|
||||||
"network get-all-reservoirs-properties": (ctx) => apiGetAll(ctx, "读取全部水库属性成功", "/reservoirs"),
|
"network get-all-reservoirs-properties": (ctx, argv) => apiGetAll(ctx, argv, "读取全部水库属性成功", "/reservoirs"),
|
||||||
"network get-tank-properties": (ctx, argv) => apiGet(ctx, argv, "读取水箱属性成功", "/tanks/properties", "tank"),
|
"network get-tank-properties": (ctx, argv) => apiGet(ctx, argv, "读取水箱属性成功", "/tanks/properties", "tank"),
|
||||||
"network get-all-tanks-properties": (ctx) => apiGetAll(ctx, "读取全部水箱属性成功", "/tanks"),
|
"network get-all-tanks-properties": (ctx, argv) => apiGetAll(ctx, argv, "读取全部水箱属性成功", "/tanks"),
|
||||||
"network get-pump-properties": (ctx, argv) => apiGet(ctx, argv, "读取水泵属性成功", "/pumps/properties", "pump"),
|
"network get-pump-properties": (ctx, argv) => apiGet(ctx, argv, "读取水泵属性成功", "/pumps/properties", "pump"),
|
||||||
"network get-all-pumps-properties": (ctx) => apiGetAll(ctx, "读取全部水泵属性成功", "/pumps"),
|
"network get-all-pumps-properties": (ctx, argv) => apiGetAll(ctx, argv, "读取全部水泵属性成功", "/pumps"),
|
||||||
"network get-valve-properties": (ctx, argv) => apiGet(ctx, argv, "读取阀门属性成功", "/valves/properties", "valve"),
|
"network get-valve-properties": (ctx, argv) => apiGet(ctx, argv, "读取阀门属性成功", "/valves/properties", "valve"),
|
||||||
"network get-all-valves-properties": (ctx) => apiGetAll(ctx, "读取全部阀门属性成功", "/valves"),
|
"network get-all-valves-properties": (ctx, argv) => apiGetAll(ctx, argv, "读取全部阀门属性成功", "/valves"),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -76,6 +76,100 @@ export async function requestJson(ctx: RuntimeContext, request: RequestOptions):
|
|||||||
return [payload, durationMs];
|
return [payload, durationMs];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function requestAllPages(
|
||||||
|
ctx: RuntimeContext,
|
||||||
|
request: RequestOptions,
|
||||||
|
pageSize: number,
|
||||||
|
): Promise<[unknown[], number]> {
|
||||||
|
const items: unknown[] = [];
|
||||||
|
let durationMs = 0;
|
||||||
|
let offset = 0;
|
||||||
|
let expectedTotal: number | null = null;
|
||||||
|
|
||||||
|
while (expectedTotal === null || offset < expectedTotal) {
|
||||||
|
const [payload, pageDurationMs] = await requestJson(ctx, {
|
||||||
|
...request,
|
||||||
|
params: {
|
||||||
|
...request.params,
|
||||||
|
limit: pageSize,
|
||||||
|
offset,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
durationMs += pageDurationMs;
|
||||||
|
const page = normalizePage(payload);
|
||||||
|
if (!page) {
|
||||||
|
throw new CliError(
|
||||||
|
"服务端错误",
|
||||||
|
"INVALID_PAGINATION_RESPONSE",
|
||||||
|
"backend collection response must contain items, total, limit, and offset",
|
||||||
|
7,
|
||||||
|
false,
|
||||||
|
payload,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (expectedTotal === null) {
|
||||||
|
expectedTotal = page.total;
|
||||||
|
} else if (page.total !== expectedTotal) {
|
||||||
|
throw new CliError(
|
||||||
|
"服务端错误",
|
||||||
|
"PAGINATION_TOTAL_CHANGED",
|
||||||
|
`backend collection total changed from ${expectedTotal} to ${page.total}`,
|
||||||
|
7,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (page.offset !== offset) {
|
||||||
|
throw new CliError(
|
||||||
|
"服务端错误",
|
||||||
|
"PAGINATION_OFFSET_MISMATCH",
|
||||||
|
`backend collection returned offset ${page.offset}, expected ${offset}`,
|
||||||
|
7,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (page.items.length === 0 && offset < expectedTotal) {
|
||||||
|
throw new CliError(
|
||||||
|
"服务端错误",
|
||||||
|
"PAGINATION_STALLED",
|
||||||
|
`backend collection returned an empty page at offset ${offset} before total ${expectedTotal}`,
|
||||||
|
7,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
items.push(...page.items);
|
||||||
|
offset += page.items.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [items.slice(0, expectedTotal ?? 0), durationMs];
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizePage(
|
||||||
|
payload: unknown,
|
||||||
|
): { items: unknown[]; limit: number; offset: number; total: number } | null {
|
||||||
|
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
|
||||||
|
const page = payload as Record<string, unknown>;
|
||||||
|
if (
|
||||||
|
!Array.isArray(page.items) ||
|
||||||
|
typeof page.limit !== "number" ||
|
||||||
|
!Number.isInteger(page.limit) ||
|
||||||
|
typeof page.offset !== "number" ||
|
||||||
|
!Number.isInteger(page.offset) ||
|
||||||
|
typeof page.total !== "number" ||
|
||||||
|
!Number.isInteger(page.total) ||
|
||||||
|
page.limit <= 0 ||
|
||||||
|
page.offset < 0 ||
|
||||||
|
page.total < 0
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
items: page.items,
|
||||||
|
limit: page.limit,
|
||||||
|
offset: page.offset,
|
||||||
|
total: page.total,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function mapStatus(status: number): number {
|
function mapStatus(status: number): number {
|
||||||
if (status === 400 || status === 422) return 2;
|
if (status === 400 || status === 422) return 2;
|
||||||
if (status === 401) return 3;
|
if (status === 401) return 3;
|
||||||
|
|||||||
@@ -32,15 +32,15 @@ type CommandSpec = readonly [path: string, summary: string, options: readonly st
|
|||||||
const commandSpecs: readonly CommandSpec[] = [
|
const commandSpecs: readonly CommandSpec[] = [
|
||||||
["network get-junction-properties", "读取节点属性", ["--junction <JUNCTION>"], ["tjwater-cli network get-junction-properties --junction J1"]],
|
["network get-junction-properties", "读取节点属性", ["--junction <JUNCTION>"], ["tjwater-cli network get-junction-properties --junction J1"]],
|
||||||
["network get-pipe-properties", "读取管道属性", ["--pipe <PIPE>"], ["tjwater-cli network get-pipe-properties --pipe P1"]],
|
["network get-pipe-properties", "读取管道属性", ["--pipe <PIPE>"], ["tjwater-cli network get-pipe-properties --pipe P1"]],
|
||||||
["network get-all-pipes-properties", "读取全部管道属性", [], ["tjwater-cli network get-all-pipes-properties"]],
|
["network get-all-pipes-properties", "读取全部管道属性", ["[--page-size <PAGE_SIZE>]"], ["tjwater-cli network get-all-pipes-properties"]],
|
||||||
["network get-reservoir-properties", "读取水库属性", ["--reservoir <RESERVOIR>"], ["tjwater-cli network get-reservoir-properties --reservoir R1"]],
|
["network get-reservoir-properties", "读取水库属性", ["--reservoir <RESERVOIR>"], ["tjwater-cli network get-reservoir-properties --reservoir R1"]],
|
||||||
["network get-all-reservoirs-properties", "读取全部水库属性", [], ["tjwater-cli network get-all-reservoirs-properties"]],
|
["network get-all-reservoirs-properties", "读取全部水库属性", ["[--page-size <PAGE_SIZE>]"], ["tjwater-cli network get-all-reservoirs-properties"]],
|
||||||
["network get-tank-properties", "读取水箱属性", ["--tank <TANK>"], ["tjwater-cli network get-tank-properties --tank T1"]],
|
["network get-tank-properties", "读取水箱属性", ["--tank <TANK>"], ["tjwater-cli network get-tank-properties --tank T1"]],
|
||||||
["network get-all-tanks-properties", "读取全部水箱属性", [], ["tjwater-cli network get-all-tanks-properties"]],
|
["network get-all-tanks-properties", "读取全部水箱属性", ["[--page-size <PAGE_SIZE>]"], ["tjwater-cli network get-all-tanks-properties"]],
|
||||||
["network get-pump-properties", "读取水泵属性", ["--pump <PUMP>"], ["tjwater-cli network get-pump-properties --pump PU1"]],
|
["network get-pump-properties", "读取水泵属性", ["--pump <PUMP>"], ["tjwater-cli network get-pump-properties --pump PU1"]],
|
||||||
["network get-all-pumps-properties", "读取全部水泵属性", [], ["tjwater-cli network get-all-pumps-properties"]],
|
["network get-all-pumps-properties", "读取全部水泵属性", ["[--page-size <PAGE_SIZE>]"], ["tjwater-cli network get-all-pumps-properties"]],
|
||||||
["network get-valve-properties", "读取阀门属性", ["--valve <VALVE>"], ["tjwater-cli network get-valve-properties --valve V1"]],
|
["network get-valve-properties", "读取阀门属性", ["--valve <VALVE>"], ["tjwater-cli network get-valve-properties --valve V1"]],
|
||||||
["network get-all-valves-properties", "读取全部阀门属性", [], ["tjwater-cli network get-all-valves-properties"]],
|
["network get-all-valves-properties", "读取全部阀门属性", ["[--page-size <PAGE_SIZE>]"], ["tjwater-cli network get-all-valves-properties"]],
|
||||||
["component option schema", "读取选项 schema", ["--kind <KIND>", "[--pump <PUMP>]"], ["tjwater-cli component option schema --kind time", "tjwater-cli component option schema --kind energy", "tjwater-cli component option schema --kind pump-energy --pump PUMP1", "tjwater-cli component option schema --kind network"]],
|
["component option schema", "读取选项 schema", ["--kind <KIND>", "[--pump <PUMP>]"], ["tjwater-cli component option schema --kind time", "tjwater-cli component option schema --kind energy", "tjwater-cli component option schema --kind pump-energy --pump PUMP1", "tjwater-cli component option schema --kind network"]],
|
||||||
["component option get", "读取选项属性", ["--kind <KIND>", "[--pump <PUMP>]"], ["tjwater-cli component option get --kind time", "tjwater-cli component option get --kind energy", "tjwater-cli component option get --kind pump-energy --pump PUMP1", "tjwater-cli component option get --kind network"]],
|
["component option get", "读取选项属性", ["--kind <KIND>", "[--pump <PUMP>]"], ["tjwater-cli component option get --kind time", "tjwater-cli component option get --kind energy", "tjwater-cli component option get --kind pump-energy --pump PUMP1", "tjwater-cli component option get --kind network"]],
|
||||||
["simulation run", "触发指定绝对时间的模拟运行", ["--start-time <START_TIME>", "--duration <DURATION>"], ["tjwater-cli simulation run --start-time 2025-01-02T03:04:05+08:00 --duration 30"], ["tjwater-cli data timeseries realtime links --start-time 2025-01-02T03:04:05+08:00 --end-time 2025-01-02T03:34:05+08:00", "tjwater-cli data timeseries realtime nodes --start-time 2025-01-02T03:04:05+08:00 --end-time 2025-01-02T03:34:05+08:00"]],
|
["simulation run", "触发指定绝对时间的模拟运行", ["--start-time <START_TIME>", "--duration <DURATION>"], ["tjwater-cli simulation run --start-time 2025-01-02T03:04:05+08:00 --duration 30"], ["tjwater-cli data timeseries realtime links --start-time 2025-01-02T03:04:05+08:00 --end-time 2025-01-02T03:34:05+08:00", "tjwater-cli data timeseries realtime nodes --start-time 2025-01-02T03:04:05+08:00 --end-time 2025-01-02T03:34:05+08:00"]],
|
||||||
|
|||||||
@@ -104,7 +104,11 @@ async function startJsonServer(responseData) {
|
|||||||
url: req.url,
|
url: req.url,
|
||||||
});
|
});
|
||||||
res.setHeader("content-type", "application/json");
|
res.setHeader("content-type", "application/json");
|
||||||
res.end(JSON.stringify(responseData));
|
res.end(
|
||||||
|
JSON.stringify(
|
||||||
|
typeof responseData === "function" ? responseData(req) : responseData,
|
||||||
|
),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
await new Promise((resolveListen, reject) => {
|
await new Promise((resolveListen, reject) => {
|
||||||
@@ -138,7 +142,20 @@ function normalizeSeenRequest(request) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function runAgainstServer(name, runner, args, auth, responseData = { accepted: true }) {
|
function defaultContractResponse(req) {
|
||||||
|
const url = new URL(req.url, "http://127.0.0.1");
|
||||||
|
if (["/api/v1/pipes", "/api/v1/reservoirs", "/api/v1/tanks", "/api/v1/pumps", "/api/v1/valves"].includes(url.pathname)) {
|
||||||
|
return {
|
||||||
|
items: [],
|
||||||
|
limit: Number(url.searchParams.get("limit")),
|
||||||
|
offset: Number(url.searchParams.get("offset")),
|
||||||
|
total: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return { accepted: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runAgainstServer(name, runner, args, auth, responseData = defaultContractResponse) {
|
||||||
const server = await startJsonServer(responseData);
|
const server = await startJsonServer(responseData);
|
||||||
try {
|
try {
|
||||||
const result = await runner(["--auth-stdin", ...args], { ...auth, server: server.url });
|
const result = await runner(["--auth-stdin", ...args], { ...auth, server: server.url });
|
||||||
@@ -232,6 +249,52 @@ test("sends auth headers and simulation body through the backend API contract",
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("get-all network commands collect every backend page", async () => {
|
||||||
|
const items = Array.from({ length: 2_005 }, (_, index) => ({
|
||||||
|
id: `P${index + 1}`,
|
||||||
|
node1: `N${index + 1}`,
|
||||||
|
node2: `N${index + 2}`,
|
||||||
|
}));
|
||||||
|
const server = await startJsonServer((req) => {
|
||||||
|
const url = new URL(req.url, "http://127.0.0.1");
|
||||||
|
const limit = Number(url.searchParams.get("limit") ?? 100);
|
||||||
|
const offset = Number(url.searchParams.get("offset") ?? 0);
|
||||||
|
return {
|
||||||
|
items: items.slice(offset, offset + limit),
|
||||||
|
limit,
|
||||||
|
offset,
|
||||||
|
total: items.length,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await runCli(
|
||||||
|
["--auth-stdin", "network", "get-all-pipes-properties"],
|
||||||
|
{
|
||||||
|
server: server.url,
|
||||||
|
access_token: "token-1",
|
||||||
|
project_id: "project-1",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.equal(result.exitCode, 0, result.stderr);
|
||||||
|
const payload = parseJsonResult(result);
|
||||||
|
assert.equal(payload.data.length, items.length);
|
||||||
|
assert.deepEqual(payload.data[0], items[0]);
|
||||||
|
assert.deepEqual(payload.data.at(-1), items.at(-1));
|
||||||
|
assert.deepEqual(
|
||||||
|
server.seen.map((request) => normalizeSeenRequest(request).query),
|
||||||
|
[
|
||||||
|
{ limit: "1000", offset: "0" },
|
||||||
|
{ limit: "1000", offset: "1000" },
|
||||||
|
{ limit: "1000", offset: "2000" },
|
||||||
|
],
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
await server.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
test("uses project scoped headers for realtime data commands", async () => {
|
test("uses project scoped headers for realtime data commands", async () => {
|
||||||
const server = await startJsonServer([{ id: "P1" }]);
|
const server = await startJsonServer([{ id: "P1" }]);
|
||||||
try {
|
try {
|
||||||
|
|||||||
+7
-7
@@ -44,6 +44,12 @@
|
|||||||
"bash": {
|
"bash": {
|
||||||
"*": "ask",
|
"*": "ask",
|
||||||
"rm *": "ask",
|
"rm *": "ask",
|
||||||
|
"rm -rf *": "deny",
|
||||||
|
"rm -fr *": "deny",
|
||||||
|
"rm -r -f *": "deny",
|
||||||
|
"rm -f -r *": "deny",
|
||||||
|
"rm --recursive --force *": "deny",
|
||||||
|
"rm --force --recursive *": "deny",
|
||||||
"rmdir *": "ask",
|
"rmdir *": "ask",
|
||||||
"mv *": "ask",
|
"mv *": "ask",
|
||||||
"chmod *": "ask",
|
"chmod *": "ask",
|
||||||
@@ -51,13 +57,7 @@
|
|||||||
"sudo *": "ask",
|
"sudo *": "ask",
|
||||||
"curl *": "ask",
|
"curl *": "ask",
|
||||||
"wget *": "ask",
|
"wget *": "ask",
|
||||||
"*.env*": "deny",
|
"*.env*": "deny"
|
||||||
"*data/*": "deny",
|
|
||||||
"* data": "deny",
|
|
||||||
"*/data": "deny",
|
|
||||||
"*logs/*": "deny",
|
|
||||||
"* logs": "deny",
|
|
||||||
"*/logs": "deny"
|
|
||||||
},
|
},
|
||||||
"question": "allow",
|
"question": "allow",
|
||||||
"task": "deny",
|
"task": "deny",
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ export type SessionBinding = {
|
|||||||
clientSessionId: string;
|
clientSessionId: string;
|
||||||
sessionId: string;
|
sessionId: string;
|
||||||
startedAt: number;
|
startedAt: number;
|
||||||
|
workspaceDirectory?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type SessionContext = {
|
export type SessionContext = {
|
||||||
@@ -52,20 +53,26 @@ export class ChatSessionBridge {
|
|||||||
await this.abortActiveRuntime(requestContext.clientSessionId, existingSessionId);
|
await this.abortActiveRuntime(requestContext.clientSessionId, existingSessionId);
|
||||||
|
|
||||||
let sessionId = existingSessionId;
|
let sessionId = existingSessionId;
|
||||||
|
let runtimeSession;
|
||||||
let created = false;
|
let created = false;
|
||||||
if (!sessionId) {
|
if (!sessionId) {
|
||||||
const session = await this.runtime.createSession();
|
runtimeSession = await this.runtime.createSession(undefined, {
|
||||||
sessionId = session.id;
|
conversationWorkspace: true,
|
||||||
|
});
|
||||||
|
sessionId = runtimeSession.id;
|
||||||
requestContext = {
|
requestContext = {
|
||||||
...requestContext,
|
...requestContext,
|
||||||
clientSessionId: sessionId,
|
clientSessionId: sessionId,
|
||||||
};
|
};
|
||||||
created = true;
|
created = true;
|
||||||
|
} else {
|
||||||
|
runtimeSession = await this.runtime.getSession(sessionId);
|
||||||
}
|
}
|
||||||
const binding: SessionBinding = {
|
const binding: SessionBinding = {
|
||||||
clientSessionId: requestContext.clientSessionId,
|
clientSessionId: requestContext.clientSessionId,
|
||||||
sessionId,
|
sessionId,
|
||||||
startedAt: Date.now(),
|
startedAt: Date.now(),
|
||||||
|
workspaceDirectory: runtimeSession.directory,
|
||||||
};
|
};
|
||||||
setRuntimeSessionContext({
|
setRuntimeSessionContext({
|
||||||
accessToken: requestContext.accessToken,
|
accessToken: requestContext.accessToken,
|
||||||
@@ -79,6 +86,7 @@ export class ChatSessionBridge {
|
|||||||
sessionId,
|
sessionId,
|
||||||
tokenExpiresAt: requestContext.tokenExpiresAt,
|
tokenExpiresAt: requestContext.tokenExpiresAt,
|
||||||
traceId: requestContext.traceId,
|
traceId: requestContext.traceId,
|
||||||
|
workspaceDirectory: runtimeSession.directory,
|
||||||
});
|
});
|
||||||
|
|
||||||
return { binding, requestContext, created };
|
return { binding, requestContext, created };
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ export type CliExecutionResult = {
|
|||||||
signal: NodeJS.Signals | null;
|
signal: NodeJS.Signals | null;
|
||||||
status: number;
|
status: number;
|
||||||
stderr: string;
|
stderr: string;
|
||||||
|
stderrTruncated: boolean;
|
||||||
stdout: string;
|
stdout: string;
|
||||||
exceededStream?: OutputStream;
|
exceededStream?: OutputStream;
|
||||||
};
|
};
|
||||||
@@ -17,7 +18,8 @@ export type CliExecutionResult = {
|
|||||||
type ExecuteCliCommandOptions = {
|
type ExecuteCliCommandOptions = {
|
||||||
apiBaseUrl: string;
|
apiBaseUrl: string;
|
||||||
cliPath: string;
|
cliPath: string;
|
||||||
maxOutputBytes: number;
|
maxStderrBytes: number;
|
||||||
|
maxStdoutBytes: number;
|
||||||
terminationGraceMs?: number;
|
terminationGraceMs?: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -46,9 +48,11 @@ export const executeCliCommand = async (
|
|||||||
timeoutSec: number,
|
timeoutSec: number,
|
||||||
options: ExecuteCliCommandOptions,
|
options: ExecuteCliCommandOptions,
|
||||||
): Promise<CliExecutionResult> => {
|
): Promise<CliExecutionResult> => {
|
||||||
const maxOutputBytes = options.maxOutputBytes;
|
if (!Number.isSafeInteger(options.maxStdoutBytes) || options.maxStdoutBytes <= 0) {
|
||||||
if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes <= 0) {
|
throw new Error("maxStdoutBytes must be a positive safe integer");
|
||||||
throw new Error("maxOutputBytes must be a positive safe integer");
|
}
|
||||||
|
if (!Number.isSafeInteger(options.maxStderrBytes) || options.maxStderrBytes <= 0) {
|
||||||
|
throw new Error("maxStderrBytes must be a positive safe integer");
|
||||||
}
|
}
|
||||||
|
|
||||||
const child = spawn(
|
const child = spawn(
|
||||||
@@ -60,6 +64,7 @@ export const executeCliCommand = async (
|
|||||||
const stderrChunks: Buffer[] = [];
|
const stderrChunks: Buffer[] = [];
|
||||||
let stdoutBytes = 0;
|
let stdoutBytes = 0;
|
||||||
let stderrBytes = 0;
|
let stderrBytes = 0;
|
||||||
|
let stderrTruncated = false;
|
||||||
let terminationReason:
|
let terminationReason:
|
||||||
| "timeout"
|
| "timeout"
|
||||||
| "output_limit"
|
| "output_limit"
|
||||||
@@ -98,23 +103,34 @@ export const executeCliCommand = async (
|
|||||||
}, options.terminationGraceMs ?? 1500);
|
}, options.terminationGraceMs ?? 1500);
|
||||||
};
|
};
|
||||||
|
|
||||||
const capture = (stream: OutputStream, data: Buffer) => {
|
const captureStdout = (data: Buffer) => {
|
||||||
if (terminationReason) {
|
if (terminationReason) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const chunks = stream === "stdout" ? stdoutChunks : stderrChunks;
|
if (stdoutBytes + data.length > options.maxStdoutBytes) {
|
||||||
const bytes = stream === "stdout" ? stdoutBytes : stderrBytes;
|
exceededStream = "stdout";
|
||||||
if (bytes + data.length > maxOutputBytes) {
|
|
||||||
exceededStream = stream;
|
|
||||||
terminate("output_limit");
|
terminate("output_limit");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
chunks.push(data);
|
stdoutChunks.push(data);
|
||||||
if (stream === "stdout") {
|
stdoutBytes += data.length;
|
||||||
stdoutBytes += data.length;
|
};
|
||||||
} else {
|
|
||||||
stderrBytes += data.length;
|
const captureStderr = (data: Buffer) => {
|
||||||
|
if (terminationReason || stderrTruncated) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
const remainingBytes = options.maxStderrBytes - stderrBytes;
|
||||||
|
if (data.length > remainingBytes) {
|
||||||
|
if (remainingBytes > 0) {
|
||||||
|
stderrChunks.push(data.subarray(0, remainingBytes));
|
||||||
|
stderrBytes += remainingBytes;
|
||||||
|
}
|
||||||
|
stderrTruncated = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
stderrChunks.push(data);
|
||||||
|
stderrBytes += data.length;
|
||||||
};
|
};
|
||||||
|
|
||||||
const timeoutTimer = setTimeout(() => {
|
const timeoutTimer = setTimeout(() => {
|
||||||
@@ -123,8 +139,8 @@ export const executeCliCommand = async (
|
|||||||
}
|
}
|
||||||
}, timeoutSec * 1000);
|
}, timeoutSec * 1000);
|
||||||
|
|
||||||
child.stdout.on("data", (data: Buffer) => capture("stdout", data));
|
child.stdout.on("data", captureStdout);
|
||||||
child.stderr.on("data", (data: Buffer) => capture("stderr", data));
|
child.stderr.on("data", captureStderr);
|
||||||
child.stdin.on("error", (error) => {
|
child.stdin.on("error", (error) => {
|
||||||
if (terminationReason === null) {
|
if (terminationReason === null) {
|
||||||
executionError = error;
|
executionError = error;
|
||||||
@@ -150,6 +166,7 @@ export const executeCliCommand = async (
|
|||||||
signal,
|
signal,
|
||||||
status: 504,
|
status: 504,
|
||||||
stderr: "",
|
stderr: "",
|
||||||
|
stderrTruncated,
|
||||||
stdout: "",
|
stdout: "",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
@@ -166,6 +183,7 @@ export const executeCliCommand = async (
|
|||||||
signal,
|
signal,
|
||||||
status: 502,
|
status: 502,
|
||||||
stderr: "",
|
stderr: "",
|
||||||
|
stderrTruncated,
|
||||||
stdout: "",
|
stdout: "",
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
@@ -179,6 +197,7 @@ export const executeCliCommand = async (
|
|||||||
signal,
|
signal,
|
||||||
status: getCompletedStatus(exitCode, stdout),
|
status: getCompletedStatus(exitCode, stdout),
|
||||||
stderr,
|
stderr,
|
||||||
|
stderrTruncated,
|
||||||
stdout,
|
stdout,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+19
-3
@@ -7,6 +7,8 @@ import {
|
|||||||
parseAgentModelOptions,
|
parseAgentModelOptions,
|
||||||
} from "./chat/modelConfig.js";
|
} from "./chat/modelConfig.js";
|
||||||
|
|
||||||
|
export const RESULT_REF_IMPORT_DIRECTORY = "./data/conversation-workspaces";
|
||||||
|
|
||||||
// 本地开发可在项目根目录放 .local.env;已存在的系统环境变量优先级更高。
|
// 本地开发可在项目根目录放 .local.env;已存在的系统环境变量优先级更高。
|
||||||
dotenv.config({ path: ".local.env", override: false });
|
dotenv.config({ path: ".local.env", override: false });
|
||||||
|
|
||||||
@@ -61,8 +63,20 @@ const envSchema = z
|
|||||||
TJWATER_API_BASE_URL: z.string().default("http://127.0.0.1:8000"),
|
TJWATER_API_BASE_URL: z.string().default("http://127.0.0.1:8000"),
|
||||||
// 代理调用 TJWater 后端 API 的超时时间(毫秒)。
|
// 代理调用 TJWater 后端 API 的超时时间(毫秒)。
|
||||||
TJWATER_API_TIMEOUT_MS: z.coerce.number().int().positive().default(30000),
|
TJWATER_API_TIMEOUT_MS: z.coerce.number().int().positive().default(30000),
|
||||||
// 后端结果在直接内联返回给模型前允许的最大字节数。
|
// OpenCode 工具结果以内联形式返回给模型的阈值;更大的结果由 OpenCode 落盘。
|
||||||
MAX_INLINE_RESULT_BYTES: z.coerce.number().int().positive().default(12000),
|
MAX_INLINE_RESULT_BYTES: z.coerce.number().int().positive().default(12000),
|
||||||
|
// 单次 tjwater-cli stdout 的硬上限;超过后终止子进程。
|
||||||
|
MAX_CLI_OUTPUT_BYTES: z.coerce
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.positive()
|
||||||
|
.default(128 * 1024 * 1024),
|
||||||
|
// 单次 tjwater-cli stderr 最多保留的字节数;超过后截断但不终止进程。
|
||||||
|
MAX_CLI_STDERR_BYTES: z.coerce
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.positive()
|
||||||
|
.default(256 * 1024),
|
||||||
// 生成结果 preview 时最多抽样的条目数。
|
// 生成结果 preview 时最多抽样的条目数。
|
||||||
MAX_PREVIEW_SAMPLE_ITEMS: z.coerce.number().int().positive().default(3),
|
MAX_PREVIEW_SAMPLE_ITEMS: z.coerce.number().int().positive().default(3),
|
||||||
// memory 持久化存储目录。
|
// memory 持久化存储目录。
|
||||||
@@ -104,13 +118,15 @@ const envSchema = z
|
|||||||
// result_ref 持久化存储目录。
|
// result_ref 持久化存储目录。
|
||||||
RESULT_REF_STORAGE_DIR: z.string().default("./data/result-refs"),
|
RESULT_REF_STORAGE_DIR: z.string().default("./data/result-refs"),
|
||||||
// 仅允许 store_render_ref 从该目录导入受控 JSON 包装文件。
|
// 仅允许 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 的最大导入字节数。
|
// 单个渲染包装 JSON 的最大导入字节数。
|
||||||
RESULT_REF_IMPORT_MAX_BYTES: z.coerce
|
RESULT_REF_IMPORT_MAX_BYTES: z.coerce
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
.positive()
|
.positive()
|
||||||
.default(64 * 1024 * 1024),
|
.default(128 * 1024 * 1024),
|
||||||
// result_ref 保留时长(小时)。
|
// result_ref 保留时长(小时)。
|
||||||
RESULT_REF_TTL_HOURS: z.coerce.number().int().positive().default(168),
|
RESULT_REF_TTL_HOURS: z.coerce.number().int().positive().default(168),
|
||||||
// 定时清理过期 result_ref 的扫描周期(毫秒)。
|
// 定时清理过期 result_ref 的扫描周期(毫秒)。
|
||||||
|
|||||||
+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 { isAbsolute, relative } from "node:path";
|
||||||
|
|
||||||
import { readJsonFile, removeFileIfExists } from "../utils/fileStore.js";
|
import { readJsonFile, removeFileIfExists } from "../utils/fileStore.js";
|
||||||
@@ -68,9 +68,19 @@ export class ResultReferenceResolver {
|
|||||||
|
|
||||||
async registerRenderPayloadFile(
|
async registerRenderPayloadFile(
|
||||||
filePath: string,
|
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);
|
const fileStat = await stat(resolvedFilePath);
|
||||||
if (!fileStat.isFile()) {
|
if (!fileStat.isFile()) {
|
||||||
throw new Error("render payload path must point to a regular file");
|
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");
|
throw new Error("render payload file does not contain a valid junction render payload");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const { workspaceDirectory: _workspaceDirectory, ...registrationInput } = input;
|
||||||
const record = await this.register({
|
const record = await this.register({
|
||||||
...input,
|
...registrationInput,
|
||||||
data: payload,
|
data: payload,
|
||||||
kind: RESULT_REFERENCE_KIND.renderJunctionsPayload,
|
kind: RESULT_REFERENCE_KIND.renderJunctionsPayload,
|
||||||
schemaVersion: 1,
|
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)) {
|
if (!isAbsolute(filePath)) {
|
||||||
throw new Error("render payload file_path must be absolute");
|
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" ? "\\" : "/"}`) ||
|
relativePath.startsWith(`..${process.platform === "win32" ? "\\" : "/"}`) ||
|
||||||
isAbsolute(relativePath)
|
isAbsolute(relativePath)
|
||||||
) {
|
) {
|
||||||
throw new Error("render payload file must be inside RESULT_REF_IMPORT_DIR");
|
throw new Error(outsideMessage);
|
||||||
}
|
}
|
||||||
return resolvedFilePath;
|
return resolvedFilePath;
|
||||||
};
|
};
|
||||||
|
|||||||
+7
-2
@@ -155,7 +155,9 @@ export const buildChatRouter = (
|
|||||||
const actorKey = toActorKey(userId);
|
const actorKey = toActorKey(userId);
|
||||||
const projectKey = toProjectKey(projectId);
|
const projectKey = toProjectKey(projectId);
|
||||||
const requestedSessionId = parsed.data.session_id?.trim();
|
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({
|
const { record, created } = await sessionMetadataStore.ensure({
|
||||||
actorKey,
|
actorKey,
|
||||||
@@ -451,7 +453,9 @@ export const buildChatRouter = (
|
|||||||
res.status(404).json({ message: "source session not found" });
|
res.status(404).json({ message: "source session not found" });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const forkSession = await runtime.createSession();
|
const forkSession = await runtime.createSession(undefined, {
|
||||||
|
conversationWorkspace: true,
|
||||||
|
});
|
||||||
const { record: targetSessionRecord } = await sessionMetadataStore.ensure({
|
const { record: targetSessionRecord } = await sessionMetadataStore.ensure({
|
||||||
actorKey,
|
actorKey,
|
||||||
parentSessionId: sourceSessionId,
|
parentSessionId: sourceSessionId,
|
||||||
@@ -874,6 +878,7 @@ export const buildChatRouter = (
|
|||||||
traceId: requestContext.traceId,
|
traceId: requestContext.traceId,
|
||||||
projectId: requestContext.projectId,
|
projectId: requestContext.projectId,
|
||||||
signal: abortController.signal,
|
signal: abortController.signal,
|
||||||
|
workspaceRoot: binding.workspaceDirectory,
|
||||||
write: (event, data) => {
|
write: (event, data) => {
|
||||||
publish(event, data);
|
publish(event, data);
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,5 +1,14 @@
|
|||||||
|
import { lstatSync, readdirSync, realpathSync } from "node:fs";
|
||||||
|
import { isAbsolute, relative, resolve, sep } from "node:path";
|
||||||
|
|
||||||
export type ApprovalMode = "request" | "auto" | "always";
|
export type ApprovalMode = "request" | "auto" | "always";
|
||||||
|
|
||||||
|
export type PermissionApprovalContext = {
|
||||||
|
metadata?: Record<string, unknown>;
|
||||||
|
patterns?: readonly string[];
|
||||||
|
workspaceRoot?: string;
|
||||||
|
};
|
||||||
|
|
||||||
const lowRiskToolPermissions = new Set([
|
const lowRiskToolPermissions = new Set([
|
||||||
"apply_layer_style",
|
"apply_layer_style",
|
||||||
"geocode",
|
"geocode",
|
||||||
@@ -12,10 +21,31 @@ const lowRiskToolPermissions = new Set([
|
|||||||
"zoom_to_map",
|
"zoom_to_map",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
const lowRiskSearchRootNames = new Set([
|
||||||
|
".opencode",
|
||||||
|
"cli",
|
||||||
|
"contracts",
|
||||||
|
"node-tests",
|
||||||
|
"scripts",
|
||||||
|
"src",
|
||||||
|
"tests",
|
||||||
|
]);
|
||||||
|
|
||||||
const normalizePermission = (permission: string) => permission.trim().toLowerCase();
|
const normalizePermission = (permission: string) => permission.trim().toLowerCase();
|
||||||
|
|
||||||
export const canAutoApprovePermission = (permission: string): boolean => {
|
export const canAutoApprovePermission = (
|
||||||
|
permission: string,
|
||||||
|
context: PermissionApprovalContext = {},
|
||||||
|
): boolean => {
|
||||||
const normalized = normalizePermission(permission);
|
const normalized = normalizePermission(permission);
|
||||||
|
if (normalized === "skill") {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (normalized === "glob" || normalized === "grep") {
|
||||||
|
return isSafeWorkspaceSearch(normalized, context);
|
||||||
|
}
|
||||||
|
|
||||||
if (lowRiskToolPermissions.has(normalized)) {
|
if (lowRiskToolPermissions.has(normalized)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -30,19 +60,44 @@ export const canAutoApprovePermission = (permission: string): boolean => {
|
|||||||
export const resolvePermissionApproval = (
|
export const resolvePermissionApproval = (
|
||||||
approvalMode: ApprovalMode,
|
approvalMode: ApprovalMode,
|
||||||
permission: string,
|
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") {
|
if (approvalMode === "always") {
|
||||||
return {
|
return {
|
||||||
autoApprove: true,
|
autoApprove: true,
|
||||||
|
autoReject: false,
|
||||||
title: "已按始终允许模式放行",
|
title: "已按始终允许模式放行",
|
||||||
detail:
|
detail:
|
||||||
"当前会话处于始终允许模式,已放行本次权限请求;明确禁止的权限仍由 OpenCode 拒绝。",
|
"当前会话处于始终允许模式,已放行本次权限请求;明确禁止的权限仍由 OpenCode 拒绝。",
|
||||||
} as const;
|
} as const;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (approvalMode === "auto" && canAutoApprovePermission(permission)) {
|
if (approvalMode === "auto" && canAutoApprovePermission(permission, context)) {
|
||||||
return {
|
return {
|
||||||
autoApprove: true,
|
autoApprove: true,
|
||||||
|
autoReject: false,
|
||||||
title: "已自动批准低风险权限",
|
title: "已自动批准低风险权限",
|
||||||
detail: "当前批准模式允许自动执行低风险工具,已放行本次请求。",
|
detail: "当前批准模式允许自动执行低风险工具,已放行本次请求。",
|
||||||
} as const;
|
} as const;
|
||||||
@@ -50,7 +105,266 @@ export const resolvePermissionApproval = (
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
autoApprove: false,
|
autoApprove: false,
|
||||||
|
autoReject: false,
|
||||||
title: "等待权限确认",
|
title: "等待权限确认",
|
||||||
detail: undefined,
|
detail: undefined,
|
||||||
} as const;
|
} 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,
|
||||||
|
): boolean => {
|
||||||
|
const workspaceRoot = context.workspaceRoot?.trim();
|
||||||
|
if (!workspaceRoot) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const requestedPath =
|
||||||
|
typeof context.metadata?.path === "string" && context.metadata.path.trim()
|
||||||
|
? context.metadata.path
|
||||||
|
: workspaceRoot;
|
||||||
|
let root: string;
|
||||||
|
let searchRoot: string;
|
||||||
|
try {
|
||||||
|
root = realpathSync.native(resolve(workspaceRoot));
|
||||||
|
searchRoot = realpathSync.native(resolve(root, requestedPath));
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let relativePath = relative(root, searchRoot);
|
||||||
|
if (
|
||||||
|
relativePath === ".." ||
|
||||||
|
relativePath.startsWith(`..${sep}`) ||
|
||||||
|
isAbsolute(relativePath)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const expressions: string[] = [];
|
||||||
|
if (permission === "glob" && typeof context.metadata?.pattern === "string") {
|
||||||
|
expressions.push(context.metadata.pattern);
|
||||||
|
}
|
||||||
|
if (permission === "glob") {
|
||||||
|
expressions.push(...(context.patterns ?? []));
|
||||||
|
}
|
||||||
|
if (typeof context.metadata?.include === "string") {
|
||||||
|
expressions.push(context.metadata.include);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
expressions.some(
|
||||||
|
(expression) =>
|
||||||
|
isAbsolute(expression) ||
|
||||||
|
containsParentTraversal(expression) ||
|
||||||
|
containsAmbiguousGlobSyntax(expression) ||
|
||||||
|
containsProtectedPath(expression),
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!relativePath) {
|
||||||
|
if (permission !== "glob") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const literalPrefix = getLiteralGlobPrefix(expressions[0]);
|
||||||
|
if (!literalPrefix) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
searchRoot = realpathSync.native(resolve(root, literalPrefix));
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
relativePath = relative(root, searchRoot);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
relativePath !== "" &&
|
||||||
|
relativePath !== ".." &&
|
||||||
|
!relativePath.startsWith(`..${sep}`) &&
|
||||||
|
!isAbsolute(relativePath) &&
|
||||||
|
!containsProtectedPath(relativePath) &&
|
||||||
|
isSafeSearchTarget(searchRoot, relativePath)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const isSafeSearchTarget = (searchRoot: string, relativePath: string): boolean => {
|
||||||
|
try {
|
||||||
|
const target = lstatSync(searchRoot);
|
||||||
|
if (target.isFile()) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (!target.isDirectory()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const topLevelName = relativePath.split(sep)[0];
|
||||||
|
if (!topLevelName || !lowRiskSearchRootNames.has(topLevelName)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const pending = [searchRoot];
|
||||||
|
while (pending.length > 0) {
|
||||||
|
const directory = pending.pop()!;
|
||||||
|
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
||||||
|
if (entry.isSymbolicLink() || containsProtectedPath(entry.name)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (entry.isDirectory()) {
|
||||||
|
pending.push(resolve(directory, entry.name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const getLiteralGlobPrefix = (expression: string | undefined): string | null => {
|
||||||
|
const firstSegment = expression
|
||||||
|
?.replaceAll("\\", "/")
|
||||||
|
.replace(/^\.\//, "")
|
||||||
|
.split("/")[0];
|
||||||
|
return firstSegment && !/[*?[\]{}()!+@]/.test(firstSegment)
|
||||||
|
? firstSegment
|
||||||
|
: null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const containsParentTraversal = (value: string): boolean =>
|
||||||
|
value.replaceAll("\\", "/").split("/").includes("..");
|
||||||
|
|
||||||
|
const containsAmbiguousGlobSyntax = (value: string): boolean =>
|
||||||
|
/[?[\]{}()!+@\\]/.test(value);
|
||||||
|
|
||||||
|
const containsProtectedPath = (value: string): boolean => {
|
||||||
|
const normalized = value.replaceAll("\\", "/").toLowerCase();
|
||||||
|
return (
|
||||||
|
normalized.includes(".env") ||
|
||||||
|
/(?:^|[^a-z0-9_-])(?:data|logs)(?:$|[^a-z0-9_-])/.test(normalized)
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|||||||
@@ -71,6 +71,7 @@ type StreamPromptOptions = {
|
|||||||
traceId?: string;
|
traceId?: string;
|
||||||
projectId?: string;
|
projectId?: string;
|
||||||
signal?: AbortSignal;
|
signal?: AbortSignal;
|
||||||
|
workspaceRoot?: string;
|
||||||
write: (event: string, data: Record<string, unknown>) => void;
|
write: (event: string, data: Record<string, unknown>) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -157,6 +158,7 @@ export const streamPromptResponse = async ({
|
|||||||
traceId,
|
traceId,
|
||||||
projectId,
|
projectId,
|
||||||
signal,
|
signal,
|
||||||
|
workspaceRoot,
|
||||||
write,
|
write,
|
||||||
}: StreamPromptOptions): Promise<{
|
}: StreamPromptOptions): Promise<{
|
||||||
aborted: boolean;
|
aborted: boolean;
|
||||||
@@ -394,6 +396,11 @@ export const streamPromptResponse = async ({
|
|||||||
const permissionApproval = resolvePermissionApproval(
|
const permissionApproval = resolvePermissionApproval(
|
||||||
approvalMode,
|
approvalMode,
|
||||||
event.properties.permission,
|
event.properties.permission,
|
||||||
|
{
|
||||||
|
metadata: event.properties.metadata,
|
||||||
|
patterns: event.properties.patterns,
|
||||||
|
workspaceRoot: workspaceRoot ?? process.cwd(),
|
||||||
|
},
|
||||||
);
|
);
|
||||||
logDevelopmentDebug("permission request received", {
|
logDevelopmentDebug("permission request received", {
|
||||||
...debugContext,
|
...debugContext,
|
||||||
@@ -405,20 +412,25 @@ export const streamPromptResponse = async ({
|
|||||||
emitProgress({
|
emitProgress({
|
||||||
id: `permission-${event.properties.id}`,
|
id: `permission-${event.properties.id}`,
|
||||||
phase: "permission",
|
phase: "permission",
|
||||||
status: permissionApproval.autoApprove ? "completed" : "running",
|
status: permissionApproval.autoReject
|
||||||
|
? "error"
|
||||||
|
: permissionApproval.autoApprove
|
||||||
|
? "completed"
|
||||||
|
: "running",
|
||||||
title: permissionApproval.title,
|
title: permissionApproval.title,
|
||||||
detail: permissionApproval.detail ?? buildPermissionDetail(event),
|
detail: permissionApproval.detail ?? buildPermissionDetail(event),
|
||||||
});
|
});
|
||||||
if (permissionApproval.autoApprove) {
|
if (permissionApproval.autoApprove || permissionApproval.autoReject) {
|
||||||
|
const reply = permissionApproval.autoReject ? "reject" : "once";
|
||||||
await runtime.replyPermission({
|
await runtime.replyPermission({
|
||||||
requestId: event.properties.id,
|
requestId: event.properties.id,
|
||||||
sessionId,
|
sessionId,
|
||||||
reply: "once",
|
reply,
|
||||||
});
|
});
|
||||||
write("permission_response", {
|
write("permission_response", {
|
||||||
session_id: clientSessionId,
|
session_id: clientSessionId,
|
||||||
request_id: event.properties.id,
|
request_id: event.properties.id,
|
||||||
reply: "once" satisfies PermissionReply,
|
reply: reply satisfies PermissionReply,
|
||||||
});
|
});
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -440,6 +452,11 @@ export const streamPromptResponse = async ({
|
|||||||
const permissionApproval = resolvePermissionApproval(
|
const permissionApproval = resolvePermissionApproval(
|
||||||
approvalMode,
|
approvalMode,
|
||||||
event.properties.action,
|
event.properties.action,
|
||||||
|
{
|
||||||
|
metadata: event.properties.metadata,
|
||||||
|
patterns: event.properties.resources,
|
||||||
|
workspaceRoot: workspaceRoot ?? process.cwd(),
|
||||||
|
},
|
||||||
);
|
);
|
||||||
logDevelopmentDebug("permission v2 request received", {
|
logDevelopmentDebug("permission v2 request received", {
|
||||||
...debugContext,
|
...debugContext,
|
||||||
@@ -451,20 +468,25 @@ export const streamPromptResponse = async ({
|
|||||||
emitProgress({
|
emitProgress({
|
||||||
id: `permission-${event.properties.id}`,
|
id: `permission-${event.properties.id}`,
|
||||||
phase: "permission",
|
phase: "permission",
|
||||||
status: permissionApproval.autoApprove ? "completed" : "running",
|
status: permissionApproval.autoReject
|
||||||
|
? "error"
|
||||||
|
: permissionApproval.autoApprove
|
||||||
|
? "completed"
|
||||||
|
: "running",
|
||||||
title: permissionApproval.title,
|
title: permissionApproval.title,
|
||||||
detail: permissionApproval.detail ?? buildPermissionV2Detail(event),
|
detail: permissionApproval.detail ?? buildPermissionV2Detail(event),
|
||||||
});
|
});
|
||||||
if (permissionApproval.autoApprove) {
|
if (permissionApproval.autoApprove || permissionApproval.autoReject) {
|
||||||
|
const reply = permissionApproval.autoReject ? "reject" : "once";
|
||||||
await runtime.replyPermission({
|
await runtime.replyPermission({
|
||||||
requestId: event.properties.id,
|
requestId: event.properties.id,
|
||||||
sessionId,
|
sessionId,
|
||||||
reply: "once",
|
reply,
|
||||||
});
|
});
|
||||||
write("permission_response", {
|
write("permission_response", {
|
||||||
session_id: clientSessionId,
|
session_id: clientSessionId,
|
||||||
request_id: event.properties.id,
|
request_id: event.properties.id,
|
||||||
reply: "once" satisfies PermissionReply,
|
reply: reply satisfies PermissionReply,
|
||||||
});
|
});
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
+87
-5
@@ -2,11 +2,18 @@ import {
|
|||||||
createOpencode,
|
createOpencode,
|
||||||
type OpencodeClient,
|
type OpencodeClient,
|
||||||
} from "@opencode-ai/sdk/v2";
|
} from "@opencode-ai/sdk/v2";
|
||||||
|
import { randomUUID } from "node:crypto";
|
||||||
import { existsSync, readFileSync } from "node:fs";
|
import { existsSync, readFileSync } from "node:fs";
|
||||||
|
import { chmod, mkdir, rmdir } from "node:fs/promises";
|
||||||
import { resolve } from "node:path";
|
import { resolve } from "node:path";
|
||||||
|
|
||||||
import { config } from "../config.js";
|
import { config } from "../config.js";
|
||||||
import { logger } from "../logger.js";
|
import { logger } from "../logger.js";
|
||||||
|
import { ensureDirectory } from "../utils/fileStore.js";
|
||||||
|
import {
|
||||||
|
cleanupExpiredToolOutputs,
|
||||||
|
resolveOpencodeToolOutputDirectory,
|
||||||
|
} from "./opencodeToolOutputCleanup.js";
|
||||||
|
|
||||||
const isDevelopmentDebugLoggingEnabled = process.env.NODE_ENV === "development";
|
const isDevelopmentDebugLoggingEnabled = process.env.NODE_ENV === "development";
|
||||||
|
|
||||||
@@ -46,6 +53,7 @@ const getRuntimeMessageId = (message: RuntimeMessage) => message.info.id;
|
|||||||
export class OpencodeRuntimeAdapter {
|
export class OpencodeRuntimeAdapter {
|
||||||
private clientPromise: Promise<OpencodeClient> | null = null;
|
private clientPromise: Promise<OpencodeClient> | null = null;
|
||||||
private closeServer: (() => void) | null = null;
|
private closeServer: (() => void) | null = null;
|
||||||
|
private toolOutputCleanupTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
|
|
||||||
async ensureClient(): Promise<OpencodeClient> {
|
async ensureClient(): Promise<OpencodeClient> {
|
||||||
if (!this.clientPromise) {
|
if (!this.clientPromise) {
|
||||||
@@ -121,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 client = await this.ensureClient();
|
||||||
const response = await client.session.create({
|
if (!options.conversationWorkspace) {
|
||||||
title,
|
const response = await client.session.create({ title });
|
||||||
});
|
return requireData(response.data, "session.create");
|
||||||
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) {
|
async sendPrompt(sessionId: string, text: string) {
|
||||||
@@ -380,12 +422,18 @@ export class OpencodeRuntimeAdapter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async dispose(): Promise<void> {
|
async dispose(): Promise<void> {
|
||||||
|
if (this.toolOutputCleanupTimer) {
|
||||||
|
clearInterval(this.toolOutputCleanupTimer);
|
||||||
|
this.toolOutputCleanupTimer = null;
|
||||||
|
}
|
||||||
this.closeServer?.();
|
this.closeServer?.();
|
||||||
this.closeServer = null;
|
this.closeServer = null;
|
||||||
this.clientPromise = null;
|
this.clientPromise = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async bootstrapClient(): Promise<OpencodeClient> {
|
private async bootstrapClient(): Promise<OpencodeClient> {
|
||||||
|
await this.cleanupToolOutputs();
|
||||||
|
|
||||||
// embedded 模式下,把服务内工具桥地址注入到 opencode 进程环境里,
|
// embedded 模式下,把服务内工具桥地址注入到 opencode 进程环境里,
|
||||||
// 这样 .opencode/tools 下的自定义工具可以回调本服务。
|
// 这样 .opencode/tools 下的自定义工具可以回调本服务。
|
||||||
process.env.TJWATER_AGENT_INTERNAL_BASE_URL = `http://127.0.0.1:${config.PORT}`;
|
process.env.TJWATER_AGENT_INTERNAL_BASE_URL = `http://127.0.0.1:${config.PORT}`;
|
||||||
@@ -436,9 +484,39 @@ export class OpencodeRuntimeAdapter {
|
|||||||
this.closeServer = () => {
|
this.closeServer = () => {
|
||||||
runtime.server.close();
|
runtime.server.close();
|
||||||
};
|
};
|
||||||
|
this.startToolOutputCleanupLoop();
|
||||||
|
|
||||||
return runtime.client;
|
return runtime.client;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async cleanupToolOutputs(): Promise<void> {
|
||||||
|
const directory = resolveOpencodeToolOutputDirectory();
|
||||||
|
const ttlMs = config.RESULT_REF_TTL_HOURS * 60 * 60 * 1000;
|
||||||
|
try {
|
||||||
|
const result = await cleanupExpiredToolOutputs(directory, ttlMs);
|
||||||
|
if (result.removed > 0) {
|
||||||
|
logger.info(
|
||||||
|
{ directory, ...result },
|
||||||
|
"removed expired opencode tool output files",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn(
|
||||||
|
{ err: error, directory },
|
||||||
|
"failed to clean expired opencode tool output files",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private startToolOutputCleanupLoop(): void {
|
||||||
|
if (this.toolOutputCleanupTimer) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.toolOutputCleanupTimer = setInterval(() => {
|
||||||
|
void this.cleanupToolOutputs();
|
||||||
|
}, config.RESULT_REF_CLEANUP_INTERVAL_MS);
|
||||||
|
this.toolOutputCleanupTimer.unref();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const opencodeRuntime = new OpencodeRuntimeAdapter();
|
export const opencodeRuntime = new OpencodeRuntimeAdapter();
|
||||||
@@ -448,6 +526,10 @@ function buildOpencodeConfig(): Record<string, unknown> {
|
|||||||
deepMerge(readProjectOpencodeConfig(), readEnvOpencodeConfig()),
|
deepMerge(readProjectOpencodeConfig(), readEnvOpencodeConfig()),
|
||||||
{
|
{
|
||||||
model: config.OPENCODE_MODEL,
|
model: config.OPENCODE_MODEL,
|
||||||
|
tool_output: {
|
||||||
|
max_bytes: config.MAX_INLINE_RESULT_BYTES,
|
||||||
|
max_lines: 2000,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { readdir, rm, stat } from "node:fs/promises";
|
||||||
|
import { homedir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
export type ToolOutputCleanupResult = {
|
||||||
|
removed: number;
|
||||||
|
scanned: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const resolveOpencodeToolOutputDirectory = (): string => {
|
||||||
|
const dataRoot = process.env.XDG_DATA_HOME?.trim() || join(homedir(), ".local", "share");
|
||||||
|
return join(dataRoot, "opencode", "tool-output");
|
||||||
|
};
|
||||||
|
|
||||||
|
export const cleanupExpiredToolOutputs = async (
|
||||||
|
directory: string,
|
||||||
|
ttlMs: number,
|
||||||
|
now = Date.now(),
|
||||||
|
): Promise<ToolOutputCleanupResult> => {
|
||||||
|
if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
|
||||||
|
throw new Error("tool output cleanup ttlMs must be a positive number");
|
||||||
|
}
|
||||||
|
|
||||||
|
let entries;
|
||||||
|
try {
|
||||||
|
entries = await readdir(directory, { withFileTypes: true });
|
||||||
|
} catch (error) {
|
||||||
|
if (isNodeError(error, "ENOENT")) {
|
||||||
|
return { removed: 0, scanned: 0 };
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
let removed = 0;
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (!entry.isFile() || !entry.name.startsWith("tool_")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const path = join(directory, entry.name);
|
||||||
|
try {
|
||||||
|
const file = await stat(path);
|
||||||
|
if (now - file.mtimeMs <= ttlMs) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
await rm(path);
|
||||||
|
removed += 1;
|
||||||
|
} catch (error) {
|
||||||
|
if (!isNodeError(error, "ENOENT")) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { removed, scanned: entries.length };
|
||||||
|
};
|
||||||
|
|
||||||
|
const isNodeError = (error: unknown, code: string): error is NodeJS.ErrnoException =>
|
||||||
|
error instanceof Error && "code" in error && error.code === code;
|
||||||
@@ -15,6 +15,7 @@ export type RuntimeSessionContext = {
|
|||||||
sessionId: string;
|
sessionId: string;
|
||||||
tokenExpiresAt?: string;
|
tokenExpiresAt?: string;
|
||||||
traceId: string;
|
traceId: string;
|
||||||
|
workspaceDirectory?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const contexts = new Map<string, RuntimeSessionContext>();
|
const contexts = new Map<string, RuntimeSessionContext>();
|
||||||
|
|||||||
+21
-11
@@ -233,7 +233,8 @@ app.post("/internal/tools/tjwater-cli-call", async (req, res) => {
|
|||||||
executeCliCommand(activeContext, command, timeoutSec, {
|
executeCliCommand(activeContext, command, timeoutSec, {
|
||||||
apiBaseUrl: config.TJWATER_API_BASE_URL,
|
apiBaseUrl: config.TJWATER_API_BASE_URL,
|
||||||
cliPath: config.TJWATER_CLI_PATH,
|
cliPath: config.TJWATER_CLI_PATH,
|
||||||
maxOutputBytes: config.MAX_INLINE_RESULT_BYTES,
|
maxStderrBytes: config.MAX_CLI_STDERR_BYTES,
|
||||||
|
maxStdoutBytes: config.MAX_CLI_OUTPUT_BYTES,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -278,7 +279,7 @@ app.post("/internal/tools/tjwater-cli-call", async (req, res) => {
|
|||||||
summary: "CLI 输出超过安全限制",
|
summary: "CLI 输出超过安全限制",
|
||||||
error: {
|
error: {
|
||||||
code: "OUTPUT_LIMIT_EXCEEDED",
|
code: "OUTPUT_LIMIT_EXCEEDED",
|
||||||
message: `${result.exceededStream ?? "output"} exceeded ${config.MAX_INLINE_RESULT_BYTES} bytes`,
|
message: `${result.exceededStream ?? "output"} exceeded ${config.MAX_CLI_OUTPUT_BYTES} bytes`,
|
||||||
retryable: false,
|
retryable: false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -307,16 +308,17 @@ app.post("/internal/tools/tjwater-cli-call", async (req, res) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
if (result.stdout.trim()) {
|
||||||
res.json(JSON.parse(result.stdout));
|
res.status(200).type("application/json").send(result.stdout);
|
||||||
} catch {
|
return;
|
||||||
res.json({
|
|
||||||
ok: true,
|
|
||||||
schema_version: "tjwater-cli/v1",
|
|
||||||
raw: result.stdout,
|
|
||||||
stderr: result.stderr || undefined,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
res.json({
|
||||||
|
ok: true,
|
||||||
|
schema_version: "tjwater-cli/v1",
|
||||||
|
raw: "",
|
||||||
|
stderr: result.stderr || undefined,
|
||||||
|
stderr_truncated: result.stderrTruncated || undefined,
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
app.post("/internal/tools/store-render-ref", async (req, res) => {
|
app.post("/internal/tools/store-render-ref", async (req, res) => {
|
||||||
@@ -340,6 +342,13 @@ app.post("/internal/tools/store-render-ref", async (req, res) => {
|
|||||||
res.status(400).json({ message: "file_path is required" });
|
res.status(400).json({ message: "file_path is required" });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (!context.workspaceDirectory) {
|
||||||
|
res.status(400).json({
|
||||||
|
message: "conversation workspace is required",
|
||||||
|
detail: "create a new conversation before importing render data",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const record = await resultReferenceResolver.registerRenderPayloadFile(filePath, {
|
const record = await resultReferenceResolver.registerRenderPayloadFile(filePath, {
|
||||||
@@ -350,6 +359,7 @@ app.post("/internal/tools/store-render-ref", async (req, res) => {
|
|||||||
sessionId: context.clientSessionId,
|
sessionId: context.clientSessionId,
|
||||||
source: RESULT_REFERENCE_SOURCE.agentGenerated,
|
source: RESULT_REFERENCE_SOURCE.agentGenerated,
|
||||||
traceId: context.traceId,
|
traceId: context.traceId,
|
||||||
|
workspaceDirectory: context.workspaceDirectory,
|
||||||
});
|
});
|
||||||
res.json({
|
res.json({
|
||||||
ok: true,
|
ok: true,
|
||||||
|
|||||||
@@ -21,7 +21,8 @@ const context: RuntimeSessionContext = {
|
|||||||
const run = (
|
const run = (
|
||||||
command: string,
|
command: string,
|
||||||
options: {
|
options: {
|
||||||
maxOutputBytes?: number;
|
maxStderrBytes?: number;
|
||||||
|
maxStdoutBytes?: number;
|
||||||
terminationGraceMs?: number;
|
terminationGraceMs?: number;
|
||||||
timeoutSec?: number;
|
timeoutSec?: number;
|
||||||
} = {},
|
} = {},
|
||||||
@@ -29,13 +30,14 @@ const run = (
|
|||||||
executeCliCommand(context, command, options.timeoutSec ?? 1, {
|
executeCliCommand(context, command, options.timeoutSec ?? 1, {
|
||||||
apiBaseUrl: "http://127.0.0.1:8000",
|
apiBaseUrl: "http://127.0.0.1:8000",
|
||||||
cliPath,
|
cliPath,
|
||||||
maxOutputBytes: options.maxOutputBytes ?? 64,
|
maxStderrBytes: options.maxStderrBytes ?? 8,
|
||||||
|
maxStdoutBytes: options.maxStdoutBytes ?? 64,
|
||||||
terminationGraceMs: options.terminationGraceMs ?? 20,
|
terminationGraceMs: options.terminationGraceMs ?? 20,
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("executeCliCommand", () => {
|
describe("executeCliCommand", () => {
|
||||||
test("accepts output at the byte limit", async () => {
|
test("accepts output at the byte limit", async () => {
|
||||||
await expect(run("stdout 123456", { maxOutputBytes: 6 })).resolves.toMatchObject({
|
await expect(run("stdout 123456", { maxStdoutBytes: 6 })).resolves.toMatchObject({
|
||||||
outcome: "completed",
|
outcome: "completed",
|
||||||
exitCode: 0,
|
exitCode: 0,
|
||||||
status: 200,
|
status: 200,
|
||||||
@@ -43,8 +45,16 @@ describe("executeCliCommand", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("does not treat the OpenCode 12000-byte inline threshold as a CLI limit", async () => {
|
||||||
|
const stdout = "x".repeat(12_001);
|
||||||
|
const result = await run(`stdout ${stdout}`, { maxStdoutBytes: 128 * 1024 * 1024 });
|
||||||
|
|
||||||
|
expect(result.outcome).toBe("completed");
|
||||||
|
expect(result.stdout).toBe(stdout);
|
||||||
|
});
|
||||||
|
|
||||||
test("rejects multibyte output above the byte limit without returning a partial body", async () => {
|
test("rejects multibyte output above the byte limit without returning a partial body", async () => {
|
||||||
await expect(run("stdout 水水", { maxOutputBytes: 5 })).resolves.toMatchObject({
|
await expect(run("stdout 水水", { maxStdoutBytes: 5 })).resolves.toMatchObject({
|
||||||
outcome: "output_limit",
|
outcome: "output_limit",
|
||||||
exceededStream: "stdout",
|
exceededStream: "stdout",
|
||||||
status: 502,
|
status: 502,
|
||||||
@@ -53,13 +63,16 @@ describe("executeCliCommand", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
test("limits stderr independently", async () => {
|
test("truncates stderr independently without terminating a successful command", async () => {
|
||||||
await expect(run("stderr 1234567", { maxOutputBytes: 6 })).resolves.toMatchObject({
|
await expect(
|
||||||
outcome: "output_limit",
|
run("stderr-success 123456789", { maxStderrBytes: 6 }),
|
||||||
exceededStream: "stderr",
|
).resolves.toMatchObject({
|
||||||
status: 502,
|
outcome: "completed",
|
||||||
stderr: "",
|
exitCode: 0,
|
||||||
stdout: "",
|
status: 200,
|
||||||
|
stderr: "123456",
|
||||||
|
stderrTruncated: true,
|
||||||
|
stdout: '{"ok":true}',
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -94,7 +107,8 @@ describe("executeCliCommand", () => {
|
|||||||
executeCliCommand(largeContext, "ignore-term", 0.25, {
|
executeCliCommand(largeContext, "ignore-term", 0.25, {
|
||||||
apiBaseUrl: "http://127.0.0.1:8000",
|
apiBaseUrl: "http://127.0.0.1:8000",
|
||||||
cliPath,
|
cliPath,
|
||||||
maxOutputBytes: 64,
|
maxStderrBytes: 8,
|
||||||
|
maxStdoutBytes: 64,
|
||||||
terminationGraceMs: 20,
|
terminationGraceMs: 20,
|
||||||
}),
|
}),
|
||||||
).resolves.toMatchObject({
|
).resolves.toMatchObject({
|
||||||
@@ -114,7 +128,8 @@ describe("executeCliCommand", () => {
|
|||||||
executeCliCommand(largeContext, "closed-stdin", 1, {
|
executeCliCommand(largeContext, "closed-stdin", 1, {
|
||||||
apiBaseUrl: "http://127.0.0.1:8000",
|
apiBaseUrl: "http://127.0.0.1:8000",
|
||||||
cliPath,
|
cliPath,
|
||||||
maxOutputBytes: 64,
|
maxStderrBytes: 8,
|
||||||
|
maxStdoutBytes: 64,
|
||||||
terminationGraceMs: 20,
|
terminationGraceMs: 20,
|
||||||
}),
|
}),
|
||||||
).rejects.toBeInstanceOf(Error);
|
).rejects.toBeInstanceOf(Error);
|
||||||
|
|||||||
Vendored
+6
@@ -15,6 +15,12 @@ if (command === "stderr") {
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (command === "stderr-success") {
|
||||||
|
process.stderr.write(value);
|
||||||
|
process.stdout.write('{"ok":true}');
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
if (command === "term") {
|
if (command === "term") {
|
||||||
process.on("SIGTERM", () => {
|
process.on("SIGTERM", () => {
|
||||||
setTimeout(() => process.exit(0), 30);
|
setTimeout(() => process.exit(0), 30);
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
|
import { afterEach, beforeEach, describe, expect, it } from "bun:test";
|
||||||
import { mkdtemp, rm, stat, writeFile } from "node:fs/promises";
|
import { mkdir, mkdtemp, rm, stat, symlink, writeFile } from "node:fs/promises";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
|
|
||||||
@@ -12,13 +12,18 @@ import {
|
|||||||
|
|
||||||
describe("ResultReferenceResolver", () => {
|
describe("ResultReferenceResolver", () => {
|
||||||
let tempDir: string;
|
let tempDir: string;
|
||||||
|
let importRoot: string;
|
||||||
|
let conversationWorkspace: string;
|
||||||
let store: ResultReferenceStore;
|
let store: ResultReferenceStore;
|
||||||
let resolver: ResultReferenceResolver;
|
let resolver: ResultReferenceResolver;
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
tempDir = await mkdtemp(join(tmpdir(), "tjwater-result-ref-"));
|
tempDir = await mkdtemp(join(tmpdir(), "tjwater-result-ref-"));
|
||||||
store = new ResultReferenceStore(tempDir, 60_000);
|
importRoot = join(tempDir, "conversation-workspaces");
|
||||||
resolver = new ResultReferenceResolver(store, tempDir, 1024 * 1024);
|
conversationWorkspace = join(importRoot, "conversation-1");
|
||||||
|
await mkdir(conversationWorkspace, { recursive: true });
|
||||||
|
store = new ResultReferenceStore(join(tempDir, "refs"), 60_000);
|
||||||
|
resolver = new ResultReferenceResolver(store, importRoot, 1024 * 1024);
|
||||||
await store.initialize();
|
await store.initialize();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -127,7 +132,7 @@ describe("ResultReferenceResolver", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("registers render refs from local wrapper files and normalizes payloads", async () => {
|
it("registers render refs from local wrapper files and normalizes payloads", async () => {
|
||||||
const filePath = join(tempDir, "render-wrapper.json");
|
const filePath = join(conversationWorkspace, "render-wrapper.json");
|
||||||
await writeFile(
|
await writeFile(
|
||||||
filePath,
|
filePath,
|
||||||
JSON.stringify(
|
JSON.stringify(
|
||||||
@@ -166,6 +171,7 @@ describe("ResultReferenceResolver", () => {
|
|||||||
sessionId: "session-3",
|
sessionId: "session-3",
|
||||||
source: RESULT_REFERENCE_SOURCE.agentGenerated,
|
source: RESULT_REFERENCE_SOURCE.agentGenerated,
|
||||||
traceId: "trace-3",
|
traceId: "trace-3",
|
||||||
|
workspaceDirectory: conversationWorkspace,
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(record.kind).toBe(RESULT_REFERENCE_KIND.renderJunctionsPayload);
|
expect(record.kind).toBe(RESULT_REFERENCE_KIND.renderJunctionsPayload);
|
||||||
@@ -218,6 +224,7 @@ describe("ResultReferenceResolver", () => {
|
|||||||
sessionId: "session-4",
|
sessionId: "session-4",
|
||||||
source: RESULT_REFERENCE_SOURCE.agentGenerated,
|
source: RESULT_REFERENCE_SOURCE.agentGenerated,
|
||||||
traceId: "trace-4",
|
traceId: "trace-4",
|
||||||
|
workspaceDirectory: outsideDir,
|
||||||
}),
|
}),
|
||||||
).rejects.toThrow("RESULT_REF_IMPORT_DIR");
|
).rejects.toThrow("RESULT_REF_IMPORT_DIR");
|
||||||
} finally {
|
} finally {
|
||||||
@@ -226,9 +233,9 @@ describe("ResultReferenceResolver", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("rejects oversized render payload files before parsing", async () => {
|
it("rejects oversized render payload files before parsing", async () => {
|
||||||
const filePath = join(tempDir, "oversized.json");
|
const filePath = join(conversationWorkspace, "oversized.json");
|
||||||
await writeFile(filePath, "x".repeat(128), "utf8");
|
await writeFile(filePath, "x".repeat(128), "utf8");
|
||||||
const sizeLimitedResolver = new ResultReferenceResolver(store, tempDir, 64);
|
const sizeLimitedResolver = new ResultReferenceResolver(store, importRoot, 64);
|
||||||
|
|
||||||
await expect(
|
await expect(
|
||||||
sizeLimitedResolver.registerRenderPayloadFile(filePath, {
|
sizeLimitedResolver.registerRenderPayloadFile(filePath, {
|
||||||
@@ -238,8 +245,65 @@ describe("ResultReferenceResolver", () => {
|
|||||||
sessionId: "session-5",
|
sessionId: "session-5",
|
||||||
source: RESULT_REFERENCE_SOURCE.agentGenerated,
|
source: RESULT_REFERENCE_SOURCE.agentGenerated,
|
||||||
traceId: "trace-5",
|
traceId: "trace-5",
|
||||||
|
workspaceDirectory: conversationWorkspace,
|
||||||
}),
|
}),
|
||||||
).rejects.toThrow("RESULT_REF_IMPORT_MAX_BYTES");
|
).rejects.toThrow("RESULT_REF_IMPORT_MAX_BYTES");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("rejects render payload files owned by another conversation workspace", async () => {
|
||||||
|
const otherWorkspace = join(importRoot, "conversation-2");
|
||||||
|
await mkdir(otherWorkspace);
|
||||||
|
const filePath = join(otherWorkspace, "render-wrapper.json");
|
||||||
|
await writeFile(
|
||||||
|
filePath,
|
||||||
|
JSON.stringify({
|
||||||
|
metadata: {},
|
||||||
|
location: { file_path: filePath },
|
||||||
|
data: { node_area_map: { J1: "DMA-1" } },
|
||||||
|
}),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
resolver.registerRenderPayloadFile(filePath, {
|
||||||
|
actorKey: "actor-6",
|
||||||
|
clientSessionId: "client-6",
|
||||||
|
projectKey: "project-key-6",
|
||||||
|
sessionId: "session-6",
|
||||||
|
source: RESULT_REFERENCE_SOURCE.agentGenerated,
|
||||||
|
traceId: "trace-6",
|
||||||
|
workspaceDirectory: conversationWorkspace,
|
||||||
|
}),
|
||||||
|
).rejects.toThrow("current conversation workspace");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a conversation workspace that is itself a symbolic link", async () => {
|
||||||
|
const targetWorkspace = join(importRoot, "conversation-target");
|
||||||
|
const linkedWorkspace = join(importRoot, "conversation-linked");
|
||||||
|
await mkdir(targetWorkspace);
|
||||||
|
await symlink(targetWorkspace, linkedWorkspace, "dir");
|
||||||
|
const filePath = join(targetWorkspace, "render-wrapper.json");
|
||||||
|
await writeFile(
|
||||||
|
filePath,
|
||||||
|
JSON.stringify({
|
||||||
|
metadata: {},
|
||||||
|
location: { file_path: filePath },
|
||||||
|
data: { node_area_map: { J1: "DMA-1" } },
|
||||||
|
}),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
resolver.registerRenderPayloadFile(filePath, {
|
||||||
|
actorKey: "actor-7",
|
||||||
|
clientSessionId: "client-7",
|
||||||
|
projectKey: "project-key-7",
|
||||||
|
sessionId: "session-7",
|
||||||
|
source: RESULT_REFERENCE_SOURCE.agentGenerated,
|
||||||
|
traceId: "trace-7",
|
||||||
|
workspaceDirectory: linkedWorkspace,
|
||||||
|
}),
|
||||||
|
).rejects.toThrow("symbolic link");
|
||||||
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,7 @@
|
|||||||
import { describe, expect, it } from "bun:test";
|
import { describe, expect, it } from "bun:test";
|
||||||
|
import { mkdtemp, mkdir, rm, symlink } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { dirname, join } from "node:path";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
canAutoApprovePermission,
|
canAutoApprovePermission,
|
||||||
@@ -9,10 +12,100 @@ describe("permission approval policy", () => {
|
|||||||
it.each([
|
it.each([
|
||||||
"show_chart",
|
"show_chart",
|
||||||
"web_search",
|
"web_search",
|
||||||
|
"skill",
|
||||||
])("allows low-risk permission %s", (permission) => {
|
])("allows low-risk permission %s", (permission) => {
|
||||||
expect(canAutoApprovePermission(permission)).toBe(true);
|
expect(canAutoApprovePermission(permission)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("allows structured searches within the workspace", () => {
|
||||||
|
const workspaceRoot = process.cwd();
|
||||||
|
const context = {
|
||||||
|
workspaceRoot,
|
||||||
|
metadata: { path: join(workspaceRoot, "src"), include: "*.ts" },
|
||||||
|
patterns: ["*.ts"],
|
||||||
|
};
|
||||||
|
expect(canAutoApprovePermission("glob", context)).toBe(true);
|
||||||
|
expect(canAutoApprovePermission("grep", context)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("allows a glob with an explicit safe prefix from the workspace root", () => {
|
||||||
|
expect(
|
||||||
|
canAutoApprovePermission("glob", {
|
||||||
|
workspaceRoot: process.cwd(),
|
||||||
|
metadata: { path: process.cwd(), pattern: "src/**/*.ts" },
|
||||||
|
patterns: ["src/**/*.ts"],
|
||||||
|
}),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{ metadata: { path: dirname(process.cwd()) }, patterns: ["*"] },
|
||||||
|
{ metadata: { path: join(process.cwd(), ".local.env") }, patterns: ["*"] },
|
||||||
|
{ metadata: { path: join(process.cwd(), "data") }, patterns: ["*"] },
|
||||||
|
{ metadata: { path: join(process.cwd(), "src") }, patterns: ["../logs/**"] },
|
||||||
|
{ metadata: { path: process.cwd() }, patterns: ["**/*.env"] },
|
||||||
|
{ metadata: { path: process.cwd() }, patterns: ["**/*"] },
|
||||||
|
{ metadata: { path: join(process.cwd(), "src") }, patterns: [".[e]nv"] },
|
||||||
|
])("keeps protected or external searches interactive", (request) => {
|
||||||
|
expect(
|
||||||
|
canAutoApprovePermission("glob", {
|
||||||
|
workspaceRoot: process.cwd(),
|
||||||
|
...request,
|
||||||
|
}),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("keeps grep from the workspace root interactive", () => {
|
||||||
|
expect(
|
||||||
|
canAutoApprovePermission("grep", {
|
||||||
|
workspaceRoot: process.cwd(),
|
||||||
|
metadata: { path: process.cwd(), include: "*.ts" },
|
||||||
|
patterns: ["secret"],
|
||||||
|
}),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects a workspace symlink that resolves outside the workspace", async () => {
|
||||||
|
const workspaceRoot = await mkdtemp(join(tmpdir(), "permission-workspace-"));
|
||||||
|
const externalRoot = await mkdtemp(join(tmpdir(), "permission-external-"));
|
||||||
|
try {
|
||||||
|
await mkdir(join(externalRoot, "src"));
|
||||||
|
const linkedPath = join(workspaceRoot, "linked");
|
||||||
|
await symlink(join(externalRoot, "src"), linkedPath, "dir");
|
||||||
|
|
||||||
|
expect(
|
||||||
|
canAutoApprovePermission("grep", {
|
||||||
|
workspaceRoot,
|
||||||
|
metadata: { path: linkedPath, include: "*.ts" },
|
||||||
|
patterns: ["secret"],
|
||||||
|
}),
|
||||||
|
).toBe(false);
|
||||||
|
} finally {
|
||||||
|
await Promise.all([
|
||||||
|
rm(workspaceRoot, { force: true, recursive: true }),
|
||||||
|
rm(externalRoot, { force: true, recursive: true }),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects protected descendants below an otherwise safe search root", async () => {
|
||||||
|
const workspaceRoot = await mkdtemp(join(tmpdir(), "permission-descendant-"));
|
||||||
|
try {
|
||||||
|
const sourceRoot = join(workspaceRoot, "src");
|
||||||
|
await mkdir(join(sourceRoot, "data"), { recursive: true });
|
||||||
|
|
||||||
|
expect(
|
||||||
|
canAutoApprovePermission("grep", {
|
||||||
|
workspaceRoot,
|
||||||
|
metadata: { path: sourceRoot, include: "*.ts" },
|
||||||
|
patterns: ["secret"],
|
||||||
|
}),
|
||||||
|
).toBe(false);
|
||||||
|
} finally {
|
||||||
|
await rm(workspaceRoot, { force: true, recursive: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it.each([
|
it.each([
|
||||||
"bash",
|
"bash",
|
||||||
"edit",
|
"edit",
|
||||||
@@ -36,4 +129,42 @@ describe("permission approval policy", () => {
|
|||||||
title: "已按始终允许模式放行",
|
title: "已按始终允许模式放行",
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
"rm -rf ./target",
|
||||||
|
"rm -rf ./target",
|
||||||
|
"rm -Rf ./target",
|
||||||
|
"/bin/rm -rf ./target",
|
||||||
|
"command rm --force --recursive ./target",
|
||||||
|
"env LANG=C rm -r -f ./target",
|
||||||
|
"SAFE=1 rm -rf ./target",
|
||||||
|
"env -u HOME rm -rf ./target",
|
||||||
|
"r\"\"m -rf ./target",
|
||||||
|
"(rm -rf ./target)",
|
||||||
|
"! rm -rf ./target",
|
||||||
|
"npm test && rm --recursive --force ./target",
|
||||||
|
])("rejects direct recursive force removal in always mode: %s", (command) => {
|
||||||
|
expect(
|
||||||
|
resolvePermissionApproval("always", "bash", {
|
||||||
|
metadata: { command },
|
||||||
|
patterns: [command],
|
||||||
|
}),
|
||||||
|
).toMatchObject({
|
||||||
|
autoApprove: false,
|
||||||
|
autoReject: true,
|
||||||
|
title: "已拒绝递归强制删除",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(["rm tmp.txt", "rm -f tmp.txt", "rm -r tmp-dir", "echo 'rm -rf tmp'"])(
|
||||||
|
"keeps non-recursive or non-executed removal text available for confirmation: %s",
|
||||||
|
(command) => {
|
||||||
|
expect(
|
||||||
|
resolvePermissionApproval("always", "bash", {
|
||||||
|
metadata: { command },
|
||||||
|
patterns: [command],
|
||||||
|
}),
|
||||||
|
).toMatchObject({ autoApprove: false, autoReject: false });
|
||||||
|
},
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -435,6 +435,54 @@ describe("streamPromptResponse", () => {
|
|||||||
expect(events.some((item) => item.event === "permission_request")).toBe(false);
|
expect(events.some((item) => item.event === "permission_request")).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("rejects recursive force removal even in always mode", async () => {
|
||||||
|
const replies: Array<Record<string, unknown>> = [];
|
||||||
|
const runtime = {
|
||||||
|
subscribeEvents: async () =>
|
||||||
|
createEventStream([
|
||||||
|
{
|
||||||
|
type: "permission.asked",
|
||||||
|
properties: {
|
||||||
|
id: "perm-always-rm-rf",
|
||||||
|
sessionID: "runtime-session-1",
|
||||||
|
permission: "bash",
|
||||||
|
patterns: ["/bin/rm -rf ./target"],
|
||||||
|
metadata: { command: "/bin/rm -rf ./target" },
|
||||||
|
always: ["/bin/rm -rf ./target"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: "session.idle", properties: { sessionID: "runtime-session-1" } },
|
||||||
|
]),
|
||||||
|
prompt: async () => undefined,
|
||||||
|
messages: async () => [],
|
||||||
|
replyPermission: async (options: Record<string, unknown>) => replies.push(options),
|
||||||
|
} as unknown as OpencodeRuntimeAdapter;
|
||||||
|
const events: Array<{ event: string; data: Record<string, unknown> }> = [];
|
||||||
|
|
||||||
|
await streamPromptResponse({
|
||||||
|
runtime,
|
||||||
|
sessionId: "runtime-session-1",
|
||||||
|
clientSessionId: "client-session-1",
|
||||||
|
message: "delete recursively",
|
||||||
|
approvalMode: "always",
|
||||||
|
write: (event, data) => events.push({ event, data }),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(replies).toEqual([
|
||||||
|
{
|
||||||
|
requestId: "perm-always-rm-rf",
|
||||||
|
sessionId: "runtime-session-1",
|
||||||
|
reply: "reject",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
expect(events.some((item) => item.event === "permission_request")).toBe(false);
|
||||||
|
expect(events.find((item) => item.event === "permission_response")?.data).toEqual({
|
||||||
|
session_id: "client-session-1",
|
||||||
|
request_id: "perm-always-rm-rf",
|
||||||
|
reply: "reject",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it("forwards opencode v2 permission requests as SSE payloads", async () => {
|
it("forwards opencode v2 permission requests as SSE payloads", async () => {
|
||||||
const runtime = {
|
const runtime = {
|
||||||
subscribeEvents: async () =>
|
subscribeEvents: async () =>
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import { describe, expect, it } from "bun:test";
|
import { describe, expect, it } from "bun:test";
|
||||||
import { type OpencodeClient } from "@opencode-ai/sdk/v2";
|
import { type OpencodeClient } from "@opencode-ai/sdk/v2";
|
||||||
|
import { mkdtemp, readdir, rm, stat } from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join, relative } from "node:path";
|
||||||
|
|
||||||
import { config } from "../../src/config.js";
|
import { config } from "../../src/config.js";
|
||||||
import { OpencodeRuntimeAdapter } from "../../src/runtime/opencode.js";
|
import { OpencodeRuntimeAdapter } from "../../src/runtime/opencode.js";
|
||||||
@@ -87,6 +90,79 @@ describe("OpencodeRuntimeAdapter.ensureClient", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("OpencodeRuntimeAdapter.createSession", () => {
|
||||||
|
it("creates a real chat session inside a dedicated conversation workspace", async () => {
|
||||||
|
const workspaceRoot = await mkdtemp(join(tmpdir(), "tjwater-conversations-"));
|
||||||
|
const calls: Array<Record<string, unknown>> = [];
|
||||||
|
const client = {
|
||||||
|
session: {
|
||||||
|
create: async (input: Record<string, unknown>) => {
|
||||||
|
calls.push(input);
|
||||||
|
return {
|
||||||
|
data: {
|
||||||
|
id: "runtime-session-1",
|
||||||
|
directory: input.directory,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as unknown as OpencodeClient;
|
||||||
|
const runtime = Object.assign(Object.create(OpencodeRuntimeAdapter.prototype), {
|
||||||
|
clientPromise: null,
|
||||||
|
closeServer: null,
|
||||||
|
ensureClient: async () => client,
|
||||||
|
}) as OpencodeRuntimeAdapter;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const session = await runtime.createSession("chat", {
|
||||||
|
conversationWorkspace: true,
|
||||||
|
workspaceRoot,
|
||||||
|
});
|
||||||
|
const directory = String(calls[0]?.directory);
|
||||||
|
|
||||||
|
expect(relative(workspaceRoot, directory).startsWith("..")).toBe(false);
|
||||||
|
const workspaceStat = await stat(directory);
|
||||||
|
expect(workspaceStat.isDirectory()).toBe(true);
|
||||||
|
expect(workspaceStat.mode & 0o777).toBe(0o700);
|
||||||
|
expect(session.directory).toBe(directory);
|
||||||
|
expect(calls[0]?.permission).toEqual([
|
||||||
|
{ permission: "read", pattern: `${directory}/**`, action: "allow" },
|
||||||
|
{ permission: "edit", pattern: `${directory}/**`, action: "ask" },
|
||||||
|
]);
|
||||||
|
} finally {
|
||||||
|
await rm(workspaceRoot, { force: true, recursive: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("removes an empty conversation workspace when session creation fails", async () => {
|
||||||
|
const workspaceRoot = await mkdtemp(join(tmpdir(), "tjwater-conversations-"));
|
||||||
|
const client = {
|
||||||
|
session: {
|
||||||
|
create: async () => {
|
||||||
|
throw new Error("session creation failed");
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as unknown as OpencodeClient;
|
||||||
|
const runtime = Object.assign(Object.create(OpencodeRuntimeAdapter.prototype), {
|
||||||
|
clientPromise: null,
|
||||||
|
closeServer: null,
|
||||||
|
ensureClient: async () => client,
|
||||||
|
}) as OpencodeRuntimeAdapter;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(
|
||||||
|
runtime.createSession("chat", {
|
||||||
|
conversationWorkspace: true,
|
||||||
|
workspaceRoot,
|
||||||
|
}),
|
||||||
|
).rejects.toThrow("session creation failed");
|
||||||
|
expect(await readdir(workspaceRoot)).toEqual([]);
|
||||||
|
} finally {
|
||||||
|
await rm(workspaceRoot, { force: true, recursive: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("OpencodeRuntimeAdapter.warmup", () => {
|
describe("OpencodeRuntimeAdapter.warmup", () => {
|
||||||
it("initializes the project session and model tools before reporting ready", async () => {
|
it("initializes the project session and model tools before reporting ready", async () => {
|
||||||
const calls: string[] = [];
|
const calls: string[] = [];
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import { describe, expect, it } from "bun:test";
|
import { describe, expect, it } from "bun:test";
|
||||||
import { readFile } from "node:fs/promises";
|
import { readFile } from "node:fs/promises";
|
||||||
|
import storeRenderRef, {
|
||||||
|
resolveStoreRenderFilePath,
|
||||||
|
} from "../../.opencode/tools/store_render_ref.js";
|
||||||
|
|
||||||
describe("internal OpenCode permissions", () => {
|
describe("internal OpenCode permissions", () => {
|
||||||
it("keeps protected paths denied in every approval mode", async () => {
|
it("keeps protected paths denied in every approval mode", async () => {
|
||||||
@@ -23,8 +26,66 @@ describe("internal OpenCode permissions", () => {
|
|||||||
expect(edit?.["data/**"]).toBe("deny");
|
expect(edit?.["data/**"]).toBe("deny");
|
||||||
expect(edit?.["**/logs/**"]).toBe("deny");
|
expect(edit?.["**/logs/**"]).toBe("deny");
|
||||||
expect(bash?.["*"]).toBe("ask");
|
expect(bash?.["*"]).toBe("ask");
|
||||||
|
expect(bash?.["rm *"]).toBe("ask");
|
||||||
|
expect(bash?.["rm -rf *"]).toBe("deny");
|
||||||
|
expect(bash?.["rm -fr *"]).toBe("deny");
|
||||||
|
expect(bash?.["rm -r -f *"]).toBe("deny");
|
||||||
|
expect(bash?.["rm -f -r *"]).toBe("deny");
|
||||||
|
expect(bash?.["rm --recursive --force *"]).toBe("deny");
|
||||||
|
expect(bash?.["rm --force --recursive *"]).toBe("deny");
|
||||||
expect(bash?.["*.env*"]).toBe("deny");
|
expect(bash?.["*.env*"]).toBe("deny");
|
||||||
expect(bash?.["*data/*"]).toBe("deny");
|
expect(bash?.["*data/*"]).toBeUndefined();
|
||||||
expect(bash?.["*logs/*"]).toBe("deny");
|
expect(bash?.["*logs/*"]).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("store_render_ref arguments", () => {
|
||||||
|
it("accepts the observed camelCase alias without changing snake_case precedence", () => {
|
||||||
|
expect(
|
||||||
|
resolveStoreRenderFilePath({
|
||||||
|
filePath: "/app/data/conversation-workspaces/chat-1/partition.json",
|
||||||
|
}),
|
||||||
|
).toBe("/app/data/conversation-workspaces/chat-1/partition.json");
|
||||||
|
|
||||||
|
expect(
|
||||||
|
resolveStoreRenderFilePath({
|
||||||
|
file_path: "/app/data/conversation-workspaces/chat-1/preferred.json",
|
||||||
|
filePath: "/app/data/conversation-workspaces/chat-1/compatibility.json",
|
||||||
|
}),
|
||||||
|
).toBe("/app/data/conversation-workspaces/chat-1/preferred.json");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("forwards a camelCase compatibility argument as file_path", async () => {
|
||||||
|
const originalFetch = globalThis.fetch;
|
||||||
|
let requestBody: unknown;
|
||||||
|
globalThis.fetch = (async (
|
||||||
|
_input: RequestInfo | URL,
|
||||||
|
init?: RequestInit,
|
||||||
|
) => {
|
||||||
|
requestBody = JSON.parse(String(init?.body));
|
||||||
|
return new Response('{"render_ref":"res-test"}');
|
||||||
|
}) as unknown as typeof fetch;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const definition = storeRenderRef as unknown as {
|
||||||
|
args: Record<string, unknown>;
|
||||||
|
execute: (args: unknown, context: unknown) => Promise<unknown>;
|
||||||
|
};
|
||||||
|
expect(definition.args.filePath).toBeDefined();
|
||||||
|
await definition.execute(
|
||||||
|
{
|
||||||
|
reason: "regression test",
|
||||||
|
filePath: "/app/data/conversation-workspaces/chat-1/partition.json",
|
||||||
|
},
|
||||||
|
{ sessionID: "session-test" } as never,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
globalThis.fetch = originalFetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
expect(requestBody).toEqual({
|
||||||
|
session_id: "session-test",
|
||||||
|
file_path: "/app/data/conversation-workspaces/chat-1/partition.json",
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import {
|
||||||
|
lstat,
|
||||||
|
mkdir,
|
||||||
|
mkdtemp,
|
||||||
|
readFile,
|
||||||
|
rm,
|
||||||
|
stat,
|
||||||
|
symlink,
|
||||||
|
utimes,
|
||||||
|
writeFile,
|
||||||
|
} from "node:fs/promises";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
|
||||||
|
import { cleanupExpiredToolOutputs } from "../../src/runtime/opencodeToolOutputCleanup.js";
|
||||||
|
|
||||||
|
describe("cleanupExpiredToolOutputs", () => {
|
||||||
|
test("removes only expired regular tool output files", async () => {
|
||||||
|
const directory = await mkdtemp(join(tmpdir(), "opencode-tool-output-cleanup-"));
|
||||||
|
const expired = join(directory, "tool_expired");
|
||||||
|
const current = join(directory, "tool_current");
|
||||||
|
const unrelated = join(directory, "keep.txt");
|
||||||
|
const toolDirectory = join(directory, "tool_directory");
|
||||||
|
const toolSymlink = join(directory, "tool_symlink");
|
||||||
|
try {
|
||||||
|
await Promise.all([
|
||||||
|
writeFile(expired, "expired"),
|
||||||
|
writeFile(current, "current"),
|
||||||
|
writeFile(unrelated, "unrelated"),
|
||||||
|
mkdir(toolDirectory),
|
||||||
|
]);
|
||||||
|
await symlink(unrelated, toolSymlink);
|
||||||
|
const now = Date.now();
|
||||||
|
const old = new Date(now - 8 * 24 * 60 * 60 * 1000);
|
||||||
|
await utimes(expired, old, old);
|
||||||
|
|
||||||
|
const result = await cleanupExpiredToolOutputs(
|
||||||
|
directory,
|
||||||
|
7 * 24 * 60 * 60 * 1000,
|
||||||
|
now,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result).toEqual({ removed: 1, scanned: 5 });
|
||||||
|
await expect(stat(expired)).rejects.toMatchObject({ code: "ENOENT" });
|
||||||
|
expect(await readFile(current, "utf8")).toBe("current");
|
||||||
|
expect(await readFile(unrelated, "utf8")).toBe("unrelated");
|
||||||
|
expect((await stat(toolDirectory)).isDirectory()).toBe(true);
|
||||||
|
expect((await lstat(toolSymlink)).isSymbolicLink()).toBe(true);
|
||||||
|
} finally {
|
||||||
|
await rm(directory, { force: true, recursive: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("treats a missing tool output directory as empty", async () => {
|
||||||
|
const directory = join(tmpdir(), `missing-tool-output-${crypto.randomUUID()}`);
|
||||||
|
await expect(cleanupExpiredToolOutputs(directory, 1_000)).resolves.toEqual({
|
||||||
|
removed: 0,
|
||||||
|
scanned: 0,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -19,6 +19,7 @@ describe("runtime session context", () => {
|
|||||||
projectKey: "project-1",
|
projectKey: "project-1",
|
||||||
sessionId: "runtime-session-1",
|
sessionId: "runtime-session-1",
|
||||||
traceId: "trace-1",
|
traceId: "trace-1",
|
||||||
|
workspaceDirectory: "/app/data/conversation-workspaces/chat-session-1",
|
||||||
});
|
});
|
||||||
|
|
||||||
const runtimeContext = getRuntimeSessionContext("runtime-session-1");
|
const runtimeContext = getRuntimeSessionContext("runtime-session-1");
|
||||||
@@ -27,6 +28,9 @@ describe("runtime session context", () => {
|
|||||||
expect(runtimeContext?.clientSessionId).toBe("chat-session-1");
|
expect(runtimeContext?.clientSessionId).toBe("chat-session-1");
|
||||||
expect(runtimeContext?.network).toBe("fengyang");
|
expect(runtimeContext?.network).toBe("fengyang");
|
||||||
expect(runtimeContext?.sessionId).toBe("runtime-session-1");
|
expect(runtimeContext?.sessionId).toBe("runtime-session-1");
|
||||||
|
expect(runtimeContext?.workspaceDirectory).toBe(
|
||||||
|
"/app/data/conversation-workspaces/chat-session-1",
|
||||||
|
);
|
||||||
|
|
||||||
removeRuntimeSessionContext("runtime-session-1");
|
removeRuntimeSessionContext("runtime-session-1");
|
||||||
expect(getRuntimeSessionContext("runtime-session-1")).toBeNull();
|
expect(getRuntimeSessionContext("runtime-session-1")).toBeNull();
|
||||||
|
|||||||
Reference in New Issue
Block a user