Compare commits
35
Commits
v2.5.0
..
77ef1ec11c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
77ef1ec11c | ||
|
|
0234bc85e5 | ||
|
|
24d7f023ba | ||
|
|
d03d8ba95b | ||
|
|
10bf2f554b | ||
|
|
0ec9aec93e | ||
|
|
5959b4a674 | ||
|
|
4e1c1f36d0 | ||
|
|
a52b227d8b | ||
|
|
317397154e | ||
|
|
0f9cc241bb | ||
|
|
69e44c27ae | ||
|
|
469e801319 | ||
|
|
5b45368f58 | ||
|
|
a7eecdbe97 | ||
|
|
c7394dc45f | ||
|
|
8764fedabc | ||
|
|
29e4f6e6ea | ||
|
|
59994b688a | ||
|
|
50c53fd885 | ||
|
|
870033f26d | ||
|
|
c892703673 | ||
|
|
01757d4f4b | ||
|
|
c0488938ff | ||
|
|
20824dc42e | ||
|
|
419e3fc914 | ||
|
|
83644c09e7 | ||
|
|
d06cd6cedf | ||
|
|
4e97194b04 | ||
|
|
8ef4ec1ee4 | ||
|
|
2d5467203b | ||
|
|
80e9dcb0aa | ||
|
|
b5cfa36832 | ||
|
|
f451027729 | ||
|
|
8a5c8b1547 |
@@ -7,6 +7,9 @@ data/
|
||||
tasks/
|
||||
skills/deps/
|
||||
skills/*/.deps_installed
|
||||
# 本地端(local/):运行期产物与生成的配置都不入库(含密钥,见 local/README.md)
|
||||
local/.runtime/
|
||||
local/config.local.yml
|
||||
# officecli 二进制资产:skills/office/install.sh 运行期拉取,不进 git
|
||||
skills/office/bin/
|
||||
skills/**/__pycache__/
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
| `wxbot/` | 微信 iLink 协议调制解调器(多实例) | 独立容器 `agent-wxbot` |
|
||||
| `mcp/` | 同栈 MCP 服务:`web_search` / `image_task` / `video_task` / `asr` | 四个容器,仅内网 |
|
||||
| `skills/` | 目录式技能(`SKILL.md` + `run.py`/`run.sh`) | 运行时挂载,`skills/deps` 为依赖层 |
|
||||
| `local/` | **本地端启动器**:同一份代码跑在本机(不起 Docker / executor),`start.sh` 负责探测、装依赖、守护 | 独立于 compose,见 `docs/local-mode.md` |
|
||||
| `scripts/` | `init.sh` 生成 `.env` + 首次创建 `config.yml`(仅初始管理员);`init_host.sh` 裸机初始化 | 幂等,**不覆盖已有配置** |
|
||||
| `docs/` | 专题文档:`tool-design.md`(工具接口规范)、`OFFICE.md` | — |
|
||||
| `tasks/` | **运行时数据**:每个会话一个工作目录 | gitignore |
|
||||
|
||||
+17
-6
@@ -62,7 +62,7 @@ AGENT_CONFIG=./config.yml node server/server.js
|
||||
| `server/log.js` | 分级日志 `log.debug/info/warn/error(category, ...)` |
|
||||
| `server/balance.js` | 平台余额查询适配器(按 `platform.type` 分发) |
|
||||
| `server/version.js` | git commit/date:优先读 `version.json`(post-commit 钩子生成),宿主机有 git 时兜底 `git rev-parse`;页面版本号另外由 `routes/system.js` 的 `VERSION` 字面量决定 |
|
||||
| `server/templates/` | system prompt 模板、压缩/标题指令、profile prompt |
|
||||
| `server/templates/` | system prompt 模板、环境段(按部署形态二选一)、压缩/标题指令、profile prompt |
|
||||
|
||||
## 一次用户消息的生命周期
|
||||
|
||||
@@ -162,7 +162,7 @@ IM 用户在实时对话,回合中插话应当“当前这步跑完就插”
|
||||
|
||||
`buildMessages(session, language, mintUrl, profile)` 的输出顺序固定:
|
||||
|
||||
1. `system`:模板(`profile-default.txt` 或 profile 自定义 prompt)+ 技能清单段 + 语言指令;
|
||||
1. `system`:模板(`profile-default.txt` 或 profile 自定义 prompt)+ 环境段 + 技能清单段 + 语言指令;
|
||||
进程内按 `(profile, language)` 缓存,保证前缀缓存稳定。
|
||||
2. 画像快照(`sessions.profile_snapshot`,建会话/清空时冻结):作为首条 `user`。**不在 messages 表里**,
|
||||
压缩与归档碰不到它。
|
||||
@@ -223,10 +223,17 @@ IM 用户在实时对话,回合中插话应当“当前这步跑完就插”
|
||||
`disable` 连 `tools/list` 都不发。旧字段 `enable` 已废弃,`mode: silent` 已移除,
|
||||
出现即报配置错(不静默忽略)。
|
||||
- `executeTool(baseCtx, name, args)`:先查 `HANDLERS` 表,未命中再交给 MCP 注册表。
|
||||
`ctx = {sessionId, taskDir, run, cfg, db, vision}`;工具返回字符串,`read_file` 读图时返回
|
||||
`ctx = {sessionId, taskDir, workDir, run, cfg, db, vision}`;工具返回字符串,`read_file` 读图时返回
|
||||
`{text, image_rel}`(`text` 是结构化 JSON 回执,由 engine 转成 `image_ref` 块)。
|
||||
`workDir` = 会话手选的工作目录(本地端新建会话可选),空串时 `taskDir` 就是默认的
|
||||
`workspace_root/<会话id>`。
|
||||
- **路径沙箱**:所有路径经 `resolveInTask` 解析到 `taskDir` 内;`/tmp` 会被映射到
|
||||
`<taskDir>/.tmp`(与 executor 容器里 `/tmp` 的 bind 对齐)。符号链接越界一律拒绝。
|
||||
例外:`AGENT_FILE_SCOPE=workspace`(本地端 `local/start.sh` 注入)把业务工具的根放宽到
|
||||
`workspace_root`,且 `/tmp` 不重写、直接放行(本地 terminal 写的是真 `/tmp`);
|
||||
会话若手选了目录(`sessions.work_dir` 非空),业务工具与文件 API 的根都取那个真实目录
|
||||
(`fsRoot` 优先返回 `ctx.workDir`),且不再创建 `task-*` 子目录;
|
||||
路由层(文件 API / 公网短链 / data-page)与 `@会话` 仍按 `taskDir` 校验,不随之外扩。
|
||||
- **跨会话只读**:`@<session-id>/<rel>` 只允许 `list_directory`、`read_file`、`copy_path` 的
|
||||
`source_path`,且只限同一用户的会话。写侧显式拒绝——否则会造出字面 `@task-x` 目录。
|
||||
- `checkToolArgs` + `unwrapToolArgs`:前者做结构性预检并生成 `errAck`,后者按 schema 逐层剥掉
|
||||
@@ -238,8 +245,9 @@ IM 用户在实时对话,回合中插话应当“当前这步跑完就插”
|
||||
get/run 指认技能,`args` 仅 run 用;条件必填写不进 schema,由 `toolSkill` 校验并点名。
|
||||
`toolSkill` 在入口把旧字段名 `input_args` 归一化成 `args`,之后只走一条分派路径
|
||||
(曾有两条路径,其中一条只读 `input_args`,会静默丢参)。
|
||||
`input_schema.required` 在 `run` 前校验;相对路径参数按会话目录转绝对路径;入口一律用绝对路径
|
||||
(远端 cwd 是会话目录)。配了 executor 就走 `remote-exec`,否则本地 `spawn`。
|
||||
`input_schema.required` 在 `run` 前校验;相对路径参数按会话目录转绝对路径;入口一律用绝对路径,
|
||||
cwd 也一律是会话目录(本地 spawn 与远端一致,否则按 cwd 干活的技能会写到技能目录里)。
|
||||
配了 executor 就走 `remote-exec`,否则本地 `spawn`。
|
||||
模型可见的技能清单是 `listCallableSkills`(目录技能 + `mode=skill` 的 MCP 工具,同名时目录胜出);
|
||||
设置页的技能 API 仍只用 `listSkills`(按目录增删改),两者不要混用。
|
||||
mode=skill 的 MCP 技能在 `runSkill` 里位于 `absolutizeArgs` **之前**:直接 `mcp.callTool` 转发
|
||||
@@ -379,7 +387,10 @@ preview-proxy.mount(末尾兜底)
|
||||
|
||||
**改 prompt / profile**
|
||||
|
||||
- 默认 prompt:`templates/profile-default.txt`(`{APP_SKILLS_SECTION}` 占位技能清单)。
|
||||
- 默认 prompt:`templates/profile-default.txt`(`{APP_SKILLS_SECTION}` 占位技能清单,
|
||||
`{APP_ENV_SECTION}` 占位环境段)。
|
||||
- 环境段:`templates/env-server.txt`(executor 容器形态)/ `env-local.txt`(本机 spawn 形态),
|
||||
启动时按 `EXECUTOR_URL` 有无选定(`server.js` 的 `llm.setEnvMode`),改完重启。
|
||||
- 压缩/标题指令:`templates/prompt-compress.txt` / `prompt-title.txt`。
|
||||
- 自定义组合:`config.yml` 的 `model_profiles` + 模型的 `profile: <名>`;改完重启。
|
||||
|
||||
|
||||
Generated
+157
-157
File diff suppressed because it is too large
Load Diff
+9
-1
@@ -104,6 +104,12 @@ function createAuth(cfg) {
|
||||
let users = (cfg.auth && cfg.auth.users) || [];
|
||||
if (!users.length) {
|
||||
// 未启用认证 = 单用户自用:管理接口按「本机主人」放行,用户 CRUD 由 routes/users.js 自己拒绝。
|
||||
// /api/me 在关闭分支里也必须存在:前端靠它一次请求判定形态(auth:false = 未启用),
|
||||
// 若这里不注册,本地模式(无认证)下浏览器网络面板会永远挂着一条红色 404,
|
||||
// 也无法区分「路由不存在」和「cookie 失效」——后者才该跳登录页。
|
||||
router.get('/api/me', (req, res) => {
|
||||
res.json({ user: null, role: 'admin', model: '', auth: false });
|
||||
});
|
||||
return {
|
||||
enabled: false,
|
||||
middleware: (req, res, next) => next(),
|
||||
@@ -232,7 +238,9 @@ function createAuth(cfg) {
|
||||
// 与中间件同一解析顺序(cookie 优先),保证 /api/me 显示的用户与业务路由认定的用户一致
|
||||
const name = authUser(req);
|
||||
const row = name ? userRow(name) : null;
|
||||
res.json({ user: name, role: row ? row.role : '', model: row ? (row.model || '') : '' });
|
||||
// auth:true 让前端明确区分「启用了认证但当前无登录」(user:null → 跳登录)
|
||||
// 与「根本没启用认证」(auth:false → 单用户自用)这两种 user:null。
|
||||
res.json({ user: name, role: row ? row.role : '', model: row ? (row.model || '') : '', auth: true });
|
||||
});
|
||||
|
||||
// ----- 登录页 / 登出跳转 -----
|
||||
|
||||
@@ -231,6 +231,9 @@ function initDb(dbPath) {
|
||||
// 迁移:title_locked 用户手动重命名过标题(renameSession 置 1):显式留痕「名字是用户起的」,
|
||||
// 不得静默冲掉;清空会话时随标题一并复位(旧名字已文不对题)。
|
||||
if (!cols.some(c => c.name === 'title_locked')) db.exec("ALTER TABLE sessions ADD COLUMN title_locked INTEGER NOT NULL DEFAULT 0");
|
||||
// 迁移:会话级工作目录(本地桌面端新建会话时手选一个真实目录)。空串 = 沿用
|
||||
// workspace_root/<会话id>;服务器形态永远为空,行为与旧版完全一致(见 engine.taskDirOf)。
|
||||
if (!cols.some(c => c.name === 'work_dir')) db.exec("ALTER TABLE sessions ADD COLUMN work_dir TEXT NOT NULL DEFAULT ''");
|
||||
// 迁移:wechat_bindings 补 deep_think 列——微信端全局深度思考开关(routes/channel.js /think 读写,
|
||||
// 投递时作为既有 deepThink 参数的取值来源);默认 0=关(与 H5 按钮初始态一致,/think on 手动开)。
|
||||
// 旧库若曾按 DEFAULT 1 补过列(当时默认开,存量行都是默认值回填而非用户显式选择),
|
||||
|
||||
+82
-13
@@ -53,8 +53,41 @@ function genTaskId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
// 会话级工作目录:本地桌面端新建会话时可手选一个真实目录(DB 列 work_dir,见 db.js 迁移)。
|
||||
// 空串 = 沿用 workspace_root/<会话id>,服务器形态永远走这条,行为与 v2.5.0 完全一致。
|
||||
// 用缓存的 prepared statement:taskDirOf 在文件 API / 工具链里被高频调用,每次现 prepare 没必要。
|
||||
let stmtWorkDir = null;
|
||||
function sessionWorkDir(sessionId) {
|
||||
try {
|
||||
if (!stmtWorkDir) stmtWorkDir = db.prepare('SELECT work_dir FROM sessions WHERE id = ?');
|
||||
const row = stmtWorkDir.get(sessionId);
|
||||
return String((row && row.work_dir) || '');
|
||||
} catch (_) { return ''; }
|
||||
}
|
||||
|
||||
function taskDirOf(sessionId) {
|
||||
return path.join(cfg.workspace_root, sessionId);
|
||||
return sessionWorkDir(sessionId) || path.join(cfg.workspace_root, sessionId);
|
||||
}
|
||||
|
||||
// 校验并归一化「手选工作目录」:必须已存在的真实目录(不替用户 mkdir),且不能是根目录 /
|
||||
// 或平台数据目录——后者存着 SQLite(.agent.db)和 prompt dump,让会话目录指过去等于让 AI
|
||||
// 直接动运行数据库。用户主目录/Linux 根下子目录不拦(本地模式本来就没沙箱,README 已提示
|
||||
// 选专用目录),但选到根目录本身无意义。
|
||||
function normalizeWorkDir(input) {
|
||||
const raw = String(input || '').trim();
|
||||
if (!raw) return '';
|
||||
if (!path.isAbsolute(raw)) throw Object.assign(new Error('工作目录必须是绝对路径:' + raw), { status_code: 400 });
|
||||
let real;
|
||||
try { real = fs.realpathSync(raw); } catch (_) { throw Object.assign(new Error('工作目录不存在:' + raw), { status_code: 400 }); }
|
||||
let st;
|
||||
try { st = fs.statSync(real); } catch (_) { throw Object.assign(new Error('工作目录不可访问:' + raw), { status_code: 400 }); }
|
||||
if (!st.isDirectory()) throw Object.assign(new Error('不是目录:' + raw), { status_code: 400 });
|
||||
if (real === path.parse(real).root) throw Object.assign(new Error('不能把根目录作为工作目录'), { status_code: 400 });
|
||||
const dataRoot = String(cfg.data_root || '');
|
||||
if (dataRoot && (real === dataRoot || real.startsWith(dataRoot + path.sep))) {
|
||||
throw Object.assign(new Error('不能选择平台数据目录作为工作目录'), { status_code: 400 });
|
||||
}
|
||||
return real;
|
||||
}
|
||||
|
||||
function getSession(sessionId) {
|
||||
@@ -631,6 +664,29 @@ function cleanTitle(raw) {
|
||||
return t.slice(0, 60);
|
||||
}
|
||||
|
||||
// 读图回传上游有两条取图路,取决于「谁能访问这个 URL」:
|
||||
// - 服务器形态:签一条公网短链(/p/<id>),模型厂商的服务器来拉;
|
||||
// - 本地形态:core 监听在回环地址,厂商拉不到 127.0.0.1,改为把压缩后的图内联成 data URL
|
||||
// (llm.js 侧本来就接受这个形态——用户粘贴附件的 image_url 走的就是它)。
|
||||
// 只认 AGENT_IMAGE_INLINE=1(local/start.sh 注入):服务器不设 → 完全走原路径。
|
||||
const INLINE_IMAGE_MAX_BYTES = 1.5 * 1024 * 1024;
|
||||
const INLINE_IMAGE_MIME = {
|
||||
'.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png',
|
||||
'.webp': 'image/webp', '.gif': 'image/gif',
|
||||
};
|
||||
|
||||
function inlineImageDataUrl(abs) {
|
||||
if (String(process.env.AGENT_IMAGE_INLINE || '') !== '1') return null;
|
||||
const mime = INLINE_IMAGE_MIME[path.extname(abs).toLowerCase()];
|
||||
if (!mime) return null;
|
||||
try {
|
||||
// 上限按原文件字节算(base64 约 1.34 倍):超限宁可不发——llm 侧会照旧降级成
|
||||
// 「像素未送达」——也不把请求体顶爆(.imgcache 产物已压到长边 2000px,正常远低于上限)。
|
||||
if (fs.statSync(abs).size > INLINE_IMAGE_MAX_BYTES) return null;
|
||||
return 'data:' + mime + ';base64,' + fs.readFileSync(abs).toString('base64');
|
||||
} catch (_) { return null; }
|
||||
}
|
||||
|
||||
async function runLoopInner(sessionId, run) {
|
||||
let iter = 0;
|
||||
// 已纳入模型请求的最大消息 id;用于判断是否有尚未被回应的新 user 消息
|
||||
@@ -647,16 +703,21 @@ async function runLoopInner(sessionId, run) {
|
||||
// 且不传 tools,模型只能输出摘要文本。
|
||||
// 发送前为历史里的 image_ref 块现签公网外链(GET /p/<id>,同 mint_public_link):
|
||||
// 每次请求重签,回合内多轮迭代/重试永不过期;DB 只存几十字符的 rel,base64 不进库不进请求体。
|
||||
// base_url 未配/校验不过/mint 异常时返回 null,buildMessages 降级为文字占位。
|
||||
// base_url 未配/校验不过/mint 异常时返回 null,buildMessages 降级为文字占位;本地形态
|
||||
// 没有公网前缀时改走内联 data URL(同见 inlineImageDataUrl),厂商拉不到回环地址。
|
||||
// image_rel 可能是压缩无收益时直指的原文件:与 mint_public_link 同款 realpath 复核,
|
||||
// 防任务目录里指向外部的符号链接图片被签上公网。
|
||||
const mintImageUrl = (rel) => {
|
||||
const pl = cfg.public_link || {};
|
||||
if (!pl.base_url) return null;
|
||||
let dir, real;
|
||||
try {
|
||||
const dir = taskDirOf(sessionId);
|
||||
const real = fs.realpathSync(resolveInTask(dir, rel));
|
||||
dir = taskDirOf(sessionId);
|
||||
real = fs.realpathSync(resolveInTask(dir, rel));
|
||||
if (real !== dir && !real.startsWith(dir + path.sep)) return null;
|
||||
} catch (_) { return null; }
|
||||
// 符号链接复核先做完再分叉:内联形态同样不能让任务目录外的图出去(见 inlineImageDataUrl)。
|
||||
if (!pl.base_url) return inlineImageDataUrl(real);
|
||||
try {
|
||||
return pl.base_url + '/p/' + publicFiles.mint({ sessionId: sessionId, rel, ttlMs: pl.ttl_ms });
|
||||
} catch (_) { return null; }
|
||||
};
|
||||
@@ -842,7 +903,7 @@ async function runLoopInner(sessionId, run) {
|
||||
isError = true;
|
||||
} else {
|
||||
try {
|
||||
output = await executeTool({ sessionId, taskDir: taskDirOf(sessionId), run, cfg, db, vision,
|
||||
output = await executeTool({ sessionId, taskDir: taskDirOf(sessionId), workDir: sessionWorkDir(sessionId), run, cfg, db, vision,
|
||||
onTaskCreated: () => { run.taskWrap = true; }, onCard: (card) => bus.emit(sessionId, 'ui_card', card),
|
||||
onDeepThink: (info) => {
|
||||
const m = (cfg.models || []).find(x => x.id === session.model_id);
|
||||
@@ -1116,7 +1177,7 @@ function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
|
||||
// ---------- 对外 API ----------
|
||||
// 新建即绑模(无排队):指定了优先模型(welcome 预选)就取其平台「最不 active」的 key;
|
||||
// 模型无效或平台无槽位退回全局优先级选。池完全为空直接报错(配置问题),不建吊儿郎当的会话。
|
||||
function createSession(title, preferModelId, assistantType, user) {
|
||||
function createSession(title, preferModelId, assistantType, user, workDir) {
|
||||
// 用户锁定模型(auth.users[].model)优先于前端预选;锁定值无效/被禁用时退回原逻辑(用前端预选或全局自动选择)。
|
||||
const lock = lockedModelOf(user);
|
||||
const lockValid = !!lock && platformModels(platformOf(lock)).includes(lock);
|
||||
@@ -1137,11 +1198,14 @@ function createSession(title, preferModelId, assistantType, user) {
|
||||
if (!modelId) throw Object.assign(new Error('无可用模型:请检查配置并重启服务'), { status_code: 503 });
|
||||
}
|
||||
const id = genTaskId();
|
||||
const dir = taskDirOf(id);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
// 手选目录:直接当作会话工作目录(不建 task-* 子目录);未选 = 老行为,在 workspace_root 下按 id 建档。
|
||||
// 选中的目录必须已存在(normalizeWorkDir 已校验),绝不在用户目录里替它 mkdir。
|
||||
const wd = normalizeWorkDir(workDir);
|
||||
const dir = wd || path.join(cfg.workspace_root, id);
|
||||
if (!wd) fs.mkdirSync(dir, { recursive: true });
|
||||
db.prepare(
|
||||
"INSERT INTO sessions (id, title, status, model_id, model_slot, last_model_id, held_at, assistant_type, user, created_at, updated_at) VALUES (?,?,'held',?,?,?,?,?,?,?,?)"
|
||||
).run(id, title || '', modelId, key.id, modelId, now(), assistantType || 'secretary', user || '', now(), now());
|
||||
"INSERT INTO sessions (id, title, status, model_id, model_slot, last_model_id, held_at, assistant_type, user, work_dir, created_at, updated_at) VALUES (?,?,'held',?,?,?,?,?,?,?,?,?)"
|
||||
).run(id, title || '', modelId, key.id, modelId, now(), assistantType || 'secretary', user || '', wd, now(), now());
|
||||
db.prepare('UPDATE model_pool SET last_used_at = ? WHERE id = ?').run(now(), key.id);
|
||||
profile.freezeSnapshot(db, id); // 冻结画像快照:仅创建/清空时点注入,会话内恒定(见 user-profile.js)
|
||||
// 新建会话默认走模型配置的 profile(未配 = 全量默认组合 + profile-default.txt),不再有顾问阶段
|
||||
@@ -1358,6 +1422,9 @@ function renameSession(sessionId, title) {
|
||||
function deleteSession(sessionId, deleteDir) {
|
||||
const session = getSession(sessionId);
|
||||
if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 });
|
||||
// 删行前先取目录:行没了 taskDirOf 会退回默认路径,且手选目录根本不归平台管。
|
||||
const sessionDir = taskDirOf(sessionId);
|
||||
const ownWorkDir = String(session.work_dir || '');
|
||||
stop(sessionId);
|
||||
// 尽力清理该会话在 executor 侧的预览槽(officecli 预览已迁 executor/preview.js;未配 executor 静默,失败只记日志不阻断删除)
|
||||
try { rexec.killPreviewSession(cfg, sessionId); } catch (_) {}
|
||||
@@ -1367,8 +1434,10 @@ function deleteSession(sessionId, deleteDir) {
|
||||
const frags = memory.dropFragment(db, sessionId); // 日记随会话一并销毁:删掉的会话不该还活在长期记忆里
|
||||
if (frags) log.info('task', sessionId + ' 连带删除日记碎片 ' + frags + ' 条');
|
||||
autoCompressProposed.delete(sessionId); // 提议闸门随会话销毁
|
||||
if (deleteDir) {
|
||||
try { fs.rmSync(taskDirOf(sessionId), { recursive: true, force: true }); } catch (_) {}
|
||||
if (deleteDir && !ownWorkDir) {
|
||||
// 只删平台自己建的会话目录(workspace_root/<会话id>)。手选工作目录是用户的资产,
|
||||
// 多个会话可以共用同一个目录,删会话绝不能连带删用户的项目。
|
||||
try { fs.rmSync(sessionDir, { recursive: true, force: true }); } catch (_) {}
|
||||
}
|
||||
bus.closeAll(sessionId);
|
||||
return { ok: true };
|
||||
|
||||
+24
-7
@@ -58,6 +58,26 @@ function setProfilePrompts(map) {
|
||||
// system prompt 每次请求都随 messages 发出,拼接结果按 (profile, 语言) 缓存,不重复分配大字符串。
|
||||
let _promptTextCache = new Map(); // 'profile\u0000lang' -> text
|
||||
|
||||
// 部署形态决定的环境段:模板里的 {APP_ENV_SECTION} 由两份小模板填充(mode 由 server.js 启动时选定)。
|
||||
// 为什么不能写成一段「两边都成立」的话:服务器形态是容器(每会话隔离、会话级 /tmp、只读 skills),
|
||||
// 本地形态是用户自己那台机器(无沙箱、真实共享 /tmp)——两边的环境事实互相矛盾,混着写会误导模型。
|
||||
// 只选一次、进程内恒定,和技能段同属「前缀缓存不得抖动」的部分。
|
||||
const APP_ENV_TOKEN = '{APP_ENV_SECTION}';
|
||||
const ENV_TEXTS = {
|
||||
server: fs.readFileSync(path.join(__dirname, 'templates', 'env-server.txt'), 'utf8').trim(),
|
||||
local: fs.readFileSync(path.join(__dirname, 'templates', 'env-local.txt'), 'utf8').trim(),
|
||||
};
|
||||
let ENV_TEXT = ENV_TEXTS.server;
|
||||
function setEnvMode(mode) {
|
||||
ENV_TEXT = ENV_TEXTS[mode] || ENV_TEXTS.server;
|
||||
_promptTextCache = new Map(); // 环境段换了,拼接结果必须重建
|
||||
}
|
||||
|
||||
// 自定义 profile prompt 里写了占位符也照样生效(没写就是没有环境段,同技能段规则)。
|
||||
function withEnvSection(text) {
|
||||
return text.indexOf(APP_ENV_TOKEN) >= 0 ? text.split(APP_ENV_TOKEN).join(ENV_TEXT) : text;
|
||||
}
|
||||
|
||||
// “可用技能”段落(skills.formatSkillListForPrompt):启动时快照(server.js)与技能变更后
|
||||
//(routes/skills.js)经 setSkillListText 更新。插入位置由模板内的 {APP_SKILLS_SECTION} 占位符决定
|
||||
//(拼在技能规则旁边,模型一眼看到清单,不再盲猜尾部多出来的孤儿段落):
|
||||
@@ -85,12 +105,9 @@ function systemPromptText(language, profile) {
|
||||
const key = (profile || 'default') + '\u0000' + t;
|
||||
const hit = _promptTextCache.get(key);
|
||||
if (hit) return hit;
|
||||
let text;
|
||||
if (profile && PROFILE_PROMPTS[profile]) {
|
||||
text = withSkillList(PROFILE_PROMPTS[profile], false); // 自定义文件:没放占位符就真没有技能段
|
||||
} else {
|
||||
text = withSkillList(SYSTEM_PROMPT_TEMPLATE, true);
|
||||
}
|
||||
// 环境段先替(模板里的占位符),再拼技能段:自定义 prompt 没放占位符就真没有环境段/技能段
|
||||
const custom = profile && PROFILE_PROMPTS[profile];
|
||||
let text = withSkillList(withEnvSection(custom || SYSTEM_PROMPT_TEMPLATE), !custom);
|
||||
if (t) text += '\n\n## Reply Language\n' +
|
||||
'- ALWAYS respond to the user in ' + t + '. Tool descriptions, tool outputs and errors are usually in English — ' +
|
||||
'never let them switch your reply language. Tool names, parameters, code, file paths and shell commands stay as-is; ' +
|
||||
@@ -795,4 +812,4 @@ async function callModel(cfg, modelId, messages, tools, options) {
|
||||
return { content, reasoning, tool_calls: Array.from(toolCalls.values()), finish_reason: finishReason, usage, aborted, sseFrames };
|
||||
}
|
||||
|
||||
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, setSkillListText, setPayloadTrim, setProfilePrompts, encodeBlocks, decodeBlocks, compressMessages, titleMessages, patchImageReceipt };
|
||||
module.exports = { callModel, buildMessages, buildSystemPrompt, systemPromptText, setSkillListText, setEnvMode, setPayloadTrim, setProfilePrompts, encodeBlocks, decodeBlocks, compressMessages, titleMessages, patchImageReceipt };
|
||||
|
||||
+146
-20
@@ -127,6 +127,61 @@ main { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
/* 本地端:新建会话手选工作目录(服务器形态由 JS 整块隐藏)。 */
|
||||
.welcome-dir {
|
||||
margin-top: 18px;
|
||||
max-width: min(90vw, 560px);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 6px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
background: var(--surface);
|
||||
font-size: 13px;
|
||||
color: var(--ink);
|
||||
}
|
||||
.welcome-dir-cap { flex: 0 0 auto; opacity: .6; }
|
||||
.welcome-dir-pick {
|
||||
min-width: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
.welcome-dir-pick:disabled { opacity: .6; cursor: default; }
|
||||
.welcome-dir-pick .ic { flex: 0 0 auto; color: var(--active); }
|
||||
.welcome-dir-path {
|
||||
max-width: 44ch;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.welcome-dir.is-set .welcome-dir-path { color: var(--active); }
|
||||
.welcome-dir-clear {
|
||||
flex: 0 0 auto;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 50%;
|
||||
background: none;
|
||||
color: var(--ink);
|
||||
opacity: .5;
|
||||
cursor: pointer;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.welcome-dir-clear:hover { opacity: 1; background: var(--border); }
|
||||
.welcome-dir-clear .ic { width: 12px; height: 12px; }
|
||||
|
||||
/* ---------- 对话状态:对话内容区 ---------- */
|
||||
/* overflow-x 显式 hidden:overflow-y:auto 会把 visible 的 overflow-x 计算成 auto,
|
||||
宽代码块/表格自带横向滚动,不该再让消息流整体横向溢出 */
|
||||
@@ -798,6 +853,75 @@ body.voice-active .scroll-bottom-btn { display: none; }
|
||||
.search-box input::placeholder { color: var(--gray-light); }
|
||||
|
||||
.drawer-list { flex: 1; min-height: 0; overflow-y: auto; padding: 0 8px 12px; }
|
||||
|
||||
/* ---------- 抽屉底部图标操作栏(会话/文件树/预览/设置) + 只读文件树 ----------
|
||||
操作栏替代了原来整行可点的用户区:4 个图标,当前生效的那一项高亮(active)。 */
|
||||
.drawer-actions {
|
||||
flex: none; display: flex; align-items: center; justify-content: space-around; gap: 4px;
|
||||
padding: 6px 10px calc(6px + var(--sab)); border-top: 1px solid var(--border);
|
||||
background: var(--drawer-bg);
|
||||
}
|
||||
.drawer-act {
|
||||
flex: 1; height: 40px; display: inline-flex; align-items: center; justify-content: center;
|
||||
border: 0; background: none; border-radius: 10px; color: var(--gray); cursor: pointer;
|
||||
transition: background .12s, color .12s;
|
||||
}
|
||||
.drawer-act:hover { background: var(--surface); color: var(--ink); }
|
||||
.drawer-act.active { color: var(--active); background: var(--active-soft); }
|
||||
.drawer-act svg {
|
||||
width: 20px; height: 20px; fill: none; stroke: currentColor;
|
||||
stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round;
|
||||
}
|
||||
/* 窄屏:没有右侧预览分栏(预览走全屏 #fs-viewer);文件浏览只保留输入行右侧的
|
||||
旧「任务文件」面板,左栏不再出现文件树(不做两套文件 UI)。所以文件树钮也隐藏。 */
|
||||
@media (max-width: 959px) { #da-files { display: none !important; } }
|
||||
|
||||
.files-tree { display: none; flex: 1; min-height: 0; flex-direction: column; }
|
||||
#drawer.drawer-mode-files .drawer-search,
|
||||
#drawer.drawer-mode-files .drawer-list { display: none; }
|
||||
#drawer.drawer-mode-files .files-tree { display: flex; }
|
||||
|
||||
/* 左栏树头部复用预览栏的 .pv-head / .pv-actions / .icon-btn:
|
||||
它俩在桌面上左右并排,高一点点或图标小一号都会明显错位。
|
||||
不放地址条:侧栏只有 280px,路径必然被截断,没有信息量。 */
|
||||
.tree-head .pv-actions { gap: 4px; margin-left: auto; } /* 靠右,与预览栏的操作钮同一侧 */
|
||||
/* 头部图标的「开启中」态(如显示隐藏文件) */
|
||||
.pv-actions .icon-btn.active { color: var(--active); background: var(--active-soft); }
|
||||
|
||||
.tree-body { flex: 1; min-height: 0; overflow: auto; padding: 4px 6px 12px; }
|
||||
.tree-row {
|
||||
display: flex; align-items: center; gap: 5px;
|
||||
padding: 5px 6px; border-radius: 8px; cursor: pointer;
|
||||
font-size: 13px; color: var(--ink); white-space: nowrap;
|
||||
}
|
||||
.tree-row:hover { background: var(--surface); }
|
||||
.tree-row.is-ignored { color: var(--gray-light); cursor: default; }
|
||||
.tree-row.is-link { color: var(--gray); }
|
||||
.tree-caret { flex: none; width: 12px; height: 12px; position: relative; }
|
||||
.tree-row.is-dir .tree-caret::before {
|
||||
content: ""; position: absolute; left: 3px; top: 3px;
|
||||
border-left: 5px solid var(--gray);
|
||||
border-top: 4px solid transparent; border-bottom: 4px solid transparent;
|
||||
transition: transform .12s;
|
||||
}
|
||||
.tree-row.is-dir.open .tree-caret::before { transform: rotate(90deg); }
|
||||
.tree-ico { flex: none; width: 16px; height: 16px; display: inline-flex; color: var(--gray); }
|
||||
.tree-ico svg { width: 16px; height: 16px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.tree-row.is-dir .tree-ico { color: var(--active); }
|
||||
.tree-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||
.tree-act {
|
||||
flex: none; width: 20px; height: 20px; display: none; align-items: center; justify-content: center;
|
||||
border: 0; background: none; color: var(--gray); cursor: pointer; border-radius: 6px;
|
||||
}
|
||||
.tree-row:hover .tree-act { display: inline-flex; }
|
||||
.tree-act:hover { background: var(--border); color: var(--active); }
|
||||
.tree-act.danger:hover { background: #fdf3f2; color: #c0392b; }
|
||||
.tree-act svg { width: 13px; height: 13px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.tree-empty, .tree-loading, .tree-more { padding: 10px 12px; font-size: 12px; color: var(--gray); }
|
||||
|
||||
/* 桌面端:文件浏览交给左栏文件树,隐藏输入行右侧的旧「任务文件」浮层入口。
|
||||
手机端仍用它(窄屏放不下树)。 */
|
||||
@media (min-width: 960px) { #files-btn { display: none !important; } }
|
||||
/* 会话分组表头(按今天/昨天分组):滚动时吸顶,下一个 group-label 滚过来时把它顶走
|
||||
背景色与抽屉一致,避免 sticky 时下面会话透过看到上一组的尾巴 */
|
||||
.group-label {
|
||||
@@ -866,12 +990,7 @@ body.voice-active .scroll-bottom-btn { display: none; }
|
||||
/* 删除会话 modal 副标题:会话 ID 等二级说明,字号小、灰色 */
|
||||
.confirm-sub { font-size: 12px; color: var(--gray); margin-top: 6px; }
|
||||
|
||||
/* 底部用户区 */
|
||||
.drawer-user {
|
||||
flex: none; display: flex; align-items: center; gap: 10px;
|
||||
padding: 12px 14px calc(12px + var(--sab));
|
||||
border-top: 1px solid var(--border);
|
||||
}
|
||||
/* 底部图标操作栏见上方 .drawer-actions(原用户区整行可点已废弃) */
|
||||
.avatar {
|
||||
width: 36px; height: 36px; border-radius: 50%; flex: none;
|
||||
background: var(--active); /* 真实用户名下的头像:JS 按用户名取色内联覆盖,与设置页 user-card 一致 */
|
||||
@@ -1069,10 +1188,6 @@ label.icon-btn { cursor: pointer; }
|
||||
.set-desc { font-size: 12px; color: var(--gray); }
|
||||
.set-arrow { color: var(--gray-light); }
|
||||
|
||||
/* ---------- 抽屉底部用户区:整行可点 ---------- */
|
||||
.drawer-user { cursor: pointer; }
|
||||
.drawer-user:active { background: var(--surface); }
|
||||
|
||||
/* ---------- 通用白卡与设置表单(搬自 style.css 设置页) ---------- */
|
||||
.settings-card {
|
||||
background: var(--page); border: 1px solid var(--border); border-radius: 12px;
|
||||
@@ -1255,7 +1370,7 @@ label.icon-btn { cursor: pointer; }
|
||||
.modal .mpe-unit { position: relative; flex: none; width: 118px; }
|
||||
.modal .mpe-unit input { width: 100%; margin: 0; padding: 8px 30px 8px 10px; }
|
||||
.modal .mpe-unit i { position: absolute; right: 10px; top: 50%; transform: translateY(-50%); font-style: normal; font-size: 11.5px; color: var(--gray-light); pointer-events: none; }
|
||||
/* 预设模式下 name/url 是契约值(只读),压暗以区别于可编辑输入框 */
|
||||
/* 预设模式下 name 是契约值(只读),压暗以区别于可编辑输入框 */
|
||||
.modal input[readonly] { background: #f1f3f7; color: var(--gray); }
|
||||
.modal .mpe-ck { display: flex; align-items: center; gap: 5px; font-size: 12.5px; color: var(--gray); }
|
||||
.modal .mpe-ck input { width: 15px; height: 15px; padding: 0; margin: 0; border: none; background: none; accent-color: var(--active); cursor: pointer; }
|
||||
@@ -1402,23 +1517,33 @@ label.icon-btn { cursor: pointer; }
|
||||
body.drawer-open #toast { left: calc(50% + var(--sidebar-w) / 2); }
|
||||
}
|
||||
|
||||
/* ---------- 文档预览右栏(桌面端≥960px;移动端 office 走全屏 #fs-viewer,本栏隐藏) ---------- */
|
||||
/* ---------- 文档预览分栏(桌面端≥960px;紧贴左侧文件树,移动端 office 走全屏 #fs-viewer,本栏隐藏) ---------- */
|
||||
#pv-pane { display: none; }
|
||||
@media (min-width: 960px) {
|
||||
body.pv-open #pv-pane {
|
||||
display: flex; flex-direction: column;
|
||||
position: fixed; top: 0; right: 0; bottom: 0;
|
||||
position: fixed; top: 0; left: 0; right: auto; bottom: 0;
|
||||
width: var(--pv-w, min(50vw, 900px)); min-width: 320px;
|
||||
background: var(--page); border-left: 1px solid var(--border);
|
||||
background: var(--page); border-right: 1px solid var(--border);
|
||||
z-index: 55;
|
||||
}
|
||||
body.pv-open.pv-max #pv-pane { left: 0; width: auto; border-left: none; z-index: 120; }
|
||||
/* 挤压式分栏:会话列让位;打开右栏时左侧历史栏会自动折叠(若手动再展开则两者同时让位) */
|
||||
body.pv-open #app { width: calc(100% - var(--pv-w, min(50vw, 900px))); margin-left: 0; }
|
||||
body.pv-open.drawer-open #app { width: calc(100% - var(--sidebar-w) - var(--pv-w, min(50vw, 900px))); margin-left: var(--sidebar-w); }
|
||||
/* 侧栏展开时预览紧贴文件树右侧:文件树 | 预览 | 会话(IDE 习惯,点文件后内容就在旁边) */
|
||||
body.pv-open.drawer-open #pv-pane { left: var(--sidebar-w); }
|
||||
body.pv-open.pv-max #pv-pane { left: 0; right: 0; width: auto; border-right: none; z-index: 120; }
|
||||
/* 挤压式分栏:会话列往右让位 */
|
||||
body.pv-open #app { width: calc(100% - var(--pv-w, min(50vw, 900px))); margin-left: var(--pv-w, min(50vw, 900px)); }
|
||||
body.pv-open.drawer-open #app {
|
||||
width: calc(100% - var(--sidebar-w) - var(--pv-w, min(50vw, 900px)));
|
||||
margin-left: calc(var(--sidebar-w) + var(--pv-w, min(50vw, 900px)));
|
||||
}
|
||||
body.pv-open.pv-max #app { width: 100%; margin-left: 0; }
|
||||
/* toast 相对会话列居中(预览开着时会话列被挤到右边) */
|
||||
body.pv-open.drawer-open #toast { left: calc(50% + (var(--sidebar-w) + var(--pv-w, min(50vw, 900px))) / 2); }
|
||||
}
|
||||
.pv-head { flex: none; position: relative; display: flex; align-items: center; gap: 8px; padding: 8px 10px 8px 14px; border-bottom: 1px solid var(--border); background: var(--drawer-bg); }
|
||||
/* 头部高度定死:预览栏里有地址条(内容更高)、文件树只有 32px 图标钮,
|
||||
靠内容撑会让两栏的头部差几像素、下边框对不齐。
|
||||
49 = 32 控件 + 上下各 8 内边距 + 1 下边框(全局 box-sizing:border-box)。 */
|
||||
.pv-head { flex: none; position: relative; display: flex; align-items: center; gap: 8px; height: 49px; padding: 8px 10px 8px 14px; border-bottom: 1px solid var(--border); background: var(--drawer-bg); }
|
||||
/* 地址条胶囊:路径 input + 内嵌动作钮,模拟浏览器地址栏 */
|
||||
.pv-addr { flex: 1; min-width: 0; display: flex; align-items: center; gap: 2px; background: var(--surface); border: 1px solid transparent; border-radius: 10px; padding: 2px 2px 2px 4px; }
|
||||
.pv-addr:focus-within { border-color: var(--border); background: var(--page); }
|
||||
@@ -1445,7 +1570,8 @@ label.icon-btn { cursor: pointer; }
|
||||
@keyframes pvspin { to { transform: rotate(360deg); } }
|
||||
|
||||
/* ---------- preview pane v2: drag resize / info card / plain text ---------- */
|
||||
.pv-resizer { position: absolute; left: 0; top: 0; bottom: 0; width: 6px; cursor: col-resize; z-index: 6; touch-action: none; }
|
||||
/* 拖拽调宽的手柄:预览在左半侧,所以手柄在它的右缘(与会话列的分界) */
|
||||
.pv-resizer { position: absolute; right: 0; top: 0; bottom: 0; width: 6px; cursor: col-resize; z-index: 6; touch-action: none; }
|
||||
.pv-resizer:hover, .pv-resizer:active { background: var(--active); opacity: .3; }
|
||||
body.pv-resizing { cursor: col-resize; user-select: none; }
|
||||
body.pv-resizing #pv-pane iframe { pointer-events: none; }
|
||||
|
||||
@@ -151,6 +151,18 @@
|
||||
</div>
|
||||
<div class="welcome-slogan">随时开始吧</div>
|
||||
</div>
|
||||
<!-- 本地端:新建会话时手选工作目录(服务器形态由 JS 整块隐藏)。
|
||||
只暂存在前端,真正建档时随 POST /api/sessions 提交一次;不选 = 老行为。 -->
|
||||
<div class="welcome-dir hidden" id="welcome-dir">
|
||||
<span class="welcome-dir-cap">工作目录</span>
|
||||
<button type="button" class="welcome-dir-pick" id="welcome-dir-pick" title="选择本会话的工作目录">
|
||||
<svg class="ic sm" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path></svg>
|
||||
<span class="welcome-dir-path" id="welcome-dir-path">默认</span>
|
||||
</button>
|
||||
<button type="button" class="welcome-dir-clear hidden" id="welcome-dir-clear" title="恢复默认目录" aria-label="恢复默认目录">
|
||||
<svg class="ic sm" viewBox="0 0 24 24"><line x1="6" y1="6" x2="18" y2="18"></line><line x1="18" y1="6" x2="6" y2="18"></line></svg>
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ================= 对话状态:对话内容区 ================= -->
|
||||
@@ -222,11 +234,16 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="drawer-list" id="drawer-list"></div>
|
||||
<div class="drawer-user" id="drawer-user">
|
||||
<div class="avatar" id="drawer-avatar">A</div>
|
||||
<div class="user-name" id="drawer-user-name">Agent 用户</div>
|
||||
<button class="user-more" id="user-more-btn" title="更多设置" aria-label="更多设置">
|
||||
<svg class="ic sm" viewBox="0 0 24 24"><circle cx="5" cy="12" r="1.4" fill="currentColor" stroke="none"></circle><circle cx="12" cy="12" r="1.4" fill="currentColor" stroke="none"></circle><circle cx="19" cy="12" r="1.4" fill="currentColor" stroke="none"></circle></svg>
|
||||
<div class="files-tree" id="files-tree"></div>
|
||||
<!-- 底部图标操作栏:文件树 / 设置(文件树按钮是「会话 ↔ 文件」的切换开关)。
|
||||
预览不占按钮:桌面端在文件树里点文件即开预览栏,关窗走预览栏自己的关闭钮。
|
||||
窄屏两个都隐藏:文件只保留输入行右侧的旧面板(不做两套)。选中项高亮。 -->
|
||||
<div class="drawer-actions" id="drawer-actions">
|
||||
<button class="drawer-act" id="da-files" type="button" title="文件树" aria-label="文件树">
|
||||
<svg viewBox="0 0 24 24"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"></path></svg>
|
||||
</button>
|
||||
<button class="drawer-act" id="da-settings" type="button" title="设置" aria-label="设置">
|
||||
<svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"></circle><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"></path></svg>
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
@@ -352,7 +369,7 @@
|
||||
<h3 id="mce-title">编辑 MCP 服务</h3>
|
||||
<input type="text" id="mce-name" placeholder="服务名">
|
||||
<input type="text" id="mce-url" placeholder="MCP 服务 JSON-RPC URL">
|
||||
<!-- 内置服务预设字段(url/name 只读,表单由预设生成) -->
|
||||
<!-- 内置服务预设字段(name 只读、url 可改,表单由预设生成) -->
|
||||
<div class="mpe-sec hidden" id="mce-preset-sec">
|
||||
<div class="mpe-sec-head"><span>配置参数</span><span class="cfg-note" id="mce-preset-desc"></span></div>
|
||||
<div id="mce-preset-fields"></div>
|
||||
@@ -472,7 +489,7 @@
|
||||
<span id="img-count" class="hidden"></span>
|
||||
</div>
|
||||
|
||||
<!-- ================= 文档预览右栏(桌面端≥960px;office/全部文档类型统一承载;移动端走全屏 #fs-viewer,本栏隐藏) -->
|
||||
<!-- ================= 文档预览分栏(桌面端≥960px;紧贴左侧文件树:文件树 | 预览 | 会话;office/全部文档类型统一承载;移动端走全屏 #fs-viewer,本栏隐藏) -->
|
||||
<aside id="pv-pane" aria-label="文档预览">
|
||||
<header class="pv-head">
|
||||
<!-- 地址条胶囊:路径 input(点击全选可复制) + 内嵌 刷新/新窗口,模拟浏览器地址栏 -->
|
||||
@@ -536,17 +553,18 @@
|
||||
<script src="/js/files.js"></script>
|
||||
<script src="/js/voice.js"></script>
|
||||
<script src="/js/preview.js"></script>
|
||||
<script src="/js/files-tree.js"></script>
|
||||
<script src="/js/settings.js"></script>
|
||||
<script>
|
||||
// 启动自愈:外部工具改前端文件是非原子写入,极端时机下浏览器可能拿到半截或重复拼接的 HTML
|
||||
// (脚本缺半 → 白屏裸首页;重复注入 → 每个文件报 duplicate variable 后 JS 全挂)。
|
||||
// 这里检测关键脚本数量与入口全局,不对就自动整页重载一次(sessionStorage 防循环)。
|
||||
// 注意:js/ 脚本增减时需同步改这里的期望数 9。
|
||||
// 注意:js/ 脚本增减时需同步改这里的期望数 10。
|
||||
(function () {
|
||||
var ok = false;
|
||||
try {
|
||||
var n = document.querySelectorAll('script[src^="/js/"]').length;
|
||||
ok = n === 9 && typeof state !== 'undefined' &&
|
||||
ok = n === 10 && typeof state !== 'undefined' &&
|
||||
typeof openFilePreview === 'function' && typeof restartNow === 'function';
|
||||
} catch (_) {}
|
||||
if (ok) { try { sessionStorage.removeItem('boot-heal'); } catch (_) {} return; }
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
// 桌面端左栏文件树:会话文件的唯一浏览入口(服务器形态与 local 形态共用)。
|
||||
// · 懒加载:一次只请求一层目录,展开才拉下一层;node_modules 这类大目录后端只回标记、不展开,
|
||||
// 避免旧的整棵递归接口在单线程 core 上卡死;
|
||||
// · 点文件 → 中间预览栏(文件树 | 预览 | 会话);行内 hover 出「下载 / 删除 / 在 Finder 中显示」;
|
||||
// · 「在 Finder / 终端中打开」只在 local 启动器下可用(服务器上这些动作没有意义),
|
||||
// 靠 /api/local/info 探测,拿不到就隐藏这两个按钮。
|
||||
// 手机端不启用(收纳在抽屉里体验太差),仍走输入行右侧的旧文件面板。
|
||||
// 依赖(全局):state $ req toast downloadFile confirmModal openFilePreview
|
||||
'use strict';
|
||||
(function () {
|
||||
const SVG_FOLDER = '<svg class="ic sm" viewBox="0 0 24 24"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>';
|
||||
const SVG_FILE = '<svg class="ic sm" viewBox="0 0 24 24"><path d="M6 3h8l4 4v14H6z"/><path d="M14 3v4h4"/></svg>';
|
||||
const SVG_LINK = '<svg class="ic sm" viewBox="0 0 24 24"><path d="M10 13a5 5 0 0 0 7 0l2-2a5 5 0 0 0-7-7l-1 1"/><path d="M14 11a5 5 0 0 0-7 0l-2 2a5 5 0 0 0 7 7l1-1"/></svg>';
|
||||
const SVG_REVEAL = '<svg class="ic sm" viewBox="0 0 24 24"><path d="M14 4h6v6"/><path d="M20 4l-9 9"/><path d="M19 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h5"/></svg>';
|
||||
const SVG_REFRESH = '<svg class="ic sm" viewBox="0 0 24 24"><path d="M20 12a8 8 0 1 1-2.3-5.7"/><path d="M20 4v5h-5"/></svg>';
|
||||
const SVG_TERM = '<svg class="ic sm" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="16" rx="2"/><path d="M7 9l3 3-3 3"/><path d="M13 15h4"/></svg>';
|
||||
const SVG_EYE = '<svg class="ic sm" viewBox="0 0 24 24"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="2.6"/></svg>';
|
||||
const SVG_DL = '<svg viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>';
|
||||
const SVG_DEL = '<svg viewBox="0 0 24 24"><polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/><line x1="10" y1="11" x2="10" y2="17"/><line x1="14" y1="11" x2="14" y2="17"/></svg>';
|
||||
const SVG_REVEAL_SM = '<svg viewBox="0 0 24 24"><path d="M14 4h6v6"/><path d="M20 4l-9 9"/><path d="M19 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1h5"/></svg>';
|
||||
|
||||
let localCapable = false; // local 启动器:才显示「在 Finder/终端中打开」
|
||||
let showHidden = false;
|
||||
let expanded = new Set(['']); // 已展开的相对目录('' = 根)
|
||||
let cache = new Map(); // rel -> /tree 响应
|
||||
let loading = new Map(); // rel -> Promise(并发去重)
|
||||
let gen = 0; // 会话切换/刷新时自增,防止旧请求回填到新树的缓存
|
||||
|
||||
// 失效缓存。gen 自增让在飞的旧请求回来时不再写缓存(否则切会话会闪旧目录)。
|
||||
function invalidate(keepExpanded) {
|
||||
gen++;
|
||||
cache = new Map();
|
||||
loading = new Map();
|
||||
if (!keepExpanded) expanded = new Set(['']);
|
||||
}
|
||||
|
||||
function sid() { return (state && state.sessionId) || ''; }
|
||||
|
||||
function tip(parent, text, cls) {
|
||||
const el = document.createElement('div');
|
||||
el.className = cls || 'tree-empty';
|
||||
el.textContent = text;
|
||||
parent.appendChild(el);
|
||||
}
|
||||
|
||||
function openDir(rel) {
|
||||
if (cache.has(rel)) return Promise.resolve(cache.get(rel));
|
||||
if (loading.has(rel)) return loading.get(rel);
|
||||
if (!sid()) return Promise.resolve(null);
|
||||
const url = '/api/sessions/' + encodeURIComponent(sid()) + '/tree?dir=' +
|
||||
encodeURIComponent(rel) + (showHidden ? '&hidden=1' : '');
|
||||
const myGen = gen;
|
||||
const p = req('GET', url).then(function (data) {
|
||||
if (myGen === gen) { cache.set(rel, data); loading.delete(rel); }
|
||||
return data;
|
||||
}, function (e) {
|
||||
if (myGen === gen) loading.delete(rel);
|
||||
throw e;
|
||||
});
|
||||
loading.set(rel, p);
|
||||
return p;
|
||||
}
|
||||
|
||||
function actBtn(act, title, svg, danger) {
|
||||
const b = document.createElement('button');
|
||||
b.type = 'button';
|
||||
b.className = 'tree-act' + (danger ? ' danger' : '');
|
||||
b.dataset.act = act;
|
||||
b.title = title;
|
||||
b.innerHTML = svg;
|
||||
return b;
|
||||
}
|
||||
|
||||
function rowFor(ent, depth) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'tree-row';
|
||||
row.dataset.rel = ent.rel;
|
||||
row.dataset.type = ent.type;
|
||||
row.style.paddingLeft = (6 + depth * 14) + 'px';
|
||||
row.title = ent.rel;
|
||||
if (ent.type === 'dir') {
|
||||
row.classList.add('is-dir');
|
||||
if (expanded.has(ent.rel)) row.classList.add('open');
|
||||
}
|
||||
if (ent.type === 'link') row.classList.add('is-link');
|
||||
if (ent.ignored) row.classList.add('is-ignored');
|
||||
|
||||
const caret = document.createElement('span');
|
||||
caret.className = 'tree-caret';
|
||||
row.appendChild(caret);
|
||||
|
||||
const ico = document.createElement('span');
|
||||
ico.className = 'tree-ico';
|
||||
ico.innerHTML = ent.type === 'dir' ? SVG_FOLDER : (ent.type === 'link' ? SVG_LINK : SVG_FILE);
|
||||
row.appendChild(ico);
|
||||
|
||||
const name = document.createElement('span');
|
||||
name.className = 'tree-name';
|
||||
name.textContent = ent.name;
|
||||
row.appendChild(name);
|
||||
|
||||
if (ent.ignored) {
|
||||
row.title = ent.rel + '(已忽略的大目录/构建产物)';
|
||||
return row;
|
||||
}
|
||||
// 行内动作:服务器形态给「下载 / 删除」;local 本就跑在同一台机器上,
|
||||
// 「下载」到本地是多余的(用 Finder 直接看原文件更顺),所以换成「在 Finder 中显示」。
|
||||
if (ent.type === 'file' && !localCapable) row.appendChild(actBtn('download', '下载', SVG_DL, false));
|
||||
if (localCapable) row.appendChild(actBtn('reveal', '在 Finder 中显示', SVG_REVEAL_SM, false));
|
||||
row.appendChild(actBtn('delete', '删除', SVG_DEL, true));
|
||||
return row;
|
||||
}
|
||||
|
||||
async function renderDirInto(container, rel, depth) {
|
||||
container.innerHTML = '';
|
||||
const data = await openDir(rel);
|
||||
if (!data) return;
|
||||
const frag = document.createDocumentFragment();
|
||||
const list = data.entries || [];
|
||||
if (!list.length) tip(frag, '(空目录)');
|
||||
for (const ent of list) {
|
||||
frag.appendChild(rowFor(ent, depth));
|
||||
if (ent.type === 'dir' && !ent.ignored && expanded.has(ent.rel)) {
|
||||
const kids = document.createElement('div');
|
||||
kids.className = 'tree-children';
|
||||
frag.appendChild(kids);
|
||||
renderDirInto(kids, ent.rel, depth + 1).catch(function () {}); // 异步填充子层
|
||||
}
|
||||
}
|
||||
if (data.capped) tip(frag, '仅显示前 ' + list.length + ' 项(共 ' + data.total + ' 项)', 'tree-more');
|
||||
container.appendChild(frag);
|
||||
}
|
||||
|
||||
async function renderBody() {
|
||||
const body = $('tree-body');
|
||||
if (!body) return;
|
||||
// 没有会话就没有任务目录:不写提示,直接把侧栏退回会话列表。
|
||||
// 这条会兜住「在文件页里点了新建会话 / 删掉了当前会话」——那时卡片不该停在一个空树里。
|
||||
if (!sid()) {
|
||||
body.innerHTML = '';
|
||||
if (typeof setDrawerPane === 'function') setDrawerPane(false);
|
||||
return;
|
||||
}
|
||||
const sc = body.scrollTop;
|
||||
body.innerHTML = '';
|
||||
const root = document.createElement('div');
|
||||
body.appendChild(root);
|
||||
try {
|
||||
await renderDirInto(root, '', 0);
|
||||
} catch (e) {
|
||||
root.innerHTML = '';
|
||||
tip(root, '加载失败:' + e.message);
|
||||
}
|
||||
body.scrollTop = sc;
|
||||
}
|
||||
|
||||
async function localAction(kind, rel) {
|
||||
if (!localCapable) return;
|
||||
if (!sid()) { toast('尚未开始会话'); return; }
|
||||
try {
|
||||
await req('POST', '/api/local/' + kind, { session: sid(), path: rel });
|
||||
} catch (e) {
|
||||
toast((kind === 'reveal' ? '打开目录失败:' : '打开终端失败:') + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteNode(rel, isDir) {
|
||||
if (!sid()) return;
|
||||
const name = rel.split('/').pop();
|
||||
const ok = typeof confirmModal === 'function'
|
||||
? await confirmModal('删除' + (isDir ? '文件夹' : '文件'),
|
||||
'删除「' + name + '」' + (isDir ? '(含其中全部内容)' : '') + '?', '删除', true)
|
||||
: true;
|
||||
if (!ok) return;
|
||||
try {
|
||||
await req('DELETE', '/api/sessions/' + sid() + '/files?path=' + encodeURIComponent(rel));
|
||||
// 预览里正开着被删的文件 → 一起关掉,别留一份已不存在的内容
|
||||
if (typeof pvState === 'object' && pvState && pvState.name === rel && typeof pvCloseDoc === 'function') pvCloseDoc();
|
||||
invalidate(true);
|
||||
renderBody();
|
||||
toast('已删除');
|
||||
} catch (e) { toast('删除失败:' + e.message); }
|
||||
}
|
||||
|
||||
function onTreeClick(e) {
|
||||
const row = e.target.closest('.tree-row');
|
||||
if (!row) return;
|
||||
const rel = row.dataset.rel;
|
||||
const isDir = row.dataset.type === 'dir';
|
||||
const act = e.target.closest('.tree-act');
|
||||
if (act) {
|
||||
e.stopPropagation();
|
||||
const a = act.dataset.act;
|
||||
if (a === 'download') { if (typeof downloadFile === 'function') downloadFile(rel); }
|
||||
else if (a === 'delete') deleteNode(rel, isDir);
|
||||
else if (a === 'reveal') localAction('reveal', rel);
|
||||
return;
|
||||
}
|
||||
if (row.classList.contains('is-ignored') || row.dataset.type === 'link') return;
|
||||
if (isDir) {
|
||||
if (expanded.has(rel)) expanded.delete(rel); else expanded.add(rel);
|
||||
renderBody();
|
||||
} else if (typeof openFilePreview === 'function') {
|
||||
openFilePreview(rel, '');
|
||||
// 窄屏的预览是全屏浮层:点完把抽屉收起(同点会话的行为),否则关预览后还压在抽屉上
|
||||
if (typeof openDrawer === 'function' && !window.matchMedia('(min-width: 960px)').matches) openDrawer(false);
|
||||
}
|
||||
}
|
||||
|
||||
// local 能力探测结果回来后才把「在 Finder/终端中打开」露出来(服务器形态永远隐藏)
|
||||
function syncLocalButtons() {
|
||||
const rv = $('tree-reveal'), tm = $('tree-terminal');
|
||||
if (rv) rv.classList.toggle('hidden', !localCapable);
|
||||
if (tm) tm.classList.toggle('hidden', !localCapable);
|
||||
if (localCapable && $('tree-body')) renderBody(); // 行内 reveal 按钮也要重新生成
|
||||
}
|
||||
|
||||
function ensureShell() {
|
||||
const box = $('files-tree');
|
||||
if (!box || box.dataset.ready) return;
|
||||
box.dataset.ready = '1';
|
||||
box.innerHTML = '';
|
||||
|
||||
// 头部直接复用预览栏的 .pv-head / .pv-actions / .icon-btn:
|
||||
// 两者在桌面上左右并排,尺寸/描边/内边距必须一模一样,否则一眼就看出错位。
|
||||
// 不放地址条(路径在 280px 里必然截断,没有信息量),所以只剩右侧操作钮。
|
||||
const head = document.createElement('header');
|
||||
head.className = 'pv-head tree-head';
|
||||
head.innerHTML =
|
||||
'<span class="pv-actions">' +
|
||||
'<button class="icon-btn" type="button" id="tree-hidden" title="显示隐藏文件" aria-label="显示隐藏文件">' + SVG_EYE + '</button>' +
|
||||
'<button class="icon-btn" type="button" id="tree-refresh" title="刷新" aria-label="刷新">' + SVG_REFRESH + '</button>' +
|
||||
'<button class="icon-btn hidden" type="button" id="tree-reveal" title="在 Finder 中打开" aria-label="在 Finder 中打开">' + SVG_REVEAL + '</button>' +
|
||||
'<button class="icon-btn hidden" type="button" id="tree-terminal" title="在终端中打开" aria-label="在终端中打开">' + SVG_TERM + '</button>' +
|
||||
'</span>';
|
||||
|
||||
const body = document.createElement('div');
|
||||
body.className = 'tree-body';
|
||||
body.id = 'tree-body';
|
||||
|
||||
box.appendChild(head);
|
||||
box.appendChild(body);
|
||||
|
||||
head.querySelector('#tree-hidden').addEventListener('click', function () {
|
||||
showHidden = !showHidden;
|
||||
invalidate(false);
|
||||
this.classList.toggle('active', showHidden);
|
||||
renderBody();
|
||||
});
|
||||
head.querySelector('#tree-refresh').addEventListener('click', function () {
|
||||
invalidate(true);
|
||||
renderBody();
|
||||
});
|
||||
head.querySelector('#tree-reveal').addEventListener('click', function () { localAction('reveal', ''); });
|
||||
head.querySelector('#tree-terminal').addEventListener('click', function () { localAction('terminal', ''); });
|
||||
body.addEventListener('click', onTreeClick);
|
||||
|
||||
syncLocalButtons();
|
||||
}
|
||||
|
||||
// 侧栏底部「文件树」图标 → 切到这个面板(由 files.js 的 setDrawerPane 调用)。
|
||||
window.showFileTree = function () {
|
||||
ensureShell();
|
||||
renderBody();
|
||||
};
|
||||
|
||||
// 会话切换后由 sessions.js 调用,避免树停在旧会话。
|
||||
window.refreshFileTree = function () {
|
||||
invalidate(false);
|
||||
const drawer = $('drawer');
|
||||
if (drawer && drawer.classList.contains('drawer-mode-files')) renderBody();
|
||||
};
|
||||
|
||||
(function init() {
|
||||
if (!$('drawer-actions') || !$('files-tree')) return;
|
||||
req('GET', '/api/local/info').then(function (info) {
|
||||
if (!info || !info.enabled) return;
|
||||
localCapable = true;
|
||||
syncLocalButtons();
|
||||
}).catch(function () { /* 服务器形态:接口 404,保持纯服务器行为 */ });
|
||||
})();
|
||||
})();
|
||||
@@ -910,6 +910,8 @@
|
||||
// 全部成功不再弹提示(卡片已完成态即反馈);有失败才提醒
|
||||
if (errCount) toast('已上传 ' + done + ' 个,失败 ' + errCount + ' 个');
|
||||
loadFiles();
|
||||
// 桌面端左栏文件树是新的浏览入口,上传后要同步(旧面板只在手机端用)
|
||||
if (typeof window.refreshFileTree === 'function') window.refreshFileTree();
|
||||
// 1.2s 后收起进度条(还有别的批次在传就不收)
|
||||
setTimeout(() => {
|
||||
if (uploadBatches.size) return;
|
||||
@@ -1096,6 +1098,8 @@
|
||||
if (delBtn) { e.stopPropagation(); deleteSession(delBtn.dataset.del); return; }
|
||||
const item = e.target.closest('.conv-item');
|
||||
if (!item) return;
|
||||
// 设置页现在保留左栏(可在设置中看会话/文件):点会话即退出设置页回到对话。
|
||||
if (typeof closeSettings === 'function' && !$('settings-page').classList.contains('hidden')) closeSettings();
|
||||
openSession(item.dataset.id);
|
||||
if (!drawerMQ.matches) openDrawer(false); // 桌面端侧栏常驻,选完会话不收起来
|
||||
});
|
||||
@@ -1229,9 +1233,38 @@
|
||||
document.addEventListener('touchcancel', e => endDrag(e, false), { passive: true });
|
||||
})();
|
||||
|
||||
// 抽屉底部用户区:整行点击 → 设置主页(逻辑见文末「设置区」一节)
|
||||
$('drawer-user').addEventListener('click', () => {
|
||||
if (!drawerMQ.matches) openDrawer(false); // 桌面端设置页覆盖在会话区上,侧栏保持展开
|
||||
// 抽屉底部图标操作栏:文件树 / 预览 / 设置。
|
||||
// 「文件树」是侧栏两个互斥面板的切换开关:不在文件页 → 切到文件树(高亮),
|
||||
// 再点一次 → 回会话列表(不亮)。预览与设置不占用侧栏,高亮由 preview.js / settings.js 同步。
|
||||
function setDrawerPane(files) {
|
||||
// 窄屏没有文件树(只有输入行右侧的旧文件面板),任何调用方都不允许切过去
|
||||
if (files && !drawerMQ.matches) return;
|
||||
// 还没开始会话 = 没有任务目录:不切过去(否则只能切出一个写着「尚未开始会话」的空面板)
|
||||
if (files && !state.sessionId) return;
|
||||
// 文件树模块没加载成功时不要把一个空面板切出来
|
||||
if (files && typeof window.showFileTree !== 'function') return;
|
||||
const drawer = $('drawer');
|
||||
const changed = drawer.classList.contains('drawer-mode-files') !== files;
|
||||
drawer.classList.toggle('drawer-mode-files', files);
|
||||
$('da-files').classList.toggle('active', files);
|
||||
// 重复点当前项不重干活(不重拉列表/不重渲树),避免白掉请求和滚动位置
|
||||
if (!changed) return;
|
||||
if (files) window.showFileTree();
|
||||
else loadSessionList();
|
||||
}
|
||||
$('da-files').addEventListener('click', () => {
|
||||
setDrawerPane(!$('drawer').classList.contains('drawer-mode-files'));
|
||||
});
|
||||
// 窄屏只保留输入行右侧的旧「任务文件」面板,左栏不再提供文件树(按钮也已 CSS 隐藏)。
|
||||
// 宽屏缩到窄屏时如果正停在文件页,先退回会话列表,避免出现两套文件 UI。
|
||||
drawerMQ.addEventListener('change', (e) => { if (!e.matches) setDrawerPane(false); });
|
||||
// 预览没有独立按钮:桌面端只在文件树里点文件时开窗(关窗走预览栏自己的关闭钮 / Esc)。
|
||||
$('da-settings').addEventListener('click', () => {
|
||||
if (typeof showSettings !== 'function') return;
|
||||
const page = $('settings-page');
|
||||
// 再点一次返回(关设置页);否则打开。不看当前在设置栈的第几层,都当"退出设置"
|
||||
if (page && !page.classList.contains('hidden')) { closeSettings(); return; }
|
||||
if (!drawerMQ.matches) openDrawer(false); // 移动端设置页整屏,抽屉先收起
|
||||
showSettings();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// 通用文档预览窗(桌面右侧 #pv-pane / 移动端全屏 #fs-viewer)
|
||||
// 通用文档预览窗(桌面分栏 #pv-pane:文件树 | 预览 | 会话 / 移动端全屏 #fs-viewer)
|
||||
// —— 文件列表的点击一律进预览窗:office 走 /preview 预览网关(固定格式前端自拼);
|
||||
// md/txt/代码/json/csv 等文本渲染;html/pdf/图片专用渲染;其余类型显示文件信息占位 + 下载。
|
||||
// 桌面打开时自动折叠左侧历史栏让位,关闭恢复;左右边界可拖拽调宽(记忆在 localStorage)。
|
||||
// 桌面端紧贴左栏文件树右侧:点文件后内容就在旁边,不用横跨整个会话区看。
|
||||
// 右边界可拖拽调宽(记忆在 localStorage)。
|
||||
// 依赖(core.js/chat.js/stream.js/files.js 顶层声明):state $ esc toast mdHtml decorateCodePre
|
||||
// rewriteHtmlDocSrcs rewriteMdImageSrcs openFullscreen setFsSource closeFullscreen
|
||||
// openImageViewer downloadFile openDrawer
|
||||
@@ -16,7 +17,7 @@ const PV_TEXT = /\.(md|markdown|txt|log|csv|tsv|json|jsonl|xml|yml|yaml|toml|ini
|
||||
const PV_TEXT_MAX = 512 * 1024; // 文本预览截断阈值(字符),超出提示下载看全文
|
||||
let pvSeq = 0; // 预览序号:快速连点时旧请求不许再动 DOM
|
||||
// reload: 当前内容的"重新载入"动作(文本类无 iframe,按名重开);为 null 时回退到 reload iframe
|
||||
const pvState = { name: null, url: null, blobUrl: null, reload: null, drawerWasOpen: false, mobilePush: false };
|
||||
const pvState = { name: null, url: null, blobUrl: null, reload: null, mobilePush: false };
|
||||
|
||||
function pvDesktop() { return window.matchMedia('(min-width: 960px)').matches; }
|
||||
|
||||
@@ -117,11 +118,13 @@ function pvInfoNode(name, sizeText, hint) {
|
||||
}
|
||||
|
||||
function pvOpenPane() {
|
||||
// 不自动折叠左侧栏:左栏是文件树,打开预览时保持可见(文件树 | 预览 | 会话)。
|
||||
if (!document.body.classList.contains('pv-open')) {
|
||||
pvState.drawerWasOpen = document.getElementById('drawer').classList.contains('open');
|
||||
if (pvState.drawerWasOpen && typeof openDrawer === 'function') openDrawer(false); // 挤压式分栏:折叠左侧让位
|
||||
document.body.classList.add('pv-open');
|
||||
}
|
||||
// 开预览就把侧栏切到文件树:预览就贴在它旁边,切了才能顺手换文件看。
|
||||
// 已经在文件页时 setDrawerPane 内部会因「没变化」而直接返回,不会重复拉树。
|
||||
if (typeof setDrawerPane === 'function') setDrawerPane(true);
|
||||
}
|
||||
|
||||
function pvCloseDoc() {
|
||||
@@ -130,12 +133,11 @@ function pvCloseDoc() {
|
||||
if (typeof pvSetMaxUI === 'function') pvSetMaxUI(false); // 收起时复位放大钮图标(函数声明提升,定义在后亦可)
|
||||
pvClearBody();
|
||||
pvState.name = null; pvState.url = null;
|
||||
if (pvState.drawerWasOpen) {
|
||||
pvState.drawerWasOpen = false;
|
||||
if (typeof openDrawer === 'function') openDrawer(true); // 恢复打开预览前的折叠态
|
||||
}
|
||||
}
|
||||
|
||||
// 侧栏底部没有「预览」按钮:桌面端的预览只有一条入口——在文件树里点文件(点即开窗),
|
||||
// 关窗走预览栏自己的关闭钮 / Esc / 缩到窄屏。所以这里不再维护任何按钮高亮状态。
|
||||
|
||||
// 移动端全屏承载:把节点塞进 #fs-viewer 并展开
|
||||
// opts.bar → 文件预览沉浸模式:顶部独立操作条,内容全宽占满剩余空间
|
||||
// opts.name → 操作条左侧的文件名(仅 bar 模式可见)
|
||||
@@ -572,17 +574,18 @@ window.addEventListener('popstate', () => {
|
||||
const fs = document.getElementById('fs-viewer');
|
||||
if (!fs.classList.contains('hidden') && fs.querySelector('.fs-html-frame[src^="/preview/"]')) closeFullscreen();
|
||||
});
|
||||
// Esc 关闭右栏(未开全屏查看器时)
|
||||
// Esc 关闭预览分栏(未开全屏查看器时)
|
||||
window.addEventListener('keydown', (e) => {
|
||||
if (e.key !== 'Escape') return;
|
||||
if (document.activeElement && document.activeElement.id === 'pv-title') { document.activeElement.blur(); return; } // 地址条聚焦时:先退框不关栏
|
||||
if (!document.getElementById('fs-viewer').classList.contains('hidden')) return;
|
||||
pvCloseDoc();
|
||||
});
|
||||
// 窗口收窄到移动端宽度:右栏收起
|
||||
// 窗口收窄到移动端宽度:预览栏收起
|
||||
window.matchMedia('(min-width: 960px)').addEventListener('change', () => { if (!pvDesktop()) pvCloseDoc(); });
|
||||
|
||||
// ---------- 左缘拖拽调宽(预览/会话列边界):双击复位默认宽度,宽度记在 localStorage ----------
|
||||
// ---------- 右缘拖拽调宽(预览/会话列边界):双击复位默认宽度,宽度记在 localStorage ----------
|
||||
// 预览现在贴在文件树右侧(文件树 | 预览 | 会话),所以手柄在它自己的右缘,往右拖变宽。
|
||||
(function bindPvResize() {
|
||||
const pane = document.getElementById('pv-pane');
|
||||
const saved = Number(localStorage.getItem('pv-w') || 0);
|
||||
@@ -599,7 +602,7 @@ window.matchMedia('(min-width: 960px)').addEventListener('change', () => { if (!
|
||||
});
|
||||
h.addEventListener('pointermove', (e) => {
|
||||
if (!st) return;
|
||||
document.documentElement.style.setProperty('--pv-w', clamp(st.w + (st.x - e.clientX)) + 'px');
|
||||
document.documentElement.style.setProperty('--pv-w', clamp(st.w + (e.clientX - st.x)) + 'px');
|
||||
});
|
||||
function end() {
|
||||
if (!st) return;
|
||||
|
||||
@@ -78,6 +78,7 @@
|
||||
state.sessionId = null;
|
||||
state.sessionTitle = '';
|
||||
state.sessionType = 'secretary';
|
||||
if (window.refreshFileTree) window.refreshFileTree();
|
||||
state.pendingModel = '';
|
||||
state.pending = [];
|
||||
renderSendQueue();
|
||||
@@ -187,7 +188,8 @@
|
||||
closeStream();
|
||||
removeTyping();
|
||||
setFilesPanel(false); // 会话切换,收起文件面板防旧列表残留
|
||||
if (typeof pvCloseDoc === 'function') pvCloseDoc(); // 同上:收起文档预览右栏,防旧会话内容残留
|
||||
// 预览分栏故意不关:它现在是「随手看参考」的第三列,切会话时关掉会让用户反复重开。
|
||||
// 保留已渲染的内容(静态文件,不存在跨会话越权),点新会话的文件会自然覆盖。
|
||||
state.sessionId = id;
|
||||
state.status = '';
|
||||
state.modelId = '';
|
||||
@@ -222,6 +224,7 @@
|
||||
if (state.sessionId !== id) return; // 期间已切到别的会话
|
||||
renderDetail(detail);
|
||||
connectStream();
|
||||
if (window.refreshFileTree) window.refreshFileTree();
|
||||
} catch (e) {
|
||||
if (state.sessionId === id) toast('打开会话失败:' + e.message);
|
||||
}
|
||||
@@ -231,11 +234,12 @@
|
||||
// welcome 经弹窗预选的模型在这里兑现:model_id 建档透传。
|
||||
async function ensureSession() {
|
||||
if (state.sessionId) return state.sessionId;
|
||||
const s = await req('POST', '/api/sessions', { title: '', model_id: state.pendingModel || '', assistant_type: state.mode });
|
||||
const s = await req('POST', '/api/sessions', { title: '', model_id: state.pendingModel || '', assistant_type: state.mode, work_dir: pendingWorkDir || undefined });
|
||||
state.sessionId = s.id;
|
||||
state.sessionTitle = (s && s.title) || '';
|
||||
state.sessionType = (s && s.assistant_type) || state.mode;
|
||||
state.pendingModel = '';
|
||||
if (window.refreshFileTree) window.refreshFileTree();
|
||||
setView('chat');
|
||||
renderHeader();
|
||||
updateHeaderActions();
|
||||
@@ -243,6 +247,49 @@
|
||||
return s.id;
|
||||
}
|
||||
|
||||
// ---------- 本地端:新建会话时手选工作目录 ----------
|
||||
// 只在 local/ 启动器(AGENT_LOCAL_PICK=1)下可用:探测 /api/local/info,拿不到就把整条
|
||||
// chip 隐藏,服务器形态完全看不见这个入口。选择只暂存在前端,真正建档时随
|
||||
// POST /api/sessions 提交一次;不选 = work_dir 空串 = 老行为(workspace_root/<会话id>)。
|
||||
let pendingWorkDir = '';
|
||||
|
||||
function renderWelcomeDir() {
|
||||
const pathEl = $('welcome-dir-path');
|
||||
if (!pathEl) return;
|
||||
const chip = $('welcome-dir');
|
||||
pathEl.textContent = pendingWorkDir || '默认(工作区内)';
|
||||
pathEl.title = pendingWorkDir || '默认:每个会话在系统工作目录下单独建档';
|
||||
chip.classList.toggle('is-set', !!pendingWorkDir);
|
||||
$('welcome-dir-clear').classList.toggle('hidden', !pendingWorkDir);
|
||||
}
|
||||
|
||||
async function pickWelcomeDir() {
|
||||
const btn = $('welcome-dir-pick');
|
||||
if (btn.disabled) return;
|
||||
btn.disabled = true;
|
||||
try {
|
||||
// 超时给足 130s:后端对话框上限 120s,这里多留余量,别让前端先断
|
||||
const r = await req('POST', '/api/local/pick-dir', {}, false, 130000);
|
||||
if (r && r.path) { pendingWorkDir = r.path; renderWelcomeDir(); }
|
||||
} catch (e) {
|
||||
toast('选择目录失败:' + e.message);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
(function initWelcomeDir() {
|
||||
const chip = $('welcome-dir');
|
||||
if (!chip) return;
|
||||
req('GET', '/api/local/info').then(info => {
|
||||
if (!info || !info.enabled) return;
|
||||
chip.classList.remove('hidden');
|
||||
renderWelcomeDir();
|
||||
}).catch(() => { /* 服务器形态:接口 404,整条隐藏 */ });
|
||||
$('welcome-dir-pick').addEventListener('click', pickWelcomeDir);
|
||||
$('welcome-dir-clear').addEventListener('click', () => { pendingWorkDir = ''; renderWelcomeDir(); });
|
||||
})();
|
||||
|
||||
function newChat() {
|
||||
closeStream();
|
||||
removeTyping();
|
||||
@@ -250,6 +297,7 @@
|
||||
state.sessionId = null;
|
||||
state.sessionTitle = '';
|
||||
state.sessionType = 'secretary';
|
||||
if (window.refreshFileTree) window.refreshFileTree();
|
||||
state.status = '';
|
||||
state.modelId = '';
|
||||
state.schedule = null;
|
||||
@@ -257,6 +305,8 @@
|
||||
renderSendQueue();
|
||||
state.pendingModel = '';
|
||||
state.attachments = [];
|
||||
pendingWorkDir = ''; // 新建会话把上次手选的工作目录也归零(回到默认)
|
||||
renderWelcomeDir();
|
||||
if (typeof clearEditState === 'function') clearEditState();
|
||||
state.streamEl = null;
|
||||
state.streamText = '';
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
stack: [],
|
||||
snaps: {}, // 页名 → 静态快照 HTML(setPush 时刷新;右滑返回垫底用)
|
||||
role: 'user', // 当前登录用户角色(admin | user);启动时由 /api/me 回填
|
||||
authEnabled: true, // 是否启用多用户认证(/api/me 404 = 未启用,单用户自用)
|
||||
authEnabled: true, // 是否启用多用户认证(/api/me 返回 auth:false = 未启用,单用户自用)
|
||||
pendingKeys: new Set(), // 已写盘、尚未重启生效的顶层配置段
|
||||
effCfg: null, cfgOrig: '',
|
||||
users: [], userModels: [], // 用户管理页:账号/角色/默认模型 + 可选模型清单
|
||||
@@ -130,17 +130,17 @@
|
||||
function showSettings() {
|
||||
// 普通用户没有设置主页:直接进账户页(栈里只有一页,返回即退出设置)
|
||||
SET.stack = [SET.role === 'admin' ? 'home' : 'account']; SET.snaps = {}; setUnderHide();
|
||||
// 桌面端:打开设置时收起侧边栏让设置页占满窗口,关闭时恢复之前的展开态
|
||||
if (drawerMQ.matches) { drawerWasOpenBeforeSet = document.body.classList.contains('drawer-open'); openDrawer(false); }
|
||||
// 桌面端保留左侧栏:设置页是 #app 内的 absolute 覆盖层,自然只占侧栏右侧区域,
|
||||
// 左栏(会话/文件)保持可见可用。
|
||||
$('settings-page').classList.remove('hidden'); renderSetPage();
|
||||
const b = $('da-settings'); if (b) b.classList.add('active'); // 侧栏底部图标同步选中态
|
||||
}
|
||||
let drawerWasOpenBeforeSet = false;
|
||||
function closeSettings() {
|
||||
SET.stack = []; SET.snaps = {}; setUnderHide();
|
||||
// 退回会话页才重置模型池状态:平台卡全部折叠、余额清空,下次进入重新自动查
|
||||
SET.expandedGroups = {}; SET.balanceByGroup = {}; SET.balanceRequested = {};
|
||||
$('settings-page').classList.add('hidden');
|
||||
if (drawerMQ.matches && drawerWasOpenBeforeSet) { openDrawer(true); drawerWasOpenBeforeSet = false; }
|
||||
const b = $('da-settings'); if (b) b.classList.remove('active');
|
||||
}
|
||||
// 当前页静态快照(顶栏+正文):右滑返回时垫底,呈现原生导航栈的视差感。
|
||||
// 快照里的 id 全部剥除,防止重复 id 干扰 $('…') 查找;仅作动画背景,滑完由 renderSetPage 重渲染真页。
|
||||
@@ -320,23 +320,8 @@
|
||||
for (const ch of String(name || '')) h = (h * 31 + ch.codePointAt(0)) >>> 0;
|
||||
return AVATAR_COLORS[h % AVATAR_COLORS.length];
|
||||
}
|
||||
// 侧边栏底部用户区:展示真实登录用户名,头像样式与设置页 user-card 一致(按用户名取色+首两字)。
|
||||
// 启动校验已经拉到登录用户时直接传入,避免同一次加载重复请求 /api/me;未传入时自拉兜底。
|
||||
async function loadDrawerUser(knownUser) {
|
||||
const av = $('drawer-avatar'), un = $('drawer-user-name');
|
||||
if (!av || !un) return;
|
||||
let name = knownUser ? String(knownUser) : '';
|
||||
if (!name) {
|
||||
try {
|
||||
const r = await req('GET', '/api/me');
|
||||
name = r && r.user ? String(r.user) : '';
|
||||
} catch (_) { return; /* 未启用认证时无 /api/me,保留默认占位 */ }
|
||||
}
|
||||
if (!name) return; // 未登录态(理论上不会出现,401 已自动跳登录页)
|
||||
av.textContent = userInitials(name);
|
||||
av.style.background = avatarColor(name);
|
||||
un.textContent = name;
|
||||
}
|
||||
// 侧栏底部已改成纯图标操作栏,不再展示登录用户名(用户信息仍在设置页「账户」里),
|
||||
// 所以原来的 loadDrawerUser 已随之删除。
|
||||
function userCardHtml(me) {
|
||||
return '<div class="settings-card user-card">' +
|
||||
'<div class="user-avatar" style="background:' + avatarColor(me) + '">' + esc(userInitials(me)) + '</div>' +
|
||||
@@ -351,9 +336,9 @@
|
||||
setActions('');
|
||||
setBody('<div class="set-scroll"><div class="empty-tip">加载中…</div></div>');
|
||||
// 单个 /api/me 判认证开关:启用时中间件保证已登录,user 必有;
|
||||
// 未启用时该路由 404 → 只是没有密码/登出卡,画像仍渲染(未认证 = 空串键隐式单用户)。
|
||||
// 未启用时回 auth:false + user:null → 只是没有密码/登出卡,画像仍渲染(未认证 = 空串键隐式单用户)。
|
||||
let me = null;
|
||||
try { const r = await req('GET', '/api/me'); if (r && r.user) me = r; } catch (_) { /* 404 等一律按无账户信息处理 */ }
|
||||
try { const r = await req('GET', '/api/me'); if (r && r.user) me = r; } catch (_) { /* 一律按无账户信息处理 */ }
|
||||
let p = null, pErr = '';
|
||||
try { p = await req('GET', '/api/profile'); } catch (e) { pErr = String((e && e.message) || e); }
|
||||
if (!ctx()) return;
|
||||
@@ -1700,13 +1685,16 @@
|
||||
const txt = f.secret ? (v ? '已配置' : '--') : (v ? String(v) : '--');
|
||||
return '<div class="cfg-kv"><label>' + esc(f.label || f.header) + '</label><b>' + esc(txt) + '</b></div>';
|
||||
}).join('');
|
||||
// 地址一律显示真实配置:预设地址只是容器形态的缺省值,本地形态是 127.0.0.1:809x,
|
||||
// 照抄预设会与「已连接」徽章自相矛盾。
|
||||
const urlTxt = (s ? (s.url || '') : p.url) || '';
|
||||
return '<div class="model-card' + (mode === 'disable' ? ' off' : '') + '"' +
|
||||
' onclick="mcpUI.' + (s ? 'editPreset' : 'addPreset') + '(\'' + att(p.key) + '\')">' +
|
||||
'<div class="model-card-head">' +
|
||||
'<span class="model-card-name">' + esc(p.label || p.key) + '</span>' +
|
||||
state +
|
||||
'</div>' +
|
||||
'<div class="cfg-kv"><label>地址</label><b>' + esc(p.url) + '</b></div>' + kv +
|
||||
'<div class="cfg-kv"><label>地址</label><b>' + esc(urlTxt) + '</b></div>' + kv +
|
||||
'</div>';
|
||||
}
|
||||
// MCP 卡:头部 = 名称 + url + mode 状态;体内 = headers 键值列表。整卡点击进入编辑。
|
||||
@@ -1735,7 +1723,8 @@
|
||||
'</div>';
|
||||
}
|
||||
// 弹窗打开:add 模式 (idx=null) → 空工作态;edit 模式 → 从当前配置复制。
|
||||
// presetKey 有值 = 内置服务模式:url/name/mode 是契约(只读),表单由预设的 fields 生成。
|
||||
// presetKey 有值 = 内置服务模式:name/mode 是契约(只读),url 可改(地址随部署形态变,预设只给缺省值),
|
||||
// 表单由预设的 fields 生成。
|
||||
function openMcpEditor(idx, presetKey) {
|
||||
const preset = presetKey ? (presetMcpList().find(p => p.key === presetKey) || null) : null;
|
||||
const add = idx == null;
|
||||
@@ -1768,9 +1757,11 @@
|
||||
}
|
||||
$('mce-title').textContent = (add ? '添加 ' : '编辑 ') + (preset ? preset.label : 'MCP 服务');
|
||||
$('mce-name').value = preset ? preset.key : (add ? '' : (s.name || ''));
|
||||
$('mce-url').value = preset ? preset.url : (add ? '' : (s.url || ''));
|
||||
// 预填优先级:当前配置 > 预设缺省值。url 不锁只读——容器形态是 mcp_*:3000,本地形态是
|
||||
// 127.0.0.1:809x,漏改这里用户就看不到也改不了真实地址。
|
||||
$('mce-url').value = add ? (preset ? preset.url : '') : (s.url || (preset ? preset.url : ''));
|
||||
$('mce-name').readOnly = !!preset;
|
||||
$('mce-url').readOnly = !!preset;
|
||||
$('mce-url').readOnly = false;
|
||||
// 运行配置里的 timeout_ms 已被 config.js 填上缺省值,所以这里显示的就是当前生效值(没配则为 60000)。
|
||||
$('mce-timeout').value = add || s.timeout_ms == null ? '' : String(s.timeout_ms);
|
||||
// 预设的 mode 是契约(asr / image_task 必须 skill 才不会把一堆转写/生成工具塞进每轮工具表),
|
||||
@@ -1903,11 +1894,13 @@
|
||||
if (!Number.isFinite(tmo) || tmo < 1000 || tmo > 600000) throw new Error('超时要填 1000 ~ 600000 毫秒(留空 = 默认 60s)');
|
||||
tmo = Math.round(tmo);
|
||||
}
|
||||
// 内置服务的 name/url 是契约(表单只读),只有自定义服务才从输入框取
|
||||
const name = preset ? preset.key : $('mce-name').value.trim();
|
||||
const url = preset ? preset.url : $('mce-url').value.trim();
|
||||
const headers = preset ? presetHeaders() : plainHeaders();
|
||||
// name 是契约(预设的服务名固定);url 不再是契约——展示与写盘均以 config 为准,
|
||||
// 输入框里默认的就是预设值,改了就存。
|
||||
const add = mcpEdit.idx < 0;
|
||||
const cur = add ? {} : (SET.cfgMcp[mcpEdit.idx] || {});
|
||||
const name = preset ? preset.key : $('mce-name').value.trim();
|
||||
const url = $('mce-url').value.trim();
|
||||
const headers = preset ? presetHeaders() : plainHeaders();
|
||||
if (add) {
|
||||
if (!url) throw new Error('请填写 url');
|
||||
const obj = { url };
|
||||
@@ -1917,12 +1910,10 @@
|
||||
if (Object.keys(headers).length) obj.headers = headers;
|
||||
edits.push({ op: 'append', path: ['mcp_servers'], value: obj });
|
||||
} else {
|
||||
const cur = SET.cfgMcp[mcpEdit.idx] || {};
|
||||
if (!preset) {
|
||||
if (!url) throw new Error('请填写 url');
|
||||
if (name !== (cur.name || '')) edits.push({ path: ['mcp_servers', mcpEdit.idx, 'name'], value: name });
|
||||
if (url !== (cur.url || '')) edits.push({ path: ['mcp_servers', mcpEdit.idx, 'url'], value: url });
|
||||
}
|
||||
// 自定义服务:name/url 都能改;内置服务只允许改 url(name/mode 是契约)
|
||||
if (!url) throw new Error('请填写 url');
|
||||
if (!preset && name !== (cur.name || '')) edits.push({ path: ['mcp_servers', mcpEdit.idx, 'name'], value: name });
|
||||
if (url !== (cur.url || '')) edits.push({ path: ['mcp_servers', mcpEdit.idx, 'url'], value: url });
|
||||
// mode:默认值不写进文件(选 advertise 就删键)
|
||||
if ((cur.mode || 'advertise') !== mode) edits.push(mode === 'advertise'
|
||||
? { path: ['mcp_servers', mcpEdit.idx, 'mode'], op: 'delete' }
|
||||
@@ -2057,29 +2048,32 @@
|
||||
drawerMQ.addEventListener('change', e => openDrawer(e.matches));
|
||||
// 页面加载时校验 cookie 身份:防止 localStorage 旧 token 通过 autoRestore 恢复错误用户
|
||||
(async () => {
|
||||
let verifiedUser = null; // 校验结果顺带复用给侧边栏,避免同一次加载请求两次 /api/me
|
||||
try {
|
||||
const res = await fetch('/api/me', { credentials: 'include' });
|
||||
if (res.ok) {
|
||||
const j = await res.json();
|
||||
if (!j.user) {
|
||||
if (j.auth === false) {
|
||||
// 未启用多用户认证(单用户自用,本地模式即此形态):没有登录态可校验,全部设置可见
|
||||
SET.role = 'admin';
|
||||
SET.authEnabled = false;
|
||||
} else if (!j.user) {
|
||||
// cookie 无效或用户已从配置中移除 → 彻底清理所有前端凭据并跳登录
|
||||
localStorage.removeItem('agent_token');
|
||||
sessionStorage.removeItem('agent_creds'); // 旧版本遗留的 Basic 凭据,顺带清理
|
||||
location.href = '/logout';
|
||||
return;
|
||||
} else {
|
||||
SET.role = j.role === 'admin' ? 'admin' : 'user';
|
||||
SET.authEnabled = true;
|
||||
}
|
||||
verifiedUser = String(j.user);
|
||||
SET.role = j.role === 'admin' ? 'admin' : 'user';
|
||||
SET.authEnabled = true;
|
||||
} else {
|
||||
// /api/me 404 = 未启用多用户认证:单用户自用,全部设置可见(用户管理页因 auth 关闭而隐藏)
|
||||
// 兜底:改契约之前的旧后端在未启用认证时该路由不存在(404),按未启用处理
|
||||
SET.role = 'admin';
|
||||
SET.authEnabled = false;
|
||||
}
|
||||
} catch (_) { /* 网络错误放过,让后续请求正常走 */ }
|
||||
loadSessionList();
|
||||
loadDrawerUser(verifiedUser); // 侧边栏底部展示真实登录用户(未启用鉴权/拉取失败时静默回退默认占位)
|
||||
// 侧栏底部已是纯图标操作栏(不展示用户信息),不再需要 loadDrawerUser
|
||||
// 会话深链 /?s=<session_id>:数据页面(/app/{task_id}/...)的「返回会话」FAB 用——
|
||||
// task_id 即会话 id(engine 里 1:1),启动时消费一次即 replaceState 抹掉参数,
|
||||
// 避免刷新/分享时被钉回该会话;会话已删则 openSession 自行报错,落在 welcome。
|
||||
|
||||
@@ -47,9 +47,19 @@ router.use('/app', (req, res) => {
|
||||
if (!sessionId) return notFound(res, '会话不存在');
|
||||
if (!engine.getSession(sessionId)) return notFound(res, '会话不存在');
|
||||
const appRoot = path.join(engine.taskDirOf(sessionId), '.app');
|
||||
// 页面根目录的地址必须带尾斜杠:浏览器按「最后一段是否目录」算相对链接的基址,
|
||||
// /app/<会话> 会把 ./table.html 解析成 /app/table.html(白屏)。
|
||||
// 空余路径 = 就是在要根目录 → 补斜杠再跳转;比让每个技能模板改绝对链接可靠。
|
||||
// 注意不能靠 stat 判断:下面空余路径会先被映射成 index.html,永远不是目录。
|
||||
const rest = segs.slice(1).join('/');
|
||||
if (!rest && !req.path.endsWith('/')) {
|
||||
const q = req.originalUrl.indexOf('?');
|
||||
return res.redirect(302, (q < 0 ? req.originalUrl : req.originalUrl.slice(0, q)) + '/'
|
||||
+ (q < 0 ? '' : req.originalUrl.slice(q)));
|
||||
}
|
||||
let abs;
|
||||
try {
|
||||
abs = resolveInTask(appRoot, segs.slice(1).join('/') || 'index.html'); // 越界即挡,限 .app/ 子树
|
||||
abs = resolveInTask(appRoot, rest || 'index.html'); // 越界即挡,限 .app/ 子树
|
||||
} catch (_) {
|
||||
return notFound(res, '非法路径');
|
||||
}
|
||||
|
||||
@@ -76,6 +76,72 @@ router.post('/:id/files', upload.array('files', 10), function (req, res) {
|
||||
}
|
||||
});
|
||||
|
||||
// ---------- 会话文件树(桌面端左栏唯一浏览入口) ----------
|
||||
// 为什么不复用 GET /:id/files:那个接口同步递归整棵目录,会话里一旦有大项目 /
|
||||
// node_modules,单线程 core 会被卡死(连 SSE 一起挂)。这里一律「一次一层」、
|
||||
// 忽略大目录、限量返回,客户端展开才请求下一层。
|
||||
const TREE_IGNORE_DIRS = new Set([
|
||||
'node_modules', '.git', 'dist', 'build', 'out', 'target', '.venv', 'venv',
|
||||
'__pycache__', '.next', '.cache', 'coverage', '.idea', '.vscode',
|
||||
]);
|
||||
const TREE_MAX = 500;
|
||||
|
||||
// 相对路径 → 会话根内的绝对路径。字面 + realpath 双重校验,防符号链接跳出会话目录。
|
||||
function resolveTreeAbs(rootAbs, rel) {
|
||||
const p = String(rel || '').replace(/^[\\/]+/, '');
|
||||
const abs = p ? path.resolve(rootAbs, p) : rootAbs;
|
||||
const inside = (root, x) => x === root || x.startsWith(root + path.sep);
|
||||
if (!inside(rootAbs, abs)) throw new Error('路径越界');
|
||||
let realAbs = abs, realRoot = rootAbs;
|
||||
try { realAbs = fs.realpathSync(abs); } catch (_) {}
|
||||
try { realRoot = fs.realpathSync(rootAbs); } catch (_) {}
|
||||
if (!inside(realRoot, realAbs)) throw new Error('路径越界');
|
||||
return abs;
|
||||
}
|
||||
|
||||
router.get('/:id/tree', function (req, res) {
|
||||
const session = engine.getSession(req.params.id);
|
||||
if (!session) return res.status(404).json({ error: '会话不存在' });
|
||||
const rootAbs = path.resolve(engine.taskDirOf(req.params.id));
|
||||
const rel = String(req.query.dir || '').replace(/^[\\/]+/, '').replace(/\/+$/, '');
|
||||
let abs;
|
||||
try { abs = resolveTreeAbs(rootAbs, rel); }
|
||||
catch (err) { return res.status(400).json({ error: err.message }); }
|
||||
let st;
|
||||
try { st = fs.statSync(abs); } catch (_) { return res.status(404).json({ error: '目录不存在' }); }
|
||||
if (!st.isDirectory()) return res.status(400).json({ error: '不是目录' });
|
||||
const showHidden = req.query.hidden === '1';
|
||||
const entries = [];
|
||||
try {
|
||||
for (const e of fs.readdirSync(abs, { withFileTypes: true })) {
|
||||
if (!showHidden && e.name.startsWith('.')) continue;
|
||||
const childRel = rel ? rel + '/' + e.name : e.name;
|
||||
if (e.isSymbolicLink()) { entries.push({ name: e.name, rel: childRel, type: 'link' }); continue; }
|
||||
if (e.isDirectory()) {
|
||||
entries.push({ name: e.name, rel: childRel, type: 'dir', ignored: TREE_IGNORE_DIRS.has(e.name) });
|
||||
} else if (e.isFile()) {
|
||||
let size = null;
|
||||
try { size = fs.statSync(path.join(abs, e.name)).size; } catch (_) {}
|
||||
entries.push({ name: e.name, rel: childRel, type: 'file', size: size });
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
return res.status(500).json({ error: String((err && err.message) || err) });
|
||||
}
|
||||
// 排序:正常目录 → 正常文件 → 被忽略的大目录(灰显沉底);同类按名称
|
||||
entries.sort((a, b) =>
|
||||
(a.ignored ? 1 : 0) - (b.ignored ? 1 : 0) ||
|
||||
(a.type === 'dir' ? 0 : 1) - (b.type === 'dir' ? 0 : 1) ||
|
||||
(a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
||||
res.json({
|
||||
root: rootAbs,
|
||||
dir: rel,
|
||||
total: entries.length,
|
||||
capped: entries.length > TREE_MAX,
|
||||
entries: entries.slice(0, TREE_MAX),
|
||||
});
|
||||
});
|
||||
|
||||
router.get('/:id/files', function (req, res) {
|
||||
try {
|
||||
const session = engine.getSession(req.params.id);
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
// 本地桌面端(local/ 启动器)专用:唤起系统原生目录选择器。
|
||||
// 只在 AGENT_LOCAL_PICK=1 时挂载(见 server.js),服务器形态根本不加载本文件。
|
||||
//
|
||||
// 为什么必须走后端:浏览器拿不到本机目录的绝对路径(<input webkitdirectory> 只给相对名),
|
||||
// 要真实路径只能调系统对话框。必须 execFile 异步——同步执行会阻塞事件循环,所有会话的 SSE
|
||||
// 都会卡住,直到用户关掉对话框。用户取消不是错误,回 { path: '' };
|
||||
// 其它失败(无对话框、权限被拒、超时)要带原因回给前端,别让用户以为是自己取消了。
|
||||
const express = require('express');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const { execFile } = require('child_process');
|
||||
const engine = require('../engine');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
function sendErr(res, err) {
|
||||
const code = (err && err.status_code) || 500;
|
||||
res.status(code).json({ error: String((err && err.message) || err) });
|
||||
}
|
||||
|
||||
// 各平台可用的对话框后端。mac 用 osascript;Linux 依次试 zenity / kdialog。
|
||||
// cancelRe / cancelExit 区分「用户取消」和「真失败」:
|
||||
// osascript 取消时 stderr 是 "User canceled. (-128)",别的报错(如自动化权限被拒)不能当取消;
|
||||
// zenity/kdialog 取消统一退出码 1。
|
||||
const CANDIDATES = process.platform === 'darwin'
|
||||
? [{ cmd: 'osascript', args: ['-e', 'POSIX path of (choose folder with prompt "选择这个会话的工作目录")'], cancelRe: /User canceled|-128/ }]
|
||||
: process.platform === 'linux'
|
||||
? [
|
||||
{ cmd: 'zenity', args: ['--file-selection', '--directory', '--title=选择这个会话的工作目录'], cancelExit: 1 },
|
||||
{ cmd: 'kdialog', args: ['--getexistingdirectory', os.homedir(), '--title', '选择这个会话的工作目录'], cancelExit: 1 },
|
||||
]
|
||||
: [];
|
||||
|
||||
// 跑一个对话框,resolve 出选中的路径(用户取消 → '')。
|
||||
// 超时兜底:对话框可能被用户晾在那儿,这里到点 kill,避免永远挂着一个 child。
|
||||
function runPicker(cand, timeoutMs) {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(cand.cmd, cand.args, { timeout: timeoutMs, maxBuffer: 1 << 20 }, (err, stdout, stderr) => {
|
||||
if (!err) return resolve(String(stdout || '').trim());
|
||||
if (err.code === 'ENOENT') return reject(Object.assign(new Error('no-cmd'), { no_cmd: true }));
|
||||
if (err.killed) return reject(Object.assign(new Error('选择目录超时,请重试'), { status_code: 408 }));
|
||||
const msg = String(stderr || '').trim();
|
||||
if (cand.cancelRe && cand.cancelRe.test(msg)) return resolve('');
|
||||
if (cand.cancelExit && err.code === cand.cancelExit) return resolve('');
|
||||
reject(Object.assign(new Error('目录选择器失败:' + (msg || ('退出码 ' + err.code))), { status_code: 500 }));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function pickDir() {
|
||||
if (!CANDIDATES.length) {
|
||||
throw Object.assign(new Error('当前系统不支持目录选择(仅支持 macOS / Linux)'), { status_code: 501 });
|
||||
}
|
||||
for (const cand of CANDIDATES) {
|
||||
try {
|
||||
const out = await runPicker(cand, 120000);
|
||||
if (!out) return '';
|
||||
// osascript 的 POSIX path 带尾斜杠,去掉让展示一致;选到根 '/' 时保底保留。
|
||||
return out.replace(/\/+$/, '') || '/';
|
||||
} catch (e) {
|
||||
if (e.no_cmd) continue; // 换下一个后端
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
throw Object.assign(new Error('没有可用的目录选择器(Linux 请安装 zenity 或 kdialog)'), { status_code: 501 });
|
||||
}
|
||||
|
||||
// ---------- 原生文件管理器(仅本机会话目录内) ----------
|
||||
// 文件树的列表接口已上收为通用的 GET /api/sessions/:id/tree(桌面端服务器形态也用),
|
||||
// 这里只剩「在 Finder / 终端中打开」这两个只能开在本机的动作。
|
||||
function isInside(rootAbs, abs) {
|
||||
return abs === rootAbs || abs.startsWith(rootAbs + path.sep);
|
||||
}
|
||||
|
||||
// 会话内相对路径 → 绝对路径,双重越界校验(字面 + realpath,防符号链接跳出)。
|
||||
function resolveInside(sessionId, rel) {
|
||||
const sid = String(sessionId || '').trim();
|
||||
if (!sid) throw Object.assign(new Error('缺少 session'), { status_code: 400 });
|
||||
const session = engine.getSession(sid);
|
||||
if (!session) throw Object.assign(new Error('会话不存在'), { status_code: 404 });
|
||||
const rootAbs = path.resolve(engine.taskDirOf(sid));
|
||||
const p = String(rel || '').replace(/^[\\/]+/, '');
|
||||
const abs = p ? path.resolve(rootAbs, p) : rootAbs;
|
||||
if (!isInside(rootAbs, abs)) throw Object.assign(new Error('路径越界'), { status_code: 400 });
|
||||
let real = abs, rootReal = rootAbs;
|
||||
try { real = fs.realpathSync(abs); } catch (_) {}
|
||||
try { rootReal = fs.realpathSync(rootAbs); } catch (_) {}
|
||||
if (!isInside(rootReal, real)) throw Object.assign(new Error('路径越界'), { status_code: 400 });
|
||||
return { rootAbs: rootAbs, abs: abs };
|
||||
}
|
||||
|
||||
// execFile 异步(同步会阻塞事件循环);open/xdg-open 一般秒回,10s 兜底。
|
||||
function runOpen(cmd, args) {
|
||||
return new Promise((resolve, reject) => {
|
||||
execFile(cmd, args, { timeout: 10000 }, (err) => {
|
||||
if (!err) return resolve();
|
||||
if (err.code === 'ENOENT') return reject(Object.assign(new Error('no-cmd'), { no_cmd: true }));
|
||||
if (err.killed) return reject(Object.assign(new Error('系统调用超时'), { status_code: 504 }));
|
||||
reject(Object.assign(new Error('打开失败:' + (err.message || err.code)), { status_code: 500 }));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function dirOf(abs) {
|
||||
try { return fs.statSync(abs).isDirectory() ? abs : path.dirname(abs); } catch (_) { return path.dirname(abs); }
|
||||
}
|
||||
|
||||
// 在系统文件管理器里打开:目录→直接打开;文件→定位所在目录(mac 用 open -R 直接选中该文件)。
|
||||
router.post('/reveal', (req, res) => {
|
||||
let target;
|
||||
try { target = resolveInside(req.body && req.body.session, req.body && req.body.path); }
|
||||
catch (err) { return sendErr(res, err); }
|
||||
const abs = target.abs;
|
||||
let isDir = false;
|
||||
try { isDir = fs.statSync(abs).isDirectory(); } catch (_) {}
|
||||
const mac = process.platform === 'darwin';
|
||||
const cmd = mac ? 'open' : 'xdg-open';
|
||||
const args = mac && !isDir ? ['-R', abs] : [isDir ? abs : path.dirname(abs)];
|
||||
runOpen(cmd, args).then(() => res.json({ ok: true })).catch(err => sendErr(res, err));
|
||||
});
|
||||
|
||||
// 在系统终端里打开该目录。mac 用 open -a Terminal;Linux 尽力而为。
|
||||
router.post('/terminal', (req, res) => {
|
||||
let target;
|
||||
try { target = resolveInside(req.body && req.body.session, req.body && req.body.path); }
|
||||
catch (err) { return sendErr(res, err); }
|
||||
const dir = dirOf(target.abs);
|
||||
if (process.platform === 'darwin') {
|
||||
runOpen('open', ['-a', 'Terminal', dir]).then(() => res.json({ ok: true })).catch(err => sendErr(res, err));
|
||||
return;
|
||||
}
|
||||
runOpen('x-terminal-emulator', ['--working-directory=' + dir])
|
||||
.then(() => res.json({ ok: true }))
|
||||
.catch(() => runOpen('gnome-terminal', ['--working-directory=' + dir])
|
||||
.then(() => res.json({ ok: true }))
|
||||
.catch(() => sendErr(res, Object.assign(new Error('没有可用的终端程序'), { status_code: 501 }))));
|
||||
});
|
||||
|
||||
// 能力探测:前端凭这个决定是否显示「工作目录」入口(拿不到就整条隐藏)。
|
||||
router.get('/info', (req, res) => {
|
||||
res.json({ enabled: true, platform: process.platform, workspace_root: engine.getConfig().workspace_root });
|
||||
});
|
||||
|
||||
router.post('/pick-dir', (req, res) => {
|
||||
pickDir().then(p => res.json({ path: p })).catch(err => sendErr(res, err));
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -84,7 +84,9 @@ router.post('/', wrap((req, res) => {
|
||||
const assistantType = String((req.body && req.body.assistant_type) || 'secretary').trim().slice(0, 32) || 'secretary';
|
||||
// 创建者取认证中间件的 req.user(不信客户端传参);未启用认证时为空串
|
||||
const user = String(req.user || '').trim().slice(0, 64);
|
||||
const session = engine.createSession(title, modelId, assistantType, user);
|
||||
// 手选工作目录(仅本地端前端会传,服务器前端从不带;不传/空串 = 老行为,见 engine.createSession)
|
||||
const workDir = String((req.body && req.body.work_dir) || '').trim();
|
||||
const session = engine.createSession(title, modelId, assistantType, user, workDir);
|
||||
log.info('task', (req.user || '-') + ' 新建任务 ' + session.id + '「' + (session.title || '未命名') + '」model=' + (modelId || '自动') + ' type=' + (session.assistant_type || 'secretary'));
|
||||
res.json(session);
|
||||
}));
|
||||
|
||||
+19
-3
@@ -19,6 +19,11 @@ const log = require('./log');
|
||||
const cfg = loadConfig(process.env.AGENT_CONFIG);
|
||||
log.setLevel(cfg.log_level); // 分级日志开关(log.js;config.yml log_level,重启生效)
|
||||
llm.setPayloadTrim(cfg.agent); // 历史重放的重负载占位裁剪规则(llm.buildMessages;config agent.trim.rules)
|
||||
// system prompt 的「环境段」:executor.url 为空 = 命令在本机 spawn(本地桌面形态,无沙箱),
|
||||
// 有值 = 送进 agent-executor 容器(每会话隔离)。用这个信号而不是另立开关,因为它就是
|
||||
// 隔离与否的成因(resolveInTask 的 /tmp 重写、WIDE_SCOPE 同理)。启动日志跟一行,方便核对。
|
||||
llm.setEnvMode(cfg.executor.url ? 'server' : 'local');
|
||||
log.info('startup', '环境形态:' + (cfg.executor.url ? 'server(executor 容器隔离)' : 'local(本机 spawn,无沙箱)'));
|
||||
// 启动时把生效规则打出来:工具名拼错不会报错(MCP 工具要等发现后才存在),只能靠这行核对。
|
||||
log.info('startup', '历史重放占位裁剪:' + (((cfg.agent && cfg.agent.trim && cfg.agent.trim.rules) || [])
|
||||
.map(r => r.tool + '/' + r.side + '(轮≥' + r.rounds + ',回合≥' + r.turns + ')').join(', ') || '关闭'));
|
||||
@@ -67,6 +72,12 @@ require('./routes/preview-proxy').earlyGuard(app);
|
||||
|
||||
app.use(express.static(path.join(__dirname, 'public')));
|
||||
|
||||
// 本地桌面端(local/ 启动器)专用:原生目录选择器。AGENT_LOCAL_PICK=1 才挂,
|
||||
// 服务器形态零影响(不加载 routes/local.js,/api/local/* 一律 404)。
|
||||
if (String(process.env.AGENT_LOCAL_PICK || '') === '1') {
|
||||
app.use('/api/local', require('./routes/local'));
|
||||
}
|
||||
|
||||
app.use('/api/sessions', require('./routes/sessions'));
|
||||
app.use('/api/sessions', require('./routes/messages'));
|
||||
app.use('/api/sessions', require('./routes/files'));
|
||||
@@ -169,6 +180,9 @@ app.get('/api/health', (req, res) => {
|
||||
});
|
||||
|
||||
const PORT = process.env.PORT || cfg.port;
|
||||
// 监听地址:不设 = 0.0.0.0(容器/服务器形态,宿主机端口映射靠它)。
|
||||
// 本机 local 模式由 local/start.sh 注入 HOST=127.0.0.1:单机自用不该让同一局域网的人直接访问。
|
||||
const HOST = String(process.env.HOST || '').trim();
|
||||
|
||||
// 启动成功后把模型实际收到的各部分 dump 到文件方便人工核对(data_root 默认 ./data,
|
||||
// 宿主机对应 <repo>/data/prompt.txt,已被 gitignore)。包含:
|
||||
@@ -211,8 +225,8 @@ mcp.init(cfg).then(async () => {
|
||||
} catch (e) {
|
||||
log.warn('startup', '技能列表生成失败:' + e.message);
|
||||
}
|
||||
server.listen(PORT, () => {
|
||||
log.info('startup', 'Agent server listening on ' + PORT);
|
||||
const onListening = () => {
|
||||
log.info('startup', 'Agent server listening on ' + (HOST ? HOST + ':' : '') + PORT);
|
||||
log.info('startup', ' public_link=' + ((cfg.public_link || {}).base_url || '未配置(mint_public_link 不可用)'));
|
||||
log.info('startup', ' workspace_root=' + cfg.workspace_root);
|
||||
log.info('startup', ' data_root=' + cfg.data_root);
|
||||
@@ -231,7 +245,9 @@ mcp.init(cfg).then(async () => {
|
||||
} catch (e) {
|
||||
log.warn('startup', 'prompt dump 失败:' + e.message);
|
||||
}
|
||||
});
|
||||
};
|
||||
if (HOST) server.listen(PORT, HOST, onListening);
|
||||
else server.listen(PORT, onListening);
|
||||
});
|
||||
|
||||
// 优雅退出(照抄 executor/server.js 的 shutdown 形态):node 在容器里是 PID 1,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
- You run on the user's own machine with their permissions, not a sandbox; other
|
||||
conversations share it and `/tmp` is the system temp dir. Work inside the
|
||||
working directory; treat everything outside it as the user's.
|
||||
- `python3` may be missing. Install what a task needs; Python packages go into
|
||||
`$AGENT_SKILLS_DEPS`. If a skill fails, cat its own `AGENTS.md`
|
||||
(`"$(dirname "$AGENT_SKILLS_DEPS")/<skill>/AGENTS.md"`) and follow it.
|
||||
- Installs and big downloads stay silent until they end. Run them in the background
|
||||
with output to a log file and poll that file every ~10s, instead of one long timeout.
|
||||
- Slow or failing installs and downloads: switch mirrors instead of retrying — pip
|
||||
`-i https://pypi.tuna.tsinghua.edu.cn/simple`, npm `--registry=https://registry.npmmirror.com`,
|
||||
GitHub URLs prefixed with `https://gh-proxy.com/`, Homebrew mirrors or let the user install.
|
||||
@@ -0,0 +1,16 @@
|
||||
- Linux container, isolated per conversation: you see the working directory, a
|
||||
session-scoped `/tmp`, read-only `/workspace/skills`, and system paths — never
|
||||
other sessions.
|
||||
- `terminal` runs POSIX sh (`/bin/sh` is dash); use `bash` for scripts.
|
||||
- `/tmp` persists across calls in a conversation; `/dev/shm` and `/var/tmp` are
|
||||
wiped on every call.
|
||||
- Python 3.11; system packages are read-only. Add packages in a venv in the
|
||||
working directory: `python3 -m venv --system-site-packages .venv`, then
|
||||
`.venv/bin/pip` / `.venv/bin/python`. Don't reinstall packages that are
|
||||
already importable.
|
||||
- System packages can't be installed at runtime (`apt-get` fails). A missing CLI
|
||||
tool must be added on the server — tell the user.
|
||||
- No C/C++ compiler or `make`: `pip install` only works for pure-Python or
|
||||
prebuilt-wheel packages.
|
||||
- Chinese text in matplotlib: set `font.sans-serif` to `Noto Sans CJK SC`. For
|
||||
ZIPs with GBK filenames, use `unar` or `7z x` to avoid garbled names.
|
||||
@@ -56,19 +56,4 @@ domain must never be hand-rolled.
|
||||
|
||||
## Environment
|
||||
|
||||
- Linux container, isolated per conversation: you see the working directory, a
|
||||
session-scoped `/tmp`, read-only `/workspace/skills`, and system paths — never
|
||||
other sessions.
|
||||
- `terminal` runs POSIX sh (`/bin/sh` is dash); use `bash` for scripts.
|
||||
- `/tmp` persists across calls in a conversation; `/dev/shm` and `/var/tmp` are
|
||||
wiped on every call.
|
||||
- Python 3.11; system packages are read-only. Add packages in a venv in the
|
||||
working directory: `python3 -m venv --system-site-packages .venv`, then
|
||||
`.venv/bin/pip` / `.venv/bin/python`. Don't reinstall packages that are
|
||||
already importable.
|
||||
- System packages can't be installed at runtime (`apt-get` fails). A missing CLI
|
||||
tool must be added on the server — tell the user.
|
||||
- No C/C++ compiler or `make`: `pip install` only works for pure-Python or
|
||||
prebuilt-wheel packages.
|
||||
- Chinese text in matplotlib: set `font.sans-serif` to `Noto Sans CJK SC`. For
|
||||
ZIPs with GBK filenames, use `unar` or `7z x` to avoid garbled names.
|
||||
{APP_ENV_SECTION}
|
||||
|
||||
@@ -19,30 +19,65 @@ const memory = require('../memory'); // recall 工具的数据面(日记翻阅
|
||||
const BUILTIN_TOOL_DEFS = require('./definitions.json');
|
||||
|
||||
// ---------- 路径沙箱 ----------
|
||||
function resolveInTask(taskDir, p) {
|
||||
// 文件工具的可见范围(AGENT_FILE_SCOPE,默认 session):
|
||||
// session = 锁在会话目录。与 executor 容器里的物理视图一致,是服务器形态。
|
||||
// workspace= 放宽到 workspace_root。本地桌面端形态(不起 executor、单机单用户):
|
||||
// AI 要能操作你指定的整个工作目录,而不是它的一个子目录。
|
||||
// 纯 env 接线与 EXECUTOR_URL/ASR_URL 同类:这是部署形态,不是平台配置。
|
||||
const WIDE_SCOPE = String(process.env.AGENT_FILE_SCOPE || '').trim().toLowerCase() === 'workspace';
|
||||
|
||||
function resolveInTask(taskDir, p, rootDir) {
|
||||
if (typeof p !== 'string' || !p.trim()) throw new Error('路径不能为空');
|
||||
const taskRoot = path.resolve(taskDir);
|
||||
let abs;
|
||||
if (path.isAbsolute(p)) {
|
||||
abs = path.normalize(p);
|
||||
// /tmp → <taskDir>/.tmp:与 executor 容器的 bind 对齐(容器内 /tmp 即会话 .tmp,
|
||||
// terminal 写 /tmp/x,core 侧实体在 <taskDir>/.tmp/x)。先 normalize 再重写,
|
||||
// 重写后仍走下方越界校验,无穿越风险。
|
||||
if (abs === '/tmp') abs = path.join(path.resolve(taskDir), '.tmp');
|
||||
else if (abs.startsWith('/tmp/')) abs = path.join(path.resolve(taskDir), '.tmp', abs.slice(5));
|
||||
// workspace 形态【不重写】:本地 terminal 是真 spawn,写的就是本机 /tmp,
|
||||
// 两边必须指向同一处——否则 AI 自己刚写到 /tmp 的文件,自己 read_file 读不到。
|
||||
if (!WIDE_SCOPE) {
|
||||
if (abs === '/tmp') abs = path.join(taskRoot, '.tmp');
|
||||
else if (abs.startsWith('/tmp/')) abs = path.join(taskRoot, '.tmp', abs.slice(5));
|
||||
}
|
||||
} else {
|
||||
abs = path.resolve(taskDir, p);
|
||||
// 相对路径永远相对会话目录(AI 的 cwd 就在那里),不随 rootDir 漂移。
|
||||
abs = path.resolve(taskRoot, p);
|
||||
}
|
||||
const root = path.resolve(taskDir);
|
||||
if (abs !== root && !abs.startsWith(root + path.sep)) {
|
||||
throw new Error('路径越界(只允许任务目录内操作):' + p);
|
||||
const root = path.resolve(rootDir || taskRoot);
|
||||
const inRoot = abs === root || abs.startsWith(root + path.sep);
|
||||
// workspace 形态额外放行本机 /tmp:AI 与 terminal 共用的临时区。
|
||||
const inTmp = WIDE_SCOPE && (abs === '/tmp' || abs.startsWith('/tmp/'));
|
||||
if (!inRoot && !inTmp) {
|
||||
throw new Error((rootDir ? '路径越界(只允许工作目录内操作):' : '路径越界(只允许任务目录内操作):') + p);
|
||||
}
|
||||
return abs;
|
||||
}
|
||||
|
||||
// 工具层允许的根:session 形态 = 会话目录;workspace 形态 = workspace_root。
|
||||
// 只给「业务工具」用;路由层(文件 API/公网短链/data-page)与 @历史会话仍按会话目录校验。
|
||||
function fsRoot(ctx) {
|
||||
// 手选工作目录的会话:AI 的一切文件操作都在这个真实目录里(本地端,不建 task-* 子目录)。
|
||||
// 优先于 WIDE_SCOPE 的 workspace_root 兜底。
|
||||
if (ctx.workDir) return ctx.workDir;
|
||||
if (!WIDE_SCOPE) return ctx.taskDir;
|
||||
return (ctx.cfg && ctx.cfg.workspace_root) || ctx.taskDir;
|
||||
}
|
||||
|
||||
function relOf(taskDir, abs) {
|
||||
return path.relative(path.resolve(taskDir), abs) || '.';
|
||||
}
|
||||
|
||||
// 展示用路径:会话目录内保持相对(跟以前一致,省 token);
|
||||
// 宽根模式下文件可能在会话目录外,那就回绝对路径——否则模型看到的是
|
||||
// ../../../../tmp/x 这种既难读、又容易被它当成会话内路径去二次拼接的名字。
|
||||
function dispPath(ctx, abs) {
|
||||
const rel = relOf(ctx.taskDir, abs);
|
||||
if (rel === '..' || rel.startsWith('..' + path.sep)) return abs;
|
||||
return rel;
|
||||
}
|
||||
|
||||
// ---------- 跨会话路径:@<会话id>/<rel>(历史只读,「看一眼」可过墙,「字节落地」只走 copy_path) ----------
|
||||
// 背景:terminal 在远端 executor 容器里跑(compose:wrapper 启动即 unmount host-tasks),
|
||||
// 别的会话目录在 shell 物理视图里根本不存在;core 进程内的文件工具又被 resolveInTask
|
||||
@@ -58,13 +93,15 @@ function resolvePastPath(ctx, p) {
|
||||
const sid = m[1];
|
||||
const rel = m[2] || '.';
|
||||
if (!/^task-[0-9A-Za-z_\-]+$/.test(sid)) throw new Error('@ 后需会话 id, 形如 task-YYYYMMDD-NNN: ' + sid);
|
||||
const s = ctx.db.prepare('SELECT id, user, title FROM sessions WHERE id = ?').get(sid);
|
||||
const s = ctx.db.prepare('SELECT id, user, title, work_dir FROM sessions WHERE id = ?').get(sid);
|
||||
if (!s) throw new Error('会话不存在: ' + sid);
|
||||
const me = ctx.db.prepare('SELECT user FROM sessions WHERE id = ?').get(ctx.sessionId);
|
||||
if (String(s.user || '') !== String((me && me.user) || '')) throw new Error('无权访问该会话: ' + sid);
|
||||
// 目标会话若手选了工作目录,@<会话> 也必须指向那个真实目录,而不是 workspace_root/<id>。
|
||||
const wd = String(s.work_dir || '');
|
||||
const root = String((ctx.cfg && ctx.cfg.workspace_root) || '');
|
||||
if (!root) throw new Error('workspace_root 未配置');
|
||||
const dir = path.join(root, sid);
|
||||
const dir = wd || (root ? path.join(root, sid) : '');
|
||||
if (!dir) throw new Error('workspace_root 未配置');
|
||||
return { sid: sid, title: s.title || sid, dir: dir, abs: resolveInTask(dir, rel) };
|
||||
}
|
||||
|
||||
@@ -284,7 +321,7 @@ async function toolReadFile(ctx, args) {
|
||||
const inner = relOf(past.dir, abs);
|
||||
disp = inner === '.' ? '@' + past.sid : '@' + past.sid + '/' + inner;
|
||||
} else {
|
||||
abs = resolveInTask(ctx.taskDir, args.path);
|
||||
abs = resolveInTask(ctx.taskDir, args.path, fsRoot(ctx));
|
||||
// 本会话沿用绝对路径做展示(大纲/首 1KB 头,历史行为不变);历史会话只暴露 @<sid>/<rel> 形,
|
||||
// 不把别的会话的 workspace_root 绝对路径喂进上下文。
|
||||
disp = abs;
|
||||
@@ -370,7 +407,7 @@ async function toolListDirectory(ctx, args) {
|
||||
const inner = relOf(past.dir, abs);
|
||||
prefix = '@' + past.sid + (inner === '.' ? '/' : '/' + inner + '/');
|
||||
} else {
|
||||
abs = resolveInTask(ctx.taskDir, p || '.');
|
||||
abs = resolveInTask(ctx.taskDir, p || '.', fsRoot(ctx));
|
||||
const inner = relOf(ctx.taskDir, abs);
|
||||
prefix = inner === '.' ? '' : inner + '/';
|
||||
}
|
||||
@@ -408,14 +445,15 @@ async function toolCopyPath(ctx, args) {
|
||||
const dp = String(args.destination_path || '').trim();
|
||||
if (!sp || !dp) throw new Error('source_path 与 destination_path 都必填');
|
||||
if (dp.startsWith('@')) throw new Error('destination_path 不支持 @ (历史只读)');
|
||||
const dst = resolveInTask(ctx.taskDir, dp);
|
||||
if (path.resolve(dst) === path.resolve(ctx.taskDir)) throw new Error('destination_path 不能是任务目录本身');
|
||||
const root = fsRoot(ctx);
|
||||
const dst = resolveInTask(ctx.taskDir, dp, root);
|
||||
if (path.resolve(dst) === path.resolve(root)) throw new Error('destination_path 不能是任务目录本身');
|
||||
let src;
|
||||
if (sp.startsWith('@')) {
|
||||
const past = resolvePastPath(ctx, sp);
|
||||
src = past.abs;
|
||||
} else {
|
||||
src = resolveInTask(ctx.taskDir, sp);
|
||||
src = resolveInTask(ctx.taskDir, sp, root);
|
||||
}
|
||||
if (path.resolve(src) === path.resolve(dst)) throw new Error('源与目标相同');
|
||||
let lst;
|
||||
@@ -435,17 +473,17 @@ async function toolCopyPath(ctx, args) {
|
||||
}
|
||||
let exists = true;
|
||||
try { await fsp.stat(dst); } catch (_) { exists = false; }
|
||||
if (exists) throw new Error('目标已存在, 拒绝覆盖: ' + relOf(ctx.taskDir, dst));
|
||||
if (exists) throw new Error('目标已存在, 拒绝覆盖: ' + dispPath(ctx, dst));
|
||||
await fsp.mkdir(path.dirname(dst), { recursive: true });
|
||||
await fsp.cp(src, dst, { recursive: true });
|
||||
recordFile(ctx, dst); // 文件表只记普通文件(目录自然跳过),供前端/微信附件展示
|
||||
const sizeNote = budget ? ' (' + budget.files + ' files, ' + Math.round(budget.bytes / 1024) + ' KB)' : '';
|
||||
return '已复制 ' + sp + ' -> ' + relOf(ctx.taskDir, dst) + sizeNote;
|
||||
return '已复制 ' + sp + ' -> ' + dispPath(ctx, dst) + sizeNote;
|
||||
}
|
||||
|
||||
async function toolWriteFile(ctx, args) {
|
||||
if (String(args.path || '').trim().startsWith('@')) throw new Error('write_file 不支持 @ 路径(历史只读;要改旧成果先 copy_path 导入本会话)');
|
||||
const abs = resolveInTask(ctx.taskDir, args.path);
|
||||
const abs = resolveInTask(ctx.taskDir, args.path, fsRoot(ctx));
|
||||
// 纵深防御:引擎 checkToolArgs 已把 null 判缺,但直调 executor(测试等)不经过它;
|
||||
// 旧版 `?? ''` 会把 null 洗成空串静默清空已有文件,这里显式拒绝。
|
||||
if (args.content == null) throw new Error('write_file 缺少参数 content(写空文件请显式传空字符串 "")');
|
||||
@@ -456,7 +494,7 @@ async function toolWriteFile(ctx, args) {
|
||||
await fsp.writeFile(abs, String(args.content), 'utf8');
|
||||
recordFile(ctx, abs);
|
||||
const nbytes = Buffer.byteLength(String(args.content), 'utf8');
|
||||
const rel = relOf(ctx.taskDir, abs);
|
||||
const rel = dispPath(ctx, abs);
|
||||
// 区分新建/覆盖:「原 M 字节」是给模型的止损信号(盲覆盖大文件时能立刻察觉)。
|
||||
return st
|
||||
? '已覆盖文件 ' + rel + '(' + nbytes + ' 字节,原 ' + st.size + ' 字节)'
|
||||
@@ -686,7 +724,7 @@ function applyEdit(text, edit, i) {
|
||||
// 错误信息告知模型已应用了多少、需重新 read_file。
|
||||
async function toolEditFile(ctx, args) {
|
||||
if (String(args.path || '').trim().startsWith('@')) throw new Error('edit_file 不支持 @ 路径(历史只读;要改旧成果先 copy_path 导入本会话)');
|
||||
const abs = resolveInTask(ctx.taskDir, args.path);
|
||||
const abs = resolveInTask(ctx.taskDir, args.path, fsRoot(ctx));
|
||||
let st;
|
||||
try { st = await fsp.stat(abs); }
|
||||
catch (_) { throw new Error('文件不存在:' + args.path); }
|
||||
@@ -711,7 +749,7 @@ async function toolEditFile(ctx, args) {
|
||||
? '(前 ' + applied + ' 处编辑已应用并保存,文件已变化,请重新 read_file 后再继续)'
|
||||
: '(文件未改动)'));
|
||||
}
|
||||
return '已成功应用 ' + applied + ' 处编辑到 ' + relOf(ctx.taskDir, abs);
|
||||
return '已成功应用 ' + applied + ' 处编辑到 ' + dispPath(ctx, abs);
|
||||
}
|
||||
|
||||
// 对齐 Zed select_terminal_output_lines:head/tail 各自取行;同时给时中间空一行;不去重叠;0 合法。
|
||||
@@ -751,7 +789,7 @@ async function toolTerminal(ctx, args) {
|
||||
const timeout = args.timeout_ms || cfg.terminal.default_timeout_ms;
|
||||
const maxChars = cfg.terminal.max_output_chars;
|
||||
let cwd = ctx.taskDir;
|
||||
if (args.cd) cwd = resolveInTask(ctx.taskDir, args.cd);
|
||||
if (args.cd) cwd = resolveInTask(ctx.taskDir, args.cd, fsRoot(ctx));
|
||||
if (!fs.existsSync(cwd)) throw new Error('工作目录不存在:' + cwd);
|
||||
|
||||
// 配了 executor.url(或 env EXECUTOR_URL):命令交给远端 agent-executor 执行,文本拼回与本地完全一致。
|
||||
@@ -1166,9 +1204,13 @@ function recordFile(ctx, abs) {
|
||||
try {
|
||||
const st = fs.statSync(abs);
|
||||
if (!st.isFile()) return;
|
||||
// 宽根模式(本地)下写在会话目录之外的文件不进附件表:表里的 filename 是会话相对路径,
|
||||
// 存个 '../x' 会让前端按会话去取,最终只能拿到 400。
|
||||
const rel = relOf(ctx.taskDir, abs);
|
||||
if (rel === '..' || rel.startsWith('..' + path.sep)) return;
|
||||
ctx.db.prepare(
|
||||
'INSERT INTO files (session_id, filename, size, created_at) VALUES (?,?,?,?)'
|
||||
).run(ctx.sessionId, relOf(ctx.taskDir, abs), st.size, Date.now());
|
||||
).run(ctx.sessionId, rel, st.size, Date.now());
|
||||
} catch (_) { /* 文件表仅用于展示,失败不影响主流程 */ }
|
||||
}
|
||||
|
||||
@@ -1177,7 +1219,11 @@ function recordFile(ctx, abs) {
|
||||
// 而 ctx.taskDir 就是会话目录,relOf 的结果正是取用侧(routes/public-files.js)要的 rel。
|
||||
async function toolMintPublicLink(ctx, args) {
|
||||
const pl = (ctx.cfg && ctx.cfg.public_link) || {};
|
||||
if (!pl.base_url) throw new Error('public_link.base_url 未配置,无法签发公网链接');
|
||||
// 本地桌面形态没有公网前缀,但用户就在这台机器上:回环地址签出来的链接照样点得开。
|
||||
// 与 visit_url 的回落同源(都不写配置,靠 HOST 判断形态);容器/服务器形态 HOST 为空
|
||||
// → localOrigin 返回 '' → 仍是原来那句报错,行为不变。
|
||||
const base = String(pl.base_url || '').replace(/\/+$/, '') || localOrigin(ctx.cfg);
|
||||
if (!base) throw new Error('public_link.base_url 未配置,无法签发公网链接');
|
||||
const abs = resolveInTask(ctx.taskDir, args.path);
|
||||
const rel = relOf(ctx.taskDir, abs);
|
||||
if (rel === '.') throw new Error('path 要指向一个文件,不能是任务目录本身');
|
||||
@@ -1191,7 +1237,7 @@ async function toolMintPublicLink(ctx, args) {
|
||||
throw new Error('path 经符号链接指向了任务目录之外,拒绝签发');
|
||||
}
|
||||
const id = publicFiles.mint({ sessionId: ctx.sessionId, rel, ttlMs: pl.ttl_ms });
|
||||
return pl.base_url + '/p/' + id;
|
||||
return base + '/p/' + id;
|
||||
}
|
||||
|
||||
// schedule:用户全部定时任务的生命周期(op 分派,规范见 docs/tool-design.md)。
|
||||
@@ -1577,6 +1623,15 @@ function toolDb(ctx, args) {
|
||||
// visit_url(front matter 可选):页面产物类技能声明访问路径模板,run 成功后在本层拼
|
||||
// public_link.base_url(与 mint_public_link 同源)追加完整「访问地址」——技能进程跑在
|
||||
// executor 隔离视图里不知道公网前缀,AI 拿到相对路径就会原样转给用户,而相对路径打不开。
|
||||
// 本地桌面形态的对外前缀:只有监听在回环地址(local/start.sh 注入 HOST=127.0.0.1)才认。
|
||||
// 容器/服务器形态 HOST 为空(= 0.0.0.0),不能凭空造一个 127.0.0.1 给远端用户,照旧只给站内路径。
|
||||
function localOrigin(cfg) {
|
||||
const host = String(process.env.HOST || '').trim().toLowerCase();
|
||||
if (host !== '127.0.0.1' && host !== 'localhost' && host !== '::1') return '';
|
||||
const port = String(process.env.PORT || (cfg && cfg.port) || '').trim();
|
||||
return port ? 'http://127.0.0.1:' + port : '';
|
||||
}
|
||||
|
||||
async function runSkillWithVisit(ctx, name, inputArgs) {
|
||||
const out = await skills.runSkill(ctx, name, inputArgs);
|
||||
let fm;
|
||||
@@ -1590,9 +1645,11 @@ async function runSkillWithVisit(ctx, name, inputArgs) {
|
||||
const rel = tpl.replace(/\{task_id\}/g, ctx.sessionId || path.basename(path.resolve(ctx.taskDir || '')));
|
||||
const pl = (ctx.cfg && ctx.cfg.public_link) || {};
|
||||
const base = String(pl.base_url || '').trim().replace(/\/+$/, '');
|
||||
return out + '\n访问地址:' + (base
|
||||
? base + rel
|
||||
: rel + '(站内路径:public_link.base_url 未配置,拼不出公网前缀)');
|
||||
if (base) return out + '\n访问地址:' + base + rel;
|
||||
// 没有公网前缀时别只给站内路径:本地形态用户就在这台机器上,回环地址就是能直接点开的地址。
|
||||
const origin = localOrigin(ctx.cfg);
|
||||
if (origin) return out + '\n访问地址:' + origin + rel;
|
||||
return out + '\n访问地址:' + rel + '(站内路径:public_link.base_url 未配置,拼不出公网前缀)';
|
||||
}
|
||||
|
||||
const SKILL_USAGE = 'skill 用法:{"op":"list"} / {"op":"get","name":"<技能名>"} / {"op":"run","name":"<技能名>","args":{...}}';
|
||||
|
||||
@@ -280,10 +280,10 @@ async function runSkill(ctx, skillName, inputArgs) {
|
||||
throw new SkillExecutionError('技能 ' + skillName + ' 缺少入口 run.py 或 run.sh', 1);
|
||||
}
|
||||
|
||||
// cwd:远端取会话目录(executor 侧命中 session 隔离,技能看到的 /workspace/tasks/<sid>
|
||||
// 与 core 侧是同一份数据,absolutizeArgs 产出的绝对路径因此有效);缺 taskDir 时退回
|
||||
// 技能目录(退化为旧行为)。本地无隔离诉求,仍以技能目录为 cwd。
|
||||
const execCwd = rexec.isRemote(ctx.cfg) ? (ctx.taskDir || dir) : dir;
|
||||
// cwd 一律取会话任务目录(技能契约,见 skills/README §6:技能按 cwd 读写会话数据,
|
||||
// data-page 这类会往 cwd 下写 .app/)。旧代码在「无 executor」分支退回技能目录,
|
||||
// 等于假设线上一定走远端;本地桌面形态(本机 spawn)下会把所有按 cwd 干活的技能打歪。
|
||||
const execCwd = ctx.taskDir || dir;
|
||||
const timeoutMs = (ctx.cfg && ctx.cfg.skills && ctx.cfg.skills.timeout_ms) || 120000;
|
||||
log.info('skills', '执行 ' + skillName + ':' + entry + ' ' + cmdArgs.join(' ') + '(cwd=' + execCwd + ')');
|
||||
return runEntry(ctx, entry, cmdArgs, execCwd, timeoutMs);
|
||||
|
||||
@@ -0,0 +1,431 @@
|
||||
# 本地端(local 模式):设计与交接
|
||||
|
||||
> 本文是 `local/` 的设计说明 + 交接单。
|
||||
> **状态:已在 macOS 真机(12.7.6 / x86_64 / Node 22.21 / python3 3.10,本机无 ffmpeg)按第 6 节
|
||||
> 清单逐项跑过,结果见第 5 节。** 只剩三件依赖人工交互或外部环境的事没覆盖(真实选目录弹窗、
|
||||
> 真浏览器打开、装 ffmpeg 之后的链路),见第 6 节。
|
||||
|
||||
## 1. 目标
|
||||
|
||||
把同一个 `agent-core` 直接跑在本机(macOS / Linux),**不装 Docker、不起 executor**,形态类似
|
||||
桌面 agent:给它一个工作目录,它在这个目录里放开手脚干活。
|
||||
|
||||
明确的设计约束(都来自讨论):
|
||||
|
||||
- **和服务器端同一份代码**,不 fork 新仓库、不长期开 branch;靠运行时开关分叉
|
||||
- **`app/` 最小化改动**(最终只有 2 个后端文件,前端 0 改动)
|
||||
- **组件按需**:node 必需;ffmpeg 决定语音;python3 决定 Python 类技能能否执行(非 Python 技能如 `office` 不受影响)
|
||||
- **Windows 暂时不做**(本机执行依赖 POSIX 语义,见第 7 节)
|
||||
- 不用 Docker(用户明确否决)
|
||||
|
||||
基线版本:`v2.5.0`(服务器端最后一个纯容器部署版本)。
|
||||
|
||||
## 2. 与服务器形态的差异(只有五处)
|
||||
|
||||
| 差异 | 服务器 | 本地 | 由谁注入 |
|
||||
|---|---|---|---|
|
||||
| 命令在哪跑 | `agent-executor` 容器(mount/pid namespace 隔离) | 本机 `spawn`(**无沙箱**) | `EXECUTOR_URL` 留空 → 现成分支,未改代码 |
|
||||
| 文件工具的根 | 会话目录 `tasks/<会话id>/` | 指定的工作目录 | `AGENT_FILE_SCOPE=workspace` |
|
||||
| 监听地址 | `0.0.0.0` | `127.0.0.1` | `HOST=127.0.0.1` |
|
||||
| 对外链接(`mint_public_link` / `visit_url`) | `public_link.base_url` 拼公网短链 | 没有公网前缀时改拼 `http://127.0.0.1:<PORT>/p/<id>` | 复用 `localOrigin()`,靠 `HOST` 判断形态,不写配置 |
|
||||
| 读图回传给模型 | 签公网短链,上游服务器来拉 | 上游拉不到回环地址,改为内联 base64 `data:` URL | `AGENT_IMAGE_INLINE=1` |
|
||||
|
||||
后四项是本次新增的开关。**四个都不设置时,行为与 v2.5.0 完全一致**(容器部署不受影响)。
|
||||
|
||||
## 3. 本次改动清单
|
||||
|
||||
### 后端(`app/`)
|
||||
|
||||
| 文件 | 改动 |
|
||||
|---|---|
|
||||
| `app/server/server.js` | 读 `HOST` 环境变量;有值则 `server.listen(PORT, HOST, cb)`,无值维持 `listen(PORT, cb)`(= `0.0.0.0`)。启动日志带上 host |
|
||||
| `app/server/tools/executor.js` | 新增 `WIDE_SCOPE`(由 `AGENT_FILE_SCOPE=workspace` 打开)与 `fsRoot(ctx)`;`resolveInTask()` 增加可选第三参 `rootDir`;6 个业务工具的调用点改为传 `fsRoot(ctx)`;`recordFile()` 跳过会话目录之外的文件;`mint_public_link` 在没有 `public_link.base_url` 时改用 `localOrigin()`(回环地址) |
|
||||
| `app/server/engine.js` | `mintImageUrl` 在没有 `public_link.base_url` 且 `AGENT_IMAGE_INLINE=1` 时,把待回传的图内联成 `data:` URL(先做同样的 realpath 越界复核;>1.5MB 仍降级) |
|
||||
| `app/server/routes/files.js` | 新增 `GET /:id/tree`(桌面端左栏文件树用:单层懒加载、忽略大目录、上限 500、越界双重校验) |
|
||||
|
||||
`resolveInTask` 的两个分叉点:
|
||||
|
||||
1. **根**:`rootDir` 给了就按它校验(workspace 形态 = `workspace_root`),否则仍按会话目录
|
||||
2. **`/tmp`**:`session` 形态保持「重定向到 `<会话>/.tmp`」;`workspace` 形态**不重定向**,并把真实
|
||||
`/tmp` 纳入允许范围
|
||||
|
||||
### 刻意没有动的(重要)
|
||||
|
||||
- `resolvePastPath()`(`@<会话id>/...` 跨会话只读)—— 仍锁在对方会话目录
|
||||
- `routes/public-files.js`、`routes/data-page.js` —— 公网短链与 data-page 仍按会话目录校验
|
||||
- `mint_public_link` —— 路径校验仍是会话目录语义;只是没有公网前缀时改用回环地址签发(见 §2)
|
||||
- 前端 —— 本地模式没有专属前端代码;左栏文件树是桌面端共用的(见下)
|
||||
|
||||
> 追加:文件树最初只给 local 用,后来上收为桌面端通用能力 —— `/tree` 移到 `routes/files.js`,
|
||||
> 服务器形态的桌面端也用它取代「输入行右侧的旧文件面板」(含下载/删除);`reveal`、`terminal`、
|
||||
> `pick-dir` 仍只在 `AGENT_LOCAL_PICK=1` 下挂载(它们开的是跑 core 那台机器的窗口)。
|
||||
|
||||
### 新增 `local/`
|
||||
|
||||
| 文件 | 作用 |
|
||||
|---|---|
|
||||
| `start.sh` | 主入口:探测 → 首次生成配置 → 装依赖 → 起 core + MCP → 守护重启。**后台化**:拉起真正的启动器就返回 |
|
||||
| `stop.sh` | 停止启动器(按 `supervisor.pid` → core 的父进程 → 占端口的进程,三级兜底),幂等 |
|
||||
| `config.example.yml` | **仅作参考,不被读取**;实际配置由 `start.sh` 生成到 `config.local.yml` |
|
||||
| `README.md` | 给使用者的说明(含安全边界、已知限制) |
|
||||
|
||||
`.gitignore` 增加 `local/.runtime/`、`local/config.local.yml`。
|
||||
|
||||
> 曾经有一个 `start.command`(macOS 双击入口),已删除:Finder 里双击 `.command` 常被系统当文本
|
||||
> 预览打开、不执行,而且它补的 PATH 探测和 `start.sh` 重复。现在唯一入口就是 `./local/start.sh`。
|
||||
|
||||
### 3.1 真机验证阶段补的修改
|
||||
|
||||
首次在 mac 上跑,暴露了下面这些;都不是设计变更,是实现跟设计对不上或漏了边界:
|
||||
|
||||
| 文件 | 改动 | 为的什么 |
|
||||
|---|---|---|
|
||||
| `local/start.sh` | 新增启动即弹出的**状态页**(`local/.runtime/status.html`,每秒自刷新) | 启动时终端看不到进度;失败页既没有应用名也没有日志,用户无从判断 |
|
||||
| `local/start.sh` | 依赖检测从「node_modules 在不在」改成**逐包实测 + `.agent-installed` 时间戳** | `npm install` 中途失败会留下半成品目录(目录在、包不全),原逻辑会永远跳过安装,core 起来就 require 失败 |
|
||||
| `local/start.sh` | `npm install` 输出 `tee` 到 `local/.runtime/npm-install.log`,并嵌进状态页 | 失败时只有终端能看到,滚过去就没了 |
|
||||
| `local/start.sh` | MCP 默认端口 3101~3104 → **8091~8094**;新增「PORT 撞 MCP 端口就拒绝启动」检查 | 跟 core 的 8090 连号,同时堵掉「换端口时不小心占用 MCP 端口」→ 子进程 bind 失败、静默降级 |
|
||||
| `local/start.sh` | 已有配置里的 MCP 端口与本次启动不一致时**告警** | 配置永不覆盖,改了默认值/用了 `MCP_*_PORT` 时,旧配置会让 core 静默发现不到工具 |
|
||||
| `local/start.sh` | 生成的 YAML 里路径**加引号** | 用户选的目录带空格/`:`/`#` 时会被 YAML 解析坏 |
|
||||
| `local/start.sh` | 没 ffmpeg 时**不再启动** `mcp_asr`(原实现无条件启动,与 4.3 的设计说明不符) | 否则模型拿到一个必然失败的 `transcribe_audio` 工具;同时少一个 `0.0.0.0` 监听 |
|
||||
| `local/start.sh` | 默认**后台化**(`AGENT_LOCAL_DETACH=1`),拉起启动器后 1 秒返回;新增 `local/stop.sh` | 用户不想让一个终端窗口永远挂着;Finder 里关窗口很容易误杀服务,后台 + 显式 `stop.sh` 更可控 |
|
||||
| `local/start.sh` | 没 node 时在入口就拦下(生成配置之前),并在终端打出安装方式 | 原来先进「选工作目录」、写好配置才报「后台进程立刻退出了」,用户白选一次,而且日志里只有两行启动横幅,看不出原因 |
|
||||
| `local/start.sh` | 同一轮只开一个状态页标签(`UI_OPENED`) | `ui_init` 已经开过一次,失败时 `ui_fail` 又开一个,同一个页面两个标签 |
|
||||
| `local/start.sh` | 「已在运行」改看 `supervisor.pid`(pid 存活且命令行是本脚本),health 只做兜底 | 只看 health 时 core 还没起来的几秒内连跑两次,会拉起两个启动器抢同一端口(实测:互相 `EADDRINUSE` 重启,`stop.sh` 只能停一个) |
|
||||
| `local/start.sh` | 首次安装**不自动跳转**,停在状态页给「打开应用」按钮;后续启动才 2 秒自动跳 | 首次装完先让用户看完「怎么配模型」再进去,别一上来就甩进空界面 |
|
||||
| `app/server/tools/executor.js` | 新增 `dispPath()`:会话目录外用绝对路径回显 | 宽根模式下写 `/tmp/x` 会回 `../../../../tmp/x`,模型容易当会话内路径二次拼接 |
|
||||
| `app/package-lock.json` | `resolved` 从腾讯云**内网镜像**改为公共 registry | 原 lockfile 把 tarball 钉在 `mirrors.tencentyun.com`(只有腾讯云 VPC 内能解析),外部机器 `npm install` 必失败,且换 `NPM_REGISTRY` 也无效 |
|
||||
|
||||
## 4. 关键设计决定(含「为什么」,别推翻)
|
||||
|
||||
### 4.1 开关用环境变量,不进 `config.yml`
|
||||
|
||||
`EXECUTOR_URL` / `ASR_URL` 已经是「部署接线走 env」的先例,本地模式属于同一类(部署形态),
|
||||
不是平台配置。好处是 `app/` 只需改 2 个文件,不必动 `config.js` 的 `DEFAULTS` 和
|
||||
`config.example.yml`(改配置项必须两处同步,是仓库的硬规则)。
|
||||
|
||||
### 4.2 配置**首次生成后永不覆盖**
|
||||
|
||||
`config.local.yml` 里既有启动器生成的字段(`workspace_root` / `skills_root`),也有用户在网页里
|
||||
配的东西(`platforms`、API Key、MCP headers)。每次启动重写会直接冲掉后者。
|
||||
|
||||
推论:**能力变化不能靠改配置实现**,只能靠 env / 起不起子进程 / 软链(见 4.3、4.4)。
|
||||
|
||||
### 4.3 ffmpeg 是运行时能力,与配置解耦
|
||||
|
||||
`routes/asr.js` 直接读 `process.env.ASR_URL`,`/api/asr/status` 在 `ASR_URL` 为空时返回
|
||||
`enabled:false`,前端 `voice.js` 据此**自动隐藏麦克风**。所以:
|
||||
|
||||
- 有 ffmpeg → 启动器起 `mcp_asr` + 注入 `ASR_URL`
|
||||
- 没 ffmpeg → 不起、不注入 → 麦克风自动消失
|
||||
|
||||
装完 ffmpeg 后**重跑脚本**即生效,配置文件一个字不用改。
|
||||
|
||||
### 4.4 技能目录用软链固定指向仓库,不再按 python3 有无切换
|
||||
|
||||
配置里永远写 `skills_root: <仓库>/local/.runtime/skills`(首次生成后不覆盖),启动器每次都重建这个
|
||||
软链,恒指向 `<仓库>/skills`。
|
||||
|
||||
早期版本在「没有 python3」时把它指向一个空目录,想的是“别让模型看到跑不了的工具”。两个问题:
|
||||
|
||||
1. **技能不一定是 Python 的**。`office` 只有 `SKILL.md` + `scripts/office`,模型在 `terminal` 里调
|
||||
`office <cmd>`,完全不需要 python3——一刀切会把这类技能一并藏掉。
|
||||
2. **没必要防**。`skills.js` 的 `runEntry` 对 `spawn` 的 `error` 有处理,缺解释器时模型拿到的是
|
||||
「技能入口启动失败:spawn python3 ENOENT」,干净可读、不崩不挂。模型据此自己装解释器或模块,
|
||||
装完继续跑即可。
|
||||
|
||||
所以现在只有一种行为:技能总是可见;python3 缺失只影响 `run.py` 类技能能否执行。装好 python3 后
|
||||
(若在 core 启动时 `PATH` 已有的目录里,如 brew 的 `/opt/homebrew/bin`)无需重启即生效,否则重跑脚本。
|
||||
|
||||
**没有改 `skills.js` 一行代码。**
|
||||
|
||||
### 4.5 启动器必须是守护进程
|
||||
|
||||
`routes/system.js` 的重启实现是「校验配置 → `process.exit(0)` → 等 Docker restart 策略拉起」,
|
||||
注释里写明「非 docker 部署不会自动重启」。本地没有 Docker,如果启动器只是前台 `node`,
|
||||
用户配完模型点一次「重启」,服务就再也回不来。
|
||||
|
||||
所以主循环是:起 core → 等健康 → `wait` → 非用户中断就 1 秒后重启;连续异常退出 5 次才停
|
||||
(防配置写坏导致无限刷屏)。`exit 0` 视为用户主动重启。
|
||||
|
||||
### 4.6 四个 MCP 必须分端口
|
||||
|
||||
容器里它们是四个独立容器、都监听 3000;本地同机必须错开(默认 **8091~8094**,紧跟 core 的 8090)。
|
||||
另外**它们的启动参数不统一**,这是个坑:
|
||||
|
||||
| 服务 | 启动方式 | 说明 |
|
||||
|---|---|---|
|
||||
| `web_search` | `node server.js --http --host --port` | 默认 host 已经是 `127.0.0.1` |
|
||||
| `image_task` | `node src/mcp-server.js --http --host --port` | 默认 `0.0.0.0` |
|
||||
| `video_task` | `node src/mcp-server.js --http --host --port` | 默认 `0.0.0.0` |
|
||||
| `mcp_asr` | **只认 `PORT` 环境变量** | 不解析 argv,且 `listen` 没带 host(= `0.0.0.0`) |
|
||||
|
||||
所以 `start.sh` 拆成 `start_mcp_flags` / `start_mcp_env` 两个函数,别合并。
|
||||
|
||||
### 4.7 `/tmp` 语义为什么分叉
|
||||
|
||||
服务器端:executor 在 session 模式下执行 `mount --bind <会话>/.tmp /tmp`,容器内 `/tmp` 的物理
|
||||
落点就是宿主 `<会话>/.tmp`。core 的文件工具必须去同一处找,否则 AI 用 terminal 写 `/tmp/x` 后
|
||||
`read_file /tmp/x` 读不到。所以那份「重定向」是**必需的**,不是 bug。
|
||||
|
||||
本地端:`toolTerminal` 是真 `spawn('/bin/sh')`,`/tmp` 就是本机 `/tmp`。此时再重定向就会造成
|
||||
「terminal 写真实 /tmp、file 工具读会话 .tmp」的错位——这正是 `AGENT_FILE_SCOPE=workspace`
|
||||
要关掉重定向的原因。
|
||||
|
||||
### 4.8 `skills_root` 的默认值陷阱
|
||||
|
||||
`skills.skills_root` 留空时默认取 `workspace_root` 的**同级** `skills` 目录。本地把
|
||||
`workspace_root` 指到用户选的目录后,默认值会变成不存在的 `<用户目录>/../skills`。
|
||||
因此生成的配置必须显式写死 `skills_root`。
|
||||
|
||||
### 4.9 状态页:静态文件 + `meta refresh`,不起 HTTP 服务
|
||||
|
||||
启动时终端窗口不一定在前台,失败时也可能已经滚过去。所以启动就打开
|
||||
`local/.runtime/status.html`,并让它能自己更新:
|
||||
|
||||
- 脚本把状态写进 `local/.runtime/ui/` 下的几个小文件(`title` / `steps` / `busy` / `logpath` /
|
||||
`error` / `redirect`),`ui_render` 把它们拼成整页;页面用 `<meta http-equiv="refresh" content="1">`
|
||||
每秒重读一次。不需要常驻服务,所以「连 node 都没装」的环境也能打开。
|
||||
- 长步骤(`npm install`、等 core 健康检查)另起一个**心跳子进程**每秒重绘,页面上就能看到
|
||||
已经过了多少秒 + 当前日志的尾巴(npm 输出、core 启动报错)。
|
||||
- 状态全部落文件而不是留 shell 变量:心跳子进程拿到的是 fork 时的快照,用变量会越刷越旧。
|
||||
- 成功时:**首次安装**(配置是本次刚生成的)页面停在「已启动」,只给一个「打开应用」按钮,
|
||||
用户自己点(先看完下面的首次使用提示);**后续启动**写入 `redirect`,2 秒后自动进应用
|
||||
(同一个标签页,不多开窗)。
|
||||
- 失败时页面保留错误说明和日志尾部,并把完整日志路径写在页面上。
|
||||
- 默认只在 macOS 自动弹出(`AGENT_LOCAL_UI=auto`),Linux 服务器上要显式 `AGENT_LOCAL_UI=1`;
|
||||
无论弹不弹,页面都会生成。
|
||||
- 渲染先写临时文件再 `mv`:浏览器随时可能在刷新,不能让它读到半截 HTML;临时名用 `mktemp`
|
||||
而不是 `$$`——`$$` 在子 shell 里仍是主 shell 的 PID,心跳与主流程同时渲染会撞车。
|
||||
|
||||
### 4.10 依赖检测为什么不能只看 `node_modules` 目录
|
||||
|
||||
`npm install` 失败(断网、源不对)会留下一堆**空目录**:`app/node_modules` 在、`express` 目录
|
||||
也在,但里面没东西。原逻辑「目录存在且不比 `package.json` 旧」会判定为已安装,以后每次启动
|
||||
都跳过安装,core 起来立刻 `require` 失败——用户看到的是「装依赖那步过了,但服务起不来」。
|
||||
|
||||
现在的判定:
|
||||
|
||||
1. 逐个直接依赖检查 `node_modules/<dep>/package.json` 是否存在(比 `require.resolve` 可靠:
|
||||
`@modelcontextprotocol/sdk` 这类纯 ESM 包的 `exports.require` 指向的文件根本不存在,
|
||||
`require.resolve` 会误判成「没装」);
|
||||
2. 装成功后 `touch node_modules/.agent-installed`,只有 `package.json` 比它新才重装
|
||||
(npm 在「已经是最新」时不会更新 `node_modules` 的 mtime,只比目录 mtime 会每启动都白跑一次)。
|
||||
|
||||
### 4.11 后台化 + 显式 `stop.sh`,以及「已在运行」怎么判
|
||||
|
||||
用户不想为了跑一个本地服务永久占着一个终端窗口(而且关窗口可能连带杀掉进程)。所以:
|
||||
|
||||
- `start.sh` 自己**只做入口**:首次配置生成(要 tty 弹窗)→ `nohup` 拉起真正的启动器 → 1 秒后
|
||||
打印地址/状态页/停止命令并 `exit 0`。`AGENT_LOCAL_DETACHED=1` 是子进程标记,防无限重入。
|
||||
- 停止统一走 `local/stop.sh`。它按「`supervisor.pid` → core 的父进程 → 占端口的进程」三级兜底:
|
||||
只杀 core 会被守护循环重新拉起,所以必须能认出**启动器**。命令行是相对路径(`sh ./local/start.sh`),
|
||||
`pgrep -f` 匹配不到绝对路径,所以第一选择是 pid 文件。
|
||||
- 前台模式保留:`AGENT_LOCAL_DETACH=0 ./local/start.sh`(看实时日志、`Ctrl-C` 停)。
|
||||
|
||||
「已在运行」的判定不能只看 `/api/health`:core 起来要几秒(先起 MCP,首次还要装依赖),
|
||||
这期间再跟一次 `start.sh` 就会拉起第二个启动器,两个 core 抢同一个端口——一个被守护循环
|
||||
反复 `EADDRINUSE` 重启,而 `stop.sh` 只认 pid 文件里那一个,等于停不干净(已实测复现)。
|
||||
改成先看 `supervisor.pid`(子进程一启动就写,秒级就绪;`kill -0` + 命令行含 `start.sh` 防 pid 被回收),
|
||||
health 只作为「端口上有服务但不是本启动器拉起的」兜底提示。
|
||||
|
||||
### 4.12 依赖安装:源探测 + 换源重试 + 本地缓存(只在 `local/` 里做)
|
||||
|
||||
首装联网是逃不掉的,但「哪个源能用、卡住了怎么办」不该让用户想。启动器的策略:
|
||||
|
||||
1. **已装齐 → 不联网**(逐包检查 + `.agent-installed` 时间戳,见 4.10);
|
||||
2. **缓存命中 → 解压**:装成功后把 `node_modules` 打成
|
||||
`<平台>-<架构>-abi<ABI>-<依赖哈希>.tgz` 放 `~/.cache/agent-local/`;原生模块与 ABI 绑定,
|
||||
所以文件名必须含 ABI(`process.versions.modules`)。换 clone / 删 `node_modules` 都走这里,
|
||||
秒级且零网络;只留最近 3 份。
|
||||
3. **缓存未命中 → 选源安装**:并行探 `npmmirror` 与官方源(各 3 秒超时),取最快的;
|
||||
结果缓存一天。**只用命令行参数传源,绝不写 `~/.npmrc`**。
|
||||
4. **失败换源**:仅当用的是公共源(npmmirror / 官方)时换下一个重试,换源成功就记住;
|
||||
用户显式指定或公司私有源不兜底(乱兜底可能装错东西)。重试前先删半成品 `node_modules`。
|
||||
5. **看门狗**:npm 10 + Node 22 在断网时既不报错也不退出(已知的
|
||||
`Exit handler never called`,实测卡死超过 2 分钟),所以每次 `npm install` 都带超时,
|
||||
超时就 `SIGKILL` 整棵树再换源。
|
||||
6. **报错翻译**:把 npm 原文归成「网络没通 / 缺编译工具链(`xcode-select --install`)/
|
||||
没有写权限 / 源没响应」,状态页只显示这一句,原文仍完整落在 `npm-install.log`。
|
||||
|
||||
两个容易踩的实现细节(都踩过):
|
||||
|
||||
- `kill_tree` 不能把参数先赋给变量再递归:POSIX sh 没有局部变量,递归会覆盖它,回到外层
|
||||
kill 的是子进程而不是原本那个。
|
||||
- 看门狗只用 `SIGKILL`:先 `TERM` 会先干掉外壳让 npm 变成孤儿(`PPID=1`),`kill -0` 判不到,
|
||||
再想硬杀就找不到它了。
|
||||
|
||||
### 4.13 Python 包:不预装,交给模型按提示词装进 `skills/deps`
|
||||
|
||||
服务器上技能依赖由 `agent-executor-init` 一次性装进 `skills/deps`(compose 再把它放进
|
||||
`PYTHONPATH`)。本地没有这套东西,`start.sh` 也不去跑 pip——安装时机、镜像源、半成品清理
|
||||
是另一整套逻辑,收益不抵成本。做法改成「缺了再装」:
|
||||
|
||||
- `start.sh` 起 core 时注入 `PYTHONPATH=<仓库>/skills/deps`(**原本就有**)与
|
||||
`AGENT_SKILLS_DEPS=<仓库>/skills/deps`(新增,只为把路径交给模型)。
|
||||
`terminal` 与技能子进程都继承 core 的 env,所以装进去的东西**下次运行就能 import**,不用重启。
|
||||
- `templates/env-local.txt` 把原来的「永远不要自己装任何东西」改成「缺模块就装进
|
||||
`$AGENT_SKILLS_DEPS` 再重试」——**只给路径,不给命令**,怎么装由模型自己决定。
|
||||
技能失败时 stdout+stderr 是合并回给模型的,它能看到 `ModuleNotFoundError` 自己判断。
|
||||
- 为什么给一个目录而不是让模型自己选:那个目录已经在 `PYTHONPATH` 里,装进去下次运行就能
|
||||
import;而不指定位置的话,它很可能装到别处(或去改系统 Python)。pip 对 `--target` 的
|
||||
PEP 668 拦截明确豁免(`pip/_internal/commands/install.py`),所以这条路在 Homebrew 那种
|
||||
externally-managed 解释器上也走得通——但这话不写进提示词,交给模型自己判断。
|
||||
- 缺 `python3` 本体时也放给模型自己处理:本地形态是「用户自己的机器 + 用户自己的 agent」,
|
||||
目标是把事做成,而不是把它当生产环境保护。提示词只告诉它**装到哪**(Python 包进
|
||||
`$AGENT_SKILLS_DEPS`),不写条件也不写禁令——要不要先知会用户,交给模型按场合自己判断。
|
||||
- 技能自己的 `requirements.txt` 一律**不写版本号**:服务端 init 用
|
||||
`pip install --no-index --dry-run` 探测,pin 到与镜像不同的版本会让探测失败 → 真的往
|
||||
`skills/deps` 装一份旧的,而 `PYTHONPATH` 优先于系统 site-packages,等于反向遮蔽镜像包。
|
||||
|
||||
需要系统库的包(`weasyprint` → pango/cairo)pip 装不了,仍需用户 `brew install`;这类不在
|
||||
自动修复范围内,模型只报结论。
|
||||
|
||||
### 4.14 技能自洽:本机环境写在技能目录的 `AGENTS.md`
|
||||
|
||||
`install.sh` / `requirements.txt` 是服务器工件(镜像构建与 `agent-executor-init` 读它们),本机不跑、
|
||||
不改。启动器也不认识任何具体技能:不注入 PATH、不预装、不做特判。新增技能不需要动 `local/`。
|
||||
|
||||
本机缺东西时只有一条入口:技能自己目录下的 `AGENTS.md`。它是**排错清单**,只写「现象 → 命令」
|
||||
(报什么错、敲什么),不写背景、不提服务器。起点是 `env-local` 提示词的一句话:技能失败就读
|
||||
`"$(dirname "$AGENT_SKILLS_DEPS")/<技能>/AGENTS.md"`。装完不需要重启,旧进程不影响。
|
||||
|
||||
分两层,各管各的:**技能目录的 `AGENTS.md` 只写该技能特有的**(缺哪个包、缺什么系统库);
|
||||
**网络换源与长任务这类通用规则不进技能文档**,直接写在 `env-local.txt` 提示词里——
|
||||
它们必须常驻上下文,靠「出错时去翻文件」是拉不动的(尤其长任务:AI 决定跑 `brew install` 的
|
||||
那一刻没有任何报错信号触发它去查文档)。
|
||||
|
||||
代价明写:`office` 的命令入口在本地不在 PATH 上,按次 `PATH="$SK/scripts:$PATH" office ...` 即可
|
||||
(这是它 `AGENTS.md` 的第一条)。
|
||||
|
||||
报错指向各自文档,不在 core 里做全局特征匹配(那种正则既脆又不可移植):
|
||||
|
||||
| 位置 | 报错附带 |
|
||||
|---|---|
|
||||
| `office` 封装层 ENOENT | 本技能 `AGENTS.md` 绝对路径 |
|
||||
| `x2pdf` 缺包 / 无渲染后端 | 同上 |
|
||||
| `image-process` 缺中文字体 | 同上(并提示传 `font`) |
|
||||
| 网络类 / 长任务 | 不进技能文档:写在 `env-local.txt`,常驻上下文 |
|
||||
|
||||
唯一保留的环境相关代码是 `x2pdf` 的 `find_soffice()`:`brew install --cask libreoffice` 后
|
||||
`soffice` 不在 PATH(在 app bundle 内),不探这几个默认位置,“装 LibreOffice 即可”就是假的。
|
||||
另保留了 WeasyPrint 不可用时回落 LibreOffice,让本地只需一个后端而不是 pango + WeasyPrint 两套链。
|
||||
|
||||
没做的是预览:预览卡片要 executor 的 `:3100` 网关,本地没有。要补相当于把
|
||||
`executor/preview.js` 的槽位管理搬进 core,不值得。
|
||||
|
||||
## 5. 验证结果(macOS 12.7.6 / x86_64 / Node 22.21 / python3 3.10 / 本机无 ffmpeg)
|
||||
|
||||
静态检查:`sh -n local/start.sh`、`sh -n local/stop.sh`、`node --check` 均通过。
|
||||
|
||||
| 项 | 结果 |
|
||||
|---|---|
|
||||
| 首次启动:生成配置 → 装依赖(app 134 包,image_task / video_task 各 127 包)→ 起 MCP + core → 打开状态页(停在「已启动」,等点击) | 通过 |
|
||||
| 配置内容:`workspace_root` 是选的目录、`data_root` 指仓库 `data/`、`skills_root` 指 `local/.runtime/skills`、`platforms: []`、MCP 端口 8091~8094 | 通过 |
|
||||
| 绑定地址:`lsof` 只有 `127.0.0.1:8090` | 通过 |
|
||||
| 设置页「重启」→ 守护拉起:PID 变化,2 秒内 `/api/health` 恢复 | 通过 |
|
||||
| 文件工具越出会话目录:工作目录根的 `probe.txt` 可读 | 通过 |
|
||||
| 越界保护:`read_file ~/.ssh/config`、`terminal cd /etc` 均报「路径越界」 | 通过 |
|
||||
| `/tmp` 一致性:`write_file /tmp/x` → `terminal cat /tmp/x` 与 `read_file /tmp/x` 内容一致 | 通过 |
|
||||
| 无 ffmpeg:`/api/asr/status` = `enabled:false`(麦克风隐藏),asr 子进程不启动,8094 不监听 | 通过 |
|
||||
| 有 python3:Python 技能可执行;桩掉 python3 后技能清单不变(`/api/skills` 照常返回),执行 `run.py` 类技能报「技能入口启动失败:spawn python3 ENOENT」,`office` 这类非 Python 技能不受影响 | 待复测 |
|
||||
| 四个 MCP 在具备条件时均能发现工具(`[mcp] web_search / image_task / video_task / asr: 发现 1 个工具`) | 通过 |
|
||||
| 前台模式 `Ctrl-C` 与 `TERM`:8090 与 8091~8094 全部释放,无残留进程 | 通过 |
|
||||
| 二次启动:沿用配置、跳过依赖安装(时间戳生效) | 通过 |
|
||||
| 后台模式:`start.sh` 1 秒返回、启动器 PPID=1、`supervisor.pid` 是子进程 pid | 通过 |
|
||||
| `stop.sh`:命中 pid 文件分支;pid 文件丢失时按 core 父进程/端口也能停;未运行时幂等返回 | 通过 |
|
||||
| 重复执行 `start.sh`:打印「已在运行(启动器 pid N)」+ 停止命令,exit 0,不起第二个进程 | 通过 |
|
||||
| 启动器被 `kill -9` 后的恢复:残留 pid 文件被清理,端口仍被占时明确提示先 `stop.sh` | 通过 |
|
||||
| 依赖源自动探测:删依赖后启动,自动选中 `registry.npmmirror.com`(本机 npm 全局源也是它),状态页显示「依赖源」 | 通过 |
|
||||
| 依赖缓存:装成功后生成 `~/.cache/agent-local/deps-...tgz`;删掉 `node_modules` 重启,日志为「使用本地依赖缓存」、`npm-install.log` 为空(零网络) | 通过 |
|
||||
| 换源自愈:把缓存里的源改成不可达地址 → 看门狗超时 → 自动换到 npmmirror 装完,缓存里的源被改回可用值 | 通过 |
|
||||
| 失败翻译:源不可用 + 冷 npm 缓存 → 状态页标题「依赖安装失败」、提示「源没有响应…(已自动换源重试)」,无 npm 残留进程 | 通过 |
|
||||
| 前台模式 `AGENT_LOCAL_DETACH=0`:阻塞运行,`TERM` 后端口全部释放 | 通过 |
|
||||
| 无 node(PATH 里剥掉 node/npm):入口直接拦下,**不** 先让选目录、不生成配置;终端打出安装方式;状态页列出自检项(X Node.js / X npm) | 通过 |
|
||||
| 失败时只开一个状态页标签(不再两个) | 通过 |
|
||||
| 状态页:启动即弹出、每秒刷新、显示步骤/计时/日志尾巴;失败时保留错误与日志 | 通过 |
|
||||
| `osascript` 真实选目录弹窗 | 未验证(用桩跑的「没选→回落 `~/AgentWork`」分支) |
|
||||
| 真浏览器打开(`open`) | 未验证(用桩记录了被打开的 URL) |
|
||||
| 装 ffmpeg 之后:`ASR_URL` 注入、asr 子进程与麦克风一起出现 | 未验证(本机未装 ffmpeg) |
|
||||
|
||||
验证过程中发现并修掉的问题见 3.1(依赖检测、lockfile 内网源、`asr` 无条件启动、端口冲突、
|
||||
状态页日志缺失、全角字符紧贴变量名导致的 `unbound variable`)。
|
||||
|
||||
## 6. 还没覆盖的三项(需要人工交互或外部环境)
|
||||
|
||||
其余清单已在 mac 上跑完(结果见第 5 节)。剩下这三项要在真实场景里补:
|
||||
|
||||
1. **真实选目录弹窗**:删掉 `local/config.local.yml` 后跑 `./local/start.sh`,确认弹出的是 macOS 原生
|
||||
选目录窗、选完的路径写进 `workspace_root`(带空格的目录名要顺手验一下,配置里已加引号)。
|
||||
2. **真浏览器打开**:跑 `./local/start.sh`(或前台模式),确认(a)状态页在启动过程中每秒刷新;
|
||||
(b)首次安装停在页面上等你点「打开应用」;(c)后续启动 2 秒自动进应用。
|
||||
3. **装 ffmpeg 之后**:`brew install ffmpeg` → 重跑脚本,预期:状态页显示 `ffmpeg` 为 OK、
|
||||
终端打「语音:可用」、8094 开始监听、`/api/asr/status` 变成需要填上游(不再是「未设置 ASR_URL」)。
|
||||
|
||||
手工复验用的命令:
|
||||
|
||||
```bash
|
||||
./local/start.sh # 后台启动(1 秒返回)
|
||||
./local/stop.sh # 停止(幂等)
|
||||
./local/start.sh # 已在运行时只打印地址与停止方式
|
||||
lsof -nP -iTCP:8090 -sTCP:LISTEN # 应只有 127.0.0.1
|
||||
lsof -nP -iTCP:8091-8094 -sTCP:LISTEN # 3 或 4 个 MCP(没 ffmpeg 时没有 8094)
|
||||
curl -s http://127.0.0.1:8090/api/asr/status
|
||||
curl -s -X POST http://127.0.0.1:8090/api/system/restart # 应由守护拉起
|
||||
tail -f local/.runtime/core.log # 以及 npm-install.log / mcp-*.log
|
||||
```
|
||||
|
||||
## 7. 已知限制(都不打算在本次解决)
|
||||
|
||||
| 限制 | 说明 |
|
||||
|---|---|
|
||||
| **无沙箱** | AI 的 `terminal` 就是本机 shell,能读 `~/.ssh` 等一切。这是「给它一个目录就放开手脚」的代价;README 已提示「专用目录 + `git init`」 |
|
||||
| 没 ffmpeg 时 asr 会报「工具发现失败」 | 此时 `mcp_asr` 不启动(它转码依赖 ffmpeg),但配置里的 asr 条目仍在(配置不覆盖),所以 core 启动会 warn 一次并重试,属预期 |
|
||||
| `mcp_asr` 监听 `0.0.0.0` | 它只认 `PORT` 环境变量、`listen` 不带 host(已启动时才是问题)。不存密钥(上游参数随请求带入),暴露面有限;要收紧需给 `mcp/asr` 加 `--host` 支持 |
|
||||
| Windows 不支持 | `spawn('/bin/sh')`、`process.kill(-pid)`、模型写的 bash 语法都是 POSIX 语义 |
|
||||
| 链接只在本机可达 | 本地没有公网前缀:`mint_public_link` / 页面访问地址都签成 `http://127.0.0.1:<PORT>/...`,只能在这台机器上打开(这正是本地形态的预期)。要真正对外暴露才需在设置页填 `public_link.base_url` |
|
||||
| 技能依赖 | 本地不预装:缺包时模型会把包装进 `skills/deps`(`$AGENT_SKILLS_DEPS`,已在该进程 `PYTHONPATH` 里,装完下次运行即生效);连 `python3` 都没有时也由它自己装。怎么装由模型自己决定。需要系统库的包(`weasyprint`→pango/cairo)pip 装不了,仍需手工 `brew install`。服务器上由 `agent-executor-init` 处理 |
|
||||
| `office` 二进制 | 不入库、也不预装:首次用到时报 `binary missing` 并给出该技能 `AGENTS.md` 的绝对路径,模型按它自己下载(`releases/latest`,~34MB,GitHub 慢就用 gh-proxy)。不需要 root、不需重启。officecli 会自更新到 latest,版本比服务器 pin 的新属正常 |
|
||||
| `office` 预览 | 预览卡片走 core → executor 的 `:3100` 网关,本地没有这个网关 → 点开打不开。文档创建/编辑/读取不受影响 |
|
||||
| 首个 `npm install` 要联网 | 支持 `NPM_REGISTRY` 覆盖源;`app/package-lock.json` 的 `resolved` 已改指向公共 registry(原来钉在内网镜像,外部机器必失败) |
|
||||
|
||||
## 8. 回滚
|
||||
|
||||
本地模式的所有开关默认关闭,服务器行为不变。真要整体撤掉:
|
||||
|
||||
```bash
|
||||
git revert <本次提交>
|
||||
rm -rf local/ # 或保留脚本、只是不用
|
||||
```
|
||||
|
||||
`v2.5.0` 是这批改动之前的基线,可随时对照。
|
||||
|
||||
## 9. 记录:测试残留(都不入库)
|
||||
|
||||
跑过启动器之后本机会多出:`local/.runtime/`(日志、状态页、技能软链)、
|
||||
`local/config.local.yml`、`~/AgentWork/`、`app/node_modules/`、`mcp/image_task|video_task/node_modules/`。
|
||||
全部在 gitignore 内,不影响仓库;想彻底重来就把它们删掉再跑脚本(会话产出在 `data/` 与
|
||||
工作目录下的 `task-*` 里,不会被清)。
|
||||
|
||||
## 10. 新建会话手选工作目录(本地端)
|
||||
|
||||
默认每个会话落在 `workspace_root/<会话id>`(形如 `task-YYYYMMDD-NNN`)。本地端希望「给它一个
|
||||
目录就放开手脚」,所以新建会话时可以手选一个真实目录,这个会话的 AI 一切操作都在那儿。
|
||||
|
||||
**后端只动 `taskDirOf` 一处**(`engine.js`):
|
||||
|
||||
```js
|
||||
taskDirOf(sessionId) = sessions.work_dir || path.join(workspace_root, sessionId)
|
||||
```
|
||||
|
||||
全仓库的会话路径(文件 API、上传、`terminal` 的 cwd、`resolveInTask` 基准、data-page、
|
||||
`@会话` 只读)都经由它,所以改这一处即全线生效,不必逐个路由改。
|
||||
|
||||
- 选择只存前端(`pendingWorkDir`),建档时随 `POST /api/sessions` 提交一次;不选 = 空串 = 老行为。
|
||||
- **不建 `task-*` 子目录**,直接以所选目录为工作目录(隐藏产物 `.tmp`/`.imgcache`/`.app`/`data.db` 落在这里)。
|
||||
- 允许多个会话选同一目录;**删会话绝不删该目录**(`deleteSession` 只在 `work_dir` 为空时才 `rmSync`)。
|
||||
- `fsRoot` 优先返回 `ctx.workDir`;`@<会话>` 也按目标会话的 `work_dir` 解析(`resolvePastPath`)。
|
||||
- 目录选择器:`routes/local.js` 用 `osascript`(mac)/ `zenity`/`kdialog`(Linux)弹原生窗口,
|
||||
**仅 `AGENT_LOCAL_PICK=1` 时挂载**(`server.js`),服务器形态 `/api/local/*` 一律 404,前端整条入口隐藏。
|
||||
必须 `execFile` 异步:同步会阻塞事件循环、卡住所有 SSE。
|
||||
- 只接受已存在的目录(`normalizeWorkDir` 校验真实路径),并拒绝根目录 `/` 与平台数据目录。
|
||||
- 服务器形态:前端从不传 `work_dir`,`work_dir` 列恒为空,行为与旧版完全一致。
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
# 本地端(local 模式)
|
||||
|
||||
把同一个 `agent-core` 直接跑在本机(macOS / Linux),不装 Docker、不起 executor。
|
||||
|
||||
它和服务器版是**同一份代码**,差别只在三件事,全部由 `local/start.sh` 注入:
|
||||
|
||||
| 差异 | 服务器 | 本地 |
|
||||
|---|---|---|
|
||||
| 命令在哪跑 | `agent-executor` 容器(mount/pid namespace 隔离) | 直接在本机 `spawn`(无沙箱) |
|
||||
| 文件工具的根 | 会话目录 `tasks/<会话id>/` | 你指定的工作目录 `workspace_root` |
|
||||
| 监听地址 | `0.0.0.0`(靠宿主机端口映射对外) | `127.0.0.1`(只有本机能访问) |
|
||||
|
||||
后两项分别由环境变量 `AGENT_FILE_SCOPE=workspace` 和 `HOST=127.0.0.1` 控制,容器部署不设置,
|
||||
行为与以前完全一致。
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
cd agent
|
||||
./local/start.sh # 后台启动,命令 1 秒就返回,可以关掉终端窗口
|
||||
./local/stop.sh # 停止
|
||||
```
|
||||
|
||||
首次运行会:
|
||||
|
||||
1. 自检环境(Node 20+ 必需;ffmpeg / python3 可选),并打开一个**启动状态页**
|
||||
2. 弹窗让你选一个**工作目录**(AI 会在这个目录里干活)
|
||||
3. 生成 `local/config.local.yml`
|
||||
4. 装一次 Node 依赖(`app/` 与带依赖的 MCP,需要联网)
|
||||
5. 起 core + MCP 子进程(没 ffmpeg 时 asr 不启动)
|
||||
6. 停在那儿守护:core 退出就自动拉起
|
||||
|
||||
浏览器里首次使用:**左下角「用户区」→ 设置 → 模型池**,添加平台和 API Key,然后点「重启」。
|
||||
|
||||
新建会话时,欢迎页「随时开始吧」下方可以**手选一个工作目录**:选了之后这个会话的 AI 一切操作
|
||||
都在那个目录里(不再建 `task-*` 子目录);不选就沿用默认(系统工作目录下的独立会话目录)。
|
||||
删会话不会删你选的目录。
|
||||
|
||||
没有 Node 20+ 时不会让你白选目录:脚本在入口就停下,终端打出安装方式,自检结果(哪项缺、怎么装)写到状态页。
|
||||
|
||||
> 「重启」能用是因为启动器在守护。`routes/system.js` 的重启实现是 `process.exit(0)`,
|
||||
> 原本靠 Docker 的 restart 策略拉起;本地没有 Docker,没有守护的话点一次服务就回不来了。
|
||||
|
||||
启动器在后台常驻,所以:
|
||||
|
||||
- 关掉终端窗口**不会**停服务;要停就 `./local/stop.sh`
|
||||
- 重复跑 `./local/start.sh` 是安全的:检测到已在运行就只打印地址和停止方式
|
||||
- 想在终端里看实时日志、用 `Ctrl-C` 停:`AGENT_LOCAL_DETACH=0 ./local/start.sh`
|
||||
|
||||
## 启动状态页
|
||||
|
||||
启动时会在浏览器打开 `local/.runtime/status.html`(macOS 默认自动弹,Linux 要 `AGENT_LOCAL_UI=1`):
|
||||
|
||||
- 启动过程中每秒自动刷新,依次列出环境自检、工作目录、依赖安装、MCP、core 就绪
|
||||
- 长步骤(装依赖、等 core 起来)会显示已用时间,并把 npm / core 日志的尾巴实时刷出来
|
||||
- **首次安装**(配置刚生成)不自动跳转:就停在这一页,点「打开应用」自己进去
|
||||
- **后续启动**:就绪后 2 秒自动进应用(同一个标签页)
|
||||
- **失败时就在页面上给出原因和日志**,不用回头翻终端
|
||||
|
||||
这个页面是纯静态文件(不用起服务),所以“node 都没装”的时候也能打开。重跑脚本会重新生成;
|
||||
即使没自动弹出,文件也一直在那个路径。
|
||||
|
||||
## 可选能力
|
||||
|
||||
| 能力 | 需要 | 没有时的表现 |
|
||||
|---|---|---|
|
||||
| 语音输入 | `ffmpeg` + 设置页给 `asr` 填上游(`X-ASR-Base-Url` / `X-ASR-Model`) | 麦克风入口自动隐藏(`/api/asr/status` 返回 `enabled:false`),`mcp_asr` 子进程也不启动 |
|
||||
| 技能 | `python3`(仅 Python 类技能需要) | 技能清单照常显示;调 `run.py` 类技能报「入口启动失败」,`office` 这类非 Python 技能不受影响 |
|
||||
| Office 文档(docx/xlsx/pptx) | 首次用到时下载一次 officecli 二进制(约 34MB) | `office` 报 `binary missing` 并给出该技能 `AGENTS.md` 的路径,按它下载即可(不需 root、不需重启) |
|
||||
| 网页搜索 | 无 | 装了 Node 就有(内置免费后端) |
|
||||
| 图片 / 视频生成 | 设置页给对应 MCP 填上游 key | 调用时报明确的缺参错误 |
|
||||
|
||||
装完 `ffmpeg` 之后**重跑一次 `./local/start.sh`** 即可生效。`python3` 稍特殊:技能清单本来就在,
|
||||
只要新装的解释器落在 core 启动时 `PATH` 已包含的目录里(如 brew 的 `/opt/homebrew/bin`)就无需重启;
|
||||
换了目录就重跑脚本。这三项都不写进配置,靠「起不起子进程 / 注入什么环境变量」切换。
|
||||
|
||||
## 配置放哪
|
||||
|
||||
- 生成的配置:`local/config.local.yml`(**首次生成,之后永不覆盖**,避免冲掉你在网页里配的模型与密钥)
|
||||
- 会话数据:`data/`(SQLite + prompt dump)与工作目录下的 `task-YYYYMMDD-NNN/`
|
||||
- 运行期产物:`local/.runtime/`(`status.html` 状态页、`core.log`、`npm-install.log`、各 MCP 日志、技能软链)
|
||||
|
||||
想彻底重来:删掉 `local/config.local.yml`(以及可选的 `data/`)再启动。会话目录里的产出不会被删。
|
||||
|
||||
## 常用环境变量
|
||||
|
||||
| 变量 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| `PORT` | `8090` | core 端口(别撞下面的 MCP 端口) |
|
||||
| `NPM_REGISTRY` | 空 | 手动指定 npm 源(默认自动探测;指定后不再自动换源) |
|
||||
| `MCP_WEB_PORT` / `MCP_IMAGE_PORT` / `MCP_VIDEO_PORT` / `MCP_ASR_PORT` | 8091~8094 | 四个 MCP 的端口(同机跑必须各占一个;改这里还要同步改配置里的 url) |
|
||||
| `AGENT_LOCAL_UI` | `auto` | 是否自动打开状态页:`auto` = 仅 macOS,`1` 强制,`0` 关闭(页面无论如何都会生成) |
|
||||
| `AGENT_LOCAL_DETACH` | `1` | `1` = 后台启动后立即返回(用 `stop.sh` 停);`0` = 前台阻塞(看实时日志、`Ctrl-C` 停) |
|
||||
| `AGENT_LOCAL_CACHE` | `~/.cache/agent-local` | 依赖缓存的存放位置(多个 clone 共享) |
|
||||
| `AGENT_LOCAL_NPM_TIMEOUT` | `240` | 单次 `npm install` 的超时秒数,超过就换源重试 |
|
||||
|
||||
## 依赖安装与网络(国内环境)
|
||||
|
||||
首次启动要装一次 Node 依赖,启动器会自己处理环境问题,不需要你操心:
|
||||
|
||||
- **自动选源**:并行探 `registry.npmmirror.com` 与官方源,用最快的那个(国内基本会选 npmmirror)。
|
||||
结果缓存一天;不写你本机的 `~/.npmrc`,也不改全局配置。
|
||||
- **失败自动换源重试**:一个源不行就换下一个;换源成功会记住它。
|
||||
- **卡住有看门狗**:npm 在断网时可能既不报错也不退出,超过 `AGENT_LOCAL_NPM_TIMEOUT` 就结束它并换源。
|
||||
- **装完存缓存**:打成一张 tarball 放到 `~/.cache/agent-local/`。之后重启、删掉 `node_modules`、
|
||||
再 clone 一份,都是解压恢复(秒级、零网络)。
|
||||
- **失败说人话**:状态页会直接告诉你「网络没通 / 缺编译工具链(`xcode-select --install`)/ 没有写权限」,
|
||||
不需要读 npm 日志。
|
||||
|
||||
要清缓存就删那个目录:`rm -rf ~/.cache/agent-local`(下次启动会重新装一次)。
|
||||
|
||||
## 更新
|
||||
|
||||
```bash
|
||||
git pull
|
||||
./local/stop.sh && ./local/start.sh # package.json 变了会自动重装依赖
|
||||
```
|
||||
|
||||
`app/server` 是直接跑源码,前端也是免构建的,所以改完代码重启(或在网页点「重启」)即生效。
|
||||
|
||||
## 安全边界(务必知情)
|
||||
|
||||
本地模式**没有沙箱**:AI 的 `terminal` 就是本机 shell,能读写你账号有权限的任何文件,
|
||||
包括 `~/.ssh`、浏览器数据、其它项目。这不是配置疏漏,而是「给它一个目录就放开手脚」的代价。
|
||||
|
||||
两条低成本保险:
|
||||
|
||||
1. 工作目录选一个**专用**目录,别直接选 `$HOME` 或整个代码仓库根
|
||||
2. 那个目录先 `git init` 一下,改坏了能回滚
|
||||
|
||||
另外,`core` 只监听 `127.0.0.1`,同一局域网的人访问不到。
|
||||
|
||||
## 已知限制
|
||||
|
||||
- **没 ffmpeg 时 core 日志会有一条 `asr 工具发现失败`**:此时 `mcp_asr` 不启动(它转码要靠
|
||||
ffmpeg),但配置里的 asr 条目仍保留(配置不被覆盖)。重试几次后放弃,不影响其它功能。
|
||||
- **`mcp_asr` 启动后监听 `0.0.0.0`**:它只认 `PORT` 环境变量,没有 `--host` 参数
|
||||
(另外三个服务都传了 `--host 127.0.0.1`)。它不存任何密钥(上游参数随请求带入),
|
||||
暴露面有限,但严格起见可以给 `mcp/asr` 补一个 `--host` 支持。
|
||||
- **Windows 暂不支持**:本机执行走 `spawn('/bin/sh')` 与 `process.kill(-pid)`,都是 POSIX 语义。
|
||||
- **链接只在本机可达**:没有公网前缀时,`mint_public_link` 与页面访问地址都会签成
|
||||
`http://127.0.0.1:<PORT>/...`,在这台机器上点得开,发给别人打不开。要对外暴露再填
|
||||
`public_link.base_url`(设置页)。本地监听回环地址,模型厂商也拉不到,所以读图回传改走内联
|
||||
base64(`AGENT_IMAGE_INLINE=1`,启动器已注入)。
|
||||
- **`office` 文档没有预览**:预览卡片走 core → executor 的 `:3100` 网关,本地没有这个网关,
|
||||
点开得不到可用页面;文档本身的创建/编辑/读取完全正常。
|
||||
- **技能依赖不预装**:本地没有 `agent-executor-init`,`skills/*/requirements.txt` 不会在启动时
|
||||
自动安装。技能缺包时会报 `ModuleNotFoundError`,模型会把缺的包装进 `skills/deps`
|
||||
(`AGENT_SKILLS_DEPS` 指向它,且已在该进程的 `PYTHONPATH` 里,装完下次运行即生效)。
|
||||
连 `python3` 都没有时技能清单依旧完整,模型会自己把它装上再继续。
|
||||
需要系统库的包(如 `weasyprint` 依赖 pango/cairo)pip 装不了,得自己 `brew install`。
|
||||
- **首个 `npm install` 要联网**:启动器会自动选源、换源重试、并把装好的依赖缓存到
|
||||
`~/.cache/agent-local/`;之后重启 / 换 clone 都是本地解压,不需要网络。真要手动指定源:
|
||||
`NPM_REGISTRY=https://registry.npmmirror.com ./local/start.sh`。中途失败留下的半成品
|
||||
`node_modules` 不用手删(换源重试前会自动清)。
|
||||
|
||||
## 排查
|
||||
|
||||
```bash
|
||||
open local/.runtime/status.html # 启动状态页:步骤、失败原因、日志尾巴
|
||||
tail -f local/.runtime/core.log # core 日志(含 prompt dump 路径、MCP 发现结果)
|
||||
tail -f local/.runtime/npm-install.log # 装依赖的输出
|
||||
tail -f local/.runtime/mcp-asr.log # 单个 MCP 的日志
|
||||
```
|
||||
|
||||
启动失败时状态页会自己弹出(带错误说明和日志尾部);它是个静态页,所以改完环境要自己重跑脚本
|
||||
(它不会自动重试)。
|
||||
|
||||
进程表 / 端口对不上时:
|
||||
|
||||
```bash
|
||||
lsof -nP -iTCP:8090-8094 -sTCP:LISTEN # core + 四个 MCP 的监听情况
|
||||
```
|
||||
@@ -0,0 +1,47 @@
|
||||
# 本机 local 模式的配置参考。
|
||||
#
|
||||
# ⚠️ 这个文件不会被读取,只是给人看的样板:真正的配置由 local/start.sh 首次运行时
|
||||
# 生成到 local/config.local.yml(含你选的工作目录与分配好的端口)。
|
||||
# 想看自己机器上实际生成成什么样,启动一次后直接打开 local/config.local.yml。
|
||||
#
|
||||
# 字段含义与服务器版完全一致(见 app/config.example.yml);下面只列 local 模式实际用到的那部分。
|
||||
|
||||
port: 8090
|
||||
|
||||
# AI 的工作根。local 模式注入 AGENT_FILE_SCOPE=workspace 后,文件工具可读写这个目录下任何位置。
|
||||
workspace_root: /Users/you/AgentWork
|
||||
|
||||
# SQLite(.agent.db)与启动 prompt dump。默认指到仓库里的 data/(已在 .gitignore)。
|
||||
data_root: /path/to/agent/data
|
||||
|
||||
skills:
|
||||
# 指向 local/.runtime/skills —— 启动脚本按「python3 是否可用」把它软链到真技能目录或空目录,
|
||||
# 因此装不装 python3 都不需要改这里,改完重跑启动脚本即生效。
|
||||
skills_root: /path/to/agent/local/.runtime/skills
|
||||
|
||||
# 留空:启动后到设置页添加平台与 API Key,再点「重启」(启动器负责把进程拉起来)。
|
||||
platforms: []
|
||||
|
||||
log_level: info
|
||||
|
||||
mcp_servers:
|
||||
# 四个同栈 MCP 由启动器在本机拉起,端口与 start.sh 里的默认值对应(8091~8094,
|
||||
# 紧跟在 core 的 8090 后面;改 PORT 时别撞上这四个)。
|
||||
# web_search 不需要任何密钥(内置免费后端);其余三个的上游参数在设置页卡片里填,
|
||||
# 会写进对应条目的 headers。
|
||||
- name: web_search
|
||||
url: "http://127.0.0.1:8091/"
|
||||
- name: image_task
|
||||
url: "http://127.0.0.1:8092/mcp"
|
||||
mode: skill
|
||||
- name: video_task
|
||||
url: "http://127.0.0.1:8093/mcp"
|
||||
mode: skill
|
||||
- name: asr
|
||||
url: "http://127.0.0.1:8094/mcp"
|
||||
mode: skill
|
||||
# 例:填了这两项才算启用语音(缺 X-ASR-Base-Url 时 /api/asr/status 返回 enabled:false,麦克风自动隐藏)
|
||||
# headers:
|
||||
# Authorization: Bearer <key>
|
||||
# X-ASR-Base-Url: "https://<host>/v1"
|
||||
# X-ASR-Model: "whisper-1"
|
||||
Executable
+1070
File diff suppressed because it is too large
Load Diff
Executable
+102
@@ -0,0 +1,102 @@
|
||||
#!/bin/sh
|
||||
# local/stop.sh —— 停掉本机 local 模式拉起来的 agent-core 与 MCP 子进程。
|
||||
#
|
||||
# 正常停法就是 ./local/stop.sh:启动器默认是后台跑的(start.sh 拉起后就返回)。
|
||||
# 前台模式(AGENT_LOCAL_DETACH=0)下 Ctrl-C / 关窗口也能停。
|
||||
# 但终端可能被关掉、进程可能是从别处起的——那时就只能按 pid / 端口找。
|
||||
#
|
||||
# 关键点:启动器是父进程(启动器 → core + 3/4 个 MCP),只杀 core 会被它重新拉起来
|
||||
# (那是「重启」的语义)。所以必须先停启动器,停不掉再按端口硬收。
|
||||
# 幂等:没在运行时直说,不报错。
|
||||
set -u
|
||||
|
||||
HERE=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
RUNTIME="$HERE/.runtime"
|
||||
PIDFILE="$RUNTIME/supervisor.pid"
|
||||
|
||||
PORT="${PORT:-8090}"
|
||||
# 与 start.sh 的默认值一致;用 MCP_*_PORT 改过端口时这里也要跟着改(否则兜底那步找不到它们)。
|
||||
MCP_PORTS="${MCP_WEB_PORT:-8091} ${MCP_IMAGE_PORT:-8092} ${MCP_VIDEO_PORT:-8093} ${MCP_ASR_PORT:-8094}"
|
||||
|
||||
stopped=0
|
||||
|
||||
say() { printf '==> %s\n' "$*"; }
|
||||
|
||||
# 某个端口上处于 LISTEN 的进程 pid(没有 lsof 就返回空)。
|
||||
pids_on_port() {
|
||||
command -v lsof >/dev/null 2>&1 || return 0
|
||||
lsof -nP -tiTCP:"$1" -sTCP:LISTEN 2>/dev/null
|
||||
}
|
||||
|
||||
stop_pid() {
|
||||
# $1 pid $2 说明
|
||||
kill -TERM "$1" 2>/dev/null || return 0
|
||||
say "停止$2(pid $1)"
|
||||
stopped=1
|
||||
}
|
||||
|
||||
wait_gone() {
|
||||
# $1 pid,最多等 10 秒
|
||||
i=0
|
||||
while [ "$i" -lt 20 ]; do
|
||||
kill -0 "$1" 2>/dev/null || return 0
|
||||
sleep 0.5 2>/dev/null || sleep 1
|
||||
i=$((i + 1))
|
||||
done
|
||||
}
|
||||
|
||||
# 1) 首选:启动器自己写的 pid 文件(最准,也最快)。
|
||||
if [ -f "$PIDFILE" ]; then
|
||||
pid=$(cat "$PIDFILE" 2>/dev/null || printf '')
|
||||
case "$pid" in ''|*[!0-9]*) pid='';; esac
|
||||
if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then
|
||||
stop_pid "$pid" '启动器'
|
||||
wait_gone "$pid"
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
say '启动器 10 秒内没退出,强制结束'
|
||||
kill -KILL "$pid" 2>/dev/null || true
|
||||
fi
|
||||
sleep 1
|
||||
fi
|
||||
rm -f "$PIDFILE"
|
||||
fi
|
||||
|
||||
# 2) pid 文件丢了(终端被强杀、目录被清过):从 core 的父进程认出启动器。
|
||||
# 按「谁是 8090 的父进程」找,而不是按启动命令的路径拼写去 pgrep——
|
||||
# 同机可能有别的 clone,靠路径匹配容易误杀或不匹配(实测 `sh ./local/start.sh` 是相对路径)。
|
||||
if [ "$stopped" = 0 ]; then
|
||||
for pid in $(pids_on_port "$PORT"); do
|
||||
ppid=$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ')
|
||||
case "$ppid" in ''|0|1|*[!0-9]*) continue;; esac
|
||||
if ps -o command= -p "$ppid" 2>/dev/null | grep -q 'start\.sh'; then
|
||||
stop_pid "$ppid" '启动器(按 core 的父进程识别)'
|
||||
wait_gone "$ppid"
|
||||
if kill -0 "$ppid" 2>/dev/null; then
|
||||
say '启动器 10 秒内没退出,强制结束'
|
||||
kill -KILL "$ppid" 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
done
|
||||
[ "$stopped" = 1 ] && sleep 2
|
||||
fi
|
||||
|
||||
# 3) 兜底:还占着端口的直接收(启动器已经死了,剩下的都是孤儿)。
|
||||
for p in "$PORT" $MCP_PORTS; do
|
||||
for pid in $(pids_on_port "$p"); do
|
||||
stop_pid "$pid" "端口 $p 上的进程"
|
||||
done
|
||||
done
|
||||
[ "$stopped" = 1 ] && sleep 2
|
||||
|
||||
# 4) 收尾:仍占着端口的强制结束,避免下次启动被判「端口被占用」。
|
||||
for p in "$PORT" $MCP_PORTS; do
|
||||
for pid in $(pids_on_port "$p"); do
|
||||
kill -KILL "$pid" 2>/dev/null || true
|
||||
done
|
||||
done
|
||||
|
||||
if [ "$stopped" = 1 ]; then
|
||||
say '已停止'
|
||||
else
|
||||
say "没有在运行($PORT 与 MCP 端口 $MCP_PORTS 都空闲)"
|
||||
fi
|
||||
+7
-5
@@ -25,6 +25,7 @@ skills/
|
||||
├── run.py # 技能主入口(Python 脚本,推荐)或 run.sh
|
||||
├── requirements.txt # Python 依赖(可选,若需要第三方包)
|
||||
├── install.sh # 系统级依赖安装脚本(可选,如 apt-get)
|
||||
├── AGENTS.md # 该技能的排错命令(可选;core 不读,只在报错信息里被指向)
|
||||
└── ... # 其他技能相关文件(如字体、模板等)
|
||||
```
|
||||
|
||||
@@ -163,12 +164,13 @@ def main():
|
||||
示例 `requirements.txt`:
|
||||
|
||||
```
|
||||
requests==2.28.1
|
||||
beautifulsoup4==4.11.1
|
||||
requests
|
||||
beautifulsoup4
|
||||
```
|
||||
|
||||
- 依赖安装使用 `pip install --target`,不会污染系统全局;镜像已带的包不会重复装。
|
||||
- 所有技能**共享**同一个 `deps` 目录,请注意版本冲突(后装的覆盖先装的)。建议锁定精确版本。
|
||||
- 所有技能**共享**同一个 `deps` 目录,请注意版本冲突(后装的覆盖先装的)。
|
||||
- 默认**不写版本号**:init 用 `pip install --no-index --dry-run <行>` 探测是否已满足,写死版本而镜像/外挂层里是别的版本时探测失败,会往 `deps` 再装一份,而 `PYTHONPATH` 优先于系统 site-packages,等于用旧版本遮蔽镜像包。确有兼容约束才 pin(如 `weasyprint==65.1` 与 pydyf 的编码兼容)。
|
||||
- 运行期 skills 目录只读;若上线后经 UI 改了 `requirements.txt`,需重启(`docker compose up -d`)触发重新 init,否则该技能会因依赖未就绪而失败。
|
||||
|
||||
### 5.2 系统级依赖
|
||||
@@ -288,7 +290,7 @@ A:确保 `requirements.txt` 存在且列出了所有需要的包,并检查 `
|
||||
A:检查网络连接和 pip 源是否可用,查看 Skill Manager 输出的错误日志。
|
||||
|
||||
**Q:多个技能依赖冲突如何解决?**
|
||||
A:目前所有技能共享同一个 `deps` 目录,建议锁定精确版本,或考虑将冲突的技能拆分到不同的环境中(未来可能支持隔离)。
|
||||
A:目前所有技能共享同一个 `deps` 目录,后装的覆盖先装的。真遇到冲突才给冲突的包 pin(pin 会让离线探测失败,把该版本强行装进 `deps` 并遮蔽镜像包);能升到共同版本更好。
|
||||
|
||||
---
|
||||
|
||||
@@ -296,7 +298,7 @@ A:目前所有技能共享同一个 `deps` 目录,建议锁定精确版本
|
||||
|
||||
查看现有的 `x2pdf` 技能(位于 `skills/x2pdf/`)可以了解一个较为完整的实现,包括如何自带声明 Python 依赖与系统级依赖(不假设镜像预烘)、按扩展名分派渲染后端、参数化版式 CSS 等。但请根据自身技能的实际需求进行设计,不必拘泥于该示例。
|
||||
|
||||
图像处理类需求可参考 `skills/image-process/`:它演示了一个纯 Python + 预装 Pillow 的实现(转换/缩放/裁剪/压缩/水印/切片/拼图,无 requirements.txt,仅靠 install.sh 保证中文字体),并明确区分“确定性图像处理”与“AI 生成/修图”的能力边界。
|
||||
图像处理类需求可参考 `skills/image-process/`:它演示了一个纯 Python + 预装 Pillow 的实现(转换/缩放/裁剪/压缩/水印/切片/拼图,Python 依赖只列 Pillow,中文字体由 install.sh 保证),并明确区分“确定性图像处理”与“AI 生成/修图”的能力边界。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# document-photo-to-pdf
|
||||
|
||||
`ModuleNotFoundError`(`numpy` / `PIL` / `fitz`):把依赖装进 `$AGENT_SKILLS_DEPS`
|
||||
|
||||
```sh
|
||||
python3 -m pip install --upgrade --target "$AGENT_SKILLS_DEPS" -r "$(dirname "$AGENT_SKILLS_DEPS")/document-photo-to-pdf/requirements.txt"
|
||||
```
|
||||
|
||||
`fitz` 是 `pymupdf` 的 import 名,`pypdfium2` 不用装。没有 `python3` 先装运行时(Windows 上解释器常是 `python` / `py`)。
|
||||
@@ -39,7 +39,7 @@ input_schema:
|
||||
|
||||
```json
|
||||
{"ok":true,"summary":"3 页已生成;1 页建议在审核页确认;原始页图见 out/","pdf":"合同_校正.pdf","images":["out/合同_校正-01.png","out/合同_校正-02.png","out/合同_校正-03.png"]}
|
||||
访问地址:https://agent.ai.foresh.com/app/task-20261023-001/doc-review/
|
||||
访问地址:<站点地址>/app/task-20261023-001/doc-review/
|
||||
```
|
||||
|
||||
审核页可拖角、旋转、删页/排序、改纸张与清晰度;改动后点「重新生成 PDF」覆盖同名文件。
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
# 这份文件主要给「本地端」(local/)用:本机 python 缺包时,启动器或模型自己可以按它补装。
|
||||
#
|
||||
# 刻意不写版本号:服务端 agent-executor-init 的判定是
|
||||
# python3 -m pip install --no-index --dry-run <本行>
|
||||
# 退出码 0 即视为已满足、直接跳过装包(executor 镜像已烘了 numpy/Pillow/pymupdf)。
|
||||
# 一旦写了 pin 而镜像里是别的版本,探测就会失败 → 真的往 skills/deps 装一份老版本,
|
||||
# 而 PYTHONPATH 优先于系统 site-packages,等于用外挂层遮蔽镜像版,会牵连其它技能。
|
||||
#
|
||||
# pypdfium2 是 check.py 里 fitz 缺失时的兜底渲染器,不是必需,故不声明。
|
||||
|
||||
numpy
|
||||
Pillow
|
||||
pymupdf
|
||||
@@ -864,7 +864,11 @@ def process(args, t0):
|
||||
if not state_ok:
|
||||
warnings.append("state 文件写入失败:%s" % state_path)
|
||||
|
||||
if checks.get("ok") is False:
|
||||
if checks.get("ok") is None:
|
||||
# 自检根本没跑(无 PDF 渲染后端等):不能让它伪装成「建议确认」——
|
||||
# 那种情况下页面压根没过边缘/短边检验,模型和用户都得知道判据缺失。
|
||||
summary = "%d 页已生成;PDF 自检未能执行,请在审核页人工确认" % len(ordered_pages)
|
||||
elif checks.get("ok") is False:
|
||||
summary = "%d 页已生成;自检有未通过项" % len(ordered_pages)
|
||||
elif needs:
|
||||
summary = "%d 页已生成;%d 页建议在审核页确认" % (
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# image-process
|
||||
|
||||
`ModuleNotFoundError: No module named 'PIL'`:把依赖装进 `$AGENT_SKILLS_DEPS`
|
||||
|
||||
```sh
|
||||
python3 -m pip install --upgrade --target "$AGENT_SKILLS_DEPS" -r "$(dirname "$AGENT_SKILLS_DEPS")/image-process/requirements.txt"
|
||||
```
|
||||
|
||||
`中文水印缺少字体`:传 `font` 参数,指向本机任意中文字体文件(ttf/ttc)
|
||||
|
||||
```json
|
||||
{"action":"watermark","input":"a.jpg","text":"机密","font":"<本机中文字体路径>"}
|
||||
```
|
||||
|
||||
找字体:Linux `fc-list :lang=zh`;macOS `ls /System/Library/Fonts`;Windows `C:\Windows\Fonts\msyh*`。
|
||||
@@ -0,0 +1,7 @@
|
||||
# 本技能只用 Pillow(Image/ImageDraw/ImageFont/ImageOps)。
|
||||
#
|
||||
# 这份文件主要给「本地端」(local/)用:本机 python 缺包时按它补装。
|
||||
# 不写版本号的原因见 skills/document-photo-to-pdf/requirements.txt 顶部的说明:
|
||||
# 服务端 init 用 `pip install --no-index --dry-run` 探测,pin 到与镜像不同的版本会反向遮蔽镜像包。
|
||||
|
||||
Pillow
|
||||
@@ -249,7 +249,8 @@ def action_watermark(img, fmt, args):
|
||||
if font_path:
|
||||
font = ImageFont.truetype(font_path, font_size)
|
||||
elif need_cjk:
|
||||
raise ValueError('中文水印缺少字体:请传 font 参数(TTF/TTC 路径),或确认系统已装文泉驿/Noto 字体')
|
||||
raise ValueError('中文水印缺少字体:传 font 参数(TTF/TTC 路径);本机环境见 %s'
|
||||
% (Path(__file__).resolve().parent / 'AGENTS.md'))
|
||||
else:
|
||||
try:
|
||||
font = ImageFont.load_default(size=font_size)
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
# office
|
||||
|
||||
`office: command not found`:用技能自带入口
|
||||
|
||||
```sh
|
||||
PATH="$(dirname "$AGENT_SKILLS_DEPS")/office/scripts:$PATH" office help
|
||||
```
|
||||
|
||||
`office.core binary missing`:按本机平台下载对应资产到 `bin/officecli`(Windows 存成 `bin/officecli.exe`),再 `chmod +x`
|
||||
|
||||
```sh
|
||||
SK="$(dirname "$AGENT_SKILLS_DEPS")/office"
|
||||
curl -fL -o "$SK/bin/officecli" \
|
||||
https://github.com/iOfficeAI/OfficeCLI/releases/latest/download/officecli-<平台>-<架构>
|
||||
chmod +x "$SK/bin/officecli"
|
||||
```
|
||||
|
||||
资产名是 `{mac,linux,win}-{x64,arm64}`,如 `officecli-mac-arm64`、`officecli-linux-x64`、`officecli-win-x64.exe`;
|
||||
musl 系统(Alpine)用 `officecli-linux-alpine-{x64,arm64}`。`uname -sm` 可判断平台与架构。
|
||||
@@ -31,6 +31,9 @@ office <command> [args...]
|
||||
|
||||
create/open 成功后,用户可自行查看该文档的实时预览(预览页上的选区、标注类交互之后都能被 get-pos 读到)。用户反馈"看第几段/选中了哪里/修改哪里"时,优先用 get-pos 读回选区再针对性改。
|
||||
|
||||
本地直跑没有预览卡片时,用 `office watch <file>` 起自带预览页(立即返回本机地址),
|
||||
`office unwatch <file>` 停。
|
||||
|
||||
## 注意
|
||||
|
||||
- 所有操作文档在任务目录里。
|
||||
|
||||
@@ -2,22 +2,28 @@
|
||||
// office: officecli 的封装层(技能唯一入口)。
|
||||
// - 二进制不进 PATH、SKILL.md 不提及:可见面 = 可调用面,模型只认识本脚本;路径可用 OFFICECLI_BIN 覆盖。
|
||||
// - 命令治理移植自原 MCP 桥:隐去命令报原生风格 unrecognized;view 渲染族拦截给替代路径;
|
||||
// watch 族不透传(预览由平台托管)。
|
||||
// watch 族在服务器形态不透传(预览由平台网关托管),本地直跑放行(见 LOCAL 分支)。
|
||||
// - create/open 成功在 stdout 尾行发 ui_card marker(::ui_card {json}::):core 剥离后转聊天流卡片,
|
||||
// 模型面不感知 marker;arg 为相对 cwd(会话目录)的文件路径。
|
||||
// 模型面不感知 marker;arg 为相对 cwd(会话目录)的文件路径。本地没有预览网关,不发卡片。
|
||||
'use strict';
|
||||
const { spawnSync } = require('node:child_process');
|
||||
const { spawn, spawnSync } = require('node:child_process');
|
||||
const path = require('node:path');
|
||||
const http = require('node:http');
|
||||
const fs = require('node:fs');
|
||||
const net = require('node:net');
|
||||
const os = require('node:os');
|
||||
|
||||
const BIN = process.env.OFFICECLI_BIN || path.resolve(__dirname, '..', 'bin', 'officecli');
|
||||
// 本地直跑(local/start.sh 注入):没有 executor,也没有 /preview 网关,
|
||||
// 预览卡片必然是死链、__pv-touch 打不通,watch 也就没有平台托管可言。
|
||||
const LOCAL = process.env.AGENT_LOCAL_PICK === '1';
|
||||
|
||||
// 本部署不合适的命令(自锁死 / 装配环境族):原生风格报错,help 清单同步删行(见 help 段)。
|
||||
const unrecognized = (v) => "Unrecognized command or argument '" + v + "'.";
|
||||
const HIDDEN_TOP = /^(mcp|skills|install|plugins)(?:\s|$)/;
|
||||
const HIDDEN_LINE = /^ {2}(?:mcp|skills|install|plugins)\b/; // '\b' 绝不能用字符串拼 RegExp(会变退格符)
|
||||
const HELP_STRIP = /^ {2}(?:watch|unwatch)\b/;
|
||||
const HIDDEN_SUBS = new Set(['mark', 'unmark', 'marks', 'goto']); // 标注/滚动族:预览交互由 get-pos 单点覆盖
|
||||
const HIDDEN_SUBS = new Set(['mark', 'unmark', 'marks', 'goto']); // 标注/滚动族:预览交互由 get-pos 单点覆盖(本地有真实 watch,放行)
|
||||
const VIEW_BLOCKED = new Set(['html', 'screenshot', 'svg', 'pdf', 'forms']); // 需无头浏览器/导出插件,本环境没有
|
||||
const OFFICE_EXT_RE = /\.(?:docx|xlsx|pptx)$/i;
|
||||
const EDIT_RE = /^(set|add|remove|move|swap|raw-set|add-part|batch|import|merge|refresh)$/;
|
||||
@@ -60,8 +66,8 @@ const first = String(argv[0] || '');
|
||||
// ---------- 命令面闸门 ----------
|
||||
let m = HIDDEN_TOP.exec(cmd);
|
||||
if (m || (first === 'help' && HIDDEN_TOP.test(argv.slice(1).join(' ')))) err(unrecognized(m ? m[1] : argv[1]));
|
||||
if (HIDDEN_SUBS.has(first)) err(unrecognized(first));
|
||||
if (first === 'watch' || first === 'unwatch') {
|
||||
if (!LOCAL && HIDDEN_SUBS.has(first)) err(unrecognized(first));
|
||||
if (!LOCAL && (first === 'watch' || first === 'unwatch')) {
|
||||
err('Preview slots are managed by the platform: create/open a document, then click the preview card in the chat.');
|
||||
}
|
||||
|
||||
@@ -83,6 +89,63 @@ if (first === 'get-pos') {
|
||||
argv = ['get', file, 'selected', '--json'];
|
||||
}
|
||||
|
||||
// watch:原生是常驻 HTTP 预览服务,前台透传会一直阻塞到 terminal 超时。
|
||||
// 本地改成后台拉起 → 等端口就绪 → 报地址 → 立刻退出,预览页留在后台刷新(编辑通知走原生管道,同机可用)。
|
||||
function startWatch() {
|
||||
const file = argv[1];
|
||||
if (!file) err('Usage: watch <file> [--port <port>]');
|
||||
let port = 26315;
|
||||
for (let i = 2; i < argv.length; i++) {
|
||||
const a = String(argv[i]);
|
||||
if (a === '--port') { port = Number(argv[i + 1]); break; }
|
||||
if (a.startsWith('--port=')) { port = Number(a.slice(7)); break; }
|
||||
}
|
||||
if (!Number.isInteger(port) || port <= 0 || port > 65535) err('watch: --port 需要合法端口号');
|
||||
const url = 'http://127.0.0.1:' + port + '/';
|
||||
const report = () => {
|
||||
process.stdout.write('预览地址:' + url + '\n停止预览:unwatch ' + file + '\n');
|
||||
process.exit(0);
|
||||
};
|
||||
const probe = (cb) => {
|
||||
const s = net.connect({ host: '127.0.0.1', port });
|
||||
s.setTimeout(300);
|
||||
s.once('connect', () => { s.destroy(); cb(true); });
|
||||
s.once('timeout', () => { s.destroy(); cb(false); });
|
||||
s.once('error', () => cb(false));
|
||||
};
|
||||
probe((up) => {
|
||||
if (up) return report();
|
||||
const logf = path.join(os.tmpdir(), 'officecli-watch-' + port + '.log');
|
||||
let fd;
|
||||
try { fd = fs.openSync(logf, 'a'); } catch (e) { err('watch: 无法写日志 ' + logf + ': ' + (e && e.message || e)); }
|
||||
const child = spawn(BIN, argv, {
|
||||
cwd: process.cwd(), env: vendorEnv(), detached: true, stdio: ['ignore', fd, fd],
|
||||
});
|
||||
try { fs.closeSync(fd); } catch (_) {}
|
||||
child.on('error', (e) => { err('watch 启动失败:' + (e && e.message || e)); });
|
||||
child.unref();
|
||||
let tries = 0;
|
||||
const tick = () => {
|
||||
probe((ok) => {
|
||||
if (ok) return report();
|
||||
if (++tries > 50) {
|
||||
let tail = '';
|
||||
try { tail = fs.readFileSync(logf, 'utf8').split('\n').slice(-5).join('\n').trim(); } catch (_) {}
|
||||
err('watch 未能在 5s 内就绪;日志:' + logf + (tail ? '\n' + tail : ''));
|
||||
}
|
||||
setTimeout(tick, 100);
|
||||
});
|
||||
};
|
||||
setTimeout(tick, 100);
|
||||
});
|
||||
}
|
||||
|
||||
if (LOCAL && first === 'watch' && !helpCmd && !(argv[2] && HIDDEN_SUBS.has(String(argv[2])))) {
|
||||
startWatch();
|
||||
// 不能落到下面的同步透传:spawnSync 会堵住事件循环,端口就绪的回调就再也跑不到
|
||||
return;
|
||||
}
|
||||
|
||||
// ---------- 透传 ----------
|
||||
let r;
|
||||
try {
|
||||
@@ -92,7 +155,8 @@ try {
|
||||
}
|
||||
if (r.error) {
|
||||
if (r.error.code === 'ENOENT') {
|
||||
err('office.core binary missing: ' + BIN + ' (skill asset not fetched: docker compose up -d agent-executor-init to retry, or place it per skills/office/install.sh)');
|
||||
err('office.core binary missing: ' + BIN + '\nLocal env: ' + path.resolve(__dirname, '..', 'AGENTS.md')
|
||||
+ ' (server: docker compose up -d agent-executor-init)');
|
||||
}
|
||||
err(String(r.error.message || r.error));
|
||||
}
|
||||
@@ -100,13 +164,14 @@ if (r.error) {
|
||||
let outRaw = scrub(r.stdout || '');
|
||||
// help 文本对齐可调用面:隐去的命令删行(原生 cwd 已是会话目录,无扩展命令需补录)
|
||||
if (helpCmd && outRaw.includes('Commands:')) {
|
||||
outRaw = outRaw.split('\n').filter((ln) => !HIDDEN_LINE.test(ln) && !HELP_STRIP.test(ln)).join('\n');
|
||||
outRaw = outRaw.split('\n')
|
||||
.filter((ln) => !HIDDEN_LINE.test(ln) && (LOCAL || !HELP_STRIP.test(ln))).join('\n');
|
||||
}
|
||||
if (outRaw) process.stdout.write(outRaw);
|
||||
if (r.stderr) process.stderr.write(scrub(r.stderr || ''));
|
||||
|
||||
// create/open 成功尾行发预览卡片 marker(core 解析后剥离;模型面无感)
|
||||
if (r.status === 0 && /^(create|open)$/.test(first)) {
|
||||
if (r.status === 0 && !LOCAL && /^(create|open)$/.test(first)) {
|
||||
let file = null;
|
||||
for (const t of argv) {
|
||||
const s = String(t);
|
||||
@@ -129,7 +194,7 @@ if (r.status === 0 && /^(create|open)$/.test(first)) {
|
||||
// 网关命中活槽位后 POST watch /api/switch 就地重读,页面靠 vendor 自带的 doc-switched 监听自刷。
|
||||
// fire-and-forget:800ms 封顶,一切失败静默——预览永远不是命令成功的前提。
|
||||
const CODE = r.status === null ? 1 : r.status;
|
||||
if (CODE === 0 && !process.env.OFFICE_JAIL && EDIT_RE.test(first) && argv[1]) {
|
||||
if (CODE === 0 && !LOCAL && !process.env.OFFICE_JAIL && EDIT_RE.test(first) && argv[1]) {
|
||||
let done = false;
|
||||
const finish = () => { if (done) return; done = true; process.exit(CODE); };
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# x2pdf
|
||||
|
||||
`ModuleNotFoundError`(`markdown`):把依赖装进 `$AGENT_SKILLS_DEPS`
|
||||
|
||||
```sh
|
||||
python3 -m pip install --upgrade --target "$AGENT_SKILLS_DEPS" -r "$(dirname "$AGENT_SKILLS_DEPS")/x2pdf/requirements.txt"
|
||||
```
|
||||
|
||||
## 后端缺哪个,代价多大
|
||||
|
||||
| 后端 | 缺了的影响 | 怎么补 |
|
||||
|---|---|---|
|
||||
| LibreOffice | **Office 类(docx/xlsx/pptx)完全不能转**,必装 | Linux `apt install libreoffice`;macOS `brew install --cask libreoffice`;Windows `winget install TheDocumentFoundation.LibreOffice` |
|
||||
| 浏览器 | 文本类落到 LibreOffice,CSS 基本失效 | 通常不用装:已有 Chrome / Chromium / Edge 就自动用 |
|
||||
| WeasyPrint | 文本类没有页码、`@page` 精确排版失效 | 先装 Python 包(见上),再补系统库 pango/cairo:Linux `apt install libpango-1.0-0 libpangocairo-1.0-0 libcairo2`;macOS `brew install pango`;Windows 补 GTK 运行库,装不上就跳过 |
|
||||
|
||||
报「没有可用的 PDF 排版能力」时:文本类有三个后端可退,按上表从便宜到贵补,别一次全装。
|
||||
输出带着「排版降级」(无页码/边距偏差)不是失败,是后端不全,按需补。
|
||||
系统级安装(几百 MB,老系统上可能源码编译十几分钟)先跟用户说清代价,由他决定装还是接受降级。
|
||||
|
||||
## 装完必须验证
|
||||
|
||||
`pip install` 成功不代表能用,缺系统库时 import 就炸:
|
||||
|
||||
```sh
|
||||
python3 -c "import weasyprint; print(weasyprint.__version__)"
|
||||
```
|
||||
|
||||
报 `could not import some external libraries` = 系统库(pango/cairo)还没到位,不是 Python 包的问题。
|
||||
@@ -37,8 +37,8 @@ output_schema:
|
||||
|
||||
统一 PDF 转换入口,按扩展名自动分派两条渲染路径:
|
||||
|
||||
- **md / txt / html → WeasyPrint**(CSS 排版,字体走 fontconfig,中文用系统文泉驿/Noto,无需字体文件)
|
||||
- **docx / xlsx / pptx / odt / ods / odp → LibreOffice headless**(忠于原文档版式,`page`/`css` 参数不生效)
|
||||
- **md / txt / html → 渲染成 PDF**(CSS 排版,字体走系统 fontconfig,中文用系统文泉驿/Noto,无需字体文件)
|
||||
- **docx / xlsx / pptx / odt / ods / odp → 按原文档版式转换**(`page`/`css` 参数不生效)
|
||||
|
||||
### Markdown 输入(`.md` / `.markdown`)
|
||||
- 标准语法之外,支持表格(管道语法)、围栏代码块(```/~~~)、脚注、定义列表、
|
||||
|
||||
@@ -4,4 +4,7 @@
|
||||
# 选 65.1:晚于 pydyf 0.12 发布,对 pydyf 0.11/0.12 兼容性经上游验证;
|
||||
# 系统要求(Pango>=1.44)与本技能 install.sh 声明一致。
|
||||
weasyprint==65.1
|
||||
markdown==3.6
|
||||
# markdown 不锁版:只用 markdown(text, extensions=['extra','toc']),3.x 全系稳定。
|
||||
# 锁了反而有害——服务端 init 用 `pip install --no-index --dry-run` 探测,写死版本与镜像里
|
||||
# 已有的不一致时会往 skills/deps 再装一份,而 PYTHONPATH 优先于系统 site-packages。
|
||||
markdown
|
||||
|
||||
+139
-9
@@ -3,13 +3,19 @@
|
||||
x2pdf 技能主入口:通用 PDF 转换。
|
||||
|
||||
分派策略(按输入文件扩展名):
|
||||
- .md / .markdown / .txt / .html / .htm → WeasyPrint 渲染
|
||||
- .md / .markdown / .txt / .html / .htm → 依次尝试 WeasyPrint / 无头浏览器 / LibreOffice
|
||||
三者都是本机可能没有的渲染后端:WeasyPrint 缺包或缺 pango/cairo 时不可用,
|
||||
浏览器(Chrome/Chromium/Edge)不需要任何 Python 依赖,保真度介于两者之间
|
||||
- .docx / .xlsx / .pptx / .odt / .ods / .odp → LibreOffice headless 转换
|
||||
|
||||
依赖不假设镜像预烘:Python 包由 requirements.txt 声明,系统库由 install.sh 就绪校验。
|
||||
LibreOffice 与浏览器的定位不只看 PATH:macOS 的 app bundle 与 Windows 的安装目录都不进 PATH,
|
||||
which() 找不到不等于没装(见 find_soffice / find_browser)。
|
||||
中文字体走 fontconfig(系统文泉驿/Noto),技能不携带字体文件。
|
||||
"""
|
||||
import contextlib
|
||||
import html as html_mod
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -27,6 +33,51 @@ SUPPORTED_EXTS = TEXT_EXTS | OFFICE_EXTS
|
||||
|
||||
PAGE_DEFAULTS = {'size': 'A4', 'margin': '20mm', 'font_size': '10.5pt'}
|
||||
|
||||
SKILL_DIR = Path(__file__).resolve().parent
|
||||
|
||||
|
||||
def find_soffice():
|
||||
"""定位 LibreOffice 可执行文件。
|
||||
PATH 优先(服务器/apt 装的都在);再探 macOS 的 app bundle 与 Windows 的安装目录——
|
||||
这两个位置正常安装都不进 PATH,只用 shutil.which() 会把「装了」误判成「没装」。"""
|
||||
for name in ('soffice', 'libreoffice'):
|
||||
p = shutil.which(name)
|
||||
if p:
|
||||
return p
|
||||
for c in ('/Applications/LibreOffice.app/Contents/MacOS/soffice',
|
||||
str(Path.home() / 'Applications/LibreOffice.app/Contents/MacOS/soffice'),
|
||||
r'C:\Program Files\LibreOffice\program\soffice.exe',
|
||||
r'C:\Program Files (x86)\LibreOffice\program\soffice.exe'):
|
||||
if Path(c).is_file():
|
||||
return c
|
||||
return None
|
||||
|
||||
|
||||
def find_browser():
|
||||
"""定位支持 --headless --print-to-pdf 的浏览器(Chrome / Chromium / Edge)。
|
||||
不要求用户为了转 PDF 装 Python 侧渲染栈:pango 在老系统上只能现编。
|
||||
同 find_soffice:macOS app bundle 与 Windows 安装目录都不进 PATH。"""
|
||||
for name in ('google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser',
|
||||
'microsoft-edge', 'msedge'):
|
||||
p = shutil.which(name)
|
||||
if p:
|
||||
return p
|
||||
for c in ('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
|
||||
'/Applications/Chromium.app/Contents/MacOS/Chromium',
|
||||
'/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
|
||||
str(Path.home() / 'Applications/Google Chrome.app/Contents/MacOS/Google Chrome'),
|
||||
r'C:\Program Files\Google\Chrome\Application\chrome.exe',
|
||||
r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe',
|
||||
r'C:\Program Files\Microsoft\Edge\Application\msedge.exe',
|
||||
r'C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe'):
|
||||
if Path(c).is_file():
|
||||
return c
|
||||
return None
|
||||
|
||||
|
||||
def req_hint():
|
||||
return '本机环境: %s' % (SKILL_DIR / 'AGENTS.md')
|
||||
|
||||
# 默认样式:黑白友好、打印向。字号用 em 相对值,整体缩放只依赖 html font-size
|
||||
# (由 page.font_size 参数注入),因此压单页只需调小字号/边距。
|
||||
DEFAULT_CSS = """
|
||||
@@ -136,9 +187,7 @@ def build_document(title, body_html):
|
||||
|
||||
|
||||
def convert_text_pdf(input_path, output_path, css_arg, page_arg):
|
||||
"""md/txt/html → WeasyPrint"""
|
||||
from weasyprint import CSS, HTML
|
||||
|
||||
"""md/txt/html → PDF。返回一句后端提示(正常走 WeasyPrint 时为空串)。"""
|
||||
ext = input_path.suffix.lower()
|
||||
text = input_path.read_text(encoding='utf-8', errors='replace')
|
||||
user_css = None
|
||||
@@ -157,7 +206,10 @@ def convert_text_pdf(input_path, output_path, css_arg, page_arg):
|
||||
sheets = [s for s in (page_css(page_arg, with_defaults=False), user_css) if s]
|
||||
else:
|
||||
if ext in MD_EXTS:
|
||||
import markdown
|
||||
try:
|
||||
import markdown
|
||||
except ImportError:
|
||||
raise RuntimeError('缺 Python 包 markdown,无法解析 Markdown;%s' % req_hint())
|
||||
# extra 已含 tables/fenced_code/footnotes/attr_list/md_in_html/sane_lists 等;
|
||||
# 不可再单独传其中的扩展名,否则 ExtensionAlreadyConfigured
|
||||
body = markdown.markdown(
|
||||
@@ -172,17 +224,92 @@ def convert_text_pdf(input_path, output_path, css_arg, page_arg):
|
||||
sheets.append(user_css)
|
||||
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
# 导入失败时 WeasyPrint 会往 stdout 打一大段「could not import some external libraries」
|
||||
# (text/ffi.py 里裸 print),模型会把这段当成真错。降级是预期行为,噪声吞掉,
|
||||
# 由返回值那句 note 告知实际后端。
|
||||
sink = io.StringIO()
|
||||
with contextlib.redirect_stdout(sink), contextlib.redirect_stderr(sink):
|
||||
from weasyprint import CSS, HTML
|
||||
except (ImportError, OSError):
|
||||
# 缺 Python 包是 ImportError;装了包但缺它要 dlopen 的 libpango/libgobject 时是 OSError。
|
||||
# 两种都当作「本机没有 WeasyPrint」:先试浏览器(只需装了 Chrome 系),再回落 LibreOffice。
|
||||
browser = find_browser()
|
||||
if browser:
|
||||
return convert_html_browser(browser, document, output_path, base_url, sheets, ext)
|
||||
return convert_html_pdf(document, output_path, ext)
|
||||
# 注:stylesheets 参数只接受 CSS 对象,传字符串会被当成文件路径
|
||||
HTML(string=document, base_url=base_url).write_pdf(
|
||||
str(output_path), stylesheets=[CSS(string=s) for s in sheets] or None)
|
||||
return ''
|
||||
|
||||
|
||||
def inject_styles(document, sheets, base_url):
|
||||
"""把 CSS 与 base 标签塞进已有 HTML:浏览器后端只能吃单个文件。
|
||||
注入点是 </head>(其次 <body>),绝不能落到 doctype 前面——那会触发怪异模式。"""
|
||||
head = ''
|
||||
if base_url:
|
||||
head += '<base href="%s/">\n' % Path(base_url).resolve().as_uri()
|
||||
if sheets:
|
||||
head += '<style>\n%s\n</style>\n' % '\n'.join(sheets)
|
||||
if not head:
|
||||
return document
|
||||
m = re.search(r'</head\s*>', document, re.I) or re.search(r'<body[^>]*>', document, re.I)
|
||||
if m:
|
||||
return document[:m.start()] + head + document[m.start():]
|
||||
d = re.match(r'\s*<!doctype[^>]*>', document, re.I)
|
||||
if d:
|
||||
return document[:d.end()] + '\n' + head + document[d.end():]
|
||||
return head + document
|
||||
|
||||
|
||||
def convert_html_browser(browser, document, output_path, base_url, sheets, ext):
|
||||
"""HTML → 无头浏览器打印:WeasyPrint 不可用时的中间档。
|
||||
浏览器能完整解析 CSS(表格边框/底纹/分页),但页码是 WeasyPrint 的 CSS 计数器特性,
|
||||
这里不生效;@page 的 size/margin 视浏览器版本部分生效。"""
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_root = Path(tempfile.mkdtemp(prefix='x2pdf-browser-'))
|
||||
try:
|
||||
# 浏览器默认纸张是 Letter,WeasyPrint 默认 A4。文档自己没写 @page 时补上 A4,
|
||||
# 否则同一份 html 换后端就换纸型。
|
||||
if not any('@page' in s for s in sheets) and '@page' not in document:
|
||||
sheets = list(sheets) + ['@page { size: A4; }']
|
||||
src = tmp_root / 'document.html'
|
||||
src.write_text(inject_styles(document, sheets, base_url), encoding='utf-8')
|
||||
cmd = [browser, '--headless', '--disable-gpu', '--no-pdf-header-footer',
|
||||
'--virtual-time-budget=2000',
|
||||
'--print-to-pdf=%s' % str(output_path.resolve()), src.as_uri()]
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True, timeout=120)
|
||||
if not output_path.is_file() or output_path.stat().st_size == 0:
|
||||
detail = (proc.stderr or proc.stdout or '').strip().replace('\n', ' ')[:300]
|
||||
raise RuntimeError('PDF 生成失败(exit=%s):%s' % (proc.returncode, detail or '无输出'))
|
||||
finally:
|
||||
shutil.rmtree(tmp_root, ignore_errors=True)
|
||||
return '排版降级:无页码,尺寸/边距可能与预期有偏差'
|
||||
|
||||
|
||||
def convert_html_pdf(document, output_path, ext):
|
||||
"""HTML → LibreOffice:最后一道回落(浏览器也没有时)。
|
||||
代价是保真度:@page 的边距/页码与大部分 CSS 在 LibreOffice 的 HTML 导入里不生效,
|
||||
适合「拿到一份能看的 PDF」,不适合精确排版。"""
|
||||
if not find_soffice():
|
||||
raise RuntimeError('这台机器没有可用的 PDF 排版能力,无法转换 %s;%s' % (ext, req_hint()))
|
||||
tmp_root = Path(tempfile.mkdtemp(prefix='x2pdf-html-'))
|
||||
try:
|
||||
src = tmp_root / 'document.html'
|
||||
src.write_text(document, encoding='utf-8')
|
||||
convert_office_pdf(src, output_path)
|
||||
finally:
|
||||
shutil.rmtree(tmp_root, ignore_errors=True)
|
||||
return '排版降级:边距/页码与部分 CSS 不生效'
|
||||
|
||||
|
||||
def convert_office_pdf(input_path, output_path):
|
||||
"""docx/xlsx/pptx 等 → LibreOffice headless。
|
||||
每次用独立临时 UserInstallation/HOME,避免并发实例互踩共享配置。"""
|
||||
soffice = shutil.which('soffice') or shutil.which('libreoffice')
|
||||
soffice = find_soffice()
|
||||
if not soffice:
|
||||
raise FileNotFoundError('未找到 soffice/libreoffice,无法转换 Office 文档(需镜像预装)')
|
||||
raise FileNotFoundError('这台机器没有可用于转换 Office 文档的组件;%s' % req_hint())
|
||||
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_root = Path(tempfile.mkdtemp(prefix='x2pdf-office-'))
|
||||
@@ -203,7 +330,7 @@ def convert_office_pdf(input_path, output_path):
|
||||
generated = pdf_dir / (input_path.stem + '.pdf')
|
||||
if not generated.exists():
|
||||
detail = (proc.stderr or proc.stdout or '').strip().replace('\n', ' ')[:300]
|
||||
raise RuntimeError('LibreOffice 转换失败(exit=%s):%s' % (proc.returncode, detail or '无输出'))
|
||||
raise RuntimeError('文档转换失败(exit=%s):%s' % (proc.returncode, detail or '无输出'))
|
||||
shutil.move(str(generated), str(output_path))
|
||||
finally:
|
||||
shutil.rmtree(tmp_root, ignore_errors=True)
|
||||
@@ -239,6 +366,7 @@ def main():
|
||||
output_arg = args.get('output')
|
||||
output_path = Path(output_arg) if output_arg else input_path.with_suffix('.pdf')
|
||||
|
||||
note = ''
|
||||
try:
|
||||
if ext in OFFICE_EXTS:
|
||||
ignored = [k for k in ('css', 'page') if args.get(k)]
|
||||
@@ -246,12 +374,14 @@ def main():
|
||||
print('提示:Office 输入忽略参数 %s' % '、'.join(ignored))
|
||||
convert_office_pdf(input_path, output_path)
|
||||
else:
|
||||
convert_text_pdf(input_path, output_path, args.get('css'), args.get('page'))
|
||||
note = convert_text_pdf(input_path, output_path, args.get('css'), args.get('page'))
|
||||
except Exception as e:
|
||||
print('Error during conversion: %s' % e, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
print('PDF generated: %s' % output_path.resolve())
|
||||
if note:
|
||||
print(note)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
Reference in New Issue
Block a user