diff --git a/.github/workflows/platform.yml b/.github/workflows/platform.yml index 612590753..89d6b1d83 100644 --- a/.github/workflows/platform.yml +++ b/.github/workflows/platform.yml @@ -24,6 +24,10 @@ jobs: run: bash scripts/build-chatbot.sh - name: Let Chromium use its sandbox as an unprivileged user run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + # Engine and API tests run SOP nodes in the shared test-native sandbox, + # which is bwrap on Linux. + - name: Install bubblewrap for the native sandbox + run: sudo apt-get update && sudo apt-get install -y bubblewrap - name: Warm up Chromium so the first real-browser test does not pay the cold start run: | for name in chromium chromium-browser google-chrome-stable google-chrome; do @@ -87,6 +91,19 @@ jobs: working-directory: e2e - run: bash ../scripts/install-playwright-deps.sh npx playwright working-directory: e2e + # The e2e SOPs and the runner the suite starts use the native e2e sandbox, + # which is bwrap on Linux. + - name: Let bubblewrap create user namespaces + run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0 + - name: Install bubblewrap for the native sandbox + run: sudo apt-get update && sudo apt-get install -y bubblewrap + # The welcome SOP runs in generic-docker. As in a Compose installation, it + # uses the pinned platform image instead of building one during the tests. + - name: Pull the pinned platform image for the generic-docker sandbox + run: | + pinned=$(sed -n 's/^ *image: \${LOOPFORGE_IMAGE:-\(.*\)}$/\1/p' compose.yaml) + docker pull --quiet "$pinned" + echo "AGENTFLOW_ISOLATED_IMAGE=$pinned" >> "$GITHUB_ENV" - name: Start clean local installation run: | bash scripts/dev.sh > /tmp/loopforge.log 2>&1 & @@ -172,6 +189,8 @@ jobs: # The path a new user takes: one-command install, then accounts created in the browser. # Pulls the GHCR release pinned in compose.yaml; release.yml smoke-tests each newly published image. # A pin bumped ahead of its tag has no image yet, so that commit is checked from source. + # So is a commit whose schema scripts differ from the pinned tag: the installer applies + # this checkout's scripts, which the released image may not be able to read. runs-on: ubuntu-latest timeout-minutes: 30 env: @@ -187,14 +206,22 @@ jobs: working-directory: e2e - run: bash ../scripts/install-playwright-deps.sh npx playwright working-directory: e2e - - name: Install the pinned release, or build it while that release is not published yet + - name: Install the pinned release, or build this checkout when the release cannot run it run: | pinned=$(sed -n 's/^ *image: \${LOOPFORGE_IMAGE:-\(.*\)}$/\1/p' compose.yaml) - if docker manifest inspect "$pinned" > /dev/null 2>&1; then - ./start.sh -d - else + tag="v${pinned##*:}" + schema=(migrations scripts/install-schema-extensions.sh scripts/install-observability-schema.sh) + if ! docker manifest inspect "$pinned" > /dev/null 2>&1; then echo "::notice::$pinned is not published yet; building this checkout" ./start.sh dev + elif ! git fetch --quiet --depth=1 origin "refs/tags/$tag:refs/tags/$tag"; then + echo "::warning::could not fetch $tag to compare schema scripts; installing $pinned" + ./start.sh -d + elif ! git diff --quiet "$tag" -- "${schema[@]}"; then + echo "::notice::schema scripts changed since $tag; building this checkout" + ./start.sh dev + else + ./start.sh -d fi - name: Generate test passwords run: | diff --git a/AGENTS.md b/AGENTS.md index d4641dc8c..432f54e30 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,7 @@ Preserve the platform architecture; keep deployment-specific adapters isolated. | 领域 Repo | 拥有 | |---|---| -| `CatalogRepo` | agents/rules/skills/MCP servers/executors/dockerfiles/environments/sandboxes/workflows/repositories/sync config/schedule jobs/definition revisions/generic templates | +| `CatalogRepo` | agents/rules/skills/MCP servers/executors/sandboxes(内嵌 Dockerfile 与安装脚本)/workflows/repositories/sync config/schedule jobs/definition revisions/generic templates | | `ProjectsRepo` | projects、project members | | `IssuesRepo` | issues、issue comments | | `TasksRepo` | tasks(跨实例幂等记录) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 48c3c9e59..4f52ad9f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,9 @@ Platform releases use `vX.Y.Z` tags and publish `ghcr.io/tencent/loopforge`. Loo - On macOS `/bin/bash` 3.2, a missing local image or a failed automatic mirror pull no longer aborts `./start.sh` before the official image pull. - `./start.sh` and `./start.sh pull` time `ghcr.io` and `ghcr.nju.edu.cn`. Nanjing is used only when the ghcr.io manifest digest was verified and the mirror returned the same digest; the pull is that digest, then tagged back to the name pinned in `compose.yaml`. A missing official digest, a digest mismatch, or a failed mirror pull stays on `ghcr.io`. `MIRROR=ghcr.io` forces the upstream registry; `MIRROR=` still forces that host and does not fall back. Accepting Nanjing, or setting `MIRROR`, trusts that host. The choice is not saved in `.env`. `registry-mirrors` such as `https://docker.nju.edu.cn` only accelerates Docker Hub. +- **Breaking:** `local` sandboxes are now bound to one execution machine and its owner, and are for conversation workspaces only. A local workspace starts empty like any other conversation workspace; the repository list sent to the agent names each repository's checkout on the machine (its configured path, or a clone under `~/.loopforge/local`), and the agent adds git worktrees of it when a task needs the repository instead of cloning into the workspace. The workspace keeps its files and worktrees until it is deleted, and follows Claude Code's default permission rules for every CLI: reads, searches and built-in read-only commands inside the workspace run directly, while other commands, edits and reads outside the workspace follow the chosen approval mode. SOPs can no longer use `local`; the default sandbox is `generic-docker`, and `AGENTFLOW_LOCAL_SANDBOX` is removed. Unbound local profiles must be re-saved by the machine owner; run `migrations/040_local_sandbox_runner_only.sql` to move built-in SOPs to `generic-docker`. Local workspaces need Runner 0.12.0. +- 设置 → AI 助手 gains 「对话工作区」: users choose the sandbox kind (Docker, native or local) the assistant prefers when it opens a conversation workspace itself. The preference (`workspaceDriver` in `/api/assistant/preferences`) puts that kind first in the assistant's choices and is used when it names no environment; the assistant still switches when only another environment has the toolchain a task needs, and a conversation's fixed environment still wins. The workbench environment picker now also lists native sandboxes, and local sandboxes bound to the conversation's machine for their owner, grouped by kind. `migrations/042_assistant_workspace_driver.sql` adds the column for deployments that apply DDL by hand; startup AutoMigrate also adds it. +- **Breaking:** a sandbox now carries its own Dockerfile (docker) or environment install script (native), and the 环境资产 page becomes 「沙箱管理」 without type tabs: the sandbox editor holds the Dockerfile and its build-context files, or the install script, PATH entries and install variables. Dockerfiles and install scripts are no longer separate assets that sandboxes reference and share on their own. `/api/dockerfiles`, `/api/environments`, the `dockerfiles_*` / `environments_*` assistant and MCP tools and the `dockerfiles` / `environments` bootstrap fields are removed; `PUT /api/sandboxes` takes `dockerfile {content, files}` and `install {script, pathEntries, variables}` in place of `dockerfileId` and `environmentId`. Run `migrations/041_sandbox_inline_assets.sql` after upgrading (the installer and `./start.sh pull` run it): it copies each referenced Dockerfile and install script into its sandbox, turns one that no sandbox used into a sandbox of its own, and drops the `dockerfiles` and `environments` tables. Docker images are reused; a native sandbox reinstalls its toolchain once. The runner protocol is unchanged. ## 0.4.0 — scheduled task history, an MR node in delivery SOPs and agent CLIs in conversation workspaces diff --git a/chatbot/src/NativeApprovalPanel.jsx b/chatbot/src/NativeApprovalPanel.jsx index bde4b75d9..b0a1e49dd 100644 --- a/chatbot/src/NativeApprovalPanel.jsx +++ b/chatbot/src/NativeApprovalPanel.jsx @@ -3,8 +3,8 @@ import { api, write, sessionPath } from "./api"; import HarnessIcon from "./HarnessIcon"; import "./native-approval.css"; -// External commands and external MCP writes can wait here for the speaker -// in "请求批准" mode. +// External commands and external MCP writes, and every non-read action of a +// local workspace, can wait here for the speaker in "请求批准" mode. function commandText(input) { const command = input?.command ?? input?.cmd ?? input?.commands; if (typeof command === "string") return command; @@ -56,15 +56,15 @@ export default function NativeApprovalPanel({ chat, onChange }) { }, [pendingIds]); if (!mine.length) return null; return ( -
+
{mine.map((item) => (
{commandText(item.input)}
-

这项操作会写入外部系统。仅批准这一次。停止回复、调用取消或等待超时后,审批会失效。

+

{item.local ? "这项操作直接在你的执行机器上执行,没有沙箱隔离。" : "这项操作会写入外部系统。"}仅批准这一次。停止回复、调用取消或等待超时后,审批会失效。

`; } function renderAssetGrid(){ @@ -97,7 +97,9 @@ function assetCurrent(){ } function assetDetailHeadHTML(a,{creating=false,dirty=false}={}){ const kind=assetKindLabel(),copy=assetPageCopy(),readonly=!creating&&!catalogOwned(a.projectId); - const badge=creating?'':readonly?`来自 ${escapeHTML(assetProjectName(a))}`:`${a.shared?'已共享':'未共享'}`; + // A local sandbox belongs to its runner owner and is never shared. + const shareable=!(state.assetType==='sandboxes'&&a.driver==='local'); + const badge=creating?'':readonly?`来自 ${escapeHTML(assetProjectName(a))}`:shareable?`${a.shared?'已共享':'未共享'}`:''; const title=creating?`新建${kind}`:(a.name||a.id); const desc=creating?`填写标识和名称后创建${state.assetType==='skills'?',创建后即可上传文件':''}。`:(a.description||'暂无说明'); let actions; @@ -106,7 +108,7 @@ function assetDetailHeadHTML(a,{creating=false,dirty=false}={}){ else{ const blocked=assetDeleteBlocked(a); actions=`未保存`+ - ``+ + (shareable?``:'')+ `
`+ `
`+ ``; @@ -116,7 +118,7 @@ function assetDetailHeadHTML(a,{creating=false,dirty=false}={}){ function renderAssetDetailHead(a){ const creating=state.selectedAsset==='__new__',copy=assetPageCopy(); const crumbs=$('#assetCrumbs'); - if(crumbs)crumbs.innerHTML=`${escapeHTML(copy.page)} · ${escapeHTML(copy.tab)}${huiIcon('chevron-right')}${escapeHTML(creating?`新建${assetKindLabel()}`:(a.name||a.id))}`; + if(crumbs)crumbs.innerHTML=`${escapeHTML(copy.crumb||`${copy.page} · ${copy.tab}`)}${huiIcon('chevron-right')}${escapeHTML(creating?`新建${assetKindLabel()}`:(a.name||a.id))}`; const head=$('#assetDetailHead');if(!head)return; closeAssetMenu(); head.innerHTML=assetDetailHeadHTML(a,{creating,dirty:!!state.assetDirty}); @@ -254,22 +256,19 @@ async function toggleAssetShare(id){ toast(saved.shared?(state.assetType==='skills'?'已共享,所有对话和定时任务会自动装入':'已共享,其他项目可绑定'):'已取消共享'); }catch(e){toast(e.message)} } -function assetEmptyHint(){return ({rules:'规则是写给 Agent 的行为约束,例如编码规范、禁止事项。建好后在「角色定义」里绑定到角色。',skills:'技能是 Agent 可按需加载的说明和附加文件,例如某个框架的操作手册。建好后在「角色定义」里绑定到角色。',dockerfiles:'Dockerfile 定义沙箱容器的镜像。建好后在「沙箱管理」里选用;也可以直接用「共享」里的现成配置。',environments:'安装脚本在沙箱初始化时把工具装进隔离环境,例如指定版本的 Go、PHP、Node。建好后在「沙箱管理」里选用。',sandboxes:'沙箱决定 SOP 节点在什么隔离环境里执行,由 Dockerfile 和安装脚本组合而成。建好后在流程设置里选用;也可以直接用「共享」里的现成配置。'})[state.assetType]||''} -function assetKindLabel(){return ({rules:'规则',skills:'技能',dockerfiles:'Dockerfile',environments:'环境安装脚本',sandboxes:'沙箱'})[state.assetType]||'资产'} -function assetRefKindLabel(){return ({rules:'角色',skills:'角色',dockerfiles:'沙箱',environments:'沙箱',sandboxes:'流程'})[state.assetType]||'引用'} +function assetEmptyHint(){return ({rules:'规则是写给 Agent 的行为约束,例如编码规范、禁止事项。建好后在「角色定义」里绑定到角色。',skills:'技能是 Agent 可按需加载的说明和附加文件,例如某个框架的操作手册。建好后在「角色定义」里绑定到角色。',sandboxes:'沙箱决定 SOP 节点和对话工作区在什么隔离环境里执行:docker 沙箱自带 Dockerfile,native 沙箱自带环境安装脚本。建好后在流程设置里选用;也可以直接用「共享」里的现成配置。'})[state.assetType]||''} +function assetKindLabel(){return ({rules:'规则',skills:'技能',sandboxes:'沙箱'})[state.assetType]||'资产'} +function assetRefKindLabel(){return ({rules:'角色',skills:'角色',sandboxes:'流程'})[state.assetType]||'引用'} function assetReferenceNames(a){ if(!a?.id)return []; if(state.assetType==='rules')return (state.data.agents||[]).filter(x=>(x.rules||[]).includes(a.id)).map(x=>x.name||x.id); if(state.assetType==='skills')return (state.data.agents||[]).filter(x=>(x.skills||[]).includes(a.id)).map(x=>x.name||x.id); - if(state.assetType==='dockerfiles')return (state.data.sandboxes||[]).filter(x=>x.dockerfileId===a.id).map(x=>x.name||x.id); - if(state.assetType==='environments')return (state.data.sandboxes||[]).filter(x=>x.environmentId===a.id).map(x=>x.name||x.id); if(state.assetType==='sandboxes')return (state.data.workflows||[]).filter(x=>!catalogGeneric(x)&&x.sandboxProfileId===a.id).map(x=>x.name||x.id); return []; } function assetDeleteBlocked(a){ if(!a?.id)return '无法删除'; - if(state.assetType==='sandboxes'&&(a.id==='local'||a.id==='generic-docker'))return `内置沙箱 ${a.id} 不能删除`; - if(state.assetType==='dockerfiles'&&a.id==='generic-backend')return '内置 Dockerfile generic-backend 不能删除'; + if(state.assetType==='sandboxes'&&a.id==='generic-docker')return `内置沙箱 ${a.id} 不能删除`; if(a.shared)return `共享状态的${assetKindLabel()}不能删除,请先取消共享`; const refs=assetReferenceNames(a); if(refs.length)return `${assetKindLabel()}仍被 ${refs.length} 个${assetRefKindLabel()}引用(${refs.join('、')}),请先解除引用`; @@ -298,14 +297,55 @@ function selectedRuleWorkflowIds(){try{const ids=JSON.parse($('#ruleSOPPicker')? function setRuleWorkflowIds(ids){const host=$('#ruleSOPPicker');if(!host)return;const known=new Set(ruleSOPChoices().map(w=>w.id));host.dataset.ids=JSON.stringify([...new Set((ids||[]).map(id=>String(id||'').trim()).filter(id=>id&&known.has(id)))]);renderRuleSOPPicker();markAssetDirty()} function renderRuleSOPPicker(){const host=$('#ruleSOPPicker');if(!host)return;const sops=ruleSOPChoices();const selected=selectedRuleWorkflowIds();const chosen=new Set(selected);const leftover=sops.filter(w=>!chosen.has(w.id));const tags=selected.map(id=>{const sop=sops.find(w=>w.id===id);const name=sop?.name||id;const nodes=sop?.nodes?.length||0;const label=nodes?`${name} · ${nodes} 个节点`:name;return ``}).join('');const options=leftover.map(w=>``).join('');const placeholder=!sops.length?'暂无可选 SOP':(!leftover.length?'已全部选择':'+ 添加 SOP…');host.innerHTML=`
${tags}
`;host.querySelectorAll('[data-remove-rule-sop]').forEach(b=>b.onclick=()=>setRuleWorkflowIds(selected.filter(id=>id!==b.dataset.removeRuleSop)));const sel=host.querySelector('select');if(sel)sel.onchange=()=>{if(!sel.value)return;setRuleWorkflowIds([...selected,sel.value])}} function bindRuleGlobalPicker(a){const host=$('#ruleSOPPicker');if(!host)return;const known=new Set(ruleSOPChoices().map(w=>w.id));host.dataset.ids=JSON.stringify((Array.isArray(a.workflowIds)?a.workflowIds:[]).filter(id=>known.has(id)));const toggle=document.querySelector('#assetForm [name="global"]');const wrap=$('#ruleSOPPickerWrap');const sync=()=>{if(wrap)wrap.hidden=!(toggle&&toggle.checked)};if(toggle)toggle.onchange=sync;sync();renderRuleSOPPicker()} -function dockerfileOptions(selected){const items=(state.data.dockerfiles||[]).filter(x=>catalogVisible(x.projectId,x.shared));if(!items.length)return ``;return ``+items.map(x=>``).join('')} -function environmentOptions(selected){const items=(state.data.environments||[]).filter(x=>catalogVisible(x.projectId,x.shared));return ``+items.map(x=>``).join('')} // seatbelt / bwrap are the per-OS forms of native; rows saved before the merge still carry them. -function sandboxDriverOption(driver){return ['seatbelt','bwrap','native'].includes(driver)?'native':driver==='docker'?'docker':'local'} -function syncSandboxDriverFields(select){const driver=select?.value||'local';select?.form?.querySelectorAll('[data-sandbox-drivers]').forEach(el=>{el.hidden=!el.dataset.sandboxDrivers.split(' ').includes(driver)})} +function sandboxDriverOption(driver){return ['seatbelt','bwrap','native'].includes(driver)?'native':driver==='local'?'local':'docker'} +function syncSandboxDriverFields(select){const driver=select?.value||'docker';select?.form?.querySelectorAll('[data-sandbox-drivers]').forEach(el=>{el.hidden=!el.dataset.sandboxDrivers.split(' ').includes(driver)})} +// A local sandbox runs on its owner's own execution machine, so only runners the current user owns are offered. +function localSandboxRunnerOptions(selected){const uid=Number(state.currentUser?.id)||0;const mine=(state.runners||[]).filter(r=>uid>0&&Number(r.ownerUserId)===uid);const options=mine.map(r=>``);if(selected&&!mine.some(r=>r.id===selected))options.unshift(``);return ``+options.join('')} +function localSandboxRepositories(a){const projectId=a.projectId||state.projectFilter||'';return (state.data.repositories||[]).filter(r=>r.projectId===projectId)} +function localSandboxRepoPathsHTML(a){const repos=localSandboxRepositories(a),paths=a.repositoryPaths||{};if(!repos.length)return `
本项目还没有仓库。
`;return `
`+repos.map(r=>``).join('')+`
`} +function localSandboxRepositoryPaths(f,a){const shown=new Set(localSandboxRepositories(a).map(r=>r.id)),paths={};Object.entries(a?.repositoryPaths||{}).forEach(([id,path])=>{if(!shown.has(id))paths[id]=path});f.querySelectorAll('[data-local-repo-path]').forEach(input=>{const path=input.value.trim();if(path)paths[input.dataset.localRepoPath]=path});return paths} +async function refreshLocalSandboxRunners(f,selected){try{state.runners=await api('/api/runners?mine=1',{silent:true})||[]}catch{return}const select=f.elements.runnerId;if(select&&f.isConnected)select.innerHTML=localSandboxRunnerOptions(select.value||selected||'')} function resolveAssetSaveIdentity(items,selectedID,requestedID){if(selectedID!=='__new__'){const existing=(items||[]).find(item=>item.id===selectedID);return existing?{id:existing.id,existing,created:false}:{error:'选中的资产已不存在,请刷新后重试'}}if((items||[]).some(item=>item.id===requestedID))return {error:'该标识已存在,请换一个标识,或回到列表打开已有资产修改'};return {id:requestedID,existing:null,created:true}} -function assetPaneTabs(type=state.assetType){return ({rules:[['edit','编辑'],['preview','预览']],skills:[['files','文件']],dockerfiles:[['content','Dockerfile'],['files','构建上下文']],environments:[['script','install.sh'],['vars','环境变量'],['path','PATH']],sandboxes:[['env','环境变量']]})[type]||[['edit','编辑']]} -function assetPaneHint(type=state.assetType){return ({rules:'支持 Markdown',skills:'每次上传都会完整替换现有文件',dockerfiles:'沙箱初始化时用库里这份 docker build',environments:'脚本把工具装进 $PREFIX',sandboxes:'驱动与执行环境在右侧设置,不要在这里保存凭证'})[type]||''} +function assetPaneTabs(type=state.assetType){return ({rules:[['edit','编辑'],['preview','预览']],skills:[['files','文件']],sandboxes:[['setup','配置']]})[type]||[['edit','编辑']]} +function assetPaneHint(type=state.assetType){return ({rules:'支持 Markdown',skills:'每次上传都会完整替换现有文件',sandboxes:'隔离方式决定沙箱在哪里、怎样执行'})[type]||''} +function assetFieldLabel(text,help,forId=''){return `
${forId?``:`${escapeHTML(text)}`}${help?``:''}
`} +function sandboxSetupHTML(a){const driver=sandboxDriverOption(a.driver);return `
+ ${assetFieldLabel('隔离方式','docker 在 OCI 容器里执行;native 按执行机器的系统自动选择 seatbelt(macOS)或 bwrap(Linux);local 只用于对话工作区,直接在你自己的执行机器上用 git worktree 工作,不做隔离,SOP 不能使用。')} + +
+ ${assetFieldLabel('Dockerfile','保存在这个沙箱里。沙箱初始化时用它 docker build 出镜像;内容相同的沙箱共用同一个镜像。不要指向仓库目录或现成镜像名。','assetDockerfile')} + + ${assetFieldLabel('构建上下文文件','JSON 对象:键是构建上下文里的相对路径,值是文件内容,和 Dockerfile 一起保存,可在 Dockerfile 里 COPY。','assetDockerfileFiles')} + +
+ + + + + +
+
+
+ ${assetFieldLabel('环境安装脚本','沙箱初始化时执行一次,把工具装进隔离的 $PREFIX;脚本内容变化后重新安装,只改安装变量不会触发重装。不要往宿主机写。留空时,若 workspace 存在 agentflow-environment/ 也会自动启用。','assetInstallScript')} + +
$PREFIX 是这个沙箱专属的工具目录,位于工作区的 .agentflow/environment/<沙箱标识>,每个新工作区都会重新安装一次。脚本把工具装进这里,$PREFIX/bin 自动排在 PATH 最前面;下面的 PATH 条目和安装变量里也可以用 $PREFIX 指代它。
+ ${assetFieldLabel('PATH 条目','$PREFIX/bin 总会排在 PATH 最前面;这里追加 $PREFIX 下的其他目录(相对路径),每行一个。','assetInstallPath')} + + ${assetFieldLabel('安装变量','JSON 对象,安装脚本和执行时都会设置,值里可以引用 $PREFIX。','assetInstallVars')} + +
+
+ ${assetFieldLabel('执行机器','只能选你自己的执行机器;对话固定在这台机器上时才能使用这个沙箱。')} + + ${assetFieldLabel('基础目录','执行机器上的绝对路径或 ~/ 开头的路径。没有配置路径的仓库第一次用到时 clone 到这里的同名目录。留空使用 ~/.loopforge/local。','assetLocalBaseDir')} + + ${assetFieldLabel('仓库路径','填执行机器上已有的仓库目录。对话用到这个仓库时,Agent 从这里切出 git worktree,只在其中 fetch 并新增 worktree 和工作分支,不改动已检出的文件。')} + ${localSandboxRepoPathsHTML(a)} +
+ ${assetFieldLabel('环境变量','JSON 对象,叠加到沙箱基础环境并随资产保存;不要在这里保存凭证。平台凭证、HOME/TMPDIR 和遥测变量优先级更高。')} + +
`} function assetMainPanesHTML(a,{creating,readonly}){ const pane=(key,body)=>`
${body}
`; if(state.assetType==='rules')return pane('edit',``)+pane('preview',`
`); @@ -327,26 +367,13 @@ function assetMainPanesHTML(a,{creating,readonly}){ ${locked?'':`
每次上传都是完全替换:文件夹 / zip 替换为整批文件;单独上传 SKILL.md 会先弹出确认,然后该技能只保留这一份 SKILL.md。单文件 ≤1MB,最多 500 个,单技能 ≤64MB。zip 自动解包并保留可执行位;markdown / 代码 / 图片可直接预览。
`}
`); } - if(state.assetType==='dockerfiles')return pane('content',`
正文和附加文件保存在这条 Dockerfile 资产里,写入数据库,和 install.sh 一样。不要指向仓库目录或现成镜像名。沙箱初始化时用库里这份 docker build 出一次性镜像。
`)+pane('files',`
键是构建上下文里的相对路径,值是文件内容;与 Dockerfile 一起保存。
`); - if(state.assetType==='environments')return pane('script',`
脚本保存在环境资产里。Studio 保存即写库;下次沙箱初始化会按库里这份执行,把工具装进 $PREFIX。不要往宿主机写。脚本内容变化后会重新安装。
`)+pane('vars',``)+pane('path',``); - if(state.assetType==='sandboxes')return pane('env',`
叠加到沙箱基础环境并随资产持久化;不要在这里保存凭证。平台凭证、HOME/TMPDIR 和遥测变量拥有更高优先级。
`); + if(state.assetType==='sandboxes')return pane('setup',sandboxSetupHTML(a)); return ''; } function assetBasicFieldsHTML(a,{creating}){ const kind=assetKindLabel(); let html=`
${creating?'创建后不可修改,用于资产引用。':'标识用于资产引用,创建后不可修改。'}
`; if(state.assetType==='rules')html+=`
数值越大越先注入。
${ruleGlobalFields(a)}`; - if(state.assetType==='sandboxes')html+=`
直接在本机 workspace 执行,并继承受控的宿主进程环境。
按执行机器的系统自动选择:macOS 用 seatbelt,Linux 用 bwrap。
选中后沙箱会执行该环境的 install.sh,把工具装进隔离的 $PREFIX,再用 PATH 切换。未选择时,若 workspace 存在 agentflow-environment/ 也会自动启用。
沙箱只引用这条目录资产;初始化时用库里的内容构建临时镜像,结束后删除容器和镜像。
-
- - - - - -
`; return html; } function assetAsideHTML(a,{creating}){ @@ -373,9 +400,8 @@ function renderAssetForm(a){ if(state.assetType==='sandboxes'){ f.elements.driver.onchange=()=>syncSandboxDriverFields(f.elements.driver); syncSandboxDriverFields(f.elements.driver); - f.querySelector('#assetReadOnlyRootFSHelp')?.addEventListener('click',event=>{ - window.HuiTooltip?.show(event.currentTarget); - }); + refreshLocalSandboxRunners(f,a.runnerId); + f.querySelectorAll('.field-help').forEach(button=>button.addEventListener('click',event=>window.HuiTooltip?.show(event.currentTarget))); } f.querySelectorAll('select.asset-select').forEach(sel=>window.enhanceSelect?.(sel)); if(readonly)f.querySelectorAll('input,textarea,select,.repo-picker-tag').forEach(el=>{if(el.type!=='file')el.disabled=true}); @@ -690,10 +716,8 @@ async function openSkillFilePreview(skill, path){ async function saveAsset(e){e.preventDefault();const f=e.currentTarget,items=state.data[state.assetType]||[],projectScoped=isProjectSharedAsset(state.assetType),identity=resolveAssetSaveIdentity(items,state.selectedAsset,f.elements.id.value.trim());if(identity.error)return toast(identity.error);const existing=identity.existing;if(existing&&projectScoped&&catalogForeign(existing.projectId))return toast('共享资产只读');let value={id:identity.id,name:f.elements.name.value.trim(),description:f.elements.description.value,projectId:existing?(existing.projectId||''):(state.projectFilter||''),shared:projectScoped&&!!existing?.shared};if(!value.id||!value.name)return toast('标识和名称不能为空');try{ if(state.assetType==='rules'){const global=!!f.elements.global?.checked;Object.assign(value,{priority:Number(f.elements.priority.value),content:f.elements.content.value,global,workflowIds:global?selectedRuleWorkflowIds():[]})} if(state.assetType==='skills'){/* 文件经独立上传接口承载;此处只提交元数据。服务端会强制保留 Content/Files/FileRefs。 */} - if(state.assetType==='dockerfiles')Object.assign(value,{content:f.elements.content.value,files:JSON.parse(f.elements.files.value||'{}')}); - if(state.assetType==='environments')Object.assign(value,{variables:JSON.parse(f.elements.variables.value||'{}'),pathEntries:lines(f.elements.pathEntries.value),installScript:f.elements.installScript.value}); - if(state.assetType==='sandboxes'){const driver=f.elements.driver.value,sandbox={driver,environment:JSON.parse(f.elements.environment.value||'{}')};if(driver==='docker')Object.assign(sandbox,{dockerfileId:f.elements.dockerfileId.value,readOnlyRootFS:f.elements.readOnlyRootFS.checked});if(driver==='native')Object.assign(sandbox,{environmentId:f.elements.environmentId.value});Object.assign(value,sandbox)} - const endpoints={rules:'rules',skills:'skills',dockerfiles:'dockerfiles',environments:'environments',sandboxes:'sandboxes'};await api(`/api/${endpoints[state.assetType]}`,{method:'PUT',body:JSON.stringify(value)});const i=items.findIndex(x=>x.id===value.id);if(state.assetType==='skills'&&existing)value={...existing,...value,fileRefs:existing.fileRefs||[],content:existing.content||'',files:existing.files||{}};if(i>=0)items[i]=value;else items.push(value);state.selectedAsset=value.id;state.assetDirty=false; + if(state.assetType==='sandboxes'){const driver=f.elements.driver.value,sandbox={driver,environment:JSON.parse(f.elements.environment.value||'{}')};if(driver==='docker')Object.assign(sandbox,{dockerfile:{content:f.elements.dockerfileContent.value,files:JSON.parse(f.elements.dockerfileFiles.value||'{}')},readOnlyRootFS:f.elements.readOnlyRootFS.checked});if(driver==='native')Object.assign(sandbox,{install:{script:f.elements.installScript.value,pathEntries:lines(f.elements.installPathEntries.value),variables:JSON.parse(f.elements.installVariables.value||'{}')}});if(driver==='local')Object.assign(sandbox,{runnerId:f.elements.runnerId.value,baseDir:f.elements.baseDir.value.trim(),repositoryPaths:localSandboxRepositoryPaths(f,existing||value)});Object.assign(value,sandbox)} + const endpoints={rules:'rules',skills:'skills',sandboxes:'sandboxes'};await api(`/api/${endpoints[state.assetType]}`,{method:'PUT',body:JSON.stringify(value)});const i=items.findIndex(x=>x.id===value.id);if(state.assetType==='skills'&&existing)value={...existing,...value,fileRefs:existing.fileRefs||[],content:existing.content||'',files:existing.files||{}};if(i>=0)items[i]=value;else items.push(value);state.selectedAsset=value.id;state.assetDirty=false; if(identity.created){history.replaceState(history.state,'',assetViewHash(state.assetType,value.id));state.assetDetailKey='';renderAssets()} else{renderAssetDetailHead(value);refreshAssetAside(value)} renderWorkflowMeta();renderProperties();toast(identity.created?'资产已创建':'资产修改已保存'); diff --git a/web/app/assistant-settings.js b/web/app/assistant-settings.js index e54b2deda..5e799d7b5 100644 --- a/web/app/assistant-settings.js +++ b/web/app/assistant-settings.js @@ -1,14 +1,15 @@ -// AI 助手设置:生成中消息的发送方式、主动派发与每轮自定义规则。只对当前用户生效。 +// AI 助手设置:生成中消息的发送方式、主动派发、对话工作区倾向与每轮自定义规则。只对当前用户生效。 const ASSISTANT_RULES_MAX=4000; +const ASSISTANT_WORKSPACE_DRIVERS=[['','由 Agent 选择'],['docker','Docker 沙箱'],['native','native 沙箱'],['local','local 沙箱']]; const assistantPrefsUI={saved:null,loading:false,saving:false,error:''}; function assistantPrefsSignedIn(){return !!state.currentUser&&!state.currentUser.isGuest} function assistantPrefsForm(){return document.querySelector('#assistantPrefsForm')} -function assistantPrefsDraft(form){return {proactiveRoles:form.proactiveRoles.checked,proactiveSops:form.proactiveSops.checked,steerOnSend:form.messageDuringGeneration.value==='steer',instructions:form.instructions.value.trim()}} +function assistantPrefsDraft(form){return {proactiveRoles:form.proactiveRoles.checked,proactiveSops:form.proactiveSops.checked,steerOnSend:form.messageDuringGeneration.value==='steer',workspaceDriver:form.workspaceDriver.value,instructions:form.instructions.value.trim()}} function assistantPrefsDirty(form){ const saved=assistantPrefsUI.saved;if(!saved||!form)return false; const draft=assistantPrefsDraft(form); - return draft.proactiveRoles!==!!saved.proactiveRoles||draft.proactiveSops!==!!saved.proactiveSops||draft.steerOnSend!==!!saved.steerOnSend||draft.instructions!==(saved.instructions||''); + return draft.proactiveRoles!==!!saved.proactiveRoles||draft.proactiveSops!==!!saved.proactiveSops||draft.steerOnSend!==!!saved.steerOnSend||draft.workspaceDriver!==(saved.workspaceDriver||'')||draft.instructions!==(saved.instructions||''); } function assistantPrefsSwitchRow(name,title,help,on){ return ``; @@ -25,6 +26,10 @@ function assistantPrefsFormHTML(p){ ${assistantPrefsSwitchRow('proactiveRoles','主动派角色','整件事是某个角色的本职(如独立评审、整套测试),或改了高风险代码需要复核时,直接交给这个角色。',p.proactiveRoles)} ${assistantPrefsSwitchRow('proactiveSops','主动走 SOP','遇到要落到仓库的新需求时,先交给项目里用途对得上的 SOP,而不是自己直接改代码。',p.proactiveSops)}
+

对话工作区

会话里没有固定运行环境时,AI 助手自己选择在哪类沙箱里打开工作区。

+

自定义规则

每轮对话都会带上这些规则,适合写你的习惯和偏好;不会越过审批模式和平台规则。

diff --git a/web/app/flows.js b/web/app/flows.js index f036534d6..1a4c4ef04 100644 --- a/web/app/flows.js +++ b/web/app/flows.js @@ -878,7 +878,7 @@ function renderAgentAssetsPanel(a){ const host=$('#agentAssetsPanel');if(!host)return; const d=ensureAgentDraft(a); const generic=catalogGeneric(state.workflow); - const col=(title,sub,name,items,selected)=>{const vis=name==='mcpServers'?(generic?(items||[]):visibleMCPAssets(items)):(name==='rules'||name==='skills'?(items||[]).filter(item=>catalogVisible(item.projectId,item.shared)):visibleAssets(items));const picked=vis.filter(item=>name==='mcpServers'&&generic?genericMCPChecked(item.id,selected):(selected||[]).includes(item.id)).length;const empty=name==='mcpServers'?(generic?'通用模板绑定市场别名(如 github),运行时落到当前项目已安装的 MCP':'这个项目或你的个人范围还没有 MCP,先到「MCP 管理」里添加'):name==='rules'?'这个项目还没有可用规则,先到「规则管理」里添加或共享':name==='skills'?'这个项目还没有可用技能,先到「技能管理」里添加或共享':'这个项目还没有此类配置,先到「环境资产」里添加';return `
${title}${sub}${picked?` · 已选 ${picked}`:''}
${vis.map(x=>``).join('')||`
${empty}
`}
`}; + const col=(title,sub,name,items,selected)=>{const vis=name==='mcpServers'?(generic?(items||[]):visibleMCPAssets(items)):(name==='rules'||name==='skills'?(items||[]).filter(item=>catalogVisible(item.projectId,item.shared)):visibleAssets(items));const picked=vis.filter(item=>name==='mcpServers'&&generic?genericMCPChecked(item.id,selected):(selected||[]).includes(item.id)).length;const empty=name==='mcpServers'?(generic?'通用模板绑定市场别名(如 github),运行时落到当前项目已安装的 MCP':'这个项目或你的个人范围还没有 MCP,先到「MCP 管理」里添加'):name==='rules'?'这个项目还没有可用规则,先到「规则管理」里添加或共享':name==='skills'?'这个项目还没有可用技能,先到「技能管理」里添加或共享':'这个项目还没有此类配置,先到「沙箱管理」里添加';return `
${title}${sub}${picked?` · 已选 ${picked}`:''}
${vis.map(x=>``).join('')||`
${empty}
`}
`}; host.innerHTML=`
平台能力独立开关,不占用 MCP 列表
${col('必须遵守','规则','rules',state.data.rules,d.rules)}${col('怎么干活','技能','skills',state.data.skills,d.skills)}${col('外部工具','MCP','mcpServers',generic?genericTemplateMCPOptions(d.mcpServers):state.data.mcpServers,d.mcpServers)}
运行时 Hook在工具调用前后插一段脚本,比如拦危险命令。一般可以先不配。
`; host.querySelectorAll('[data-asset-filter]').forEach(input=>input.oninput=()=>{const q=input.value.trim().toLowerCase();input.closest('.as-asset-col').querySelectorAll('.as-asset-item').forEach(row=>row.hidden=!!q&&!row.textContent.toLowerCase().includes(q))}); host.querySelectorAll('input[type=checkbox]').forEach(el=>el.onchange=()=>{renderAgentSummary();dirty()}); diff --git a/web/app/harness-motion.js b/web/app/harness-motion.js index 73c725df0..bef4689e2 100644 --- a/web/app/harness-motion.js +++ b/web/app/harness-motion.js @@ -1150,7 +1150,7 @@ sops: "workflow", runs: "runs", management: "dashboard", runners: "server", settings: "settings", bots: "robot", assistant: "sparkles", projects: "users", flow: "workflow", agents: "user", mcp: "connector", rules: "doc", skills: "skills", - dockerfiles: "layers", environments: "terminal", sandboxes: "server", + sandboxes: "layers", observability: "token", guide: "key", platform: "gate", }; const controls = { diff --git a/web/assets_detail_test.js b/web/assets_detail_test.js index 59c1d21cf..c1097bbd3 100644 --- a/web/assets_detail_test.js +++ b/web/assets_detail_test.js @@ -49,8 +49,8 @@ function reset(type, data) { assetType: type, selectedAsset: null, assetQuery: '', - ruleScope: 'project', skillScope: 'project', dockerfileScope: 'project', environmentScope: 'project', sandboxScope: 'project', - data: { projects: [{ id: 'p1', name: '本项目' }, { id: 'p2', name: '平台公共' }], agents: [], sandboxes: [], workflows: [], rules: [], skills: [], dockerfiles: [], environments: [], ...data }, + ruleScope: 'project', skillScope: 'project', sandboxScope: 'project', + data: { projects: [{ id: 'p1', name: '本项目' }, { id: 'p2', name: '平台公共' }], agents: [], sandboxes: [], workflows: [], rules: [], skills: [], ...data }, }; } @@ -80,7 +80,7 @@ for (const html of [own, shared, foreign]) { assert.ok(!/data-(share|delete)-asset/.test(html), 'share/delete moved off the card'); assert.ok(!/class="[^"]*\bopen\b/.test(html), 'card classes must not collide with .open menu state'); } -for (const [type, icon] of [['rules', 'gate'], ['skills', 'skills'], ['dockerfiles', 'layers'], ['environments', 'terminal'], ['sandboxes', 'server']]) { +for (const [type, icon] of [['rules', 'gate'], ['skills', 'skills'], ['sandboxes', 'server']]) { assert.strictEqual(ctx.assetIconName(type), icon); } @@ -128,6 +128,8 @@ reset('sandboxes', { sandboxes: [{ id: 'generic-docker', name: '通用 Docker', head = ctx.assetDetailHeadHTML(ctx.state.data.sandboxes[0], {}); assert.ok(head.includes('内置沙箱 generic-docker 不能删除'), 'builtin reason'); assert.ok(ctx.assetOverviewCardHTML(ctx.state.data.sandboxes[0]).includes('
类型
内置
')); +assert.ok(ctx.assetCardHTML({ id: 'd', projectId: 'p1', driver: 'docker', dockerfile: { content: 'FROM x\nRUN y\n' } }).includes('Dockerfile 2 行')); +assert.ok(ctx.assetCardHTML({ id: 'n', projectId: 'p1', driver: 'seatbelt', install: { script: 'echo' } }).includes('安装脚本')); reset('skills', {}); ctx.state.selectedAsset = '__new__'; @@ -188,18 +190,18 @@ async function save(type, existing, values) { { id: 's', ...base }, { id: 's', name: 'N', description: 'D', projectId: 'p1', shared: false }, ['description', 'id', 'name']], - ['dockerfiles', { id: 'd', projectId: 'p1' }, - { id: 'd', ...base, content: 'FROM x', files: '{"a":"b"}' }, - { id: 'd', name: 'N', description: 'D', projectId: 'p1', shared: false, content: 'FROM x', files: { a: 'b' } }, - ['content', 'description', 'files', 'id', 'name']], - ['environments', { id: 'e', projectId: 'p1' }, - { id: 'e', ...base, variables: '{"V":"1"}', pathEntries: 'bin\n sbin ', installScript: 'echo' }, - { id: 'e', name: 'N', description: 'D', projectId: 'p1', shared: false, variables: { V: '1' }, pathEntries: ['bin', 'sbin'], installScript: 'echo' }, - ['description', 'id', 'installScript', 'name', 'pathEntries', 'variables']], - ['sandboxes', { id: 'x', projectId: 'p1', driver: 'docker' }, - { id: 'x', ...base, driver: 'docker', environment: '{}', dockerfileId: 'df', readOnlyRootFS: true, environmentId: 'env' }, - { id: 'x', name: 'N', description: 'D', projectId: 'p1', shared: false, driver: 'docker', environment: {}, dockerfileId: 'df', readOnlyRootFS: true }, - ['description', 'dockerfileId', 'driver', 'environment', 'environmentId', 'id', 'name', 'readOnlyRootFS']], + ['sandboxes', { id: 'x', projectId: 'p1', driver: 'docker', dockerfile: { content: 'FROM old' } }, + { id: 'x', ...base, driver: 'docker', environment: '{}', dockerfileContent: 'FROM x', dockerfileFiles: '{"a":"b"}', readOnlyRootFS: true, installScript: 'echo', installPathEntries: 'bin', installVariables: '{}' }, + { id: 'x', name: 'N', description: 'D', projectId: 'p1', shared: false, driver: 'docker', environment: {}, dockerfile: { content: 'FROM x', files: { a: 'b' } }, readOnlyRootFS: true }, + ['baseDir', 'description', 'dockerfileContent', 'dockerfileFiles', 'driver', 'environment', 'id', 'installPathEntries', 'installScript', 'installVariables', 'name', 'readOnlyRootFS', 'runnerId']], + ['sandboxes', { id: 'n', projectId: 'p1', driver: 'native' }, + { id: 'n', ...base, driver: 'native', environment: '{}', dockerfileContent: 'FROM x', dockerfileFiles: '{}', readOnlyRootFS: true, installScript: 'echo', installPathEntries: 'bin\n sbin ', installVariables: '{"V":"1"}' }, + { id: 'n', name: 'N', description: 'D', projectId: 'p1', shared: false, driver: 'native', environment: {}, install: { script: 'echo', pathEntries: ['bin', 'sbin'], variables: { V: '1' } } }, + ['baseDir', 'description', 'dockerfileContent', 'dockerfileFiles', 'driver', 'environment', 'id', 'installPathEntries', 'installScript', 'installVariables', 'name', 'readOnlyRootFS', 'runnerId']], + ['sandboxes', { id: 'l', projectId: 'p1', driver: 'local', runnerId: 'r1', repositoryPaths: { removed: '/srv/removed' } }, + { id: 'l', ...base, driver: 'local', environment: '{}', runnerId: 'r1', baseDir: ' ~/work ', dockerfileContent: 'FROM x', dockerfileFiles: '{}', readOnlyRootFS: true, installScript: 'echo', installPathEntries: '', installVariables: '{}' }, + { id: 'l', name: 'N', description: 'D', projectId: 'p1', shared: false, driver: 'local', environment: {}, runnerId: 'r1', baseDir: '~/work', repositoryPaths: { removed: '/srv/removed' } }, + ['baseDir', 'description', 'dockerfileContent', 'dockerfileFiles', 'driver', 'environment', 'id', 'installPathEntries', 'installScript', 'installVariables', 'name', 'readOnlyRootFS', 'runnerId']], ]; for (const [type, existing, values, body, fields] of cases) { assert.deepStrictEqual(await save(type, existing, values), body, `${type} save payload`); diff --git a/web/assistant_settings_test.js b/web/assistant_settings_test.js index 1d63be9f6..0da92d0da 100644 --- a/web/assistant_settings_test.js +++ b/web/assistant_settings_test.js @@ -22,12 +22,18 @@ assert.match(html, /id="assistantPrefsSave" disabled/); assert.match(html, /